Debian Codegraph @

third_party/rust/minidump-writer/src/linux/dumper_cpu_info/arm.rs

raw
1 use crate::{errors::CpuInfoError, minidump_format::*};
2 use scroll::Pwrite;
3 use std::{
4 collections::HashSet,
5 fs::File,
6 io::{BufRead, BufReader, Read},
7 path,
8 };
9
10 type Result<T> = std::result::Result<T, CpuInfoError>;
11
12 pub fn parse_cpus_from_sysfile(file: &mut File) -> Result<HashSet<u32>> {
13 let mut res = HashSet::new();
14 let mut content = String::new();
15 file.read_to_string(&mut content)?;
16 // Expected format: comma-separated list of items, where each
17 // item can be a decimal integer, or two decimal integers separated
18 // by a dash.
19 // E.g.:
20 // 0
21 // 0,1,2,3
22 // 0-3
23 // 1,10-23
24 for items in content.split(',') {
25 let items = items.trim();
26 if items.is_empty() {
27 continue;
28 }
29 let cores: std::result::Result<Vec<_>, _> =
30 items.split('-').map(|x| x.parse::<u32>()).collect();
31 let cores = cores?;
32 match cores.as_slice() {
33 [x] => {
34 res.insert(*x);
35 }
36 [x, y] => {
37 for core in *x..=*y {
38 res.insert(core);
39 }
40 }
41 _ => {
42 return Err(CpuInfoError::UnparsableCores(format!("{:?}", cores)));
43 }
44 }
45 }
46 Ok(res)
47 }
48
49 struct CpuInfoEntry {
50 field: &'static str,
51 format: char,
52 bit_lshift: u8,
53 bit_length: u8,
54 }
55
56 impl CpuInfoEntry {
57 fn new(field: &'static str, format: char, bit_lshift: u8, bit_length: u8) -> Self {
58 CpuInfoEntry {
59 field,
60 format,
61 bit_lshift,
62 bit_length,
63 }
64 }
65 }
66
67 /// Retrieves the hardware capabilities from the 'Features' field.
68 #[cfg(target_arch = "arm")]
69 fn parse_features(val: &str) -> u32 {
70 struct CpuFeaturesEntry {
71 tag: &'static str,
72 hwcaps: u32,
73 }
74
75 impl CpuFeaturesEntry {
76 fn new(tag: &'static str, hwcaps: u32) -> Self {
77 CpuFeaturesEntry { tag, hwcaps }
78 }
79 }
80
81 // The ELF hwcaps are listed in the "Features" entry as textual tags.
82 // This table is used to rebuild them.
83 let cpu_features_entries = [
84 CpuFeaturesEntry::new("swp", MDCPUInformationARMElfHwCaps::HWCAP_SWP.bits()),
85 CpuFeaturesEntry::new("half", MDCPUInformationARMElfHwCaps::HWCAP_HALF.bits()),
86 CpuFeaturesEntry::new("thumb", MDCPUInformationARMElfHwCaps::HWCAP_THUMB.bits()),
87 CpuFeaturesEntry::new("bit26", MDCPUInformationARMElfHwCaps::HWCAP_26BIT.bits()),
88 CpuFeaturesEntry::new(
89 "fastmult",
90 MDCPUInformationARMElfHwCaps::HWCAP_FAST_MULT.bits(),
91 ),
92 CpuFeaturesEntry::new("fpa", MDCPUInformationARMElfHwCaps::HWCAP_FPA.bits()),
93 CpuFeaturesEntry::new("vfp", MDCPUInformationARMElfHwCaps::HWCAP_VFP.bits()),
94 CpuFeaturesEntry::new("edsp", MDCPUInformationARMElfHwCaps::HWCAP_EDSP.bits()),
95 CpuFeaturesEntry::new("java", MDCPUInformationARMElfHwCaps::HWCAP_JAVA.bits()),
96 CpuFeaturesEntry::new("iwmmxt", MDCPUInformationARMElfHwCaps::HWCAP_IWMMXT.bits()),
97 CpuFeaturesEntry::new("crunch", MDCPUInformationARMElfHwCaps::HWCAP_CRUNCH.bits()),
98 CpuFeaturesEntry::new(
99 "thumbee",
100 MDCPUInformationARMElfHwCaps::HWCAP_THUMBEE.bits(),
101 ),
102 CpuFeaturesEntry::new("neon", MDCPUInformationARMElfHwCaps::HWCAP_NEON.bits()),
103 CpuFeaturesEntry::new("vfpv3", MDCPUInformationARMElfHwCaps::HWCAP_VFPv3.bits()),
104 CpuFeaturesEntry::new(
105 "vfpv3d16",
106 MDCPUInformationARMElfHwCaps::HWCAP_VFPv3D16.bits(),
107 ),
108 CpuFeaturesEntry::new("tls", MDCPUInformationARMElfHwCaps::HWCAP_TLS.bits()),
109 CpuFeaturesEntry::new("vfpv4", MDCPUInformationARMElfHwCaps::HWCAP_VFPv4.bits()),
110 CpuFeaturesEntry::new("idiva", MDCPUInformationARMElfHwCaps::HWCAP_IDIVA.bits()),
111 CpuFeaturesEntry::new("idivt", MDCPUInformationARMElfHwCaps::HWCAP_IDIVT.bits()),
112 CpuFeaturesEntry::new("idiv", MDCPUInformationARMElfHwCaps::HWCAP_IDIV.bits()),
113 ];
114
115 let mut ehwc = 0;
116 // Parse each space-separated tag.
117 for tag in val.split_whitespace() {
118 for entry in &cpu_features_entries {
119 if entry.tag == tag {
120 ehwc |= entry.hwcaps;
121 break;
122 }
123 }
124 }
125
126 ehwc
127 }
128
129 /// Stub for aarch64, always 0
130 #[cfg(target_arch = "aarch64")]
131 fn parse_features(_val: &str) -> u32 {
132 0
133 }
134
135 pub fn write_cpu_information(sys_info: &mut MDRawSystemInfo) -> Result<()> {
136 // The CPUID value is broken up in several entries in /proc/cpuinfo.
137 // This table is used to rebuild it from the entries.
138 let cpu_id_entries = [
139 CpuInfoEntry::new("CPU implementer", 'x', 24, 8),
140 CpuInfoEntry::new("CPU variant", 'x', 20, 4),
141 CpuInfoEntry::new("CPU part", 'x', 4, 12),
142 CpuInfoEntry::new("CPU revision", 'd', 0, 4),
143 ];
144
145 // processor_architecture should always be set, do this first
146 if cfg!(target_arch = "aarch64") {
147 sys_info.processor_architecture =
148 MDCPUArchitecture::PROCESSOR_ARCHITECTURE_ARM64_OLD as u16;
149 } else {
150 sys_info.processor_architecture = MDCPUArchitecture::PROCESSOR_ARCHITECTURE_ARM as u16;
151 }
152
153 // /proc/cpuinfo is not readable under various sandboxed environments
154 // (e.g. Android services with the android:isolatedProcess attribute)
155 // prepare for this by setting default values now, which will be
156 // returned when this happens.
157 //
158 // Note: Bogus values are used to distinguish between failures (to
159 // read /sys and /proc files) and really badly configured kernels.
160 sys_info.number_of_processors = 0;
161 sys_info.processor_level = 1; // There is no ARMv1
162 sys_info.processor_revision = 42;
163
164 // Counting the number of CPUs involves parsing two sysfs files,
165 // because the content of /proc/cpuinfo will only mirror the number
166 // of 'online' cores, and thus will vary with time.
167 // See http://www.kernel.org/doc/Documentation/cputopology.txt
168 if let Ok(mut present_file) = File::open("/sys/devices/system/cpu/present") {
169 // Ignore unparsable content
170 let cpus_present = parse_cpus_from_sysfile(&mut present_file).unwrap_or_default();
171
172 if let Ok(mut possible_file) = File::open("/sys/devices/system/cpu/possible") {
173 // Ignore unparsable content
174 let cpus_possible = parse_cpus_from_sysfile(&mut possible_file).unwrap_or_default();
175 let intersection = cpus_present.intersection(&cpus_possible).count();
176 let cpu_count = std::cmp::min(255, intersection) as u8;
177 sys_info.number_of_processors = cpu_count;
178 }
179 }
180
181 // Parse /proc/cpuinfo to reconstruct the CPUID value, as well
182 // as the ELF hwcaps field. For the latter, it would be easier to
183 // read /proc/self/auxv but unfortunately, this file is not always
184 // readable from regular Android applications on later versions
185 // (>= 4.1) of the Android platform.
186
187 let cpuinfo_file = match File::open(path::PathBuf::from("/proc/cpuinfo")) {
188 Ok(x) => x,
189 Err(_) => {
190 // Do not return Error here to allow the minidump generation
191 // to happen properly.
192 return Ok(());
193 }
194 };
195
196 let mut cpuid = 0;
197 let mut elf_hwcaps = 0;
198
199 for line in BufReader::new(cpuinfo_file).lines() {
200 let line = line?;
201 // Expected format: <field-name> <space>+ ':' <space> <value>
202 // Note that:
203 // - empty lines happen.
204 // - <field-name> can contain spaces.
205 // - some fields have an empty <value>
206 if line.trim().is_empty() {
207 continue;
208 }
209
210 let (field, value) = if let Some(ind) = line.find(':') {
211 (&line[..ind], Some(&line[ind + 1..]))
212 } else {
213 (line.as_str(), None)
214 };
215
216 if let Some(val) = value {
217 for entry in &cpu_id_entries {
218 if field != entry.field {
219 continue;
220 }
221
222 let rr = if val.starts_with("0x") || entry.format == 'x' {
223 usize::from_str_radix(val.trim_start_matches("0x"), 16)
224 } else {
225 val.parse()
226 };
227
228 if let Ok(mut result) = rr {
229 result &= (1 << entry.bit_length) - 1;
230 result <<= entry.bit_lshift;
231 cpuid |= result as u32;
232 }
233 }
234 }
235
236 if cfg!(target_arch = "arm") {
237 // Get the architecture version from the "Processor" field.
238 // Note that it is also available in the "CPU architecture" field,
239 // however, some existing kernels are misconfigured and will report
240 // invalid values here (e.g. 6, while the CPU is ARMv7-A based).
241 // The "Processor" field doesn't have this issue.
242 if field == "Processor" {
243 // Expected format: <text> (v<level><endian>)
244 // Where <text> is some text like "ARMv7 Processor rev 2"
245 // and <level> is a decimal corresponding to the ARM
246 // architecture number. <endian> is either 'l' or 'b'
247 // and corresponds to the endianess, it is ignored here.
248 if let Some(val) = value.and_then(|v| v.split_whitespace().last()) {
249 // val is now something like "(v7l)"
250 sys_info.processor_level = val[2..val.len() - 2].parse::<u16>().unwrap_or(5);
251 }
252 }
253 } else {
254 // aarch64
255 // The aarch64 architecture does not provide the architecture level
256 // in the Processor field, so we instead check the "CPU architecture"
257 // field.
258 if field == "CPU architecture" {
259 sys_info.processor_level = match value.and_then(|v| v.parse::<u16>().ok()) {
260 Some(v) => v,
261 None => {
262 continue;
263 }
264 };
265 }
266 }
267
268 // Rebuild the ELF hwcaps from the 'Features' field.
269 if field == "Features" {
270 if let Some(val) = value {
271 elf_hwcaps = parse_features(val);
272 }
273 }
274 }
275
276 // The sys_info.cpu field is just a byte array, but in arm's case it is
277 // actually
278 // minidump_common::format::ARMCpuInfo {
279 // pub cpuid: u32,
280 // pub elf_hwcaps: u32,
281 // }
282 sys_info
283 .cpu
284 .data
285 .pwrite_with(cpuid, 0, scroll::Endian::Little)
286 .expect("impossible");
287 sys_info
288 .cpu
289 .data
290 .pwrite_with(
291 elf_hwcaps,
292 std::mem::size_of::<u32>(),
293 scroll::Endian::Little,
294 )
295 .expect("impossible");
296
297 Ok(())
298 }
299
300 #[cfg(test)]
301 mod tests {
302 use super::*;
303 // In tests we can have access to std
304 extern crate std;
305 use std::io::Write;
306
307 fn new_file(content: &str) -> File {
308 let mut file = tempfile::Builder::new()
309 .prefix("cpu_sets")
310 .tempfile()
311 .unwrap();
312 write!(file, "{}", content).unwrap();
313 std::fs::File::open(file).unwrap()
314 }
315
316 #[test]
317 fn test_empty_count() {
318 let mut file = new_file("");
319 let set = parse_cpus_from_sysfile(&mut file).expect("Failed to parse empty file");
320 assert_eq!(set.len(), 0);
321 }
322
323 #[test]
324 fn test_one_cpu() {
325 let mut file = new_file("10");
326 let set = parse_cpus_from_sysfile(&mut file).expect("Failed to file");
327 assert_eq!(set, [10,].iter().copied().collect());
328 }
329
330 #[test]
331 fn test_one_cpu_newline() {
332 let mut file = new_file("10\n");
333 let set = parse_cpus_from_sysfile(&mut file).expect("Failed to file");
334 assert_eq!(set, [10,].iter().copied().collect());
335 }
336
337 #[test]
338 fn test_two_cpus() {
339 let mut file = new_file("1,10\n");
340 let set = parse_cpus_from_sysfile(&mut file).expect("Failed to file");
341 assert_eq!(set, [1, 10].iter().copied().collect());
342 }
343
344 #[test]
345 fn test_two_cpus_with_range() {
346 let mut file = new_file("1-2\n");
347 let set = parse_cpus_from_sysfile(&mut file).expect("Failed to file");
348 assert_eq!(set, [1, 2].iter().copied().collect());
349 }
350
351 #[test]
352 fn test_ten_cpus_with_range() {
353 let mut file = new_file("9-18\n");
354 let set = parse_cpus_from_sysfile(&mut file).expect("Failed to file");
355 assert_eq!(set, (9..=18).collect());
356 }
357
358 #[test]
359 fn test_multiple_items() {
360 let mut file = new_file("0, 2-4, 128\n");
361 let set = parse_cpus_from_sysfile(&mut file).expect("Failed to file");
362 assert_eq!(set, [0, 2, 3, 4, 128].iter().copied().collect());
363 }
364
365 #[test]
366 fn test_intersects_with() {
367 let mut file1 = new_file("9-19\n");
368 let mut set1 = parse_cpus_from_sysfile(&mut file1).expect("Failed to file");
369 assert_eq!(set1, (9..=19).collect());
370
371 let mut file2 = new_file("16-24\n");
372 let set2 = parse_cpus_from_sysfile(&mut file2).expect("Failed to file");
373 assert_eq!(set2, (16..=24).collect());
374
375 set1 = set1.intersection(&set2).copied().collect();
376 assert_eq!(set1, (16..=19).collect());
377 }
378
379 #[test]
380 fn test_intersects_with_discontinuous() {
381 let mut file1 = new_file("0, 2-4, 7, 10\n");
382 let mut set1 = parse_cpus_from_sysfile(&mut file1).expect("Failed to file");
383 assert_eq!(set1, [0, 2, 3, 4, 7, 10].iter().copied().collect());
384
385 let mut file2 = new_file("0-2, 5, 8-10\n");
386 let set2 = parse_cpus_from_sysfile(&mut file2).expect("Failed to file");
387 assert_eq!(set2, [0, 1, 2, 5, 8, 9, 10].iter().copied().collect());
388
389 set1 = set1.intersection(&set2).copied().collect();
390 assert_eq!(set1, [0, 2, 10].iter().copied().collect());
391 }
392
393 #[test]
394 fn test_bad_input() {
395 let mut file = new_file("abc\n");
396 let _set = parse_cpus_from_sysfile(&mut file).expect_err("Did not fail to parse");
397 }
398
399 #[test]
400 fn test_bad_input_range() {
401 let mut file = new_file("1-abc\n");
402 let _set = parse_cpus_from_sysfile(&mut file).expect_err("Did not fail to parse");
403 }
404 }