Coverage Report

Created: 2024-10-16 07:58

/rust/registry/src/index.crates.io-6f17d22bba15001f/backtrace-0.3.73/src/symbolize/gimli.rs
Line
Count
Source (jump to first uncovered line)
1
//! Support for symbolication using the `gimli` crate on crates.io
2
//!
3
//! This is the default symbolication implementation for Rust.
4
5
use self::gimli::read::EndianSlice;
6
use self::gimli::NativeEndian as Endian;
7
use self::mmap::Mmap;
8
use self::stash::Stash;
9
use super::BytesOrWideString;
10
use super::ResolveWhat;
11
use super::SymbolName;
12
use addr2line::gimli;
13
use core::convert::TryInto;
14
use core::mem;
15
use core::u32;
16
use libc::c_void;
17
use mystd::ffi::OsString;
18
use mystd::fs::File;
19
use mystd::path::Path;
20
use mystd::prelude::v1::*;
21
22
#[cfg(backtrace_in_libstd)]
23
mod mystd {
24
    pub use crate::*;
25
}
26
#[cfg(not(backtrace_in_libstd))]
27
extern crate std as mystd;
28
29
cfg_if::cfg_if! {
30
    if #[cfg(windows)] {
31
        #[path = "gimli/mmap_windows.rs"]
32
        mod mmap;
33
    } else if #[cfg(target_vendor = "apple")] {
34
        #[path = "gimli/mmap_unix.rs"]
35
        mod mmap;
36
    } else if #[cfg(any(
37
        target_os = "android",
38
        target_os = "freebsd",
39
        target_os = "fuchsia",
40
        target_os = "haiku",
41
        target_os = "hurd",
42
        target_os = "linux",
43
        target_os = "openbsd",
44
        target_os = "solaris",
45
        target_os = "illumos",
46
        target_os = "aix",
47
    ))] {
48
        #[path = "gimli/mmap_unix.rs"]
49
        mod mmap;
50
    } else {
51
        #[path = "gimli/mmap_fake.rs"]
52
        mod mmap;
53
    }
