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
//! 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.
fn exited(&self) -> Result<Exit<'_>, Error>;
/// 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<'_>;
}
/// 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), 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.
#[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. Only Linux's
/// [`Kernel`](crate::identity::Kernel) has methods yet; elsewhere `kernel` is not consulted.
pub(crate) fn open_with(
kernel: &dyn crate::identity::Kernel,
id: ProcessId,
) -> Result<Option<Box<dyn OsProcess>>, OpenFailure> {
#[cfg(target_os = "linux")]
{
Ok(linux::open::open_verified_with(kernel, id)?
.map(|pidfd| Box::new(linux::LinuxProcess::new(Some(id.pid()), pidfd)) as Box<dyn OsProcess>))
}
#[cfg(windows)]
{
let _ = kernel;
Ok(windows::WindowsProcess::open(id)?.map(|p| Box::new(p) as Box<dyn OsProcess>))
}
#[cfg(target_os = "macos")]
{
let _ = kernel;
Ok(macos::MacProcess::open(id)?.map(|p| Box::new(p) as Box<dyn OsProcess>))
}
}
/// 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::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())
}