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(windows)]
143pub mod windows_spawn;
144
145pub fn protect_current_thread() -> std::io::Result<()> {
182 #[cfg(windows)]
183 {
184 windows_acl::protect_current_thread()
185 }
186 #[cfg(not(windows))]
187 {
188 Ok(())
189 }
190}
191
192#[cfg(unix)]
193pub use launch_nonce::LaunchNonceHandoff;
194pub use launch_nonce::{
195 launch_nonce, LaunchNonce, LaunchNonceError, LaunchNonceSource, LAUNCH_NONCE_ENV,
196 LAUNCH_NONCE_FD, LAUNCH_NONCE_FD_ENV, LAUNCH_NONCE_PIPE_ENV, LAUNCH_NONCE_PIPE_FALLBACK_ENV,
197};
198
199#[cfg(windows)]
200pub use launch_nonce::{LaunchNoncePipeDelivery, LaunchNoncePipeHandoff};
201
202pub use registration_channel::{
203 registration_refusal, supervised, take_registration_channel, RegistrationChannel,
204 RegistrationChannelError, RegistrationRefusal,
205};
206
207#[cfg(target_os = "linux")]
208mod linux;
209#[cfg(target_os = "macos")]
210mod macos;
211
212#[cfg(target_os = "macos")]
213pub use macos::owned_child_start_time;
214#[cfg(windows)]
215mod windows;
216#[cfg(all(test, windows))]
217mod windows_tests;
218#[cfg(windows)]
219pub use windows::{
220 ExecutableCapture, ImageAgreement, ImageUnavailable, SpawnedImage, WindowsFileIdentity,
221};
222
223#[cfg(target_os = "linux")]
224use linux as platform;
225#[cfg(target_os = "macos")]
226use macos as platform;
227
228use std::{io, path::Path};
229
230pub const PROCESS_IDENTITY_SUPPORTED: bool =
232 cfg!(any(target_os = "linux", target_os = "macos", windows));
233
234#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
237pub struct FileIdentity {
238 pub device: u64,
239 pub inode: u64,
240}
241
242pub fn file_identity(path: &Path) -> Option<FileIdentity> {
245 #[cfg(unix)]
246 {
247 use std::os::unix::fs::MetadataExt;
248
249 std::fs::metadata(path).ok().map(|metadata| FileIdentity {
250 device: metadata.dev(),
251 inode: metadata.ino(),
252 })
253 }
254 #[cfg(not(unix))]
255 {
256 let _ = path;
257 None
258 }
259}
260
261#[derive(Debug, Clone, Copy, PartialEq, Eq)]
263pub struct Observation {
264 pub start_time: u64,
269 pub executable: Option<FileIdentity>,
274}
275
276#[derive(Debug, Clone, Copy, PartialEq, Eq)]
280pub enum ExecutableAccess {
281 Readable,
282 PermissionDenied,
283 Unavailable,
284}
285
286#[derive(Debug, Clone, Copy, PartialEq, Eq)]
288pub enum Signal {
289 Terminate,
291 Kill,
293}
294
295pub fn start_time(pid: u32) -> Option<u64> {
299 #[cfg(any(target_os = "linux", target_os = "macos"))]
300 {
301 platform::start_time(pid)
302 }
303 #[cfg(windows)]
304 {
305 Process::open(pid)
306 .ok()??
307 .observe()
308 .map(|observation| observation.start_time)
309 }
310 #[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
311 {
312 let _ = pid;
313 None
314 }
315}
316
317#[derive(Clone, Copy, Debug, PartialEq, Eq)]
319pub(crate) enum IdentityRead {
320 Alive(u64),
321 #[cfg_attr(windows, allow(dead_code))]
322 Gone,
324 Unknown,
325}
326
327#[cfg(all(test, any(target_os = "linux", target_os = "macos")))]
328mod identity_read_tests {
329 use super::*;
330
331 #[test]
332 fn identity_probe_distinguishes_alive_gone_and_invalid() {
333 let mut child = std::process::Command::new("/bin/sh")
334 .args(["-c", "exit 0"])
335 .spawn()
336 .unwrap();
337 let pid = child.id();
338 let until = std::time::Instant::now() + std::time::Duration::from_secs(5);
339 while read_identity(pid) != IdentityRead::Gone {
340 assert!(
341 std::time::Instant::now() < until,
342 "an exited owned child must become gone before reaping"
343 );
344 std::thread::yield_now();
345 }
346 child.wait().unwrap();
347 assert_eq!(
348 read_identity(pid),
349 IdentityRead::Gone,
350 "a missing owned PID is gone"
351 );
352 assert_eq!(read_identity(0), IdentityRead::Unknown);
353 assert!(matches!(
354 read_identity(std::process::id()),
355 IdentityRead::Alive(_)
356 ));
357 }
358}
359
360#[cfg(not(windows))]
361fn read_identity(pid: u32) -> IdentityRead {
362 #[cfg(any(target_os = "linux", target_os = "macos"))]
363 {
364 platform::read_identity(pid)
365 }
366 #[cfg(not(any(target_os = "linux", target_os = "macos")))]
367 {
368 start_time(pid).map_or(IdentityRead::Unknown, IdentityRead::Alive)
369 }
370}
371
372mod process_tree;
373pub use process_tree::{BirthBaseline, ProcessGroup, ProcessMember, ProcessTable, TreeUsage};
374
375pub fn process_start_time_ms(pid: u32) -> Option<u64> {
383 start_time_ms_from_native(start_time(pid)?)
384}
385
386fn start_time_ms_from_native(raw: u64) -> Option<u64> {
387 #[cfg(target_os = "linux")]
388 {
389 linux_start_time_ms(raw, || std::fs::read_to_string("/proc/stat").ok())
390 }
391 #[cfg(target_os = "macos")]
392 {
393 Some(raw / 1_000)
394 }
395 #[cfg(windows)]
396 {
397 (raw / 10_000).checked_sub(11_644_473_600_000)
398 }
399 #[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
400 {
401 let _ = raw;
402 None
403 }
404}
405
406#[cfg(target_os = "linux")]
407fn linux_start_time_ms(raw: u64, read_boot: impl FnOnce() -> Option<String>) -> Option<u64> {
408 let boot = read_boot()?
412 .lines()
413 .find_map(|line| line.strip_prefix("btime ")?.parse::<u64>().ok())?;
414 boot.checked_mul(1_000)?
415 .checked_add(raw.checked_mul(1_000)? / rustix::param::clock_ticks_per_second().max(1))
416}
417
418#[cfg(all(test, target_os = "linux"))]
419#[test]
420fn linux_start_identity_uses_fresh_boot_time_after_clock_step() {
421 let before = linux_start_time_ms(100, || Some("btime 1000\n".into())).unwrap();
422 let after = linux_start_time_ms(100, || Some("btime 1002\n".into())).unwrap();
423 assert_eq!(after - before, 2_000);
424}
425
426pub fn process_start_time_precision_ms() -> u64 {
428 #[cfg(target_os = "linux")]
429 {
430 1_000_u64.div_ceil(rustix::param::clock_ticks_per_second().max(1))
431 }
432 #[cfg(not(target_os = "linux"))]
433 {
434 1
435 }
436}
437
438pub fn parent_pid(pid: u32) -> Option<u32> {
441 #[cfg(any(target_os = "linux", target_os = "macos"))]
442 {
443 platform::parent_pid(pid)
444 }
445 #[cfg(windows)]
446 {
447 windows::parent_pid(pid)
448 }
449 #[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
450 {
451 let _ = pid;
452 None
453 }
454}
455
456pub const RESOURCE_USAGE_SUPPORTED: bool =
460 cfg!(any(target_os = "linux", target_os = "macos", windows));
461
462#[derive(Debug, Clone, Copy, PartialEq, Eq)]
465pub enum MemoryKind {
466 PhysFootprint,
470 ResidentSet,
474 WindowsWorkingSet,
477}
478
479#[derive(Debug, Clone, Copy, PartialEq, Eq)]
484pub struct ResourceUsage {
485 pub memory_bytes: u64,
487 pub memory_kind: MemoryKind,
488 pub swap_bytes: Option<u64>,
491 pub cpu_user: std::time::Duration,
493 pub cpu_system: std::time::Duration,
495}
496
497pub fn resource_usage(pid: u32) -> Option<ResourceUsage> {
509 #[cfg(any(target_os = "linux", target_os = "macos"))]
510 {
511 platform::resource_usage(pid)
512 }
513 #[cfg(windows)]
514 {
515 Process::open(pid).ok()??.resource_usage()
516 }
517 #[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
518 {
519 let _ = pid;
520 None
521 }
522}
523
524#[derive(Debug)]
526pub struct Process {
527 pid: u32,
528 #[cfg(target_os = "linux")]
529 pidfd: Option<std::os::fd::OwnedFd>,
530 #[cfg(windows)]
531 handle: std::os::windows::io::OwnedHandle,
532}
533
534impl Process {
535 pub fn open(pid: u32) -> io::Result<Option<Self>> {
545 #[cfg(target_os = "linux")]
546 {
547 linux::open(pid).map(|opened| opened.map(|pidfd| Self { pid, pidfd }))
548 }
549 #[cfg(target_os = "macos")]
550 {
551 Ok(platform::exists(pid).then_some(Self { pid }))
552 }
553 #[cfg(windows)]
554 {
555 windows::open(pid).map(|opened| opened.map(|handle| Self { pid, handle }))
556 }
557 #[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
558 {
559 let _ = pid;
560 Err(io::Error::new(
561 io::ErrorKind::Unsupported,
562 "process identity is not available on this platform",
563 ))
564 }
565 }
566
567 pub fn pid(&self) -> u32 {
568 self.pid
569 }
570
571 pub fn signals_through_pidfd(&self) -> bool {
574 #[cfg(target_os = "linux")]
575 {
576 self.pidfd.is_some()
577 }
578 #[cfg(not(target_os = "linux"))]
579 {
580 false
581 }
582 }
583
584 pub fn observe(&self) -> Option<Observation> {
588 self.observe_with_executable_access()
589 .map(|(observed, _)| observed)
590 }
591
592 pub fn is_alive_but_unobservable(&self) -> bool {
596 #[cfg(target_os = "linux")]
597 {
598 linux::alive_but_unobservable(self.pid, self.pidfd.as_ref())
599 }
600 #[cfg(not(target_os = "linux"))]
601 {
602 false
603 }
604 }
605
606 pub fn observe_with_executable_access(&self) -> Option<(Observation, ExecutableAccess)> {
610 #[cfg(any(target_os = "linux", target_os = "macos"))]
611 {
612 #[cfg(target_os = "linux")]
613 if !linux::pidfd_alive(self.pidfd.as_ref()) {
614 return None;
615 }
616 let start_time = platform::start_time(self.pid)?;
617 #[cfg(target_os = "linux")]
618 let (executable, access) = match linux::executable_identity(self.pid) {
619 Ok(identity) => (Some(identity), ExecutableAccess::Readable),
620 Err(error) if error.kind() == io::ErrorKind::PermissionDenied => {
621 (None, ExecutableAccess::PermissionDenied)
622 }
623 Err(_) => (None, ExecutableAccess::Unavailable),
624 };
625 #[cfg(target_os = "macos")]
626 let executable = macos::executable_identity(self.pid);
627 #[cfg(target_os = "macos")]
628 let access = if executable.is_some() {
629 ExecutableAccess::Readable
630 } else {
631 ExecutableAccess::Unavailable
632 };
633 Some((
634 Observation {
635 start_time,
636 executable,
637 },
638 access,
639 ))
640 }
641 #[cfg(windows)]
642 {
643 windows::observe(self).map(|observed| (observed, ExecutableAccess::Unavailable))
644 }
645 #[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
646 {
647 None
648 }
649 }
650
651 #[cfg(windows)]
654 pub fn wait_for_exit(&self, timeout: std::time::Duration) -> io::Result<bool> {
655 windows::wait(self, timeout)
656 }
657
658 #[cfg(windows)]
662 pub fn force_stop(
663 &self,
664 expected_start_time: u64,
665 timeout: std::time::Duration,
666 ) -> io::Result<bool> {
667 windows::force_stop(self, expected_start_time, timeout)
668 }
669
670 #[cfg(windows)]
675 pub fn terminate_with_exit_code(&self, exit_code: u32) -> io::Result<bool> {
676 windows::terminate_with_exit_code(self, exit_code)
677 }
678
679 #[cfg(windows)]
681 pub fn resource_usage(&self) -> Option<ResourceUsage> {
682 windows::resource_usage(self)
683 }
684
685 #[cfg(windows)]
688 pub fn cumulative_cpu_ms(&self) -> Option<u64> {
689 windows::cumulative_cpu_ms(self)
690 }
691
692 pub fn signal(&self, signal: Signal) -> io::Result<bool> {
706 #[cfg(any(target_os = "linux", target_os = "macos"))]
707 {
708 #[cfg(target_os = "linux")]
709 let result = linux::signal(self.pid, self.pidfd.as_ref(), signal);
710 #[cfg(target_os = "macos")]
711 let result = macos::signal(self.pid, signal);
712 match result {
713 Ok(()) => Ok(true),
714 Err(rustix::io::Errno::SRCH) => Ok(false),
715 Err(error) => Err(error.into()),
716 }
717 }
718 #[cfg(not(any(target_os = "linux", target_os = "macos")))]
719 {
720 let _ = signal;
721 Err(io::Error::new(
722 io::ErrorKind::Unsupported,
723 "process signalling is not available on this platform",
724 ))
725 }
726 }
727}
728
729#[cfg(all(test, any(target_os = "linux", target_os = "macos")))]
730mod tests {
731 use std::{
732 io::Read,
733 process::{Child, Command, Stdio},
734 time::{Duration, Instant},
735 };
736
737 use super::*;
738
739 fn spawn_sleep() -> Child {
740 Command::new("sleep")
741 .arg("60")
742 .spawn()
743 .expect("spawn sleep")
744 }
745
746 fn sleep_identity() -> FileIdentity {
748 let path = ["/bin/sleep", "/usr/bin/sleep"]
749 .into_iter()
750 .find(|path| Path::new(path).exists())
751 .expect("sleep is installed");
752 file_identity(Path::new(path)).expect("stat sleep")
753 }
754
755 fn wait_for_executable(process: &Process, expected: FileIdentity) -> Observation {
758 let deadline = Instant::now() + Duration::from_secs(5);
759 loop {
760 let observation = process.observe().expect("child is alive");
761 if observation.executable == Some(expected) || Instant::now() > deadline {
762 return observation;
763 }
764 std::thread::sleep(Duration::from_millis(10));
765 }
766 }
767
768 #[test]
769 fn own_process_is_observable_with_its_own_image() {
770 let process = Process::open(std::process::id())
771 .expect("open own process")
772 .expect("own process exists");
773 let observation = process.observe().expect("own process is alive");
774 let own_image = file_identity(&std::env::current_exe().unwrap()).unwrap();
775 assert_eq!(observation.executable, Some(own_image));
776 assert_eq!(start_time(std::process::id()), Some(observation.start_time));
777 }
778
779 #[test]
780 fn child_start_time_is_stable_and_differs_from_ours() {
781 let mut child = spawn_sleep();
782 let pid = child.id();
783 let process = Process::open(pid).unwrap().unwrap();
784 let observation = wait_for_executable(&process, sleep_identity());
785 assert_eq!(observation.executable, Some(sleep_identity()));
786 assert_eq!(start_time(pid), Some(observation.start_time));
787 child.kill().unwrap();
788 child.wait().unwrap();
789 }
790
791 #[test]
792 fn a_signalled_and_unreaped_child_reads_as_exited() {
793 let mut child = spawn_sleep();
794 let process = Process::open(child.id()).unwrap().unwrap();
795 assert!(process.signal(Signal::Terminate).unwrap());
796 let deadline = Instant::now() + Duration::from_secs(5);
797 while process.observe().is_some() {
798 assert!(Instant::now() < deadline, "child still observed as alive");
799 std::thread::sleep(Duration::from_millis(10));
800 }
801 assert_eq!(start_time(child.id()), None);
803 child.wait().unwrap();
804 }
805
806 #[test]
807 fn a_reaped_child_cannot_be_opened_or_observed() {
808 let mut child = spawn_sleep();
809 let pid = child.id();
810 child.kill().unwrap();
811 child.wait().unwrap();
812 if let Some(process) = Process::open(pid).unwrap() {
814 if let Some(observation) = process.observe() {
815 assert_ne!(observation.executable, Some(sleep_identity()));
816 }
817 }
818 }
819
820 #[cfg(target_os = "macos")]
824 #[test]
825 fn macos_start_time_is_microseconds_since_the_epoch() {
826 let now = std::time::SystemTime::now()
827 .duration_since(std::time::UNIX_EPOCH)
828 .unwrap()
829 .as_micros() as u64;
830 let started = start_time(std::process::id()).unwrap();
831 assert!(started <= now, "start time {started} is after now {now}");
832 assert!(
833 now - started < 3_600 * 1_000_000,
834 "start time {started} is more than an hour before now {now}"
835 );
836 }
837
838 fn thread_cpu_time() -> Duration {
842 let now = rustix::time::clock_gettime(rustix::time::ClockId::ThreadCPUTime);
843 Duration::new(now.tv_sec as u64, now.tv_nsec as u32)
844 }
845
846 fn burn_cpu(cpu: Duration) {
852 let start = thread_cpu_time();
853 let give_up = Instant::now() + Duration::from_secs(60);
854 let mut value = 0u64;
855 while thread_cpu_time().saturating_sub(start) < cpu {
856 assert!(
857 Instant::now() < give_up,
858 "thread CPU clock stopped advancing"
859 );
860 for step in 0..10_000u64 {
861 value = std::hint::black_box(value.wrapping_mul(31).wrapping_add(step));
862 }
863 }
864 std::hint::black_box(value);
865 }
866
867 #[test]
868 fn own_resource_usage_is_present_and_plausible() {
869 let pages = vec![0xa5u8; 8 * 1024 * 1024];
874 std::hint::black_box(&pages);
875 let usage = resource_usage(std::process::id()).expect("own process is readable");
876 assert!(
877 usage.memory_bytes >= pages.len() as u64,
878 "memory {} bytes cannot account for {} touched private bytes",
879 usage.memory_bytes,
880 pages.len()
881 );
882 std::hint::black_box(&pages);
883 assert!(
884 usage.memory_bytes < 64 * 1024 * 1024 * 1024,
885 "memory {} bytes is implausibly large",
886 usage.memory_bytes
887 );
888 #[cfg(target_os = "macos")]
889 assert_eq!(usage.memory_kind, MemoryKind::PhysFootprint);
890 #[cfg(target_os = "linux")]
891 {
892 assert_eq!(usage.memory_kind, MemoryKind::ResidentSet);
893 assert!(usage.swap_bytes.is_some(), "Linux reports VmSwap");
894 }
895 }
896
897 #[test]
902 fn own_cpu_time_grows_by_about_the_busy_work_done() {
903 let pid = std::process::id();
904 let total = |usage: ResourceUsage| usage.cpu_user + usage.cpu_system;
905 let before = total(resource_usage(pid).unwrap());
906 let busy = Duration::from_millis(400);
907 burn_cpu(busy);
908 let after = total(resource_usage(pid).unwrap());
909 let grown = after.saturating_sub(before);
910 assert!(
915 grown >= busy * 9 / 10,
916 "cpu time grew by {grown:?} over {busy:?} of busy work"
917 );
918 }
919
920 #[test]
921 fn a_child_reads_its_own_usage_not_ours() {
922 struct ChildGuard(Child);
923 impl Drop for ChildGuard {
924 fn drop(&mut self) {
925 let _ = self.0.kill();
926 let _ = self.0.wait();
927 }
928 }
929
930 let ours = resource_usage(std::process::id()).unwrap();
934 let bytes = usize::try_from(ours.memory_bytes)
935 .unwrap()
936 .checked_add(64 * 1024 * 1024)
937 .unwrap();
938 let scratch = cortexkit_test_support::ScratchDir::new("subc-os-resource-usage");
939 let ready = scratch.join("ready");
940 let mut child = ChildGuard(
941 Command::new(std::env::current_exe().unwrap())
942 .args([
943 "tests::resource_usage_child",
944 "--exact",
945 "--ignored",
946 "--nocapture",
947 "--test-threads=1",
948 ])
949 .env("SUBC_OS_TEST_RESOURCE_BYTES", bytes.to_string())
950 .env("SUBC_OS_TEST_RESOURCE_READY", &ready)
951 .stdin(Stdio::piped())
952 .stdout(Stdio::null())
953 .spawn()
954 .unwrap(),
955 );
956 let deadline = Instant::now() + Duration::from_secs(10);
957 while !ready.exists() {
958 assert!(child.0.try_wait().unwrap().is_none(), "memory child exited");
959 assert!(Instant::now() < deadline, "memory child never became ready");
960 std::thread::sleep(Duration::from_millis(5));
961 }
962
963 let ours = resource_usage(std::process::id()).unwrap();
964 let usage = resource_usage(child.0.id()).expect("live child is readable");
965 assert!(
968 ours.memory_bytes < bytes as u64,
969 "caller uses {} bytes, overlapping the child's {bytes} touched bytes",
970 ours.memory_bytes,
971 );
972 assert!(
973 usage.memory_bytes >= bytes as u64,
974 "child uses {} bytes, fewer than its {bytes} touched bytes (caller uses {})",
975 usage.memory_bytes,
976 ours.memory_bytes,
977 );
978 }
979
980 #[test]
981 #[ignore = "re-exec fixture retaining touched private memory until its parent closes stdin"]
982 fn resource_usage_child() {
983 let bytes: usize = std::env::var("SUBC_OS_TEST_RESOURCE_BYTES")
984 .unwrap()
985 .parse()
986 .unwrap();
987 let ready = std::env::var_os("SUBC_OS_TEST_RESOURCE_READY").unwrap();
988 let pages = vec![0xa5u8; bytes];
989 std::hint::black_box(&pages);
990 std::fs::write(ready, b"ready").unwrap();
991 let _ = std::io::stdin().read(&mut [0]);
992 std::hint::black_box(&pages);
993 }
994
995 #[test]
996 fn an_exited_child_reads_as_unavailable_not_zero() {
997 let mut child = spawn_sleep();
998 let pid = child.id();
999 child.kill().unwrap();
1000 let deadline = Instant::now() + Duration::from_secs(5);
1002 while start_time(pid).is_some() {
1003 assert!(Instant::now() < deadline, "child still observed as alive");
1004 std::thread::sleep(Duration::from_millis(10));
1005 }
1006 assert_eq!(resource_usage(pid), None, "a zombie reads as unavailable");
1007 child.wait().unwrap();
1008 if let Some(usage) = resource_usage(pid) {
1011 assert!(usage.memory_bytes > 0, "a reused pid is some live process");
1012 }
1013 }
1014
1015 #[test]
1016 fn a_pid_with_no_process_reads_as_unavailable() {
1017 assert_eq!(resource_usage(i32::MAX as u32), None);
1020 assert_eq!(resource_usage(u32::MAX), None);
1022 }
1023
1024 #[cfg(target_os = "linux")]
1025 #[test]
1026 fn linux_signals_go_through_a_pidfd() {
1027 let mut child = spawn_sleep();
1028 let process = Process::open(child.id()).unwrap().unwrap();
1029 assert!(process.signals_through_pidfd());
1030 child.kill().unwrap();
1031 child.wait().unwrap();
1032 assert!(!process.signal(Signal::Kill).unwrap());
1034 }
1035}