1use std::borrow::Cow;
13use std::collections::BTreeSet;
14use std::error::Error;
15use std::fmt;
16use std::marker::PhantomData;
17use std::ops::Deref;
18use std::sync::Arc;
19
20use fallible_iterator::FallibleIterator;
21use gimli::read::{AttributeValue, Error as GimliError, Range};
22use gimli::{constants, AbbreviationsCacheStrategy, DwarfFileType, UnitSectionOffset};
23use once_cell::sync::OnceCell;
24use thiserror::Error;
25
26use symbolic_common::{AsSelf, Language, Name, NameMangling, SelfCell};
27
28use crate::base::*;
29use crate::function_builder::FunctionBuilder;
30#[cfg(feature = "macho")]
31use crate::macho::BcSymbolMap;
32use crate::sourcebundle::SourceFileDescriptor;
33
34#[cfg(not(feature = "macho"))]
37#[derive(Debug)]
38pub struct BcSymbolMap<'d> {
39 _marker: std::marker::PhantomData<&'d str>,
40}
41
42#[cfg(not(feature = "macho"))]
43impl<'d> BcSymbolMap<'d> {
44 pub(crate) fn resolve_opt(&self, _name: impl AsRef<[u8]>) -> Option<&str> {
45 None
46 }
47}
48
49#[doc(hidden)]
50pub use gimli;
51pub use gimli::RunTimeEndian as Endian;
52
53type Slice<'a> = gimli::read::EndianSlice<'a, Endian>;
54type RangeLists<'a> = gimli::read::RangeLists<Slice<'a>>;
55type Unit<'a> = gimli::read::Unit<Slice<'a>>;
56type DwarfInner<'a> = gimli::read::Dwarf<Slice<'a>>;
57
58type Die<'d, 'u> = gimli::read::DebuggingInformationEntry<'u, 'u, Slice<'d>, usize>;
59type Attribute<'a> = gimli::read::Attribute<Slice<'a>>;
60type UnitOffset = gimli::read::UnitOffset<usize>;
61type DebugInfoOffset = gimli::DebugInfoOffset<usize>;
62type EntriesRaw<'d, 'u> = gimli::EntriesRaw<'u, 'u, Slice<'d>>;
63
64type UnitHeader<'a> = gimli::read::UnitHeader<Slice<'a>>;
65type IncompleteLineNumberProgram<'a> = gimli::read::IncompleteLineProgram<Slice<'a>>;
66type LineNumberProgramHeader<'a> = gimli::read::LineProgramHeader<Slice<'a>>;
67type LineProgramFileEntry<'a> = gimli::read::FileEntry<Slice<'a>>;
68
69fn offset(addr: u64, offset: i64) -> u64 {
74 (addr as i64).wrapping_sub(offset) as u64
75}
76
77#[non_exhaustive]
79#[derive(Clone, Copy, Debug, PartialEq, Eq)]
80pub enum DwarfErrorKind {
81 InvalidUnitRef(usize),
83
84 InvalidFileRef(u64),
86
87 UnexpectedInline,
89
90 InvertedFunctionRange,
92
93 CorruptedData,
95}
96
97impl fmt::Display for DwarfErrorKind {
98 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
99 match self {
100 Self::InvalidUnitRef(offset) => {
101 write!(f, "compilation unit for offset {offset} does not exist")
102 }
103 Self::InvalidFileRef(id) => write!(f, "referenced file {id} does not exist"),
104 Self::UnexpectedInline => write!(f, "unexpected inline function without parent"),
105 Self::InvertedFunctionRange => write!(f, "function with inverted address range"),
106 Self::CorruptedData => write!(f, "corrupted dwarf debug data"),
107 }
108 }
109}
110
111#[derive(Debug, Error)]
113#[error("{kind}")]
114pub struct DwarfError {
115 kind: DwarfErrorKind,
116 #[source]
117 source: Option<Box<dyn Error + Send + Sync + 'static>>,
118}
119
120impl DwarfError {
121 fn new<E>(kind: DwarfErrorKind, source: E) -> Self
124 where
125 E: Into<Box<dyn Error + Send + Sync>>,
126 {
127 let source = Some(source.into());
128 Self { kind, source }
129 }
130
131 pub fn kind(&self) -> DwarfErrorKind {
133 self.kind
134 }
135}
136
137impl From<DwarfErrorKind> for DwarfError {
138 fn from(kind: DwarfErrorKind) -> Self {
139 Self { kind, source: None }
140 }
141}
142
143impl From<GimliError> for DwarfError {
144 fn from(e: GimliError) -> Self {
145 Self::new(DwarfErrorKind::CorruptedData, e)
146 }
147}
148
149#[derive(Clone)]
155pub struct DwarfSection<'data> {
156 pub address: u64,
158
159 pub offset: u64,
161
162 pub align: u64,
164
165 pub data: Cow<'data, [u8]>,
167}
168
169impl fmt::Debug for DwarfSection<'_> {
170 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
171 f.debug_struct("DwarfSection")
172 .field("address", &format_args!("{:#x}", self.address))
173 .field("offset", &format_args!("{:#x}", self.offset))
174 .field("align", &format_args!("{:#x}", self.align))
175 .field("len()", &self.data.len())
176 .finish()
177 }
178}
179
180pub trait Dwarf<'data> {
186 fn endianity(&self) -> Endian;
191
192 fn raw_section(&self, name: &str) -> Option<DwarfSection<'data>>;
201
202 fn section(&self, name: &str) -> Option<DwarfSection<'data>> {
211 self.raw_section(name)
212 }
213
214 fn has_section(&self, name: &str) -> bool {
220 self.raw_section(name).is_some()
221 }
222}
223
224#[derive(Debug)]
226struct DwarfRow {
227 address: u64,
228 file_index: u64,
229 line: Option<u64>,
230 size: Option<u64>,
231}
232
233#[derive(Debug)]
235struct DwarfSequence {
236 start: u64,
237 end: u64,
238 rows: Vec<DwarfRow>,
239}
240
241#[derive(Debug)]
243struct DwarfLineProgram<'d> {
244 header: LineNumberProgramHeader<'d>,
245 sequences: Vec<DwarfSequence>,
246}
247
248impl<'d> DwarfLineProgram<'d> {
249 fn prepare(program: IncompleteLineNumberProgram<'d>) -> Self {
250 let mut sequences = Vec::new();
251 let mut sequence_rows = Vec::<DwarfRow>::new();
252 let mut prev_address = 0;
253 let mut state_machine = program.rows();
254
255 while let Ok(Some((_, &program_row))) = state_machine.next_row() {
256 let address = program_row.address();
257
258 if address == 0 {
264 continue;
265 }
266
267 if let Some(last_row) = sequence_rows.last_mut() {
268 if address >= last_row.address {
269 last_row.size = Some(address - last_row.address);
270 }
271 }
272
273 if program_row.end_sequence() {
274 if !sequence_rows.is_empty() {
277 sequences.push(DwarfSequence {
278 start: sequence_rows[0].address,
279 end: if address < prev_address {
282 prev_address + 1
283 } else {
284 address
285 },
286 rows: std::mem::take(&mut sequence_rows),
287 });
288 }
289 prev_address = 0;
290 } else if address < prev_address {
291 } else {
298 let file_index = program_row.file_index();
299 let line = program_row.line().map(|v| v.get());
300 let mut duplicate = false;
301 if let Some(last_row) = sequence_rows.last_mut() {
302 if last_row.address == address {
303 last_row.file_index = file_index;
304 last_row.line = line;
305 duplicate = true;
306 }
307 }
308 if !duplicate {
309 sequence_rows.push(DwarfRow {
310 address,
311 file_index,
312 line,
313 size: None,
314 });
315 }
316 prev_address = address;
317 }
318 }
319
320 if !sequence_rows.is_empty() {
321 let start = sequence_rows[0].address;
324 let end = prev_address + 1;
325 sequences.push(DwarfSequence {
326 start,
327 end,
328 rows: sequence_rows,
329 });
330 }
331
332 sequences.sort_by_key(|x| x.start);
334
335 DwarfLineProgram {
336 header: state_machine.header().clone(),
337 sequences,
338 }
339 }
340
341 pub fn get_rows(&self, range: &Range) -> &[DwarfRow] {
342 for seq in &self.sequences {
343 if seq.end <= range.begin || seq.start > range.end {
344 continue;
345 }
346
347 let from = match seq.rows.binary_search_by_key(&range.begin, |x| x.address) {
348 Ok(idx) => idx,
349 Err(0) => continue,
350 Err(next_idx) => next_idx - 1,
351 };
352
353 let len = seq.rows[from..]
354 .binary_search_by_key(&range.end, |x| x.address)
355 .unwrap_or_else(|e| e);
356 return &seq.rows[from..from + len];
357 }
358 &[]
359 }
360}
361
362#[derive(Clone, Copy, Debug)]
364struct UnitRef<'d, 'a> {
365 info: &'a DwarfInfo<'d>,
366 unit: &'a Unit<'d>,
367}
368
369impl<'d> UnitRef<'d, '_> {
370 #[inline(always)]
372 fn slice_value(&self, value: AttributeValue<Slice<'d>>) -> Option<&'d [u8]> {
373 self.info
374 .attr_string(self.unit, value)
375 .map(|reader| reader.slice())
376 .ok()
377 }
378
379 #[inline(always)]
381 fn string_value(&self, value: AttributeValue<Slice<'d>>) -> Option<Cow<'d, str>> {
382 let slice = self.slice_value(value)?;
383 Some(String::from_utf8_lossy(slice))
384 }
385
386 fn resolve_reference<T, F>(&self, attr: Attribute<'d>, f: F) -> Result<Option<T>, DwarfError>
391 where
392 F: FnOnce(Self, &Die<'d, '_>) -> Result<Option<T>, DwarfError>,
393 {
394 let (unit, offset) = match attr.value() {
395 AttributeValue::UnitRef(offset) => (*self, offset),
396 AttributeValue::DebugInfoRef(offset) => self.info.find_unit_offset(offset)?,
397 _ => return Ok(None),
399 };
400
401 let mut entries = unit.unit.entries_at_offset(offset)?;
402 entries.next_entry()?;
403
404 if let Some(entry) = entries.current() {
405 f(unit, entry)
406 } else {
407 Ok(None)
408 }
409 }
410
411 fn offset(&self) -> UnitSectionOffset {
413 self.unit.header.offset()
414 }
415
416 fn resolve_function_name(
418 &self,
419 entry: &Die<'d, '_>,
420 language: Language,
421 bcsymbolmap: Option<&'d BcSymbolMap<'d>>,
422 prior_offset: Option<UnitOffset>,
423 ) -> Result<Option<Name<'d>>, DwarfError> {
424 let mut attrs = entry.attrs();
425 let mut fallback_name = None;
426 let mut reference_target = None;
427
428 while let Some(attr) = attrs.next()? {
429 match attr.name() {
430 constants::DW_AT_linkage_name | constants::DW_AT_MIPS_linkage_name => {
432 return Ok(self
433 .string_value(attr.value())
434 .map(|n| resolve_cow_name(bcsymbolmap, n))
435 .map(|n| Name::new(n, NameMangling::Mangled, language)));
436 }
437 constants::DW_AT_name => {
438 fallback_name = Some(attr);
439 }
440 constants::DW_AT_abstract_origin | constants::DW_AT_specification => {
441 reference_target = Some(attr);
442 }
443 _ => {}
444 }
445 }
446
447 if let Some(attr) = fallback_name {
448 return Ok(self
449 .string_value(attr.value())
450 .map(|n| resolve_cow_name(bcsymbolmap, n))
451 .map(|n| Name::new(n, NameMangling::Unmangled, language)));
452 }
453
454 if let Some(attr) = reference_target {
455 return self.resolve_reference(attr, |ref_unit, ref_entry| {
456 if let Some(prior) = prior_offset {
459 if self.offset() == ref_unit.offset() && prior == ref_entry.offset() {
460 return Ok(None);
461 }
462 }
463
464 if self.offset() != ref_unit.offset() || entry.offset() != ref_entry.offset() {
465 ref_unit.resolve_function_name(
466 ref_entry,
467 language,
468 bcsymbolmap,
469 Some(entry.offset()),
470 )
471 } else {
472 Ok(None)
473 }
474 });
475 }
476
477 Ok(None)
478 }
479}
480
481#[derive(Debug)]
483struct DwarfUnit<'d, 'a> {
484 inner: UnitRef<'d, 'a>,
485 bcsymbolmap: Option<&'d BcSymbolMap<'d>>,
486 language: Language,
487 line_program: Option<DwarfLineProgram<'d>>,
488 prefer_dwarf_names: bool,
489}
490
491impl<'d, 'a> DwarfUnit<'d, 'a> {
492 fn from_unit(
494 unit: &'a Unit<'d>,
495 info: &'a DwarfInfo<'d>,
496 bcsymbolmap: Option<&'d BcSymbolMap<'d>>,
497 ) -> Result<Option<Self>, DwarfError> {
498 let inner = UnitRef { info, unit };
499 let mut entries = unit.entries();
500 let entry = match entries.next_dfs()? {
501 Some((_, entry)) => entry,
502 None => return Err(gimli::read::Error::MissingUnitDie.into()),
503 };
504
505 if info.kind != ObjectKind::Relocatable
510 && unit.low_pc == 0
511 && entry.attr(constants::DW_AT_ranges)?.is_none()
512 {
513 return Ok(None);
514 }
515
516 let language = match entry.attr_value(constants::DW_AT_language)? {
517 Some(AttributeValue::Language(lang)) => language_from_dwarf(lang),
518 _ => Language::Unknown,
519 };
520
521 let line_program = unit
522 .line_program
523 .as_ref()
524 .map(|program| DwarfLineProgram::prepare(program.clone()));
525
526 let producer = entry
530 .attr_value(constants::DW_AT_producer)?
531 .and_then(|av| av.string_value(&info.inner.debug_str));
532
533 let prefer_dwarf_names = producer.as_deref() == Some(b"Dart VM");
536
537 Ok(Some(DwarfUnit {
538 inner,
539 bcsymbolmap,
540 language,
541 line_program,
542 prefer_dwarf_names,
543 }))
544 }
545
546 fn compilation_dir(&self) -> &'d [u8] {
548 match self.inner.unit.comp_dir {
549 Some(ref dir) => resolve_byte_name(self.bcsymbolmap, dir.slice()),
550 None => &[],
551 }
552 }
553
554 fn parse_ranges<'r>(
560 &self,
561 entries: &mut EntriesRaw<'d, '_>,
562 abbrev: &gimli::Abbreviation,
563 range_buf: &'r mut Vec<Range>,
564 ) -> Result<(&'r mut Vec<Range>, CallLocation), DwarfError> {
565 range_buf.clear();
566
567 let mut call_line = None;
568 let mut call_file = None;
569 let mut low_pc = None;
570 let mut high_pc = None;
571 let mut high_pc_rel = None;
572
573 let kind = self.inner.info.kind;
574
575 for spec in abbrev.attributes() {
576 let attr = entries.read_attribute(*spec)?;
577 match attr.name() {
578 constants::DW_AT_low_pc => match attr.value() {
579 AttributeValue::Addr(addr) => low_pc = Some(addr),
580 AttributeValue::DebugAddrIndex(index) => {
581 low_pc = Some(self.inner.info.address(self.inner.unit, index)?)
582 }
583 _ => return Err(GimliError::UnsupportedAttributeForm.into()),
584 },
585 constants::DW_AT_high_pc => match attr.value() {
586 AttributeValue::Addr(addr) => high_pc = Some(addr),
587 AttributeValue::DebugAddrIndex(index) => {
588 high_pc = Some(self.inner.info.address(self.inner.unit, index)?)
589 }
590 AttributeValue::Udata(size) => high_pc_rel = Some(size),
591 _ => return Err(GimliError::UnsupportedAttributeForm.into()),
592 },
593 constants::DW_AT_call_line => match attr.value() {
594 AttributeValue::Udata(line) => call_line = Some(line),
595 _ => return Err(GimliError::UnsupportedAttributeForm.into()),
596 },
597 constants::DW_AT_call_file => match attr.value() {
598 AttributeValue::FileIndex(file) => call_file = Some(file),
599 _ => return Err(GimliError::UnsupportedAttributeForm.into()),
600 },
601 constants::DW_AT_ranges
602 | constants::DW_AT_rnglists_base
603 | constants::DW_AT_start_scope => {
604 match self.inner.info.attr_ranges(self.inner.unit, attr.value())? {
605 Some(mut ranges) => {
606 while let Some(range) = match ranges.next() {
607 Ok(range) => range,
608 Err(gimli::Error::InvalidAddressRange) => None,
614 Err(err) => {
615 return Err(err.into());
616 }
617 } {
618 if range.begin > 0 || kind == ObjectKind::Relocatable {
621 range_buf.push(range);
622 }
623 }
624 }
625 None => continue,
626 }
627 }
628 _ => continue,
629 }
630 }
631
632 let call_location = CallLocation {
633 call_file,
634 call_line,
635 };
636
637 if range_buf.is_empty() {
638 if let Some(range) = Self::convert_pc_range(low_pc, high_pc, high_pc_rel, kind)? {
639 range_buf.push(range);
640 }
641 }
642
643 Ok((range_buf, call_location))
644 }
645
646 fn convert_pc_range(
647 low_pc: Option<u64>,
648 high_pc: Option<u64>,
649 high_pc_rel: Option<u64>,
650 kind: ObjectKind,
651 ) -> Result<Option<Range>, DwarfError> {
652 let low_pc = match low_pc {
657 Some(low_pc) if low_pc != 0 || kind == ObjectKind::Relocatable => low_pc,
658 _ => return Ok(None),
659 };
660
661 let high_pc = match (high_pc, high_pc_rel) {
662 (Some(high_pc), _) => high_pc,
663 (_, Some(high_pc_rel)) => low_pc.wrapping_add(high_pc_rel),
664 _ => return Ok(None),
665 };
666
667 if low_pc == high_pc {
668 return Ok(None);
671 }
672
673 if low_pc == u64::MAX || low_pc == u64::MAX - 1 {
674 return Ok(None);
677 }
678
679 if low_pc > high_pc {
680 return Err(DwarfErrorKind::InvertedFunctionRange.into());
681 }
682
683 Ok(Some(Range {
684 begin: low_pc,
685 end: high_pc,
686 }))
687 }
688
689 fn file_info(
691 &self,
692 line_program: &LineNumberProgramHeader<'d>,
693 file: &LineProgramFileEntry<'d>,
694 ) -> FileInfo<'d> {
695 FileInfo::new(
696 Cow::Borrowed(resolve_byte_name(
697 self.bcsymbolmap,
698 file.directory(line_program)
699 .and_then(|attr| self.inner.slice_value(attr))
700 .unwrap_or_default(),
701 )),
702 Cow::Borrowed(resolve_byte_name(
703 self.bcsymbolmap,
704 self.inner.slice_value(file.path_name()).unwrap_or_default(),
705 )),
706 )
707 }
708
709 fn resolve_file(&self, file_id: u64) -> Option<FileInfo<'d>> {
711 let line_program = match self.line_program {
712 Some(ref program) => &program.header,
713 None => return None,
714 };
715
716 line_program
717 .file(file_id)
718 .map(|file| self.file_info(line_program, file))
719 }
720
721 fn resolve_symbol_name(&self, address: u64) -> Option<Name<'d>> {
723 let symbol = self.inner.info.symbol_map.lookup_exact(address)?;
724 let name = resolve_cow_name(self.bcsymbolmap, symbol.name.clone()?);
725 Some(Name::new(name, NameMangling::Mangled, self.language))
726 }
727
728 fn resolve_dwarf_name(&self, entry: &Die<'d, '_>) -> Option<Name<'d>> {
730 self.inner
731 .resolve_function_name(entry, self.language, self.bcsymbolmap, None)
732 .ok()
733 .flatten()
734 }
735
736 fn parse_functions(
738 &self,
739 depth: isize,
740 entries: &mut EntriesRaw<'d, '_>,
741 output: &mut FunctionsOutput<'_, 'd>,
742 ) -> Result<(), DwarfError> {
743 while !entries.is_empty() {
744 let dw_die_offset = entries.next_offset();
745 let next_depth = entries.next_depth();
746 if next_depth <= depth {
747 return Ok(());
748 }
749 if let Some(abbrev) = entries.read_abbreviation()? {
750 if abbrev.tag() == constants::DW_TAG_subprogram {
751 self.parse_function(dw_die_offset, next_depth, entries, abbrev, output)?;
752 } else {
753 entries.skip_attributes(abbrev.attributes())?;
754 }
755 }
756 }
757 Ok(())
758 }
759
760 fn parse_function(
770 &self,
771 dw_die_offset: gimli::UnitOffset<usize>,
772 depth: isize,
773 entries: &mut EntriesRaw<'d, '_>,
774 abbrev: &gimli::Abbreviation,
775 output: &mut FunctionsOutput<'_, 'd>,
776 ) -> Result<(), DwarfError> {
777 let (ranges, _) = self.parse_ranges(entries, abbrev, &mut output.range_buf)?;
778
779 let seen_ranges = &mut *output.seen_ranges;
780 ranges.retain(|range| {
781 if range.begin > range.end {
783 return false;
784 }
785
786 let address = offset(range.begin, self.inner.info.address_offset);
795 let size = range.end - range.begin;
796
797 seen_ranges.insert((address, size))
798 });
799
800 if ranges.is_empty() {
808 return self.parse_functions(depth, entries, output);
809 }
810
811 let symbol_name = if self.prefer_dwarf_names {
818 None
819 } else {
820 let first_range_begin = ranges.iter().map(|range| range.begin).min().unwrap();
821 let function_address = offset(first_range_begin, self.inner.info.address_offset);
822 self.resolve_symbol_name(function_address)
823 };
824
825 let name = symbol_name
826 .or_else(|| self.resolve_dwarf_name(&self.inner.unit.entry(dw_die_offset).unwrap()))
827 .unwrap_or_else(|| Name::new("", NameMangling::Unmangled, self.language));
828
829 let mut builders: Vec<(Range, FunctionBuilder)> = ranges
832 .iter()
833 .map(|range| {
834 let address = offset(range.begin, self.inner.info.address_offset);
835 let size = range.end - range.begin;
836 (
837 *range,
838 FunctionBuilder::new(name.clone(), self.compilation_dir(), address, size),
839 )
840 })
841 .collect();
842
843 self.parse_function_children(depth, 0, entries, &mut builders, output)?;
844
845 if let Some(line_program) = &self.line_program {
846 for (range, builder) in &mut builders {
847 for row in line_program.get_rows(range) {
848 let address = offset(row.address, self.inner.info.address_offset);
849 let size = row.size;
850 let file = self.resolve_file(row.file_index).unwrap_or_default();
851 let line = row.line.unwrap_or(0);
852 builder.add_leaf_line(address, size, file, line);
853 }
854 }
855 }
856
857 for (_range, builder) in builders {
858 output.functions.push(builder.finish());
859 }
860
861 Ok(())
862 }
863
864 fn parse_function_children(
866 &self,
867 depth: isize,
868 inline_depth: u32,
869 entries: &mut EntriesRaw<'d, '_>,
870 builders: &mut [(Range, FunctionBuilder<'d>)],
871 output: &mut FunctionsOutput<'_, 'd>,
872 ) -> Result<(), DwarfError> {
873 while !entries.is_empty() {
874 let dw_die_offset = entries.next_offset();
875 let next_depth = entries.next_depth();
876 if next_depth <= depth {
877 return Ok(());
878 }
879 let abbrev = match entries.read_abbreviation()? {
880 Some(abbrev) => abbrev,
881 None => continue,
882 };
883 match abbrev.tag() {
884 constants::DW_TAG_subprogram => {
885 self.parse_function(dw_die_offset, next_depth, entries, abbrev, output)?;
886 }
887 constants::DW_TAG_inlined_subroutine => {
888 self.parse_inlinee(
889 dw_die_offset,
890 next_depth,
891 inline_depth,
892 entries,
893 abbrev,
894 builders,
895 output,
896 )?;
897 }
898 _ => {
899 entries.skip_attributes(abbrev.attributes())?;
900 }
901 }
902 }
903 Ok(())
904 }
905
906 #[allow(clippy::too_many_arguments)]
915 fn parse_inlinee(
916 &self,
917 dw_die_offset: gimli::UnitOffset<usize>,
918 depth: isize,
919 inline_depth: u32,
920 entries: &mut EntriesRaw<'d, '_>,
921 abbrev: &gimli::Abbreviation,
922 builders: &mut [(Range, FunctionBuilder<'d>)],
923 output: &mut FunctionsOutput<'_, 'd>,
924 ) -> Result<(), DwarfError> {
925 let (ranges, call_location) = self.parse_ranges(entries, abbrev, &mut output.range_buf)?;
926
927 ranges.retain(|range| range.end > range.begin);
928
929 if ranges.is_empty() {
937 return self.parse_functions(depth, entries, output);
938 }
939
940 let name = self
941 .resolve_dwarf_name(&self.inner.unit.entry(dw_die_offset).unwrap())
942 .unwrap_or_else(|| Name::new("", NameMangling::Unmangled, self.language));
943
944 let call_file = call_location
945 .call_file
946 .and_then(|i| self.resolve_file(i))
947 .unwrap_or_default();
948 let call_line = call_location.call_line.unwrap_or(0);
949
950 for range in ranges.iter() {
952 let builder = match builders.iter_mut().find(|(outer_range, _builder)| {
955 range.begin >= outer_range.begin && range.begin < outer_range.end
956 }) {
957 Some((_outer_range, builder)) => builder,
958 None => continue,
959 };
960
961 let address = offset(range.begin, self.inner.info.address_offset);
962 let size = range.end - range.begin;
963 builder.add_inlinee(
964 inline_depth,
965 name.clone(),
966 address,
967 size,
968 call_file.clone(),
969 call_line,
970 );
971 }
972
973 self.parse_function_children(depth, inline_depth + 1, entries, builders, output)
974 }
975
976 fn functions(
978 &self,
979 seen_ranges: &mut BTreeSet<(u64, u64)>,
980 ) -> Result<Vec<Function<'d>>, DwarfError> {
981 let mut entries = self.inner.unit.entries_raw(None)?;
982 let mut output = FunctionsOutput::with_seen_ranges(seen_ranges);
983 self.parse_functions(-1, &mut entries, &mut output)?;
984 Ok(output.functions)
985 }
986}
987
988struct FunctionsOutput<'a, 'd> {
990 pub functions: Vec<Function<'d>>,
993 pub range_buf: Vec<Range>,
995 pub seen_ranges: &'a mut BTreeSet<(u64, u64)>,
997}
998
999impl<'a> FunctionsOutput<'a, '_> {
1000 pub fn with_seen_ranges(seen_ranges: &'a mut BTreeSet<(u64, u64)>) -> Self {
1001 Self {
1002 functions: Vec::new(),
1003 range_buf: Vec::new(),
1004 seen_ranges,
1005 }
1006 }
1007}
1008
1009#[derive(Debug, Default, Clone, Copy)]
1011struct CallLocation {
1012 pub call_file: Option<u64>,
1013 pub call_line: Option<u64>,
1014}
1015
1016fn language_from_dwarf(language: gimli::DwLang) -> Language {
1018 match language {
1019 constants::DW_LANG_C => Language::C,
1020 constants::DW_LANG_C11 => Language::C,
1021 constants::DW_LANG_C89 => Language::C,
1022 constants::DW_LANG_C99 => Language::C,
1023 constants::DW_LANG_C_plus_plus => Language::Cpp,
1024 constants::DW_LANG_C_plus_plus_03 => Language::Cpp,
1025 constants::DW_LANG_C_plus_plus_11 => Language::Cpp,
1026 constants::DW_LANG_C_plus_plus_14 => Language::Cpp,
1027 constants::DW_LANG_D => Language::D,
1028 constants::DW_LANG_Go => Language::Go,
1029 constants::DW_LANG_ObjC => Language::ObjC,
1030 constants::DW_LANG_ObjC_plus_plus => Language::ObjCpp,
1031 constants::DW_LANG_Rust => Language::Rust,
1032 constants::DW_LANG_Swift => Language::Swift,
1033 _ => Language::Unknown,
1034 }
1035}
1036
1037struct DwarfSectionData<'data, S> {
1039 data: Cow<'data, [u8]>,
1040 endianity: Endian,
1041 _ph: PhantomData<S>,
1042}
1043
1044impl<'data, S> DwarfSectionData<'data, S>
1045where
1046 S: gimli::read::Section<Slice<'data>>,
1047{
1048 fn load<D>(dwarf: &D) -> Self
1050 where
1051 D: Dwarf<'data>,
1052 {
1053 DwarfSectionData {
1054 data: dwarf
1055 .section(&S::section_name()[1..])
1056 .map(|section| section.data)
1057 .unwrap_or_default(),
1058 endianity: dwarf.endianity(),
1059 _ph: PhantomData,
1060 }
1061 }
1062
1063 fn to_gimli(&'data self) -> S {
1065 S::from(Slice::new(&self.data, self.endianity))
1066 }
1067}
1068
1069impl<'d, S> fmt::Debug for DwarfSectionData<'d, S>
1070where
1071 S: gimli::read::Section<Slice<'d>>,
1072{
1073 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1074 let owned = match self.data {
1075 Cow::Owned(_) => true,
1076 Cow::Borrowed(_) => false,
1077 };
1078
1079 f.debug_struct("DwarfSectionData")
1080 .field("type", &S::section_name())
1081 .field("endianity", &self.endianity)
1082 .field("len()", &self.data.len())
1083 .field("owned()", &owned)
1084 .finish()
1085 }
1086}
1087
1088struct DwarfSections<'data> {
1090 debug_abbrev: DwarfSectionData<'data, gimli::read::DebugAbbrev<Slice<'data>>>,
1091 debug_addr: DwarfSectionData<'data, gimli::read::DebugAddr<Slice<'data>>>,
1092 debug_aranges: DwarfSectionData<'data, gimli::read::DebugAranges<Slice<'data>>>,
1093 debug_info: DwarfSectionData<'data, gimli::read::DebugInfo<Slice<'data>>>,
1094 debug_line: DwarfSectionData<'data, gimli::read::DebugLine<Slice<'data>>>,
1095 debug_line_str: DwarfSectionData<'data, gimli::read::DebugLineStr<Slice<'data>>>,
1096 debug_str: DwarfSectionData<'data, gimli::read::DebugStr<Slice<'data>>>,
1097 debug_str_offsets: DwarfSectionData<'data, gimli::read::DebugStrOffsets<Slice<'data>>>,
1098 debug_ranges: DwarfSectionData<'data, gimli::read::DebugRanges<Slice<'data>>>,
1099 debug_rnglists: DwarfSectionData<'data, gimli::read::DebugRngLists<Slice<'data>>>,
1100 debug_macinfo: DwarfSectionData<'data, gimli::read::DebugMacinfo<Slice<'data>>>,
1101 debug_macro: DwarfSectionData<'data, gimli::read::DebugMacro<Slice<'data>>>,
1102}
1103
1104impl<'data> DwarfSections<'data> {
1105 fn from_dwarf<D>(dwarf: &D) -> Self
1107 where
1108 D: Dwarf<'data>,
1109 {
1110 DwarfSections {
1111 debug_abbrev: DwarfSectionData::load(dwarf),
1112 debug_addr: DwarfSectionData::load(dwarf),
1113 debug_aranges: DwarfSectionData::load(dwarf),
1114 debug_info: DwarfSectionData::load(dwarf),
1115 debug_line: DwarfSectionData::load(dwarf),
1116 debug_line_str: DwarfSectionData::load(dwarf),
1117 debug_str: DwarfSectionData::load(dwarf),
1118 debug_str_offsets: DwarfSectionData::load(dwarf),
1119 debug_ranges: DwarfSectionData::load(dwarf),
1120 debug_rnglists: DwarfSectionData::load(dwarf),
1121 debug_macinfo: DwarfSectionData::load(dwarf),
1122 debug_macro: DwarfSectionData::load(dwarf),
1123 }
1124 }
1125}
1126
1127struct DwarfInfo<'data> {
1128 inner: DwarfInner<'data>,
1129 headers: Vec<UnitHeader<'data>>,
1130 units: Vec<OnceCell<Option<Unit<'data>>>>,
1131 symbol_map: SymbolMap<'data>,
1132 address_offset: i64,
1133 kind: ObjectKind,
1134}
1135
1136impl<'d> Deref for DwarfInfo<'d> {
1137 type Target = DwarfInner<'d>;
1138
1139 fn deref(&self) -> &Self::Target {
1140 &self.inner
1141 }
1142}
1143
1144impl<'d> DwarfInfo<'d> {
1145 pub fn parse(
1147 sections: &'d DwarfSections<'d>,
1148 symbol_map: SymbolMap<'d>,
1149 address_offset: i64,
1150 kind: ObjectKind,
1151 ) -> Result<Self, DwarfError> {
1152 let mut inner = gimli::read::Dwarf {
1153 abbreviations_cache: Default::default(),
1154 debug_abbrev: sections.debug_abbrev.to_gimli(),
1155 debug_addr: sections.debug_addr.to_gimli(),
1156 debug_aranges: sections.debug_aranges.to_gimli(),
1157 debug_info: sections.debug_info.to_gimli(),
1158 debug_line: sections.debug_line.to_gimli(),
1159 debug_line_str: sections.debug_line_str.to_gimli(),
1160 debug_str: sections.debug_str.to_gimli(),
1161 debug_str_offsets: sections.debug_str_offsets.to_gimli(),
1162 debug_types: Default::default(),
1163 debug_macinfo: sections.debug_macinfo.to_gimli(),
1164 debug_macro: sections.debug_macro.to_gimli(),
1165 locations: Default::default(),
1166 ranges: RangeLists::new(
1167 sections.debug_ranges.to_gimli(),
1168 sections.debug_rnglists.to_gimli(),
1169 ),
1170 file_type: DwarfFileType::Main,
1171 sup: Default::default(),
1172 };
1173 inner.populate_abbreviations_cache(AbbreviationsCacheStrategy::Duplicates);
1174
1175 let headers = inner.units().collect::<Vec<_>>()?;
1177 let units = headers.iter().map(|_| OnceCell::new()).collect();
1178
1179 Ok(DwarfInfo {
1180 inner,
1181 headers,
1182 units,
1183 symbol_map,
1184 address_offset,
1185 kind,
1186 })
1187 }
1188
1189 fn get_unit(&self, index: usize) -> Result<Option<&Unit<'d>>, DwarfError> {
1191 let cell = match self.units.get(index) {
1193 Some(cell) => cell,
1194 None => return Ok(None),
1195 };
1196
1197 let unit_opt = cell.get_or_try_init(|| {
1198 let header = self.headers[index];
1203 match self.inner.unit(header) {
1204 Ok(unit) => Ok(Some(unit)),
1205 Err(gimli::read::Error::MissingUnitDie) => Ok(None),
1206 Err(error) => Err(DwarfError::from(error)),
1207 }
1208 })?;
1209
1210 Ok(unit_opt.as_ref())
1211 }
1212
1213 fn find_unit_offset(
1215 &self,
1216 offset: DebugInfoOffset,
1217 ) -> Result<(UnitRef<'d, '_>, UnitOffset), DwarfError> {
1218 let section_offset = UnitSectionOffset::DebugInfoOffset(offset);
1219 let search_result = self
1220 .headers
1221 .binary_search_by_key(§ion_offset, UnitHeader::offset);
1222
1223 let index = match search_result {
1224 Ok(index) => index,
1225 Err(0) => return Err(DwarfErrorKind::InvalidUnitRef(offset.0).into()),
1226 Err(next_index) => next_index - 1,
1227 };
1228
1229 if let Some(unit) = self.get_unit(index)? {
1230 if let Some(unit_offset) = section_offset.to_unit_offset(unit) {
1231 return Ok((UnitRef { unit, info: self }, unit_offset));
1232 }
1233 }
1234
1235 Err(DwarfErrorKind::InvalidUnitRef(offset.0).into())
1236 }
1237
1238 fn units(&'d self, bcsymbolmap: Option<&'d BcSymbolMap<'d>>) -> DwarfUnitIterator<'d> {
1240 DwarfUnitIterator {
1241 info: self,
1242 bcsymbolmap,
1243 index: 0,
1244 }
1245 }
1246}
1247
1248impl<'slf, 'd: 'slf> AsSelf<'slf> for DwarfInfo<'d> {
1249 type Ref = DwarfInfo<'slf>;
1250
1251 fn as_self(&'slf self) -> &'slf Self::Ref {
1252 unsafe { std::mem::transmute(self) }
1253 }
1254}
1255
1256impl fmt::Debug for DwarfInfo<'_> {
1257 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1258 f.debug_struct("DwarfInfo")
1259 .field("headers", &self.headers)
1260 .field("symbol_map", &self.symbol_map)
1261 .field("address_offset", &self.address_offset)
1262 .finish()
1263 }
1264}
1265
1266struct DwarfUnitIterator<'s> {
1268 info: &'s DwarfInfo<'s>,
1269 bcsymbolmap: Option<&'s BcSymbolMap<'s>>,
1270 index: usize,
1271}
1272
1273impl<'s> Iterator for DwarfUnitIterator<'s> {
1274 type Item = Result<DwarfUnit<'s, 's>, DwarfError>;
1275
1276 fn next(&mut self) -> Option<Self::Item> {
1277 while self.index < self.info.headers.len() {
1278 let result = self.info.get_unit(self.index);
1279 self.index += 1;
1280
1281 let unit = match result {
1282 Ok(Some(unit)) => unit,
1283 Ok(None) => continue,
1284 Err(error) => return Some(Err(error)),
1285 };
1286
1287 match DwarfUnit::from_unit(unit, self.info, self.bcsymbolmap) {
1288 Ok(Some(unit)) => return Some(Ok(unit)),
1289 Ok(None) => continue,
1290 Err(error) => return Some(Err(error)),
1291 }
1292 }
1293
1294 None
1295 }
1296}
1297
1298impl std::iter::FusedIterator for DwarfUnitIterator<'_> {}
1299
1300pub struct DwarfDebugSession<'data> {
1302 cell: SelfCell<Box<DwarfSections<'data>>, DwarfInfo<'data>>,
1303 bcsymbolmap: Option<Arc<BcSymbolMap<'data>>>,
1304}
1305
1306impl<'data> DwarfDebugSession<'data> {
1307 pub fn parse<D>(
1309 dwarf: &D,
1310 symbol_map: SymbolMap<'data>,
1311 address_offset: i64,
1312 kind: ObjectKind,
1313 ) -> Result<Self, DwarfError>
1314 where
1315 D: Dwarf<'data>,
1316 {
1317 let sections = DwarfSections::from_dwarf(dwarf);
1318 let cell = SelfCell::try_new(Box::new(sections), |sections| {
1319 DwarfInfo::parse(unsafe { &*sections }, symbol_map, address_offset, kind)
1320 })?;
1321
1322 Ok(DwarfDebugSession {
1323 cell,
1324 bcsymbolmap: None,
1325 })
1326 }
1327
1328 #[cfg(feature = "macho")]
1333 pub(crate) fn load_symbolmap(&mut self, symbolmap: Option<Arc<BcSymbolMap<'data>>>) {
1334 self.bcsymbolmap = symbolmap;
1335 }
1336
1337 pub fn files(&self) -> DwarfFileIterator<'_> {
1339 DwarfFileIterator {
1340 units: self.cell.get().units(self.bcsymbolmap.as_deref()),
1341 files: DwarfUnitFileIterator::default(),
1342 finished: false,
1343 }
1344 }
1345
1346 pub fn functions(&self) -> DwarfFunctionIterator<'_> {
1348 DwarfFunctionIterator {
1349 units: self.cell.get().units(self.bcsymbolmap.as_deref()),
1350 functions: Vec::new().into_iter(),
1351 seen_ranges: BTreeSet::new(),
1352 finished: false,
1353 }
1354 }
1355
1356 pub fn source_by_path(
1358 &self,
1359 _path: &str,
1360 ) -> Result<Option<SourceFileDescriptor<'_>>, DwarfError> {
1361 Ok(None)
1362 }
1363}
1364
1365impl<'session> DebugSession<'session> for DwarfDebugSession<'_> {
1366 type Error = DwarfError;
1367 type FunctionIterator = DwarfFunctionIterator<'session>;
1368 type FileIterator = DwarfFileIterator<'session>;
1369
1370 fn functions(&'session self) -> Self::FunctionIterator {
1371 self.functions()
1372 }
1373
1374 fn files(&'session self) -> Self::FileIterator {
1375 self.files()
1376 }
1377
1378 fn source_by_path(&self, path: &str) -> Result<Option<SourceFileDescriptor<'_>>, Self::Error> {
1379 self.source_by_path(path)
1380 }
1381}
1382
1383#[derive(Debug, Default)]
1384struct DwarfUnitFileIterator<'s> {
1385 unit: Option<DwarfUnit<'s, 's>>,
1386 index: usize,
1387}
1388
1389impl<'s> Iterator for DwarfUnitFileIterator<'s> {
1390 type Item = FileEntry<'s>;
1391
1392 fn next(&mut self) -> Option<Self::Item> {
1393 let unit = self.unit.as_ref()?;
1394 let line_program = unit.line_program.as_ref().map(|p| &p.header)?;
1395 let file = line_program.file_names().get(self.index)?;
1396
1397 self.index += 1;
1398
1399 Some(FileEntry::new(
1400 Cow::Borrowed(unit.compilation_dir()),
1401 unit.file_info(line_program, file),
1402 ))
1403 }
1404}
1405
1406fn resolve_byte_name<'s>(bcsymbolmap: Option<&'s BcSymbolMap<'s>>, s: &'s [u8]) -> &'s [u8] {
1407 bcsymbolmap
1408 .and_then(|b| b.resolve_opt(s))
1409 .map(AsRef::as_ref)
1410 .unwrap_or(s)
1411}
1412
1413fn resolve_cow_name<'s>(bcsymbolmap: Option<&'s BcSymbolMap<'s>>, s: Cow<'s, str>) -> Cow<'s, str> {
1414 bcsymbolmap
1415 .and_then(|b| b.resolve_opt(s.as_bytes()))
1416 .map(Cow::Borrowed)
1417 .unwrap_or(s)
1418}
1419
1420pub struct DwarfFileIterator<'s> {
1422 units: DwarfUnitIterator<'s>,
1423 files: DwarfUnitFileIterator<'s>,
1424 finished: bool,
1425}
1426
1427impl<'s> Iterator for DwarfFileIterator<'s> {
1428 type Item = Result<FileEntry<'s>, DwarfError>;
1429
1430 fn next(&mut self) -> Option<Self::Item> {
1431 if self.finished {
1432 return None;
1433 }
1434
1435 loop {
1436 if let Some(file_entry) = self.files.next() {
1437 return Some(Ok(file_entry));
1438 }
1439
1440 let unit = match self.units.next() {
1441 Some(Ok(unit)) => unit,
1442 Some(Err(error)) => return Some(Err(error)),
1443 None => break,
1444 };
1445
1446 self.files = DwarfUnitFileIterator {
1447 unit: Some(unit),
1448 index: 0,
1449 };
1450 }
1451
1452 self.finished = true;
1453 None
1454 }
1455}
1456
1457pub struct DwarfFunctionIterator<'s> {
1459 units: DwarfUnitIterator<'s>,
1460 functions: std::vec::IntoIter<Function<'s>>,
1461 seen_ranges: BTreeSet<(u64, u64)>,
1462 finished: bool,
1463}
1464
1465impl<'s> Iterator for DwarfFunctionIterator<'s> {
1466 type Item = Result<Function<'s>, DwarfError>;
1467
1468 fn next(&mut self) -> Option<Self::Item> {
1469 if self.finished {
1470 return None;
1471 }
1472
1473 loop {
1474 if let Some(func) = self.functions.next() {
1475 return Some(Ok(func));
1476 }
1477
1478 let unit = match self.units.next() {
1479 Some(Ok(unit)) => unit,
1480 Some(Err(error)) => return Some(Err(error)),
1481 None => break,
1482 };
1483
1484 self.functions = match unit.functions(&mut self.seen_ranges) {
1485 Ok(functions) => functions.into_iter(),
1486 Err(error) => return Some(Err(error)),
1487 };
1488 }
1489
1490 self.finished = true;
1491 None
1492 }
1493}
1494
1495impl std::iter::FusedIterator for DwarfFunctionIterator<'_> {}
1496
1497#[cfg(test)]
1498mod tests {
1499 use super::*;
1500
1501 use crate::macho::MachObject;
1502
1503 #[cfg(feature = "macho")]
1504 #[test]
1505 fn test_loads_debug_str_offsets() {
1506 let data = std::fs::read("tests/fixtures/helloworld").unwrap();
1509
1510 let obj = MachObject::parse(&data).unwrap();
1511
1512 let sections = DwarfSections::from_dwarf(&obj);
1513 assert_eq!(sections.debug_str_offsets.data.len(), 48);
1514 }
1515}