Debian Codegraph @

third_party/rust/minidump-writer/src/linux/maps_reader.rs

raw
1 use {
2 crate::{auxv::AuxvType, errors::MapsReaderError},
3 byteorder::{NativeEndian, ReadBytesExt},
4 goblin::elf,
5 memmap2::{Mmap, MmapOptions},
6 procfs_core::process::{MMPermissions, MMapPath, MemoryMaps},
7 std::{
8 ffi::{OsStr, OsString},
9 fs::File,
10 mem::size_of,
11 os::unix::ffi::{OsStrExt, OsStringExt},
12 path::PathBuf,
13 },
14 };
15
16 pub const LINUX_GATE_LIBRARY_NAME: &str = "linux-gate.so";
17 pub const DELETED_SUFFIX: &[u8] = b" (deleted)";
18
19 type Result<T> = std::result::Result<T, MapsReaderError>;
20
21 #[derive(Debug, PartialEq, Eq, Clone, serde::Serialize)]
22 pub struct SystemMappingInfo {
23 pub start_address: usize,
24 pub end_address: usize,
25 }
26
27 // One of these is produced for each mapping in the process (i.e. line in
28 // /proc/$x/maps).
29 #[derive(Debug, PartialEq, Eq, Clone, serde::Serialize)]
30 pub struct MappingInfo {
31 // On Android, relocation packing can mean that the reported start
32 // address of the mapping must be adjusted by a bias in order to
33 // compensate for the compression of the relocation section. The
34 // following two members hold (after LateInit) the adjusted mapping
35 // range. See crbug.com/606972 for more information.
36 pub start_address: usize,
37 pub size: usize,
38 // When Android relocation packing causes |start_addr| and |size| to
39 // be modified with a load bias, we need to remember the unbiased
40 // address range. The following structure holds the original mapping
41 // address range as reported by the operating system.
42 pub system_mapping_info: SystemMappingInfo,
43 pub offset: usize, // offset into the backed file.
44 pub permissions: MMPermissions, // read, write and execute permissions.
45 pub name: Option<OsString>,
46 // pub elf_obj: Option<elf::Elf>,
47 }
48
49 #[derive(Debug)]
50 pub struct MappingEntry {
51 pub mapping: MappingInfo,
52 pub identifier: Vec<u8>,
53 }
54
55 // A list of <MappingInfo, GUID>
56 pub type MappingList = Vec<MappingEntry>;
57
58 #[derive(Debug)]
59 pub enum MappingInfoParsingResult {
60 SkipLine,
61 Success(MappingInfo),
62 }
63
64 fn is_mapping_a_path(pathname: Option<&OsStr>) -> bool {
65 match pathname {
66 Some(x) => x.as_bytes().contains(&b'/'),
67 None => false,
68 }
69 }
70
71 /// Sanitize mapped paths.
72 ///
73 /// This removes a ` (deleted)` suffix, if present.
74 fn sanitize_path(pathname: OsString) -> OsString {
75 if let Some(bytes) = pathname.as_bytes().strip_suffix(DELETED_SUFFIX) {
76 OsString::from_vec(bytes.to_owned())
77 } else {
78 pathname
79 }
80 }
81
82 impl MappingInfo {
83 /// Return whether the `name` field is a path (contains a `/`).
84 pub fn name_is_path(&self) -> bool {
85 is_mapping_a_path(self.name.as_deref())
86 }
87
88 pub fn is_empty_page(&self) -> bool {
89 (self.offset == 0) && (self.permissions == MMPermissions::PRIVATE) && self.name.is_none()
90 }
91
92 pub fn end_address(&self) -> usize {
93 self.start_address + self.size
94 }
95
96 pub fn aggregate(
97 memory_maps: MemoryMaps,
98 linux_gate_loc: Option<AuxvType>,
99 ) -> Result<Vec<Self>> {
100 let mut infos = Vec::<Self>::new();
101
102 for mm in memory_maps {
103 let start_address: usize = mm.address.0.try_into()?;
104 let end_address: usize = mm.address.1.try_into()?;
105 let mut offset: usize = mm.offset.try_into()?;
106
107 let mut pathname: Option<OsString> = match mm.pathname {
108 MMapPath::Path(p) => Some(sanitize_path(p.into())),
109 MMapPath::Heap => Some("[heap]".into()),
110 MMapPath::Stack => Some("[stack]".into()),
111 MMapPath::TStack(i) => Some(format!("[stack:{i}]").into()),
112 MMapPath::Vdso => Some("[vdso]".into()),
113 MMapPath::Vvar => Some("[vvar]".into()),
114 MMapPath::Vsyscall => Some("[vsyscall]".into()),
115 MMapPath::Rollup => Some("[rollup]".into()),
116 MMapPath::Vsys(i) => Some(format!("/SYSV{i:x}").into()),
117 MMapPath::Other(n) => Some(format!("[{n}]").into()),
118 MMapPath::Anonymous => None,
119 };
120
121 let is_path = is_mapping_a_path(pathname.as_deref());
122
123 if let Some(linux_gate_loc) = linux_gate_loc.map(|u| usize::try_from(u).unwrap()) {
124 if !is_path && start_address == linux_gate_loc {
125 pathname = Some(LINUX_GATE_LIBRARY_NAME.into());
126 offset = 0;
127 }
128 }
129
130 if let Some(prev_module) = infos.last_mut() {
131 if (start_address == prev_module.end_address())
132 && pathname.is_some()
133 && (pathname == prev_module.name)
134 {
135 // Merge adjacent mappings into one module, assuming they're a single
136 // library mapped by the dynamic linker.
137 prev_module.system_mapping_info.end_address = end_address;
138 prev_module.size = end_address - prev_module.start_address;
139 prev_module.permissions |= mm.perms;
140 continue;
141 } else if (start_address == prev_module.end_address())
142 && prev_module.is_executable()
143 && prev_module.name_is_path()
144 && ((offset == 0) || (offset == prev_module.end_address()))
145 && (mm.perms == MMPermissions::PRIVATE)
146 {
147 // Also merge mappings that result from address ranges that the
148 // linker reserved but which a loaded library did not use. These
149 // appear as an anonymous private mapping with no access flags set
150 // and which directly follow an executable mapping.
151 prev_module.size = end_address - prev_module.start_address;
152 continue;
153 }
154 }
155
156 // Sometimes the unused ranges reserved but the linker appear within the library.
157 // If we detect an empty page that is adjacent to two mappings of the same library
158 // we fold the three mappings together.
159 if let Some(previous_modules) = infos.rchunks_exact_mut(2).next() {
160 let empty_page = if let Some(prev_module) = previous_modules.last() {
161 let prev_prev_module = previous_modules.first().unwrap();
162 prev_prev_module.name_is_path()
163 && (prev_prev_module.end_address() == prev_module.start_address)
164 && prev_module.is_empty_page()
165 && (prev_module.end_address() == start_address)
166 } else {
167 false
168 };
169
170 if empty_page {
171 let prev_prev_module = previous_modules.first_mut().unwrap();
172
173 if pathname == prev_prev_module.name {
174 prev_prev_module.system_mapping_info.end_address = end_address;
175 prev_prev_module.size = end_address - prev_prev_module.start_address;
176 prev_prev_module.permissions |= mm.perms;
177 infos.pop();
178 continue;
179 }
180 }
181 }
182
183 infos.push(MappingInfo {
184 start_address,
185 size: end_address - start_address,
186 system_mapping_info: SystemMappingInfo {
187 start_address,
188 end_address,
189 },
190 offset,
191 permissions: mm.perms,
192 name: pathname,
193 });
194 }
195 Ok(infos)
196 }
197
198 pub fn get_mmap(name: &Option<OsString>, offset: usize) -> Result<Mmap> {
199 if !MappingInfo::is_mapped_file_safe_to_open(name) {
200 return Err(MapsReaderError::NotSafeToOpenMapping(
201 name.clone().unwrap_or_default(),
202 ));
203 }
204
205 // Not doing this as root_prefix is always "" at the moment
206 // if (!dumper.GetMappingAbsolutePath(mapping, filename))
207 let filename = name.clone().unwrap_or_default();
208 let mapped_file = unsafe {
209 MmapOptions::new()
210 .offset(offset.try_into()?) // try_into() to work for both 32 and 64 bit
211 .map(&File::open(filename)?)?
212 };
213
214 if mapped_file.is_empty() || mapped_file.len() < elf::header::SELFMAG {
215 return Err(MapsReaderError::MmapSanityCheckFailed);
216 }
217 Ok(mapped_file)
218 }
219
220 pub fn stack_has_pointer_to_mapping(&self, stack_copy: &[u8], sp_offset: usize) -> bool {
221 // Loop over all stack words that would have been on the stack in
222 // the target process (i.e. are word aligned, and at addresses >=
223 // the stack pointer). Regardless of the alignment of |stack_copy|,
224 // the memory starting at |stack_copy| + |offset| represents an
225 // aligned word in the target process.
226 let low_addr = self.system_mapping_info.start_address;
227 let high_addr = self.system_mapping_info.end_address;
228 let mut offset = (sp_offset + size_of::<usize>() - 1) & !(size_of::<usize>() - 1);
229 while offset <= stack_copy.len() - size_of::<usize>() {
230 let addr = match std::mem::size_of::<usize>() {
231 4 => stack_copy[offset..]
232 .as_ref()
233 .read_u32::<NativeEndian>()
234 .map(|u| u as usize),
235 8 => stack_copy[offset..]
236 .as_ref()
237 .read_u64::<NativeEndian>()
238 .map(|u| u as usize),
239 x => panic!("Unexpected type width: {}", x),
240 };
241 if let Ok(addr) = addr {
242 if low_addr <= addr && addr <= high_addr {
243 return true;
244 }
245 offset += size_of::<usize>();
246 } else {
247 break;
248 }
249 }
250 false
251 }
252
253 pub fn is_mapped_file_safe_to_open(name: &Option<OsString>) -> bool {
254 // It is unsafe to attempt to open a mapped file that lives under /dev,
255 // because the semantics of the open may be driver-specific so we'd risk
256 // hanging the crash dumper. And a file in /dev/ almost certainly has no
257 // ELF file identifier anyways.
258 if let Some(name) = name {
259 if name.as_bytes().starts_with(b"/dev/") {
260 return false;
261 }
262 }
263 true
264 }
265
266 /// Find the shared object name (SONAME) by examining the ELF information
267 /// for the mapping.
268 fn so_name(&self) -> Result<String> {
269 use super::module_reader::{ReadFromModule, SoName};
270
271 let mapped_file = MappingInfo::get_mmap(&self.name, self.offset)?;
272 Ok(SoName::read_from_module((&*mapped_file).into())
273 .map_err(|e| MapsReaderError::NoSoName(self.name.clone().unwrap_or_default(), e))?
274 .0
275 .to_string())
276 }
277
278 #[inline]
279 fn so_version(&self) -> Option<SoVersion> {
280 SoVersion::parse(self.name.as_deref()?)
281 }
282
283 pub fn get_mapping_effective_path_name_and_version(
284 &self,
285 soname: Option<String>,
286 ) -> Result<(PathBuf, String, Option<SoVersion>)> {
287 let mut file_path = PathBuf::from(self.name.clone().unwrap_or_default());
288
289 // Tools such as minidump_stackwalk use the name of the module to look up
290 // symbols produced by dump_syms. dump_syms will prefer to use a module's
291 // DT_SONAME as the module name, if one exists, and will fall back to the
292 // filesystem name of the module.
293
294 // Just use the filesystem name if no SONAME is present.
295 let Some(file_name) = soname.or_else(|| self.so_name().ok()) else {
296 // file_path := /path/to/libname.so
297 // file_name := libname.so
298 let file_name = file_path
299 .file_name()
300 .map(|s| s.to_string_lossy().into_owned())
301 .unwrap_or_default();
302
303 return Ok((file_path, file_name, self.so_version()));
304 };
305
306 if self.is_executable() && self.offset != 0 {
307 // If an executable is mapped from a non-zero offset, this is likely because
308 // the executable was loaded directly from inside an archive file (e.g., an
309 // apk on Android).
310 // In this case, we append the file_name to the mapped archive path:
311 // file_name := libname.so
312 // file_path := /path/to/ARCHIVE.APK/libname.so
313 file_path.push(&file_name);
314 } else {
315 // Otherwise, replace the basename with the SONAME.
316 file_path.set_file_name(&file_name);
317 }
318
319 Ok((file_path, file_name, self.so_version()))
320 }
321
322 pub fn is_contained_in(&self, user_mapping_list: &MappingList) -> bool {
323 for user in user_mapping_list {
324 // Ignore any mappings that are wholly contained within
325 // mappings in the mapping_info_ list.
326 if self.start_address >= user.mapping.start_address
327 && (self.start_address + self.size)
328 <= (user.mapping.start_address + user.mapping.size)
329 {
330 return true;
331 }
332 }
333 false
334 }
335
336 pub fn is_interesting(&self) -> bool {
337 // only want modules with filenames.
338 self.name.is_some() &&
339 // Only want to include one mapping per shared lib.
340 // Avoid filtering executable mappings.
341 (self.offset == 0 || self.is_executable()) &&
342 // big enough to get a signature for.
343 self.size >= 4096
344 }
345
346 pub fn contains_address(&self, address: usize) -> bool {
347 self.system_mapping_info.start_address <= address
348 && address < self.system_mapping_info.end_address
349 }
350
351 pub fn is_executable(&self) -> bool {
352 self.permissions.contains(MMPermissions::EXECUTE)
353 }
354
355 pub fn is_readable(&self) -> bool {
356 self.permissions.contains(MMPermissions::READ)
357 }
358
359 pub fn is_writable(&self) -> bool {
360 self.permissions.contains(MMPermissions::WRITE)
361 }
362 }
363
364 /// Version metadata retrieved from an .so filename
365 ///
366 /// There is no standard for .so version numbers so this implementation just
367 /// does a best effort to pull as much data as it can based on real .so schemes
368 /// seen
369 ///
370 /// That being said, the [libtool](https://www.gnu.org/software/libtool/manual/html_node/Libtool-versioning.html)
371 /// versioning scheme is fairly common
372 #[cfg_attr(test, derive(Debug))]
373 pub struct SoVersion {
374 /// Might be non-zero if there is at least one non-zero numeric component after .so.
375 ///
376 /// Equivalent to `current` in libtool versions
377 pub major: u32,
378 /// The numeric component after the major version, if any
379 ///
380 /// Equivalent to `revision` in libtool versions
381 pub minor: u32,
382 /// The numeric component after the minor version, if any
383 ///
384 /// Equivalent to `age` in libtool versions
385 pub patch: u32,
386 /// The patch component may contain additional non-numeric metadata similar
387 /// to a semver prelease, this is any numeric data that suffixes that prerelease
388 /// string
389 pub prerelease: u32,
390 }
391
392 impl SoVersion {
393 /// Attempts to retrieve the .so version of the elf path via its filename
394 fn parse(so_path: &OsStr) -> Option<Self> {
395 let filename = std::path::Path::new(so_path).file_name()?;
396
397 // Avoid an allocation unless the string contains non-utf8
398 let filename = filename.to_string_lossy();
399
400 let (_, version) = filename.split_once(".so.")?;
401
402 let mut sov = Self {
403 major: 0,
404 minor: 0,
405 patch: 0,
406 prerelease: 0,
407 };
408
409 let comps = [
410 &mut sov.major,
411 &mut sov.minor,
412 &mut sov.patch,
413 &mut sov.prerelease,
414 ];
415
416 for (i, comp) in version.split('.').enumerate() {
417 if i <= 1 {
418 *comps[i] = comp.parse().unwrap_or_default();
419 } else if i >= 4 {
420 break;
421 } else {
422 // In some cases the release/patch version is alphanumeric (eg. '2rc5'),
423 // so try to parse either a single or two numbers
424 if let Some(pend) = comp.find(|c: char| !c.is_ascii_digit()) {
425 if let Ok(patch) = comp[..pend].parse() {
426 *comps[i] = patch;
427 }
428
429 if i >= comps.len() - 1 {
430 break;
431 }
432 if let Some(pre) = comp.rfind(|c: char| !c.is_ascii_digit()) {
433 if let Ok(pre) = comp[pre + 1..].parse() {
434 *comps[i + 1] = pre;
435 break;
436 }
437 }
438 } else {
439 *comps[i] = comp.parse().unwrap_or_default();
440 }
441 }
442 }
443
444 Some(sov)
445 }
446 }
447
448 #[cfg(test)]
449 impl PartialEq<(u32, u32, u32, u32)> for SoVersion {
450 fn eq(&self, o: &(u32, u32, u32, u32)) -> bool {
451 self.major == o.0 && self.minor == o.1 && self.patch == o.2 && self.prerelease == o.3
452 }
453 }
454
455 #[cfg(test)]
456 #[cfg(target_pointer_width = "64")] // All addresses are 64 bit and I'm currently too lazy to adjust it to work for both
457 mod tests {
458 use super::*;
459 use procfs_core::FromRead;
460
461 fn get_mappings_for(map: &str, linux_gate_loc: u64) -> Vec<MappingInfo> {
462 MappingInfo::aggregate(
463 MemoryMaps::from_read(map.as_bytes()).expect("failed to read mapping info"),
464 Some(linux_gate_loc),
465 )
466 .unwrap_or_default()
467 }
468
469 const LINES: &str = "\
470 5597483fc000-5597483fe000 r--p 00000000 00:31 4750073 /usr/bin/cat
471 5597483fe000-559748402000 r-xp 00002000 00:31 4750073 /usr/bin/cat
472 559748402000-559748404000 r--p 00006000 00:31 4750073 /usr/bin/cat
473 559748404000-559748405000 r--p 00007000 00:31 4750073 /usr/bin/cat
474 559748405000-559748406000 rw-p 00008000 00:31 4750073 /usr/bin/cat
475 559749b0e000-559749b2f000 rw-p 00000000 00:00 0 [heap]
476 7efd968d3000-7efd968f5000 rw-p 00000000 00:00 0
477 7efd968f5000-7efd9694a000 r--p 00000000 00:31 5004638 /usr/lib/locale/en_US.utf8/LC_CTYPE
478 7efd9694a000-7efd96bc2000 r--p 00000000 00:31 5004373 /usr/lib/locale/en_US.utf8/LC_COLLATE
479 7efd96bc2000-7efd96bc4000 rw-p 00000000 00:00 0
480 7efd96bc4000-7efd96bea000 r--p 00000000 00:31 4996104 /lib64/libc-2.32.so
481 7efd96bea000-7efd96d39000 r-xp 00026000 00:31 4996104 /lib64/libc-2.32.so
482 7efd96d39000-7efd96d85000 r--p 00175000 00:31 4996104 /lib64/libc-2.32.so
483 7efd96d85000-7efd96d86000 ---p 001c1000 00:31 4996104 /lib64/libc-2.32.so
484 7efd96d86000-7efd96d89000 r--p 001c1000 00:31 4996104 /lib64/libc-2.32.so
485 7efd96d89000-7efd96d8c000 rw-p 001c4000 00:31 4996104 /lib64/libc-2.32.so
486 7efd96d8c000-7efd96d92000 ---p 00000000 00:00 0
487 7efd96da0000-7efd96da1000 r--p 00000000 00:31 5004379 /usr/lib/locale/en_US.utf8/LC_NUMERIC
488 7efd96da1000-7efd96da2000 r--p 00000000 00:31 5004382 /usr/lib/locale/en_US.utf8/LC_TIME
489 7efd96da2000-7efd96da3000 r--p 00000000 00:31 5004377 /usr/lib/locale/en_US.utf8/LC_MONETARY
490 7efd96da3000-7efd96da4000 r--p 00000000 00:31 5004376 /usr/lib/locale/en_US.utf8/LC_MESSAGES/SYS_LC_MESSAGES
491 7efd96da4000-7efd96da5000 r--p 00000000 00:31 5004380 /usr/lib/locale/en_US.utf8/LC_PAPER
492 7efd96da5000-7efd96da6000 r--p 00000000 00:31 5004378 /usr/lib/locale/en_US.utf8/LC_NAME
493 7efd96da6000-7efd96da7000 r--p 00000000 00:31 5004372 /usr/lib/locale/en_US.utf8/LC_ADDRESS
494 7efd96da7000-7efd96da8000 r--p 00000000 00:31 5004381 /usr/lib/locale/en_US.utf8/LC_TELEPHONE
495 7efd96da8000-7efd96da9000 r--p 00000000 00:31 5004375 /usr/lib/locale/en_US.utf8/LC_MEASUREMENT
496 7efd96da9000-7efd96db0000 r--s 00000000 00:31 5004639 /usr/lib64/gconv/gconv-modules.cache
497 7efd96db0000-7efd96db1000 r--p 00000000 00:31 5004374 /usr/lib/locale/en_US.utf8/LC_IDENTIFICATION
498 7efd96db1000-7efd96db2000 r--p 00000000 00:31 4996100 /lib64/ld-2.32.so
499 7efd96db2000-7efd96dd3000 r-xp 00001000 00:31 4996100 /lib64/ld-2.32.so
500 7efd96dd3000-7efd96ddc000 r--p 00022000 00:31 4996100 /lib64/ld-2.32.so
501 7efd96ddc000-7efd96ddd000 r--p 0002a000 00:31 4996100 /lib64/ld-2.32.so
502 7efd96ddd000-7efd96ddf000 rw-p 0002b000 00:31 4996100 /lib64/ld-2.32.so
503 7ffc6dfda000-7ffc6dffb000 rw-p 00000000 00:00 0 [stack]
504 7ffc6e0f3000-7ffc6e0f7000 r--p 00000000 00:00 0 [vvar]
505 7ffc6e0f7000-7ffc6e0f9000 r-xp 00000000 00:00 0 [vdso]
506 ffffffffff600000-ffffffffff601000 --xp 00000000 00:00 0 [vsyscall]";
507 const LINUX_GATE_LOC: u64 = 0x7ffc6e0f7000;
508
509 fn get_all_mappings() -> Vec<MappingInfo> {
510 get_mappings_for(LINES, LINUX_GATE_LOC)
511 }
512
513 #[test]
514 fn test_merged() {
515 // Only /usr/bin/cat and [heap]
516 let mappings = get_mappings_for(
517 "\
518 5597483fc000-5597483fe000 r--p 00000000 00:31 4750073 /usr/bin/cat
519 5597483fe000-559748402000 r-xp 00002000 00:31 4750073 /usr/bin/cat
520 559748402000-559748404000 r--p 00006000 00:31 4750073 /usr/bin/cat
521 559748404000-559748405000 r--p 00007000 00:31 4750073 /usr/bin/cat
522 559748405000-559748406000 rw-p 00008000 00:31 4750073 /usr/bin/cat
523 559749b0e000-559749b2f000 rw-p 00000000 00:00 0 [heap]
524 7efd968d3000-7efd968f5000 rw-p 00000000 00:00 0 ",
525 0x7ffc6e0f7000,
526 );
527
528 assert_eq!(mappings.len(), 3);
529 let cat_map = MappingInfo {
530 start_address: 0x5597483fc000,
531 size: 40960,
532 system_mapping_info: SystemMappingInfo {
533 start_address: 0x5597483fc000,
534 end_address: 0x559748406000,
535 },
536 offset: 0,
537 permissions: MMPermissions::READ
538 | MMPermissions::WRITE
539 | MMPermissions::EXECUTE
540 | MMPermissions::PRIVATE,
541 name: Some("/usr/bin/cat".into()),
542 };
543
544 assert_eq!(mappings[0], cat_map);
545
546 let heap_map = MappingInfo {
547 start_address: 0x559749b0e000,
548 size: 135168,
549 system_mapping_info: SystemMappingInfo {
550 start_address: 0x559749b0e000,
551 end_address: 0x559749b2f000,
552 },
553 offset: 0,
554 permissions: MMPermissions::READ | MMPermissions::WRITE | MMPermissions::PRIVATE,
555 name: Some("[heap]".into()),
556 };
557
558 assert_eq!(mappings[1], heap_map);
559
560 let empty_map = MappingInfo {
561 start_address: 0x7efd968d3000,
562 size: 139264,
563 system_mapping_info: SystemMappingInfo {
564 start_address: 0x7efd968d3000,
565 end_address: 0x7efd968f5000,
566 },
567 offset: 0,
568 permissions: MMPermissions::READ | MMPermissions::WRITE | MMPermissions::PRIVATE,
569 name: None,
570 };
571
572 assert_eq!(mappings[2], empty_map);
573 }
574
575 #[test]
576 fn test_linux_gate_parsing() {
577 let mappings = get_all_mappings();
578
579 let gate_map = MappingInfo {
580 start_address: 0x7ffc6e0f7000,
581 size: 8192,
582 system_mapping_info: SystemMappingInfo {
583 start_address: 0x7ffc6e0f7000,
584 end_address: 0x7ffc6e0f9000,
585 },
586 offset: 0,
587 permissions: MMPermissions::READ | MMPermissions::EXECUTE | MMPermissions::PRIVATE,
588 name: Some("linux-gate.so".into()),
589 };
590
591 assert_eq!(mappings[21], gate_map);
592 }
593
594 #[test]
595 fn test_reading_all() {
596 let mappings = get_all_mappings();
597
598 let found_items: Vec<Option<OsString>> = vec![
599 Some("/usr/bin/cat".into()),
600 Some("[heap]".into()),
601 None,
602 Some("/usr/lib/locale/en_US.utf8/LC_CTYPE".into()),
603 Some("/usr/lib/locale/en_US.utf8/LC_COLLATE".into()),
604 None,
605 Some("/lib64/libc-2.32.so".into()),
606 // The original shows a None here, but this is an address ranges that the
607 // linker reserved but which a loaded library did not use. These
608 // appear as an anonymous private mapping with no access flags set
609 // and which directly follow an executable mapping.
610 Some("/usr/lib/locale/en_US.utf8/LC_NUMERIC".into()),
611 Some("/usr/lib/locale/en_US.utf8/LC_TIME".into()),
612 Some("/usr/lib/locale/en_US.utf8/LC_MONETARY".into()),
613 Some("/usr/lib/locale/en_US.utf8/LC_MESSAGES/SYS_LC_MESSAGES".into()),
614 Some("/usr/lib/locale/en_US.utf8/LC_PAPER".into()),
615 Some("/usr/lib/locale/en_US.utf8/LC_NAME".into()),
616 Some("/usr/lib/locale/en_US.utf8/LC_ADDRESS".into()),
617 Some("/usr/lib/locale/en_US.utf8/LC_TELEPHONE".into()),
618 Some("/usr/lib/locale/en_US.utf8/LC_MEASUREMENT".into()),
619 Some("/usr/lib64/gconv/gconv-modules.cache".into()),
620 Some("/usr/lib/locale/en_US.utf8/LC_IDENTIFICATION".into()),
621 Some("/lib64/ld-2.32.so".into()),
622 Some("[stack]".into()),
623 Some("[vvar]".into()),
624 // This is rewritten from [vdso] to linux-gate.so
625 Some("linux-gate.so".into()),
626 Some("[vsyscall]".into()),
627 ];
628
629 assert_eq!(
630 mappings.iter().map(|x| x.name.clone()).collect::<Vec<_>>(),
631 found_items
632 );
633 }
634
635 #[test]
636 fn test_merged_reserved_mappings() {
637 let mappings = get_all_mappings();
638
639 let gate_map = MappingInfo {
640 start_address: 0x7efd96bc4000,
641 size: 1892352, // Merged the anonymous area after in this mapping, so its bigger..
642 system_mapping_info: SystemMappingInfo {
643 start_address: 0x7efd96bc4000,
644 end_address: 0x7efd96d8c000, // ..but this is not visible here
645 },
646 offset: 0,
647 permissions: MMPermissions::READ
648 | MMPermissions::WRITE
649 | MMPermissions::EXECUTE
650 | MMPermissions::PRIVATE,
651 name: Some("/lib64/libc-2.32.so".into()),
652 };
653
654 assert_eq!(mappings[6], gate_map);
655 }
656
657 #[test]
658 fn test_merged_reserved_mappings_within_module() {
659 let mappings = get_mappings_for(
660 "\
661 9b4a0000-9b931000 r--p 00000000 08:12 393449 /data/app/org.mozilla.firefox-1/lib/x86/libxul.so
662 9b931000-9bcae000 ---p 00000000 00:00 0
663 9bcae000-a116b000 r-xp 00490000 08:12 393449 /data/app/org.mozilla.firefox-1/lib/x86/libxul.so
664 a116b000-a4562000 r--p 0594d000 08:12 393449 /data/app/org.mozilla.firefox-1/lib/x86/libxul.so
665 a4562000-a4563000 ---p 00000000 00:00 0
666 a4563000-a4840000 r--p 08d44000 08:12 393449 /data/app/org.mozilla.firefox-1/lib/x86/libxul.so
667 a4840000-a4873000 rw-p 09021000 08:12 393449 /data/app/org.mozilla.firefox-1/lib/x86/libxul.so",
668 0xa4876000,
669 );
670
671 let gate_map = MappingInfo {
672 start_address: 0x9b4a0000,
673 size: 155004928, // Merged the anonymous area after in this mapping, so its bigger..
674 system_mapping_info: SystemMappingInfo {
675 start_address: 0x9b4a0000,
676 end_address: 0xa4873000,
677 },
678 offset: 0,
679 permissions: MMPermissions::READ
680 | MMPermissions::WRITE
681 | MMPermissions::EXECUTE
682 | MMPermissions::PRIVATE,
683 name: Some("/data/app/org.mozilla.firefox-1/lib/x86/libxul.so".into()),
684 };
685
686 assert_eq!(mappings[0], gate_map);
687 }
688
689 #[test]
690 fn test_get_mapping_effective_name() {
691 let mappings = get_mappings_for(
692 "\
693 7f0b97b6f000-7f0b97b70000 r--p 00000000 00:3e 27136458 /home/martin/Documents/mozilla/devel/mozilla-central/obj/widget/gtk/mozgtk/gtk3/libmozgtk.so
694 7f0b97b70000-7f0b97b71000 r-xp 00000000 00:3e 27136458 /home/martin/Documents/mozilla/devel/mozilla-central/obj/widget/gtk/mozgtk/gtk3/libmozgtk.so
695 7f0b97b71000-7f0b97b73000 r--p 00000000 00:3e 27136458 /home/martin/Documents/mozilla/devel/mozilla-central/obj/widget/gtk/mozgtk/gtk3/libmozgtk.so
696 7f0b97b73000-7f0b97b74000 rw-p 00001000 00:3e 27136458 /home/martin/Documents/mozilla/devel/mozilla-central/obj/widget/gtk/mozgtk/gtk3/libmozgtk.so",
697 0x7ffe091bf000,
698 );
699 assert_eq!(mappings.len(), 1);
700
701 let (file_path, file_name, _version) = mappings[0]
702 .get_mapping_effective_path_name_and_version(None)
703 .expect("Couldn't get effective name for mapping");
704 assert_eq!(file_name, "libmozgtk.so");
705 assert_eq!(file_path, PathBuf::from("/home/martin/Documents/mozilla/devel/mozilla-central/obj/widget/gtk/mozgtk/gtk3/libmozgtk.so"));
706 }
707
708 #[test]
709 fn test_elf_file_so_version() {
710 #[rustfmt::skip]
711 let test_cases = [
712 ("/usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.32", (6, 0, 32, 0)),
713 ("/usr/lib/x86_64-linux-gnu/libcairo-gobject.so.2.11800.0", (2, 11800, 0, 0)),
714 ("/usr/lib/x86_64-linux-gnu/libm.so.6", (6, 0, 0, 0)),
715 ("/usr/lib/x86_64-linux-gnu/libpthread.so.0", (0, 0, 0, 0)),
716 ("/usr/lib/x86_64-linux-gnu/libgmodule-2.0.so.0.7800.0", (0, 7800, 0, 0)),
717 ("/usr/lib/x86_64-linux-gnu/libabsl_time_zone.so.20220623.0.0", (20220623, 0, 0, 0)),
718 ("/usr/lib/x86_64-linux-gnu/libdbus-1.so.3.34.2rc5", (3, 34, 2, 5)),
719 ("/usr/lib/x86_64-linux-gnu/libdbus-1.so.3.34.2rc", (3, 34, 2, 0)),
720 ("/usr/lib/x86_64-linux-gnu/libdbus-1.so.3.34.rc5", (3, 34, 0, 5)),
721 ("/usr/lib/x86_64-linux-gnu/libtoto.so.AAA", (0, 0, 0, 0)),
722 ("/usr/lib/x86_64-linux-gnu/libsemver-1.so.1.2.alpha.1", (1, 2, 0, 1)),
723 ("/usr/lib/x86_64-linux-gnu/libboop.so.1.2.3.4.5", (1, 2, 3, 4)),
724 ("/usr/lib/x86_64-linux-gnu/libboop.so.1.2.3pre4.5", (1, 2, 3, 4)),
725 ];
726
727 assert!(SoVersion::parse(OsStr::new("/home/alex/bin/firefox/libmozsandbox.so")).is_none());
728
729 for (path, expected) in test_cases {
730 let actual = SoVersion::parse(OsStr::new(path)).unwrap();
731 assert_eq!(actual, expected);
732 }
733 }
734
735 #[test]
736 fn test_whitespaces_in_name() {
737 let mappings = get_mappings_for(
738 "\
739 10000000-20000000 r--p 00000000 00:3e 27136458 libmoz gtk.so
740 30000000-40000000 r--p 00000000 00:3e 27136458 \"libmoz gtk.so (deleted)\"
741 30000000-40000000 r--p 00000000 00:3e 27136458 ",
742 0x7ffe091bf000,
743 );
744
745 assert_eq!(mappings.len(), 3);
746 assert_eq!(mappings[0].name, Some("libmoz gtk.so".into()));
747 assert_eq!(
748 mappings[1].name,
749 Some("\"libmoz gtk.so (deleted)\"".into())
750 );
751 assert_eq!(mappings[2].name, None);
752 }
753 }