use nix::sys::signal::Signal;
use crate::identity::RawPid;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Member {
pub(crate) pid: RawPid,
pub(crate) token: u64,
pub(crate) system: bool,
}
#[cfg(target_os = "macos")]
pub(crate) fn members(pgid: i32) -> std::io::Result<Vec<Member>> {
use crate::identity::kinfo::kinfo_proc;
const RECORD: usize = std::mem::size_of::<kinfo_proc>();
let mut mib = [libc::CTL_KERN, libc::KERN_PROC, libc::KERN_PROC_PGRP, pgid];
let mut slack: usize = 1;
loop {
let mut len: libc::size_t = 0;
let rc = unsafe {
libc::sysctl(
mib.as_mut_ptr(),
mib.len() as libc::c_uint,
std::ptr::null_mut(),
&mut len,
std::ptr::null_mut(),
0,
)
};
if rc != 0 {
let e = std::io::Error::last_os_error();
if e.raw_os_error() == Some(libc::EINTR) {
continue;
}
return Err(e);
}
let mut buf: Vec<kinfo_proc> = Vec::with_capacity(len / RECORD + slack);
let mut got = buf.capacity() * RECORD;
let rc = unsafe {
libc::sysctl(
mib.as_mut_ptr(),
mib.len() as libc::c_uint,
buf.as_mut_ptr().cast(),
&mut got,
std::ptr::null_mut(),
0,
)
};
if rc != 0 {
let e = std::io::Error::last_os_error();
if e.raw_os_error() == Some(libc::ENOMEM) {
slack = slack.saturating_mul(2);
continue;
}
if e.raw_os_error() == Some(libc::EINTR) {
continue;
}
return Err(e);
}
if !got.is_multiple_of(RECORD) {
return Err(std::io::Error::other(format!(
"sysctl(KERN_PROC_PGRP, {pgid}) returned {got} bytes, not a whole multiple of \
the {RECORD}-byte kinfo_proc record — kernel ABI drift, refusing to reinterpret"
)));
}
unsafe { buf.set_len(got / RECORD) };
return Ok(buf
.iter()
.map(|k| Member {
pid: k.kp_proc.p_pid as RawPid,
token: unsafe {
k.kp_proc.p_un.p_starttime.tv_sec as u64 * 1_000_000 + k.kp_proc.p_un.p_starttime.tv_usec as u64
},
system: k.kp_proc.p_flag & crate::identity::kinfo::P_SYSTEM != 0,
})
.collect());
}
}
#[cfg(target_os = "linux")]
pub(crate) fn members(pgid: i32) -> std::io::Result<Vec<Member>> {
use crate::identity::stat_parse::{parse_pgrp, parse_starttime_jiffies};
let proc_dir = crate::identity::proc_view()
.into_dir()
.map_err(|why| match why.openat2_requirement() {
Some(requirement) => std::io::Error::new(
std::io::ErrorKind::Unsupported,
format!("containment::unix::group::members: {requirement}, so pgid {pgid} cannot be listed"),
),
None => std::io::Error::other(format!(
"containment::unix::group::members: {why}, so its process listing says nothing about pgid {pgid}"
)),
})?;
let mut out = Vec::new();
for pid in proc_dir.pids()? {
let stat = match crate::identity::pid_stat::read(&proc_dir, pid) {
Ok(crate::identity::pid_stat::PidStat::Read(bytes)) => bytes,
Ok(crate::identity::pid_stat::PidStat::Skipped(e)) => {
log::debug!("containment::unix::group::members: /proc/{pid}/stat unreadable ({e}); excluding it");
continue;
}
Err(e) => {
return Err(std::io::Error::other(format!(
"containment::unix::group::members: {e}, so process group {pgid} cannot be listed"
)));
}
};
let Some(g) = parse_pgrp(&stat) else {
log::debug!(
"containment::unix::group::members: /proc/{pid}/stat had no parseable pgrp \
field; excluding it"
);
continue;
};
if g != pgid as u32 {
continue;
}
let Some(token) = parse_starttime_jiffies(&stat) else {
log::debug!(
"containment::unix::group::members: /proc/{pid}/stat matched pgid {pgid} but \
had no parseable starttime; excluding it"
);
continue;
};
out.push(Member {
pid,
token,
system: false,
});
}
Ok(out)
}
#[cfg(all(unix, not(any(target_os = "macos", target_os = "linux"))))]
pub(crate) fn members(_pgid: i32) -> std::io::Result<Vec<Member>> {
Err(std::io::Error::new(
std::io::ErrorKind::Unsupported,
"process-group membership is implemented only for Linux and macOS",
))
}
#[derive(Debug)]
pub(crate) enum GroupState {
Cleared,
Refused {
refused: Vec<RawPid>,
unassessable: Vec<RawPid>,
},
Unlistable {
detail: String,
source: Option<std::io::Error>,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Reached {
Yes,
No,
Unknown,
}
enum MemberOutcome {
NotASurvivor,
Survivor(RawPid),
Unassessable(RawPid),
}
fn classify_member(
pid: RawPid,
liveness: crate::identity::Liveness,
reached: impl FnOnce() -> Reached,
) -> MemberOutcome {
match liveness {
crate::identity::Liveness::Dead => MemberOutcome::NotASurvivor,
crate::identity::Liveness::Alive | crate::identity::Liveness::Unknown => match reached() {
Reached::Yes => MemberOutcome::NotASurvivor,
Reached::No => MemberOutcome::Survivor(pid),
Reached::Unknown => MemberOutcome::Unassessable(pid),
},
}
}
fn check_or_signal(pid: RawPid, id: crate::identity::ProcessId, signal: Option<Signal>) -> Reached {
debug_assert!(
matches!(signal, None | Some(Signal::SIGKILL)),
"check_or_signal called with {signal:?}; only None (probe) or Some(SIGKILL) (resend) \
are ever valid here — SIGTERM must never resend, see converge's design note"
);
match crate::identity::ProcessId::of(pid) {
crate::identity::Resolved::Found(live) if live == id => {}
crate::identity::Resolved::Found(_) => {
log::debug!(
"containment::unix::group: pid {pid} now names a different process (recycled \
mid-teardown) — not the listed member, so not a survivor"
);
return Reached::Yes;
}
crate::identity::Resolved::Gone => return Reached::Yes,
crate::identity::Resolved::Unknown => {
log::warn!(
"containment::unix::group: pid {pid} could not be re-verified (access denied?) \
— treated as unassessable, not signalled (an unverified pid is never signalled \
on this platform: a recycled pid onto an unrelated, signalable process would \
be hit for real, not safely refused)"
);
return Reached::Unknown;
}
}
let Some(target) = crate::identity::probe::signal_target(pid) else {
log::warn!("containment::unix::group: pid {pid} is not a single-process signal target");
return Reached::Unknown;
};
match nix::sys::signal::kill(nix::unistd::Pid::from_raw(target), signal) {
Ok(()) | Err(nix::errno::Errno::ESRCH) => Reached::Yes,
Err(nix::errno::Errno::EPERM) => {
log::debug!("containment::unix::group: kill({pid}, {signal:?}) refused: EPERM");
Reached::No
}
Err(e) => {
log::warn!("containment::unix::group: kill({pid}, {signal:?}) answered {e}, neither EPERM nor ESRCH");
Reached::Unknown
}
}
}
#[cfg(target_os = "linux")]
fn check_or_signal_linux_sigkill(pid: RawPid, id: crate::identity::ProcessId) -> Reached {
match crate::wait::backend::open_verified(id, crate::wait::backend::PidfdOp::GroupTeardown) {
Ok(None) => Reached::Yes, Ok(Some(pidfd)) => match rustix::process::pidfd_send_signal(&pidfd, rustix::process::Signal::KILL) {
Ok(()) => Reached::Yes,
Err(rustix::io::Errno::SRCH) => Reached::Yes, Err(rustix::io::Errno::PERM) => {
log::debug!(
"containment::unix::group: pidfd_send_signal({}, KILL) refused: EPERM",
id.pid()
);
Reached::No
}
Err(e) => {
log::warn!(
"containment::unix::group: pidfd_send_signal({}, KILL) answered {e}, neither EPERM nor ESRCH",
id.pid()
);
Reached::Unknown
}
},
Err(e @ (crate::error::Error::Unsupported { .. } | crate::error::Error::Io(_))) => {
log::debug!(
"containment::unix::group: pidfd unavailable ({e}) for pid {}; falling back to \
kill(2) — same residual race macOS already accepts",
id.pid()
);
check_or_signal(pid, id, Some(Signal::SIGKILL))
}
Err(e @ crate::error::Error::NotThreadGroupLeader { .. }) => {
log::warn!(
"containment::unix::group: pid {} is a live thread, not a thread-group leader, so it \
is not signalled: {e}",
id.pid()
);
Reached::Unknown
}
Err(e) => {
log::warn!("containment::unix::group: open_verified for pid {}: {e}", id.pid());
Reached::Unknown
}
}
}
fn reconfirm_survivor(outcome: MemberOutcome, recheck: impl FnOnce() -> crate::identity::Liveness) -> MemberOutcome {
let MemberOutcome::Survivor(pid) = outcome else {
return outcome;
};
match recheck() {
crate::identity::Liveness::Alive => MemberOutcome::Survivor(pid),
crate::identity::Liveness::Dead => {
log::debug!(
"containment::unix::group: pid {pid} answered EPERM but has since gone (exited \
mid-teardown); downgraded from a confirmed refusal to not-a-survivor"
);
MemberOutcome::NotASurvivor
}
crate::identity::Liveness::Unknown => MemberOutcome::Survivor(pid),
}
}
pub(crate) fn converge(pgid: i32, signal: Signal) -> std::io::Result<GroupState> {
let listed = members(pgid)?;
#[cfg(test)]
fault::run_after_listing();
let mut refused = Vec::new();
let mut unassessable = Vec::new();
for m in &listed {
let id = crate::identity::ProcessId::from_parts(m.pid, m.token);
let outcome = classify_member(m.pid, id.is_alive(), || {
if signal == Signal::SIGKILL && excluded_from_sigkill_resend(m.pid, m.system) {
log::warn!(
"containment::unix::group: pid {pid} in process group {pgid} is excluded \
from the SIGKILL resend (mirrors xnu's own killpg1 exclusion for init/ \
P_SYSTEM) and reported unassessable, not cleared, since it was never \
actually reached",
pid = m.pid
);
return Reached::Unknown;
}
if signal == Signal::SIGKILL {
#[cfg(target_os = "linux")]
{
check_or_signal_linux_sigkill(m.pid, id)
}
#[cfg(not(target_os = "linux"))]
{
check_or_signal(m.pid, id, Some(signal))
}
} else {
check_or_signal(m.pid, id, None)
}
});
match reconfirm_survivor(outcome, || id.is_alive()) {
MemberOutcome::NotASurvivor => {}
MemberOutcome::Survivor(pid) => refused.push(pid),
MemberOutcome::Unassessable(pid) => unassessable.push(pid),
}
}
Ok(decide(pgid, signal, refused, unassessable))
}
fn excluded_from_sigkill_resend(pid: RawPid, system: bool) -> bool {
pid == 1 || system
}
fn decide(pgid: i32, signal: Signal, refused: Vec<RawPid>, unassessable: Vec<RawPid>) -> GroupState {
if !refused.is_empty() {
return GroupState::Refused { refused, unassessable };
}
if !unassessable.is_empty() {
let list = unassessable
.iter()
.map(|p| p.to_string())
.collect::<Vec<_>>()
.join(", ");
return GroupState::Unlistable {
detail: format!(
"{n} member(s) of process group {pgid} could not be assessed after {signal} \
(pid {list})",
n = unassessable.len(),
),
source: None,
};
}
GroupState::Cleared
}
pub(crate) fn state(pgid: i32, signal: Signal) -> GroupState {
debug_assert!(
pgid > 0,
"group::state called with a non-positive pgid ({pgid}); the real guard belongs in the \
caller, before any signal is sent — see unix.rs::signal_group"
);
match converge(pgid, signal) {
Ok(gs) => gs,
Err(e) => GroupState::Unlistable {
detail: format!("process group {pgid} could not be listed after {signal}"),
source: Some(e),
},
}
}
#[cfg(test)]
pub(crate) mod fault {
thread_local! {
static AFTER_LISTING: crate::oneshot_hook::OneShotHook = const { crate::oneshot_hook::OneShotHook::new() };
}
#[cfg(target_os = "linux")]
pub(crate) fn set_after_listing(hook: impl FnOnce() + 'static) -> ArmedAfterListing {
crate::oneshot_hook::arm(&AFTER_LISTING, hook)
}
pub(crate) fn run_after_listing() {
crate::oneshot_hook::fire(&AFTER_LISTING);
}
#[cfg(target_os = "linux")]
pub(crate) type ArmedAfterListing = crate::oneshot_hook::Armed;
#[cfg(target_os = "linux")]
pub(crate) use crate::identity::pid_stat::fault::force_stat_read;
}
#[cfg(test)]
#[path = "group_tests.rs"]
mod group_tests;
#[cfg(all(test, target_os = "linux"))]
#[path = "group_namespace_tests.rs"]
mod group_namespace_tests;