Files
addr2line
adler
ahash
aho_corasick
ansi_term
anyhow
arc_swap
arrayref
arrayvec
ascii
assert_matches
async_stream
async_stream_impl
async_trait
atty
auto_enums
auto_enums_core
auto_enums_derive
backoff
backtrace
base32
base64
bincode
bip39
bitflags
bitvec
blake3
block_buffer
block_padding
borsh
borsh_derive
borsh_derive_internal
borsh_schema_derive_internal
bs58
bstr
bv
byte_slice_cast
byte_unit
bytecount
byteorder
bytes
bzip2
bzip2_sys
cargo_build_bpf
cargo_metadata
cargo_platform
cargo_test_bpf
cast
cc
cfg_if
chrono
chrono_humanize
clap
colored
combine
console
const_fn
constant_time_eq
core_affinity
cpufeatures
crc32fast
criterion_stats
crossbeam_channel
crossbeam_deque
crossbeam_epoch
crossbeam_queue
crossbeam_utils
crunchy
crypto_mac
csv
csv_core
ctrlc
curve25519_dalek
dashmap
derivative
derive_more
derive_utils
dialoguer
digest
dir_diff
dirs_next
dirs_sys_next
dlopen
dlopen_derive
doc_comment
dtoa
ed25519
ed25519_dalek
either
encoding_rs
enum_iterator
enum_iterator_derive
env_logger
ethabi
ethbloom
ethereum
ethereum_types
evm
evm_bridge
evm_core
evm_gasometer
evm_rpc
evm_runtime
evm_state
evm_utils
failure
failure_derive
fake_simd
fast_math
fd_lock
filetime
fixed_hash
flate2
fnv
foreign_types
foreign_types_shared
form_urlencoded
fs_extra
futures
futures_channel
futures_core
futures_executor
futures_io
futures_macro
futures_sink
futures_task
futures_util
async_await
future
io
lock
sink
stream
task
gag
generic_array
gethostname
getrandom
gimli
globset
goauth
goblin
h2
half
hash256_std_hasher
hash32
hash_db
hashbrown
heck
hex
hidapi
histogram
hmac
hmac_drbg
http
http_body
httparse
httpdate
humantime
hyper
hyper_rustls
hyper_tls
idna
ieee754
impl_codec
impl_rlp
impl_serde
indexed
indexmap
indicatif
inflector
cases
camelcase
case
classcase
kebabcase
pascalcase
screamingsnakecase
sentencecase
snakecase
tablecase
titlecase
traincase
numbers
deordinalize
ordinalize
string
constants
deconstantize
demodulize
pluralize
singularize
suffix
foreignkey
input_buffer
instant
iovec
ipnet
itertools
itoa
jemalloc_ctl
jemalloc_sys
jemallocator
jobserver
jsonrpc_client_transports
jsonrpc_core
jsonrpc_core_client
jsonrpc_derive
jsonrpc_http_server
jsonrpc_pubsub
jsonrpc_server_utils
jsonrpc_ws_server
keccak
keccak_hash
keccak_hasher
kernel32
lazy_static
lazycell
libc
libloading
librocksdb_sys
linked_hash_map
lock_api
log
lru
matches
maybe_uninit
memchr
memmap2
memoffset
mime
mime_guess
miniz_oxide
mio
mio_extras
miow
native_tls
net2
nix
num_cpus
num_derive
num_enum
num_enum_derive
num_integer
num_traits
number_prefix
object
once_cell
opaque_debug
openssl
openssl_probe
openssl_sys
ouroboros
ouroboros_macro
parity_scale_codec
parity_scale_codec_derive
parity_ws
parking_lot
parking_lot_core
paste
paste_impl
paw
paw_attributes
paw_raw
pbkdf2
percent_encoding
pest
pickledb
pin_project
pin_project_lite
pin_utils
plain
ppv_lite86
pretty_hex
primitive_types
proc_macro2
proc_macro_crate
proc_macro_error
proc_macro_error_attr
proc_macro_hack
proc_macro_nested
prost
prost_derive
prost_types
quote
radium
rand
rand_chacha
rand_core
rand_isaac
raptorq
rayon
rayon_core
reed_solomon_erasure
regex
regex_automata
regex_syntax
remove_dir_all
reqwest
retain_mut
ring
ripemd160
rlp
rlp_derive
rocksdb
rpassword
rustc_demangle
rustc_hash
rustc_hex
rustls
rustversion
ryu
same_file
scopeguard
scroll
scroll_derive
sct
secp256k1
secp256k1_sys
semver
semver_parser
serde
serde_bytes
serde_cbor
serde_derive
serde_json
serde_urlencoded
serde_yaml
sha1
sha2
sha3
signal_hook
signal_hook_registry
signature
simpl
simple_logger
slab
smallvec
smpl_jwt
snafu
snafu_derive
socket2
solana_account_decoder
solana_accounts_bench
solana_banking_bench
solana_banks_client
solana_banks_interface
solana_banks_server
solana_bench_exchange
solana_bench_streamer
solana_bench_tps
solana_bench_tps_evm
solana_bpf_loader_program
solana_budget_program
solana_clap_utils
solana_cli
solana_cli_config
solana_cli_output
solana_client
solana_config_program
solana_core
solana_crate_features
solana_csv_to_validator_infos
solana_dos
solana_download_utils
solana_evm_loader_program
solana_exchange_program
solana_failure_program
solana_faucet
solana_frozen_abi
solana_frozen_abi_macro
solana_genesis
solana_ip_address
solana_ip_address_server
solana_ledger
solana_ledger_tool
solana_ledger_udev
solana_local_cluster
solana_log_analyzer
solana_logger
solana_measure
solana_merkle_root_bench
solana_merkle_tree
solana_metrics
solana_net_shaper
solana_net_utils
solana_noop_program
solana_notifier
solana_ownable
solana_perf
solana_poh_bench
solana_program
solana_program_test
solana_ramp_tps
solana_rayon_threadlimit
solana_rbpf
solana_remote_wallet
solana_runtime
solana_sdk
solana_sdk_macro
solana_secp256k1_program
solana_sleep_program
solana_stake_accounts
solana_stake_monitor
solana_stake_o_matic
solana_stake_program
solana_storage_bigtable
solana_storage_proto
solana_store_tool
solana_streamer
solana_sys_tuner
solana_tokens
solana_transaction_status
solana_upload_perf
solana_version
solana_vest_program
solana_vote_program
solana_watchtower
spin
spl_associated_token_account
spl_memo
spl_token
stable_deref_trait
standback
static_assertions
strsim
structopt
structopt_derive
subtle
symlink
syn
synstructure
sysctl
tar
tarpc
tarpc_plugins
tempfile
termcolor
terminal_size
textwrap
thiserror
thiserror_impl
thread_scoped
time
time_macros
time_macros_impl
tiny_keccak
tinyvec
tinyvec_macros
tokio
fs
future
io
loom
macros
net
park
process
runtime
signal
stream
sync
task
time
util
tokio_codec
tokio_executor
tokio_fs
tokio_io
tokio_reactor
tokio_rustls
tokio_serde
tokio_sync
tokio_tcp
tokio_threadpool
tokio_tls
tokio_util
toml
tonic
tower
tower_balance
tower_buffer
tower_discover
tower_layer
tower_limit
tower_load
tower_load_shed
tower_make
tower_ready_cache
tower_retry
tower_service
tower_timeout
tower_util
tracing
tracing_attributes
tracing_core
tracing_futures
trees
triedb
triehash
try_lock
tungstenite
typenum
ucd_trie
uint
unicase
unicode_bidi
unicode_normalization
unicode_segmentation
unicode_width
unicode_xid
unix_socket
unreachable
untrusted
url
users
utf8
utf8_width
vec_map
velas
velas_account_program
velas_faucet
velas_genesis
velas_gossip
velas_install
velas_install_init
velas_keygen
velas_test_validator
velas_validator
void
walkdir
want
webpki
webpki_roots
websocket
websocket_base
winapi
ws2_32
xattr
yaml_rust
zeroize
zeroize_derive
zstd
zstd_safe
zstd_sys
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
//! Read DWARF debugging information.
//!
//! * [Example Usage](#example-usage)
//! * [API Structure](#api-structure)
//! * [Using with `FallibleIterator`](#using-with-fallibleiterator)
//!
//! ## Example Usage
//!
//! Print out all of the functions in the debuggee program:
//!
//! ```rust,no_run
//! # fn example() -> Result<(), gimli::Error> {
//! # type R = gimli::EndianSlice<'static, gimli::LittleEndian>;
//! # let get_file_section_reader = |name| -> Result<R, gimli::Error> { unimplemented!() };
//! # let get_sup_file_section_reader = |name| -> Result<R, gimli::Error> { unimplemented!() };
//! // Read the DWARF sections with whatever object loader you're using.
//! // These closures should return a `Reader` instance (e.g. `EndianSlice`).
//! let loader = |section: gimli::SectionId| { get_file_section_reader(section.name()) };
//! let sup_loader = |section: gimli::SectionId| { get_sup_file_section_reader(section.name()) };
//! let dwarf = gimli::Dwarf::load(loader, sup_loader)?;
//!
//! // Iterate over all compilation units.
//! let mut iter = dwarf.units();
//! while let Some(header) = iter.next()? {
//!     // Parse the abbreviations and other information for this compilation unit.
//!     let unit = dwarf.unit(header)?;
//!
//!     // Iterate over all of this compilation unit's entries.
//!     let mut entries = unit.entries();
//!     while let Some((_, entry)) = entries.next_dfs()? {
//!         // If we find an entry for a function, print it.
//!         if entry.tag() == gimli::DW_TAG_subprogram {
//!             println!("Found a function: {:?}", entry);
//!         }
//!     }
//! }
//! # unreachable!()
//! # }
//! ```
//!
//! Full example programs:
//!
//!   * [A simple parser](https://github.com/gimli-rs/gimli/blob/master/examples/simple.rs)
//!
//!   * [A `dwarfdump`
//!     clone](https://github.com/gimli-rs/gimli/blob/master/examples/dwarfdump.rs)
//!
//!   * [An `addr2line` clone](https://github.com/gimli-rs/addr2line)
//!
//!   * [`ddbug`](https://github.com/philipc/ddbug), a utility giving insight into
//!     code generation by making debugging information readable
//!
//!   * [`dwprod`](https://github.com/fitzgen/dwprod), a tiny utility to list the
//!     compilers used to create each compilation unit within a shared library or
//!     executable (via `DW_AT_producer`)
//!
//!   * [`dwarf-validate`](http://github.com/gimli-rs/gimli/blob/master/examples/dwarf-validate.rs),
//!     a program to validate the integrity of some DWARF and its references
//!     between sections and compilation units.
//!
//! ## API Structure
//!
//! * Basic familiarity with DWARF is assumed.
//!
//! * The [`Dwarf`](./struct.Dwarf.html) type contains the commonly used DWARF
//! sections. It has methods that simplify access to debugging data that spans
//! multiple sections. Use of this type is optional, but recommended.
//!
//! * Each section gets its own type. Consider these types the entry points to
//! the library:
//!
//!   * [`DebugAbbrev`](./struct.DebugAbbrev.html): The `.debug_abbrev` section.
//!
//!   * [`DebugAddr`](./struct.DebugAddr.html): The `.debug_addr` section.
//!
//!   * [`DebugAranges`](./struct.DebugAranges.html): The `.debug_aranges`
//!   section.
//!
//!   * [`DebugFrame`](./struct.DebugFrame.html): The `.debug_frame` section.
//!
//!   * [`DebugInfo`](./struct.DebugInfo.html): The `.debug_info` section.
//!
//!   * [`DebugLine`](./struct.DebugLine.html): The `.debug_line` section.
//!
//!   * [`DebugLineStr`](./struct.DebugLineStr.html): The `.debug_line_str` section.
//!
//!   * [`DebugLoc`](./struct.DebugLoc.html): The `.debug_loc` section.
//!
//!   * [`DebugLocLists`](./struct.DebugLocLists.html): The `.debug_loclists` section.
//!
//!   * [`DebugPubNames`](./struct.DebugPubNames.html): The `.debug_pubnames`
//!   section.
//!
//!   * [`DebugPubTypes`](./struct.DebugPubTypes.html): The `.debug_pubtypes`
//!   section.
//!
//!   * [`DebugRanges`](./struct.DebugRanges.html): The `.debug_ranges` section.
//!
//!   * [`DebugRngLists`](./struct.DebugRngLists.html): The `.debug_rnglists` section.
//!
//!   * [`DebugStr`](./struct.DebugStr.html): The `.debug_str` section.
//!
//!   * [`DebugStrOffsets`](./struct.DebugStrOffsets.html): The `.debug_str_offsets` section.
//!
//!   * [`DebugTypes`](./struct.DebugTypes.html): The `.debug_types` section.
//!
//!   * [`EhFrame`](./struct.EhFrame.html): The `.eh_frame` section.
//!
//!   * [`EhFrameHdr`](./struct.EhFrameHdr.html): The `.eh_frame_hdr` section.
//!
//! * Each section type exposes methods for accessing the debugging data encoded
//! in that section. For example, the [`DebugInfo`](./struct.DebugInfo.html)
//! struct has the [`units`](./struct.DebugInfo.html#method.units) method for
//! iterating over the compilation units defined within it.
//!
//! * Offsets into a section are strongly typed: an offset into `.debug_info` is
//! the [`DebugInfoOffset`](./struct.DebugInfoOffset.html) type. It cannot be
//! used to index into the [`DebugLine`](./struct.DebugLine.html) type because
//! `DebugLine` represents the `.debug_line` section. There are similar types
//! for offsets relative to a compilation unit rather than a section.
//!
//! ## Using with `FallibleIterator`
//!
//! The standard library's `Iterator` trait and related APIs do not play well
//! with iterators where the `next` operation is fallible. One can make the
//! `Iterator`'s associated `Item` type be a `Result<T, E>`, however the
//! provided methods cannot gracefully handle the case when an `Err` is
//! returned.
//!
//! This situation led to the
//! [`fallible-iterator`](https://crates.io/crates/fallible-iterator) crate's
//! existence. You can read more of the rationale for its existence in its
//! docs. The crate provides the helpers you have come to expect (eg `map`,
//! `filter`, etc) for iterators that can fail.
//!
//! `gimli`'s many lazy parsing iterators are a perfect match for the
//! `fallible-iterator` crate's `FallibleIterator` trait because parsing is not
//! done eagerly. Parse errors later in the input might only be discovered after
//! having iterated through many items.
//!
//! To use `gimli` iterators with `FallibleIterator`, import the crate and trait
//! into your code:
//!
//! ```
//! # #[cfg(feature = "fallible-iterator")]
//! # fn foo() {
//! // Use the `FallibleIterator` trait so its methods are in scope!
//! use fallible_iterator::FallibleIterator;
//! use gimli::{DebugAranges, EndianSlice, LittleEndian};
//!
//! fn find_sum_of_address_range_lengths(aranges: DebugAranges<EndianSlice<LittleEndian>>)
//!     -> gimli::Result<u64>
//! {
//!     // `DebugAranges::items` returns a `FallibleIterator`!
//!     aranges.items()
//!         // `map` is provided by `FallibleIterator`!
//!         .map(|arange| Ok(arange.length()))
//!         // `fold` is provided by `FallibleIterator`!
//!         .fold(0, |sum, len| Ok(sum + len))
//! }
//! # }
//! # fn main() {}
//! ```

