Skip to content

Commit 1509785

Browse files
committed
Add parallel disassemble example
1 parent 9d08967 commit 1509785

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

capstone-rs/Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ libc = { version = "0.2", default-features = false }
2121
[dev-dependencies]
2222
macho = "0.*"
2323
criterion = "0.2"
24+
rayon = "1.1"
2425

2526
[[bench]]
2627
name = "my_benchmark"

capstone-rs/examples/parallel.rs

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
//! This example shows how to disassemble in parallel. You need a separate `Capstone` struct for
2+
//! each thread.
3+
//!
4+
//! We shard the input by using parallel iterators from the rayon crate.
5+
6+
use capstone::prelude::*;
7+
use rayon::prelude::*;
8+
9+
fn main() -> CsResult<()> {
10+
// Closure to create `Capstone` instance
11+
let create_cs = || -> CsResult<Capstone> {
12+
let cs = Capstone::new()
13+
.x86()
14+
.mode(arch::x86::ArchMode::Mode64)
15+
.detail(true)
16+
.build()?;
17+
Ok(cs)
18+
};
19+
20+
// Slice of code to disassemble
21+
let input_code: &[&[u8]] = &[
22+
b"\x55\x48\x8b\x05\xb8\x13\x00\x00\xe9\x14\x9e\x08\x00\x45\x31\xe4",
23+
b"\x90\x41\xe8\x04\x03\x02\x01",
24+
b"\xff\xff\xff\xff\xff",
25+
];
26+
27+
let results: Vec<CsResult<Vec<String>>> = input_code
28+
.par_iter() // iterate in parallel
29+
.map(|bytes| {
30+
// map input byte to output mnemonic
31+
let cs = create_cs()?;
32+
let insns = cs.disasm_all(bytes, 0x1000)?;
33+
let result: Option<Vec<String>> = insns
34+
.iter()
35+
.map(|insn| -> Option<String> { Some(insn.mnemonic()?.to_string()) })
36+
.collect();
37+
let result = result.ok_or(capstone::Error::CustomError("No mnemonic"))?;
38+
Ok(result)
39+
})
40+
.collect();
41+
42+
println!("{:#?}", results);
43+
44+
Ok(())
45+
}

0 commit comments

Comments
 (0)