cosca 0.9.0

Unified cross-platform subprocess management: spawning, stdio, process trees, stable identity, and elevation.
Documentation
//! `sysctl(KERN_PROC_PID)` / `kinfo_proc` — the BSD interface that resolves EPERM-hidden
//! cross-user processes (libproc's `PROC_PIDTBSDINFO` does not), and reads a zombie's `p_stat`
//! and `p_flag`. libc has no apple
//! definition for these structs, so this is a minimal faithful local one. Only
//! `p_un.p_starttime`, `p_stat`, `p_oppid` and `eproc.e_ppid` are read, and in tests `eproc.e_jobc`;
//! everything else is layout.
//! Layout is triple-checked: the compile-time size tripwires below, the kernel-size oracle,
//! and the token-vs-libproc / ppid-vs-libproc oracles (kinfo_tests.rs).

use super::super::{RawPid, Resolved};
#[cfg(test)]
use super::kernel::Kernel;

/// `struct kinfo_proc` (LP64): `extern_proc` head + opaque `eproc` tail.
#[repr(C)]
pub(crate) struct kinfo_proc {
    pub(crate) kp_proc: extern_proc,
    kp_eproc: [u8; 352],
}

impl kinfo_proc {
    /// Byte offset of `eproc.e_ppid` within the opaque `kp_eproc` tail (`struct eproc`:
    /// `e_paddr` + `e_sess` pointers, then `struct _pcred e_pcred`, `struct _ucred e_ucred`,
    /// `struct vmspace e_vm`, then `e_ppid`). Determined two ways before landing here — an
    /// `offsetof` probe compiled against Apple's real `sys/sysctl.h`, and a live `sysctl`
    /// call compared against `getppid()` — and re-checked on every test run by
    /// `sysctl_e_ppid_matches_libproc_across_the_live_process_table` (kinfo_tests.rs), the
    /// permanent oracle: a future SDK layout drift fails that test rather than silently
    /// misreading ppids.
    const E_PPID_OFFSET: usize = 264;

    /// `eproc.e_ppid` — the parent pid the kernel recorded in this snapshot. A checked-offset
    /// read rather than fielding the rest of `eproc`: nothing else in it is needed, and every
    /// additional fielded sub-struct (`_pcred`, `_ucred`, `vmspace`, ...) would be more
    /// hand-copied kernel ABI to keep in sync for zero benefit (see the module doc).
    pub(super) fn e_ppid(&self) -> libc::pid_t {
        const LEN: usize = std::mem::size_of::<libc::pid_t>();
        let bytes: [u8; LEN] = self.kp_eproc[kinfo_proc::E_PPID_OFFSET..kinfo_proc::E_PPID_OFFSET + LEN]
            .try_into()
            .expect("kp_eproc is 352 bytes; E_PPID_OFFSET + LEN fits with room to spare (see the tripwire below)");
        libc::pid_t::from_ne_bytes(bytes)
    }
}

/// `e_jobc` is read by the tracer helper's tests (`test_support::tracer_tests`) for their
/// preconditions.
#[cfg(test)]
impl kinfo_proc {
    /// Byte offset of `eproc.e_jobc` within `kp_eproc`: after `e_ppid` and `e_pgid`
    /// (`offsetof` probe against Apple's `sys/sysctl.h`, arm64 and x86_64).
    const E_JOBC_OFFSET: usize = 272;

    /// `eproc.e_jobc`: the group's `pg_jobc`, its members whose parent is in another group of the
    /// same session. 0 means the group is orphaned.
    pub(crate) fn e_jobc(&self) -> i16 {
        let at = kinfo_proc::E_JOBC_OFFSET;
        i16::from_ne_bytes(self.kp_eproc[at..at + 2].try_into().expect("2 bytes"))
    }

    fn set_e_ppid(&mut self, ppid: libc::pid_t) {
        let at = kinfo_proc::E_PPID_OFFSET;
        self.kp_eproc[at..at + std::mem::size_of::<libc::pid_t>()].copy_from_slice(&ppid.to_ne_bytes());
    }

    /// The host's record of the live process `pid`, stating the parent it had when a tracer attached
    /// (`oppid`) and the parent it has now (`ppid`).
    pub(crate) fn of_host_held_by(pid: RawPid, oppid: libc::pid_t, ppid: libc::pid_t) -> kinfo_proc {
        let (Resolved::Found(mut record), _) = super::kernel::HostKernel.kinfo(pid) else {
            panic!("pid {pid} is live and has a kinfo_proc");
        };
        record.kp_proc.p_oppid = oppid;
        record.set_e_ppid(ppid);
        record
    }

