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
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 {
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))
})
}
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 {
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;
} 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>,
mappings: Vec<(usize, Mapping)>,
}
struct Library {
name: OsString,
segments: Vec<LibrarySegment>,
bias: usize,
}
struct LibrarySegment {
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)) {
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)| {
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;
}
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);
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;
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<'_>| {
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,
};
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> {
Frame {
addr: *mut c_void,
location: Option<addr2line::Location<'a>>,
name: Option<&'a [u8]>,
},
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,
}
}
}