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>;
fn kill_refusal(&self) -> KillRefusal;
fn kernel(&self) -> &dyn crate::identity::Kernel;
#[cfg(unix)]
fn number_holder(&self, pid: u32) -> crate::identity::NumberRead {
crate::identity::ProcessId::of_with(self.kernel(), pid)
}
fn peek(&self) -> Result<PeekOutcome, Error>;
fn try_observe(&self) -> Result<TryObserveOutcome<'_>, Error>;
#[cfg(unix)]
fn try_reap(&self) -> Result<crate::wait::exit_only::Reap, Error>;
#[cfg(unix)]
fn exact_consume(&self) -> bool;
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum KillRefusal {
Never,
#[cfg_attr(
target_os = "macos",
allow(dead_code, reason = "a macOS kill is refused for any reason: `Any`")
)]
Permission,
#[cfg_attr(
not(target_os = "macos"),
allow(dead_code, reason = "only a macOS kill is checked by an identity read")
)]
Any,
}
#[derive(Debug)]
pub(crate) enum TryObserveOutcome<'a> {
Exited(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 = "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 = match adopt_macos(|_, _| crate::identity::HostKernel, id) {
Ok(os) => os,
Err(e) => return Err((e, child)),
};
#[cfg(windows)]
let os = adopt_std_over(crate::identity::HostKernel, child, id);
#[cfg(unix)]
drop(child);
Ok(os)
}
#[cfg(all(test, target_os = "macos"))]
fn adopt_macos<K: crate::identity::Kernel + Send + 'static>(
kernel: impl FnOnce(u32, u64) -> K,
id: crate::identity::ProcessId,
) -> Result<Box<dyn OsChild>, Error> {
let pid = id.pid();
match crate::signal::read_identity(&crate::identity::HostKernel, pid) {
Ok(Some(unique)) => Ok(Box::new(super::macos::child::MacosChild::new(
kernel(pid, unique),
pid,
unique,
)?)),
Ok(None) => Err(Error::Io(std::io::Error::from_raw_os_error(libc::ECHILD))),
Err(errno) => Err(crate::signal::identity_unreadable(pid, errno)),
}
}
#[cfg(all(test, target_os = "macos"))]
#[allow(
clippy::result_large_err,
reason = "the child is handed back untouched for the caller to deal with"
)]
pub(crate) fn adopt_std_over<K: crate::identity::Kernel + Send + 'static>(
kernel: impl FnOnce(u32, u64) -> K,
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");
match adopt_macos(kernel, id) {
Ok(os) => {
drop(child);
Ok(os)
}
Err(e) => Err((e, child)),
}
}
#[cfg(all(test, windows))]
pub(crate) fn adopt_std_over<K: crate::identity::Kernel + Send + 'static>(
kernel: K,
child: std::process::Child,
id: crate::identity::ProcessId,
) -> Box<dyn OsChild> {
debug_assert_eq!(child.id(), id.pid(), "the identity must be the child's");
Box::new(super::windows::WindowsProcess::for_child(
kernel,
std::os::windows::io::OwnedHandle::from(child),
id.pid(),
))
}
#[cfg(all(test, target_os = "linux"))]
pub(crate) fn adopt_pidfd<K: crate::identity::Kernel + Send + 'static>(
kernel: K,
id: crate::identity::ProcessId,
) -> Result<Box<dyn OsChild>, Error> {
use std::os::fd::AsFd as _;
use crate::wait::exit_only::linux::peek;
use crate::wait::exit_only::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(&kernel, 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(kernel, Some(id.pid()), pidfd)))
}
}
}
#[cfg(test)]
pub(crate) fn adopted_blocker() -> (Box<dyn OsChild>, crate::identity::ProcessId, std::process::ChildStdin) {
let (child, stdin) = crate::test_child::blocker().into_parts();
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: {}", crate::error::Report(&e)));
(os, id, stdin)
}