Skip to main content

aither_sandbox/
process_tree.rs

1//! A command's process tree: killing it, and finding what outlives the
2//! command's own shell.
3//!
4//! A job's lifetime is its whole tree, not its top-level shell. A `&` child
5//! outlives the shell that started it, and a `setsid` child also leaves the
6//! shell's process group, so no group signal reaches it. [`JobTree`] finds the
7//! descendants of one job from a snapshot of the process table:
8//!
9//! - every process in the job's process group, and every process whose
10//!   ancestry leads to one of the found processes or to the job's root;
11//! - every process of the same user whose environment carries the job's
12//!   marker, [`JobMarker`] — the link that survives `setsid` and the
13//!   reparenting that follows when the shell exits;
14//! - on macOS, every process whose parent's unique id (`p_puniqueid`) is that
15//!   of a process the job has seen, the root included, even one that has
16//!   exited since. The kernel records that id when the process is forked and
17//!   resets it to `launchd`'s (1) at the first `exec` the process makes after
18//!   it was reparented, so the link holds only until that `exec`.
19//!
20//! The job's task therefore watches the root from the moment it is spawned
21//! (kqueue `NOTE_FORK | NOTE_EXEC | NOTE_EXIT` on macOS) and scans on every
22//! event, so children enter the member set while their lineage is readable,
23//! and it keeps the unique ids of exited members for lineage.
24//!
25//! A process is identified by more than its pid, so a reused pid is never
26//! mistaken for a member: Linux pairs the pid with the start time in
27//! `/proc/<pid>/stat`, macOS uses the 64-bit unique id (see
28//! `platform::Spi` for the SPI it comes from). The identity is checked again
29//! right before every signal.
30//!
31//! The job's own task owns its member set; [`JobTree`] is the handle that
32//! sends it messages. The job's root is kept unreaped until the job ends
33//! ([`wait_for_exit`]), so its pid and process group stay reserved. A kill
34//! freezes the members with `SIGSTOP` until a pass finds nothing new, then
35//! sends `SIGKILL`, and a tracked member that survives is an error.
36//!
37//! What cannot be found. This paragraph covers every job until sandboxed jobs
38//! are attributed by the sandbox itself (lexoliu/heel#134); after that it
39//! describes unsafe jobs only, whose membership stays an approximation.
40//! A descendant is found by a scan that runs while it is still linkable: it
41//! is in the job's process group, its parent is the root or a process already
42//! seen, or its `p_puniqueid` is in the lineage. It escapes when it has left
43//! the group and every link it has leads only to processes that no scan saw
44//! alive, and it has no readable marker: it cleared it from its environment
45//! (`env -i`, a daemon that scrubs its environment), or its environment is
46//! unreadable (Apple's own binaries on macOS, another user's processes). Such
47//! a link leads nowhere when the process it names lived for less than one
48//! scan latency, or when an `exec` after a reparent reset it. A scan follows
49//! an event within about 5 ms on the development Mac (event delivery, the
50//! blocking-pool hand-off and a 1-3 ms lineage-only read), so a process that
51//! sets its session up faster than that after its fork, or whose every
52//! intermediate parent exits faster, can escape. The irreducible case is the
53//! double fork whose intermediates live for microseconds: no scan rate sees
54//! them. Such a process is invisible to the job; it is not reported as
55//! covered.
56//! Windows has no such tracking: `taskkill /T` ends the tree, and nothing
57//! finds a descendant that outlives its shell.
58//!
59//! Linux membership is exact only once heel provides a per-job subreaper
60//! (lexoliu/heel#129); until then Linux uses the marker and the ancestry scan.
61
62#[cfg(unix)]
63use std::time::Duration;
64
65/// The environment variable that marks every process of a job; its value is
66/// the job's [`JobMarker`].
67pub const JOB_MARKER_VAR: &str = "AITHER_JOB";
68
69/// How often a job whose shell has exited is checked for remaining
70/// descendants where the platform cannot signal exits, and how long a shared
71/// process-table scan may be reused meanwhile.
72#[cfg(target_os = "linux")]
73const DESCENDANT_POLL: Duration = Duration::from_millis(250);
74
75/// How many times a kill re-reads the process table to freeze a process that
76/// forked while the others were being stopped.
77#[cfg(unix)]
78const FREEZE_ROUNDS: u32 = 50;
79
80/// How many times a kill re-reads the process table to catch a process that
81/// forked while it was being killed.
82#[cfg(unix)]
83const KILL_ROUNDS: u32 = 50;
84
85/// The pause between two such reads.
86#[cfg(unix)]
87const KILL_ROUND_PAUSE: Duration = Duration::from_millis(10);
88
89/// Why a process tree could not be killed.
90#[derive(Debug, thiserror::Error)]
91pub enum KillTreeError {
92    /// The signal to the process group failed, locally or on a server.
93    #[error("failed to signal the process group: {0}")]
94    Signal(#[source] std::io::Error),
95    /// The descendants of the job could not be found or killed.
96    #[error(transparent)]
97    Descendants(#[from] ProcessTableError),
98    /// The job's process tree had already ended, so nothing was killed.
99    #[cfg(unix)]
100    #[error("the job's process tree had already ended")]
101    Ended,
102    /// `taskkill` could not be started.
103    #[cfg(windows)]
104    #[error("failed to run taskkill: {0}")]
105    Taskkill(#[source] std::io::Error),
106    /// `taskkill` ran and reported failure.
107    #[cfg(windows)]
108    #[error("taskkill reported failure ({status}): {stderr}")]
109    TaskkillFailed {
110        /// The exit status `taskkill` returned.
111        status: std::process::ExitStatus,
112        /// What `taskkill` wrote to its standard error.
113        stderr: String,
114    },
115    /// The job's supervisor could not end its tree; its report names any
116    /// process that survived.
117    #[cfg(target_os = "linux")]
118    #[error("the job's supervisor could not end its tree: {0}")]
119    Supervised(#[source] heel::supervisor::TreeKillError),
120}
121
122/// Why a job's descendants could not be found or killed.
123#[derive(Debug, thiserror::Error)]
124pub enum ProcessTableError {
125    /// The platform's process table could not be read.
126    #[error("cannot read the process table: {0}")]
127    Table(#[source] std::io::Error),
128    /// A process of the job could not be signalled, for example for lack of
129    /// permission.
130    #[error("cannot signal {} (pid {}): {source}", process.name, process.pid)]
131    Signal {
132        /// The process the signal was for.
133        process: JobProcess,
134        /// What `kill(2)` reported.
135        #[source]
136        source: std::io::Error,
137    },
138    /// Processes of the job were still alive after repeated `SIGKILL`.
139    #[error("processes of the job survived SIGKILL: {}", names(.0))]
140    Survived(Vec<JobProcess>),
141    /// The task that owns the job's processes ended before it answered.
142    #[error("the task tracking the job's processes ended")]
143    TaskEnded,
144}
145
146fn names(processes: &[JobProcess]) -> String {
147    processes
148        .iter()
149        .map(|process| format!("{} ({})", process.name, process.pid))
150        .collect::<Vec<_>>()
151        .join(", ")
152}
153
154/// A process of a job other than its top-level shell.
155#[derive(Debug, Clone, PartialEq, Eq)]
156pub struct JobProcess {
157    /// The process id.
158    pub pid: u32,
159    /// The command name the platform reports for the process.
160    pub name: String,
161}
162
163/// The value of [`JOB_MARKER_VAR`] in every process of one job: a fresh id,
164/// unrelated to the job's display name, so no other job or host shares it.
165#[derive(Debug, Clone, PartialEq, Eq)]
166pub struct JobMarker {
167    value: String,
168}
169
170impl JobMarker {
171    /// A marker no other job has.
172    #[must_use]
173    pub fn new() -> Self {
174        Self {
175            value: uuid::Uuid::new_v4().to_string(),
176        }
177    }
178
179    /// The environment entry every process of the job must be started with.
180    #[must_use]
181    pub fn entry(&self) -> (String, String) {
182        (JOB_MARKER_VAR.to_string(), self.value.clone())
183    }
184}
185
186impl Default for JobMarker {
187    fn default() -> Self {
188        Self::new()
189    }
190}
191
192/// Kills the process `pid` and every process in its process group.
193///
194/// On Unix `pid` must lead its own process group (spawned with
195/// `process_group(0)`), and the group receives `SIGKILL`; descendants that
196/// left the group are [`JobTree`]'s business. On Windows `taskkill /F /T` ends
197/// the tree.
198///
199/// # Errors
200///
201/// Returns [`KillTreeError`] when the kill could not be delivered.
202pub async fn kill_process_tree(pid: u32) -> Result<(), KillTreeError> {
203    #[cfg(unix)]
204    {
205        kill_group(pid)
206    }
207
208    #[cfg(windows)]
209    {
210        let output = async_process::Command::new("taskkill")
211            .args(["/F", "/T", "/PID", &pid.to_string()])
212            .output()
213            .await
214            .map_err(KillTreeError::Taskkill)?;
215        if output.status.success() {
216            Ok(())
217        } else {
218            Err(KillTreeError::TaskkillFailed {
219                status: output.status,
220                stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
221            })
222        }
223    }
224}
225
226/// The processes of each job rooted at `roots`, the root included, from one
227/// read of the process table: those of the root's process group and
228/// everything descending from them. A root that has exited yields no pids.
229///
230/// # Errors
231///
232/// Returns the error of reading the process table.
233#[cfg(unix)]
234pub fn tree_pids(roots: &[u32]) -> std::io::Result<Vec<Vec<u32>>> {
235    let (mode, _) = platform::identity_mode();
236    let table = platform::snapshot(mode, false)?;
237    let host = std::process::id();
238    let none = std::collections::HashSet::new();
239    let no_lineage = std::collections::HashSet::new();
240    Ok(roots
241        .iter()
242        .map(|&root| {
243            let alive = table.procs.iter().any(|process| process.pid() == root);
244            let members = unix::members(&table.procs, root, host, "", &none, &no_lineage);
245            alive
246                .then_some(root)
247                .into_iter()
248                .chain(members.into_iter().map(unix::Proc::pid))
249                .collect()
250        })
251        .collect())
252}
253
254/// Sends `SIGKILL` to the process group `pid` leads.
255#[cfg(unix)]
256fn kill_group(pid: u32) -> Result<(), KillTreeError> {
257    // SAFETY: `kill` takes plain integers and touches no memory.
258    let result = unsafe { libc::kill(-pid.cast_signed(), libc::SIGKILL) };
259    if result == 0 {
260        Ok(())
261    } else {
262        Err(KillTreeError::Signal(std::io::Error::last_os_error()))
263    }
264}
265
266/// Returns once the process `pid`, a child of this process, has exited, and
267/// leaves it unreaped: it stays a zombie, so its pid and process group stay
268/// reserved until the caller waits for it.
269///
270/// The exit is signalled by the kernel (a kqueue `NOTE_EXIT` on macOS, a
271/// pidfd on Linux, 5.3 or later), so a long-lived root holds no thread.
272///
273/// # Errors
274///
275/// Returns the OS error when `pid` is not a child of this process.
276#[cfg(unix)]
277pub async fn wait_for_exit(pid: u32) -> std::io::Result<()> {
278    // Registered before the check, so an exit between them is not missed.
279    let watch = platform::ExitWatch::new(pid)?;
280    if exited_unreaped(pid)? {
281        return Ok(());
282    }
283    watch.exited().await
284}
285
286/// Whether the child `pid` has exited, without reaping it.
287#[cfg(unix)]
288fn exited_unreaped(pid: u32) -> std::io::Result<bool> {
289    wait_unreaped(pid, libc::WNOHANG)
290}
291
292/// Blocks until the child `pid` has exited, without reaping it.
293///
294/// Called only once the kernel reported the child exiting, so it returns
295/// within the kernel's own exit teardown.
296#[cfg(target_os = "macos")]
297fn block_until_exited_unreaped(pid: u32) -> std::io::Result<()> {
298    wait_unreaped(pid, 0).map(drop)
299}
300
301/// `waitid` for the exit of the child `pid` with `WNOWAIT` and `flags`;
302/// whether it reported the exit.
303#[cfg(unix)]
304fn wait_unreaped(pid: u32, flags: libc::c_int) -> std::io::Result<bool> {
305    loop {
306        // SAFETY: `siginfo_t` is plain data for which all-zero bytes are valid.
307        let mut info: libc::siginfo_t = unsafe { std::mem::zeroed() };
308        // SAFETY: `info` is live memory of the type `waitid` writes; `WNOWAIT`
309        // leaves the child waitable.
310        let result = unsafe {
311            libc::waitid(
312                libc::P_PID,
313                pid,
314                &raw mut info,
315                libc::WEXITED | libc::WNOWAIT | flags,
316            )
317        };
318        if result == 0 {
319            // `waitid` leaves `si_pid` zero when no child has exited yet.
320            #[cfg(target_os = "linux")]
321            // SAFETY: `waitid` filled `info`.
322            let reported = unsafe { info.si_pid() };
323            #[cfg(not(target_os = "linux"))]
324            let reported = info.si_pid;
325            return Ok(reported != 0);
326        }
327        let error = std::io::Error::last_os_error();
328        if error.kind() != std::io::ErrorKind::Interrupted {
329            return Err(error);
330        }
331    }
332}
333
334/// Every scan of the process table may share one cache where reading is dear
335/// (Linux), so jobs checking in the same tick read the table once between
336/// them. A read never holds the cache's lock.
337///
338/// One scanner belongs to one registry, and clones share it.
339///
340/// On Linux the supervisor owns the trees it watches, so it is kept for its
341/// tests and the other Unixes.
342#[cfg_attr(target_os = "linux", allow(dead_code))]
343#[derive(Debug, Clone, Default)]
344pub struct ProcessScanner {
345    #[cfg(target_os = "linux")]
346    cache: std::sync::Arc<std::sync::Mutex<Option<CachedTable>>>,
347}
348
349/// A process table and when it was read.
350#[cfg(target_os = "linux")]
351type CachedTable = (std::time::Instant, std::sync::Arc<unix::Table>);
352
353#[cfg(unix)]
354impl ProcessScanner {
355    /// The process table as it was at most `max_age` ago; a zero age always
356    /// reads it afresh. `markers` asks for the environment markers, which
357    /// are most of a read's cost; a table without them still links processes
358    /// by group, ancestry and lineage.
359    fn table(
360        &self,
361        max_age: Duration,
362        mode: platform::IdentityMode,
363        markers: bool,
364    ) -> std::io::Result<std::sync::Arc<unix::Table>> {
365        self.table_with(max_age, || platform::snapshot(mode, markers))
366    }
367
368    /// [`Self::table`] with the read `read` performs. The cache is checked
369    /// and filled under its lock, and `read` runs outside it, so concurrent
370    /// reads proceed together.
371    #[cfg_attr(not(target_os = "linux"), allow(clippy::unused_self))]
372    fn table_with(
373        &self,
374        max_age: Duration,
375        read: impl FnOnce() -> std::io::Result<unix::Table>,
376    ) -> std::io::Result<std::sync::Arc<unix::Table>> {
377        #[cfg(target_os = "linux")]
378        if !max_age.is_zero()
379            && let Some((at, table)) = self
380                .cache
381                .lock()
382                .unwrap_or_else(std::sync::PoisonError::into_inner)
383                .as_ref()
384            && at.elapsed() < max_age
385        {
386            return Ok(std::sync::Arc::clone(table));
387        }
388        #[cfg(not(target_os = "linux"))]
389        let _ = max_age;
390        let table = std::sync::Arc::new(read()?);
391        #[cfg(target_os = "linux")]
392        {
393            *self
394                .cache
395                .lock()
396                .unwrap_or_else(std::sync::PoisonError::into_inner) =
397                Some((std::time::Instant::now(), std::sync::Arc::clone(&table)));
398        }
399        Ok(table)
400    }
401}
402
403/// The process tree of one local job: its root shell and everything that
404/// descends from it, wherever the descendants have gone.
405///
406/// On Linux the tree is owned by the job's supervisor
407/// ([`TrackedJob::Supervised`]), which is a child subreaper inside the
408/// sandbox, so a descendant that empties its environment, double-forks or
409/// leaves its session is still attributed and still dies with the job.
410/// Everywhere else it is the job's own task watching the process table.
411#[derive(Debug, Clone)]
412pub struct JobTree {
413    #[cfg(windows)]
414    root: u32,
415    #[cfg(unix)]
416    tracked: TrackedJob,
417}
418
419/// How a Unix job's tree is owned.
420#[cfg(unix)]
421#[derive(Debug, Clone)]
422enum TrackedJob {
423    /// A handle to the job's own task, which owns the set of processes found
424    /// so far. Cloning keeps a handle to the same task.
425    ///
426    /// Only the other Unixes and the tests use it: on Linux the supervisor
427    /// owns the tree.
428    #[cfg_attr(target_os = "linux", allow(dead_code))]
429    Watched(async_channel::Sender<unix::Command>),
430    /// A handle to the job's `heel supervise` supervisor: the tree is ended
431    /// through it, not by signalling the process group.
432    #[cfg(target_os = "linux")]
433    Supervised(heel::supervisor::TreeControl),
434}
435
436#[cfg(unix)]
437#[cfg_attr(target_os = "linux", allow(dead_code))]
438impl JobTree {
439    /// Starts the task of the job whose root shell is `root`, a process group
440    /// leader the caller keeps unreaped until [`JobTree::finish`], and whose
441    /// processes carry `marker` in [`JOB_MARKER_VAR`].
442    ///
443    /// Call it right after the root was spawned: it reads the root's unique
444    /// id and starts watching the root before returning, so the children the
445    /// root forks are seen while their lineage can still be read.
446    pub fn spawn<E: executor_core::Executor>(
447        executor: &E,
448        scanner: ProcessScanner,
449        root: u32,
450        marker: &JobMarker,
451    ) -> Self {
452        let (commands, inbox) = async_channel::unbounded();
453        let task = unix::Task::new(root, marker.value.clone(), scanner);
454        executor_core::Task::detach(executor.spawn(task.run(inbox)));
455        Self {
456            tracked: TrackedJob::Watched(commands),
457        }
458    }
459
460    /// The tree of a job whose command runs under `heel supervise`.
461    ///
462    /// The supervisor already owns membership — every orphan of the job
463    /// reparents to it — so the job asks it to end the tree and trusts its
464    /// report rather than scanning the process table.
465    #[cfg(target_os = "linux")]
466    #[must_use]
467    pub const fn supervised(control: heel::supervisor::TreeControl) -> Self {
468        Self {
469            tracked: TrackedJob::Supervised(control),
470        }
471    }
472
473    /// Sends `command` to the job's task and returns its answer; `None` when
474    /// the task has ended, which it does only once the job did.
475    async fn ask_at<T>(
476        &self,
477        commands: &async_channel::Sender<unix::Command>,
478        command: impl FnOnce(async_channel::Sender<T>) -> unix::Command,
479    ) -> Result<Option<T>, ProcessTableError> {
480        let (reply, answer) = async_channel::bounded(1);
481        if commands.send(command(reply)).await.is_err() {
482            return Ok(None);
483        }
484        answer
485            .recv()
486            .await
487            .map(Some)
488            .map_err(|_| ProcessTableError::TaskEnded)
489    }
490
491    /// Kills the whole job: its process group, then every descendant that is
492    /// still alive.
493    ///
494    /// # Errors
495    ///
496    /// Returns [`KillTreeError`] when a process cannot be signalled, when the
497    /// process table cannot be read, when a process the job tracks is still
498    /// alive after repeated kills, or when the tree had already ended
499    /// ([`KillTreeError::Ended`]): nothing was killed then.
500    pub async fn kill(&self) -> Result<(), KillTreeError> {
501        match &self.tracked {
502            TrackedJob::Watched(commands) => {
503                self.ask_at(commands, |reply| unix::Command::Kill { group: true, reply })
504                    .await?
505                    .ok_or(KillTreeError::Ended)??;
506            }
507            #[cfg(target_os = "linux")]
508            TrackedJob::Supervised(control) => {
509                control.kill().await.map_err(KillTreeError::Supervised)?;
510            }
511        }
512        Ok(())
513    }
514
515    /// Kills every descendant of the job that is alive and returns what it
516    /// killed; empty when none was.
517    ///
518    /// # Errors
519    ///
520    /// Returns [`ProcessTableError`] when the process table cannot be read, a
521    /// process cannot be signalled, or a tracked descendant survives repeated
522    /// `SIGKILL`.
523    pub async fn kill_descendants(&self) -> Result<Vec<JobProcess>, ProcessTableError> {
524        match &self.tracked {
525            TrackedJob::Watched(commands) => Ok(self
526                .ask_at(commands, |reply| unix::Command::Kill {
527                    group: false,
528                    reply,
529                })
530                .await?
531                .transpose()?
532                .unwrap_or_default()),
533            // A supervised job's supervisor has already torn its tree down
534            // by the time descendants are asked for; what it killed arrives
535            // in the wait's report.
536            #[cfg(target_os = "linux")]
537            TrackedJob::Supervised(_) => Ok(Vec::new()),
538        }
539    }
540
541    /// Returns once no descendant of the job is alive.
542    ///
543    /// Ends only when the tree is empty, so the caller bounds it with the
544    /// job's own timeout and kill.
545    ///
546    /// # Errors
547    ///
548    /// Returns [`ProcessTableError`] when the process table cannot be read.
549    pub async fn wait_descendants_exit(&self) -> Result<(), ProcessTableError> {
550        match &self.tracked {
551            TrackedJob::Watched(commands) => {
552                self.ask_at(commands, unix::Command::Wait)
553                    .await?
554                    .transpose()?;
555            }
556            // A supervised background job's supervisor exits only once the
557            // last descendant has, which the caller's own wait on the child
558            // already covers; a supervised foreground job's teardown is
559            // reported by that same wait.
560            #[cfg(target_os = "linux")]
561            TrackedJob::Supervised(_) => {}
562        }
563        Ok(())
564    }
565
566    /// Ends the job's task. Called before the root is reaped: afterwards the
567    /// root's pid may belong to any process, so every later kill does nothing.
568    pub async fn finish(&self) {
569        match &self.tracked {
570            TrackedJob::Watched(commands) => {
571                let _ = self.ask_at(commands, unix::Command::Finish).await;
572            }
573            #[cfg(target_os = "linux")]
574            TrackedJob::Supervised(_) => {}
575        }
576    }
577}
578
579#[cfg(windows)]
580impl JobTree {
581    /// The tree of the job whose root shell is `root`.
582    pub const fn spawn<E: executor_core::Executor>(
583        _executor: &E,
584        _scanner: ProcessScanner,
585        root: u32,
586        _marker: &JobMarker,
587    ) -> Self {
588        Self { root }
589    }
590
591    /// Kills the root and its tree with `taskkill /T`.
592    ///
593    /// # Errors
594    ///
595    /// Returns [`KillTreeError`] when `taskkill` fails.
596    pub async fn kill(&self) -> Result<(), KillTreeError> {
597        kill_process_tree(self.root).await
598    }
599
600    /// Windows finds no descendants beyond `taskkill /T`.
601    ///
602    /// # Errors
603    ///
604    /// Never fails.
605    #[allow(clippy::unused_async)]
606    pub async fn kill_descendants(&self) -> Result<Vec<JobProcess>, ProcessTableError> {
607        Ok(Vec::new())
608    }
609
610    /// Windows finds no descendants beyond `taskkill /T`.
611    ///
612    /// # Errors
613    ///
614    /// Never fails.
615    #[allow(clippy::unused_async)]
616    pub async fn wait_descendants_exit(&self) -> Result<(), ProcessTableError> {
617        Ok(())
618    }
619
620    /// Nothing to end.
621    #[allow(clippy::unused_async)]
622    pub async fn finish(&self) {}
623}
624
625/// The watched-tree machinery a Linux build keeps for the tests and the
626/// other Unixes only: the supervisor owns the trees there.
627#[cfg(unix)]
628#[cfg_attr(target_os = "linux", allow(dead_code))]
629mod unix {
630    use std::{collections::HashSet, io, time::Duration};
631
632    use async_channel::{Receiver, Sender};
633
634    use super::{
635        FREEZE_ROUNDS, JobProcess, KILL_ROUND_PAUSE, KILL_ROUNDS, ProcessScanner,
636        ProcessTableError, platform,
637    };
638
639    /// What identifies one process for as long as the kernel runs: the pid
640    /// alone is reused.
641    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
642    pub(super) struct Identity {
643        pub(super) pid: u32,
644        pub(super) birth: Birth,
645    }
646
647    /// What distinguishes the process that has a pid now from any other that
648    /// had it before.
649    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
650    pub(super) enum Birth {
651        /// The start time in clock ticks since boot, `/proc/<pid>/stat`
652        /// field 22 (Linux).
653        #[cfg_attr(not(target_os = "linux"), allow(dead_code))]
654        Ticks(u64),
655        /// The kernel's 64-bit unique process id, never reused (macOS).
656        #[cfg_attr(not(target_os = "macos"), allow(dead_code))]
657        Unique(u64),
658        /// The start time `proc_bsdinfo` reports (macOS fallback).
659        #[cfg_attr(not(target_os = "macos"), allow(dead_code))]
660        Started { seconds: u64, micros: u64 },
661    }
662
663    impl Birth {
664        /// The unique id, when that is what identifies the process.
665        pub(super) const fn unique(self) -> Option<u64> {
666            match self {
667                Self::Unique(id) => Some(id),
668                Self::Ticks(_) | Self::Started { .. } => None,
669            }
670        }
671    }
672
673    /// One row of the process table.
674    #[derive(Debug, Clone)]
675    pub(super) struct Proc {
676        pub(super) identity: Identity,
677        pub(super) ppid: u32,
678        /// The parent's unique id as it was when the process was forked
679        /// (macOS). The kernel resets it to `launchd`'s at the first `exec`
680        /// after the process was reparented.
681        pub(super) parent_unique: Option<u64>,
682        pub(super) pgid: u32,
683        pub(super) zombie: bool,
684        pub(super) name: String,
685        /// The value of the job marker in the environment, read for live
686        /// processes of this user only.
687        pub(super) marker: Option<String>,
688    }
689
690    impl Proc {
691        pub(super) const fn pid(&self) -> u32 {
692            self.identity.pid
693        }
694
695        const fn unique(&self) -> Option<u64> {
696            self.identity.birth.unique()
697        }
698    }
699
700    /// The process table at one moment.
701    #[derive(Debug)]
702    pub(super) struct Table {
703        pub(super) procs: Vec<Proc>,
704    }
705
706    /// A process of the job found in one scan.
707    #[derive(Debug, Clone)]
708    pub(super) struct Member {
709        pub(super) identity: Identity,
710        pub(super) name: String,
711        pub(super) zombie: bool,
712    }
713
714    impl Member {
715        fn process(&self) -> JobProcess {
716            JobProcess {
717                pid: self.identity.pid,
718                name: self.name.clone(),
719            }
720        }
721    }
722
723    /// The members of the job rooted at `root`: processes of `known`, of the
724    /// root's process group, carrying `marker`, and everything whose ancestry
725    /// or lineage reaches one of those or the root. `lineage` holds the unique
726    /// ids of every process the job has seen, the root and the exited ones
727    /// included. The root and the host are never members.
728    pub(super) fn members<'a>(
729        table: &'a [Proc],
730        root: u32,
731        host: u32,
732        marker: &str,
733        known: &HashSet<Identity>,
734        lineage: &HashSet<u64>,
735    ) -> Vec<&'a Proc> {
736        let eligible =
737            |process: &Proc| process.pid() > 1 && process.pid() != root && process.pid() != host;
738        let root_unique = table
739            .iter()
740            .find(|process| process.pid() == root)
741            .and_then(Proc::unique);
742        let mut found: HashSet<u32> = HashSet::new();
743        let mut found_unique: HashSet<u64> = HashSet::new();
744        for process in table.iter().filter(|process| eligible(process)) {
745            if process.pgid == root
746                || known.contains(&process.identity)
747                || process.marker.as_deref() == Some(marker)
748            {
749                found.insert(process.pid());
750                found_unique.extend(process.unique());
751            }
752        }
753        loop {
754            let before = found.len();
755            for process in table.iter().filter(|process| eligible(process)) {
756                let linked = process.ppid == root
757                    || found.contains(&process.ppid)
758                    || process.parent_unique.is_some_and(|parent| {
759                        root_unique == Some(parent)
760                            || lineage.contains(&parent)
761                            || found_unique.contains(&parent)
762                    });
763                if linked {
764                    found.insert(process.pid());
765                    found_unique.extend(process.unique());
766                }
767            }
768            if found.len() == before {
769                break;
770            }
771        }
772        table
773            .iter()
774            .filter(|process| found.contains(&process.pid()))
775            .collect()
776    }
777
778    /// Signals `member` unless the pid now belongs to another process. A
779    /// process that is gone is no error; one that cannot be signalled is.
780    pub(super) fn signal(member: &Member, signal: libc::c_int) -> Result<(), ProcessTableError> {
781        if !platform::is_same(member.identity).map_err(ProcessTableError::Table)? {
782            return Ok(());
783        }
784        // SAFETY: `kill` takes plain integers and touches no memory.
785        if unsafe { libc::kill(member.identity.pid.cast_signed(), signal) } == 0 {
786            return Ok(());
787        }
788        let source = io::Error::last_os_error();
789        if source.raw_os_error() == Some(libc::ESRCH) {
790            return Ok(());
791        }
792        Err(ProcessTableError::Signal {
793            process: member.process(),
794            source,
795        })
796    }
797
798    /// Signals the first listed process this user may not signal, as a member
799    /// would be; `None` when there is none.
800    #[cfg(test)]
801    pub(super) fn signal_foreign_for_test(
802        number: libc::c_int,
803    ) -> Option<Result<(), ProcessTableError>> {
804        let table =
805            platform::snapshot(platform::identity_mode().0, true).expect("the table is readable");
806        table
807            .procs
808            .iter()
809            .filter(|process| !process.zombie)
810            .find(|process| {
811                // SAFETY: signal 0 probes whether a signal could be sent.
812                let refused = unsafe { libc::kill(process.pid().cast_signed(), 0) } != 0;
813                refused && io::Error::last_os_error().raw_os_error() == Some(libc::EPERM)
814            })
815            .map(|row| {
816                signal(
817                    &Member {
818                        identity: row.identity,
819                        name: row.name.clone(),
820                        zombie: row.zombie,
821                    },
822                    number,
823                )
824            })
825    }
826
827    /// Signals the job's process group; a group that is gone is no error.
828    fn signal_group(root: &JobProcess, signal: libc::c_int) -> Result<(), ProcessTableError> {
829        // SAFETY: `kill` takes plain integers and touches no memory.
830        if unsafe { libc::kill(-root.pid.cast_signed(), signal) } == 0 {
831            return Ok(());
832        }
833        let source = io::Error::last_os_error();
834        if source.raw_os_error() == Some(libc::ESRCH) {
835            return Ok(());
836        }
837        Err(ProcessTableError::Signal {
838            process: root.clone(),
839            source,
840        })
841    }
842
843    /// How a task delivers signals: the operating system's, or a test's
844    /// stand-in for a process that does not die.
845    pub(super) trait Signals {
846        /// Signals one member, as [`signal`] does.
847        fn member(&self, member: &Member, signal: libc::c_int) -> Result<(), ProcessTableError>;
848
849        /// Signals the job's process group.
850        fn group(&self, root: &JobProcess, signal: libc::c_int) -> Result<(), ProcessTableError>;
851    }
852
853    /// The operating system's `kill(2)`.
854    pub(super) struct Os;
855
856    impl Signals for Os {
857        fn member(&self, member: &Member, number: libc::c_int) -> Result<(), ProcessTableError> {
858            signal(member, number)
859        }
860
861        fn group(&self, root: &JobProcess, number: libc::c_int) -> Result<(), ProcessTableError> {
862            signal_group(root, number)
863        }
864    }
865
866    /// A message to the job's task.
867    #[derive(Debug)]
868    pub(super) enum Command {
869        /// Answer once no descendant is alive.
870        Wait(Sender<Result<(), ProcessTableError>>),
871        /// Kill the descendants, and the process group when `group` is set;
872        /// answers with what was killed.
873        Kill {
874            group: bool,
875            reply: Sender<Result<Vec<JobProcess>, ProcessTableError>>,
876        },
877        /// End the task.
878        Finish(Sender<()>),
879    }
880
881    /// The task's end of its command channel. Dropping it closes the channel
882    /// and drops every command still queued, whose asker then learns that the
883    /// task ended: async-channel keeps a queued message, and the reply sender
884    /// inside it, alive for as long as any sender does, so a command left in
885    /// the queue would otherwise wait for its answer forever.
886    struct Inbox(Receiver<Command>);
887
888    impl Drop for Inbox {
889        fn drop(&mut self) {
890            self.0.close();
891            while self.0.try_recv().is_ok() {}
892        }
893    }
894
895    enum Event {
896        Command(Command),
897        Changed(io::Result<()>),
898        Closed,
899    }
900
901    /// The task that owns one job's member set.
902    pub(super) struct Task<S> {
903        root: u32,
904        root_name: String,
905        /// Whether the root has exited and waits to be reaped. A process
906        /// group that holds only that zombie cannot be signalled on macOS.
907        root_zombie: bool,
908        marker: String,
909        scanner: ProcessScanner,
910        /// How processes are identified, decided once when the job starts.
911        mode: platform::IdentityMode,
912        /// Watches the root from the spawn on, and every member found.
913        watch: Option<platform::Watch>,
914        /// Why there is no watch, when the kernel refused it.
915        watch_error: Option<String>,
916        /// Members the last scan found; a member that exited is not in it.
917        known: HashSet<Identity>,
918        /// The unique ids of the root and of every member seen so far, the
919        /// exited ones included: a child of any of them belongs to the job.
920        lineage: HashSet<u64>,
921        waiters: Vec<Sender<Result<(), ProcessTableError>>>,
922        signals: S,
923    }
924
925    impl Task<Os> {
926        /// The task of the job whose root is `root`. It reads the root's
927        /// unique id and starts watching the root before it returns.
928        pub(super) fn new(root: u32, marker: String, scanner: ProcessScanner) -> Self {
929            Self::with_signals(Os, root, marker, scanner)
930        }
931    }
932
933    impl<S: Signals + Send + 'static> Task<S> {
934        pub(super) fn with_signals(
935            signals: S,
936            root: u32,
937            marker: String,
938            scanner: ProcessScanner,
939        ) -> Self {
940            let (mode, degraded) = platform::identity_mode();
941            if let Some(reason) = degraded {
942                tracing::warn!(
943                    root,
944                    %reason,
945                    "process identity falls back to pid plus start time; \
946                     descendants are found by group, ancestry and the environment marker only"
947                );
948            }
949            let (watch, watch_error) = match platform::Watch::new(root) {
950                Ok(watch) => (Some(watch), None),
951                Err(error) => {
952                    tracing::warn!(root, %error, "cannot watch the job's processes");
953                    (None, Some(error.to_string()))
954                }
955            };
956            Self {
957                root,
958                root_name: "the job's shell".to_string(),
959                root_zombie: false,
960                marker,
961                scanner,
962                mode,
963                watch,
964                watch_error,
965                known: HashSet::new(),
966                lineage: platform::unique_of(mode, root).into_iter().collect(),
967                waiters: Vec::new(),
968                signals,
969            }
970        }
971
972        /// The task's loop. `inbox` is wrapped before the returned future is
973        /// first polled, so even a task dropped unpolled leaves no command
974        /// waiting for an answer.
975        pub(super) fn run(
976            self,
977            inbox: Receiver<Command>,
978        ) -> impl std::future::Future<Output = ()> + Send + 'static {
979            self.serve(Inbox(inbox))
980        }
981
982        async fn serve(mut self, inbox: Inbox) {
983            let inbox = &inbox.0;
984            let mut finished = None;
985            loop {
986                let next = async { inbox.recv().await.map_or(Event::Closed, Event::Command) };
987                let event = if self.watching() {
988                    futures_lite::future::or(next, async { Event::Changed(self.changed().await) })
989                        .await
990                } else {
991                    next.await
992                };
993                let mut scan = false;
994                match event {
995                    Event::Closed => break,
996                    Event::Command(Command::Wait(reply)) => match &self.watch_error {
997                        Some(reason) => {
998                            let error = ProcessTableError::Table(io::Error::other(reason.clone()));
999                            let _ = reply.send(Err(error)).await;
1000                        }
1001                        None => self.waiters.push(reply),
1002                    },
1003                    Event::Command(Command::Kill { group, reply }) => {
1004                        let result = self.kill(group).await;
1005                        let _ = reply.send(result).await;
1006                    }
1007                    Event::Command(Command::Finish(ack)) => {
1008                        // Closed before the finish is acknowledged, so a
1009                        // command sent once `finish` returned is refused and
1010                        // reads as the job having ended.
1011                        inbox.close();
1012                        finished = Some(ack);
1013                        break;
1014                    }
1015                    Event::Changed(Err(error)) => {
1016                        tracing::warn!(root = self.root, %error, "the job's watch failed");
1017                        self.watch = None;
1018                        self.watch_error = Some(error.to_string());
1019                        self.fail_waiters(ProcessTableError::Table(error)).await;
1020                    }
1021                    Event::Changed(Ok(())) => scan = true,
1022                }
1023                let started = std::time::Instant::now();
1024                self.settle(scan).await;
1025                if scan && let Some(watch) = self.watch.as_mut() {
1026                    // A fork storm cannot make the job scan without a break:
1027                    // the watch rests as long as this scan took, which caps
1028                    // the share of time spent scanning at one half. The scan
1029                    // that answers an event never waits.
1030                    watch.rest(started.elapsed());
1031                }
1032            }
1033            if let Some(ack) = finished {
1034                let _ = ack.send(()).await;
1035            }
1036        }
1037
1038        /// Whether the next event may come from the watch: always where the
1039        /// platform signals forks and exits, so children are found while
1040        /// their lineage can be read; otherwise only while a wait runs.
1041        const fn watching(&self) -> bool {
1042            self.watch.is_some() && (platform::WATCH_FROM_SPAWN || !self.waiters.is_empty())
1043        }
1044
1045        async fn changed(&mut self) -> io::Result<()> {
1046            match self.watch.as_mut() {
1047                Some(watch) => watch.changed().await,
1048                None => std::future::pending().await,
1049            }
1050        }
1051
1052        /// Reads the table, at most `max_age` old, and attributes it to the
1053        /// job; `markers` says whether the environment markers are read too.
1054        /// What it finds becomes the job's member set, and its unique ids join
1055        /// the lineage.
1056        async fn scan(
1057            &mut self,
1058            max_age: Duration,
1059            markers: bool,
1060        ) -> Result<Vec<Member>, ProcessTableError> {
1061            let scanner = self.scanner.clone();
1062            let (root, mode) = (self.root, self.mode);
1063            // The seen sets move into the read and back, so a long job's
1064            // history is never copied per scan.
1065            let (marker, known, lineage) = (
1066                self.marker.clone(),
1067                std::mem::take(&mut self.known),
1068                std::mem::take(&mut self.lineage),
1069            );
1070            let (known, lineage, outcome) = blocking::unblock(move || {
1071                let outcome = scanner
1072                    .table(max_age, mode, markers)
1073                    .map_err(ProcessTableError::Table)
1074                    .map(|table| {
1075                        let host = std::process::id();
1076                        let members = members(&table.procs, root, host, &marker, &known, &lineage)
1077                            .into_iter()
1078                            .map(|process| Member {
1079                                identity: process.identity,
1080                                name: process.name.clone(),
1081                                zombie: process.zombie,
1082                            })
1083                            .collect::<Vec<_>>();
1084                        let root = table
1085                            .procs
1086                            .iter()
1087                            .find(|process| process.pid() == root)
1088                            .map(|process| {
1089                                (process.name.clone(), process.zombie, process.unique())
1090                            });
1091                        (members, root)
1092                    });
1093                (known, lineage, outcome)
1094            })
1095            .await;
1096            self.known = known;
1097            self.lineage = lineage;
1098            let (members, root) = outcome?;
1099            // An unreaped root that the table does not list is a zombie.
1100            self.root_zombie = root.as_ref().is_none_or(|(_, zombie, _)| *zombie);
1101            if let Some((name, _, unique)) = root {
1102                self.root_name = name;
1103                self.lineage.extend(unique);
1104            }
1105            self.lineage.extend(
1106                members
1107                    .iter()
1108                    .filter_map(|member| member.identity.birth.unique()),
1109            );
1110            self.known = members.iter().map(|member| member.identity).collect();
1111            Ok(members)
1112        }
1113
1114        /// Whether no descendant is alive, watching the live ones so the next
1115        /// change is signalled.
1116        ///
1117        /// `markers` says whether the scan reads the environment markers.
1118        /// Without them a scan is several times faster, which is what an
1119        /// event needs: the child that forked has little time before its
1120        /// parent exits. The markers are read again by the next scan that
1121        /// needs them.
1122        async fn poll_empty(&mut self, markers: bool) -> Result<bool, ProcessTableError> {
1123            for _ in 0..2 {
1124                let members = self.scan(platform::SCAN_SHARING, markers).await?;
1125                let live: Vec<u32> = members
1126                    .iter()
1127                    .filter(|member| !member.zombie)
1128                    .map(|member| member.identity.pid)
1129                    .collect();
1130                if live.is_empty() {
1131                    return Ok(true);
1132                }
1133                // A process registered now may have forked before it was
1134                // watched, so a new registration is followed by another scan.
1135                let root = self.root;
1136                let watched = self
1137                    .watch
1138                    .as_mut()
1139                    .map_or(Ok(false), |watch| watch.follow(root, &live));
1140                if !watched.map_err(ProcessTableError::Table)? {
1141                    break;
1142                }
1143            }
1144            Ok(false)
1145        }
1146
1147        /// Scans after a watch event, or while a wait runs, and ends the
1148        /// waits when nothing is alive.
1149        async fn settle(&mut self, event: bool) {
1150            if !event && self.waiters.is_empty() {
1151                return;
1152            }
1153            let markers = !self.waiters.is_empty();
1154            match self.poll_empty(markers).await {
1155                Ok(false) => {}
1156                Ok(true) => {
1157                    for waiter in self.waiters.drain(..) {
1158                        let _ = waiter.send(Ok(())).await;
1159                    }
1160                }
1161                Err(error) if self.waiters.is_empty() => {
1162                    tracing::warn!(root = self.root, %error, "cannot scan the job's processes");
1163                }
1164                Err(error) => self.fail_waiters(error).await,
1165            }
1166        }
1167
1168        async fn fail_waiters(&mut self, error: ProcessTableError) {
1169            let message = error.to_string();
1170            let mut error = Some(error);
1171            for waiter in self.waiters.drain(..) {
1172                let reply = error
1173                    .take()
1174                    .unwrap_or_else(|| ProcessTableError::Table(io::Error::other(message.clone())));
1175                let _ = waiter.send(Err(reply)).await;
1176            }
1177        }
1178
1179        /// Freezes the job's processes until a pass finds no new one, then
1180        /// kills them, and fails if a tracked member is still alive.
1181        async fn kill(&mut self, group: bool) -> Result<Vec<JobProcess>, ProcessTableError> {
1182            let mut frozen: Vec<Member> = Vec::new();
1183            let result = self.freeze_and_kill(group, &mut frozen).await;
1184            if result.is_err() {
1185                // Do not leave stopped processes behind a failed kill.
1186                for member in &frozen {
1187                    let _ = self.signals.member(member, libc::SIGCONT);
1188                }
1189                if group && !self.root_zombie {
1190                    let _ = self.signals.group(&self.root_process(), libc::SIGCONT);
1191                }
1192            }
1193            result
1194        }
1195
1196        fn root_process(&self) -> JobProcess {
1197            JobProcess {
1198                pid: self.root,
1199                name: self.root_name.clone(),
1200            }
1201        }
1202
1203        async fn freeze_and_kill(
1204            &mut self,
1205            group: bool,
1206            frozen: &mut Vec<Member>,
1207        ) -> Result<Vec<JobProcess>, ProcessTableError> {
1208            // Names are read from the last pass of the freeze, after the
1209            // processes stopped, so a just-forked child has usually exec'd.
1210            let mut killed: Vec<Member> = Vec::new();
1211            if group {
1212                // Learns whether the root is alive before the group is signalled.
1213                self.scan(Duration::ZERO, true).await?;
1214            }
1215            for _ in 0..FREEZE_ROUNDS {
1216                if group && !self.root_zombie {
1217                    self.signals.group(&self.root_process(), libc::SIGSTOP)?;
1218                }
1219                let members = self.scan(Duration::ZERO, true).await?;
1220                let live: Vec<Member> = members
1221                    .into_iter()
1222                    .filter(|member| !member.zombie)
1223                    .collect();
1224                let fresh: Vec<Member> = live
1225                    .iter()
1226                    .filter(|member| frozen.iter().all(|seen| seen.identity != member.identity))
1227                    .cloned()
1228                    .collect();
1229                killed = live;
1230                if fresh.is_empty() {
1231                    break;
1232                }
1233                for member in fresh {
1234                    self.signals.member(&member, libc::SIGSTOP)?;
1235                    frozen.push(member);
1236                }
1237            }
1238            if group && !self.root_zombie {
1239                self.signals.group(&self.root_process(), libc::SIGKILL)?;
1240            }
1241            for _ in 0..KILL_ROUNDS {
1242                let live: Vec<Member> = self
1243                    .scan(Duration::ZERO, true)
1244                    .await?
1245                    .into_iter()
1246                    .filter(|member| !member.zombie)
1247                    .collect();
1248                if live.is_empty() {
1249                    return Ok(killed.iter().map(Member::process).collect());
1250                }
1251                for member in live {
1252                    self.signals.member(&member, libc::SIGKILL)?;
1253                    if killed.iter().all(|seen| seen.identity != member.identity) {
1254                        killed.push(member);
1255                    }
1256                }
1257                async_io::Timer::after(KILL_ROUND_PAUSE).await;
1258            }
1259            let survivors: Vec<JobProcess> = self
1260                .scan(Duration::ZERO, true)
1261                .await?
1262                .iter()
1263                .filter(|member| !member.zombie)
1264                .map(Member::process)
1265                .collect();
1266            if survivors.is_empty() {
1267                return Ok(killed.iter().map(Member::process).collect());
1268            }
1269            Err(ProcessTableError::Survived(survivors))
1270        }
1271    }
1272}
1273
1274/// Parts of the process-table reads are reached only through the watched
1275/// tree, which the supervisor replaces on Linux.
1276#[cfg(target_os = "linux")]
1277#[cfg_attr(target_os = "linux", allow(dead_code))]
1278mod platform {
1279    use std::{
1280        fs, io,
1281        os::{
1282            fd::{FromRawFd, OwnedFd},
1283            unix::fs::MetadataExt,
1284        },
1285        time::Duration,
1286    };
1287
1288    use async_io::Async;
1289
1290    use super::unix::{Birth, Identity, Proc, Table};
1291
1292    /// How long a table read may be reused by another job's check.
1293    pub(super) const SCAN_SHARING: Duration = super::DESCENDANT_POLL;
1294
1295    /// Linux has no exit events for arbitrary processes, so a job is checked
1296    /// only while a wait runs.
1297    pub(super) const WATCH_FROM_SPAWN: bool = false;
1298
1299    /// How processes are identified: on Linux always by pid and start time.
1300    #[derive(Debug, Clone, Copy)]
1301    pub(super) struct IdentityMode;
1302
1303    /// Linux identities never fall back.
1304    pub(super) const fn identity_mode() -> (IdentityMode, Option<String>) {
1305        (IdentityMode, None)
1306    }
1307
1308    fn gone(error: &io::Error) -> bool {
1309        error.kind() == io::ErrorKind::NotFound || error.raw_os_error() == Some(libc::ESRCH)
1310    }
1311
1312    /// Fields of a `/proc/<pid>/stat` dump: the command name sits in
1313    /// parentheses and may itself contain spaces and parentheses, so the other
1314    /// fields are read after the last `") "`.
1315    #[allow(clippy::similar_names)] // `ppid` and `pgid` are the kernel's names
1316    pub(super) fn parse_stat(pid: u32, line: &str) -> Option<Stat> {
1317        let (head, rest) = line.rsplit_once(") ")?;
1318        let name = head.split_once('(')?.1.to_string();
1319        let mut fields = rest.split_whitespace();
1320        let state = fields.next()?;
1321        // `X` (dead) is a task already reaped and on its way out of /proc: it
1322        // reports ppid 0 and process group and session -1, and it is no
1323        // longer a member of any tree, unlike a zombie.
1324        if state == "X" {
1325            return Some(Stat::Reaped);
1326        }
1327        let ppid = fields.next()?.parse().ok()?;
1328        let pgid = fields.next()?.parse().ok()?;
1329        // Field 22, `starttime`, is the 20th after the state (field 3).
1330        let starttime = fields.nth(16)?.parse().ok()?;
1331        Some(Stat::Listed(Proc {
1332            identity: Identity {
1333                pid,
1334                birth: Birth::Ticks(starttime),
1335            },
1336            ppid,
1337            parent_unique: None,
1338            pgid,
1339            zombie: state == "Z",
1340            name,
1341            marker: None,
1342        }))
1343    }
1344
1345    /// A parsed `/proc/<pid>/stat` line.
1346    pub(super) enum Stat {
1347        /// A process the table lists, a zombie included.
1348        Listed(Proc),
1349        /// A task already reaped, which the table treats as gone.
1350        Reaped,
1351    }
1352
1353    /// The value of the job marker in the environment of `pid`. A process
1354    /// whose environment cannot be read (it exited, or disabled dumping) is
1355    /// not attributable this way.
1356    fn marker_of(pid: u32) -> Option<String> {
1357        let prefix = format!("{}=", super::JOB_MARKER_VAR);
1358        let environment = fs::read(format!("/proc/{pid}/environ")).ok()?;
1359        environment
1360            .split(|byte| *byte == 0)
1361            .find_map(|entry| entry.strip_prefix(prefix.as_bytes()))
1362            .map(|value| String::from_utf8_lossy(value).into_owned())
1363    }
1364
1365    /// Linux reads the markers whatever `_markers` says: only macOS scans
1366    /// without them.
1367    pub(super) fn snapshot(_mode: IdentityMode, _markers: bool) -> io::Result<Table> {
1368        // SAFETY: `geteuid` has no preconditions.
1369        let me = unsafe { libc::geteuid() };
1370        let mut procs = Vec::new();
1371        for entry in fs::read_dir("/proc")? {
1372            let entry = entry?;
1373            let Some(pid) = entry
1374                .file_name()
1375                .to_str()
1376                .and_then(|name| name.parse().ok())
1377            else {
1378                continue;
1379            };
1380            let uid = match entry.metadata() {
1381                Ok(metadata) => metadata.uid(),
1382                Err(error) if gone(&error) => continue,
1383                Err(error) => return Err(error),
1384            };
1385            let line = match fs::read_to_string(entry.path().join("stat")) {
1386                Ok(line) => line,
1387                Err(error) if gone(&error) => continue,
1388                Err(error) => return Err(error),
1389            };
1390            let mut process = match parse_stat(pid, &line) {
1391                Some(Stat::Listed(process)) => process,
1392                Some(Stat::Reaped) => continue,
1393                None => {
1394                    return Err(io::Error::other(format!(
1395                        "malformed /proc/{pid}/stat: {line:?}"
1396                    )));
1397                }
1398            };
1399            if uid == me && !process.zombie {
1400                process.marker = marker_of(pid);
1401            }
1402            procs.push(process);
1403        }
1404        Ok(Table { procs })
1405    }
1406
1407    /// Linux identifies by start time and has no lineage ids.
1408    pub(super) const fn unique_of(_mode: IdentityMode, _pid: u32) -> Option<u64> {
1409        None
1410    }
1411
1412    /// Whether `identity` is the process that has its pid now.
1413    pub(super) fn is_same(identity: Identity) -> io::Result<bool> {
1414        match fs::read_to_string(format!("/proc/{}/stat", identity.pid)) {
1415            Ok(line) => Ok(matches!(
1416                parse_stat(identity.pid, &line),
1417                Some(Stat::Listed(process)) if process.identity == identity
1418            )),
1419            Err(error) if gone(&error) => Ok(false),
1420            Err(error) => Err(error),
1421        }
1422    }
1423
1424    /// Linux has no exit events for arbitrary processes, so a job waiting on
1425    /// its tree checks it once per [`SCAN_SHARING`].
1426    pub(super) struct Watch;
1427
1428    // Linux has nothing to register or fail on, but the callers see the same
1429    // fallible shape as on macOS.
1430    #[allow(
1431        clippy::unnecessary_wraps,
1432        clippy::unused_self,
1433        clippy::needless_pass_by_ref_mut
1434    )]
1435    impl Watch {
1436        pub(super) const fn new(_root: u32) -> io::Result<Self> {
1437            Ok(Self)
1438        }
1439
1440        /// Nothing to register: reports no new watch.
1441        pub(super) const fn follow(&mut self, _root: u32, _live: &[u32]) -> io::Result<bool> {
1442            Ok(false)
1443        }
1444
1445        /// Polling already spaces the scans.
1446        pub(super) const fn rest(&mut self, _duration: Duration) {}
1447
1448        pub(super) async fn changed(&mut self) -> io::Result<()> {
1449            async_io::Timer::after(super::DESCENDANT_POLL).await;
1450            Ok(())
1451        }
1452    }
1453
1454    /// A pidfd of a child, readable once the child has exited.
1455    pub(super) struct ExitWatch {
1456        pid: u32,
1457        pidfd: Async<OwnedFd>,
1458    }
1459
1460    impl ExitWatch {
1461        pub(super) fn new(pid: u32) -> io::Result<Self> {
1462            // SAFETY: `pidfd_open` takes plain integers.
1463            let fd = unsafe { libc::syscall(libc::SYS_pidfd_open, pid.cast_signed(), 0) };
1464            if fd < 0 {
1465                return Err(io::Error::last_os_error());
1466            }
1467            let fd = libc::c_int::try_from(fd).expect("a descriptor fits c_int");
1468            // SAFETY: `fd` is a new descriptor nothing else owns.
1469            let pidfd = unsafe { OwnedFd::from_raw_fd(fd) };
1470            Ok(Self {
1471                pid,
1472                pidfd: Async::new(pidfd)?,
1473            })
1474        }
1475
1476        /// Returns once the child has exited and can be waited for. The
1477        /// kernel makes a pidfd readable once the process is a zombie or
1478        /// reaped, so the check that follows fails only for a child that
1479        /// something else reaped.
1480        pub(super) async fn exited(self) -> io::Result<()> {
1481            self.pidfd.readable().await?;
1482            if super::exited_unreaped(self.pid)? {
1483                Ok(())
1484            } else {
1485                Err(io::Error::other(format!(
1486                    "the pidfd of {} is readable but waitid reports no exit",
1487                    self.pid
1488                )))
1489            }
1490        }
1491    }
1492
1493    #[cfg(test)]
1494    mod tests {
1495        use super::{Birth, Stat, parse_stat};
1496
1497        /// The name may hold spaces and parentheses; the identity is field 22,
1498        /// the start time.
1499        #[test]
1500        fn stat_lines_yield_group_state_and_start_time() {
1501            let line = "4242 (my (odd) cmd) Z 1 4243 4242 0 -1 4194560 1000 0 0 0 5 6 0 0 20 0 3 0 \
1502                        987654 12345678 100 18446744073709551615";
1503            let Some(Stat::Listed(process)) = parse_stat(4242, line) else {
1504                panic!("a valid stat line");
1505            };
1506            assert_eq!(process.name, "my (odd) cmd");
1507            assert_eq!((process.ppid, process.pgid), (1, 4243));
1508            assert!(process.zombie);
1509            assert_eq!(process.identity.birth, Birth::Ticks(987_654));
1510            assert!(parse_stat(1, "1 (init) S 0").is_none());
1511        }
1512
1513        /// A dead task's line, as CI read it while the kill test's process
1514        /// was being reaped: no group, and not a member of any tree.
1515        #[test]
1516        fn a_reaped_task_is_not_listed() {
1517            let line = "10865 (aither_sandbox-) X 0 -1 -1 0 -1 4227084 1198 0 0 0 0 0 0 0 20 0 0 0 \
1518                        111813 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 17 3 0 0 0 0 0 0 0 0 0 0 0 0 0\n";
1519            assert!(matches!(parse_stat(10865, line), Some(Stat::Reaped)));
1520        }
1521    }
1522}
1523
1524#[cfg(target_os = "macos")]
1525mod platform {
1526    use std::{
1527        collections::HashSet,
1528        ffi::c_int,
1529        io,
1530        mem::{size_of, zeroed},
1531        os::fd::{AsRawFd, FromRawFd, OwnedFd},
1532        time::{Duration, Instant},
1533    };
1534
1535    use async_io::Async;
1536
1537    use super::unix::{Birth, Identity, Proc, Table};
1538
1539    /// A table read is never reused: an exit is signalled by the kernel, and
1540    /// a scan answers it.
1541    pub(super) const SCAN_SHARING: Duration = Duration::ZERO;
1542
1543    /// The kernel signals a job's forks, execs and exits, so its task watches
1544    /// it from the spawn on.
1545    pub(super) const WATCH_FROM_SPAWN: bool = true;
1546
1547    /// `proc_pidinfo` flavor `PROC_PIDUNIQIDENTIFIERINFO`.
1548    ///
1549    /// Apple SPI: this flavor and [`ProcUniqIdentifierInfo`] sit under
1550    /// `#ifdef PRIVATE` in `sys/proc_info.h`, so the public SDK and the `libc`
1551    /// crate do not declare them, and they are declared here from xnu's
1552    /// header. Verified on macOS 27.0.1 (build 26A434, Apple silicon): the
1553    /// call returns 56 bytes and `p_uniqueid` is never reused. `p_puniqueid`
1554    /// survives the parent's exit and the reparenting to `launchd`, but the
1555    /// kernel resets it to `launchd`'s (1) at the first `exec` the process
1556    /// makes after it was reparented; a process that execs before its parent
1557    /// exits keeps it. Apple may change all of it without notice: when the
1558    /// call fails or returns another size at the start of a job, that job's
1559    /// identity is the pid plus the public start time
1560    /// (`pbi_start_tvsec`/`pbi_start_tvusec` from `PROC_PIDTBSDINFO`) for its
1561    /// whole life, lineage is dropped, attribution keeps the environment
1562    /// marker, and the job logs one warning naming the failure. A failure
1563    /// later in a job's life fails the scan; it never changes the identities.
1564    const PROC_PIDUNIQIDENTIFIERINFO: c_int = 17;
1565
1566    /// `struct proc_uniqidentifierinfo` of `sys/proc_info.h` (SPI, see
1567    /// [`PROC_PIDUNIQIDENTIFIERINFO`]).
1568    #[repr(C)]
1569    #[allow(clippy::struct_field_names)] // the C names, kept to match the header
1570    struct ProcUniqIdentifierInfo {
1571        /// UUID of the main executable.
1572        p_uuid: [u8; 16],
1573        /// The 64-bit unique id of the process.
1574        p_uniqueid: u64,
1575        /// The unique id of the process's parent when it was forked.
1576        p_puniqueid: u64,
1577        p_idversion: i32,
1578        p_orig_ppidversion: i32,
1579        p_reserve2: u64,
1580        p_reserve3: u64,
1581    }
1582
1583    /// A process's unique id and its parent's.
1584    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
1585    pub(super) struct Uniq {
1586        pub(super) id: u64,
1587        pub(super) parent: u64,
1588    }
1589
1590    /// Why unique ids could not be read for a process.
1591    #[derive(Debug)]
1592    pub(super) enum UniqError {
1593        /// The process exited.
1594        Gone,
1595        /// The SPI failed or answered unexpectedly.
1596        Unavailable(String),
1597    }
1598
1599    /// Where unique ids come from: the SPI, or a test's stand-in.
1600    pub(super) trait IdentitySource {
1601        fn unique(&self, pid: i32) -> Result<Uniq, UniqError>;
1602    }
1603
1604    /// The `PROC_PIDUNIQIDENTIFIERINFO` SPI.
1605    pub(super) struct Spi;
1606
1607    impl IdentitySource for Spi {
1608        fn unique(&self, pid: i32) -> Result<Uniq, UniqError> {
1609            // SAFETY: the struct is plain data for which all-zero bytes are valid.
1610            let mut info: ProcUniqIdentifierInfo = unsafe { zeroed() };
1611            let size = c_int::try_from(size_of::<ProcUniqIdentifierInfo>()).expect("fits c_int");
1612            // SAFETY: `info` is `size` bytes of live memory.
1613            let written = unsafe {
1614                libc::proc_pidinfo(
1615                    pid,
1616                    PROC_PIDUNIQIDENTIFIERINFO,
1617                    0,
1618                    (&raw mut info).cast(),
1619                    size,
1620                )
1621            };
1622            if written == size {
1623                return Ok(Uniq {
1624                    id: info.p_uniqueid,
1625                    parent: info.p_puniqueid,
1626                });
1627            }
1628            let error = io::Error::last_os_error();
1629            if written <= 0 && error.raw_os_error() == Some(libc::ESRCH) {
1630                return Err(UniqError::Gone);
1631            }
1632            Err(UniqError::Unavailable(if written <= 0 {
1633                format!("proc_pidinfo(PROC_PIDUNIQIDENTIFIERINFO) for pid {pid} failed: {error}")
1634            } else {
1635                format!(
1636                    "proc_pidinfo(PROC_PIDUNIQIDENTIFIERINFO) for pid {pid} returned {written} \
1637                     bytes, expected {size}"
1638                )
1639            }))
1640        }
1641    }
1642
1643    /// The public part of a process's row.
1644    struct Bsd {
1645        pid: u32,
1646        ppid: u32,
1647        pgid: u32,
1648        uid: u32,
1649        zombie: bool,
1650        name: String,
1651        started_seconds: u64,
1652        started_micros: u64,
1653    }
1654
1655    fn list() -> io::Result<Vec<Bsd>> {
1656        // `proc_listallpids` reports a count of pids, and a null buffer asks
1657        // for the current count; processes start meanwhile, so the buffer
1658        // grows until the call does not fill it.
1659        // SAFETY: a null buffer of size 0 is the documented size query.
1660        let mut capacity =
1661            usize::try_from(unsafe { libc::proc_listallpids(std::ptr::null_mut(), 0) })
1662                .map_err(|_| io::Error::last_os_error())?
1663                + 64;
1664        let pids = loop {
1665            let mut pids = vec![0 as c_int; capacity];
1666            let bytes = c_int::try_from(capacity * size_of::<c_int>()).expect("fits c_int");
1667            // SAFETY: the buffer holds `bytes` bytes of live memory.
1668            let count = unsafe { libc::proc_listallpids(pids.as_mut_ptr().cast(), bytes) };
1669            let count = usize::try_from(count).map_err(|_| io::Error::last_os_error())?;
1670            if count < capacity {
1671                pids.truncate(count);
1672                break pids;
1673            }
1674            capacity *= 2;
1675        };
1676        let mut rows = Vec::with_capacity(pids.len());
1677        for pid in pids.into_iter().filter(|pid| *pid > 0) {
1678            if let Some(info) = bsd_info(pid) {
1679                rows.push(Bsd {
1680                    pid: info.pbi_pid,
1681                    ppid: info.pbi_ppid,
1682                    pgid: info.pbi_pgid,
1683                    uid: info.pbi_uid,
1684                    zombie: info.pbi_status == libc::SZOMB,
1685                    name: c_name(&info.pbi_name)
1686                        .filter(|name| !name.is_empty())
1687                        .unwrap_or_else(|| c_name(&info.pbi_comm).unwrap_or_default()),
1688                    started_seconds: info.pbi_start_tvsec,
1689                    started_micros: info.pbi_start_tvusec,
1690                });
1691            }
1692        }
1693        Ok(rows)
1694    }
1695
1696    /// `PROC_PIDTBSDINFO` of `pid`; `None` when the process exited.
1697    fn bsd_info(pid: c_int) -> Option<libc::proc_bsdinfo> {
1698        // SAFETY: `proc_bsdinfo` is plain data for which all-zero bytes are valid.
1699        let mut info: libc::proc_bsdinfo = unsafe { zeroed() };
1700        let size = c_int::try_from(size_of::<libc::proc_bsdinfo>()).expect("fits c_int");
1701        // SAFETY: `info` is `size` bytes of live memory.
1702        let written = unsafe {
1703            libc::proc_pidinfo(pid, libc::PROC_PIDTBSDINFO, 0, (&raw mut info).cast(), size)
1704        };
1705        (written == size).then_some(info)
1706    }
1707
1708    fn c_name(raw: &[libc::c_char]) -> Option<String> {
1709        let bytes: Vec<u8> = raw
1710            .iter()
1711            .take_while(|byte| **byte != 0)
1712            .map(|byte| byte.cast_unsigned())
1713            .collect();
1714        String::from_utf8(bytes).ok()
1715    }
1716
1717    /// The raw `KERN_PROCARGS2` block of `pid`: argument count, executable
1718    /// path, arguments, then the environment, all NUL-separated. `None` when
1719    /// the process exited or refuses the read.
1720    fn process_arguments(pid: u32) -> Option<Vec<u8>> {
1721        let mut mib = [libc::CTL_KERN, libc::KERN_PROCARGS2, pid.cast_signed()];
1722        let mut size = 0usize;
1723        // SAFETY: a null `oldp` asks for the needed size; `mib` has three entries.
1724        let sized = unsafe {
1725            libc::sysctl(
1726                mib.as_mut_ptr(),
1727                3,
1728                std::ptr::null_mut(),
1729                &raw mut size,
1730                std::ptr::null_mut(),
1731                0,
1732            )
1733        };
1734        if sized != 0 {
1735            return None;
1736        }
1737        let mut buffer = vec![0u8; size];
1738        // SAFETY: `buffer` holds `size` writable bytes.
1739        let read = unsafe {
1740            libc::sysctl(
1741                mib.as_mut_ptr(),
1742                3,
1743                buffer.as_mut_ptr().cast(),
1744                &raw mut size,
1745                std::ptr::null_mut(),
1746                0,
1747            )
1748        };
1749        if read != 0 {
1750            return None;
1751        }
1752        buffer.truncate(size);
1753        Some(buffer)
1754    }
1755
1756    /// The value of the job marker in the environment of `pid`. A process
1757    /// whose arguments cannot be read is not attributable this way.
1758    fn marker_of(pid: u32) -> Option<String> {
1759        let prefix = format!("{}=", super::JOB_MARKER_VAR);
1760        process_arguments(pid)?
1761            .split(|byte| *byte == 0)
1762            .find_map(|entry| entry.strip_prefix(prefix.as_bytes()))
1763            .map(|value| String::from_utf8_lossy(value).into_owned())
1764    }
1765
1766    /// How processes are identified, decided once per job.
1767    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
1768    pub(super) enum IdentityMode {
1769        /// By the SPI's unique id, with lineage.
1770        Unique,
1771        /// By pid plus the public start time, without lineage.
1772        Started,
1773    }
1774
1775    /// The identity mode this macOS supports, and why it is not the unique
1776    /// id when it is not.
1777    pub(super) fn identity_mode() -> (IdentityMode, Option<String>) {
1778        identity_mode_with(&Spi)
1779    }
1780
1781    /// [`identity_mode`] asking `source` about this process.
1782    pub(super) fn identity_mode_with(
1783        source: &impl IdentitySource,
1784    ) -> (IdentityMode, Option<String>) {
1785        match source.unique(std::process::id().cast_signed()) {
1786            Ok(_) => (IdentityMode::Unique, None),
1787            Err(UniqError::Gone) => (
1788                IdentityMode::Started,
1789                Some("the SPI does not know this process".to_string()),
1790            ),
1791            Err(UniqError::Unavailable(reason)) => (IdentityMode::Started, Some(reason)),
1792        }
1793    }
1794
1795    pub(super) fn snapshot(mode: IdentityMode, markers: bool) -> io::Result<Table> {
1796        snapshot_with(&Spi, mode, markers)
1797    }
1798
1799    /// The table with identities from `source` in `mode`. A process that
1800    /// exited during the read is dropped; any other failure of the source in
1801    /// [`IdentityMode::Unique`] fails the read, so identities never change
1802    /// kind within a job. `markers` says whether to read the environment of
1803    /// each of this user's processes.
1804    pub(super) fn snapshot_with(
1805        source: &impl IdentitySource,
1806        mode: IdentityMode,
1807        markers: bool,
1808    ) -> io::Result<Table> {
1809        // SAFETY: `geteuid` has no preconditions.
1810        let me = unsafe { libc::geteuid() };
1811        let mut procs = Vec::new();
1812        for row in list()? {
1813            let (birth, parent_unique) = match mode {
1814                IdentityMode::Started => (
1815                    Birth::Started {
1816                        seconds: row.started_seconds,
1817                        micros: row.started_micros,
1818                    },
1819                    None,
1820                ),
1821                IdentityMode::Unique => match source.unique(row.pid.cast_signed()) {
1822                    Ok(unique) => (Birth::Unique(unique.id), Some(unique.parent)),
1823                    // The process exited between the listing and the query.
1824                    Err(UniqError::Gone) => continue,
1825                    Err(UniqError::Unavailable(reason)) => return Err(io::Error::other(reason)),
1826                },
1827            };
1828            let marker = (markers && row.uid == me && !row.zombie)
1829                .then(|| marker_of(row.pid))
1830                .flatten();
1831            procs.push(Proc {
1832                identity: Identity {
1833                    pid: row.pid,
1834                    birth,
1835                },
1836                ppid: row.ppid,
1837                parent_unique,
1838                pgid: row.pgid,
1839                zombie: row.zombie,
1840                name: row.name,
1841                marker,
1842            });
1843        }
1844        Ok(Table { procs })
1845    }
1846
1847    /// The unique id of `pid`; `None` in [`IdentityMode::Started`] or when it
1848    /// cannot be read (the process is a zombie or gone).
1849    pub(super) fn unique_of(mode: IdentityMode, pid: u32) -> Option<u64> {
1850        match mode {
1851            IdentityMode::Unique => Spi.unique(pid.cast_signed()).ok().map(|unique| unique.id),
1852            IdentityMode::Started => None,
1853        }
1854    }
1855
1856    /// Whether `identity` is the process that has its pid now.
1857    pub(super) fn is_same(identity: Identity) -> io::Result<bool> {
1858        let pid = identity.pid.cast_signed();
1859        match identity.birth {
1860            Birth::Unique(id) => match Spi.unique(pid) {
1861                Ok(unique) => Ok(unique.id == id),
1862                Err(UniqError::Gone) => Ok(false),
1863                Err(UniqError::Unavailable(reason)) => Err(io::Error::other(reason)),
1864            },
1865            Birth::Started { seconds, micros } => Ok(bsd_info(pid).is_some_and(|info| {
1866                info.pbi_start_tvsec == seconds && info.pbi_start_tvusec == micros
1867            })),
1868            Birth::Ticks(_) => unreachable!("macOS identities are never start ticks"),
1869        }
1870    }
1871
1872    /// A kqueue descriptor. It rejects `FIONBIO`, so it is registered with
1873    /// the reactor as it is, and every read of it is a `kevent` with a zero
1874    /// timeout.
1875    fn new_queue() -> io::Result<Async<OwnedFd>> {
1876        // SAFETY: `kqueue` takes no arguments.
1877        let fd = unsafe { libc::kqueue() };
1878        if fd < 0 {
1879            return Err(io::Error::last_os_error());
1880        }
1881        // SAFETY: `fd` is a new descriptor nothing else owns.
1882        let queue = unsafe { OwnedFd::from_raw_fd(fd) };
1883        // SAFETY: plain integers.
1884        if unsafe { libc::fcntl(fd, libc::F_SETFD, libc::FD_CLOEXEC) } < 0 {
1885            return Err(io::Error::last_os_error());
1886        }
1887        Async::new_nonblocking(queue)
1888    }
1889
1890    /// Registers `pid` on `queue` for `fflags`; `false` when the process is
1891    /// gone or a zombie, which the kernel does not watch.
1892    fn register(queue: &Async<OwnedFd>, pid: u32, fflags: u32) -> io::Result<bool> {
1893        // SAFETY: `kevent` is plain data for which all-zero bytes are valid.
1894        let mut change: libc::kevent = unsafe { zeroed() };
1895        change.ident = pid as usize;
1896        change.filter = libc::EVFILT_PROC;
1897        change.flags = libc::EV_ADD | libc::EV_CLEAR;
1898        change.fflags = fflags;
1899        // SAFETY: one change is passed and no event is requested.
1900        let result = unsafe {
1901            libc::kevent(
1902                queue.as_raw_fd(),
1903                &raw const change,
1904                1,
1905                std::ptr::null_mut(),
1906                0,
1907                std::ptr::null(),
1908            )
1909        };
1910        if result >= 0 {
1911            return Ok(true);
1912        }
1913        let error = io::Error::last_os_error();
1914        if error.raw_os_error() == Some(libc::ESRCH) {
1915            Ok(false)
1916        } else {
1917            Err(error)
1918        }
1919    }
1920
1921    /// Drains pending events; whether there was any.
1922    fn drain(queue: &Async<OwnedFd>) -> io::Result<bool> {
1923        let mut any = false;
1924        loop {
1925            // SAFETY: `kevent` is plain data for which all-zero bytes are valid.
1926            let mut events: [libc::kevent; 16] = unsafe { zeroed() };
1927            let timeout = libc::timespec {
1928                tv_sec: 0,
1929                tv_nsec: 0,
1930            };
1931            // SAFETY: `events` has room for the 16 events asked for.
1932            let count = unsafe {
1933                libc::kevent(
1934                    queue.as_raw_fd(),
1935                    std::ptr::null(),
1936                    0,
1937                    events.as_mut_ptr(),
1938                    16,
1939                    &raw const timeout,
1940                )
1941            };
1942            if count < 0 {
1943                return Err(io::Error::last_os_error());
1944            }
1945            any |= count > 0;
1946            if count < 16 {
1947                return Ok(any);
1948            }
1949        }
1950    }
1951
1952    /// What a job's processes are followed for.
1953    const FOLLOWED: u32 = libc::NOTE_FORK | libc::NOTE_EXEC | libc::NOTE_EXIT;
1954
1955    /// A kqueue that signals when a watched process forks, execs or exits.
1956    pub(super) struct Watch {
1957        queue: Async<OwnedFd>,
1958        followed: HashSet<u32>,
1959        /// Until when the watch rests after a scan.
1960        rest_until: Option<Instant>,
1961    }
1962
1963    impl Watch {
1964        /// A watch that already follows `root`: created right after the root
1965        /// was spawned, it misses none of its forks.
1966        pub(super) fn new(root: u32) -> io::Result<Self> {
1967            let queue = new_queue()?;
1968            let mut followed = HashSet::new();
1969            if register(&queue, root, FOLLOWED)? {
1970                followed.insert(root);
1971            }
1972            Ok(Self {
1973                queue,
1974                followed,
1975                rest_until: None,
1976            })
1977        }
1978
1979        /// Watches the root and the `live` pids; returns whether any process
1980        /// was newly watched.
1981        pub(super) fn follow(&mut self, root: u32, live: &[u32]) -> io::Result<bool> {
1982            let wanted: HashSet<u32> = live.iter().copied().chain([root]).collect();
1983            self.followed.retain(|pid| wanted.contains(pid));
1984            let mut added = false;
1985            for pid in wanted {
1986                if self.followed.contains(&pid) {
1987                    continue;
1988                }
1989                // A process that exited already is seen by the scan that follows.
1990                if register(&self.queue, pid, FOLLOWED)? {
1991                    self.followed.insert(pid);
1992                }
1993                added = true;
1994            }
1995            Ok(added)
1996        }
1997
1998        /// Rests for `duration` before the next event is taken, so the
1999        /// scans a fork storm causes use at most half the time.
2000        pub(super) fn rest(&mut self, duration: Duration) {
2001            self.rest_until = Some(Instant::now() + duration);
2002        }
2003
2004        /// Returns after a watched process forked, exec'd or exited. An event
2005        /// is answered at once unless it comes within the previous scan's own
2006        /// duration after that scan: a child's lineage lasts only until its
2007        /// first `exec` after the parent exited, so no fixed delay is
2008        /// acceptable.
2009        pub(super) async fn changed(&mut self) -> io::Result<()> {
2010            loop {
2011                if let Some(until) = self.rest_until.take() {
2012                    async_io::Timer::at(until).await;
2013                }
2014                self.queue.readable().await?;
2015                if drain(&self.queue)? {
2016                    return Ok(());
2017                }
2018            }
2019        }
2020    }
2021
2022    /// A kqueue that signals when one child exits.
2023    pub(super) struct ExitWatch {
2024        pid: u32,
2025        queue: Async<OwnedFd>,
2026        watched: bool,
2027    }
2028
2029    impl ExitWatch {
2030        pub(super) fn new(pid: u32) -> io::Result<Self> {
2031            let queue = new_queue()?;
2032            let watched = register(&queue, pid, libc::NOTE_EXIT)?;
2033            Ok(Self {
2034                pid,
2035                queue,
2036                watched,
2037            })
2038        }
2039
2040        /// Returns once the child has exited and can be waited for.
2041        ///
2042        /// xnu refuses a new watch (`P_REF_DEAD`, `proc_prepareexit`) and then
2043        /// posts `NOTE_EXIT` (`proc_exit`) before it marks the process a
2044        /// zombie, so neither an exit event nor a refused watch means the
2045        /// child is waitable yet, and no further event follows. The wait for
2046        /// that last step blocks, which takes a pool thread only for the
2047        /// remainder of the kernel's exit teardown. A pid that is no child
2048        /// of this process fails that wait.
2049        pub(super) async fn exited(self) -> io::Result<()> {
2050            if self.watched {
2051                loop {
2052                    self.queue.readable().await?;
2053                    if drain(&self.queue)? {
2054                        break;
2055                    }
2056                }
2057            }
2058            let pid = self.pid;
2059            blocking::unblock(move || super::block_until_exited_unreaped(pid)).await
2060        }
2061    }
2062
2063    #[cfg(test)]
2064    pub(super) mod tests {
2065        use super::{
2066            Birth, IdentityMode, IdentitySource, ProcUniqIdentifierInfo, Spi, Uniq, UniqError,
2067            identity_mode, identity_mode_with, size_of, snapshot_with, unique_of,
2068        };
2069
2070        /// A source whose every query fails the way a changed SPI would.
2071        struct Broken(UniqError);
2072
2073        impl Broken {
2074            fn failing() -> Self {
2075                Self(UniqError::Unavailable(
2076                    "proc_pidinfo(PROC_PIDUNIQIDENTIFIERINFO) failed: test".to_string(),
2077                ))
2078            }
2079        }
2080
2081        impl IdentitySource for Broken {
2082            fn unique(&self, _pid: i32) -> Result<Uniq, UniqError> {
2083                match &self.0 {
2084                    UniqError::Gone => Err(UniqError::Gone),
2085                    UniqError::Unavailable(reason) => Err(UniqError::Unavailable(reason.clone())),
2086                }
2087            }
2088        }
2089
2090        /// A source that answers with another struct size than the SPI's.
2091        struct WrongSize;
2092
2093        impl IdentitySource for WrongSize {
2094            fn unique(&self, pid: i32) -> Result<Uniq, UniqError> {
2095                Err(UniqError::Unavailable(format!(
2096                    "returned 24 bytes for pid {pid}, expected {}",
2097                    size_of::<ProcUniqIdentifierInfo>()
2098                )))
2099            }
2100        }
2101
2102        fn own_row(table: &super::Table) -> &super::Proc {
2103            let me = std::process::id();
2104            table
2105                .procs
2106                .iter()
2107                .find(|process| process.pid() == me)
2108                .expect("the table lists this process")
2109        }
2110
2111        /// The SPI answers with the size declared here, and the unique id of
2112        /// a child links to its parent's.
2113        #[test]
2114        fn the_spi_answers_with_unique_ids_that_link_children_to_parents() {
2115            let (mode, degraded) = identity_mode();
2116            assert_eq!(degraded, None, "the SPI should work on this macOS");
2117            assert_eq!(mode, IdentityMode::Unique);
2118            let table = snapshot_with(&Spi, mode, true).expect("the table is readable");
2119            let me = own_row(&table);
2120            let Birth::Unique(my_id) = me.identity.birth else {
2121                panic!("expected a unique id, got {:?}", me.identity.birth);
2122            };
2123            let mut child = std::process::Command::new("/bin/sleep")
2124                .arg("5")
2125                .spawn()
2126                .expect("sleep should start");
2127            let table = snapshot_with(&Spi, mode, true).expect("the table is readable");
2128            let row = table
2129                .procs
2130                .iter()
2131                .find(|process| process.pid() == child.id())
2132                .expect("the table lists the child");
2133            assert_eq!(row.parent_unique, Some(my_id));
2134            child.kill().expect("child should be killed");
2135            child.wait().expect("child should be reaped");
2136        }
2137
2138        /// When the SPI fails, the job's identity is pid plus start time for
2139        /// good and lineage is dropped, and it says why.
2140        #[test]
2141        fn a_failing_spi_falls_back_to_pid_plus_start_time() {
2142            let (mode, degraded) = identity_mode_with(&Broken::failing());
2143            assert_eq!(mode, IdentityMode::Started);
2144            assert!(
2145                degraded
2146                    .as_deref()
2147                    .is_some_and(|reason| reason.contains("PROC_PIDUNIQIDENTIFIERINFO")),
2148                "{degraded:?}"
2149            );
2150            // The fallback never asks the SPI again.
2151            let table =
2152                snapshot_with(&Broken::failing(), mode, true).expect("the table is readable");
2153            assert!(!table.procs.is_empty());
2154            for process in &table.procs {
2155                assert!(matches!(process.identity.birth, Birth::Started { .. }));
2156                assert_eq!(process.parent_unique, None);
2157            }
2158            assert_eq!(own_row(&table).pid(), std::process::id());
2159            assert_eq!(unique_of(mode, std::process::id()), None);
2160        }
2161
2162        /// An unexpected size is treated like a failure.
2163        #[test]
2164        fn an_spi_answering_another_size_falls_back_too() {
2165            let (mode, degraded) = identity_mode_with(&WrongSize);
2166            assert_eq!(mode, IdentityMode::Started);
2167            assert!(
2168                degraded
2169                    .as_deref()
2170                    .is_some_and(|reason| reason.contains("expected")),
2171                "{degraded:?}"
2172            );
2173        }
2174
2175        /// A job that started with unique ids does not slip into start times
2176        /// when the SPI fails later: the scan fails instead.
2177        #[test]
2178        fn an_spi_failing_mid_job_fails_the_read() {
2179            let error = snapshot_with(&Broken::failing(), IdentityMode::Unique, true)
2180                .expect_err("identities never change kind");
2181            assert!(error.to_string().contains("PROC_PIDUNIQIDENTIFIERINFO"));
2182        }
2183
2184        /// The kqueue reports a watched process's forks, execs and exit, the
2185        /// first at once; nothing else wakes it on macOS, so this is the
2186        /// event-driven path itself.
2187        #[tokio::test]
2188        async fn the_watch_reports_a_fork_and_an_exit() {
2189            let mut shell = std::process::Command::new("/bin/sh")
2190                .args(["-c", "/bin/sleep 0.4 & /bin/sleep 0.6"])
2191                .spawn()
2192                .expect("sh should start");
2193            let mut watch = super::Watch::new(shell.id()).expect("kqueue should open");
2194            assert!(
2195                !watch.follow(shell.id(), &[]).expect("watch registers"),
2196                "the root is watched from the start"
2197            );
2198            // Events keep coming until the shell has exited and been seen.
2199            loop {
2200                tokio::time::timeout(std::time::Duration::from_secs(5), watch.changed())
2201                    .await
2202                    .expect("no event before the shell exited")
2203                    .expect("the watch reads events");
2204                if shell.try_wait().expect("sh is polled").is_some() {
2205                    break;
2206                }
2207            }
2208        }
2209
2210        /// The exit of a child is signalled to a watch made before it.
2211        #[tokio::test]
2212        async fn the_exit_watch_signals_the_exit_of_a_child() {
2213            let mut child = std::process::Command::new("/bin/sh")
2214                .args(["-c", "/bin/sleep 0.3"])
2215                .spawn()
2216                .expect("sh should start");
2217            let watch = super::ExitWatch::new(child.id()).expect("kqueue should open");
2218            tokio::time::timeout(std::time::Duration::from_secs(5), watch.exited())
2219                .await
2220                .expect("no event for the exit")
2221                .expect("the watch reads events");
2222            child.wait().expect("sh is reaped");
2223        }
2224
2225        /// A watch made after the child exited is refused by the kernel; it
2226        /// still ends once the child is waitable rather than failing.
2227        #[tokio::test]
2228        async fn a_watch_made_after_the_exit_ends_with_the_waitable_child() {
2229            let mut child = std::process::Command::new("/bin/sh")
2230                .args(["-c", "exit 0"])
2231                .spawn()
2232                .expect("sh should start");
2233            super::super::wait_for_exit(child.id())
2234                .await
2235                .expect("the exit is observed");
2236            let watch = super::ExitWatch::new(child.id()).expect("kqueue should open");
2237            assert!(!watch.watched, "the kernel watches no zombie");
2238            tokio::time::timeout(std::time::Duration::from_secs(5), watch.exited())
2239                .await
2240                .expect("the exited child is waitable")
2241                .expect("the zombie is this process's child");
2242            child.wait().expect("sh is reaped");
2243        }
2244
2245        /// A process that exits while the table is read is dropped, not a
2246        /// reason to fall back.
2247        #[test]
2248        fn a_process_that_exited_during_the_read_is_no_degradation() {
2249            let table = snapshot_with(&Broken(UniqError::Gone), IdentityMode::Unique, true)
2250                .expect("the table is readable");
2251            assert!(table.procs.is_empty());
2252        }
2253    }
2254}
2255
2256#[cfg(all(unix, not(any(target_os = "linux", target_os = "macos"))))]
2257compile_error!("descendant tracking needs /proc (Linux) or libproc (macOS); this Unix has neither");
2258
2259#[cfg(all(test, unix))]
2260mod tests {
2261    use std::{collections::HashSet, os::unix::process::CommandExt, time::Duration};
2262
2263    use executor_core::tokio::TokioGlobal;
2264
2265    use super::{
2266        JobMarker, JobProcess, JobTree, KillTreeError, ProcessScanner, ProcessTableError, platform,
2267        unix::{
2268            Birth, Command, Identity, Member, Proc, Signals, Table, Task, members, signal,
2269            signal_foreign_for_test,
2270        },
2271        wait_for_exit,
2272    };
2273
2274    const MARKER: &str = "job-marker";
2275
2276    fn proc(id: u32, parent: u32, group: u32) -> Proc {
2277        Proc {
2278            identity: Identity {
2279                pid: id,
2280                birth: Birth::Ticks(u64::from(id) * 10),
2281            },
2282            ppid: parent,
2283            parent_unique: None,
2284            pgid: group,
2285            zombie: false,
2286            name: format!("p{id}"),
2287            marker: None,
2288        }
2289    }
2290
2291    fn marked(mut process: Proc) -> Proc {
2292        process.marker = Some(MARKER.to_string());
2293        process
2294    }
2295
2296    fn pids(found: &[&Proc]) -> Vec<u32> {
2297        let mut pids: Vec<u32> = found.iter().map(|process| process.pid()).collect();
2298        pids.sort_unstable();
2299        pids
2300    }
2301
2302    /// Members come from the root's group, from ancestry below any member,
2303    /// from the marker and from earlier finds; the root and the host never do.
2304    #[test]
2305    fn members_follow_group_ancestry_and_marker() {
2306        let table = [
2307            proc(10, 1, 10),         // the root shell
2308            proc(11, 10, 10),        // a `&` child in the group
2309            proc(12, 11, 12),        // its child that left the group
2310            marked(proc(20, 1, 20)), // a setsid orphan with the marker
2311            proc(21, 20, 21),        // its child
2312            proc(30, 1, 30),         // unrelated
2313            proc(99, 1, 99),         // the host
2314        ];
2315        let found = members(&table, 10, 99, MARKER, &HashSet::new(), &HashSet::new());
2316        assert_eq!(pids(&found), [11, 12, 20, 21]);
2317    }
2318
2319    /// With nothing to link it an orphan that left the group is not a member:
2320    /// the limit the module documents.
2321    #[test]
2322    fn an_unmarked_session_leader_is_not_a_member() {
2323        let table = [proc(10, 1, 10), proc(20, 1, 20)];
2324        assert!(members(&table, 10, 99, MARKER, &HashSet::new(), &HashSet::new()).is_empty());
2325    }
2326
2327    /// A marker of another job does not attribute a process to this one.
2328    #[test]
2329    fn another_jobs_marker_is_no_member() {
2330        let mut other = proc(20, 1, 20);
2331        other.marker = Some("another-job".to_string());
2332        let table = [proc(10, 1, 10), other];
2333        assert!(members(&table, 10, 99, MARKER, &HashSet::new(), &HashSet::new()).is_empty());
2334    }
2335
2336    /// An earlier find stays a member while it is the same process, and a pid
2337    /// that now belongs to another process is not one.
2338    #[test]
2339    fn a_known_pid_reused_by_another_process_is_no_member() {
2340        let table = [proc(10, 1, 10), proc(20, 1, 20)];
2341        let same = HashSet::from([table[1].identity]);
2342        assert_eq!(
2343            pids(&members(&table, 10, 99, MARKER, &same, &HashSet::new())),
2344            [20]
2345        );
2346        let earlier = Identity {
2347            pid: 20,
2348            birth: Birth::Ticks(1),
2349        };
2350        let reused = HashSet::from([earlier]);
2351        assert!(members(&table, 10, 99, MARKER, &reused, &HashSet::new()).is_empty());
2352    }
2353
2354    /// Lineage by unique id survives reparenting: the orphan's `ppid` is 1,
2355    /// but its parent's unique id is the root's.
2356    #[test]
2357    fn lineage_links_an_orphan_to_the_root_and_to_found_members() {
2358        let unique = |mut process: Proc, id: u64, parent: u64| {
2359            process.identity.birth = Birth::Unique(id);
2360            process.parent_unique = Some(parent);
2361            process
2362        };
2363        let table = [
2364            unique(proc(10, 1, 10), 100, 1),
2365            unique(proc(20, 1, 20), 101, 100), // reparented child of the root
2366            unique(proc(21, 1, 21), 102, 101), // reparented child of that child
2367            unique(proc(30, 1, 30), 103, 1),   // unrelated
2368        ];
2369        let found = members(&table, 10, 99, MARKER, &HashSet::new(), &HashSet::new());
2370        assert_eq!(pids(&found), [20, 21]);
2371        // A zombie root is not listed on macOS: the id read earlier serves.
2372        let unlisted = &table[1..];
2373        let found = members(
2374            unlisted,
2375            10,
2376            99,
2377            MARKER,
2378            &HashSet::new(),
2379            &HashSet::from([100]),
2380        );
2381        assert_eq!(pids(&found), [20, 21]);
2382        // The unique ids of members that exited since still link their
2383        // children, and only those do.
2384        let exited = [
2385            unique(proc(10, 1, 10), 100, 1),
2386            unique(proc(21, 1, 21), 102, 101),
2387        ];
2388        let seen = HashSet::from([101]);
2389        let found = members(&exited, 10, 99, MARKER, &HashSet::new(), &seen);
2390        assert_eq!(pids(&found), [21]);
2391        let found = members(&exited, 10, 99, MARKER, &HashSet::new(), &HashSet::new());
2392        assert!(found.is_empty());
2393    }
2394
2395    fn spawn_group_leader(script: &str, marker: &JobMarker) -> std::process::Child {
2396        let (name, value) = marker.entry();
2397        std::process::Command::new("/bin/sh")
2398            .arg("-c")
2399            .arg(script)
2400            .env(name, value)
2401            .process_group(0)
2402            .stdout(std::process::Stdio::null())
2403            .stderr(std::process::Stdio::null())
2404            .spawn()
2405            .expect("sh should start")
2406    }
2407
2408    fn alive(pid: u32) -> bool {
2409        // SAFETY: signal 0 probes process existence.
2410        unsafe { libc::kill(pid.cast_signed(), 0) == 0 }
2411    }
2412
2413    async fn gone_within(pid: u32, wait: Duration) -> bool {
2414        let deadline = std::time::Instant::now() + wait;
2415        while std::time::Instant::now() < deadline {
2416            if !alive(pid) {
2417                return true;
2418            }
2419            async_io::Timer::after(Duration::from_millis(20)).await;
2420        }
2421        false
2422    }
2423
2424    /// The root stays a zombie, pid and group reserved, until it is waited
2425    /// for, and its status is still there.
2426    #[tokio::test(flavor = "multi_thread")]
2427    async fn the_root_stays_unreaped_until_it_is_waited_for() {
2428        let mut root = std::process::Command::new("/bin/sh")
2429            .args(["-c", "exit 3"])
2430            .process_group(0)
2431            .spawn()
2432            .expect("sh should start");
2433        wait_for_exit(root.id())
2434            .await
2435            .expect("the exit is observed");
2436        assert!(alive(root.id()), "the unreaped root still holds its pid");
2437        let status = root.wait().expect("the root is reaped afterwards");
2438        assert_eq!(status.code(), Some(3));
2439        assert!(!alive(root.id()));
2440    }
2441
2442    /// The failure path: a pid that is no child of this process.
2443    #[tokio::test(flavor = "multi_thread")]
2444    async fn waiting_for_a_process_that_is_no_child_fails() {
2445        assert!(wait_for_exit(1).await.is_err());
2446    }
2447
2448    /// Regression for the review's reproduction: a `setsid` Apple binary that
2449    /// the environment cannot attribute, found once through ancestry and then
2450    /// orphaned, is killed by a kill raced against the wait, and the wait ends.
2451    #[cfg(target_os = "macos")]
2452    #[tokio::test(flavor = "multi_thread")]
2453    async fn a_kill_raced_against_the_wait_kills_an_orphaned_apple_binary() {
2454        let marker = JobMarker::new();
2455        let dir = tempfile::tempdir().expect("temp dir");
2456        let pid_file = dir.path().join("perl.pid");
2457        let script = format!(
2458            "/bin/sh -c \"/usr/bin/perl -e 'use POSIX; POSIX::setsid(); \
2459             open(F, \\\">{}\\\"); print F \\$\\$; close F; sleep 30' & sleep 2\" &",
2460            pid_file.display()
2461        );
2462        let mut root = spawn_group_leader(&script, &marker);
2463        let tree = JobTree::spawn(&TokioGlobal, ProcessScanner::default(), root.id(), &marker);
2464        wait_for_exit(root.id()).await.expect("root exit observed");
2465        let waiter = {
2466            let tree = tree.clone();
2467            tokio::spawn(async move { tree.wait_descendants_exit().await })
2468        };
2469        // Past the inner shell's exit: perl is a session leader with ppid 1
2470        // and no readable environment.
2471        tokio::time::sleep(Duration::from_millis(3500)).await;
2472        let perl: u32 = std::fs::read_to_string(&pid_file)
2473            .expect("perl wrote its pid")
2474            .trim()
2475            .parse()
2476            .expect("pid");
2477        assert!(alive(perl), "perl must outlive the shells");
2478        tree.kill()
2479            .await
2480            .expect("the kill reports success only if it worked");
2481        assert!(
2482            gone_within(perl, Duration::from_secs(2)).await,
2483            "perl {perl} survived a kill that returned Ok"
2484        );
2485        tokio::time::timeout(Duration::from_secs(5), waiter)
2486            .await
2487            .expect("the wait ends after the kill")
2488            .expect("the wait task joins")
2489            .expect("the wait succeeds");
2490        tree.finish().await;
2491        root.wait().expect("root is reaped");
2492    }
2493
2494    /// A descendant that empties its environment loses the marker, and one
2495    /// that also leaves its session can no longer be found through its
2496    /// group either: only its ancestry — or, on Linux, the job's supervisor —
2497    /// still attributes it to the job. The kill must reach it anyway.
2498    #[cfg(all(unix, not(target_os = "linux")))]
2499    #[tokio::test(flavor = "multi_thread")]
2500    async fn an_env_cleaned_setsid_descendant_is_still_killed() {
2501        let marker = JobMarker::new();
2502        #[cfg(target_os = "macos")]
2503        let script = "/usr/bin/env -i /usr/bin/perl -e \
2504            'use POSIX; POSIX::setsid(); exec \"sleep\", \"300\"' & exit 0";
2505        #[cfg(not(target_os = "macos"))]
2506        let script = "/usr/bin/env -i sleep 300 & exit 0";
2507        let mut root = spawn_group_leader(script, &marker);
2508        let tree = JobTree::spawn(&TokioGlobal, ProcessScanner::default(), root.id(), &marker);
2509        wait_for_exit(root.id()).await.expect("root exit observed");
2510        let killed = tree.kill_descendants().await.expect("kill succeeds");
2511        assert_eq!(killed.len(), 1, "{killed:?}");
2512        assert!(
2513            gone_within(killed[0].pid, Duration::from_secs(2)).await,
2514            "the env-cleaned setsid child survived its job's kill"
2515        );
2516        tree.finish().await;
2517        root.wait().expect("root is reaped");
2518    }
2519
2520    /// On Linux the same escape runs under the job's supervisor, which owns
2521    /// the descendants itself: neither marker nor ancestry is needed to
2522    /// name the leftover it killed.
2523    #[cfg(target_os = "linux")]
2524    #[tokio::test(flavor = "multi_thread")]
2525    async fn an_env_cleaned_setsid_descendant_is_still_killed() {
2526        let config = heel::SandboxConfig::builder()
2527            .heel_binary(crate::test_heel::binary().await.unwrap())
2528            .network(heel::DenyAll)
2529            .security(heel::SecurityConfig::interactive())
2530            .supervised_spawn(true)
2531            .build();
2532        let sandbox = heel::Sandbox::with_config_and_executor(config, TokioGlobal)
2533            .await
2534            .expect("the sandbox builds");
2535        let mut child = sandbox
2536            .command("sh")
2537            .args(["-c", "/usr/bin/env -i setsid sleep 300 & exit 0"])
2538            .spawn_supervised(heel::supervisor::Foreground {
2539                reap_timeout: Duration::from_secs(5),
2540            })
2541            .await
2542            .expect("the supervised command spawns");
2543        let exit = child.wait().await.expect("the supervisor tears down");
2544        assert_eq!(exit.report.killed.len(), 1, "{:?}", exit.report.killed);
2545        // The name is read at kill time, and the background command passes
2546        // through `sh` (forked, before its exec), `env`, `setsid` and `sleep`.
2547        assert!(
2548            matches!(
2549                exit.report.killed[0].name.as_str(),
2550                "sh" | "env" | "setsid" | "sleep"
2551            ),
2552            "{:?}",
2553            exit.report.killed[0]
2554        );
2555        assert!(
2556            gone_within(exit.report.killed[0].pid, Duration::from_secs(2)).await,
2557            "the env-cleaned setsid child survived its job's teardown"
2558        );
2559    }
2560
2561    /// A kill of a plain tree freezes and kills the group's members and the
2562    /// descendants that left it, and names them.
2563    #[tokio::test(flavor = "multi_thread")]
2564    async fn kill_descendants_names_what_it_killed() {
2565        let marker = JobMarker::new();
2566        let mut root = spawn_group_leader("sleep 300 & sleep 300 & exit 0", &marker);
2567        let tree = JobTree::spawn(&TokioGlobal, ProcessScanner::default(), root.id(), &marker);
2568        wait_for_exit(root.id()).await.expect("root exit observed");
2569        let killed = tree.kill_descendants().await.expect("kill succeeds");
2570        assert_eq!(killed.len(), 2, "{killed:?}");
2571        for JobProcess { pid, name } in &killed {
2572            assert_eq!(name, "sleep", "the name is read after the freeze");
2573            assert!(gone_within(*pid, Duration::from_secs(2)).await);
2574        }
2575        assert_eq!(tree.kill_descendants().await.expect("again"), []);
2576        tree.finish().await;
2577        root.wait().expect("root is reaped");
2578    }
2579
2580    /// After the job's task ended, a kill does nothing and says so: the
2581    /// root's pid may be anyone's.
2582    #[tokio::test(flavor = "multi_thread")]
2583    async fn a_finished_tree_kills_nothing() {
2584        let marker = JobMarker::new();
2585        let mut root = spawn_group_leader("exit 0", &marker);
2586        let tree = JobTree::spawn(&TokioGlobal, ProcessScanner::default(), root.id(), &marker);
2587        wait_for_exit(root.id()).await.expect("root exit observed");
2588        tree.wait_descendants_exit().await.expect("nothing left");
2589        tree.finish().await;
2590        root.wait().expect("root is reaped");
2591        assert!(
2592            matches!(tree.kill().await, Err(KillTreeError::Ended)),
2593            "a kill after the tree ended is not a success"
2594        );
2595        assert_eq!(tree.kill_descendants().await.expect("nothing"), []);
2596    }
2597
2598    /// A command still queued when the task ends is dropped with the task,
2599    /// so its asker learns the task ended instead of waiting forever, and a
2600    /// command sent afterwards is refused.
2601    #[tokio::test(flavor = "multi_thread")]
2602    async fn a_command_queued_behind_the_finish_is_not_left_unanswered() {
2603        let marker = JobMarker::new();
2604        let mut root = spawn_group_leader("exit 0", &marker);
2605        let (commands, inbox) = async_channel::unbounded();
2606        let task = Task::new(root.id(), marker.entry().1, ProcessScanner::default());
2607        let (ack, finished) = async_channel::bounded(1);
2608        let (reply, answer) = async_channel::bounded(1);
2609        commands
2610            .send(Command::Finish(ack))
2611            .await
2612            .expect("the task's inbox is open");
2613        commands
2614            .send(Command::Kill { group: true, reply })
2615            .await
2616            .expect("the task's inbox is open");
2617        task.run(inbox).await;
2618        finished.try_recv().expect("the finish is acknowledged");
2619        assert!(
2620            matches!(answer.try_recv(), Err(async_channel::TryRecvError::Closed)),
2621            "the queued kill's reply must be dropped with the task"
2622        );
2623        let (late, _) = async_channel::bounded(1);
2624        assert!(
2625            commands.send(Command::Finish(late)).await.is_err(),
2626            "a command sent after the task ended must be refused"
2627        );
2628        wait_for_exit(root.id()).await.expect("root exit observed");
2629        root.wait().expect("root is reaped");
2630    }
2631
2632    /// A process that cannot be signalled is an error naming it, not a
2633    /// success. Signal 0 delivers nothing.
2634    #[test]
2635    fn a_process_that_cannot_be_signalled_is_an_error_naming_it() {
2636        let Some(result) = signal_foreign_for_test(0) else {
2637            panic!("no listed process belongs to another user");
2638        };
2639        match result.expect_err("the process is not ours to signal") {
2640            ProcessTableError::Signal { process, source } => {
2641                assert!(process.pid > 0);
2642                assert_ne!(process.name, "");
2643                assert_eq!(source.raw_os_error(), Some(libc::EPERM));
2644            }
2645            other => panic!("expected a signal error, got {other}"),
2646        }
2647    }
2648
2649    /// Delivers every signal but `SIGKILL`: a process that does not die.
2650    struct IgnoresKill;
2651
2652    impl Signals for IgnoresKill {
2653        fn member(&self, member: &Member, number: libc::c_int) -> Result<(), ProcessTableError> {
2654            if number == libc::SIGKILL {
2655                Ok(())
2656            } else {
2657                signal(member, number)
2658            }
2659        }
2660
2661        fn group(&self, _root: &JobProcess, _number: libc::c_int) -> Result<(), ProcessTableError> {
2662            Ok(())
2663        }
2664    }
2665
2666    /// A kill that leaves a tracked process alive is an error naming it,
2667    /// never a success.
2668    #[tokio::test(flavor = "multi_thread")]
2669    async fn a_kill_that_leaves_survivors_is_not_ok() {
2670        let marker = JobMarker::new();
2671        let mut root = spawn_group_leader("sleep 300 & exit 0", &marker);
2672        let (commands, inbox) = async_channel::unbounded();
2673        let task = Task::with_signals(
2674            IgnoresKill,
2675            root.id(),
2676            marker.entry().1,
2677            ProcessScanner::default(),
2678        );
2679        executor_core::Task::detach(executor_core::Executor::spawn(
2680            &TokioGlobal,
2681            task.run(inbox),
2682        ));
2683        let tree = JobTree {
2684            tracked: super::TrackedJob::Watched(commands),
2685        };
2686        wait_for_exit(root.id()).await.expect("root exit observed");
2687        let result = tree.kill_descendants().await;
2688        let survivors = match result {
2689            Err(ProcessTableError::Survived(survivors)) => survivors,
2690            other => panic!("expected the survivors as an error, got {other:?}"),
2691        };
2692        assert_eq!(survivors.len(), 1, "{survivors:?}");
2693        assert_eq!(survivors[0].name, "sleep");
2694        // SAFETY: the pid is a live child's of this test.
2695        unsafe { libc::kill(survivors[0].pid.cast_signed(), libc::SIGKILL) };
2696        assert!(gone_within(survivors[0].pid, Duration::from_secs(2)).await);
2697        tree.finish().await;
2698        root.wait().expect("root is reaped");
2699    }
2700
2701    /// A start time or unique id that is not the process's own.
2702    const fn stale(birth: Birth) -> Birth {
2703        match birth {
2704            Birth::Ticks(ticks) => Birth::Ticks(ticks + 1),
2705            Birth::Unique(id) => Birth::Unique(id + 1),
2706            Birth::Started { seconds, micros } => Birth::Started {
2707                seconds: seconds + 1,
2708                micros,
2709            },
2710        }
2711    }
2712
2713    /// The identity is checked right before a signal: a pid that now belongs
2714    /// to another process is not signalled.
2715    #[test]
2716    fn a_signal_for_a_reused_pid_reaches_nobody() {
2717        use std::os::unix::process::ExitStatusExt;
2718
2719        let mut child = std::process::Command::new("/bin/sleep")
2720            .arg("30")
2721            .spawn()
2722            .expect("sleep should start");
2723        let table =
2724            platform::snapshot(platform::identity_mode().0, true).expect("the table is readable");
2725        let row = table
2726            .procs
2727            .iter()
2728            .find(|process| process.pid() == child.id())
2729            .expect("the table lists the child");
2730        let member = |birth| Member {
2731            identity: Identity {
2732                pid: row.pid(),
2733                birth,
2734            },
2735            name: row.name.clone(),
2736            zombie: false,
2737        };
2738        signal(&member(stale(row.identity.birth)), libc::SIGKILL)
2739            .expect("a pid that changed hands is no error");
2740        // A delivered SIGKILL ends a sleeping process at once; the pause is
2741        // only for the kernel to act on one.
2742        std::thread::sleep(Duration::from_millis(200));
2743        assert!(
2744            child.try_wait().expect("child is polled").is_none(),
2745            "the stale identity must not be signalled"
2746        );
2747        signal(&member(row.identity.birth), libc::SIGKILL).expect("the real one is signalled");
2748        let status = child.wait().expect("child is reaped");
2749        assert_eq!(status.signal(), Some(libc::SIGKILL));
2750    }
2751
2752    /// Two reads of the table run together: neither waits for the other to
2753    /// finish, so the kills of several jobs are really concurrent.
2754    #[test]
2755    fn reads_of_the_process_table_do_not_wait_for_each_other() {
2756        let scanner = ProcessScanner::default();
2757        let (first_started, second_waits) = std::sync::mpsc::channel::<()>();
2758        let (second_started, first_waits) = std::sync::mpsc::channel::<()>();
2759        let patience = Duration::from_secs(5);
2760        std::thread::scope(|scope| {
2761            let scanner = &scanner;
2762            let first = scope.spawn(move || {
2763                scanner.table_with(Duration::ZERO, || {
2764                    first_started.send(()).expect("the other read listens");
2765                    first_waits
2766                        .recv_timeout(patience)
2767                        .expect("the other read must start while this one runs");
2768                    Ok(Table { procs: Vec::new() })
2769                })
2770            });
2771            let second = scope.spawn(move || {
2772                scanner.table_with(Duration::ZERO, || {
2773                    second_started.send(()).expect("the other read listens");
2774                    second_waits
2775                        .recv_timeout(patience)
2776                        .expect("the other read must start while this one runs");
2777                    Ok(Table { procs: Vec::new() })
2778                })
2779            });
2780            first.join().expect("first read").expect("table");
2781            second.join().expect("second read").expect("table");
2782        });
2783    }
2784
2785    /// Reads the pid a helper wrote to `file`, waiting for it to appear.
2786    #[cfg(target_os = "macos")]
2787    async fn pid_from(file: &std::path::Path) -> u32 {
2788        let deadline = std::time::Instant::now() + Duration::from_secs(5);
2789        loop {
2790            if let Ok(text) = std::fs::read_to_string(file)
2791                && let Ok(pid) = text.trim().parse()
2792            {
2793                return pid;
2794            }
2795            assert!(
2796                std::time::Instant::now() < deadline,
2797                "{} was never written",
2798                file.display()
2799            );
2800            async_io::Timer::after(Duration::from_millis(20)).await;
2801        }
2802    }
2803
2804    /// Kills `pid` whatever a test found, so a failed assertion leaks nothing.
2805    #[cfg(target_os = "macos")]
2806    fn kill_leftover(pid: u32) {
2807        // SAFETY: plain integers; a pid that is gone is no harm.
2808        unsafe { libc::kill(pid.cast_signed(), libc::SIGKILL) };
2809    }
2810
2811    /// R3b: an Apple binary that calls `setsid`, started in the background as
2812    /// the shell's last command, while the shell exits at once. Watching the
2813    /// root from its spawn finds it before it leaves the group, and the job's
2814    /// kill ends it.
2815    #[cfg(target_os = "macos")]
2816    #[tokio::test(flavor = "multi_thread")]
2817    async fn a_setsid_apple_binary_started_as_the_last_command_is_killed() {
2818        let marker = JobMarker::new();
2819        let dir = tempfile::tempdir().expect("temp dir");
2820        let pid_file = dir.path().join("perl.pid");
2821        let script = format!(
2822            "/usr/bin/perl -e 'use POSIX; POSIX::setsid(); open(F, \">{}\"); \
2823             print F $$; close F; sleep 30' &",
2824            pid_file.display()
2825        );
2826        let mut root = spawn_group_leader(&script, &marker);
2827        let tree = JobTree::spawn(&TokioGlobal, ProcessScanner::default(), root.id(), &marker);
2828        wait_for_exit(root.id()).await.expect("root exit observed");
2829        let perl = pid_from(&pid_file).await;
2830        let killed = tree.kill_descendants().await;
2831        let gone = gone_within(perl, Duration::from_secs(2)).await;
2832        kill_leftover(perl);
2833        tree.finish().await;
2834        root.wait().expect("root is reaped");
2835        let killed = killed.expect("the kill succeeds");
2836        assert!(
2837            killed.iter().any(|process| process.pid == perl),
2838            "perl {perl} was not found: {killed:?}"
2839        );
2840        assert!(gone, "perl {perl} survived the kill");
2841    }
2842
2843    /// R2b: a program that daemonizes the way `ssh -f` does (fork, the parent
2844    /// exits, the child calls `setsid`) while the shell goes on for a while.
2845    /// The job is not over while the daemon lives, and its kill ends it.
2846    #[cfg(target_os = "macos")]
2847    #[ignore = "approximation test: passed 199 of 200 runs with a scan on every event; the one failure came while other builds ran and its cause was not captured, so it stays out of the default run until a failure is captured"]
2848    #[tokio::test(flavor = "multi_thread")]
2849    async fn a_daemonizing_apple_binary_keeps_the_job_alive_and_is_killed() {
2850        let marker = JobMarker::new();
2851        let dir = tempfile::tempdir().expect("temp dir");
2852        let pid_file = dir.path().join("daemon.pid");
2853        let script = format!(
2854            "/usr/bin/perl -e 'use POSIX; fork and exit; POSIX::setsid(); \
2855             open(F, \">{}\"); print F $$; close F; sleep 30'; sleep 1",
2856            pid_file.display()
2857        );
2858        let mut root = spawn_group_leader(&script, &marker);
2859        let tree = JobTree::spawn(&TokioGlobal, ProcessScanner::default(), root.id(), &marker);
2860        wait_for_exit(root.id()).await.expect("root exit observed");
2861        let daemon = pid_from(&pid_file).await;
2862        let mut waiter = {
2863            let tree = tree.clone();
2864            tokio::spawn(async move { tree.wait_descendants_exit().await })
2865        };
2866        let early = tokio::time::timeout(Duration::from_secs(2), &mut waiter).await;
2867        let still_waiting = early.is_err();
2868        let killed = tree.kill().await;
2869        let gone = gone_within(daemon, Duration::from_secs(2)).await;
2870        kill_leftover(daemon);
2871        let finished = match early {
2872            Ok(done) => done,
2873            Err(_) => tokio::time::timeout(Duration::from_secs(5), &mut waiter)
2874                .await
2875                .expect("the wait ends after the kill"),
2876        };
2877        tree.finish().await;
2878        root.wait().expect("root is reaped");
2879        assert!(
2880            still_waiting,
2881            "the wait ended while the daemon {daemon} lived"
2882        );
2883        killed.expect("the kill succeeds");
2884        assert!(gone, "the daemon {daemon} survived the kill");
2885        finished
2886            .expect("the wait task joins")
2887            .expect("the wait succeeds");
2888    }
2889}