Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 22 additions & 7 deletions src/uu/lscpu/src/lscpu.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,15 @@
use clap::{crate_version, Arg, ArgAction, Command};
use regex::RegexBuilder;
use serde::Serialize;
use std::{cmp, collections::HashMap, fs};
use std::{cmp, collections::HashMap, fs, path::PathBuf};
use sysfs::CacheSize;
use uucore::{error::UResult, format_usage, help_about, help_usage};

mod options {
pub const BYTES: &str = "bytes";
pub const HEX: &str = "hex";
pub const JSON: &str = "json";
pub const SYSROOT: &str = "sysroot";
}

mod sysfs;
Expand Down Expand Up @@ -80,30 +81,35 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
json: matches.get_flag(options::JSON),
};

let sysroot = matches
.get_one::<PathBuf>(options::SYSROOT)
.expect("sysroot has a default value");

let mut cpu_infos = CpuInfos::new();

let mut arch_info = CpuInfo::new("Architecture", &get_architecture());

// TODO: We just silently ignore failures to read `/proc/cpuinfo` currently and treat it as empty
// Perhaps a better solution should be put in place, but what?
let contents = fs::read_to_string("/proc/cpuinfo").unwrap_or_default();
let contents =
fs::read_to_string(sysfs::system_path(sysroot, "/proc/cpuinfo")).unwrap_or_default();

if let Some(addr_sizes) = find_cpuinfo_value(&contents, "address sizes") {
arch_info.add_child(CpuInfo::new("Address sizes", &addr_sizes))
}

if let Some(byte_order) = sysfs::read_cpu_byte_order() {
if let Some(byte_order) = sysfs::read_cpu_byte_order(sysroot) {
arch_info.add_child(CpuInfo::new("Byte Order", byte_order));
}

cpu_infos.push(arch_info);

let cpu_topology = sysfs::CpuTopology::new();
let cpu_topology = sysfs::CpuTopology::new(sysroot)?;
let mut cores_info = CpuInfo::new("CPU(s)", &format!("{}", cpu_topology.cpus.len()));

cores_info.add_child(CpuInfo::new(
"On-line CPU(s) list",
&sysfs::read_online_cpus(),
&sysfs::read_online_cpus(sysroot)?,
));

cpu_infos.push(cores_info);
Expand Down Expand Up @@ -139,7 +145,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
));
model_name_info.add_child(CpuInfo::new("Socket(s)", &socket_count.to_string()));

