cosca 0.5.0

Unified cross-platform subprocess management: spawning, stdio, process trees, stable identity, and elevation.
Documentation
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
//! Linux death-watch + kill via pidfd. `pidfd_open` returns a fd that
//! becomes readable (POLLIN) when the task becomes a zombie (exits); polling never reaps.
//! `pidfd_send_signal` is identity-bound (no pid-reuse race). A refused `pidfd_open` is
//! [`Error::Unsupported`], a transient one [`Error::Io`] prefixed `pidfd_open:`; the errno
//! classification is documented once, on [`Error::Unsupported`].
//!
//! The kernel floor, the per-syscall versions, and how a refused syscall is classified
//! (`Unsupported` versus `Io`) are in the crate root's "Platform requirements". Without `openat2`
//! the checked `/proc` view cannot be built, and `open_verified` is `Unsupported` naming `openat2`.
//! `spawn` probes `pidfd_open` on this process's own pid before it forks ([`probe_pidfd_support`]),
//! so a refusal fails the spawn with no child; see `child::spawn::pidfd_handshake` for the rest.

use std::os::fd::AsFd;
use std::time::Instant;

use rustix::event::{poll, PollFd, PollFlags};
use rustix::process::{pidfd_open, pidfd_send_signal, Pid, PidfdFlags, Signal};

use crate::error::Error;
use crate::identity::{Existence, Liveness, PidfdTarget, ProcDir, ProcView, ProcessId, ViewUnreadable};

/// Open a pidfd for `id`, re-verifying identity. `Ok(None)` => already gone (treat as exited).
///
/// Every `/proc` read goes through one checked `/proc` dirfd shown to describe `id`'s pid
/// namespace; otherwise [`Error::Unassessable`], never a `Gone` off a foreign `/proc`.
pub(crate) fn open_verified(id: ProcessId, op: PidfdOp) -> Result<Option<rustix::fd::OwnedFd>, Error> {
    debug_assert!(
        id.pid() <= i32::MAX as u32,
        "pid {} exceeds i32::MAX; pidfd cast would truncate",
        id.pid()
    );
    let raw = Pid::from_raw(id.pid() as i32).expect("a resolvable ProcessId is never pid 0");
    match pidfd_open_checked(raw) {
        Ok(pidfd) => verify_pidfd_target(id, pidfd, op),
        Err(rustix::io::Errno::SRCH) => Ok(None),
        // pidfd_open needs a pid that resolves to a thread-group leader task. EINVAL (< 6.16) /
        // ENOENT (>= 6.16) means either a reaped process-group leader whose pid lives on as a PGID
        // (gone), or a non-leader tid: live, or a ptraced zombie thread kept until its tracer
        // waits. Errno alone can't tell, so re-verify.
        Err(e @ (rustix::io::Errno::INVAL | rustix::io::Errno::NOENT)) => verify_without_pidfd(id, op, e),
        Err(e) => match refusal_name(e) {
            Some(name) => Err(pidfd_open_unsupported(op, name)),
            None => Err(Error::Io(crate::error::io_context(
                "pidfd_open",
                std::io::Error::from(e),
            ))),
        },
    }
}

/// The operation that needed a pidfd, named in [`Error::Unsupported`]. It names what the caller
/// asked for, whoever owns the target.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum PidfdOp {
    /// Waiting for exit: `wait`, `wait_timeout`, and the grace wait of `graceful_shutdown*`.
    Wait,
    /// `kill`, and the escalation of `graceful_shutdown*`.
    Kill,
    /// `terminate`, and the first step of `graceful_shutdown*`.
    Terminate,
    /// Signalling a process-group member during teardown.
    GroupTeardown,
    /// `spawn`: adopting the child it just created.
    Spawn,
}

impl PidfdOp {
    fn name(self) -> &'static str {
        match self {
            PidfdOp::Wait => "process wait",
            PidfdOp::Kill => "process kill",
            PidfdOp::Terminate => "process terminate",
            PidfdOp::GroupTeardown => "process-group teardown",
            PidfdOp::Spawn => "spawn",
        }
    }

    /// What is left undone when this operation cannot go ahead, for an [`Error::Unassessable`].
    fn consequence(self) -> &'static str {
        match self {
            PidfdOp::Wait => "its exit cannot be observed",
            PidfdOp::Kill | PidfdOp::Terminate => "no signal was sent",
            PidfdOp::GroupTeardown => "process-group teardown verification",
            PidfdOp::Spawn => {
                debug_assert!(
                    false,
                    "spawn adopts through open_own_child, which never reports Unassessable"
                );
                "the spawned child cannot be adopted"
            }
        }
    }
}

