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::pal::linux::pidfd::PidFd;
20use crate::{fmt, mem, sys};
21
22cfg_select! {
23 target_os = "nto" => {
24 use crate::thread;
25 use libc::{c_char, posix_spawn_file_actions_t, posix_spawnattr_t};
26 use crate::time::Duration;
27 use crate::sync::LazyLock;
28 fn get_clock_resolution() -> Duration {
31 static MIN_DELAY: LazyLock<Duration, fn() -> Duration> = LazyLock::new(|| {
32 let mut mindelay = libc::timespec { tv_sec: 0, tv_nsec: 0 };
33 if unsafe { libc::clock_getres(libc::CLOCK_MONOTONIC, &mut mindelay) } == 0
34 {
35 Duration::from_nanos(mindelay.tv_nsec as u64)
36 } else {
37 Duration::from_millis(1)
38 }
39 });
40 *MIN_DELAY
41 }
42 const MIN_FORKSPAWN_SLEEP: Duration = Duration::from_nanos(1);
44 const MAX_FORKSPAWN_SLEEP: Duration = Duration::from_millis(1000);
46 }
47 _ => {}
48}
49
50impl Command {
55 pub fn spawn(
56 &mut self,
57 default: Stdio,
58 needs_stdin: bool,
59 ) -> io::Result<(Process, StdioPipes)> {
60 const CLOEXEC_MSG_FOOTER: [u8; 4] = *b"NOEX";
61
62 let envp = self.capture_env();
63
64 if self.saw_nul() {
65 return Err(io::const_error!(
66 ErrorKind::InvalidInput,
67 "nul byte found in provided data",
68 ));
69 }
70
71 let (ours, theirs) = self.setup_io(default, needs_stdin)?;
72
73 if let Some(ret) = self.posix_spawn(&theirs, envp.as_ref())? {
74 return Ok((ret, ours));
75 }
76
77 #[cfg(target_os = "linux")]
78 let (input, output) = sys::net::Socket::new_pair(libc::AF_UNIX, libc::SOCK_SEQPACKET)?;
79
80 #[cfg(not(target_os = "linux"))]
81 let (input, output) = sys::pipe::pipe()?;
82
83 let env_lock = sys::env::env_read_lock();
94 let pid = unsafe { self.do_fork()? };
95
96 if pid == 0 {
97 crate::panic::always_abort();
98 mem::forget(env_lock); drop(input);
100 #[cfg(target_os = "linux")]
101 if self.get_create_pidfd() {
102 self.send_pidfd(&output);
103 }
104 let Err(err) = unsafe { self.do_exec(theirs, envp.as_ref()) };
105 let errno = err.raw_os_error().unwrap_or(libc::EINVAL) as u32;
106 let errno = errno.to_be_bytes();
107 let bytes = [
108 errno[0],
109 errno[1],
110 errno[2],
111 errno[3],
112 CLOEXEC_MSG_FOOTER[0],
113 CLOEXEC_MSG_FOOTER[1],
114 CLOEXEC_MSG_FOOTER[2],
115 CLOEXEC_MSG_FOOTER[3],
116 ];
117 rtassert!(output.write(&bytes).is_ok());
121 unsafe { libc::_exit(1) }
122 }
123
124 drop(env_lock);
125 drop(output);
126
127 #[cfg(target_os = "linux")]
128 let pidfd = if self.get_create_pidfd() { self.recv_pidfd(&input) } else { -1 };
129
130 #[cfg(not(target_os = "linux"))]
131 let pidfd = -1;
132
133 let mut p = unsafe { Process::new(pid, pidfd) };
135 let mut bytes = [0; 8];
136
137 loop {
139 match input.read(&mut bytes) {
140 Ok(0) => return Ok((p, ours)),
141 Ok(8) => {
142 let (errno, footer) = bytes.split_at(4);
143 assert_eq!(
144 CLOEXEC_MSG_FOOTER, footer,
145 "Validation on the CLOEXEC pipe failed: {:?}",
146 bytes
147 );
148 let errno = i32::from_be_bytes(errno.try_into().unwrap());
149 assert!(p.wait().is_ok(), "wait() should either return Ok or panic");
150 return Err(Error::from_raw_os_error(errno));
151 }
152 Err(ref e) if e.is_interrupted() => {}
153 Err(e) => {
154 assert!(p.wait().is_ok(), "wait() should either return Ok or panic");
155 panic!("the CLOEXEC pipe failed: {e:?}")
156 }
157 Ok(..) => {
158 assert!(p.wait().is_ok(), "wait() should either return Ok or panic");
161 panic!("short read on the CLOEXEC pipe")
162 }
163 }
164 }
165 }
166
167 #[cfg(any(target_os = "tvos", target_os = "watchos"))]
174 const ERR_APPLE_TV_WATCH_NO_FORK_EXEC: Error = io::const_error!(
175 ErrorKind::Unsupported,
176 "`fork`+`exec`-based process spawning is not supported on this target",
177 );
178
179 #[cfg(any(target_os = "tvos", target_os = "watchos"))]
180 unsafe fn do_fork(&mut self) -> Result<pid_t, io::Error> {
181 return Err(Self::ERR_APPLE_TV_WATCH_NO_FORK_EXEC);
182 }
183
184 #[cfg(not(any(target_os = "watchos", target_os = "tvos", target_os = "nto")))]
187 unsafe fn do_fork(&mut self) -> Result<pid_t, io::Error> {
188 cvt(libc::fork())
189 }
190
191 #[cfg(target_os = "nto")]
196 unsafe fn do_fork(&mut self) -> Result<pid_t, io::Error> {
197 use crate::sys::os::errno;
198
199 let mut delay = MIN_FORKSPAWN_SLEEP;
200
201 loop {
202 let r = libc::fork();
203 if r == -1 as libc::pid_t && errno() as libc::c_int == libc::EBADF {
204 if delay < get_clock_resolution() {
205 thread::yield_now();
208 } else if delay < MAX_FORKSPAWN_SLEEP {
209 thread::sleep(delay);
210 } else {
211 return Err(io::const_error!(
212 ErrorKind::WouldBlock,
213 "forking returned EBADF too often",
214 ));
215 }
216 delay *= 2;
217 continue;
218 } else {
219 return cvt(r);
220 }
221 }
222 }
223
224 pub fn exec(&mut self, default: Stdio) -> io::Error {
225 let envp = self.capture_env();
226
227 if self.saw_nul() {
228 return io::const_error!(ErrorKind::InvalidInput, "nul byte found in provided data");
229 }
230
231 match self.setup_io(default, true) {
232 Ok((_, theirs)) => {
233 unsafe {
234 let _lock = sys::env::env_read_lock();
238
239 let Err(e) = self.do_exec(theirs, envp.as_ref());
240 e
241 }
242 }
243 Err(e) => e,
244 }
245 }
246
247 #[cfg(not(any(target_os = "tvos", target_os = "watchos")))]
278 unsafe fn do_exec(
279 &mut self,
280 stdio: ChildPipes,
281 maybe_envp: Option<&CStringArray>,
282 ) -> Result<!, io::Error> {
283 use crate::sys::{self, cvt_r};
284
285 if let Some(fd) = stdio.stdin.fd() {
286 cvt_r(|| libc::dup2(fd, libc::STDIN_FILENO))?;
287 }
288 if let Some(fd) = stdio.stdout.fd() {
289 cvt_r(|| libc::dup2(fd, libc::STDOUT_FILENO))?;
290 }
291 if let Some(fd) = stdio.stderr.fd() {
292 cvt_r(|| libc::dup2(fd, libc::STDERR_FILENO))?;
293 }
294
295 #[cfg(not(target_os = "l4re"))]
296 {
297 if let Some(_g) = self.get_groups() {
298 #[cfg(not(target_os = "redox"))]
300 cvt(libc::setgroups(_g.len().try_into().unwrap(), _g.as_ptr()))?;
301 }
302 if let Some(u) = self.get_gid() {
303 cvt(libc::setgid(u as gid_t))?;
304 }
305 if let Some(u) = self.get_uid() {
306 #[cfg(not(target_os = "redox"))]
314 if self.get_groups().is_none() {
315 let res = cvt(libc::setgroups(0, crate::ptr::null()));
316 if let Err(e) = res {
317 if e.raw_os_error() != Some(libc::EPERM) {
321 return Err(e.into());
322 }
323 }
324 }
325 cvt(libc::setuid(u as uid_t))?;
326 }
327 }
328 if let Some(chroot) = self.get_chroot() {
329 #[cfg(not(target_os = "fuchsia"))]
330 cvt(libc::chroot(chroot.as_ptr()))?;
331 #[cfg(target_os = "fuchsia")]
332 return Err(io::const_error!(
333 io::ErrorKind::Unsupported,
334 "chroot not supported by fuchsia"
335 ));
336 }
337 if let Some(cwd) = self.get_cwd() {
338 cvt(libc::chdir(cwd.as_ptr()))?;
339 }
340
341 if let Some(pgroup) = self.get_pgroup() {
342 cvt(libc::setpgid(0, pgroup))?;
343 }
344
345 if self.get_setsid() {
346 cvt(libc::setsid())?;
347 }
348
349 #[cfg(not(target_os = "emscripten"))]
351 {
352 if !crate::sys::pal::on_broken_pipe_flag_used() {
360 #[cfg(target_os = "android")] {
362 let mut action: libc::sigaction = mem::zeroed();
363 action.sa_sigaction = libc::SIG_DFL;
364 cvt(libc::sigaction(libc::SIGPIPE, &action, crate::ptr::null_mut()))?;
365 }
366 #[cfg(not(target_os = "android"))]
367 {
368 let ret = sys::signal(libc::SIGPIPE, libc::SIG_DFL);
369 if ret == libc::SIG_ERR {
370 return Err(io::Error::last_os_error());
371 }
372 }
373 #[cfg(target_os = "hurd")]
374 {
375 let ret = sys::signal(libc::SIGLOST, libc::SIG_DFL);
376 if ret == libc::SIG_ERR {
377 return Err(io::Error::last_os_error());
378 }
379 }
380 }
381 }
382
383 for callback in self.get_closures().iter_mut() {
384 callback()?;
385 }
386
387 let mut _reset = None;
393 if let Some(envp) = maybe_envp {
394 struct Reset(*const *const libc::c_char);
395
396 impl Drop for Reset {
397 fn drop(&mut self) {
398 unsafe {
399 *sys::env::environ() = self.0;
400 }
401 }
402 }
403
404 _reset = Some(Reset(*sys::env::environ()));
405 *sys::env::environ() = envp.as_ptr();
406 }
407
408 libc::execvp(self.get_program_cstr().as_ptr(), self.get_argv().as_ptr());
409 Err(io::Error::last_os_error())
410 }
411
412 #[cfg(any(target_os = "tvos", target_os = "watchos"))]
413 unsafe fn do_exec(
414 &mut self,
415 _stdio: ChildPipes,
416 _maybe_envp: Option<&CStringArray>,
417 ) -> Result<!, io::Error> {
418 return Err(Self::ERR_APPLE_TV_WATCH_NO_FORK_EXEC);
419 }
420
421 #[cfg(not(any(
422 target_os = "freebsd",
423 target_os = "illumos",
424 all(target_os = "linux", target_env = "gnu"),
425 all(target_os = "linux", target_env = "musl"),
426 target_os = "nto",
427 target_vendor = "apple",
428 target_os = "cygwin",
429 )))]
430 fn posix_spawn(
431 &mut self,
432 _: &ChildPipes,
433 _: Option<&CStringArray>,
434 ) -> io::Result<Option<Process>> {
435 Ok(None)
436 }
437
438 #[cfg(any(
441 target_os = "freebsd",
442 target_os = "illumos",
443 all(target_os = "linux", target_env = "gnu"),
444 all(target_os = "linux", target_env = "musl"),
445 target_os = "nto",
446 target_vendor = "apple",
447 target_os = "cygwin",
448 ))]
449 fn posix_spawn(
450 &mut self,
451 stdio: &ChildPipes,
452 envp: Option<&CStringArray>,
453 ) -> io::Result<Option<Process>> {
454 #[cfg(target_os = "linux")]
455 use core::sync::atomic::{Atomic, AtomicU8, Ordering};
456
457 use crate::mem::MaybeUninit;
458 use crate::sys::{self, cvt_nz, on_broken_pipe_flag_used};
459
460 if self.get_gid().is_some()
461 || self.get_uid().is_some()
462 || (self.env_saw_path() && !self.program_is_path())
463 || !self.get_closures().is_empty()
464 || self.get_groups().is_some()
465 || self.get_chroot().is_some()
466 {
467 return Ok(None);
468 }
469
470 cfg_select! {
471 target_os = "linux" => {
472 use crate::sys::weak::weak;
473
474 weak!(
475 fn pidfd_spawnp(
476 pidfd: *mut libc::c_int,
477 path: *const libc::c_char,
478 file_actions: *const libc::posix_spawn_file_actions_t,
479 attrp: *const libc::posix_spawnattr_t,
480 argv: *const *mut libc::c_char,
481 envp: *const *mut libc::c_char,
482 ) -> libc::c_int;
483 );
484
485 static PIDFD_SUPPORTED: Atomic<u8> = AtomicU8::new(0);
486 const UNKNOWN: u8 = 0;
487 const SPAWN: u8 = 1;
488 const FORK_EXEC: u8 = 2;
490 const NO: u8 = 3;
493
494 if self.get_create_pidfd() {
495 let mut support = PIDFD_SUPPORTED.load(Ordering::Relaxed);
496 if support == FORK_EXEC {
497 return Ok(None);
498 }
499 if support == UNKNOWN {
500 support = NO;
501
502 match PidFd::current_process() {
503 Ok(pidfd) => {
504 support = FORK_EXEC;
506 if pidfd_spawnp.get().is_some() && let Ok(pid) = pidfd.pid() {
509 assert_eq!(pid, crate::process::id(), "sanity check");
510 support = SPAWN;
511 }
512 }
513 Err(e) if e.raw_os_error() == Some(libc::EMFILE) => {
514 return Err(e)
517 }
518 _ => {
519 }
521 }
522 PIDFD_SUPPORTED.store(support, Ordering::Relaxed);
523 if support == FORK_EXEC {
524 return Ok(None);
525 }
526 }
527 core::assert_matches::debug_assert_matches!(support, SPAWN | NO);
528 }
529 }
530 _ => {
531 if self.get_create_pidfd() {
532 unreachable!("only implemented on linux")
533 }
534 }
535 }
536
537 #[cfg(all(target_os = "linux", target_env = "gnu"))]
539 {
540 if let Some(version) = sys::os::glibc_version() {
541 if version < (2, 24) {
542 return Ok(None);
543 }
544 } else {
545 return Ok(None);
546 }
547 }
548
549 #[cfg(target_os = "nto")]
554 unsafe fn retrying_libc_posix_spawnp(
555 pid: *mut pid_t,
556 file: *const c_char,
557 file_actions: *const posix_spawn_file_actions_t,
558 attrp: *const posix_spawnattr_t,
559 argv: *const *mut c_char,
560 envp: *const *mut c_char,
561 ) -> io::Result<i32> {
562 let mut delay = MIN_FORKSPAWN_SLEEP;
563 loop {
564 match libc::posix_spawnp(pid, file, file_actions, attrp, argv, envp) {
565 libc::EBADF => {
566 if delay < get_clock_resolution() {
567 thread::yield_now();
570 } else if delay < MAX_FORKSPAWN_SLEEP {
571 thread::sleep(delay);
572 } else {
573 return Err(io::const_error!(
574 ErrorKind::WouldBlock,
575 "posix_spawnp returned EBADF too often",
576 ));
577 }
578 delay *= 2;
579 continue;
580 }
581 r => {
582 return Ok(r);
583 }
584 }
585 }
586 }
587
588 type PosixSpawnAddChdirFn = unsafe extern "C" fn(
589 *mut libc::posix_spawn_file_actions_t,
590 *const libc::c_char,
591 ) -> libc::c_int;
592
593 #[cfg(not(any(all(target_os = "linux", target_env = "musl"), target_os = "cygwin")))]
600 fn get_posix_spawn_addchdir() -> Option<PosixSpawnAddChdirFn> {
601 use crate::sys::weak::weak;
602
603 weak!(
608 fn posix_spawn_file_actions_addchdir_np(
609 file_actions: *mut libc::posix_spawn_file_actions_t,
610 path: *const libc::c_char,
611 ) -> libc::c_int;
612 );
613
614 weak!(
615 fn posix_spawn_file_actions_addchdir(
616 file_actions: *mut libc::posix_spawn_file_actions_t,
617 path: *const libc::c_char,
618 ) -> libc::c_int;
619 );
620
621 posix_spawn_file_actions_addchdir_np
622 .get()
623 .or_else(|| posix_spawn_file_actions_addchdir.get())
624 }
625
626 #[cfg(any(all(target_os = "linux", target_env = "musl"), target_os = "cygwin"))]
636 fn get_posix_spawn_addchdir() -> Option<PosixSpawnAddChdirFn> {
637 Some(libc::posix_spawn_file_actions_addchdir_np)
639 }
640
641 let addchdir = match self.get_cwd() {
642 Some(cwd) => {
643 if cfg!(target_vendor = "apple") {
644 if self.get_program_kind() == ProgramKind::Relative {
650 return Ok(None);
651 }
652 }
653 match get_posix_spawn_addchdir() {
657 Some(f) => Some((f, cwd)),
658 None => return Ok(None),
659 }
660 }
661 None => None,
662 };
663
664 let pgroup = self.get_pgroup();
665
666 struct PosixSpawnFileActions<'a>(&'a mut MaybeUninit<libc::posix_spawn_file_actions_t>);
667
668 impl Drop for PosixSpawnFileActions<'_> {
669 fn drop(&mut self) {
670 unsafe {
671 libc::posix_spawn_file_actions_destroy(self.0.as_mut_ptr());
672 }
673 }
674 }
675
676 struct PosixSpawnattr<'a>(&'a mut MaybeUninit<libc::posix_spawnattr_t>);
677
678 impl Drop for PosixSpawnattr<'_> {
679 fn drop(&mut self) {
680 unsafe {
681 libc::posix_spawnattr_destroy(self.0.as_mut_ptr());
682 }
683 }
684 }
685
686 unsafe {
687 let mut attrs = MaybeUninit::uninit();
688 cvt_nz(libc::posix_spawnattr_init(attrs.as_mut_ptr()))?;
689 let attrs = PosixSpawnattr(&mut attrs);
690
691 let mut flags = 0;
692
693 let mut file_actions = MaybeUninit::uninit();
694 cvt_nz(libc::posix_spawn_file_actions_init(file_actions.as_mut_ptr()))?;
695 let file_actions = PosixSpawnFileActions(&mut file_actions);
696
697 if let Some(fd) = stdio.stdin.fd() {
698 cvt_nz(libc::posix_spawn_file_actions_adddup2(
699 file_actions.0.as_mut_ptr(),
700 fd,
701 libc::STDIN_FILENO,
702 ))?;
703 }
704 if let Some(fd) = stdio.stdout.fd() {
705 cvt_nz(libc::posix_spawn_file_actions_adddup2(
706 file_actions.0.as_mut_ptr(),
707 fd,
708 libc::STDOUT_FILENO,
709 ))?;
710 }
711 if let Some(fd) = stdio.stderr.fd() {
712 cvt_nz(libc::posix_spawn_file_actions_adddup2(
713 file_actions.0.as_mut_ptr(),
714 fd,
715 libc::STDERR_FILENO,
716 ))?;
717 }
718 if let Some((f, cwd)) = addchdir {
719 cvt_nz(f(file_actions.0.as_mut_ptr(), cwd.as_ptr()))?;
720 }
721
722 if let Some(pgroup) = pgroup {
723 flags |= libc::POSIX_SPAWN_SETPGROUP;
724 cvt_nz(libc::posix_spawnattr_setpgroup(attrs.0.as_mut_ptr(), pgroup))?;
725 }
726
727 if !on_broken_pipe_flag_used() {
735 let mut default_set = MaybeUninit::<libc::sigset_t>::uninit();
736 cvt(sigemptyset(default_set.as_mut_ptr()))?;
737 cvt(sigaddset(default_set.as_mut_ptr(), libc::SIGPIPE))?;
738 #[cfg(target_os = "hurd")]
739 {
740 cvt(sigaddset(default_set.as_mut_ptr(), libc::SIGLOST))?;
741 }
742 cvt_nz(libc::posix_spawnattr_setsigdefault(
743 attrs.0.as_mut_ptr(),
744 default_set.as_ptr(),
745 ))?;
746 flags |= libc::POSIX_SPAWN_SETSIGDEF;
747 }
748
749 if self.get_setsid() {
750 cfg_select! {
751 all(target_os = "linux", target_env = "gnu") => {
752 flags |= libc::POSIX_SPAWN_SETSID;
753 }
754 _ => {
755 return Ok(None);
756 }
757 }
758 }
759
760 cvt_nz(libc::posix_spawnattr_setflags(attrs.0.as_mut_ptr(), flags as _))?;
761
762 let _env_lock = sys::env::env_read_lock();
764 let envp = envp.map(|c| c.as_ptr()).unwrap_or_else(|| *sys::env::environ() as *const _);
765
766 #[cfg(not(target_os = "nto"))]
767 let spawn_fn = libc::posix_spawnp;
768 #[cfg(target_os = "nto")]
769 let spawn_fn = retrying_libc_posix_spawnp;
770
771 #[cfg(target_os = "linux")]
772 if self.get_create_pidfd() && PIDFD_SUPPORTED.load(Ordering::Relaxed) == SPAWN {
773 let mut pidfd: libc::c_int = -1;
774 let spawn_res = pidfd_spawnp.get().unwrap()(
775 &mut pidfd,
776 self.get_program_cstr().as_ptr(),
777 file_actions.0.as_ptr(),
778 attrs.0.as_ptr(),
779 self.get_argv().as_ptr() as *const _,
780 envp as *const _,
781 );
782
783 let spawn_res = cvt_nz(spawn_res);
784 if let Err(ref e) = spawn_res
785 && e.raw_os_error() == Some(libc::ENOSYS)
786 {
787 PIDFD_SUPPORTED.store(FORK_EXEC, Ordering::Relaxed);
788 return Ok(None);
789 }
790 spawn_res?;
791
792 use crate::os::fd::{FromRawFd, IntoRawFd};
793
794 let pidfd = PidFd::from_raw_fd(pidfd);
795 let pid = match pidfd.pid() {
796 Ok(pid) => pid,
797 Err(e) => {
798 return Err(Error::new(
804 e.kind(),
805 "pidfd_spawnp succeeded but the child's PID could not be obtained",
806 ));
807 }
808 };
809
810 return Ok(Some(Process::new(pid as i32, pidfd.into_raw_fd())));
811 }
812
813 let mut p = Process::new(0, -1);
815
816 let spawn_res = spawn_fn(
817 &mut p.pid,
818 self.get_program_cstr().as_ptr(),
819 file_actions.0.as_ptr(),
820 attrs.0.as_ptr(),
821 self.get_argv().as_ptr() as *const _,
822 envp as *const _,
823 );
824
825 #[cfg(target_os = "nto")]
826 let spawn_res = spawn_res?;
827
828 cvt_nz(spawn_res)?;
829 Ok(Some(p))
830 }
831 }
832
833 #[cfg(target_os = "linux")]
834 fn send_pidfd(&self, sock: &crate::sys::net::Socket) {
835 use libc::{CMSG_DATA, CMSG_FIRSTHDR, CMSG_LEN, CMSG_SPACE, SCM_RIGHTS, SOL_SOCKET};
836
837 use crate::io::IoSlice;
838 use crate::os::fd::RawFd;
839 use crate::sys::cvt_r;
840
841 unsafe {
842 let child_pid = libc::getpid();
843 let pidfd = libc::syscall(libc::SYS_pidfd_open, child_pid, 0);
845
846 let fds: [c_int; 1] = [pidfd as RawFd];
847
848 const SCM_MSG_LEN: usize = size_of::<[c_int; 1]>();
849
850 #[repr(C)]
851 union Cmsg {
852 buf: [u8; unsafe { CMSG_SPACE(SCM_MSG_LEN as u32) as usize }],
853 _align: libc::cmsghdr,
854 }
855
856 let mut cmsg: Cmsg = mem::zeroed();
857
858 let mut iov = [IoSlice::new(b"")];
860 let mut msg: libc::msghdr = mem::zeroed();
861
862 msg.msg_iov = (&raw mut iov) as *mut _;
863 msg.msg_iovlen = 1;
864
865 if pidfd >= 0 {
867 msg.msg_controllen = size_of_val(&cmsg.buf) as _;
868 msg.msg_control = (&raw mut cmsg.buf) as *mut _;
869
870 let hdr = CMSG_FIRSTHDR((&raw mut msg) as *mut _);
871 (*hdr).cmsg_level = SOL_SOCKET;
872 (*hdr).cmsg_type = SCM_RIGHTS;
873 (*hdr).cmsg_len = CMSG_LEN(SCM_MSG_LEN as _) as _;
874 let data = CMSG_DATA(hdr);
875 crate::ptr::copy_nonoverlapping(
876 fds.as_ptr().cast::<u8>(),
877 data as *mut _,
878 SCM_MSG_LEN,
879 );
880 }
881
882 match cvt_r(|| libc::sendmsg(sock.as_raw(), &msg, 0)) {
885 Ok(0) => {}
886 other => rtabort!("failed to communicate with parent process. {:?}", other),
887 }
888 }
889 }
890
891 #[cfg(target_os = "linux")]
892 fn recv_pidfd(&self, sock: &crate::sys::net::Socket) -> pid_t {
893 use libc::{CMSG_DATA, CMSG_FIRSTHDR, CMSG_LEN, CMSG_SPACE, SCM_RIGHTS, SOL_SOCKET};
894
895 use crate::io::IoSliceMut;
896 use crate::sys::cvt_r;
897
898 unsafe {
899 const SCM_MSG_LEN: usize = size_of::<[c_int; 1]>();
900
901 #[repr(C)]
902 union Cmsg {
903 _buf: [u8; unsafe { CMSG_SPACE(SCM_MSG_LEN as u32) as usize }],
904 _align: libc::cmsghdr,
905 }
906 let mut cmsg: Cmsg = mem::zeroed();
907 let mut iov = [IoSliceMut::new(&mut [])];
909
910 let mut msg: libc::msghdr = mem::zeroed();
911
912 msg.msg_iov = (&raw mut iov) as *mut _;
913 msg.msg_iovlen = 1;
914 msg.msg_controllen = size_of::<Cmsg>() as _;
915 msg.msg_control = (&raw mut cmsg) as *mut _;
916
917 match cvt_r(|| libc::recvmsg(sock.as_raw(), &mut msg, libc::MSG_CMSG_CLOEXEC)) {
918 Err(_) => return -1,
919 Ok(_) => {}
920 }
921
922 let hdr = CMSG_FIRSTHDR((&raw mut msg) as *mut _);
923 if hdr.is_null()
924 || (*hdr).cmsg_level != SOL_SOCKET
925 || (*hdr).cmsg_type != SCM_RIGHTS
926 || (*hdr).cmsg_len != CMSG_LEN(SCM_MSG_LEN as _) as _
927 {
928 return -1;
929 }
930 let data = CMSG_DATA(hdr);
931
932 let mut fds = [-1 as c_int];
933
934 crate::ptr::copy_nonoverlapping(
935 data as *const _,
936 fds.as_mut_ptr().cast::<u8>(),
937 SCM_MSG_LEN,
938 );
939
940 fds[0]
941 }
942 }
943}
944
945pub struct Process {
951 pid: pid_t,
952 status: Option<ExitStatus>,
953 #[cfg(target_os = "linux")]
958 pidfd: Option<PidFd>,
959}
960
961impl Process {
962 #[cfg(target_os = "linux")]
963 unsafe fn new(pid: pid_t, pidfd: pid_t) -> Self {
970 use crate::os::unix::io::FromRawFd;
971 use crate::sys::FromInner;
972 let pidfd = (pidfd >= 0).then(|| PidFd::from_inner(sys::fd::FileDesc::from_raw_fd(pidfd)));
974 Process { pid, status: None, pidfd }
975 }
976
977 #[cfg(not(target_os = "linux"))]
978 unsafe fn new(pid: pid_t, _pidfd: pid_t) -> Self {
979 Process { pid, status: None }
980 }
981
982 pub fn id(&self) -> u32 {
983 self.pid as u32
984 }
985
986 pub fn kill(&self) -> io::Result<()> {
987 self.send_signal(libc::SIGKILL)
988 }
989
990 pub(crate) fn send_signal(&self, signal: i32) -> io::Result<()> {
991 if self.status.is_some() {
995 return Ok(());
996 }
997 #[cfg(target_os = "linux")]
998 if let Some(pid_fd) = self.pidfd.as_ref() {
999 return pid_fd.send_signal(signal);
1001 }
1002 cvt(unsafe { libc::kill(self.pid, signal) }).map(drop)
1003 }
1004
1005 pub fn wait(&mut self) -> io::Result<ExitStatus> {
1006 use crate::sys::cvt_r;
1007 if let Some(status) = self.status {
1008 return Ok(status);
1009 }
1010 #[cfg(target_os = "linux")]
1011 if let Some(pid_fd) = self.pidfd.as_ref() {
1012 let status = pid_fd.wait()?;
1013 self.status = Some(status);
1014 return Ok(status);
1015 }
1016 let mut status = 0 as c_int;
1017 cvt_r(|| unsafe { libc::waitpid(self.pid, &mut status, 0) })?;
1018 self.status = Some(ExitStatus::new(status));
1019 Ok(ExitStatus::new(status))
1020 }
1021
1022 pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
1023 if let Some(status) = self.status {
1024 return Ok(Some(status));
1025 }
1026 #[cfg(target_os = "linux")]
1027 if let Some(pid_fd) = self.pidfd.as_ref() {
1028 let status = pid_fd.try_wait()?;
1029 if let Some(status) = status {
1030 self.status = Some(status)
1031 }
1032 return Ok(status);
1033 }
1034 let mut status = 0 as c_int;
1035 let pid = cvt(unsafe { libc::waitpid(self.pid, &mut status, libc::WNOHANG) })?;
1036 if pid == 0 {
1037 Ok(None)
1038 } else {
1039 self.status = Some(ExitStatus::new(status));
1040 Ok(Some(ExitStatus::new(status)))
1041 }
1042 }
1043}
1044
1045#[derive(PartialEq, Eq, Clone, Copy, Default)]
1050pub struct ExitStatus(c_int);
1051
1052impl fmt::Debug for ExitStatus {
1053 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1054 f.debug_tuple("unix_wait_status").field(&self.0).finish()
1055 }
1056}
1057
1058impl ExitStatus {
1059 pub fn new(status: c_int) -> ExitStatus {
1060 ExitStatus(status)
1061 }
1062
1063 #[cfg(target_os = "linux")]
1064 pub fn from_waitid_siginfo(siginfo: libc::siginfo_t) -> ExitStatus {
1065 let status = unsafe { siginfo.si_status() };
1066
1067 match siginfo.si_code {
1068 libc::CLD_EXITED => ExitStatus((status & 0xff) << 8),
1069 libc::CLD_KILLED => ExitStatus(status),
1070 libc::CLD_DUMPED => ExitStatus(status | 0x80),
1071 libc::CLD_CONTINUED => ExitStatus(0xffff),
1072 libc::CLD_STOPPED | libc::CLD_TRAPPED => ExitStatus(((status & 0xff) << 8) | 0x7f),
1073 _ => unreachable!("waitid() should only return the above codes"),
1074 }
1075 }
1076
1077 fn exited(&self) -> bool {
1078 libc::WIFEXITED(self.0)
1079 }
1080
1081 pub fn exit_ok(&self) -> Result<(), ExitStatusError> {
1082 match NonZero::try_from(self.0) {
1088 Ok(failure) => Err(ExitStatusError(failure)),
1089 Err(_) => Ok(()),
1090 }
1091 }
1092
1093 pub fn code(&self) -> Option<i32> {
1094 self.exited().then(|| libc::WEXITSTATUS(self.0))
1095 }
1096
1097 pub fn signal(&self) -> Option<i32> {
1098 libc::WIFSIGNALED(self.0).then(|| libc::WTERMSIG(self.0))
1099 }
1100
1101 pub fn core_dumped(&self) -> bool {
1102 libc::WIFSIGNALED(self.0) && libc::WCOREDUMP(self.0)
1103 }
1104
1105 pub fn stopped_signal(&self) -> Option<i32> {
1106 libc::WIFSTOPPED(self.0).then(|| libc::WSTOPSIG(self.0))
1107 }
1108
1109 pub fn continued(&self) -> bool {
1110 libc::WIFCONTINUED(self.0)
1111 }
1112
1113 pub fn into_raw(&self) -> c_int {
1114 self.0
1115 }
1116}
1117
1118impl From<c_int> for ExitStatus {
1120 fn from(a: c_int) -> ExitStatus {
1121 ExitStatus(a)
1122 }
1123}
1124
1125fn signal_string(signal: i32) -> &'static str {
1132 match signal {
1133 libc::SIGHUP => " (SIGHUP)",
1134 libc::SIGINT => " (SIGINT)",
1135 libc::SIGQUIT => " (SIGQUIT)",
1136 libc::SIGILL => " (SIGILL)",
1137 libc::SIGTRAP => " (SIGTRAP)",
1138 libc::SIGABRT => " (SIGABRT)",
1139 #[cfg(not(target_os = "l4re"))]
1140 libc::SIGBUS => " (SIGBUS)",
1141 libc::SIGFPE => " (SIGFPE)",
1142 libc::SIGKILL => " (SIGKILL)",
1143 #[cfg(not(target_os = "l4re"))]
1144 libc::SIGUSR1 => " (SIGUSR1)",
1145 libc::SIGSEGV => " (SIGSEGV)",
1146 #[cfg(not(target_os = "l4re"))]
1147 libc::SIGUSR2 => " (SIGUSR2)",
1148 libc::SIGPIPE => " (SIGPIPE)",
1149 libc::SIGALRM => " (SIGALRM)",
1150 libc::SIGTERM => " (SIGTERM)",
1151 #[cfg(not(target_os = "l4re"))]
1152 libc::SIGCHLD => " (SIGCHLD)",
1153 #[cfg(not(target_os = "l4re"))]
1154 libc::SIGCONT => " (SIGCONT)",
1155 #[cfg(not(target_os = "l4re"))]
1156 libc::SIGSTOP => " (SIGSTOP)",
1157 #[cfg(not(target_os = "l4re"))]
1158 libc::SIGTSTP => " (SIGTSTP)",
1159 #[cfg(not(target_os = "l4re"))]
1160 libc::SIGTTIN => " (SIGTTIN)",
1161 #[cfg(not(target_os = "l4re"))]
1162 libc::SIGTTOU => " (SIGTTOU)",
1163 #[cfg(not(target_os = "l4re"))]
1164 libc::SIGURG => " (SIGURG)",
1165 #[cfg(not(target_os = "l4re"))]
1166 libc::SIGXCPU => " (SIGXCPU)",
1167 #[cfg(not(any(target_os = "l4re", target_os = "rtems")))]
1168 libc::SIGXFSZ => " (SIGXFSZ)",
1169 #[cfg(not(any(target_os = "l4re", target_os = "rtems")))]
1170 libc::SIGVTALRM => " (SIGVTALRM)",
1171 #[cfg(not(target_os = "l4re"))]
1172 libc::SIGPROF => " (SIGPROF)",
1173 #[cfg(not(any(target_os = "l4re", target_os = "rtems")))]
1174 libc::SIGWINCH => " (SIGWINCH)",
1175 #[cfg(not(any(target_os = "haiku", target_os = "l4re")))]
1176 libc::SIGIO => " (SIGIO)",
1177 #[cfg(target_os = "haiku")]
1178 libc::SIGPOLL => " (SIGPOLL)",
1179 #[cfg(not(target_os = "l4re"))]
1180 libc::SIGSYS => " (SIGSYS)",
1181 #[cfg(all(
1183 target_os = "linux",
1184 any(
1185 target_arch = "x86_64",
1186 target_arch = "x86",
1187 target_arch = "arm",
1188 target_arch = "aarch64"
1189 )
1190 ))]
1191 libc::SIGSTKFLT => " (SIGSTKFLT)",
1192 #[cfg(any(target_os = "linux", target_os = "nto", target_os = "cygwin"))]
1193 libc::SIGPWR => " (SIGPWR)",
1194 #[cfg(any(
1195 target_os = "freebsd",
1196 target_os = "netbsd",
1197 target_os = "openbsd",
1198 target_os = "dragonfly",
1199 target_os = "nto",
1200 target_vendor = "apple",
1201 target_os = "cygwin",
1202 ))]
1203 libc::SIGEMT => " (SIGEMT)",
1204 #[cfg(any(
1205 target_os = "freebsd",
1206 target_os = "netbsd",
1207 target_os = "openbsd",
1208 target_os = "dragonfly",
1209 target_vendor = "apple",
1210 ))]
1211 libc::SIGINFO => " (SIGINFO)",
1212 #[cfg(target_os = "hurd")]
1213 libc::SIGLOST => " (SIGLOST)",
1214 #[cfg(target_os = "freebsd")]
1215 libc::SIGTHR => " (SIGTHR)",
1216 #[cfg(target_os = "freebsd")]
1217 libc::SIGLIBRT => " (SIGLIBRT)",
1218 _ => "",
1219 }
1220}
1221
1222impl fmt::Display for ExitStatus {
1223 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1224 if let Some(code) = self.code() {
1225 write!(f, "exit status: {code}")
1226 } else if let Some(signal) = self.signal() {
1227 let signal_string = signal_string(signal);
1228 if self.core_dumped() {
1229 write!(f, "signal: {signal}{signal_string} (core dumped)")
1230 } else {
1231 write!(f, "signal: {signal}{signal_string}")
1232 }
1233 } else if let Some(signal) = self.stopped_signal() {
1234 let signal_string = signal_string(signal);
1235 write!(f, "stopped (not terminated) by signal: {signal}{signal_string}")
1236 } else if self.continued() {
1237 write!(f, "continued (WIFCONTINUED)")
1238 } else {
1239 write!(f, "unrecognised wait status: {} {:#x}", self.0, self.0)
1240 }
1241 }
1242}
1243
1244#[derive(PartialEq, Eq, Clone, Copy)]
1245pub struct ExitStatusError(NonZero<c_int>);
1246
1247impl Into<ExitStatus> for ExitStatusError {
1248 fn into(self) -> ExitStatus {
1249 ExitStatus(self.0.into())
1250 }
1251}
1252
1253impl fmt::Debug for ExitStatusError {
1254 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1255 f.debug_tuple("unix_wait_status").field(&self.0).finish()
1256 }
1257}
1258
1259impl ExitStatusError {
1260 pub fn code(self) -> Option<NonZero<i32>> {
1261 ExitStatus(self.0.into()).code().map(|st| st.try_into().unwrap())
1262 }
1263}
1264
1265#[cfg(target_os = "linux")]
1266mod linux_child_ext {
1267 use crate::io::ErrorKind;
1268 use crate::os::linux::process as os;
1269 use crate::sys::FromInner;
1270 use crate::sys::pal::linux::pidfd as imp;
1271 use crate::{io, mem};
1272
1273 #[unstable(feature = "linux_pidfd", issue = "82971")]
1274 impl crate::os::linux::process::ChildExt for crate::process::Child {
1275 fn pidfd(&self) -> io::Result<&os::PidFd> {
1276 self.handle
1277 .pidfd
1278 .as_ref()
1279 .map(|fd| unsafe { mem::transmute::<&imp::PidFd, &os::PidFd>(fd) })
1281 .ok_or_else(|| io::const_error!(ErrorKind::Uncategorized, "no pidfd was created."))
1282 }
1283
1284 fn into_pidfd(mut self) -> Result<os::PidFd, Self> {
1285 self.handle
1286 .pidfd
1287 .take()
1288 .map(|fd| <os::PidFd as FromInner<imp::PidFd>>::from_inner(fd))
1289 .ok_or_else(|| self)
1290 }
1291 }
1292}
1293
1294#[cfg(test)]
1295mod tests;
1296
1297#[cfg(all(test, target_os = "linux"))]
1299#[path = "unsupported/wait_status.rs"]
1300mod unsupported_wait_status;