From 8351ba3e3e69f840fbc1258e9effd43c8c59f036 Mon Sep 17 00:00:00 2001 From: Tyler McMullen Date: Mon, 23 Apr 2018 23:24:02 -0400 Subject: [PATCH] Disassemble compiled binary for debugging (#308) * Use Capstone to disassemble and print code after compilation in cton-util. * Fix rustfmt errors --- cranelift/Cargo.toml | 1 + cranelift/src/compile.rs | 41 +++++++++++++++++++++++++++++++++++++- cranelift/src/cton-util.rs | 1 + 3 files changed, 42 insertions(+), 1 deletion(-) diff --git a/cranelift/Cargo.toml b/cranelift/Cargo.toml index ded5a8e588..dc916f116a 100644 --- a/cranelift/Cargo.toml +++ b/cranelift/Cargo.toml @@ -29,5 +29,6 @@ serde = "1.0.8" serde_derive = "1.0.8" tempdir = "0.3.5" term = "0.5.1" +capstone = "0.3.1" [workspace] diff --git a/cranelift/src/compile.rs b/cranelift/src/compile.rs index 4b9f77494d..def23bf7de 100644 --- a/cranelift/src/compile.rs +++ b/cranelift/src/compile.rs @@ -1,8 +1,10 @@ //! CLI tool to read Cretonne IR files and compile them into native code. -use cretonne_codegen::Context; +use capstone::prelude::*; +use cretonne_codegen::isa::TargetIsa; use cretonne_codegen::print_errors::pretty_error; use cretonne_codegen::settings::FlagsOrIsa; +use cretonne_codegen::Context; use cretonne_codegen::{binemit, ir}; use cretonne_reader::parse_test; use std::path::Path; @@ -121,8 +123,45 @@ fn handle_module( print!("{}", byte); } println!(); + + let cs = get_disassembler(isa)?; + + println!("\nDisassembly:"); + let insns = cs.disasm_all(&mem, 0x0).unwrap(); + for i in insns.iter() { + println!("{}", i); + } } } Ok(()) } + +fn get_disassembler(isa: &TargetIsa) -> Result { + let cs = match isa.name() { + "riscv" => return Err(String::from("No disassembler for RiscV")), + "x86" => { + if isa.flags().is_64bit() { + Capstone::new() + .x86() + .mode(arch::x86::ArchMode::Mode64) + .build() + } else { + Capstone::new() + .x86() + .mode(arch::x86::ArchMode::Mode32) + .build() + } + } + "arm32" => Capstone::new().arm().mode(arch::arm::ArchMode::Arm).build(), + "arm64" => { + Capstone::new() + .arm64() + .mode(arch::arm64::ArchMode::Arm) + .build() + } + _ => return Err(String::from("Unknown ISA")), + }; + + cs.map_err(|err| err.to_string()) +} diff --git a/cranelift/src/cton-util.rs b/cranelift/src/cton-util.rs index d69c561c44..0010034a0a 100644 --- a/cranelift/src/cton-util.rs +++ b/cranelift/src/cton-util.rs @@ -20,6 +20,7 @@ extern crate filecheck; extern crate serde_derive; extern crate tempdir; extern crate term; +extern crate capstone; use cretonne_codegen::{timing, VERSION}; use docopt::Docopt;