Skip to content

Commit 4032b7a

Browse files
alexcrichtonalex
andcommitted
std: Synchronize access to global env during exec
This commit, after reverting #55359, applies a different fix for #46775 while also fixing #55775. The basic idea was to go back to pre-#55359 libstd, and then fix #46775 in a way that doesn't expose #55775. The issue described in #46775 boils down to two problems: * First, the global environment is reset during `exec` but, but if the `exec` call fails then the global environment was a dangling pointer into free'd memory as the block of memory was deallocated when `Command` is dropped. This is fixed in this commit by installing a `Drop` stack object which ensures that the `environ` pointer is preserved on a failing `exec`. * Second, the global environment was accessed in an unsynchronized fashion during `exec`. This was fixed by ensuring that the Rust-specific environment lock is acquired for these system-level operations. Thanks to Alex Gaynor for pioneering the solution here! Closes #55775 Co-authored-by: Alex Gaynor <alex.gaynor@gmail.com>
1 parent 5856797 commit 4032b7a

File tree

3 files changed

+96
-16
lines changed

3 files changed

+96
-16
lines changed

src/libstd/sys/unix/os.rs

+12-8
Original file line numberDiff line numberDiff line change
@@ -27,15 +27,12 @@ use path::{self, PathBuf};
2727
use ptr;
2828
use slice;
2929
use str;
30-
use sys_common::mutex::Mutex;
30+
use sys_common::mutex::{Mutex, MutexGuard};
3131
use sys::cvt;
3232
use sys::fd;
3333
use vec;
3434

3535
const TMPBUF_SZ: usize = 128;
36-
// We never call `ENV_LOCK.init()`, so it is UB to attempt to
37-
// acquire this mutex reentrantly!
38-
static ENV_LOCK: Mutex = Mutex::new();
3936

4037

