1#![deny(unsafe_code)]
64
65#[cfg(target_os = "macos")]
66mod darwin_user_temp;
67#[cfg(target_os = "macos")]
68pub use darwin_user_temp::darwin_user_temp_dir;
69
70#[cfg(windows)]
71mod profile;
72#[cfg(windows)]
73pub use profile::profile_dir;
74
75#[cfg(unix)]
76mod user_home;
77#[cfg(unix)]
78pub use user_home::{effective_uid, real_user_home_dir};
79
80#[cfg(unix)]
81pub mod admission_gate;
82pub mod boot_id;
83#[cfg(unix)]
84pub mod child_exit;
85pub mod child_spawn;
86#[cfg(target_os = "macos")]
87pub mod code_signature;
88pub mod config_keychain;
89mod durable_replace;
90#[cfg(any(unix, windows))]
91mod retained_file;
92#[cfg(any(target_os = "linux", target_os = "macos", windows))]
93mod retained_replace;
94#[cfg(windows)]
95pub use durable_replace::durable_move_to_new_name;
96#[cfg(feature = "test-support")]
97pub use durable_replace::durable_replace_with_rename_hook;
98pub use durable_replace::{durable_replace, DurableReplaceError};
99#[cfg(any(unix, windows))]
100pub use retained_file::{
101 open_directory_nofollow_all, open_regular_nofollow, open_regular_nofollow_all,
102 retained_file_identity, OpenRegularError, RetainedFileIdentity,
103};
104#[cfg(windows)]
105pub use retained_file::{
106 retained_file_index, retained_file_information, WindowsFileIndexIdentity,
107 WindowsFileInformation,
108};
109#[cfg(any(target_os = "linux", target_os = "macos", windows))]
110pub use retained_replace::{
111 create_directory_nofollow_at, move_file_aside_nofollow_at, move_file_to_noreplace_at,
112 open_directory_nofollow_at, open_or_create_private_directory_at,
113 open_single_link_file_nofollow_at, probe_retained_directory_write,
114 probe_retained_regular_file_at, retained_directory_path, retained_regular_file_at,
115 OpenRetainedError, RetainedMovedFile, RetainedTempFile,
116};
117#[cfg(all(unix, feature = "test-support"))]
118pub mod fork_exec_test;
119pub mod host;
120pub mod launch_nonce;
121pub mod local_peer;
122#[cfg(windows)]
123mod loopback_connect;
124#[cfg(windows)]
125pub use loopback_connect::connect_loopback;
126pub mod named_pipe;
127pub mod privacy_identity;
128mod private_directory;
129#[cfg(unix)]
130pub mod process_group;
131pub mod process_identity;
132pub use private_directory::create_private_directory_exclusive;
133pub mod registration_channel;
134pub mod script_pipe;
135pub mod socket_peer;
136#[cfg(windows)]
137pub mod user_path;
138#[cfg_attr(not(windows), path = "windows_acl_noop.rs")]
139pub mod windows_acl;
140#[cfg(all(windows, feature = "test-support"))]
141pub mod windows_console_test;
142#[cfg(unix)]
143pub use launch_nonce::LaunchNonceHandoff;
144pub use launch_nonce::{
145 launch_nonce, LaunchNonce, LaunchNonceError, LaunchNonceSource, LAUNCH_NONCE_ENV,
146 LAUNCH_NONCE_FD, LAUNCH_NONCE_FD_ENV, LAUNCH_NONCE_PIPE_ENV, LAUNCH_NONCE_PIPE_FALLBACK_ENV,
147};
148
149#[cfg(windows)]
150pub use launch_nonce::{LaunchNoncePipeDelivery, LaunchNoncePipeHandoff};
151
152pub use registration_channel::{
153 registration_refusal, supervised, take_registration_channel, RegistrationChannel,
154 RegistrationChannelError, RegistrationRefusal,
155};
156
157#[cfg(target_os = "linux")]
158mod linux;
159#[cfg(target_os = "macos")]
160mod macos;
161
162#[cfg(target_os = "macos")]
163pub use macos::owned_child_start_time;
164#[cfg(windows)]
165mod windows;
166#[cfg(all(test, windows))]
167mod windows_tests;
168#[cfg(windows)]
169pub use windows::{
170 ExecutableCapture, ImageAgreement, ImageUnavailable, SpawnedImage, WindowsFileIdentity,
171};
172
173#[cfg(target_os = "linux")]
174use linux as platform;
175#[cfg(target_os = "macos")]
176use macos as platform;
177
178use std::{io, path::Path};
179
180pub const PROCESS_IDENTITY_SUPPORTED: bool =
182 cfg!(any(target_os = "linux", target_os = "macos", windows));
183
184#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
187pub struct FileIdentity {
188 pub device: u64,
189 pub inode: u64,
190}
191
192pub fn file_identity(path: &Path) -> Option<FileIdentity> {
195 #[cfg(unix)]
196 {
197 use std::os::unix::fs::MetadataExt;
198
199 std::fs::metadata(path).ok().map(|metadata| FileIdentity {
200 device: metadata.dev(),
201 inode: metadata.ino(),
202 })
203 }
204 #[cfg(not(unix))]
205 {
206 let _ = path;
207 None
208 }
209}
210
211#[derive(Debug, Clone, Copy, PartialEq, Eq)]
213pub struct Observation {
214 pub start_time: u64,
219 pub executable: Option<FileIdentity>,
224}
225
226#[derive(Debug, Clone, Copy, PartialEq, Eq)]
230pub enum ExecutableAccess {
231 Readable,
232 PermissionDenied,
233 Unavailable,
234}
235
236#[derive(Debug, Clone, Copy, PartialEq, Eq)]
238pub enum Signal {
239 Terminate,
241 Kill,
243}
244
245pub fn start_time(pid: u32) -> Option<u64> {
249 #[cfg(any(target_os = "linux", target_os = "macos"))]
250 {
251 platform::start_time(pid)
252 }
253 #[cfg(windows)]
254 {
255 Process::open(pid)
256 .ok()??
257 .observe()
258 .map(|observation| observation.start_time)
259 }
260 #[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
261 {
262 let _ = pid;
263 None
264 }
265}
266
267#[derive(Clone, Copy, Debug, PartialEq, Eq)]
269pub(crate) enum IdentityRead {
270 Alive(u64),
271 #[cfg_attr(windows, allow(dead_code))]
272 Gone,
274 Unknown,
275}
276
277#[cfg(all(test, any(target_os = "linux", target_os = "macos")))]
278mod identity_read_tests {
279 use super::*;
280
281 #[test]
282 fn identity_probe_distinguishes_alive_gone_and_invalid() {
283 let mut child = std::process::Command::new("/bin/sh")
284 .args(["-c", "exit 0"])
285 .spawn()
286 .unwrap();
287 let pid = child.id();
288 let until = std::time::Instant::now() + std::time::Duration::from_secs(5);
289 while read_identity(pid) != IdentityRead::Gone {
290 assert!(
291 std::time::Instant::now() < until,
292 "an exited owned child must become gone before reaping"
293 );
294 std::thread::yield_now();
295 }
296 child.wait().unwrap();
297 assert_eq!(
298 read_identity(pid),
299 IdentityRead::Gone,
300 "a missing owned PID is gone"
301 );
302 assert_eq!(read_identity(0), IdentityRead::Unknown);
303 assert!(matches!(
304 read_identity(std::process::id()),
305 IdentityRead::Alive(_)
306 ));
307 }
308}
309
310#[cfg(not(windows))]
311fn read_identity(pid: u32) -> IdentityRead {
312 #[cfg(any(target_os = "linux", target_os = "macos"))]
313 {
314 platform::read_identity(pid)
315 }
316 #[cfg(not(any(target_os = "linux", target_os = "macos")))]
317 {
318 start_time(pid).map_or(IdentityRead::Unknown, IdentityRead::Alive)
319 }
320}
321
322mod process_tree;
323pub use process_tree::{BirthBaseline, ProcessGroup, ProcessMember, ProcessTable, TreeUsage};
324
325pub fn process_start_time_ms(pid: u32) -> Option<u64> {
333 start_time_ms_from_native(start_time(pid)?)
334}
335
336fn start_time_ms_from_native(raw: u64) -> Option<u64> {
337 #[cfg(target_os = "linux")]
338 {
339 linux_start_time_ms(raw, || std::fs::read_to_string("/proc/stat").ok())
340 }
341 #[cfg(target_os = "macos")]
342 {
343 Some(raw / 1_000)
344 }
345 #[cfg(windows)]
346 {
347 (raw / 10_000).checked_sub(11_644_473_600_000)
348 }
349 #[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
350 {
351 let _ = raw;
352 None
353 }
354}
355
356#[cfg(target_os = "linux")]
357fn linux_start_time_ms(raw: u64, read_boot: impl FnOnce() -> Option<String>) -> Option<u64> {
358 let boot = read_boot()?
362 .lines()
363 .find_map(|line| line.strip_prefix("btime ")?.parse::<u64>().ok())?;
364 boot.checked_mul(1_000)?
365 .checked_add(raw.checked_mul(1_000)? / rustix::param::clock_ticks_per_second().max(1))
366}
367
368#[cfg(all(test, target_os = "linux"))]
369#[test]
370fn linux_start_identity_uses_fresh_boot_time_after_clock_step() {
371 let before = linux_start_time_ms(100, || Some("btime 1000\n".into())).unwrap();
372 let after = linux_start_time_ms(100, || Some("btime 1002\n".into())).unwrap();
373 assert_eq!(after - before, 2_000);
374}
375
376pub fn process_start_time_precision_ms() -> u64 {
378 #[cfg(target_os = "linux")]
379 {
380 1_000_u64.div_ceil(rustix::param::clock_ticks_per_second().max(1))
381 }
382 #[cfg(not(target_os = "linux"))]
383 {
384 1
385 }
386}
387
388pub fn parent_pid(pid: u32) -> Option<u32> {
391 #[cfg(any(target_os = "linux", target_os = "macos"))]
392 {
393 platform::parent_pid(pid)
394 }
395 #[cfg(windows)]
396 {
397 windows::parent_pid(pid)
398 }
399 #[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
400 {
401 let _ = pid;
402 None
403 }
404}
405
406pub const RESOURCE_USAGE_SUPPORTED: bool =
410 cfg!(any(target_os = "linux", target_os = "macos", windows));
411
412#[derive(Debug, Clone, Copy, PartialEq, Eq)]
415pub enum MemoryKind {
416 PhysFootprint,
420 ResidentSet,
424 WindowsWorkingSet,
427}
428
429#[derive(Debug, Clone, Copy, PartialEq, Eq)]
434pub struct ResourceUsage {
435 pub memory_bytes: u64,
437 pub memory_kind: MemoryKind,
438 pub swap_bytes: Option<u64>,
441 pub cpu_user: std::time::Duration,
443 pub cpu_system: std::time::Duration,
445}
446
447pub fn resource_usage(pid: u32) -> Option<ResourceUsage> {
459 #[cfg(any(target_os = "linux", target_os = "macos"))]
460 {
461 platform::resource_usage(pid)
462 }
463 #[cfg(windows)]
464 {
465 Process::open(pid).ok()??.resource_usage()
466 }
467 #[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
468 {
469 let _ = pid;
470 None
471 }
472}
473
474#[derive(Debug)]
476pub struct Process {
477 pid: u32,
478 #[cfg(target_os = "linux")]
479 pidfd: Option<std::os::fd::OwnedFd>,
480 #[cfg(windows)]
481 handle: std::os::windows::io::OwnedHandle,
482}
483
484impl Process {
485 pub fn open(pid: u32) -> io::Result<Option<Self>> {
495 #[cfg(target_os = "linux")]
496 {
497 linux::open(pid).map(|opened| opened.map(|pidfd| Self { pid, pidfd }))
498 }
499 #[cfg(target_os = "macos")]
500 {
501 Ok(platform::exists(pid).then_some(Self { pid }))
502 }
503 #[cfg(windows)]
504 {
505 windows::open(pid).map(|opened| opened.map(|handle| Self { pid, handle }))
506 }
507 #[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
508 {
509 let _ = pid;
510 Err(io::Error::new(
511 io::ErrorKind::Unsupported,
512 "process identity is not available on this platform",
513 ))
514 }
515 }
516
517 pub fn pid(&self) -> u32 {
518 self.pid
519 }
520
521 pub fn signals_through_pidfd(&self) -> bool {
524 #[cfg(target_os = "linux")]
525 {
526 self.pidfd.is_some()
527 }
528 #[cfg(not(target_os = "linux"))]
529 {
530 false
531 }
532 }
533
534 pub fn observe(&self) -> Option<Observation> {
538 self.observe_with_executable_access()
539 .map(|(observed, _)| observed)
540 }
541
542 pub fn is_alive_but_unobservable(&self) -> bool {
546 #[cfg(target_os = "linux")]
547 {
548 linux::alive_but_unobservable(self.pid, self.pidfd.as_ref())
549 }
550 #[cfg(not(target_os = "linux"))]
551 {
552 false
553 }
554 }
555
556 pub fn observe_with_executable_access(&self) -> Option<(Observation, ExecutableAccess)> {
560 #[cfg(any(target_os = "linux", target_os = "macos"))]
561 {
562 #[cfg(target_os = "linux")]
563 if !linux::pidfd_alive(self.pidfd.as_ref()) {
564 return None;
565 }
566 let start_time = platform::start_time(self.pid)?;
567 #[cfg(target_os = "linux")]
568 let (executable, access) = match linux::executable_identity(self.pid) {
569 Ok(identity) => (Some(identity), ExecutableAccess::Readable),
570 Err(error) if error.kind() == io::ErrorKind::PermissionDenied => {
571 (None, ExecutableAccess::PermissionDenied)
572 }
573 Err(_) => (None, ExecutableAccess::Unavailable),
574 };
575 #[cfg(target_os = "macos")]
576 let executable = macos::executable_identity(self.pid);
577 #[cfg(target_os = "macos")]
578 let access = if executable.is_some() {
579 ExecutableAccess::Readable
580 } else {
581 ExecutableAccess::Unavailable
582 };
583 Some((
584 Observation {
585 start_time,
586 executable,
587 },
588 access,
589 ))
590 }
591 #[cfg(windows)]
592 {
593 windows::observe(self).map(|observed| (observed, ExecutableAccess::Unavailable))
594 }
595 #[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
596 {
597 None
598 }
599 }
600
601 #[cfg(windows)]
604 pub fn wait_for_exit(&self, timeout: std::time::Duration) -> io::Result<bool> {
605 windows::wait(self, timeout)
606 }
607
608 #[cfg(windows)]
612 pub fn force_stop(
613 &self,
614 expected_start_time: u64,
615 timeout: std::time::Duration,
616 ) -> io::Result<bool> {
617 windows::force_stop(self, expected_start_time, timeout)
618 }
619
620 #[cfg(windows)]
625 pub fn terminate_with_exit_code(&self, exit_code: u32) -> io::Result<bool> {
626 windows::terminate_with_exit_code(self, exit_code)
627 }
628
629 #[cfg(windows)]
631 pub fn resource_usage(&self) -> Option<ResourceUsage> {
632 windows::resource_usage(self)
633 }
634
635 #[cfg(windows)]
638 pub fn cumulative_cpu_ms(&self) -> Option<u64> {
639 windows::cumulative_cpu_ms(self)
640 }
641
642 pub fn signal(&self, signal: Signal) -> io::Result<bool> {
656 #[cfg(any(target_os = "linux", target_os = "macos"))]
657 {
658 #[cfg(target_os = "linux")]
659 let result = linux::signal(self.pid, self.pidfd.as_ref(), signal);
660 #[cfg(target_os = "macos")]
661 let result = macos::signal(self.pid, signal);
662 match result {
663 Ok(()) => Ok(true),
664 Err(rustix::io::Errno::SRCH) => Ok(false),
665 Err(error) => Err(error.into()),
666 }
667 }
668 #[cfg(not(any(target_os = "linux", target_os = "macos")))]
669 {
670 let _ = signal;
671 Err(io::Error::new(
672 io::ErrorKind::Unsupported,
673 "process signalling is not available on this platform",
674 ))
675 }
676 }
677}
678
679#[cfg(all(test, any(target_os = "linux", target_os = "macos")))]
680mod tests {
681 use std::{
682 io::Read,
683 process::{Child, Command, Stdio},
684 time::{Duration, Instant},
685 };
686
687 use super::*;
688
689 fn spawn_sleep() -> Child {
690 Command::new("sleep")
691 .arg("60")
692 .spawn()
693 .expect("spawn sleep")
694 }
695
696 fn sleep_identity() -> FileIdentity {
698 let path = ["/bin/sleep", "/usr/bin/sleep"]
699 .into_iter()
700 .find(|path| Path::new(path).exists())
701 .expect("sleep is installed");
702 file_identity(Path::new(path)).expect("stat sleep")
703 }
704
705 fn wait_for_executable(process: &Process, expected: FileIdentity) -> Observation {
708 let deadline = Instant::now() + Duration::from_secs(5);
709 loop {
710 let observation = process.observe().expect("child is alive");
711 if observation.executable == Some(expected) || Instant::now() > deadline {
712 return observation;
713 }
714 std::thread::sleep(Duration::from_millis(10));
715 }
716 }
717
718 #[test]
719 fn own_process_is_observable_with_its_own_image() {
720 let process = Process::open(std::process::id())
721 .expect("open own process")
722 .expect("own process exists");
723 let observation = process.observe().expect("own process is alive");
724 let own_image = file_identity(&std::env::current_exe().unwrap()).unwrap();
725 assert_eq!(observation.executable, Some(own_image));
726 assert_eq!(start_time(std::process::id()), Some(observation.start_time));
727 }
728
729 #[test]
730 fn child_start_time_is_stable_and_differs_from_ours() {
731 let mut child = spawn_sleep();
732 let pid = child.id();
733 let process = Process::open(pid).unwrap().unwrap();
734 let observation = wait_for_executable(&process, sleep_identity());
735 assert_eq!(observation.executable, Some(sleep_identity()));
736 assert_eq!(start_time(pid), Some(observation.start_time));
737 child.kill().unwrap();
738 child.wait().unwrap();
739 }
740
741 #[test]
742 fn a_signalled_and_unreaped_child_reads_as_exited() {
743 let mut child = spawn_sleep();
744 let process = Process::open(child.id()).unwrap().unwrap();
745 assert!(process.signal(Signal::Terminate).unwrap());
746 let deadline = Instant::now() + Duration::from_secs(5);
747 while process.observe().is_some() {
748 assert!(Instant::now() < deadline, "child still observed as alive");
749 std::thread::sleep(Duration::from_millis(10));
750 }
751 assert_eq!(start_time(child.id()), None);
753 child.wait().unwrap();
754 }
755
756 #[test]
757 fn a_reaped_child_cannot_be_opened_or_observed() {
758 let mut child = spawn_sleep();
759 let pid = child.id();
760 child.kill().unwrap();
761 child.wait().unwrap();
762 if let Some(process) = Process::open(pid).unwrap() {
764 if let Some(observation) = process.observe() {
765 assert_ne!(observation.executable, Some(sleep_identity()));
766 }
767 }
768 }
769
770 #[cfg(target_os = "macos")]
774 #[test]
775 fn macos_start_time_is_microseconds_since_the_epoch() {
776 let now = std::time::SystemTime::now()
777 .duration_since(std::time::UNIX_EPOCH)
778 .unwrap()
779 .as_micros() as u64;
780 let started = start_time(std::process::id()).unwrap();
781 assert!(started <= now, "start time {started} is after now {now}");
782 assert!(
783 now - started < 3_600 * 1_000_000,
784 "start time {started} is more than an hour before now {now}"
785 );
786 }
787
788 fn thread_cpu_time() -> Duration {
792 let now = rustix::time::clock_gettime(rustix::time::ClockId::ThreadCPUTime);
793 Duration::new(now.tv_sec as u64, now.tv_nsec as u32)
794 }
795
796 fn burn_cpu(cpu: Duration) {
802 let start = thread_cpu_time();
803 let give_up = Instant::now() + Duration::from_secs(60);
804 let mut value = 0u64;
805 while thread_cpu_time().saturating_sub(start) < cpu {
806 assert!(
807 Instant::now() < give_up,
808 "thread CPU clock stopped advancing"
809 );
810 for step in 0..10_000u64 {
811 value = std::hint::black_box(value.wrapping_mul(31).wrapping_add(step));
812 }
813 }
814 std::hint::black_box(value);
815 }
816
817 #[test]
818 fn own_resource_usage_is_present_and_plausible() {
819 let pages = vec![0xa5u8; 8 * 1024 * 1024];
824 std::hint::black_box(&pages);
825 let usage = resource_usage(std::process::id()).expect("own process is readable");
826 assert!(
827 usage.memory_bytes >= pages.len() as u64,
828 "memory {} bytes cannot account for {} touched private bytes",
829 usage.memory_bytes,
830 pages.len()
831 );
832 std::hint::black_box(&pages);
833 assert!(
834 usage.memory_bytes < 64 * 1024 * 1024 * 1024,
835 "memory {} bytes is implausibly large",
836 usage.memory_bytes
837 );
838 #[cfg(target_os = "macos")]
839 assert_eq!(usage.memory_kind, MemoryKind::PhysFootprint);
840 #[cfg(target_os = "linux")]
841 {
842 assert_eq!(usage.memory_kind, MemoryKind::ResidentSet);
843 assert!(usage.swap_bytes.is_some(), "Linux reports VmSwap");
844 }
845 }
846
847 #[test]
852 fn own_cpu_time_grows_by_about_the_busy_work_done() {
853 let pid = std::process::id();
854 let total = |usage: ResourceUsage| usage.cpu_user + usage.cpu_system;
855 let before = total(resource_usage(pid).unwrap());
856 let busy = Duration::from_millis(400);
857 burn_cpu(busy);
858 let after = total(resource_usage(pid).unwrap());
859 let grown = after.saturating_sub(before);
860 assert!(
865 grown >= busy * 9 / 10,
866 "cpu time grew by {grown:?} over {busy:?} of busy work"
867 );
868 }
869
870 #[test]
871 fn a_child_reads_its_own_usage_not_ours() {
872 struct ChildGuard(Child);
873 impl Drop for ChildGuard {
874 fn drop(&mut self) {
875 let _ = self.0.kill();
876 let _ = self.0.wait();
877 }
878 }
879
880 let ours = resource_usage(std::process::id()).unwrap();
884 let bytes = usize::try_from(ours.memory_bytes)
885 .unwrap()
886 .checked_add(64 * 1024 * 1024)
887 .unwrap();
888 let scratch = cortexkit_test_support::ScratchDir::new("subc-os-resource-usage");
889 let ready = scratch.join("ready");
890 let mut child = ChildGuard(
891 Command::new(std::env::current_exe().unwrap())
892 .args([
893 "tests::resource_usage_child",
894 "--exact",
895 "--ignored",
896 "--nocapture",
897 "--test-threads=1",
898 ])
899 .env("SUBC_OS_TEST_RESOURCE_BYTES", bytes.to_string())
900 .env("SUBC_OS_TEST_RESOURCE_READY", &ready)
901 .stdin(Stdio::piped())
902 .stdout(Stdio::null())
903 .spawn()
904 .unwrap(),
905 );
906 let deadline = Instant::now() + Duration::from_secs(10);
907 while !ready.exists() {
908 assert!(child.0.try_wait().unwrap().is_none(), "memory child exited");
909 assert!(Instant::now() < deadline, "memory child never became ready");
910 std::thread::sleep(Duration::from_millis(5));
911 }
912
913 let ours = resource_usage(std::process::id()).unwrap();
914 let usage = resource_usage(child.0.id()).expect("live child is readable");
915 assert!(
918 ours.memory_bytes < bytes as u64,
919 "caller uses {} bytes, overlapping the child's {bytes} touched bytes",
920 ours.memory_bytes,
921 );
922 assert!(
923 usage.memory_bytes >= bytes as u64,
924 "child uses {} bytes, fewer than its {bytes} touched bytes (caller uses {})",
925 usage.memory_bytes,
926 ours.memory_bytes,
927 );
928 }
929
930 #[test]
931 #[ignore = "re-exec fixture retaining touched private memory until its parent closes stdin"]
932 fn resource_usage_child() {
933 let bytes: usize = std::env::var("SUBC_OS_TEST_RESOURCE_BYTES")
934 .unwrap()
935 .parse()
936 .unwrap();
937 let ready = std::env::var_os("SUBC_OS_TEST_RESOURCE_READY").unwrap();
938 let pages = vec![0xa5u8; bytes];
939 std::hint::black_box(&pages);
940 std::fs::write(ready, b"ready").unwrap();
941 let _ = std::io::stdin().read(&mut [0]);
942 std::hint::black_box(&pages);
943 }
944
945 #[test]
946 fn an_exited_child_reads_as_unavailable_not_zero() {
947 let mut child = spawn_sleep();
948 let pid = child.id();
949 child.kill().unwrap();
950 let deadline = Instant::now() + Duration::from_secs(5);
952 while start_time(pid).is_some() {
953 assert!(Instant::now() < deadline, "child still observed as alive");
954 std::thread::sleep(Duration::from_millis(10));
955 }
956 assert_eq!(resource_usage(pid), None, "a zombie reads as unavailable");
957 child.wait().unwrap();
958 if let Some(usage) = resource_usage(pid) {
961 assert!(usage.memory_bytes > 0, "a reused pid is some live process");
962 }
963 }
964
965 #[test]
966 fn a_pid_with_no_process_reads_as_unavailable() {
967 assert_eq!(resource_usage(i32::MAX as u32), None);
970 assert_eq!(resource_usage(u32::MAX), None);
972 }
973
974 #[cfg(target_os = "linux")]
975 #[test]
976 fn linux_signals_go_through_a_pidfd() {
977 let mut child = spawn_sleep();
978 let process = Process::open(child.id()).unwrap().unwrap();
979 assert!(process.signals_through_pidfd());
980 child.kill().unwrap();
981 child.wait().unwrap();
982 assert!(!process.signal(Signal::Kill).unwrap());
984 }
985}