    /// The host's record of the live process `pid`, stating its exit: `P_WEXIT` set when `begun` and
    /// clear otherwise, and `p_stat` `SRUN` either way, as measured at every `EPERM` the token send
    /// answered to an exiting child (the process is not yet a zombie).
    pub(crate) fn of_host_with_exit(pid: RawPid, begun: bool) -> kinfo_proc {
        let (Resolved::Found(mut record), _) = super::kernel::HostKernel.kinfo(pid) else {
            panic!("pid {pid} is live and has a kinfo_proc");
        };
        record.kp_proc.p_stat = libc::SRUN as libc::c_char;
        if begun {
            record.kp_proc.p_flag |= P_WEXIT;
        } else {
            record.kp_proc.p_flag &= !P_WEXIT;
        }
        record
    }
}

// E_PPID_OFFSET must stay inside the opaque tail it reads from - a compile-time companion to
// the two size tripwires below, same reasoning.
const _: () = assert!(kinfo_proc::E_PPID_OFFSET + std::mem::size_of::<libc::pid_t>() <= 352);

/// `struct extern_proc` (LP64 user copy, from XNU's proc.h). Kernel pointers are
/// represented as `u64` (they are opaque user_addr_t values in the sysctl copy).
#[repr(C)]
pub(crate) struct extern_proc {
    pub(crate) p_un: p_un,
    p_vmspace: u64,
    p_sigacts: u64,
    pub(crate) p_flag: libc::c_int,
    pub(crate) p_stat: libc::c_char,
    pub(crate) p_pid: libc::pid_t,
    /// The parent at a tracer's attach, which the tracer's detach restores (xnu `mach_process.c`).
    pub(crate) p_oppid: libc::pid_t,
    p_dupfd: libc::c_int,
    user_stack: u64,
    exit_thread: u64,
    p_debugger: libc::c_int,
    sigwait: libc::c_int, // boolean_t
    p_estcpu: libc::c_uint,
    p_cpticks: libc::c_int,
    p_pctcpu: u32, // fixpt_t
    p_wchan: u64,
    p_wmesg: u64,
    p_swtime: libc::c_uint,
    p_slptime: libc::c_uint,
    p_realtimer: itimerval,
    p_rtime: libc::timeval,
    p_uticks: u64,
    p_sticks: u64,
    p_iticks: u64,
    p_traceflag: libc::c_int,
    p_tracep: u64,
    p_siglist: libc::c_int,
    p_textvp: u64,
    p_holdcnt: libc::c_int,
    p_sigmask: u32, // sigset_t
    p_sigignore: u32,
    p_sigcatch: u32,
    p_priority: u8,
    p_usrpri: u8,
    p_nice: libc::c_char,
    p_comm: [libc::c_char; 17], // MAXCOMLEN + 1
    p_pgrp: u64,
    p_addr: u64,
    p_xstat: u16,
    p_acflag: u16,
    p_ru: u64,
}

#[repr(C)]
pub(crate) union p_un {
    p_st1: run_sleep_queue,
    pub(crate) p_starttime: libc::timeval,
}

#[repr(C)]
#[derive(Clone, Copy)]
struct run_sleep_queue {
    p_forw: u64,
    p_back: u64,
}

#[repr(C)]
struct itimerval {
    it_interval: libc::timeval,
    it_value: libc::timeval,
}

// Compile-time layout tripwire: sizeof(struct kinfo_proc) == 648 on LP64 darwin (ps and
// libtop hard-code the same). The kernel-size oracle in kinfo_tests.rs re-checks this
// against the running kernel.
const _: () = assert!(std::mem::size_of::<kinfo_proc>() == 648);
const _: () = assert!(std::mem::size_of::<extern_proc>() == 296);

/// `p_flag`'s "system process" bit, source-verified against the Xcode Command Line Tools
/// SDK: `#define P_SYSTEM 0x00000200` in `usr/include/sys/proc.h`. xnu's `killpg1` excludes
/// it from a process-group signal alongside — but independently of — `initproc` (pid 1),
/// confirmed against xnu's own `bsd/kern/kern_sig.c`. `containment::unix::group` restates
/// both exclusions (`excluded_from_sigkill_resend`). `kinfo_tests.rs` cross-checks this bit's
/// value against a second, independently-issued sysctl query and, where a live process allows
/// it, `proc_pidinfo`'s own `PROC_FLAG_SYSTEM` bit.
pub(crate) const P_SYSTEM: libc::c_int = 0x00000200;

/// `kinfo_proc`'s `p_flag` bit for a process that has begun to exit: `#define P_WEXIT
/// 0x00002000` in the SDK's `usr/include/sys/proc.h`. XNU sets it from `P_LEXIT`, which is never
/// cleared. It shows before the process's children are reparented (measured on macOS 15.7.9, 15.8.2 and
/// 26.7.2; 14, the floor, is not measurable on CI), so a read that finds it clear met a process none of
/// whose children its exit had moved.
pub(crate) const P_WEXIT: libc::c_int = 0x0000_2000;

/// How far a process's exit has gone, as `kinfo_proc` shows it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ExitState {
    /// `P_WEXIT` is clear and the process is not a zombie.
    Running,
    /// `P_WEXIT` is set and the process is not yet a zombie.
    Exiting,
    /// `p_stat` is `SZOMB`: exited and not reaped.
    Zombie,
}

