gimli/read/
mod.rs

1//! Read DWARF debugging information.
2//!
3//! * [Example Usage](#example-usage)
4//! * [API Structure](#api-structure)
5//! * [Using with `FallibleIterator`](#using-with-fallibleiterator)
6//!
7//! ## Example Usage
8//!
9//! Print out all of the functions in the debuggee program:
10//!
11//! ```rust,no_run
12//! # fn example() -> Result<(), gimli::Error> {
13//! # type R = gimli::EndianSlice<'static, gimli::LittleEndian>;
14//! # let get_file_section_reader = |name| -> Result<R, gimli::Error> { unimplemented!() };
15//! # let get_sup_file_section_reader = |name| -> Result<R, gimli::Error> { unimplemented!() };
16//! // Read the DWARF sections with whatever object loader you're using.
17//! // These closures should return a `Reader` instance (e.g. `EndianSlice`).
18//! let loader = |section: gimli::SectionId| { get_file_section_reader(section.name()) };
19//! let sup_loader = |section: gimli::SectionId| { get_sup_file_section_reader(section.name()) };
20//! let mut dwarf = gimli::Dwarf::load(loader)?;
21//! dwarf.load_sup(sup_loader)?;
22//!
23//! // Iterate over all compilation units.
24//! let mut iter = dwarf.units();
25//! while let Some(header) = iter.next()? {
26//!     // Parse the abbreviations and other information for this compilation unit.
27//!     let unit = dwarf.unit(header)?;
28//!
29//!     // Iterate over all of this compilation unit's entries.
30//!     let mut entries = unit.entries();
31//!     while let Some((_, entry)) = entries.next_dfs()? {
32//!         // If we find an entry for a function, print it.
33//!         if entry.tag() == gimli::DW_TAG_subprogram {
34//!             println!("Found a function: {:?}", entry);
35//!         }
36//!     }
37//! }
38//! # unreachable!()
39//! # }
40//! ```
41//!
42//! Full example programs:
43//!
44//!   * [A simple parser](https://github.com/gimli-rs/gimli/blob/master/crates/examples/src/bin/simple.rs)
45//!
46//!   * [A `dwarfdump`
47//!     clone](https://github.com/gimli-rs/gimli/blob/master/crates/examples/src/bin/dwarfdump.rs)
48//!
49//!   * [An `addr2line` clone](https://github.com/gimli-rs/addr2line)
50//!
51//!   * [`ddbug`](https://github.com/gimli-rs/ddbug), a utility giving insight into
52//!     code generation by making debugging information readable
53//!
54//!   * [`dwprod`](https://github.com/fitzgen/dwprod), a tiny utility to list the
55//!     compilers used to create each compilation unit within a shared library or
56//!     executable (via `DW_AT_producer`)
57//!
58//!   * [`dwarf-validate`](https://github.com/gimli-rs/gimli/blob/master/crates/examples/src/bin/dwarf-validate.rs),
59//!     a program to validate the integrity of some DWARF and its references
60//!     between sections and compilation units.
61//!
62//! ## API Structure
63//!
64//! * Basic familiarity with DWARF is assumed.
65//!
66//! * The [`Dwarf`](./struct.Dwarf.html) type contains the commonly used DWARF
67//!   sections. It has methods that simplify access to debugging data that spans
68//!   multiple sections. Use of this type is optional, but recommended.
69//!
70//! * The [`DwarfPackage`](./struct.Dwarf.html) type contains the DWARF
71//!   package (DWP) sections. It has methods to find a DWARF object (DWO)
72//!   within the package.
73//!
74//! * Each section gets its own type. Consider these types the entry points to
75//!   the library:
76//!
77//!   * [`DebugAbbrev`](./struct.DebugAbbrev.html): The `.debug_abbrev` section.
78//!
79//!   * [`DebugAddr`](./struct.DebugAddr.html): The `.debug_addr` section.
80//!
81//!   * [`DebugAranges`](./struct.DebugAranges.html): The `.debug_aranges`
82//!     section.
83//!
84//!   * [`DebugFrame`](./struct.DebugFrame.html): The `.debug_frame` section.
85//!
86//!   * [`DebugInfo`](./struct.DebugInfo.html): The `.debug_info` section.
87//!
88//!   * [`DebugLine`](./struct.DebugLine.html): The `.debug_line` section.
89//!
90//!   * [`DebugLineStr`](./struct.DebugLineStr.html): The `.debug_line_str` section.
91//!
92//!   * [`DebugLoc`](./struct.DebugLoc.html): The `.debug_loc` section.
93//!
94//!   * [`DebugLocLists`](./struct.DebugLocLists.html): The `.debug_loclists` section.
95//!
96//!   * [`DebugPubNames`](./struct.DebugPubNames.html): The `.debug_pubnames`
97//!     section.
98//!
99//!   * [`DebugPubTypes`](./struct.DebugPubTypes.html): The `.debug_pubtypes`
100//!     section.
101//!
102//!   * [`DebugRanges`](./struct.DebugRanges.html): The `.debug_ranges` section.
103//!
104//!   * [`DebugRngLists`](./struct.DebugRngLists.html): The `.debug_rnglists` section.
105//!
106//!   * [`DebugStr`](./struct.DebugStr.html): The `.debug_str` section.
107//!
108//!   * [`DebugStrOffsets`](./struct.DebugStrOffsets.html): The `.debug_str_offsets` section.
109//!
110//!   * [`DebugTypes`](./struct.DebugTypes.html): The `.debug_types` section.
111//!
112//!   * [`DebugCuIndex`](./struct.DebugCuIndex.html): The `.debug_cu_index` section.
113//!
114//!   * [`DebugTuIndex`](./struct.DebugTuIndex.html): The `.debug_tu_index` section.
115//!
116//!   * [`EhFrame`](./struct.EhFrame.html): The `.eh_frame` section.
117//!
118//!   * [`EhFrameHdr`](./struct.EhFrameHdr.html): The `.eh_frame_hdr` section.
119//!
120//! * Each section type exposes methods for accessing the debugging data encoded
121//!   in that section. For example, the [`DebugInfo`](./struct.DebugInfo.html)
122//!   struct has the [`units`](./struct.DebugInfo.html#method.units) method for
123//!   iterating over the compilation units defined within it.
124//!
125//! * Offsets into a section are strongly typed: an offset into `.debug_info` is
126//!   the [`DebugInfoOffset`](./struct.DebugInfoOffset.html) type. It cannot be
127//!   used to index into the [`DebugLine`](./struct.DebugLine.html) type because
128//!   `DebugLine` represents the `.debug_line` section. There are similar types
129//!   for offsets relative to a compilation unit rather than a section.
130//!
131//! ## Using with `FallibleIterator`
132//!
133//! The standard library's `Iterator` trait and related APIs do not play well
134//! with iterators where the `next` operation is fallible. One can make the
135//! `Iterator`'s associated `Item` type be a `Result<T, E>`, however the
136//! provided methods cannot gracefully handle the case when an `Err` is
137//! returned.
138//!
139//! This situation led to the
140//! [`fallible-iterator`](https://crates.io/crates/fallible-iterator) crate's
141//! existence. You can read more of the rationale for its existence in its
142//! docs. The crate provides the helpers you have come to expect (eg `map`,
143//! `filter`, etc) for iterators that can fail.
144//!
145//! `gimli`'s many lazy parsing iterators are a perfect match for the
146//! `fallible-iterator` crate's `FallibleIterator` trait because parsing is not
147//! done eagerly. Parse errors later in the input might only be discovered after
148//! having iterated through many items.
149//!
150//! To use `gimli` iterators with `FallibleIterator`, import the crate and trait
151//! into your code:
152//!
153//! ```
154//! # #[cfg(feature = "fallible-iterator")]
155//! # fn foo() {
156//! // Use the `FallibleIterator` trait so its methods are in scope!
157//! use fallible_iterator::FallibleIterator;
158//! use gimli::{DebugAranges, EndianSlice, LittleEndian};
159//!
160//! fn find_sum_of_address_range_lengths(aranges: DebugAranges<EndianSlice<LittleEndian>>)
161//!     -> gimli::Result<u64>
162//! {
163//!     // `DebugAranges::headers` returns a `FallibleIterator`!
164//!     aranges.headers()
165//!         // `flat_map` is provided by `FallibleIterator`!
166//!         .flat_map(|header| Ok(header.entries()))
167//!         // `map` is provided by `FallibleIterator`!
168//!         .map(|arange| Ok(arange.length()))
169//!         // `fold` is provided by `FallibleIterator`!
170//!         .fold(0, |sum, len| Ok(sum + len))
171//! }
172//! # }
173//! # fn main() {}
174//! ```
175
176use core::fmt::{self, Debug};
177use core::result;
178#[cfg(feature = "std")]
179use std::{error, io};
180
181use crate::common::{Register, SectionId};
182use crate::constants;
183
184mod util;
185pub use util::*;
186
187mod addr;
188pub use self::addr::*;
189
190mod cfi;
191pub use self::cfi::*;
192
193#[cfg(feature = "read")]
194mod dwarf;
195#[cfg(feature = "read")]
196pub use self::dwarf::*;
197
198mod endian_slice;
199pub use self::endian_slice::*;
200
201#[cfg(feature = "endian-reader")]
202mod endian_reader;
203#[cfg(feature = "endian-reader")]
204pub use self::endian_reader::*;
205
206mod reader;
207pub use self::reader::*;
208
209mod relocate;
210pub use self::relocate::*;
211
212#[cfg(feature = "read")]
213mod abbrev;
214#[cfg(feature = "read")]
215pub use self::abbrev::*;
216
217mod aranges;
218pub use self::aranges::*;
219
220mod index;
221pub use self::index::*;
222
223#[cfg(feature = "read")]
224mod line;
225#[cfg(feature = "read")]
226pub use self::line::*;
227
228mod lists;
229
230mod loclists;
231pub use self::loclists::*;
232
233#[cfg(feature = "read")]
234mod lookup;
235
236mod op;
237pub use self::op::*;
238
239#[cfg(feature = "read")]
240mod pubnames;
241#[cfg(feature = "read")]
242pub use self::pubnames::*;
243
244#[cfg(feature = "read")]
245mod pubtypes;
246#[cfg(feature = "read")]
247pub use self::pubtypes::*;
248
249mod rnglists;
250pub use self::rnglists::*;
251
252mod str;
253pub use self::str::*;
254
255/// An offset into the current compilation or type unit.
256#[derive(Debug, Clone, Copy, PartialEq, Eq, Ord, PartialOrd, Hash)]
257pub struct UnitOffset<T = usize>(pub T);
258
259#[cfg(feature = "read")]
260mod unit;
261#[cfg(feature = "read")]
262pub use self::unit::*;
263
264mod value;
265pub use self::value::*;
266
267/// Indicates that storage should be allocated on heap.
268#[derive(Debug, Clone, Copy, PartialEq, Eq)]
269pub struct StoreOnHeap;
270
271/// `EndianBuf` has been renamed to `EndianSlice`. For ease of upgrading across
272/// `gimli` versions, we export this type alias.
273#[deprecated(note = "EndianBuf has been renamed to EndianSlice, use that instead.")]
274pub type EndianBuf<'input, Endian> = EndianSlice<'input, Endian>;
275
276/// An error that occurred when parsing.
277#[derive(Debug, Clone, Copy, PartialEq, Eq)]
278#[non_exhaustive]
279pub enum Error {
280    /// An I/O error occurred while reading.
281    Io,
282    /// Found a PC relative pointer, but the section base is undefined.
283    PcRelativePointerButSectionBaseIsUndefined,
284    /// Found a `.text` relative pointer, but the `.text` base is undefined.
285    TextRelativePointerButTextBaseIsUndefined,
286    /// Found a data relative pointer, but the data base is undefined.
287    DataRelativePointerButDataBaseIsUndefined,
288    /// Found a function relative pointer in a context that does not have a
289    /// function base.
290    FuncRelativePointerInBadContext,
291    /// Cannot parse a pointer with a `DW_EH_PE_omit` encoding.
292    CannotParseOmitPointerEncoding,
293    /// An error parsing an unsigned LEB128 value.
294    BadUnsignedLeb128,
295    /// An error parsing a signed LEB128 value.
296    BadSignedLeb128,
297    /// An abbreviation declared that its tag is zero, but zero is reserved for
298    /// null records.
299    AbbreviationTagZero,
300    /// An attribute specification declared that its form is zero, but zero is
301    /// reserved for null records.
302    AttributeFormZero,
303    /// The abbreviation's has-children byte was not one of
304    /// `DW_CHILDREN_{yes,no}`.
305    BadHasChildren,
306    /// The specified length is impossible.
307    BadLength,
308    /// Found an unknown `DW_FORM_*` type.
309    UnknownForm(constants::DwForm),
310    /// Expected a zero, found something else.
311    ExpectedZero,
312    /// Found an abbreviation code that has already been used.
313    DuplicateAbbreviationCode,
314    /// Found a duplicate arange.
315    DuplicateArange,
316    /// Found an unknown reserved length value.
317    UnknownReservedLength,
318    /// Found an unknown DWARF version.
319    UnknownVersion(u64),
320    /// Found a record with an unknown abbreviation code.
321    UnknownAbbreviation(u64),
322    /// Hit the end of input before it was expected.
323    UnexpectedEof(ReaderOffsetId),
324    /// Read a null entry before it was expected.
325    UnexpectedNull,
326    /// Found an unknown standard opcode.
327    UnknownStandardOpcode(constants::DwLns),
328    /// Found an unknown extended opcode.
329    UnknownExtendedOpcode(constants::DwLne),
330    /// Found an unknown location-lists format.
331    UnknownLocListsEntry(constants::DwLle),
332    /// Found an unknown range-lists format.
333    UnknownRangeListsEntry(constants::DwRle),
334    /// The specified address size is not supported.
335    UnsupportedAddressSize(u8),
336    /// The specified offset size is not supported.
337    UnsupportedOffsetSize(u8),
338    /// The specified field size is not supported.
339    UnsupportedFieldSize(u8),
340    /// The minimum instruction length must not be zero.
341    MinimumInstructionLengthZero,
342    /// The maximum operations per instruction must not be zero.
343    MaximumOperationsPerInstructionZero,
344    /// The line range must not be zero.
345    LineRangeZero,
346    /// The opcode base must not be zero.
347    OpcodeBaseZero,
348    /// Found an invalid UTF-8 string.
349    BadUtf8,
350    /// Expected to find the CIE ID, but found something else.
351    NotCieId,
352    /// Expected to find a pointer to a CIE, but found the CIE ID instead.
353    NotCiePointer,
354    /// Expected to find a pointer to an FDE, but found a CIE instead.
355    NotFdePointer,
356    /// Invalid branch target for a DW_OP_bra or DW_OP_skip.
357    BadBranchTarget(u64),
358    /// DW_OP_push_object_address used but no address passed in.
359    InvalidPushObjectAddress,
360    /// Not enough items on the stack when evaluating an expression.
361    NotEnoughStackItems,
362    /// Too many iterations to compute the expression.
363    TooManyIterations,
364    /// An unrecognized operation was found while parsing a DWARF
365    /// expression.
366    InvalidExpression(constants::DwOp),
367    /// An unsupported operation was found while evaluating a DWARF expression.
368    UnsupportedEvaluation,
369    /// The expression had a piece followed by an expression
370    /// terminator without a piece.
371    InvalidPiece,
372    /// An expression-terminating operation was followed by something
373    /// other than the end of the expression or a piece operation.
374    InvalidExpressionTerminator(u64),
375    /// Division or modulus by zero when evaluating an expression.
376    DivisionByZero,
377    /// An expression operation used mismatching types.
378    TypeMismatch,
379    /// An expression operation required an integral type but saw a
380    /// floating point type.
381    IntegralTypeRequired,
382    /// An expression operation used types that are not supported.
383    UnsupportedTypeOperation,
384    /// The shift value in an expression must be a non-negative integer.
385    InvalidShiftExpression,
386    /// An unknown DW_CFA_* instruction.
387    UnknownCallFrameInstruction(constants::DwCfa),
388    /// The end of an address range was before the beginning.
389    InvalidAddressRange,
390    /// An address calculation overflowed.
391    ///
392    /// This is returned in cases where the address is expected to be
393    /// larger than a previous address, but the calculation overflowed.
394    AddressOverflow,
395    /// Encountered a call frame instruction in a context in which it is not
396    /// valid.
397    CfiInstructionInInvalidContext,
398    /// When evaluating call frame instructions, found a `DW_CFA_restore_state`
399    /// stack pop instruction, but the stack was empty, and had nothing to pop.
400    PopWithEmptyStack,
401    /// Do not have unwind info for the given address.
402    NoUnwindInfoForAddress,
403    /// An offset value was larger than the maximum supported value.
404    UnsupportedOffset,
405    /// The given pointer encoding is either unknown or invalid.
406    UnknownPointerEncoding(constants::DwEhPe),
407    /// Did not find an entry at the given offset.
408    NoEntryAtGivenOffset,
409    /// The given offset is out of bounds.
410    OffsetOutOfBounds,
411    /// Found an unknown CFI augmentation.
412    UnknownAugmentation,
413    /// We do not support the given pointer encoding yet.
414    UnsupportedPointerEncoding,
415    /// Registers larger than `u16` are not supported.
416    UnsupportedRegister(u64),
417    /// The CFI program defined more register rules than we have storage for.
418    TooManyRegisterRules,
419    /// Attempted to push onto the CFI or evaluation stack, but it was already
420    /// at full capacity.
421    StackFull,
422    /// The `.eh_frame_hdr` binary search table claims to be variable-length encoded,
423    /// which makes binary search impossible.
424    VariableLengthSearchTable,
425    /// The `DW_UT_*` value for this unit is not supported yet.
426    UnsupportedUnitType,
427    /// Ranges using AddressIndex are not supported yet.
428    UnsupportedAddressIndex,
429    /// Nonzero segment selector sizes aren't supported yet.
430    UnsupportedSegmentSize,
431    /// A compilation unit or type unit is missing its top level DIE.
432    MissingUnitDie,
433    /// A DIE attribute used an unsupported form.
434    UnsupportedAttributeForm,
435    /// Missing DW_LNCT_path in file entry format.
436    MissingFileEntryFormatPath,
437    /// Expected an attribute value to be a string form.
438    ExpectedStringAttributeValue,
439    /// `DW_FORM_implicit_const` used in an invalid context.
440    InvalidImplicitConst,
441    /// Invalid section count in `.dwp` index.
442    InvalidIndexSectionCount,
443    /// Invalid slot count in `.dwp` index.
444    InvalidIndexSlotCount,
445    /// Invalid hash row in `.dwp` index.
446    InvalidIndexRow,
447    /// Unknown section type in `.dwp` index.
448    UnknownIndexSection(constants::DwSect),
449    /// Unknown section type in version 2 `.dwp` index.
450    UnknownIndexSectionV2(constants::DwSectV2),
451}
452
453impl fmt::Display for Error {
454    #[inline]
455    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> ::core::result::Result<(), fmt::Error> {
456        write!(f, "{}", self.description())
457    }
458}
459
460impl Error {
461    /// A short description of the error.
462    pub fn description(&self) -> &str {
463        match *self {
464            Error::Io => "An I/O error occurred while reading.",
465            Error::PcRelativePointerButSectionBaseIsUndefined => {
466                "Found a PC relative pointer, but the section base is undefined."
467            }
468            Error::TextRelativePointerButTextBaseIsUndefined => {
469                "Found a `.text` relative pointer, but the `.text` base is undefined."
470            }
471            Error::DataRelativePointerButDataBaseIsUndefined => {
472                "Found a data relative pointer, but the data base is undefined."
473            }
474            Error::FuncRelativePointerInBadContext => {
475                "Found a function relative pointer in a context that does not have a function base."
476            }
477            Error::CannotParseOmitPointerEncoding => {
478                "Cannot parse a pointer with a `DW_EH_PE_omit` encoding."
479            }
480            Error::BadUnsignedLeb128 => "An error parsing an unsigned LEB128 value",
481            Error::BadSignedLeb128 => "An error parsing a signed LEB128 value",
482            Error::AbbreviationTagZero => {
483                "An abbreviation declared that its tag is zero,
484                 but zero is reserved for null records"
485            }
486            Error::AttributeFormZero => {
487                "An attribute specification declared that its form is zero,
488                 but zero is reserved for null records"
489            }
490            Error::BadHasChildren => {
491                "The abbreviation's has-children byte was not one of
492                 `DW_CHILDREN_{yes,no}`"
493            }
494            Error::BadLength => "The specified length is impossible",
495            Error::UnknownForm(_) => "Found an unknown `DW_FORM_*` type",
496            Error::ExpectedZero => "Expected a zero, found something else",
497            Error::DuplicateAbbreviationCode => {
498                "Found an abbreviation code that has already been used"
499            }
500            Error::DuplicateArange => "Found a duplicate arange",
501            Error::UnknownReservedLength => "Found an unknown reserved length value",
502            Error::UnknownVersion(_) => "Found an unknown DWARF version",
503            Error::UnknownAbbreviation(_) => "Found a record with an unknown abbreviation code",
504            Error::UnexpectedEof(_) => "Hit the end of input before it was expected",
505            Error::UnexpectedNull => "Read a null entry before it was expected.",
506            Error::UnknownStandardOpcode(_) => "Found an unknown standard opcode",
507            Error::UnknownExtendedOpcode(_) => "Found an unknown extended opcode",
508            Error::UnknownLocListsEntry(_) => "Found an unknown location lists entry",
509            Error::UnknownRangeListsEntry(_) => "Found an unknown range lists entry",
510            Error::UnsupportedAddressSize(_) => "The specified address size is not supported",
511            Error::UnsupportedOffsetSize(_) => "The specified offset size is not supported",
512            Error::UnsupportedFieldSize(_) => "The specified field size is not supported",
513            Error::MinimumInstructionLengthZero => {
514                "The minimum instruction length must not be zero."
515            }
516            Error::MaximumOperationsPerInstructionZero => {
517                "The maximum operations per instruction must not be zero."
518            }
519            Error::LineRangeZero => "The line range must not be zero.",
520            Error::OpcodeBaseZero => "The opcode base must not be zero.",
521            Error::BadUtf8 => "Found an invalid UTF-8 string.",
522            Error::NotCieId => "Expected to find the CIE ID, but found something else.",
523            Error::NotCiePointer => "Expected to find a CIE pointer, but found the CIE ID instead.",
524            Error::NotFdePointer => {
525                "Expected to find an FDE pointer, but found a CIE pointer instead."
526            }
527            Error::BadBranchTarget(_) => "Invalid branch target in DWARF expression",
528            Error::InvalidPushObjectAddress => {
529                "DW_OP_push_object_address used but no object address given"
530            }
531            Error::NotEnoughStackItems => "Not enough items on stack when evaluating expression",
532            Error::TooManyIterations => "Too many iterations to evaluate DWARF expression",
533            Error::InvalidExpression(_) => "Invalid opcode in DWARF expression",
534            Error::UnsupportedEvaluation => "Unsupported operation when evaluating expression",
535            Error::InvalidPiece => {
536                "DWARF expression has piece followed by non-piece expression at end"
537            }
538            Error::InvalidExpressionTerminator(_) => "Expected DW_OP_piece or DW_OP_bit_piece",
539            Error::DivisionByZero => "Division or modulus by zero when evaluating expression",
540            Error::TypeMismatch => "Type mismatch when evaluating expression",
541            Error::IntegralTypeRequired => "Integral type expected when evaluating expression",
542            Error::UnsupportedTypeOperation => {
543                "An expression operation used types that are not supported"
544            }
545            Error::InvalidShiftExpression => {
546                "The shift value in an expression must be a non-negative integer."
547            }
548            Error::UnknownCallFrameInstruction(_) => "An unknown DW_CFA_* instructiion",
549            Error::InvalidAddressRange => {
550                "The end of an address range must not be before the beginning."
551            }
552            Error::AddressOverflow => "An address calculation overflowed.",
553            Error::CfiInstructionInInvalidContext => {
554                "Encountered a call frame instruction in a context in which it is not valid."
555            }
556            Error::PopWithEmptyStack => {
557                "When evaluating call frame instructions, found a `DW_CFA_restore_state` stack pop \
558                 instruction, but the stack was empty, and had nothing to pop."
559            }
560            Error::NoUnwindInfoForAddress => "Do not have unwind info for the given address.",
561            Error::UnsupportedOffset => {
562                "An offset value was larger than the maximum supported value."
563            }
564            Error::UnknownPointerEncoding(_) => {
565                "The given pointer encoding is either unknown or invalid."
566            }
567            Error::NoEntryAtGivenOffset => "Did not find an entry at the given offset.",
568            Error::OffsetOutOfBounds => "The given offset is out of bounds.",
569            Error::UnknownAugmentation => "Found an unknown CFI augmentation.",
570            Error::UnsupportedPointerEncoding => {
571                "We do not support the given pointer encoding yet."
572            }
573            Error::UnsupportedRegister(_) => "Registers larger than `u16` are not supported.",
574            Error::TooManyRegisterRules => {
575                "The CFI program defined more register rules than we have storage for."
576            }
577            Error::StackFull => {
578                "Attempted to push onto the CFI stack, but it was already at full capacity."
579            }
580            Error::VariableLengthSearchTable => {
581                "The `.eh_frame_hdr` binary search table claims to be variable-length encoded, \
582                 which makes binary search impossible."
583            }
584            Error::UnsupportedUnitType => "The `DW_UT_*` value for this unit is not supported yet",
585            Error::UnsupportedAddressIndex => "Ranges involving AddressIndex are not supported yet",
586            Error::UnsupportedSegmentSize => "Nonzero segment size not supported yet",
587            Error::MissingUnitDie => {
588                "A compilation unit or type unit is missing its top level DIE."
589            }
590            Error::UnsupportedAttributeForm => "A DIE attribute used an unsupported form.",
591            Error::MissingFileEntryFormatPath => "Missing DW_LNCT_path in file entry format.",
592            Error::ExpectedStringAttributeValue => {
593                "Expected an attribute value to be a string form."
594            }
595            Error::InvalidImplicitConst => "DW_FORM_implicit_const used in an invalid context.",
596            Error::InvalidIndexSectionCount => "Invalid section count in `.dwp` index.",
597            Error::InvalidIndexSlotCount => "Invalid slot count in `.dwp` index.",
598            Error::InvalidIndexRow => "Invalid hash row in `.dwp` index.",
599            Error::UnknownIndexSection(_) => "Unknown section type in `.dwp` index.",
600            Error::UnknownIndexSectionV2(_) => "Unknown section type in version 2 `.dwp` index.",
601        }
602    }
603}
604
605#[cfg(feature = "std")]
606impl error::Error for Error {}
607
608#[cfg(feature = "std")]
609impl From<io::Error> for Error {
610    fn from(_: io::Error) -> Self {
611        Error::Io
612    }
613}
614
615/// The result of a parse.
616pub type Result<T> = result::Result<T, Error>;
617
618/// A convenience trait for loading DWARF sections from object files.  To be
619/// used like:
620///
621/// ```
622/// use gimli::{DebugInfo, EndianSlice, LittleEndian, Reader, Section};
623///
624/// let buf = [0x00, 0x01, 0x02, 0x03];
625/// let reader = EndianSlice::new(&buf, LittleEndian);
626/// let loader = |name| -> Result<_, ()> { Ok(reader) };
627///
628/// let debug_info: DebugInfo<_> = Section::load(loader).unwrap();
629/// ```
630pub trait Section<R>: From<R> {
631    /// Returns the section id for this type.
632    fn id() -> SectionId;
633
634    /// Returns the ELF section name for this type.
635    fn section_name() -> &'static str {
636        Self::id().name()
637    }
638
639    /// Returns the ELF section name (if any) for this type when used in a dwo
640    /// file.
641    fn dwo_section_name() -> Option<&'static str> {
642        Self::id().dwo_name()
643    }
644
645    /// Returns the XCOFF section name (if any) for this type when used in a XCOFF
646    /// file.
647    fn xcoff_section_name() -> Option<&'static str> {
648        Self::id().xcoff_name()
649    }
650
651    /// Try to load the section using the given loader function.
652    fn load<F, E>(f: F) -> core::result::Result<Self, E>
653    where
654        F: FnOnce(SectionId) -> core::result::Result<R, E>,
655    {
656        f(Self::id()).map(From::from)
657    }
658
659    /// Returns the `Reader` for this section.
660    fn reader(&self) -> &R
661    where
662        R: Reader;
663
664    /// Returns the subrange of the section that is the contribution of
665    /// a unit in a `.dwp` file.
666    fn dwp_range(&self, offset: u32, size: u32) -> Result<Self>
667    where
668        R: Reader,
669    {
670        let mut data = self.reader().clone();
671        data.skip(R::Offset::from_u32(offset))?;
672        data.truncate(R::Offset::from_u32(size))?;
673        Ok(data.into())
674    }
675
676    /// Returns the `Reader` for this section.
677    fn lookup_offset_id(&self, id: ReaderOffsetId) -> Option<(SectionId, R::Offset)>
678    where
679        R: Reader,
680    {
681        self.reader()
682            .lookup_offset_id(id)
683            .map(|offset| (Self::id(), offset))
684    }
685}
686
687impl Register {
688    pub(crate) fn from_u64(x: u64) -> Result<Register> {
689        let y = x as u16;
690        if u64::from(y) == x {
691            Ok(Register(y))
692        } else {
693            Err(Error::UnsupportedRegister(x))
694        }
695    }
696}
697
698#[cfg(test)]
699mod tests {
700    use super::*;
701    use crate::common::Format;
702    use crate::endianity::LittleEndian;
703    use test_assembler::{Endian, Section};
704
705    #[test]
706    fn test_parse_initial_length_32_ok() {
707        let section = Section::with_endian(Endian::Little).L32(0x7856_3412);
708        let buf = section.get_contents().unwrap();
709
710        let input = &mut EndianSlice::new(&buf, LittleEndian);
711        match input.read_initial_length() {
712            Ok((length, format)) => {
713                assert_eq!(input.len(), 0);
714                assert_eq!(format, Format::Dwarf32);
715                assert_eq!(0x7856_3412, length);
716            }
717            otherwise => panic!("Unexpected result: {:?}", otherwise),
718        }
719    }
720
721    #[test]
722    fn test_parse_initial_length_64_ok() {
723        let section = Section::with_endian(Endian::Little)
724            // Dwarf_64_INITIAL_UNIT_LENGTH
725            .L32(0xffff_ffff)
726            // Actual length
727            .L64(0xffde_bc9a_7856_3412);
728        let buf = section.get_contents().unwrap();
729        let input = &mut EndianSlice::new(&buf, LittleEndian);
730
731        #[cfg(target_pointer_width = "64")]
732        match input.read_initial_length() {
733            Ok((length, format)) => {
734                assert_eq!(input.len(), 0);
735                assert_eq!(format, Format::Dwarf64);
736                assert_eq!(0xffde_bc9a_7856_3412, length);
737            }
738            otherwise => panic!("Unexpected result: {:?}", otherwise),
739        }
740
741        #[cfg(target_pointer_width = "32")]
742        match input.read_initial_length() {
743            Err(Error::UnsupportedOffset) => {}
744            otherwise => panic!("Unexpected result: {:?}", otherwise),
745        };
746    }
747
748    #[test]
749    fn test_parse_initial_length_unknown_reserved_value() {
750        let section = Section::with_endian(Endian::Little).L32(0xffff_fffe);
751        let buf = section.get_contents().unwrap();
752
753        let input = &mut EndianSlice::new(&buf, LittleEndian);
754        match input.read_initial_length() {
755            Err(Error::UnknownReservedLength) => {}
756            otherwise => panic!("Unexpected result: {:?}", otherwise),
757        };
758    }
759
760    #[test]
761    fn test_parse_initial_length_incomplete() {
762        let buf = [0xff, 0xff, 0xff]; // Need at least 4 bytes.
763
764        let input = &mut EndianSlice::new(&buf, LittleEndian);
765        match input.read_initial_length() {
766            Err(Error::UnexpectedEof(_)) => {}
767            otherwise => panic!("Unexpected result: {:?}", otherwise),
768        };
769    }
770
771    #[test]
772    fn test_parse_initial_length_64_incomplete() {
773        let section = Section::with_endian(Endian::Little)
774            // Dwarf_64_INITIAL_UNIT_LENGTH
775            .L32(0xffff_ffff)
776            // Actual length is not long enough.
777            .L32(0x7856_3412);
778        let buf = section.get_contents().unwrap();
779
780        let input = &mut EndianSlice::new(&buf, LittleEndian);
781        match input.read_initial_length() {
782            Err(Error::UnexpectedEof(_)) => {}
783            otherwise => panic!("Unexpected result: {:?}", otherwise),
784        };
785    }
786
787    #[test]
788    fn test_parse_offset_32() {
789        let section = Section::with_endian(Endian::Little).L32(0x0123_4567);
790        let buf = section.get_contents().unwrap();
791
792        let input = &mut EndianSlice::new(&buf, LittleEndian);
793        match input.read_offset(Format::Dwarf32) {
794            Ok(val) => {
795                assert_eq!(input.len(), 0);
796                assert_eq!(val, 0x0123_4567);
797            }
798            otherwise => panic!("Unexpected result: {:?}", otherwise),
799        };
800    }
801
802    #[test]
803    fn test_parse_offset_64_small() {
804        let section = Section::with_endian(Endian::Little).L64(0x0123_4567);
805        let buf = section.get_contents().unwrap();
806
807        let input = &mut EndianSlice::new(&buf, LittleEndian);
808        match input.read_offset(Format::Dwarf64) {
809            Ok(val) => {
810                assert_eq!(input.len(), 0);
811                assert_eq!(val, 0x0123_4567);
812            }
813            otherwise => panic!("Unexpected result: {:?}", otherwise),
814        };
815    }
816
817    #[test]
818    #[cfg(target_pointer_width = "64")]
819    fn test_parse_offset_64_large() {
820        let section = Section::with_endian(Endian::Little).L64(0x0123_4567_89ab_cdef);
821        let buf = section.get_contents().unwrap();
822
823        let input = &mut EndianSlice::new(&buf, LittleEndian);
824        match input.read_offset(Format::Dwarf64) {
825            Ok(val) => {
826                assert_eq!(input.len(), 0);
827                assert_eq!(val, 0x0123_4567_89ab_cdef);
828            }
829            otherwise => panic!("Unexpected result: {:?}", otherwise),
830        };
831    }
832
833    #[test]
834    #[cfg(target_pointer_width = "32")]
835    fn test_parse_offset_64_large() {
836        let section = Section::with_endian(Endian::Little).L64(0x0123_4567_89ab_cdef);
837        let buf = section.get_contents().unwrap();
838
839        let input = &mut EndianSlice::new(&buf, LittleEndian);
840        match input.read_offset(Format::Dwarf64) {
841            Err(Error::UnsupportedOffset) => {}
842            otherwise => panic!("Unexpected result: {:?}", otherwise),
843        };
844    }
845}