use std::os::fd::{AsFd, AsRawFd, BorrowedFd};
use std::time::Instant;
use crate::identity::RawPid;
pub(crate) const PROC_PIDFDPIPEINFO: libc::c_int = 6;
pub(crate) const PROC_FP_CLEXEC: u32 = 2;
#[repr(C)]
#[derive(Clone, Copy)]
pub(crate) struct ProcFileInfo {
fi_openflags: u32,
fi_status: u32,
fi_offset: i64,
fi_type: i32,
fi_guardflags: u32,
}
#[repr(C)]
#[derive(Clone, Copy)]
pub(crate) struct PipeFdInfo {
pfi: ProcFileInfo,
pipe_stat: libc::vinfo_stat,
pub(crate) pipe_handle: u64,
pub(crate) pipe_peerhandle: u64,
pipe_status: i32,
rfu_1: i32,
}
const _: () = assert!(std::mem::size_of::<ProcFileInfo>() == 24);
const _: () = assert!(std::mem::size_of::<PipeFdInfo>() == 184);
const _: () = assert!(std::mem::offset_of!(PipeFdInfo, pipe_handle) == 160);
pub(crate) fn pipe_handle_of(fd: BorrowedFd<'_>) -> Option<u64> {
match fd_pipe_info(std::process::id(), fd.as_raw_fd()) {
FdPipeInfoQuery::Found(info) => Some(info.pipe_handle),
FdPipeInfoQuery::Absent | FdPipeInfoQuery::Denied => None,
}
}
pub(crate) enum FdPipeInfoQuery {
Found(PipeFdInfo),
Absent,
Denied,
}
pub(crate) fn fd_pipe_info(pid: RawPid, fd: libc::c_int) -> FdPipeInfoQuery {
let mut info: PipeFdInfo = unsafe { std::mem::zeroed() };
let size = std::mem::size_of::<PipeFdInfo>() as libc::c_int;
let n = clear_errno_and_call(|| unsafe {
libc::proc_pidfdinfo(
pid as libc::c_int,
fd,
PROC_PIDFDPIPEINFO,
&mut info as *mut _ as *mut libc::c_void,
size,
)
});
if n == size {
return FdPipeInfoQuery::Found(info);
}
match std::io::Error::last_os_error().raw_os_error() {
None | Some(0) | Some(libc::ESRCH) | Some(libc::EBADF) => FdPipeInfoQuery::Absent,
_ => FdPipeInfoQuery::Denied,
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Holder {
pub pid: RawPid,
pub clexec: bool,
}
pub(crate) enum PipeQuery {
Found(Vec<libc::c_int>),
Gone,
Denied,
}
pub(crate) fn holders(handle: u64, pids: &[RawPid]) -> Vec<Holder> {
let mut out = Vec::new();
let mut denied = 0usize;
for &pid in pids {
let fds = match pipe_fds_of(pid) {
PipeQuery::Found(fds) => fds,
PipeQuery::Gone => continue,
PipeQuery::Denied => {
denied += 1;
continue;
}
};
let mut found = false;
let mut all_clexec = true;
for fd in fds {
match fd_pipe_info(pid, fd) {
FdPipeInfoQuery::Found(info) => {
if info.pipe_handle != handle {
continue;
}
found = true;
all_clexec &= info.pfi.fi_status & PROC_FP_CLEXEC != 0;
}
FdPipeInfoQuery::Absent => {
log::debug!(
"fd marker {handle:#x}: PROC_PIDFDPIPEINFO for pid {pid} fd {fd} \
(already listed as a pipe) came back empty; treating as vanished \
between the two calls"
);
}
FdPipeInfoQuery::Denied => {
denied += 1;
log::debug!(
"fd marker {handle:#x}: PROC_PIDFDPIPEINFO for pid {pid} fd {fd} \
(already listed as a pipe) was denied"
);
}
}
}
if !found {
continue;
}
if all_clexec {
log::warn!(
"fd marker {handle:#x}: holder pid {pid} will lose the marker at its next \
exec (every copy of its inherited descriptor is FD_CLOEXEC)"
);
}
out.push(Holder {
pid,
clexec: all_clexec,
});
}
if denied > 0 {
log::debug!(
"fd marker {handle:#x}: {denied} of {} host pids were unqueryable this pass \
(access denied); none were confirmed holders, but a denied pid already holding \
the marker would be invisible to this scan",
pids.len()
);
}
out
}
#[cfg_attr(
not(test),
allow(
dead_code,
reason = "only tests call it; production uses holds_marker_query directly"
)
)]
pub(crate) fn holds_marker(pid: RawPid, handle: u64) -> bool {
matches!(holds_marker_query(pid, handle), MarkerQuery::Held)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum MarkerQuery {
Held,
NotHeld,
Denied,
}
pub(crate) fn holds_marker_query(pid: RawPid, handle: u64) -> MarkerQuery {
let fds = match pipe_fds_of(pid) {
PipeQuery::Found(fds) => fds,
PipeQuery::Gone => return MarkerQuery::NotHeld,
PipeQuery::Denied => return MarkerQuery::Denied,
};
for fd in fds {
match fd_pipe_info(pid, fd) {
FdPipeInfoQuery::Found(info) if info.pipe_handle == handle => return MarkerQuery::Held,
FdPipeInfoQuery::Found(_) => continue,
FdPipeInfoQuery::Absent => {
log::debug!(
"fd marker {handle:#x}: PROC_PIDFDPIPEINFO for pid {pid} fd {fd} (already \
listed as a pipe) came back empty; treating as vanished between the two calls"
);
continue;
}
FdPipeInfoQuery::Denied => {
return MarkerQuery::Denied;
}
}
}
MarkerQuery::NotHeld
}
fn fd_list_buf_bytes(cap: usize, entry: usize) -> std::io::Result<libc::c_int> {
cap.checked_mul(entry)
.and_then(|bytes| libc::c_int::try_from(bytes).ok())
.ok_or_else(|| {
std::io::Error::other(format!(
"a {cap}-entry proc_fdinfo buffer cannot be described in proc_pidinfo's int \
size argument"
))
})
}
pub(crate) fn pipe_fds_of(pid: RawPid) -> PipeQuery {
let entry = std::mem::size_of::<libc::proc_fdinfo>();
let needed = clear_errno_and_call(|| unsafe {
libc::proc_pidinfo(pid as libc::c_int, libc::PROC_PIDLISTFDS, 0, std::ptr::null_mut(), 0)
});
if needed <= 0 {
return classify_pidlistfds_failure();
}
let mut cap = needed as usize / entry + 16;
loop {
let buf_bytes = match fd_list_buf_bytes(cap, entry) {
Ok(b) => b,
Err(e) => {
log::warn!(
"fd marker: pid {pid}'s open-fd count cannot be enumerated ({report}); treating \
as denied for this pass",
report = crate::error::Report(&e)
);
return PipeQuery::Denied;
}
};
let mut fds: Vec<libc::proc_fdinfo> = vec![unsafe { std::mem::zeroed() }; cap];
let written = clear_errno_and_call(|| unsafe {
libc::proc_pidinfo(
pid as libc::c_int,
libc::PROC_PIDLISTFDS,
0,
fds.as_mut_ptr() as *mut libc::c_void,
buf_bytes,
)
});
if written <= 0 {
return classify_pidlistfds_failure();
}
let count = written as usize / entry;
if count > cap {
log::warn!(
"fd marker: pid {pid}'s proc_pidinfo(PROC_PIDLISTFDS) reported {count} entries \
into a {cap}-entry buffer; treating as denied for this pass"
);
return PipeQuery::Denied;
}
if count == cap {
cap *= 2;
continue;
}
return PipeQuery::Found(
fds[..count]
.iter()
.filter(|f| f.proc_fdtype == libc::PROX_FDTYPE_PIPE as u32)
.map(|f| f.proc_fd)
.collect(),
);
}
}
fn clear_errno_and_call(f: impl FnOnce() -> libc::c_int) -> libc::c_int {
unsafe {
*libc::__error() = 0;
}
f()
}
fn classify_pidlistfds_failure() -> PipeQuery {
let e = std::io::Error::last_os_error();
match e.raw_os_error() {
None | Some(0) => PipeQuery::Found(Vec::new()), Some(libc::ESRCH) => PipeQuery::Gone,
_ => PipeQuery::Denied,
}
}
use std::os::fd::{FromRawFd, OwnedFd, RawFd};
use crate::containment::ContainMode;
pub(crate) fn marker_wanted(mode: Option<ContainMode>, is_root: bool, suppressed: bool) -> bool {
mode.is_some() && is_root && !suppressed
}
const HIGH_FLOOR: RawFd = 64;
pub(crate) fn safe_marker_fd(candidate: RawFd, reserved: &[RawFd]) -> RawFd {
let floor = reserved
.iter()
.copied()
.max()
.map_or(HIGH_FLOOR, |m| m.saturating_add(1))
.max(HIGH_FLOOR);
candidate.max(floor)
}
pub(crate) struct PreparedMarker {
pub read: OwnedFd,
pub handle: u64,
pub read_handle: u64,
#[cfg_attr(not(test), allow(dead_code, reason = "read only by tests"))]
pub fd: RawFd,
pub kernel: crate::identity::SpawnKernel,
}
pub(crate) fn install(
steps: &mut crate::child::spawn::in_child::InChild,
reserved: &[RawFd],
kernel: &crate::identity::SpawnKernel,
) -> Result<PreparedMarker, Error> {
let failed = |detail: &str, source: Option<std::io::Error>| Error::Containment {
detail: detail.to_owned(),
source: source.map(Error::io_cause),
};
let (read, write) = match create_pipe() {
Ok(p) => p,
Err(e) => return Err(failed("fd marker: pipe() failed", Some(e))),
};
let want = safe_marker_fd(write.as_fd().as_raw_fd(), reserved);
let write: OwnedFd = match place_write_end(write, want) {
Ok(fd) => fd,
Err(e) => {
return Err(failed(
"fd marker: could not place the marker descriptor",
Some(e.into()),
))
}
};
let fd = write.as_raw_fd();
debug_assert!(
unsafe { libc::fcntl(fd, libc::F_GETFD) } & libc::FD_CLOEXEC != 0,
"the marker's supervisor-side write-end copy must be FD_CLOEXEC"
);
let Some(handle) = read_handle(write.as_fd()) else {
return Err(failed("fd marker: the marker pipe has no readable handle", None));
};
if handle == 0 {
debug_assert!(
false,
"fd marker: pipe_handle_of the write end returned 0, the reserved sentinel"
);
return Err(failed(
"fd marker: the marker pipe's write end reported a zero handle",
None,
));
}
debug_assert!(
matches!(
fd_pipe_info(std::process::id(), read.as_raw_fd()),
FdPipeInfoQuery::Found(info) if info.pipe_peerhandle == handle
),
"the marker's read end must report the write end's handle as its peer"
);
let Some(read_handle_value) = pipe_handle_of(read.as_fd()) else {
return Err(failed(
"fd marker: the marker pipe's read end has no readable handle",
None,
));
};
if read_handle_value == 0 {
debug_assert!(
false,
"fd marker: pipe_handle_of the read end returned 0, the reserved sentinel"
);
return Err(failed(
"fd marker: the marker pipe's read end reported a zero handle",
None,
));
}
steps.preserve(write);
Ok(PreparedMarker {
read: OwnedFd::from(read),
handle,
read_handle: read_handle_value,
fd,
kernel: std::sync::Arc::clone(kernel),
})
}
fn create_pipe() -> std::io::Result<(std::io::PipeReader, std::io::PipeWriter)> {
#[cfg(test)]
if fault::take_if(fault::Fault::Pipe) {
return Err(std::io::Error::from_raw_os_error(libc::EMFILE));
}
crate::pipe::pair()
}
fn place_write_end(write: std::io::PipeWriter, want: RawFd) -> Result<OwnedFd, nix::errno::Errno> {
#[cfg(test)]
if fault::take_if(fault::Fault::Place) {
return Err(nix::errno::Errno::EMFILE);
}
let placed = nix::fcntl::fcntl(write.as_fd(), nix::fcntl::FcntlArg::F_DUPFD_CLOEXEC(want))?;
debug_assert!(
placed >= want,
"F_DUPFD_CLOEXEC({want}) returned {placed}, below the floor it was given"
);
Ok(unsafe { OwnedFd::from_raw_fd(placed) })
}
fn read_handle(fd: BorrowedFd<'_>) -> Option<u64> {
#[cfg(test)]
if fault::take_if(fault::Fault::Handle) {
return None;
}
pipe_handle_of(fd)
}
#[cfg(test)]
pub(crate) mod fault {
use std::cell::Cell;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Fault {
Pipe,
Place,
Handle,
}
thread_local! {
static FAULT: Cell<Option<Fault>> = const { Cell::new(None) };
}
pub(crate) fn set_fault(f: Option<Fault>) {
FAULT.with(|c| c.set(f));
}
pub(crate) fn take_if(want: Fault) -> bool {
FAULT.with(|c| {
if c.get() == Some(want) {
c.set(None);
true
} else {
false
}
})
}
pub(crate) fn take_fault() -> Option<Fault> {
FAULT.with(|c| c.take())
}
thread_local! {
static FORCE_ROOT_KILL_NOOP: Cell<bool> = const { Cell::new(false) };
}
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))
}
pub(crate) fn armed() -> bool {
FORCE_ROOT_KILL_NOOP.with(|f| f.get())
}
type HolderSignal = (u32, nix::sys::signal::Signal);
thread_local! {
static HOLDER_KILLS: std::cell::RefCell<Option<Vec<HolderSignal>>> = const { std::cell::RefCell::new(None) };
}
pub(crate) fn record_holder_kills() -> HolderKillRecorder {
HOLDER_KILLS.with(|k| *k.borrow_mut() = Some(Vec::new()));
HolderKillRecorder(())
}
#[must_use = "recording stops as soon as the recorder is dropped"]
pub(crate) struct HolderKillRecorder(());
impl HolderKillRecorder {
pub(crate) fn killed(&self) -> Vec<u32> {
self.sent().into_iter().map(|(pid, _)| pid).collect()
}
pub(crate) fn signals_to(&self, pid: u32) -> Vec<nix::sys::signal::Signal> {
self.sent()
.into_iter()
.filter_map(|(to, signal)| (to == pid).then_some(signal))
.collect()
}
fn sent(&self) -> Vec<HolderSignal> {
HOLDER_KILLS.with(|k| k.borrow().clone().expect("the recorder is live"))
}
}
impl Drop for HolderKillRecorder {
fn drop(&mut self) {
HOLDER_KILLS.with(|k| *k.borrow_mut() = None);
}
}
pub(crate) fn holder_kills_so_far() -> Vec<u32> {
HOLDER_KILLS
.with(|k| k.borrow().clone().expect("a recorder is live"))
.into_iter()
.map(|(pid, _)| pid)
.collect()
}
pub(super) fn note_holder_kill(pid: u32, signal: nix::sys::signal::Signal) {
HOLDER_KILLS.with(|k| {
if let Some(killed) = k.borrow_mut().as_mut() {
killed.push((pid, signal));
}
});
}
static LOG_SERIALIZE: std::sync::Mutex<()> = std::sync::Mutex::new(());
pub(crate) fn lock_for_log_assertion() -> std::sync::MutexGuard<'static, ()> {
LOG_SERIALIZE.lock().unwrap_or_else(|e| e.into_inner())
}
}
use std::io;
use crate::containment::dispatch::{TreeKillOutcome, Unkilled};
use crate::containment::drain_edge::DrainEdge;
use crate::containment::mechanism::{Contains, Release};
use crate::containment::root::NumberLook;
use crate::containment::sweep_passes::run_passes;
use crate::containment::treewalk::{KillOutcome, Listing};
use crate::containment::{Containment, Root, SendOutcome, Skip, TerminateOutcome, TreeKill, TreeStop, Why};
use crate::error::Error;
use crate::identity::{ProcessId, Resolved};
use crate::signal::Sig;
#[derive(Clone, Copy)]
enum Scope<'r> {
Full(Option<&'r dyn Root>),
HoldersOnly { except: Option<ProcessId> },
}
struct SweepState<'k> {
seen: std::collections::HashSet<ProcessId>,
group_result: Result<(), Error>,
group_unsent: bool,
delivered: bool,
incomplete: bool,
killed: &'k mut Vec<ProcessId>,
}
impl<'k> SweepState<'k> {
fn new(killed: &'k mut Vec<ProcessId>) -> SweepState<'k> {
SweepState {
seen: std::collections::HashSet::new(),
group_result: Ok(()),
group_unsent: false,
delivered: false,
incomplete: false,
killed,
}
}
fn record(&mut self, id: ProcessId, signal: Sig, outcome: &KillOutcome, waited_for: bool) {
match outcome {
KillOutcome::Terminated => {
self.delivered = true;
if waited_for && signal == Sig::Kill {
self.killed.push(id);
}
}
KillOutcome::NotAttempted(_) => self.incomplete = true,
KillOutcome::AlreadyGone => {}
}
}
}
pub(crate) struct Marker {
read: OwnedFd,
kernel: crate::identity::SpawnKernel,
handle: u64,
read_handle: u64,
root: Option<ProcessId>,
pgid: Option<i32>,
own_fd: RawFd,
}
impl std::fmt::Debug for Marker {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Marker")
.field("handle", &format_args!("{:#x}", self.handle))
.field("pgid", &self.pgid)
.finish_non_exhaustive()
}
}
impl Contains for Marker {
fn kill(&self, root: Option<&dyn Root>) -> TreeKill<'_> {
self.kill_tree(root)
}
fn send_terminate(&self, _pid: u32, root: Option<&dyn Root>, how: TreeStop) -> (TerminateOutcome, Option<Listing>) {
(self.terminate_tree(root, how), None)
}
fn drain_edge(&self) -> Option<DrainEdge<'_>> {
Some(DrainEdge::Marker(self))
}
fn kind(&self) -> Containment {
Containment::FdMarker
}
fn disarm(&self) -> io::Result<()> {
Ok(())
}
fn subject(&self) -> String {
format!("FdMarker({self:?})")
}
fn would_reach(&self, _pid: u32, _pidfd: Option<BorrowedFd<'_>>) -> Result<bool, crate::error::Error> {
Ok(false)
}
fn reached(&self, _child: &crate::child::owned::OwnedChild) -> Result<bool, crate::error::Error> {
Ok(false)
}
fn release(self) -> (Release, Option<Marker>) {
(Release::nothing(), None)
}
}
pub(crate) fn is_signalable(pid: RawPid) -> bool {
pid > 1 && pid != std::process::id()
}
fn pid_is_live_group_member(pid: RawPid, pgid: i32) -> bool {
debug_assert!(
pid <= i32::MAX as u32,
"pid {pid} exceeds i32::MAX; pgid comparison would truncate"
);
nix::unistd::getpgid(Some(nix::unistd::Pid::from_raw(pid as i32)))
.map(|g| g.as_raw() == pgid)
.unwrap_or(false)
}
fn combine_group_errors(first: Error, latest: Error) -> Error {
let containment = matches!(first, Error::Containment { .. }) || matches!(latest, Error::Containment { .. });
let detail = "the teardown failed in more than one way".to_owned();
let source =
Some(crate::error::Failures::new(std::sync::Arc::new(first), [std::sync::Arc::new(latest)]).into_cause());
if containment {
Error::Containment { detail, source }
} else {
Error::Unassessable { detail, source }
}
}
impl Marker {
pub(crate) fn new(prepared: PreparedMarker, root: ProcessId, pgid: Option<i32>) -> Marker {
Marker {
read: prepared.read,
kernel: prepared.kernel,
handle: prepared.handle,
read_handle: prepared.read_handle,
root: Some(root),
pgid,
own_fd: prepared.fd,
}
}
pub(crate) fn without_root(prepared: PreparedMarker) -> Marker {
Marker {
read: prepared.read,
kernel: prepared.kernel,
handle: prepared.handle,
read_handle: prepared.read_handle,
root: None,
pgid: None,
own_fd: prepared.fd,
}
}
#[cfg_attr(
not(test),
allow(dead_code, reason = "consumed by Child::test_marker_handle (test-only)")
)]
pub(crate) fn handle(&self) -> u64 {
self.handle
}
pub(crate) fn own_fd(&self) -> RawFd {
self.own_fd
}
#[cfg(test)]
pub(crate) fn root(&self) -> Option<ProcessId> {
self.root
}
#[cfg(test)]
pub(crate) fn pgid(&self) -> Option<i32> {
self.pgid
}
#[cfg(test)]
pub(crate) fn force_pgid_for_test(&mut self, pgid: i32) {
self.pgid = Some(pgid);
}
pub(crate) fn read_end(&self) -> BorrowedFd<'_> {
self.read.as_fd()
}
pub(crate) fn wait_drained(&self, deadline: Option<Instant>) -> Result<crate::containment::TreeDrain, Error> {
self.check_read_end_still_valid()?;
debug_assert_ne!(
crate::containment::marker_eof::write_end_check(self.read_end()),
crate::containment::marker_eof::WriteEndCheck::HeldByUs,
"the supervisor still holds a copy of the marker write end - the tree-drain edge can never fire"
);
crate::containment::marker_eof::block_until_drained(self.read_end(), deadline)
}
fn hard_kill(&self, root: Option<&dyn Root>, killed: &mut Vec<ProcessId>) -> Result<(), Error> {
self.hard_kill_impl(Scope::Full(root), killed)
}
fn look_at(&self, root: Option<&dyn Root>) -> Option<(NumberLook, Option<ProcessId>)> {
let (Some(_), Some(root)) = (self.root, root) else {
return None;
};
let look = crate::containment::root::look(root);
#[cfg(test)]
crate::graceful_hooks::run_hook(crate::graceful_hooks::HookPoint::AfterRootLook);
let except = match &look {
NumberLook::Untrusted(crate::signal::RootState::Unpinned) => self.root,
_ => None,
};
Some((look, except))
}
fn number_named(&self, verb: &str, root_pid: u32) -> String {
let walk = format!("walk the process table from the root's pid (root pid {root_pid})");
match self.pgid {
Some(pgid) => format!("{verb} its process group (pgid {pgid}) or {walk}"),
None => walk,
}
}
fn skip(&self, verb: &str, root_pid: u32, look: NumberLook, holders: Result<(), Error>) -> Skip {
let why = match look {
NumberLook::Untrusted(state) => Why::untrusted(&state),
NumberLook::MayNameAnother { refusal, probe, .. } => Why::MayNameAnother(refusal, probe),
NumberLook::Trusted | NumberLook::GroupGone => {
unreachable!("a send that is not skipped has no skip to say")
}
};
Skip {
action: self.number_named(verb, root_pid),
why,
root_alone: false,
holders: Some(holders),
}
}
pub(crate) fn kill_tree<'a>(&self, root: Option<&dyn Root>) -> TreeKill<'a> {
let ran = |sent: Result<(), Error>| sent.map_err(Unkilled::from);
let mut killed = Vec::new();
let outcome = match self.look_at(root) {
None => match self.root {
None => TreeKillOutcome::Ran(ran(
self.hard_kill_impl(Scope::HoldersOnly { except: None }, &mut killed)
)),
Some(_) => {
debug_assert!(false, "a marker with a root was given no root to look at");
TreeKillOutcome::Ran(ran(self.hard_kill(root, &mut killed)))
}
},
Some((look, except)) => {
let root_pid = root.map_or(0, Root::pid);
match look {
NumberLook::Trusted => TreeKillOutcome::Ran(ran(self.hard_kill(root, &mut killed))),
look => TreeKillOutcome::Skipped(self.skip(
"kill",
root_pid,
look,
self.hard_kill_impl(Scope::HoldersOnly { except }, &mut killed),
)),
}
}
};
TreeKill::of(outcome).reaching(killed)
}
fn hard_kill_impl(&self, scope: Scope<'_>, killed: &mut Vec<ProcessId>) -> Result<(), Error> {
self.check_read_end_still_valid()?;
let mut state = SweepState::new(killed);
let still_forking = run_passes(|pass| self.sweep_pass(Sig::Kill, &mut state, pass == 1, scope));
Self::finish_sweep(self.handle, state.group_result, state.incomplete, still_forking)
}
fn terminate(&self, root: Option<&dyn Root>, how: TreeStop) -> SendOutcome {
self.terminate_impl(Scope::Full(root), how)
}
pub(crate) fn terminate_tree(&self, root: Option<&dyn Root>, how: TreeStop) -> TerminateOutcome {
let holders_only = |except| self.terminate_impl(Scope::HoldersOnly { except }, how);
let earlier = Some(how.earlier());
let Some((look, except)) = self.look_at(root) else {
let sent = match self.root {
None => holders_only(None),
Some(_) => {
debug_assert!(false, "a marker with a root was given no root to look at");
self.terminate(root, how)
}
};
return TerminateOutcome::of(sent, earlier);
};
let root_pid = root.map_or(0, Root::pid);
match look {
NumberLook::Trusted => TerminateOutcome::of(self.terminate(root, how), earlier),
NumberLook::Untrusted(_) => TerminateOutcome::of(holders_only(except), earlier),
look => match holders_only(None) {
SendOutcome::Sent(result) => TerminateOutcome::HoldersOnly(self.skip("signal", root_pid, look, result)),
SendOutcome::NotSent(not_sent) | SendOutcome::RootExited(not_sent) => {
TerminateOutcome::NotSent(not_sent)
}
},
}
}
fn terminate_impl(&self, scope: Scope<'_>, how: TreeStop) -> SendOutcome {
if let Err(stale) = self.check_read_end_still_valid() {
return SendOutcome::NotSent(stale);
}
let mut reached = Vec::new();
let mut state = SweepState::new(&mut reached);
self.sweep_pass(how.sig(), &mut state, true, scope);
let swept = Self::finish_sweep(self.handle, state.group_result, state.incomplete, false);
match swept {
Err(unsent) if state.group_unsent && !state.delivered => SendOutcome::NotSent(unsent),
swept => SendOutcome::Sent(swept),
}
}
pub(crate) fn check_read_end_still_valid(&self) -> Result<(), Error> {
let read_still_valid = matches!(
fd_pipe_info(std::process::id(), self.read.as_raw_fd()),
FdPipeInfoQuery::Found(info) if info.pipe_handle == self.read_handle
);
debug_assert!(
read_still_valid,
"fd marker {:#x}: the read end must still be the same pipe object at sweep time",
self.handle
);
if !read_still_valid {
let msg = format!(
"fd marker {:#x}: the read end no longer names its recorded pipe object at \
sweep entry — refusing to sweep rather than signal against a handle that may \
now name an unrelated live pipe",
self.handle
);
log::error!("{msg}");
return Err(Error::Containment {
detail: msg,
source: None,
});
}
Ok(())
}
fn sweep_pass(&self, signal: Sig, state: &mut SweepState<'_>, first_pass: bool, scope: Scope<'_>) -> usize {
let SweepState {
seen,
group_result,
group_unsent,
incomplete,
killed,
..
} = state;
let walk = matches!(scope, Scope::Full(_));
let group_root = match scope {
Scope::Full(root) => root,
Scope::HoldersOnly { .. } => None,
};
let except = match scope {
Scope::HoldersOnly { except } => except,
Scope::Full(_) => None,
};
let (pids, parents, _ppid_denied) = crate::containment::enumerate::snapshot(&*self.kernel);
let blind = pids.is_empty();
if blind {
*incomplete = true;
if first_pass {
let still = match scope {
Scope::Full(_) => {
"the group signal and root kill below still run, since neither needs the process table"
}
Scope::HoldersOnly { .. } => "nothing else runs, so nothing is signalled this pass",
};
log::warn!(
"fd marker {:#x}: the host process table could not be read on the first \
pass; the ppid-walk and marker channels are blind ({still})",
self.handle
);
} else {
log::warn!(
"fd marker {:#x}: the host process table could not be read this pass; \
every channel is blind this pass — the root was already handled on an \
earlier pass and is not retried, and the group signal does not re-fire \
without a live member freshly confirmed THIS pass (not observed this \
pass is not the same as observed absent). This pass performs no teardown \
on any channel",
self.handle
);
}
}
let mut new_walk: Vec<ProcessId> = Vec::new();
debug_assert!(
!walk || self.root.is_some(),
"a full sweep of a marker made without its root"
);
if let Some(root) = self.root.filter(|_| walk) {
if seen.insert(root) {
new_walk.push(root);
}
if !blind {
match crate::containment::treewalk::walk_from(&*self.kernel, root, &parents, crate::Recursive::Yes) {
Ok(Some(walk)) => {
#[cfg(test)]
crate::containment::treewalk::fault::note_walk(root.pid());
for id in walk.members {
if seen.insert(id) {
new_walk.push(id);
}
}
if !walk.unassessed.is_empty() {
crate::containment::treewalk::warn_unassessed(&walk.unassessed);
*incomplete = true;
}
}
Ok(None) => {}
Err(e) => {
log::warn!(
"fd marker {:#x}: the root's descendants could not be walked ({report}) \
- the ppid-walk channel is blind this pass",
self.handle,
report = crate::error::Report(&e)
);
*incomplete = true;
}
}
}
}
let this_pass_holders: Vec<Holder> = if blind { Vec::new() } else { holders(self.handle, &pids) };
let mut new_holders: Vec<ProcessId> = Vec::new();
for h in &this_pass_holders {
if !is_signalable(h.pid) {
log::warn!(
"fd marker {:#x}: self-exclusion guard fired for pid {} found in the \
holder set (the supervisor or pid 0/1 must never hold its own marker)",
self.handle,
h.pid
);
debug_assert!(
false,
"fd marker sweep found pid {} in its own holder set (supervisor, pid 0, or \
pid 1) — the write-end hand-off must never reach any of them",
h.pid
);
continue;
}
let id = match ProcessId::of_with(&*self.kernel, h.pid).0 {
Resolved::Found(id) => id,
Resolved::Gone => continue,
Resolved::Unknown => {
log::warn!(
"fd marker {:#x}: holder pid {} could not be queried (access denied?) \
- not signaled, left running",
self.handle,
h.pid
);
*incomplete = true;
continue;
}
};
if Some(id) == except {
log::debug!(
"fd marker {:#x}: holder pid {} is not pinned by this process - not signaled",
self.handle,
h.pid
);
continue;
}
if seen.insert(id) {
new_holders.push(id);
}
}
{
let live_holder_confirms_pgid = !blind
&& self.pgid.is_some_and(|pgid| {
this_pass_holders
.iter()
.any(|h| is_signalable(h.pid) && pid_is_live_group_member(h.pid, pgid))
});
let should_fire = first_pass || live_holder_confirms_pgid;
if !walk {
} else if should_fire {
let this_pass_group_result: Result<(), Error> = match (self.pgid, signal) {
(Some(pgid), Sig::Kill) => crate::containment::unix::kill_group(pgid, group_root, killed),
(Some(pgid), Sig::Graceful(signal)) => {
match crate::containment::unix::term_group_sent(pgid, group_root, signal) {
SendOutcome::Sent(checked) => checked,
SendOutcome::NotSent(unsent) | SendOutcome::RootExited(unsent) => {
*group_unsent = true;
Err(unsent)
}
}
}
(None, _) => Ok(()),
};
*group_result = match (std::mem::replace(group_result, Ok(())), this_pass_group_result) {
(Ok(()), r) => r,
(e @ Err(_), Ok(())) => e,
(Err(first), Err(latest)) => Err(combine_group_errors(first, latest)),
};
} else if self.pgid.is_some() {
if blind {
log::debug!(
"fd marker {:#x}: skipping this pass's group signal — the process \
table could not be read this pass, so no live member of this pass's \
pgid was observed (not: none was found)",
self.handle
);
} else {
log::debug!(
"fd marker {:#x}: skipping this pass's group signal — no live member \
confirmed this pass's pgid, so it may have been recycled",
self.handle
);
}
}
}
let found = new_walk.len() + new_holders.len();
if found == 0 {
return 0;
}
for id in new_walk {
#[cfg(test)]
if Some(id) == self.root && fault::take_force_root_kill_noop() {
continue;
}
let outcome = crate::containment::treewalk::kill_by_identity(&*self.kernel, id, signal);
crate::containment::treewalk::warn_if_not_attempted(id, signal, &outcome);
state.record(id, signal, &outcome, Some(id) != self.root);
}
for id in new_holders {
if let Some(outcome) = self.kill_holder(id, signal) {
state.record(id, signal, &outcome, true);
}
}
found
}
fn finish_sweep(
handle: u64,
group_result: Result<(), Error>,
incomplete: bool,
still_forking: bool,
) -> Result<(), Error> {
if incomplete || still_forking {
let mut causes = Vec::new();
if incomplete {
causes.push(
"the host process table was unreadable on at least one pass, or at least one \
known/suspected member could not be assessed or signalled",
);
}
if still_forking {
causes.push(
"the tree was still forking when the sweep stopped, so a process it forked \
during the last pass may be left running, unnamed",
);
}
let msg = format!(
"fd marker {handle:#x}: teardown may be incomplete — {}",
causes.join("; ")
);
let incomplete_err = Error::Unassessable {
detail: msg,
source: None,
};
return match group_result {
Ok(()) => Err(incomplete_err),
Err(group_err) => Err(group_err.with_peers([std::sync::Arc::new(incomplete_err)])),
};
}
group_result
}
fn kill_holder(&self, id: ProcessId, signal: Sig) -> Option<KillOutcome> {
match holds_marker_query(id.pid(), self.handle) {
MarkerQuery::NotHeld => {
log::debug!(
"fd marker {:#x}: pid {} no longer holds the marker - not signaled",
self.handle,
id.pid()
);
None
}
MarkerQuery::Denied => {
let detail = format!(
"fd marker {:#x}: pid {} (a confirmed holder this pass) could not be re-queried before \
signalling (access denied?)",
self.handle,
id.pid()
);
log::warn!("{detail} - not signalled, left running");
Some(KillOutcome::NotAttempted(Error::Unassessable { detail, source: None }))
}
MarkerQuery::Held => {
let outcome = crate::containment::treewalk::kill_by_identity(&*self.kernel, id, signal);
crate::containment::treewalk::warn_if_not_attempted(id, signal, &outcome);
#[cfg(test)]
if matches!(outcome, KillOutcome::Terminated) {
fault::note_holder_kill(id.pid(), signal.as_nix());
}
Some(outcome)
}
}
}
}
#[cfg(test)]
#[path = "fdmarker_tests.rs"]
pub(crate) mod fdmarker_tests;