/// The name of `errno` if `pidfd_open` answering it is a refusal: no pidfd is possible here.
/// The classification is documented on [`Error::Unsupported`].
fn refusal_name(errno: rustix::io::Errno) -> Option<&'static str> {
    match errno {
        rustix::io::Errno::NOSYS => Some("ENOSYS"),
        rustix::io::Errno::PERM => Some("EPERM"),
        rustix::io::Errno::ACCESS => Some("EACCES"),
        rustix::io::Errno::NODEV => Some("ENODEV"),
        _ => None,
    }
}

fn pidfd_open_unsupported(op: PidfdOp, errno_name: &str) -> Error {
    Error::Unsupported {
        op: op.name().into(),
        platform: "linux",
        detail: format!(
            "cosca requires pidfd_open (Linux \u{2265} 5.3), refused here: pidfd_open answered {errno_name}"
        ),
    }
}

/// A `pidfd_open` failure while spawning: a refusal is [`Error::Unsupported`], anything else `Io`.
pub(crate) fn spawn_open_error(errno: rustix::io::Errno) -> Error {
    match refusal_name(errno) {
        Some(name) => pidfd_open_unsupported(PidfdOp::Spawn, name),
        None => Error::Io(crate::error::io_context("pidfd_open", std::io::Error::from(errno))),
    }
}

/// The pre-fork probe: `pidfd_open` on this process's own pid, closed at once. Spawning forks
/// through std, which cannot hand back a pidfd, so a kernel or filter that refuses `pidfd_open`
/// has to be found out BEFORE the fork, or the child would exist with no pidfd. A refusal is
/// [`Error::Unsupported`] naming `spawn`; any other failure (`EMFILE`, `ENFILE`, `ENOMEM`) is `Io`
/// naming `pidfd_open`. Either way no child exists.
///
/// Two syscalls per spawn, and no cached verdict: a cache is process-global state, and a filter
/// can be installed after the first spawn.
pub(crate) fn probe_pidfd_support() -> Result<(), Error> {
    pidfd_open_checked(rustix::process::getpid())
        .map(drop)
        .map_err(spawn_open_error)
}

/// The next scripted `pidfd_open` outcome on THIS thread, for a `pidfd_open` made elsewhere: the
/// spawn handshake's is made by the child. See [`fault::force_pidfd_open_script`].
#[cfg(test)]
pub(crate) fn take_scripted_pidfd_open() -> Option<rustix::io::Errno> {
    fault::take_forced_pidfd_open_errno()
}

