Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

8.8 KB
Raw Blame
// SPDX-License-Identifier: MIT
// Copyright (c) 2026 Cua AI, Inc.

//! Linux process enumeration via the /proc filesystem.
//!
//! Each /proc/<pid>/status file contains Name:, Pid:, PPid: etc.
//! /proc/<pid>/cmdline is the full command line (NUL-separated).

use std::fs;
use std::path::Path;

#[derive(Debug, Clone)]
pub struct ProcessInfo {
    pub pid: u32,
    pub name: String,
    pub cmdline: String,
}

fn is_process_live_state(status: &str) -> bool {
    status
        .lines()
        .find_map(|line| {
            line.strip_prefix("State:")
                .and_then(|state| state.trim().chars().next())
        })
        .is_some_and(|state| !matches!(state, 'Z' | 'X'))
}

/// Return whether a PID still represents a live process.
///
/// A zombie remains visible under `/proc` until its parent reaps it, so an
/// existence check alone is not enough for callers that may query AT-SPI or
/// X11 state for the process. Treat zombies and dead processes as gone.
pub fn is_process_live(pid: u32) -> bool {
    let status = match fs::read_to_string(format!("/proc/{pid}/status")) {
        Ok(status) => status,
        Err(_) => return false,
    };

    is_process_live_state(&status)
}

/// Parse the kernel start time (field 22, in clock ticks) from the contents
/// of `/proc/<pid>/stat`.
pub(crate) fn process_start_time_from_stat(stat: &str) -> Option<u64> {
    // `comm` is parenthesized and may contain spaces and closing parentheses.
    // Fields after its final `)` begin with state (field 3); starttime is
    // field 22.
    stat.rsplit_once(')')?
        .1
        .split_whitespace()
        .nth(19)?
        .parse()
        .ok()
}

/// Kernel start-time token for one PID. Unlike the numeric PID alone, this
/// distinguishes a live process from a later process that reused its PID.
pub fn process_instance_id(pid: u32) -> Option<u64> {
    let stat = fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
    process_start_time_from_stat(&stat)
}

/// One process instance as `/proc/<pid>/stat` describes it: its scheduler
/// state and its kernel start time.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct ProcessStat {
    pub state: char,
    pub start_time: u64,
}

/// Parse state (field 3) and start time (field 22) from `/proc/<pid>/stat`.
pub(crate) fn process_stat_from_stat(stat: &str) -> Option<ProcessStat> {
    let state = stat
        .rsplit_once(')')?
        .1
        .split_whitespace()
        .next()?
        .chars()
        .next()?;
    Some(ProcessStat {
        state,
        start_time: process_start_time_from_stat(stat)?,
    })
}

/// Read one pid's [`ProcessStat`]; `Ok(None)` when no such process exists.
pub(crate) fn read_process_stat(pid: u32) -> std::io::Result<Option<ProcessStat>> {
    match fs::read_to_string(format!("/proc/{pid}/stat")) {
        Ok(stat) => process_stat_from_stat(&stat).map(Some).ok_or_else(|| {
            std::io::Error::new(std::io::ErrorKind::InvalidData, "malformed /proc stat")
        }),
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
        Err(error) => Err(error),
    }
}

/// How the process first read as `before` ended, judged from a later read of
/// the same pid, or `None` while that same instance is still alive. A zombie
/// has exited and only waits for its parent to reap it.
pub(crate) fn process_exit_observation(
    before: ProcessStat,
    now: Option<ProcessStat>,
) -> Option<&'static str> {
    match now {
        None => Some("process_absent"),
        Some(now) if now.start_time != before.start_time => Some("pid_reused"),
        Some(now) if matches!(now.state, 'Z' | 'X') => Some("zombie"),
        Some(_) => None,
    }
}

