use std::os::fd::AsFd;
use std::time::Instant;
use rustix::event::{poll, PollFd, PollFlags};
use rustix::process::{pidfd_open, pidfd_send_signal, Pid, PidfdFlags, Signal};
use crate::error::Error;
use crate::identity::{Existence, Liveness, PidfdTarget, ProcDir, ProcView, ProcessId, ViewUnreadable};
pub(crate) fn open_verified(id: ProcessId, op: PidfdOp) -> Result<Option<rustix::fd::OwnedFd>, Error> {
debug_assert!(
id.pid() <= i32::MAX as u32,
"pid {} exceeds i32::MAX; pidfd cast would truncate",
id.pid()
);
let raw = Pid::from_raw(id.pid() as i32).expect("a resolvable ProcessId is never pid 0");
match pidfd_open_checked(raw) {
Ok(pidfd) => verify_pidfd_target(id, pidfd, op),
Err(rustix::io::Errno::SRCH) => Ok(None),
Err(e @ (rustix::io::Errno::INVAL | rustix::io::Errno::NOENT)) => verify_without_pidfd(id, op, e),
Err(e) => match refusal_name(e) {
Some(name) => Err(pidfd_open_unsupported(op, name)),
None => Err(Error::Io(crate::error::io_context(
"pidfd_open",
std::io::Error::from(e),
))),
},
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum PidfdOp {
Wait,
Kill,
Terminate,
GroupTeardown,
Spawn,
}
impl PidfdOp {
fn name(self) -> &'static str {
match self {
PidfdOp::Wait => "process wait",
PidfdOp::Kill => "process kill",
PidfdOp::Terminate => "process terminate",
PidfdOp::GroupTeardown => "process-group teardown",
PidfdOp::Spawn => "spawn",
}
}
fn consequence(self) -> &'static str {
match self {
PidfdOp::Wait => "its exit cannot be observed",
PidfdOp::Kill | PidfdOp::Terminate => "no signal was sent",
PidfdOp::GroupTeardown => "process-group teardown verification",
PidfdOp::Spawn => {
debug_assert!(
false,
"spawn adopts through open_own_child, which never reports Unassessable"
);
"the spawned child cannot be adopted"
}
}
}
}
fn refusal_name(errno: rustix::io::Errno) -> Option<&'static str> {
match errno {
rustix::io::Errno::NOSYS => Some("ENOSYS"),
rustix::io::Errno::PERM => Some("EPERM"),
rustix::io::Errno::ACCESS => Some("EACCES"),
rustix::io::Errno::NODEV => Some("ENODEV"),
_ => None,
}
}
fn pidfd_open_unsupported(op: PidfdOp, errno_name: &str) -> Error {
Error::Unsupported {
op: op.name().into(),
platform: "linux",
detail: format!(
"cosca requires pidfd_open (Linux \u{2265} 5.3), refused here: pidfd_open answered {errno_name}"
),
}
}
pub(crate) fn spawn_open_error(errno: rustix::io::Errno) -> Error {
match refusal_name(errno) {
Some(name) => pidfd_open_unsupported(PidfdOp::Spawn, name),
None => Error::Io(crate::error::io_context("pidfd_open", std::io::Error::from(errno))),
}
}
pub(crate) fn probe_pidfd_support() -> Result<(), Error> {
pidfd_open_checked(rustix::process::getpid())
.map(drop)
.map_err(spawn_open_error)
}
#[cfg(test)]
pub(crate) fn take_scripted_pidfd_open() -> Option<rustix::io::Errno> {
fault::take_forced_pidfd_open_errno()
}
#[cfg(test)]
pub(crate) fn open_own_child(pid: u32, id: Option<ProcessId>) -> Result<Option<rustix::fd::OwnedFd>, Error> {
use crate::wait::exit_only::{self, Foreign, Peek, Target};
debug_assert!(
pid <= i32::MAX as u32,
"pid {pid} exceeds i32::MAX; pidfd cast would truncate"
);
let raw = Pid::from_raw(pid as i32).expect("a spawned child's pid is never 0");
let pidfd = match pidfd_open_checked(raw) {
Ok(pidfd) => pidfd,
Err(rustix::io::Errno::SRCH | rustix::io::Errno::INVAL | rustix::io::Errno::NOENT) => return Ok(None),
Err(e) => return Err(spawn_open_error(e)),
};
let pidfd = crate::above_stdio::above_stdio(pidfd).map_err(Error::Io)?;
if let Some(id) = id {
if let ProcView::Same(proc_dir) = crate::identity::proc_view() {
if exists_checked(id, &proc_dir) == Existence::Gone {
return Ok(None);
}
}
}
match exit_only::peek(&Target::PidFd(pidfd.as_fd())) {
Ok(Peek::Foreign(Foreign::Gone)) => Ok(None),
Ok(_) => Ok(Some(pidfd)),
Err(e) => Err(Error::Io(e)),
}
}
fn verify_without_pidfd(
id: ProcessId,
op: PidfdOp,
errno: rustix::io::Errno,
) -> Result<Option<rustix::fd::OwnedFd>, Error> {
if id.signal_says_no_such_process() {
return Ok(None);
}
match crate::identity::proc_view() {
ProcView::Same(proc_dir) => match exists_checked(id, &proc_dir) {
Existence::Gone => Ok(None),
Existence::Present => match alive_checked(id, &proc_dir) {
Liveness::Dead => Ok(None),
Liveness::Alive => Err(Error::NotThreadGroupLeader {
pid: id.pid(),
detail: op.consequence().into(),
source: std::io::Error::from(errno),
}),
Liveness::Unknown => Err(unassessable(
id,
op,
"the OS refused the liveness query",
None,
Some(errno),
)),
},
Existence::Unknown => Err(unassessable(
id,
op,
"the OS refused the existence query",
None,
Some(errno),
)),
},
ProcView::Diverged => Err(unassessable(
id,
op,
"this process's /proc is an outer pid namespace's",
None,
Some(errno),
)),
ProcView::Unassessable(why) => Err(view_unreadable(id, op, why, Some(errno))),
}
}
fn verify_pidfd_target(
id: ProcessId,
pidfd: rustix::fd::OwnedFd,
op: PidfdOp,
) -> Result<Option<rustix::fd::OwnedFd>, Error> {
let proc_dir = crate::identity::ProcDir::open().map_err(|why| view_unreadable(id, op, why, None))?;
match crate::identity::pidfd_pid_in_view(&proc_dir, pidfd.as_fd()) {
Ok(PidfdTarget::Pid(pid)) if pid == id.pid() => {}
Ok(PidfdTarget::Reaped) => return Ok(None),
Ok(PidfdTarget::Pid(pid)) => {
return Err(unassessable(
id,
op,
&format!(
"the mounted /proc numbers the target {pid} (0 = invisible), so it is an outer pid namespace's"
),
None,
None,
));
}
Err(why) => return Err(unassessable(id, op, &why.reason, why.source, None)),
}
match exists_checked(id, &proc_dir) {
Existence::Present => Ok(Some(pidfd)),
Existence::Gone => Ok(None),
Existence::Unknown => Err(unassessable(id, op, "the OS refused the existence query", None, None)),
}
}
fn view_unreadable(id: ProcessId, op: PidfdOp, why: ViewUnreadable, pidfd_errno: Option<rustix::io::Errno>) -> Error {
match why.unsupported(op.name()) {
Some(unsupported) => {
log::warn!("wait: pid {} {}: {unsupported}", id.pid(), op.name());
unsupported
}
None => unassessable(id, op, &why.reason, why.source, pidfd_errno),
}
}
fn unassessable(
id: ProcessId,
op: PidfdOp,
why: &str,
source: Option<std::io::Error>,
pidfd_errno: Option<rustix::io::Errno>,
) -> Error {
let mut detail = format!("pid {} identity could not be confirmed: {why}", id.pid());
if let Some(source) = &source {
detail.push_str(&format!(": {source}"));
}
if let Some(errno) = pidfd_errno {
detail.push_str(&format!(" (pidfd_open: {errno})"));
}
detail.push_str(&format!("; {}", op.consequence()));
log::warn!("wait: {detail}");
Error::Unassessable {
detail,
source: source.or_else(|| pidfd_errno.map(std::io::Error::from)),
}
}
#[cfg(test)]
fn pidfd_open_checked(raw: Pid) -> Result<rustix::fd::OwnedFd, rustix::io::Errno> {
match fault::take_forced_pidfd_open_errno() {
Some(errno) => Err(errno),
None => pidfd_open(raw, PidfdFlags::empty()),
}
}
#[cfg(not(test))]
fn pidfd_open_checked(raw: Pid) -> Result<rustix::fd::OwnedFd, rustix::io::Errno> {
pidfd_open(raw, PidfdFlags::empty())
}
#[cfg(test)]
fn exists_checked(id: ProcessId, proc_dir: &ProcDir) -> Existence {
fault::run_between_hook();
match fault::take_forced_exists() {
Some(existence) => existence,
None => id.exists_in(proc_dir),
}
}
#[cfg(not(test))]
fn exists_checked(id: ProcessId, proc_dir: &ProcDir) -> Existence {
id.exists_in(proc_dir)
}
#[cfg(test)]
fn alive_checked(id: ProcessId, proc_dir: &ProcDir) -> Liveness {
match fault::take_forced_alive() {
Some(liveness) => liveness,
None => id.is_alive_in(proc_dir),
}
}
#[cfg(not(test))]
fn alive_checked(id: ProcessId, proc_dir: &ProcDir) -> Liveness {
id.is_alive_in(proc_dir)
}
#[cfg(test)]
pub(crate) mod fault {
use crate::identity::{Existence, Liveness};
use std::cell::Cell;
thread_local! {
static FORCE_PIDFD_OPEN_ERRNO: std::cell::RefCell<std::collections::VecDeque<Option<rustix::io::Errno>>> =
const { std::cell::RefCell::new(std::collections::VecDeque::new()) };
static FORCE_EXISTS: Cell<Option<Existence>> = const { Cell::new(None) };
static FORCE_ALIVE: Cell<Option<Liveness>> = const { Cell::new(None) };
static BETWEEN_HOOK: std::cell::RefCell<Option<Box<dyn FnOnce()>>> = const { std::cell::RefCell::new(None) };
}
#[must_use = "dropping this immediately disarms the hook; bind it for the probe's duration"]
pub(crate) struct BetweenHook(());
pub(crate) fn between_check_and_read(hook: impl FnOnce() + 'static) -> BetweenHook {
BETWEEN_HOOK.with(|h| *h.borrow_mut() = Some(Box::new(hook)));
BetweenHook(())
}
impl Drop for BetweenHook {
fn drop(&mut self) {
BETWEEN_HOOK.with(|h| h.borrow_mut().take());
}
}
pub(super) fn run_between_hook() {
if let Some(hook) = BETWEEN_HOOK.with(|h| h.borrow_mut().take()) {
hook();
}
}
#[must_use = "dropping this immediately disarms the forced errno; bind it for the probe's duration"]
pub(crate) struct ForcedPidfdOpenErrno(());
pub(crate) fn force_pidfd_open_errno_once(errno: rustix::io::Errno) -> ForcedPidfdOpenErrno {
force_pidfd_open_script([Some(errno)])
}
pub(crate) fn force_pidfd_open_script(
script: impl IntoIterator<Item = Option<rustix::io::Errno>>,
) -> ForcedPidfdOpenErrno {
FORCE_PIDFD_OPEN_ERRNO.with(|f| *f.borrow_mut() = script.into_iter().collect());
ForcedPidfdOpenErrno(())
}
impl Drop for ForcedPidfdOpenErrno {
fn drop(&mut self) {
FORCE_PIDFD_OPEN_ERRNO.with(|f| f.borrow_mut().clear());
}
}
pub(crate) fn take_forced_pidfd_open_errno() -> Option<rustix::io::Errno> {
FORCE_PIDFD_OPEN_ERRNO.with(|f| f.borrow_mut().pop_front().flatten())
}
#[must_use = "dropping this immediately disarms the forced existence; bind it for the probe's duration"]
pub(crate) struct ForcedExists(());
pub(crate) fn force_exists_once(existence: Existence) -> ForcedExists {
FORCE_EXISTS.with(|f| f.set(Some(existence)));
ForcedExists(())
}
impl Drop for ForcedExists {
fn drop(&mut self) {
FORCE_EXISTS.with(|f| f.set(None));
}
}
pub(crate) fn take_forced_exists() -> Option<Existence> {
FORCE_EXISTS.with(|f| f.take())
}
#[must_use = "dropping this immediately disarms the forced liveness; bind it for the probe's duration"]
pub(crate) struct ForcedAlive(());
pub(crate) fn force_alive_once(liveness: Liveness) -> ForcedAlive {
FORCE_ALIVE.with(|f| f.set(Some(liveness)));
ForcedAlive(())
}
impl Drop for ForcedAlive {
fn drop(&mut self) {
FORCE_ALIVE.with(|f| f.set(None));
}
}
pub(crate) fn take_forced_alive() -> Option<Liveness> {
FORCE_ALIVE.with(|f| f.take())
}
}
pub(crate) fn block_until_exit(id: ProcessId, deadline: Option<Option<Instant>>) -> Result<bool, Error> {
let Some(pidfd) = open_verified(id, PidfdOp::Wait)? else {
return Ok(true);
};
loop {
let mut fds = [PollFd::new(&pidfd, PollFlags::IN)];
let ts = crate::wait::remaining(deadline).map(|d| rustix::event::Timespec {
tv_sec: d.as_secs().min(i64::MAX as u64) as i64,
tv_nsec: d.subsec_nanos() as _,
});
match poll(&mut fds, ts.as_ref()) {
Ok(0) => return Ok(false), Ok(_) => {
let revents = fds[0].revents();
debug_assert!(
!revents.contains(PollFlags::NVAL),
"pidfd reported POLLNVAL — owned-fd contract violation"
);
if revents.contains(PollFlags::ERR) {
return Err(Error::Io(std::io::Error::other("pidfd poll returned POLLERR")));
}
return Ok(true); }
Err(rustix::io::Errno::INTR) => continue, Err(e) => return Err(Error::Io(std::io::Error::from(e))),
}
}
}
pub(crate) fn kill(id: ProcessId) -> Result<(), Error> {
let Some(pidfd) = open_verified(id, PidfdOp::Kill)? else {
return Ok(());
};
match pidfd_send_signal(&pidfd, Signal::KILL) {
Ok(()) => Ok(()),
Err(rustix::io::Errno::SRCH) => Ok(()), Err(e) => Err(Error::Io(std::io::Error::from(e))),
}
}
pub(crate) fn terminate(id: ProcessId) -> Result<(), Error> {
let Some(pidfd) = open_verified(id, PidfdOp::Terminate)? else {
return Ok(());
};
match pidfd_send_signal(&pidfd, Signal::TERM) {
Ok(()) => Ok(()),
Err(rustix::io::Errno::SRCH) => Ok(()), Err(e) => Err(Error::Io(std::io::Error::from(e))),
}
}
#[cfg(test)]
#[path = "linux_tests.rs"]
mod linux_tests;
#[cfg(test)]
#[path = "linux_namespace_tests.rs"]
mod linux_namespace_tests;
#[cfg(test)]
#[path = "linux_openat2_tests.rs"]
mod linux_openat2_tests;