use nix::sys::signal::Signal;
use crate::containment::{check_number, Root};
use crate::error::Error;
use crate::identity::{ProcessId, RawPid};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Member {
pub(crate) id: ProcessId,
pub(crate) system: bool,
}
#[cfg(target_os = "macos")]
pub(crate) fn members(_kernel: &dyn crate::identity::Kernel, 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 {
id: ProcessId::from_parts(
k.kp_proc.p_pid as RawPid,
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(kernel: &dyn crate::identity::Kernel, pgid: i32) -> std::io::Result<Vec<Member>> {
use crate::identity::stat_parse::parse_pgrp;
use crate::identity::Resolved;
let proc_dir =
crate::identity::proc_view_with(kernel)
.into_dir()
.map_err(|why| match why.openat2_requirement() {
Some(requirement) => listing_error(
std::io::ErrorKind::Unsupported,
format!("containment::unix::group::members: {requirement}, so pgid {pgid} cannot be listed"),
why.source.map(Into::into),
),
None => {
let message = format!(
"containment::unix::group::members: {why}, so its process listing says nothing about pgid {pgid}"
);
listing_error(std::io::ErrorKind::Other, message, why.source.map(Into::into))
}
})?;
let mut out = Vec::new();
for pid in kernel.pids(&proc_dir)? {
let stat = match crate::identity::pid_stat::read_in_scan(kernel, &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 ({report}); excluding it",
report = crate::error::Report(&e)
);
continue;
}
Err(e) => {
let message = format!("containment::unix::group::members: process group {pgid} cannot be listed");
return Err(listing_error(
std::io::ErrorKind::Other,
message,
Some(Box::new(e.into_cause())),
));
}
};
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 (id, own_stat) = match ProcessId::of_stat_with(kernel, pid) {
(Resolved::Found(read), _) => read,
(Resolved::Gone, _) => {
log::debug!("containment::unix::group::members: pid {pid} is gone; excluding it");
continue;
}
(Resolved::Unknown, cause) => match cause.into_error(&format!("pid {pid}")) {
Some(why) => {
let message =
format!("containment::unix::group::members: {why}, so process group {pgid} cannot be listed");
return Err(match why {
crate::error::Error::Unsupported { source, .. } => {
listing_error(std::io::ErrorKind::Unsupported, message, source.map(Into::into))
}
crate::error::Error::Unassessable { source, .. } => {
listing_error(std::io::ErrorKind::Other, message, source.map(Into::into))
}
other => {
debug_assert!(
false,
"an unreadable identity is Unsupported or Unassessable: {other:?}"
);
listing_error(std::io::ErrorKind::Other, message, None)
}
});
}
None => {
log::debug!(
"containment::unix::group::members: pid {pid} matched pgid {pgid} but its identity \
could not be read; excluding it"
);
continue;
}
},
};
if parse_pgrp(&own_stat) != Some(pgid as u32) {
log::debug!("containment::unix::group::members: pid {pid} is no longer in pgid {pgid}; excluding it");
continue;
}
out.push(Member { id, system: false });
}
Ok(out)
}
#[cfg(target_os = "linux")]
fn listing_error(
kind: std::io::ErrorKind,
message: String,
cause: Option<Box<dyn std::error::Error + Send + Sync>>,
) -> std::io::Error {
#[derive(Debug)]
struct Listing {
message: String,
cause: Option<Box<dyn std::error::Error + Send + Sync>>,
}
impl std::fmt::Display for Listing {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.message)
}
}
impl std::error::Error for Listing {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
self.cause.as_deref().map(|cause| cause as _)
}
}
std::io::Error::new(kind, Listing { message, cause })
}
#[cfg(all(unix, not(any(target_os = "macos", target_os = "linux"))))]
pub(crate) fn members(_kernel: &dyn crate::identity::Kernel, _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, Error)>,
unassessable: Vec<(RawPid, Error)>,
},
Unassessed { members: Vec<(RawPid, Error)> },
Unlistable { detail: String, source: std::io::Error },
}
#[derive(Debug)]
enum Reached {
Yes,
Killed,
No(Error),
Unknown(Error),
}
enum MemberOutcome {
NotASurvivor,
Survivor(RawPid, Error),
Unassessable(RawPid, Error),
}
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 | Reached::Killed => MemberOutcome::NotASurvivor,
Reached::No(cause) => MemberOutcome::Survivor(pid, cause),
Reached::Unknown(cause) => MemberOutcome::Unassessable(pid, cause),
},
}
}
fn probe_member(
kernel: &dyn crate::identity::Kernel,
pid: RawPid,
id: crate::identity::ProcessId,
root: Option<&dyn Root>,
) -> Reached {
if let Err(reached) = root_check_before_send(root, pid, None) {
return reached;
}
match crate::identity::ProcessId::of_with(kernel, pid).0 {
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 probed"
);
return Reached::Unknown(Error::Unassessable {
detail: "its identity could not be re-verified (access denied?), so it was not probed".to_owned(),
source: None,
});
}
}
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(Error::Unassessable {
detail: "it is not a single-process signal target".to_owned(),
source: None,
});
};
match super::probe_signal(super::Target::Member(pid), super::Sys::Process(target)) {
Ok(()) | Err(nix::errno::Errno::ESRCH) => Reached::Yes,
Err(e @ nix::errno::Errno::EPERM) => {
log::debug!("containment::unix::group: kill({pid}, 0) refused: EPERM");
Reached::No(Error::Io(e.into()))
}
Err(e) => {
log::warn!(
"containment::unix::group: kill({pid}, 0) answered {report}, neither EPERM nor ESRCH",
report = crate::error::Report(&e)
);
Reached::Unknown(Error::Io(e.into()))
}
}
}
fn root_check_before_send(root: Option<&dyn Root>, pid: RawPid, signal: Option<Signal>) -> Result<(), Reached> {
let send = signal.map_or_else(|| "probed".to_owned(), |signal| format!("resent {signal}"));
match check_number(root) {
Ok(()) => Ok(()),
Err(why @ crate::containment::NotItsGroup::Empty) => {
log::debug!(
"containment::unix::group: {why}, so pid {pid} is in another group, and is not {send}",
why = crate::error::Report(&why)
);
Err(Reached::Yes)
}
Err(why) => {
log::warn!(
"containment::unix::group: {why}, so pid {pid} is not {send}; it is unassessable",
why = crate::error::Report(&why)
);
Err(Reached::Unknown(Error::Unassessable {
detail: format!("{why}, so it is not {send}"),
source: why.cause(),
}))
}
}
}
fn resend_sigkill(
kernel: &dyn crate::identity::Kernel,
id: crate::identity::ProcessId,
root: Option<&dyn Root>,
) -> Reached {
use crate::containment::treewalk::KillOutcome;
use crate::signal::Sig;
match crate::os_process::open_with(kernel, id).map_err(crate::os_process::OpenFailure::into_open_error) {
Ok(None) => Reached::Yes, Ok(Some(os)) => match root_check_before_send(root, id.pid(), Some(Signal::SIGKILL)) {
Err(reached) => reached,
Ok(()) => {
match KillOutcome::of(os.signal(Sig::Kill)) {
KillOutcome::Terminated => Reached::Killed,
KillOutcome::AlreadyGone => Reached::Yes,
KillOutcome::NotAttempted(refused) if matches!(&refused, Error::Io(e) if e.raw_os_error() == Some(libc::EPERM)) =>
{
log::debug!("containment::unix::group: SIGKILL to pid {} refused: EPERM", id.pid());
Reached::No(refused)
}
KillOutcome::NotAttempted(e) => {
log::warn!(
"containment::unix::group: SIGKILL to pid {} answered {report}, neither EPERM nor ESRCH",
id.pid(),
report = crate::error::Report(&e)
);
Reached::Unknown(e)
}
}
}
},
Err(e @ Error::NotThreadGroupLeader { .. }) => {
log::warn!(
"containment::unix::group: pid {} is a live thread, not a thread-group leader, so it \
is not signalled: {report}",
id.pid(),
report = crate::error::Report(&e)
);
Reached::Unknown(e)
}
Err(e) => {
log::warn!(
"containment::unix::group: pid {} could not be opened by identity: {report}",
id.pid(),
report = crate::error::Report(&e)
);
Reached::Unknown(e)
}
}
}
fn reconfirm_survivor(outcome: MemberOutcome, recheck: impl FnOnce() -> crate::identity::Liveness) -> MemberOutcome {
let MemberOutcome::Survivor(pid, cause) = outcome else {
return outcome;
};
match recheck() {
crate::identity::Liveness::Alive => MemberOutcome::Survivor(pid, cause),
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, cause),
}
}
pub(crate) fn converge(
kernel: &dyn crate::identity::Kernel,
pgid: i32,
signal: Signal,
root: Option<&dyn Root>,
killed: &mut Vec<crate::identity::ProcessId>,
) -> std::io::Result<GroupState> {
#[cfg(test)]
let listing_pgid = fault::listed(pgid);
#[cfg(not(test))]
let listing_pgid = pgid;
let listed = members(kernel, listing_pgid)?;
#[cfg(test)]
fault::run_after_listing();
let mut refused = Vec::new();
let mut unassessable = Vec::new();
for m in &listed {
let id = m.id;
let mut delivered = false;
let outcome = classify_member(id.pid(), id.is_alive_with(kernel), || {
if signal == Signal::SIGKILL && excluded_from_sigkill_resend(id.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 = id.pid()
);
return Reached::Unknown(Error::Unassessable {
detail: "it is excluded from the SIGKILL resend (init, or a system process), so it was \
never reached"
.to_owned(),
source: None,
});
}
if signal == Signal::SIGKILL {
let reached = resend_sigkill(kernel, id, root);
delivered = matches!(reached, Reached::Killed);
reached
} else {
probe_member(kernel, id.pid(), id, root)
}
});
if delivered && Some(id.pid()) != root.map(Root::pid) {
killed.push(id);
}
match reconfirm_survivor(outcome, || id.is_alive_with(kernel)) {
MemberOutcome::NotASurvivor => {}
MemberOutcome::Survivor(pid, cause) => refused.push((pid, cause)),
MemberOutcome::Unassessable(pid, cause) => unassessable.push((pid, cause)),
}
}
Ok(decide(refused, unassessable))
}
fn excluded_from_sigkill_resend(pid: RawPid, system: bool) -> bool {
pid == 1 || system
}
fn decide(refused: Vec<(RawPid, Error)>, unassessable: Vec<(RawPid, Error)>) -> GroupState {
if !refused.is_empty() {
return GroupState::Refused { refused, unassessable };
}
if !unassessable.is_empty() {
return GroupState::Unassessed { members: unassessable };
}
GroupState::Cleared
}
pub(crate) fn state(
pgid: i32,
signal: Signal,
root: Option<&dyn Root>,
killed: &mut Vec<crate::identity::ProcessId>,
) -> 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(&crate::identity::HostKernel, pgid, signal, root, killed) {
Ok(gs) => gs,
Err(e) => GroupState::Unlistable {
detail: format!("process group {pgid} could not be listed after {signal}"),
source: e,
},
}
}
#[cfg(test)]
pub(crate) mod fault {
use std::cell::Cell;
thread_local! {
static AFTER_LISTING: crate::oneshot_hook::OneShotHook = const { crate::oneshot_hook::OneShotHook::new() };
static LIST_INSTEAD: Cell<Option<i32>> = const { Cell::new(None) };
}
#[cfg(target_os = "linux")]
pub(crate) fn list_instead(pgid: i32) -> ListInstead {
LIST_INSTEAD.with(|l| l.set(Some(pgid)));
ListInstead(())
}
#[cfg(target_os = "linux")]
#[must_use = "the listing names the given group again as soon as the guard is dropped"]
pub(crate) struct ListInstead(());
#[cfg(target_os = "linux")]
impl Drop for ListInstead {
fn drop(&mut self) {
LIST_INSTEAD.with(|l| l.set(None));
}
}
pub(super) fn listed(pgid: i32) -> i32 {
LIST_INSTEAD.with(Cell::get).unwrap_or(pgid)
}
#[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(test)]
#[path = "group_tests.rs"]
mod group_tests;
#[cfg(all(test, target_os = "linux"))]
#[path = "group_namespace_tests.rs"]
mod group_namespace_tests;