cosca 0.10.0

Unified cross-platform subprocess management: spawning, stdio, process trees, stable identity, and elevation.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
//! Layout/value oracles for the local kinfo_proc definition. macOS-only at runtime.

use super::*;
use crate::identity::{FakeKernel, HostKernel};

// The kernel must agree with our struct size exactly: for a real one-record fetch, XNU
// sets the written size to sizeof(struct kinfo_proc). (A NULL-buffer probe is NOT usable
// here — XNU inflates it by KERN_PROCSLOP = 5*sizeof, so it reports 6*sizeof for one pid.)
#[skuld::test]
fn kernel_writes_exactly_our_kinfo_proc_size() {
    let mut buf = [0u8; 2 * std::mem::size_of::<kinfo_proc>()];
    let mut size = buf.len();
    let mut mib = [
        libc::CTL_KERN,
        libc::KERN_PROC,
        libc::KERN_PROC_PID,
        std::process::id() as libc::c_int,
    ];
    // SAFETY: `buf`/`size` describe the buffer; sysctl writes at most `size` bytes. No
    // field is read from `buf`, so its alignment is irrelevant.
    let rc = unsafe {
        libc::sysctl(
            mib.as_mut_ptr(),
            mib.len() as libc::c_uint,
            buf.as_mut_ptr() as *mut libc::c_void,
            &mut size,
            std::ptr::null_mut(),
            0,
        )
    };
    assert_eq!(rc, 0, "sysctl fetch failed: {}", std::io::Error::last_os_error());
    assert_eq!(
        size,
        std::mem::size_of::<kinfo_proc>(),
        "kernel kinfo_proc record size disagrees with our layout"
    );
}

// Verifies contract_violation's warn is actually captured, not just that debug panics —
// the release lane (no should_panic) asserts the captured record directly.
#[cfg_attr(debug_assertions, should_panic(expected = "synthetic"))]
#[skuld::test]
fn contract_violation_traces_then_trips() {
    crate::log_capture::install();
    let mark = crate::log_capture::mark();
    super::super::contract_violation(format_args!("synthetic contract violation (test)"));
    // Only reachable in release (debug panicked above, as expected):
    assert!(
        crate::log_capture::contains_since(mark, "synthetic contract violation (test)"),
        "the warn must have fired before the (compiled-out) tripwire"
    );
}

// Value oracle: for a LIVE process the sysctl-derived token must equal the
// proc_pidinfo-derived token — a wrong `p_un` offset or padding error fails here.
// `proc_pidinfo` survives ONLY as this oracle.
#[skuld::test]
fn sysctl_token_matches_libproc_for_a_live_process() {
    let pid = std::process::id() as libc::c_int;

    let (crate::identity::Resolved::Found(ours), _) = HostKernel.kinfo(pid as super::super::RawPid) else {
        panic!("self resolves via sysctl");
    };
    let ours = {
        // SAFETY: as in token_of — the kernel fills p_starttime for KERN_PROC copies.
        let t = unsafe { ours.kp_proc.p_un.p_starttime };
        t.tv_sec as u64 * 1_000_000 + t.tv_usec as u64
    };

    let mut info: libc::proc_bsdinfo = unsafe { std::mem::zeroed() };
    let size = std::mem::size_of::<libc::proc_bsdinfo>() as libc::c_int;
    // SAFETY: proc_pidinfo writes up to `size` bytes into `info`.
    let n = unsafe {
        libc::proc_pidinfo(
            pid,
            libc::PROC_PIDTBSDINFO,
            0,
            &mut info as *mut _ as *mut libc::c_void,
            size,
        )
    };
    assert_eq!(n, size, "proc_pidinfo oracle failed for self");
    let theirs = info.pbi_start_tvsec * 1_000_000 + info.pbi_start_tvusec;

    assert_eq!(ours, theirs, "sysctl and libproc disagree on self's start token");
}

