cosca 0.7.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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
//! macOS process-identity backend: `proc_pidinfo` (Apple's stable public libproc API) is
//! the PRIMARY source; `sysctl(KERN_PROC_PID)` (the `kinfo` module) is the FALLBACK for
//! what libproc cannot see — ZOMBIES and EPERM-hidden cross-user processes — keeping
//! identity resolution zombie-inclusive like Linux procfs while the common live path stays
//! on the stable ABI. Both sources report the process start time in µs (cross-source
//! equality pinned by the kinfo_tests oracle), so a layout drift in the undocumented
//! kinfo_proc ABI degrades only zombie/cross-user resolution (a token mismatch — the
//! pre-fix behavior), never live same-uid identity.
//!
//! [`ppid_of`] resolves a pid's parent the same primary/fallback way — `proc_pidinfo` first,
//! the sysctl fallback on a miss — and is reused whole by `containment::enumerate::macos`,
//! rather than that module keeping a second `proc_pidinfo` call and a second copy of the
//! zero-ppid guard ([`trusted_ppid`]) next to a duplicated `kinfo_proc` layout.

use std::time::{Duration, SystemTime};

use super::{Key, Liveness, OrderedRead, ParentRead, RawPid, Resolved, UnknownCause};

#[path = "macos/kinfo.rs"]
pub(crate) mod kinfo;