54
}
55
56
mod stash;
57
58
const MAPPINGS_CACHE_SIZE: usize = 4;
59
60
struct Mapping {
61
    // 'static lifetime is a lie to hack around lack of support for self-referential structs.
62
    cx: Context<'static>,
63
    _map: Mmap,
64
    stash: Stash,
65
}
66
67
enum Either<A, B> {
68
    #[allow(dead_code)]
69
    A(A),
70
    B(B),
71
}
72
73
impl Mapping {
74
    /// Creates a `Mapping` by ensuring that the `data` specified is used to
75
    /// create a `Context` and it can only borrow from that or the `Stash` of
76
    /// decompressed sections or auxiliary data.
77
0
    fn mk<F>(data: Mmap, mk: F) -> Option<Mapping>
78
0
    where
79
0
        F: for<'a> FnOnce(&'a [u8], &'a Stash) -> Option<Context<'a>>,
80
0
    {
81
0
        Mapping::mk_or_other(data, move |data, stash| {
82
0
            let cx = mk(data, stash)?;
83
0
            Some(Either::B(cx))
84
0
        })
85
0
    }
86
87
    /// Creates a `Mapping` from `data`, or if the closure decides to, returns a
88
    /// different mapping.
89
0
    fn mk_or_other<F>(data: Mmap, mk: F) -> Option<Mapping>
90
0
    where
91
0
        F: for<'a> FnOnce(&'a [u8], &'a Stash) -> Option<Either<Mapping, Context<'a>>>,
92
0
    {
93
0
        let stash = Stash::new();
94
0
        let cx = match mk(&data, &stash)? {
95
0
            Either::A(mapping) => return Some(mapping),
96
0
            Either::B(cx) => cx,
97
0
        };
98
0
        Some(Mapping {
99
0
            // Convert to 'static lifetimes since the symbols should
100
0
            // only borrow `map` and `stash` and we're preserving them below.
101
0
            cx: unsafe { core::mem::transmute::<Context<'_>, Context<'static>>(cx) },
102
0
            _map: data,
103
0
            stash: stash,
104
0
        })
105
0
    }
Unexecuted instantiation: <backtrace::symbolize::gimli::Mapping>::mk_or_other::<<backtrace::symbolize::gimli::Mapping>::mk<<backtrace::symbolize::gimli::Mapping>::new_debug::{closure#0}>::{closure#0}>
Unexecuted instantiation: <backtrace::symbolize::gimli::Mapping>::mk_or_other::<<backtrace::symbolize::gimli::Mapping>::new::{closure#0}>
106
}
107
108
struct Context<'a> {
109
    dwarf: addr2line::Context<EndianSlice<'a, Endian>>,
110
    object: Object<'a>,
111
    package: Option<gimli::DwarfPackage<EndianSlice<'a, Endian>>>,
112
}
113
114
impl<'data> Context<'data> {
115
0
    fn new(
116
0
        stash: &'data Stash,
117
0
        object: Object<'data>,
118
0
        sup: Option<Object<'data>>,
119
0
        dwp: Option<Object<'data>>,
120
0
    ) -> Option<Context<'data>> {
121
0
        let mut sections = gimli::Dwarf::load(|id| -> Result<_, ()> {
122
0
            if cfg!(not(target_os = "aix")) {
123
0
                let data = object.section(stash, id.name()).unwrap_or(&[]);
124
0
                Ok(EndianSlice::new(data, Endian))
125
            } else {
126
0
                if let Some(name) = id.xcoff_name() {
127
0
                    let data = object.section(stash, name).unwrap_or(&[]);
128
0
                    Ok(EndianSlice::new(data, Endian))
129
                } else {
130
0
                    Ok(EndianSlice::new(&[], Endian))
131
                }
132
            }
133
0
        })
134
0
        .ok()?;
135
136
0
        if let Some(sup) = sup {
137
0
            sections
138
0
                .load_sup(|id| -> Result<_, ()> {
139
0
                    let data = sup.section(stash, id.name()).unwrap_or(&[]);
140
0
                    Ok(EndianSlice::new(data, Endian))
141
0
                })
142
0
                .ok()?;
143
0
        }
144
0
        let dwarf = addr2line::Context::from_dwarf(sections).ok()?;
145
146
0
        let mut package = None;
147
0
        if let Some(dwp) = dwp {
148
            package = Some(
149
0
                gimli::DwarfPackage::load(
150
0
                    |id| -> Result<_, gimli::Error> {
151
0
                        let data = id
152
0
                            .dwo_name()
153
0
                            .and_then(|name| dwp.section(stash, name))
154
0
                            .unwrap_or(&[]);
155
0
                        Ok(EndianSlice::new(data, Endian))
156
0
                    },
157
0
                    EndianSlice::new(&[], Endian),
158
0
                )
159
0
                .ok()?,
160
            );
161
0
        }
162
163
0
        Some(Context {
164
0
            dwarf,
165
0
            object,
166
0
            package,
167
0
        })
168
0
    }
169
170
0
    fn find_frames(
171
0
        &'_ self,
172
0
        stash: &'data Stash,
173
0
        probe: u64,
174
0
    ) -> gimli::Result<addr2line::FrameIter<'_, EndianSlice<'data, Endian>>> {
175
0
        use addr2line::{LookupContinuation, LookupResult};
176
0
177
0
        let mut l = self.dwarf.find_frames(probe);
178
0
        loop {
179
0
            let (load, continuation) = match l {
180
0
                LookupResult::Output(output) => break output,
181
0
                LookupResult::Load { load, continuation } => (load, continuation),
182
0
            };
183
0
184
0
            l = continuation.resume(handle_split_dwarf(self.package.as_ref(), stash, load));
185
        }
186
0
    }
187
}
188
189
0
fn mmap(path: &Path) -> Option<Mmap> {
190
0
    let file = File::open(path).ok()?;
191
0
    let len = file.metadata().ok()?.len().try_into().ok()?;
192
0
    unsafe { Mmap::map(&file, len) }
193
0
}
194
195
cfg_if::cfg_if! {
196
    if #[cfg(windows)] {
197
        mod coff;
198
        use self::coff::{handle_split_dwarf, Object};
199
    } else if #[cfg(any(target_vendor = "apple"))] {
