Crate capstone [] [src]

Bindings to the capstone library disassembly framework.

This crate is a wrapper around the Capstone disassembly library, a "lightweight multi-platform, multi-architecture disassembly framework."

The Capstone struct is the main interface to the library.

extern crate capstone;

use capstone::prelude::*;
use capstone::InsnDetail;

const MIPS_CODE: &'static [u8] = b"\x56\x34\x21\x34\xc2\x17\x01\x00";

const X86_CODE: &'static [u8] = b"\x55\x48\x8b\x05\xb8\x13\x00\x00\xe9\x14\x9e\x08\x00\x45\x31\xe4";

/// Print register names
fn reg_names<T, I>(cs: &Capstone, regs: T) -> String
where
    T: Iterator<Item = I>,
    I: Into<RegId>,
{
    let names: Vec<String> = regs.map(|x| cs.reg_name(x.into()).unwrap()).collect();
    names.join(", ")
}

/// Print instruction group names
fn group_names<T, I>(cs: &Capstone, regs: T) -> String
where
    T: Iterator<Item = I>,
    I: Into<InsnGroupId>,
{
    let names: Vec<String> = regs.map(|x| cs.group_name(x.into()).unwrap()).collect();
    names.join(", ")
}

/// Disassemble code and print information
fn arch_example(cs: &mut Capstone, code: &[u8]) -> CsResult<()> {
    let insns = cs.disasm_all(code, 0x1000)?;
    println!("Found {} instructions", insns.len());
    for i in insns.iter() {
        println!();
        println!("{}", i);

        let detail: InsnDetail = cs.insn_detail(&i)?;
        let arch_detail: ArchDetail = detail.arch_detail();
        let ops = arch_detail.operands();

        let output: &[(&str, String)] = &[
            ("insn id:", format!("{:?}", i.id().0)),
            ("bytes:", format!("{:?}", i.bytes())),
            ("read regs:", reg_names(&cs, detail.regs_read())),
            ("write regs:", reg_names(&cs, detail.regs_write())),
            ("insn groups:", group_names(&cs, detail.groups())),
        ];

        for &(ref name, ref message) in output.iter() {
            println!("{:4}{:12} {}", "", name, message);
        }

        println!("{:4}operands: {}", "", ops.len());
        for op in ops {
            println!("{:8}{:?}", "", op);
        }
    }
    Ok(())
}

fn example() -> CsResult<()> {
    let cs_mips: Capstone = Capstone::new()
        .mips()
        .mode(arch::mips::ArchMode::Mips32R6)
        .detail(true)
        .build()?;

    let cs_x86 = Capstone::new()
        .x86()
        .mode(arch::x86::ArchMode::Mode64)
        .syntax(arch::x86::ArchSyntax::Att)
        .detail(true)
        .build()?;

    let mut examples = [
        ("MIPS", cs_mips, MIPS_CODE),
        ("X86", cs_x86, X86_CODE),
    ];

    for &mut (arch, ref mut cs, code) in examples.iter_mut() {
        println!("\n*************************************");
        println!("Architecture {}:", arch);
        arch_example(cs, &code)?;
    }

    Ok(())
}

fn main() {
    if let Err(err) = example() {
        println!("Error: {}", err);
    }
}

Produces:


*************************************
Architecture MIPS:
Found 2 instructions

0x1000: ori $at, $at, 0x3456
    insn id:     445
    bytes:       [86, 52, 33, 52]
    read regs:
    write regs:
    insn groups: stdenc
    operands: 3
        MipsOperand(Reg(RegId(2)))
        MipsOperand(Reg(RegId(2)))
        MipsOperand(Imm(13398))

0x1004: srl $v0, $at, 0x1f
    insn id:     525
    bytes:       [194, 23, 1, 0]
    read regs:
    write regs:
    insn groups: stdenc
    operands: 3
        MipsOperand(Reg(RegId(3)))
        MipsOperand(Reg(RegId(2)))
        MipsOperand(Imm(31))

*************************************
Architecture X86:
Found 4 instructions

0x1000: pushq %rbp
    insn id:     580
    bytes:       [85]
    read regs:   rsp
    write regs:  rsp
    insn groups: mode64
    operands: 1
        X86Operand(X86Operand { size: 8, avx_bcast: X86_AVX_BCAST_INVALID, avx_zero_opmask: false, op_type: Reg(RegId(36)) })

0x1001: movq 0x13b8(%rip), %rax
    insn id:     442
    bytes:       [72, 139, 5, 184, 19, 0, 0]
    read regs:
    write regs:
    insn groups:
    operands: 2
        X86Operand(X86Operand { size: 8, avx_bcast: X86_AVX_BCAST_INVALID, avx_zero_opmask: false, op_type: Mem(X86OpMem(x86_op_mem { segment: 0, base: 41, index: 0, scale: 1, disp: 5048 })) })
        X86Operand(X86Operand { size: 8, avx_bcast: X86_AVX_BCAST_INVALID, avx_zero_opmask: false, op_type: Reg(RegId(35)) })

0x1008: jmp 0x8ae21
    insn id:     266
    bytes:       [233, 20, 158, 8, 0]
    read regs:
    write regs:
    insn groups: jump
    operands: 1
        X86Operand(X86Operand { size: 8, avx_bcast: X86_AVX_BCAST_INVALID, avx_zero_opmask: false, op_type: Imm(568865) })

0x100d: xorl %r12d, %r12d
    insn id:     327
    bytes:       [69, 49, 228]
    read regs:
    write regs:  rflags
    insn groups:
    operands: 2
        X86Operand(X86Operand { size: 4, avx_bcast: X86_AVX_BCAST_INVALID, avx_zero_opmask: false, op_type: Reg(RegId(222)) })
        X86Operand(X86Operand { size: 4, avx_bcast: X86_AVX_BCAST_INVALID, avx_zero_opmask: false, op_type: Reg(RegId(222)) })

Modules

arch

Contains architecture-specific types and modules

prelude

Contains items that you probably want to always import

Structs

Capstone

An instance of the capstone disassembler

EmptyExtraModeIter

Represents an empty set of ExtraMode.

Insn

A wrapper for the raw capstone-sys instruction

InsnDetail

Contains extra information about an instruction such as register reads in addition to architecture-specific information

InsnGroupId

Represents the group an instruction belongs to, which may be architecture-specific.

InsnGroupIter

Iterator over instruction group ids

InsnId

Represents an instruction id, which may architecture-specific.

InstructionIterator

An iterator over the instructions returned by disasm

Instructions

Representation of the array of instructions returned by disasm

RegId

Represents an register id, which is architecture-specific.

RegsIter

Iterator over registers ids

Enums

Arch

Architectures for the disassembler

CapstoneError

Error for Capstone

Endian

Disassembler endianness

Error

An error enum for this library

ExtraMode

Extra modes or features that can be enabled with some modes

Mode

Disassembler modes

Syntax

Disassembly syntax

Statics

NO_EXTRA_MODE

Represents that no extra modes are enabled. Can be passed to Capstone::new_raw() as the extra_mode argument.

Type Definitions

CsResult
InsnGroupIdInt

Integer type used in InsnGroupId

InsnIdInt

Integer type used in InsnId

RegIdInt

Integer type used in RegId