#[path = "child/graceful.rs"]
mod graceful;
#[path = "child/suspended.rs"]
mod suspended;
pub use suspended::SuspendedChild;
#[path = "child/proc_source.rs"]
mod proc_source;
pub(crate) use proc_source::ProcSource;
#[cfg(any(unix, test))]
pub(crate) use proc_source::Waited;
use std::collections::BTreeMap;
use std::process::ExitStatus;
#[cfg(unix)]
use crate::child::ParentEnd;
use crate::containment::{Attached, Containment};
use crate::error::Error;
use crate::identity::ProcessId;
use crate::signal::{Sent, Sig};
use crate::stdio::Fd;
#[cfg(unix)]
pub(super) type FdPipes = BTreeMap<Fd, ParentEnd>;
#[cfg(windows)]
pub(super) type FdPipes = BTreeMap<Fd, super::stdio::OwnedStd>;
const PROC_TAKEN: &str = "the async child's process backend is taken only by Drop";
#[derive(Debug, Default)]
pub(crate) struct OsResources {
pub(crate) proc: Option<ProcSource>,
pub(crate) attached: Attached,
pub(crate) pipes: FdPipes,
pub(crate) owned_std: BTreeMap<Fd, super::stdio::OwnedStd>,
}
impl OsResources {
pub(crate) fn proc_mut(&mut self) -> &mut ProcSource {
self.proc.as_mut().expect(PROC_TAKEN)
}
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();
}
}
#[derive(Debug)]
pub struct Child {
os: OsResources,
id: 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: ProcessId,
kill_on_drop: bool,
attachment: crate::containment::Attachment,
pipes: FdPipes,
owned_std: BTreeMap<Fd, super::stdio::OwnedStd>,
) -> Child {
Child {
os: OsResources {
proc: Some(proc),
attached: attachment.attached,
pipes,
owned_std,
},
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(unix)]
pub(super) fn tree_killed(&self) -> bool {
self.tree_killed.is_set()
}
#[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;
} else {
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()
}
#[cfg(windows)]
pub(super) fn proc(&self) -> &ProcSource {
self.os.proc.as_ref().expect(PROC_TAKEN)
}
pub(super) fn commit_kill_on_drop(&self) {
self.os.attached.honor_kill_on_drop(self.kill_on_drop);
}
#[cfg(unix)]
pub(super) fn kill_tree_members_unless_reaped(
&self,
view: &crate::containment::DropView,
) -> Result<Option<String>, Error> {
self.os
.attached
.hard_kill_marking_unless_reaped(view, &self.tree_killed)
}
#[cfg(unix)]
pub(super) fn read_root_view(&self, label: &str) -> crate::containment::DropView {
crate::containment::DropView::read(
label,
self.id,
|| {
self.os
.proc
.as_ref()
.map_or(crate::signal::RootState::Reaped, ProcSource::state)
},
&self.tree_killed,
)
}
#[cfg(unix)]
pub(super) fn block_until_members_drained(&self) -> Result<(), Error> {
#[cfg(target_os = "linux")]
if matches!(self.os.attached, crate::containment::Attached::Cgroup(_)) {
return self.os.attached.wait_drained(None).map(drop);
}
Ok(())
}
#[cfg(all(test, unix))]
pub(super) fn carries_recyclable_pgid(&self) -> bool {
self.os.attached.carries_recyclable_pgid()
}
#[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.id.pid())
}
#[cfg(unix)]
pub(super) fn cgroup_was_killed(&self) -> bool {
self.tree_killed.is_set()
}
#[cfg(unix)]
pub(super) fn cgroup_not_killed(&self, failure: Option<&str>) -> Error {
crate::elevation::front::cgroup_not_killed_of(self.front, self.id.pid(), failure)
}
#[cfg(unix)]
pub(super) fn cgroup_kill_reached(&self) -> Result<(), Error> {
cgroup_kill_reached(self.front, &self.os, self.id.pid())
}
#[cfg(unix)]
pub(super) fn terminate_gate(&self) -> crate::elevation::front::Gate {
crate::elevation::front::terminate_gate(self.front, self.id.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.id.pid();
let (waited, cause) = self.proc_mut().wait_and_reap_caused(pid, log::Level::Debug);
match waited {
Waited::Exited => {
let id = Some(self.id);
(self.proc_mut().collect_exit(id), None)
}
Waited::Foreign | Waited::Unverified => (
crate::error::ChildFate::Killed,
self.proc_mut().forget_for_wait(waited, cause),
),
}
}
pub fn id(&self) -> ProcessId {
self.id
}
pub fn is_alive(&self) -> crate::identity::Liveness {
self.id.is_alive()
}
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> {
if let Some(owned) = self.take_owned_in(crate::stdio::Fd::STDIN) {
return Some(super::stdio::ChildStdin { inner: owned });
}
self.proc_mut().take_stdin().map(|s| super::stdio::ChildStdin {
inner: super::stdio::InInner::Tokio(s),
})
}
pub fn stdout(&mut self) -> Option<super::stdio::ChildStdout> {
if let Some(owned) = self.take_owned_out(crate::stdio::Fd::STDOUT) {
return Some(super::stdio::ChildStdout { inner: owned });
}
self.proc_mut().take_stdout().map(|s| super::stdio::ChildStdout {
inner: super::stdio::OutInner::Stdout(s),
})
}
pub fn stderr(&mut self) -> Option<super::stdio::ChildStderr> {
if let Some(owned) = self.take_owned_out(crate::stdio::Fd::STDERR) {
return Some(super::stdio::ChildStderr { inner: owned });
}
self.proc_mut().take_stderr().map(|s| super::stdio::ChildStderr {
inner: super::stdio::OutInner::Stderr(s),
})
}
#[cfg(unix)]
fn take_owned_out(&mut self, fd: Fd) -> Option<super::stdio::OutInner> {
use std::os::fd::OwnedFd;
match self.os.owned_std.remove(&fd)? {
ParentEnd::Reader(r) => match ::tokio::net::unix::pipe::Receiver::from_owned_fd(OwnedFd::from(r)) {
Ok(recv) => Some(super::stdio::OutInner::Owned(recv)),
Err(e) => {
log::warn!(
"{fd} merge-target read end dropped: tokio conversion failed ({e}); the child will see EPIPE on writes"
);
None
}
},
end => {
self.os.owned_std.insert(fd, end); None
}
}
}
#[cfg(windows)]
fn take_owned_out(&mut self, fd: Fd) -> Option<super::stdio::OutInner> {
match self.os.owned_std.remove(&fd)? {
super::stdio::OwnedStd::Read(r) => Some(super::stdio::OutInner::Owned(r)),
end => {
self.os.owned_std.insert(fd, end); None
}
}
}
#[cfg(unix)]
fn take_owned_in(&mut self, fd: Fd) -> Option<super::stdio::InInner> {
use std::os::fd::OwnedFd;
match self.os.owned_std.remove(&fd)? {
ParentEnd::Writer(w) => match ::tokio::net::unix::pipe::Sender::from_owned_fd(OwnedFd::from(w)) {
Ok(send) => Some(super::stdio::InInner::Owned(send)),
Err(e) => {
log::warn!(
"{fd} merge-target write end dropped: tokio conversion failed ({e}); the child will see EOF on reads"
);
None
}
},
end => {
self.os.owned_std.insert(fd, end); None
}
}
}
#[cfg(windows)]
fn take_owned_in(&mut self, fd: Fd) -> Option<super::stdio::InInner> {
match self.os.owned_std.remove(&fd)? {
super::stdio::OwnedStd::Write(w) => Some(super::stdio::InInner::Owned(w)),
end => {
self.os.owned_std.insert(fd, end); None
}
}
}
#[cfg(unix)]
pub fn fd_read_end(&mut self, fd: impl Into<crate::stdio::Fd>) -> Option<::tokio::net::unix::pipe::Receiver> {
use std::os::fd::OwnedFd;
let fd = fd.into();
match self.os.pipes.remove(&fd)? {
crate::child::ParentEnd::Reader(r) => {
match ::tokio::net::unix::pipe::Receiver::from_owned_fd(OwnedFd::from(r)) {
Ok(recv) => Some(recv),
Err(e) => {
log::warn!(
"{fd} read end dropped: tokio conversion failed ({e}); the child will see EPIPE on writes"
);
None
}
}
}
end => {
self.os.pipes.insert(fd, end); None
}
}
}
#[cfg(unix)]
pub fn fd_write_end(&mut self, fd: impl Into<crate::stdio::Fd>) -> Option<::tokio::net::unix::pipe::Sender> {
use std::os::fd::OwnedFd;
let fd = fd.into();
match self.os.pipes.remove(&fd)? {
crate::child::ParentEnd::Writer(w) => {
match ::tokio::net::unix::pipe::Sender::from_owned_fd(OwnedFd::from(w)) {
Ok(send) => Some(send),
Err(e) => {
log::warn!(
"{fd} write end dropped: tokio conversion failed ({e}); the child will see EOF on reads"
);
None
}
}
}
end => {
self.os.pipes.insert(fd, end);
None
}
}
}
#[cfg(windows)]
pub fn fd_read_end(&mut self, fd: impl Into<Fd>) -> Option<super::stdio::ChildStdout> {
let fd = fd.into();
match self.os.pipes.remove(&fd)? {
super::stdio::OwnedStd::Read(r) => Some(super::stdio::ChildStdout {
inner: super::stdio::OutInner::Owned(r),
}),
end => {
self.os.pipes.insert(fd, end); None
}
}
}
#[cfg(windows)]
pub fn fd_write_end(&mut self, fd: impl Into<Fd>) -> Option<super::stdio::ChildStdin> {
let fd = fd.into();
match self.os.pipes.remove(&fd)? {
super::stdio::OwnedStd::Write(w) => Some(super::stdio::ChildStdin {
inner: super::stdio::InInner::Owned(w),
}),
end => {
self.os.pipes.insert(fd, end); None
}
}
}
#[cfg(windows)]
pub fn test_job_handle_contains_self(&self) -> bool {
self.test_job_handle_contains(self.id.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) => Some(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);
}
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(
#[cfg(unix)]
gate,
)
}
pub(crate) fn kill_sent_gated(&mut self, #[cfg(unix)] gate: crate::elevation::front::Gate) -> Result<Sent, Error> {
let sent = self.signal_gated(
#[cfg(unix)]
gate,
);
if matches!(sent, Ok(Sent::Gone | Sent::Unverified)) {
#[cfg(unix)]
self.proc_mut().forget_if_foreign();
}
sent
}
pub(crate) fn signal_gated(&mut self, #[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 => {
self.os
.attached
.hard_kill_marking(&self.tree_killed)
.map_err(|e| crate::elevation::front::cgroup_kill_failed(self.front, self.id.pid(), e))?;
cgroup_kill_reached(self.front, &self.os, self.id.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.id.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(None)
}
pub(crate) fn kill_tree_after(&mut self, earlier: Option<&str>) -> Result<(), Error> {
#[cfg(not(target_os = "macos"))]
let _ = earlier;
self.require_contained()?;
#[cfg(unix)]
let front = match self.kill_gate() {
crate::elevation::front::Gate::Closed(unkillable) => return Err(unkillable),
crate::elevation::front::Gate::Open => None,
crate::elevation::front::Gate::Exited => Some(false),
crate::elevation::front::Gate::CgroupOnly => Some(true),
};
#[cfg(target_os = "macos")]
if let Some(result) =
self.tree_signal_untrusted(crate::containment::dispatch::TreeSignal::Kill, "kill_tree", earlier)
{
return result;
}
#[cfg(unix)]
debug_assert!(
!self.os.attached.carries_recyclable_pgid() || {
let now = ProcessId::of(self.id.pid());
let now_liveness = match now {
crate::identity::Resolved::Found(id) => id.is_alive(),
crate::identity::Resolved::Gone | crate::identity::Resolved::Unknown => {
crate::identity::Liveness::Unknown
}
};
!crate::child::root_pid_was_recycled(self.id, now, now_liveness)
},
"kill_tree/terminate_tree called after the contained root's pid ({}) was reaped and \
recycled onto a different, live process; a pgid-based mechanism would now signal an \
unrelated process group",
self.id.pid()
);
let group_result = self.os.attached.hard_kill_marking(&self.tree_killed);
if self.os.attached.hard_kill_refused_to_walk(&group_result) {
return group_result;
}
#[cfg(unix)]
if let Some(in_cgroup) = front {
return match group_result {
Ok(()) if in_cgroup => cgroup_kill_reached(self.front, &self.os, self.id.pid()),
Err(e) if in_cgroup => Err(crate::elevation::front::cgroup_kill_failed(
self.front,
self.id.pid(),
e,
)),
other => other,
};
}
#[cfg(unix)]
let backstop = if self.root_is_unpinned() {
log::debug!(
"kill_tree({}): launchd holds the root's zombie, so the handle backstop is skipped",
self.id.pid()
);
Ok(())
} else {
self.kill_sent_gated(crate::elevation::front::Gate::Open).map(|_| ())
};
#[cfg(not(unix))]
let backstop = self.kill();
if let (Err(group), Err(bs)) = (&group_result, &backstop) {
log::debug!("kill_tree handle backstop also failed ({bs}); surfacing the group error: {group}");
}
group_result.and(backstop)
}
pub fn terminate_tree(&self) -> Result<(), Error> {
self.require_contained()?;
#[cfg(target_os = "macos")]
if let Some(result) =
self.tree_signal_untrusted(crate::containment::dispatch::TreeSignal::Term, "terminate_tree", None)
{
return result;
}
self.terminate_tree_signalling()
}
fn terminate_tree_signalling(&self) -> Result<(), Error> {
#[cfg(windows)]
if !self.proc().pins_pid() {
return Err(self.unpinned_pid_refusal("terminate_tree"));
}
#[cfg(unix)]
debug_assert!(
!self.os.attached.carries_recyclable_pgid() || {
let now = ProcessId::of(self.id.pid());
let now_liveness = match now {
crate::identity::Resolved::Found(id) => id.is_alive(),
crate::identity::Resolved::Gone | crate::identity::Resolved::Unknown => {
crate::identity::Liveness::Unknown
}
};
!crate::child::root_pid_was_recycled(self.id, now, now_liveness)
},
"kill_tree/terminate_tree called after the contained root's pid ({}) was reaped and \
recycled onto a different, live process; a pgid-based mechanism would now signal an \
unrelated process group",
self.id.pid()
);
self.os.attached.terminate(self.id.pid())
}
#[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.id.pid()
),
source: None,
}
}
#[cfg(unix)]
fn root_state(&self) -> crate::signal::RootState {
self.os
.proc
.as_ref()
.map_or(crate::signal::RootState::Reaped, ProcSource::state)
}
#[cfg(unix)]
pub(super) fn refuse_unpinned(&self, op: &str, earlier: Option<&str>) -> Result<(), Error> {
crate::signal::refuse_unpinned(self.id.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
}
#[cfg(target_os = "macos")]
pub(super) fn tree_signal_untrusted(
&self,
signal: crate::containment::dispatch::TreeSignal,
op: &str,
earlier: Option<&str>,
) -> Option<Result<(), Error>> {
let root = crate::signal::untrusted_root(|| self.root_state())?;
self.os
.attached
.signal_tree_untrusted(signal, &root, self.id.pid(), op, earlier, &self.tree_killed)
}
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) {
self.kill_on_drop = false;
self.os.attached.disarm();
}
}
#[cfg(test)]
#[path = "child_drop_tests.rs"]
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/root_state_tests.rs"]
mod root_state_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, 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(all(test, unix))]
#[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_kill_tree_view_tests.rs"]
mod child_kill_tree_view_tests;
#[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();
}
}
impl Child {
pub(crate) fn tear_down_now(&mut self) -> crate::error::ChildFate {
let fate = self.tear_down();
self.kill_on_drop = false;
fate
}
fn tear_down(&mut self) -> crate::error::ChildFate {
use crate::error::ChildFate;
let _bounded = crate::bounded::Section::enter();
let mut os = std::mem::take(&mut self.os);
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(Some(self.id)));
#[cfg(unix)]
let view = crate::containment::DropView::read(
"Child::drop",
self.id,
|| {
os.proc
.as_ref()
.map_or(crate::signal::RootState::Reaped, ProcSource::state)
},
&self.tree_killed,
);
#[cfg(unix)]
let mut signals = DropSignals::new(ChildFate::Running { id: Some(self.id) });
#[cfg(unix)]
let mut front_left = None;
#[cfg(not(unix))]
let mut signals = DropSignals::new(ChildFate::Running { id: Some(self.id) });
if self.kill_on_drop {
#[cfg(unix)]
match kill_gate(self.front, &os, self.id.pid()) {
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(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",
self.id.pid()
);
if forgot.reaped_elsewhere() && signals.fate != ChildFate::Killed {
signals.fate = ChildFate::Gone;
}
}
}
}
if own_reap {
#[cfg(unix)]
{
signals.fate = forgotten.unwrap_or(ChildFate::Reaped);
}
#[cfg(not(unix))]
{
signals.fate = ChildFate::Reaped;
}
}
#[cfg(unix)]
{
let mut report = crate::child::drop_report::DropReport::new("Child::drop", &view);
report.front = front_left.as_ref();
report.skipped = signals.skipped;
report.forgot = signals.forgot;
report.tree = signals.tree;
report.left = signals.left;
report.emit(&self.reported);
}
#[cfg(not(unix))]
if !signals.left.is_empty() {
log::warn!("Child::drop: {}", signals.left.join("; "));
}
os.release_without_waiting();
signals.fate
}
}
#[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>,
#[cfg(unix)]
tree: Option<String>,
left: Vec<String>,
}
impl DropSignals {
fn new(fate: crate::error::ChildFate) -> DropSignals {
DropSignals {
fate,
#[cfg(unix)]
skipped: None,
#[cfg(unix)]
forgot: None,
#[cfg(unix)]
tree: None,
left: Vec::new(),
}
}
}
fn signal_on_drop(
id: 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);
let pid = id.pid();
#[cfg(unix)]
let tree = {
let kill = os.attached.hard_kill_for_drop(view);
signals.skipped = kill.skipped;
kill.result
};
#[cfg(not(unix))]
let tree = {
_ = tree_killed;
os.attached.hard_kill()
};
if let Err(e) = &tree {
let mut failed = format!("contained-tree teardown did not fully succeed: {e}");
if os.attached.hard_kill_refused_to_walk(&tree) {
failed.push_str("; the root is killed regardless, so its descendants may be orphaned");
}
#[cfg(unix)]
{
signals.tree = Some(failed);
}
#[cfg(not(unix))]
signals.left.push(failed);
}
#[cfg(unix)]
if view.leaves_root_alone() {
signals.fate = ChildFate::Gone;
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) = cgroup_front {
match tree.and_then(|()| cgroup_kill_reached(Some(front), os, pid)) {
Ok(()) => signals.fate = ChildFate::Killed,
Err(e) => {
signals.left.push(format!(
"elevation front pid {pid}: 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"
));
signals.fate = ChildFate::Running { id: Some(id) };
}
}
return signals;
}
let Some(proc) = os.proc.as_mut() else {
return signals;
};
#[cfg(all(test, unix))]
drop_fault::note_root_kill();
#[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);
match killed {
Ok(Sent::Gone) => {
signals.fate = ChildFate::Gone;
return signals;
}
Ok(Sent::Unverified) => {
signals.fate = ChildFate::Running { id: Some(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: Some(id) }
};
return signals;
}
}
if proc.is_reaped() {
signals.fate = ChildFate::Reaped;
return signals;
}
let looked = proc.try_wait();
if !matches!(looked, Ok(Some(_))) {
signals.left.push(format!(
"async child {pid} could not be terminated on drop; leaving it running"
));
}
signals.fate = crate::child::spawn::fate_of_a_look(looked.map_err(|e| e.raw_os_error()), Some(id));
return signals;
}
signals.fate = ChildFate::Killed;
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 RELEASES: Cell<usize> = const { Cell::new(0) };
static BACKEND_DROPS: Cell<usize> = const { Cell::new(0) };
}
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(all(test, target_os = "macos"))]
#[path = "child/identity_macos_tests.rs"]
mod identity_macos_tests;