1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
//! 在 crates.io 上使用 `gimli` crate 支持符号化
//!
//! 这是 Rust 的默认符号实现。

use self::gimli::read::EndianSlice;
use self::gimli::NativeEndian as Endian;
use self::mmap::Mmap;
use self::stash::Stash;
use super::BytesOrWideString;
use super::ResolveWhat;
use super::SymbolName;
use addr2line::gimli;
use core::convert::TryInto;
use core::mem;
use core::u32;
use libc::c_void;
use mystd::ffi::OsString;
use mystd::fs::File;
use mystd::path::Path;
use mystd::prelude::v1::*;

#[cfg(backtrace_in_libstd)]
mod mystd {
    pub use crate::*;
}
#[cfg(not(backtrace_in_libstd))]
extern crate std as mystd;

cfg_if::cfg_if! {
    if #[cfg(windows)] {
        #[path = "gimli/mmap_windows.rs"]
        mod mmap;
    } else if #[cfg(any(
        target_os = "android",
        target_os = "freebsd",
        target_os = "fuchsia",
        target_os = "haiku",
        target_os = "ios",
        target_os = "linux",
        target_os = "macos",
        target_os = "openbsd",
        target_os = "solaris",
        target_os = "illumos",
    ))] {
        #[path = "gimli/mmap_unix.rs"]
        mod mmap;
    } else {
        #[path = "gimli/mmap_fake.rs"]
        mod mmap;
    }
}

mod stash;

const MAPPINGS_CACHE_SIZE: usize = 4;

struct Mapping {
    // 静态生命周期是一个谎言,它可以绕过缺乏对自引用结构的支持。
    cx: Context<'static>,
    _map: Mmap,
    _stash: Stash,
}

enum Either<A, B> {
    #[allow(dead_code)]
    A(A),
    B(B),
}

impl Mapping {
    /// 通过确保指定的 `data` 用于创建 `Context` 来创建 `Mapping`,并且只能从该 `data` 或已解压部分或辅助数据的 `Stash` 中借用。
    ///
    ///
    fn mk<F>(data: Mmap, mk: F) -> Option<Mapping>
    where
        F: for<'a> FnOnce(&'a [u8], &'a Stash) -> Option<Context<'a>>,
    {
        Mapping::mk_or_other(data, move |data, stash| {
            let cx = mk(data, stash)?;
            Some(Either::B(cx))
        })
    }

    /// 从 `data` 创建一个 `Mapping`,或者如果闭包决定,返回一个不同的映射。
    ///
    fn mk_or_other<F>(data: Mmap, mk: F) -> Option<Mapping>
    where
        F: for<'a> FnOnce(&'a [u8], &'a Stash) -> Option<Either<Mapping, Context<'a>>>,
    {
        let stash = Stash::new();
        let cx = match mk(&data, &stash)? {
            Either::A(mapping) => return Some(mapping),
            Either::B(cx) => cx,
        };
        Some(Mapping {
            // 转换为静态生命周期,因为这些符号仅应借用 `map` 和 `stash`,我们将其保留在下面。
            //
            cx: unsafe { core::mem::transmute::<Context<'_>, Context<'static>>(cx) },
            _map: data,
            _stash: stash,
        })
    }
}

struct Context<'a> {
    dwarf: addr2line::Context<EndianSlice<'a, Endian>>,
    object: Object<'a>,
}

impl<'data> Context<'data> {
    fn new(
        stash: &'data Stash,
        object: Object<'data>,
        sup: Option<Object<'data>>,
    ) -> Option<Context<'data>> {
        let mut sections = gimli::Dwarf::load(|id| -> Result<_, ()> {
            let data = object.section(stash, id.name()).unwrap_or(&[]);
            Ok(EndianSlice::new(data, Endian))
        })
        .ok()?;