use core::fmt::{self, Debug};
use core::result;
#[cfg(feature = "std")]
use std::{error, io};

use crate::common::{Register, SectionId};
use crate::constants;

mod addr;
pub use self::addr::*;

mod cfi;
pub use self::cfi::*;

mod dwarf;
pub use self::dwarf::*;

mod endian_slice;
pub use self::endian_slice::*;

#[cfg(feature = "endian-reader")]
mod endian_reader;
#[cfg(feature = "endian-reader")]
pub use self::endian_reader::*;

mod reader;
pub use self::reader::*;

mod abbrev;
pub use self::abbrev::*;

mod aranges;
pub use self::aranges::*;

mod line;
pub use self::line::*;

mod lists;

mod loclists;
pub use self::loclists::*;

mod lookup;

mod op;
pub use self::op::*;

mod pubnames;
pub use self::pubnames::*;

mod pubtypes;
pub use self::pubtypes::*;

mod rnglists;
pub use self::rnglists::*;

mod str;
pub use self::str::*;

mod unit;
pub use self::unit::*;

mod value;
pub use self::value::*;

/// `EndianBuf` has been renamed to `EndianSlice`. For ease of upgrading across
/// `gimli` versions, we export this type alias.
#[deprecated(note = "EndianBuf has been renamed to EndianSlice, use that instead.")]
pub type EndianBuf<'input, Endian> = EndianSlice<'input, Endian>;

