use std::collections::BTreeMap;
use std::process::Stdio as StdStdio;
#[cfg(unix)]
use crate::child::lifecycle::{wait_to_exit, Settlement};
#[cfg(unix)]
use crate::child::owned::teardown::{Disposition, Remains, TeardownOutcome};
#[cfg(unix)]
use crate::child::owned::ChildWaitOutcome;
use crate::child::owned::OwnedChild;
pub(crate) use crate::child::spawn::failure::{after_the_spawn, failed_after_the_spawn, Classify, SpawnFailure};
use crate::child::Child;
use crate::command::{Command, CommandInput, EnvOp};
#[cfg(any(unix, feature = "tokio"))]
use crate::error::ChildFate;
use crate::error::Error;
use crate::identity::ProcessId;
use crate::pipe::ParentEnd;
use crate::stdio::{Direction, Fd, ResolvedStdio};
#[cfg(unix)]
pub(crate) type ChildEnd = std::os::unix::io::OwnedFd;
#[cfg(windows)]
pub(crate) use windows_child_end::ChildEnd;
pub(crate) fn spawn(cmd: &mut Command) -> Result<Child, SpawnFailure> {
spawn_uncommitted(cmd)?.commit_kill_on_drop()
}
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 {
mut 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 r = spawn_unelevated(&mut derived, kill_on_drop);
let mut child = match backend_path.as_deref() {
Some(bp) => r.map_err(|f| f.map(|e| crate::elevation::remap_derived_spawn_error(e, bp)))?,
None => r?,
};
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(mut child: Child, written: Result<(), Error>) -> Result<Child, SpawnFailure> {
use crate::containment::dispatch::{SettleOutcome, TreeKillOutcome};
let Err(write_err) = written else {
return Ok(child);
};
let gate = child.kill_gate();
let view = crate::containment::DropView::read(
crate::containment::dispatch::TeardownCaller::FinishElevated,
child.pid(),
child.id,
|| child.proc.state(),
&child.tree_killed,
);
let mut report = crate::child::drop_report::DropReport::new(&view);
let mut skipped = None;
let front_closed = matches!(gate, crate::elevation::front::Gate::Closed(_));
let kill_tree = || {
let held = child.proc.hold(child.pid());
child.attached.hard_kill_for_drop(&view, &held.group())
};
let tree = (child.containment().can_teardown() && !front_closed).then(|| {
let kill = kill_tree();
skipped = kill.skip_note(&view);
kill
});
let tree_failure = tree.as_ref().and_then(TreeKillOutcome::incomplete);
let exited_front = matches!(gate, crate::elevation::front::Gate::Exited);
let pid = child.pid();
let (root_note, torn) = if view.unpinned_root() {
let fate = crate::os_process::child::Foreign::Gone.fate(false);
(
format!(
"the elevated child was left alone, neither signalled nor waited on: {}",
view.why_number_untrusted()
),
Remains::collected(fate),
)
} else {
let root = match gate {
crate::elevation::front::Gate::CgroupOnly if tree.as_ref().is_some_and(TreeKillOutcome::completed) => {
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.pid(),
tree_failure.as_deref(),
)),
crate::elevation::front::Gate::Closed(unkillable) => Err(unkillable),
gate => child.kill_sent_gated(gate),
};
match root {
Ok(crate::signal::Sent::Gone) if exited_front => (
"the elevated child had already exited, and was reaped by someone else".to_string(),
Remains::collected(ChildFate::Gone),
),
Ok(crate::signal::Sent::Gone) => (
"the elevated child could not be terminated (it was already reaped)".to_string(),
Remains::collected(ChildFate::Gone),
),
Ok(crate::signal::Sent::Unverified) => {
debug_assert!(false, "a sync child's kill always verifies its target");
let torn = TeardownOutcome::left_uncollected(
ChildFate::Running { id: child.id() },
format!(
"the elevated child pid {pid} could not be terminated (it could not be verified, and may \
still be running){}",
Disposition::HandBack.suffix(true)
),
);
(
"the elevated child could not be terminated (it could not be verified, and may still be running)"
.to_string(),
report.fold_clause(torn),
)
}
Ok(crate::signal::Sent::Delivered) => {
#[cfg(test)]
fault::run_between_kill_and_wait();
let settlement = Settlement::new(wait_killed_elevated(&child), true);
#[cfg(test)]
if let Some(status) = settlement.status() {
fault::record_teardown_reap(pid, status);
}
let (note, torn) = root_after_a_delivered_kill(pid, child.id(), exited_front, &settlement);
(note, report.fold_clause(torn))
}
Err(e) => {
#[cfg(test)]
fault::run_between_kill_and_wait();
let note = format!("the elevated child {}", crate::child::owned::teardown::kill_refused(&e));
let looked = child.proc.look_after_refused_kill(child.id(), e, Disposition::HandBack);
(
root_after_a_refused_kill(note, looked.refused_look()),
report.fold_clause(looked),
)
}
}
};
let hands_back = Disposition::HandBack.hands_back(&torn);
let fate = torn.fate;
let tree = tree.map(|kill| child.attached.settle(&child.tree_killed, kill, fate.not_running()));
let tree_settled = !tree_needs_another_kill(&tree) || (skipped.is_some() && view.leaves_root_alone());
let unvouched = matches!(tree, Some(Ok(SettleOutcome::Unvouched { .. })));
debug_assert!(
!unvouched || hands_back || fate.not_running(),
"an unvouched tree leaves the handle disarmed only over a root that ended or went to the caller: {fate:?}"
);
let subject = child.attached.teardown_subject();
let (mut tree_note, tree_warn) = report_tree_teardown(tree, &subject);
report.tree = tree_warn;
if let Some(note) = skipped {
tree_note.push_str(&format!("; its contained tree was not killed: {note}"));
}
if hands_back && !tree_settled {
let early = kill_tree();
let more = match child.attached.settle(&child.tree_killed, early, fate.not_running()) {
Ok(SettleOutcome::Skipped) => None,
Ok(SettleOutcome::Killed) => {
tree_note.clear();
report.tree = tree_failure.as_ref().map(|first| {
format!(
"tree teardown after a failed password write needed the drop's tree kill, made early \
({subject}): the cleanup's kill failed: {first}"
)
});
None
}
Ok(outcome @ SettleOutcome::Unvouched { kind }) => Some((
format!("; on the drop's tree kill, made early, {}", kind.unvouched_text()),
Ok(outcome),
)),
Err(again) => Some((
format!("; the drop's tree kill, made early, failed too ({again})"),
Err(again),
)),
};
if let Some((added, again)) = more {
tree_note.push_str(&added);
match report.tree.as_mut() {
Some(warn) => warn.push_str(&added),
None => report.tree = report_tree_teardown(Some(again), &subject).1,
}
}
}
let warned = report.emit(&[]);
let root_note = if hands_back {
format!("{root_note}{}", Disposition::HandBack.suffix(true))
} else {
root_note
};
if hands_back || tree_settled {
child.kill_on_drop = false;
}
child.reported = warned;
let unreaped = hands_back.then(|| child.into_unreaped());
Err(SpawnFailure::started(
Error::Elevation {
kind: crate::error::ElevationErrorKind::AuthFailed,
detail: format!("{write_err}; {root_note}{tree_note}"),
},
fate,
unreaped,
))
}
#[cfg(unix)]
fn root_after_a_delivered_kill(
pid: u32,
id: Option<ProcessId>,
exited_front: bool,
settlement: &Settlement,
) -> (String, TeardownOutcome) {
let subject = if exited_front {
format!("the elevated child pid {pid} (it had already exited)")
} else {
format!("the elevated child pid {pid}")
};
let note = if settlement.status().is_some() {
if exited_front {
"the elevated child had already exited, and was reaped".to_string()
} else {
"the elevated child was terminated".to_string()
}
} else {
settlement.wording(&subject, None, None).text().to_owned()
};
let torn = TeardownOutcome::of_settlement(settlement, id, &subject, None, Disposition::HandBack);
(note, torn)
}
#[cfg(unix)]
fn root_after_a_refused_kill(refusal: String, looked: Option<&Settlement>) -> String {
match looked {
Some(settlement) if matches!(settlement.fate(None), ChildFate::Reaped) => {
let unreadable = settlement
.unreadable_record()
.map_or(String::new(), |why| format!("; {why}"));
format!("{refusal}: it has exited, and was reaped{unreadable}")
}
Some(settlement) => settlement.wording(&refusal, None, None).text().to_owned(),
None => refusal,
}
}
#[cfg(feature = "tokio")]
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<ChildWaitOutcome, Error> {
let waited = wait_to_exit(&child.proc, None);
#[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<crate::containment::dispatch::SettleOutcome, crate::containment::dispatch::Unsettled>>,
subject: &dyn std::fmt::Display,
) -> (String, Option<String>) {
use crate::containment::dispatch::SettleOutcome;
match tree {
Some(Err(e)) => (
format!("; its contained tree could not be killed ({subject}: {e})"),
Some(tree_teardown_warn(subject, &e)),
),
Some(Ok(SettleOutcome::Unvouched { kind })) => {
let text = kind.unvouched_text();
(
format!("; {text} ({subject})"),
Some(tree_teardown_warn(subject, &text)),
)
}
None | Some(Ok(SettleOutcome::Killed | SettleOutcome::Skipped)) => (String::new(), None),
}
}
#[cfg(unix)]
pub(crate) fn tree_needs_another_kill(
tree: &Option<Result<crate::containment::dispatch::SettleOutcome, crate::containment::dispatch::Unsettled>>,
) -> bool {
use crate::containment::dispatch::SettleOutcome;
!matches!(
tree,
None | Some(Ok(SettleOutcome::Killed | SettleOutcome::Unvouched { .. }))
)
}
#[cfg(unix)]
pub(crate) fn tree_teardown_warn(subject: &dyn std::fmt::Display, said: &dyn std::fmt::Display) -> String {
format!("{TREE_TEARDOWN_WARN} ({subject}): {said}")
}
#[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::os_process::linux::open::probe_pidfd_support_with(&crate::identity::HostKernel).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(unix)]
let mut steps = in_child::InChild::default();
#[cfg(target_os = "linux")]
let (mut std_cmd, handshake) = build_std_command_with(cmd, &mut steps, pidfd_handshake::register).not_started()?;
#[cfg(target_os = "macos")]
let (mut std_cmd, report) = build_std_command_with(cmd, &mut steps, 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 reserved = reserved_fds(&fds);
#[cfg(target_os = "macos")]
let (mut prepared, child, unique, parent_ends) = {
let (prepared, spawned, first, parent_ends) = {
let _guard = spawn_lock();
let parent_ends = resolve_into_std(&mut std_cmd, &mut steps, &fds).not_started()?;
let prepared = crate::containment::prepare(
&mut std_cmd,
&mut steps,
&cmd.contain_request(),
cmd.flags_request(),
&reserved,
cmd.fd_marker_suppressed(),
cmd.env_ops(),
)
.not_started()?;
let report = report.open(&_guard).not_started()?;
steps.register(&mut std_cmd);
#[allow(
clippy::disallowed_methods,
reason = "spawn_lock is held by `_guard`, taken at the top of this block"
)]
let (spawned, first) = report.run(|| std_cmd.spawn().map_err(Error::Io), |c| Some(c.id()));
drop(std_cmd);
(prepared, spawned, first, parent_ends)
};
let unique = first.finish();
let c = spawned
.map_err(|e| unique_report::failed_spawn_error(e, &unique))
.not_started()?;
(prepared, c, unique, parent_ends)
};
#[cfg(target_os = "linux")]
let (mut prepared, child, pidfd, parent_ends) = {
let parent_ends = resolve_into_std(&mut std_cmd, &mut steps, &fds).not_started()?;
let prepared = crate::containment::prepare(
&mut std_cmd,
&mut steps,
&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(&crate::identity::HostKernel, || leaf.id()).not_started()?;
}
let _guard = spawn_lock();
let handshake = handshake.open(&_guard).not_started()?;
steps.register(&mut std_cmd);
#[allow(clippy::disallowed_methods, reason = "spawn_lock is held by `_guard` above")]
let held = handshake.run(|| std_cmd.spawn())?;
(prepared, held.child, held.pidfd, parent_ends)
};
#[cfg(windows)]
let (mut prepared, child, parent_ends) = {
let parent_ends = resolve_into_std(&mut std_cmd, &fds).not_started()?;
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, parent_ends)
};
#[cfg(target_os = "linux")]
let (pid, owned) = {
let pid = child.id();
drop(child);
(
pid,
OwnedChild::new(Box::new(crate::os_process::linux::LinuxProcess::new(Some(pid), pidfd))),
)
};
#[cfg(windows)]
let (pid, owned) = {
let pid = child.id();
(
pid,
OwnedChild::new(Box::new(crate::os_process::windows::WindowsProcess::for_child(
std::os::windows::io::OwnedHandle::from(child),
pid,
))),
)
};
#[cfg(windows)]
let proc_handle = {
use std::os::windows::io::AsRawHandle;
owned.os_handle().as_raw_handle()
};
#[cfg(target_os = "macos")]
let pid = child.id();
let front = cmd.elevation_front();
#[cfg(target_os = "macos")]
let unique = match unique_report::adopted_id(unique, pid) {
Ok(unique) => unique,
Err(not_adopted) => return Err(abandon_unadopted(child, not_adopted, front, prepared)),
};
#[cfg(target_os = "linux")]
let subtree = front_subtree(front.and(prepared.cgroup_leaf.as_ref()));
if front.is_some() {
prepared.watch_front(pid);
}
#[cfg(test)]
fault::run_at(fault::SpawnPoint::BeforeIdentity, pid);
#[cfg(target_os = "linux")]
let through = crate::wait::exit_only::Target::PidFd(owned.os_handle());
#[cfg(target_os = "macos")]
let through = crate::wait::exit_only::Target::pid(pid, Some(unique));
#[cfg(windows)]
let through = crate::wait::exit_only::Target::Handle(owned.os_handle());
#[cfg(target_os = "linux")]
let handle = crate::containment::ChildHandle {
pid,
pidfd: owned.os_handle(),
};
let (resolved, cause, mut why) = resolve_identity(&crate::identity::HostKernel, pid, &through);
let id = match resolved {
crate::identity::Resolved::Found(id) => Ok(id),
crate::identity::Resolved::Unknown => Err(kept_without_identity(pid, cause, &mut why)),
other => {
settle_before_teardown(
&mut prepared,
#[cfg(target_os = "linux")]
handle,
);
#[cfg(target_os = "linux")]
if front.is_none() {
kill_group_before_teardown(&prepared, handle, &mut why);
}
#[cfg(target_os = "linux")]
if front.is_some() {
drop(prepared);
}
#[cfg(target_os = "macos")]
if front.is_none() {
note_group_left_running(&prepared, pid, &mut why);
}
#[cfg(target_os = "macos")]
let (fate, child_fate) = {
let identity = crate::containment::RootIdentity::Gone;
let child_fate = leave_unverified_child(child, identity, None, &mut why);
(front.map(|_| FrontFate::of_unverified(identity)), child_fate)
};
let error = spawn_identity_error(other, cause);
#[cfg(target_os = "linux")]
let (error, child_fate, unreaped) = held_teardown::tear_down_held(
owned,
held_teardown::HeldTeardown {
front,
id: None,
subtree: subtree.as_ref(),
disposition: crate::child::owned::teardown::Disposition::HandBack,
due: None,
},
&mut why,
error,
);
#[cfg(windows)]
let (child_fate, unreaped) = held_teardown::tear_down_failed_spawn(
owned,
None,
crate::child::owned::teardown::Past::Clean,
crate::child::owned::teardown::Disposition::HandBack,
None,
&mut why,
);
#[cfg(target_os = "macos")]
let (error, unreaped) = (note_front(fate, error, front, Some(pid)), None);
return Err(SpawnFailure::started(error, child_fate, unreaped));
}
};
#[cfg(test)]
fault::run_at(fault::SpawnPoint::BeforeAttach, pid);
let id_read = id.as_ref().ok().copied();
let attachment = match attach_or_fault(
#[cfg(unix)]
pid,
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) = {
if id_read.is_some() {
assert_attach_cannot_fail(&error);
}
if front.is_some() {
(
Some(leave_front_after_attach_failure(child)),
ChildFate::Running { id: id_read },
)
} else {
(None, teardown_after_attach_failure(child, unique, id_read))
}
};
#[cfg(target_os = "linux")]
let (error, child_fate, unreaped) = held_teardown::tear_down_held(
owned,
held_teardown::HeldTeardown {
front,
id: id_read,
subtree: subtree.as_ref(),
disposition: crate::child::owned::teardown::Disposition::HandBack,
due: None,
},
&mut why,
error,
);
#[cfg(target_os = "linux")]
return Err(SpawnFailure::started(error, child_fate, unreaped));
#[cfg(windows)]
{
let (child_fate, unreaped) = held_teardown::tear_down_failed_spawn(
owned,
id_read,
crate::child::owned::teardown::Past::Clean,
crate::child::owned::teardown::Disposition::HandBack,
None,
&mut why,
);
return Err(SpawnFailure::started(error, child_fate, unreaped));
}
#[cfg(target_os = "macos")]
return Err(SpawnFailure::started(
note_front(fate, error, front, Some(pid)),
child_fate,
None,
));
}
};
#[cfg(target_os = "macos")]
let owned = match crate::os_process::macos::child::MacChild::new(pid, unique) {
Ok(os) => {
drop(child);
OwnedChild::new(Box::new(os))
}
Err(error) => {
let (fate, child_fate) = if front.is_some() {
(
Some(leave_front_after_attach_failure(child)),
ChildFate::Running { id: id_read },
)
} else {
(None, teardown_after_attach_failure(child, unique, id_read))
};
return Err(SpawnFailure::started(
note_front(fate, error, front, Some(pid)),
child_fate,
None,
));
}
};
let mut child = Child::from_parts(owned, id_read, 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!(
"{} is left running and unreaped, with nothing signalled or waited on by pid: its attach failed, and a \
kill would orphan the elevated program",
crate::elevation::front::front_named(Some(child.id()))
);
drop(child);
FrontFate::LeftUnreaped
}
#[cfg(target_os = "macos")]
fn teardown_after_attach_failure(child: std::process::Child, unique: u64, id: Option<ProcessId>) -> ChildFate {
let fate = kill_and_reap_verified(child.id(), unique, id, ZOMBIE_NOTE, None);
drop(child);
fate
}
#[cfg(target_os = "macos")]
pub(crate) fn kill_and_reap_verified(
pid: u32,
unique: u64,
id: Option<ProcessId>,
left_running: &str,
warn_after: Option<std::time::Duration>,
) -> ChildFate {
let mut notes = Vec::new();
let mut breach = None;
let (fate, kill) = kill_and_reap_noting(pid, unique, id, warn_after, &mut notes, &mut breach, |_| {});
match kill {
KillOutcome::Refused(why) => notes.insert(0, format!("could not be killed: {why}")),
KillOutcome::Unverified => notes.insert(0, UNVERIFIED.to_owned()),
KillOutcome::Delivered | KillOutcome::NotSent => {}
}
if matches!(fate, ChildFate::Running { .. }) {
notes.push(left_running.to_owned());
}
if !notes.is_empty() {
log::warn!("spawn teardown: pid {pid} {}", notes.join("; "));
}
debug_assert!(breach.is_none(), "{}", breach.unwrap_or_default());
fate
}
#[cfg(target_os = "macos")]
const ZOMBIE_NOTE: &str = "is left unreaped: it stays a zombie once it exits";
#[cfg(target_os = "macos")]
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum KillOutcome {
Delivered,
NotSent,
Unverified,
Refused(String),
}
#[cfg(target_os = "macos")]
pub(crate) struct Unreported {
pub(crate) fate: ChildFate,
kill: KillOutcome,
notes: Vec<String>,
breach: Option<String>,
}
#[cfg(target_os = "macos")]
pub(crate) fn kill_and_reap_unreported(
pid: u32,
unique: u64,
prepared: crate::containment::Prepared,
warn_after: Option<std::time::Duration>,
) -> Unreported {
#[cfg(test)]
fault::run_at(fault::SpawnPoint::BeforeLateTeardown, pid);
let mut tree = LateTree::attach(pid, unique, prepared);
tree.kill(Sweep::RootAlive);
#[cfg(test)]
fault::run_at(fault::SpawnPoint::BeforeLateRootKill, pid);
let mut notes = Vec::new();
let mut breach = None;
let (fate, kill) = kill_and_reap_noting(pid, unique, tree.id, warn_after, &mut notes, &mut breach, |zombie| {
tree.kill(Sweep::RootKilled { zombie })
});
let mut owed = std::mem::take(&mut tree.notes);
owed.extend(tree.failure_note(matches!(kill, KillOutcome::Delivered | KillOutcome::NotSent)));
notes.splice(0..0, owed);
Unreported {
fate,
kill,
notes,
breach,
}
}
#[cfg(target_os = "macos")]
#[derive(Debug, Clone, Copy)]
enum Sweep {
RootAlive,
RootKilled { zombie: bool },
}
#[cfg(target_os = "macos")]
enum Reach {
None,
Attached(crate::containment::Attached),
Holders(crate::containment::fdmarker::Marker),
}
#[cfg(target_os = "macos")]
struct LateTree {
reach: Reach,
pid: u32,
unique: u64,
id: Option<ProcessId>,
sweeps: Vec<Result<(), crate::containment::dispatch::Unkilled>>,
notes: Vec<String>,
}
#[cfg(target_os = "macos")]
impl LateTree {
fn attach(pid: u32, unique: u64, prepared: crate::containment::Prepared) -> LateTree {
use crate::identity::Resolved;
let mut tree = LateTree {
reach: Reach::None,
pid,
unique,
id: None,
sweeps: Vec::new(),
notes: Vec::new(),
};
if prepared.mode.is_none() || !prepared.is_root {
return tree;
}
let (resolved, _, mut why) = resolve_identity(
&crate::identity::HostKernel,
pid,
&crate::wait::exit_only::Target::pid(pid, Some(unique)),
);
let unshown = match resolved {
Resolved::Found(id) => {
tree.id = Some(id);
match attach_or_fault(pid, Ok(id), prepared) {
Ok(attachment) => tree.reach = Reach::Attached(attachment.attached),
Err(e) => {
assert_attach_cannot_fail(&e);
tree.notes.push(format!("its tree was not killed: {e}"));
}
}
return tree;
}
Resolved::Gone => "the child is gone, or is not ours",
Resolved::Unknown => "the child's identity could not be read",
};
match prepared.marker {
Some(marker) => {
tree.notes.push(why.fold(format!(
"{unshown}, so its tree is reached only through its marker's holders, not its process group \
or the processes its pid parents"
)));
tree.reach = Reach::Holders(crate::containment::fdmarker::Marker::without_root(marker));
}
None => tree.notes.push(why.fold(format!("its tree was not killed: {unshown}"))),
}
tree
}
fn kill(&mut self, sweep: Sweep) {
use crate::containment::Attached;
match (&self.reach, sweep) {
(Reach::None, _) => {}
(Reach::Attached(attached), Sweep::RootAlive | Sweep::RootKilled { zombie: true }) => {
let (pid, unique) = (self.pid, self.unique);
#[cfg(test)]
crate::graceful_hooks::run_hook(crate::graceful_hooks::HookPoint::AfterRootLook);
let check = || {
let target = crate::wait::exit_only::Target::pid(pid, Some(unique));
let state = crate::signal::RootState::of_peek(crate::wait::exit_only::peek_verified(&target));
crate::child::tree_call::group_number_holds(pid, state)
};
self.sweeps.push(
attached
.hard_kill(&crate::containment::GroupRoot::new(None, &check))
.into_result(),
);
}
(Reach::Attached(Attached::FdMarker(m)), Sweep::RootKilled { zombie: false }) => {
if let Err(e) = m.hard_kill_holders_only(m.root()) {
self.notes
.push(format!("its marker's holders were not all killed after its kill: {e}"));
}
self.notes.push(NOT_SWEPT_AGAIN.to_owned());
}
(Reach::Attached(_), Sweep::RootKilled { zombie: false }) => self.notes.push(NOT_SWEPT_AGAIN.to_owned()),
(Reach::Holders(m), _) => self.sweeps.push(
m.hard_kill_holders_only(None)
.map_err(crate::containment::dispatch::Unkilled::from),
),
}
}
fn failure_note(&mut self, root_ended: bool) -> Option<String> {
let mut failed = None;
let mut succeeded_after = false;
for sweep in self.sweeps.drain(..) {
match (sweep.or_else(|left| left.unsettled(root_ended)), &failed) {
(Err(left), None) => failed = Some(left.to_string()),
(Err(_), Some(_)) => succeeded_after = false,
(Ok(()), failed) => succeeded_after = failed.is_some(),
}
}
let failed = failed?;
Some(if succeeded_after {
format!(
"its tree may not be fully killed: a kill of it failed ({failed}), and the later one that succeeded \
cannot be shown to reach what that one missed"
)
} else {
format!("its tree was not fully killed: {failed}")
})
}
}
#[cfg(target_os = "macos")]
const NOT_SWEPT_AGAIN: &str = "it was not shown an unreaped zombie, so its tree was not killed again by its pid: what \
it started after the first kill of its tree may be left running";
#[cfg(target_os = "macos")]
const UNVERIFIED: &str = "could not be verified, so it was not signalled";
#[cfg(target_os = "macos")]
const LATE: &str = "was spawned while at least two of this process's descriptors 0 to 2 were closed, so its exec \
cannot be confirmed and the program may have started; it was not adopted";
#[cfg(target_os = "macos")]
fn said(kill: &KillOutcome, fate: ChildFate) -> String {
let sent = match kill {
KillOutcome::Delivered => "was sent SIGKILL".to_owned(),
KillOutcome::NotSent => "was gone, or its pid names another process, so nothing was sent".to_owned(),
KillOutcome::Unverified => UNVERIFIED.to_owned(),
KillOutcome::Refused(why) => format!("could not be killed ({why})"),
};
let state = match fate {
ChildFate::Reaped => "it was reaped",
ChildFate::Killed => "its status was not collected",
ChildFate::Running { .. } => "it is still running",
ChildFate::Gone => "it is gone, or was reaped by someone else",
ChildFate::Unknown => "what became of it is unknown",
};
format!("{sent}; {state}")
}
#[cfg(target_os = "macos")]
impl Unreported {
pub(crate) fn warn(self, pid: u32, tail: Option<&str>) -> ChildFate {
let mut line = format!("child {pid} {LATE}, and {}", said(&self.kill, self.fate));
for note in self.notes.iter().filter(|note| *note != "is still running") {
line.push_str("; ");
line.push_str(note);
}
if let Some(tail) = tail {
line.push_str("; ");
line.push_str(tail);
}
log::warn!("{line}");
debug_assert!(self.breach.is_none(), "{}", self.breach.unwrap_or_default());
self.fate
}
pub(crate) fn zombie_tail(&self) -> Option<&'static str> {
matches!(self.fate, ChildFate::Running { .. }).then_some(ZOMBIE_NOTE)
}
}
#[cfg(target_os = "macos")]
pub(crate) fn warn_late_front(pid: u32, tail: Option<&str>) {
let tail = tail.map_or_else(String::new, |tail| format!("; {tail}"));
log::warn!(
"child {pid} {LATE}; it is an elevation front, so nothing was sent to it and it is left unreaped: it stays a \
zombie once it exits{tail}"
);
}
#[cfg(target_os = "macos")]
fn kill_and_reap_noting(
pid: u32,
unique: u64,
id: Option<ProcessId>,
warn_after: Option<std::time::Duration>,
notes: &mut Vec<String>,
breach: &mut Option<String>,
after_kill: impl FnOnce(bool),
) -> (ChildFate, KillOutcome) {
use crate::os_process::child::Foreign;
use crate::signal::{via_audit_token, Sent, Sig};
use crate::wait::macos::Waited;
let target = crate::wait::exit_only::Target::pid(pid, Some(unique));
match via_audit_token(pid, Some(unique), Sig::Kill) {
Ok(Sent::Delivered) => {
#[cfg(test)]
fault::run_between_kill_and_wait();
let waited = await_exit_warning(pid, unique, warn_after);
after_kill(matches!(waited, Ok(Waited::Reapable)));
let fate = match waited {
Ok(Waited::Reapable) => reap_verified(pid, &target, id, true, notes, breach),
Ok(Waited::Gone) => {
log::debug!("spawn teardown: pid {pid} was reaped by someone else");
Foreign::Gone.fate(true)
}
Ok(Waited::Orphaned) => {
notes.push(unverifiable(&crate::signal::UNPINNED_WHY));
Foreign::Orphaned.fate(true)
}
Ok(Waited::DeadlinePassed) => {
debug_assert!(false, "an unbounded wait reported a passed deadline");
notes.push("is still running after its kill".to_owned());
ChildFate::Running { id }
}
Err(e) => {
notes.push(format!(
"could not be waited for ({e}), so it is left unreaped: it stays a zombie once it exits"
));
ChildFate::Killed
}
};
(fate, KillOutcome::Delivered)
}
Ok(Sent::Gone) => {
log::debug!("spawn teardown: pid {pid} is already gone");
after_kill(false);
(Foreign::Gone.fate(false), KillOutcome::NotSent)
}
Ok(Sent::Unverified) => {
debug_assert!(false, "`via_audit_token` was given `Some(unique)`, so it verifies");
after_kill(false);
(ChildFate::Running { id }, KillOutcome::Unverified)
}
Err(kill) => {
after_kill(false);
let fate = reap_verified(pid, &target, id, false, notes, breach);
(fate, KillOutcome::Refused(kill.to_string()))
}
}
}
#[cfg(target_os = "macos")]
fn await_exit_warning(
pid: u32,
unique: u64,
warn_after: Option<std::time::Duration>,
) -> std::io::Result<crate::wait::macos::Waited> {
use crate::wait::macos::{await_reapable, Waited};
crate::wait::teardown_warn::wait_warning(
None,
crate::wait::teardown_warn::Due::in_(warn_after),
|found, until| match await_reapable(pid, Some(unique), Some(until)) {
Ok(Waited::DeadlinePassed) => false,
done => {
*found = Some(done);
true
}
},
|after| warn_still_waiting(Some(pid), after),
|found| found.unwrap_or_else(|| await_reapable(pid, Some(unique), None)),
)
}
pub(crate) fn warn_still_waiting(pid: Option<u32>, after: std::time::Duration) {
let who = pid.map_or_else(
|| "the spawned child (pid unknown)".to_owned(),
|pid| format!("child {pid}"),
);
#[cfg(unix)]
log::warn!(
"{who} is not reapable {after:?} after its kill (it is still running, or a tracer holds its exit); still waiting for it to exit"
);
#[cfg(windows)]
log::warn!("{who} has not exited {after:?} after its kill was requested; still waiting for it to exit");
}
#[cfg(target_os = "macos")]
fn unverifiable(why: &dyn std::fmt::Display) -> String {
format!("cannot be shown to be ours or reaped ({why})")
}
#[cfg(target_os = "macos")]
fn reap_verified(
pid: u32,
target: &crate::wait::exit_only::Target<'_>,
id: Option<ProcessId>,
killed: bool,
notes: &mut Vec<String>,
breach: &mut Option<String>,
) -> ChildFate {
use crate::os_process::child::{ExitRecord, Foreign, PeekOutcome};
use crate::wait::exit_only::{peek_verified, try_reap, Reap};
let foreign = |why: Foreign, notes: &mut Vec<String>| {
match why {
Foreign::Orphaned => notes.push(unverifiable(&crate::signal::UNPINNED_WHY)),
Foreign::Gone | Foreign::Other => log::debug!("spawn teardown: pid {pid} was reaped by someone else"),
}
why.fate(killed)
};
match peek_verified(target) {
Err(e) => {
notes.push(unverifiable(&e));
return ChildFate::Unknown;
}
Ok(PeekOutcome::Foreign(why)) => return foreign(why, notes),
Ok(PeekOutcome::Running) => {
notes.push("is still running".to_owned());
return ChildFate::Running { id };
}
Ok(PeekOutcome::Exit(_)) => {}
}
match try_reap(target) {
Ok(Reap::Reaped(ExitRecord::Status(_))) => ChildFate::Reaped,
Ok(Reap::Reaped(ExitRecord::Unreadable { si_code })) => {
notes.push(format!(
"a consuming waitid returned si_code {si_code}, not an exit record"
));
*breach = Some(format!("a consuming waitid on a zombie returned si_code {si_code}"));
ChildFate::Reaped
}
Ok(Reap::Running) => {
notes.push("is still running".to_owned());
ChildFate::Running { id }
}
Ok(Reap::Foreign(why)) => foreign(why, notes),
Err(e) => {
notes.push(format!("could not be reaped: {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>,
prepared: crate::containment::Prepared,
) -> 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::Late(unique) => {
#[cfg(test)]
fault::capture(ProcessId::of(pid));
if front.is_some() {
warn_late_front(pid, None);
drop(child);
return SpawnFailure::started(
FrontFate::LeftUnreaped.note(error, front, Some(pid)),
ChildFate::Running { id: None },
None,
);
}
let done = kill_and_reap_unreported(pid, unique, prepared, None);
let tail = done.zombie_tail();
let fate = done.warn(pid, tail);
drop(child);
SpawnFailure::started(error, fate, 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,
None,
)
}
}
}
#[cfg(target_os = "macos")]
fn leave_unverified_child(
child: std::process::Child,
identity: crate::containment::RootIdentity,
id: Option<ProcessId>,
why: &mut Diagnosis,
) -> ChildFate {
let pid = child.id();
let fate = if identity == crate::containment::RootIdentity::Gone {
log::warn!(
"{}",
why.fold(format!(
"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!(
"{}",
why.fold(format!(
"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(target_os = "macos")]
fn teardown_after_failed_adoption(
child: std::process::Child,
error: Error,
id: Option<ProcessId>,
) -> (Error, ChildFate) {
#[cfg(test)]
fault::capture(ProcessId::of(child.id()));
let fate = leave_unverified_child(
child,
crate::containment::RootIdentity::Unknown,
id,
&mut Diagnosis::default(),
);
(error, fate)
}
pub(crate) fn spawn_lock() -> SpawnLockGuard {
acquire_spawn_lock(|| {
#[cfg(all(test, target_os = "macos"))]
fault::spawn_lock_contended();
})
}
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> {
#[cfg(unix)]
{
let mut steps = in_child::InChild::default();
let (mut std_cmd, ()) = build_std_command_with(cmd, &mut steps, |_| ())?;
steps.register(&mut std_cmd);
Ok(std_cmd)
}
#[cfg(not(unix))]
build_std_command_with(cmd, |_| ()).map(|(std_cmd, ())| std_cmd)
}
pub(crate) fn build_std_command_with<R>(
cmd: &Command,
#[cfg(unix)] steps: &mut in_child::InChild,
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 {
#[cfg(unix)]
Some(dir) if enter => enter_in_child(steps, &dir)?,
#[cfg(not(unix))]
Some(_) if enter => unreachable!("only anchor_posix asks the child to enter its directory"),
Some(dir) => {
std_cmd.current_dir(dir);
}
None => {}
}
Ok((std_cmd, first))
}
#[cfg(unix)]
fn enter_in_child(steps: &mut in_child::InChild, dir: &std::path::Path) -> Result<(), Error> {
use std::os::unix::ffi::OsStrExt;
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",
))
})?;
steps.enter(dir);
Ok(())
}
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>);
pub(crate) fn resolve_stdio(
fds: &BTreeMap<Fd, ResolvedStdio>,
parent_std: ParentStd,
) -> Result<ResolvedStdioEnds, Error> {
let slots: Vec<Fd> = [Fd::STDIN, Fd::STDOUT, Fd::STDERR]
.into_iter()
.chain(fds.keys().copied().filter(|f| f.raw() >= 3))
.collect();
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, None if slot.raw() >= 3 => continue,
_ => {
let (child_end, parent) = resolve_non_merge(slot, resolved, parent_std)?;
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) {
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_into_std(
cmd: &mut std::process::Command,
#[cfg(unix)] steps: &mut in_child::InChild,
fds: &BTreeMap<Fd, ResolvedStdio>,
) -> Result<BTreeMap<Fd, ParentEnd>, Error> {
#[cfg(windows)]
debug_assert!(
fds.keys().all(|f| f.raw() < 3),
"an fd >= 3 routes to the raw backend, never the std path"
);
let (mut child_ends, parent_ends) = resolve_stdio(fds, ParentStd::read())?;
for slot in [Fd::STDIN, Fd::STDOUT, Fd::STDERR] {
let end = child_ends
.remove(&slot)
.unwrap_or_else(|| unreachable!("resolve_stdio resolves 0/1/2 always"));
let stdio = StdStdio::from(end);
match slot {
Fd::STDIN => cmd.stdin(stdio),
Fd::STDOUT => cmd.stdout(stdio),
_ => cmd.stderr(stdio),
};
}
#[cfg(unix)]
{
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(steps, mappings).map_err(Error::Io)?;
}
#[cfg(not(unix))]
debug_assert!(child_ends.is_empty(), "the std path on Windows has no fd >= 3 end");
Ok(parent_ends)
}
pub(crate) fn reserved_fds(fds: &BTreeMap<Fd, ResolvedStdio>) -> Vec<i32> {
fds.keys().map(|fd| fd.raw()).filter(|&n| n >= 3).collect()
}
pub(crate) fn resolve_non_merge(
slot: Fd,
r: Option<&ResolvedStdio>,
parent_std: ParentStd,
) -> Result<(ChildEnd, Option<ParentEnd>), Error> {
match r {
None | Some(ResolvedStdio::Inherit) => Ok((inherit_end(slot, parent_std)?, None)),
Some(ResolvedStdio::Null) => Ok((null_end()?, None)),
Some(ResolvedStdio::File(f)) => Ok((file_end(f)?, None)),
Some(ResolvedStdio::Pipe(dir)) => make_pipe(*dir).map(|(child_end, parent_end)| (child_end, Some(parent_end))),
Some(ResolvedStdio::Merge(_)) => unreachable!("merge handled in second pass"),
}
}
pub(crate) fn make_pipe(dir: Direction) -> Result<(ChildEnd, ParentEnd), Error> {
let (child_end, parent_end) = crate::pipe::child_pipe(dir).map_err(Error::Io)?;
Ok((ChildEnd::from(child_end), parent_end))
}
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)]
{
end.try_clone().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))
}
#[cfg_attr(
not(windows),
allow(unused_variables, reason = "only the Windows arm reads the parent's std handles")
)]
fn inherit_end(slot: Fd, parent_std: ParentStd) -> 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 live = parent_std.is_live(slot);
let owned = match slot {
Fd::STDIN => {
let s = std::io::stdin();
dup_std_handle(s.as_handle(), live)
}
Fd::STDOUT => {
let s = std::io::stdout();
dup_std_handle(s.as_handle(), live)
}
Fd::STDERR => {
let s = std::io::stderr();
dup_std_handle(s.as_handle(), live)
}
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)
}
}
#[cfg(windows)]
fn dup_std_handle(h: std::os::windows::io::BorrowedHandle<'_>, live: bool) -> std::io::Result<ChildEnd> {
use std::os::windows::io::AsRawHandle;
if !live || h.as_raw_handle().is_null() {
return Ok(ChildEnd::absent());
}
h.try_clone_to_owned().map(ChildEnd::from)
}
#[derive(Clone, Copy)]
pub(crate) struct ParentStd {
#[cfg(windows)]
live: [bool; 3],
}
impl ParentStd {
pub(crate) fn read() -> ParentStd {
#[cfg(windows)]
{
use std::os::windows::io::{AsHandle, AsRawHandle};
ParentStd {
live: [
!std::io::stdin().as_handle().as_raw_handle().is_null(),
!std::io::stdout().as_handle().as_raw_handle().is_null(),
!std::io::stderr().as_handle().as_raw_handle().is_null(),
],
}
}
#[cfg(not(windows))]
{
ParentStd {}
}
}
#[cfg(windows)]
pub(crate) fn is_live(self, slot: Fd) -> bool {
usize::try_from(slot.raw())
.ok()
.and_then(|i| self.live.get(i).copied())
.unwrap_or(false)
}
#[cfg(windows)]
pub(crate) fn any_live(self) -> bool {
self.live.iter().any(|&l| l)
}
}
pub(crate) fn spawn_identity_error(
outcome: crate::identity::Resolved<ProcessId>,
cause: crate::identity::UnknownCause,
) -> Error {
match outcome {
crate::identity::Resolved::Unknown => {
cause
.into_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(
kernel: &dyn crate::identity::Kernel,
pid: u32,
through: &crate::wait::exit_only::Target<'_>,
) -> (
crate::identity::Resolved<ProcessId>,
crate::identity::UnknownCause,
Diagnosis,
) {
use crate::identity::Resolved;
#[cfg(target_os = "linux")]
let (read, cause) = {
let crate::wait::exit_only::Target::PidFd(held) = *through;
resolve_identity_unchecked(kernel, pid, held)
};
#[cfg(not(target_os = "linux"))]
let (read, cause) = resolve_identity_unchecked(kernel, pid);
let Resolved::Found(_) = read else {
return (read, cause, Diagnosis::default());
};
#[cfg(test)]
fault::run_at(fault::SpawnPoint::AfterIdentityRead, pid);
#[cfg(unix)]
{
use crate::os_process::child::PeekOutcome;
#[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(PeekOutcome::Running | PeekOutcome::Exit(_)) => (read, cause, Diagnosis::default()),
Ok(PeekOutcome::Foreign(crate::os_process::child::Foreign::Orphaned)) => (
Resolved::Gone,
cause,
Diagnosis::of(format!(
"child {pid}: launchd holds its zombie, so its tracer died; it is not ours to reap"
)),
),
Ok(PeekOutcome::Foreign(_)) => (Resolved::Gone, cause, Diagnosis::default()),
Err(e) => (
Resolved::Unknown,
cause,
Diagnosis::of_failed_check(
format!(
"child {pid}: its identity could not be checked against its handle ({e}); it is not shown to be ours"
),
e,
),
),
}
}
#[cfg(windows)]
{
let _ = through;
(read, cause, Diagnosis::default())
}
}
#[derive(Debug, Default)]
pub(crate) struct Diagnosis {
owed: Option<String>,
kept_check: Option<String>,
failed_check: Option<std::io::Error>,
}
impl Diagnosis {
#[cfg(unix)]
fn of(text: String) -> Diagnosis {
Diagnosis {
owed: Some(text),
kept_check: None,
failed_check: None,
}
}
#[cfg(unix)]
fn of_failed_check(text: String, error: std::io::Error) -> Diagnosis {
Diagnosis {
owed: Some(text),
kept_check: None,
failed_check: Some(error),
}
}
#[cfg(unix)]
pub(crate) fn add(&mut self, text: impl std::fmt::Display) {
match &mut self.owed {
Some(owed) => owed.push_str(&format!("; {text}")),
None => self.owed = Some(text.to_string()),
}
}
#[cfg(any(target_os = "linux", windows))]
pub(crate) fn is_owed(&self) -> bool {
self.owed.is_some() || self.kept_check.is_some()
}
pub(crate) fn fold(&mut self, text: impl std::fmt::Display) -> String {
let mut parts: Vec<String> = [self.kept_check.take(), self.owed.take()]
.into_iter()
.flatten()
.collect();
parts.push(text.to_string());
parts.join("; ")
}
}
impl Drop for Diagnosis {
fn drop(&mut self) {
if std::thread::panicking() {
return;
}
if let Some(check) = self.kept_check.take() {
log::debug!("{check}");
}
if let Some(diagnosis) = self.owed.take() {
log::warn!("{diagnosis}");
}
}
}
pub(crate) fn kept_without_identity(pid: u32, cause: crate::identity::UnknownCause, why: &mut Diagnosis) -> Error {
let error = match why.failed_check.take() {
Some(source) => Error::Unassessable {
detail: "the spawned child's identity could not be checked against its handle".into(),
source: Some(source),
},
None => spawn_identity_error(crate::identity::Resolved::Unknown, cause),
};
log::debug!("child {pid}: {error}; the child is kept without an identity");
why.kept_check = why.owed.take();
error
}
pub(crate) fn resolve_identity_unchecked(
kernel: &dyn crate::identity::Kernel,
pid: u32,
#[cfg(target_os = "linux")] held: std::os::fd::BorrowedFd<'_>,
) -> (crate::identity::Resolved<ProcessId>, crate::identity::UnknownCause) {
#[cfg(test)]
{
if fault::force_identity_unknown() {
fault::capture(ProcessId::of(pid));
return (crate::identity::Resolved::Unknown, Default::default());
}
if fault::force_identity_vanished() {
fault::capture(ProcessId::of(pid));
return (crate::identity::Resolved::Gone, Default::default());
}
}
#[cfg(target_os = "linux")]
{
ProcessId::of_held_with(kernel, pid, held)
}
#[cfg(not(target_os = "linux"))]
{
ProcessId::of_with(kernel, pid)
}
}
pub(crate) fn attach_or_fault(
#[cfg(unix)] pid: u32,
id: Result<ProcessId, Error>,
#[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() {
if let Ok(id) = &id {
fault::capture(crate::identity::Resolved::Found(*id));
}
let mut prepared = prepared;
prepared.settle_verdict(
#[cfg(target_os = "linux")]
child,
);
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,
);
return Ok(attachment);
}
crate::containment::attach(
#[cfg(unix)]
pid,
id,
#[cfg(target_os = "linux")]
child,
#[cfg(windows)]
proc_handle,
prepared,
)
}
#[cfg(target_os = "linux")]
pub(crate) fn named(pid: Option<u32>) -> String {
match pid {
Some(pid) => format!("pid {pid}"),
None => "the spawned child (pid unknown)".to_string(),
}
}
#[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 {
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,
}
}
#[cfg(target_os = "linux")]
pub(crate) fn of_look(look: &crate::child::owned::teardown::LookOutcome) -> FrontFate {
use crate::child::owned::teardown::LookOutcome;
match look {
LookOutcome::Ended(settlement) => settlement.front_fate(),
LookOutcome::LeftRunning => FrontFate::LeftUnreaped,
LookOutcome::PlaceUnreadable(_) | LookOutcome::SubtreeUnreadable(_) => FrontFate::Unplaced,
}
}
#[cfg_attr(
not(any(unix, feature = "tokio")),
allow(
dead_code,
reason = "Windows has no elevation front; only the async child notes one there"
)
)]
pub(crate) fn note(self, error: Error, front: Option<crate::elevation::front::Front>, pid: Option<u32>) -> Error {
self.noting(error, front, pid, false)
}
#[cfg(target_os = "linux")]
pub(crate) fn note_handed_back(
self,
error: Error,
front: Option<crate::elevation::front::Front>,
pid: Option<u32>,
) -> Error {
self.noting(error, front, pid, true)
}
fn noting(
self,
error: Error,
front: Option<crate::elevation::front::Front>,
pid: Option<u32>,
handed_back: bool,
) -> Error {
let Some(front) = front else {
return error;
};
let what = crate::elevation::front::describe(front, pid);
use crate::child::owned::teardown::Disposition;
let left = if handed_back {
Disposition::HandBack
} else {
Disposition::Leave
}
.suffix(true);
let fate = match self {
FrontFate::Reaped => {
"it was sent no signal of its own; it had exited, or its cgroup's kill ended it, and it was reaped"
.to_owned()
}
FrontFate::LeftUnreaped => {
format!("it was sent nothing, so the elevated program may be running{left}")
}
FrontFate::Unaccounted if handed_back => {
format!("it was sent nothing and could not be waited on, so the elevated program may be running{left}")
}
FrontFate::Unaccounted => {
"it was sent nothing and could not be waited on, so the elevated program may be running".to_owned()
}
FrontFate::Unplaced => format!(
"it was sent nothing, and where it is cannot be read, so the elevated program may be running{left}"
),
};
error.with_note(&format!("{what}; {fate}"))
}
}
#[cfg(target_os = "macos")]
fn note_front(
fate: Option<FrontFate>,
error: Error,
front: Option<crate::elevation::front::Front>,
pid: Option<u32>,
) -> Error {
match fate {
Some(fate) => fate.note(error, front, pid),
None => error,
}
}
pub(crate) fn settle_before_teardown(
prepared: &mut crate::containment::Prepared,
#[cfg(target_os = "linux")] child: crate::containment::ChildHandle<'_>,
) {
prepared.settle_verdict(
#[cfg(target_os = "linux")]
child,
);
}
#[cfg(target_os = "linux")]
pub(crate) fn kill_group_before_teardown(
prepared: &crate::containment::Prepared,
child: crate::containment::ChildHandle<'_>,
why: &mut Diagnosis,
) {
if let Err(e) = prepared.kill_group_before_attach(child) {
note_refused_group_kill(Some(child.pid), e, false, why);
}
}
#[cfg(target_os = "linux")]
pub(crate) fn note_refused_group_kill(pid: Option<u32>, refusal: nix::errno::Errno, reaped: bool, why: &mut Diagnosis) {
let named = named(pid);
let reaped = if reaped {
"; the child was already reaped, so it may never have run the program"
} else {
""
};
match refusal {
nix::errno::Errno::EINVAL => why.add(format!(
"members of the process group of {named} may be left running: the kernel refused \
PIDFD_SIGNAL_PROCESS_GROUP (EINVAL, expected below Linux 6.9), so nothing was sent to the \
group, whose number may name another group{reaped}"
)),
e => why.add(format!(
"spawn teardown could not kill the process group of {named} through its pidfd ({e}); its \
members may be left running{reaped}"
)),
}
}
#[cfg(target_os = "macos")]
pub(crate) fn note_group_left_running(prepared: &crate::containment::Prepared, pid: u32, why: &mut Diagnosis) {
if prepared.group_is_containment() {
why.add(format!(
"members of the process group of pid {pid} may be left running: macOS has no exact kill of a \
process group, so the group is sent nothing"
));
}
}
#[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(test)]
pub(crate) mod fault {
use std::cell::Cell;
use crate::identity::ProcessId;
#[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) };
#[cfg(unix)]
static FORCE_REAP_FAIL: Cell<Option<&'static str>> = const { Cell::new(None) };
#[cfg(feature = "tokio")]
static FORCE_KILL_FAIL: Cell<Option<(&'static str, std::io::ErrorKind)>> = 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) };
#[cfg(all(windows, feature = "tokio"))]
static LATE_EXIT: Cell<bool> = const { Cell::new(false) };
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() };
#[cfg(target_os = "macos")]
static BEFORE_LATE_TEARDOWN: crate::oneshot_hook::OneShotHook = const { crate::oneshot_hook::OneShotHook::new() };
#[cfg(target_os = "macos")]
static BEFORE_LATE_ROOT_KILL: 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(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(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
}
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())
}
#[cfg(unix)]
pub(crate) fn set_force_reap_failure(marker: &'static str) {
FORCE_REAP_FAIL.with(|f| f.set(Some(marker)));
}
#[cfg(unix)]
pub(crate) fn take_force_reap_failure() -> Option<&'static str> {
FORCE_REAP_FAIL.with(|f| f.take())
}
#[cfg(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))));
}
#[cfg(feature = "tokio")]
pub(crate) fn take_force_kill_failure() -> Option<(&'static str, std::io::ErrorKind)> {
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())
}
#[cfg(all(windows, feature = "tokio"))]
pub(crate) fn set_late_exit() -> LateExit {
LATE_EXIT.with(|f| f.set(true));
LateExit(())
}
#[cfg(all(windows, feature = "tokio"))]
#[must_use = "the override is cleared as soon as the guard is dropped"]
pub(crate) struct LateExit(());
#[cfg(all(windows, feature = "tokio"))]
impl Drop for LateExit {
fn drop(&mut self) {
LATE_EXIT.with(|f| f.set(false));
}
}
#[cfg(all(windows, feature = "tokio"))]
pub(crate) fn take_late_exit() -> bool {
LATE_EXIT.with(|f| f.replace(false))
}
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;
#[cfg(target_os = "macos")]
static ON_SPAWN_LOCK_CONTENDED: std::sync::Mutex<Option<Box<dyn FnOnce() + Send>>> = std::sync::Mutex::new(None);
#[cfg(target_os = "macos")]
pub(crate) fn on_spawn_lock_contended(hook: impl FnOnce() + Send + 'static) -> ContendedHook {
let previous = ON_SPAWN_LOCK_CONTENDED
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.replace(Box::new(hook));
debug_assert!(previous.is_none(), "a contention hook is already armed");
ContendedHook(())
}
#[cfg(target_os = "macos")]
#[must_use = "the hook is dropped as soon as the guard is dropped"]
pub(crate) struct ContendedHook(());
#[cfg(target_os = "macos")]
impl Drop for ContendedHook {
fn drop(&mut self) {
ON_SPAWN_LOCK_CONTENDED
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.take();
}
}
#[cfg(target_os = "macos")]
pub(super) fn spawn_lock_contended() {
let hook = ON_SPAWN_LOCK_CONTENDED
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.take();
if let Some(hook) = hook {
hook();
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum SpawnPoint {
BeforeIdentity,
BeforeAttach,
AfterIdentityRead,
#[cfg(target_os = "macos")]
BeforeLateTeardown,
#[cfg(target_os = "macos")]
BeforeLateRootKill,
}
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(target_os = "macos")]
SpawnPoint::BeforeLateTeardown => &BEFORE_LATE_TEARDOWN,
#[cfg(target_os = "macos")]
SpawnPoint::BeforeLateRootKill => &BEFORE_LATE_ROOT_KILL,
}
}
#[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())
}
pub(crate) fn assert_killed(&self) {
let reaps = self.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: {status:?}"
);
}
}
}
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);
(
crate::stdio::Stdio::from_file(std::fs::File::from(reader)),
release_between_kill_and_wait(writer),
)
}
pub(crate) fn release_between_kill_and_wait(held: impl Sized + 'static) -> TeardownBlocker {
let fired = std::rc::Rc::new(std::cell::Cell::new(false));
let held = std::rc::Rc::new(std::cell::Cell::new(Some(held)));
let hook = || {
let (held, fired) = (std::rc::Rc::clone(&held), std::rc::Rc::clone(&fired));
move || {
drop(held.take());
fired.set(true);
}
};
let between = set_between_kill_and_wait(hook());
let after_kill = crate::graceful_hooks::at(crate::graceful_hooks::HookPoint::AfterDropKill, hook());
TeardownBlocker {
_release: vec![between, after_kill],
fired,
reaps: record_teardown_reaps(),
}
}
pub(crate) fn release_at_drop_kill(held: impl Sized + 'static) -> TeardownBlocker {
let fired = std::rc::Rc::new(std::cell::Cell::new(false));
let release = crate::graceful_hooks::at(
crate::graceful_hooks::HookPoint::AfterDropKill,
release_hook(held, &fired),
);
TeardownBlocker {
_release: vec![release],
fired,
reaps: record_teardown_reaps(),
}
}
#[cfg(target_os = "linux")]
pub(crate) fn release_when_a_teardown_waits<T: 'static>(
held: &std::rc::Rc<std::cell::Cell<Option<T>>>,
) -> Box<dyn std::any::Any> {
use crate::graceful_hooks::{at, HookPoint};
let release = || {
let held = std::rc::Rc::clone(held);
move || drop(held.take())
};
Box::new((
at(HookPoint::AfterDropKill, release()),
at(HookPoint::BeforeReap, release()),
set_between_kill_and_wait(release()),
))
}
fn release_hook(held: impl Sized + 'static, fired: &std::rc::Rc<std::cell::Cell<bool>>) -> impl FnOnce() + 'static {
let fired = std::rc::Rc::clone(fired);
move || {
drop(held);
fired.set(true);
}
}
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: Vec<crate::oneshot_hook::Armed>,
fired: std::rc::Rc<std::cell::Cell<bool>>,
reaps: TeardownReaps,
}
impl TeardownBlocker {
#[cfg(any(unix, feature = "tokio"))]
pub(crate) fn recorded(&self) -> Vec<TeardownReap> {
self.reaps.recorded()
}
pub(crate) fn assert_killed(&self) {
assert!(
self.fired.get(),
"the teardown must have reached its release hook (the kill returned)"
);
self.reaps.assert_killed();
}
#[cfg(target_os = "macos")]
pub(crate) fn assert_released(&self) {
assert!(
self.fired.get(),
"the teardown must have reached its release hook (the kill returned)"
);
}
#[cfg(windows)]
pub(crate) fn assert_reaps_killed(&self) {
self.reaps.assert_killed();
}
}
#[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(unix)]
#[path = "spawn/in_child.rs"]
pub(crate) mod in_child;
#[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(any(target_os = "linux", windows))]
#[path = "spawn/held_teardown.rs"]
pub(crate) mod held_teardown;
#[cfg(windows)]
#[path = "spawn/windows_raw.rs"]
pub(crate) mod windows_raw;
#[cfg(windows)]
#[path = "spawn/windows_child_end.rs"]
mod windows_child_end;
#[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 = "macos"))]
#[path = "spawn/late_report_tests.rs"]
pub(crate) mod late_report_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/held_teardown_tests.rs"]
mod held_teardown_tests;
#[cfg(all(test, target_os = "linux"))]
#[path = "spawn/identity_group_tests.rs"]
pub(crate) mod identity_group_tests;