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::pin::{Pin, pin};
466        use crate::sys::helpers::COpaque;
467        use crate::sys::{self, cvt_nz, on_broken_pipe_used};
468
469        if self.get_gid().is_some()
470            || self.get_uid().is_some()
471            || (self.env_saw_path() && !self.program_is_path())
472            || !self.get_closures().is_empty()
473            || self.get_groups().is_some()
474            || self.get_chroot().is_some()
475        {
476            return Ok(None);
477        }
478
479        cfg_select! {
480            target_os = "linux" => {
481                use crate::sys::weak::weak;
482
483                weak!(
484                    fn pidfd_spawnp(
485                        pidfd: *mut libc::c_int,
486                        path: *const libc::c_char,
487                        file_actions: *const libc::posix_spawn_file_actions_t,
488                        attrp: *const libc::posix_spawnattr_t,
489                        argv: *const *mut libc::c_char,
490                        envp: *const *mut libc::c_char,
491                    ) -> libc::c_int;
492                );
493
494                static PIDFD_SUPPORTED: Atomic<u8> = AtomicU8::new(0);
495                const UNKNOWN: u8 = 0;
496                const SPAWN: u8 = 1;
497                // Obtaining a pidfd via the fork+exec path might work
498                const FORK_EXEC: u8 = 2;
499                // Neither pidfd_spawn nor fork/exec will get us a pidfd.
500                // Instead we'll just posix_spawn if the other preconditions are met.
501                const NO: u8 = 3;
502
503                if self.get_create_pidfd() {
504                    let mut support = PIDFD_SUPPORTED.load(Ordering::Relaxed);
505                    if support == FORK_EXEC {
506                        return Ok(None);
507                    }
508                    if support == UNKNOWN {
509                        support = NO;
510
511                        match PidFd::current_process() {
512                            Ok(pidfd) => {
513                                // if pidfd_open works then we at least know the fork path is available.
514                                support = FORK_EXEC;
515                                // but for the fast path we need both spawnp and the
516                                // pidfd -> pid conversion to work.
517                                if pidfd_spawnp.get().is_some()
518                                    && let Ok(pid) = pidfd.pid()
519                                {
520                                    assert_eq!(pid, crate::process::id(), "sanity check");
521                                    support = SPAWN;
522                                }
523                            }
524                            Err(e)
525                                if matches!(
526                                    e.raw_os_error(),
527                                    Some(libc::EMFILE | libc::ENFILE | libc::ENOMEM)
528                                ) =>
529                            {
530                                // We're temporarily(?) out of file descriptors or memory. In this case pidfd_spawnp would also fail
531                                // Don't update the support flag so we can probe again later.
532                                return Err(e);
533                            }
534                            _ => {
535                                // pidfd_open not available? likely an old kernel without pidfd support.
536                            }
537                        }
538                        PIDFD_SUPPORTED.store(support, Ordering::Relaxed);
539                        if support == FORK_EXEC {
540                            return Ok(None);
541                        }
542                    }
543                    core::debug_assert_matches!(support, SPAWN | NO);
544                }
545            }
546            _ => {
547                if self.get_create_pidfd() {
548                    unreachable!("only implemented on linux")
549                }
550            }
551        }
552
553        // Only glibc 2.24+ posix_spawn() supports returning ENOENT directly.
554        #[cfg(all(target_os = "linux", target_env = "gnu"))]
555        {
556            if let Some(version) = sys::pal::conf::glibc_version() {
557                if version < (2, 24) {
558                    return Ok(None);
559                }
560            } else {
561                return Ok(None);
562            }
563        }
564
565        // On QNX SDP, posix_spawnp can fail with EBADF in case "another thread might have opened
566        // or closed a file descriptor while the posix_spawn() was occurring".
567        // Documentation says "... or try calling posix_spawn() again". This is what we do here.
568        // See also https://www.qnx.com/developers/docs/7.1/com.qnx.doc.neutrino.lib_ref/topic/p/posix_spawn.html
569        #[cfg(any(target_os = "nto", target_os = "qnx"))]
570        unsafe fn retrying_libc_posix_spawnp(
571            pid: *mut pid_t,
572            file: *const c_char,
573            file_actions: *const posix_spawn_file_actions_t,
574            attrp: *const posix_spawnattr_t,
575            argv: *const *mut c_char,
576            envp: *const *mut c_char,
577        ) -> io::Result<i32> {
578            let mut delay = MIN_FORKSPAWN_SLEEP;
579            loop {
580                match libc::posix_spawnp(pid, file, file_actions, attrp, argv, envp) {
581                    libc::EBADF => {
582                        if delay < get_clock_resolution() {
583                            // We cannot sleep this short (it would be longer).
584                            // Yield instead.
585                            thread::yield_now();
586                        } else if delay < MAX_FORKSPAWN_SLEEP {
587                            thread::sleep(delay);
588                        } else {
589                            return Err(io::const_error!(
590                                ErrorKind::WouldBlock,
591                                "posix_spawnp returned EBADF too often",
592                            ));
593                        }
594                        delay *= 2;
595                        continue;
596                    }
597                    r => {
598                        return Ok(r);
599                    }
600                }
601            }
602        }
603
604        type PosixSpawnAddChdirFn = unsafe extern "C" fn(
605            *mut libc::posix_spawn_file_actions_t,
606            *const libc::c_char,
607        ) -> libc::c_int;
608
609        /// Get the function pointer for adding a chdir action to a
610        /// `posix_spawn_file_actions_t`, if available, assuming a dynamic libc.
611        ///
612        /// Some platforms can set a new working directory for a spawned process in the
613        /// `posix_spawn` path. This function looks up the function pointer for adding
614        /// such an action to a `posix_spawn_file_actions_t` struct.
615        #[cfg(not(any(all(target_os = "linux", target_env = "musl"), target_os = "cygwin")))]
616        fn get_posix_spawn_addchdir() -> Option<PosixSpawnAddChdirFn> {
617            use crate::sys::weak::weak;
618
619            // POSIX.1-2024 standardizes this function:
620            // https://pubs.opengroup.org/onlinepubs/9799919799/functions/posix_spawn_file_actions_addchdir.html.
621            // The _np version is more widely available, though, so try that first.
622
623            weak!(
624                fn posix_spawn_file_actions_addchdir_np(
625                    file_actions: *mut libc::posix_spawn_file_actions_t,
626                    path: *const libc::c_char,
627                ) -> libc::c_int;
628            );
629
630            weak!(
631                fn posix_spawn_file_actions_addchdir(
632                    file_actions: *mut libc::posix_spawn_file_actions_t,
633                    path: *const libc::c_char,
634                ) -> libc::c_int;
635            );
636
637            posix_spawn_file_actions_addchdir_np
638                .get()
639                .or_else(|| posix_spawn_file_actions_addchdir.get())
640        }
641
642        /// Get the function pointer for adding a chdir action to a
643        /// `posix_spawn_file_actions_t`, if available, on platforms where the function
644        /// is known to exist.
645        ///
646        /// Weak symbol lookup doesn't work with statically linked libcs, so in cases
647        /// where static linking is possible we need to either check for the presence
648        /// of the symbol at compile time or know about it upfront.
649        ///
650        /// Cygwin doesn't support weak symbol, so just link it.
651        #[cfg(any(all(target_os = "linux", target_env = "musl"), target_os = "cygwin"))]
652        fn get_posix_spawn_addchdir() -> Option<PosixSpawnAddChdirFn> {
653            // Our minimum required musl supports this function, so we can just use it.
654            Some(libc::posix_spawn_file_actions_addchdir_np)
655        }
656
657        let addchdir = match self.get_cwd() {
658            Some(cwd) => {
659                if cfg!(target_vendor = "apple") {
660                    // There is a bug in macOS where a relative executable
661                    // path like "../myprogram" will cause `posix_spawn` to
662                    // successfully launch the program, but erroneously return
663                    // ENOENT when used with posix_spawn_file_actions_addchdir_np
664                    // which was introduced in macOS 10.15.
665                    if self.get_program_kind() == ProgramKind::Relative {
666                        return Ok(None);
667                    }
668                }
669                // Check for the availability of the posix_spawn addchdir
670                // function now. If it isn't available, bail and use the
671                // fork/exec path.
672                match get_posix_spawn_addchdir() {
673                    Some(f) => Some((f, cwd)),
674                    None => return Ok(None),
675                }
676            }
677            None => None,
678        };
679
680        let pgroup = self.get_pgroup();
681
682        struct PosixSpawnFileActions<'a>(Pin<&'a COpaque<libc::posix_spawn_file_actions_t>>);
683
684        impl Drop for PosixSpawnFileActions<'_> {
685            fn drop(&mut self) {
686                unsafe {
687                    libc::posix_spawn_file_actions_destroy(self.0.get());
688                }
689            }
690        }
691
692        struct PosixSpawnattr<'a>(Pin<&'a COpaque<libc::posix_spawnattr_t>>);
693
694        impl Drop for PosixSpawnattr<'_> {
695            fn drop(&mut self) {
696                unsafe {
697                    libc::posix_spawnattr_destroy(self.0.get());
698                }
699            }
700        }
701
702        unsafe {
703            let attrs = pin!(COpaque::uninit());
704            // FIXME(pin-ergonomics): remove the next line.
705            let attrs = attrs.into_ref();
706            cvt_nz(libc::posix_spawnattr_init(attrs.get()))?;
707            let attrs = PosixSpawnattr(attrs);
708
709            let mut flags = 0;
710
711            let file_actions = pin!(COpaque::uninit());
712            let file_actions = file_actions.into_ref();
713            cvt_nz(libc::posix_spawn_file_actions_init(file_actions.get()))?;
714            let file_actions = PosixSpawnFileActions(file_actions);
715
716            if let Some(fd) = stdio.stdin.fd() {
717                cvt_nz(libc::posix_spawn_file_actions_adddup2(
718                    file_actions.0.get(),
719                    fd,
720                    libc::STDIN_FILENO,
721                ))?;
722            }
723            if let Some(fd) = stdio.stdout.fd() {
724                cvt_nz(libc::posix_spawn_file_actions_adddup2(
725                    file_actions.0.get(),
726                    fd,
727                    libc::STDOUT_FILENO,
728                ))?;
729            }
730            if let Some(fd) = stdio.stderr.fd() {
731                cvt_nz(libc::posix_spawn_file_actions_adddup2(
732                    file_actions.0.get(),
733                    fd,
734                    libc::STDERR_FILENO,
735                ))?;
736            }
737            if let Some((f, cwd)) = addchdir {
738                cvt_nz(f(file_actions.0.get(), cwd.as_ptr()))?;
739            }
740
741            if let Some(pgroup) = pgroup {
742                flags |= libc::POSIX_SPAWN_SETPGROUP;
743                cvt_nz(libc::posix_spawnattr_setpgroup(attrs.0.get(), pgroup))?;
744            }
745
746            // Inherit the signal mask from this process rather than resetting it (i.e. do not call
747            // posix_spawnattr_setsigmask).
748
749            // If -Zon-broken-pipe is used, don't reset SIGPIPE to SIG_DFL.
750            // If -Zon-broken-pipe is not used, reset SIGPIPE to SIG_DFL for backward compatibility.
751            //
752            // -Zon-broken-pipe is an opportunity to change the default here.
753            if !on_broken_pipe_used() {
754                let mut default_set = MaybeUninit::<libc::sigset_t>::uninit();
755                cvt(sigemptyset(default_set.as_mut_ptr()))?;
756                cvt(sigaddset(default_set.as_mut_ptr(), libc::SIGPIPE))?;
757                #[cfg(target_os = "hurd")]
758                {
759                    cvt(sigaddset(default_set.as_mut_ptr(), libc::SIGLOST))?;
760                }
761                cvt_nz(libc::posix_spawnattr_setsigdefault(attrs.0.get(), default_set.as_ptr()))?;
762                flags |= libc::POSIX_SPAWN_SETSIGDEF;
763            }
764
765            if self.get_setsid() {
766                cfg_select! {
767                    all(target_os = "linux", target_env = "gnu") => {
768                        flags |= libc::POSIX_SPAWN_SETSID as i32;
769                    }
770                    _ => {
771                        return Ok(None);
772                    }
773                }
774            }
775
776            cvt_nz(libc::posix_spawnattr_setflags(attrs.0.get(), flags as _))?;
777
778            // Make sure we synchronize access to the global `environ` resource
779            let _env_lock = sys::env::env_read_lock();
780            let envp = envp.map(|c| c.as_ptr()).unwrap_or_else(|| *sys::env::environ() as *const _);
781
782            #[cfg(not(any(target_os = "nto", target_os = "qnx")))]
783            let spawn_fn = libc::posix_spawnp;
784            #[cfg(any(target_os = "nto", target_os = "qnx"))]
785            let spawn_fn = retrying_libc_posix_spawnp;
786
787            #[cfg(target_os = "linux")]
788            if self.get_create_pidfd() && PIDFD_SUPPORTED.load(Ordering::Relaxed) == SPAWN {
789                let mut pidfd: libc::c_int = -1;
790                let spawn_res = pidfd_spawnp.get().unwrap()(
791                    &mut pidfd,
792                    self.get_program_cstr().as_ptr(),
793                    file_actions.0.get(),
794                    attrs.0.get(),
795                    self.get_argv().as_ptr() as *const _,
796                    envp as *const _,
797                );
798
799                let spawn_res = cvt_nz(spawn_res);
800                if let Err(ref e) = spawn_res
801                    && e.raw_os_error() == Some(libc::ENOSYS)
802                {
803                    PIDFD_SUPPORTED.store(FORK_EXEC, Ordering::Relaxed);
804                    return Ok(None);
805                }
806                spawn_res?;
807
808                use crate::os::fd::{FromRawFd, IntoRawFd};
809
810                let pidfd = PidFd::from_raw_fd(pidfd);
811                let pid = match pidfd.pid() {
812                    Ok(pid) => pid,
813                    Err(e) => {
814                        // The child has been spawned and we are holding its pidfd.
815                        // But we cannot obtain its pid even though pidfd_spawnp and getpid support
816                        // was verified earlier.
817                        // This is quite unlikely, but might happen if the ioctl is not supported,
818                        // glibc tries to use procfs and we're out of file descriptors.
819                        return Err(Error::new(
820                            e.kind(),
821                            "pidfd_spawnp succeeded but the child's PID could not be obtained",
822                        ));
823                    }
824                };
825
826                return Ok(Some(Process::new(pid as i32, pidfd.into_raw_fd())));
827            }
828
829            // Safety: -1 indicates we don't have a pidfd.
830            let mut p = Process::new(0, -1);
831
832            let spawn_res = spawn_fn(
833                &mut p.pid,
834                self.get_program_cstr().as_ptr(),
835                file_actions.0.get(),
836                attrs.0.get(),
837                self.get_argv().as_ptr() as *const _,
838                envp as *const _,
839            );
840
841            #[cfg(any(target_os = "nto", target_os = "qnx"))]
842            let spawn_res = spawn_res?;
843
844            cvt_nz(spawn_res)?;
845            Ok(Some(p))
846        }
847    }
848
849    #[cfg(target_os = "linux")]
850    fn send_pidfd(&self, sock: &crate::sys::net::Socket) {
851        use libc::{CMSG_DATA, CMSG_FIRSTHDR, CMSG_LEN, CMSG_SPACE, SCM_RIGHTS, SOL_SOCKET};
852
853        use crate::io::IoSlice;
854        use crate::os::fd::RawFd;
855        use crate::sys::cvt_r;
856
857        unsafe {
858            let child_pid = libc::getpid();
859            // pidfd_open sets CLOEXEC by default
860            let pidfd = libc::syscall(libc::SYS_pidfd_open, child_pid, 0);
861
862            let fds: [c_int; 1] = [pidfd as RawFd];
863
864            const SCM_MSG_LEN: usize = size_of::<[c_int; 1]>();
865
866            #[repr(C)]
867            union Cmsg {
868                buf: [u8; unsafe { CMSG_SPACE(SCM_MSG_LEN as u32) as usize }],
869                _align: libc::cmsghdr,
870            }
871
872            let mut cmsg: Cmsg = mem::zeroed();
873
874            // 0-length message to send through the socket so we can pass along the fd
875            let mut iov = [IoSlice::new(b"")];
876            let mut msg: libc::msghdr = mem::zeroed();
877
878            msg.msg_iov = (&raw mut iov) as *mut _;
879            msg.msg_iovlen = 1;
880
881            // only attach cmsg if we successfully acquired the pidfd
882            if pidfd >= 0 {
883                msg.msg_controllen = size_of_val(&cmsg.buf) as _;
884                msg.msg_control = (&raw mut cmsg.buf) as *mut _;
885
886                let hdr = CMSG_FIRSTHDR((&raw mut msg) as *mut _);
887                (*hdr).cmsg_level = SOL_SOCKET;
888                (*hdr).cmsg_type = SCM_RIGHTS;
889                (*hdr).cmsg_len = CMSG_LEN(SCM_MSG_LEN as _) as _;
890                let data = CMSG_DATA(hdr);
891                crate::ptr::copy_nonoverlapping(
892                    fds.as_ptr().cast::<u8>(),
893                    data as *mut _,
894                    SCM_MSG_LEN,
895                );
896            }
897
898            // we send the 0-length message even if we failed to acquire the pidfd
899            // so we get a consistent SEQPACKET order
900            match cvt_r(|| libc::sendmsg(sock.as_raw(), &msg, libc::MSG_EOR)) {
901                Ok(0) => {}
902                other => rtabort!("failed to communicate with parent process. {:?}", other),
903            }
904        }
905    }
906
907    #[cfg(target_os = "linux")]
908    fn recv_pidfd(&self, sock: &crate::sys::net::Socket) -> pid_t {
909        use libc::{CMSG_DATA, CMSG_FIRSTHDR, CMSG_LEN, CMSG_SPACE, SCM_RIGHTS, SOL_SOCKET};
910
911        use crate::io::IoSliceMut;
912        use crate::sys::cvt_r;
913
914        unsafe {
915            const SCM_MSG_LEN: usize = size_of::<[c_int; 1]>();
916
917            #[repr(C)]
918            union Cmsg {
919                _buf: [u8; unsafe { CMSG_SPACE(SCM_MSG_LEN as u32) as usize }],
920                _align: libc::cmsghdr,
921            }
922            let mut cmsg: Cmsg = mem::zeroed();
923            // 0-length read to get the fd
924            let mut iov = [IoSliceMut::new(&mut [])];
925
926            let mut msg: libc::msghdr = mem::zeroed();
927
928            msg.msg_iov = (&raw mut iov) as *mut _;
929            msg.msg_iovlen = 1;
930            msg.msg_controllen = size_of::<Cmsg>() as _;
931            msg.msg_control = (&raw mut cmsg) as *mut _;
932
933            if cvt_r(|| libc::recvmsg(sock.as_raw(), &mut msg, libc::MSG_CMSG_CLOEXEC)).is_err() {
934                return -1;
935            }
936
937            let hdr = CMSG_FIRSTHDR((&raw mut msg) as *mut _);
938            if hdr.is_null()
939                || (*hdr).cmsg_level != SOL_SOCKET
940                || (*hdr).cmsg_type != SCM_RIGHTS
941                || (*hdr).cmsg_len != CMSG_LEN(SCM_MSG_LEN as _) as _
942            {
943                return -1;
944            }
945            let data = CMSG_DATA(hdr);
946
947            let mut fds = [-1 as c_int];
948
949            crate::ptr::copy_nonoverlapping(
950                data as *const _,
951                fds.as_mut_ptr().cast::<u8>(),
952                SCM_MSG_LEN,
953            );
954
955            fds[0]
956        }
957    }
958}
959
960////////////////////////////////////////////////////////////////////////////////
961// Processes
962////////////////////////////////////////////////////////////////////////////////
963
964/// The unique ID of the process (this should never be negative).
965pub struct Process {
966    pid: pid_t,
967    status: Option<ExitStatus>,
968    // On Linux, stores the pidfd created for this child.
969    // This is None if the user did not request pidfd creation,
970    // or if the pidfd could not be created for some reason
971    // (e.g. the `pidfd_open` syscall was not available).
972    #[cfg(target_os = "linux")]
973    pidfd: Option<PidFd>,
974}
975
976impl Process {
977    #[cfg(target_os = "linux")]
978    /// # Safety
979    ///
980    /// `pidfd` must either be -1 (representing no file descriptor) or a valid, exclusively owned file
981    /// descriptor (See [I/O Safety]).
982    ///
983    /// [I/O Safety]: crate::io#io-safety
984    unsafe fn new(pid: pid_t, pidfd: pid_t) -> Self {
985        use crate::os::unix::io::FromRawFd;
986        use crate::sys::FromInner;
987        // Safety: If `pidfd` is nonnegative, we assume it's valid and otherwise unowned.
988        let pidfd = (pidfd >= 0).then(|| PidFd::from_inner(sys::fd::FileDesc::from_raw_fd(pidfd)));
989        Process { pid, status: None, pidfd }
990    }
991
992    #[cfg(not(target_os = "linux"))]
993    unsafe fn new(pid: pid_t, _pidfd: pid_t) -> Self {
994        Process { pid, status: None }
995    }
996
997    pub fn id(&self) -> u32 {
998        self.pid as u32
999    }
1000
1001    pub fn kill(&self) -> io::Result<()> {
1002        self.send_signal(libc::SIGKILL)
1003    }
1004
1005    pub(crate) fn send_signal(&self, signal: i32) -> io::Result<()> {
1006        // If we've already waited on this process then the pid can be recycled and
1007        // used for another process, and we probably shouldn't be sending signals to
1008        // random processes, so return Ok because the process has exited already.
1009        if self.status.is_some() {
1010            return Ok(());
1011        }
1012        #[cfg(target_os = "linux")]
1013        if let Some(pid_fd) = self.pidfd.as_ref() {
1014            // pidfd_send_signal predates pidfd_open. so if we were able to get an fd then sending signals will work too
1015            return pid_fd.send_signal(signal);
1016        }
1017        cvt(unsafe { libc::kill(self.pid, signal) }).map(drop)
1018    }
1019
1020    pub(crate) fn send_process_group_signal(&self, signal: i32) -> io::Result<()> {
1021        // See note in `send_signal` regarding recycled PIDs.
1022        if self.status.is_some() {
1023            return Ok(());
1024        }
1025        #[cfg(target_os = "linux")]
1026        if let Some(pid_fd) = self.pidfd.as_ref() {
1027            // The `PIDFD_SIGNAL_PROCESS_GROUP` flag requires kernel >= 6.9
1028            return pid_fd.send_process_group_signal(signal);
1029        }
1030        cvt(unsafe { libc::killpg(self.pid, signal) }).map(drop)
1031    }
1032
1033    pub fn wait(&mut self) -> io::Result<ExitStatus> {
1034        use crate::sys::cvt_r;
1035        if let Some(status) = self.status {
1036            return Ok(status);
1037        }
1038        #[cfg(target_os = "linux")]
1039        if let Some(pid_fd) = self.pidfd.as_ref() {
1040            let status = pid_fd.wait()?;
1041            self.status = Some(status);
1042            return Ok(status);
1043        }
1044        let mut status = 0 as c_int;
1045        cvt_r(|| unsafe { libc::waitpid(self.pid, &mut status, 0) })?;
1046        self.status = Some(ExitStatus::new(status));
1047        Ok(ExitStatus::new(status))
1048    }
1049
1050    pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
1051        if let Some(status) = self.status {
1052            return Ok(Some(status));
1053        }
1054        #[cfg(target_os = "linux")]
1055        if let Some(pid_fd) = self.pidfd.as_ref() {
1056            let status = pid_fd.try_wait()?;
1057            if let Some(status) = status {
1058                self.status = Some(status)
1059            }
1060            return Ok(status);
1061        }
1062        let mut status = 0 as c_int;
1063        let pid = cvt(unsafe { libc::waitpid(self.pid, &mut status, libc::WNOHANG) })?;
1064        if pid == 0 {
1065            Ok(None)
1066        } else {
1067            self.status = Some(ExitStatus::new(status));
1068            Ok(Some(ExitStatus::new(status)))
1069        }
1070    }
1071}
1072
1073/// Unix exit statuses
1074//
1075// This is not actually an "exit status" in Unix terminology.  Rather, it is a "wait status".
1076// See the discussion in comments and doc comments for `std::process::ExitStatus`.
1077#[derive(PartialEq, Eq, Clone, Copy, Default)]
1078pub struct ExitStatus(c_int);
1079
1080impl fmt::Debug for ExitStatus {
1081    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1082        f.debug_tuple("unix_wait_status").field(&self.0).finish()
1083    }
1084}
1085
1086impl ExitStatus {
1087    pub fn new(status: c_int) -> ExitStatus {
1088        ExitStatus(status)
1089    }
1090
1091    #[cfg(target_os = "linux")]
1092    pub fn from_waitid_siginfo(siginfo: libc::siginfo_t) -> ExitStatus {
1093        let status = unsafe { siginfo.si_status() };
1094
1095        match siginfo.si_code {
1096            libc::CLD_EXITED => ExitStatus((status & 0xff) << 8),
1097            libc::CLD_KILLED => ExitStatus(status),
1098            libc::CLD_DUMPED => ExitStatus(status | 0x80),
1099            libc::CLD_CONTINUED => ExitStatus(0xffff),
1100            libc::CLD_STOPPED | libc::CLD_TRAPPED => ExitStatus(((status & 0xff) << 8) | 0x7f),
1101            _ => unreachable!("waitid() should only return the above codes"),
1102        }
1103    }
1104
1105    fn exited(&self) -> bool {
1106        libc::WIFEXITED(self.0)
1107    }
1108
1109    pub fn exit_ok(&self) -> Result<(), ExitStatusError> {
1110        // This assumes that WIFEXITED(status) && WEXITSTATUS==0 corresponds to status==0. This is
1111        // true on all actual versions of Unix, is widely assumed, and is specified in SuS
1112        // https://pubs.opengroup.org/onlinepubs/9799919799/functions/wait.html. If it is not
1113        // true for a platform pretending to be Unix, the tests (our doctests, and also
1114        // unix/tests.rs) will spot it. `ExitStatusError::code` assumes this too.
1115        match NonZero::try_from(self.0) {
1116            /* was nonzero */ Ok(failure) => Err(ExitStatusError(failure)),
1117            /* was zero, couldn't convert */ Err(_) => Ok(()),
1118        }
1119    }
1120
1121    pub fn code(&self) -> Option<i32> {
1122        self.exited().then(|| libc::WEXITSTATUS(self.0))
1123    }
1124
1125    pub fn signal(&self) -> Option<i32> {
1126        libc::WIFSIGNALED(self.0).then(|| libc::WTERMSIG(self.0))
1127    }
1128
1129    pub fn core_dumped(&self) -> bool {
1130        libc::WIFSIGNALED(self.0) && libc::WCOREDUMP(self.0)
1131    }
1132
1133    pub fn stopped_signal(&self) -> Option<i32> {
1134        libc::WIFSTOPPED(self.0).then(|| libc::WSTOPSIG(self.0))
1135    }
1136
1137    pub fn continued(&self) -> bool {
1138        libc::WIFCONTINUED(self.0)
1139    }
1140
1141    pub fn into_raw(&self) -> c_int {
1142        self.0
1143    }
1144}
1145
1146/// Converts a raw `c_int` to a type-safe `ExitStatus` by wrapping it without copying.
1147impl From<c_int> for ExitStatus {
1148    fn from(a: c_int) -> ExitStatus {
1149        ExitStatus(a)
1150    }
1151}
1152
1153/// Converts a signal number to a readable, searchable name.
1154///
1155/// This string should be displayed right after the signal number.
1156/// If a signal is unrecognized, it returns the empty string, so that
1157/// you just get the number like "0". If it is recognized, you'll get
1158/// something like "9 (SIGKILL)".
1159fn signal_string(signal: i32) -> &'static str {
1160    match signal {
1161        libc::SIGHUP => " (SIGHUP)",
1162        libc::SIGINT => " (SIGINT)",
1163        libc::SIGQUIT => " (SIGQUIT)",
1164        libc::SIGILL => " (SIGILL)",
1165        libc::SIGTRAP => " (SIGTRAP)",
1166        libc::SIGABRT => " (SIGABRT)",
1167        #[cfg(not(target_os = "l4re"))]
1168        libc::SIGBUS => " (SIGBUS)",
1169        libc::SIGFPE => " (SIGFPE)",
1170        libc::SIGKILL => " (SIGKILL)",
1171        #[cfg(not(target_os = "l4re"))]
1172        libc::SIGUSR1 => " (SIGUSR1)",
1173        libc::SIGSEGV => " (SIGSEGV)",
1174        #[cfg(not(target_os = "l4re"))]
1175        libc::SIGUSR2 => " (SIGUSR2)",
1176        libc::SIGPIPE => " (SIGPIPE)",
1177        libc::SIGALRM => " (SIGALRM)",
1178        libc::SIGTERM => " (SIGTERM)",
1179        #[cfg(not(target_os = "l4re"))]
1180        libc::SIGCHLD => " (SIGCHLD)",
1181        #[cfg(not(target_os = "l4re"))]
1182        libc::SIGCONT => " (SIGCONT)",
1183        #[cfg(not(target_os = "l4re"))]
1184        libc::SIGSTOP => " (SIGSTOP)",
1185        #[cfg(not(target_os = "l4re"))]
1186        libc::SIGTSTP => " (SIGTSTP)",
1187        #[cfg(not(target_os = "l4re"))]
1188        libc::SIGTTIN => " (SIGTTIN)",
1189        #[cfg(not(target_os = "l4re"))]
1190        libc::SIGTTOU => " (SIGTTOU)",
1191        #[cfg(not(target_os = "l4re"))]
1192        libc::SIGURG => " (SIGURG)",
1193        #[cfg(not(target_os = "l4re"))]
1194        libc::SIGXCPU => " (SIGXCPU)",
1195        #[cfg(not(any(target_os = "l4re", target_os = "rtems")))]
1196        libc::SIGXFSZ => " (SIGXFSZ)",
1197        #[cfg(not(any(target_os = "l4re", target_os = "rtems")))]
1198        libc::SIGVTALRM => " (SIGVTALRM)",
1199        #[cfg(not(target_os = "l4re"))]
1200        libc::SIGPROF => " (SIGPROF)",
1201        #[cfg(not(any(target_os = "l4re", target_os = "rtems")))]
1202        libc::SIGWINCH => " (SIGWINCH)",
1203        #[cfg(not(any(target_os = "haiku", target_os = "l4re")))]
1204        libc::SIGIO => " (SIGIO)",
1205        #[cfg(target_os = "haiku")]
1206        libc::SIGPOLL => " (SIGPOLL)",
1207        #[cfg(not(target_os = "l4re"))]
1208        libc::SIGSYS => " (SIGSYS)",
1209        // For information on Linux signals, run `man 7 signal`
1210        #[cfg(all(
1211            target_os = "linux",
1212            any(
1213                target_arch = "x86_64",
1214                target_arch = "x86",
1215                target_arch = "arm",
1216                target_arch = "aarch64"
1217            )
1218        ))]
1219        libc::SIGSTKFLT => " (SIGSTKFLT)",
1220        #[cfg(any(
1221            target_os = "linux",
1222            target_os = "nto",
1223            target_os = "qnx",
1224            target_os = "cygwin"
1225        ))]
1226        libc::SIGPWR => " (SIGPWR)",
1227        #[cfg(any(
1228            target_os = "freebsd",
1229            target_os = "netbsd",
1230            target_os = "openbsd",
1231            target_os = "dragonfly",
1232            target_os = "nto",
1233            target_os = "qnx",
1234            target_vendor = "apple",
1235            target_os = "cygwin",
1236        ))]
1237        libc::SIGEMT => " (SIGEMT)",
1238        #[cfg(any(
1239            target_os = "freebsd",
1240            target_os = "netbsd",
1241            target_os = "openbsd",
1242            target_os = "dragonfly",
1243            target_vendor = "apple",
1244        ))]
1245        libc::SIGINFO => " (SIGINFO)",
1246        #[cfg(target_os = "hurd")]
1247        libc::SIGLOST => " (SIGLOST)",
1248        #[cfg(target_os = "freebsd")]
1249        libc::SIGTHR => " (SIGTHR)",
1250        #[cfg(target_os = "freebsd")]
1251        libc::SIGLIBRT => " (SIGLIBRT)",
1252        _ => "",
1253    }
1254}
1255
1256impl fmt::Display for ExitStatus {
1257    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1258        if let Some(code) = self.code() {
1259            write!(f, "exit status: {code}")
1260        } else if let Some(signal) = self.signal() {
1261            let signal_string = signal_string(signal);
1262            if self.core_dumped() {
1263                write!(f, "signal: {signal}{signal_string} (core dumped)")
1264            } else {
1265                write!(f, "signal: {signal}{signal_string}")
1266            }
1267        } else if let Some(signal) = self.stopped_signal() {
1268            let signal_string = signal_string(signal);
1269            write!(f, "stopped (not terminated) by signal: {signal}{signal_string}")
1270        } else if self.continued() {
1271            write!(f, "continued (WIFCONTINUED)")
1272        } else {
1273            write!(f, "unrecognised wait status: {} {:#x}", self.0, self.0)
1274        }
1275    }
1276}
1277
1278#[derive(PartialEq, Eq, Clone, Copy)]
1279pub struct ExitStatusError(NonZero<c_int>);
1280
1281impl Into<ExitStatus> for ExitStatusError {
1282    fn into(self) -> ExitStatus {
1283        ExitStatus(self.0.into())
1284    }
1285}
1286
1287impl fmt::Debug for ExitStatusError {
1288    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1289        f.debug_tuple("unix_wait_status").field(&self.0).finish()
1290    }
1291}
1292
1293impl ExitStatusError {
1294    pub fn code(self) -> Option<NonZero<i32>> {
1295        ExitStatus(self.0.into()).code().map(|st| st.try_into().unwrap())
1296    }
1297}
1298
1299#[cfg(target_os = "linux")]
1300mod linux_child_ext {
1301    use crate::io::ErrorKind;
1302    use crate::os::linux::process as os;
1303    use crate::sys::{FromInner, process as imp};
1304    use crate::{io, mem};
1305
1306    #[unstable(feature = "linux_pidfd", issue = "82971")]
1307    impl crate::os::linux::process::ChildExt for crate::process::Child {
1308        fn pidfd(&self) -> io::Result<&os::PidFd> {
1309            self.handle
1310                .pidfd
1311                .as_ref()
1312                // SAFETY: The os type is a transparent wrapper, therefore we can transmute references
1313                .map(|fd| unsafe { mem::transmute::<&imp::PidFd, &os::PidFd>(fd) })
1314                .ok_or_else(|| io::const_error!(ErrorKind::Uncategorized, "no pidfd was created."))
1315        }
1316
1317        fn into_pidfd(mut self) -> Result<os::PidFd, Self> {
1318            self.handle
1319                .pidfd
1320                .take()
1321                .map(<os::PidFd as FromInner<imp::PidFd>>::from_inner)
1322                .ok_or_else(|| self)
1323        }
1324    }
1325}
1326
1327#[cfg(test)]
1328mod tests;
1329
1330// See [`unsupported_wait_status::compare_with_linux`];
1331#[cfg(all(test, target_os = "linux"))]
1332#[path = "unsupported/wait_status.rs"]
1333mod unsupported_wait_status;