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