]> git.proxmox.com Git - rustc.git/blob - library/std/src/sys/unix/process/process_unix.rs
New upstream version 1.61.0+dfsg1
[rustc.git] / library / std / src / sys / unix / process / process_unix.rs
1 use crate::convert::{TryFrom, TryInto};
2 use crate::fmt;
3 use crate::io::{self, Error, ErrorKind};
4 use crate::mem;
5 use crate::num::NonZeroI32;
6 use crate::ptr;
7 use crate::sys;
8 use crate::sys::cvt;
9 use crate::sys::process::process_common::*;
10 use core::ffi::NonZero_c_int;
11
12 #[cfg(target_os = "linux")]
13 use crate::os::linux::process::PidFd;
14
15 #[cfg(target_os = "linux")]
16 use crate::sys::weak::raw_syscall;
17
18 #[cfg(any(
19 target_os = "macos",
20 target_os = "freebsd",
21 all(target_os = "linux", target_env = "gnu"),
22 all(target_os = "linux", target_env = "musl"),
23 ))]
24 use crate::sys::weak::weak;
25
26 #[cfg(target_os = "vxworks")]
27 use libc::RTP_ID as pid_t;
28
29 #[cfg(not(target_os = "vxworks"))]
30 use libc::{c_int, pid_t};
31
32 #[cfg(not(any(target_os = "vxworks", target_os = "l4re")))]
33 use libc::{gid_t, uid_t};
34
35 ////////////////////////////////////////////////////////////////////////////////
36 // Command
37 ////////////////////////////////////////////////////////////////////////////////
38
39 impl Command {
40 pub fn spawn(
41 &mut self,
42 default: Stdio,
43 needs_stdin: bool,
44 ) -> io::Result<(Process, StdioPipes)> {
45 const CLOEXEC_MSG_FOOTER: [u8; 4] = *b"NOEX";
46
47 let envp = self.capture_env();
48
49 if self.saw_nul() {
50 return Err(io::const_io_error!(
51 ErrorKind::InvalidInput,
52 "nul byte found in provided data",
53 ));
54 }
55
56 let (ours, theirs) = self.setup_io(default, needs_stdin)?;
57
58 if let Some(ret) = self.posix_spawn(&theirs, envp.as_ref())? {
59 return Ok((ret, ours));
60 }
61
62 let (input, output) = sys::pipe::anon_pipe()?;
63
64 // Whatever happens after the fork is almost for sure going to touch or
65 // look at the environment in one way or another (PATH in `execvp` or
66 // accessing the `environ` pointer ourselves). Make sure no other thread
67 // is accessing the environment when we do the fork itself.
68 //
69 // Note that as soon as we're done with the fork there's no need to hold
70 // a lock any more because the parent won't do anything and the child is
71 // in its own process. Thus the parent drops the lock guard while the child
72 // forgets it to avoid unlocking it on a new thread, which would be invalid.
73 let env_lock = sys::os::env_read_lock();
74 let (pid, pidfd) = unsafe { self.do_fork()? };
75
76 if pid == 0 {
77 crate::panic::always_abort();
78 mem::forget(env_lock);
79 drop(input);
80 let Err(err) = unsafe { self.do_exec(theirs, envp.as_ref()) };
81 let errno = err.raw_os_error().unwrap_or(libc::EINVAL) as u32;
82 let errno = errno.to_be_bytes();
83 let bytes = [
84 errno[0],
85 errno[1],
86 errno[2],
87 errno[3],
88 CLOEXEC_MSG_FOOTER[0],
89 CLOEXEC_MSG_FOOTER[1],
90 CLOEXEC_MSG_FOOTER[2],
91 CLOEXEC_MSG_FOOTER[3],
92 ];
93 // pipe I/O up to PIPE_BUF bytes should be atomic, and then
94 // we want to be sure we *don't* run at_exit destructors as
95 // we're being torn down regardless
96 rtassert!(output.write(&bytes).is_ok());
97 unsafe { libc::_exit(1) }
98 }
99
100 drop(env_lock);
101 drop(output);
102
103 // Safety: We obtained the pidfd from calling `clone3` with
104 // `CLONE_PIDFD` so it's valid an otherwise unowned.
105 let mut p = unsafe { Process::new(pid, pidfd) };
106 let mut bytes = [0; 8];
107
108 // loop to handle EINTR
109 loop {
110 match input.read(&mut bytes) {
111 Ok(0) => return Ok((p, ours)),
112 Ok(8) => {
113 let (errno, footer) = bytes.split_at(4);
114 assert_eq!(
115 CLOEXEC_MSG_FOOTER, footer,
116 "Validation on the CLOEXEC pipe failed: {:?}",
117 bytes
118 );
119 let errno = i32::from_be_bytes(errno.try_into().unwrap());
120 assert!(p.wait().is_ok(), "wait() should either return Ok or panic");
121 return Err(Error::from_raw_os_error(errno));
122 }
123 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
124 Err(e) => {
125 assert!(p.wait().is_ok(), "wait() should either return Ok or panic");
126 panic!("the CLOEXEC pipe failed: {e:?}")
127 }
128 Ok(..) => {
129 // pipe I/O up to PIPE_BUF bytes should be atomic
130 assert!(p.wait().is_ok(), "wait() should either return Ok or panic");
131 panic!("short read on the CLOEXEC pipe")
132 }
133 }
134 }
135 }
136
137 // Attempts to fork the process. If successful, returns Ok((0, -1))
138 // in the child, and Ok((child_pid, -1)) in the parent.
139 #[cfg(not(target_os = "linux"))]
140 unsafe fn do_fork(&mut self) -> Result<(pid_t, pid_t), io::Error> {
141 cvt(libc::fork()).map(|res| (res, -1))
142 }
143
144 // Attempts to fork the process. If successful, returns Ok((0, -1))
145 // in the child, and Ok((child_pid, child_pidfd)) in the parent.
146 #[cfg(target_os = "linux")]
147 unsafe fn do_fork(&mut self) -> Result<(pid_t, pid_t), io::Error> {
148 use crate::sync::atomic::{AtomicBool, Ordering};
149
150 static HAS_CLONE3: AtomicBool = AtomicBool::new(true);
151 const CLONE_PIDFD: u64 = 0x00001000;
152
153 #[repr(C)]
154 struct clone_args {
155 flags: u64,
156 pidfd: u64,
157 child_tid: u64,
158 parent_tid: u64,
159 exit_signal: u64,
160 stack: u64,
161 stack_size: u64,
162 tls: u64,
163 set_tid: u64,
164 set_tid_size: u64,
165 cgroup: u64,
166 }
167
168 raw_syscall! {
169 fn clone3(cl_args: *mut clone_args, len: libc::size_t) -> libc::c_long
170 }
171
172 // Bypassing libc for `clone3` can make further libc calls unsafe,
173 // so we use it sparingly for now. See #89522 for details.
174 // Some tools (e.g. sandboxing tools) may also expect `fork`
175 // rather than `clone3`.
176 let want_clone3_pidfd = self.get_create_pidfd();
177
178 // If we fail to create a pidfd for any reason, this will
179 // stay as -1, which indicates an error.
180 let mut pidfd: pid_t = -1;
181
182 // Attempt to use the `clone3` syscall, which supports more arguments
183 // (in particular, the ability to create a pidfd). If this fails,
184 // we will fall through this block to a call to `fork()`
185 if want_clone3_pidfd && HAS_CLONE3.load(Ordering::Relaxed) {
186 let mut args = clone_args {
187 flags: CLONE_PIDFD,
188 pidfd: &mut pidfd as *mut pid_t as u64,
189 child_tid: 0,
190 parent_tid: 0,
191 exit_signal: libc::SIGCHLD as u64,
192 stack: 0,
193 stack_size: 0,
194 tls: 0,
195 set_tid: 0,
196 set_tid_size: 0,
197 cgroup: 0,
198 };
199
200 let args_ptr = &mut args as *mut clone_args;
201 let args_size = crate::mem::size_of::<clone_args>();
202
203 let res = cvt(clone3(args_ptr, args_size));
204 match res {
205 Ok(n) => return Ok((n as pid_t, pidfd)),
206 Err(e) => match e.raw_os_error() {
207 // Multiple threads can race to execute this store,
208 // but that's fine - that just means that multiple threads
209 // will have tried and failed to execute the same syscall,
210 // with no other side effects.
211 Some(libc::ENOSYS) => HAS_CLONE3.store(false, Ordering::Relaxed),
212 // Fallback to fork if `EPERM` is returned. (e.g. blocked by seccomp)
213 Some(libc::EPERM) => {}
214 _ => return Err(e),
215 },
216 }
217 }
218
219 // Generally, we just call `fork`. If we get here after wanting `clone3`,
220 // then the syscall does not exist or we do not have permission to call it.
221 cvt(libc::fork()).map(|res| (res, pidfd))
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_io_error!(ErrorKind::InvalidInput, "nul byte found in provided data",);
229 }
230
231 match self.setup_io(default, true) {
232 Ok((_, theirs)) => {
233 unsafe {
234 // Similar to when forking, we want to ensure that access to
235 // the environment is synchronized, so make sure to grab the
236 // environment lock before we try to exec.
237 let _lock = sys::os::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 // And at this point we've reached a special time in the life of the
248 // child. The child must now be considered hamstrung and unable to
249 // do anything other than syscalls really. Consider the following
250 // scenario:
251 //
252 // 1. Thread A of process 1 grabs the malloc() mutex
253 // 2. Thread B of process 1 forks(), creating thread C
254 // 3. Thread C of process 2 then attempts to malloc()
255 // 4. The memory of process 2 is the same as the memory of
256 // process 1, so the mutex is locked.
257 //
258 // This situation looks a lot like deadlock, right? It turns out
259 // that this is what pthread_atfork() takes care of, which is
260 // presumably implemented across platforms. The first thing that
261 // threads to *before* forking is to do things like grab the malloc
262 // mutex, and then after the fork they unlock it.
263 //
264 // Despite this information, libnative's spawn has been witnessed to
265 // deadlock on both macOS and FreeBSD. I'm not entirely sure why, but
266 // all collected backtraces point at malloc/free traffic in the
267 // child spawned process.
268 //
269 // For this reason, the block of code below should contain 0
270 // invocations of either malloc of free (or their related friends).
271 //
272 // As an example of not having malloc/free traffic, we don't close
273 // this file descriptor by dropping the FileDesc (which contains an
274 // allocation). Instead we just close it manually. This will never
275 // have the drop glue anyway because this code never returns (the
276 // child will either exec() or invoke libc::exit)
277 unsafe fn do_exec(
278 &mut self,
279 stdio: ChildPipes,
280 maybe_envp: Option<&CStringArray>,
281 ) -> Result<!, io::Error> {
282 use crate::sys::{self, cvt_r};
283
284 if let Some(fd) = stdio.stdin.fd() {
285 cvt_r(|| libc::dup2(fd, libc::STDIN_FILENO))?;
286 }
287 if let Some(fd) = stdio.stdout.fd() {
288 cvt_r(|| libc::dup2(fd, libc::STDOUT_FILENO))?;
289 }
290 if let Some(fd) = stdio.stderr.fd() {
291 cvt_r(|| libc::dup2(fd, libc::STDERR_FILENO))?;
292 }
293
294 #[cfg(not(target_os = "l4re"))]
295 {
296 if let Some(_g) = self.get_groups() {
297 //FIXME: Redox kernel does not support setgroups yet
298 #[cfg(not(target_os = "redox"))]
299 cvt(libc::setgroups(_g.len().try_into().unwrap(), _g.as_ptr()))?;
300 }
301 if let Some(u) = self.get_gid() {
302 cvt(libc::setgid(u as gid_t))?;
303 }
304 if let Some(u) = self.get_uid() {
305 // When dropping privileges from root, the `setgroups` call
306 // will remove any extraneous groups. We only drop groups
307 // if the current uid is 0 and we weren't given an explicit
308 // set of groups. If we don't call this, then even though our
309 // uid has dropped, we may still have groups that enable us to
310 // do super-user things.
311 //FIXME: Redox kernel does not support setgroups yet
312 #[cfg(not(target_os = "redox"))]
313 if libc::getuid() == 0 && self.get_groups().is_none() {
314 cvt(libc::setgroups(0, ptr::null()))?;
315 }
316 cvt(libc::setuid(u as uid_t))?;
317 }
318 }
319 if let Some(ref cwd) = *self.get_cwd() {
320 cvt(libc::chdir(cwd.as_ptr()))?;
321 }
322
323 if let Some(pgroup) = self.get_pgroup() {
324 cvt(libc::setpgid(0, pgroup))?;
325 }
326
327 // emscripten has no signal support.
328 #[cfg(not(target_os = "emscripten"))]
329 {
330 use crate::mem::MaybeUninit;
331 // Reset signal handling so the child process starts in a
332 // standardized state. libstd ignores SIGPIPE, and signal-handling
333 // libraries often set a mask. Child processes inherit ignored
334 // signals and the signal mask from their parent, but most
335 // UNIX programs do not reset these things on their own, so we
336 // need to clean things up now to avoid confusing the program
337 // we're about to run.
338 let mut set = MaybeUninit::<libc::sigset_t>::uninit();
339 cvt(sigemptyset(set.as_mut_ptr()))?;
340 cvt(libc::pthread_sigmask(libc::SIG_SETMASK, set.as_ptr(), ptr::null_mut()))?;
341
342 #[cfg(target_os = "android")] // see issue #88585
343 {
344 let mut action: libc::sigaction = mem::zeroed();
345 action.sa_sigaction = libc::SIG_DFL;
346 cvt(libc::sigaction(libc::SIGPIPE, &action, ptr::null_mut()))?;
347 }
348 #[cfg(not(target_os = "android"))]
349 {
350 let ret = sys::signal(libc::SIGPIPE, libc::SIG_DFL);
351 if ret == libc::SIG_ERR {
352 return Err(io::Error::last_os_error());
353 }
354 }
355 }
356
357 for callback in self.get_closures().iter_mut() {
358 callback()?;
359 }
360
361 // Although we're performing an exec here we may also return with an
362 // error from this function (without actually exec'ing) in which case we
363 // want to be sure to restore the global environment back to what it
364 // once was, ensuring that our temporary override, when free'd, doesn't
365 // corrupt our process's environment.
366 let mut _reset = None;
367 if let Some(envp) = maybe_envp {
368 struct Reset(*const *const libc::c_char);
369
370 impl Drop for Reset {
371 fn drop(&mut self) {
372 unsafe {
373 *sys::os::environ() = self.0;
374 }
375 }
376 }
377
378 _reset = Some(Reset(*sys::os::environ()));
379 *sys::os::environ() = envp.as_ptr();
380 }
381
382 libc::execvp(self.get_program_cstr().as_ptr(), self.get_argv().as_ptr());
383 Err(io::Error::last_os_error())
384 }
385
386 #[cfg(not(any(
387 target_os = "macos",
388 target_os = "freebsd",
389 all(target_os = "linux", target_env = "gnu"),
390 all(target_os = "linux", target_env = "musl"),
391 )))]
392 fn posix_spawn(
393 &mut self,
394 _: &ChildPipes,
395 _: Option<&CStringArray>,
396 ) -> io::Result<Option<Process>> {
397 Ok(None)
398 }
399
400 // Only support platforms for which posix_spawn() can return ENOENT
401 // directly.
402 #[cfg(any(
403 target_os = "macos",
404 target_os = "freebsd",
405 all(target_os = "linux", target_env = "gnu"),
406 all(target_os = "linux", target_env = "musl"),
407 ))]
408 fn posix_spawn(
409 &mut self,
410 stdio: &ChildPipes,
411 envp: Option<&CStringArray>,
412 ) -> io::Result<Option<Process>> {
413 use crate::mem::MaybeUninit;
414 use crate::sys::{self, cvt_nz};
415
416 if self.get_gid().is_some()
417 || self.get_uid().is_some()
418 || (self.env_saw_path() && !self.program_is_path())
419 || !self.get_closures().is_empty()
420 || self.get_groups().is_some()
421 || self.get_create_pidfd()
422 {
423 return Ok(None);
424 }
425
426 // Only glibc 2.24+ posix_spawn() supports returning ENOENT directly.
427 #[cfg(all(target_os = "linux", target_env = "gnu"))]
428 {
429 if let Some(version) = sys::os::glibc_version() {
430 if version < (2, 24) {
431 return Ok(None);
432 }
433 } else {
434 return Ok(None);
435 }
436 }
437
438 // Solaris, glibc 2.29+, and musl 1.24+ can set a new working directory,
439 // and maybe others will gain this non-POSIX function too. We'll check
440 // for this weak symbol as soon as it's needed, so we can return early
441 // otherwise to do a manual chdir before exec.
442 weak! {
443 fn posix_spawn_file_actions_addchdir_np(
444 *mut libc::posix_spawn_file_actions_t,
445 *const libc::c_char
446 ) -> libc::c_int
447 }
448 let addchdir = match self.get_cwd() {
449 Some(cwd) => {
450 if cfg!(target_os = "macos") {
451 // There is a bug in macOS where a relative executable
452 // path like "../myprogram" will cause `posix_spawn` to
453 // successfully launch the program, but erroneously return
454 // ENOENT when used with posix_spawn_file_actions_addchdir_np
455 // which was introduced in macOS 10.15.
456 return Ok(None);
457 }
458 match posix_spawn_file_actions_addchdir_np.get() {
459 Some(f) => Some((f, cwd)),
460 None => return Ok(None),
461 }
462 }
463 None => None,
464 };
465
466 let pgroup = self.get_pgroup();
467
468 // Safety: -1 indicates we don't have a pidfd.
469 let mut p = unsafe { Process::new(0, -1) };
470
471 struct PosixSpawnFileActions<'a>(&'a mut MaybeUninit<libc::posix_spawn_file_actions_t>);
472
473 impl Drop for PosixSpawnFileActions<'_> {
474 fn drop(&mut self) {
475 unsafe {
476 libc::posix_spawn_file_actions_destroy(self.0.as_mut_ptr());
477 }
478 }
479 }
480
481 struct PosixSpawnattr<'a>(&'a mut MaybeUninit<libc::posix_spawnattr_t>);
482
483 impl Drop for PosixSpawnattr<'_> {
484 fn drop(&mut self) {
485 unsafe {
486 libc::posix_spawnattr_destroy(self.0.as_mut_ptr());
487 }
488 }
489 }
490
491 unsafe {
492 let mut attrs = MaybeUninit::uninit();
493 cvt_nz(libc::posix_spawnattr_init(attrs.as_mut_ptr()))?;
494 let attrs = PosixSpawnattr(&mut attrs);
495
496 let mut flags = 0;
497
498 let mut file_actions = MaybeUninit::uninit();
499 cvt_nz(libc::posix_spawn_file_actions_init(file_actions.as_mut_ptr()))?;
500 let file_actions = PosixSpawnFileActions(&mut file_actions);
501
502 if let Some(fd) = stdio.stdin.fd() {
503 cvt_nz(libc::posix_spawn_file_actions_adddup2(
504 file_actions.0.as_mut_ptr(),
505 fd,
506 libc::STDIN_FILENO,
507 ))?;
508 }
509 if let Some(fd) = stdio.stdout.fd() {
510 cvt_nz(libc::posix_spawn_file_actions_adddup2(
511 file_actions.0.as_mut_ptr(),
512 fd,
513 libc::STDOUT_FILENO,
514 ))?;
515 }
516 if let Some(fd) = stdio.stderr.fd() {
517 cvt_nz(libc::posix_spawn_file_actions_adddup2(
518 file_actions.0.as_mut_ptr(),
519 fd,
520 libc::STDERR_FILENO,
521 ))?;
522 }
523 if let Some((f, cwd)) = addchdir {
524 cvt_nz(f(file_actions.0.as_mut_ptr(), cwd.as_ptr()))?;
525 }
526
527 if let Some(pgroup) = pgroup {
528 flags |= libc::POSIX_SPAWN_SETPGROUP;
529 cvt_nz(libc::posix_spawnattr_setpgroup(attrs.0.as_mut_ptr(), pgroup))?;
530 }
531
532 let mut set = MaybeUninit::<libc::sigset_t>::uninit();
533 cvt(sigemptyset(set.as_mut_ptr()))?;
534 cvt_nz(libc::posix_spawnattr_setsigmask(attrs.0.as_mut_ptr(), set.as_ptr()))?;
535 cvt(sigaddset(set.as_mut_ptr(), libc::SIGPIPE))?;
536 cvt_nz(libc::posix_spawnattr_setsigdefault(attrs.0.as_mut_ptr(), set.as_ptr()))?;
537
538 flags |= libc::POSIX_SPAWN_SETSIGDEF | libc::POSIX_SPAWN_SETSIGMASK;
539 cvt_nz(libc::posix_spawnattr_setflags(attrs.0.as_mut_ptr(), flags as _))?;
540
541 // Make sure we synchronize access to the global `environ` resource
542 let _env_lock = sys::os::env_read_lock();
543 let envp = envp.map(|c| c.as_ptr()).unwrap_or_else(|| *sys::os::environ() as *const _);
544 cvt_nz(libc::posix_spawnp(
545 &mut p.pid,
546 self.get_program_cstr().as_ptr(),
547 file_actions.0.as_ptr(),
548 attrs.0.as_ptr(),
549 self.get_argv().as_ptr() as *const _,
550 envp as *const _,
551 ))?;
552 Ok(Some(p))
553 }
554 }
555 }
556
557 ////////////////////////////////////////////////////////////////////////////////
558 // Processes
559 ////////////////////////////////////////////////////////////////////////////////
560
561 /// The unique ID of the process (this should never be negative).
562 pub struct Process {
563 pid: pid_t,
564 status: Option<ExitStatus>,
565 // On Linux, stores the pidfd created for this child.
566 // This is None if the user did not request pidfd creation,
567 // or if the pidfd could not be created for some reason
568 // (e.g. the `clone3` syscall was not available).
569 #[cfg(target_os = "linux")]
570 pidfd: Option<PidFd>,
571 }
572
573 impl Process {
574 #[cfg(target_os = "linux")]
575 unsafe fn new(pid: pid_t, pidfd: pid_t) -> Self {
576 use crate::os::unix::io::FromRawFd;
577 use crate::sys_common::FromInner;
578 // Safety: If `pidfd` is nonnegative, we assume it's valid and otherwise unowned.
579 let pidfd = (pidfd >= 0).then(|| PidFd::from_inner(sys::fd::FileDesc::from_raw_fd(pidfd)));
580 Process { pid, status: None, pidfd }
581 }
582
583 #[cfg(not(target_os = "linux"))]
584 unsafe fn new(pid: pid_t, _pidfd: pid_t) -> Self {
585 Process { pid, status: None }
586 }
587
588 pub fn id(&self) -> u32 {
589 self.pid as u32
590 }
591
592 pub fn kill(&mut self) -> io::Result<()> {
593 // If we've already waited on this process then the pid can be recycled
594 // and used for another process, and we probably shouldn't be killing
595 // random processes, so just return an error.
596 if self.status.is_some() {
597 Err(io::const_io_error!(
598 ErrorKind::InvalidInput,
599 "invalid argument: can't kill an exited process",
600 ))
601 } else {
602 cvt(unsafe { libc::kill(self.pid, libc::SIGKILL) }).map(drop)
603 }
604 }
605
606 pub fn wait(&mut self) -> io::Result<ExitStatus> {
607 use crate::sys::cvt_r;
608 if let Some(status) = self.status {
609 return Ok(status);
610 }
611 let mut status = 0 as c_int;
612 cvt_r(|| unsafe { libc::waitpid(self.pid, &mut status, 0) })?;
613 self.status = Some(ExitStatus::new(status));
614 Ok(ExitStatus::new(status))
615 }
616
617 pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
618 if let Some(status) = self.status {
619 return Ok(Some(status));
620 }
621 let mut status = 0 as c_int;
622 let pid = cvt(unsafe { libc::waitpid(self.pid, &mut status, libc::WNOHANG) })?;
623 if pid == 0 {
624 Ok(None)
625 } else {
626 self.status = Some(ExitStatus::new(status));
627 Ok(Some(ExitStatus::new(status)))
628 }
629 }
630 }
631
632 /// Unix exit statuses
633 //
634 // This is not actually an "exit status" in Unix terminology. Rather, it is a "wait status".
635 // See the discussion in comments and doc comments for `std::process::ExitStatus`.
636 #[derive(PartialEq, Eq, Clone, Copy)]
637 pub struct ExitStatus(c_int);
638
639 impl fmt::Debug for ExitStatus {
640 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
641 f.debug_tuple("unix_wait_status").field(&self.0).finish()
642 }
643 }
644
645 impl ExitStatus {
646 pub fn new(status: c_int) -> ExitStatus {
647 ExitStatus(status)
648 }
649
650 fn exited(&self) -> bool {
651 libc::WIFEXITED(self.0)
652 }
653
654 pub fn exit_ok(&self) -> Result<(), ExitStatusError> {
655 // This assumes that WIFEXITED(status) && WEXITSTATUS==0 corresponds to status==0. This is
656 // true on all actual versions of Unix, is widely assumed, and is specified in SuS
657 // https://pubs.opengroup.org/onlinepubs/9699919799/functions/wait.html . If it is not
658 // true for a platform pretending to be Unix, the tests (our doctests, and also
659 // procsss_unix/tests.rs) will spot it. `ExitStatusError::code` assumes this too.
660 match NonZero_c_int::try_from(self.0) {
661 /* was nonzero */ Ok(failure) => Err(ExitStatusError(failure)),
662 /* was zero, couldn't convert */ Err(_) => Ok(()),
663 }
664 }
665
666 pub fn code(&self) -> Option<i32> {
667 self.exited().then(|| libc::WEXITSTATUS(self.0))
668 }
669
670 pub fn signal(&self) -> Option<i32> {
671 libc::WIFSIGNALED(self.0).then(|| libc::WTERMSIG(self.0))
672 }
673
674 pub fn core_dumped(&self) -> bool {
675 libc::WIFSIGNALED(self.0) && libc::WCOREDUMP(self.0)
676 }
677
678 pub fn stopped_signal(&self) -> Option<i32> {
679 libc::WIFSTOPPED(self.0).then(|| libc::WSTOPSIG(self.0))
680 }
681
682 pub fn continued(&self) -> bool {
683 libc::WIFCONTINUED(self.0)
684 }
685
686 pub fn into_raw(&self) -> c_int {
687 self.0
688 }
689 }
690
691 /// Converts a raw `c_int` to a type-safe `ExitStatus` by wrapping it without copying.
692 impl From<c_int> for ExitStatus {
693 fn from(a: c_int) -> ExitStatus {
694 ExitStatus(a)
695 }
696 }
697
698 impl fmt::Display for ExitStatus {
699 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
700 if let Some(code) = self.code() {
701 write!(f, "exit status: {code}")
702 } else if let Some(signal) = self.signal() {
703 if self.core_dumped() {
704 write!(f, "signal: {signal} (core dumped)")
705 } else {
706 write!(f, "signal: {signal}")
707 }
708 } else if let Some(signal) = self.stopped_signal() {
709 write!(f, "stopped (not terminated) by signal: {signal}")
710 } else if self.continued() {
711 write!(f, "continued (WIFCONTINUED)")
712 } else {
713 write!(f, "unrecognised wait status: {} {:#x}", self.0, self.0)
714 }
715 }
716 }
717
718 #[derive(PartialEq, Eq, Clone, Copy)]
719 pub struct ExitStatusError(NonZero_c_int);
720
721 impl Into<ExitStatus> for ExitStatusError {
722 fn into(self) -> ExitStatus {
723 ExitStatus(self.0.into())
724 }
725 }
726
727 impl fmt::Debug for ExitStatusError {
728 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
729 f.debug_tuple("unix_wait_status").field(&self.0).finish()
730 }
731 }
732
733 impl ExitStatusError {
734 pub fn code(self) -> Option<NonZeroI32> {
735 ExitStatus(self.0.into()).code().map(|st| st.try_into().unwrap())
736 }
737 }
738
739 #[cfg(target_os = "linux")]
740 #[unstable(feature = "linux_pidfd", issue = "82971")]
741 impl crate::os::linux::process::ChildExt for crate::process::Child {
742 fn pidfd(&self) -> io::Result<&PidFd> {
743 self.handle
744 .pidfd
745 .as_ref()
746 .ok_or_else(|| Error::new(ErrorKind::Other, "No pidfd was created."))
747 }
748
749 fn take_pidfd(&mut self) -> io::Result<PidFd> {
750 self.handle
751 .pidfd
752 .take()
753 .ok_or_else(|| Error::new(ErrorKind::Other, "No pidfd was created."))
754 }
755 }
756
757 #[cfg(test)]
758 #[path = "process_unix/tests.rs"]
759 mod tests;