1 // SPDX-License-Identifier: (Apache-2.0 OR MIT) 2 // Copyright 2017 6WIND S.A. <quentin.monnet@6wind.com> 3 4 #[macro_use] 5 extern crate json; 6 7 extern crate elf; 8 use std::path::PathBuf; 9 10 extern crate rbpf; 11 use rbpf::disassembler; 12 13 // Turn a program into a JSON string. 14 // 15 // Relies on `json` crate. 16 // 17 // You may copy this function and adapt it according to your needs. For instance, you may want to: 18 // 19 // * Remove the "desc" (description) attributes from the output. 20 // * Print integers as integers, and not as strings containing their hexadecimal representation 21 // (just replace the relevant `format!()` calls by the commented values. 22 fn to_json(prog: &[u8]) -> String { 23 // This call returns a high-level representation of the instructions, with the two parts of 24 // `LD_DW_IMM` instructions merged, and name and descriptions of the instructions. 25 // If you prefer to use a lower-level representation, use `ebpf::to_insn_vec()` function 26 // instead. 27 let insns = disassembler::to_insn_vec(prog); 28 let mut json_insns = vec![]; 29 for insn in insns { 30 json_insns.push(object!( 31 "opc" => format!("{:#x}", insn.opc), // => insn.opc, 32 "dst" => format!("{:#x}", insn.dst), // => insn.dst, 33 "src" => format!("{:#x}", insn.src), // => insn.src, 34 "off" => format!("{:#x}", insn.off), // => insn.off, 35 // Warning: for imm we use a i64 instead of a i32 (to have correct values for 36 // `lddw` operation. If we print a number in the JSON this is not a problem, the 37 // internal i64 has the same value with extended sign on 32 most significant bytes. 38 // If we print the hexadecimal value as a string however, we want to cast as a i32 39 // to prevent all other instructions to print spurious `ffffffff` prefix if the 40 // number is negative. When values takes more than 32 bits with `lddw`, the cast 41 // has no effect and the complete value is printed anyway. 42 "imm" => format!("{:#x}", insn.imm as i32), // => insn.imm, 43 "desc" => insn.desc 44 )); 45 } 46 json::stringify_pretty( 47 object!( 48 "size" => json_insns.len(), 49 "insns" => json_insns 50 ), 51 4, 52 ) 53 } 54 55 // Load a program from an object file, and prints it to standard output as a JSON string. 56 fn main() { 57 // Let's reuse this file from `load_elf/example`. 58 let filename = "examples/load_elf__block_a_port.elf"; 59 60 let path = PathBuf::from(filename); 61 let file = match elf::File::open_path(path) { 62 Ok(f) => f, 63 Err(e) => panic!("Error: {:?}", e), 64 }; 65 66 let text_scn = match file.get_section(".classifier") { 67 Some(s) => s, 68 None => panic!("Failed to look up .classifier section"), 69 }; 70 71 let prog = &text_scn.data; 72 73 println!("{}", to_json(prog)); 74 } 75