Debian Codegraph @

third_party/rust/macho-unwind-info/examples/unwindinfolookup.rs

raw
1 use std::{fmt::Display, fs::File, io::Read};
2
3 use macho_unwind_info::opcodes::{OpcodeArm64, OpcodeX86, OpcodeX86_64};
4 use macho_unwind_info::UnwindInfo;
5 use object::{Architecture, ObjectSection};
6
7 fn main() {
8 let mut args = std::env::args().skip(1);
9 if args.len() < 1 {
10 eprintln!("Usage: {} <path> <pc>", std::env::args().next().unwrap());
11 std::process::exit(1);
12 }
13 let path = args.next().unwrap();
14 let pc = args.next().unwrap();
15 let pc: u32 = if let Some(hexstr) = pc.strip_prefix("0x") {
16 u32::from_str_radix(hexstr, 16).unwrap()
17 } else {
18 pc.parse().unwrap()
19 };
20
21 let mut data = Vec::new();
22 let mut file = File::open(path).unwrap();
23 file.read_to_end(&mut data).unwrap();
24 let data = &data[..];
25
26 let file = object::File::parse(data).expect("Could not parse object file");
27 use object::Object;
28 let unwind_info_data_section = file
29 .section_by_name_bytes(b"__unwind_info")
30 .expect("Could not find __unwind_info section");
31 let data = unwind_info_data_section.data().unwrap();
32 let arch = file.architecture();
33
34 let unwind_info = UnwindInfo::parse(data).unwrap();
35 let function = match unwind_info.lookup(pc) {
36 Ok(Some(f)) => f,
37 Ok(None) => {
38 println!("No entry was found for address 0x{:x}", pc);
39 std::process::exit(1);
40 }
41 Err(e) => {
42 println!(
43 "There was an error when looking up address 0x{:x}: {}",
44 pc, e
45 );
46 std::process::exit(1);
47 }
48 };
49 print_entry(function.start_address, function.opcode, arch);
50 }
51
52 fn print_entry(address: u32, opcode: u32, arch: Architecture) {
53 match arch {
54 Architecture::I386 => print_entry_impl(address, OpcodeX86::parse(opcode)),
55 Architecture::X86_64 => print_entry_impl(address, OpcodeX86_64::parse(opcode)),
56 Architecture::Aarch64 => print_entry_impl(address, OpcodeArm64::parse(opcode)),
57 _ => {}
58 }
59 }
60
61 fn print_entry_impl(address: u32, opcode: impl Display) {
62 println!(
63 "Found entry with function address 0x{:08x} and opcode {}",
64 address, opcode
65 );
66 }