@@ -11,14 +11,12 @@ use crate::path::{self, PathBuf, Path};
11
11
use crate :: ptr;
12
12
use crate :: slice;
13
13
use crate :: str;
14
- use crate :: sys_common:: mutex:: Mutex ;
14
+ use crate :: sys_common:: mutex:: { Mutex , MutexGuard } ;
15
15
use crate :: sys:: cvt;
16
16
/*use sys::fd; this one is probably important */
17
17
use crate :: vec;
18
18
19
19
const TMPBUF_SZ : usize = 128 ;
20
- static ENV_LOCK : Mutex = Mutex :: new ( ) ;
21
-
22
20
23
21
// This is a terrible fix
24
22
use crate :: sys:: os_str:: Buf ;
@@ -200,11 +198,18 @@ pub unsafe fn environ() -> *mut *const *const c_char {
200
198
& mut environ
201
199
}
202
200
201
+ pub unsafe fn env_lock ( ) -> MutexGuard < ' static > {
202
+ // We never call `ENV_LOCK.init()`, so it is UB to attempt to
203
+ // acquire this mutex reentrantly!
204
+ static ENV_LOCK : Mutex = Mutex :: new ( ) ;
205
+ ENV_LOCK . lock ( )
206
+ }
207
+
203
208
/// Returns a vector of (variable, value) byte-vector pairs for all the
204
209
/// environment variables of the current process.
205
210
pub fn env ( ) -> Env {
206
211
unsafe {
207
- let _guard = ENV_LOCK . lock ( ) ;
212
+ let _guard = env_lock ( ) ;
208
213
let mut environ = * environ ( ) ;
209
214
if environ == ptr:: null ( ) {
210
215
panic ! ( "os::env() failure getting env string from OS: {}" ,
@@ -244,7 +249,7 @@ pub fn getenv(k: &OsStr) -> io::Result<Option<OsString>> {
244
249
// always None as well
245
250
let k = CString :: new ( k. as_bytes ( ) ) ?;
246
251
unsafe {
247
- let _guard = ENV_LOCK . lock ( ) ;
252
+ let _guard = env_lock ( ) ;
248
253
let s = libc:: getenv ( k. as_ptr ( ) ) as * const libc:: c_char ;
249
254
let ret = if s. is_null ( ) {
250
255
None
@@ -260,7 +265,7 @@ pub fn setenv(k: &OsStr, v: &OsStr) -> io::Result<()> {
260
265
let v = CString :: new ( v. as_bytes ( ) ) ?;
261
266
262
267
unsafe {
263
- let _guard = ENV_LOCK . lock ( ) ;
268
+ let _guard = env_lock ( ) ;
264
269
cvt ( libc:: setenv ( k. as_ptr ( ) , v. as_ptr ( ) , 1 ) ) . map ( |_| ( ) )
265
270
}
266
271
}
@@ -269,7 +274,7 @@ pub fn unsetenv(n: &OsStr) -> io::Result<()> {
269
274
let nbuf = CString :: new ( n. as_bytes ( ) ) ?;
270
275
271
276
unsafe {
272
- let _guard = ENV_LOCK . lock ( ) ;
277
+ let _guard = env_lock ( ) ;
273
278
cvt ( libc:: unsetenv ( nbuf. as_ptr ( ) ) ) . map ( |_| ( ) )
274
279
}
275
280
}
0 commit comments