cosca 0.10.0

Unified cross-platform subprocess management: spawning, stdio, process trees, stable identity, and elevation.
Documentation
//! Test-only record of every signal cosca sends to a process, and how it addressed it.
//!
//! An entry is written immediately AFTER the syscall, whatever the syscall answers: a `kill(2)`
//! that fails with `ESRCH` still records, so a test sees an attempt that reached the OS. A send
//! that was skipped leaves no record, so an entry is evidence the call was made, not that the
//! signal arrived: a test that needs the effect reads the target's status. A [`GroupStep`] send (to
//! a group, its leader or a member, signal 0 included) is written by
//! [`send_signal`](crate::containment::unix::send_signal) or
//! [`probe_signal`](crate::containment::unix::probe_signal) after the syscall returned, with the
//! signal number it handed the syscall. Where a test seam answers in the kernel's place, no syscall
//! is made, and the step is still recorded. The group steps and the identity-checked sends are two
//! logs; [`Capture::ordered_steps`] merges them in the order the thread took them.

use std::cell::RefCell;

use crate::signal::Sig;

/// What addressed the target.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[allow(dead_code, reason = "each platform and later unit feeds a subset")]
pub(crate) enum Via {
    Pidfd,
    Pid,
    Handle,
    Identity,
}

pub(crate) type Entry = (u32, Sig, Via);

/// A signal sent to a process after checking its identity: the pid and the signal number. Kept
/// apart from [`Entry`] so the by-handle log of the drops keeps its shape.
pub(crate) type IdentityEntry = (u32, i32);

/// One step of a send to a process group, in order: a check of the root, or a send.
#[cfg(unix)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum GroupStep {
    /// The root's pid was checked to still name its group.
    Check,
    /// The signal (its number) to the whole group.
    Group(Route, i32),
    /// The signal (its number) to the leader alone, after the group's was refused.
    Leader(Route, i32),
    /// A member's resend: the member's pid, and the signal's number.
    Member(Route, u32, i32),
}

#[cfg(unix)]
impl GroupStep {
    /// A send of signal 0, which asks whether its target exists and delivers nothing.
    fn is_probe(self) -> bool {
        matches!(
            self,
            GroupStep::Group(_, 0) | GroupStep::Leader(_, 0) | GroupStep::Member(_, _, 0)
        )
    }
}

/// Asserts that the first step is `signo` sent to the whole group through the root's pidfd, before
/// any resend, and that nothing went to the group by its number.
#[cfg(all(target_os = "linux", test))]
#[track_caller]
pub(crate) fn assert_group_signalled_first_through_the_pidfd(steps: &[GroupStep], signo: i32) {
    assert_eq!(steps.first(), Some(&GroupStep::Group(Route::Pidfd, signo)), "{steps:?}");
    assert!(
        !steps.iter().any(|s| matches!(s, GroupStep::Group(Route::Number, _))),
        "nothing went by the group's number: {steps:?}"
    );
}

/// How a [`GroupStep`] send named its target.
#[cfg(unix)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[allow(dead_code, reason = "only Linux sends through a pidfd")]
pub(crate) enum Route {
    Pidfd,
    Number,
}

/// One step in the order this thread took it, across the group steps and the identity-checked
/// sends, which are kept in separate logs.
#[cfg(unix)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum OrderedStep {
    Group(GroupStep),
    /// An identity-checked send: the pid, and the signal's number.
    Identity(u32, i32),
}

thread_local! {
    static LOG: RefCell<Option<Vec<Entry>>> = const { RefCell::new(None) };
    // Each record of the next two carries its place in this thread's one sequence.
    static BY_IDENTITY: RefCell<Option<Vec<(u64, IdentityEntry)>>> = const { RefCell::new(None) };
    #[cfg(unix)]
    static GROUP: RefCell<Option<Vec<(u64, GroupStep)>>> = const { RefCell::new(None) };
    #[cfg(unix)]
    static SEQUENCE: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
}

/// The next place in this thread's sequence of records.
#[cfg(unix)]
fn next_place() -> u64 {
    SEQUENCE.with(|next| {
        let place = next.get();
        next.set(place + 1);
        place
    })
}

/// Records one step of a send to a process group on this thread, if a [`Capture`] is live.
#[cfg(unix)]
pub(crate) fn record_group(step: GroupStep) {
    GROUP.with(|log| {
        if let Some(steps) = log.borrow_mut().as_mut() {
            steps.push((next_place(), step));
        }
    });
}

/// Records one identity-checked send attempt (`signo`), if a [`Capture`] is live.
#[cfg(unix)]
pub(crate) fn record_by_identity(pid: u32, signo: i32) {
    BY_IDENTITY.with(|log| {
        if let Some(entries) = log.borrow_mut().as_mut() {
            entries.push((next_place(), (pid, signo)));
        }
    });
}

