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