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`): every `unsafe` block here
6//! is a single foreign call with its preconditions stated beside it, and nothing
7//! unsafe is exported.
8//!
9//! Today it answers one 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//! For the peer of an accepted local-endpoint connection (a Unix-domain
48//! socket, or a named-pipe client on Windows), [`local_peer`] reads the
49//! kernel's record of the connecting process: its user, pid and executable,
50//! and on macOS its code-signing identifier.
51//!
52//! And it carries the launch nonce from the daemon to each module it spawns
53//! over an inherited Unix pipe or a PID-authenticated Windows named pipe:
54//! [`launch_nonce`] is the one cached reader every module uses. Windows keeps
55//! an environment copy for old Windows readers until live source reports show
56//! every module consuming the named pipe.
57
58#![deny(unsafe_code)]
59
60#[cfg(all(unix, feature = "test-support"))]
61pub mod fork_exec_test;
62pub mod host;
63pub mod launch_nonce;
64pub mod local_peer;
65pub mod privacy_identity;
66pub mod process_identity;
67pub mod socket_peer;
68#[cfg_attr(not(windows), path = "windows_acl_noop.rs")]
69pub mod windows_acl;
70#[cfg(unix)]
71pub use launch_nonce::LaunchNonceHandoff;
72pub use launch_nonce::{
73 launch_nonce, LaunchNonce, LaunchNonceError, LaunchNonceSource, LAUNCH_NONCE_ENV,
74 LAUNCH_NONCE_FD, LAUNCH_NONCE_FD_ENV, LAUNCH_NONCE_PIPE_ENV, LAUNCH_NONCE_PIPE_FALLBACK_ENV,
75};
76
77#[cfg(windows)]
78pub use launch_nonce::{LaunchNoncePipeDelivery, LaunchNoncePipeHandoff};
79
80#[cfg(target_os = "linux")]
81mod linux;
82#[cfg(target_os = "macos")]
83mod macos;
84#[cfg(windows)]
85mod windows;
86#[cfg(all(test, windows))]
87mod windows_tests;
88#[cfg(windows)]
89pub use windows::{
90 ExecutableCapture, ImageAgreement, ImageUnavailable, SpawnedImage, WindowsFileIdentity,
91};
92
93#[cfg(target_os = "linux")]
94use linux as platform;
95#[cfg(target_os = "macos")]
96use macos as platform;
97
98use std::{io, path::Path};
99
100/// True where [`Process`] can identify and stop a process by pid.
101pub const PROCESS_IDENTITY_SUPPORTED: bool =
102 cfg!(any(target_os = "linux", target_os = "macos", windows));
103
104/// Device and inode of a file: which file, independent of the name used to
105/// reach it.
106#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
107pub struct FileIdentity {
108 pub device: u64,
109 pub inode: u64,
110}
111
112/// The device and inode of the file at `path`, following symlinks. `None` if it
113/// cannot be read or the platform has no inode numbers.
114pub fn file_identity(path: &Path) -> Option<FileIdentity> {
115 #[cfg(unix)]
116 {
117 use std::os::unix::fs::MetadataExt;
118
119 std::fs::metadata(path).ok().map(|metadata| FileIdentity {
120 device: metadata.dev(),
121 inode: metadata.ino(),
122 })
123 }
124 #[cfg(not(unix))]
125 {
126 let _ = path;
127 None
128 }
129}
130
131/// What a live process looks like right now.
132#[derive(Debug, Clone, Copy, PartialEq, Eq)]
133pub struct Observation {
134 /// The kernel's start time for the process. Opaque: compare it only with a
135 /// value read on the same host by this crate. Linux counts clock ticks since
136 /// boot; macOS counts microseconds since the epoch; Windows counts 100 ns
137 /// intervals since the Windows epoch.
138 pub start_time: u64,
139 /// The file the process is executing, or `None` if it could not be read
140 /// (for example, a process owned by another user).
141 /// Windows uses the full file ID in `SpawnedImage` instead of a Unix inode;
142 /// this field is always `None` there.
143 pub executable: Option<FileIdentity>,
144}
145
146/// Whether the running executable's identity could be read. Permission denial
147/// is distinct on Linux because a non-dumpable process hides its executable
148/// while leaving its start time readable.
149#[derive(Debug, Clone, Copy, PartialEq, Eq)]
150pub enum ExecutableAccess {
151 Readable,
152 PermissionDenied,
153 Unavailable,
154}
155
156/// A signal [`Process::signal`] can send.
157#[derive(Debug, Clone, Copy, PartialEq, Eq)]
158pub enum Signal {
159 /// SIGTERM: a request to exit, which the process may handle or ignore.
160 Terminate,
161 /// SIGKILL: ends the process; it cannot be handled or ignored.
162 Kill,
163}
164
165/// The kernel start time of the process holding `pid`, or `None` if there is
166/// none, it has already exited (a zombie waiting to be reaped counts as exited),
167/// or the platform has no source.
168pub fn start_time(pid: u32) -> Option<u64> {
169 #[cfg(any(target_os = "linux", target_os = "macos"))]
170 {
171 platform::start_time(pid)
172 }
173 #[cfg(windows)]
174 {
175 Process::open(pid)
176 .ok()??
177 .observe()
178 .map(|observation| observation.start_time)
179 }
180 #[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
181 {
182 let _ = pid;
183 None
184 }
185}
186
187/// The parent pid reported by the kernel, or `None` when it cannot be read.
188/// On Windows a reused parent pid (created after the child) is rejected.
189pub fn parent_pid(pid: u32) -> Option<u32> {
190 #[cfg(any(target_os = "linux", target_os = "macos"))]
191 {
192 platform::parent_pid(pid)
193 }
194 #[cfg(windows)]
195 {
196 windows::parent_pid(pid)
197 }
198 #[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
199 {
200 let _ = pid;
201 None
202 }
203}
204
205/// True where [`resource_usage`] can read a live process. Elsewhere it always
206/// answers `None`, and a caller can use this to say "not supported here"
207/// rather than "could not read".
208pub const RESOURCE_USAGE_SUPPORTED: bool =
209 cfg!(any(target_os = "linux", target_os = "macos", windows));
210
211/// What [`ResourceUsage::memory_bytes`] measures. The platforms offer
212/// different figures, and they are not interchangeable.
213#[derive(Debug, Clone, Copy, PartialEq, Eq)]
214pub enum MemoryKind {
215 /// macOS `phys_footprint`: the memory the kernel charges to the process
216 /// (dirty and compressed pages, among others), which is also what jetsam
217 /// acts on. Pages an allocator has released with `MADV_FREE` do not count.
218 PhysFootprint,
219 /// Linux `VmRSS`: pages of the process resident in RAM, including shared
220 /// file-backed pages. Swapped-out pages are not included; see
221 /// [`ResourceUsage::swap_bytes`].
222 ResidentSet,
223 /// Windows `WorkingSetSize`: pageable memory currently resident in RAM,
224 /// including shared pages. This is not Unix RSS or private committed memory.
225 WindowsWorkingSet,
226}
227
228/// One reading of a process's memory and cumulative CPU time.
229///
230/// It covers the process named by the pid alone: its threads are included,
231/// processes it has started are not.
232#[derive(Debug, Clone, Copy, PartialEq, Eq)]
233pub struct ResourceUsage {
234 /// Memory in bytes, measured as [`Self::memory_kind`] says.
235 pub memory_bytes: u64,
236 pub memory_kind: MemoryKind,
237 /// Bytes swapped out (Linux `VmSwap`). `None` where the platform does not
238 /// report it for a single process, which is not the same as zero.
239 pub swap_bytes: Option<u64>,
240 /// CPU time spent in user mode since the process started.
241 pub cpu_user: std::time::Duration,
242 /// CPU time spent in the kernel on the process's behalf since it started.
243 pub cpu_system: std::time::Duration,
244}
245
246/// Memory and cumulative CPU time of the process holding `pid`, read now.
247///
248/// `None` when there is no such process, it has exited (a zombie awaiting its
249/// reap counts as exited), it cannot be read (for example, another user's
250/// process on macOS), or the platform has no source
251/// (see [`RESOURCE_USAGE_SUPPORTED`]). Never a reading of zeros in place of
252/// one of those.
253///
254/// Like any pid-based read, this describes whatever process holds `pid` now;
255/// a caller that needs it to be a particular process should confirm that
256/// process's [`start_time`] around the call.
257pub fn resource_usage(pid: u32) -> Option<ResourceUsage> {
258 #[cfg(any(target_os = "linux", target_os = "macos"))]
259 {
260 platform::resource_usage(pid)
261 }
262 #[cfg(windows)]
263 {
264 Process::open(pid).ok()??.resource_usage()
265 }
266 #[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
267 {
268 let _ = pid;
269 None
270 }
271}
272
273/// A handle on the process holding one pid at the moment it was opened.
274#[derive(Debug)]
275pub struct Process {
276 pid: u32,
277 #[cfg(target_os = "linux")]
278 pidfd: Option<std::os::fd::OwnedFd>,
279 #[cfg(windows)]
280 handle: std::os::windows::io::OwnedHandle,
281}
282
283impl Process {
284 /// Open a handle on the process now holding `pid`.
285 ///
286 /// `Ok(None)` means no process holds that pid (on macOS, also a zombie
287 /// awaiting its reap; on Linux a zombie opens, and [`Self::observe`] then
288 /// reports it as exited). On Linux this opens a pidfd,
289 /// which from then on refers to this exact process even if it exits and the
290 /// pid is reused; when the kernel cannot open one (older than 5.3, or a
291 /// seccomp policy refusing the call) the handle falls back to the pid, as
292 /// on macOS.
293 pub fn open(pid: u32) -> io::Result<Option<Self>> {
294 #[cfg(target_os = "linux")]
295 {
296 linux::open(pid).map(|opened| opened.map(|pidfd| Self { pid, pidfd }))
297 }
298 #[cfg(target_os = "macos")]
299 {
300 Ok(platform::exists(pid).then_some(Self { pid }))
301 }
302 #[cfg(windows)]
303 {
304 windows::open(pid).map(|opened| opened.map(|handle| Self { pid, handle }))
305 }
306 #[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
307 {
308 let _ = pid;
309 Err(io::Error::new(
310 io::ErrorKind::Unsupported,
311 "process identity is not available on this platform",
312 ))
313 }
314 }
315
316 pub fn pid(&self) -> u32 {
317 self.pid
318 }
319
320 /// True when signals go through a pidfd, so they cannot reach a different
321 /// process that has since reused this pid.
322 pub fn signals_through_pidfd(&self) -> bool {
323 #[cfg(target_os = "linux")]
324 {
325 self.pidfd.is_some()
326 }
327 #[cfg(not(target_os = "linux"))]
328 {
329 false
330 }
331 }
332
333 /// The process's start time and executable, or `None` when it has exited
334 /// (including as a zombie not yet reaped) or cannot be observed. On Linux,
335 /// [`Self::is_alive_but_unobservable`] distinguishes a hidden procfs entry.
336 pub fn observe(&self) -> Option<Observation> {
337 self.observe_with_executable_access()
338 .map(|(observed, _)| observed)
339 }
340
341 /// Whether Linux hides the entire procfs entry while the process still
342 /// exists. This proves existence, not identity, and never authorizes a signal.
343 /// Other platforms return false without changing their observation behavior.
344 pub fn is_alive_but_unobservable(&self) -> bool {
345 #[cfg(target_os = "linux")]
346 {
347 linux::alive_but_unobservable(self.pid, self.pidfd.as_ref())
348 }
349 #[cfg(not(target_os = "linux"))]
350 {
351 false
352 }
353 }
354
355 /// Observe the process and distinguish Linux executable permission denial
356 /// from other failures, without changing the legacy observation's fields.
357 /// Other platforms retain their existing readable/unavailable distinction.
358 pub fn observe_with_executable_access(&self) -> Option<(Observation, ExecutableAccess)> {
359 #[cfg(any(target_os = "linux", target_os = "macos"))]
360 {
361 #[cfg(target_os = "linux")]
362 if !linux::pidfd_alive(self.pidfd.as_ref()) {
363 return None;
364 }
365 let start_time = platform::start_time(self.pid)?;
366 #[cfg(target_os = "linux")]
367 let (executable, access) = match linux::executable_identity(self.pid) {
368 Ok(identity) => (Some(identity), ExecutableAccess::Readable),
369 Err(error) if error.kind() == io::ErrorKind::PermissionDenied => {
370 (None, ExecutableAccess::PermissionDenied)
371 }
372 Err(_) => (None, ExecutableAccess::Unavailable),
373 };
374 #[cfg(target_os = "macos")]
375 let executable = macos::executable_identity(self.pid);
376 #[cfg(target_os = "macos")]
377 let access = if executable.is_some() {
378 ExecutableAccess::Readable
379 } else {
380 ExecutableAccess::Unavailable
381 };
382 Some((
383 Observation {
384 start_time,
385 executable,
386 },
387 access,
388 ))
389 }
390 #[cfg(windows)]
391 {
392 windows::observe(self).map(|observed| (observed, ExecutableAccess::Unavailable))
393 }
394 #[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
395 {
396 None
397 }
398 }
399
400 /// Wait on the retained Windows handle. `Ok(false)` means the bound elapsed,
401 /// not that a reused PID was observed.
402 #[cfg(windows)]
403 pub fn wait_for_exit(&self, timeout: std::time::Duration) -> io::Result<bool> {
404 windows::wait(self, timeout)
405 }
406
407 /// Force the confirmed Windows process to stop, then wait on the same handle.
408 /// This is not a graceful termination signal. A different creation time
409 /// refuses before any action; `Ok(false)` means the wait bound elapsed.
410 #[cfg(windows)]
411 pub fn force_stop(
412 &self,
413 expected_start_time: u64,
414 timeout: std::time::Duration,
415 ) -> io::Result<bool> {
416 windows::force_stop(self, expected_start_time, timeout)
417 }
418
419 /// Windows resources read through the retained handle, not by reopening its PID.
420 #[cfg(windows)]
421 pub fn resource_usage(&self) -> Option<ResourceUsage> {
422 windows::resource_usage(self)
423 }
424
425 /// Send `signal` to the process.
426 ///
427 /// With a pidfd the signal can only reach the process this handle was
428 /// opened on: if that process has exited, the call fails with `ESRCH` even
429 /// if the pid has been reused. Without one (macOS, or a Linux kernel with no
430 /// pidfd) the signal goes to whatever holds the pid now, so callers should
431 /// [`Self::observe`] immediately before signalling. What remains is the
432 /// time between that check and this call; for a different process to be
433 /// hit, the checked one must exit, be reaped, and have its pid handed to a
434 /// new process inside that window, and both kernels hand out pids in
435 /// increasing order, so a reuse needs the whole pid space to wrap first.
436 ///
437 /// `Ok(false)` means the process had already exited (`ESRCH`).
438 pub fn signal(&self, signal: Signal) -> io::Result<bool> {
439 #[cfg(any(target_os = "linux", target_os = "macos"))]
440 {
441 #[cfg(target_os = "linux")]
442 let result = linux::signal(self.pid, self.pidfd.as_ref(), signal);
443 #[cfg(target_os = "macos")]
444 let result = macos::signal(self.pid, signal);
445 match result {
446 Ok(()) => Ok(true),
447 Err(rustix::io::Errno::SRCH) => Ok(false),
448 Err(error) => Err(error.into()),
449 }
450 }
451 #[cfg(not(any(target_os = "linux", target_os = "macos")))]
452 {
453 let _ = signal;
454 Err(io::Error::new(
455 io::ErrorKind::Unsupported,
456 "process signalling is not available on this platform",
457 ))
458 }
459 }
460}
461
462#[cfg(all(test, any(target_os = "linux", target_os = "macos")))]
463mod tests {
464 use std::{
465 io::Read,
466 process::{Child, Command, Stdio},
467 time::{Duration, Instant},
468 };
469
470 use super::*;
471
472 fn spawn_sleep() -> Child {
473 Command::new("sleep")
474 .arg("60")
475 .spawn()
476 .expect("spawn sleep")
477 }
478
479 /// The executable a spawned `sleep` runs, resolved the way `Command` found it.
480 fn sleep_identity() -> FileIdentity {
481 let path = ["/bin/sleep", "/usr/bin/sleep"]
482 .into_iter()
483 .find(|path| Path::new(path).exists())
484 .expect("sleep is installed");
485 file_identity(Path::new(path)).expect("stat sleep")
486 }
487
488 /// Right after `spawn` returns the child may not have finished exec yet,
489 /// and until then it still runs the test binary's image.
490 fn wait_for_executable(process: &Process, expected: FileIdentity) -> Observation {
491 let deadline = Instant::now() + Duration::from_secs(5);
492 loop {
493 let observation = process.observe().expect("child is alive");
494 if observation.executable == Some(expected) || Instant::now() > deadline {
495 return observation;
496 }
497 std::thread::sleep(Duration::from_millis(10));
498 }
499 }
500
501 #[test]
502 fn own_process_is_observable_with_its_own_image() {
503 let process = Process::open(std::process::id())
504 .expect("open own process")
505 .expect("own process exists");
506 let observation = process.observe().expect("own process is alive");
507 let own_image = file_identity(&std::env::current_exe().unwrap()).unwrap();
508 assert_eq!(observation.executable, Some(own_image));
509 assert_eq!(start_time(std::process::id()), Some(observation.start_time));
510 }
511
512 #[test]
513 fn child_start_time_is_stable_and_differs_from_ours() {
514 let mut child = spawn_sleep();
515 let pid = child.id();
516 let process = Process::open(pid).unwrap().unwrap();
517 let observation = wait_for_executable(&process, sleep_identity());
518 assert_eq!(observation.executable, Some(sleep_identity()));
519 assert_eq!(start_time(pid), Some(observation.start_time));
520 child.kill().unwrap();
521 child.wait().unwrap();
522 }
523
524 #[test]
525 fn a_signalled_and_unreaped_child_reads_as_exited() {
526 let mut child = spawn_sleep();
527 let process = Process::open(child.id()).unwrap().unwrap();
528 assert!(process.signal(Signal::Terminate).unwrap());
529 let deadline = Instant::now() + Duration::from_secs(5);
530 while process.observe().is_some() {
531 assert!(Instant::now() < deadline, "child still observed as alive");
532 std::thread::sleep(Duration::from_millis(10));
533 }
534 // Not yet reaped: the pid is still a zombie here, and still reads as exited.
535 assert_eq!(start_time(child.id()), None);
536 child.wait().unwrap();
537 }
538
539 #[test]
540 fn a_reaped_child_cannot_be_opened_or_observed() {
541 let mut child = spawn_sleep();
542 let pid = child.id();
543 child.kill().unwrap();
544 child.wait().unwrap();
545 // The pid could in principle be reused by now; either way it is not the child.
546 if let Some(process) = Process::open(pid).unwrap() {
547 if let Some(observation) = process.observe() {
548 assert_ne!(observation.executable, Some(sleep_identity()));
549 }
550 }
551 }
552
553 /// The macOS fields are read at fixed offsets, so check the value is a
554 /// plausible start time and not some other field: our own process started
555 /// in the past, and not long ago.
556 #[cfg(target_os = "macos")]
557 #[test]
558 fn macos_start_time_is_microseconds_since_the_epoch() {
559 let now = std::time::SystemTime::now()
560 .duration_since(std::time::UNIX_EPOCH)
561 .unwrap()
562 .as_micros() as u64;
563 let started = start_time(std::process::id()).unwrap();
564 assert!(started <= now, "start time {started} is after now {now}");
565 assert!(
566 now - started < 3_600 * 1_000_000,
567 "start time {started} is more than an hour before now {now}"
568 );
569 }
570
571 /// Keeps one core busy for at least `wall` of wall-clock time.
572 /// This thread's CPU time, from the thread CPU clock rather than the
573 /// process-usage API under test.
574 fn thread_cpu_time() -> Duration {
575 let now = rustix::time::clock_gettime(rustix::time::ClockId::ThreadCPUTime);
576 Duration::new(now.tv_sec as u64, now.tv_nsec as u32)
577 }
578
579 /// Spend `cpu` of this thread's CPU time. Measured on CPU time, not wall
580 /// time: on a loaded machine the thread is descheduled for part of any
581 /// wall interval, so a wall-timed loop can do far less work than its
582 /// duration suggests. A generous wall cap keeps a stalled clock from
583 /// hanging the test.
584 fn burn_cpu(cpu: Duration) {
585 let start = thread_cpu_time();
586 let give_up = Instant::now() + Duration::from_secs(60);
587 let mut value = 0u64;
588 while thread_cpu_time().saturating_sub(start) < cpu {
589 assert!(
590 Instant::now() < give_up,
591 "thread CPU clock stopped advancing"
592 );
593 for step in 0..10_000u64 {
594 value = std::hint::black_box(value.wrapping_mul(31).wrapping_add(step));
595 }
596 }
597 std::hint::black_box(value);
598 }
599
600 #[test]
601 fn own_resource_usage_is_present_and_plausible() {
602 // Clean executable pages need not count toward physical footprint, and
603 // nextest runs this case in a fresh process with little private memory.
604 // Touch and retain private pages so the byte/unit check has a known
605 // lower bound instead of assuming a minimum footprint for the binary.
606 let pages = vec![0xa5u8; 8 * 1024 * 1024];
607 std::hint::black_box(&pages);
608 let usage = resource_usage(std::process::id()).expect("own process is readable");
609 assert!(
610 usage.memory_bytes >= pages.len() as u64,
611 "memory {} bytes cannot account for {} touched private bytes",
612 usage.memory_bytes,
613 pages.len()
614 );
615 std::hint::black_box(&pages);
616 assert!(
617 usage.memory_bytes < 64 * 1024 * 1024 * 1024,
618 "memory {} bytes is implausibly large",
619 usage.memory_bytes
620 );
621 #[cfg(target_os = "macos")]
622 assert_eq!(usage.memory_kind, MemoryKind::PhysFootprint);
623 #[cfg(target_os = "linux")]
624 {
625 assert_eq!(usage.memory_kind, MemoryKind::ResidentSet);
626 assert!(usage.swap_bytes.is_some(), "Linux reports VmSwap");
627 }
628 }
629
630 /// CPU time must grow with busy work, and by roughly the amount of work
631 /// done: a reading in the wrong unit (for example Mach ticks taken as
632 /// nanoseconds on Apple silicon, about 24 times too small) grows too, but
633 /// not by enough.
634 #[test]
635 fn own_cpu_time_grows_by_about_the_busy_work_done() {
636 let pid = std::process::id();
637 let total = |usage: ResourceUsage| usage.cpu_user + usage.cpu_system;
638 let before = total(resource_usage(pid).unwrap());
639 let busy = Duration::from_millis(400);
640 burn_cpu(busy);
641 let after = total(resource_usage(pid).unwrap());
642 let grown = after.saturating_sub(before);
643 // This thread alone spent `busy` of CPU time, so the process total
644 // grew by at least that much; other tests' threads only add to it.
645 // The 10% allowance covers tick rounding in the reading, and is far
646 // tighter than the ~24x a unit error would cause.
647 assert!(
648 grown >= busy * 9 / 10,
649 "cpu time grew by {grown:?} over {busy:?} of busy work"
650 );
651 }
652
653 #[test]
654 fn a_child_reads_its_own_usage_not_ours() {
655 struct ChildGuard(Child);
656 impl Drop for ChildGuard {
657 fn drop(&mut self) {
658 let _ = self.0.kill();
659 let _ = self.0.wait();
660 }
661 }
662
663 // An unrelated executable's RSS need not be smaller than ours. Give
664 // the child a known amount of touched private memory instead, with a
665 // margin above the caller's footprint even while other tests run.
666 let ours = resource_usage(std::process::id()).unwrap();
667 let bytes = usize::try_from(ours.memory_bytes)
668 .unwrap()
669 .checked_add(64 * 1024 * 1024)
670 .unwrap();
671 let scratch = cortexkit_test_support::ScratchDir::new("subc-os-resource-usage");
672 let ready = scratch.join("ready");
673 let mut child = ChildGuard(
674 Command::new(std::env::current_exe().unwrap())
675 .args([
676 "tests::resource_usage_child",
677 "--exact",
678 "--ignored",
679 "--nocapture",
680 "--test-threads=1",
681 ])
682 .env("SUBC_OS_TEST_RESOURCE_BYTES", bytes.to_string())
683 .env("SUBC_OS_TEST_RESOURCE_READY", &ready)
684 .stdin(Stdio::piped())
685 .stdout(Stdio::null())
686 .spawn()
687 .unwrap(),
688 );
689 let deadline = Instant::now() + Duration::from_secs(10);
690 while !ready.exists() {
691 assert!(child.0.try_wait().unwrap().is_none(), "memory child exited");
692 assert!(Instant::now() < deadline, "memory child never became ready");
693 std::thread::sleep(Duration::from_millis(5));
694 }
695
696 let ours = resource_usage(std::process::id()).unwrap();
697 let usage = resource_usage(child.0.id()).expect("live child is readable");
698 // The caller cannot meet the child's lower bound. Reading our own
699 // usage for both pids must therefore fail, not satisfy the test.
700 assert!(
701 ours.memory_bytes < bytes as u64,
702 "caller uses {} bytes, overlapping the child's {bytes} touched bytes",
703 ours.memory_bytes,
704 );
705 assert!(
706 usage.memory_bytes >= bytes as u64,
707 "child uses {} bytes, fewer than its {bytes} touched bytes (caller uses {})",
708 usage.memory_bytes,
709 ours.memory_bytes,
710 );
711 }
712
713 #[test]
714 #[ignore = "re-exec fixture retaining touched private memory until its parent closes stdin"]
715 fn resource_usage_child() {
716 let bytes: usize = std::env::var("SUBC_OS_TEST_RESOURCE_BYTES")
717 .unwrap()
718 .parse()
719 .unwrap();
720 let ready = std::env::var_os("SUBC_OS_TEST_RESOURCE_READY").unwrap();
721 let pages = vec![0xa5u8; bytes];
722 std::hint::black_box(&pages);
723 std::fs::write(ready, b"ready").unwrap();
724 let _ = std::io::stdin().read(&mut [0]);
725 std::hint::black_box(&pages);
726 }
727
728 #[test]
729 fn an_exited_child_reads_as_unavailable_not_zero() {
730 let mut child = spawn_sleep();
731 let pid = child.id();
732 child.kill().unwrap();
733 // Killed but not reaped: a zombie, which still has a pid.
734 let deadline = Instant::now() + Duration::from_secs(5);
735 while start_time(pid).is_some() {
736 assert!(Instant::now() < deadline, "child still observed as alive");
737 std::thread::sleep(Duration::from_millis(10));
738 }
739 assert_eq!(resource_usage(pid), None, "a zombie reads as unavailable");
740 child.wait().unwrap();
741 // Reaped: the pid names nothing (barring reuse, which would be some
742 // other live process and so still not a reading of zeros).
743 if let Some(usage) = resource_usage(pid) {
744 assert!(usage.memory_bytes > 0, "a reused pid is some live process");
745 }
746 }
747
748 #[test]
749 fn a_pid_with_no_process_reads_as_unavailable() {
750 // Above both kernels' pid limits (Linux caps pid_max at 2^22, macOS at
751 // 99998), so nothing can hold it.
752 assert_eq!(resource_usage(i32::MAX as u32), None);
753 // Not a representable pid at all.
754 assert_eq!(resource_usage(u32::MAX), None);
755 }
756
757 #[cfg(target_os = "linux")]
758 #[test]
759 fn linux_signals_go_through_a_pidfd() {
760 let mut child = spawn_sleep();
761 let process = Process::open(child.id()).unwrap().unwrap();
762 assert!(process.signals_through_pidfd());
763 child.kill().unwrap();
764 child.wait().unwrap();
765 // The pidfd still names the reaped child, so a signal cannot reach anything else.
766 assert!(!process.signal(Signal::Kill).unwrap());
767 }
768}