/// An error that occurred when parsing.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Error {
    /// An I/O error occurred while reading.
    Io,
    /// Found a PC relative pointer, but the section base is undefined.
    PcRelativePointerButSectionBaseIsUndefined,
    /// Found a `.text` relative pointer, but the `.text` base is undefined.
    TextRelativePointerButTextBaseIsUndefined,
    /// Found a data relative pointer, but the data base is undefined.
    DataRelativePointerButDataBaseIsUndefined,
    /// Found a function relative pointer in a context that does not have a
    /// function base.
    FuncRelativePointerInBadContext,
    /// Cannot parse a pointer with a `DW_EH_PE_omit` encoding.
    CannotParseOmitPointerEncoding,
    /// An error parsing an unsigned LEB128 value.
    BadUnsignedLeb128,
    /// An error parsing a signed LEB128 value.
    BadSignedLeb128,
    /// An abbreviation declared that its tag is zero, but zero is reserved for
    /// null records.
    AbbreviationTagZero,
    /// An attribute specification declared that its form is zero, but zero is
    /// reserved for null records.
    AttributeFormZero,
    /// The abbreviation's has-children byte was not one of
    /// `DW_CHILDREN_{yes,no}`.
    BadHasChildren,
    /// The specified length is impossible.
    BadLength,
    /// Found an unknown `DW_FORM_*` type.
    UnknownForm,
    /// Expected a zero, found something else.
    ExpectedZero,
    /// Found an abbreviation code that has already been used.
    DuplicateAbbreviationCode,
    /// Found a duplicate arange.
    DuplicateArange,
    /// Found an unknown reserved length value.
    UnknownReservedLength,
    /// Found an unknown DWARF version.
    UnknownVersion(u64),
    /// Found a record with an unknown abbreviation code.
    UnknownAbbreviation,
    /// Hit the end of input before it was expected.
    UnexpectedEof(ReaderOffsetId),
    /// Read a null entry before it was expected.
    UnexpectedNull,
    /// Found an unknown standard opcode.
    UnknownStandardOpcode(constants::DwLns),
    /// Found an unknown extended opcode.
    UnknownExtendedOpcode(constants::DwLne),
    /// The specified address size is not supported.
    UnsupportedAddressSize(u8),
    /// The specified offset size is not supported.
    UnsupportedOffsetSize(u8),
    /// The specified field size is not supported.
    UnsupportedFieldSize(u8),
    /// The minimum instruction length must not be zero.
    MinimumInstructionLengthZero,
    /// The maximum operations per instruction must not be zero.
    MaximumOperationsPerInstructionZero,
    /// The line range must not be zero.
    LineRangeZero,
    /// The opcode base must not be zero.
    OpcodeBaseZero,
    /// Found an invalid UTF-8 string.
    BadUtf8,
    /// Expected to find the CIE ID, but found something else.
    NotCieId,
    /// Expected to find a pointer to a CIE, but found the CIE ID instead.
    NotCiePointer,
    /// Expected to find a pointer to an FDE, but found a CIE instead.
    NotFdePointer,
    /// Invalid branch target for a DW_OP_bra or DW_OP_skip.
    BadBranchTarget(u64),
    /// DW_OP_push_object_address used but no address passed in.
    InvalidPushObjectAddress,
    /// Not enough items on the stack when evaluating an expression.
    NotEnoughStackItems,
    /// Too many iterations to compute the expression.
    TooManyIterations,
    /// An unrecognized operation was found while parsing a DWARF
    /// expression.
    InvalidExpression(constants::DwOp),
    /// The expression had a piece followed by an expression
    /// terminator without a piece.
    InvalidPiece,
    /// An expression-terminating operation was followed by something
    /// other than the end of the expression or a piece operation.
    InvalidExpressionTerminator(u64),
    /// Division or modulus by zero when evaluating an expression.
    DivisionByZero,
    /// An expression operation used mismatching types.
    TypeMismatch,
    /// An expression operation required an integral type but saw a
    /// floating point type.
    IntegralTypeRequired,
    /// An expression operation used types that are not supported.
    UnsupportedTypeOperation,
    /// The shift value in an expression must be a non-negative integer.
    InvalidShiftExpression,
    /// An unknown DW_CFA_* instruction.
    UnknownCallFrameInstruction(constants::DwCfa),
    /// The end of an address range was before the beginning.
    InvalidAddressRange,
    /// The end offset of a loc list entry was before the beginning.
    InvalidLocationAddressRange,
    /// Encountered a call frame instruction in a context in which it is not
    /// valid.
    CfiInstructionInInvalidContext,
    /// When evaluating call frame instructions, found a `DW_CFA_restore_state`
    /// stack pop instruction, but the stack was empty, and had nothing to pop.
    PopWithEmptyStack,
    /// Do not have unwind info for the given address.
    NoUnwindInfoForAddress,
    /// An offset value was larger than the maximum supported value.
    UnsupportedOffset,
    /// The given pointer encoding is either unknown or invalid.
    UnknownPointerEncoding,
    /// Did not find an entry at the given offset.
    NoEntryAtGivenOffset,
    /// The given offset is out of bounds.
    OffsetOutOfBounds,
    /// Found an unknown CFI augmentation.
    UnknownAugmentation,
    /// We do not support the given pointer encoding yet.
    UnsupportedPointerEncoding,
    /// Registers larger than `u16` are not supported.
    UnsupportedRegister(u64),
    /// The CFI program defined more register rules than we have storage for.
    TooManyRegisterRules,
    /// Attempted to push onto the CFI stack, but it was already at full
    /// capacity.
    CfiStackFull,
    /// The `.eh_frame_hdr` binary search table claims to be variable-length encoded,
    /// which makes binary search impossible.
    VariableLengthSearchTable,
    /// The `DW_UT_*` value for this unit is not supported yet.
    UnsupportedUnitType,
    /// Ranges using AddressIndex are not supported yet.
    UnsupportedAddressIndex,
    /// Nonzero segment selector sizes aren't supported yet.
    UnsupportedSegmentSize,
    /// A compilation unit or type unit is missing its top level DIE.
    MissingUnitDie,
    /// A DIE attribute used an unsupported form.
    UnsupportedAttributeForm,
    /// Missing DW_LNCT_path in file entry format.
    MissingFileEntryFormatPath,
    /// Expected an attribute value to be a string form.
    ExpectedStringAttributeValue,
    /// `DW_FORM_implicit_const` used in an invalid context.
    InvalidImplicitConst,
}

