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::{Pid, Process};

use std::collections::HashMap;
use std::ffi::CStr;

use objc2_core_foundation::{CFArray, CFDictionary, CFNumber, CFRetained, CFString, CFType};

use objc2_io_kit::{
    IOIteratorNext, IORegistryEntryCreateCFProperties, IORegistryEntryGetChildIterator,
    IORegistryGetRootEntry, kIODeviceTreePlane, kIOReturnSuccess, kIOServicePlane,
};

struct Keys {
    accumulated_gpu_time: CFRetained<CFString>,
    app_usage: CFRetained<CFString>,
    io_user: CFRetained<CFString>,
}

impl Keys {
    fn new() -> Self {
        Self {
            accumulated_gpu_time: CFString::from_str("accumulatedGPUTime"),
            app_usage: CFString::from_str("AppUsage"),
            io_user: CFString::from_str("IOUserClientCreator"),
        }
    }
}

pub fn get_processes_gpu_usage(processes: &mut HashMap<Pid, Process>) {
    // A process can disappear from the IORegistry after it stops using the GPU.
    for process in processes.values_mut() {
        process.inner.gpu_usage = None;
    }

    let mut result = HashMap::new();

    unsafe {
        let root = IORegistryGetRootEntry(*MAIN_PORT);

        let Some(root) = IOReleaser::new(root) else {
            sinf_debug!("processes GPU: IORegistryGetRootEntry failed");
            return;
        };

        let keys = Keys::new();

        // If the information is stored inside other "planes", iterate through more of them.
        for plane in [kIODeviceTreePlane, kIOServicePlane] {
            walk_plane(&root, plane, &mut result, &keys);
        }
    }

    if !result.is_empty() {
        let instant = std::time::Instant::now();

        for (pid, gpu_time) in result {
            if let Some(proc) = processes.get_mut(&pid) {
                proc.inner.compute_gpu_usage(gpu_time, instant);
            }
        }
    }
}

unsafe fn walk_plane(
    entry: &IOReleaser,
    plane: &CStr,
    result: &mut HashMap<Pid, u64>,
    keys: &Keys,
) {
    unsafe {
        inspect(entry, result, keys);

        let mut iter = 0;
        if IORegistryEntryGetChildIterator(entry.inner(), plane.as_ptr() as *mut _, &mut iter)
            != kIOReturnSuccess
        {
            return;
        }
        let Some(iter) = IOReleaser::new(iter) else {
            return;
        };
        while let Some(child) = IOReleaser::new(IOIteratorNext(iter.inner())) {
            walk_plane(&child, plane, result, keys);
        }
    }
}

unsafe fn inspect(entry: &IOReleaser, result: &mut HashMap<Pid, u64>, keys: &Keys) {
    let mut props: Option<std::ptr::NonNull<CFDictionary<CFString, CFType>>> = None;

    unsafe {
        if IORegistryEntryCreateCFProperties(entry.inner(), &mut props as *mut _ as *mut _, None, 0)
            == kIOReturnSuccess
            && let Some(props) = props
            && let props = CFRetained::<CFDictionary<CFString, CFType>>::from_raw(props)
            && let Some(pid) = props.get(&keys.io_user)
            && let Some(pid) = pid.downcast::<CFString>().ok().map(|s| s.to_string())
            && let Some(pid) = pid.strip_prefix("pid ")
            && let Some(pid) = pid.split(',').next()
            && let Ok(pid) = pid.trim().parse::<libc::pid_t>().map(Pid)
        {
            // Implementation for macOS 12.6 and 15.7 (on non-`mac M*`).
            if let Some(gpu_time) = get_u64(&props, &keys.accumulated_gpu_time) {
                if gpu_time != 0 {
                    result
                        .entry(pid)
                        .and_modify(|v| *v += gpu_time)
                        .or_insert(gpu_time);
                }
            // For now, every other Mac configuration.
            } else if let Some(array) = get_array(&props, &keys.app_usage) {
                let array = array.cast_unchecked::<CFType>();
                for item in array.iter() {
                    if let Ok(item) = item.downcast::<CFDictionary>()
                        && let Some(gpu_time) = get_u64(
                            item.cast_unchecked::<CFString, CFType>(),
                            &keys.accumulated_gpu_time,
                        )
                        && gpu_time != 0
                    {
                        result
                            .entry(pid)
                            .and_modify(|v| *v += gpu_time)
                            .or_insert(gpu_time);
                    }
                }
            }
        }
    }
}

unsafe fn get_u64(dict: &CFDictionary<CFString, CFType>, key: &CFString) -> Option<u64> {
    unsafe {
        let dict = dict.cast_unchecked::<CFString, CFType>();
        dict.get(key)?
            .downcast::<CFNumber>()
            .ok()?
            .as_i64()
            .map(|x| x as u64)
    }
}

unsafe fn get_array(
    dict: &CFDictionary<CFString, CFType>,
    key: &CFString,
) -> Option<CFRetained<CFArray>> {
    unsafe {
        let dict = dict.cast_unchecked::<CFString, CFType>();
        dict.get(key)?.downcast::<CFArray>().ok()
    }
}

#[test]
fn missing_gpu_client_does_not_keep_previous_usage() {
    let pid = Pid::from_u32(u32::MAX);
    let mut process = Process {
        inner: crate::ProcessInner::new_empty(pid),
    };
    process.inner.gpu_usage = Some(17.0);

    let mut processes = HashMap::from([(pid, process)]);
    get_processes_gpu_usage(&mut processes);

    assert_eq!(processes[&pid].gpu_usage(), None);
}