Skip to main content

symbolic_debuginfo/
dwarf.rs

1//! Support for DWARF debugging information, common to ELF and MachO.
2//! In rare cases, PE's may contain it as well.
3//!
4//! The central element of this module is the [`Dwarf`] trait, which is implemented by [`ElfObject`],
5//! [`MachObject`] and [`PeObject`]. The dwarf debug session object can be obtained via getters on those types.
6//!
7//! [`Dwarf`]: trait.Dwarf.html
8//! [`ElfObject`]: ../elf/struct.ElfObject.html
9//! [`MachObject`]: ../macho/struct.MachObject.html
10//! [`PeObject`]: ../pe/struct.PeObject.html
11
12use 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/// This is a fake BcSymbolMap used when macho support is turned off since they are unfortunately
35/// part of the dwarf interface
36#[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
69/// This applies the offset to the address.
70///
71/// This function does not panic but would wrap around if too large or small
72/// numbers are passed.
73fn offset(addr: u64, offset: i64) -> u64 {
74    (addr as i64).wrapping_sub(offset) as u64
75}
76
77/// The error type for [`DwarfError`].
78#[non_exhaustive]
79#[derive(Clone, Copy, Debug, PartialEq, Eq)]
80pub enum DwarfErrorKind {
81    /// A compilation unit referenced by index does not exist.
82    InvalidUnitRef(usize),
83
84    /// A file record referenced by index does not exist.
85    InvalidFileRef(u64),
86
87    /// An inline record was encountered without an inlining parent.
88    UnexpectedInline,
89
90    /// The debug_ranges of a function are invalid.
91    InvertedFunctionRange,
92
93    /// The DWARF file is corrupted. See the cause for more information.
94    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/// An error handling [`DWARF`](trait.Dwarf.html) debugging information.
112#[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    /// Creates a new DWARF error from a known kind of error as well as an arbitrary error
122    /// payload.
123    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    /// Returns the corresponding [`DwarfErrorKind`] for this error.
132    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/// DWARF section information including its data.
150///
151/// This is returned from objects implementing the [`Dwarf`] trait.
152///
153/// [`Dwarf`]: trait.Dwarf.html
154#[derive(Clone)]
155pub struct DwarfSection<'data> {
156    /// Memory address of this section in virtual memory.
157    pub address: u64,
158
159    /// File offset of this section.
160    pub offset: u64,
161
162    /// Section address alignment (power of two).
163    pub align: u64,
164
165    /// Binary data of this section.
166    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
180/// Provides access to DWARF debugging information independent of the container file type.
181///
182/// When implementing this trait, verify whether the container file type supports compressed section
183/// data. If so, override the provided `section_data` method. Also, if there is a faster way to
184/// check for the existence of a section without loading its data, override `has_section`.
185pub trait Dwarf<'data> {
186    /// Returns whether the file was compiled for a big-endian or little-endian machine.
187    ///
188    /// This can usually be determined by inspecting the file's headers. Sometimes, this is also
189    /// given by the architecture.
190    fn endianity(&self) -> Endian;
191
192    /// Returns information and raw data of a section.
193    ///
194    /// The section name is given without leading punctuation, such dots or underscores. For
195    /// instance, the name of the Debug Info section would be `"debug_info"`, which translates to
196    /// `".debug_info"` in ELF and `"__debug_info"` in MachO.
197    ///
198    /// Certain containers might allow compressing section data. In this case, this function returns
199    /// the compressed data. To get uncompressed data instead, use `section_data`.
200    fn raw_section(&self, name: &str) -> Option<DwarfSection<'data>>;
201
202    /// Returns information and data of a section.
203    ///
204    /// If the section is compressed, this decompresses on the fly and returns allocated memory.
205    /// Otherwise, this should return a slice of the raw data.
206    ///
207    /// The section name is given without leading punctuation, such dots or underscores. For
208    /// instance, the name of the Debug Info section would be `"debug_info"`, which translates to
209    /// `".debug_info"` in ELF and `"__debug_info"` in MachO.
210    fn section(&self, name: &str) -> Option<DwarfSection<'data>> {
211        self.raw_section(name)
212    }
213
214    /// Determines whether the specified section exists.
215    ///
216    /// The section name is given without leading punctuation, such dots or underscores. For
217    /// instance, the name of the Debug Info section would be `"debug_info"`, which translates to
218    /// `".debug_info"` in ELF and `"__debug_info"` in MachO.
219    fn has_section(&self, name: &str) -> bool {
220        self.raw_section(name).is_some()
221    }
222}
223
224/// A row in the DWARF line program.
225#[derive(Debug)]
226struct DwarfRow {
227    address: u64,
228    file_index: u64,
229    line: Option<u64>,
230    size: Option<u64>,
231}
232
233/// A sequence in the DWARF line program.
234#[derive(Debug)]
235struct DwarfSequence {
236    start: u64,
237    end: u64,
238    rows: Vec<DwarfRow>,
239}
240
241/// Helper that prepares a DwarfLineProgram for more efficient access.
242#[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            // we have seen rustc emit for WASM targets a bad sequence that spans from 0 to
259            // the end of the program.  https://github.com/rust-lang/rust/issues/79410
260            // We want to skip these bad sequences. Unfortunately, code in .o files can legitimately
261            // be located at address 0, so we incorrectly skip line sequences in that case, too.
262            // See https://github.com/getsentry/symbolic/issues/471 .
263            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                // Theoretically, there could be multiple DW_LNE_end_sequence in a row. We're not
275                // interested in empty sequences, so we can skip them completely.
276                if !sequence_rows.is_empty() {
277                    sequences.push(DwarfSequence {
278                        start: sequence_rows[0].address,
279                        // Take a defensive approach and ensure that `high_address` always covers
280                        // the last encountered row, assuming a 1 byte instruction.
281                        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                // The standard says:
292                // "Within a sequence, addresses and operation pointers may only increase."
293                // So this row is invalid, we can ignore it.
294                //
295                // If we wanted to handle this, we could start a new sequence
296                // here, but let's wait until that is needed.
297            } 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            // A sequence without an end_sequence row.
322            // Let's assume the last row covered 1 byte.
323            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 are not guaranteed to be in order.
333        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/// A slim wrapper around a DWARF unit.
363#[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    /// Resolve the binary value of an attribute.
371    #[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    /// Resolve the actual string value of an attribute.
380    #[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    /// Resolves an entry and if found invokes a function to transform it.
387    ///
388    /// As this might resolve into cached information the data borrowed from
389    /// abbrev can only be temporarily accessed in the callback.
390    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            // TODO: There is probably more that can come back here.
398            _ => 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    /// Returns the offset of this unit within its section.
412    fn offset(&self) -> UnitSectionOffset {
413        self.unit.header.offset()
414    }
415
416    /// Returns the source language declared in the root DIE of this compilation unit.
417    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    /// Maximum recursion depth for following `DW_AT_abstract_origin` chains, matching the limit
431    /// used by elfutils `dwarf_attr_integrate`.
432    const MAX_ABSTRACT_ORIGIN_DEPTH: u8 = 16;
433
434    /// Resolves the source language for a DIE by following `DW_AT_abstract_origin` chains,
435    /// including across compilation unit boundaries. `depth` limits recursion to guard against
436    /// cycles or malformed DWARF.
437    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                // Recurse first to follow deeper chains.
448                if let Some(lang) = ref_unit.resolve_entry_language(ref_entry, depth - 1)? {
449                    return Ok(Some(lang));
450                }
451                // No deeper reference: use the CU language if this is a cross-unit ref.
452                if self.offset() != ref_unit.offset() {
453                    ref_unit.language()
454                } else {
455                    Ok(None)
456                }
457            });
458        }
459        Ok(None)
460    }
461
462    /// Resolves the function name of a debug entry.
463    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                // Prioritize these. If we get them, take them.
477                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                // Self-references may have a layer of indirection. Avoid infinite recursion
503                // in this scenario.
504                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/// Wrapper around a DWARF Unit.
528#[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    /// Creates a DWARF unit from the gimli `Unit` type.
539    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        // Clang's LLD might eliminate an entire compilation unit and simply set the low_pc to zero
552        // and remove all range entries to indicate that it is missing. Skip such a unit, as it does
553        // not contain any code that can be executed. Special case relocatable objects, as here the
554        // range information has not been written yet and all units look like this.
555        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        // The value of DW_AT_producer may be an in-place string or a
573        // reference into the debug_str section. We use `string_value`
574        // to resolve it correctly in either case.
575        let producer = entry
576            .attr_value(constants::DW_AT_producer)?
577            .and_then(|av| av.string_value(&info.inner.debug_str));
578
579        // Trust the symbol table more to contain accurate mangled names. However, since Dart's name
580        // mangling is lossy, we need to load the demangled name instead.
581        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    /// The path of the compilation directory. File names are usually relative to this path.
593    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    /// Parses the call site and range lists of this Debugging Information Entry.
601    ///
602    /// This method consumes the attributes of the DIE. This means that the `entries` iterator must
603    /// be placed just before the attributes of the DIE. On return, the `entries` iterator is placed
604    /// after the attributes, ready to read the next DIE's abbrev.
605    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                                // We have seen broken ranges for some WASM debug files generated by
655                                // emscripten. They mostly manifest themselves in these errors, which
656                                // are triggered by an inverted range (going high to low).
657                                // See a few more examples of broken ranges here:
658                                // https://github.com/emscripten-core/emscripten/issues/15552
659                                Err(gimli::Error::InvalidAddressRange) => None,
660                                Err(err) => {
661                                    return Err(err.into());
662                                }
663                            } {
664                                // A range that begins at 0 indicates code that was eliminated by
665                                // the linker, see below.
666                                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        // To go by the logic in dwarf2read, a `low_pc` of 0 can indicate an
699        // eliminated duplicate when the GNU linker is used. In relocatable
700        // objects, all functions are at `0` since they have not been placed
701        // yet, so we want to retain them.
702        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            // Most likely low_pc == high_pc means the DIE should be ignored.
715            // https://sourceware.org/ml/gdb-patches/2011-03/msg00739.html
716            return Ok(None);
717        }
718
719        if low_pc == u64::MAX || low_pc == u64::MAX - 1 {
720            // Similarly, u64::MAX/u64::MAX-1 may be used to indicate deleted code.
721            // See https://reviews.llvm.org/D59553
722            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    /// Resolves file information from a line program.
736    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    /// Resolves a file entry by its index.
756    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    /// Resolves the name of a function from the symbol table.
768    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    /// Resolves the source language for a function by following `DW_AT_abstract_origin` to the
775    /// origin compilation unit when crossing unit boundaries.
776    ///
777    /// With LTO, the linker may create artificial compilation units whose `DW_AT_language`
778    /// does not reflect the original source language (e.g., a C++ CU containing functions
779    /// originally written in C). When such a CU's subprogram carries a cross-unit
780    /// `DW_AT_abstract_origin`, the referenced CU's language is more authoritative.
781    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    /// Parses any DW_TAG_subprogram DIEs in the DIE subtree.
794    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    /// Parse a single function from a DWARF DIE subtree.
818    ///
819    /// The `entries` iterator must be placed after the abbrev / before the attributes of the
820    /// function DIE.
821    ///
822    /// This method can call itself recursively if another DW_TAG_subprogram entry is encountered
823    /// in the subtree.
824    ///
825    /// On return, the `entries` iterator is placed after the attributes of the last-read DIE.
826    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            // Filter out empty and reversed ranges.
839            if range.begin > range.end {
840                return false;
841            }
842
843            // We have seen duplicate top-level function entries being yielded from the
844            // [`DwarfFunctionIterator`], which combined with recursively walking its inlinees can
845            // blow past symcache limits.
846            // We suspect the reason is that the the same top-level functions might be defined in
847            // different compile units. We suspect this might be caused by link-time deduplication
848            // which merges templated code that is being generated multiple times in each
849            // compilation unit. We make sure to detect this here, so we can avoid creating these
850            // duplicates as early as possible.
851            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        // Ranges can be empty for three reasons: (1) the function is a no-op and does not
858        // contain any code, (2) the function did contain eliminated dead code, or (3) some
859        // tooling created garbage reversed ranges which we filtered out.
860        // In the dead code case, a surrogate DIE remains with `DW_AT_low_pc(0)` and empty ranges.
861        // That DIE might still contain inlined functions with actual ranges - these must be skipped.
862        // However, non-inlined functions may be present in this subtree, so we must still descend
863        // into it.
864        if ranges.is_empty() {
865            return self.parse_functions(depth, entries, output);
866        }
867
868        // Resolve functions in the symbol table first. Only if there is no entry, fall back
869        // to debug information only if there is no match. Sometimes, debug info contains a
870        // lesser quality of symbol names.
871        //
872        // XXX: Maybe we should actually parse the ranges in the resolve function and always
873        // look at the symbol table based on the start of the DIE range.
874
875        let entry = self.inner.unit.entry(dw_die_offset)?;
876        // With LTO the current CU may be an artificial unit with an incorrect language. Follow
877        // DW_AT_abstract_origin cross-unit to find the true source language. The resolved
878        // language is also propagated to all inlinees of this function.
879        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        // Create one function per range. In the common case there is only one range, so
899        // we usually only have one function builder here.
900        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    /// Traverses a subtree during function parsing.
934    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                    // Nested subprograms resolve their own language independently.
956                    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    /// Recursively parse the inlinees of a function from a DWARF DIE subtree.
979    ///
980    /// The `entries` iterator must be placed just before the attributes of the inline function DIE.
981    ///
982    /// This method calls itself recursively for other DW_TAG_inlined_subroutine entries in the
983    /// subtree. It can also call `parse_function` if a `DW_TAG_subprogram` entry is encountered.
984    ///
985    /// On return, the `entries` iterator is placed after the attributes of the last-read DIE.
986    #[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        // Ranges can be empty for three reasons: (1) the function is a no-op and does not
1003        // contain any code, (2) the function did contain eliminated dead code, or (3) some
1004        // tooling created garbage reversed ranges which we filtered out.
1005        // In the dead code case, a surrogate DIE remains with `DW_AT_low_pc(0)` and empty ranges.
1006        // That DIE might still contain inlined functions with actual ranges - these must be skipped.
1007        // However, non-inlined functions may be present in this subtree, so we must still descend
1008        // into it.
1009        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        // Use the language resolved for the enclosing top-level subprogram rather than
1017        // self.language: the inlinee's DW_AT_abstract_origin may resolve to a partial unit
1018        // which carries the wrong language (e.g. a C++ LTO partial unit for C code).
1019        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        // Create a separate inlinee for each range.
1033        for range in ranges.iter() {
1034            // Find the builder for the outer function that covers this range. Usually there's only
1035            // one outer range, so only one builder.
1036            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    /// Collects all functions within this compilation unit.
1059    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
1070/// The state we pass around during function parsing.
1071struct FunctionsOutput<'a, 'd> {
1072    /// The list of fully-parsed outer functions. Items are appended whenever we are done
1073    /// parsing an entire function.
1074    pub functions: Vec<Function<'d>>,
1075    /// A scratch buffer which avoids frequent allocations.
1076    pub range_buf: Vec<Range>,
1077    /// The set of `(address, size)` ranges of the functions we've already parsed.
1078    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/// For returning (partial) call location information from `parse_ranges`.
1092#[derive(Debug, Default, Clone, Copy)]
1093struct CallLocation {
1094    pub call_file: Option<u64>,
1095    pub call_line: Option<u64>,
1096}
1097
1098/// Converts a DWARF language number into our `Language` type.
1099fn 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
1119/// Data of a specific DWARF section.
1120struct 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    /// Loads data for this section from the object file.
1131    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    /// Creates a gimli dwarf section object from the loaded data.
1146    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
1170/// All DWARF sections that are needed by `DwarfDebugSession`.
1171struct 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    /// Loads all sections from a DWARF object.
1188    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    /// Parses DWARF information from its raw section data.
1228    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        // Prepare random access to unit headers.
1258        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    /// Loads a compilation unit.
1272    fn get_unit(&self, index: usize) -> Result<Option<&Unit<'d>>, DwarfError> {
1273        // Silently ignore unit references out-of-bound
1274        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            // Parse the compilation unit from the header. This requires a top-level DIE that
1281            // describes the unit itself. For some older DWARF files, this DIE might be missing
1282            // which causes gimli to error out. We prefer to skip them silently as this simply marks
1283            // an empty unit for us.
1284            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    /// Resolves an offset into a different compilation unit.
1296    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(&section_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    /// Returns an iterator over all compilation units.
1321    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
1348/// An iterator over compilation units in a DWARF object.
1349struct 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
1382/// A debugging session for DWARF debugging information.
1383pub struct DwarfDebugSession<'data> {
1384    cell: SelfCell<Box<DwarfSections<'data>>, DwarfInfo<'data>>,
1385    bcsymbolmap: Option<Arc<BcSymbolMap<'data>>>,
1386}
1387
1388impl<'data> DwarfDebugSession<'data> {
1389    /// Parses a dwarf debugging information from the given DWARF file.
1390    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    /// Loads the [`BcSymbolMap`] into this debug session.
1411    ///
1412    /// All the file and function names yielded by this debug session will be resolved using
1413    /// the provided symbol map.
1414    #[cfg(feature = "macho")]
1415    pub(crate) fn load_symbolmap(&mut self, symbolmap: Option<Arc<BcSymbolMap<'data>>>) {
1416        self.bcsymbolmap = symbolmap;
1417    }
1418
1419    /// Returns an iterator over all source files in this debug file.
1420    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    /// Returns an iterator over all functions in this debug file.
1429    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    /// See [DebugSession::source_by_path] for more information.
1439    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
1502/// An iterator over source files in a DWARF file.
1503pub 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
1539/// An iterator over functions in a DWARF file.
1540pub 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        // File generated using dsymutil
1589
1590        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}