-
Notifications
You must be signed in to change notification settings - Fork 108
/
Copy pathcfi.rs
7712 lines (6911 loc) · 264 KB
/
cfi.rs
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
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#[cfg(feature = "read")]
use alloc::vec::Vec;
use core::cmp::{Ord, Ordering};
use core::fmt::{self, Debug};
use core::iter::FromIterator;
use core::mem;
use core::num::Wrapping;
use super::util::{ArrayLike, ArrayVec};
use crate::common::{
DebugFrameOffset, EhFrameOffset, Encoding, Format, Register, SectionId, Vendor,
};
use crate::constants::{self, DwEhPe};
use crate::endianity::Endianity;
use crate::read::{
EndianSlice, Error, Expression, Reader, ReaderOffset, Result, Section, StoreOnHeap,
};
/// `DebugFrame` contains the `.debug_frame` section's frame unwinding
/// information required to unwind to and recover registers from older frames on
/// the stack. For example, this is useful for a debugger that wants to print
/// locals in a backtrace.
///
/// Most interesting methods are defined in the
/// [`UnwindSection`](trait.UnwindSection.html) trait.
///
/// ### Differences between `.debug_frame` and `.eh_frame`
///
/// While the `.debug_frame` section's information has a lot of overlap with the
/// `.eh_frame` section's information, the `.eh_frame` information tends to only
/// encode the subset of information needed for exception handling. Often, only
/// one of `.eh_frame` or `.debug_frame` will be present in an object file.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct DebugFrame<R: Reader> {
section: R,
address_size: u8,
segment_size: u8,
vendor: Vendor,
}
impl<R: Reader> DebugFrame<R> {
/// Set the size of a target address in bytes.
///
/// This defaults to the native word size.
/// This is only used if the CIE version is less than 4.
pub fn set_address_size(&mut self, address_size: u8) {
self.address_size = address_size
}
/// Set the size of a segment selector in bytes.
///
/// This defaults to 0.
/// This is only used if the CIE version is less than 4.
pub fn set_segment_size(&mut self, segment_size: u8) {
self.segment_size = segment_size
}
/// Set the vendor extensions to use.
///
/// This defaults to `Vendor::Default`.
pub fn set_vendor(&mut self, vendor: Vendor) {
self.vendor = vendor;
}
}
impl<'input, Endian> DebugFrame<EndianSlice<'input, Endian>>
where
Endian: Endianity,
{
/// Construct a new `DebugFrame` instance from the data in the
/// `.debug_frame` section.
///
/// It is the caller's responsibility to read the section and present it as
/// a `&[u8]` slice. That means using some ELF loader on Linux, a Mach-O
/// loader on macOS, etc.
///
/// ```
/// use gimli::{DebugFrame, NativeEndian};
///
/// // Use with `.debug_frame`
/// # let buf = [0x00, 0x01, 0x02, 0x03];
/// # let read_debug_frame_section_somehow = || &buf;
/// let debug_frame = DebugFrame::new(read_debug_frame_section_somehow(), NativeEndian);
/// ```
pub fn new(section: &'input [u8], endian: Endian) -> Self {
Self::from(EndianSlice::new(section, endian))
}
}
impl<R: Reader> Section<R> for DebugFrame<R> {
fn id() -> SectionId {
SectionId::DebugFrame
}
fn reader(&self) -> &R {
&self.section
}
}
impl<R: Reader> From<R> for DebugFrame<R> {
fn from(section: R) -> Self {
// Default to no segments and native word size.
DebugFrame {
section,
address_size: mem::size_of::<usize>() as u8,
segment_size: 0,
vendor: Vendor::Default,
}
}
}
/// `EhFrameHdr` contains the information about the `.eh_frame_hdr` section.
///
/// A pointer to the start of the `.eh_frame` data, and optionally, a binary
/// search table of pointers to the `.eh_frame` records that are found in this section.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct EhFrameHdr<R: Reader>(R);
/// `ParsedEhFrameHdr` contains the parsed information from the `.eh_frame_hdr` section.
#[derive(Clone, Debug)]
pub struct ParsedEhFrameHdr<R: Reader> {
address_size: u8,
section: R,
eh_frame_ptr: Pointer,
fde_count: u64,
table_enc: DwEhPe,
table: R,
}
impl<'input, Endian> EhFrameHdr<EndianSlice<'input, Endian>>
where
Endian: Endianity,
{
/// Constructs a new `EhFrameHdr` instance from the data in the `.eh_frame_hdr` section.
pub fn new(section: &'input [u8], endian: Endian) -> Self {
Self::from(EndianSlice::new(section, endian))
}
}
impl<R: Reader> EhFrameHdr<R> {
/// Parses this `EhFrameHdr` to a `ParsedEhFrameHdr`.
pub fn parse(&self, bases: &BaseAddresses, address_size: u8) -> Result<ParsedEhFrameHdr<R>> {
let mut reader = self.0.clone();
let version = reader.read_u8()?;
if version != 1 {
return Err(Error::UnknownVersion(u64::from(version)));
}
let eh_frame_ptr_enc = parse_pointer_encoding(&mut reader)?;
let fde_count_enc = parse_pointer_encoding(&mut reader)?;
let table_enc = parse_pointer_encoding(&mut reader)?;
let parameters = PointerEncodingParameters {
bases: &bases.eh_frame_hdr,
func_base: None,
address_size,
section: &self.0,
};
// Omitting this pointer is not valid (defeats the purpose of .eh_frame_hdr entirely)
if eh_frame_ptr_enc == constants::DW_EH_PE_omit {
return Err(Error::CannotParseOmitPointerEncoding);
}
let eh_frame_ptr = parse_encoded_pointer(eh_frame_ptr_enc, ¶meters, &mut reader)?;
let fde_count;
if fde_count_enc == constants::DW_EH_PE_omit || table_enc == constants::DW_EH_PE_omit {
fde_count = 0
} else {
fde_count = parse_encoded_pointer(fde_count_enc, ¶meters, &mut reader)?.direct()?;
}
Ok(ParsedEhFrameHdr {
address_size,
section: self.0.clone(),
eh_frame_ptr,
fde_count,
table_enc,
table: reader,
})
}
}
impl<R: Reader> Section<R> for EhFrameHdr<R> {
fn id() -> SectionId {
SectionId::EhFrameHdr
}
fn reader(&self) -> &R {
&self.0
}
}
impl<R: Reader> From<R> for EhFrameHdr<R> {
fn from(section: R) -> Self {
EhFrameHdr(section)
}
}
impl<R: Reader> ParsedEhFrameHdr<R> {
/// Returns the address of the binary's `.eh_frame` section.
pub fn eh_frame_ptr(&self) -> Pointer {
self.eh_frame_ptr
}
/// Retrieves the CFI binary search table, if there is one.
pub fn table(&self) -> Option<EhHdrTable<R>> {
// There are two big edge cases here:
// * You search the table for an invalid address. As this is just a binary
// search table, we always have to return a valid result for that (unless
// you specify an address that is lower than the first address in the
// table). Since this means that you have to recheck that the FDE contains
// your address anyways, we just return the first FDE even when the address
// is too low. After all, we're just doing a normal binary search.
// * This falls apart when the table is empty - there is no entry we could
// return. We conclude that an empty table is not really a table at all.
if self.fde_count == 0 {
None
} else {
Some(EhHdrTable { hdr: self })
}
}
}
/// An iterator for `.eh_frame_hdr` section's binary search table.
///
/// Each table entry consists of a tuple containing an `initial_location` and `address`.
/// The `initial location` represents the first address that the targeted FDE
/// is able to decode. The `address` is the address of the FDE in the `.eh_frame` section.
/// The `address` can be converted with `EhHdrTable::pointer_to_offset` and `EhFrame::fde_from_offset` to an FDE.
#[derive(Debug)]
pub struct EhHdrTableIter<'a, 'bases, R: Reader> {
hdr: &'a ParsedEhFrameHdr<R>,
table: R,
bases: &'bases BaseAddresses,
remain: u64,
}
impl<'a, 'bases, R: Reader> EhHdrTableIter<'a, 'bases, R> {
/// Yield the next entry in the `EhHdrTableIter`.
pub fn next(&mut self) -> Result<Option<(Pointer, Pointer)>> {
if self.remain == 0 {
return Ok(None);
}
let parameters = PointerEncodingParameters {
bases: &self.bases.eh_frame_hdr,
func_base: None,
address_size: self.hdr.address_size,
section: &self.hdr.section,
};
self.remain -= 1;
let from = parse_encoded_pointer(self.hdr.table_enc, ¶meters, &mut self.table)?;
let to = parse_encoded_pointer(self.hdr.table_enc, ¶meters, &mut self.table)?;
Ok(Some((from, to)))
}
/// Yield the nth entry in the `EhHdrTableIter`
pub fn nth(&mut self, n: usize) -> Result<Option<(Pointer, Pointer)>> {
use core::convert::TryFrom;
let size = match self.hdr.table_enc.format() {
constants::DW_EH_PE_uleb128 | constants::DW_EH_PE_sleb128 => {
return Err(Error::VariableLengthSearchTable);
}
constants::DW_EH_PE_sdata2 | constants::DW_EH_PE_udata2 => 2,
constants::DW_EH_PE_sdata4 | constants::DW_EH_PE_udata4 => 4,
constants::DW_EH_PE_sdata8 | constants::DW_EH_PE_udata8 => 8,
_ => return Err(Error::UnknownPointerEncoding),
};
let row_size = size * 2;
let n = u64::try_from(n).map_err(|_| Error::UnsupportedOffset)?;
self.remain = self.remain.saturating_sub(n);
self.table.skip(R::Offset::from_u64(n * row_size)?)?;
self.next()
}
}
#[cfg(feature = "fallible-iterator")]
impl<'a, 'bases, R: Reader> fallible_iterator::FallibleIterator for EhHdrTableIter<'a, 'bases, R> {
type Item = (Pointer, Pointer);
type Error = Error;
fn next(&mut self) -> Result<Option<Self::Item>> {
EhHdrTableIter::next(self)
}
fn size_hint(&self) -> (usize, Option<usize>) {
use core::convert::TryInto;
(
self.remain.try_into().unwrap_or(0),
self.remain.try_into().ok(),
)
}
fn nth(&mut self, n: usize) -> Result<Option<Self::Item>> {
EhHdrTableIter::nth(self, n)
}
}
/// The CFI binary search table that is an optional part of the `.eh_frame_hdr` section.
#[derive(Debug, Clone)]
pub struct EhHdrTable<'a, R: Reader> {
hdr: &'a ParsedEhFrameHdr<R>,
}
impl<'a, R: Reader + 'a> EhHdrTable<'a, R> {
/// Return an iterator that can walk the `.eh_frame_hdr` table.
///
/// Each table entry consists of a tuple containing an `initial_location` and `address`.
/// The `initial location` represents the first address that the targeted FDE
/// is able to decode. The `address` is the address of the FDE in the `.eh_frame` section.
/// The `address` can be converted with `EhHdrTable::pointer_to_offset` and `EhFrame::fde_from_offset` to an FDE.
pub fn iter<'bases>(&self, bases: &'bases BaseAddresses) -> EhHdrTableIter<'_, 'bases, R> {
EhHdrTableIter {
hdr: self.hdr,
bases,
remain: self.hdr.fde_count,
table: self.hdr.table.clone(),
}
}
/// *Probably* returns a pointer to the FDE for the given address.
///
/// This performs a binary search, so if there is no FDE for the given address,
/// this function **will** return a pointer to any other FDE that's close by.
///
/// To be sure, you **must** call `contains` on the FDE.
pub fn lookup(&self, address: u64, bases: &BaseAddresses) -> Result<Pointer> {
let size = match self.hdr.table_enc.format() {
constants::DW_EH_PE_uleb128 | constants::DW_EH_PE_sleb128 => {
return Err(Error::VariableLengthSearchTable);
}
constants::DW_EH_PE_sdata2 | constants::DW_EH_PE_udata2 => 2,
constants::DW_EH_PE_sdata4 | constants::DW_EH_PE_udata4 => 4,
constants::DW_EH_PE_sdata8 | constants::DW_EH_PE_udata8 => 8,
_ => return Err(Error::UnknownPointerEncoding),
};
let row_size = size * 2;
let mut len = self.hdr.fde_count;
let mut reader = self.hdr.table.clone();
let parameters = PointerEncodingParameters {
bases: &bases.eh_frame_hdr,
func_base: None,
address_size: self.hdr.address_size,
section: &self.hdr.section,
};
while len > 1 {
let head = reader.split(R::Offset::from_u64((len / 2) * row_size)?)?;
let tail = reader.clone();
let pivot =
parse_encoded_pointer(self.hdr.table_enc, ¶meters, &mut reader)?.direct()?;
match pivot.cmp(&address) {
Ordering::Equal => {
reader = tail;
break;
}
Ordering::Less => {
reader = tail;
len = len - (len / 2);
}
Ordering::Greater => {
reader = head;
len /= 2;
}
}
}
reader.skip(R::Offset::from_u64(size)?)?;
parse_encoded_pointer(self.hdr.table_enc, ¶meters, &mut reader)
}
/// Convert a `Pointer` to a section offset.
///
/// This does not support indirect pointers.
pub fn pointer_to_offset(&self, ptr: Pointer) -> Result<EhFrameOffset<R::Offset>> {
let ptr = ptr.direct()?;
let eh_frame_ptr = self.hdr.eh_frame_ptr().direct()?;
// Calculate the offset in the EhFrame section
R::Offset::from_u64(ptr - eh_frame_ptr).map(EhFrameOffset)
}
/// Returns a parsed FDE for the given address, or `NoUnwindInfoForAddress`
/// if there are none.
///
/// You must provide a function to get its associated CIE. See
/// `PartialFrameDescriptionEntry::parse` for more information.
///
/// # Example
///
/// ```
/// # use gimli::{BaseAddresses, EhFrame, ParsedEhFrameHdr, EndianSlice, NativeEndian, Error, UnwindSection};
/// # fn foo() -> Result<(), Error> {
/// # let eh_frame: EhFrame<EndianSlice<NativeEndian>> = unreachable!();
/// # let eh_frame_hdr: ParsedEhFrameHdr<EndianSlice<NativeEndian>> = unimplemented!();
/// # let addr = 0;
/// # let bases = unimplemented!();
/// let table = eh_frame_hdr.table().unwrap();
/// let fde = table.fde_for_address(&eh_frame, &bases, addr, EhFrame::cie_from_offset)?;
/// # Ok(())
/// # }
/// ```
pub fn fde_for_address<F>(
&self,
frame: &EhFrame<R>,
bases: &BaseAddresses,
address: u64,
get_cie: F,
) -> Result<FrameDescriptionEntry<R>>
where
F: FnMut(
&EhFrame<R>,
&BaseAddresses,
EhFrameOffset<R::Offset>,
) -> Result<CommonInformationEntry<R>>,
{
let fdeptr = self.lookup(address, bases)?;
let offset = self.pointer_to_offset(fdeptr)?;
let entry = frame.fde_from_offset(bases, offset, get_cie)?;
if entry.contains(address) {
Ok(entry)
} else {
Err(Error::NoUnwindInfoForAddress)
}
}
#[inline]
#[doc(hidden)]
#[deprecated(note = "Method renamed to fde_for_address; use that instead.")]
pub fn lookup_and_parse<F>(
&self,
address: u64,
bases: &BaseAddresses,
frame: EhFrame<R>,
get_cie: F,
) -> Result<FrameDescriptionEntry<R>>
where
F: FnMut(
&EhFrame<R>,
&BaseAddresses,
EhFrameOffset<R::Offset>,
) -> Result<CommonInformationEntry<R>>,
{
self.fde_for_address(&frame, bases, address, get_cie)
}
/// Returns the frame unwind information for the given address,
/// or `NoUnwindInfoForAddress` if there are none.
///
/// You must provide a function to get the associated CIE. See
/// `PartialFrameDescriptionEntry::parse` for more information.
pub fn unwind_info_for_address<'ctx, F, A: UnwindContextStorage<R>>(
&self,
frame: &EhFrame<R>,
bases: &BaseAddresses,
ctx: &'ctx mut UnwindContext<R, A>,
address: u64,
get_cie: F,
) -> Result<&'ctx UnwindTableRow<R, A>>
where
F: FnMut(
&EhFrame<R>,
&BaseAddresses,
EhFrameOffset<R::Offset>,
) -> Result<CommonInformationEntry<R>>,
{
let fde = self.fde_for_address(frame, bases, address, get_cie)?;
fde.unwind_info_for_address(frame, bases, ctx, address)
}
}
/// `EhFrame` contains the frame unwinding information needed during exception
/// handling found in the `.eh_frame` section.
///
/// Most interesting methods are defined in the
/// [`UnwindSection`](trait.UnwindSection.html) trait.
///
/// See
/// [`DebugFrame`](./struct.DebugFrame.html#differences-between-debug_frame-and-eh_frame)
/// for some discussion on the differences between `.debug_frame` and
/// `.eh_frame`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct EhFrame<R: Reader> {
section: R,
address_size: u8,
vendor: Vendor,
}
impl<R: Reader> EhFrame<R> {
/// Set the size of a target address in bytes.
///
/// This defaults to the native word size.
pub fn set_address_size(&mut self, address_size: u8) {
self.address_size = address_size
}
/// Set the vendor extensions to use.
///
/// This defaults to `Vendor::Default`.
pub fn set_vendor(&mut self, vendor: Vendor) {
self.vendor = vendor;
}
}
impl<'input, Endian> EhFrame<EndianSlice<'input, Endian>>
where
Endian: Endianity,
{
/// Construct a new `EhFrame` instance from the data in the
/// `.eh_frame` section.
///
/// It is the caller's responsibility to read the section and present it as
/// a `&[u8]` slice. That means using some ELF loader on Linux, a Mach-O
/// loader on macOS, etc.
///
/// ```
/// use gimli::{EhFrame, EndianSlice, NativeEndian};
///
/// // Use with `.eh_frame`
/// # let buf = [0x00, 0x01, 0x02, 0x03];
/// # let read_eh_frame_section_somehow = || &buf;
/// let eh_frame = EhFrame::new(read_eh_frame_section_somehow(), NativeEndian);
/// ```
pub fn new(section: &'input [u8], endian: Endian) -> Self {
Self::from(EndianSlice::new(section, endian))
}
}
impl<R: Reader> Section<R> for EhFrame<R> {
fn id() -> SectionId {
SectionId::EhFrame
}
fn reader(&self) -> &R {
&self.section
}
}
impl<R: Reader> From<R> for EhFrame<R> {
fn from(section: R) -> Self {
// Default to native word size.
EhFrame {
section,
address_size: mem::size_of::<usize>() as u8,
vendor: Vendor::Default,
}
}
}
// This has to be `pub` to silence a warning (that is deny(..)'d by default) in
// rustc. Eventually, not having this `pub` will become a hard error.
#[doc(hidden)]
#[allow(missing_docs)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CieOffsetEncoding {
U32,
U64,
}
/// An offset into an `UnwindSection`.
//
// Needed to avoid conflicting implementations of `Into<T>`.
pub trait UnwindOffset<T = usize>: Copy + Debug + Eq + From<T>
where
T: ReaderOffset,
{
/// Convert an `UnwindOffset<T>` into a `T`.
fn into(self) -> T;
}
impl<T> UnwindOffset<T> for DebugFrameOffset<T>
where
T: ReaderOffset,
{
#[inline]
fn into(self) -> T {
self.0
}
}
impl<T> UnwindOffset<T> for EhFrameOffset<T>
where
T: ReaderOffset,
{
#[inline]
fn into(self) -> T {
self.0
}
}
/// This trait completely encapsulates everything that is different between
/// `.eh_frame` and `.debug_frame`, as well as all the bits that can change
/// between DWARF versions.
#[doc(hidden)]
pub trait _UnwindSectionPrivate<R: Reader> {
/// Get the underlying section data.
fn section(&self) -> &R;
/// Returns true if the given length value should be considered an
/// end-of-entries sentinel.
fn length_value_is_end_of_entries(length: R::Offset) -> bool;
/// Return true if the given offset if the CIE sentinel, false otherwise.
fn is_cie(format: Format, id: u64) -> bool;
/// Return the CIE offset/ID encoding used by this unwind section with the
/// given DWARF format.
fn cie_offset_encoding(format: Format) -> CieOffsetEncoding;
/// For `.eh_frame`, CIE offsets are relative to the current position. For
/// `.debug_frame`, they are relative to the start of the section. We always
/// internally store them relative to the section, so we handle translating
/// `.eh_frame`'s relative offsets in this method. If the offset calculation
/// underflows, return `None`.
fn resolve_cie_offset(&self, base: R::Offset, offset: R::Offset) -> Option<R::Offset>;
/// Does this version of this unwind section encode address and segment
/// sizes in its CIEs?
fn has_address_and_segment_sizes(version: u8) -> bool;
/// The address size to use if `has_address_and_segment_sizes` returns false.
fn address_size(&self) -> u8;
/// The segment size to use if `has_address_and_segment_sizes` returns false.
fn segment_size(&self) -> u8;
/// The vendor extensions to use.
fn vendor(&self) -> Vendor;
}
/// A section holding unwind information: either `.debug_frame` or
/// `.eh_frame`. See [`DebugFrame`](./struct.DebugFrame.html) and
/// [`EhFrame`](./struct.EhFrame.html) respectively.
pub trait UnwindSection<R: Reader>: Clone + Debug + _UnwindSectionPrivate<R> {
/// The offset type associated with this CFI section. Either
/// `DebugFrameOffset` or `EhFrameOffset`.
type Offset: UnwindOffset<R::Offset>;
/// Iterate over the `CommonInformationEntry`s and `FrameDescriptionEntry`s
/// in this `.debug_frame` section.
///
/// Can be [used with
/// `FallibleIterator`](./index.html#using-with-fallibleiterator).
fn entries<'bases>(&self, bases: &'bases BaseAddresses) -> CfiEntriesIter<'bases, Self, R> {
CfiEntriesIter {
section: self.clone(),
bases,
input: self.section().clone(),
}
}
/// Parse the `CommonInformationEntry` at the given offset.
fn cie_from_offset(
&self,
bases: &BaseAddresses,
offset: Self::Offset,
) -> Result<CommonInformationEntry<R>> {
let offset = UnwindOffset::into(offset);
let input = &mut self.section().clone();
input.skip(offset)?;
CommonInformationEntry::parse(bases, self, input)
}
/// Parse the `PartialFrameDescriptionEntry` at the given offset.
fn partial_fde_from_offset<'bases>(
&self,
bases: &'bases BaseAddresses,
offset: Self::Offset,
) -> Result<PartialFrameDescriptionEntry<'bases, Self, R>> {
let offset = UnwindOffset::into(offset);
let input = &mut self.section().clone();
input.skip(offset)?;
PartialFrameDescriptionEntry::parse_partial(self, bases, input)
}
/// Parse the `FrameDescriptionEntry` at the given offset.
fn fde_from_offset<F>(
&self,
bases: &BaseAddresses,
offset: Self::Offset,
get_cie: F,
) -> Result<FrameDescriptionEntry<R>>
where
F: FnMut(&Self, &BaseAddresses, Self::Offset) -> Result<CommonInformationEntry<R>>,
{
let partial = self.partial_fde_from_offset(bases, offset)?;
partial.parse(get_cie)
}
/// Find the `FrameDescriptionEntry` for the given address.
///
/// If found, the FDE is returned. If not found,
/// `Err(gimli::Error::NoUnwindInfoForAddress)` is returned.
/// If parsing fails, the error is returned.
///
/// You must provide a function to get its associated CIE. See
/// `PartialFrameDescriptionEntry::parse` for more information.
///
/// Note: this iterates over all FDEs. If available, it is possible
/// to do a binary search with `EhFrameHdr::fde_for_address` instead.
fn fde_for_address<F>(
&self,
bases: &BaseAddresses,
address: u64,
mut get_cie: F,
) -> Result<FrameDescriptionEntry<R>>
where
F: FnMut(&Self, &BaseAddresses, Self::Offset) -> Result<CommonInformationEntry<R>>,
{
let mut entries = self.entries(bases);
while let Some(entry) = entries.next()? {
match entry {
CieOrFde::Cie(_) => {}
CieOrFde::Fde(partial) => {
let fde = partial.parse(&mut get_cie)?;
if fde.contains(address) {
return Ok(fde);
}
}
}
}
Err(Error::NoUnwindInfoForAddress)
}
/// Find the frame unwind information for the given address.
///
/// If found, the unwind information is returned. If not found,
/// `Err(gimli::Error::NoUnwindInfoForAddress)` is returned. If parsing or
/// CFI evaluation fails, the error is returned.
///
/// ```
/// use gimli::{BaseAddresses, EhFrame, EndianSlice, NativeEndian, UnwindContext,
/// UnwindSection};
///
/// # fn foo() -> gimli::Result<()> {
/// # let read_eh_frame_section = || unimplemented!();
/// // Get the `.eh_frame` section from the object file. Alternatively,
/// // use `EhFrame` with the `.eh_frame` section of the object file.
/// let eh_frame = EhFrame::new(read_eh_frame_section(), NativeEndian);
///
/// # let get_frame_pc = || unimplemented!();
/// // Get the address of the PC for a frame you'd like to unwind.
/// let address = get_frame_pc();
///
/// // This context is reusable, which cuts down on heap allocations.
/// let ctx = UnwindContext::new();
///
/// // Optionally provide base addresses for any relative pointers. If a
/// // base address isn't provided and a pointer is found that is relative to
/// // it, we will return an `Err`.
/// # let address_of_text_section_in_memory = unimplemented!();
/// # let address_of_got_section_in_memory = unimplemented!();
/// let bases = BaseAddresses::default()
/// .set_text(address_of_text_section_in_memory)
/// .set_got(address_of_got_section_in_memory);
///
/// let unwind_info = eh_frame.unwind_info_for_address(
/// &bases,
/// &mut ctx,
/// address,
/// EhFrame::cie_from_offset,
/// )?;
///
/// # let do_stuff_with = |_| unimplemented!();
/// do_stuff_with(unwind_info);
/// # let _ = ctx;
/// # unreachable!()
/// # }
/// ```
#[inline]
fn unwind_info_for_address<'ctx, F, A: UnwindContextStorage<R>>(
&self,
bases: &BaseAddresses,
ctx: &'ctx mut UnwindContext<R, A>,
address: u64,
get_cie: F,
) -> Result<&'ctx UnwindTableRow<R, A>>
where
F: FnMut(&Self, &BaseAddresses, Self::Offset) -> Result<CommonInformationEntry<R>>,
{
let fde = self.fde_for_address(bases, address, get_cie)?;
fde.unwind_info_for_address(self, bases, ctx, address)
}
}
impl<R: Reader> _UnwindSectionPrivate<R> for DebugFrame<R> {
fn section(&self) -> &R {
&self.section
}
fn length_value_is_end_of_entries(_: R::Offset) -> bool {
false
}
fn is_cie(format: Format, id: u64) -> bool {
match format {
Format::Dwarf32 => id == 0xffff_ffff,
Format::Dwarf64 => id == 0xffff_ffff_ffff_ffff,
}
}
fn cie_offset_encoding(format: Format) -> CieOffsetEncoding {
match format {
Format::Dwarf32 => CieOffsetEncoding::U32,
Format::Dwarf64 => CieOffsetEncoding::U64,
}
}
fn resolve_cie_offset(&self, _: R::Offset, offset: R::Offset) -> Option<R::Offset> {
Some(offset)
}
fn has_address_and_segment_sizes(version: u8) -> bool {
version == 4
}
fn address_size(&self) -> u8 {
self.address_size
}
fn segment_size(&self) -> u8 {
self.segment_size
}
fn vendor(&self) -> Vendor {
self.vendor
}
}
impl<R: Reader> UnwindSection<R> for DebugFrame<R> {
type Offset = DebugFrameOffset<R::Offset>;
}
impl<R: Reader> _UnwindSectionPrivate<R> for EhFrame<R> {
fn section(&self) -> &R {
&self.section
}
fn length_value_is_end_of_entries(length: R::Offset) -> bool {
length.into_u64() == 0
}
fn is_cie(_: Format, id: u64) -> bool {
id == 0
}
fn cie_offset_encoding(_format: Format) -> CieOffsetEncoding {
// `.eh_frame` offsets are always 4 bytes, regardless of the DWARF
// format.
CieOffsetEncoding::U32
}
fn resolve_cie_offset(&self, base: R::Offset, offset: R::Offset) -> Option<R::Offset> {
base.checked_sub(offset)
}
fn has_address_and_segment_sizes(_version: u8) -> bool {
false
}
fn address_size(&self) -> u8 {
self.address_size
}
fn segment_size(&self) -> u8 {
0
}
fn vendor(&self) -> Vendor {
self.vendor
}
}
impl<R: Reader> UnwindSection<R> for EhFrame<R> {
type Offset = EhFrameOffset<R::Offset>;
}
/// Optional base addresses for the relative `DW_EH_PE_*` encoded pointers.
///
/// During CIE/FDE parsing, if a relative pointer is encountered for a base
/// address that is unknown, an Err will be returned.
///
/// ```
/// use gimli::BaseAddresses;
///
/// # fn foo() {
/// # let address_of_eh_frame_hdr_section_in_memory = unimplemented!();
/// # let address_of_eh_frame_section_in_memory = unimplemented!();
/// # let address_of_text_section_in_memory = unimplemented!();
/// # let address_of_got_section_in_memory = unimplemented!();
/// # let address_of_the_start_of_current_func = unimplemented!();
/// let bases = BaseAddresses::default()
/// .set_eh_frame_hdr(address_of_eh_frame_hdr_section_in_memory)
/// .set_eh_frame(address_of_eh_frame_section_in_memory)
/// .set_text(address_of_text_section_in_memory)
/// .set_got(address_of_got_section_in_memory);
/// # let _ = bases;
/// # }
/// ```
#[derive(Clone, Default, Debug, PartialEq, Eq)]
pub struct BaseAddresses {
/// The base addresses to use for pointers in the `.eh_frame_hdr` section.
pub eh_frame_hdr: SectionBaseAddresses,
/// The base addresses to use for pointers in the `.eh_frame` section.
pub eh_frame: SectionBaseAddresses,
}
/// Optional base addresses for the relative `DW_EH_PE_*` encoded pointers
/// in a particular section.
///
/// See `BaseAddresses` for methods that are helpful in setting these addresses.
#[derive(Clone, Default, Debug, PartialEq, Eq)]
pub struct SectionBaseAddresses {
/// The address of the section containing the pointer.
pub section: Option<u64>,
/// The base address for text relative pointers.
/// This is generally the address of the `.text` section.
pub text: Option<u64>,
/// The base address for data relative pointers.
///
/// For pointers in the `.eh_frame_hdr` section, this is the address
/// of the `.eh_frame_hdr` section
///
/// For pointers in the `.eh_frame` section, this is generally the
/// global pointer, such as the address of the `.got` section.
pub data: Option<u64>,
}
impl BaseAddresses {
/// Set the `.eh_frame_hdr` section base address.
#[inline]
pub fn set_eh_frame_hdr(mut self, addr: u64) -> Self {
self.eh_frame_hdr.section = Some(addr);
self.eh_frame_hdr.data = Some(addr);
self
}
/// Set the `.eh_frame` section base address.
#[inline]
pub fn set_eh_frame(mut self, addr: u64) -> Self {
self.eh_frame.section = Some(addr);
self
}
/// Set the `.text` section base address.
#[inline]
pub fn set_text(mut self, addr: u64) -> Self {
self.eh_frame_hdr.text = Some(addr);
self.eh_frame.text = Some(addr);
self
}
/// Set the `.got` section base address.
#[inline]
pub fn set_got(mut self, addr: u64) -> Self {
self.eh_frame.data = Some(addr);
self
}
}
/// An iterator over CIE and FDE entries in a `.debug_frame` or `.eh_frame`
/// section.
///
/// Some pointers may be encoded relative to various base addresses. Use the
/// [`BaseAddresses`](./struct.BaseAddresses.html) parameter to provide them. By
/// default, none are provided. If a relative pointer is encountered for a base
/// address that is unknown, an `Err` will be returned and iteration will abort.
///
/// Can be [used with
/// `FallibleIterator`](./index.html#using-with-fallibleiterator).
///
/// ```
/// use gimli::{BaseAddresses, EhFrame, EndianSlice, NativeEndian, UnwindSection};
///
/// # fn foo() -> gimli::Result<()> {
/// # let read_eh_frame_somehow = || unimplemented!();
/// let eh_frame = EhFrame::new(read_eh_frame_somehow(), NativeEndian);
///
/// # let address_of_eh_frame_hdr_section_in_memory = unimplemented!();
/// # let address_of_eh_frame_section_in_memory = unimplemented!();
/// # let address_of_text_section_in_memory = unimplemented!();
/// # let address_of_got_section_in_memory = unimplemented!();
/// # let address_of_the_start_of_current_func = unimplemented!();
/// // Provide base addresses for relative pointers.
/// let bases = BaseAddresses::default()
/// .set_eh_frame_hdr(address_of_eh_frame_hdr_section_in_memory)
/// .set_eh_frame(address_of_eh_frame_section_in_memory)