fn bsd_info(pid: RawPid) -> Option<libc::proc_bsdinfo> {
    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`; pointer and size match.
    let n = unsafe {
        libc::proc_pidinfo(
            pid as libc::c_int,
            libc::PROC_PIDTBSDINFO,
            0,
            &mut info as *mut _ as *mut libc::c_void,
            size,
        )
    };
    if n == size {
        return Some(info);
    }
    if n <= 0 {
        let e = std::io::Error::last_os_error();
        match e.raw_os_error() {
            // Expected misses: gone/zombie (ESRCH) or an unprivileged cross-user query
            // (EPERM) — the sysctl fallback covers both.
            Some(libc::ESRCH) | Some(libc::EPERM) => {}
            _ => contract_violation(format_args!("proc_pidinfo({pid}) failed: {e}")),
        }
        return None;
    }
    // 0 < n < size: a partial record — never trust it.
    contract_violation(format_args!("proc_pidinfo({pid}) wrote {n} bytes, expected {size}"));
    None
}

/// The shared contract-violation disposition for BOTH identity sources: trace FIRST (so
/// the warn executes in every build mode), then the debug tripwire.
pub(super) fn contract_violation(what: std::fmt::Arguments<'_>) {
    log::warn!("{what}");
    debug_assert!(false, "{what}");
}

fn token_of_bsd(info: &libc::proc_bsdinfo) -> Key {
    Key::from_raw(info.pbi_start_tvsec * 1_000_000 + info.pbi_start_tvusec)
}

fn token_of_kinfo(info: &kinfo::kinfo_proc) -> Key {
    // SAFETY: the kernel's KERN_PROC copy always fills `p_starttime` (XNU
    // fill_externproc); the union's other arm is kernel-internal queue pointers never
    // exported here. Both arms are plain old data, so the read is defined.
    let start = unsafe { info.kp_proc.p_un.p_starttime };
    Key::from_raw(start.tv_sec as u64 * 1_000_000 + start.tv_usec as u64)
}

/// Which identity read a [`uniq_info`] or [`held_by`] call is, so a test can inject a result into
/// one read without touching the others.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ReadPurpose {
    /// The child's identity, read by pid at adoption (test-only).
    #[cfg_attr(not(test), allow(dead_code, reason = "only the test-only by-pid read uses it"))]
    Adopt,
    /// The re-read just before a signal.
    Kill,
    /// The reads that bracket the arming of an exit watch in `os_process::open`.
    Open,
    /// A peek that found an exit record, just before its consume.
    Peek,
    /// A peek that found the child running, and the liveness read that follows it.
    Running,
    /// A peek that got `ECHILD`: does the pid still name our child, and who holds it?
    Echild,
    /// The own-zombie read before the first reap, for the second peek.
    PreReap,
    /// The second peek's.
    SecondPeek,
    /// Whether a pid whose unique id is not known yet was forked by this process.
    Origin,
    /// A tracer on the chain that holds a child: which process it is, and who holds it.
    Link,
}

/// The pid launchd runs as, the parent of every orphan.
pub(crate) const LAUNCHD: RawPid = 1;

/// `PROC_PIDUNIQIDENTIFIERINFO`, `proc_info_private.h`. Private, and read unprivileged: the kernel
/// answers it for any user's process (`NO_CHECK_SAME_USER`, `proc_info.c`).
const PROC_PIDUNIQIDENTIFIERINFO: libc::c_int = 17;

// `libc::PROC_PIDT_SHORTBSDINFO` is also `NO_CHECK_SAME_USER`, unlike `PROC_PIDTBSDINFO`, which is
// refused for any process whose effective uid is not ours.

/// `struct proc_uniqidentifierinfo` (`proc_info_private.h`, 56 bytes).
#[repr(C)]
#[derive(Clone, Copy)]
struct ProcUniqIdentifierInfo {
    p_uuid: [u8; 16],
    p_uniqueid: u64,
    p_puniqueid: u64,
    p_idversion: i32,
    p_orig_ppidversion: i32,
    p_reserve2: u64,
    p_reserve3: u64,
}
const _: () = assert!(std::mem::size_of::<ProcUniqIdentifierInfo>() == 56);

/// What `proc_pidinfo(pid, 17, ...)` says of a process.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct UniqInfo {
    /// The process's 64-bit id, never reused and kept across `exec`.
    pub(crate) unique_id: u64,
    /// `p_idversion`, the audit token's `val[7]`: it changes at `exec`, and the kernel checks it
    /// when it signals by audit token.
    pub(crate) id_version: i32,
}

/// The outcome of a `proc_pidinfo` read by pid.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum UniqRead {
    Found(UniqInfo),
    /// `ESRCH`. With `arg = 1` a process is resolved from `P_REF_DEAD` until its reap
    /// (`proc_pidinfo` falls back to `proc_find_zombref`, which accepts `P_REF_DEAD`: xnu-12377
    /// `proc_info.c:2198-2215`, `kern_proc.c:814-817` and `:1131`), so this means reaped.
    Gone,
    /// Any other errno (`EPERM` from a MACF denial, ...): the read failed.
    Refused(i32),
}

/// Runs `proc_pidinfo(pid, flavor, arg = 1, ...)` into `buf`. `arg = 1` sees zombies. It never
/// waits on `P_LINTRANSIT` (xnu-12377.121.6 and xnu-10063.101.15: `proc_info.c` has no
/// `proc_transwait`; `proc_find` waits only for the brief `P_REF_WILL_EXEC | P_REF_IN_EXEC` switch
/// after exec's point of no return, as `kill(2)` does). `n <= 0` is classified by errno.
fn pidinfo<T>(pid: RawPid, flavor: libc::c_int, buf: &mut T) -> Result<(), ReadErr> {
    let size = std::mem::size_of::<T>() as libc::c_int;
    // SAFETY: proc_pidinfo writes up to `size` bytes into `buf`; pointer and size match.
    let n = unsafe { libc::proc_pidinfo(pid as libc::c_int, flavor, 1, buf as *mut T as *mut libc::c_void, size) };
    if n == size {
        return Ok(());
    }
    if n <= 0 {
        let errno = std::io::Error::last_os_error().raw_os_error().unwrap_or(libc::EIO);
        return Err(if errno == libc::ESRCH {
            ReadErr::Gone
        } else {
            ReadErr::Refused(errno)
        });
    }
    log::warn!("proc_pidinfo({pid}, {flavor}) wrote {n} bytes, expected {size}");
    Err(ReadErr::Refused(libc::EIO))
}

/// `pid`'s unique id through `proc_pidinfo(PROC_PIDUNIQIDENTIFIERINFO)`. Unprivileged for any
/// user's process, and it sees zombies.
pub(crate) fn uniq_info(pid: RawPid, purpose: ReadPurpose) -> UniqRead {
    #[cfg(test)]
    uniq_fault::note(purpose);
    #[cfg(test)]
    if let Some(forced) = uniq_fault::take(purpose) {
        return forced;
    }
    #[cfg(not(test))]
    let _ = purpose;
    // SAFETY: all-zero is a valid `ProcUniqIdentifierInfo`.
    let mut info: ProcUniqIdentifierInfo = unsafe { std::mem::zeroed() };
    match pidinfo(pid, PROC_PIDUNIQIDENTIFIERINFO, &mut info) {
        Ok(()) => UniqRead::Found(UniqInfo {
            unique_id: info.p_uniqueid,
            id_version: info.p_idversion,
        }),
        Err(ReadErr::Gone) => UniqRead::Gone,
        Err(ReadErr::Refused(errno)) => UniqRead::Refused(errno),
    }
}

/// The calling process's own unique id, for a child to report before `exec`. **Async-signal-safe**:
/// no allocation, lock or logging. `Err` is the errno.
pub(crate) fn own_unique_id() -> Result<u64, i32> {
    // SAFETY: all-zero is a valid `ProcUniqIdentifierInfo`.
    let mut info: ProcUniqIdentifierInfo = unsafe { std::mem::zeroed() };
    let size = std::mem::size_of::<ProcUniqIdentifierInfo>() as libc::c_int;
    // SAFETY: `getpid` has no preconditions; proc_pidinfo writes up to `size` bytes into `info`.
    let n = unsafe {
        libc::proc_pidinfo(
            libc::getpid(),
            PROC_PIDUNIQIDENTIFIERINFO,
            1,
            (&mut info as *mut ProcUniqIdentifierInfo).cast(),
            size,
        )
    };
    if n == size {
        Ok(info.p_uniqueid)
    } else if n <= 0 {
        Err(std::io::Error::last_os_error().raw_os_error().unwrap_or(libc::EIO))
    } else {
        Err(libc::EIO)
    }
}

/// What [`held_by`] saw.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Held {
    /// The process still has the expected unique id, and this parent pid.
    Parent(u32),
    /// The pid names another process now.
    Other,
    /// Reaped.
    Gone,
    /// A read failed with this errno.
    Refused(i32),
}

/// The parent pid of the process whose unique id is `expected`. The parent is read through
/// `PROC_PIDT_SHORTBSDINFO`, between two unique-id reads: the same id before and after proves the
/// parent read was of that process, because a unique id is never reused.
pub(crate) fn held_by(pid: RawPid, expected: u64, purpose: ReadPurpose) -> Held {
    match short_read(pid, expected, purpose, short_ppid) {
        Ok(ppid) => Held::Parent(ppid),
        Err(Mismatch::Other) => Held::Other,
        Err(Mismatch::Gone) => Held::Gone,
        Err(Mismatch::Refused(errno)) => Held::Refused(errno),
    }
}

/// Whether the process whose unique id is `expected` has exited, read as a zombie
/// (`PROC_PIDT_SHORTBSDINFO`'s `SZOMB`) between two unique-id reads, as in [`held_by`]. A pid that
/// names another process now, or none, has had its process reaped: exited. `Err` is the errno of a
/// refused read.
pub(crate) fn has_exited(pid: RawPid, expected: u64, purpose: ReadPurpose) -> Result<bool, i32> {
    match short_read(pid, expected, purpose, short_status) {
        Ok(status) => Ok(status == libc::SZOMB),
        Err(Mismatch::Other | Mismatch::Gone) => Ok(true),
        Err(Mismatch::Refused(errno)) => Err(errno),
    }
}

/// The error of a [`has_exited`] that was refused with `errno`: the child cannot be shown to be
/// running.
pub(crate) fn has_exited_error(pid: RawPid, errno: i32) -> std::io::Error {
    std::io::Error::new(
        std::io::Error::from_raw_os_error(errno).kind(),
        format!("pid {pid}: its identity could not be read (errno {errno}); it cannot be shown to be running"),
    )
}

/// Why a [`short_read`] did not read the process it was asked for.
enum Mismatch {
    /// The pid names another process now.
    Other,
    /// Reaped.
    Gone,
    /// A read failed with this errno.
    Refused(i32),
}

/// `read` of `pid`, between two unique-id reads: the same id before and after proves the read was of
/// the process whose unique id is `expected`, because a unique id is never reused.
fn short_read<T>(
    pid: RawPid,
    expected: u64,
    purpose: ReadPurpose,
    read: impl FnOnce(RawPid) -> Result<T, ReadErr>,
) -> Result<T, Mismatch> {
    let same = |read: UniqRead| match read {
        UniqRead::Found(info) if info.unique_id == expected => Ok(()),
        UniqRead::Found(_) => Err(Mismatch::Other),
        UniqRead::Gone => Err(Mismatch::Gone),
        UniqRead::Refused(errno) => Err(Mismatch::Refused(errno)),
    };
    same(uniq_info(pid, purpose))?;
    let read = read(pid);
    same(uniq_info(pid, purpose))?;
    match read {
        Ok(read) => Ok(read),
        // The id matched before and after this read, so the process was in the pid hash at both
        // ends and cannot have been reaped in between. Flavors 13 and 17 share one lookup
        // (`proc_find`, then `proc_find_zombref`, `proc_info.c:2199-2215`) and one
        // `NO_CHECK_SAME_USER` policy (`:2230-2236`), so xnu cannot answer `ESRCH` here.
        Err(ReadErr::Gone) => {
            debug_assert!(false, "pid {pid}: a read said ESRCH between two matching id reads");
            Err(Mismatch::Gone)
        }
        Err(ReadErr::Refused(errno)) => Err(Mismatch::Refused(errno)),
    }
}

/// What [`origin`] saw.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Origin {
    /// This process forked it: its parent is this process, or was when a tracer attached.
    /// `parent` holds it now: this process, a tracer, or launchd (a child whose tracer exited while
    /// the child was exiting).
    Ours { parent: RawPid },
    /// Another process's, or not the same process from one read to the next.
    NotOurs,
    /// No process has the pid.
    Gone,
    /// A unique-id read failed with this errno.
    Refused(i32),
    /// The `kinfo_proc` read was refused.
    Unreadable,
}

/// Whether the process `pid` names was forked by this process, for a pid whose unique id is not
/// known yet. A tracer takes a child from its parent: the child's `p_ppid` names the tracer, and
/// `p_oppid` keeps the parent it had at the attach (xnu `mach_process.c`, `PT_ATTACH`). So the child
/// is ours when either names this process and its unique id is above this process's own, which
/// excludes a stale `p_oppid` left by an earlier holder of this process's pid: ids are allocated in
/// increasing order and never reused, so only a process created after this one has a higher one.
/// The `kinfo_proc` read is between two unique-id reads, as in [`held_by`].
pub(crate) fn origin(pid: RawPid) -> Origin {
    let own = match own_unique_id() {
        Ok(own) => own,
        Err(errno) => return Origin::Refused(errno),
    };
    let unique = match uniq_info(pid, ReadPurpose::Origin) {
        UniqRead::Found(info) => info.unique_id,
        UniqRead::Gone => return Origin::Gone,
        UniqRead::Refused(errno) => return Origin::Refused(errno),
    };
    let info = match kinfo::kinfo(pid) {
        Resolved::Found(info) => info,
        Resolved::Gone => return Origin::Gone,
        Resolved::Unknown => return Origin::Unreadable,
    };
    match uniq_info(pid, ReadPurpose::Origin) {
        UniqRead::Found(again) if again.unique_id == unique => {}
        UniqRead::Found(_) => return Origin::NotOurs,
        UniqRead::Gone => return Origin::Gone,
        UniqRead::Refused(errno) => return Origin::Refused(errno),
    }
    let me = std::process::id() as libc::pid_t;
    if unique > own && (info.kp_proc.p_oppid == me || info.e_ppid() == me) {
        Origin::Ours {
            parent: info.e_ppid() as RawPid,
        }
    } else {
        Origin::NotOurs
    }
}

/// What [`link`] saw.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Link {
    /// The process with unique id `unique`. `parent` holds it now; `at_attach` is its parent when a
    /// tracer attached, or 0 when none did.
    Found {
        unique: u64,
        parent: RawPid,
        at_attach: RawPid,
    },
    /// No process has the pid, or another took it between the reads.
    Gone,
    /// A unique-id read failed with this errno.
    Refused(i32),
    /// The `kinfo_proc` read was refused.
    Unreadable,
}

/// The process `pid` names on a chain of tracers, and its parents: who holds it now, and who held
/// it when a tracer attached. The `kinfo_proc` read is between two unique-id reads, as in
/// [`held_by`].
pub(crate) fn link(pid: RawPid) -> Link {
    let unique = match uniq_info(pid, ReadPurpose::Link) {
        UniqRead::Found(info) => info.unique_id,
        UniqRead::Gone => return Link::Gone,
        UniqRead::Refused(errno) => return Link::Refused(errno),
    };
    let info = match kinfo::kinfo(pid) {
        Resolved::Found(info) => info,
        Resolved::Gone => return Link::Gone,
        Resolved::Unknown => return Link::Unreadable,
    };
    match uniq_info(pid, ReadPurpose::Link) {
        UniqRead::Found(again) if again.unique_id == unique => Link::Found {
            unique,
            parent: info.e_ppid() as RawPid,
            at_attach: info.kp_proc.p_oppid as RawPid,
        },
        UniqRead::Found(_) | UniqRead::Gone => Link::Gone,
        UniqRead::Refused(errno) => Link::Refused(errno),
    }
}

/// Why a `proc_pidinfo` read by pid failed: `ESRCH`, or any other errno.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ReadErr {
    Gone,
    Refused(i32),
}

fn short_ppid(pid: RawPid) -> Result<u32, ReadErr> {
    #[cfg(test)]
    if let Some(forced) = ppid_fault::take() {
        return forced;
    }
    // SAFETY: all-zero is a valid `ProcBsdShortInfo`.
    let mut info: libc::proc_bsdshortinfo = unsafe { std::mem::zeroed() };
    pidinfo(pid, libc::PROC_PIDT_SHORTBSDINFO, &mut info).map(|()| info.pbsi_ppid)
}

fn short_status(pid: RawPid) -> Result<u32, ReadErr> {
    // SAFETY: all-zero is a valid `ProcBsdShortInfo`.
    let mut info: libc::proc_bsdshortinfo = unsafe { std::mem::zeroed() };
    pidinfo(pid, libc::PROC_PIDT_SHORTBSDINFO, &mut info).map(|()| info.pbsi_status)
}

/// Forces [`uniq_info`] of a purpose below the syscall.
#[cfg(test)]
pub(crate) mod uniq_fault {
    use std::cell::RefCell;

    use super::{ReadPurpose, UniqRead};

    thread_local! {
        static FORCED: RefCell<Vec<(ReadPurpose, UniqRead)>> = const { RefCell::new(Vec::new()) };
    }

    #[must_use = "dropping this immediately disarms the force; bind it for the probe's duration"]
    pub(crate) struct Forced(());

    /// The next `uniq_info` for `purpose` on this thread answers `read`. Forces queue.
    pub(crate) fn force_uniq_read_once(purpose: ReadPurpose, read: UniqRead) -> Forced {
        FORCED.with(|f| f.borrow_mut().push((purpose, read)));
        Forced(())
    }

    impl Drop for Forced {
        fn drop(&mut self) {
            FORCED.with(|f| f.borrow_mut().clear());
        }
    }

    thread_local! {
        static RECORDED: RefCell<Option<Vec<ReadPurpose>>> = const { RefCell::new(None) };
    }

    /// Records the purpose of every by-pid unique-id read on this thread until the guard drops.
    pub(crate) fn record() -> Recorder {
        RECORDED.with(|r| *r.borrow_mut() = Some(Vec::new()));
        Recorder(())
    }

    #[must_use = "recording stops as soon as the recorder is dropped"]
    pub(crate) struct Recorder(());

    impl Recorder {
        /// The purposes recorded so far, in order.
        pub(crate) fn purposes(&self) -> Vec<ReadPurpose> {
            RECORDED.with(|r| r.borrow().clone().unwrap_or_default())
        }
    }

    impl Drop for Recorder {
        fn drop(&mut self) {
            RECORDED.with(|r| *r.borrow_mut() = None);
        }
    }

    pub(super) fn note(purpose: ReadPurpose) {
        RECORDED.with(|r| {
            if let Some(recorded) = r.borrow_mut().as_mut() {
                recorded.push(purpose);
            }
        });
    }

    pub(super) fn take(purpose: ReadPurpose) -> Option<UniqRead> {
        FORCED.with(|f| {
            let mut forced = f.borrow_mut();
            let at = forced.iter().position(|(p, _)| *p == purpose)?;
            Some(forced.remove(at).1)
        })
    }
}

/// Forces the parent read of [`held_by`] below the syscall.
#[cfg(test)]
pub(crate) mod ppid_fault {
    use std::cell::RefCell;

    use super::ReadErr;

    /// What [`force_ppid_with`] answers.
    type Reads = Box<dyn FnMut() -> Result<u32, ReadErr>>;

    thread_local! {
        static FORCED: RefCell<Vec<Result<u32, ReadErr>>> = const { RefCell::new(Vec::new()) };
        static READS: RefCell<Option<Reads>> = const { RefCell::new(None) };
    }

    #[must_use = "dropping this immediately disarms the force; bind it for the probe's duration"]
    pub(crate) struct Forced(());

    /// The next parent read on this thread answers `read`. Forces queue.
    pub(crate) fn force_ppid_once(read: Result<u32, ReadErr>) -> Forced {
        FORCED.with(|f| f.borrow_mut().push(read));
        Forced(())
    }

    /// While the guard lives, every parent read on this thread that no queued force answers
    /// answers what `reads` does at that read.
    pub(crate) fn force_ppid_with(reads: impl FnMut() -> Result<u32, ReadErr> + 'static) -> ForcedReads {
        READS.with(|r| *r.borrow_mut() = Some(Box::new(reads)));
        ForcedReads(())
    }

    impl Drop for Forced {
        fn drop(&mut self) {
            FORCED.with(|f| f.borrow_mut().clear());
        }
    }

    #[must_use = "the reads are real again as soon as the guard is dropped"]
    pub(crate) struct ForcedReads(());

    impl Drop for ForcedReads {
        fn drop(&mut self) {
            READS.with(|r| r.borrow_mut().take());
        }
    }

    pub(super) fn take() -> Option<Result<u32, ReadErr>> {
        let queued = FORCED.with(|f| {
            let mut forced = f.borrow_mut();
            (!forced.is_empty()).then(|| forced.remove(0))
        });
        queued.or_else(|| READS.with(|r| r.borrow_mut().as_mut().map(|reads| reads())))
    }
}

/// What one read of a process's record says: its start key, and its parent pid as the record has
/// it, not yet judged ([`Record::ppid`]).
struct Record {
    key: Key,
    raw_ppid: RawPid,
}

impl Record {
    /// The record's parent pid of `pid`, when [`trusted_ppid`] trusts it; `None` is a `fork()` still
    /// filling it in.
    fn ppid(&self, pid: RawPid) -> Option<RawPid> {
        trusted_ppid(pid, self.raw_ppid)
    }
}

/// One read of `pid`'s record, the one read behind the by-pid start key and the parent pid:
/// `proc_pidinfo` first, and when it misses (libproc-invisible: gone, a ZOMBIE, or EPERM-hidden)
/// the sysctl, which alone resolves the latter two and distinguishes an empty reply (gone) from a
/// failure (unknown). The key and the parent pid are of the one record.
fn read_record(pid: RawPid) -> Resolved<Record> {
    if let Some(info) = bsd_info(pid) {
        return Resolved::Found(Record {
            key: token_of_bsd(&info),
            raw_ppid: info.pbi_ppid,
        });
    }
    kinfo::kinfo(pid).map(|info| Record {
        key: token_of_kinfo(&info),
        raw_ppid: info.e_ppid() as RawPid,
    })
}

/// A by-pid identity read of `pid`: `read`, unless a test forces the OS's refusal.
fn by_pid<T>(pid: RawPid, read: impl FnOnce() -> Resolved<T>) -> Resolved<T> {
    #[cfg(test)]
    if fault::is_unknown(pid) {
        return Resolved::Unknown;
    }
    #[cfg(not(test))]
    let _ = pid;
    read()
}

pub(super) fn start_token(pid: RawPid) -> Resolved<Key> {
    by_pid(pid, || read_record(pid).map(|record| record.key))
}

/// The key, with no order key, and, when `ask_parent`, the parent pid of `pid`, from one record.
/// With `ask_parent`, waits out a parent pid that `fork()` is still filling in ([`ppid_of`]);
/// without, reads the record once. `expected`: see
/// [`ProcessId::of_ordered_with`](super::ProcessId::of_ordered_with).
pub(super) fn ordered_read(pid: RawPid, expected: Option<Key>, ask_parent: bool) -> OrderedRead {
    let read = if ask_parent {
        by_pid(pid, || ppid_and_key(pid)).map(|(ppid, key)| (key, ParentRead::Is(ppid)))
    } else {
        by_pid(pid, || read_record(pid)).map(|record| (record.key, ParentRead::NotAsked))
    };
    match read {
        Resolved::Found((key, parent)) => OrderedRead {
            read: Resolved::Found((key, None)),
            parent,
            cause: UnknownCause::default(),
        }
        .against(expected),
        Resolved::Gone => OrderedRead::missing(Resolved::Gone, UnknownCause::default(), ask_parent),
        Resolved::Unknown => OrderedRead::missing(Resolved::Unknown, UnknownCause::default(), ask_parent),
    }
}

/// Whether a raw ppid value read from the kernel for `pid` is trustworthy - shared by BOTH
/// [`ppid_of`]'s primary read (`proc_bsdinfo.pbi_ppid`, via `proc_pidinfo`) and its sysctl
/// fallback (`kinfo_proc.kp_eproc.e_ppid`), which read the same underlying kernel field,
/// `p->p_ppid` (confirmed live, across the whole process table, by
/// `sysctl_e_ppid_matches_libproc_across_the_live_process_table`, which also calls this
/// function rather than re-deriving the rule) - a single function so production's two call
/// sites and that oracle test cannot silently drift apart on what counts as trustworthy.
///
/// `0` is legitimate ONLY for pid 0 (`kernel_task`, the kernel itself: never forked, and its own
/// parent number) and pid 1 (launchd, the one real process whose parent is the kernel). Neither is
/// ever mid-`fork()`, so waiting on a `0` there would never end. For any
/// other pid, a `0` here means XNU served this pid's process-info record
/// before `fork()` finished filling in its parent field. This IS a real, live race, not a
/// theoretical one: measured directly on a busy host during this crate's own test runs (a
/// live, non-pid-1, freshly-forked process's sysctl record read `e_ppid == 0` while
/// `proc_pidinfo` already reported the true value moments earlier), diagnosed against
/// `ps -eo pid,ppid,comm` to confirm genuine process churn rather than an offset bug. A
/// separate synthetic stress harness (two threads, 30k `fork()`+`_exit` and 4k
/// `posix_spawn` iterations, ~2.3M records) did NOT reproduce it - which sharpens rather
/// than clears the finding, since a targeted fork-storm and ordinary host churn during a
/// parallel test run are different windows onto the same kernel-internal, userspace-
/// invisible race, the same class already documented for `proc_listallpids`'s walk cap.
/// Never trusted as a real ppid: [`ppid_of`] re-reads it until the fork finishes. The record
/// itself is otherwise valid (correctly sized, no sysctl/libproc error) - this is not
/// `contract_violation`'s "layout drifted or the kernel misbehaved" case, only a narrow timing
/// window - so an excluded `0` is a DESIGNED `None`, `debug`-logged like every other per-pid probe.
fn trusted_ppid(pid: RawPid, raw: RawPid) -> Option<RawPid> {
    if raw == 0 && pid > 1 {
        log::debug!(
            "pid {pid}'s process-info record reported ppid == 0 for a process other than pid 0 and 1 - a \
             fork()-in-progress record, not a resolvable ppid"
        );
        None
    } else {
        Some(raw)
    }
}

/// One attempt at `pid`'s parent pid.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum PpidRead {
    /// The parent pid and the start key, both from the one record the parent pid was read from.
    Found(RawPid, Key),
    /// The record reported an untrusted `e_ppid == 0` ([`trusted_ppid`]): `fork()` has not
    /// finished. Transient.
    Forking,
    /// The fallback positively confirmed the pid does not exist.
    Gone,
    /// The sysctl fallback was refused (`EPERM`/`EACCES`, a sandbox) or answered outside its
    /// contract. Persistent.
    Refused,
}

/// One attempt: [`read_record`], whose parent pid is trusted or the attempt is `Forking`.
fn read_ppid_once(pid: RawPid) -> PpidRead {
    #[cfg(test)]
    if let Some(read) = fault::next_ppid_read(pid) {
        return read;
    }
    match read_record(pid) {
        Resolved::Found(record) => match record.ppid(pid) {
            Some(ppid) => PpidRead::Found(ppid, record.key),
            None => PpidRead::Forking,
        },
        Resolved::Gone => PpidRead::Gone,
        Resolved::Unknown => PpidRead::Refused,
    }
}

/// Drive `read` to an answer. `Forking` is re-read after `pause(attempt)`; nothing else is.
fn resolve_ppid(mut read: impl FnMut() -> PpidRead, mut pause: impl FnMut(u32)) -> Resolved<(RawPid, Key)> {
    let mut attempt = 0;
    loop {
        match read() {
            PpidRead::Found(ppid, key) => return Resolved::Found((ppid, key)),
            PpidRead::Gone => return Resolved::Gone,
            PpidRead::Refused => return Resolved::Unknown,
            PpidRead::Forking => {
                pause(attempt);
                attempt = attempt.saturating_add(1);
            }
        }
    }
}

/// `pid`'s parent pid.
///
/// `Unknown` is only a PERSISTENT refusal: the sysctl fallback answering `EPERM`/`EACCES` (a
/// sandbox), which a re-read would not change. The other cause is transient, so it is not
/// `Unknown`: a record reporting the untrusted `e_ppid == 0` of a `fork()` in progress
/// ([`trusted_ppid`]) is re-read, with a growing pause, until it resolves. That re-checks a
/// deterministic condition - a fork always finishes - so it has neither a count cap nor a
/// deadline; the pid exiting meanwhile ends it as `Gone`. `Gone` is only returned when the
/// fallback itself positively confirms the pid no longer exists.
pub(crate) fn ppid_of(pid: RawPid) -> Resolved<RawPid> {
    ppid_and_key(pid).map(|(ppid, _)| ppid)
}

/// [`ppid_of`], with the start key of the record the parent pid was read from: the parent and the
/// identity of the process it was read for come from one read, so they describe the same process.
pub(super) fn ppid_and_key(pid: RawPid) -> Resolved<(RawPid, Key)> {
    resolve_ppid(|| read_ppid_once(pid), fork_pause)
}

/// The pause before re-reading a pid whose `fork()` is still filling in its parent: yield first,
/// then sleep for `2^attempt` microseconds, growing to 1 ms.
fn fork_pause(attempt: u32) {
    if attempt == 0 {
        std::thread::yield_now();
    } else {
        std::thread::sleep(Duration::from_micros(1 << attempt.min(10)));
    }
}

/// `proc_pidinfo` on self is always permitted, so the by-pid path cannot be denied here.
pub(super) fn current_token() -> Resolved<Key> {
    start_token(std::process::id())
}

pub(super) fn is_running(pid: RawPid, start: Key) -> Liveness {
    if let Some(info) = bsd_info(pid) {
        if token_of_bsd(&info) != start {
            return Liveness::Dead; // reused PID
        }
        // SZOMB == zombie (exited, unreaped). Anything else is a live process.
        return if info.pbi_status == libc::SZOMB {
            Liveness::Dead
        } else {
            Liveness::Alive
        };
    }
    // libproc-invisible: gone, a ZOMBIE, or an EPERM-hidden LIVE process (an unprivileged
    // cross-user query — pid 1 on darwin CI proved a miss is NOT always gone-or-zombie).
    // The fallback keeps the same shape — token-guarded, zombie-EXCLUSIVE via `p_stat` —
    // and a kinfo layout drift fails safe to the pre-fix answer (token mismatch => false).
    match kinfo::kinfo(pid) {
        Resolved::Found(info) => {
            // A reused PID names a different process; SZOMB is exited-but-unreaped. Both
            // are "not running", and neither is an unassessable read.
            if token_of_kinfo(&info) != start || info.kp_proc.p_stat as u32 == libc::SZOMB {
                Liveness::Dead
            } else {
                Liveness::Alive
            }
        }
        Resolved::Gone => Liveness::Dead,
        Resolved::Unknown => Liveness::Unknown,
    }
}

pub(super) fn created_at(start: Key) -> Option<SystemTime> {
    Some(SystemTime::UNIX_EPOCH + Duration::from_micros(start.raw()))
}

/// The `kinfo_proc` / `proc_bsdinfo` start time is absolute µs since the Unix epoch,
/// recorded once at creation, so it survives a reboot unchanged and needs no scope.
pub(super) fn session_scope() -> Result<super::persist::Scope, super::persist::ScopeReadError> {
    Ok(super::persist::Scope::none())
}

/// Test-only seam: a by-pid identity read answers `Unknown`, as an OS refusal would.
#[cfg(test)]
pub(crate) mod fault {
    use std::cell::RefCell;

    thread_local! {
        static UNKNOWN: RefCell<Vec<super::RawPid>> = const { RefCell::new(Vec::new()) };
        static PPID_READS: RefCell<Vec<(super::RawPid, std::collections::VecDeque<super::PpidRead>)>> =
            const { RefCell::new(Vec::new()) };
        static PPID_READ_COUNT: RefCell<Vec<(super::RawPid, usize)>> = const { RefCell::new(Vec::new()) };
    }

    /// Disarms [`force_unknown`] on drop.
    #[must_use = "dropping this immediately disarms the forced read"]
    pub(crate) struct Forced(());

    impl Drop for Forced {
        fn drop(&mut self) {
            UNKNOWN.with(|u| u.borrow_mut().clear());
            PPID_READS.with(|p| p.borrow_mut().clear());
            PPID_READ_COUNT.with(|p| p.borrow_mut().clear());
        }
    }

    /// Script the first attempts of `pid`'s parent read on THIS thread: each attempt takes the
    /// next of `reads`; once they run out the real read answers. Every attempt is counted, real
    /// or scripted ([`ppid_read_attempts`]).
    pub(crate) fn force_ppid_reads(pid: super::RawPid, reads: &[super::PpidRead]) -> Forced {
        PPID_READ_COUNT.with(|c| c.borrow_mut().retain(|&(p, _)| p != pid));
        PPID_READS.with(|p| p.borrow_mut().push((pid, reads.iter().copied().collect())));
        Forced(())
    }

    /// How many attempts `pid`'s parent read has made on THIS thread since the guard was made.
    pub(crate) fn ppid_read_attempts(pid: super::RawPid) -> usize {
        PPID_READ_COUNT.with(|c| c.borrow().iter().find(|&&(p, _)| p == pid).map_or(0, |&(_, n)| n))
    }

    pub(super) fn next_ppid_read(pid: super::RawPid) -> Option<super::PpidRead> {
        PPID_READ_COUNT.with(|c| {
            let mut c = c.borrow_mut();
            match c.iter_mut().find(|(p, _)| *p == pid) {
                Some((_, n)) => *n += 1,
                None => c.push((pid, 1)),
            }
        });
        PPID_READS.with(|p| {
            p.borrow_mut()
                .iter_mut()
                .find(|(q, _)| *q == pid)
                .and_then(|(_, reads)| reads.pop_front())
        })
    }

    /// Make every by-pid identity read of `pid` on THIS thread answer `Resolved::Unknown`.
    pub(crate) fn force_unknown(pid: super::RawPid) -> Forced {
        UNKNOWN.with(|u| u.borrow_mut().push(pid));
        Forced(())
    }

    pub(super) fn is_unknown(pid: super::RawPid) -> bool {
        UNKNOWN.with(|u| u.borrow().contains(&pid))
    }
}

#[cfg(test)]
#[path = "macos/ppid_tests.rs"]
mod ppid_tests;

#[cfg(test)]
#[path = "macos/origin_tests.rs"]
mod origin_tests;