Skip to main content

aft_base/
process_identity.rs

1//! OS process start timestamps distinguish reused PIDs from their prior owners.
2
3#[cfg(any(test, feature = "test-support"))]
4use std::collections::HashMap;
5#[cfg(any(target_os = "linux", test))]
6use std::fs;
7#[cfg(any(test, feature = "test-support"))]
8use std::sync::Mutex;
9#[cfg(any(target_os = "linux", any(test, feature = "test-support")))]
10use std::sync::OnceLock;
11
12#[cfg(any(test, feature = "test-support"))]
13static PROCESS_START_TIME_OVERRIDES: OnceLock<Mutex<HashMap<u32, Option<u64>>>> = OnceLock::new();
14
15#[cfg(any(test, feature = "test-support"))]
16pub fn set_process_start_time_for_test(pid: u32, started_at_ms: Option<u64>) {
17    PROCESS_START_TIME_OVERRIDES
18        .get_or_init(|| Mutex::new(HashMap::new()))
19        .lock()
20        .expect("process start override mutex")
21        .insert(pid, started_at_ms);
22}
23
24#[cfg(any(test, feature = "test-support"))]
25pub fn clear_process_start_time_for_test(pid: u32) {
26    if let Some(overrides) = PROCESS_START_TIME_OVERRIDES.get() {
27        overrides
28            .lock()
29            .expect("process start override mutex")
30            .remove(&pid);
31    }
32}
33
34#[cfg(any(test, feature = "test-support"))]
35fn process_start_time_override(pid: u32) -> Option<Option<u64>> {
36    PROCESS_START_TIME_OVERRIDES
37        .get()
38        .and_then(|overrides| overrides.lock().ok()?.get(&pid).copied())
39}
40
41#[cfg(target_os = "linux")]
42/// Return the OS start time for `pid`, in Unix milliseconds, when available.
43pub fn process_start_time_ms(pid: u32) -> Option<u64> {
44    #[cfg(any(test, feature = "test-support"))]
45    if let Some(override_value) = process_start_time_override(pid) {
46        return override_value;
47    }
48
49    let stat = fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
50    let after_comm = stat.rsplit_once(") ")?.1;
51    let fields = after_comm.split_whitespace().collect::<Vec<_>>();
52    let start_ticks = fields.get(19)?.parse::<u64>().ok()?;
53    let boot_time_secs = boot_time_secs()?;
54    let ticks_per_second = unsafe { libc::sysconf(libc::_SC_CLK_TCK) };
55    if ticks_per_second <= 0 {
56        return None;
57    }
58    let ticks_per_second = ticks_per_second as u64;
59    Some(
60        boot_time_secs
61            .saturating_mul(1_000)
62            .saturating_add(start_ticks.saturating_mul(1_000) / ticks_per_second),
63    )
64}
65
66#[cfg(target_os = "linux")]
67fn read_boot_time_secs() -> Option<u64> {
68    fs::read_to_string("/proc/stat")
69        .ok()?
70        .lines()
71        .find_map(|line| line.strip_prefix("btime ")?.parse::<u64>().ok())
72}
73
74#[cfg(target_os = "linux")]
75fn boot_time_secs() -> Option<u64> {
76    static BOOT_TIME_SECS: OnceLock<Option<u64>> = OnceLock::new();
77    cached_boot_time_secs(&BOOT_TIME_SECS, read_boot_time_secs)
78}
79
80/// Read once per process: boot time cannot change while the process runs.
81/// Shared with the platform-independent test that proves the reader runs once.
82#[cfg(any(target_os = "linux", any(test, feature = "test-support")))]
83#[cfg_attr(not(test), allow(dead_code))]
84fn cached_boot_time_secs(
85    cache: &OnceLock<Option<u64>>,
86    reader: impl FnOnce() -> Option<u64>,
87) -> Option<u64> {
88    *cache.get_or_init(reader)
89}
90
91#[cfg(target_os = "macos")]
92/// Return the OS start time for `pid`, in Unix milliseconds, when available.
93pub fn process_start_time_ms(pid: u32) -> Option<u64> {
94    #[cfg(any(test, feature = "test-support"))]
95    if let Some(override_value) = process_start_time_override(pid) {
96        return override_value;
97    }
98
99    crate::fs_lock::macos_kinfo(pid)?
100        .started_at_us
101        .map(|start| start / 1_000)
102}
103
104#[cfg(not(any(target_os = "linux", target_os = "macos")))]
105/// Return the OS start time for `pid`, in Unix milliseconds, when available.
106pub fn process_start_time_ms(pid: u32) -> Option<u64> {
107    #[cfg(any(test, feature = "test-support"))]
108    if let Some(override_value) = process_start_time_override(pid) {
109        return override_value;
110    }
111    #[cfg(windows)]
112    {
113        crate::fs_lock::windows_process_start_time_ms(pid)
114    }
115    #[cfg(not(windows))]
116    {
117        let _ = pid;
118        None
119    }
120}
121
122#[cfg(test)]
123mod tests {
124    use super::*;
125    #[test]
126    fn audit_growth_boot_time_cache_reads_its_source_once() {
127        let directory = tempfile::tempdir().unwrap();
128        let path = directory.path().join("proc-stat-fixture");
129        fs::write(&path, "btime 1234\n").unwrap();
130        let cache = OnceLock::new();
131        let reads = std::cell::Cell::new(0);
132        let first = cached_boot_time_secs(&cache, || {
133            reads.set(reads.get() + 1);
134            fs::read_to_string(&path)
135                .ok()?
136                .lines()
137                .find_map(|line| line.strip_prefix("btime ")?.parse::<u64>().ok())
138        });
139        let second = cached_boot_time_secs(&cache, || {
140            reads.set(reads.get() + 1);
141            fs::read_to_string(&path)
142                .ok()?
143                .lines()
144                .find_map(|line| line.strip_prefix("btime ")?.parse::<u64>().ok())
145        });
146        assert_eq!(first, Some(1234));
147        assert_eq!(second, first);
148        assert_eq!(
149            reads.get(),
150            1,
151            "/proc/stat's equivalent source is read once"
152        );
153    }
154}
155
156/// A failed identity probe is not evidence that a task has stopped.
157#[derive(Debug, Clone, Copy, PartialEq, Eq)]
158pub enum ProcessLiveness {
159    Gone,
160    Alive,
161    Unknown,
162}
163
164pub fn is_process_alive(pid: u32) -> bool {
165    probe_process(pid).1
166}
167
168// The second value is recovery's boolean: OS probe errors remain false.
169// The recorded-process probe keeps a live PID with an unreadable start time alive.
170#[cfg(unix)]
171pub fn probe_process(pid: u32) -> (ProcessLiveness, bool) {
172    let Ok(pid) = i32::try_from(pid) else {
173        return (ProcessLiveness::Unknown, false);
174    };
175    if pid <= 0 {
176        return (ProcessLiveness::Unknown, false);
177    }
178    if unsafe { libc::kill(pid, 0) == 0 } {
179        return (ProcessLiveness::Alive, true);
180    }
181    match std::io::Error::last_os_error().raw_os_error() {
182        Some(libc::EPERM) => (ProcessLiveness::Alive, true),
183        Some(libc::ESRCH) => (ProcessLiveness::Gone, false),
184        _ => (ProcessLiveness::Unknown, false),
185    }
186}
187
188#[cfg(windows)]
189pub fn probe_process(pid: u32) -> (ProcessLiveness, bool) {
190    use std::ffi::c_void;
191
192    type Handle = *mut c_void;
193
194    extern "system" {
195        fn OpenProcess(dwDesiredAccess: u32, bInheritHandle: i32, dwProcessId: u32) -> Handle;
196        fn GetExitCodeProcess(hProcess: Handle, lpExitCode: *mut u32) -> i32;
197        fn CloseHandle(hObject: Handle) -> i32;
198    }
199
200    const FALSE: i32 = 0;
201    const PROCESS_QUERY_LIMITED_INFORMATION: u32 = 0x1000;
202    const STILL_ACTIVE: u32 = 0x103;
203
204    if pid == 0 {
205        return (ProcessLiveness::Unknown, false);
206    }
207
208    unsafe {
209        let handle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid);
210        if handle.is_null() {
211            // Windows reports ERROR_INVALID_PARAMETER for a nonexistent PID.
212            let state = if std::io::Error::last_os_error().raw_os_error() == Some(87) {
213                ProcessLiveness::Gone
214            } else {
215                ProcessLiveness::Unknown
216            };
217            return (state, false);
218        }
219        let mut exit_code = 0;
220        let state = if GetExitCodeProcess(handle, &mut exit_code) == 0 {
221            ProcessLiveness::Unknown
222        } else if exit_code == STILL_ACTIVE {
223            ProcessLiveness::Alive
224        } else {
225            ProcessLiveness::Gone
226        };
227        let _ = CloseHandle(handle);
228        (state, state == ProcessLiveness::Alive)
229    }
230}
231
232#[cfg(test)]
233mod liveness_tests {
234    use super::is_process_alive;
235
236    #[test]
237    fn is_process_alive_returns_true_for_self() {
238        assert!(is_process_alive(std::process::id()));
239    }
240
241    #[test]
242    fn is_process_alive_returns_false_for_dead_pid() {
243        #[cfg(unix)]
244        let mut child = std::process::Command::new("/bin/sh")
245            .args(["-c", "true"])
246            .spawn()
247            .expect("spawn true");
248
249        #[cfg(windows)]
250        let mut child = std::process::Command::new("cmd.exe")
251            .args(["/D", "/C", "exit 0"])
252            .spawn()
253            .expect("spawn cmd");
254
255        let pid = child.id();
256        child.wait().expect("wait for child");
257
258        assert!(!is_process_alive(pid));
259    }
260}