cosca 0.10.0

Unified cross-platform subprocess management: spawning, stdio, process trees, stable identity, and elevation.
Documentation
//! macOS `exit_only`: `waitid(P_PID, ...)` by number, on a child that is this process's own and
//! unreaped. Never `waitpid`: XNU's `wait4` reports a stopped child to its tracer as if
//! `WUNTRACED` were set (`kern_exit.c:3028-3041`), while `waitid` reports stops only under
//! `WSTOPPED` (`:3270-3277`).

use std::io;

use crate::identity::{held_by, Held, Kernel, UniqRead, LAUNCHD};

use super::{exit_record_of, is_exit_record, Reap, Target};
use crate::os_process::child::{Foreign, PeekOutcome};

fn parts<'a>(target: &Target<'a>) -> (&'a dyn Kernel, u32, Option<u64>) {
    match target {
        Target::Pid { pid, unique, kernel } => (*kernel, *pid, *unique),
    }
}

fn is_echild(e: &io::Error) -> bool {
    e.raw_os_error() == Some(libc::ECHILD)
}

/// The non-consuming look, `kernel`'s peek, with no start check.
fn peek_raw(kernel: &dyn Kernel, pid: u32) -> io::Result<PeekOutcome> {
    match kernel.peek(pid) {
        Ok(Some(record)) if is_exit_record(record.si_code) => Ok(PeekOutcome::Exit(exit_record_of(record))),
        Ok(_) => Ok(PeekOutcome::Running),
        Err(e) if is_echild(&e) => Ok(PeekOutcome::Foreign(Foreign::Gone)),
        Err(e) => Err(e),
    }
}

/// Whether `pid`'s unique id is `unique`.
enum IdCheck {
    Matches,
    Other,
    Gone,
    /// The read failed with this errno (a MACF denial).
    Unreadable(i32),
}

fn check_unique(kernel: &dyn Kernel, pid: u32, unique: u64) -> IdCheck {
    match kernel.unique_info(pid) {
        UniqRead::Found(now) if now.unique_id == unique => IdCheck::Matches,
        UniqRead::Found(_) => IdCheck::Other,
        UniqRead::Gone => IdCheck::Gone,
        UniqRead::Refused(errno) => IdCheck::Unreadable(errno),
    }
}

pub(super) fn peek(target: &Target<'_>) -> io::Result<PeekOutcome> {
    peek_with(target, false)
}

/// [`peek`]; with `verified`, a `Running` child whose id cannot be read is an error.
pub(super) fn peek_with(target: &Target<'_>, verified: bool) -> io::Result<PeekOutcome> {
    peek_holder(target, verified).map(|(peeked, _)| peeked)
}

/// [`peek_with`], and the tracer that holds the child when the verdict is `Running` because a
/// process other than this one and launchd holds it.
pub(super) fn peek_holder(target: &Target<'_>, verified: bool) -> io::Result<(PeekOutcome, Option<u32>)> {
    let (kernel, pid, unique) = parts(target);
    let peeked = peek_raw(kernel, pid)?;
    let Some(unique) = unique else {
        return Ok((peeked, None));
    };
    match peeked {
        PeekOutcome::Exit(_) => match check_unique(kernel, pid, unique) {
            IdCheck::Matches => Ok((peeked, None)),
            IdCheck::Other => Ok((PeekOutcome::Foreign(Foreign::Other), None)),
            IdCheck::Gone => Ok((PeekOutcome::Foreign(Foreign::Gone), None)),
            // The read was refused (a MACF denial): an exit that cannot be tied to the child is not
            // consumed by a bare pid. The errno stays in the error, so `EPERM` stays
            // `PermissionDenied`.
            IdCheck::Unreadable(errno) => Err(crate::error::io_context(
                format!("pid {pid}: its identity could not be read; its exit was not consumed"),
                io::Error::from_raw_os_error(errno),
            )),
        },
        // `waitid` found a child of ours that has not exited. A foreign reap followed by a reuse
        // of the pid by another child of ours also looks like this, so the id decides.
        PeekOutcome::Running => match check_unique(kernel, pid, unique) {
            IdCheck::Other => Ok((PeekOutcome::Foreign(Foreign::Other), None)),
            // `waitid` found the child running and the id read finds no such process: it was
            // reaped in between, so nothing is left to call running.
            IdCheck::Gone => Ok((PeekOutcome::Foreign(Foreign::Gone), None)),
            IdCheck::Matches => Ok((peeked, None)),
            IdCheck::Unreadable(_) if !verified => Ok((peeked, None)),
            IdCheck::Unreadable(errno) => Err(crate::error::io_context(
                format!("pid {pid}: its identity could not be read; it cannot be shown to be ours"),
                io::Error::from_raw_os_error(errno),
            )),
        },
        // `ECHILD` is not proof of a reap: while a tracer holds our child the parent's `waitid`
        // answers `ECHILD` (`src/test_support/tracer.rs`), and the tracer's hand-back re-sends
        // `NOTE_EXIT`. The pid names our child and a live process other than launchd holds it:
        // running, held by that tracer. No `NOTE_EXIT` of the child's reaches us before the
        // hand-back, so a kqueue wait also watches the tracer's exit (`wait::macos::TracerWatch`).
        // A child held by launchd is a zombie (or a child mid-exit) whose tracer died:
        // XNU reparents it to launchd and keeps `p_oppid` naming us (xnu-12377.121.6
        // `kern_exit.c:2612-2613` and `:2748`, which sends the `SIGCHLD` to launchd). It comes
        // back to us only if launchd waits on it: `reap_child_locked` then finds `p_oppid`, hands
        // it back and re-sends `NOTE_EXIT` (`:2864-2912`). On CI launchd never did, in a 30 s
        // window, so it is reported apart, as `Orphaned`: not ours to reap, and its fate is `Gone`
        // (see `Foreign::fate`). The sync child's later `wait` or `try_wait` still reaps the zombie
        // if that hand-back ever comes. A spawn that meets it fails with its child `Gone`, and its
        // child (dropped) is not reaped by pid, so a hand-back leaves the zombie.
        PeekOutcome::Foreign(Foreign::Gone) => match held_by(kernel, pid, unique) {
            Held::Other => Ok((PeekOutcome::Foreign(Foreign::Other), None)),
            Held::Parent(ppid) if ppid == LAUNCHD => Ok((PeekOutcome::Foreign(Foreign::Orphaned), None)),
            // A tracer detached between the two reads: our child again.
            Held::Parent(ppid) if ppid == std::process::id() => Ok((PeekOutcome::Running, None)),
            Held::Parent(tracer) => Ok((PeekOutcome::Running, Some(tracer))),
            // `ESRCH` with `arg = 1` is a reap: a process resolves from `P_REF_DEAD` until then.
            Held::Gone => Ok((peeked, None)),
            // A MACF denial: not ours to see. A caller that treats `Running` as "this is our
            // child" cannot tell a reap from a denial, so it gets the error, with the errno.
            Held::Refused(_) if !verified => Ok((peeked, None)),
            Held::Refused(errno) => Err(crate::error::io_context(
                format!("pid {pid}: its identity could not be read; it cannot be shown to be reaped"),
                io::Error::from_raw_os_error(errno),
            )),
        },
        PeekOutcome::Foreign(Foreign::Other | Foreign::Orphaned) => Ok((peeked, None)),
    }
}

