Skip to main content

kernel/
process.rs

1//! Linux process inspection and the kernel's process-tree kill (tree-memory.ts `killProcessTree`, `descendantPids`).
2
3use rustix::process::{Pid, Signal, kill_process, kill_process_group};
4use std::collections::HashMap;
5use std::time::Duration;
6
7pub(crate) struct ProcStat {
8    pub state: String,
9    pub ppid: i32,
10    /// Start time in clock ticks since boot: tells a live process apart from a later one reusing its pid.
11    pub start_time: u64,
12}
13
14/// Fields after the parenthesized command name of /proc/<pid>/stat: state(3), ppid(4), ...
15fn stat_fields(pid: i32) -> Option<Vec<String>> {
16    let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
17    let rest = stat.get(stat.rfind(')')? + 2..)?;
18    Some(rest.split(' ').map(str::to_string).collect())
19}
20
21/// Parent, state and start time of one process (`processStat`), or none when it is gone.
22pub(crate) fn process_stat(pid: i32) -> Option<ProcStat> {
23    let fields = stat_fields(pid)?;
24    Some(ProcStat {
25        state: fields.first()?.clone(),
26        ppid: fields.get(1)?.parse().ok()?,
27        start_time: fields.get(19)?.parse().ok()?,
28    })
29}
30
31/// CPU seconds (user + system) of one Linux process, or None when unavailable.
32pub(crate) fn process_cpu_seconds(pid: i32) -> Option<f64> {
33    let fields = stat_fields(pid)?;
34    let user: f64 = fields.get(11)?.parse().ok()?;
35    let system: f64 = fields.get(12)?.parse().ok()?;
36    Some((user + system) / 100.0)
37}
38
39/// Live descendants of `root`, breadth first (zombies are skipped: they cannot be signalled).
40pub(crate) fn descendant_pids(root: i32) -> Vec<i32> {
41    let Ok(entries) = std::fs::read_dir("/proc") else {
42        return Vec::new();
43    };
44    let mut children: HashMap<i32, Vec<i32>> = HashMap::new();
45    for entry in entries.flatten() {
46        let Some(pid) = entry.file_name().to_str().and_then(|name| name.parse::<i32>().ok()) else {
47            continue;
48        };
49        let Some(stat) = process_stat(pid) else {
50            continue;
51        };
52        if stat.state == "Z" || stat.state == "X" {
53            continue;
54        }
55        children.entry(stat.ppid).or_default().push(pid);
56    }
57    let mut result = Vec::new();
58    let mut queue = std::collections::VecDeque::from([root]);
59    while let Some(parent) = queue.pop_front() {
60        for &child in children.get(&parent).map(Vec::as_slice).unwrap_or_default() {
61            result.push(child);
62            queue.push_back(child);
63        }
64    }
65    result
66}
67
68/// The process group a host may signal for a command it started in a group of its own: `pgid` itself, when it is
69/// a real positive group id (never 0, -1 or another negative value, never init's 1) and neither this process's pid
70/// nor this process's own group. Pure, so the guard is tested without sending any signal.
71fn command_group_target(pgid: i32, own_pid: i32, own_group: i32) -> Option<Pid> {
72    if pgid <= 1 || pgid == own_pid || pgid == own_group {
73        return None;
74    }
75    Pid::from_raw(pgid)
76}
77
78/// The process a host may signal: a positive pid other than init and this process (pure, as above).
79pub(crate) fn process_target(pid: i32, own_pid: i32) -> Option<Pid> {
80    if pid <= 1 || pid == own_pid {
81        return None;
82    }
83    Pid::from_raw(pid)
84}
85
86/// SIGKILLs the process group the host created for one command (its leader's `pgid`), through
87/// [`command_group_target`]; whether a signal was sent.
88pub fn kill_command_group(pgid: i32) -> bool {
89    let own_pid = rustix::process::getpid().as_raw_nonzero().get();
90    let own_group = rustix::process::getpgrp().as_raw_nonzero().get();
91    match command_group_target(pgid, own_pid, own_group) {
92        Some(group) => kill_process_group(group, Signal::KILL).is_ok(),
93        None => false,
94    }
95}
96
97fn signal(pid: i32, signal: Signal) {
98    let own = rustix::process::getpid().as_raw_nonzero().get();
99    if let Some(pid) = process_target(pid, own) {
100        let _ = kill_process(pid, signal);
101    }
102}
103
104/// What else a tree kill reaches (`KillTreeOptions` of tree-memory.ts).
105#[derive(Default)]
106pub(crate) struct KillExtras<'a> {
107    /// Processes seen in the tree earlier (pid to start time), killed when still the same process.
108    pub known: Option<&'a HashMap<i32, u64>>,
109    /// The kernel's cgroup scope: every process still in it is killed.
110    pub cgroup_dir: Option<&'a std::path::Path>,
111}
112
113/// SIGKILLs `root` and every process in its tree. The root is stopped first so it can neither start new processes
114/// nor exit while its descendants are killed; as a child subreaper it adopts their orphans, which later sweeps kill.
115/// `root_alive`: the root is still the host's unreaped child, so its pid cannot belong to another process. Processes
116/// seen in earlier watchdog scans and the members of the kernel's scope are killed too.
117pub(crate) fn kill_process_tree(root: i32, owns_process_group: bool, root_alive: bool, extras: KillExtras<'_>) {
118    if root_alive {
119        signal(root, Signal::STOP);
120        for sweep in 0..20 {
121            let pids = descendant_pids(root);
122            if pids.is_empty() {
123                break;
124            }
125            for pid in pids {
126                signal(pid, Signal::KILL);
127            }
128            std::thread::sleep(Duration::from_millis(if sweep < 5 { 2 } else { 10 }));
129        }
130    }
131    if owns_process_group {
132        kill_command_group(root);
133    }
134    if root_alive {
135        signal(root, Signal::KILL);
136    }
137    for (&pid, &start_time) in extras.known.into_iter().flatten() {
138        if process_stat(pid).is_some_and(|stat| stat.start_time == start_time && stat.state != "Z") {
139            signal(pid, Signal::KILL);
140        }
141    }
142    // Only a scope of the kernel's own: never the host's cgroup or an ancestor of it (see `is_foreign_scope`).
143    if let Some(dir) = extras
144        .cgroup_dir
145        .filter(|dir| crate::tree_memory::is_foreign_scope(dir))
146    {
147        let own = std::process::id() as i32;
148        for pid in crate::tree_memory::cgroup_pids(dir) {
149            if pid != own {
150                signal(pid, Signal::KILL);
151            }
152        }
153    }
154}
155
156#[cfg(test)]
157mod tests {
158    use super::command_group_target;
159
160    /// The process-group kill guard, tested as a pure function only: no signal is ever sent here.
161    #[test]
162    fn kernel_w16f_only_a_real_command_group_other_than_the_hosts_own_may_be_signalled() {
163        let (own_pid, own_group) = (4242, 4000);
164        for refused in [0, -1, -4242, 1, own_pid, own_group, i32::MIN] {
165            assert_eq!(command_group_target(refused, own_pid, own_group), None, "{refused}");
166        }
167        for allowed in [2, 4001, 4243, i32::MAX] {
168            assert_eq!(
169                command_group_target(allowed, own_pid, own_group).map(|pid| pid.as_raw_nonzero().get()),
170                Some(allowed)
171            );
172        }
173    }
174}