1use alloc::string::String;
2use alloc::sync::Arc;
3
4use crate::common::{
5    DebugAddrBase, DebugAddrIndex, DebugInfoOffset, DebugLineStrOffset, DebugLocListsBase,
6    DebugLocListsIndex, DebugRngListsBase, DebugRngListsIndex, DebugStrOffset, DebugStrOffsetsBase,
7    DebugStrOffsetsIndex, DebugTypeSignature, DebugTypesOffset, DwarfFileType, DwoId, Encoding,
8    LocationListsOffset, RangeListsOffset, RawRangeListsOffset, SectionId, UnitSectionOffset,
9};
10use crate::constants;
11use crate::read::{
12    Abbreviations, AbbreviationsCache, AbbreviationsCacheStrategy, AttributeValue, DebugAbbrev,
13    DebugAddr, DebugAranges, DebugCuIndex, DebugInfo, DebugInfoUnitHeadersIter, DebugLine,
14    DebugLineStr, DebugLoc, DebugLocLists, DebugRanges, DebugRngLists, DebugStr, DebugStrOffsets,
15    DebugTuIndex, DebugTypes, DebugTypesUnitHeadersIter, DebuggingInformationEntry, EntriesCursor,
16    EntriesRaw, EntriesTree, Error, IncompleteLineProgram, IndexSectionId, LocListIter,
17    LocationLists, Range, RangeLists, RawLocListIter, RawRngListIter, Reader, ReaderOffset,
18    ReaderOffsetId, Result, RngListIter, Section, UnitHeader, UnitIndex, UnitIndexSectionIterator,
19    UnitOffset, UnitType,
20};
21
22#[derive(Debug, Default)]
50pub struct DwarfSections<T> {
51    pub debug_abbrev: DebugAbbrev<T>,
53    pub debug_addr: DebugAddr<T>,
55    pub debug_aranges: DebugAranges<T>,
57    pub debug_info: DebugInfo<T>,
59    pub debug_line: DebugLine<T>,
61    pub debug_line_str: DebugLineStr<T>,
63    pub debug_str: DebugStr<T>,
65    pub debug_str_offsets: DebugStrOffsets<T>,
67    pub debug_types: DebugTypes<T>,
69    pub debug_loc: DebugLoc<T>,
71    pub debug_loclists: DebugLocLists<T>,
73    pub debug_ranges: DebugRanges<T>,
75    pub debug_rnglists: DebugRngLists<T>,
77}
78
79impl<T> DwarfSections<T> {
80    pub fn load<F, E>(mut section: F) -> core::result::Result<Self, E>
85    where
86        F: FnMut(SectionId) -> core::result::Result<T, E>,
87    {
88        Ok(DwarfSections {
89            debug_abbrev: Section::load(&mut section)?,
91            debug_addr: Section::load(&mut section)?,
92            debug_aranges: Section::load(&mut section)?,
93            debug_info: Section::load(&mut section)?,
94            debug_line: Section::load(&mut section)?,
95            debug_line_str: Section::load(&mut section)?,
96            debug_str: Section::load(&mut section)?,
97            debug_str_offsets: Section::load(&mut section)?,
98            debug_types: Section::load(&mut section)?,
99            debug_loc: Section::load(&mut section)?,
100            debug_loclists: Section::load(&mut section)?,
101            debug_ranges: Section::load(&mut section)?,
102            debug_rnglists: Section::load(&mut section)?,
103        })
104    }
105
106    pub fn borrow<'a, F, R>(&'a self, mut borrow: F) -> Dwarf<R>
108    where
109        F: FnMut(&'a T) -> R,
110    {
111        Dwarf::from_sections(DwarfSections {
112            debug_abbrev: self.debug_abbrev.borrow(&mut borrow),
113            debug_addr: self.debug_addr.borrow(&mut borrow),
114            debug_aranges: self.debug_aranges.borrow(&mut borrow),
115            debug_info: self.debug_info.borrow(&mut borrow),
116            debug_line: self.debug_line.borrow(&mut borrow),
117            debug_line_str: self.debug_line_str.borrow(&mut borrow),
118            debug_str: self.debug_str.borrow(&mut borrow),
119            debug_str_offsets: self.debug_str_offsets.borrow(&mut borrow),
120            debug_types: self.debug_types.borrow(&mut borrow),
121            debug_loc: self.debug_loc.borrow(&mut borrow),
122            debug_loclists: self.debug_loclists.borrow(&mut borrow),
123            debug_ranges: self.debug_ranges.borrow(&mut borrow),
124            debug_rnglists: self.debug_rnglists.borrow(&mut borrow),
125        })
126    }
127
128    pub fn borrow_with_sup<'a, F, R>(&'a self, sup: &'a Self, mut borrow: F) -> Dwarf<R>
150    where
151        F: FnMut(&'a T) -> R,
152    {
153        let mut dwarf = self.borrow(&mut borrow);
154        dwarf.set_sup(sup.borrow(&mut borrow));
155        dwarf
156    }
157}
158
159#[derive(Debug, Default)]
161pub struct Dwarf<R> {
162    pub debug_abbrev: DebugAbbrev<R>,
164
165    pub debug_addr: DebugAddr<R>,
167
168    pub debug_aranges: DebugAranges<R>,
170
171    pub debug_info: DebugInfo<R>,
173
174    pub debug_line: DebugLine<R>,
176
177    pub debug_line_str: DebugLineStr<R>,
179
180    pub debug_str: DebugStr<R>,
182
183    pub debug_str_offsets: DebugStrOffsets<R>,
185
186    pub debug_types: DebugTypes<R>,
188
189    pub locations: LocationLists<R>,
191
192    pub ranges: RangeLists<R>,
194
195    pub file_type: DwarfFileType,
197
198    pub sup: Option<Arc<Dwarf<R>>>,
200
201    pub abbreviations_cache: AbbreviationsCache,
203}
204
205impl<T> Dwarf<T> {
206    pub fn load<F, E>(section: F) -> core::result::Result<Self, E>
214    where
215        F: FnMut(SectionId) -> core::result::Result<T, E>,
216    {
217        let sections = DwarfSections::load(section)?;
218        Ok(Self::from_sections(sections))
219    }
220
221    pub fn load_sup<F, E>(&mut self, section: F) -> core::result::Result<(), E>
227    where
228        F: FnMut(SectionId) -> core::result::Result<T, E>,
229    {
230        self.set_sup(Self::load(section)?);
231        Ok(())
232    }
233
234    fn from_sections(sections: DwarfSections<T>) -> Self {
238        Dwarf {
239            debug_abbrev: sections.debug_abbrev,
240            debug_addr: sections.debug_addr,
241            debug_aranges: sections.debug_aranges,
242            debug_info: sections.debug_info,
243            debug_line: sections.debug_line,
244            debug_line_str: sections.debug_line_str,
245            debug_str: sections.debug_str,
246            debug_str_offsets: sections.debug_str_offsets,
247            debug_types: sections.debug_types,
248            locations: LocationLists::new(sections.debug_loc, sections.debug_loclists),
249            ranges: RangeLists::new(sections.debug_ranges, sections.debug_rnglists),
250            file_type: DwarfFileType::Main,
251            sup: None,
252            abbreviations_cache: AbbreviationsCache::new(),
253        }
254    }
255
256    #[deprecated(note = "use `DwarfSections::borrow` instead")]
284    pub fn borrow<'a, F, R>(&'a self, mut borrow: F) -> Dwarf<R>
285    where
286        F: FnMut(&'a T) -> R,
287    {
288        Dwarf {
289            debug_abbrev: self.debug_abbrev.borrow(&mut borrow),
290            debug_addr: self.debug_addr.borrow(&mut borrow),
291            debug_aranges: self.debug_aranges.borrow(&mut borrow),
292            debug_info: self.debug_info.borrow(&mut borrow),
293            debug_line: self.debug_line.borrow(&mut borrow),
294            debug_line_str: self.debug_line_str.borrow(&mut borrow),
295            debug_str: self.debug_str.borrow(&mut borrow),
296            debug_str_offsets: self.debug_str_offsets.borrow(&mut borrow),
297            debug_types: self.debug_types.borrow(&mut borrow),
298            locations: self.locations.borrow(&mut borrow),
299            ranges: self.ranges.borrow(&mut borrow),
300            file_type: self.file_type,
301            sup: self.sup().map(|sup| Arc::new(sup.borrow(borrow))),
302            abbreviations_cache: AbbreviationsCache::new(),
303        }
304    }
305
306    pub fn set_sup(&mut self, sup: Dwarf<T>) {
308        self.sup = Some(Arc::new(sup));
309    }
310
311    pub fn sup(&self) -> Option<&Dwarf<T>> {
313        self.sup.as_ref().map(Arc::as_ref)
314    }
315}
316
317impl<R: Reader> Dwarf<R> {
318    pub fn populate_abbreviations_cache(&mut self, strategy: AbbreviationsCacheStrategy) {
326        self.abbreviations_cache
327            .populate(strategy, &self.debug_abbrev, self.debug_info.units());
328    }
329
330    #[inline]
335    pub fn units(&self) -> DebugInfoUnitHeadersIter<R> {
336        self.debug_info.units()
337    }
338
339    #[inline]
341    pub fn unit(&self, header: UnitHeader<R>) -> Result<Unit<R>> {
342        Unit::new(self, header)
343    }
344
345    #[inline]
350    pub fn type_units(&self) -> DebugTypesUnitHeadersIter<R> {
351        self.debug_types.units()
352    }
353
354    #[inline]
356    pub fn abbreviations(&self, unit: &UnitHeader<R>) -> Result<Arc<Abbreviations>> {
357        self.abbreviations_cache
358            .get(&self.debug_abbrev, unit.debug_abbrev_offset())
359    }
360
361    #[inline]
363    pub fn string_offset(
364        &self,
365        unit: &Unit<R>,
366        index: DebugStrOffsetsIndex<R::Offset>,
367    ) -> Result<DebugStrOffset<R::Offset>> {
368        self.debug_str_offsets
369            .get_str_offset(unit.header.format(), unit.str_offsets_base, index)
370    }
371
372    #[inline]
374    pub fn string(&self, offset: DebugStrOffset<R::Offset>) -> Result<R> {
375        self.debug_str.get_str(offset)
376    }
377
378    #[inline]
380    pub fn line_string(&self, offset: DebugLineStrOffset<R::Offset>) -> Result<R> {
381        self.debug_line_str.get_str(offset)
382    }
383
384    #[inline]
387    pub fn sup_string(&self, offset: DebugStrOffset<R::Offset>) -> Result<R> {
388        if let Some(sup) = self.sup() {
389            sup.debug_str.get_str(offset)
390        } else {
391            Err(Error::ExpectedStringAttributeValue)
392        }
393    }
394
395    pub fn attr_string(&self, unit: &Unit<R>, attr: AttributeValue<R>) -> Result<R> {
410        match attr {
411            AttributeValue::String(string) => Ok(string),
412            AttributeValue::DebugStrRef(offset) => self.string(offset),
413            AttributeValue::DebugStrRefSup(offset) => self.sup_string(offset),
414            AttributeValue::DebugLineStrRef(offset) => self.line_string(offset),
415            AttributeValue::DebugStrOffsetsIndex(index) => {
416                let offset = self.string_offset(unit, index)?;
417                self.string(offset)
418            }
419            _ => Err(Error::ExpectedStringAttributeValue),
420        }
421    }
422
423    pub fn address(&self, unit: &Unit<R>, index: DebugAddrIndex<R::Offset>) -> Result<u64> {
425        self.debug_addr
426            .get_address(unit.encoding().address_size, unit.addr_base, index)
427    }
428
429    pub fn attr_address(&self, unit: &Unit<R>, attr: AttributeValue<R>) -> Result<Option<u64>> {
439        match attr {
440            AttributeValue::Addr(addr) => Ok(Some(addr)),
441            AttributeValue::DebugAddrIndex(index) => self.address(unit, index).map(Some),
442            _ => Ok(None),
443        }
444    }
445
446    pub fn ranges_offset_from_raw(
450        &self,
451        unit: &Unit<R>,
452        offset: RawRangeListsOffset<R::Offset>,
453    ) -> RangeListsOffset<R::Offset> {
454        if self.file_type == DwarfFileType::Dwo && unit.header.version() < 5 {
455            RangeListsOffset(offset.0.wrapping_add(unit.rnglists_base.0))
456        } else {
457            RangeListsOffset(offset.0)
458        }
459    }
460
461    pub fn ranges_offset(
463        &self,
464        unit: &Unit<R>,
465        index: DebugRngListsIndex<R::Offset>,
466    ) -> Result<RangeListsOffset<R::Offset>> {
467        self.ranges
468            .get_offset(unit.encoding(), unit.rnglists_base, index)
469    }
470
471    pub fn ranges(
473        &self,
474        unit: &Unit<R>,
475        offset: RangeListsOffset<R::Offset>,
476    ) -> Result<RngListIter<R>> {
477        self.ranges.ranges(
478            offset,
479            unit.encoding(),
480            unit.low_pc,
481            &self.debug_addr,
482            unit.addr_base,
483        )
484    }
485
486    pub fn raw_ranges(
488        &self,
489        unit: &Unit<R>,
490        offset: RangeListsOffset<R::Offset>,
491    ) -> Result<RawRngListIter<R>> {
492        self.ranges.raw_ranges(offset, unit.encoding())
493    }
494
495    pub fn attr_ranges_offset(
505        &self,
506        unit: &Unit<R>,
507        attr: AttributeValue<R>,
508    ) -> Result<Option<RangeListsOffset<R::Offset>>> {
509        match attr {
510            AttributeValue::RangeListsRef(offset) => {
511                Ok(Some(self.ranges_offset_from_raw(unit, offset)))
512            }
513            AttributeValue::DebugRngListsIndex(index) => self.ranges_offset(unit, index).map(Some),
514            _ => Ok(None),
515        }
516    }
517
518    pub fn attr_ranges(
528        &self,
529        unit: &Unit<R>,
530        attr: AttributeValue<R>,
531    ) -> Result<Option<RngListIter<R>>> {
532        match self.attr_ranges_offset(unit, attr)? {
533            Some(offset) => Ok(Some(self.ranges(unit, offset)?)),
534            None => Ok(None),
535        }
536    }
537
538    pub fn die_ranges(
542        &self,
543        unit: &Unit<R>,
544        entry: &DebuggingInformationEntry<'_, '_, R>,
545    ) -> Result<RangeIter<R>> {
546        let mut low_pc = None;
547        let mut high_pc = None;
548        let mut size = None;
549        let mut attrs = entry.attrs();
550        while let Some(attr) = attrs.next()? {
551            match attr.name() {
552                constants::DW_AT_low_pc => {
553                    low_pc = Some(
554                        self.attr_address(unit, attr.value())?
555                            .ok_or(Error::UnsupportedAttributeForm)?,
556                    );
557                }
558                constants::DW_AT_high_pc => match attr.value() {
559                    AttributeValue::Udata(val) => size = Some(val),
560                    attr => {
561                        high_pc = Some(
562                            self.attr_address(unit, attr)?
563                                .ok_or(Error::UnsupportedAttributeForm)?,
564                        );
565                    }
566                },
567                constants::DW_AT_ranges => {
568                    if let Some(list) = self.attr_ranges(unit, attr.value())? {
569                        return Ok(RangeIter(RangeIterInner::List(list)));
570                    }
571                }
572                _ => {}
573            }
574        }
575        let range = low_pc.and_then(|begin| {
576            let end = size.map(|size| begin + size).or(high_pc);
577            end.map(|end| Range { begin, end })
579        });
580        Ok(RangeIter(RangeIterInner::Single(range)))
581    }
582
583    pub fn unit_ranges(&self, unit: &Unit<R>) -> Result<RangeIter<R>> {
588        let mut cursor = unit.header.entries(&unit.abbreviations);
589        cursor.next_dfs()?;
590        let root = cursor.current().ok_or(Error::MissingUnitDie)?;
591        self.die_ranges(unit, root)
592    }
593
594    pub fn locations_offset(
596        &self,
597        unit: &Unit<R>,
598        index: DebugLocListsIndex<R::Offset>,
599    ) -> Result<LocationListsOffset<R::Offset>> {
600        self.locations
601            .get_offset(unit.encoding(), unit.loclists_base, index)
602    }
603
604    pub fn locations(
606        &self,
607        unit: &Unit<R>,
608        offset: LocationListsOffset<R::Offset>,
609    ) -> Result<LocListIter<R>> {
610        match self.file_type {
611            DwarfFileType::Main => self.locations.locations(
612                offset,
613                unit.encoding(),
614                unit.low_pc,
615                &self.debug_addr,
616                unit.addr_base,
617            ),
618            DwarfFileType::Dwo => self.locations.locations_dwo(
619                offset,
620                unit.encoding(),
621                unit.low_pc,
622                &self.debug_addr,
623                unit.addr_base,
624            ),
625        }
626    }
627
628    pub fn raw_locations(
630        &self,
631        unit: &Unit<R>,
632        offset: LocationListsOffset<R::Offset>,
633    ) -> Result<RawLocListIter<R>> {
634        match self.file_type {
635            DwarfFileType::Main => self.locations.raw_locations(offset, unit.encoding()),
636            DwarfFileType::Dwo => self.locations.raw_locations_dwo(offset, unit.encoding()),
637        }
638    }
639
640    pub fn attr_locations_offset(
650        &self,
651        unit: &Unit<R>,
652        attr: AttributeValue<R>,
653    ) -> Result<Option<LocationListsOffset<R::Offset>>> {
654        match attr {
655            AttributeValue::LocationListsRef(offset) => Ok(Some(offset)),
656            AttributeValue::DebugLocListsIndex(index) => {
657                self.locations_offset(unit, index).map(Some)
658            }
659            _ => Ok(None),
660        }
661    }
662
663    pub fn attr_locations(
673        &self,
674        unit: &Unit<R>,
675        attr: AttributeValue<R>,
676    ) -> Result<Option<LocListIter<R>>> {
677        match self.attr_locations_offset(unit, attr)? {
678            Some(offset) => Ok(Some(self.locations(unit, offset)?)),
679            None => Ok(None),
680        }
681    }
682
683    pub fn lookup_offset_id(&self, id: ReaderOffsetId) -> Option<(bool, SectionId, R::Offset)> {
687        None.or_else(|| self.debug_abbrev.lookup_offset_id(id))
688            .or_else(|| self.debug_addr.lookup_offset_id(id))
689            .or_else(|| self.debug_aranges.lookup_offset_id(id))
690            .or_else(|| self.debug_info.lookup_offset_id(id))
691            .or_else(|| self.debug_line.lookup_offset_id(id))
692            .or_else(|| self.debug_line_str.lookup_offset_id(id))
693            .or_else(|| self.debug_str.lookup_offset_id(id))
694            .or_else(|| self.debug_str_offsets.lookup_offset_id(id))
695            .or_else(|| self.debug_types.lookup_offset_id(id))
696            .or_else(|| self.locations.lookup_offset_id(id))
697            .or_else(|| self.ranges.lookup_offset_id(id))
698            .map(|(id, offset)| (false, id, offset))
699            .or_else(|| {
700                self.sup()
701                    .and_then(|sup| sup.lookup_offset_id(id))
702                    .map(|(_, id, offset)| (true, id, offset))
703            })
704    }
705
706    pub fn format_error(&self, err: Error) -> String {
710        #[allow(clippy::single_match)]
711        match err {
712            Error::UnexpectedEof(id) => match self.lookup_offset_id(id) {
713                Some((sup, section, offset)) => {
714                    return format!(
715                        "{} at {}{}+0x{:x}",
716                        err,
717                        section.name(),
718                        if sup { "(sup)" } else { "" },
719                        offset.into_u64(),
720                    );
721                }
722                None => {}
723            },
724            _ => {}
725        }
726        err.description().into()
727    }
728}
729
730impl<R: Clone> Dwarf<R> {
731    pub fn make_dwo(&mut self, parent: &Dwarf<R>) {
735        self.file_type = DwarfFileType::Dwo;
736        self.debug_addr = parent.debug_addr.clone();
738        self.ranges
741            .set_debug_ranges(parent.ranges.debug_ranges().clone());
742        self.sup.clone_from(&parent.sup);
743    }
744}
745
746#[derive(Debug, Default)]
775pub struct DwarfPackageSections<T> {
776    pub cu_index: DebugCuIndex<T>,
778    pub tu_index: DebugTuIndex<T>,
780    pub debug_abbrev: DebugAbbrev<T>,
782    pub debug_info: DebugInfo<T>,
784    pub debug_line: DebugLine<T>,
786    pub debug_str: DebugStr<T>,
788    pub debug_str_offsets: DebugStrOffsets<T>,
790    pub debug_loc: DebugLoc<T>,
794    pub debug_loclists: DebugLocLists<T>,
796    pub debug_rnglists: DebugRngLists<T>,
798    pub debug_types: DebugTypes<T>,
802}
803
804impl<T> DwarfPackageSections<T> {
805    pub fn load<F, E>(mut section: F) -> core::result::Result<Self, E>
810    where
811        F: FnMut(SectionId) -> core::result::Result<T, E>,
812        E: From<Error>,
813    {
814        Ok(DwarfPackageSections {
815            cu_index: Section::load(&mut section)?,
817            tu_index: Section::load(&mut section)?,
818            debug_abbrev: Section::load(&mut section)?,
819            debug_info: Section::load(&mut section)?,
820            debug_line: Section::load(&mut section)?,
821            debug_str: Section::load(&mut section)?,
822            debug_str_offsets: Section::load(&mut section)?,
823            debug_loc: Section::load(&mut section)?,
824            debug_loclists: Section::load(&mut section)?,
825            debug_rnglists: Section::load(&mut section)?,
826            debug_types: Section::load(&mut section)?,
827        })
828    }
829
830    pub fn borrow<'a, F, R>(&'a self, mut borrow: F, empty: R) -> Result<DwarfPackage<R>>
832    where
833        F: FnMut(&'a T) -> R,
834        R: Reader,
835    {
836        DwarfPackage::from_sections(
837            DwarfPackageSections {
838                cu_index: self.cu_index.borrow(&mut borrow),
839                tu_index: self.tu_index.borrow(&mut borrow),
840                debug_abbrev: self.debug_abbrev.borrow(&mut borrow),
841                debug_info: self.debug_info.borrow(&mut borrow),
842                debug_line: self.debug_line.borrow(&mut borrow),
843                debug_str: self.debug_str.borrow(&mut borrow),
844                debug_str_offsets: self.debug_str_offsets.borrow(&mut borrow),
845                debug_loc: self.debug_loc.borrow(&mut borrow),
846                debug_loclists: self.debug_loclists.borrow(&mut borrow),
847                debug_rnglists: self.debug_rnglists.borrow(&mut borrow),
848                debug_types: self.debug_types.borrow(&mut borrow),
849            },
850            empty,
851        )
852    }
853}
854
855#[derive(Debug)]
857pub struct DwarfPackage<R: Reader> {
858    pub cu_index: UnitIndex<R>,
860
861    pub tu_index: UnitIndex<R>,
863
864    pub debug_abbrev: DebugAbbrev<R>,
866
867    pub debug_info: DebugInfo<R>,
869
870    pub debug_line: DebugLine<R>,
872
873    pub debug_str: DebugStr<R>,
875
876    pub debug_str_offsets: DebugStrOffsets<R>,
878
879    pub debug_loc: DebugLoc<R>,
883
884    pub debug_loclists: DebugLocLists<R>,
886
887    pub debug_rnglists: DebugRngLists<R>,
889
890    pub debug_types: DebugTypes<R>,
894
895    pub empty: R,
899}
900
901impl<R: Reader> DwarfPackage<R> {
902    pub fn load<F, E>(section: F, empty: R) -> core::result::Result<Self, E>
907    where
908        F: FnMut(SectionId) -> core::result::Result<R, E>,
909        E: From<Error>,
910    {
911        let sections = DwarfPackageSections::load(section)?;
912        Ok(Self::from_sections(sections, empty)?)
913    }
914
915    fn from_sections(sections: DwarfPackageSections<R>, empty: R) -> Result<Self> {
917        Ok(DwarfPackage {
918            cu_index: sections.cu_index.index()?,
919            tu_index: sections.tu_index.index()?,
920            debug_abbrev: sections.debug_abbrev,
921            debug_info: sections.debug_info,
922            debug_line: sections.debug_line,
923            debug_str: sections.debug_str,
924            debug_str_offsets: sections.debug_str_offsets,
925            debug_loc: sections.debug_loc,
926            debug_loclists: sections.debug_loclists,
927            debug_rnglists: sections.debug_rnglists,
928            debug_types: sections.debug_types,
929            empty,
930        })
931    }
932
933    pub fn find_cu(&self, id: DwoId, parent: &Dwarf<R>) -> Result<Option<Dwarf<R>>> {
952        let row = match self.cu_index.find(id.0) {
953            Some(row) => row,
954            None => return Ok(None),
955        };
956        self.cu_sections(row, parent).map(Some)
957    }
958
959    pub fn find_tu(
962        &self,
963        signature: DebugTypeSignature,
964        parent: &Dwarf<R>,
965    ) -> Result<Option<Dwarf<R>>> {
966        let row = match self.tu_index.find(signature.0) {
967            Some(row) => row,
968            None => return Ok(None),
969        };
970        self.tu_sections(row, parent).map(Some)
971    }
972
973    pub fn cu_sections(&self, index: u32, parent: &Dwarf<R>) -> Result<Dwarf<R>> {
979        self.sections(self.cu_index.sections(index)?, parent)
980    }
981
982    pub fn tu_sections(&self, index: u32, parent: &Dwarf<R>) -> Result<Dwarf<R>> {
988        self.sections(self.tu_index.sections(index)?, parent)
989    }
990
991    pub fn sections(
995        &self,
996        sections: UnitIndexSectionIterator<'_, R>,
997        parent: &Dwarf<R>,
998    ) -> Result<Dwarf<R>> {
999        let mut abbrev_offset = 0;
1000        let mut abbrev_size = 0;
1001        let mut info_offset = 0;
1002        let mut info_size = 0;
1003        let mut line_offset = 0;
1004        let mut line_size = 0;
1005        let mut loc_offset = 0;
1006        let mut loc_size = 0;
1007        let mut loclists_offset = 0;
1008        let mut loclists_size = 0;
1009        let mut str_offsets_offset = 0;
1010        let mut str_offsets_size = 0;
1011        let mut rnglists_offset = 0;
1012        let mut rnglists_size = 0;
1013        let mut types_offset = 0;
1014        let mut types_size = 0;
1015        for section in sections {
1016            match section.section {
1017                IndexSectionId::DebugAbbrev => {
1018                    abbrev_offset = section.offset;
1019                    abbrev_size = section.size;
1020                }
1021                IndexSectionId::DebugInfo => {
1022                    info_offset = section.offset;
1023                    info_size = section.size;
1024                }
1025                IndexSectionId::DebugLine => {
1026                    line_offset = section.offset;
1027                    line_size = section.size;
1028                }
1029                IndexSectionId::DebugLoc => {
1030                    loc_offset = section.offset;
1031                    loc_size = section.size;
1032                }
1033                IndexSectionId::DebugLocLists => {
1034                    loclists_offset = section.offset;
1035                    loclists_size = section.size;
1036                }
1037                IndexSectionId::DebugStrOffsets => {
1038                    str_offsets_offset = section.offset;
1039                    str_offsets_size = section.size;
1040                }
1041                IndexSectionId::DebugRngLists => {
1042                    rnglists_offset = section.offset;
1043                    rnglists_size = section.size;
1044                }
1045                IndexSectionId::DebugTypes => {
1046                    types_offset = section.offset;
1047                    types_size = section.size;
1048                }
1049                IndexSectionId::DebugMacro | IndexSectionId::DebugMacinfo => {
1050                    }
1052            }
1053        }
1054
1055        let debug_abbrev = self.debug_abbrev.dwp_range(abbrev_offset, abbrev_size)?;
1056        let debug_info = self.debug_info.dwp_range(info_offset, info_size)?;
1057        let debug_line = self.debug_line.dwp_range(line_offset, line_size)?;
1058        let debug_loc = self.debug_loc.dwp_range(loc_offset, loc_size)?;
1059        let debug_loclists = self
1060            .debug_loclists
1061            .dwp_range(loclists_offset, loclists_size)?;
1062        let debug_str_offsets = self
1063            .debug_str_offsets
1064            .dwp_range(str_offsets_offset, str_offsets_size)?;
1065        let debug_rnglists = self
1066            .debug_rnglists
1067            .dwp_range(rnglists_offset, rnglists_size)?;
1068        let debug_types = self.debug_types.dwp_range(types_offset, types_size)?;
1069
1070        let debug_str = self.debug_str.clone();
1071
1072        let debug_addr = parent.debug_addr.clone();
1073        let debug_ranges = parent.ranges.debug_ranges().clone();
1074
1075        let debug_aranges = self.empty.clone().into();
1076        let debug_line_str = self.empty.clone().into();
1077
1078        Ok(Dwarf {
1079            debug_abbrev,
1080            debug_addr,
1081            debug_aranges,
1082            debug_info,
1083            debug_line,
1084            debug_line_str,
1085            debug_str,
1086            debug_str_offsets,
1087            debug_types,
1088            locations: LocationLists::new(debug_loc, debug_loclists),
1089            ranges: RangeLists::new(debug_ranges, debug_rnglists),
1090            file_type: DwarfFileType::Dwo,
1091            sup: parent.sup.clone(),
1092            abbreviations_cache: AbbreviationsCache::new(),
1093        })
1094    }
1095}
1096
1097#[derive(Debug)]
1100pub struct Unit<R, Offset = <R as Reader>::Offset>
1101where
1102    R: Reader<Offset = Offset>,
1103    Offset: ReaderOffset,
1104{
1105    pub header: UnitHeader<R, Offset>,
1107
1108    pub abbreviations: Arc<Abbreviations>,
1110
1111    pub name: Option<R>,
1113
1114    pub comp_dir: Option<R>,
1116
1117    pub low_pc: u64,
1119
1120    pub str_offsets_base: DebugStrOffsetsBase<Offset>,
1122
1123    pub addr_base: DebugAddrBase<Offset>,
1125
1126    pub loclists_base: DebugLocListsBase<Offset>,
1128
1129    pub rnglists_base: DebugRngListsBase<Offset>,
1131
1132    pub line_program: Option<IncompleteLineProgram<R, Offset>>,
1134
1135    pub dwo_id: Option<DwoId>,
1137}
1138
1139impl<R: Reader> Unit<R> {
1140    #[inline]
1142    pub fn new(dwarf: &Dwarf<R>, header: UnitHeader<R>) -> Result<Self> {
1143        let abbreviations = dwarf.abbreviations(&header)?;
1144        Self::new_with_abbreviations(dwarf, header, abbreviations)
1145    }
1146
1147    #[inline]
1153    pub fn new_with_abbreviations(
1154        dwarf: &Dwarf<R>,
1155        header: UnitHeader<R>,
1156        abbreviations: Arc<Abbreviations>,
1157    ) -> Result<Self> {
1158        let mut unit = Unit {
1159            abbreviations,
1160            name: None,
1161            comp_dir: None,
1162            low_pc: 0,
1163            str_offsets_base: DebugStrOffsetsBase::default_for_encoding_and_file(
1164                header.encoding(),
1165                dwarf.file_type,
1166            ),
1167            addr_base: DebugAddrBase(R::Offset::from_u8(0)),
1169            loclists_base: DebugLocListsBase::default_for_encoding_and_file(
1170                header.encoding(),
1171                dwarf.file_type,
1172            ),
1173            rnglists_base: DebugRngListsBase::default_for_encoding_and_file(
1174                header.encoding(),
1175                dwarf.file_type,
1176            ),
1177            line_program: None,
1178            dwo_id: match header.type_() {
1179                UnitType::Skeleton(dwo_id) | UnitType::SplitCompilation(dwo_id) => Some(dwo_id),
1180                _ => None,
1181            },
1182            header,
1183        };
1184        let mut name = None;
1185        let mut comp_dir = None;
1186        let mut line_program_offset = None;
1187        let mut low_pc_attr = None;
1188
1189        {
1190            let mut cursor = unit.header.entries(&unit.abbreviations);
1191            cursor.next_dfs()?;
1192            let root = cursor.current().ok_or(Error::MissingUnitDie)?;
1193            let mut attrs = root.attrs();
1194            while let Some(attr) = attrs.next()? {
1195                match attr.name() {
1196                    constants::DW_AT_name => {
1197                        name = Some(attr.value());
1198                    }
1199                    constants::DW_AT_comp_dir => {
1200                        comp_dir = Some(attr.value());
1201                    }
1202                    constants::DW_AT_low_pc => {
1203                        low_pc_attr = Some(attr.value());
1204                    }
1205                    constants::DW_AT_stmt_list => {
1206                        if let AttributeValue::DebugLineRef(offset) = attr.value() {
1207                            line_program_offset = Some(offset);
1208                        }
1209                    }
1210                    constants::DW_AT_str_offsets_base => {
1211                        if let AttributeValue::DebugStrOffsetsBase(base) = attr.value() {
1212                            unit.str_offsets_base = base;
1213                        }
1214                    }
1215                    constants::DW_AT_addr_base | constants::DW_AT_GNU_addr_base => {
1216                        if let AttributeValue::DebugAddrBase(base) = attr.value() {
1217                            unit.addr_base = base;
1218                        }
1219                    }
1220                    constants::DW_AT_loclists_base => {
1221                        if let AttributeValue::DebugLocListsBase(base) = attr.value() {
1222                            unit.loclists_base = base;
1223                        }
1224                    }
1225                    constants::DW_AT_rnglists_base | constants::DW_AT_GNU_ranges_base => {
1226                        if let AttributeValue::DebugRngListsBase(base) = attr.value() {
1227                            unit.rnglists_base = base;
1228                        }
1229                    }
1230                    constants::DW_AT_GNU_dwo_id => {
1231                        if unit.dwo_id.is_none() {
1232                            if let AttributeValue::DwoId(dwo_id) = attr.value() {
1233                                unit.dwo_id = Some(dwo_id);
1234                            }
1235                        }
1236                    }
1237                    _ => {}
1238                }
1239            }
1240        }
1241
1242        unit.name = match name {
1243            Some(val) => dwarf.attr_string(&unit, val).ok(),
1244            None => None,
1245        };
1246        unit.comp_dir = match comp_dir {
1247            Some(val) => dwarf.attr_string(&unit, val).ok(),
1248            None => None,
1249        };
1250        unit.line_program = match line_program_offset {
1251            Some(offset) => Some(dwarf.debug_line.program(
1252                offset,
1253                unit.header.address_size(),
1254                unit.comp_dir.clone(),
1255                unit.name.clone(),
1256            )?),
1257            None => None,
1258        };
1259        if let Some(low_pc_attr) = low_pc_attr {
1260            if let Some(addr) = dwarf.attr_address(&unit, low_pc_attr)? {
1261                unit.low_pc = addr;
1262            }
1263        }
1264        Ok(unit)
1265    }
1266
1267    pub fn unit_ref<'a>(&'a self, dwarf: &'a Dwarf<R>) -> UnitRef<'a, R> {
1269        UnitRef::new(dwarf, self)
1270    }
1271
1272    #[inline]
1274    pub fn encoding(&self) -> Encoding {
1275        self.header.encoding()
1276    }
1277
1278    pub fn entry(
1280        &self,
1281        offset: UnitOffset<R::Offset>,
1282    ) -> Result<DebuggingInformationEntry<'_, '_, R>> {
1283        self.header.entry(&self.abbreviations, offset)
1284    }
1285
1286    #[inline]
1288    pub fn entries(&self) -> EntriesCursor<'_, '_, R> {
1289        self.header.entries(&self.abbreviations)
1290    }
1291
1292    #[inline]
1295    pub fn entries_at_offset(
1296        &self,
1297        offset: UnitOffset<R::Offset>,
1298    ) -> Result<EntriesCursor<'_, '_, R>> {
1299        self.header.entries_at_offset(&self.abbreviations, offset)
1300    }
1301
1302    #[inline]
1305    pub fn entries_tree(
1306        &self,
1307        offset: Option<UnitOffset<R::Offset>>,
1308    ) -> Result<EntriesTree<'_, '_, R>> {
1309        self.header.entries_tree(&self.abbreviations, offset)
1310    }
1311
1312    #[inline]
1314    pub fn entries_raw(
1315        &self,
1316        offset: Option<UnitOffset<R::Offset>>,
1317    ) -> Result<EntriesRaw<'_, '_, R>> {
1318        self.header.entries_raw(&self.abbreviations, offset)
1319    }
1320
1321    pub fn copy_relocated_attributes(&mut self, other: &Unit<R>) {
1325        self.low_pc = other.low_pc;
1326        self.addr_base = other.addr_base;
1327        if self.header.version() < 5 {
1328            self.rnglists_base = other.rnglists_base;
1329        }
1330    }
1331
1332    pub fn dwo_name(&self) -> Result<Option<AttributeValue<R>>> {
1338        let mut entries = self.entries();
1339        entries.next_entry()?;
1340        let entry = entries.current().ok_or(Error::MissingUnitDie)?;
1341        if self.header.version() < 5 {
1342            entry.attr_value(constants::DW_AT_GNU_dwo_name)
1343        } else {
1344            entry.attr_value(constants::DW_AT_dwo_name)
1345        }
1346    }
1347}
1348
1349#[derive(Debug)]
1356pub struct UnitRef<'a, R: Reader> {
1357    pub dwarf: &'a Dwarf<R>,
1359
1360    pub unit: &'a Unit<R>,
1362}
1363
1364impl<'a, R: Reader> Clone for UnitRef<'a, R> {
1365    fn clone(&self) -> Self {
1366        *self
1367    }
1368}
1369
1370impl<'a, R: Reader> Copy for UnitRef<'a, R> {}
1371
1372impl<'a, R: Reader> core::ops::Deref for UnitRef<'a, R> {
1373    type Target = Unit<R>;
1374
1375    fn deref(&self) -> &Self::Target {
1376        self.unit
1377    }
1378}
1379
1380impl<'a, R: Reader> UnitRef<'a, R> {
1381    pub fn new(dwarf: &'a Dwarf<R>, unit: &'a Unit<R>) -> Self {
1383        UnitRef { dwarf, unit }
1384    }
1385
1386    #[inline]
1388    pub fn string_offset(
1389        &self,
1390        index: DebugStrOffsetsIndex<R::Offset>,
1391    ) -> Result<DebugStrOffset<R::Offset>> {
1392        self.dwarf.string_offset(self.unit, index)
1393    }
1394
1395    #[inline]
1397    pub fn string(&self, offset: DebugStrOffset<R::Offset>) -> Result<R> {
1398        self.dwarf.string(offset)
1399    }
1400
1401    #[inline]
1403    pub fn line_string(&self, offset: DebugLineStrOffset<R::Offset>) -> Result<R> {
1404        self.dwarf.line_string(offset)
1405    }
1406
1407    #[inline]
1410    pub fn sup_string(&self, offset: DebugStrOffset<R::Offset>) -> Result<R> {
1411        self.dwarf.sup_string(offset)
1412    }
1413
1414    pub fn attr_string(&self, attr: AttributeValue<R>) -> Result<R> {
1418        self.dwarf.attr_string(self.unit, attr)
1419    }
1420
1421    pub fn address(&self, index: DebugAddrIndex<R::Offset>) -> Result<u64> {
1423        self.dwarf.address(self.unit, index)
1424    }
1425
1426    pub fn attr_address(&self, attr: AttributeValue<R>) -> Result<Option<u64>> {
1430        self.dwarf.attr_address(self.unit, attr)
1431    }
1432
1433    pub fn ranges_offset_from_raw(
1437        &self,
1438        offset: RawRangeListsOffset<R::Offset>,
1439    ) -> RangeListsOffset<R::Offset> {
1440        self.dwarf.ranges_offset_from_raw(self.unit, offset)
1441    }
1442
1443    pub fn ranges_offset(
1445        &self,
1446        index: DebugRngListsIndex<R::Offset>,
1447    ) -> Result<RangeListsOffset<R::Offset>> {
1448        self.dwarf.ranges_offset(self.unit, index)
1449    }
1450
1451    pub fn ranges(&self, offset: RangeListsOffset<R::Offset>) -> Result<RngListIter<R>> {
1453        self.dwarf.ranges(self.unit, offset)
1454    }
1455
1456    pub fn raw_ranges(&self, offset: RangeListsOffset<R::Offset>) -> Result<RawRngListIter<R>> {
1458        self.dwarf.raw_ranges(self.unit, offset)
1459    }
1460
1461    pub fn attr_ranges_offset(
1465        &self,
1466        attr: AttributeValue<R>,
1467    ) -> Result<Option<RangeListsOffset<R::Offset>>> {
1468        self.dwarf.attr_ranges_offset(self.unit, attr)
1469    }
1470
1471    pub fn attr_ranges(&self, attr: AttributeValue<R>) -> Result<Option<RngListIter<R>>> {
1475        self.dwarf.attr_ranges(self.unit, attr)
1476    }
1477
1478    pub fn die_ranges(&self, entry: &DebuggingInformationEntry<'_, '_, R>) -> Result<RangeIter<R>> {
1482        self.dwarf.die_ranges(self.unit, entry)
1483    }
1484
1485    pub fn unit_ranges(&self) -> Result<RangeIter<R>> {
1490        self.dwarf.unit_ranges(self.unit)
1491    }
1492
1493    pub fn locations_offset(
1495        &self,
1496        index: DebugLocListsIndex<R::Offset>,
1497    ) -> Result<LocationListsOffset<R::Offset>> {
1498        self.dwarf.locations_offset(self.unit, index)
1499    }
1500
1501    pub fn locations(&self, offset: LocationListsOffset<R::Offset>) -> Result<LocListIter<R>> {
1503        self.dwarf.locations(self.unit, offset)
1504    }
1505
1506    pub fn raw_locations(
1508        &self,
1509        offset: LocationListsOffset<R::Offset>,
1510    ) -> Result<RawLocListIter<R>> {
1511        self.dwarf.raw_locations(self.unit, offset)
1512    }
1513
1514    pub fn attr_locations_offset(
1518        &self,
1519        attr: AttributeValue<R>,
1520    ) -> Result<Option<LocationListsOffset<R::Offset>>> {
1521        self.dwarf.attr_locations_offset(self.unit, attr)
1522    }
1523
1524    pub fn attr_locations(&self, attr: AttributeValue<R>) -> Result<Option<LocListIter<R>>> {
1528        self.dwarf.attr_locations(self.unit, attr)
1529    }
1530}
1531
1532impl<T: ReaderOffset> UnitSectionOffset<T> {
1533    pub fn to_unit_offset<R>(&self, unit: &Unit<R>) -> Option<UnitOffset<T>>
1538    where
1539        R: Reader<Offset = T>,
1540    {
1541        let (offset, unit_offset) = match (self, unit.header.offset()) {
1542            (
1543                UnitSectionOffset::DebugInfoOffset(offset),
1544                UnitSectionOffset::DebugInfoOffset(unit_offset),
1545            ) => (offset.0, unit_offset.0),
1546            (
1547                UnitSectionOffset::DebugTypesOffset(offset),
1548                UnitSectionOffset::DebugTypesOffset(unit_offset),
1549            ) => (offset.0, unit_offset.0),
1550            _ => return None,
1551        };
1552        let offset = match offset.checked_sub(unit_offset) {
1553            Some(offset) => UnitOffset(offset),
1554            None => return None,
1555        };
1556        if !unit.header.is_valid_offset(offset) {
1557            return None;
1558        }
1559        Some(offset)
1560    }
1561}
1562
1563impl<T: ReaderOffset> UnitOffset<T> {
1564    pub fn to_unit_section_offset<R>(&self, unit: &Unit<R>) -> UnitSectionOffset<T>
1569    where
1570        R: Reader<Offset = T>,
1571    {
1572        match unit.header.offset() {
1573            UnitSectionOffset::DebugInfoOffset(unit_offset) => {
1574                DebugInfoOffset(unit_offset.0 + self.0).into()
1575            }
1576            UnitSectionOffset::DebugTypesOffset(unit_offset) => {
1577                DebugTypesOffset(unit_offset.0 + self.0).into()
1578            }
1579        }
1580    }
1581}
1582
1583#[derive(Debug)]
1587pub struct RangeIter<R: Reader>(RangeIterInner<R>);
1588
1589#[derive(Debug)]
1590enum RangeIterInner<R: Reader> {
1591    Single(Option<Range>),
1592    List(RngListIter<R>),
1593}
1594
1595impl<R: Reader> Default for RangeIter<R> {
1596    fn default() -> Self {
1597        RangeIter(RangeIterInner::Single(None))
1598    }
1599}
1600
1601impl<R: Reader> RangeIter<R> {
1602    pub fn next(&mut self) -> Result<Option<Range>> {
1604        match self.0 {
1605            RangeIterInner::Single(ref mut range) => Ok(range.take()),
1606            RangeIterInner::List(ref mut list) => list.next(),
1607        }
1608    }
1609}
1610
1611#[cfg(feature = "fallible-iterator")]
1612impl<R: Reader> fallible_iterator::FallibleIterator for RangeIter<R> {
1613    type Item = Range;
1614    type Error = Error;
1615
1616    #[inline]
1617    fn next(&mut self) -> ::core::result::Result<Option<Self::Item>, Self::Error> {
1618        RangeIter::next(self)
1619    }
1620}
1621
1622#[cfg(test)]
1623mod tests {
1624    use super::*;
1625    use crate::read::EndianSlice;
1626    use crate::{Endianity, LittleEndian};
1627
1628    #[test]
1630    fn test_dwarf_variance() {
1631        fn _f<'a: 'b, 'b, E: Endianity>(x: Dwarf<EndianSlice<'a, E>>) -> Dwarf<EndianSlice<'b, E>> {
1633            x
1634        }
1635    }
1636
1637    #[test]
1639    fn test_dwarf_unit_variance() {
1640        fn _f<'a: 'b, 'b, E: Endianity>(x: Unit<EndianSlice<'a, E>>) -> Unit<EndianSlice<'b, E>> {
1642            x
1643        }
1644    }
1645
1646    #[test]
1647    fn test_send() {
1648        fn assert_is_send<T: Send>() {}
1649        assert_is_send::<Dwarf<EndianSlice<'_, LittleEndian>>>();
1650        assert_is_send::<Unit<EndianSlice<'_, LittleEndian>>>();
1651    }
1652
1653    #[test]
1654    fn test_format_error() {
1655        let dwarf_sections = DwarfSections::load(|_| -> Result<_> { Ok(vec![1, 2]) }).unwrap();
1656        let sup_sections = DwarfSections::load(|_| -> Result<_> { Ok(vec![1, 2]) }).unwrap();
1657        let dwarf = dwarf_sections.borrow_with_sup(&sup_sections, |section| {
1658            EndianSlice::new(section, LittleEndian)
1659        });
1660
1661        match dwarf.debug_str.get_str(DebugStrOffset(1)) {
1662            Ok(r) => panic!("Unexpected str {:?}", r),
1663            Err(e) => {
1664                assert_eq!(
1665                    dwarf.format_error(e),
1666                    "Hit the end of input before it was expected at .debug_str+0x1"
1667                );
1668            }
1669        }
1670        match dwarf.sup().unwrap().debug_str.get_str(DebugStrOffset(1)) {
1671            Ok(r) => panic!("Unexpected str {:?}", r),
1672            Err(e) => {
1673                assert_eq!(
1674                    dwarf.format_error(e),
1675                    "Hit the end of input before it was expected at .debug_str(sup)+0x1"
1676                );
1677            }
1678        }
1679        assert_eq!(dwarf.format_error(Error::Io), Error::Io.description());
1680    }
1681}