use std::collections::BTreeMap;
#[cfg(not(target_os = "linux"))]
use std::process::Stdio as StdStdio;
#[cfg(unix)]
use std::sync::Arc;
#[cfg(unix)]
use crate::child::drop_teardown::Torn;
#[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;
#[cfg(unix)]
pub(crate) use crate::child::spawn::failure::failed_after_the_spawn;
pub(crate) use crate::child::spawn::failure::{after_the_spawn, failed_after_teardown, Classify, SpawnFailure};
use crate::child::spawn::policy::SpawnPolicy;
use crate::child::Child;
#[cfg(not(target_os = "linux"))]
use crate::command::EnvOp;
use crate::command::{Command, CommandInput};
use crate::elevation::front::TrackedKind;
#[cfg(unix)]
use crate::error::ChildFate;
use crate::error::Error;
#[cfg(unix)]
use crate::error::Failures;
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(target_os = "linux")]
use crate::child::owned::teardown::Reach;
#[cfg(windows)]
pub(crate) use windows_child_end::ChildEnd;
pub(crate) fn spawn(cmd: &mut Command) -> Result<Child, SpawnFailure> {
spawn_with(cmd, crate::identity::HostKernel)
}
pub(crate) fn spawn_with<K: crate::identity::Kernel + Send + 'static>(
cmd: &mut Command,
kernel: K,
) -> Result<Child, SpawnFailure> {
spawn_uncommitted(cmd, SpawnPolicy::SYNC, kernel)?.commit_kill_on_drop()
}
pub(crate) fn spawn_uncommitted<K: crate::identity::Kernel + Send + 'static>(
cmd: &mut Command,
policy: SpawnPolicy,
kernel: K,
) -> Result<Child, SpawnFailure> {
spawn_over(cmd, policy, crate::identity::spawn_kernel(kernel))
}
fn spawn_over(
cmd: &mut Command,
policy: SpawnPolicy,
kernel: crate::identity::SpawnKernel,
) -> 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, policy, kernel);
}
#[cfg(unix)]
{
let crate::elevation::posix::PosixRewrite {
mut derived,
password_write,
backend_path,
} = crate::elevation::posix::rewrite(cmd).not_started()?;
let r = spawn_unelevated(&mut derived, kill_on_drop, policy, kernel);
let 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?,
};
let written = password_write.map_or(Ok(()), |pw| pw.write_after_spawn());
return finish_elevated(child, written);
}
#[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(),
source: None,
}));
}
}
spawn_unelevated(cmd, kill_on_drop, policy, kernel)
}
#[cfg(unix)]
pub(crate) fn finish_elevated(mut child: Child, written: Result<(), Error>) -> Result<Child, SpawnFailure> {
use crate::containment::dispatch::{SettleOutcome, TreeKillOutcome};
use crate::elevation::front::{AloneStep, KillNeed, KillRootOutcome, RootStep};
let Err(write_err) = written else {
return Ok(child);
};
let read_view = || {
crate::containment::DropView::read(
crate::containment::dispatch::TeardownCaller::FinishElevated,
child.pid(),
child.id,
&child.proc,
&child.tree,
)
};
let kill_tree = |view: &crate::containment::DropView| {
let root_handle = child.proc.hold(child.pid());
let kill = {
let seen = crate::containment::Seen::new(&root_handle, view.look());
child.tree.send_kill(Some(&seen))
};
kill.log_skip(view);
kill
};
let kill_tree_once = || {
let view = read_view();
let mut skipped = None;
let tree = child.containment().can_teardown().then(|| {
let kill = kill_tree(&view);
skipped = kill.skip_note(&view);
kill
});
(view, tree, skipped)
};
let killed = child.proc.kill_root(
Some(&child.tree),
|_| {
let torn = kill_tree_once();
if torn.1.as_ref().is_some_and(TreeKillOutcome::completed) {
AloneStep::Killed {
result: Ok(()),
carry: torn,
}
} else {
AloneStep::NotKilled(torn)
}
},
|need| {
let (view, tree, skipped) = kill_tree_once();
if view.unpinned_root() {
RootStep::Answered((view, tree, skipped))
} else {
RootStep::ThenRoot((view, tree, skipped, need == KillNeed::Exited))
}
},
);
let (view, tree, skipped, exited_front, root) = match killed {
KillRootOutcome::Refused(refusal) => (read_view(), None, None, false, Some(Err(refusal))),
KillRootOutcome::Contained {
reached,
carry: (view, tree, skipped),
} => (
view,
tree,
skipped,
false,
Some(reached.map(|()| crate::signal::Sent::Delivered)),
),
KillRootOutcome::Root {
sent,
carry: (view, tree, skipped, exited_front),
} => (view, tree, skipped, exited_front, Some(sent)),
KillRootOutcome::Answered((view, tree, skipped)) => (view, tree, skipped, false, None),
};
let mut report = crate::child::drop_report::DropReport::new(&view);
let tree_failure = tree.as_ref().and_then(TreeKillOutcome::incomplete);
let pid = child.pid();
let (root_note, torn) = if let Some(root) = root.filter(|_| !view.unpinned_root()) {
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 = "the elevated child could not be terminated".to_owned();
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),
)
}
}
} else {
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),
)
};
let hands_back = Disposition::HandBack.hands_back(&torn);
let fate = torn.fate;
let root_failures = torn.failures;
let tree = tree.map(|kill| child.tree.settle(kill, fate.not_running()).answer.map_err(Arc::new));
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.tree.teardown_subject();
let mut tree_failures: Vec<Arc<Error>> = tree
.iter()
.filter_map(|answer| answer.as_ref().err().cloned())
.collect();
let mut early_failures: Vec<Arc<Error>> = Vec::new();
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(&view);
let more = match child.tree.settle(early, fate.not_running()).answer.map_err(Arc::new) {
Ok(SettleOutcome::Skipped { .. }) => None,
Ok(SettleOutcome::Killed) => {
tree_note.clear();
tree_failures.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 }) => {
let added = format!("; on the drop's tree kill, made early, {}", kind.unvouched_text());
Some((added.clone(), added, Ok(outcome)))
}
Err(again) => {
let added_warned = format!(
"; the drop's tree kill, made early, failed too ({})",
crate::error::Report(&*again)
);
early_failures.push(Arc::clone(&again));
Some((String::new(), added_warned, Err(again)))
}
};
if let Some((added, added_warned, again)) = more {
tree_note.push_str(&added);
match report.tree.as_mut() {
Some(warn) => warn.push_str(&added_warned),
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 behind_front = child.proc.tracked_kind().front().is_some();
let unreaped = hands_back.then(|| child.into_unreaped());
let cleanup = Failures::merged(
Failures::merged(Failures::collect(tree_failures), root_failures),
Failures::collect(early_failures),
);
Err(failed_after_the_spawn(
write_err,
Torn {
fate,
unreaped,
cleanup,
},
behind_front,
)
.with_detail(Some(format!("{root_note}{tree_note}"))))
}
#[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) => {
format!("{refusal}: it has exited, and was reaped")
}
Some(settlement) => settlement.wording(&refusal, None, None).text().to_owned(),
None => refusal,
}
}
#[cfg(unix)]
fn wait_killed_elevated(child: &Child) -> Result<ChildWaitOutcome, Error> {
let waited = wait_to_exit(
&child.proc,
crate::wait::teardown_warn::Due::in_(child.policy.teardown_warn_after),
);
#[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, Arc<Error>>>,
subject: &dyn std::fmt::Display,
) -> (String, Option<String>) {
use crate::containment::dispatch::SettleOutcome;
match tree {
Some(Err(e)) => {
let report = crate::error::Report(&*e).to_string();
(String::new(), Some(tree_teardown_warn(subject, &report)))
}
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, Arc<Error>>>,
) -> 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,
policy: SpawnPolicy,
kernel: crate::identity::SpawnKernel,
) -> Result<Child, SpawnFailure> {
let elevation = cmd.elevation_report().cloned();
let behind_front = elevation
.as_ref()
.is_some_and(|report| report.tracked().front().is_some());
spawn_reported(cmd, kill_on_drop, policy, elevation, kernel).map_err(|failure| {
if behind_front {
failure.behind_front()
} else {
failure
}
})
}
fn spawn_reported(
cmd: &mut Command,
kill_on_drop: bool,
policy: SpawnPolicy,
elevation: Option<crate::elevation::ElevationReport>,
kernel: crate::identity::SpawnKernel,
) -> Result<Child, SpawnFailure> {
let tracked = elevation
.as_ref()
.map_or(TrackedKind::Own, crate::elevation::ElevationReport::tracked);
#[cfg(unix)]
let front = tracked.front();
#[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, policy, kernel);
}
#[cfg(unix)]
let mut steps = in_child::InChild::default();
#[cfg(target_os = "linux")]
let (invocation, later, env) = {
let mut invocation = invocation(cmd).not_started()?;
let env = child_env::child_env_of(cmd);
let later = invocation.find(&env).not_started()?;
if let Some(dir) = &invocation.cwd {
enter_in_child(&mut steps, dir).not_started()?;
}
(invocation, later, env)
};
#[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(),
policy.teardown_warn_after,
&kernel,
)
.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(&*kernel);
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, pid, owned, parent_ends) = {
let parent_ends = resolve_into_fork(&mut steps, &fds).not_started()?;
let contain = cmd.contain_request();
let mut prepared = crate::containment::prepare(
&mut steps,
&contain,
cmd.flags_request(),
&reserved,
cmd.fd_marker_suppressed(),
cmd.env_ops(),
policy.teardown_warn_after,
&kernel,
)
.not_started()?;
if let Some(leaf) = prepared.cgroup_leaf.as_ref().filter(|_| front.is_some()) {
crate::containment::cgroup::front_placement(&kernel, || leaf.id()).not_started()?;
}
let program = fork_spawn::program(&invocation, &later, env).not_started()?;
let guard = spawn_lock();
let refusing_placement = prepared.refuses_failed_placement();
let on_failure = fork_spawn::OnFailure {
policy,
tracked,
placement: prepared.placement_leaf(),
refusing_placement,
};
let started = fork_spawn::start(&program, &mut steps, kernel, on_failure, &guard);
drop(steps);
let started = started?;
(prepared, started.pid, started.owned, 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(),
policy.teardown_warn_after,
&kernel,
)
.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(windows)]
let (pid, owned) = {
let pid = child.id();
(
pid,
OwnedChild::new(
Box::new(crate::os_process::windows::WindowsProcess::for_child(
kernel,
std::os::windows::io::OwnedHandle::from(child),
pid,
)),
tracked,
),
)
};
#[cfg(windows)]
let proc_handle = {
use std::os::windows::io::AsRawHandle;
owned.os_handle().as_raw_handle()
};
#[cfg(target_os = "macos")]
let (pid, owned) = {
let pid = child.id();
#[cfg(test)]
fault::run_at(fault::SpawnPoint::BeforeAdopt, pid);
let unique = match unique_report::adopted_id(unique, pid) {
Ok(unique) => unique,
Err(not_adopted) => return Err(abandon_unadopted(child, not_adopted, tracked, prepared, policy)),
};
match crate::os_process::macos::child::MacosChild::new(std::sync::Arc::clone(&kernel), pid, unique) {
Ok(os) => {
drop(child);
(pid, OwnedChild::new(Box::new(os), tracked))
}
Err(refusal) => {
return Err(leave_unwatched_child(
UnwatchedChild { child, pid, unique },
UnwatchedReport {
front,
prepared,
refusal,
late: None,
},
))
}
}
};
let front = owned.tracked_kind().front();
#[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 handle = crate::containment::ChildHandle {
pid,
pidfd: owned.os_handle(),
};
let (resolved, cause, mut why) = resolve_identity(owned.kernel(), pid, &owned);
#[cfg(windows)]
let id = windows_identity_or_keep(pid, resolved, cause, &mut why);
#[cfg(unix)]
let id = match resolved {
crate::identity::Resolved::Found(id) => Ok(id),
crate::identity::Resolved::Unknown => Err(kept_without_identity(pid, cause, &mut why)),
other => {
let never_ran = settle_before_teardown(
&mut prepared,
#[cfg(target_os = "linux")]
handle,
);
#[cfg(target_os = "linux")]
if let Some(failure) = never_ran {
drop(prepared);
let torn = held_teardown::tear_down_unexecuted(
owned,
None,
held_teardown::unexecuted_past(None),
policy,
&mut why,
);
return Err(failure::failed_attach(true, failure.cause, None, None, torn));
}
#[cfg(not(target_os = "linux"))]
let _ = never_ran;
#[cfg(target_os = "linux")]
let group_kill_failure = if front.is_none() {
kill_group_before_teardown(&prepared, handle, &mut why)
} else {
None
};
#[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);
}
let error = spawn_identity_error(other, cause);
let (
detail,
Torn {
fate: child_fate,
unreaped,
cleanup,
},
) = held_teardown::tear_down_held(
owned,
held_teardown::HeldTeardown {
id: None,
#[cfg(target_os = "linux")]
reach: subtree.as_ref().map(|subtree| subtree as &dyn Reach),
#[cfg(target_os = "macos")]
reach: None,
disposition: crate::child::owned::teardown::Disposition::HandBack,
policy,
},
&mut why,
);
let failure = SpawnFailure::started(error, child_fate, unreaped).with_detail(detail);
#[cfg(target_os = "linux")]
let failure = failure.with_cleanup(group_kill_failure);
return Err(failure.with_cleanup(cleanup));
}
};
#[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(failure) => {
log::debug!("attach failed: {report}", report = crate::error::Report(&failure.cause));
#[cfg(target_os = "macos")]
if id_read.is_some() {
assert_attach_cannot_fail(&failure.cause);
}
#[cfg(unix)]
return Err(held_teardown::tear_down_after_failed_attach(
owned,
id_read,
failure,
#[cfg(target_os = "linux")]
held_teardown::unexecuted_past(id_read),
#[cfg(target_os = "macos")]
crate::child::owned::teardown::Past::WaitMayFail,
policy,
&mut why,
|owned, why| {
held_teardown::tear_down_held(
owned,
held_teardown::HeldTeardown {
id: id_read,
#[cfg(target_os = "linux")]
reach: subtree.as_ref().map(|subtree| subtree as &dyn Reach),
#[cfg(target_os = "macos")]
reach: None,
disposition: crate::child::owned::teardown::Disposition::HandBack,
policy,
},
why,
)
},
));
#[cfg(windows)]
return Err(held_teardown::tear_down_after_failed_windows_attach(
owned, id_read, failure, policy, &mut why,
));
}
};
Ok(Child::from_parts(
owned,
id_read,
parent_ends,
kill_on_drop,
attachment,
elevation,
policy,
cmd.stop_action(),
#[cfg(windows)]
cmd.ctrl_proxy_setting(),
))
}
#[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: {}",
crate::error::Report(error)
);
#[cfg(not(test))]
debug_assert!(false, "a macOS attach cannot fail: {}", crate::error::Report(error));
let _ = error;
}
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 abandon_unadopted(
child: std::process::Child,
not_adopted: unique_report::NotAdopted,
tracked: TrackedKind,
prepared: crate::containment::Prepared,
policy: SpawnPolicy,
) -> SpawnFailure {
use unique_report::Unadoptable;
let front = tracked.front();
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) => late_child::abandon_late_child(child, unique, error, tracked, prepared, policy),
Unadoptable::Unverified => {
let fate = leave_unverified_child(child);
SpawnFailure::started(error, fate, None).with_detail(FrontFate::LeftUnreaped.detail(front, Some(pid)))
}
}
}
#[cfg(target_os = "macos")]
fn leave_unverified_child(child: std::process::Child) -> ChildFate {
let pid = child.id();
#[cfg(test)]
fault::capture(ProcessId::of(pid));
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"
);
drop(child);
ChildFate::Running { id: None }
}
#[cfg(target_os = "macos")]
struct UnwatchedChild {
child: std::process::Child,
pid: u32,
unique: u64,
}
#[cfg(target_os = "macos")]
struct UnwatchedReport {
front: Option<crate::elevation::front::Front>,
prepared: crate::containment::Prepared,
refusal: Error,
late: Option<Error>,
}
#[cfg(target_os = "macos")]
fn leave_unwatched_child(unwatched: UnwatchedChild, report: UnwatchedReport) -> SpawnFailure {
let UnwatchedChild { child, pid, unique } = unwatched;
let UnwatchedReport {
front,
prepared,
refusal,
late,
} = report;
let (fate, said, killing) = unwatched_child_fate(&*prepared.kernel, pid, unique, front.is_some());
let holders = if front.is_some() {
None
} else {
late_child::marker_holders(prepared)
};
let swept = holders.map(|tree| tree.send_kill(None).into_result().or_else(|left| left.unsettled(true)));
let tree = match &swept {
None => "its tree was not killed".to_owned(),
Some(Ok(())) => "its marker's holders were killed, and the rest of its tree (its process group, the \
processes its pid parents) was not"
.to_owned(),
Some(Err(left)) => format!(
"its marker's holders were not all killed ({}), and the rest of its tree was not",
crate::error::Report(left)
),
};
let lead = if late.is_some() {
format!("child {pid} {}, and its exit could not be watched", late_child::LATE)
} else {
format!("child {pid}'s exit could not be watched")
};
log::warn!(
"{lead} ({}), so it has no handle and {tree}: {said}; it is not waited for or reaped, so \
it stays a zombie once it exits",
crate::error::Report(&refusal)
);
drop(child);
let (cause, refused) = match late {
Some(late) => (late, Failures::collect([Arc::new(refusal)])),
None => (refusal, None),
};
let left = Failures::collect(swept.and_then(Result::err).map(Arc::new));
SpawnFailure::started(cause, fate, None)
.with_detail(FrontFate::LeftUnreaped.detail(front, Some(pid)))
.with_cleanup(refused)
.with_cleanup(killing)
.with_cleanup(left)
}
#[cfg(target_os = "macos")]
fn unwatched_child_fate(
kernel: &dyn crate::identity::Kernel,
pid: u32,
unique: u64,
front: bool,
) -> (ChildFate, String, Option<Failures>) {
use crate::signal::{via_audit_token, Sent, Sig};
if front {
return (
ChildFate::Running { id: None },
"it is an elevation front, so nothing was sent to it".to_owned(),
None,
);
}
match via_audit_token(kernel, pid, Some(unique), Sig::Kill) {
Ok(Sent::Delivered) => (
ChildFate::Killed,
"it was sent SIGKILL, or its exit had begun when the send was made".to_owned(),
None,
),
Ok(Sent::Gone) => (
ChildFate::Gone,
"it was gone, or its pid names another process, so nothing was sent".to_owned(),
None,
),
Ok(Sent::Unverified) => {
debug_assert!(false, "`via_audit_token` was given `Some(unique)`, so it verifies");
(ChildFate::Running { id: None }, "it was not signalled".to_owned(), None)
}
Err(kill) => (
ChildFate::Running { id: None },
format!("it could not be killed ({})", crate::error::Report(&kill)),
Failures::collect([Error::io_cause(crate::error::io_context("killing the child", kill))]),
),
}
}
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(not(any(target_os = "linux", target_os = "macos")))]
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)
}
#[cfg(not(target_os = "linux"))]
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> {
#[cfg_attr(not(unix), allow(unused_mut, reason = "only a unix spawn searches for its program"))]
let mut invocation = invocation(cmd)?;
#[cfg(unix)]
invocation.find(&child_env::child_env_of(cmd))?;
let mut std_cmd = invocation.std_command();
let Invocation { cwd, enter, .. } = invocation;
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,
#[cfg(unix)]
searched: 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)]
searched: true,
};
#[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,
searched: false,
});
}
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))
}
pub(crate) struct Invocation {
pub(crate) program: std::ffi::OsString,
#[cfg(unix)]
pub(crate) arg0: Option<std::ffi::OsString>,
pub(crate) args: Vec<std::ffi::OsString>,
#[cfg(windows)]
raw_args: Option<std::ffi::OsString>,
pub(crate) cwd: Option<std::path::PathBuf>,
#[cfg_attr(
target_os = "linux",
allow(dead_code, reason = "the Linux child enters every directory itself, asked or not")
)]
pub(crate) enter: bool,
#[cfg(unix)]
pub(crate) searched: bool,
}
impl Invocation {
#[cfg(not(target_os = "linux"))]
fn std_command(&self) -> std::process::Command {
let mut c = std::process::Command::new(&self.program);
#[cfg(unix)]
if let Some(arg0) = &self.arg0 {
use std::os::unix::process::CommandExt;
c.arg0(arg0);
}
c.args(&self.args);
#[cfg(windows)]
if let Some(raw) = &self.raw_args {
use std::os::windows::process::CommandExt;
c.raw_arg(raw); }
c
}
}
pub(crate) fn invocation(cmd: &Command) -> Result<Invocation, Error> {
let invocation = match cmd.input() {
CommandInput::Empty => return Err(Error::Io(std::io::Error::other("no program specified"))),
CommandInput::Argv(argv) => {
let (
Resolved {
program,
cwd,
enter,
#[cfg(unix)]
searched,
},
rest,
) = resolve_program_argv(cmd, argv)?;
Invocation {
program,
#[cfg(unix)]
arg0: cmd.executable_path().map(|exe| {
argv.first()
.map_or(exe.as_os_str(), std::ffi::OsString::as_os_str)
.to_owned()
}),
args: rest.to_vec(),
#[cfg(windows)]
raw_args: None,
cwd,
enter,
#[cfg(unix)]
searched,
}
}
CommandInput::CommandLine(line) => invocation_of_commandline(cmd, line)?,
};
reject_batch_path(std::path::Path::new(&invocation.program))?;
Ok(invocation)
}
#[cfg(unix)]
fn invocation_of_commandline(cmd: &Command, line: &std::ffi::OsString) -> Result<Invocation, Error> {
use std::ffi::OsString;
use std::os::unix::ffi::{OsStrExt, OsStringExt};
let words = crate::quote::posix::split(line.as_bytes())?;
let mut 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,
searched,
} = resolve_program(cmd, argv[0].clone())?;
let arg0 = cmd.executable_path().map(|_| argv[0].clone());
let args = argv.split_off(1);
Ok(Invocation {
program,
arg0,
args,
cwd,
enter,
searched,
})
}
#[cfg(windows)]
fn invocation_of_commandline(cmd: &Command, line: &std::ffi::OsString) -> Result<Invocation, Error> {
use std::os::windows::ffi::{OsStrExt, OsStringExt};
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")))?;
Ok(Invocation {
program: std::ffi::OsString::from_wide(&first),
args: Vec::new(),
raw_args: Some(std::ffi::OsString::from_wide(&rest)),
cwd: cmd.cwd().map(std::path::Path::to_path_buf),
enter: false,
})
}
#[cfg(not(target_os = "linux"))]
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(),
source: None,
});
}
}
}
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(),
source: None,
})?;
child_ends.insert(slot, dup(src)?);
}
}
Ok((child_ends, parent_ends))
}
#[cfg(unix)]
fn fd_mappings(child_ends: BTreeMap<Fd, ChildEnd>) -> Vec<fd_map::FdMapping> {
child_ends
.into_iter()
.map(|(fd, owned)| fd_map::FdMapping {
parent_fd: owned,
child_fd: fd.raw(),
})
.collect()
}
#[cfg(target_os = "linux")]
fn resolve_into_fork(
steps: &mut in_child::InChild,
fds: &BTreeMap<Fd, ResolvedStdio>,
) -> Result<BTreeMap<Fd, ParentEnd>, Error> {
let (mut child_ends, parent_ends) = resolve_stdio(fds, ParentStd::read())?;
let stdio = [Fd::STDIN, Fd::STDOUT, Fd::STDERR]
.into_iter()
.map(|slot| fd_map::FdMapping {
parent_fd: child_ends
.remove(&slot)
.unwrap_or_else(|| unreachable!("resolve_stdio resolves 0/1/2 always")),
child_fd: slot.raw(),
})
.collect();
steps.map_stdio(fd_map::Plan::stdio(stdio));
fd_map::install(steps, fd_mappings(child_ends)).map_err(Error::Io)?;
Ok(parent_ends)
}
#[cfg(not(target_os = "linux"))]
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)]
fd_map::install(steps, fd_mappings(child_ends)).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(),
source: None,
})
}
};
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(),
source: None,
})
}
};
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: &OwnedChild,
) -> (
crate::identity::Resolved<ProcessId>,
crate::identity::UnknownCause,
Diagnosis,
) {
use crate::identity::Resolved;
#[cfg(any(target_os = "linux", windows))]
let (read, cause) = resolve_identity_unchecked(kernel, pid, through.os_handle());
#[cfg(target_os = "macos")]
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;
match through.peek().map_err(Error::into_io) {
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 ({}); it is not shown to be ours",
crate::error::Report(&e)
),
e,
),
),
}
}
#[cfg(windows)]
{
(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()),
}
}
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, said) = match why.failed_check.take() {
Some(source) => {
let error = Error::Unassessable {
detail: "the spawned child's identity could not be checked against its handle".into(),
source: Some(Error::io_cause(source)),
};
let said = error.to_string();
(error, said)
}
None => {
let error = spawn_identity_error(crate::identity::Resolved::Unknown, cause);
let said = crate::error::Report(&error).to_string();
(error, said)
}
};
log::debug!("child {pid}: {said}; the child is kept without an identity");
why.kept_check = why.owed.take();
error
}
#[cfg(windows)]
pub(crate) fn windows_identity_or_keep(
pid: u32,
read: crate::identity::Resolved<ProcessId>,
cause: crate::identity::UnknownCause,
why: &mut Diagnosis,
) -> Result<ProcessId, Error> {
use crate::identity::Resolved;
match read {
Resolved::Found(id) => Ok(id),
Resolved::Unknown => Err(kept_without_identity(pid, cause, why)),
Resolved::Gone => {
debug_assert!(false, "the read of a Windows process handle never says `Gone`");
Err(kept_without_identity(pid, cause, why))
}
}
}
pub(crate) fn resolve_identity_unchecked(
kernel: &dyn crate::identity::Kernel,
pid: u32,
#[cfg(any(target_os = "linux", windows))] held: crate::os_process::child::OsHandle<'_>,
) -> (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());
}
#[cfg(unix)]
if fault::force_identity_vanished() {
fault::capture(ProcessId::of(pid));
return (crate::identity::Resolved::Gone, Default::default());
}
}
#[cfg(any(target_os = "linux", windows))]
{
ProcessId::of_held_with(kernel, pid, held)
}
#[cfg(target_os = "macos")]
{
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, crate::containment::dispatch::AttachFailure> {
#[cfg(test)]
if fault::force_attach_failure() {
if let Ok(id) = &id {
fault::capture(crate::identity::Resolved::Found(*id));
}
#[cfg(unix)]
{
let mut prepared = prepared;
prepared.settle_verdict(
#[cfg(target_os = "linux")]
child,
);
}
return Err(Error::Containment {
detail: "forced attach failure (test seam)".into(),
source: None,
}
.into());
}
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)]
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(unix)]
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(unix)]
pub(crate) fn detail(self, front: Option<crate::elevation::front::Front>, pid: Option<u32>) -> Option<String> {
self.detailing(front, pid, false)
}
#[cfg(unix)]
pub(crate) fn detail_handed_back(
self,
front: Option<crate::elevation::front::Front>,
pid: Option<u32>,
) -> Option<String> {
self.detailing(front, pid, true)
}
#[cfg(unix)]
fn detailing(
self,
front: Option<crate::elevation::front::Front>,
pid: Option<u32>,
handed_back: bool,
) -> Option<String> {
let front = front?;
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}"
),
};
Some(format!("{what}; {fate}"))
}
}
#[cfg(unix)]
pub(crate) fn settle_before_teardown(
prepared: &mut crate::containment::Prepared,
#[cfg(target_os = "linux")] child: crate::containment::ChildHandle<'_>,
) -> Option<crate::containment::dispatch::AttachFailure> {
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,
) -> Option<Failures> {
let refusal = prepared.kill_group_before_attach(child).err()?;
note_refused_group_kill(Some(child.pid), refusal, false, why);
refused_group_kill_failure(child.pid, refusal)
}
#[cfg(target_os = "linux")]
pub(crate) fn refused_group_kill_failure(pid: u32, refusal: nix::errno::Errno) -> Option<Failures> {
Failures::collect([Error::io_cause(crate::error::io_context(
format!("killing the process group of {}", named(Some(pid))),
std::io::Error::from(refusal),
))])
}
#[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 ({}); its \
members may be left running{reaped}",
crate::error::Report(&e)
)),
}
}
#[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 ({report}); its teardown cannot place it",
report = crate::error::Report(&e)
);
None
}
}
}
#[cfg(test)]
pub(crate) mod fault {
use std::cell::Cell;
use crate::identity::ProcessId;
use crate::relayed_probe::{self, Probe};
thread_local! {
#[cfg(unix)]
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) };
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() };
#[cfg(target_os = "macos")]
static BEFORE_ADOPT: 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(unix)]
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())
}
#[cfg(unix)]
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));
}
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())
}
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;
#[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")]
BeforeAdopt,
#[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::BeforeAdopt => &BEFORE_ADOPT,
#[cfg(target_os = "macos")]
SpawnPoint::BeforeLateTeardown => &BEFORE_LATE_TEARDOWN,
#[cfg(target_os = "macos")]
SpawnPoint::BeforeLateRootKill => &BEFORE_LATE_ROOT_KILL,
}
}
#[cfg_attr(
not(any(all(feature = "tokio", target_os = "linux"), windows)),
allow(
dead_code,
reason = "only the Linux async spawn's and the Windows spawn's tests arm a spawn point"
)
)]
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) struct Ran;
impl Probe for Ran {
type Event = RanAt;
}
#[cfg_attr(
not(feature = "tokio"),
allow(dead_code, reason = "only the async spawn's tests read it")
)]
pub(crate) struct RanAt {
pub(crate) point: SpawnPoint,
pub(crate) thread: std::thread::ThreadId,
pub(crate) id: crate::identity::Resolved<ProcessId>,
}
#[cfg_attr(
not(feature = "tokio"),
allow(dead_code, reason = "only the async spawn's tests install it")
)]
pub(crate) fn install_ran(tx: std::sync::mpsc::Sender<RanAt>) -> relayed_probe::Guard<Ran> {
relayed_probe::install(tx)
}
pub(crate) fn run_at(point: SpawnPoint, pid: u32) {
if relayed_probe::is_installed::<Ran>() {
relayed_probe::notify::<Ran>(RanAt {
point,
thread: std::thread::current().id(),
id: ProcessId::of(pid),
});
}
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(any(all(feature = "tokio", target_os = "linux"), windows)),
allow(
dead_code,
reason = "only the Linux async spawn's and the Windows spawn's tests arm a spawn point"
)
)]
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 stdout = None;
#[cfg(windows)]
let stdout = Some(crate::stdio::Stdio::null());
TeardownBlockerParts {
argv: crate::test_child::BLOCKER_ARGV.iter().map(Into::into).collect(),
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(unix)]
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(not(target_os = "macos"))]
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/child_env.rs"]
mod child_env;
#[cfg(unix)]
#[path = "spawn/lookup.rs"]
mod lookup;
#[cfg(unix)]
#[path = "spawn/in_child.rs"]
pub(crate) mod in_child;
#[cfg(target_os = "macos")]
#[path = "spawn/fd_channel.rs"]
pub(crate) mod fd_channel;
#[cfg(target_os = "linux")]
#[path = "spawn/fork_exec.rs"]
pub(crate) mod fork_exec;
#[cfg(target_os = "linux")]
#[path = "spawn/fork_spawn.rs"]
mod fork_spawn;
#[path = "spawn/failure.rs"]
pub(crate) mod failure;
#[path = "spawn/policy.rs"]
pub(crate) mod policy;
#[path = "spawn/held_teardown.rs"]
pub(crate) mod held_teardown;
#[cfg(target_os = "macos")]
#[path = "spawn/late_child.rs"]
mod late_child;
#[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(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(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;