// Value oracle for E_PPID_OFFSET, over the WHOLE live process table rather than just self:
// for every pid where `proc_pidinfo` succeeds, the sysctl-derived `e_ppid` must be
// byte-identical to `proc_bsdinfo.pbi_ppid` — a wrong offset fails here on real ppid values,
// not a coincidental zero. Also reports the two things the offset makes possible: how many
// pids ONLY sysctl could resolve (the `containment::enumerate::macos::ppid_of` fallback's
// rescue set — EPERM cross-user or a ZOMBIE), and how many resolved on NEITHER path (the
// genuine residual — see that module's doc). Run with `--nocapture` to see the counts.
//
// Both raw values are passed through `super::super::trusted_ppid` - the SAME function
// `identity::macos::ppid_of` applies to both its primary and fallback reads in production -
// rather than this test re-deriving the "`e_ppid == 0` is untrustworthy" rule a third time.
// A wrong offset still fails loudly: `trusted_ppid` only ever excludes a `0` (never a
// nonzero value), so a genuine layout bug still surfaces as a real `assert_eq!` mismatch on
// real ppid values, not silent exclusion.
//
// Applying the SAME rule to BOTH sides (not sysctl only) matters: a fork()-in-progress `0`
// is not sysctl-specific — libproc and sysctl read the same underlying kernel field,
// `p->p_ppid` (that is what this very oracle exists to confirm), so either syscall can serve
// the pre-fork()-fill `0` for a live, non-pid-1 pid. Excluding it on one side only would make
// an untrusted libproc `0` hard-fail this test via `assert_eq!(0, <real ppid>)` on whatever
// host process happens to be mid-fork() during a parallel test run - a latent flake
// whose message would point at layout drift instead of the race.
//
// `identity::macos::trusted_ppid`'s doc has the full evidence for why this is a REAL,
// measured race (diagnosed live against `ps -eo pid,ppid,comm`, not reproduced by a targeted
// synthetic fork-storm) rather than a retry-worthy flake: not a race to synchronize away with
// a retry loop (which would just move the same "how many tries is enough" guess into this
// test), but a value both production call sites treat the same way: excluded by the pid it
// names, never trusted as a real ppid.
//
// A simple grow-until-it-fits pid listing, not `collect_pids`'s hot-path doubling discipline
// (see `containment::enumerate::macos`) — this test only needs one complete snapshot, not a
// `hard_kill`-safe allocator.
#[skuld::test]
fn sysctl_e_ppid_matches_libproc_across_the_live_process_table() {
    let mut cap = 1024usize;
    let pids = loop {
        let mut buf = vec![0i32; cap];
        let bytes = (buf.len() * std::mem::size_of::<i32>()) as libc::c_int;
        // SAFETY: `buf` owns exactly `bytes` writable bytes; proc_listallpids writes c_ints
        // into it and never past the size it is given.
        let written = unsafe { libc::proc_listallpids(buf.as_mut_ptr() as *mut libc::c_void, bytes) };
        assert!(
            written > 0,
            "proc_listallpids failed: {}",
            std::io::Error::last_os_error()
        );
        let written = written as usize;
        if written < buf.len() {
            buf.truncate(written);
            break buf;
        }
        cap *= 2;
    };

    let (mut agreed, mut rescued, mut both_failed) = (0usize, 0usize, 0usize);
    // Split by WHICH side read the untrusted `0`, purely for reporting - both raw reads hit
    // the same guard either way (see the doc above), and a pid where both sides read `0`
    // counts in both breakdowns, not a third bucket.
    let (mut ambiguous_zero_libproc, mut ambiguous_zero_sysctl) = (0usize, 0usize);

    for pid in pids {
        if pid <= 0 {
            continue; // pid 0 is the kernel process, not a real pid
        }
        let pid_raw = pid as super::super::RawPid;

        let mut info: libc::proc_bsdinfo = unsafe { std::mem::zeroed() };
        let size = std::mem::size_of::<libc::proc_bsdinfo>() as libc::c_int;
        // SAFETY: proc_pidinfo writes up to `size` bytes into `info`.
        let n = unsafe {
            libc::proc_pidinfo(
                pid,
                libc::PROC_PIDTBSDINFO,
                0,
                &mut info as *mut _ as *mut libc::c_void,
                size,
            )
        };
        let libproc_ppid = (n == size).then_some(info.pbi_ppid);

        let sysctl_ppid = match HostKernel.kinfo(pid_raw).0 {
            crate::identity::Resolved::Found(k) => Some(k.e_ppid() as super::super::RawPid),
            crate::identity::Resolved::Gone | crate::identity::Resolved::Unknown => None,
        };

        // The SAME guard, applied identically to both raw reads - see the doc above for why
        // asymmetry here is a latent flake, not just an inconsistency.
        let libproc_untrusted = libproc_ppid.is_some_and(|raw| super::super::trusted_ppid(pid_raw, raw).is_none());
        let sysctl_untrusted = sysctl_ppid.is_some_and(|raw| super::super::trusted_ppid(pid_raw, raw).is_none());

        match (libproc_ppid, sysctl_ppid) {
            _ if libproc_untrusted || sysctl_untrusted => {
                if libproc_untrusted {
                    ambiguous_zero_libproc += 1;
                }
                if sysctl_untrusted {
                    ambiguous_zero_sysctl += 1;
                }
            }
            (Some(a), Some(b)) => {
                assert_eq!(a, b, "pid {pid}: libproc ppid {a} disagrees with sysctl ppid {b}");
                agreed += 1;
            }
            (None, Some(_)) => rescued += 1,
            // libproc succeeded but sysctl did not - the reverse fork/exit-window race, or a
            // genuinely narrower gap than the fallback's target case. `both_failed`, not a
            // separate bucket: from `identity::macos::ppid_of`'s perspective (proc_pidinfo
            // primary, sysctl fallback) this pid is unresolved either way, since its own
            // primary already succeeded and it never reaches the fallback at all.
            (Some(_), None) => both_failed += 1,
            (None, None) => both_failed += 1,
        }
    }

    eprintln!(
        "sysctl_e_ppid oracle over the live process table: agreed={agreed} rescued={rescued} \
         both_failed={both_failed} ambiguous_zero_libproc={ambiguous_zero_libproc} \
         ambiguous_zero_sysctl={ambiguous_zero_sysctl}"
    );
    assert!(
        agreed > 0,
        "must observe at least one libproc/sysctl agreement on a live host (self, if nothing else)"
    );
}

