#![deny(unsafe_code)]
#[cfg(target_os = "macos")]
mod darwin_user_temp;
#[cfg(target_os = "macos")]
pub use darwin_user_temp::darwin_user_temp_dir;
#[cfg(windows)]
mod profile;
#[cfg(windows)]
pub use profile::profile_dir;
#[cfg(unix)]
mod user_home;
#[cfg(unix)]
pub use user_home::{effective_uid, real_user_home_dir};
#[cfg(unix)]
pub mod admission_gate;
pub mod boot_id;
#[cfg(unix)]
pub mod child_exit;
pub mod child_spawn;
#[cfg(target_os = "macos")]
pub mod code_signature;
pub mod config_keychain;
mod durable_replace;
#[cfg(any(unix, windows))]
mod retained_file;
#[cfg(feature = "test-support")]
pub use durable_replace::durable_replace_with_rename_hook;
pub use durable_replace::{durable_replace, DurableReplaceError};
#[cfg(any(unix, windows))]
pub use retained_file::{
open_regular_nofollow, open_regular_nofollow_all, retained_file_identity, OpenRegularError,
RetainedFileIdentity,
};
#[cfg(all(unix, feature = "test-support"))]
pub mod fork_exec_test;
pub mod host;
pub mod launch_nonce;
pub mod local_peer;
pub mod named_pipe;
pub mod privacy_identity;
#[cfg(unix)]
pub mod process_group;
pub mod process_identity;
pub mod registration_channel;
pub mod script_pipe;
pub mod socket_peer;
#[cfg_attr(not(windows), path = "windows_acl_noop.rs")]
pub mod windows_acl;
#[cfg(unix)]
pub use launch_nonce::LaunchNonceHandoff;
pub use launch_nonce::{
launch_nonce, LaunchNonce, LaunchNonceError, LaunchNonceSource, LAUNCH_NONCE_ENV,
LAUNCH_NONCE_FD, LAUNCH_NONCE_FD_ENV, LAUNCH_NONCE_PIPE_ENV, LAUNCH_NONCE_PIPE_FALLBACK_ENV,
};
#[cfg(windows)]
pub use launch_nonce::{LaunchNoncePipeDelivery, LaunchNoncePipeHandoff};
pub use registration_channel::{
registration_refusal, supervised, take_registration_channel, RegistrationChannel,
RegistrationChannelError, RegistrationRefusal,
};
#[cfg(target_os = "linux")]
mod linux;
#[cfg(target_os = "macos")]
mod macos;
#[cfg(target_os = "macos")]
pub use macos::owned_child_start_time;
#[cfg(windows)]
mod windows;
#[cfg(all(test, windows))]
mod windows_tests;
#[cfg(windows)]
pub use windows::{
ExecutableCapture, ImageAgreement, ImageUnavailable, SpawnedImage, WindowsFileIdentity,
};
#[cfg(target_os = "linux")]
use linux as platform;
#[cfg(target_os = "macos")]
use macos as platform;
use std::{io, path::Path};
pub const PROCESS_IDENTITY_SUPPORTED: bool =
cfg!(any(target_os = "linux", target_os = "macos", windows));
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct FileIdentity {
pub device: u64,
pub inode: u64,
}
pub fn file_identity(path: &Path) -> Option<FileIdentity> {
#[cfg(unix)]
{
use std::os::unix::fs::MetadataExt;
std::fs::metadata(path).ok().map(|metadata| FileIdentity {
device: metadata.dev(),
inode: metadata.ino(),
})
}
#[cfg(not(unix))]
{
let _ = path;
None
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Observation {
pub start_time: u64,
pub executable: Option<FileIdentity>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ExecutableAccess {
Readable,
PermissionDenied,
Unavailable,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Signal {
Terminate,
Kill,
}
pub fn start_time(pid: u32) -> Option<u64> {
#[cfg(any(target_os = "linux", target_os = "macos"))]
{
platform::start_time(pid)
}
#[cfg(windows)]
{
Process::open(pid)
.ok()??
.observe()
.map(|observation| observation.start_time)
}
#[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
{
let _ = pid;
None
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum IdentityRead {
Alive(u64),
#[cfg_attr(windows, allow(dead_code))]
Gone,
Unknown,
}
#[cfg(all(test, any(target_os = "linux", target_os = "macos")))]
mod identity_read_tests {
use super::*;
#[test]
fn identity_probe_distinguishes_alive_gone_and_invalid() {
let mut child = std::process::Command::new("/bin/sh")
.args(["-c", "exit 0"])
.spawn()
.unwrap();
let pid = child.id();
let until = std::time::Instant::now() + std::time::Duration::from_secs(5);
while read_identity(pid) != IdentityRead::Gone {
assert!(
std::time::Instant::now() < until,
"an exited owned child must become gone before reaping"
);
std::thread::yield_now();
}
child.wait().unwrap();
assert_eq!(
read_identity(pid),
IdentityRead::Gone,
"a missing owned PID is gone"
);
assert_eq!(read_identity(0), IdentityRead::Unknown);
assert!(matches!(
read_identity(std::process::id()),
IdentityRead::Alive(_)
));
}
}
#[cfg(not(windows))]
fn read_identity(pid: u32) -> IdentityRead {
#[cfg(any(target_os = "linux", target_os = "macos"))]
{
platform::read_identity(pid)
}
#[cfg(not(any(target_os = "linux", target_os = "macos")))]
{
start_time(pid).map_or(IdentityRead::Unknown, IdentityRead::Alive)
}
}
mod process_tree;
pub use process_tree::{ProcessGroup, ProcessMember, ProcessTable, TreeUsage};
pub fn process_start_time_ms(pid: u32) -> Option<u64> {
start_time_ms_from_native(start_time(pid)?)
}
fn start_time_ms_from_native(raw: u64) -> Option<u64> {
#[cfg(target_os = "linux")]
{
linux_start_time_ms(raw, || std::fs::read_to_string("/proc/stat").ok())
}
#[cfg(target_os = "macos")]
{
Some(raw / 1_000)
}
#[cfg(windows)]
{
(raw / 10_000).checked_sub(11_644_473_600_000)
}
#[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
{
let _ = raw;
None
}
}
#[cfg(target_os = "linux")]
fn linux_start_time_ms(raw: u64, read_boot: impl FnOnce() -> Option<String>) -> Option<u64> {
let boot = read_boot()?
.lines()
.find_map(|line| line.strip_prefix("btime ")?.parse::<u64>().ok())?;
boot.checked_mul(1_000)?
.checked_add(raw.checked_mul(1_000)? / rustix::param::clock_ticks_per_second().max(1))
}
#[cfg(all(test, target_os = "linux"))]
#[test]
fn linux_start_identity_uses_fresh_boot_time_after_clock_step() {
let before = linux_start_time_ms(100, || Some("btime 1000\n".into())).unwrap();
let after = linux_start_time_ms(100, || Some("btime 1002\n".into())).unwrap();
assert_eq!(after - before, 2_000);
}
pub fn process_start_time_precision_ms() -> u64 {
#[cfg(target_os = "linux")]
{
1_000_u64.div_ceil(rustix::param::clock_ticks_per_second().max(1))
}
#[cfg(not(target_os = "linux"))]
{
1
}
}
pub fn parent_pid(pid: u32) -> Option<u32> {
#[cfg(any(target_os = "linux", target_os = "macos"))]
{
platform::parent_pid(pid)
}
#[cfg(windows)]
{
windows::parent_pid(pid)
}
#[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
{
let _ = pid;
None
}
}
pub const RESOURCE_USAGE_SUPPORTED: bool =
cfg!(any(target_os = "linux", target_os = "macos", windows));
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MemoryKind {
PhysFootprint,
ResidentSet,
WindowsWorkingSet,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ResourceUsage {
pub memory_bytes: u64,
pub memory_kind: MemoryKind,
pub swap_bytes: Option<u64>,
pub cpu_user: std::time::Duration,
pub cpu_system: std::time::Duration,
}
pub fn resource_usage(pid: u32) -> Option<ResourceUsage> {
#[cfg(any(target_os = "linux", target_os = "macos"))]
{
platform::resource_usage(pid)
}
#[cfg(windows)]
{
Process::open(pid).ok()??.resource_usage()
}
#[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
{
let _ = pid;
None
}
}
#[derive(Debug)]
pub struct Process {
pid: u32,
#[cfg(target_os = "linux")]
pidfd: Option<std::os::fd::OwnedFd>,
#[cfg(windows)]
handle: std::os::windows::io::OwnedHandle,
}
impl Process {
pub fn open(pid: u32) -> io::Result<Option<Self>> {
#[cfg(target_os = "linux")]
{
linux::open(pid).map(|opened| opened.map(|pidfd| Self { pid, pidfd }))
}
#[cfg(target_os = "macos")]
{
Ok(platform::exists(pid).then_some(Self { pid }))
}
#[cfg(windows)]
{
windows::open(pid).map(|opened| opened.map(|handle| Self { pid, handle }))
}
#[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
{
let _ = pid;
Err(io::Error::new(
io::ErrorKind::Unsupported,
"process identity is not available on this platform",
))
}
}
pub fn pid(&self) -> u32 {
self.pid
}
pub fn signals_through_pidfd(&self) -> bool {
#[cfg(target_os = "linux")]
{
self.pidfd.is_some()
}
#[cfg(not(target_os = "linux"))]
{
false
}
}
pub fn observe(&self) -> Option<Observation> {
self.observe_with_executable_access()
.map(|(observed, _)| observed)
}
pub fn is_alive_but_unobservable(&self) -> bool {
#[cfg(target_os = "linux")]
{
linux::alive_but_unobservable(self.pid, self.pidfd.as_ref())
}
#[cfg(not(target_os = "linux"))]
{
false
}
}
pub fn observe_with_executable_access(&self) -> Option<(Observation, ExecutableAccess)> {
#[cfg(any(target_os = "linux", target_os = "macos"))]
{
#[cfg(target_os = "linux")]
if !linux::pidfd_alive(self.pidfd.as_ref()) {
return None;
}
let start_time = platform::start_time(self.pid)?;
#[cfg(target_os = "linux")]
let (executable, access) = match linux::executable_identity(self.pid) {
Ok(identity) => (Some(identity), ExecutableAccess::Readable),
Err(error) if error.kind() == io::ErrorKind::PermissionDenied => {
(None, ExecutableAccess::PermissionDenied)
}
Err(_) => (None, ExecutableAccess::Unavailable),
};
#[cfg(target_os = "macos")]
let executable = macos::executable_identity(self.pid);
#[cfg(target_os = "macos")]
let access = if executable.is_some() {
ExecutableAccess::Readable
} else {
ExecutableAccess::Unavailable
};
Some((
Observation {
start_time,
executable,
},
access,
))
}
#[cfg(windows)]
{
windows::observe(self).map(|observed| (observed, ExecutableAccess::Unavailable))
}
#[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
{
None
}
}
#[cfg(windows)]
pub fn wait_for_exit(&self, timeout: std::time::Duration) -> io::Result<bool> {
windows::wait(self, timeout)
}
#[cfg(windows)]
pub fn force_stop(
&self,
expected_start_time: u64,
timeout: std::time::Duration,
) -> io::Result<bool> {
windows::force_stop(self, expected_start_time, timeout)
}
#[cfg(windows)]
pub fn terminate_with_exit_code(&self, exit_code: u32) -> io::Result<bool> {
windows::terminate_with_exit_code(self, exit_code)
}
#[cfg(windows)]
pub fn resource_usage(&self) -> Option<ResourceUsage> {
windows::resource_usage(self)
}
#[cfg(windows)]
pub fn cumulative_cpu_ms(&self) -> Option<u64> {
windows::cumulative_cpu_ms(self)
}
pub fn signal(&self, signal: Signal) -> io::Result<bool> {
#[cfg(any(target_os = "linux", target_os = "macos"))]
{
#[cfg(target_os = "linux")]
let result = linux::signal(self.pid, self.pidfd.as_ref(), signal);
#[cfg(target_os = "macos")]
let result = macos::signal(self.pid, signal);
match result {
Ok(()) => Ok(true),
Err(rustix::io::Errno::SRCH) => Ok(false),
Err(error) => Err(error.into()),
}
}
#[cfg(not(any(target_os = "linux", target_os = "macos")))]
{
let _ = signal;
Err(io::Error::new(
io::ErrorKind::Unsupported,
"process signalling is not available on this platform",
))
}
}
}
#[cfg(all(test, any(target_os = "linux", target_os = "macos")))]
mod tests {
use std::{
io::Read,
process::{Child, Command, Stdio},
time::{Duration, Instant},
};
use super::*;
fn spawn_sleep() -> Child {
Command::new("sleep")
.arg("60")
.spawn()
.expect("spawn sleep")
}
fn sleep_identity() -> FileIdentity {
let path = ["/bin/sleep", "/usr/bin/sleep"]
.into_iter()
.find(|path| Path::new(path).exists())
.expect("sleep is installed");
file_identity(Path::new(path)).expect("stat sleep")
}
fn wait_for_executable(process: &Process, expected: FileIdentity) -> Observation {
let deadline = Instant::now() + Duration::from_secs(5);
loop {
let observation = process.observe().expect("child is alive");
if observation.executable == Some(expected) || Instant::now() > deadline {
return observation;
}
std::thread::sleep(Duration::from_millis(10));
}
}
#[test]
fn own_process_is_observable_with_its_own_image() {
let process = Process::open(std::process::id())
.expect("open own process")
.expect("own process exists");
let observation = process.observe().expect("own process is alive");
let own_image = file_identity(&std::env::current_exe().unwrap()).unwrap();
assert_eq!(observation.executable, Some(own_image));
assert_eq!(start_time(std::process::id()), Some(observation.start_time));
}
#[test]
fn child_start_time_is_stable_and_differs_from_ours() {
let mut child = spawn_sleep();
let pid = child.id();
let process = Process::open(pid).unwrap().unwrap();
let observation = wait_for_executable(&process, sleep_identity());
assert_eq!(observation.executable, Some(sleep_identity()));
assert_eq!(start_time(pid), Some(observation.start_time));
child.kill().unwrap();
child.wait().unwrap();
}
#[test]
fn a_signalled_and_unreaped_child_reads_as_exited() {
let mut child = spawn_sleep();
let process = Process::open(child.id()).unwrap().unwrap();
assert!(process.signal(Signal::Terminate).unwrap());
let deadline = Instant::now() + Duration::from_secs(5);
while process.observe().is_some() {
assert!(Instant::now() < deadline, "child still observed as alive");
std::thread::sleep(Duration::from_millis(10));
}
assert_eq!(start_time(child.id()), None);
child.wait().unwrap();
}
#[test]
fn a_reaped_child_cannot_be_opened_or_observed() {
let mut child = spawn_sleep();
let pid = child.id();
child.kill().unwrap();
child.wait().unwrap();
if let Some(process) = Process::open(pid).unwrap() {
if let Some(observation) = process.observe() {
assert_ne!(observation.executable, Some(sleep_identity()));
}
}
}
#[cfg(target_os = "macos")]
#[test]
fn macos_start_time_is_microseconds_since_the_epoch() {
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_micros() as u64;
let started = start_time(std::process::id()).unwrap();
assert!(started <= now, "start time {started} is after now {now}");
assert!(
now - started < 3_600 * 1_000_000,
"start time {started} is more than an hour before now {now}"
);
}
fn thread_cpu_time() -> Duration {
let now = rustix::time::clock_gettime(rustix::time::ClockId::ThreadCPUTime);
Duration::new(now.tv_sec as u64, now.tv_nsec as u32)
}
fn burn_cpu(cpu: Duration) {
let start = thread_cpu_time();
let give_up = Instant::now() + Duration::from_secs(60);
let mut value = 0u64;
while thread_cpu_time().saturating_sub(start) < cpu {
assert!(
Instant::now() < give_up,
"thread CPU clock stopped advancing"
);
for step in 0..10_000u64 {
value = std::hint::black_box(value.wrapping_mul(31).wrapping_add(step));
}
}
std::hint::black_box(value);
}
#[test]
fn own_resource_usage_is_present_and_plausible() {
let pages = vec![0xa5u8; 8 * 1024 * 1024];
std::hint::black_box(&pages);
let usage = resource_usage(std::process::id()).expect("own process is readable");
assert!(
usage.memory_bytes >= pages.len() as u64,
"memory {} bytes cannot account for {} touched private bytes",
usage.memory_bytes,
pages.len()
);
std::hint::black_box(&pages);
assert!(
usage.memory_bytes < 64 * 1024 * 1024 * 1024,
"memory {} bytes is implausibly large",
usage.memory_bytes
);
#[cfg(target_os = "macos")]
assert_eq!(usage.memory_kind, MemoryKind::PhysFootprint);
#[cfg(target_os = "linux")]
{
assert_eq!(usage.memory_kind, MemoryKind::ResidentSet);
assert!(usage.swap_bytes.is_some(), "Linux reports VmSwap");
}
}
#[test]
fn own_cpu_time_grows_by_about_the_busy_work_done() {
let pid = std::process::id();
let total = |usage: ResourceUsage| usage.cpu_user + usage.cpu_system;
let before = total(resource_usage(pid).unwrap());
let busy = Duration::from_millis(400);
burn_cpu(busy);
let after = total(resource_usage(pid).unwrap());
let grown = after.saturating_sub(before);
assert!(
grown >= busy * 9 / 10,
"cpu time grew by {grown:?} over {busy:?} of busy work"
);
}
#[test]
fn a_child_reads_its_own_usage_not_ours() {
struct ChildGuard(Child);
impl Drop for ChildGuard {
fn drop(&mut self) {
let _ = self.0.kill();
let _ = self.0.wait();
}
}
let ours = resource_usage(std::process::id()).unwrap();
let bytes = usize::try_from(ours.memory_bytes)
.unwrap()
.checked_add(64 * 1024 * 1024)
.unwrap();
let scratch = cortexkit_test_support::ScratchDir::new("subc-os-resource-usage");
let ready = scratch.join("ready");
let mut child = ChildGuard(
Command::new(std::env::current_exe().unwrap())
.args([
"tests::resource_usage_child",
"--exact",
"--ignored",
"--nocapture",
"--test-threads=1",
])
.env("SUBC_OS_TEST_RESOURCE_BYTES", bytes.to_string())
.env("SUBC_OS_TEST_RESOURCE_READY", &ready)
.stdin(Stdio::piped())
.stdout(Stdio::null())
.spawn()
.unwrap(),
);
let deadline = Instant::now() + Duration::from_secs(10);
while !ready.exists() {
assert!(child.0.try_wait().unwrap().is_none(), "memory child exited");
assert!(Instant::now() < deadline, "memory child never became ready");
std::thread::sleep(Duration::from_millis(5));
}
let ours = resource_usage(std::process::id()).unwrap();
let usage = resource_usage(child.0.id()).expect("live child is readable");
assert!(
ours.memory_bytes < bytes as u64,
"caller uses {} bytes, overlapping the child's {bytes} touched bytes",
ours.memory_bytes,
);
assert!(
usage.memory_bytes >= bytes as u64,
"child uses {} bytes, fewer than its {bytes} touched bytes (caller uses {})",
usage.memory_bytes,
ours.memory_bytes,
);
}
#[test]
#[ignore = "re-exec fixture retaining touched private memory until its parent closes stdin"]
fn resource_usage_child() {
let bytes: usize = std::env::var("SUBC_OS_TEST_RESOURCE_BYTES")
.unwrap()
.parse()
.unwrap();
let ready = std::env::var_os("SUBC_OS_TEST_RESOURCE_READY").unwrap();
let pages = vec![0xa5u8; bytes];
std::hint::black_box(&pages);
std::fs::write(ready, b"ready").unwrap();
let _ = std::io::stdin().read(&mut [0]);
std::hint::black_box(&pages);
}
#[test]
fn an_exited_child_reads_as_unavailable_not_zero() {
let mut child = spawn_sleep();
let pid = child.id();
child.kill().unwrap();
let deadline = Instant::now() + Duration::from_secs(5);
while start_time(pid).is_some() {
assert!(Instant::now() < deadline, "child still observed as alive");
std::thread::sleep(Duration::from_millis(10));
}
assert_eq!(resource_usage(pid), None, "a zombie reads as unavailable");
child.wait().unwrap();
if let Some(usage) = resource_usage(pid) {
assert!(usage.memory_bytes > 0, "a reused pid is some live process");
}
}
#[test]
fn a_pid_with_no_process_reads_as_unavailable() {
assert_eq!(resource_usage(i32::MAX as u32), None);
assert_eq!(resource_usage(u32::MAX), None);
}
#[cfg(target_os = "linux")]
#[test]
fn linux_signals_go_through_a_pidfd() {
let mut child = spawn_sleep();
let process = Process::open(child.id()).unwrap().unwrap();
assert!(process.signals_through_pidfd());
child.kill().unwrap();
child.wait().unwrap();
assert!(!process.signal(Signal::Kill).unwrap());
}
}