200
        mod macho;
201
        use self::macho::{handle_split_dwarf, Object};
202
    } else if #[cfg(target_os = "aix")] {
203
        mod xcoff;
204
        use self::xcoff::{handle_split_dwarf, Object};
205
    } else {
206
        mod elf;
207
        use self::elf::{handle_split_dwarf, Object};
208
    }
209
}
210
211
cfg_if::cfg_if! {
212
    if #[cfg(windows)] {
213
        mod libs_windows;
214
        use libs_windows::native_libraries;
215
    } else if #[cfg(target_vendor = "apple")] {
216
        mod libs_macos;
217
        use libs_macos::native_libraries;
218
    } else if #[cfg(target_os = "illumos")] {
219
        mod libs_illumos;
220
        use libs_illumos::native_libraries;
221
    } else if #[cfg(all(
222
        any(
223
            target_os = "linux",
224
            target_os = "fuchsia",
225
            target_os = "freebsd",
226
            target_os = "hurd",
227
            target_os = "openbsd",
228
            target_os = "netbsd",
229
            all(target_os = "android", feature = "dl_iterate_phdr"),
230
        ),
231
        not(target_env = "uclibc"),
232
    ))] {
233
        mod libs_dl_iterate_phdr;
234
        use libs_dl_iterate_phdr::native_libraries;
235
        #[path = "gimli/parse_running_mmaps_unix.rs"]
236
        mod parse_running_mmaps;
237
    } else if #[cfg(target_env = "libnx")] {
238
        mod libs_libnx;
239
        use libs_libnx::native_libraries;
240
    } else if #[cfg(target_os = "haiku")] {
241
        mod libs_haiku;
242
        use libs_haiku::native_libraries;
243
    } else if #[cfg(target_os = "aix")] {
244
        mod libs_aix;
245
        use libs_aix::native_libraries;
246
    } else {
247
        // Everything else should doesn't know how to load native libraries.
248
        fn native_libraries() -> Vec<Library> {
249
            Vec::new()
250
        }
251
    }
