Debian Codegraph @

third_party/rust/minidump-unwind/src/symbols/debuginfo.rs

raw
1 //! This module provides a `SymbolProvider` which uses local binary debuginfo.
2
3 use super::{async_trait, FileError, FileKind, FillSymbolError, FrameSymbolizer, FrameWalker};
4 use cachemap2::CacheMap;
5 use framehop::Unwinder;
6 use memmap2::Mmap;
7 use minidump::{MinidumpModuleList, MinidumpSystemInfo, Module};
8 use object::read::{macho::FatArch, Architecture};
9 use std::cell::UnsafeCell;
10 use std::fs::File;
11 use std::path::{Path, PathBuf};
12
13 /// A symbol provider which gets information from the minidump modules on the local system.
14 ///
15 /// Note: this symbol provider will currently only restore the registers necessary for unwinding
16 /// the given platform. In the future this may be extended to restore all registers.
17 pub struct DebugInfoSymbolProvider {
18 unwinder: Box<dyn UnwinderInterface + Send + Sync>,
19 symbols: Box<dyn SymbolInterface + Send + Sync>,
20 /// The caches and unwinder operate on the memory held by the mapped modules, so this field
21 /// must not be dropped until after they are dropped.
22 _mapped_modules: Box<[Mmap]>,
23 }
24
25 pub struct DebugInfoSymbolProviderBuilder {
26 #[cfg(feature = "debuginfo-symbols")]
27 enable_symbols: bool,
28 }
29
30 type ModuleData = std::borrow::Cow<'static, [u8]>;
31 type FHModule = framehop::Module<ModuleData>;
32
33 struct UnwinderImpl<U: Unwinder> {
34 unwinder: U,
35 unwind_cache: PerThread<U::Cache>,
36 }
37
38 impl<U: Unwinder + Default> Default for UnwinderImpl<U> {
39 fn default() -> Self {
40 UnwinderImpl {
41 unwinder: Default::default(),
42 unwind_cache: Default::default(),
43 }
44 }
45 }
46
47 impl UnwinderImpl<framehop::x86_64::UnwinderX86_64<ModuleData>> {
48 pub fn x86_64() -> Box<dyn UnwinderInterface + Send + Sync> {
49 Box::<Self>::default()
50 }
51 }
52
53 impl UnwinderImpl<framehop::aarch64::UnwinderAarch64<ModuleData>> {
54 pub fn aarch64() -> Box<dyn UnwinderInterface + Send + Sync> {
55 Box::<Self>::default()
56 }
57 }
58
59 trait WalkerRegs: Sized {
60 fn regs_from_walker(walker: &(dyn FrameWalker + Send)) -> Option<Self>;
61 fn update_walker(self, walker: &mut (dyn FrameWalker + Send)) -> Option<()>;
62 }
63
64 impl WalkerRegs for framehop::x86_64::UnwindRegsX86_64 {
65 fn regs_from_walker(walker: &(dyn FrameWalker + Send)) -> Option<Self> {
66 let sp = walker.get_callee_register("rsp")?;
67 let bp = walker.get_callee_register("rbp")?;
68 let ip = walker.get_callee_register("rip")?;
69 Some(Self::new(ip, sp, bp))
70 }
71
72 fn update_walker(self, walker: &mut (dyn FrameWalker + Send)) -> Option<()> {
73 walker.set_cfa(self.sp())?;
74 walker.set_caller_register("rbp", self.bp())?;
75 Some(())
76 }
77 }
78
79 impl WalkerRegs for framehop::aarch64::UnwindRegsAarch64 {
80 fn regs_from_walker(walker: &(dyn FrameWalker + Send)) -> Option<Self> {
81 let lr = walker.get_callee_register("lr")?;
82 let sp = walker.get_callee_register("sp")?;
83 let fp = walker.get_callee_register("fp")?;
84 // TODO PtrAuthMask on MacOS?
85 Some(Self::new(lr, sp, fp))
86 }
87
88 fn update_walker(self, walker: &mut (dyn FrameWalker + Send)) -> Option<()> {
89 walker.set_cfa(self.sp())?;
90 walker.set_caller_register("lr", self.lr())?;
91 walker.set_caller_register("fp", self.fp())?;
92 Some(())
93 }
94 }
95
96 trait UnwinderInterface {
97 fn add_module(&mut self, module: FHModule);
98 fn unwind_frame(&self, walker: &mut (dyn FrameWalker + Send)) -> Option<()>;
99 }
100
101 impl<U: Unwinder<Module = FHModule>> UnwinderInterface for UnwinderImpl<U>
102 where
103 U::UnwindRegs: WalkerRegs,
104 U::Cache: Default,
105 {
106 fn add_module(&mut self, module: FHModule) {
107 self.unwinder.add_module(module);
108 }
109
110 fn unwind_frame(&self, walker: &mut (dyn FrameWalker + Send)) -> Option<()> {
111 let mut regs = U::UnwindRegs::regs_from_walker(walker)?;
112 let instruction = walker.get_instruction();
113 let result = self.unwind_cache.with(|cache| {
114 self.unwinder.unwind_frame(
115 if walker.has_grand_callee() {
116 framehop::FrameAddress::from_return_address(instruction + 1).unwrap()
117 } else {
118 framehop::FrameAddress::from_instruction_pointer(instruction)
119 },
120 &mut regs,
121 cache,
122 &mut |addr| walker.get_register_at_address(addr).ok_or(()),
123 )
124 });
125 let ra = match result {
126 Ok(ra) => ra,
127 Err(e) => {
128 tracing::error!("failed to unwind frame: {e}");
129 return None;
130 }
131 };
132 if let Some(ra) = ra {
133 walker.set_ra(ra);
134 }
135 regs.update_walker(walker)?;
136 Some(())
137 }
138 }
139
140 #[async_trait]
141 trait SymbolInterface {
142 async fn fill_symbol(
143 &self,
144 module: &(dyn Module + Sync),
145 frame: &mut (dyn FrameSymbolizer + Send),
146 ) -> Result<(), FillSymbolError>;
147 }
148
149 /// A SymbolInterface that always returns `Ok(())` without doing anything.
150 struct NoSymbols;
151
152 #[async_trait]
153 impl SymbolInterface for NoSymbols {
154 async fn fill_symbol(
155 &self,
156 _module: &(dyn Module + Sync),
157 _frame: &mut (dyn FrameSymbolizer + Send),
158 ) -> Result<(), FillSymbolError> {
159 Ok(())
160 }
161 }
162
163 #[cfg(feature = "debuginfo-symbols")]
164 mod wholesym_symbol_interface {
165 use super::*;
166 use futures_util::lock::Mutex;
167 use std::collections::HashMap;
168 use wholesym::{LookupAddress, SymbolManager, SymbolManagerConfig, SymbolMap};
169
170 pub struct Impl {
171 /// Indexed by module base address.
172 symbols: HashMap<ModuleKey, Mutex<SymbolMap>>,
173 }
174
175 impl Impl {
176 pub async fn new(modules: &MinidumpModuleList) -> Self {
177 let mut symbols = HashMap::new();
178 let symbol_manager = SymbolManager::with_config(SymbolManagerConfig::new());
179 for module in modules.iter() {
180 let path = effective_debug_file(module, false);
181 if let Ok(sm) = symbol_manager
182 .load_symbol_map_for_binary_at_path(&path, None)
183 .await
184 {
185 symbols.insert(module.into(), Mutex::new(sm));
186 }
187 }
188 Impl { symbols }
189 }
190 }
191
192 #[async_trait]
193 impl SymbolInterface for Impl {
194 async fn fill_symbol(
195 &self,
196 module: &(dyn Module + Sync),
197 frame: &mut (dyn FrameSymbolizer + Send),
198 ) -> Result<(), FillSymbolError> {
199 let key = ModuleKey::for_module(module);
200 let symbol_map = self.symbols.get(&key).ok_or(FillSymbolError {})?;
201
202 use std::convert::TryInto;
203 let addr = match (frame.get_instruction() - module.base_address()).try_into() {
204 Ok(a) => a,
205 Err(e) => {
206 tracing::error!("failed to downcast relative address offset: {e}");
207 return Ok(());
208 }
209 };
210
211 let address_info = symbol_map
212 .lock()
213 .await
214 .lookup(LookupAddress::Relative(addr))
215 .await;
216
217 if let Some(address_info) = address_info {
218 frame.set_function(
219 &address_info.symbol.name,
220 module.base_address() + address_info.symbol.address as u64,
221 0,
222 );
223
224 if let Some(frames) = address_info.frames {
225 let mut iter = frames.into_iter().rev();
226 if let Some(f) = iter.next() {
227 if let Some(path) = f.file_path {
228 frame.set_source_file(
229 path.raw_path(),
230 f.line_number.unwrap_or(0),
231 module.base_address() + address_info.symbol.address as u64,
232 );
233 }
234 }
235 for f in iter {
236 frame.add_inline_frame(
237 f.function.as_deref().unwrap_or(""),
238 f.file_path.as_ref().map(|p| p.raw_path()),
239 f.line_number,
240 );
241 }
242 }
243 }
244 Ok(())
245 }
246 }
247 }
248
249 #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
250 struct ModuleKey(u64);
251
252 impl ModuleKey {
253 /// Create a module key for the given module.
254 pub fn for_module(module: &dyn Module) -> Self {
255 ModuleKey(module.base_address())
256 }
257 }
258
259 impl From<&dyn Module> for ModuleKey {
260 fn from(module: &dyn Module) -> Self {
261 Self::for_module(module)
262 }
263 }
264
265 impl From<&minidump::MinidumpModule> for ModuleKey {
266 fn from(module: &minidump::MinidumpModule) -> Self {
267 Self::for_module(module)
268 }
269 }
270
271 struct PerThread<T> {
272 inner: CacheMap<std::thread::ThreadId, UnsafeCell<T>>,
273 }
274
275 impl<T> Default for PerThread<T> {
276 fn default() -> Self {
277 PerThread {
278 inner: Default::default(),
279 }
280 }
281 }
282
283 impl<T: Default> PerThread<T> {
284 pub fn with<F, R>(&self, f: F) -> R
285 where
286 F: FnOnce(&mut T) -> R,
287 {
288 // # Safety
289 // We guarantee unique access to the mutable reference because the values are indexed by
290 // thread id: each thread gets its own value which it can freely mutate. We prevent
291 // multiple mutable aliases from being created by requiring a callback function.
292 f(unsafe { &mut *self.inner.cache_default(std::thread::current().id()).get() })
293 }
294 }
295
296 mod object_section_info {
297 use framehop::ModuleSectionInfo;
298 use object::read::{Object, ObjectSection, ObjectSegment};
299 use std::ops::Range;
300
301 #[repr(transparent)]
302 pub struct ObjectSectionInfo<'a, O>(pub &'a O);
303
304 impl<O> std::ops::Deref for ObjectSectionInfo<'_, O> {
305 type Target = O;
306
307 fn deref(&self) -> &Self::Target {
308 self.0
309 }
310 }
311
312 impl<'data: 'file, 'file, O, D> ModuleSectionInfo<D> for ObjectSectionInfo<'file, O>
313 where
314 O: Object<'data>,
315 D: From<&'data [u8]>,
316 {
317 fn base_svma(&self) -> u64 {
318 if let Some(text_segment) = self.segments().find(|s| s.name() == Ok(Some("__TEXT"))) {
319 // This is a mach-O image. "Relative addresses" are relative to the
320 // vmaddr of the __TEXT segment.
321 return text_segment.address();
322 }
323
324 // For PE binaries, relative_address_base() returns the image base address.
325 // Otherwise it returns zero. This gives regular ELF images a base address of zero,
326 // which is what we want.
327 self.relative_address_base()
328 }
329
330 fn section_svma_range(&mut self, name: &[u8]) -> Option<Range<u64>> {
331 let section = self.section_by_name_bytes(name)?;
332 Some(section.address()..section.address() + section.size())
333 }
334
335 fn section_data(&mut self, name: &[u8]) -> Option<D> {
336 let section = self.section_by_name_bytes(name)?;
337 section.data().ok().map(|data| data.into())
338 }
339
340 fn segment_svma_range(&mut self, name: &[u8]) -> Option<Range<u64>> {
341 let segment = self.segments().find(|s| s.name_bytes() == Ok(Some(name)))?;
342 Some(segment.address()..segment.address() + segment.size())
343 }
344
345 fn segment_data(&mut self, name: &[u8]) -> Option<D> {
346 let segment = self.segments().find(|s| s.name_bytes() == Ok(Some(name)))?;
347 segment.data().ok().map(|data| data.into())
348 }
349 }
350 }
351
352 /// Get the file path with debug information for the given module.
353 ///
354 /// If `unwind_info` is true, returns the path that should contain unwind information.
355 fn effective_debug_file(module: &dyn Module, unwind_info: bool) -> PathBuf {
356 // Windows x86_64 always stores the unwind info _only_ in the binary.
357 let ignore_debug_file = unwind_info && cfg!(all(windows, target_arch = "x86_64"));
358
359 let code_file = module.code_file();
360 let code_file_path: &Path = code_file.as_ref().as_ref();
361
362 if !ignore_debug_file {
363 if let Some(file) = module.debug_file() {
364 let file_path: &Path = file.as_ref().as_ref();
365 // Anchor relative paths in the code file parent.
366 if file_path.is_relative() {
367 if let Some(parent) = code_file_path.parent() {
368 let path = parent.join(file_path);
369 if path.exists() {
370 return path;
371 }
372 }
373 }
374 if file_path.exists() {
375 return file_path.to_owned();
376 }
377 }
378 // else fall back to code file below
379 }
380
381 code_file_path.to_owned()
382 }
383
384 fn load_unwind_module(
385 module: &dyn Module,
386 arch: Architecture,
387 ) -> Option<(Mmap, framehop::Module<ModuleData>)> {
388 let path = effective_debug_file(module, true);
389 let file = match File::open(&path) {
390 Ok(file) => file,
391 Err(e) => {
392 tracing::warn!("failed to open {} for debug info: {e}", path.display());
393 return None;
394 }
395 };
396 // # Safety
397 // The file is presumably read-only (being some binary or debug info file).
398 let mapped = match unsafe { Mmap::map(&file) } {
399 Ok(m) => m,
400 Err(e) => {
401 tracing::error!("failed to map {} for debug info: {e}", path.display());
402 return None;
403 }
404 };
405
406 // # Safety
407 // We broaden the lifetime to static, but ensure that the Mmap which provides the data
408 // outlives all references.
409 let data = unsafe { std::mem::transmute::<&[u8], &'static [u8]>(mapped.as_ref()) };
410
411 let object_data = match object::read::FileKind::parse(data) {
412 Err(e) => {
413 // If FileKind parsing fails, File parsing will fail too, so bail out.
414 tracing::error!("failed to parse file kind for {}: {e}", path.display());
415 return None;
416 }
417 Ok(object::read::FileKind::MachOFat64) => get_fat_macho_data(
418 &path,
419 data,
420 object::read::macho::MachOFatFile64::parse(data),
421 arch,
422 )?,
423 Ok(object::read::FileKind::MachOFat32) => get_fat_macho_data(
424 &path,
425 data,
426 object::read::macho::MachOFatFile32::parse(data),
427 arch,
428 )?,
429 _ => data,
430 };
431
432 let objfile = match object::read::File::parse(object_data) {
433 Ok(o) => o,
434 Err(e) => {
435 tracing::error!("failed to parse object file {}: {e}", path.display());
436 return None;
437 }
438 };
439
440 let base = module.base_address();
441 let end = base + module.size();
442 let fhmodule = framehop::Module::new(
443 path.display().to_string(),
444 base..end,
445 base,
446 object_section_info::ObjectSectionInfo(&objfile),
447 );
448
449 Some((mapped, fhmodule))
450 }
451
452 fn get_fat_macho_data<'data, Fat: FatArch>(
453 path: &Path,
454 fatfile_data: &'data [u8],
455 result: object::read::Result<object::read::macho::MachOFatFile<'data, Fat>>,
456 arch: Architecture,
457 ) -> Option<&'data [u8]> {
458 match result {
459 Err(e) => {
460 tracing::error!("failed to parse fat macho file {}: {e}", path.display());
461 None
462 }
463 Ok(fatfile) => {
464 let Some(arch) = fatfile.arches().iter().find(|a| a.architecture() == arch) else {
465 tracing::error!(
466 "failed to find object file for {arch:?} architecture in fat macho file {}",
467 path.display()
468 );
469 return None;
470 };
471 arch.data(fatfile_data).map_or_else(
472 |e| {
473 tracing::error!(
474 "failed to read data from fat macho file {}: {e}",
475 path.display()
476 );
477 None
478 },
479 Some,
480 )
481 }
482 }
483 }
484
485 impl Default for DebugInfoSymbolProviderBuilder {
486 fn default() -> Self {
487 DebugInfoSymbolProviderBuilder {
488 #[cfg(feature = "debuginfo-symbols")]
489 enable_symbols: true,
490 }
491 }
492 }
493
494 impl DebugInfoSymbolProviderBuilder {
495 /// Create a new builder.
496 ///
497 /// This returns the default builder.
498 pub fn new() -> Self {
499 Self::default()
500 }
501
502 /// Enable or disable symbolication.
503 ///
504 /// This saves processing time if desired, only doing unwinding if symbols are disabled. This
505 /// option is only available when the `wholesym` feature (usually through the `debuginfo`
506 /// feature) is enabled, and defaults to `true`.
507 #[cfg(feature = "debuginfo-symbols")]
508 pub fn symbols(mut self, enable: bool) -> Self {
509 self.enable_symbols = enable;
510 self
511 }
512
513 /// Create the DebugInfoSymbolProvider.
514 pub async fn build(
515 self,
516 system_info: &MinidumpSystemInfo,
517 modules: &MinidumpModuleList,
518 ) -> DebugInfoSymbolProvider {
519 let mut mapped_modules = Vec::new();
520 use minidump::system_info::Cpu;
521 let (arch, mut unwinder) = match system_info.cpu {
522 Cpu::X86_64 => (Architecture::X86_64, UnwinderImpl::x86_64()),
523 Cpu::Arm64 => (Architecture::Aarch64, UnwinderImpl::aarch64()),
524 _ => unimplemented!(),
525 };
526
527 #[cfg(not(feature = "debuginfo-symbols"))]
528 let symbols: Box<dyn SymbolInterface + Send + Sync> = Box::new(NoSymbols);
529
530 #[cfg(feature = "debuginfo-symbols")]
531 let symbols: Box<dyn SymbolInterface + Send + Sync> = if self.enable_symbols {
532 Box::new(wholesym_symbol_interface::Impl::new(modules).await)
533 } else {
534 Box::new(NoSymbols)
535 };
536
537 for module in modules.iter() {
538 if let Some((mapped, fhmodule)) = load_unwind_module(module, arch) {
539 mapped_modules.push(mapped);
540 unwinder.add_module(fhmodule);
541 }
542 }
543 DebugInfoSymbolProvider {
544 unwinder,
545 symbols,
546 _mapped_modules: mapped_modules.into(),
547 }
548 }
549 }
550
551 impl DebugInfoSymbolProvider {
552 /// Create a builder for the DebugInfoSymbolProvider.
553 pub fn builder() -> DebugInfoSymbolProviderBuilder {
554 Default::default()
555 }
556
557 /// Create a new DebugInfoSymbolProvider with the default builder settings.
558 pub async fn new(system_info: &MinidumpSystemInfo, modules: &MinidumpModuleList) -> Self {
559 Self::builder().build(system_info, modules).await
560 }
561 }
562
563 #[async_trait]
564 impl super::SymbolProvider for DebugInfoSymbolProvider {
565 async fn fill_symbol(
566 &self,
567 module: &(dyn Module + Sync),
568 frame: &mut (dyn FrameSymbolizer + Send),
569 ) -> Result<(), FillSymbolError> {
570 self.symbols.fill_symbol(module, frame).await
571 }
572
573 async fn walk_frame(
574 &self,
575 _module: &(dyn Module + Sync),
576 walker: &mut (dyn FrameWalker + Send),
577 ) -> Option<()> {
578 self.unwinder.unwind_frame(walker)
579 }
580
581 async fn get_file_path(
582 &self,
583 module: &(dyn Module + Sync),
584 file_kind: FileKind,
585 ) -> Result<PathBuf, FileError> {
586 let path = match file_kind {
587 FileKind::BreakpadSym => None,
588 FileKind::Binary => Some(PathBuf::from(module.code_file().as_ref())),
589 FileKind::ExtraDebugInfo => module.debug_file().map(|p| PathBuf::from(p.as_ref())),
590 };
591 match path {
592 Some(path) if path.exists() => Ok(path),
593 _ => Err(FileError::NotFound),
594 }
595 }
596 }