use std::fmt::Arguments;
use std::io;
use std::sync::{Arc, Mutex};
use super::Kernel;
use crate::identity::kinfo::kinfo_proc;
use crate::identity::{RawPid, ReadErr, Record, Resolved, UniqRead};
use crate::os_process::macos::kqueue::{Kqueue, Subscription};
struct Rows<A, T> {
once: Mutex<Vec<(A, T)>>,
every: Mutex<Vec<(A, EveryAnswer<T>)>>,
}
type EveryAnswer<T> = Arc<dyn Fn() -> T + Send + Sync>;
impl<A: PartialEq, T> Rows<A, T> {
fn new() -> Self {
Rows {
once: Mutex::new(Vec::new()),
every: Mutex::new(Vec::new()),
}
}
fn push(&self, asked: A, answer: T) {
self.once
.lock()
.expect("no thread panics holding the rows")
.push((asked, answer));
}
fn push_every(&self, asked: A, answer: impl Fn() -> T + Send + Sync + 'static) {
let mut rows = self.every.lock().expect("no thread panics holding the rows");
rows.retain(|(row, _)| *row != asked);
rows.push((asked, Arc::new(answer)));
}
fn spent(&self) -> bool {
self.once.lock().expect("no thread panics holding the rows").is_empty()
}
fn take(&self, asked: &A) -> Option<T> {
{
let mut rows = self.once.lock().expect("no thread panics holding the rows");
if let Some(at) = rows.iter().position(|(row, _)| row == asked) {
return Some(rows.remove(at).1);
}
}
let answer = self
.every
.lock()
.expect("no thread panics holding the rows")
.iter()
.find(|(row, _)| row == asked)
.map(|(_, answer)| Arc::clone(answer))?;
Some(answer())
}
}
type KinfoAnswer = (Resolved<kinfo_proc>, Option<io::Error>);
pub(crate) struct FakeKernel<'a> {
real: Option<&'a dyn Kernel>,
peeks: Rows<u32, io::Result<Option<Record>>>,
consumes: Rows<u32, io::Result<Option<Record>>>,
unique_infos: Rows<RawPid, UniqRead>,
short_bsds: Rows<RawPid, Result<libc::proc_bsdshortinfo, ReadErr>>,
bsd_infos: Rows<RawPid, Result<libc::proc_bsdinfo, ReadErr>>,
kinfos: Rows<RawPid, KinfoAnswer>,
subscribes: Rows<Subscription, Result<(), i32>>,
peek_reads: Mutex<Vec<(RawPid, usize)>>,
kinfo_reads: Mutex<Vec<(RawPid, usize)>>,
unique_info_reads: Mutex<Vec<(RawPid, usize)>>,
bsd_info_reads: Mutex<Vec<(RawPid, usize)>>,
}
fn count_read(counts: &Mutex<Vec<(RawPid, usize)>>, pid: RawPid) {
let mut counts = counts.lock().expect("no panic holds the counts");
match counts.iter_mut().find(|(p, _)| *p == pid) {
Some((_, n)) => *n += 1,
None => counts.push((pid, 1)),
}
}
fn reads_of(counts: &Mutex<Vec<(RawPid, usize)>>, pid: RawPid) -> usize {
let counts = counts.lock().expect("no panic holds the counts");
counts.iter().find(|(p, _)| *p == pid).map_or(0, |(_, n)| *n)
}
impl<'a> FakeKernel<'a> {
pub(crate) fn new() -> Self {
FakeKernel {
real: None,
peeks: Rows::new(),
consumes: Rows::new(),
unique_infos: Rows::new(),
short_bsds: Rows::new(),
bsd_infos: Rows::new(),
kinfos: Rows::new(),
subscribes: Rows::new(),
peek_reads: Mutex::new(Vec::new()),
kinfo_reads: Mutex::new(Vec::new()),
unique_info_reads: Mutex::new(Vec::new()),
bsd_info_reads: Mutex::new(Vec::new()),
}
}
pub(crate) fn over(real: &'a dyn Kernel) -> Self {
FakeKernel {
real: Some(real),
..Self::new()
}
}
pub(crate) fn on_peek(self, pid: u32, answer: io::Result<Option<Record>>) -> Self {
self.state_peek(pid, answer);
self
}
pub(crate) fn state_peek(&self, pid: u32, answer: io::Result<Option<Record>>) {
self.peeks.push(pid, answer);
}
pub(crate) fn on_every_peek(
self,
pid: u32,
answer: impl Fn() -> io::Result<Option<Record>> + Send + Sync + 'static,
) -> Self {
self.state_every_peek(pid, answer);
self
}
pub(crate) fn state_every_peek(
&self,
pid: u32,
answer: impl Fn() -> io::Result<Option<Record>> + Send + Sync + 'static,
) {
self.peeks.push_every(pid, answer);
}
pub(crate) fn on_consume(self, pid: u32, answer: io::Result<Option<Record>>) -> Self {
self.consumes.push(pid, answer);
self
}
pub(crate) fn on_unique_info(self, pid: RawPid, answer: UniqRead) -> Self {
self.state_unique_info(pid, answer);
self
}
pub(crate) fn state_unique_info(&self, pid: RawPid, answer: UniqRead) {
self.unique_infos.push(pid, answer);
}
pub(crate) fn on_short_bsd(self, pid: RawPid, answer: Result<libc::proc_bsdshortinfo, ReadErr>) -> Self {
self.state_short_bsd(pid, answer);
self
}
pub(crate) fn state_short_bsd(&self, pid: RawPid, answer: Result<libc::proc_bsdshortinfo, ReadErr>) {
self.short_bsds.push(pid, answer);
}
pub(crate) fn on_every_short_bsd(
self,
pid: RawPid,
answer: impl Fn() -> Result<libc::proc_bsdshortinfo, ReadErr> + Send + Sync + 'static,
) -> Self {
self.state_every_short_bsd(pid, answer);
self
}
pub(crate) fn state_every_short_bsd(
&self,
pid: RawPid,
answer: impl Fn() -> Result<libc::proc_bsdshortinfo, ReadErr> + Send + Sync + 'static,
) {
self.short_bsds.push_every(pid, answer);
}
pub(crate) fn on_bsd_info(self, pid: RawPid, answer: Result<libc::proc_bsdinfo, ReadErr>) -> Self {
self.bsd_infos.push(pid, answer);
self
}
pub(crate) fn on_kinfo(self, pid: RawPid, record: kinfo_proc) -> Self {
self.kinfos.push(pid, (Resolved::Found(record), None));
self
}
pub(crate) fn on_every_kinfo(self, pid: RawPid, record: impl Fn() -> kinfo_proc + Send + Sync + 'static) -> Self {
self.kinfos.push_every(pid, move || (Resolved::Found(record()), None));
self
}
pub(crate) fn on_kinfo_refused(self, pid: RawPid, errno: i32) -> Self {
self.kinfos
.push(pid, (Resolved::Unknown, Some(io::Error::from_raw_os_error(errno))));
self
}
pub(crate) fn on_every_unique_info(
self,
pid: RawPid,
answer: impl Fn() -> UniqRead + Send + Sync + 'static,
) -> Self {
self.unique_infos.push_every(pid, answer);
self
}
pub(crate) fn on_every_bsd_info_failing(self, pid: RawPid, error: ReadErr) -> Self {
self.bsd_infos.push_every(pid, move || Err(error));
self
}
pub(crate) fn on_every_kinfo_refused(self, pid: RawPid, errno: i32) -> Self {
self.kinfos.push_every(pid, move || {
(Resolved::Unknown, Some(io::Error::from_raw_os_error(errno)))
});
self
}
pub(crate) fn on_subscribe(self, what: Subscription) -> Self {
self.subscribes.push(what, Ok(()));
self
}
pub(crate) fn on_subscribe_refused(self, what: Subscription, errno: i32) -> Self {
self.subscribes.push(what, Err(errno));
self
}
pub(crate) fn peek_reads(&self, pid: u32) -> usize {
reads_of(&self.peek_reads, pid)
}
pub(crate) fn kinfo_reads(&self, pid: RawPid) -> usize {
reads_of(&self.kinfo_reads, pid)
}
pub(crate) fn unique_info_reads(&self, pid: RawPid) -> usize {
reads_of(&self.unique_info_reads, pid)
}
pub(crate) fn bsd_info_reads(&self, pid: RawPid) -> usize {
reads_of(&self.bsd_info_reads, pid)
}
pub(crate) fn record_reads(&self, pid: RawPid) -> usize {
self.bsd_info_reads(pid) + self.kinfo_reads(pid)
}
pub(crate) fn all_record_reads(&self) -> usize {
let total = |counts: &Mutex<Vec<(RawPid, usize)>>| {
let counts = counts.lock().expect("no panic holds the counts");
counts.iter().map(|(_, n)| n).sum::<usize>()
};
total(&self.bsd_info_reads) + total(&self.kinfo_reads)
}
pub(crate) fn all_rows_taken(&self) -> bool {
self.peeks.spent()
&& self.consumes.spent()
&& self.unique_infos.spent()
&& self.short_bsds.spent()
&& self.bsd_infos.spent()
&& self.kinfos.spent()
&& self.subscribes.spent()
}
fn real(&self, asked: Arguments<'_>) -> &'a dyn Kernel {
self.real
.unwrap_or_else(|| panic!("the fake kernel has no row left for {asked}"))
}
}
impl Kernel for FakeKernel<'_> {
fn peek(&self, pid: u32) -> io::Result<Option<Record>> {
count_read(&self.peek_reads, pid);
self.peeks
.take(&pid)
.unwrap_or_else(|| self.real(format_args!("a peek of pid {pid}")).peek(pid))
}
fn consume(&self, pid: u32) -> io::Result<Option<Record>> {
self.consumes
.take(&pid)
.unwrap_or_else(|| self.real(format_args!("a consume of pid {pid}")).consume(pid))
}
fn unique_info(&self, pid: RawPid) -> UniqRead {
count_read(&self.unique_info_reads, pid);
self.unique_infos.take(&pid).unwrap_or_else(|| {
self.real(format_args!("a unique-id read of pid {pid}"))
.unique_info(pid)
})
}
fn short_bsd(&self, pid: RawPid) -> Result<libc::proc_bsdshortinfo, ReadErr> {
self.short_bsds.take(&pid).unwrap_or_else(|| {
self.real(format_args!("a short BSD-info read of pid {pid}"))
.short_bsd(pid)
})
}
fn bsd_info(&self, pid: RawPid) -> Result<libc::proc_bsdinfo, ReadErr> {
count_read(&self.bsd_info_reads, pid);
self.bsd_infos
.take(&pid)
.unwrap_or_else(|| self.real(format_args!("a BSD-info read of pid {pid}")).bsd_info(pid))
}
fn kinfo(&self, pid: RawPid) -> KinfoAnswer {
count_read(&self.kinfo_reads, pid);
self.kinfos
.take(&pid)
.unwrap_or_else(|| self.real(format_args!("a kinfo_proc read of pid {pid}")).kinfo(pid))
}
fn subscribe(&self, kq: &Kqueue, what: Subscription) -> io::Result<()> {
match self.subscribes.take(&what) {
Some(Ok(())) => Ok(()),
Some(Err(errno)) => Err(io::Error::from_raw_os_error(errno)),
None => self.real(format_args!("the registration {what:?}")).subscribe(kq, what),
}
}
}
pub(crate) fn exit_record(status: i32) -> Record {
Record {
si_code: libc::CLD_EXITED,
si_status: status,
}
}
pub(crate) fn short_info(ppid: u32, status: u32) -> libc::proc_bsdshortinfo {
let mut info: libc::proc_bsdshortinfo = unsafe { std::mem::zeroed() };
info.pbsi_ppid = ppid;
info.pbsi_status = status;
info
}
pub(crate) fn short_info_held_by(pid: RawPid, ppid: u32) -> libc::proc_bsdshortinfo {
let mut info = super::HostKernel
.short_bsd(pid)
.unwrap_or_else(|e| panic!("pid {pid} is live and has a short BSD info: {e:?}"));
info.pbsi_ppid = ppid;
info
}