1use self::gimli::read::EndianSlice;
6use self::gimli::NativeEndian as Endian;
7use self::mmap::Mmap;
8use self::stash::Stash;
9use super::BytesOrWideString;
10use super::ResolveWhat;
11use super::SymbolName;
12use addr2line::gimli;
13use core::convert::TryInto;
14use core::mem;
15use libc::c_void;
16use mystd::ffi::OsString;
17use mystd::fs::File;
18use mystd::path::Path;
19use mystd::prelude::v1::*;
20
21#[cfg(backtrace_in_libstd)]
22mod mystd {
23 pub use crate::*;
24}
25#[cfg(not(backtrace_in_libstd))]
26extern crate std as mystd;
27
28cfg_if::cfg_if! {
29 if #[cfg(windows)] {
30 #[path = "gimli/mmap_windows.rs"]
31 mod mmap;
32 } else if #[cfg(target_vendor = "apple")] {
33 #[path = "gimli/mmap_unix.rs"]
34 mod mmap;
35 } else if #[cfg(any(
36 target_os = "android",
37 target_os = "freebsd",
38 target_os = "fuchsia",
39 target_os = "haiku",
40 target_os = "hurd",
41 target_os = "linux",
42 target_os = "openbsd",
43 target_os = "solaris",
44 target_os = "illumos",
45 target_os = "aix",
46 target_os = "cygwin",
47 ))] {
48 #[path = "gimli/mmap_unix.rs"]
49 mod mmap;
50 } else {
51 #[path = "gimli/mmap_fake.rs"]
52 mod mmap;
53 }
54}
55
56mod lru;
57mod stash;
58
59use lru::Lru;
60
61const MAPPINGS_CACHE_SIZE: usize = 4;
62
63struct Mapping {
64 cx: Context<'static>,
66 _map: Mmap,
67 stash: Stash,
68}
69
70enum Either<A, B> {
71 #[allow(dead_code)]
72 A(A),
73 B(B),
74}
75
76impl Mapping {
77 fn mk<F>(data: Mmap, mk: F) -> Option<Mapping>
81 where
82 F: for<'a> FnOnce(&'a [u8], &'a Stash) -> Option<Context<'a>>,
83 {
84 Mapping::mk_or_other(data, move |data, stash| {
85 let cx = mk(data, stash)?;
86 Some(Either::B(cx))
87 })
88 }
89
90 fn mk_or_other<F>(data: Mmap, mk: F) -> Option<Mapping>
93 where
94 F: for<'a> FnOnce(&'a [u8], &'a Stash) -> Option<Either<Mapping, Context<'a>>>,
95 {
96 let stash = Stash::new();
97 let cx = match mk(&data, &stash)? {
98 Either::A(mapping) => return Some(mapping),
99 Either::B(cx) => cx,
100 };
101 Some(Mapping {
102 cx: unsafe { core::mem::transmute::<Context<'_>, Context<'static>>(cx) },
105 _map: data,
106 stash,
107 })
108 }
109}
110
111struct Context<'a> {
112 dwarf: addr2line::Context<EndianSlice<'a, Endian>>,
113 object: Object<'a>,
114 package: Option<gimli::DwarfPackage<EndianSlice<'a, Endian>>>,
115}
116
117impl<'data> Context<'data> {
118 fn new(
119 stash: &'data Stash,
120 object: Object<'data>,
121 sup: Option<Object<'data>>,
122 dwp: Option<Object<'data>>,
123 ) -> Option<Context<'data>> {
124 let mut sections = gimli::Dwarf::load(|id| -> Result<_, ()> {
125 if cfg!(not(target_os = "aix")) {
126 let data = object.section(stash, id.name()).unwrap_or(&[]);
127 Ok(EndianSlice::new(data, Endian))
128 } else if let Some(name) = id.xcoff_name() {
129 let data = object.section(stash, name).unwrap_or(&[]);
130 Ok(EndianSlice::new(data, Endian))
131 } else {
132 Ok(EndianSlice::new(&[], Endian))
133 }
134 })
135 .ok()?;
136
137 if let Some(sup) = sup {
138 sections
139 .load_sup(|id| -> Result<_, ()> {
140 let data = sup.section(stash, id.name()).unwrap_or(&[]);
141 Ok(EndianSlice::new(data, Endian))
142 })
143 .ok()?;
144 }
145 let dwarf = addr2line::Context::from_dwarf(sections).ok()?;
146
147 let mut package = None;
148 if let Some(dwp) = dwp {
149 package = Some(
150 gimli::DwarfPackage::load(
151 |id| -> Result<_, gimli::Error> {
152 let data = id
153 .dwo_name()
154 .and_then(|name| dwp.section(stash, name))
155 .unwrap_or(&[]);
156 Ok(EndianSlice::new(data, Endian))
157 },
158 EndianSlice::new(&[], Endian),
159 )
160 .ok()?,
161 );
162 }
163
164 Some(Context {
165 dwarf,
166 object,
167 package,
168 })
169 }
170
171 fn find_frames(
172 &'_ self,
173 stash: &'data Stash,
174 probe: u64,
175 ) -> gimli::Result<addr2line::FrameIter<'_, EndianSlice<'data, Endian>>> {
176 use addr2line::{LookupContinuation, LookupResult};
177
178 let mut l = self.dwarf.find_frames(probe);
179 loop {
180 let (load, continuation) = match l {
181 LookupResult::Output(output) => break output,
182 LookupResult::Load { load, continuation } => (load, continuation),
183 };
184
185 l = continuation.resume(handle_split_dwarf(self.package.as_ref(), stash, load));
186 }
187 }
188}
189
190fn mmap(path: &Path) -> Option<Mmap> {
191 let file = File::open(path).ok()?;
192 let len = file.metadata().ok()?.len().try_into().ok()?;
193 unsafe { Mmap::map(&file, len, 0) }
194}
195
196cfg_if::cfg_if! {
197 if #[cfg(any(windows, target_os = "cygwin"))] {
198 mod coff;
199 use self::coff::{handle_split_dwarf, Object};
200 } else if #[cfg(any(target_vendor = "apple"))] {
201 mod macho;
202 use self::macho::{handle_split_dwarf, Object};
203 } else if #[cfg(target_os = "aix")] {
204 mod xcoff;
205 use self::xcoff::{handle_split_dwarf, Object};
206 } else {
207 mod elf;
208 use self::elf::{handle_split_dwarf, Object};
209 }
210}
211
212cfg_if::cfg_if! {
213 if #[cfg(any(windows, target_os = "cygwin"))] {
214 mod libs_windows;
215 use libs_windows::native_libraries;
216 } else if #[cfg(target_vendor = "apple")] {
217 mod libs_macos;
218 use libs_macos::native_libraries;
219 } else if #[cfg(target_os = "illumos")] {
220 mod libs_illumos;
221 use libs_illumos::native_libraries;
222 } else if #[cfg(all(
223 any(
224 target_os = "linux",
225 target_os = "fuchsia",
226 target_os = "freebsd",
227 target_os = "hurd",
228 target_os = "openbsd",
229 target_os = "netbsd",
230 target_os = "nto",
231 target_os = "android",
232 ),
233 not(target_env = "uclibc"),
234 ))] {
235 mod libs_dl_iterate_phdr;
236 use libs_dl_iterate_phdr::native_libraries;
237 #[path = "gimli/parse_running_mmaps_unix.rs"]
238 mod parse_running_mmaps;
239 } else if #[cfg(target_env = "libnx")] {
240 mod libs_libnx;
241 use libs_libnx::native_libraries;
242 } else if #[cfg(target_os = "haiku")] {
243 mod libs_haiku;
244 use libs_haiku::native_libraries;
245 } else if #[cfg(target_os = "aix")] {
246 mod libs_aix;
247 use libs_aix::native_libraries;
248 } else {
249 fn native_libraries() -> Vec<Library> {
251 Vec::new()
252 }
253 }
254}
255
256#[derive(Default)]
257struct Cache {
258 libraries: Vec<Library>,
260
261 mappings: Lru<(usize, Mapping), MAPPINGS_CACHE_SIZE>,
271}
272
273struct Library {
274 name: OsString,
275 #[cfg(target_os = "android")]
276 zip_offset: Option<u64>,
290 #[cfg(target_os = "aix")]
291 member_name: OsString,
297 segments: Vec<LibrarySegment>,
299 bias: usize,
305}
306
307struct LibrarySegment {
308 stated_virtual_memory_address: usize,
312 len: usize,
314}
315
316fn create_mapping(lib: &Library) -> Option<Mapping> {
317 cfg_if::cfg_if! {
318 if #[cfg(target_os = "aix")] {
319 Mapping::new(lib.name.as_ref(), &lib.member_name)
320 } else if #[cfg(target_os = "android")] {
321 Mapping::new_android(lib.name.as_ref(), lib.zip_offset)
322 } else {
323 Mapping::new(lib.name.as_ref())
324 }
325 }
326}
327
328#[cfg(target_os = "android")]
333fn extract_zip_path_android(path: &mystd::ffi::OsStr) -> Option<&mystd::ffi::OsStr> {
334 use mystd::os::unix::ffi::OsStrExt;
335
336 path.as_bytes()
337 .windows(2)
338 .enumerate()
339 .find(|(_, chunk)| chunk == b"!/")
340 .map(|(index, _)| mystd::ffi::OsStr::from_bytes(path.as_bytes().split_at(index).0))
341}
342
343pub unsafe fn clear_symbol_cache() {
345 unsafe {
346 Cache::with_global(|cache| cache.mappings.clear());
347 }
348}
349
350impl Cache {
351 fn new() -> Cache {
352 Cache {
353 mappings: Lru::default(),
354 libraries: native_libraries(),
355 }
356 }
357
358 unsafe fn with_global(f: impl FnOnce(&mut Self)) {
360 static mut MAPPINGS_CACHE: Option<Cache> = None;
371
372 unsafe {
373 #[allow(static_mut_refs)]
375 f(MAPPINGS_CACHE.get_or_insert_with(Cache::new))
376 }
377 }
378
379 fn avma_to_svma(&self, addr: *const u8) -> Option<(usize, *const u8)> {
380 self.libraries
381 .iter()
382 .enumerate()
383 .filter_map(|(i, lib)| {
384 if !lib.segments.iter().any(|s| {
396 let svma = s.stated_virtual_memory_address;
397 let start = svma.wrapping_add(lib.bias);
398 let end = start.wrapping_add(s.len);
399 let address = addr as usize;
400 start <= address && address < end
401 }) {
402 return None;
403 }
404
405 let svma = (addr as usize).wrapping_sub(lib.bias);
408 Some((i, svma as *const u8))
409 })
410 .next()
411 }
412
413 fn mapping_for_lib<'a>(&'a mut self, lib: usize) -> Option<(&'a mut Context<'a>, &'a Stash)> {
414 let cache_idx = self.mappings.iter().position(|(lib_id, _)| *lib_id == lib);
415
416 let cache_entry = if let Some(idx) = cache_idx {
417 self.mappings.move_to_front(idx)
418 } else {
419 create_mapping(&self.libraries[lib])
422 .and_then(|mapping| self.mappings.push_front((lib, mapping)))
423 };
424
425 let (_, mapping) = cache_entry?;
426 let cx: &'a mut Context<'static> = &mut mapping.cx;
427 let stash: &'a Stash = &mapping.stash;
428 Some((
431 unsafe { mem::transmute::<&'a mut Context<'static>, &'a mut Context<'a>>(cx) },
432 stash,
433 ))
434 }
435}
436
437pub unsafe fn resolve(what: ResolveWhat<'_>, cb: &mut dyn FnMut(&super::Symbol)) {
438 let addr = what.address_or_ip();
439 let mut call = |sym: Symbol<'_>| {
440 let sym = unsafe { mem::transmute::<Symbol<'_>, Symbol<'static>>(sym) };
445 (cb)(&super::Symbol { inner: sym });
446 };
447
448 unsafe {
449 Cache::with_global(|cache| {
450 let (lib, addr) = match cache.avma_to_svma(addr.cast_const().cast::<u8>()) {
451 Some(pair) => pair,
452 None => return,
453 };
454
455 let (cx, stash) = match cache.mapping_for_lib(lib) {
458 Some((cx, stash)) => (cx, stash),
459 None => return,
460 };
461 let mut any_frames = false;
462 if let Ok(mut frames) = cx.find_frames(stash, addr as u64) {
463 while let Ok(Some(frame)) = frames.next() {
464 any_frames = true;
465 let name = match frame.function {
466 Some(f) => Some(f.name.slice()),
467 None => cx.object.search_symtab(addr as u64),
468 };
469 call(Symbol::Frame {
470 addr: addr as *mut c_void,
471 location: frame.location,
472 name,
473 });
474 }
475 }
476 if !any_frames {
477 if let Some((object_cx, object_addr)) = cx.object.search_object_map(addr as u64) {
478 if let Ok(mut frames) = object_cx.find_frames(stash, object_addr) {
479 while let Ok(Some(frame)) = frames.next() {
480 any_frames = true;
481 call(Symbol::Frame {
482 addr: addr as *mut c_void,
483 location: frame.location,
484 name: frame.function.map(|f| f.name.slice()),
485 });
486 }
487 }
488 }
489 }
490 if !any_frames {
491 if let Some(name) = cx.object.search_symtab(addr as u64) {
492 call(Symbol::Symtab { name });
493 }
494 }
495 });
496 }
497}
498
499pub enum Symbol<'a> {
500 Frame {
503 addr: *mut c_void,
504 location: Option<addr2line::Location<'a>>,
505 name: Option<&'a [u8]>,
506 },
507 Symtab { name: &'a [u8] },
510}
511
512impl Symbol<'_> {
513 pub fn name(&self) -> Option<SymbolName<'_>> {
514 match self {
515 Symbol::Frame { name, .. } => {
516 let name = name.as_ref()?;
517 Some(SymbolName::new(name))
518 }
519 Symbol::Symtab { name, .. } => Some(SymbolName::new(name)),
520 }
521 }
522
523 pub fn addr(&self) -> Option<*mut c_void> {
524 match self {
525 Symbol::Frame { addr, .. } => Some(*addr),
526 Symbol::Symtab { .. } => None,
527 }
528 }
529
530 pub fn filename_raw(&self) -> Option<BytesOrWideString<'_>> {
531 match self {
532 Symbol::Frame { location, .. } => {
533 let file = location.as_ref()?.file?;
534 Some(BytesOrWideString::Bytes(file.as_bytes()))
535 }
536 Symbol::Symtab { .. } => None,
537 }
538 }
539
540 pub fn filename(&self) -> Option<&Path> {
541 match self {
542 Symbol::Frame { location, .. } => {
543 let file = location.as_ref()?.file?;
544 Some(Path::new(file))
545 }
546 Symbol::Symtab { .. } => None,
547 }
548 }
549
550 pub fn lineno(&self) -> Option<u32> {
551 match self {
552 Symbol::Frame { location, .. } => location.as_ref()?.line,
553 Symbol::Symtab { .. } => None,
554 }
555 }
556
557 pub fn colno(&self) -> Option<u32> {
558 match self {
559 Symbol::Frame { location, .. } => location.as_ref()?.column,
560 Symbol::Symtab { .. } => None,
561 }
562 }
563}