sinf 0.1.0

Library for obtaining in-depth system information at both the hardware and software levels
Documentation
use crate::sys::utils::{IOReleaser, MAIN_PORT};
use crate::{Gpu, PCI};

use objc2_core_foundation::{
    CFData, CFDictionary, CFNumber, CFRange, CFRetained, CFString, kCFAllocatorDefault,
};
use objc2_io_kit::{
    IOIteratorNext, IOObjectConformsTo, IORegistryEntryCreateCFProperty,
    IORegistryEntryGetParentEntry, IOServiceGetMatchingServices, IOServiceMatching, io_iterator_t,
    kIOReturnSuccess, kIOServicePlane,
};

mod info;
mod inner;
mod pci;
#[cfg(test)]
mod tests;

use self::info::is_gpu;
pub(crate) use self::inner::GpuInner;
use self::pci::parse_pcidebug;

pub(crate) struct GpusInner {
    pub(crate) gpus: Vec<Gpu>,
}

impl GpusInner {
    pub(crate) fn new() -> Result<Self, crate::Error> {
        Ok(Self { gpus: Vec::new() })
    }

    pub(crate) fn refresh(&mut self) {
        unsafe {
            let Some(matching) = IOServiceMatching(c"IOAccelerator".as_ptr()) else {
                sinf_debug!("Failed to create IOAccelerator matching dictionary");
                return;
            };
            let matching = CFRetained::<CFDictionary>::from(&matching);

            let mut iterator: io_iterator_t = 0;
            let result = IOServiceGetMatchingServices(*MAIN_PORT, Some(matching), &mut iterator);
            if result != kIOReturnSuccess {
                sinf_debug!("Error: IOServiceGetMatchingServices() = {result}");
                return;
            }

            let Some(iterator) = IOReleaser::new(iterator) else {
                sinf_debug!(
                    "GPU error: IOServiceGetMatchingServices succeeded but returned invalid descriptor"
                );
                return;
            };

            let model_key = CFString::from_str("model");
            let vendor_id_key = CFString::from_str("vendor-id");
            let class_code_key = CFString::from_str("class-code");
            let pcidebug_key = CFString::from_str("pcidebug");
            let perf_key = CFString::from_str("PerformanceStatistics");

            while let Some(accelerator) = IOReleaser::new(IOIteratorNext(iterator.inner())) {
                let mut device = 0;
                let ret = IORegistryEntryGetParentEntry(
                    accelerator.inner(),
                    kIOServicePlane.as_ptr() as *mut _,
                    &mut device,
                );
                if ret != kIOReturnSuccess || device == 0 {
                    continue;
                }
                let Some(device) = IOReleaser::new(device) else {
                    continue;
                };

                // M-series GPUs do not use PCI.
                let is_m_series =
                    if IOObjectConformsTo(device.inner(), c"AppleARMIODevice".as_ptr() as *mut _) {
                        true
                    } else if IOObjectConformsTo(device.inner(), c"IOPCIDevice".as_ptr() as *mut _)
                        && is_gpu(device.inner(), &class_code_key)
                    {
                        false
                    } else {
                        continue;
                    };

                let pci = if is_m_series {
                    // This fake PCI address is for identification only.
                    PCI {
                        domain: 0xffffffff,
                        bus: 0xff,
                        device: 0xff,
                        function: 0xff,
                    }
                } else if let Some(prop) = IORegistryEntryCreateCFProperty(
                    device.inner(),
                    Some(&pcidebug_key),
                    kCFAllocatorDefault,
                    0,
                ) && let Ok(prop_ref) = prop.downcast::<CFString>()
                    && let pcidebug = prop_ref.to_string()
                    && let Some(pci) = parse_pcidebug(pcidebug.as_str())
                {
                    pci
                } else {
                    continue;
                };

                let gpu = match self.gpus.iter_mut().find(|g| g.inner.pci == pci) {
                    Some(g) => {
                        g.inner.updated = true;
                        &mut g.inner
                    }
                    None => {
                        self.gpus.push(Gpu {
                            inner: GpuInner {
                                pci,
                                model: None,
                                vendor: None,
                                usage: None,
                                updated: true,
                            },
                        });
                        &mut self.gpus.last_mut().unwrap().inner
                    }
                };

                if gpu.model.is_none()
                    && let Some(model) = IORegistryEntryCreateCFProperty(
                        accelerator.inner(),
                        Some(&model_key),
                        kCFAllocatorDefault,
                        0,
                    )
                    && let Ok(model_ref) = model.downcast::<CFString>()
                {
                    gpu.model = Some(model_ref.to_string());
                }

                if gpu.vendor.is_none()
                    && let Some(vendor_prop) = IORegistryEntryCreateCFProperty(
                        accelerator.inner(),
                        Some(&vendor_id_key),
                        kCFAllocatorDefault,
                        0,
                    )
                    && let Ok(vendor_ref) = vendor_prop.downcast::<CFData>()
                    && vendor_ref.length() >= 4
                {
                    let mut vendor_id: u32 = 0;
                    vendor_ref.bytes(
                        CFRange {
                            location: 0,
                            length: 4,
                        },
                        &mut vendor_id as *mut _ as *mut _,
                    );
                    gpu.vendor = crate::gpu::gpu_vendor_name(vendor_id).map(|s| s.to_owned());
                }

                if let Some(usage) = IORegistryEntryCreateCFProperty(
                    accelerator.inner(),
                    Some(&perf_key),
                    kCFAllocatorDefault,
                    0,
                ) && let Some(usage_dict) = usage.downcast_ref::<CFDictionary>()
                    && let usage_dict = usage_dict.cast_unchecked::<CFString, CFNumber>()
                    && let Some(usage) = usage_dict
                        .get(&CFString::from_str("Device Utilization %"))
                        .or_else(|| usage_dict.get(&CFString::from_str("Device Utilization")))
                    && let Ok(usage) = usage.downcast::<CFNumber>()
                    && let Some(usage) = usage.as_i64()
                {
                    gpu.usage = Some(usage as f32);
                }
            }
        }
    }
}