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
//! Layer 1 of the process stack: one OS-facing object per process, found by [`open`] and driven
//! by [`drive`].
//!
//! An [`OsProcess`] answers two questions about a process, "did it exit" and "signal it", and
//! never reaps it. It owns no wait loop: when the process still runs, [`OsProcess::exited`] hands
//! out the OS primitive a caller can block or register on ([`WaitFor`]), and the driver loops
//! "look; if running, wait on what the look returned".
use std::fmt;
use crate::error::Error;
use crate::identity::ProcessId;
use crate::signal::{Sent, Sig};
pub(crate) mod child;
pub(crate) mod drive;
#[cfg(test)]
pub(crate) mod fake;
#[cfg(target_os = "linux")]
pub(crate) mod linux;
#[cfg(target_os = "macos")]
pub(crate) mod macos;
#[cfg(unix)]
pub(crate) mod poll;
#[cfg(windows)]
pub(crate) mod windows;
#[cfg(unix)]
use std::os::fd::BorrowedFd;
#[cfg(windows)]
use std::os::windows::io::BorrowedHandle;
/// One process, as the OS names it. `Send` so a driver may move it to a blocking thread, and
/// `Sync` so one open serves a signal and a wait from different threads.
pub(crate) trait OsProcess: Send + Sync + fmt::Debug {
/// Send `sig`. [`Sent::Gone`] when the process is no longer the one opened.
fn signal(&self, sig: Sig) -> Result<Sent, Error>;
/// Look at the process once, without blocking. A [`Exit::Running`] look carries what to wait
/// on for the next change; the wait ends on any change, so look again after it. On macOS
/// [`Exit::Exited`] means the process is a zombie or gone, not merely that its `NOTE_EXIT` has
/// fired; [`ProcessId::is_alive`] never reads `Alive` afterwards. A child another process holds
/// (its tracer, or launchd) gets no `NOTE_EXIT` until it is handed back, so its look reads the zombie
/// itself.
fn exited(&self) -> Result<Exit<'_>, Error>;
/// What one wait for the process's exit loops on ([`drive::exited_until`]): its own `Waitable`,
/// which may own the readiness source it blocks on, since a source that is read has one reader.
/// The default looks with [`exited`](OsProcess::exited) and waits on what that returns. It
/// is made before the wait's first look, so a source it arms misses no change after it.
fn exit_wait(&self) -> Result<ExitWait<'_>, Error> {
Ok(Box::new(drive::ProcessExit(self)))
}
/// The OS object that names the process, lent to platform-only consumers (Job Objects, resume,
/// cgroup attach). A fake lends its own wake fd or event, which names no process: code that
/// uses a handle is tested against real processes.
#[cfg(any(target_os = "linux", windows))]
fn os_handle(&self) -> child::OsHandle<'_>;
}
/// The wait [`OsProcess::exit_wait`] makes: `Send`, so the asynchronous driver's future is.
pub(crate) type ExitWait<'a> = Box<dyn drive::Waitable<Output = ()> + Send + 'a>;
/// What one look at a process found.
#[derive(Debug)]
pub(crate) enum Exit<'a> {
Exited,
Running(WaitFor<'a>),
/// macOS: the exit edge has fired but the process is not yet a zombie (or gone), or no edge will
/// come (another process holds the child), and nothing will signal the change: look again after a
/// backoff. A look that only asks whether it runs
/// reads this as running.
#[cfg_attr(
not(target_os = "macos"),
allow(dead_code, reason = "only macOS's exit edge precedes the state the exit is read in")
)]
Recheck,
}
/// What to block or register on to learn that a running process may have changed. Spurious
/// wakes are allowed; a wake is never the answer, the next look is.
#[derive(Debug)]
pub(crate) enum WaitFor<'a> {
/// Unix: a descriptor that polls readable once the process has exited, and that nothing reads:
/// the pidfd on Linux, a kqueue armed for the exit on macOS. A macOS [`OsProcess::exit_wait`]
/// hands out another: the kqueue it owns, readable on any change it armed for (exit, signal,
/// reap), which only that wait reads, draining it before each look.
#[cfg(unix)]
Readable(BorrowedFd<'a>),
/// Windows: the process handle; signalled once the process has exited.
#[cfg(windows)]
Signalled(BorrowedHandle<'a>),
}
/// The words of what a failed look at a process leaves undone.
#[cfg(unix)]
macro_rules! exit_unobserved {
() => {
"its exit cannot be observed"
};
}
/// What is left undone when the look that arms an exit watch cannot go ahead (macOS).
#[cfg(target_os = "macos")]
pub(crate) const EXIT_CONSEQUENCE: &str = exit_unobserved!();
/// What is left undone when an [`open`] cannot go ahead, for the errors it returns: the one open
/// serves every act on the process.
#[cfg(unix)]
pub(crate) const OPEN_CONSEQUENCE: &str = concat!(exit_unobserved!(), " and no signal was sent");
/// What a message calls a child whose pid is not known ([`OsChild::pid`](child::OsChild::pid)).
pub(crate) const PIDLESS_CHILD: &str = "the child (pid unknown)";
/// How a message names a child: `child 4242`, or what stands for a pid that is not known.
pub(crate) fn child_named(pid: Option<u32>) -> String {
pid.map_or_else(|| PIDLESS_CHILD.to_owned(), |pid| format!("child {pid}"))
}
/// Open the process `id` names. `Ok(None)`: it is gone, or its pid now names another process. The
/// tests' entry; the library opens through [`open_with`].
#[cfg(test)]
pub(crate) fn open(id: ProcessId) -> Result<Option<Box<dyn OsProcess>>, Error> {
open_with(crate::identity::HostKernel, id).map_err(OpenFailure::into_open_error)
}
/// Why an [`open_with`] opened nothing and found nothing gone. It logs nothing: the caller that
/// returns the error passes it on, and one that drops it warns.
#[derive(Debug)]
pub(crate) enum OpenFailure {
/// Linux: a pidfd call failed for a reason that says nothing about the target. The call and its
/// errno are for a consumer to build its own error from: [`into_open_error`](Self::into_open_error)
/// is [`Process::open`](crate::Process::open)'s.
#[cfg(target_os = "linux")]
Call(crate::identity::FailedCall),
/// An error already in its final form: every other failure, on every platform.
Finished(Error),
}
impl From<Error> for OpenFailure {
fn from(error: Error) -> Self {
OpenFailure::Finished(error)
}
}
impl OpenFailure {
/// The error [`Process::open`](crate::Process::open) documents: a failed call is
/// [`open_error`](linux::open::open_error), the rest as they are.
pub(crate) fn into_open_error(self) -> Error {
match self {
#[cfg(target_os = "linux")]
OpenFailure::Call(call) => linux::open::open_error(call),
OpenFailure::Finished(error) => error,
}
}
}
/// [`open`] through `kernel`: the one entry to the open, on every platform. The open checks `id`
/// through `kernel`, and the process it returns owns the same `kernel`, so every later read of it asks
/// that one. The kernel is as long-lived as the process: a borrow (what the walks pass, of one kernel
/// they open every member from) gives a process that lives inside the walk. Windows's open asks
/// its [`Kernel`](crate::identity::Kernel) nothing.
pub(crate) fn open_with<'k, K: crate::identity::Kernel + Send + 'k>(
kernel: K,
id: ProcessId,
) -> Result<Option<Box<dyn OsProcess + 'k>>, OpenFailure> {
#[cfg(target_os = "linux")]
{
Ok(linux::open::open_verified_with(&kernel, id)?
.map(|pidfd| Box::new(linux::LinuxProcess::new(kernel, Some(id.pid()), pidfd)) as Box<dyn OsProcess + 'k>))
}
#[cfg(windows)]
{
Ok(windows::WindowsProcess::open(kernel, id)?.map(|p| Box::new(p) as Box<dyn OsProcess + 'k>))
}
#[cfg(target_os = "macos")]
{
Ok(macos::MacosProcess::open(kernel, id)?.map(|p| Box::new(p) as Box<dyn OsProcess + 'k>))
}
}
/// Hard-kill the held process. Already gone: `Ok`.
pub(crate) fn kill(p: &dyn OsProcess) -> Result<(), Error> {
// `Gone` and `Delivered` are both success: nothing is left for the caller to do.
p.signal(Sig::Kill).map(|_: Sent| ())
}
/// Send the graceful termination signal to the held process, without waiting. Already gone: `Ok`.
#[cfg(unix)]
pub(crate) fn terminate(p: &dyn OsProcess) -> Result<(), Error> {
p.signal(Sig::Graceful(crate::signal::Signal::Term)).map(|_: Sent| ())
}
/// There is no [`Sig`] to send for it on Windows: `Unsupported`.
#[cfg(windows)]
pub(crate) fn terminate(_p: &dyn OsProcess) -> Result<(), Error> {
Err(Error::terminate_unsupported())
}