cosca 0.10.0

Unified cross-platform subprocess management: spawning, stdio, process trees, stable identity, and elevation.
Documentation
//! `OwnedChild` against a child this process traces (`TRACER` group; needs
//! `COSCA_TEST_TRACER_CONSENT=1`). Every fixture child is spawned under `spawn_lock`.
//!
//! Linux reports a ptrace stop to the tracer whatever the `waitid` options say
//! (`kernel/exit.c`, "Traditionally we see ptrace'd stopped tasks regardless of options"), as
//! `CLD_TRAPPED`, and a consuming `waitid` clears it. So a one-step reap of a child this process
//! traces would take the stop for an exit and steal the tracer's stop event.

#[cfg(target_os = "linux")]
use super::fixtures::{try_wait, wait_status, Blocker};
#[cfg(target_os = "linux")]
use crate::child::owned::{ChildWaitOutcome, State};
#[cfg(target_os = "linux")]
use crate::signal::Sig;
#[cfg(target_os = "linux")]
use crate::test_child::reaped_elsewhere::kill_own_child;
#[cfg(target_os = "linux")]
use crate::test_groups::{tracer_group, Group};
#[cfg(target_os = "linux")]
use crate::test_support::own_tracer;

/// `try_wait` on a child stopped under this process's `PTRACE_SEIZE` returns `None`, leaves the
/// state `N`, and leaves the stop for the tracer: the test's own `waitpid` then still gets it.
///
/// Mutants: a one-step consuming `waitid`, which returns `CLD_TRAPPED` and consumes it; a peek
/// without `WNOWAIT` (`src/wait/exit_only/linux.rs`), which consumes the stop yet still returns
/// `None`; a `try_wait` that caches a state. Each fails by assertion.
#[cfg(target_os = "linux")]
#[skuld::test]
fn try_wait_leaves_a_ptrace_stop_for_the_tracer(#[fixture(tracer_group)] _group: &Group) {
    use std::os::unix::process::ExitStatusExt as _;

    let b = Blocker::spawn();
    let pid = b.pid as libc::pid_t;
    own_tracer::seize_and_stop(pid);

    assert!(
        matches!(try_wait(&b.owned), Ok(ChildWaitOutcome::DeadlinePassed)),
        "a stop is not an exit"
    );
    assert!(matches!(b.owned.lock().state, State::N));

    // The stop is still there for the tracer. `WNOHANG`: the `WNOWAIT` peek above already saw it,
    // so a missing stop is an assertion failure here, never a wait that blocks forever.
    let mut status = 0;
    // SAFETY: `status` is a valid out-pointer.
    let reaped = unsafe { libc::waitpid(pid, &mut status, libc::WNOHANG | libc::__WALL) };
    assert_eq!(reaped, pid);
    assert!(
        libc::WIFSTOPPED(status),
        "try_wait consumed the tracer's stop: {status:#x}"
    );

    // SIGKILL sent by the test itself, never PTRACE_KILL (which before v5.19 only resumes a
    // PTRACE_EVENT_STOP). Not the handle's `kill`: a send that went nowhere would leave this
    // tracee stopped for the `wait` below to block on, and ending it by closing its stdin does
    // not wake a ptrace stop.
    kill_own_child(b.pid);
    assert_eq!(wait_status(&b.owned).signal(), Some(libc::SIGKILL));
}

/// The handle's `kill` ends a child stopped under this process's `PTRACE_SEIZE`: a `SIGKILL` wakes
/// a ptrace stop. The test then resumes the tracee as its tracer (`ESRCH`: the kill already woke
/// it) and only then ends its stdin, so a kill that was lost leaves a resumed `cat` that reads EOF
/// and exits 0, and the assertion on the status fails; nothing waits on the lost kill.
#[cfg(target_os = "linux")]
#[skuld::test]
fn kill_ends_a_child_stopped_for_its_tracer(#[fixture(tracer_group)] _group: &Group) {
    use std::os::unix::process::ExitStatusExt as _;

    let mut b = Blocker::spawn();
    let pid = b.pid as libc::pid_t;
    own_tracer::seize_and_stop(pid);

    b.owned.signal(Sig::Kill).expect("kill");
    own_tracer::resume_unless_dying(pid);
    b.end_child();
    assert_eq!(
        wait_status(&b.owned).signal(),
        Some(libc::SIGKILL),
        "the handle's kill did not end the stopped tracee"
    );
}

