diff --git a/src/uu/lscpu/src/sysfs.rs b/src/uu/lscpu/src/sysfs.rs index 0c8a3e82..267ae173 100644 --- a/src/uu/lscpu/src/sysfs.rs +++ b/src/uu/lscpu/src/sysfs.rs @@ -19,6 +19,12 @@ pub fn system_path(root: &Path, path: &str) -> PathBuf { root.join(path.trim_start_matches('/')) } +fn read_trimmed(path: &Path) -> Option { + fs::read_to_string(path) + .ok() + .map(|contents| contents.trim().to_string()) +} + pub struct CpuVulnerability { pub name: String, pub mitigation: String, @@ -34,7 +40,9 @@ pub struct Cpu { // i64 rather than usize: the kernel reports -1 when the architecture // does not expose physical package information pub pkg_id: i64, - pub core_id: usize, + // `None` when sysfs does not report a core id for this CPU; such a CPU is + // treated as its own core instead of falling back to its index. + pub core_id: Option, pub caches: Vec, } @@ -60,22 +68,20 @@ impl CpuTopology { pub fn new(root: &Path) -> UResult { let mut out: Vec = vec![]; - let online_cpus = parse_cpu_list(&read_online_cpus(root)?); + let online_cpus = parse_cpu_list(&read_online_cpus(root)?)?; for cpu_index in online_cpus { let cpu_dir = system_path(root, &format!("/sys/devices/system/cpu/cpu{cpu_index}/")); - let pkg_id = fs::read_to_string(cpu_dir.join("topology/physical_package_id")) - .unwrap() - .trim() - .parse::() - .unwrap(); + // Keep reporting partial topology when sysfs is incomplete: -1 + // means an unknown package, and a CPU without core_id is treated + // as its own core instead of failing the whole command. + let pkg_id = read_trimmed(&cpu_dir.join("topology/physical_package_id")) + .and_then(|value| value.parse::().ok()) + .unwrap_or(-1); - let core_id = fs::read_to_string(cpu_dir.join("topology/core_id")) - .unwrap() - .trim() - .parse::() - .unwrap(); + let core_id = read_trimmed(&cpu_dir.join("topology/core_id")) + .and_then(|value| value.parse::().ok()); let caches = read_cpu_caches(root, cpu_index); @@ -98,8 +104,18 @@ impl CpuTopology { } pub fn core_count(&self) -> usize { - let core_ids: HashSet<_> = self.cpus.iter().map(|cpu| cpu.core_id).collect(); - core_ids.len() + // core_id is only unique within a package, so known cores are keyed by + // (package, core) to avoid merging same-numbered cores from different + // sockets. A CPU without a core_id is counted as its own core; using + // its index as the id could collide with a real core_id of another + // CPU. + let known_cores: HashSet<(i64, usize)> = self + .cpus + .iter() + .filter_map(|cpu| cpu.core_id.map(|core_id| (cpu.pkg_id, core_id))) + .collect(); + let unknown_cores = self.cpus.iter().filter(|cpu| cpu.core_id.is_none()).count(); + known_cores.len() + unknown_cores } } @@ -108,8 +124,8 @@ impl CacheSize { Self(size) } - fn parse(s: &str) -> Self { - Self(parse_size::parse_size_u64(s).expect("Could not parse cache size")) + fn parse(s: &str) -> Option { + parse_size::parse_size_u64(s).ok().map(Self) } pub fn size_bytes(&self) -> u64 { @@ -145,7 +161,9 @@ pub fn read_online_cpus(root: &Path) -> UResult { fn read_cpu_caches(root: &Path, cpu_index: usize) -> Vec { let cpu_dir = system_path(root, &format!("/sys/devices/system/cpu/cpu{cpu_index}/")); - let cache_dir = fs::read_dir(cpu_dir.join("cache")).unwrap(); + let Ok(cache_dir) = fs::read_dir(cpu_dir.join("cache")) else { + return Vec::new(); + }; let cache_paths = cache_dir .flatten() .filter(|x| x.path().is_dir()) @@ -154,26 +172,34 @@ fn read_cpu_caches(root: &Path, cpu_index: usize) -> Vec { let mut caches: Vec = vec![]; for cache_path in cache_paths { - let type_string = fs::read_to_string(cache_path.join("type")).unwrap(); - - let c_type = match type_string.trim() { - "Unified" => CacheType::Unified, - "Data" => CacheType::Data, - "Instruction" => CacheType::Instruction, - _ => panic!("Unrecognized cache type: {type_string}"), + // Ignore entries with unknown or missing metadata rather than failing + // the command; new kernel cache types should not break lscpu. + let Some(c_type) = + read_trimmed(&cache_path.join("type")).and_then(|value| match value.as_str() { + "Unified" => Some(CacheType::Unified), + "Data" => Some(CacheType::Data), + "Instruction" => Some(CacheType::Instruction), + _ => None, + }) + else { + continue; }; - let c_level = fs::read_to_string(cache_path.join("level")) - .map(|s| s.trim().parse::().unwrap()) - .unwrap(); + let Some(c_level) = + read_trimmed(&cache_path.join("level")).and_then(|value| value.parse::().ok()) + else { + continue; + }; - let size_string = fs::read_to_string(cache_path.join("size")).unwrap(); - let c_size = CacheSize::parse(size_string.trim()); + let Some(c_size) = + read_trimmed(&cache_path.join("size")).and_then(|value| CacheSize::parse(&value)) + else { + continue; + }; - let shared_cpu_map = fs::read_to_string(cache_path.join("shared_cpu_map")) - .unwrap() - .trim() - .to_string(); + let Some(shared_cpu_map) = read_trimmed(&cache_path.join("shared_cpu_map")) else { + continue; + }; caches.push(CpuCache { level: c_level, @@ -206,10 +232,12 @@ pub fn read_cpu_vulnerabilities(root: &Path) -> Vec { for file in files { if let Ok(content) = fs::read_to_string(&file) { - let name = file.file_name().unwrap().to_str().unwrap(); + let Some(name) = file.file_name().and_then(|name| name.to_str()) else { + continue; + }; out.push(CpuVulnerability { - name: (name[..1].to_uppercase() + &name[1..]).replace("_", " "), + name: vulnerability_name(name), mitigation: content.trim().to_string(), }); } @@ -230,48 +258,83 @@ pub fn read_cpu_byte_order(root: &Path) -> Option<&'static str> { None } +fn vulnerability_name(file_name: &str) -> String { + let mut chars = file_name.chars(); + let Some(first) = chars.next() else { + return String::new(); + }; + + let mut name = first.to_uppercase().collect::(); + name.push_str(chars.as_str()); + name.replace('_', " ") +} + +fn parse_cpu_index(value: &str) -> UResult { + value + .trim() + .parse::() + .map_err(|_| USimpleError::new(1, format!("Invalid CPU index value: {value}"))) +} + // Takes in a human-readable list of CPUs, and returns a list of indices parsed from that list // These can come in the form of a plain range like `X-Y`, or a comma-separated ranges and indices ie. `1,3-4,7-8,10` // Kernel docs with examples: https://www.kernel.org/doc/html/latest/admin-guide/cputopology.html -fn parse_cpu_list(list: &str) -> Vec { +fn parse_cpu_list(list: &str) -> UResult> { let mut out: Vec = vec![]; + let list = list.trim(); if list.is_empty() { - return out; + return Ok(out); } - for part in list.trim().split(",") { - if part.contains("-") { - let bounds: Vec<_> = part.split("-").flat_map(|x| x.parse::()).collect(); - assert_eq!(bounds.len(), 2); - for idx in bounds[0]..bounds[1] + 1 { - out.push(idx) + for part in list.split(',') { + let part = part.trim(); + + if part.is_empty() { + return Err(USimpleError::new(1, "Invalid empty CPU list entry")); + } + + if let Some((start, end)) = part.split_once('-') { + let start = parse_cpu_index(start)?; + let end = parse_cpu_index(end)?; + + if start > end { + return Err(USimpleError::new(1, format!("Invalid CPU range: {part}"))); } + + out.extend(start..=end); } else { - let idx = part.parse::().expect("Invalid CPU index value"); - out.push(idx); + out.push(parse_cpu_index(part)?); } } - out + Ok(out) } #[test] fn test_parse_cache_size() { - assert_eq!(CacheSize::parse("512").size_bytes(), 512); - assert_eq!(CacheSize::parse("1K").size_bytes(), 1024); - assert_eq!(CacheSize::parse("1M").size_bytes(), 1024 * 1024); - assert_eq!(CacheSize::parse("1G").size_bytes(), 1024 * 1024 * 1024); + assert_eq!(CacheSize::parse("512").unwrap().size_bytes(), 512); + assert_eq!(CacheSize::parse("1K").unwrap().size_bytes(), 1024); + assert_eq!(CacheSize::parse("1M").unwrap().size_bytes(), 1024 * 1024); assert_eq!( - CacheSize::parse("1T").size_bytes(), + CacheSize::parse("1G").unwrap().size_bytes(), + 1024 * 1024 * 1024 + ); + assert_eq!( + CacheSize::parse("1T").unwrap().size_bytes(), 1024 * 1024 * 1024 * 1024 ); - assert_eq!(CacheSize::parse("123K").size_bytes(), 123 * 1024); - assert_eq!(CacheSize::parse("32M").size_bytes(), 32 * 1024 * 1024); + assert_eq!(CacheSize::parse("123K").unwrap().size_bytes(), 123 * 1024); + assert_eq!( + CacheSize::parse("32M").unwrap().size_bytes(), + 32 * 1024 * 1024 + ); assert_eq!( - CacheSize::parse("345G").size_bytes(), + CacheSize::parse("345G").unwrap().size_bytes(), 345 * 1024 * 1024 * 1024 ); + + assert!(CacheSize::parse("not-a-size").is_none()); } #[test] @@ -302,13 +365,13 @@ fn test_socket_count_with_unknown_package_id() { Cpu { _index: 0, pkg_id: -1, - core_id: 0, + core_id: Some(0), caches: vec![], }, Cpu { _index: 1, pkg_id: -1, - core_id: 1, + core_id: Some(1), caches: vec![], }, ], @@ -317,17 +380,35 @@ fn test_socket_count_with_unknown_package_id() { assert_eq!(topology.core_count(), 2); } +#[test] +fn test_vulnerability_name() { + assert_eq!(vulnerability_name("spectre_v1"), "Spectre v1"); + assert_eq!(vulnerability_name("meltdown"), "Meltdown"); + assert_eq!(vulnerability_name(""), ""); +} + #[test] fn test_parse_cpu_list() { - assert_eq!(parse_cpu_list(""), Vec::::new()); - assert_eq!(parse_cpu_list("1-3"), Vec::::from([1, 2, 3])); - assert_eq!(parse_cpu_list("1,2,3"), Vec::::from([1, 2, 3])); + assert_eq!(parse_cpu_list("").unwrap(), Vec::::new()); assert_eq!( - parse_cpu_list("1,3-6,8"), + parse_cpu_list("1-3").unwrap(), + Vec::::from([1, 2, 3]) + ); + assert_eq!( + parse_cpu_list("1,2,3").unwrap(), + Vec::::from([1, 2, 3]) + ); + assert_eq!( + parse_cpu_list("1,3-6,8").unwrap(), Vec::::from([1, 3, 4, 5, 6, 8]) ); assert_eq!( - parse_cpu_list("1-2,3-5,7"), + parse_cpu_list("1-2,3-5,7").unwrap(), Vec::::from([1, 2, 3, 4, 5, 7]) ); + + assert!(parse_cpu_list("1-").is_err()); + assert!(parse_cpu_list("a").is_err()); + assert!(parse_cpu_list("3-1").is_err()); + assert!(parse_cpu_list("1,,2").is_err()); } diff --git a/tests/by-util/test_lscpu.rs b/tests/by-util/test_lscpu.rs index e2ef6a89..7dc4e517 100644 --- a/tests/by-util/test_lscpu.rs +++ b/tests/by-util/test_lscpu.rs @@ -21,6 +21,17 @@ fn write_file(dir: &Path, name: &str, contents: &str) { std::fs::write(dir.join(name), contents).unwrap(); } +fn assert_field(stdout: &str, field: &str, value: &str) { + let prefix = format!("{field}:"); + let line = stdout + .lines() + .find(|line| line.trim_start().starts_with(&prefix)) + .unwrap_or_else(|| panic!("missing {field}")); + + let actual = line.trim_start()[prefix.len()..].trim(); + assert_eq!(actual, value, "unexpected value for {field}"); +} + /// Builds a minimal fake `/sys/devices/system/cpu` and `/proc/cpuinfo`. /// /// Values are deliberately different from typical host values so tests fail if @@ -83,6 +94,20 @@ impl TestSysCpu { fn path(&self) -> &Path { self.sysroot.path() } + + fn write_relative(&self, relative: &str, contents: &str) { + let path = self.path().join(relative); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, contents).unwrap(); + } + + fn remove_file(&self, relative: &str) { + std::fs::remove_file(self.path().join(relative)).unwrap(); + } + + fn remove_dir(&self, relative: &str) { + std::fs::remove_dir_all(self.path().join(relative)).unwrap(); + } } #[test] @@ -138,17 +163,6 @@ fn test_sysroot_output() { .succeeds(); let stdout = res.no_stderr().stdout_str(); - fn assert_field(stdout: &str, field: &str, value: &str) { - let prefix = format!("{field}:"); - let line = stdout - .lines() - .find(|line| line.trim_start().starts_with(&prefix)) - .unwrap_or_else(|| panic!("missing {field}")); - - let actual = line.trim_start()[prefix.len()..].trim(); - assert_eq!(actual, value, "unexpected value for {field}"); - } - assert_field(stdout, "Address sizes", "39 bits physical, 48 bits virtual"); assert_field(stdout, "Byte Order", "Big Endian"); assert_field(stdout, "On-line CPU(s) list", "0-1"); @@ -223,3 +237,143 @@ fn test_sysroot_invalid() { .code_is(1) .stderr_contains("Could not read"); } + +#[test] +#[cfg(target_os = "linux")] +fn test_sysroot_missing_cache_dir() { + let test_root = TestSysCpu::new(); + test_root.remove_dir("sys/devices/system/cpu/cpu0/cache"); + test_root.remove_dir("sys/devices/system/cpu/cpu1/cache"); + + let res = new_ucmd!().arg("-s").arg(test_root.path()).succeeds(); + let stdout = res.no_stderr().stdout_str(); + + assert_field(stdout, "CPU(s)", "2"); + assert!(!stdout.contains("Caches (sum of all)")); +} + +#[test] +#[cfg(target_os = "linux")] +fn test_sysroot_missing_cache_size() { + let test_root = TestSysCpu::new(); + for cpu in 0..2 { + test_root.remove_file(&format!( + "sys/devices/system/cpu/cpu{cpu}/cache/index0/size" + )); + } + + let res = new_ucmd!().arg("-s").arg(test_root.path()).succeeds(); + let stdout = res.no_stderr().stdout_str(); + + assert!(!stdout.contains("L1d:")); + assert_field(stdout, "L1i", "128 KiB (2 instances)"); + assert_field(stdout, "L2", "512 KiB (2 instances)"); +} + +#[test] +#[cfg(target_os = "linux")] +fn test_sysroot_missing_cache_shared_cpu_map() { + let test_root = TestSysCpu::new(); + for cpu in 0..2 { + test_root.remove_file(&format!( + "sys/devices/system/cpu/cpu{cpu}/cache/index1/shared_cpu_map" + )); + } + + let res = new_ucmd!().arg("-s").arg(test_root.path()).succeeds(); + let stdout = res.no_stderr().stdout_str(); + + assert!(!stdout.contains("L1i:")); + assert_field(stdout, "L1d", "64 KiB (2 instances)"); + assert_field(stdout, "L2", "512 KiB (2 instances)"); +} + +#[test] +#[cfg(target_os = "linux")] +fn test_sysroot_missing_cache_level() { + let test_root = TestSysCpu::new(); + for cpu in 0..2 { + test_root.remove_file(&format!( + "sys/devices/system/cpu/cpu{cpu}/cache/index2/level" + )); + } + + let res = new_ucmd!().arg("-s").arg(test_root.path()).succeeds(); + let stdout = res.no_stderr().stdout_str(); + + assert!(!stdout.contains("L2:")); + assert_field(stdout, "L1d", "64 KiB (2 instances)"); +} + +#[test] +#[cfg(target_os = "linux")] +fn test_sysroot_unknown_cache_type() { + let test_root = TestSysCpu::new(); + for cpu in 0..2 { + test_root.write_relative( + &format!("sys/devices/system/cpu/cpu{cpu}/cache/index2/type"), + "Mystery\n", + ); + } + + let res = new_ucmd!().arg("-s").arg(test_root.path()).succeeds(); + let stdout = res.no_stderr().stdout_str(); + + assert!(!stdout.contains("L2:")); + assert_field(stdout, "L3", "8 MiB (1 instances)"); +} + +#[test] +#[cfg(target_os = "linux")] +fn test_sysroot_missing_topology() { + let test_root = TestSysCpu::new(); + for cpu in 0..2 { + test_root.remove_file(&format!( + "sys/devices/system/cpu/cpu{cpu}/topology/physical_package_id" + )); + test_root.remove_file(&format!("sys/devices/system/cpu/cpu{cpu}/topology/core_id")); + } + + let res = new_ucmd!().arg("-s").arg(test_root.path()).succeeds(); + let stdout = res.no_stderr().stdout_str(); + + assert_field(stdout, "CPU(s)", "2"); + assert_field(stdout, "Thread(s) per core", "1"); + assert_field(stdout, "Core(s) per socket", "2"); + assert_field(stdout, "Socket(s)", "1"); +} + +#[test] +#[cfg(target_os = "linux")] +fn test_sysroot_single_cpu_missing_core_id() { + let test_root = TestSysCpu::new(); + + // cpu0 reports a core_id that equals cpu1's CPU index, while cpu1 has no + // core_id. Both CPUs live on the same package, so they must still be + // counted as two distinct cores; falling back to cpu1's index as its + // core_id would collide with cpu0 and undercount the cores. + test_root.write_relative("sys/devices/system/cpu/cpu0/topology/core_id", "1\n"); + test_root.remove_file("sys/devices/system/cpu/cpu1/topology/core_id"); + + let res = new_ucmd!().arg("-s").arg(test_root.path()).succeeds(); + let stdout = res.no_stderr().stdout_str(); + + assert_field(stdout, "CPU(s)", "2"); + assert_field(stdout, "Thread(s) per core", "1"); + assert_field(stdout, "Core(s) per socket", "2"); + assert_field(stdout, "Socket(s)", "1"); +} + +#[test] +#[cfg(target_os = "linux")] +fn test_sysroot_invalid_cpu_list() { + let test_root = TestSysCpu::new(); + test_root.write_relative("sys/devices/system/cpu/online", "0-abc\n"); + + new_ucmd!() + .arg("-s") + .arg(test_root.path()) + .fails() + .code_is(1) + .stderr_contains("Invalid CPU index value: abc"); +}