Browse Source

examples/to_json.rs: load program from ELF file instead of hardcoding it

Quentin Monnet 8 years ago
parent
commit
485a575341
1 changed files with 21 additions and 28 deletions
  1. 21 28
      examples/to_json.rs

+ 21 - 28
examples/to_json.rs

@@ -8,6 +8,10 @@
 #[macro_use]
 extern crate json;
 
+extern crate byteorder;
+extern crate elf;
+use std::path::PathBuf;
+
 extern crate rbpf;
 use rbpf::disassembler;
 
@@ -52,35 +56,24 @@ fn to_json(prog: &std::vec::Vec<u8>) -> String {
         ), 4)
 }
 
-// Print a JSON string representing the program to standard output.
+// Load a program from an object file, and prints it to standard output as a JSON string.
 fn main() {
-    let prog = vec![
-        0xb7, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-        0x79, 0x12, 0x50, 0x00, 0x00, 0x00, 0x00, 0x00,
-        0x79, 0x11, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00,
-        0xbf, 0x13, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-        0x07, 0x03, 0x00, 0x00, 0x36, 0x00, 0x00, 0x00,
-        0x2d, 0x23, 0x12, 0x00, 0x00, 0x00, 0x00, 0x00,
-        0x69, 0x12, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00,
-        0x55, 0x02, 0x10, 0x00, 0x08, 0x00, 0x00, 0x00,
-        0x71, 0x12, 0x17, 0x00, 0x00, 0x00, 0x00, 0x00,
-        0x55, 0x02, 0x0e, 0x00, 0x06, 0x00, 0x00, 0x00,
-        0x18, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff,
-        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-        0x79, 0x11, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00,
-        0xbf, 0x12, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-        0x57, 0x02, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00,
-        0x15, 0x02, 0x08, 0x00, 0x99, 0x99, 0x00, 0x00,
-        0x18, 0x02, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff,
-        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-        0x5f, 0x21, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-        0xb7, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff,
-        0x18, 0x02, 0x00, 0x00, 0x00, 0x00, 0x99, 0x99,
-        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-        0x1d, 0x21, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00,
-        0xb7, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-        0x95, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
-    ];
+
+    // Let's reuse this file from `load_elf` example.
+    let filename = "examples/load_elf__block_a_port.o";
+
+    let path = PathBuf::from(filename);
+    let file = match elf::File::open_path(&path) {
+        Ok(f) => f,
+        Err(e) => panic!("Error: {:?}", e),
+    };
+
+    let text_scn = match file.get_section(".classifier") {
+        Some(s) => s,
+        None => panic!("Failed to look up .classifier section"),
+    };
+
+    let ref prog = &text_scn.data;
 
     println!("{}", to_json(&prog));
 }