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 language(&self) -> Result<Option<Language>, DwarfError> {
418 let mut entries = self.unit.entries();
419 let Some((_, root_entry)) = entries.next_dfs()? else {
420 return Ok(None);
421 };
422 let Some(AttributeValue::Language(lang)) =
423 root_entry.attr_value(constants::DW_AT_language)?
424 else {
425 return Ok(None);
426 };
427 Ok(Some(language_from_dwarf(lang)))
428 }
429
430 const MAX_ABSTRACT_ORIGIN_DEPTH: u8 = 16;
433
434 fn resolve_entry_language(
438 &self,
439 entry: &Die<'d, '_>,
440 depth: u8,
441 ) -> Result<Option<Language>, DwarfError> {
442 if depth == 0 {
443 return Ok(None);
444 }
445 if let Ok(Some(attr)) = entry.attr(constants::DW_AT_abstract_origin) {
446 return self.resolve_reference(attr, |ref_unit, ref_entry| {
447 if let Some(lang) = ref_unit.resolve_entry_language(ref_entry, depth - 1)? {
449 return Ok(Some(lang));
450 }
451 if self.offset() != ref_unit.offset() {
453 ref_unit.language()
454 } else {
455 Ok(None)
456 }
457 });
458 }
459 Ok(None)
460 }
461
462 fn resolve_function_name(
464 &self,
465 entry: &Die<'d, '_>,
466 language: Language,
467 bcsymbolmap: Option<&'d BcSymbolMap<'d>>,
468 prior_offset: Option<UnitOffset>,
469 ) -> Result<Option<Name<'d>>, DwarfError> {
470 let mut attrs = entry.attrs();
471 let mut fallback_name = None;
472 let mut reference_target = None;
473
474 while let Some(attr) = attrs.next()? {
475 match attr.name() {
476 constants::DW_AT_linkage_name | constants::DW_AT_MIPS_linkage_name => {
478 return Ok(self
479 .string_value(attr.value())
480 .map(|n| resolve_cow_name(bcsymbolmap, n))
481 .map(|n| Name::new(n, NameMangling::Mangled, language)));
482 }
483 constants::DW_AT_name => {
484 fallback_name = Some(attr);
485 }
486 constants::DW_AT_abstract_origin | constants::DW_AT_specification => {
487 reference_target = Some(attr);
488 }
489 _ => {}
490 }
491 }
492
493 if let Some(attr) = fallback_name {
494 return Ok(self
495 .string_value(attr.value())
496 .map(|n| resolve_cow_name(bcsymbolmap, n))
497 .map(|n| Name::new(n, NameMangling::Unmangled, language)));
498 }
499
500 if let Some(attr) = reference_target {
501 return self.resolve_reference(attr, |ref_unit, ref_entry| {
502 if let Some(prior) = prior_offset {
505 if self.offset() == ref_unit.offset() && prior == ref_entry.offset() {
506 return Ok(None);
507 }
508 }
509
510 if self.offset() != ref_unit.offset() || entry.offset() != ref_entry.offset() {
511 ref_unit.resolve_function_name(
512 ref_entry,
513 language,
514 bcsymbolmap,
515 Some(entry.offset()),
516 )
517 } else {
518 Ok(None)
519 }
520 });
521 }
522
523 Ok(None)
524 }
525}
526
527#[derive(Debug)]
529struct DwarfUnit<'d, 'a> {
530 inner: UnitRef<'d, 'a>,
531 bcsymbolmap: Option<&'d BcSymbolMap<'d>>,
532 language: Language,
533 line_program: Option<DwarfLineProgram<'d>>,
534 prefer_dwarf_names: bool,
535}
536
537impl<'d, 'a> DwarfUnit<'d, 'a> {
538 fn from_unit(
540 unit: &'a Unit<'d>,
541 info: &'a DwarfInfo<'d>,
542 bcsymbolmap: Option<&'d BcSymbolMap<'d>>,
543 ) -> Result<Option<Self>, DwarfError> {
544 let inner = UnitRef { info, unit };
545 let mut entries = unit.entries();
546 let entry = match entries.next_dfs()? {
547 Some((_, entry)) => entry,
548 None => return Err(gimli::read::Error::MissingUnitDie.into()),
549 };
550
551 if info.kind != ObjectKind::Relocatable
556 && unit.low_pc == 0
557 && entry.attr(constants::DW_AT_ranges)?.is_none()
558 {
559 return Ok(None);
560 }
561
562 let language = match entry.attr_value(constants::DW_AT_language)? {
563 Some(AttributeValue::Language(lang)) => language_from_dwarf(lang),
564 _ => Language::Unknown,
565 };
566
567 let line_program = unit
568 .line_program
569 .as_ref()
570 .map(|program| DwarfLineProgram::prepare(program.clone()));
571
572 let producer = entry
576 .attr_value(constants::DW_AT_producer)?
577 .and_then(|av| av.string_value(&info.inner.debug_str));
578
579 let prefer_dwarf_names = producer.as_deref() == Some(b"Dart VM");
582
583 Ok(Some(DwarfUnit {
584 inner,
585 bcsymbolmap,
586 language,
587 line_program,
588 prefer_dwarf_names,
589 }))
590 }
591
592 fn compilation_dir(&self) -> &'d [u8] {
594 match self.inner.unit.comp_dir {
595 Some(ref dir) => resolve_byte_name(self.bcsymbolmap, dir.slice()),
596 None => &[],
597 }
598 }
599
600 fn parse_ranges<'r>(
606 &self,
607 entries: &mut EntriesRaw<'d, '_>,
608 abbrev: &gimli::Abbreviation,
609 range_buf: &'r mut Vec<Range>,
610 ) -> Result<(&'r mut Vec<Range>, CallLocation), DwarfError> {
611 range_buf.clear();
612
613 let mut call_line = None;
614 let mut call_file = None;
615 let mut low_pc = None;
616 let mut high_pc = None;
617 let mut high_pc_rel = None;
618
619 let kind = self.inner.info.kind;
620
621 for spec in abbrev.attributes() {
622 let attr = entries.read_attribute(*spec)?;
623 match attr.name() {
624 constants::DW_AT_low_pc => match attr.value() {
625 AttributeValue::Addr(addr) => low_pc = Some(addr),
626 AttributeValue::DebugAddrIndex(index) => {
627 low_pc = Some(self.inner.info.address(self.inner.unit, index)?)
628 }
629 _ => return Err(GimliError::UnsupportedAttributeForm.into()),
630 },
631 constants::DW_AT_high_pc => match attr.value() {
632 AttributeValue::Addr(addr) => high_pc = Some(addr),
633 AttributeValue::DebugAddrIndex(index) => {
634 high_pc = Some(self.inner.info.address(self.inner.unit, index)?)
635 }
636 AttributeValue::Udata(size) => high_pc_rel = Some(size),
637 _ => return Err(GimliError::UnsupportedAttributeForm.into()),
638 },
639 constants::DW_AT_call_line => match attr.value() {
640 AttributeValue::Udata(line) => call_line = Some(line),
641 _ => return Err(GimliError::UnsupportedAttributeForm.into()),
642 },
643 constants::DW_AT_call_file => match attr.value() {
644 AttributeValue::FileIndex(file) => call_file = Some(file),
645 _ => return Err(GimliError::UnsupportedAttributeForm.into()),
646 },
647 constants::DW_AT_ranges
648 | constants::DW_AT_rnglists_base
649 | constants::DW_AT_start_scope => {
650 match self.inner.info.attr_ranges(self.inner.unit, attr.value())? {
651 Some(mut ranges) => {
652 while let Some(range) = match ranges.next() {
653 Ok(range) => range,
654 Err(gimli::Error::InvalidAddressRange) => None,
660 Err(err) => {
661 return Err(err.into());
662 }
663 } {
664 if range.begin > 0 || kind == ObjectKind::Relocatable {
667 range_buf.push(range);
668 }
669 }
670 }
671 None => continue,
672 }
673 }
674 _ => continue,
675 }
676 }
677
678 let call_location = CallLocation {
679 call_file,
680 call_line,
681 };
682
683 if range_buf.is_empty() {
684 if let Some(range) = Self::convert_pc_range(low_pc, high_pc, high_pc_rel, kind)? {
685 range_buf.push(range);
686 }
687 }
688
689 Ok((range_buf, call_location))
690 }
691
692 fn convert_pc_range(
693 low_pc: Option<u64>,
694 high_pc: Option<u64>,
695 high_pc_rel: Option<u64>,
696 kind: ObjectKind,
697 ) -> Result<Option<Range>, DwarfError> {
698 let low_pc = match low_pc {
703 Some(low_pc) if low_pc != 0 || kind == ObjectKind::Relocatable => low_pc,
704 _ => return Ok(None),
705 };
706
707 let high_pc = match (high_pc, high_pc_rel) {
708 (Some(high_pc), _) => high_pc,
709 (_, Some(high_pc_rel)) => low_pc.wrapping_add(high_pc_rel),
710 _ => return Ok(None),
711 };
712
713 if low_pc == high_pc {
714 return Ok(None);
717 }
718
719 if low_pc == u64::MAX || low_pc == u64::MAX - 1 {
720 return Ok(None);
723 }
724
725 if low_pc > high_pc {
726 return Err(DwarfErrorKind::InvertedFunctionRange.into());
727 }
728
729 Ok(Some(Range {
730 begin: low_pc,
731 end: high_pc,
732 }))
733 }
734
735 fn file_info(
737 &self,
738 line_program: &LineNumberProgramHeader<'d>,
739 file: &LineProgramFileEntry<'d>,
740 ) -> FileInfo<'d> {
741 FileInfo::new(
742 Cow::Borrowed(resolve_byte_name(
743 self.bcsymbolmap,
744 file.directory(line_program)
745 .and_then(|attr| self.inner.slice_value(attr))
746 .unwrap_or_default(),
747 )),
748 Cow::Borrowed(resolve_byte_name(
749 self.bcsymbolmap,
750 self.inner.slice_value(file.path_name()).unwrap_or_default(),
751 )),
752 )
753 }
754
755 fn resolve_file(&self, file_id: u64) -> Option<FileInfo<'d>> {
757 let line_program = match self.line_program {
758 Some(ref program) => &program.header,
759 None => return None,
760 };
761
762 line_program
763 .file(file_id)
764 .map(|file| self.file_info(line_program, file))
765 }
766
767 fn resolve_symbol_name(&self, address: u64, language: Language) -> Option<Name<'d>> {
769 let symbol = self.inner.info.symbol_map.lookup_exact(address)?;
770 let name = resolve_cow_name(self.bcsymbolmap, symbol.name.clone()?);
771 Some(Name::new(name, NameMangling::Mangled, language))
772 }
773
774 fn resolve_function_language(
782 &self,
783 entry: &Die<'d, '_>,
784 fallback_language: Language,
785 ) -> Language {
786 self.inner
787 .resolve_entry_language(entry, UnitRef::MAX_ABSTRACT_ORIGIN_DEPTH)
788 .ok()
789 .flatten()
790 .unwrap_or(fallback_language)
791 }
792
793 fn parse_functions(
795 &self,
796 depth: isize,
797 entries: &mut EntriesRaw<'d, '_>,
798 output: &mut FunctionsOutput<'_, 'd>,
799 ) -> Result<(), DwarfError> {
800 while !entries.is_empty() {
801 let dw_die_offset = entries.next_offset();
802 let next_depth = entries.next_depth();
803 if next_depth <= depth {
804 return Ok(());
805 }
806 if let Some(abbrev) = entries.read_abbreviation()? {
807 if abbrev.tag() == constants::DW_TAG_subprogram {
808 self.parse_function(dw_die_offset, next_depth, entries, abbrev, output)?;
809 } else {
810 entries.skip_attributes(abbrev.attributes())?;
811 }
812 }
813 }
814 Ok(())
815 }
816
817 fn parse_function(
827 &self,
828 dw_die_offset: gimli::UnitOffset<usize>,
829 depth: isize,
830 entries: &mut EntriesRaw<'d, '_>,
831 abbrev: &gimli::Abbreviation,
832 output: &mut FunctionsOutput<'_, 'd>,
833 ) -> Result<(), DwarfError> {
834 let (ranges, _) = self.parse_ranges(entries, abbrev, &mut output.range_buf)?;
835
836 let seen_ranges = &mut *output.seen_ranges;
837 ranges.retain(|range| {
838 if range.begin > range.end {
840 return false;
841 }
842
843 let address = offset(range.begin, self.inner.info.address_offset);
852 let size = range.end - range.begin;
853
854 seen_ranges.insert((address, size))
855 });
856
857 if ranges.is_empty() {
865 return self.parse_functions(depth, entries, output);
866 }
867
868 let entry = self.inner.unit.entry(dw_die_offset)?;
876 let language = self.resolve_function_language(&entry, self.language);
880
881 let symbol_name = if self.prefer_dwarf_names {
882 None
883 } else {
884 let first_range_begin = ranges.iter().map(|range| range.begin).min().unwrap();
885 let function_address = offset(first_range_begin, self.inner.info.address_offset);
886 self.resolve_symbol_name(function_address, language)
887 };
888
889 let name = symbol_name
890 .or_else(|| {
891 self.inner
892 .resolve_function_name(&entry, language, self.bcsymbolmap, None)
893 .ok()
894 .flatten()
895 })
896 .unwrap_or_else(|| Name::new("", NameMangling::Unmangled, language));
897
898 let mut builders: Vec<(Range, FunctionBuilder)> = ranges
901 .iter()
902 .map(|range| {
903 let address = offset(range.begin, self.inner.info.address_offset);
904 let size = range.end - range.begin;
905 (
906 *range,
907 FunctionBuilder::new(name.clone(), self.compilation_dir(), address, size),
908 )
909 })
910 .collect();
911
912 self.parse_function_children(depth, 0, entries, &mut builders, output, language)?;
913
914 if let Some(line_program) = &self.line_program {
915 for (range, builder) in &mut builders {
916 for row in line_program.get_rows(range) {
917 let address = offset(row.address, self.inner.info.address_offset);
918 let size = row.size;
919 let file = self.resolve_file(row.file_index).unwrap_or_default();
920 let line = row.line.unwrap_or(0);
921 builder.add_leaf_line(address, size, file, line);
922 }
923 }
924 }
925
926 for (_range, builder) in builders {
927 output.functions.push(builder.finish());
928 }
929
930 Ok(())
931 }
932
933 fn parse_function_children(
935 &self,
936 depth: isize,
937 inline_depth: u32,
938 entries: &mut EntriesRaw<'d, '_>,
939 builders: &mut [(Range, FunctionBuilder<'d>)],
940 output: &mut FunctionsOutput<'_, 'd>,
941 language: Language,
942 ) -> Result<(), DwarfError> {
943 while !entries.is_empty() {
944 let dw_die_offset = entries.next_offset();
945 let next_depth = entries.next_depth();
946 if next_depth <= depth {
947 return Ok(());
948 }
949 let abbrev = match entries.read_abbreviation()? {
950 Some(abbrev) => abbrev,
951 None => continue,
952 };
953 match abbrev.tag() {
954 constants::DW_TAG_subprogram => {
955 self.parse_function(dw_die_offset, next_depth, entries, abbrev, output)?;
957 }
958 constants::DW_TAG_inlined_subroutine => {
959 self.parse_inlinee(
960 dw_die_offset,
961 next_depth,
962 inline_depth,
963 entries,
964 abbrev,
965 builders,
966 output,
967 language,
968 )?;
969 }
970 _ => {
971 entries.skip_attributes(abbrev.attributes())?;
972 }
973 }
974 }
975 Ok(())
976 }
977
978 #[allow(clippy::too_many_arguments)]
987 fn parse_inlinee(
988 &self,
989 dw_die_offset: gimli::UnitOffset<usize>,
990 depth: isize,
991 inline_depth: u32,
992 entries: &mut EntriesRaw<'d, '_>,
993 abbrev: &gimli::Abbreviation,
994 builders: &mut [(Range, FunctionBuilder<'d>)],
995 output: &mut FunctionsOutput<'_, 'd>,
996 language: Language,
997 ) -> Result<(), DwarfError> {
998 let (ranges, call_location) = self.parse_ranges(entries, abbrev, &mut output.range_buf)?;
999
1000 ranges.retain(|range| range.end > range.begin);
1001
1002 if ranges.is_empty() {
1010 return self.parse_functions(depth, entries, output);
1011 }
1012
1013 let entry = self.inner.unit.entry(dw_die_offset)?;
1014 let language = self.resolve_function_language(&entry, language);
1015
1016 let name = self
1020 .inner
1021 .resolve_function_name(&entry, language, self.bcsymbolmap, None)
1022 .ok()
1023 .flatten()
1024 .unwrap_or_else(|| Name::new("", NameMangling::Unmangled, language));
1025
1026 let call_file = call_location
1027 .call_file
1028 .and_then(|i| self.resolve_file(i))
1029 .unwrap_or_default();
1030 let call_line = call_location.call_line.unwrap_or(0);
1031
1032 for range in ranges.iter() {
1034 let builder = match builders.iter_mut().find(|(outer_range, _builder)| {
1037 range.begin >= outer_range.begin && range.begin < outer_range.end
1038 }) {
1039 Some((_outer_range, builder)) => builder,
1040 None => continue,
1041 };
1042
1043 let address = offset(range.begin, self.inner.info.address_offset);
1044 let size = range.end - range.begin;
1045 builder.add_inlinee(
1046 inline_depth,
1047 name.clone(),
1048 address,
1049 size,
1050 call_file.clone(),
1051 call_line,
1052 );
1053 }
1054
1055 self.parse_function_children(depth, inline_depth + 1, entries, builders, output, language)
1056 }
1057
1058 fn functions(
1060 &self,
1061 seen_ranges: &mut BTreeSet<(u64, u64)>,
1062 ) -> Result<Vec<Function<'d>>, DwarfError> {
1063 let mut entries = self.inner.unit.entries_raw(None)?;
1064 let mut output = FunctionsOutput::with_seen_ranges(seen_ranges);
1065 self.parse_functions(-1, &mut entries, &mut output)?;
1066 Ok(output.functions)
1067 }
1068}
1069
1070struct FunctionsOutput<'a, 'd> {
1072 pub functions: Vec<Function<'d>>,
1075 pub range_buf: Vec<Range>,
1077 pub seen_ranges: &'a mut BTreeSet<(u64, u64)>,
1079}
1080
1081impl<'a> FunctionsOutput<'a, '_> {
1082 pub fn with_seen_ranges(seen_ranges: &'a mut BTreeSet<(u64, u64)>) -> Self {
1083 Self {
1084 functions: Vec::new(),
1085 range_buf: Vec::new(),
1086 seen_ranges,
1087 }
1088 }
1089}
1090
1091#[derive(Debug, Default, Clone, Copy)]
1093struct CallLocation {
1094 pub call_file: Option<u64>,
1095 pub call_line: Option<u64>,
1096}
1097
1098fn language_from_dwarf(language: gimli::DwLang) -> Language {
1100 match language {
1101 constants::DW_LANG_C => Language::C,
1102 constants::DW_LANG_C11 => Language::C,
1103 constants::DW_LANG_C89 => Language::C,
1104 constants::DW_LANG_C99 => Language::C,
1105 constants::DW_LANG_C_plus_plus => Language::Cpp,
1106 constants::DW_LANG_C_plus_plus_03 => Language::Cpp,
1107 constants::DW_LANG_C_plus_plus_11 => Language::Cpp,
1108 constants::DW_LANG_C_plus_plus_14 => Language::Cpp,
1109 constants::DW_LANG_D => Language::D,
1110 constants::DW_LANG_Go => Language::Go,
1111 constants::DW_LANG_ObjC => Language::ObjC,
1112 constants::DW_LANG_ObjC_plus_plus => Language::ObjCpp,
1113 constants::DW_LANG_Rust => Language::Rust,
1114 constants::DW_LANG_Swift => Language::Swift,
1115 _ => Language::Unknown,
1116 }
1117}
1118
1119struct DwarfSectionData<'data, S> {
1121 data: Cow<'data, [u8]>,
1122 endianity: Endian,
1123 _ph: PhantomData<S>,
1124}
1125
1126impl<'data, S> DwarfSectionData<'data, S>
1127where
1128 S: gimli::read::Section<Slice<'data>>,
1129{
1130 fn load<D>(dwarf: &D) -> Self
1132 where
1133 D: Dwarf<'data>,
1134 {
1135 DwarfSectionData {
1136 data: dwarf
1137 .section(&S::section_name()[1..])
1138 .map(|section| section.data)
1139 .unwrap_or_default(),
1140 endianity: dwarf.endianity(),
1141 _ph: PhantomData,
1142 }
1143 }
1144
1145 fn to_gimli(&'data self) -> S {
1147 S::from(Slice::new(&self.data, self.endianity))
1148 }
1149}
1150
1151impl<'d, S> fmt::Debug for DwarfSectionData<'d, S>
1152where
1153 S: gimli::read::Section<Slice<'d>>,
1154{
1155 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1156 let owned = match self.data {
1157 Cow::Owned(_) => true,
1158 Cow::Borrowed(_) => false,
1159 };
1160
1161 f.debug_struct("DwarfSectionData")
1162 .field("type", &S::section_name())
1163 .field("endianity", &self.endianity)
1164 .field("len()", &self.data.len())
1165 .field("owned()", &owned)
1166 .finish()
1167 }
1168}
1169
1170struct DwarfSections<'data> {
1172 debug_abbrev: DwarfSectionData<'data, gimli::read::DebugAbbrev<Slice<'data>>>,
1173 debug_addr: DwarfSectionData<'data, gimli::read::DebugAddr<Slice<'data>>>,
1174 debug_aranges: DwarfSectionData<'data, gimli::read::DebugAranges<Slice<'data>>>,
1175 debug_info: DwarfSectionData<'data, gimli::read::DebugInfo<Slice<'data>>>,
1176 debug_line: DwarfSectionData<'data, gimli::read::DebugLine<Slice<'data>>>,
1177 debug_line_str: DwarfSectionData<'data, gimli::read::DebugLineStr<Slice<'data>>>,
1178 debug_str: DwarfSectionData<'data, gimli::read::DebugStr<Slice<'data>>>,
1179 debug_str_offsets: DwarfSectionData<'data, gimli::read::DebugStrOffsets<Slice<'data>>>,
1180 debug_ranges: DwarfSectionData<'data, gimli::read::DebugRanges<Slice<'data>>>,
1181 debug_rnglists: DwarfSectionData<'data, gimli::read::DebugRngLists<Slice<'data>>>,
1182 debug_macinfo: DwarfSectionData<'data, gimli::read::DebugMacinfo<Slice<'data>>>,
1183 debug_macro: DwarfSectionData<'data, gimli::read::DebugMacro<Slice<'data>>>,
1184}
1185
1186impl<'data> DwarfSections<'data> {
1187 fn from_dwarf<D>(dwarf: &D) -> Self
1189 where
1190 D: Dwarf<'data>,
1191 {
1192 DwarfSections {
1193 debug_abbrev: DwarfSectionData::load(dwarf),
1194 debug_addr: DwarfSectionData::load(dwarf),
1195 debug_aranges: DwarfSectionData::load(dwarf),
1196 debug_info: DwarfSectionData::load(dwarf),
1197 debug_line: DwarfSectionData::load(dwarf),
1198 debug_line_str: DwarfSectionData::load(dwarf),
1199 debug_str: DwarfSectionData::load(dwarf),
1200 debug_str_offsets: DwarfSectionData::load(dwarf),
1201 debug_ranges: DwarfSectionData::load(dwarf),
1202 debug_rnglists: DwarfSectionData::load(dwarf),
1203 debug_macinfo: DwarfSectionData::load(dwarf),
1204 debug_macro: DwarfSectionData::load(dwarf),
1205 }
1206 }
1207}
1208
1209struct DwarfInfo<'data> {
1210 inner: DwarfInner<'data>,
1211 headers: Vec<UnitHeader<'data>>,
1212 units: Vec<OnceCell<Option<Unit<'data>>>>,
1213 symbol_map: SymbolMap<'data>,
1214 address_offset: i64,
1215 kind: ObjectKind,
1216}
1217
1218impl<'d> Deref for DwarfInfo<'d> {
1219 type Target = DwarfInner<'d>;
1220
1221 fn deref(&self) -> &Self::Target {
1222 &self.inner
1223 }
1224}
1225
1226impl<'d> DwarfInfo<'d> {
1227 pub fn parse(
1229 sections: &'d DwarfSections<'d>,
1230 symbol_map: SymbolMap<'d>,
1231 address_offset: i64,
1232 kind: ObjectKind,
1233 ) -> Result<Self, DwarfError> {
1234 let mut inner = gimli::read::Dwarf {
1235 abbreviations_cache: Default::default(),
1236 debug_abbrev: sections.debug_abbrev.to_gimli(),
1237 debug_addr: sections.debug_addr.to_gimli(),
1238 debug_aranges: sections.debug_aranges.to_gimli(),
1239 debug_info: sections.debug_info.to_gimli(),
1240 debug_line: sections.debug_line.to_gimli(),
1241 debug_line_str: sections.debug_line_str.to_gimli(),
1242 debug_str: sections.debug_str.to_gimli(),
1243 debug_str_offsets: sections.debug_str_offsets.to_gimli(),
1244 debug_types: Default::default(),
1245 debug_macinfo: sections.debug_macinfo.to_gimli(),
1246 debug_macro: sections.debug_macro.to_gimli(),
1247 locations: Default::default(),
1248 ranges: RangeLists::new(
1249 sections.debug_ranges.to_gimli(),
1250 sections.debug_rnglists.to_gimli(),
1251 ),
1252 file_type: DwarfFileType::Main,
1253 sup: Default::default(),
1254 };
1255 inner.populate_abbreviations_cache(AbbreviationsCacheStrategy::Duplicates);
1256
1257 let headers = inner.units().collect::<Vec<_>>()?;
1259 let units = headers.iter().map(|_| OnceCell::new()).collect();
1260
1261 Ok(DwarfInfo {
1262 inner,
1263 headers,
1264 units,
1265 symbol_map,
1266 address_offset,
1267 kind,
1268 })
1269 }
1270
1271 fn get_unit(&self, index: usize) -> Result<Option<&Unit<'d>>, DwarfError> {
1273 let cell = match self.units.get(index) {
1275 Some(cell) => cell,
1276 None => return Ok(None),
1277 };
1278
1279 let unit_opt = cell.get_or_try_init(|| {
1280 let header = self.headers[index];
1285 match self.inner.unit(header) {
1286 Ok(unit) => Ok(Some(unit)),
1287 Err(gimli::read::Error::MissingUnitDie) => Ok(None),
1288 Err(error) => Err(DwarfError::from(error)),
1289 }
1290 })?;
1291
1292 Ok(unit_opt.as_ref())
1293 }
1294
1295 fn find_unit_offset(
1297 &self,
1298 offset: DebugInfoOffset,
1299 ) -> Result<(UnitRef<'d, '_>, UnitOffset), DwarfError> {
1300 let section_offset = UnitSectionOffset::DebugInfoOffset(offset);
1301 let search_result = self
1302 .headers
1303 .binary_search_by_key(§ion_offset, UnitHeader::offset);
1304
1305 let index = match search_result {
1306 Ok(index) => index,
1307 Err(0) => return Err(DwarfErrorKind::InvalidUnitRef(offset.0).into()),
1308 Err(next_index) => next_index - 1,
1309 };
1310
1311 if let Some(unit) = self.get_unit(index)? {
1312 if let Some(unit_offset) = section_offset.to_unit_offset(unit) {
1313 return Ok((UnitRef { unit, info: self }, unit_offset));
1314 }
1315 }
1316
1317 Err(DwarfErrorKind::InvalidUnitRef(offset.0).into())
1318 }
1319
1320 fn units(&'d self, bcsymbolmap: Option<&'d BcSymbolMap<'d>>) -> DwarfUnitIterator<'d> {
1322 DwarfUnitIterator {
1323 info: self,
1324 bcsymbolmap,
1325 index: 0,
1326 }
1327 }
1328}
1329
1330impl<'slf, 'd: 'slf> AsSelf<'slf> for DwarfInfo<'d> {
1331 type Ref = DwarfInfo<'slf>;
1332
1333 fn as_self(&'slf self) -> &'slf Self::Ref {
1334 unsafe { std::mem::transmute(self) }
1335 }
1336}
1337
1338impl fmt::Debug for DwarfInfo<'_> {
1339 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1340 f.debug_struct("DwarfInfo")
1341 .field("headers", &self.headers)
1342 .field("symbol_map", &self.symbol_map)
1343 .field("address_offset", &self.address_offset)
1344 .finish()
1345 }
1346}
1347
1348struct DwarfUnitIterator<'s> {
1350 info: &'s DwarfInfo<'s>,
1351 bcsymbolmap: Option<&'s BcSymbolMap<'s>>,
1352 index: usize,
1353}
1354
1355impl<'s> Iterator for DwarfUnitIterator<'s> {
1356 type Item = Result<DwarfUnit<'s, 's>, DwarfError>;
1357
1358 fn next(&mut self) -> Option<Self::Item> {
1359 while self.index < self.info.headers.len() {
1360 let result = self.info.get_unit(self.index);
1361 self.index += 1;
1362
1363 let unit = match result {
1364 Ok(Some(unit)) => unit,
1365 Ok(None) => continue,
1366 Err(error) => return Some(Err(error)),
1367 };
1368
1369 match DwarfUnit::from_unit(unit, self.info, self.bcsymbolmap) {
1370 Ok(Some(unit)) => return Some(Ok(unit)),
1371 Ok(None) => continue,
1372 Err(error) => return Some(Err(error)),
1373 }
1374 }
1375
1376 None
1377 }
1378}
1379
1380impl std::iter::FusedIterator for DwarfUnitIterator<'_> {}
1381
1382pub struct DwarfDebugSession<'data> {
1384 cell: SelfCell<Box<DwarfSections<'data>>, DwarfInfo<'data>>,
1385 bcsymbolmap: Option<Arc<BcSymbolMap<'data>>>,
1386}
1387
1388impl<'data> DwarfDebugSession<'data> {
1389 pub fn parse<D>(
1391 dwarf: &D,
1392 symbol_map: SymbolMap<'data>,
1393 address_offset: i64,
1394 kind: ObjectKind,
1395 ) -> Result<Self, DwarfError>
1396 where
1397 D: Dwarf<'data>,
1398 {
1399 let sections = DwarfSections::from_dwarf(dwarf);
1400 let cell = SelfCell::try_new(Box::new(sections), |sections| {
1401 DwarfInfo::parse(unsafe { &*sections }, symbol_map, address_offset, kind)
1402 })?;
1403
1404 Ok(DwarfDebugSession {
1405 cell,
1406 bcsymbolmap: None,
1407 })
1408 }
1409
1410 #[cfg(feature = "macho")]
1415 pub(crate) fn load_symbolmap(&mut self, symbolmap: Option<Arc<BcSymbolMap<'data>>>) {
1416 self.bcsymbolmap = symbolmap;
1417 }
1418
1419 pub fn files(&self) -> DwarfFileIterator<'_> {
1421 DwarfFileIterator {
1422 units: self.cell.get().units(self.bcsymbolmap.as_deref()),
1423 files: DwarfUnitFileIterator::default(),
1424 finished: false,
1425 }
1426 }
1427
1428 pub fn functions(&self) -> DwarfFunctionIterator<'_> {
1430 DwarfFunctionIterator {
1431 units: self.cell.get().units(self.bcsymbolmap.as_deref()),
1432 functions: Vec::new().into_iter(),
1433 seen_ranges: BTreeSet::new(),
1434 finished: false,
1435 }
1436 }
1437
1438 pub fn source_by_path(
1440 &self,
1441 _path: &str,
1442 ) -> Result<Option<SourceFileDescriptor<'_>>, DwarfError> {
1443 Ok(None)
1444 }
1445}
1446
1447impl<'session> DebugSession<'session> for DwarfDebugSession<'_> {
1448 type Error = DwarfError;
1449 type FunctionIterator = DwarfFunctionIterator<'session>;
1450 type FileIterator = DwarfFileIterator<'session>;
1451
1452 fn functions(&'session self) -> Self::FunctionIterator {
1453 self.functions()
1454 }
1455
1456 fn files(&'session self) -> Self::FileIterator {
1457 self.files()
1458 }
1459
1460 fn source_by_path(&self, path: &str) -> Result<Option<SourceFileDescriptor<'_>>, Self::Error> {
1461 self.source_by_path(path)
1462 }
1463}
1464
1465#[derive(Debug, Default)]
1466struct DwarfUnitFileIterator<'s> {
1467 unit: Option<DwarfUnit<'s, 's>>,
1468 index: usize,
1469}
1470
1471impl<'s> Iterator for DwarfUnitFileIterator<'s> {
1472 type Item = FileEntry<'s>;
1473
1474 fn next(&mut self) -> Option<Self::Item> {
1475 let unit = self.unit.as_ref()?;
1476 let line_program = unit.line_program.as_ref().map(|p| &p.header)?;
1477 let file = line_program.file_names().get(self.index)?;
1478
1479 self.index += 1;
1480
1481 Some(FileEntry::new(
1482 Cow::Borrowed(unit.compilation_dir()),
1483 unit.file_info(line_program, file),
1484 ))
1485 }
1486}
1487
1488fn resolve_byte_name<'s>(bcsymbolmap: Option<&'s BcSymbolMap<'s>>, s: &'s [u8]) -> &'s [u8] {
1489 bcsymbolmap
1490 .and_then(|b| b.resolve_opt(s))
1491 .map(AsRef::as_ref)
1492 .unwrap_or(s)
1493}
1494
1495fn resolve_cow_name<'s>(bcsymbolmap: Option<&'s BcSymbolMap<'s>>, s: Cow<'s, str>) -> Cow<'s, str> {
1496 bcsymbolmap
1497 .and_then(|b| b.resolve_opt(s.as_bytes()))
1498 .map(Cow::Borrowed)
1499 .unwrap_or(s)
1500}
1501
1502pub struct DwarfFileIterator<'s> {
1504 units: DwarfUnitIterator<'s>,
1505 files: DwarfUnitFileIterator<'s>,
1506 finished: bool,
1507}
1508
1509impl<'s> Iterator for DwarfFileIterator<'s> {
1510 type Item = Result<FileEntry<'s>, DwarfError>;
1511
1512 fn next(&mut self) -> Option<Self::Item> {
1513 if self.finished {
1514 return None;
1515 }
1516
1517 loop {
1518 if let Some(file_entry) = self.files.next() {
1519 return Some(Ok(file_entry));
1520 }
1521
1522 let unit = match self.units.next() {
1523 Some(Ok(unit)) => unit,
1524 Some(Err(error)) => return Some(Err(error)),
1525 None => break,
1526 };
1527
1528 self.files = DwarfUnitFileIterator {
1529 unit: Some(unit),
1530 index: 0,
1531 };
1532 }
1533
1534 self.finished = true;
1535 None
1536 }
1537}
1538
1539pub struct DwarfFunctionIterator<'s> {
1541 units: DwarfUnitIterator<'s>,
1542 functions: std::vec::IntoIter<Function<'s>>,
1543 seen_ranges: BTreeSet<(u64, u64)>,
1544 finished: bool,
1545}
1546
1547impl<'s> Iterator for DwarfFunctionIterator<'s> {
1548 type Item = Result<Function<'s>, DwarfError>;
1549
1550 fn next(&mut self) -> Option<Self::Item> {
1551 if self.finished {
1552 return None;
1553 }
1554
1555 loop {
1556 if let Some(func) = self.functions.next() {
1557 return Some(Ok(func));
1558 }
1559
1560 let unit = match self.units.next() {
1561 Some(Ok(unit)) => unit,
1562 Some(Err(error)) => return Some(Err(error)),
1563 None => break,
1564 };
1565
1566 self.functions = match unit.functions(&mut self.seen_ranges) {
1567 Ok(functions) => functions.into_iter(),
1568 Err(error) => return Some(Err(error)),
1569 };
1570 }
1571
1572 self.finished = true;
1573 None
1574 }
1575}
1576
1577impl std::iter::FusedIterator for DwarfFunctionIterator<'_> {}
1578
1579#[cfg(test)]
1580mod tests {
1581 use super::*;
1582
1583 use crate::macho::MachObject;
1584
1585 #[cfg(feature = "macho")]
1586 #[test]
1587 fn test_loads_debug_str_offsets() {
1588 let data = std::fs::read("tests/fixtures/helloworld").unwrap();
1591
1592 let obj = MachObject::parse(&data).unwrap();
1593
1594 let sections = DwarfSections::from_dwarf(&obj);
1595 assert_eq!(sections.debug_str_offsets.data.len(), 48);
1596 }
1597}