/// Open a pidfd for `pid`, a child this process spawned, and confirm it names that child.
/// `Ok(None)` means the child is gone: something else reaped it, so there is nothing to wait on.
///
/// This never goes through [`open_verified`], whose `EINVAL`/`ENOENT` arm applies foreign-process
/// semantics: for a child we forked the number is a thread-group leader, so `ESRCH`, `EINVAL` and
/// `ENOENT` alike mean it is gone (before 6.16 an `EINVAL` covers a reaped leader whose number
/// lives on as a PGID or SID; from 6.16 an `ESRCH` does, and `ENOENT` covers a number reused by a
/// non-leader thread). A refusal (`ENOSYS`, `EPERM`, `EACCES`, `ENODEV`) is
/// [`Error::Unsupported`], with no fallback; any other errno is `Io`.
///
/// - With `Some(id)`, and only when the checked `/proc` view is [`ProcView::Same`], the identity
///   is checked too: `Gone` is gone, and `Unknown` skips the check (never a release). A diverged
///   or unassessable view skips it: a live child is never released as foreign because of the
///   view, and the confirmation below decides.
/// - Then, on every view, `waitid(P_PIDFD, WEXITED | WNOHANG | WNOWAIT)` confirms the pidfd names
///   our child: `ECHILD` is gone. A pid reused by a process that is not our child answers it,
///   even if its start time matched.
#[cfg(test)]
pub(crate) fn open_own_child(pid: u32, id: Option<ProcessId>) -> Result<Option<rustix::fd::OwnedFd>, Error> {
    use crate::wait::exit_only::{self, Foreign, Peek, Target};

    debug_assert!(
        pid <= i32::MAX as u32,
        "pid {pid} exceeds i32::MAX; pidfd cast would truncate"
    );
    let raw = Pid::from_raw(pid as i32).expect("a spawned child's pid is never 0");
    let pidfd = match pidfd_open_checked(raw) {
        Ok(pidfd) => pidfd,
        Err(rustix::io::Errno::SRCH | rustix::io::Errno::INVAL | rustix::io::Errno::NOENT) => return Ok(None),
        Err(e) => return Err(spawn_open_error(e)),
    };
    // Never in a stdio slot: with 0, 1 or 2 closed, the lowest free number is one, and the
    // application may `dup2` its stdio back over it, destroying the pidfd.
    let pidfd = crate::above_stdio::above_stdio(pidfd).map_err(Error::Io)?;
    if let Some(id) = id {
        if let ProcView::Same(proc_dir) = crate::identity::proc_view() {
            if exists_checked(id, &proc_dir) == Existence::Gone {
                return Ok(None);
            }
        }
    }
    match exit_only::peek(&Target::PidFd(pidfd.as_fd())) {
        Ok(Peek::Foreign(Foreign::Gone)) => Ok(None),
        Ok(_) => Ok(Some(pidfd)),
        Err(e) => Err(Error::Io(e)),
    }
}

/// `pidfd_open` refused `id`'s pid with `errno`. `Ok(None)` when the process is provably gone;
/// otherwise an error, since a live target cannot be waited on or signalled through a pidfd.
///
/// - `kill(pid, 0)` answering `ESRCH` is `Gone` whatever `/proc` shows.
/// - Else the `/proc` view must be [`ProcView::Same`]: `Gone` means the process is gone.
///   `Present` is a non-leader thread: `Dead` (a ptraced zombie) is exited, `Alive` is
///   [`Error::NotThreadGroupLeader`]. `Unknown` from either query is `Unassessable`.
/// - `Diverged`, or a view that could not be established, is `Unassessable` naming the view and
///   the `pidfd_open` errno. A raw `Io` here would surface as a bare `NotFound` on 6.16+, which
///   reads as "gone", and `containment::unix::group` treats `Io` as "no pidfd" and falls back to
///   `kill(2)`.
///
/// No pidfd to cross-check against, so the view comes from [`proc_view`](crate::identity::proc_view).
fn verify_without_pidfd(
    id: ProcessId,
    op: PidfdOp,
    errno: rustix::io::Errno,
) -> Result<Option<rustix::fd::OwnedFd>, Error> {
    if id.signal_says_no_such_process() {
        return Ok(None);
    }
    match crate::identity::proc_view() {
        ProcView::Same(proc_dir) => match exists_checked(id, &proc_dir) {
            Existence::Gone => Ok(None),
            Existence::Present => match alive_checked(id, &proc_dir) {
                Liveness::Dead => Ok(None),
                Liveness::Alive => Err(Error::NotThreadGroupLeader {
                    pid: id.pid(),
                    detail: op.consequence().into(),
                    source: std::io::Error::from(errno),
                }),
                Liveness::Unknown => Err(unassessable(
                    id,
                    op,
                    "the OS refused the liveness query",
                    None,
                    Some(errno),
                )),
            },
            Existence::Unknown => Err(unassessable(
                id,
                op,
                "the OS refused the existence query",
                None,
                Some(errno),
            )),
        },
        ProcView::Diverged => Err(unassessable(
            id,
            op,
            "this process's /proc is an outer pid namespace's",
            None,
            Some(errno),
        )),
        ProcView::Unassessable(why) => Err(view_unreadable(id, op, why, Some(errno))),
    }
}

