use crate::error::Error;
use crate::identity::{Existence, ProcessId, RawPid, Resolved, UnknownCause};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum KillOutcome {
Terminated,
AlreadyGone,
NotAttempted,
}
pub(crate) fn resolve_or_drop(pid: RawPid) -> Option<ProcessId> {
match ProcessId::of(pid) {
Resolved::Found(id) => Some(id),
Resolved::Gone => None,
Resolved::Unknown => {
log::warn!("treewalk: pid {pid} could not be queried (access denied?) - dropped from the walk");
None
}
}
}
#[cfg(unix)]
use nix::sys::signal::Signal;
#[cfg(any(target_os = "linux", target_os = "macos"))]
pub(crate) const ALLOW_EQUAL_TOKEN: bool = true;
#[cfg(windows)]
pub(crate) const ALLOW_EQUAL_TOKEN: bool = false;
#[cfg(all(unix, not(any(target_os = "linux", target_os = "macos"))))]
pub(crate) const ALLOW_EQUAL_TOKEN: bool = false;
pub(crate) fn keeps_token(token: u64, anchor: u64, allow_equal: bool) -> bool {
token > anchor || (allow_equal && token == anchor)
}
pub(crate) fn descendants_with(
root: ProcessId,
parents: &[(RawPid, RawPid)],
allow_equal: bool,
resolve: impl Fn(RawPid) -> Option<ProcessId>,
) -> Vec<ProcessId> {
let root_token = root.start_token_raw();
let keep = |token: u64| keeps_token(token, root_token, allow_equal);
let mut result: Vec<ProcessId> = Vec::new();
let mut frontier: Vec<RawPid> = vec![root.pid()];
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>> = std::collections::HashMap::new();
while !frontier.is_empty() {
let mut next: Vec<RawPid> = Vec::new();
let mut still_pending: Vec<(RawPid, RawPid)> = Vec::with_capacity(pending.len());
for (pid, ppid) in pending.drain(..) {
if !frontier.contains(&ppid) {
still_pending.push((pid, ppid));
continue;
}
if pid == ppid {
continue;
}
let id = *resolved.entry(pid).or_insert_with(|| resolve(pid));
let Some(id) = id else {
log::debug!("treewalk: pid {pid} unresolvable — dropping its subtree");
continue;
};
if !keep(id.start_token_raw()) {
log::debug!("treewalk: dropping subtree under impostor pid {pid} (recycled pid / stale ppid)");
continue;
}
if accepted.insert(pid) {
result.push(id);
next.push(pid);
}
}
pending = still_pending;
frontier = next;
}
result
}
pub(crate) fn descendants(root: ProcessId, parents: &[(RawPid, RawPid)]) -> Vec<ProcessId> {
descendants_with(root, parents, ALLOW_EQUAL_TOKEN, resolve_or_drop)
}
pub(crate) fn children_of_with(
parent: ProcessId,
parents: &[(RawPid, RawPid)],
allow_equal: bool,
resolve: impl Fn(RawPid) -> Option<ProcessId>,
) -> Vec<ProcessId> {
let ptoken = parent.start_token_raw();
let mut out = Vec::new();
let mut seen = std::collections::HashSet::new();
for &(pid, ppid) in parents {
if ppid != parent.pid() || pid == ppid {
continue;
}
let Some(id) = resolve(pid) else {
log::debug!("treewalk: pid {pid} unresolvable — dropped from children");
continue;
};
if !keeps_token(id.start_token_raw(), ptoken, allow_equal) {
log::debug!("treewalk: dropping impostor pid {pid} (recycled pid / stale ppid)");
continue;
}
if seen.insert(pid) {
out.push(id);
}
}
out
}
pub(crate) fn children_of(parent: ProcessId, parents: &[(RawPid, RawPid)]) -> Vec<ProcessId> {
children_of_with(parent, parents, ALLOW_EQUAL_TOKEN, resolve_or_drop)
}
#[cfg(unix)]
pub(crate) fn kill_by_identity(id: ProcessId, signal: Signal) -> KillOutcome {
use nix::sys::signal::kill;
use nix::unistd::Pid;
match ProcessId::of(id.pid()) {
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 => {
log::warn!(
"treewalk: pid {pid} could not be queried (access denied?) - not signaled, left running",
pid = id.pid()
);
return KillOutcome::NotAttempted;
}
}
let Some(target) = crate::identity::probe::signal_target(id.pid()) else {
log::warn!(
"treewalk: pid {} is not a single-process signal target - not signaled",
id.pid()
);
return KillOutcome::NotAttempted;
};
#[cfg(test)]
crate::send_log::record_by_identity(id.pid(), signal as i32);
match kill(Pid::from_raw(target), signal) {
Ok(()) => KillOutcome::Terminated,
Err(nix::errno::Errno::ESRCH) => KillOutcome::AlreadyGone,
Err(e) => {
log::warn!("treewalk: kill(pid {}, {signal:?}) failed: {e}", id.pid());
KillOutcome::NotAttempted
}
}
}
#[cfg(windows)]
pub(crate) fn kill_by_identity(id: ProcessId) -> KillOutcome {
use windows::Win32::System::Threading::{TerminateProcess, PROCESS_QUERY_LIMITED_INFORMATION, PROCESS_TERMINATE};
use crate::identity::{windows_close, windows_open_classified, HandleIdentity, Opened};
let handle = match windows_open_classified(id.pid(), PROCESS_TERMINATE | PROCESS_QUERY_LIMITED_INFORMATION) {
Opened::Found(h) => h,
Opened::Gone => return KillOutcome::AlreadyGone,
Opened::Denied(e) => {
log::warn!(
"treewalk: pid {} could not be queried (access denied?) - not opened to terminate ({e}), left running",
id.pid()
);
return KillOutcome::NotAttempted;
}
};
let outcome = match crate::identity::windows_handle_identity(handle, id) {
HandleIdentity::Same => {
match unsafe { TerminateProcess(handle, 1) } {
Ok(()) => KillOutcome::Terminated,
Err(e) => {
log::warn!("treewalk: TerminateProcess(pid {}) failed: {e}", id.pid());
KillOutcome::NotAttempted
}
}
}
HandleIdentity::Different => {
log::debug!(
"treewalk: skipping pid {} - identity changed since the snapshot",
id.pid()
);
KillOutcome::AlreadyGone
}
HandleIdentity::Unreadable(e) => {
log::warn!(
"treewalk: pid {} opened but its identity could not be read ({e}) - not terminated",
id.pid()
);
KillOutcome::NotAttempted
}
};
windows_close(handle);
outcome
}
pub(crate) fn anchor_present(root: ProcessId) -> Result<bool, Error> {
match root.exists_explained() {
(Existence::Present, _) => Ok(true),
(Existence::Gone, _) => Ok(false),
(Existence::Unknown, cause) => Err(unqueryable(&format!("pid {}", root.pid()), cause)),
}
}
pub(crate) fn unqueryable(subject: &str, cause: UnknownCause) -> Error {
cause.into_error(subject).unwrap_or_else(|| Error::Unassessable {
detail: format!("{subject} exists but could not be queried (access denied?)"),
source: None,
})
}
pub(crate) fn hard_kill(root: ProcessId) -> Result<bool, Error> {
#[cfg(test)]
fault::note_walk(root.pid());
#[cfg(test)]
let skip_root = fault::take_force_root_kill_noop();
#[cfg(not(test))]
let skip_root = false;
let parents = crate::containment::enumerate::process_parents()?;
if !anchor_present(root)? {
return Ok(true);
}
let mut complete = true;
#[cfg(test)]
if fault::take_force_incomplete() {
complete = false;
}
let descendants = descendants(root, &parents);
#[cfg(unix)]
{
if !skip_root {
complete &= kill_by_identity(root, Signal::SIGKILL) != KillOutcome::NotAttempted;
}
for id in descendants {
complete &= kill_by_identity(id, Signal::SIGKILL) != KillOutcome::NotAttempted;
}
}
#[cfg(windows)]
{
if !skip_root {
complete &= kill_by_identity(root) != KillOutcome::NotAttempted;
}
for id in descendants {
complete &= kill_by_identity(id) != KillOutcome::NotAttempted;
}
}
#[cfg(not(any(unix, windows)))]
let _ = (root, descendants, skip_root);
Ok(complete)
}
#[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) };
static FORCE_INCOMPLETE: Cell<bool> = const { Cell::new(false) };
}
#[cfg(all(unix, not(target_os = "macos")))]
pub(crate) fn force_incomplete_once() {
FORCE_INCOMPLETE.with(|f| f.set(true));
}
pub(super) fn take_force_incomplete() -> bool {
FORCE_INCOMPLETE.with(|f| f.replace(false))
}
#[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(root: ProcessId) -> Result<(), Error> {
#[cfg(unix)]
{
let parents = crate::containment::enumerate::process_parents()?;
if !anchor_present(root)? {
return Ok(());
}
let descendants = descendants(root, &parents);
let _ = kill_by_identity(root, Signal::SIGTERM);
for id in descendants {
let _ = kill_by_identity(id, Signal::SIGTERM);
}
Ok(())
}
#[cfg(windows)]
{
crate::containment::windows::terminate(root.pid())
}
#[cfg(not(any(unix, windows)))]
{
let _ = 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 = "macos"))]
#[path = "treewalk_blind_tests.rs"]
mod treewalk_blind_tests;
#[cfg(all(test, windows))]
#[path = "treewalk_toolhelp_tests.rs"]
mod treewalk_toolhelp_tests;