/// The consuming `kernel.consume`. `Ok(None)` when it finds nothing.
fn consume(kernel: &dyn Kernel, pid: u32) -> io::Result<Option<crate::identity::Record>> {
    kernel.consume(pid)
}

pub(super) fn try_reap(target: &Target<'_>) -> io::Result<Reap> {
    let (kernel, pid, unique) = parts(target);
    match peek(target)? {
        PeekOutcome::Exit(_) => {}
        PeekOutcome::Running => return Ok(Reap::Running),
        PeekOutcome::Foreign(f) => return Ok(Reap::Foreign(f)),
    }
    // Our own zombie's unique id, read before the first reap: the first reap does not change it
    // (`proc_reparentlocked` returns early when the parent is unchanged, `kern_exit.c:3411`),
    // and the second peek checks it.
    let second_unique = unique.or_else(|| match kernel.unique_info(pid) {
        UniqRead::Found(now) => Some(now.unique_id),
        UniqRead::Gone | UniqRead::Refused(_) => None,
    });
    let first = match consume(kernel, pid) {
        Ok(Some(record)) => exit_record_of(record),
        // A by-pid consume is never pinned: a foreign reap between the peek and here, then a
        // reuse of the pid by a child that is still running, finds nothing. A reuser that is our
        // own child and already a zombie has its exit record consumed instead: the id check above
        // is a check, not a pin.
        Ok(None) => return Ok(Reap::Foreign(Foreign::Gone)),
        Err(e) if is_echild(&e) => return Ok(Reap::Foreign(Foreign::Gone)),
        Err(e) => return Err(e),
    };
    second_reap(kernel, pid, second_unique);
    Ok(Reap::Reaped(first))
}

/// The second peek-and-consume every first reap is followed by. When this process traces its own
/// child, `p_oppid == p_ppid`: the first consuming reap only reparents the zombie to this same
/// process, re-sends `NOTE_EXIT` and returns before it reaps (`kern_exit.c:2721-2773`), so the
/// zombie is still there. Not gated on a tracer: for an untraced child the peek answers `ECHILD`
/// and this is a no-op.
///
/// The first status is already in hand, so nothing here panics: every outcome is a quiet skip
/// or a `warn`.
pub(crate) fn second_reap(kernel: &dyn Kernel, pid: u32, unique: Option<u64>) {
    match peek_raw(kernel, pid) {
        Ok(PeekOutcome::Exit(_)) => {}
        Ok(PeekOutcome::Running) => {
            log::debug!("second reap of pid {pid}: nothing to consume");
            return;
        }
        // The first consume was this handle's, so an untraced child is gone, not reaped by another:
        // a peek that answers `Foreign` (`peek_raw` maps `ECHILD` to it) finds nothing left to
        // consume.
        Ok(PeekOutcome::Foreign(_)) => {
            log::debug!("second reap of pid {pid}: nothing left to consume");
            return;
        }
        Err(e) => {
            log::warn!(
                "second reap of pid {pid}: peek failed ({report}); a zombie may be left",
                report = crate::error::Report(&e)
            );
            return;
        }
    }
    // A consume by a bare pid could take a reusing process's exit record.
    let Some(unique) = unique else {
        log::warn!("second reap of pid {pid}: no identity to check it against; a zombie may be left");
        return;
    };
    match check_unique(kernel, pid, unique) {
        IdCheck::Matches => {}
        IdCheck::Other | IdCheck::Gone => {
            log::debug!("second reap of pid {pid}: the pid names another process now");
            return;
        }
        IdCheck::Unreadable(_) => {
            log::warn!("second reap of pid {pid}: its identity could not be read; a zombie may be left");
            return;
        }
    }
    match consume(kernel, pid) {
        Ok(_) => {}
        Err(e) if is_echild(&e) => log::debug!("second reap of pid {pid}: already reaped elsewhere"),
        Err(e) => log::warn!(
            "second reap of pid {pid} failed ({report}); a zombie may be left",
            report = crate::error::Report(&e)
        ),
    }
}