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