cosca 0.10.0

Unified cross-platform subprocess management: spawning, stdio, process trees, stable identity, and elevation.
Documentation
//! Layer 1 of the process stack: one OS-facing object per process, found by [`open`] and driven
//! by [`drive`].
//!
//! An [`OsProcess`] answers two questions about a process, "did it exit" and "signal it", and
//! never reaps it. It owns no wait loop: when the process still runs, [`OsProcess::exited`] hands
//! out the OS primitive a caller can block or register on ([`WaitFor`]), and the driver loops
//! "look; if running, wait on what the look returned".

use std::fmt;

use crate::error::Error;
use crate::identity::ProcessId;
use crate::signal::{Sent, Sig};

pub(crate) mod child;
pub(crate) mod drive;
#[cfg(test)]
pub(crate) mod fake;
#[cfg(target_os = "linux")]
pub(crate) mod linux;
#[cfg(target_os = "macos")]
pub(crate) mod macos;
#[cfg(unix)]
pub(crate) mod poll;
#[cfg(windows)]
pub(crate) mod windows;

#[cfg(unix)]
use std::os::fd::BorrowedFd;
#[cfg(windows)]
use std::os::windows::io::BorrowedHandle;

/// One process, as the OS names it. `Send` so a driver may move it to a blocking thread, and
/// `Sync` so one open serves a signal and a wait from different threads.
pub(crate) trait OsProcess: Send + Sync + fmt::Debug {
    /// Send `sig`. [`Sent::Gone`] when the process is no longer the one opened.
    fn signal(&self, sig: Sig) -> Result<Sent, Error>;

    /// Look at the process once, without blocking. A [`Exit::Running`] look carries what to wait
    /// on for the next change; the wait ends on any change, so look again after it. On macOS
    /// [`Exit::Exited`] means the process is a zombie or gone, not merely that its `NOTE_EXIT` has
    /// fired; [`ProcessId::is_alive`] never reads `Alive` afterwards. A child another process holds
    /// (its tracer, or launchd) gets no `NOTE_EXIT` until it is handed back, so its look reads the zombie
    /// itself.
    fn exited(&self) -> Result<Exit<'_>, Error>;

    /// What one wait for the process's exit loops on ([`drive::exited_until`]): its own `Waitable`,
    /// which may own the readiness source it blocks on, since a source that is read has one reader.
    /// The default looks with [`exited`](OsProcess::exited) and waits on what that returns. It
    /// is made before the wait's first look, so a source it arms misses no change after it.
    fn exit_wait(&self) -> Result<ExitWait<'_>, Error> {
        Ok(Box::new(drive::ProcessExit(self)))
    }

    /// The OS object that names the process, lent to platform-only consumers (Job Objects, resume,
    /// cgroup attach). A fake lends its own wake fd or event, which names no process: code that
    /// uses a handle is tested against real processes.
    #[cfg(any(target_os = "linux", windows))]
    fn os_handle(&self) -> child::OsHandle<'_>;
}

/// The wait [`OsProcess::exit_wait`] makes: `Send`, so the asynchronous driver's future is.
pub(crate) type ExitWait<'a> = Box<dyn drive::Waitable<Output = ()> + Send + 'a>;

/// What one look at a process found.
#[derive(Debug)]
pub(crate) enum Exit<'a> {
    Exited,
    Running(WaitFor<'a>),
    /// macOS: the exit edge has fired but the process is not yet a zombie (or gone), or no edge will
    /// come (another process holds the child), and nothing will signal the change: look again after a
    /// backoff. A look that only asks whether it runs
    /// reads this as running.
    #[cfg_attr(
        not(target_os = "macos"),
        allow(dead_code, reason = "only macOS's exit edge precedes the state the exit is read in")
    )]
    Recheck,
}