// Value oracle for `P_SYSTEM`. On this host (and every recent Darwin release checked, up to
// 26.5.2), `kernproc` (pid 0) is the ONLY process carrying the flag — not `launchd`/`initproc`
// (pid 1), which xnu's `killpg1` excludes from a process-group signal by a direct `p ==
// initproc` pointer check, entirely separate from its `P_SYSTEM` test (confirmed against
// xnu's own `bsd/kern/kern_sig.c`). `libc::proc_pidinfo` cannot serve as an oracle for either
// root-owned pid measured here (pid 0 or pid 1): it fails to resolve a foreign-uid process
// without root, the same as it fails for pid 0. The positive case (pid 0) is instead
// cross-checked against a second, independently-issued sysctl call reading the WHOLE process
// table (`KERN_PROC_ALL`, a different selector/code path from `Kernel::kinfo`'s own `KERN_PROC_PID`)
// rather than trusting one query alone. The negative case is checked for both pid 1 (sysctl
// only) and this test's own process — the latter additionally cross-checked against
// `proc_pidinfo`'s independently-defined `PROC_FLAG_SYSTEM` (`sys/proc_info.h`, no `libc`
// crate constant, restated here as a local, source-cited value).
#[skuld::test]
fn p_flag_system_bit_matches_a_second_sysctl_query_and_libproc_disagrees_for_non_system() {
    const PROC_FLAG_SYSTEM: u32 = 1;

    // Positive: kernproc (pid 0), read via `Kernel::kinfo` (production code path, KERN_PROC_PID).
    let (crate::identity::Resolved::Found(k), _) = HostKernel.kinfo(0) else {
        panic!("pid 0 (kernproc) resolves via sysctl KERN_PROC_PID");
    };
    assert!(
        k.kp_proc.p_flag & P_SYSTEM != 0,
        "kernproc (pid 0) must be P_SYSTEM-flagged via KERN_PROC_PID"
    );

    // Cross-check: an independently-issued KERN_PROC_ALL scan must agree pid 0 carries the
    // same bit — a different selector/code path from the KERN_PROC_PID query above.
    let mut mib = [libc::CTL_KERN, libc::KERN_PROC, libc::KERN_PROC_ALL, 0];
    let mut len: libc::size_t = 0;
    // SAFETY: a size query — null buffer, `len` receives the byte count.
    let rc = unsafe {
        libc::sysctl(
            mib.as_mut_ptr(),
            mib.len() as libc::c_uint,
            std::ptr::null_mut(),
            &mut len,
            std::ptr::null_mut(),
            0,
        )
    };
    assert_eq!(
        rc,
        0,
        "KERN_PROC_ALL sizing query failed: {}",
        std::io::Error::last_os_error()
    );
    let record = std::mem::size_of::<kinfo_proc>();
    let mut buf: Vec<kinfo_proc> = Vec::with_capacity(len / record + 8);
    let mut got = buf.capacity() * record;
    // SAFETY: `buf` has room for `got` bytes of records; sysctl writes at most `got`.
    let rc = unsafe {
        libc::sysctl(
            mib.as_mut_ptr(),
            mib.len() as libc::c_uint,
            buf.as_mut_ptr().cast(),
            &mut got,
            std::ptr::null_mut(),
            0,
        )
    };
    assert_eq!(rc, 0, "KERN_PROC_ALL fetch failed: {}", std::io::Error::last_os_error());
    // SAFETY: sysctl initialised exactly `got / record` whole records.
    unsafe { buf.set_len(got / record) };
    let kernproc = buf
        .iter()
        .find(|k| k.kp_proc.p_pid == 0)
        .expect("pid 0 (kernproc) present in a KERN_PROC_ALL scan");
    assert!(
        kernproc.kp_proc.p_flag & P_SYSTEM != 0,
        "kernproc (pid 0) must be P_SYSTEM-flagged via the independent KERN_PROC_ALL scan too"
    );

    // Negative, sysctl-only: neither pid 1 (launchd, root-owned) nor this test process is
    // P_SYSTEM-flagged. `proc_pidinfo` cannot cross-check pid 1 here — measured, it also
    // fails to resolve a foreign-uid pid without root, same as it fails for pid 0 above — so
    // only this test's own pid gets the `proc_pidinfo` cross-check, right below.
    for pid in [1, std::process::id() as libc::c_int] {
        let (crate::identity::Resolved::Found(k), _) = HostKernel.kinfo(pid as super::super::RawPid) else {
            panic!("pid {pid} resolves via sysctl");
        };
        assert!(
            k.kp_proc.p_flag & P_SYSTEM == 0,
            "pid {pid} must not be P_SYSTEM-flagged via sysctl"
        );
    }

    // Negative, cross-checked: this test process itself is not PROC_FLAG_SYSTEM-flagged
    // either, via proc_pidinfo's independently-defined bit.
    let me = std::process::id() as libc::c_int;
    let mut info: libc::proc_bsdinfo = unsafe { std::mem::zeroed() };
    let size = std::mem::size_of::<libc::proc_bsdinfo>() as libc::c_int;
    // SAFETY: proc_pidinfo writes up to `size` bytes into `info`.
    let n = unsafe {
        libc::proc_pidinfo(
            me,
            libc::PROC_PIDTBSDINFO,
            0,
            &mut info as *mut _ as *mut libc::c_void,
            size,
        )
    };
    assert_eq!(n, size, "proc_pidinfo oracle failed for self");
    assert!(
        info.pbi_flags & PROC_FLAG_SYSTEM == 0,
        "this test process must not be PROC_FLAG_SYSTEM-flagged via proc_pidinfo"
    );
}