impl fmt::Display for Error {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter) -> ::core::result::Result<(), fmt::Error> {
        write!(f, "{}", self.description())
    }
}

impl Error {
    /// A short description of the error.
    pub fn description(&self) -> &str {
        match *self {
            Error::Io => "An I/O error occurred while reading.",
            Error::PcRelativePointerButSectionBaseIsUndefined => {
                "Found a PC relative pointer, but the section base is undefined."
            }
            Error::TextRelativePointerButTextBaseIsUndefined => {
                "Found a `.text` relative pointer, but the `.text` base is undefined."
            }
            Error::DataRelativePointerButDataBaseIsUndefined => {
                "Found a data relative pointer, but the data base is undefined."
            }
            Error::FuncRelativePointerInBadContext => {
                "Found a function relative pointer in a context that does not have a function base."
            }
            Error::CannotParseOmitPointerEncoding => {
                "Cannot parse a pointer with a `DW_EH_PE_omit` encoding."
            }
            Error::BadUnsignedLeb128 => "An error parsing an unsigned LEB128 value",
            Error::BadSignedLeb128 => "An error parsing a signed LEB128 value",
            Error::AbbreviationTagZero => {
                "An abbreviation declared that its tag is zero,
                 but zero is reserved for null records"
            }
            Error::AttributeFormZero => {
                "An attribute specification declared that its form is zero,
                 but zero is reserved for null records"
            }
            Error::BadHasChildren => {
                "The abbreviation's has-children byte was not one of
                 `DW_CHILDREN_{yes,no}`"
            }
            Error::BadLength => "The specified length is impossible",
            Error::UnknownForm => "Found an unknown `DW_FORM_*` type",
            Error::ExpectedZero => "Expected a zero, found something else",
            Error::DuplicateAbbreviationCode => {
                "Found an abbreviation code that has already been used"
            }
            Error::DuplicateArange => "Found a duplicate arange",
            Error::UnknownReservedLength => "Found an unknown reserved length value",
            Error::UnknownVersion(_) => "Found an unknown DWARF version",
            Error::UnknownAbbreviation => "Found a record with an unknown abbreviation code",
            Error::UnexpectedEof(_) => "Hit the end of input before it was expected",
            Error::UnexpectedNull => "Read a null entry before it was expected.",
            Error::UnknownStandardOpcode(_) => "Found an unknown standard opcode",
            Error::UnknownExtendedOpcode(_) => "Found an unknown extended opcode",
            Error::UnsupportedAddressSize(_) => "The specified address size is not supported",
            Error::UnsupportedOffsetSize(_) => "The specified offset size is not supported",
            Error::UnsupportedFieldSize(_) => "The specified field size is not supported",
            Error::MinimumInstructionLengthZero => {
                "The minimum instruction length must not be zero."
            }
            Error::MaximumOperationsPerInstructionZero => {
                "The maximum operations per instruction must not be zero."
            }
            Error::LineRangeZero => "The line range must not be zero.",
            Error::OpcodeBaseZero => "The opcode base must not be zero.",
            Error::BadUtf8 => "Found an invalid UTF-8 string.",
            Error::NotCieId => "Expected to find the CIE ID, but found something else.",
            Error::NotCiePointer => "Expected to find a CIE pointer, but found the CIE ID instead.",
            Error::NotFdePointer => {
                "Expected to find an FDE pointer, but found a CIE pointer instead."
            }
            Error::BadBranchTarget(_) => "Invalid branch target in DWARF expression",
            Error::InvalidPushObjectAddress => {
                "DW_OP_push_object_address used but no object address given"
            }
            Error::NotEnoughStackItems => "Not enough items on stack when evaluating expression",
            Error::TooManyIterations => "Too many iterations to evaluate DWARF expression",
            Error::InvalidExpression(_) => "Invalid opcode in DWARF expression",
            Error::InvalidPiece => {
                "DWARF expression has piece followed by non-piece expression at end"
            }
            Error::InvalidExpressionTerminator(_) => "Expected DW_OP_piece or DW_OP_bit_piece",
            Error::DivisionByZero => "Division or modulus by zero when evaluating expression",
            Error::TypeMismatch => "Type mismatch when evaluating expression",
            Error::IntegralTypeRequired => "Integral type expected when evaluating expression",
            Error::UnsupportedTypeOperation => {
                "An expression operation used types that are not supported"
            }
            Error::InvalidShiftExpression => {
                "The shift value in an expression must be a non-negative integer."
            }
            Error::UnknownCallFrameInstruction(_) => "An unknown DW_CFA_* instructiion",
            Error::InvalidAddressRange => {
                "The end of an address range must not be before the beginning."
            }
            Error::InvalidLocationAddressRange => {
                "The end offset of a location list entry must not be before the beginning."
            }
            Error::CfiInstructionInInvalidContext => {
                "Encountered a call frame instruction in a context in which it is not valid."
            }
            Error::PopWithEmptyStack => {
                "When evaluating call frame instructions, found a `DW_CFA_restore_state` stack pop \
                 instruction, but the stack was empty, and had nothing to pop."
            }
            Error::NoUnwindInfoForAddress => "Do not have unwind info for the given address.",
            Error::UnsupportedOffset => {
                "An offset value was larger than the maximum supported value."
            }
            Error::UnknownPointerEncoding => {
                "The given pointer encoding is either unknown or invalid."
            }
            Error::NoEntryAtGivenOffset => "Did not find an entry at the given offset.",
            Error::OffsetOutOfBounds => "The given offset is out of bounds.",
            Error::UnknownAugmentation => "Found an unknown CFI augmentation.",
            Error::UnsupportedPointerEncoding => {
                "We do not support the given pointer encoding yet."
            }
            Error::UnsupportedRegister(_) => "Registers larger than `u16` are not supported.",
            Error::TooManyRegisterRules => {
                "The CFI program defined more register rules than we have storage for."
            }
            Error::CfiStackFull => {
                "Attempted to push onto the CFI stack, but it was already at full capacity."
            }
            Error::VariableLengthSearchTable => {
                "The `.eh_frame_hdr` binary search table claims to be variable-length encoded, \
                 which makes binary search impossible."
            }
            Error::UnsupportedUnitType => "The `DW_UT_*` value for this unit is not supported yet",
            Error::UnsupportedAddressIndex => "Ranges involving AddressIndex are not supported yet",
            Error::UnsupportedSegmentSize => "Nonzero segment size not supported yet",
            Error::MissingUnitDie => {
                "A compilation unit or type unit is missing its top level DIE."
            }
            Error::UnsupportedAttributeForm => "A DIE attribute used an unsupported form.",
            Error::MissingFileEntryFormatPath => "Missing DW_LNCT_path in file entry format.",
            Error::ExpectedStringAttributeValue => {
                "Expected an attribute value to be a string form."
            }
            Error::InvalidImplicitConst => "DW_FORM_implicit_const used in an invalid context.",
        }
    }
}

