sinf 0.1.0

Library for obtaining in-depth system information at both the hardware and software levels
Documentation
use windows::Win32::System::SystemInformation::{FIRMWARE_TABLE_PROVIDER, GetSystemFirmwareTable};

use super::types::SMBIOSType;

/// Retrieves the SMBIOS table through the Win32 API.
pub(crate) fn get_smbios_table() -> Option<Vec<u8>> {
    const PROVIDER: FIRMWARE_TABLE_PROVIDER = FIRMWARE_TABLE_PROVIDER(u32::from_be_bytes(*b"RSMB"));

    let size = unsafe { GetSystemFirmwareTable(PROVIDER, 0, None) };
    if size == 0 {
        return None;
    }

    let mut buffer = vec![0u8; size as usize];
    if unsafe { GetSystemFirmwareTable(PROVIDER, 0, Some(&mut buffer)) } == 0 {
        return None;
    }
    Some(buffer)
}

/// Parses the SMBIOS table to retrieve the structure with the given type number.
pub(crate) fn parse_smbios<T: SMBIOSType>(table: &[u8], number: u8) -> Option<(T, Vec<&str>)> {
    let mut offset = 0;
    while offset + 1 < table.len() {
        let kind = table[offset];
        let length = table[offset + 1] as usize;
        if length < 2 || offset + length > table.len() {
            return None;
        }
        let strings_start = offset + length;
        let strings_end = find_strings_end(table, strings_start)?;

        if kind == number {
            let data = &table[offset..offset + length];
            if data.len() < std::mem::size_of::<T>() {
                return None;
            }

            // Safety: the bounds check above and `T: SMBIOSType` guarantee a valid read.
            let info: T = unsafe { std::ptr::read_unaligned(data.as_ptr() as *const _) };
            let strings = parse_strings(&table[strings_start..strings_end]);
            return Some((info, strings));
        }

        offset = strings_end + 2;
    }
    None
}

pub(crate) fn string_value(strings: &[&str], index: u8) -> Option<String> {
    if index == 0 {
        return None;
    }
    strings.get(index as usize - 1).copied().map(str::to_string)
}

fn find_strings_end(table: &[u8], start: usize) -> Option<usize> {
    let mut i = start;
    while i + 1 < table.len() {
        if table[i] == 0 && table[i + 1] == 0 {
            return Some(i);
        }
        i += 1;
    }
    None
}

fn parse_strings(data: &[u8]) -> Vec<&str> {
    // SMBIOS 3 requires UTF-8, but some virtual machines return non-compliant data.
    data.split(|&byte| byte == 0)
        .filter_map(|value| std::str::from_utf8(value).ok())
        .take_while(|value| !value.is_empty())
        .collect()
}