// macOS: a child this process traces itself =====
//
// macOS refuses `ptrace` attach with `EPERM` to an ad-hoc signed tracer unless the tracer carries
// `com.apple.security.cs.debugger`. So each case re-execs a copy of this test binary signed with
// it, in a fresh process: the tracer is the whole process, not a thread.

#[cfg(target_os = "macos")]
mod macos {
    use std::time::Duration;

    use super::super::fixtures::{try_wait, wait_status, Blocker};
    use crate::child::owned::{ChildWaitOutcome, State};
    use crate::identity::{FakeKernel, HostKernel, Kernel as _, UniqRead};
    use crate::os_process::child::ExitRecord;
    use crate::signal::Sig;
    use crate::test_child::{run_fixture_output_within, step, watchdog};
    use crate::test_groups::{tracer_group, Group};
    use crate::test_support::tracer::{attach_settled, debugger_signed_copy, settled_stop, AttachError};

    const MARKER: &str = "COSCA_TESTCFG_SHARED_TRACER";

    /// The failure bound of the driver's wait for its fixture, which aborts from its own
    /// [`BOUND`] watchdog well before.
    const DRIVER_BOUND: Duration = Duration::from_secs(12);

    /// The fixture's own failure bound.
    const BOUND: Duration = Duration::from_secs(8);

    /// Run `fixture` in a re-exec of a debugger-entitled copy of this binary.
    pub(super) fn run_signed(fixture: &str) {
        let dir = tempfile::tempdir().expect("tempdir");
        let exe = debugger_signed_copy(dir.path());
        match run_fixture_output_within(fixture, MARKER, &exe, DRIVER_BOUND) {
            Ok(output) => crate::test_child::assert_fixture_passed(fixture, &output),
            Err(output) => panic!(
                "fixture {fixture} was still running after {DRIVER_BOUND:?}, so it was killed:\n{}\n{}",
                String::from_utf8_lossy(&output.stdout),
                String::from_utf8_lossy(&output.stderr)
            ),
        }
    }

    /// Attach to `blocker`'s child and wait, without consuming it, until its stop has settled: a
    /// request before the tracee's threads have parked wakes nothing ([`attach_settled`]).
    ///
    /// Fixtures end the child with [`kill_stopped`], never by resuming it: a `cat` blocked in
    /// `read` when it resumes gets `EINTR`, prints `Interrupted system call` and exits 1. And the
    /// attach is `PT_ATTACH`: under `PT_ATTACHEXC` the same `EINTR` kills a blocked `cat` before it
    /// ever stops, and no stop comes.
    fn attach_and_confirm_stop(blocker: &Blocker) {
        step("attach and settle");
        match attach_settled(blocker.pid) {
            Ok(()) => {}
            Err(AttachError::Errno(e)) => panic!("attach: {}", std::io::Error::from_raw_os_error(e)),
            Err(AttachError::Exited { code, status }) => {
                panic!("the tracee exited before it stopped (si_code {code}, si_status {status})")
            }
        }
    }

    /// End a child stopped by [`attach_and_confirm_stop`]. `PT_KILL` does it: it posts `SIGKILL`
    /// and releases the stopped thread, which then delivers the pending `SIGKILL`
    /// (xnu-12377.121.6 `kern_sig.c`, "Necessary for PT_KILL"; `mach_process.c` `PT_KILL`, then
    /// `resume`).
    ///
    /// The handle's `kill` does not: a `SIGKILL` to a traced child is taken by its tracer as a
    /// stop, and posted only to one that already is stopped (`kern_sig.c`). A debugger
    /// delays a kill and cannot cancel it. So the child is asserted still stopped after `kill`,
    /// until `PT_KILL`.
    fn kill_stopped(blocker: &Blocker) {
        let pid = blocker.pid;
        blocker.owned.signal(Sig::Kill).expect("kill");
        let stopped = settled_stop(pid);
        assert!(
            matches!(stopped, Ok(Some(_))),
            "the handle's SIGKILL ended or released a traced child: {stopped:?}"
        );
        // SAFETY: a plain ptrace request on this test's own child.
        let rc = unsafe { libc::ptrace(libc::PT_KILL, pid as libc::pid_t, std::ptr::null_mut(), 0) };
        assert_eq!(rc, 0, "PT_KILL: {}", std::io::Error::last_os_error());
    }

    fn assert_killed(status: std::process::ExitStatus) {
        assert_eq!(
            std::os::unix::process::ExitStatusExt::signal(&status),
            Some(libc::SIGKILL),
            "{status:?}"
        );
    }

