use std::io;
use rustix::io::Errno;
use super::kernel::Kernel;
use super::proc_view::ProcDir;
use super::prove::FailedCall;
#[derive(Debug)]
pub(crate) enum PidStat {
Read(Vec<u8>),
Skipped(io::Error),
}
#[derive(Debug)]
pub(crate) struct Unreadable {
pid: u32,
kind: Kind,
cause: io::Error,
peer: Option<io::Error>,
}
impl Unreadable {
pub(crate) fn take_peer(&mut self) -> Option<io::Error> {
self.peer.take()
}
pub(crate) fn into_cause(mut self) -> crate::error::Error {
use crate::error::Error;
let peer = self.take_peer();
let own = Error::Io(io::Error::other(self));
match peer {
None => own,
Some(peer) => Error::Several(crate::error::Failures::new(
std::sync::Arc::new(own),
[Error::io_cause(peer)],
)),
}
}
}
#[derive(Debug)]
enum Kind {
BeyondMount,
DirectoryRefuses,
RecheckFailed,
Other,
}
impl std::fmt::Display for Unreadable {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let Unreadable { pid, kind, .. } = self;
match kind {
Kind::BeyondMount => write!(f, "{pid}/stat lies beyond a mount in /proc and was not read"),
Kind::DirectoryRefuses => write!(
f,
"{pid}/stat was refused (its error below), and the checked /proc refused self/stat too"
),
Kind::RecheckFailed => write!(f, "{pid}/stat was refused, and the re-check of self/stat failed"),
Kind::Other => write!(f, "{pid}/stat could not be read"),
}
}
}
impl std::error::Error for Unreadable {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
Some(&self.cause)
}
}
pub(crate) fn read_in_scan(kernel: &dyn Kernel, dir: &ProcDir, pid: u32) -> Result<PidStat, Unreadable> {
let source = match read_stat_file(kernel, dir, pid) {
Ok(stat) => return Ok(PidStat::Read(stat)),
Err(e) => e,
};
let (kind, cause, peer) = match source.raw_os_error() {
Some(libc::ENOENT | libc::ESRCH | libc::EACCES) => return Ok(PidStat::Skipped(source)),
Some(libc::EPERM) => match check_dir_answers(kernel, dir) {
Ok(()) => return Ok(PidStat::Skipped(source)),
Err(recheck) if is_refusal(&recheck) => (Kind::DirectoryRefuses, source, Some(recheck)),
Err(recheck) => (Kind::RecheckFailed, recheck, Some(source)),
},
Some(libc::EXDEV | libc::ELOOP) => (Kind::BeyondMount, source, None),
_ => (Kind::Other, source, None),
};
Err(Unreadable { pid, kind, cause, peer })
}
pub(crate) fn read_stat_file(kernel: &dyn Kernel, dir: &ProcDir, pid: u32) -> io::Result<Vec<u8>> {
kernel.read(dir, &format!("{pid}/stat"))
}
fn is_refusal(error: &io::Error) -> bool {
Errno::from_io_error(error).is_some_and(|errno| FailedCall::openat2(errno).requirement().is_some())
}
fn check_dir_answers(kernel: &dyn Kernel, dir: &ProcDir) -> io::Result<()> {
kernel.read(dir, "self/stat").map(drop)
}
#[cfg(test)]
#[path = "pid_stat_tests.rs"]
mod pid_stat_tests;