gimli/read/
dwarf.rs

1use alloc::string::String;
2use alloc::sync::Arc;
3
4use crate::common::{
5    DebugAddrBase, DebugAddrIndex, DebugInfoOffset, DebugLineStrOffset, DebugLocListsBase,
6    DebugLocListsIndex, DebugMacinfoOffset, DebugRngListsBase, DebugRngListsIndex, DebugStrOffset,
7    DebugStrOffsetsBase, DebugStrOffsetsIndex, DebugTypeSignature, DebugTypesOffset, DwarfFileType,
8    DwoId, Encoding, LocationListsOffset, RangeListsOffset, RawRangeListsOffset, SectionId,
9    UnitSectionOffset,
10};
11use crate::read::{
12    Abbreviations, AbbreviationsCache, AbbreviationsCacheStrategy, AttributeValue, DebugAbbrev,
13    DebugAddr, DebugAranges, DebugCuIndex, DebugInfo, DebugInfoUnitHeadersIter, DebugLine,
14    DebugLineStr, DebugLoc, DebugLocLists, DebugMacinfo, DebugMacro, DebugRanges, DebugRngLists,
15    DebugStr, DebugStrOffsets, DebugTuIndex, DebugTypes, DebugTypesUnitHeadersIter,
16    DebuggingInformationEntry, EntriesCursor, EntriesRaw, EntriesTree, Error,
17    IncompleteLineProgram, IndexSectionId, LocListIter, LocationLists, MacroIter, Range,
18    RangeLists, RawLocListIter, RawRngListIter, Reader, ReaderOffset, ReaderOffsetId, Result,
19    RngListIter, Section, UnitHeader, UnitIndex, UnitIndexSectionIterator, UnitOffset, UnitType,
20};
21use crate::{constants, DebugMacroOffset};
22
23/// All of the commonly used DWARF sections.
24///
25/// This is useful for storing sections when `T` does not implement `Reader`.
26/// It can be used to create a `Dwarf` that references the data in `self`.
27/// If `T` does implement `Reader`, then use `Dwarf` directly.
28///
29/// ## Example Usage
30///
31/// It can be useful to load DWARF sections into owned data structures,
32/// such as `Vec`. However, we do not implement the `Reader` trait
33/// for `Vec`, because it would be very inefficient, but this trait
34/// is required for all of the methods that parse the DWARF data.
35/// So we first load the DWARF sections into `Vec`s, and then use
36/// `borrow` to create `Reader`s that reference the data.
37///
38/// ```rust,no_run
39/// # fn example() -> Result<(), gimli::Error> {
40/// # let loader = |name| -> Result<_, gimli::Error> { unimplemented!() };
41/// // Read the DWARF sections into `Vec`s with whatever object loader you're using.
42/// let dwarf_sections: gimli::DwarfSections<Vec<u8>> = gimli::DwarfSections::load(loader)?;
43/// // Create references to the DWARF sections.
44/// let dwarf: gimli::Dwarf<_> = dwarf_sections.borrow(|section| {
45///     gimli::EndianSlice::new(&section, gimli::LittleEndian)
46/// });
47/// # unreachable!()
48/// # }
49/// ```
50#[derive(Debug, Default)]
51pub struct DwarfSections<T> {
52    /// The `.debug_abbrev` section.
53    pub debug_abbrev: DebugAbbrev<T>,
54    /// The `.debug_addr` section.
55    pub debug_addr: DebugAddr<T>,
56    /// The `.debug_aranges` section.
57    pub debug_aranges: DebugAranges<T>,
58    /// The `.debug_info` section.
59    pub debug_info: DebugInfo<T>,
60    /// The `.debug_line` section.
61    pub debug_line: DebugLine<T>,
62    /// The `.debug_line_str` section.
63    pub debug_line_str: DebugLineStr<T>,
64    /// The `.debug_macinfo` section.
65    pub debug_macinfo: DebugMacinfo<T>,
66    /// The `.debug_macro` section.
67    pub debug_macro: DebugMacro<T>,
68    /// The `.debug_str` section.
69    pub debug_str: DebugStr<T>,
70    /// The `.debug_str_offsets` section.
71    pub debug_str_offsets: DebugStrOffsets<T>,
72    /// The `.debug_types` section.
73    pub debug_types: DebugTypes<T>,
74    /// The `.debug_loc` section.
75    pub debug_loc: DebugLoc<T>,
76    /// The `.debug_loclists` section.
77    pub debug_loclists: DebugLocLists<T>,
78    /// The `.debug_ranges` section.
79    pub debug_ranges: DebugRanges<T>,
80    /// The `.debug_rnglists` section.
81    pub debug_rnglists: DebugRngLists<T>,
82}
83
84impl<T> DwarfSections<T> {
85    /// Try to load the DWARF sections using the given loader function.
86    ///
87    /// `section` loads a DWARF section from the object file.
88    /// It should return an empty section if the section does not exist.
89    pub fn load<F, E>(mut section: F) -> core::result::Result<Self, E>
90    where
91        F: FnMut(SectionId) -> core::result::Result<T, E>,
92    {
93        Ok(DwarfSections {
94            // Section types are inferred.
95            debug_abbrev: Section::load(&mut section)?,
96            debug_addr: Section::load(&mut section)?,
97            debug_aranges: Section::load(&mut section)?,
98            debug_info: Section::load(&mut section)?,
99            debug_line: Section::load(&mut section)?,
100            debug_line_str: Section::load(&mut section)?,
101            debug_macinfo: Section::load(&mut section)?,
102            debug_macro: Section::load(&mut section)?,
103            debug_str: Section::load(&mut section)?,
104            debug_str_offsets: Section::load(&mut section)?,
105            debug_types: Section::load(&mut section)?,
106            debug_loc: Section::load(&mut section)?,
107            debug_loclists: Section::load(&mut section)?,
108            debug_ranges: Section::load(&mut section)?,
109            debug_rnglists: Section::load(&mut section)?,
110        })
111    }
112
113    /// Create a `Dwarf` structure that references the data in `self`.
114    pub fn borrow<'a, F, R>(&'a self, mut borrow: F) -> Dwarf<R>
115    where
116        F: FnMut(&'a T) -> R,
117    {
118        Dwarf::from_sections(DwarfSections {
119            debug_abbrev: self.debug_abbrev.borrow(&mut borrow),
120            debug_addr: self.debug_addr.borrow(&mut borrow),
121            debug_aranges: self.debug_aranges.borrow(&mut borrow),
122            debug_info: self.debug_info.borrow(&mut borrow),
123            debug_line: self.debug_line.borrow(&mut borrow),
124            debug_line_str: self.debug_line_str.borrow(&mut borrow),
125            debug_macinfo: self.debug_macinfo.borrow(&mut borrow),
126            debug_macro: self.debug_macro.borrow(&mut borrow),
127            debug_str: self.debug_str.borrow(&mut borrow),
128            debug_str_offsets: self.debug_str_offsets.borrow(&mut borrow),
129            debug_types: self.debug_types.borrow(&mut borrow),
130            debug_loc: self.debug_loc.borrow(&mut borrow),
131            debug_loclists: self.debug_loclists.borrow(&mut borrow),
132            debug_ranges: self.debug_ranges.borrow(&mut borrow),
133            debug_rnglists: self.debug_rnglists.borrow(&mut borrow),
134        })
135    }
136
137    /// Create a `Dwarf` structure that references the data in `self` and `sup`.
138    ///
139    /// This is like `borrow`, but also includes the supplementary object file.
140    /// This is useful when `R` implements `Reader` but `T` does not.
141    ///
142    /// ## Example Usage
143    ///
144    /// ```rust,no_run
145    /// # fn example() -> Result<(), gimli::Error> {
146    /// # let loader = |name| -> Result<_, gimli::Error> { unimplemented!() };
147    /// # let sup_loader = |name| -> Result<_, gimli::Error> { unimplemented!() };
148    /// // Read the DWARF sections into `Vec`s with whatever object loader you're using.
149    /// let dwarf_sections: gimli::DwarfSections<Vec<u8>> = gimli::DwarfSections::load(loader)?;
150    /// let dwarf_sup_sections: gimli::DwarfSections<Vec<u8>> = gimli::DwarfSections::load(sup_loader)?;
151    /// // Create references to the DWARF sections.
152    /// let dwarf = dwarf_sections.borrow_with_sup(&dwarf_sup_sections, |section| {
153    ///     gimli::EndianSlice::new(&section, gimli::LittleEndian)
154    /// });
155    /// # unreachable!()
156    /// # }
157    /// ```
158    pub fn borrow_with_sup<'a, F, R>(&'a self, sup: &'a Self, mut borrow: F) -> Dwarf<R>
159    where
160        F: FnMut(&'a T) -> R,
161    {
162        let mut dwarf = self.borrow(&mut borrow);
163        dwarf.set_sup(sup.borrow(&mut borrow));
164        dwarf
165    }
166}
167
168/// All of the commonly used DWARF sections, and other common information.
169#[derive(Debug, Default)]
170pub struct Dwarf<R> {
171    /// The `.debug_abbrev` section.
172    pub debug_abbrev: DebugAbbrev<R>,
173
174    /// The `.debug_addr` section.
175    pub debug_addr: DebugAddr<R>,
176
177    /// The `.debug_aranges` section.
178    pub debug_aranges: DebugAranges<R>,
179
180    /// The `.debug_info` section.
181    pub debug_info: DebugInfo<R>,
182
183    /// The `.debug_line` section.
184    pub debug_line: DebugLine<R>,
185
186    /// The `.debug_line_str` section.
187    pub debug_line_str: DebugLineStr<R>,
188
189    /// The `.debug_macinfo` section.
190    pub debug_macinfo: DebugMacinfo<R>,
191
192    /// The `.debug_macro` section.
193    pub debug_macro: DebugMacro<R>,
194
195    /// The `.debug_str` section.
196    pub debug_str: DebugStr<R>,
197
198    /// The `.debug_str_offsets` section.
199    pub debug_str_offsets: DebugStrOffsets<R>,
200
201    /// The `.debug_types` section.
202    pub debug_types: DebugTypes<R>,
203
204    /// The location lists in the `.debug_loc` and `.debug_loclists` sections.
205    pub locations: LocationLists<R>,
206
207    /// The range lists in the `.debug_ranges` and `.debug_rnglists` sections.
208    pub ranges: RangeLists<R>,
209
210    /// The type of this file.
211    pub file_type: DwarfFileType,
212
213    /// The DWARF sections for a supplementary object file.
214    pub sup: Option<Arc<Dwarf<R>>>,
215
216    /// A cache of previously parsed abbreviations for units in this file.
217    pub abbreviations_cache: AbbreviationsCache,
218}
219
220impl<T> Dwarf<T> {
221    /// Try to load the DWARF sections using the given loader function.
222    ///
223    /// `section` loads a DWARF section from the object file.
224    /// It should return an empty section if the section does not exist.
225    ///
226    /// After loading, the user should set the `file_type` field and
227    /// call `load_sup` if required.
228    pub fn load<F, E>(section: F) -> core::result::Result<Self, E>
229    where
230        F: FnMut(SectionId) -> core::result::Result<T, E>,
231    {
232        let sections = DwarfSections::load(section)?;
233        Ok(Self::from_sections(sections))
234    }
235
236    /// Load the DWARF sections from the supplementary object file.
237    ///
238    /// `section` operates the same as for `load`.
239    ///
240    /// Sets `self.sup`, replacing any previous value.
241    pub fn load_sup<F, E>(&mut self, section: F) -> core::result::Result<(), E>
242    where
243        F: FnMut(SectionId) -> core::result::Result<T, E>,
244    {
245        self.set_sup(Self::load(section)?);
246        Ok(())
247    }
248
249    /// Create a `Dwarf` structure from the given sections.
250    ///
251    /// The caller should set the `file_type` and `sup` fields if required.
252    fn from_sections(sections: DwarfSections<T>) -> Self {
253        Dwarf {
254            debug_abbrev: sections.debug_abbrev,
255            debug_addr: sections.debug_addr,
256            debug_aranges: sections.debug_aranges,
257            debug_info: sections.debug_info,
258            debug_line: sections.debug_line,
259            debug_line_str: sections.debug_line_str,
260            debug_macinfo: sections.debug_macinfo,
261            debug_macro: sections.debug_macro,
262            debug_str: sections.debug_str,
263            debug_str_offsets: sections.debug_str_offsets,
264            debug_types: sections.debug_types,
265            locations: LocationLists::new(sections.debug_loc, sections.debug_loclists),
266            ranges: RangeLists::new(sections.debug_ranges, sections.debug_rnglists),
267            file_type: DwarfFileType::Main,
268            sup: None,
269            abbreviations_cache: AbbreviationsCache::new(),
270        }
271    }
272
273    /// Create a `Dwarf` structure that references the data in `self`.
274    ///
275    /// This is useful when `R` implements `Reader` but `T` does not.
276    ///
277    /// ## Example Usage
278    ///
279    /// It can be useful to load DWARF sections into owned data structures,
280    /// such as `Vec`. However, we do not implement the `Reader` trait
281    /// for `Vec`, because it would be very inefficient, but this trait
282    /// is required for all of the methods that parse the DWARF data.
283    /// So we first load the DWARF sections into `Vec`s, and then use
284    /// `borrow` to create `Reader`s that reference the data.
285    ///
286    /// ```rust,no_run
287    /// # fn example() -> Result<(), gimli::Error> {
288    /// # let loader = |name| -> Result<_, gimli::Error> { unimplemented!() };
289    /// # let sup_loader = |name| -> Result<_, gimli::Error> { unimplemented!() };
290    /// // Read the DWARF sections into `Vec`s with whatever object loader you're using.
291    /// let mut owned_dwarf: gimli::Dwarf<Vec<u8>> = gimli::Dwarf::load(loader)?;
292    /// owned_dwarf.load_sup(sup_loader)?;
293    /// // Create references to the DWARF sections.
294    /// let dwarf = owned_dwarf.borrow(|section| {
295    ///     gimli::EndianSlice::new(&section, gimli::LittleEndian)
296    /// });
297    /// # unreachable!()
298    /// # }
299    /// ```
300    #[deprecated(note = "use `DwarfSections::borrow` instead")]
301    pub fn borrow<'a, F, R>(&'a self, mut borrow: F) -> Dwarf<R>
302    where
303        F: FnMut(&'a T) -> R,
304    {
305        Dwarf {
306            debug_abbrev: self.debug_abbrev.borrow(&mut borrow),
307            debug_addr: self.debug_addr.borrow(&mut borrow),
308            debug_aranges: self.debug_aranges.borrow(&mut borrow),
309            debug_info: self.debug_info.borrow(&mut borrow),
310            debug_line: self.debug_line.borrow(&mut borrow),
311            debug_line_str: self.debug_line_str.borrow(&mut borrow),
312            debug_macinfo: self.debug_macinfo.borrow(&mut borrow),
313            debug_macro: self.debug_macro.borrow(&mut borrow),
314            debug_str: self.debug_str.borrow(&mut borrow),
315            debug_str_offsets: self.debug_str_offsets.borrow(&mut borrow),
316            debug_types: self.debug_types.borrow(&mut borrow),
317            locations: self.locations.borrow(&mut borrow),
318            ranges: self.ranges.borrow(&mut borrow),
319            file_type: self.file_type,
320            sup: self.sup().map(|sup| Arc::new(sup.borrow(borrow))),
321            abbreviations_cache: AbbreviationsCache::new(),
322        }
323    }
324
325    /// Store the DWARF sections for the supplementary object file.
326    pub fn set_sup(&mut self, sup: Dwarf<T>) {
327        self.sup = Some(Arc::new(sup));
328    }
329
330    /// Return a reference to the DWARF sections for the supplementary object file.
331    pub fn sup(&self) -> Option<&Dwarf<T>> {
332        self.sup.as_ref().map(Arc::as_ref)
333    }
334}
335
336impl<R: Reader> Dwarf<R> {
337    /// Parse abbreviations and store them in the cache.
338    ///
339    /// This will iterate over the units in `self.debug_info` to determine the
340    /// abbreviations offsets.
341    ///
342    /// Errors during parsing abbreviations are also stored in the cache.
343    /// Errors during iterating over the units are ignored.
344    pub fn populate_abbreviations_cache(&mut self, strategy: AbbreviationsCacheStrategy) {
345        self.abbreviations_cache
346            .populate(strategy, &self.debug_abbrev, self.debug_info.units());
347    }
348
349    /// Iterate the unit headers in the `.debug_info` section.
350    ///
351    /// Can be [used with
352    /// `FallibleIterator`](./index.html#using-with-fallibleiterator).
353    #[inline]
354    pub fn units(&self) -> DebugInfoUnitHeadersIter<R> {
355        self.debug_info.units()
356    }
357
358    /// Construct a new `Unit` from the given unit header.
359    #[inline]
360    pub fn unit(&self, header: UnitHeader<R>) -> Result<Unit<R>> {
361        Unit::new(self, header)
362    }
363
364    /// Iterate the type-unit headers in the `.debug_types` section.
365    ///
366    /// Can be [used with
367    /// `FallibleIterator`](./index.html#using-with-fallibleiterator).
368    #[inline]
369    pub fn type_units(&self) -> DebugTypesUnitHeadersIter<R> {
370        self.debug_types.units()
371    }
372
373    /// Parse the abbreviations for a compilation unit.
374    #[inline]
375    pub fn abbreviations(&self, unit: &UnitHeader<R>) -> Result<Arc<Abbreviations>> {
376        self.abbreviations_cache
377            .get(&self.debug_abbrev, unit.debug_abbrev_offset())
378    }
379
380    /// Return the string offset at the given index.
381    #[inline]
382    pub fn string_offset(
383        &self,
384        unit: &Unit<R>,
385        index: DebugStrOffsetsIndex<R::Offset>,
386    ) -> Result<DebugStrOffset<R::Offset>> {
387        self.debug_str_offsets
388            .get_str_offset(unit.header.format(), unit.str_offsets_base, index)
389    }
390
391    /// Return the string at the given offset in `.debug_str`.
392    #[inline]
393    pub fn string(&self, offset: DebugStrOffset<R::Offset>) -> Result<R> {
394        self.debug_str.get_str(offset)
395    }
396
397    /// Return the string at the given offset in `.debug_line_str`.
398    #[inline]
399    pub fn line_string(&self, offset: DebugLineStrOffset<R::Offset>) -> Result<R> {
400        self.debug_line_str.get_str(offset)
401    }
402
403    /// Return the string at the given offset in the `.debug_str`
404    /// in the supplementary object file.
405    #[inline]
406    pub fn sup_string(&self, offset: DebugStrOffset<R::Offset>) -> Result<R> {
407        if let Some(sup) = self.sup() {
408            sup.debug_str.get_str(offset)
409        } else {
410            Err(Error::ExpectedStringAttributeValue)
411        }
412    }
413
414    /// Return an attribute value as a string slice.
415    ///
416    /// If the attribute value is one of:
417    ///
418    /// - an inline `DW_FORM_string` string
419    /// - a `DW_FORM_strp` reference to an offset into the `.debug_str` section
420    /// - a `DW_FORM_strp_sup` reference to an offset into a supplementary
421    ///   object file
422    /// - a `DW_FORM_line_strp` reference to an offset into the `.debug_line_str`
423    ///   section
424    /// - a `DW_FORM_strx` index into the `.debug_str_offsets` entries for the unit
425    ///
426    /// then return the attribute's string value. Returns an error if the attribute
427    /// value does not have a string form, or if a string form has an invalid value.
428    pub fn attr_string(&self, unit: &Unit<R>, attr: AttributeValue<R>) -> Result<R> {
429        match attr {
430            AttributeValue::String(string) => Ok(string),
431            AttributeValue::DebugStrRef(offset) => self.string(offset),
432            AttributeValue::DebugStrRefSup(offset) => self.sup_string(offset),
433            AttributeValue::DebugLineStrRef(offset) => self.line_string(offset),
434            AttributeValue::DebugStrOffsetsIndex(index) => {
435                let offset = self.string_offset(unit, index)?;
436                self.string(offset)
437            }
438            _ => Err(Error::ExpectedStringAttributeValue),
439        }
440    }
441
442    /// Return the address at the given index.
443    pub fn address(&self, unit: &Unit<R>, index: DebugAddrIndex<R::Offset>) -> Result<u64> {
444        self.debug_addr
445            .get_address(unit.encoding().address_size, unit.addr_base, index)
446    }
447
448    /// Try to return an attribute value as an address.
449    ///
450    /// If the attribute value is one of:
451    ///
452    /// - a `DW_FORM_addr`
453    /// - a `DW_FORM_addrx` index into the `.debug_addr` entries for the unit
454    ///
455    /// then return the address.
456    /// Returns `None` for other forms.
457    pub fn attr_address(&self, unit: &Unit<R>, attr: AttributeValue<R>) -> Result<Option<u64>> {
458        match attr {
459            AttributeValue::Addr(addr) => Ok(Some(addr)),
460            AttributeValue::DebugAddrIndex(index) => self.address(unit, index).map(Some),
461            _ => Ok(None),
462        }
463    }
464
465    /// Return the range list offset for the given raw offset.
466    ///
467    /// This handles adding `DW_AT_GNU_ranges_base` if required.
468    pub fn ranges_offset_from_raw(
469        &self,
470        unit: &Unit<R>,
471        offset: RawRangeListsOffset<R::Offset>,
472    ) -> RangeListsOffset<R::Offset> {
473        if self.file_type == DwarfFileType::Dwo && unit.header.version() < 5 {
474            RangeListsOffset(offset.0.wrapping_add(unit.rnglists_base.0))
475        } else {
476            RangeListsOffset(offset.0)
477        }
478    }
479
480    /// Return the range list offset at the given index.
481    pub fn ranges_offset(
482        &self,
483        unit: &Unit<R>,
484        index: DebugRngListsIndex<R::Offset>,
485    ) -> Result<RangeListsOffset<R::Offset>> {
486        self.ranges
487            .get_offset(unit.encoding(), unit.rnglists_base, index)
488    }
489
490    /// Iterate over the `RangeListEntry`s starting at the given offset.
491    pub fn ranges(
492        &self,
493        unit: &Unit<R>,
494        offset: RangeListsOffset<R::Offset>,
495    ) -> Result<RngListIter<R>> {
496        self.ranges.ranges(
497            offset,
498            unit.encoding(),
499            unit.low_pc,
500            &self.debug_addr,
501            unit.addr_base,
502        )
503    }
504
505    /// Iterate over the `RawRngListEntry`ies starting at the given offset.
506    pub fn raw_ranges(
507        &self,
508        unit: &Unit<R>,
509        offset: RangeListsOffset<R::Offset>,
510    ) -> Result<RawRngListIter<R>> {
511        self.ranges.raw_ranges(offset, unit.encoding())
512    }
513
514    /// Try to return an attribute value as a range list offset.
515    ///
516    /// If the attribute value is one of:
517    ///
518    /// - a `DW_FORM_sec_offset` reference to the `.debug_ranges` or `.debug_rnglists` sections
519    /// - a `DW_FORM_rnglistx` index into the `.debug_rnglists` entries for the unit
520    ///
521    /// then return the range list offset of the range list.
522    /// Returns `None` for other forms.
523    pub fn attr_ranges_offset(
524        &self,
525        unit: &Unit<R>,
526        attr: AttributeValue<R>,
527    ) -> Result<Option<RangeListsOffset<R::Offset>>> {
528        match attr {
529            AttributeValue::RangeListsRef(offset) => {
530                Ok(Some(self.ranges_offset_from_raw(unit, offset)))
531            }
532            AttributeValue::DebugRngListsIndex(index) => self.ranges_offset(unit, index).map(Some),
533            _ => Ok(None),
534        }
535    }
536
537    /// Try to return an attribute value as a range list entry iterator.
538    ///
539    /// If the attribute value is one of:
540    ///
541    /// - a `DW_FORM_sec_offset` reference to the `.debug_ranges` or `.debug_rnglists` sections
542    /// - a `DW_FORM_rnglistx` index into the `.debug_rnglists` entries for the unit
543    ///
544    /// then return an iterator over the entries in the range list.
545    /// Returns `None` for other forms.
546    pub fn attr_ranges(
547        &self,
548        unit: &Unit<R>,
549        attr: AttributeValue<R>,
550    ) -> Result<Option<RngListIter<R>>> {
551        match self.attr_ranges_offset(unit, attr)? {
552            Some(offset) => Ok(Some(self.ranges(unit, offset)?)),
553            None => Ok(None),
554        }
555    }
556
557    /// Return an iterator for the address ranges of a `DebuggingInformationEntry`.
558    ///
559    /// This uses `DW_AT_low_pc`, `DW_AT_high_pc` and `DW_AT_ranges`.
560    pub fn die_ranges(
561        &self,
562        unit: &Unit<R>,
563        entry: &DebuggingInformationEntry<'_, '_, R>,
564    ) -> Result<RangeIter<R>> {
565        let mut low_pc = None;
566        let mut high_pc = None;
567        let mut size = None;
568        let mut attrs = entry.attrs();
569        while let Some(attr) = attrs.next()? {
570            match attr.name() {
571                constants::DW_AT_low_pc => {
572                    low_pc = Some(
573                        self.attr_address(unit, attr.value())?
574                            .ok_or(Error::UnsupportedAttributeForm)?,
575                    );
576                }
577                constants::DW_AT_high_pc => match attr.value() {
578                    AttributeValue::Udata(val) => size = Some(val),
579                    attr => {
580                        high_pc = Some(
581                            self.attr_address(unit, attr)?
582                                .ok_or(Error::UnsupportedAttributeForm)?,
583                        );
584                    }
585                },
586                constants::DW_AT_ranges => {
587                    if let Some(list) = self.attr_ranges(unit, attr.value())? {
588                        return Ok(RangeIter(RangeIterInner::List(list)));
589                    }
590                }
591                _ => {}
592            }
593        }
594        let range = low_pc.and_then(|begin| {
595            let end = size.map(|size| begin + size).or(high_pc);
596            // TODO: perhaps return an error if `end` is `None`
597            end.map(|end| Range { begin, end })
598        });
599        Ok(RangeIter(RangeIterInner::Single(range)))
600    }
601
602    /// Return an iterator for the address ranges of a `Unit`.
603    ///
604    /// This uses `DW_AT_low_pc`, `DW_AT_high_pc` and `DW_AT_ranges` of the
605    /// root `DebuggingInformationEntry`.
606    pub fn unit_ranges(&self, unit: &Unit<R>) -> Result<RangeIter<R>> {
607        let mut cursor = unit.header.entries(&unit.abbreviations);
608        cursor.next_dfs()?;
609        let root = cursor.current().ok_or(Error::MissingUnitDie)?;
610        self.die_ranges(unit, root)
611    }
612
613    /// Return the location list offset at the given index.
614    pub fn locations_offset(
615        &self,
616        unit: &Unit<R>,
617        index: DebugLocListsIndex<R::Offset>,
618    ) -> Result<LocationListsOffset<R::Offset>> {
619        self.locations
620            .get_offset(unit.encoding(), unit.loclists_base, index)
621    }
622
623    /// Iterate over the `LocationListEntry`s starting at the given offset.
624    pub fn locations(
625        &self,
626        unit: &Unit<R>,
627        offset: LocationListsOffset<R::Offset>,
628    ) -> Result<LocListIter<R>> {
629        match self.file_type {
630            DwarfFileType::Main => self.locations.locations(
631                offset,
632                unit.encoding(),
633                unit.low_pc,
634                &self.debug_addr,
635                unit.addr_base,
636            ),
637            DwarfFileType::Dwo => self.locations.locations_dwo(
638                offset,
639                unit.encoding(),
640                unit.low_pc,
641                &self.debug_addr,
642                unit.addr_base,
643            ),
644        }
645    }
646
647    /// Iterate over the raw `LocationListEntry`s starting at the given offset.
648    pub fn raw_locations(
649        &self,
650        unit: &Unit<R>,
651        offset: LocationListsOffset<R::Offset>,
652    ) -> Result<RawLocListIter<R>> {
653        match self.file_type {
654            DwarfFileType::Main => self.locations.raw_locations(offset, unit.encoding()),
655            DwarfFileType::Dwo => self.locations.raw_locations_dwo(offset, unit.encoding()),
656        }
657    }
658
659    /// Try to return an attribute value as a location list offset.
660    ///
661    /// If the attribute value is one of:
662    ///
663    /// - a `DW_FORM_sec_offset` reference to the `.debug_loc` or `.debug_loclists` sections
664    /// - a `DW_FORM_loclistx` index into the `.debug_loclists` entries for the unit
665    ///
666    /// then return the location list offset of the location list.
667    /// Returns `None` for other forms.
668    pub fn attr_locations_offset(
669        &self,
670        unit: &Unit<R>,
671        attr: AttributeValue<R>,
672    ) -> Result<Option<LocationListsOffset<R::Offset>>> {
673        match attr {
674            AttributeValue::LocationListsRef(offset) => Ok(Some(offset)),
675            AttributeValue::DebugLocListsIndex(index) => {
676                self.locations_offset(unit, index).map(Some)
677            }
678            _ => Ok(None),
679        }
680    }
681
682    /// Try to return an attribute value as a location list entry iterator.
683    ///
684    /// If the attribute value is one of:
685    ///
686    /// - a `DW_FORM_sec_offset` reference to the `.debug_loc` or `.debug_loclists` sections
687    /// - a `DW_FORM_loclistx` index into the `.debug_loclists` entries for the unit
688    ///
689    /// then return an iterator over the entries in the location list.
690    /// Returns `None` for other forms.
691    pub fn attr_locations(
692        &self,
693        unit: &Unit<R>,
694        attr: AttributeValue<R>,
695    ) -> Result<Option<LocListIter<R>>> {
696        match self.attr_locations_offset(unit, attr)? {
697            Some(offset) => Ok(Some(self.locations(unit, offset)?)),
698            None => Ok(None),
699        }
700    }
701
702    /// Call `Reader::lookup_offset_id` for each section, and return the first match.
703    ///
704    /// The first element of the tuple is `true` for supplementary sections.
705    pub fn lookup_offset_id(&self, id: ReaderOffsetId) -> Option<(bool, SectionId, R::Offset)> {
706        None.or_else(|| self.debug_abbrev.lookup_offset_id(id))
707            .or_else(|| self.debug_addr.lookup_offset_id(id))
708            .or_else(|| self.debug_aranges.lookup_offset_id(id))
709            .or_else(|| self.debug_info.lookup_offset_id(id))
710            .or_else(|| self.debug_line.lookup_offset_id(id))
711            .or_else(|| self.debug_line_str.lookup_offset_id(id))
712            .or_else(|| self.debug_str.lookup_offset_id(id))
713            .or_else(|| self.debug_str_offsets.lookup_offset_id(id))
714            .or_else(|| self.debug_types.lookup_offset_id(id))
715            .or_else(|| self.locations.lookup_offset_id(id))
716            .or_else(|| self.ranges.lookup_offset_id(id))
717            .map(|(id, offset)| (false, id, offset))
718            .or_else(|| {
719                self.sup()
720                    .and_then(|sup| sup.lookup_offset_id(id))
721                    .map(|(_, id, offset)| (true, id, offset))
722            })
723    }
724
725    /// Returns a string representation of the given error.
726    ///
727    /// This uses information from the DWARF sections to provide more information in some cases.
728    pub fn format_error(&self, err: Error) -> String {
729        #[allow(clippy::single_match)]
730        match err {
731            Error::UnexpectedEof(id) => match self.lookup_offset_id(id) {
732                Some((sup, section, offset)) => {
733                    return format!(
734                        "{} at {}{}+0x{:x}",
735                        err,
736                        section.name(),
737                        if sup { "(sup)" } else { "" },
738                        offset.into_u64(),
739                    );
740                }
741                None => {}
742            },
743            _ => {}
744        }
745        err.description().into()
746    }
747
748    /// Return a fallible iterator over the macro information from `.debug_macinfo` for the given offset.
749    pub fn macinfo(&self, offset: DebugMacinfoOffset<R::Offset>) -> Result<MacroIter<R>> {
750        self.debug_macinfo.get_macinfo(offset)
751    }
752
753    /// Return a fallible iterator over the macro information from `.debug_macro` for the given offset.
754    pub fn macros(&self, offset: DebugMacroOffset<R::Offset>) -> Result<MacroIter<R>> {
755        self.debug_macro.get_macros(offset)
756    }
757}
758
759impl<R: Clone> Dwarf<R> {
760    /// Assuming `self` was loaded from a .dwo, take the appropriate
761    /// sections from `parent` (which contains the skeleton unit for this
762    /// dwo) such as `.debug_addr` and merge them into this `Dwarf`.
763    pub fn make_dwo(&mut self, parent: &Dwarf<R>) {
764        self.file_type = DwarfFileType::Dwo;
765        // These sections are always taken from the parent file and not the dwo.
766        self.debug_addr = parent.debug_addr.clone();
767        // .debug_rnglists comes from the DWO, .debug_ranges comes from the
768        // parent file.
769        self.ranges
770            .set_debug_ranges(parent.ranges.debug_ranges().clone());
771        self.sup.clone_from(&parent.sup);
772    }
773}
774
775/// The sections from a `.dwp` file.
776///
777/// This is useful for storing sections when `T` does not implement `Reader`.
778/// It can be used to create a `DwarfPackage` that references the data in `self`.
779/// If `T` does implement `Reader`, then use `DwarfPackage` directly.
780///
781/// ## Example Usage
782///
783/// It can be useful to load DWARF sections into owned data structures,
784/// such as `Vec`. However, we do not implement the `Reader` trait
785/// for `Vec`, because it would be very inefficient, but this trait
786/// is required for all of the methods that parse the DWARF data.
787/// So we first load the DWARF sections into `Vec`s, and then use
788/// `borrow` to create `Reader`s that reference the data.
789///
790/// ```rust,no_run
791/// # fn example() -> Result<(), gimli::Error> {
792/// # let loader = |name| -> Result<_, gimli::Error> { unimplemented!() };
793/// // Read the DWARF sections into `Vec`s with whatever object loader you're using.
794/// let dwp_sections: gimli::DwarfPackageSections<Vec<u8>> = gimli::DwarfPackageSections::load(loader)?;
795/// // Create references to the DWARF sections.
796/// let dwp: gimli::DwarfPackage<_> = dwp_sections.borrow(
797///     |section| gimli::EndianSlice::new(&section, gimli::LittleEndian),
798///     gimli::EndianSlice::new(&[], gimli::LittleEndian),
799/// )?;
800/// # unreachable!()
801/// # }
802/// ```
803#[derive(Debug, Default)]
804pub struct DwarfPackageSections<T> {
805    /// The `.debug_cu_index` section.
806    pub cu_index: DebugCuIndex<T>,
807    /// The `.debug_tu_index` section.
808    pub tu_index: DebugTuIndex<T>,
809    /// The `.debug_abbrev.dwo` section.
810    pub debug_abbrev: DebugAbbrev<T>,
811    /// The `.debug_info.dwo` section.
812    pub debug_info: DebugInfo<T>,
813    /// The `.debug_line.dwo` section.
814    pub debug_line: DebugLine<T>,
815    /// The `.debug_str.dwo` section.
816    pub debug_str: DebugStr<T>,
817    /// The `.debug_str_offsets.dwo` section.
818    pub debug_str_offsets: DebugStrOffsets<T>,
819    /// The `.debug_loc.dwo` section.
820    ///
821    /// Only present when using GNU split-dwarf extension to DWARF 4.
822    pub debug_loc: DebugLoc<T>,
823    /// The `.debug_loclists.dwo` section.
824    pub debug_loclists: DebugLocLists<T>,
825    /// The `.debug_rnglists.dwo` section.
826    pub debug_rnglists: DebugRngLists<T>,
827    /// The `.debug_types.dwo` section.
828    ///
829    /// Only present when using GNU split-dwarf extension to DWARF 4.
830    pub debug_types: DebugTypes<T>,
831}
832
833impl<T> DwarfPackageSections<T> {
834    /// Try to load the `.dwp` sections using the given loader function.
835    ///
836    /// `section` loads a DWARF section from the object file.
837    /// It should return an empty section if the section does not exist.
838    pub fn load<F, E>(mut section: F) -> core::result::Result<Self, E>
839    where
840        F: FnMut(SectionId) -> core::result::Result<T, E>,
841        E: From<Error>,
842    {
843        Ok(DwarfPackageSections {
844            // Section types are inferred.
845            cu_index: Section::load(&mut section)?,
846            tu_index: Section::load(&mut section)?,
847            debug_abbrev: Section::load(&mut section)?,
848            debug_info: Section::load(&mut section)?,
849            debug_line: Section::load(&mut section)?,
850            debug_str: Section::load(&mut section)?,
851            debug_str_offsets: Section::load(&mut section)?,
852            debug_loc: Section::load(&mut section)?,
853            debug_loclists: Section::load(&mut section)?,
854            debug_rnglists: Section::load(&mut section)?,
855            debug_types: Section::load(&mut section)?,
856        })
857    }
858
859    /// Create a `DwarfPackage` structure that references the data in `self`.
860    pub fn borrow<'a, F, R>(&'a self, mut borrow: F, empty: R) -> Result<DwarfPackage<R>>
861    where
862        F: FnMut(&'a T) -> R,
863        R: Reader,
864    {
865        DwarfPackage::from_sections(
866            DwarfPackageSections {
867                cu_index: self.cu_index.borrow(&mut borrow),
868                tu_index: self.tu_index.borrow(&mut borrow),
869                debug_abbrev: self.debug_abbrev.borrow(&mut borrow),
870                debug_info: self.debug_info.borrow(&mut borrow),
871                debug_line: self.debug_line.borrow(&mut borrow),
872                debug_str: self.debug_str.borrow(&mut borrow),
873                debug_str_offsets: self.debug_str_offsets.borrow(&mut borrow),
874                debug_loc: self.debug_loc.borrow(&mut borrow),
875                debug_loclists: self.debug_loclists.borrow(&mut borrow),
876                debug_rnglists: self.debug_rnglists.borrow(&mut borrow),
877                debug_types: self.debug_types.borrow(&mut borrow),
878            },
879            empty,
880        )
881    }
882}
883
884/// The sections from a `.dwp` file, with parsed indices.
885#[derive(Debug)]
886pub struct DwarfPackage<R: Reader> {
887    /// The compilation unit index in the `.debug_cu_index` section.
888    pub cu_index: UnitIndex<R>,
889
890    /// The type unit index in the `.debug_tu_index` section.
891    pub tu_index: UnitIndex<R>,
892
893    /// The `.debug_abbrev.dwo` section.
894    pub debug_abbrev: DebugAbbrev<R>,
895
896    /// The `.debug_info.dwo` section.
897    pub debug_info: DebugInfo<R>,
898
899    /// The `.debug_line.dwo` section.
900    pub debug_line: DebugLine<R>,
901
902    /// The `.debug_str.dwo` section.
903    pub debug_str: DebugStr<R>,
904
905    /// The `.debug_str_offsets.dwo` section.
906    pub debug_str_offsets: DebugStrOffsets<R>,
907
908    /// The `.debug_loc.dwo` section.
909    ///
910    /// Only present when using GNU split-dwarf extension to DWARF 4.
911    pub debug_loc: DebugLoc<R>,
912
913    /// The `.debug_loclists.dwo` section.
914    pub debug_loclists: DebugLocLists<R>,
915
916    /// The `.debug_rnglists.dwo` section.
917    pub debug_rnglists: DebugRngLists<R>,
918
919    /// The `.debug_types.dwo` section.
920    ///
921    /// Only present when using GNU split-dwarf extension to DWARF 4.
922    pub debug_types: DebugTypes<R>,
923
924    /// An empty section.
925    ///
926    /// Used when creating `Dwarf<R>`.
927    pub empty: R,
928}
929
930impl<R: Reader> DwarfPackage<R> {
931    /// Try to load the `.dwp` sections using the given loader function.
932    ///
933    /// `section` loads a DWARF section from the object file.
934    /// It should return an empty section if the section does not exist.
935    pub fn load<F, E>(section: F, empty: R) -> core::result::Result<Self, E>
936    where
937        F: FnMut(SectionId) -> core::result::Result<R, E>,
938        E: From<Error>,
939    {
940        let sections = DwarfPackageSections::load(section)?;
941        Ok(Self::from_sections(sections, empty)?)
942    }
943
944    /// Create a `DwarfPackage` structure from the given sections.
945    fn from_sections(sections: DwarfPackageSections<R>, empty: R) -> Result<Self> {
946        Ok(DwarfPackage {
947            cu_index: sections.cu_index.index()?,
948            tu_index: sections.tu_index.index()?,
949            debug_abbrev: sections.debug_abbrev,
950            debug_info: sections.debug_info,
951            debug_line: sections.debug_line,
952            debug_str: sections.debug_str,
953            debug_str_offsets: sections.debug_str_offsets,
954            debug_loc: sections.debug_loc,
955            debug_loclists: sections.debug_loclists,
956            debug_rnglists: sections.debug_rnglists,
957            debug_types: sections.debug_types,
958            empty,
959        })
960    }
961
962    /// Find the compilation unit with the given DWO identifier and return its section
963    /// contributions.
964    ///
965    /// ## Example Usage
966    ///
967    /// ```rust,no_run
968    /// # fn example<R: gimli::Reader>(
969    /// #        dwarf: &gimli::Dwarf<R>,
970    /// #        dwp: &gimli::DwarfPackage<R>,
971    /// #        dwo_id: gimli::DwoId,
972    /// # ) -> Result<(), gimli::Error> {
973    /// if let Some(dwo) = dwp.find_cu(dwo_id, dwarf)? {
974    ///    let dwo_header = dwo.units().next()?.expect("DWO should have one unit");
975    ///    let dwo_unit = dwo.unit(dwo_header)?;
976    ///    // Do something with `dwo_unit`.
977    /// }
978    /// # unreachable!()
979    /// # }
980    pub fn find_cu(&self, id: DwoId, parent: &Dwarf<R>) -> Result<Option<Dwarf<R>>> {
981        let row = match self.cu_index.find(id.0) {
982            Some(row) => row,
983            None => return Ok(None),
984        };
985        self.cu_sections(row, parent).map(Some)
986    }
987
988    /// Find the type unit with the given type signature and return its section
989    /// contributions.
990    pub fn find_tu(
991        &self,
992        signature: DebugTypeSignature,
993        parent: &Dwarf<R>,
994    ) -> Result<Option<Dwarf<R>>> {
995        let row = match self.tu_index.find(signature.0) {
996            Some(row) => row,
997            None => return Ok(None),
998        };
999        self.tu_sections(row, parent).map(Some)
1000    }
1001
1002    /// Return the section contributions of the compilation unit at the given index.
1003    ///
1004    /// The index must be in the range `1..cu_index.unit_count`.
1005    ///
1006    /// This function should only be needed by low level parsers.
1007    pub fn cu_sections(&self, index: u32, parent: &Dwarf<R>) -> Result<Dwarf<R>> {
1008        self.sections(self.cu_index.sections(index)?, parent)
1009    }
1010
1011    /// Return the section contributions of the compilation unit at the given index.
1012    ///
1013    /// The index must be in the range `1..tu_index.unit_count`.
1014    ///
1015    /// This function should only be needed by low level parsers.
1016    pub fn tu_sections(&self, index: u32, parent: &Dwarf<R>) -> Result<Dwarf<R>> {
1017        self.sections(self.tu_index.sections(index)?, parent)
1018    }
1019
1020    /// Return the section contributions of a unit.
1021    ///
1022    /// This function should only be needed by low level parsers.
1023    pub fn sections(
1024        &self,
1025        sections: UnitIndexSectionIterator<'_, R>,
1026        parent: &Dwarf<R>,
1027    ) -> Result<Dwarf<R>> {
1028        let mut abbrev_offset = 0;
1029        let mut abbrev_size = 0;
1030        let mut info_offset = 0;
1031        let mut info_size = 0;
1032        let mut line_offset = 0;
1033        let mut line_size = 0;
1034        let mut loc_offset = 0;
1035        let mut loc_size = 0;
1036        let mut loclists_offset = 0;
1037        let mut loclists_size = 0;
1038        let mut str_offsets_offset = 0;
1039        let mut str_offsets_size = 0;
1040        let mut rnglists_offset = 0;
1041        let mut rnglists_size = 0;
1042        let mut types_offset = 0;
1043        let mut types_size = 0;
1044        for section in sections {
1045            match section.section {
1046                IndexSectionId::DebugAbbrev => {
1047                    abbrev_offset = section.offset;
1048                    abbrev_size = section.size;
1049                }
1050                IndexSectionId::DebugInfo => {
1051                    info_offset = section.offset;
1052                    info_size = section.size;
1053                }
1054                IndexSectionId::DebugLine => {
1055                    line_offset = section.offset;
1056                    line_size = section.size;
1057                }
1058                IndexSectionId::DebugLoc => {
1059                    loc_offset = section.offset;
1060                    loc_size = section.size;
1061                }
1062                IndexSectionId::DebugLocLists => {
1063                    loclists_offset = section.offset;
1064                    loclists_size = section.size;
1065                }
1066                IndexSectionId::DebugStrOffsets => {
1067                    str_offsets_offset = section.offset;
1068                    str_offsets_size = section.size;
1069                }
1070                IndexSectionId::DebugRngLists => {
1071                    rnglists_offset = section.offset;
1072                    rnglists_size = section.size;
1073                }
1074                IndexSectionId::DebugTypes => {
1075                    types_offset = section.offset;
1076                    types_size = section.size;
1077                }
1078                IndexSectionId::DebugMacro | IndexSectionId::DebugMacinfo => {
1079                    // These are valid but we can't parse these yet.
1080                }
1081            }
1082        }
1083
1084        let debug_abbrev = self.debug_abbrev.dwp_range(abbrev_offset, abbrev_size)?;
1085        let debug_info = self.debug_info.dwp_range(info_offset, info_size)?;
1086        let debug_line = self.debug_line.dwp_range(line_offset, line_size)?;
1087        let debug_loc = self.debug_loc.dwp_range(loc_offset, loc_size)?;
1088        let debug_loclists = self
1089            .debug_loclists
1090            .dwp_range(loclists_offset, loclists_size)?;
1091        let debug_str_offsets = self
1092            .debug_str_offsets
1093            .dwp_range(str_offsets_offset, str_offsets_size)?;
1094        let debug_rnglists = self
1095            .debug_rnglists
1096            .dwp_range(rnglists_offset, rnglists_size)?;
1097        let debug_types = self.debug_types.dwp_range(types_offset, types_size)?;
1098
1099        let debug_str = self.debug_str.clone();
1100
1101        let debug_addr = parent.debug_addr.clone();
1102        let debug_ranges = parent.ranges.debug_ranges().clone();
1103
1104        let debug_aranges = self.empty.clone().into();
1105        let debug_line_str = self.empty.clone().into();
1106        let debug_macinfo = self.empty.clone().into();
1107        let debug_macro = self.empty.clone().into();
1108
1109        Ok(Dwarf {
1110            debug_abbrev,
1111            debug_addr,
1112            debug_aranges,
1113            debug_info,
1114            debug_line,
1115            debug_line_str,
1116            debug_macinfo,
1117            debug_macro,
1118            debug_str,
1119            debug_str_offsets,
1120            debug_types,
1121            locations: LocationLists::new(debug_loc, debug_loclists),
1122            ranges: RangeLists::new(debug_ranges, debug_rnglists),
1123            file_type: DwarfFileType::Dwo,
1124            sup: parent.sup.clone(),
1125            abbreviations_cache: AbbreviationsCache::new(),
1126        })
1127    }
1128}
1129
1130/// All of the commonly used information for a unit in the `.debug_info` or `.debug_types`
1131/// sections.
1132#[derive(Debug)]
1133pub struct Unit<R, Offset = <R as Reader>::Offset>
1134where
1135    R: Reader<Offset = Offset>,
1136    Offset: ReaderOffset,
1137{
1138    /// The header of the unit.
1139    pub header: UnitHeader<R, Offset>,
1140
1141    /// The parsed abbreviations for the unit.
1142    pub abbreviations: Arc<Abbreviations>,
1143
1144    /// The `DW_AT_name` attribute of the unit.
1145    pub name: Option<R>,
1146
1147    /// The `DW_AT_comp_dir` attribute of the unit.
1148    pub comp_dir: Option<R>,
1149
1150    /// The `DW_AT_low_pc` attribute of the unit. Defaults to 0.
1151    pub low_pc: u64,
1152
1153    /// The `DW_AT_str_offsets_base` attribute of the unit. Defaults to 0.
1154    pub str_offsets_base: DebugStrOffsetsBase<Offset>,
1155
1156    /// The `DW_AT_addr_base` attribute of the unit. Defaults to 0.
1157    pub addr_base: DebugAddrBase<Offset>,
1158
1159    /// The `DW_AT_loclists_base` attribute of the unit. Defaults to 0.
1160    pub loclists_base: DebugLocListsBase<Offset>,
1161
1162    /// The `DW_AT_rnglists_base` attribute of the unit. Defaults to 0.
1163    pub rnglists_base: DebugRngListsBase<Offset>,
1164
1165    /// The line number program of the unit.
1166    pub line_program: Option<IncompleteLineProgram<R, Offset>>,
1167
1168    /// The DWO ID of a skeleton unit or split compilation unit.
1169    pub dwo_id: Option<DwoId>,
1170}
1171
1172impl<R: Reader> Unit<R> {
1173    /// Construct a new `Unit` from the given unit header.
1174    #[inline]
1175    pub fn new(dwarf: &Dwarf<R>, header: UnitHeader<R>) -> Result<Self> {
1176        let abbreviations = dwarf.abbreviations(&header)?;
1177        Self::new_with_abbreviations(dwarf, header, abbreviations)
1178    }
1179
1180    /// Construct a new `Unit` from the given unit header and abbreviations.
1181    ///
1182    /// The abbreviations for this call can be obtained using `dwarf.abbreviations(&header)`.
1183    /// The caller may implement caching to reuse the `Abbreviations` across units with the
1184    /// same `header.debug_abbrev_offset()` value.
1185    #[inline]
1186    pub fn new_with_abbreviations(
1187        dwarf: &Dwarf<R>,
1188        header: UnitHeader<R>,
1189        abbreviations: Arc<Abbreviations>,
1190    ) -> Result<Self> {
1191        let mut unit = Unit {
1192            abbreviations,
1193            name: None,
1194            comp_dir: None,
1195            low_pc: 0,
1196            str_offsets_base: DebugStrOffsetsBase::default_for_encoding_and_file(
1197                header.encoding(),
1198                dwarf.file_type,
1199            ),
1200            // NB: Because the .debug_addr section never lives in a .dwo, we can assume its base is always 0 or provided.
1201            addr_base: DebugAddrBase(R::Offset::from_u8(0)),
1202            loclists_base: DebugLocListsBase::default_for_encoding_and_file(
1203                header.encoding(),
1204                dwarf.file_type,
1205            ),
1206            rnglists_base: DebugRngListsBase::default_for_encoding_and_file(
1207                header.encoding(),
1208                dwarf.file_type,
1209            ),
1210            line_program: None,
1211            dwo_id: match header.type_() {
1212                UnitType::Skeleton(dwo_id) | UnitType::SplitCompilation(dwo_id) => Some(dwo_id),
1213                _ => None,
1214            },
1215            header,
1216        };
1217        let mut name = None;
1218        let mut comp_dir = None;
1219        let mut line_program_offset = None;
1220        let mut low_pc_attr = None;
1221
1222        {
1223            let mut cursor = unit.header.entries(&unit.abbreviations);
1224            cursor.next_dfs()?;
1225            let root = cursor.current().ok_or(Error::MissingUnitDie)?;
1226            let mut attrs = root.attrs();
1227            while let Some(attr) = attrs.next()? {
1228                match attr.name() {
1229                    constants::DW_AT_name => {
1230                        name = Some(attr.value());
1231                    }
1232                    constants::DW_AT_comp_dir => {
1233                        comp_dir = Some(attr.value());
1234                    }
1235                    constants::DW_AT_low_pc => {
1236                        low_pc_attr = Some(attr.value());
1237                    }
1238                    constants::DW_AT_stmt_list => {
1239                        if let AttributeValue::DebugLineRef(offset) = attr.value() {
1240                            line_program_offset = Some(offset);
1241                        }
1242                    }
1243                    constants::DW_AT_str_offsets_base => {
1244                        if let AttributeValue::DebugStrOffsetsBase(base) = attr.value() {
1245                            unit.str_offsets_base = base;
1246                        }
1247                    }
1248                    constants::DW_AT_addr_base | constants::DW_AT_GNU_addr_base => {
1249                        if let AttributeValue::DebugAddrBase(base) = attr.value() {
1250                            unit.addr_base = base;
1251                        }
1252                    }
1253                    constants::DW_AT_loclists_base => {
1254                        if let AttributeValue::DebugLocListsBase(base) = attr.value() {
1255                            unit.loclists_base = base;
1256                        }
1257                    }
1258                    constants::DW_AT_rnglists_base | constants::DW_AT_GNU_ranges_base => {
1259                        if let AttributeValue::DebugRngListsBase(base) = attr.value() {
1260                            unit.rnglists_base = base;
1261                        }
1262                    }
1263                    constants::DW_AT_GNU_dwo_id => {
1264                        if unit.dwo_id.is_none() {
1265                            if let AttributeValue::DwoId(dwo_id) = attr.value() {
1266                                unit.dwo_id = Some(dwo_id);
1267                            }
1268                        }
1269                    }
1270                    _ => {}
1271                }
1272            }
1273        }
1274
1275        unit.name = match name {
1276            Some(val) => dwarf.attr_string(&unit, val).ok(),
1277            None => None,
1278        };
1279        unit.comp_dir = match comp_dir {
1280            Some(val) => dwarf.attr_string(&unit, val).ok(),
1281            None => None,
1282        };
1283        unit.line_program = match line_program_offset {
1284            Some(offset) => Some(dwarf.debug_line.program(
1285                offset,
1286                unit.header.address_size(),
1287                unit.comp_dir.clone(),
1288                unit.name.clone(),
1289            )?),
1290            None => None,
1291        };
1292        if let Some(low_pc_attr) = low_pc_attr {
1293            if let Some(addr) = dwarf.attr_address(&unit, low_pc_attr)? {
1294                unit.low_pc = addr;
1295            }
1296        }
1297        Ok(unit)
1298    }
1299
1300    /// Return a reference to this unit and its associated `Dwarf`.
1301    pub fn unit_ref<'a>(&'a self, dwarf: &'a Dwarf<R>) -> UnitRef<'a, R> {
1302        UnitRef::new(dwarf, self)
1303    }
1304
1305    /// Return the encoding parameters for this unit.
1306    #[inline]
1307    pub fn encoding(&self) -> Encoding {
1308        self.header.encoding()
1309    }
1310
1311    /// Read the `DebuggingInformationEntry` at the given offset.
1312    pub fn entry(
1313        &self,
1314        offset: UnitOffset<R::Offset>,
1315    ) -> Result<DebuggingInformationEntry<'_, '_, R>> {
1316        self.header.entry(&self.abbreviations, offset)
1317    }
1318
1319    /// Navigate this unit's `DebuggingInformationEntry`s.
1320    #[inline]
1321    pub fn entries(&self) -> EntriesCursor<'_, '_, R> {
1322        self.header.entries(&self.abbreviations)
1323    }
1324
1325    /// Navigate this unit's `DebuggingInformationEntry`s
1326    /// starting at the given offset.
1327    #[inline]
1328    pub fn entries_at_offset(
1329        &self,
1330        offset: UnitOffset<R::Offset>,
1331    ) -> Result<EntriesCursor<'_, '_, R>> {
1332        self.header.entries_at_offset(&self.abbreviations, offset)
1333    }
1334
1335    /// Navigate this unit's `DebuggingInformationEntry`s as a tree
1336    /// starting at the given offset.
1337    #[inline]
1338    pub fn entries_tree(
1339        &self,
1340        offset: Option<UnitOffset<R::Offset>>,
1341    ) -> Result<EntriesTree<'_, '_, R>> {
1342        self.header.entries_tree(&self.abbreviations, offset)
1343    }
1344
1345    /// Read the raw data that defines the Debugging Information Entries.
1346    #[inline]
1347    pub fn entries_raw(
1348        &self,
1349        offset: Option<UnitOffset<R::Offset>>,
1350    ) -> Result<EntriesRaw<'_, '_, R>> {
1351        self.header.entries_raw(&self.abbreviations, offset)
1352    }
1353
1354    /// Copy attributes that are subject to relocation from another unit. This is intended
1355    /// to be used to copy attributes from a skeleton compilation unit to the corresponding
1356    /// split compilation unit.
1357    pub fn copy_relocated_attributes(&mut self, other: &Unit<R>) {
1358        self.low_pc = other.low_pc;
1359        self.addr_base = other.addr_base;
1360        if self.header.version() < 5 {
1361            self.rnglists_base = other.rnglists_base;
1362        }
1363    }
1364
1365    /// Find the dwo name (if any) for this unit, automatically handling the differences
1366    /// between the standardized DWARF 5 split DWARF format and the pre-DWARF 5 GNU
1367    /// extension.
1368    ///
1369    /// The returned value is relative to this unit's `comp_dir`.
1370    pub fn dwo_name(&self) -> Result<Option<AttributeValue<R>>> {
1371        let mut entries = self.entries();
1372        entries.next_entry()?;
1373        let entry = entries.current().ok_or(Error::MissingUnitDie)?;
1374        if self.header.version() < 5 {
1375            entry.attr_value(constants::DW_AT_GNU_dwo_name)
1376        } else {
1377            entry.attr_value(constants::DW_AT_dwo_name)
1378        }
1379    }
1380}
1381
1382/// A reference to a `Unit` and its associated `Dwarf`.
1383///
1384/// These often need to be passed around together, so this struct makes that easier.
1385///
1386/// It implements `Deref` to `Unit`, so you can use it as if it were a `Unit`.
1387/// It also implements methods that correspond to methods on `Dwarf` that take a `Unit`.
1388#[derive(Debug)]
1389pub struct UnitRef<'a, R: Reader> {
1390    /// The `Dwarf` that contains the unit.
1391    pub dwarf: &'a Dwarf<R>,
1392
1393    /// The `Unit` being referenced.
1394    pub unit: &'a Unit<R>,
1395}
1396
1397impl<'a, R: Reader> Clone for UnitRef<'a, R> {
1398    fn clone(&self) -> Self {
1399        *self
1400    }
1401}
1402
1403impl<'a, R: Reader> Copy for UnitRef<'a, R> {}
1404
1405impl<'a, R: Reader> core::ops::Deref for UnitRef<'a, R> {
1406    type Target = Unit<R>;
1407
1408    fn deref(&self) -> &Self::Target {
1409        self.unit
1410    }
1411}
1412
1413impl<'a, R: Reader> UnitRef<'a, R> {
1414    /// Construct a new `UnitRef` from a `Dwarf` and a `Unit`.
1415    pub fn new(dwarf: &'a Dwarf<R>, unit: &'a Unit<R>) -> Self {
1416        UnitRef { dwarf, unit }
1417    }
1418
1419    /// Return the string offset at the given index.
1420    #[inline]
1421    pub fn string_offset(
1422        &self,
1423        index: DebugStrOffsetsIndex<R::Offset>,
1424    ) -> Result<DebugStrOffset<R::Offset>> {
1425        self.dwarf.string_offset(self.unit, index)
1426    }
1427
1428    /// Return the string at the given offset in `.debug_str`.
1429    #[inline]
1430    pub fn string(&self, offset: DebugStrOffset<R::Offset>) -> Result<R> {
1431        self.dwarf.string(offset)
1432    }
1433
1434    /// Return the string at the given offset in `.debug_line_str`.
1435    #[inline]
1436    pub fn line_string(&self, offset: DebugLineStrOffset<R::Offset>) -> Result<R> {
1437        self.dwarf.line_string(offset)
1438    }
1439
1440    /// Return the string at the given offset in the `.debug_str`
1441    /// in the supplementary object file.
1442    #[inline]
1443    pub fn sup_string(&self, offset: DebugStrOffset<R::Offset>) -> Result<R> {
1444        self.dwarf.sup_string(offset)
1445    }
1446
1447    /// Return an attribute value as a string slice.
1448    ///
1449    /// See [`Dwarf::attr_string`] for more information.
1450    pub fn attr_string(&self, attr: AttributeValue<R>) -> Result<R> {
1451        self.dwarf.attr_string(self.unit, attr)
1452    }
1453
1454    /// Return the address at the given index.
1455    pub fn address(&self, index: DebugAddrIndex<R::Offset>) -> Result<u64> {
1456        self.dwarf.address(self.unit, index)
1457    }
1458
1459    /// Try to return an attribute value as an address.
1460    ///
1461    /// See [`Dwarf::attr_address`] for more information.
1462    pub fn attr_address(&self, attr: AttributeValue<R>) -> Result<Option<u64>> {
1463        self.dwarf.attr_address(self.unit, attr)
1464    }
1465
1466    /// Return the range list offset for the given raw offset.
1467    ///
1468    /// This handles adding `DW_AT_GNU_ranges_base` if required.
1469    pub fn ranges_offset_from_raw(
1470        &self,
1471        offset: RawRangeListsOffset<R::Offset>,
1472    ) -> RangeListsOffset<R::Offset> {
1473        self.dwarf.ranges_offset_from_raw(self.unit, offset)
1474    }
1475
1476    /// Return the range list offset at the given index.
1477    pub fn ranges_offset(
1478        &self,
1479        index: DebugRngListsIndex<R::Offset>,
1480    ) -> Result<RangeListsOffset<R::Offset>> {
1481        self.dwarf.ranges_offset(self.unit, index)
1482    }
1483
1484    /// Iterate over the `RangeListEntry`s starting at the given offset.
1485    pub fn ranges(&self, offset: RangeListsOffset<R::Offset>) -> Result<RngListIter<R>> {
1486        self.dwarf.ranges(self.unit, offset)
1487    }
1488
1489    /// Iterate over the `RawRngListEntry`ies starting at the given offset.
1490    pub fn raw_ranges(&self, offset: RangeListsOffset<R::Offset>) -> Result<RawRngListIter<R>> {
1491        self.dwarf.raw_ranges(self.unit, offset)
1492    }
1493
1494    /// Try to return an attribute value as a range list offset.
1495    ///
1496    /// See [`Dwarf::attr_ranges_offset`] for more information.
1497    pub fn attr_ranges_offset(
1498        &self,
1499        attr: AttributeValue<R>,
1500    ) -> Result<Option<RangeListsOffset<R::Offset>>> {
1501        self.dwarf.attr_ranges_offset(self.unit, attr)
1502    }
1503
1504    /// Try to return an attribute value as a range list entry iterator.
1505    ///
1506    /// See [`Dwarf::attr_ranges`] for more information.
1507    pub fn attr_ranges(&self, attr: AttributeValue<R>) -> Result<Option<RngListIter<R>>> {
1508        self.dwarf.attr_ranges(self.unit, attr)
1509    }
1510
1511    /// Return an iterator for the address ranges of a `DebuggingInformationEntry`.
1512    ///
1513    /// This uses `DW_AT_low_pc`, `DW_AT_high_pc` and `DW_AT_ranges`.
1514    pub fn die_ranges(&self, entry: &DebuggingInformationEntry<'_, '_, R>) -> Result<RangeIter<R>> {
1515        self.dwarf.die_ranges(self.unit, entry)
1516    }
1517
1518    /// Return an iterator for the address ranges of the `Unit`.
1519    ///
1520    /// This uses `DW_AT_low_pc`, `DW_AT_high_pc` and `DW_AT_ranges` of the
1521    /// root `DebuggingInformationEntry`.
1522    pub fn unit_ranges(&self) -> Result<RangeIter<R>> {
1523        self.dwarf.unit_ranges(self.unit)
1524    }
1525
1526    /// Return the location list offset at the given index.
1527    pub fn locations_offset(
1528        &self,
1529        index: DebugLocListsIndex<R::Offset>,
1530    ) -> Result<LocationListsOffset<R::Offset>> {
1531        self.dwarf.locations_offset(self.unit, index)
1532    }
1533
1534    /// Iterate over the `LocationListEntry`s starting at the given offset.
1535    pub fn locations(&self, offset: LocationListsOffset<R::Offset>) -> Result<LocListIter<R>> {
1536        self.dwarf.locations(self.unit, offset)
1537    }
1538
1539    /// Iterate over the raw `LocationListEntry`s starting at the given offset.
1540    pub fn raw_locations(
1541        &self,
1542        offset: LocationListsOffset<R::Offset>,
1543    ) -> Result<RawLocListIter<R>> {
1544        self.dwarf.raw_locations(self.unit, offset)
1545    }
1546
1547    /// Try to return an attribute value as a location list offset.
1548    ///
1549    /// See [`Dwarf::attr_locations_offset`] for more information.
1550    pub fn attr_locations_offset(
1551        &self,
1552        attr: AttributeValue<R>,
1553    ) -> Result<Option<LocationListsOffset<R::Offset>>> {
1554        self.dwarf.attr_locations_offset(self.unit, attr)
1555    }
1556
1557    /// Try to return an attribute value as a location list entry iterator.
1558    ///
1559    /// See [`Dwarf::attr_locations`] for more information.
1560    pub fn attr_locations(&self, attr: AttributeValue<R>) -> Result<Option<LocListIter<R>>> {
1561        self.dwarf.attr_locations(self.unit, attr)
1562    }
1563
1564    /// Try to return an iterator for the list of macros at the given `.debug_macinfo` offset.
1565    pub fn macinfo(&self, offset: DebugMacinfoOffset<R::Offset>) -> Result<MacroIter<R>> {
1566        self.dwarf.macinfo(offset)
1567    }
1568
1569    /// Try to return an iterator for the list of macros at the given `.debug_macro` offset.
1570    pub fn macros(&self, offset: DebugMacroOffset<R::Offset>) -> Result<MacroIter<R>> {
1571        self.dwarf.macros(offset)
1572    }
1573}
1574
1575impl<T: ReaderOffset> UnitSectionOffset<T> {
1576    /// Convert an offset to be relative to the start of the given unit,
1577    /// instead of relative to the start of the section.
1578    ///
1579    /// Returns `None` if the offset is not within the unit entries.
1580    pub fn to_unit_offset<R>(&self, unit: &Unit<R>) -> Option<UnitOffset<T>>
1581    where
1582        R: Reader<Offset = T>,
1583    {
1584        let (offset, unit_offset) = match (self, unit.header.offset()) {
1585            (
1586                UnitSectionOffset::DebugInfoOffset(offset),
1587                UnitSectionOffset::DebugInfoOffset(unit_offset),
1588            ) => (offset.0, unit_offset.0),
1589            (
1590                UnitSectionOffset::DebugTypesOffset(offset),
1591                UnitSectionOffset::DebugTypesOffset(unit_offset),
1592            ) => (offset.0, unit_offset.0),
1593            _ => return None,
1594        };
1595        let offset = match offset.checked_sub(unit_offset) {
1596            Some(offset) => UnitOffset(offset),
1597            None => return None,
1598        };
1599        if !unit.header.is_valid_offset(offset) {
1600            return None;
1601        }
1602        Some(offset)
1603    }
1604}
1605
1606impl<T: ReaderOffset> UnitOffset<T> {
1607    /// Convert an offset to be relative to the start of the .debug_info section,
1608    /// instead of relative to the start of the given compilation unit.
1609    ///
1610    /// Does not check that the offset is valid.
1611    pub fn to_unit_section_offset<R>(&self, unit: &Unit<R>) -> UnitSectionOffset<T>
1612    where
1613        R: Reader<Offset = T>,
1614    {
1615        match unit.header.offset() {
1616            UnitSectionOffset::DebugInfoOffset(unit_offset) => {
1617                DebugInfoOffset(unit_offset.0 + self.0).into()
1618            }
1619            UnitSectionOffset::DebugTypesOffset(unit_offset) => {
1620                DebugTypesOffset(unit_offset.0 + self.0).into()
1621            }
1622        }
1623    }
1624}
1625
1626/// An iterator for the address ranges of a `DebuggingInformationEntry`.
1627///
1628/// Returned by `Dwarf::die_ranges` and `Dwarf::unit_ranges`.
1629#[derive(Debug)]
1630pub struct RangeIter<R: Reader>(RangeIterInner<R>);
1631
1632#[derive(Debug)]
1633enum RangeIterInner<R: Reader> {
1634    Single(Option<Range>),
1635    List(RngListIter<R>),
1636}
1637
1638impl<R: Reader> Default for RangeIter<R> {
1639    fn default() -> Self {
1640        RangeIter(RangeIterInner::Single(None))
1641    }
1642}
1643
1644impl<R: Reader> RangeIter<R> {
1645    /// Advance the iterator to the next range.
1646    pub fn next(&mut self) -> Result<Option<Range>> {
1647        match self.0 {
1648            RangeIterInner::Single(ref mut range) => Ok(range.take()),
1649            RangeIterInner::List(ref mut list) => list.next(),
1650        }
1651    }
1652}
1653
1654#[cfg(feature = "fallible-iterator")]
1655impl<R: Reader> fallible_iterator::FallibleIterator for RangeIter<R> {
1656    type Item = Range;
1657    type Error = Error;
1658
1659    #[inline]
1660    fn next(&mut self) -> ::core::result::Result<Option<Self::Item>, Self::Error> {
1661        RangeIter::next(self)
1662    }
1663}
1664
1665#[cfg(test)]
1666mod tests {
1667    use super::*;
1668    use crate::read::EndianSlice;
1669    use crate::{Endianity, LittleEndian};
1670
1671    /// Ensure that `Dwarf<R>` is covariant wrt R.
1672    #[test]
1673    fn test_dwarf_variance() {
1674        /// This only needs to compile.
1675        fn _f<'a: 'b, 'b, E: Endianity>(x: Dwarf<EndianSlice<'a, E>>) -> Dwarf<EndianSlice<'b, E>> {
1676            x
1677        }
1678    }
1679
1680    /// Ensure that `Unit<R>` is covariant wrt R.
1681    #[test]
1682    fn test_dwarf_unit_variance() {
1683        /// This only needs to compile.
1684        fn _f<'a: 'b, 'b, E: Endianity>(x: Unit<EndianSlice<'a, E>>) -> Unit<EndianSlice<'b, E>> {
1685            x
1686        }
1687    }
1688
1689    #[test]
1690    fn test_send() {
1691        fn assert_is_send<T: Send>() {}
1692        assert_is_send::<Dwarf<EndianSlice<'_, LittleEndian>>>();
1693        assert_is_send::<Unit<EndianSlice<'_, LittleEndian>>>();
1694    }
1695
1696    #[test]
1697    fn test_format_error() {
1698        let dwarf_sections = DwarfSections::load(|_| -> Result<_> { Ok(vec![1, 2]) }).unwrap();
1699        let sup_sections = DwarfSections::load(|_| -> Result<_> { Ok(vec![1, 2]) }).unwrap();
1700        let dwarf = dwarf_sections.borrow_with_sup(&sup_sections, |section| {
1701            EndianSlice::new(section, LittleEndian)
1702        });
1703
1704        match dwarf.debug_str.get_str(DebugStrOffset(1)) {
1705            Ok(r) => panic!("Unexpected str {:?}", r),
1706            Err(e) => {
1707                assert_eq!(
1708                    dwarf.format_error(e),
1709                    "Hit the end of input before it was expected at .debug_str+0x1"
1710                );
1711            }
1712        }
1713        match dwarf.sup().unwrap().debug_str.get_str(DebugStrOffset(1)) {
1714            Ok(r) => panic!("Unexpected str {:?}", r),
1715            Err(e) => {
1716                assert_eq!(
1717                    dwarf.format_error(e),
1718                    "Hit the end of input before it was expected at .debug_str(sup)+0x1"
1719                );
1720            }
1721        }
1722        assert_eq!(dwarf.format_error(Error::Io), Error::Io.description());
1723    }
1724}