forked from gimli-rs/gimli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dwarfdump.rs
2369 lines (2254 loc) · 76.4 KB
/
dwarfdump.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
// Allow clippy lints when building without clippy.
#![allow(unknown_lints)]
use fallible_iterator::FallibleIterator;
use gimli::{Section, UnitHeader, UnitOffset, UnitSectionOffset, UnitType, UnwindSection};
use object::{Object, ObjectSection, ObjectSymbol};
use regex::bytes::Regex;
use std::borrow::{Borrow, Cow};
use std::cmp::min;
use std::collections::HashMap;
use std::env;
use std::fmt::{self, Debug};
use std::fs;
use std::io;
use std::io::{BufWriter, Write};
use std::iter::Iterator;
use std::mem;
use std::process;
use std::result;
use std::sync::{Condvar, Mutex};
use typed_arena::Arena;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Error {
GimliError(gimli::Error),
ObjectError(object::read::Error),
IoError,
}
impl fmt::Display for Error {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> ::std::result::Result<(), fmt::Error> {
Debug::fmt(self, f)
}
}
fn writeln_error<W: Write, R: Reader>(
w: &mut W,
dwarf: &gimli::Dwarf<R>,
err: Error,
msg: &str,
) -> io::Result<()> {
writeln!(
w,
"{}: {}",
msg,
match err {
Error::GimliError(err) => dwarf.format_error(err),
Error::ObjectError(err) =>
format!("{}:{:?}", "An object error occurred while reading", err),
Error::IoError => "An I/O error occurred while writing.".to_string(),
}
)
}
impl From<gimli::Error> for Error {
fn from(err: gimli::Error) -> Self {
Error::GimliError(err)
}
}
impl From<io::Error> for Error {
fn from(_: io::Error) -> Self {
Error::IoError
}
}
impl From<object::read::Error> for Error {
fn from(err: object::read::Error) -> Self {
Error::ObjectError(err)
}
}
pub type Result<T> = result::Result<T, Error>;
fn parallel_output<W, II, F>(w: &mut W, max_workers: usize, iter: II, f: F) -> Result<()>
where
W: Write + Send,
F: Sync + Fn(II::Item, &mut Vec<u8>) -> Result<()>,
II: IntoIterator,
II::IntoIter: Send,
{
struct ParallelOutputState<I, W> {
iterator: I,
current_worker: usize,
result: Result<()>,
w: W,
}
let state = Mutex::new(ParallelOutputState {
iterator: iter.into_iter().fuse(),
current_worker: 0,
result: Ok(()),
w,
});
let workers = min(max_workers, num_cpus::get());
let mut condvars = Vec::new();
for _ in 0..workers {
condvars.push(Condvar::new());
}
{
let state_ref = &state;
let f_ref = &f;
let condvars_ref = &condvars;
crossbeam::scope(|scope| {
for i in 0..workers {
scope.spawn(move |_| {
let mut v = Vec::new();
let mut lock = state_ref.lock().unwrap();
while lock.current_worker != i {
lock = condvars_ref[i].wait(lock).unwrap();
}
loop {
let item = if lock.result.is_ok() {
lock.iterator.next()
} else {
None
};
lock.current_worker = (i + 1) % workers;
condvars_ref[lock.current_worker].notify_one();
mem::drop(lock);
let ret = if let Some(item) = item {
v.clear();
f_ref(item, &mut v)
} else {
return;
};
lock = state_ref.lock().unwrap();
while lock.current_worker != i {
lock = condvars_ref[i].wait(lock).unwrap();
}
if lock.result.is_ok() {
let ret2 = lock.w.write_all(&v);
if ret.is_err() {
lock.result = ret;
} else {
lock.result = ret2.map_err(Error::from);
}
}
}
});
}
})
.unwrap();
}
state.into_inner().unwrap().result
}
trait Reader: gimli::Reader<Offset = usize> + Send + Sync {}
impl<'input, Endian> Reader for gimli::EndianSlice<'input, Endian> where
Endian: gimli::Endianity + Send + Sync
{
}
type RelocationMap = HashMap<usize, object::Relocation>;
fn add_relocations(
relocations: &mut RelocationMap,
file: &object::File,
section: &object::Section,
) {
for (offset64, mut relocation) in section.relocations() {
let offset = offset64 as usize;
if offset as u64 != offset64 {
continue;
}
let offset = offset as usize;
match relocation.kind() {
object::RelocationKind::Absolute => {
match relocation.target() {
object::RelocationTarget::Symbol(symbol_idx) => {
match file.symbol_by_index(symbol_idx) {
Ok(symbol) => {
let addend =
symbol.address().wrapping_add(relocation.addend() as u64);
relocation.set_addend(addend as i64);
}
Err(_) => {
eprintln!(
"Relocation with invalid symbol for section {} at offset 0x{:08x}",
section.name().unwrap(),
offset
);
}
}
}
_ => {}
}
if relocations.insert(offset, relocation).is_some() {
eprintln!(
"Multiple relocations for section {} at offset 0x{:08x}",
section.name().unwrap(),
offset
);
}
}
_ => {
eprintln!(
"Unsupported relocation for section {} at offset 0x{:08x}",
section.name().unwrap(),
offset
);
}
}
}
}
/// Apply relocations to addresses and offsets during parsing,
/// instead of requiring the data to be fully relocated prior
/// to parsing.
///
/// Pros
/// - allows readonly buffers, we don't need to implement writing of values back to buffers
/// - potentially allows us to handle addresses and offsets differently
/// - potentially allows us to add metadata from the relocation (eg symbol names)
/// Cons
/// - maybe incomplete
#[derive(Debug, Clone)]
struct Relocate<'a, R: gimli::Reader<Offset = usize>> {
relocations: &'a RelocationMap,
section: R,
reader: R,
}
impl<'a, R: gimli::Reader<Offset = usize>> Relocate<'a, R> {
fn relocate(&self, offset: usize, value: u64) -> u64 {
if let Some(relocation) = self.relocations.get(&offset) {
match relocation.kind() {
object::RelocationKind::Absolute => {
if relocation.has_implicit_addend() {
// Use the explicit addend too, because it may have the symbol value.
return value.wrapping_add(relocation.addend() as u64);
} else {
return relocation.addend() as u64;
}
}
_ => {}
}
};
value
}
}
impl<'a, R: gimli::Reader<Offset = usize>> gimli::Reader for Relocate<'a, R> {
type Endian = R::Endian;
type Offset = R::Offset;
fn read_address(&mut self, address_size: u8) -> gimli::Result<u64> {
let offset = self.reader.offset_from(&self.section);
let value = self.reader.read_address(address_size)?;
Ok(self.relocate(offset, value))
}
fn read_length(&mut self, format: gimli::Format) -> gimli::Result<usize> {
let offset = self.reader.offset_from(&self.section);
let value = self.reader.read_length(format)?;
<usize as gimli::ReaderOffset>::from_u64(self.relocate(offset, value as u64))
}
fn read_offset(&mut self, format: gimli::Format) -> gimli::Result<usize> {
let offset = self.reader.offset_from(&self.section);
let value = self.reader.read_offset(format)?;
<usize as gimli::ReaderOffset>::from_u64(self.relocate(offset, value as u64))
}
fn read_sized_offset(&mut self, size: u8) -> gimli::Result<usize> {
let offset = self.reader.offset_from(&self.section);
let value = self.reader.read_sized_offset(size)?;
<usize as gimli::ReaderOffset>::from_u64(self.relocate(offset, value as u64))
}
#[inline]
fn split(&mut self, len: Self::Offset) -> gimli::Result<Self> {
let mut other = self.clone();
other.reader.truncate(len)?;
self.reader.skip(len)?;
Ok(other)
}
// All remaining methods simply delegate to `self.reader`.
#[inline]
fn endian(&self) -> Self::Endian {
self.reader.endian()
}
#[inline]
fn len(&self) -> Self::Offset {
self.reader.len()
}
#[inline]
fn empty(&mut self) {
self.reader.empty()
}
#[inline]
fn truncate(&mut self, len: Self::Offset) -> gimli::Result<()> {
self.reader.truncate(len)
}
#[inline]
fn offset_from(&self, base: &Self) -> Self::Offset {
self.reader.offset_from(&base.reader)
}
#[inline]
fn offset_id(&self) -> gimli::ReaderOffsetId {
self.reader.offset_id()
}
#[inline]
fn lookup_offset_id(&self, id: gimli::ReaderOffsetId) -> Option<Self::Offset> {
self.reader.lookup_offset_id(id)
}
#[inline]
fn find(&self, byte: u8) -> gimli::Result<Self::Offset> {
self.reader.find(byte)
}
#[inline]
fn skip(&mut self, len: Self::Offset) -> gimli::Result<()> {
self.reader.skip(len)
}
#[inline]
fn to_slice(&self) -> gimli::Result<Cow<[u8]>> {
self.reader.to_slice()
}
#[inline]
fn to_string(&self) -> gimli::Result<Cow<str>> {
self.reader.to_string()
}
#[inline]
fn to_string_lossy(&self) -> gimli::Result<Cow<str>> {
self.reader.to_string_lossy()
}
#[inline]
fn read_slice(&mut self, buf: &mut [u8]) -> gimli::Result<()> {
self.reader.read_slice(buf)
}
}
impl<'a, R: Reader> Reader for Relocate<'a, R> {}
#[derive(Default)]
struct Flags<'a> {
eh_frame: bool,
goff: bool,
info: bool,
line: bool,
pubnames: bool,
pubtypes: bool,
aranges: bool,
dwo: bool,
dwp: bool,
dwo_parent: Option<object::File<'a>>,
sup: Option<object::File<'a>>,
raw: bool,
match_units: Option<Regex>,
}
fn print_usage(opts: &getopts::Options) -> ! {
let brief = format!("Usage: {} <options> <file>", env::args().next().unwrap());
write!(&mut io::stderr(), "{}", opts.usage(&brief)).ok();
process::exit(1);
}
fn main() {
let mut opts = getopts::Options::new();
opts.optflag(
"",
"eh-frame",
"print .eh-frame exception handling frame information",
);
opts.optflag("G", "", "show global die offsets");
opts.optflag("i", "", "print .debug_info and .debug_types sections");
opts.optflag("l", "", "print .debug_line section");
opts.optflag("p", "", "print .debug_pubnames section");
opts.optflag("r", "", "print .debug_aranges section");
opts.optflag("y", "", "print .debug_pubtypes section");
opts.optflag(
"",
"dwo",
"print the .dwo versions of the selected sections",
);
opts.optflag(
"",
"dwp",
"print the .dwp versions of the selected sections",
);
opts.optopt(
"",
"dwo-parent",
"use the specified file as the parent of the dwo or dwp (e.g. for .debug_addr)",
"library path",
);
opts.optflag("", "raw", "print raw data values");
opts.optopt(
"u",
"match-units",
"print compilation units whose output matches a regex",
"REGEX",
);
opts.optopt("", "sup", "path to supplementary object file", "PATH");
let matches = match opts.parse(env::args().skip(1)) {
Ok(m) => m,
Err(e) => {
writeln!(&mut io::stderr(), "{:?}\n", e).ok();
print_usage(&opts);
}
};
if matches.free.is_empty() {
print_usage(&opts);
}
let mut all = true;
let mut flags = Flags::default();
if matches.opt_present("eh-frame") {
flags.eh_frame = true;
all = false;
}
if matches.opt_present("G") {
flags.goff = true;
}
if matches.opt_present("i") {
flags.info = true;
all = false;
}
if matches.opt_present("l") {
flags.line = true;
all = false;
}
if matches.opt_present("p") {
flags.pubnames = true;
all = false;
}
if matches.opt_present("y") {
flags.pubtypes = true;
all = false;
}
if matches.opt_present("r") {
flags.aranges = true;
all = false;
}
if matches.opt_present("dwo") {
flags.dwo = true;
}
if matches.opt_present("dwp") {
flags.dwp = true;
}
if matches.opt_present("raw") {
flags.raw = true;
}
if all {
// .eh_frame is excluded even when printing all information.
// cosmetic flags like -G must be set explicitly too.
flags.info = true;
flags.line = true;
flags.pubnames = true;
flags.pubtypes = true;
flags.aranges = true;
}
flags.match_units = if let Some(r) = matches.opt_str("u") {
match Regex::new(&r) {
Ok(r) => Some(r),
Err(e) => {
eprintln!("Invalid regular expression {}: {}", r, e);
process::exit(1);
}
}
} else {
None
};
let arena_mmap = Arena::new();
let load_file = |path| {
let file = match fs::File::open(&path) {
Ok(file) => file,
Err(err) => {
eprintln!("Failed to open file '{}': {}", path, err);
process::exit(1);
}
};
let mmap = match unsafe { memmap2::Mmap::map(&file) } {
Ok(mmap) => mmap,
Err(err) => {
eprintln!("Failed to map file '{}': {}", path, err);
process::exit(1);
}
};
let mmap_ref = (*arena_mmap.alloc(mmap)).borrow();
match object::File::parse(&**mmap_ref) {
Ok(file) => Some(file),
Err(err) => {
eprintln!("Failed to parse file '{}': {}", path, err);
process::exit(1);
}
}
};
flags.sup = matches.opt_str("sup").and_then(load_file);
flags.dwo_parent = matches.opt_str("dwo-parent").and_then(load_file);
if flags.dwo_parent.is_some() && !flags.dwo && !flags.dwp {
eprintln!("--dwo-parent also requires --dwo or --dwp");
process::exit(1);
}
if flags.dwo_parent.is_none() && flags.dwp {
eprintln!("--dwp also requires --dwo-parent");
process::exit(1);
}
for file_path in &matches.free {
if matches.free.len() != 1 {
println!("{}", file_path);
println!();
}
let file = match fs::File::open(&file_path) {
Ok(file) => file,
Err(err) => {
eprintln!("Failed to open file '{}': {}", file_path, err);
continue;
}
};
let file = match unsafe { memmap2::Mmap::map(&file) } {
Ok(mmap) => mmap,
Err(err) => {
eprintln!("Failed to map file '{}': {}", file_path, err);
continue;
}
};
let file = match object::File::parse(&*file) {
Ok(file) => file,
Err(err) => {
eprintln!("Failed to parse file '{}': {}", file_path, err);
continue;
}
};
let endian = if file.is_little_endian() {
gimli::RunTimeEndian::Little
} else {
gimli::RunTimeEndian::Big
};
let ret = dump_file(&file, endian, &flags);
match ret {
Ok(_) => (),
Err(err) => eprintln!("Failed to dump '{}': {}", file_path, err,),
}
}
}
fn empty_file_section<'input, 'arena, Endian: gimli::Endianity>(
endian: Endian,
arena_relocations: &'arena Arena<RelocationMap>,
) -> Relocate<'arena, gimli::EndianSlice<'arena, Endian>> {
let reader = gimli::EndianSlice::new(&[], endian);
let section = reader;
let relocations = RelocationMap::default();
let relocations = (*arena_relocations.alloc(relocations)).borrow();
Relocate {
relocations,
section,
reader,
}
}
fn load_file_section<'input, 'arena, Endian: gimli::Endianity>(
id: gimli::SectionId,
file: &object::File<'input>,
endian: Endian,
is_dwo: bool,
arena_data: &'arena Arena<Cow<'input, [u8]>>,
arena_relocations: &'arena Arena<RelocationMap>,
) -> Result<Relocate<'arena, gimli::EndianSlice<'arena, Endian>>> {
let mut relocations = RelocationMap::default();
let name = if is_dwo {
id.dwo_name()
} else if file.format() == object::BinaryFormat::Xcoff {
id.xcoff_name()
} else {
Some(id.name())
};
let data = match name.and_then(|name| file.section_by_name(&name)) {
Some(ref section) => {
// DWO sections never have relocations, so don't bother.
if !is_dwo {
add_relocations(&mut relocations, file, section);
}
section.uncompressed_data()?
}
// Use a non-zero capacity so that `ReaderOffsetId`s are unique.
None => Cow::Owned(Vec::with_capacity(1)),
};
let data_ref = (*arena_data.alloc(data)).borrow();
let reader = gimli::EndianSlice::new(data_ref, endian);
let section = reader;
let relocations = (*arena_relocations.alloc(relocations)).borrow();
Ok(Relocate {
relocations,
section,
reader,
})
}
fn dump_file<Endian>(file: &object::File, endian: Endian, flags: &Flags) -> Result<()>
where
Endian: gimli::Endianity + Send + Sync,
{
let arena_data = Arena::new();
let arena_relocations = Arena::new();
let dwo_parent = if let Some(dwo_parent_file) = flags.dwo_parent.as_ref() {
let mut load_dwo_parent_section = |id: gimli::SectionId| -> Result<_> {
load_file_section(
id,
dwo_parent_file,
endian,
false,
&arena_data,
&arena_relocations,
)
};
Some(gimli::Dwarf::load(&mut load_dwo_parent_section)?)
} else {
None
};
let dwo_parent = dwo_parent.as_ref();
let dwo_parent_units = if let Some(dwo_parent) = dwo_parent {
Some(
match dwo_parent
.units()
.map(|unit_header| dwo_parent.unit(unit_header))
.filter_map(|unit| Ok(unit.dwo_id.map(|dwo_id| (dwo_id, unit))))
.collect()
{
Ok(units) => units,
Err(err) => {
eprintln!("Failed to process --dwo-parent units: {}", err);
return Ok(());
}
},
)
} else {
None
};
let dwo_parent_units = dwo_parent_units.as_ref();
let mut load_section = |id: gimli::SectionId| -> Result<_> {
load_file_section(
id,
file,
endian,
flags.dwo || flags.dwp,
&arena_data,
&arena_relocations,
)
};
let w = &mut BufWriter::new(io::stdout());
if flags.dwp {
let empty = empty_file_section(endian, &arena_relocations);
let dwp = gimli::DwarfPackage::load(&mut load_section, empty)?;
dump_dwp(w, &dwp, dwo_parent.unwrap(), dwo_parent_units, flags)?;
w.flush()?;
return Ok(());
}
let mut dwarf = gimli::Dwarf::load(&mut load_section)?;
if flags.dwo {
if let Some(dwo_parent) = dwo_parent {
dwarf.make_dwo(&dwo_parent);
} else {
dwarf.file_type = gimli::DwarfFileType::Dwo;
}
}
if let Some(sup_file) = flags.sup.as_ref() {
let mut load_sup_section = |id: gimli::SectionId| -> Result<_> {
// Note: we really only need the `.debug_str` section,
// but for now we load them all.
load_file_section(id, sup_file, endian, false, &arena_data, &arena_relocations)
};
dwarf.load_sup(&mut load_sup_section)?;
}
if flags.eh_frame {
let eh_frame = gimli::EhFrame::load(&mut load_section).unwrap();
dump_eh_frame(w, file, eh_frame)?;
}
if flags.info {
dump_info(w, &dwarf, dwo_parent_units, flags)?;
dump_types(w, &dwarf, dwo_parent_units, flags)?;
}
if flags.line {
dump_line(w, &dwarf)?;
}
if flags.pubnames {
let debug_pubnames = &gimli::Section::load(&mut load_section).unwrap();
dump_pubnames(w, debug_pubnames, &dwarf.debug_info)?;
}
if flags.aranges {
let debug_aranges = &gimli::Section::load(&mut load_section).unwrap();
dump_aranges(w, debug_aranges)?;
}
if flags.pubtypes {
let debug_pubtypes = &gimli::Section::load(&mut load_section).unwrap();
dump_pubtypes(w, debug_pubtypes, &dwarf.debug_info)?;
}
w.flush()?;
Ok(())
}
fn dump_eh_frame<R: Reader, W: Write>(
w: &mut W,
file: &object::File,
mut eh_frame: gimli::EhFrame<R>,
) -> Result<()> {
// TODO: this might be better based on the file format.
let address_size = file
.architecture()
.address_size()
.map(|w| w.bytes())
.unwrap_or(mem::size_of::<usize>() as u8);
eh_frame.set_address_size(address_size);
fn register_name_none(_: gimli::Register) -> Option<&'static str> {
None
}
let arch_register_name = match file.architecture() {
object::Architecture::Arm | object::Architecture::Aarch64 => gimli::Arm::register_name,
object::Architecture::I386 => gimli::X86::register_name,
object::Architecture::X86_64 => gimli::X86_64::register_name,
_ => register_name_none,
};
let register_name = &|register| match arch_register_name(register) {
Some(name) => Cow::Borrowed(name),
None => Cow::Owned(format!("{}", register.0)),
};
let mut bases = gimli::BaseAddresses::default();
if let Some(section) = file.section_by_name(".eh_frame_hdr") {
bases = bases.set_eh_frame_hdr(section.address());
}
if let Some(section) = file.section_by_name(".eh_frame") {
bases = bases.set_eh_frame(section.address());
}
if let Some(section) = file.section_by_name(".text") {
bases = bases.set_text(section.address());
}
if let Some(section) = file.section_by_name(".got") {
bases = bases.set_got(section.address());
}
// TODO: Print "__eh_frame" here on macOS, and more generally use the
// section that we're actually looking at, which is what the canonical
// dwarfdump does.
writeln!(
w,
"Exception handling frame information for section .eh_frame"
)?;
let mut cies = HashMap::new();
let mut entries = eh_frame.entries(&bases);
loop {
match entries.next()? {
None => return Ok(()),
Some(gimli::CieOrFde::Cie(cie)) => {
writeln!(w)?;
writeln!(w, "{:#010x}: CIE", cie.offset())?;
writeln!(w, " length: {:#010x}", cie.entry_len())?;
// TODO: CIE_id
writeln!(w, " version: {:#04x}", cie.version())?;
// TODO: augmentation
writeln!(w, " code_align: {}", cie.code_alignment_factor())?;
writeln!(w, " data_align: {}", cie.data_alignment_factor())?;
writeln!(
w,
" ra_register: {}",
register_name(cie.return_address_register())
)?;
if let Some(encoding) = cie.lsda_encoding() {
writeln!(
w,
" lsda_encoding: {}/{}",
encoding.application(),
encoding.format()
)?;
}
if let Some((encoding, personality)) = cie.personality_with_encoding() {
write!(
w,
" personality: {}/{} ",
encoding.application(),
encoding.format()
)?;
dump_pointer(w, personality)?;
writeln!(w)?;
}
if let Some(encoding) = cie.fde_address_encoding() {
writeln!(
w,
" fde_encoding: {}/{}",
encoding.application(),
encoding.format()
)?;
}
let instructions = cie.instructions(&eh_frame, &bases);
dump_cfi_instructions(w, instructions, true, register_name)?;
writeln!(w)?;
}
Some(gimli::CieOrFde::Fde(partial)) => {
let mut offset = None;
let fde = partial.parse(|_, bases, o| {
offset = Some(o);
cies.entry(o)
.or_insert_with(|| eh_frame.cie_from_offset(bases, o))
.clone()
})?;
writeln!(w)?;
writeln!(w, "{:#010x}: FDE", fde.offset())?;
writeln!(w, " length: {:#010x}", fde.entry_len())?;
writeln!(w, " CIE_pointer: {:#010x}", offset.unwrap().0)?;
// TODO: symbolicate the start address like the canonical dwarfdump does.
writeln!(w, " start_addr: {:#018x}", fde.initial_address())?;
writeln!(
w,
" range_size: {:#018x} (end_addr = {:#018x})",
fde.len(),
fde.initial_address() + fde.len()
)?;
if let Some(lsda) = fde.lsda() {
write!(w, " lsda: ")?;
dump_pointer(w, lsda)?;
writeln!(w)?;
}
let instructions = fde.instructions(&eh_frame, &bases);
dump_cfi_instructions(w, instructions, false, register_name)?;
writeln!(w)?;
}
}
}
}
fn dump_pointer<W: Write>(w: &mut W, p: gimli::Pointer) -> Result<()> {
match p {
gimli::Pointer::Direct(p) => {
write!(w, "{:#018x}", p)?;
}
gimli::Pointer::Indirect(p) => {
write!(w, "({:#018x})", p)?;
}
}
Ok(())
}
#[allow(clippy::unneeded_field_pattern)]
fn dump_cfi_instructions<R: Reader, W: Write>(
w: &mut W,
mut insns: gimli::CallFrameInstructionIter<R>,
is_initial: bool,
register_name: &dyn Fn(gimli::Register) -> Cow<'static, str>,
) -> Result<()> {
use gimli::CallFrameInstruction::*;
// TODO: we need to actually evaluate these instructions as we iterate them
// so we can print the initialized state for CIEs, and each unwind row's
// registers for FDEs.
//
// TODO: We should print DWARF expressions for the CFI instructions that
// embed DWARF expressions within themselves.
if !is_initial {
writeln!(w, " Instructions:")?;
}
loop {
match insns.next() {
Err(e) => {
writeln!(w, "Failed to decode CFI instruction: {}", e)?;
return Ok(());
}
Ok(None) => {
if is_initial {
writeln!(w, " Instructions: Init State:")?;
}
return Ok(());
}
Ok(Some(op)) => match op {
SetLoc { address } => {
writeln!(w, " DW_CFA_set_loc ({:#x})", address)?;
}
AdvanceLoc { delta } => {
writeln!(w, " DW_CFA_advance_loc ({})", delta)?;
}
DefCfa { register, offset } => {
writeln!(
w,
" DW_CFA_def_cfa ({}, {})",
register_name(register),
offset
)?;
}
DefCfaSf {
register,
factored_offset,
} => {
writeln!(
w,
" DW_CFA_def_cfa_sf ({}, {})",
register_name(register),
factored_offset
)?;
}
DefCfaRegister { register } => {
writeln!(
w,
" DW_CFA_def_cfa_register ({})",
register_name(register)
)?;
}
DefCfaOffset { offset } => {
writeln!(w, " DW_CFA_def_cfa_offset ({})", offset)?;
}
DefCfaOffsetSf { factored_offset } => {
writeln!(
w,
" DW_CFA_def_cfa_offset_sf ({})",
factored_offset
)?;
}
DefCfaExpression { expression: _ } => {
writeln!(w, " DW_CFA_def_cfa_expression (...)")?;
}
Undefined { register } => {
writeln!(
w,
" DW_CFA_undefined ({})",
register_name(register)
)?;
}
SameValue { register } => {
writeln!(
w,
" DW_CFA_same_value ({})",
register_name(register)
)?;
}
Offset {
register,
factored_offset,
} => {
writeln!(
w,
" DW_CFA_offset ({}, {})",
register_name(register),
factored_offset
)?;
}
OffsetExtendedSf {
register,
factored_offset,
} => {
writeln!(
w,
" DW_CFA_offset_extended_sf ({}, {})",
register_name(register),
factored_offset
)?;
}
ValOffset {
register,
factored_offset,
} => {
writeln!(
w,
" DW_CFA_val_offset ({}, {})",
register_name(register),
factored_offset
)?;
}
ValOffsetSf {
register,
factored_offset,
} => {
writeln!(
w,