/// The [`ExitState`] of a process that `kinfo_proc` shows with `p_stat` and `p_flag`. A zombie is
/// a zombie whether or not `P_WEXIT` shows (XNU sets `P_LEXIT` first, but the state is the stronger
/// fact).
pub(crate) fn exit_state(p_stat: libc::c_char, p_flag: libc::c_int) -> ExitState {
    if p_stat as u32 == libc::SZOMB {
        ExitState::Zombie
    } else if p_flag & P_WEXIT != 0 {
        ExitState::Exiting
    } else {
        ExitState::Running
    }
}

/// Whether the exit has begun: [`ExitState::Exiting`] or [`ExitState::Zombie`].
pub(crate) fn exit_begun(p_stat: libc::c_char, p_flag: libc::c_int) -> bool {
    exit_state(p_stat, p_flag) != ExitState::Running
}

/// [`Kernel::kinfo`] as the host kernel answers it: the `sysctl` itself, with the failure that left
/// the read `Unknown`.
pub(super) fn host_kinfo(pid: RawPid) -> (Resolved<kinfo_proc>, Option<std::io::Error>) {
    let mut mib = [libc::CTL_KERN, libc::KERN_PROC, libc::KERN_PROC_PID, pid as libc::c_int];
    loop {
        let mut info: kinfo_proc = unsafe { std::mem::zeroed() };
        let mut size = std::mem::size_of::<kinfo_proc>();
        // SAFETY: `info` and `size` describe one kinfo_proc; sysctl writes at most `size`.
        let rc = unsafe {
            libc::sysctl(
                mib.as_mut_ptr(),
                mib.len() as libc::c_uint,
                &mut info as *mut _ as *mut libc::c_void,
                &mut size,
                std::ptr::null_mut(),
                0,
            )
        };
        let called = if rc == 0 {
            Ok(size)
        } else {
            Err(std::io::Error::last_os_error())
        };
        return match classify(pid, called) {
            SysctlOutcome::Retry => continue,
            SysctlOutcome::Gone => (Resolved::Gone, None),
            SysctlOutcome::Refused(e) => {
                log::debug!(
                    "sysctl(KERN_PROC_PID, {pid}) refused: {report}",
                    report = crate::error::Report(&e)
                );
                (Resolved::Unknown, Some(e))
            }
            SysctlOutcome::Violation { message, error } => {
                super::contract_violation(format_args!("{message}"));
                (Resolved::Unknown, Some(error))
            }
            SysctlOutcome::Record => (Resolved::Found(info), None),
        };
    }
}

/// What one `sysctl(KERN_PROC_PID)` call's result means.
#[derive(Debug)]
enum SysctlOutcome {
    /// `EINTR`: ask again.
    Retry,
    /// The OS positively says there is no such process: `ESRCH`, or an empty reply.
    Gone,
    /// A sandbox or hardened runtime refused the query: the DESIGNED `Unknown`, not a contract
    /// violation.
    Refused(std::io::Error),
    /// The kernel broke the contract: what to trace, and the error the read answers, which keeps a
    /// failure's own errno.
    Violation { message: String, error: std::io::Error },
    /// A record of exactly our `kinfo_proc`'s size.
    Record,
}

/// What `called`, the bytes the sysctl wrote or the error it failed with, means for `pid`.
///
/// `ENOMEM` and `EINVAL` are neither race- nor permission-reachable. `ENOMEM` in particular is the ONLY
/// runtime detector for a kernel `kinfo_proc` that has grown past our 648-byte definition: it fails
/// before the size check is ever reached, and the compile-time size assert cannot fire because the Rust
/// definition is what stayed still. A record of another size is layout drift: never trusted.
fn classify(pid: RawPid, called: std::io::Result<usize>) -> SysctlOutcome {
    match called {
        Err(e) => match e.raw_os_error() {
            Some(libc::EINTR) => SysctlOutcome::Retry,
            Some(libc::ESRCH) => SysctlOutcome::Gone,
            Some(libc::EPERM | libc::EACCES) => SysctlOutcome::Refused(e),
            _ => SysctlOutcome::Violation {
                message: format!(
                    "sysctl(KERN_PROC_PID, {pid}) failed: {report}",
                    report = crate::error::Report(&e)
                ),
                error: e,
            },
        },
        Ok(0) => SysctlOutcome::Gone,
        Ok(size) if size == std::mem::size_of::<kinfo_proc>() => SysctlOutcome::Record,
        Ok(size) => {
            let message = format!(
                "sysctl(KERN_PROC_PID, {pid}) wrote {size} bytes, expected {}",
                std::mem::size_of::<kinfo_proc>()
            );
            SysctlOutcome::Violation {
                error: std::io::Error::other(message.clone()),
                message,
            }
        }
    }
}

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