use std::io;
use std::os::fd::{AsFd, AsRawFd, BorrowedFd, OwnedFd};
use std::sync::Arc;
use super::parse::{is_at_or_under, parse_v2_relative_path};
use super::KillRecord;
use crate::child::owned::teardown::Reach;
const PIDFD_GET_INFO: libc::Ioctl = 0xC040_FF0B_u32 as libc::Ioctl;
const PIDFD_INFO_CGROUPID: u64 = 1 << 2;
#[repr(C)]
#[derive(Default)]
struct PidfdInfo {
mask: u64,
cgroupid: u64,
rest: [u32; 12],
}
pub(crate) fn pidfd_cgroup_id(pidfd: BorrowedFd<'_>) -> io::Result<Option<u64>> {
#[cfg(test)]
if super::fault::pidfd_info_missing() {
return Ok(None);
}
#[cfg(test)]
if super::fault::pidfd_info_fails() {
return Err(io::Error::from_raw_os_error(libc::EIO));
}
#[cfg(test)]
if let Some(id) = super::fault::forced_pidfd_cgroup_id() {
return Ok(Some(id));
}
let mut info = PidfdInfo {
mask: PIDFD_INFO_CGROUPID,
..PidfdInfo::default()
};
let rc = unsafe { libc::ioctl(pidfd.as_raw_fd(), PIDFD_GET_INFO, &mut info as *mut PidfdInfo) };
if rc == 0 {
if info.mask & PIDFD_INFO_CGROUPID == 0 {
return Ok(None);
}
return Ok(Some(info.cgroupid));
}
let e = io::Error::last_os_error();
match e.raw_os_error() {
Some(libc::ENOTTY) | Some(libc::EINVAL) => Ok(None),
_ => Err(e),
}
}
pub(crate) fn proc_names(
leaf_path: &str,
pid: u32,
recorded: impl FnOnce() -> Option<bool>,
other_id: bool,
) -> io::Result<bool> {
#[cfg(test)]
if let Some(errno) = super::fault::proc_hidden_as() {
return Err(io::Error::from_raw_os_error(errno));
}
let proc_dir = match crate::identity::proc_view_with(&crate::identity::HostKernel) {
crate::identity::ProcView::Same(dir) => dir,
crate::identity::ProcView::Diverged => {
return Err(io::Error::other(format!(
"{}, so pid {pid}'s cgroup cannot be read",
crate::identity::DIVERGED_REASON
)));
}
crate::identity::ProcView::Unassessable(why) => {
let kind = why.source.as_ref().map_or(io::ErrorKind::Other, io::Error::kind);
return Err(io::Error::new(
kind,
format!(
"the /proc view could not be established, so pid {pid}'s cgroup cannot be read: {}",
why.reason
),
));
}
};
let text = proc_dir.read_to_string(&format!("{pid}/cgroup"))?;
let path = parse_v2_relative_path(&text)
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "no cgroup v2 `0::` line"))?;
names_leaf(path, leaf_path, other_id, recorded)
}
const DELETED: &str = " (deleted)";
pub(crate) fn names_leaf(
path: &str,
leaf_path: &str,
other_id: bool,
recorded: impl FnOnce() -> Option<bool>,
) -> io::Result<bool> {
if is_at_or_under(path, leaf_path) {
return Ok(true);
}
if path.strip_suffix(DELETED) != Some(leaf_path) || other_id {
return Ok(false);
}
recorded().ok_or_else(|| {
io::Error::other(format!(
"{path} is either the removed leaf or a live cgroup of that name, and the task's place was not \
recorded before the leaf's removal"
))
})
}
#[derive(Debug, Clone, Default)]
pub(crate) struct PlacedAtRemoval(Arc<std::sync::Mutex<Option<(u32, bool)>>>);
impl PlacedAtRemoval {
pub(crate) fn record(&self, pid: u32, inside: bool) {
*self.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some((pid, inside));
}
pub(crate) fn clear(&self) {
*self.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = None;
}
pub(crate) fn of(&self, pid: u32) -> Option<bool> {
match *self.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner) {
Some((recorded, inside)) if recorded == pid => Some(inside),
_ => None,
}
}
}
#[derive(Debug)]
pub(crate) struct Subtree {
leaf_id: Option<u64>,
dir: Option<Arc<OwnedFd>>,
path: Option<String>,
swept: super::Swept,
placed: PlacedAtRemoval,
killed: Arc<KillRecord>,
}
impl Subtree {
pub(crate) fn new(
leaf_id: Option<u64>,
dir: Option<Arc<OwnedFd>>,
path: Option<String>,
swept: super::Swept,
placed: PlacedAtRemoval,
killed: Arc<KillRecord>,
) -> Subtree {
Subtree {
leaf_id,
dir,
path,
swept,
placed,
killed,
}
}
pub(crate) fn holds(&self, pid: u32, pidfd: Option<BorrowedFd<'_>>) -> io::Result<bool> {
let mut elsewhere = false;
if let (Some(pidfd), Some(leaf_id)) = (pidfd, self.leaf_id) {
if let Some(id) = pidfd_cgroup_id(pidfd)? {
if id == leaf_id || self.swept.holds(id) {
return Ok(true);
}
if let Some(under) = self.walk_places(id) {
return Ok(under);
}
elsewhere = true;
}
}
let Some(path) = &self.path else {
return Ok(false);
};
proc_names(path, pid, || self.placed.of(pid), elsewhere).map_err(|e| {
if elsewhere {
io::Error::new(
e.kind(),
format!(
"pid {pid} is in another cgroup than its leaf, maybe one under it, and that cgroup's path \
cannot be read ({e})"
),
)
} else {
e
}
})
}
fn walk_places(&self, id: u64) -> Option<bool> {
let dir = self.dir.as_ref()?;
match super::find_descendant(dir.as_fd(), id) {
super::Walked::Found => Some(true),
super::Walked::Absent => match self.dying() {
Ok(Some(0)) => Some(false),
Ok(dying) => {
log::debug!(
"the cgroups under a leaf were all walked without finding cgroup {id}, but {} are removed \
and not yet freed, so it is not shown to be outside",
dying.map_or("an unknown number".to_owned(), |n| n.to_string())
);
None
}
Err(e) => {
log::debug!(
"the cgroups under a leaf were all walked without finding cgroup {id}, but its cgroup.stat \
cannot be read ({e}), so it is not shown to be outside"
);
None
}
},
super::Walked::Unknown(e) => {
log::debug!("the cgroups under a leaf could not all be walked ({e})");
None
}
}
}
fn dying(&self) -> io::Result<Option<u64>> {
let dir = self
.dir
.as_ref()
.ok_or_else(|| io::Error::other("the subtree holds no leaf directory"))?;
let file = rustix::fs::openat(
dir.as_fd(),
"cgroup.stat",
rustix::fs::OFlags::RDONLY | rustix::fs::OFlags::CLOEXEC,
rustix::fs::Mode::empty(),
)?;
let text = io::read_to_string(std::fs::File::from(file))?;
Ok(dying_in(&text))
}
pub(crate) fn reached_by(&self, pid: u32, pidfd: Option<BorrowedFd<'_>>) -> io::Result<bool> {
if !self.killed.landed() {
return Ok(false);
}
self.holds(pid, pidfd)
}
}
impl Reach for Subtree {
fn reached(&self, child: &crate::child::owned::OwnedChild) -> io::Result<bool> {
match child.pid() {
Some(pid) => self.reached_by(pid, child.pidfd()),
None => Err(io::Error::other("the child's pid is not known, so it cannot be placed")),
}
}
}
fn dying_in(text: &str) -> Option<u64> {
text.lines()
.find_map(|line| line.strip_prefix("nr_dying_descendants ")?.trim().parse::<u64>().ok())
}
pub(crate) fn front_placement(
kernel: &dyn crate::identity::Kernel,
leaf_id: impl FnOnce() -> io::Result<u64>,
) -> Result<(), crate::error::Error> {
use std::os::fd::AsFd;
if let Err(e) = leaf_id() {
return Err(match e.raw_os_error() {
Some(libc::ENOSYS | libc::EOPNOTSUPP | libc::EPERM) => unplaceable(format!(
"this host gives no cgroup's id by name_to_handle_at ({e}), as a kernel without CONFIG_FHANDLE, a \
filesystem without export operations or a seccomp filter refuses it"
)),
_ => crate::error::Error::Io(crate::error::io_context(
"the cgroup id of the elevated front's leaf",
e,
)),
});
}
let own = rustix::process::pidfd_open(rustix::process::getpid(), rustix::process::PidfdFlags::empty())
.map_err(|e| crate::error::Error::Io(crate::error::io_context("pidfd_open of this process", e.into())))?;
let own_id = pidfd_cgroup_id(own.as_fd());
drop(own);
match own_id {
Ok(Some(_)) => return Ok(()),
Ok(None) => {}
Err(e) => {
return Err(unplaceable(format!(
"PIDFD_GET_INFO failed on this process's own pidfd ({e})"
)))
}
}
untraceable_cgroup_readable(kernel).map_err(refusal)
}
fn refusal(why: Unreadable) -> crate::error::Error {
match why {
Unreadable::Hidden(e) => unplaceable(format!(
"this kernel has no PIDFD_GET_INFO (Linux 6.13 or later), and /proc hides the cgroup of a process \
this one may not trace ({e}), as a hidepid /proc does: it would hide the elevated front's too"
)),
Unreadable::View(why) => unplaceable(format!(
"this kernel has no PIDFD_GET_INFO (Linux 6.13 or later), and {why}"
)),
Unreadable::Probe(e) => crate::error::Error::Io(crate::error::io_context(
"probing whether /proc shows the cgroup of a process this one may not trace",
e,
)),
}
}
fn unplaceable(why: String) -> crate::error::Error {
crate::error::Error::Unsupported {
op: "contain() on an elevated command".into(),
platform: "linux",
detail: format!(
"{why}. cosca could not tell whether a cgroup kill reached the elevated front, so the spawn is \
refused before anything is spawned"
),
}
}
#[derive(Debug)]
enum Unreadable {
Hidden(io::Error),
View(String),
Probe(io::Error),
}
const RELEASED: i32 = 0;
const ABANDONED: i32 = 1;
struct Probe {
pid: libc::pid_t,
hold: Hold,
channel: Option<std::os::unix::net::UnixStream>,
}
impl Probe {
fn channel(&self) -> &std::os::unix::net::UnixStream {
self.channel.as_ref().expect("a probe is not ended while it is read")
}
fn end(mut self) -> io::Result<ProbeEnd> {
let channel = self.channel.take().expect("a probe is ended once");
kill_and_reap(self.pid, &self.hold, channel)
}
}
impl Drop for Probe {
fn drop(&mut self) {
let Some(channel) = self.channel.take() else {
return;
};
if let Err(e) = kill_and_reap(self.pid, &self.hold, channel) {
log::warn!(
"containment::cgroup: the placement probe's child {} could not be reaped ({e})",
self.pid
);
}
}
}
fn fork_probe(proc: &crate::identity::ProcDir, parent: libc::pid_t, dumpable: bool) -> io::Result<Probe> {
use std::os::fd::AsRawFd;
let _guard = crate::child::spawn::spawn_lock();
let (channel, child_end) = std::os::unix::net::UnixStream::pair()?;
let ends = Ends {
child: child_end.as_raw_fd(),
parent: channel.as_raw_fd(),
};
let pid = unsafe { libc::fork() };
if pid == 0 {
unsafe { probe_child(proc, parent, dumpable, ends) }
}
if pid < 0 {
return Err(io::Error::last_os_error());
}
drop(child_end);
let hold = match own_child_pidfd(pid) {
Ok(pidfd) => Hold::Pidfd(pidfd),
Err(Unpinned::Gone(e)) => return Err(e),
Err(Unpinned::Failed(e)) => {
log::warn!(
"containment::cgroup: no pidfd pins the placement probe's child {pid} ({e}), so it is killed and reaped by its number"
);
Hold::Number
}
};
Ok(Probe {
pid,
hold,
channel: Some(channel),
})
}
#[derive(Clone, Copy)]
struct Ends {
child: libc::c_int,
parent: libc::c_int,
}
unsafe fn probe_child(proc: &crate::identity::ProcDir, parent: libc::pid_t, dumpable: bool, ends: Ends) -> ! {
unsafe {
if !keep_only_own(proc, ends) {
libc::_exit(ABANDONED);
}
libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGKILL, 0, 0, 0);
if libc::getppid() != parent {
libc::_exit(ABANDONED);
}
if !dumpable {
libc::prctl(libc::PR_SET_DUMPABLE, 0, 0, 0, 0);
}
let mut pdeathsig: libc::c_int = 0;
libc::prctl(libc::PR_GET_PDEATHSIG, (&raw mut pdeathsig) as libc::c_ulong, 0, 0, 0);
let report = [libc::prctl(libc::PR_GET_DUMPABLE, 0, 0, 0, 0) as u8, pdeathsig as u8];
libc::write(ends.child, report.as_ptr().cast(), report.len());
let mut byte = 0u8;
let read = loop {
let n = libc::read(ends.child, (&raw mut byte).cast(), 1);
if n < 0 && *libc::__errno_location() == libc::EINTR {
continue;
}
break n;
};
libc::_exit(if read == 1 { RELEASED } else { ABANDONED });
}
}
unsafe fn keep_only_own(proc: &crate::identity::ProcDir, ends: Ends) -> bool {
use std::os::fd::IntoRawFd;
unsafe {
libc::close(ends.parent);
#[cfg(test)]
let opened = if super::fault::probe_fd_dir_fails() {
None
} else {
proc.open_own_fd_dir().ok()
};
#[cfg(not(test))]
let opened = proc.open_own_fd_dir().ok();
let Some(dir) = opened.map(IntoRawFd::into_raw_fd) else {
return false;
};
let close_range = |first: libc::c_uint, last: libc::c_uint| {
#[cfg(test)]
if super::fault::probe_close_range_refused() {
return false;
}
libc::syscall(libc::SYS_close_range, first, last, 0 as libc::c_uint) == 0
};
let ranges = ranges_around(ends.child as libc::c_uint, dir as libc::c_uint);
if ranges.iter().flatten().all(|&(first, last)| close_range(first, last)) {
libc::close(dir);
return true;
}
close_by_walk(dir, ends.child)
}
}
fn ranges_around(kept: libc::c_uint, dir: libc::c_uint) -> [Option<(libc::c_uint, libc::c_uint)>; 3] {
debug_assert_ne!(kept, dir, "the walk's directory is not the kept descriptor");
let (low, high) = (kept.min(dir), kept.max(dir));
[
low.checked_sub(1).map(|last| (0, last)),
(high - low > 1).then(|| (low + 1, high - 1)),
high.checked_add(1).map(|first| (first, libc::c_uint::MAX)),
]
}
unsafe fn close_by_walk(dir: libc::c_int, keep: libc::c_int) -> bool {
#[repr(C, align(8))]
struct Buf([u8; 1024]);
const RECLEN: usize = 16;
const NAME: usize = 19;
let mut buf = Buf([0; 1024]);
unsafe {
loop {
let n = libc::syscall(libc::SYS_getdents64, dir, buf.0.as_mut_ptr(), buf.0.len());
if n < 0 {
libc::close(dir);
return false;
}
if n == 0 {
break;
}
let mut closed = false;
let mut at = 0;
while at < n as usize {
let reclen = usize::from(u16::from_ne_bytes([buf.0[at + RECLEN], buf.0[at + RECLEN + 1]]));
let name = &buf.0[at + NAME..at + reclen];
at += reclen;
let mut fd: libc::c_int = 0;
let mut digits = 0;
for &b in name.iter().take_while(|&&b| b != 0) {
if !b.is_ascii_digit() {
digits = 0;
break;
}
fd = fd.wrapping_mul(10).wrapping_add(libc::c_int::from(b - b'0'));
digits += 1;
}
if digits == 0 || fd == dir || fd == keep {
continue;
}
libc::close(fd);
closed = true;
}
if closed && libc::lseek(dir, 0, libc::SEEK_SET) < 0 {
libc::close(dir);
return false;
}
}
libc::close(dir);
}
true
}
enum Hold {
Pidfd(OwnedFd),
Number,
}
enum Unpinned {
Gone(io::Error),
Failed(io::Error),
}
fn own_child_pidfd(pid: libc::pid_t) -> Result<OwnedFd, Unpinned> {
use rustix::process::{pidfd_open, Pid, PidfdFlags};
let Some(raw) = Pid::from_raw(pid) else {
unreachable!("fork returned pid {pid} to its parent");
};
#[cfg(test)]
let opened = match super::fault::run_before_probe_pin(pid) {
Some(errno) => Err(rustix::io::Errno::from_raw_os_error(errno)),
None => pidfd_open(raw, PidfdFlags::empty()),
};
#[cfg(not(test))]
let opened = pidfd_open(raw, PidfdFlags::empty());
match opened {
Ok(pidfd) => confirm_child(pid, pidfd),
Err(e @ rustix::io::Errno::SRCH) => Err(gone(pid, e)),
Err(e) => Err(Unpinned::Failed(io::Error::from(e))),
}
}
fn confirm_child(pid: libc::pid_t, pidfd: OwnedFd) -> Result<OwnedFd, Unpinned> {
use rustix::process::{waitid, WaitId, WaitIdOptions};
loop {
match waitid(
WaitId::PidFd(pidfd.as_fd()),
WaitIdOptions::EXITED | WaitIdOptions::NOHANG | WaitIdOptions::NOWAIT,
) {
Err(rustix::io::Errno::INTR) => continue,
Err(e @ rustix::io::Errno::CHILD) => return Err(gone(pid, e)),
Err(e) => return Err(Unpinned::Failed(io::Error::from(e))),
Ok(_) => return Ok(pidfd),
}
}
}
fn gone(pid: libc::pid_t, e: rustix::io::Errno) -> Unpinned {
Unpinned::Gone(io::Error::other(format!(
"the placement probe's child {pid} was reaped before it was pinned, by another reaper in this process or, with SIGCHLD ignored, by the kernel as it exited ({e})"
)))
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ProbeEnd {
Signal(i32),
Exit(i32),
Elsewhere,
}
fn kill_and_reap(pid: libc::pid_t, hold: &Hold, channel: std::os::unix::net::UnixStream) -> io::Result<ProbeEnd> {
#[cfg(test)]
let seam = super::fault::run_before_probe_kill(pid).map(rustix::io::Errno::from_raw_os_error);
#[cfg(not(test))]
let seam: Option<rustix::io::Errno> = None;
let killed = match hold {
Hold::Pidfd(pidfd) => kill_probe(ProbeKill::Pidfd(pidfd.as_fd()), seam),
Hold::Number => kill_probe(ProbeKill::Number(pid), seam),
};
match killed {
Ok(()) => {}
Err(rustix::io::Errno::SRCH) => log::debug!(
"containment::cgroup: the placement probe's child {pid} had already exited, or was reaped by another reaper in this process, when it was to be killed"
),
Err(e) => log::warn!(
"containment::cgroup: the kill of the placement probe's child {pid} failed ({e}); it is released to exit by itself"
),
}
release_probe(pid, channel);
match hold {
Hold::Pidfd(pidfd) => reap_through(pid, pidfd),
Hold::Number => reap_by_number(pid),
}
}
enum ProbeKill<'a> {
Pidfd(BorrowedFd<'a>),
Number(libc::pid_t),
}
fn kill_probe(kill: ProbeKill<'_>, seam: Option<rustix::io::Errno>) -> rustix::io::Result<()> {
use rustix::process::{kill_process, pidfd_send_signal, Pid, Signal};
let (signal, sent) = match (seam, &kill) {
(Some(errno), _) => (Signal::KILL, Err(errno)),
(None, ProbeKill::Pidfd(pidfd)) => {
let signal = Signal::KILL;
(signal, pidfd_send_signal(pidfd, signal))
}
(None, ProbeKill::Number(pid)) => match Pid::from_raw(*pid) {
Some(pid) => {
let signal = Signal::KILL;
(signal, kill_process(pid, signal))
}
None => unreachable!("fork returned pid {pid} to its parent"),
},
};
#[cfg(test)]
super::fault::record_probe_step(super::fault::ProbeStep::Kill(
match kill {
ProbeKill::Pidfd(_) => crate::send_log::Via::Pidfd,
ProbeKill::Number(_) => crate::send_log::Via::Pid,
},
signal.as_raw(),
));
#[cfg(not(test))]
let _ = signal;
sent
}
fn release_probe(pid: libc::pid_t, channel: std::os::unix::net::UnixStream) {
let sent = loop {
match rustix::net::send(&channel, &[0], rustix::net::SendFlags::NOSIGNAL) {
Err(rustix::io::Errno::INTR) => continue,
other => break other,
}
};
match sent {
Ok(_) | Err(rustix::io::Errno::PIPE | rustix::io::Errno::CONNRESET) => {}
Err(e) => log::warn!(
"containment::cgroup: the placement probe's child {pid} could not be released ({e}); it exits once every copy of its socket closes"
),
}
}
fn reap_through(pid: libc::pid_t, pidfd: &OwnedFd) -> io::Result<ProbeEnd> {
let end = loop {
match rustix::process::waitid(
rustix::process::WaitId::PidFd(pidfd.as_fd()),
rustix::process::WaitIdOptions::EXITED,
) {
Err(rustix::io::Errno::INTR) => continue,
Err(rustix::io::Errno::CHILD) => {
reaped_elsewhere(pid);
break ProbeEnd::Elsewhere;
}
Err(e) => return Err(io::Error::from(e)),
Ok(Some(status)) => match status.terminating_signal() {
Some(signo) => break ProbeEnd::Signal(signo),
None => break ProbeEnd::Exit(status.exit_status().unwrap_or(-1)),
},
Ok(None) => unreachable!("a waitid without WNOHANG returns a status"),
}
};
#[cfg(test)]
super::fault::record_probe_step(super::fault::ProbeStep::Reap(crate::send_log::Via::Pidfd, end));
Ok(end)
}
fn reap_by_number(pid: libc::pid_t) -> io::Result<ProbeEnd> {
let mut status = 0;
let end = loop {
if unsafe { libc::waitpid(pid, &mut status, 0) } == pid {
break if libc::WIFSIGNALED(status) {
ProbeEnd::Signal(libc::WTERMSIG(status))
} else {
ProbeEnd::Exit(libc::WEXITSTATUS(status))
};
}
let e = io::Error::last_os_error();
match e.raw_os_error() {
Some(libc::EINTR) => {}
Some(libc::ECHILD) => {
reaped_elsewhere(pid);
break ProbeEnd::Elsewhere;
}
_ => return Err(e),
}
};
#[cfg(test)]
super::fault::record_probe_step(super::fault::ProbeStep::Reap(crate::send_log::Via::Pid, end));
Ok(end)
}
fn reaped_elsewhere(pid: libc::pid_t) {
log::debug!("containment::cgroup: the placement probe's child {pid} was reaped by another reaper in this process");
}
fn describe_end(end: ProbeEnd) -> String {
match end {
ProbeEnd::Signal(signo) => format!("killed by signal {signo}"),
ProbeEnd::Exit(ABANDONED) => format!(
"exited ABANDONED ({ABANDONED}): it could not set up its descriptors, its socket closed with no release byte, or its parent was gone"
),
ProbeEnd::Exit(status) => format!("exited with status {status}"),
ProbeEnd::Elsewhere => "reaped by another reaper, so its status is lost".to_owned(),
}
}
fn log_probe_end(pid: libc::pid_t, end: ProbeEnd) {
match end {
ProbeEnd::Signal(libc::SIGKILL) | ProbeEnd::Exit(RELEASED) => {
log::debug!(
"containment::cgroup: the placement probe's child {pid} ended: {}",
describe_end(end)
);
}
ProbeEnd::Elsewhere => {}
other => log::warn!(
"containment::cgroup: the placement probe's child {pid} ended on its own: {}",
describe_end(other)
),
}
}
fn untraceable_cgroup_readable(kernel: &dyn crate::identity::Kernel) -> Result<(), Unreadable> {
let proc_dir = match crate::identity::proc_view_with(kernel) {
crate::identity::ProcView::Same(dir) => dir,
crate::identity::ProcView::Diverged => {
return Err(Unreadable::View(format!(
"{}, so no process's cgroup can be read by its pid",
crate::identity::DIVERGED_REASON
)))
}
crate::identity::ProcView::Unassessable(why) => {
return Err(Unreadable::View(format!(
"this process's /proc view could not be established ({})",
why.reason
)))
}
};
#[cfg(test)]
let dumpable = super::fault::probe_kept_dumpable();
#[cfg(not(test))]
let dumpable = false;
let probe =
fork_probe(&proc_dir, rustix::process::getpid().as_raw_nonzero().get(), dumpable).map_err(Unreadable::Probe)?;
let pid = probe.pid;
let mut ready = [0u8; 2];
let readied = loop {
match std::io::Read::read(&mut probe.channel(), &mut ready) {
Err(e) if e.kind() == io::ErrorKind::Interrupted => {}
other => break other,
}
};
#[cfg(test)]
let hidden = super::fault::proc_hidden_as();
#[cfg(not(test))]
let hidden: Option<i32> = None;
let read = match readied {
Ok(2) if ready[0] != 0 => Some(Err(Unreadable::Probe(io::Error::other(
"the probe's child could not make itself non-dumpable",
)))),
Ok(2) if i32::from(ready[1]) != libc::SIGKILL => Some(Err(Unreadable::Probe(io::Error::other(
"the probe's child could not ask to die with its parent",
)))),
Ok(2) => Some(
match hidden {
Some(errno) => Err(io::Error::from_raw_os_error(errno)),
None => kernel
.read(&proc_dir, &format!("{pid}/cgroup"))
.and_then(crate::identity::utf8)
.map(drop),
}
.map_err(|e| match e.raw_os_error() {
Some(libc::ENOENT | libc::EPERM | libc::EACCES) => Unreadable::Hidden(e),
_ => Unreadable::Probe(e),
}),
),
Ok(_) => None,
Err(e) => Some(Err(Unreadable::Probe(e))),
};
let end = probe.end().map_err(Unreadable::Probe)?;
log_probe_end(pid, end);
read.unwrap_or_else(|| {
Err(Unreadable::Probe(io::Error::other(format!(
"the probe's child died before it was ready: it {}",
describe_end(end)
))))
})
}
#[cfg(test)]
#[path = "reach_tests.rs"]
mod reach_tests;