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 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 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()
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 return Err(e);
531 }
532 _ => {
533 }
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 #[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 #[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 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 #[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 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 #[cfg(any(all(target_os = "linux", target_env = "musl"), target_os = "cygwin"))]
650 fn get_posix_spawn_addchdir() -> Option<PosixSpawnAddChdirFn> {
651 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 if self.get_program_kind() == ProgramKind::Relative {
664 return Ok(None);
665 }
666 }
667 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 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 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 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 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 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 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 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 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 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 if cvt_r(|| libc::recvmsg(sock.as_raw(), &mut msg, libc::MSG_CMSG_CLOEXEC)).is_err() {
932 return -1;
933 }
934
935 let hdr = CMSG_FIRSTHDR((&raw mut msg) as *mut _);
936 if hdr.is_null()
937 || (*hdr).cmsg_level != SOL_SOCKET
938 || (*hdr).cmsg_type != SCM_RIGHTS
939 || (*hdr).cmsg_len != CMSG_LEN(SCM_MSG_LEN as _) as _
940 {
941 return -1;
942 }
943 let data = CMSG_DATA(hdr);
944
945 let mut fds = [-1 as c_int];
946
947 crate::ptr::copy_nonoverlapping(
948 data as *const _,
949 fds.as_mut_ptr().cast::<u8>(),
950 SCM_MSG_LEN,
951 );
952
953 fds[0]
954 }
955 }
956}
957
958pub struct Process {
964 pid: pid_t,
965 status: Option<ExitStatus>,
966 #[cfg(target_os = "linux")]
971 pidfd: Option<PidFd>,
972}
973
974impl Process {
975 #[cfg(target_os = "linux")]
976 unsafe fn new(pid: pid_t, pidfd: pid_t) -> Self {
983 use crate::os::unix::io::FromRawFd;
984 use crate::sys::FromInner;
985 let pidfd = (pidfd >= 0).then(|| PidFd::from_inner(sys::fd::FileDesc::from_raw_fd(pidfd)));
987 Process { pid, status: None, pidfd }
988 }
989
990 #[cfg(not(target_os = "linux"))]
991 unsafe fn new(pid: pid_t, _pidfd: pid_t) -> Self {
992 Process { pid, status: None }
993 }
994
995 pub fn id(&self) -> u32 {
996 self.pid as u32
997 }
998
999 pub fn kill(&self) -> io::Result<()> {
1000 self.send_signal(libc::SIGKILL)
1001 }
1002
1003 pub(crate) fn send_signal(&self, signal: i32) -> io::Result<()> {
1004 if self.status.is_some() {
1008 return Ok(());
1009 }
1010 #[cfg(target_os = "linux")]
1011 if let Some(pid_fd) = self.pidfd.as_ref() {
1012 return pid_fd.send_signal(signal);
1014 }
1015 cvt(unsafe { libc::kill(self.pid, signal) }).map(drop)
1016 }
1017
1018 pub(crate) fn send_process_group_signal(&self, signal: i32) -> io::Result<()> {
1019 if self.status.is_some() {
1021 return Ok(());
1022 }
1023 #[cfg(target_os = "linux")]
1024 if let Some(pid_fd) = self.pidfd.as_ref() {
1025 return pid_fd.send_process_group_signal(signal);
1027 }
1028 cvt(unsafe { libc::killpg(self.pid, signal) }).map(drop)
1029 }
1030
1031 pub fn wait(&mut self) -> io::Result<ExitStatus> {
1032 use crate::sys::cvt_r;
1033 if let Some(status) = self.status {
1034 return Ok(status);
1035 }
1036 #[cfg(target_os = "linux")]
1037 if let Some(pid_fd) = self.pidfd.as_ref() {
1038 let status = pid_fd.wait()?;
1039 self.status = Some(status);
1040 return Ok(status);
1041 }
1042 let mut status = 0 as c_int;
1043 cvt_r(|| unsafe { libc::waitpid(self.pid, &mut status, 0) })?;
1044 self.status = Some(ExitStatus::new(status));
1045 Ok(ExitStatus::new(status))
1046 }
1047
1048 pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
1049 if let Some(status) = self.status {
1050 return Ok(Some(status));
1051 }
1052 #[cfg(target_os = "linux")]
1053 if let Some(pid_fd) = self.pidfd.as_ref() {
1054 let status = pid_fd.try_wait()?;
1055 if let Some(status) = status {
1056 self.status = Some(status)
1057 }
1058 return Ok(status);
1059 }
1060 let mut status = 0 as c_int;
1061 let pid = cvt(unsafe { libc::waitpid(self.pid, &mut status, libc::WNOHANG) })?;
1062 if pid == 0 {
1063 Ok(None)
1064 } else {
1065 self.status = Some(ExitStatus::new(status));
1066 Ok(Some(ExitStatus::new(status)))
1067 }
1068 }
1069}
1070
1071#[derive(PartialEq, Eq, Clone, Copy, Default)]
1076pub struct ExitStatus(c_int);
1077
1078impl fmt::Debug for ExitStatus {
1079 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1080 f.debug_tuple("unix_wait_status").field(&self.0).finish()
1081 }
1082}
1083
1084impl ExitStatus {
1085 pub fn new(status: c_int) -> ExitStatus {
1086 ExitStatus(status)
1087 }
1088
1089 #[cfg(target_os = "linux")]
1090 pub fn from_waitid_siginfo(siginfo: libc::siginfo_t) -> ExitStatus {
1091 let status = unsafe { siginfo.si_status() };
1092
1093 match siginfo.si_code {
1094 libc::CLD_EXITED => ExitStatus((status & 0xff) << 8),
1095 libc::CLD_KILLED => ExitStatus(status),
1096 libc::CLD_DUMPED => ExitStatus(status | 0x80),
1097 libc::CLD_CONTINUED => ExitStatus(0xffff),
1098 libc::CLD_STOPPED | libc::CLD_TRAPPED => ExitStatus(((status & 0xff) << 8) | 0x7f),
1099 _ => unreachable!("waitid() should only return the above codes"),
1100 }
1101 }
1102
1103 fn exited(&self) -> bool {
1104 libc::WIFEXITED(self.0)
1105 }
1106
1107 pub fn exit_ok(&self) -> Result<(), ExitStatusError> {
1108 match NonZero::try_from(self.0) {
1114 Ok(failure) => Err(ExitStatusError(failure)),
1115 Err(_) => Ok(()),
1116 }
1117 }
1118
1119 pub fn code(&self) -> Option<i32> {
1120 self.exited().then(|| libc::WEXITSTATUS(self.0))
1121 }
1122
1123 pub fn signal(&self) -> Option<i32> {
1124 libc::WIFSIGNALED(self.0).then(|| libc::WTERMSIG(self.0))
1125 }
1126
1127 pub fn core_dumped(&self) -> bool {
1128 libc::WIFSIGNALED(self.0) && libc::WCOREDUMP(self.0)
1129 }
1130
1131 pub fn stopped_signal(&self) -> Option<i32> {
1132 libc::WIFSTOPPED(self.0).then(|| libc::WSTOPSIG(self.0))
1133 }
1134
1135 pub fn continued(&self) -> bool {
1136 libc::WIFCONTINUED(self.0)
1137 }
1138
1139 pub fn into_raw(&self) -> c_int {
1140 self.0
1141 }
1142}
1143
1144impl From<c_int> for ExitStatus {
1146 fn from(a: c_int) -> ExitStatus {
1147 ExitStatus(a)
1148 }
1149}
1150
1151fn signal_string(signal: i32) -> &'static str {
1158 match signal {
1159 libc::SIGHUP => " (SIGHUP)",
1160 libc::SIGINT => " (SIGINT)",
1161 libc::SIGQUIT => " (SIGQUIT)",
1162 libc::SIGILL => " (SIGILL)",
1163 libc::SIGTRAP => " (SIGTRAP)",
1164 libc::SIGABRT => " (SIGABRT)",
1165 #[cfg(not(target_os = "l4re"))]
1166 libc::SIGBUS => " (SIGBUS)",
1167 libc::SIGFPE => " (SIGFPE)",
1168 libc::SIGKILL => " (SIGKILL)",
1169 #[cfg(not(target_os = "l4re"))]
1170 libc::SIGUSR1 => " (SIGUSR1)",
1171 libc::SIGSEGV => " (SIGSEGV)",
1172 #[cfg(not(target_os = "l4re"))]
1173 libc::SIGUSR2 => " (SIGUSR2)",
1174 libc::SIGPIPE => " (SIGPIPE)",
1175 libc::SIGALRM => " (SIGALRM)",
1176 libc::SIGTERM => " (SIGTERM)",
1177 #[cfg(not(target_os = "l4re"))]
1178 libc::SIGCHLD => " (SIGCHLD)",
1179 #[cfg(not(target_os = "l4re"))]
1180 libc::SIGCONT => " (SIGCONT)",
1181 #[cfg(not(target_os = "l4re"))]
1182 libc::SIGSTOP => " (SIGSTOP)",
1183 #[cfg(not(target_os = "l4re"))]
1184 libc::SIGTSTP => " (SIGTSTP)",
1185 #[cfg(not(target_os = "l4re"))]
1186 libc::SIGTTIN => " (SIGTTIN)",
1187 #[cfg(not(target_os = "l4re"))]
1188 libc::SIGTTOU => " (SIGTTOU)",
1189 #[cfg(not(target_os = "l4re"))]
1190 libc::SIGURG => " (SIGURG)",
1191 #[cfg(not(target_os = "l4re"))]
1192 libc::SIGXCPU => " (SIGXCPU)",
1193 #[cfg(not(any(target_os = "l4re", target_os = "rtems")))]
1194 libc::SIGXFSZ => " (SIGXFSZ)",
1195 #[cfg(not(any(target_os = "l4re", target_os = "rtems")))]
1196 libc::SIGVTALRM => " (SIGVTALRM)",
1197 #[cfg(not(target_os = "l4re"))]
1198 libc::SIGPROF => " (SIGPROF)",
1199 #[cfg(not(any(target_os = "l4re", target_os = "rtems")))]
1200 libc::SIGWINCH => " (SIGWINCH)",
1201 #[cfg(not(any(target_os = "haiku", target_os = "l4re")))]
1202 libc::SIGIO => " (SIGIO)",
1203 #[cfg(target_os = "haiku")]
1204 libc::SIGPOLL => " (SIGPOLL)",
1205 #[cfg(not(target_os = "l4re"))]
1206 libc::SIGSYS => " (SIGSYS)",
1207 #[cfg(all(
1209 target_os = "linux",
1210 any(
1211 target_arch = "x86_64",
1212 target_arch = "x86",
1213 target_arch = "arm",
1214 target_arch = "aarch64"
1215 )
1216 ))]
1217 libc::SIGSTKFLT => " (SIGSTKFLT)",
1218 #[cfg(any(
1219 target_os = "linux",
1220 target_os = "nto",
1221 target_os = "qnx",
1222 target_os = "cygwin"
1223 ))]
1224 libc::SIGPWR => " (SIGPWR)",
1225 #[cfg(any(
1226 target_os = "freebsd",
1227 target_os = "netbsd",
1228 target_os = "openbsd",
1229 target_os = "dragonfly",
1230 target_os = "nto",
1231 target_os = "qnx",
1232 target_vendor = "apple",
1233 target_os = "cygwin",
1234 ))]
1235 libc::SIGEMT => " (SIGEMT)",
1236 #[cfg(any(
1237 target_os = "freebsd",
1238 target_os = "netbsd",
1239 target_os = "openbsd",
1240 target_os = "dragonfly",
1241 target_vendor = "apple",
1242 ))]
1243 libc::SIGINFO => " (SIGINFO)",
1244 #[cfg(target_os = "hurd")]
1245 libc::SIGLOST => " (SIGLOST)",
1246 #[cfg(target_os = "freebsd")]
1247 libc::SIGTHR => " (SIGTHR)",
1248 #[cfg(target_os = "freebsd")]
1249 libc::SIGLIBRT => " (SIGLIBRT)",
1250 _ => "",
1251 }
1252}
1253
1254impl fmt::Display for ExitStatus {
1255 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1256 if let Some(code) = self.code() {
1257 write!(f, "exit status: {code}")
1258 } else if let Some(signal) = self.signal() {
1259 let signal_string = signal_string(signal);
1260 if self.core_dumped() {
1261 write!(f, "signal: {signal}{signal_string} (core dumped)")
1262 } else {
1263 write!(f, "signal: {signal}{signal_string}")
1264 }
1265 } else if let Some(signal) = self.stopped_signal() {
1266 let signal_string = signal_string(signal);
1267 write!(f, "stopped (not terminated) by signal: {signal}{signal_string}")
1268 } else if self.continued() {
1269 write!(f, "continued (WIFCONTINUED)")
1270 } else {
1271 write!(f, "unrecognised wait status: {} {:#x}", self.0, self.0)
1272 }
1273 }
1274}
1275
1276#[derive(PartialEq, Eq, Clone, Copy)]
1277pub struct ExitStatusError(NonZero<c_int>);
1278
1279impl Into<ExitStatus> for ExitStatusError {
1280 fn into(self) -> ExitStatus {
1281 ExitStatus(self.0.into())
1282 }
1283}
1284
1285impl fmt::Debug for ExitStatusError {
1286 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1287 f.debug_tuple("unix_wait_status").field(&self.0).finish()
1288 }
1289}
1290
1291impl ExitStatusError {
1292 pub fn code(self) -> Option<NonZero<i32>> {
1293 ExitStatus(self.0.into()).code().map(|st| st.try_into().unwrap())
1294 }
1295}
1296
1297#[cfg(target_os = "linux")]
1298mod linux_child_ext {
1299 use crate::io::ErrorKind;
1300 use crate::os::linux::process as os;
1301 use crate::sys::{FromInner, process as imp};
1302 use crate::{io, mem};
1303
1304 #[unstable(feature = "linux_pidfd", issue = "82971")]
1305 impl crate::os::linux::process::ChildExt for crate::process::Child {
1306 fn pidfd(&self) -> io::Result<&os::PidFd> {
1307 self.handle
1308 .pidfd
1309 .as_ref()
1310 .map(|fd| unsafe { mem::transmute::<&imp::PidFd, &os::PidFd>(fd) })
1312 .ok_or_else(|| io::const_error!(ErrorKind::Uncategorized, "no pidfd was created."))
1313 }
1314
1315 fn into_pidfd(mut self) -> Result<os::PidFd, Self> {
1316 self.handle
1317 .pidfd
1318 .take()
1319 .map(<os::PidFd as FromInner<imp::PidFd>>::from_inner)
1320 .ok_or_else(|| self)
1321 }
1322 }
1323}
1324
1325#[cfg(test)]
1326mod tests;
1327
1328#[cfg(all(test, target_os = "linux"))]
1330#[path = "unsupported/wait_status.rs"]
1331mod unsupported_wait_status;