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
//! macOS `(pid, ppid)` snapshot: `proc_listallpids` for the pid set, then
//! `identity::macos_ppid_of` per pid (the same `proc_pidinfo`-primary,
//! sysctl-fallback resolver `identity` uses for its own start token / liveness checks).
//!
//! Three things worth knowing (an EPERM gap — an unprivileged caller getting no edge for
//! another user's process — is CLOSED: `identity::macos_ppid_of` falls back to
//! `sysctl(KERN_PROC_PID)` on a `proc_pidinfo` miss, the same fallback `identity` itself uses
//! for zombies and EPERM-hidden cross-user processes):
//!
//! - Even with the fallback, an edge can still be dropped: the target pid genuinely exited
//! between the snapshot and the query, a sandbox denies the fallback's own sysctl (rare —
//! EPERM/EACCES there is a DESIGNED `Unknown`, not a second EPERM gap), or `e_ppid == 0`
//! mid fork() on both reads (pid 1 excepted — see `identity::macos::ppid_of`'s doc).
//! - A failed snapshot is reported as an EMPTY one, because `process_parents` has no error
//! channel. A tree walk over an empty snapshot finds no descendants, so the failure is
//! logged at `warn` naming that consequence.
//! - `proc_listallpids`' fill path caps its walk at `min(nprocs + 20, our buffer capacity)`,
//! using an UNLOCKED read of `nprocs` taken before the process list locks (confirmed
//! against XNU's `bsd/kern/proc_info.c`). Our buffer capacity is the sizing call's answer
//! (itself `nprocs + 20`, at sizing time) plus `HEADROOM`; the `+ 20` term is on both sides
//! of the comparison and cancels, so our buffer exceeds the kernel's fill-time cap only
//! while fewer than `HEADROOM` net new processes are created between the sizing call and
//! the fill call. Above that threshold OUR buffer is the binding limit instead, the fill
//! saturates, and `collect_pids`'s grow loop doubles and retries — exactly the case it
//! exists for. `written < cap` is therefore not an airtight completeness proof: even once
//! the buffer has grown past being the limit, a narrow, kernel-internal, userspace-invisible
//! race remains on every fill — ≥20 net new processes inside THAT fill's own
//! unlocked-read-to-locked-walk window. Nothing in this module can close it without
//! changing the underlying syscall.
use crate;
/// Extra pid slots asked for on top of the kernel's sizing answer, so the common case
/// needs exactly one fill: the process set can grow between the sizing call and the fill.
const HEADROOM: usize = 16;
/// How many denied pids to name in a snapshot's log line — enough to start a debugging
/// session from, not so many that a snapshot with hundreds of denials floods the log.
const DENIED_SAMPLE_CAP: usize = 5;
/// Read the parent pid of `pid` via `identity::macos_ppid_of` — `proc_pidinfo` primary,
/// sysctl fallback on a miss, and the shared zero-ppid guard, all owned by `identity::macos`
/// (see that module's `ppid_of` doc for why: this backend reuses it whole rather than
/// keeping a second `proc_pidinfo` call and a second copy of the guard here). The tri-state is
/// forwarded whole, not collapsed to `Option`: [`join_edges`] needs to tell a genuine absence
/// (`Gone` — the pid exited, a legitimate exclusion) apart from a refused query (`Unknown` —
/// e.g. a sandboxed sysctl refusal, or the fork-in-progress `e_ppid == 0` window hitting both
/// reads for this pid — a real gap in the ppid-walk channel, not a legitimate one). Silent
/// per-call either way: a dropped edge drops the pid's whole subtree in
/// `treewalk::descendants_with`, and [`snapshot`] is what surfaces the aggregate.
/// Buffer capacity, in PIDS, for a sizing answer of `needed` pids.
///
/// `proc_listallpids` is one of the libproc wrappers that CONVERTS before returning: it
/// calls `proc_listpids` — which answers in bytes — and divides by `sizeof(int)`. Both its
/// sizing answer and its fill answer are therefore PID COUNTS, unlike `proc_listpids` and
/// `proc_listpidspath`, which answer in bytes.
///
/// `saturating_add`, not `+`: `needed` ultimately comes from `interpret_written`'s
/// `libc::c_int`-derived bound today, but `capacity_for` is a private seam a future caller
/// could invoke with an unvalidated `usize`, and a plain `+` would panic in debug or
/// silently wrap in release for `needed` near
/// `usize::MAX`. Saturating is safe here: `collect_pids`'s `allocate` step rejects any
/// capacity whose byte size exceeds `i32::MAX` before ever allocating, so a saturated
/// `usize::MAX` capacity fails loudly one call later, not silently.
/// `proc_listallpids`' buffer-size argument — an `int` of BYTES — for a buffer of
/// `pid_count` pids. An error rather than a wrapped cast: a wrapped size would describe an
/// allocation that does not exist.
///
/// A negative `buffersize` is not rejected by `proc_listallpids` itself (measured: it is
/// silently read as a large unsigned byte count) - so callers of this function's output
/// depend on it never producing one. That contract is asserted below, not just documented:
/// `checked_mul` operates on `usize` (never negative) and `c_int::try_from` only succeeds
/// for values in `0..=c_int::MAX`, so the assertion cannot fire without a bug in this
/// function or in `c_int::try_from` itself - it exists to make that invariant loud rather
/// than assumed.
/// A completed fill. `Debug` so tests can call `.expect_err(..)` on a `Result<Filled, _>`.
/// Interpret `proc_listallpids`' raw return value as a pid count or an error.
///
/// Measured: a genuine kernel failure (a bad buffer pointer, EFAULT) reports as `0`,
/// never negative — so `written <= 0` is the correct failure guard. Narrowing it to
/// `written < 0` would read a real failure as a successful empty pid list. Applies
/// identically to the sizing form's return (also `proc_listallpids`, also measured
/// success-as-positive / failure-as-`0`).
///
/// Must be called immediately after the syscall whose return value it interprets —
/// `last_os_error` reads whatever errno the most recently invoked libc call left behind.
/// One `proc_listallpids` fill into `pids`, answering in PIDS (see [`capacity_for`]).
///
/// Its `size_argument_for` call is unreachable-on-error via the only production call chain
/// (`collect_pids` already validates the identical `cap` immediately before constructing
/// `pids` from it, so `pids.len()` here can never be a size `collect_pids` didn't already
/// accept) - kept anyway as a defensive contract (same reasoning as `capacity_for`'s
/// `saturating_add`, above).
/// Fill a growing buffer until the kernel's answer proves the buffer was not the limit —
/// until it reports FEWER pids than the buffer could hold.
///
/// The kernel fills whatever buffer it is handed and reports how many pids it wrote; it
/// does NOT report truncation. An answer equal to the capacity is therefore ambiguous —
/// the list may have been cut off at the buffer's edge — and the only way to tell is to
/// ask again with more room. This is why a fixed headroom is not enough: it narrows the
/// window in which the answer is a silent truncation instead of closing it.
///
/// Termination is by real conditions, never a counter. Each round doubles the capacity
/// actually produced (`pids.len()`, not the `cap` requested — see below), so either the
/// kernel's answer fits (the process table is bounded by `maxproc`) or the byte size stops
/// fitting in an `int` and `allocate` errors. The production `allocate_pids` checks the size
/// BEFORE allocating, so the error is reachable without first attempting the allocation it
/// would have rejected, and doubling cannot overflow because `size_argument_for` refuses
/// every capacity above `i32::MAX / 4` first.
///
/// `fill` and `allocate` are both injected: `fill` so the doubling logic can be pinned against
/// an exact, host-independent total and its error / over-report branches driven
/// deterministically - a live kernel CAN be forced to saturate on demand by starting from a
/// deliberately small `cap` (see `collect_pids_grows_against_the_live_kernel`), but not to
/// report a specific total, an error, or a bogus over-report; `allocate` so both the
/// doubling-then-refusal path and an allocation failure can be driven deterministically
/// without a real run to the true ~536M-pid boundary or genuine memory pressure. Production
/// passes [`fill_from_kernel`] and [`allocate_pids`]; that exact composition is pinned live in
/// `collect_pids_grows_against_the_live_kernel`.
///
/// `cap == 0` is refused up front as a real `Err`, in every build profile: a zero capacity
/// can never grow (`written < n` is `0 < 0` = false, so the "saturated, retry" branch would
/// spin at `n == 0` forever) — this runs inside `hard_kill`, where a hang is worse
/// than the truncation this function exists to prevent.
/// The production `allocate` step: validate the size argument, then reserve fallibly.
/// `try_reserve_exact`, not `vec![0; cap]`: this runs inside `hard_kill`, where a failed
/// allocation must be an error the caller can report rather than the abort
/// `handle_alloc_error` would take. `resize` after a successful reservation cannot
/// reallocate, so it cannot abort either.
/// The two live syscalls wired together. Separate from [`all_pids`] so tests can see the
/// round count and the error.
/// Every pid the kernel will list, given a way to perform the snapshot. Split from
/// [`all_pids`] so the `Err` arm - never reachable from a live syscall in a test, same
/// reasoning as `collect_pids`'s injected `fill` - is exercisable without a genuine
/// kernel-level failure.
/// Every pid the kernel will list. Empty on failure — see the module docs.
///
/// Test-only fault seam: [`force_blind_snapshot_for_next_call`] arms a thread-local that makes
/// the NEXT call on the calling thread report empty without touching the real syscall, as if
/// `proc_listallpids` itself had failed. This exists so `Marker::sweep`'s `incomplete`/`Err`
/// path can be exercised end-to-end through the real public `hard_kill()`/`terminate()` API
/// with a genuinely blind pass, rather than a synthetic in-process mock of `sweep`'s internals.
thread_local!
/// Arms (`true`) or disarms (`false`) the blind-snapshot fault for the next [`all_pids`] call
/// (via [`snapshot`]/[`process_parents`]) on the CALLING thread only — consumed automatically
/// on that one call, so a test does not need to remember to disarm it afterward.
pub
/// Join pids to `(pid, ppid)` edges, filtering non-positive pids first. Pure and taking its
/// input as a plain slice - deterministically testable with a synthetic `[0, -1, <a real
/// pid>]` input, unlike a live call, which depends on the host's process table happening to
/// contain a non-positive pid at all. Returns the edges, how many pids the OS DENIED a ppid
/// read for — a `Gone` pid is a legitimate exclusion (it simply exited) and is not counted;
/// only `Unknown` (denied) is, since that subtree is a real gap for a caller tracking
/// completeness (`snapshot`'s doc, `Marker::sweep`) — and a bounded sample of the denied pids
/// for logging.
/// Push `pid` onto `sample` unless it is already at [`DENIED_SAMPLE_CAP`]. Factored out of
/// [`join_edges`] so the cap is unit-testable on its own: there is no deterministic live
/// trigger for `Resolved::Unknown` (see [`snapshot`]'s doc), so a test exercising the cap
/// through a real `Marker::sweep`/`join_edges` call is not possible.
pub
/// Every listable pid, the `(pid, ppid)` edges readable from those pids, and how many pids the
/// OS DENIED a ppid read for (as opposed to simply having exited) — all from ONE enumeration,
/// so the ppid-walk teardown channel and macOS's fd-marker sweep (which additionally needs the
/// raw pid list to search for marker holders) cannot disagree about the host.
///
/// A denied pid's subtree is a real gap in the ppid-walk channel — e.g. after a
/// credential-changing `exec`, the same scenario the marker channel already names — not a
/// legitimate absence like a pid that simply exited; a caller tracking completeness
/// (`Marker::sweep`) folds this count into its own `incomplete` accounting instead of treating
/// it as one.
pub