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, AttributeValue, DebugAbbrev, DebugAddr, DebugAranges,
13 DebugCuIndex, DebugInfo, DebugInfoUnitHeadersIter, DebugLine, DebugLineStr, DebugLoc,
14 DebugLocLists, DebugRngLists, DebugStr, DebugStrOffsets, DebugTuIndex, DebugTypes,
15 DebugTypesUnitHeadersIter, DebuggingInformationEntry, EntriesCursor, EntriesRaw, EntriesTree,
16 Error, IncompleteLineProgram, LocListIter, LocationLists, Range, RangeLists, RawLocListIter,
17 RawRngListIter, Reader, ReaderOffset, ReaderOffsetId, Result, RngListIter, Section, UnitHeader,
18 UnitIndex, UnitIndexSectionIterator, UnitOffset, UnitType,
19};
20
21/// All of the commonly used DWARF sections, and other common information.
22#[derive(Debug, Default)]
23pub struct Dwarf<R> {
24 /// The `.debug_abbrev` section.
25 pub debug_abbrev: DebugAbbrev<R>,
26
27 /// The `.debug_addr` section.
28 pub debug_addr: DebugAddr<R>,
29
30 /// The `.debug_aranges` section.
31 pub debug_aranges: DebugAranges<R>,
32
33 /// The `.debug_info` section.
34 pub debug_info: DebugInfo<R>,
35
36 /// The `.debug_line` section.
37 pub debug_line: DebugLine<R>,
38
39 /// The `.debug_line_str` section.
40 pub debug_line_str: DebugLineStr<R>,
41
42 /// The `.debug_str` section.
43 pub debug_str: DebugStr<R>,
44
45 /// The `.debug_str_offsets` section.
46 pub debug_str_offsets: DebugStrOffsets<R>,
47
48 /// The `.debug_types` section.
49 pub debug_types: DebugTypes<R>,
50
51 /// The location lists in the `.debug_loc` and `.debug_loclists` sections.
52 pub locations: LocationLists<R>,
53
54 /// The range lists in the `.debug_ranges` and `.debug_rnglists` sections.
55 pub ranges: RangeLists<R>,
56
57 /// The type of this file.
58 pub file_type: DwarfFileType,
59
60 /// The DWARF sections for a supplementary object file.
61 pub sup: Option<Arc<Dwarf<R>>>,
62
63 /// A cache of previously parsed abbreviations for units in this file.
64 pub abbreviations_cache: AbbreviationsCache,
65}
66
67impl<T> Dwarf<T> {
68 /// Try to load the DWARF sections using the given loader function.
69 ///
70 /// `section` loads a DWARF section from the object file.
71 /// It should return an empty section if the section does not exist.
72 ///
73 /// `section` may either directly return a `Reader` instance (such as
74 /// `EndianSlice`), or it may return some other type and then convert
75 /// that type into a `Reader` using `Dwarf::borrow`.
76 ///
77 /// After loading, the user should set the `file_type` field and
78 /// call `load_sup` if required.
79 pub fn load<F, E>(mut section: F) -> core::result::Result<Self, E>
80 where
81 F: FnMut(SectionId) -> core::result::Result<T, E>,
82 {
83 // Section types are inferred.
84 let debug_loc = Section::load(&mut section)?;
85 let debug_loclists = Section::load(&mut section)?;
86 let debug_ranges = Section::load(&mut section)?;
87 let debug_rnglists = Section::load(&mut section)?;
88 Ok(Dwarf {
89 debug_abbrev: Section::load(&mut section)?,
90 debug_addr: Section::load(&mut section)?,
91 debug_aranges: Section::load(&mut section)?,
92 debug_info: Section::load(&mut section)?,
93 debug_line: Section::load(&mut section)?,
94 debug_line_str: Section::load(&mut section)?,
95 debug_str: Section::load(&mut section)?,
96 debug_str_offsets: Section::load(&mut section)?,
97 debug_types: Section::load(&mut section)?,
98 locations: LocationLists::new(debug_loc, debug_loclists),
99 ranges: RangeLists::new(debug_ranges, debug_rnglists),
100 file_type: DwarfFileType::Main,
101 sup: None,
102 abbreviations_cache: AbbreviationsCache::new(),
103 })
104 }
105
106 /// Load the DWARF sections from the supplementary object file.
107 ///
108 /// `section` operates the same as for `load`.
109 ///
110 /// Sets `self.sup`, replacing any previous value.
111 pub fn load_sup<F, E>(&mut self, section: F) -> core::result::Result<(), E>
112 where
113 F: FnMut(SectionId) -> core::result::Result<T, E>,
114 {
115 self.sup = Some(Arc::new(Self::load(section)?));
116 Ok(())
117 }
118
119 /// Create a `Dwarf` structure that references the data in `self`.
120 ///
121 /// This is useful when `R` implements `Reader` but `T` does not.
122 ///
123 /// ## Example Usage
124 ///
125 /// It can be useful to load DWARF sections into owned data structures,
126 /// such as `Vec`. However, we do not implement the `Reader` trait
127 /// for `Vec`, because it would be very inefficient, but this trait
128 /// is required for all of the methods that parse the DWARF data.
129 /// So we first load the DWARF sections into `Vec`s, and then use
130 /// `borrow` to create `Reader`s that reference the data.
131 ///
132 /// ```rust,no_run
133 /// # fn example() -> Result<(), gimli::Error> {
134 /// # let loader = |name| -> Result<_, gimli::Error> { unimplemented!() };
135 /// # let sup_loader = |name| -> Result<_, gimli::Error> { unimplemented!() };
136 /// // Read the DWARF sections into `Vec`s with whatever object loader you're using.
137 /// let mut owned_dwarf: gimli::Dwarf<Vec<u8>> = gimli::Dwarf::load(loader)?;
138 /// owned_dwarf.load_sup(sup_loader)?;
139 /// // Create references to the DWARF sections.
140 /// let dwarf = owned_dwarf.borrow(|section| {
141 /// gimli::EndianSlice::new(&section, gimli::LittleEndian)
142 /// });
143 /// # unreachable!()
144 /// # }
145 /// ```
146 pub fn borrow<'a, F, R>(&'a self, mut borrow: F) -> Dwarf<R>
147 where
148 F: FnMut(&'a T) -> R,
149 {
150 Dwarf {
151 debug_abbrev: self.debug_abbrev.borrow(&mut borrow),
152 debug_addr: self.debug_addr.borrow(&mut borrow),
153 debug_aranges: self.debug_aranges.borrow(&mut borrow),
154 debug_info: self.debug_info.borrow(&mut borrow),
155 debug_line: self.debug_line.borrow(&mut borrow),
156 debug_line_str: self.debug_line_str.borrow(&mut borrow),
157 debug_str: self.debug_str.borrow(&mut borrow),
158 debug_str_offsets: self.debug_str_offsets.borrow(&mut borrow),
159 debug_types: self.debug_types.borrow(&mut borrow),
160 locations: self.locations.borrow(&mut borrow),
161 ranges: self.ranges.borrow(&mut borrow),
162 file_type: self.file_type,
163 sup: self.sup().map(|sup| Arc::new(sup.borrow(borrow))),
164 abbreviations_cache: AbbreviationsCache::new(),
165 }
166 }
167
168 /// Return a reference to the DWARF sections for supplementary object file.
169 pub fn sup(&self) -> Option<&Dwarf<T>> {
170 self.sup.as_ref().map(Arc::as_ref)
171 }
172}
173
174impl<R: Reader> Dwarf<R> {
175 /// Iterate the unit headers in the `.debug_info` section.
176 ///
177 /// Can be [used with
178 /// `FallibleIterator`](./index.html#using-with-fallibleiterator).
179 #[inline]
180 pub fn units(&self) -> DebugInfoUnitHeadersIter<R> {
181 self.debug_info.units()
182 }
183
184 /// Construct a new `Unit` from the given unit header.
185 #[inline]
186 pub fn unit(&self, header: UnitHeader<R>) -> Result<Unit<R>> {
187 Unit::new(self, header)
188 }
189
190 /// Iterate the type-unit headers in the `.debug_types` section.
191 ///
192 /// Can be [used with
193 /// `FallibleIterator`](./index.html#using-with-fallibleiterator).
194 #[inline]
195 pub fn type_units(&self) -> DebugTypesUnitHeadersIter<R> {
196 self.debug_types.units()
197 }
198
199 /// Parse the abbreviations for a compilation unit.
200 #[inline]
201 pub fn abbreviations(&self, unit: &UnitHeader<R>) -> Result<Arc<Abbreviations>> {
202 self.abbreviations_cache
203 .get(&self.debug_abbrev, unit.debug_abbrev_offset())
204 }
205
206 /// Return the string offset at the given index.
207 #[inline]
208 pub fn string_offset(
209 &self,
210 unit: &Unit<R>,
211 index: DebugStrOffsetsIndex<R::Offset>,
212 ) -> Result<DebugStrOffset<R::Offset>> {
213 self.debug_str_offsets
214 .get_str_offset(unit.header.format(), unit.str_offsets_base, index)
215 }
216
217 /// Return the string at the given offset in `.debug_str`.
218 #[inline]
219 pub fn string(&self, offset: DebugStrOffset<R::Offset>) -> Result<R> {
220 self.debug_str.get_str(offset)
221 }
222
223 /// Return the string at the given offset in `.debug_line_str`.
224 #[inline]
225 pub fn line_string(&self, offset: DebugLineStrOffset<R::Offset>) -> Result<R> {
226 self.debug_line_str.get_str(offset)
227 }
228
229 /// Return an attribute value as a string slice.
230 ///
231 /// If the attribute value is one of:
232 ///
233 /// - an inline `DW_FORM_string` string
234 /// - a `DW_FORM_strp` reference to an offset into the `.debug_str` section
235 /// - a `DW_FORM_strp_sup` reference to an offset into a supplementary
236 /// object file
237 /// - a `DW_FORM_line_strp` reference to an offset into the `.debug_line_str`
238 /// section
239 /// - a `DW_FORM_strx` index into the `.debug_str_offsets` entries for the unit
240 ///
241 /// then return the attribute's string value. Returns an error if the attribute
242 /// value does not have a string form, or if a string form has an invalid value.
243 pub fn attr_string(&self, unit: &Unit<R>, attr: AttributeValue<R>) -> Result<R> {
244 match attr {
245 AttributeValue::String(string) => Ok(string),
246 AttributeValue::DebugStrRef(offset) => self.debug_str.get_str(offset),
247 AttributeValue::DebugStrRefSup(offset) => {
248 if let Some(sup) = self.sup() {
249 sup.debug_str.get_str(offset)
250 } else {
251 Err(Error::ExpectedStringAttributeValue)
252 }
253 }
254 AttributeValue::DebugLineStrRef(offset) => self.debug_line_str.get_str(offset),
255 AttributeValue::DebugStrOffsetsIndex(index) => {
256 let offset = self.debug_str_offsets.get_str_offset(
257 unit.header.format(),
258 unit.str_offsets_base,
259 index,
260 )?;
261 self.debug_str.get_str(offset)
262 }
263 _ => Err(Error::ExpectedStringAttributeValue),
264 }
265 }
266
267 /// Return the address at the given index.
268 pub fn address(&self, unit: &Unit<R>, index: DebugAddrIndex<R::Offset>) -> Result<u64> {
269 self.debug_addr
270 .get_address(unit.encoding().address_size, unit.addr_base, index)
271 }
272
273 /// Try to return an attribute value as an address.
274 ///
275 /// If the attribute value is one of:
276 ///
277 /// - a `DW_FORM_addr`
278 /// - a `DW_FORM_addrx` index into the `.debug_addr` entries for the unit
279 ///
280 /// then return the address.
281 /// Returns `None` for other forms.
282 pub fn attr_address(&self, unit: &Unit<R>, attr: AttributeValue<R>) -> Result<Option<u64>> {
283 match attr {
284 AttributeValue::Addr(addr) => Ok(Some(addr)),
285 AttributeValue::DebugAddrIndex(index) => self.address(unit, index).map(Some),
286 _ => Ok(None),
287 }
288 }
289
290 /// Return the range list offset for the given raw offset.
291 ///
292 /// This handles adding `DW_AT_GNU_ranges_base` if required.
293 pub fn ranges_offset_from_raw(
294 &self,
295 unit: &Unit<R>,
296 offset: RawRangeListsOffset<R::Offset>,
297 ) -> RangeListsOffset<R::Offset> {
298 if self.file_type == DwarfFileType::Dwo && unit.header.version() < 5 {
299 RangeListsOffset(offset.0.wrapping_add(unit.rnglists_base.0))
300 } else {
301 RangeListsOffset(offset.0)
302 }
303 }
304
305 /// Return the range list offset at the given index.
306 pub fn ranges_offset(
307 &self,
308 unit: &Unit<R>,
309 index: DebugRngListsIndex<R::Offset>,
310 ) -> Result<RangeListsOffset<R::Offset>> {
311 self.ranges
312 .get_offset(unit.encoding(), unit.rnglists_base, index)
313 }
314
315 /// Iterate over the `RangeListEntry`s starting at the given offset.
316 pub fn ranges(
317 &self,
318 unit: &Unit<R>,
319 offset: RangeListsOffset<R::Offset>,
320 ) -> Result<RngListIter<R>> {
321 self.ranges.ranges(
322 offset,
323 unit.encoding(),
324 unit.low_pc,
325 &self.debug_addr,
326 unit.addr_base,
327 )
328 }
329
330 /// Iterate over the `RawRngListEntry`ies starting at the given offset.
331 pub fn raw_ranges(
332 &self,
333 unit: &Unit<R>,
334 offset: RangeListsOffset<R::Offset>,
335 ) -> Result<RawRngListIter<R>> {
336 self.ranges.raw_ranges(offset, unit.encoding())
337 }
338
339 /// Try to return an attribute value as a range list offset.
340 ///
341 /// If the attribute value is one of:
342 ///
343 /// - a `DW_FORM_sec_offset` reference to the `.debug_ranges` or `.debug_rnglists` sections
344 /// - a `DW_FORM_rnglistx` index into the `.debug_rnglists` entries for the unit
345 ///
346 /// then return the range list offset of the range list.
347 /// Returns `None` for other forms.
348 pub fn attr_ranges_offset(
349 &self,
350 unit: &Unit<R>,
351 attr: AttributeValue<R>,
352 ) -> Result<Option<RangeListsOffset<R::Offset>>> {
353 match attr {
354 AttributeValue::RangeListsRef(offset) => {
355 Ok(Some(self.ranges_offset_from_raw(unit, offset)))
356 }
357 AttributeValue::DebugRngListsIndex(index) => self.ranges_offset(unit, index).map(Some),
358 _ => Ok(None),
359 }
360 }
361
362 /// Try to return an attribute value as a range list entry iterator.
363 ///
364 /// If the attribute value is one of:
365 ///
366 /// - a `DW_FORM_sec_offset` reference to the `.debug_ranges` or `.debug_rnglists` sections
367 /// - a `DW_FORM_rnglistx` index into the `.debug_rnglists` entries for the unit
368 ///
369 /// then return an iterator over the entries in the range list.
370 /// Returns `None` for other forms.
371 pub fn attr_ranges(
372 &self,
373 unit: &Unit<R>,
374 attr: AttributeValue<R>,
375 ) -> Result<Option<RngListIter<R>>> {
376 match self.attr_ranges_offset(unit, attr)? {
377 Some(offset) => Ok(Some(self.ranges(unit, offset)?)),
378 None => Ok(None),
379 }
380 }
381
382 /// Return an iterator for the address ranges of a `DebuggingInformationEntry`.
383 ///
384 /// This uses `DW_AT_low_pc`, `DW_AT_high_pc` and `DW_AT_ranges`.
385 pub fn die_ranges(
386 &self,
387 unit: &Unit<R>,
388 entry: &DebuggingInformationEntry<R>,
389 ) -> Result<RangeIter<R>> {
390 let mut low_pc = None;
391 let mut high_pc = None;
392 let mut size = None;
393 let mut attrs = entry.attrs();
394 while let Some(attr) = attrs.next()? {
395 match attr.name() {
396 constants::DW_AT_low_pc => {
397 low_pc = Some(
398 self.attr_address(unit, attr.value())?
399 .ok_or(Error::UnsupportedAttributeForm)?,
400 );
401 }
402 constants::DW_AT_high_pc => match attr.value() {
403 AttributeValue::Udata(val) => size = Some(val),
404 attr => {
405 high_pc = Some(
406 self.attr_address(unit, attr)?
407 .ok_or(Error::UnsupportedAttributeForm)?,
408 );
409 }
410 },
411 constants::DW_AT_ranges => {
412 if let Some(list) = self.attr_ranges(unit, attr.value())? {
413 return Ok(RangeIter(RangeIterInner::List(list)));
414 }
415 }
416 _ => {}
417 }
418 }
419 let range = low_pc.and_then(|begin| {
420 let end = size.map(|size| begin + size).or(high_pc);
421 // TODO: perhaps return an error if `end` is `None`
422 end.map(|end| Range { begin, end })
423 });
424 Ok(RangeIter(RangeIterInner::Single(range)))
425 }
426
427 /// Return an iterator for the address ranges of a `Unit`.
428 ///
429 /// This uses `DW_AT_low_pc`, `DW_AT_high_pc` and `DW_AT_ranges` of the
430 /// root `DebuggingInformationEntry`.
431 pub fn unit_ranges(&self, unit: &Unit<R>) -> Result<RangeIter<R>> {
432 let mut cursor = unit.header.entries(&unit.abbreviations);
433 cursor.next_dfs()?;
434 let root = cursor.current().ok_or(Error::MissingUnitDie)?;
435 self.die_ranges(unit, root)
436 }
437
438 /// Return the location list offset at the given index.
439 pub fn locations_offset(
440 &self,
441 unit: &Unit<R>,
442 index: DebugLocListsIndex<R::Offset>,
443 ) -> Result<LocationListsOffset<R::Offset>> {
444 self.locations
445 .get_offset(unit.encoding(), unit.loclists_base, index)
446 }
447
448 /// Iterate over the `LocationListEntry`s starting at the given offset.
449 pub fn locations(
450 &self,
451 unit: &Unit<R>,
452 offset: LocationListsOffset<R::Offset>,
453 ) -> Result<LocListIter<R>> {
454 match self.file_type {
455 DwarfFileType::Main => self.locations.locations(
456 offset,
457 unit.encoding(),
458 unit.low_pc,
459 &self.debug_addr,
460 unit.addr_base,
461 ),
462 DwarfFileType::Dwo => self.locations.locations_dwo(
463 offset,
464 unit.encoding(),
465 unit.low_pc,
466 &self.debug_addr,
467 unit.addr_base,
468 ),
469 }
470 }
471
472 /// Iterate over the raw `LocationListEntry`s starting at the given offset.
473 pub fn raw_locations(
474 &self,
475 unit: &Unit<R>,
476 offset: LocationListsOffset<R::Offset>,
477 ) -> Result<RawLocListIter<R>> {
478 match self.file_type {
479 DwarfFileType::Main => self.locations.raw_locations(offset, unit.encoding()),
480 DwarfFileType::Dwo => self.locations.raw_locations_dwo(offset, unit.encoding()),
481 }
482 }
483
484 /// Try to return an attribute value as a location list offset.
485 ///
486 /// If the attribute value is one of:
487 ///
488 /// - a `DW_FORM_sec_offset` reference to the `.debug_loc` or `.debug_loclists` sections
489 /// - a `DW_FORM_loclistx` index into the `.debug_loclists` entries for the unit
490 ///
491 /// then return the location list offset of the location list.
492 /// Returns `None` for other forms.
493 pub fn attr_locations_offset(
494 &self,
495 unit: &Unit<R>,
496 attr: AttributeValue<R>,
497 ) -> Result<Option<LocationListsOffset<R::Offset>>> {
498 match attr {
499 AttributeValue::LocationListsRef(offset) => Ok(Some(offset)),
500 AttributeValue::DebugLocListsIndex(index) => {
501 self.locations_offset(unit, index).map(Some)
502 }
503 _ => Ok(None),
504 }
505 }
506
507 /// Try to return an attribute value as a location list entry iterator.
508 ///
509 /// If the attribute value is one of:
510 ///
511 /// - a `DW_FORM_sec_offset` reference to the `.debug_loc` or `.debug_loclists` sections
512 /// - a `DW_FORM_loclistx` index into the `.debug_loclists` entries for the unit
513 ///
514 /// then return an iterator over the entries in the location list.
515 /// Returns `None` for other forms.
516 pub fn attr_locations(
517 &self,
518 unit: &Unit<R>,
519 attr: AttributeValue<R>,
520 ) -> Result<Option<LocListIter<R>>> {
521 match self.attr_locations_offset(unit, attr)? {
522 Some(offset) => Ok(Some(self.locations(unit, offset)?)),
523 None => Ok(None),
524 }
525 }
526
527 /// Call `Reader::lookup_offset_id` for each section, and return the first match.
528 ///
529 /// The first element of the tuple is `true` for supplementary sections.
530 pub fn lookup_offset_id(&self, id: ReaderOffsetId) -> Option<(bool, SectionId, R::Offset)> {
531 None.or_else(|| self.debug_abbrev.lookup_offset_id(id))
532 .or_else(|| self.debug_addr.lookup_offset_id(id))
533 .or_else(|| self.debug_aranges.lookup_offset_id(id))
534 .or_else(|| self.debug_info.lookup_offset_id(id))
535 .or_else(|| self.debug_line.lookup_offset_id(id))
536 .or_else(|| self.debug_line_str.lookup_offset_id(id))
537 .or_else(|| self.debug_str.lookup_offset_id(id))
538 .or_else(|| self.debug_str_offsets.lookup_offset_id(id))
539 .or_else(|| self.debug_types.lookup_offset_id(id))
540 .or_else(|| self.locations.lookup_offset_id(id))
541 .or_else(|| self.ranges.lookup_offset_id(id))
542 .map(|(id, offset)| (false, id, offset))
543 .or_else(|| {
544 self.sup()
545 .and_then(|sup| sup.lookup_offset_id(id))
546 .map(|(_, id, offset)| (true, id, offset))
547 })
548 }
549
550 /// Returns a string representation of the given error.
551 ///
552 /// This uses information from the DWARF sections to provide more information in some cases.
553 pub fn format_error(&self, err: Error) -> String {
554 #[allow(clippy::single_match)]
555 match err {
556 Error::UnexpectedEof(id) => match self.lookup_offset_id(id) {
557 Some((sup, section, offset)) => {
558 return format!(
559 "{} at {}{}+0x{:x}",
560 err,
561 section.name(),
562 if sup { "(sup)" } else { "" },
563 offset.into_u64(),
564 );
565 }
566 None => {}
567 },
568 _ => {}
569 }
570 err.description().into()
571 }
572}
573
574impl<R: Clone> Dwarf<R> {
575 /// Assuming `self` was loaded from a .dwo, take the appropriate
576 /// sections from `parent` (which contains the skeleton unit for this
577 /// dwo) such as `.debug_addr` and merge them into this `Dwarf`.
578 pub fn make_dwo(&mut self, parent: &Dwarf<R>) {
579 self.file_type = DwarfFileType::Dwo;
580 // These sections are always taken from the parent file and not the dwo.
581 self.debug_addr = parent.debug_addr.clone();
582 // .debug_rnglists comes from the DWO, .debug_ranges comes from the
583 // parent file.
584 self.ranges
585 .set_debug_ranges(parent.ranges.debug_ranges().clone());
586 self.sup = parent.sup.clone();
587 }
588}
589
590/// The sections from a `.dwp` file.
591#[derive(Debug)]
592pub struct DwarfPackage<R: Reader> {
593 /// The compilation unit index in the `.debug_cu_index` section.
594 pub cu_index: UnitIndex<R>,
595
596 /// The type unit index in the `.debug_tu_index` section.
597 pub tu_index: UnitIndex<R>,
598
599 /// The `.debug_abbrev.dwo` section.
600 pub debug_abbrev: DebugAbbrev<R>,
601
602 /// The `.debug_info.dwo` section.
603 pub debug_info: DebugInfo<R>,
604
605 /// The `.debug_line.dwo` section.
606 pub debug_line: DebugLine<R>,
607
608 /// The `.debug_str.dwo` section.
609 pub debug_str: DebugStr<R>,
610
611 /// The `.debug_str_offsets.dwo` section.
612 pub debug_str_offsets: DebugStrOffsets<R>,
613
614 /// The `.debug_loc.dwo` section.
615 ///
616 /// Only present when using GNU split-dwarf extension to DWARF 4.
617 pub debug_loc: DebugLoc<R>,
618
619 /// The `.debug_loclists.dwo` section.
620 pub debug_loclists: DebugLocLists<R>,
621
622 /// The `.debug_rnglists.dwo` section.
623 pub debug_rnglists: DebugRngLists<R>,
624
625 /// The `.debug_types.dwo` section.
626 ///
627 /// Only present when using GNU split-dwarf extension to DWARF 4.
628 pub debug_types: DebugTypes<R>,
629
630 /// An empty section.
631 ///
632 /// Used when creating `Dwarf<R>`.
633 pub empty: R,
634}
635
636impl<R: Reader> DwarfPackage<R> {
637 /// Try to load the `.dwp` sections using the given loader function.
638 ///
639 /// `section` loads a DWARF section from the object file.
640 /// It should return an empty section if the section does not exist.
641 pub fn load<F, E>(mut section: F, empty: R) -> core::result::Result<Self, E>
642 where
643 F: FnMut(SectionId) -> core::result::Result<R, E>,
644 E: From<Error>,
645 {
646 Ok(DwarfPackage {
647 cu_index: DebugCuIndex::load(&mut section)?.index()?,
648 tu_index: DebugTuIndex::load(&mut section)?.index()?,
649 // Section types are inferred.
650 debug_abbrev: Section::load(&mut section)?,
651 debug_info: Section::load(&mut section)?,
652 debug_line: Section::load(&mut section)?,
653 debug_str: Section::load(&mut section)?,
654 debug_str_offsets: Section::load(&mut section)?,
655 debug_loc: Section::load(&mut section)?,
656 debug_loclists: Section::load(&mut section)?,
657 debug_rnglists: Section::load(&mut section)?,
658 debug_types: Section::load(&mut section)?,
659 empty,
660 })
661 }
662
663 /// Find the compilation unit with the given DWO identifier and return its section
664 /// contributions.
665 pub fn find_cu(&self, id: DwoId, parent: &Dwarf<R>) -> Result<Option<Dwarf<R>>> {
666 let row = match self.cu_index.find(id.0) {
667 Some(row) => row,
668 None => return Ok(None),
669 };
670 self.cu_sections(row, parent).map(Some)
671 }
672
673 /// Find the type unit with the given type signature and return its section
674 /// contributions.
675 pub fn find_tu(
676 &self,
677 signature: DebugTypeSignature,
678 parent: &Dwarf<R>,
679 ) -> Result<Option<Dwarf<R>>> {
680 let row = match self.tu_index.find(signature.0) {
681 Some(row) => row,
682 None => return Ok(None),
683 };
684 self.tu_sections(row, parent).map(Some)
685 }
686
687 /// Return the section contributions of the compilation unit at the given index.
688 ///
689 /// The index must be in the range `1..cu_index.unit_count`.
690 ///
691 /// This function should only be needed by low level parsers.
692 pub fn cu_sections(&self, index: u32, parent: &Dwarf<R>) -> Result<Dwarf<R>> {
693 self.sections(self.cu_index.sections(index)?, parent)
694 }
695
696 /// Return the section contributions of the compilation unit at the given index.
697 ///
698 /// The index must be in the range `1..tu_index.unit_count`.
699 ///
700 /// This function should only be needed by low level parsers.
701 pub fn tu_sections(&self, index: u32, parent: &Dwarf<R>) -> Result<Dwarf<R>> {
702 self.sections(self.tu_index.sections(index)?, parent)
703 }
704
705 /// Return the section contributions of a unit.
706 ///
707 /// This function should only be needed by low level parsers.
708 pub fn sections(
709 &self,
710 sections: UnitIndexSectionIterator<R>,
711 parent: &Dwarf<R>,
712 ) -> Result<Dwarf<R>> {
713 let mut abbrev_offset = 0;
714 let mut abbrev_size = 0;
715 let mut info_offset = 0;
716 let mut info_size = 0;
717 let mut line_offset = 0;
718 let mut line_size = 0;
719 let mut loc_offset = 0;
720 let mut loc_size = 0;
721 let mut loclists_offset = 0;
722 let mut loclists_size = 0;
723 let mut str_offsets_offset = 0;
724 let mut str_offsets_size = 0;
725 let mut rnglists_offset = 0;
726 let mut rnglists_size = 0;
727 let mut types_offset = 0;
728 let mut types_size = 0;
729 for section in sections {
730 match section.section {
731 SectionId::DebugAbbrev => {
732 abbrev_offset = section.offset;
733 abbrev_size = section.size;
734 }
735 SectionId::DebugInfo => {
736 info_offset = section.offset;
737 info_size = section.size;
738 }
739 SectionId::DebugLine => {
740 line_offset = section.offset;
741 line_size = section.size;
742 }
743 SectionId::DebugLoc => {
744 loc_offset = section.offset;
745 loc_size = section.size;
746 }
747 SectionId::DebugLocLists => {
748 loclists_offset = section.offset;
749 loclists_size = section.size;
750 }
751 SectionId::DebugStrOffsets => {
752 str_offsets_offset = section.offset;
753 str_offsets_size = section.size;
754 }
755 SectionId::DebugRngLists => {
756 rnglists_offset = section.offset;
757 rnglists_size = section.size;
758 }
759 SectionId::DebugTypes => {
760 types_offset = section.offset;
761 types_size = section.size;
762 }
763 SectionId::DebugMacro | SectionId::DebugMacinfo => {
764 // These are valid but we can't parse these yet.
765 }
766 _ => return Err(Error::UnknownIndexSection),
767 }
768 }
769
770 let debug_abbrev = self.debug_abbrev.dwp_range(abbrev_offset, abbrev_size)?;
771 let debug_info = self.debug_info.dwp_range(info_offset, info_size)?;
772 let debug_line = self.debug_line.dwp_range(line_offset, line_size)?;
773 let debug_loc = self.debug_loc.dwp_range(loc_offset, loc_size)?;
774 let debug_loclists = self
775 .debug_loclists
776 .dwp_range(loclists_offset, loclists_size)?;
777 let debug_str_offsets = self
778 .debug_str_offsets
779 .dwp_range(str_offsets_offset, str_offsets_size)?;
780 let debug_rnglists = self
781 .debug_rnglists
782 .dwp_range(rnglists_offset, rnglists_size)?;
783 let debug_types = self.debug_types.dwp_range(types_offset, types_size)?;
784
785 let debug_str = self.debug_str.clone();
786
787 let debug_addr = parent.debug_addr.clone();
788 let debug_ranges = parent.ranges.debug_ranges().clone();
789
790 let debug_aranges = self.empty.clone().into();
791 let debug_line_str = self.empty.clone().into();
792
793 Ok(Dwarf {
794 debug_abbrev,
795 debug_addr,
796 debug_aranges,
797 debug_info,
798 debug_line,
799 debug_line_str,
800 debug_str,
801 debug_str_offsets,
802 debug_types,
803 locations: LocationLists::new(debug_loc, debug_loclists),
804 ranges: RangeLists::new(debug_ranges, debug_rnglists),
805 file_type: DwarfFileType::Dwo,
806 sup: parent.sup.clone(),
807 abbreviations_cache: AbbreviationsCache::new(),
808 })
809 }
810}
811
812/// All of the commonly used information for a unit in the `.debug_info` or `.debug_types`
813/// sections.
814#[derive(Debug)]
815pub struct Unit<R, Offset = <R as Reader>::Offset>
816where
817 R: Reader<Offset = Offset>,
818 Offset: ReaderOffset,
819{
820 /// The header of the unit.
821 pub header: UnitHeader<R, Offset>,
822
823 /// The parsed abbreviations for the unit.
824 pub abbreviations: Arc<Abbreviations>,
825
826 /// The `DW_AT_name` attribute of the unit.
827 pub name: Option<R>,
828
829 /// The `DW_AT_comp_dir` attribute of the unit.
830 pub comp_dir: Option<R>,
831
832 /// The `DW_AT_low_pc` attribute of the unit. Defaults to 0.
833 pub low_pc: u64,
834
835 /// The `DW_AT_str_offsets_base` attribute of the unit. Defaults to 0.
836 pub str_offsets_base: DebugStrOffsetsBase<Offset>,
837
838 /// The `DW_AT_addr_base` attribute of the unit. Defaults to 0.
839 pub addr_base: DebugAddrBase<Offset>,
840
841 /// The `DW_AT_loclists_base` attribute of the unit. Defaults to 0.
842 pub loclists_base: DebugLocListsBase<Offset>,
843
844 /// The `DW_AT_rnglists_base` attribute of the unit. Defaults to 0.
845 pub rnglists_base: DebugRngListsBase<Offset>,
846
847 /// The line number program of the unit.
848 pub line_program: Option<IncompleteLineProgram<R, Offset>>,
849
850 /// The DWO ID of a skeleton unit or split compilation unit.
851 pub dwo_id: Option<DwoId>,
852}
853
854impl<R: Reader> Unit<R> {
855 /// Construct a new `Unit` from the given unit header.
856 #[inline]
857 pub fn new(dwarf: &Dwarf<R>, header: UnitHeader<R>) -> Result<Self> {
858 let abbreviations = dwarf.abbreviations(&header)?;
859 let mut unit = Unit {
860 abbreviations,
861 name: None,
862 comp_dir: None,
863 low_pc: 0,
864 str_offsets_base: DebugStrOffsetsBase::default_for_encoding_and_file(
865 header.encoding(),
866 dwarf.file_type,
867 ),
868 // NB: Because the .debug_addr section never lives in a .dwo, we can assume its base is always 0 or provided.
869 addr_base: DebugAddrBase(R::Offset::from_u8(0)),
870 loclists_base: DebugLocListsBase::default_for_encoding_and_file(
871 header.encoding(),
872 dwarf.file_type,
873 ),
874 rnglists_base: DebugRngListsBase::default_for_encoding_and_file(
875 header.encoding(),
876 dwarf.file_type,
877 ),
878 line_program: None,
879 dwo_id: match header.type_() {
880 UnitType::Skeleton(dwo_id) | UnitType::SplitCompilation(dwo_id) => Some(dwo_id),
881 _ => None,
882 },
883 header,
884 };
885 let mut name = None;
886 let mut comp_dir = None;
887 let mut line_program_offset = None;
888 let mut low_pc_attr = None;
889
890 {
891 let mut cursor = unit.header.entries(&unit.abbreviations);
892 cursor.next_dfs()?;
893 let root = cursor.current().ok_or(Error::MissingUnitDie)?;
894 let mut attrs = root.attrs();
895 while let Some(attr) = attrs.next()? {
896 match attr.name() {
897 constants::DW_AT_name => {
898 name = Some(attr.value());
899 }
900 constants::DW_AT_comp_dir => {
901 comp_dir = Some(attr.value());
902 }
903 constants::DW_AT_low_pc => {
904 low_pc_attr = Some(attr.value());
905 }
906 constants::DW_AT_stmt_list => {
907 if let AttributeValue::DebugLineRef(offset) = attr.value() {
908 line_program_offset = Some(offset);
909 }
910 }
911 constants::DW_AT_str_offsets_base => {
912 if let AttributeValue::DebugStrOffsetsBase(base) = attr.value() {
913 unit.str_offsets_base = base;
914 }
915 }
916 constants::DW_AT_addr_base | constants::DW_AT_GNU_addr_base => {
917 if let AttributeValue::DebugAddrBase(base) = attr.value() {
918 unit.addr_base = base;
919 }
920 }
921 constants::DW_AT_loclists_base => {
922 if let AttributeValue::DebugLocListsBase(base) = attr.value() {
923 unit.loclists_base = base;
924 }
925 }
926 constants::DW_AT_rnglists_base | constants::DW_AT_GNU_ranges_base => {
927 if let AttributeValue::DebugRngListsBase(base) = attr.value() {
928 unit.rnglists_base = base;
929 }
930 }
931 constants::DW_AT_GNU_dwo_id => {
932 if unit.dwo_id.is_none() {
933 if let AttributeValue::DwoId(dwo_id) = attr.value() {
934 unit.dwo_id = Some(dwo_id);
935 }
936 }
937 }
938 _ => {}
939 }
940 }
941 }
942
943 unit.name = match name {
944 Some(val) => dwarf.attr_string(&unit, val).ok(),
945 None => None,
946 };
947 unit.comp_dir = match comp_dir {
948 Some(val) => dwarf.attr_string(&unit, val).ok(),
949 None => None,
950 };
951 unit.line_program = match line_program_offset {
952 Some(offset) => Some(dwarf.debug_line.program(
953 offset,
954 unit.header.address_size(),
955 unit.comp_dir.clone(),
956 unit.name.clone(),
957 )?),
958 None => None,
959 };
960 if let Some(low_pc_attr) = low_pc_attr {
961 if let Some(addr) = dwarf.attr_address(&unit, low_pc_attr)? {
962 unit.low_pc = addr;
963 }
964 }
965 Ok(unit)
966 }
967
968 /// Return the encoding parameters for this unit.
969 #[inline]
970 pub fn encoding(&self) -> Encoding {
971 self.header.encoding()
972 }
973
974 /// Read the `DebuggingInformationEntry` at the given offset.
975 pub fn entry(&self, offset: UnitOffset<R::Offset>) -> Result<DebuggingInformationEntry<R>> {
976 self.header.entry(&self.abbreviations, offset)
977 }
978
979 /// Navigate this unit's `DebuggingInformationEntry`s.
980 #[inline]
981 pub fn entries(&self) -> EntriesCursor<R> {
982 self.header.entries(&self.abbreviations)
983 }
984
985 /// Navigate this unit's `DebuggingInformationEntry`s
986 /// starting at the given offset.
987 #[inline]
988 pub fn entries_at_offset(&self, offset: UnitOffset<R::Offset>) -> Result<EntriesCursor<R>> {
989 self.header.entries_at_offset(&self.abbreviations, offset)
990 }
991
992 /// Navigate this unit's `DebuggingInformationEntry`s as a tree
993 /// starting at the given offset.
994 #[inline]
995 pub fn entries_tree(&self, offset: Option<UnitOffset<R::Offset>>) -> Result<EntriesTree<R>> {
996 self.header.entries_tree(&self.abbreviations, offset)
997 }
998
999 /// Read the raw data that defines the Debugging Information Entries.
1000 #[inline]
1001 pub fn entries_raw(&self, offset: Option<UnitOffset<R::Offset>>) -> Result<EntriesRaw<R>> {
1002 self.header.entries_raw(&self.abbreviations, offset)
1003 }
1004
1005 /// Copy attributes that are subject to relocation from another unit. This is intended
1006 /// to be used to copy attributes from a skeleton compilation unit to the corresponding
1007 /// split compilation unit.
1008 pub fn copy_relocated_attributes(&mut self, other: &Unit<R>) {
1009 self.low_pc = other.low_pc;
1010 self.addr_base = other.addr_base;
1011 if self.header.version() < 5 {
1012 self.rnglists_base = other.rnglists_base;
1013 }
1014 }
1015
1016 /// Find the dwo name (if any) for this unit, automatically handling the differences
1017 /// between the standardized DWARF 5 split DWARF format and the pre-DWARF 5 GNU
1018 /// extension.
1019 ///
1020 /// The returned value is relative to this unit's `comp_dir`.
1021 pub fn dwo_name(&self) -> Result<Option<AttributeValue<R>>> {
1022 let mut entries = self.entries();
1023 if let None = entries.next_entry()? {
1024 return Ok(None);
1025 }
1026
1027 let entry = entries.current().unwrap();
1028 if self.header.version() < 5 {
1029 entry.attr_value(constants::DW_AT_GNU_dwo_name)
1030 } else {
1031 entry.attr_value(constants::DW_AT_dwo_name)
1032 }
1033 }
1034}
1035
1036impl<T: ReaderOffset> UnitSectionOffset<T> {
1037 /// Convert an offset to be relative to the start of the given unit,
1038 /// instead of relative to the start of the section.
1039 /// Returns `None` if the offset is not within the unit entries.
1040 pub fn to_unit_offset<R>(&self, unit: &Unit<R>) -> Option<UnitOffset<T>>
1041 where
1042 R: Reader<Offset = T>,
1043 {
1044 let (offset, unit_offset) = match (self, unit.header.offset()) {
1045 (
1046 UnitSectionOffset::DebugInfoOffset(offset),
1047 UnitSectionOffset::DebugInfoOffset(unit_offset),
1048 ) => (offset.0, unit_offset.0),
1049 (
1050 UnitSectionOffset::DebugTypesOffset(offset),
1051 UnitSectionOffset::DebugTypesOffset(unit_offset),
1052 ) => (offset.0, unit_offset.0),
1053 _ => return None,
1054 };
1055 let offset = match offset.checked_sub(unit_offset) {
1056 Some(offset) => UnitOffset(offset),
1057 None => return None,
1058 };
1059 if !unit.header.is_valid_offset(offset) {
1060 return None;
1061 }
1062 Some(offset)
1063 }
1064}
1065
1066impl<T: ReaderOffset> UnitOffset<T> {
1067 /// Convert an offset to be relative to the start of the .debug_info section,
1068 /// instead of relative to the start of the given compilation unit.
1069 ///
1070 /// Does not check that the offset is valid.
1071 pub fn to_unit_section_offset<R>(&self, unit: &Unit<R>) -> UnitSectionOffset<T>
1072 where
1073 R: Reader<Offset = T>,
1074 {
1075 match unit.header.offset() {
1076 UnitSectionOffset::DebugInfoOffset(unit_offset: DebugInfoOffset) => {
1077 DebugInfoOffset(unit_offset.0 + self.0).into()
1078 }
1079 UnitSectionOffset::DebugTypesOffset(unit_offset: DebugTypesOffset) => {
1080 DebugTypesOffset(unit_offset.0 + self.0).into()
1081 }
1082 }
1083 }
1084}
1085
1086/// An iterator for the address ranges of a `DebuggingInformationEntry`.
1087///
1088/// Returned by `Dwarf::die_ranges` and `Dwarf::unit_ranges`.
1089#[derive(Debug)]
1090pub struct RangeIter<R: Reader>(RangeIterInner<R>);
1091
1092#[derive(Debug)]
1093enum RangeIterInner<R: Reader> {
1094 Single(Option<Range>),
1095 List(RngListIter<R>),
1096}
1097
1098impl<R: Reader> Default for RangeIter<R> {
1099 fn default() -> Self {
1100 RangeIter(RangeIterInner::Single(None))
1101 }
1102}
1103
1104impl<R: Reader> RangeIter<R> {
1105 /// Advance the iterator to the next range.
1106 pub fn next(&mut self) -> Result<Option<Range>> {
1107 match self.0 {
1108 RangeIterInner::Single(ref mut range: &mut {unknown}) => Ok(range.take()),
1109 RangeIterInner::List(ref mut list: &mut RngListIter) => list.next(),
1110 }
1111 }
1112}
1113
1114#[cfg(feature = "fallible-iterator")]
1115impl<R: Reader> fallible_iterator::FallibleIterator for RangeIter<R> {
1116 type Item = Range;
1117 type Error = Error;
1118
1119 #[inline]
1120 fn next(&mut self) -> ::core::result::Result<Option<Self::Item>, Self::Error> {
1121 RangeIter::next(self)
1122 }
1123}
1124
1125#[cfg(test)]
1126mod tests {
1127 use super::*;
1128 use crate::read::EndianSlice;
1129 use crate::{Endianity, LittleEndian};
1130
1131 /// Ensure that `Dwarf<R>` is covariant wrt R.
1132 #[test]
1133 fn test_dwarf_variance() {
1134 /// This only needs to compile.
1135 fn _f<'a: 'b, 'b, E: Endianity>(x: Dwarf<EndianSlice<'a, E>>) -> Dwarf<EndianSlice<'b, E>> {
1136 x
1137 }
1138 }
1139
1140 /// Ensure that `Unit<R>` is covariant wrt R.
1141 #[test]
1142 fn test_dwarf_unit_variance() {
1143 /// This only needs to compile.
1144 fn _f<'a: 'b, 'b, E: Endianity>(x: Unit<EndianSlice<'a, E>>) -> Unit<EndianSlice<'b, E>> {
1145 x
1146 }
1147 }
1148
1149 #[test]
1150 fn test_send() {
1151 fn assert_is_send<T: Send>() {}
1152 assert_is_send::<Dwarf<EndianSlice<LittleEndian>>>();
1153 assert_is_send::<Unit<EndianSlice<LittleEndian>>>();
1154 }
1155
1156 #[test]
1157 fn test_format_error() {
1158 let mut owned_dwarf = Dwarf::load(|_| -> Result<_> { Ok(vec![1, 2]) }).unwrap();
1159 owned_dwarf
1160 .load_sup(|_| -> Result<_> { Ok(vec![1, 2]) })
1161 .unwrap();
1162 let dwarf = owned_dwarf.borrow(|section| EndianSlice::new(&section, LittleEndian));
1163
1164 match dwarf.debug_str.get_str(DebugStrOffset(1)) {
1165 Ok(r) => panic!("Unexpected str {:?}", r),
1166 Err(e) => {
1167 assert_eq!(
1168 dwarf.format_error(e),
1169 "Hit the end of input before it was expected at .debug_str+0x1"
1170 );
1171 }
1172 }
1173 match dwarf.sup().unwrap().debug_str.get_str(DebugStrOffset(1)) {
1174 Ok(r) => panic!("Unexpected str {:?}", r),
1175 Err(e) => {
1176 assert_eq!(
1177 dwarf.format_error(e),
1178 "Hit the end of input before it was expected at .debug_str(sup)+0x1"
1179 );
1180 }
1181 }
1182 assert_eq!(dwarf.format_error(Error::Io), Error::Io.description());
1183 }
1184}
1185