1 use crate::convert::TryInto;
3 use crate::io::{self, Error, ErrorKind};
7 use crate::sys::process::process_common::*;
9 use libc::{c_int, gid_t, pid_t, uid_t};
11 ////////////////////////////////////////////////////////////////////////////////
13 ////////////////////////////////////////////////////////////////////////////////
20 ) -> io::Result<(Process, StdioPipes)> {
21 const CLOEXEC_MSG_FOOTER: [u8; 4] = *b"NOEX";
23 let envp = self.capture_env();
26 return Err(io::Error::new(ErrorKind::InvalidInput, "nul byte found in provided data"));
29 let (ours, theirs) = self.setup_io(default, needs_stdin)?;
31 if let Some(ret) = self.posix_spawn(&theirs, envp.as_ref())? {
32 return Ok((ret, ours));
35 let (input, output) = sys::pipe::anon_pipe()?;
37 // Whatever happens after the fork is almost for sure going to touch or
38 // look at the environment in one way or another (PATH in `execvp` or
39 // accessing the `environ` pointer ourselves). Make sure no other thread
40 // is accessing the environment when we do the fork itself.
42 // Note that as soon as we're done with the fork there's no need to hold
43 // a lock any more because the parent won't do anything and the child is
44 // in its own process.
46 let _env_lock = sys::os::env_lock();
54 let Err(err) = self.do_exec(theirs, envp.as_ref());
55 let errno = err.raw_os_error().unwrap_or(libc::EINVAL) as u32;
56 let errno = errno.to_be_bytes();
62 CLOEXEC_MSG_FOOTER[0],
63 CLOEXEC_MSG_FOOTER[1],
64 CLOEXEC_MSG_FOOTER[2],
65 CLOEXEC_MSG_FOOTER[3],
67 // pipe I/O up to PIPE_BUF bytes should be atomic, and then
68 // we want to be sure we *don't* run at_exit destructors as
69 // we're being torn down regardless
70 assert!(output.write(&bytes).is_ok());
77 let mut p = Process { pid, status: None };
79 let mut bytes = [0; 8];
81 // loop to handle EINTR
83 match input.read(&mut bytes) {
84 Ok(0) => return Ok((p, ours)),
86 let (errno, footer) = bytes.split_at(4);
88 CLOEXEC_MSG_FOOTER, footer,
89 "Validation on the CLOEXEC pipe failed: {:?}",
92 let errno = i32::from_be_bytes(errno.try_into().unwrap());
93 assert!(p.wait().is_ok(), "wait() should either return Ok or panic");
94 return Err(Error::from_raw_os_error(errno));
96 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
98 assert!(p.wait().is_ok(), "wait() should either return Ok or panic");
99 panic!("the CLOEXEC pipe failed: {:?}", e)
102 // pipe I/O up to PIPE_BUF bytes should be atomic
103 assert!(p.wait().is_ok(), "wait() should either return Ok or panic");
104 panic!("short read on the CLOEXEC pipe")
110 pub fn exec(&mut self, default: Stdio) -> io::Error {
111 let envp = self.capture_env();
114 return io::Error::new(ErrorKind::InvalidInput, "nul byte found in provided data");
117 match self.setup_io(default, true) {
120 // Similar to when forking, we want to ensure that access to
121 // the environment is synchronized, so make sure to grab the
122 // environment lock before we try to exec.
123 let _lock = sys::os::env_lock();
125 let Err(e) = self.do_exec(theirs, envp.as_ref());
133 // And at this point we've reached a special time in the life of the
134 // child. The child must now be considered hamstrung and unable to
135 // do anything other than syscalls really. Consider the following
138 // 1. Thread A of process 1 grabs the malloc() mutex
139 // 2. Thread B of process 1 forks(), creating thread C
140 // 3. Thread C of process 2 then attempts to malloc()
141 // 4. The memory of process 2 is the same as the memory of
142 // process 1, so the mutex is locked.
144 // This situation looks a lot like deadlock, right? It turns out
145 // that this is what pthread_atfork() takes care of, which is
146 // presumably implemented across platforms. The first thing that
147 // threads to *before* forking is to do things like grab the malloc
148 // mutex, and then after the fork they unlock it.
150 // Despite this information, libnative's spawn has been witnessed to
151 // deadlock on both macOS and FreeBSD. I'm not entirely sure why, but
152 // all collected backtraces point at malloc/free traffic in the
153 // child spawned process.
155 // For this reason, the block of code below should contain 0
156 // invocations of either malloc of free (or their related friends).
158 // As an example of not having malloc/free traffic, we don't close
159 // this file descriptor by dropping the FileDesc (which contains an
160 // allocation). Instead we just close it manually. This will never
161 // have the drop glue anyway because this code never returns (the
162 // child will either exec() or invoke libc::exit)
166 maybe_envp: Option<&CStringArray>,
167 ) -> Result<!, io::Error> {
168 use crate::sys::{self, cvt_r};
170 if let Some(fd) = stdio.stdin.fd() {
171 cvt_r(|| libc::dup2(fd, libc::STDIN_FILENO))?;
173 if let Some(fd) = stdio.stdout.fd() {
174 cvt_r(|| libc::dup2(fd, libc::STDOUT_FILENO))?;
176 if let Some(fd) = stdio.stderr.fd() {
177 cvt_r(|| libc::dup2(fd, libc::STDERR_FILENO))?;
180 #[cfg(not(target_os = "l4re"))]
182 if let Some(u) = self.get_gid() {
183 cvt(libc::setgid(u as gid_t))?;
185 if let Some(u) = self.get_uid() {
186 // When dropping privileges from root, the `setgroups` call
187 // will remove any extraneous groups. If we don't call this,
188 // then even though our uid has dropped, we may still have
189 // groups that enable us to do super-user things. This will
190 // fail if we aren't root, so don't bother checking the
191 // return value, this is just done as an optimistic
192 // privilege dropping function.
193 //FIXME: Redox kernel does not support setgroups yet
194 #[cfg(not(target_os = "redox"))]
195 let _ = libc::setgroups(0, ptr::null());
196 cvt(libc::setuid(u as uid_t))?;
199 if let Some(ref cwd) = *self.get_cwd() {
200 cvt(libc::chdir(cwd.as_ptr()))?;
203 // emscripten has no signal support.
204 #[cfg(not(target_os = "emscripten"))]
206 use crate::mem::MaybeUninit;
207 // Reset signal handling so the child process starts in a
208 // standardized state. libstd ignores SIGPIPE, and signal-handling
209 // libraries often set a mask. Child processes inherit ignored
210 // signals and the signal mask from their parent, but most
211 // UNIX programs do not reset these things on their own, so we
212 // need to clean things up now to avoid confusing the program
213 // we're about to run.
214 let mut set = MaybeUninit::<libc::sigset_t>::uninit();
215 cvt(sigemptyset(set.as_mut_ptr()))?;
216 cvt(libc::pthread_sigmask(libc::SIG_SETMASK, set.as_ptr(), ptr::null_mut()))?;
217 let ret = sys::signal(libc::SIGPIPE, libc::SIG_DFL);
218 if ret == libc::SIG_ERR {
219 return Err(io::Error::last_os_error());
223 for callback in self.get_closures().iter_mut() {
227 // Although we're performing an exec here we may also return with an
228 // error from this function (without actually exec'ing) in which case we
229 // want to be sure to restore the global environment back to what it
230 // once was, ensuring that our temporary override, when free'd, doesn't
231 // corrupt our process's environment.
232 let mut _reset = None;
233 if let Some(envp) = maybe_envp {
234 struct Reset(*const *const libc::c_char);
236 impl Drop for Reset {
239 *sys::os::environ() = self.0;
244 _reset = Some(Reset(*sys::os::environ()));
245 *sys::os::environ() = envp.as_ptr();
248 libc::execvp(self.get_program().as_ptr(), self.get_argv().as_ptr());
249 Err(io::Error::last_os_error())
254 target_os = "freebsd",
255 all(target_os = "linux", target_env = "gnu")
260 _: Option<&CStringArray>,
261 ) -> io::Result<Option<Process>> {
265 // Only support platforms for which posix_spawn() can return ENOENT
269 target_os = "freebsd",
270 all(target_os = "linux", target_env = "gnu")
275 envp: Option<&CStringArray>,
276 ) -> io::Result<Option<Process>> {
277 use crate::mem::MaybeUninit;
280 if self.get_gid().is_some()
281 || self.get_uid().is_some()
282 || self.env_saw_path()
283 || !self.get_closures().is_empty()
288 // Only glibc 2.24+ posix_spawn() supports returning ENOENT directly.
289 #[cfg(all(target_os = "linux", target_env = "gnu"))]
291 if let Some(version) = sys::os::glibc_version() {
292 if version < (2, 24) {
300 // Solaris and glibc 2.29+ can set a new working directory, and maybe
301 // others will gain this non-POSIX function too. We'll check for this
302 // weak symbol as soon as it's needed, so we can return early otherwise
303 // to do a manual chdir before exec.
305 fn posix_spawn_file_actions_addchdir_np(
306 *mut libc::posix_spawn_file_actions_t,
310 let addchdir = match self.get_cwd() {
311 Some(cwd) => match posix_spawn_file_actions_addchdir_np.get() {
312 Some(f) => Some((f, cwd)),
313 None => return Ok(None),
318 let mut p = Process { pid: 0, status: None };
320 struct PosixSpawnFileActions(MaybeUninit<libc::posix_spawn_file_actions_t>);
322 impl Drop for PosixSpawnFileActions {
325 libc::posix_spawn_file_actions_destroy(self.0.as_mut_ptr());
330 struct PosixSpawnattr(MaybeUninit<libc::posix_spawnattr_t>);
332 impl Drop for PosixSpawnattr {
335 libc::posix_spawnattr_destroy(self.0.as_mut_ptr());
341 let mut file_actions = PosixSpawnFileActions(MaybeUninit::uninit());
342 let mut attrs = PosixSpawnattr(MaybeUninit::uninit());
344 libc::posix_spawnattr_init(attrs.0.as_mut_ptr());
345 libc::posix_spawn_file_actions_init(file_actions.0.as_mut_ptr());
347 if let Some(fd) = stdio.stdin.fd() {
348 cvt(libc::posix_spawn_file_actions_adddup2(
349 file_actions.0.as_mut_ptr(),
354 if let Some(fd) = stdio.stdout.fd() {
355 cvt(libc::posix_spawn_file_actions_adddup2(
356 file_actions.0.as_mut_ptr(),
361 if let Some(fd) = stdio.stderr.fd() {
362 cvt(libc::posix_spawn_file_actions_adddup2(
363 file_actions.0.as_mut_ptr(),
368 if let Some((f, cwd)) = addchdir {
369 cvt(f(file_actions.0.as_mut_ptr(), cwd.as_ptr()))?;
372 let mut set = MaybeUninit::<libc::sigset_t>::uninit();
373 cvt(sigemptyset(set.as_mut_ptr()))?;
374 cvt(libc::posix_spawnattr_setsigmask(attrs.0.as_mut_ptr(), set.as_ptr()))?;
375 cvt(sigaddset(set.as_mut_ptr(), libc::SIGPIPE))?;
376 cvt(libc::posix_spawnattr_setsigdefault(attrs.0.as_mut_ptr(), set.as_ptr()))?;
378 let flags = libc::POSIX_SPAWN_SETSIGDEF | libc::POSIX_SPAWN_SETSIGMASK;
379 cvt(libc::posix_spawnattr_setflags(attrs.0.as_mut_ptr(), flags as _))?;
381 // Make sure we synchronize access to the global `environ` resource
382 let _env_lock = sys::os::env_lock();
383 let envp = envp.map(|c| c.as_ptr()).unwrap_or_else(|| *sys::os::environ() as *const _);
384 let ret = libc::posix_spawnp(
386 self.get_program().as_ptr(),
387 file_actions.0.as_ptr(),
389 self.get_argv().as_ptr() as *const _,
392 if ret == 0 { Ok(Some(p)) } else { Err(io::Error::from_raw_os_error(ret)) }
397 ////////////////////////////////////////////////////////////////////////////////
399 ////////////////////////////////////////////////////////////////////////////////
401 /// The unique ID of the process (this should never be negative).
404 status: Option<ExitStatus>,
408 pub fn id(&self) -> u32 {
412 pub fn kill(&mut self) -> io::Result<()> {
413 // If we've already waited on this process then the pid can be recycled
414 // and used for another process, and we probably shouldn't be killing
415 // random processes, so just return an error.
416 if self.status.is_some() {
418 ErrorKind::InvalidInput,
419 "invalid argument: can't kill an exited process",
422 cvt(unsafe { libc::kill(self.pid, libc::SIGKILL) }).map(drop)
426 pub fn wait(&mut self) -> io::Result<ExitStatus> {
427 use crate::sys::cvt_r;
428 if let Some(status) = self.status {
431 let mut status = 0 as c_int;
432 cvt_r(|| unsafe { libc::waitpid(self.pid, &mut status, 0) })?;
433 self.status = Some(ExitStatus::new(status));
434 Ok(ExitStatus::new(status))
437 pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
438 if let Some(status) = self.status {
439 return Ok(Some(status));
441 let mut status = 0 as c_int;
442 let pid = cvt(unsafe { libc::waitpid(self.pid, &mut status, libc::WNOHANG) })?;
446 self.status = Some(ExitStatus::new(status));
447 Ok(Some(ExitStatus::new(status)))
452 /// Unix exit statuses
453 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
454 pub struct ExitStatus(c_int);
457 pub fn new(status: c_int) -> ExitStatus {
461 fn exited(&self) -> bool {
462 unsafe { libc::WIFEXITED(self.0) }
465 pub fn success(&self) -> bool {
466 self.code() == Some(0)
469 pub fn code(&self) -> Option<i32> {
470 if self.exited() { Some(unsafe { libc::WEXITSTATUS(self.0) }) } else { None }
473 pub fn signal(&self) -> Option<i32> {
474 if !self.exited() { Some(unsafe { libc::WTERMSIG(self.0) }) } else { None }
478 /// Converts a raw `c_int` to a type-safe `ExitStatus` by wrapping it without copying.
479 impl From<c_int> for ExitStatus {
480 fn from(a: c_int) -> ExitStatus {
485 impl fmt::Display for ExitStatus {
486 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
487 if let Some(code) = self.code() {
488 write!(f, "exit code: {}", code)
490 let signal = self.signal().unwrap();
491 write!(f, "signal: {}", signal)