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::pin::{Pin, pin};
466 use crate::sys::helpers::COpaque;
467 use crate::sys::{self, cvt_nz, on_broken_pipe_used};
468
469 if self.get_gid().is_some()
470 || self.get_uid().is_some()
471 || (self.env_saw_path() && !self.program_is_path())
472 || !self.get_closures().is_empty()
473 || self.get_groups().is_some()
474 || self.get_chroot().is_some()
475 {
476 return Ok(None);
477 }
478
479 cfg_select! {
480 target_os = "linux" => {
481 use crate::sys::weak::weak;
482
483 weak!(
484 fn pidfd_spawnp(
485 pidfd: *mut libc::c_int,
486 path: *const libc::c_char,
487 file_actions: *const libc::posix_spawn_file_actions_t,
488 attrp: *const libc::posix_spawnattr_t,
489 argv: *const *mut libc::c_char,
490 envp: *const *mut libc::c_char,
491 ) -> libc::c_int;
492 );
493
494 static PIDFD_SUPPORTED: Atomic<u8> = AtomicU8::new(0);
495 const UNKNOWN: u8 = 0;
496 const SPAWN: u8 = 1;
497 const FORK_EXEC: u8 = 2;
499 const NO: u8 = 3;
502
503 if self.get_create_pidfd() {
504 let mut support = PIDFD_SUPPORTED.load(Ordering::Relaxed);
505 if support == FORK_EXEC {
506 return Ok(None);
507 }
508 if support == UNKNOWN {
509 support = NO;
510
511 match PidFd::current_process() {
512 Ok(pidfd) => {
513 support = FORK_EXEC;
515 if pidfd_spawnp.get().is_some()
518 && let Ok(pid) = pidfd.pid()
519 {
520 assert_eq!(pid, crate::process::id(), "sanity check");
521 support = SPAWN;
522 }
523 }
524 Err(e)
525 if matches!(
526 e.raw_os_error(),
527 Some(libc::EMFILE | libc::ENFILE | libc::ENOMEM)
528 ) =>
529 {
530 return Err(e);
533 }
534 _ => {
535 }
537 }
538 PIDFD_SUPPORTED.store(support, Ordering::Relaxed);
539 if support == FORK_EXEC {
540 return Ok(None);
541 }
542 }
543 core::debug_assert_matches!(support, SPAWN | NO);
544 }
545 }
546 _ => {
547 if self.get_create_pidfd() {
548 unreachable!("only implemented on linux")
549 }
550 }
551 }
552
553 #[cfg(all(target_os = "linux", target_env = "gnu"))]
555 {
556 if let Some(version) = sys::pal::conf::glibc_version() {
557 if version < (2, 24) {
558 return Ok(None);
559 }
560 } else {
561 return Ok(None);
562 }
563 }
564
565 #[cfg(any(target_os = "nto", target_os = "qnx"))]
570 unsafe fn retrying_libc_posix_spawnp(
571 pid: *mut pid_t,
572 file: *const c_char,
573 file_actions: *const posix_spawn_file_actions_t,
574 attrp: *const posix_spawnattr_t,
575 argv: *const *mut c_char,
576 envp: *const *mut c_char,
577 ) -> io::Result<i32> {
578 let mut delay = MIN_FORKSPAWN_SLEEP;
579 loop {
580 match libc::posix_spawnp(pid, file, file_actions, attrp, argv, envp) {
581 libc::EBADF => {
582 if delay < get_clock_resolution() {
583 thread::yield_now();
586 } else if delay < MAX_FORKSPAWN_SLEEP {
587 thread::sleep(delay);
588 } else {
589 return Err(io::const_error!(
590 ErrorKind::WouldBlock,
591 "posix_spawnp returned EBADF too often",
592 ));
593 }
594 delay *= 2;
595 continue;
596 }
597 r => {
598 return Ok(r);
599 }
600 }
601 }
602 }
603
604 type PosixSpawnAddChdirFn = unsafe extern "C" fn(
605 *mut libc::posix_spawn_file_actions_t,
606 *const libc::c_char,
607 ) -> libc::c_int;
608
609 #[cfg(not(any(all(target_os = "linux", target_env = "musl"), target_os = "cygwin")))]
616 fn get_posix_spawn_addchdir() -> Option<PosixSpawnAddChdirFn> {
617 use crate::sys::weak::weak;
618
619 weak!(
624 fn posix_spawn_file_actions_addchdir_np(
625 file_actions: *mut libc::posix_spawn_file_actions_t,
626 path: *const libc::c_char,
627 ) -> libc::c_int;
628 );
629
630 weak!(
631 fn posix_spawn_file_actions_addchdir(
632 file_actions: *mut libc::posix_spawn_file_actions_t,
633 path: *const libc::c_char,
634 ) -> libc::c_int;
635 );
636
637 posix_spawn_file_actions_addchdir_np
638 .get()
639 .or_else(|| posix_spawn_file_actions_addchdir.get())
640 }
641
642 #[cfg(any(all(target_os = "linux", target_env = "musl"), target_os = "cygwin"))]
652 fn get_posix_spawn_addchdir() -> Option<PosixSpawnAddChdirFn> {
653 Some(libc::posix_spawn_file_actions_addchdir_np)
655 }
656
657 let addchdir = match self.get_cwd() {
658 Some(cwd) => {
659 if cfg!(target_vendor = "apple") {
660 if self.get_program_kind() == ProgramKind::Relative {
666 return Ok(None);
667 }
668 }
669 match get_posix_spawn_addchdir() {
673 Some(f) => Some((f, cwd)),
674 None => return Ok(None),
675 }
676 }
677 None => None,
678 };
679
680 let pgroup = self.get_pgroup();
681
682 struct PosixSpawnFileActions<'a>(Pin<&'a COpaque<libc::posix_spawn_file_actions_t>>);
683
684 impl Drop for PosixSpawnFileActions<'_> {
685 fn drop(&mut self) {
686 unsafe {
687 libc::posix_spawn_file_actions_destroy(self.0.get());
688 }
689 }
690 }
691
692 struct PosixSpawnattr<'a>(Pin<&'a COpaque<libc::posix_spawnattr_t>>);
693
694 impl Drop for PosixSpawnattr<'_> {
695 fn drop(&mut self) {
696 unsafe {
697 libc::posix_spawnattr_destroy(self.0.get());
698 }
699 }
700 }
701
702 unsafe {
703 let attrs = pin!(COpaque::uninit());
704 let attrs = attrs.into_ref();
706 cvt_nz(libc::posix_spawnattr_init(attrs.get()))?;
707 let attrs = PosixSpawnattr(attrs);
708
709 let mut flags = 0;
710
711 let file_actions = pin!(COpaque::uninit());
712 let file_actions = file_actions.into_ref();
713 cvt_nz(libc::posix_spawn_file_actions_init(file_actions.get()))?;
714 let file_actions = PosixSpawnFileActions(file_actions);
715
716 if let Some(fd) = stdio.stdin.fd() {
717 cvt_nz(libc::posix_spawn_file_actions_adddup2(
718 file_actions.0.get(),
719 fd,
720 libc::STDIN_FILENO,
721 ))?;
722 }
723 if let Some(fd) = stdio.stdout.fd() {
724 cvt_nz(libc::posix_spawn_file_actions_adddup2(
725 file_actions.0.get(),
726 fd,
727 libc::STDOUT_FILENO,
728 ))?;
729 }
730 if let Some(fd) = stdio.stderr.fd() {
731 cvt_nz(libc::posix_spawn_file_actions_adddup2(
732 file_actions.0.get(),
733 fd,
734 libc::STDERR_FILENO,
735 ))?;
736 }
737 if let Some((f, cwd)) = addchdir {
738 cvt_nz(f(file_actions.0.get(), cwd.as_ptr()))?;
739 }
740
741 if let Some(pgroup) = pgroup {
742 flags |= libc::POSIX_SPAWN_SETPGROUP;
743 cvt_nz(libc::posix_spawnattr_setpgroup(attrs.0.get(), pgroup))?;
744 }
745
746 if !on_broken_pipe_used() {
754 let mut default_set = MaybeUninit::<libc::sigset_t>::uninit();
755 cvt(sigemptyset(default_set.as_mut_ptr()))?;
756 cvt(sigaddset(default_set.as_mut_ptr(), libc::SIGPIPE))?;
757 #[cfg(target_os = "hurd")]
758 {
759 cvt(sigaddset(default_set.as_mut_ptr(), libc::SIGLOST))?;
760 }
761 cvt_nz(libc::posix_spawnattr_setsigdefault(attrs.0.get(), default_set.as_ptr()))?;
762 flags |= libc::POSIX_SPAWN_SETSIGDEF;
763 }
764
765 if self.get_setsid() {
766 cfg_select! {
767 all(target_os = "linux", target_env = "gnu") => {
768 flags |= libc::POSIX_SPAWN_SETSID as i32;
769 }
770 _ => {
771 return Ok(None);
772 }
773 }
774 }
775
776 cvt_nz(libc::posix_spawnattr_setflags(attrs.0.get(), flags as _))?;
777
778 let _env_lock = sys::env::env_read_lock();
780 let envp = envp.map(|c| c.as_ptr()).unwrap_or_else(|| *sys::env::environ() as *const _);
781
782 #[cfg(not(any(target_os = "nto", target_os = "qnx")))]
783 let spawn_fn = libc::posix_spawnp;
784 #[cfg(any(target_os = "nto", target_os = "qnx"))]
785 let spawn_fn = retrying_libc_posix_spawnp;
786
787 #[cfg(target_os = "linux")]
788 if self.get_create_pidfd() && PIDFD_SUPPORTED.load(Ordering::Relaxed) == SPAWN {
789 let mut pidfd: libc::c_int = -1;
790 let spawn_res = pidfd_spawnp.get().unwrap()(
791 &mut pidfd,
792 self.get_program_cstr().as_ptr(),
793 file_actions.0.get(),
794 attrs.0.get(),
795 self.get_argv().as_ptr() as *const _,
796 envp as *const _,
797 );
798
799 let spawn_res = cvt_nz(spawn_res);
800 if let Err(ref e) = spawn_res
801 && e.raw_os_error() == Some(libc::ENOSYS)
802 {
803 PIDFD_SUPPORTED.store(FORK_EXEC, Ordering::Relaxed);
804 return Ok(None);
805 }
806 spawn_res?;
807
808 use crate::os::fd::{FromRawFd, IntoRawFd};
809
810 let pidfd = PidFd::from_raw_fd(pidfd);
811 let pid = match pidfd.pid() {
812 Ok(pid) => pid,
813 Err(e) => {
814 return Err(Error::new(
820 e.kind(),
821 "pidfd_spawnp succeeded but the child's PID could not be obtained",
822 ));
823 }
824 };
825
826 return Ok(Some(Process::new(pid as i32, pidfd.into_raw_fd())));
827 }
828
829 let mut p = Process::new(0, -1);
831
832 let spawn_res = spawn_fn(
833 &mut p.pid,
834 self.get_program_cstr().as_ptr(),
835 file_actions.0.get(),
836 attrs.0.get(),
837 self.get_argv().as_ptr() as *const _,
838 envp as *const _,
839 );
840
841 #[cfg(any(target_os = "nto", target_os = "qnx"))]
842 let spawn_res = spawn_res?;
843
844 cvt_nz(spawn_res)?;
845 Ok(Some(p))
846 }
847 }
848
849 #[cfg(target_os = "linux")]
850 fn send_pidfd(&self, sock: &crate::sys::net::Socket) {
851 use libc::{CMSG_DATA, CMSG_FIRSTHDR, CMSG_LEN, CMSG_SPACE, SCM_RIGHTS, SOL_SOCKET};
852
853 use crate::io::IoSlice;
854 use crate::os::fd::RawFd;
855 use crate::sys::cvt_r;
856
857 unsafe {
858 let child_pid = libc::getpid();
859 let pidfd = libc::syscall(libc::SYS_pidfd_open, child_pid, 0);
861
862 let fds: [c_int; 1] = [pidfd as RawFd];
863
864 const SCM_MSG_LEN: usize = size_of::<[c_int; 1]>();
865
866 #[repr(C)]
867 union Cmsg {
868 buf: [u8; unsafe { CMSG_SPACE(SCM_MSG_LEN as u32) as usize }],
869 _align: libc::cmsghdr,
870 }
871
872 let mut cmsg: Cmsg = mem::zeroed();
873
874 let mut iov = [IoSlice::new(b"")];
876 let mut msg: libc::msghdr = mem::zeroed();
877
878 msg.msg_iov = (&raw mut iov) as *mut _;
879 msg.msg_iovlen = 1;
880
881 if pidfd >= 0 {
883 msg.msg_controllen = size_of_val(&cmsg.buf) as _;
884 msg.msg_control = (&raw mut cmsg.buf) as *mut _;
885
886 let hdr = CMSG_FIRSTHDR((&raw mut msg) as *mut _);
887 (*hdr).cmsg_level = SOL_SOCKET;
888 (*hdr).cmsg_type = SCM_RIGHTS;
889 (*hdr).cmsg_len = CMSG_LEN(SCM_MSG_LEN as _) as _;
890 let data = CMSG_DATA(hdr);
891 crate::ptr::copy_nonoverlapping(
892 fds.as_ptr().cast::<u8>(),
893 data as *mut _,
894 SCM_MSG_LEN,
895 );
896 }
897
898 match cvt_r(|| libc::sendmsg(sock.as_raw(), &msg, libc::MSG_EOR)) {
901 Ok(0) => {}
902 other => rtabort!("failed to communicate with parent process. {:?}", other),
903 }
904 }
905 }
906
907 #[cfg(target_os = "linux")]
908 fn recv_pidfd(&self, sock: &crate::sys::net::Socket) -> pid_t {
909 use libc::{CMSG_DATA, CMSG_FIRSTHDR, CMSG_LEN, CMSG_SPACE, SCM_RIGHTS, SOL_SOCKET};
910
911 use crate::io::IoSliceMut;
912 use crate::sys::cvt_r;
913
914 unsafe {
915 const SCM_MSG_LEN: usize = size_of::<[c_int; 1]>();
916
917 #[repr(C)]
918 union Cmsg {
919 _buf: [u8; unsafe { CMSG_SPACE(SCM_MSG_LEN as u32) as usize }],
920 _align: libc::cmsghdr,
921 }
922 let mut cmsg: Cmsg = mem::zeroed();
923 let mut iov = [IoSliceMut::new(&mut [])];
925
926 let mut msg: libc::msghdr = mem::zeroed();
927
928 msg.msg_iov = (&raw mut iov) as *mut _;
929 msg.msg_iovlen = 1;
930 msg.msg_controllen = size_of::<Cmsg>() as _;
931 msg.msg_control = (&raw mut cmsg) as *mut _;
932
933 if cvt_r(|| libc::recvmsg(sock.as_raw(), &mut msg, libc::MSG_CMSG_CLOEXEC)).is_err() {
934 return -1;
935 }
936
937 let hdr = CMSG_FIRSTHDR((&raw mut msg) as *mut _);
938 if hdr.is_null()
939 || (*hdr).cmsg_level != SOL_SOCKET
940 || (*hdr).cmsg_type != SCM_RIGHTS
941 || (*hdr).cmsg_len != CMSG_LEN(SCM_MSG_LEN as _) as _
942 {
943 return -1;
944 }
945 let data = CMSG_DATA(hdr);
946
947 let mut fds = [-1 as c_int];
948
949 crate::ptr::copy_nonoverlapping(
950 data as *const _,
951 fds.as_mut_ptr().cast::<u8>(),
952 SCM_MSG_LEN,
953 );
954
955 fds[0]
956 }
957 }
958}
959
960pub struct Process {
966 pid: pid_t,
967 status: Option<ExitStatus>,
968 #[cfg(target_os = "linux")]
973 pidfd: Option<PidFd>,
974}
975
976impl Process {
977 #[cfg(target_os = "linux")]
978 unsafe fn new(pid: pid_t, pidfd: pid_t) -> Self {
985 use crate::os::unix::io::FromRawFd;
986 use crate::sys::FromInner;
987 let pidfd = (pidfd >= 0).then(|| PidFd::from_inner(sys::fd::FileDesc::from_raw_fd(pidfd)));
989 Process { pid, status: None, pidfd }
990 }
991
992 #[cfg(not(target_os = "linux"))]
993 unsafe fn new(pid: pid_t, _pidfd: pid_t) -> Self {
994 Process { pid, status: None }
995 }
996
997 pub fn id(&self) -> u32 {
998 self.pid as u32
999 }
1000
1001 pub fn kill(&self) -> io::Result<()> {
1002 self.send_signal(libc::SIGKILL)
1003 }
1004
1005 pub(crate) fn send_signal(&self, signal: i32) -> io::Result<()> {
1006 if self.status.is_some() {
1010 return Ok(());
1011 }
1012 #[cfg(target_os = "linux")]
1013 if let Some(pid_fd) = self.pidfd.as_ref() {
1014 return pid_fd.send_signal(signal);
1016 }
1017 cvt(unsafe { libc::kill(self.pid, signal) }).map(drop)
1018 }
1019
1020 pub(crate) fn send_process_group_signal(&self, signal: i32) -> io::Result<()> {
1021 if self.status.is_some() {
1023 return Ok(());
1024 }
1025 #[cfg(target_os = "linux")]
1026 if let Some(pid_fd) = self.pidfd.as_ref() {
1027 return pid_fd.send_process_group_signal(signal);
1029 }
1030 cvt(unsafe { libc::killpg(self.pid, signal) }).map(drop)
1031 }
1032
1033 pub fn wait(&mut self) -> io::Result<ExitStatus> {
1034 use crate::sys::cvt_r;
1035 if let Some(status) = self.status {
1036 return Ok(status);
1037 }
1038 #[cfg(target_os = "linux")]
1039 if let Some(pid_fd) = self.pidfd.as_ref() {
1040 let status = pid_fd.wait()?;
1041 self.status = Some(status);
1042 return Ok(status);
1043 }
1044 let mut status = 0 as c_int;
1045 cvt_r(|| unsafe { libc::waitpid(self.pid, &mut status, 0) })?;
1046 self.status = Some(ExitStatus::new(status));
1047 Ok(ExitStatus::new(status))
1048 }
1049
1050 pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
1051 if let Some(status) = self.status {
1052 return Ok(Some(status));
1053 }
1054 #[cfg(target_os = "linux")]
1055 if let Some(pid_fd) = self.pidfd.as_ref() {
1056 let status = pid_fd.try_wait()?;
1057 if let Some(status) = status {
1058 self.status = Some(status)
1059 }
1060 return Ok(status);
1061 }
1062 let mut status = 0 as c_int;
1063 let pid = cvt(unsafe { libc::waitpid(self.pid, &mut status, libc::WNOHANG) })?;
1064 if pid == 0 {
1065 Ok(None)
1066 } else {
1067 self.status = Some(ExitStatus::new(status));
1068 Ok(Some(ExitStatus::new(status)))
1069 }
1070 }
1071}
1072
1073#[derive(PartialEq, Eq, Clone, Copy, Default)]
1078pub struct ExitStatus(c_int);
1079
1080impl fmt::Debug for ExitStatus {
1081 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1082 f.debug_tuple("unix_wait_status").field(&self.0).finish()
1083 }
1084}
1085
1086impl ExitStatus {
1087 pub fn new(status: c_int) -> ExitStatus {
1088 ExitStatus(status)
1089 }
1090
1091 #[cfg(target_os = "linux")]
1092 pub fn from_waitid_siginfo(siginfo: libc::siginfo_t) -> ExitStatus {
1093 let status = unsafe { siginfo.si_status() };
1094
1095 match siginfo.si_code {
1096 libc::CLD_EXITED => ExitStatus((status & 0xff) << 8),
1097 libc::CLD_KILLED => ExitStatus(status),
1098 libc::CLD_DUMPED => ExitStatus(status | 0x80),
1099 libc::CLD_CONTINUED => ExitStatus(0xffff),
1100 libc::CLD_STOPPED | libc::CLD_TRAPPED => ExitStatus(((status & 0xff) << 8) | 0x7f),
1101 _ => unreachable!("waitid() should only return the above codes"),
1102 }
1103 }
1104
1105 fn exited(&self) -> bool {
1106 libc::WIFEXITED(self.0)
1107 }
1108
1109 pub fn exit_ok(&self) -> Result<(), ExitStatusError> {
1110 match NonZero::try_from(self.0) {
1116 Ok(failure) => Err(ExitStatusError(failure)),
1117 Err(_) => Ok(()),
1118 }
1119 }
1120
1121 pub fn code(&self) -> Option<i32> {
1122 self.exited().then(|| libc::WEXITSTATUS(self.0))
1123 }
1124
1125 pub fn signal(&self) -> Option<i32> {
1126 libc::WIFSIGNALED(self.0).then(|| libc::WTERMSIG(self.0))
1127 }
1128
1129 pub fn core_dumped(&self) -> bool {
1130 libc::WIFSIGNALED(self.0) && libc::WCOREDUMP(self.0)
1131 }
1132
1133 pub fn stopped_signal(&self) -> Option<i32> {
1134 libc::WIFSTOPPED(self.0).then(|| libc::WSTOPSIG(self.0))
1135 }
1136
1137 pub fn continued(&self) -> bool {
1138 libc::WIFCONTINUED(self.0)
1139 }
1140
1141 pub fn into_raw(&self) -> c_int {
1142 self.0
1143 }
1144}
1145
1146impl From<c_int> for ExitStatus {
1148 fn from(a: c_int) -> ExitStatus {
1149 ExitStatus(a)
1150 }
1151}
1152
1153fn signal_string(signal: i32) -> &'static str {
1160 match signal {
1161 libc::SIGHUP => " (SIGHUP)",
1162 libc::SIGINT => " (SIGINT)",
1163 libc::SIGQUIT => " (SIGQUIT)",
1164 libc::SIGILL => " (SIGILL)",
1165 libc::SIGTRAP => " (SIGTRAP)",
1166 libc::SIGABRT => " (SIGABRT)",
1167 #[cfg(not(target_os = "l4re"))]
1168 libc::SIGBUS => " (SIGBUS)",
1169 libc::SIGFPE => " (SIGFPE)",
1170 libc::SIGKILL => " (SIGKILL)",
1171 #[cfg(not(target_os = "l4re"))]
1172 libc::SIGUSR1 => " (SIGUSR1)",
1173 libc::SIGSEGV => " (SIGSEGV)",
1174 #[cfg(not(target_os = "l4re"))]
1175 libc::SIGUSR2 => " (SIGUSR2)",
1176 libc::SIGPIPE => " (SIGPIPE)",
1177 libc::SIGALRM => " (SIGALRM)",
1178 libc::SIGTERM => " (SIGTERM)",
1179 #[cfg(not(target_os = "l4re"))]
1180 libc::SIGCHLD => " (SIGCHLD)",
1181 #[cfg(not(target_os = "l4re"))]
1182 libc::SIGCONT => " (SIGCONT)",
1183 #[cfg(not(target_os = "l4re"))]
1184 libc::SIGSTOP => " (SIGSTOP)",
1185 #[cfg(not(target_os = "l4re"))]
1186 libc::SIGTSTP => " (SIGTSTP)",
1187 #[cfg(not(target_os = "l4re"))]
1188 libc::SIGTTIN => " (SIGTTIN)",
1189 #[cfg(not(target_os = "l4re"))]
1190 libc::SIGTTOU => " (SIGTTOU)",
1191 #[cfg(not(target_os = "l4re"))]
1192 libc::SIGURG => " (SIGURG)",
1193 #[cfg(not(target_os = "l4re"))]
1194 libc::SIGXCPU => " (SIGXCPU)",
1195 #[cfg(not(any(target_os = "l4re", target_os = "rtems")))]
1196 libc::SIGXFSZ => " (SIGXFSZ)",
1197 #[cfg(not(any(target_os = "l4re", target_os = "rtems")))]
1198 libc::SIGVTALRM => " (SIGVTALRM)",
1199 #[cfg(not(target_os = "l4re"))]
1200 libc::SIGPROF => " (SIGPROF)",
1201 #[cfg(not(any(target_os = "l4re", target_os = "rtems")))]
1202 libc::SIGWINCH => " (SIGWINCH)",
1203 #[cfg(not(any(target_os = "haiku", target_os = "l4re")))]
1204 libc::SIGIO => " (SIGIO)",
1205 #[cfg(target_os = "haiku")]
1206 libc::SIGPOLL => " (SIGPOLL)",
1207 #[cfg(not(target_os = "l4re"))]
1208 libc::SIGSYS => " (SIGSYS)",
1209 #[cfg(all(
1211 target_os = "linux",
1212 any(
1213 target_arch = "x86_64",
1214 target_arch = "x86",
1215 target_arch = "arm",
1216 target_arch = "aarch64"
1217 )
1218 ))]
1219 libc::SIGSTKFLT => " (SIGSTKFLT)",
1220 #[cfg(any(
1221 target_os = "linux",
1222 target_os = "nto",
1223 target_os = "qnx",
1224 target_os = "cygwin"
1225 ))]
1226 libc::SIGPWR => " (SIGPWR)",
1227 #[cfg(any(
1228 target_os = "freebsd",
1229 target_os = "netbsd",
1230 target_os = "openbsd",
1231 target_os = "dragonfly",
1232 target_os = "nto",
1233 target_os = "qnx",
1234 target_vendor = "apple",
1235 target_os = "cygwin",
1236 ))]
1237 libc::SIGEMT => " (SIGEMT)",
1238 #[cfg(any(
1239 target_os = "freebsd",
1240 target_os = "netbsd",
1241 target_os = "openbsd",
1242 target_os = "dragonfly",
1243 target_vendor = "apple",
1244 ))]
1245 libc::SIGINFO => " (SIGINFO)",
1246 #[cfg(target_os = "hurd")]
1247 libc::SIGLOST => " (SIGLOST)",
1248 #[cfg(target_os = "freebsd")]
1249 libc::SIGTHR => " (SIGTHR)",
1250 #[cfg(target_os = "freebsd")]
1251 libc::SIGLIBRT => " (SIGLIBRT)",
1252 _ => "",
1253 }
1254}
1255
1256impl fmt::Display for ExitStatus {
1257 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1258 if let Some(code) = self.code() {
1259 write!(f, "exit status: {code}")
1260 } else if let Some(signal) = self.signal() {
1261 let signal_string = signal_string(signal);
1262 if self.core_dumped() {
1263 write!(f, "signal: {signal}{signal_string} (core dumped)")
1264 } else {
1265 write!(f, "signal: {signal}{signal_string}")
1266 }
1267 } else if let Some(signal) = self.stopped_signal() {
1268 let signal_string = signal_string(signal);
1269 write!(f, "stopped (not terminated) by signal: {signal}{signal_string}")
1270 } else if self.continued() {
1271 write!(f, "continued (WIFCONTINUED)")
1272 } else {
1273 write!(f, "unrecognised wait status: {} {:#x}", self.0, self.0)
1274 }
1275 }
1276}
1277
1278#[derive(PartialEq, Eq, Clone, Copy)]
1279pub struct ExitStatusError(NonZero<c_int>);
1280
1281impl Into<ExitStatus> for ExitStatusError {
1282 fn into(self) -> ExitStatus {
1283 ExitStatus(self.0.into())
1284 }
1285}
1286
1287impl fmt::Debug for ExitStatusError {
1288 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1289 f.debug_tuple("unix_wait_status").field(&self.0).finish()
1290 }
1291}
1292
1293impl ExitStatusError {
1294 pub fn code(self) -> Option<NonZero<i32>> {
1295 ExitStatus(self.0.into()).code().map(|st| st.try_into().unwrap())
1296 }
1297}
1298
1299#[cfg(target_os = "linux")]
1300mod linux_child_ext {
1301 use crate::io::ErrorKind;
1302 use crate::os::linux::process as os;
1303 use crate::sys::{FromInner, process as imp};
1304 use crate::{io, mem};
1305
1306 #[unstable(feature = "linux_pidfd", issue = "82971")]
1307 impl crate::os::linux::process::ChildExt for crate::process::Child {
1308 fn pidfd(&self) -> io::Result<&os::PidFd> {
1309 self.handle
1310 .pidfd
1311 .as_ref()
1312 .map(|fd| unsafe { mem::transmute::<&imp::PidFd, &os::PidFd>(fd) })
1314 .ok_or_else(|| io::const_error!(ErrorKind::Uncategorized, "no pidfd was created."))
1315 }
1316
1317 fn into_pidfd(mut self) -> Result<os::PidFd, Self> {
1318 self.handle
1319 .pidfd
1320 .take()
1321 .map(<os::PidFd as FromInner<imp::PidFd>>::from_inner)
1322 .ok_or_else(|| self)
1323 }
1324 }
1325}
1326
1327#[cfg(test)]
1328mod tests;
1329
1330#[cfg(all(test, target_os = "linux"))]
1332#[path = "unsupported/wait_status.rs"]
1333mod unsupported_wait_status;