use std::{collections::HashMap, io};
use super::{Pid, Signal, native_pid, vanished};
use crate::platform::process::{ChildIdentity, ProcessId};
#[derive(Default)]
pub(super) struct Descendants {
#[cfg(target_os = "macos")]
seen: std::sync::Mutex<HashMap<ProcessId, Member>>,
}
impl Descendants {
pub(super) fn signal(&self, root: ChildIdentity, signal: Signal) -> io::Result<bool> {
#[cfg(target_os = "linux")]
let mut members = HashMap::<ProcessId, Member>::new();
#[cfg(target_os = "macos")]
let mut members = self.seen.lock().expect("process tree not poisoned");
let mut pending = members.keys().copied().collect::<Vec<_>>();
pending.push(root.pid);
while let Some(parent) = pending.pop() {
let identity = if parent == root.pid {
root
} else {
members[&parent].identity
};
if !super::super::is_alive(Some(identity))? {
continue;
}
for pid in direct_children(native_pid(parent.get())?)? {
let child_id = ProcessId::new(pid.as_raw_pid() as u32);
if child_id == root.pid || members.contains_key(&child_id) {
continue;
}
if let Some(member) = Member::capture(pid, identity)? {
#[cfg(target_os = "linux")]
if parent != root.pid && !members[&parent].still_running()? {
continue;
}
members.insert(child_id, member);
pending.push(child_id);
}
}
}
let mut found = false;
let mut result = Ok(());
members.retain(|_, member| match member.signal(signal) {
Ok(sent) => {
found |= sent;
sent
}
Err(error) => {
result = Err(error);
true
}
});
result?;
Ok(found)
}
}
struct Member {
identity: ChildIdentity,
#[cfg(target_os = "linux")]
handle: std::os::fd::OwnedFd,
}
impl Member {
fn capture(pid: Pid, parent: ChildIdentity) -> io::Result<Option<Self>> {
#[cfg(target_os = "linux")]
let Some(handle) = vanished(
rustix::process::pidfd_open(pid, rustix::process::PidfdFlags::empty())
.map_err(io::Error::from),
)?
else {
return Ok(None);
};
let Some((ppid, start_time)) = vanished(parent_and_start(pid))? else {
return Ok(None);
};
if ppid != Some(native_pid(parent.pid.get())?) || !super::super::is_alive(Some(parent))? {
return Ok(None);
}
Ok(Some(Self {
identity: ChildIdentity {
pid: ProcessId::new(pid.as_raw_pid() as u32),
start_time,
},
#[cfg(target_os = "linux")]
handle,
}))
}
#[cfg(target_os = "linux")]
fn still_running(&self) -> io::Result<bool> {
use std::os::fd::AsRawFd;
let mut descriptor = libc::pollfd {
fd: self.handle.as_raw_fd(),
events: libc::POLLIN,
revents: 0,
};
loop {
match unsafe { libc::poll(&mut descriptor, 1, 0) } {
0 => return Ok(true),
1 => return Ok(false),
_ => {
let error = io::Error::last_os_error();
if error.kind() != io::ErrorKind::Interrupted {
return Err(error);
}
}
}
}
}
fn signal(&self, signal: Signal) -> io::Result<bool> {
#[cfg(target_os = "linux")]
{
let sent = rustix::process::pidfd_send_signal(&self.handle, signal);
Ok(vanished(sent.map_err(io::Error::from))?.is_some())
}
#[cfg(target_os = "macos")]
super::signal_member(native_pid(self.identity.pid.get())?, signal, || {
super::super::is_alive(Some(self.identity))
})
}
}
#[cfg(target_os = "linux")]
fn parent_and_start(pid: Pid) -> io::Result<(Option<Pid>, u64)> {
let stat = super::process_stat(pid.as_raw_pid() as u32)?;
if matches!(stat.state, super::ProcessState::Exited) {
return Err(io::ErrorKind::NotFound.into());
}
Ok((stat.parent, stat.start))
}
#[cfg(target_os = "linux")]
fn direct_children(pid: Pid) -> io::Result<Vec<Pid>> {
let Some(tasks) = vanished(std::fs::read_dir(format!("/proc/{pid}/task")))? else {
return Ok(Vec::new());
};
let mut children = Vec::new();
for task in tasks {
let Some(task) = vanished(task)? else {
continue;
};
if let Some(ids) = vanished(std::fs::read_to_string(task.path().join("children")))? {
for id in ids.split_ascii_whitespace() {
let pid = id.parse().ok().and_then(Pid::from_raw).ok_or_else(|| {
io::Error::new(io::ErrorKind::InvalidData, "invalid child process ID")
})?;
children.push(pid);
}
}
}
Ok(children)
}
#[cfg(target_os = "macos")]
fn parent_and_start(pid: Pid) -> io::Result<(Option<Pid>, u64)> {
let info = super::process_info(pid.as_raw_pid())?;
if info.pbi_status == libc::SZOMB || info.pbi_flags & super::PROC_FLAG_INEXIT != 0 {
return Err(io::ErrorKind::NotFound.into());
}
Ok((
Pid::from_raw(info.pbi_ppid as i32),
super::process_birth_time(info)?,
))
}
#[cfg(target_os = "macos")]
fn direct_children(pid: Pid) -> io::Result<Vec<Pid>> {
const MAX_PID_BYTES: usize = 16 * 1024 * 1024;
let mut capacity = unsafe { child_pids(pid, std::ptr::null_mut(), 0)? }.max(1);
loop {
let bytes = capacity
.checked_mul(size_of::<libc::pid_t>())
.filter(|&bytes| bytes <= MAX_PID_BYTES)
.ok_or_else(|| io::Error::other("child process enumeration exceeds 16 MiB"))?;
let mut pids = vec![0; capacity];
let read = unsafe { child_pids(pid, pids.as_mut_ptr(), bytes as i32)? };
if read < capacity {
pids.truncate(read);
return Ok(pids.into_iter().filter_map(Pid::from_raw).collect());
}
capacity *= 2;
}
}
#[cfg(target_os = "macos")]
unsafe fn child_pids(pid: Pid, buffer: *mut libc::pid_t, size: i32) -> io::Result<usize> {
unsafe {
*libc::__error() = 0;
let count = libc::proc_listchildpids(pid.as_raw_pid(), buffer.cast(), size);
let error = io::Error::last_os_error();
if count < 0 || (count == 0 && !matches!(error.raw_os_error(), Some(0 | libc::ESRCH))) {
return Err(error);
}
Ok(count as usize)
}
}