    /// `try_wait` on a child stopped under this process's own `PT_ATTACH` returns `None` and
    /// leaves the state `N`.
    ///
    /// Mutant: a `waitpid(WNOHANG)` reap returns the stop as a status and writes `E`.
    #[skuld::test]
    fn try_wait_on_a_child_this_process_traces_returns_none_while_it_is_stopped(
        #[fixture(tracer_group)] _group: &Group,
    ) {
        if !crate::test_child::is_marked_fixture_reexec(MARKER) {
            return run_signed(crate::test_child::fixture_path!(
                try_wait_on_a_child_this_process_traces_returns_none_while_it_is_stopped,
                Group
            ));
        }
        let _dog = watchdog("try_wait on a stopped tracee", BOUND);
        step("spawn");
        let b = Blocker::spawn();
        attach_and_confirm_stop(&b);
        step("try_wait");
        assert!(
            matches!(try_wait(&b.owned), Ok(ChildWaitOutcome::DeadlinePassed)),
            "a stop is not an exit"
        );
        assert!(matches!(b.owned.lock().state, State::N));
        kill_stopped(&b);
        assert_killed(wait_status(&b.owned));
    }

    /// A child this process traces is reaped fully by the end of its handle: XNU needs two reaps,
    /// because the first only hands the zombie back to this same process (`reap_child_locked` in
    /// xnu-12377.121.6's `kern_exit.c`), and the second peek consumes it. The wait before it
    /// consumes nothing.
    ///
    /// Mutant: one consuming reap leaves the zombie, which the final peek still finds.
    #[skuld::test]
    fn a_child_this_process_traces_is_reaped_fully(#[fixture(tracer_group)] _group: &Group) {
        if !crate::test_child::is_marked_fixture_reexec(MARKER) {
            return run_signed(crate::test_child::fixture_path!(
                a_child_this_process_traces_is_reaped_fully,
                Group
            ));
        }
        let _dog = watchdog("reaped fully", BOUND);
        step("spawn");
        let b = Blocker::spawn();
        attach_and_confirm_stop(&b);
        kill_stopped(&b);
        step("wait");
        assert_killed(wait_status(&b.owned));
        let pid = b.pid;
        step("drop");
        drop(b);
        // SAFETY: an all-zero `siginfo_t` is valid, and `waitid` writes only into it.
        let mut info: libc::siginfo_t = unsafe { std::mem::zeroed() };
        let r = unsafe {
            libc::waitid(
                libc::P_PID,
                pid as libc::id_t,
                &mut info,
                libc::WEXITED | libc::WNOHANG | libc::WNOWAIT,
            )
        };
        assert_eq!(r, -1);
        assert_eq!(std::io::Error::last_os_error().raw_os_error(), Some(libc::ECHILD));
    }

    /// A refused identity read in the second reap, at the end of the handle, neither panics nor
    /// touches the state: the wait's status is kept, and one `warn` names the pid.
    ///
    /// Mutant: a second reap that panics on a refused identity read.
    #[skuld::test]
    fn a_failed_start_read_in_the_second_reap_neither_panics_nor_leaves_n(#[fixture(tracer_group)] _group: &Group) {
        if !crate::test_child::is_marked_fixture_reexec(MARKER) {
            return run_signed(crate::test_child::fixture_path!(
                a_failed_start_read_in_the_second_reap_neither_panics_nor_leaves_n,
                Group
            ));
        }
        crate::log_capture::install();
        let _dog = watchdog("failed start read", BOUND);
        step("spawn");
        let (b, kernel) = Blocker::spawn_over(|_, _| FakeKernel::over(&HostKernel));
        attach_and_confirm_stop(&b);
        let marker = format!("second reap of pid {}", b.pid);
        let mark = crate::log_capture::mark();
        kill_stopped(&b);
        assert_killed(wait_status(&b.owned));
        assert!(
            matches!(b.owned.lock().state, State::Exited(ExitRecord::Status(_))),
            "the wait's status is cached"
        );
        assert_eq!(
            crate::log_capture::levels_since(mark, &marker),
            Vec::<log::Level>::new(),
            "the wait made no second reap"
        );
        // The end of the handle reads the child's id twice: the first reap's peek, which finds it, and
        // the second reap's, which is refused.
        kernel.state_unique_info(b.pid, HostKernel.unique_info(b.pid));
        kernel.state_unique_info(b.pid, UniqRead::Refused(libc::EPERM));
        drop(b);
        assert_eq!(crate::log_capture::levels_since(mark, &marker), vec![log::Level::Warn]);
    }
}