Skip to main content

std/sys/process/unix/
unix.rs

1#[cfg(target_os = "vxworks")]
2use libc::RTP_ID as pid_t;
3#[cfg(not(target_os = "vxworks"))]
4use libc::{c_int, pid_t};
5#[cfg(not(any(
6    target_os = "vxworks",
7    target_os = "l4re",
8    target_os = "tvos",
9    target_os = "watchos",
10)))]
11use libc::{gid_t, uid_t};
12
13use super::common::*;
14use crate::io::{self, Error, ErrorKind};
15use crate::num::NonZero;
16use crate::process::StdioPipes;
17use crate::sys::cvt;
18#[cfg(target_os = "linux")]
19use crate::sys::process::PidFd;
20use crate::{fmt, mem, sys};
21
22cfg_select! {
23    any(target_os = "nto", target_os = "qnx") => {
24        use libc::{c_char, posix_spawn_file_actions_t, posix_spawnattr_t};
25
26        use crate::sync::LazyLock;
27        use crate::thread;
28        use crate::time::Duration;
29        // Get smallest amount of time we can sleep.
30        // Return a common value if it cannot be determined.
31        fn get_clock_resolution() -> Duration {
32            static MIN_DELAY: LazyLock<Duration, fn() -> Duration> = LazyLock::new(|| {
33                let mut mindelay = libc::timespec { tv_sec: 0, tv_nsec: 0 };
34                if unsafe { libc::clock_getres(libc::CLOCK_MONOTONIC, &mut mindelay) } == 0 {
35                    Duration::from_nanos(mindelay.tv_nsec as u64)
36                } else {
37                    Duration::from_millis(1)
38                }
39            });
40            *MIN_DELAY
41        }
42        // Arbitrary minimum sleep duration for retrying fork/spawn
43        const MIN_FORKSPAWN_SLEEP: Duration = Duration::from_nanos(1);
44        // Maximum duration of sleeping before giving up and returning an error
45        const MAX_FORKSPAWN_SLEEP: Duration = Duration::from_millis(1000);
46    }
47    _ => {}
48}
49
50////////////////////////////////////////////////////////////////////////////////
51// Command
52////////////////////////////////////////////////////////////////////////////////
53
54impl Command {
55    pub fn spawn(
56        &mut self,
57        default: Stdio,
58        needs_stdin: bool,
59    ) -> io::Result<(Process, StdioPipes)> {
60        const CLOEXEC_MSG_FOOTER: [u8; 4] = *b"NOEX";
61
62        let envp = self.capture_env();
63
64        if self.saw_nul() {
65            return Err(io::const_error!(
66                ErrorKind::InvalidInput,
67                "nul byte found in provided data",
68            ));
69        }
70
71        let (ours, theirs) = self.setup_io(default, needs_stdin)?;
72
73        if let Some(ret) = self.posix_spawn(&theirs, envp.as_ref())? {
74            return Ok((ret, ours));
75        }
76
77        #[cfg(target_os = "linux")]
78        let (input, output) = sys::net::Socket::new_pair(libc::AF_UNIX, libc::SOCK_SEQPACKET)?;
79
80        #[cfg(not(target_os = "linux"))]
81        let (input, output) = sys::pipe::pipe()?;
82
83        // Whatever happens after the fork is almost for sure going to touch or
84        // look at the environment in one way or another (PATH in `execvp` or
85        // accessing the `environ` pointer ourselves). Make sure no other thread
86        // is accessing the environment when we do the fork itself.
87        //
88        // Note that as soon as we're done with the fork there's no need to hold
89        // a lock any more because the parent won't do anything and the child is
90        // in its own process. Thus the parent drops the lock guard immediately.
91        // The child calls `mem::forget` to leak the lock, which is crucial because
92        // releasing a lock is not async-signal-safe.
93        let env_lock = sys::env::env_read_lock();
94        let pid = unsafe { self.do_fork()? };
95
96        if pid == 0 {
97            crate::panic::always_abort();
98            mem::forget(env_lock); // avoid non-async-signal-safe unlocking
99            drop(input);
100            #[cfg(target_os = "linux")]
101            if self.get_create_pidfd() {
102                self.send_pidfd(&output);
103            }
104            let Err(err) = unsafe { self.do_exec(theirs, envp.as_ref()) };
105            let errno = err.raw_os_error().unwrap_or(libc::EINVAL) as u32;
106            let errno = errno.to_be_bytes();
107            let bytes = [
108                errno[0],
109                errno[1],
110                errno[2],
111                errno[3],
112                CLOEXEC_MSG_FOOTER[0],
113                CLOEXEC_MSG_FOOTER[1],
114                CLOEXEC_MSG_FOOTER[2],
115                CLOEXEC_MSG_FOOTER[3],
116            ];
117            // pipe I/O up to PIPE_BUF bytes should be atomic, and then
118            // we want to be sure we *don't* run at_exit destructors as
119            // we're being torn down regardless
120            rtassert!(output.write(&bytes).is_ok());
121            unsafe { libc::_exit(1) }
122        }
123
124        drop(env_lock);
125        drop(output);
126
127        #[cfg(target_os = "linux")]
128        let pidfd = if self.get_create_pidfd() { self.recv_pidfd(&input) } else { -1 };
129
130        #[cfg(not(target_os = "linux"))]
131        let pidfd = -1;
132
133        // Safety: We obtained the pidfd (on Linux) using SOCK_SEQPACKET, so it's valid.
134        let mut p = unsafe { Process::new(pid, pidfd) };
135        let mut bytes = [0; 8];
136
137        // loop to handle EINTR
138        loop {
139            match input.read(&mut bytes) {
140                Ok(0) => return Ok((p, ours)),
141                Ok(8) => {
142                    let (errno, footer) = bytes.split_at(4);
143                    assert_eq!(
144                        CLOEXEC_MSG_FOOTER, footer,
145                        "Validation on the CLOEXEC pipe failed: {:?}",
146                        bytes
147                    );
148                    let errno = i32::from_be_bytes(errno.try_into().unwrap());
149                    assert!(p.wait().is_ok(), "wait() should either return Ok or panic");
150                    return Err(Error::from_raw_os_error(errno));
151                }
152                Err(ref e) if e.is_interrupted() => {}
153                Err(e) => {
154                    assert!(p.wait().is_ok(), "wait() should either return Ok or panic");
155                    panic!("the CLOEXEC pipe failed: {e:?}")
156                }
157                Ok(..) => {
158                    // pipe I/O up to PIPE_BUF bytes should be atomic
159                    // similarly SOCK_SEQPACKET messages should arrive whole
160                    assert!(p.wait().is_ok(), "wait() should either return Ok or panic");
161                    panic!("short read on the CLOEXEC pipe")
162                }
163            }
164        }
165    }
166
167    // WatchOS and TVOS headers mark the `fork`/`exec*` functions with
168    // `__WATCHOS_PROHIBITED __TVOS_PROHIBITED`, and indicate that the
169    // `posix_spawn*` functions should be used instead. It isn't entirely clear
170    // what `PROHIBITED` means here (e.g. if calls to these functions are
171    // allowed to exist in dead code), but it sounds bad, so we go out of our
172    // way to avoid that all-together.
173    #[cfg(any(target_os = "tvos", target_os = "watchos"))]
174    const ERR_APPLE_TV_WATCH_NO_FORK_EXEC: Error = io::const_error!(
175        ErrorKind::Unsupported,
176        "`fork`+`exec`-based process spawning is not supported on this target",
177    );
178
179    #[cfg(any(target_os = "tvos", target_os = "watchos"))]
180    unsafe fn do_fork(&mut self) -> Result<pid_t, io::Error> {
181        return Err(Self::ERR_APPLE_TV_WATCH_NO_FORK_EXEC);
182    }
183
184    // Attempts to fork the process. If successful, returns Ok((0, -1))
185    // in the child, and Ok((child_pid, -1)) in the parent.
186    #[cfg(not(any(
187        target_os = "watchos",
188        target_os = "tvos",
189        target_os = "nto",
190        target_os = "qnx"
191    )))]
192    unsafe fn do_fork(&mut self) -> Result<pid_t, io::Error> {
193        cvt(libc::fork())
194    }
195
196    // On QNX SDP, fork can fail with EBADF in case "another thread might have opened
197    // or closed a file descriptor while the fork() was occurring".
198    // Documentation says "... or try calling fork() again". This is what we do here.
199    // See also https://www.qnx.com/developers/docs/7.1/com.qnx.doc.neutrino.lib_ref/topic/f/fork.html
200    #[cfg(any(target_os = "nto", target_os = "qnx"))]
201    unsafe fn do_fork(&mut self) -> Result<pid_t, io::Error> {
202        use crate::sys::io::errno;
203
204        let mut delay = MIN_FORKSPAWN_SLEEP;
205
206        loop {
207            let r = libc::fork();
208            if r == -1 as libc::pid_t && errno() as libc::c_int == libc::EBADF {
209                if delay < get_clock_resolution() {
210                    // We cannot sleep this short (it would be longer).
211                    // Yield instead.
212                    thread::yield_now();
213                } else if delay < MAX_FORKSPAWN_SLEEP {
214                    thread::sleep(delay);
215                } else {
216                    return Err(io::const_error!(
217                        ErrorKind::WouldBlock,
218                        "forking returned EBADF too often",
219                    ));
220                }
221                delay *= 2;
222                continue;
223            } else {
224                return cvt(r);
225            }
226        }
227    }
228
229    pub fn exec(&mut self, default: Stdio) -> io::Error {
230        let envp = self.capture_env();
231
232        if self.saw_nul() {
233            return io::const_error!(ErrorKind::InvalidInput, "nul byte found in provided data");
234        }
235
236        match self.setup_io(default, true) {
237            Ok((_, theirs)) => {
238                unsafe {
239                    // Similar to when forking, we want to ensure that access to
240                    // the environment is synchronized, so make sure to grab the
241                    // environment lock before we try to exec.
242                    let _lock = sys::env::env_read_lock();
243
244                    let Err(e) = self.do_exec(theirs, envp.as_ref());
245                    e
246                }
247            }
248            Err(e) => e,
249        }
250    }
251
252    // And at this point we've reached a special time in the life of the
253    // child. The child must now be considered hamstrung and unable to
254    // do anything other than syscalls really. Consider the following
255    // scenario:
256    //
257    //      1. Thread A of process 1 grabs the malloc() mutex
258    //      2. Thread B of process 1 forks(), creating thread C
259    //      3. Thread C of process 2 then attempts to malloc()
260    //      4. The memory of process 2 is the same as the memory of
261    //         process 1, so the mutex is locked.
262    //
263    // This situation looks a lot like deadlock, right? It turns out
264    // that this is what pthread_atfork() takes care of, which is
265    // presumably implemented across platforms. The first thing that
266    // threads to *before* forking is to do things like grab the malloc
267    // mutex, and then after the fork they unlock it.
268    //
269    // Despite this information, libnative's spawn has been witnessed to
270    // deadlock on both macOS and FreeBSD. I'm not entirely sure why, but
271    // all collected backtraces point at malloc/free traffic in the
272    // child spawned process.
273    //
274    // For this reason, the block of code below should contain 0
275    // invocations of either malloc of free (or their related friends).
276    //
277    // As an example of not having malloc/free traffic, we don't close
278    // this file descriptor by dropping the FileDesc (which contains an
279    // allocation). Instead we just close it manually. This will never
280    // have the drop glue anyway because this code never returns (the
281    // child will either exec() or invoke libc::exit)
282    #[cfg(not(any(target_os = "tvos", target_os = "watchos")))]
283    unsafe fn do_exec(
284        &mut self,
285        stdio: ChildPipes,
286        maybe_envp: Option<&CStringArray>,
287    ) -> Result<!, io::Error> {
288        use crate::sys::{self, cvt_r};
289
290        if let Some(fd) = stdio.stdin.fd() {
291            cvt_r(|| libc::dup2(fd, libc::STDIN_FILENO))?;
292        }
293        if let Some(fd) = stdio.stdout.fd() {
294            cvt_r(|| libc::dup2(fd, libc::STDOUT_FILENO))?;
295        }
296        if let Some(fd) = stdio.stderr.fd() {
297            cvt_r(|| libc::dup2(fd, libc::STDERR_FILENO))?;
298        }
299
300        #[cfg(not(target_os = "l4re"))]
301        {
302            if let Some(_g) = self.get_groups() {
303                //FIXME: Redox kernel does not support setgroups yet
304                #[cfg(not(target_os = "redox"))]
305                cvt(libc::setgroups(_g.len().try_into().unwrap(), _g.as_ptr()))?;
306            }
307            if let Some(u) = self.get_gid() {
308                cvt(libc::setgid(u as gid_t))?;
309            }
310            if let Some(u) = self.get_uid() {
311                // When dropping privileges from root, the `setgroups` call
312                // will remove any extraneous groups. We only drop groups
313                // if we have CAP_SETGID and we weren't given an explicit
314                // set of groups. If we don't call this, then even though our
315                // uid has dropped, we may still have groups that enable us to
316                // do super-user things.
317                //FIXME: Redox kernel does not support setgroups yet
318                #[cfg(not(target_os = "redox"))]
319                if self.get_groups().is_none() {
320                    let res = cvt(libc::setgroups(0, crate::ptr::null()));
321                    if let Err(e) = res {
322                        // Here we ignore the case of not having CAP_SETGID.
323                        // An alternative would be to require CAP_SETGID (in
324                        // addition to CAP_SETUID) for setting the UID.
325                        if e.raw_os_error() != Some(libc::EPERM) {
326                            return Err(e);
327                        }
328                    }
329                }
330                cvt(libc::setuid(u as uid_t))?;
331            }
332        }
333        if let Some(chroot) = self.get_chroot() {
334            #[cfg(not(target_os = "fuchsia"))]
335            cvt(libc::chroot(chroot.as_ptr()))?;
336            #[cfg(target_os = "fuchsia")]
337            return Err(io::const_error!(
338                io::ErrorKind::Unsupported,
339                "chroot not supported by fuchsia"
340            ));
341        }
342        if let Some(cwd) = self.get_cwd() {
343            cvt(libc::chdir(cwd.as_ptr()))?;
344        }
345
346        if let Some(pgroup) = self.get_pgroup() {
347            cvt(libc::setpgid(0, pgroup))?;
348        }
349
350        if self.get_setsid() {
351            cvt(libc::setsid())?;
352        }
353
354        // emscripten has no signal support.
355        #[cfg(not(target_os = "emscripten"))]
356        {
357            // Inherit the signal mask from the parent rather than resetting it (i.e. do not call
358            // pthread_sigmask).
359
360            // If -Zon-broken-pipe is used, don't reset SIGPIPE to SIG_DFL.
361            // If -Zon-broken-pipe is not used, reset SIGPIPE to SIG_DFL for backward compatibility.
362            //
363            // -Zon-broken-pipe is an opportunity to change the default here.
364            if !crate::sys::pal::on_broken_pipe_used() {
365                #[cfg(target_os = "android")] // see issue #88585
366                {
367                    let mut action: libc::sigaction = mem::zeroed();
368                    action.sa_sigaction = libc::SIG_DFL;
369                    cvt(libc::sigaction(libc::SIGPIPE, &action, crate::ptr::null_mut()))?;
370                }
371                #[cfg(not(target_os = "android"))]
372                {
373                    let ret = sys::signal(libc::SIGPIPE, libc::SIG_DFL);
374                    if ret == libc::SIG_ERR {
375                        return Err(io::Error::last_os_error());
376                    }
377                }
378                #[cfg(target_os = "hurd")]
379                {
380                    let ret = sys::signal(libc::SIGLOST, libc::SIG_DFL);
381                    if ret == libc::SIG_ERR {
382                        return Err(io::Error::last_os_error());
383                    }
384                }
385            }
386        }
387
388        for callback in self.get_closures().iter_mut() {
389            callback()?;
390        }
391
392        // Although we're performing an exec here we may also return with an
393        // error from this function (without actually exec'ing) in which case we
394        // want to be sure to restore the global environment back to what it
395        // once was, ensuring that our temporary override, when free'd, doesn't
396        // corrupt our process's environment.
397        let mut _reset = None;
398        if let Some(envp) = maybe_envp {
399            struct Reset(*const *const libc::c_char);
400
401            impl Drop for Reset {
402                fn drop(&mut self) {
403                    unsafe {
404                        *sys::env::environ() = self.0;
405                    }
406                }
407            }
408
409            _reset = Some(Reset(*sys::env::environ()));
410            *sys::env::environ() = envp.as_ptr();
411        }
412
413        libc::execvp(self.get_program_cstr().as_ptr(), self.get_argv().as_ptr());
414        Err(io::Error::last_os_error())
415    }
416
417    #[cfg(any(target_os = "tvos", target_os = "watchos"))]
418    unsafe fn do_exec(
419        &mut self,
420        _stdio: ChildPipes,
421        _maybe_envp: Option<&CStringArray>,
422    ) -> Result<!, io::Error> {
423        return Err(Self::ERR_APPLE_TV_WATCH_NO_FORK_EXEC);
424    }
425
426    #[cfg(not(any(
427        target_os = "freebsd",
428        target_os = "illumos",
429        all(target_os = "linux", target_env = "gnu"),
430        all(target_os = "linux", target_env = "musl"),
431        target_os = "nto",
432        target_os = "qnx",
433        target_vendor = "apple",
434        target_os = "cygwin",
435    )))]
436    fn posix_spawn(
437        &mut self,
438        _: &ChildPipes,
439        _: Option<&CStringArray>,
440    ) -> io::Result<Option<Process>> {
441        Ok(None)
442    }
443
444    // Only support platforms for which posix_spawn() can return ENOENT
445    // directly.
446    #[cfg(any(
447        target_os = "freebsd",
448        target_os = "illumos",
449        all(target_os = "linux", target_env = "gnu"),
450        all(target_os = "linux", target_env = "musl"),
451        target_os = "nto",
452        target_os = "qnx",
453        target_vendor = "apple",
454        target_os = "cygwin",
455    ))]
456    fn posix_spawn(
457        &mut self,
458        stdio: &ChildPipes,
459        envp: Option<&CStringArray>,
460    ) -> io::Result<Option<Process>> {
461        #[cfg(target_os = "linux")]
462        use core::sync::atomic::{Atomic, AtomicU8, Ordering};
463
464        use crate::mem::MaybeUninit;
465        use crate::sys::{self, cvt_nz, on_broken_pipe_used};
466
467        if self.get_gid().is_some()
468            || self.get_uid().is_some()
469            || (self.env_saw_path() && !self.program_is_path())
470            || !self.get_closures().is_empty()
471            || self.get_groups().is_some()
472            || self.get_chroot().is_some()
473        {
474            return Ok(None);
475        }
476
477        cfg_select! {
478            target_os = "linux" => {
479                use crate::sys::weak::weak;
480
481                weak!(
482                    fn pidfd_spawnp(
483                        pidfd: *mut libc::c_int,
484                        path: *const libc::c_char,
485                        file_actions: *const libc::posix_spawn_file_actions_t,
486                        attrp: *const libc::posix_spawnattr_t,
487                        argv: *const *mut libc::c_char,
488                        envp: *const *mut libc::c_char,
489                    ) -> libc::c_int;
490                );
491
492                static PIDFD_SUPPORTED: Atomic<u8> = AtomicU8::new(0);
493                const UNKNOWN: u8 = 0;
494                const SPAWN: u8 = 1;
495                // Obtaining a pidfd via the fork+exec path might work
496                const FORK_EXEC: u8 = 2;
497                // Neither pidfd_spawn nor fork/exec will get us a pidfd.
498                // Instead we'll just posix_spawn if the other preconditions are met.
499                const NO: u8 = 3;
500
501                if self.get_create_pidfd() {
502                    let mut support = PIDFD_SUPPORTED.load(Ordering::Relaxed);
503                    if support == FORK_EXEC {
504                        return Ok(None);
505                    }
506                    if support == UNKNOWN {
507                        support = NO;
508
509                        match PidFd::current_process() {
510                            Ok(pidfd) => {
511                                // if pidfd_open works then we at least know the fork path is available.
512                                support = FORK_EXEC;
513                                // but for the fast path we need both spawnp and the
514                                // pidfd -> pid conversion to work.
515                                if pidfd_spawnp.get().is_some()
516                                    && let Ok(pid) = pidfd.pid()
517                                {
518                                    assert_eq!(pid, crate::process::id(), "sanity check");
519                                    support = SPAWN;
520                                }
521                            }
522                            Err(e)
523                                if matches!(
524                                    e.raw_os_error(),
525                                    Some(libc::EMFILE | libc::ENFILE | libc::ENOMEM)
526                                ) =>
527                            {
528                                // We're temporarily(?) out of file descriptors or memory. In this case pidfd_spawnp would also fail
529                                // Don't update the support flag so we can probe again later.
530                                return Err(e);
531                            }
532                            _ => {
533                                // pidfd_open not available? likely an old kernel without pidfd support.
534                            }
535                        }
536                        PIDFD_SUPPORTED.store(support, Ordering::Relaxed);
537                        if support == FORK_EXEC {
538                            return Ok(None);
539                        }
540                    }
541                    core::debug_assert_matches!(support, SPAWN | NO);
542                }
543            }
544            _ => {
545                if self.get_create_pidfd() {
546                    unreachable!("only implemented on linux")
547                }
548            }
549        }
550
551        // Only glibc 2.24+ posix_spawn() supports returning ENOENT directly.
552        #[cfg(all(target_os = "linux", target_env = "gnu"))]
553        {
554            if let Some(version) = sys::pal::conf::glibc_version() {
555                if version < (2, 24) {
556                    return Ok(None);
557                }
558            } else {
559                return Ok(None);
560            }
561        }
562
563        // On QNX SDP, posix_spawnp can fail with EBADF in case "another thread might have opened
564        // or closed a file descriptor while the posix_spawn() was occurring".
565        // Documentation says "... or try calling posix_spawn() again". This is what we do here.
566        // See also https://www.qnx.com/developers/docs/7.1/com.qnx.doc.neutrino.lib_ref/topic/p/posix_spawn.html
567        #[cfg(any(target_os = "nto", target_os = "qnx"))]
568        unsafe fn retrying_libc_posix_spawnp(
569            pid: *mut pid_t,
570            file: *const c_char,
571            file_actions: *const posix_spawn_file_actions_t,
572            attrp: *const posix_spawnattr_t,
573            argv: *const *mut c_char,
574            envp: *const *mut c_char,
575        ) -> io::Result<i32> {
576            let mut delay = MIN_FORKSPAWN_SLEEP;
577            loop {
578                match libc::posix_spawnp(pid, file, file_actions, attrp, argv, envp) {
579                    libc::EBADF => {
580                        if delay < get_clock_resolution() {
581                            // We cannot sleep this short (it would be longer).
582                            // Yield instead.
583                            thread::yield_now();
584                        } else if delay < MAX_FORKSPAWN_SLEEP {
585                            thread::sleep(delay);
586                        } else {
587                            return Err(io::const_error!(
588                                ErrorKind::WouldBlock,
589                                "posix_spawnp returned EBADF too often",
590                            ));
591                        }
592                        delay *= 2;
593                        continue;
594                    }
595                    r => {
596                        return Ok(r);
597                    }
598                }
599            }
600        }
601
602        type PosixSpawnAddChdirFn = unsafe extern "C" fn(
603            *mut libc::posix_spawn_file_actions_t,
604            *const libc::c_char,
605        ) -> libc::c_int;
606
607        /// Get the function pointer for adding a chdir action to a
608        /// `posix_spawn_file_actions_t`, if available, assuming a dynamic libc.
609        ///
610        /// Some platforms can set a new working directory for a spawned process in the
611        /// `posix_spawn` path. This function looks up the function pointer for adding
612        /// such an action to a `posix_spawn_file_actions_t` struct.
613        #[cfg(not(any(all(target_os = "linux", target_env = "musl"), target_os = "cygwin")))]
614        fn get_posix_spawn_addchdir() -> Option<PosixSpawnAddChdirFn> {
615            use crate::sys::weak::weak;
616
617            // POSIX.1-2024 standardizes this function:
618            // https://pubs.opengroup.org/onlinepubs/9799919799/functions/posix_spawn_file_actions_addchdir.html.
619            // The _np version is more widely available, though, so try that first.
620
621            weak!(
622                fn posix_spawn_file_actions_addchdir_np(
623                    file_actions: *mut libc::posix_spawn_file_actions_t,
624                    path: *const libc::c_char,
625                ) -> libc::c_int;
626            );
627
628            weak!(
629                fn posix_spawn_file_actions_addchdir(
630                    file_actions: *mut libc::posix_spawn_file_actions_t,
631                    path: *const libc::c_char,
632                ) -> libc::c_int;
633            );
634
635            posix_spawn_file_actions_addchdir_np
636                .get()
637                .or_else(|| posix_spawn_file_actions_addchdir.get())
638        }
639
640        /// Get the function pointer for adding a chdir action to a
641        /// `posix_spawn_file_actions_t`, if available, on platforms where the function
642        /// is known to exist.
643        ///
644        /// Weak symbol lookup doesn't work with statically linked libcs, so in cases
645        /// where static linking is possible we need to either check for the presence
646        /// of the symbol at compile time or know about it upfront.
647        ///
648        /// Cygwin doesn't support weak symbol, so just link it.
649        #[cfg(any(all(target_os = "linux", target_env = "musl"), target_os = "cygwin"))]
650        fn get_posix_spawn_addchdir() -> Option<PosixSpawnAddChdirFn> {
651            // Our minimum required musl supports this function, so we can just use it.
652            Some(libc::posix_spawn_file_actions_addchdir_np)
653        }
654
655        let addchdir = match self.get_cwd() {
656            Some(cwd) => {
657                if cfg!(target_vendor = "apple") {
658                    // There is a bug in macOS where a relative executable
659                    // path like "../myprogram" will cause `posix_spawn` to
660                    // successfully launch the program, but erroneously return
661                    // ENOENT when used with posix_spawn_file_actions_addchdir_np
662                    // which was introduced in macOS 10.15.
663                    if self.get_program_kind() == ProgramKind::Relative {
664                        return Ok(None);
665                    }
666                }
667                // Check for the availability of the posix_spawn addchdir
668                // function now. If it isn't available, bail and use the
669                // fork/exec path.
670                match get_posix_spawn_addchdir() {
671                    Some(f) => Some((f, cwd)),
672                    None => return Ok(None),
673                }
674            }
675            None => None,
676        };
677
678        let pgroup = self.get_pgroup();
679
680        struct PosixSpawnFileActions<'a>(&'a mut MaybeUninit<libc::posix_spawn_file_actions_t>);
681
682        impl Drop for PosixSpawnFileActions<'_> {
683            fn drop(&mut self) {
684                unsafe {
685                    libc::posix_spawn_file_actions_destroy(self.0.as_mut_ptr());
686                }
687            }
688        }
689
690        struct PosixSpawnattr<'a>(&'a mut MaybeUninit<libc::posix_spawnattr_t>);
691
692        impl Drop for PosixSpawnattr<'_> {
693            fn drop(&mut self) {
694                unsafe {
695                    libc::posix_spawnattr_destroy(self.0.as_mut_ptr());
696                }
697            }
698        }
699
700        unsafe {
701            let mut attrs = MaybeUninit::uninit();
702            cvt_nz(libc::posix_spawnattr_init(attrs.as_mut_ptr()))?;
703            let attrs = PosixSpawnattr(&mut attrs);
704
705            let mut flags = 0;
706
707            let mut file_actions = MaybeUninit::uninit();
708            cvt_nz(libc::posix_spawn_file_actions_init(file_actions.as_mut_ptr()))?;
709            let file_actions = PosixSpawnFileActions(&mut file_actions);
710
711            if let Some(fd) = stdio.stdin.fd() {
712                cvt_nz(libc::posix_spawn_file_actions_adddup2(
713                    file_actions.0.as_mut_ptr(),
714                    fd,
715                    libc::STDIN_FILENO,
716                ))?;
717            }
718            if let Some(fd) = stdio.stdout.fd() {
719                cvt_nz(libc::posix_spawn_file_actions_adddup2(
720                    file_actions.0.as_mut_ptr(),
721                    fd,
722                    libc::STDOUT_FILENO,
723                ))?;
724            }
725            if let Some(fd) = stdio.stderr.fd() {
726                cvt_nz(libc::posix_spawn_file_actions_adddup2(
727                    file_actions.0.as_mut_ptr(),
728                    fd,
729                    libc::STDERR_FILENO,
730                ))?;
731            }
732            if let Some((f, cwd)) = addchdir {
733                cvt_nz(f(file_actions.0.as_mut_ptr(), cwd.as_ptr()))?;
734            }
735
736            if let Some(pgroup) = pgroup {
737                flags |= libc::POSIX_SPAWN_SETPGROUP;
738                cvt_nz(libc::posix_spawnattr_setpgroup(attrs.0.as_mut_ptr(), pgroup))?;
739            }
740
741            // Inherit the signal mask from this process rather than resetting it (i.e. do not call
742            // posix_spawnattr_setsigmask).
743
744            // If -Zon-broken-pipe is used, don't reset SIGPIPE to SIG_DFL.
745            // If -Zon-broken-pipe is not used, reset SIGPIPE to SIG_DFL for backward compatibility.
746            //
747            // -Zon-broken-pipe is an opportunity to change the default here.
748            if !on_broken_pipe_used() {
749                let mut default_set = MaybeUninit::<libc::sigset_t>::uninit();
750                cvt(sigemptyset(default_set.as_mut_ptr()))?;
751                cvt(sigaddset(default_set.as_mut_ptr(), libc::SIGPIPE))?;
752                #[cfg(target_os = "hurd")]
753                {
754                    cvt(sigaddset(default_set.as_mut_ptr(), libc::SIGLOST))?;
755                }
756                cvt_nz(libc::posix_spawnattr_setsigdefault(
757                    attrs.0.as_mut_ptr(),
758                    default_set.as_ptr(),
759                ))?;
760                flags |= libc::POSIX_SPAWN_SETSIGDEF;
761            }
762
763            if self.get_setsid() {
764                cfg_select! {
765                    all(target_os = "linux", target_env = "gnu") => {
766                        flags |= libc::POSIX_SPAWN_SETSID as i32;
767                    }
768                    _ => {
769                        return Ok(None);
770                    }
771                }
772            }
773
774            cvt_nz(libc::posix_spawnattr_setflags(attrs.0.as_mut_ptr(), flags as _))?;
775
776            // Make sure we synchronize access to the global `environ` resource
777            let _env_lock = sys::env::env_read_lock();
778            let envp = envp.map(|c| c.as_ptr()).unwrap_or_else(|| *sys::env::environ() as *const _);
779
780            #[cfg(not(any(target_os = "nto", target_os = "qnx")))]
781            let spawn_fn = libc::posix_spawnp;
782            #[cfg(any(target_os = "nto", target_os = "qnx"))]
783            let spawn_fn = retrying_libc_posix_spawnp;
784
785            #[cfg(target_os = "linux")]
786            if self.get_create_pidfd() && PIDFD_SUPPORTED.load(Ordering::Relaxed) == SPAWN {
787                let mut pidfd: libc::c_int = -1;
788                let spawn_res = pidfd_spawnp.get().unwrap()(
789                    &mut pidfd,
790                    self.get_program_cstr().as_ptr(),
791                    file_actions.0.as_ptr(),
792                    attrs.0.as_ptr(),
793                    self.get_argv().as_ptr() as *const _,
794                    envp as *const _,
795                );
796
797                let spawn_res = cvt_nz(spawn_res);
798                if let Err(ref e) = spawn_res
799                    && e.raw_os_error() == Some(libc::ENOSYS)
800                {
801                    PIDFD_SUPPORTED.store(FORK_EXEC, Ordering::Relaxed);
802                    return Ok(None);
803                }
804                spawn_res?;
805
806                use crate::os::fd::{FromRawFd, IntoRawFd};
807
808                let pidfd = PidFd::from_raw_fd(pidfd);
809                let pid = match pidfd.pid() {
810                    Ok(pid) => pid,
811                    Err(e) => {
812                        // The child has been spawned and we are holding its pidfd.
813                        // But we cannot obtain its pid even though pidfd_spawnp and getpid support
814                        // was verified earlier.
815                        // This is quite unlikely, but might happen if the ioctl is not supported,
816                        // glibc tries to use procfs and we're out of file descriptors.
817                        return Err(Error::new(
818                            e.kind(),
819                            "pidfd_spawnp succeeded but the child's PID could not be obtained",
820                        ));
821                    }
822                };
823
824                return Ok(Some(Process::new(pid as i32, pidfd.into_raw_fd())));
825            }
826
827            // Safety: -1 indicates we don't have a pidfd.
828            let mut p = Process::new(0, -1);
829
830            let spawn_res = spawn_fn(
831                &mut p.pid,
832                self.get_program_cstr().as_ptr(),
833                file_actions.0.as_ptr(),
834                attrs.0.as_ptr(),
835                self.get_argv().as_ptr() as *const _,
836                envp as *const _,
837            );
838
839            #[cfg(any(target_os = "nto", target_os = "qnx"))]
840            let spawn_res = spawn_res?;
841
842            cvt_nz(spawn_res)?;
843            Ok(Some(p))
844        }
845    }
846
847    #[cfg(target_os = "linux")]
848    fn send_pidfd(&self, sock: &crate::sys::net::Socket) {
849        use libc::{CMSG_DATA, CMSG_FIRSTHDR, CMSG_LEN, CMSG_SPACE, SCM_RIGHTS, SOL_SOCKET};
850
851        use crate::io::IoSlice;
852        use crate::os::fd::RawFd;
853        use crate::sys::cvt_r;
854
855        unsafe {
856            let child_pid = libc::getpid();
857            // pidfd_open sets CLOEXEC by default
858            let pidfd = libc::syscall(libc::SYS_pidfd_open, child_pid, 0);
859
860            let fds: [c_int; 1] = [pidfd as RawFd];
861
862            const SCM_MSG_LEN: usize = size_of::<[c_int; 1]>();
863
864            #[repr(C)]
865            union Cmsg {
866                buf: [u8; unsafe { CMSG_SPACE(SCM_MSG_LEN as u32) as usize }],
867                _align: libc::cmsghdr,
868            }
869
870            let mut cmsg: Cmsg = mem::zeroed();
871
872            // 0-length message to send through the socket so we can pass along the fd
873            let mut iov = [IoSlice::new(b"")];
874            let mut msg: libc::msghdr = mem::zeroed();
875
876            msg.msg_iov = (&raw mut iov) as *mut _;
877            msg.msg_iovlen = 1;
878
879            // only attach cmsg if we successfully acquired the pidfd
880            if pidfd >= 0 {
881                msg.msg_controllen = size_of_val(&cmsg.buf) as _;
882                msg.msg_control = (&raw mut cmsg.buf) as *mut _;
883
884                let hdr = CMSG_FIRSTHDR((&raw mut msg) as *mut _);
885                (*hdr).cmsg_level = SOL_SOCKET;
886                (*hdr).cmsg_type = SCM_RIGHTS;
887                (*hdr).cmsg_len = CMSG_LEN(SCM_MSG_LEN as _) as _;
888                let data = CMSG_DATA(hdr);
889                crate::ptr::copy_nonoverlapping(
890                    fds.as_ptr().cast::<u8>(),
891                    data as *mut _,
892                    SCM_MSG_LEN,
893                );
894            }
895
896            // we send the 0-length message even if we failed to acquire the pidfd
897            // so we get a consistent SEQPACKET order
898            match cvt_r(|| libc::sendmsg(sock.as_raw(), &msg, libc::MSG_EOR)) {
899                Ok(0) => {}
900                other => rtabort!("failed to communicate with parent process. {:?}", other),
901            }
902        }
903    }
904
905    #[cfg(target_os = "linux")]
906    fn recv_pidfd(&self, sock: &crate::sys::net::Socket) -> pid_t {
907        use libc::{CMSG_DATA, CMSG_FIRSTHDR, CMSG_LEN, CMSG_SPACE, SCM_RIGHTS, SOL_SOCKET};
908
909        use crate::io::IoSliceMut;
910        use crate::sys::cvt_r;
911
912        unsafe {
913            const SCM_MSG_LEN: usize = size_of::<[c_int; 1]>();
914
915            #[repr(C)]
916            union Cmsg {
917                _buf: [u8; unsafe { CMSG_SPACE(SCM_MSG_LEN as u32) as usize }],
918                _align: libc::cmsghdr,
919            }
920            let mut cmsg: Cmsg = mem::zeroed();
921            // 0-length read to get the fd
922            let mut iov = [IoSliceMut::new(&mut [])];
923
924            let mut msg: libc::msghdr = mem::zeroed();
925
926            msg.msg_iov = (&raw mut iov) as *mut _;
927            msg.msg_iovlen = 1;
928            msg.msg_controllen = size_of::<Cmsg>() as _;
929            msg.msg_control = (&raw mut cmsg) as *mut _;
930
931            match cvt_r(|| libc::recvmsg(sock.as_raw(), &mut msg, libc::MSG_CMSG_CLOEXEC)) {
932                Err(_) => return -1,
933                Ok(_) => {}
934            }
935
936            let hdr = CMSG_FIRSTHDR((&raw mut msg) as *mut _);
937            if hdr.is_null()
938                || (*hdr).cmsg_level != SOL_SOCKET
939                || (*hdr).cmsg_type != SCM_RIGHTS
940                || (*hdr).cmsg_len != CMSG_LEN(SCM_MSG_LEN as _) as _
941            {
942                return -1;
943            }
944            let data = CMSG_DATA(hdr);
945
946            let mut fds = [-1 as c_int];
947
948            crate::ptr::copy_nonoverlapping(
949                data as *const _,
950                fds.as_mut_ptr().cast::<u8>(),
951                SCM_MSG_LEN,
952            );
953
954            fds[0]
955        }
956    }
957}
958
959////////////////////////////////////////////////////////////////////////////////
960// Processes
961////////////////////////////////////////////////////////////////////////////////
962
963/// The unique ID of the process (this should never be negative).
964pub struct Process {
965    pid: pid_t,
966    status: Option<ExitStatus>,
967    // On Linux, stores the pidfd created for this child.
968    // This is None if the user did not request pidfd creation,
969    // or if the pidfd could not be created for some reason
970    // (e.g. the `pidfd_open` syscall was not available).
971    #[cfg(target_os = "linux")]
972    pidfd: Option<PidFd>,
973}
974
975impl Process {
976    #[cfg(target_os = "linux")]
977    /// # Safety
978    ///
979    /// `pidfd` must either be -1 (representing no file descriptor) or a valid, exclusively owned file
980    /// descriptor (See [I/O Safety]).
981    ///
982    /// [I/O Safety]: crate::io#io-safety
983    unsafe fn new(pid: pid_t, pidfd: pid_t) -> Self {
984        use crate::os::unix::io::FromRawFd;
985        use crate::sys::FromInner;
986        // Safety: If `pidfd` is nonnegative, we assume it's valid and otherwise unowned.
987        let pidfd = (pidfd >= 0).then(|| PidFd::from_inner(sys::fd::FileDesc::from_raw_fd(pidfd)));
988        Process { pid, status: None, pidfd }
989    }
990
991    #[cfg(not(target_os = "linux"))]
992    unsafe fn new(pid: pid_t, _pidfd: pid_t) -> Self {
993        Process { pid, status: None }
994    }
995
996    pub fn id(&self) -> u32 {
997        self.pid as u32
998    }
999
1000    pub fn kill(&self) -> io::Result<()> {
1001        self.send_signal(libc::SIGKILL)
1002    }
1003
1004    pub(crate) fn send_signal(&self, signal: i32) -> io::Result<()> {
1005        // If we've already waited on this process then the pid can be recycled and
1006        // used for another process, and we probably shouldn't be sending signals to
1007        // random processes, so return Ok because the process has exited already.
1008        if self.status.is_some() {
1009            return Ok(());
1010        }
1011        #[cfg(target_os = "linux")]
1012        if let Some(pid_fd) = self.pidfd.as_ref() {
1013            // pidfd_send_signal predates pidfd_open. so if we were able to get an fd then sending signals will work too
1014            return pid_fd.send_signal(signal);
1015        }
1016        cvt(unsafe { libc::kill(self.pid, signal) }).map(drop)
1017    }
1018
1019    pub(crate) fn send_process_group_signal(&self, signal: i32) -> io::Result<()> {
1020        // See note in `send_signal` regarding recycled PIDs.
1021        if self.status.is_some() {
1022            return Ok(());
1023        }
1024        #[cfg(target_os = "linux")]
1025        if let Some(pid_fd) = self.pidfd.as_ref() {
1026            // The `PIDFD_SIGNAL_PROCESS_GROUP` flag requires kernel >= 6.9
1027            return pid_fd.send_process_group_signal(signal);
1028        }
1029        cvt(unsafe { libc::killpg(self.pid, signal) }).map(drop)
1030    }
1031
1032    pub fn wait(&mut self) -> io::Result<ExitStatus> {
1033        use crate::sys::cvt_r;
1034        if let Some(status) = self.status {
1035            return Ok(status);
1036        }
1037        #[cfg(target_os = "linux")]
1038        if let Some(pid_fd) = self.pidfd.as_ref() {
1039            let status = pid_fd.wait()?;
1040            self.status = Some(status);
1041            return Ok(status);
1042        }
1043        let mut status = 0 as c_int;
1044        cvt_r(|| unsafe { libc::waitpid(self.pid, &mut status, 0) })?;
1045        self.status = Some(ExitStatus::new(status));
1046        Ok(ExitStatus::new(status))
1047    }
1048
1049    pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
1050        if let Some(status) = self.status {
1051            return Ok(Some(status));
1052        }
1053        #[cfg(target_os = "linux")]
1054        if let Some(pid_fd) = self.pidfd.as_ref() {
1055            let status = pid_fd.try_wait()?;
1056            if let Some(status) = status {
1057                self.status = Some(status)
1058            }
1059            return Ok(status);
1060        }
1061        let mut status = 0 as c_int;
1062        let pid = cvt(unsafe { libc::waitpid(self.pid, &mut status, libc::WNOHANG) })?;
1063        if pid == 0 {
1064            Ok(None)
1065        } else {
1066            self.status = Some(ExitStatus::new(status));
1067            Ok(Some(ExitStatus::new(status)))
1068        }
1069    }
1070}
1071
1072/// Unix exit statuses
1073//
1074// This is not actually an "exit status" in Unix terminology.  Rather, it is a "wait status".
1075// See the discussion in comments and doc comments for `std::process::ExitStatus`.
1076#[derive(PartialEq, Eq, Clone, Copy, Default)]
1077pub struct ExitStatus(c_int);
1078
1079impl fmt::Debug for ExitStatus {
1080    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1081        f.debug_tuple("unix_wait_status").field(&self.0).finish()
1082    }
1083}
1084
1085impl ExitStatus {
1086    pub fn new(status: c_int) -> ExitStatus {
1087        ExitStatus(status)
1088    }
1089
1090    #[cfg(target_os = "linux")]
1091    pub fn from_waitid_siginfo(siginfo: libc::siginfo_t) -> ExitStatus {
1092        let status = unsafe { siginfo.si_status() };
1093
1094        match siginfo.si_code {
1095            libc::CLD_EXITED => ExitStatus((status & 0xff) << 8),
1096            libc::CLD_KILLED => ExitStatus(status),
1097            libc::CLD_DUMPED => ExitStatus(status | 0x80),
1098            libc::CLD_CONTINUED => ExitStatus(0xffff),
1099            libc::CLD_STOPPED | libc::CLD_TRAPPED => ExitStatus(((status & 0xff) << 8) | 0x7f),
1100            _ => unreachable!("waitid() should only return the above codes"),
1101        }
1102    }
1103
1104    fn exited(&self) -> bool {
1105        libc::WIFEXITED(self.0)
1106    }
1107
1108    pub fn exit_ok(&self) -> Result<(), ExitStatusError> {
1109        // This assumes that WIFEXITED(status) && WEXITSTATUS==0 corresponds to status==0. This is
1110        // true on all actual versions of Unix, is widely assumed, and is specified in SuS
1111        // https://pubs.opengroup.org/onlinepubs/9799919799/functions/wait.html. If it is not
1112        // true for a platform pretending to be Unix, the tests (our doctests, and also
1113        // unix/tests.rs) will spot it. `ExitStatusError::code` assumes this too.
1114        match NonZero::try_from(self.0) {
1115            /* was nonzero */ Ok(failure) => Err(ExitStatusError(failure)),
1116            /* was zero, couldn't convert */ Err(_) => Ok(()),
1117        }
1118    }
1119
1120    pub fn code(&self) -> Option<i32> {
1121        self.exited().then(|| libc::WEXITSTATUS(self.0))
1122    }
1123
1124    pub fn signal(&self) -> Option<i32> {
1125        libc::WIFSIGNALED(self.0).then(|| libc::WTERMSIG(self.0))
1126    }
1127
1128    pub fn core_dumped(&self) -> bool {
1129        libc::WIFSIGNALED(self.0) && libc::WCOREDUMP(self.0)
1130    }
1131
1132    pub fn stopped_signal(&self) -> Option<i32> {
1133        libc::WIFSTOPPED(self.0).then(|| libc::WSTOPSIG(self.0))
1134    }
1135
1136    pub fn continued(&self) -> bool {
1137        libc::WIFCONTINUED(self.0)
1138    }
1139
1140    pub fn into_raw(&self) -> c_int {
1141        self.0
1142    }
1143}
1144
1145/// Converts a raw `c_int` to a type-safe `ExitStatus` by wrapping it without copying.
1146impl From<c_int> for ExitStatus {
1147    fn from(a: c_int) -> ExitStatus {
1148        ExitStatus(a)
1149    }
1150}
1151
1152/// Converts a signal number to a readable, searchable name.
1153///
1154/// This string should be displayed right after the signal number.
1155/// If a signal is unrecognized, it returns the empty string, so that
1156/// you just get the number like "0". If it is recognized, you'll get
1157/// something like "9 (SIGKILL)".
1158fn signal_string(signal: i32) -> &'static str {
1159    match signal {
1160        libc::SIGHUP => " (SIGHUP)",
1161        libc::SIGINT => " (SIGINT)",
1162        libc::SIGQUIT => " (SIGQUIT)",
1163        libc::SIGILL => " (SIGILL)",
1164        libc::SIGTRAP => " (SIGTRAP)",
1165        libc::SIGABRT => " (SIGABRT)",
1166        #[cfg(not(target_os = "l4re"))]
1167        libc::SIGBUS => " (SIGBUS)",
1168        libc::SIGFPE => " (SIGFPE)",
1169        libc::SIGKILL => " (SIGKILL)",
1170        #[cfg(not(target_os = "l4re"))]
1171        libc::SIGUSR1 => " (SIGUSR1)",
1172        libc::SIGSEGV => " (SIGSEGV)",
1173        #[cfg(not(target_os = "l4re"))]
1174        libc::SIGUSR2 => " (SIGUSR2)",
1175        libc::SIGPIPE => " (SIGPIPE)",
1176        libc::SIGALRM => " (SIGALRM)",
1177        libc::SIGTERM => " (SIGTERM)",
1178        #[cfg(not(target_os = "l4re"))]
1179        libc::SIGCHLD => " (SIGCHLD)",
1180        #[cfg(not(target_os = "l4re"))]
1181        libc::SIGCONT => " (SIGCONT)",
1182        #[cfg(not(target_os = "l4re"))]
1183        libc::SIGSTOP => " (SIGSTOP)",
1184        #[cfg(not(target_os = "l4re"))]
1185        libc::SIGTSTP => " (SIGTSTP)",
1186        #[cfg(not(target_os = "l4re"))]
1187        libc::SIGTTIN => " (SIGTTIN)",
1188        #[cfg(not(target_os = "l4re"))]
1189        libc::SIGTTOU => " (SIGTTOU)",
1190        #[cfg(not(target_os = "l4re"))]
1191        libc::SIGURG => " (SIGURG)",
1192        #[cfg(not(target_os = "l4re"))]
1193        libc::SIGXCPU => " (SIGXCPU)",
1194        #[cfg(not(any(target_os = "l4re", target_os = "rtems")))]
1195        libc::SIGXFSZ => " (SIGXFSZ)",
1196        #[cfg(not(any(target_os = "l4re", target_os = "rtems")))]
1197        libc::SIGVTALRM => " (SIGVTALRM)",
1198        #[cfg(not(target_os = "l4re"))]
1199        libc::SIGPROF => " (SIGPROF)",
1200        #[cfg(not(any(target_os = "l4re", target_os = "rtems")))]
1201        libc::SIGWINCH => " (SIGWINCH)",
1202        #[cfg(not(any(target_os = "haiku", target_os = "l4re")))]
1203        libc::SIGIO => " (SIGIO)",
1204        #[cfg(target_os = "haiku")]
1205        libc::SIGPOLL => " (SIGPOLL)",
1206        #[cfg(not(target_os = "l4re"))]
1207        libc::SIGSYS => " (SIGSYS)",
1208        // For information on Linux signals, run `man 7 signal`
1209        #[cfg(all(
1210            target_os = "linux",
1211            any(
1212                target_arch = "x86_64",
1213                target_arch = "x86",
1214                target_arch = "arm",
1215                target_arch = "aarch64"
1216            )
1217        ))]
1218        libc::SIGSTKFLT => " (SIGSTKFLT)",
1219        #[cfg(any(
1220            target_os = "linux",
1221            target_os = "nto",
1222            target_os = "qnx",
1223            target_os = "cygwin"
1224        ))]
1225        libc::SIGPWR => " (SIGPWR)",
1226        #[cfg(any(
1227            target_os = "freebsd",
1228            target_os = "netbsd",
1229            target_os = "openbsd",
1230            target_os = "dragonfly",
1231            target_os = "nto",
1232            target_os = "qnx",
1233            target_vendor = "apple",
1234            target_os = "cygwin",
1235        ))]
1236        libc::SIGEMT => " (SIGEMT)",
1237        #[cfg(any(
1238            target_os = "freebsd",
1239            target_os = "netbsd",
1240            target_os = "openbsd",
1241            target_os = "dragonfly",
1242            target_vendor = "apple",
1243        ))]
1244        libc::SIGINFO => " (SIGINFO)",
1245        #[cfg(target_os = "hurd")]
1246        libc::SIGLOST => " (SIGLOST)",
1247        #[cfg(target_os = "freebsd")]
1248        libc::SIGTHR => " (SIGTHR)",
1249        #[cfg(target_os = "freebsd")]
1250        libc::SIGLIBRT => " (SIGLIBRT)",
1251        _ => "",
1252    }
1253}
1254
1255impl fmt::Display for ExitStatus {
1256    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1257        if let Some(code) = self.code() {
1258            write!(f, "exit status: {code}")
1259        } else if let Some(signal) = self.signal() {
1260            let signal_string = signal_string(signal);
1261            if self.core_dumped() {
1262                write!(f, "signal: {signal}{signal_string} (core dumped)")
1263            } else {
1264                write!(f, "signal: {signal}{signal_string}")
1265            }
1266        } else if let Some(signal) = self.stopped_signal() {
1267            let signal_string = signal_string(signal);
1268            write!(f, "stopped (not terminated) by signal: {signal}{signal_string}")
1269        } else if self.continued() {
1270            write!(f, "continued (WIFCONTINUED)")
1271        } else {
1272            write!(f, "unrecognised wait status: {} {:#x}", self.0, self.0)
1273        }
1274    }
1275}
1276
1277#[derive(PartialEq, Eq, Clone, Copy)]
1278pub struct ExitStatusError(NonZero<c_int>);
1279
1280impl Into<ExitStatus> for ExitStatusError {
1281    fn into(self) -> ExitStatus {
1282        ExitStatus(self.0.into())
1283    }
1284}
1285
1286impl fmt::Debug for ExitStatusError {
1287    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1288        f.debug_tuple("unix_wait_status").field(&self.0).finish()
1289    }
1290}
1291
1292impl ExitStatusError {
1293    pub fn code(self) -> Option<NonZero<i32>> {
1294        ExitStatus(self.0.into()).code().map(|st| st.try_into().unwrap())
1295    }
1296}
1297
1298#[cfg(target_os = "linux")]
1299mod linux_child_ext {
1300    use crate::io::ErrorKind;
1301    use crate::os::linux::process as os;
1302    use crate::sys::{FromInner, process as imp};
1303    use crate::{io, mem};
1304
1305    #[unstable(feature = "linux_pidfd", issue = "82971")]
1306    impl crate::os::linux::process::ChildExt for crate::process::Child {
1307        fn pidfd(&self) -> io::Result<&os::PidFd> {
1308            self.handle
1309                .pidfd
1310                .as_ref()
1311                // SAFETY: The os type is a transparent wrapper, therefore we can transmute references
1312                .map(|fd| unsafe { mem::transmute::<&imp::PidFd, &os::PidFd>(fd) })
1313                .ok_or_else(|| io::const_error!(ErrorKind::Uncategorized, "no pidfd was created."))
1314        }
1315
1316        fn into_pidfd(mut self) -> Result<os::PidFd, Self> {
1317            self.handle
1318                .pidfd
1319                .take()
1320                .map(|fd| <os::PidFd as FromInner<imp::PidFd>>::from_inner(fd))
1321                .ok_or_else(|| self)
1322        }
1323    }
1324}
1325
1326#[cfg(test)]
1327mod tests;
1328
1329// See [`unsupported_wait_status::compare_with_linux`];
1330#[cfg(all(test, target_os = "linux"))]
1331#[path = "unsupported/wait_status.rs"]
1332mod unsupported_wait_status;