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