use std::collections::BTreeMap;
use std::io::{PipeReader, PipeWriter};
use crate::command::Command;
use crate::containment::Containment;
use crate::error::Error;
use crate::identity::ProcessId;
use crate::stdio::Fd;
#[path = "child/pump.rs"]
pub(crate) mod pump;
#[path = "child/spawn.rs"]
pub(crate) mod spawn;
#[path = "child/proc_handle.rs"]
pub(crate) mod proc_handle;
use proc_handle::ProcHandle;
#[path = "child/lifecycle.rs"]
mod lifecycle;
#[path = "child/graceful.rs"]
mod graceful;
#[cfg(test)]
#[path = "child_tests.rs"]
mod child_tests;
#[derive(Debug)]
pub(crate) enum ParentEnd {
Reader(PipeReader),
Writer(PipeWriter),
}
#[cfg_attr(not(unix), allow(dead_code))] pub(crate) fn root_pid_was_recycled(
original: ProcessId,
current: crate::identity::Resolved<ProcessId>,
current_liveness: crate::identity::Liveness,
) -> bool {
match current {
crate::identity::Resolved::Found(now) => {
now != original && current_liveness == crate::identity::Liveness::Alive
}
crate::identity::Resolved::Gone | crate::identity::Resolved::Unknown => false,
}
}
#[derive(Debug)]
pub struct Child {
proc: ProcHandle,
id: ProcessId,
pipes: BTreeMap<Fd, ParentEnd>,
kill_on_drop: bool,
containment: Containment,
attached: crate::containment::Attached,
graceful: crate::graceful::GracefulMechanism,
elevation: Option<crate::elevation::ElevationReport>,
}
impl Child {
pub(crate) fn from_parts(
proc: ProcHandle,
id: ProcessId,
pipes: BTreeMap<Fd, ParentEnd>,
kill_on_drop: bool,
attachment: crate::containment::Attachment,
) -> Child {
Child {
proc,
id,
pipes,
kill_on_drop,
containment: attachment.containment,
attached: attachment.attached,
graceful: attachment.graceful,
elevation: None,
}
}
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()
}
pub fn containment(&self) -> Containment {
self.containment
}
pub fn graceful_mechanism(&self) -> crate::graceful::GracefulMechanism {
self.graceful
}
fn require_contained(&self) -> Result<(), Error> {
crate::containment::require_contained(self.containment, &self.attached)
}
fn require_drainable(&self) -> Result<(), Error> {
crate::containment::require_drainable(self.containment, &self.attached)
}
pub fn id(&self) -> ProcessId {
self.id
}
pub fn is_alive(&self) -> crate::identity::Liveness {
self.id.is_alive()
}
pub fn wait(&self) -> Result<std::process::ExitStatus, Error> {
self.proc.wait().map_err(Error::Io)
}
pub fn try_wait(&self) -> Result<Option<std::process::ExitStatus>, Error> {
self.proc.try_wait().map_err(Error::Io)
}
fn is_elevated_wrapper(&self) -> bool {
matches!(
self.elevation.as_ref().map(|r| &r.via),
Some(crate::elevation::ElevatedVia::Wrapped(_) | crate::elevation::ElevatedVia::WindowsUac)
)
}
pub fn kill(&self) -> Result<(), Error> {
self.proc
.kill()
.map_err(|e| crate::elevation::map_elevated_kill_error(e, self.is_elevated_wrapper()))
}
pub fn kill_tree(&self) -> Result<(), Error> {
self.require_contained()?;
#[cfg(unix)]
debug_assert!(
!self.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
}
};
!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.attached.hard_kill();
let backstop = self
.proc
.kill()
.map_err(|e| crate::elevation::map_elevated_kill_error(e, self.is_elevated_wrapper()));
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(unix)]
debug_assert!(
!self.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
}
};
!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.attached.terminate(self.proc.id())
}
pub fn stdin(&mut self) -> Option<PipeWriter> {
self.fd_write_end(Fd::STDIN)
}
pub fn stdout(&mut self) -> Option<PipeReader> {
take_reader(&mut self.pipes, Fd::STDOUT)
}
pub fn stderr(&mut self) -> Option<PipeReader> {
take_reader(&mut self.pipes, Fd::STDERR)
}
pub fn fd_write_end(&mut self, fd: Fd) -> Option<PipeWriter> {
match self.pipes.remove(&fd) {
Some(ParentEnd::Writer(w)) => Some(w),
other => {
if let Some(e) = other {
self.pipes.insert(fd, e);
}
None
}
}
}
pub fn fd_read_end(&mut self, fd: Fd) -> Option<PipeReader> {
take_reader(&mut self.pipes, fd)
}
pub fn detach(mut self) {
self.attached.disarm();
self.kill_on_drop = false;
}
pub fn communicate(&mut self, input: Option<&[u8]>) -> Result<crate::Output, Error> {
pump::communicate(self, input)
}
pub(crate) fn take_stdin_writer(&mut self) -> Option<PipeWriter> {
self.stdin()
}
pub(crate) fn take_reader(&mut self, fd: Fd) -> Option<PipeReader> {
take_reader(&mut self.pipes, fd)
}
#[cfg(windows)]
pub fn test_job_handle_contains_self(&self) -> bool {
crate::containment::windows::job_contains_pid(&self.attached, self.proc.id())
}
#[cfg(all(test, target_os = "macos"))]
#[allow(dead_code)] pub(crate) fn test_marker_handle(&self) -> Option<u64> {
match &self.attached {
crate::containment::Attached::FdMarker(m) => Some(m.handle()),
_ => None,
}
}
#[doc(hidden)]
#[cfg(target_os = "macos")]
pub fn test_fdmarker_fd(&self) -> Option<i32> {
match &self.attached {
crate::containment::Attached::FdMarker(m) => Some(m.own_fd()),
_ => None,
}
}
#[cfg(all(test, target_os = "macos"))]
pub(crate) fn test_force_fdmarker_pgid(&mut self, pgid: i32) {
match &mut self.attached {
crate::containment::Attached::FdMarker(m) => m.force_pgid_for_test(pgid),
other => panic!("test_force_fdmarker_pgid called on a non-FdMarker child: {other:?}"),
}
}
}
pub(crate) fn is_teardown_mechanism_failure(e: &Error) -> bool {
matches!(e, Error::Io(_) | Error::Unsupported { .. }) || matches!(e, Error::Unassessable { source: Some(_), .. })
}
impl Drop for Child {
fn drop(&mut self) {
if !self.kill_on_drop {
return; }
let tree = self.attached.hard_kill();
if let Err(e) = &tree {
debug_assert!(
!is_teardown_mechanism_failure(e),
"contained-tree teardown failed on sync Drop: {e:?}"
);
log::warn!("Child::drop: contained-tree teardown did not fully succeed: {e}");
}
self.proc.teardown_on_drop();
}
}
fn take_reader(pipes: &mut BTreeMap<Fd, ParentEnd>, fd: Fd) -> Option<PipeReader> {
match pipes.remove(&fd) {
Some(ParentEnd::Reader(r)) => Some(r),
other => {
if let Some(e) = other {
pipes.insert(fd, e);
}
None
}
}
}
impl Command {
pub fn spawn(&mut self) -> Result<Child, Error> {
spawn::spawn(self)
}
}