Skip to main content

agentmux_srv_core/backend/mem_census/
process.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! What the operating system says about this process: memory, threads, handles.
5
6/// This process's own figures. A field the platform does not give is `None`.
7#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize)]
8pub struct ProcessFigures {
9    /// Resident memory: the working set on Windows.
10    pub resident_bytes: u64,
11    /// Private committed memory. Windows only: elsewhere the same call answers with the size of the
12    /// address space, which says nothing about use.
13    pub private_bytes: Option<u64>,
14    pub threads: Option<u32>,
15    /// Open handles on Windows, open file descriptors on Linux.
16    pub handles: Option<u32>,
17}
18
19/// Read them now. One targeted process refresh, and on Windows one process snapshot for the thread
20/// count: a few milliseconds, for a caller that runs every few minutes.
21pub fn own() -> ProcessFigures {
22    let pid = sysinfo::Pid::from(std::process::id() as usize);
23    let mut sys = sysinfo::System::new();
24    sys.refresh_processes_specifics(
25        sysinfo::ProcessesToUpdate::Some(&[pid]),
26        false,
27        sysinfo::ProcessRefreshKind::nothing().with_memory(),
28    );
29    let (resident, committed) = sys.process(pid).map(|p| (p.memory(), p.virtual_memory())).unwrap_or((0, 0));
30    ProcessFigures {
31        resident_bytes: resident,
32        private_bytes: cfg!(target_os = "windows").then_some(committed),
33        threads: thread_count(),
34        handles: handle_count(),
35    }
36}
37
38#[cfg(target_os = "windows")]
39fn handle_count() -> Option<u32> {
40    crate::backend::sysinfo::process_handle_count(std::process::id())
41}
42
43#[cfg(target_os = "linux")]
44fn handle_count() -> Option<u32> {
45    std::fs::read_dir("/proc/self/fd").ok().map(|entries| entries.count() as u32)
46}
47
48#[cfg(not(any(target_os = "windows", target_os = "linux")))]
49fn handle_count() -> Option<u32> {
50    None
51}
52
53#[cfg(target_os = "windows")]
54fn thread_count() -> Option<u32> {
55    use windows_sys::Win32::Foundation::{CloseHandle, INVALID_HANDLE_VALUE};
56    use windows_sys::Win32::System::Diagnostics::ToolHelp::{
57        CreateToolhelp32Snapshot, Process32FirstW, Process32NextW, PROCESSENTRY32W, TH32CS_SNAPPROCESS,
58    };
59    let me = std::process::id();
60    // SAFETY: the snapshot handle is checked before use and closed on every path; the entry is
61    // zeroed with its size set before the first call, as the API requires.
62    unsafe {
63        let snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
64        if snapshot == INVALID_HANDLE_VALUE {
65            return None;
66        }
67        let mut entry: PROCESSENTRY32W = std::mem::zeroed();
68        entry.dwSize = std::mem::size_of::<PROCESSENTRY32W>() as u32;
69        let mut threads = None;
70        let mut more = Process32FirstW(snapshot, &mut entry);
71        while more != 0 {
72            if entry.th32ProcessID == me {
73                threads = Some(entry.cntThreads);
74                break;
75            }
76            more = Process32NextW(snapshot, &mut entry);
77        }
78        CloseHandle(snapshot);
79        threads
80    }
81}
82
83#[cfg(target_os = "linux")]
84fn thread_count() -> Option<u32> {
85    let status = std::fs::read_to_string("/proc/self/status").ok()?;
86    status.lines().find_map(|line| line.strip_prefix("Threads:"))?.trim().parse().ok()
87}
88
89#[cfg(not(any(target_os = "windows", target_os = "linux")))]
90fn thread_count() -> Option<u32> {
91    None
92}
93
94#[cfg(test)]
95mod tests {
96    use super::*;
97
98    #[test]
99    fn this_process_has_memory_and_where_the_platform_says_so_threads_and_handles() {
100        let figures = own();
101        assert!(figures.resident_bytes > 0, "{figures:?}");
102        assert_eq!(figures.private_bytes.is_some(), cfg!(target_os = "windows"));
103        if cfg!(any(target_os = "windows", target_os = "linux")) {
104            assert!(figures.threads.is_some_and(|n| n >= 1), "{figures:?}");
105            assert!(figures.handles.is_some_and(|n| n >= 1), "{figures:?}");
106        }
107    }
108}