4138
extern {
@@ -408,11 +405,18 @@ pub unsafe fn environ() -> *mut *const *const c_char {
408405
&mut environ
409406
}
410407

408+
pub unsafe fn env_lock() -> MutexGuard<'static> {
409+
// We never call `ENV_LOCK.init()`, so it is UB to attempt to
410+
// acquire this mutex reentrantly!
411+
static ENV_LOCK: Mutex = Mutex::new();
412+
ENV_LOCK.lock()
413+
}
414+
411415
/// Returns a vector of (variable, value) byte-vector pairs for all the
412416
/// environment variables of the current process.
413417
pub fn env() -> Env {
414418
unsafe {
415-
let _guard = ENV_LOCK.lock();
419+
let _guard = env_lock();
416420
let mut environ = *environ();
417421
let mut result = Vec::new();
418422
while environ != ptr::null() && *environ != ptr::null() {
@@ -448,7 +452,7 @@ pub fn getenv(k: &OsStr) -> io::Result<Option<OsString>> {
448452
// always None as well
449453
let k = CString::new(k.as_bytes())?;
450454
unsafe {
451-
let _guard = ENV_LOCK.lock();
455+
let _guard = env_lock();
452456
let s = libc::getenv(k.as_ptr()) as *const libc::c_char;
453457
let ret = if s.is_null() {
454458
None
@@ -464,7 +468,7 @@ pub fn setenv(k: &OsStr, v: &OsStr) -> io::Result<()> {
464468
let v = CString::new(v.as_bytes())?;
465469

466470
unsafe {
467-
let _guard = ENV_LOCK.lock();
471+
let _guard = env_lock();
468472
cvt(libc::setenv(k.as_ptr(), v.as_ptr(), 1)).map(|_| ())
469473
}
470474
}
@@ -473,7 +477,7 @@ pub fn unsetenv(n: &OsStr) -> io::Result<()> {
473477
let nbuf = CString::new(n.as_bytes())?;
474478

475479
unsafe {
476-
let _guard = ENV_LOCK.lock();
480+
let _guard = env_lock();
477481
cvt(libc::unsetenv(nbuf.as_ptr())).map(|_| ())
478482
}
479483
}

src/libstd/sys/unix/process/process_unix.rs

+48-8
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,9 @@
1111
use io::{self, Error, ErrorKind};
1212
use libc::{self, c_int, gid_t, pid_t, uid_t};
1313
use ptr;
14-
1514
use sys::cvt;
1615
use sys::process::process_common::*;
16+
use sys;
1717

1818
////////////////////////////////////////////////////////////////////////////////
1919
// Command
@@ -22,8 +22,6 @@ use sys::process::process_common::*;
2222
impl Command {
2323
pub fn spawn(&mut self, default: Stdio, needs_stdin: bool)
2424
-> io::Result<(Process, StdioPipes)> {
25-
use sys;
26-
2725
const CLOEXEC_MSG_FOOTER: &'static [u8] = b"NOEX";
2826

2927
let envp = self.capture_env();
@@ -41,8 +39,21 @@ impl Command {
4139

4240
let (input, output) = sys::pipe::anon_pipe()?;
4341

42+
// Whatever happens after the fork is almost for sure going to touch or
43+
// look at the environment in one way or another (PATH in `execvp` or
44+
// accessing the `environ` pointer ourselves). Make sure no other thread
45+
// is accessing the environment when we do the fork itself.
46+
//
47+
// Note that as soon as we're done with the fork there's no need to hold
48+
// a lock any more because the parent won't do anything and the child is
49+
// in its own process.
50+
let result = unsafe {
51+
let _env_lock = sys::os::env_lock();
52+
cvt(libc::fork())?
53+
};
54+
4455
let pid = unsafe {
45-
match cvt(libc::fork())? {
56+
match result {
4657
0 => {
4758
drop(input);
4859
let err = self.do_exec(theirs, envp.as_ref());
@@ -114,7 +125,16 @@ impl Command {
114125
}
115126

116127
match self.setup_io(default, true) {
117-
Ok((_, theirs)) => unsafe { self.do_exec(theirs, envp.as_ref()) },
128+
Ok((_, theirs)) => {
129+
unsafe {
130+
// Similar to when forking, we want to ensure that access to
131+
// the environment is synchronized, so make sure to grab the
132+
// environment lock before we try to exec.
133+
let _lock = sys::os::env_lock();
134+
135+
self.do_exec(theirs, envp.as_ref())
136+
}
137+
}
118138
Err(e) => e,
119139
}
120140
}
@@ -193,9 +213,6 @@ impl Command {
193213
if let Some(ref cwd) = *self.get_cwd() {
194214
t!(cvt(libc::chdir(cwd.as_ptr())));
195215
}
196-
if let Some(envp) = maybe_envp {
197-
*sys::os::environ() = envp.as_ptr();
198-
}
199216

200217
// emscripten has no signal support.
201218
#[cfg(not(any(target_os = "emscripten")))]
@@ -231,6 +248,27 @@ impl Command {
231248
t!(callback());
232249
}
233250

251+
// Although we're performing an exec here we may also return with an
252+
// error from this function (without actually exec'ing) in which case we
253+
// want to be sure to restore the global environment back to what it
254+
// once was, ensuring that our temporary override, when free'd, doesn't
255+
// corrupt our process's environment.
256+
let mut _reset = None;
257+
if let Some(envp) = maybe_envp {
258+
struct Reset(*const *const libc::c_char);
259+
260+
impl Drop for Reset {
261+
fn drop(&mut self) {
262+
unsafe {
263+
*sys::os::environ() = self.0;
264+
}
265+
}
266+
}
267+
268+
_reset = Some(Reset(*sys::os::environ()));
269+
*sys::os::environ() = envp.as_ptr();
270+
}
271+
234272
libc::execvp(self.get_argv()[0], self.get_argv().as_ptr());
235273
io::Error::last_os_error()
236274
}
@@ -330,6 +368,8 @@ impl Command {
330368
libc::POSIX_SPAWN_SETSIGMASK;
331369
cvt(libc::posix_spawnattr_setflags(&mut attrs.0, flags as _))?;
332370

371+
// Make sure we synchronize access to the global `environ` resource
372+
let _env_lock = sys::os::env_lock();
333373
let envp = envp.map(|c| c.as_ptr())
334374
.unwrap_or_else(|| *sys::os::environ() as *const _);
335375
let ret = libc::posix_spawnp(

src/test/run-pass/command-exec.rs

+36
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,23 @@ fn main() {
4848
println!("passed");
4949
}
5050

51+
"exec-test5" => {
52+
env::set_var("VARIABLE", "ABC");
53+
Command::new("definitely-not-a-real-binary").env("VARIABLE", "XYZ").exec();
54+
assert_eq!(env::var("VARIABLE").unwrap(), "ABC");
55+
println!("passed");
56+
}
57+
58+
"exec-test6" => {
59+
let err = Command::new("echo").arg("passed").env_clear().exec();
60+
panic!("failed to spawn: {}", err);
61+
}
62+
63+
"exec-test7" => {
64+
let err = Command::new("echo").arg("passed").env_remove("PATH").exec();
65+
panic!("failed to spawn: {}", err);
66+
}
67+
5168
_ => panic!("unknown argument: {}", arg),
5269
}
5370
return
@@ -72,4 +89,23 @@ fn main() {
7289
assert!(output.status.success());
7390
assert!(output.stderr.is_empty());
7491
assert_eq!(output.stdout, b"passed\n");
92+
93+
let output = Command::new(&me).arg("exec-test5").output().unwrap();
94+
assert!(output.status.success());
95+
assert!(output.stderr.is_empty());
96+
assert_eq!(output.stdout, b"passed\n");
97+
98+
if cfg!(target_os = "linux") {
99+
let output = Command::new(&me).arg("exec-test6").output().unwrap();
100+
println!("{:?}", output);
101+
assert!(output.status.success());
102+
assert!(output.stderr.is_empty());
103+
assert_eq!(output.stdout, b"passed\n");
104+
105+
let output = Command::new(&me).arg("exec-test7").output().unwrap();
106+
println!("{:?}", output);
107+
assert!(output.status.success());
108+
assert!(output.stderr.is_empty());
109+
assert_eq!(output.stdout, b"passed\n");
110+
}
75111
}

0 commit comments

Comments
 (0)