#[cfg(feature = "std")]
impl error::Error for Error {}

#[cfg(feature = "std")]
impl From<io::Error> for Error {
    fn from(_: io::Error) -> Self {
        Error::Io
    }
}

/// The result of a parse.
pub type Result<T> = result::Result<T, Error>;

/// A convenience trait for loading DWARF sections from object files.  To be
/// used like:
///
/// ```
/// use gimli::{DebugInfo, EndianSlice, LittleEndian, Reader, Section};
///
/// let buf = [0x00, 0x01, 0x02, 0x03];
/// let reader = EndianSlice::new(&buf, LittleEndian);
/// let loader = |name| -> Result<_, ()> { Ok(reader) };
///
/// let debug_info: DebugInfo<_> = Section::load(loader).unwrap();
/// ```
pub trait Section<R>: From<R> {
    /// Returns the section id for this type.
    fn id() -> SectionId;

    /// Returns the ELF section name for this type.
    fn section_name() -> &'static str {
        Self::id().name()
    }

    /// Returns the ELF section name (if any) for this type when used in a dwo
    /// file.
    fn dwo_section_name() -> Option<&'static str> {
        Self::id().dwo_name()
    }

    /// Try to load the section using the given loader function.
    fn load<F, E>(f: F) -> core::result::Result<Self, E>
    where
        F: FnOnce(SectionId) -> core::result::Result<R, E>,
    {
        f(Self::id()).map(From::from)
    }

    /// Returns the `Reader` for this section.
    fn reader(&self) -> &R
    where
        R: Reader;

    /// Returns the `Reader` for this section.
    fn lookup_offset_id(&self, id: ReaderOffsetId) -> Option<(SectionId, R::Offset)>
    where
        R: Reader,
    {
        self.reader()
            .lookup_offset_id(id)
            .map(|offset| (Self::id(), offset))
    }
}

