use std::process::ExitStatus;
use super::{OsProcess, WaitFor};
use crate::error::{ChildFate, Error};
#[cfg(target_os = "linux")]
use std::os::fd::BorrowedFd;
#[cfg(windows)]
use std::os::windows::io::BorrowedHandle;
#[cfg(target_os = "linux")]
pub(crate) type OsHandle<'a> = BorrowedFd<'a>;
#[cfg(windows)]
pub(crate) type OsHandle<'a> = BorrowedHandle<'a>;
pub(crate) trait OsChild: OsProcess {
fn pid(&self) -> Option<u32>;
#[cfg(any(target_os = "linux", windows))]
fn kill_refusal(&self) -> KillRefusal;
fn peek(&self) -> Result<PeekOutcome, Error>;
fn exited_unannounced(&self) -> Result<bool, Error> {
Ok(false)
}
fn try_reap(&self) -> Result<TryReapOutcome<'_>, Error>;
}
#[cfg_attr(
not(any(target_os = "linux", windows)),
allow(
dead_code,
reason = "only the Linux and Windows spawns tear a child down over a handle"
)
)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum KillRefusal {
Never,
Permission,
}
#[derive(Debug)]
pub(crate) enum TryReapOutcome<'a> {
Reaped(ExitRecord),
Running(WaitFor<'a>),
#[cfg_attr(
windows,
allow(
dead_code,
reason = "a process handle pins its process: nothing waits for a zombie a tracer holds"
)
)]
Recheck,
Foreign(Foreign),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ExitRecord {
Status(ExitStatus),
#[cfg_attr(windows, allow(dead_code, reason = "Windows has no `waitid` records"))]
Unreadable {
si_code: i32,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(
windows,
allow(dead_code, reason = "a process handle pins its process: no foreign reap")
)]
pub(crate) enum Foreign {
Gone,
#[cfg_attr(
not(target_os = "macos"),
allow(dead_code, reason = "only macOS reads a child by a pid that can be reused")
)]
Other,
#[cfg_attr(
not(target_os = "macos"),
allow(dead_code, reason = "only macOS has a zombie launchd holds")
)]
Orphaned,
}
impl Foreign {
#[cfg_attr(
windows,
allow(dead_code, reason = "a process handle pins its process: no foreign reap")
)]
pub(crate) fn fate(self, kill_delivered: bool) -> ChildFate {
let _ = self;
if kill_delivered {
ChildFate::Killed
} else {
ChildFate::Gone
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum PeekOutcome {
Exit(ExitRecord),
Running,
#[cfg_attr(
windows,
allow(dead_code, reason = "a process handle pins its process: no foreign reap")
)]
Foreign(Foreign),
}
#[cfg(test)]
#[allow(
clippy::result_large_err,
reason = "the child is handed back untouched for the caller to deal with"
)]
pub(crate) fn adopt_std(
child: std::process::Child,
id: crate::identity::ProcessId,
) -> Result<Box<dyn OsChild>, (Error, std::process::Child)> {
debug_assert_eq!(child.id(), id.pid(), "the identity must be the child's");
#[cfg(target_os = "macos")]
let gone = || Error::Io(std::io::Error::from_raw_os_error(libc::ECHILD));
#[cfg(target_os = "linux")]
let os = match adopt_pidfd(&crate::identity::HostKernel, id) {
Ok(os) => os,
Err(e) => return Err((e, child)),
};
#[cfg(target_os = "macos")]
let os: Box<dyn OsChild> = match crate::signal::read_identity(id.pid()) {
Ok(Some(unique)) => match super::macos::child::MacChild::new(id.pid(), unique) {
Ok(os) => Box::new(os),
Err(e) => return Err((e, child)),
},
Ok(None) => return Err((gone(), child)),
Err(errno) => return Err((crate::signal::identity_unreadable(id.pid(), errno), child)),
};
#[cfg(windows)]
let os: Box<dyn OsChild> = Box::new(super::windows::WindowsProcess::for_child(
std::os::windows::io::OwnedHandle::from(child),
id.pid(),
));
#[cfg(unix)]
drop(child);
Ok(os)
}
#[cfg(all(test, target_os = "linux"))]
pub(crate) fn adopt_pidfd(
kernel: &dyn crate::identity::Kernel,
id: crate::identity::ProcessId,
) -> Result<Box<dyn OsChild>, Error> {
use std::os::fd::AsFd as _;
use crate::wait::exit_only::{peek, Target};
let target = rustix::process::Pid::from_raw(id.pid() as i32).expect("a spawned child's pid is never 0");
let pidfd = kernel
.pidfd_open(target, rustix::process::PidfdFlags::empty())
.map_err(|e| Error::Io(crate::error::io_context("pidfd_open", std::io::Error::from(e))))?;
let pidfd = crate::above_stdio::above_stdio(pidfd).map_err(Error::Io)?;
match peek(&Target::PidFd(pidfd.as_fd())).map_err(Error::Io)? {
PeekOutcome::Foreign(_) => Err(Error::Io(std::io::Error::from_raw_os_error(libc::ECHILD))),
PeekOutcome::Exit(_) | PeekOutcome::Running => {
Ok(Box::new(super::linux::LinuxProcess::new(Some(id.pid()), pidfd)))
}
}
}
#[cfg(test)]
pub(crate) fn adopted_blocker() -> (Box<dyn OsChild>, crate::identity::ProcessId, std::process::ChildStdin) {
let mut cmd = crate::test_child::held_std_killable_blocker();
let mut child = crate::test_spawn::spawn(&mut cmd).expect("spawn the blocker");
let stdin = child.stdin.take().expect("piped stdin");
let id = crate::identity::ProcessId::of(child.id())
.found()
.expect("the live child has an identity");
let os = adopt_std(child, id).unwrap_or_else(|(e, _)| panic!("adopt: {e}"));
(os, id, stdin)
}