use crate::containment::dispatch::{TreeKillOutcome, Unkilled};
use crate::error::Error;
use crate::identity::{resolution_of, Kernel, OrderKey, ProcessId, RawPid, Resolution};
use crate::Recursive;
#[derive(Debug)]
pub(crate) enum KillOutcome {
Terminated,
AlreadyGone,
NotAttempted(Error),
}
#[cfg(unix)]
pub(crate) fn warn_if_not_attempted(id: ProcessId, signal: Signal, outcome: &KillOutcome) {
if let KillOutcome::NotAttempted(why) = outcome {
log::warn!("treewalk: pid {} was sent no {signal}: {why}", id.pid());
}
}
#[derive(Debug, Default)]
pub(crate) struct Walk {
pub(crate) members: Vec<ProcessId>,
pub(crate) unassessed: Vec<(RawPid, Error)>,
}
impl Walk {
pub(crate) fn complete_members(self) -> Result<Vec<ProcessId>, Error> {
let Walk { members, unassessed } = self;
let mut unassessed = unassessed.into_iter();
let Some((_, first)) = unassessed.next() else {
return Ok(members);
};
let others: Vec<String> = unassessed
.map(|(pid, why)| format!("pid {pid} ({})", cause_text(&why)))
.collect();
Err(if others.is_empty() {
first
} else {
first.with_note(&format!(
"the walk could not assess these either: {}",
others.join("; ")
))
})
}
}
fn cause_text(why: &Error) -> String {
match why {
Error::Unassessable { detail, .. } => detail.clone(),
other => other.to_string(),
}
}
#[cfg(unix)]
pub(crate) fn warn_unassessed(unassessed: &[(RawPid, Error)]) {
for (pid, why) in unassessed {
log::warn!("treewalk: pid {pid} dropped from the walk ({})", cause_text(why));
}
}
pub(crate) fn resolve_or_drop(
kernel: &dyn Kernel,
pid: RawPid,
parent: ProcessId,
bound: Option<OrderKey>,
) -> Resolution {
resolution_of(
"pid",
pid,
ProcessId::of_ordered_with(kernel, pid, Some(parent), None, bound),
)
}
#[cfg(unix)]
use nix::sys::signal::Signal;
pub(crate) fn descendants_with(
root: ProcessId,
root_bound: Option<OrderKey>,
parents: &[(RawPid, RawPid)],
resolve: impl Fn(RawPid, ProcessId, Option<OrderKey>) -> Resolution,
) -> Walk {
let mut walk = Walk::default();
let mut frontier: Vec<(ProcessId, Option<OrderKey>)> = vec![(root, root_bound)];
let mut pending: Vec<(RawPid, RawPid)> = parents.to_vec();
let mut accepted: std::collections::HashSet<RawPid> = std::collections::HashSet::new();
let mut resolved: std::collections::HashMap<RawPid, Option<(ProcessId, Option<OrderKey>)>> =
std::collections::HashMap::new();
while !frontier.is_empty() {
let mut next: Vec<(ProcessId, Option<OrderKey>)> = Vec::new();
let mut still_pending: Vec<(RawPid, RawPid)> = Vec::with_capacity(pending.len());
for (pid, ppid) in pending.drain(..) {
let Some(&(parent, bound)) = frontier.iter().find(|(p, _)| p.pid() == ppid) else {
still_pending.push((pid, ppid));
continue;
};
if pid == ppid {
continue;
}
let read = *resolved
.entry(pid)
.or_insert_with(|| match resolve(pid, parent, bound) {
Ok(None) => {
log::debug!(
"treewalk: pid {pid} gone, or an impostor (recycled pid / stale ppid) - dropping its subtree"
);
None
}
Ok(read) => read,
Err(why) => {
walk.unassessed.push((pid, why));
None
}
});
let Some((id, children_bound)) = read else {
continue;
};
if accepted.insert(pid) {
walk.members.push(id);
next.push((id, children_bound));
}
}
pending = still_pending;
frontier = next;
}
walk
}
fn anchor(kernel: &dyn Kernel, anchor: ProcessId) -> Result<Option<AnchorProof>, Error> {
let proof = resolution_of("pid", anchor.pid(), anchor.anchor_bound_with(kernel))?;
if proof.is_none() {
log::debug!("treewalk: pid {pid} is gone - walking nothing", pid = anchor.pid());
}
Ok(proof.map(|bound| AnchorProof { bound }))
}
struct AnchorProof {
bound: Option<OrderKey>,
}
pub(crate) fn children_of_with(
parent: ProcessId,
parent_bound: Option<OrderKey>,
parents: &[(RawPid, RawPid)],
resolve: impl Fn(RawPid, ProcessId, Option<OrderKey>) -> Resolution,
) -> Walk {
let mut walk = Walk::default();
let mut resolved = std::collections::HashSet::new();
for &(pid, ppid) in parents {
if ppid != parent.pid() || pid == ppid || !resolved.insert(pid) {
continue;
}
match resolve(pid, parent, parent_bound) {
Ok(Some((id, _))) => walk.members.push(id),
Ok(None) => {
log::debug!(
"treewalk: pid {pid} gone, or an impostor (recycled pid / stale ppid) - dropped from children"
);
}
Err(why) => walk.unassessed.push((pid, why)),
}
}
walk
}
pub(crate) fn walk_from(
kernel: &dyn Kernel,
root: ProcessId,
parents: &[(RawPid, RawPid)],
depth: Recursive,
) -> Result<Option<Walk>, Error> {
let Some(AnchorProof { bound: root_bound }) = anchor(kernel, root)? else {
return Ok(None);
};
let resolve = |pid, parent, bound| resolve_or_drop(kernel, pid, parent, bound);
Ok(Some(match depth {
Recursive::No => children_of_with(root, root_bound, parents, resolve),
Recursive::Yes => descendants_with(root, root_bound, parents, resolve),
}))
}
#[cfg(any(all(unix, not(target_os = "linux")), windows))]
fn identity_unread(detail: String, source: Option<std::io::Error>) -> KillOutcome {
KillOutcome::NotAttempted(Error::Unassessable { detail, source })
}
#[cfg(any(unix, windows))]
fn refused(os: std::io::Error) -> KillOutcome {
KillOutcome::NotAttempted(Error::Io(os))
}
#[cfg(target_os = "linux")]
pub(crate) fn kill_by_identity(kernel: &dyn Kernel, id: ProcessId, signal: Signal) -> KillOutcome {
use std::os::fd::AsFd as _;
use nix::errno::Errno;
use crate::os_process::linux::open::OpenFailure;
match crate::os_process::linux::open::open_verified_with(kernel, id) {
Ok(None) => {
log::debug!(
"treewalk: skipping pid {pid} - identity changed or gone since the snapshot",
pid = id.pid()
);
KillOutcome::AlreadyGone
}
Ok(Some(pidfd)) => {
let sent = crate::containment::unix::pidfd_signal_member(pidfd.as_fd(), id.pid(), signal);
#[cfg(test)]
crate::send_log::record_by_identity(id.pid(), signal as i32);
match sent {
Ok(()) => KillOutcome::Terminated,
Err(Errno::ESRCH) => KillOutcome::AlreadyGone,
Err(e) => refused(e.into()),
}
}
Err(OpenFailure::Call(call)) => {
KillOutcome::NotAttempted(crate::identity::call_error(&format!("pid {}", id.pid()), call))
}
Err(OpenFailure::Finished(error)) => KillOutcome::NotAttempted(match error {
error @ (Error::Unassessable { .. } | Error::Unsupported { .. }) => error,
other => unproved(id.pid(), other),
}),
}
}
#[cfg(target_os = "linux")]
fn unproved(pid: RawPid, error: Error) -> Error {
Error::Unassessable {
detail: format!("pid {pid} identity could not be confirmed: its pidfd could not be proved to name it: {error}"),
source: Some(std::io::Error::other(error)),
}
}
#[cfg(all(unix, not(target_os = "linux")))]
pub(crate) fn kill_by_identity(kernel: &dyn Kernel, id: ProcessId, signal: Signal) -> KillOutcome {
use nix::sys::signal::kill;
use nix::unistd::Pid;
use crate::identity::Resolved;
match ProcessId::of_with(kernel, id.pid()).0 {
Resolved::Found(live) if live == id => {}
Resolved::Found(_) | Resolved::Gone => {
log::debug!(
"treewalk: skipping pid {pid} - identity changed since the snapshot",
pid = id.pid()
);
return KillOutcome::AlreadyGone;
}
Resolved::Unknown => {
return identity_unread("it could not be queried (access denied?)".to_owned(), None);
}
}
let Some(target) = crate::identity::probe::signal_target(id.pid()) else {
return identity_unread("it is not a single-process signal target".to_owned(), None);
};
let sent = kill(Pid::from_raw(target), signal);
#[cfg(test)]
crate::send_log::record_by_identity(id.pid(), signal as i32);
match sent {
Ok(()) => KillOutcome::Terminated,
Err(nix::errno::Errno::ESRCH) => KillOutcome::AlreadyGone,
Err(e) => refused(e.into()),
}
}
#[cfg(windows)]
pub(crate) fn kill_by_identity(id: ProcessId) -> KillOutcome {
use windows::Win32::System::Threading::{PROCESS_QUERY_LIMITED_INFORMATION, PROCESS_TERMINATE};
use crate::identity::{
windows_close, windows_open_classified, windows_terminate_held, HandleIdentity, Opened, Termination,
};
let rights = PROCESS_TERMINATE | PROCESS_QUERY_LIMITED_INFORMATION;
let handle = match windows_open_classified(id.pid(), rights) {
Opened::Found(h) => h,
Opened::Gone => return KillOutcome::AlreadyGone,
Opened::Denied(e) => {
return identity_unread(
format!("it could not be queried (access denied?) - not opened to terminate ({e})"),
Some(crate::error::win32_io_error(e)),
);
}
};
let outcome = match crate::identity::windows_handle_identity(handle, id) {
HandleIdentity::Same => {
#[cfg(test)]
fault::run_before_terminate();
match windows_terminate_held(handle, rights) {
Termination::Terminated => KillOutcome::Terminated,
Termination::Exited => KillOutcome::AlreadyGone,
Termination::Failed(e) => refused(crate::error::win32_io_error(e)),
}
}
HandleIdentity::Different => {
log::debug!(
"treewalk: skipping pid {} - identity changed since the snapshot",
id.pid()
);
KillOutcome::AlreadyGone
}
HandleIdentity::Unreadable(e) => identity_unread(
format!("it opened but its identity could not be read ({e}) - not terminated"),
Some(crate::error::win32_io_error(e)),
),
};
windows_close(handle);
outcome
}
pub(crate) fn hard_kill(kernel: &dyn Kernel, root: ProcessId) -> TreeKillOutcome {
#[cfg(test)]
let skip_root = fault::take_force_root_kill_noop();
#[cfg(not(test))]
let skip_root = false;
let Walk {
members: descendants,
unassessed,
} = match crate::containment::enumerate::process_parents(kernel)
.and_then(|parents| walk_from(kernel, root, &parents, Recursive::Yes))
{
Ok(Some(walk)) => walk,
Ok(None) => return TreeKillOutcome::NoRoot,
Err(error) => return TreeKillOutcome::Unwalked(error),
};
#[cfg(test)]
fault::note_walk(root.pid());
let mut left: Vec<Error> = unassessed.into_iter().map(|(pid, why)| not_killed(pid, why)).collect();
let mut root_left: Option<Error> = None;
#[cfg(all(test, unix))]
if let Some(forced) = fault::take_force_incomplete() {
let forced_error = |pid| {
not_killed(
pid,
Error::Containment {
detail: "the walk was forced incomplete".into(),
},
)
};
if forced.leaves_root() {
root_left = Some(forced_error(root.pid()));
}
if forced.leaves_descendant() {
left.push(forced_error(root.pid().wrapping_add(1)));
}
}
let mut resolved = Vec::new();
#[cfg(any(unix, windows))]
{
if !skip_root {
root_left = left_behind(root, kill_one(kernel, root)).or(root_left);
}
for id in descendants {
if let Some(error) = left_behind(id, kill_one(kernel, id)) {
left.push(error);
resolved.push(id);
}
}
}
#[cfg(not(any(unix, windows)))]
let _ = (kernel, root, descendants, skip_root);
if left.is_empty() && root_left.is_none() {
return TreeKillOutcome::Ran(Ok(()));
}
TreeKillOutcome::Ran(Err(Unkilled {
members: left,
root: root_left,
resolved,
}))
}
#[cfg(any(unix, windows))]
fn kill_one(kernel: &dyn Kernel, id: ProcessId) -> KillOutcome {
#[cfg(unix)]
return kill_by_identity(kernel, id, Signal::SIGKILL);
#[cfg(windows)]
{
let _ = kernel;
kill_by_identity(id)
}
}
#[derive(Debug, Clone)]
pub(crate) enum Left {
Resolved(ProcessId),
Unread { pid: RawPid, said: String },
}
impl Left {
pub(crate) fn of(left: &Unkilled) -> Vec<Left> {
let last = left.members.len().saturating_sub(1);
left.members
.iter()
.enumerate()
.filter_map(|(at, member)| {
let Error::MemberNotKilled { pid, source, .. } = member else {
debug_assert!(
at == last
&& left.root.is_none()
&& matches!(member, Error::Unassessable { .. } | Error::Unsupported { .. }),
"only the error of a walk not made is not a `MemberNotKilled`, and it is last: {left:?}"
);
return None;
};
Some(match left.resolved.iter().find(|id| id.pid() == *pid) {
Some(id) => Left::Resolved(*id),
None => Left::Unread {
pid: *pid,
said: match &**source {
Error::Unassessable { detail, .. } => detail.clone(),
other => other.to_string(),
},
},
})
})
.collect()
}
fn pid(&self) -> RawPid {
match self {
Left::Resolved(id) => id.pid(),
Left::Unread { pid, .. } => *pid,
}
}
}
pub(crate) fn with_earlier(
kernel: &dyn Kernel,
earlier: Vec<Left>,
walked: Result<(), Unkilled>,
) -> Result<(), Unkilled> {
let mut walked = match walked {
Ok(()) => Unkilled {
members: Vec::new(),
root: None,
resolved: Vec::new(),
},
Err(left) => left,
};
let named: Vec<RawPid> = walked
.members
.iter()
.filter_map(|member| match member {
Error::MemberNotKilled { pid, .. } => Some(*pid),
_ => None,
})
.collect();
let mut members = Vec::new();
for left in earlier.into_iter().filter(|left| !named.contains(&left.pid())) {
match left {
Left::Resolved(id) => {
#[cfg(any(unix, windows))]
if let Some(error) = left_behind(id, kill_one(kernel, id)) {
members.push(error);
walked.resolved.push(id);
}
#[cfg(not(any(unix, windows)))]
let _ = (kernel, id);
}
Left::Unread { pid, said } => members.push(not_killed(
pid,
Error::Unassessable {
detail: said,
source: None,
},
)),
}
}
if members.is_empty() && walked.members.is_empty() && walked.root.is_none() {
return Ok(());
}
members.append(&mut walked.members);
walked.members = members;
Err(walked)
}
fn not_killed(pid: RawPid, source: Error) -> Error {
Error::MemberNotKilled {
pid,
source: Box::new(source),
note: None,
}
}
#[cfg(any(unix, windows))]
fn left_behind(id: ProcessId, outcome: KillOutcome) -> Option<Error> {
match outcome {
KillOutcome::NotAttempted(source) => Some(not_killed(id.pid(), source)),
KillOutcome::Terminated | KillOutcome::AlreadyGone => None,
}
}
#[cfg(test)]
pub(crate) mod fault {
use std::cell::{Cell, RefCell};
thread_local! {
static FORCE_ROOT_KILL_NOOP: Cell<bool> = const { Cell::new(false) };
static WALKS: RefCell<Option<Vec<u32>>> = const { RefCell::new(None) };
#[cfg(unix)]
static FORCE_INCOMPLETE: Cell<Option<LeftBehind>> = const { Cell::new(None) };
#[cfg(windows)]
static BEFORE_TERMINATE: RefCell<Option<Box<dyn FnOnce()>>> = const { RefCell::new(None) };
}
#[cfg(windows)]
pub(crate) fn set_before_terminate(hook: impl FnOnce() + 'static) {
BEFORE_TERMINATE.with(|h| *h.borrow_mut() = Some(Box::new(hook)));
}
#[cfg(windows)]
pub(super) fn run_before_terminate() {
if let Some(hook) = BEFORE_TERMINATE.with(|h| h.borrow_mut().take()) {
hook();
}
}
#[cfg(unix)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum LeftBehind {
Root,
Descendant,
#[cfg(not(target_os = "macos"))]
RootAndDescendant,
}
#[cfg(unix)]
impl LeftBehind {
pub(super) fn leaves_root(self) -> bool {
match self {
LeftBehind::Root => true,
LeftBehind::Descendant => false,
#[cfg(not(target_os = "macos"))]
LeftBehind::RootAndDescendant => true,
}
}
pub(super) fn leaves_descendant(self) -> bool {
match self {
LeftBehind::Root => false,
LeftBehind::Descendant => true,
#[cfg(not(target_os = "macos"))]
LeftBehind::RootAndDescendant => true,
}
}
}
#[cfg(unix)]
pub(crate) fn force_incomplete_once(left: LeftBehind) {
FORCE_INCOMPLETE.with(|f| f.set(Some(left)));
}
#[cfg(unix)]
pub(super) fn take_force_incomplete() -> Option<LeftBehind> {
FORCE_INCOMPLETE.with(|f| f.take())
}
#[cfg(unix)]
pub(crate) fn record_walks() -> WalkRecorder {
WALKS.with(|w| *w.borrow_mut() = Some(Vec::new()));
WalkRecorder(())
}
#[cfg(unix)]
#[must_use = "recording stops as soon as the recorder is dropped"]
pub(crate) struct WalkRecorder(());
#[cfg(unix)]
impl WalkRecorder {
pub(crate) fn walked(&self) -> Vec<u32> {
WALKS.with(|w| w.borrow().clone().expect("the recorder is live"))
}
}
#[cfg(unix)]
impl Drop for WalkRecorder {
fn drop(&mut self) {
WALKS.with(|w| *w.borrow_mut() = None);
}
}
pub(crate) fn note_walk(root_pid: u32) {
WALKS.with(|w| {
if let Some(walked) = w.borrow_mut().as_mut() {
walked.push(root_pid);
}
});
}
#[cfg_attr(
target_os = "macos",
allow(
dead_code,
reason = "dispatch_tests.rs uses the fdmarker::fault seam on macOS instead"
)
)]
pub(crate) fn set_force_root_kill_noop(on: bool) {
FORCE_ROOT_KILL_NOOP.with(|f| f.set(on));
}
pub(crate) fn take_force_root_kill_noop() -> bool {
FORCE_ROOT_KILL_NOOP.with(|f| f.replace(false))
}
#[cfg_attr(
target_os = "macos",
allow(
dead_code,
reason = "dispatch_tests.rs uses the fdmarker::fault seam on macOS instead"
)
)]
pub(crate) fn armed() -> bool {
FORCE_ROOT_KILL_NOOP.with(|f| f.get())
}
}
pub(crate) fn terminate(kernel: &dyn Kernel, root: ProcessId) -> Result<(), Error> {
#[cfg(unix)]
{
let parents = crate::containment::enumerate::process_parents(kernel)?;
let Some(walk) = walk_from(kernel, root, &parents, Recursive::Yes)? else {
return Ok(());
};
#[cfg(test)]
fault::note_walk(root.pid());
warn_unassessed(&walk.unassessed);
for id in std::iter::once(root).chain(walk.members) {
warn_if_not_attempted(id, Signal::SIGTERM, &kill_by_identity(kernel, id, Signal::SIGTERM));
}
Ok(())
}
#[cfg(windows)]
{
let _ = kernel;
crate::containment::windows::terminate(root.pid())
}
#[cfg(not(any(unix, windows)))]
{
let _ = (kernel, root);
Ok(())
}
}
#[cfg(test)]
#[path = "treewalk_tests.rs"]
mod treewalk_tests;
#[cfg(all(test, target_os = "linux"))]
#[path = "treewalk_view_tests.rs"]
mod treewalk_view_tests;
#[cfg(all(test, target_os = "linux"))]
#[path = "treewalk_pidfs_tests.rs"]
mod treewalk_pidfs_tests;
#[cfg(all(test, target_os = "macos"))]
#[path = "treewalk_blind_tests.rs"]
mod treewalk_blind_tests;
#[cfg(all(test, windows))]
#[path = "treewalk_toolhelp_tests.rs"]
mod treewalk_toolhelp_tests;