The subtree search returned early whenever it found *any* group member, so an in-tree stage that was busy or sleeping on a timer masked a reparented member genuinely parked on the tty. Checking every member instead would have meant a /proc scan per session per tick whenever nothing was parked — the common case. ProcGroups snapshots /proc once per activity pass and indexes by process group, so the cost is one walk however many sessions the daemon owns, and the subtree walk disappears: the index is a superset of it. Also fixes the background-helper test, which had stopped discriminating. It polled until awaiting_input was true and caught a moment before the helper spawned, so it passed against a deepest-descendant walk too. It now waits for the helper to exist first. Both regression tests were re-checked by patching each old implementation back in. Reported in review on #51. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
264 lines
9.5 KiB
Rust
264 lines
9.5 KiB
Rust
//! Best-effort `/proc` inspection for the activity watcher (NAP-340, Linux).
|
|
//!
|
|
//! Decides whether a session is **blocked waiting on the user**: ask the kernel
|
|
//! which process group owns the terminal, then check whether any live member of
|
|
//! that group is parked on the terminal.
|
|
//!
|
|
//! `/proc/<pid>/syscall` would say so exactly, but it's ptrace-gated and
|
|
//! unreadable for our own sessions on a default kernel, so we combine three
|
|
//! *unprivileged* signals instead:
|
|
//!
|
|
//! 1. process state `S` (interruptible sleep — where a blocking `read()` parks),
|
|
//! 2. its `wchan` is not a pure timer sleep (so `sleep 30`, which also sits in
|
|
//! `S` with the terminal inherited, is excluded), and
|
|
//! 3. one of its stdio fds is the pane's tty.
|
|
//!
|
|
//! Every step degrades to `false` on a read failure, so a non-Linux host or a
|
|
//! denied `/proc` read falls back to `Idle`.
|
|
|
|
use std::collections::HashMap;
|
|
|
|
/// One walk of `/proc`, shared by every session in an activity pass.
|
|
///
|
|
/// The foreground process group is the unit that matters, and its members are
|
|
/// not reliably reachable from the pane: the group leader can exit while others
|
|
/// run on, and a stage that forks a terminal-reading child and exits leaves
|
|
/// that child reparented to init. Walking the pane's process tree misses both.
|
|
///
|
|
/// Snapshotting once per pass costs one `/proc` walk however many sessions the
|
|
/// daemon owns — cheaper than the per-session `tmux list-panes` fork that
|
|
/// already runs on the same tick.
|
|
#[derive(Debug, Default)]
|
|
pub struct ProcGroups {
|
|
stats: HashMap<i32, Stat>,
|
|
by_pgid: HashMap<i32, Vec<i32>>,
|
|
}
|
|
|
|
impl ProcGroups {
|
|
pub fn snapshot() -> Self {
|
|
let mut stats = HashMap::new();
|
|
let mut by_pgid: HashMap<i32, Vec<i32>> = HashMap::new();
|
|
let Ok(entries) = std::fs::read_dir("/proc") else {
|
|
return Self::default();
|
|
};
|
|
for pid in entries
|
|
.flatten()
|
|
.filter_map(|e| e.file_name().to_str()?.parse::<i32>().ok())
|
|
{
|
|
// A process can exit mid-walk; skipping it is the correct answer.
|
|
if let Some(stat) = read_stat(pid) {
|
|
by_pgid.entry(stat.pgrp).or_default().push(pid);
|
|
stats.insert(pid, stat);
|
|
}
|
|
}
|
|
Self { stats, by_pgid }
|
|
}
|
|
|
|
/// The process group the terminal considers foreground, per `tpgid`.
|
|
fn foreground_pgid(&self, pane_pid: i32) -> Option<i32> {
|
|
let tpgid = self.stats.get(&pane_pid)?.tpgid;
|
|
// -1 when the process has no controlling terminal.
|
|
(tpgid > 0).then_some(tpgid)
|
|
}
|
|
|
|
fn members(&self, pgid: i32) -> &[i32] {
|
|
self.by_pgid.get(&pgid).map_or(&[], Vec::as_slice)
|
|
}
|
|
|
|
fn state(&self, pid: i32) -> Option<char> {
|
|
self.stats.get(&pid).map(|s| s.state)
|
|
}
|
|
}
|
|
|
|
/// Whether the session on `tty` (e.g. `/dev/pts/3`) is blocked waiting on the
|
|
/// user — the signal for `AwaitingInput`.
|
|
///
|
|
/// True when *any* member of the terminal's foreground group is parked on it: a
|
|
/// group can hold a busy or timer-sleeping stage alongside the one actually
|
|
/// reading, and either can be the reparented one.
|
|
pub fn awaiting_input(pane_pid: i32, tty: &str, groups: &ProcGroups) -> bool {
|
|
let Some(pgid) = groups.foreground_pgid(pane_pid) else {
|
|
return false;
|
|
};
|
|
groups
|
|
.members(pgid)
|
|
.iter()
|
|
.any(|pid| parked_on_tty(*pid, tty, groups))
|
|
}
|
|
|
|
/// Whether `pid` is parked on `tty` rather than busy or sleeping on a timer.
|
|
fn parked_on_tty(pid: i32, tty: &str, groups: &ProcGroups) -> bool {
|
|
// Interruptible sleep is where a blocking read parks; anything else
|
|
// (running, uninterruptible) is busy, not waiting on us.
|
|
if groups.state(pid) != Some('S') {
|
|
return false;
|
|
}
|
|
// A pure timer sleep (`sleep`, `usleep`) also sits in 'S' with the terminal
|
|
// inherited — exclude it so it reads as Idle, not AwaitingInput.
|
|
if is_timer_sleep(pid) {
|
|
return false;
|
|
}
|
|
fd_points_at_tty(pid, tty)
|
|
}
|
|
|
|
/// The fields of `/proc/<pid>/stat` this module needs.
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
struct Stat {
|
|
state: char,
|
|
/// The process group this process belongs to.
|
|
pgrp: i32,
|
|
/// Foreground process group of the controlling terminal.
|
|
tpgid: i32,
|
|
}
|
|
|
|
fn read_stat(pid: i32) -> Option<Stat> {
|
|
parse_stat(&std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?)
|
|
}
|
|
|
|
/// Parse the fields after `comm` from a `/proc/<pid>/stat` line.
|
|
///
|
|
/// The format is `pid (comm) state ppid pgrp session tty_nr tpgid ...`, and
|
|
/// `comm` can itself contain spaces and parens — so everything is indexed from
|
|
/// the *final* `)`, never by splitting the whole line.
|
|
fn parse_stat(stat: &str) -> Option<Stat> {
|
|
let close = stat.rfind(')')?;
|
|
let mut rest = stat[close + 1..].split_whitespace();
|
|
let state = rest.next()?.chars().next()?;
|
|
let _ppid = rest.next()?;
|
|
let pgrp = rest.next()?.parse().ok()?;
|
|
let _session = rest.next()?;
|
|
let _tty_nr = rest.next()?;
|
|
let tpgid = rest.next()?.parse().ok()?;
|
|
Some(Stat { state, pgrp, tpgid })
|
|
}
|
|
|
|
/// Whether `pid`'s `wchan` (the kernel symbol it's blocked in) is a timer
|
|
/// sleep — `hrtimer_nanosleep`, `do_nanosleep`, etc. Those are quiescent but
|
|
/// *not* waiting on the user.
|
|
fn is_timer_sleep(pid: i32) -> bool {
|
|
std::fs::read_to_string(format!("/proc/{pid}/wchan"))
|
|
.map(|w| is_timer_wchan(&w))
|
|
.unwrap_or(false)
|
|
}
|
|
|
|
/// Classify a `wchan` symbol as a pure timer sleep. Kept pure for testing.
|
|
fn is_timer_wchan(wchan: &str) -> bool {
|
|
wchan.contains("nanosleep")
|
|
}
|
|
|
|
/// Whether any of `pid`'s stdio fds (0/1/2) is the terminal `tty`.
|
|
fn fd_points_at_tty(pid: i32, tty: &str) -> bool {
|
|
(0..3).any(|fd| {
|
|
std::fs::read_link(format!("/proc/{pid}/fd/{fd}"))
|
|
.map(|target| target.to_string_lossy() == tty)
|
|
.unwrap_or(false)
|
|
})
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
/// `pid (comm) state ppid pgrp session tty_nr tpgid …`
|
|
fn stat_line(comm: &str, state: char, tpgid: i32) -> String {
|
|
stat_line_pgrp(comm, state, 1234, tpgid)
|
|
}
|
|
|
|
fn stat_line_pgrp(comm: &str, state: char, pgrp: i32, tpgid: i32) -> String {
|
|
format!("1234 ({comm}) {state} 1000 {pgrp} 1234 34816 {tpgid} 4194304 …")
|
|
}
|
|
|
|
#[test]
|
|
fn parse_stat_reads_state_pgrp_and_tpgid() {
|
|
let s = parse_stat(&stat_line_pgrp("bash", 'S', 500, 4321)).unwrap();
|
|
assert_eq!(s.state, 'S');
|
|
assert_eq!(s.pgrp, 500);
|
|
assert_eq!(s.tpgid, 4321);
|
|
|
|
let r = parse_stat(&stat_line_pgrp("cat", 'R', 7, 99)).unwrap();
|
|
assert_eq!(r.state, 'R');
|
|
assert_eq!(r.pgrp, 7);
|
|
assert_eq!(r.tpgid, 99);
|
|
}
|
|
|
|
/// `comm` is attacker-adjacent: it is the process name, it can contain
|
|
/// spaces and parens, and splitting the whole line on whitespace would put
|
|
/// every later field at the wrong index.
|
|
#[test]
|
|
fn parse_stat_indexes_from_the_final_paren() {
|
|
let s = parse_stat(&stat_line_pgrp("weird (name) with spaces", 'D', 42, 777)).unwrap();
|
|
assert_eq!(s.state, 'D');
|
|
assert_eq!(s.pgrp, 42);
|
|
assert_eq!(s.tpgid, 777);
|
|
}
|
|
|
|
#[test]
|
|
fn parse_stat_carries_the_no_terminal_sentinel() {
|
|
// -1 means no controlling terminal; `foreground_pid` rejects it.
|
|
assert_eq!(parse_stat(&stat_line("daemon", 'S', -1)).unwrap().tpgid, -1);
|
|
}
|
|
|
|
#[test]
|
|
fn parse_stat_rejects_garbage() {
|
|
assert!(parse_stat("not a stat line").is_none());
|
|
assert!(parse_stat("123 (comm)").is_none());
|
|
// Truncated before tpgid.
|
|
assert!(parse_stat("123 (comm) S 1 1 1").is_none());
|
|
}
|
|
|
|
#[test]
|
|
fn timer_wchan_excludes_sleep_but_not_a_tty_wait() {
|
|
// `sleep` blocks here — excluded.
|
|
assert!(is_timer_wchan("hrtimer_nanosleep"));
|
|
assert!(is_timer_wchan("do_nanosleep"));
|
|
// A terminal read / poll parks here — not a timer.
|
|
assert!(!is_timer_wchan("wait_woken"));
|
|
assert!(!is_timer_wchan("n_tty_read"));
|
|
assert!(!is_timer_wchan("do_select"));
|
|
assert!(!is_timer_wchan("0"));
|
|
}
|
|
|
|
/// The snapshot indexes by process group, not by parentage — that is the
|
|
/// whole point, since a group member need not be under the pane. Checked
|
|
/// against this process's own group, which certainly has a live member.
|
|
#[test]
|
|
fn snapshot_indexes_this_process_under_its_group() {
|
|
// SAFETY: argument-less query of the caller's own process group.
|
|
let own = unsafe { libc::getpgid(0) };
|
|
assert!(own > 0, "expected a real process group, got {own}");
|
|
|
|
let groups = ProcGroups::snapshot();
|
|
let me = std::process::id() as i32;
|
|
assert!(
|
|
groups.members(own).contains(&me),
|
|
"snapshot missed this process ({me}) in group {own}: {:?}",
|
|
groups.members(own)
|
|
);
|
|
assert!(
|
|
groups.state(me).is_some(),
|
|
"a process in the snapshot must carry its state"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn snapshot_has_no_members_for_a_group_that_cannot_exist() {
|
|
assert!(ProcGroups::snapshot().members(i32::MAX).is_empty());
|
|
}
|
|
|
|
#[test]
|
|
fn a_pid_with_no_controlling_terminal_has_no_foreground_group() {
|
|
let groups = ProcGroups::snapshot();
|
|
assert_eq!(groups.foreground_pgid(i32::MAX), None);
|
|
}
|
|
|
|
#[test]
|
|
fn awaiting_input_is_false_for_nonexistent_pid() {
|
|
// A pid that can't exist → not in the snapshot → false (falls back to Idle).
|
|
assert!(!awaiting_input(
|
|
i32::MAX,
|
|
"/dev/pts/0",
|
|
&ProcGroups::snapshot()
|
|
));
|
|
}
|
|
}
|