use crate::containment::{ContainMode, ContainRequest, Containment, Nesting};
use crate::error::Error;
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(all(target_os = "linux", feature = "tokio"))]
pub teardown_warn_after: Option<std::time::Duration>,
#[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;
}
pub(crate) fn settle_verdict(&mut self, #[cfg(target_os = "linux")] child: ChildHandle<'_>) {
#[cfg(target_os = "linux")]
if let Some(leaf) = self.cgroup_leaf.as_mut().filter(|leaf| leaf.holds_verdict_to_take()) {
if let Err(e) = leaf.take_placement(child) {
log::debug!("cgroup v2: a failed spawn's child is not placed in its leaf: {e}");
}
}
}
#[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_entered());
#[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(all(target_os = "linux", feature = "tokio"))]
pub(crate) fn leafless_group_is_containment(&self) -> bool {
self.cgroup_leaf.is_none() && self.group_is_containment()
}
#[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))
}
#[cfg_attr(
not(feature = "tokio"),
allow(
dead_code,
reason = "only the tokio spawn path can lose a handle before a verdict is settled"
)
)]
pub(crate) fn abandon_before_verdict(
&mut self,
front: bool,
#[cfg(target_os = "linux")] child: Option<(std::os::fd::OwnedFd, crate::child::owned::teardown::Past)>,
) -> AbandonedChild {
#[cfg(target_os = "linux")]
if let Some(leaf) = self.cgroup_leaf.as_mut() {
use crate::containment::cgroup::Abandoned;
#[cfg(feature = "tokio")]
let mut warn = crate::containment::cgroup::WarnAfter(self.teardown_warn_after);
#[cfg(not(feature = "tokio"))]
let mut warn = crate::containment::cgroup::NoWarn;
let Some(child) = child else {
use crate::containment::cgroup::WithoutChild;
return match leaf.abandon_without_child(&mut warn) {
WithoutChild::Unnamed => AbandonedChild::MaybeUnreaped,
WithoutChild::Named => {
debug_assert!(false, "a child that named itself was abandoned with no handle");
AbandonedChild::MaybeUnreachable
}
WithoutChild::AlreadyAbandoned => {
debug_assert!(false, "a spawn's abandonment was asked for twice");
AbandonedChild::MaybeUnreachable
}
};
};
return match leaf.abandon_before_verdict(front, child, &mut warn) {
Abandoned::Ended(fate) => AbandonedChild::Ended(fate),
Abandoned::Uncollected(clause) => AbandonedChild::Uncollected(clause),
Abandoned::Front(fate) => AbandonedChild::Front(fate),
Abandoned::Repeated => {
debug_assert!(false, "a spawn's abandonment was asked for twice");
AbandonedChild::MaybeUnreachable
}
};
}
#[cfg(not(target_os = "linux"))]
let _ = front;
AbandonedChild::MaybeUnreachable
}
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;
}
}
#[cfg(all(target_os = "linux", feature = "tokio"))]
impl Drop for Prepared {
fn drop(&mut self) {
if let Some(leaf) = self.cgroup_leaf.take() {
leaf.drop_warning(&mut crate::containment::cgroup::WarnAfter(self.teardown_warn_after));
}
}
}
#[cfg_attr(
not(all(target_os = "linux", feature = "tokio")),
allow(
dead_code,
reason = "only a Linux leaf under tokio produces more than MaybeUnreachable"
)
)]
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum AbandonedChild {
Ended(crate::error::ChildFate),
MaybeUnreaped,
MaybeUnreachable,
Uncollected(crate::child::owned::teardown::Left),
Front(crate::child::spawn::FrontFate),
}
pub(crate) struct Attachment {
pub containment: Containment,
pub attached: Attached,
pub graceful: crate::graceful::GracefulMechanism,
}
#[cfg(windows)]
impl Attachment {
pub(crate) fn uac_elevated() -> Attachment {
Attachment {
containment: Containment::None,
attached: Attached::None,
graceful: crate::graceful::GracefulMechanism::Unknown,
}
}
}
#[cfg(unix)]
#[derive(Debug)]
pub(crate) enum RootView {
Reaped,
Unknown(std::io::Error),
Unpinned,
Trusted,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum TeardownCaller {
Drop,
FailedRun,
#[cfg_attr(
not(any(target_os = "linux", windows, feature = "tokio")),
allow(
dead_code,
reason = "only the Linux and Windows spawns and the async spawn 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: RootView,
pub(crate) tree_killed: bool,
}
#[cfg(unix)]
impl DropView {
pub(crate) fn read(
caller: TeardownCaller,
root_pid: u32,
id: Option<crate::identity::ProcessId>,
root: impl FnOnce() -> crate::signal::RootState,
tree_killed: &TreeKilled,
) -> DropView {
use crate::signal::RootState;
let label = caller.label();
let now = crate::child::root_identity_now(root_pid);
let state = root();
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 ({e}), but its number shows it reaped"
),
RootState::Unpinned => log::debug!(
"{label}: the root is not pinned by this process, but its number shows it reaped"
),
RootState::Unreaped | RootState::Reaped { .. } => {}
}
RootView::Reaped
} else {
match state {
RootState::Unreaped => RootView::Trusted,
RootState::Unknown(e) => RootView::Unknown(e),
RootState::Unpinned => RootView::Unpinned,
RootState::Reaped { .. } => RootView::Reaped,
}
};
let view = DropView {
caller,
root_pid,
root,
tree_killed: tree_killed.is_set(),
};
if now.is_unknown() && !handle_reaped {
if view.unsettled() {
log::debug!(
"{label}: the root's number ({root_pid}) could not be read either; kills by that number are skipped"
);
} else {
log::debug!(
"{label}: the root's number ({root_pid}) could not be read; treating the root as not reaped"
);
}
}
view
}
pub(crate) fn unsettled(&self) -> bool {
matches!(self.root, RootView::Unknown(_) | RootView::Unpinned)
}
pub(crate) fn number_untrusted(&self) -> bool {
!matches!(self.root, RootView::Trusted)
}
pub(crate) fn unpinned_root(&self) -> bool {
matches!(self.root, RootView::Unpinned)
}
pub(crate) fn leaves_root_alone(&self) -> bool {
matches!(self.root, RootView::Reaped | RootView::Unpinned)
}
pub(crate) fn why_number_untrusted(&self) -> String {
match &self.root {
RootView::Unknown(e) => format!("the root could not be shown to be unreaped (RootState::Unknown: {e})"),
RootView::Unpinned => format!(
"the root is not pinned by this process (RootState::Unpinned: {})",
crate::signal::UNPINNED_WHY
),
RootView::Reaped => "the root is already reaped".to_owned(),
RootView::Trusted => {
debug_assert!(false, "a trusted root's number is not untrusted");
"the root's number is trusted".to_owned()
}
}
}
pub(crate) fn skipped_action(&self, attached: &Attached) -> Option<String> {
attached
.named_by_root_number(self.root_pid, "kill")
.filter(|_| self.number_untrusted())
}
}
#[derive(Debug, Default)]
pub(crate) struct TreeKilled {
state: std::sync::Mutex<TreeState>,
}
#[derive(Debug, Default)]
enum TreeState {
#[default]
Never,
Killed,
Left(Vec<crate::containment::treewalk::Left>),
Unvouched(UnvouchedKind),
}
fn next(
prev: &TreeState,
walked: bool,
left_now: Vec<crate::containment::treewalk::Left>,
running: bool,
root_seen_running: bool,
) -> TreeState {
debug_assert!(
!root_seen_running || running,
"a root seen running is something left running"
);
if !left_now.is_empty() {
return TreeState::Left(left_now);
}
let named = if root_seen_running {
UnvouchedKind::RootSeenRunning
} else if running {
UnvouchedKind::Earlier
} else {
UnvouchedKind::HeldMembersGone
};
match prev {
_ if walked && !running => TreeState::Killed,
TreeState::Never if !running => TreeState::Never,
TreeState::Killed if !running => TreeState::Killed,
TreeState::Unvouched(kept) if !running => TreeState::Unvouched(*kept),
TreeState::Never | TreeState::Killed | TreeState::Left(_) | TreeState::Unvouched(_) => {
TreeState::Unvouched(named)
}
}
}
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 {
matches!(*self.lock(), TreeState::Killed)
}
}
#[cfg(unix)]
#[derive(Debug, Clone, Copy)]
pub(crate) enum TreeSignal {
Kill,
Term,
}
#[cfg(unix)]
impl TreeSignal {
pub(crate) fn verb(self) -> &'static str {
match self {
TreeSignal::Kill => "kill",
TreeSignal::Term => "signal",
}
}
}
#[cfg(unix)]
enum DropReach {
Kill,
#[cfg(target_os = "linux")]
GroupGone,
Skip(String),
}
#[derive(Debug)]
pub(crate) struct Unkilled {
pub(crate) members: Vec<Error>,
pub(crate) root: Option<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_ref())
.expect("an incomplete kill left a member")
}
#[cfg(test)]
pub(crate) fn into_error(self) -> Error {
self.members
.into_iter()
.next()
.or(self.root)
.expect("an incomplete kill left a member")
}
pub(crate) fn unsettled(self, root_ended: bool) -> Result<(), Unsettled> {
let mut left = self.members.into_iter().chain(self.root.filter(|_| !root_ended));
match left.next() {
None => Ok(()),
Some(first) => Err(Unsettled {
first,
others: left.collect(),
}),
}
}
}
impl From<Error> for Unkilled {
fn from(error: Error) -> Unkilled {
Unkilled {
members: vec![error],
root: None,
resolved: Vec::new(),
}
}
}
#[derive(Debug)]
pub(crate) struct Unsettled {
pub(crate) first: Error,
pub(crate) others: Vec<Error>,
}
impl Unsettled {
pub(crate) fn report(self, caller: &str) -> Error {
for other in &self.others {
log::warn!("{caller}: {other}");
}
self.first
}
}
impl std::fmt::Display for Unsettled {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.first)?;
self.others.iter().try_for_each(|other| write!(f, "; {other}"))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum SettleOutcome {
Killed,
Skipped,
Unvouched { kind: UnvouchedKind },
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum UnvouchedKind {
HeldMembersGone,
RootSeenRunning,
Earlier,
}
impl UnvouchedKind {
fn found(self) -> &'static str {
match self {
UnvouchedKind::HeldMembersGone => {
"the members an earlier kill left 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"
}
}
}
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 => self.unvouched_text(),
}
}
fn gone_root_text(self) -> &'static str {
match self {
UnvouchedKind::HeldMembersGone => {
"the members an earlier kill left are gone; the tree could not be walked from its gone 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"
}
}
}
}
#[derive(Debug)]
pub(crate) enum TreeKillOutcome {
Ran(Result<(), Unkilled>),
Unwalked(Error),
NoRoot,
#[cfg_attr(
not(unix),
allow(dead_code, reason = "only a Unix drop or cleanup skips a kill by the root's number")
)]
Skipped {
action: String,
holders: Result<(), Unkilled>,
},
}
impl From<Result<(), Unkilled>> for TreeKillOutcome {
fn from(result: Result<(), Unkilled>) -> TreeKillOutcome {
TreeKillOutcome::Ran(result)
}
}
impl TreeKillOutcome {
pub(crate) fn no_root_error() -> Error {
Error::Unassessable {
detail: "the root is gone or no longer holds its pid, so no walk ran and nothing was killed".to_owned(),
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::Skipped { holders: result, .. } => result,
TreeKillOutcome::Unwalked(error) => Err(Unkilled::from(error)),
TreeKillOutcome::NoRoot => Err(Unkilled::from(Self::no_root_error())),
}
}
#[cfg(unix)]
pub(crate) fn completed(&self) -> bool {
matches!(self, TreeKillOutcome::Ran(Ok(())))
}
#[cfg(unix)]
pub(crate) fn incomplete(&self) -> Option<String> {
if self.completed() {
return None;
}
Some(match self {
TreeKillOutcome::Ran(Err(left)) | TreeKillOutcome::Skipped { holders: Err(left), .. } => {
left.first().to_string()
}
TreeKillOutcome::Skipped {
action,
holders: Ok(()),
} => format!("the kill was skipped, and would {action}"),
TreeKillOutcome::Unwalked(error) => error.to_string(),
TreeKillOutcome::NoRoot => Self::no_root_error().to_string(),
TreeKillOutcome::Ran(Ok(())) => unreachable!("a completed kill has nothing left"),
})
}
#[cfg(unix)]
pub(crate) fn skipped(&self) -> Option<&str> {
match self {
TreeKillOutcome::Skipped { action, .. } => Some(action),
TreeKillOutcome::Ran(_) | TreeKillOutcome::Unwalked(_) | TreeKillOutcome::NoRoot => 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()
)
})
}
}
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,
}
}
}
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(
op: &str,
attached: &Attached,
killed: &TreeKilled,
walk: TreeKillOutcome,
backstop: Result<(), Error>,
root_ended: bool,
) -> Result<(), SweepFailure> {
let walk = attached.settle_for_kill_tree(op, killed, walk, root_ended);
if let (Err(walk), Err(backstop)) = (&walk, &backstop) {
log::debug!("{op} handle backstop also failed ({backstop}); surfacing the walk's error: {walk}");
}
walk.and(backstop).map_err(|error| SweepFailure { error, root_ended })
}
}
#[derive(Debug, Default)]
pub(crate) enum Attached {
#[default]
None,
Delegated,
#[cfg(unix)]
ProcessGroup(i32), #[cfg(target_os = "linux")]
Cgroup(crate::containment::cgroup::CgroupLeaf),
#[cfg(windows)]
JobObject(crate::containment::windows::JobHandle),
#[cfg(target_os = "macos")]
FdMarker(crate::containment::fdmarker::Marker),
TreeWalk(crate::identity::ProcessId),
}
#[cfg(target_os = "linux")]
impl std::fmt::Debug for crate::containment::cgroup::CgroupLeaf {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("CgroupLeaf").finish_non_exhaustive()
}
}
impl Attached {
#[cfg(unix)]
pub(crate) fn teardown_subject(&self) -> String {
#[cfg(target_os = "linux")]
if let Attached::Cgroup(leaf) = self {
return format!("cgroup leaf {}", leaf.path().display());
}
format!("{self:?}")
}
#[cfg(unix)]
#[cfg_attr(
not(target_os = "linux"),
allow(unused_variables, reason = "only a Linux cgroup reads it")
)]
pub(crate) fn kill_reaches_across_credentials(
&self,
pid: u32,
pidfd: Option<std::os::fd::BorrowedFd<'_>>,
) -> std::io::Result<bool> {
#[cfg(target_os = "linux")]
if let Attached::Cgroup(leaf) = self {
return leaf.holds_member(pid, pidfd);
}
Ok(false)
}
#[cfg(all(feature = "tokio", target_os = "linux"))]
pub(crate) fn cgroup_kill_landed(&self) -> bool {
matches!(self, Attached::Cgroup(leaf) if leaf.kill_landed())
}
#[cfg(unix)]
#[cfg_attr(
not(target_os = "linux"),
allow(unused_variables, reason = "only a Linux cgroup reads it")
)]
pub(crate) fn cgroup_names(&self, pid: u32, pidfd: Option<std::os::fd::BorrowedFd<'_>>) -> std::io::Result<bool> {
#[cfg(target_os = "linux")]
if let Attached::Cgroup(leaf) = self {
return leaf.names(pid, pidfd);
}
Ok(false)
}
#[cfg_attr(
not(unix),
allow(unused_variables, reason = "only Unix names a group by the root's pid")
)]
pub(crate) fn hard_kill(&self, root: &crate::containment::GroupRoot<'_>) -> TreeKillOutcome {
let ran = |result: Result<(), Error>| TreeKillOutcome::Ran(result.map_err(Unkilled::from));
match self {
Attached::None | Attached::Delegated => TreeKillOutcome::Ran(Ok(())),
#[cfg(unix)]
Attached::ProcessGroup(pgid) => ran(crate::containment::unix::kill_group(*pgid, root)),
#[cfg(target_os = "linux")]
Attached::Cgroup(leaf) => ran(leaf.hard_kill()),
#[cfg(windows)]
Attached::JobObject(job) => ran(job.hard_kill().map_err(Error::Io)),
#[cfg(target_os = "macos")]
Attached::FdMarker(m) => ran(m.hard_kill(root)),
Attached::TreeWalk(root) => crate::containment::treewalk::hard_kill(&crate::identity::HostKernel, *root),
}
}
#[cfg(unix)]
pub(crate) fn hard_kill_settled(
&self,
caller: &str,
killed: &TreeKilled,
root: &crate::containment::GroupRoot<'_>,
) -> Result<(), Error> {
self.settle_for_kill_tree(caller, killed, self.hard_kill(root), false)
}
pub(crate) fn settle(
&self,
killed: &TreeKilled,
outcome: impl Into<TreeKillOutcome>,
root_ended: bool,
) -> Result<SettleOutcome, Unsettled> {
let outcome = outcome.into();
let walk = matches!(self, Attached::TreeWalk(_));
let mut state = killed.lock();
let was_killed = matches!(*state, TreeState::Killed);
let held = match &*state {
TreeState::Left(held) => held.clone(),
TreeState::Never | TreeState::Killed | TreeState::Unvouched(_) => Vec::new(),
};
let gone_root = matches!(outcome, TreeKillOutcome::NoRoot);
let ran = matches!(outcome, TreeKillOutcome::Ran(_));
let looked_for_no_member = matches!(outcome, TreeKillOutcome::NoRoot | TreeKillOutcome::Unwalked(_));
let covered = gone_root && !matches!(*state, TreeState::Never);
let mut result = if covered { Ok(()) } else { outcome.into_result() };
let mut left_now = Vec::new();
if walk {
result = crate::containment::treewalk::with_earlier(&crate::identity::HostKernel, held, result);
if let Err(left) = &result {
left_now = crate::containment::treewalk::Left::of(left);
}
}
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);
if gone_root && result.is_ok() && !was_killed {
let error = match after {
TreeState::Unvouched(kind) => TreeKillOutcome::no_root_after_kills_error(kind),
TreeState::Never | TreeState::Killed | TreeState::Left(_) => {
debug_assert!(
false,
"a gone root over held or unvouched members leaves the tree unvouched"
);
TreeKillOutcome::no_root_error()
}
};
result = Err(Unkilled::from(error));
}
let unsettled = match result {
Ok(()) => Ok(()),
Err(left) => {
debug_assert!(left.root.is_none() || walk, "only a tree walk leaves the root alone");
left.unsettled(root_ended)
}
};
let answer = unsettled.map(|()| match &after {
TreeState::Unvouched(kind) => SettleOutcome::Unvouched { kind: *kind },
_ if ran || gone_root => {
debug_assert!(matches!(after, TreeState::Killed), "`Killed` answers a killed tree");
SettleOutcome::Killed
}
_ => SettleOutcome::Skipped,
});
*state = after;
answer
}
pub(crate) fn settle_for_kill_tree(
&self,
caller: &str,
killed: &TreeKilled,
walk: impl Into<TreeKillOutcome>,
root_ended: bool,
) -> Result<(), Error> {
self.settle(killed, walk, root_ended)
.map(drop)
.map_err(|left| left.report(caller))
}
pub(crate) fn unless_unwalked(
&self,
caller: &str,
killed: &TreeKilled,
walk: TreeKillOutcome,
) -> Result<TreeKillOutcome, SweepFailure> {
if !matches!(walk, TreeKillOutcome::Unwalked(_)) {
return Ok(walk);
}
match self.settle_for_kill_tree(caller, killed, walk, false) {
Err(error) => Err(SweepFailure::from(error)),
Ok(()) => unreachable!("a walk not made leaves its error"),
}
}
pub(crate) fn settle_for_drop(
&self,
killed: &TreeKilled,
outcome: impl Into<TreeKillOutcome>,
root_ended: bool,
) -> Option<String> {
let outcome = outcome.into();
let after = match &outcome {
TreeKillOutcome::Unwalked(_) => "; the root is killed regardless, so its descendants may be orphaned",
TreeKillOutcome::Ran(_) | TreeKillOutcome::NoRoot | TreeKillOutcome::Skipped { .. } => "",
};
let left = match self.settle(killed, outcome, root_ended) {
Err(left) => left.to_string(),
Ok(SettleOutcome::Unvouched { kind }) => kind.drop_text(),
Ok(SettleOutcome::Killed | SettleOutcome::Skipped) => return None,
};
Some(format!("contained-tree teardown did not fully succeed: {left}{after}"))
}
#[cfg_attr(
not(unix),
allow(unused_variables, reason = "only Unix names a group by the root's pid")
)]
pub(crate) fn terminate(&self, _child_pid: u32, root: &crate::containment::GroupRoot<'_>) -> Result<(), Error> {
match self {
Attached::None | Attached::Delegated => {
debug_assert!(
self.is_actionable(),
"Attached::terminate on a non-actionable mechanism"
);
Err(crate::error::Error::Unsupported {
op: "terminate on a non-actionable mechanism".into(),
platform: std::env::consts::OS,
detail: "internal invariant: a non-actionable mechanism reached terminate".into(),
})
}
#[cfg(unix)]
Attached::ProcessGroup(pgid) => crate::containment::unix::term_group(*pgid, root),
#[cfg(target_os = "linux")]
Attached::Cgroup(leaf) => leaf.terminate(),
#[cfg(windows)]
Attached::JobObject(_) => crate::containment::windows::terminate(_child_pid),
#[cfg(target_os = "macos")]
Attached::FdMarker(m) => m.terminate(root),
Attached::TreeWalk(root) => crate::containment::treewalk::terminate(&crate::identity::HostKernel, *root),
}
}
pub(crate) fn honor_kill_on_drop(&self, kill_on_drop: bool) -> std::io::Result<()> {
if kill_on_drop {
Ok(())
} else {
self.disarm()
}
}
pub(crate) fn disarm(&self) -> std::io::Result<()> {
match self {
Attached::None | Attached::Delegated => {}
#[cfg(unix)]
Attached::ProcessGroup(_) => {} #[cfg(target_os = "linux")]
Attached::Cgroup(leaf) => leaf.disarm(), #[cfg(windows)]
Attached::JobObject(job) => return job.disarm(), #[cfg(target_os = "macos")]
Attached::FdMarker(_) => {}
Attached::TreeWalk(_) => {} }
Ok(())
}
#[cfg(all(test, unix))]
pub(crate) fn signals_a_group(&self) -> bool {
match self {
Attached::ProcessGroup(_) => true,
#[cfg(target_os = "macos")]
Attached::FdMarker(m) => m.pgid().is_some(),
_ => false,
}
}
#[cfg(unix)]
pub(crate) fn needs_root_check(&self) -> bool {
match self {
Attached::ProcessGroup(_) => true,
#[cfg(target_os = "macos")]
Attached::FdMarker(_) => true,
_ => false,
}
}
#[cfg(unix)]
pub(crate) fn named_by_root_number(&self, root_pid: u32, verb: &str) -> Option<String> {
match self {
Attached::ProcessGroup(pgid) => Some(format!("{verb} its process group (pgid {pgid})")),
#[cfg(target_os = "macos")]
Attached::FdMarker(m) => {
let walk = format!("walk the process table from the root's pid (root pid {root_pid})");
Some(match m.pgid() {
Some(pgid) => format!("{verb} its process group (pgid {pgid}) or {walk}"),
None => walk,
})
}
Attached::TreeWalk(_) => Some(format!(
"walk the process table from the root's pid (root pid {root_pid})"
)),
_ => None,
}
}
#[cfg(unix)]
pub(crate) fn hard_kill_for_drop(
&self,
view: &DropView,
root: &crate::containment::GroupRoot<'_>,
) -> TreeKillOutcome {
let action = match self.drop_reach(view, root) {
DropReach::Kill => return self.hard_kill(root),
#[cfg(target_os = "linux")]
DropReach::GroupGone => return TreeKillOutcome::Ran(Ok(())),
DropReach::Skip(action) => action,
};
let why = view.why_number_untrusted();
let (label, this) = (view.caller.label(), view.caller.this_event());
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, RootView::Reaped) {
log::debug!("{label}: {why}, so {this} does not {action}");
}
let holders = match self {
#[cfg(target_os = "macos")]
Attached::FdMarker(m) => m
.hard_kill_holders_only(m.root().filter(|_| view.unpinned_root()))
.map_err(Unkilled::from),
_ => Ok(()),
};
TreeKillOutcome::Skipped { action, holders }
}
#[cfg(unix)]
fn drop_reach(&self, view: &DropView, root: &crate::containment::GroupRoot<'_>) -> DropReach {
let reach = self.decide_drop_reach(view, root);
#[cfg(test)]
crate::graceful_hooks::run_hook(crate::graceful_hooks::HookPoint::AfterRootLook);
reach
}
#[cfg(unix)]
#[cfg_attr(not(target_os = "linux"), allow(unused_variables, reason = "only Linux has a pidfd"))]
fn decide_drop_reach(&self, view: &DropView, root: &crate::containment::GroupRoot<'_>) -> DropReach {
let Some(skipped) = view.skipped_action(self) else {
return DropReach::Kill;
};
#[cfg(target_os = "linux")]
{
use crate::child::tree_call::{through_the_pidfd, RootNumber};
let why = view.why_number_untrusted();
let number = RootNumber::MayNameAnother {
exact_root: matches!(view.root, RootView::Unknown(_)),
why: why.clone(),
};
match through_the_pidfd(self, number, root) {
RootNumber::Trusted => return DropReach::Kill,
RootNumber::GroupGone => {
log::debug!(
"{}: {why}, and its pidfd shows its process group has no member left, so nothing is sent",
view.caller.label()
);
return DropReach::GroupGone;
}
_ => {}
}
}
DropReach::Skip(skipped)
}
#[cfg(target_os = "macos")]
pub(crate) fn signal_tree_untrusted(
&self,
signal: TreeSignal,
root: &crate::signal::RootState,
root_pid: u32,
op: &str,
earlier: Option<&str>,
) -> Option<Result<(), Error>> {
let skipped = self.named_by_root_number(root_pid, signal.verb())?;
let why = crate::signal::why_untrusted(root);
let earlier = earlier.map_or_else(String::new, |sent| format!(", though {sent} was sent before it"));
let unassessable = |sent: &str, because: &str| Error::Unassessable {
detail: format!("pid {root_pid}: {why}; {op} {sent}{earlier}: {because}it did not {skipped}"),
source: None,
};
let Attached::FdMarker(m) = self else {
return Some(Err(unassessable(
"sent nothing",
"its signals are all named by the root's number, so ",
)));
};
let except = m.root().filter(|_| matches!(root, crate::signal::RootState::Unpinned));
log::debug!("{op}: {why}, so it does not {skipped}; it signals the marker holders");
Some(match signal {
TreeSignal::Kill => m
.hard_kill_holders_only(except)
.and_then(|()| Err(unassessable("signalled only the marker holders", ""))),
TreeSignal::Term => m.terminate_holders_only(except),
})
}
#[cfg(unix)]
#[cfg_attr(
not(target_os = "macos"),
allow(unused_variables, reason = "only a macOS fd marker names its tree by identity")
)]
pub(crate) fn signal_holders_only(&self, signal: TreeSignal) -> Option<Result<(), Error>> {
match self {
#[cfg(target_os = "macos")]
Attached::FdMarker(m) => Some(match signal {
TreeSignal::Kill => m.hard_kill_holders_only(None),
TreeSignal::Term => m.terminate_holders_only(None),
}),
_ => None,
}
}
#[cfg(target_os = "macos")]
pub(crate) fn fd_marker_has_group(&self) -> Option<bool> {
match self {
Attached::FdMarker(m) => Some(m.pgid().is_some()),
_ => None,
}
}
#[cfg(target_os = "macos")]
pub(crate) fn signal_group_and_holders(
&self,
signal: TreeSignal,
root: &crate::containment::GroupRoot<'_>,
) -> Option<Result<(), Error>> {
let Attached::FdMarker(m) = self else {
return None;
};
Some(match signal {
TreeSignal::Kill => m.hard_kill_group_and_holders(root),
TreeSignal::Term => m.terminate_group_and_holders(root),
})
}
#[cfg(target_os = "macos")]
pub(crate) fn names_tree_by_identity(&self) -> bool {
matches!(self, Attached::FdMarker(_))
}
#[cfg(unix)]
pub(crate) fn is_cgroup(&self) -> bool {
#[cfg(target_os = "linux")]
return matches!(self, Attached::Cgroup(_));
#[cfg(not(target_os = "linux"))]
false
}
pub(crate) fn is_actionable(&self) -> bool {
match self {
Attached::None | Attached::Delegated => false,
#[cfg(unix)]
Attached::ProcessGroup(_) => true,
#[cfg(target_os = "linux")]
Attached::Cgroup(_) => true,
#[cfg(windows)]
Attached::JobObject(_) => true,
#[cfg(target_os = "macos")]
Attached::FdMarker(_) => true,
Attached::TreeWalk(_) => true,
}
}
#[cfg(feature = "tokio")]
pub(crate) fn release_without_waiting(self) {
match self {
#[cfg(target_os = "linux")]
Attached::Cgroup(leaf) => leaf.release_without_waiting(),
other => drop(other),
}
}
pub(crate) fn can_observe_drain(&self) -> bool {
match self {
#[cfg(target_os = "linux")]
Attached::Cgroup(_) => true,
#[cfg(windows)]
Attached::JobObject(_) => true,
#[cfg(target_os = "macos")]
Attached::FdMarker(_) => true,
_ => false,
}
}
pub(crate) fn wait_drained(
&self,
deadline: Option<std::time::Instant>,
) -> Result<crate::containment::TreeDrain, Error> {
#[cfg(feature = "tokio")]
crate::bounded::assert_may_block("waiting for the contained tree to drain");
match self {
#[cfg(target_os = "linux")]
Attached::Cgroup(leaf) => leaf.wait_drained(deadline),
#[cfg(windows)]
Attached::JobObject(job) => job.wait_drained(deadline, None),
#[cfg(target_os = "macos")]
Attached::FdMarker(m) => m.wait_drained(deadline),
_ => Err(Error::Unsupported {
op: "wait for the contained tree to drain".into(),
platform: std::env::consts::OS,
detail: "this child's containment mechanism exposes no kernel edge for tree drain".into(),
}),
}
}
}
pub(crate) fn is_nested(marker_present: bool) -> bool {
marker_present
}
#[cfg_attr(
not(target_os = "macos"),
allow(dead_code, reason = "only macOS leaves a child unverified")
)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum RootIdentity {
Gone,
Unknown,
}
#[cfg(unix)]
impl crate::child::owned::teardown::Reach for Attached {
#[cfg_attr(
not(target_os = "linux"),
allow(unused_variables, reason = "only a Linux cgroup reads it")
)]
fn reached(&self, child: &crate::child::owned::OwnedChild) -> std::io::Result<bool> {
#[cfg(target_os = "linux")]
if let Attached::Cgroup(leaf) = self {
return leaf.subtree()?.reached(child);
}
Ok(false)
}
}
#[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: is_root && req.nesting == Nesting::Mark,
}
}
pub(crate) fn prepare(
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],
) -> 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(all(target_os = "linux", feature = "tokio"))]
teardown_warn_after: None,
#[cfg(target_os = "macos")]
marker: None,
#[cfg(windows)]
graceful,
#[cfg(windows)]
frozen: flags.suspended,
});
}
let marker_env = is_root && req.nesting == Nesting::Mark;
#[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(not(windows))]
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, #[cfg(all(target_os = "linux", feature = "tokio"))]
teardown_warn_after: None,
});
}
UnixSetup::None => {
return Ok(Prepared {
mode,
is_root,
cgroup_leaf: None,
#[cfg(all(target_os = "linux", feature = "tokio"))]
teardown_warn_after: None,
});
}
UnixSetup::ProcessGroup => {
crate::containment::unix::set_process_group(std_cmd);
}
}
let leaf = match crate::containment::cgroup::try_create_leaf() {
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(), l.placement_slot()) };
}
return Ok(Prepared {
mode,
is_root,
cgroup_leaf: leaf,
#[cfg(all(target_os = "linux", feature = "tokio"))]
teardown_warn_after: None,
});
}
return Ok(Prepared {
mode,
is_root,
cgroup_leaf: None,
#[cfg(all(target_os = "linux", feature = "tokio"))]
teardown_warn_after: 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) {
crate::containment::fdmarker::install(steps, reserved_fds)
} 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(all(target_os = "linux", feature = "tokio"))]
teardown_warn_after: None,
#[cfg(target_os = "macos")]
marker,
#[cfg(windows)]
graceful,
#[cfg(windows)]
frozen: flags.suspended,
})
}
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, Error> {
let graceful = prepared.graceful_mechanism();
let (containment, attached) = attach_tree(
#[cfg(unix)]
pid,
id,
#[cfg(target_os = "linux")]
child,
#[cfg(windows)]
proc_handle,
prepared,
)?;
Ok(Attachment {
containment,
attached,
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<(Containment, Attached), Error> {
#[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((Containment::TreeWalk, Attached::TreeWalk(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((Containment::Session, Attached::ProcessGroup(pgid)));
}
if let Some(mut leaf) = prepared.cgroup_leaf.take() {
match leaf.take_placement(child) {
Ok(()) => return Ok((Containment::CgroupV2, Attached::Cgroup(leaf))),
Err(reason) => {
crate::containment::cgroup::log_degrade(&reason);
leaf.remove_unentered();
return Ok((Containment::ProcessGroup, Attached::ProcessGroup(pgid)));
}
}
}
return Ok((Containment::ProcessGroup, Attached::ProcessGroup(pgid)));
} else {
return Ok((Containment::Delegated, Attached::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((
Containment::FdMarker,
Attached::FdMarker(crate::containment::fdmarker::Marker::new(marker, id?, pgid)),
));
}
if matches!(prepared.mode, Some(ContainMode::TreeWalk)) {
return Ok((Containment::TreeWalk, Attached::TreeWalk(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 containment = match prepared.mode {
Some(ContainMode::Session) => Containment::Session,
_ => Containment::ProcessGroup,
};
return Ok((containment, Attached::ProcessGroup(pgid)));
} 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((Containment::Delegated, Attached::Delegated));
}
}
}
#[cfg(windows)]
{
if prepared.mode.is_some() && prepared.is_root {
if matches!(prepared.mode, Some(ContainMode::TreeWalk)) {
return Ok((Containment::TreeWalk, Attached::TreeWalk(id?)));
}
if prepared.frozen {
return match crate::containment::windows::assign_held(proc_handle) {
Ok(job) => Ok((Containment::JobObject, Attached::JobObject(job))),
Err(e) => Err(Error::Containment { detail: e.to_string() }),
};
}
match crate::containment::windows::attach_job(proc_handle) {
Ok(Some(job)) => return Ok((Containment::JobObject, Attached::JobObject(job))),
Ok(None) => {
return Ok((Containment::TreeWalk, Attached::TreeWalk(id?)));
}
Err(e) => return Err(Error::Containment { detail: e.to_string() }),
}
} else if prepared.mode.is_some() {
return Ok((Containment::Delegated, Attached::Delegated));
}
}
let _ = prepared;
Ok((Containment::None, Attached::None))
}
#[cfg(test)]
#[path = "dispatch_tests.rs"]
mod dispatch_tests;