// The exit-begun read is `P_WEXIT` or a zombie's state, and no other flag: this process shows neither.
// Mutants: the zombie state is not read; any flag counts.
#[skuld::test]
fn exit_begun_is_p_wexit_or_a_zombie_and_no_other_flag() {
    let running = libc::SRUN as libc::c_char;
    let zombie = libc::SZOMB as libc::c_char;
    assert!(!exit_begun(running, 0));
    assert!(!exit_begun(running, P_SYSTEM));
    assert!(exit_begun(running, P_WEXIT));
    assert!(exit_begun(zombie, 0));
    // Only `P_WEXIT` without `SZOMB` is `Exiting`; a zombie is a zombie whether or not the flag shows.
    assert_eq!(exit_state(running, 0), ExitState::Running);
    assert_eq!(exit_state(running, P_WEXIT), ExitState::Exiting);
    assert_eq!(exit_state(zombie, 0), ExitState::Zombie);
    assert_eq!(exit_state(zombie, P_WEXIT), ExitState::Zombie);

    let me = HostKernel
        .kinfo(std::process::id())
        .0
        .found()
        .expect("this process resolves");
    assert!(
        !exit_begun(me.kp_proc.p_stat, me.kp_proc.p_flag),
        "this process is running"
    );
}

// The identity read of the exit goes by the token: this process's own is running, another process's
// token at this pid is `Gone`, and a refused `sysctl` is `Unknown`, with the refusal as the cause.
// Mutants: the token is not compared; a refusal is `Gone`; the cause is dropped.
#[skuld::test]
fn the_exit_read_of_an_identity_is_gone_for_another_token_and_unknown_when_refused() {
    let me = crate::identity::ProcessId::of(std::process::id())
        .found()
        .expect("this process has an identity");
    assert_eq!(
        super::super::exit_begun(&HostKernel, me.pid(), me.key).0,
        crate::identity::Resolved::Found(false),
        "this process is running"
    );

    let other = crate::identity::Key::from_raw(me.key.raw() + 1);
    assert_eq!(
        super::super::exit_begun(&HostKernel, me.pid(), other).0,
        crate::identity::Resolved::Gone,
        "the pid holds another process than the token's"
    );

    let refused = FakeKernel::over(&HostKernel).on_kinfo_refused(me.pid(), libc::EPERM);
    let (read, cause) = super::super::exit_begun(&refused, me.pid(), me.key);
    assert_eq!(read, crate::identity::Resolved::Unknown);
    let error = cause.into_error("pid 1").expect("the refusal is the cause");
    assert!(error.to_string().contains("kinfo_proc could not be read"), "{error}");
}

