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