        if let Some(sup) = sup {
            sections
                .load_sup(|id| -> Result<_, ()> {
                    let data = sup.section(stash, id.name()).unwrap_or(&[]);
                    Ok(EndianSlice::new(data, Endian))
                })
                .ok()?;
        }
        let dwarf = addr2line::Context::from_dwarf(sections).ok()?;

        Some(Context { dwarf, object })
    }
}

fn mmap(path: &Path) -> Option<Mmap> {
    let file = File::open(path).ok()?;
    let len = file.metadata().ok()?.len().try_into().ok()?;
    unsafe { Mmap::map(&file, len) }
}

cfg_if::cfg_if! {
    if #[cfg(windows)] {
        mod coff;
        use self::coff::Object;
    } else if #[cfg(any(
        target_os = "macos",
        target_os = "ios",
        target_os = "tvos",
        target_os = "watchos",
    ))] {
        mod macho;
        use self::macho::Object;
    } else {
        mod elf;
        use self::elf::Object;
    }
}

cfg_if::cfg_if! {
    if #[cfg(windows)] {
        mod libs_windows;
        use libs_windows::native_libraries;
    } else if #[cfg(any(
        target_os = "macos",
        target_os = "ios",
        target_os = "tvos",
        target_os = "watchos",
    ))] {
        mod libs_macos;
        use libs_macos::native_libraries;
    } else if #[cfg(target_os = "illumos")] {
        mod libs_illumos;
        use libs_illumos::native_libraries;
    } else if #[cfg(all(
        any(
            target_os = "linux",
            target_os = "fuchsia",
            target_os = "freebsd",
            target_os = "openbsd",
            all(target_os = "android", feature = "dl_iterate_phdr"),
        ),
        not(target_env = "uclibc"),
    ))] {
        mod libs_dl_iterate_phdr;
        use libs_dl_iterate_phdr::native_libraries;
        #[path = "gimli/parse_running_mmaps_unix.rs"]
        mod parse_running_mmaps;
    } else if #[cfg(target_env = "libnx")] {
        mod libs_libnx;
        use libs_libnx::native_libraries;
    } else if #[cfg(target_os = "haiku")] {
        mod libs_haiku;
        use libs_haiku::native_libraries;
    } else {
        // 其他的一切都不应该知道如何加载本机库。
        fn native_libraries() -> Vec<Library> {
            Vec::new()
        }
    }
}

#[derive(Default)]
struct Cache {
    /// 已加载的所有已知共享库。
    libraries: Vec<Library>,

    /// 映射缓存,其中保留了解析的矮人信息。
    ///
    /// 该列表在其整个生命周期中具有固定容量,且容量从不增加。
    /// 每对中的 `usize` 元素是 `libraries` 的索引,以上 `usize::max_value()` 表示当前可执行文件。
    ///
    /// `Mapping` 是相应的解析后的矮人信息。
    ///
    /// 请注意,这基本上是一个 LRU 缓存,我们将在这里对地址进行符号化,以表示地址。
    ///
    mappings: Vec<(usize, Mapping)>,
}

struct Library {
    name: OsString,
    /// 该库的各段已加载到内存中以及它们的加载位置。
    segments: Vec<LibrarySegment>,
    /// 该库的 "bias",通常是它被加载到内存中的位置。
    /// 将此值添加到每个段的声明地址中,以获取该段加载到的实际虚拟内存地址。
    /// 另外,从实际虚拟内存地址中减去此偏差以将其索引到 debuginfo 和符号表中。
    ///
    ///
    bias: usize,
}

struct LibrarySegment {
    /// 对象文件中此段的指定地址。
    /// 实际上,这不是加载该段的位置,而是在该地址加上包含库的 `bias` 所在的位置。
    ///
    stated_virtual_memory_address: usize,
    /// 此段在内存中的大小。
    len: usize,
}

// 不安全,因为需要从外部进行同步
pub unsafe fn clear_symbol_cache() {
    Cache::with_global(|cache| cache.mappings.clear());
}