if let Some(freq_boost_enabled) = sysfs::read_freq_boost_state() {
if let Some(freq_boost_enabled) = sysfs::read_freq_boost_state(sysroot) {
let s = if freq_boost_enabled {
"enabled"
} else {
Expand All @@ -158,7 +164,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
cpu_infos.push(cache_info);
}

let vulns = sysfs::read_cpu_vulnerabilities();
let vulns = sysfs::read_cpu_vulnerabilities(sysroot);
if !vulns.is_empty() {
let mut vuln_info = CpuInfo::new("Vulnerabilities", "");
for vuln in vulns {
Expand Down Expand Up @@ -350,4 +356,13 @@ pub fn uu_app() -> Command {
Setting this flag instead prints the decimal amount of bytes with no suffix.",
),
)
.arg(
Arg::new(options::SYSROOT)
.short('s')
.long("sysroot")
.value_name("directory")
.value_parser(clap::value_parser!(PathBuf))
.default_value("/")
.help("Use the specified directory as system root"),
)
}
54 changes: 34 additions & 20 deletions src/uu/lscpu/src/sysfs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,21 @@
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.

use std::{collections::HashSet, fs, path::PathBuf};
use uucore::parser::parse_size;
use std::{
collections::HashSet,
fs,
path::{Path, PathBuf},
};
use uucore::{
error::{UResult, USimpleError},
parser::parse_size,
};

/// `Path::join` discards the root when the joined path is absolute, so strip
/// the leading separator before joining.
pub fn system_path(root: &Path, path: &str) -> PathBuf {
root.join(path.trim_start_matches('/'))
}

pub struct CpuVulnerability {
pub name: String,
Expand Down Expand Up @@ -44,13 +57,13 @@ pub enum CacheType {
}

impl CpuTopology {
pub fn new() -> Self {
pub fn new(root: &Path) -> UResult<Self> {
let mut out: Vec<Cpu> = vec![];

let online_cpus = parse_cpu_list(&read_online_cpus());
let online_cpus = parse_cpu_list(&read_online_cpus(root)?);

for cpu_index in online_cpus {
let cpu_dir = PathBuf::from(format!("/sys/devices/system/cpu/cpu{cpu_index}/"));
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()
Expand All @@ -64,7 +77,7 @@ impl CpuTopology {
.parse::<usize>()
.unwrap();

let caches = read_cpu_caches(cpu_index);
let caches = read_cpu_caches(root, cpu_index);

out.push(Cpu {
_index: cpu_index,
Expand All @@ -73,7 +86,7 @@ impl CpuTopology {
caches,
})
}
Self { cpus: out }
Ok(Self { cpus: out })
}

pub fn socket_count(&self) -> usize {
Expand Down Expand Up @@ -122,15 +135,16 @@ impl CacheSize {
}

// TODO: respect `--hex` option and output the bitmask instead of human-readable range
pub fn read_online_cpus() -> String {
fs::read_to_string("/sys/devices/system/cpu/online")
.expect("Could not read sysfs")
.trim()
.to_string()
pub fn read_online_cpus(root: &Path) -> UResult<String> {
let path = system_path(root, "/sys/devices/system/cpu/online");

fs::read_to_string(&path)
.map(|contents| contents.trim().to_string())
.map_err(|err| USimpleError::new(1, format!("Could not read {}: {err}", path.display())))
}

fn read_cpu_caches(cpu_index: usize) -> Vec<CpuCache> {
let cpu_dir = PathBuf::from(format!("/sys/devices/system/cpu/cpu{cpu_index}/"));
fn read_cpu_caches(root: &Path, cpu_index: usize) -> Vec<CpuCache> {
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 cache_paths = cache_dir
.flatten()
Expand Down Expand Up @@ -172,16 +186,16 @@ fn read_cpu_caches(cpu_index: usize) -> Vec<CpuCache> {
caches
}

pub fn read_freq_boost_state() -> Option<bool> {
fs::read_to_string("/sys/devices/system/cpu/cpufreq/boost")
pub fn read_freq_boost_state(root: &Path) -> Option<bool> {
fs::read_to_string(system_path(root, "/sys/devices/system/cpu/cpufreq/boost"))
.map(|content| content.trim() == "1")
.ok()
}

pub fn read_cpu_vulnerabilities() -> Vec<CpuVulnerability> {
pub fn read_cpu_vulnerabilities(root: &Path) -> Vec<CpuVulnerability> {
let mut out: Vec<CpuVulnerability> = vec![];

if let Ok(dir) = fs::read_dir("/sys/devices/system/cpu/vulnerabilities") {
if let Ok(dir) = fs::read_dir(system_path(root, "/sys/devices/system/cpu/vulnerabilities")) {
let mut files: Vec<_> = dir
.flatten()
.map(|x| x.path())
Expand All @@ -205,8 +219,8 @@ pub fn read_cpu_vulnerabilities() -> Vec<CpuVulnerability> {
out
}

pub fn read_cpu_byte_order() -> Option<&'static str> {
if let Ok(byte_order) = fs::read_to_string("/sys/kernel/cpu_byteorder") {
pub fn read_cpu_byte_order(root: &Path) -> Option<&'static str> {
if let Ok(byte_order) = fs::read_to_string(system_path(root, "/sys/kernel/cpu_byteorder")) {
match byte_order.trim() {
"big" => return Some("Big Endian"),
"little" => return Some("Little Endian"),
Expand Down
176 changes: 176 additions & 0 deletions tests/by-util/test_lscpu.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,88 @@
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.

use serde_json::Value;
use std::path::Path;
use uutests::new_ucmd;

const CPUINFO: &str = "\
processor\t: 0
vendor_id\t: TestVendor
cpu family\t: 6
model\t\t: 42
model name\t: Test CPU
address sizes\t: 39 bits physical, 48 bits virtual
";

fn write_file(dir: &Path, name: &str, contents: &str) {
std::fs::create_dir_all(dir).unwrap();
std::fs::write(dir.join(name), contents).unwrap();
}

/// Builds a minimal fake `/sys/devices/system/cpu` and `/proc/cpuinfo`.
///
/// Values are deliberately different from typical host values so tests fail if
/// any read accidentally bypasses `--sysroot` and uses the host filesystem.
struct TestSysCpu {
sysroot: tempfile::TempDir,
}

impl TestSysCpu {
fn new() -> Self {
let sysroot = tempfile::tempdir().unwrap();
let root = sysroot.path();
let cpu = root.join("sys/devices/system/cpu");

write_file(&cpu, "online", "0-1\n");
write_file(&cpu, "present", "0-1\n");
write_file(&cpu, "offline", "\n");
write_file(&root.join("sys/kernel"), "cpu_byteorder", "big\n");
write_file(&cpu.join("cpufreq"), "boost", "0\n");
write_file(
&cpu.join("vulnerabilities"),
"fake_vuln",
"Mitigation: fake\n",
);

for cpu_index in 0..2 {
let cpu_dir = cpu.join(format!("cpu{cpu_index}"));
let topology = cpu_dir.join("topology");

write_file(&topology, "physical_package_id", "0\n");
write_file(&topology, "core_id", &format!("{cpu_index}\n"));

let caches = [
("index0", "Data", "1", "32K", format!("{cpu_index:x}")),
(
"index1",
"Instruction",
"1",
"64K",
format!("{cpu_index:x}"),
),
("index2", "Unified", "2", "256K", format!("{cpu_index:x}")),
("index3", "Unified", "3", "8M", "3".to_string()),
];

for (name, cache_type, level, size, shared_cpu_map) in caches {
let cache_dir = cpu_dir.join("cache").join(name);
write_file(&cache_dir, "type", cache_type);
write_file(&cache_dir, "level", level);
write_file(&cache_dir, "size", size);
write_file(&cache_dir, "shared_cpu_map", &shared_cpu_map);
}
}

write_file(&root.join("proc"), "cpuinfo", CPUINFO);

Self { sysroot }
}

fn path(&self) -> &Path {
self.sysroot.path()
}
}

#[test]
fn test_invalid_arg() {
new_ucmd!().arg("--definitely-invalid").fails().code_is(1);
Expand Down Expand Up @@ -47,3 +127,99 @@ fn test_output() {
assert!(stdout.contains("\n Model name:"));
assert!(stdout.contains("\n CPU Family:"));
}

#[test]
#[cfg(target_os = "linux")]
fn test_sysroot_output() {
let test_root = TestSysCpu::new();
let res = new_ucmd!()
.arg("--sysroot")
.arg(test_root.path())
.succeeds();
let stdout = res.no_stderr().stdout_str();

fn assert_field(stdout: &str, field: &str, value: &str) {
Comment thread
tuxnode marked this conversation as resolved.
Resolved
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");
assert_field(stdout, "Vendor ID", "TestVendor");
assert_field(stdout, "Model name", "Test CPU");
assert_field(stdout, "CPU Family", "6");
assert_field(stdout, "Model", "42");
assert_field(stdout, "Thread(s) per core", "1");
assert_field(stdout, "Core(s) per socket", "2");
assert_field(stdout, "Socket(s)", "1");
assert_field(stdout, "Frequency boost", "disabled");

// L1/L2 are private to each CPU, L3 is shared by both CPUs.
assert_field(stdout, "L1d", "64 KiB (2 instances)");
assert_field(stdout, "L1i", "128 KiB (2 instances)");
assert_field(stdout, "L2", "512 KiB (2 instances)");
assert_field(stdout, "L3", "8 MiB (1 instances)");

assert!(stdout.contains("Vulnerabilities:"));
assert_field(stdout, "Fake vuln", "Mitigation: fake");
}

#[test]
#[cfg(target_os = "linux")]
fn test_sysroot_json() {
let test_root = TestSysCpu::new();
let res = new_ucmd!()
.arg("-s")
.arg(test_root.path())
.arg("--json")
.succeeds();

fn find_entry<'a>(entries: &'a [Value], field: &str) -> Option<&'a Value> {
for entry in entries {
if entry["field"] == field {
return Some(entry);
}

if let Some(children) = entry["children"].as_array() {
if let Some(found) = find_entry(children, field) {
return Some(found);
}
}
}

None
}

let json: Value = serde_json::from_str(res.no_stderr().stdout_str()).unwrap();
let entries = json["lscpu"].as_array().unwrap();

for (field, value) in [
("CPU(s)", "2"),
("Vendor ID", "TestVendor"),
("L1d", "64 KiB (2 instances)"),
] {
let entry = find_entry(entries, field).unwrap_or_else(|| panic!("missing field {field}"));
assert_eq!(entry["data"], value, "unexpected value for {field}");
}
}

#[test]
#[cfg(target_os = "linux")]
fn test_sysroot_invalid() {
let sysroot = tempfile::tempdir().unwrap();
let missing = sysroot.path().join("missing");

new_ucmd!()
.arg("--sysroot")
.arg(missing)
.fails()
.code_is(1)
.stderr_contains("Could not read");
}
Loading