use crate::containment::mechanism::{Contains, Mechanism};
use crate::containment::{ContainMode, ContainRequest, Nesting, Skip, Tree};
use crate::error::{Error, Failures};
#[cfg(unix)]
use crate::signal::RootState;
use std::sync::Arc;
pub(crate) struct Prepared {
pub mode: Option<ContainMode>,
pub is_root: bool,
#[cfg(target_os = "linux")]
pub cgroup_leaf: Option<crate::containment::cgroup::CgroupLeaf>,
#[cfg(target_os = "macos")]
pub marker: Option<crate::containment::fdmarker::PreparedMarker>,
#[cfg(windows)]
pub graceful: crate::graceful::GracefulMechanism,
#[cfg(windows)]
pub frozen: bool,
}
#[cfg(target_os = "linux")]
#[derive(Debug, Clone, Copy)]
pub(crate) struct ChildHandle<'a> {
pub(crate) pid: u32,
pub(crate) pidfd: std::os::fd::BorrowedFd<'a>,
}
#[cfg(target_os = "linux")]
pub(crate) fn kill_group_through_pidfd(
pidfd: std::os::fd::BorrowedFd<'_>,
pid: Option<u32>,
) -> Result<(), nix::errno::Errno> {
use nix::errno::Errno;
let named = crate::child::spawn::named(pid);
match crate::containment::unix::pidfd_signal_group(pidfd, nix::sys::signal::Signal::SIGKILL) {
Ok(()) => log::debug!("spawn teardown: sent SIGKILL to the process group of {named} through its pidfd"),
Err(Errno::ESRCH) => log::debug!("spawn teardown: the process group of {named} has no member left"),
Err(e) => return Err(e),
}
Ok(())
}
impl Prepared {
pub(crate) fn graceful_mechanism(&self) -> crate::graceful::GracefulMechanism {
#[cfg(windows)]
return self.graceful;
#[cfg(not(windows))]
return crate::graceful::GracefulMechanism::Process;
}
#[cfg(target_os = "linux")]
pub(crate) fn placement_leaf(&mut self) -> Option<&mut crate::containment::cgroup::CgroupLeaf> {
self.cgroup_leaf.as_mut()
}
#[cfg(target_os = "linux")]
pub(crate) fn refuses_failed_placement(&self) -> bool {
self.cgroup_leaf.is_some() && self.mode.is_some_and(ContainMode::is_strict)
}
pub(crate) fn settle_verdict(
&mut self,
#[cfg(target_os = "linux")] child: ChildHandle<'_>,
) -> Option<AttachFailure> {
#[cfg(target_os = "linux")]
if let Some(leaf) = self.cgroup_leaf.as_mut().filter(|leaf| leaf.holds_verdict_to_take()) {
if let Err(reason) = leaf.take_placement(child) {
let path = leaf.path().display().to_string();
let strict = self.mode.is_some_and(ContainMode::is_strict);
return match not_started_failure(reason, &path, strict) {
Ok(failure) => Some(failure),
Err(reason) => {
log::debug!(
"cgroup v2: a failed spawn's child is not placed in its leaf: {report}",
report = crate::error::Report(&reason)
);
None
}
};
}
}
None
}
#[cfg(unix)]
pub(crate) fn group_is_containment(&self) -> bool {
#[cfg(target_os = "linux")]
let taken_by_a_leaf = self.cgroup_leaf.as_ref().is_some_and(|leaf| leaf.child_proven_in());
#[cfg(not(target_os = "linux"))]
let taken_by_a_leaf = false;
self.is_root && !taken_by_a_leaf && matches!(self.mode, Some(mode) if !matches!(mode, ContainMode::TreeWalk))
}
#[cfg(target_os = "linux")]
pub(crate) fn kill_group_before_attach(&self, child: ChildHandle<'_>) -> Result<(), nix::errno::Errno> {
if !self.group_is_containment() {
return Ok(());
}
kill_group_through_pidfd(child.pidfd, Some(child.pid))
}
pub(crate) fn watch_front(&mut self, pid: u32) {
#[cfg(target_os = "linux")]
if let Some(leaf) = self.cgroup_leaf.as_mut() {
leaf.watch_front(pid);
}
#[cfg(not(target_os = "linux"))]
let _ = pid;
}
}
pub(crate) struct Attachment {
pub tree: Tree,
pub graceful: crate::graceful::GracefulMechanism,
}
#[cfg(windows)]
impl Attachment {
pub(crate) fn uac_elevated() -> Attachment {
Attachment {
tree: Tree::none(),
graceful: crate::graceful::GracefulMechanism::Unknown,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum TeardownCaller {
Drop,
FailedRun,
#[cfg_attr(
not(any(target_os = "linux", windows)),
allow(dead_code, reason = "only the Linux and Windows spawns tear a child down")
)]
FailedSpawn,
#[cfg(unix)]
FinishElevated,
}
impl TeardownCaller {
pub(crate) fn label(self) -> &'static str {
match self {
TeardownCaller::Drop => "Child::drop",
TeardownCaller::FailedRun => "teardown after a failed run",
TeardownCaller::FailedSpawn => "teardown after a failed spawn",
#[cfg(unix)]
TeardownCaller::FinishElevated => "finish_elevated",
}
}
#[cfg(unix)]
pub(crate) fn this_event(self) -> &'static str {
match self {
TeardownCaller::Drop => "this drop",
TeardownCaller::FailedSpawn | TeardownCaller::FailedRun | TeardownCaller::FinishElevated => "this teardown",
}
}
}
#[cfg(unix)]
#[derive(Debug)]
pub(crate) struct DropView {
pub(crate) caller: TeardownCaller,
pub(crate) root_pid: u32,
pub(crate) root: RootState,
pub(crate) tree_killed: bool,
}
#[cfg(unix)]
impl DropView {
pub(crate) fn read(
caller: TeardownCaller,
root_pid: u32,
id: Option<crate::identity::ProcessId>,
proc: &crate::child::owned::OwnedChild,
tree: &Tree,
) -> DropView {
let label = caller.label();
let (now, unread) = proc.number_holder(root_pid);
let state = proc.state();
let handle_reaped = matches!(state, RootState::Reaped);
let root = if crate::child::root_reaped(handle_reaped, id, now) {
match &state {
RootState::Unknown(e) => log::debug!(
"{label}: the root's own handle could not say whether it was reaped ({report}), but its number shows it reaped",
report = crate::error::Report(e)
),
RootState::Unpinned => log::debug!(
"{label}: the root is not pinned by this process, but its number shows it reaped"
),
RootState::Unreaped | RootState::Reaped => {}
}
RootState::Reaped
} else {
state
};
let view = DropView {
caller,
root_pid,
root,
tree_killed: tree.is_killed(),
};
if now.is_unknown() && !handle_reaped {
let why = unread
.into_error(&format!("pid {root_pid}"))
.map_or_else(String::new, |e| format!(": {}", crate::error::Report(&e)));
if view.unsettled() {
log::debug!(
"{label}: the root's number ({root_pid}) could not be read either; kills by that number are skipped{why}"
);
} else {
log::debug!(
"{label}: the root's number ({root_pid}) could not be read; treating the root as not reaped{why}"
);
}
}
view
}
pub(crate) fn unsettled(&self) -> bool {
matches!(self.root, RootState::Unknown(_) | RootState::Unpinned)
}
pub(crate) fn unpinned_root(&self) -> bool {
matches!(self.root, RootState::Unpinned)
}
pub(crate) fn leaves_root_alone(&self) -> bool {
matches!(self.root, RootState::Reaped | RootState::Unpinned)
}
pub(crate) fn look(&self) -> RootState {
self.root.clone()
}
pub(crate) fn why_number_untrusted(&self) -> String {
match &self.root {
RootState::Reaped => "the root is already reaped".to_owned(),
untrusted => crate::signal::why_untrusted_with_cause(untrusted),
}
}
}
#[derive(Debug, Default)]
pub(crate) struct TreeKilled {
state: std::sync::Mutex<TreeState>,
}
#[derive(Debug, Default)]
struct TreeState {
vouching: Vouching,
held: Vec<crate::containment::treewalk::Left>,
}
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
enum Vouching {
#[default]
Never,
Killed,
Unvouched(UnvouchedKind),
}
impl Vouching {
fn under_held(self, root_seen_running: bool) -> Vouching {
match self {
Vouching::Killed => Vouching::Never,
Vouching::Unvouched(_) if root_seen_running => Vouching::Unvouched(UnvouchedKind::RootSeenRunning),
kept @ (Vouching::Never | Vouching::Unvouched(_)) => kept,
}
}
}
impl TreeState {
fn new(vouching: Vouching, held: Vec<crate::containment::treewalk::Left>) -> TreeState {
debug_assert!(
vouching != Vouching::Killed || held.is_empty(),
"a killed tree holds no member"
);
TreeState { vouching, held }
}
}
fn next(
prev: &TreeState,
walked: bool,
left_now: Vec<crate::containment::treewalk::Left>,
running: bool,
root_seen_running: bool,
exit_unread: bool,
) -> TreeState {
debug_assert!(
!root_seen_running || running,
"a root seen running is something left running"
);
debug_assert!(
!exit_unread || (walked && !running),
"an unread exit flag is a walk that left nothing running"
);
if !left_now.is_empty() {
return TreeState::new(prev.vouching.under_held(root_seen_running), left_now);
}
let named = if root_seen_running {
UnvouchedKind::RootSeenRunning
} else if running {
UnvouchedKind::Earlier
} else {
UnvouchedKind::HeldMembersGone
};
let vouching = match prev.vouching {
_ if exit_unread => Vouching::Unvouched(UnvouchedKind::ExitUnread),
_ if walked && !running => Vouching::Killed,
Vouching::Never if !running && prev.held.is_empty() => Vouching::Never,
Vouching::Killed if !running => Vouching::Killed,
Vouching::Unvouched(kept) if !running => Vouching::Unvouched(kept),
Vouching::Never | Vouching::Killed | Vouching::Unvouched(_) => Vouching::Unvouched(named),
};
TreeState::new(vouching, Vec::new())
}
impl TreeKilled {
fn lock(&self) -> std::sync::MutexGuard<'_, TreeState> {
self.state.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
}
#[cfg(any(unix, test))]
pub(crate) fn is_set(&self) -> bool {
self.lock().vouching == Vouching::Killed
}
pub(crate) fn holds_members(&self) -> bool {
!self.lock().held.is_empty()
}
pub(crate) fn hold(
&self,
members: Vec<crate::identity::ProcessId>,
complete: bool,
call: Option<&crate::containment::treewalk::WalkToken>,
) -> Option<crate::containment::treewalk::WalkToken> {
use crate::containment::treewalk::Left;
let walk = call.filter(|_| complete).cloned();
let mut state = self.lock();
let mut held = state.held.clone();
for id in members {
match held.iter_mut().find(|member| match member {
Left::Resolved(held_id) | Left::Termed { id: held_id, .. } => *held_id == id,
Left::Unread { .. } => false,
}) {
Some(Left::Termed { walk: tagged, .. }) => {
if walk.is_some() {
tagged.clone_from(&walk);
}
}
Some(_) => {}
None => held.push(Left::Termed { id, walk: walk.clone() }),
}
}
if !held.is_empty() {
*state = TreeState::new(state.vouching.under_held(false), held);
}
walk
}
}
#[cfg(unix)]
#[derive(Debug, Clone, Copy)]
pub(crate) enum TreeSignal {
Kill,
Term,
}
#[derive(Debug)]
pub(crate) struct Unkilled {
pub(crate) members: Vec<Error>,
pub(crate) root: Option<Box<Error>>,
pub(crate) resolved: Vec<crate::identity::ProcessId>,
}
impl Unkilled {
#[cfg(unix)]
pub(crate) fn first(&self) -> &Error {
self.members
.first()
.or(self.root.as_deref())
.expect("an incomplete kill left a member")
}
#[cfg(test)]
pub(crate) fn into_error(self) -> Error {
self.members
.into_iter()
.next()
.or(self.root.map(|root| *root))
.expect("an incomplete kill left a member")
}
pub(crate) fn unsettled(self, root_ended: bool) -> Result<(), Error> {
let root = self.root.filter(|_| !root_ended).map(|root| *root);
let left = self.members.into_iter().chain(root);
let (mut members, mut unnamed) = (Vec::new(), Vec::new());
for error in left {
if matches!(error, Error::MemberNotKilled { .. }) {
members.push(Arc::new(error));
} else {
unnamed.push(error);
}
}
match Failures::collect(members) {
Some(members) => {
let unnamed = Failures::collect(unnamed.into_iter().map(Arc::new));
Err(Error::members_left(members, unnamed.map(Failures::into_cause)))
}
None => {
let mut unnamed = unnamed.into_iter();
match unnamed.next() {
None => Ok(()),
Some(first) => Err(first.with_peers(unnamed.map(Arc::new))),
}
}
}
}
}
impl From<Error> for Unkilled {
fn from(error: Error) -> Unkilled {
Unkilled {
members: vec![error],
root: None,
resolved: Vec::new(),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum SettleOutcome {
Killed,
Skipped { over_killed: bool },
Unvouched { kind: UnvouchedKind },
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum UnvouchedKind {
HeldMembersGone,
RootSeenRunning,
Earlier,
ExitUnread,
}
impl UnvouchedKind {
fn found(self) -> &'static str {
match self {
UnvouchedKind::HeldMembersGone => {
"the members an earlier kill left, or a SIGTERM walk reached, are gone now, but no later walk has \
checked what they forked"
}
UnvouchedKind::RootSeenRunning => {
"the walk found the root running, and what the root forked meanwhile was never looked for"
}
UnvouchedKind::Earlier => {
"a kill left something running that it could not name, and no later walk has checked what it forked"
}
UnvouchedKind::ExitUnread => {
"the walk could not tell whether the root's exit had begun, so children it may have reparented out \
of the walk were never looked for"
}
}
}
pub(crate) fn unvouched_text(self) -> String {
format!("{}, so the tree could not be vouched for", self.found())
}
fn drop_text(self) -> String {
match self {
UnvouchedKind::HeldMembersGone | UnvouchedKind::Earlier => {
format!("the drop skipped the kill, and {}", self.unvouched_text())
}
UnvouchedKind::RootSeenRunning | UnvouchedKind::ExitUnread => self.unvouched_text(),
}
}
fn gone_root_text(self) -> &'static str {
match self {
UnvouchedKind::HeldMembersGone => {
"the members an earlier kill left, or a SIGTERM walk reached, are gone; the tree could not be walked \
from its exited root, so what they forked is unknown"
}
UnvouchedKind::RootSeenRunning => {
"the root an earlier walk found running is gone; the tree could not be walked from it, so what it \
forked is unknown"
}
UnvouchedKind::Earlier => {
"a kill left something running that it could not name, and no walk since has checked what it \
forked; the tree could not be walked from its gone root"
}
UnvouchedKind::ExitUnread => {
"an earlier walk could not tell whether the root's exit had begun, and the root is gone now; the tree \
could not be walked from it, so children its exit may have reparented are unknown"
}
}
}
}
#[derive(Debug)]
pub(crate) enum TreeKillOutcome {
Ran(Result<(), Unkilled>),
#[cfg_attr(
not(unix),
allow(dead_code, reason = "only a Unix mechanism answers by the root's number")
)]
Answered(Result<(), Unkilled>),
Unwalked(Error),
NoRoot(u32, Option<crate::containment::treewalk::WalkToken>),
#[cfg_attr(
not(unix),
allow(dead_code, reason = "only a Unix kernel reparents a root's children at its exit")
)]
RootExiting(u32, Option<crate::containment::treewalk::WalkToken>),
#[cfg_attr(
not(unix),
allow(dead_code, reason = "only a Unix kernel reparents a root's children at its exit")
)]
ExitUnread(Error),
#[cfg_attr(
not(unix),
allow(dead_code, reason = "only a Unix mechanism skips by the root's number")
)]
Skipped(Skip),
#[cfg_attr(
not(unix),
allow(dead_code, reason = "only a Unix mechanism skips by the root's number")
)]
SkippedHolders(Option<Result<(), Error>>),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Keeping {
ForWalkFromRunningRoot,
Nothing,
}
impl From<Result<(), Unkilled>> for TreeKillOutcome {
fn from(result: Result<(), Unkilled>) -> TreeKillOutcome {
TreeKillOutcome::Ran(result)
}
}
impl TreeKillOutcome {
pub(crate) fn in_call(self, call: Option<&crate::containment::treewalk::WalkToken>) -> TreeKillOutcome {
match self {
TreeKillOutcome::NoRoot(pid, _) => TreeKillOutcome::NoRoot(pid, call.cloned()),
TreeKillOutcome::RootExiting(pid, _) => TreeKillOutcome::RootExiting(pid, call.cloned()),
other => other,
}
}
#[cfg(unix)]
pub(crate) fn exiting_root_error(pid: u32) -> Error {
Error::Unassessable {
detail: format!(
"the root (pid {pid}) had begun to exit when the walk ended, so its children may have been \
reparented out of the walk and the tree cannot be vouched for"
),
source: None,
}
}
pub(crate) fn no_root_error(pid: u32) -> Error {
#[cfg(unix)]
let detail = format!(
"the root (pid {pid}) has exited, so its descendants were reparented and a walk from its pid finds \
none: no walk ran and nothing was killed"
);
#[cfg(not(unix))]
let detail =
format!("the root's pid ({pid}) names no process of this tree: no walk ran and nothing was killed");
Error::Unassessable { detail, source: None }
}
pub(crate) fn no_root_after_kills_error(kind: UnvouchedKind) -> Error {
Error::Unassessable {
detail: kind.gone_root_text().to_owned(),
source: None,
}
}
pub(crate) fn into_result(self) -> Result<(), Unkilled> {
match self {
TreeKillOutcome::Ran(result) | TreeKillOutcome::Answered(result) => result,
TreeKillOutcome::Skipped(Skip { holders, .. }) | TreeKillOutcome::SkippedHolders(holders) => {
holders.unwrap_or(Ok(())).map_err(Unkilled::from)
}
TreeKillOutcome::Unwalked(error) => Err(Unkilled::from(error)),
TreeKillOutcome::NoRoot(pid, _) => Err(Unkilled::from(Self::no_root_error(pid))),
#[cfg(unix)]
TreeKillOutcome::RootExiting(pid, _) => Err(Unkilled::from(Self::exiting_root_error(pid))),
#[cfg(not(unix))]
TreeKillOutcome::RootExiting(..) => unreachable!("only a Unix walk finds a root exiting"),
TreeKillOutcome::ExitUnread(error) => Err(Unkilled::from(error)),
}
}
#[cfg(unix)]
pub(crate) fn completed(&self) -> bool {
matches!(self, TreeKillOutcome::Ran(Ok(())) | TreeKillOutcome::Answered(Ok(())))
}
#[cfg(unix)]
pub(crate) fn incomplete(&self) -> Option<String> {
if self.completed() {
return None;
}
let word = |error: &Error| crate::error::Report(error).to_string();
Some(match self {
TreeKillOutcome::Ran(Err(left)) | TreeKillOutcome::Answered(Err(left)) => word(left.first()),
TreeKillOutcome::Skipped(Skip {
holders: Some(Err(error)),
..
})
| TreeKillOutcome::SkippedHolders(Some(Err(error))) => word(error),
TreeKillOutcome::Skipped(Skip { action, .. }) => {
format!("the kill was skipped, and would {action}")
}
TreeKillOutcome::SkippedHolders(_) => "the kill was skipped".to_owned(),
TreeKillOutcome::Unwalked(error) | TreeKillOutcome::ExitUnread(error) => word(error),
TreeKillOutcome::NoRoot(pid, _) => word(&Self::no_root_error(*pid)),
TreeKillOutcome::RootExiting(pid, _) => word(&Self::exiting_root_error(*pid)),
TreeKillOutcome::Ran(Ok(())) | TreeKillOutcome::Answered(Ok(())) => {
unreachable!("a completed kill has nothing left")
}
})
}
#[cfg(unix)]
pub(crate) fn skipped(&self) -> Option<&str> {
match self {
TreeKillOutcome::Skipped(skip) => Some(&skip.action),
TreeKillOutcome::Ran(_)
| TreeKillOutcome::SkippedHolders(_)
| TreeKillOutcome::Answered(_)
| TreeKillOutcome::Unwalked(_)
| TreeKillOutcome::ExitUnread(_)
| TreeKillOutcome::NoRoot(..)
| TreeKillOutcome::RootExiting(..) => None,
}
}
#[cfg(unix)]
pub(crate) fn left_undone(&self, view: &DropView) -> Option<String> {
self.skipped().filter(|_| !view.tree_killed).map(str::to_owned)
}
#[cfg(unix)]
pub(crate) fn skip_note(&self, view: &DropView) -> Option<String> {
self.skipped().map(|action| {
format!(
"{}, so its number may name another process, and the kill would {action}",
view.why_number_untrusted()
)
})
}
#[cfg(unix)]
pub(crate) fn log_skip(&self, view: &DropView) {
let TreeKillOutcome::Skipped(skip) = self else {
return;
};
let why = view.why_number_untrusted();
let (label, this, action) = (view.caller.label(), view.caller.this_event(), &skip.action);
if view.tree_killed {
log::debug!("{label}: {why} and this handle already killed the tree, so {this} does not {action}");
} else if !matches!(view.root, RootState::Reaped) {
log::debug!("{label}: {why}, so {this} does not {action}");
}
}
}
pub(crate) struct Settled<A = Result<SettleOutcome, Error>> {
pub(crate) answer: A,
pub(crate) killed_again: Vec<crate::identity::ProcessId>,
}
impl<A> Settled<A> {
pub(crate) fn of(answer: A) -> Settled<A> {
Settled {
answer,
killed_again: Vec::new(),
}
}
pub(crate) fn map<B>(self, f: impl FnOnce(A) -> B) -> Settled<B> {
Settled {
answer: f(self.answer),
killed_again: self.killed_again,
}
}
}
pub(crate) struct SweepFailure {
pub(crate) error: Error,
pub(crate) root_ended: bool,
}
impl From<Error> for SweepFailure {
fn from(error: Error) -> SweepFailure {
SweepFailure {
error,
root_ended: false,
}
}
}
pub(crate) struct Swept<'a> {
op: &'static str,
answer: Result<(), SweepFailure>,
wait: crate::containment::KillWait<'a>,
}
impl<'a> Swept<'a> {
pub(crate) fn new(
op: &'static str,
answer: Result<(), SweepFailure>,
wait: crate::containment::KillWait<'a>,
) -> Swept<'a> {
Swept { op, answer, wait }
}
pub(crate) fn unwaited(op: &'static str, answer: Result<(), SweepFailure>) -> Swept<'a> {
Swept::new(op, answer, crate::containment::KillWait::none())
}
pub(crate) fn answer(self) -> Result<(), SweepFailure> {
self.answer
}
pub(crate) fn wait(self) -> Result<(), SweepFailure> {
let root_ended = self.wait.waits_for_root();
let waited = self.wait.wait();
Self::after_wait(self.op, self.answer, waited, root_ended)
}
#[cfg(feature = "tokio")]
pub(crate) async fn wait_async(self) -> Result<(), SweepFailure> {
let root_ended = self.wait.waits_for_root();
let waited = self.wait.wait_async().await;
Self::after_wait(self.op, self.answer, waited, root_ended)
}
fn after_wait(
op: &str,
answer: Result<(), SweepFailure>,
waited: Result<(), Error>,
root_ended: bool,
) -> Result<(), SweepFailure> {
crate::containment::tree_kill::answer_after_wait(op, answer, waited, |error| SweepFailure { error, root_ended })
}
}
impl SweepFailure {
pub(crate) fn killed_root(sent: &Result<crate::signal::Sent, Error>) -> bool {
use crate::signal::Sent;
matches!(sent, Ok(Sent::Delivered | Sent::Gone))
}
pub(crate) fn backstop_of(sent: Result<crate::signal::Sent, Error>) -> (Result<(), Error>, bool) {
let ended = Self::killed_root(&sent);
(sent.map(drop), ended)
}
pub(crate) fn of(
tree: &Tree,
walk: TreeKillOutcome,
backstop: Result<(), Error>,
root: u32,
root_ended: bool,
) -> Settled<Result<(), SweepFailure>> {
tree.settle_for_kill_tree(walk, root_ended, Keeping::Nothing)
.map(|walk| {
let error = match (walk, backstop) {
(Ok(()), Ok(())) => return Ok(()),
(Err(walk), Ok(())) => walk,
(walk, Err(backstop)) => Self::with_backstop(tree, walk.err(), backstop, root),
};
Err(SweepFailure { error, root_ended })
})
}
fn with_backstop(tree: &Tree, walk: Option<Error>, backstop: Error, root: u32) -> Error {
let backstop = Arc::new(backstop);
let root_member = |source| Error::MemberNotKilled { pid: root, source };
match walk {
Some(Error::MembersLeft { members, others }) => {
let mut root_seen = false;
let mut members: Vec<Arc<Error>> = members
.iter()
.map(|member| match &**member {
Error::MemberNotKilled { pid, source } if *pid == root => {
root_seen = true;
Arc::new(root_member(
Failures::new(Arc::clone(&backstop), [Arc::clone(source)]).into_cause(),
))
}
_ => Arc::clone(member),
})
.collect();
if !root_seen {
members.push(Arc::new(root_member(backstop)));
}
Error::members_left(Failures::collect(members).expect("a member was left"), others)
}
Some(other) => other.with_peers([Arc::new(root_member(backstop))]),
None => tree.root_left(root_member(backstop)),
}
}
}
impl TreeKilled {
pub(crate) fn settle(
&self,
mechanism: Option<&Mechanism>,
outcome: impl Into<TreeKillOutcome>,
root_ended: bool,
) -> Settled {
let outcome = outcome.into();
let mut state = self.lock();
let was_killed = state.vouching == Vouching::Killed;
let held = state.held.clone();
let (gone_root_pid, call) = match &outcome {
TreeKillOutcome::NoRoot(pid, call) | TreeKillOutcome::RootExiting(pid, call) => (Some(*pid), call.as_ref()),
_ => (None, None),
};
let gone_root = gone_root_pid.is_some();
let listing_stands = call.is_some_and(|call| {
!matches!(state.vouching, Vouching::Unvouched(_))
&& state.held.iter().all(|member| {
matches!(member, crate::containment::treewalk::Left::Termed { walk: Some(walk), .. } if walk == call)
})
});
let ran = matches!(
outcome,
TreeKillOutcome::Ran(_) | TreeKillOutcome::Answered(_) | TreeKillOutcome::ExitUnread(_)
);
let exit_unread = matches!(outcome, TreeKillOutcome::ExitUnread(_));
let looked_for_no_member = matches!(
outcome,
TreeKillOutcome::NoRoot(..)
| TreeKillOutcome::RootExiting(..)
| TreeKillOutcome::Unwalked(_)
| TreeKillOutcome::ExitUnread(_)
);
let covered = gone_root && (listing_stands || state.vouching != Vouching::Never || !state.held.is_empty());
let result = if covered { Ok(()) } else { outcome.into_result() };
let crate::containment::mechanism::KillLeftOutcome {
mut result,
left: left_now,
killed: killed_again,
} = match mechanism {
Some(mechanism) => mechanism.kill_left(result, held),
None => crate::containment::mechanism::nothing_held(result),
};
let running = result.is_err() && !looked_for_no_member;
let root_seen_running = matches!(&result, Err(left) if left.root.is_some());
let after = next(&state, ran, left_now, running, root_seen_running, exit_unread);
let listing_clear = listing_stands && result.is_ok();
let after = if listing_clear {
TreeState::new(Vouching::Killed, Vec::new())
} else {
after
};
if gone_root && result.is_ok() && !was_killed && !listing_clear {
let error = match after.vouching {
Vouching::Unvouched(kind) => TreeKillOutcome::no_root_after_kills_error(kind),
Vouching::Never | Vouching::Killed => {
debug_assert!(
false,
"a gone root over held or unvouched members leaves the tree unvouched"
);
TreeKillOutcome::no_root_error(gone_root_pid.expect("a gone root has its pid"))
}
};
result = Err(Unkilled::from(error));
}
let unsettled = match result {
Ok(()) => Ok(()),
Err(left) => left.unsettled(root_ended),
};
let answer = unsettled.map(|()| match after.vouching {
Vouching::Unvouched(kind) => SettleOutcome::Unvouched { kind },
_ if ran || gone_root => {
debug_assert!(after.vouching == Vouching::Killed, "`Killed` answers a killed tree");
SettleOutcome::Killed
}
_ => SettleOutcome::Skipped {
over_killed: was_killed,
},
});
*state = after;
Settled { answer, killed_again }
}
pub(crate) fn settle_for_kill_tree(
&self,
mechanism: Option<&Mechanism>,
outcome: impl Into<TreeKillOutcome>,
root_ended: bool,
keeping: Keeping,
) -> Settled<Result<(), Error>> {
match (outcome.into(), keeping) {
(TreeKillOutcome::Unwalked(error), Keeping::ForWalkFromRunningRoot) => {
let mut members =
crate::containment::treewalk::refused_still(&crate::identity::HostKernel, &self.lock().held);
members.push(error);
Settled::of(
Unkilled {
members,
root: None,
resolved: Vec::new(),
}
.unsettled(false),
)
}
(outcome, _) => self
.settle(mechanism, outcome, root_ended)
.map(|answer| answer.map(drop)),
}
}
pub(crate) fn settle_for_drop(
&self,
mechanism: Option<&Mechanism>,
outcome: impl Into<TreeKillOutcome>,
root_ended: bool,
) -> Option<TreeLeft> {
let outcome = outcome.into();
let unwalked = matches!(outcome, TreeKillOutcome::Unwalked(_));
let settled = self.settle(mechanism, outcome, root_ended);
let (left, failure) = match settled.answer {
Err(left) => (crate::error::Report(&left).to_string(), Some(left)),
Ok(SettleOutcome::Unvouched { kind }) => (kind.drop_text(), None),
Ok(SettleOutcome::Killed | SettleOutcome::Skipped { .. }) => return None,
};
let after = match (unwalked, &settled.killed_again[..]) {
(false, _) => String::new(),
(true, []) => "; the root is killed regardless, so its other descendants may be orphaned".to_owned(),
(true, killed) => {
let pids: Vec<String> = killed.iter().map(|id| id.pid().to_string()).collect();
format!(
"; the members this handle held were killed by identity (pid {}), and the root is killed \
regardless, so its other descendants may be orphaned",
pids.join(", ")
)
}
};
Some(TreeLeft {
text: format!("contained-tree teardown did not fully succeed: {left}{after}"),
failure,
})
}
}
pub(crate) struct TreeLeft {
pub(crate) text: String,
pub(crate) failure: Option<Error>,
}
pub(crate) fn is_nested(marker_present: bool) -> bool {
marker_present
}
#[cfg(unix)]
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum UnixSetup {
Session,
ProcessGroup,
None,
}
#[cfg(unix)]
pub(crate) fn unix_setup_for(mode: Option<ContainMode>) -> UnixSetup {
match mode {
Some(ContainMode::Session) => UnixSetup::Session,
Some(ContainMode::TreeWalk) => UnixSetup::None,
_ => UnixSetup::ProcessGroup,
}
}
#[cfg(windows)]
pub(crate) struct WindowsContain {
pub creation_flags: u32,
pub marker_env: bool,
}
#[cfg(windows)]
pub(crate) fn windows_contain_setup(req: &ContainRequest, is_root: bool) -> WindowsContain {
let Some(mode) = req.mode else {
return WindowsContain {
creation_flags: 0,
marker_env: false,
};
};
let creation_flags = if is_root && !matches!(mode, ContainMode::TreeWalk) {
crate::containment::windows::root_flags()
} else {
crate::containment::windows::group_flags()
};
WindowsContain {
creation_flags,
marker_env: marks_environment(req, is_root),
}
}
fn marks_environment(req: &ContainRequest, is_root: bool) -> bool {
is_root && req.nesting == Nesting::Mark
}
#[cfg(unix)]
pub(crate) fn marks_child_environment(req: &ContainRequest, marker_present: bool) -> bool {
req.mode.is_some() && marks_environment(req, !is_nested(marker_present))
}
#[allow(
clippy::too_many_arguments,
reason = "each Unix platform reads its own subset of the arguments"
)]
pub(crate) fn prepare(
#[cfg(not(target_os = "linux"))] std_cmd: &mut std::process::Command,
#[cfg(unix)] steps: &mut crate::child::spawn::in_child::InChild,
req: &ContainRequest,
#[cfg_attr(
not(windows),
allow(
unused_variables,
reason = "only Windows can honour the caller's creation-flag request"
)
)]
flags: &crate::command::flags::FlagsRequest,
#[cfg_attr(
not(target_os = "macos"),
allow(unused_variables, reason = "drives the macOS fd-marker install only")
)]
reserved_fds: &[i32],
#[cfg_attr(
not(target_os = "macos"),
allow(unused_variables, reason = "drives the macOS fd-marker install only")
)]
marker_suppressed: bool,
#[cfg_attr(
not(windows),
allow(unused_variables, reason = "only the Windows path composes env ops into the request")
)]
env_ops: &[crate::command::EnvOp],
#[cfg_attr(
not(target_os = "linux"),
allow(unused_variables, reason = "only a Linux cgroup leaf waits for its drain")
)]
teardown_warn_after: Option<std::time::Duration>,
#[cfg_attr(
not(any(target_os = "linux", target_os = "macos")),
allow(
unused_variables,
reason = "only a Linux cgroup leaf and a macOS fd marker own a clone of the spawn's kernel"
)
)]
kernel: &crate::identity::SpawnKernel,
) -> Result<Prepared, Error> {
let mode = req.mode;
#[cfg(windows)]
let snapshot = crate::child::spawn::windows_raw::env_snapshot::EnvSnapshot::read()?;
#[cfg(windows)]
let marker_present = snapshot
.var(std::ffi::OsStr::new(crate::containment::NESTED_ENV))
.is_some();
#[cfg(not(windows))]
let marker_present = std::env::var_os(crate::containment::NESTED_ENV).is_some();
let is_root = !is_nested(marker_present);
#[cfg(windows)]
let graceful = {
use std::os::windows::process::CommandExt;
let spawn =
crate::command::flags::windows_spawn(req, *flags, is_root, crate::command::flags::SpawnBackend::Std)?;
std_cmd.creation_flags(spawn.creation_flags);
crate::containment::windows::mechanism_from_flags(spawn.creation_flags)
};
if mode.is_none() {
return Ok(Prepared {
mode: None,
is_root: false,
#[cfg(target_os = "linux")]
cgroup_leaf: None,
#[cfg(target_os = "macos")]
marker: None,
#[cfg(windows)]
graceful,
#[cfg(windows)]
frozen: flags.suspended,
});
}
#[cfg(not(target_os = "linux"))]
let marker_env = marks_environment(req, is_root);
#[cfg(windows)]
{
use crate::child::spawn::windows_raw::{child_ops, resolve::ChildEnv};
let env = ChildEnv::capture(&snapshot, &child_ops(env_ops, marker_env));
std_cmd.env_clear();
std_cmd.envs(env.captured_vars().expect("a capture is never inherited"));
}
#[cfg(target_os = "macos")]
if marker_env {
std_cmd.env(crate::containment::NESTED_ENV, "1");
}
#[cfg(target_os = "linux")]
{
if is_root && mode.is_some() {
match unix_setup_for(mode) {
UnixSetup::Session => {
crate::containment::unix::set_session(steps);
return Ok(Prepared {
mode,
is_root,
cgroup_leaf: None, });
}
UnixSetup::None => {
return Ok(Prepared {
mode,
is_root,
cgroup_leaf: None,
});
}
UnixSetup::ProcessGroup => {
steps.process_group();
}
}
let strict = mode.is_some_and(ContainMode::is_strict);
let leaf = if strict {
crate::containment::cgroup::leaf_if_offered(
crate::containment::cgroup::offered_cgroup(),
kernel,
teardown_warn_after,
)?
} else {
match crate::containment::cgroup::try_create_leaf(kernel, teardown_warn_after) {
Ok(leaf) => Some(leaf),
Err(e) => {
crate::containment::cgroup::log_degrade(&e);
None
}
}
};
if let Some(ref l) = leaf {
unsafe { steps.place(l.procs_fd(), strict) };
}
return Ok(Prepared {
mode,
is_root,
cgroup_leaf: leaf,
});
}
return Ok(Prepared {
mode,
is_root,
cgroup_leaf: None,
});
}
#[cfg(all(unix, not(target_os = "linux")))]
if is_root && mode.is_some() {
match unix_setup_for(mode) {
UnixSetup::Session => crate::containment::unix::set_session(steps),
UnixSetup::ProcessGroup => crate::containment::unix::set_process_group(std_cmd),
UnixSetup::None => {} }
}
#[cfg(target_os = "macos")]
let marker = if crate::containment::fdmarker::marker_wanted(mode, is_root, marker_suppressed) {
match crate::containment::fdmarker::install(steps, reserved_fds, kernel) {
Ok(marker) => Some(marker),
Err(e) if mode.is_some_and(ContainMode::is_strict) => return Err(e),
Err(e) => {
log::warn!(
"{report}; falling back to the pre-existing containment channel for this mode",
report = crate::error::Report(&e)
);
None
}
}
} else {
None
};
#[cfg(windows)]
crate::containment::windows::clear_std_handle_inheritance();
#[cfg_attr(
target_os = "linux",
expect(unreachable_code, reason = "the linux block above returns on every path")
)]
Ok(Prepared {
mode,
is_root,
#[cfg(target_os = "linux")]
cgroup_leaf: None,
#[cfg(target_os = "macos")]
marker,
#[cfg(windows)]
graceful,
#[cfg(windows)]
frozen: flags.suspended,
})
}
#[derive(Debug)]
pub(crate) struct AttachFailure {
pub(crate) cause: Error,
pub(crate) cleanup: Option<Failures>,
#[cfg_attr(
not(any(target_os = "linux", windows)),
allow(dead_code, reason = "read only by the Linux and Windows arms of the spawn")
)]
pub(crate) not_started: bool,
#[cfg(windows)]
pub(crate) proven: Option<Box<crate::containment::windows::ProvenRoot>>,
}
#[cfg(target_os = "linux")]
pub(crate) fn not_started_failure(
reason: crate::containment::cgroup::NotPlaced,
path: &str,
strict: bool,
) -> Result<AttachFailure, crate::containment::cgroup::NotPlaced> {
use crate::containment::cgroup::NotEntered;
let (detail, source) = match reason.report() {
NotEntered::NotReported => (
format!(
"cgroup v2: the child did not report its placement in leaf cgroup {path}, so the program did not run"
),
None,
),
NotEntered::WriteFailed(errno) if strict => (
format!("cgroup v2: the child could not be placed in its leaf cgroup {path}, so the program did not run"),
Some(Error::io_cause(std::io::Error::from_raw_os_error(errno))),
),
NotEntered::WriteFailed(_) | NotEntered::Unknown(_) => return Err(reason),
};
log::debug!(
"cgroup v2: the program did not run: {report}",
report = crate::error::Report(&reason)
);
let cause = Error::Containment { detail, source }.with_peers(reason.into_read_failure().map(Error::io_cause));
Ok(AttachFailure {
cause,
cleanup: None,
not_started: true,
#[cfg(windows)]
proven: None,
})
}
#[cfg(target_os = "linux")]
fn unproven_failure(
leaf: crate::containment::cgroup::CgroupLeaf,
reason: crate::containment::cgroup::NotPlaced,
path: &str,
errno: i32,
child: ChildHandle<'_>,
) -> AttachFailure {
log::debug!(
"cgroup v2: the child's placement is unknown: {report}",
report = crate::error::Report(&reason)
);
drop(leaf);
let cleanup = kill_group_through_pidfd(child.pidfd, Some(child.pid))
.err()
.and_then(|refusal| crate::child::spawn::refused_group_kill_failure(child.pid, refusal));
let cause = Error::Containment {
detail: format!(
"cgroup v2: the spawn could not read the child's status channel, so it is not known whether the \
child entered its leaf cgroup {path}; the child is torn down"
),
source: Some(Error::io_cause(std::io::Error::from_raw_os_error(errno))),
}
.with_peers(reason.into_read_failure().map(Error::io_cause));
AttachFailure {
cleanup,
..AttachFailure::from(cause)
}
}
impl From<Error> for AttachFailure {
fn from(cause: Error) -> AttachFailure {
AttachFailure {
cause,
cleanup: None,
not_started: false,
#[cfg(windows)]
proven: None,
}
}
}
pub(crate) fn attach(
#[cfg(unix)] pid: u32,
id: Result<crate::identity::ProcessId, Error>,
#[cfg(target_os = "linux")] child: ChildHandle<'_>,
#[cfg(windows)] proc_handle: std::os::windows::io::RawHandle,
prepared: Prepared,
) -> Result<Attachment, AttachFailure> {
let graceful = prepared.graceful_mechanism();
let tree = attach_tree(
#[cfg(unix)]
pid,
id,
#[cfg(target_os = "linux")]
child,
#[cfg(windows)]
proc_handle,
prepared,
)?;
Ok(Attachment { tree, graceful })
}
fn attach_tree(
#[cfg(unix)] pid: u32,
id: Result<crate::identity::ProcessId, Error>,
#[cfg(target_os = "linux")] child: ChildHandle<'_>,
#[cfg(windows)] proc_handle: std::os::windows::io::RawHandle,
prepared: Prepared,
) -> Result<Tree, AttachFailure> {
use crate::containment::treewalk::Walker;
#[cfg(unix)]
use crate::containment::unix::Group;
#[cfg(target_os = "linux")]
{
let mut prepared = prepared;
if prepared.mode.is_some() {
if prepared.is_root {
if matches!(prepared.mode, Some(ContainMode::TreeWalk)) {
return Ok(Tree::contained(Mechanism::Walk(Walker::new(id?))));
}
let raw_pid = pid;
debug_assert!(
raw_pid <= i32::MAX as u32,
"pid {raw_pid} exceeds i32::MAX; pgid cast would truncate"
);
let pgid = raw_pid as i32;
if matches!(prepared.mode, Some(ContainMode::Session)) {
return Ok(Tree::contained(Mechanism::Group(Group::session(pgid))));
}
if let Some(mut leaf) = prepared.cgroup_leaf.take() {
match leaf.take_placement(child) {
Ok(()) => {
return Ok(Tree::contained(Mechanism::Cgroup(leaf)));
}
Err(reason) => {
let path = leaf.path().display().to_string();
if let crate::containment::cgroup::NotEntered::Unknown(errno) = reason.report() {
return Err(unproven_failure(leaf, reason, &path, errno, child));
}
leaf.remove_unentered();
let strict = prepared.mode.is_some_and(ContainMode::is_strict);
return match not_started_failure(reason, &path, strict) {
Ok(failure) => Err(failure),
Err(reason) => {
crate::containment::cgroup::log_degrade(&reason);
Ok(Tree::contained(Mechanism::Group(Group::process_group(pgid))))
}
};
}
}
}
return Ok(Tree::contained(Mechanism::Group(Group::process_group(pgid))));
} else {
return Ok(Tree::delegated());
}
}
}
#[cfg(all(unix, not(target_os = "linux")))]
{
if prepared.mode.is_some() {
if prepared.is_root {
#[cfg(target_os = "macos")]
if let Some(marker) = prepared.marker {
let pgid = match prepared.mode {
Some(ContainMode::TreeWalk) => None,
_ => {
debug_assert!(
pid <= i32::MAX as u32,
"pid {pid} exceeds i32::MAX; pgid cast would truncate"
);
Some(pid as i32)
}
};
return Ok(Tree::contained(Mechanism::Marker(
crate::containment::fdmarker::Marker::new(marker, id?, pgid),
)));
}
if matches!(prepared.mode, Some(ContainMode::TreeWalk)) {
return Ok(Tree::contained(Mechanism::Walk(Walker::new(id?))));
}
let raw_pid = pid;
debug_assert!(
raw_pid <= i32::MAX as u32,
"pid {raw_pid} exceeds i32::MAX; pgid cast would truncate"
);
let pgid = raw_pid as i32;
let group = match prepared.mode {
Some(ContainMode::Session) => Group::session(pgid),
_ => Group::process_group(pgid),
};
return Ok(Tree::contained(Mechanism::Group(group)));
} else {
#[cfg(target_os = "macos")]
if prepared.marker.is_some() {
log::warn!(
"fd marker: a nested spawn's prepare() unexpectedly produced a marker; \
a nested member must inherit the root's marker, never create its own \
— discarding it"
);
debug_assert!(
false,
"a nested member inherits the root's marker and must never create one"
);
}
return Ok(Tree::delegated());
}
}
}
#[cfg(windows)]
{
if prepared.mode.is_some() && prepared.is_root {
if matches!(prepared.mode, Some(ContainMode::TreeWalk)) {
return Ok(Tree::contained(Mechanism::Walk(Walker::new(id?))));
}
if prepared.frozen {
return match crate::containment::windows::assign_held(proc_handle) {
Ok(job) => Ok(Tree::contained(Mechanism::Job(job))),
Err(e) => Err(Error::Containment {
detail: "the frozen child could not be put in its Job Object".to_owned(),
source: Some(Error::io_cause(e)),
}
.into()),
};
}
let strict = prepared.mode.is_some_and(ContainMode::is_strict);
match crate::containment::windows::attach_job(proc_handle, strict) {
Ok(Some(job)) => return Ok(Tree::contained(Mechanism::Job(job))),
Ok(None) => {
return Ok(Tree::contained(Mechanism::Walk(Walker::new(id?))));
}
Err(failure) => return Err(failure),
}
} else if prepared.mode.is_some() {
return Ok(Tree::delegated());
}
}
let _ = prepared;
Ok(Tree::none())
}
#[cfg(test)]
#[path = "dispatch_tests.rs"]
mod dispatch_tests;