Debian Codegraph @

third_party/rust/framehop/src/unwinder.rs

raw
1 use alloc::string::String;
2 use alloc::sync::Arc;
3 use alloc::vec::Vec;
4 use fallible_iterator::FallibleIterator;
5 use gimli::{EndianSlice, LittleEndian};
6
7 use crate::arch::Arch;
8 use crate::cache::{AllocationPolicy, Cache};
9 use crate::dwarf::{DwarfCfiIndex, DwarfUnwinder, DwarfUnwinding, UnwindSectionType};
10 use crate::error::{Error, UnwinderError};
11 use crate::instruction_analysis::InstructionAnalysis;
12
13 #[cfg(feature = "macho")]
14 use crate::macho::{
15 CompactUnwindInfoUnwinder, CompactUnwindInfoUnwinding, CuiUnwindResult, TextBytes,
16 };
17 #[cfg(feature = "pe")]
18 use crate::pe::{DataAtRvaRange, PeUnwinding};
19 use crate::rule_cache::CacheResult;
20 use crate::unwind_result::UnwindResult;
21 use crate::unwind_rule::UnwindRule;
22 use crate::FrameAddress;
23
24 use core::marker::PhantomData;
25 use core::ops::{Deref, Range};
26 use core::sync::atomic::{AtomicU16, Ordering};
27
28 /// Unwinder is the trait that each CPU architecture's concrete unwinder type implements.
29 /// This trait's methods are what let you do the actual unwinding.
30 pub trait Unwinder: Clone {
31 /// The unwind registers type for the targeted CPU architecture.
32 type UnwindRegs;
33
34 /// The unwind cache for the targeted CPU architecture.
35 /// This is an associated type because the cache stores unwind rules, whose concrete
36 /// type depends on the CPU arch, and because the cache can support different allocation
37 /// policies.
38 type Cache;
39
40 /// The module type. This is an associated type because the concrete type varies
41 /// depending on the type you use to give the module access to the unwind section data.
42 type Module;
43
44 /// Add a module that's loaded in the profiled process. This is how you provide unwind
45 /// information and address ranges.
46 ///
47 /// This should be called whenever a new module is loaded into the process.
48 fn add_module(&mut self, module: Self::Module);
49
50 /// Remove a module that was added before using `add_module`, keyed by the start
51 /// address of that module's address range. If no match is found, the call is ignored.
52 /// This should be called whenever a module is unloaded from the process.
53 fn remove_module(&mut self, module_avma_range_start: u64);
54
55 /// Returns the highest code address that is known in this process based on the module
56 /// address ranges. Returns 0 if no modules have been added.
57 ///
58 /// This method can be used together with
59 /// [`PtrAuthMask::from_max_known_address`](crate::aarch64::PtrAuthMask::from_max_known_address)
60 /// to make an educated guess at a pointer authentication mask for Aarch64 return addresses.
61 fn max_known_code_address(&self) -> u64;
62
63 /// Unwind a single frame, to recover return address and caller register values.
64 /// This is the main entry point for unwinding.
65 fn unwind_frame<F>(
66 &self,
67 address: FrameAddress,
68 regs: &mut Self::UnwindRegs,
69 cache: &mut Self::Cache,
70 read_stack: &mut F,
71 ) -> Result<Option<u64>, Error>
72 where
73 F: FnMut(u64) -> Result<u64, ()>;
74
75 /// Return an iterator that unwinds frame by frame until the end of the stack is found.
76 fn iter_frames<'u, 'c, 'r, F>(
77 &'u self,
78 pc: u64,
79 regs: Self::UnwindRegs,
80 cache: &'c mut Self::Cache,
81 read_stack: &'r mut F,
82 ) -> UnwindIterator<'u, 'c, 'r, Self, F>
83 where
84 F: FnMut(u64) -> Result<u64, ()>,
85 {
86 UnwindIterator::new(self, pc, regs, cache, read_stack)
87 }
88 }
89
90 /// An iterator for unwinding the entire stack, starting from the initial register values.
91 ///
92 /// The first yielded frame is the instruction pointer. Subsequent addresses are return
93 /// addresses.
94 ///
95 /// This iterator attempts to detect if stack unwinding completed successfully, or if the
96 /// stack was truncated prematurely. If it thinks that it successfully found the root
97 /// function, it will complete with `Ok(None)`, otherwise it will complete with `Err(...)`.
98 /// However, the detection does not work in all cases, so you should expect `Err(...)` to
99 /// be returned even during normal operation. As a result, it is not recommended to use
100 /// this iterator as a `FallibleIterator`, because you might lose the entire stack if the
101 /// last iteration returns `Err(...)`.
102 ///
103 /// Lifetimes:
104 ///
105 /// - `'u`: The lifetime of the [`Unwinder`].
106 /// - `'c`: The lifetime of the unwinder cache.
107 /// - `'r`: The lifetime of the exclusive access to the `read_stack` callback.
108 pub struct UnwindIterator<'u, 'c, 'r, U: Unwinder + ?Sized, F: FnMut(u64) -> Result<u64, ()>> {
109 unwinder: &'u U,
110 state: UnwindIteratorState,
111 regs: U::UnwindRegs,
112 cache: &'c mut U::Cache,
113 read_stack: &'r mut F,
114 }
115
116 enum UnwindIteratorState {
117 Initial(u64),
118 Unwinding(FrameAddress),
119 Done,
120 }
121
122 impl<'u, 'c, 'r, U: Unwinder + ?Sized, F: FnMut(u64) -> Result<u64, ()>>
123 UnwindIterator<'u, 'c, 'r, U, F>
124 {
125 /// Create a new iterator. You'd usually use [`Unwinder::iter_frames`] instead.
126 pub fn new(
127 unwinder: &'u U,
128 pc: u64,
129 regs: U::UnwindRegs,
130 cache: &'c mut U::Cache,
131 read_stack: &'r mut F,
132 ) -> Self {
133 Self {
134 unwinder,
135 state: UnwindIteratorState::Initial(pc),
136 regs,
137 cache,
138 read_stack,
139 }
140 }
141 }
142
143 impl<'u, 'c, 'r, U: Unwinder + ?Sized, F: FnMut(u64) -> Result<u64, ()>>
144 UnwindIterator<'u, 'c, 'r, U, F>
145 {
146 /// Yield the next frame in the stack.
147 ///
148 /// The first frame is `Ok(Some(FrameAddress::InstructionPointer(...)))`.
149 /// Subsequent frames are `Ok(Some(FrameAddress::ReturnAddress(...)))`.
150 ///
151 /// If a root function has been reached, this iterator completes with `Ok(None)`.
152 /// Otherwise it completes with `Err(...)`, usually indicating that a certain stack
153 /// address could not be read.
154 #[allow(clippy::should_implement_trait)]
155 pub fn next(&mut self) -> Result<Option<FrameAddress>, Error> {
156 let next = match self.state {
157 UnwindIteratorState::Initial(pc) => {
158 self.state = UnwindIteratorState::Unwinding(FrameAddress::InstructionPointer(pc));
159 return Ok(Some(FrameAddress::InstructionPointer(pc)));
160 }
161 UnwindIteratorState::Unwinding(address) => {
162 self.unwinder
163 .unwind_frame(address, &mut self.regs, self.cache, self.read_stack)?
164 }
165 UnwindIteratorState::Done => return Ok(None),
166 };
167 match next {
168 Some(return_address) => {
169 let return_address = FrameAddress::from_return_address(return_address)
170 .ok_or(Error::ReturnAddressIsNull)?;
171 self.state = UnwindIteratorState::Unwinding(return_address);
172 Ok(Some(return_address))
173 }
174 None => {
175 self.state = UnwindIteratorState::Done;
176 Ok(None)
177 }
178 }
179 }
180 }
181
182 impl<'u, 'c, 'r, U: Unwinder + ?Sized, F: FnMut(u64) -> Result<u64, ()>> FallibleIterator
183 for UnwindIterator<'u, 'c, 'r, U, F>
184 {
185 type Item = FrameAddress;
186 type Error = Error;
187
188 fn next(&mut self) -> Result<Option<FrameAddress>, Error> {
189 self.next()
190 }
191 }
192
193 /// This global generation counter makes it so that the cache can be shared
194 /// between multiple unwinders.
195 /// This is a u16, so if you make it wrap around by adding / removing modules
196 /// more than 65535 times, then you risk collisions in the cache; meaning:
197 /// unwinding might not work properly if an old unwind rule was found in the
198 /// cache for the same address and the same (pre-wraparound) modules_generation.
199 static GLOBAL_MODULES_GENERATION: AtomicU16 = AtomicU16::new(0);
200
201 fn next_global_modules_generation() -> u16 {
202 GLOBAL_MODULES_GENERATION.fetch_add(1, Ordering::Relaxed)
203 }
204
205 cfg_if::cfg_if! {
206 if #[cfg(all(feature = "macho", feature = "pe"))] {
207 pub trait Unwinding:
208 Arch + DwarfUnwinding + InstructionAnalysis + CompactUnwindInfoUnwinding + PeUnwinding {}
209 impl<T: Arch + DwarfUnwinding + InstructionAnalysis + CompactUnwindInfoUnwinding + PeUnwinding>
210 Unwinding for T {}
211 } else if #[cfg(feature = "macho")] {
212 pub trait Unwinding:
213 Arch + DwarfUnwinding + InstructionAnalysis + CompactUnwindInfoUnwinding {}
214 impl<T: Arch + DwarfUnwinding + InstructionAnalysis + CompactUnwindInfoUnwinding> Unwinding for T {}
215 } else if #[cfg(feature = "pe")] {
216 pub trait Unwinding:
217 Arch + DwarfUnwinding + InstructionAnalysis + PeUnwinding {}
218 impl<T: Arch + DwarfUnwinding + InstructionAnalysis + PeUnwinding> Unwinding for T {}
219 } else {
220 pub trait Unwinding: Arch + DwarfUnwinding + InstructionAnalysis {}
221 impl<T: Arch + DwarfUnwinding + InstructionAnalysis> Unwinding for T {}
222 }
223 }
224
225 pub struct UnwinderInternal<D, A, P> {
226 /// sorted by avma_range.start
227 modules: Vec<Module<D>>,
228 /// Incremented every time modules is changed.
229 modules_generation: u16,
230 _arch: PhantomData<A>,
231 _allocation_policy: PhantomData<P>,
232 }
233
234 impl<D, A, P> Default for UnwinderInternal<D, A, P> {
235 fn default() -> Self {
236 Self::new()
237 }
238 }
239
240 impl<D, A, P> Clone for UnwinderInternal<D, A, P> {
241 fn clone(&self) -> Self {
242 Self {
243 modules: self.modules.clone(),
244 modules_generation: self.modules_generation,
245 _arch: PhantomData,
246 _allocation_policy: PhantomData,
247 }
248 }
249 }
250
251 impl<D, A, P> UnwinderInternal<D, A, P> {
252 pub fn new() -> Self {
253 Self {
254 modules: Vec::new(),
255 modules_generation: next_global_modules_generation(),
256 _arch: PhantomData,
257 _allocation_policy: PhantomData,
258 }
259 }
260 }
261
262 impl<D: Deref<Target = [u8]>, A: Unwinding, P: AllocationPolicy> UnwinderInternal<D, A, P> {
263 pub fn add_module(&mut self, module: Module<D>) {
264 let insertion_index = match self
265 .modules
266 .binary_search_by_key(&module.avma_range.start, |module| module.avma_range.start)
267 {
268 Ok(i) => {
269 #[cfg(feature = "std")]
270 eprintln!(
271 "Now we have two modules at the same start address 0x{:x}. This can't be good.",
272 module.avma_range.start
273 );
274 i
275 }
276 Err(i) => i,
277 };
278 self.modules.insert(insertion_index, module);
279 self.modules_generation = next_global_modules_generation();
280 }
281
282 pub fn remove_module(&mut self, module_address_range_start: u64) {
283 if let Ok(index) = self
284 .modules
285 .binary_search_by_key(&module_address_range_start, |module| {
286 module.avma_range.start
287 })
288 {
289 self.modules.remove(index);
290 self.modules_generation = next_global_modules_generation();
291 };
292 }
293
294 pub fn max_known_code_address(&self) -> u64 {
295 self.modules.last().map_or(0, |m| m.avma_range.end)
296 }
297
298 fn find_module_for_address(&self, address: u64) -> Option<(usize, u32)> {
299 let (module_index, module) = match self
300 .modules
301 .binary_search_by_key(&address, |m| m.avma_range.start)
302 {
303 Ok(i) => (i, &self.modules[i]),
304 Err(insertion_index) => {
305 if insertion_index == 0 {
306 // address is before first known module
307 return None;
308 }
309 let i = insertion_index - 1;
310 let module = &self.modules[i];
311 if module.avma_range.end <= address {
312 // address is after this module
313 return None;
314 }
315 (i, module)
316 }
317 };
318 if address < module.base_avma {
319 // Invalid base address
320 return None;
321 }
322 let relative_address = u32::try_from(address - module.base_avma).ok()?;
323 Some((module_index, relative_address))
324 }
325
326 fn with_cache<F, G>(
327 &self,
328 address: FrameAddress,
329 regs: &mut A::UnwindRegs,
330 cache: &mut Cache<A::UnwindRule, P>,
331 read_stack: &mut F,
332 callback: G,
333 ) -> Result<Option<u64>, Error>
334 where
335 F: FnMut(u64) -> Result<u64, ()>,
336 G: FnOnce(
337 &Module<D>,
338 FrameAddress,
339 u32,
340 &mut A::UnwindRegs,
341 &mut Cache<A::UnwindRule, P>,
342 &mut F,
343 ) -> Result<UnwindResult<A::UnwindRule>, UnwinderError>,
344 {
345 let lookup_address = address.address_for_lookup();
346 let is_first_frame = !address.is_return_address();
347 let cache_handle = match cache
348 .rule_cache
349 .lookup(lookup_address, self.modules_generation)
350 {
351 CacheResult::Hit(unwind_rule) => {
352 return unwind_rule.exec(is_first_frame, regs, read_stack);
353 }
354 CacheResult::Miss(handle) => handle,
355 };
356
357 let unwind_rule = match self.find_module_for_address(lookup_address) {
358 None => A::UnwindRule::fallback_rule(),
359 Some((module_index, relative_lookup_address)) => {
360 let module = &self.modules[module_index];
361 match callback(
362 module,
363 address,
364 relative_lookup_address,
365 regs,
366 cache,
367 read_stack,
368 ) {
369 Ok(UnwindResult::ExecRule(rule)) => rule,
370 Ok(UnwindResult::Uncacheable(return_address)) => {
371 return Ok(Some(return_address))
372 }
373 Err(_err) => {
374 // eprintln!("Unwinder error: {}", err);
375 A::UnwindRule::fallback_rule()
376 }
377 }
378 }
379 };
380 cache.rule_cache.insert(cache_handle, unwind_rule);
381 unwind_rule.exec(is_first_frame, regs, read_stack)
382 }
383
384 pub fn unwind_frame<F>(
385 &self,
386 address: FrameAddress,
387 regs: &mut A::UnwindRegs,
388 cache: &mut Cache<A::UnwindRule, P>,
389 read_stack: &mut F,
390 ) -> Result<Option<u64>, Error>
391 where
392 F: FnMut(u64) -> Result<u64, ()>,
393 {
394 self.with_cache(address, regs, cache, read_stack, Self::unwind_frame_impl)
395 }
396
397 fn unwind_frame_impl<F>(
398 module: &Module<D>,
399 address: FrameAddress,
400 rel_lookup_address: u32,
401 regs: &mut A::UnwindRegs,
402 cache: &mut Cache<A::UnwindRule, P>,
403 read_stack: &mut F,
404 ) -> Result<UnwindResult<A::UnwindRule>, UnwinderError>
405 where
406 F: FnMut(u64) -> Result<u64, ()>,
407 {
408 let is_first_frame = !address.is_return_address();
409 let unwind_result = match &*module.unwind_data {
410 #[cfg(feature = "macho")]
411 ModuleUnwindDataInternal::CompactUnwindInfoAndEhFrame {
412 unwind_info,
413 eh_frame,
414 stubs_svma: stubs,
415 stub_helper_svma: stub_helper,
416 base_addresses,
417 text_data,
418 } => {
419 // eprintln!("unwinding with cui and eh_frame in module {}", module.name);
420 let text_bytes = text_data.as_ref().and_then(|data| {
421 let offset_from_base =
422 u32::try_from(data.svma_range.start.checked_sub(module.base_svma)?).ok()?;
423 Some(TextBytes::new(offset_from_base, &data.bytes[..]))
424 });
425 let stubs_range = if let Some(stubs_range) = stubs {
426 (
427 (stubs_range.start - module.base_svma) as u32,
428 (stubs_range.end - module.base_svma) as u32,
429 )
430 } else {
431 (0, 0)
432 };
433 let stub_helper_range = if let Some(stub_helper_range) = stub_helper {
434 (
435 (stub_helper_range.start - module.base_svma) as u32,
436 (stub_helper_range.end - module.base_svma) as u32,
437 )
438 } else {
439 (0, 0)
440 };
441 let mut unwinder = CompactUnwindInfoUnwinder::<A>::new(
442 &unwind_info[..],
443 text_bytes,
444 stubs_range,
445 stub_helper_range,
446 );
447
448 let unwind_result = unwinder.unwind_frame(rel_lookup_address, is_first_frame)?;
449 match unwind_result {
450 CuiUnwindResult::ExecRule(rule) => UnwindResult::ExecRule(rule),
451 CuiUnwindResult::NeedDwarf(fde_offset) => {
452 let eh_frame_data =
453 eh_frame.as_deref().ok_or(UnwinderError::NoDwarfData)?;
454 let mut dwarf_unwinder = DwarfUnwinder::<_, A, _>::new(
455 EndianSlice::new(eh_frame_data, LittleEndian),
456 UnwindSectionType::EhFrame,
457 None,
458 &mut cache.gimli_unwind_context,
459 base_addresses.clone(),
460 module.base_svma,
461 );
462 dwarf_unwinder.unwind_frame_with_fde::<_, P::GimliEvaluationStorage<_>>(
463 regs,
464 is_first_frame,
465 rel_lookup_address,
466 fde_offset,
467 read_stack,
468 )?
469 }
470 }
471 }
472 ModuleUnwindDataInternal::EhFrameHdrAndEhFrame {
473 eh_frame_hdr,
474 eh_frame,
475 base_addresses,
476 } => {
477 let eh_frame_hdr_data = &eh_frame_hdr[..];
478 let mut dwarf_unwinder = DwarfUnwinder::<_, A, _>::new(
479 EndianSlice::new(eh_frame, LittleEndian),
480 UnwindSectionType::EhFrame,
481 Some(eh_frame_hdr_data),
482 &mut cache.gimli_unwind_context,
483 base_addresses.clone(),
484 module.base_svma,
485 );
486 let fde_offset = dwarf_unwinder
487 .get_fde_offset_for_relative_address(rel_lookup_address)
488 .ok_or(UnwinderError::EhFrameHdrCouldNotFindAddress)?;
489 dwarf_unwinder.unwind_frame_with_fde::<_, P::GimliEvaluationStorage<_>>(
490 regs,
491 is_first_frame,
492 rel_lookup_address,
493 fde_offset,
494 read_stack,
495 )?
496 }
497 ModuleUnwindDataInternal::DwarfCfiIndexAndEhFrame {
498 index,
499 eh_frame,
500 base_addresses,
501 } => {
502 let mut dwarf_unwinder = DwarfUnwinder::<_, A, _>::new(
503 EndianSlice::new(eh_frame, LittleEndian),
504 UnwindSectionType::EhFrame,
505 None,
506 &mut cache.gimli_unwind_context,
507 base_addresses.clone(),
508 module.base_svma,
509 );
510 let fde_offset = index
511 .fde_offset_for_relative_address(rel_lookup_address)
512 .ok_or(UnwinderError::DwarfCfiIndexCouldNotFindAddress)?;
513 dwarf_unwinder.unwind_frame_with_fde::<_, P::GimliEvaluationStorage<_>>(
514 regs,
515 is_first_frame,
516 rel_lookup_address,
517 fde_offset,
518 read_stack,
519 )?
520 }
521 ModuleUnwindDataInternal::DwarfCfiIndexAndDebugFrame {
522 index,
523 debug_frame,
524 base_addresses,
525 } => {
526 let mut dwarf_unwinder = DwarfUnwinder::<_, A, _>::new(
527 EndianSlice::new(debug_frame, LittleEndian),
528 UnwindSectionType::DebugFrame,
529 None,
530 &mut cache.gimli_unwind_context,
531 base_addresses.clone(),
532 module.base_svma,
533 );
534 let fde_offset = index
535 .fde_offset_for_relative_address(rel_lookup_address)
536 .ok_or(UnwinderError::DwarfCfiIndexCouldNotFindAddress)?;
537 dwarf_unwinder.unwind_frame_with_fde::<_, P::GimliEvaluationStorage<_>>(
538 regs,
539 is_first_frame,
540 rel_lookup_address,
541 fde_offset,
542 read_stack,
543 )?
544 }
545 #[cfg(feature = "pe")]
546 ModuleUnwindDataInternal::PeUnwindInfo {
547 pdata,
548 rdata,
549 xdata,
550 text,
551 } => <A as PeUnwinding>::unwind_frame(
552 crate::pe::PeSections {
553 pdata,
554 rdata: rdata.as_ref(),
555 xdata: xdata.as_ref(),
556 text: text.as_ref(),
557 },
558 rel_lookup_address,
559 regs,
560 is_first_frame,
561 read_stack,
562 )?,
563 ModuleUnwindDataInternal::None => return Err(UnwinderError::NoModuleUnwindData),
564 };
565 Ok(unwind_result)
566 }
567 }
568
569 /// The unwind data that should be used when unwinding addresses inside this module.
570 /// Unwind data describes how to recover register values of the caller frame.
571 ///
572 /// The type of unwind information you use depends on the platform and what's available
573 /// in the binary.
574 ///
575 /// Type arguments:
576 ///
577 /// - `D`: The type for unwind section data. This allows carrying owned data on the
578 /// module, e.g. `Vec<u8>`. But it could also be a wrapper around mapped memory from
579 /// a file or a different process, for example. It just needs to provide a slice of
580 /// bytes via its `Deref` implementation.
581 enum ModuleUnwindDataInternal<D> {
582 /// Used on macOS, with mach-O binaries. Compact unwind info is in the `__unwind_info`
583 /// section and is sometimes supplemented with DWARF CFI information in the `__eh_frame`
584 /// section. `__stubs` and `__stub_helper` ranges are used by the unwinder.
585 #[cfg(feature = "macho")]
586 CompactUnwindInfoAndEhFrame {
587 unwind_info: D,
588 eh_frame: Option<D>,
589 stubs_svma: Option<Range<u64>>,
590 stub_helper_svma: Option<Range<u64>>,
591 base_addresses: crate::dwarf::BaseAddresses,
592 text_data: Option<TextByteData<D>>,
593 },
594 /// Used with ELF binaries (Linux and friends), in the `.eh_frame_hdr` and `.eh_frame`
595 /// sections. Contains an index and DWARF CFI.
596 EhFrameHdrAndEhFrame {
597 eh_frame_hdr: D,
598 eh_frame: D,
599 base_addresses: crate::dwarf::BaseAddresses,
600 },
601 /// Used with ELF binaries (Linux and friends), in the `.eh_frame` section. Contains
602 /// DWARF CFI. We create a binary index for the FDEs when a module with this unwind
603 /// data type is added.
604 DwarfCfiIndexAndEhFrame {
605 index: DwarfCfiIndex,
606 eh_frame: D,
607 base_addresses: crate::dwarf::BaseAddresses,
608 },
609 /// Used with ELF binaries (Linux and friends), in the `.debug_frame` section. Contains
610 /// DWARF CFI. We create a binary index for the FDEs when a module with this unwind
611 /// data type is added.
612 DwarfCfiIndexAndDebugFrame {
613 index: DwarfCfiIndex,
614 debug_frame: D,
615 base_addresses: crate::dwarf::BaseAddresses,
616 },
617 /// Used with PE binaries (Windows).
618 #[cfg(feature = "pe")]
619 PeUnwindInfo {
620 pdata: D,
621 rdata: Option<DataAtRvaRange<D>>,
622 xdata: Option<DataAtRvaRange<D>>,
623 text: Option<DataAtRvaRange<D>>,
624 },
625 /// No unwind information is used. Unwinding in this module will use a fallback rule
626 /// (usually frame pointer unwinding).
627 None,
628 }
629
630 impl<D: Deref<Target = [u8]>> ModuleUnwindDataInternal<D> {
631 fn new(section_info: &mut impl ModuleSectionInfo<D>) -> Self {
632 use crate::dwarf::base_addresses_for_sections;
633
634 #[cfg(feature = "macho")]
635 if let Some(unwind_info) = section_info.section_data(b"__unwind_info") {
636 let eh_frame = section_info.section_data(b"__eh_frame");
637 let stubs = section_info.section_svma_range(b"__stubs");
638 let stub_helper = section_info.section_svma_range(b"__stub_helper");
639 // Get the bytes of the executable code (instructions).
640 //
641 // In mach-O objects, executable code is stored in the `__TEXT` segment, which contains
642 // multiple executable sections such as `__text`, `__stubs`, and `__stub_helper`. If we
643 // don't have the full `__TEXT` segment contents, we can fall back to the contents of
644 // just the `__text` section.
645 let text_data = if let (Some(bytes), Some(svma_range)) = (
646 section_info.segment_data(b"__TEXT"),
647 section_info.segment_svma_range(b"__TEXT"),
648 ) {
649 Some(TextByteData { bytes, svma_range })
650 } else if let (Some(bytes), Some(svma_range)) = (
651 section_info.section_data(b"__text"),
652 section_info.section_svma_range(b"__text"),
653 ) {
654 Some(TextByteData { bytes, svma_range })
655 } else {
656 None
657 };
658 return ModuleUnwindDataInternal::CompactUnwindInfoAndEhFrame {
659 unwind_info,
660 eh_frame,
661 stubs_svma: stubs,
662 stub_helper_svma: stub_helper,
663 base_addresses: base_addresses_for_sections(section_info),
664 text_data,
665 };
666 }
667
668 #[cfg(feature = "pe")]
669 if let Some(pdata) = section_info.section_data(b".pdata") {
670 let mut range_and_data = |name| {
671 let rva_range = section_info.section_svma_range(name).and_then(|range| {
672 Some(Range {
673 start: (range.start - section_info.base_svma()).try_into().ok()?,
674 end: (range.end - section_info.base_svma()).try_into().ok()?,
675 })
676 })?;
677 let data = section_info.section_data(name)?;
678 Some(DataAtRvaRange { data, rva_range })
679 };
680 return ModuleUnwindDataInternal::PeUnwindInfo {
681 pdata,
682 rdata: range_and_data(b".rdata"),
683 xdata: range_and_data(b".xdata"),
684 text: range_and_data(b".text"),
685 };
686 }
687
688 if let Some(eh_frame) = section_info
689 .section_data(b".eh_frame")
690 .or_else(|| section_info.section_data(b"__eh_frame"))
691 {
692 if let Some(eh_frame_hdr) = section_info
693 .section_data(b".eh_frame_hdr")
694 .or_else(|| section_info.section_data(b"__eh_frame_hdr"))
695 {
696 ModuleUnwindDataInternal::EhFrameHdrAndEhFrame {
697 eh_frame_hdr,
698 eh_frame,
699 base_addresses: base_addresses_for_sections(section_info),
700 }
701 } else {
702 match DwarfCfiIndex::try_new_eh_frame(&eh_frame, section_info) {
703 Ok(index) => ModuleUnwindDataInternal::DwarfCfiIndexAndEhFrame {
704 index,
705 eh_frame,
706 base_addresses: base_addresses_for_sections(section_info),
707 },
708 Err(_) => ModuleUnwindDataInternal::None,
709 }
710 }
711 } else if let Some(debug_frame) = section_info.section_data(b".debug_frame") {
712 match DwarfCfiIndex::try_new_debug_frame(&debug_frame, section_info) {
713 Ok(index) => ModuleUnwindDataInternal::DwarfCfiIndexAndDebugFrame {
714 index,
715 debug_frame,
716 base_addresses: base_addresses_for_sections(section_info),
717 },
718 Err(_) => ModuleUnwindDataInternal::None,
719 }
720 } else {
721 ModuleUnwindDataInternal::None
722 }
723 }
724 }
725
726 /// Used to supply raw instruction bytes to the unwinder, which uses it to analyze
727 /// instructions in order to provide high quality unwinding inside function prologues and
728 /// epilogues.
729 ///
730 /// This is only needed on macOS, because mach-O `__unwind_info` and `__eh_frame` only
731 /// cares about accuracy in function bodies, not in function prologues and epilogues.
732 ///
733 /// On Linux, compilers produce `.eh_frame` and `.debug_frame` which provides correct
734 /// unwind information for all instructions including those in function prologues and
735 /// epilogues, so instruction analysis is not needed.
736 ///
737 /// Type arguments:
738 ///
739 /// - `D`: The type for unwind section data. This allows carrying owned data on the
740 /// module, e.g. `Vec<u8>`. But it could also be a wrapper around mapped memory from
741 /// a file or a different process, for example. It just needs to provide a slice of
742 /// bytes via its `Deref` implementation.
743 #[cfg(feature = "macho")]
744 struct TextByteData<D> {
745 pub bytes: D,
746 pub svma_range: Range<u64>,
747 }
748
749 /// Information about a module that is loaded in a process. You might know this under a
750 /// different name, for example: (Shared) library, binary image, DSO ("Dynamic shared object")
751 ///
752 /// The unwinder needs to have an up-to-date list of modules so that it can match an
753 /// absolute address to the right module, and so that it can find that module's unwind
754 /// information.
755 ///
756 /// Type arguments:
757 ///
758 /// - `D`: The type for unwind section data. This allows carrying owned data on the
759 /// module, e.g. `Vec<u8>`. But it could also be a wrapper around mapped memory from
760 /// a file or a different process, for example. It just needs to provide a slice of
761 /// bytes via its `Deref` implementation.
762 pub struct Module<D> {
763 /// The name or file path of the module. Unused, it's just there for easier debugging.
764 #[allow(unused)]
765 name: String,
766 /// The address range where this module is mapped into the process.
767 avma_range: Range<u64>,
768 /// The base address of this module, in the process's address space. On Linux, the base
769 /// address can sometimes be different from the start address of the mapped range.
770 base_avma: u64,
771 /// The base address of this module, according to the module.
772 base_svma: u64,
773 /// The unwind data that should be used for unwinding addresses from this module.
774 unwind_data: Arc<ModuleUnwindDataInternal<D>>,
775 }
776
777 impl<D> Clone for Module<D> {
778 fn clone(&self) -> Self {
779 Self {
780 name: self.name.clone(),
781 avma_range: self.avma_range.clone(),
782 base_avma: self.base_avma,
783 base_svma: self.base_svma,
784 unwind_data: self.unwind_data.clone(),
785 }
786 }
787 }
788
789 /// Information about a module's sections (and segments).
790 ///
791 /// This trait is used as an interface to module information, and each function with `&mut self` is
792 /// called at most once with a particular argument (e.g., `section_data(b".text")` will be called
793 /// at most once, so it can move data out of the underlying type if desired).
794 ///
795 /// Type arguments:
796 ///
797 /// - `D`: The type for section data. This allows carrying owned data on the module, e.g.
798 /// `Vec<u8>`. But it could also be a wrapper around mapped memory from a file or a different
799 /// process, for example.
800 pub trait ModuleSectionInfo<D> {
801 /// Return the base address stated in the module.
802 ///
803 /// For mach-O objects, this is the vmaddr of the __TEXT segment. For ELF objects, this is
804 /// zero. For PE objects, this is the image base address.
805 ///
806 /// This is used to convert between SVMAs and relative addresses.
807 fn base_svma(&self) -> u64;
808
809 /// Get the given section's memory range, as stated in the module.
810 fn section_svma_range(&mut self, name: &[u8]) -> Option<Range<u64>>;
811
812 /// Get the given section's data. This will only be called once per section.
813 fn section_data(&mut self, name: &[u8]) -> Option<D>;
814
815 /// Get the given segment's memory range, as stated in the module.
816 fn segment_svma_range(&mut self, _name: &[u8]) -> Option<Range<u64>> {
817 None
818 }
819
820 /// Get the given segment's data. This will only be called once per segment.
821 fn segment_data(&mut self, _name: &[u8]) -> Option<D> {
822 None
823 }
824 }
825
826 /// Explicit addresses and data of various sections in the module. This implements
827 /// the `ModuleSectionInfo` trait.
828 ///
829 /// Unless otherwise stated, these are SVMAs, "stated virtual memory addresses", i.e. addresses as
830 /// stated in the object, as opposed to AVMAs, "actual virtual memory addresses", i.e. addresses in
831 /// the virtual memory of the profiled process.
832 ///
833 /// Code addresses inside a module's unwind information are usually written down as SVMAs,
834 /// or as relative addresses. For example, DWARF CFI can have code addresses expressed as
835 /// relative-to-.text addresses or as absolute SVMAs. And mach-O compact unwind info
836 /// contains addresses relative to the image base address.
837 #[derive(Clone, Debug, Default, PartialEq, Eq)]
838 pub struct ExplicitModuleSectionInfo<D> {
839 /// The image base address, as stated in the object. For mach-O objects, this is the
840 /// vmaddr of the `__TEXT` segment. For ELF objects, this is zero.
841 ///
842 /// This is used to convert between SVMAs and relative addresses.
843 pub base_svma: u64,
844 /// The address range of the `__text` or `.text` section. This is where most of the compiled
845 /// code is stored.
846 ///
847 /// This is used to detect whether we need to do instruction analysis for an address.
848 pub text_svma: Option<Range<u64>>,
849 /// The data of the `__text` or `.text` section. This is where most of the compiled code is
850 /// stored. For mach-O binaries, this does not need to be supplied if `text_segment` is supplied.
851 ///
852 /// This is used to handle function prologues and epilogues in some cases.
853 pub text: Option<D>,
854 /// The address range of the mach-O `__stubs` section. Contains small pieces of
855 /// executable code for calling imported functions. Code inside this section is not
856 /// covered by the unwind information in `__unwind_info`.
857 ///
858 /// This is used to exclude addresses in this section from incorrectly applying
859 /// `__unwind_info` opcodes. It is also used to infer unwind rules for the known
860 /// structure of stub functions.
861 pub stubs_svma: Option<Range<u64>>,
862 /// The address range of the mach-O `__stub_helper` section. Contains small pieces of
863 /// executable code for calling imported functions. Code inside this section is not
864 /// covered by the unwind information in `__unwind_info`.
865 ///
866 /// This is used to exclude addresses in this section from incorrectly applying
867 /// `__unwind_info` opcodes. It is also used to infer unwind rules for the known
868 /// structure of stub helper
869 /// functions.
870 pub stub_helper_svma: Option<Range<u64>>,
871 /// The address range of the `.got` section (Global Offset Table). This is used
872 /// during DWARF CFI processing, to resolve got-relative addresses.
873 pub got_svma: Option<Range<u64>>,
874 /// The data of the `__unwind_info` section of mach-O binaries.
875 pub unwind_info: Option<D>,
876 /// The address range of the `__eh_frame` or `.eh_frame` section. This is used during DWARF CFI
877 /// processing, to resolve eh_frame-relative addresses.
878 pub eh_frame_svma: Option<Range<u64>>,
879 /// The data of the `__eh_frame` or `.eh_frame` section. This is used during DWARF CFI
880 /// processing, to resolve eh_frame-relative addresses.
881 pub eh_frame: Option<D>,
882 /// The address range of the `.eh_frame_hdr` section. This is used during DWARF CFI processing,
883 /// to resolve eh_frame_hdr-relative addresses.
884 pub eh_frame_hdr_svma: Option<Range<u64>>,
885 /// The data of the `.eh_frame_hdr` section. This is used during DWARF CFI processing, to
886 /// resolve eh_frame_hdr-relative addresses.
887 pub eh_frame_hdr: Option<D>,
888 /// The data of the `.debug_frame` section. The related address range is not needed.
889 pub debug_frame: Option<D>,
890 /// The address range of the `__TEXT` segment of mach-O binaries, if available.
891 pub text_segment_svma: Option<Range<u64>>,
892 /// The data of the `__TEXT` segment of mach-O binaries, if available.
893 pub text_segment: Option<D>,
894 }
895
896 impl<D> ModuleSectionInfo<D> for ExplicitModuleSectionInfo<D>
897 where
898 D: Deref<Target = [u8]>,
899 {
900 fn base_svma(&self) -> u64 {
901 self.base_svma
902 }
903
904 fn section_svma_range(&mut self, name: &[u8]) -> Option<Range<u64>> {
905 match name {
906 b"__text" | b".text" => self.text_svma.clone(),
907 b"__stubs" => self.stubs_svma.clone(),
908 b"__stub_helper" => self.stub_helper_svma.clone(),
909 b"__eh_frame" | b".eh_frame" => self.eh_frame_svma.clone(),
910 b"__eh_frame_hdr" | b".eh_frame_hdr" => self.eh_frame_hdr_svma.clone(),
911 b"__got" | b".got" => self.got_svma.clone(),
912 _ => None,
913 }
914 }
915 fn section_data(&mut self, name: &[u8]) -> Option<D> {
916 match name {
917 b"__text" | b".text" => self.text.take(),
918 b"__unwind_info" => self.unwind_info.take(),
919 b"__eh_frame" | b".eh_frame" => self.eh_frame.take(),
920 b"__eh_frame_hdr" | b".eh_frame_hdr" => self.eh_frame_hdr.take(),
921 b"__debug_frame" | b".debug_frame" => self.debug_frame.take(),
922 _ => None,
923 }
924 }
925 fn segment_svma_range(&mut self, name: &[u8]) -> Option<Range<u64>> {
926 match name {
927 b"__TEXT" => self.text_segment_svma.clone(),
928 _ => None,
929 }
930 }
931 fn segment_data(&mut self, name: &[u8]) -> Option<D> {
932 match name {
933 b"__TEXT" => self.text_segment.take(),
934 _ => None,
935 }
936 }
937 }
938
939 impl<D: Deref<Target = [u8]>> Module<D> {
940 pub fn new(
941 name: String,
942 avma_range: core::ops::Range<u64>,
943 base_avma: u64,
944 mut section_info: impl ModuleSectionInfo<D>,
945 ) -> Self {
946 let unwind_data = ModuleUnwindDataInternal::new(&mut section_info);
947
948 Self {
949 name,
950 avma_range,
951 base_avma,
952 base_svma: section_info.base_svma(),
953 unwind_data: Arc::new(unwind_data),
954 }
955 }
956
957 pub fn avma_range(&self) -> core::ops::Range<u64> {
958 self.avma_range.clone()
959 }
960
961 pub fn base_avma(&self) -> u64 {
962 self.base_avma
963 }
964
965 pub fn name(&self) -> &str {
966 &self.name
967 }
968 }