#[path = "child/graceful.rs"]
mod graceful;
#[path = "child/suspended.rs"]
mod suspended;
pub use suspended::SuspendedChild;
#[path = "child/proc_source.rs"]
mod proc_source;
#[cfg(target_os = "macos")]
pub(crate) use proc_source::Forgotten;
pub(crate) use proc_source::ProcSource;
#[cfg(any(unix, test))]
pub(crate) use proc_source::Waited;
#[cfg(target_os = "macos")]
pub(crate) use proc_source::HANDED_TO_ORPHAN_REAPER;
use std::collections::BTreeMap;
use std::process::ExitStatus;
use crate::containment::dispatch::{SweepFailure, TeardownCaller, TreeKillOutcome};
use crate::containment::{Attached, Containment};
use crate::error::Error;
use crate::identity::ProcessId;
use crate::pipe::ParentEnd;
use crate::signal::{Sent, Sig};
use crate::stdio::Fd;
#[cfg(unix)]
use crate::wait::teardown_warn::{wait_warning, Due};
pub(super) type FdPipes = BTreeMap<Fd, ParentEnd>;
fn take_reader(ends: &mut FdPipes, fd: Fd, what: &str) -> Option<super::stdio::OwnedRead> {
match ends.remove(&fd)? {
ParentEnd::Reader(r) => match super::stdio::register_reader(r) {
Ok(end) => Some(end),
Err(e) => {
log::warn!(
"{fd} {what} dropped: tokio conversion failed ({e}); the child will see a broken pipe on writes"
);
None
}
},
end => {
ends.insert(fd, end);
None
}
}
}
fn take_writer(ends: &mut FdPipes, fd: Fd, what: &str) -> Option<super::stdio::OwnedWrite> {
try_take_writer(ends, fd).unwrap_or_else(|e| {
log::warn!("{fd} {what} dropped: tokio conversion failed ({e}); the child will see EOF on reads");
None
})
}
fn try_take_writer(ends: &mut FdPipes, fd: Fd) -> std::io::Result<Option<super::stdio::OwnedWrite>> {
match ends.remove(&fd) {
None => Ok(None),
Some(ParentEnd::Writer(w)) => super::stdio::register_writer(w).map(Some),
Some(end) => {
ends.insert(fd, end);
Ok(None)
}
}
}
const PROC_TAKEN: &str = "the async child's process backend is taken only by a teardown";
#[derive(Debug, Default)]
pub(crate) struct OsResources {
pub(crate) proc: Option<ProcSource>,
pub(crate) attached: Attached,
pub(crate) pipes: FdPipes,
}
impl OsResources {
pub(crate) fn proc_mut(&mut self) -> &mut ProcSource {
self.proc.as_mut().expect(PROC_TAKEN)
}
#[cfg(unix)]
pub(crate) fn pid(&self) -> u32 {
self.proc.as_ref().expect(PROC_TAKEN).pid()
}
pub(crate) fn release_without_waiting(mut self) {
#[cfg(test)]
fault::note_release();
if let Some(proc) = self.proc.take() {
proc.release();
}
std::mem::take(&mut self.attached).release_without_waiting();
}
#[cfg(unix)]
fn release_after_drain(self, late: &mut LateWarn, tree_failed: bool) {
if let Some(attached) = self.release_backend(tree_failed) {
drop_after_drain(attached, late);
}
}
#[cfg(unix)]
async fn release_after_drain_awaiting(self, pid: u32, tree_failed: bool) {
let Some(attached) = self.release_backend(tree_failed) else {
return;
};
let draining = Draining {
pid,
attached: Some(attached),
};
#[cfg(target_os = "linux")]
if let Some(Attached::Cgroup(leaf)) = &draining.attached {
if let Err(e) = crate::tokio::wait::cgroup_wait_tree_drained(leaf, None).await {
log::debug!(
"async child {pid}: its leaf's drain cannot be watched ({e}); the teardown waits for it on \
this thread, blocking"
);
return;
}
}
draining.finish();
}
#[cfg(unix)]
fn release_backend(mut self, tree_failed: bool) -> Option<Attached> {
#[cfg(test)]
fault::note_release();
if let Some(proc) = self.proc.take() {
proc.release();
}
let attached = std::mem::take(&mut self.attached);
#[cfg(target_os = "linux")]
if tree_failed && matches!(attached, Attached::Cgroup(_)) && !attached.cgroup_kill_landed() {
attached.release_without_waiting();
return None;
}
#[cfg(not(target_os = "linux"))]
let _ = tree_failed;
Some(attached)
}
}
#[cfg(unix)]
fn drop_after_drain(attached: Attached, late: &mut LateWarn) {
match attached {
#[cfg(target_os = "linux")]
Attached::Cgroup(leaf) => leaf.drop_warning(late),
other => {
let _ = late;
drop(other);
}
}
}
#[cfg(unix)]
struct Draining {
pid: u32,
attached: Option<Attached>,
}
#[cfg(unix)]
impl Draining {
fn finish(mut self) {
drop(self.attached.take());
}
}
#[cfg(unix)]
impl Drop for Draining {
fn drop(&mut self) {
if let Some(attached) = self.attached.take() {
if std::thread::panicking() {
drop(attached);
} else {
drop_after_drain(attached, &mut LateWarn::new(self.pid));
}
}
}
}
#[derive(Debug)]
pub struct Child {
os: OsResources,
id: Option<ProcessId>,
kill_on_drop: bool,
containment: Containment,
tree_killed: crate::containment::TreeKilled,
graceful: crate::graceful::GracefulMechanism,
elevation: Option<crate::elevation::ElevationReport>,
front: Option<crate::elevation::front::Front>,
#[cfg(unix)]
reported: Vec<crate::child::drop_report::PartKey>,
}
impl Child {
pub(super) fn from_parts(
proc: ProcSource,
id: Option<ProcessId>,
kill_on_drop: bool,
attachment: crate::containment::Attachment,
pipes: FdPipes,
) -> Child {
debug_assert!(
id.is_none_or(|id| proc.pid() == id.pid()),
"a child's process and identity name one pid"
);
Child {
os: OsResources {
proc: Some(proc),
attached: attachment.attached,
pipes,
},
id,
kill_on_drop,
containment: attachment.containment,
tree_killed: Default::default(),
graceful: attachment.graceful,
elevation: None,
front: None,
#[cfg(unix)]
reported: Vec::new(),
}
}
#[cfg(windows)]
pub(super) fn process_handle(&self) -> Option<std::os::windows::io::RawHandle> {
self.os.proc.as_ref()?.raw_handle()
}
#[cfg(unix)]
pub(super) fn forget_for(
&mut self,
view: &crate::containment::DropView,
) -> Option<crate::child::drop_report::Forgot> {
self.os.proc.as_mut()?.forget_for(view)
}
#[cfg(all(test, unix, not(target_os = "macos")))]
pub(super) fn tree_killed(&self) -> bool {
self.tree_killed.is_set()
}
#[cfg(unix)]
pub(super) fn settle_tree(
&self,
kill: TreeKillOutcome,
root_ended: bool,
) -> Result<crate::containment::dispatch::SettleOutcome, crate::containment::dispatch::Unsettled> {
self.os.attached.settle(&self.tree_killed, kill, root_ended)
}
#[cfg(unix)]
pub(super) fn end_cleanup(&mut self, settled: bool, warned: Vec<crate::child::drop_report::PartKey>) {
if settled {
self.kill_on_drop = false;
}
self.reported = warned;
}
pub(super) fn set_front(&mut self, front: Option<crate::elevation::front::Front>) {
self.front = front;
}
pub(super) fn proc_mut(&mut self) -> &mut ProcSource {
self.os.proc_mut()
}
pub(super) fn proc(&self) -> &ProcSource {
self.os.proc.as_ref().expect(PROC_TAKEN)
}
pub(super) fn commit_kill_on_drop(mut self) -> Result<Child, crate::child::spawn::SpawnFailure> {
let Err(refusal) = self.os.attached.honor_kill_on_drop(self.kill_on_drop) else {
return Ok(self);
};
self.kill_on_drop = true;
let fate = self.tear_down_now(crate::containment::dispatch::TeardownCaller::FailedRun);
Err(crate::child::spawn::failed_after_the_spawn(
Error::Io(refusal),
fate,
None,
self.behind_wrapper(),
))
}
#[cfg(unix)]
pub(super) fn kill_tree_members_unless_reaped(&self, view: &crate::containment::DropView) -> TreeKillOutcome {
let check = || self.group_number_holds();
self.os
.attached
.hard_kill_for_drop(view, &crate::containment::GroupRoot::new(self.root_pidfd(), &check))
}
#[cfg(unix)]
pub(super) fn read_root_view(
&self,
caller: crate::containment::dispatch::TeardownCaller,
) -> crate::containment::DropView {
crate::containment::DropView::read(
caller,
self.pid(),
self.id,
|| {
self.os
.proc
.as_ref()
.map_or(crate::signal::RootState::Reaped { own: false }, ProcSource::state)
},
&self.tree_killed,
)
}
#[cfg(unix)]
pub(super) fn block_until_members_drained(&mut self) -> Result<(), Error> {
#[cfg(target_os = "linux")]
if let crate::containment::Attached::Cgroup(leaf) = &mut self.os.attached {
return leaf.wait_drained_then_warn(&mut crate::containment::cgroup::WarnAfter(slow_teardown_after()));
}
Ok(())
}
#[cfg(all(test, unix))]
pub(super) fn signals_a_group(&self) -> bool {
self.os.attached.signals_a_group()
}
#[cfg(unix)]
pub(super) fn teardown_subject(&self) -> String {
self.os.attached.teardown_subject()
}
pub(crate) fn set_elevation(&mut self, report: Option<crate::elevation::ElevationReport>) {
self.elevation = report;
}
pub fn elevation(&self) -> Option<crate::elevation::ElevationReport> {
self.elevation.clone()
}
#[cfg(unix)]
pub(super) fn kill_gate(&self) -> crate::elevation::front::Gate {
kill_gate(self.front, &self.os, self.pid())
}
#[cfg(unix)]
pub(super) fn cgroup_not_killed(&self, failure: Option<&str>) -> Error {
crate::elevation::front::cgroup_not_killed_of(self.front, self.pid(), failure)
}
#[cfg(unix)]
pub(super) fn cgroup_kill_reached(&self) -> Result<(), Error> {
cgroup_kill_reached(self.front, &self.os, self.pid())
}
#[cfg(unix)]
pub(super) fn terminate_gate(&self) -> crate::elevation::front::Gate {
crate::elevation::front::terminate_gate(self.front, self.pid(), || {
self.os.proc.as_ref().map_or(Ok(false), ProcSource::is_running)
})
}
pub(crate) fn behind_wrapper(&self) -> bool {
#[cfg(test)]
if crate::child::spawn::failure::seams::wrapper() {
return true;
}
self.elevation
.as_ref()
.is_some_and(|report| report.via.program_outlives_child())
}
fn is_elevated_wrapper(&self) -> bool {
matches!(
self.elevation.as_ref().map(|r| &r.via),
Some(crate::elevation::ElevatedVia::Wrapped(_) | crate::elevation::ElevatedVia::WindowsUac)
)
}
#[cfg(unix)]
pub(super) fn wait_and_reap_blocking(
&mut self,
) -> (crate::error::ChildFate, Option<crate::child::drop_report::Forgot>) {
let pid = self.pid();
let (waited, cause) = self
.proc_mut()
.wait_warning(pid, |proc| proc.wait_and_reap_caused(pid, log::Level::Debug));
match waited {
Waited::Exited => {
let id = self.id;
(self.proc_mut().collect_exit(id), None)
}
_ => (
crate::error::ChildFate::Killed,
self.proc_mut().forget_for_wait(waited, cause),
),
}
}
pub fn id(&self) -> Option<ProcessId> {
self.id
}
pub fn pid(&self) -> u32 {
self.proc().pid()
}
pub fn is_alive(&self) -> crate::identity::Liveness {
self.proc().liveness()
}
pub fn containment(&self) -> Containment {
self.containment
}
pub fn graceful_mechanism(&self) -> crate::graceful::GracefulMechanism {
self.graceful
}
pub fn stdin(&mut self) -> Option<super::stdio::ChildStdin> {
take_writer(&mut self.os.pipes, Fd::STDIN, "write end").map(|inner| super::stdio::ChildStdin { inner })
}
pub(super) fn stdin_or_error(&mut self) -> std::io::Result<Option<super::stdio::ChildStdin>> {
Ok(try_take_writer(&mut self.os.pipes, Fd::STDIN)?.map(|inner| super::stdio::ChildStdin { inner }))
}
pub fn stdout(&mut self) -> Option<super::stdio::ChildStdout> {
take_reader(&mut self.os.pipes, Fd::STDOUT, "read end").map(|inner| super::stdio::ChildStdout { inner })
}
pub fn stderr(&mut self) -> Option<super::stdio::ChildStderr> {
take_reader(&mut self.os.pipes, Fd::STDERR, "read end").map(|inner| super::stdio::ChildStderr { inner })
}
#[cfg(unix)]
pub fn fd_read_end(&mut self, fd: impl Into<crate::stdio::Fd>) -> Option<::tokio::net::unix::pipe::Receiver> {
take_reader(&mut self.os.pipes, fd.into(), "read end")
}
#[cfg(unix)]
pub fn fd_write_end(&mut self, fd: impl Into<crate::stdio::Fd>) -> Option<::tokio::net::unix::pipe::Sender> {
take_writer(&mut self.os.pipes, fd.into(), "write end")
}
#[cfg(windows)]
pub fn fd_read_end(&mut self, fd: impl Into<Fd>) -> Option<super::stdio::ChildStdout> {
take_reader(&mut self.os.pipes, fd.into(), "read end").map(|inner| super::stdio::ChildStdout { inner })
}
#[cfg(windows)]
pub fn fd_write_end(&mut self, fd: impl Into<Fd>) -> Option<super::stdio::ChildStdin> {
take_writer(&mut self.os.pipes, fd.into(), "write end").map(|inner| super::stdio::ChildStdin { inner })
}
#[cfg(windows)]
pub fn test_job_handle_contains_self(&self) -> bool {
self.test_job_handle_contains(self.pid())
}
#[cfg(windows)]
pub fn test_job_handle_contains(&self, pid: u32) -> bool {
crate::containment::windows::job_contains_pid(&self.os.attached, pid)
}
#[cfg(all(test, unix))]
pub(crate) fn test_treewalk_root(&self) -> Option<ProcessId> {
match &self.os.attached {
crate::containment::Attached::TreeWalk(root) => Some(*root),
_ => None,
}
}
#[cfg(all(test, target_os = "macos"))]
pub(crate) fn test_marker_root(&self) -> Option<ProcessId> {
match &self.os.attached {
crate::containment::Attached::FdMarker(m) => m.root(),
_ => None,
}
}
pub async fn wait(&mut self) -> Result<ExitStatus, Error> {
#[cfg(test)]
if let Some(error) = crate::child::spawn::failure::seams::take_wait_failure() {
return Err(error);
}
drop(self.os.pipes.remove(&Fd::STDIN));
self.proc_mut().wait().await
}
pub fn try_wait(&mut self) -> Result<Option<ExitStatus>, Error> {
self.proc_mut().try_wait()
}
pub fn kill(&mut self) -> Result<(), Error> {
self.kill_sent().map(|_| ())
}
pub(crate) fn kill_sent(&mut self) -> Result<Sent, Error> {
#[cfg(unix)]
let gate = self.kill_gate();
#[cfg(unix)]
if !matches!(gate, crate::elevation::front::Gate::Closed(_)) {
self.refuse_unpinned("kill", None)?;
}
self.kill_sent_gated(
"kill",
#[cfg(unix)]
gate,
)
}
pub(crate) fn kill_sent_gated(
&mut self,
caller: &str,
#[cfg(unix)] gate: crate::elevation::front::Gate,
) -> Result<Sent, Error> {
let sent = self.signal_gated(
caller,
#[cfg(unix)]
gate,
);
if matches!(sent, Ok(Sent::Gone | Sent::Unverified)) {
#[cfg(unix)]
self.proc_mut().forget_if_foreign();
}
sent
}
#[cfg_attr(
not(unix),
allow(unused_variables, reason = "only a Unix cgroup front's kill names its caller")
)]
pub(crate) fn signal_gated(
&mut self,
caller: &str,
#[cfg(unix)] gate: crate::elevation::front::Gate,
) -> Result<Sent, Error> {
#[cfg(test)]
if fault::take_force_kill_failure() {
return Err(fault::forced_kill_failure());
}
#[cfg(unix)]
let exited_front = matches!(gate, crate::elevation::front::Gate::Exited);
#[cfg(not(unix))]
let exited_front = false;
#[cfg(unix)]
match gate {
crate::elevation::front::Gate::Open | crate::elevation::front::Gate::Exited => {}
crate::elevation::front::Gate::CgroupOnly => {
let check = || self.group_number_holds();
self.os
.attached
.hard_kill_settled(
caller,
&self.tree_killed,
&crate::containment::GroupRoot::new(self.root_pidfd(), &check),
)
.map_err(|e| crate::elevation::front::cgroup_kill_failed(self.front, self.pid(), e))?;
cgroup_kill_reached(self.front, &self.os, self.pid())?;
return Ok(Sent::Delivered);
}
crate::elevation::front::Gate::Closed(unkillable) => return Err(unkillable),
}
match self.proc_mut().signal(Sig::Kill) {
Err(Error::Io(e)) if exited_front && e.kind() == std::io::ErrorKind::PermissionDenied => {
log::debug!("the kill of exited front pid {} was refused ({e})", self.pid());
Ok(Sent::Delivered)
}
Err(Error::Io(e)) => Err(crate::elevation::map_elevated_kill_error(e, self.is_elevated_wrapper())),
Err(other) => Err(other),
Ok(sent) => Ok(sent),
}
}
pub fn kill_tree(&mut self) -> Result<(), Error> {
self.kill_tree_after("kill_tree", None).map_err(|failure| failure.error)
}
pub(crate) fn kill_tree_after(&mut self, op: &'static str, earlier: Option<&str>) -> Result<(), SweepFailure> {
#[cfg(not(unix))]
let _ = earlier;
self.require_contained()?;
#[cfg(unix)]
let front = match self.kill_gate() {
crate::elevation::front::Gate::Closed(unkillable) => return Err(unkillable.into()),
crate::elevation::front::Gate::Open => None,
crate::elevation::front::Gate::Exited => Some(false),
crate::elevation::front::Gate::CgroupOnly => Some(true),
};
#[cfg(unix)]
let check = || self.group_number_holds();
#[cfg(unix)]
let group = crate::containment::GroupRoot::new(self.root_pidfd(), &check);
#[cfg(not(unix))]
let group = crate::containment::GroupRoot::none();
#[cfg(unix)]
let root_ended_by_handle = std::cell::Cell::new(false);
#[cfg(unix)]
if let Some(result) = self
.tree_call(crate::containment::dispatch::TreeSignal::Kill, op, earlier)
.root_checked(
|| self.root_state(),
|| {
let sent = self.kill_root_through_handle();
root_ended_by_handle.set(SweepFailure::killed_root(&sent));
sent
},
&group,
)
{
return result.map_err(|error| SweepFailure {
error,
root_ended: root_ended_by_handle.get(),
});
}
let group_result = self.os.attached.hard_kill(&group);
let group_result = self.os.attached.unless_unwalked(op, &self.tree_killed, group_result)?;
#[cfg(unix)]
if let Some(in_cgroup) = front {
return match self
.os
.attached
.settle_for_kill_tree(op, &self.tree_killed, group_result, false)
{
Ok(()) if in_cgroup => cgroup_kill_reached(self.front, &self.os, self.pid()),
Err(left) if in_cgroup => Err(crate::elevation::front::cgroup_kill_failed(
self.front,
self.pid(),
left,
)),
other => other,
}
.map_err(SweepFailure::from);
}
#[cfg(unix)]
let (backstop, root_ended) = if self.root_is_unpinned() {
log::debug!(
"{op}({}): launchd holds the root's zombie, so the handle backstop is skipped",
self.pid()
);
(Ok(()), true)
} else {
SweepFailure::backstop_of(self.kill_sent_gated(op, crate::elevation::front::Gate::Open))
};
#[cfg(not(unix))]
let (backstop, root_ended) = SweepFailure::backstop_of(self.kill_sent_gated(op));
SweepFailure::of(
op,
&self.os.attached,
&self.tree_killed,
group_result,
backstop,
root_ended,
)
}
pub fn terminate_tree(&self) -> Result<(), Error> {
self.require_contained()?;
#[cfg(unix)]
let check = || self.group_number_holds();
#[cfg(unix)]
let group = crate::containment::GroupRoot::new(self.root_pidfd(), &check);
#[cfg(not(unix))]
let group = crate::containment::GroupRoot::none();
#[cfg(unix)]
if let Some(result) = self
.tree_call(crate::containment::dispatch::TreeSignal::Term, "terminate_tree", None)
.root_checked(|| self.root_state(), || self.term_root_through_handle(), &group)
{
return result;
}
self.terminate_tree_unchecked(&group)
}
#[cfg(unix)]
pub(super) fn group_number_holds(&self) -> Result<(), String> {
crate::child::tree_call::group_number_holds(self.pid(), self.root_state())
}
#[cfg(unix)]
pub(super) fn root_pidfd(&self) -> Option<std::os::fd::BorrowedFd<'_>> {
self.os.proc.as_ref().and_then(ProcSource::pidfd)
}
#[cfg(unix)]
fn kill_root_through_handle(&self) -> Result<Sent, Error> {
let Some(proc) = self.os.proc.as_ref() else {
return Ok(Sent::Gone);
};
match proc.signal(Sig::Kill) {
Err(Error::Io(e)) => Err(crate::elevation::map_elevated_kill_error(e, self.is_elevated_wrapper())),
other => other,
}
}
#[cfg(unix)]
fn term_root_through_handle(&self) -> Result<Sent, Error> {
self.os
.proc
.as_ref()
.map_or(Ok(Sent::Gone), |proc| proc.signal(Sig::Term))
}
#[cfg(unix)]
fn tree_call<'a>(
&'a self,
signal: crate::containment::dispatch::TreeSignal,
op: &'static str,
earlier: Option<&'a str>,
) -> crate::child::TreeCall<'a> {
crate::child::TreeCall {
attached: &self.os.attached,
pid: self.pid(),
signal,
op,
earlier,
killed: &self.tree_killed,
}
}
pub(super) fn terminate_tree_unchecked(&self, group: &crate::containment::GroupRoot<'_>) -> Result<(), Error> {
#[cfg(windows)]
if !self.proc().pins_pid() {
return Err(self.unpinned_pid_refusal("terminate_tree"));
}
self.os.attached.terminate(self.pid(), group)
}
#[cfg(windows)]
fn unpinned_pid_refusal(&self, op: &str) -> Error {
Error::Unassessable {
detail: format!(
"this handle no longer pins pid {pid}: the async backend released the child's \
process handle when its exit was observed, so the pid may since name an \
unrelated process. A console control event is addressed by pid alone, so {op}() \
sent nothing. The child itself is already gone; kill_tree() addresses no pid and \
still tears down any survivors.",
pid = self.pid()
),
source: None,
}
}
#[cfg(unix)]
fn root_state(&self) -> crate::signal::RootState {
self.os
.proc
.as_ref()
.map_or(crate::signal::RootState::Reaped { own: false }, ProcSource::state)
}
#[cfg(unix)]
pub(super) fn refuse_unpinned(&self, op: &str, earlier: Option<&str>) -> Result<(), Error> {
crate::signal::refuse_unpinned(self.pid(), op, earlier, || self.root_state())
}
pub(super) fn root_is_unpinned(&self) -> bool {
#[cfg(unix)]
return crate::signal::is_unpinned(|| self.root_state());
#[cfg(not(unix))]
false
}
fn require_contained(&self) -> Result<(), Error> {
crate::containment::require_contained(self.containment, &self.os.attached)
}
fn require_drainable(&self) -> Result<(), Error> {
crate::containment::require_drainable(self.containment, &self.os.attached)
}
pub async fn wait_tree(&self) -> Result<crate::containment::TreeDrain, Error> {
self.require_drainable()?;
super::wait::wait_tree_drained_dispatch(&self.os.attached, None).await
}
pub async fn wait_tree_timeout(
&self,
timeout: std::time::Duration,
) -> Result<crate::containment::TreeDrain, Error> {
self.require_drainable()?;
let deadline = super::wait::deadline_from(timeout);
super::wait::wait_tree_drained_dispatch(&self.os.attached, deadline).await
}
}
impl Child {
pub fn detach(&mut self) -> Result<(), Error> {
if !self.kill_on_drop {
return Ok(());
}
self.os.attached.disarm().map_err(Error::Io)?;
self.kill_on_drop = false;
Ok(())
}
}
#[cfg(test)]
#[path = "child_drop_tests.rs"]
pub(crate) mod child_drop_tests;
#[cfg(all(test, unix))]
pub(crate) mod drop_fault {
use std::cell::Cell;
thread_local! {
static COUNTS: Cell<Option<(u32, u32)>> = const { Cell::new(None) };
}
pub(crate) fn record() -> Recorder {
COUNTS.with(|c| c.set(Some((0, 0))));
Recorder(())
}
#[must_use = "recording stops as soon as the recorder is dropped"]
pub(crate) struct Recorder(());
impl Recorder {
pub(crate) fn kills(&self) -> u32 {
COUNTS.with(|c| c.get().expect("the recorder is live").0)
}
pub(crate) fn forgets(&self) -> u32 {
COUNTS.with(|c| c.get().expect("the recorder is live").1)
}
}
impl Drop for Recorder {
fn drop(&mut self) {
COUNTS.with(|c| c.set(None));
}
}
pub(super) fn note_root_kill() {
COUNTS.with(|c| {
if let Some((k, f)) = c.get() {
c.set(Some((k + 1, f)));
}
});
}
pub(super) fn note_forget() {
COUNTS.with(|c| {
if let Some((k, f)) = c.get() {
c.set(Some((k, f + 1)));
}
});
}
}
#[cfg(all(test, unix))]
#[path = "child_drop_reaped_tests.rs"]
mod child_drop_reaped_tests;
#[cfg(all(test, target_os = "linux"))]
#[path = "child/pid_reuse_tests.rs"]
mod pid_reuse_tests;
#[cfg(all(test, unix))]
#[path = "child/armed_drop_tests.rs"]
mod armed_drop_tests;
#[cfg(all(test, target_os = "linux"))]
#[path = "child/failed_spawn_drain_tests.rs"]
mod failed_spawn_drain_tests;
#[cfg(all(test, unix))]
#[path = "child/foreign_reap_tree_tests.rs"]
mod foreign_reap_tree_tests;
#[cfg(all(test, unix))]
#[path = "child/foreign_reap_after_look_tests.rs"]
mod foreign_reap_after_look_tests;
#[cfg(all(test, unix))]
#[path = "child/root_state_tests.rs"]
mod root_state_tests;
#[cfg(all(test, target_os = "linux"))]
#[path = "child/group_route_tests.rs"]
mod group_route_tests;
#[cfg(all(test, target_os = "linux"))]
#[path = "child/group_exact_tests.rs"]
mod group_exact_tests;
#[cfg(all(test, target_os = "linux"))]
#[path = "child/drop_group_exact_tests.rs"]
mod drop_group_exact_tests;
#[cfg(all(test, target_os = "linux"))]
#[path = "child/forget_pidfd_tests.rs"]
mod forget_pidfd_tests;
#[cfg(all(test, unix))]
#[path = "child/drop_report_tests.rs"]
mod drop_report_tests;
#[cfg(all(test, target_os = "macos"))]
#[path = "child/unpinned_public_tests.rs"]
mod unpinned_public_tests;
#[cfg(all(test, target_os = "macos"))]
#[path = "child/unpinned_graceful_tests.rs"]
mod unpinned_graceful_tests;
#[cfg(all(test, windows))]
#[path = "child/windows_signal_tests.rs"]
mod windows_signal_tests;
#[cfg(all(test, windows))]
#[path = "child/windows_teardown_tests.rs"]
mod windows_teardown_tests;
#[cfg(all(test, windows))]
#[path = "child/disarm_refused_tests.rs"]
mod disarm_refused_tests;
#[cfg(all(test, windows))]
#[path = "child/pipe_mode_tests.rs"]
mod pipe_mode_tests;
#[cfg(all(test, any(target_os = "linux", target_os = "macos")))]
#[path = "child/bypass_drop_tests.rs"]
mod bypass_drop_tests;
#[cfg(all(test, any(target_os = "linux", target_os = "macos")))]
#[path = "child/drop_fate_tests.rs"]
mod drop_fate_tests;
#[cfg(all(test, target_os = "macos"))]
#[path = "child/macos_kill_tests.rs"]
mod macos_kill_tests;
#[cfg(all(test, unix))]
#[path = "child/front_kill_tests.rs"]
mod front_kill_tests;
#[cfg(all(test, target_os = "linux"))]
#[path = "child/front_cgroup_tests.rs"]
mod front_cgroup_tests;
#[cfg(test)]
#[path = "child_pipe_conversion_tests.rs"]
mod child_pipe_conversion_tests;
#[cfg(test)]
#[path = "child_reap_tests.rs"]
mod child_reap_tests;
#[cfg(test)]
#[path = "child_wait_tree_tests.rs"]
mod child_wait_tree_tests;
#[cfg(all(test, target_os = "linux"))]
#[path = "child_openat2_refused_drop_tests.rs"]
mod child_openat2_refused_drop_tests;
#[cfg(all(test, target_os = "linux"))]
impl Child {
pub(crate) fn leaf_path_for_test(&self) -> Option<std::path::PathBuf> {
match &self.os.attached {
crate::containment::Attached::Cgroup(leaf) => Some(leaf.path().to_path_buf()),
_ => None,
}
}
}
#[cfg(all(test, windows))]
impl Child {
pub(crate) fn install_wait_observer(
&mut self,
started: ::tokio::sync::oneshot::Sender<()>,
outcome: ::tokio::sync::oneshot::Sender<crate::child::spawn::windows_raw::WaitOutcome>,
) {
self.proc_mut().install_wait_observer(started, outcome);
}
}
impl Drop for Child {
fn drop(&mut self) {
_ = self.tear_down(TeardownCaller::Drop);
}
}
impl Child {
pub(crate) fn tear_down_now(&mut self, caller: TeardownCaller) -> crate::error::ChildFate {
let fate = self.tear_down(caller);
self.kill_on_drop = false;
fate
}
pub(crate) async fn tear_down_awaiting(&mut self) -> crate::error::ChildFate {
let teardown = self.signal_for_teardown(TeardownCaller::FailedRun);
self.kill_on_drop = false;
match teardown {
Teardown::Done(fate) => fate,
#[cfg(unix)]
Teardown::Waits(signalled) => {
let mut reaping = Reaping {
child: self,
signalled: Some(signalled),
};
let signalled = reaping.signalled.as_mut().expect("taken only once the reap is over");
let pid = signalled.os.pid();
if signalled.signals.settle == Settle::ReapAndDrain {
if let Err(e) = reap_killed_root_awaiting(self.id, &mut signalled.os, &mut signalled.signals).await
{
log::warn!(
"async child {pid}: its exit cannot be watched ({e}); the teardown reaps it on this \
thread, blocking"
);
let signalled = reaping.signalled.take().expect("taken only here before the drop");
return self.settle(signalled);
}
}
let signalled = reaping.signalled.take().expect("taken only here before the drop");
let (os, fate, tree_failed) = self.report(*signalled);
os.release_after_drain_awaiting(pid, tree_failed).await;
fate
}
}
}
fn tear_down(&mut self, caller: TeardownCaller) -> crate::error::ChildFate {
match self.signal_for_teardown(caller) {
Teardown::Done(fate) => fate,
#[cfg(unix)]
Teardown::Waits(signalled) => self.settle(signalled),
}
}
#[cfg(unix)]
fn settle(&self, mut signalled: Box<Signalled>) -> crate::error::ChildFate {
let pid = signalled.os.pid();
let mut late = LateWarn::new(pid);
if signalled.signals.settle == Settle::ReapAndDrain {
reap_killed_root(pid, self.id, &mut signalled.os, &mut signalled.signals, &mut late);
}
let (os, fate, tree_failed) = self.report(*signalled);
os.release_after_drain(&mut late, tree_failed);
fate
}
fn signal_for_teardown(&mut self, caller: TeardownCaller) -> Teardown {
use crate::error::ChildFate;
let bounded = crate::bounded::Section::enter();
let mut os = std::mem::take(&mut self.os);
let Some(pid) = os.proc.as_ref().map(ProcSource::pid) else {
drop(bounded);
return Teardown::Done(ChildFate::Reaped);
};
let own_reap = os.proc.as_ref().is_none_or(|proc| proc.is_reaped());
#[cfg(unix)]
let forgotten = os.proc.as_ref().and_then(|proc| proc.forgotten_fate(self.id));
#[cfg(unix)]
let gate = self.kill_on_drop.then(|| kill_gate(self.front, &os, pid));
#[cfg(unix)]
let view = crate::containment::DropView::read(
caller,
pid,
self.id,
|| {
os.proc
.as_ref()
.map_or(crate::signal::RootState::Reaped { own: false }, ProcSource::state)
},
&self.tree_killed,
);
let mut signals = DropSignals::new(ChildFate::Running { id: self.id });
#[cfg(unix)]
let mut front_left = None;
if self.kill_on_drop {
#[cfg(unix)]
match gate.expect("an armed drop reads the gate") {
crate::elevation::front::Gate::Closed(unkillable) => front_left = Some(unkillable),
gate => {
let cgroup_front = matches!(gate, crate::elevation::front::Gate::CgroupOnly)
.then_some(self.front)
.flatten();
signals = signal_on_drop(pid, self.id, &view, cgroup_front, &mut os);
}
}
#[cfg(not(unix))]
{
signals = signal_on_drop(self.id, &self.tree_killed, &mut os);
}
}
#[cfg(unix)]
if !own_reap && signals.forgot.is_none() {
if let Some(proc) = os.proc.as_mut() {
signals.forgot = proc.forget_for(&view);
if let Some(forgot) = &signals.forgot {
log::debug!(
"async child {} cannot be shown to be ours (reaped outside its handle, unknown, or unpinned); \
dropping it would reap by that number, so it was forgotten",
pid
);
if forgot.reaped_elsewhere() && signals.fate != ChildFate::Killed {
signals.fate = ChildFate::Gone;
}
}
}
}
signals.name_refused_kill(pid, self.id, &os);
let signalled = Signalled {
os,
signals,
#[cfg(not(unix))]
caller,
own_reap,
#[cfg(unix)]
forgotten,
#[cfg(unix)]
view,
#[cfg(unix)]
front_left,
};
#[cfg(unix)]
if self.kill_on_drop && signalled.signals.settle != Settle::Nothing {
drop(bounded);
return Teardown::Waits(Box::new(signalled));
}
let (os, fate, _) = self.report(signalled);
os.release_without_waiting();
drop(bounded);
Teardown::Done(fate)
}
fn report(&self, signalled: Signalled) -> (OsResources, crate::error::ChildFate, bool) {
use crate::error::ChildFate;
let Signalled {
os,
mut signals,
#[cfg(not(unix))]
caller,
own_reap,
#[cfg(unix)]
forgotten,
#[cfg(unix)]
view,
#[cfg(unix)]
front_left,
} = signalled;
if own_reap {
#[cfg(unix)]
{
signals.fate = match forgotten {
Some(ChildFate::Running { .. }) if matches!(signals.fate, ChildFate::Killed | ChildFate::Gone) => {
signals.fate
}
forgotten => forgotten.unwrap_or(ChildFate::Reaped),
};
}
#[cfg(not(unix))]
{
signals.fate = ChildFate::Reaped;
}
}
let tree = signals.tree.take().and_then(|kill| {
os.attached
.settle_for_drop(&self.tree_killed, kill, signals.fate.not_running())
});
#[cfg(unix)]
let tree_failed = tree.is_some();
#[cfg(unix)]
{
let mut report = crate::child::drop_report::DropReport::new(&view);
report.front = front_left.as_ref();
report.skipped = signals.skipped;
report.forgot = signals.forgot;
report.tree = tree;
report.left = signals.left;
report.emit(&self.reported);
}
#[cfg(not(unix))]
let tree_failed = false;
#[cfg(not(unix))]
if let Some(tree) = tree {
signals.left.insert(0, tree);
}
#[cfg(not(unix))]
if !signals.left.is_empty() {
log::warn!("{}: {}", caller.label(), signals.left.join("; "));
}
(os, signals.fate, tree_failed)
}
}
enum Teardown {
Done(crate::error::ChildFate),
#[cfg(unix)]
Waits(Box<Signalled>),
}
#[cfg(unix)]
struct Reaping<'a> {
child: &'a Child,
signalled: Option<Box<Signalled>>,
}
#[cfg(unix)]
impl Drop for Reaping<'_> {
fn drop(&mut self) {
if let Some(signalled) = self.signalled.take() {
if !std::thread::panicking() {
_ = self.child.settle(signalled);
}
}
}
}
struct Signalled {
os: OsResources,
signals: DropSignals,
#[cfg(not(unix))]
caller: TeardownCaller,
own_reap: bool,
#[cfg(unix)]
forgotten: Option<crate::error::ChildFate>,
#[cfg(unix)]
view: crate::containment::DropView,
#[cfg(unix)]
front_left: Option<Error>,
}
#[cfg_attr(
all(test, target_os = "macos"),
allow(dead_code, reason = "a test opts in with its own threshold off Linux")
)]
const LATE: std::time::Duration = std::time::Duration::from_secs(1);
pub(crate) fn slow_teardown_after() -> Option<std::time::Duration> {
#[cfg(test)]
return fault::slow_teardown_after();
#[cfg(not(test))]
Some(LATE)
}
#[cfg(unix)]
struct LateWarn {
pid: u32,
due: Option<(std::time::Instant, std::time::Duration)>,
warned: bool,
}
#[cfg(unix)]
impl LateWarn {
fn new(pid: u32) -> LateWarn {
LateWarn {
pid,
due: slow_teardown_after().map(|after| (crate::wait::now() + after, after)),
warned: false,
}
}
fn due(&self) -> Option<Due> {
self.due
.filter(|_| !self.warned)
.map(|(until, after)| Due { until, after })
}
fn warn(&mut self, what: &str) {
let Some((_, after)) = self.due else {
return;
};
if std::mem::replace(&mut self.warned, true) {
return;
}
log::warn!(
"Child::drop: async child {} {what} {after:?} into this wait; still waiting: the drop blocks \
until the child is reaped and its tree has drained (call kill() and wait().await, and \
wait_tree().await for a tree, before dropping, to wait without blocking)",
self.pid,
);
}
}
#[cfg(target_os = "linux")]
impl crate::containment::cgroup::TeardownWarn for LateWarn {
fn due(&self) -> Option<Due> {
LateWarn::due(self)
}
fn warn(&mut self, leaf: &std::path::Path) {
LateWarn::warn(
self,
&format!("has a cgroup leaf {} that has not drained", leaf.display()),
);
}
}
#[cfg(unix)]
fn reap_killed_root(
pid: u32,
id: Option<ProcessId>,
os: &mut OsResources,
signals: &mut DropSignals,
late: &mut LateWarn,
) {
let Some(proc) = os.proc.as_mut() else {
return;
};
if proc.is_reaped() {
return;
}
let (waited, cause) = wait_warning(
&mut *proc,
late.due(),
|proc, until| {
#[cfg(test)]
fault::run_before_reap_look();
proc.exit_visible_by(pid, until)
},
|_| late.warn("has not been reaped"),
|proc| proc.wait_and_reap_caused(pid, log::Level::Debug),
);
match waited {
Waited::Exited => signals.fate = proc.collect_exit(id),
_ => signals.forgot = proc.forget_for_wait(waited, cause),
}
}
#[cfg(unix)]
async fn reap_killed_root_awaiting(
id: Option<ProcessId>,
os: &mut OsResources,
signals: &mut DropSignals,
) -> Result<(), Error> {
let Some(proc) = os.proc.as_mut() else {
return Ok(());
};
if proc.is_reaped() {
return Ok(());
}
let (waited, cause) = proc.wait_and_reap_awaiting().await?;
match waited {
Waited::Exited => signals.fate = proc.collect_exit(id),
_ => signals.forgot = proc.forget_for_wait(waited, cause),
}
Ok(())
}
#[cfg(unix)]
fn kill_gate(
front: Option<crate::elevation::front::Front>,
os: &OsResources,
pid: u32,
) -> crate::elevation::front::Gate {
crate::elevation::front::kill_gate(
front,
pid,
|| os.proc.as_ref().map_or(Ok(false), ProcSource::is_running),
|| {
os.attached
.kill_reaches_across_credentials(pid, os.proc.as_ref().and_then(ProcSource::pidfd))
},
)
}
#[cfg(unix)]
fn cgroup_kill_reached(front: Option<crate::elevation::front::Front>, os: &OsResources, pid: u32) -> Result<(), Error> {
crate::elevation::front::cgroup_kill_reached(
front,
pid,
|| {
os.proc
.as_ref()
.map_or(Ok(false), ProcSource::is_running)
.map(|running| !running)
},
|| {
os.attached
.cgroup_names(pid, os.proc.as_ref().and_then(ProcSource::pidfd))
},
)
}
struct DropSignals {
fate: crate::error::ChildFate,
#[cfg(unix)]
skipped: Option<String>,
#[cfg(unix)]
forgot: Option<crate::child::drop_report::Forgot>,
tree: Option<TreeKillOutcome>,
left: Vec<String>,
refused_kill: bool,
#[cfg(unix)]
settle: Settle,
}
#[cfg(unix)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Settle {
Nothing,
Drain,
ReapAndDrain,
}
impl DropSignals {
fn new(fate: crate::error::ChildFate) -> DropSignals {
DropSignals {
fate,
#[cfg(unix)]
settle: Settle::Nothing,
#[cfg(unix)]
skipped: None,
#[cfg(unix)]
forgot: None,
tree: None,
left: Vec::new(),
refused_kill: false,
}
}
fn name_refused_kill(&mut self, pid: u32, id: Option<ProcessId>, os: &OsResources) {
use crate::child::owned::teardown::LEAVING_RUNNING;
if !self.refused_kill {
return;
}
#[cfg(unix)]
let tail = match os.proc.as_ref().and_then(|proc| proc.forgotten_fate(id)) {
Some(crate::error::ChildFate::Gone) => "; it is already gone",
Some(_) => LEAVING_RUNNING,
None => "; leaving it running",
};
#[cfg(not(unix))]
let tail = {
_ = (os, id);
LEAVING_RUNNING
};
self.left
.push(format!("async child {pid} could not be terminated on drop{tail}"));
}
}
fn signal_on_drop(
#[cfg(unix)] pid: u32,
id: Option<ProcessId>,
#[cfg(unix)] view: &crate::containment::DropView,
#[cfg(unix)] cgroup_front: Option<crate::elevation::front::Front>,
#[cfg(not(unix))] tree_killed: &crate::containment::TreeKilled,
os: &mut OsResources,
) -> DropSignals {
use crate::error::ChildFate;
#[allow(unused_mut, reason = "only the Unix signals collect anything")]
let mut signals = DropSignals::new(ChildFate::Unknown);
#[cfg(unix)]
let tree = {
let proc = os.proc.as_ref();
let check = || {
crate::child::tree_call::group_number_holds(
pid,
proc.map_or(crate::signal::RootState::Reaped { own: false }, ProcSource::state),
)
};
let kill = os.attached.hard_kill_for_drop(
view,
&crate::containment::GroupRoot::new(proc.and_then(ProcSource::pidfd), &check),
);
signals.skipped = kill.left_undone(view);
kill
};
#[cfg(not(unix))]
let tree = {
_ = tree_killed;
os.attached.hard_kill(&crate::containment::GroupRoot::none())
};
#[cfg(unix)]
let front_gate = cgroup_front.map(|front| (front, tree.incomplete()));
signals.tree = Some(tree);
#[cfg(unix)]
if view.leaves_root_alone() {
signals.fate = ChildFate::Gone;
signals.settle = Settle::Drain;
return signals;
}
#[cfg(not(unix))]
if os.proc.as_ref().is_none_or(|proc| proc.is_reaped()) {
signals.fate = ChildFate::Reaped;
return signals;
}
#[cfg(unix)]
if let Some((front, incomplete)) = front_gate {
let reached = match incomplete {
None => cgroup_kill_reached(Some(front), os, pid).map_err(|e| e.to_string()),
Some(failure) => Err(failure),
};
match reached {
Ok(()) => {
signals.fate = ChildFate::Killed;
signals.settle = Settle::ReapAndDrain;
}
Err(e) => {
signals.left.push(format!(
"{}: its cgroup kill is not shown to have reached it ({e}); the front is killed through its \
cgroup if it is still in it; cosca does not wait for it, and tokio reaps it once it exits",
crate::elevation::front::front_named(Some(pid))
));
signals.fate = ChildFate::Running { id };
}
}
return signals;
}
let Some(proc) = os.proc.as_mut() else {
return signals;
};
#[cfg(test)]
let killed = if fault::take_force_kill_failure() {
Err(fault::forced_kill_failure())
} else {
proc.signal(Sig::Kill)
};
#[cfg(not(test))]
let killed = proc.signal(Sig::Kill);
#[cfg(all(test, unix))]
drop_fault::note_root_kill();
match killed {
Ok(Sent::Gone) => {
signals.fate = ChildFate::Gone;
#[cfg(unix)]
{
signals.settle = Settle::Drain;
}
return signals;
}
Ok(Sent::Unverified) => {
signals.fate = ChildFate::Running { id };
return signals;
}
_ => {}
}
if killed.is_err() {
#[cfg(unix)]
{
signals.forgot = proc.forget_for(view);
if let Some(forgot) = &signals.forgot {
signals.fate = if forgot.reaped_elsewhere() {
ChildFate::Gone
} else {
ChildFate::Running { id }
};
return signals;
}
if let Some(fate) = proc.forgotten_fate(id) {
debug_assert!(
matches!(fate, ChildFate::Running { .. }),
"only an unproven backend's signal fails"
);
signals.left.push(format!(
"async child {pid} could not be terminated on drop{}",
crate::child::owned::teardown::LEAVING_RUNNING
));
signals.fate = fate;
return signals;
}
}
if proc.is_reaped() {
signals.fate = ChildFate::Reaped;
return signals;
}
let looked = proc.try_wait();
signals.refused_kill = !matches!(looked, Ok(Some(_)));
signals.fate = crate::child::spawn::fate_of_a_look(looked.map_err(|e| e.raw_os_error()), id);
return signals;
}
signals.fate = ChildFate::Killed;
#[cfg(unix)]
{
signals.settle = Settle::ReapAndDrain;
}
signals
}
#[cfg(all(test, unix))]
fn exit_status_of(info: &libc::siginfo_t) -> std::process::ExitStatus {
exit_status_from_parts(info.si_code, unsafe { info.si_status() })
}
#[cfg(all(test, unix))]
fn exit_status_from_parts(si_code: libc::c_int, si_status: libc::c_int) -> std::process::ExitStatus {
use std::os::unix::process::ExitStatusExt as _;
let raw = match si_code {
libc::CLD_EXITED => si_status << 8,
libc::CLD_DUMPED => si_status | 0x80,
_ => si_status, };
std::process::ExitStatus::from_raw(raw)
}
#[cfg(test)]
pub(crate) mod fault {
use std::cell::Cell;
use crate::error::Error;
thread_local! {
static FORCE_KILL_FAILURE: Cell<bool> = const { Cell::new(false) };
static PEND_AWAITED_REAP: Cell<bool> = const { Cell::new(false) };
static FAIL_REAP_WATCH: Cell<bool> = const { Cell::new(false) };
static FAIL_DRAIN_WATCH: Cell<bool> = const { Cell::new(false) };
static FAIL_HANDLE_WAIT: Cell<bool> = const { Cell::new(false) };
static REAP_PARKED: crate::oneshot_hook::OneShotHook = const { crate::oneshot_hook::OneShotHook::new() };
static BEFORE_REAP_LOOK: crate::oneshot_hook::OneShotHook = const { crate::oneshot_hook::OneShotHook::new() };
static RELEASES: Cell<usize> = const { Cell::new(0) };
static BACKEND_DROPS: Cell<usize> = const { Cell::new(0) };
static SLOW_TEARDOWN_AFTER: Cell<Option<std::time::Duration>> = const { Cell::new(None) };
}
#[cfg(any(target_os = "linux", windows))]
pub(crate) fn warn_slow_teardowns() -> WarnSlowTeardowns {
warn_slow_teardowns_after(super::LATE)
}
pub(crate) fn warn_slow_teardowns_after(after: std::time::Duration) -> WarnSlowTeardowns {
SLOW_TEARDOWN_AFTER.with(|w| w.set(Some(after)));
WarnSlowTeardowns(())
}
#[must_use = "the warn is off again as soon as the guard is dropped"]
pub(crate) struct WarnSlowTeardowns(());
impl Drop for WarnSlowTeardowns {
fn drop(&mut self) {
SLOW_TEARDOWN_AFTER.with(|w| w.set(None));
}
}
pub(super) fn slow_teardown_after() -> Option<std::time::Duration> {
SLOW_TEARDOWN_AFTER.with(Cell::get)
}
pub(crate) fn count_backend_drops() -> BackendDropCount {
BACKEND_DROPS.with(|d| d.set(0));
BackendDropCount(())
}
#[must_use = "the count is zeroed as soon as the guard is dropped"]
pub(crate) struct BackendDropCount(());
impl BackendDropCount {
pub(crate) fn get(&self) -> usize {
BACKEND_DROPS.with(Cell::get)
}
}
impl Drop for BackendDropCount {
fn drop(&mut self) {
BACKEND_DROPS.with(|d| d.set(0));
}
}
pub(crate) struct CountedDrop {
pub(crate) _child: ::tokio::process::Child,
}
impl Drop for CountedDrop {
fn drop(&mut self) {
note_backend_drop();
}
}
fn note_backend_drop() {
BACKEND_DROPS.with(|d| d.set(d.get() + 1));
}
pub(crate) fn count_releases() -> ReleaseCount {
RELEASES.with(|r| r.set(0));
ReleaseCount(())
}
#[must_use = "the count is zeroed as soon as the guard is dropped"]
pub(crate) struct ReleaseCount(());
impl ReleaseCount {
pub(crate) fn get(&self) -> usize {
RELEASES.with(Cell::get)
}
}
impl Drop for ReleaseCount {
fn drop(&mut self) {
RELEASES.with(|r| r.set(0));
}
}
pub(super) fn note_release() {
RELEASES.with(|r| r.set(r.get() + 1));
}
pub(crate) fn force_kill_failure() -> KillFailureGuard {
FORCE_KILL_FAILURE.with(|f| f.set(true));
KillFailureGuard(())
}
#[must_use = "the seam is cleared as soon as the guard is dropped"]
pub(crate) struct KillFailureGuard(());
impl Drop for KillFailureGuard {
fn drop(&mut self) {
FORCE_KILL_FAILURE.with(|f| f.set(false));
}
}
pub(super) fn take_force_kill_failure() -> bool {
FORCE_KILL_FAILURE.with(|f| f.replace(false))
}
pub(super) fn forced_kill_failure() -> Error {
Error::Io(std::io::Error::other("forced kill failure (test seam)"))
}
#[cfg(target_os = "linux")]
pub(crate) fn pend_awaited_reap() -> PendAwaitedReap {
PEND_AWAITED_REAP.with(|f| f.set(true));
PendAwaitedReap(())
}
#[cfg(target_os = "linux")]
#[must_use = "the seam is cleared as soon as the guard is dropped"]
pub(crate) struct PendAwaitedReap(());
#[cfg(target_os = "linux")]
impl PendAwaitedReap {
pub(crate) fn taken(&self) -> bool {
!PEND_AWAITED_REAP.with(Cell::get)
}
}
#[cfg(target_os = "linux")]
impl Drop for PendAwaitedReap {
fn drop(&mut self) {
PEND_AWAITED_REAP.with(|f| f.set(false));
}
}
#[cfg(unix)]
pub(super) fn take_pend_awaited_reap() -> bool {
PEND_AWAITED_REAP.with(|f| f.replace(false))
}
#[cfg(windows)]
pub(crate) fn fail_handle_wait() -> FailHandleWait {
FAIL_HANDLE_WAIT.with(|f| f.set(true));
FailHandleWait(())
}
#[cfg(windows)]
#[must_use = "the seam is cleared as soon as the guard is dropped"]
pub(crate) struct FailHandleWait(());
#[cfg(windows)]
impl FailHandleWait {
pub(crate) fn taken(&self) -> bool {
!FAIL_HANDLE_WAIT.with(Cell::get)
}
}
#[cfg(windows)]
impl Drop for FailHandleWait {
fn drop(&mut self) {
FAIL_HANDLE_WAIT.with(|f| f.set(false));
}
}
#[cfg(windows)]
pub(super) fn take_fail_handle_wait() -> bool {
FAIL_HANDLE_WAIT.with(|f| f.replace(false))
}
#[cfg(unix)]
pub(crate) fn fail_reap_watch() -> FailReapWatch {
FAIL_REAP_WATCH.with(|f| f.set(true));
FailReapWatch(())
}
#[cfg(unix)]
#[must_use = "the seam is cleared as soon as the guard is dropped"]
pub(crate) struct FailReapWatch(());
#[cfg(unix)]
impl Drop for FailReapWatch {
fn drop(&mut self) {
FAIL_REAP_WATCH.with(|f| f.set(false));
}
}
#[cfg(unix)]
pub(crate) fn take_fail_reap_watch() -> bool {
FAIL_REAP_WATCH.with(|f| f.replace(false))
}
#[cfg(target_os = "linux")]
pub(crate) fn fail_drain_watch() -> FailDrainWatch {
FAIL_DRAIN_WATCH.with(|f| f.set(true));
FailDrainWatch(())
}
#[cfg(target_os = "linux")]
#[must_use = "the seam is cleared as soon as the guard is dropped"]
pub(crate) struct FailDrainWatch(());
#[cfg(target_os = "linux")]
impl Drop for FailDrainWatch {
fn drop(&mut self) {
FAIL_DRAIN_WATCH.with(|f| f.set(false));
}
}
#[cfg(target_os = "linux")]
pub(crate) fn take_fail_drain_watch() -> bool {
FAIL_DRAIN_WATCH.with(|f| f.replace(false))
}
#[cfg(unix)]
pub(crate) fn set_reap_parked(hook: impl FnOnce() + 'static) -> crate::oneshot_hook::Armed {
crate::oneshot_hook::arm(&REAP_PARKED, hook)
}
#[cfg(unix)]
pub(crate) fn run_reap_parked() {
crate::oneshot_hook::fire(&REAP_PARKED);
}
#[cfg(target_os = "macos")]
pub(crate) fn set_before_reap_look(hook: impl FnOnce() + 'static) -> crate::oneshot_hook::Armed {
crate::oneshot_hook::arm(&BEFORE_REAP_LOOK, hook)
}
#[cfg(unix)]
pub(super) fn run_before_reap_look() {
crate::oneshot_hook::fire(&BEFORE_REAP_LOOK);
}
}
#[cfg(all(test, target_os = "macos"))]
#[path = "child/identity_macos_tests.rs"]
mod identity_macos_tests;
#[cfg(all(test, target_os = "macos"))]
#[path = "child/late_report_tests.rs"]
mod late_report_tests;