sinf 0.1.0

Library for obtaining in-depth system information at both the hardware and software levels
Documentation
use std::io::Error;
use std::mem;

use crate::{Cpu, CpuRefreshKind, Error as SError};

use windows::Win32::Foundation::ERROR_INSUFFICIENT_BUFFER;
use windows::Win32::System::Power::{
    CallNtPowerInformation, PROCESSOR_POWER_INFORMATION, ProcessorInformation,
};
use windows::Win32::System::SystemInformation::{
    GetLogicalProcessorInformationEx, GetSystemInfo, RelationAll, RelationProcessorCore,
    SYSTEM_INFO, SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX,
};

use super::{CpuInner, get_vendor_id_and_brand};

// From https://stackoverflow.com/a/43813138: With 64 or fewer logical CPUs installed, the code above works.
pub(crate) fn get_frequencies(nb_cpus: usize) -> Vec<u64> {
    let size = nb_cpus * mem::size_of::<PROCESSOR_POWER_INFORMATION>();
    let mut infos: Vec<PROCESSOR_POWER_INFORMATION> = Vec::with_capacity(nb_cpus);

    unsafe {
        if CallNtPowerInformation(
            ProcessorInformation,
            None,
            0,
            Some(infos.as_mut_ptr() as _),
            size as _,
        )
        .is_ok()
        {
            infos.set_len(nb_cpus);
            // infos.Number
            return infos
                .into_iter()
                .map(|i| i.CurrentMhz as u64)
                .collect::<Vec<_>>();
        }
    }
    sinf_debug!("get_frequencies: CallNtPowerInformation failed");
    vec![0; nb_cpus]
}

pub(crate) fn get_physical_core_count() -> Result<usize, SError> {
    // The CPU count cannot be used to pre-calculate the buffer size.

    let mut needed_size = 0;
    unsafe {
        // This call always returns an error: it reports success only after writing at least one item to the buffer, which cannot happen here.
        let _err = GetLogicalProcessorInformationEx(RelationAll, None, &mut needed_size);

        let mut buf: Vec<u8> = Vec::with_capacity(needed_size as _);

        loop {
            // The length must be updated for `Vec::reserve` to add capacity when `GetLogicalProcessorInformationEx` fails because the buffer is too small.
            buf.set_len(needed_size as _);

            if GetLogicalProcessorInformationEx(
                RelationAll,
                Some(buf.as_mut_ptr().cast()),
                &mut needed_size,
            )
            .is_ok()
            {
                break;
            } else {
                let e = Error::last_os_error();
                // The function may still return a size that is too small.
                match e.raw_os_error() {
                    Some(value) if value == ERROR_INSUFFICIENT_BUFFER.0 as i32 => {}
                    _ => {
                        sinf_debug!("get_physical_core_count: GetLogicalCpuInformationEx failed");
                        return Err(SError::Other(
                            "failed to retrieve physical core count".into(),
                        ));
                    }
                }
            }
            let reserve = if needed_size as usize > buf.capacity() {
                needed_size as usize - buf.capacity()
            } else {
                1
            };
            needed_size = match needed_size.checked_add(reserve as _) {
                Some(new_size) => new_size,
                None => {
                    sinf_debug!(
                        "get_physical_core_count: buffer size is too big ({} + {})",
                        needed_size,
                        reserve,
                    );
                    return Err(SError::Other(
                        "failed to retrieve physical core count".into(),
                    ));
                }
            };
            buf.reserve(reserve);
        }

        buf.set_len(needed_size as _);

        let mut i = 0;
        let raw_buf = buf.as_ptr();
        let mut count = 0;
        while i < buf.len() {
            let p = &*(raw_buf.add(i) as *const SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX);
            i += p.Size as usize;
            if p.Relationship == RelationProcessorCore {
                // Count only the physical cores.
                count += 1;
            }
        }
        Ok(count)
    }
}

pub(crate) fn init_cpus(refresh_kind: CpuRefreshKind) -> Vec<Cpu> {
    unsafe {
        let mut sys_info = SYSTEM_INFO::default();
        GetSystemInfo(&mut sys_info);
        let (vendor_id, brand) = get_vendor_id_and_brand(&sys_info);
        let nb_cpus = sys_info.dwNumberOfProcessors as usize;
        let frequencies = if refresh_kind.frequency() {
            get_frequencies(nb_cpus)
        } else {
            vec![0; nb_cpus]
        };
        let mut ret = Vec::with_capacity(nb_cpus + 1);
        for (nb, frequency) in frequencies.iter().enumerate() {
            ret.push(Cpu {
                inner: CpuInner::new_with_values(
                    format!("CPU {}", nb + 1),
                    vendor_id.clone(),
                    brand.clone(),
                    *frequency,
                ),
            });
        }
        ret
    }
}