/// `pidfd_open` succeeded. Confirm that this process's `/proc` describes the target before
/// comparing its start token, and read that token through the same `/proc` dirfd.
///
/// The pidfd's fdinfo `Pid:` is the target as the mounted procfs numbers it (`0` if invisible
/// there). Equal to `id.pid()` means that procfs names the target under this number, so
/// `{pid}/stat` describes it: the start token then tells a recycled pid from the original.
/// Anything else is `Unassessable`.
fn verify_pidfd_target(
    id: ProcessId,
    pidfd: rustix::fd::OwnedFd,
    op: PidfdOp,
) -> Result<Option<rustix::fd::OwnedFd>, Error> {
    let proc_dir = crate::identity::ProcDir::open().map_err(|why| view_unreadable(id, op, why, None))?;
    match crate::identity::pidfd_pid_in_view(&proc_dir, pidfd.as_fd()) {
        Ok(PidfdTarget::Pid(pid)) if pid == id.pid() => {}
        // Reaped after `pidfd_open`: gone, and nothing to signal.
        Ok(PidfdTarget::Reaped) => return Ok(None),
        Ok(PidfdTarget::Pid(pid)) => {
            return Err(unassessable(
                id,
                op,
                &format!(
                    "the mounted /proc numbers the target {pid} (0 = invisible), so it is an outer pid namespace's"
                ),
                None,
                None,
            ));
        }
        Err(why) => return Err(unassessable(id, op, &why.reason, why.source, None)),
    }
    // A pid recycled before open means the original is already gone. An unassessable pid
    // (hidepid, EPERM) is NOT gone and must not be treated as one.
    match exists_checked(id, &proc_dir) {
        Existence::Present => Ok(Some(pidfd)),
        Existence::Gone => Ok(None),
        Existence::Unknown => Err(unassessable(id, op, "the OS refused the existence query", None, None)),
    }
}

/// `why`, the `/proc` view that could not be established, as an error for `id`:
/// [`Error::Unsupported`] naming `openat2` when that is missing, else [`unassessable`].
fn view_unreadable(id: ProcessId, op: PidfdOp, why: ViewUnreadable, pidfd_errno: Option<rustix::io::Errno>) -> Error {
    match why.unsupported(op.name()) {
        Some(unsupported) => {
            log::warn!("wait: pid {} {}: {unsupported}", id.pid(), op.name());
            unsupported
        }
        None => unassessable(id, op, &why.reason, why.source, pidfd_errno),
    }
}

/// [`Error::Unassessable`] for `id`, logged at `warn`. `why` (with `source`'s text, if any) and
/// the `pidfd_open` errno, if there was one, are in the message, so the cause survives a
/// caller that only prints it; `source()` is the OS error behind `why`, else the errno.
fn unassessable(
    id: ProcessId,
    op: PidfdOp,
    why: &str,
    source: Option<std::io::Error>,
    pidfd_errno: Option<rustix::io::Errno>,
) -> Error {
    let mut detail = format!("pid {} identity could not be confirmed: {why}", id.pid());
    if let Some(source) = &source {
        detail.push_str(&format!(": {source}"));
    }
    if let Some(errno) = pidfd_errno {
        detail.push_str(&format!(" (pidfd_open: {errno})"));
    }
    detail.push_str(&format!("; {}", op.consequence()));
    log::warn!("wait: {detail}");
    Error::Unassessable {
        detail,
        source: source.or_else(|| pidfd_errno.map(std::io::Error::from)),
    }
}

/// `pidfd_open`, with a test seam: a forced errno (see [`fault::force_pidfd_open_errno_once`])
/// replaces the syscall once.
#[cfg(test)]
fn pidfd_open_checked(raw: Pid) -> Result<rustix::fd::OwnedFd, rustix::io::Errno> {
    match fault::take_forced_pidfd_open_errno() {
        Some(errno) => Err(errno),
        None => pidfd_open(raw, PidfdFlags::empty()),
    }
}
#[cfg(not(test))]
fn pidfd_open_checked(raw: Pid) -> Result<rustix::fd::OwnedFd, rustix::io::Errno> {
    pidfd_open(raw, PidfdFlags::empty())
}

/// `id.exists_in(proc_dir)`, with a test seam: a forced [`Existence`] (see
/// [`fault::force_exists_once`]) replaces the `/proc` read once, to drive the `Unknown` arms; runs
/// [`fault::between_check_and_read`]'s hook first.
#[cfg(test)]
fn exists_checked(id: ProcessId, proc_dir: &ProcDir) -> Existence {
    fault::run_between_hook();
    match fault::take_forced_exists() {
        Some(existence) => existence,
        None => id.exists_in(proc_dir),
    }
}
#[cfg(not(test))]
fn exists_checked(id: ProcessId, proc_dir: &ProcDir) -> Existence {
    id.exists_in(proc_dir)
}