impl Cache {
    fn new() -> Cache {
        Cache {
            mappings: Vec::with_capacity(MAPPINGS_CACHE_SIZE),
            libraries: native_libraries(),
        }
    }

    // 不安全,因为需要从外部进行同步
    unsafe fn with_global(f: impl FnOnce(&mut Self)) {
        // 一个非常小,非常简单的 LRU 缓存,用于调试信息映射。
        //
        // 命中率应该很高,因为典型的栈不会在许多共享库之间交叉。
        //
        // `addr2line::Context` 结构的创建成本非常高。
        // 预期其成本将由后续的 `locate` 查询摊销,这些查询将利用在构建 `addr2line::Context`s 时构建的结构来获得良好的加速效果。
        //
        // 如果我们没有此缓存,则摊销将永远不会发生,而象征性回溯将是 ssssllllooooowwww。
        //
        //
        static mut MAPPINGS_CACHE: Option<Cache> = None;

        f(MAPPINGS_CACHE.get_or_insert_with(|| Cache::new()))
    }

    fn avma_to_svma(&self, addr: *const u8) -> Option<(usize, *const u8)> {
        self.libraries
            .iter()
            .enumerate()
            .filter_map(|(i, lib)| {
                // 首先,测试此 `lib` 是否具有包含 `addr` 的任何段 (处理重定位)。如果此检查通过,那么我们可以继续下面的内容并实际翻译地址。
                //
                // 请注意,我们在这里使用 `wrapping_add` 以避免溢出检查。疯狂地看到 SVMA + 偏差计算会溢出。
                // 这似乎有点奇怪,但除了可能忽略这些片段,因为它们可能指向太空之外,我们对此无能为力。
                //
                // 这最初是在 rust-lang/backtrace-rs#329 中出现的。
                //
                //
                //
                //
                //
                if !lib.segments.iter().any(|s| {
                    let svma = s.stated_virtual_memory_address;
                    let start = svma.wrapping_add(lib.bias);
                    let end = start.wrapping_add(s.len);
                    let address = addr as usize;
                    start <= address && address < end
                }) {
                    return None;
                }

                // 现在我们知道 `lib` 包含 `addr`,我们可以用偏差进行偏移以找到指定的虚拟内存地址。
                //
                let svma = (addr as usize).wrapping_sub(lib.bias);
                Some((i, svma as *const u8))
            })
            .next()
    }

    fn mapping_for_lib<'a>(&'a mut self, lib: usize) -> Option<&'a mut Context<'a>> {
        let idx = self.mappings.iter().position(|(idx, _)| *idx == lib);

        // 不变性: 在此条件完成后且未提前从错误中返回后,此路径的缓存条目位于索引处 0.
        //

        if let Some(idx) = idx {
            // 当映射已经在缓存中时,将其移到最前面。
            if idx != 0 {
                let entry = self.mappings.remove(idx);
                self.mappings.insert(0, entry);
            }
        } else {
            // 当映射不在高速缓存中时,请创建一个新的映射,将其插入高速缓存的前面,并在必要时逐出最旧的高速缓存条目。
            //
            //
            let name = &self.libraries[lib].name;
            let mapping = Mapping::new(name.as_ref())?;

            if self.mappings.len() == MAPPINGS_CACHE_SIZE {
                self.mappings.pop();
            }

            self.mappings.insert(0, (lib, mapping));
        }

        let cx: &'a mut Context<'static> = &mut self.mappings[0].1.cx;
        // 不要泄漏 `'static` 的生命周期,请确保它仅限于我们自己
        //
        Some(unsafe { mem::transmute::<&'a mut Context<'static>, &'a mut Context<'a>>(cx) })
    }
}

