Skip to main content

subc_os/
lib.rs

1//! Operating-system primitives the subc daemon needs and cannot reach without
2//! unsafe code, each behind a small safe API.
3//!
4//! The daemon crates forbid unsafe code. This crate is the one deliberate
5//! exception (like `subc-uptime` and `subc-cgroup`): each `unsafe` block here is
6//! a foreign call, or a read of a buffer such a call returned, with its
7//! preconditions stated beside it, and nothing unsafe is exported.
8//!
9//! Its central question: is the process now holding pid N the same
10//! process the daemon spawned earlier? A pid alone cannot say, because the
11//! kernel reuses pids once a process has been reaped. [`Process`] reads the two
12//! facts that tell processes apart, the kernel's start time for the pid and the
13//! file identity (device and inode) of the executable image it runs, and sends
14//! signals to it.
15//!
16//! Sources, per platform:
17//!
18//! - Linux: the start time is field 22 of `/proc/<pid>/stat` (clock ticks since
19//!   boot), and the executable is `stat` through `/proc/<pid>/exe`, which
20//!   resolves to the running image even if its file has since been replaced or
21//!   deleted. A pidfd is opened before either is read and signals go through it
22//!   (`pidfd_send_signal`), so the process that was checked is the process that
23//!   is signalled. No unsafe code is needed: rustix wraps both calls.
24//! - macOS: the start time is `kp_proc.p_starttime` from `sysctl`
25//!   `KERN_PROC_PID` (microseconds since the epoch), and the executable is the
26//!   path `proc_pidpath` reports, then `stat` on that path. These two calls are
27//!   unsafe. macOS has no pidfd, so a signal is a plain
28//!   `kill` sent right after the checks; see [`Process::signal`].
29//! - Windows: creation time and forced stops use one retained process handle.
30//!   `ExecutableCapture` pins the resolved executable until a suspended spawn
31//!   binds its volume and 128-bit file ID to that handle and creation time.
32//! - Anywhere else: [`Process::open`] reports [`std::io::ErrorKind::Unsupported`].
33//!
34//! For persisted PID owners, [`process_identity`] reads versioned kernel start
35//! identities and distinguishes alive, dead and unknown without spawning a
36//! process. Its foreign calls are signal-zero `kill` on Unix and `proc_pidinfo`
37//! on macOS. Only dead owners may be reclaimed; unknown owners stay protected.
38//!
39//! It also reads how much memory and CPU time one process is using, for
40//! reporting only; see [`resource_usage`]. On Linux that is procfs again; on
41//! macOS it is `proc_pid_rusage`, plus `mach_timebase_info` to convert its CPU
42//! times to nanoseconds, the other two unsafe calls in the crate.
43//!
44//! For the machine as a whole, [`host`] reads total and available memory, the
45//! load averages and the space on a filesystem, again for reporting only.
46//!
47//! It also resolves per-user locations from account records rather than the
48//! environment: the password-database home and effective uid on Unix, Darwin's
49//! per-user temporary directory on macOS, and the recorded profile folder on
50//! Windows (`profile_dir`).
51//!
52//! For the peer of an accepted local-endpoint connection (a Unix-domain
53//! socket, or a named-pipe client on Windows), [`local_peer`] reads the
54//! kernel's record of the connecting process: its user, pid and executable,
55//! and on macOS its code-signing identifier.
56//!
57//! And it carries the launch nonce from the daemon to each module it spawns
58//! over an inherited Unix pipe or a PID-authenticated Windows named pipe:
59//! [`launch_nonce`] is the one cached reader every module uses. Windows keeps
60//! an environment copy for old Windows readers until live source reports show
61//! every module consuming the named pipe.
62
63#![deny(unsafe_code)]
64
65#[cfg(target_os = "macos")]
66mod darwin_user_temp;
67#[cfg(target_os = "macos")]
68pub use darwin_user_temp::darwin_user_temp_dir;
69
70#[cfg(windows)]
71mod profile;
72#[cfg(windows)]
73pub use profile::profile_dir;
74
75#[cfg(unix)]
76mod user_home;
77#[cfg(unix)]
78pub use user_home::{effective_uid, real_user_home_dir};
79
80#[cfg(unix)]
81pub mod admission_gate;
82pub mod boot_id;
83#[cfg(unix)]
84pub mod child_exit;
85pub mod child_spawn;
86#[cfg(target_os = "macos")]
87pub mod code_signature;
88pub mod config_keychain;
89mod durable_replace;
90#[cfg(any(unix, windows))]
91mod retained_file;
92#[cfg(any(target_os = "linux", target_os = "macos", windows))]
93mod retained_replace;
94#[cfg(windows)]
95pub use durable_replace::durable_move_to_new_name;
96#[cfg(feature = "test-support")]
97pub use durable_replace::durable_replace_with_rename_hook;
98pub use durable_replace::{durable_replace, DurableReplaceError};
99#[cfg(any(unix, windows))]
100pub use retained_file::{
101    open_directory_nofollow_all, open_regular_nofollow, open_regular_nofollow_all,
102    retained_file_identity, OpenRegularError, RetainedFileIdentity,
103};
104#[cfg(windows)]
105pub use retained_file::{retained_file_index, WindowsFileIndexIdentity};
106#[cfg(any(target_os = "linux", target_os = "macos", windows))]
107pub use retained_replace::{
108    create_directory_nofollow_at, move_file_aside_nofollow_at, move_file_to_noreplace_at,
109    open_directory_nofollow_at, open_or_create_private_directory_at,
110    open_single_link_file_nofollow_at, probe_retained_directory_write,
111    probe_retained_regular_file_at, retained_directory_path, retained_regular_file_at,
112    OpenRetainedError, RetainedMovedFile, RetainedTempFile,
113};
114#[cfg(all(unix, feature = "test-support"))]
115pub mod fork_exec_test;
116pub mod host;
117pub mod launch_nonce;
118pub mod local_peer;
119#[cfg(windows)]
120mod loopback_connect;
121#[cfg(windows)]
122pub use loopback_connect::connect_loopback;
123pub mod named_pipe;
124pub mod privacy_identity;
125mod private_directory;
126#[cfg(unix)]
127pub mod process_group;
128pub mod process_identity;
129pub use private_directory::create_private_directory_exclusive;
130pub mod registration_channel;
131pub mod script_pipe;
132pub mod socket_peer;
133#[cfg(windows)]
134pub mod user_path;
135#[cfg_attr(not(windows), path = "windows_acl_noop.rs")]
136pub mod windows_acl;
137#[cfg(unix)]
138pub use launch_nonce::LaunchNonceHandoff;
139pub use launch_nonce::{
140    launch_nonce, LaunchNonce, LaunchNonceError, LaunchNonceSource, LAUNCH_NONCE_ENV,
141    LAUNCH_NONCE_FD, LAUNCH_NONCE_FD_ENV, LAUNCH_NONCE_PIPE_ENV, LAUNCH_NONCE_PIPE_FALLBACK_ENV,
142};
143
144#[cfg(windows)]
145pub use launch_nonce::{LaunchNoncePipeDelivery, LaunchNoncePipeHandoff};
146
147pub use registration_channel::{
148    registration_refusal, supervised, take_registration_channel, RegistrationChannel,
149    RegistrationChannelError, RegistrationRefusal,
150};
151
152#[cfg(target_os = "linux")]
153mod linux;
154#[cfg(target_os = "macos")]
155mod macos;
156
157#[cfg(target_os = "macos")]
158pub use macos::owned_child_start_time;
159#[cfg(windows)]
160mod windows;
161#[cfg(all(test, windows))]
162mod windows_tests;
163#[cfg(windows)]
164pub use windows::{
165    ExecutableCapture, ImageAgreement, ImageUnavailable, SpawnedImage, WindowsFileIdentity,
166};
167
168#[cfg(target_os = "linux")]
169use linux as platform;
170#[cfg(target_os = "macos")]
171use macos as platform;
172
173use std::{io, path::Path};
174
175/// True where [`Process`] can identify and stop a process by pid.
176pub const PROCESS_IDENTITY_SUPPORTED: bool =
177    cfg!(any(target_os = "linux", target_os = "macos", windows));
178
179/// Device and inode of a file: which file, independent of the name used to
180/// reach it.
181#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
182pub struct FileIdentity {
183    pub device: u64,
184    pub inode: u64,
185}
186
187/// The device and inode of the file at `path`, following symlinks. `None` if it
188/// cannot be read or the platform has no inode numbers.
189pub fn file_identity(path: &Path) -> Option<FileIdentity> {
190    #[cfg(unix)]
191    {
192        use std::os::unix::fs::MetadataExt;
193
194        std::fs::metadata(path).ok().map(|metadata| FileIdentity {
195            device: metadata.dev(),
196            inode: metadata.ino(),
197        })
198    }
199    #[cfg(not(unix))]
200    {
201        let _ = path;
202        None
203    }
204}
205
206/// What a live process looks like right now.
207#[derive(Debug, Clone, Copy, PartialEq, Eq)]
208pub struct Observation {
209    /// The kernel's start time for the process. Opaque: compare it only with a
210    /// value read on the same host by this crate. Linux counts clock ticks since
211    /// boot; macOS counts microseconds since the epoch; Windows counts 100 ns
212    /// intervals since the Windows epoch.
213    pub start_time: u64,
214    /// The file the process is executing, or `None` if it could not be read
215    /// (for example, a process owned by another user).
216    /// Windows uses the full file ID in `SpawnedImage` instead of a Unix inode;
217    /// this field is always `None` there.
218    pub executable: Option<FileIdentity>,
219}
220
221/// Whether the running executable's identity could be read. Permission denial
222/// is distinct on Linux because a non-dumpable process hides its executable
223/// while leaving its start time readable.
224#[derive(Debug, Clone, Copy, PartialEq, Eq)]
225pub enum ExecutableAccess {
226    Readable,
227    PermissionDenied,
228    Unavailable,
229}
230
231/// A signal [`Process::signal`] can send.
232#[derive(Debug, Clone, Copy, PartialEq, Eq)]
233pub enum Signal {
234    /// SIGTERM: a request to exit, which the process may handle or ignore.
235    Terminate,
236    /// SIGKILL: ends the process; it cannot be handled or ignored.
237    Kill,
238}
239
240/// The kernel start time of the process holding `pid`, or `None` if there is
241/// none, it has already exited (a zombie waiting to be reaped counts as exited),
242/// or the platform has no source.
243pub fn start_time(pid: u32) -> Option<u64> {
244    #[cfg(any(target_os = "linux", target_os = "macos"))]
245    {
246        platform::start_time(pid)
247    }
248    #[cfg(windows)]
249    {
250        Process::open(pid)
251            .ok()??
252            .observe()
253            .map(|observation| observation.start_time)
254    }
255    #[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
256    {
257        let _ = pid;
258        None
259    }
260}
261
262/// Snapshot probes distinguish an exited process from a failed identity read.
263#[derive(Clone, Copy, Debug, PartialEq, Eq)]
264pub(crate) enum IdentityRead {
265    Alive(u64),
266    #[cfg_attr(windows, allow(dead_code))]
267    // Windows retains its existing unknown-on-observe-failure policy.
268    Gone,
269    Unknown,
270}
271
272#[cfg(all(test, any(target_os = "linux", target_os = "macos")))]
273mod identity_read_tests {
274    use super::*;
275
276    #[test]
277    fn identity_probe_distinguishes_alive_gone_and_invalid() {
278        let mut child = std::process::Command::new("/bin/sh")
279            .args(["-c", "exit 0"])
280            .spawn()
281            .unwrap();
282        let pid = child.id();
283        let until = std::time::Instant::now() + std::time::Duration::from_secs(5);
284        while read_identity(pid) != IdentityRead::Gone {
285            assert!(
286                std::time::Instant::now() < until,
287                "an exited owned child must become gone before reaping"
288            );
289            std::thread::yield_now();
290        }
291        child.wait().unwrap();
292        assert_eq!(
293            read_identity(pid),
294            IdentityRead::Gone,
295            "a missing owned PID is gone"
296        );
297        assert_eq!(read_identity(0), IdentityRead::Unknown);
298        assert!(matches!(
299            read_identity(std::process::id()),
300            IdentityRead::Alive(_)
301        ));
302    }
303}
304
305#[cfg(not(windows))]
306fn read_identity(pid: u32) -> IdentityRead {
307    #[cfg(any(target_os = "linux", target_os = "macos"))]
308    {
309        platform::read_identity(pid)
310    }
311    #[cfg(not(any(target_os = "linux", target_os = "macos")))]
312    {
313        start_time(pid).map_or(IdentityRead::Unknown, IdentityRead::Alive)
314    }
315}
316
317mod process_tree;
318pub use process_tree::{BirthBaseline, ProcessGroup, ProcessMember, ProcessTable, TreeUsage};
319
320/// Kernel process creation time, in milliseconds since the Unix epoch.
321///
322/// Linux combines procfs boot time (whole seconds) with start ticks (usually
323/// 10 ms precision). macOS truncates microseconds and Windows truncates 100 ns
324/// FILETIME ticks to milliseconds. Use [`process_start_time_precision_ms`] when
325/// comparing a declaration made by another process; this is not a unique ID
326/// for two starts within the kernel's timestamp resolution.
327pub fn process_start_time_ms(pid: u32) -> Option<u64> {
328    start_time_ms_from_native(start_time(pid)?)
329}
330
331fn start_time_ms_from_native(raw: u64) -> Option<u64> {
332    #[cfg(target_os = "linux")]
333    {
334        linux_start_time_ms(raw, || std::fs::read_to_string("/proc/stat").ok())
335    }
336    #[cfg(target_os = "macos")]
337    {
338        Some(raw / 1_000)
339    }
340    #[cfg(windows)]
341    {
342        (raw / 10_000).checked_sub(11_644_473_600_000)
343    }
344    #[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
345    {
346        let _ = raw;
347        None
348    }
349}
350
351#[cfg(target_os = "linux")]
352fn linux_start_time_ms(raw: u64, read_boot: impl FnOnce() -> Option<String>) -> Option<u64> {
353    // Realtime clock steps change the boot-time value in the `btime` line.
354    // The daemon and a newly started client
355    // must both convert against the current value, not a per-process cache.
356    let boot = read_boot()?
357        .lines()
358        .find_map(|line| line.strip_prefix("btime ")?.parse::<u64>().ok())?;
359    boot.checked_mul(1_000)?
360        .checked_add(raw.checked_mul(1_000)? / rustix::param::clock_ticks_per_second().max(1))
361}
362
363#[cfg(all(test, target_os = "linux"))]
364#[test]
365fn linux_start_identity_uses_fresh_boot_time_after_clock_step() {
366    let before = linux_start_time_ms(100, || Some("btime 1000\n".into())).unwrap();
367    let after = linux_start_time_ms(100, || Some("btime 1002\n".into())).unwrap();
368    assert_eq!(after - before, 2_000);
369}
370
371/// Resolution used by [`process_start_time_ms`], rounded up to milliseconds.
372pub fn process_start_time_precision_ms() -> u64 {
373    #[cfg(target_os = "linux")]
374    {
375        1_000_u64.div_ceil(rustix::param::clock_ticks_per_second().max(1))
376    }
377    #[cfg(not(target_os = "linux"))]
378    {
379        1
380    }
381}
382
383/// The parent pid reported by the kernel, or `None` when it cannot be read.
384/// On Windows a reused parent pid (created after the child) is rejected.
385pub fn parent_pid(pid: u32) -> Option<u32> {
386    #[cfg(any(target_os = "linux", target_os = "macos"))]
387    {
388        platform::parent_pid(pid)
389    }
390    #[cfg(windows)]
391    {
392        windows::parent_pid(pid)
393    }
394    #[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
395    {
396        let _ = pid;
397        None
398    }
399}
400
401/// True where [`resource_usage`] can read a live process. Elsewhere it always
402/// answers `None`, and a caller can use this to say "not supported here"
403/// rather than "could not read".
404pub const RESOURCE_USAGE_SUPPORTED: bool =
405    cfg!(any(target_os = "linux", target_os = "macos", windows));
406
407/// What [`ResourceUsage::memory_bytes`] measures. The platforms offer
408/// different figures, and they are not interchangeable.
409#[derive(Debug, Clone, Copy, PartialEq, Eq)]
410pub enum MemoryKind {
411    /// macOS `phys_footprint`: the memory the kernel charges to the process
412    /// (dirty and compressed pages, among others), which is also what jetsam
413    /// acts on. Pages an allocator has released with `MADV_FREE` do not count.
414    PhysFootprint,
415    /// Linux `VmRSS`: pages of the process resident in RAM, including shared
416    /// file-backed pages. Swapped-out pages are not included; see
417    /// [`ResourceUsage::swap_bytes`].
418    ResidentSet,
419    /// Windows `WorkingSetSize`: pageable memory currently resident in RAM,
420    /// including shared pages. This is not Unix RSS or private committed memory.
421    WindowsWorkingSet,
422}
423
424/// One reading of a process's memory and cumulative CPU time.
425///
426/// It covers the process named by the pid alone: its threads are included,
427/// processes it has started are not.
428#[derive(Debug, Clone, Copy, PartialEq, Eq)]
429pub struct ResourceUsage {
430    /// Memory in bytes, measured as [`Self::memory_kind`] says.
431    pub memory_bytes: u64,
432    pub memory_kind: MemoryKind,
433    /// Bytes swapped out (Linux `VmSwap`). `None` where the platform does not
434    /// report it for a single process, which is not the same as zero.
435    pub swap_bytes: Option<u64>,
436    /// CPU time spent in user mode since the process started.
437    pub cpu_user: std::time::Duration,
438    /// CPU time spent in the kernel on the process's behalf since it started.
439    pub cpu_system: std::time::Duration,
440}
441
442/// Memory and cumulative CPU time of the process holding `pid`, read now.
443///
444/// `None` when there is no such process, it has exited (a zombie awaiting its
445/// reap counts as exited), it cannot be read (for example, another user's
446/// process on macOS), or the platform has no source
447/// (see [`RESOURCE_USAGE_SUPPORTED`]). Never a reading of zeros in place of
448/// one of those.
449///
450/// Like any pid-based read, this describes whatever process holds `pid` now;
451/// a caller that needs it to be a particular process should confirm that
452/// process's [`start_time`] around the call.
453pub fn resource_usage(pid: u32) -> Option<ResourceUsage> {
454    #[cfg(any(target_os = "linux", target_os = "macos"))]
455    {
456        platform::resource_usage(pid)
457    }
458    #[cfg(windows)]
459    {
460        Process::open(pid).ok()??.resource_usage()
461    }
462    #[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
463    {
464        let _ = pid;
465        None
466    }
467}
468
469/// A handle on the process holding one pid at the moment it was opened.
470#[derive(Debug)]
471pub struct Process {
472    pid: u32,
473    #[cfg(target_os = "linux")]
474    pidfd: Option<std::os::fd::OwnedFd>,
475    #[cfg(windows)]
476    handle: std::os::windows::io::OwnedHandle,
477}
478
479impl Process {
480    /// Open a handle on the process now holding `pid`.
481    ///
482    /// `Ok(None)` means no process holds that pid (on macOS, also a zombie
483    /// awaiting its reap; on Linux a zombie opens, and [`Self::observe`] then
484    /// reports it as exited). On Linux this opens a pidfd,
485    /// which from then on refers to this exact process even if it exits and the
486    /// pid is reused; when the kernel cannot open one (older than 5.3, or a
487    /// seccomp policy refusing the call) the handle falls back to the pid, as
488    /// on macOS.
489    pub fn open(pid: u32) -> io::Result<Option<Self>> {
490        #[cfg(target_os = "linux")]
491        {
492            linux::open(pid).map(|opened| opened.map(|pidfd| Self { pid, pidfd }))
493        }
494        #[cfg(target_os = "macos")]
495        {
496            Ok(platform::exists(pid).then_some(Self { pid }))
497        }
498        #[cfg(windows)]
499        {
500            windows::open(pid).map(|opened| opened.map(|handle| Self { pid, handle }))
501        }
502        #[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
503        {
504            let _ = pid;
505            Err(io::Error::new(
506                io::ErrorKind::Unsupported,
507                "process identity is not available on this platform",
508            ))
509        }
510    }
511
512    pub fn pid(&self) -> u32 {
513        self.pid
514    }
515
516    /// True when signals go through a pidfd, so they cannot reach a different
517    /// process that has since reused this pid.
518    pub fn signals_through_pidfd(&self) -> bool {
519        #[cfg(target_os = "linux")]
520        {
521            self.pidfd.is_some()
522        }
523        #[cfg(not(target_os = "linux"))]
524        {
525            false
526        }
527    }
528
529    /// The process's start time and executable, or `None` when it has exited
530    /// (including as a zombie not yet reaped) or cannot be observed. On Linux,
531    /// [`Self::is_alive_but_unobservable`] distinguishes a hidden procfs entry.
532    pub fn observe(&self) -> Option<Observation> {
533        self.observe_with_executable_access()
534            .map(|(observed, _)| observed)
535    }
536
537    /// Whether Linux hides the entire procfs entry while the process still
538    /// exists. This proves existence, not identity, and never authorizes a signal.
539    /// Other platforms return false without changing their observation behavior.
540    pub fn is_alive_but_unobservable(&self) -> bool {
541        #[cfg(target_os = "linux")]
542        {
543            linux::alive_but_unobservable(self.pid, self.pidfd.as_ref())
544        }
545        #[cfg(not(target_os = "linux"))]
546        {
547            false
548        }
549    }
550
551    /// Observe the process and distinguish Linux executable permission denial
552    /// from other failures, without changing the legacy observation's fields.
553    /// Other platforms retain their existing readable/unavailable distinction.
554    pub fn observe_with_executable_access(&self) -> Option<(Observation, ExecutableAccess)> {
555        #[cfg(any(target_os = "linux", target_os = "macos"))]
556        {
557            #[cfg(target_os = "linux")]
558            if !linux::pidfd_alive(self.pidfd.as_ref()) {
559                return None;
560            }
561            let start_time = platform::start_time(self.pid)?;
562            #[cfg(target_os = "linux")]
563            let (executable, access) = match linux::executable_identity(self.pid) {
564                Ok(identity) => (Some(identity), ExecutableAccess::Readable),
565                Err(error) if error.kind() == io::ErrorKind::PermissionDenied => {
566                    (None, ExecutableAccess::PermissionDenied)
567                }
568                Err(_) => (None, ExecutableAccess::Unavailable),
569            };
570            #[cfg(target_os = "macos")]
571            let executable = macos::executable_identity(self.pid);
572            #[cfg(target_os = "macos")]
573            let access = if executable.is_some() {
574                ExecutableAccess::Readable
575            } else {
576                ExecutableAccess::Unavailable
577            };
578            Some((
579                Observation {
580                    start_time,
581                    executable,
582                },
583                access,
584            ))
585        }
586        #[cfg(windows)]
587        {
588            windows::observe(self).map(|observed| (observed, ExecutableAccess::Unavailable))
589        }
590        #[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
591        {
592            None
593        }
594    }
595
596    /// Wait on the retained Windows handle. `Ok(false)` means the bound elapsed,
597    /// not that a reused PID was observed.
598    #[cfg(windows)]
599    pub fn wait_for_exit(&self, timeout: std::time::Duration) -> io::Result<bool> {
600        windows::wait(self, timeout)
601    }
602
603    /// Force the confirmed Windows process to stop, then wait on the same handle.
604    /// This is not a graceful termination signal. A different creation time
605    /// refuses before any action; `Ok(false)` means the wait bound elapsed.
606    #[cfg(windows)]
607    pub fn force_stop(
608        &self,
609        expected_start_time: u64,
610        timeout: std::time::Duration,
611    ) -> io::Result<bool> {
612        windows::force_stop(self, expected_start_time, timeout)
613    }
614
615    /// Request forced termination on the retained Windows handle with a chosen
616    /// exit code. `Ok(true)` means the termination request was accepted;
617    /// `Ok(false)` means the process had already exited. This does not wait for
618    /// exit: call [`Self::wait_for_exit`] before treating the process as dead.
619    #[cfg(windows)]
620    pub fn terminate_with_exit_code(&self, exit_code: u32) -> io::Result<bool> {
621        windows::terminate_with_exit_code(self, exit_code)
622    }
623
624    /// Windows resources read through the retained handle, not by reopening its PID.
625    #[cfg(windows)]
626    pub fn resource_usage(&self) -> Option<ResourceUsage> {
627        windows::resource_usage(self)
628    }
629
630    /// Cumulative CPU read from the retained Windows process handle, including
631    /// after exit. Unlike working-set observations, final CPU remains available.
632    #[cfg(windows)]
633    pub fn cumulative_cpu_ms(&self) -> Option<u64> {
634        windows::cumulative_cpu_ms(self)
635    }
636
637    /// Send `signal` to the process.
638    ///
639    /// With a pidfd the signal can only reach the process this handle was
640    /// opened on: if that process has exited, the call fails with `ESRCH` even
641    /// if the pid has been reused. Without one (macOS, or a Linux kernel with no
642    /// pidfd) the signal goes to whatever holds the pid now, so callers should
643    /// [`Self::observe`] immediately before signalling. What remains is the
644    /// time between that check and this call; for a different process to be
645    /// hit, the checked one must exit, be reaped, and have its pid handed to a
646    /// new process inside that window, and both kernels hand out pids in
647    /// increasing order, so a reuse needs the whole pid space to wrap first.
648    ///
649    /// `Ok(false)` means the process had already exited (`ESRCH`).
650    pub fn signal(&self, signal: Signal) -> io::Result<bool> {
651        #[cfg(any(target_os = "linux", target_os = "macos"))]
652        {
653            #[cfg(target_os = "linux")]
654            let result = linux::signal(self.pid, self.pidfd.as_ref(), signal);
655            #[cfg(target_os = "macos")]
656            let result = macos::signal(self.pid, signal);
657            match result {
658                Ok(()) => Ok(true),
659                Err(rustix::io::Errno::SRCH) => Ok(false),
660                Err(error) => Err(error.into()),
661            }
662        }
663        #[cfg(not(any(target_os = "linux", target_os = "macos")))]
664        {
665            let _ = signal;
666            Err(io::Error::new(
667                io::ErrorKind::Unsupported,
668                "process signalling is not available on this platform",
669            ))
670        }
671    }
672}
673
674#[cfg(all(test, any(target_os = "linux", target_os = "macos")))]
675mod tests {
676    use std::{
677        io::Read,
678        process::{Child, Command, Stdio},
679        time::{Duration, Instant},
680    };
681
682    use super::*;
683
684    fn spawn_sleep() -> Child {
685        Command::new("sleep")
686            .arg("60")
687            .spawn()
688            .expect("spawn sleep")
689    }
690
691    /// The executable a spawned `sleep` runs, resolved the way `Command` found it.
692    fn sleep_identity() -> FileIdentity {
693        let path = ["/bin/sleep", "/usr/bin/sleep"]
694            .into_iter()
695            .find(|path| Path::new(path).exists())
696            .expect("sleep is installed");
697        file_identity(Path::new(path)).expect("stat sleep")
698    }
699
700    /// Right after `spawn` returns the child may not have finished exec yet,
701    /// and until then it still runs the test binary's image.
702    fn wait_for_executable(process: &Process, expected: FileIdentity) -> Observation {
703        let deadline = Instant::now() + Duration::from_secs(5);
704        loop {
705            let observation = process.observe().expect("child is alive");
706            if observation.executable == Some(expected) || Instant::now() > deadline {
707                return observation;
708            }
709            std::thread::sleep(Duration::from_millis(10));
710        }
711    }
712
713    #[test]
714    fn own_process_is_observable_with_its_own_image() {
715        let process = Process::open(std::process::id())
716            .expect("open own process")
717            .expect("own process exists");
718        let observation = process.observe().expect("own process is alive");
719        let own_image = file_identity(&std::env::current_exe().unwrap()).unwrap();
720        assert_eq!(observation.executable, Some(own_image));
721        assert_eq!(start_time(std::process::id()), Some(observation.start_time));
722    }
723
724    #[test]
725    fn child_start_time_is_stable_and_differs_from_ours() {
726        let mut child = spawn_sleep();
727        let pid = child.id();
728        let process = Process::open(pid).unwrap().unwrap();
729        let observation = wait_for_executable(&process, sleep_identity());
730        assert_eq!(observation.executable, Some(sleep_identity()));
731        assert_eq!(start_time(pid), Some(observation.start_time));
732        child.kill().unwrap();
733        child.wait().unwrap();
734    }
735
736    #[test]
737    fn a_signalled_and_unreaped_child_reads_as_exited() {
738        let mut child = spawn_sleep();
739        let process = Process::open(child.id()).unwrap().unwrap();
740        assert!(process.signal(Signal::Terminate).unwrap());
741        let deadline = Instant::now() + Duration::from_secs(5);
742        while process.observe().is_some() {
743            assert!(Instant::now() < deadline, "child still observed as alive");
744            std::thread::sleep(Duration::from_millis(10));
745        }
746        // Not yet reaped: the pid is still a zombie here, and still reads as exited.
747        assert_eq!(start_time(child.id()), None);
748        child.wait().unwrap();
749    }
750
751    #[test]
752    fn a_reaped_child_cannot_be_opened_or_observed() {
753        let mut child = spawn_sleep();
754        let pid = child.id();
755        child.kill().unwrap();
756        child.wait().unwrap();
757        // The pid could in principle be reused by now; either way it is not the child.
758        if let Some(process) = Process::open(pid).unwrap() {
759            if let Some(observation) = process.observe() {
760                assert_ne!(observation.executable, Some(sleep_identity()));
761            }
762        }
763    }
764
765    /// The macOS fields are read at fixed offsets, so check the value is a
766    /// plausible start time and not some other field: our own process started
767    /// in the past, and not long ago.
768    #[cfg(target_os = "macos")]
769    #[test]
770    fn macos_start_time_is_microseconds_since_the_epoch() {
771        let now = std::time::SystemTime::now()
772            .duration_since(std::time::UNIX_EPOCH)
773            .unwrap()
774            .as_micros() as u64;
775        let started = start_time(std::process::id()).unwrap();
776        assert!(started <= now, "start time {started} is after now {now}");
777        assert!(
778            now - started < 3_600 * 1_000_000,
779            "start time {started} is more than an hour before now {now}"
780        );
781    }
782
783    /// Keeps one core busy for at least `wall` of wall-clock time.
784    /// This thread's CPU time, from the thread CPU clock rather than the
785    /// process-usage API under test.
786    fn thread_cpu_time() -> Duration {
787        let now = rustix::time::clock_gettime(rustix::time::ClockId::ThreadCPUTime);
788        Duration::new(now.tv_sec as u64, now.tv_nsec as u32)
789    }
790
791    /// Spend `cpu` of this thread's CPU time. Measured on CPU time, not wall
792    /// time: on a loaded machine the thread is descheduled for part of any
793    /// wall interval, so a wall-timed loop can do far less work than its
794    /// duration suggests. A generous wall cap keeps a stalled clock from
795    /// hanging the test.
796    fn burn_cpu(cpu: Duration) {
797        let start = thread_cpu_time();
798        let give_up = Instant::now() + Duration::from_secs(60);
799        let mut value = 0u64;
800        while thread_cpu_time().saturating_sub(start) < cpu {
801            assert!(
802                Instant::now() < give_up,
803                "thread CPU clock stopped advancing"
804            );
805            for step in 0..10_000u64 {
806                value = std::hint::black_box(value.wrapping_mul(31).wrapping_add(step));
807            }
808        }
809        std::hint::black_box(value);
810    }
811
812    #[test]
813    fn own_resource_usage_is_present_and_plausible() {
814        // Clean executable pages need not count toward physical footprint, and
815        // nextest runs this case in a fresh process with little private memory.
816        // Touch and retain private pages so the byte/unit check has a known
817        // lower bound instead of assuming a minimum footprint for the binary.
818        let pages = vec![0xa5u8; 8 * 1024 * 1024];
819        std::hint::black_box(&pages);
820        let usage = resource_usage(std::process::id()).expect("own process is readable");
821        assert!(
822            usage.memory_bytes >= pages.len() as u64,
823            "memory {} bytes cannot account for {} touched private bytes",
824            usage.memory_bytes,
825            pages.len()
826        );
827        std::hint::black_box(&pages);
828        assert!(
829            usage.memory_bytes < 64 * 1024 * 1024 * 1024,
830            "memory {} bytes is implausibly large",
831            usage.memory_bytes
832        );
833        #[cfg(target_os = "macos")]
834        assert_eq!(usage.memory_kind, MemoryKind::PhysFootprint);
835        #[cfg(target_os = "linux")]
836        {
837            assert_eq!(usage.memory_kind, MemoryKind::ResidentSet);
838            assert!(usage.swap_bytes.is_some(), "Linux reports VmSwap");
839        }
840    }
841
842    /// CPU time must grow with busy work, and by roughly the amount of work
843    /// done: a reading in the wrong unit (for example Mach ticks taken as
844    /// nanoseconds on Apple silicon, about 24 times too small) grows too, but
845    /// not by enough.
846    #[test]
847    fn own_cpu_time_grows_by_about_the_busy_work_done() {
848        let pid = std::process::id();
849        let total = |usage: ResourceUsage| usage.cpu_user + usage.cpu_system;
850        let before = total(resource_usage(pid).unwrap());
851        let busy = Duration::from_millis(400);
852        burn_cpu(busy);
853        let after = total(resource_usage(pid).unwrap());
854        let grown = after.saturating_sub(before);
855        // This thread alone spent `busy` of CPU time, so the process total
856        // grew by at least that much; other tests' threads only add to it.
857        // The 10% allowance covers tick rounding in the reading, and is far
858        // tighter than the ~24x a unit error would cause.
859        assert!(
860            grown >= busy * 9 / 10,
861            "cpu time grew by {grown:?} over {busy:?} of busy work"
862        );
863    }
864
865    #[test]
866    fn a_child_reads_its_own_usage_not_ours() {
867        struct ChildGuard(Child);
868        impl Drop for ChildGuard {
869            fn drop(&mut self) {
870                let _ = self.0.kill();
871                let _ = self.0.wait();
872            }
873        }
874
875        // An unrelated executable's RSS need not be smaller than ours. Give
876        // the child a known amount of touched private memory instead, with a
877        // margin above the caller's footprint even while other tests run.
878        let ours = resource_usage(std::process::id()).unwrap();
879        let bytes = usize::try_from(ours.memory_bytes)
880            .unwrap()
881            .checked_add(64 * 1024 * 1024)
882            .unwrap();
883        let scratch = cortexkit_test_support::ScratchDir::new("subc-os-resource-usage");
884        let ready = scratch.join("ready");
885        let mut child = ChildGuard(
886            Command::new(std::env::current_exe().unwrap())
887                .args([
888                    "tests::resource_usage_child",
889                    "--exact",
890                    "--ignored",
891                    "--nocapture",
892                    "--test-threads=1",
893                ])
894                .env("SUBC_OS_TEST_RESOURCE_BYTES", bytes.to_string())
895                .env("SUBC_OS_TEST_RESOURCE_READY", &ready)
896                .stdin(Stdio::piped())
897                .stdout(Stdio::null())
898                .spawn()
899                .unwrap(),
900        );
901        let deadline = Instant::now() + Duration::from_secs(10);
902        while !ready.exists() {
903            assert!(child.0.try_wait().unwrap().is_none(), "memory child exited");
904            assert!(Instant::now() < deadline, "memory child never became ready");
905            std::thread::sleep(Duration::from_millis(5));
906        }
907
908        let ours = resource_usage(std::process::id()).unwrap();
909        let usage = resource_usage(child.0.id()).expect("live child is readable");
910        // The caller cannot meet the child's lower bound. Reading our own
911        // usage for both pids must therefore fail, not satisfy the test.
912        assert!(
913            ours.memory_bytes < bytes as u64,
914            "caller uses {} bytes, overlapping the child's {bytes} touched bytes",
915            ours.memory_bytes,
916        );
917        assert!(
918            usage.memory_bytes >= bytes as u64,
919            "child uses {} bytes, fewer than its {bytes} touched bytes (caller uses {})",
920            usage.memory_bytes,
921            ours.memory_bytes,
922        );
923    }
924
925    #[test]
926    #[ignore = "re-exec fixture retaining touched private memory until its parent closes stdin"]
927    fn resource_usage_child() {
928        let bytes: usize = std::env::var("SUBC_OS_TEST_RESOURCE_BYTES")
929            .unwrap()
930            .parse()
931            .unwrap();
932        let ready = std::env::var_os("SUBC_OS_TEST_RESOURCE_READY").unwrap();
933        let pages = vec![0xa5u8; bytes];
934        std::hint::black_box(&pages);
935        std::fs::write(ready, b"ready").unwrap();
936        let _ = std::io::stdin().read(&mut [0]);
937        std::hint::black_box(&pages);
938    }
939
940    #[test]
941    fn an_exited_child_reads_as_unavailable_not_zero() {
942        let mut child = spawn_sleep();
943        let pid = child.id();
944        child.kill().unwrap();
945        // Killed but not reaped: a zombie, which still has a pid.
946        let deadline = Instant::now() + Duration::from_secs(5);
947        while start_time(pid).is_some() {
948            assert!(Instant::now() < deadline, "child still observed as alive");
949            std::thread::sleep(Duration::from_millis(10));
950        }
951        assert_eq!(resource_usage(pid), None, "a zombie reads as unavailable");
952        child.wait().unwrap();
953        // Reaped: the pid names nothing (barring reuse, which would be some
954        // other live process and so still not a reading of zeros).
955        if let Some(usage) = resource_usage(pid) {
956            assert!(usage.memory_bytes > 0, "a reused pid is some live process");
957        }
958    }
959
960    #[test]
961    fn a_pid_with_no_process_reads_as_unavailable() {
962        // Above both kernels' pid limits (Linux caps pid_max at 2^22, macOS at
963        // 99998), so nothing can hold it.
964        assert_eq!(resource_usage(i32::MAX as u32), None);
965        // Not a representable pid at all.
966        assert_eq!(resource_usage(u32::MAX), None);
967    }
968
969    #[cfg(target_os = "linux")]
970    #[test]
971    fn linux_signals_go_through_a_pidfd() {
972        let mut child = spawn_sleep();
973        let process = Process::open(child.id()).unwrap().unwrap();
974        assert!(process.signals_through_pidfd());
975        child.kill().unwrap();
976        child.wait().unwrap();
977        // The pidfd still names the reaped child, so a signal cannot reach anything else.
978        assert!(!process.signal(Signal::Kill).unwrap());
979    }
980}