/// `id.is_alive_in(proc_dir)`, with a test seam: a forced [`Liveness`] (see
/// [`fault::force_alive_once`]) replaces the `/proc` read once.
#[cfg(test)]
fn alive_checked(id: ProcessId, proc_dir: &ProcDir) -> Liveness {
    match fault::take_forced_alive() {
        Some(liveness) => liveness,
        None => id.is_alive_in(proc_dir),
    }
}
#[cfg(not(test))]
fn alive_checked(id: ProcessId, proc_dir: &ProcDir) -> Liveness {
    id.is_alive_in(proc_dir)
}

#[cfg(test)]
pub(crate) mod fault {
    use crate::identity::{Existence, Liveness};
    use std::cell::Cell;
    thread_local! {
        static FORCE_PIDFD_OPEN_ERRNO: std::cell::RefCell<std::collections::VecDeque<Option<rustix::io::Errno>>> =
            const { std::cell::RefCell::new(std::collections::VecDeque::new()) };
        static FORCE_EXISTS: Cell<Option<Existence>> = const { Cell::new(None) };
        static FORCE_ALIVE: Cell<Option<Liveness>> = const { Cell::new(None) };
        static BETWEEN_HOOK: std::cell::RefCell<Option<Box<dyn FnOnce()>>> = const { std::cell::RefCell::new(None) };
    }

    /// Clears the between-check-and-read hook on drop, consumed or not.
    #[must_use = "dropping this immediately disarms the hook; bind it for the probe's duration"]
    pub(crate) struct BetweenHook(());

    /// Run `hook` once on THIS thread, after `open_verified` has checked that `/proc` describes
    /// the target and before it reads `{pid}/stat`: the window in which a `/proc` looked up by
    /// path could differ from the one that was checked.
    pub(crate) fn between_check_and_read(hook: impl FnOnce() + 'static) -> BetweenHook {
        BETWEEN_HOOK.with(|h| *h.borrow_mut() = Some(Box::new(hook)));
        BetweenHook(())
    }

    impl Drop for BetweenHook {
        fn drop(&mut self) {
            BETWEEN_HOOK.with(|h| h.borrow_mut().take());
        }
    }

    pub(super) fn run_between_hook() {
        if let Some(hook) = BETWEEN_HOOK.with(|h| h.borrow_mut().take()) {
            hook();
        }
    }

    /// Disarms the forced errno on drop, so an unconsumed force can't leak into the next test on
    /// this thread.
    #[must_use = "dropping this immediately disarms the forced errno; bind it for the probe's duration"]
    pub(crate) struct ForcedPidfdOpenErrno(());

    /// Force the NEXT `pidfd_open` inside `open_verified` on THIS thread to fail with `errno`,
    /// consumed the first time it's read.
    pub(crate) fn force_pidfd_open_errno_once(errno: rustix::io::Errno) -> ForcedPidfdOpenErrno {
        force_pidfd_open_script([Some(errno)])
    }

    /// Script the next `pidfd_open` calls inside `open_verified` on THIS thread, one entry per
    /// call: `Some(errno)` fails it, `None` lets it through. Calls past the script run for real.
    pub(crate) fn force_pidfd_open_script(
        script: impl IntoIterator<Item = Option<rustix::io::Errno>>,
    ) -> ForcedPidfdOpenErrno {
        FORCE_PIDFD_OPEN_ERRNO.with(|f| *f.borrow_mut() = script.into_iter().collect());
        ForcedPidfdOpenErrno(())
    }

    impl Drop for ForcedPidfdOpenErrno {
        fn drop(&mut self) {
            FORCE_PIDFD_OPEN_ERRNO.with(|f| f.borrow_mut().clear());
        }
    }

    pub(crate) fn take_forced_pidfd_open_errno() -> Option<rustix::io::Errno> {
        FORCE_PIDFD_OPEN_ERRNO.with(|f| f.borrow_mut().pop_front().flatten())
    }

    /// Disarms the forced `Existence` on drop; see [`ForcedPidfdOpenErrno`].
    #[must_use = "dropping this immediately disarms the forced existence; bind it for the probe's duration"]
    pub(crate) struct ForcedExists(());