/// Records one send attempt on this thread, if a [`Capture`] is live.
pub(crate) fn record(pid: u32, sig: Sig, via: Via) {
    LOG.with(|log| {
        if let Some(entries) = log.borrow_mut().as_mut() {
            entries.push((pid, sig, via));
        }
    });
}

/// Collects this thread's send attempts until dropped.
pub(crate) struct Capture(());

impl Capture {
    pub(crate) fn start() -> Capture {
        LOG.with(|log| {
            let mut log = log.borrow_mut();
            assert!(log.is_none(), "a send-log capture is already live on this thread");
            *log = Some(Vec::new());
        });
        BY_IDENTITY.with(|log| *log.borrow_mut() = Some(Vec::new()));
        #[cfg(unix)]
        GROUP.with(|log| *log.borrow_mut() = Some(Vec::new()));
        Capture(())
    }

    pub(crate) fn entries(&self) -> Vec<Entry> {
        LOG.with(|log| log.borrow().clone().expect("a live capture has a log"))
    }

    /// Whether `sig` was sent to `pid`, by whatever route: the send was made, which a root reaped
    /// before its status could be read still shows.
    #[cfg(feature = "tokio")]
    pub(crate) fn sent(&self, pid: u32, sig: Sig) -> bool {
        self.entries().iter().any(|&(p, s, _)| p == pid && s == sig)
    }
}

impl Capture {
    /// The identity-checked sends: every signal a held `os_process` sends, written inside that send
    /// (a pidfd's on Linux, an audit token's on macOS), whatever the kernel answered.
    #[cfg(unix)]
    pub(crate) fn by_identity(&self) -> Vec<IdentityEntry> {
        BY_IDENTITY.with(|log| {
            let log = log.borrow();
            log.as_ref()
                .expect("a live capture has a log")
                .iter()
                .map(|&(_, entry)| entry)
                .collect()
        })
    }

    /// The group steps (no signal-0 probe) and the identity-checked sends together, in the order
    /// this thread took them.
    #[cfg(unix)]
    pub(crate) fn ordered_steps(&self) -> Vec<OrderedStep> {
        let mut steps: Vec<(u64, OrderedStep)> = GROUP.with(|log| {
            let log = log.borrow();
            log.as_ref()
                .expect("a live capture has a log")
                .iter()
                .filter(|(_, step)| !step.is_probe())
                .map(|&(place, step)| (place, OrderedStep::Group(step)))
                .collect()
        });
        BY_IDENTITY.with(|log| {
            let log = log.borrow();
            let sends = log.as_ref().expect("a live capture has a log");
            steps.extend(
                sends
                    .iter()
                    .map(|&(place, (pid, signo))| (place, OrderedStep::Identity(pid, signo))),
            );
        });
        steps.sort_by_key(|&(place, _)| place);
        steps.into_iter().map(|(_, step)| step).collect()
    }

    /// Ends the capture: `Err` unless it holds an attempted send of `signo` (to a group, a group's leader, or
    /// a member by its identity), whatever the syscall answered. Lets a test's stop action fail by assertion
    /// when its send sent nothing. A check of the root is no send. A cgroup leaf's sends to its members are
    /// recorded elsewhere and are not seen here.
    #[cfg(unix)]
    pub(crate) fn require_a_send(self, signo: i32) -> Result<(), crate::error::Error> {
        let attempted = self.ordered_steps().into_iter().any(|step| match step {
            OrderedStep::Group(GroupStep::Group(_, sent) | GroupStep::Leader(_, sent)) => sent == signo,
            OrderedStep::Identity(_, sent) => sent == signo,
            OrderedStep::Group(_) => false,
        });
        if attempted {
            Ok(())
        } else {
            Err(crate::error::Error::Io(std::io::Error::other(format!(
                "no send of signal {signo} was attempted"
            ))))
        }
    }
}

impl Capture {
    /// The checks and the signals of the sends to process groups, in order: no signal-0 probe.
    #[cfg(unix)]
    pub(crate) fn group_steps(&self) -> Vec<GroupStep> {
        let mut steps = self.group_steps_with_probes();
        steps.retain(|step| !step.is_probe());
        steps
    }

    /// Every step of the sends to process groups, in order, the signal-0 probes included.
    #[cfg(unix)]
    pub(crate) fn group_steps_with_probes(&self) -> Vec<GroupStep> {
        GROUP.with(|log| {
            let log = log.borrow();
            log.as_ref()
                .expect("a live capture has a log")
                .iter()
                .map(|&(_, step)| step)
                .collect()
        })
    }
}

impl Drop for Capture {
    fn drop(&mut self) {
        LOG.with(|log| *log.borrow_mut() = None);
        BY_IDENTITY.with(|log| *log.borrow_mut() = None);
        #[cfg(unix)]
        GROUP.with(|log| *log.borrow_mut() = None);
    }
}