impl Register {
    pub(crate) fn from_u64(x: u64) -> Result<Register> {
        let y = x as u16;
        if u64::from(y) == x {
            Ok(Register(y))
        } else {
            Err(Error::UnsupportedRegister(x))
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::common::Format;
    use crate::endianity::LittleEndian;
    use test_assembler::{Endian, Section};

    #[test]
    fn test_parse_initial_length_32_ok() {
        let section = Section::with_endian(Endian::Little).L32(0x7856_3412);
        let buf = section.get_contents().unwrap();

        let input = &mut EndianSlice::new(&buf, LittleEndian);
        match input.read_initial_length() {
            Ok((length, format)) => {
                assert_eq!(input.len(), 0);
                assert_eq!(format, Format::Dwarf32);
                assert_eq!(0x7856_3412, length);
            }
            otherwise => panic!("Unexpected result: {:?}", otherwise),
        }
    }

    #[test]
    fn test_parse_initial_length_64_ok() {
        let section = Section::with_endian(Endian::Little)
            // Dwarf_64_INITIAL_UNIT_LENGTH
            .L32(0xffff_ffff)
            // Actual length
            .L64(0xffde_bc9a_7856_3412);
        let buf = section.get_contents().unwrap();
        let input = &mut EndianSlice::new(&buf, LittleEndian);

        #[cfg(target_pointer_width = "64")]
        match input.read_initial_length() {
            Ok((length, format)) => {
                assert_eq!(input.len(), 0);
                assert_eq!(format, Format::Dwarf64);
                assert_eq!(0xffde_bc9a_7856_3412, length);
            }
            otherwise => panic!("Unexpected result: {:?}", otherwise),
        }

        #[cfg(target_pointer_width = "32")]
        match input.read_initial_length() {
            Err(Error::UnsupportedOffset) => {}
            otherwise => panic!("Unexpected result: {:?}", otherwise),
        };
    }

    #[test]
    fn test_parse_initial_length_unknown_reserved_value() {
        let section = Section::with_endian(Endian::Little).L32(0xffff_fffe);
        let buf = section.get_contents().unwrap();

        let input = &mut EndianSlice::new(&buf, LittleEndian);
        match input.read_initial_length() {
            Err(Error::UnknownReservedLength) => assert!(true),
            otherwise => panic!("Unexpected result: {:?}", otherwise),
        };
    }

    #[test]
    fn test_parse_initial_length_incomplete() {
        let buf = [0xff, 0xff, 0xff]; // Need at least 4 bytes.

        let input = &mut EndianSlice::new(&buf, LittleEndian);
        match input.read_initial_length() {
            Err(Error::UnexpectedEof(_)) => assert!(true),
            otherwise => panic!("Unexpected result: {:?}", otherwise),
        };
    }

    #[test]
    fn test_parse_initial_length_64_incomplete() {
        let section = Section::with_endian(Endian::Little)
            // Dwarf_64_INITIAL_UNIT_LENGTH
            .L32(0xffff_ffff)
            // Actual length is not long enough.
            .L32(0x7856_3412);
        let buf = section.get_contents().unwrap();

        let input = &mut EndianSlice::new(&buf, LittleEndian);
        match input.read_initial_length() {
            Err(Error::UnexpectedEof(_)) => assert!(true),
            otherwise => panic!("Unexpected result: {:?}", otherwise),
        };
    }

    #[test]
    fn test_parse_offset_32() {
        let section = Section::with_endian(Endian::Little).L32(0x0123_4567);
        let buf = section.get_contents().unwrap();

        let input = &mut EndianSlice::new(&buf, LittleEndian);
        match input.read_offset(Format::Dwarf32) {
            Ok(val) => {
                assert_eq!(input.len(), 0);
                assert_eq!(val, 0x0123_4567);
            }
            otherwise => panic!("Unexpected result: {:?}", otherwise),
        };
    }

    #[test]
    fn test_parse_offset_64_small() {
        let section = Section::with_endian(Endian::Little).L64(0x0123_4567);
        let buf = section.get_contents().unwrap();

        let input = &mut EndianSlice::new(&buf, LittleEndian);
        match input.read_offset(Format::Dwarf64) {
            Ok(val) => {
                assert_eq!(input.len(), 0);
                assert_eq!(val, 0x0123_4567);
            }
            otherwise => panic!("Unexpected result: {:?}", otherwise),
        };
    }

    #[test]
    #[cfg(target_pointer_width = "64")]
    fn test_parse_offset_64_large() {
        let section = Section::with_endian(Endian::Little).L64(0x0123_4567_89ab_cdef);
        let buf = section.get_contents().unwrap();

        let input = &mut EndianSlice::new(&buf, LittleEndian);
        match input.read_offset(Format::Dwarf64) {
            Ok(val) => {
                assert_eq!(input.len(), 0);
                assert_eq!(val, 0x0123_4567_89ab_cdef);
            }
            otherwise => panic!("Unexpected result: {:?}", otherwise),
        };
    }

    #[test]
    #[cfg(target_pointer_width = "32")]
    fn test_parse_offset_64_large() {
        let section = Section::with_endian(Endian::Little).L64(0x0123_4567_89ab_cdef);
        let buf = section.get_contents().unwrap();

        let input = &mut EndianSlice::new(&buf, LittleEndian);
        match input.read_offset(Format::Dwarf64) {
            Err(Error::UnsupportedOffset) => assert!(true),
            otherwise => panic!("Unexpected result: {:?}", otherwise),
        };
    }
}