Skip to content

Ghidrust provides a hyper fast, AI native reverse engineering platform built in Rust, inspired by Ghidra. Includes experimental GPU kernels to rapidly decompile large files, a decryption suite, and network monitor for packet to binary reverse engineering.

Add new crates: ghidrust-decode, ghidrust-ir, and ghidrust-lift; update Cargo.toml and Cargo.lock. Refactor disassembly logic to use ghidrust-decode. Enhance documentation on dependency policies and GPU decompilation stages.

oofz5dd869dc33c5
diff --git a/Cargo.lock b/Cargo.lock
index 1c2816d..a7c7d76 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1328,6 +1328,7 @@ version = "0.1.0"
dependencies = [
"bincode",
"bytemuck",
+ "ghidrust-decode",
"pollster",
"rayon",
"serde",
@@ -1335,6 +1336,13 @@ dependencies = [
"wgpu",
]
+[[package]]
+name = "ghidrust-decode"
+version = "0.1.0"
+dependencies = [
+ "serde",
+]
+
[[package]]
name = "ghidrust-decomp"
version = "0.1.0"
@@ -1353,9 +1361,25 @@ dependencies = [
"eframe",
"egui",
"ghidrust-core",
+ "ghidrust-decomp",
"rfd",
]
+[[package]]
+name = "ghidrust-ir"
+version = "0.1.0"
+dependencies = [
+ "serde",
+]
+
+[[package]]
+name = "ghidrust-lift"
+version = "0.1.0"
+dependencies = [
+ "ghidrust-decode",
+ "ghidrust-ir",
+]
+
[[package]]
name = "gl_generator"
version = "0.14.0"
diff --git a/Cargo.toml b/Cargo.toml
index 632baab..bd45c66 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,6 +1,9 @@
[workspace]
resolver = "2"
members = [
+ "crates/ghidrust-ir",
+ "crates/ghidrust-decode",
+ "crates/ghidrust-lift",
"crates/ghidrust-core",
"crates/ghidrust-decomp",
"crates/ghidrust-cli",
@@ -15,5 +18,8 @@ license = "Apache-2.0"
repository = "https://github.com/example/ghidrust"
[workspace.dependencies]
+ghidrust-ir = { path = "crates/ghidrust-ir" }
+ghidrust-decode = { path = "crates/ghidrust-decode" }
+ghidrust-lift = { path = "crates/ghidrust-lift" }
ghidrust-core = { path = "crates/ghidrust-core" }
ghidrust-decomp = { path = "crates/ghidrust-decomp" }
diff --git a/DEPENDENCIES.md b/DEPENDENCIES.md
index da1e172..f215ff2 100644
--- a/DEPENDENCIES.md
+++ b/DEPENDENCIES.md
@@ -1,6 +1,22 @@
# Dependency policy
-**Prefer hand-rolled, task-specific Rust.** Analysis core (loaders, x86-64 decode, RTTI, all Auto Analysis implementations under `src/analyzers/*`, program model, MCP protocol framing) is written in-tree with no third-party analysis crates.
+**Prefer hand-rolled, task-specific Rust.** Analysis core (loaders, x86-64 decode, RTTI, all Auto Analysis implementations under `src/analyzers/*`, program model, MCP protocol framing, and the planned IR → SSA → structure → typed-C pipeline) is written in-tree with no third-party analysis crates at **runtime**.
+
+## Hand-rolled targets (analysis IP)
+
+These stay in-tree (existing or planned crates). Do **not** take iced-x86, Zydis, Capstone, goblin, rsleigh, hexray, fission, or analyssa as runtime dependencies for decode / lift / SSA / decomp:
+
+| Area | Role |
+|------|------|
+| Loaders, program model, analyzers | Already in `ghidrust-core` |
+| x86-64 decode / lift | Hand-rolled (expand toward `ghidrust-decode` / `ghidrust-lift`) |
+| **`ghidrust-ir`** | Architecture-neutral pcode-like ops, varnodes, address spaces, blocks |
+| **`ghidrust-ssa`** | CFG → SSA, phi, copy-prop, DCE, constant folding |
+| **`ghidrust-types`** | Data type manager, lattice, local/param recovery |
+| **`ghidrust-structure`** | Region structuring (if/else, loops, switch) |
+| **`ghidrust-decomp`** | Pipeline orchestration + emit (Stage-0 CFG→pseudo-C today; SSA/typed C later) |
+
+Open-source RE sources (Ghidra Decompiler / SLEIGH, iced-x86, academic papers) may be **read as reference** only; logic is reimplemented here.
## Allowed third-party
@@ -8,19 +24,27 @@
|-------|-----|
| **egui / eframe** (and their transitive deps) | Interactive CodeBrowser shell with Material 3–inspired Dark/Light chrome (not a full Material library). |
| **serde / serde_json** | Minimal JSON for CLI `--json` and MCP JSON-RPC framing (stdio agent protocol). |
-| **rayon** | Work-stealing CPU pool for bulk RE scans (strings / patterns / entropy windows). |
+| **rayon** | Work-stealing CPU pool for bulk RE scans and parallel analyze/decomp. |
| **bincode** | Fast binary analysis persistence (`analysis.bin`) — multi-100MB pretty JSON is not viable for UI reopen. |
-| **ghidrust-decomp** (workspace crate) | Hand-rolled decompile method (blocks/CFG → pseudo-C); not a third-party decompiler product. |
-| **wgpu / pollster / bytemuck** (optional, feature `gpu`) | Experimental GPU compute bulk printable-mark kernel; auto CPU fallback without adapter. |
+| **ghidrust-decomp** (workspace crate) | Hand-rolled decompile method (Stage-0 blocks/CFG → pseudo-C; SSA pipeline planned in-tree); not a third-party decompiler product. |
+| **wgpu / pollster / bytemuck** (optional, feature `gpu`) | Experimental GPU compute bulk printable-mark kernel and Stage-0 VRAM multipass; auto CPU fallback without adapter. |
+
+## Dev-only differential oracles (CI / tests — not runtime)
+
+| Tool / crate | Allowed use | Not allowed |
+|--------------|-------------|-------------|
+| **iced-x86** (or Zydis) | Length-disasm / decode **differential tests** as an external oracle in CI or `dev-dependencies` | Linking into production decode, lift, GUI, CLI, or MCP runtime paths |
+
+Same rule for any other mature decoder used only to cross-check edge cases against the hand-rolled decoder.
## Not used (on purpose)
- `goblin`, `object`, `pelite`, `scroll` — PE/ELF parsed by hand in `ghidrust-core`.
-- `iced-x86`, `zydis`, `capstone` bindings — x86-64 decode hand-rolled for the MVP slice.
+- `iced-x86`, `zydis`, `capstone` bindings — **not** runtime decode; see CI oracle exception above.
- Full `rmcp` / heavy MCP SDKs — thin hand-rolled tools/list + tools/call over stdio.
## Supply chain
- UI stack is the only large external surface; pin versions in workspace/crate `Cargo.toml`.
- No `unsafe` required in analysis paths for the MVP fixture set.
-- Open-source RE crates may be **read as reference** only; logic is reimplemented here so this remains a contributable foundation.
+- Owning IR layout keeps the “faster than Ghidra JVM” thesis possible (cache-friendly SoA, no JNI/bridge tax) without ceding the analysis moat to a third-party lifter/SSA crate.
diff --git a/README.md b/README.md
index 43d6cb0..dab36e0 100644
--- a/README.md
+++ b/README.md
@@ -12,13 +12,14 @@ It is **not** a Ghidra fork or wrapper. Analysis logic (loaders, decode, analyze
| Goal | Meaning in practice |
|------|---------------------|
-| **Ghidra-shaped workflow** | Familiar labels and surfaces (Auto Analysis names, project import/analyze/export, listing + decompile) without depending on the Ghidra JVM stack |
-| **Hand-rolled core** | PE/ELF, x86-64 decode, RTTI, analyzers, and decompile implemented in Rust — third-party RE libraries are avoided on purpose ([DEPENDENCIES.md](DEPENDENCIES.md)) |
+| **Surpass Ghidra (measurable)** | On x86-64 PE/ELF: faster Auto Analysis + decompile-all wall clock than Ghidra headless on the same machine/binary; ≥ Ghidra F1 on function discovery; structured typed C (not mnemonic scaffolding); differential correctness vs Ghidra on a fixed corpus — **target**, not a claim of today’s quality |
+| **Ghidra-shaped workflow** | Familiar labels and surfaces (Auto Analysis names, project import/analyze/export, listing + click FUN → decompile) without depending on the Ghidra JVM stack |
+| **Hand-rolled core** | PE/ELF, x86-64 decode, RTTI, analyzers, and the IR → SSA → structure → typed-C pipeline implemented in Rust — third-party RE libraries are avoided at runtime ([DEPENDENCIES.md](DEPENDENCIES.md)); Ghidra sources are reference-only |
| **CPU-correct first** | CPU paths are the oracle; optional GPU paths must match or enrich them, not replace honesty with speed claims |
| **Agent-ready** | Headless CLI + stdio MCP so coding agents can load, disassemble, analyze, and decompile without a GUI |
| **Practical projects** | Create a workspace, import binaries, run analyzers, persist results (`analysis.bin`), reopen later |
-**Non-goals (today):** full Ghidra/Hex-Rays parity, multi-ISA SLEIGH, debugger integration, or “GPU is always faster.”
+**Current maturity (Stage-0):** decompile emit is still CFG → goto / mnemonic-style **pseudo-C**. SSA, structuring, and typed C are the roadmap; Hex-Rays-class expression/type quality is a later phase after the Ghidra bar is met. **Non-goals (today):** multi-ISA SLEIGH runtime, debugger integration, or “GPU is always faster.”
---
@@ -336,7 +337,7 @@ You should not need to type JSON by hand day-to-day — the IDE/agent does that
| Crate | Role |
|-------|------|
| `ghidrust-core` | PE/ELF, x86-64, analyzers, projects, bulk scan |
-| `ghidrust-decomp` | Hand-rolled decompile (CPU + experimental GPU) |
+| `ghidrust-decomp` | Hand-rolled decompile: Stage-0 CFG→pseudo-C today (+ experimental GPU); SSA/typed C planned in-tree |
| `ghidrust-cli` | CLI + MCP + benches / `gpu-decompile` |
| `ghidrust-gui` | CodeBrowser-style UI |
diff --git a/crates/ghidrust-core/Cargo.toml b/crates/ghidrust-core/Cargo.toml
index c8984e9..929122a 100644
--- a/crates/ghidrust-core/Cargo.toml
+++ b/crates/ghidrust-core/Cargo.toml
@@ -11,6 +11,7 @@ default = []
gpu = ["wgpu", "pollster", "bytemuck"]
[dependencies]
+ghidrust-decode = { workspace = true }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
rayon = "1"
diff --git a/crates/ghidrust-core/src/disasm.rs b/crates/ghidrust-core/src/disasm.rs
index 8edcc4a..7a9a0b3 100644
--- a/crates/ghidrust-core/src/disasm.rs
+++ b/crates/ghidrust-core/src/disasm.rs
@@ -1,660 +1,17 @@
-//! Minimal x86-64 decoder slice (hand-rolled). Enough for common prologue / fixture bytes.
+//! Program-aware disassembly wrappers over [`ghidrust_decode`].
+//!
+//! Pure byte decode lives in `ghidrust-decode`; this module reads from
+//! [`crate::program::Program`] and maps errors into [`crate::Error`].
use crate::error::{Error, Result};
use crate::program::Program;
-use serde::{Deserialize, Serialize};
-
-#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
-pub struct Instruction {
- pub address: u64,
- pub bytes: Vec<u8>,
- pub mnemonic: String,
- pub operands: String,
- pub length: u8,
-}
-
-impl Instruction {
- pub fn text(&self) -> String {
- let hex = format!("{:24}", hex_bytes(&self.bytes));
- if self.operands.is_empty() {
- format!("{:016x}: {} {}", self.address, hex, self.mnemonic)
- } else {
- format!(
- "{:016x}: {} {} {}",
- self.address, hex, self.mnemonic, self.operands
- )
- }
- }
-}
-
-fn hex_bytes(b: &[u8]) -> String {
- b.iter()
- .map(|x| format!("{x:02x}"))
- .collect::<Vec<_>>()
- .join(" ")
-}
-
-const REGS64: [&str; 16] = [
- "rax", "rcx", "rdx", "rbx", "rsp", "rbp", "rsi", "rdi", "r8", "r9", "r10", "r11", "r12", "r13",
- "r14", "r15",
-];
-const REGS32: [&str; 16] = [
- "eax", "ecx", "edx", "ebx", "esp", "ebp", "esi", "edi", "r8d", "r9d", "r10d", "r11d", "r12d",
- "r13d", "r14d", "r15d",
-];
-const REGS16: [&str; 16] = [
- "ax", "cx", "dx", "bx", "sp", "bp", "si", "di", "r8w", "r9w", "r10w", "r11w", "r12w", "r13w",
- "r14w", "r15w",
-];
-const REGS8: [&str; 16] = [
- "al", "cl", "dl", "bl", "spl", "bpl", "sil", "dil", "r8b", "r9b", "r10b", "r11b", "r12b",
- "r13b", "r14b", "r15b",
-];
-
-#[derive(Clone, Copy, Default)]
-struct Prefix {
- rex_w: bool,
- rex_r: bool,
- rex_x: bool,
- rex_b: bool,
- has_rex: bool,
- op_size: bool, // 0x66
- addr_size: bool, // 0x67
- rep: bool,
- repne: bool,
- lock: bool,
- seg: Option<&'static str>,
-}
-
-fn reg_name(idx: u8, w: bool, op16: bool, byte_op: bool) -> &'static str {
- let i = (idx & 0xf) as usize;
- if byte_op {
- REGS8[i]
- } else if op16 {
- REGS16[i]
- } else if w {
- REGS64[i]
- } else {
- REGS32[i]
- }
-}
-
-struct Cursor<'a> {
- data: &'a [u8],
- pos: usize,
- start: usize,
-}
-
-impl<'a> Cursor<'a> {
- fn new(data: &'a [u8]) -> Self {
- Self {
- data,
- pos: 0,
- start: 0,
- }
- }
- fn remaining(&self) -> usize {
- self.data.len().saturating_sub(self.pos)
- }
- fn get(&mut self) -> Result<u8> {
- if self.pos >= self.data.len() {
- return Err(Error::Decode("truncated instruction stream".into()));
- }
- let b = self.data[self.pos];
- self.pos += 1;
- Ok(b)
- }
- fn peek(&self) -> Result<u8> {
- self.data
- .get(self.pos)
- .copied()
- .ok_or_else(|| Error::Decode("truncated".into()))
- }
- fn take_imm(&mut self, n: usize) -> Result<u64> {
- if self.remaining() < n {
- return Err(Error::Decode("imm truncated".into()));
- }
- let mut v = 0u64;
- for i in 0..n {
- v |= (self.data[self.pos + i] as u64) << (8 * i);
- }
- self.pos += n;
- Ok(v)
- }
- fn bytes_taken(&self) -> &[u8] {
- &self.data[self.start..self.pos]
- }
-}
-
-fn sign_hex(v: i64) -> String {
- if v < 0 {
- format!("-{:#x}", -v)
- } else {
- format!("{v:#x}")
- }
-}
-
-fn decode_modrm_mem(
- cur: &mut Cursor<'_>,
- modrm: u8,
- pfx: Prefix,
- byte_op: bool,
-) -> Result<(u8, String)> {
- let mod_ = modrm >> 6;
- let reg = ((modrm >> 3) & 7) | if pfx.rex_r { 8 } else { 0 };
- let rm = (modrm & 7) | if pfx.rex_b { 8 } else { 0 };
- let op16 = pfx.op_size && !pfx.rex_w;
-
- if mod_ == 3 {
- let name = if byte_op {
- reg_name(rm, false, false, true)
- } else if pfx.rex_w {
- reg_name(rm, true, false, false)
- } else if op16 {
- reg_name(rm, false, true, false)
- } else {
- reg_name(rm, false, false, false)
- };
- return Ok((reg, name.to_string()));
- }
-
- // SIB if rm low 3 bits == 4 (without rex_b folded for encoding check)
- let rm_enc = modrm & 7;
- let mut parts = String::new();
- if rm_enc == 4 {
- let sib = cur.get()?;
- let scale = 1u32 << (sib >> 6);
- let index = ((sib >> 3) & 7) | if pfx.rex_x { 8 } else { 0 };
- let base = (sib & 7) | if pfx.rex_b { 8 } else { 0 };
- let mut terms = Vec::new();
- if !(mod_ == 0 && (sib & 7) == 5) {
- terms.push(REGS64[base as usize].to_string());
- }
- if index != 4 {
- if scale == 1 {
- terms.push(REGS64[index as usize].to_string());
- } else {
- terms.push(format!("{}*{}", REGS64[index as usize], scale));
- }
- }
- let disp = match mod_ {
- 0 if (sib & 7) == 5 => Some(cur.take_imm(4)? as i32 as i64),
- 1 => Some(cur.take_imm(1)? as i8 as i64),
- 2 => Some(cur.take_imm(4)? as i32 as i64),
- _ => None,
- };
- if let Some(d) = disp {
- if d != 0 || terms.is_empty() {
- parts = if terms.is_empty() {
- format!("[{}]", sign_hex(d))
- } else {
- format!(
- "[{}{}{}]",
- terms.join("+"),
- if d < 0 { "" } else { "+" },
- sign_hex(d)
- )
- };
- } else {
- parts = format!("[{}]", terms.join("+"));
- }
- } else {
- parts = format!("[{}]", terms.join("+"));
- }
- } else if mod_ == 0 && rm_enc == 5 {
- // RIP-relative
- let disp = cur.take_imm(4)? as i32 as i64;
- parts = format!("[rip+{}]", sign_hex(disp));
- } else {
- let base = REGS64[rm as usize];
- match mod_ {
- 0 => parts = format!("[{base}]"),
- 1 => {
- let d = cur.take_imm(1)? as i8 as i64;
- parts = format!(
- "[{base}{}{}]",
- if d < 0 { "" } else { "+" },
- sign_hex(d)
- );
- }
- 2 => {
- let d = cur.take_imm(4)? as i32 as i64;
- parts = format!(
- "[{base}{}{}]",
- if d < 0 { "" } else { "+" },
- sign_hex(d)
- );
- }
- _ => {}
- }
- }
- if let Some(seg) = pfx.seg {
- parts = format!("{seg}:{parts}");
- }
- Ok((reg, parts))
-}
-
-/// Decode one instruction from raw bytes at `address` (VA for display only).
-pub fn decode_one(bytes: &[u8], address: u64) -> Result<Instruction> {
- if bytes.is_empty() {
- return Err(Error::Decode("empty".into()));
- }
- let mut cur = Cursor::new(bytes);
- let mut pfx = Prefix::default();
-
- // prefixes
- loop {
- let b = cur.peek()?;
- match b {
- 0xF0 => {
- cur.get()?;
- pfx.lock = true;
- }
- 0xF2 => {
- cur.get()?;
- pfx.repne = true;
- }
- 0xF3 => {
- cur.get()?;
- pfx.rep = true;
- }
- 0x2E => {
- cur.get()?;
- pfx.seg = Some("cs");
- }
- 0x36 => {
- cur.get()?;
- pfx.seg = Some("ss");
- }
- 0x3E => {
- cur.get()?;
- pfx.seg = Some("ds");
- }
- 0x26 => {
- cur.get()?;
- pfx.seg = Some("es");
- }
- 0x64 => {
- cur.get()?;
- pfx.seg = Some("fs");
- }
- 0x65 => {
- cur.get()?;
- pfx.seg = Some("gs");
- }
- 0x66 => {
- cur.get()?;
- pfx.op_size = true;
- }
- 0x67 => {
- cur.get()?;
- pfx.addr_size = true;
- }
- x if x & 0xf0 == 0x40 => {
- let rex = cur.get()?;
- pfx.has_rex = true;
- pfx.rex_w = rex & 0x8 != 0;
- pfx.rex_r = rex & 0x4 != 0;
- pfx.rex_x = rex & 0x2 != 0;
- pfx.rex_b = rex & 0x1 != 0;
- }
- _ => break,
- }
- if cur.pos > 15 {
- return Err(Error::Decode("too many prefixes".into()));
- }
- }
-
- let op = cur.get()?;
- let w64 = pfx.rex_w;
- let op16 = pfx.op_size && !pfx.rex_w;
-
- let (mnemonic, operands) = match op {
- // PUSH r64: 50+rd
- 0x50..=0x57 => {
- let r = (op - 0x50) | if pfx.rex_b { 8 } else { 0 };
- ("push".into(), REGS64[r as usize].to_string())
- }
- // POP r64
- 0x58..=0x5F => {
- let r = (op - 0x58) | if pfx.rex_b { 8 } else { 0 };
- ("pop".into(), REGS64[r as usize].to_string())
- }
- // MOV r/m, r
- 0x89 => {
- let modrm = cur.get()?;
- let (reg, rm) = decode_modrm_mem(&mut cur, modrm, pfx, false)?;
- let reg_s = if w64 {
- reg_name(reg, true, false, false)
- } else if op16 {
- reg_name(reg, false, true, false)
- } else {
- reg_name(reg, false, false, false)
- };
- ("mov".into(), format!("{rm}, {reg_s}"))
- }
- // MOV r, r/m
- 0x8B => {
- let modrm = cur.get()?;
- let (reg, rm) = decode_modrm_mem(&mut cur, modrm, pfx, false)?;
- let reg_s = if w64 {
- reg_name(reg, true, false, false)
- } else if op16 {
- reg_name(reg, false, true, false)
- } else {
- reg_name(reg, false, false, false)
- };
- ("mov".into(), format!("{reg_s}, {rm}"))
- }
- // MOV r/m8, r8
- 0x88 => {
- let modrm = cur.get()?;
- let (reg, rm) = decode_modrm_mem(&mut cur, modrm, pfx, true)?;
- ("mov".into(), format!("{rm}, {}", reg_name(reg, false, false, true)))
- }
- // MOV r8, r/m8
- 0x8A => {
- let modrm = cur.get()?;
- let (reg, rm) = decode_modrm_mem(&mut cur, modrm, pfx, true)?;
- ("mov".into(), format!("{}, {rm}", reg_name(reg, false, false, true)))
- }
- // MOV r/m, imm32 (C7 /0)
- 0xC7 => {
- let modrm = cur.get()?;
- let reg_field = (modrm >> 3) & 7;
- if reg_field != 0 {
- return Err(Error::Decode(format!("unhandled C7 /{reg_field}")));
- }
- let (_reg, rm) = decode_modrm_mem(&mut cur, modrm, pfx, false)?;
- let imm = if w64 {
- // C7 still uses 32-bit imm sign-extended
- cur.take_imm(4)? as i32 as i64
- } else if op16 {
- cur.take_imm(2)? as i16 as i64
- } else {
- cur.take_imm(4)? as i32 as i64
- };
- ("mov".into(), format!("{rm}, {imm:#x}"))
- }
- // MOV r64/r32, imm
- 0xB8..=0xBF => {
- let r = (op - 0xB8) | if pfx.rex_b { 8 } else { 0 };
- if w64 {
- let imm = cur.take_imm(8)?;
- (
- "mov".into(),
- format!("{}, {imm:#x}", reg_name(r, true, false, false)),
- )
- } else if op16 {
- let imm = cur.take_imm(2)?;
- (
- "mov".into(),
- format!("{}, {imm:#x}", reg_name(r, false, true, false)),
- )
- } else {
- let imm = cur.take_imm(4)?;
- (
- "mov".into(),
- format!("{}, {imm:#x}", reg_name(r, false, false, false)),
- )
- }
- }
- // MOV r8, imm8
- 0xB0..=0xB7 => {
- let r = (op - 0xB0) | if pfx.rex_b { 8 } else { 0 };
- let imm = cur.take_imm(1)?;
- (
- "mov".into(),
- format!("{}, {imm:#x}", reg_name(r, false, false, true)),
- )
- }
- // LEA r, m
- 0x8D => {
- let modrm = cur.get()?;
- let (reg, rm) = decode_modrm_mem(&mut cur, modrm, pfx, false)?;
- let reg_s = if w64 {
- reg_name(reg, true, false, false)
- } else if op16 {
- reg_name(reg, false, true, false)
- } else {
- reg_name(reg, false, false, false)
- };
- ("lea".into(), format!("{reg_s}, {rm}"))
- }
- // ADD/OR/ADC/SBB/AND/SUB/XOR/CMP r/m, r (01 family)
- 0x01 | 0x09 | 0x11 | 0x19 | 0x21 | 0x29 | 0x31 | 0x39 => {
- let mnem = match op {
- 0x01 => "add",
- 0x09 => "or",
- 0x11 => "adc",
- 0x19 => "sbb",
- 0x21 => "and",
- 0x29 => "sub",
- 0x31 => "xor",
- 0x39 => "cmp",
- _ => unreachable!(),
- };
- let modrm = cur.get()?;
- let (reg, rm) = decode_modrm_mem(&mut cur, modrm, pfx, false)?;
- let reg_s = if w64 {
- reg_name(reg, true, false, false)
- } else if op16 {
- reg_name(reg, false, true, false)
- } else {
- reg_name(reg, false, false, false)
- };
- (mnem.into(), format!("{rm}, {reg_s}"))
- }
- // same r, r/m
- 0x03 | 0x0B | 0x13 | 0x1B | 0x23 | 0x2B | 0x33 | 0x3B => {
- let mnem = match op {
- 0x03 => "add",
- 0x0B => "or",
- 0x13 => "adc",
- 0x1B => "sbb",
- 0x23 => "and",
- 0x2B => "sub",
- 0x33 => "xor",
- 0x3B => "cmp",
- _ => unreachable!(),
- };
- let modrm = cur.get()?;
- let (reg, rm) = decode_modrm_mem(&mut cur, modrm, pfx, false)?;
- let reg_s = if w64 {
- reg_name(reg, true, false, false)
- } else if op16 {
- reg_name(reg, false, true, false)
- } else {
- reg_name(reg, false, false, false)
- };
- (mnem.into(), format!("{reg_s}, {rm}"))
- }
- // XOR r/m8,r8 etc skip; XOR r32,r/m already covered
- // TEST
- 0x85 => {
- let modrm = cur.get()?;
- let (reg, rm) = decode_modrm_mem(&mut cur, modrm, pfx, false)?;
- let reg_s = if w64 {
- reg_name(reg, true, false, false)
- } else {
- reg_name(reg, false, op16, false)
- };
- ("test".into(), format!("{rm}, {reg_s}"))
- }
- // NOP
- 0x90 => ("nop".into(), String::new()),
- // RET
- 0xC3 => ("ret".into(), String::new()),
- 0xC2 => {
- let imm = cur.take_imm(2)?;
- ("ret".into(), format!("{imm:#x}"))
- }
- // CALL rel32
- 0xE8 => {
- let rel = cur.take_imm(4)? as i32 as i64;
- let target = address
- .wrapping_add(cur.pos as u64)
- .wrapping_add(rel as u64);
- ("call".into(), format!("{target:#x}"))
- }
- // JMP rel32
- 0xE9 => {
- let rel = cur.take_imm(4)? as i32 as i64;
- let target = address
- .wrapping_add(cur.pos as u64)
- .wrapping_add(rel as u64);
- ("jmp".into(), format!("{target:#x}"))
- }
- // JMP rel8
- 0xEB => {
- let rel = cur.take_imm(1)? as i8 as i64;
- let target = address
- .wrapping_add(cur.pos as u64)
- .wrapping_add(rel as u64);
- ("jmp".into(), format!("{target:#x}"))
- }
- // Jcc rel8
- 0x70..=0x7F => {
- let names = [
- "jo", "jno", "jb", "jae", "je", "jne", "jbe", "ja", "js", "jns", "jp", "jnp",
- "jl", "jge", "jle", "jg",
- ];
- let rel = cur.take_imm(1)? as i8 as i64;
- let target = address
- .wrapping_add(cur.pos as u64)
- .wrapping_add(rel as u64);
- (names[(op - 0x70) as usize].into(), format!("{target:#x}"))
- }
- // INT3
- 0xCC => ("int3".into(), String::new()),
- // CDQ / CQO
- 0x99 => {
- if w64 {
- ("cqo".into(), String::new())
- } else {
- ("cdq".into(), String::new())
- }
- }
- // LEAVE
- 0xC9 => ("leave".into(), String::new()),
- // SUB/ADD r/m, imm8 (83 /x)
- 0x83 => {
- let modrm = cur.get()?;
- let reg_field = (modrm >> 3) & 7;
- let mnem = match reg_field {
- 0 => "add",
- 1 => "or",
- 2 => "adc",
- 3 => "sbb",
- 4 => "and",
- 5 => "sub",
- 6 => "xor",
- 7 => "cmp",
- _ => "grp",
- };
- let (_reg, rm) = decode_modrm_mem(&mut cur, modrm, pfx, false)?;
- let imm = cur.take_imm(1)? as i8 as i64;
- (mnem.into(), format!("{rm}, {imm:#x}"))
- }
- // group 81 r/m, imm32
- 0x81 => {
- let modrm = cur.get()?;
- let reg_field = (modrm >> 3) & 7;
- let mnem = match reg_field {
- 0 => "add",
- 1 => "or",
- 2 => "adc",
- 3 => "sbb",
- 4 => "and",
- 5 => "sub",
- 6 => "xor",
- 7 => "cmp",
- _ => "grp",
- };
- let (_reg, rm) = decode_modrm_mem(&mut cur, modrm, pfx, false)?;
- let imm = if op16 {
- cur.take_imm(2)? as i16 as i64
- } else {
- cur.take_imm(4)? as i32 as i64
- };
- (mnem.into(), format!("{rm}, {imm:#x}"))
- }
- // two-byte 0F
- 0x0F => {
- let op2 = cur.get()?;
- match op2 {
- // Jcc rel32
- 0x80..=0x8F => {
- let names = [
- "jo", "jno", "jb", "jae", "je", "jne", "jbe", "ja", "js", "jns", "jp",
- "jnp", "jl", "jge", "jle", "jg",
- ];
- let rel = cur.take_imm(4)? as i32 as i64;
- let target = address
- .wrapping_add(cur.pos as u64)
- .wrapping_add(rel as u64);
- (names[(op2 - 0x80) as usize].into(), format!("{target:#x}"))
- }
- 0x1F => {
- // NOP r/m
- let modrm = cur.get()?;
- let (_r, rm) = decode_modrm_mem(&mut cur, modrm, pfx, false)?;
- ("nop".into(), rm)
- }
- 0x05 => ("syscall".into(), String::new()),
- 0xA2 => ("cpuid".into(), String::new()),
- _ => {
- return Err(Error::Decode(format!("unhandled 0F {op2:02x}")));
- }
- }
- }
- // FF /2 CALL, /4 JMP
- 0xFF => {
- let modrm = cur.get()?;
- let reg_field = (modrm >> 3) & 7;
- let (_r, rm) = decode_modrm_mem(&mut cur, modrm, pfx, false)?;
- match reg_field {
- 2 => ("call".into(), rm),
- 4 => ("jmp".into(), rm),
- 6 => ("push".into(), rm),
- _ => {
- return Err(Error::Decode(format!("unhandled FF /{reg_field}")));
- }
- }
- }
- // XOR r8,r8 style short: 31 already; also 30
- 0x30 | 0x32 => {
- let modrm = cur.get()?;
- let (reg, rm) = decode_modrm_mem(&mut cur, modrm, pfx, true)?;
- let mnem = if op == 0x30 { "xor" } else { "xor" };
- if op == 0x30 {
- (mnem.into(), format!("{rm}, {}", reg_name(reg, false, false, true)))
- } else {
- (mnem.into(), format!("{}, {rm}", reg_name(reg, false, false, true)))
- }
- }
- other => {
- return Err(Error::Decode(format!(
- "unhandled opcode {other:02x} at {address:#x}"
- )));
- }
- };
-
- let taken = cur.bytes_taken().to_vec();
- Ok(Instruction {
- address,
- length: taken.len() as u8,
- bytes: taken,
- mnemonic,
- operands,
- })
-}
+pub use ghidrust_decode::{decode_one, Instruction};
pub fn disassemble_at(prog: &Program, va: u64) -> Result<Instruction> {
let bytes = prog
.read_va(va, 15)
.ok_or_else(|| Error::OutOfBounds(format!("no bytes at {va:#x}")))?;
- decode_one(&bytes, va)
+ Ok(decode_one(&bytes, va)?)
}
pub fn disassemble_range(prog: &Program, start: u64, max_insns: usize) -> Result<Vec<Instruction>> {
@@ -682,8 +39,6 @@ mod tests {
#[test]
fn decode_push_rbp_mov_rbp_rsp() {
- // 55 push rbp
- // 48 89 e5 mov rbp, rsp
let b = [0x55, 0x48, 0x89, 0xe5];
let i0 = decode_one(&b, 0x1000).unwrap();
assert_eq!(i0.mnemonic, "push");
@@ -696,8 +51,6 @@ mod tests {
#[test]
fn decode_xor_eax_eax_ret() {
- // 31 c0 xor eax, eax
- // c3 ret
let b = [0x31, 0xc0, 0xc3];
let i0 = decode_one(&b, 0).unwrap();
assert_eq!(i0.mnemonic, "xor");
diff --git a/crates/ghidrust-core/src/error.rs b/crates/ghidrust-core/src/error.rs
index 3ee5f48..98b3b4c 100644
--- a/crates/ghidrust-core/src/error.rs
+++ b/crates/ghidrust-core/src/error.rs
@@ -23,4 +23,12 @@ impl fmt::Display for Error {
impl std::error::Error for Error {}
+impl From<ghidrust_decode::Error> for Error {
+ fn from(e: ghidrust_decode::Error) -> Self {
+ match e {
+ ghidrust_decode::Error::Decode(m) => Error::Decode(m),
+ }
+ }
+}
+
pub type Result<T> = std::result::Result<T, Error>;
diff --git a/crates/ghidrust-core/src/lib.rs b/crates/ghidrust-core/src/lib.rs
index 4ff5692..2477b0e 100644
--- a/crates/ghidrust-core/src/lib.rs
+++ b/crates/ghidrust-core/src/lib.rs
@@ -27,7 +27,7 @@ pub use gpu_analyzers::{
gpu_enrich_analyzers, merge_seeds_into_program, pad_large, seeds_equal, strategy_matrix,
AnalyzerBenchRow, GpuStrategyClass,
};
-pub use disasm::{disassemble_at, disassemble_range, Instruction};
+pub use disasm::{decode_one, disassemble_at, disassemble_range, Instruction};
pub use error::{Error, Result};
pub use program::{
AddressTableInfo, AnalysisState, CallFixupInfo, DiscoveredRange, FidMatch, FunctionInfo,
diff --git a/crates/ghidrust-decode/Cargo.toml b/crates/ghidrust-decode/Cargo.toml
new file mode 100644
index 0000000..185393b
--- /dev/null
+++ b/crates/ghidrust-decode/Cargo.toml
@@ -0,0 +1,9 @@
+[package]
+name = "ghidrust-decode"
+version.workspace = true
+edition.workspace = true
+license.workspace = true
+description = "Hand-rolled x86-64 instruction decode (length-disasm + mnemonic)"
+
+[dependencies]
+serde = { version = "1", features = ["derive"] }
diff --git a/crates/ghidrust-decode/src/lib.rs b/crates/ghidrust-decode/src/lib.rs
new file mode 100644
index 0000000..ebb3892
--- /dev/null
+++ b/crates/ghidrust-decode/src/lib.rs
@@ -0,0 +1,76 @@
+//! Hand-rolled x86-64 instruction decode (no Capstone / iced-x86 / Zydis at runtime).
+//!
+//! Length-disassembly + mnemonic/operand strings for common prologue and fixture
+//! opcodes. Program-aware helpers (`disassemble_at` / `disassemble_range`) remain
+//! in `ghidrust-core` and call [`decode_one`] here.
+
+mod x86_64;
+
+pub use x86_64::{decode_one, Instruction};
+
+use std::fmt;
+
+/// Decode failure (truncated stream, unhandled opcode, …).
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum Error {
+ Decode(String),
+}
+
+impl fmt::Display for Error {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ match self {
+ Error::Decode(m) => write!(f, "decode: {m}"),
+ }
+ }
+}
+
+impl std::error::Error for Error {}
+
+pub type Result<T> = std::result::Result<T, Error>;
+
+/// Decode a linear byte slice into a sequence of instructions (stops on first error).
+pub fn decode_bytes(bytes: &[u8], start_address: u64, max_insns: usize) -> Result<Vec<Instruction>> {
+ let mut out = Vec::new();
+ let mut off = 0usize;
+ let mut va = start_address;
+ for _ in 0..max_insns {
+ if off >= bytes.len() {
+ break;
+ }
+ match decode_one(&bytes[off..], va) {
+ Ok(insn) => {
+ let len = insn.length as usize;
+ off += len;
+ va = va.wrapping_add(len as u64);
+ out.push(insn);
+ }
+ Err(e) => {
+ if out.is_empty() {
+ return Err(e);
+ }
+ break;
+ }
+ }
+ }
+ if out.is_empty() {
+ return Err(Error::Decode(format!(
+ "no instructions at {start_address:#x}"
+ )));
+ }
+ Ok(out)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn decode_bytes_prologue() {
+ let b = [0x55, 0x48, 0x89, 0xe5, 0xc3];
+ let insns = decode_bytes(&b, 0x1000, 8).unwrap();
+ assert_eq!(insns.len(), 3);
+ assert_eq!(insns[0].mnemonic, "push");
+ assert_eq!(insns[1].mnemonic, "mov");
+ assert_eq!(insns[2].mnemonic, "ret");
+ }
+}
diff --git a/crates/ghidrust-decode/src/x86_64.rs b/crates/ghidrust-decode/src/x86_64.rs
new file mode 100644
index 0000000..bcdd5de
--- /dev/null
+++ b/crates/ghidrust-decode/src/x86_64.rs
@@ -0,0 +1,681 @@
+//! Minimal x86-64 decoder slice (hand-rolled). Enough for common prologue / fixture bytes.
+
+use crate::{Error, Result};
+use serde::{Deserialize, Serialize};
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+pub struct Instruction {
+ pub address: u64,
+ pub bytes: Vec<u8>,
+ pub mnemonic: String,
+ pub operands: String,
+ pub length: u8,
+}
+
+impl Instruction {
+ pub fn text(&self) -> String {
+ let hex = format!("{:24}", hex_bytes(&self.bytes));
+ if self.operands.is_empty() {
+ format!("{:016x}: {} {}", self.address, hex, self.mnemonic)
+ } else {
+ format!(
+ "{:016x}: {} {} {}",
+ self.address, hex, self.mnemonic, self.operands
+ )
+ }
+ }
+}
+
+fn hex_bytes(b: &[u8]) -> String {
+ b.iter()
+ .map(|x| format!("{x:02x}"))
+ .collect::<Vec<_>>()
+ .join(" ")
+}
+
+const REGS64: [&str; 16] = [
+ "rax", "rcx", "rdx", "rbx", "rsp", "rbp", "rsi", "rdi", "r8", "r9", "r10", "r11", "r12", "r13",
+ "r14", "r15",
+];
+const REGS32: [&str; 16] = [
+ "eax", "ecx", "edx", "ebx", "esp", "ebp", "esi", "edi", "r8d", "r9d", "r10d", "r11d", "r12d",
+ "r13d", "r14d", "r15d",
+];
+const REGS16: [&str; 16] = [
+ "ax", "cx", "dx", "bx", "sp", "bp", "si", "di", "r8w", "r9w", "r10w", "r11w", "r12w", "r13w",
+ "r14w", "r15w",
+];
+const REGS8: [&str; 16] = [
+ "al", "cl", "dl", "bl", "spl", "bpl", "sil", "dil", "r8b", "r9b", "r10b", "r11b", "r12b",
+ "r13b", "r14b", "r15b",
+];
+
+#[derive(Clone, Copy, Default)]
+struct Prefix {
+ rex_w: bool,
+ rex_r: bool,
+ rex_x: bool,
+ rex_b: bool,
+ has_rex: bool,
+ op_size: bool, // 0x66
+ addr_size: bool, // 0x67
+ rep: bool,
+ repne: bool,
+ lock: bool,
+ seg: Option<&'static str>,
+}
+
+fn reg_name(idx: u8, w: bool, op16: bool, byte_op: bool) -> &'static str {
+ let i = (idx & 0xf) as usize;
+ if byte_op {
+ REGS8[i]
+ } else if op16 {
+ REGS16[i]
+ } else if w {
+ REGS64[i]
+ } else {
+ REGS32[i]
+ }
+}
+
+struct Cursor<'a> {
+ data: &'a [u8],
+ pos: usize,
+ start: usize,
+}
+
+impl<'a> Cursor<'a> {
+ fn new(data: &'a [u8]) -> Self {
+ Self {
+ data,
+ pos: 0,
+ start: 0,
+ }
+ }
+ fn remaining(&self) -> usize {
+ self.data.len().saturating_sub(self.pos)
+ }
+ fn get(&mut self) -> Result<u8> {
+ if self.pos >= self.data.len() {
+ return Err(Error::Decode("truncated instruction stream".into()));
+ }
+ let b = self.data[self.pos];
+ self.pos += 1;
+ Ok(b)
+ }
+ fn peek(&self) -> Result<u8> {
+ self.data
+ .get(self.pos)
+ .copied()
+ .ok_or_else(|| Error::Decode("truncated".into()))
+ }
+ fn take_imm(&mut self, n: usize) -> Result<u64> {
+ if self.remaining() < n {
+ return Err(Error::Decode("imm truncated".into()));
+ }
+ let mut v = 0u64;
+ for i in 0..n {
+ v |= (self.data[self.pos + i] as u64) << (8 * i);
+ }
+ self.pos += n;
+ Ok(v)
+ }
+ fn bytes_taken(&self) -> &[u8] {
+ &self.data[self.start..self.pos]
+ }
+}
+
+fn sign_hex(v: i64) -> String {
+ if v < 0 {
+ format!("-{:#x}", -v)
+ } else {
+ format!("{v:#x}")
+ }
+}
+
+fn decode_modrm_mem(
+ cur: &mut Cursor<'_>,
+ modrm: u8,
+ pfx: Prefix,
+ byte_op: bool,
+) -> Result<(u8, String)> {
+ let mod_ = modrm >> 6;
+ let reg = ((modrm >> 3) & 7) | if pfx.rex_r { 8 } else { 0 };
+ let rm = (modrm & 7) | if pfx.rex_b { 8 } else { 0 };
+ let op16 = pfx.op_size && !pfx.rex_w;
+
+ if mod_ == 3 {
+ let name = if byte_op {
+ reg_name(rm, false, false, true)
+ } else if pfx.rex_w {
+ reg_name(rm, true, false, false)
+ } else if op16 {
+ reg_name(rm, false, true, false)
+ } else {
+ reg_name(rm, false, false, false)
+ };
+ return Ok((reg, name.to_string()));
+ }
+
+ // SIB if rm low 3 bits == 4 (without rex_b folded for encoding check)
+ let rm_enc = modrm & 7;
+ let mut parts = String::new();
+ if rm_enc == 4 {
+ let sib = cur.get()?;
+ let scale = 1u32 << (sib >> 6);
+ let index = ((sib >> 3) & 7) | if pfx.rex_x { 8 } else { 0 };
+ let base = (sib & 7) | if pfx.rex_b { 8 } else { 0 };
+ let mut terms = Vec::new();
+ if !(mod_ == 0 && (sib & 7) == 5) {
+ terms.push(REGS64[base as usize].to_string());
+ }
+ if index != 4 {
+ if scale == 1 {
+ terms.push(REGS64[index as usize].to_string());
+ } else {
+ terms.push(format!("{}*{}", REGS64[index as usize], scale));
+ }
+ }
+ let disp = match mod_ {
+ 0 if (sib & 7) == 5 => Some(cur.take_imm(4)? as i32 as i64),
+ 1 => Some(cur.take_imm(1)? as i8 as i64),
+ 2 => Some(cur.take_imm(4)? as i32 as i64),
+ _ => None,
+ };
+ if let Some(d) = disp {
+ if d != 0 || terms.is_empty() {
+ parts = if terms.is_empty() {
+ format!("[{}]", sign_hex(d))
+ } else {
+ format!(
+ "[{}{}{}]",
+ terms.join("+"),
+ if d < 0 { "" } else { "+" },
+ sign_hex(d)
+ )
+ };
+ } else {
+ parts = format!("[{}]", terms.join("+"));
+ }
+ } else {
+ parts = format!("[{}]", terms.join("+"));
+ }
+ } else if mod_ == 0 && rm_enc == 5 {
+ // RIP-relative
+ let disp = cur.take_imm(4)? as i32 as i64;
+ parts = format!("[rip+{}]", sign_hex(disp));
+ } else {
+ let base = REGS64[rm as usize];
+ match mod_ {
+ 0 => parts = format!("[{base}]"),
+ 1 => {
+ let d = cur.take_imm(1)? as i8 as i64;
+ parts = format!(
+ "[{base}{}{}]",
+ if d < 0 { "" } else { "+" },
+ sign_hex(d)
+ );
+ }
+ 2 => {
+ let d = cur.take_imm(4)? as i32 as i64;
+ parts = format!(
+ "[{base}{}{}]",
+ if d < 0 { "" } else { "+" },
+ sign_hex(d)
+ );
+ }
+ _ => {}
+ }
+ }
+ if let Some(seg) = pfx.seg {
+ parts = format!("{seg}:{parts}");
+ }
+ Ok((reg, parts))
+}
+
+/// Decode one instruction from raw bytes at `address` (VA for display only).
+pub fn decode_one(bytes: &[u8], address: u64) -> Result<Instruction> {
+ if bytes.is_empty() {
+ return Err(Error::Decode("empty".into()));
+ }
+ let mut cur = Cursor::new(bytes);
+ let mut pfx = Prefix::default();
+
+ // prefixes
+ loop {
+ let b = cur.peek()?;
+ match b {
+ 0xF0 => {
+ cur.get()?;
+ pfx.lock = true;
+ }
+ 0xF2 => {
+ cur.get()?;
+ pfx.repne = true;
+ }
+ 0xF3 => {
+ cur.get()?;
+ pfx.rep = true;
+ }
+ 0x2E => {
+ cur.get()?;
+ pfx.seg = Some("cs");
+ }
+ 0x36 => {
+ cur.get()?;
+ pfx.seg = Some("ss");
+ }
+ 0x3E => {
+ cur.get()?;
+ pfx.seg = Some("ds");
+ }
+ 0x26 => {
+ cur.get()?;
+ pfx.seg = Some("es");
+ }
+ 0x64 => {
+ cur.get()?;
+ pfx.seg = Some("fs");
+ }
+ 0x65 => {
+ cur.get()?;
+ pfx.seg = Some("gs");
+ }
+ 0x66 => {
+ cur.get()?;
+ pfx.op_size = true;
+ }
+ 0x67 => {
+ cur.get()?;
+ pfx.addr_size = true;
+ }
+ x if x & 0xf0 == 0x40 => {
+ let rex = cur.get()?;
+ pfx.has_rex = true;
+ pfx.rex_w = rex & 0x8 != 0;
+ pfx.rex_r = rex & 0x4 != 0;
+ pfx.rex_x = rex & 0x2 != 0;
+ pfx.rex_b = rex & 0x1 != 0;
+ }
+ _ => break,
+ }
+ if cur.pos > 15 {
+ return Err(Error::Decode("too many prefixes".into()));
+ }
+ }
+
+ let op = cur.get()?;
+ let w64 = pfx.rex_w;
+ let op16 = pfx.op_size && !pfx.rex_w;
+
+ let (mnemonic, operands) = match op {
+ // PUSH r64: 50+rd
+ 0x50..=0x57 => {
+ let r = (op - 0x50) | if pfx.rex_b { 8 } else { 0 };
+ ("push".into(), REGS64[r as usize].to_string())
+ }
+ // POP r64
+ 0x58..=0x5F => {
+ let r = (op - 0x58) | if pfx.rex_b { 8 } else { 0 };
+ ("pop".into(), REGS64[r as usize].to_string())
+ }
+ // MOV r/m, r
+ 0x89 => {
+ let modrm = cur.get()?;
+ let (reg, rm) = decode_modrm_mem(&mut cur, modrm, pfx, false)?;
+ let reg_s = if w64 {
+ reg_name(reg, true, false, false)
+ } else if op16 {
+ reg_name(reg, false, true, false)
+ } else {
+ reg_name(reg, false, false, false)
+ };
+ ("mov".into(), format!("{rm}, {reg_s}"))
+ }
+ // MOV r, r/m
+ 0x8B => {
+ let modrm = cur.get()?;
+ let (reg, rm) = decode_modrm_mem(&mut cur, modrm, pfx, false)?;
+ let reg_s = if w64 {
+ reg_name(reg, true, false, false)
+ } else if op16 {
+ reg_name(reg, false, true, false)
+ } else {
+ reg_name(reg, false, false, false)
+ };
+ ("mov".into(), format!("{reg_s}, {rm}"))
+ }
+ // MOV r/m8, r8
+ 0x88 => {
+ let modrm = cur.get()?;
+ let (reg, rm) = decode_modrm_mem(&mut cur, modrm, pfx, true)?;
+ ("mov".into(), format!("{rm}, {}", reg_name(reg, false, false, true)))
+ }
+ // MOV r8, r/m8
+ 0x8A => {
+ let modrm = cur.get()?;
+ let (reg, rm) = decode_modrm_mem(&mut cur, modrm, pfx, true)?;
+ ("mov".into(), format!("{}, {rm}", reg_name(reg, false, false, true)))
+ }
+ // MOV r/m, imm32 (C7 /0)
+ 0xC7 => {
+ let modrm = cur.get()?;
+ let reg_field = (modrm >> 3) & 7;
+ if reg_field != 0 {
+ return Err(Error::Decode(format!("unhandled C7 /{reg_field}")));
+ }
+ let (_reg, rm) = decode_modrm_mem(&mut cur, modrm, pfx, false)?;
+ let imm = if w64 {
+ // C7 still uses 32-bit imm sign-extended
+ cur.take_imm(4)? as i32 as i64
+ } else if op16 {
+ cur.take_imm(2)? as i16 as i64
+ } else {
+ cur.take_imm(4)? as i32 as i64
+ };
+ ("mov".into(), format!("{rm}, {imm:#x}"))
+ }
+ // MOV r64/r32, imm
+ 0xB8..=0xBF => {
+ let r = (op - 0xB8) | if pfx.rex_b { 8 } else { 0 };
+ if w64 {
+ let imm = cur.take_imm(8)?;
+ (
+ "mov".into(),
+ format!("{}, {imm:#x}", reg_name(r, true, false, false)),
+ )
+ } else if op16 {
+ let imm = cur.take_imm(2)?;
+ (
+ "mov".into(),
+ format!("{}, {imm:#x}", reg_name(r, false, true, false)),
+ )
+ } else {
+ let imm = cur.take_imm(4)?;
+ (
+ "mov".into(),
+ format!("{}, {imm:#x}", reg_name(r, false, false, false)),
+ )
+ }
+ }
+ // MOV r8, imm8
+ 0xB0..=0xB7 => {
+ let r = (op - 0xB0) | if pfx.rex_b { 8 } else { 0 };
+ let imm = cur.take_imm(1)?;
+ (
+ "mov".into(),
+ format!("{}, {imm:#x}", reg_name(r, false, false, true)),
+ )
+ }
+ // LEA r, m
+ 0x8D => {
+ let modrm = cur.get()?;
+ let (reg, rm) = decode_modrm_mem(&mut cur, modrm, pfx, false)?;
+ let reg_s = if w64 {
+ reg_name(reg, true, false, false)
+ } else if op16 {
+ reg_name(reg, false, true, false)
+ } else {
+ reg_name(reg, false, false, false)
+ };
+ ("lea".into(), format!("{reg_s}, {rm}"))
+ }
+ // ADD/OR/ADC/SBB/AND/SUB/XOR/CMP r/m, r (01 family)
+ 0x01 | 0x09 | 0x11 | 0x19 | 0x21 | 0x29 | 0x31 | 0x39 => {
+ let mnem = match op {
+ 0x01 => "add",
+ 0x09 => "or",
+ 0x11 => "adc",
+ 0x19 => "sbb",
+ 0x21 => "and",
+ 0x29 => "sub",
+ 0x31 => "xor",
+ 0x39 => "cmp",
+ _ => unreachable!(),
+ };
+ let modrm = cur.get()?;
+ let (reg, rm) = decode_modrm_mem(&mut cur, modrm, pfx, false)?;
+ let reg_s = if w64 {
+ reg_name(reg, true, false, false)
+ } else if op16 {
+ reg_name(reg, false, true, false)
+ } else {
+ reg_name(reg, false, false, false)
+ };
+ (mnem.into(), format!("{rm}, {reg_s}"))
+ }
+ // same r, r/m
+ 0x03 | 0x0B | 0x13 | 0x1B | 0x23 | 0x2B | 0x33 | 0x3B => {
+ let mnem = match op {
+ 0x03 => "add",
+ 0x0B => "or",
+ 0x13 => "adc",
+ 0x1B => "sbb",
+ 0x23 => "and",
+ 0x2B => "sub",
+ 0x33 => "xor",
+ 0x3B => "cmp",
+ _ => unreachable!(),
+ };
+ let modrm = cur.get()?;
+ let (reg, rm) = decode_modrm_mem(&mut cur, modrm, pfx, false)?;
+ let reg_s = if w64 {
+ reg_name(reg, true, false, false)
+ } else if op16 {
+ reg_name(reg, false, true, false)
+ } else {
+ reg_name(reg, false, false, false)
+ };
+ (mnem.into(), format!("{reg_s}, {rm}"))
+ }
+ // XOR r/m8,r8 etc skip; XOR r32,r/m already covered
+ // TEST
+ 0x85 => {
+ let modrm = cur.get()?;
+ let (reg, rm) = decode_modrm_mem(&mut cur, modrm, pfx, false)?;
+ let reg_s = if w64 {
+ reg_name(reg, true, false, false)
+ } else {
+ reg_name(reg, false, op16, false)
+ };
+ ("test".into(), format!("{rm}, {reg_s}"))
+ }
+ // NOP
+ 0x90 => ("nop".into(), String::new()),
+ // RET
+ 0xC3 => ("ret".into(), String::new()),
+ 0xC2 => {
+ let imm = cur.take_imm(2)?;
+ ("ret".into(), format!("{imm:#x}"))
+ }
+ // CALL rel32
+ 0xE8 => {
+ let rel = cur.take_imm(4)? as i32 as i64;
+ let target = address
+ .wrapping_add(cur.pos as u64)
+ .wrapping_add(rel as u64);
+ ("call".into(), format!("{target:#x}"))
+ }
+ // JMP rel32
+ 0xE9 => {
+ let rel = cur.take_imm(4)? as i32 as i64;
+ let target = address
+ .wrapping_add(cur.pos as u64)
+ .wrapping_add(rel as u64);
+ ("jmp".into(), format!("{target:#x}"))
+ }
+ // JMP rel8
+ 0xEB => {
+ let rel = cur.take_imm(1)? as i8 as i64;
+ let target = address
+ .wrapping_add(cur.pos as u64)
+ .wrapping_add(rel as u64);
+ ("jmp".into(), format!("{target:#x}"))
+ }
+ // Jcc rel8
+ 0x70..=0x7F => {
+ let names = [
+ "jo", "jno", "jb", "jae", "je", "jne", "jbe", "ja", "js", "jns", "jp", "jnp",
+ "jl", "jge", "jle", "jg",
+ ];
+ let rel = cur.take_imm(1)? as i8 as i64;
+ let target = address
+ .wrapping_add(cur.pos as u64)
+ .wrapping_add(rel as u64);
+ (names[(op - 0x70) as usize].into(), format!("{target:#x}"))
+ }
+ // INT3
+ 0xCC => ("int3".into(), String::new()),
+ // CDQ / CQO
+ 0x99 => {
+ if w64 {
+ ("cqo".into(), String::new())
+ } else {
+ ("cdq".into(), String::new())
+ }
+ }
+ // LEAVE
+ 0xC9 => ("leave".into(), String::new()),
+ // SUB/ADD r/m, imm8 (83 /x)
+ 0x83 => {
+ let modrm = cur.get()?;
+ let reg_field = (modrm >> 3) & 7;
+ let mnem = match reg_field {
+ 0 => "add",
+ 1 => "or",
+ 2 => "adc",
+ 3 => "sbb",
+ 4 => "and",
+ 5 => "sub",
+ 6 => "xor",
+ 7 => "cmp",
+ _ => "grp",
+ };
+ let (_reg, rm) = decode_modrm_mem(&mut cur, modrm, pfx, false)?;
+ let imm = cur.take_imm(1)? as i8 as i64;
+ (mnem.into(), format!("{rm}, {imm:#x}"))
+ }
+ // group 81 r/m, imm32
+ 0x81 => {
+ let modrm = cur.get()?;
+ let reg_field = (modrm >> 3) & 7;
+ let mnem = match reg_field {
+ 0 => "add",
+ 1 => "or",
+ 2 => "adc",
+ 3 => "sbb",
+ 4 => "and",
+ 5 => "sub",
+ 6 => "xor",
+ 7 => "cmp",
+ _ => "grp",
+ };
+ let (_reg, rm) = decode_modrm_mem(&mut cur, modrm, pfx, false)?;
+ let imm = if op16 {
+ cur.take_imm(2)? as i16 as i64
+ } else {
+ cur.take_imm(4)? as i32 as i64
+ };
+ (mnem.into(), format!("{rm}, {imm:#x}"))
+ }
+ // two-byte 0F
+ 0x0F => {
+ let op2 = cur.get()?;
+ match op2 {
+ // Jcc rel32
+ 0x80..=0x8F => {
+ let names = [
+ "jo", "jno", "jb", "jae", "je", "jne", "jbe", "ja", "js", "jns", "jp",
+ "jnp", "jl", "jge", "jle", "jg",
+ ];
+ let rel = cur.take_imm(4)? as i32 as i64;
+ let target = address
+ .wrapping_add(cur.pos as u64)
+ .wrapping_add(rel as u64);
+ (names[(op2 - 0x80) as usize].into(), format!("{target:#x}"))
+ }
+ 0x1F => {
+ // NOP r/m
+ let modrm = cur.get()?;
+ let (_r, rm) = decode_modrm_mem(&mut cur, modrm, pfx, false)?;
+ ("nop".into(), rm)
+ }
+ 0x05 => ("syscall".into(), String::new()),
+ 0xA2 => ("cpuid".into(), String::new()),
+ _ => {
+ return Err(Error::Decode(format!("unhandled 0F {op2:02x}")));
+ }
+ }
+ }
+ // FF /2 CALL, /4 JMP
+ 0xFF => {
+ let modrm = cur.get()?;
+ let reg_field = (modrm >> 3) & 7;
+ let (_r, rm) = decode_modrm_mem(&mut cur, modrm, pfx, false)?;
+ match reg_field {
+ 2 => ("call".into(), rm),
+ 4 => ("jmp".into(), rm),
+ 6 => ("push".into(), rm),
+ _ => {
+ return Err(Error::Decode(format!("unhandled FF /{reg_field}")));
+ }
+ }
+ }
+ // XOR r8,r8 style short: 31 already; also 30
+ 0x30 | 0x32 => {
+ let modrm = cur.get()?;
+ let (reg, rm) = decode_modrm_mem(&mut cur, modrm, pfx, true)?;
+ let mnem = if op == 0x30 { "xor" } else { "xor" };
+ if op == 0x30 {
+ (mnem.into(), format!("{rm}, {}", reg_name(reg, false, false, true)))
+ } else {
+ (mnem.into(), format!("{}, {rm}", reg_name(reg, false, false, true)))
+ }
+ }
+ other => {
+ return Err(Error::Decode(format!(
+ "unhandled opcode {other:02x} at {address:#x}"
+ )));
+ }
+ };
+
+ let taken = cur.bytes_taken().to_vec();
+ Ok(Instruction {
+ address,
+ length: taken.len() as u8,
+ bytes: taken,
+ mnemonic,
+ operands,
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn decode_push_rbp_mov_rbp_rsp() {
+ // 55 push rbp
+ // 48 89 e5 mov rbp, rsp
+ let b = [0x55, 0x48, 0x89, 0xe5];
+ let i0 = decode_one(&b, 0x1000).unwrap();
+ assert_eq!(i0.mnemonic, "push");
+ assert_eq!(i0.operands, "rbp");
+ assert_eq!(i0.length, 1);
+ let i1 = decode_one(&b[1..], 0x1001).unwrap();
+ assert_eq!(i1.mnemonic, "mov");
+ assert_eq!(i1.operands, "rbp, rsp");
+ }
+
+ #[test]
+ fn decode_xor_eax_eax_ret() {
+ // 31 c0 xor eax, eax
+ // c3 ret
+ let b = [0x31, 0xc0, 0xc3];
+ let i0 = decode_one(&b, 0).unwrap();
+ assert_eq!(i0.mnemonic, "xor");
+ assert_eq!(i0.operands, "eax, eax");
+ let i1 = decode_one(&b[2..], 2).unwrap();
+ assert_eq!(i1.mnemonic, "ret");
+ }
+}
diff --git a/crates/ghidrust-decomp/src/lib.rs b/crates/ghidrust-decomp/src/lib.rs
index d1d236b..166265d 100644
--- a/crates/ghidrust-decomp/src/lib.rs
+++ b/crates/ghidrust-decomp/src/lib.rs
@@ -1,11 +1,20 @@
-//! Hand-rolled reverse-engineering **decompile method** (not Hex-Rays / Ghidra).
+//! Hand-rolled reverse-engineering **decompile method**.
//!
-//! ## CPU path
-//! Linear instructions → basic blocks + branch edges → structured pseudo-C.
+//! **Aspirational target:** structured, typed C that is measurable against Ghidra
+//! (wall clock, function discovery, readability, differential correctness on a
+//! fixed x86-64 corpus). Hex-Rays-class quality is a later ceiling after that bar.
+//!
+//! **Stage-0 (current):** linear instructions → basic blocks + branch edges →
+//! CFG / goto-style **pseudo-C** (mnemonic scaffolding). This remains the CPU
+//! and GPU multipass emit today and the regression oracle until SSA emit is default.
+//!
+//! ## CPU path (Stage-0)
+//! Linear instructions → basic blocks + branch edges → pseudo-C emit.
//!
//! ## GPU-resident path (`gpu_decompile`)
-//! Multi-pass SIMT kernels keep IR/CFG/emit buffers in **VRAM**; host only uploads
-//! code once and downloads the final dump. See `docs/GPU_DECOMPILE_PROCESS.md`.
+//! Multi-pass SIMT kernels keep Stage-0 IR/CFG/emit buffers in **VRAM**; host only
+//! uploads code once and downloads the final dump. SSA structuring stays on the
+//! CPU roadmap. See `docs/GPU_DECOMPILE_PROCESS.md`.
pub mod gpu_decompile;
diff --git a/crates/ghidrust-gui/Cargo.toml b/crates/ghidrust-gui/Cargo.toml
index 6e95cf1..b88364e 100644
--- a/crates/ghidrust-gui/Cargo.toml
+++ b/crates/ghidrust-gui/Cargo.toml
@@ -11,6 +11,8 @@ path = "src/main.rs"
[dependencies]
ghidrust-core = { workspace = true, features = ["gpu"] }
+# CPU Stage-0 (CFG → pseudo-C); do not call GPU decompile APIs from the GUI.
+ghidrust-decomp = { path = "../ghidrust-decomp" }
eframe = { version = "0.31", default-features = true }
egui = "0.31"
rfd = "0.15"
diff --git a/crates/ghidrust-gui/src/main.rs b/crates/ghidrust-gui/src/main.rs
index 0d3b7c4..5c946af 100644
--- a/crates/ghidrust-gui/src/main.rs
+++ b/crates/ghidrust-gui/src/main.rs
@@ -2,14 +2,20 @@
//! Icons: Google Material 3 geometry (see `icons.rs`); no emoji in the UI.
mod icons;
+mod menu_actions;
use eframe::egui::{self, Color32, Visuals};
use ghidrust_core::{
analyzer_catalog, disassemble_range, load_path, m3_tokens, set_preferred_bulk_mode,
- AnalysisRunReport, AnalyzerInfo, BulkScanMode, FoundString,
- Instruction, Program, Project, ProjectTreeModel, RttiReport, ThemeMode,
+ AnalysisRunReport, AnalyzerInfo, BulkScanMode, FoundString, Instruction, Program, Project,
+ ProjectTreeModel, RttiReport, ThemeMode,
};
use icons::{m3_icon, m3_linear_progress, status_badge, M3Icon};
+use menu_actions::{
+ decompile_entry_for_va, listing_index_at_or_before, parse_address, parse_hex_pattern,
+ processor_info, search_memory, search_program_text, stage0_pseudo_c, ListingSelection,
+ MemoryHit, TextHit, STAGE0_MAX_INSNS,
+};
use std::path::{Path, PathBuf};
fn recent_projects_path() -> PathBuf {
@@ -68,7 +74,7 @@ fn main() -> eframe::Result<()> {
)
}
-#[derive(Clone, Copy, PartialEq, Eq)]
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum CenterPane {
/// File summary + analysis counts (default after open/analyze).
Overview,
@@ -124,6 +130,26 @@ pub struct GhidrustApp {
show_startup_picker: bool,
recent_projects: Vec<String>,
nyi_note: Option<String>,
+ // ── CodeBrowser selection / search / navigation (Ghidra-analog) ──────
+ listing_selection: ListingSelection,
+ undo_stack: Vec<ListingSelection>,
+ redo_stack: Vec<ListingSelection>,
+ listing_focus_va: Option<u64>,
+ show_goto_dialog: bool,
+ goto_input: String,
+ show_search_memory_dialog: bool,
+ search_memory_input: String,
+ show_search_text_dialog: bool,
+ search_text_input: String,
+ search_text_case_insensitive: bool,
+ show_search_results: bool,
+ memory_hits: Vec<MemoryHit>,
+ text_hits: Vec<TextHit>,
+ show_processor_dialog: bool,
+ /// Cached Stage-0 pseudo-C for the focused function entry (None = stale / empty).
+ decomp_entry: Option<u64>,
+ decomp_text: String,
+ decomp_status: String,
}
impl GhidrustApp {
@@ -176,7 +202,217 @@ impl GhidrustApp {
show_startup_picker: false,
recent_projects: Vec::new(),
nyi_note: None,
+ listing_selection: ListingSelection::default(),
+ undo_stack: Vec::new(),
+ redo_stack: Vec::new(),
+ listing_focus_va: None,
+ show_goto_dialog: false,
+ goto_input: String::new(),
+ show_search_memory_dialog: false,
+ search_memory_input: String::new(),
+ show_search_text_dialog: false,
+ search_text_input: String::new(),
+ search_text_case_insensitive: true,
+ show_search_results: false,
+ memory_hits: Vec::new(),
+ text_hits: Vec::new(),
+ show_processor_dialog: false,
+ decomp_entry: None,
+ decomp_text: String::new(),
+ decomp_status: String::new(),
+ }
+ }
+
+ fn clear_decompiler_cache(&mut self) {
+ self.decomp_entry = None;
+ self.decomp_text.clear();
+ self.decomp_status.clear();
+ }
+
+ /// Refresh Stage-0 decompiler cache for `va` (containing / nearest function).
+ pub fn refresh_decompiler_at(&mut self, va: u64) {
+ let Some(prog) = self.program.as_ref() else {
+ self.decomp_entry = None;
+ self.decomp_text.clear();
+ self.decomp_status = "No program loaded.".into();
+ return;
+ };
+ let entry = decompile_entry_for_va(prog, va);
+ if self.decomp_entry == Some(entry) && !self.decomp_text.is_empty() {
+ return;
+ }
+ match stage0_pseudo_c(prog, va, STAGE0_MAX_INSNS) {
+ Ok((entry, text)) => {
+ self.decomp_entry = Some(entry);
+ self.decomp_text = text;
+ self.decomp_status = format!("Stage-0 · {entry:#x}");
+ }
+ Err(e) => {
+ self.decomp_entry = Some(entry);
+ self.decomp_text = format!("// decompile failed at {entry:#x}\n// {e}\n");
+ self.decomp_status = format!("error: {e}");
+ }
+ }
+ }
+
+ /// Symbol Tree / Navigation: focus a function entry in Listing and update Decompiler.
+ pub fn focus_function(&mut self, entry: u64) {
+ let addr = format!("{entry:#x}");
+ if let Err(e) = self.goto_address_str(&addr) {
+ self.status = format!("error: {e}");
+ self.log(self.status.clone());
+ return;
+ }
+ self.refresh_decompiler_at(entry);
+ self.center = CenterPane::Decompiler;
+ self.status = format!("Function {entry:#x}");
+ self.log(self.status.clone());
+ }
+
+ fn push_selection_undo(&mut self) {
+ self.undo_stack.push(self.listing_selection);
+ if self.undo_stack.len() > 64 {
+ self.undo_stack.remove(0);
+ }
+ self.redo_stack.clear();
+ }
+
+ /// Edit → Undo (selection history).
+ pub fn edit_undo(&mut self) {
+ if let Some(prev) = self.undo_stack.pop() {
+ self.redo_stack.push(self.listing_selection);
+ self.listing_selection = prev;
+ self.status = "Undo: restored selection".into();
+ self.log(self.status.clone());
+ } else {
+ self.status = "Nothing to undo".into();
+ self.log(self.status.clone());
+ }
+ }
+
+ /// Edit → Redo.
+ pub fn edit_redo(&mut self) {
+ if let Some(next) = self.redo_stack.pop() {
+ self.undo_stack.push(self.listing_selection);
+ self.listing_selection = next;
+ self.status = "Redo: restored selection".into();
+ self.log(self.status.clone());
+ } else {
+ self.status = "Nothing to redo".into();
+ self.log(self.status.clone());
+ }
+ }
+
+ /// Edit → Clear Selection.
+ pub fn edit_clear_selection(&mut self) {
+ self.push_selection_undo();
+ self.listing_selection = ListingSelection::clear();
+ self.status = "Selection cleared".into();
+ self.log(self.status.clone());
+ }
+
+ /// Select → Select All (listing range).
+ pub fn select_all_listing(&mut self) {
+ self.push_selection_undo();
+ self.listing_selection = ListingSelection::all(self.listing.len());
+ self.status = format!(
+ "Selected all {} listing instruction(s)",
+ self.listing.len()
+ );
+ self.log(self.status.clone());
+ self.center = CenterPane::Listing;
+ }
+
+ /// Navigation → Go To Address.
+ /// If `va` is outside the current listing window, re-disassembles 64 insns at `va`.
+ pub fn goto_address_str(&mut self, s: &str) -> Result<(), String> {
+ let va = parse_address(s)?;
+ self.listing_focus_va = Some(va);
+ self.center = CenterPane::Listing;
+
+ if let Some(i) = listing_index_at_or_before(&self.listing, va) {
+ self.push_selection_undo();
+ self.listing_selection = ListingSelection {
+ start: Some(i),
+ end: Some(i),
+ };
+ } else {
+ // Outside loaded listing (or empty) — re-disassemble at target VA.
+ let prog = self
+ .program
+ .as_ref()
+ .ok_or_else(|| "no program loaded".to_string())?;
+ let l = disassemble_range(prog, va, 64).map_err(|e| e.to_string())?;
+ if l.is_empty() {
+ return Err(format!("no instructions at {va:#x}"));
+ }
+ self.listing = l;
+ self.push_selection_undo();
+ self.listing_selection = ListingSelection {
+ start: Some(0),
+ end: Some(0),
+ };
+ }
+
+ self.status = format!("Go to {va:#x}");
+ self.log(self.status.clone());
+ Ok(())
+ }
+
+ /// Navigation → Go To entry.
+ pub fn goto_entry(&mut self) {
+ self.center = CenterPane::Listing;
+ if let Some(prog) = &self.program {
+ if let Some(e) = prog.entry {
+ let _ = self.goto_address_str(&format!("{e:#x}"));
+ return;
+ }
}
+ self.status = "No entry point".into();
+ self.log(self.status.clone());
+ }
+
+ /// Search → Memory.
+ pub fn run_search_memory(&mut self) -> Result<(), String> {
+ let prog = self
+ .program
+ .as_ref()
+ .ok_or_else(|| "no program loaded".to_string())?;
+ let pat = parse_hex_pattern(&self.search_memory_input)?;
+ self.memory_hits = search_memory(prog, &pat, 500);
+ self.text_hits.clear();
+ self.show_search_results = true;
+ self.status = format!(
+ "Memory search: {} hit(s) for '{}'",
+ self.memory_hits.len(),
+ self.search_memory_input.trim()
+ );
+ self.log(self.status.clone());
+ Ok(())
+ }
+
+ /// Search → Program Text.
+ pub fn run_search_text(&mut self) -> Result<(), String> {
+ let prog = self
+ .program
+ .as_ref()
+ .ok_or_else(|| "no program loaded".to_string())?;
+ self.text_hits = search_program_text(
+ prog,
+ &self.listing,
+ &self.search_text_input,
+ self.search_text_case_insensitive,
+ 500,
+ );
+ self.memory_hits.clear();
+ self.show_search_results = true;
+ self.status = format!(
+ "Text search: {} hit(s) for '{}'",
+ self.text_hits.len(),
+ self.search_text_input.trim()
+ );
+ self.log(self.status.clone());
+ Ok(())
}
fn remember_project(&mut self, dir: &str) {
@@ -322,6 +558,7 @@ impl GhidrustApp {
self.listing.clear();
self.strings.clear();
self.rtti = RttiReport::default();
+ self.clear_decompiler_cache();
let next = self
.project
.as_ref()
@@ -540,6 +777,15 @@ impl GhidrustApp {
}
self.center = CenterPane::Overview;
self.show_symbol_tree = true;
+ // Function list / names may have changed — drop cache and re-seed Stage-0.
+ self.clear_decompiler_cache();
+ if let Some(va) = self
+ .listing_focus_va
+ .or_else(|| self.listing.first().map(|i| i.address))
+ .or_else(|| self.program.as_ref().and_then(|p| p.entry))
+ {
+ self.refresh_decompiler_at(va);
+ }
// Restore default bulk mode after experimental run
set_preferred_bulk_mode(BulkScanMode::ParallelCpu);
Ok(())
@@ -600,6 +846,10 @@ impl GhidrustApp {
self.strings.clear();
self.last_analysis = AnalysisRunReport::default();
self.last_analyzers_run.clear();
+ self.clear_decompiler_cache();
+ if let Some(va) = self.listing.first().map(|i| i.address).or(self.listing_focus_va) {
+ self.refresh_decompiler_at(va);
+ }
Ok(())
}
@@ -744,6 +994,15 @@ impl GhidrustApp {
self.log(self.status.clone());
self.program = Some(prog);
self.listing = listing;
+ self.clear_decompiler_cache();
+ if let Some(va) = self
+ .listing
+ .first()
+ .map(|i| i.address)
+ .or_else(|| self.program.as_ref().and_then(|p| p.entry))
+ {
+ self.refresh_decompiler_at(va);
+ }
self.center = CenterPane::Overview;
self.show_symbol_tree = true;
if let Some(p) = self.project.as_mut() {
@@ -802,6 +1061,7 @@ impl GhidrustApp {
}
}
+ #[allow(dead_code)] // kept for non-menubar future stubs; menubar stubs are wired
fn nyi(&mut self, what: &str) {
let m = format!("Not yet implemented: {what}");
self.status = m.clone();
@@ -1164,15 +1424,15 @@ impl eframe::App for GhidrustApp {
});
ui.menu_button("Edit", |ui| {
if ui.button("Undo").clicked() {
- self.nyi("Edit → Undo");
+ self.edit_undo();
ui.close_menu();
}
if ui.button("Redo").clicked() {
- self.nyi("Edit → Redo");
+ self.edit_redo();
ui.close_menu();
}
if ui.button("Clear selection").clicked() {
- self.nyi("Edit → Clear selection");
+ self.edit_clear_selection();
ui.close_menu();
}
});
@@ -1190,33 +1450,40 @@ impl eframe::App for GhidrustApp {
});
ui.menu_button("Navigation", |ui| {
if ui.button("Go to entry").clicked() {
- self.center = CenterPane::Listing;
+ self.goto_entry();
ui.close_menu();
}
if ui.button("Go to address…").clicked() {
- self.nyi("Navigation → Go to address");
+ if let Some(prog) = &self.program {
+ if let Some(e) = prog.entry {
+ self.goto_input = format!("{e:#x}");
+ } else {
+ self.goto_input = format!("{:#x}", prog.image_base);
+ }
+ }
+ self.show_goto_dialog = true;
ui.close_menu();
}
});
ui.menu_button("Search", |ui| {
if ui.button("Search memory…").clicked() {
- self.nyi("Search → Search memory");
+ self.show_search_memory_dialog = true;
ui.close_menu();
}
if ui.button("Search program text…").clicked() {
- self.nyi("Search → Search program text");
+ self.show_search_text_dialog = true;
ui.close_menu();
}
});
ui.menu_button("Select", |ui| {
if ui.button("Select all").clicked() {
- self.nyi("Select → Select all");
+ self.select_all_listing();
ui.close_menu();
}
});
ui.menu_button("Tools", |ui| {
if ui.button("Processor options…").clicked() {
- self.nyi("Tools → Processor options");
+ self.show_processor_dialog = true;
ui.close_menu();
}
});
@@ -1675,16 +1942,40 @@ impl eframe::App for GhidrustApp {
.collect();
let row_h = ui.text_style_height(&egui::TextStyle::Monospace);
let n = rows.len();
+ let mut clicked_fn: Option<u64> = None;
egui::ScrollArea::vertical()
.id_salt("fn_scroll")
.max_height(220.0)
.show_rows(ui, row_h, n, |ui, range| {
for i in range {
let (va, name) = &rows[i];
- ui.monospace(format!("{va:#x} {name}"));
+ let label = format!("{va:#x} {name}");
+ let focused = self.decomp_entry == Some(*va)
+ || self.listing_focus_va == Some(*va);
+ let rich = if focused {
+ egui::RichText::new(label)
+ .monospace()
+ .color(primary)
+ } else {
+ egui::RichText::new(label).monospace()
+ };
+ let r = ui.add(
+ egui::Label::new(rich).sense(egui::Sense::click()),
+ );
+ if r.clicked() {
+ clicked_fn = Some(*va);
+ }
+ if r.hovered() {
+ ui.ctx().set_cursor_icon(
+ egui::CursorIcon::PointingHand,
+ );
+ }
}
});
- ui.small(format!("{n} shown"));
+ if let Some(va) = clicked_fn {
+ self.focus_function(va);
+ }
+ ui.small(format!("{n} shown · click → Listing + Decompiler"));
}
});
@@ -1806,23 +2097,102 @@ impl eframe::App for GhidrustApp {
}
CenterPane::Listing => {
ui.heading("Listing");
+ if !self.listing_selection.is_empty() {
+ ui.small(format!(
+ "Selection: {}–{}",
+ self.listing_selection.start.unwrap_or(0),
+ self.listing_selection.end.unwrap_or(0)
+ ));
+ }
+ if let Some(va) = self.listing_focus_va {
+ ui.small(format!("Focus VA {va:#x}"));
+ }
egui::ScrollArea::vertical().show(ui, |ui| {
if self.listing.is_empty() {
ui.weak("No listing — double-click a project file to open.");
}
- for insn in &self.listing {
- ui.monospace(insn.text());
+ let focus = self.listing_focus_va;
+ let sel = self.listing_selection;
+ let t = m3_tokens(self.theme);
+ let sel_bg = Color32::from_rgb(t.primary[0], t.primary[1], t.primary[2])
+ .gamma_multiply(0.35);
+ let rows: Vec<(usize, u64, String)> = self
+ .listing
+ .iter()
+ .enumerate()
+ .map(|(i, insn)| (i, insn.address, insn.text()))
+ .collect();
+ let mut click_i: Option<(usize, u64)> = None;
+ for (i, addr, row) in rows {
+ let focused = focus == Some(addr);
+ let selected = sel.contains(i);
+ let mut job = egui::text::LayoutJob::default();
+ let color = if focused {
+ Color32::from_rgb(0xFF, 0xD5, 0x4F)
+ } else {
+ ui.visuals().text_color()
+ };
+ job.append(
+ &row,
+ 0.0,
+ egui::TextFormat {
+ font_id: egui::FontId::monospace(13.0),
+ color,
+ background: if selected {
+ sel_bg
+ } else {
+ Color32::TRANSPARENT
+ },
+ ..Default::default()
+ },
+ );
+ let r = ui.add(egui::Label::new(job).sense(egui::Sense::click()));
+ if r.clicked() {
+ click_i = Some((i, addr));
+ }
+ }
+ if let Some((i, addr)) = click_i {
+ self.push_selection_undo();
+ self.listing_selection = ListingSelection {
+ start: Some(i),
+ end: Some(i),
+ };
+ self.listing_focus_va = Some(addr);
+ self.refresh_decompiler_at(addr);
}
});
}
CenterPane::Decompiler => {
ui.heading("Decompiler");
- ui.weak(
- "Not yet implemented — Phase 3 production decompiler (structure present).",
- );
- if let Some(prog) = &self.program {
- if let Some(e) = prog.entry {
- ui.monospace(format!("// placeholder for function at {e:#x}"));
+ if self.program.is_none() {
+ ui.weak("Open a project file, then select a function or listing address.");
+ } else {
+ // Keep cache in sync with focus when switching to this pane.
+ if let Some(va) = self.listing_focus_va.or(self.decomp_entry).or_else(|| {
+ self.program.as_ref().and_then(|p| p.entry)
+ }) {
+ self.refresh_decompiler_at(va);
+ }
+ if !self.decomp_status.is_empty() {
+ ui.small(&self.decomp_status);
+ }
+ ui.separator();
+ if self.decomp_text.is_empty() {
+ ui.weak(
+ "Select a Symbol Tree function or a Listing instruction to decompile (Stage-0 CFG → pseudo-C).",
+ );
+ } else {
+ egui::ScrollArea::both()
+ .id_salt("decomp_scroll")
+ .auto_shrink([false, false])
+ .show(ui, |ui| {
+ ui.add(
+ egui::Label::new(
+ egui::RichText::new(&self.decomp_text).monospace(),
+ )
+ .selectable(true),
+ );
+ });
}
}
}
@@ -1839,6 +2209,170 @@ impl eframe::App for GhidrustApp {
}
});
+ // Navigation → Go To Address
+ if self.show_goto_dialog {
+ egui::Window::new("Go To Address")
+ .collapsible(false)
+ .resizable(false)
+ .anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0])
+ .show(ctx, |ui| {
+ ui.label("Address (hex, optional 0x prefix):");
+ ui.text_edit_singleline(&mut self.goto_input);
+ ui.horizontal(|ui| {
+ if ui.button("Cancel").clicked() {
+ self.show_goto_dialog = false;
+ }
+ if ui.button("Go").clicked() {
+ match self.goto_address_str(&self.goto_input.clone()) {
+ Ok(()) => self.show_goto_dialog = false,
+ Err(e) => {
+ self.status = format!("error: {e}");
+ self.log(self.status.clone());
+ }
+ }
+ }
+ });
+ });
+ }
+
+ // Search → Memory
+ if self.show_search_memory_dialog {
+ egui::Window::new("Search Memory")
+ .collapsible(false)
+ .resizable(true)
+ .default_width(420.0)
+ .anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0])
+ .show(ctx, |ui| {
+ ui.label("Byte pattern (hex; ?? = wildcard):");
+ ui.text_edit_singleline(&mut self.search_memory_input);
+ ui.small("Example: 55 48 89 e5 or 48??e5");
+ ui.horizontal(|ui| {
+ if ui.button("Cancel").clicked() {
+ self.show_search_memory_dialog = false;
+ }
+ if ui.button("Search").clicked() {
+ match self.run_search_memory() {
+ Ok(()) => self.show_search_memory_dialog = false,
+ Err(e) => {
+ self.status = format!("error: {e}");
+ self.log(self.status.clone());
+ }
+ }
+ }
+ });
+ });
+ }
+
+ // Search → Program Text
+ if self.show_search_text_dialog {
+ egui::Window::new("Search Program Text")
+ .collapsible(false)
+ .resizable(true)
+ .default_width(420.0)
+ .anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0])
+ .show(ctx, |ui| {
+ ui.label("Query (listing / symbols / functions / memory text):");
+ ui.text_edit_singleline(&mut self.search_text_input);
+ ui.checkbox(&mut self.search_text_case_insensitive, "Case insensitive");
+ ui.horizontal(|ui| {
+ if ui.button("Cancel").clicked() {
+ self.show_search_text_dialog = false;
+ }
+ if ui.button("Search").clicked() {
+ match self.run_search_text() {
+ Ok(()) => self.show_search_text_dialog = false,
+ Err(e) => {
+ self.status = format!("error: {e}");
+ self.log(self.status.clone());
+ }
+ }
+ }
+ });
+ });
+ }
+
+ // Search results window
+ if self.show_search_results {
+ egui::Window::new("Search Results")
+ .collapsible(true)
+ .resizable(true)
+ .default_width(480.0)
+ .default_height(280.0)
+ .show(ctx, |ui| {
+ if ui.button("Close").clicked() {
+ self.show_search_results = false;
+ }
+ ui.separator();
+ egui::ScrollArea::vertical().show(ui, |ui| {
+ for h in self.memory_hits.clone() {
+ if ui
+ .button(format!("{:#x} {} +{:#x}", h.va, h.block, h.offset_in_block))
+ .clicked()
+ {
+ let _ = self.goto_address_str(&format!("{:#x}", h.va));
+ }
+ }
+ for h in self.text_hits.clone() {
+ let label = match h.va {
+ Some(va) => format!("[{}] {:#x}: {}", h.kind, va, h.text),
+ None => format!("[{}] {}", h.kind, h.text),
+ };
+ if ui.button(label).clicked() {
+ if let Some(va) = h.va {
+ let _ = self.goto_address_str(&format!("{va:#x}"));
+ }
+ }
+ }
+ if self.memory_hits.is_empty() && self.text_hits.is_empty() {
+ ui.weak("No hits.");
+ }
+ });
+ });
+ }
+
+ // Tools → Processor options
+ if self.show_processor_dialog {
+ egui::Window::new("Processor Options")
+ .collapsible(false)
+ .resizable(true)
+ .default_width(440.0)
+ .anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0])
+ .show(ctx, |ui| {
+ if let Some(prog) = &self.program {
+ let info = processor_info(prog);
+ ui.monospace(format!("Language: {}", info.language));
+ ui.monospace(format!("Compiler: {}", info.compiler));
+ ui.monospace(format!("Format: {}", info.format));
+ ui.monospace(format!("Endian: {}", info.endian));
+ ui.monospace(format!("Pointer size: {} bytes", info.pointer_size));
+ ui.monospace(format!("Image base: {:#x}", info.image_base));
+ ui.monospace(format!(
+ "Entry: {}",
+ info.entry
+ .map(|e| format!("{e:#x}"))
+ .unwrap_or_else(|| "—".into())
+ ));
+ ui.separator();
+ ui.small(&info.notes);
+ ui.separator();
+ ui.label("Sections:");
+ egui::ScrollArea::vertical().max_height(160.0).show(ui, |ui| {
+ for s in &prog.sections {
+ ui.monospace(format!(
+ "{} va={:#x} vsize={:#x}",
+ s.name, s.va, s.virtual_size
+ ));
+ }
+ });
+ } else {
+ ui.weak("Load a program to view processor / language options.");
+ }
+ if ui.button("Close").clicked() {
+ self.show_processor_dialog = false;
+ }
+ });
+ }
+
if self.show_analysis_dialog && self.analysis_job.is_none() {
let t = m3_tokens(self.theme);
let primary = Color32::from_rgb(t.primary[0], t.primary[1], t.primary[2]);
@@ -2118,6 +2652,29 @@ mod tests {
assert_eq!(app.analyzer_infos.len(), ANALYZER_NAMES.len());
}
+ #[test]
+ fn headless_stage0_decompiler_wires_on_focus() {
+ let mut app = GhidrustApp::headless();
+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
+ assert!(!app.decomp_text.is_empty(), "load should seed Stage-0 text");
+ assert!(!app.decomp_text.contains("Not yet implemented"));
+
+ let va = app.listing[0].address;
+ app.refresh_decompiler_at(va);
+ assert!(app.decomp_entry.is_some());
+ assert!(
+ app.decomp_text.contains("void ") || app.decomp_text.contains("block_"),
+ "expected Stage-0 pseudo-C:\n{}",
+ app.decomp_text
+ );
+
+ let entry = app.decomp_entry.unwrap();
+ app.focus_function(entry);
+ assert_eq!(app.center, CenterPane::Decompiler);
+ assert_eq!(app.listing_focus_va, Some(entry));
+ assert!(!app.decomp_text.is_empty());
+ }
+
#[test]
fn headless_project_import_analyze_save() {
let dir = std::env::temp_dir().join(format!("ghidrust_gui_proj_{}", std::process::id()));
@@ -2156,6 +2713,10 @@ mod tests {
assert!(src.contains("Program Tree"));
assert!(src.contains("Project Tree") || src.contains("project_tree"));
assert!(src.contains("Decompiler"));
+ assert!(src.contains("refresh_decompiler_at") || src.contains("stage0_pseudo_c"));
+ assert!(src.contains("focus_function"));
+ assert!(src.contains("Stage-0"));
+ assert!(src.contains("decomp_scroll") || src.contains("decomp_text"));
assert!(src.contains("ASCII Strings"));
assert!(src.contains("Analyzed") || src.contains("has_saved_analysis"));
assert!(src.contains("analyze_from_tree") || src.contains("small_button(\"Analyze\")"));
@@ -2187,4 +2748,133 @@ mod tests {
assert!(!icons.contains('\u{1F4C1}'));
assert!(!icons.contains('\u{25CF}'));
}
+
+ #[test]
+ fn former_menu_stubs_are_wired_not_nyi_only() {
+ let src = include_str!("main.rs");
+ // No remaining nyi() for inventoried Edit/Nav/Search/Select/Tools stubs
+ assert!(!src.contains("nyi(\"Edit → Undo\")"));
+ assert!(!src.contains("nyi(\"Edit → Redo\")"));
+ assert!(!src.contains("nyi(\"Edit → Clear selection\")"));
+ assert!(!src.contains("nyi(\"Navigation → Go to address\")"));
+ assert!(!src.contains("nyi(\"Search → Search memory\")"));
+ assert!(!src.contains("nyi(\"Search → Search program text\")"));
+ assert!(!src.contains("nyi(\"Select → Select all\")"));
+ assert!(!src.contains("nyi(\"Tools → Processor options\")"));
+ // Real handlers present
+ assert!(src.contains("edit_undo"));
+ assert!(src.contains("edit_redo"));
+ assert!(src.contains("edit_clear_selection"));
+ assert!(src.contains("goto_address_str") || src.contains("show_goto_dialog"));
+ assert!(src.contains("run_search_memory"));
+ assert!(src.contains("run_search_text"));
+ assert!(src.contains("select_all_listing"));
+ assert!(src.contains("show_processor_dialog"));
+ }
+
+ #[test]
+ fn menu_actions_goto_search_select_on_loaded_program() {
+ let mut app = GhidrustApp::headless();
+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
+ assert!(!app.listing.is_empty());
+
+ app.select_all_listing();
+ assert!(!app.listing_selection.is_empty());
+ assert!(app.listing_selection.contains(0));
+
+ app.edit_clear_selection();
+ assert!(app.listing_selection.is_empty());
+
+ app.select_all_listing();
+ app.edit_undo();
+ assert!(app.listing_selection.is_empty());
+ app.edit_redo();
+ assert!(!app.listing_selection.is_empty());
+
+ let entry = app.program.as_ref().and_then(|p| p.entry).unwrap();
+ app.goto_address_str(&format!("{entry:#x}")).expect("goto");
+ assert_eq!(app.listing_focus_va, Some(entry));
+ assert_eq!(app.center, CenterPane::Listing);
+
+ app.search_memory_input = "55 48 89 e5".into();
+ app.run_search_memory().expect("mem search");
+ assert!(!app.memory_hits.is_empty());
+ assert!(app.show_search_results);
+
+ app.search_text_input = "push".into();
+ app.run_search_text().expect("text search");
+ assert!(!app.text_hits.is_empty());
+
+ app.show_processor_dialog = true;
+ let info = processor_info(app.program.as_ref().unwrap());
+ assert!(info.language.contains("x86"));
+ }
+
+ #[test]
+ fn goto_out_of_window_va_redisassembles_listing() {
+ let mut app = GhidrustApp::headless();
+ // analysis_lab has richer layout; load then go to a VA outside entry window
+ app.load_binary(&fixture_path("analysis_lab.pe")).expect("load");
+ let entry = app.program.as_ref().and_then(|p| p.entry).unwrap();
+ let first_listing_va = app.listing[0].address;
+ assert_eq!(first_listing_va, entry);
+
+ // Pick a program block VA that is not covered by the entry listing window
+ let window_end = {
+ let last = app.listing.last().unwrap();
+ last.address + u64::from(last.length).max(1)
+ };
+ let outside = app
+ .program
+ .as_ref()
+ .unwrap()
+ .blocks
+ .iter()
+ .map(|b| b.va)
+ .find(|&va| va < first_listing_va || va >= window_end)
+ .expect("need a block VA outside entry listing window");
+
+ // Confirm helper says outside
+ assert!(
+ listing_index_at_or_before(&app.listing, outside).is_none(),
+ "precondition: {outside:#x} must be outside listing [{first_listing_va:#x}..)"
+ );
+
+ app.goto_address_str(&format!("{outside:#x}"))
+ .expect("goto outside");
+ assert_eq!(app.listing_focus_va, Some(outside));
+ assert!(
+ !app.listing.is_empty(),
+ "re-disassemble must produce listing"
+ );
+ assert_eq!(
+ app.listing[0].address, outside,
+ "listing must start at target VA after re-disassemble"
+ );
+ // Selection points at first insn of new window
+ assert_eq!(app.listing_selection.start, Some(0));
+
+ // Memory search hit navigation also refreshes when needed
+ if let Some(hit) = app.memory_hits.first().cloned() {
+ let _ = hit;
+ }
+ app.search_memory_input = "55 48 89 e5".into();
+ app.run_search_memory().expect("mem");
+ assert!(!app.memory_hits.is_empty());
+ let hit_va = app.memory_hits[0].va;
+ // Force listing back to entry-only window
+ app.goto_address_str(&format!("{entry:#x}")).expect("back to entry");
+ assert_eq!(app.listing[0].address, entry);
+ // Navigate to memory hit (may be same or different region)
+ app.goto_address_str(&format!("{hit_va:#x}"))
+ .expect("goto hit");
+ assert!(
+ app.listing
+ .iter()
+ .any(|i| i.address == hit_va
+ || (i.address <= hit_va && hit_va < i.address + u64::from(i.length))),
+ "listing must cover hit VA {hit_va:#x} after goto; first={:#x}",
+ app.listing[0].address
+ );
+ }
}
diff --git a/crates/ghidrust-gui/src/menu_actions.rs b/crates/ghidrust-gui/src/menu_actions.rs
new file mode 100644
index 0000000..2fbf2e2
--- /dev/null
+++ b/crates/ghidrust-gui/src/menu_actions.rs
@@ -0,0 +1,427 @@
+//! Pure helpers for CodeBrowser menu actions (Ghidra analogs).
+//! Unit-tested without egui click automation.
+
+use ghidrust_core::{Instruction, Program};
+
+/// Listing selection as inclusive instruction indices (Ghidra: selection in Listing).
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
+pub struct ListingSelection {
+ pub start: Option<usize>,
+ pub end: Option<usize>,
+}
+
+impl ListingSelection {
+ pub fn is_empty(&self) -> bool {
+ self.start.is_none() || self.end.is_none()
+ }
+
+ pub fn clear() -> Self {
+ Self::default()
+ }
+
+ pub fn all(len: usize) -> Self {
+ if len == 0 {
+ return Self::default();
+ }
+ Self {
+ start: Some(0),
+ end: Some(len - 1),
+ }
+ }
+
+ pub fn contains(&self, i: usize) -> bool {
+ match (self.start, self.end) {
+ (Some(a), Some(b)) => {
+ let lo = a.min(b);
+ let hi = a.max(b);
+ i >= lo && i <= hi
+ }
+ _ => false,
+ }
+ }
+}
+
+/// Parse VA for Navigation → Go To Address (hex with optional 0x, or decimal).
+/// Ghidra analog: Navigation → Go To… accepts hex address.
+pub fn parse_address(s: &str) -> Result<u64, String> {
+ let t = s.trim();
+ if t.is_empty() {
+ return Err("empty address".into());
+ }
+ let t = t.trim_start_matches("0x").trim_start_matches("0X");
+ u64::from_str_radix(t, 16)
+ .or_else(|_| t.parse::<u64>())
+ .map_err(|e| format!("invalid address: {e}"))
+}
+
+/// Parse space/hex-digit memory pattern for Search → Memory.
+/// Accepts "48 89 e5", "4889e5", "??" wildcards (byte = any).
+pub fn parse_hex_pattern(s: &str) -> Result<Vec<Option<u8>>, String> {
+ let cleaned: String = s
+ .chars()
+ .filter(|c| !c.is_whitespace())
+ .collect();
+ if cleaned.is_empty() {
+ return Err("empty pattern".into());
+ }
+ if cleaned.len() % 2 != 0 {
+ return Err("hex pattern length must be even".into());
+ }
+ let mut out = Vec::new();
+ let bytes = cleaned.as_bytes();
+ let mut i = 0;
+ while i + 1 < bytes.len() {
+ let a = bytes[i] as char;
+ let b = bytes[i + 1] as char;
+ if a == '?' && b == '?' {
+ out.push(None);
+ } else {
+ let hi = hex_nibble(a)?;
+ let lo = hex_nibble(b)?;
+ out.push(Some((hi << 4) | lo));
+ }
+ i += 2;
+ }
+ Ok(out)
+}
+
+fn hex_nibble(c: char) -> Result<u8, String> {
+ c.to_digit(16)
+ .map(|d| d as u8)
+ .ok_or_else(|| format!("invalid hex digit '{c}'"))
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct MemoryHit {
+ pub va: u64,
+ pub block: String,
+ pub offset_in_block: usize,
+}
+
+/// Search → Memory: scan program image for byte pattern (wildcards allowed).
+pub fn search_memory(prog: &Program, pattern: &[Option<u8>], max_hits: usize) -> Vec<MemoryHit> {
+ if pattern.is_empty() || max_hits == 0 {
+ return Vec::new();
+ }
+ let mut hits = Vec::new();
+ for b in &prog.blocks {
+ let bytes = &b.bytes;
+ if bytes.len() < pattern.len() {
+ continue;
+ }
+ let last = bytes.len() - pattern.len();
+ for off in 0..=last {
+ if pattern_matches(&bytes[off..off + pattern.len()], pattern) {
+ hits.push(MemoryHit {
+ va: b.va + off as u64,
+ block: b.name.clone(),
+ offset_in_block: off,
+ });
+ if hits.len() >= max_hits {
+ return hits;
+ }
+ }
+ }
+ }
+ hits
+}
+
+fn pattern_matches(hay: &[u8], pat: &[Option<u8>]) -> bool {
+ hay.iter().zip(pat.iter()).all(|(h, p)| match p {
+ None => true,
+ Some(b) => h == b,
+ })
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct TextHit {
+ pub kind: &'static str,
+ pub va: Option<u64>,
+ pub text: String,
+}
+
+/// Search → Program Text: listing mnemonics + symbols + strings + section names.
+pub fn search_program_text(
+ prog: &Program,
+ listing: &[Instruction],
+ query: &str,
+ case_insensitive: bool,
+ max_hits: usize,
+) -> Vec<TextHit> {
+ if query.is_empty() || max_hits == 0 {
+ return Vec::new();
+ }
+ let q = if case_insensitive {
+ query.to_ascii_lowercase()
+ } else {
+ query.to_string()
+ };
+ let mut hits = Vec::new();
+ let mut try_push = |kind: &'static str, va: Option<u64>, text: String| -> bool {
+ if hits.len() >= max_hits {
+ return true;
+ }
+ let hay = if case_insensitive {
+ text.to_ascii_lowercase()
+ } else {
+ text.clone()
+ };
+ if hay.contains(&q) {
+ hits.push(TextHit { kind, va, text });
+ }
+ hits.len() >= max_hits
+ };
+
+ for insn in listing {
+ if try_push("listing", Some(insn.address), insn.text()) {
+ return hits;
+ }
+ }
+ for s in &prog.analysis.symbols {
+ if try_push("symbol", Some(s.va), s.name.clone()) {
+ return hits;
+ }
+ }
+ for f in &prog.analysis.functions {
+ if try_push("function", Some(f.entry), f.name.clone()) {
+ return hits;
+ }
+ }
+ for sec in &prog.sections {
+ if try_push("section", Some(sec.va), sec.name.clone()) {
+ return hits;
+ }
+ }
+ for b in &prog.blocks {
+ let s = String::from_utf8_lossy(&b.bytes);
+ if case_insensitive {
+ let lower = s.to_ascii_lowercase();
+ if let Some(pos) = lower.find(&q) {
+ if try_push(
+ "memory-text",
+ Some(b.va + pos as u64),
+ format!("{}…", &s[pos..].chars().take(48).collect::<String>()),
+ ) {
+ return hits;
+ }
+ }
+ } else if let Some(pos) = s.find(query) {
+ if try_push(
+ "memory-text",
+ Some(b.va + pos as u64),
+ format!("{}…", &s[pos..].chars().take(48).collect::<String>()),
+ ) {
+ return hits;
+ }
+ }
+ }
+ hits
+}
+
+/// Index of listing instruction at or nearest before `va` **within the loaded window**.
+///
+/// Returns `None` when the listing is empty or `va` is outside
+/// `[first.address, last.address + last.length)` so the caller can re-disassemble.
+pub fn listing_index_at_or_before(listing: &[Instruction], va: u64) -> Option<usize> {
+ if listing.is_empty() {
+ return None;
+ }
+ let first = listing[0].address;
+ let last = listing.last().unwrap();
+ let window_end = last
+ .address
+ .saturating_add(u64::from(last.length).max(1));
+ // Outside the loaded listing span → not a hit (do not fake index 0).
+ if va < first || va >= window_end {
+ return None;
+ }
+ let mut best = None;
+ for (i, insn) in listing.iter().enumerate() {
+ if insn.address == va {
+ return Some(i);
+ }
+ if insn.address <= va {
+ best = Some(i);
+ }
+ if insn.address > va {
+ break;
+ }
+ }
+ best
+}
+
+/// Processor / language summary (Ghidra: Edit → Tool Options / language; we show Tools → Processor).
+#[derive(Debug, Clone)]
+pub struct ProcessorInfo {
+ pub language: String,
+ pub compiler: String,
+ pub format: String,
+ pub image_base: u64,
+ pub entry: Option<u64>,
+ pub endian: String,
+ pub pointer_size: u32,
+ pub notes: String,
+}
+
+pub fn processor_info(prog: &Program) -> ProcessorInfo {
+ ProcessorInfo {
+ language: "x86:LE:64:default".into(),
+ compiler: "windows / gcc (inferred)".into(),
+ format: prog.format.clone(),
+ image_base: prog.image_base,
+ entry: prog.entry,
+ endian: "little".into(),
+ pointer_size: 8,
+ notes: "Ghidrust ships a fixed x86-64 decode path (no multi-processor SLEIGH editor). \
+ Analog to Ghidra language/processor display for the loaded program."
+ .into(),
+ }
+}
+
+/// Default max instructions for Stage-0 decompile in the GUI (matches CLI default scale).
+pub const STAGE0_MAX_INSNS: usize = 128;
+
+/// Resolve a decompile entry for `va`: containing function, else nearest prior entry, else `va`.
+pub fn decompile_entry_for_va(prog: &Program, va: u64) -> u64 {
+ let fns = &prog.analysis.functions;
+ if let Some(f) = fns.iter().find(|f| {
+ if f.end > f.entry {
+ va >= f.entry && va < f.end
+ } else {
+ f.entry == va
+ }
+ }) {
+ return f.entry;
+ }
+ fns.iter()
+ .filter(|f| f.entry <= va)
+ .max_by_key(|f| f.entry)
+ .map(|f| f.entry)
+ .unwrap_or(va)
+}
+
+/// Stage-0 CPU decompile → pseudo-C text (unit-testable without egui).
+pub fn stage0_pseudo_c(prog: &Program, va: u64, max_insns: usize) -> Result<(u64, String), String> {
+ let entry = decompile_entry_for_va(prog, va);
+ let d = ghidrust_decomp::decompile_at(prog, entry, max_insns).map_err(|e| e.to_string())?;
+ Ok((d.entry, d.pseudo_c))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use ghidrust_core::{fixture_path, load_path};
+
+ #[test]
+ fn parse_address_hex_and_dec() {
+ assert_eq!(parse_address("0x140001000").unwrap(), 0x140001000);
+ assert_eq!(parse_address("140001000").unwrap(), 0x140001000);
+ assert!(parse_address("").is_err());
+ assert!(parse_address("zz").is_err());
+ }
+
+ #[test]
+ fn parse_hex_pattern_and_wildcards() {
+ let p = parse_hex_pattern("55 48 89 e5").unwrap();
+ assert_eq!(p, vec![Some(0x55), Some(0x48), Some(0x89), Some(0xe5)]);
+ let w = parse_hex_pattern("48??e5").unwrap();
+ assert_eq!(w, vec![Some(0x48), None, Some(0xe5)]);
+ }
+
+ #[test]
+ fn search_memory_finds_push_rbp_on_tiny() {
+ let prog = load_path(fixture_path("tiny_x64.pe")).unwrap();
+ let pat = parse_hex_pattern("55 48 89 e5").unwrap();
+ let hits = search_memory(&prog, &pat, 16);
+ assert!(!hits.is_empty(), "expected prologue bytes in tiny_x64.pe");
+ assert!(hits[0].va >= prog.image_base);
+ }
+
+ #[test]
+ fn search_program_text_finds_listing_or_name() {
+ let prog = load_path(fixture_path("tiny_x64.pe")).unwrap();
+ let listing = ghidrust_core::disassemble_range(
+ &prog,
+ prog.entry.unwrap_or(prog.image_base),
+ 32,
+ )
+ .unwrap_or_default();
+ let hits = search_program_text(&prog, &listing, "push", true, 32);
+ assert!(!hits.is_empty(), "expected push in listing");
+ }
+
+ #[test]
+ fn listing_selection_all_and_clear() {
+ let a = ListingSelection::all(10);
+ assert!(a.contains(0));
+ assert!(a.contains(9));
+ assert!(!a.contains(10));
+ assert!(ListingSelection::clear().is_empty());
+ }
+
+ #[test]
+ fn listing_index_none_outside_window() {
+ let listing = vec![
+ Instruction {
+ address: 0x1000,
+ bytes: vec![0x90],
+ mnemonic: "nop".into(),
+ operands: String::new(),
+ length: 1,
+ },
+ Instruction {
+ address: 0x1001,
+ bytes: vec![0xc3],
+ mnemonic: "ret".into(),
+ operands: String::new(),
+ length: 1,
+ },
+ ];
+ assert_eq!(listing_index_at_or_before(&listing, 0x1000), Some(0));
+ assert_eq!(listing_index_at_or_before(&listing, 0x1001), Some(1));
+ assert_eq!(listing_index_at_or_before(&listing, 0x0fff), None);
+ assert_eq!(listing_index_at_or_before(&listing, 0x1002), None);
+ assert_eq!(listing_index_at_or_before(&[], 0x1000), None);
+ }
+
+ #[test]
+ fn processor_info_x64() {
+ let prog = load_path(fixture_path("analysis_lab.pe")).unwrap();
+ let p = processor_info(&prog);
+ assert!(p.language.contains("x86"));
+ assert_eq!(p.pointer_size, 8);
+ assert!(!p.format.is_empty());
+ }
+
+ #[test]
+ fn stage0_pseudo_c_from_entry() {
+ let prog = load_path(fixture_path("tiny_x64.pe")).unwrap();
+ let va = prog.entry.unwrap_or(prog.image_base);
+ let (entry, text) = stage0_pseudo_c(&prog, va, STAGE0_MAX_INSNS).expect("decompile");
+ assert_eq!(entry, decompile_entry_for_va(&prog, va));
+ assert!(
+ text.contains("void ") || text.contains("block_") || text.contains("function"),
+ "expected Stage-0 pseudo-C, got:\n{text}"
+ );
+ assert!(!text.contains("Not yet implemented"));
+ }
+
+ #[test]
+ fn decompile_entry_prefers_containing_function() {
+ use ghidrust_core::FunctionInfo;
+ let mut prog = load_path(fixture_path("tiny_x64.pe")).unwrap();
+ let entry = prog.entry.unwrap_or(prog.image_base);
+ prog.analysis.functions.push(FunctionInfo {
+ entry,
+ end: entry + 0x40,
+ name: "FUN_test".into(),
+ calling_convention: None,
+ noreturn: false,
+ varargs: false,
+ parameters: Vec::new(),
+ stack_locals: Vec::new(),
+ });
+ assert_eq!(decompile_entry_for_va(&prog, entry + 0x10), entry);
+ assert_eq!(decompile_entry_for_va(&prog, entry), entry);
+ }
+}
diff --git a/crates/ghidrust-ir/Cargo.toml b/crates/ghidrust-ir/Cargo.toml
new file mode 100644
index 0000000..bf2c3e1
--- /dev/null
+++ b/crates/ghidrust-ir/Cargo.toml
@@ -0,0 +1,9 @@
+[package]
+name = "ghidrust-ir"
+version.workspace = true
+edition.workspace = true
+license.workspace = true
+description = "Architecture-neutral pcode-like IR for Ghidrust decompile pipeline"
+
+[dependencies]
+serde = { version = "1", features = ["derive"] }
diff --git a/crates/ghidrust-ir/src/lib.rs b/crates/ghidrust-ir/src/lib.rs
new file mode 100644
index 0000000..90c0868
--- /dev/null
+++ b/crates/ghidrust-ir/src/lib.rs
@@ -0,0 +1,228 @@
+//! Architecture-neutral **pcode-like IR** for the Ghidrust decompile pipeline.
+//!
+//! Inspired by Ghidra’s `PcodeOp` / `Varnode` model (reference only — reimplemented
+//! in-tree). This crate owns the type surface; SSA, structuring, and emit live
+//! elsewhere.
+//!
+//! # Design notes
+//!
+//! - **Ops** are a fixed starter set (copy, load/store, integer ALU, control flow).
+//! Unhandled ISA semantics can use [`OpCode::Unimplemented`] until lift coverage grows.
+//! - **Varnodes** name a location (`AddrSpace` + offset + size). Constants use
+//! [`AddrSpace::Constant`]; temps use [`AddrSpace::Unique`].
+//! - **Basic blocks** are placeholders for CFG construction — not yet wired to SSA.
+
+use serde::{Deserialize, Serialize};
+
+/// Identifier for a named address space in a program IR instance.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
+pub struct SpaceId(pub u16);
+
+/// Built-in address spaces (Ghidra-like stubs).
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
+pub enum AddrSpace {
+ /// Physical / image memory (RAM).
+ Ram,
+ /// Processor register file; `offset` indexes a register.
+ Register,
+ /// Immediate / constant pool; `offset` holds the value.
+ Constant,
+ /// Temporary / unique space for intermediate results.
+ Unique,
+ /// Abstract stack space (size in bytes; offset relative to frame).
+ Stack,
+ /// Other named space (extension point).
+ Other(SpaceId),
+}
+
+/// A typed location: space + offset + width in bytes.
+#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
+pub struct Varnode {
+ pub space: AddrSpace,
+ pub offset: u64,
+ /// Size in bytes (1, 2, 4, 8, …).
+ pub size: u32,
+}
+
+impl Varnode {
+ pub fn constant(value: u64, size: u32) -> Self {
+ Self {
+ space: AddrSpace::Constant,
+ offset: value,
+ size,
+ }
+ }
+
+ pub fn register(reg_id: u64, size: u32) -> Self {
+ Self {
+ space: AddrSpace::Register,
+ offset: reg_id,
+ size,
+ }
+ }
+
+ pub fn unique(id: u64, size: u32) -> Self {
+ Self {
+ space: AddrSpace::Unique,
+ offset: id,
+ size,
+ }
+ }
+
+ pub fn ram(addr: u64, size: u32) -> Self {
+ Self {
+ space: AddrSpace::Ram,
+ offset: addr,
+ size,
+ }
+ }
+
+ pub fn stack(offset: u64, size: u32) -> Self {
+ Self {
+ space: AddrSpace::Stack,
+ offset,
+ size,
+ }
+ }
+}
+
+/// Pcode-like operation codes (minimal starter set).
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
+pub enum OpCode {
+ /// `out = in0`
+ Copy,
+ /// `out = *(in0)` — load from address in0
+ Load,
+ /// `*(in0) = in1` — store
+ Store,
+ IntAdd,
+ IntSub,
+ IntXor,
+ IntAnd,
+ IntOr,
+ /// Unconditional branch to destination (input 0 = target const/addr).
+ Branch,
+ /// Conditional branch: if in0 != 0 goto in1.
+ CBranch,
+ Call,
+ /// Return from call (optional return value in inputs).
+ Return,
+ /// Push value onto stack (modeled explicitly for early lift).
+ Push,
+ /// Pop into output varnode.
+ Pop,
+ /// ISA op not yet lifted — mnemonic preserved in [`PcodeOp::note`].
+ Unimplemented,
+}
+
+/// One IR operation (Ghidra `PcodeOp` analogue).
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct PcodeOp {
+ pub opcode: OpCode,
+ pub output: Option<Varnode>,
+ pub inputs: Vec<Varnode>,
+ /// Optional human note (e.g. original mnemonic for `Unimplemented`).
+ pub note: Option<String>,
+}
+
+impl PcodeOp {
+ pub fn new(opcode: OpCode, output: Option<Varnode>, inputs: Vec<Varnode>) -> Self {
+ Self {
+ opcode,
+ output,
+ inputs,
+ note: None,
+ }
+ }
+
+ pub fn with_note(mut self, note: impl Into<String>) -> Self {
+ self.note = Some(note.into());
+ self
+ }
+
+ pub fn unimplemented(mnemonic: impl Into<String>) -> Self {
+ Self::new(OpCode::Unimplemented, None, vec![]).with_note(mnemonic)
+ }
+}
+
+/// Placeholder basic block for future CFG / SSA work.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct BasicBlock {
+ pub id: u32,
+ /// Start address in the original image (if known).
+ pub start: Option<u64>,
+ pub ops: Vec<PcodeOp>,
+ /// Successor block ids (empty until CFG is built).
+ pub successors: Vec<u32>,
+}
+
+impl BasicBlock {
+ pub fn new(id: u32) -> Self {
+ Self {
+ id,
+ start: None,
+ ops: Vec::new(),
+ successors: Vec::new(),
+ }
+ }
+}
+
+/// Flat sequence of ops from lifting a linear instruction stream.
+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
+pub struct IrSequence {
+ pub ops: Vec<PcodeOp>,
+}
+
+impl IrSequence {
+ pub fn new() -> Self {
+ Self::default()
+ }
+
+ pub fn extend(&mut self, ops: impl IntoIterator<Item = PcodeOp>) {
+ self.ops.extend(ops);
+ }
+
+ pub fn len(&self) -> usize {
+ self.ops.len()
+ }
+
+ pub fn is_empty(&self) -> bool {
+ self.ops.is_empty()
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn varnode_helpers_and_copy_op() {
+ let dst = Varnode::register(0 /* rax */, 8);
+ let src = Varnode::register(4 /* rsp */, 8);
+ let op = PcodeOp::new(OpCode::Copy, Some(dst.clone()), vec![src.clone()]);
+ assert_eq!(op.opcode, OpCode::Copy);
+ assert_eq!(op.output.as_ref().unwrap().space, AddrSpace::Register);
+ assert_eq!(op.inputs[0].offset, 4);
+ }
+
+ #[test]
+ fn sequence_and_unimplemented() {
+ let mut seq = IrSequence::new();
+ seq.extend([
+ PcodeOp::new(OpCode::Push, None, vec![Varnode::register(5, 8)]),
+ PcodeOp::unimplemented("cpuid"),
+ ]);
+ assert_eq!(seq.len(), 2);
+ assert_eq!(seq.ops[1].opcode, OpCode::Unimplemented);
+ assert_eq!(seq.ops[1].note.as_deref(), Some("cpuid"));
+ }
+
+ #[test]
+ fn basic_block_placeholder() {
+ let mut bb = BasicBlock::new(0);
+ bb.start = Some(0x1000);
+ bb.ops.push(PcodeOp::new(OpCode::Return, None, vec![]));
+ assert!(bb.successors.is_empty());
+ assert_eq!(bb.ops[0].opcode, OpCode::Return);
+ }
+}
diff --git a/crates/ghidrust-lift/Cargo.toml b/crates/ghidrust-lift/Cargo.toml
new file mode 100644
index 0000000..1709d95
--- /dev/null
+++ b/crates/ghidrust-lift/Cargo.toml
@@ -0,0 +1,13 @@
+[package]
+name = "ghidrust-lift"
+version.workspace = true
+edition.workspace = true
+license.workspace = true
+description = "Lift decoded instructions to ghidrust-ir (x86-64 first)"
+
+[dependencies]
+ghidrust-decode = { workspace = true }
+ghidrust-ir = { workspace = true }
+
+[dev-dependencies]
+ghidrust-decode = { workspace = true }
diff --git a/crates/ghidrust-lift/src/lib.rs b/crates/ghidrust-lift/src/lib.rs
new file mode 100644
index 0000000..c40e9aa
--- /dev/null
+++ b/crates/ghidrust-lift/src/lib.rs
@@ -0,0 +1,252 @@
+//! Lift decoded machine instructions into [`ghidrust_ir`] (x86-64 first).
+//!
+//! Coverage is intentionally small: common control/stack/move forms used in
+//! fixtures and Stage-0 tests. Unhandled mnemonics become
+//! [`ghidrust_ir::OpCode::Unimplemented`]. Full SSA is out of scope here.
+
+use ghidrust_decode::Instruction;
+use ghidrust_ir::{IrSequence, OpCode, PcodeOp, Varnode};
+
+/// x86-64 GP register encoding (REX-aware index 0..15), matching Intel SDM.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+#[repr(u8)]
+pub enum X86Reg {
+ Rax = 0,
+ Rcx = 1,
+ Rdx = 2,
+ Rbx = 3,
+ Rsp = 4,
+ Rbp = 5,
+ Rsi = 6,
+ Rdi = 7,
+ R8 = 8,
+ R9 = 9,
+ R10 = 10,
+ R11 = 11,
+ R12 = 12,
+ R13 = 13,
+ R14 = 14,
+ R15 = 15,
+}
+
+impl X86Reg {
+ pub fn as_varnode(self, size: u32) -> Varnode {
+ Varnode::register(self as u64, size)
+ }
+}
+
+fn parse_reg(name: &str) -> Option<(X86Reg, u32)> {
+ let n = name.trim().to_ascii_lowercase();
+ let (reg, size) = match n.as_str() {
+ "rax" => (X86Reg::Rax, 8),
+ "eax" => (X86Reg::Rax, 4),
+ "ax" => (X86Reg::Rax, 2),
+ "al" => (X86Reg::Rax, 1),
+ "rcx" => (X86Reg::Rcx, 8),
+ "ecx" => (X86Reg::Rcx, 4),
+ "rdx" => (X86Reg::Rdx, 8),
+ "edx" => (X86Reg::Rdx, 4),
+ "rbx" => (X86Reg::Rbx, 8),
+ "ebx" => (X86Reg::Rbx, 4),
+ "rsp" => (X86Reg::Rsp, 8),
+ "esp" => (X86Reg::Rsp, 4),
+ "rbp" => (X86Reg::Rbp, 8),
+ "ebp" => (X86Reg::Rbp, 4),
+ "rsi" => (X86Reg::Rsi, 8),
+ "esi" => (X86Reg::Rsi, 4),
+ "rdi" => (X86Reg::Rdi, 8),
+ "edi" => (X86Reg::Rdi, 4),
+ "r8" => (X86Reg::R8, 8),
+ "r8d" => (X86Reg::R8, 4),
+ "r9" => (X86Reg::R9, 8),
+ "r9d" => (X86Reg::R9, 4),
+ "r10" => (X86Reg::R10, 8),
+ "r11" => (X86Reg::R11, 8),
+ "r12" => (X86Reg::R12, 8),
+ "r13" => (X86Reg::R13, 8),
+ "r14" => (X86Reg::R14, 8),
+ "r15" => (X86Reg::R15, 8),
+ _ => return None,
+ };
+ Some((reg, size))
+}
+
+fn parse_imm(s: &str) -> Option<u64> {
+ let s = s.trim();
+ if let Some(hex) = s.strip_prefix("0x").or_else(|| s.strip_prefix("0X")) {
+ u64::from_str_radix(hex, 16).ok()
+ } else {
+ s.parse().ok()
+ }
+}
+
+fn split_operands(ops: &str) -> Vec<&str> {
+ ops.split(',').map(str::trim).filter(|s| !s.is_empty()).collect()
+}
+
+fn is_jcc(mnem: &str) -> bool {
+ matches!(
+ mnem,
+ "jo" | "jno"
+ | "jb"
+ | "jae"
+ | "je"
+ | "jne"
+ | "jbe"
+ | "ja"
+ | "js"
+ | "jns"
+ | "jp"
+ | "jnp"
+ | "jl"
+ | "jge"
+ | "jle"
+ | "jg"
+ )
+}
+
+/// Lift a single decoded instruction to zero or more pcode-like ops.
+pub fn lift_instruction(insn: &Instruction) -> Vec<PcodeOp> {
+ let mnem = insn.mnemonic.as_str();
+ let parts = split_operands(&insn.operands);
+
+ match mnem {
+ "push" => {
+ if let Some((reg, size)) = parts.first().and_then(|p| parse_reg(p)) {
+ return vec![PcodeOp::new(OpCode::Push, None, vec![reg.as_varnode(size)])
+ .with_note(format!("{} {}", mnem, insn.operands))];
+ }
+ }
+ "pop" => {
+ if let Some((reg, size)) = parts.first().and_then(|p| parse_reg(p)) {
+ return vec![PcodeOp::new(
+ OpCode::Pop,
+ Some(reg.as_varnode(size)),
+ vec![],
+ )
+ .with_note(format!("{} {}", mnem, insn.operands))];
+ }
+ }
+ "ret" => {
+ let mut inputs = Vec::new();
+ if let Some(imm) = parts.first().and_then(|p| parse_imm(p)) {
+ inputs.push(Varnode::constant(imm, 2));
+ }
+ return vec![PcodeOp::new(OpCode::Return, None, inputs).with_note("ret")];
+ }
+ "mov" if parts.len() == 2 => {
+ if let (Some((dst, dsz)), Some((src, ssz))) =
+ (parse_reg(parts[0]), parse_reg(parts[1]))
+ {
+ let size = dsz.min(ssz);
+ return vec![PcodeOp::new(
+ OpCode::Copy,
+ Some(dst.as_varnode(size)),
+ vec![src.as_varnode(size)],
+ )
+ .with_note(format!("mov {}", insn.operands))];
+ }
+ if let (Some((dst, dsz)), Some(imm)) =
+ (parse_reg(parts[0]), parse_imm(parts[1]))
+ {
+ return vec![PcodeOp::new(
+ OpCode::Copy,
+ Some(dst.as_varnode(dsz)),
+ vec![Varnode::constant(imm, dsz)],
+ )
+ .with_note(format!("mov {}", insn.operands))];
+ }
+ }
+ "jmp" => {
+ if let Some(target) = parts.first().and_then(|p| parse_imm(p)) {
+ return vec![PcodeOp::new(
+ OpCode::Branch,
+ None,
+ vec![Varnode::constant(target, 8)],
+ )
+ .with_note("jmp")];
+ }
+ }
+ m if is_jcc(m) => {
+ if let Some(target) = parts.first().and_then(|p| parse_imm(p)) {
+ // Condition flag abstracted as unique temp until flag modeling exists.
+ let cond = Varnode::unique(0, 1);
+ return vec![PcodeOp::new(
+ OpCode::CBranch,
+ None,
+ vec![cond, Varnode::constant(target, 8)],
+ )
+ .with_note(m.to_string())];
+ }
+ }
+ _ => {}
+ }
+
+ vec![PcodeOp::unimplemented(format!(
+ "{} {}",
+ insn.mnemonic, insn.operands
+ ))]
+}
+
+/// Lift a slice of decoded instructions into a flat IR sequence.
+pub fn lift_instructions(insns: &[Instruction]) -> IrSequence {
+ let mut seq = IrSequence::new();
+ for insn in insns {
+ seq.extend(lift_instruction(insn));
+ }
+ seq
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use ghidrust_decode::{decode_bytes, decode_one};
+
+ #[test]
+ fn lift_push_mov_ret_fixture() {
+ // push rbp; mov rbp, rsp; ret
+ let bytes = [0x55, 0x48, 0x89, 0xe5, 0xc3];
+ let insns = decode_bytes(&bytes, 0x1000, 8).unwrap();
+ let seq = lift_instructions(&insns);
+ assert_eq!(seq.ops.len(), 3);
+ assert_eq!(seq.ops[0].opcode, OpCode::Push);
+ assert_eq!(seq.ops[0].inputs[0].offset, X86Reg::Rbp as u64);
+ assert_eq!(seq.ops[1].opcode, OpCode::Copy);
+ assert_eq!(seq.ops[1].output.as_ref().unwrap().offset, X86Reg::Rbp as u64);
+ assert_eq!(seq.ops[1].inputs[0].offset, X86Reg::Rsp as u64);
+ assert_eq!(seq.ops[2].opcode, OpCode::Return);
+ }
+
+ #[test]
+ fn lift_jcc_and_pop() {
+ // je rel8; pop rax — use synthetic Instruction for jcc target formatting
+ let je = Instruction {
+ address: 0x2000,
+ bytes: vec![0x74, 0x00],
+ mnemonic: "je".into(),
+ operands: "0x2010".into(),
+ length: 2,
+ };
+ let pop = decode_one(&[0x58], 0x2002).unwrap();
+ let seq = lift_instructions(&[je, pop]);
+ assert_eq!(seq.ops[0].opcode, OpCode::CBranch);
+ assert_eq!(seq.ops[0].note.as_deref(), Some("je"));
+ assert_eq!(seq.ops[0].inputs[1].offset, 0x2010);
+ assert_eq!(seq.ops[1].opcode, OpCode::Pop);
+ assert_eq!(seq.ops[1].output.as_ref().unwrap().offset, X86Reg::Rax as u64);
+ }
+
+ #[test]
+ fn unhandled_becomes_unimplemented() {
+ let insn = Instruction {
+ address: 0,
+ bytes: vec![0x90],
+ mnemonic: "nop".into(),
+ operands: String::new(),
+ length: 1,
+ };
+ let ops = lift_instruction(&insn);
+ assert_eq!(ops.len(), 1);
+ assert_eq!(ops[0].opcode, OpCode::Unimplemented);
+ }
+}
diff --git a/docs/GPU_DECOMPILER_RESEARCH.md b/docs/GPU_DECOMPILER_RESEARCH.md
index 62fff11..dd894ec 100644
--- a/docs/GPU_DECOMPILER_RESEARCH.md
+++ b/docs/GPU_DECOMPILER_RESEARCH.md
@@ -34,9 +34,13 @@ The open question for Ghidrust was:
4. **Correctness oracles**: multipass text equality (GPU vs CPU multipass) and structural opcode match vs classic `decompile_instructions`.
5. Honest **performance measurements** on production hardware (no fabricated speedups).
-### 1.3 Non-claims
+### 1.3 Non-claims / maturity
-This is **not** Hex-Rays / Ghidra parity (SSA, rich types, multi-ISA SLEIGH, recompilable C). It is **not** full x86 ISA emulation on the GPU as a general-purpose CPU substitute. It **is** full *Ghidrust* decompile stages on device with VRAM residency and a file dump.
+This paper covers **Stage-0 GPU multipass** only: the same CFG → goto / mnemonic-style pseudo-C pipeline as classic CPU `decompile_instructions`, run with mid-pipeline buffers in VRAM.
+
+- It is **not** a claim that Ghidrust already surpasses Ghidra or Hex-Rays on C quality (that is the product roadmap; SSA / structuring / typed C are **CPU** stages).
+- It is **not** full x86 ISA emulation on the GPU as a general-purpose CPU substitute.
+- It **is** full *Ghidrust Stage-0* decompile stages on device with VRAM residency and a file dump — a research path for bulk/shallow stages, not a substitute for the hand-rolled IR → SSA → typed-C pipeline.
---
@@ -199,7 +203,7 @@ Naïve designs that download IR after every instruction multiply PCIe cost by *N
### 6.2 Limitations
- Opcode coverage is a deliberate subset of the hand-rolled decoder (not full x86-64).
-- Emit is multipass normal form, not Hex-Rays-quality C.
+- Emit is Stage-0 multipass normal form (mnemonic scaffolding), not SSA/typed C or Hex-Rays-quality C.
- Cold-start wgpu pipeline cost is large relative to a 5-instruction function.
- Some stages remain single-threaded *on device* (decode walk, emit); parallelization of those stages is future work without abandoning residency.
@@ -208,7 +212,8 @@ Naïve designs that download IR after every instruction multiply PCIe cost by *N
- Persistent device/pipeline reuse across many functions
- Larger IR capacity and multi-function batch upload
- Wider opcode coverage shared with `ghidrust-core::disasm`
-- Optional SSA-lite passes still fully device-resident
+- Keep GPU focused on bulk seed / Stage-0 scan; **SSA structuring and typed emit stay on the CPU roadmap** (optional later IR-parallel GPU experiments only after that bar)
+
---
diff --git a/skill/SKILL.md b/skill/SKILL.md
index 569fb0a..e05630c 100644
--- a/skill/SKILL.md
+++ b/skill/SKILL.md
@@ -13,7 +13,7 @@ metadata:
# Ghidrust — agent skill
-Hand-rolled **Rust** reverse-engineering core (Ghidra-inspired labels). Prefer **CLI or MCP** for agents; GUI is for humans. **Never invent analysis** — if a fixture has no evidence, outputs are empty/honest.
+Hand-rolled **Rust** reverse-engineering core (Ghidra-inspired labels; measurable **Ghidra-surpass** target on x86-64, Stage-0 decompile today). Prefer **CLI or MCP** for agents; GUI is for humans. **Never invent analysis** — if a fixture has no evidence, outputs are empty/honest.
## Paths & binaries
@@ -58,8 +58,12 @@ Need RTTI CPU vs GPU timings (PCIe split)?
Need full matrix bench?
→ analyzer-bench / analyzer-bench-matrix
-Full Hex-Rays C decompiler?
- → NOT AVAILABLE. Use gpu-decompile multipass pseudo-C + listing.
+Need decompiled C?
+ → Staged capability (be honest about which stage you have):
+ Stage-0 (current): `decompile` / `gpu-decompile` → CFG→goto / mnemonic-style pseudo-C + listing
+ SSA-C (roadmap): structured if/while/switch pseudo-C after IR→SSA
+ typed-C (roadmap): locals/params/types; Ghidra-surpass bar before Hex-Rays-class ceiling
+ → Do not invent Hex-Rays-quality C; emit only what the current stage produces.
```
---
@@ -135,7 +139,7 @@ Add `--json` for structured stdout.
| List analyzers | `ghidrust analyzers` |
| **Analyze** | `ghidrust analyze <path> [--analyzers a,b \| --analyzer NAME …] [--gpu]` |
| Bulk bench | `ghidrust bulk-bench <path>` |
-| Decompile (CPU multipass-style) | `ghidrust decompile <path>` |
+| Decompile (CPU Stage-0 pseudo-C) | `ghidrust decompile <path>` |
| **GPU decompile** | `ghidrust gpu-decompile <path> [--out F] [--metrics F]` |
| RE bench | `ghidrust re-bench <path>` |
| Analyzer CPU/GPU matrix bench | `ghidrust analyzer-bench <path> [--large] [--out F]` |
@@ -225,7 +229,7 @@ ASCII Strings · Aggressive Instruction Finder · Call Convention ID · Call-Fix
**Do:** exact analyzer names; `--analyzer` or `--analyzers`; `--gpu` when GPU enrich wanted; `--json` for scripts; `analyzer-bench-matrix` for strategy list.
-**Don't:** invent decompiled C; claim Ghidra MCP is Ghidrust; skip empty-result honesty; conflate PCIe with on-device time.
+**Don't:** invent typed/Hex-Rays C beyond Stage-0 emit; claim Ghidra MCP is Ghidrust; claim Ghidra-surpass metrics without captured benches; skip empty-result honesty; conflate PCIe with on-device time.
---