#[path = "child/graceful.rs"]
mod graceful;
#[path = "child/proc_source.rs"]
mod proc_source;
pub(crate) use proc_source::ProcSource;
#[path = "child/reaper.rs"]
mod reaper;
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::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)
}
}
#[derive(Debug)]
pub struct Child {
os: OsResources,
id: ProcessId,
kill_on_drop: bool,
containment: Containment,
graceful: crate::graceful::GracefulMechanism,
elevation: Option<crate::elevation::ElevationReport>,
}
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,
graceful: attachment.graceful,
elevation: None,
}
}
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(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()
}
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) {
let pid = self.id.pid();
self.proc_mut().wait_and_reap(pid);
}
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) => {
debug_assert!(false, "own pipe end failed tokio conversion: {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) => {
debug_assert!(false, "own pipe end failed tokio conversion: {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) => {
debug_assert!(false, "own pipe end failed tokio conversion: {e}");
log::warn!("fd {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) => {
debug_assert!(false, "own pipe end failed tokio conversion: {e}");
log::warn!(
"fd {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 {
crate::containment::windows::job_contains_pid(&self.os.attached, self.id.pid())
}
pub async fn wait(&mut self) -> Result<ExitStatus, 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> {
match self.proc_mut().start_kill() {
Err(Error::Io(e)) => Err(crate::elevation::map_elevated_kill_error(e, self.is_elevated_wrapper())),
other => other,
}
}
pub fn kill_tree(&mut self) -> Result<(), Error> {
self.require_contained()?;
#[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();
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(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,
}
}
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 = crate::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(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, 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) {
if !self.kill_on_drop {
return;
}
#[cfg(test)]
let probe = reaper::test_probe::take();
#[cfg(test)]
if let Some(p) = probe.as_ref() {
let _ = p.entered.send(std::thread::current().id());
}
let tree = self.os.attached.hard_kill();
if let Err(e) = &tree {
debug_assert!(
!crate::child::is_teardown_mechanism_failure(e),
"contained-tree teardown failed on async Drop: {e:?}"
);
log::warn!("Child::drop: contained-tree teardown did not fully succeed: {e}");
}
let _ = tree;
let pid = self.id.pid();
let mut os = std::mem::take(&mut self.os);
if os.proc_mut().is_reaped() {
return;
}
#[cfg(test)]
let killed = if reaper::fault::take_force_kill_failure() {
Err(Error::Io(std::io::Error::other("forced kill failure (test seam)")))
} else {
os.proc_mut().start_kill()
};
#[cfg(not(test))]
let killed = os.proc_mut().start_kill();
if killed.is_err() {
if !matches!(os.proc_mut().try_wait(), Ok(Some(_))) {
log::warn!("async child {pid} could not be terminated on drop; leaving it running");
}
return;
}
reaper::submit(reaper::ReapJob {
os,
pid,
#[cfg(test)]
origin: std::thread::current().id(),
#[cfg(test)]
probe,
#[cfg(test)]
force_panic: false,
#[cfg(test)]
force_release_panic: false,
#[cfg(test)]
force_glue_panic: false,
});
}
}
pub(crate) fn reap_now(child: &mut ::tokio::process::Child, pid: u32, done_ok: bool) {
let killed = child.start_kill();
debug_assert!(killed.is_ok(), "start_kill of an owned child should not fail");
if killed.is_err() {
return;
}
wait_and_reap(child, pid, done_ok);
}
pub(crate) fn wait_and_reap(child: &mut ::tokio::process::Child, pid: u32, done_ok: bool) {
if child.id().is_none() {
debug_assert!(
done_ok,
"wait_and_reap found an already-reaped child where one was impossible"
);
return;
}
#[cfg(unix)]
{
debug_assert!(pid <= i32::MAX as u32, "pid {pid} exceeds i32::MAX");
let mut info: libc::siginfo_t = unsafe { std::mem::zeroed() };
loop {
let rc = unsafe { libc::waitid(libc::P_PID, pid as libc::id_t, &mut info, libc::WEXITED | libc::WNOWAIT) };
if rc == 0 {
break;
}
let err = std::io::Error::last_os_error();
if err.raw_os_error() == Some(libc::EINTR) {
continue;
}
debug_assert!(false, "waitid in wait_and_reap failed unexpectedly: {err}");
break;
}
}
#[cfg(windows)]
{
use windows::Win32::Foundation::{HANDLE, WAIT_OBJECT_0};
use windows::Win32::System::Threading::{WaitForSingleObject, INFINITE};
let _ = pid;
let h = child.raw_handle().expect("tokio owns the handle while id() is Some");
let waited = unsafe { WaitForSingleObject(HANDLE(h), INFINITE) };
debug_assert!(
waited == WAIT_OBJECT_0,
"wait_and_reap did not observe the child's exit: {waited:?}"
);
}
}