pub unsafe fn resolve(what: ResolveWhat<'_>, cb: &mut dyn FnMut(&super::Symbol)) {
    let addr = what.address_or_ip();
    let mut call = |sym: Symbol<'_>| {
        // 将 `sym` 的生命周期延长到 `'static`,因为不幸的是这里要求我们这样做,但它只是作为一个引用,所以无论如何,不应在此框架之外持续对它的引用。
        //
        //
        let sym = mem::transmute::<Symbol<'_>, Symbol<'static>>(sym);
        (cb)(&super::Symbol { inner: sym });
    };

    Cache::with_global(|cache| {
        let (lib, addr) = match cache.avma_to_svma(addr as *const u8) {
            Some(pair) => pair,
            None => return,
        };

        // 最后,获取缓存的映射或为此文件创建新的映射,并评估 DWARF 信息以查找该地址的 file/line/name。
        //
        let cx = match cache.mapping_for_lib(lib) {
            Some(cx) => cx,
            None => return,
        };
        let mut any_frames = false;
        if let Ok(mut frames) = cx.dwarf.find_frames(addr as u64) {
            while let Ok(Some(frame)) = frames.next() {
                any_frames = true;
                let name = match frame.function {
                    Some(f) => Some(f.name.slice()),
                    None => cx.object.search_symtab(addr as u64),
                };
                call(Symbol::Frame {
                    addr: addr as *mut c_void,
                    location: frame.location,
                    name,
                });
            }
        }
        if !any_frames {
            if let Some((object_cx, object_addr)) = cx.object.search_object_map(addr as u64) {
                if let Ok(mut frames) = object_cx.dwarf.find_frames(object_addr) {
                    while let Ok(Some(frame)) = frames.next() {
                        any_frames = true;
                        call(Symbol::Frame {
                            addr: addr as *mut c_void,
                            location: frame.location,
                            name: frame.function.map(|f| f.name.slice()),
                        });
                    }
                }
            }
        }
        if !any_frames {
            if let Some(name) = cx.object.search_symtab(addr as u64) {
                call(Symbol::Symtab {
                    addr: addr as *mut c_void,
                    name,
                });
            }
        }
    });
}

pub enum Symbol<'a> {
    /// 我们能够找到该符号的框架信息,并且 `addr2line` 的框架内部具有所有细腻的细节。
    ///
    Frame {
        addr: *mut c_void,
        location: Option<addr2line::Location<'a>>,
        name: Option<&'a [u8]>,
    },
    /// 找不到调试信息,但是我们在 elf 可执行文件的符号表中找到了它。
    ///
    Symtab { addr: *mut c_void, name: &'a [u8] },
}

impl Symbol<'_> {
    pub fn name(&self) -> Option<SymbolName<'_>> {
        match self {
            Symbol::Frame { name, .. } => {
                let name = name.as_ref()?;
                Some(SymbolName::new(name))
            }
            Symbol::Symtab { name, .. } => Some(SymbolName::new(name)),
        }
    }

    pub fn addr(&self) -> Option<*mut c_void> {
        match self {
            Symbol::Frame { addr, .. } => Some(*addr),
            Symbol::Symtab { .. } => None,
        }
    }

    pub fn filename_raw(&self) -> Option<BytesOrWideString<'_>> {
        match self {
            Symbol::Frame { location, .. } => {
                let file = location.as_ref()?.file?;
                Some(BytesOrWideString::Bytes(file.as_bytes()))
            }
            Symbol::Symtab { .. } => None,
        }
    }

    pub fn filename(&self) -> Option<&Path> {
        match self {
            Symbol::Frame { location, .. } => {
                let file = location.as_ref()?.file?;
                Some(Path::new(file))
            }
            Symbol::Symtab { .. } => None,
        }
    }

    pub fn lineno(&self) -> Option<u32> {
        match self {
            Symbol::Frame { location, .. } => location.as_ref()?.line,
            Symbol::Symtab { .. } => None,
        }
    }

    pub fn colno(&self) -> Option<u32> {
        match self {
            Symbol::Frame { location, .. } => location.as_ref()?.column,
            Symbol::Symtab { .. } => None,
        }
    }
}