/// Return all running processes by reading /proc/<pid>/status.
pub fn list_processes() -> Vec<ProcessInfo> {
    let mut result = Vec::new();
    let proc_dir = Path::new("/proc");
    let entries = match fs::read_dir(proc_dir) {
        Ok(e) => e,
        Err(_) => return result,
    };

    for entry in entries.flatten() {
        let name = entry.file_name();
        let pid_str = name.to_string_lossy();
        let pid: u32 = match pid_str.parse() {
            Ok(p) => p,
            Err(_) => continue, // Skip non-numeric entries.
        };

        let status_path = proc_dir.join(&*pid_str).join("status");
        let status = match fs::read_to_string(&status_path) {
            Ok(s) => s,
            Err(_) => continue,
        };

        if !is_process_live_state(&status) {
            continue;
        }

        let proc_name = status
            .lines()
            .find(|l| l.starts_with("Name:"))
            .map(|l| l[5..].trim().to_owned())
            .unwrap_or_default();

        let cmdline_path = proc_dir.join(&*pid_str).join("cmdline");
        let cmdline = fs::read(cmdline_path)
            .ok()
            .map(|b| {
                // cmdline is NUL-separated; first entry is argv[0].
                let s = String::from_utf8_lossy(&b);
                s.split('\0').next().unwrap_or("").trim().to_owned()
            })
            .unwrap_or_default();

        result.push(ProcessInfo {
            pid,
            name: proc_name,
            cmdline,
        });
    }

    result.sort_by_key(|p| p.pid);
    result
}

#[cfg(test)]
mod tests {
    #[test]
    fn process_start_time_handles_spaces_in_comm() {
        let mut fields = vec!["S".to_owned()];
        fields.extend((4..=21).map(|field| field.to_string()));
        fields.push("987654".to_owned());
        let fields = fields.join(" ");
        for comm in [
            "fixture with spaces",
            "name with ) parentheses",
            "ends with )",
        ] {
            let stat = format!("42 ({comm}) {fields} 23");
            assert_eq!(
                super::process_start_time_from_stat(&stat),
                Some(987654),
                "{comm}"
            );
        }
        assert_eq!(super::process_start_time_from_stat("bad"), None);
        assert_eq!(
            super::process_start_time_from_stat("42 (short) S 1 2"),
            None
        );
    }

    #[test]
    fn exit_observation_tells_the_same_live_instance_from_its_end() {
        let stat = |state| super::ProcessStat {
            state,
            start_time: 7,
        };
        let parsed = super::process_stat_from_stat(&format!(
            "42 (a) b) S {} 7 23",
            (4..=21)
                .map(|f| f.to_string())
                .collect::<Vec<_>>()
                .join(" ")
        ));
        assert_eq!(parsed, Some(stat('S')));
        assert_eq!(
            super::process_exit_observation(stat('S'), Some(stat('R'))),
            None
        );
        assert_eq!(
            super::process_exit_observation(stat('S'), Some(stat('Z'))),
            Some("zombie")
        );
        assert_eq!(
            super::process_exit_observation(stat('S'), None),
            Some("process_absent")
        );
        let reused = super::ProcessStat {
            state: 'S',
            start_time: 8,
        };
        assert_eq!(
            super::process_exit_observation(stat('S'), Some(reused)),
            Some("pid_reused")
        );
    }

    #[test]
    fn process_states_fail_closed() {
        assert!(super::is_process_live_state(
            "Name:\ttest\nState:\tR (running)\n"
        ));
        assert!(super::is_process_live_state("State:\tS (sleeping)"));
        assert!(!super::is_process_live_state("State:\tZ (zombie)"));
        assert!(!super::is_process_live_state("State:\tX (dead)"));
        assert!(!super::is_process_live_state("Name:\ttest\n"));
        assert!(!super::is_process_live_state("State:\t"));
    }

    #[test]
    fn real_zombie_is_not_live_and_disappears_after_reaping() {
        let child = unsafe { libc::fork() };
        assert!(
            child >= 0,
            "fork failed: {}",
            std::io::Error::last_os_error()
        );
        if child == 0 {
            unsafe { libc::_exit(0) };
        }

        let pid = child as u32;
        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2);
        let mut observed_zombie = false;
        while std::time::Instant::now() < deadline {
            if std::fs::read_to_string(format!("/proc/{pid}/status"))
                .ok()
                .is_some_and(|status| status.contains("State:\tZ"))
            {
                observed_zombie = true;
                break;
            }
            std::thread::sleep(std::time::Duration::from_millis(10));
        }
        let live_while_zombie = super::is_process_live(pid);
        let mut status = 0;
        let reaped = unsafe { libc::waitpid(child, &mut status, 0) };

        assert!(observed_zombie, "child never entered zombie state");
        assert!(!live_while_zombie, "zombie pid was reported live");
        assert_eq!(reaped, child, "failed to reap child");
        assert!(!super::is_process_live(pid), "reaped pid was reported live");
    }
}