// What one sysctl call's result means. Mutants: `EINTR` is not retried; a refusal is a contract
// violation (a sandbox then trips the debug tripwire), or an `ENOMEM` / `EINVAL` is quiet; a record of
// another size is trusted; an empty reply is a violation.
#[skuld::test]
fn a_sysctl_result_is_classified_by_its_errno_and_size() {
    let failed = |errno| std::io::Error::from_raw_os_error(errno);
    let size = std::mem::size_of::<kinfo_proc>();
    assert!(matches!(classify(7, Err(failed(libc::EINTR))), SysctlOutcome::Retry));
    assert!(matches!(classify(7, Err(failed(libc::ESRCH))), SysctlOutcome::Gone));
    assert!(matches!(classify(7, Ok(0)), SysctlOutcome::Gone));
    assert!(matches!(classify(7, Ok(size)), SysctlOutcome::Record));
    for errno in [libc::EPERM, libc::EACCES] {
        match classify(7, Err(failed(errno))) {
            SysctlOutcome::Refused(e) => assert_eq!(e.raw_os_error(), Some(errno)),
            other => panic!("errno {errno} is a refusal, got {other:?}"),
        }
    }
    for errno in [libc::ENOMEM, libc::EINVAL] {
        match classify(7, Err(failed(errno))) {
            SysctlOutcome::Violation { message, error } => {
                assert!(message.contains("sysctl(KERN_PROC_PID, 7) failed"), "{message}");
                assert_eq!(error.raw_os_error(), Some(errno), "the errno stays the read's cause");
            }
            other => panic!("errno {errno} is a contract violation, got {other:?}"),
        }
    }
    for wrote in [size - 1, size + 1] {
        match classify(7, Ok(wrote)) {
            SysctlOutcome::Violation { message, error } => {
                assert_eq!(
                    message,
                    format!("sysctl(KERN_PROC_PID, 7) wrote {wrote} bytes, expected {size}")
                );
                assert_eq!(error.to_string(), message);
            }
            other => panic!("{wrote} bytes is layout drift, got {other:?}"),
        }
    }
}