252
}
253
254
#[derive(Default)]
255
struct Cache {
256
    /// All known shared libraries that have been loaded.
257
    libraries: Vec<Library>,
258
259
    /// Mappings cache where we retain parsed dwarf information.
260
    ///
261
    /// This list has a fixed capacity for its entire lifetime which never
262
    /// increases. The `usize` element of each pair is an index into `libraries`
263
    /// above where `usize::max_value()` represents the current executable. The
264
    /// `Mapping` is corresponding parsed dwarf information.
265
    ///
266
    /// Note that this is basically an LRU cache and we'll be shifting things
267
    /// around in here as we symbolize addresses.
268
    mappings: Vec<(usize, Mapping)>,
269
}
270
271
struct Library {
272
    name: OsString,
273
    #[cfg(target_os = "aix")]
274
    /// On AIX, the library mmapped can be a member of a big-archive file.
275
    /// For example, with a big-archive named libfoo.a containing libbar.so,
276
    /// one can use `dlopen("libfoo.a(libbar.so)", RTLD_MEMBER | RTLD_LAZY)`
277
    /// to use the `libbar.so` library. In this case, only `libbar.so` is
278
    /// mmapped, not the whole `libfoo.a`.
279
    member_name: OsString,
280
    /// Segments of this library loaded into memory, and where they're loaded.
281
    segments: Vec<LibrarySegment>,
282
    /// The "bias" of this library, typically where it's loaded into memory.
283
    /// This value is added to each segment's stated address to get the actual
284
    /// virtual memory address that the segment is loaded into. Additionally
285
    /// this bias is subtracted from real virtual memory addresses to index into
286
    /// debuginfo and the symbol table.
287
    bias: usize,
288
}
289
290
struct LibrarySegment {
291
    /// The stated address of this segment in the object file. This is not
292
    /// actually where the segment is loaded, but rather this address plus the
293
    /// containing library's `bias` is where to find it.
294
    stated_virtual_memory_address: usize,
295
    /// The size of this segment in memory.
296
    len: usize,
297
}
298
299
#[cfg(target_os = "aix")]
300
fn create_mapping(lib: &Library) -> Option<Mapping> {
301
    let name = &lib.name;
302
    let member_name = &lib.member_name;
303
    Mapping::new(name.as_ref(), member_name)
304
}
305
306
#[cfg(not(target_os = "aix"))]
307
0
fn create_mapping(lib: &Library) -> Option<Mapping> {
308
0
    let name = &lib.name;
309
0
    Mapping::new(name.as_ref())
310
0
}
311
312
// unsafe because this is required to be externally synchronized
313
0
pub unsafe fn clear_symbol_cache() {
314
0
    Cache::with_global(|cache| cache.mappings.clear());
315
0
}
316
317
impl Cache {
318
0
    fn new() -> Cache {
319
0
        Cache {
320
0
            mappings: Vec::with_capacity(MAPPINGS_CACHE_SIZE),
321
0
            libraries: native_libraries(),
322
0
        }
323
0
    }
324
325
    // unsafe because this is required to be externally synchronized
326
0
    unsafe fn with_global(f: impl FnOnce(&mut Self)) {
327
0
        // A very small, very simple LRU cache for debug info mappings.
328
0
        //
329
0
        // The hit rate should be very high, since the typical stack doesn't cross
330
0
        // between many shared libraries.
331
0
        //
332
0
        // The `addr2line::Context` structures are pretty expensive to create. Its
333
0
        // cost is expected to be amortized by subsequent `locate` queries, which
334
0
        // leverage the structures built when constructing `addr2line::Context`s to
335
0
        // get nice speedups. If we didn't have this cache, that amortization would
336
0
        // never happen, and symbolicating backtraces would be ssssllllooooowwww.
337
0
        static mut MAPPINGS_CACHE: Option<Cache> = None;
338
0
339
0
        f(MAPPINGS_CACHE.get_or_insert_with(|| Cache::new()))
Unexecuted instantiation: <backtrace::symbolize::gimli::Cache>::with_global::<backtrace::symbolize::gimli::clear_symbol_cache::{closure#0}>::{closure#0}
Unexecuted instantiation: <backtrace::symbolize::gimli::Cache>::with_global::<backtrace::symbolize::gimli::resolve::{closure#1}>::{closure#0}
340
0
    }
Unexecuted instantiation: <backtrace::symbolize::gimli::Cache>::with_global::<backtrace::symbolize::gimli::clear_symbol_cache::{closure#0}>
Unexecuted instantiation: <backtrace::symbolize::gimli::Cache>::with_global::<backtrace::symbolize::gimli::resolve::{closure#1}>
341
342
0
    fn avma_to_svma(&self, addr: *const u8) -> Option<(usize, *const u8)> {
343
0
        self.libraries
344
0
            .iter()
345
0
            .enumerate()
346
0
            .filter_map(|(i, lib)| {
347
0
                // First up, test if this `lib` has any segment containing the
348
0
                // `addr` (handling relocation). If this check passes then we
349
0
                // can continue below and actually translate the address.
350
0
                //
351
0
                // Note that we're using `wrapping_add` here to avoid overflow
352
0
                // checks. It's been seen in the wild that the SVMA + bias
353
0
                // computation overflows. It seems a bit odd that would happen
354
0
                // but there's not a huge amount we can do about it other than
355
0
                // probably just ignore those segments since they're likely
356
0
                // pointing off into space. This originally came up in
357
0
                // rust-lang/backtrace-rs#329.
358
0
                if !lib.segments.iter().any(|s| {
359
0
                    let svma = s.stated_virtual_memory_address;
360
0
                    let start = svma.wrapping_add(lib.bias);
361
0
                    let end = start.wrapping_add(s.len);
362
0
                    let address = addr as usize;
363
0
                    start <= address && address < end
364
0
                }) {
365
0
                    return None;
366
0
                }
367
0
368
0
                // Now that we know `lib` contains `addr`, we can offset with
369
0
                // the bias to find the stated virtual memory address.
370
0
                let svma = (addr as usize).wrapping_sub(lib.bias);
371
0
                Some((i, svma as *const u8))
372
0
            })
373
0
            .next()
374
0
    }
375
376
0
    fn mapping_for_lib<'a>(&'a mut self, lib: usize) -> Option<(&'a mut Context<'a>, &'a Stash)> {
377
0
        let idx = self.mappings.iter().position(|(idx, _)| *idx == lib);
378
379
        // Invariant: after this conditional completes without early returning
380
        // from an error, the cache entry for this path is at index 0.
381
382
0
        if let Some(idx) = idx {
383
            // When the mapping is already in the cache, move it to the front.
384
0
            if idx != 0 {
385
0
                let entry = self.mappings.remove(idx);
386
0
                self.mappings.insert(0, entry);
387
0
            }
388
        } else {
389
            // When the mapping is not in the cache, create a new mapping,
390
            // insert it into the front of the cache, and evict the oldest cache
391
            // entry if necessary.
392
0
            let mapping = create_mapping(&self.libraries[lib])?;
393
394
0
            if self.mappings.len() == MAPPINGS_CACHE_SIZE {
395
0
                self.mappings.pop();
396
0
            }
397
398
0
            self.mappings.insert(0, (lib, mapping));
399
        }
400
401
0
        let mapping = &mut self.mappings[0].1;
402
0
        let cx: &'a mut Context<'static> = &mut mapping.cx;
403
0
        let stash: &'a Stash = &mapping.stash;
404
0
        // don't leak the `'static` lifetime, make sure it's scoped to just
405
0
        // ourselves
406
0
        Some((
407
0
            unsafe { mem::transmute::<&'a mut Context<'static>, &'a mut Context<'a>>(cx) },
408
0
            stash,
409
0
        ))
410
0
    }
411
}
412
413
0
pub unsafe fn resolve(what: ResolveWhat<'_>, cb: &mut dyn FnMut(&super::Symbol)) {
414
0
    let addr = what.address_or_ip();
415
0
    let mut call = |sym: Symbol<'_>| {
416
0
        // Extend the lifetime of `sym` to `'static` since we are unfortunately
417
0
        // required to here, but it's only ever going out as a reference so no
418
0
        // reference to it should be persisted beyond this frame anyway.
419
0
        let sym = mem::transmute::<Symbol<'_>, Symbol<'static>>(sym);
420
0
        (cb)(&super::Symbol { inner: sym });
421
0
    };
422
0
423
0
    Cache::with_global(|cache| {
424
0
        let (lib, addr) = match cache.avma_to_svma(addr.cast_const().cast::<u8>()) {
425
0
            Some(pair) => pair,
426
0
            None => return,
427
        };
428
429
        // Finally, get a cached mapping or create a new mapping for this file, and
430
        // evaluate the DWARF info to find the file/line/name for this address.
431
0
        let (cx, stash) = match cache.mapping_for_lib(lib) {
432
0
            Some((cx, stash)) => (cx, stash),
433
0
            None => return,
434
        };
435
0
        let mut any_frames = false;
436
0
        if let Ok(mut frames) = cx.find_frames(stash, addr as u64) {
437
0
            while let Ok(Some(frame)) = frames.next() {
438
0
                any_frames = true;
439
0
                let name = match frame.function {
440
0
                    Some(f) => Some(f.name.slice()),
441
0
                    None => cx.object.search_symtab(addr as u64),
442
                };
443
0
                call(Symbol::Frame {
444
0
                    addr: addr as *mut c_void,
445
0
                    location: frame.location,
446
0
                    name,
447
0
                });
448
            }
449
0
        }
450
0
        if !any_frames {
451
0
            if let Some((object_cx, object_addr)) = cx.object.search_object_map(addr as u64) {
452
0
                if let Ok(mut frames) = object_cx.find_frames(stash, object_addr) {
453
0
                    while let Ok(Some(frame)) = frames.next() {
454
0
                        any_frames = true;
455
0
                        call(Symbol::Frame {
456
0
                            addr: addr as *mut c_void,
457
0
                            location: frame.location,
458
0
                            name: frame.function.map(|f| f.name.slice()),
459
0
                        });
460
0
                    }
461
0
                }
462
0
            }
463
0
        }
464
0
        if !any_frames {
465
0
            if let Some(name) = cx.object.search_symtab(addr as u64) {
466
0
                call(Symbol::Symtab { name });
467
0
            }
468
0
        }
469
0
    });
470
0
}
471
472
pub enum Symbol<'a> {
473
    /// We were able to locate frame information for this symbol, and
474
    /// `addr2line`'s frame internally has all the nitty gritty details.
475
    Frame {
476
        addr: *mut c_void,
477
        location: Option<addr2line::Location<'a>>,
478
        name: Option<&'a [u8]>,
479
    },
480
    /// Couldn't find debug information, but we found it in the symbol table of
481
    /// the elf executable.
482
    Symtab { name: &'a [u8] },
483
}
484
485
impl Symbol<'_> {
486
0
    pub fn name(&self) -> Option<SymbolName<'_>> {
487
0
        match self {
488
0
            Symbol::Frame { name, .. } => {
489
0
                let name = name.as_ref()?;
490
0
                Some(SymbolName::new(name))
491
            }
492
0
            Symbol::Symtab { name, .. } => Some(SymbolName::new(name)),
493
        }
494
0
    }
495
496
0
    pub fn addr(&self) -> Option<*mut c_void> {
497
0
        match self {
498
0
            Symbol::Frame { addr, .. } => Some(*addr),
499
0
            Symbol::Symtab { .. } => None,
500
        }
501
0
    }
502
503
0
    pub fn filename_raw(&self) -> Option<BytesOrWideString<'_>> {
504
0
        match self {
505
0
            Symbol::Frame { location, .. } => {
506
0
                let file = location.as_ref()?.file?;
507
0
                Some(BytesOrWideString::Bytes(file.as_bytes()))
508
            }
509
0
            Symbol::Symtab { .. } => None,
510
        }
511
0
    }
512
513
0
    pub fn filename(&self) -> Option<&Path> {
514
0
        match self {
515
0
            Symbol::Frame { location, .. } => {
516
0
                let file = location.as_ref()?.file?;
517
0
                Some(Path::new(file))
518
            }
519
0
            Symbol::Symtab { .. } => None,
520
        }
521
0
    }
522
523
0
    pub fn lineno(&self) -> Option<u32> {
524
0
        match self {
525
0
            Symbol::Frame { location, .. } => location.as_ref()?.line,
526
0
            Symbol::Symtab { .. } => None,
527
        }
528
0
    }
529
530
0
    pub fn colno(&self) -> Option<u32> {
531
0
        match self {
532
0
            Symbol::Frame { location, .. } => location.as_ref()?.column,
533
0
            Symbol::Symtab { .. } => None,
534
        }
535
0
    }
536
}