use std::fs;
use std::path::Path;
use crate::hardware::PciDevice;
use super::helpers::{read_hex_u8, read_hex_u16, read_hex_u32, read_link_name};
pub(super) fn load() -> Vec<PciDevice> {
load_from(Path::new("/sys/bus/pci/devices"))
}
fn load_from(root: &Path) -> Vec<PciDevice> {
let Ok(entries) = fs::read_dir(root) else {
return Vec::new();
};
let mut devices: Vec<PciDevice> = entries
.flatten()
.map(|entry| entry.path())
.filter_map(|path| {
let address = path.file_name()?.to_string_lossy().into_owned();
let vendor_id = read_hex_u16(&path.join("vendor"))?;
let device_id = read_hex_u16(&path.join("device"))?;
Some(PciDevice {
address,
vendor_id,
device_id,
class: read_hex_u32(&path.join("class")).unwrap_or(0),
subsystem_vendor_id: read_hex_u16(&path.join("subsystem_vendor")).unwrap_or(0),
subsystem_device_id: read_hex_u16(&path.join("subsystem_device")).unwrap_or(0),
revision: read_hex_u8(&path.join("revision")).unwrap_or(0),
driver: read_link_name(&path.join("driver")),
})
})
.collect();
devices.sort_by(|a, b| a.address.cmp(&b.address));
devices
}
#[cfg(test)]
mod tests {
use std::fs;
#[test]
fn parses_pci_entries_and_skips_malformed() {
let root = tempfile::tempdir().unwrap();
let device = root.path().join("0000:00:01.0");
fs::create_dir(&device).unwrap();
for (name, value) in [
("vendor", "0x1022"),
("device", "0x14b5"),
("class", "0x060000"),
("subsystem_vendor", "0x1043"),
("subsystem_device", "0x1234"),
("revision", "0x01"),
] {
fs::write(device.join(name), value).unwrap();
}
fs::create_dir(root.path().join("malformed")).unwrap();
let devices = super::load_from(root.path());
assert_eq!(devices.len(), 1);
let device = &devices[0];
assert_eq!(device.address, "0000:00:01.0");
assert_eq!(device.vendor_id, 0x1022);
assert_eq!(device.device_id, 0x14b5);
assert_eq!(device.class, 0x060000);
assert_eq!(device.revision, 1);
}
}