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