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
//! Platform job layer — one `imp::Job` per target, all exposing the same shape.
//!
//! A `Job` is the kernel object that contains a process tree so the whole tree
//! dies with its owner:
//!
//! - **Windows** — a [Job Object] with `JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE`.
//! - **Linux** — a [cgroup v2] killed via `cgroup.kill`, falling back to a POSIX
//! process group when no writable cgroup is available.
//! - **FreeBSD** — a [process reaper] (`procctl(PROC_REAP_ACQUIRE)`) layered over
//! the same process-group bookkeeping: the tree is enumerated with
//! `PROC_REAP_GETPIDS` and torn down with `PROC_REAP_KILL`, so a descendant that
//! `setsid`s away is still contained. See `freebsd`.
//! - **macOS / the other BSDs** — a POSIX process group (`killpg` the tree on
//! drop); no cgroups, Job Objects or reapers exist there. See `pgroup`.
//!
//! Only Unix and Windows are supported; other targets fail to compile (see the
//! `compile_error!` below).
//!
//! [Job Object]: https://learn.microsoft.com/windows/win32/procthread/job-objects
//! [cgroup v2]: https://docs.kernel.org/admin-guide/cgroup-v2.html
//! [process reaper]: https://man.freebsd.org/cgi/man.cgi?query=procctl&sektion=2
use io;
use Duration;
use ;
use crateMechanism;
use crateSignal;
use crate;
use crateMemberInfo;
use crateProcessGroupStats;
/// The raw `SIGTERM` signal number — the default signal for the graceful
/// teardown tier (`graceful_shutdown` and the run-level graceful timeout).
/// Defined cross-platform; only *used* on unix (Windows' graceful tier ignores
/// the signal and kills the job atomically).
pub const SIGTERM_RAW: i32 = SIGTERM;
pub const SIGTERM_RAW: i32 = 15;
/// Serialize every Windows child-creation call made by ProcessKit.
///
/// Headless ConPTY launch briefly replaces this process's standard-handle slots
/// with null so the pseudoconsole, rather than redirected launcher stdio, owns
/// the child's handles. Ordinary and detached ProcessKit spawns must not observe
/// that process-global window. Code outside this crate cannot share this lock;
/// the remaining limitation is documented on [`crate::Command::use_pty`].
static PROCESS_SPAWN_LOCK: Mutex = new;
pub
// The generation-guarded "don't kill on Drop" latch. Split into its own module so
// the standalone loom harness (`loom/`) can `#[path]`-include just that pure core
// and model-check the spawn/shutdown re-arm race (T-079) — see `skip_drop_kill.rs`
// and `crate::sync`.
pub use SkipDropKill;
// The token a spawn's re-arm of that latch hands its own rollback. Only the Unix
// backends undo a spawn that way (`rollback_pty_spawn`), so only they name the type
// — re-exporting it unconditionally would be an unused import on Windows.
pub use DisplacedSpare;
// Test-only fault injection at the OS-primitive boundary of the platform backends:
// a unit test arms "this cgroup write / this Job Object info class / this signal
// delivery fails with this errno" and asserts what the crate reports, without a
// privileged or degraded host. Absent from every non-test build — see the module
// doc for why this shape was chosen over a trait layer at the same boundary.
pub
/// Per-process resource metrics sampled from the OS.
pub
/// An opaque snapshot of a process's OS-reported **start identity** — a start
/// timestamp captured once so a later metrics read can prove a pid still names the
/// *same* process instance, not one that recycled the number after the original
/// was reaped. Only ever compared for equality, never interpreted: the units are
/// platform-specific — Windows uses the process-creation `FILETIME` (100 ns units)
/// and Linux uses `/proc/<pid>/stat` field 22 (`starttime`, clock ticks since
/// boot); the `/proc`-less POSIX targets (macOS and the BSDs, FreeBSD's reaper
/// included) report none. This is the per-process
/// analogue of the pgroup backend's start-time identity token (see
/// `pgroup::read_identity`); it exists to keep a pid-reuse
/// race from folding an unrelated process's CPU/memory into a sample.
pub ;
// Constructed and read only by the Linux (`/proc` starttime) and Windows
// (creation `FILETIME`) backends; the `/proc`-less POSIX targets (macOS and the
// other BSDs in `unix.rs`, FreeBSD in `freebsd.rs`) report no identity and
// ignore the anchor, leaving both associated items unused there — allow it on
// exactly those targets rather than deleting methods the other two backends
// need (mirrors the `SpawnOptions` field pattern above).
/// Sample CPU time and peak memory for a single process by pid, but only when its
/// current OS identity still matches `expected` (see [`ProcIdentity`]). If the pid
/// was recycled by an unrelated process — its start identity no longer matching —
/// the read yields defaults (all `None`) rather than that stranger's counters, so
/// a sample can never be misattributed after PID reuse. `expected == None` skips
/// the check (no identity was captured, or the platform can't report one),
/// preserving the number-only behavior with no weakening. Returns defaults if the
/// process is gone or the platform can't report.
pub
/// Capture the OS start-time identity anchor of the *live* process at `pid`, or
/// `None` if the platform can't report one (macOS/BSD) or the process is already
/// gone. Captured once — at spawn for the per-process sampler, or when a cgroup
/// member is first read for a group-stats fold — and handed back to
/// [`process_metrics`] so a later reading taken against a recycled pid is
/// rejected rather than folded in.
pub
/// Identity + best-effort metadata for an **arbitrary** pid (not one tracked by
/// any group) — the platform-dispatching core of the public
/// [`process_info`](crate::process_info) query. Returns the same fields a
/// [`MemberInfo`] carries for a group member, read through the
/// **same** per-platform readers (`/proc/<pid>/stat` on Linux, `proc_pidinfo` on
/// macOS, `Toolhelp32` + creation `FILETIME` on Windows, a `kill(pid, 0)` existence
/// probe on the bare BSDs).
///
/// The three-way contract every backend upholds:
/// - `Ok(Some(info))` — the process exists; each enriching field is honestly
/// `Option` (`None` where the platform can't report it).
/// - `Ok(None)` — the process definitively does **not** exist (an honest negative,
/// never an error).
/// - `Err` — the process may exist but couldn't be inspected (a permission denial
/// or other OS error), so a caller never mistakes "not allowed to look" for
/// "dead".
///
/// Reads no argv/environment on any platform — the crate's standing "never
/// argv/env" rule.
pub
// Shared POSIX process-group backend: the Linux fallback, macOS/the other BSDs,
// and the bookkeeping substrate the FreeBSD reaper layers on.
pub
// Shared `/proc/<pid>/stat` parser for the Linux/Android backends. The pgroup
// liveness identity token (`pgroup::read_identity`) and the Linux per-process
// metrics sampler (`imp::process_metrics` / `process_identity`) all pull the same
// start-time field from the same file with the same "skip past the comm's last
// ')', then field 22 = whitespace index 19" convention; centralizing it here keeps
// that convention from drifting between them and silently weakening the
// anti-pid-reuse identity gate.
pub
// Shared graceful-shutdown escalation driver. The whole-tree
// signal → poll → escalate loop ([`graceful::run`]) and its [`GracefulTarget`]
// trait are cross-platform: all three unix mechanisms drive it (the cgroup, the
// process group and the FreeBSD reaper: SIGTERM → grace → SIGKILL), and the
// Windows Job Object drives it too for the opt-in console-CTRL graceful path
// (CTRL_BREAK → grace → `TerminateJobObject`). The single-child kill-and-reap
// primitive ([`graceful::run_pid`]/[`PidTarget`]/[`UnixChild`]) stays unix-only
// — it leans on `PidGate`/`libc` and drives the shared-group streaming-timeout
// teardown from `crate::running`. `pub(crate)` so both are reachable from those
// callers.
pub
// The linearizable pid gate: serializes every raw direct-child kill a detached
// teardown watchdog issues against the reap that frees (and lets the OS recycle)
// the pid. Cross-platform (the state machine is platform-agnostic; only the kill
// syscall behind `force_kill` differs); driven by `crate::running`.
pub
// The opt-in PTY launch backend (`Command::use_pty`): `openpty` (Unix) /
// `CreatePseudoConsole` ConPTY (Windows) instead of three pipes, wired into the
// SAME per-platform containment path as `Job::spawn` (K-032). Compiled only with
// the `pty` feature; the merged-stream `Backend::Pty` in `crate::running`
// consumes what it hands back.
pub
// The parent-side reader for a `merge_stderr_in_pipe` stage's shared
// stdout+stderr pipe, per platform: Unix drives the read end through tokio's
// reactor (`AsyncFd`); Windows, whose anonymous pipe handle cannot be registered
// with that reactor, blocks on a bridge thread of the module's own and
// interrupts it when the reader is dropped. Neither holds a thread of the
// runtime's shared blocking pool. Compiled on the two OS families that support
// the marker at all —
// `runner::launch` rejects it as `Unsupported` anywhere else, before a pipe
// exists.
pub
/// Per-spawn knobs that must reach the platform backend (the
/// `tokio::process::Command` can't carry them: creation flags have no getter,
/// and the pgroup backend must know about `setsid` *before* it sets a process
/// group).
pub
// processkit supports only Unix and Windows: it relies on `tokio::process` and
// on OS job / process-group primitives (cgroups, setpgid, Job Objects) that have
// no equivalent on bare targets like wasm. Fail with a clear message rather than
// a cascade of missing-symbol errors from a containment-less fallback.
compile_error!;
// Exactly one platform module is compiled per target. Each defines an `imp::Job`
// with the same inherent methods plus a kill-on-close `Drop`.
//
// The arms are mutually exclusive by construction, so at most one `path` ever
// applies: `windows` and `unix` are disjoint, `target_os = "freebsd"` implies
// `unix` and excludes `linux`, and the final catch-all subtracts both
// target-specific unix arms. Adding a target-specific backend therefore means
// adding its arm AND narrowing the catch-all in the same edit — otherwise two
// `path`s would apply at once. Only the FreeBSD arm is new: Windows, Linux, macOS
// and every other BSD resolve exactly where they did before.
/// A handle to an OS job owning a tree of child processes.
///
/// Dropping the `Job` hard-kills every process still inside it, so an exiting or
/// panicking owner never leaks subprocesses.
pub ;
/// Read-only prediction of the containment [`Mechanism`] a fresh [`Job`] would use
/// on this host **right now**, computed without creating any OS object or spawning
/// a process — the detection extracted from the group-creation path so it can back
/// the public `host_containment()` query as well.
///
/// A fixed constant on Windows ([`Mechanism::JobObject`]), FreeBSD
/// ([`Mechanism::ProcessReaper`]) and macOS/the other BSDs
/// ([`Mechanism::ProcessGroup`]); on Linux a best-effort read-only probe of cgroup
/// v2 availability and writability that agrees with [`Job::new`]'s selection on any
/// real host, differing only in the rare window where a writable-looking cgroup then
/// rejects leaf creation (see the Linux backend's `detect_mechanism`). The FreeBSD
/// constant carries an analogous — but far narrower — caveat, since acquiring reaper
/// status is a side effect this query must not have: see the FreeBSD backend's
/// `detect_mechanism`.
pub