Skip to main content

jump_core/
process.rs

1// Copyright 2026 entro314-labs
2// SPDX-License-Identifier: MPL-2.0
3
4//! Process search, behind the `kill` keyword.
5//!
6//! Typing `kill fire` lists the user's own processes whose name or command
7//! line matches, heaviest first; activating one sends `SIGTERM`, and the
8//! frontend offers `SIGKILL` as a secondary action. Behind a keyword rather
9//! than always-on for the same reason clipboard history is: a result whose
10//! activation kills something must never appear next to results whose
11//! activation opens something.
12//!
13//! The listing is a plain `/proc` walk, done fresh per keystroke. A few
14//! hundred processes at two small files each is well under a millisecond of
15//! I/O, and a cache would only be a way to offer a process that has already
16//! exited.
17
18use std::path::Path;
19use std::process::{Command, Stdio};
20
21use crate::model::{Icon, Item, ItemKey, Source};
22
23/// Results returned to the UI.
24const RESULTS: usize = 12;
25
26/// One running process.
27#[derive(Debug, Clone)]
28struct Process {
29    pid: u32,
30    /// Short name from `/proc/<pid>/comm`.
31    name: String,
32    /// Full command line, NUL separators replaced with spaces.
33    cmdline: String,
34    /// Resident set size in bytes.
35    rss: u64,
36}
37
38/// The user's own processes matching `needle`, heaviest first.
39///
40/// An empty needle lists everything, which is what `kill ` with nothing after
41/// it shows: the biggest things running, which is usually what the user is
42/// hunting for anyway.
43#[must_use]
44pub fn matching(needle: &str) -> Vec<Item> {
45    let needle = needle.to_lowercase();
46    let tokens: Vec<&str> = needle.split_whitespace().collect();
47
48    let mut processes: Vec<Process> = list()
49        .into_iter()
50        .filter(|process| {
51            let haystack = format!(
52                "{} {} {}",
53                process.name.to_lowercase(),
54                process.cmdline.to_lowercase(),
55                process.pid
56            );
57            tokens.iter().all(|token| haystack.contains(token))
58        })
59        .collect();
60
61    // Heaviest first: with no better signal, the process eating the most
62    // memory is the likeliest kill target, and a deterministic order beats
63    // pid order for a list the user scans.
64    processes.sort_by_key(|process| std::cmp::Reverse(process.rss));
65    processes.truncate(RESULTS);
66
67    processes
68        .into_iter()
69        .map(|process| Item {
70            // Keyed by name rather than pid: pids never repeat across
71            // sessions, so frecency could not learn "the user keeps killing
72            // this program" any other way.
73            key: ItemKey(format!("process:{}", process.name)),
74            id: 0,
75            title: process.name,
76            subtitle: format!(
77                "PID {} · {} · {}",
78                process.pid,
79                human_bytes(process.rss),
80                truncate(&process.cmdline, 80),
81            ),
82            icon: Some(Icon::Name("utilities-system-monitor-symbolic".to_owned())),
83            category_icon: None,
84            window: None,
85            source: Source::Process { pid: process.pid },
86            autocomplete: None,
87            score: 0.0,
88        })
89        .collect()
90}
91
92/// Ask a process to exit, or make it.
93///
94/// `SIGTERM` by default so the process can save and clean up; `force` is
95/// `SIGKILL`, the action panel's escalation for the ones that ignore that.
96/// Delivered through `kill(1)` rather than a syscall binding — it is
97/// everywhere, and this path runs a handful of times per session.
98pub fn terminate(pid: u32, force: bool) {
99    let signal = if force { "-KILL" } else { "-TERM" };
100    let result = Command::new("kill")
101        .arg(signal)
102        .arg(pid.to_string())
103        .stdin(Stdio::null())
104        .stdout(Stdio::null())
105        .stderr(Stdio::null())
106        .status();
107
108    match result {
109        Ok(status) if status.success() => {}
110        Ok(status) => tracing::warn!(pid, ?status, "kill refused; process may have exited"),
111        Err(error) => tracing::error!(pid, %error, "could not run kill"),
112    }
113}
114
115/// Every live process belonging to the current user, except this one.
116fn list() -> Vec<Process> {
117    use std::os::unix::fs::MetadataExt;
118
119    let uid = effective_uid();
120    let own_pid = std::process::id();
121
122    let Ok(entries) = std::fs::read_dir("/proc") else {
123        return Vec::new();
124    };
125
126    entries
127        .flatten()
128        .filter_map(|entry| {
129            let pid: u32 = entry.file_name().to_str()?.parse().ok()?;
130            if pid == own_pid {
131                return None;
132            }
133
134            // Other users' processes cannot be signalled, so listing them
135            // would only offer actions that fail.
136            let metadata = entry.metadata().ok()?;
137            if u64::from(metadata.uid()) != uid {
138                return None;
139            }
140
141            let path = entry.path();
142            read_process(&path, pid)
143        })
144        .collect()
145}
146
147/// Read one process's identity, skipping kernel threads.
148fn read_process(path: &Path, pid: u32) -> Option<Process> {
149    let cmdline_raw = std::fs::read(path.join("cmdline")).ok()?;
150    // Kernel threads have an empty cmdline; nothing the user can kill.
151    if cmdline_raw.is_empty() {
152        return None;
153    }
154    let cmdline: String = cmdline_raw
155        .split(|byte| *byte == 0)
156        .filter(|part| !part.is_empty())
157        .map(|part| String::from_utf8_lossy(part).into_owned())
158        .collect::<Vec<_>>()
159        .join(" ");
160
161    let name = std::fs::read_to_string(path.join("comm"))
162        .ok()?
163        .trim()
164        .to_owned();
165
166    // statm's second field is resident pages.
167    let rss = std::fs::read_to_string(path.join("statm"))
168        .ok()
169        .and_then(|statm| {
170            statm
171                .split_whitespace()
172                .nth(1)
173                .and_then(|pages| pages.parse::<u64>().ok())
174        })
175        .map_or(0, |pages| pages * 4096);
176
177    Some(Process {
178        pid,
179        name,
180        cmdline,
181        rss,
182    })
183}
184
185/// The effective uid, without a libc dependency: the answer is in procfs,
186/// and reading our own `/proc/self/status` costs one small file.
187fn effective_uid() -> u64 {
188    std::fs::read_to_string("/proc/self/status")
189        .ok()
190        .and_then(|status| {
191            status.lines().find_map(|line| {
192                let rest = line.strip_prefix("Uid:")?;
193                // Fields: real, effective, saved, filesystem.
194                rest.split_whitespace().nth(1)?.parse().ok()
195            })
196        })
197        .unwrap_or(u64::MAX)
198}
199
200fn human_bytes(bytes: u64) -> String {
201    const MB: u64 = 1024 * 1024;
202    const GB: u64 = 1024 * MB;
203    if bytes >= GB {
204        format!("{:.1} GB", bytes as f64 / GB as f64)
205    } else {
206        format!("{} MB", bytes / MB)
207    }
208}
209
210fn truncate(text: &str, limit: usize) -> String {
211    if text.chars().count() <= limit {
212        text.to_owned()
213    } else {
214        let cut: String = text.chars().take(limit).collect();
215        format!("{cut}…")
216    }
217}
218
219#[cfg(test)]
220mod tests {
221    use super::*;
222    use std::time::{Duration, Instant};
223
224    #[test]
225    fn finds_and_terminates_a_real_process() {
226        let mut child = Command::new("sleep")
227            .arg("300")
228            .stdin(Stdio::null())
229            .stdout(Stdio::null())
230            .spawn()
231            .expect("spawn sleep");
232        let pid = child.id();
233
234        // Give /proc a moment on slow machines.
235        std::thread::sleep(Duration::from_millis(50));
236
237        let items = matching(&pid.to_string());
238        assert!(
239            items
240                .iter()
241                .any(|item| item.source == Source::Process { pid }),
242            "spawned process appears in the listing"
243        );
244
245        terminate(pid, false);
246
247        let deadline = Instant::now() + Duration::from_secs(5);
248        loop {
249            match child.try_wait().expect("try_wait") {
250                Some(_) => break,
251                None if Instant::now() > deadline => panic!("process survived SIGTERM"),
252                None => std::thread::sleep(Duration::from_millis(20)),
253            }
254        }
255    }
256
257    #[test]
258    fn all_tokens_must_match() {
259        let mut child = Command::new("sleep")
260            .arg("300")
261            .stdin(Stdio::null())
262            .stdout(Stdio::null())
263            .spawn()
264            .expect("spawn sleep");
265        let pid = child.id();
266        std::thread::sleep(Duration::from_millis(50));
267
268        let items = matching(&format!("sleep no-such-token-{pid}"));
269        assert!(items.is_empty());
270
271        terminate(pid, true);
272        let _ = child.wait();
273    }
274
275    #[test]
276    fn other_processes_do_not_leak_into_a_pid_query() {
277        // A query for a nonsense token matches nothing at all.
278        assert!(matching("zzqx-definitely-not-a-process").is_empty());
279    }
280
281    #[test]
282    fn bytes_render_for_humans() {
283        assert_eq!(human_bytes(512 * 1024 * 1024), "512 MB");
284        assert_eq!(human_bytes(3 * 1024 * 1024 * 1024), "3.0 GB");
285    }
286}