    /// Force the NEXT `id.exists()` re-verify inside `open_verified` on THIS thread to answer
    /// `existence`, consumed the first time it's read.
    pub(crate) fn force_exists_once(existence: Existence) -> ForcedExists {
        FORCE_EXISTS.with(|f| f.set(Some(existence)));
        ForcedExists(())
    }

    impl Drop for ForcedExists {
        fn drop(&mut self) {
            FORCE_EXISTS.with(|f| f.set(None));
        }
    }

    pub(crate) fn take_forced_exists() -> Option<Existence> {
        FORCE_EXISTS.with(|f| f.take())
    }

    /// Disarms the forced `Liveness` on drop; see [`ForcedPidfdOpenErrno`].
    #[must_use = "dropping this immediately disarms the forced liveness; bind it for the probe's duration"]
    pub(crate) struct ForcedAlive(());

    /// Force the NEXT `id.is_alive_in(..)` inside `open_verified` on THIS thread to answer
    /// `liveness`, consumed the first time it's read.
    pub(crate) fn force_alive_once(liveness: Liveness) -> ForcedAlive {
        FORCE_ALIVE.with(|f| f.set(Some(liveness)));
        ForcedAlive(())
    }

    impl Drop for ForcedAlive {
        fn drop(&mut self) {
            FORCE_ALIVE.with(|f| f.set(None));
        }
    }

    pub(crate) fn take_forced_alive() -> Option<Liveness> {
        FORCE_ALIVE.with(|f| f.take())
    }
}

pub(crate) fn block_until_exit(id: ProcessId, deadline: Option<Option<Instant>>) -> Result<bool, Error> {
    let Some(pidfd) = open_verified(id, PidfdOp::Wait)? else {
        return Ok(true);
    };
    loop {
        let mut fds = [PollFd::new(&pidfd, PollFlags::IN)];
        // rustix 1.x poll takes Option<&Timespec> (None = infinite); Timespec is
        // { tv_sec: i64, tv_nsec: Nsecs }. Build it from the remaining duration.
        let ts = crate::wait::remaining(deadline).map(|d| rustix::event::Timespec {
            tv_sec: d.as_secs().min(i64::MAX as u64) as i64,
            tv_nsec: d.subsec_nanos() as _,
        });
        match poll(&mut fds, ts.as_ref()) {
            Ok(0) => return Ok(false), // timed out, still alive
            Ok(_) => {
                let revents = fds[0].revents();
                // POLLNVAL on an fd we own and hold alive is a contract violation.
                debug_assert!(
                    !revents.contains(PollFlags::NVAL),
                    "pidfd reported POLLNVAL — owned-fd contract violation"
                );
                if revents.contains(PollFlags::ERR) {
                    return Err(Error::Io(std::io::Error::other("pidfd poll returned POLLERR")));
                }
                return Ok(true); // POLLIN (zombie) / POLLHUP (reaped) => exited
            }
            Err(rustix::io::Errno::INTR) => continue, // retry only on EINTR (no cap)
            Err(e) => return Err(Error::Io(std::io::Error::from(e))),
        }
    }
}

pub(crate) fn kill(id: ProcessId) -> Result<(), Error> {
    let Some(pidfd) = open_verified(id, PidfdOp::Kill)? else {
        return Ok(());
    };
    match pidfd_send_signal(&pidfd, Signal::KILL) {
        Ok(()) => Ok(()),
        Err(rustix::io::Errno::SRCH) => Ok(()), // exited between re-verify and signal
        Err(e) => Err(Error::Io(std::io::Error::from(e))),
    }
}

pub(crate) fn terminate(id: ProcessId) -> Result<(), Error> {
    let Some(pidfd) = open_verified(id, PidfdOp::Terminate)? else {
        return Ok(());
    };
    match pidfd_send_signal(&pidfd, Signal::TERM) {
        Ok(()) => Ok(()),
        Err(rustix::io::Errno::SRCH) => Ok(()), // exited between re-verify and signal
        Err(e) => Err(Error::Io(std::io::Error::from(e))),
    }
}

#[cfg(test)]
#[path = "linux_tests.rs"]
mod linux_tests;

#[cfg(test)]
#[path = "linux_namespace_tests.rs"]
mod linux_namespace_tests;

#[cfg(test)]
#[path = "linux_openat2_tests.rs"]
mod linux_openat2_tests;