Skip to main content

micromegas_tracing/
cpu_brand.rs

1//! Host CPU model identification.
2
3/// Human-readable identification of the host CPU model.
4pub fn get_cpu_brand() -> String {
5    #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
6    return raw_cpuid::CpuId::new()
7        .get_processor_brand_string()
8        .map_or_else(|| "unknown".to_owned(), |b| b.as_str().to_owned());
9    #[cfg(all(
10        target_arch = "aarch64",
11        any(target_os = "linux", target_os = "android")
12    ))]
13    return read_arm_brand().unwrap_or_else(|| std::env::consts::ARCH.to_owned());
14    #[cfg(all(target_arch = "aarch64", target_os = "macos"))]
15    return macos_brand_string().unwrap_or_else(|| std::env::consts::ARCH.to_owned());
16    #[cfg(not(any(
17        target_arch = "x86",
18        target_arch = "x86_64",
19        all(
20            target_arch = "aarch64",
21            any(target_os = "linux", target_os = "android", target_os = "macos")
22        )
23    )))]
24    return std::env::consts::ARCH.to_owned();
25}
26
27#[cfg(all(
28    target_arch = "aarch64",
29    any(target_os = "linux", target_os = "android")
30))]
31fn read_arm_brand() -> Option<String> {
32    // /proc/cpuinfo is the fallback for kernels or sandboxes that hide the regs directory.
33    let (implementer, part) =
34        std::fs::read_to_string("/sys/devices/system/cpu/cpu0/regs/identification/midr_el1")
35            .ok()
36            .and_then(|t| parse_midr(&t))
37            .or_else(|| {
38                std::fs::read_to_string("/proc/cpuinfo")
39                    .ok()
40                    .and_then(|t| parse_cpuinfo_ids(&t))
41            })?;
42    Some(format_arm_brand(implementer, part))
43}
44
45#[cfg(all(target_arch = "aarch64", target_os = "macos"))]
46fn macos_brand_string() -> Option<String> {
47    use std::ffi::{CString, c_char, c_int, c_void};
48
49    unsafe extern "C" {
50        fn sysctlbyname(
51            name: *const c_char,
52            oldp: *mut c_void,
53            oldlenp: *mut usize,
54            newp: *mut c_void,
55            newlen: usize,
56        ) -> c_int;
57    }
58
59    let name = CString::new("machdep.cpu.brand_string").ok()?;
60    let mut len: usize = 0;
61    // SAFETY: a null buffer asks sysctl only for the required size.
62    let rc = unsafe {
63        sysctlbyname(
64            name.as_ptr(),
65            std::ptr::null_mut(),
66            &mut len,
67            std::ptr::null_mut(),
68            0,
69        )
70    };
71    if rc != 0 || len == 0 {
72        return None;
73    }
74    let mut buf = vec![0u8; len];
75    // SAFETY: buf has exactly `len` writable bytes.
76    let rc = unsafe {
77        sysctlbyname(
78            name.as_ptr(),
79            buf.as_mut_ptr().cast::<c_void>(),
80            &mut len,
81            std::ptr::null_mut(),
82            0,
83        )
84    };
85    if rc != 0 {
86        return None;
87    }
88    buf.truncate(len);
89    while buf.last() == Some(&0) {
90        buf.pop();
91    }
92    let brand = String::from_utf8_lossy(&buf).trim().to_owned();
93    (!brand.is_empty()).then_some(brand)
94}
95
96#[cfg_attr(
97    not(all(
98        target_arch = "aarch64",
99        any(target_os = "linux", target_os = "android")
100    )),
101    allow(dead_code)
102)]
103fn parse_midr(text: &str) -> Option<(u32, u32)> {
104    let t = text.trim();
105    let t = t
106        .strip_prefix("0x")
107        .or_else(|| t.strip_prefix("0X"))
108        .unwrap_or(t);
109    let midr = u64::from_str_radix(t, 16).ok()?;
110    Some((((midr >> 24) & 0xff) as u32, ((midr >> 4) & 0xfff) as u32))
111}
112
113#[cfg_attr(
114    not(all(
115        target_arch = "aarch64",
116        any(target_os = "linux", target_os = "android")
117    )),
118    allow(dead_code)
119)]
120fn parse_cpuinfo_ids(text: &str) -> Option<(u32, u32)> {
121    let mut implementer = None;
122    let mut part = None;
123    for line in text.lines() {
124        let Some((key, value)) = line.split_once(':') else {
125            continue;
126        };
127        let parse_hex = |v: &str| {
128            let v = v.trim();
129            u32::from_str_radix(v.strip_prefix("0x").unwrap_or(v), 16).ok()
130        };
131        match key.trim() {
132            "CPU implementer" if implementer.is_none() => implementer = parse_hex(value),
133            "CPU part" if part.is_none() => part = parse_hex(value),
134            _ => {}
135        }
136        if implementer.is_some() && part.is_some() {
137            break;
138        }
139    }
140    Some((implementer?, part?))
141}
142
143#[cfg_attr(
144    not(all(
145        target_arch = "aarch64",
146        any(target_os = "linux", target_os = "android")
147    )),
148    allow(dead_code)
149)]
150fn format_arm_brand(implementer: u32, part: u32) -> String {
151    match arm_part_name(implementer, part) {
152        Some(name) => format!("{name} (0x{implementer:02x}:0x{part:03x})"),
153        None => format!("0x{implementer:02x}:0x{part:03x}"),
154    }
155}
156
157#[cfg_attr(
158    not(all(
159        target_arch = "aarch64",
160        any(target_os = "linux", target_os = "android")
161    )),
162    allow(dead_code)
163)]
164fn arm_part_name(implementer: u32, part: u32) -> Option<&'static str> {
165    match (implementer, part) {
166        (0x41, 0xd03) => Some("Cortex-A53"),
167        (0x41, 0xd05) => Some("Cortex-A55"),
168        (0x41, 0xd07) => Some("Cortex-A57"),
169        (0x41, 0xd08) => Some("Cortex-A72"),
170        (0x41, 0xd09) => Some("Cortex-A73"),
171        (0x41, 0xd0a) => Some("Cortex-A75"),
172        (0x41, 0xd0b) => Some("Cortex-A76"),
173        (0x41, 0xd0c) => Some("Neoverse-N1"),
174        (0x41, 0xd0d) => Some("Cortex-A77"),
175        (0x41, 0xd40) => Some("Neoverse-V1"),
176        (0x41, 0xd41) => Some("Cortex-A78"),
177        (0x41, 0xd44) => Some("Cortex-X1"),
178        (0x41, 0xd46) => Some("Cortex-A510"),
179        (0x41, 0xd47) => Some("Cortex-A710"),
180        (0x41, 0xd48) => Some("Cortex-X2"),
181        (0x41, 0xd49) => Some("Neoverse-N2"),
182        (0x41, 0xd4f) => Some("Neoverse-V2"),
183        (0x41, 0xd84) => Some("Neoverse-V3"),
184        (0x41, 0xd8e) => Some("Neoverse-N3"),
185        (0xc0, 0xac3) => Some("Ampere-1"),
186        (0xc0, 0xac4) => Some("Ampere-1a"),
187        _ => None,
188    }
189}
190
191#[cfg(test)]
192mod tests {
193    use super::*;
194
195    #[test]
196    fn midr_parsing() {
197        assert_eq!(parse_midr("0x00000000413fd0c1"), Some((0x41, 0xd0c)));
198        assert_eq!(parse_midr("0x00000000413fd0c1\n"), Some((0x41, 0xd0c)));
199        assert_eq!(parse_midr("00000000413fd0c1"), Some((0x41, 0xd0c)));
200        assert_eq!(parse_midr(""), None);
201        assert_eq!(parse_midr("garbage"), None);
202    }
203
204    #[test]
205    fn cpuinfo_parsing() {
206        let arm = "processor\t: 0\nBogoMIPS\t: 243.75\nFeatures\t: fp asimd\n\
207                   CPU implementer\t: 0x41\nCPU architecture: 8\nCPU variant\t: 0x3\n\
208                   CPU part\t: 0xd0c\nCPU revision\t: 1\n\n\
209                   processor\t: 1\nCPU implementer\t: 0x61\nCPU part\t: 0x022\n";
210        assert_eq!(parse_cpuinfo_ids(arm), Some((0x41, 0xd0c)));
211        assert_eq!(
212            parse_cpuinfo_ids("processor : 0\nCPU implementer : 0x41\n"),
213            None
214        );
215        let x86 = "processor\t: 0\nvendor_id\t: GenuineIntel\nmodel name\t: Xeon\n";
216        assert_eq!(parse_cpuinfo_ids(x86), None);
217    }
218
219    #[test]
220    fn brand_formatting() {
221        assert_eq!(format_arm_brand(0x41, 0xd0c), "Neoverse-N1 (0x41:0xd0c)");
222        assert_eq!(format_arm_brand(0x41, 0xd40), "Neoverse-V1 (0x41:0xd40)");
223        assert_eq!(format_arm_brand(0x41, 0xd4f), "Neoverse-V2 (0x41:0xd4f)");
224        assert_eq!(format_arm_brand(0x41, 0xfff), "0x41:0xfff");
225        assert_eq!(format_arm_brand(0x61, 0x022), "0x61:0x022");
226    }
227
228    #[test]
229    fn host_brand_is_not_empty() {
230        assert!(!get_cpu_brand().is_empty());
231    }
232}