#[path = "linux/pid_stat.rs"]
pub(crate) mod pid_stat;
#[path = "linux/proc_view.rs"]
pub(crate) mod proc_view;
#[cfg(test)]
#[path = "linux/fault.rs"]
pub(crate) mod fault;
#[cfg(test)]
#[path = "linux/read_tests.rs"]
mod read_tests;
#[cfg(test)]
#[path = "linux/read_namespace_tests.rs"]
mod read_namespace_tests;
use std::time::{Duration, SystemTime};
use self::proc_view::ProcDir;
use super::probe::{classify_unreadable, SignalProbe};
use super::stat_parse::parse_starttime_jiffies;
use super::{Liveness, RawPid, Resolved, StartToken};
use crate::error::Error;
fn signal_probe(pid: RawPid) -> SignalProbe {
let Some(p) = super::probe::signal_target(pid) else {
return SignalProbe::NotAPid;
};
if unsafe { libc::kill(p, 0) } == 0 {
return SignalProbe::Signalable;
}
match std::io::Error::last_os_error().raw_os_error() {
Some(libc::ESRCH) => SignalProbe::NoSuchProcess,
_ => SignalProbe::Denied,
}
}
fn read_stat(pid: RawPid) -> Resolved<Vec<u8>> {
read_stat_explained(pid).0
}
fn read_stat_explained(pid: RawPid) -> (Resolved<Vec<u8>>, Option<proc_view::ViewUnreadable>) {
match proc_view::proc_view().into_dir() {
Ok(dir) => (read_stat_in(&dir, pid), None),
Err(why) => (
resolve_unreadable(pid, format_args!("the /proc view could not be established: {why}")),
Some(why),
),
}
}
fn read_stat_in(proc_dir: &ProcDir, pid: RawPid) -> Resolved<Vec<u8>> {
#[cfg(test)]
if let Some(errno) = proc_view::fault::forced_identity_stat_errno(pid) {
return resolve_unreadable(pid, std::io::Error::from_raw_os_error(errno));
}
read_stat_with(pid, || proc_dir.read(&format!("{pid}/stat")))
}
fn read_stat_with(pid: RawPid, read: impl FnOnce() -> std::io::Result<Vec<u8>>) -> Resolved<Vec<u8>> {
match read() {
Ok(bytes) => Resolved::Found(bytes),
Err(e) => resolve_unreadable(pid, e),
}
}
fn resolve_unreadable(pid: RawPid, why: impl std::fmt::Display) -> Resolved<Vec<u8>> {
match classify_unreadable(signal_probe(pid)) {
Resolved::Gone => Resolved::Gone,
_ => {
log::debug!("/proc/{pid}/stat not read ({why}) but the pid is not provably gone");
Resolved::Unknown
}
}
}
pub(super) fn signal_says_no_such_process(pid: RawPid) -> bool {
signal_probe(pid) == SignalProbe::NoSuchProcess
}
pub(super) fn start_token_explained(pid: RawPid) -> (Resolved<StartToken>, Option<proc_view::ViewUnreadable>) {
let (stat, cause) = read_stat_explained(pid);
(start_token_from(pid, stat), cause)
}
pub(super) fn start_token_in(proc_dir: &ProcDir, pid: RawPid) -> Resolved<StartToken> {
start_token_from(pid, read_stat_in(proc_dir, pid))
}
fn start_token_from(pid: RawPid, stat: Resolved<Vec<u8>>) -> Resolved<StartToken> {
#[cfg(test)]
if let Some(aliased) = fault::on_read(pid, matches!(stat, Resolved::Found(_))) {
return Resolved::Found(aliased);
}
match stat {
Resolved::Found(stat) => match parse_starttime_jiffies(&stat) {
Some(j) => Resolved::Found(StartToken::from_raw(j)),
None => {
log::debug!("/proc/{pid}/stat has no parseable starttime");
Resolved::Unknown
}
},
Resolved::Gone => Resolved::Gone,
Resolved::Unknown => Resolved::Unknown,
}
}
pub(super) fn is_running(pid: RawPid, start: StartToken) -> Liveness {
match read_stat(pid) {
Resolved::Found(stat) => super::stat_parse::running_from_stat(&stat, start),
Resolved::Gone => Liveness::Dead, Resolved::Unknown => Liveness::Unknown,
}
}
pub(super) fn is_running_in(proc_dir: &ProcDir, pid: RawPid, start: StartToken) -> Liveness {
match read_stat_in(proc_dir, pid) {
Resolved::Found(stat) => super::stat_parse::running_from_stat(&stat, start),
Resolved::Gone => Liveness::Dead,
Resolved::Unknown => Liveness::Unknown,
}
}
pub(super) fn current_token() -> Resolved<StartToken> {
match read_self_stat() {
Ok(stat) => start_token_from(std::process::id(), Resolved::Found(stat)),
Err(e) => {
log::error!("own start token unreadable: /proc/self/stat: {e}");
Resolved::Unknown
}
}
}
fn read_self_stat() -> std::io::Result<Vec<u8>> {
#[cfg(test)]
if let Some(bytes) = proc_view::fault::take_forced_self_stat() {
return Ok(bytes);
}
std::fs::read("/proc/self/stat")
}
pub(crate) fn unknown_identity_error(subject: &str) -> Option<Error> {
proc_view::proc_view()
.into_dir()
.err()
.map(|why| view_error(subject, why))
}
pub(crate) fn view_error(subject: &str, why: proc_view::ViewUnreadable) -> Error {
why.unsupported(format!("identifying {subject}"))
.unwrap_or_else(|| unassessable_view(subject, &why.reason, why.source))
}
fn unassessable_view(subject: &str, reason: &str, source: Option<std::io::Error>) -> Error {
let mut detail = format!("{subject} identity could not be read: {reason}");
if let Some(source) = &source {
detail.push_str(&format!(": {source}"));
}
Error::Unassessable { detail, source }
}
pub(super) fn created_at(start: StartToken) -> Option<SystemTime> {
let jiffies = start.raw();
let hz = clock_ticks_per_sec()?;
let btime = boot_time_secs()?;
let secs = btime + jiffies / hz;
let nanos = ((jiffies % hz) * 1_000_000_000 / hz) as u32;
Some(SystemTime::UNIX_EPOCH + Duration::new(secs, nanos))
}
fn clock_ticks_per_sec() -> Option<u64> {
let hz = unsafe { libc::sysconf(libc::_SC_CLK_TCK) };
(hz > 0).then_some(hz as u64)
}
fn boot_time_secs() -> Option<u64> {
std::fs::read_to_string("/proc/stat")
.ok()?
.lines()
.find_map(|l| l.strip_prefix("btime "))
.and_then(|v| v.trim().parse::<u64>().ok())
}
use super::persist::{Scope, ScopeReadError};
const BOOT_ID_PATH: &str = "/proc/sys/kernel/random/boot_id";
const PID_NS_PATH: &str = "/proc/self/ns/pid";
pub(super) fn session_scope() -> Result<Scope, ScopeReadError> {
session_scope_at(std::path::Path::new(BOOT_ID_PATH), std::path::Path::new(PID_NS_PATH))
}
pub(super) fn session_scope_at(
boot_id_path: &std::path::Path,
pid_ns_path: &std::path::Path,
) -> Result<Scope, ScopeReadError> {
use std::os::unix::fs::MetadataExt;
let boot_id = std::fs::read_to_string(boot_id_path).map_err(|source| ScopeReadError {
path: boot_id_path.display().to_string(),
source,
})?;
let boot_id = boot_id.trim();
if boot_id.is_empty() {
return Err(ScopeReadError {
path: boot_id_path.display().to_string(),
source: std::io::Error::new(std::io::ErrorKind::InvalidData, "boot_id is empty"),
});
}
let pid_ns = std::fs::metadata(pid_ns_path)
.map_err(|source| ScopeReadError {
path: pid_ns_path.display().to_string(),
source,
})?
.ino();
Ok(Scope {
boot_id: Some(boot_id.to_owned()),
pid_ns: Some(pid_ns),
})
}