cosca 0.9.0

Unified cross-platform subprocess management: spawning, stdio, process trees, stable identity, and elevation.
Documentation
//! What a parent learns about its child's exit, and [`OsChild`], the parent's extras over an
//! [`OsProcess`].

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;

/// The OS object that names a process, lent by [`OsProcess::os_handle`].
#[cfg(target_os = "linux")]
pub(crate) type OsHandle<'a> = BorrowedFd<'a>;
/// The OS object that names a process, lent by [`OsProcess::os_handle`].
#[cfg(windows)]
pub(crate) type OsHandle<'a> = BorrowedHandle<'a>;

/// A process this process is the parent of: what only the parent gets, the exit record and the reap.
/// Policy (reap once, "already reaped is gone") belongs to the caller: these calls state what the OS
/// says now.
pub(crate) trait OsChild: OsProcess {
    /// The child's pid, for messages. `None`: the spawn never learned it (a Linux child whose spawn
    /// failed after its clone gave the pidfd); acts go by the handle either way.
    fn pid(&self) -> Option<u32>;

    /// What a kill through this handle may be refused for, as whatever built the handle knows it.
    /// A teardown's contract with its caller reads it.
    fn kill_refusal(&self) -> KillRefusal;

    /// The kernel this child was built with, which every read of it asks: the one place a read by the
    /// child's number (a reap and reuse of it, a cgroup read) asks too.
    fn kernel(&self) -> &dyn crate::identity::Kernel;

    /// The identity `pid`, the child's number as its caller holds it, holds now, and why it could not
    /// be read when the read knows: a read by number through [`kernel`](Self::kernel), never through
    /// the child's handle, which after a reap names the dead child and not the number's holder. It
    /// needs no [`pid`](Self::pid) of the box, so a box without one answers it too.
    #[cfg(unix)]
    fn number_holder(&self, pid: u32) -> crate::identity::NumberRead {
        crate::identity::ProcessId::of_with(self.kernel(), pid)
    }

    /// Look at the exit record without consuming it, and without touching anything a waiter waits
    /// on. A stop, or a zombie only its tracer sees, is [`PeekOutcome::Running`]. Any thread, any
    /// time.
    fn peek(&self) -> Result<PeekOutcome, Error>;

    /// The waiter's look: prepare what it will wait on, then read the exit record if there is one
    /// (never a stop), **leaving it in place**: the zombie stays this process's, and keeps its
    /// number. [`TryObserveOutcome::Running`] carries the wait, which the caller waits on before it
    /// calls again. Only the one waiter that holds the wait calls it.
    fn try_observe(&self) -> Result<TryObserveOutcome<'_>, Error>;

    /// Consume the exit record if there is one, once and without blocking: the end of the child's
    /// handle, which is where every reap of a child happens. [`Reap::Running`] when there was
    /// nothing to consume (the child has not exited, or a tracer holds its zombie).
    #[cfg(unix)]
    fn try_reap(&self) -> Result<crate::wait::exit_only::Reap, Error>;

    /// Whether [`try_reap`](Self::try_reap) names this child exactly (a pidfd), so it can only take
    /// this child's exit record. `false`: it consumes by the child's number, a check and not a pin,
    /// so the handle asks it only for an exit its own wait saw.
    #[cfg(unix)]
    fn exact_consume(&self) -> bool;
}

/// What a kill through a handle may be refused for. The handle's constructor decides: it knows the
/// rights it asked for or was granted.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum KillRefusal {
    /// Never: the handle can kill its process (a Windows handle holding `PROCESS_TERMINATE`), so a
    /// refusal is a contract breach. A refusal that only says the process is exiting
    /// (`ERROR_ACCESS_DENIED` on an exiting process) is not one: it is answered as an exit
    /// (`Termination::Exited`).
    Never,
    /// For want of permission alone ([`PermissionDenied`](std::io::ErrorKind::PermissionDenied)): a
    /// Linux pidfd (`EPERM`), a Windows handle that lacks `PROCESS_TERMINATE`.
    #[cfg_attr(
        target_os = "macos",
        allow(dead_code, reason = "a macOS kill is refused for any reason: `Any`")
    )]
    Permission,
    /// For any reason: macOS checks a kill by reading the process's unique id first, and the kernel
    /// can refuse that read with any errno, besides the `EPERM` of the signal itself.
    #[cfg_attr(
        not(target_os = "macos"),
        allow(dead_code, reason = "only a macOS kill is checked by an identity read")
    )]
    Any,
}

/// What [`OsChild::try_observe`] did.
#[derive(Debug)]
pub(crate) enum TryObserveOutcome<'a> {
    /// The exit record, left in place.
    Exited(ExitRecord),
    /// Not exited: wait on this, then look again.
    Running(WaitFor<'a>),
    /// An exit was seen but there is no record to consume, and nothing will signal the change (a
    /// tracer holds the zombie, or the OS is still finishing the exit): look again after a backoff.
    #[cfg_attr(
        windows,
        allow(
            dead_code,
            reason = "a process handle pins its process: nothing waits for a zombie a tracer holds"
        )
    )]
    Recheck,
    Foreign(Foreign),
}

