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 crate::thread;
25 use libc::{c_char, posix_spawn_file_actions_t, posix_spawnattr_t};
26 use crate::time::Duration;
27 use crate::sync::LazyLock;
28 fn get_clock_resolution() -> Duration {
31 static MIN_DELAY: LazyLock<Duration, fn() -> Duration> = LazyLock::new(|| {
32 let mut mindelay = libc::timespec { tv_sec: 0, tv_nsec: 0 };
33 if unsafe { libc::clock_getres(libc::CLOCK_MONOTONIC, &mut mindelay) } == 0
34 {
35 Duration::from_nanos(mindelay.tv_nsec as u64)
36 } else {
37 Duration::from_millis(1)
38 }
39 });
40 *MIN_DELAY
41 }
42 const MIN_FORKSPAWN_SLEEP: Duration = Duration::from_nanos(1);
44 const MAX_FORKSPAWN_SLEEP: Duration = Duration::from_millis(1000);
46 }
47 _ => {}
48}
49
50impl 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 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); 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 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 let mut p = unsafe { Process::new(pid, pidfd) };
135 let mut bytes = [0; 8];
136
137 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 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 #[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 #[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 #[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 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 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 #[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 #[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 #[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 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 #[cfg(not(target_os = "emscripten"))]
356 {
357 if !crate::sys::pal::on_broken_pipe_used() {
365 #[cfg(target_os = "android")] {
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 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 #[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 const FORK_EXEC: u8 = 2;
497 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 support = FORK_EXEC;
513 if pidfd_spawnp.get().is_some() && let Ok(pid) = pidfd.pid() {
516 assert_eq!(pid, crate::process::id(), "sanity check");
517 support = SPAWN;
518 }
519 }
520 Err(e) if matches!(e.raw_os_error(), Some(libc::EMFILE | libc::ENFILE | libc::ENOMEM)) => {
521 return Err(e)
524 }
525 _ => {
526 }
528 }
529 PIDFD_SUPPORTED.store(support, Ordering::Relaxed);
530 if support == FORK_EXEC {
531 return Ok(None);
532 }
533 }
534 core::debug_assert_matches!(support, SPAWN | NO);
535 }
536 }
537 _ => {
538 if self.get_create_pidfd() {
539 unreachable!("only implemented on linux")
540 }
541 }
542 }
543
544 #[cfg(all(target_os = "linux", target_env = "gnu"))]
546 {
547 if let Some(version) = sys::pal::conf::glibc_version() {
548 if version < (2, 24) {
549 return Ok(None);
550 }
551 } else {
552 return Ok(None);
553 }
554 }
555
556 #[cfg(any(target_os = "nto", target_os = "qnx"))]
561 unsafe fn retrying_libc_posix_spawnp(
562 pid: *mut pid_t,
563 file: *const c_char,
564 file_actions: *const posix_spawn_file_actions_t,
565 attrp: *const posix_spawnattr_t,
566 argv: *const *mut c_char,
567 envp: *const *mut c_char,
568 ) -> io::Result<i32> {
569 let mut delay = MIN_FORKSPAWN_SLEEP;
570 loop {
571 match libc::posix_spawnp(pid, file, file_actions, attrp, argv, envp) {
572 libc::EBADF => {
573 if delay < get_clock_resolution() {
574 thread::yield_now();
577 } else if delay < MAX_FORKSPAWN_SLEEP {
578 thread::sleep(delay);
579 } else {
580 return Err(io::const_error!(
581 ErrorKind::WouldBlock,
582 "posix_spawnp returned EBADF too often",
583 ));
584 }
585 delay *= 2;
586 continue;
587 }
588 r => {
589 return Ok(r);
590 }
591 }
592 }
593 }
594
595 type PosixSpawnAddChdirFn = unsafe extern "C" fn(
596 *mut libc::posix_spawn_file_actions_t,
597 *const libc::c_char,
598 ) -> libc::c_int;
599
600 #[cfg(not(any(all(target_os = "linux", target_env = "musl"), target_os = "cygwin")))]
607 fn get_posix_spawn_addchdir() -> Option<PosixSpawnAddChdirFn> {
608 use crate::sys::weak::weak;
609
610 weak!(
615 fn posix_spawn_file_actions_addchdir_np(
616 file_actions: *mut libc::posix_spawn_file_actions_t,
617 path: *const libc::c_char,
618 ) -> libc::c_int;
619 );
620
621 weak!(
622 fn posix_spawn_file_actions_addchdir(
623 file_actions: *mut libc::posix_spawn_file_actions_t,
624 path: *const libc::c_char,
625 ) -> libc::c_int;
626 );
627
628 posix_spawn_file_actions_addchdir_np
629 .get()
630 .or_else(|| posix_spawn_file_actions_addchdir.get())
631 }
632
633 #[cfg(any(all(target_os = "linux", target_env = "musl"), target_os = "cygwin"))]
643 fn get_posix_spawn_addchdir() -> Option<PosixSpawnAddChdirFn> {
644 Some(libc::posix_spawn_file_actions_addchdir_np)
646 }
647
648 let addchdir = match self.get_cwd() {
649 Some(cwd) => {
650 if cfg!(target_vendor = "apple") {
651 if self.get_program_kind() == ProgramKind::Relative {
657 return Ok(None);
658 }
659 }
660 match get_posix_spawn_addchdir() {
664 Some(f) => Some((f, cwd)),
665 None => return Ok(None),
666 }
667 }
668 None => None,
669 };
670
671 let pgroup = self.get_pgroup();
672
673 struct PosixSpawnFileActions<'a>(&'a mut MaybeUninit<libc::posix_spawn_file_actions_t>);
674
675 impl Drop for PosixSpawnFileActions<'_> {
676 fn drop(&mut self) {
677 unsafe {
678 libc::posix_spawn_file_actions_destroy(self.0.as_mut_ptr());
679 }
680 }
681 }
682
683 struct PosixSpawnattr<'a>(&'a mut MaybeUninit<libc::posix_spawnattr_t>);
684
685 impl Drop for PosixSpawnattr<'_> {
686 fn drop(&mut self) {
687 unsafe {
688 libc::posix_spawnattr_destroy(self.0.as_mut_ptr());
689 }
690 }
691 }
692
693 unsafe {
694 let mut attrs = MaybeUninit::uninit();
695 cvt_nz(libc::posix_spawnattr_init(attrs.as_mut_ptr()))?;
696 let attrs = PosixSpawnattr(&mut attrs);
697
698 let mut flags = 0;
699
700 let mut file_actions = MaybeUninit::uninit();
701 cvt_nz(libc::posix_spawn_file_actions_init(file_actions.as_mut_ptr()))?;
702 let file_actions = PosixSpawnFileActions(&mut file_actions);
703
704 if let Some(fd) = stdio.stdin.fd() {
705 cvt_nz(libc::posix_spawn_file_actions_adddup2(
706 file_actions.0.as_mut_ptr(),
707 fd,
708 libc::STDIN_FILENO,
709 ))?;
710 }
711 if let Some(fd) = stdio.stdout.fd() {
712 cvt_nz(libc::posix_spawn_file_actions_adddup2(
713 file_actions.0.as_mut_ptr(),
714 fd,
715 libc::STDOUT_FILENO,
716 ))?;
717 }
718 if let Some(fd) = stdio.stderr.fd() {
719 cvt_nz(libc::posix_spawn_file_actions_adddup2(
720 file_actions.0.as_mut_ptr(),
721 fd,
722 libc::STDERR_FILENO,
723 ))?;
724 }
725 if let Some((f, cwd)) = addchdir {
726 cvt_nz(f(file_actions.0.as_mut_ptr(), cwd.as_ptr()))?;
727 }
728
729 if let Some(pgroup) = pgroup {
730 flags |= libc::POSIX_SPAWN_SETPGROUP;
731 cvt_nz(libc::posix_spawnattr_setpgroup(attrs.0.as_mut_ptr(), pgroup))?;
732 }
733
734 if !on_broken_pipe_used() {
742 let mut default_set = MaybeUninit::<libc::sigset_t>::uninit();
743 cvt(sigemptyset(default_set.as_mut_ptr()))?;
744 cvt(sigaddset(default_set.as_mut_ptr(), libc::SIGPIPE))?;
745 #[cfg(target_os = "hurd")]
746 {
747 cvt(sigaddset(default_set.as_mut_ptr(), libc::SIGLOST))?;
748 }
749 cvt_nz(libc::posix_spawnattr_setsigdefault(
750 attrs.0.as_mut_ptr(),
751 default_set.as_ptr(),
752 ))?;
753 flags |= libc::POSIX_SPAWN_SETSIGDEF;
754 }
755
756 if self.get_setsid() {
757 cfg_select! {
758 all(target_os = "linux", target_env = "gnu") => {
759 flags |= libc::POSIX_SPAWN_SETSID;
760 }
761 _ => {
762 return Ok(None);
763 }
764 }
765 }
766
767 cvt_nz(libc::posix_spawnattr_setflags(attrs.0.as_mut_ptr(), flags as _))?;
768
769 let _env_lock = sys::env::env_read_lock();
771 let envp = envp.map(|c| c.as_ptr()).unwrap_or_else(|| *sys::env::environ() as *const _);
772
773 #[cfg(not(any(target_os = "nto", target_os = "qnx")))]
774 let spawn_fn = libc::posix_spawnp;
775 #[cfg(any(target_os = "nto", target_os = "qnx"))]
776 let spawn_fn = retrying_libc_posix_spawnp;
777
778 #[cfg(target_os = "linux")]
779 if self.get_create_pidfd() && PIDFD_SUPPORTED.load(Ordering::Relaxed) == SPAWN {
780 let mut pidfd: libc::c_int = -1;
781 let spawn_res = pidfd_spawnp.get().unwrap()(
782 &mut pidfd,
783 self.get_program_cstr().as_ptr(),
784 file_actions.0.as_ptr(),
785 attrs.0.as_ptr(),
786 self.get_argv().as_ptr() as *const _,
787 envp as *const _,
788 );
789
790 let spawn_res = cvt_nz(spawn_res);
791 if let Err(ref e) = spawn_res
792 && e.raw_os_error() == Some(libc::ENOSYS)
793 {
794 PIDFD_SUPPORTED.store(FORK_EXEC, Ordering::Relaxed);
795 return Ok(None);
796 }
797 spawn_res?;
798
799 use crate::os::fd::{FromRawFd, IntoRawFd};
800
801 let pidfd = PidFd::from_raw_fd(pidfd);
802 let pid = match pidfd.pid() {
803 Ok(pid) => pid,
804 Err(e) => {
805 return Err(Error::new(
811 e.kind(),
812 "pidfd_spawnp succeeded but the child's PID could not be obtained",
813 ));
814 }
815 };
816
817 return Ok(Some(Process::new(pid as i32, pidfd.into_raw_fd())));
818 }
819
820 let mut p = Process::new(0, -1);
822
823 let spawn_res = spawn_fn(
824 &mut p.pid,
825 self.get_program_cstr().as_ptr(),
826 file_actions.0.as_ptr(),
827 attrs.0.as_ptr(),
828 self.get_argv().as_ptr() as *const _,
829 envp as *const _,
830 );
831
832 #[cfg(any(target_os = "nto", target_os = "qnx"))]
833 let spawn_res = spawn_res?;
834
835 cvt_nz(spawn_res)?;
836 Ok(Some(p))
837 }
838 }
839
840 #[cfg(target_os = "linux")]
841 fn send_pidfd(&self, sock: &crate::sys::net::Socket) {
842 use libc::{CMSG_DATA, CMSG_FIRSTHDR, CMSG_LEN, CMSG_SPACE, SCM_RIGHTS, SOL_SOCKET};
843
844 use crate::io::IoSlice;
845 use crate::os::fd::RawFd;
846 use crate::sys::cvt_r;
847
848 unsafe {
849 let child_pid = libc::getpid();
850 let pidfd = libc::syscall(libc::SYS_pidfd_open, child_pid, 0);
852
853 let fds: [c_int; 1] = [pidfd as RawFd];
854
855 const SCM_MSG_LEN: usize = size_of::<[c_int; 1]>();
856
857 #[repr(C)]
858 union Cmsg {
859 buf: [u8; unsafe { CMSG_SPACE(SCM_MSG_LEN as u32) as usize }],
860 _align: libc::cmsghdr,
861 }
862
863 let mut cmsg: Cmsg = mem::zeroed();
864
865 let mut iov = [IoSlice::new(b"")];
867 let mut msg: libc::msghdr = mem::zeroed();
868
869 msg.msg_iov = (&raw mut iov) as *mut _;
870 msg.msg_iovlen = 1;
871
872 if pidfd >= 0 {
874 msg.msg_controllen = size_of_val(&cmsg.buf) as _;
875 msg.msg_control = (&raw mut cmsg.buf) as *mut _;
876
877 let hdr = CMSG_FIRSTHDR((&raw mut msg) as *mut _);
878 (*hdr).cmsg_level = SOL_SOCKET;
879 (*hdr).cmsg_type = SCM_RIGHTS;
880 (*hdr).cmsg_len = CMSG_LEN(SCM_MSG_LEN as _) as _;
881 let data = CMSG_DATA(hdr);
882 crate::ptr::copy_nonoverlapping(
883 fds.as_ptr().cast::<u8>(),
884 data as *mut _,
885 SCM_MSG_LEN,
886 );
887 }
888
889 match cvt_r(|| libc::sendmsg(sock.as_raw(), &msg, libc::MSG_EOR)) {
892 Ok(0) => {}
893 other => rtabort!("failed to communicate with parent process. {:?}", other),
894 }
895 }
896 }
897
898 #[cfg(target_os = "linux")]
899 fn recv_pidfd(&self, sock: &crate::sys::net::Socket) -> pid_t {
900 use libc::{CMSG_DATA, CMSG_FIRSTHDR, CMSG_LEN, CMSG_SPACE, SCM_RIGHTS, SOL_SOCKET};
901
902 use crate::io::IoSliceMut;
903 use crate::sys::cvt_r;
904
905 unsafe {
906 const SCM_MSG_LEN: usize = size_of::<[c_int; 1]>();
907
908 #[repr(C)]
909 union Cmsg {
910 _buf: [u8; unsafe { CMSG_SPACE(SCM_MSG_LEN as u32) as usize }],
911 _align: libc::cmsghdr,
912 }
913 let mut cmsg: Cmsg = mem::zeroed();
914 let mut iov = [IoSliceMut::new(&mut [])];
916
917 let mut msg: libc::msghdr = mem::zeroed();
918
919 msg.msg_iov = (&raw mut iov) as *mut _;
920 msg.msg_iovlen = 1;
921 msg.msg_controllen = size_of::<Cmsg>() as _;
922 msg.msg_control = (&raw mut cmsg) as *mut _;
923
924 match cvt_r(|| libc::recvmsg(sock.as_raw(), &mut msg, libc::MSG_CMSG_CLOEXEC)) {
925 Err(_) => return -1,
926 Ok(_) => {}
927 }
928
929 let hdr = CMSG_FIRSTHDR((&raw mut msg) as *mut _);
930 if hdr.is_null()
931 || (*hdr).cmsg_level != SOL_SOCKET
932 || (*hdr).cmsg_type != SCM_RIGHTS
933 || (*hdr).cmsg_len != CMSG_LEN(SCM_MSG_LEN as _) as _
934 {
935 return -1;
936 }
937 let data = CMSG_DATA(hdr);
938
939 let mut fds = [-1 as c_int];
940
941 crate::ptr::copy_nonoverlapping(
942 data as *const _,
943 fds.as_mut_ptr().cast::<u8>(),
944 SCM_MSG_LEN,
945 );
946
947 fds[0]
948 }
949 }
950}
951
952pub struct Process {
958 pid: pid_t,
959 status: Option<ExitStatus>,
960 #[cfg(target_os = "linux")]
965 pidfd: Option<PidFd>,
966}
967
968impl Process {
969 #[cfg(target_os = "linux")]
970 unsafe fn new(pid: pid_t, pidfd: pid_t) -> Self {
977 use crate::os::unix::io::FromRawFd;
978 use crate::sys::FromInner;
979 let pidfd = (pidfd >= 0).then(|| PidFd::from_inner(sys::fd::FileDesc::from_raw_fd(pidfd)));
981 Process { pid, status: None, pidfd }
982 }
983
984 #[cfg(not(target_os = "linux"))]
985 unsafe fn new(pid: pid_t, _pidfd: pid_t) -> Self {
986 Process { pid, status: None }
987 }
988
989 pub fn id(&self) -> u32 {
990 self.pid as u32
991 }
992
993 pub fn kill(&self) -> io::Result<()> {
994 self.send_signal(libc::SIGKILL)
995 }
996
997 pub(crate) fn send_signal(&self, signal: i32) -> io::Result<()> {
998 if self.status.is_some() {
1002 return Ok(());
1003 }
1004 #[cfg(target_os = "linux")]
1005 if let Some(pid_fd) = self.pidfd.as_ref() {
1006 return pid_fd.send_signal(signal);
1008 }
1009 cvt(unsafe { libc::kill(self.pid, signal) }).map(drop)
1010 }
1011
1012 pub(crate) fn send_process_group_signal(&self, signal: i32) -> io::Result<()> {
1013 if self.status.is_some() {
1015 return Ok(());
1016 }
1017 #[cfg(target_os = "linux")]
1018 if let Some(pid_fd) = self.pidfd.as_ref() {
1019 return pid_fd.send_process_group_signal(signal);
1021 }
1022 cvt(unsafe { libc::killpg(self.pid, signal) }).map(drop)
1023 }
1024
1025 pub fn wait(&mut self) -> io::Result<ExitStatus> {
1026 use crate::sys::cvt_r;
1027 if let Some(status) = self.status {
1028 return Ok(status);
1029 }
1030 #[cfg(target_os = "linux")]
1031 if let Some(pid_fd) = self.pidfd.as_ref() {
1032 let status = pid_fd.wait()?;
1033 self.status = Some(status);
1034 return Ok(status);
1035 }
1036 let mut status = 0 as c_int;
1037 cvt_r(|| unsafe { libc::waitpid(self.pid, &mut status, 0) })?;
1038 self.status = Some(ExitStatus::new(status));
1039 Ok(ExitStatus::new(status))
1040 }
1041
1042 pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
1043 if let Some(status) = self.status {
1044 return Ok(Some(status));
1045 }
1046 #[cfg(target_os = "linux")]
1047 if let Some(pid_fd) = self.pidfd.as_ref() {
1048 let status = pid_fd.try_wait()?;
1049 if let Some(status) = status {
1050 self.status = Some(status)
1051 }
1052 return Ok(status);
1053 }
1054 let mut status = 0 as c_int;
1055 let pid = cvt(unsafe { libc::waitpid(self.pid, &mut status, libc::WNOHANG) })?;
1056 if pid == 0 {
1057 Ok(None)
1058 } else {
1059 self.status = Some(ExitStatus::new(status));
1060 Ok(Some(ExitStatus::new(status)))
1061 }
1062 }
1063}
1064
1065#[derive(PartialEq, Eq, Clone, Copy, Default)]
1070pub struct ExitStatus(c_int);
1071
1072impl fmt::Debug for ExitStatus {
1073 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1074 f.debug_tuple("unix_wait_status").field(&self.0).finish()
1075 }
1076}
1077
1078impl ExitStatus {
1079 pub fn new(status: c_int) -> ExitStatus {
1080 ExitStatus(status)
1081 }
1082
1083 #[cfg(target_os = "linux")]
1084 pub fn from_waitid_siginfo(siginfo: libc::siginfo_t) -> ExitStatus {
1085 let status = unsafe { siginfo.si_status() };
1086
1087 match siginfo.si_code {
1088 libc::CLD_EXITED => ExitStatus((status & 0xff) << 8),
1089 libc::CLD_KILLED => ExitStatus(status),
1090 libc::CLD_DUMPED => ExitStatus(status | 0x80),
1091 libc::CLD_CONTINUED => ExitStatus(0xffff),
1092 libc::CLD_STOPPED | libc::CLD_TRAPPED => ExitStatus(((status & 0xff) << 8) | 0x7f),
1093 _ => unreachable!("waitid() should only return the above codes"),
1094 }
1095 }
1096
1097 fn exited(&self) -> bool {
1098 libc::WIFEXITED(self.0)
1099 }
1100
1101 pub fn exit_ok(&self) -> Result<(), ExitStatusError> {
1102 match NonZero::try_from(self.0) {
1108 Ok(failure) => Err(ExitStatusError(failure)),
1109 Err(_) => Ok(()),
1110 }
1111 }
1112
1113 pub fn code(&self) -> Option<i32> {
1114 self.exited().then(|| libc::WEXITSTATUS(self.0))
1115 }
1116
1117 pub fn signal(&self) -> Option<i32> {
1118 libc::WIFSIGNALED(self.0).then(|| libc::WTERMSIG(self.0))
1119 }
1120
1121 pub fn core_dumped(&self) -> bool {
1122 libc::WIFSIGNALED(self.0) && libc::WCOREDUMP(self.0)
1123 }
1124
1125 pub fn stopped_signal(&self) -> Option<i32> {
1126 libc::WIFSTOPPED(self.0).then(|| libc::WSTOPSIG(self.0))
1127 }
1128
1129 pub fn continued(&self) -> bool {
1130 libc::WIFCONTINUED(self.0)
1131 }
1132
1133 pub fn into_raw(&self) -> c_int {
1134 self.0
1135 }
1136}
1137
1138impl From<c_int> for ExitStatus {
1140 fn from(a: c_int) -> ExitStatus {
1141 ExitStatus(a)
1142 }
1143}
1144
1145fn signal_string(signal: i32) -> &'static str {
1152 match signal {
1153 libc::SIGHUP => " (SIGHUP)",
1154 libc::SIGINT => " (SIGINT)",
1155 libc::SIGQUIT => " (SIGQUIT)",
1156 libc::SIGILL => " (SIGILL)",
1157 libc::SIGTRAP => " (SIGTRAP)",
1158 libc::SIGABRT => " (SIGABRT)",
1159 #[cfg(not(target_os = "l4re"))]
1160 libc::SIGBUS => " (SIGBUS)",
1161 libc::SIGFPE => " (SIGFPE)",
1162 libc::SIGKILL => " (SIGKILL)",
1163 #[cfg(not(target_os = "l4re"))]
1164 libc::SIGUSR1 => " (SIGUSR1)",
1165 libc::SIGSEGV => " (SIGSEGV)",
1166 #[cfg(not(target_os = "l4re"))]
1167 libc::SIGUSR2 => " (SIGUSR2)",
1168 libc::SIGPIPE => " (SIGPIPE)",
1169 libc::SIGALRM => " (SIGALRM)",
1170 libc::SIGTERM => " (SIGTERM)",
1171 #[cfg(not(target_os = "l4re"))]
1172 libc::SIGCHLD => " (SIGCHLD)",
1173 #[cfg(not(target_os = "l4re"))]
1174 libc::SIGCONT => " (SIGCONT)",
1175 #[cfg(not(target_os = "l4re"))]
1176 libc::SIGSTOP => " (SIGSTOP)",
1177 #[cfg(not(target_os = "l4re"))]
1178 libc::SIGTSTP => " (SIGTSTP)",
1179 #[cfg(not(target_os = "l4re"))]
1180 libc::SIGTTIN => " (SIGTTIN)",
1181 #[cfg(not(target_os = "l4re"))]
1182 libc::SIGTTOU => " (SIGTTOU)",
1183 #[cfg(not(target_os = "l4re"))]
1184 libc::SIGURG => " (SIGURG)",
1185 #[cfg(not(target_os = "l4re"))]
1186 libc::SIGXCPU => " (SIGXCPU)",
1187 #[cfg(not(any(target_os = "l4re", target_os = "rtems")))]
1188 libc::SIGXFSZ => " (SIGXFSZ)",
1189 #[cfg(not(any(target_os = "l4re", target_os = "rtems")))]
1190 libc::SIGVTALRM => " (SIGVTALRM)",
1191 #[cfg(not(target_os = "l4re"))]
1192 libc::SIGPROF => " (SIGPROF)",
1193 #[cfg(not(any(target_os = "l4re", target_os = "rtems")))]
1194 libc::SIGWINCH => " (SIGWINCH)",
1195 #[cfg(not(any(target_os = "haiku", target_os = "l4re")))]
1196 libc::SIGIO => " (SIGIO)",
1197 #[cfg(target_os = "haiku")]
1198 libc::SIGPOLL => " (SIGPOLL)",
1199 #[cfg(not(target_os = "l4re"))]
1200 libc::SIGSYS => " (SIGSYS)",
1201 #[cfg(all(
1203 target_os = "linux",
1204 any(
1205 target_arch = "x86_64",
1206 target_arch = "x86",
1207 target_arch = "arm",
1208 target_arch = "aarch64"
1209 )
1210 ))]
1211 libc::SIGSTKFLT => " (SIGSTKFLT)",
1212 #[cfg(any(
1213 target_os = "linux",
1214 target_os = "nto",
1215 target_os = "qnx",
1216 target_os = "cygwin"
1217 ))]
1218 libc::SIGPWR => " (SIGPWR)",
1219 #[cfg(any(
1220 target_os = "freebsd",
1221 target_os = "netbsd",
1222 target_os = "openbsd",
1223 target_os = "dragonfly",
1224 target_os = "nto",
1225 target_os = "qnx",
1226 target_vendor = "apple",
1227 target_os = "cygwin",
1228 ))]
1229 libc::SIGEMT => " (SIGEMT)",
1230 #[cfg(any(
1231 target_os = "freebsd",
1232 target_os = "netbsd",
1233 target_os = "openbsd",
1234 target_os = "dragonfly",
1235 target_vendor = "apple",
1236 ))]
1237 libc::SIGINFO => " (SIGINFO)",
1238 #[cfg(target_os = "hurd")]
1239 libc::SIGLOST => " (SIGLOST)",
1240 #[cfg(target_os = "freebsd")]
1241 libc::SIGTHR => " (SIGTHR)",
1242 #[cfg(target_os = "freebsd")]
1243 libc::SIGLIBRT => " (SIGLIBRT)",
1244 _ => "",
1245 }
1246}
1247
1248impl fmt::Display for ExitStatus {
1249 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1250 if let Some(code) = self.code() {
1251 write!(f, "exit status: {code}")
1252 } else if let Some(signal) = self.signal() {
1253 let signal_string = signal_string(signal);
1254 if self.core_dumped() {
1255 write!(f, "signal: {signal}{signal_string} (core dumped)")
1256 } else {
1257 write!(f, "signal: {signal}{signal_string}")
1258 }
1259 } else if let Some(signal) = self.stopped_signal() {
1260 let signal_string = signal_string(signal);
1261 write!(f, "stopped (not terminated) by signal: {signal}{signal_string}")
1262 } else if self.continued() {
1263 write!(f, "continued (WIFCONTINUED)")
1264 } else {
1265 write!(f, "unrecognised wait status: {} {:#x}", self.0, self.0)
1266 }
1267 }
1268}
1269
1270#[derive(PartialEq, Eq, Clone, Copy)]
1271pub struct ExitStatusError(NonZero<c_int>);
1272
1273impl Into<ExitStatus> for ExitStatusError {
1274 fn into(self) -> ExitStatus {
1275 ExitStatus(self.0.into())
1276 }
1277}
1278
1279impl fmt::Debug for ExitStatusError {
1280 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1281 f.debug_tuple("unix_wait_status").field(&self.0).finish()
1282 }
1283}
1284
1285impl ExitStatusError {
1286 pub fn code(self) -> Option<NonZero<i32>> {
1287 ExitStatus(self.0.into()).code().map(|st| st.try_into().unwrap())
1288 }
1289}
1290
1291#[cfg(target_os = "linux")]
1292mod linux_child_ext {
1293 use crate::io::ErrorKind;
1294 use crate::os::linux::process as os;
1295 use crate::sys::{FromInner, process as imp};
1296 use crate::{io, mem};
1297
1298 #[unstable(feature = "linux_pidfd", issue = "82971")]
1299 impl crate::os::linux::process::ChildExt for crate::process::Child {
1300 fn pidfd(&self) -> io::Result<&os::PidFd> {
1301 self.handle
1302 .pidfd
1303 .as_ref()
1304 .map(|fd| unsafe { mem::transmute::<&imp::PidFd, &os::PidFd>(fd) })
1306 .ok_or_else(|| io::const_error!(ErrorKind::Uncategorized, "no pidfd was created."))
1307 }
1308
1309 fn into_pidfd(mut self) -> Result<os::PidFd, Self> {
1310 self.handle
1311 .pidfd
1312 .take()
1313 .map(|fd| <os::PidFd as FromInner<imp::PidFd>>::from_inner(fd))
1314 .ok_or_else(|| self)
1315 }
1316 }
1317}
1318
1319#[cfg(test)]
1320mod tests;
1321
1322#[cfg(all(test, target_os = "linux"))]
1324#[path = "unsupported/wait_status.rs"]
1325mod unsupported_wait_status;