use crate::error::{ Error, Result }; use crate::facility::{ CreatableFacility, Facility, FacilityType }; use crate::property_list::{ parse_dictionary, Array, Dictionary, Value }; use std::any::Any; use std::ffi::c_void; use std::slice::from_raw_parts; use async_fs::File; use rustix::ioctl::{ ioctl, Opcode, Getter }; use rustix::ioctl::opcode::read_write; use rustix::mm::munmap; pub struct EnvSys { sysmon: File, } #[repr(C)] #[derive(Debug)] struct PropertyListReference { data: *mut u8, size: usize, } impl Facility for EnvSys { fn as_any_mut(&mut self) -> &mut dyn Any { self } } impl CreatableFacility for EnvSys { const FACILITY_TYPE: FacilityType = FacilityType::ENVSYS; async fn new() -> Result { println!("loading envsys"); let sysmon = File::open("/dev/sysmon").await?; let envsys = EnvSys { sysmon }; envsys.get_dictionary().await?; Ok(envsys) } } impl EnvSys { const ENVSYS_GETDICTIONARY: Opcode = read_write::(b'E', 0); #[allow(dead_code)] const ENVSYS_SETDICTIONARY: Opcode = read_write::(b'E', 1); #[allow(dead_code)] const ENVSYS_REMOVEPROPS: Opcode = read_write::(b'E', 2); async fn get_dictionary(&self) -> Result { let call = unsafe { Getter::<{ Self::ENVSYS_GETDICTIONARY }, PropertyListReference>::new() }; /* If the call fails, we can safely return because there's no resulting * memory allocation. */ let result = unsafe { ioctl(&self.sysmon, call) }?; /* We're expecting the final byte to be a null, acting as a C string * terminator. We ignore it. */ let xml: &[u8] = unsafe { from_raw_parts(result.data, result.size - 1) }; /* This returns a Result, but we want to clean up before we peek inside. */ let dictionary = parse_dictionary(xml); /* So. Fun story. Inspecting NetBSD src/common/lib/libprop/prop_kern.c, * we find that the kernel creates a new memory mapping for the dictionary * it returns. When we're done, we're expected to munmap() it. Wild. * * Anyway, if munmap() fails we have no way to clean up regardless, so we * just return. */ unsafe { munmap(result.data as *mut c_void, result.size) }?; dictionary } }