/// A child's exit as its exit record states it. A peek sees one too.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ExitRecord {
    Status(ExitStatus),
    /// A consuming `waitid` that should have handed back a zombie's exit record gave another
    /// `si_code`. A contract breach, but the zombie is consumed, so it is a cached outcome. Only the
    /// consuming reap at the end of a handle can see one.
    #[cfg_attr(windows, allow(dead_code, reason = "Windows has no `waitid` records"))]
    Unreadable {
        si_code: i32,
    },
}

/// Why a child is not this process's to reap any more.
#[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 {
    /// The OS answered `ECHILD`, or a by-pid consume found nothing: something else reaped it.
    Gone,
    /// The pid names another process now: its start time differs from the child's.
    #[cfg_attr(
        not(target_os = "macos"),
        allow(dead_code, reason = "only macOS reads a child by a pid that can be reused")
    )]
    Other,
    /// `ECHILD` for a pid that still names the child, held by launchd: its tracer died and XNU
    /// reparented it. It has exited and is not this process's to reap. Kept apart from `Gone` so
    /// that a log can say why.
    #[cfg_attr(
        not(target_os = "macos"),
        allow(dead_code, reason = "only macOS has a zombie launchd holds")
    )]
    Orphaned,
}

impl Foreign {
    /// The fate of a child that is not this process's to reap. Every path that maps a `Foreign` to a
    /// fate uses this:
    ///
    /// - `kill_delivered`: cosca's kill was delivered, so the child is [`Killed`](ChildFate::Killed):
    ///   dead or dying, its exit not collected by cosca.
    /// - Otherwise cosca delivered nothing, and the child is [`Gone`](ChildFate::Gone).
    #[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 {
        // Every foreign verdict is the same situation for the fate: only the kill tells them apart.
        let _ = self;
        if kill_delivered {
            ChildFate::Killed
        } else {
            ChildFate::Gone
        }
    }
}

/// What a peek saw.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum PeekOutcome {
    /// An exit record, not consumed.
    Exit(ExitRecord),
    /// No exit record: still running, stopped under a tracer, or a zombie only its tracer sees.
    Running,
    #[cfg_attr(
        windows,
        allow(dead_code, reason = "a process handle pins its process: no foreign reap")
    )]
    Foreign(Foreign),
}

/// Take over the std `child`, whose identity `id` the caller has just read, as the [`OsChild`] of
/// its platform. **Never reaps**: an already-exited child is still a zombie afterwards. A child
/// already reaped elsewhere cannot be adopted: `Err`, and the child handed back untouched.
///
/// - Linux: the `pidfd_open` of its pid fails, or `waitid(P_PIDFD, WEXITED | WNOHANG | WNOWAIT)` on
///   the pidfd answers `ECHILD`: it names no child of this process. A running child, or an exit
///   not yet reaped, is adopted.
/// - macOS: `ECHILD`, or an unreadable identity.
///
/// Tests only: a spawn adopts through the handle it holds.
#[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);
    // std's `Child` holds nothing else the tests use: dropping it neither kills nor reaps.
    #[cfg(unix)]
    drop(child);
    Ok(os)
}

/// [`adopt_std`]'s macOS half: a [`MacosChild`](super::macos::child::MacosChild) of `id`'s pid that
/// asks the kernel `kernel(pid, unique)` makes, where `unique` is the host's own read of the pid's
/// unique id. The kernel is made once the child's id is known, for a test whose rows name it. `ECHILD`
/// if the pid has no process, and the unreadable-identity error if the read is refused.
#[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)),
    }
}

/// [`adopt_std`] with a kernel the test states: see [`adopt_macos`].
#[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) => {
            // std's `Child` holds nothing else the tests use: dropping it neither kills nor reaps.
            drop(child);
            Ok(os)
        }
        Err(e) => Err((e, child)),
    }
}

/// [`adopt_std`]'s Windows half over a kernel the test states: a
/// [`WindowsProcess`](super::windows::WindowsProcess) of the child's own handle, which owns `kernel`.
/// It cannot fail: the handle pins the process.
#[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(),
    ))
}

/// [`adopt_std`]'s Linux half: the pidfd of `id`'s pid, opened through `kernel`, which the child then
/// owns, confirmed to name a child of this process.
#[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))))?;
    // Never in a stdio slot: with 0, 1 or 2 closed, the lowest free number is one, and the
    // application may `dup2` its stdio back over it, destroying the pidfd.
    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)))
        }
    }
}

/// A running blocker child (see [`crate::test_child::blocker`]) adopted by [`adopt_std`], its
/// identity, and the write end of its stdin: closing it ends the child.
#[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)
}