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