Skip to main content

subc_os/
lib.rs

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