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
//! Backend-agnostic owned-process handle. A `Child` holds one of these and
//! forwards its wait/kill/identity operations to whichever backend spawned it:
//! the std path's [`SharedChild`], or (Windows only) the raw `CreateProcessW`
//! child [`RawChild`]. Keeping the fan-out here lets `Child` stay backend-blind.
use std::io;
use std::process::ExitStatus;
use std::time::Instant;
use super::shared::SharedChild;
#[cfg(windows)]
use super::spawn::windows_raw::RawChild;
/// The process backend behind an owned [`Child`](super::Child).
#[derive(Debug)]
pub(crate) enum ProcHandle {
/// std-spawned child, adopted into a [`SharedChild`] for concurrent wait/kill.
Std(SharedChild),
/// Raw `CreateProcessW` child owning the process handle directly.
#[cfg(windows)]
Raw(RawChild),
}
impl ProcHandle {
/// Adopt a std-spawned child. Adoption never reaps, so nothing is reaped yet.
pub(crate) fn std(shared: SharedChild) -> ProcHandle {
ProcHandle::Std(shared)
}
/// The unique id the handle checks its by-pid actions against. Tests only.
#[cfg(all(target_os = "macos", test))]
pub(crate) fn adopted_unique(&self) -> Option<u64> {
let ProcHandle::Std(shared) = self;
shared.adopted_unique()
}
/// Whether this handle itself has reaped the root: [`wait`](Self::wait),
/// [`try_wait`](Self::try_wait) or [`wait_deadline`](Self::wait_deadline) recorded the exit.
/// True from the moment the reap is recorded, even before the recording waiter returns. A reap by someone else is not seen here.
/// `Raw` (Windows) reads the process handle's signalled state: nothing is consumed there.
#[cfg_attr(not(unix), allow(dead_code, reason = "read only on unix and in tests"))]
pub(crate) fn is_reaped(&self) -> bool {
match self {
ProcHandle::Std(s) => s.is_reaped(),
#[cfg(windows)]
ProcHandle::Raw(r) => r.is_reaped(),
}
}
/// Block until the child exits.
pub(crate) fn wait(&self) -> io::Result<ExitStatus> {
match self {
ProcHandle::Std(s) => s.wait(),
#[cfg(windows)]
ProcHandle::Raw(r) => r.wait(),
}
}
/// The exit status if the child has already exited, else `None`.
pub(crate) fn try_wait(&self) -> io::Result<Option<ExitStatus>> {
match self {
ProcHandle::Std(s) => s.try_wait(),
#[cfg(windows)]
ProcHandle::Raw(r) => r.try_wait(),
}
}
/// Block until the child exits or `deadline` passes (`Ok(None)` at expiry).
pub(crate) fn wait_deadline(&self, deadline: Instant) -> io::Result<Option<ExitStatus>> {
match self {
// `SharedChild` decides expiry itself, from `crate::wait::now()`, never early.
ProcHandle::Std(s) => s.wait_deadline(deadline),
#[cfg(windows)]
ProcHandle::Raw(r) => r.wait_deadline(deadline),
}
}
/// Hard-kill the process (already-exited is success).
pub(crate) fn kill(&self) -> io::Result<()> {
match self {
ProcHandle::Std(s) => s.kill(),
#[cfg(windows)]
ProcHandle::Raw(r) => r.kill(),
}
}
/// [`kill`](ProcHandle::kill), reporting whether a signal was sent.
#[cfg(unix)]
pub(crate) fn kill_sent(&self) -> io::Result<crate::signal::Sent> {
match self {
ProcHandle::Std(s) => s.kill_sent(),
}
}
/// The pidfd naming the process, if it holds one (Linux).
#[cfg(unix)]
pub(crate) fn pidfd(&self) -> Option<std::os::fd::BorrowedFd<'_>> {
match self {
#[cfg(target_os = "linux")]
ProcHandle::Std(s) => s.pidfd(),
#[cfg(not(target_os = "linux"))]
ProcHandle::Std(_) => None,
}
}
/// Whether the process is still running, read without reaping it.
#[cfg(unix)]
pub(crate) fn is_running(&self) -> io::Result<bool> {
match self {
ProcHandle::Std(s) => s.is_running(),
}
}
/// Reap a child a tree kill has just ended, sending it nothing: the kill bounds the wait.
#[cfg(unix)]
pub(crate) fn reap_after_tree_kill(&self) -> crate::error::ChildFate {
use crate::error::ChildFate;
match self {
ProcHandle::Std(s) => {
#[cfg(test)]
crate::child::spawn::fault::run_between_kill_and_wait();
match s.wait() {
Ok(_) => ChildFate::Reaped,
Err(e) => {
log_teardown_wait_failure(s.id(), &e);
if e.raw_os_error() == Some(libc::ECHILD) {
ChildFate::Gone
} else {
ChildFate::Killed
}
}
}
}
}
}
/// The OS process id.
pub(crate) fn id(&self) -> u32 {
match self {
ProcHandle::Std(s) => s.id(),
#[cfg(windows)]
ProcHandle::Raw(r) => r.id(),
}
}
/// Best-effort teardown for `kill_on_drop`: kill then reap. NEVER blocks on an
/// unkillable child (an elevated child a plain parent cannot signal — POSIX EPERM,
/// Windows ACCESS_DENIED). The `Std` arm dispatches on the OBSERVED kill result, not
/// on any "elevation requested" flag: a child that gained privilege on its OWN (a
/// setuid helper, or `sudo` spawned with no `.elevate()`) also returns EPERM, and
/// keying on a request flag would take the blocking `wait()` and hang Drop forever.
/// The Windows `Raw` arm handles its own higher-integrity runas case via its flag.
pub(crate) fn teardown_on_drop(&self, id: crate::identity::ProcessId) -> crate::error::ChildFate {
use crate::error::ChildFate;
#[cfg(all(test, unix))]
crate::child::fault::note_root_teardown();
match self {
ProcHandle::Std(s) => {
#[cfg(unix)]
let (kill_result, delivered) = {
let sent = s.kill_sent();
let delivered = matches!(sent, Ok(crate::signal::Sent::Delivered));
(sent.map(drop), delivered)
};
#[cfg(not(unix))]
let kill_result = s.kill();
match std_teardown_action(&kill_result) {
// Kill succeeded: reap the zombie with a bounded blocking wait (SIGKILL
// cannot be caught, so the child's exit is guaranteed — this is the
// sanctioned real-child-exit wait).
StdTeardown::ReapBlocking => match s.wait() {
Ok(_) => ChildFate::Reaped,
Err(e) => {
log_teardown_wait_failure(s.id(), &e);
#[cfg(unix)]
if e.raw_os_error() == Some(libc::ECHILD) {
// Delivered, the kill is `Killed`; found nothing to signal, `Gone`.
return crate::wait::exit_only::Foreign::Gone.fate(delivered);
}
ChildFate::Killed
}
},
// Kill failed: NEVER block. Reap non-blockingly; if it was EPERM and the
// child is still running (an elevated child we cannot signal), warn.
StdTeardown::ReapNonBlocking => {
let looked = s.try_wait();
let still_running = !matches!(looked, Ok(Some(_)));
let permission_denied =
matches!(&kill_result, Err(e) if e.kind() == io::ErrorKind::PermissionDenied);
if still_running && permission_denied {
log::warn!(
"elevated child {} could not be terminated on drop (permission denied); leaving it running",
s.id()
);
}
crate::child::spawn::fate_of_a_look(looked.map_err(|e| e.raw_os_error()), Some(id))
}
}
}
#[cfg(windows)]
ProcHandle::Raw(r) => r.teardown_on_drop(id),
}
}
}
/// A failed reap after a successful kill: `ECHILD` (someone else reaped the child) is expected
/// and quiet; anything else leaves a zombie or an unread exit, and is a `warn`.
fn log_teardown_wait_failure(pid: u32, e: &io::Error) {
#[cfg(unix)]
let gone = e.raw_os_error() == Some(libc::ECHILD);
#[cfg(windows)]
let gone = false;
if gone {
log::debug!("teardown of child {pid}: it was reaped elsewhere before the reap after the kill");
} else {
log::warn!("teardown of child {pid}: the reap after the kill failed: {e}");
}
}
/// The teardown action for a `Std` child, decided purely from the observed kill result.
/// Extracted so the "any `Err` → NEVER a blocking wait" invariant is unit-testable without
/// a real EPERM (root-only) child.
#[derive(Debug, PartialEq, Eq)]
enum StdTeardown {
/// Kill succeeded: reap with a bounded blocking wait.
ReapBlocking,
/// Kill failed: reap non-blockingly; the child may survive (elevated → EPERM).
ReapNonBlocking,
}
fn std_teardown_action(kill_result: &io::Result<()>) -> StdTeardown {
match kill_result {
Ok(()) => StdTeardown::ReapBlocking,
Err(_) => StdTeardown::ReapNonBlocking,
}
}
#[cfg(test)]
#[path = "proc_handle_tests.rs"]
mod proc_handle_tests;