use std::mem::{size_of, zeroed};
use windows::Win32::Devices::DeviceAndDriverInstallation::{
DIGCF_PRESENT, GUID_DEVCLASS_DISPLAY, HDEVINFO, SETUP_DI_REGISTRY_PROPERTY, SP_DEVINFO_DATA,
SPDRP_ADDRESS, SPDRP_BUSNUMBER, SetupDiDestroyDeviceInfoList, SetupDiEnumDeviceInfo,
SetupDiGetClassDevsW, SetupDiGetDeviceRegistryPropertyW,
};
use crate::PCI;
struct ClassDevs(HDEVINFO);
impl ClassDevs {
unsafe fn new() -> Option<Self> {
unsafe {
if let Ok(ret) =
SetupDiGetClassDevsW(Some(&GUID_DEVCLASS_DISPLAY), None, None, DIGCF_PRESENT)
&& !ret.is_invalid()
{
Some(Self(ret))
} else {
None
}
}
}
}
impl Drop for ClassDevs {
fn drop(&mut self) {
unsafe {
let _ = SetupDiDestroyDeviceInfoList(self.0);
}
}
}
pub(super) fn utf16_to_string(buf: &[u16]) -> String {
unsafe {
let buf = std::slice::from_raw_parts(buf.as_ptr(), buf.len());
let len = buf.iter().position(|x| *x == 0).unwrap_or(buf.len());
String::from_utf16_lossy(&buf[..len])
}
}
unsafe fn get_u32_property(
h_dev_info: HDEVINFO,
dev_info_data: &SP_DEVINFO_DATA,
key: SETUP_DI_REGISTRY_PROPERTY,
) -> Option<u32> {
let mut required = std::mem::size_of::<u32>() as u32;
let mut value = [0u8; std::mem::size_of::<u32>()];
unsafe {
if SetupDiGetDeviceRegistryPropertyW(
h_dev_info,
dev_info_data,
key,
None,
Some(&mut value),
Some(&mut required),
)
.is_ok()
{
Some(u32::from_ne_bytes(value))
} else {
None
}
}
}
pub(super) unsafe fn get_all_pcis() -> Option<Vec<PCI>> {
unsafe {
let dev_info_set = ClassDevs::new()?;
let mut dev_info_data: SP_DEVINFO_DATA = zeroed();
dev_info_data.cbSize = size_of::<SP_DEVINFO_DATA>() as _;
let mut index = 0;
let mut pcis = Vec::new();
while SetupDiEnumDeviceInfo(dev_info_set.0, index, &mut dev_info_data).is_ok() {
index += 1;
let bus =
get_u32_property(dev_info_set.0, &dev_info_data, SPDRP_BUSNUMBER).unwrap_or(0);
let address =
get_u32_property(dev_info_set.0, &dev_info_data, SPDRP_ADDRESS).unwrap_or(0);
let device = (address >> 16) & 0xFFFF;
let function = address & 0xFFFF;
pcis.push(PCI {
domain: 0,
bus,
device,
function,
});
}
Some(pcis)
}
}