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
//! Unix process-group and session containment.
//!
//! Two mechanisms are available:
//! - **ProcessGroup** (`process_group(0)` / `setpgid`): the child becomes a
//! process-group leader (pgid == pid). Teardown sends `killpg`. cgroup v2
//! preempts this on Linux when available. macOS uses this for
//! `ContainMode::Strongest`.
//! - **Session** (`setsid`): the child becomes a session leader *and*
//! process-group leader in a new session, detached from any controlling
//! terminal. Teardown is identical (`killpg` on the session's initial pgroup,
//! which equals the leader's pid). Useful for daemon-like children.
//!
//! **Mutual exclusivity:** `setsid` makes the child a session *and*
//! process-group leader simultaneously. Calling `setpgid`/`process_group(0)`
//! on a session leader fails with `EPERM`. Therefore Session mode applies
//! `setsid` *instead of* `process_group(0)` — never both.
//!
//! **Self-`setsid` escape:** a child that calls `setsid` itself exits the
//! parent's session/group; containment is then best-effort. This applies to
//! both mechanisms and is documented as a known limitation (not a sandbox).
//!
//! Parent-side signals use `nix` (not hand-rolled `libc`).
//!
//! # What `killpg` does and does not report
//! Its return value says only whether *at least one* member took the signal. A
//! group holding both a member we may signal and one we may not reports plain
//! success while the second keeps running, on both Unixes. macOS additionally
//! reports `EPERM` for a group whose survivors are all zombies, because xnu
//! excludes zombies from the pgrp iteration before counting. And on Linux even
//! `ESRCH` is not trustworthy as "definitely empty": `__kill_pgrp_info` keeps
//! overwriting its return value with each member's error until one succeeds, so
//! a departed member processed after a live refuser can leave the group's
//! overall `ESRCH` hiding that refuser. None of `killpg`'s three outcomes can be
//! trusted alone on either platform, so teardown always confirms itself against
//! the group's actual membership — see the `group` submodule.
//!
//! # PGID-reuse caveat
//! Reaping the leader (`wait`) alone is harmless: `killpg` on an absent pgid returns `ESRCH`,
//! which `signal_group`/`verify` above already treat as `Cleared`. The actual hazard is
//! narrower — the kernel recycling the leader's already-reaped PID/PGID onto a *different,
//! live* process group before `kill_tree`/`term_group` next runs: only then does `killpg` risk
//! signalling that unrelated group. This is reachable on the ORDINARY spawn-then-teardown path
//! for any fast-exiting child, not only via an explicit `wait()` before `kill_tree()`: `std`'s
//! `SharedChild::new` (inside `Command::spawn`) can reap a fast-exiting leader itself, before
//! the caller ever gets a `Child` handle back — see `child/spawn.rs`'s own comment on this race,
//! and `Child::kill_tree`'s precondition assert (`src/child.rs`), which fires on POSITIVE
//! evidence of an actual recycle (a different, live identity at the same pid), not on a mere
//! reap. cgroup v2 and the identity-reverifying TreeWalk mechanism do not have this hole at
//! all — prefer them when the guarantee matters.
use io;
use ;
use Pid;
use crateError;
/// Apply pre-spawn group setup to `std_cmd` (root spawns only).
/// Must not be combined with `set_session` on the same command.
pub
/// Apply pre-spawn session setup to `std_cmd` via a `pre_exec` `setsid` call
/// (root spawns only, `ContainMode::Session`).
///
/// `setsid` makes the child a session leader *and* process-group leader (pgid
/// == sid == pid), detached from any controlling terminal. Because the child is
/// already a process-group leader after `setsid`, calling `setpgid` or
/// `process_group(0)` on it would return `EPERM` — do not call
/// `set_process_group` on the same command.
///
/// The `pre_exec` closure is async-signal-safe: it calls only raw `libc::setsid`
/// (no allocation, no unwinding). Failure of `setsid` aborts the spawn.
pub
/// Hard-kill the whole process group, then confirm the group actually came
/// down. See [`signal_group`]. `Ok(())` means every member the ONE listing pass saw was
/// either reached or already gone — not an atomic, ongoing guarantee: a member that forks a
/// new process into the group after that listing (an ordinary respawning supervisor, not
/// only an adversarial fork-bomb) is never seen, never signalled, and does not affect the
/// verdict. `Attached::Cgroup` (Linux cgroup v2, `cgroup.kill`) is fork-proof where this
/// mechanism structurally cannot be; prefer it when that atomicity matters.
pub
/// Send the graceful signal to the whole process group, then confirm no live
/// member refused it. See [`signal_group`].
pub
/// Signal the group and report what was actually achieved. `killpg`'s return value is a
/// best-effort first delivery attempt, never the final verdict — see the module docs and
/// `verify` for why none of `Ok`/`ESRCH`/`EPERM` can be trusted alone on either platform.
///
/// **The `pgid` guard lives HERE, before any signal is sent — not only in `group::state`.**
/// A `pgid` of `0` signals the CALLER's own process group (per POSIX); a negative one risks
/// the broadcast/double-negation hazard this file's Background measures. A check placed after
/// the dangerous syscall it claims to guard is not a guard.
/// Turn the group's actual membership into a contract answer — the single source of truth
/// regardless of what `killpg` reported. See `group`'s module docs for the listing and
/// signal-delivery design (one pass; `SIGKILL` resends for real, `SIGTERM` only probes).
/// Signal `pid` directly. Already-gone is success. Kept, unmodified, because sibling #54
/// explicitly forbids touching this fallback — but the two signals it guards need opposite
/// framing, worked out fully rather than left as one general "unclear":
///
/// - **`kill_group` (`SIGKILL`)**: redundant for a member `converge` actually reaches, NOT
/// provably redundant overall. `converge` only resends to a member it has classified
/// `Liveness::Alive` AND successfully re-verified (`classify_member`/`check_or_signal`);
/// any member whose liveness or identity the OS refuses to confirm (`Liveness::Unknown` /
/// `Resolved::Unknown`) is never signalled by `converge` at all — for THOSE, this direct
/// call is the only delivery attempt, not a duplicate. It is also not the same check: this
/// call signals a bare `pid` number with NO identity verification, while `converge` refuses
/// to signal a pid whose token no longer matches — under the #54 pgid-recycle hazard the two
/// calls can have different, divergent targets. Kept because #54 forbids removing it, not
/// because it is proven safe or proven duplicative.
/// - **`term_group` (`SIGTERM`)**: NOT redundant — the only real one. `converge`'s `SIGTERM`
/// path deliberately never resends — only probes, to avoid tripping a program's own
/// double-signal escalation convention — so this is the ONLY actual `SIGTERM`
/// delivery attempt to the leader after `killpg` reports `EPERM`. Do not remove or reframe
/// this arm as optional for the graceful path.
///
/// Its failure is intentionally NOT propagated (best-effort; `verify`'s listing decides the
/// contract answer either way), but is now logged rather than silently discarded, so a
/// genuine `SIGTERM` delivery failure here — the one case that matters — leaves a trace.