use std::collections::BTreeMap;
use std::process::Stdio as StdStdio;
use crate::child::proc_handle::ProcHandle;
use crate::child::shared::SharedChild;
pub(crate) use crate::child::spawn::failure::{after_the_spawn, Classify, SpawnFailure};
use crate::child::{Child, ParentEnd};
use crate::command::{Command, CommandInput, EnvOp};
use crate::error::{ChildFate, Error};
use crate::identity::ProcessId;
use crate::stdio::{Direction, Fd, ResolvedStdio};
#[cfg(unix)]
pub(crate) type ChildEnd = std::os::unix::io::OwnedFd;
#[cfg(windows)]
pub(crate) type ChildEnd = std::os::windows::io::OwnedHandle;
pub(crate) fn spawn(cmd: &mut Command) -> Result<Child, SpawnFailure> {
let child = spawn_uncommitted(cmd)?;
child.commit_kill_on_drop();
Ok(child)
}
pub(crate) fn spawn_uncommitted(cmd: &mut Command) -> Result<Child, SpawnFailure> {
let kill_on_drop = cmd.kill_on_drop_flag();
if cmd.elevation_request().enabled {
#[cfg(windows)]
{
return crate::elevation::windows::spawn_elevated(cmd, kill_on_drop);
}
#[cfg(unix)]
{
let crate::elevation::posix::PosixRewrite {
derived,
report,
password_write,
backend_path,
} = crate::elevation::posix::rewrite(cmd).not_started()?;
let wrapper = report.as_ref().is_some_and(|r| r.via.program_outlives_child());
let spawned = (|| {
let mut child = match derived {
Some(mut derived) => {
let r = spawn_unelevated(&mut derived, kill_on_drop);
match backend_path.as_deref() {
Some(bp) => r.map_err(|f| f.map(|e| crate::elevation::remap_derived_spawn_error(e, bp)))?,
None => r?,
}
}
None => spawn_unelevated(cmd, kill_on_drop)?,
};
child.set_elevation(report);
let written = password_write.map_or(Ok(()), |pw| pw.write_after_spawn());
finish_elevated(child, written)
})();
return spawned.map_err(|failure| if wrapper { failure.behind_wrapper() } else { failure });
}
#[cfg(not(any(unix, windows)))]
{
return Err(SpawnFailure::NotStarted(Error::Unsupported {
op: "elevation".into(),
platform: std::env::consts::OS,
detail: "no elevation backend on this platform".into(),
}));
}
}
spawn_unelevated(cmd, kill_on_drop)
}
#[cfg(unix)]
pub(crate) fn finish_elevated(child: Child, written: Result<(), Error>) -> Result<Child, SpawnFailure> {
let Err(write_err) = written else {
return Ok(child);
};
let view = crate::containment::DropView::read(child.id, child.proc.is_reaped(), &child.tree_killed);
let mut skipped = None;
let gate = child.kill_gate();
let front_closed = matches!(gate, crate::elevation::front::Gate::Closed(_));
let tree = (child.containment().can_teardown() && !front_closed).then(|| {
child
.attached
.hard_kill_marking_unless_reaped(view, &child.tree_killed)
.map(|s| skipped = s)
});
let tree_failure = match &tree {
Some(Err(e)) => Some(e.to_string()),
_ => None,
};
let mut tree_note = report_tree_teardown(tree, &child.attached.teardown_subject());
if let Some(action) = skipped {
tree_note.push_str(&format!(
"; its contained tree was not killed: the root was already reaped, so its number may name another \
process, and the kill would {action}"
));
}
let exited_front = matches!(gate, crate::elevation::front::Gate::Exited);
let root = match gate {
crate::elevation::front::Gate::CgroupOnly if child.tree_killed.is_set() => {
child.cgroup_kill_reached().map(|()| crate::signal::Sent::Delivered)
}
crate::elevation::front::Gate::CgroupOnly => Err(crate::elevation::front::cgroup_not_killed_of(
child.front,
child.id().pid(),
tree_failure.as_deref(),
)),
crate::elevation::front::Gate::Closed(unkillable) => Err(unkillable),
gate => child.kill_sent_gated(gate),
};
let pid = child.id().pid();
let (root_note, fate) = match root {
Ok(crate::signal::Sent::Gone) if exited_front => (
"the elevated child had already exited, and was reaped by someone else".to_string(),
ChildFate::Gone,
),
Ok(crate::signal::Sent::Gone) => (
"the elevated child could not be terminated (it was already reaped)".to_string(),
ChildFate::Gone,
),
Ok(crate::signal::Sent::Unverified) => {
debug_assert!(false, "a sync child's kill always verifies its target");
(
"the elevated child could not be terminated (it could not be verified, and may still be running)"
.to_string(),
ChildFate::Running { id: Some(child.id()) },
)
}
Ok(crate::signal::Sent::Delivered) => {
#[cfg(test)]
fault::run_between_kill_and_wait();
match wait_killed_elevated(&child) {
Ok(_status) => {
#[cfg(test)]
fault::record_teardown_reap(pid, _status);
let note = if exited_front {
"the elevated child had already exited, and was reaped"
} else {
"the elevated child was terminated"
};
(note.to_string(), ChildFate::Reaped)
}
Err(e) if exited_front => {
log::warn!("could not reap the exited elevated child pid {pid}: {e}");
(
format!("the elevated child had already exited, but could not be reaped ({e})"),
ChildFate::Killed,
)
}
Err(e) => {
log::warn!("could not reap the killed elevated child pid {pid}: {e}");
(
format!("the elevated child was killed but could not be reaped ({e})"),
ChildFate::Killed,
)
}
}
}
Err(e) => {
#[cfg(test)]
fault::run_between_kill_and_wait();
let fate = fate_of_a_look(child.try_wait().map_err(|e| e.raw_os_error()), Some(child.id()));
(format!("the elevated child could not be terminated ({e})"), fate)
}
};
Err(SpawnFailure::started(
Error::Elevation {
kind: crate::error::ElevationErrorKind::AuthFailed,
detail: format!("{write_err}; {root_note}{tree_note}"),
},
fate,
))
}
pub(crate) fn fate_of_a_look(
looked: Result<Option<std::process::ExitStatus>, Option<i32>>,
id: Option<ProcessId>,
) -> ChildFate {
match looked {
Ok(Some(_)) => ChildFate::Reaped,
Ok(None) => ChildFate::Running { id },
#[cfg(unix)]
Err(Some(libc::ECHILD)) => ChildFate::Gone,
Err(_) => ChildFate::Unknown,
}
}
#[cfg(unix)]
fn wait_killed_elevated(child: &Child) -> Result<std::process::ExitStatus, Error> {
let waited = child.wait();
#[cfg(test)]
if let Some(marker) = fault::take_force_reap_failure() {
return waited.and(Err(Error::Io(std::io::Error::other(marker))));
}
waited
}
#[cfg(unix)]
pub(crate) const TREE_TEARDOWN_WARN: &str = "tree teardown after a failed password write failed";
#[cfg(all(test, target_os = "linux"))]
pub(crate) fn teardown_warn_marker(leaf_path: &std::path::Path) -> String {
format!("{TREE_TEARDOWN_WARN} (cgroup leaf {})", leaf_path.display())
}
#[cfg(unix)]
pub(crate) fn report_tree_teardown(tree: Option<Result<(), Error>>, subject: &dyn std::fmt::Display) -> String {
let Some(Err(e)) = tree else {
return String::new();
};
log::warn!("{TREE_TEARDOWN_WARN} ({subject}): {e}");
format!("; its contained tree could not be killed ({subject}: {e})")
}
#[cfg(windows)]
pub(crate) fn routes_to_raw_backend(cmd: &Command) -> bool {
cmd.executable_path().is_some() || cmd.fds().keys().any(|slot| slot.raw() >= 3)
}
pub(crate) fn spawn_unelevated(cmd: &mut Command, kill_on_drop: bool) -> Result<Child, SpawnFailure> {
#[cfg(target_os = "linux")]
crate::wait::backend::probe_pidfd_support().not_started()?;
#[cfg(windows)]
let to_raw_backend = routes_to_raw_backend(cmd);
let fds = std::mem::take(cmd.fds_mut());
#[cfg(windows)]
if to_raw_backend {
return windows_raw::spawn_raw(cmd, fds, kill_on_drop);
}
#[cfg(target_os = "linux")]
let (mut std_cmd, handshake) = build_std_command_with(cmd, pidfd_handshake::register).not_started()?;
#[cfg(target_os = "macos")]
let (mut std_cmd, report) = build_std_command_with(cmd, unique_report::register).not_started()?;
#[cfg(not(any(target_os = "linux", target_os = "macos")))]
let mut std_cmd = build_std_command(cmd).not_started()?;
let std_slots = [Fd::STDIN, Fd::STDOUT, Fd::STDERR];
let all_slots: Vec<Fd> = {
#[cfg_attr(not(unix), allow(unused_mut, reason = "the n>=3 push below is unix-only"))]
let mut v: Vec<Fd> = std_slots.to_vec();
#[cfg(unix)]
for &fd in fds.keys() {
if fd.raw() >= 3 {
v.push(fd);
}
}
v
};
let (mut child_ends, parent_ends) = resolve_stdio(&fds, &all_slots, PipeOwnership::Owned).not_started()?;
for slot in std_slots {
if let Some(end) = child_ends.remove(&slot) {
let stdio = StdStdio::from(end);
match slot {
Fd::STDIN => std_cmd.stdin(stdio),
Fd::STDOUT => std_cmd.stdout(stdio),
_ => std_cmd.stderr(stdio),
};
}
}
#[cfg(unix)]
let reserved: Vec<i32> = child_ends.keys().map(|fd| fd.raw()).collect();
#[cfg(not(unix))]
let reserved: Vec<i32> = Vec::new();
#[cfg(target_os = "macos")]
let (mut prepared, child, unique) = {
let _guard = spawn_lock();
let prepared = crate::containment::prepare(
&mut std_cmd,
&cmd.contain_request(),
cmd.flags_request(),
&reserved,
cmd.fd_marker_suppressed(),
cmd.env_ops(),
)
.not_started()?;
let report = report.open(&_guard).not_started()?;
let mappings: Vec<fd_map::FdMapping> = child_ends
.into_iter()
.map(|(fd, owned)| fd_map::FdMapping {
parent_fd: owned,
child_fd: fd.raw(),
})
.collect();
fd_map::install(&mut std_cmd, mappings).not_started()?;
#[allow(
clippy::disallowed_methods,
reason = "spawn_lock is held by `_guard`, taken at the top of this block"
)]
let (spawned, unique) = report.run(|| std_cmd.spawn().map_err(Error::Io));
let c = spawned
.map_err(|e| unique_report::failed_spawn_error(e, &unique))
.not_started()?;
drop(std_cmd);
(prepared, c, unique)
};
#[cfg(target_os = "linux")]
let (mut prepared, child, pidfd) = {
let prepared = crate::containment::prepare(
&mut std_cmd,
&cmd.contain_request(),
cmd.flags_request(),
&reserved,
cmd.fd_marker_suppressed(),
cmd.env_ops(),
)
.not_started()?;
if let Some(leaf) = prepared
.cgroup_leaf
.as_ref()
.filter(|_| cmd.elevation_front().is_some())
{
crate::containment::cgroup::front_placement(|| leaf.id()).not_started()?;
}
let _guard = spawn_lock();
let handshake = handshake.open(&_guard).not_started()?;
let mappings: Vec<fd_map::FdMapping> = child_ends
.into_iter()
.map(|(fd, owned)| fd_map::FdMapping {
parent_fd: owned,
child_fd: fd.raw(),
})
.collect();
fd_map::install(&mut std_cmd, mappings).not_started()?;
#[allow(clippy::disallowed_methods, reason = "spawn_lock is held by `_guard` above")]
let held = handshake.run(|| std_cmd.spawn())?;
(prepared, held.child, held.pidfd)
};
#[cfg(windows)]
let (mut prepared, child) = {
let prepared = crate::containment::prepare(
&mut std_cmd,
&cmd.contain_request(),
cmd.flags_request(),
&reserved,
cmd.fd_marker_suppressed(),
cmd.env_ops(),
)
.not_started()?;
let c = {
let _guard = spawn_lock();
#[allow(clippy::disallowed_methods, reason = "spawn_lock is held by `_guard` above")]
let spawned = std_cmd.spawn().map_err(Error::Io);
let spawned =
spawned.map_err(|e| crate::command::flags::classify_spawn_syscall_error(e, *cmd.flags_request()));
spawned.not_started()?
};
(prepared, c)
};
#[cfg(windows)]
let proc_handle = {
use std::os::windows::io::AsRawHandle;
child.as_raw_handle()
};
#[cfg(target_os = "linux")]
let child = HeldStdChild {
through: PidfdChild::new(Some(child.id()), pidfd),
child,
};
let front = cmd.elevation_front();
#[cfg(target_os = "macos")]
let unique = match unique_report::adopted_id(unique, child.id()) {
Ok(unique) => unique,
Err(not_adopted) => return Err(abandon_unadopted(child, not_adopted, front)),
};
#[cfg(target_os = "linux")]
let subtree = front_subtree(front.and(prepared.cgroup_leaf.as_ref()));
if front.is_some() {
prepared.watch_front(child.id());
}
#[cfg(test)]
fault::run_at(fault::SpawnPoint::BeforeIdentity, child.id());
#[cfg(target_os = "linux")]
let through = child.through.target();
#[cfg(target_os = "macos")]
let through = crate::wait::exit_only::Target::pid(child.id(), Some(unique));
#[cfg(windows)]
let through = {
use std::os::windows::io::AsHandle;
crate::wait::exit_only::Target::Handle(child.as_handle())
};
let pid = child.id();
#[cfg(target_os = "linux")]
let handle = crate::containment::ChildHandle {
pid,
pidfd: std::os::fd::AsFd::as_fd(&child.through.pidfd),
};
let id = match resolve_identity(pid, &through) {
crate::identity::Resolved::Found(id) => id,
other => {
settle_before_teardown(
&mut prepared,
#[cfg(target_os = "linux")]
handle,
#[cfg(not(target_os = "linux"))]
pid,
);
#[cfg(target_os = "linux")]
if front.is_some() {
drop(prepared);
}
#[cfg(target_os = "macos")]
let (fate, child_fate) = {
let identity = if matches!(other, crate::identity::Resolved::Gone) {
crate::containment::RootIdentity::Gone
} else {
crate::containment::RootIdentity::Unknown
};
let child_fate = leave_unverified_child(child, identity, None);
(FrontFate::of_unverified(identity), child_fate)
};
#[cfg(target_os = "linux")]
let (fate, child_fate) = teardown_unadopted_or_front(child, front, None, subtree.as_ref());
#[cfg(all(not(target_os = "macos"), not(target_os = "linux")))]
let (fate, child_fate) = teardown_unadopted_or_front(child, front, None);
return Err(SpawnFailure::started(
fate.note(spawn_identity_error(other), front, Some(pid)),
child_fate,
));
}
};
#[cfg(test)]
fault::run_at(fault::SpawnPoint::BeforeAttach, child.id());
let attachment = match attach_or_fault(
id,
#[cfg(target_os = "linux")]
handle,
#[cfg(windows)]
proc_handle,
prepared,
) {
Ok(v) => v,
Err(error) => {
log::debug!("attach failed: {error}");
#[cfg(target_os = "macos")]
let (fate, child_fate) = {
assert_attach_cannot_fail(&error);
if front.is_some() {
(
leave_front_after_attach_failure(child),
ChildFate::Running { id: Some(id) },
)
} else {
(FrontFate::NotAFront, teardown_after_attach_failure(child, unique, id))
}
};
#[cfg(target_os = "linux")]
let (fate, child_fate) = teardown_unadopted_or_front(child, front, Some(id), subtree.as_ref());
#[cfg(all(not(target_os = "macos"), not(target_os = "linux")))]
let (fate, child_fate) = teardown_unadopted_or_front(child, front, Some(id));
return Err(SpawnFailure::started(fate.note(error, front, Some(pid)), child_fate));
}
};
#[cfg(target_os = "linux")]
let shared = SharedChild::adopt_opened(child.child, id, child.through.pidfd);
#[cfg(target_os = "macos")]
let shared = SharedChild::adopt_verified(child, id, unique);
#[cfg(windows)]
let shared = match SharedChild::adopt(child, id) {
Ok(shared) => shared,
Err((error, child)) => {
let (error, fate) = teardown_after_failed_adoption(child, error, Some(id));
return Err(SpawnFailure::started(error, fate));
}
};
let mut child = Child::from_parts(ProcHandle::std(shared), id, parent_ends, kill_on_drop, attachment);
child.set_front(cmd.elevation_front());
Ok(child)
}
#[cfg(target_os = "macos")]
pub(crate) fn assert_attach_cannot_fail(error: &Error) {
#[cfg(test)]
debug_assert!(fault::force_attach_failure(), "a macOS attach cannot fail: {error}");
#[cfg(not(test))]
debug_assert!(false, "a macOS attach cannot fail: {error}");
let _ = error;
}
#[cfg(target_os = "macos")]
fn leave_front_after_attach_failure(child: std::process::Child) -> FrontFate {
log::warn!(
"elevation front pid {} is left running and unreaped, with nothing signalled or waited on by pid: its \
attach failed, and a kill would orphan the elevated program",
child.id()
);
drop(child);
FrontFate::LeftUnreaped
}
#[cfg(target_os = "macos")]
fn teardown_after_attach_failure(child: std::process::Child, unique: u64, id: ProcessId) -> ChildFate {
let fate = kill_and_reap_verified(child.id(), unique, Some(id));
drop(child);
fate
}
#[cfg(target_os = "macos")]
pub(crate) fn kill_and_reap_verified(pid: u32, unique: u64, id: Option<ProcessId>) -> ChildFate {
use crate::signal::{via_verified_pid, Sent, Sig};
use crate::wait::backend::{await_reapable, Waited};
use crate::wait::exit_only::Foreign;
let target = crate::wait::exit_only::Target::pid(pid, Some(unique));
match via_verified_pid(pid, Some(unique), Sig::Kill) {
Ok(Sent::Delivered) => match await_reapable(pid, Some(unique), None) {
Ok(Waited::Reapable) => reap_verified(pid, &target, id, true),
Ok(Waited::Gone) => {
log::debug!("spawn teardown: pid {pid} was reaped by someone else");
Foreign::Gone.fate(true)
}
Ok(Waited::Orphaned) => {
log::warn!(
"spawn teardown: pid {pid} is not ours to reap (launchd holds its zombie, because its tracer died)"
);
Foreign::Orphaned.fate(true)
}
Ok(Waited::DeadlinePassed) => {
log::warn!("spawn teardown: pid {pid} is still running after its kill");
ChildFate::Running { id }
}
Err(e) => {
log::warn!("spawn teardown could not wait for pid {pid}: {e}");
ChildFate::Killed
}
},
Ok(Sent::Gone) => {
log::debug!("spawn teardown: pid {pid} is already gone");
Foreign::Gone.fate(false)
}
Ok(Sent::Unverified) => {
debug_assert!(false, "`via_verified_pid` was given `Some(unique)`, so it verifies");
log::warn!("spawn teardown: pid {pid} could not be verified, so it was not signalled");
ChildFate::Running { id }
}
Err(kill) => {
log::warn!("spawn teardown failed to kill pid {pid}: {kill}");
reap_verified(pid, &target, id, false)
}
}
}
#[cfg(target_os = "macos")]
fn reap_verified(
pid: u32,
target: &crate::wait::exit_only::Target<'_>,
id: Option<ProcessId>,
killed: bool,
) -> ChildFate {
use crate::wait::exit_only::{peek_verified, try_reap, Foreign, Peek, Reap, Reaped};
let unverifiable = |why: &dyn std::fmt::Display| {
log::warn!("spawn teardown: pid {pid} cannot be shown to be ours or reaped ({why})");
ChildFate::Unknown
};
let foreign = |why: Foreign| {
match why {
Foreign::Orphaned => log::warn!(
"spawn teardown: pid {pid} is not ours to reap (launchd holds its zombie, because its tracer died)"
),
Foreign::Gone | Foreign::Other => log::debug!("spawn teardown: pid {pid} was reaped by someone else"),
}
why.fate(killed)
};
let running = || {
log::warn!("spawn teardown: pid {pid} is still running");
ChildFate::Running { id }
};
match peek_verified(target) {
Err(e) => return unverifiable(&e),
Ok(Peek::Foreign(why)) => return foreign(why),
Ok(Peek::Running) => return running(),
Ok(Peek::Exit(_)) => {}
}
match try_reap(target) {
Ok(Reap::Reaped(Reaped::Status(_))) => ChildFate::Reaped,
Ok(Reap::Reaped(Reaped::Unreadable { si_code })) => {
log::warn!("spawn teardown: pid {pid}: a consuming waitid returned si_code {si_code}, not an exit record");
debug_assert!(false, "a consuming waitid on a zombie returned si_code {si_code}");
ChildFate::Reaped
}
Ok(Reap::Running) => running(),
Ok(Reap::Foreign(why)) => foreign(why),
Err(e) => {
log::warn!("spawn teardown failed to reap pid {pid}: {e}");
ChildFate::Unknown
}
}
}
#[cfg(target_os = "macos")]
fn abandon_unadopted(
child: std::process::Child,
not_adopted: unique_report::NotAdopted,
front: Option<crate::elevation::front::Front>,
) -> SpawnFailure {
use unique_report::Unadoptable;
let pid = child.id();
let error = not_adopted.error;
match not_adopted.why {
Unadoptable::DiedBeforeExec => {
log::warn!(
"child {pid} died before exec; nothing is signalled or waited on by pid, so its status is not collected"
);
drop(child);
SpawnFailure::NotStarted(error)
}
Unadoptable::Unreported => {
#[cfg(test)]
fault::capture(ProcessId::of(pid));
log::warn!(
"child {pid} had not reported its unique id when its spawn returned; it is not adopted, nothing is \
signalled or waited on by pid, and it may be running"
);
drop(child);
SpawnFailure::started(
FrontFate::LeftUnreaped.note(error, front, Some(pid)),
ChildFate::Running { id: None },
)
}
Unadoptable::Unverified => {
let (error, fate) = teardown_after_failed_adoption(child, error, None);
SpawnFailure::started(
FrontFate::of_unverified(crate::containment::RootIdentity::Unknown).note(error, front, Some(pid)),
fate,
)
}
}
}
#[cfg(target_os = "macos")]
fn leave_unverified_child(
child: std::process::Child,
identity: crate::containment::RootIdentity,
id: Option<ProcessId>,
) -> ChildFate {
let pid = child.id();
let fate = if identity == crate::containment::RootIdentity::Gone {
log::warn!(
"child {pid} was reaped by someone else; its pid may be reused, so nothing is signalled or waited on by pid"
);
ChildFate::Gone
} else {
log::warn!(
"child {pid} cannot be shown to be ours (its identity could not be read); leaving it unreaped, with \
nothing signalled or waited on by pid, and it may still be running"
);
ChildFate::Running { id }
};
drop(child);
fate
}
#[cfg(not(target_os = "linux"))]
fn teardown_after_failed_adoption(
child: std::process::Child,
error: Error,
id: Option<ProcessId>,
) -> (Error, ChildFate) {
#[cfg(test)]
fault::capture(ProcessId::of(child.id()));
#[cfg(target_os = "macos")]
let fate = leave_unverified_child(child, crate::containment::RootIdentity::Unknown, id);
#[cfg(not(target_os = "macos"))]
let fate = teardown_unadopted(child, id);
(error, fate)
}
pub(crate) fn spawn_lock() -> SpawnLockGuard {
acquire_spawn_lock(|| {})
}
static SPAWN_MUTEX: std::sync::Mutex<()> = std::sync::Mutex::new(());
#[must_use = "if unused the spawn lock is released immediately; bind the guard for the whole window"]
pub(crate) struct SpawnLockGuard {
_guard: std::sync::MutexGuard<'static, ()>,
}
thread_local! {
#[cfg(any(test, debug_assertions))]
static SPAWN_LOCK_HELD_BY_THIS_THREAD: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
#[cfg(any(test, debug_assertions))]
impl Drop for SpawnLockGuard {
fn drop(&mut self) {
SPAWN_LOCK_HELD_BY_THIS_THREAD.with(|f| f.set(false));
}
}
fn acquire_spawn_lock(on_contended: impl FnOnce()) -> SpawnLockGuard {
#[cfg(any(test, debug_assertions))]
assert!(
!spawn_lock_held_by_this_thread(),
"spawn_lock re-entered: the mutex is not reentrant; drop the outer spawn_lock() (fork_running and cosca spawns take it themselves)"
);
let guard = match SPAWN_MUTEX.try_lock() {
Ok(guard) => guard,
Err(std::sync::TryLockError::Poisoned(e)) => e.into_inner(),
Err(std::sync::TryLockError::WouldBlock) => {
on_contended();
SPAWN_MUTEX.lock().unwrap_or_else(|e| e.into_inner())
}
};
#[cfg(any(test, debug_assertions))]
SPAWN_LOCK_HELD_BY_THIS_THREAD.with(|f| f.set(true));
SpawnLockGuard { _guard: guard }
}
#[cfg(all(target_os = "linux", test))]
pub(crate) fn spawn_lock_tracked(on_contended: impl FnOnce()) -> SpawnLockGuard {
acquire_spawn_lock(on_contended)
}
#[cfg(any(test, debug_assertions))]
pub(crate) fn spawn_lock_held_by_this_thread() -> bool {
SPAWN_LOCK_HELD_BY_THIS_THREAD.with(|f| f.get())
}
#[cfg(any(not(any(target_os = "linux", target_os = "macos")), test))]
pub(crate) fn build_std_command(cmd: &Command) -> Result<std::process::Command, Error> {
build_std_command_with(cmd, |_| ()).map(|(std_cmd, ())| std_cmd)
}
pub(crate) fn build_std_command_with<R>(
cmd: &Command,
first: impl FnOnce(&mut std::process::Command) -> R,
) -> Result<(std::process::Command, R), Error> {
let StdLaunch {
program,
mut std_cmd,
cwd,
enter,
} = match cmd.input() {
CommandInput::Empty => return Err(Error::Io(std::io::Error::other("no program specified"))),
CommandInput::Argv(argv) => {
let (Resolved { program, cwd, enter }, rest) = resolve_program_argv(cmd, argv)?;
let mut c = std::process::Command::new(&program);
c.args(rest);
#[cfg(unix)]
if let Some(exe) = cmd.executable_path() {
use std::os::unix::process::CommandExt;
c.arg0(argv.first().map_or(exe.as_os_str(), std::ffi::OsString::as_os_str));
}
StdLaunch {
program,
std_cmd: c,
cwd,
enter,
}
}
CommandInput::CommandLine(line) => build_from_commandline(cmd, line)?,
};
reject_batch_path(std::path::Path::new(&program))?;
apply_env(&mut std_cmd, cmd.env_ops());
let first = first(&mut std_cmd);
match cwd {
Some(dir) if enter => enter_in_child(&mut std_cmd, &dir)?,
Some(dir) => {
std_cmd.current_dir(dir);
}
None => {}
}
Ok((std_cmd, first))
}
#[cfg(unix)]
fn enter_in_child(std_cmd: &mut std::process::Command, dir: &std::path::Path) -> Result<(), Error> {
use std::os::unix::ffi::OsStrExt;
use std::os::unix::process::CommandExt;
let dir = std::ffi::CString::new(dir.as_os_str().as_bytes()).map_err(|_| {
Error::Io(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
"current_dir() contains an embedded NUL",
))
})?;
unsafe {
std_cmd.pre_exec(move || {
#[expect(
clippy::disallowed_methods,
reason = "this closure runs in the forked child, between fork and exec, so the chdir \
moves that child's cwd and never this process's — see this function's doc"
)]
let status = libc::chdir(dir.as_ptr());
if status == 0 {
Ok(())
} else {
Err(std::io::Error::last_os_error())
}
});
}
Ok(())
}
#[cfg(not(unix))]
fn enter_in_child(_: &mut std::process::Command, _: &std::path::Path) -> Result<(), Error> {
unreachable!("only anchor_posix asks the child to enter its directory")
}
struct Resolved {
program: std::ffi::OsString,
cwd: Option<std::path::PathBuf>,
enter: bool,
}
fn resolve_program(cmd: &Command, fallback: std::ffi::OsString) -> Result<Resolved, Error> {
let as_given = |exe: Option<&std::path::Path>| Resolved {
program: exe.map_or(fallback, |p| p.as_os_str().to_os_string()),
cwd: cmd.cwd().map(std::path::Path::to_path_buf),
enter: false,
};
#[cfg(unix)]
if let Some(crate::command::ExecutableSpec::Exact(p)) = cmd.executable_spec() {
let a = crate::resolve::exact::anchor_posix(p.as_os_str(), cmd.cwd())?;
return Ok(Resolved {
program: a.program.into_os_string(),
cwd: a.cwd,
enter: a.enter,
});
}
Ok(as_given(cmd.executable_path()))
}
fn resolve_program_argv<'a>(
cmd: &'a Command,
argv: &'a [std::ffi::OsString],
) -> Result<(Resolved, &'a [std::ffi::OsString]), Error> {
if argv.is_empty() && cmd.executable_path().is_none() {
return Err(Error::Io(std::io::Error::other("empty argv")));
}
let fallback = if argv.is_empty() {
std::ffi::OsString::new()
} else {
argv[0].clone()
};
let program = resolve_program(cmd, fallback)?;
let rest = if argv.is_empty() { argv } else { &argv[1..] };
Ok((program, rest))
}
struct StdLaunch {
program: std::ffi::OsString,
std_cmd: std::process::Command,
cwd: Option<std::path::PathBuf>,
enter: bool,
}
#[cfg(unix)]
fn build_from_commandline(cmd: &Command, line: &std::ffi::OsString) -> Result<StdLaunch, Error> {
use std::ffi::OsString;
use std::os::unix::ffi::{OsStrExt, OsStringExt};
let words = crate::quote::posix::split(line.as_bytes())?;
let argv: Vec<OsString> = words.into_iter().map(OsString::from_vec).collect();
if argv.is_empty() {
return Err(Error::Io(std::io::Error::other("empty command line")));
}
let Resolved { program, cwd, enter } = resolve_program(cmd, argv[0].clone())?;
let mut c = std::process::Command::new(&program);
if cmd.executable_path().is_some() {
use std::os::unix::process::CommandExt;
c.arg0(&argv[0]);
}
c.args(&argv[1..]);
Ok(StdLaunch {
program,
std_cmd: c,
cwd,
enter,
})
}
#[cfg(windows)]
fn build_from_commandline(cmd: &Command, line: &std::ffi::OsString) -> Result<StdLaunch, Error> {
use std::os::windows::ffi::{OsStrExt, OsStringExt};
use std::os::windows::process::CommandExt;
let wide: Vec<u16> = line.encode_wide().collect();
let (first, rest) = crate::quote::windows::first_token_and_rest_wide(&wide)
.ok_or_else(|| Error::Io(std::io::Error::other("empty command line")))?;
let program = std::ffi::OsString::from_wide(&first);
let mut c = std::process::Command::new(&program);
c.raw_arg(std::ffi::OsString::from_wide(&rest)); Ok(StdLaunch {
program,
std_cmd: c,
cwd: cmd.cwd().map(std::path::Path::to_path_buf),
enter: false,
})
}
pub(crate) fn apply_env(std_cmd: &mut std::process::Command, ops: &[EnvOp]) {
for op in ops {
match op {
EnvOp::Set(k, v) => {
std_cmd.env(k, v);
}
EnvOp::Remove(k) => {
std_cmd.env_remove(k);
}
EnvOp::Clear => {
std_cmd.env_clear();
}
}
}
}
pub(crate) type ResolvedStdioEnds = (BTreeMap<Fd, ChildEnd>, BTreeMap<Fd, ParentEnd>);
#[derive(Clone, Copy)]
pub(crate) enum PipeOwnership {
Owned,
#[cfg_attr(
not(feature = "tokio"),
allow(dead_code, reason = "only the async spawn path constructs Deferred")
)]
Deferred,
}
pub(crate) fn resolve_stdio(
fds: &BTreeMap<Fd, ResolvedStdio>,
slots: &[Fd],
pipe: PipeOwnership,
) -> Result<ResolvedStdioEnds, Error> {
for &slot in slots {
if let Some(ResolvedStdio::Merge(target)) = fds.get(&slot) {
if matches!(fds.get(target), Some(ResolvedStdio::Merge(_))) {
return Err(Error::Unsupported {
op: format!("merge {slot} -> {target} -> <another merge>"),
platform: std::env::consts::OS,
detail: "chained merges (merge-to-merge) are not supported; \
redirect to a concrete slot (pipe/file/null/inherit)"
.into(),
});
}
}
}
let mut child_ends: BTreeMap<Fd, ChildEnd> = BTreeMap::new();
let mut parent_ends: BTreeMap<Fd, ParentEnd> = BTreeMap::new();
for &slot in slots {
let resolved = fds.get(&slot);
match resolved {
Some(ResolvedStdio::Merge(_)) => continue, Some(ResolvedStdio::Pipe(_)) if matches!(pipe, PipeOwnership::Deferred) && slot.raw() < 3 => continue,
None if slot.raw() >= 3 => continue,
_ => {
let (child_end, parent) = resolve_non_merge(slot, resolved)?;
if let Some(p) = parent {
parent_ends.insert(slot, p);
}
child_ends.insert(slot, child_end);
}
}
}
for &slot in slots {
if let Some(ResolvedStdio::Merge(target)) = fds.get(&slot) {
if matches!(pipe, PipeOwnership::Deferred)
&& target.raw() < 3
&& matches!(fds.get(target), Some(ResolvedStdio::Pipe(_)))
{
return Err(Error::Unsupported {
op: format!("async merge {slot} -> {target} (piped)"),
platform: std::env::consts::OS,
detail: "merging into a piped target with a deferred (tokio-owned) pipe end needs \
the merge target resolved first; merge into file/null/inherit, or capture \
separately"
.into(),
});
}
let src = child_ends.get(target).ok_or_else(|| Error::Unsupported {
op: format!("merge {slot} -> {target}"),
platform: std::env::consts::OS,
detail: "merge target descriptor is not configured".into(),
})?;
child_ends.insert(slot, dup(src)?);
}
}
Ok((child_ends, parent_ends))
}
pub(crate) fn resolve_non_merge(slot: Fd, r: Option<&ResolvedStdio>) -> Result<(ChildEnd, Option<ParentEnd>), Error> {
match r {
None | Some(ResolvedStdio::Inherit) => Ok((inherit_end(slot)?, None)),
Some(ResolvedStdio::Null) => Ok((null_end()?, None)),
Some(ResolvedStdio::File(f)) => Ok((file_end(f)?, None)),
Some(ResolvedStdio::Pipe(dir)) => make_pipe(*dir),
Some(ResolvedStdio::Merge(_)) => unreachable!("merge handled in second pass"),
}
}
fn make_pipe(dir: Direction) -> Result<(ChildEnd, Option<ParentEnd>), Error> {
let (reader, writer) = std::io::pipe().map_err(Error::Io)?;
match dir {
Direction::In => Ok((ChildEnd::from(reader), Some(ParentEnd::Writer(writer)))),
Direction::Out => Ok((ChildEnd::from(writer), Some(ParentEnd::Reader(reader)))),
}
}
pub(crate) fn dup(end: &ChildEnd) -> Result<ChildEnd, Error> {
#[cfg(unix)]
{
use std::os::fd::AsFd;
end.as_fd().try_clone_to_owned().map_err(Error::Io)
}
#[cfg(windows)]
{
use std::os::windows::io::AsHandle;
end.as_handle().try_clone_to_owned().map_err(Error::Io)
}
}
fn null_end() -> Result<ChildEnd, Error> {
let f = std::fs::OpenOptions::new()
.read(true)
.write(true)
.open(if cfg!(windows) { "NUL" } else { "/dev/null" })
.map_err(Error::Io)?;
Ok(ChildEnd::from(f))
}
fn file_end(f: &std::fs::File) -> Result<ChildEnd, Error> {
let dup = f.try_clone().map_err(Error::Io)?;
Ok(ChildEnd::from(dup))
}
fn inherit_end(slot: Fd) -> Result<ChildEnd, Error> {
#[cfg(unix)]
{
use std::os::fd::AsFd;
let owned = match slot {
Fd::STDIN => {
let s = std::io::stdin();
s.as_fd().try_clone_to_owned()
}
Fd::STDOUT => {
let s = std::io::stdout();
s.as_fd().try_clone_to_owned()
}
Fd::STDERR => {
let s = std::io::stderr();
s.as_fd().try_clone_to_owned()
}
other => {
return Err(Error::Unsupported {
op: format!("Stdio::inherit() on {other}"),
platform: "unix",
detail: "inherit on fd >= 3 has no defined parent stream; \
use pipe/file/null instead"
.into(),
})
}
};
owned.map_err(Error::Io)
}
#[cfg(windows)]
{
use std::os::windows::io::AsHandle;
let owned = match slot {
Fd::STDIN => {
let s = std::io::stdin();
s.as_handle().try_clone_to_owned()
}
Fd::STDOUT => {
let s = std::io::stdout();
s.as_handle().try_clone_to_owned()
}
Fd::STDERR => {
let s = std::io::stderr();
s.as_handle().try_clone_to_owned()
}
other => {
return Err(Error::Unsupported {
op: format!("Stdio::inherit() on {other}"),
platform: "windows",
detail: "inherit on fd >= 3 has no defined parent stream; \
use pipe/file/null instead"
.into(),
})
}
};
owned.map_err(Error::Io)
}
}
pub(crate) fn spawn_identity_error(outcome: crate::identity::Resolved<ProcessId>) -> Error {
match outcome {
crate::identity::Resolved::Unknown => crate::identity::unknown_identity_error("the spawned child")
.unwrap_or_else(|| Error::Unassessable {
detail: "the OS refused to report the spawned child's identity".into(),
source: None,
}),
_ => Error::Io(std::io::Error::other(
"the spawned child exited and was reaped by another party, or its zombie is held by one, before its \
identity could be read",
)),
}
}
pub(crate) fn resolve_identity(
pid: u32,
through: &crate::wait::exit_only::Target<'_>,
) -> crate::identity::Resolved<ProcessId> {
use crate::identity::Resolved;
let read = resolve_identity_unchecked(pid);
let Resolved::Found(_) = read else {
return read;
};
#[cfg(test)]
fault::run_at(fault::SpawnPoint::AfterIdentityRead, pid);
#[cfg(unix)]
{
use crate::wait::exit_only::Peek;
#[cfg(target_os = "linux")]
let peeked = crate::wait::exit_only::peek(through);
#[cfg(target_os = "macos")]
let peeked = crate::wait::exit_only::peek_verified(through);
match peeked {
Ok(Peek::Running | Peek::Exit(_)) => read,
#[cfg(target_os = "macos")]
Ok(Peek::Foreign(crate::wait::exit_only::Foreign::Orphaned)) => {
log::warn!("child {pid}: launchd holds its zombie, so its tracer died; it is not ours to reap");
Resolved::Gone
}
Ok(Peek::Foreign(_)) => Resolved::Gone,
Err(e) => {
log::warn!("child {pid}: its identity could not be checked against its handle ({e}); it is not shown to be ours");
Resolved::Unknown
}
}
}
#[cfg(windows)]
{
let _ = through;
read
}
}
pub(crate) fn resolve_identity_unchecked(pid: u32) -> crate::identity::Resolved<ProcessId> {
#[cfg(test)]
{
if fault::force_identity_unknown() {
fault::capture(ProcessId::of(pid));
return crate::identity::Resolved::Unknown;
}
if fault::force_identity_vanished() {
fault::capture(ProcessId::of(pid));
return crate::identity::Resolved::Gone;
}
}
ProcessId::of(pid)
}
pub(crate) fn attach_or_fault(
id: ProcessId,
#[cfg(target_os = "linux")] child: crate::containment::ChildHandle<'_>,
#[cfg(windows)] proc_handle: std::os::windows::io::RawHandle,
prepared: crate::containment::Prepared,
) -> Result<crate::containment::Attachment, Error> {
#[cfg(test)]
if fault::force_attach_failure() {
fault::capture(crate::identity::Resolved::Found(id));
let mut prepared = prepared;
prepared.settle_verdict(
#[cfg(target_os = "linux")]
child,
#[cfg(not(target_os = "linux"))]
id.pid(),
);
return Err(Error::Containment {
detail: "forced attach failure (test seam)".into(),
});
}
#[cfg(all(test, target_os = "linux"))]
if let Some(attachment) = fault::take_attachment_override() {
let mut prepared = prepared;
prepared.settle_verdict(
#[cfg(target_os = "linux")]
child,
#[cfg(not(target_os = "linux"))]
id.pid(),
);
return Ok(attachment);
}
crate::containment::attach(
id,
#[cfg(target_os = "linux")]
child,
#[cfg(windows)]
proc_handle,
prepared,
)
}
#[cfg(not(target_os = "macos"))]
trait Unadopted: Send + 'static {
fn pid(&self) -> Option<u32>;
fn kill(&mut self) -> std::io::Result<()>;
#[cfg(unix)]
fn kill_delivered(&self) -> bool {
true
}
fn try_wait(&mut self) -> std::io::Result<Option<std::process::ExitStatus>>;
fn wait(&mut self) -> std::io::Result<std::process::ExitStatus>;
#[cfg(target_os = "linux")]
fn pidfd(&self) -> Option<std::os::fd::BorrowedFd<'_>>;
}
#[cfg(not(target_os = "macos"))]
pub(crate) fn named(pid: Option<u32>) -> String {
match pid {
Some(pid) => format!("pid {pid}"),
None => "the spawned child (pid unknown)".to_string(),
}
}
#[cfg(not(target_os = "macos"))]
#[cfg(not(target_os = "linux"))]
impl Unadopted for std::process::Child {
fn pid(&self) -> Option<u32> {
Some(std::process::Child::id(self))
}
fn kill(&mut self) -> std::io::Result<()> {
std::process::Child::kill(self)
}
fn try_wait(&mut self) -> std::io::Result<Option<std::process::ExitStatus>> {
std::process::Child::try_wait(self)
}
fn wait(&mut self) -> std::io::Result<std::process::ExitStatus> {
std::process::Child::wait(self)
}
}
#[cfg(target_os = "linux")]
struct PidfdChild {
pid: Option<u32>,
pidfd: std::os::fd::OwnedFd,
reaped: Option<std::process::ExitStatus>,
delivered: bool,
}
#[cfg(target_os = "linux")]
impl PidfdChild {
fn new(pid: Option<u32>, pidfd: std::os::fd::OwnedFd) -> PidfdChild {
PidfdChild {
pid,
pidfd,
reaped: None,
delivered: false,
}
}
fn target(&self) -> crate::wait::exit_only::Target<'_> {
use std::os::fd::AsFd;
crate::wait::exit_only::Target::PidFd(self.pidfd.as_fd())
}
}
#[cfg(target_os = "linux")]
impl Unadopted for PidfdChild {
fn pid(&self) -> Option<u32> {
self.pid
}
fn pidfd(&self) -> Option<std::os::fd::BorrowedFd<'_>> {
use std::os::fd::AsFd;
Some(self.pidfd.as_fd())
}
fn kill(&mut self) -> std::io::Result<()> {
use std::os::fd::AsFd;
let sent = crate::signal::via_pidfd(
Some(self.pidfd.as_fd()),
self.pid.unwrap_or(0),
crate::signal::Sig::Kill,
)?;
self.delivered = matches!(sent, crate::signal::Sent::Delivered);
Ok(())
}
#[cfg(unix)]
fn kill_delivered(&self) -> bool {
self.delivered
}
fn try_wait(&mut self) -> std::io::Result<Option<std::process::ExitStatus>> {
use crate::wait::exit_only::{try_reap, Reap, Reaped};
if self.reaped.is_some() {
return Ok(self.reaped);
}
match try_reap(&self.target())? {
Reap::Reaped(Reaped::Status(status)) => {
self.reaped = Some(status);
Ok(Some(status))
}
Reap::Reaped(Reaped::Unreadable { si_code }) => Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
format!("the child's exit record was unreadable (si_code {si_code})"),
)),
Reap::Running => Ok(None),
Reap::Foreign(_) => Err(std::io::Error::from_raw_os_error(libc::ECHILD)),
}
}
fn wait(&mut self) -> std::io::Result<std::process::ExitStatus> {
use crate::wait::exit_only::{reap_blocking, Reaped};
if let Some(status) = self.reaped {
return Ok(status);
}
match reap_blocking(&self.target())? {
Ok(Reaped::Status(status)) => {
self.reaped = Some(status);
Ok(status)
}
Ok(Reaped::Unreadable { si_code }) => Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
format!("the child's exit record was unreadable (si_code {si_code})"),
)),
Err(_) => Err(std::io::Error::from_raw_os_error(libc::ECHILD)),
}
}
}
#[cfg(target_os = "linux")]
struct HeldStdChild {
child: std::process::Child,
through: PidfdChild,
}
#[cfg(target_os = "linux")]
impl HeldStdChild {
fn id(&self) -> u32 {
self.child.id()
}
}
#[cfg(target_os = "linux")]
impl Unadopted for HeldStdChild {
fn pid(&self) -> Option<u32> {
Some(self.child.id())
}
fn pidfd(&self) -> Option<std::os::fd::BorrowedFd<'_>> {
self.through.pidfd()
}
fn kill(&mut self) -> std::io::Result<()> {
self.through.kill()
}
#[cfg(unix)]
fn kill_delivered(&self) -> bool {
self.through.kill_delivered()
}
fn try_wait(&mut self) -> std::io::Result<Option<std::process::ExitStatus>> {
self.through.try_wait()
}
fn wait(&mut self) -> std::io::Result<std::process::ExitStatus> {
self.through.wait()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(
target_os = "macos",
allow(
dead_code,
reason = "macOS leaves an unverified child without tearing it down, so it is never reaped here"
)
)]
pub(crate) enum FrontFate {
NotAFront,
Reaped,
LeftUnreaped,
Unaccounted,
#[cfg_attr(
not(target_os = "linux"),
allow(dead_code, reason = "only a Linux cgroup leaf places a front")
)]
Unplaced,
}
impl FrontFate {
#[cfg_attr(
not(target_os = "macos"),
allow(dead_code, reason = "only macOS leaves a child unverified")
)]
pub(crate) fn of_unverified(identity: crate::containment::RootIdentity) -> FrontFate {
match identity {
crate::containment::RootIdentity::Gone => FrontFate::Unaccounted,
crate::containment::RootIdentity::Unknown => FrontFate::LeftUnreaped,
}
}
pub(crate) fn note(self, error: Error, front: Option<crate::elevation::front::Front>, pid: Option<u32>) -> Error {
let Some(front) = front else {
return error;
};
let what = crate::elevation::front::describe(front, pid);
let fate = match self {
FrontFate::NotAFront => {
debug_assert!(false, "a front's teardown reports its fate");
return error;
}
FrontFate::Reaped => {
"it was sent no signal of its own; it had exited, or its cgroup's kill ended it, and it was reaped"
}
FrontFate::LeftUnreaped => {
"it was sent nothing, so the elevated program may be running; it is left unreaped"
}
FrontFate::Unaccounted => {
"it was sent nothing and could not be waited on, so the elevated program may be running"
}
FrontFate::Unplaced => {
"it was sent nothing, and where it is cannot be read, so the elevated program may be running; it \
is left unreaped"
}
};
error.with_note(&format!("{what}; {fate}"))
}
}
pub(crate) fn settle_before_teardown(
prepared: &mut crate::containment::Prepared,
#[cfg(target_os = "linux")] child: crate::containment::ChildHandle<'_>,
#[cfg(not(target_os = "linux"))] pid: u32,
) {
prepared.settle_verdict(
#[cfg(target_os = "linux")]
child,
#[cfg(not(target_os = "linux"))]
pid,
);
}
#[cfg(target_os = "linux")]
pub(crate) fn front_subtree(
leaf: Option<&crate::containment::cgroup::CgroupLeaf>,
) -> Option<crate::containment::cgroup::Subtree> {
match leaf?.subtree() {
Ok(subtree) => Some(subtree),
Err(e) => {
log::debug!("spawn: an elevation front's leaf subtree cannot be read ({e}); its teardown cannot place it");
None
}
}
}
#[cfg(not(target_os = "macos"))]
fn teardown_unadopted_or_front(
mut child: impl Unadopted,
front: Option<crate::elevation::front::Front>,
id: Option<ProcessId>,
#[cfg(target_os = "linux")] subtree: Option<&crate::containment::cgroup::Subtree>,
) -> (FrontFate, ChildFate) {
if front.is_none() {
return (FrontFate::NotAFront, teardown_unadopted(child, id));
}
#[cfg(all(test, target_os = "linux"))]
if fault::fronts_exit_before_teardown() {
let steps = crate::containment::cgroup::fault::take_leaf_steps();
crate::containment::cgroup::fault::record_leaf_steps();
assert!(
steps.iter().any(|s| s == "kill"),
"the leaf's kill was written before the teardown waits for the front's exit: {steps:?}"
);
if let Some(pid) = child.pid() {
crate::test_child::wait_until_zombie(pid);
}
}
#[cfg(test)]
let tried = if fault::fronts_seen_running() {
Ok(None)
} else {
child.try_wait()
};
#[cfg(not(test))]
let tried = child.try_wait();
let fate = fate_of_a_look(tried.as_ref().map(|s| *s).map_err(std::io::Error::raw_os_error), id);
match tried {
Ok(Some(_)) => (FrontFate::Reaped, fate),
Ok(None) => {
#[cfg(target_os = "linux")]
let mut unplaced = false;
#[cfg(target_os = "linux")]
if let (Some(subtree), Some(pid)) = (subtree, child.pid()) {
match subtree.reached(pid, child.pidfd()) {
Ok(true) => {
#[cfg(test)]
fault::run_between_kill_and_wait();
return match child.wait() {
Ok(_status) => {
#[cfg(test)]
fault::record_teardown_reap(pid, _status);
(FrontFate::Reaped, ChildFate::Reaped)
}
Err(e) => {
log::warn!(
"spawn teardown: elevation front {} could not be reaped ({e})",
named(Some(pid))
);
(FrontFate::Unaccounted, ChildFate::Killed)
}
};
}
Ok(false) => {}
Err(e) => {
log::debug!(
"spawn teardown: elevation front {}'s cgroup cannot be read ({e})",
named(Some(pid))
);
unplaced = true;
}
}
}
log::warn!(
"spawn teardown left elevation front {} running, unsignalled and unreaped: a kill would orphan the \
elevated program",
named(child.pid())
);
#[cfg(target_os = "linux")]
if unplaced {
return (FrontFate::Unplaced, ChildFate::Unknown);
}
(FrontFate::LeftUnreaped, fate)
}
Err(e) => {
log::debug!(
"spawn teardown: elevation front {} cannot be waited on ({e})",
named(child.pid())
);
(FrontFate::Unaccounted, fate)
}
}
}
#[cfg(target_os = "linux")]
pub(crate) fn leave_front_through_pidfd(
pid: Option<u32>,
pidfd: std::os::fd::OwnedFd,
front: crate::elevation::front::Front,
id: Option<ProcessId>,
subtree: Option<&crate::containment::cgroup::Subtree>,
) -> (FrontFate, ChildFate) {
teardown_unadopted_or_front(PidfdChild::new(pid, pidfd), Some(front), id, subtree)
}
#[cfg(target_os = "linux")]
pub(crate) fn teardown_through_pidfd(
pid: Option<u32>,
pidfd: std::os::fd::OwnedFd,
id: Option<ProcessId>,
) -> ChildFate {
use crate::wait::exit_only::{peek, Peek};
let child = PidfdChild::new(pid, pidfd);
match peek(&child.target()) {
Ok(Peek::Foreign(why)) => {
log::debug!("{}: already collected when its spawn failed", named(pid));
return why.fate(false);
}
Ok(Peek::Exit(_) | Peek::Running) => {}
Err(e) => {
log::warn!(
"{}: its spawn failed, and its pidfd could not be waited on ({e}); it is left as it is",
named(pid)
);
debug_assert!(false, "waitid on a spawned child's pidfd failed: {e}");
return ChildFate::Unknown;
}
}
teardown_unadopted(child, id)
}
#[cfg(not(target_os = "macos"))]
fn teardown_unadopted(mut child: impl Unadopted, id: Option<ProcessId>) -> ChildFate {
if let Err(kill) = kill_unadopted(&mut child) {
log::warn!(
"spawn teardown failed to kill {}: {kill}; reaping it in the background once it exits",
named(child.pid())
);
let looked = child.try_wait();
let fate = fate_of_a_look(looked.as_ref().map(|s| *s).map_err(std::io::Error::raw_os_error), id);
if !matches!(looked, Ok(Some(_))) {
reap_in_background(child);
}
debug_assert!(
kill.kind() == std::io::ErrorKind::PermissionDenied,
"sync spawn teardown failed to kill child: {kill}"
);
return fate;
}
#[cfg(test)]
fault::run_between_kill_and_wait();
match reap_unadopted(&mut child) {
Ok(_) => ChildFate::Reaped,
#[cfg(unix)]
Err(reap) if reap.raw_os_error() == Some(libc::ECHILD) => {
log::debug!("spawn teardown: {} was reaped by someone else", named(child.pid()));
crate::wait::exit_only::Foreign::Gone.fate(child.kill_delivered())
}
Err(reap) => {
log::warn!("spawn teardown failed to reap {}: {reap}", named(child.pid()));
debug_assert!(false, "sync spawn teardown failed to reap child: {reap}");
ChildFate::Killed
}
}
}
#[cfg(not(target_os = "macos"))]
fn reap_in_background(mut child: impl Unadopted) {
#[cfg(test)]
let notify = fault::take_background_reap_notifier();
let name = child
.pid()
.map_or_else(|| "cosca-reap".to_string(), |pid| format!("cosca-reap-{pid}"));
let pid = named(child.pid());
let reaper_pid = pid.clone();
let spawned = std::thread::Builder::new().name(name).spawn(move || {
let pid = reaper_pid;
let reaped = child.wait().map(drop);
if let Err(e) = &reaped {
log::warn!("background reap of {pid} failed: {e}");
}
#[cfg(test)]
if let Some(notify) = notify {
_ = notify.send(reaped);
}
});
if let Err(e) = spawned {
log::warn!("could not start a thread to reap {pid}, which stays unreaped: {e}");
}
}
#[cfg(not(target_os = "macos"))]
fn kill_unadopted(child: &mut impl Unadopted) -> std::io::Result<()> {
#[cfg(test)]
if let Some((marker, kind, alive)) = fault::take_force_kill_failure() {
if !alive {
child.kill()?;
child.wait()?;
}
return Err(std::io::Error::new(kind, marker));
}
#[cfg(test)]
let killed = match fault::take_force_kill_error_after_exit() {
Some((marker, kind)) => {
child.wait()?;
Err(std::io::Error::new(kind, marker))
}
None => child.kill(),
};
#[cfg(not(test))]
let killed = child.kill();
match killed {
Err(_) if matches!(child.try_wait(), Ok(Some(_))) => Ok(()),
other => other,
}
}
#[cfg(not(target_os = "macos"))]
fn reap_unadopted(child: &mut impl Unadopted) -> std::io::Result<std::process::ExitStatus> {
#[cfg(test)]
let forced = fault::take_force_reap_failure();
let status = child.wait()?;
#[cfg(test)]
fault::record_teardown_reap(child.pid().unwrap_or(0), status);
#[cfg(test)]
if let Some(marker) = forced {
return Err(std::io::Error::other(marker));
}
Ok(status)
}
#[cfg(test)]
pub(crate) mod fault {
use std::cell::Cell;
use crate::identity::ProcessId;
thread_local! {
#[cfg(not(target_os = "macos"))]
static FRONTS_SEEN_RUNNING: Cell<bool> = const { Cell::new(false) };
#[cfg(target_os = "linux")]
static FRONTS_EXIT_FIRST: Cell<bool> = const { Cell::new(false) };
}
#[cfg(target_os = "linux")]
pub(crate) fn see_fronts_running() -> SeeFrontsRunning {
FRONTS_SEEN_RUNNING.with(|f| f.set(true));
SeeFrontsRunning(())
}
#[cfg(target_os = "linux")]
#[must_use = "fronts are seen as they are again as soon as the guard is dropped"]
pub(crate) struct SeeFrontsRunning(());
#[cfg(target_os = "linux")]
impl Drop for SeeFrontsRunning {
fn drop(&mut self) {
FRONTS_SEEN_RUNNING.with(|f| f.set(false));
}
}
#[cfg(not(target_os = "macos"))]
pub(crate) fn fronts_seen_running() -> bool {
FRONTS_SEEN_RUNNING.with(Cell::get)
}
#[cfg(target_os = "linux")]
pub(crate) fn exit_fronts_before_teardown() -> ExitFrontsFirst {
FRONTS_EXIT_FIRST.with(|f| f.set(true));
ExitFrontsFirst(())
}
#[cfg(target_os = "linux")]
#[must_use = "fronts are read as they are again as soon as the guard is dropped"]
pub(crate) struct ExitFrontsFirst(());
#[cfg(target_os = "linux")]
impl Drop for ExitFrontsFirst {
fn drop(&mut self) {
FRONTS_EXIT_FIRST.with(|f| f.set(false));
}
}
#[cfg(target_os = "linux")]
pub(crate) fn fronts_exit_before_teardown() -> bool {
FRONTS_EXIT_FIRST.with(Cell::get)
}
#[cfg(all(target_os = "linux", feature = "tokio"))]
type PidHook = Box<dyn FnOnce(u32)>;
thread_local! {
static FORCE_VANISH: Cell<bool> = const { Cell::new(false) };
static FORCE_UNKNOWN: Cell<bool> = const { Cell::new(false) };
static FORCE_ATTACH_FAIL: Cell<bool> = const { Cell::new(false) };
static FORCE_REAP_FAIL: Cell<Option<&'static str>> = const { Cell::new(None) };
static FORCE_KILL_FAIL: Cell<Option<(&'static str, std::io::ErrorKind, bool)>> = const { Cell::new(None) };
static FORCE_KILL_ERROR_AFTER_EXIT: Cell<Option<(&'static str, std::io::ErrorKind)>> = const { Cell::new(None) };
static BACKGROUND_REAP_NOTIFY: Cell<Option<std::sync::mpsc::Sender<std::io::Result<()>>>> = const { Cell::new(None) };
static CAPTURED: Cell<Option<crate::identity::Resolved<ProcessId>>> = const { Cell::new(None) };
static BETWEEN_KILL_AND_WAIT: crate::oneshot_hook::OneShotHook = const { crate::oneshot_hook::OneShotHook::new() };
static SPAWN_PID: Cell<Option<u32>> = const { Cell::new(None) };
static BEFORE_IDENTITY: crate::oneshot_hook::OneShotHook = const { crate::oneshot_hook::OneShotHook::new() };
static BEFORE_ATTACH: crate::oneshot_hook::OneShotHook = const { crate::oneshot_hook::OneShotHook::new() };
static AFTER_IDENTITY_READ: crate::oneshot_hook::OneShotHook = const { crate::oneshot_hook::OneShotHook::new() };
static TEARDOWN_REAPS: std::cell::RefCell<Option<Vec<TeardownReap>>> = const { std::cell::RefCell::new(None) };
#[cfg(target_os = "linux")]
static ATTACHMENT_OVERRIDE: std::cell::RefCell<Option<crate::containment::Attachment>> =
const { std::cell::RefCell::new(None) };
#[cfg(all(target_os = "linux", feature = "tokio"))]
static FORCE_POST_FORK_FAIL: Cell<bool> = const { Cell::new(false) };
#[cfg(feature = "tokio")]
static FAIL_TOKIO_SPAWN: Cell<bool> = const { Cell::new(false) };
#[cfg(all(target_os = "linux", feature = "tokio"))]
static AFTER_FAILED_TOKIO_FORK: std::cell::RefCell<Option<PidHook>> = const { std::cell::RefCell::new(None) };
#[cfg(feature = "tokio")]
static FORGOTTEN_PID: Cell<Option<u32>> = const { Cell::new(None) };
#[cfg(all(target_os = "linux", feature = "tokio"))]
static FORGOTTEN_LEAF: std::cell::RefCell<Option<std::path::PathBuf>> = const { std::cell::RefCell::new(None) };
#[cfg(all(target_os = "linux", feature = "tokio"))]
static FORGOTTEN_PIDFD: std::cell::RefCell<Option<std::os::fd::OwnedFd>> = const { std::cell::RefCell::new(None) };
}
#[cfg(all(target_os = "linux", feature = "tokio"))]
pub(crate) fn set_force_post_fork_failure(on: bool) {
FORCE_POST_FORK_FAIL.with(|f| f.set(on));
}
#[cfg(feature = "tokio")]
pub(crate) fn take_forgotten_pid() -> Option<u32> {
FORGOTTEN_PID.with(|f| f.take())
}
#[cfg(all(target_os = "linux", feature = "tokio"))]
pub(crate) fn take_forgotten_pidfd() -> Option<std::os::fd::OwnedFd> {
FORGOTTEN_PIDFD.with(|f| f.borrow_mut().take())
}
#[cfg(all(target_os = "linux", feature = "tokio"))]
pub(crate) fn take_forgotten_leaf() -> Option<std::path::PathBuf> {
FORGOTTEN_LEAF.with(|f| f.take())
}
#[cfg(feature = "tokio")]
pub(crate) fn fail_tokio_spawns_after_fork() -> FailTokioSpawns {
FAIL_TOKIO_SPAWN.with(|f| f.set(true));
FailTokioSpawns(())
}
#[cfg(all(target_os = "linux", feature = "tokio"))]
pub(crate) fn fail_tokio_spawns_after_fork_then(hook: impl FnOnce(u32) + 'static) -> FailTokioSpawns {
AFTER_FAILED_TOKIO_FORK.with(|h| *h.borrow_mut() = Some(Box::new(hook)));
fail_tokio_spawns_after_fork()
}
#[cfg(feature = "tokio")]
#[must_use = "spawns succeed again as soon as the guard is dropped"]
pub(crate) struct FailTokioSpawns(());
#[cfg(feature = "tokio")]
impl Drop for FailTokioSpawns {
fn drop(&mut self) {
FAIL_TOKIO_SPAWN.with(|f| f.set(false));
#[cfg(target_os = "linux")]
AFTER_FAILED_TOKIO_FORK.with(|h| h.borrow_mut().take());
}
}
#[cfg(all(target_os = "linux", feature = "tokio"))]
pub(crate) fn fail_tokio_spawn_after_fork(
spawned: std::io::Result<::tokio::process::Child>,
leaf: Option<&std::path::Path>,
) -> std::io::Result<::tokio::process::Child> {
if !FAIL_TOKIO_SPAWN.with(Cell::get) {
return spawned;
}
FORGOTTEN_LEAF.with(|f| *f.borrow_mut() = leaf.map(std::path::Path::to_path_buf));
let child = spawned?;
if let (Some(hook), Some(pid)) = (AFTER_FAILED_TOKIO_FORK.with(|h| h.borrow_mut().take()), child.id()) {
hook(pid);
}
forget_child(child);
Err(std::io::Error::from_raw_os_error(libc::ENOSPC))
}
#[cfg(all(not(target_os = "linux"), feature = "tokio"))]
pub(crate) fn fail_tokio_spawn_after_fork(
spawned: std::io::Result<::tokio::process::Child>,
) -> std::io::Result<::tokio::process::Child> {
if !FAIL_TOKIO_SPAWN.with(Cell::get) {
return spawned;
}
let child = spawned?;
FORGOTTEN_PID.with(|f| f.set(child.id()));
std::mem::forget(child);
Err(std::io::Error::other(
"forced tokio spawn failure after the fork (test seam)",
))
}
#[cfg(all(target_os = "linux", feature = "tokio"))]
fn forget_child(child: ::tokio::process::Child) -> u32 {
FORGOTTEN_PID.with(|f| f.set(child.id()));
let pidfd = child
.id()
.and_then(|pid| rustix::process::Pid::from_raw(pid as i32))
.and_then(|pid| rustix::process::pidfd_open(pid, rustix::process::PidfdFlags::empty()).ok())
.and_then(|pidfd| rustix::io::fcntl_dupfd_cloexec(&pidfd, 3).ok());
FORGOTTEN_PIDFD.with(|f| *f.borrow_mut() = pidfd);
let pid = child.id().expect("an unreaped child has its pid");
std::mem::forget(child);
pid
}
#[cfg(all(target_os = "linux", feature = "tokio"))]
pub(crate) fn post_fork_failure(
spawned: Result<::tokio::process::Child, super::SpawnFailure>,
leaf: Option<&std::path::Path>,
) -> Result<::tokio::process::Child, super::SpawnFailure> {
if !FORCE_POST_FORK_FAIL.with(|f| f.replace(false)) {
return spawned;
}
FORGOTTEN_LEAF.with(|f| *f.borrow_mut() = leaf.map(std::path::Path::to_path_buf));
let child = spawned?;
let pid = forget_child(child);
Err(super::SpawnFailure::started(
crate::error::Error::Io(std::io::Error::other(format!(
"forced post-fork spawn failure (test seam) for child {pid}"
))),
crate::error::ChildFate::Unknown,
))
}
pub(crate) fn set_force_identity_vanished(on: bool) {
FORCE_VANISH.with(|f| f.set(on));
}
#[cfg(unix)]
pub(crate) fn set_force_identity_unknown(on: bool) {
FORCE_UNKNOWN.with(|f| f.set(on));
}
pub(crate) fn force_identity_unknown() -> bool {
FORCE_UNKNOWN.with(|f| f.get())
}
pub(crate) fn force_identity_vanished() -> bool {
FORCE_VANISH.with(|f| f.get())
}
pub(crate) fn set_force_attach_failure(on: bool) {
FORCE_ATTACH_FAIL.with(|f| f.set(on));
}
#[cfg(target_os = "linux")]
pub(crate) fn set_attachment_override(attachment: crate::containment::Attachment) {
ATTACHMENT_OVERRIDE.with(|f| *f.borrow_mut() = Some(attachment));
}
#[cfg(target_os = "linux")]
pub(crate) fn take_attachment_override() -> Option<crate::containment::Attachment> {
ATTACHMENT_OVERRIDE.with(|f| f.borrow_mut().take())
}
pub(crate) fn force_attach_failure() -> bool {
FORCE_ATTACH_FAIL.with(|f| f.get())
}
pub(crate) fn set_force_reap_failure(marker: &'static str) {
FORCE_REAP_FAIL.with(|f| f.set(Some(marker)));
}
pub(crate) fn take_force_reap_failure() -> Option<&'static str> {
FORCE_REAP_FAIL.with(|f| f.take())
}
#[cfg(not(target_os = "macos"))]
pub(crate) fn set_force_kill_failure(marker: &'static str, kind: std::io::ErrorKind) {
FORCE_KILL_FAIL.with(|f| f.set(Some((marker, kind, false))));
}
#[cfg(not(target_os = "macos"))]
pub(crate) fn set_force_kill_failure_leaving_child_alive(marker: &'static str) {
set_force_kill_failure_leaving_child_alive_as(marker, std::io::ErrorKind::Other);
}
#[cfg(any(not(target_os = "macos"), feature = "tokio"))]
pub(crate) fn set_force_kill_failure_leaving_child_alive_as(marker: &'static str, kind: std::io::ErrorKind) {
FORCE_KILL_FAIL.with(|f| f.set(Some((marker, kind, true))));
}
#[cfg(not(target_os = "macos"))]
pub(crate) fn set_force_kill_error_after_exit(marker: &'static str, kind: std::io::ErrorKind) {
FORCE_KILL_ERROR_AFTER_EXIT.with(|f| f.set(Some((marker, kind))));
}
#[cfg(not(target_os = "macos"))]
pub(crate) fn take_force_kill_error_after_exit() -> Option<(&'static str, std::io::ErrorKind)> {
FORCE_KILL_ERROR_AFTER_EXIT.with(|f| f.take())
}
#[cfg(not(target_os = "macos"))]
pub(crate) fn set_background_reap_notifier(notify: std::sync::mpsc::Sender<std::io::Result<()>>) {
BACKGROUND_REAP_NOTIFY.with(|f| f.set(Some(notify)));
}
#[cfg(not(target_os = "macos"))]
pub(crate) fn take_background_reap_notifier() -> Option<std::sync::mpsc::Sender<std::io::Result<()>>> {
BACKGROUND_REAP_NOTIFY.with(|f| f.take())
}
#[cfg(any(not(target_os = "macos"), feature = "tokio"))]
pub(crate) fn take_force_kill_failure() -> Option<(&'static str, std::io::ErrorKind, bool)> {
FORCE_KILL_FAIL.with(|f| f.take())
}
pub(crate) fn capture(id: crate::identity::Resolved<ProcessId>) {
CAPTURED.with(|c| c.set(Some(id)));
}
pub(crate) fn take_captured() -> Option<crate::identity::Resolved<ProcessId>> {
CAPTURED.with(|c| c.take())
}
pub(crate) fn set_between_kill_and_wait(hook: impl FnOnce() + 'static) -> ArmedBetweenKillAndWait {
crate::oneshot_hook::arm(&BETWEEN_KILL_AND_WAIT, hook)
}
pub(crate) fn run_between_kill_and_wait() {
crate::oneshot_hook::fire(&BETWEEN_KILL_AND_WAIT);
}
pub(crate) type ArmedBetweenKillAndWait = crate::oneshot_hook::Armed;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum SpawnPoint {
BeforeIdentity,
BeforeAttach,
AfterIdentityRead,
}
fn hook_at(point: SpawnPoint) -> &'static std::thread::LocalKey<crate::oneshot_hook::OneShotHook> {
match point {
SpawnPoint::BeforeIdentity => &BEFORE_IDENTITY,
SpawnPoint::BeforeAttach => &BEFORE_ATTACH,
SpawnPoint::AfterIdentityRead => &AFTER_IDENTITY_READ,
}
}
#[cfg_attr(
not(all(feature = "tokio", target_os = "linux")),
allow(dead_code, reason = "only the Linux async spawn's tests arm a spawn point so far")
)]
pub(crate) fn set_at(point: SpawnPoint, hook: impl FnOnce() + 'static) -> crate::oneshot_hook::Armed {
crate::oneshot_hook::arm(hook_at(point), hook)
}
pub(crate) fn run_at(point: SpawnPoint, pid: u32) {
SPAWN_PID.with(|p| p.set(Some(pid)));
crate::oneshot_hook::fire(hook_at(point));
SPAWN_PID.with(|p| p.set(None));
}
#[cfg_attr(
not(all(feature = "tokio", target_os = "linux")),
allow(dead_code, reason = "only the Linux async spawn's tests arm a spawn point so far")
)]
pub(crate) fn spawn_pid() -> u32 {
SPAWN_PID.with(Cell::get).expect("spawn_pid is read from a spawn hook")
}
type TeardownReap = (u32, std::process::ExitStatus);
pub(crate) fn record_teardown_reaps() -> TeardownReaps {
let previous = TEARDOWN_REAPS.with(|r| r.borrow_mut().replace(Vec::new()));
debug_assert!(previous.is_none(), "teardown reaps are already being recorded");
TeardownReaps
}
pub(crate) fn record_teardown_reap(pid: u32, status: std::process::ExitStatus) {
TEARDOWN_REAPS.with(|r| {
if let Some(reaps) = r.borrow_mut().as_mut() {
reaps.push((pid, status));
}
});
}
#[must_use]
pub(crate) struct TeardownReaps;
impl TeardownReaps {
pub(crate) fn recorded(&self) -> Vec<TeardownReap> {
TEARDOWN_REAPS.with(|r| r.borrow().clone().unwrap_or_default())
}
}
impl Drop for TeardownReaps {
fn drop(&mut self) {
let reaps = TEARDOWN_REAPS.with(|r| r.borrow_mut().take());
drop(reaps);
}
}
pub(crate) fn teardown_blocker_stdin() -> (crate::stdio::Stdio, TeardownBlocker) {
let (reader, writer) = std::io::pipe().expect("pipe");
#[cfg(unix)]
let reader = std::os::fd::OwnedFd::from(reader);
#[cfg(windows)]
let reader = std::os::windows::io::OwnedHandle::from(reader);
let fired = std::rc::Rc::new(std::cell::Cell::new(false));
let release = set_between_kill_and_wait({
let fired = std::rc::Rc::clone(&fired);
move || {
drop(writer);
fired.set(true);
}
});
let reaps = record_teardown_reaps();
(
crate::stdio::Stdio::from_file(std::fs::File::from(reader)),
TeardownBlocker {
_release: release,
#[cfg(any(not(target_os = "macos"), feature = "tokio"))]
fired,
reaps,
},
)
}
pub(crate) struct TeardownBlockerParts {
pub(crate) argv: Vec<std::ffi::OsString>,
pub(crate) stdin: crate::stdio::Stdio,
pub(crate) stdout: Option<crate::stdio::Stdio>,
pub(crate) guard: TeardownBlocker,
}
pub(crate) fn teardown_blocker_parts() -> TeardownBlockerParts {
let (stdin, guard) = teardown_blocker_stdin();
#[cfg(unix)]
let (argv, stdout) = (crate::test_child::BLOCKER_ARGV.iter().map(Into::into).collect(), None);
#[cfg(windows)]
let (argv, stdout) = (
vec![crate::test_child::windows_more().into_os_string()],
Some(crate::stdio::Stdio::null()),
);
TeardownBlockerParts {
argv,
stdin,
stdout,
guard,
}
}
#[must_use]
pub(crate) struct TeardownBlocker {
_release: ArmedBetweenKillAndWait,
#[cfg(any(not(target_os = "macos"), feature = "tokio"))]
fired: std::rc::Rc<std::cell::Cell<bool>>,
reaps: TeardownReaps,
}
impl TeardownBlocker {
#[cfg(unix)]
pub(crate) fn recorded(&self) -> Vec<TeardownReap> {
self.reaps.recorded()
}
#[cfg(any(not(target_os = "macos"), feature = "tokio"))]
pub(crate) fn assert_killed(&self) {
assert!(
self.fired.get(),
"the teardown must have reached its between-kill-and-wait hook"
);
let reaps = self.reaps.recorded();
assert!(!reaps.is_empty(), "the teardown must have reaped the child");
for (pid, status) in reaps {
#[cfg(unix)]
{
use std::os::unix::process::ExitStatusExt as _;
assert_eq!(
status.signal(),
Some(libc::SIGKILL),
"pid {pid} must be SIGKILLed by its teardown kill, not merely reaped once it exits on its own: {status:?}"
);
}
#[cfg(windows)]
assert_eq!(
status.code(),
Some(1),
"pid {pid} must be terminated by its teardown kill (`TerminateProcess` exits 1), not merely reaped once it exits on its own"
);
}
}
}
#[cfg(any(not(target_os = "macos"), feature = "tokio"))]
pub(crate) fn assert_child_reaped(captured: crate::identity::Resolved<ProcessId>) {
let crate::identity::Resolved::Found(captured) = captured else {
panic!("the seam must capture a resolved identity, got {captured:?}");
};
#[cfg(unix)]
match ProcessId::of(captured.pid()) {
crate::identity::Resolved::Found(id) => assert_ne!(
id, captured,
"a failed spawn must fully reap its child (no lingering zombie at its identity)"
),
crate::identity::Resolved::Gone => {}
crate::identity::Resolved::Unknown => {}
}
#[cfg(windows)]
assert_eq!(
captured.is_alive(),
crate::identity::Liveness::Dead,
"a failed spawn must leave the child dead"
);
}
}
#[path = "spawn/batch_gate.rs"]
mod batch_gate;
pub(crate) use batch_gate::reject_batch_path;
#[cfg(unix)]
#[path = "spawn/fd_map.rs"]
pub(crate) mod fd_map;
#[cfg(any(target_os = "linux", target_os = "macos"))]
#[path = "spawn/fd_channel.rs"]
pub(crate) mod fd_channel;
#[path = "spawn/failure.rs"]
pub(crate) mod failure;
#[cfg(target_os = "linux")]
#[path = "spawn/pidfd_handshake.rs"]
pub(crate) mod pidfd_handshake;
#[cfg(windows)]
#[path = "spawn/windows_raw.rs"]
pub(crate) mod windows_raw;
#[cfg(test)]
#[path = "spawn_tests.rs"]
mod spawn_tests;
#[cfg(all(test, target_os = "linux"))]
#[path = "spawn/placement_reuse_tests.rs"]
mod placement_reuse_tests;
#[cfg(test)]
#[path = "spawn/spawn_lock_tests.rs"]
mod spawn_lock_tests;
#[cfg(all(test, unix))]
#[path = "spawn/exact_posix_tests.rs"]
mod exact_posix_tests;
#[cfg(all(test, target_os = "linux"))]
#[path = "spawn/identity_error_tests.rs"]
mod identity_error_tests;
#[cfg(all(test, target_os = "macos"))]
#[path = "spawn/identity_macos_tests.rs"]
pub(crate) mod identity_macos_tests;
#[cfg(all(test, target_os = "linux"))]
#[path = "spawn/identity_peek_tests.rs"]
mod identity_peek_tests;
#[cfg(target_os = "macos")]
#[path = "spawn/unique_report.rs"]
pub(crate) mod unique_report;
#[cfg(all(test, target_os = "linux"))]
#[path = "spawn/front_teardown_tests.rs"]
mod front_teardown_tests;