cosca 0.10.0

Unified cross-platform subprocess management: spawning, stdio, process trees, stable identity, and elevation.
Documentation
//! Pure parsers for `/proc/<pid>/stat` fields.
//!
//! The comm field (field 2) is paren-wrapped and may contain spaces and ')', so
//! the parsers anchor on the LAST ')': index 0 of the whitespace-split tail is
//! field 3 (state); `starttime` is field 22 (index 19).
//
// Compiled on every target (for host unit tests); only `linux.rs` calls these,
// so they are dead on non-Linux builds.
#![cfg_attr(
    not(target_os = "linux"),
    allow(
        dead_code,
        reason = "compiled on every host for pure-logic test coverage; the Linux backend is the only production caller"
    )
)]

fn tail(stat: &[u8]) -> Option<&str> {
    let close = stat.iter().rposition(|&b| b == b')')?;
    std::str::from_utf8(stat.get(close + 1..)?).ok()
}

/// Field 22 (`starttime`) as RAW jiffies since boot.
pub(crate) fn parse_starttime_jiffies(stat: &[u8]) -> Option<u64> {
    tail(stat)?.split_whitespace().nth(19)?.parse::<u64>().ok()
}

/// Field 3 (process state) as its single state character, e.g. `b'R'`, `b'Z'`.
pub(crate) fn parse_state(stat: &[u8]) -> Option<u8> {
    tail(stat)?.split_whitespace().next()?.bytes().next()
}

/// Field 4 (`ppid`, index 1 of the tail) — the parent pid. Used by the
/// containment tree-walk's `/proc` enumerator; comm-safe via the same anchor.
pub(crate) fn parse_ppid(stat: &[u8]) -> Option<u32> {
    tail(stat)?.split_whitespace().nth(1)?.parse::<u32>().ok()
}

/// Field 9 (`flags`, index 6 of the tail) — the task's `PF_*` flags. An unprivileged reader sees it
/// (not masked like the ptrace-gated fields).
pub(crate) fn parse_flags(stat: &[u8]) -> Option<u32> {
    tail(stat)?.split_whitespace().nth(6)?.parse::<u32>().ok()
}

/// `PF_EXITING`: `exit_signals` sets it, before the task's children are reparented
/// (`exit_notify`), so a read that shows it sees an exit under way while the children still name
/// the task's group as their parent. Measured on Linux 6.12.113, for a same-uid, an other-uid and a
/// non-root reader of a root-owned task: 60 of 60 held exits showed it before the reparent, and a
/// zombie keeps it. The exit also sets `0x8` and, once a zombie, `0x8000`; the test is the bit.
pub(crate) const PF_EXITING: u32 = 0x4;

/// Whether the task whose raw `stat` this is has begun to exit ([`PF_EXITING`] in its flags), and so
/// stays after it became a zombie. `None` for a record without a flags field.
pub(crate) fn exiting_from_stat(stat: &[u8]) -> Option<bool> {
    parse_flags(stat).map(|flags| flags & PF_EXITING != 0)
}

/// Field 5 (`pgrp`, index 2 of the tail) — the process-group id. Used by the
/// containment group-membership listing; comm-safe via the same anchor.
pub(crate) fn parse_pgrp(stat: &[u8]) -> Option<u32> {
    tail(stat)?.split_whitespace().nth(2)?.parse::<u32>().ok()
}

/// Field 20 (`num_threads`, index 17 of the tail) — the live threads of the process.
pub(crate) fn parse_num_threads(stat: &[u8]) -> Option<u64> {
    tail(stat)?.split_whitespace().nth(17)?.parse::<u64>().ok()
}

/// Decide whether a process is *running* from its raw `/proc/<pid>/stat` bytes: the
/// starttime token must match `start` (reject a reused PID) AND the state must not be zombie
/// ('Z') or dead ('X'/'x'). A zombie that still has other live threads is running: its leader
/// thread exited (`pthread_exit`) and the process has not, and the kernel hands its children to a
/// live thread, so their ppid stays the process's pid. An unparseable record, or a zombie's
/// unreadable thread count, is `Unknown`: we read the file, so the process is there, but not its
/// state. Pure, so it is host-testable.
pub(super) fn running_from_stat(stat: &[u8], ticks: u64) -> super::Liveness {
    use super::Liveness;
    match parse_starttime_jiffies(stat) {
        Some(j) if j == ticks => {}
        Some(_) => return Liveness::Dead, // reused PID
        None => return Liveness::Unknown, // unparseable — not evidence of death
    }
    match parse_state(stat) {
        Some(b'Z') => match parse_num_threads(stat) {
            Some(threads) if threads > 1 => Liveness::Alive,
            Some(_) => Liveness::Dead,
            None => Liveness::Unknown,
        },
        Some(b'X' | b'x') => Liveness::Dead,
        Some(_) => Liveness::Alive,
        None => Liveness::Unknown,
    }
}

/// The `stat` of a process in `state` that started at `starttime` (field 22, index 19 after the last
/// `)`): `pid (comm) STATE ppid pgroup session tty tpgid flags minflt cminflt majflt cmajflt utime
/// stime cutime cstime priority nice numthreads itrealvalue starttime ...`.
#[cfg(test)]
pub(crate) fn stat_fixture(state: &str, starttime: u64) -> Vec<u8> {
    format!("1234 (myproc) {state} 1 1234 1234 0 -1 4194560 100 0 0 0 1 2 0 0 20 0 1 0 {starttime} 0 0").into_bytes()
}

#[cfg(test)]
#[path = "stat_parse_tests.rs"]
mod stat_parse_tests;