/// What to block or register on to learn that a running process may have changed. Spurious
/// wakes are allowed; a wake is never the answer, the next look is.
#[derive(Debug)]
pub(crate) enum WaitFor<'a> {
    /// Unix: a descriptor that polls readable once the process has exited, and that nothing reads:
    /// the pidfd on Linux, a kqueue armed for the exit on macOS. A macOS [`OsProcess::exit_wait`]
    /// hands out another: the kqueue it owns, readable on any change it armed for (exit, signal,
    /// reap), which only that wait reads, draining it before each look.
    #[cfg(unix)]
    Readable(BorrowedFd<'a>),
    /// Windows: the process handle; signalled once the process has exited.
    #[cfg(windows)]
    Signalled(BorrowedHandle<'a>),
}

/// The words of what a failed look at a process leaves undone.
#[cfg(unix)]
macro_rules! exit_unobserved {
    () => {
        "its exit cannot be observed"
    };
}

/// What is left undone when the look that arms an exit watch cannot go ahead (macOS).
#[cfg(target_os = "macos")]
pub(crate) const EXIT_CONSEQUENCE: &str = exit_unobserved!();

/// What is left undone when an [`open`] cannot go ahead, for the errors it returns: the one open
/// serves every act on the process.
#[cfg(unix)]
pub(crate) const OPEN_CONSEQUENCE: &str = concat!(exit_unobserved!(), " and no signal was sent");

/// What a message calls a child whose pid is not known ([`OsChild::pid`](child::OsChild::pid)).
pub(crate) const PIDLESS_CHILD: &str = "the child (pid unknown)";

/// How a message names a child: `child 4242`, or what stands for a pid that is not known.
pub(crate) fn child_named(pid: Option<u32>) -> String {
    pid.map_or_else(|| PIDLESS_CHILD.to_owned(), |pid| format!("child {pid}"))
}

/// Open the process `id` names. `Ok(None)`: it is gone, or its pid now names another process. The
/// tests' entry; the library opens through [`open_with`].
#[cfg(test)]
pub(crate) fn open(id: ProcessId) -> Result<Option<Box<dyn OsProcess>>, Error> {
    open_with(crate::identity::HostKernel, id).map_err(OpenFailure::into_open_error)
}

/// Why an [`open_with`] opened nothing and found nothing gone. It logs nothing: the caller that
/// returns the error passes it on, and one that drops it warns.
#[derive(Debug)]
pub(crate) enum OpenFailure {
    /// Linux: a pidfd call failed for a reason that says nothing about the target. The call and its
    /// errno are for a consumer to build its own error from: [`into_open_error`](Self::into_open_error)
    /// is [`Process::open`](crate::Process::open)'s.
    #[cfg(target_os = "linux")]
    Call(crate::identity::FailedCall),
    /// An error already in its final form: every other failure, on every platform.
    Finished(Error),
}

impl From<Error> for OpenFailure {
    fn from(error: Error) -> Self {
        OpenFailure::Finished(error)
    }
}

impl OpenFailure {
    /// The error [`Process::open`](crate::Process::open) documents: a failed call is
    /// [`open_error`](linux::open::open_error), the rest as they are.
    pub(crate) fn into_open_error(self) -> Error {
        match self {
            #[cfg(target_os = "linux")]
            OpenFailure::Call(call) => linux::open::open_error(call),
            OpenFailure::Finished(error) => error,
        }
    }
}

/// [`open`] through `kernel`: the one entry to the open, on every platform. The open checks `id`
/// through `kernel`, and the process it returns owns the same `kernel`, so every later read of it asks
/// that one. The kernel is as long-lived as the process: a borrow (what the walks pass, of one kernel
/// they open every member from) gives a process that lives inside the walk. Windows's open asks
/// its [`Kernel`](crate::identity::Kernel) nothing.
pub(crate) fn open_with<'k, K: crate::identity::Kernel + Send + 'k>(
    kernel: K,
    id: ProcessId,
) -> Result<Option<Box<dyn OsProcess + 'k>>, OpenFailure> {
    #[cfg(target_os = "linux")]
    {
        Ok(linux::open::open_verified_with(&kernel, id)?
            .map(|pidfd| Box::new(linux::LinuxProcess::new(kernel, Some(id.pid()), pidfd)) as Box<dyn OsProcess + 'k>))
    }
    #[cfg(windows)]
    {
        Ok(windows::WindowsProcess::open(kernel, id)?.map(|p| Box::new(p) as Box<dyn OsProcess + 'k>))
    }
    #[cfg(target_os = "macos")]
    {
        Ok(macos::MacosProcess::open(kernel, id)?.map(|p| Box::new(p) as Box<dyn OsProcess + 'k>))
    }
}

/// Hard-kill the held process. Already gone: `Ok`.
pub(crate) fn kill(p: &dyn OsProcess) -> Result<(), Error> {
    // `Gone` and `Delivered` are both success: nothing is left for the caller to do.
    p.signal(Sig::Kill).map(|_: Sent| ())
}

/// Send the graceful termination signal to the held process, without waiting. Already gone: `Ok`.
#[cfg(unix)]
pub(crate) fn terminate(p: &dyn OsProcess) -> Result<(), Error> {
    p.signal(Sig::Graceful(crate::signal::Signal::Term)).map(|_: Sent| ())
}

/// There is no [`Sig`] to send for it on Windows: `Unsupported`.
#[cfg(windows)]
pub(crate) fn terminate(_p: &dyn OsProcess) -> Result<(), Error> {
    Err(Error::terminate_unsupported())
}