use std::io;
use std::os::fd::{BorrowedFd, OwnedFd};
use rustix::fs::{fstat, fstatfs};
use rustix::io::Errno;
use rustix::process::{pidfd_open, test_kill_process, Pid, PidfdFlags};
use super::proc_view::{ProcDir, ViewUnreadable};
pub(crate) const PIDFD_THREAD: PidfdFlags = PidfdFlags::from_bits_retain(libc::PIDFD_THREAD);
const PID_FS_MAGIC: i64 = 0x5049_4446;
pub(crate) trait Kernel: Sync {
fn pidfd_open(&self, target: Pid, flags: PidfdFlags) -> Result<OwnedFd, Errno>;
fn pidfs_ino(&self, fd: BorrowedFd<'_>) -> Result<Option<u64>, Errno>;
fn open_proc(&self) -> Result<ProcDir, ViewUnreadable>;
fn read(&self, dir: &ProcDir, path: &str) -> io::Result<Vec<u8>>;
fn pids(&self, dir: &ProcDir) -> io::Result<Vec<u32>>;
fn signal_probe(&self, target: Pid) -> Result<(), Errno>;
}
pub(crate) struct HostKernel;
impl Kernel for HostKernel {
fn pidfd_open(&self, target: Pid, flags: PidfdFlags) -> Result<OwnedFd, Errno> {
pidfd_open(target, flags)
}
fn pidfs_ino(&self, fd: BorrowedFd<'_>) -> Result<Option<u64>, Errno> {
if fstatfs(fd)?.f_type as i64 != PID_FS_MAGIC {
return Ok(None);
}
Ok(Some(fstat(fd)?.st_ino as u64))
}
fn open_proc(&self) -> Result<ProcDir, ViewUnreadable> {
ProcDir::open()
}
fn read(&self, dir: &ProcDir, path: &str) -> io::Result<Vec<u8>> {
dir.read(path)
}
fn pids(&self, dir: &ProcDir) -> io::Result<Vec<u32>> {
dir.pids()
}
fn signal_probe(&self, target: Pid) -> Result<(), Errno> {
test_kill_process(target)
}
}
#[cfg(test)]
#[path = "kernel/fake.rs"]
pub(crate) mod fake;
#[cfg(test)]
#[path = "kernel_tests.rs"]
mod kernel_tests;