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.

Enhance Ghidrust CLI and core functionality by setting Stage-1 as the default decompilation stage, with options for Stage-0 and Stage-0.5. Update command usage in documentation and improve JSON output structure for decompile and decompile-bench commands. Introduce parallel processing for Stage-1 decompilation, leveraging Rayon for performance improvements. Add support for equates and function tags in program edits, ensuring they persist through save/load operations.

oofzc31cd686859e
diff --git a/Cargo.lock b/Cargo.lock
index d7acf22..427cf5c 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1357,6 +1357,7 @@ dependencies = [
"ghidrust-structure",
"ghidrust-types",
"pollster",
+ "rayon",
"serde",
"serde_json",
"wgpu",
@@ -1372,6 +1373,8 @@ dependencies = [
"ghidrust-decomp",
"ghidrust-types",
"rfd",
+ "serde",
+ "serde_json",
]
[[package]]
diff --git a/README.md b/README.md
index 0dc2792..e5db9c1 100644
--- a/README.md
+++ b/README.md
@@ -19,7 +19,7 @@ It is **not** a Ghidra fork or wrapper. Analysis logic (loaders, decode, analyze
| **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 |
-**Current maturity:** Stage-0 CFG → goto / mnemonic-style pseudo-C is the default and regression oracle. **Stage-0.5** is opt-in (`decompile --stage05`) and emits IR-informed statements (`xor a,a → a=0`, augmented-assign, `push`/`pop`, direct `call`, flag-driven `jcc`) from the hand-rolled x86-64 lifter into `ghidrust-ir`, falling back to Stage-0 scaffolding for anything the lifter has not yet covered — **no fabricated C**. **Stage-1** (`decompile <path> --stage1` / GUI Decompiler stage picker) runs the full hand-rolled pipeline: `ghidrust-ssa` builds CFG + dominators + Cytron phi placement + a Cytron rename pass with copy-propagation, `ghidrust-structure` recovers `if`/`while`/`do-while`/`loop`/`return` regions (natural loops + iterative post-dominators), and `ghidrust-types` supplies a small type lattice (`Bottom`→`Bool`/`IntN`/`Ptr`→`Any`) with stack-local + x86-64 SysV/Windows integer-register parameter recovery. Stage-1 falls back to Stage-0.5-shaped scaffolding for irreducible regions or lift ratios <50% — again, no fabricated C. Head-to-head timings against Ghidra headless are captured (never fabricated) via `ghidrust ghidra-headtohead` and [`docs/GHIDRA_HEADTOHEAD.md`](docs/GHIDRA_HEADTOHEAD.md). Hex-Rays-class quality remains a later phase after the Ghidra bar is met. **Non-goals (today):** multi-ISA SLEIGH runtime, switch-statement structuring, debugger integration, or "GPU is always faster."
+**Current maturity (Phase F, pcode-parity plan):** **Stage-1 is the product default** on CLI, GUI, and MCP. It runs the full hand-rolled pipeline: `ghidrust-ssa` builds CFG + dominators + Cytron phi placement + rename + copy/const/load-store propagation + DCE; `ghidrust-structure` recovers gotoless `if`/`while`/`do-while`/`loop`/`switch`/short-circuit regions with `break;` / `continue;` inside natural loops (goto rate <0.15 on lab fixture); `ghidrust-types` supplies a lattice covering `Bool` / `IntN` / `IntSigned` / `Ptr` / `StructPtr` / `ArrayPtr` / `Void` / `Any`, recovers return type + Windows/SysV prototypes (register + stack params), stack locals, and struct/array pointer seeds from load/store patterns rendered as `p->field_<off>` / `p[i]`. **Stage-0** (`decompile --stage0`) and **Stage-0.5** (`--stage05`) remain as regression oracles; the Phase-E head-to-head oracle enforces a shared-entry set and Stage-1-vs-Ghidra normalized-token similarity metric so no unfair comparison ships. **Never fabricates C**: irreducible regions or lift ratios <50% — again, no fabricated C. Head-to-head timings against Ghidra headless are captured (never fabricated) via `ghidrust ghidra-headtohead` and [`docs/GHIDRA_HEADTOHEAD.md`](docs/GHIDRA_HEADTOHEAD.md). Hex-Rays-class quality remains a later phase after the Ghidra bar is met. **Non-goals (today):** multi-ISA SLEIGH runtime, switch-statement structuring, debugger integration, or "GPU is always faster."
---
@@ -172,10 +172,11 @@ Notes:
| Method | CLI | What it emits | Outputs / where to see them |
|---|---|---|---|
-| **Stage-0** (default) | `ghidrust decompile <path> [--addr HEX] [--count N]` | CFG-driven pseudo-C: `void FUN_<va>() { block_0: … goto/return; }` — mnemonic-style scaffolding, no fabricated locals or types. | stdout: `pseudo_c`. stderr status: `[name] stage=0 blocks=… edges=… insns=… lines=…`. `--json`: full `Decompile { name, blocks[], edges[], insn_count, pseudo_c }`. |
-| **Stage-0.5 IR** | `ghidrust decompile <path> --stage05 [--addr HEX] [--count N]` | IR-informed emit from the hand-rolled x86-64 lifter → `ghidrust-ir`: `xor a,a → a=0`, `add/sub/or/and/xor/shl/shr` augmented-assign, `push`/`pop`, direct `call`, flag-driven `jcc`. Falls back to Stage-0 scaffolding for uncovered ops. Pseudo-C header line is `// Ghidrust Stage-0.5 IR emit — function …`. | stdout: `pseudo_c`. stderr adds `ir_ops=… lift=…%`. `--json`: `{decompile: …, lift_coverage: {total_ops, unimplemented_ops, source_instructions, ratio}}`. |
-| **decompile-bench** | `ghidrust decompile-bench <path> [--functions N] [--count N] [--out FILE]` | Runs default analyzers, then for every discovered function runs Stage-0 and Stage-0.5 back-to-back: totals `insns`, `ir_ops`, per-stage `µs`, and average lift-ratio. | Text table on stdout (or JSON via `--json`); optional `--out FILE` writes the same. Eval report captured 6 functions / 33 insns / 48 IR ops / avg lift 0.96 on `analysis_lab.pe`. |
-| **ghidra-headtohead** | `ghidrust ghidra-headtohead <path> [--functions N] [--count N] [--ghidra DIR] [--captured JSON] [--out FILE]` | Optional Ghidra oracle: either runs Ghidra headless (`--ghidra DIR`) or loads pre-captured JSON (`--captured JSON`) and diffs Stage-0 / Stage-0.5 vs Ghidra decomp output. | Text or JSON report; no Ghidra install ⇒ report notes that both sides ran but oracle was unavailable. Useful for local Ghidra-surpass tracking, not shipped in the eval report. |
+| **Stage-1** (**default**) | `ghidrust decompile <path> [--addr HEX] [--count N]` | Full SSA + structure + types Stage-1 emit: recovered return type / SysV or Windows __fastcall prototype, `local_<off>: T` stack locals, `struct s_<key>{ field_<off>: T; }` seeds from load/store patterns rendered as `p->field_<off>` / `p[i]`, `switch { case … }` regions from Decompiler Switch Analysis, compound `&&` / `\|\|` short-circuits, and `break;` / `continue;` inside natural loops (goto rate <0.15 on lab). | stdout: `pseudo_c`. stderr status: `[name] stage=1 blocks=… phis=… loops=… locals=… params=… lift=…%`. `--json`: `{decompile: …, stage1: {loops, phis, locals, params, structs, lift_ratio, goto_rate, return_type, prototype, total_ops}}`. |
+| **Stage-0** (oracle) | `ghidrust decompile <path> --stage0 [--addr HEX] [--count N]` | CFG-driven pseudo-C: `void FUN_<va>() { block_0: … goto/return; }` — mnemonic-style scaffolding, no fabricated locals or types. Kept as regression oracle only. | stdout: `pseudo_c`. stderr status: `[name] stage=0 blocks=… edges=… insns=… lines=…`. `--json`: full `Decompile { name, blocks[], edges[], insn_count, pseudo_c }`. |
+| **Stage-0.5 IR** (oracle) | `ghidrust decompile <path> --stage05 [--addr HEX] [--count N]` | IR-informed emit from the hand-rolled x86-64 lifter → `ghidrust-ir`: `xor a,a → a=0`, `add/sub/or/and/xor/shl/shr` augmented-assign, `push`/`pop`, direct `call`, flag-driven `jcc`. Falls back to Stage-0 scaffolding for uncovered ops. | stdout: `pseudo_c`. stderr adds `ir_ops=… lift=…%`. `--json`: `{decompile: …, lift_coverage: {total_ops, unimplemented_ops, source_instructions, ratio}}`. |
+| **decompile-bench** | `ghidrust decompile-bench <path> [--functions N] [--count N] [--stage1] [--parallel] [--out FILE]` | Runs default analyzers, then benches Stage-0/0.5 (default) or Stage-1 (`--stage1`) across every discovered function; `--parallel` fans out per-entry Stage-1 across a rayon thread pool. | Text table (or JSON via `--json`); optional `--out FILE`. Report carries per-function `stage0_us`, `stage05_us`, `stage1_us`, `stage1_goto_count`, `stage1_leaf_count`, and per-function `pseudo_c` when Stage-1 is on. |
+| **ghidra-headtohead** (Phase E, fair) | `ghidrust ghidra-headtohead <path> [--functions N] [--count N] [--ghidra DIR] [--captured JSON] [--out FILE]` | Fair Ghidra oracle: shared-entry intersection with Ghidra `DecompInterface` output, per-row Stage-1 vs Ghidra normalized-token similarity, per-entry Stage-1 wall time. Without `--ghidra` / `--captured` the report is methodology-only. | Text or JSON; each row carries `token_similarity`, `ghidrust_stage1_us`, `ghidra_wall_us`. See [`docs/GHIDRA_HEADTOHEAD.md`](docs/GHIDRA_HEADTOHEAD.md). |
| **gpu-decompile** | `ghidrust gpu-decompile <path> [--out FILE] [--metrics FILE]` | Full **GPU-resident** VRAM multipass decompile of the entry function: decode → leaders → blocks → emit kernels; single final download; asserts `mid_pipeline_host_reads == 0` and multipass-CPU equivalence. | `.gdecomp` binary dump at `--out`. stdout: pseudo-C. `--json` / `--metrics FILE` produces `{gpu_backend, gpu_device, gpu_ms, mid_pipeline_host_reads, kernels, dump_path, dump_bytes, gpu_ir_count, gpu_block_count, gpu_edge_count, equivalence_multipass, pseudo_c_head}`. Non-zero exit if equivalence fails or a mid-pipeline host read is observed. |
| **re-bench** | `ghidrust re-bench <path> [--out FILE]` | CPU decompile of the entry + bulk RE on a padded haystack, once on CPU (parallel) and once on GPU / fallback; asserts equal bulk hit counts. | Text report to stdout (or JSON with `--json` / `--out`). Fields: `decompile_cpu {backend, ms, entry, name, blocks, edges, insns, lines, chars, pseudo_c_head}`, `bulk_cpu`, `bulk_gpu` (each: `mode, backend, ms, hits, haystack_bytes`), plus `note` explaining that decompile stays on CPU. |
diff --git a/crates/ghidrust-cli/src/main.rs b/crates/ghidrust-cli/src/main.rs
index e8ded84..04444d7 100644
--- a/crates/ghidrust-cli/src/main.rs
+++ b/crates/ghidrust-cli/src/main.rs
@@ -66,8 +66,8 @@ fn print_help() {
ghidrust analyzers [--json]\n\
ghidrust analyze <path> [--analyzers a,b | --analyzer NAME ...] [--gpu] [--json]\n\
ghidrust bulk-bench <path> [--json] # seq vs parallel vs GPU/fallback timings\n\
- ghidrust decompile <path> [--addr HEX] [--count N] [--stage05|--stage1] [--json]\n\
- ghidrust decompile-bench <path> [--functions N] [--count N] [--out FILE] [--json]\n\
+ ghidrust decompile <path> [--addr HEX] [--count N] [--stage0|--stage05|--stage1 (default)] [--json]\n\
+ ghidrust decompile-bench <path> [--functions N] [--count N] [--out FILE] [--stage1] [--parallel] [--json]\n\
ghidrust ghidra-headtohead <path> [--functions N] [--count N] [--ghidra DIR] [--captured JSON] [--out FILE] [--spawn-timeout SECS] [--ghidra-fn-cap N] [--json]\n\
ghidrust gpu-decompile <path> [--out FILE] [--metrics FILE] [--json]\n\
ghidrust re-bench <path> [--out FILE] [--json] # CPU then GPU metrics (decomp+bulk)\n\
@@ -941,15 +941,19 @@ fn cmd_decompile(args: &[String], json: bool) -> ExitCode {
Some(p) => PathBuf::from(p),
None => {
eprintln!(
- "usage: ghidrust decompile <path> [--addr HEX] [--count N] [--stage05] [--json]"
+ "usage: ghidrust decompile <path> [--addr HEX] [--count N] [--stage0|--stage05|--stage1] [--json]"
);
return ExitCode::from(2);
}
};
let mut addr: Option<u64> = None;
let mut count: usize = 64;
+ // Phase F: Stage-1 is the product default. `--stage0` / `--stage05`
+ // opt out for oracle / regression comparisons; explicit `--stage1`
+ // is accepted for symmetry.
let mut stage05 = false;
- let mut stage1 = false;
+ let mut stage0 = false;
+ let mut stage1 = true;
let mut i = 1;
while i < args.len() {
match args[i].as_str() {
@@ -961,17 +965,27 @@ fn cmd_decompile(args: &[String], json: bool) -> ExitCode {
count = args[i + 1].parse().unwrap_or(64);
i += 2;
}
+ "--stage0" | "--stage-0" | "--legacy" => {
+ stage0 = true;
+ stage1 = false;
+ stage05 = false;
+ i += 1;
+ }
"--stage05" | "--stage-0.5" | "--ir" => {
stage05 = true;
+ stage1 = false;
i += 1;
}
"--stage1" | "--stage-1" | "--ssa" => {
stage1 = true;
+ stage05 = false;
+ stage0 = false;
i += 1;
}
_ => i += 1,
}
}
+ let _ = stage0; // suppressed; retained for future gating
match load_path(&path) {
Ok(prog) => {
let va = addr.unwrap_or_else(|| prog.entry.unwrap_or(prog.image_base));
@@ -1089,7 +1103,7 @@ fn cmd_decompile_bench(args: &[String], json: bool) -> ExitCode {
Some(p) => PathBuf::from(p),
None => {
eprintln!(
- "usage: ghidrust decompile-bench <path> [--functions N] [--count N] [--out FILE] [--json]"
+ "usage: ghidrust decompile-bench <path> [--functions N] [--count N] [--out FILE] [--stage1] [--parallel] [--json]"
);
return ExitCode::from(2);
}
@@ -1097,6 +1111,12 @@ fn cmd_decompile_bench(args: &[String], json: bool) -> ExitCode {
let mut max_functions: usize = 32;
let mut count: usize = 128;
let mut out_path: Option<PathBuf> = None;
+ // Phase F: `--stage1` opts into the Stage-1 bench (SSA + structure +
+ // types) with per-entry pseudo-C text captured. `--parallel` runs the
+ // per-entry Stage-1 pipeline across a rayon thread pool. Both default
+ // off to keep back-compat with the shipped decompile-bench numbers.
+ let mut stage1 = false;
+ let mut parallel = false;
let mut i = 1;
while i < args.len() {
match args[i].as_str() {
@@ -1112,6 +1132,15 @@ fn cmd_decompile_bench(args: &[String], json: bool) -> ExitCode {
out_path = Some(PathBuf::from(&args[i + 1]));
i += 2;
}
+ "--stage1" | "--stage-1" => {
+ stage1 = true;
+ i += 1;
+ }
+ "--parallel" | "--rayon" => {
+ parallel = true;
+ stage1 = true;
+ i += 1;
+ }
_ => i += 1,
}
}
@@ -1122,10 +1151,19 @@ fn cmd_decompile_bench(args: &[String], json: bool) -> ExitCode {
return ExitCode::FAILURE;
}
};
- // Run default analyzers so `decompile-bench` picks up whatever functions
- // the analyzer stack recovers; missing functions falls back to entry.
let _ = ghidrust_core::run_analyzers(&mut prog, &[]);
- let report = ghidrust_decomp::bench_program(&prog, max_functions, count);
+ let conv = if prog.format.to_ascii_lowercase().contains("pe") {
+ ghidrust_types::CallConv::Windows
+ } else {
+ ghidrust_types::CallConv::SystemV
+ };
+ let report = if stage1 && parallel {
+ ghidrust_decomp::bench_program_stage1_parallel(&prog, None, max_functions, count, conv)
+ } else if stage1 {
+ ghidrust_decomp::bench_program_stage1(&prog, None, max_functions, count, conv)
+ } else {
+ ghidrust_decomp::bench_program(&prog, max_functions, count)
+ };
let output = if json { report.to_json() } else { report.to_text() };
if let Some(path) = out_path {
if let Err(e) = std::fs::write(&path, &output) {
@@ -1688,6 +1726,24 @@ fn tool_defs() -> Vec<ToolDef> {
description: "Per-analyzer GPU strategy matrix (all Auto Analysis + decompile)",
input_schema: json!({ "type": "object", "properties": {} }),
},
+ ToolDef {
+ name: "decompile",
+ description: "Decompile function to structured C. Defaults to Stage-1 (SSA + types + structure). Pass stage='stage0' or 'stage05' for oracle output.",
+ input_schema: json!({
+ "type": "object",
+ "properties": {
+ "path": { "type": "string" },
+ "addr": { "type": "string", "description": "Function entry VA in hex (default: program entry)" },
+ "count": { "type": "integer", "description": "Max instructions to decode (default: 64)" },
+ "stage": {
+ "type": "string",
+ "enum": ["stage0", "stage05", "stage1"],
+ "description": "Emit stage. Default 'stage1' — full SSA + types + structure."
+ }
+ },
+ "required": ["path"]
+ }),
+ },
ToolDef {
name: "gpu_decompile",
description: "GPU-resident multipass decompile of entry; returns dump metrics (PCIe/device when available)",
@@ -1861,6 +1917,82 @@ fn call_tool(params: &Value) -> Result<String, String> {
}))
.unwrap())
}
+ "decompile" => {
+ let path = args
+ .get("path")
+ .and_then(|p| p.as_str())
+ .ok_or_else(|| "missing arguments.path".to_string())?;
+ let count = args.get("count").and_then(|c| c.as_u64()).unwrap_or(64) as usize;
+ let stage = args
+ .get("stage")
+ .and_then(|s| s.as_str())
+ .unwrap_or("stage1");
+ let prog = load_path(path).map_err(|e| e.to_string())?;
+ let va = if let Some(a) = args.get("addr").and_then(|a| a.as_str()) {
+ parse_u64(a)?
+ } else {
+ prog.entry.unwrap_or(prog.image_base)
+ };
+ let conv = if prog.format.to_ascii_lowercase().contains("pe") {
+ ghidrust_types::CallConv::Windows
+ } else {
+ ghidrust_types::CallConv::SystemV
+ };
+ match stage {
+ "stage0" | "stage-0" => {
+ let d =
+ ghidrust_decomp::decompile_at(&prog, va, count).map_err(|e| e.to_string())?;
+ Ok(serde_json::to_string_pretty(&json!({
+ "stage": "0",
+ "name": d.name,
+ "entry": format!("{:#x}", d.entry),
+ "blocks": d.blocks.len(),
+ "edges": d.edges.len(),
+ "insns": d.insn_count,
+ "pseudo_c": d.pseudo_c,
+ }))
+ .unwrap())
+ }
+ "stage05" | "stage-0.5" | "ir" => {
+ let (d, cov) = ghidrust_decomp::decompile_ir_at(&prog, va, count)
+ .map_err(|e| e.to_string())?;
+ Ok(serde_json::to_string_pretty(&json!({
+ "stage": "0.5",
+ "name": d.name,
+ "entry": format!("{:#x}", d.entry),
+ "blocks": d.blocks.len(),
+ "edges": d.edges.len(),
+ "insns": d.insn_count,
+ "lift_ratio": cov.ratio(),
+ "pseudo_c": d.pseudo_c,
+ }))
+ .unwrap())
+ }
+ _ => {
+ // Default (Phase F): Stage-1 full pipeline.
+ let (d, s1) = ghidrust_decomp::decompile_stage1_at(&prog, va, count, conv)
+ .map_err(|e| e.to_string())?;
+ Ok(serde_json::to_string_pretty(&json!({
+ "stage": "1",
+ "name": d.name,
+ "entry": format!("{:#x}", d.entry),
+ "blocks": d.blocks.len(),
+ "insns": d.insn_count,
+ "loops": s1.structure.loops.len(),
+ "phis": s1.ssa.phi_count(),
+ "locals": s1.types.locals.len(),
+ "params": s1.types.params.len(),
+ "structs": s1.types.structs.len(),
+ "lift_ratio": s1.coverage.ratio(),
+ "goto_rate": s1.summary().goto_rate,
+ "return_type": s1.types.signature.return_type.c_style(),
+ "prototype": s1.types.signature.to_prototype(),
+ "pseudo_c": d.pseudo_c,
+ }))
+ .unwrap())
+ }
+ }
+ }
"load" | "disassemble" | "rtti" | "analyze" => {
let path = args
.get("path")
diff --git a/crates/ghidrust-cli/tests/eval_analysis_decompile.rs b/crates/ghidrust-cli/tests/eval_analysis_decompile.rs
index ea401b1..65d73f9 100644
--- a/crates/ghidrust-cli/tests/eval_analysis_decompile.rs
+++ b/crates/ghidrust-cli/tests/eval_analysis_decompile.rs
@@ -497,11 +497,13 @@ fn eval_one_analyzer(check: &AnalyzerCheck) -> EvalRow {
fn eval_decompile_stage0(fixture: &str) -> EvalRow {
let path = fixture_path(fixture);
let path_s = path.to_string_lossy().into_owned();
+ // Stage-1 is the CLI default (Phase F); this row still exercises the
+ // Stage-0 oracle path via the explicit flag.
let (ok, stdout, stderr, ms) =
- run_ghidrust(&["decompile", &path_s, "--count", "128", "--json"]);
+ run_ghidrust(&["decompile", &path_s, "--count", "128", "--stage0", "--json"]);
let mut row = EvalRow {
kind: "decompile",
- name: "Stage-0 (ghidrust decompile)".into(),
+ name: "Stage-0 (ghidrust decompile --stage0)".into(),
fixture: fixture.into(),
status: "FAIL",
ran: true,
diff --git a/crates/ghidrust-cli/tests/re_bench.rs b/crates/ghidrust-cli/tests/re_bench.rs
index 405359b..2d0069d 100644
--- a/crates/ghidrust-cli/tests/re_bench.rs
+++ b/crates/ghidrust-cli/tests/re_bench.rs
@@ -18,6 +18,10 @@ fn fixture(name: &str) -> PathBuf {
#[test]
fn decompile_tiny_pe_nonempty_structure() {
+ // Phase F: the CLI default is Stage-1. JSON now nests under
+ // `decompile.*` with an extra `stage1` sibling. Assert against the
+ // Stage-1 shape but accept either nesting so ports of this test
+ // that override with `--stage0` still pass.
let out = Command::new(bin())
.args([
"decompile",
@@ -32,12 +36,28 @@ fn decompile_tiny_pe_nonempty_structure() {
String::from_utf8_lossy(&out.stderr)
);
let v: serde_json::Value = serde_json::from_slice(&out.stdout).expect("json");
- assert!(v["pseudo_c"].as_str().unwrap_or("").contains("void "));
- assert!(v["blocks"]
+ // Both stage shapes carry a `pseudo_c` — top-level for Stage-0, under
+ // `decompile.pseudo_c` for Stage-0.5 / Stage-1.
+ let pseudo = v["pseudo_c"]
+ .as_str()
+ .or_else(|| v["decompile"]["pseudo_c"].as_str())
+ .unwrap_or("");
+ assert!(
+ pseudo.contains("void ") || pseudo.contains("uint")
+ || pseudo.contains("int32_t") || pseudo.contains("int64_t"),
+ "expected typed function header, got:\n{pseudo}"
+ );
+ let blocks = v["blocks"]
.as_array()
+ .or_else(|| v["decompile"]["blocks"].as_array())
.map(|a| !a.is_empty())
- .unwrap_or(false));
- assert!(v["insn_count"].as_u64().unwrap_or(0) > 0);
+ .unwrap_or(false);
+ assert!(blocks, "expected non-empty blocks");
+ let insns = v["insn_count"]
+ .as_u64()
+ .or_else(|| v["decompile"]["insn_count"].as_u64())
+ .unwrap_or(0);
+ assert!(insns > 0);
}
#[test]
diff --git a/crates/ghidrust-core/src/edits.rs b/crates/ghidrust-core/src/edits.rs
index e8de911..19ce5f1 100644
--- a/crates/ghidrust-core/src/edits.rs
+++ b/crates/ghidrust-core/src/edits.rs
@@ -10,7 +10,7 @@
//! [`Program::display_name_at`] / [`Program::display_function_name_at`].
use serde::{Deserialize, Serialize};
-use std::collections::BTreeMap;
+use std::collections::{BTreeMap, BTreeSet};
use crate::program::Program;
@@ -72,6 +72,20 @@ pub struct RetypeEdit {
pub type_desc: String,
}
+/// One record for an equate — Ghidra `EquateTablePlugin` binds a symbolic name
+/// to a scalar so the Listing can render `MY_FLAG` instead of `0x1234`.
+///
+/// Equates are attached to a (VA, operand-index) pair rather than to the raw
+/// value so a single number can be renamed in one place without recolouring
+/// every occurrence in the program.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct EquateEdit {
+ /// Ghidra display name (e.g. `SW_HIDE`, `O_RDONLY`).
+ pub name: String,
+ /// Underlying scalar value the equate stands in for.
+ pub value: i64,
+}
+
/// Side-car user-edit store for a [`Program`].
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ProgramEdits {
@@ -97,6 +111,55 @@ pub struct ProgramEdits {
/// User-applied types at specific VAs (Listing "Data Type" apply).
#[serde(default)]
pub applied_types: BTreeMap<u64, String>,
+ /// Equates keyed by `(va, op_index)` — Ghidra `EquateTablePlugin` model.
+ ///
+ /// Serialized as a flat `Vec` because JSON map keys must be strings.
+ #[serde(default, with = "equates_serde")]
+ pub equates: BTreeMap<(u64, u8), EquateEdit>,
+ /// Per-function tags (Ghidra `FunctionTagPlugin`). Keyed by function entry VA.
+ #[serde(default)]
+ pub function_tags: BTreeMap<u64, BTreeSet<String>>,
+ /// The universe of tags the user has ever created — retained even when no
+ /// function currently uses them so the "All Tags" pane keeps them listed.
+ #[serde(default)]
+ pub all_function_tags: BTreeSet<String>,
+}
+
+/// Serde helper — turns the equates map into a flat `Vec` so JSON
+/// (string-keyed) and bincode (any-keyed) can round-trip it identically.
+mod equates_serde {
+ use super::EquateEdit;
+ use serde::{Deserialize, Deserializer, Serialize, Serializer};
+ use std::collections::BTreeMap;
+
+ #[derive(Serialize, Deserialize)]
+ struct Row {
+ va: u64,
+ op: u8,
+ edit: EquateEdit,
+ }
+
+ pub fn serialize<S: Serializer>(
+ map: &BTreeMap<(u64, u8), EquateEdit>,
+ ser: S,
+ ) -> Result<S::Ok, S::Error> {
+ let rows: Vec<Row> = map
+ .iter()
+ .map(|((va, op), edit)| Row {
+ va: *va,
+ op: *op,
+ edit: edit.clone(),
+ })
+ .collect();
+ rows.serialize(ser)
+ }
+
+ pub fn deserialize<'de, D: Deserializer<'de>>(
+ de: D,
+ ) -> Result<BTreeMap<(u64, u8), EquateEdit>, D::Error> {
+ let rows: Vec<Row> = Vec::deserialize(de)?;
+ Ok(rows.into_iter().map(|r| ((r.va, r.op), r.edit)).collect())
+ }
}
/// Serde helper — turns the comments map into `Vec<(u64, CommentKind, String)>`
@@ -282,7 +345,127 @@ impl ProgramEdits {
function_signatures: self.function_signatures.len(),
user_types: self.user_types.len(),
applied_types: self.applied_types.len(),
+ equates: self.equates.len(),
+ function_tags: self.function_tags.values().map(|s| s.len()).sum(),
+ }
+ }
+
+ // ─── Equates (Ghidra `EquateTablePlugin`) ────────────────────────────
+
+ /// Attach an equate at `(va, op_index)`.
+ pub fn set_equate(&mut self, va: u64, op: u8, name: impl Into<String>, value: i64) {
+ let name = name.into();
+ if name.is_empty() {
+ self.equates.remove(&(va, op));
+ } else {
+ self.equates.insert((va, op), EquateEdit { name, value });
+ }
+ }
+
+ pub fn equate_at(&self, va: u64, op: u8) -> Option<&EquateEdit> {
+ self.equates.get(&(va, op))
+ }
+
+ /// Every occurrence of the equate `name` in the program.
+ ///
+ /// Returned rows share `(name, value)` and are ordered by (va, op) so the
+ /// Equates Table reference pane can render them stably.
+ pub fn equate_references(&self, name: &str) -> Vec<(u64, u8, i64)> {
+ self.equates
+ .iter()
+ .filter(|(_, e)| e.name == name)
+ .map(|((va, op), e)| (*va, *op, e.value))
+ .collect()
+ }
+
+ /// Grouped list of `(name, value, ref_count)` rows for the Equates Table's
+ /// left pane. Sorted alphabetically by name so the table is deterministic.
+ pub fn equate_groups(&self) -> Vec<(String, i64, usize)> {
+ let mut groups: BTreeMap<(String, i64), usize> = BTreeMap::new();
+ for edit in self.equates.values() {
+ *groups.entry((edit.name.clone(), edit.value)).or_insert(0) += 1;
+ }
+ groups
+ .into_iter()
+ .map(|((name, value), n)| (name, value, n))
+ .collect()
+ }
+
+ // ─── Function Tags (Ghidra `FunctionTagPlugin`) ─────────────────────
+
+ /// Whether `entry` currently has `tag` assigned.
+ pub fn function_has_tag(&self, entry: u64, tag: &str) -> bool {
+ self.function_tags
+ .get(&entry)
+ .map(|s| s.contains(tag))
+ .unwrap_or(false)
+ }
+
+ /// Assign `tag` to the function at `entry`.
+ pub fn add_function_tag(&mut self, entry: u64, tag: impl Into<String>) {
+ let tag = tag.into();
+ if tag.trim().is_empty() {
+ return;
}
+ self.all_function_tags.insert(tag.clone());
+ self.function_tags
+ .entry(entry)
+ .or_default()
+ .insert(tag);
+ }
+
+ /// Remove `tag` from the function at `entry`. Does not remove the tag from
+ /// [`ProgramEdits::all_function_tags`] (so the "All Tags" pane keeps it).
+ pub fn remove_function_tag(&mut self, entry: u64, tag: &str) -> bool {
+ let removed = self
+ .function_tags
+ .get_mut(&entry)
+ .map(|s| s.remove(tag))
+ .unwrap_or(false);
+ if let Some(set) = self.function_tags.get_mut(&entry) {
+ if set.is_empty() {
+ self.function_tags.remove(&entry);
+ }
+ }
+ removed
+ }
+
+ /// Assigned tags for `entry`, sorted alphabetically.
+ pub fn function_tags_for(&self, entry: u64) -> Vec<String> {
+ self.function_tags
+ .get(&entry)
+ .map(|s| s.iter().cloned().collect())
+ .unwrap_or_default()
+ }
+
+ /// Delete a tag globally — removes it from every function and from the
+ /// universe of known tags. Returns the number of functions the tag was
+ /// removed from.
+ pub fn delete_tag_everywhere(&mut self, tag: &str) -> usize {
+ let mut n = 0;
+ let entries: Vec<u64> = self.function_tags.keys().copied().collect();
+ for entry in entries {
+ if self.remove_function_tag(entry, tag) {
+ n += 1;
+ }
+ }
+ self.all_function_tags.remove(tag);
+ n
+ }
+
+ /// `(tag, count)` rows for the "All Tags" pane. Sorted alphabetically.
+ pub fn all_tag_counts(&self) -> Vec<(String, usize)> {
+ let mut counts: BTreeMap<String, usize> = self
+ .all_function_tags
+ .iter()
+ .map(|t| (t.clone(), 0))
+ .collect();
+ for tags in self.function_tags.values() {
+ for t in tags {
+ *counts.entry(t.clone()).or_insert(0) += 1;
+ }
+ }
+ counts.into_iter().collect()
}
}
@@ -294,6 +477,8 @@ pub struct ProgramEditTotals {
pub function_signatures: usize,
pub user_types: usize,
pub applied_types: usize,
+ pub equates: usize,
+ pub function_tags: usize,
}
impl Program {
@@ -431,6 +616,66 @@ mod tests {
assert_eq!(t.comments, 1);
}
+ #[test]
+ fn equates_group_and_reference_across_addresses() {
+ let mut e = ProgramEdits::default();
+ e.set_equate(0x1000, 1, "SW_HIDE", 0);
+ e.set_equate(0x1010, 1, "SW_HIDE", 0);
+ e.set_equate(0x1020, 1, "SW_SHOW", 5);
+ let groups = e.equate_groups();
+ assert_eq!(groups.len(), 2);
+ let (name, value, n) = groups
+ .iter()
+ .find(|(n, _, _)| n == "SW_HIDE")
+ .cloned()
+ .unwrap();
+ assert_eq!((name.as_str(), value, n), ("SW_HIDE", 0, 2));
+ // Reference table for the equate.
+ let refs = e.equate_references("SW_HIDE");
+ assert_eq!(refs.len(), 2);
+ assert!(refs.iter().any(|(va, _, _)| *va == 0x1010));
+ // Setting the name to empty clears the equate.
+ e.set_equate(0x1000, 1, "", 0);
+ assert!(e.equate_at(0x1000, 1).is_none());
+ }
+
+ #[test]
+ fn function_tags_assign_remove_and_delete_everywhere() {
+ let mut e = ProgramEdits::default();
+ e.add_function_tag(0x1000, "MALLOC");
+ e.add_function_tag(0x2000, "MALLOC");
+ e.add_function_tag(0x1000, "SANITIZED");
+ assert!(e.function_has_tag(0x1000, "MALLOC"));
+ assert!(e.function_has_tag(0x1000, "SANITIZED"));
+ assert!(e.function_has_tag(0x2000, "MALLOC"));
+ // Tag universe includes both.
+ let counts = e.all_tag_counts();
+ assert_eq!(counts.iter().find(|(t, _)| t == "MALLOC").unwrap().1, 2);
+ // Remove a single (entry, tag) association.
+ assert!(e.remove_function_tag(0x1000, "SANITIZED"));
+ assert!(!e.function_has_tag(0x1000, "SANITIZED"));
+ // The tag persists in the universe until explicitly deleted.
+ assert!(e.all_function_tags.contains("SANITIZED"));
+ // Delete a tag globally.
+ let n = e.delete_tag_everywhere("MALLOC");
+ assert_eq!(n, 2);
+ assert!(!e.function_has_tag(0x2000, "MALLOC"));
+ assert!(!e.all_function_tags.contains("MALLOC"));
+ }
+
+ #[test]
+ fn totals_include_equates_and_function_tags() {
+ let mut e = ProgramEdits::default();
+ e.set_equate(0x100, 0, "A", 1);
+ e.set_equate(0x104, 0, "B", 2);
+ e.add_function_tag(0x1000, "T1");
+ e.add_function_tag(0x1000, "T2");
+ e.add_function_tag(0x2000, "T1");
+ let t = e.totals();
+ assert_eq!(t.equates, 2);
+ assert_eq!(t.function_tags, 3);
+ }
+
#[test]
fn builtin_types_include_essentials() {
let want = ["void", "byte", "word", "dword", "qword", "char", "int", "pointer"];
diff --git a/crates/ghidrust-core/src/lib.rs b/crates/ghidrust-core/src/lib.rs
index eedb10b..4ad5005 100644
--- a/crates/ghidrust-core/src/lib.rs
+++ b/crates/ghidrust-core/src/lib.rs
@@ -12,6 +12,7 @@ pub mod program;
pub mod project;
pub mod rtti;
pub mod theme;
+pub mod xrefs;
pub use analyzers::{
analyzer_catalog, run_analyzers, run_analyzers_opts, scan_ascii_strings, AnalysisRunReport,
@@ -32,7 +33,8 @@ pub use gpu_analyzers::{
};
pub use disasm::{decode_one, disassemble_at, disassemble_range, Instruction};
pub use edits::{
- CommentKind, FunctionSignatureEdit, ProgramEditTotals, ProgramEdits, RetypeEdit, BUILTIN_TYPES,
+ CommentKind, EquateEdit, FunctionSignatureEdit, ProgramEditTotals, ProgramEdits, RetypeEdit,
+ BUILTIN_TYPES,
};
pub use error::{Error, Result};
pub use program::{
@@ -46,6 +48,7 @@ pub use project::{
};
pub use rtti::{recover_rtti, RttiClass, RttiReport};
pub use theme::{m3_tokens, ThemeMode, M3Tokens};
+pub use xrefs::{operand_addresses, xrefs_from, xrefs_to, XRef};
use std::path::{Path, PathBuf};
diff --git a/crates/ghidrust-core/src/project.rs b/crates/ghidrust-core/src/project.rs
index 9b22a18..347d66b 100644
--- a/crates/ghidrust-core/src/project.rs
+++ b/crates/ghidrust-core/src/project.rs
@@ -707,6 +707,11 @@ mod tests {
prog.edits
.set_user_type("Widget", "struct Widget { int id; }");
prog.edits.set_applied_type(va, "Widget");
+ // Phase D (M4) — equates and function tags must also round-trip.
+ prog.edits.set_equate(va, 1, "SW_HIDE", 0);
+ prog.edits.set_equate(va + 0x10, 1, "SW_HIDE", 0);
+ prog.edits.add_function_tag(va, "MALLOC");
+ prog.edits.add_function_tag(va, "SANITIZED");
let listing = disassemble_range(&prog, va, 8).unwrap_or_default();
proj.save_program_results(&entry.id, &prog, &listing, &["Function Start Search".into()])
@@ -743,6 +748,15 @@ mod tests {
prog2.function_at(va).map(|f| f.name.as_str()),
Some("my_main")
);
+ // Phase D (M4) — equates and function tags survive save/load.
+ assert_eq!(
+ prog2.edits.equate_at(va, 1).map(|e| e.name.as_str()),
+ Some("SW_HIDE")
+ );
+ assert_eq!(prog2.edits.equate_references("SW_HIDE").len(), 2);
+ assert!(prog2.edits.function_has_tag(va, "MALLOC"));
+ assert!(prog2.edits.function_has_tag(va, "SANITIZED"));
+ assert!(prog2.edits.all_function_tags.contains("MALLOC"));
let _ = fs::remove_dir_all(&dir);
}
diff --git a/crates/ghidrust-core/src/xrefs.rs b/crates/ghidrust-core/src/xrefs.rs
new file mode 100644
index 0000000..5da47a4
--- /dev/null
+++ b/crates/ghidrust-core/src/xrefs.rs
@@ -0,0 +1,218 @@
+//! Program cross-references (Ghidra `Symbol References` provider).
+//!
+//! Ghidrust does not (yet) run a full flow analyzer that populates every
+//! `to`/`from` reference the way Ghidra does. This module rebuilds an
+//! approximate xref graph on demand from three honest sources:
+//!
+//! 1. `Program::analysis.references` — real refs deposited by the address-table
+//! and resource analyzers.
+//! 2. `Program::analysis.address_tables` — pointer tables where every entry is
+//! a load-time reference.
+//! 3. Decoded x86-64 instructions in a supplied listing — any operand hex
+//! literal that lands inside a mapped memory block is treated as a
+//! reference of kind `data`/`code`/`call`/`jmp` inferred from the mnemonic.
+//!
+//! No refs are ever fabricated: if the source disagrees, the source wins.
+
+use crate::disasm::disassemble_range;
+use crate::program::Program;
+
+/// One cross-reference row rendered by the GUI's Symbol References pane.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct XRef {
+ /// Source VA (where the reference originates).
+ pub from: u64,
+ /// Target VA (where the reference points at).
+ pub to: u64,
+ /// Ghidra-analog kind (`call`, `jmp`, `cond_jmp`, `data`, `ptr_table`,
+ /// `resource`, `xref`).
+ pub kind: &'static str,
+ /// Ghidra "From Preview" — mnemonic/operand text where computable.
+ pub preview: String,
+}
+
+/// Compute references **to** `target` from three honest sources.
+///
+/// `hint_listing` is an optional pre-computed instruction slice used to
+/// enrich results with mnemonic-derived kinds; when `None`, only analyzer
+/// output is consulted. The caller is expected to pass a listing that spans
+/// the executable blocks of interest (typically the whole loaded window).
+pub fn xrefs_to(
+ prog: &Program,
+ target: u64,
+ hint_listing: Option<&[crate::disasm::Instruction]>,
+) -> Vec<XRef> {
+ let mut out = Vec::new();
+
+ for r in &prog.analysis.references {
+ if r.to == target {
+ out.push(XRef {
+ from: r.from,
+ to: r.to,
+ kind: static_kind(&r.kind),
+ preview: r.kind.clone(),
+ });
+ }
+ }
+
+ for tbl in &prog.analysis.address_tables {
+ for (i, entry) in tbl.entries.iter().enumerate() {
+ if *entry == target {
+ let from = tbl.base + (i as u64) * 8;
+ out.push(XRef {
+ from,
+ to: target,
+ kind: "ptr_table",
+ preview: format!("[{}] {:#x}", i, target),
+ });
+ }
+ }
+ }
+
+ if let Some(listing) = hint_listing {
+ for insn in listing {
+ if operand_addresses(&insn.operands).contains(&target) {
+ out.push(XRef {
+ from: insn.address,
+ to: target,
+ kind: mnemonic_kind(&insn.mnemonic),
+ preview: format!("{} {}", insn.mnemonic, insn.operands),
+ });
+ }
+ }
+ }
+
+ out.sort_by_key(|r| (r.from, r.kind));
+ out.dedup_by(|a, b| a.from == b.from && a.to == b.to && a.kind == b.kind);
+ out
+}
+
+/// Compute references **from** `source` (typically a function entry) by
+/// disassembling `max_insns` instructions from that VA and collecting every
+/// operand hex address that lands inside a mapped memory block.
+pub fn xrefs_from(prog: &Program, source: u64, max_insns: usize) -> Vec<XRef> {
+ let mut out = Vec::new();
+ let Ok(listing) = disassemble_range(prog, source, max_insns) else {
+ return out;
+ };
+ for insn in &listing {
+ for tgt in operand_addresses(&insn.operands) {
+ if prog.contains_va(tgt) {
+ out.push(XRef {
+ from: insn.address,
+ to: tgt,
+ kind: mnemonic_kind(&insn.mnemonic),
+ preview: format!("{} {}", insn.mnemonic, insn.operands),
+ });
+ }
+ }
+ }
+ out.sort_by_key(|r| (r.from, r.to));
+ out.dedup_by(|a, b| a.from == b.from && a.to == b.to && a.kind == b.kind);
+ out
+}
+
+/// Every hex-literal address that appears in `operands`.
+///
+/// Recognises `0x1234`, `0x1234abcd`, and anywhere they appear inside memory
+/// operands like `qword ptr [0x140001234]`. Decimal-only literals are not
+/// treated as addresses — Ghidra behaves the same way.
+pub fn operand_addresses(operands: &str) -> Vec<u64> {
+ let mut out = Vec::new();
+ let bytes = operands.as_bytes();
+ let mut i = 0;
+ while i + 2 < bytes.len() {
+ if bytes[i] == b'0' && (bytes[i + 1] == b'x' || bytes[i + 1] == b'X') {
+ let start = i + 2;
+ let mut end = start;
+ while end < bytes.len() && (bytes[end] as char).is_ascii_hexdigit() {
+ end += 1;
+ }
+ if end > start {
+ if let Ok(v) = u64::from_str_radix(&operands[start..end], 16) {
+ out.push(v);
+ }
+ i = end;
+ continue;
+ }
+ }
+ i += 1;
+ }
+ out
+}
+
+fn mnemonic_kind(mnem: &str) -> &'static str {
+ match mnem {
+ "call" | "callq" => "call",
+ "jmp" | "jmpq" => "jmp",
+ // x86 conditional jumps.
+ "je" | "jne" | "jz" | "jnz" | "jl" | "jle" | "jg" | "jge" | "ja" | "jae" | "jb" | "jbe"
+ | "jo" | "jno" | "js" | "jns" | "jp" | "jnp" | "jcxz" | "jecxz" | "jrcxz" | "loop"
+ | "loope" | "loopne" => "cond_jmp",
+ _ => "data",
+ }
+}
+
+fn static_kind(raw: &str) -> &'static str {
+ match raw {
+ "ptr_table" => "ptr_table",
+ "resource" => "resource",
+ "call" => "call",
+ "jmp" => "jmp",
+ "cond_jmp" => "cond_jmp",
+ "data" => "data",
+ _ => "xref",
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::{fixture_path, load_path, program::ReferenceInfo};
+
+ #[test]
+ fn operand_addresses_picks_hex_literals() {
+ assert_eq!(operand_addresses("rax, 0x1234"), vec![0x1234]);
+ assert_eq!(
+ operand_addresses("qword ptr [0x140001234]"),
+ vec![0x140001234]
+ );
+ assert!(operand_addresses("rax, 42").is_empty());
+ // Multiple literals in one operand string.
+ let v = operand_addresses("mov qword ptr [0x1000], 0xdead");
+ assert_eq!(v, vec![0x1000, 0xdead]);
+ }
+
+ #[test]
+ fn xrefs_from_entry_finds_own_addresses() {
+ let prog = load_path(fixture_path("tiny_x64.pe")).unwrap();
+ let entry = prog.entry.unwrap();
+ // xrefs_from just decodes and never fabricates.
+ let refs = xrefs_from(&prog, entry, 32);
+ for r in &refs {
+ assert!(prog.contains_va(r.to));
+ assert!(r.from >= entry);
+ }
+ }
+
+ #[test]
+ fn xrefs_to_returns_analysis_and_ptr_table_refs() {
+ let mut prog = load_path(fixture_path("analysis_lab.pe")).unwrap();
+ // Fake an address table containing entry so we can verify xrefs_to
+ // reflects the analyzer-populated pool.
+ let entry = prog.entry.unwrap();
+ prog.analysis.address_tables.push(crate::program::AddressTableInfo {
+ base: prog.image_base,
+ count: 1,
+ entries: vec![entry],
+ });
+ prog.analysis.references.push(ReferenceInfo {
+ from: prog.image_base + 0x40,
+ to: entry,
+ kind: "call".into(),
+ });
+ let refs = xrefs_to(&prog, entry, None);
+ assert!(refs.iter().any(|r| r.kind == "ptr_table"));
+ assert!(refs.iter().any(|r| r.kind == "call"));
+ }
+}
diff --git a/crates/ghidrust-decode/src/x86_64.rs b/crates/ghidrust-decode/src/x86_64.rs
index bcdd5de..5075893 100644
--- a/crates/ghidrust-decode/src/x86_64.rs
+++ b/crates/ghidrust-decode/src/x86_64.rs
@@ -133,6 +133,38 @@ fn sign_hex(v: i64) -> String {
}
}
+fn size_prefix(sz: u32) -> &'static str {
+ match sz {
+ 1 => "byte ptr ",
+ 2 => "word ptr ",
+ 4 => "dword ptr ",
+ 8 => "qword ptr ",
+ _ => "",
+ }
+}
+
+/// Wrapper around [`decode_modrm_mem`] that annotates the r/m side with an
+/// explicit width hint when it names memory. `reg_byte` still forces the
+/// register-side (mod == 3) to use the 1-byte name set; `mem_size` labels
+/// the memory access width (1/2/4/8) so downstream lift can pick the right
+/// load/store width without needing to reparse the mnemonic.
+fn decode_modrm_sized(
+ cur: &mut Cursor<'_>,
+ modrm: u8,
+ pfx: Prefix,
+ reg_byte: bool,
+ mem_size: u32,
+) -> Result<(u8, String)> {
+ let (reg, s) = decode_modrm_mem(cur, modrm, pfx, reg_byte)?;
+ if (modrm >> 6) != 3 {
+ let prefix = size_prefix(mem_size);
+ if !prefix.is_empty() && !s.contains(" ptr ") {
+ return Ok((reg, format!("{prefix}{s}")));
+ }
+ }
+ Ok((reg, s))
+}
+
fn decode_modrm_mem(
cur: &mut Cursor<'_>,
modrm: u8,
@@ -480,8 +512,212 @@ pub fn decode_one(bytes: &[u8], address: u64) -> Result<Instruction> {
};
("test".into(), format!("{rm}, {reg_s}"))
}
+ // TEST r/m8, r8
+ 0x84 => {
+ let modrm = cur.get()?;
+ let (reg, rm) = decode_modrm_sized(&mut cur, modrm, pfx, true, 1)?;
+ ("test".into(), format!("{rm}, {}", reg_name(reg, false, false, true)))
+ }
+ // TEST r/m, imm (F6 /0, F7 /0) — handled in F6/F7 groups below.
+ // XCHG r/m, r
+ 0x87 => {
+ 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)
+ };
+ ("xchg".into(), format!("{rm}, {reg_s}"))
+ }
+ // XCHG r/m8, r8
+ 0x86 => {
+ let modrm = cur.get()?;
+ let (reg, rm) = decode_modrm_sized(&mut cur, modrm, pfx, true, 1)?;
+ ("xchg".into(), format!("{rm}, {}", reg_name(reg, false, false, true)))
+ }
+ // MOV r/m8, imm8 (C6 /0)
+ 0xC6 => {
+ let modrm = cur.get()?;
+ let reg_field = (modrm >> 3) & 7;
+ if reg_field != 0 {
+ return Err(Error::Decode(format!("unhandled C6 /{reg_field}")));
+ }
+ let (_reg, rm) = decode_modrm_sized(&mut cur, modrm, pfx, true, 1)?;
+ let imm = cur.take_imm(1)? as i8 as i64;
+ ("mov".into(), format!("{rm}, {imm:#x}"))
+ }
+ // MOVSXD r64, r/m32 (Windows compilers use this constantly).
+ 0x63 => {
+ let modrm = cur.get()?;
+ let (reg, rm_raw) = decode_modrm_mem(&mut cur, modrm, pfx, false)?;
+ // Source is r/m32; when mod=3 name it as a 32-bit register even
+ // if REX.W is set. Memory forms get a "dword ptr" hint.
+ let rm = if (modrm >> 6) == 3 {
+ let src = (modrm & 7) | if pfx.rex_b { 8 } else { 0 };
+ reg_name(src, false, false, false).to_string()
+ } else if !rm_raw.contains(" ptr ") {
+ format!("{}{}", size_prefix(4), rm_raw)
+ } else {
+ rm_raw
+ };
+ let dst = if w64 {
+ reg_name(reg, true, false, false)
+ } else {
+ reg_name(reg, false, false, false)
+ };
+ let mnem = if w64 { "movsxd" } else { "mov" };
+ (mnem.into(), format!("{dst}, {rm}"))
+ }
+ // IMUL r, r/m, imm8
+ 0x6B => {
+ let modrm = cur.get()?;
+ let (reg, rm) = decode_modrm_mem(&mut cur, modrm, pfx, false)?;
+ let imm = cur.take_imm(1)? as i8 as i64;
+ let dst = if w64 {
+ reg_name(reg, true, false, false)
+ } else if op16 {
+ reg_name(reg, false, true, false)
+ } else {
+ reg_name(reg, false, false, false)
+ };
+ ("imul".into(), format!("{dst}, {rm}, {imm:#x}"))
+ }
+ // IMUL r, r/m, imm32
+ 0x69 => {
+ let modrm = cur.get()?;
+ 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
+ };
+ let dst = if w64 {
+ reg_name(reg, true, false, false)
+ } else if op16 {
+ reg_name(reg, false, true, false)
+ } else {
+ reg_name(reg, false, false, false)
+ };
+ ("imul".into(), format!("{dst}, {rm}, {imm:#x}"))
+ }
+ // Group 2 shift r/m, 1 (D0/D1) or r/m, cl (D2/D3)
+ 0xD0 | 0xD1 | 0xD2 | 0xD3 => {
+ let modrm = cur.get()?;
+ let reg_field = (modrm >> 3) & 7;
+ let mnem = match reg_field {
+ 0 => "rol",
+ 1 => "ror",
+ 2 => "rcl",
+ 3 => "rcr",
+ 4 => "shl",
+ 5 => "shr",
+ 6 => "shl",
+ 7 => "sar",
+ _ => "grp2",
+ };
+ let byte_op = op == 0xD0 || op == 0xD2;
+ let mem_size = if byte_op {
+ 1
+ } else if w64 {
+ 8
+ } else if op16 {
+ 2
+ } else {
+ 4
+ };
+ let (_reg, rm) = decode_modrm_sized(&mut cur, modrm, pfx, byte_op, mem_size)?;
+ let count = if op == 0xD0 || op == 0xD1 {
+ "1".to_string()
+ } else {
+ "cl".to_string()
+ };
+ (mnem.into(), format!("{rm}, {count}"))
+ }
+ // Group 2 shift r/m, imm8 (C0/C1)
+ 0xC0 | 0xC1 => {
+ let modrm = cur.get()?;
+ let reg_field = (modrm >> 3) & 7;
+ let mnem = match reg_field {
+ 0 => "rol",
+ 1 => "ror",
+ 2 => "rcl",
+ 3 => "rcr",
+ 4 => "shl",
+ 5 => "shr",
+ 6 => "shl",
+ 7 => "sar",
+ _ => "grp2",
+ };
+ let byte_op = op == 0xC0;
+ let mem_size = if byte_op {
+ 1
+ } else if w64 {
+ 8
+ } else if op16 {
+ 2
+ } else {
+ 4
+ };
+ let (_reg, rm) = decode_modrm_sized(&mut cur, modrm, pfx, byte_op, mem_size)?;
+ let imm = cur.take_imm(1)? as u8 as i64;
+ (mnem.into(), format!("{rm}, {imm:#x}"))
+ }
+ // Group 3 F6/F7 — test/not/neg/mul/imul/div/idiv r/m
+ 0xF6 | 0xF7 => {
+ let modrm = cur.get()?;
+ let reg_field = (modrm >> 3) & 7;
+ let byte_op = op == 0xF6;
+ let mem_size = if byte_op {
+ 1
+ } else if w64 {
+ 8
+ } else if op16 {
+ 2
+ } else {
+ 4
+ };
+ let (_reg, rm) = decode_modrm_sized(&mut cur, modrm, pfx, byte_op, mem_size)?;
+ match reg_field {
+ 0 | 1 => {
+ // test r/m, imm
+ let imm = if byte_op {
+ cur.take_imm(1)? as i8 as i64
+ } else if op16 {
+ cur.take_imm(2)? as i16 as i64
+ } else {
+ cur.take_imm(4)? as i32 as i64
+ };
+ ("test".into(), format!("{rm}, {imm:#x}"))
+ }
+ 2 => ("not".into(), rm),
+ 3 => ("neg".into(), rm),
+ 4 => ("mul".into(), rm),
+ 5 => ("imul".into(), rm),
+ 6 => ("div".into(), rm),
+ 7 => ("idiv".into(), rm),
+ _ => ("grp3".into(), rm),
+ }
+ }
// NOP
0x90 => ("nop".into(), String::new()),
+ // CBW / CWDE / CDQE
+ 0x98 => {
+ if w64 {
+ ("cdqe".into(), String::new())
+ } else if op16 {
+ ("cbw".into(), String::new())
+ } else {
+ ("cwde".into(), String::new())
+ }
+ }
+ // PUSHF / POPF (rex.w doesn't matter — these push RFLAGS)
+ 0x9C => ("pushfq".into(), String::new()),
+ 0x9D => ("popfq".into(), String::new()),
+ // HLT
+ 0xF4 => ("hlt".into(), String::new()),
// RET
0xC3 => ("ret".into(), String::new()),
0xC2 => {
@@ -594,6 +830,140 @@ pub fn decode_one(bytes: &[u8], address: u64) -> Result<Instruction> {
.wrapping_add(rel as u64);
(names[(op2 - 0x80) as usize].into(), format!("{target:#x}"))
}
+ // CMOVcc r, r/m
+ 0x40..=0x4F => {
+ let names = [
+ "cmovo", "cmovno", "cmovb", "cmovae", "cmove", "cmovne", "cmovbe",
+ "cmova", "cmovs", "cmovns", "cmovp", "cmovnp", "cmovl", "cmovge",
+ "cmovle", "cmovg",
+ ];
+ let modrm = cur.get()?;
+ let mem_size = if w64 { 8 } else if op16 { 2 } else { 4 };
+ let (reg, rm) = decode_modrm_sized(&mut cur, modrm, pfx, false, mem_size)?;
+ let dst = if w64 {
+ reg_name(reg, true, false, false)
+ } else if op16 {
+ reg_name(reg, false, true, false)
+ } else {
+ reg_name(reg, false, false, false)
+ };
+ (names[(op2 - 0x40) as usize].into(), format!("{dst}, {rm}"))
+ }
+ // SETcc r/m8
+ 0x90..=0x9F => {
+ let names = [
+ "seto", "setno", "setb", "setae", "sete", "setne", "setbe", "seta",
+ "sets", "setns", "setp", "setnp", "setl", "setge", "setle", "setg",
+ ];
+ let modrm = cur.get()?;
+ let (_r, rm) = decode_modrm_sized(&mut cur, modrm, pfx, true, 1)?;
+ (names[(op2 - 0x90) as usize].into(), rm)
+ }
+ // MOVZX r, r/m8
+ 0xB6 => {
+ let modrm = cur.get()?;
+ let (reg, rm) = decode_modrm_sized(&mut cur, modrm, pfx, true, 1)?;
+ let dst = if w64 {
+ reg_name(reg, true, false, false)
+ } else if op16 {
+ reg_name(reg, false, true, false)
+ } else {
+ reg_name(reg, false, false, false)
+ };
+ ("movzx".into(), format!("{dst}, {rm}"))
+ }
+ // MOVZX r, r/m16
+ 0xB7 => {
+ let modrm = cur.get()?;
+ // r/m is 16-bit; when mod=3 that's a word reg.
+ let (reg, rm_raw) = decode_modrm_mem(&mut cur, modrm, pfx, false)?;
+ let rm = if (modrm >> 6) == 3 {
+ // Force word regnames on the source.
+ let src = (modrm & 7) | if pfx.rex_b { 8 } else { 0 };
+ reg_name(src, false, true, false).to_string()
+ } else if !rm_raw.contains(" ptr ") {
+ format!("{}{}", size_prefix(2), rm_raw)
+ } else {
+ rm_raw
+ };
+ let dst = if w64 {
+ reg_name(reg, true, false, false)
+ } else if op16 {
+ reg_name(reg, false, true, false)
+ } else {
+ reg_name(reg, false, false, false)
+ };
+ ("movzx".into(), format!("{dst}, {rm}"))
+ }
+ // MOVSX r, r/m8
+ 0xBE => {
+ let modrm = cur.get()?;
+ let (reg, rm) = decode_modrm_sized(&mut cur, modrm, pfx, true, 1)?;
+ let dst = if w64 {
+ reg_name(reg, true, false, false)
+ } else if op16 {
+ reg_name(reg, false, true, false)
+ } else {
+ reg_name(reg, false, false, false)
+ };
+ ("movsx".into(), format!("{dst}, {rm}"))
+ }
+ // MOVSX r, r/m16
+ 0xBF => {
+ let modrm = cur.get()?;
+ let (reg, rm_raw) = decode_modrm_mem(&mut cur, modrm, pfx, false)?;
+ let rm = if (modrm >> 6) == 3 {
+ let src = (modrm & 7) | if pfx.rex_b { 8 } else { 0 };
+ reg_name(src, false, true, false).to_string()
+ } else if !rm_raw.contains(" ptr ") {
+ format!("{}{}", size_prefix(2), rm_raw)
+ } else {
+ rm_raw
+ };
+ let dst = if w64 {
+ reg_name(reg, true, false, false)
+ } else if op16 {
+ reg_name(reg, false, true, false)
+ } else {
+ reg_name(reg, false, false, false)
+ };
+ ("movsx".into(), format!("{dst}, {rm}"))
+ }
+ // IMUL r, r/m
+ 0xAF => {
+ let modrm = cur.get()?;
+ let (reg, rm) = decode_modrm_mem(&mut cur, modrm, pfx, false)?;
+ let dst = if w64 {
+ reg_name(reg, true, false, false)
+ } else if op16 {
+ reg_name(reg, false, true, false)
+ } else {
+ reg_name(reg, false, false, false)
+ };
+ ("imul".into(), format!("{dst}, {rm}"))
+ }
+ // BSWAP r32/r64
+ 0xC8..=0xCF => {
+ let r = (op2 - 0xC8) | if pfx.rex_b { 8 } else { 0 };
+ let reg = if w64 {
+ reg_name(r, true, false, false)
+ } else {
+ reg_name(r, false, false, false)
+ };
+ ("bswap".into(), reg.to_string())
+ }
+ // UD2
+ 0x0B => ("ud2".into(), String::new()),
+ // ENDBR64 / ENDBR32 (F3 0F 1E FA / FB) — with F3 already consumed as `rep`.
+ 0x1E if pfx.rep => {
+ let modrm = cur.get()?;
+ let m = match modrm {
+ 0xFA => "endbr64",
+ 0xFB => "endbr32",
+ _ => "endbr",
+ };
+ (m.into(), String::new())
+ }
0x1F => {
// NOP r/m
let modrm = cur.get()?;
@@ -678,4 +1048,102 @@ mod tests {
let i1 = decode_one(&b[2..], 2).unwrap();
assert_eq!(i1.mnemonic, "ret");
}
+
+ #[test]
+ fn decode_cmovcc_register() {
+ // 48 0f 45 c8 cmovne rcx, rax
+ let i = decode_one(&[0x48, 0x0f, 0x45, 0xc8], 0).unwrap();
+ assert_eq!(i.mnemonic, "cmovne");
+ assert_eq!(i.operands, "rcx, rax");
+ assert_eq!(i.length, 4);
+ }
+
+ #[test]
+ fn decode_setcc_r8() {
+ // 0f 94 c0 sete al
+ let i = decode_one(&[0x0f, 0x94, 0xc0], 0).unwrap();
+ assert_eq!(i.mnemonic, "sete");
+ assert_eq!(i.operands, "al");
+ }
+
+ #[test]
+ fn decode_movzx_r32_r8() {
+ // 0f b6 c1 movzx eax, cl
+ let i = decode_one(&[0x0f, 0xb6, 0xc1], 0).unwrap();
+ assert_eq!(i.mnemonic, "movzx");
+ assert_eq!(i.operands, "eax, cl");
+ }
+
+ #[test]
+ fn decode_movsxd_r64_r32() {
+ // 48 63 c1 movsxd rax, ecx
+ let i = decode_one(&[0x48, 0x63, 0xc1], 0).unwrap();
+ assert_eq!(i.mnemonic, "movsxd");
+ assert_eq!(i.operands, "rax, ecx");
+ }
+
+ #[test]
+ fn decode_shr_by_cl_and_shl_imm() {
+ // c1 e0 03 shl eax, 3
+ let a = decode_one(&[0xc1, 0xe0, 0x03], 0).unwrap();
+ assert_eq!(a.mnemonic, "shl");
+ assert_eq!(a.operands, "eax, 0x3");
+ // d3 e8 shr eax, cl
+ let b = decode_one(&[0xd3, 0xe8], 0).unwrap();
+ assert_eq!(b.mnemonic, "shr");
+ assert_eq!(b.operands, "eax, cl");
+ }
+
+ #[test]
+ fn decode_group3_neg_and_not() {
+ // f7 d8 neg eax
+ let a = decode_one(&[0xf7, 0xd8], 0).unwrap();
+ assert_eq!(a.mnemonic, "neg");
+ assert_eq!(a.operands, "eax");
+ // f7 d0 not eax
+ let b = decode_one(&[0xf7, 0xd0], 0).unwrap();
+ assert_eq!(b.mnemonic, "not");
+ }
+
+ #[test]
+ fn decode_hlt_and_int3() {
+ assert_eq!(decode_one(&[0xf4], 0).unwrap().mnemonic, "hlt");
+ assert_eq!(decode_one(&[0xcc], 0).unwrap().mnemonic, "int3");
+ }
+
+ #[test]
+ fn decode_endbr64() {
+ // f3 0f 1e fa endbr64
+ let i = decode_one(&[0xf3, 0x0f, 0x1e, 0xfa], 0).unwrap();
+ assert_eq!(i.mnemonic, "endbr64");
+ }
+
+ #[test]
+ fn decode_imul_with_imm() {
+ // 6b c0 03 imul eax, eax, 3
+ let i = decode_one(&[0x6b, 0xc0, 0x03], 0).unwrap();
+ assert_eq!(i.mnemonic, "imul");
+ assert_eq!(i.operands, "eax, eax, 0x3");
+ }
+
+ #[test]
+ fn decode_ud2_and_bswap() {
+ assert_eq!(decode_one(&[0x0f, 0x0b], 0).unwrap().mnemonic, "ud2");
+ // 0f c8 bswap eax
+ let b = decode_one(&[0x0f, 0xc8], 0).unwrap();
+ assert_eq!(b.mnemonic, "bswap");
+ assert_eq!(b.operands, "eax");
+ }
+
+ #[test]
+ fn decode_sib_with_scale_still_valid() {
+ // 8b 04 88 mov eax, [rax+rcx*4]
+ let i = decode_one(&[0x8b, 0x04, 0x88], 0).unwrap();
+ assert_eq!(i.mnemonic, "mov");
+ assert!(
+ i.operands.contains("rcx*4"),
+ "expected SIB scale 4, got '{}'",
+ i.operands
+ );
+ }
}
diff --git a/crates/ghidrust-decomp/Cargo.toml b/crates/ghidrust-decomp/Cargo.toml
index 0f9e6fe..06d0db9 100644
--- a/crates/ghidrust-decomp/Cargo.toml
+++ b/crates/ghidrust-decomp/Cargo.toml
@@ -19,6 +19,10 @@ ghidrust-structure = { workspace = true }
ghidrust-types = { workspace = true }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
+# Parallel per-function decompile (Phase F). Already a workspace dep via
+# ghidrust-core; kept explicit here so `bench_program_stage1_parallel`
+# builds without pulling core.
+rayon = "1"
wgpu = { version = "24", optional = true, default-features = true }
pollster = { version = "0.4", optional = true }
bytemuck = { version = "1", optional = true, features = ["derive"] }
diff --git a/crates/ghidrust-decomp/src/bench.rs b/crates/ghidrust-decomp/src/bench.rs
index 8ca1fbd..ebdc897 100644
--- a/crates/ghidrust-decomp/src/bench.rs
+++ b/crates/ghidrust-decomp/src/bench.rs
@@ -11,9 +11,13 @@
//! optional cap on function count. Everything else is unit-testable via
//! [`bench_functions`] over synthetic instruction lists.
-use crate::{decompile_instructions, decompile_instructions_ir, DecompileResult};
+use crate::{
+ decompile_instructions, decompile_instructions_ir, decompile_instructions_stage1,
+ DecompileResult, Stage1Result,
+};
use ghidrust_core::{disassemble_range, Program};
use ghidrust_lift::LiftCoverage;
+use ghidrust_types::CallConv;
use serde::{Deserialize, Serialize};
use std::time::{Duration, Instant};
@@ -29,6 +33,21 @@ pub struct FunctionBench {
pub stage05_us: u128,
pub stage0_bytes: usize,
pub stage05_bytes: usize,
+ /// Stage-1 wall-clock (µs). Populated by [`bench_program_stage1`] and
+ /// left as `0` by legacy Stage-0/0.5-only benches for back-compat.
+ #[serde(default)]
+ pub stage1_us: u128,
+ /// Rendered Stage-1 pseudo-C for this function; empty when Stage-1
+ /// was not run.
+ #[serde(default)]
+ pub stage1_text: String,
+ /// Number of unstructured `goto`s in the Stage-1 region tree (from
+ /// [`ghidrust_structure::goto_count`]). Zero for legacy benches.
+ #[serde(default)]
+ pub stage1_goto_count: usize,
+ /// Total number of structured leaves in the Stage-1 region tree.
+ #[serde(default)]
+ pub stage1_leaf_count: usize,
}
/// Rolled-up bench over one program.
@@ -41,6 +60,8 @@ pub struct BenchReport {
pub avg_lift_ratio: f32,
pub stage0_total_us: u128,
pub stage05_total_us: u128,
+ #[serde(default)]
+ pub stage1_total_us: u128,
pub per_function: Vec<FunctionBench>,
}
@@ -51,7 +72,13 @@ impl BenchReport {
pub fn to_text(&self) -> String {
let mut s = String::new();
- s.push_str("=== Ghidrust decompile-bench (Stage-0 vs Stage-0.5) ===\n");
+ let stage1_populated = self.stage1_total_us > 0
+ || self.per_function.iter().any(|f| f.stage1_us > 0);
+ if stage1_populated {
+ s.push_str("=== Ghidrust decompile-bench (Stage-0 vs Stage-0.5 vs Stage-1) ===\n");
+ } else {
+ s.push_str("=== Ghidrust decompile-bench (Stage-0 vs Stage-0.5) ===\n");
+ }
s.push_str(&format!("image: {}\n", self.image));
s.push_str(&format!(
"functions={} insns={} ir_ops={} lift_ratio_avg={:.1}%\n",
@@ -60,26 +87,51 @@ impl BenchReport {
self.total_ir_ops,
self.avg_lift_ratio * 100.0
));
- s.push_str(&format!(
- "wall_ms stage0={:.3} stage0.5={:.3}\n",
- self.stage0_total_us as f64 / 1000.0,
- self.stage05_total_us as f64 / 1000.0
- ));
- s.push_str("--- per function ---\n");
- for f in &self.per_function {
+ if stage1_populated {
+ s.push_str(&format!(
+ "wall_ms stage0={:.3} stage0.5={:.3} stage1={:.3}\n",
+ self.stage0_total_us as f64 / 1000.0,
+ self.stage05_total_us as f64 / 1000.0,
+ self.stage1_total_us as f64 / 1000.0
+ ));
+ } else {
s.push_str(&format!(
- " {:016x} {:>28} insns={:<4} ir={:<4} lift={:>5.1}% s0={:>7.3}ms s0.5={:>7.3}ms bytes s0={:<5} s0.5={:<5}\n",
- f.entry,
- truncate(&f.name, 28),
- f.insn_count,
- f.ir_ops,
- f.lift_ratio * 100.0,
- f.stage0_us as f64 / 1000.0,
- f.stage05_us as f64 / 1000.0,
- f.stage0_bytes,
- f.stage05_bytes,
+ "wall_ms stage0={:.3} stage0.5={:.3}\n",
+ self.stage0_total_us as f64 / 1000.0,
+ self.stage05_total_us as f64 / 1000.0
));
}
+ s.push_str("--- per function ---\n");
+ for f in &self.per_function {
+ if stage1_populated {
+ s.push_str(&format!(
+ " {:016x} {:>28} insns={:<4} ir={:<4} lift={:>5.1}% s0={:>7.3}ms s0.5={:>7.3}ms s1={:>7.3}ms goto={}/{}\n",
+ f.entry,
+ truncate(&f.name, 28),
+ f.insn_count,
+ f.ir_ops,
+ f.lift_ratio * 100.0,
+ f.stage0_us as f64 / 1000.0,
+ f.stage05_us as f64 / 1000.0,
+ f.stage1_us as f64 / 1000.0,
+ f.stage1_goto_count,
+ f.stage1_leaf_count,
+ ));
+ } else {
+ s.push_str(&format!(
+ " {:016x} {:>28} insns={:<4} ir={:<4} lift={:>5.1}% s0={:>7.3}ms s0.5={:>7.3}ms bytes s0={:<5} s0.5={:<5}\n",
+ f.entry,
+ truncate(&f.name, 28),
+ f.insn_count,
+ f.ir_ops,
+ f.lift_ratio * 100.0,
+ f.stage0_us as f64 / 1000.0,
+ f.stage05_us as f64 / 1000.0,
+ f.stage0_bytes,
+ f.stage05_bytes,
+ ));
+ }
+ }
s
}
}
@@ -125,6 +177,115 @@ pub fn bench_program(
finalize(prog.name.clone(), per_function)
}
+/// Parallel version of [`bench_program_stage1`] — decompiles each entry
+/// in a rayon thread pool. Wall-clock rows are per-entry (`stage1_us`)
+/// and remain single-threaded times so ratios stay comparable to the
+/// serial variant; the total wall-clock speed-up shows up in the
+/// harness's own `harness_us` measurement (caller-provided). Kept
+/// separate from the serial API because a chunk of downstream tests
+/// still assume deterministic ordering.
+pub fn bench_program_stage1_parallel(
+ prog: &Program,
+ entries: Option<&[u64]>,
+ max_functions: usize,
+ max_insns_per_fn: usize,
+ conv: CallConv,
+) -> BenchReport {
+ use rayon::prelude::*;
+ let mut targets: Vec<(String, u64)> = if let Some(es) = entries {
+ es.iter()
+ .map(|&e| {
+ let name = prog
+ .analysis
+ .functions
+ .iter()
+ .find(|f| f.entry == e)
+ .map(|f| f.name.clone())
+ .unwrap_or_else(|| format!("FUN_{e:016x}"));
+ (name, e)
+ })
+ .collect()
+ } else {
+ prog.analysis
+ .functions
+ .iter()
+ .take(max_functions.max(1))
+ .map(|f| (f.name.clone(), f.entry))
+ .collect()
+ };
+ if targets.is_empty() {
+ let entry = prog.entry.unwrap_or(prog.image_base);
+ targets.push((format!("FUN_{entry:016x}"), entry));
+ }
+ // Pre-disassemble serially since `Program` isn't thread-safe for
+ // decode (borrowed image slice + shared caches). Bench_one_stage1
+ // itself is pure and cheap to fan out.
+ let prepared: Vec<(String, u64, Vec<ghidrust_core::Instruction>)> = targets
+ .into_iter()
+ .filter_map(|(name, entry)| {
+ let insns = disassemble_range(prog, entry, max_insns_per_fn).ok()?;
+ Some((name, entry, insns))
+ })
+ .collect();
+ let per_function: Vec<FunctionBench> = prepared
+ .par_iter()
+ .map(|(name, entry, insns)| bench_one_stage1(name, *entry, insns, conv))
+ .collect();
+ finalize(prog.name.clone(), per_function)
+}
+
+/// **Stage-1 bench** — pick the shared entry set (or fall back to
+/// `prog.analysis.functions`) and time Stage-0, Stage-0.5, and Stage-1 on
+/// each. Captured Stage-1 text is stored so head-to-head oracles can run
+/// token-similarity metrics against Ghidra output without recomputing.
+///
+/// `entries` is optional: `None` = use `prog.analysis.functions` capped by
+/// `max_functions`; `Some(list)` = use exactly that entry list (in order).
+/// This is the API [`crate::ghidra_oracle::compare`] uses to enforce the
+/// "shared entry set" fairness rule from the P0 parity plan.
+pub fn bench_program_stage1(
+ prog: &Program,
+ entries: Option<&[u64]>,
+ max_functions: usize,
+ max_insns_per_fn: usize,
+ conv: CallConv,
+) -> BenchReport {
+ let mut targets: Vec<(String, u64)> = if let Some(es) = entries {
+ es.iter()
+ .map(|&e| {
+ let name = prog
+ .analysis
+ .functions
+ .iter()
+ .find(|f| f.entry == e)
+ .map(|f| f.name.clone())
+ .unwrap_or_else(|| format!("FUN_{e:016x}"));
+ (name, e)
+ })
+ .collect()
+ } else {
+ prog.analysis
+ .functions
+ .iter()
+ .take(max_functions.max(1))
+ .map(|f| (f.name.clone(), f.entry))
+ .collect()
+ };
+ if targets.is_empty() {
+ let entry = prog.entry.unwrap_or(prog.image_base);
+ targets.push((format!("FUN_{entry:016x}"), entry));
+ }
+ let mut per_function = Vec::new();
+ for (name, entry) in targets {
+ let insns = match disassemble_range(prog, entry, max_insns_per_fn) {
+ Ok(v) => v,
+ Err(_) => continue,
+ };
+ per_function.push(bench_one_stage1(&name, entry, &insns, conv));
+ }
+ finalize(prog.name.clone(), per_function)
+}
+
/// Alternative entry: bench pre-decoded instruction lists (useful for tests
/// and repeatable corpora without a full [`Program`] load).
pub fn bench_functions(
@@ -144,6 +305,7 @@ fn finalize(image: String, per_function: Vec<FunctionBench>) -> BenchReport {
let total_ir_ops: usize = per_function.iter().map(|f| f.ir_ops).sum();
let stage0_total_us: u128 = per_function.iter().map(|f| f.stage0_us).sum();
let stage05_total_us: u128 = per_function.iter().map(|f| f.stage05_us).sum();
+ let stage1_total_us: u128 = per_function.iter().map(|f| f.stage1_us).sum();
let avg_lift_ratio = if function_count == 0 {
0.0
} else {
@@ -157,6 +319,7 @@ fn finalize(image: String, per_function: Vec<FunctionBench>) -> BenchReport {
avg_lift_ratio,
stage0_total_us,
stage05_total_us,
+ stage1_total_us,
per_function,
}
}
@@ -181,9 +344,31 @@ fn bench_one(name: &str, entry: u64, insns: &[ghidrust_core::Instruction]) -> Fu
stage05_us: micros(s05_dur),
stage0_bytes: s0.char_count(),
stage05_bytes: s05.char_count(),
+ stage1_us: 0,
+ stage1_text: String::new(),
+ stage1_goto_count: 0,
+ stage1_leaf_count: 0,
}
}
+fn bench_one_stage1(
+ name: &str,
+ entry: u64,
+ insns: &[ghidrust_core::Instruction],
+ conv: CallConv,
+) -> FunctionBench {
+ let mut fb = bench_one(name, entry, insns);
+ let s1_start = Instant::now();
+ let (_dec, stage1): (DecompileResult, Stage1Result) =
+ decompile_instructions_stage1(name, entry, insns, conv);
+ let s1_dur = s1_start.elapsed();
+ fb.stage1_us = micros(s1_dur);
+ fb.stage1_text = stage1.pseudo_c.clone();
+ fb.stage1_goto_count = ghidrust_structure::goto_count(&stage1.structure.region);
+ fb.stage1_leaf_count = ghidrust_structure::region_leaf_count(&stage1.structure.region);
+ fb
+}
+
fn micros(d: Duration) -> u128 {
d.as_micros().max(1)
}
@@ -224,6 +409,43 @@ mod tests {
assert!(text.contains("synth_fn"));
}
+ #[test]
+ fn bench_program_stage1_captures_stage1_text_and_wall() {
+ let prog = load_path(fixture_path("tiny_x64.pe")).unwrap();
+ let entry = prog.entry.unwrap();
+ let rep = bench_program_stage1(
+ &prog,
+ Some(&[entry]),
+ 4,
+ 32,
+ CallConv::Windows,
+ );
+ assert_eq!(rep.function_count, 1);
+ let f = &rep.per_function[0];
+ assert_eq!(f.entry, entry);
+ assert!(f.stage1_us > 0, "stage1 wall must be captured");
+ assert!(!f.stage1_text.is_empty(), "stage1 text must be captured");
+ assert!(rep.stage1_total_us > 0);
+ }
+
+ #[test]
+ fn bench_program_stage1_parallel_matches_serial_shape() {
+ let prog = load_path(fixture_path("tiny_x64.pe")).unwrap();
+ let entry = prog.entry.unwrap();
+ let serial =
+ bench_program_stage1(&prog, Some(&[entry]), 4, 32, CallConv::Windows);
+ let par =
+ bench_program_stage1_parallel(&prog, Some(&[entry]), 4, 32, CallConv::Windows);
+ assert_eq!(serial.function_count, par.function_count);
+ // Text output must be identical — parallelism only changes
+ // scheduling, not the emit.
+ assert_eq!(
+ serial.per_function[0].stage1_text,
+ par.per_function[0].stage1_text,
+ "parallel bench must produce identical Stage-1 text"
+ );
+ }
+
#[test]
fn bench_program_falls_back_to_entry_when_no_functions() {
let prog = load_path(fixture_path("tiny_x64.pe")).unwrap();
diff --git a/crates/ghidrust-decomp/src/ghidra_oracle.rs b/crates/ghidrust-decomp/src/ghidra_oracle.rs
index 5b6171a..471c42f 100644
--- a/crates/ghidrust-decomp/src/ghidra_oracle.rs
+++ b/crates/ghidrust-decomp/src/ghidra_oracle.rs
@@ -33,8 +33,9 @@
//! `analyzeHeadless`, which script to run, and where to point the harness.
//! Nothing is invented.
-use crate::{bench_program, BenchReport};
+use crate::{bench_program, bench_program_stage1, BenchReport};
use ghidrust_core::Program;
+use ghidrust_types::CallConv;
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
use std::process::Command;
@@ -81,6 +82,60 @@ pub struct GhidraOracleConfig {
/// (`DecompileAndReport.java <out.json> <max_fn>`); the Java script
/// treats a missing or non-numeric value as "no cap".
pub ghidra_fn_cap: Option<usize>,
+ /// Which Ghidrust emit stage to use for the per-entry rows. Stage-1
+ /// is the fair comparison (Phase E of the pcode parity plan) since
+ /// it goes head-to-head with Ghidra's `DecompInterface` output;
+ /// Stage-0 stays available as an oracle for regression checks.
+ #[serde(default)]
+ pub ghidrust_stage: GhidrustStage,
+ /// Calling convention used for Stage-1 recovery. Defaults to
+ /// SystemV; callers on Windows binaries typically override.
+ #[serde(default)]
+ pub call_conv: GhidrustCallConv,
+}
+
+/// Which Ghidrust emit stage to run for the head-to-head. Stage-1 is the
+/// only shape suitable for a *fair* Ghidra comparison — Stage-0 is
+/// mnemonic-scaffolding and Stage-0.5 is IR-informed but pre-SSA. The
+/// enum lives here so callers can select mode via the CLI/GUI without
+/// depending on the internal emit crate names.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+pub enum GhidrustStage {
+ Stage0,
+ Stage05,
+ Stage1,
+}
+
+impl Default for GhidrustStage {
+ fn default() -> Self {
+ // Phase F flips the product default to Stage-1; the oracle
+ // follows so the head-to-head is fair by default.
+ GhidrustStage::Stage1
+ }
+}
+
+/// Calling convention selector for the oracle harness. Kept a separate
+/// enum from [`ghidrust_types::CallConv`] purely so the config surface
+/// serialises stably to JSON without leaking internal types.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+pub enum GhidrustCallConv {
+ SystemV,
+ Windows,
+}
+
+impl Default for GhidrustCallConv {
+ fn default() -> Self {
+ GhidrustCallConv::SystemV
+ }
+}
+
+impl From<GhidrustCallConv> for CallConv {
+ fn from(c: GhidrustCallConv) -> Self {
+ match c {
+ GhidrustCallConv::SystemV => CallConv::SystemV,
+ GhidrustCallConv::Windows => CallConv::Windows,
+ }
+ }
}
impl GhidraOracleConfig {
@@ -109,6 +164,21 @@ pub struct StructuralMatch {
pub ghidrust_insns: usize,
pub match_kind: MatchKind,
pub notes: String,
+ /// Normalized token similarity between Ghidrust Stage-1 text and
+ /// Ghidra `DecompInterface` output on the same entry. `1.0` = strong
+ /// token overlap; `0.0` = disjoint. Missing (`None`) when either
+ /// side didn't produce text — this is the fair-metric replacement
+ /// for the earlier `{`-count proxy.
+ #[serde(default)]
+ pub token_similarity: Option<f32>,
+ /// Ghidrust Stage-1 wall-clock in µs on the same shared-entry
+ /// corpus. `0` when Stage-1 wasn't run (legacy Stage-0/0.5 rows).
+ #[serde(default)]
+ pub ghidrust_stage1_us: u128,
+ /// Ghidra `DecompInterface.decompileFunction` wall-clock in µs from
+ /// the captured JSON. `None` when the row was Ghidra-side-missing.
+ #[serde(default)]
+ pub ghidra_wall_us: Option<u128>,
}
/// Coarse match kind for a single-function comparison. We deliberately do
@@ -149,13 +219,14 @@ impl GhidraOracleReport {
pub fn to_text(&self) -> String {
let mut s = String::new();
- s.push_str("=== Ghidrust ↔ Ghidra head-to-head oracle ===\n");
+ s.push_str("=== Ghidrust ↔ Ghidra head-to-head oracle (Phase E, shared-entry, Stage-1) ===\n");
s.push_str(&format!("image: {}\n", self.image));
s.push_str(&format!(
- "ghidrust: functions={} stage0_wall_ms={:.3} stage0.5_wall_ms={:.3} lift_avg={:.1}%\n",
+ "ghidrust: functions={} stage0_wall_ms={:.3} stage0.5_wall_ms={:.3} stage1_wall_ms={:.3} lift_avg={:.1}%\n",
self.ghidrust.function_count,
self.ghidrust.stage0_total_us as f64 / 1000.0,
self.ghidrust.stage05_total_us as f64 / 1000.0,
+ self.ghidrust.stage1_total_us as f64 / 1000.0,
self.ghidrust.avg_lift_ratio * 100.0
));
match self.ghidra_total_us {
@@ -167,16 +238,27 @@ impl GhidraOracleReport {
self.harness_us as f64 / 1000.0,
self.ghidra_unavailable
));
- s.push_str("--- per-function ---\n");
+ s.push_str("--- per-function (shared entries only) ---\n");
for r in &self.rows {
+ let sim = match r.token_similarity {
+ Some(v) => format!("sim={:.2}", v),
+ None => "sim=—".to_string(),
+ };
+ let ghidra_wall = match r.ghidra_wall_us {
+ Some(us) => format!("ghidra={:.3}ms", us as f64 / 1000.0),
+ None => "ghidra=—".to_string(),
+ };
s.push_str(&format!(
- " {:016x} {:>28} ghidrust=b{}/i{} ghidra≈b{} {:?} {}\n",
+ " {:016x} {:>28} ghidrust=leaves{}/i{} ghidra≈b{} {:?} {} s1={:.3}ms {} {}\n",
r.entry,
truncate(&r.function, 28),
r.ghidrust_blocks,
r.ghidrust_insns,
r.ghidra_blocks_estimated,
r.match_kind,
+ sim,
+ r.ghidrust_stage1_us as f64 / 1000.0,
+ ghidra_wall,
r.notes
));
}
@@ -199,10 +281,130 @@ fn truncate(s: &str, n: usize) -> String {
}
}
-/// Run a head-to-head comparison. When `cfg.ghidra_install_dir` is `None`
-/// this delegates to [`bench_program`] on the Ghidrust side and produces a
-/// report that only names the methodology on the Ghidra side (no
-/// fabricated numbers).
+/// Tokenize a chunk of C-ish source into identifiers, integer literals,
+/// and control-flow keywords. Whitespace, comments, and punctuation are
+/// dropped so the resulting bag is stable across Ghidrust / Ghidra
+/// formatting differences.
+fn tokenize_c(src: &str) -> Vec<String> {
+ let mut out = Vec::new();
+ // Strip `//` comments and `/* */` blocks.
+ let mut cur = String::with_capacity(src.len());
+ let bytes = src.as_bytes();
+ let mut i = 0;
+ while i < bytes.len() {
+ // Line comment.
+ if i + 1 < bytes.len() && bytes[i] == b'/' && bytes[i + 1] == b'/' {
+ while i < bytes.len() && bytes[i] != b'\n' {
+ i += 1;
+ }
+ continue;
+ }
+ if i + 1 < bytes.len() && bytes[i] == b'/' && bytes[i + 1] == b'*' {
+ i += 2;
+ while i + 1 < bytes.len() && !(bytes[i] == b'*' && bytes[i + 1] == b'/') {
+ i += 1;
+ }
+ i = (i + 2).min(bytes.len());
+ continue;
+ }
+ cur.push(bytes[i] as char);
+ i += 1;
+ }
+ let cleaned = cur;
+ let mut chars = cleaned.chars().peekable();
+ let mut buf = String::new();
+ while let Some(&c) = chars.peek() {
+ if c.is_alphanumeric() || c == '_' {
+ buf.clear();
+ while let Some(&d) = chars.peek() {
+ if d.is_alphanumeric() || d == '_' {
+ buf.push(d);
+ chars.next();
+ } else {
+ break;
+ }
+ }
+ if !buf.is_empty() {
+ out.push(normalize_token(&buf));
+ }
+ } else {
+ chars.next();
+ }
+ }
+ out
+}
+
+/// Fold Ghidrust-only naming conventions (e.g. `rdi#3`, `local_1c`) and
+/// Ghidra sibling shapes (`param_1`, `iVar1`, `uVar2`) toward a common
+/// bucket so the similarity metric doesn't punish structurally equivalent
+/// outputs for cosmetic naming differences.
+fn normalize_token(tok: &str) -> String {
+ let t = tok.trim();
+ if t.starts_with("local_") || t.starts_with("stack_") || t.starts_with("var_") {
+ return "LOCAL".into();
+ }
+ if t.starts_with("param_") || t.starts_with("arg_") {
+ return "PARAM".into();
+ }
+ if (t.starts_with('i') || t.starts_with('u') || t.starts_with('l')
+ || t.starts_with('c') || t.starts_with('s'))
+ && t.ends_with(|c: char| c.is_ascii_digit())
+ && t.starts_with(|c: char| c.is_ascii_lowercase())
+ && t.contains("Var")
+ {
+ return "TMP".into();
+ }
+ if t.starts_with("FUN_") || t.starts_with("sub_") || t.starts_with("SUB_") {
+ return "CALL".into();
+ }
+ if t.starts_with("0x") {
+ return "CONST".into();
+ }
+ if t.chars().all(|c| c.is_ascii_digit()) {
+ return "CONST".into();
+ }
+ t.to_lowercase()
+}
+
+/// Jaccard similarity over the bag of normalized tokens: intersection
+/// divided by union. Returns `1.0` for identical bags, `0.0` for
+/// disjoint. Both texts must be non-empty; empty inputs return `None`
+/// upstream.
+pub fn token_similarity(a: &str, b: &str) -> f32 {
+ let ta = tokenize_c(a);
+ let tb = tokenize_c(b);
+ if ta.is_empty() || tb.is_empty() {
+ return 0.0;
+ }
+ use std::collections::HashSet;
+ let sa: HashSet<&str> = ta.iter().map(|s| s.as_str()).collect();
+ let sb: HashSet<&str> = tb.iter().map(|s| s.as_str()).collect();
+ let inter = sa.intersection(&sb).count() as f32;
+ let union = sa.union(&sb).count() as f32;
+ if union == 0.0 {
+ 0.0
+ } else {
+ inter / union
+ }
+}
+
+/// Run a head-to-head comparison.
+///
+/// **Phase E fairness rules** (from the P0 pcode-parity plan):
+///
+/// 1. **Shared entry list.** When a Ghidra capture is available the
+/// Ghidrust side re-runs on the intersection of Ghidra's decompiled
+/// entries with Ghidrust's analyzer output. No side gets to pick a
+/// corpus the other one didn't see.
+/// 2. **Stage-1 by default.** [`GhidrustStage::Stage1`] is the fair
+/// comparison stage; Stage-0/0.5 stay available for regression only.
+/// 3. **Token/AST similarity metric.** Rows report normalized-token
+/// Jaccard between Ghidrust and Ghidra output (see
+/// [`token_similarity`]) — not brace-count.
+/// 4. **Timings on shared entries only.** `ghidra_total_us` sums
+/// only entries that appear in the Ghidrust row set.
+/// 5. **Nothing is fabricated.** When Ghidra output is missing the row
+/// keeps `token_similarity = None` and never invents wall time.
pub fn compare(prog: &Program, cfg: &GhidraOracleConfig) -> GhidraOracleReport {
let t0 = Instant::now();
let max_functions = if cfg.max_functions == 0 { 8 } else { cfg.max_functions };
@@ -211,11 +413,8 @@ pub fn compare(prog: &Program, cfg: &GhidraOracleConfig) -> GhidraOracleReport {
} else {
cfg.max_insns_per_fn
};
- let ghidrust = bench_program(prog, max_functions, max_insns);
- // If the caller asked us to spawn Ghidra AND supplied a binary path,
- // try to do so *before* we look at `captured_ghidra_decompiles` so a
- // successful spawn seeds the captured list transparently.
+ // 1. Try to obtain a Ghidra capture (or accept the caller's).
let spawn_note: Option<String> = None;
let (effective_captured, spawn_note): (Option<Vec<CapturedGhidraDecompile>>, Option<String>) =
if cfg.captured_ghidra_decompiles.is_some() {
@@ -229,50 +428,127 @@ pub fn compare(prog: &Program, cfg: &GhidraOracleConfig) -> GhidraOracleReport {
(None, spawn_note)
};
+ // 2. Build the shared entry list. When Ghidra output is available,
+ // the shared set is the intersection of Ghidra entries and the
+ // Ghidrust analyzer's function list (capped by `max_functions`).
+ // When Ghidra is unavailable we fall back to the Ghidrust list
+ // unchanged so the methodology-only run keeps producing rows.
+ let ghidrust_entries: Vec<u64> = prog
+ .analysis
+ .functions
+ .iter()
+ .map(|f| f.entry)
+ .collect();
+ let shared_entries: Vec<u64> = if let Some(cap) = &effective_captured {
+ let ghidra_set: std::collections::BTreeSet<u64> =
+ cap.iter().map(|c| c.entry).collect();
+ let mut inter: Vec<u64> = ghidrust_entries
+ .iter()
+ .copied()
+ .filter(|e| ghidra_set.contains(e))
+ .take(max_functions)
+ .collect();
+ if inter.is_empty() {
+ // No overlap — fall back to the Ghidrust list but mark rows as
+ // "no ghidra match" so nobody misreads the report.
+ inter = ghidrust_entries
+ .iter()
+ .copied()
+ .take(max_functions)
+ .collect();
+ }
+ inter
+ } else {
+ ghidrust_entries.iter().copied().take(max_functions).collect()
+ };
+
+ // 3. Ghidrust side: run the selected stage on the shared entry set.
+ let ghidrust = match cfg.ghidrust_stage {
+ GhidrustStage::Stage0 | GhidrustStage::Stage05 => {
+ // Stage-0.5 timings still populated via the legacy bench;
+ // Stage-1 columns stay zero. Kept behind a flag so regression
+ // runs can keep the old shape.
+ bench_program(prog, max_functions, max_insns)
+ }
+ GhidrustStage::Stage1 => bench_program_stage1(
+ prog,
+ Some(&shared_entries),
+ max_functions,
+ max_insns,
+ cfg.call_conv.into(),
+ ),
+ };
+
let mut rows = Vec::with_capacity(ghidrust.per_function.len());
- let (ghidra_total_us, ghidra_unavailable) = if let Some(cap) = &effective_captured
- {
+ let (ghidra_total_us, ghidra_unavailable) = if let Some(cap) = &effective_captured {
let mut sum = 0u128;
let mut any_wall = false;
for f in &ghidrust.per_function {
- let m = cap
- .iter()
- .find(|c| c.entry == f.entry || c.name == f.name);
- let (kind, blocks_est, note) = match m {
+ let m = cap.iter().find(|c| c.entry == f.entry || c.name == f.name);
+ let (kind, blocks_est, note, sim, wall) = match m {
Some(c) => {
if let Some(w) = c.wall_us {
sum += w;
any_wall = true;
}
let blocks = ghidra_blocks_estimate(&c.c_source);
+ let sim = if !f.stage1_text.is_empty() && !c.c_source.is_empty() {
+ Some(token_similarity(&f.stage1_text, &c.c_source))
+ } else {
+ None
+ };
+ let ghidrust_blocks_score = if cfg.ghidrust_stage == GhidrustStage::Stage1 {
+ f.stage1_leaf_count.max(1)
+ } else {
+ stage05_block_estimate(f)
+ };
let kind = if blocks == 0 && f.insn_count > 0 {
MatchKind::MissingGhidrust
} else if f.insn_count == 0 {
MatchKind::MissingGhidrust
- } else if (blocks as i64 - stage05_block_estimate(f) as i64).abs() <= 1 {
+ } else if (blocks as i64 - ghidrust_blocks_score as i64).abs() <= 1 {
MatchKind::Similar
} else {
MatchKind::Divergent
};
- (kind, blocks, "captured".to_string())
+ (
+ kind,
+ blocks,
+ match sim {
+ Some(s) => format!("captured, token_sim={:.2}", s),
+ None => "captured".to_string(),
+ },
+ sim,
+ c.wall_us,
+ )
}
- None => (MatchKind::MissingGhidra, 0, "no captured decompile".to_string()),
+ None => (
+ MatchKind::MissingGhidra,
+ 0,
+ "no captured decompile".to_string(),
+ None,
+ None,
+ ),
};
rows.push(StructuralMatch {
function: f.name.clone(),
entry: f.entry,
- ghidrust_blocks: stage05_block_estimate(f),
+ ghidrust_blocks: if cfg.ghidrust_stage == GhidrustStage::Stage1 {
+ f.stage1_leaf_count.max(1)
+ } else {
+ stage05_block_estimate(f)
+ },
ghidra_blocks_estimated: blocks_est,
ghidrust_insns: f.insn_count,
match_kind: kind,
notes: note,
+ token_similarity: sim,
+ ghidrust_stage1_us: f.stage1_us,
+ ghidra_wall_us: wall,
});
}
(if any_wall { Some(sum) } else { None }, false)
} else if cfg.ghidra_install_dir.is_some() {
- // Install dir was set but we couldn't get captured decompiles from
- // spawn — attach the spawn note (or a "binary missing" fallback)
- // so consumers can see exactly why. No timings are invented.
let note_head = spawn_note
.clone()
.unwrap_or_else(|| "ghidra_install_dir set but binary_path missing".into());
@@ -280,27 +556,40 @@ pub fn compare(prog: &Program, cfg: &GhidraOracleConfig) -> GhidraOracleReport {
rows.push(StructuralMatch {
function: f.name.clone(),
entry: f.entry,
- ghidrust_blocks: stage05_block_estimate(f),
+ ghidrust_blocks: if cfg.ghidrust_stage == GhidrustStage::Stage1 {
+ f.stage1_leaf_count.max(1)
+ } else {
+ stage05_block_estimate(f)
+ },
ghidra_blocks_estimated: 0,
ghidrust_insns: f.insn_count,
match_kind: MatchKind::MissingGhidra,
notes: format!(
"{note_head} — see docs/GHIDRA_HEADTOHEAD.md § Runbook"
),
+ token_similarity: None,
+ ghidrust_stage1_us: f.stage1_us,
+ ghidra_wall_us: None,
});
}
(None, true)
} else {
- // Methodology-only mode.
for f in &ghidrust.per_function {
rows.push(StructuralMatch {
function: f.name.clone(),
entry: f.entry,
- ghidrust_blocks: stage05_block_estimate(f),
+ ghidrust_blocks: if cfg.ghidrust_stage == GhidrustStage::Stage1 {
+ f.stage1_leaf_count.max(1)
+ } else {
+ stage05_block_estimate(f)
+ },
ghidra_blocks_estimated: 0,
ghidrust_insns: f.insn_count,
match_kind: MatchKind::MissingGhidra,
notes: "no ghidra_install_dir supplied — methodology-only run".into(),
+ token_similarity: None,
+ ghidrust_stage1_us: f.stage1_us,
+ ghidra_wall_us: None,
});
}
(None, true)
@@ -319,6 +608,26 @@ pub fn compare(prog: &Program, cfg: &GhidraOracleConfig) -> GhidraOracleReport {
}
}
+/// Public helper: intersection of Ghidra-captured entries and the
+/// Ghidrust analyzer's function list, capped at `max_functions`. Used
+/// by [`compare`] and callers who need the shared entry set for their
+/// own analyses / tables.
+pub fn shared_entry_list(
+ prog: &Program,
+ captured: &[CapturedGhidraDecompile],
+ max_functions: usize,
+) -> Vec<u64> {
+ let ghidra_set: std::collections::BTreeSet<u64> =
+ captured.iter().map(|c| c.entry).collect();
+ prog.analysis
+ .functions
+ .iter()
+ .map(|f| f.entry)
+ .filter(|e| ghidra_set.contains(e))
+ .take(max_functions)
+ .collect()
+}
+
fn stage05_block_estimate(f: &crate::FunctionBench) -> usize {
// We don't currently persist block counts through the bench summary, so
// approximate: each 8 instructions → 1 block (very rough). Callers who
@@ -842,6 +1151,104 @@ mod tests {
let _ = std::fs::remove_dir_all(&d);
}
+ #[test]
+ fn token_similarity_matches_identical_prototype_shapes() {
+ let a = "void foo(void) { int x = 0; return; }";
+ let b = "void foo(void) { int x = 0; return; }";
+ assert!(
+ (token_similarity(a, b) - 1.0).abs() < 1e-6,
+ "identical strings should yield sim=1.0"
+ );
+ }
+
+ #[test]
+ fn token_similarity_scores_partial_overlap() {
+ let a = "int foo(int x) { return x + 1; }";
+ let b = "int foo(int y) { return y + 1; }";
+ let sim = token_similarity(a, b);
+ assert!(
+ sim > 0.6 && sim < 1.0,
+ "expected 0.6 < sim < 1.0, got {sim}"
+ );
+ }
+
+ #[test]
+ fn token_similarity_disjoint_returns_low() {
+ let a = "void foo(void) { return; }";
+ let b = "int bar(int x, int y) { return x * y; }";
+ let sim = token_similarity(a, b);
+ assert!(sim < 0.4, "expected low similarity, got {sim}");
+ }
+
+ #[test]
+ fn tokenize_normalizes_local_and_param_names() {
+ let a = "int f(int param_1) { int local_1c = param_1; return local_1c; }";
+ let b = "int f(int arg_0) { int var_1 = arg_0; return var_1; }";
+ let sim = token_similarity(a, b);
+ assert!(
+ sim > 0.75,
+ "normalized locals/params should be treated as same, got {sim}"
+ );
+ }
+
+ #[test]
+ fn shared_entry_list_intersects_analyzer_and_capture() {
+ // The tiny fixture requires the Function Start analyzer to populate
+ // `prog.analysis.functions`. Without that pass the analyzer list
+ // is empty and the intersection is empty by construction — an
+ // honest outcome for the fair-comparison metric.
+ use ghidrust_core::run_analyzers;
+ let mut prog = load_path(fixture_path("tiny_x64.pe")).unwrap();
+ let _ = run_analyzers(&mut prog, &["Function Start Search"]);
+ let entry = prog.entry.unwrap();
+ let captured = vec![
+ CapturedGhidraDecompile {
+ name: "entry".into(),
+ entry,
+ c_source: "void entry(void) { return; }".into(),
+ wall_us: Some(500),
+ },
+ CapturedGhidraDecompile {
+ name: "not_in_ghidrust".into(),
+ entry: 0xdeadbeef,
+ c_source: "void x(void) {}".into(),
+ wall_us: Some(500),
+ },
+ ];
+ let shared = shared_entry_list(&prog, &captured, 32);
+ // Analyzer should have found the entry. If it doesn't (the fixture
+ // couldn't produce one via prologue-scan), assert we correctly
+ // detected the miss rather than fabricating a match.
+ if prog.analysis.functions.iter().any(|f| f.entry == entry) {
+ assert!(shared.contains(&entry), "expected shared entry: {shared:?}");
+ }
+ assert!(!shared.contains(&0xdeadbeef), "capture-only entries filtered out");
+ }
+
+ #[test]
+ fn stage1_row_includes_token_similarity_when_capture_present() {
+ let prog = load_path(fixture_path("tiny_x64.pe")).unwrap();
+ let entry = prog.entry.unwrap();
+ let cfg = GhidraOracleConfig {
+ captured_ghidra_decompiles: Some(vec![CapturedGhidraDecompile {
+ name: format!("FUN_{entry:016x}"),
+ entry,
+ c_source: "void FUN_entry(void) { return; }".into(),
+ wall_us: Some(1234),
+ }]),
+ ghidrust_stage: GhidrustStage::Stage1,
+ ..Default::default()
+ };
+ let rep = compare(&prog, &cfg);
+ assert!(!rep.rows.is_empty(), "expected rows");
+ let matched = rep.rows.iter().find(|r| r.entry == entry).expect("row");
+ assert!(
+ matched.token_similarity.is_some(),
+ "Stage-1 row should carry token_similarity"
+ );
+ assert!(matched.ghidrust_stage1_us > 0, "Stage-1 wall must be captured");
+ }
+
#[test]
fn decompile_and_report_java_stays_in_sync_with_runbook() {
// The runbook in docs/GHIDRA_HEADTOHEAD.md documents the same script
diff --git a/crates/ghidrust-decomp/src/ir_emit.rs b/crates/ghidrust-decomp/src/ir_emit.rs
index 7235643..501e318 100644
--- a/crates/ghidrust-decomp/src/ir_emit.rs
+++ b/crates/ghidrust-decomp/src/ir_emit.rs
@@ -109,17 +109,26 @@ fn emit_from_ir(insn: &Instruction, ir: &[PcodeOp]) -> String {
| OpCode::IntAnd
| OpCode::IntOr
| OpCode::IntMult
+ | OpCode::IntDiv
+ | OpCode::IntSDiv
+ | OpCode::IntRem
+ | OpCode::IntSRem
| OpCode::IntLeft
| OpCode::IntRight
| OpCode::IntSRight
| OpCode::IntNegate
| OpCode::IntNot
+ | OpCode::IntSExt
+ | OpCode::IntZExt
| OpCode::Load
| OpCode::Store
| OpCode::Push
| OpCode::Pop
| OpCode::Call
| OpCode::CallInd
+ | OpCode::Trap
+ | OpCode::Cast
+ | OpCode::Ptradd
)
});
@@ -163,9 +172,36 @@ fn pretty_op(op: &PcodeOp) -> Option<String> {
OpCode::IntAnd => binop_augmented(op, "&"),
OpCode::IntOr => binop_augmented(op, "|"),
OpCode::IntMult => binop_augmented(op, "*"),
+ OpCode::IntDiv | OpCode::IntSDiv => binop_augmented(op, "/"),
+ OpCode::IntRem | OpCode::IntSRem => binop_augmented(op, "%"),
OpCode::IntLeft => binop_augmented(op, "<<"),
OpCode::IntRight => binop_augmented(op, ">>"),
OpCode::IntSRight => binop_augmented(op, ">>>"),
+ OpCode::IntSExt => {
+ let dst = op.output.as_ref()?;
+ let a = op.inputs.first()?;
+ Some(format!("{} = (int{}_t){};", vn(dst), dst.size * 8, vn(a)))
+ }
+ OpCode::IntZExt => {
+ let dst = op.output.as_ref()?;
+ let a = op.inputs.first()?;
+ Some(format!("{} = (uint{}_t){};", vn(dst), dst.size * 8, vn(a)))
+ }
+ OpCode::Cast => {
+ let dst = op.output.as_ref()?;
+ let a = op.inputs.first()?;
+ Some(format!("{} = (uint64_t){};", vn(dst), vn(a)))
+ }
+ OpCode::Ptradd => {
+ let dst = op.output.as_ref()?;
+ let a = op.inputs.first()?;
+ let b = op.inputs.get(1)?;
+ Some(format!("{} = {} + {};", vn(dst), vn(a), vn(b)))
+ }
+ OpCode::Trap => Some(format!(
+ "/* trap: {} */;",
+ op.note.as_deref().unwrap_or("trap")
+ )),
OpCode::IntNegate => {
let dst = op.output.as_ref()?;
let a = op.inputs.first()?;
@@ -413,8 +449,9 @@ mod tests {
#[test]
fn ir_emit_falls_back_when_ir_unavailable() {
- // Instruction the lift can't understand — text should fall back to
- // Stage-0-style comment scaffolding, not fabricated C.
+ // `hlt` is a lifted `Trap` op — Stage-0.5 emits an honest trap
+ // comment rather than fabricating a C statement. A truly unlifted
+ // opcode falls back to Stage-0 scaffolding (`/* mnemonic operands */;`).
let insn = Instruction {
address: 0x3000,
bytes: vec![0xf4],
@@ -425,6 +462,26 @@ mod tests {
let d = decompile_instructions("halted", 0x3000, &[insn.clone()]);
let seq = lift_instructions(&[insn]);
let text = emit_ir_pseudo_c(&d.name, d.entry, &d.blocks, &seq);
- assert!(text.contains("/* hlt */;"), "should preserve unknown mnemonic:\n{text}");
+ assert!(
+ text.contains("trap: hlt") || text.contains("/* hlt */"),
+ "hlt should render as a Trap comment or stage-0 scaffolding:\n{text}"
+ );
+
+ // A truly unhandled mnemonic (never lifted, never decoded) still
+ // survives via the Stage-0 fallback branch of emit_ir_pseudo_c.
+ let unknown = Instruction {
+ address: 0x3010,
+ bytes: vec![0xff, 0xff],
+ mnemonic: "wibble".into(),
+ operands: "42".into(),
+ length: 2,
+ };
+ let d2 = decompile_instructions("wibbler", 0x3010, &[unknown.clone()]);
+ let seq2 = lift_instructions(&[unknown]);
+ let text2 = emit_ir_pseudo_c(&d2.name, d2.entry, &d2.blocks, &seq2);
+ assert!(
+ text2.contains("/* wibble 42 */;"),
+ "unhandled mnemonic should preserve scaffolding:\n{text2}"
+ );
}
}
diff --git a/crates/ghidrust-decomp/src/lib.rs b/crates/ghidrust-decomp/src/lib.rs
index d46616f..8972abf 100644
--- a/crates/ghidrust-decomp/src/lib.rs
+++ b/crates/ghidrust-decomp/src/lib.rs
@@ -23,10 +23,14 @@ pub mod gpu_decompile;
pub mod ir_emit;
pub mod stage1;
-pub use bench::{bench_functions, bench_program, BenchReport, FunctionBench};
+pub use bench::{
+ bench_functions, bench_program, bench_program_stage1, bench_program_stage1_parallel,
+ BenchReport, FunctionBench,
+};
pub use ghidra_oracle::{
- compare as ghidra_headtohead, spawn_ghidra_headless, CapturedGhidraDecompile,
- GhidraOracleConfig, GhidraOracleReport, GhidraSpawnError, MatchKind, StructuralMatch,
+ compare as ghidra_headtohead, shared_entry_list, spawn_ghidra_headless, token_similarity,
+ CapturedGhidraDecompile, GhidraOracleConfig, GhidraOracleReport, GhidraSpawnError,
+ GhidrustCallConv, GhidrustStage, MatchKind, StructuralMatch,
};
pub use stage1::{emit_stage1, emit_stage1_with_hints, is_structured, Stage1Result, Stage1Summary};
@@ -54,6 +58,34 @@ pub fn structure_hints_from(prog: &Program) -> StructureHints {
)
}
+/// Convert a recovered [`Stage1Result`]'s [`ghidrust_types::FunctionSignature`]
+/// into the shape `ghidrust_core::ProgramEdits` expects for
+/// `commit_params` / `commit_return_type`. Returns
+/// `(return_type_c, parameters_c, locals_c)` — each already rendered as a
+/// C declaration string ("`uint32_t param_1`", "`struct s_1* param_2`", …).
+///
+/// Meant to be called from the GUI's `Decompiler → Commit Params/Return`
+/// action so the recovered types round-trip into user edits without the
+/// GUI having to know the Ghidrust type lattice.
+pub fn stage1_commit_strings(
+ stage1: &Stage1Result,
+) -> (String, Vec<String>, Vec<String>) {
+ let ret = stage1.types.signature.return_type.c_style();
+ let params: Vec<String> = stage1
+ .types
+ .params
+ .iter()
+ .map(|p| format!("{} {}", p.ty.c_style(), p.name))
+ .collect();
+ let locals: Vec<String> = stage1
+ .types
+ .locals
+ .iter()
+ .map(|l| format!("{} {}", l.ty.c_style(), l.name))
+ .collect();
+ (ret, params, locals)
+}
+
pub use gpu_decompile::{
bench_vram_decompile_vs_cpu, classic_mnemonic_to_op, decode_gdecomp_pseudo_c,
encode_gdecomp_dump, equivalence_multipass_vs_classic_code, gpu_decompile_code_to_file,
@@ -597,6 +629,70 @@ mod tests {
assert!(d.pseudo_c.contains("return;"));
}
+ /// Phase A gate: median lift ratio across the fixture corpus must be
+ /// ≥ 98%. This test enumerates every function the analyzer recovered
+ /// in the shipped fixtures (analysis_lab.pe, tiny_x64.pe, tiny_x64.elf)
+ /// and averages the per-function `LiftCoverage.ratio()`.
+ #[test]
+ fn fixture_corpus_lift_ratio_meets_phase_a_gate() {
+ use ghidrust_core::run_analyzers;
+ use ghidrust_lift::{coverage as lift_coverage, lift_instructions};
+ let fixtures = [
+ "analysis_lab.pe",
+ "tiny_x64.pe",
+ "tiny_x64.elf",
+ ];
+ let mut total_ratio = 0f32;
+ let mut samples = 0usize;
+ let mut per_fixture: Vec<(String, f32, usize)> = Vec::new();
+ for fx in fixtures {
+ let mut prog = load_path(fixture_path(fx))
+ .unwrap_or_else(|e| panic!("load {fx}: {e}"));
+ let _ = run_analyzers(&mut prog, &["Function Start Search"]);
+ let mut entries: Vec<u64> = prog
+ .analysis
+ .functions
+ .iter()
+ .map(|f| f.entry)
+ .collect();
+ if entries.is_empty() {
+ if let Some(e) = prog.entry {
+ entries.push(e);
+ }
+ }
+ let mut fx_total = 0f32;
+ let mut fx_n = 0usize;
+ for va in entries {
+ let insns = match disassemble_range(&prog, va, 128) {
+ Ok(v) if !v.is_empty() => v,
+ _ => continue,
+ };
+ let seq = lift_instructions(&insns);
+ let cov = lift_coverage(&seq, insns.len());
+ if cov.total_ops == 0 {
+ continue;
+ }
+ fx_total += cov.ratio();
+ fx_n += 1;
+ total_ratio += cov.ratio();
+ samples += 1;
+ }
+ let avg = if fx_n > 0 { fx_total / fx_n as f32 } else { 0.0 };
+ per_fixture.push((fx.to_string(), avg, fx_n));
+ }
+ assert!(samples > 0, "fixture corpus produced no lift samples");
+ let avg = total_ratio / samples as f32;
+ eprintln!("--- fixture corpus lift ratios ---");
+ for (fx, r, n) in &per_fixture {
+ eprintln!(" {fx:<20} avg={:.3} functions={}", r, n);
+ }
+ eprintln!(" overall avg={:.3} samples={}", avg, samples);
+ assert!(
+ avg >= 0.98,
+ "Phase A gate: fixture-corpus average lift ratio {avg:.3} < 0.98"
+ );
+ }
+
#[test]
fn fixture_entry_decompiles_nonempty() {
let prog = load_path(fixture_path("tiny_x64.pe")).expect("load pe");
diff --git a/crates/ghidrust-decomp/src/stage1.rs b/crates/ghidrust-decomp/src/stage1.rs
index b784d5e..5d5d357 100644
--- a/crates/ghidrust-decomp/src/stage1.rs
+++ b/crates/ghidrust-decomp/src/stage1.rs
@@ -14,13 +14,16 @@ use ghidrust_decode::Instruction;
use ghidrust_ir::{AddrSpace, IrSequence, OpCode};
use ghidrust_lift::{coverage as lift_coverage, flag_off, lift_instructions, LiftCoverage};
use ghidrust_ssa::{
- build_cfg_with_leaders, build_ssa, copy_propagate, SsaBlock, SsaFunction, SsaOp, SsaOperand,
+ build_cfg_with_leaders, build_ssa, const_fold, copy_propagate, dead_code_eliminate,
+ load_store_propagate, SsaBlock, SsaFunction, SsaOp, SsaOperand,
};
use ghidrust_structure::{
structure_function_with_hints, NaturalLoop, Region, ShortCircuitClause, ShortCircuitKind,
StructureHints, StructureReport, SwitchCase,
};
-use ghidrust_types::{recover, CallConv, ParamList, RustType, StackLocal, TypeRecovery};
+use ghidrust_types::{
+ recover_with_name, CallConv, ParamList, RustType, StackLocal, TypeRecovery,
+};
/// Everything Stage-1 produces alongside the C text: SSA, structure, types
/// so callers (bench, GUI, MCP) can display the intermediate views without
@@ -75,10 +78,17 @@ pub fn emit_stage1_with_hints(
.collect();
let cfg = build_cfg_with_leaders(&seq, entry, region_end, &extra_leaders);
let mut ssa = build_ssa(&cfg);
- // Cheap dataflow pass; Stage-1 emit reads propagated operands directly.
- let _rewrites = copy_propagate(&mut ssa);
+ // Phase B dataflow: propagate copies, forward memory round-trips
+ // (store→load), fold constant arithmetic, drop dead pure ops. Order
+ // matters — const_fold expects copies already threaded, and DCE
+ // shouldn't run until we know which values still have a live use.
+ let _ = copy_propagate(&mut ssa);
+ let _ = load_store_propagate(&mut ssa);
+ let _ = copy_propagate(&mut ssa);
+ let _ = const_fold(&mut ssa);
+ let _ = dead_code_eliminate(&mut ssa);
let structure = structure_function_with_hints(&cfg, &ssa, hints);
- let types = recover(&ssa, conv);
+ let types = recover_with_name(&ssa, conv, name);
let coverage = lift_coverage(&seq, insns.len());
let text = render_function(name, entry, blocks, &ssa, &structure, &types, coverage);
@@ -114,8 +124,9 @@ fn render_function(
cov.ratio() * 100.0
));
- // Function signature.
- out.push_str(&format!("void {name}("));
+ // Function signature — driven by recovered return type + params.
+ let ret_c = types.signature.return_type.c_style();
+ out.push_str(&format!("{ret_c} {name}("));
if types.params.is_empty() {
out.push_str("void");
} else {
@@ -128,6 +139,30 @@ fn render_function(
}
out.push_str(") {\n");
+ // Recovered structs — emitted as forward declarations so the pointer
+ // types have a definition to reference.
+ if !types.structs.is_empty() {
+ for (_key, s) in &types.structs {
+ out.push_str(&format!(
+ " /* struct {} — recovered fields: {} */\n",
+ s.tag,
+ s.fields.len()
+ ));
+ out.push_str(&format!(" struct {} {{\n", s.tag));
+ for (off, f) in &s.fields {
+ out.push_str(&format!(
+ " {} field_{:x}; /* @{:#x} width={} */\n",
+ f.ty.c_style(),
+ off,
+ off,
+ f.width
+ ));
+ }
+ out.push_str(" };\n");
+ }
+ out.push('\n');
+ }
+
// Local declarations.
for l in types.locals.iter() {
out.push_str(&format!(
@@ -173,6 +208,12 @@ fn render_region(r: &Region, ind: usize, ctx: &mut RenderCtx, out: &mut String)
Region::Goto(b) => {
out.push_str(&format!("{}goto block_{};\n", indent(ind), b));
}
+ Region::Break => {
+ out.push_str(&format!("{}break;\n", indent(ind)));
+ }
+ Region::Continue => {
+ out.push_str(&format!("{}continue;\n", indent(ind)));
+ }
Region::Seq(rs) => {
for r in rs {
render_region(r, ind, ctx, out);
@@ -329,15 +370,28 @@ fn render_block_body(
let Some(block) = ctx.ssa.block(b) else {
return;
};
- if !block.phis.is_empty() {
- for phi in &block.phis {
- out.push_str(&indent(ind));
- out.push_str(&format!(
- "/* {} = φ({} predecessors) */\n",
- format_value_named(phi.out, ctx.types),
- phi.incoming.len()
- ));
+ // Phi nodes are emitted only when they carry a real def (version > 0).
+ // Trivial live-in passthroughs get elided so Stage-1 doesn't clutter
+ // every join with a phi header comment.
+ for phi in &block.phis {
+ if phi.out.version == 0 {
+ continue;
+ }
+ // Skip phis whose incoming values all match the phi's own key —
+ // those are just "same variable coming from every predecessor" and
+ // Stage-1's typed variables handle the naming already.
+ let all_trivial = phi
+ .incoming
+ .iter()
+ .all(|(_, v)| v.map(|inc| inc.key() == phi.out.key()).unwrap_or(true));
+ if all_trivial {
+ continue;
}
+ out.push_str(&indent(ind));
+ out.push_str(&format!(
+ "/* phi: {} */\n",
+ format_value_named(phi.out, ctx.types)
+ ));
}
let last_idx = block.ops.len().saturating_sub(1);
for (i, op) in block.ops.iter().enumerate() {
@@ -437,11 +491,100 @@ fn emit_op(op: &SsaOp, ctx: &mut RenderCtx) -> Option<String> {
OpCode::IntAnd => binop("&", op, ctx),
OpCode::IntOr => binop("|", op, ctx),
OpCode::IntMult => binop("*", op, ctx),
+ OpCode::IntDiv => binop("/", op, ctx),
+ OpCode::IntSDiv => binop("/", op, ctx),
+ OpCode::IntRem => binop("%", op, ctx),
+ OpCode::IntSRem => binop("%", op, ctx),
OpCode::IntLeft => binop("<<", op, ctx),
OpCode::IntRight => binop(">>", op, ctx),
OpCode::IntSRight => binop(">>>", op, ctx),
OpCode::IntNegate => unop("-", op, ctx),
OpCode::IntNot => unop("~", op, ctx),
+ OpCode::IntSExt => {
+ let dst = op.output?;
+ let a = op.inputs.first()?;
+ Some(format!(
+ "{} = (int{}_t){};",
+ format_value_named(dst, ctx.types),
+ dst.size * 8,
+ format_operand(a, ctx.types)
+ ))
+ }
+ OpCode::IntZExt => {
+ let dst = op.output?;
+ let a = op.inputs.first()?;
+ Some(format!(
+ "{} = (uint{}_t){};",
+ format_value_named(dst, ctx.types),
+ dst.size * 8,
+ format_operand(a, ctx.types)
+ ))
+ }
+ OpCode::Cast => {
+ let dst = op.output?;
+ let a = op.inputs.first()?;
+ // Prefer the recovered destination type over the raw pcode
+ // width so `(struct s_1*)` / `(int32_t)` renders when known.
+ let dst_ty = ctx.types.types.get(dst.space, dst.offset);
+ let cast_ty = if dst_ty == RustType::Bottom {
+ format!("uint{}_t", dst.size * 8)
+ } else {
+ dst_ty.c_style()
+ };
+ Some(format!(
+ "{} = ({cast_ty}){};",
+ format_value_named(dst, ctx.types),
+ format_operand(a, ctx.types)
+ ))
+ }
+ OpCode::Ptradd => {
+ let dst = op.output?;
+ let a = op.inputs.first()?;
+ let b = op.inputs.get(1)?;
+ Some(format!(
+ "{} = {} + {};",
+ format_value_named(dst, ctx.types),
+ format_operand(a, ctx.types),
+ format_operand(b, ctx.types)
+ ))
+ }
+ OpCode::Piece => {
+ let dst = op.output?;
+ let a = op.inputs.first()?;
+ let b = op.inputs.get(1)?;
+ Some(format!(
+ "{} = ({} << {}) | {};",
+ format_value_named(dst, ctx.types),
+ format_operand(a, ctx.types),
+ op.inputs
+ .first()
+ .map(|v| v.varnode().size * 8)
+ .unwrap_or(0),
+ format_operand(b, ctx.types)
+ ))
+ }
+ OpCode::Subpiece => {
+ let dst = op.output?;
+ let a = op.inputs.first()?;
+ let shift = op
+ .inputs
+ .get(1)
+ .and_then(|v| match v {
+ SsaOperand::Const(c) => Some(c.offset),
+ _ => None,
+ })
+ .unwrap_or(0);
+ Some(format!(
+ "{} = ({}) >> {};",
+ format_value_named(dst, ctx.types),
+ format_operand(a, ctx.types),
+ shift * 8
+ ))
+ }
+ OpCode::Trap => Some(format!(
+ "/* trap: {} */",
+ op.note.as_deref().unwrap_or("trap")
+ )),
OpCode::IntEqual => binop("==", op, ctx),
OpCode::IntNotEqual => binop("!=", op, ctx),
OpCode::IntLess => binop("<", op, ctx),
@@ -454,18 +597,18 @@ fn emit_op(op: &SsaOp, ctx: &mut RenderCtx) -> Option<String> {
OpCode::Load => {
let dst = op.output?;
let addr = op.inputs.first()?;
+ let deref = format_deref(addr, ctx);
Some(format!(
- "{} = *({});",
- format_value_named(dst, ctx.types),
- format_operand(addr, ctx.types)
+ "{} = {deref};",
+ format_value_named(dst, ctx.types)
))
}
OpCode::Store => {
let addr = op.inputs.first()?;
let val = op.inputs.get(1)?;
+ let deref = format_deref(addr, ctx);
Some(format!(
- "*({}) = {};",
- format_operand(addr, ctx.types),
+ "{deref} = {};",
format_operand(val, ctx.types)
))
}
@@ -507,6 +650,58 @@ fn unop(sym: &str, op: &SsaOp, ctx: &mut RenderCtx) -> Option<String> {
))
}
+/// Render a pointer dereference. When the pointer base has a recovered
+/// [`RustType::StructPtr`] and the address is `base + K` for a known
+/// field offset, render as `base->field_<hex>` — the same shape Ghidra's
+/// PrintC uses when a struct DataType is committed. Falls back to plain
+/// `*(addr)` when the shape isn't recognized.
+fn format_deref(addr: &SsaOperand, ctx: &RenderCtx) -> String {
+ if let SsaOperand::Value(v) = addr {
+ // Try `base + K` decomposition using the SSA def graph.
+ if let Some((base, offset)) = decompose_ssa_addr(v, ctx.ssa) {
+ let base_ty = ctx.types.types.get(base.space, base.offset);
+ if let RustType::StructPtr { key } = &base_ty {
+ if let Some(seed) = ctx.types.structs.get(key) {
+ if seed.fields.contains_key(&offset) {
+ return format!(
+ "{}->field_{:x}",
+ format_value_named(base, ctx.types),
+ offset
+ );
+ }
+ }
+ }
+ if let RustType::ArrayPtr { elem_width, .. } = base_ty {
+ if elem_width > 0 && offset % elem_width as u64 == 0 {
+ let idx = offset / elem_width as u64;
+ return format!(
+ "{}[{idx}]",
+ format_value_named(base, ctx.types)
+ );
+ }
+ }
+ }
+ }
+ format!("*({})", format_operand(addr, &ctx.types))
+}
+
+fn decompose_ssa_addr(
+ v: &ghidrust_ssa::SsaValue,
+ ssa: &SsaFunction,
+) -> Option<(ghidrust_ssa::SsaValue, u64)> {
+ for b in &ssa.blocks {
+ for op in &b.ops {
+ let Some(out) = op.output else { continue };
+ if out == *v && matches!(op.opcode, OpCode::IntAdd | OpCode::Ptradd) {
+ let base = op.inputs.first().and_then(SsaOperand::as_value)?;
+ let offset = op.inputs.get(1).and_then(SsaOperand::as_const).unwrap_or(0);
+ return Some((base, offset));
+ }
+ }
+ }
+ None
+}
+
fn emit_branch_target(v: &SsaOperand) -> String {
match v {
SsaOperand::Const(v) if v.space == AddrSpace::Constant => format!("L_{:x}", v.offset),
@@ -636,6 +831,12 @@ pub struct Stage1Summary {
pub locals: usize,
pub params: usize,
pub lift_ratio: f32,
+ /// Fraction of structured leaves that are unstructured `goto`s. The
+ /// Phase D target is <0.15 on the lab corpus.
+ pub goto_rate: f32,
+ /// Recovered struct seed count — a proxy for how much struct/array
+ /// shape Stage-1 was able to lift from load/store patterns.
+ pub structs: usize,
}
impl Stage1Result {
@@ -647,6 +848,8 @@ impl Stage1Result {
locals: self.types.locals.len(),
params: self.types.params.len(),
lift_ratio: self.coverage.ratio(),
+ goto_rate: ghidrust_structure::goto_rate(&self.structure.region),
+ structs: self.types.structs.len(),
}
}
}
@@ -700,10 +903,16 @@ mod tests {
#[test]
fn stage1_prologue_emits_return_and_function_header() {
// push rbp; mov rbp,rsp; xor eax,eax; pop rbp; ret
+ // The `xor eax,eax` before ret is a `return 0` idiom — recovered
+ // return type is uint32_t, not void.
let bytes = [0x55, 0x48, 0x89, 0xe5, 0x31, 0xc0, 0x5d, 0xc3];
let rep = stage1_bytes(&bytes, 0x1000, "prologue");
let text = &rep.pseudo_c;
- assert!(text.contains("void prologue"), "header missing:\n{text}");
+ assert!(text.contains("prologue"), "header missing:\n{text}");
+ assert!(
+ text.contains("uint32_t prologue") || text.contains("uint64_t prologue"),
+ "recovered int return type expected:\n{text}"
+ );
assert!(text.contains("return;"), "return missing:\n{text}");
assert!(text.contains("Stage-1"), "must self-identify as Stage-1:\n{text}");
// eax = 0 idiom lowered
@@ -851,11 +1060,99 @@ mod tests {
}
}
+ #[test]
+ fn stage1_pipeline_folds_and_dces_dead_arithmetic() {
+ // Phase B gate: t0 = 0x100; t1 = 0x20; rax = t0 + t1; ret
+ // — Stage-1 should render `rax = 0x120;` (const-folded), then keep
+ // the assignment because rax is a return-value register (DCE seed).
+ // 48 c7 c0 00 01 00 00 mov rax, 0x100
+ // 48 c7 c1 20 00 00 00 mov rcx, 0x20
+ // 48 01 c8 add rax, rcx
+ // c3 ret
+ let bytes = [
+ 0x48, 0xc7, 0xc0, 0x00, 0x01, 0x00, 0x00, // mov rax, 0x100
+ 0x48, 0xc7, 0xc1, 0x20, 0x00, 0x00, 0x00, // mov rcx, 0x20
+ 0x48, 0x01, 0xc8, // add rax, rcx
+ 0xc3, // ret
+ ];
+ let rep = stage1_bytes(&bytes, 0x5000, "add_two_consts");
+ assert!(
+ rep.pseudo_c.contains("0x120"),
+ "const_fold + copy_prop should render 0x120:\n{}",
+ rep.pseudo_c
+ );
+ }
+
+ #[test]
+ fn stage1_pipeline_drops_dead_pure_arithmetic() {
+ // ecx = 0; ret — rcx is not a return register, DCE should drop it.
+ // 31 c9 xor ecx, ecx
+ // c3 ret
+ let rep = stage1_bytes(&[0x31, 0xc9, 0xc3], 0x6000, "dead_ecx");
+ // The bare `ret` should be present.
+ assert!(rep.pseudo_c.contains("return;"));
+ // rcx should not appear in a live assignment (`ecx#N = 0;`) —
+ // DCE dropped it. It may still surface in a comment note.
+ let live_assign = rep
+ .pseudo_c
+ .lines()
+ .any(|l| l.contains("ecx") && l.trim().starts_with("ecx"));
+ assert!(
+ !live_assign,
+ "unused ecx write should be DCE-dropped, saw:\n{}",
+ rep.pseudo_c
+ );
+ }
+
+ #[test]
+ fn stage1_recovers_return_type_from_rax_write() {
+ // mov rax, rdi ; ret → return type recovered as uint64_t
+ let bytes = [0x48, 0x89, 0xf8, 0xc3];
+ let rep = stage1_bytes(&bytes, 0x7000, "id64");
+ let text = &rep.pseudo_c;
+ assert!(
+ text.contains("uint64_t id64") || text.contains("uint32_t id64"),
+ "expected typed return, saw:\n{text}"
+ );
+ assert_ne!(
+ rep.types.signature.return_type,
+ ghidrust_types::RustType::Void,
+ "RAX write must produce non-void return"
+ );
+ }
+
+ #[test]
+ fn stage1_diamond_has_low_goto_rate() {
+ let bytes = [0x39, 0xc1, 0x74, 0x02, 0x31, 0xc0, 0xc3, 0x31, 0xc9, 0xc3];
+ let rep = stage1_bytes(&bytes, 0x2000, "diamond_goto");
+ let s = rep.summary();
+ assert!(
+ s.goto_rate < 0.15,
+ "Phase D gate: diamond goto_rate {} < 0.15 expected, output:\n{}",
+ s.goto_rate,
+ rep.pseudo_c
+ );
+ }
+
+ #[test]
+ fn stage1_signature_carries_recovered_prototype() {
+ // 48 89 f8 mov rax, rdi
+ // 48 01 f0 add rax, rsi
+ // c3 ret
+ let bytes = [0x48, 0x89, 0xf8, 0x48, 0x01, 0xf0, 0xc3];
+ let rep = stage1_bytes(&bytes, 0x8000, "adder");
+ let sig = &rep.types.signature;
+ assert_eq!(sig.name, "adder");
+ assert!(!sig.params.is_empty(), "should recover rdi/rsi params");
+ let proto = sig.to_prototype();
+ assert!(proto.contains("adder("), "prototype: {proto}");
+ }
+
#[test]
fn stage1_falls_back_when_lift_ratio_too_low() {
use ghidrust_decode::Instruction;
- // hlt is not lifted → Stage-1 emits `unimplemented` markers instead
- // of fabricating C.
+ // `hlt` now lifts to a `Trap` op — Stage-1 preserves that as a
+ // trap comment so the output stays honest without fabricating C.
let insn = Instruction {
address: 0x4000,
bytes: vec![0xf4],
@@ -866,10 +1163,27 @@ mod tests {
let d = decompile_instructions("halted", 0x4000, &[insn.clone()]);
let rep = emit_stage1(&d.name, d.entry, &d.blocks, &[insn], CallConv::SystemV);
assert!(
- rep.pseudo_c.contains("unimplemented"),
- "unlifted op should be preserved as comment:\n{}",
+ rep.pseudo_c.contains("trap: hlt") || rep.pseudo_c.contains("unimplemented"),
+ "hlt should render as a Trap or Unimplemented comment:\n{}",
rep.pseudo_c
);
assert!(!is_structured(&rep), "hlt should not count as structured");
+
+ // A genuinely-unlifted mnemonic still surfaces via
+ // `OpCode::Unimplemented` so we never invent C.
+ let unknown = Instruction {
+ address: 0x4010,
+ bytes: vec![0xff, 0xff],
+ mnemonic: "wibble".into(),
+ operands: String::new(),
+ length: 2,
+ };
+ let d2 = decompile_instructions("wibbler", 0x4010, &[unknown.clone()]);
+ let rep2 = emit_stage1(&d2.name, d2.entry, &d2.blocks, &[unknown], CallConv::SystemV);
+ assert!(
+ rep2.pseudo_c.contains("unimplemented"),
+ "genuinely unlifted opcode should stay Unimplemented:\n{}",
+ rep2.pseudo_c
+ );
}
}
diff --git a/crates/ghidrust-gui/Cargo.toml b/crates/ghidrust-gui/Cargo.toml
index 7b9e30a..34039c8 100644
--- a/crates/ghidrust-gui/Cargo.toml
+++ b/crates/ghidrust-gui/Cargo.toml
@@ -17,3 +17,6 @@ ghidrust-types = { workspace = true }
eframe = { version = "0.31", default-features = true }
egui = "0.31"
rfd = "0.15"
+# Phase H (M8) — layout persistence (`.tool.json`) via serde_json.
+serde = { version = "1", features = ["derive"] }
+serde_json = "1"
diff --git a/crates/ghidrust-gui/src/debugger.rs b/crates/ghidrust-gui/src/debugger.rs
new file mode 100644
index 0000000..f0e466e
--- /dev/null
+++ b/crates/ghidrust-gui/src/debugger.rs
@@ -0,0 +1,405 @@
+//! Ghidrust GUI · Phase G (M7) — Debugger tool visibility.
+//!
+//! Ghidra ships a separate `Debugger` tool with a distinct catalog of
+//! `ComponentProvider`s (Targets, Threads, Modules, Regions, Registers,
+//! Stack, Breakpoints, Memory Bytes, Watches, Console). Ghidrust doesn't
+//! have a live debugger yet, but per `dev/UI_PARITY_PLAN.md` § 6 Phase G
+//! (M7) every debugger provider must be **visible** — a real pane with a
+//! labelled empty state pointing at the backend gap. This module owns
+//! that surface.
+//!
+//! Extracted per `dev/MODULARIZATION_PLAN.md` — new UI panes land here
+//! instead of piling into `main.rs`.
+
+use eframe::egui::{self, Color32, RichText, Ui};
+
+/// One provider in Ghidra's Debugger tool catalog.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
+pub enum DebuggerPane {
+ Targets,
+ Threads,
+ Modules,
+ Regions,
+ Registers,
+ Stack,
+ Breakpoints,
+ MemoryBytes,
+ Watches,
+ DebuggerConsole,
+}
+
+impl DebuggerPane {
+ pub const ALL: &'static [DebuggerPane] = &[
+ DebuggerPane::Targets,
+ DebuggerPane::Threads,
+ DebuggerPane::Modules,
+ DebuggerPane::Regions,
+ DebuggerPane::Registers,
+ DebuggerPane::Stack,
+ DebuggerPane::Breakpoints,
+ DebuggerPane::MemoryBytes,
+ DebuggerPane::Watches,
+ DebuggerPane::DebuggerConsole,
+ ];
+
+ /// Ghidra display title (Window menu label / provider `TITLE`).
+ pub const fn title(self) -> &'static str {
+ match self {
+ DebuggerPane::Targets => "Debugger Targets",
+ DebuggerPane::Threads => "Debugger Threads",
+ DebuggerPane::Modules => "Debugger Modules",
+ DebuggerPane::Regions => "Debugger Regions",
+ DebuggerPane::Registers => "Debugger Registers",
+ DebuggerPane::Stack => "Debugger Stack",
+ DebuggerPane::Breakpoints => "Debugger Breakpoints",
+ DebuggerPane::MemoryBytes => "Debugger Memory Bytes",
+ DebuggerPane::Watches => "Debugger Watches",
+ DebuggerPane::DebuggerConsole => "Debugger Console",
+ }
+ }
+
+ /// Ghidra plugin owner.
+ pub const fn plugin(self) -> &'static str {
+ match self {
+ DebuggerPane::Targets => "DebuggerTargetsPlugin",
+ DebuggerPane::Threads => "DebuggerThreadsPlugin",
+ DebuggerPane::Modules => "DebuggerModulesPlugin",
+ DebuggerPane::Regions => "DebuggerRegionsPlugin",
+ DebuggerPane::Registers => "DebuggerRegistersPlugin",
+ DebuggerPane::Stack => "DebuggerStackPlugin",
+ DebuggerPane::Breakpoints => "DebuggerBreakpointsPlugin",
+ DebuggerPane::MemoryBytes => "DebuggerMemoryBytesPlugin",
+ DebuggerPane::Watches => "DebuggerWatchesPlugin",
+ DebuggerPane::DebuggerConsole => "DebuggerConsolePlugin",
+ }
+ }
+
+ /// Stable egui window id for docking / layout persistence.
+ pub const fn egui_id(self) -> &'static str {
+ match self {
+ DebuggerPane::Targets => "pane_dbg_targets",
+ DebuggerPane::Threads => "pane_dbg_threads",
+ DebuggerPane::Modules => "pane_dbg_modules",
+ DebuggerPane::Regions => "pane_dbg_regions",
+ DebuggerPane::Registers => "pane_dbg_registers",
+ DebuggerPane::Stack => "pane_dbg_stack",
+ DebuggerPane::Breakpoints => "pane_dbg_breakpoints",
+ DebuggerPane::MemoryBytes => "pane_dbg_membytes",
+ DebuggerPane::Watches => "pane_dbg_watches",
+ DebuggerPane::DebuggerConsole => "pane_dbg_console",
+ }
+ }
+
+ /// Columns rendered in the empty-state table (Ghidra parity).
+ pub const fn columns(self) -> &'static [&'static str] {
+ match self {
+ DebuggerPane::Targets => &["Name", "Type", "State"],
+ DebuggerPane::Threads => &["TID", "Name", "State", "Comment"],
+ DebuggerPane::Modules => &["Base", "Name", "Path", "Size"],
+ DebuggerPane::Regions => &["Start", "End", "Perms", "Kind"],
+ DebuggerPane::Registers => &["Register", "Bits", "Value"],
+ DebuggerPane::Stack => &["Level", "Frame", "PC", "Function"],
+ DebuggerPane::Breakpoints => &["Enabled", "Address", "Kind", "Condition"],
+ DebuggerPane::MemoryBytes => &["Address", "Bytes", "ASCII"],
+ DebuggerPane::Watches => &["Expression", "Type", "Value"],
+ DebuggerPane::DebuggerConsole => &["Line"],
+ }
+ }
+
+ /// Copy pointing at the pending backend for this pane.
+ pub const fn backend_message(self) -> &'static str {
+ match self {
+ DebuggerPane::Targets => "Backend pending — no live target agents yet (Phase P12 in GHIDRA_PARITY_PHASE_PLANS.md).",
+ DebuggerPane::Threads => "Backend pending — target-agent thread model.",
+ DebuggerPane::Modules => "Backend pending — target-agent module list.",
+ DebuggerPane::Regions => "Backend pending — target-agent memory regions.",
+ DebuggerPane::Registers => "Backend pending — live register values (Register Manager renders the static register lattice).",
+ DebuggerPane::Stack => "Backend pending — target-agent stack unwinder.",
+ DebuggerPane::Breakpoints => "Backend pending — breakpoint model + agent set/clear.",
+ DebuggerPane::MemoryBytes => "Backend pending — live memory reads (Bytes pane renders static Program bytes).",
+ DebuggerPane::Watches => "Backend pending — expression evaluator + refresh.",
+ DebuggerPane::DebuggerConsole => "Backend pending — target-agent stdio.",
+ }
+ }
+}
+
+/// Ghidra `Debugger` menu action.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum DebuggerAction {
+ Launch,
+ Attach,
+ Disconnect,
+ Continue,
+ Interrupt,
+ StepInto,
+ StepOver,
+ StepOut,
+ ToggleBreakpoint,
+ ShowWatches,
+}
+
+impl DebuggerAction {
+ pub const ALL: &'static [DebuggerAction] = &[
+ DebuggerAction::Launch,
+ DebuggerAction::Attach,
+ DebuggerAction::Disconnect,
+ DebuggerAction::Continue,
+ DebuggerAction::Interrupt,
+ DebuggerAction::StepInto,
+ DebuggerAction::StepOver,
+ DebuggerAction::StepOut,
+ DebuggerAction::ToggleBreakpoint,
+ DebuggerAction::ShowWatches,
+ ];
+ pub const fn label(self) -> &'static str {
+ match self {
+ DebuggerAction::Launch => "Launch…",
+ DebuggerAction::Attach => "Attach…",
+ DebuggerAction::Disconnect => "Disconnect",
+ DebuggerAction::Continue => "Continue (F5)",
+ DebuggerAction::Interrupt => "Interrupt",
+ DebuggerAction::StepInto => "Step Into (F7)",
+ DebuggerAction::StepOver => "Step Over (F8)",
+ DebuggerAction::StepOut => "Step Out (Shift+F8)",
+ DebuggerAction::ToggleBreakpoint => "Toggle Breakpoint (F3)",
+ DebuggerAction::ShowWatches => "Show Watches Pane",
+ }
+ }
+}
+
+/// Persistent state for the debugger tool mode.
+#[derive(Debug, Clone, Default)]
+pub struct DebuggerState {
+ /// User-set breakpoint VAs (session-only until backend lands).
+ pub breakpoints: Vec<u64>,
+ /// User-set watch expressions.
+ pub watches: Vec<String>,
+ /// Whether the debugger tool mode is active (Ghidra `Debugger` tool
+ /// exists as a separate top-level menu group).
+ pub enabled: bool,
+ /// New-breakpoint input.
+ pub bp_input: String,
+ /// New-watch input.
+ pub watch_input: String,
+}
+
+impl DebuggerState {
+ pub fn toggle_breakpoint(&mut self, va: u64) {
+ if let Some(pos) = self.breakpoints.iter().position(|b| *b == va) {
+ self.breakpoints.remove(pos);
+ } else {
+ self.breakpoints.push(va);
+ self.breakpoints.sort();
+ }
+ }
+ /// Whether a session breakpoint is set at `va`.
+ ///
+ /// Kept `pub` so a future backend can query the session set (e.g., to
+ /// avoid re-emitting sw-breakpoints already set by the user).
+ #[allow(dead_code)]
+ pub fn has_breakpoint(&self, va: u64) -> bool {
+ self.breakpoints.contains(&va)
+ }
+ pub fn add_watch(&mut self, expr: impl Into<String>) {
+ let e = expr.into();
+ if !e.trim().is_empty() && !self.watches.iter().any(|w| w == &e) {
+ self.watches.push(e);
+ }
+ }
+ pub fn remove_watch(&mut self, idx: usize) {
+ if idx < self.watches.len() {
+ self.watches.remove(idx);
+ }
+ }
+}
+
+/// Render an honest-empty debugger pane. `state` is passed so the
+/// Breakpoints / Watches panes can render user-set entries even without a
+/// live target attached.
+pub fn render(pane: DebuggerPane, state: &mut DebuggerState, ui: &mut Ui, muted: Color32) {
+ ui.heading(pane.title());
+ ui.small(RichText::new(format!("Provider · {}", pane.plugin())).color(muted));
+ ui.separator();
+
+ match pane {
+ DebuggerPane::Breakpoints => render_breakpoints(state, ui, muted),
+ DebuggerPane::Watches => render_watches(state, ui, muted),
+ _ => render_empty_table(pane, ui, muted),
+ }
+}
+
+fn render_empty_table(pane: DebuggerPane, ui: &mut Ui, muted: Color32) {
+ ui.horizontal(|ui| {
+ for col in pane.columns() {
+ ui.strong(*col);
+ ui.separator();
+ }
+ });
+ ui.separator();
+ ui.add_space(6.0);
+ ui.label(
+ RichText::new(pane.backend_message())
+ .color(muted)
+ .italics(),
+ );
+ ui.add_space(4.0);
+ ui.small(
+ RichText::new("Pane is present for Ghidra Debugger visibility parity (M7). Real content lands with backend P12.")
+ .color(muted),
+ );
+}
+
+fn render_breakpoints(state: &mut DebuggerState, ui: &mut Ui, muted: Color32) {
+ ui.small(
+ RichText::new("Session-only breakpoint list (backend P12 will replace with target-agent state).")
+ .color(muted),
+ );
+ ui.horizontal(|ui| {
+ ui.label("Address:");
+ ui.add(
+ egui::TextEdit::singleline(&mut state.bp_input)
+ .desired_width(160.0)
+ .hint_text("0x140001000"),
+ );
+ if ui.button("Add Breakpoint").clicked() {
+ if let Some(va) = parse_hex(&state.bp_input) {
+ state.toggle_breakpoint(va);
+ state.bp_input.clear();
+ }
+ }
+ });
+ ui.separator();
+ if state.breakpoints.is_empty() {
+ ui.weak("No breakpoints set.");
+ return;
+ }
+ let mut delete: Option<usize> = None;
+ egui::Grid::new("dbg_bp_grid")
+ .num_columns(3)
+ .striped(true)
+ .show(ui, |ui| {
+ ui.strong("Enabled");
+ ui.strong("Address");
+ ui.strong("");
+ ui.end_row();
+ for (i, va) in state.breakpoints.iter().enumerate() {
+ ui.monospace("*"); // Enabled (no disable state until backend)
+ ui.monospace(format!("{va:#x}"));
+ if ui.small_button("Delete").clicked() {
+ delete = Some(i);
+ }
+ ui.end_row();
+ }
+ });
+ if let Some(i) = delete {
+ state.breakpoints.remove(i);
+ }
+}
+
+fn render_watches(state: &mut DebuggerState, ui: &mut Ui, muted: Color32) {
+ ui.small(
+ RichText::new("Session-only watch list (evaluator pending backend P12).").color(muted),
+ );
+ ui.horizontal(|ui| {
+ ui.label("Expression:");
+ ui.add(
+ egui::TextEdit::singleline(&mut state.watch_input)
+ .desired_width(280.0)
+ .hint_text("*(int*)rsp"),
+ );
+ if ui.button("Add Watch").clicked() {
+ let e = state.watch_input.clone();
+ state.add_watch(e);
+ state.watch_input.clear();
+ }
+ });
+ ui.separator();
+ if state.watches.is_empty() {
+ ui.weak("No watches.");
+ return;
+ }
+ let mut delete: Option<usize> = None;
+ egui::Grid::new("dbg_watch_grid")
+ .num_columns(3)
+ .striped(true)
+ .show(ui, |ui| {
+ ui.strong("Expression");
+ ui.strong("Value");
+ ui.strong("");
+ ui.end_row();
+ for (i, w) in state.watches.iter().enumerate() {
+ ui.monospace(w);
+ ui.small(RichText::new("<no target>").color(muted));
+ if ui.small_button("Delete").clicked() {
+ delete = Some(i);
+ }
+ ui.end_row();
+ }
+ });
+ if let Some(i) = delete {
+ state.remove_watch(i);
+ }
+}
+
+fn parse_hex(s: &str) -> Option<u64> {
+ let s = s.trim();
+ let s = s.strip_prefix("0x").or_else(|| s.strip_prefix("0X")).unwrap_or(s);
+ u64::from_str_radix(s, 16).ok()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn debugger_catalog_covers_ghidra_windows() {
+ let names: Vec<&'static str> = DebuggerPane::ALL.iter().map(|p| p.title()).collect();
+ for expected in [
+ "Debugger Targets",
+ "Debugger Threads",
+ "Debugger Modules",
+ "Debugger Regions",
+ "Debugger Registers",
+ "Debugger Stack",
+ "Debugger Breakpoints",
+ "Debugger Memory Bytes",
+ "Debugger Watches",
+ "Debugger Console",
+ ] {
+ assert!(names.contains(&expected), "missing debugger pane {expected}");
+ }
+ }
+
+ #[test]
+ fn every_debugger_pane_has_metadata() {
+ for p in DebuggerPane::ALL {
+ assert!(!p.title().is_empty());
+ assert!(!p.plugin().is_empty());
+ assert!(!p.egui_id().is_empty());
+ assert!(!p.columns().is_empty());
+ assert!(!p.backend_message().is_empty());
+ }
+ }
+
+ #[test]
+ fn breakpoint_toggle_flow() {
+ let mut s = DebuggerState::default();
+ s.toggle_breakpoint(0x1000);
+ assert!(s.has_breakpoint(0x1000));
+ s.toggle_breakpoint(0x1000);
+ assert!(!s.has_breakpoint(0x1000));
+ }
+
+ #[test]
+ fn watch_add_dedup_and_remove() {
+ let mut s = DebuggerState::default();
+ s.add_watch("rax");
+ s.add_watch("rax");
+ s.add_watch("");
+ assert_eq!(s.watches.len(), 1);
+ s.add_watch("rbx");
+ assert_eq!(s.watches.len(), 2);
+ s.remove_watch(0);
+ assert_eq!(s.watches[0], "rbx");
+ }
+}
diff --git a/crates/ghidrust-gui/src/entropy.rs b/crates/ghidrust-gui/src/entropy.rs
new file mode 100644
index 0000000..9500a76
--- /dev/null
+++ b/crates/ghidrust-gui/src/entropy.rs
@@ -0,0 +1,215 @@
+//! Ghidrust GUI · Phase E (M5) — Entropy strip + Overview banner.
+//!
+//! Renders the Ghidra `EntropyPlugin` and `OverviewPlugin` header strips as
+//! horizontal color bars sampled from executable memory blocks. Entropy is
+//! computed via `ghidrust-core::bulk_scan::entropy_windows_seq` (Shannon
+//! bits/byte, 0..8) so the strip is real, not fabricated.
+//!
+//! Extracted per `dev/MODULARIZATION_PLAN.md` — new UI panes land here
+//! instead of piling into `main.rs`.
+
+use eframe::egui::{self, Color32, Rect, Sense, Stroke, StrokeKind, Ui, Vec2};
+use ghidrust_core::{bulk_scan::entropy_windows_seq, Program};
+
+/// A single sampled window used by the strip visualisations.
+#[derive(Debug, Clone, Copy)]
+pub struct Sample {
+ pub va: u64,
+ pub end_va: u64,
+ /// Shannon entropy bits/byte in [0.0, 8.0].
+ pub entropy: f64,
+ /// Fraction of printable-ASCII bytes in the window ([0.0, 1.0]).
+ pub ascii_ratio: f32,
+}
+
+/// Compute per-block entropy samples across every mapped memory block.
+///
+/// `window` is bytes per sample (Ghidra default = 256). Result is flat,
+/// address-ordered, and honest: only mapped bytes are sampled.
+pub fn entropy_samples(prog: &Program, window: usize) -> Vec<Sample> {
+ let mut out = Vec::new();
+ let w = window.max(16);
+ for blk in &prog.blocks {
+ let ents = entropy_windows_seq(&blk.bytes, w);
+ for (i, e) in ents.iter().enumerate() {
+ let base = blk.va + (i as u64) * (w as u64);
+ let end = (base + w as u64).min(blk.va.saturating_add(blk.size));
+ let start_off = (i * w).min(blk.bytes.len());
+ let end_off = ((i + 1) * w).min(blk.bytes.len());
+ let slice = &blk.bytes[start_off..end_off];
+ let ascii = slice
+ .iter()
+ .filter(|b| (0x20u8..0x7Fu8).contains(*b) || matches!(**b, 0x09 | 0x0A | 0x0D))
+ .count();
+ let ratio = if slice.is_empty() {
+ 0.0
+ } else {
+ ascii as f32 / slice.len() as f32
+ };
+ out.push(Sample {
+ va: base,
+ end_va: end,
+ entropy: *e,
+ ascii_ratio: ratio,
+ });
+ }
+ }
+ out
+}
+
+/// Palette helper — map an entropy value to a Ghidra-like color ramp.
+pub fn entropy_color(e: f64) -> Color32 {
+ // Cold (blue) → high entropy warm (red).
+ let t = (e / 8.0).clamp(0.0, 1.0) as f32;
+ let r = (t * 220.0) as u8;
+ let g = ((1.0 - (t - 0.5).abs() * 2.0).max(0.0) * 180.0) as u8;
+ let b = ((1.0 - t) * 220.0) as u8;
+ Color32::from_rgb(r, g, b)
+}
+
+/// Overview banner palette — code (X) = green, data (RW) = cyan, RO = grey,
+/// unmapped = dark. Uses per-block RWX flags plus ASCII ratio to pick a hue.
+pub fn overview_color(prog: &Program, s: &Sample) -> Color32 {
+ let blk = prog
+ .blocks
+ .iter()
+ .find(|b| s.va >= b.va && s.va < b.va.saturating_add(b.size));
+ match blk {
+ Some(b) if b.executable => {
+ if s.ascii_ratio > 0.9 {
+ // Executable but almost all ASCII — likely misclassified data.
+ Color32::from_rgb(0x03, 0xA9, 0xF4)
+ } else {
+ Color32::from_rgb(0x4C, 0xAF, 0x50)
+ }
+ }
+ Some(b) if b.writable => Color32::from_rgb(0xFB, 0xC0, 0x2D),
+ Some(_) => Color32::from_rgb(0x9E, 0x9E, 0x9E),
+ None => Color32::from_gray(60),
+ }
+}
+
+/// Render the entropy strip. Returns the clicked VA (start of the sample) or None.
+pub fn render_entropy_strip(
+ ui: &mut Ui,
+ samples: &[Sample],
+ muted: Color32,
+ focused_va: Option<u64>,
+ primary: Color32,
+) -> Option<u64> {
+ if samples.is_empty() {
+ ui.label(
+ egui::RichText::new("No mapped memory — load a program to see entropy.").color(muted),
+ );
+ return None;
+ }
+ let avail = ui.available_width();
+ let strip_h = 24.0f32;
+ let (rect, resp) = ui.allocate_exact_size(Vec2::new(avail, strip_h), Sense::click());
+ let painter = ui.painter();
+ let per = (avail / samples.len() as f32).max(1.0);
+ for (i, s) in samples.iter().enumerate() {
+ let x = rect.min.x + i as f32 * per;
+ let r = Rect::from_min_size(
+ egui::pos2(x, rect.min.y),
+ Vec2::new(per, strip_h),
+ );
+ painter.rect_filled(r, 0.0, entropy_color(s.entropy));
+ }
+ // Focus cursor line.
+ if let Some(va) = focused_va {
+ if let Some((i, _)) = samples.iter().enumerate().find(|(_, s)| va >= s.va && va < s.end_va) {
+ let x = rect.min.x + (i as f32 + 0.5) * per;
+ painter.line_segment(
+ [egui::pos2(x, rect.min.y), egui::pos2(x, rect.max.y)],
+ Stroke::new(1.5, primary),
+ );
+ }
+ }
+ painter.rect(
+ rect,
+ 0.0,
+ Color32::TRANSPARENT,
+ Stroke::new(1.0, muted),
+ StrokeKind::Middle,
+ );
+
+ if let Some(pos) = resp.interact_pointer_pos() {
+ let idx = ((pos.x - rect.min.x) / per).floor() as usize;
+ return samples.get(idx).map(|s| s.va);
+ }
+ None
+}
+
+/// Render the Ghidra Overview banner (memory-block colour map).
+pub fn render_overview_strip(
+ ui: &mut Ui,
+ prog: &Program,
+ samples: &[Sample],
+ muted: Color32,
+ focused_va: Option<u64>,
+ primary: Color32,
+) -> Option<u64> {
+ if samples.is_empty() {
+ return None;
+ }
+ let avail = ui.available_width();
+ let strip_h = 16.0f32;
+ let (rect, resp) = ui.allocate_exact_size(Vec2::new(avail, strip_h), Sense::click());
+ let painter = ui.painter();
+ let per = (avail / samples.len() as f32).max(1.0);
+ for (i, s) in samples.iter().enumerate() {
+ let x = rect.min.x + i as f32 * per;
+ let r = Rect::from_min_size(
+ egui::pos2(x, rect.min.y),
+ Vec2::new(per, strip_h),
+ );
+ painter.rect_filled(r, 0.0, overview_color(prog, s));
+ }
+ if let Some(va) = focused_va {
+ if let Some((i, _)) = samples.iter().enumerate().find(|(_, s)| va >= s.va && va < s.end_va) {
+ let x = rect.min.x + (i as f32 + 0.5) * per;
+ painter.line_segment(
+ [egui::pos2(x, rect.min.y), egui::pos2(x, rect.max.y)],
+ Stroke::new(1.5, primary),
+ );
+ }
+ }
+ painter.rect(
+ rect,
+ 0.0,
+ Color32::TRANSPARENT,
+ Stroke::new(1.0, muted),
+ StrokeKind::Middle,
+ );
+ if let Some(pos) = resp.interact_pointer_pos() {
+ let idx = ((pos.x - rect.min.x) / per).floor() as usize;
+ return samples.get(idx).map(|s| s.va);
+ }
+ None
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use ghidrust_core::{fixture_path, load_path};
+
+ #[test]
+ fn entropy_samples_are_bounded_and_ordered() {
+ let prog = load_path(fixture_path("tiny_x64.pe")).unwrap();
+ let s = entropy_samples(&prog, 256);
+ assert!(!s.is_empty());
+ for w in s.windows(2) {
+ assert!(w[0].va <= w[1].va);
+ assert!(w[0].entropy >= 0.0 && w[0].entropy <= 8.0001);
+ assert!(w[0].ascii_ratio >= 0.0 && w[0].ascii_ratio <= 1.0);
+ }
+ }
+
+ #[test]
+ fn entropy_color_ramp_bounds() {
+ let lo = entropy_color(0.0);
+ let hi = entropy_color(8.0);
+ assert!(lo != hi);
+ }
+}
diff --git a/crates/ghidrust-gui/src/graphs.rs b/crates/ghidrust-gui/src/graphs.rs
new file mode 100644
index 0000000..defc3fa
--- /dev/null
+++ b/crates/ghidrust-gui/src/graphs.rs
@@ -0,0 +1,689 @@
+//! Ghidrust GUI · Phase E (M5) — Function Graph, Function Call Graph,
+//! Function Call Trees, and shared graph-layout helpers.
+//!
+//! These render Ghidra-analog dockable panes (`FunctionGraphPlugin`,
+//! `FunctionCallGraphPlugin`, `CallTreePlugin`) directly on top of Stage-0 CFG
+//! output from `ghidrust-decomp::decompile_at` and analyzer-recovered call
+//! references (`Program::analysis.references` + `ghidrust-core::xrefs`).
+//!
+//! **Honest-empty policy.** When a function has no recovered CFG or the
+//! program has no call references, panes render a clearly labelled empty
+//! state rather than fabricating structure.
+//!
+//! Extracted per `dev/MODULARIZATION_PLAN.md` — new UI panes land here
+//! instead of piling into `main.rs`.
+
+use eframe::egui::{self, Color32, Pos2, Rect, Sense, Stroke, StrokeKind, Ui, Vec2};
+use ghidrust_core::{xrefs_from, xrefs_to, Program, XRef};
+use ghidrust_decomp::{decompile_at, BasicBlock, CfgEdge};
+use std::collections::{BTreeMap, BTreeSet};
+
+/// Session-only state shared by Function Graph / Call Graph / Call Trees panes.
+///
+/// Kept small so `GhidrustApp` can own one and reset it on program change.
+#[derive(Debug, Clone, Default)]
+pub struct GraphPaneState {
+ /// Function Graph — user-selected layout algorithm.
+ pub fn_graph_layout: FunctionGraphLayout,
+ /// Function Graph — zoom (1.0 = fit to window).
+ pub fn_graph_zoom: f32,
+ /// Function Call Graph — expanded levels in / out (0 = source only).
+ pub call_graph_levels_in: usize,
+ pub call_graph_levels_out: usize,
+ /// Call Trees — expanded "incoming callers of X" set (function VAs).
+ /// Reserved for future stateful-tree work; expansion currently happens
+ /// on demand via `expand_tree_node`.
+ #[allow(dead_code)]
+ pub call_tree_expanded_in: BTreeSet<u64>,
+ #[allow(dead_code)]
+ pub call_tree_expanded_out: BTreeSet<u64>,
+ /// Call Trees — filter out thunks (Ghidra `Toggle Filter Thunks`).
+ pub call_tree_hide_thunks: bool,
+ /// Call Trees — "References Only" mode (data refs, no call edges).
+ pub call_tree_refs_only: bool,
+}
+
+/// Function Graph layout algorithm (Ghidra ships several; we implement two).
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
+pub enum FunctionGraphLayout {
+ /// Top-down hierarchical layered layout (Ghidra default).
+ #[default]
+ Hierarchical,
+ /// Simple grid — one row per block, in address order.
+ Grid,
+}
+
+impl FunctionGraphLayout {
+ pub const ALL: &'static [FunctionGraphLayout] = &[
+ FunctionGraphLayout::Hierarchical,
+ FunctionGraphLayout::Grid,
+ ];
+ pub const fn label(self) -> &'static str {
+ match self {
+ FunctionGraphLayout::Hierarchical => "Hierarchical",
+ FunctionGraphLayout::Grid => "Grid",
+ }
+ }
+}
+
+// ── Function Graph (Ghidra `FunctionGraphPlugin`) ────────────────────────────
+
+/// Positioned CFG block ready for egui rendering.
+#[derive(Debug, Clone)]
+pub struct BlockLayout {
+ pub id: usize,
+ pub label: String,
+ pub start_va: u64,
+ pub end_va: u64,
+ pub insn_count: usize,
+ pub is_return: bool,
+ pub is_branch: bool,
+ pub rect: Rect,
+}
+
+/// A directed edge between two positioned CFG blocks.
+#[derive(Debug, Clone)]
+pub struct EdgeLayout {
+ pub from: usize,
+ pub to: usize,
+ pub is_backedge: bool,
+ pub kind: String,
+}
+
+/// Layout the Stage-0 CFG for `entry` inside a target rectangle.
+///
+/// Returns positioned blocks + edges. If disassembly fails or the region has
+/// no blocks, returns empty vectors — callers render an honest empty state.
+pub fn layout_function_graph(
+ prog: &Program,
+ entry: u64,
+ max_insns: usize,
+ algo: FunctionGraphLayout,
+ view: Rect,
+) -> (Vec<BlockLayout>, Vec<EdgeLayout>) {
+ let Ok(res) = decompile_at(prog, entry, max_insns) else {
+ return (Vec::new(), Vec::new());
+ };
+ if res.blocks.is_empty() {
+ return (Vec::new(), Vec::new());
+ }
+
+ match algo {
+ FunctionGraphLayout::Hierarchical => layout_hierarchical(&res.blocks, &res.edges, view),
+ FunctionGraphLayout::Grid => layout_grid(&res.blocks, &res.edges, view),
+ }
+}
+
+fn block_label(b: &BasicBlock) -> String {
+ let head = b
+ .instructions
+ .first()
+ .map(|i| format!("{} {}", i.mnemonic, i.operands))
+ .unwrap_or_else(|| "(empty)".into());
+ let tail = b
+ .instructions
+ .last()
+ .filter(|_| b.instructions.len() > 1)
+ .map(|i| format!("\n{} {}", i.mnemonic, i.operands))
+ .unwrap_or_default();
+ format!("blk{} {:#x}\n{}{}", b.id, b.start, head, tail)
+}
+
+fn layout_hierarchical(
+ blocks: &[BasicBlock],
+ edges: &[CfgEdge],
+ view: Rect,
+) -> (Vec<BlockLayout>, Vec<EdgeLayout>) {
+ // Compute BFS-based depth per block starting at block 0 (entry).
+ let n = blocks.len();
+ let mut depth: Vec<usize> = vec![0; n];
+ let mut visited: Vec<bool> = vec![false; n];
+ let mut queue: std::collections::VecDeque<usize> = std::collections::VecDeque::new();
+ if n > 0 {
+ visited[0] = true;
+ queue.push_back(0);
+ }
+ while let Some(id) = queue.pop_front() {
+ for e in edges.iter().filter(|e| e.from == id) {
+ if !visited[e.to] {
+ visited[e.to] = true;
+ depth[e.to] = depth[id] + 1;
+ queue.push_back(e.to);
+ }
+ }
+ }
+ // Unvisited (unreachable) blocks pinned below with depth=max.
+ let max_depth = depth.iter().copied().max().unwrap_or(0);
+ for (i, d) in depth.iter_mut().enumerate() {
+ if !visited[i] {
+ *d = max_depth + 1;
+ }
+ }
+
+ // Group by depth for row layout.
+ let mut rows: BTreeMap<usize, Vec<usize>> = BTreeMap::new();
+ for (i, &d) in depth.iter().enumerate() {
+ rows.entry(d).or_default().push(i);
+ }
+
+ let block_w = 200.0f32;
+ let block_h = 60.0f32;
+ let hgap = 24.0f32;
+ let vgap = 40.0f32;
+
+ let mut positioned: Vec<BlockLayout> = Vec::with_capacity(n);
+ positioned.resize(
+ n,
+ BlockLayout {
+ id: 0,
+ label: String::new(),
+ start_va: 0,
+ end_va: 0,
+ insn_count: 0,
+ is_return: false,
+ is_branch: false,
+ rect: Rect::NOTHING,
+ },
+ );
+
+ let origin = view.min + Vec2::new(20.0, 20.0);
+ for (row_depth, row) in &rows {
+ let total_w = row.len() as f32 * block_w + (row.len().saturating_sub(1) as f32) * hgap;
+ let start_x = origin.x + ((view.width() - 40.0 - total_w) / 2.0).max(0.0);
+ let y = origin.y + (*row_depth as f32) * (block_h + vgap);
+ for (i_in_row, id) in row.iter().enumerate() {
+ let b = &blocks[*id];
+ let x = start_x + i_in_row as f32 * (block_w + hgap);
+ let rect = Rect::from_min_size(Pos2::new(x, y), Vec2::new(block_w, block_h));
+ positioned[*id] = BlockLayout {
+ id: b.id,
+ label: block_label(b),
+ start_va: b.start,
+ end_va: b.end,
+ insn_count: b.instructions.len(),
+ is_return: b.is_return,
+ is_branch: b.is_branch,
+ rect,
+ };
+ }
+ }
+
+ let out_edges: Vec<EdgeLayout> = edges
+ .iter()
+ .map(|e| EdgeLayout {
+ from: e.from,
+ to: e.to,
+ is_backedge: depth.get(e.to).copied().unwrap_or(0)
+ <= depth.get(e.from).copied().unwrap_or(0)
+ && e.from != e.to,
+ kind: e.kind.clone(),
+ })
+ .collect();
+
+ (positioned, out_edges)
+}
+
+fn layout_grid(
+ blocks: &[BasicBlock],
+ edges: &[CfgEdge],
+ view: Rect,
+) -> (Vec<BlockLayout>, Vec<EdgeLayout>) {
+ let block_w = 220.0f32;
+ let block_h = 56.0f32;
+ let vgap = 12.0f32;
+ let origin = view.min + Vec2::new(20.0, 20.0);
+ let positioned: Vec<BlockLayout> = blocks
+ .iter()
+ .enumerate()
+ .map(|(i, b)| {
+ let y = origin.y + (i as f32) * (block_h + vgap);
+ BlockLayout {
+ id: b.id,
+ label: block_label(b),
+ start_va: b.start,
+ end_va: b.end,
+ insn_count: b.instructions.len(),
+ is_return: b.is_return,
+ is_branch: b.is_branch,
+ rect: Rect::from_min_size(Pos2::new(origin.x, y), Vec2::new(block_w, block_h)),
+ }
+ })
+ .collect();
+ let out_edges: Vec<EdgeLayout> = edges
+ .iter()
+ .map(|e| EdgeLayout {
+ from: e.from,
+ to: e.to,
+ is_backedge: e.to <= e.from && e.from != e.to,
+ kind: e.kind.clone(),
+ })
+ .collect();
+ (positioned, out_edges)
+}
+
+/// Ghidra `FunctionGraphPlugin` — render blocks + edges. Returns clicked
+/// block start VA if any so the caller can Go To in Listing.
+///
+/// `focused_va` is drawn with a highlighted stroke so the current cursor
+/// position is visible on the graph.
+pub fn render_function_graph(
+ ui: &mut Ui,
+ blocks: &[BlockLayout],
+ edges: &[EdgeLayout],
+ focused_va: Option<u64>,
+ primary: Color32,
+ muted: Color32,
+) -> Option<u64> {
+ let painter = ui.painter();
+
+ // Draw edges first so blocks paint over the arrow heads.
+ for e in edges {
+ let (Some(a), Some(b)) = (blocks.get(e.from), blocks.get(e.to)) else {
+ continue;
+ };
+ let start = a.rect.center_bottom();
+ let end = b.rect.center_top();
+ let color = if e.is_backedge {
+ Color32::from_rgb(0xFB, 0xC0, 0x2D) // amber — backedge / loop
+ } else if e.kind == "cond" {
+ Color32::from_rgb(0x03, 0xA9, 0xF4) // cyan — conditional
+ } else {
+ muted
+ };
+ painter.line_segment([start, end], Stroke::new(1.2, color));
+ // Arrow head at target.
+ let dir = (end - start).normalized();
+ let normal = Vec2::new(-dir.y, dir.x);
+ let tip = end;
+ let base_a = end - dir * 8.0 + normal * 4.0;
+ let base_b = end - dir * 8.0 - normal * 4.0;
+ painter.add(egui::Shape::convex_polygon(
+ vec![tip, base_a, base_b],
+ color,
+ Stroke::NONE,
+ ));
+ }
+
+ let mut clicked: Option<u64> = None;
+ for b in blocks {
+ // Focus stroke for the block containing the current cursor VA.
+ let is_focused = focused_va
+ .map(|va| va >= b.start_va && va < b.end_va)
+ .unwrap_or(false);
+ let bg = if b.is_return {
+ Color32::from_rgb(0x2E, 0x1A, 0x1A)
+ } else if b.is_branch {
+ Color32::from_rgb(0x1A, 0x25, 0x2E)
+ } else {
+ Color32::from_rgb(0x1E, 0x1E, 0x24)
+ };
+ let stroke = if is_focused {
+ Stroke::new(2.0, primary)
+ } else {
+ Stroke::new(1.0, muted)
+ };
+ painter.rect(b.rect, 4.0, bg, stroke, StrokeKind::Middle);
+ painter.text(
+ b.rect.min + Vec2::new(6.0, 4.0),
+ egui::Align2::LEFT_TOP,
+ &b.label,
+ egui::FontId::monospace(11.0),
+ Color32::from_gray(220),
+ );
+ // Click detection via interaction rect on top of the painted block.
+ let resp = ui.interact(b.rect, egui::Id::new(("fg_block", b.id)), Sense::click());
+ if resp.clicked() {
+ clicked = Some(b.start_va);
+ }
+ resp.on_hover_text(format!(
+ "block {} [{:#x}..{:#x}] {} insns",
+ b.id, b.start_va, b.end_va, b.insn_count
+ ));
+ }
+
+ clicked
+}
+
+// ── Function Call Graph (Ghidra `FunctionCallGraphPlugin`) ──────────────────
+
+/// Level-based call graph vertex.
+#[derive(Debug, Clone)]
+pub struct CallVertex {
+ pub va: u64,
+ pub name: String,
+ pub level: i32, // <0 = incoming, 0 = source, >0 = outgoing
+ pub rect: Rect,
+}
+
+/// Level-based call graph edge (from caller → callee).
+#[derive(Debug, Clone)]
+pub struct CallEdge {
+ pub from: u64,
+ pub to: u64,
+}
+
+/// Compute callers of `entry` from analyzer-recovered references + xrefs.
+///
+/// A "caller" is a function whose body contains a `call` or `jmp` targeting
+/// `entry`. Honest-empty when there is no evidence.
+pub fn callers_of(prog: &Program, entry: u64) -> Vec<u64> {
+ let mut out: BTreeSet<u64> = BTreeSet::new();
+ for r in xrefs_to(prog, entry, None) {
+ if matches!(r.kind, "call" | "jmp" | "cond_jmp") {
+ if let Some(f) = prog
+ .analysis
+ .functions
+ .iter()
+ .find(|f| r.from >= f.entry && r.from < f.end)
+ {
+ out.insert(f.entry);
+ }
+ }
+ }
+ out.into_iter().collect()
+}
+
+/// Compute callees of `entry` by scanning the function's own body.
+pub fn callees_of(prog: &Program, entry: u64) -> Vec<u64> {
+ let end = prog
+ .analysis
+ .functions
+ .iter()
+ .find(|f| f.entry == entry)
+ .map(|f| f.end)
+ .unwrap_or(entry.saturating_add(0x400));
+ let approx_insns = (end.saturating_sub(entry) as usize / 3).max(64);
+ let mut out: BTreeSet<u64> = BTreeSet::new();
+ for xr in xrefs_from(prog, entry, approx_insns.min(2048)) {
+ if !matches!(xr.kind, "call" | "jmp") {
+ continue;
+ }
+ // Snap to the enclosing function's entry when possible.
+ if let Some(f) = prog
+ .analysis
+ .functions
+ .iter()
+ .find(|f| xr.to == f.entry)
+ {
+ out.insert(f.entry);
+ } else if prog
+ .analysis
+ .functions
+ .iter()
+ .any(|f| xr.to >= f.entry && xr.to < f.end)
+ {
+ out.insert(xr.to);
+ }
+ }
+ out.into_iter().collect()
+}
+
+fn function_name(prog: &Program, va: u64) -> String {
+ prog.display_function_name_at(va)
+ .unwrap_or_else(|| format!("FUN_{va:016x}"))
+}
+
+/// Build a level-based call graph rooted at `entry`, expanding at most
+/// `levels_in` incoming and `levels_out` outgoing levels.
+pub fn layout_call_graph(
+ prog: &Program,
+ entry: u64,
+ levels_in: usize,
+ levels_out: usize,
+ view: Rect,
+) -> (Vec<CallVertex>, Vec<CallEdge>) {
+ let mut per_level: BTreeMap<i32, Vec<u64>> = BTreeMap::new();
+ let mut edges: BTreeSet<(u64, u64)> = BTreeSet::new();
+ let mut seen: BTreeSet<u64> = BTreeSet::new();
+
+ per_level.entry(0).or_default().push(entry);
+ seen.insert(entry);
+
+ // Outgoing expansion.
+ let mut frontier = vec![entry];
+ for lvl in 1..=(levels_out as i32) {
+ let mut next: Vec<u64> = Vec::new();
+ for src in &frontier {
+ for callee in callees_of(prog, *src) {
+ edges.insert((*src, callee));
+ if seen.insert(callee) {
+ next.push(callee);
+ }
+ }
+ }
+ if next.is_empty() {
+ break;
+ }
+ per_level.entry(lvl).or_default().extend(next.iter().copied());
+ frontier = next;
+ }
+
+ // Incoming expansion.
+ let mut frontier = vec![entry];
+ for lvl in 1..=(levels_in as i32) {
+ let mut next: Vec<u64> = Vec::new();
+ for tgt in &frontier {
+ for caller in callers_of(prog, *tgt) {
+ edges.insert((caller, *tgt));
+ if seen.insert(caller) {
+ next.push(caller);
+ }
+ }
+ }
+ if next.is_empty() {
+ break;
+ }
+ per_level
+ .entry(-lvl)
+ .or_default()
+ .extend(next.iter().copied());
+ frontier = next;
+ }
+
+ let vw = 180.0f32;
+ let vh = 42.0f32;
+ let hgap = 20.0f32;
+ let vgap = 40.0f32;
+ let origin = view.min + Vec2::new(20.0, 20.0);
+
+ let min_lvl = per_level.keys().copied().min().unwrap_or(0);
+
+ let mut verts: Vec<CallVertex> = Vec::new();
+ for (lvl, list) in &per_level {
+ let row_y = origin.y + ((*lvl - min_lvl) as f32) * (vh + vgap);
+ let total_w = list.len() as f32 * vw + (list.len().saturating_sub(1) as f32) * hgap;
+ let row_x = origin.x + ((view.width() - 40.0 - total_w) / 2.0).max(0.0);
+ for (i, va) in list.iter().enumerate() {
+ let x = row_x + i as f32 * (vw + hgap);
+ let rect = Rect::from_min_size(Pos2::new(x, row_y), Vec2::new(vw, vh));
+ verts.push(CallVertex {
+ va: *va,
+ name: function_name(prog, *va),
+ level: *lvl,
+ rect,
+ });
+ }
+ }
+
+ let out_edges: Vec<CallEdge> = edges
+ .into_iter()
+ .map(|(f, t)| CallEdge { from: f, to: t })
+ .collect();
+ (verts, out_edges)
+}
+
+/// Render the level-based call graph. Returns the VA of any clicked vertex.
+pub fn render_call_graph(
+ ui: &mut Ui,
+ verts: &[CallVertex],
+ edges: &[CallEdge],
+ source: u64,
+ primary: Color32,
+ muted: Color32,
+) -> Option<u64> {
+ let painter = ui.painter();
+ let vmap: BTreeMap<u64, &CallVertex> = verts.iter().map(|v| (v.va, v)).collect();
+
+ for e in edges {
+ let (Some(a), Some(b)) = (vmap.get(&e.from), vmap.get(&e.to)) else {
+ continue;
+ };
+ painter.line_segment(
+ [a.rect.center_bottom(), b.rect.center_top()],
+ Stroke::new(1.0, muted),
+ );
+ }
+
+ let mut clicked: Option<u64> = None;
+ for v in verts {
+ let bg = if v.va == source {
+ Color32::from_rgb(0x25, 0x1F, 0x10)
+ } else if v.level < 0 {
+ Color32::from_rgb(0x1A, 0x25, 0x2E)
+ } else {
+ Color32::from_rgb(0x1E, 0x24, 0x1E)
+ };
+ let stroke = if v.va == source {
+ Stroke::new(2.0, primary)
+ } else {
+ Stroke::new(1.0, muted)
+ };
+ painter.rect(v.rect, 4.0, bg, stroke, StrokeKind::Middle);
+ painter.text(
+ v.rect.min + Vec2::new(6.0, 4.0),
+ egui::Align2::LEFT_TOP,
+ format!("{}\n{:#x}", v.name, v.va),
+ egui::FontId::monospace(11.0),
+ Color32::from_gray(220),
+ );
+ let resp = ui.interact(v.rect, egui::Id::new(("cg_vert", v.va)), Sense::click());
+ if resp.clicked() {
+ clicked = Some(v.va);
+ }
+ resp.on_hover_text(format!("Level {} {:#x} {}", v.level, v.va, v.name));
+ }
+ clicked
+}
+
+// ── Function Call Trees (Ghidra `CallTreePlugin`) ───────────────────────────
+
+/// One node of the incoming / outgoing call tree.
+#[derive(Debug, Clone)]
+pub struct CallTreeNode {
+ pub va: u64,
+ pub name: String,
+ pub is_thunk: bool,
+ /// Populated on demand when the user expands the row.
+ pub children_loaded: bool,
+ pub children: Vec<CallTreeNode>,
+}
+
+impl CallTreeNode {
+ fn leaf(prog: &Program, va: u64) -> Self {
+ Self {
+ va,
+ name: function_name(prog, va),
+ is_thunk: prog
+ .analysis
+ .functions
+ .iter()
+ .find(|f| f.entry == va)
+ .map(|f| f.end.saturating_sub(f.entry) <= 8)
+ .unwrap_or(false),
+ children_loaded: false,
+ children: Vec::new(),
+ }
+ }
+}
+
+/// Build the top level of the incoming (callers-of) tree for `entry`.
+pub fn build_incoming_tree(prog: &Program, entry: u64) -> Vec<CallTreeNode> {
+ callers_of(prog, entry)
+ .into_iter()
+ .map(|va| CallTreeNode::leaf(prog, va))
+ .collect()
+}
+
+/// Build the top level of the outgoing (callees-of) tree for `entry`.
+pub fn build_outgoing_tree(prog: &Program, entry: u64) -> Vec<CallTreeNode> {
+ callees_of(prog, entry)
+ .into_iter()
+ .map(|va| CallTreeNode::leaf(prog, va))
+ .collect()
+}
+
+/// Expand a call-tree row by fetching its callers / callees, mutating in place.
+///
+/// `direction` == "incoming" fetches callers; "outgoing" fetches callees.
+pub fn expand_tree_node(
+ node: &mut CallTreeNode,
+ prog: &Program,
+ direction: &str,
+ hide_thunks: bool,
+) {
+ if node.children_loaded {
+ return;
+ }
+ let kids = match direction {
+ "incoming" => callers_of(prog, node.va),
+ _ => callees_of(prog, node.va),
+ };
+ node.children = kids
+ .into_iter()
+ .map(|va| CallTreeNode::leaf(prog, va))
+ .filter(|c| !(hide_thunks && c.is_thunk))
+ .collect();
+ node.children_loaded = true;
+}
+
+// ── Data-ref helpers exposed for the Call Trees "References Only" mode. ─────
+
+/// Data-only xrefs at `entry` (kind = "data"/"ptr_table"/"resource"/"xref").
+pub fn data_xrefs_to(prog: &Program, entry: u64) -> Vec<XRef> {
+ xrefs_to(prog, entry, None)
+ .into_iter()
+ .filter(|r| !matches!(r.kind, "call" | "jmp" | "cond_jmp"))
+ .collect()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use ghidrust_core::{fixture_path, load_path};
+
+ #[test]
+ fn call_graph_source_only_when_no_calls() {
+ let prog = load_path(fixture_path("tiny_x64.pe")).unwrap();
+ let entry = prog.entry.unwrap();
+ let view = Rect::from_min_size(Pos2::ZERO, Vec2::new(800.0, 400.0));
+ let (verts, _edges) = layout_call_graph(&prog, entry, 0, 0, view);
+ assert_eq!(verts.len(), 1);
+ assert_eq!(verts[0].va, entry);
+ assert_eq!(verts[0].level, 0);
+ }
+
+ #[test]
+ fn function_graph_produces_blocks_or_empty_honestly() {
+ let prog = load_path(fixture_path("tiny_x64.pe")).unwrap();
+ let entry = prog.entry.unwrap();
+ let view = Rect::from_min_size(Pos2::ZERO, Vec2::new(1000.0, 600.0));
+ let (blocks, _edges) =
+ layout_function_graph(&prog, entry, 128, FunctionGraphLayout::Hierarchical, view);
+ // Every block must have a non-degenerate rect and a start VA at/after entry.
+ for b in &blocks {
+ assert!(b.rect.width() > 0.0);
+ assert!(b.start_va >= entry);
+ }
+ }
+
+ #[test]
+ fn call_trees_incoming_outgoing_empty_or_populated_honestly() {
+ let prog = load_path(fixture_path("tiny_x64.pe")).unwrap();
+ let entry = prog.entry.unwrap();
+ let inc = build_incoming_tree(&prog, entry);
+ let out = build_outgoing_tree(&prog, entry);
+ for n in inc.iter().chain(out.iter()) {
+ assert!(!n.name.is_empty());
+ }
+ }
+}
diff --git a/crates/ghidrust-gui/src/layouts.rs b/crates/ghidrust-gui/src/layouts.rs
new file mode 100644
index 0000000..57bf6e0
--- /dev/null
+++ b/crates/ghidrust-gui/src/layouts.rs
@@ -0,0 +1,342 @@
+//! Ghidrust GUI · Phase H (M8) — layout persistence + Configure dialog.
+//!
+//! Ghidra's `docking` framework lets users move / tab / float providers
+//! and save the result as a `.tool` XML preset. Ghidrust ships with
+//! floating `egui::Window` panes today (full `egui_dock` docking is a
+//! separate Phase H+ landing); this module gives users maximum-visible
+//! parity by:
+//!
+//! - persisting per-pane visibility + tool preferences to
+//! `%APPDATA%/ghidrust/layouts/<name>.tool.json`
+//! - listing every plugin (all compile-time in Ghidrust) in a Configure
+//! dialog so users can see the parity surface
+//!
+//! Full drag-tabbed-floating docking arrives with `egui_dock` — the plan
+//! documents that as the residual deferral for M8.
+//!
+//! Extracted per `dev/MODULARIZATION_PLAN.md` — new UI panes land here
+//! instead of piling into `main.rs`.
+
+use serde::{Deserialize, Serialize};
+use std::collections::BTreeMap;
+use std::path::PathBuf;
+
+/// One saved tool layout: which providers are open, plus tool-level toggles.
+///
+/// `open_panes` uses pane ids (short strings) so old snapshots decode after
+/// panes are renamed (unknown ids are ignored on load).
+#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
+pub struct SavedLayout {
+ pub name: String,
+ /// Pane-id → open bit.
+ pub open_panes: BTreeMap<String, bool>,
+ /// Dock checkbox states (`project_tree`, `program_tree`, `symbol_tree`, `console`).
+ pub docks: BTreeMap<String, bool>,
+ /// Center tab (`overview` / `listing` / `decompiler` / `datatypes`).
+ pub center: String,
+ /// Theme (`dark` / `light`).
+ pub theme: String,
+ /// Free-form comment shown in Configure dialog.
+ pub comment: String,
+}
+
+/// Directory holding user-saved `<name>.tool.json` files.
+pub fn layouts_dir() -> PathBuf {
+ if let Ok(appdata) = std::env::var("APPDATA") {
+ PathBuf::from(appdata).join("ghidrust").join("layouts")
+ } else if let Ok(home) = std::env::var("USERPROFILE") {
+ PathBuf::from(home).join(".ghidrust").join("layouts")
+ } else if let Ok(home) = std::env::var("HOME") {
+ PathBuf::from(home).join(".ghidrust").join("layouts")
+ } else {
+ PathBuf::from(".ghidrust_layouts")
+ }
+}
+
+/// Save a layout to `<layouts_dir>/<name>.tool.json`.
+pub fn save_layout(layout: &SavedLayout) -> std::io::Result<PathBuf> {
+ let dir = layouts_dir();
+ std::fs::create_dir_all(&dir)?;
+ let path = dir.join(format!("{}.tool.json", sanitize(&layout.name)));
+ let text = serde_json::to_string_pretty(layout).map_err(|e| {
+ std::io::Error::new(std::io::ErrorKind::InvalidData, format!("serde: {e}"))
+ })?;
+ std::fs::write(&path, text)?;
+ Ok(path)
+}
+
+/// Load a layout preset by short name.
+pub fn load_layout(name: &str) -> std::io::Result<SavedLayout> {
+ let path = layouts_dir().join(format!("{}.tool.json", sanitize(name)));
+ let text = std::fs::read_to_string(&path)?;
+ serde_json::from_str(&text).map_err(|e| {
+ std::io::Error::new(std::io::ErrorKind::InvalidData, format!("serde: {e}"))
+ })
+}
+
+/// Enumerate every saved layout on disk.
+pub fn list_layouts() -> Vec<String> {
+ let dir = layouts_dir();
+ let Ok(rd) = std::fs::read_dir(&dir) else {
+ return Vec::new();
+ };
+ let mut out = Vec::new();
+ for entry in rd.flatten() {
+ let p = entry.path();
+ if let Some(name) = p.file_name().and_then(|s| s.to_str()) {
+ if let Some(rest) = name.strip_suffix(".tool.json") {
+ out.push(rest.to_string());
+ }
+ }
+ }
+ out.sort();
+ out
+}
+
+/// Delete a saved layout by name.
+pub fn delete_layout(name: &str) -> std::io::Result<()> {
+ let path = layouts_dir().join(format!("{}.tool.json", sanitize(name)));
+ std::fs::remove_file(path)
+}
+
+fn sanitize(name: &str) -> String {
+ name.chars()
+ .map(|c| {
+ if c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.') {
+ c
+ } else {
+ '_'
+ }
+ })
+ .collect()
+}
+
+/// Plugin catalog surfaced by the Configure dialog. Ghidra ships a full
+/// plugin picker — Ghidrust plugins are compile-time so this is a
+/// read-only list.
+#[derive(Debug, Clone, Copy)]
+pub struct PluginRow {
+ pub name: &'static str,
+ pub kind: &'static str,
+ pub state: &'static str,
+ pub description: &'static str,
+}
+
+/// Every plugin analog Ghidrust ships today.
+pub const PLUGIN_CATALOG: &[PluginRow] = &[
+ PluginRow {
+ name: "CodeBrowserPlugin",
+ kind: "Core",
+ state: "Included",
+ description: "Listing + Decompiler center panes (Ghidra CodeBrowser).",
+ },
+ PluginRow {
+ name: "DecompilePlugin",
+ kind: "Core",
+ state: "Included",
+ description: "Stage-0 / Stage-0.5 / Stage-1 pseudo-C emission.",
+ },
+ PluginRow {
+ name: "SymbolTreePlugin",
+ kind: "Base",
+ state: "Included",
+ description: "Imports / Exports / Functions / Labels / Classes / Namespaces tree.",
+ },
+ PluginRow {
+ name: "ProgramTreePlugin",
+ kind: "Base",
+ state: "Included",
+ description: "Modules / fragments (Ghidra program tree) view filter.",
+ },
+ PluginRow {
+ name: "DataTypeManagerPlugin",
+ kind: "Base",
+ state: "Included",
+ description: "Built-In + Program archives, editors, Data Type Chooser.",
+ },
+ PluginRow {
+ name: "FunctionGraphPlugin",
+ kind: "FunctionGraph",
+ state: "Included",
+ description: "CFG vertex / edge layout on top of Stage-0 blocks.",
+ },
+ PluginRow {
+ name: "FunctionCallGraphPlugin",
+ kind: "GraphFunctionCalls",
+ state: "Included",
+ description: "Level-based directed call graph in / out of source function.",
+ },
+ PluginRow {
+ name: "CallTreePlugin",
+ kind: "Base",
+ state: "Included",
+ description: "Incoming callers / outgoing callees + refs GTree pair.",
+ },
+ PluginRow {
+ name: "MemoryMapPlugin",
+ kind: "Base",
+ state: "Included",
+ description: "Editable Add / Delete / Toggle RWX memory-block table.",
+ },
+ PluginRow {
+ name: "RegisterPlugin",
+ kind: "Base",
+ state: "Included",
+ description: "SLEIGH-analog register lattice + session values.",
+ },
+ PluginRow {
+ name: "OverviewPlugin",
+ kind: "Base",
+ state: "Included",
+ description: "Memory-block colour banner (X / W / R / unmapped).",
+ },
+ PluginRow {
+ name: "EntropyPlugin",
+ kind: "Base",
+ state: "Included",
+ description: "Shannon-entropy strip across mapped blocks.",
+ },
+ PluginRow {
+ name: "BookmarkPlugin",
+ kind: "Base",
+ state: "Included",
+ description: "5 Ghidra bookmark kinds; margin markers.",
+ },
+ PluginRow {
+ name: "CommentWindowPlugin",
+ kind: "Base",
+ state: "Included",
+ description: "Filter by kind + text; jump to source VA.",
+ },
+ PluginRow {
+ name: "ByteViewerPlugin",
+ kind: "Base",
+ state: "Included",
+ description: "Hex + ASCII split view over Program bytes.",
+ },
+ PluginRow {
+ name: "GhidraScriptMgrPlugin",
+ kind: "Scripting",
+ state: "Included",
+ description: "Ghidrust MCP tool catalog (from skill/SKILL.md).",
+ },
+ PluginRow {
+ name: "TextEditorManagerPlugin",
+ kind: "Scripting",
+ state: "Included",
+ description: "Multi-tab in-memory editor for local script files.",
+ },
+ PluginRow {
+ name: "InterpreterPanelPlugin",
+ kind: "Scripting",
+ state: "Included · REPL stub",
+ description: "MCP REPL — wires into `ghidrust mcp` stdio host in P17.",
+ },
+ PluginRow {
+ name: "DebuggerTargetsPlugin",
+ kind: "Debugger",
+ state: "Included · empty",
+ description: "Target agent list — backend pending P12.",
+ },
+ PluginRow {
+ name: "DebuggerThreadsPlugin",
+ kind: "Debugger",
+ state: "Included · empty",
+ description: "Live threads — backend pending P12.",
+ },
+ PluginRow {
+ name: "DebuggerModulesPlugin",
+ kind: "Debugger",
+ state: "Included · empty",
+ description: "Loaded modules — backend pending P12.",
+ },
+ PluginRow {
+ name: "DebuggerRegionsPlugin",
+ kind: "Debugger",
+ state: "Included · empty",
+ description: "Live memory regions — backend pending P12.",
+ },
+ PluginRow {
+ name: "DebuggerRegistersPlugin",
+ kind: "Debugger",
+ state: "Included · empty",
+ description: "Live register values — backend pending P12.",
+ },
+ PluginRow {
+ name: "DebuggerStackPlugin",
+ kind: "Debugger",
+ state: "Included · empty",
+ description: "Live stack frames — backend pending P12.",
+ },
+ PluginRow {
+ name: "DebuggerBreakpointsPlugin",
+ kind: "Debugger",
+ state: "Included · empty",
+ description: "Session-only breakpoint list; agent-set pending P12.",
+ },
+ PluginRow {
+ name: "DebuggerMemoryBytesPlugin",
+ kind: "Debugger",
+ state: "Included · empty",
+ description: "Live memory dumps — backend pending P12.",
+ },
+ PluginRow {
+ name: "DebuggerWatchesPlugin",
+ kind: "Debugger",
+ state: "Included · empty",
+ description: "Session-only watch list; evaluator pending P12.",
+ },
+ PluginRow {
+ name: "DebuggerConsolePlugin",
+ kind: "Debugger",
+ state: "Included · empty",
+ description: "Target-agent stdio — backend pending P12.",
+ },
+];
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn round_trip_layout_json() {
+ let l = SavedLayout {
+ name: "test".into(),
+ open_panes: [("pane_bookmarks".to_string(), true)].into_iter().collect(),
+ docks: [("console".to_string(), true)].into_iter().collect(),
+ center: "listing".into(),
+ theme: "dark".into(),
+ comment: String::new(),
+ };
+ let text = serde_json::to_string(&l).unwrap();
+ let back: SavedLayout = serde_json::from_str(&text).unwrap();
+ assert_eq!(back, l);
+ }
+
+ #[test]
+ fn sanitize_strips_path_seps() {
+ assert_eq!(sanitize("a/b\\c*d"), "a_b_c_d");
+ assert_eq!(sanitize("hello-world.1"), "hello-world.1");
+ }
+
+ #[test]
+ fn plugin_catalog_covers_new_phase_e_f_g_h_providers() {
+ let names: Vec<&'static str> = PLUGIN_CATALOG.iter().map(|p| p.name).collect();
+ for expected in [
+ "FunctionGraphPlugin",
+ "FunctionCallGraphPlugin",
+ "CallTreePlugin",
+ "MemoryMapPlugin",
+ "RegisterPlugin",
+ "OverviewPlugin",
+ "EntropyPlugin",
+ "GhidraScriptMgrPlugin",
+ "TextEditorManagerPlugin",
+ "InterpreterPanelPlugin",
+ "DebuggerTargetsPlugin",
+ "DebuggerBreakpointsPlugin",
+ ] {
+ assert!(names.contains(&expected), "missing plugin {expected}");
+ }
+ }
+}
diff --git a/crates/ghidrust-gui/src/main.rs b/crates/ghidrust-gui/src/main.rs
index 31cd469..c64c3c0 100644
--- a/crates/ghidrust-gui/src/main.rs
+++ b/crates/ghidrust-gui/src/main.rs
@@ -1,34 +1,53 @@
//! Ghidrust CodeBrowser shell — Material 3 Dark/Light, Ghidra-like menus/panes.
//! Icons: Google Material 3 geometry (see `icons.rs`); no emoji in the UI.
+mod debugger;
mod decomp_tokens;
+mod entropy;
mod events;
+mod graphs;
mod icons;
+mod layouts;
mod menu_actions;
mod nav;
mod panes;
+mod register_manager;
+mod scripts;
use eframe::egui::{self, Color32, Visuals};
use ghidrust_core::{
analyzer_catalog, analyzer_supports_gpu, disassemble_range, load_path, m3_tokens,
- set_preferred_bulk_mode, AnalysisRunReport, AnalyzerInfo, BulkScanMode, CommentKind,
- FoundString, Instruction, Program, Project, ProjectTreeModel, RttiReport, ThemeMode,
- BUILTIN_TYPES,
+ set_preferred_bulk_mode, xrefs_from, xrefs_to, AnalysisRunReport, AnalyzerInfo, AnalyzerOutput,
+ BulkScanMode, CommentKind, FoundString, Instruction, Program, Project, ProjectTreeModel,
+ RttiReport, ThemeMode, XRef, BUILTIN_TYPES,
};
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, pseudo_c_for_stage, search_memory, search_program_text, stage0_pseudo_c,
- DecompStage, ListingSelection, MemoryHit, TextHit, STAGE0_MAX_INSNS,
+ address_table_hits, decompile_entry_for_va, listing_index_at_or_before, parse_address,
+ parse_hex_pattern, processor_info, pseudo_c_for_stage, search_instruction_patterns,
+ search_memory, search_program_text, search_scalars, stage0_pseudo_c, DecompStage,
+ ListingSelection, MemoryHit, TextHit, STAGE0_MAX_INSNS,
};
use decomp_tokens::{
line_for_va as decomp_line_for_va, tokenize as tokenize_decomp, DecompLine, TokenKind,
};
+use debugger::{DebuggerAction, DebuggerPane, DebuggerState};
use events::{EventBus, EventSource, GhidrustEvent, MutationKind};
+use graphs::{
+ build_incoming_tree, build_outgoing_tree, data_xrefs_to, expand_tree_node, layout_call_graph,
+ layout_function_graph, render_call_graph, render_function_graph, CallTreeNode,
+ FunctionGraphLayout, GraphPaneState,
+};
use nav::{NavHistory, NavLocation};
use panes::{Bookmark, BookmarkKind, PaneKind};
+use register_manager::RegisterManagerState;
+use scripts::{
+ render_mcp_repl, render_script_manager, render_text_editor, MacropadReplState,
+ ScriptManagerState, TextEditorRequest, TextEditorState,
+};
use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};
+use std::sync::mpsc::{self, Receiver, RecvError, TryRecvError};
fn recent_projects_path() -> PathBuf {
// %APPDATA%/ghidrust/recent_projects.txt (or home fallback)
@@ -63,13 +82,29 @@ fn save_recent_projects(paths: &[String]) {
let _ = std::fs::write(p, paths.join("\n"));
}
-/// In-progress stepped analysis (one analyzer per frame for live M3 progress).
+/// Messages from the background analysis worker → UI thread (polled each frame).
+enum AnalysisWorkerMsg {
+ /// Analyzer at `index` is about to run.
+ StepStarted { index: usize },
+ /// Analyzer at `index` finished; `outputs` are that step's report rows.
+ StepFinished {
+ index: usize,
+ outputs: Vec<AnalyzerOutput>,
+ },
+ /// All selected analyzers finished; return mutated program to the UI.
+ Done { program: Program },
+ /// Hard failure; program is returned so the UI can restore it (may include partial work).
+ Failed { error: String, program: Program },
+}
+
+/// In-progress analysis. Heavy work runs on a background thread; the UI only polls `rx`.
struct AnalysisJob {
names: Vec<String>,
index: usize,
results: AnalysisRunReport,
file_label: String,
use_gpu: bool,
+ rx: Receiver<AnalysisWorkerMsg>,
}
fn main() -> eframe::Result<()> {
@@ -244,6 +279,93 @@ pub struct GhidrustApp {
comment_window_kind_filter: Option<CommentKind>,
/// Phase B (M2) — Console severity per line (`Info`, `Warn`, `Error`).
console_severity: Vec<ConsoleSeverity>,
+ // ── Phase D (M4) — tables & search state ────────────────────────────
+ /// Byte Viewer state (Ghidra `ByteViewerPlugin`).
+ bytes_pane_va: Option<u64>,
+ bytes_pane_bpr: usize,
+ bytes_pane_rows: usize,
+ /// Filter for Symbol References pane (name / address substring).
+ symbol_refs_filter: String,
+ /// Symbol References focus (target VA) — set from Symbol Table row.
+ symbol_refs_target: Option<u64>,
+ /// Equates Table filters + edit dialog.
+ equates_filter: String,
+ equates_selected: Option<(String, i64)>,
+ show_equate_dialog: bool,
+ equate_dialog_va: Option<u64>,
+ equate_dialog_op: u8,
+ equate_dialog_name: String,
+ equate_dialog_value: String,
+ /// Function Tags — new-tag input + selected tag for row highlight.
+ function_tags_new_input: String,
+ /// External Programs filter.
+ external_programs_filter: String,
+ /// Data Type Preview — selected built-in for preview.
+ data_type_preview_selected: String,
+ /// Checksum Generator — cached results.
+ checksum_last: Option<ChecksumReport>,
+ /// Search → For Scalars.
+ show_search_scalars_dialog: bool,
+ search_scalars_min: String,
+ search_scalars_max: String,
+ /// Search → Instruction Patterns.
+ show_search_insn_dialog: bool,
+ search_insn_mnemonic: String,
+ search_insn_operands: String,
+ /// Search → For Address Tables (populated on-demand).
+ show_search_address_tables_dialog: bool,
+ /// Function Tags pane filter.
+ function_tags_filter: String,
+ // ── Phase E (M5) — Graphs & maps ────────────────────────────────────
+ /// Function Graph / Call Graph / Call Trees session state.
+ graph_state: GraphPaneState,
+ /// Function Call Trees — top-level nodes (rebuilt on cursor change).
+ call_tree_incoming: Vec<CallTreeNode>,
+ call_tree_outgoing: Vec<CallTreeNode>,
+ /// Register Manager pane state (session-only until backend lattice lands).
+ register_manager: RegisterManagerState,
+ /// Memory Map editor — pending row edits (Add row).
+ memory_map_new_name: String,
+ memory_map_new_va: String,
+ memory_map_new_size: String,
+ memory_map_new_r: bool,
+ memory_map_new_w: bool,
+ memory_map_new_x: bool,
+ // ── Phase F (M6) — Scripts ──────────────────────────────────────────
+ /// Script Manager pane state.
+ script_manager: ScriptManagerState,
+ /// Text Editor multi-tab state.
+ text_editor: TextEditorState,
+ /// MCP REPL state.
+ mcp_repl: MacropadReplState,
+ // ── Phase G (M7) — Debugger visibility ──────────────────────────────
+ /// Debugger tool state (breakpoints, watches, session-only until backend).
+ debugger: DebuggerState,
+ /// Which debugger panes are open (Ghidra `Debugger` tool Window menu).
+ debugger_open: BTreeMap<DebuggerPane, bool>,
+ // ── Phase H (M8) — Docking / layouts / Configure ───────────────────
+ /// Configure dialog (Ghidra `File → Configure` plugin picker).
+ show_configure_dialog: bool,
+ /// Layout preset save/load dialog state.
+ show_layouts_dialog: bool,
+ layouts_new_name: String,
+ layouts_cached: Vec<String>,
+ /// Current layout name (empty = unnamed / default).
+ current_layout_name: String,
+}
+
+/// Phase D (M4) — Checksum Generator report (Ghidra `ComputeChecksumsPlugin`).
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct ChecksumReport {
+ pub target: String,
+ pub len: usize,
+ pub crc32: u32,
+ pub sum8: u32,
+ pub sum16: u32,
+ pub sum32: u64,
+ pub adler32: u32,
+ pub fletcher16: u32,
+ pub fletcher32: u64,
}
/// Phase B (M2) — severity tint for `Console` pane rows.
@@ -254,6 +376,57 @@ enum ConsoleSeverity {
Error,
}
+/// Phase D (M4) — Checksum Generator scope (Ghidra `ComputeChecksumsPlugin`).
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum ChecksumMode {
+ /// Concatenation of every loaded memory block.
+ WholeImage,
+ /// A single memory block chosen by name.
+ Section(String),
+}
+
+/// CRC-32/ISO-HDLC (polynomial `0xEDB88320`) — matches Ghidra's default.
+fn crc32_ieee(data: &[u8]) -> u32 {
+ let mut c: u32 = 0xFFFF_FFFF;
+ for &b in data {
+ c ^= b as u32;
+ for _ in 0..8 {
+ let mask = (c & 1).wrapping_neg();
+ c = (c >> 1) ^ (0xEDB8_8320 & mask);
+ }
+ }
+ !c
+}
+
+fn adler32(data: &[u8]) -> u32 {
+ const MOD: u32 = 65521;
+ let mut a: u32 = 1;
+ let mut b: u32 = 0;
+ for &byte in data {
+ a = (a + byte as u32) % MOD;
+ b = (b + a) % MOD;
+ }
+ (b << 16) | a
+}
+
+fn fletcher_pair(data: &[u8]) -> (u32, u64) {
+ let (mut a16, mut b16): (u16, u16) = (0, 0);
+ for &byte in data {
+ a16 = a16.wrapping_add(byte as u16);
+ b16 = b16.wrapping_add(a16);
+ }
+ let f16 = ((b16 as u32) << 16) | a16 as u32;
+
+ let (mut a32, mut b32): (u32, u32) = (0, 0);
+ for chunk in data.chunks_exact(2) {
+ let w = u16::from_le_bytes([chunk[0], chunk[1]]) as u32;
+ a32 = a32.wrapping_add(w);
+ b32 = b32.wrapping_add(a32);
+ }
+ let f32 = ((b32 as u64) << 32) | a32 as u64;
+ (f16, f32)
+}
+
/// Phase C (M3) — Data Type Manager `New` submenu kinds.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum NewTypeKind {
@@ -407,6 +580,47 @@ impl NewTypeKind {
}
}
+/// Recursively render one Ghidra-style Call Tree row.
+///
+/// The node's `children_loaded` flag is flipped on first expand so callers
+/// pay the xref cost only when the user opens a branch.
+fn render_call_tree_node(
+ node: &mut CallTreeNode,
+ idx: usize,
+ direction: &'static str,
+ prog: &Program,
+ hide_thunks: bool,
+ ui: &mut egui::Ui,
+ _muted: Color32,
+ primary: Color32,
+ goto: &mut Option<u64>,
+) {
+ let title = egui::RichText::new(format!("{} {:#x}", node.name, node.va)).monospace();
+ let title = if node.is_thunk {
+ title.color(Color32::from_rgb(0xFB, 0xC0, 0x2D))
+ } else {
+ title.color(primary)
+ };
+ let resp = egui::CollapsingHeader::new(title)
+ .id_salt((direction, node.va, idx))
+ .default_open(false)
+ .show(ui, |ui| {
+ expand_tree_node(node, prog, direction, hide_thunks);
+ if node.children.is_empty() {
+ ui.small("(no further edges)");
+ return;
+ }
+ for (i, child) in node.children.iter_mut().enumerate() {
+ render_call_tree_node(
+ child, i, direction, prog, hide_thunks, ui, _muted, primary, goto,
+ );
+ }
+ });
+ if resp.header_response.clicked() {
+ *goto = Some(node.va);
+ }
+}
+
impl GhidrustApp {
pub fn new(cc: &eframe::CreationContext<'_>) -> Self {
let mut app = Self::headless();
@@ -475,7 +689,11 @@ impl GhidrustApp {
decomp_entry: None,
decomp_text: String::new(),
decomp_status: String::new(),
- decomp_stage: DecompStage::Stage0,
+ // Phase F: Stage-1 is now the default GUI decompiler stage —
+ // real SSA + structure + types instead of the mnemonic-scaffold
+ // Stage-0 preview. Users can still pick Stage-0/Stage-0.5 from
+ // the stage picker combo box.
+ decomp_stage: DecompStage::Stage1,
decomp_lift_ratio: None,
pane_open: Self::default_pane_open(),
nav_history: NavHistory::default(),
@@ -525,6 +743,59 @@ impl GhidrustApp {
comment_window_filter: String::new(),
comment_window_kind_filter: None,
console_severity: vec![ConsoleSeverity::Info],
+ bytes_pane_va: None,
+ bytes_pane_bpr: 16,
+ bytes_pane_rows: 24,
+ symbol_refs_filter: String::new(),
+ symbol_refs_target: None,
+ equates_filter: String::new(),
+ equates_selected: None,
+ show_equate_dialog: false,
+ equate_dialog_va: None,
+ equate_dialog_op: 0,
+ equate_dialog_name: String::new(),
+ equate_dialog_value: String::new(),
+ function_tags_new_input: String::new(),
+ external_programs_filter: String::new(),
+ data_type_preview_selected: "dword".into(),
+ checksum_last: None,
+ show_search_scalars_dialog: false,
+ search_scalars_min: "0".into(),
+ search_scalars_max: "0xffff".into(),
+ show_search_insn_dialog: false,
+ search_insn_mnemonic: String::new(),
+ search_insn_operands: String::new(),
+ show_search_address_tables_dialog: false,
+ function_tags_filter: String::new(),
+ graph_state: GraphPaneState {
+ fn_graph_zoom: 1.0,
+ ..GraphPaneState::default()
+ },
+ call_tree_incoming: Vec::new(),
+ call_tree_outgoing: Vec::new(),
+ register_manager: RegisterManagerState::default(),
+ memory_map_new_name: String::new(),
+ memory_map_new_va: String::new(),
+ memory_map_new_size: String::new(),
+ memory_map_new_r: true,
+ memory_map_new_w: false,
+ memory_map_new_x: false,
+ script_manager: ScriptManagerState::new_with_builtin(),
+ text_editor: TextEditorState::default(),
+ mcp_repl: MacropadReplState::default(),
+ debugger: DebuggerState::default(),
+ debugger_open: {
+ let mut m = BTreeMap::new();
+ for p in DebuggerPane::ALL {
+ m.insert(*p, false);
+ }
+ m
+ },
+ show_configure_dialog: false,
+ show_layouts_dialog: false,
+ layouts_new_name: String::new(),
+ layouts_cached: Vec::new(),
+ current_layout_name: String::new(),
}
}
@@ -1123,6 +1394,192 @@ impl GhidrustApp {
Ok(name)
}
+ // ── Phase D (M4) — equates, function tags, xrefs, checksums ──────────
+
+ /// Attach an equate `name` at `(va, op)` for scalar `value` (Ghidra
+ /// `Convert → Equate`). Empty `name` clears the equate.
+ pub fn set_equate(
+ &mut self,
+ va: u64,
+ op: u8,
+ name: impl Into<String>,
+ value: i64,
+ ) -> Result<(), String> {
+ let name = name.into();
+ let prog = self
+ .program
+ .as_mut()
+ .ok_or_else(|| "no program loaded".to_string())?;
+ let clearing = name.is_empty();
+ prog.edits.set_equate(va, op, &name, value);
+ // Equates render inline in the Listing operand slot; treat as retype
+ // for cache invalidation so the Decompiler picks the change up too.
+ self.event_bus.publish(GhidrustEvent::ProgramMutated {
+ kind: MutationKind::Retype {
+ va,
+ type_desc: if clearing {
+ format!("cleared equate @ op {op}")
+ } else {
+ format!("equate {name} = {value}")
+ },
+ },
+ });
+ self.status = if clearing {
+ format!("Cleared equate @ {va:#x} op {op}")
+ } else {
+ format!("Set equate {name} = {value} @ {va:#x} op {op}")
+ };
+ self.log(self.status.clone());
+ Ok(())
+ }
+
+ /// Function Tags — add / remove / delete-everywhere (Ghidra
+ /// `FunctionTagPlugin`).
+ pub fn add_function_tag(&mut self, entry: u64, tag: impl Into<String>) -> Result<(), String> {
+ let tag = tag.into();
+ if tag.trim().is_empty() {
+ return Err("empty tag".into());
+ }
+ let prog = self
+ .program
+ .as_mut()
+ .ok_or_else(|| "no program loaded".to_string())?;
+ prog.edits.add_function_tag(entry, &tag);
+ self.event_bus.publish(GhidrustEvent::ProgramMutated {
+ kind: MutationKind::Retype {
+ va: entry,
+ type_desc: format!("tag+ {tag}"),
+ },
+ });
+ self.status = format!("Tag '{tag}' added to fn @ {entry:#x}");
+ self.log(self.status.clone());
+ Ok(())
+ }
+
+ pub fn remove_function_tag(&mut self, entry: u64, tag: &str) -> Result<(), String> {
+ let prog = self
+ .program
+ .as_mut()
+ .ok_or_else(|| "no program loaded".to_string())?;
+ let removed = prog.edits.remove_function_tag(entry, tag);
+ if !removed {
+ return Err(format!("fn @ {entry:#x} has no tag '{tag}'"));
+ }
+ self.event_bus.publish(GhidrustEvent::ProgramMutated {
+ kind: MutationKind::Retype {
+ va: entry,
+ type_desc: format!("tag- {tag}"),
+ },
+ });
+ self.status = format!("Tag '{tag}' removed from fn @ {entry:#x}");
+ self.log(self.status.clone());
+ Ok(())
+ }
+
+ /// Register a tag in the universe (`ProgramEdits::all_function_tags`)
+ /// without assigning it to a function. Ghidra's "Create tag" action
+ /// lands here.
+ pub fn create_tag(&mut self, tag: impl Into<String>) -> Result<(), String> {
+ let tag = tag.into();
+ if tag.trim().is_empty() {
+ return Err("empty tag".into());
+ }
+ let prog = self
+ .program
+ .as_mut()
+ .ok_or_else(|| "no program loaded".to_string())?;
+ prog.edits.all_function_tags.insert(tag.clone());
+ self.status = format!("Created tag '{tag}'");
+ self.log(self.status.clone());
+ Ok(())
+ }
+
+ /// Delete a tag from every function and from the universe.
+ pub fn delete_tag_everywhere(&mut self, tag: &str) -> Result<(), String> {
+ let prog = self
+ .program
+ .as_mut()
+ .ok_or_else(|| "no program loaded".to_string())?;
+ let n = prog.edits.delete_tag_everywhere(tag);
+ self.event_bus.publish(GhidrustEvent::ProgramMutated {
+ kind: MutationKind::Retype {
+ va: 0,
+ type_desc: format!("tag deleted: {tag}"),
+ },
+ });
+ self.status = format!("Tag '{tag}' deleted from {n} function(s)");
+ self.log(self.status.clone());
+ Ok(())
+ }
+
+ /// Compute references TO the given target VA. Uses `ghidrust-core::xrefs`
+ /// against the current program + focused-window listing.
+ pub fn xrefs_to_va(&self, target: u64) -> Vec<XRef> {
+ let Some(prog) = self.program.as_ref() else {
+ return Vec::new();
+ };
+ xrefs_to(prog, target, Some(&self.listing))
+ }
+
+ /// Compute references FROM the given source VA.
+ pub fn xrefs_from_va(&self, source: u64) -> Vec<XRef> {
+ let Some(prog) = self.program.as_ref() else {
+ return Vec::new();
+ };
+ xrefs_from(prog, source, STAGE0_MAX_INSNS)
+ }
+
+ /// Compute a checksum panel over the loaded program (or focused block).
+ pub fn compute_checksums(&mut self, mode: ChecksumMode) -> Result<(), String> {
+ let prog = self
+ .program
+ .as_ref()
+ .ok_or_else(|| "no program loaded".to_string())?;
+ let (target_label, data): (String, Vec<u8>) = match mode {
+ ChecksumMode::WholeImage => {
+ let bytes: Vec<u8> = prog.blocks.iter().flat_map(|b| b.bytes.clone()).collect();
+ (format!("Whole image ({})", prog.name), bytes)
+ }
+ ChecksumMode::Section(name) => {
+ let b = prog
+ .blocks
+ .iter()
+ .find(|b| b.name == name)
+ .ok_or_else(|| format!("no block named {name}"))?;
+ (format!("Block {name}"), b.bytes.clone())
+ }
+ };
+ let len = data.len();
+ let crc32 = crc32_ieee(&data);
+ let sum8: u32 = data.iter().map(|&b| b as u32).sum();
+ let sum16: u32 = data
+ .chunks_exact(2)
+ .map(|c| u16::from_le_bytes([c[0], c[1]]) as u32)
+ .sum::<u32>();
+ let sum32: u64 = data
+ .chunks_exact(4)
+ .map(|c| u32::from_le_bytes([c[0], c[1], c[2], c[3]]) as u64)
+ .sum::<u64>();
+ let adler32 = adler32(&data);
+ let (fletcher16, fletcher32) = fletcher_pair(&data);
+ self.checksum_last = Some(ChecksumReport {
+ target: target_label,
+ len,
+ crc32,
+ sum8,
+ sum16,
+ sum32,
+ adler32,
+ fletcher16,
+ fletcher32,
+ });
+ self.status = format!(
+ "Checksum: crc32={crc32:#010x} adler32={adler32:#010x} len={len}",
+ );
+ self.log(self.status.clone());
+ Ok(())
+ }
+
/// Program Tree → Set View / Add To View / Remove From View / Show All.
///
/// The Ghidra semantic is a **fragment name set**. `None` = full view.
@@ -1434,6 +1891,72 @@ impl GhidrustApp {
Ok(())
}
+ /// Search → For Scalars.
+ pub fn run_search_scalars(&mut self) -> Result<(), String> {
+ let min = self
+ .parse_scalar_input(&self.search_scalars_min.clone())
+ .map_err(|e| format!("min: {e}"))?;
+ let max = self
+ .parse_scalar_input(&self.search_scalars_max.clone())
+ .map_err(|e| format!("max: {e}"))?;
+ if min > max {
+ return Err("min > max".into());
+ }
+ self.text_hits = search_scalars(&self.listing, min, max, 1000);
+ self.memory_hits.clear();
+ self.show_search_results = true;
+ self.status = format!(
+ "Scalar search [{min}, {max}]: {} hit(s)",
+ self.text_hits.len()
+ );
+ self.log(self.status.clone());
+ Ok(())
+ }
+
+ fn parse_scalar_input(&self, s: &str) -> Result<i64, String> {
+ let t = s.trim();
+ if t.is_empty() {
+ return Err("empty".into());
+ }
+ let (sign, rest) = if let Some(r) = t.strip_prefix('-') {
+ (-1i64, r)
+ } else {
+ (1i64, t)
+ };
+ // `0x…` prefix wins → hex. Otherwise prefer decimal to preserve
+ // Ghidra's convention (numeric input without a prefix is decimal).
+ let (base, digits) = if let Some(r) = rest.strip_prefix("0x").or_else(|| rest.strip_prefix("0X")) {
+ (16u32, r)
+ } else {
+ (10u32, rest)
+ };
+ let mag = u64::from_str_radix(digits, base).map_err(|e| e.to_string())?;
+ Ok(sign * mag as i64)
+ }
+
+ /// Search → Instruction Patterns.
+ pub fn run_search_instruction_patterns(&mut self) -> Result<(), String> {
+ if self.listing.is_empty() {
+ return Err("no listing loaded".into());
+ }
+ self.text_hits = search_instruction_patterns(
+ &self.listing,
+ &self.search_insn_mnemonic,
+ &self.search_insn_operands,
+ 1000,
+ );
+ self.memory_hits.clear();
+ self.show_search_results = true;
+ self.status = format!(
+ "Instruction pattern hits: {} for `{} {}`",
+ self.text_hits.len(),
+ self.search_insn_mnemonic.trim(),
+ self.search_insn_operands.trim(),
+ );
+ self.log(self.status.clone());
+ Ok(())
+ }
+
/// Search → Program Text.
pub fn run_search_text(&mut self) -> Result<(), String> {
let prog = self
@@ -1654,7 +2177,8 @@ impl GhidrustApp {
Ok(())
}
- /// Start stepped analysis from dialog selections (progress updates each frame).
+ /// Start analysis from dialog selections on a background thread.
+ /// Progress / console lines are delivered via channel and polled each UI frame.
pub fn begin_analysis_job(&mut self) -> Result<(), String> {
if self.analysis_job.is_some() {
return Err("analysis already in progress".into());
@@ -1681,119 +2205,193 @@ impl GhidrustApp {
.as_ref()
.map(|p| p.name.clone())
.unwrap_or_else(|| "program".into());
+ let use_gpu = self.use_gpu_experimental;
self.log(format!(
"Starting analysis on {file_label}: {} analyzer(s), gpu={}",
names.len(),
- self.use_gpu_experimental
+ use_gpu
));
self.status = format!("Analyzing {file_label}…");
+
+ let (msg_tx, msg_rx) = mpsc::channel::<AnalysisWorkerMsg>();
+ // Hand the program to the worker only after spawn succeeds so a spawn
+ // failure cannot drop the only Program copy.
+ let (prog_tx, prog_rx) = mpsc::sync_channel::<Program>(1);
+ let names_worker = names.clone();
+ std::thread::Builder::new()
+ .name("ghidrust-analysis".into())
+ .spawn(move || {
+ let Ok(mut prog) = prog_rx.recv() else {
+ return;
+ };
+ for (index, name) in names_worker.iter().enumerate() {
+ let _ = msg_tx.send(AnalysisWorkerMsg::StepStarted { index });
+ let gpu = use_gpu && analyzer_supports_gpu(name);
+ // catch_unwind: core GPU paths already catch wgpu panics;
+ // belt-and-suspenders so the worker always returns the program.
+ let step = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
+ ghidrust_core::run_analyzers_opts(&mut prog, &[name.as_str()], gpu)
+ }));
+ match step {
+ Ok(Ok(report)) => {
+ let _ = msg_tx.send(AnalysisWorkerMsg::StepFinished {
+ index,
+ outputs: report.results,
+ });
+ }
+ Ok(Err(e)) => {
+ let _ = msg_tx.send(AnalysisWorkerMsg::Failed {
+ error: e.to_string(),
+ program: prog,
+ });
+ return;
+ }
+ Err(_) => {
+ let _ = msg_tx.send(AnalysisWorkerMsg::Failed {
+ error: format!(
+ "analyzer '{name}' panicked (GPU/validation); try again with GPU off"
+ ),
+ program: prog,
+ });
+ return;
+ }
+ }
+ }
+ let _ = msg_tx.send(AnalysisWorkerMsg::Done { program: prog });
+ })
+ .map_err(|e| format!("failed to spawn analysis worker: {e}"))?;
+
+ let prog = self
+ .program
+ .take()
+ .expect("program checked non-None above");
+ if prog_tx.send(prog).is_err() {
+ return Err("analysis worker exited before receiving program".into());
+ }
+
self.analysis_job = Some(AnalysisJob {
names,
index: 0,
results: AnalysisRunReport::default(),
file_label,
- use_gpu: self.use_gpu_experimental,
+ use_gpu,
+ rx: msg_rx,
});
Ok(())
}
- /// Run one analyzer step; call every frame while `analysis_job` is Some.
+ /// Poll the analysis worker (non-blocking). Call every frame while `analysis_job` is Some.
+ /// Returns `Ok(true)` when the job has finished and been finalized.
pub fn step_analysis_job(&mut self) -> Result<bool, String> {
- let (name, idx, total, label) = {
- let job = self
- .analysis_job
- .as_ref()
- .ok_or_else(|| "no analysis job".to_string())?;
- if job.index >= job.names.len() {
- self.finish_analysis_job()?;
- return Ok(true);
- }
- (
- job.names[job.index].clone(),
- job.index,
- job.names.len(),
- job.file_label.clone(),
- )
- };
- let master_gpu = self
+ self.poll_analysis_job(false)
+ }
+
+ /// Block until at least one worker message arrives (tests / headless drain).
+ pub fn step_analysis_job_blocking(&mut self) -> Result<bool, String> {
+ self.poll_analysis_job(true)
+ }
+
+ fn recv_analysis_msg(&self, block: bool) -> Result<Option<AnalysisWorkerMsg>, String> {
+ let job = self
.analysis_job
.as_ref()
- .map(|j| j.use_gpu)
- .unwrap_or(false);
- // Only request GPU for analyzers that have a strategy (matrix / docs).
- let use_gpu = master_gpu && analyzer_supports_gpu(&name);
- let prog = self
- .program
- .as_mut()
- .ok_or_else(|| "no program loaded".to_string())?;
- // catch_unwind: core GPU paths already catch wgpu panics; belt-and-suspenders for UI.
- let report = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
- ghidrust_core::run_analyzers_opts(prog, &[name.as_str()], use_gpu)
- })) {
- Ok(Ok(r)) => r,
- Ok(Err(e)) => return Err(e.to_string()),
- Err(_) => {
- return Err(format!(
- "analyzer '{name}' panicked (GPU/validation); try again with GPU off"
- ));
- }
- };
- let mut log_lines = Vec::new();
- let mut rtti_upd = None;
- let mut strings_upd = None;
- let mut outputs = Vec::new();
- for r in report.results {
- log_lines.push(format!("[{}] {} — {}", r.status, r.name, r.message));
- if r.rtti.is_some() {
- rtti_upd = r.rtti.clone();
+ .ok_or_else(|| "no analysis job".to_string())?;
+ if block {
+ match job.rx.recv() {
+ Ok(m) => Ok(Some(m)),
+ Err(RecvError) => Err("analysis worker disconnected".into()),
}
- if r.strings.is_some() {
- strings_upd = r.strings.clone();
+ } else {
+ match job.rx.try_recv() {
+ Ok(m) => Ok(Some(m)),
+ Err(TryRecvError::Empty) => Ok(None),
+ Err(TryRecvError::Disconnected) => Err("analysis worker disconnected".into()),
}
- outputs.push(r);
- }
- for line in log_lines {
- let sev = if line.starts_with("[error]") {
- ConsoleSeverity::Error
- } else if line.starts_with("[warn") {
- ConsoleSeverity::Warn
- } else {
- ConsoleSeverity::Info
- };
- self.log_with(line, sev);
- }
- if let Some(r) = rtti_upd {
- self.rtti = r;
- }
- if let Some(s) = strings_upd {
- self.strings = s;
}
- if let Some(job) = self.analysis_job.as_mut() {
- job.results.results.extend(outputs);
- job.index = idx + 1;
- }
- let done = self
- .analysis_job
- .as_ref()
- .map(|j| j.index >= j.names.len())
- .unwrap_or(true);
- if done {
- self.finish_analysis_job()?;
+ }
+
+ fn poll_analysis_job(&mut self, block: bool) -> Result<bool, String> {
+ let Some(first) = self.recv_analysis_msg(block)? else {
+ return Ok(false);
+ };
+ if self.apply_analysis_msg(first)? {
return Ok(true);
}
- self.status = format!(
- "Analyzing {label} — {}/{}: {}",
- idx + 2,
- total,
- self.analysis_job
- .as_ref()
- .and_then(|j| j.names.get(j.index))
- .map(|s| s.as_str())
- .unwrap_or("…")
- );
+ // Drain any further messages already queued so one frame can catch up.
+ while let Some(msg) = self.recv_analysis_msg(false)? {
+ if self.apply_analysis_msg(msg)? {
+ return Ok(true);
+ }
+ }
Ok(false)
}
+ /// Apply one worker message. Returns `Ok(true)` when the job is fully finished.
+ fn apply_analysis_msg(&mut self, msg: AnalysisWorkerMsg) -> Result<bool, String> {
+ match msg {
+ AnalysisWorkerMsg::StepStarted { index } => {
+ if let Some(job) = self.analysis_job.as_mut() {
+ job.index = index;
+ let total = job.names.len();
+ let label = job.file_label.clone();
+ let cur = job
+ .names
+ .get(index)
+ .cloned()
+ .unwrap_or_else(|| "…".into());
+ self.status = format!("Analyzing {label} — {}/{total}: {cur}", index + 1);
+ }
+ Ok(false)
+ }
+ AnalysisWorkerMsg::StepFinished { index, outputs } => {
+ let mut log_lines = Vec::new();
+ let mut rtti_upd = None;
+ let mut strings_upd = None;
+ for r in &outputs {
+ log_lines.push(format!("[{}] {} — {}", r.status, r.name, r.message));
+ if r.rtti.is_some() {
+ rtti_upd = r.rtti.clone();
+ }
+ if r.strings.is_some() {
+ strings_upd = r.strings.clone();
+ }
+ }
+ for line in log_lines {
+ let sev = if line.starts_with("[error]") {
+ ConsoleSeverity::Error
+ } else if line.starts_with("[warn") {
+ ConsoleSeverity::Warn
+ } else {
+ ConsoleSeverity::Info
+ };
+ self.log_with(line, sev);
+ }
+ if let Some(r) = rtti_upd {
+ self.rtti = r;
+ }
+ if let Some(s) = strings_upd {
+ self.strings = s;
+ }
+ if let Some(job) = self.analysis_job.as_mut() {
+ job.results.results.extend(outputs);
+ job.index = index + 1;
+ }
+ Ok(false)
+ }
+ AnalysisWorkerMsg::Done { program } => {
+ self.program = Some(program);
+ self.finish_analysis_job()?;
+ Ok(true)
+ }
+ AnalysisWorkerMsg::Failed { error, program } => {
+ self.program = Some(program);
+ self.analysis_job = None;
+ set_preferred_bulk_mode(BulkScanMode::ParallelCpu);
+ Err(error)
+ }
+ }
+ }
+
fn finish_analysis_job(&mut self) -> Result<(), String> {
let job = self
.analysis_job
@@ -2109,11 +2707,11 @@ impl GhidrustApp {
Ok(())
}
- /// Headless/sync: begin job and drain all steps (tests + non-UI callers).
+ /// Headless/sync: begin job and drain all worker messages (tests + non-UI callers).
pub fn run_selected_analysis(&mut self) -> Result<(), String> {
self.begin_analysis_job()?;
while self.analysis_job.is_some() {
- self.step_analysis_job()?;
+ self.step_analysis_job_blocking()?;
}
Ok(())
}
@@ -2172,6 +2770,7 @@ impl GhidrustApp {
"Tools",
"Graph",
"Window",
+ "Debugger",
"Help",
]
}
@@ -2199,6 +2798,13 @@ impl GhidrustApp {
names.push(t);
}
}
+ // Ghidra Debugger tool providers (Phase G / M7 visibility parity).
+ for p in DebuggerPane::ALL {
+ let t = p.title();
+ if !names.contains(&t) {
+ names.push(t);
+ }
+ }
names
}
@@ -2526,6 +3132,65 @@ impl GhidrustApp {
PaneKind::DefinedData => {
win.show(ctx, |ui| self.ui_defined_data(ui, muted));
}
+ PaneKind::Bytes => {
+ win.show(ctx, |ui| self.ui_bytes_pane(ui, muted, primary));
+ }
+ PaneKind::SymbolReferences => {
+ win.show(ctx, |ui| self.ui_symbol_references(ui, muted));
+ }
+ PaneKind::EquatesTable => {
+ win.show(ctx, |ui| self.ui_equates_table(ui, muted));
+ }
+ PaneKind::FunctionTags => {
+ win.show(ctx, |ui| self.ui_function_tags(ui, muted));
+ }
+ PaneKind::ExternalPrograms => {
+ win.show(ctx, |ui| self.ui_external_programs(ui, muted));
+ }
+ PaneKind::DataTypePreview => {
+ win.show(ctx, |ui| self.ui_data_type_preview(ui, muted));
+ }
+ PaneKind::ChecksumGenerator => {
+ win.show(ctx, |ui| self.ui_checksum_generator(ui, muted));
+ }
+ // Phase E (M5) — Graphs & maps.
+ PaneKind::FunctionGraph => {
+ win.default_size(egui::vec2(760.0, 520.0))
+ .show(ctx, |ui| self.ui_function_graph_pane(ui, muted, primary));
+ }
+ PaneKind::FunctionCallGraph => {
+ win.default_size(egui::vec2(760.0, 480.0))
+ .show(ctx, |ui| self.ui_function_call_graph_pane(ui, muted, primary));
+ }
+ PaneKind::FunctionCallTrees => {
+ win.default_size(egui::vec2(760.0, 460.0))
+ .show(ctx, |ui| self.ui_function_call_trees_pane(ui, muted, primary));
+ }
+ PaneKind::Entropy => {
+ win.default_size(egui::vec2(680.0, 220.0))
+ .show(ctx, |ui| self.ui_entropy_pane(ui, muted, primary));
+ }
+ PaneKind::Overview => {
+ win.default_size(egui::vec2(680.0, 340.0))
+ .show(ctx, |ui| self.ui_overview(ui));
+ }
+ PaneKind::RegisterManager => {
+ win.default_size(egui::vec2(560.0, 520.0))
+ .show(ctx, |ui| self.ui_register_manager_pane(ui, muted, primary));
+ }
+ // Phase F (M6) — Scripts & interpreters.
+ PaneKind::ScriptManager => {
+ win.default_size(egui::vec2(760.0, 480.0))
+ .show(ctx, |ui| self.ui_script_manager_pane(ui, muted, primary));
+ }
+ PaneKind::TextEditor => {
+ win.default_size(egui::vec2(720.0, 520.0))
+ .show(ctx, |ui| self.ui_text_editor_pane(ui, muted, primary));
+ }
+ PaneKind::Python => {
+ win.default_size(egui::vec2(640.0, 420.0))
+ .show(ctx, |ui| self.ui_mcp_repl_pane(ui, muted, primary));
+ }
_ => {
win.show(ctx, |ui| {
panes::empty_state(ui, kind, muted);
@@ -2537,6 +3202,539 @@ impl GhidrustApp {
self.pane_open.insert(kind, false);
}
}
+
+ // Phase G (M7) — Debugger tool provider windows.
+ self.draw_debugger_panes(ctx, muted);
+ }
+
+ // ── Phase E (M5) — Graphs & maps ────────────────────────────────────
+
+ /// Ghidra `FunctionGraphPlugin` — CFG vertex/edge layout for the current function.
+ fn ui_function_graph_pane(&mut self, ui: &mut egui::Ui, muted: Color32, primary: Color32) {
+ ui.heading("Function Graph");
+ ui.small(
+ egui::RichText::new(
+ "Ghidra FunctionGraphPlugin analog · Stage-0 CFG from ghidrust-decomp::decompile_at",
+ )
+ .color(muted),
+ );
+ ui.separator();
+
+ let Some(prog) = self.program.as_ref() else {
+ ui.weak("No program loaded.");
+ return;
+ };
+ let Some(entry) = self
+ .focused_function_entry
+ .or_else(|| self.listing_focus_va.and_then(|va| {
+ prog.analysis
+ .functions
+ .iter()
+ .find(|f| va >= f.entry && va < f.end)
+ .map(|f| f.entry)
+ }))
+ else {
+ ui.weak("Cursor is not inside a recovered function.");
+ ui.small(
+ egui::RichText::new(
+ "Click a function in Symbol Tree, Functions, or Listing to populate the graph.",
+ )
+ .color(muted),
+ );
+ return;
+ };
+
+ ui.horizontal(|ui| {
+ ui.label("Layout:");
+ let cur = self.graph_state.fn_graph_layout;
+ egui::ComboBox::from_id_salt("fg_layout")
+ .selected_text(cur.label())
+ .show_ui(ui, |ui| {
+ for l in FunctionGraphLayout::ALL {
+ ui.selectable_value(&mut self.graph_state.fn_graph_layout, *l, l.label());
+ }
+ });
+ ui.separator();
+ ui.label("Zoom:");
+ ui.add(
+ egui::Slider::new(&mut self.graph_state.fn_graph_zoom, 0.5..=2.0)
+ .clamping(egui::SliderClamping::Always)
+ .fixed_decimals(1),
+ );
+ if ui.button("Fit").on_hover_text("Reset zoom to 1.0").clicked() {
+ self.graph_state.fn_graph_zoom = 1.0;
+ }
+ ui.separator();
+ ui.small(egui::RichText::new(format!("Entry {entry:#x}")).color(muted));
+ });
+ ui.separator();
+
+ let name = prog.display_function_name_at(entry).unwrap_or_default();
+ if !name.is_empty() {
+ ui.small(egui::RichText::new(format!("Function {name}")).color(muted));
+ }
+
+ let algo = self.graph_state.fn_graph_layout;
+ let zoom = self.graph_state.fn_graph_zoom.max(0.1);
+ let focused_va = self.listing_focus_va;
+ let (rect, _resp) = ui.allocate_exact_size(
+ egui::vec2(ui.available_width(), 400.0 * zoom),
+ egui::Sense::hover(),
+ );
+ let (blocks, edges) = layout_function_graph(prog, entry, STAGE0_MAX_INSNS, algo, rect);
+ if blocks.is_empty() {
+ ui.painter().rect_stroke(
+ rect,
+ 4.0,
+ egui::Stroke::new(1.0, muted),
+ egui::StrokeKind::Middle,
+ );
+ ui.painter().text(
+ rect.center(),
+ egui::Align2::CENTER_CENTER,
+ "No Stage-0 CFG recovered for this VA.",
+ egui::FontId::proportional(13.0),
+ muted,
+ );
+ return;
+ }
+ let clicked = render_function_graph(ui, &blocks, &edges, focused_va, primary, muted);
+ if let Some(va) = clicked {
+ let _ = self.goto_address_str(&format!("{va:#x}"));
+ }
+ }
+
+ /// Ghidra `FunctionCallGraphPlugin` — level-based directed graph.
+ fn ui_function_call_graph_pane(
+ &mut self,
+ ui: &mut egui::Ui,
+ muted: Color32,
+ primary: Color32,
+ ) {
+ ui.heading("Function Call Graph");
+ ui.small(
+ egui::RichText::new(
+ "Ghidra FunctionCallGraphPlugin analog · levels expanded from analyzer references",
+ )
+ .color(muted),
+ );
+ ui.separator();
+
+ let Some(prog) = self.program.as_ref() else {
+ ui.weak("No program loaded.");
+ return;
+ };
+ let Some(entry) = self
+ .focused_function_entry
+ .or_else(|| self.listing_focus_va.and_then(|va| {
+ prog.analysis
+ .functions
+ .iter()
+ .find(|f| va >= f.entry && va < f.end)
+ .map(|f| f.entry)
+ }))
+ .or(prog.entry)
+ else {
+ ui.weak("No entry point — click a function in Symbol Tree to root the call graph.");
+ return;
+ };
+
+ ui.horizontal(|ui| {
+ ui.label("Callers levels:");
+ let mut lvl_in = self.graph_state.call_graph_levels_in;
+ ui.add(egui::Slider::new(&mut lvl_in, 0..=3));
+ self.graph_state.call_graph_levels_in = lvl_in;
+ ui.separator();
+ ui.label("Callees levels:");
+ let mut lvl_out = self.graph_state.call_graph_levels_out;
+ ui.add(egui::Slider::new(&mut lvl_out, 0..=3));
+ self.graph_state.call_graph_levels_out = lvl_out;
+ if ui.button("Reset").clicked() {
+ self.graph_state.call_graph_levels_in = 1;
+ self.graph_state.call_graph_levels_out = 1;
+ }
+ });
+ ui.separator();
+
+ let (rect, _resp) = ui.allocate_exact_size(
+ egui::vec2(ui.available_width(), 380.0),
+ egui::Sense::hover(),
+ );
+ let (verts, edges) = layout_call_graph(
+ prog,
+ entry,
+ self.graph_state.call_graph_levels_in,
+ self.graph_state.call_graph_levels_out,
+ rect,
+ );
+ ui.painter().rect_stroke(
+ rect,
+ 4.0,
+ egui::Stroke::new(1.0, muted),
+ egui::StrokeKind::Middle,
+ );
+ if verts.is_empty() {
+ ui.painter().text(
+ rect.center(),
+ egui::Align2::CENTER_CENTER,
+ "No call references recovered — run analyzers first.",
+ egui::FontId::proportional(13.0),
+ muted,
+ );
+ return;
+ }
+ let clicked = render_call_graph(ui, &verts, &edges, entry, primary, muted);
+ if let Some(va) = clicked {
+ self.focus_function(va);
+ }
+ }
+
+ /// Ghidra `CallTreePlugin` — incoming callers / outgoing callees GTree pair.
+ fn ui_function_call_trees_pane(
+ &mut self,
+ ui: &mut egui::Ui,
+ muted: Color32,
+ primary: Color32,
+ ) {
+ ui.heading("Function Call Trees");
+ ui.small(
+ egui::RichText::new(
+ "Ghidra CallTreePlugin analog · Incoming / Outgoing GTrees over analyzer refs",
+ )
+ .color(muted),
+ );
+ ui.separator();
+
+ let Some(prog) = self.program.as_ref() else {
+ ui.weak("No program loaded.");
+ return;
+ };
+ let Some(entry) = self
+ .focused_function_entry
+ .or_else(|| self.listing_focus_va.and_then(|va| {
+ prog.analysis
+ .functions
+ .iter()
+ .find(|f| va >= f.entry && va < f.end)
+ .map(|f| f.entry)
+ }))
+ else {
+ ui.weak("Cursor is not inside a recovered function.");
+ return;
+ };
+
+ // Rebuild top level if root changed.
+ let root_name = prog.display_function_name_at(entry).unwrap_or_default();
+ ui.horizontal(|ui| {
+ ui.small(egui::RichText::new(format!("Source {root_name} @ {entry:#x}")).color(muted));
+ if ui.button("Refresh").clicked() {
+ self.call_tree_incoming.clear();
+ self.call_tree_outgoing.clear();
+ }
+ ui.separator();
+ ui.checkbox(
+ &mut self.graph_state.call_tree_hide_thunks,
+ "Hide thunks",
+ );
+ ui.checkbox(
+ &mut self.graph_state.call_tree_refs_only,
+ "References only",
+ );
+ });
+ ui.separator();
+
+ if self.call_tree_incoming.is_empty() && self.call_tree_outgoing.is_empty() {
+ self.call_tree_incoming = build_incoming_tree(prog, entry);
+ self.call_tree_outgoing = build_outgoing_tree(prog, entry);
+ if self.graph_state.call_tree_hide_thunks {
+ self.call_tree_incoming.retain(|n| !n.is_thunk);
+ self.call_tree_outgoing.retain(|n| !n.is_thunk);
+ }
+ }
+
+ let refs_only = self.graph_state.call_tree_refs_only;
+ let hide_thunks = self.graph_state.call_tree_hide_thunks;
+ let mut goto: Option<u64> = None;
+ egui::ScrollArea::vertical()
+ .id_salt("calltrees_scroll")
+ .max_height(360.0)
+ .show(ui, |ui| {
+ ui.columns(2, |cols| {
+ cols[0].label(egui::RichText::new("Incoming (callers / refs to)").strong());
+ let mut inc = std::mem::take(&mut self.call_tree_incoming);
+ for (i, node) in inc.iter_mut().enumerate() {
+ render_call_tree_node(
+ node,
+ i,
+ "incoming",
+ prog,
+ hide_thunks,
+ &mut cols[0],
+ muted,
+ primary,
+ &mut goto,
+ );
+ }
+ self.call_tree_incoming = inc;
+ if refs_only {
+ cols[0].separator();
+ cols[0].label(
+ egui::RichText::new("Data refs to source")
+ .strong()
+ .color(muted),
+ );
+ for xr in data_xrefs_to(prog, entry) {
+ let text = egui::RichText::new(format!(
+ "{} {} ← {:#x}",
+ xr.kind, xr.preview, xr.from
+ ))
+ .monospace();
+ if cols[0].link(text).clicked() {
+ goto = Some(xr.from);
+ }
+ }
+ }
+
+ cols[1].label(egui::RichText::new("Outgoing (callees / refs from)").strong());
+ let mut out = std::mem::take(&mut self.call_tree_outgoing);
+ for (i, node) in out.iter_mut().enumerate() {
+ render_call_tree_node(
+ node,
+ i,
+ "outgoing",
+ prog,
+ hide_thunks,
+ &mut cols[1],
+ muted,
+ primary,
+ &mut goto,
+ );
+ }
+ self.call_tree_outgoing = out;
+ });
+ });
+ if let Some(va) = goto {
+ self.focus_function(va);
+ }
+ }
+
+ /// Ghidra `EntropyPlugin` header — Shannon-entropy strip across mapped blocks.
+ fn ui_entropy_pane(&mut self, ui: &mut egui::Ui, muted: Color32, primary: Color32) {
+ ui.heading("Entropy");
+ ui.small(
+ egui::RichText::new(
+ "Ghidra EntropyPlugin analog · Shannon bits/byte over 256-byte windows",
+ )
+ .color(muted),
+ );
+ ui.separator();
+ let Some(prog) = self.program.as_ref() else {
+ ui.weak("No program loaded.");
+ return;
+ };
+ let samples = entropy::entropy_samples(prog, 256);
+ ui.small(format!("{} windows sampled (256 bytes each)", samples.len()));
+ let clicked_e =
+ entropy::render_entropy_strip(ui, &samples, muted, self.listing_focus_va, primary);
+ ui.add_space(6.0);
+ ui.label(egui::RichText::new("Overview").strong().color(muted));
+ let clicked_o =
+ entropy::render_overview_strip(ui, prog, &samples, muted, self.listing_focus_va, primary);
+ ui.small(
+ egui::RichText::new("Click a strip to Go To that address. Green = exec, amber = writable, grey = readonly, cold-blue = low entropy, warm-red = high.").color(muted),
+ );
+ if let Some(va) = clicked_e.or(clicked_o) {
+ let _ = self.goto_address_str(&format!("{va:#x}"));
+ }
+ }
+
+ /// Ghidra `RegisterPlugin` — register lattice + user-set value ranges.
+ fn ui_register_manager_pane(
+ &mut self,
+ ui: &mut egui::Ui,
+ muted: Color32,
+ primary: Color32,
+ ) {
+ let fmt = self.program.as_ref().map(|p| p.format.clone());
+ register_manager::render(&mut self.register_manager, fmt.as_deref(), ui, muted, primary);
+ }
+
+ // ── Phase F (M6) — Scripts & interpreters ───────────────────────────
+
+ fn ui_script_manager_pane(&mut self, ui: &mut egui::Ui, muted: Color32, primary: Color32) {
+ if let Some(run) = render_script_manager(&mut self.script_manager, ui, muted, primary) {
+ let msg = format!(
+ "Script Manager · run requested for `{run}` — full script host lands in Phase F backend"
+ );
+ self.status = msg.clone();
+ self.log(msg);
+ }
+ }
+
+ fn ui_text_editor_pane(&mut self, ui: &mut egui::Ui, muted: Color32, primary: Color32) {
+ let req = render_text_editor(&mut self.text_editor, ui, muted, primary);
+ match req {
+ TextEditorRequest::None => {}
+ TextEditorRequest::NewUntitled => self.text_editor.open_untitled(),
+ TextEditorRequest::OpenFile => {
+ if let Some(path) = rfd::FileDialog::new()
+ .add_filter("Scripts", &["py", "rs", "txt", "md", "json", "toml"])
+ .add_filter("All", &["*"])
+ .pick_file()
+ {
+ if let Err(e) = self.text_editor.open_file(path) {
+ self.status = format!("open error: {e}");
+ self.log_error(self.status.clone());
+ }
+ }
+ }
+ TextEditorRequest::Save => {
+ if let Err(e) = self.text_editor.save_active() {
+ self.status = format!("save error: {e}");
+ self.log_error(self.status.clone());
+ }
+ }
+ TextEditorRequest::SaveAs => {
+ if let Some(path) = rfd::FileDialog::new().save_file() {
+ if let Err(e) = self.text_editor.save_active_as(path) {
+ self.status = format!("save error: {e}");
+ self.log_error(self.status.clone());
+ }
+ }
+ }
+ TextEditorRequest::Close => self.text_editor.close_active(),
+ }
+ }
+
+ fn ui_mcp_repl_pane(&mut self, ui: &mut egui::Ui, muted: Color32, primary: Color32) {
+ render_mcp_repl(&mut self.mcp_repl, ui, muted, primary);
+ }
+
+ // ── Phase G (M7) — Debugger tool ──────────────────────────────────
+
+ fn draw_debugger_panes(&mut self, ctx: &egui::Context, muted: Color32) {
+ let open_list: Vec<DebuggerPane> = self
+ .debugger_open
+ .iter()
+ .filter_map(|(p, v)| if *v { Some(*p) } else { None })
+ .collect();
+ for pane in open_list {
+ let mut open = true;
+ let title = pane.title();
+ let id = egui::Id::new(pane.egui_id());
+ egui::Window::new(title)
+ .id(id)
+ .open(&mut open)
+ .resizable(true)
+ .default_size(egui::vec2(520.0, 320.0))
+ .show(ctx, |ui| {
+ debugger::render(pane, &mut self.debugger, ui, muted);
+ });
+ if !open {
+ self.debugger_open.insert(pane, false);
+ }
+ }
+ }
+
+ // ── Phase H (M8) — Docking / layouts / Configure ────────────────
+
+ fn snapshot_current_layout(&self, name: impl Into<String>) -> layouts::SavedLayout {
+ let name = name.into();
+ let mut open_panes = BTreeMap::new();
+ for (k, v) in &self.pane_open {
+ open_panes.insert(k.egui_id().to_string(), *v);
+ }
+ for (p, v) in &self.debugger_open {
+ open_panes.insert(p.egui_id().to_string(), *v);
+ }
+ let mut docks = BTreeMap::new();
+ docks.insert("project_tree".into(), self.show_project_tree);
+ docks.insert("program_tree".into(), self.show_program_tree);
+ docks.insert("symbol_tree".into(), self.show_symbol_tree);
+ docks.insert("console".into(), self.show_console);
+ let center = match self.center {
+ CenterPane::Overview => "overview",
+ CenterPane::Listing => "listing",
+ CenterPane::Decompiler => "decompiler",
+ CenterPane::DataTypes => "datatypes",
+ }
+ .to_string();
+ let theme = match self.theme {
+ ThemeMode::Dark => "dark",
+ ThemeMode::Light => "light",
+ }
+ .to_string();
+ layouts::SavedLayout {
+ name,
+ open_panes,
+ docks,
+ center,
+ theme,
+ comment: String::new(),
+ }
+ }
+
+ fn apply_saved_layout(&mut self, layout: &layouts::SavedLayout) {
+ // Apply pane visibility.
+ let ids: BTreeMap<&'static str, PaneKind> = PaneKind::ALL
+ .iter()
+ .map(|k| (k.egui_id(), *k))
+ .collect();
+ for (id, open) in &layout.open_panes {
+ if let Some(k) = ids.get(id.as_str()) {
+ self.pane_open.insert(*k, *open);
+ }
+ }
+ let dbg_ids: BTreeMap<&'static str, DebuggerPane> = DebuggerPane::ALL
+ .iter()
+ .map(|p| (p.egui_id(), *p))
+ .collect();
+ for (id, open) in &layout.open_panes {
+ if let Some(p) = dbg_ids.get(id.as_str()) {
+ self.debugger_open.insert(*p, *open);
+ }
+ }
+ // Docks.
+ if let Some(v) = layout.docks.get("project_tree") {
+ self.show_project_tree = *v;
+ }
+ if let Some(v) = layout.docks.get("program_tree") {
+ self.show_program_tree = *v;
+ }
+ if let Some(v) = layout.docks.get("symbol_tree") {
+ self.show_symbol_tree = *v;
+ }
+ if let Some(v) = layout.docks.get("console") {
+ self.show_console = *v;
+ }
+ self.center = match layout.center.as_str() {
+ "listing" => CenterPane::Listing,
+ "decompiler" => CenterPane::Decompiler,
+ "datatypes" => CenterPane::DataTypes,
+ _ => CenterPane::Overview,
+ };
+ self.theme = match layout.theme.as_str() {
+ "light" => ThemeMode::Light,
+ _ => ThemeMode::Dark,
+ };
+ self.current_layout_name = layout.name.clone();
+ }
+
+ /// Save the current layout under `name`.
+ pub fn save_layout_named(&mut self, name: impl Into<String>) -> std::io::Result<PathBuf> {
+ let name = name.into();
+ let l = self.snapshot_current_layout(name.clone());
+ let p = layouts::save_layout(&l)?;
+ self.current_layout_name = name;
+ self.layouts_cached = layouts::list_layouts();
+ Ok(p)
+ }
+
+ /// Restore a saved layout by name.
+ pub fn restore_layout_named(&mut self, name: &str) -> std::io::Result<()> {
+ let l = layouts::load_layout(name)?;
+ self.apply_saved_layout(&l);
+ Ok(())
}
/// Phase C (M3) — draw all edit dialogs (rename / retype / comment / signature / new type).
@@ -3444,6 +4642,9 @@ impl GhidrustApp {
OpenRetype,
OpenChooser,
OpenSignature,
+ OpenEquate,
+ ShowRefsTo,
+ OpenBytesHere,
}
let mut pending_action: Option<(u64, RowAction)> = None;
egui::ScrollArea::both()
@@ -3552,6 +4753,19 @@ impl GhidrustApp {
pending_action = Some((va, RowAction::OpenSignature));
ui.close_menu();
}
+ ui.separator();
+ if ui.button("Set Equate…").on_hover_text("Bind a name to the first operand scalar").clicked() {
+ pending_action = Some((va, RowAction::OpenEquate));
+ ui.close_menu();
+ }
+ if ui.button("Show References To…").on_hover_text("Open Symbol References for this VA").clicked() {
+ pending_action = Some((va, RowAction::ShowRefsTo));
+ ui.close_menu();
+ }
+ if ui.button("Show Bytes Here").on_hover_text("Open Byte Viewer at this VA").clicked() {
+ pending_action = Some((va, RowAction::OpenBytesHere));
+ ui.close_menu();
+ }
});
// Bytes column.
ui.monospace(&row.bytes_hex);
@@ -3672,6 +4886,28 @@ impl GhidrustApp {
.unwrap_or(va);
self.open_signature_dialog(entry);
}
+ RowAction::OpenEquate => {
+ self.equate_dialog_va = Some(va);
+ self.equate_dialog_op = 1;
+ self.equate_dialog_name.clear();
+ // Preload first scalar from the operand string for convenience.
+ self.equate_dialog_value = self
+ .listing
+ .iter()
+ .find(|i| i.address == va)
+ .and_then(|i| menu_actions::extract_scalars(&i.operands).first().copied())
+ .map(|v| format!("{v}"))
+ .unwrap_or_default();
+ self.show_equate_dialog = true;
+ }
+ RowAction::ShowRefsTo => {
+ self.symbol_refs_target = Some(va);
+ self.pane_open.insert(PaneKind::SymbolReferences, true);
+ }
+ RowAction::OpenBytesHere => {
+ self.bytes_pane_va = Some(va);
+ self.pane_open.insert(PaneKind::Bytes, true);
+ }
}
}
}
@@ -4105,36 +5341,77 @@ impl GhidrustApp {
fn ui_memory_map_pane(&mut self, ui: &mut egui::Ui, muted: Color32) {
ui.heading("Memory Map");
ui.small(
- egui::RichText::new("Ghidra MemoryMapPlugin · read-only (edits land in Phase E)")
- .color(muted),
+ egui::RichText::new(
+ "Ghidra MemoryMapPlugin · toggle RWX / add / delete session memory blocks",
+ )
+ .color(muted),
);
ui.separator();
- let rows: Vec<(String, u64, u64, bool, bool, bool)> = match self.program.as_ref() {
- Some(prog) => prog
- .blocks
- .iter()
- .map(|b| {
- (
- b.name.clone(),
- b.va,
- b.size,
- b.readable,
- b.writable,
- b.executable,
- )
- })
- .collect(),
- None => {
- ui.weak("No program loaded.");
- return;
+ if self.program.is_none() {
+ ui.weak("No program loaded.");
+ return;
+ }
+
+ // Add-row form.
+ ui.horizontal(|ui| {
+ ui.label("Add block:");
+ ui.add(
+ egui::TextEdit::singleline(&mut self.memory_map_new_name)
+ .desired_width(120.0)
+ .hint_text("name"),
+ );
+ ui.add(
+ egui::TextEdit::singleline(&mut self.memory_map_new_va)
+ .desired_width(120.0)
+ .hint_text("VA (0x…)"),
+ );
+ ui.add(
+ egui::TextEdit::singleline(&mut self.memory_map_new_size)
+ .desired_width(100.0)
+ .hint_text("size (0x…)"),
+ );
+ ui.checkbox(&mut self.memory_map_new_r, "R");
+ ui.checkbox(&mut self.memory_map_new_w, "W");
+ ui.checkbox(&mut self.memory_map_new_x, "X");
+ let can_add = !self.memory_map_new_name.trim().is_empty()
+ && !self.memory_map_new_va.trim().is_empty()
+ && !self.memory_map_new_size.trim().is_empty();
+ if ui.add_enabled(can_add, egui::Button::new("Add")).clicked() {
+ let name = self.memory_map_new_name.clone();
+ let va = parse_address(&self.memory_map_new_va).unwrap_or(0);
+ let size = parse_address(&self.memory_map_new_size).unwrap_or(0);
+ let r = self.memory_map_new_r;
+ let w = self.memory_map_new_w;
+ let x = self.memory_map_new_x;
+ if size > 0 {
+ if let Some(prog) = self.program.as_mut() {
+ prog.blocks.push(ghidrust_core::MemoryBlock {
+ name,
+ va,
+ size,
+ bytes: vec![0u8; size.min(0x100_0000) as usize],
+ readable: r,
+ writable: w,
+ executable: x,
+ });
+ }
+ self.status = "Memory Map · added block".into();
+ self.log(self.status.clone());
+ }
}
- };
+ });
+ ui.separator();
+
let mut goto: Option<u64> = None;
+ let mut delete: Option<usize> = None;
+ let mut rename: Option<(usize, String)> = None;
+ let mut toggle: Option<(usize, char)> = None;
+
egui::ScrollArea::both()
.id_salt("memmap_scroll")
.show(ui, |ui| {
egui::Grid::new("memory_map_grid")
- .num_columns(7)
+ .num_columns(8)
.striped(true)
.show(ui, |ui| {
ui.strong("Name");
@@ -4144,9 +5421,38 @@ impl GhidrustApp {
ui.strong("R");
ui.strong("W");
ui.strong("X");
+ ui.strong("");
ui.end_row();
- for (name, va, size, r, w, x) in &rows {
- ui.monospace(name);
+ let blocks: Vec<(String, u64, u64, bool, bool, bool)> = self
+ .program
+ .as_ref()
+ .map(|p| {
+ p.blocks
+ .iter()
+ .map(|b| {
+ (
+ b.name.clone(),
+ b.va,
+ b.size,
+ b.readable,
+ b.writable,
+ b.executable,
+ )
+ })
+ .collect()
+ })
+ .unwrap_or_default();
+ for (i, (name, va, size, r, w, x)) in blocks.iter().enumerate() {
+ let mut editable = name.clone();
+ if ui
+ .add(
+ egui::TextEdit::singleline(&mut editable)
+ .desired_width(120.0),
+ )
+ .changed()
+ {
+ rename = Some((i, editable));
+ }
if ui
.link(egui::RichText::new(format!("{va:#x}")).monospace())
.clicked()
@@ -4155,16 +5461,56 @@ impl GhidrustApp {
}
ui.monospace(format!("{:#x}", va.saturating_add(*size)));
ui.monospace(format!("{size:#x}"));
- ui.monospace(if *r { "R" } else { "-" });
- ui.monospace(if *w { "W" } else { "-" });
- ui.monospace(if *x { "X" } else { "-" });
+ let mut rb = *r;
+ let mut wb = *w;
+ let mut xb = *x;
+ if ui.checkbox(&mut rb, "").changed() {
+ toggle = Some((i, 'R'));
+ }
+ if ui.checkbox(&mut wb, "").changed() {
+ toggle = Some((i, 'W'));
+ }
+ if ui.checkbox(&mut xb, "").changed() {
+ toggle = Some((i, 'X'));
+ }
+ if ui.small_button("Delete").clicked() {
+ delete = Some(i);
+ }
ui.end_row();
}
+ let _ = muted;
});
});
+
if let Some(va) = goto {
let _ = self.goto_address_str(&format!("{va:#x}"));
}
+ if let Some((i, newname)) = rename {
+ if let Some(prog) = self.program.as_mut() {
+ if let Some(b) = prog.blocks.get_mut(i) {
+ b.name = newname;
+ }
+ }
+ }
+ if let Some((i, ch)) = toggle {
+ if let Some(prog) = self.program.as_mut() {
+ if let Some(b) = prog.blocks.get_mut(i) {
+ match ch {
+ 'R' => b.readable = !b.readable,
+ 'W' => b.writable = !b.writable,
+ 'X' => b.executable = !b.executable,
+ _ => {}
+ }
+ }
+ }
+ }
+ if let Some(i) = delete {
+ if let Some(prog) = self.program.as_mut() {
+ if i < prog.blocks.len() {
+ prog.blocks.remove(i);
+ }
+ }
+ }
}
fn ui_functions_window(&mut self, ui: &mut egui::Ui, muted: Color32, primary: Color32) {
@@ -4238,7 +5584,10 @@ impl GhidrustApp {
fn ui_symbol_table(&mut self, ui: &mut egui::Ui, muted: Color32) {
ui.heading("Symbol Table");
ui.small(
- egui::RichText::new("Ghidra SymbolTablePlugin · symbols + function entries").color(muted),
+ egui::RichText::new(
+ "Ghidra SymbolTablePlugin · symbols + function entries · Refs → opens Symbol References",
+ )
+ .color(muted),
);
ui.separator();
let Some(prog) = self.program.as_ref() else {
@@ -4266,19 +5615,21 @@ impl GhidrustApp {
rows.sort_by_key(|r| r.0);
ui.small(format!("{} rows", rows.len()));
+ let mut goto: Option<u64> = None;
+ let mut show_refs: Option<u64> = None;
egui::ScrollArea::vertical()
.id_salt("symtable_scroll")
.max_height(400.0)
.show(ui, |ui| {
egui::Grid::new("symbol_table_grid")
- .num_columns(3)
+ .num_columns(4)
.striped(true)
.show(ui, |ui| {
ui.strong("Address");
ui.strong("Name");
ui.strong("Type");
+ ui.strong("Refs");
ui.end_row();
- let mut goto: Option<u64> = None;
for (va, name, ty) in &rows {
if ui
.link(egui::RichText::new(format!("{va:#x}")).monospace())
@@ -4288,13 +5639,20 @@ impl GhidrustApp {
}
ui.label(name);
ui.monospace(*ty);
+ if ui.small_button("Refs").on_hover_text("Open Symbol References for this VA").clicked() {
+ show_refs = Some(*va);
+ }
ui.end_row();
}
- if let Some(va) = goto {
- let _ = self.goto_address_str(&format!("{va:#x}"));
- }
});
});
+ if let Some(va) = goto {
+ let _ = self.goto_address_str(&format!("{va:#x}"));
+ }
+ if let Some(va) = show_refs {
+ self.symbol_refs_target = Some(va);
+ self.pane_open.insert(PaneKind::SymbolReferences, true);
+ }
}
fn ui_defined_strings(&mut self, ui: &mut egui::Ui, muted: Color32) {
@@ -4626,6 +5984,721 @@ impl GhidrustApp {
let _ = self.goto_address_str(&format!("{va:#x}"));
}
}
+
+ // ── Phase D (M4) — Byte Viewer / Symbol References / Equates / Tags ─
+
+ /// Ghidra `ByteViewerPlugin` parity — split hex / ASCII view of the
+ /// program's memory around the current cursor. Bytes-per-line combo,
+ /// programmable offset override, and click-to-navigate address column.
+ fn ui_bytes_pane(&mut self, ui: &mut egui::Ui, muted: Color32, primary: Color32) {
+ ui.heading("Bytes");
+ ui.small(
+ egui::RichText::new(
+ "Ghidra ByteViewerPlugin · split hex / ASCII, follows Listing cursor",
+ )
+ .color(muted),
+ );
+ ui.separator();
+ let Some(prog) = self.program.as_ref() else {
+ ui.weak("No program loaded.");
+ return;
+ };
+ // Cursor tracking — default to Listing focus, editable via combo.
+ if self.bytes_pane_va.is_none() {
+ self.bytes_pane_va = self.listing_focus_va.or(prog.entry).or_else(|| {
+ prog.blocks.first().map(|b| b.va)
+ });
+ }
+ let base_va = self.bytes_pane_va.unwrap_or(prog.image_base);
+ ui.horizontal(|ui| {
+ ui.label("VA:");
+ let mut input = format!("{base_va:#x}");
+ let resp = ui.add(egui::TextEdit::singleline(&mut input).desired_width(140.0));
+ if resp.lost_focus() {
+ if let Ok(v) = parse_address(&input) {
+ self.bytes_pane_va = Some(v);
+ }
+ }
+ ui.label("Bytes/line:");
+ egui::ComboBox::from_id_salt("bytes_pane_bpr")
+ .selected_text(format!("{}", self.bytes_pane_bpr))
+ .show_ui(ui, |ui| {
+ for w in [8usize, 12, 16, 24, 32] {
+ ui.selectable_value(&mut self.bytes_pane_bpr, w, format!("{w}"));
+ }
+ });
+ ui.label("Rows:");
+ egui::ComboBox::from_id_salt("bytes_pane_rows")
+ .selected_text(format!("{}", self.bytes_pane_rows))
+ .show_ui(ui, |ui| {
+ for r in [8usize, 16, 24, 32, 48, 64] {
+ ui.selectable_value(&mut self.bytes_pane_rows, r, format!("{r}"));
+ }
+ });
+ if ui.button("Follow cursor").on_hover_text("Snap to Listing cursor").clicked() {
+ self.bytes_pane_va = self.listing_focus_va;
+ }
+ });
+ ui.separator();
+ let bpr = self.bytes_pane_bpr.max(1);
+ let total = bpr.saturating_mul(self.bytes_pane_rows);
+ let mut bytes: Vec<Option<u8>> = Vec::with_capacity(total);
+ for i in 0..total {
+ bytes.push(prog.byte_at(base_va.wrapping_add(i as u64)));
+ }
+ let focus_va = self.listing_focus_va;
+ let mut nav: Option<u64> = None;
+ egui::ScrollArea::vertical()
+ .id_salt("bytes_scroll")
+ .max_height(420.0)
+ .show(ui, |ui| {
+ for row in 0..self.bytes_pane_rows {
+ let row_va = base_va.wrapping_add((row * bpr) as u64);
+ ui.horizontal(|ui| {
+ let addr = egui::RichText::new(format!("{row_va:016x}"))
+ .monospace()
+ .color(if Some(row_va) == focus_va { primary } else { ui.visuals().text_color() });
+ if ui.link(addr).on_hover_text("Go To in Listing").clicked() {
+ nav = Some(row_va);
+ }
+ ui.label("│");
+ let mut hex_line = String::new();
+ let mut ascii_line = String::new();
+ for col in 0..bpr {
+ let idx = row * bpr + col;
+ match bytes.get(idx).and_then(|b| *b) {
+ Some(b) => {
+ hex_line.push_str(&format!("{b:02x} "));
+ let c = if (0x20..0x7f).contains(&b) { b as char } else { '.' };
+ ascii_line.push(c);
+ }
+ None => {
+ hex_line.push_str("?? ");
+ ascii_line.push(' ');
+ }
+ }
+ }
+ ui.monospace(hex_line.trim_end());
+ ui.label("│");
+ ui.monospace(ascii_line);
+ });
+ }
+ });
+ if let Some(va) = nav {
+ let _ = self.goto_address_str(&format!("{va:#x}"));
+ }
+ }
+
+ /// Ghidra `Symbol References` provider — a table of every xref pointing
+ /// at the currently selected symbol (or the cursor VA).
+ fn ui_symbol_references(&mut self, ui: &mut egui::Ui, muted: Color32) {
+ ui.heading("Symbol References");
+ ui.small(
+ egui::RichText::new(
+ "Ghidra SymbolTablePlugin · every reference TO the current symbol",
+ )
+ .color(muted),
+ );
+ ui.separator();
+ let Some(prog) = self.program.as_ref() else {
+ ui.weak("No program loaded.");
+ return;
+ };
+ let target = self
+ .symbol_refs_target
+ .or(self.listing_focus_va)
+ .or(prog.entry);
+ ui.horizontal(|ui| {
+ let mut input = target.map(|v| format!("{v:#x}")).unwrap_or_default();
+ ui.label("Target:");
+ let resp = ui.add(
+ egui::TextEdit::singleline(&mut input)
+ .desired_width(140.0)
+ .hint_text("VA…"),
+ );
+ if resp.lost_focus() {
+ self.symbol_refs_target = parse_address(&input).ok();
+ }
+ ui.label("Filter:");
+ ui.add(
+ egui::TextEdit::singleline(&mut self.symbol_refs_filter)
+ .desired_width(200.0)
+ .hint_text("Substring…"),
+ );
+ if ui.button("Use cursor").clicked() {
+ self.symbol_refs_target = self.listing_focus_va;
+ }
+ });
+ ui.separator();
+ let Some(target) = target else {
+ ui.weak("No target — set cursor or type a VA above.");
+ return;
+ };
+ let refs = self.xrefs_to_va(target);
+ let q = self.symbol_refs_filter.to_ascii_lowercase();
+ let rows: Vec<XRef> = refs
+ .into_iter()
+ .filter(|r| {
+ if q.is_empty() {
+ return true;
+ }
+ r.preview.to_ascii_lowercase().contains(&q)
+ || format!("{:#x}", r.from).contains(&q)
+ || r.kind.contains(&q)
+ })
+ .collect();
+ let label_at = |va: u64| {
+ self.program
+ .as_ref()
+ .and_then(|p| p.display_name_at(va))
+ .map(|s| s.to_string())
+ .unwrap_or_default()
+ };
+ ui.small(format!("{} reference(s) to {target:#x} · {}", rows.len(), label_at(target)));
+ let mut goto: Option<u64> = None;
+ egui::ScrollArea::vertical()
+ .id_salt("symrefs_scroll")
+ .max_height(400.0)
+ .show(ui, |ui| {
+ egui::Grid::new("symbol_refs_grid")
+ .num_columns(4)
+ .striped(true)
+ .show(ui, |ui| {
+ ui.strong("From");
+ ui.strong("Label");
+ ui.strong("Kind");
+ ui.strong("Preview");
+ ui.end_row();
+ for r in &rows {
+ if ui
+ .link(egui::RichText::new(format!("{:#x}", r.from)).monospace())
+ .clicked()
+ {
+ goto = Some(r.from);
+ }
+ ui.label(label_at(r.from));
+ ui.monospace(r.kind);
+ ui.label(&r.preview);
+ ui.end_row();
+ }
+ });
+ });
+ if let Some(va) = goto {
+ let _ = self.goto_address_str(&format!("{va:#x}"));
+ }
+ }
+
+ /// Ghidra `EquateTablePlugin` — two-pane: equate groups + per-equate refs.
+ fn ui_equates_table(&mut self, ui: &mut egui::Ui, muted: Color32) {
+ ui.heading("Equates Table");
+ ui.small(
+ egui::RichText::new(
+ "Ghidra EquateTablePlugin · symbolic names bound to scalar operands",
+ )
+ .color(muted),
+ );
+ ui.separator();
+ let Some(prog) = self.program.as_ref() else {
+ ui.weak("No program loaded.");
+ return;
+ };
+ let groups = prog.edits.equate_groups();
+ ui.horizontal(|ui| {
+ ui.label("Filter:");
+ ui.add(
+ egui::TextEdit::singleline(&mut self.equates_filter)
+ .desired_width(220.0)
+ .hint_text("Name / value…"),
+ );
+ if ui.button("Add equate at cursor…").clicked() {
+ self.equate_dialog_va = self.listing_focus_va;
+ self.equate_dialog_op = 1;
+ self.equate_dialog_name.clear();
+ self.equate_dialog_value.clear();
+ self.show_equate_dialog = true;
+ }
+ });
+ ui.separator();
+ let q = self.equates_filter.to_ascii_lowercase();
+ let filtered: Vec<(String, i64, usize)> = groups
+ .into_iter()
+ .filter(|(name, val, _)| {
+ if q.is_empty() {
+ return true;
+ }
+ name.to_ascii_lowercase().contains(&q) || format!("{val:#x}").contains(&q)
+ })
+ .collect();
+ if filtered.is_empty() {
+ ui.weak("No equates — use \"Add equate at cursor\" over a scalar operand.");
+ return;
+ }
+ let mut clear: Option<(u64, u8)> = None;
+ let mut goto: Option<u64> = None;
+ ui.columns(2, |cols| {
+ cols[0].strong("Equate");
+ cols[0].separator();
+ egui::ScrollArea::vertical()
+ .id_salt("equates_left_scroll")
+ .max_height(360.0)
+ .show(&mut cols[0], |ui| {
+ egui::Grid::new("equates_groups_grid")
+ .num_columns(3)
+ .striped(true)
+ .show(ui, |ui| {
+ ui.strong("Name");
+ ui.strong("Value");
+ ui.strong("# Refs");
+ ui.end_row();
+ for (name, value, n) in &filtered {
+ let is_sel = self
+ .equates_selected
+ .as_ref()
+ .map(|(sn, sv)| sn == name && *sv == *value)
+ .unwrap_or(false);
+ let text = if is_sel {
+ egui::RichText::new(name).strong()
+ } else {
+ egui::RichText::new(name)
+ };
+ if ui.selectable_label(is_sel, text).clicked() {
+ self.equates_selected = Some((name.clone(), *value));
+ }
+ ui.monospace(format!("{value:#x}"));
+ ui.monospace(format!("{n}"));
+ ui.end_row();
+ }
+ });
+ });
+ cols[1].strong("References");
+ cols[1].separator();
+ let sel = self.equates_selected.clone();
+ let refs: Vec<(u64, u8, i64)> = match sel {
+ Some((name, _)) => prog.edits.equate_references(&name),
+ None => Vec::new(),
+ };
+ egui::ScrollArea::vertical()
+ .id_salt("equates_right_scroll")
+ .max_height(360.0)
+ .show(&mut cols[1], |ui| {
+ if refs.is_empty() {
+ ui.weak("Select an equate on the left to see its references.");
+ } else {
+ egui::Grid::new("equate_refs_grid")
+ .num_columns(4)
+ .striped(true)
+ .show(ui, |ui| {
+ ui.strong("Ref Addr");
+ ui.strong("Op");
+ ui.strong("Value");
+ ui.strong("Del");
+ ui.end_row();
+ for (va, op, value) in refs {
+ if ui
+ .link(egui::RichText::new(format!("{va:#x}")).monospace())
+ .clicked()
+ {
+ goto = Some(va);
+ }
+ ui.monospace(format!("{op}"));
+ ui.monospace(format!("{value:#x}"));
+ if ui.small_button("Del").clicked() {
+ clear = Some((va, op));
+ }
+ ui.end_row();
+ }
+ });
+ }
+ });
+ });
+ if let Some(va) = goto {
+ let _ = self.goto_address_str(&format!("{va:#x}"));
+ }
+ if let Some((va, op)) = clear {
+ let _ = self.set_equate(va, op, "", 0);
+ }
+ }
+
+ /// Ghidra `FunctionTagPlugin` — two-pane: assigned tags for current fn,
+ /// All Tags with counts.
+ fn ui_function_tags(&mut self, ui: &mut egui::Ui, muted: Color32) {
+ ui.heading("Function Tags");
+ ui.small(
+ egui::RichText::new(
+ "Ghidra FunctionTagPlugin · per-function labels + universe of tags",
+ )
+ .color(muted),
+ );
+ ui.separator();
+ let Some(prog) = self.program.as_ref() else {
+ ui.weak("No program loaded.");
+ return;
+ };
+ let entry = self.focused_function_entry.or_else(|| {
+ self.listing_focus_va
+ .and_then(|va| Some(decompile_entry_for_va(prog, va)))
+ });
+ let entry_label = entry
+ .and_then(|va| self.program.as_ref()?.display_function_name_at(va))
+ .unwrap_or_else(|| "<no function>".into());
+ ui.horizontal(|ui| {
+ ui.label("Function:");
+ ui.monospace(&entry_label);
+ if let Some(e) = entry {
+ ui.monospace(format!("@ {e:#x}"));
+ }
+ });
+ ui.separator();
+ // Left = assigned tags (with remove); right = all tags (add / delete).
+ let assigned: Vec<String> = entry
+ .map(|e| prog.edits.function_tags_for(e))
+ .unwrap_or_default();
+ let all_tags: Vec<(String, usize)> = prog.edits.all_tag_counts();
+ let mut remove_from_entry: Option<String> = None;
+ let mut add_to_entry: Option<String> = None;
+ let mut delete_globally: Option<String> = None;
+ ui.columns(2, |cols| {
+ cols[0].strong("Assigned to this function");
+ cols[0].separator();
+ if assigned.is_empty() {
+ cols[0].weak("No tags — add one from the right pane, or type a new tag.");
+ } else {
+ for t in &assigned {
+ cols[0].horizontal(|ui| {
+ ui.monospace(t);
+ if ui.small_button("Remove").clicked() {
+ remove_from_entry = Some(t.clone());
+ }
+ });
+ }
+ }
+
+ cols[1].strong("All Tags");
+ cols[1].separator();
+ cols[1].horizontal(|ui| {
+ ui.label("New:");
+ ui.add(
+ egui::TextEdit::singleline(&mut self.function_tags_new_input)
+ .desired_width(160.0)
+ .hint_text("Tag name…"),
+ );
+ if ui.button("Add").clicked() {
+ let name = self.function_tags_new_input.trim().to_string();
+ if !name.is_empty() {
+ if entry.is_some() {
+ add_to_entry = Some(name);
+ } else {
+ let _ = self.create_tag(name);
+ }
+ self.function_tags_new_input.clear();
+ }
+ }
+ });
+ cols[1].horizontal(|ui| {
+ ui.label("Filter:");
+ ui.add(
+ egui::TextEdit::singleline(&mut self.function_tags_filter)
+ .desired_width(180.0)
+ .hint_text("Substring…"),
+ );
+ });
+ cols[1].separator();
+ let q = self.function_tags_filter.to_ascii_lowercase();
+ egui::ScrollArea::vertical()
+ .id_salt("all_tags_scroll")
+ .max_height(320.0)
+ .show(&mut cols[1], |ui| {
+ egui::Grid::new("all_tags_grid")
+ .num_columns(3)
+ .striped(true)
+ .show(ui, |ui| {
+ ui.strong("Tag");
+ ui.strong("Uses");
+ ui.strong("Actions");
+ ui.end_row();
+ for (tag, n) in &all_tags {
+ if !q.is_empty() && !tag.to_ascii_lowercase().contains(&q) {
+ continue;
+ }
+ ui.monospace(tag);
+ ui.monospace(format!("{n}"));
+ ui.horizontal(|ui| {
+ if entry.is_some() && ui.small_button("Add").clicked() {
+ add_to_entry = Some(tag.clone());
+ }
+ if ui.small_button("Delete").clicked() {
+ delete_globally = Some(tag.clone());
+ }
+ });
+ ui.end_row();
+ }
+ });
+ });
+ });
+ if let (Some(tag), Some(e)) = (remove_from_entry, entry) {
+ let _ = self.remove_function_tag(e, &tag);
+ }
+ if let (Some(tag), Some(e)) = (add_to_entry, entry) {
+ let _ = self.add_function_tag(e, tag);
+ }
+ if let Some(tag) = delete_globally {
+ let _ = self.delete_tag_everywhere(&tag);
+ }
+ }
+
+ /// Ghidra `ReferencesPlugin` — External Programs table. Rendered from
+ /// analyzer-driven `imports_exports()` output (PDB symbols, `idata`
+ /// sections, demangled `dllexport` symbols) — never fabricated.
+ fn ui_external_programs(&mut self, ui: &mut egui::Ui, muted: Color32) {
+ ui.heading("External Programs");
+ ui.small(
+ egui::RichText::new(
+ "Ghidra ReferencesPlugin · analyzer-derived imports + exports",
+ )
+ .color(muted),
+ );
+ ui.separator();
+ if self.program.is_none() {
+ ui.weak("No program loaded.");
+ return;
+ }
+ let (imports, exports) = self.imports_exports();
+ ui.horizontal(|ui| {
+ ui.label("Filter:");
+ ui.add(
+ egui::TextEdit::singleline(&mut self.external_programs_filter)
+ .desired_width(220.0)
+ .hint_text("Name / VA…"),
+ );
+ });
+ ui.separator();
+ let q = self.external_programs_filter.to_ascii_lowercase();
+ let matches = |name: &str, va: u64| {
+ if q.is_empty() {
+ return true;
+ }
+ name.to_ascii_lowercase().contains(&q) || format!("{va:#x}").contains(&q)
+ };
+ let mut goto: Option<u64> = None;
+ egui::ScrollArea::vertical()
+ .id_salt("ext_progs_scroll")
+ .max_height(400.0)
+ .show(ui, |ui| {
+ ui.strong("Imports");
+ egui::Grid::new("ext_imports_grid")
+ .num_columns(3)
+ .striped(true)
+ .show(ui, |ui| {
+ ui.strong("Address");
+ ui.strong("Name");
+ ui.strong("Source");
+ ui.end_row();
+ for (va, name) in imports.iter().filter(|(va, n)| matches(n, *va)) {
+ if ui
+ .link(egui::RichText::new(format!("{va:#x}")).monospace())
+ .clicked()
+ {
+ goto = Some(*va);
+ }
+ ui.label(name);
+ ui.monospace(if name.starts_with('.') { "section" } else { "pdb" });
+ ui.end_row();
+ }
+ });
+ ui.add_space(8.0);
+ ui.strong("Exports");
+ egui::Grid::new("ext_exports_grid")
+ .num_columns(3)
+ .striped(true)
+ .show(ui, |ui| {
+ ui.strong("Address");
+ ui.strong("Name");
+ ui.strong("Source");
+ ui.end_row();
+ for (va, name) in exports.iter().filter(|(va, n)| matches(n, *va)) {
+ if ui
+ .link(egui::RichText::new(format!("{va:#x}")).monospace())
+ .clicked()
+ {
+ goto = Some(*va);
+ }
+ ui.label(name);
+ ui.monospace(if name.starts_with('.') { "section" } else { "demangle" });
+ ui.end_row();
+ }
+ if imports.is_empty() && exports.is_empty() {
+ ui.weak("No imports/exports — analyzer did not populate any.");
+ ui.end_row();
+ }
+ });
+ });
+ if let Some(va) = goto {
+ let _ = self.goto_address_str(&format!("{va:#x}"));
+ }
+ }
+
+ /// Ghidra `DataTypePreviewPlugin` — preview interpretation of bytes at
+ /// the current cursor under the chosen built-in type.
+ fn ui_data_type_preview(&mut self, ui: &mut egui::Ui, muted: Color32) {
+ ui.heading("Data Type Preview");
+ ui.small(
+ egui::RichText::new(
+ "Ghidra DataTypePreviewPlugin · byte interpretation @ cursor",
+ )
+ .color(muted),
+ );
+ ui.separator();
+ let Some(prog) = self.program.as_ref() else {
+ ui.weak("No program loaded.");
+ return;
+ };
+ let va = match self.listing_focus_va.or(prog.entry) {
+ Some(v) => v,
+ None => {
+ ui.weak("No cursor / entry.");
+ return;
+ }
+ };
+ ui.horizontal(|ui| {
+ ui.label("Cursor VA:");
+ ui.monospace(format!("{va:#x}"));
+ ui.label("Type:");
+ let sel = self.data_type_preview_selected.clone();
+ egui::ComboBox::from_id_salt("dtp_type_combo")
+ .selected_text(&sel)
+ .show_ui(ui, |ui| {
+ for name in BUILTIN_TYPES {
+ if ui
+ .selectable_label(sel.as_str() == *name, *name)
+ .clicked()
+ {
+ self.data_type_preview_selected = (*name).into();
+ }
+ }
+ });
+ });
+ ui.separator();
+ let bytes = prog.read_va(va, 16).unwrap_or_default();
+ let hex: String = bytes.iter().map(|b| format!("{b:02x} ")).collect();
+ ui.monospace(format!("bytes: {}", hex.trim_end()));
+ ui.separator();
+ egui::Grid::new("dtp_grid").num_columns(2).striped(true).show(ui, |ui| {
+ ui.strong("Interpretation");
+ ui.strong("Preview");
+ ui.end_row();
+ for (name, preview) in preview_all(&bytes) {
+ ui.monospace(name);
+ ui.monospace(preview);
+ ui.end_row();
+ }
+ });
+ }
+
+ /// Ghidra `ComputeChecksumsPlugin` — CRC-32 / Adler-32 / Fletcher / raw
+ /// sum panels over the loaded image or a chosen block.
+ fn ui_checksum_generator(&mut self, ui: &mut egui::Ui, muted: Color32) {
+ ui.heading("Checksum Generator");
+ ui.small(
+ egui::RichText::new(
+ "Ghidra ComputeChecksumsPlugin · CRC-32 / Adler-32 / Fletcher / sums",
+ )
+ .color(muted),
+ );
+ ui.separator();
+ let block_names: Vec<String> = self
+ .program
+ .as_ref()
+ .map(|p| p.blocks.iter().map(|b| b.name.clone()).collect())
+ .unwrap_or_default();
+ let mut run: Option<ChecksumMode> = None;
+ ui.horizontal(|ui| {
+ if ui.button("Whole image").clicked() {
+ run = Some(ChecksumMode::WholeImage);
+ }
+ ui.label(egui::RichText::new("or block:").color(muted));
+ for name in &block_names {
+ if ui.small_button(name).clicked() {
+ run = Some(ChecksumMode::Section(name.clone()));
+ }
+ }
+ });
+ if let Some(mode) = run {
+ let _ = self.compute_checksums(mode);
+ }
+ ui.separator();
+ match &self.checksum_last {
+ None => {
+ ui.weak("No checksum computed yet — click Whole image or a block above.");
+ }
+ Some(r) => {
+ egui::Grid::new("checksum_grid").num_columns(2).striped(true).show(ui, |ui| {
+ ui.strong("Target");
+ ui.label(&r.target);
+ ui.end_row();
+ ui.strong("Length");
+ ui.monospace(format!("{}", r.len));
+ ui.end_row();
+ ui.strong("CRC-32 (IEEE)");
+ ui.monospace(format!("{:#010x}", r.crc32));
+ ui.end_row();
+ ui.strong("Adler-32");
+ ui.monospace(format!("{:#010x}", r.adler32));
+ ui.end_row();
+ ui.strong("Sum-8");
+ ui.monospace(format!("{:#x}", r.sum8));
+ ui.end_row();
+ ui.strong("Sum-16");
+ ui.monospace(format!("{:#x}", r.sum16));
+ ui.end_row();
+ ui.strong("Sum-32");
+ ui.monospace(format!("{:#x}", r.sum32));
+ ui.end_row();
+ ui.strong("Fletcher-16");
+ ui.monospace(format!("{:#010x}", r.fletcher16));
+ ui.end_row();
+ ui.strong("Fletcher-32");
+ ui.monospace(format!("{:#018x}", r.fletcher32));
+ ui.end_row();
+ });
+ }
+ }
+ }
+}
+
+/// Data Type Preview — every well-known Stage-0 interpretation of `bytes`.
+fn preview_all(bytes: &[u8]) -> Vec<(&'static str, String)> {
+ let mut out = Vec::new();
+ if let Some(&b) = bytes.first() {
+ out.push(("int8", format!("{}", b as i8)));
+ out.push(("uint8", format!("{}", b)));
+ }
+ if bytes.len() >= 2 {
+ let w = u16::from_le_bytes([bytes[0], bytes[1]]);
+ out.push(("int16", format!("{}", w as i16)));
+ out.push(("uint16", format!("{w} ({w:#x})")));
+ }
+ if bytes.len() >= 4 {
+ let d = u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]);
+ out.push(("int32", format!("{}", d as i32)));
+ out.push(("uint32", format!("{d} ({d:#x})")));
+ out.push(("float", format!("{}", f32::from_bits(d))));
+ }
+ if bytes.len() >= 8 {
+ let q = u64::from_le_bytes([
+ bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7],
+ ]);
+ out.push(("int64", format!("{}", q as i64)));
+ out.push(("uint64", format!("{q} ({q:#x})")));
+ out.push(("double", format!("{}", f64::from_bits(q))));
+ out.push(("pointer64", format!("{q:#018x}")));
+ }
+ let ascii: String = bytes
+ .iter()
+ .take(16)
+ .map(|b| if (0x20..0x7f).contains(b) { *b as char } else { '.' })
+ .collect();
+ out.push(("ascii", ascii));
+ out
}
impl eframe::App for GhidrustApp {
@@ -4641,7 +6714,7 @@ impl eframe::App for GhidrustApp {
return;
}
- // Step analysis one analyzer per frame so M3 progress can paint.
+ // Poll background analysis worker; keep repainting so progress UI stays live.
if self.analysis_job.is_some() {
if let Err(e) = self.step_analysis_job() {
self.status = format!("error: {e}");
@@ -4864,16 +6937,22 @@ impl eframe::App for GhidrustApp {
self.pane_open.insert(PaneKind::DefinedStrings, true);
ui.close_menu();
}
- if ui.button("For Scalars…").on_hover_text("Not yet implemented — Phase D").clicked() {
- self.nyi("Search → For Scalars");
+ if ui.button("For Scalars…").on_hover_text("Ghidra ScalarSearchPlugin · operand scalar range filter").clicked() {
+ self.show_search_scalars_dialog = true;
ui.close_menu();
}
- if ui.button("For Address Tables…").on_hover_text("Not yet implemented — Phase D").clicked() {
- self.nyi("Search → For Address Tables");
+ if ui.button("For Address Tables…").on_hover_text("Ghidra AutoTableDisassemblerPlugin · pointer table candidates").clicked() {
+ self.show_search_address_tables_dialog = true;
+ // Populate immediately from analyzer output.
+ if let Some(prog) = self.program.as_ref() {
+ self.text_hits = address_table_hits(prog);
+ self.memory_hits.clear();
+ self.show_search_results = true;
+ }
ui.close_menu();
}
- if ui.button("Instruction Patterns…").on_hover_text("Not yet implemented — Phase D").clicked() {
- self.nyi("Search → Instruction Patterns");
+ if ui.button("Instruction Patterns…").on_hover_text("Ghidra BytePatternPlugin · mnemonic + operand filter").clicked() {
+ self.show_search_insn_dialog = true;
ui.close_menu();
}
if ui.button("For Direct References…").on_hover_text("Not yet implemented — Phase D").clicked() {
@@ -5047,6 +7126,69 @@ impl eframe::App for GhidrustApp {
self.toggle_pane(k, open);
}
}
+ ui.separator();
+ // Phase G (M7) — Debugger tool providers.
+ ui.label(egui::RichText::new("Debugger tool").small().weak());
+ let mut dbg = DebuggerPane::ALL.to_vec();
+ dbg.sort_by_key(|p| p.title());
+ for p in dbg {
+ let mut open = *self.debugger_open.get(&p).unwrap_or(&false);
+ if ui.checkbox(&mut open, p.title()).changed() {
+ self.debugger_open.insert(p, open);
+ }
+ }
+ ui.separator();
+ // Phase H (M8) — layout tools.
+ if ui.button("Configure plugins…").clicked() {
+ self.show_configure_dialog = true;
+ ui.close_menu();
+ }
+ if ui.button("Save Tool Layout…").clicked() {
+ self.layouts_cached = layouts::list_layouts();
+ self.layouts_new_name = self.current_layout_name.clone();
+ self.show_layouts_dialog = true;
+ ui.close_menu();
+ }
+ });
+ ui.menu_button("Debugger", |ui| {
+ for act in DebuggerAction::ALL {
+ if ui
+ .button(act.label())
+ .on_hover_text("Debugger backend pending (Phase P12)")
+ .clicked()
+ {
+ match act {
+ DebuggerAction::ShowWatches => {
+ self.debugger_open.insert(DebuggerPane::Watches, true);
+ }
+ DebuggerAction::ToggleBreakpoint => {
+ if let Some(va) = self.listing_focus_va {
+ self.debugger.toggle_breakpoint(va);
+ self.debugger_open
+ .insert(DebuggerPane::Breakpoints, true);
+ }
+ self.nyi(&format!("Debugger → {}", act.label()));
+ }
+ _ => self.nyi(&format!("Debugger → {}", act.label())),
+ }
+ ui.close_menu();
+ }
+ }
+ ui.separator();
+ ui.checkbox(&mut self.debugger.enabled, "Debugger tool mode");
+ if self.debugger.enabled {
+ // Enabling the tool opens the core debugger providers.
+ for p in [
+ DebuggerPane::Targets,
+ DebuggerPane::Threads,
+ DebuggerPane::Modules,
+ DebuggerPane::Registers,
+ DebuggerPane::Stack,
+ DebuggerPane::Breakpoints,
+ ] {
+ self.debugger_open.insert(p, true);
+ }
+ }
});
ui.menu_button("Help", |ui| {
if ui.button("Contents (F1)").on_hover_text("Not yet implemented — Phase A").clicked() {
@@ -6199,17 +8341,169 @@ impl eframe::App for GhidrustApp {
CenterPane::Decompiler => {
self.ui_decompiler_pane(ui);
}
- CenterPane::DataTypes => {
- self.ui_dtm_pane(ui);
+ CenterPane::DataTypes => {
+ self.ui_dtm_pane(ui);
+ }
+ }
+ });
+
+ // Phase A (M1) — draw every open floating provider pane.
+ self.draw_provider_panes(ctx);
+
+ // Phase C (M3) — edit dialogs (rename / retype / comment / signature / new type).
+ self.draw_edit_dialogs(ctx);
+
+ // Phase H (M8) — Configure plugins dialog.
+ if self.show_configure_dialog {
+ let mut close = false;
+ egui::Window::new("Configure plugins")
+ .id(egui::Id::new("dialog_configure"))
+ .resizable(true)
+ .default_size(egui::vec2(680.0, 460.0))
+ .show(ctx, |ui| {
+ ui.label(
+ "Ghidrust plugins are compile-time; this dialog is a Ghidra parity list of every provider Ghidrust ships.",
+ );
+ ui.separator();
+ egui::ScrollArea::vertical()
+ .id_salt("configure_scroll")
+ .max_height(340.0)
+ .show(ui, |ui| {
+ egui::Grid::new("configure_grid")
+ .num_columns(4)
+ .striped(true)
+ .show(ui, |ui| {
+ ui.strong("Plugin");
+ ui.strong("Kind");
+ ui.strong("State");
+ ui.strong("Description");
+ ui.end_row();
+ for p in layouts::PLUGIN_CATALOG {
+ ui.monospace(p.name);
+ ui.label(p.kind);
+ ui.label(p.state);
+ ui.label(p.description);
+ ui.end_row();
+ }
+ });
+ });
+ ui.separator();
+ if ui.button("Close").clicked() {
+ close = true;
+ }
+ });
+ if close {
+ self.show_configure_dialog = false;
+ }
+ }
+
+ // Phase H (M8) — Layout save / load dialog.
+ if self.show_layouts_dialog {
+ let mut close = false;
+ let mut do_save = false;
+ let mut load_name: Option<String> = None;
+ let mut delete_name: Option<String> = None;
+ egui::Window::new("Tool Layouts")
+ .id(egui::Id::new("dialog_layouts"))
+ .resizable(true)
+ .default_size(egui::vec2(480.0, 360.0))
+ .show(ctx, |ui| {
+ ui.label("Save / restore CodeBrowser tool layouts (pane visibility + docks).");
+ ui.small(
+ egui::RichText::new(
+ "Files land under %APPDATA%/ghidrust/layouts/<name>.tool.json (Ghidra .tool XML analog).",
+ )
+ .weak(),
+ );
+ ui.separator();
+ ui.horizontal(|ui| {
+ ui.label("Name:");
+ ui.add(
+ egui::TextEdit::singleline(&mut self.layouts_new_name)
+ .desired_width(200.0)
+ .hint_text("MyCodeBrowser"),
+ );
+ if ui
+ .add_enabled(
+ !self.layouts_new_name.trim().is_empty(),
+ egui::Button::new("Save current layout"),
+ )
+ .clicked()
+ {
+ do_save = true;
+ }
+ });
+ ui.separator();
+ ui.label(egui::RichText::new("Saved layouts").strong());
+ if self.layouts_cached.is_empty() {
+ ui.weak("No layouts saved yet.");
+ } else {
+ egui::ScrollArea::vertical()
+ .id_salt("layouts_scroll")
+ .max_height(180.0)
+ .show(ui, |ui| {
+ for name in &self.layouts_cached {
+ ui.horizontal(|ui| {
+ ui.monospace(name);
+ if ui.small_button("Restore").clicked() {
+ load_name = Some(name.clone());
+ }
+ if ui.small_button("Delete").clicked() {
+ delete_name = Some(name.clone());
+ }
+ });
+ }
+ });
+ }
+ ui.separator();
+ if !self.current_layout_name.is_empty() {
+ ui.small(
+ egui::RichText::new(format!(
+ "Current layout: {}",
+ self.current_layout_name
+ ))
+ .weak(),
+ );
+ }
+ if ui.button("Close").clicked() {
+ close = true;
+ }
+ });
+ if do_save {
+ match self.save_layout_named(self.layouts_new_name.clone()) {
+ Ok(p) => {
+ self.status = format!("Layout saved → {}", p.display());
+ self.log(self.status.clone());
+ }
+ Err(e) => {
+ self.status = format!("save layout error: {e}");
+ self.log_error(self.status.clone());
+ }
+ }
+ }
+ if let Some(name) = load_name {
+ match self.restore_layout_named(&name) {
+ Ok(()) => {
+ self.status = format!("Layout restored → {name}");
+ self.log(self.status.clone());
+ }
+ Err(e) => {
+ self.status = format!("restore layout error: {e}");
+ self.log_error(self.status.clone());
+ }
+ }
+ }
+ if let Some(name) = delete_name {
+ if let Err(e) = layouts::delete_layout(&name) {
+ self.status = format!("delete layout error: {e}");
+ self.log_error(self.status.clone());
}
+ self.layouts_cached = layouts::list_layouts();
}
- });
-
- // Phase A (M1) — draw every open floating provider pane.
- self.draw_provider_panes(ctx);
-
- // Phase C (M3) — edit dialogs (rename / retype / comment / signature / new type).
- self.draw_edit_dialogs(ctx);
+ if close {
+ self.show_layouts_dialog = false;
+ }
+ }
// Bookmark add dialog
if self.show_bookmark_dialog {
@@ -6338,6 +8632,138 @@ impl eframe::App for GhidrustApp {
});
}
+ // Search → For Scalars
+ if self.show_search_scalars_dialog {
+ egui::Window::new("Search For Scalars")
+ .collapsible(false)
+ .resizable(false)
+ .anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0])
+ .show(ctx, |ui| {
+ ui.label("Scan operand scalars in [min, max]. Hex ok (0x…) or decimal.");
+ ui.horizontal(|ui| {
+ ui.label("Min:");
+ ui.text_edit_singleline(&mut self.search_scalars_min);
+ });
+ ui.horizontal(|ui| {
+ ui.label("Max:");
+ ui.text_edit_singleline(&mut self.search_scalars_max);
+ });
+ ui.horizontal(|ui| {
+ if ui.button("Cancel").clicked() {
+ self.show_search_scalars_dialog = false;
+ }
+ if ui.button("Search").clicked() {
+ match self.run_search_scalars() {
+ Ok(()) => self.show_search_scalars_dialog = false,
+ Err(e) => {
+ self.status = format!("error: {e}");
+ self.log_error(self.status.clone());
+ }
+ }
+ }
+ });
+ });
+ }
+
+ // Search → Instruction Patterns
+ if self.show_search_insn_dialog {
+ egui::Window::new("Search Instruction Patterns")
+ .collapsible(false)
+ .resizable(true)
+ .default_width(420.0)
+ .anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0])
+ .show(ctx, |ui| {
+ ui.small("Matches against decoded listing rows. Empty field = don't filter.");
+ ui.horizontal(|ui| {
+ ui.label("Mnemonic:");
+ ui.text_edit_singleline(&mut self.search_insn_mnemonic);
+ });
+ ui.horizontal(|ui| {
+ ui.label("Operands:");
+ ui.text_edit_singleline(&mut self.search_insn_operands);
+ });
+ ui.horizontal(|ui| {
+ if ui.button("Cancel").clicked() {
+ self.show_search_insn_dialog = false;
+ }
+ if ui.button("Search").clicked() {
+ match self.run_search_instruction_patterns() {
+ Ok(()) => self.show_search_insn_dialog = false,
+ Err(e) => {
+ self.status = format!("error: {e}");
+ self.log_error(self.status.clone());
+ }
+ }
+ }
+ });
+ });
+ }
+
+ // Add Equate dialog (Ghidra `EquateTablePlugin` → Convert → Equate).
+ if self.show_equate_dialog {
+ let mut close = false;
+ egui::Window::new("Set Equate")
+ .collapsible(false)
+ .resizable(false)
+ .anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0])
+ .show(ctx, |ui| {
+ ui.small("Bind a name to a scalar operand (Ghidra `EquateTablePlugin`).");
+ ui.horizontal(|ui| {
+ ui.label("VA:");
+ let mut input = self
+ .equate_dialog_va
+ .map(|v| format!("{v:#x}"))
+ .unwrap_or_default();
+ if ui.text_edit_singleline(&mut input).lost_focus() {
+ self.equate_dialog_va = parse_address(&input).ok();
+ }
+ });
+ ui.horizontal(|ui| {
+ ui.label("Operand index:");
+ let mut s = format!("{}", self.equate_dialog_op);
+ if ui.text_edit_singleline(&mut s).lost_focus() {
+ self.equate_dialog_op = s.trim().parse().unwrap_or(self.equate_dialog_op);
+ }
+ });
+ ui.horizontal(|ui| {
+ ui.label("Name:");
+ ui.text_edit_singleline(&mut self.equate_dialog_name);
+ });
+ ui.horizontal(|ui| {
+ ui.label("Value (dec / hex):");
+ ui.text_edit_singleline(&mut self.equate_dialog_value);
+ });
+ ui.horizontal(|ui| {
+ if ui.button("Cancel").clicked() {
+ close = true;
+ }
+ if ui.button("Apply").clicked() {
+ let value = self
+ .parse_scalar_input(&self.equate_dialog_value.clone())
+ .unwrap_or(0);
+ if let Some(va) = self.equate_dialog_va {
+ if let Err(e) = self.set_equate(
+ va,
+ self.equate_dialog_op,
+ self.equate_dialog_name.clone(),
+ value,
+ ) {
+ self.status = format!("error: {e}");
+ self.log_error(self.status.clone());
+ } else {
+ close = true;
+ }
+ } else {
+ close = true;
+ }
+ }
+ });
+ });
+ if close {
+ self.show_equate_dialog = false;
+ }
+ }
+
// Search results window
if self.show_search_results {
egui::Window::new("Search Results")
@@ -6861,7 +9287,7 @@ mod tests {
assert!(app.analysis_job.is_some());
assert!(app.analysis_progress_fraction().is_some());
while app.analysis_job.is_some() {
- app.step_analysis_job().expect("step");
+ app.step_analysis_job_blocking().expect("step");
}
assert!(app.analysis_progress_fraction().is_none());
let tree3 = app.project_tree_model().unwrap();
@@ -6917,18 +9343,26 @@ mod tests {
#[test]
fn headless_stage0_decompiler_wires_on_focus() {
+ // Phase F: Stage-1 is the GUI default. The old assertion demanded a
+ // Stage-0-style `void foo()` / `block_N` marker; Stage-1 emits typed
+ // return values (e.g. `uint32_t FUN_...(void)`) so we accept either
+ // stage marker plus the Stage-1 self-identification header.
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.is_empty(), "load should seed decompiler 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());
+ let text = &app.decomp_text;
assert!(
- app.decomp_text.contains("void ") || app.decomp_text.contains("block_"),
- "expected Stage-0 pseudo-C:\n{}",
- app.decomp_text
+ text.contains("void ")
+ || text.contains("uint")
+ || text.contains("int32_t")
+ || text.contains("int64_t")
+ || text.contains("block_"),
+ "expected typed function header or block label:\n{text}"
);
let entry = app.decomp_entry.unwrap();
@@ -7087,7 +9521,10 @@ mod tests {
!app.decomp_lines.is_empty(),
"token cache must be populated after refresh_decompiler_at"
);
- // Stage-0 always emits a `void <name>` declaration + `block_N:` labels.
+ // Post Phase F the default GUI stage is Stage-1; the emitter drops
+ // `block_N:` labels in favour of structured regions. Assert only
+ // that we see at least one keyword token — the shape common to
+ // every stage.
let all_tokens: Vec<&TokenKind> = app
.decomp_lines
.iter()
@@ -7097,13 +9534,9 @@ mod tests {
all_tokens.iter().any(|k| matches!(k, TokenKind::Keyword)),
"expected at least one Keyword (void/return/etc)"
);
- assert!(
- all_tokens.iter().any(|k| matches!(k, TokenKind::Label)),
- "expected at least one block_N label"
- );
// Cross-highlight line should be recomputable and match what the
- // decoder found for the entry VA (may be None if Stage-0 emit stripped
- // per-line addresses, but the field remains consistent).
+ // decoder found for the entry VA (may be None if Stage-1 emit
+ // stripped per-line addresses, but the field remains consistent).
let ln = decomp_line_for_va(&app.decomp_lines, entry);
assert_eq!(app.decomp_cross_line, ln);
}
@@ -7559,4 +9992,398 @@ mod tests {
app.listing[0].address
);
}
+
+ // ─── Phase D (M4) — tables, xrefs, equates, tags, search dialogs ────
+
+ #[test]
+ fn xrefs_to_and_from_return_honest_rows_on_fixture() {
+ let mut app = GhidrustApp::headless();
+ app.load_binary(&fixture_path("analysis_lab.pe")).expect("load");
+ // xrefs_from at entry decodes and never fabricates.
+ let entry = app.program.as_ref().and_then(|p| p.entry).unwrap();
+ let from = app.xrefs_from_va(entry);
+ for r in &from {
+ assert!(app.program.as_ref().unwrap().contains_va(r.to));
+ assert!(r.from >= entry);
+ }
+
+ // Inject a fake reference so xrefs_to_va picks it up deterministically.
+ {
+ let prog = app.program.as_mut().unwrap();
+ prog.analysis.references.push(ghidrust_core::ReferenceInfo {
+ from: prog.image_base + 0x100,
+ to: entry,
+ kind: "call".into(),
+ });
+ }
+ let to = app.xrefs_to_va(entry);
+ assert!(to.iter().any(|r| r.kind == "call"));
+ assert!(to.iter().all(|r| r.to == entry));
+ }
+
+ #[test]
+ fn set_equate_and_edit_events_fan_out() {
+ let mut app = GhidrustApp::headless();
+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
+ let va = app.program.as_ref().and_then(|p| p.entry).unwrap();
+ app.set_equate(va, 1, "SW_HIDE", 0).expect("set equate");
+ let p = app.program.as_ref().unwrap();
+ assert_eq!(p.edits.equate_at(va, 1).map(|e| e.name.as_str()), Some("SW_HIDE"));
+ assert_eq!(p.edits.equate_at(va, 1).map(|e| e.value), Some(0));
+ // Groups & references consistent.
+ let groups = p.edits.equate_groups();
+ assert!(groups.iter().any(|(n, _, _)| n == "SW_HIDE"));
+ // Setting empty name clears it.
+ app.set_equate(va, 1, "", 0).expect("clear");
+ assert!(app.program.as_ref().unwrap().edits.equate_at(va, 1).is_none());
+ }
+
+ #[test]
+ fn function_tags_add_remove_delete_via_app() {
+ let mut app = GhidrustApp::headless();
+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
+ let entry = app.program.as_ref().and_then(|p| p.entry).unwrap();
+ app.add_function_tag(entry, "MALLOC").expect("add");
+ app.add_function_tag(entry, "SANITIZED").expect("add");
+ let p = app.program.as_ref().unwrap();
+ assert!(p.edits.function_has_tag(entry, "MALLOC"));
+ assert!(p.edits.function_has_tag(entry, "SANITIZED"));
+ assert!(p.edits.all_function_tags.contains("MALLOC"));
+ app.remove_function_tag(entry, "MALLOC").expect("remove");
+ assert!(!app.program.as_ref().unwrap().edits.function_has_tag(entry, "MALLOC"));
+ // Delete-everywhere strips from universe.
+ app.delete_tag_everywhere("SANITIZED").expect("delete");
+ assert!(!app.program.as_ref().unwrap().edits.all_function_tags.contains("SANITIZED"));
+ }
+
+ #[test]
+ fn search_scalars_dialog_runs_range_over_listing() {
+ let mut app = GhidrustApp::headless();
+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
+ app.search_scalars_min = "0".into();
+ app.search_scalars_max = "0xffff".into();
+ app.run_search_scalars().expect("scalars");
+ // Fixture may or may not include a scalar in this range; the runner
+ // must still succeed and populate text_hits deterministically.
+ assert!(app.show_search_results);
+ }
+
+ #[test]
+ fn search_instruction_patterns_filters_listing() {
+ let mut app = GhidrustApp::headless();
+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
+ // tiny_x64 has a `push rbp` prologue; filter should hit it.
+ app.search_insn_mnemonic = "push".into();
+ app.search_insn_operands.clear();
+ app.run_search_instruction_patterns().expect("insn");
+ assert!(!app.text_hits.is_empty());
+ assert!(app.text_hits.iter().any(|h| h.kind == "insn"));
+ }
+
+ #[test]
+ fn address_tables_hits_appear_after_analyzer_populates() {
+ let mut app = GhidrustApp::headless();
+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
+ {
+ let prog = app.program.as_mut().unwrap();
+ prog.analysis.address_tables.push(ghidrust_core::AddressTableInfo {
+ base: prog.image_base,
+ count: 3,
+ entries: vec![prog.image_base, prog.image_base + 8, prog.image_base + 16],
+ });
+ }
+ let hits = address_table_hits(app.program.as_ref().unwrap());
+ assert_eq!(hits.len(), 1);
+ assert!(hits[0].text.contains("3 entries"));
+ }
+
+ #[test]
+ fn compute_checksums_round_trip_whole_image() {
+ let mut app = GhidrustApp::headless();
+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
+ app.compute_checksums(ChecksumMode::WholeImage).expect("checksum");
+ let r = app.checksum_last.as_ref().unwrap();
+ assert!(r.len > 0);
+ assert!(r.crc32 != 0);
+ assert!(r.adler32 != 0);
+ // Deterministic: re-running yields the same values.
+ let first = r.clone();
+ app.compute_checksums(ChecksumMode::WholeImage).expect("checksum");
+ assert_eq!(app.checksum_last.as_ref().unwrap(), &first);
+ }
+
+ #[test]
+ fn bytes_pane_state_defaults_and_follow_cursor() {
+ let mut app = GhidrustApp::headless();
+ assert_eq!(app.bytes_pane_bpr, 16);
+ assert!(app.bytes_pane_va.is_none());
+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
+ // Programmatic follow — reflects listing_focus.
+ app.listing_focus_va = app.program.as_ref().and_then(|p| p.entry);
+ app.bytes_pane_va = app.listing_focus_va;
+ assert!(app.bytes_pane_va.is_some());
+ }
+
+ #[test]
+ fn parse_scalar_input_hex_and_dec_and_signed() {
+ let app = GhidrustApp::headless();
+ assert_eq!(app.parse_scalar_input("0x1234").unwrap(), 0x1234);
+ assert_eq!(app.parse_scalar_input("42").unwrap(), 42);
+ assert_eq!(app.parse_scalar_input("-0x10").unwrap(), -0x10);
+ assert!(app.parse_scalar_input("").is_err());
+ }
+
+ // ── Phase E (M5) — Graphs & maps ─────────────────────────────────────
+
+ /// Phase E — Function Graph derives Stage-0 blocks + edges from the
+ /// currently-focused function's CFG (honest empty if the region has
+ /// no recovered blocks).
+ #[test]
+ fn function_graph_pane_layouts_stage0_cfg() {
+ let mut app = GhidrustApp::headless();
+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
+ let entry = app.program.as_ref().and_then(|p| p.entry).unwrap();
+ app.focus_function(entry);
+
+ let view = eframe::egui::Rect::from_min_size(
+ eframe::egui::Pos2::ZERO,
+ eframe::egui::Vec2::new(1000.0, 600.0),
+ );
+ let (blocks, edges) = graphs::layout_function_graph(
+ app.program.as_ref().unwrap(),
+ entry,
+ STAGE0_MAX_INSNS,
+ FunctionGraphLayout::Hierarchical,
+ view,
+ );
+ // Honest-empty is acceptable, but if blocks land they must all
+ // have positive rects.
+ for b in &blocks {
+ assert!(b.rect.width() > 0.0);
+ }
+ for e in &edges {
+ assert!(e.from < blocks.len().max(1));
+ }
+ }
+
+ /// Phase E — Function Call Graph roots at the current function with
+ /// level 0; expansion levels are session-only settings.
+ #[test]
+ fn call_graph_state_settings_persist_across_frames() {
+ let mut app = GhidrustApp::headless();
+ assert_eq!(app.graph_state.call_graph_levels_in, 0);
+ assert_eq!(app.graph_state.call_graph_levels_out, 0);
+ app.graph_state.call_graph_levels_in = 2;
+ app.graph_state.call_graph_levels_out = 1;
+ assert_eq!(app.graph_state.call_graph_levels_in, 2);
+ }
+
+ /// Phase E — Editable Memory Map: RWX toggles + add + delete flow.
+ #[test]
+ fn memory_map_edit_flow_adds_and_deletes_blocks() {
+ let mut app = GhidrustApp::headless();
+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
+ let n0 = app.program.as_ref().unwrap().blocks.len();
+ // Add a synthetic RWX block at 0x900000.
+ app.program.as_mut().unwrap().blocks.push(
+ ghidrust_core::MemoryBlock {
+ name: "synthetic".into(),
+ va: 0x900000,
+ size: 0x100,
+ bytes: vec![0u8; 0x100],
+ readable: true,
+ writable: true,
+ executable: true,
+ },
+ );
+ assert_eq!(app.program.as_ref().unwrap().blocks.len(), n0 + 1);
+ // Flip its RWX (via the field, mirrors the UI checkbox mutation).
+ let idx = app.program.as_ref().unwrap().blocks.len() - 1;
+ {
+ let b = &mut app.program.as_mut().unwrap().blocks[idx];
+ b.writable = !b.writable;
+ assert!(!b.writable);
+ }
+ app.program.as_mut().unwrap().blocks.remove(idx);
+ assert_eq!(app.program.as_ref().unwrap().blocks.len(), n0);
+ }
+
+ /// Phase E — Register Manager lattice is present and set/clear works.
+ #[test]
+ fn register_manager_lattice_and_values() {
+ let mut app = GhidrustApp::headless();
+ assert!(app.register_manager.values.is_empty());
+ app.register_manager.selected = Some("RAX".into());
+ app.register_manager
+ .values
+ .push(register_manager::RegisterValueRow {
+ register: "RAX".into(),
+ start_va: 0x1000,
+ end_va: 0x1100,
+ value: "0x2a".into(),
+ });
+ assert_eq!(app.register_manager.values.len(), 1);
+ }
+
+ /// Phase E — Entropy strip samples cover mapped bytes without fabricating.
+ #[test]
+ fn entropy_samples_cover_mapped_blocks() {
+ let mut app = GhidrustApp::headless();
+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
+ let s = entropy::entropy_samples(app.program.as_ref().unwrap(), 256);
+ assert!(!s.is_empty());
+ for w in s.windows(2) {
+ assert!(w[0].va <= w[1].va);
+ }
+ }
+
+ // ── Phase F (M6) — Scripts ───────────────────────────────────────────
+
+ #[test]
+ fn script_manager_catalog_is_populated_from_mcp_surface() {
+ let app = GhidrustApp::headless();
+ assert!(!app.script_manager.catalog.is_empty());
+ assert!(app.script_manager.catalog.iter().any(|s| s.name == "mcp.list_functions"));
+ }
+
+ #[test]
+ fn text_editor_lifecycle_open_edit_close() {
+ let mut app = GhidrustApp::headless();
+ app.text_editor.open_untitled();
+ assert_eq!(app.text_editor.tabs.len(), 1);
+ app.text_editor.tabs[0].body.push_str("body");
+ app.text_editor.tabs[0].dirty = true;
+ app.text_editor.close_active();
+ assert_eq!(app.text_editor.tabs.len(), 0);
+ }
+
+ #[test]
+ fn mcp_repl_submit_records_prompt_and_response() {
+ let mut app = GhidrustApp::headless();
+ app.mcp_repl.input = "mcp.list_functions".into();
+ app.mcp_repl.submit();
+ assert_eq!(app.mcp_repl.transcript.len(), 2);
+ assert!(app.mcp_repl.transcript[0].prompt);
+ assert!(!app.mcp_repl.transcript[1].prompt);
+ }
+
+ // ── Phase G (M7) — Debugger visibility ──────────────────────────────
+
+ #[test]
+ fn debugger_panes_enumerated_in_shell_panes() {
+ let panes = GhidrustApp::shell_panes();
+ for expected in [
+ "Debugger Targets",
+ "Debugger Threads",
+ "Debugger Modules",
+ "Debugger Regions",
+ "Debugger Registers",
+ "Debugger Stack",
+ "Debugger Breakpoints",
+ "Debugger Memory Bytes",
+ "Debugger Watches",
+ "Debugger Console",
+ ] {
+ assert!(
+ panes.contains(&expected),
+ "shell_panes() missing debugger provider `{expected}`",
+ );
+ }
+ }
+
+ #[test]
+ fn debugger_menu_is_registered_in_shell() {
+ let menus = GhidrustApp::shell_menus();
+ assert!(menus.contains(&"Debugger"));
+ }
+
+ #[test]
+ fn debugger_breakpoint_and_watch_state_persist_session_only() {
+ let mut app = GhidrustApp::headless();
+ assert!(app.debugger.breakpoints.is_empty());
+ app.debugger.toggle_breakpoint(0x1000);
+ app.debugger.toggle_breakpoint(0x2000);
+ assert_eq!(app.debugger.breakpoints.len(), 2);
+ assert!(app.debugger.has_breakpoint(0x1000));
+ app.debugger.toggle_breakpoint(0x1000);
+ assert!(!app.debugger.has_breakpoint(0x1000));
+
+ app.debugger.add_watch("rax");
+ app.debugger.add_watch("rax"); // dedup
+ app.debugger.add_watch("*(int*)rsp");
+ assert_eq!(app.debugger.watches.len(), 2);
+ }
+
+ // ── Phase H (M8) — Docking / layouts ────────────────────────────────
+
+ #[test]
+ fn save_and_restore_layout_round_trip() {
+ // Use a fresh %APPDATA%/ghidrust equivalent to keep test hermetic.
+ let dir = std::env::temp_dir().join(format!(
+ "ghidrust_layouts_{}",
+ std::process::id()
+ ));
+ let _ = std::fs::remove_dir_all(&dir);
+ // Point APPDATA at our sandbox so layouts write here.
+ let prev = std::env::var("APPDATA").ok();
+ // Only override APPDATA when it's the layout-dir resolver we care about.
+ std::env::set_var("APPDATA", &dir);
+ struct RestoreAppdata(Option<String>);
+ impl Drop for RestoreAppdata {
+ fn drop(&mut self) {
+ if let Some(p) = &self.0 {
+ std::env::set_var("APPDATA", p);
+ } else {
+ std::env::remove_var("APPDATA");
+ }
+ }
+ }
+ let _guard = RestoreAppdata(prev);
+
+ let mut app = GhidrustApp::headless();
+ // Flip a few state bits so we can prove the round-trip.
+ app.toggle_pane(PaneKind::Bookmarks, true);
+ app.toggle_pane(PaneKind::MemoryMap, true);
+ app.debugger_open.insert(DebuggerPane::Targets, true);
+ app.center = CenterPane::Decompiler;
+ app.show_console = false;
+
+ app.save_layout_named("myTest").expect("save layout");
+ // Flip everything back so restore has something to change.
+ app.toggle_pane(PaneKind::Bookmarks, false);
+ app.toggle_pane(PaneKind::MemoryMap, false);
+ app.debugger_open.insert(DebuggerPane::Targets, false);
+ app.center = CenterPane::Overview;
+ app.show_console = true;
+
+ app.restore_layout_named("myTest").expect("restore layout");
+ assert!(app.is_pane_open(PaneKind::Bookmarks));
+ assert!(app.is_pane_open(PaneKind::MemoryMap));
+ assert_eq!(app.debugger_open.get(&DebuggerPane::Targets), Some(&true));
+ assert_eq!(app.center, CenterPane::Decompiler);
+ assert!(!app.show_console);
+
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
+ #[test]
+ fn configure_dialog_state_defaults_closed() {
+ let app = GhidrustApp::headless();
+ assert!(!app.show_configure_dialog);
+ assert!(!app.show_layouts_dialog);
+ }
+
+ #[test]
+ fn phase_e_f_g_h_menu_actions_wired_not_nyi() {
+ let src = include_str!("main.rs");
+ // Phase E — graph menu items open panes (not nyi).
+ assert!(!src.contains("nyi(\"Graph → Function Graph\""));
+ assert!(!src.contains("nyi(\"Graph → Function Call Graph\""));
+ assert!(!src.contains("nyi(\"Graph → Function Call Trees\""));
+ // Phase G — Debugger menu is registered.
+ assert!(src.contains("ui.menu_button(\"Debugger\","));
+ // Phase H — Configure dialog + Save Tool Layout menu items are wired.
+ assert!(src.contains("show_configure_dialog"));
+ assert!(src.contains("show_layouts_dialog"));
+ }
}
diff --git a/crates/ghidrust-gui/src/menu_actions.rs b/crates/ghidrust-gui/src/menu_actions.rs
index 6f27c66..3a4f787 100644
--- a/crates/ghidrust-gui/src/menu_actions.rs
+++ b/crates/ghidrust-gui/src/menu_actions.rs
@@ -140,6 +140,139 @@ pub struct TextHit {
pub text: String,
}
+/// Search → For Scalars — every scalar literal that appears in an operand
+/// within `[min, max]`.
+///
+/// Ghidra `ScalarSearchPlugin` lists every scalar operand and lets the user
+/// filter by numeric range. Ghidrust's Stage-0 decoder emits scalars as either
+/// `0x...` (hex) or decimal literals inside the operand string; both are
+/// picked up here.
+pub fn search_scalars(listing: &[Instruction], min: i64, max: i64, max_hits: usize) -> Vec<TextHit> {
+ let mut hits = Vec::new();
+ if max_hits == 0 || min > max {
+ return hits;
+ }
+ for insn in listing {
+ for v in extract_scalars(&insn.operands) {
+ if v >= min && v <= max {
+ hits.push(TextHit {
+ kind: "scalar",
+ va: Some(insn.address),
+ text: format!("{} {} · {}", insn.mnemonic, insn.operands, format_scalar(v)),
+ });
+ if hits.len() >= max_hits {
+ return hits;
+ }
+ }
+ }
+ }
+ hits
+}
+
+/// Every scalar literal (hex or dec, signed or unsigned) appearing in
+/// `operands`. Returns `i64` so ranges are consistent with signed comparisons.
+pub fn extract_scalars(operands: &str) -> Vec<i64> {
+ let mut out = Vec::new();
+ let bytes = operands.as_bytes();
+ let mut i = 0;
+ while i < bytes.len() {
+ let c = bytes[i] as char;
+ // Handle negative-sign prefix, but only when it directly precedes a digit.
+ let (sign, start) = if c == '-' && i + 1 < bytes.len() && (bytes[i + 1] as char).is_ascii_digit() {
+ (-1i64, i + 1)
+ } else {
+ (1i64, i)
+ };
+ if bytes.get(start).copied() == Some(b'0')
+ && matches!(bytes.get(start + 1).copied(), Some(b'x') | Some(b'X'))
+ {
+ let s = start + 2;
+ let mut e = s;
+ while e < bytes.len() && (bytes[e] as char).is_ascii_hexdigit() {
+ e += 1;
+ }
+ if e > s {
+ if let Ok(v) = u64::from_str_radix(&operands[s..e], 16) {
+ out.push(sign * v as i64);
+ }
+ i = e;
+ continue;
+ }
+ }
+ if (bytes[start] as char).is_ascii_digit() {
+ let mut e = start;
+ while e < bytes.len() && (bytes[e] as char).is_ascii_digit() {
+ e += 1;
+ }
+ if let Ok(v) = operands[start..e].parse::<u64>() {
+ out.push(sign * v as i64);
+ i = e;
+ continue;
+ }
+ }
+ i += 1;
+ }
+ out
+}
+
+fn format_scalar(v: i64) -> String {
+ if v.abs() >= 10 {
+ format!("{v} ({v:#x})")
+ } else {
+ v.to_string()
+ }
+}
+
+/// Search → For Instruction Patterns — every listing row whose mnemonic
+/// matches `mnemonic_glob` (case-insensitive substring match) and whose
+/// operands contain `operand_substr` (empty = don't filter).
+///
+/// Ghidra `BytePatternPlugin` supports a richer bit-pattern language; the
+/// Stage-0 Ghidrust flavour uses the mnemonic + operand string that the
+/// decoder already produced so users can find e.g. every `cmp * , 0x0` or
+/// every `call ptr` without needing a full pcode search host.
+pub fn search_instruction_patterns(
+ listing: &[Instruction],
+ mnemonic_glob: &str,
+ operand_substr: &str,
+ max_hits: usize,
+) -> Vec<TextHit> {
+ if max_hits == 0 {
+ return Vec::new();
+ }
+ let mnem_q = mnemonic_glob.trim().to_ascii_lowercase();
+ let op_q = operand_substr.trim().to_ascii_lowercase();
+ let mut hits = Vec::new();
+ for insn in listing {
+ let mnem_ok = mnem_q.is_empty() || insn.mnemonic.to_ascii_lowercase().contains(&mnem_q);
+ let op_ok = op_q.is_empty() || insn.operands.to_ascii_lowercase().contains(&op_q);
+ if mnem_ok && op_ok {
+ hits.push(TextHit {
+ kind: "insn",
+ va: Some(insn.address),
+ text: format!("{} {}", insn.mnemonic, insn.operands),
+ });
+ if hits.len() >= max_hits {
+ break;
+ }
+ }
+ }
+ hits
+}
+
+/// Search → For Address Tables — every analyzer-recovered pointer table.
+pub fn address_table_hits(prog: &Program) -> Vec<TextHit> {
+ prog.analysis
+ .address_tables
+ .iter()
+ .map(|t| TextHit {
+ kind: "addr_tbl",
+ va: Some(t.base),
+ text: format!("{} entries starting {:#x}", t.count, t.base),
+ })
+ .collect()
+}
+
/// Search → Program Text: listing mnemonics + symbols + strings + section names.
pub fn search_program_text(
prog: &Program,
@@ -476,6 +609,81 @@ mod tests {
assert!(!text.contains("Not yet implemented"));
}
+ #[test]
+ fn extract_scalars_handles_hex_dec_and_negatives() {
+ assert_eq!(extract_scalars("rax, 0x1234"), vec![0x1234]);
+ assert_eq!(extract_scalars("rax, 42"), vec![42]);
+ assert_eq!(extract_scalars("rax, -0x10"), vec![-0x10]);
+ assert_eq!(extract_scalars("rax, -42"), vec![-42]);
+ // Both scalars picked up in one operand string.
+ let v = extract_scalars("mov qword ptr [rax+0x8], 0x1000");
+ assert!(v.contains(&0x8));
+ assert!(v.contains(&0x1000));
+ }
+
+ #[test]
+ fn search_scalars_range_filter() {
+ let listing = vec![
+ Instruction {
+ address: 0x1000,
+ bytes: vec![0x83, 0xc0, 0x05],
+ mnemonic: "add".into(),
+ operands: "eax, 5".into(),
+ length: 3,
+ },
+ Instruction {
+ address: 0x1003,
+ bytes: vec![0x83, 0xc0, 0x64],
+ mnemonic: "add".into(),
+ operands: "eax, 100".into(),
+ length: 3,
+ },
+ ];
+ let low = search_scalars(&listing, 0, 10, 32);
+ assert_eq!(low.len(), 1);
+ assert!(low[0].text.contains("eax, 5"));
+ let hi = search_scalars(&listing, 50, 200, 32);
+ assert_eq!(hi.len(), 1);
+ assert!(hi[0].text.contains("eax, 100"));
+ }
+
+ #[test]
+ fn search_instruction_patterns_mnemonic_and_operand() {
+ let listing = vec![
+ Instruction {
+ address: 0x1000,
+ bytes: vec![0x55],
+ mnemonic: "push".into(),
+ operands: "rbp".into(),
+ length: 1,
+ },
+ Instruction {
+ address: 0x1001,
+ bytes: vec![0xc3],
+ mnemonic: "ret".into(),
+ operands: String::new(),
+ length: 1,
+ },
+ ];
+ assert_eq!(search_instruction_patterns(&listing, "push", "", 8).len(), 1);
+ assert_eq!(search_instruction_patterns(&listing, "", "rbp", 8).len(), 1);
+ assert_eq!(search_instruction_patterns(&listing, "ret", "", 8).len(), 1);
+ assert!(search_instruction_patterns(&listing, "call", "", 8).is_empty());
+ }
+
+ #[test]
+ fn address_table_hits_reflect_program_state() {
+ let mut prog = load_path(fixture_path("tiny_x64.pe")).unwrap();
+ prog.analysis.address_tables.push(ghidrust_core::AddressTableInfo {
+ base: prog.image_base,
+ count: 2,
+ entries: vec![prog.image_base, prog.image_base + 8],
+ });
+ let hits = address_table_hits(&prog);
+ assert_eq!(hits.len(), 1);
+ assert!(hits[0].text.contains("2 entries"));
+ }
+
#[test]
fn decompile_entry_prefers_containing_function() {
use ghidrust_core::FunctionInfo;
diff --git a/crates/ghidrust-gui/src/panes.rs b/crates/ghidrust-gui/src/panes.rs
index e175439..cedb49a 100644
--- a/crates/ghidrust-gui/src/panes.rs
+++ b/crates/ghidrust-gui/src/panes.rs
@@ -195,6 +195,14 @@ impl PaneKind {
| PaneKind::RelocationTable
| PaneKind::DisassembledView
| PaneKind::DefinedData
+ // Phase D (M4) — real backing added.
+ | PaneKind::Bytes
+ | PaneKind::SymbolReferences
+ | PaneKind::EquatesTable
+ | PaneKind::FunctionTags
+ | PaneKind::ExternalPrograms
+ | PaneKind::DataTypePreview
+ | PaneKind::ChecksumGenerator
)
}
@@ -310,23 +318,23 @@ pub fn empty_state(ui: &mut Ui, kind: PaneKind, muted: Color32) {
pub const fn backend_pending_message(kind: PaneKind) -> &'static str {
match kind {
PaneKind::Bookmarks => "Backend pending — Bookmarks model + margin markers land in Phase B (M2).",
- PaneKind::Bytes => "Backend pending — Byte Viewer split hex/ASCII lands in Phase D (M4).",
- PaneKind::ChecksumGenerator => "Backend pending — checksum dialog lands in Phase D (M4).",
+ PaneKind::Bytes => "",
+ PaneKind::ChecksumGenerator => "",
PaneKind::CommentWindow => "Backend pending — comment model lands in Phase C (M3).",
PaneKind::Console => "",
PaneKind::DataTypeManager => "Backend pending — DTM tree (Built-In / Program / Archive) lands in Phase C (M3).",
- PaneKind::DataTypePreview => "Backend pending — preview @ cursor lands in Phase D (M4).",
+ PaneKind::DataTypePreview => "",
PaneKind::DecompiledView => "Stage-0 pseudo-C wired via ghidrust-decomp::decompile_at. Full tokens + rename land in Phase B/C.",
PaneKind::DefinedData => "Backend pending — Program::data_items model lands in Phase D (M4).",
PaneKind::DefinedStrings => "Uses ghidrust-core::analyzers::strings::run — session-only until Program::strings lands.",
PaneKind::DisassembledView => "Backend pending — virtual disassembly + pcode preview lands in Phase D (M4).",
PaneKind::Entropy => "Backend pending — GPU/CPU histogram lands in Phase E (M5).",
- PaneKind::EquatesTable => "Backend pending — Equate model lands in Phase C/D.",
- PaneKind::ExternalPrograms => "Backend pending — external program refs land in Phase D (M4).",
+ PaneKind::EquatesTable => "",
+ PaneKind::ExternalPrograms => "",
PaneKind::FunctionCallGraph => "Backend pending — level-based directed graph lands in Phase E (M5).",
PaneKind::FunctionCallTrees => "Backend pending — incoming/outgoing GTree pair lands in Phase E (M5).",
PaneKind::FunctionGraph => "Backend pending — CFG vertex/edge layout lands in Phase E (M5).",
- PaneKind::FunctionTags => "Backend pending — Function Tags model lands in Phase C/D.",
+ PaneKind::FunctionTags => "",
PaneKind::FunctionsWindow => "Uses Program::analysis.functions.",
PaneKind::Listing => "",
PaneKind::MemoryMap => "Uses Program::blocks / Program::sections (read-only). Editable table lands in Phase E (M5).",
@@ -337,7 +345,7 @@ pub const fn backend_pending_message(kind: PaneKind) -> &'static str {
PaneKind::RegisterManager => "Backend pending — SLEIGH register lattice lands in Phase E (M5).",
PaneKind::RelocationTable => "Uses Program::sections metadata; full PE/ELF reloc parse lands in Phase D (M4).",
PaneKind::ScriptManager => "Backend pending — script catalog lands in Phase F (M6).",
- PaneKind::SymbolReferences => "Backend pending — xrefs model lands in Phase D (M4).",
+ PaneKind::SymbolReferences => "",
PaneKind::SymbolTable => "Uses Program::analysis.symbols + functions (flat table).",
PaneKind::SymbolTree => "",
PaneKind::TextEditor => "Backend pending — script editor lands in Phase F (M6).",
diff --git a/crates/ghidrust-gui/src/register_manager.rs b/crates/ghidrust-gui/src/register_manager.rs
new file mode 100644
index 0000000..a7cbb2d
--- /dev/null
+++ b/crates/ghidrust-gui/src/register_manager.rs
@@ -0,0 +1,565 @@
+//! Ghidrust GUI · Phase E (M5) — Register Manager pane.
+//!
+//! Ghidra `RegisterPlugin` provider: hierarchical register tree on the left,
+//! per-address-range value table on the right. The register lattice is a
+//! honest approximation of Ghidra's SLEIGH `register` spec for x86-64 —
+//! sub-registers are grouped under their parent (e.g. `RAX` contains `EAX`,
+//! `AX`, `AH`, `AL`).
+//!
+//! Register values (Ghidra "context register" style) are session-only until
+//! the SLEIGH register lattice lands in the backend (see UI parity plan
+//! Phase E open item). Editing / clearing values here mutates the state
+//! passed in — the GUI decides how to persist / drop on program change.
+//!
+//! Extracted per `dev/MODULARIZATION_PLAN.md` — new UI panes land here
+//! instead of piling into `main.rs`.
+
+use eframe::egui::{self, Color32, Ui};
+use std::collections::BTreeMap;
+
+/// One user-set register value covering an address range.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct RegisterValueRow {
+ pub register: String,
+ pub start_va: u64,
+ pub end_va: u64,
+ pub value: String,
+}
+
+/// Pane state (session-only until backend register lattice lands).
+#[derive(Debug, Clone, Default)]
+pub struct RegisterManagerState {
+ pub filter: String,
+ pub selected: Option<String>,
+ pub values: Vec<RegisterValueRow>,
+ /// New-value input state.
+ pub input_start: String,
+ pub input_end: String,
+ pub input_value: String,
+}
+
+/// One node in the register lattice tree.
+#[derive(Debug, Clone)]
+pub struct RegisterNode {
+ pub name: &'static str,
+ pub bits: u16,
+ pub kind: RegisterKind,
+ pub children: &'static [RegisterNode],
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
+pub enum RegisterKind {
+ General,
+ Vector,
+ Segment,
+ Control,
+ Flag,
+ Instruction,
+ Context,
+}
+
+impl RegisterKind {
+ pub const ALL: &'static [RegisterKind] = &[
+ RegisterKind::General,
+ RegisterKind::Vector,
+ RegisterKind::Segment,
+ RegisterKind::Control,
+ RegisterKind::Flag,
+ RegisterKind::Instruction,
+ RegisterKind::Context,
+ ];
+ pub const fn label(self) -> &'static str {
+ match self {
+ RegisterKind::General => "General purpose",
+ RegisterKind::Vector => "Vector (XMM / YMM / ZMM)",
+ RegisterKind::Segment => "Segment",
+ RegisterKind::Control => "Control / debug",
+ RegisterKind::Flag => "Flags",
+ RegisterKind::Instruction => "Instruction pointer",
+ RegisterKind::Context => "Context",
+ }
+ }
+}
+
+const RAX: RegisterNode = RegisterNode {
+ name: "RAX",
+ bits: 64,
+ kind: RegisterKind::General,
+ children: &[
+ RegisterNode { name: "EAX", bits: 32, kind: RegisterKind::General, children: &[] },
+ RegisterNode { name: "AX", bits: 16, kind: RegisterKind::General, children: &[] },
+ RegisterNode { name: "AH", bits: 8, kind: RegisterKind::General, children: &[] },
+ RegisterNode { name: "AL", bits: 8, kind: RegisterKind::General, children: &[] },
+ ],
+};
+const RBX: RegisterNode = RegisterNode {
+ name: "RBX",
+ bits: 64,
+ kind: RegisterKind::General,
+ children: &[
+ RegisterNode { name: "EBX", bits: 32, kind: RegisterKind::General, children: &[] },
+ RegisterNode { name: "BX", bits: 16, kind: RegisterKind::General, children: &[] },
+ RegisterNode { name: "BH", bits: 8, kind: RegisterKind::General, children: &[] },
+ RegisterNode { name: "BL", bits: 8, kind: RegisterKind::General, children: &[] },
+ ],
+};
+const RCX: RegisterNode = RegisterNode {
+ name: "RCX",
+ bits: 64,
+ kind: RegisterKind::General,
+ children: &[
+ RegisterNode { name: "ECX", bits: 32, kind: RegisterKind::General, children: &[] },
+ RegisterNode { name: "CX", bits: 16, kind: RegisterKind::General, children: &[] },
+ RegisterNode { name: "CH", bits: 8, kind: RegisterKind::General, children: &[] },
+ RegisterNode { name: "CL", bits: 8, kind: RegisterKind::General, children: &[] },
+ ],
+};
+const RDX: RegisterNode = RegisterNode {
+ name: "RDX",
+ bits: 64,
+ kind: RegisterKind::General,
+ children: &[
+ RegisterNode { name: "EDX", bits: 32, kind: RegisterKind::General, children: &[] },
+ RegisterNode { name: "DX", bits: 16, kind: RegisterKind::General, children: &[] },
+ RegisterNode { name: "DH", bits: 8, kind: RegisterKind::General, children: &[] },
+ RegisterNode { name: "DL", bits: 8, kind: RegisterKind::General, children: &[] },
+ ],
+};
+const RSI: RegisterNode = RegisterNode {
+ name: "RSI",
+ bits: 64,
+ kind: RegisterKind::General,
+ children: &[
+ RegisterNode { name: "ESI", bits: 32, kind: RegisterKind::General, children: &[] },
+ RegisterNode { name: "SI", bits: 16, kind: RegisterKind::General, children: &[] },
+ RegisterNode { name: "SIL", bits: 8, kind: RegisterKind::General, children: &[] },
+ ],
+};
+const RDI: RegisterNode = RegisterNode {
+ name: "RDI",
+ bits: 64,
+ kind: RegisterKind::General,
+ children: &[
+ RegisterNode { name: "EDI", bits: 32, kind: RegisterKind::General, children: &[] },
+ RegisterNode { name: "DI", bits: 16, kind: RegisterKind::General, children: &[] },
+ RegisterNode { name: "DIL", bits: 8, kind: RegisterKind::General, children: &[] },
+ ],
+};
+const RSP: RegisterNode = RegisterNode {
+ name: "RSP",
+ bits: 64,
+ kind: RegisterKind::General,
+ children: &[
+ RegisterNode { name: "ESP", bits: 32, kind: RegisterKind::General, children: &[] },
+ RegisterNode { name: "SP", bits: 16, kind: RegisterKind::General, children: &[] },
+ RegisterNode { name: "SPL", bits: 8, kind: RegisterKind::General, children: &[] },
+ ],
+};
+const RBP: RegisterNode = RegisterNode {
+ name: "RBP",
+ bits: 64,
+ kind: RegisterKind::General,
+ children: &[
+ RegisterNode { name: "EBP", bits: 32, kind: RegisterKind::General, children: &[] },
+ RegisterNode { name: "BP", bits: 16, kind: RegisterKind::General, children: &[] },
+ RegisterNode { name: "BPL", bits: 8, kind: RegisterKind::General, children: &[] },
+ ],
+};
+
+macro_rules! rN {
+ ($name:literal, $sub:literal) => {
+ RegisterNode {
+ name: $name,
+ bits: 64,
+ kind: RegisterKind::General,
+ children: &[
+ RegisterNode {
+ name: $sub,
+ bits: 32,
+ kind: RegisterKind::General,
+ children: &[],
+ },
+ ],
+ }
+ };
+}
+
+/// The Ghidra-analog x86-64 register lattice used by the pane.
+///
+/// This is a hand-authored subset covering the registers listed in
+/// `Ghidra/Processors/x86/data/languages/x86-64.sinc` plus a few common
+/// convenience aliases. When multi-ISA lands the pane can pick a lattice
+/// off the `Program::format`.
+pub const X86_64_REGISTERS: &[RegisterNode] = &[
+ RAX,
+ RBX,
+ RCX,
+ RDX,
+ RSI,
+ RDI,
+ RSP,
+ RBP,
+ rN!("R8", "R8D"),
+ rN!("R9", "R9D"),
+ rN!("R10", "R10D"),
+ rN!("R11", "R11D"),
+ rN!("R12", "R12D"),
+ rN!("R13", "R13D"),
+ rN!("R14", "R14D"),
+ rN!("R15", "R15D"),
+ RegisterNode {
+ name: "RIP",
+ bits: 64,
+ kind: RegisterKind::Instruction,
+ children: &[],
+ },
+ RegisterNode {
+ name: "RFLAGS",
+ bits: 64,
+ kind: RegisterKind::Flag,
+ children: &[
+ RegisterNode { name: "CF", bits: 1, kind: RegisterKind::Flag, children: &[] },
+ RegisterNode { name: "PF", bits: 1, kind: RegisterKind::Flag, children: &[] },
+ RegisterNode { name: "AF", bits: 1, kind: RegisterKind::Flag, children: &[] },
+ RegisterNode { name: "ZF", bits: 1, kind: RegisterKind::Flag, children: &[] },
+ RegisterNode { name: "SF", bits: 1, kind: RegisterKind::Flag, children: &[] },
+ RegisterNode { name: "OF", bits: 1, kind: RegisterKind::Flag, children: &[] },
+ RegisterNode { name: "DF", bits: 1, kind: RegisterKind::Flag, children: &[] },
+ ],
+ },
+ RegisterNode {
+ name: "CS",
+ bits: 16,
+ kind: RegisterKind::Segment,
+ children: &[],
+ },
+ RegisterNode {
+ name: "DS",
+ bits: 16,
+ kind: RegisterKind::Segment,
+ children: &[],
+ },
+ RegisterNode {
+ name: "ES",
+ bits: 16,
+ kind: RegisterKind::Segment,
+ children: &[],
+ },
+ RegisterNode {
+ name: "FS",
+ bits: 16,
+ kind: RegisterKind::Segment,
+ children: &[],
+ },
+ RegisterNode {
+ name: "GS",
+ bits: 16,
+ kind: RegisterKind::Segment,
+ children: &[],
+ },
+ RegisterNode {
+ name: "SS",
+ bits: 16,
+ kind: RegisterKind::Segment,
+ children: &[],
+ },
+ RegisterNode {
+ name: "XMM0",
+ bits: 128,
+ kind: RegisterKind::Vector,
+ children: &[],
+ },
+ RegisterNode {
+ name: "XMM1",
+ bits: 128,
+ kind: RegisterKind::Vector,
+ children: &[],
+ },
+ RegisterNode {
+ name: "XMM2",
+ bits: 128,
+ kind: RegisterKind::Vector,
+ children: &[],
+ },
+ RegisterNode {
+ name: "XMM3",
+ bits: 128,
+ kind: RegisterKind::Vector,
+ children: &[],
+ },
+ RegisterNode {
+ name: "XMM4",
+ bits: 128,
+ kind: RegisterKind::Vector,
+ children: &[],
+ },
+ RegisterNode {
+ name: "XMM5",
+ bits: 128,
+ kind: RegisterKind::Vector,
+ children: &[],
+ },
+ RegisterNode {
+ name: "XMM6",
+ bits: 128,
+ kind: RegisterKind::Vector,
+ children: &[],
+ },
+ RegisterNode {
+ name: "XMM7",
+ bits: 128,
+ kind: RegisterKind::Vector,
+ children: &[],
+ },
+ RegisterNode {
+ name: "CR0",
+ bits: 64,
+ kind: RegisterKind::Control,
+ children: &[],
+ },
+ RegisterNode {
+ name: "CR2",
+ bits: 64,
+ kind: RegisterKind::Control,
+ children: &[],
+ },
+ RegisterNode {
+ name: "CR3",
+ bits: 64,
+ kind: RegisterKind::Control,
+ children: &[],
+ },
+ RegisterNode {
+ name: "CR4",
+ bits: 64,
+ kind: RegisterKind::Control,
+ children: &[],
+ },
+];
+
+/// Group registers by kind for the tree UI.
+pub fn group_by_kind() -> BTreeMap<RegisterKind, Vec<&'static RegisterNode>> {
+ let mut m: BTreeMap<RegisterKind, Vec<&'static RegisterNode>> = BTreeMap::new();
+ for r in X86_64_REGISTERS {
+ m.entry(r.kind).or_default().push(r);
+ }
+ m
+}
+
+/// Render the Register Manager pane.
+pub fn render(
+ state: &mut RegisterManagerState,
+ format: Option<&str>,
+ ui: &mut Ui,
+ muted: Color32,
+ primary: Color32,
+) {
+ ui.heading("Register Manager");
+ let arch = format.unwrap_or("(no program)");
+ ui.small(
+ egui::RichText::new(format!(
+ "Ghidra RegisterPlugin · {arch} register lattice · session-only values (backend pending SLEIGH lattice)"
+ ))
+ .color(muted),
+ );
+ ui.separator();
+
+ ui.horizontal(|ui| {
+ ui.label("Filter:");
+ ui.add(
+ egui::TextEdit::singleline(&mut state.filter)
+ .desired_width(220.0)
+ .hint_text("Register name…"),
+ );
+ if ui.button("Clear filter").clicked() {
+ state.filter.clear();
+ }
+ });
+ ui.add_space(4.0);
+
+ let filt = state.filter.to_ascii_lowercase();
+ let groups = group_by_kind();
+
+ egui::ScrollArea::vertical()
+ .id_salt("regmgr_scroll")
+ .max_height(360.0)
+ .show(ui, |ui| {
+ for kind in RegisterKind::ALL {
+ let Some(rs) = groups.get(kind) else {
+ continue;
+ };
+ egui::CollapsingHeader::new(
+ egui::RichText::new(kind.label()).strong().color(primary),
+ )
+ .id_salt(("regmgr_group", *kind as u8))
+ .default_open(matches!(
+ kind,
+ RegisterKind::General | RegisterKind::Instruction | RegisterKind::Flag
+ ))
+ .show(ui, |ui| {
+ for r in rs {
+ render_row(state, r, 0, &filt, ui, muted, primary);
+ }
+ });
+ }
+ });
+
+ ui.separator();
+ ui.label(egui::RichText::new("Set Register Value").strong());
+ ui.horizontal(|ui| {
+ ui.label("Register:");
+ ui.monospace(state.selected.clone().unwrap_or_else(|| "(pick above)".into()));
+ });
+ ui.horizontal(|ui| {
+ ui.label("Start VA:");
+ ui.add(
+ egui::TextEdit::singleline(&mut state.input_start)
+ .desired_width(140.0)
+ .hint_text("0x140001000"),
+ );
+ ui.label("End VA:");
+ ui.add(
+ egui::TextEdit::singleline(&mut state.input_end)
+ .desired_width(140.0)
+ .hint_text("0x140001100"),
+ );
+ ui.label("Value:");
+ ui.add(
+ egui::TextEdit::singleline(&mut state.input_value)
+ .desired_width(140.0)
+ .hint_text("0"),
+ );
+ let can_add = state.selected.is_some()
+ && !state.input_start.is_empty()
+ && !state.input_end.is_empty()
+ && !state.input_value.is_empty();
+ if ui
+ .add_enabled(can_add, egui::Button::new("Set Value"))
+ .clicked()
+ {
+ if let (Some(reg), Some(s), Some(e)) = (
+ state.selected.clone(),
+ parse_hex(&state.input_start),
+ parse_hex(&state.input_end),
+ ) {
+ if e > s {
+ state.values.push(RegisterValueRow {
+ register: reg,
+ start_va: s,
+ end_va: e,
+ value: state.input_value.clone(),
+ });
+ }
+ }
+ }
+ });
+
+ ui.add_space(6.0);
+ ui.label(egui::RichText::new("Values").strong());
+ if state.values.is_empty() {
+ ui.weak("No user-set register values.");
+ return;
+ }
+ let mut delete: Option<usize> = None;
+ egui::Grid::new("regmgr_values_grid")
+ .num_columns(5)
+ .striped(true)
+ .show(ui, |ui| {
+ ui.strong("Register");
+ ui.strong("Start");
+ ui.strong("End");
+ ui.strong("Value");
+ ui.strong("");
+ ui.end_row();
+ for (i, row) in state.values.iter().enumerate() {
+ ui.monospace(&row.register);
+ ui.monospace(format!("{:#x}", row.start_va));
+ ui.monospace(format!("{:#x}", row.end_va));
+ ui.monospace(&row.value);
+ if ui.small_button("Clear").clicked() {
+ delete = Some(i);
+ }
+ ui.end_row();
+ }
+ });
+ if let Some(i) = delete {
+ state.values.remove(i);
+ }
+}
+
+fn render_row(
+ state: &mut RegisterManagerState,
+ node: &'static RegisterNode,
+ depth: usize,
+ filt: &str,
+ ui: &mut Ui,
+ _muted: Color32,
+ primary: Color32,
+) {
+ let matches_filter = filt.is_empty() || node.name.to_ascii_lowercase().contains(filt);
+ let has_matching_child = node
+ .children
+ .iter()
+ .any(|c| filt.is_empty() || c.name.to_ascii_lowercase().contains(filt));
+
+ if !matches_filter && !has_matching_child {
+ return;
+ }
+
+ let indent = 12.0 * depth as f32;
+ ui.horizontal(|ui| {
+ ui.add_space(indent);
+ let is_sel = state.selected.as_deref() == Some(node.name);
+ let text = egui::RichText::new(format!("{} {}b", node.name, node.bits)).monospace();
+ let text = if is_sel { text.color(primary).strong() } else { text };
+ if ui.selectable_label(is_sel, text).clicked() {
+ state.selected = Some(node.name.to_string());
+ }
+ });
+ for child in node.children {
+ render_row(state, child, depth + 1, filt, ui, _muted, primary);
+ }
+}
+
+fn parse_hex(s: &str) -> Option<u64> {
+ let s = s.trim();
+ let s = s.strip_prefix("0x").or_else(|| s.strip_prefix("0X")).unwrap_or(s);
+ u64::from_str_radix(s, 16).ok()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn register_lattice_contains_expected_registers() {
+ let names: Vec<&'static str> = X86_64_REGISTERS.iter().map(|r| r.name).collect();
+ for expected in ["RAX", "RBX", "RCX", "RDX", "RSP", "RBP", "RIP", "RFLAGS", "XMM0", "CR0"] {
+ assert!(names.contains(&expected), "missing register {expected}");
+ }
+ }
+
+ #[test]
+ fn subregisters_reachable_from_rax() {
+ let rax = X86_64_REGISTERS.iter().find(|r| r.name == "RAX").unwrap();
+ let sub: Vec<&'static str> = rax.children.iter().map(|c| c.name).collect();
+ for expected in ["EAX", "AX", "AH", "AL"] {
+ assert!(sub.contains(&expected), "RAX missing subregister {expected}");
+ }
+ }
+
+ #[test]
+ fn set_and_clear_register_value_flow() {
+ let mut st = RegisterManagerState::default();
+ st.selected = Some("RAX".into());
+ st.values.push(RegisterValueRow {
+ register: "RAX".into(),
+ start_va: 0x1000,
+ end_va: 0x1010,
+ value: "0x2a".into(),
+ });
+ assert_eq!(st.values.len(), 1);
+ st.values.remove(0);
+ assert!(st.values.is_empty());
+ }
+}
diff --git a/crates/ghidrust-gui/src/scripts.rs b/crates/ghidrust-gui/src/scripts.rs
new file mode 100644
index 0000000..7e1a1f7
--- /dev/null
+++ b/crates/ghidrust-gui/src/scripts.rs
@@ -0,0 +1,521 @@
+//! Ghidrust GUI · Phase F (M6) — Script Manager, Text Editor, and
+//! MCP REPL / interpreter panes.
+//!
+//! Ghidra's `GhidraScriptMgrPlugin` (Script Manager),
+//! `TextEditorManagerPlugin` (Text Editor), and
+//! `InterpreterPanelPlugin` (Python REPL) get honest Ghidrust analogs:
+//!
+//! - **Script Manager** — categorised catalog of shipped Ghidrust MCP tools
+//! (see `skill/SKILL.md`). Selecting a tool shows its description; the
+//! `Run` button emits a Console message so users see the parity surface
+//! without a live MCP host wired up.
+//! - **Text Editor** — multi-tab in-memory editor for `.rust` / `.py`
+//! scripts on disk. Uses `rfd` to Open/Save files.
+//! - **MCP REPL** — a line-oriented prompt that logs commands to Console
+//! and echoes a "Backend pending" hint. Full REPL wires into the
+//! `ghidrust-cli mcp` stdio host in a follow-up.
+//!
+//! Extracted per `dev/MODULARIZATION_PLAN.md` — new UI panes land here
+//! instead of piling into `main.rs`.
+
+use eframe::egui::{self, Color32, Ui};
+use std::path::PathBuf;
+
+/// One Ghidra-analog script entry (Ghidrust MCP tools double as the catalog).
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct ScriptEntry {
+ pub name: String,
+ pub category: String,
+ pub description: String,
+ /// Preferred keyboard shortcut (Ghidra "Assign Key Binding"), empty if none.
+ pub key_binding: String,
+}
+
+/// Built-in catalog — mirrors the MCP tool surface described in
+/// `skill/SKILL.md`. Order = Ghidra Script Manager order (alphabetical
+/// within category).
+pub fn builtin_catalog() -> Vec<ScriptEntry> {
+ let s = |name: &str, cat: &str, desc: &str| ScriptEntry {
+ name: name.into(),
+ category: cat.into(),
+ description: desc.into(),
+ key_binding: String::new(),
+ };
+ vec![
+ s("mcp.list_methods", "MCP · Functions", "Enumerate methods in the active program (paginated)."),
+ s("mcp.list_functions", "MCP · Functions", "List every recovered function entry."),
+ s("mcp.search_functions_by_name", "MCP · Functions", "Substring search over function names."),
+ s("mcp.decompile_function", "MCP · Decompiler", "Return pseudo-C for a named function."),
+ s("mcp.decompile_function_by_address", "MCP · Decompiler", "Return pseudo-C for a function at a VA."),
+ s("mcp.disassemble_function", "MCP · Decompiler", "Return decoded listing for a function."),
+ s("mcp.rename_function", "MCP · Edits", "Rename the function at a VA."),
+ s("mcp.rename_function_by_address", "MCP · Edits", "Rename by address."),
+ s("mcp.rename_variable", "MCP · Edits", "Rename a local variable inside a function."),
+ s("mcp.rename_data", "MCP · Edits", "Rename a global data item."),
+ s("mcp.set_function_prototype", "MCP · Edits", "Set the C signature of a function."),
+ s("mcp.set_local_variable_type", "MCP · Edits", "Retype a local variable."),
+ s("mcp.set_decompiler_comment", "MCP · Comments", "Attach a decompiler-side comment."),
+ s("mcp.set_disassembly_comment", "MCP · Comments", "Attach a listing-side comment."),
+ s("mcp.list_classes", "MCP · Program", "Enumerate C++/RTTI classes recovered."),
+ s("mcp.list_namespaces", "MCP · Program", "Enumerate scoped namespaces."),
+ s("mcp.list_segments", "MCP · Program", "Enumerate mapped memory blocks / sections."),
+ s("mcp.list_imports", "MCP · Program", "Enumerate imported symbols."),
+ s("mcp.list_exports", "MCP · Program", "Enumerate exported symbols."),
+ s("mcp.list_data_items", "MCP · Program", "Enumerate defined data items."),
+ s("mcp.list_strings", "MCP · Program", "Enumerate recovered strings."),
+ s("mcp.get_xrefs_to", "MCP · Xrefs", "References targeting a VA."),
+ s("mcp.get_xrefs_from", "MCP · Xrefs", "References emitted from a VA."),
+ s("mcp.get_function_xrefs", "MCP · Xrefs", "Callers and callees of a function."),
+ s("mcp.get_current_address", "MCP · Cursor", "Report the currently focused Listing VA."),
+ s("mcp.get_current_function", "MCP · Cursor", "Report the function containing the cursor."),
+ s("mcp.get_function_by_address", "MCP · Functions", "Fetch function metadata by VA."),
+ ]
+}
+
+/// Script Manager session state.
+#[derive(Debug, Clone, Default)]
+pub struct ScriptManagerState {
+ pub catalog: Vec<ScriptEntry>,
+ pub filter: String,
+ pub selected: Option<usize>,
+ /// User-assigned category filter ("" = all).
+ pub category_filter: String,
+}
+
+impl ScriptManagerState {
+ pub fn new_with_builtin() -> Self {
+ Self {
+ catalog: builtin_catalog(),
+ ..Self::default()
+ }
+ }
+}
+
+/// One open Text Editor tab.
+#[derive(Debug, Clone, Default)]
+pub struct TextEditorTab {
+ pub path: Option<PathBuf>,
+ pub title: String,
+ pub body: String,
+ pub dirty: bool,
+}
+
+/// Text Editor session state (multi-tab).
+#[derive(Debug, Clone, Default)]
+pub struct TextEditorState {
+ pub tabs: Vec<TextEditorTab>,
+ pub active: usize,
+}
+
+impl TextEditorState {
+ pub fn open_untitled(&mut self) {
+ let n = self.tabs.len();
+ self.tabs.push(TextEditorTab {
+ path: None,
+ title: format!("Untitled-{}", n + 1),
+ body: String::new(),
+ dirty: false,
+ });
+ self.active = self.tabs.len() - 1;
+ }
+ pub fn open_file(&mut self, path: PathBuf) -> std::io::Result<()> {
+ let body = std::fs::read_to_string(&path)?;
+ let title = path
+ .file_name()
+ .and_then(|s| s.to_str())
+ .unwrap_or("script")
+ .to_string();
+ self.tabs.push(TextEditorTab {
+ path: Some(path),
+ title,
+ body,
+ dirty: false,
+ });
+ self.active = self.tabs.len() - 1;
+ Ok(())
+ }
+ pub fn save_active(&mut self) -> std::io::Result<()> {
+ let Some(tab) = self.tabs.get_mut(self.active) else {
+ return Ok(());
+ };
+ let Some(path) = tab.path.clone() else {
+ return Err(std::io::Error::new(
+ std::io::ErrorKind::InvalidInput,
+ "no path — use Save As…",
+ ));
+ };
+ std::fs::write(&path, &tab.body)?;
+ tab.dirty = false;
+ Ok(())
+ }
+ pub fn save_active_as(&mut self, path: PathBuf) -> std::io::Result<()> {
+ let Some(tab) = self.tabs.get_mut(self.active) else {
+ return Ok(());
+ };
+ std::fs::write(&path, &tab.body)?;
+ tab.title = path
+ .file_name()
+ .and_then(|s| s.to_str())
+ .unwrap_or("script")
+ .to_string();
+ tab.path = Some(path);
+ tab.dirty = false;
+ Ok(())
+ }
+ pub fn close_active(&mut self) {
+ if self.tabs.is_empty() {
+ return;
+ }
+ let idx = self.active.min(self.tabs.len() - 1);
+ self.tabs.remove(idx);
+ self.active = self.active.saturating_sub(1);
+ }
+}
+
+/// MCP REPL session state.
+#[derive(Debug, Clone, Default)]
+pub struct MacropadReplState {
+ pub input: String,
+ pub transcript: Vec<ReplLine>,
+}
+
+#[derive(Debug, Clone)]
+pub struct ReplLine {
+ pub prompt: bool,
+ pub text: String,
+}
+
+impl MacropadReplState {
+ pub fn submit(&mut self) -> String {
+ let cmd = self.input.trim().to_string();
+ if cmd.is_empty() {
+ return String::new();
+ }
+ self.transcript.push(ReplLine {
+ prompt: true,
+ text: cmd.clone(),
+ });
+ // Echo response: backend-pending honest hint.
+ let out = format!(
+ "Backend pending — MCP REPL not yet wired to ghidrust mcp stdio host. See skill/SKILL.md."
+ );
+ self.transcript.push(ReplLine {
+ prompt: false,
+ text: out.clone(),
+ });
+ self.input.clear();
+ out
+ }
+}
+
+// ── Rendering ────────────────────────────────────────────────────────────────
+
+/// Render the Script Manager. Returns `Some(name)` if a Run was requested.
+pub fn render_script_manager(
+ state: &mut ScriptManagerState,
+ ui: &mut Ui,
+ muted: Color32,
+ primary: Color32,
+) -> Option<String> {
+ ui.heading("Script Manager");
+ ui.small(
+ egui::RichText::new(
+ "Ghidra GhidraScriptMgrPlugin analog · catalog is Ghidrust's MCP tool surface (see skill/SKILL.md)",
+ )
+ .color(muted),
+ );
+ ui.separator();
+
+ let mut categories: Vec<String> = state
+ .catalog
+ .iter()
+ .map(|s| s.category.clone())
+ .collect();
+ categories.sort();
+ categories.dedup();
+
+ ui.horizontal(|ui| {
+ ui.label("Filter:");
+ ui.add(
+ egui::TextEdit::singleline(&mut state.filter)
+ .desired_width(220.0)
+ .hint_text("name / description"),
+ );
+ ui.label("Category:");
+ egui::ComboBox::from_id_salt("scriptmgr_cat")
+ .selected_text(if state.category_filter.is_empty() {
+ "All".to_string()
+ } else {
+ state.category_filter.clone()
+ })
+ .show_ui(ui, |ui| {
+ ui.selectable_value(&mut state.category_filter, String::new(), "All");
+ for c in &categories {
+ ui.selectable_value(&mut state.category_filter, c.clone(), c);
+ }
+ });
+ });
+ ui.separator();
+
+ let filt = state.filter.to_ascii_lowercase();
+ let cf = state.category_filter.clone();
+ let rows: Vec<(usize, ScriptEntry)> = state
+ .catalog
+ .iter()
+ .enumerate()
+ .filter(|(_, s)| {
+ (cf.is_empty() || s.category == cf)
+ && (filt.is_empty()
+ || s.name.to_ascii_lowercase().contains(&filt)
+ || s.description.to_ascii_lowercase().contains(&filt))
+ })
+ .map(|(i, s)| (i, s.clone()))
+ .collect();
+
+ ui.small(format!("{} / {} scripts", rows.len(), state.catalog.len()));
+ let mut requested_run: Option<String> = None;
+ egui::ScrollArea::vertical()
+ .id_salt("scriptmgr_scroll")
+ .max_height(360.0)
+ .show(ui, |ui| {
+ egui::Grid::new("scriptmgr_grid")
+ .num_columns(5)
+ .striped(true)
+ .show(ui, |ui| {
+ ui.strong("Name");
+ ui.strong("Category");
+ ui.strong("Key");
+ ui.strong("Description");
+ ui.strong("");
+ ui.end_row();
+ for (idx, s) in &rows {
+ let is_sel = state.selected == Some(*idx);
+ let name_text = egui::RichText::new(&s.name).monospace();
+ let name_text = if is_sel { name_text.color(primary) } else { name_text };
+ if ui.selectable_label(is_sel, name_text).clicked() {
+ state.selected = Some(*idx);
+ }
+ ui.label(&s.category);
+ ui.monospace(if s.key_binding.is_empty() {
+ "-".into()
+ } else {
+ s.key_binding.clone()
+ });
+ ui.label(&s.description);
+ if ui.small_button("Run").clicked() {
+ requested_run = Some(s.name.clone());
+ }
+ ui.end_row();
+ }
+ });
+ });
+
+ if let Some(idx) = state.selected {
+ if let Some(entry) = state.catalog.get(idx) {
+ ui.separator();
+ ui.label(egui::RichText::new("Selected").strong());
+ ui.monospace(&entry.name);
+ ui.small(&entry.description);
+ }
+ }
+
+ requested_run
+}
+
+/// Render the Text Editor.
+///
+/// Returns any file-op the caller must dispatch (Open / Save / SaveAs / Close).
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum TextEditorRequest {
+ None,
+ OpenFile,
+ Save,
+ SaveAs,
+ Close,
+ NewUntitled,
+}
+
+pub fn render_text_editor(
+ state: &mut TextEditorState,
+ ui: &mut Ui,
+ muted: Color32,
+ primary: Color32,
+) -> TextEditorRequest {
+ ui.heading("Text Editor");
+ ui.small(
+ egui::RichText::new("Ghidra TextEditorManagerPlugin analog · in-memory tabs on top of the local filesystem").color(muted),
+ );
+ ui.separator();
+
+ let mut req = TextEditorRequest::None;
+ ui.horizontal(|ui| {
+ if ui.button("New").clicked() {
+ req = TextEditorRequest::NewUntitled;
+ }
+ if ui.button("Open…").clicked() {
+ req = TextEditorRequest::OpenFile;
+ }
+ if ui.button("Save").clicked() {
+ req = TextEditorRequest::Save;
+ }
+ if ui.button("Save As…").clicked() {
+ req = TextEditorRequest::SaveAs;
+ }
+ if ui.button("Close Tab").clicked() {
+ req = TextEditorRequest::Close;
+ }
+ });
+ ui.separator();
+
+ if state.tabs.is_empty() {
+ ui.weak("No files open — click Open… or New to start.");
+ return req;
+ }
+
+ // Tab bar.
+ ui.horizontal_wrapped(|ui| {
+ let mut set_active: Option<usize> = None;
+ for (i, tab) in state.tabs.iter().enumerate() {
+ let mut label = tab.title.clone();
+ if tab.dirty {
+ label.push('*');
+ }
+ let is_active = state.active == i;
+ let text = if is_active {
+ egui::RichText::new(&label).strong().color(primary)
+ } else {
+ egui::RichText::new(&label)
+ };
+ if ui.selectable_label(is_active, text).clicked() {
+ set_active = Some(i);
+ }
+ }
+ if let Some(i) = set_active {
+ state.active = i;
+ }
+ });
+
+ ui.separator();
+ let active = state.active.min(state.tabs.len().saturating_sub(1));
+ state.active = active;
+ let Some(tab) = state.tabs.get_mut(active) else {
+ return req;
+ };
+
+ let path_label = tab
+ .path
+ .as_ref()
+ .and_then(|p| p.to_str())
+ .unwrap_or("(unsaved)");
+ ui.small(egui::RichText::new(path_label).color(muted));
+ let before = tab.body.clone();
+ egui::ScrollArea::vertical()
+ .id_salt("texted_body")
+ .max_height(360.0)
+ .show(ui, |ui| {
+ ui.add(
+ egui::TextEdit::multiline(&mut tab.body)
+ .font(egui::FontId::monospace(13.0))
+ .desired_width(f32::INFINITY)
+ .desired_rows(20)
+ .code_editor(),
+ );
+ });
+ if before != tab.body {
+ tab.dirty = true;
+ }
+
+ req
+}
+
+/// Render the MCP REPL.
+pub fn render_mcp_repl(state: &mut MacropadReplState, ui: &mut Ui, muted: Color32, primary: Color32) {
+ ui.heading("Python (MCP REPL)");
+ ui.small(
+ egui::RichText::new("Ghidra InterpreterPanelPlugin analog · pipes to ghidrust mcp (stub; full wire lands in P17)").color(muted),
+ );
+ ui.separator();
+
+ egui::ScrollArea::vertical()
+ .id_salt("mcp_repl_transcript")
+ .stick_to_bottom(true)
+ .max_height(300.0)
+ .show(ui, |ui| {
+ for line in &state.transcript {
+ if line.prompt {
+ ui.monospace(egui::RichText::new(format!(">>> {}", line.text)).color(primary));
+ } else {
+ ui.monospace(egui::RichText::new(&line.text).color(muted));
+ }
+ }
+ });
+
+ ui.separator();
+ ui.horizontal(|ui| {
+ ui.label(">>> ");
+ let resp = ui.add(
+ egui::TextEdit::singleline(&mut state.input)
+ .desired_width(ui.available_width() - 80.0)
+ .hint_text("call an MCP tool… e.g. mcp.list_functions"),
+ );
+ let submit = ui.button("Run").clicked()
+ || (resp.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)));
+ if submit {
+ state.submit();
+ }
+ });
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn builtin_catalog_covers_ghidrust_mcp_surface() {
+ let cat = builtin_catalog();
+ assert!(cat.len() >= 20);
+ for want in [
+ "mcp.list_functions",
+ "mcp.decompile_function",
+ "mcp.rename_function",
+ "mcp.get_xrefs_to",
+ ] {
+ assert!(cat.iter().any(|s| s.name == want), "missing {want}");
+ }
+ }
+
+ #[test]
+ fn text_editor_open_and_save_flow() {
+ let dir = std::env::temp_dir().join(format!("ghidrust_txted_{}", std::process::id()));
+ let _ = std::fs::create_dir_all(&dir);
+ let path = dir.join("hello.txt");
+ std::fs::write(&path, "hello").unwrap();
+
+ let mut st = TextEditorState::default();
+ st.open_untitled();
+ assert_eq!(st.tabs.len(), 1);
+ st.open_file(path.clone()).unwrap();
+ assert_eq!(st.tabs.len(), 2);
+ assert_eq!(st.tabs[1].body, "hello");
+ st.tabs[1].body.push_str(" world");
+ st.tabs[1].dirty = true;
+ st.save_active().unwrap();
+ assert!(!st.tabs[1].dirty);
+ assert_eq!(std::fs::read_to_string(&path).unwrap(), "hello world");
+ st.close_active();
+ assert_eq!(st.tabs.len(), 1);
+
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
+ #[test]
+ fn repl_submit_appends_prompt_and_response() {
+ let mut r = MacropadReplState::default();
+ r.input = "mcp.list_functions".into();
+ r.submit();
+ assert_eq!(r.transcript.len(), 2);
+ assert!(r.transcript[0].prompt);
+ assert!(!r.transcript[1].prompt);
+ assert!(r.input.is_empty());
+ }
+}
diff --git a/crates/ghidrust-ir/src/lib.rs b/crates/ghidrust-ir/src/lib.rs
index fe76cae..7ec011e 100644
--- a/crates/ghidrust-ir/src/lib.rs
+++ b/crates/ghidrust-ir/src/lib.rs
@@ -111,6 +111,14 @@ pub enum OpCode {
IntOr,
/// `out = in0 * in1` (low half).
IntMult,
+ /// `out = in0 / in1` (unsigned division).
+ IntDiv,
+ /// `out = in0 / in1` (signed division).
+ IntSDiv,
+ /// `out = in0 % in1` (unsigned remainder).
+ IntRem,
+ /// `out = in0 % in1` (signed remainder).
+ IntSRem,
/// `out = in0 << in1` (logical left shift).
IntLeft,
/// `out = in0 >> in1` (logical right shift).
@@ -161,6 +169,24 @@ pub enum OpCode {
Pop,
/// No-op / hint. Preserved so structural passes see the instruction.
Nop,
+ /// Architectural trap (`int3`, `hlt`, `ud2`) — modelled explicitly so
+ /// SSA/structuring can decide whether the block terminates. Consumers
+ /// treat this as an opaque side-effect with no def.
+ Trap,
+ /// `out = concat(in0, in1)` — Ghidra `PIECE`: joins two subwords into a
+ /// wider value. `in0` is the high half, `in1` is the low half, and
+ /// `out.size == in0.size + in1.size`.
+ Piece,
+ /// `out = in0 >> (in1 * 8)` truncated to `out.size` — Ghidra
+ /// `SUBPIECE`. `in1` names the byte offset from the LSB.
+ Subpiece,
+ /// `out = in0 + in1 * <element size>` — Ghidra `PTRADD`. Semantically
+ /// identical to `IntAdd` for byte arithmetic but preserves the "array
+ /// index" shape so type recovery / emit can print `p[i]`.
+ Ptradd,
+ /// `out = (T)in0` — Ghidra `CAST`. Bit-preserving reinterpretation
+ /// used when Stage-1 emit needs to insert an explicit `(uint32_t)`.
+ Cast,
/// ISA op not yet lifted — mnemonic preserved in [`PcodeOp::note`].
Unimplemented,
}
@@ -351,4 +377,26 @@ mod tests {
assert_eq!(node.opcode, op);
}
}
+
+ #[test]
+ fn opcode_set_covers_phase_a_pcode_additions() {
+ // Phase A extensions from the P0 parity plan: division family,
+ // Trap for int3/hlt, and the Ghidra bit-manipulation ops
+ // (PIECE/SUBPIECE/PTRADD/CAST) that Stage-1 emit will need as
+ // lift coverage grows.
+ for op in [
+ OpCode::IntDiv,
+ OpCode::IntSDiv,
+ OpCode::IntRem,
+ OpCode::IntSRem,
+ OpCode::Trap,
+ OpCode::Piece,
+ OpCode::Subpiece,
+ OpCode::Ptradd,
+ OpCode::Cast,
+ ] {
+ let node = PcodeOp::new(op, None, vec![]);
+ assert_eq!(node.opcode, op);
+ }
+ }
}
diff --git a/crates/ghidrust-lift/src/lib.rs b/crates/ghidrust-lift/src/lib.rs
index 7981ccb..2797236 100644
--- a/crates/ghidrust-lift/src/lib.rs
+++ b/crates/ghidrust-lift/src/lib.rs
@@ -130,16 +130,28 @@ fn parse_reg(name: &str) -> Option<(X86Reg, u32)> {
"r9b" => (X86Reg::R9, 1),
"r10" => (X86Reg::R10, 8),
"r10d" => (X86Reg::R10, 4),
+ "r10w" => (X86Reg::R10, 2),
+ "r10b" => (X86Reg::R10, 1),
"r11" => (X86Reg::R11, 8),
"r11d" => (X86Reg::R11, 4),
+ "r11w" => (X86Reg::R11, 2),
+ "r11b" => (X86Reg::R11, 1),
"r12" => (X86Reg::R12, 8),
"r12d" => (X86Reg::R12, 4),
+ "r12w" => (X86Reg::R12, 2),
+ "r12b" => (X86Reg::R12, 1),
"r13" => (X86Reg::R13, 8),
"r13d" => (X86Reg::R13, 4),
+ "r13w" => (X86Reg::R13, 2),
+ "r13b" => (X86Reg::R13, 1),
"r14" => (X86Reg::R14, 8),
"r14d" => (X86Reg::R14, 4),
+ "r14w" => (X86Reg::R14, 2),
+ "r14b" => (X86Reg::R14, 1),
"r15" => (X86Reg::R15, 8),
"r15d" => (X86Reg::R15, 4),
+ "r15w" => (X86Reg::R15, 2),
+ "r15b" => (X86Reg::R15, 1),
_ => return None,
};
Some((reg, size))
@@ -170,11 +182,15 @@ fn split_operands(ops: &str) -> Vec<&str> {
ops.split(',').map(str::trim).filter(|s| !s.is_empty()).collect()
}
-/// Parsed memory operand. `[seg:]base±disp` — no SIB/index at this stage.
+/// Parsed memory operand. `[seg:]base+index*scale±disp` — supports SIB.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MemOperand {
pub segment: Option<String>,
pub base: Option<X86Reg>,
+ /// Optional index register (SIB).
+ pub index: Option<X86Reg>,
+ /// SIB scale factor (1/2/4/8). Ignored when `index` is `None`.
+ pub scale: u32,
pub rip_relative: bool,
pub displacement: i64,
/// Access width in bytes (defaults 8 when the mnemonic is 64-bit; caller may override).
@@ -212,47 +228,84 @@ pub fn parse_mem(op: &str) -> Option<MemOperand> {
if inner.is_empty() {
return None;
}
- if inner.contains('*') {
- // SIB with scale — not yet lifted.
+
+ // Split into `+` / `-` tokens preserving signs (base+index*scale+disp).
+ let mut tokens: Vec<(i64, String)> = Vec::new();
+ let mut cur = String::new();
+ let mut sign: i64 = 1;
+ for ch in inner.chars() {
+ match ch {
+ '+' => {
+ if !cur.trim().is_empty() {
+ tokens.push((sign, cur.trim().to_string()));
+ }
+ cur.clear();
+ sign = 1;
+ }
+ '-' => {
+ if !cur.trim().is_empty() {
+ tokens.push((sign, cur.trim().to_string()));
+ }
+ cur.clear();
+ sign = -1;
+ }
+ other => cur.push(other),
+ }
+ }
+ if !cur.trim().is_empty() {
+ tokens.push((sign, cur.trim().to_string()));
+ }
+ if tokens.is_empty() {
return None;
}
- let (base_tok, disp_tok) =
- if let Some(idx) = inner.find(|c| c == '+' || c == '-').filter(|&i| i > 0) {
- (&inner[..idx], &inner[idx..])
- } else {
- (inner, "")
- };
- let base_tok = base_tok.trim();
- let disp_tok = disp_tok.trim();
-
+ let mut base: Option<X86Reg> = None;
+ let mut index: Option<X86Reg> = None;
+ let mut scale: u32 = 1;
let mut rip_relative = false;
- let base = if base_tok == "rip" {
- rip_relative = true;
- None
- } else if base_tok.is_empty() {
- None
- } else {
- parse_reg(base_tok).map(|(r, _)| r)
- };
-
- let displacement = if disp_tok.is_empty() {
- 0i64
- } else {
- let (sign, body) = if let Some(rest) = disp_tok.strip_prefix('-') {
- (-1i64, rest.trim())
- } else if let Some(rest) = disp_tok.strip_prefix('+') {
- (1i64, rest.trim())
- } else {
- (1i64, disp_tok)
- };
- let raw = parse_imm(body)? as i64;
- sign * raw
- };
+ let mut displacement: i64 = 0;
+ for (sign, tok) in tokens {
+ // index*scale form
+ if let Some((r_tok, scale_tok)) = tok.split_once('*') {
+ let r_tok = r_tok.trim();
+ let scale_tok = scale_tok.trim();
+ let (r, _) = parse_reg(r_tok)?;
+ let s: u32 = scale_tok.parse().ok()?;
+ if index.is_some() {
+ return None;
+ }
+ index = Some(r);
+ scale = s;
+ continue;
+ }
+ if tok == "rip" {
+ rip_relative = true;
+ continue;
+ }
+ if let Some((r, _)) = parse_reg(&tok) {
+ if base.is_none() {
+ base = Some(r);
+ } else if index.is_none() {
+ index = Some(r);
+ scale = 1;
+ } else {
+ return None;
+ }
+ continue;
+ }
+ // treat as a displacement literal
+ if let Some(v) = parse_imm(&tok) {
+ displacement = displacement.wrapping_add(sign.wrapping_mul(v as i64));
+ continue;
+ }
+ return None;
+ }
Some(MemOperand {
segment,
base,
+ index,
+ scale,
rip_relative,
displacement,
size: size_hint.unwrap_or(8),
@@ -282,6 +335,62 @@ fn is_jcc(mnem: &str) -> bool {
)
}
+/// True for `cmovcc` mnemonics — `cmove`, `cmovne`, `cmovl`, …
+fn is_cmov(mnem: &str) -> bool {
+ if let Some(rest) = mnem.strip_prefix("cmov") {
+ matches!(
+ rest,
+ "o" | "no"
+ | "b"
+ | "ae"
+ | "e"
+ | "ne"
+ | "be"
+ | "a"
+ | "s"
+ | "ns"
+ | "p"
+ | "np"
+ | "l"
+ | "ge"
+ | "le"
+ | "g"
+ | "z"
+ | "nz"
+ )
+ } else {
+ false
+ }
+}
+
+/// True for `setcc` byte-destination flag captures.
+fn is_setcc(mnem: &str) -> bool {
+ if let Some(rest) = mnem.strip_prefix("set") {
+ matches!(
+ rest,
+ "o" | "no"
+ | "b"
+ | "ae"
+ | "e"
+ | "ne"
+ | "be"
+ | "a"
+ | "s"
+ | "ns"
+ | "p"
+ | "np"
+ | "l"
+ | "ge"
+ | "le"
+ | "g"
+ | "z"
+ | "nz"
+ )
+ } else {
+ false
+ }
+}
+
/// Convert a `jcc` mnemonic into the flag combination that drives it. Returns
/// a sequence of ops producing a 1-byte bool in a fresh unique varnode, plus
/// the varnode itself. This is a "small enough" model: exact flag-set from
@@ -422,18 +531,45 @@ fn mem_address_ops(ctx: &mut LiftCtx, mem: &MemOperand, insn_addr: u64, insn_len
));
return (ops, out);
}
- let base = mem
+
+ // Start from `base` (or 0 if absent).
+ let mut running = mem
.base
.map(|r| r.as_varnode(addr_size))
.unwrap_or_else(|| Varnode::constant(0, addr_size));
- if mem.displacement == 0 && mem.base.is_some() {
- return (ops, base);
+
+ // Fold in `index * scale` when present. Use PTRADD so type recovery can
+ // tell an "array index" from a plain byte offset.
+ if let Some(index_reg) = mem.index {
+ let idx = index_reg.as_varnode(addr_size);
+ let idx_term = if mem.scale == 1 {
+ idx
+ } else {
+ let scaled = ctx.take_unique(addr_size);
+ ops.push(PcodeOp::new(
+ OpCode::IntMult,
+ Some(scaled.clone()),
+ vec![idx, Varnode::constant(mem.scale as u64, addr_size)],
+ ));
+ scaled
+ };
+ let combined = ctx.take_unique(addr_size);
+ ops.push(PcodeOp::new(
+ OpCode::Ptradd,
+ Some(combined.clone()),
+ vec![running, idx_term],
+ ));
+ running = combined;
+ }
+
+ if mem.displacement == 0 {
+ return (ops, running);
}
let out = ctx.take_unique(addr_size);
ops.push(PcodeOp::new(
OpCode::IntAdd,
Some(out.clone()),
- vec![base, Varnode::constant(mem.displacement as u64, addr_size)],
+ vec![running, Varnode::constant(mem.displacement as u64, addr_size)],
));
(ops, out)
}
@@ -496,11 +632,72 @@ fn lift_with_ctx(ctx: &mut LiftCtx, insn: &Instruction) -> Vec<PcodeOp> {
let len = insn.length;
match mnem {
- "nop" => {
- return vec![PcodeOp::new(OpCode::Nop, None, vec![]).with_note("nop")];
+ "nop" | "endbr64" | "endbr32" => {
+ return vec![PcodeOp::new(OpCode::Nop, None, vec![]).with_note(mnem)];
+ }
+ // Architectural traps: model as a Trap opcode so SSA/structure knows
+ // the block has a side effect but never treats the value as
+ // "unimplemented / fabricated".
+ "int3" | "hlt" | "ud2" => {
+ return vec![PcodeOp::new(OpCode::Trap, None, vec![]).with_note(mnem)];
+ }
+ // CDQ/CQO/CBW/CWDE/CDQE — treat as a controlled sign-extension of the
+ // accumulator into rdx:rax (CDQ/CQO) or eax (CBW/CWDE/CDQE). Model
+ // as an explicit sign-extend copy; SSA/DCE will drop when unused.
+ "cdq" | "cqo" => {
+ let width = if mnem == "cqo" { 8 } else { 4 };
+ let rax = X86Reg::Rax.as_varnode(width);
+ let rdx = X86Reg::Rdx.as_varnode(width);
+ return vec![PcodeOp::new(OpCode::IntSExt, Some(rdx), vec![rax])
+ .with_note(mnem)];
+ }
+ "cwde" | "cdqe" | "cbw" => {
+ let (src_w, dst_w) = match mnem {
+ "cbw" => (1u32, 2u32),
+ "cwde" => (2u32, 4u32),
+ "cdqe" => (4u32, 8u32),
+ _ => unreachable!(),
+ };
+ let src = X86Reg::Rax.as_varnode(src_w);
+ let dst = X86Reg::Rax.as_varnode(dst_w);
+ return vec![PcodeOp::new(OpCode::IntSExt, Some(dst), vec![src])
+ .with_note(mnem)];
+ }
+ "bswap" => {
+ if let Some(first) = parts.first() {
+ if let Some((reg, size)) = parse_reg(first) {
+ let vn = reg.as_varnode(size);
+ // Model as opaque "byte-swap"; kept as an IntXor-with-self
+ // marker so we don't fabricate arithmetic. Downstream
+ // Stage-1 emit will print a `bswap(x)` builtin call.
+ return vec![PcodeOp::new(
+ OpCode::Cast,
+ Some(vn.clone()),
+ vec![vn],
+ )
+ .with_note(format!("bswap {first}"))];
+ }
+ }
+ }
+ "pushfq" => {
+ // Push RFLAGS (8 bytes). We don't model individual flag bit
+ // packing — the SSA reads of ZF/CF/… stay untouched.
+ return vec![PcodeOp::new(OpCode::Push, None, vec![])
+ .with_note("pushfq")];
+ }
+ "popfq" => {
+ return vec![PcodeOp::new(OpCode::Pop, None, vec![])
+ .with_note("popfq")];
+ }
+ "syscall" => {
+ // Modeled as an indirect call for now (result in rax after).
+ return vec![PcodeOp::new(OpCode::CallInd, None, vec![])
+ .with_note("syscall")];
}
- "int3" => {
- return vec![PcodeOp::unimplemented("int3")];
+ "cpuid" => {
+ // Reads eax/ecx, writes eax/ebx/ecx/edx. Represent as a Trap-
+ // like opaque so we don't invent a value.
+ return vec![PcodeOp::new(OpCode::Trap, None, vec![]).with_note("cpuid")];
}
"leave" => {
// rsp = rbp; rbp = pop
@@ -662,6 +859,203 @@ fn lift_with_ctx(ctx: &mut LiftCtx, insn: &Instruction) -> Vec<PcodeOp> {
ops.extend(lift_arith_flags(dst_vn, OpCode::IntMult));
return ops;
}
+ if let (Some((dst, dsz)), Some(mem)) = (parse_reg(parts[0]), parse_mem(parts[1])) {
+ let (mut ops, val) = load_from(ctx, &mem, dsz, addr, len);
+ let dst_vn = dst.as_varnode(dsz);
+ ops.push(
+ PcodeOp::new(
+ OpCode::IntMult,
+ Some(dst_vn.clone()),
+ vec![dst_vn.clone(), val],
+ )
+ .with_note(format!("{} {}", mnem, insn.operands)),
+ );
+ ops.extend(lift_arith_flags(dst_vn, OpCode::IntMult));
+ return ops;
+ }
+ }
+ // imul r, r/m, imm (three-operand form emitted by 0x6B / 0x69)
+ "imul" if parts.len() == 3 => {
+ if let (Some((dst, dsz)), Some(imm)) = (parse_reg(parts[0]), parse_imm(parts[2])) {
+ let src_vn = if let Some((sr, ssz)) = parse_reg(parts[1]) {
+ sr.as_varnode(ssz.min(dsz))
+ } else if let Some(mem) = parse_mem(parts[1]) {
+ let (load_ops, v) = load_from(ctx, &mem, dsz, addr, len);
+ let dst_vn = dst.as_varnode(dsz);
+ let mut ops = load_ops;
+ ops.push(
+ PcodeOp::new(
+ OpCode::IntMult,
+ Some(dst_vn.clone()),
+ vec![v, Varnode::constant(imm, dsz)],
+ )
+ .with_note(format!("imul {}", insn.operands)),
+ );
+ ops.extend(lift_arith_flags(dst_vn, OpCode::IntMult));
+ return ops;
+ } else {
+ return vec![PcodeOp::unimplemented(format!("imul {}", insn.operands))];
+ };
+ let dst_vn = dst.as_varnode(dsz);
+ let mut ops = vec![PcodeOp::new(
+ OpCode::IntMult,
+ Some(dst_vn.clone()),
+ vec![src_vn, Varnode::constant(imm, dsz)],
+ )
+ .with_note(format!("imul {}", insn.operands))];
+ ops.extend(lift_arith_flags(dst_vn, OpCode::IntMult));
+ return ops;
+ }
+ }
+ // 1-operand imul / mul / div / idiv (F6/F7 group).
+ // Ghidra models these as writing to rax:rdx (rdx:rax) — we
+ // conservatively update rax with the low half and drop rdx so
+ // Stage-1 doesn't fabricate a phantom def.
+ "imul" | "mul" | "idiv" | "div" if parts.len() == 1 => {
+ let op_int = match mnem {
+ "mul" => OpCode::IntMult,
+ "imul" => OpCode::IntMult,
+ "div" => OpCode::IntDiv,
+ "idiv" => OpCode::IntSDiv,
+ _ => unreachable!(),
+ };
+ let src_size_hint = parse_reg(parts[0])
+ .map(|(_, s)| s)
+ .or_else(|| parse_mem(parts[0]).map(|m| m.size))
+ .unwrap_or(8);
+ let rax = X86Reg::Rax.as_varnode(src_size_hint);
+ let (rhs_ops, rhs_vn) = if let Some((r, sz)) = parse_reg(parts[0]) {
+ (Vec::new(), r.as_varnode(sz))
+ } else if let Some(mem) = parse_mem(parts[0]) {
+ load_from(ctx, &mem, mem.size, addr, len)
+ } else {
+ return vec![PcodeOp::unimplemented(format!("{} {}", mnem, insn.operands))];
+ };
+ let mut ops = rhs_ops;
+ ops.push(
+ PcodeOp::new(op_int, Some(rax.clone()), vec![rax.clone(), rhs_vn.clone()])
+ .with_note(format!("{} {}", mnem, insn.operands)),
+ );
+ // For div/idiv, model rdx receiving the remainder.
+ if matches!(mnem, "div" | "idiv") {
+ let rdx = X86Reg::Rdx.as_varnode(src_size_hint);
+ let rem_op = if mnem == "idiv" {
+ OpCode::IntSRem
+ } else {
+ OpCode::IntRem
+ };
+ ops.push(
+ PcodeOp::new(rem_op, Some(rdx), vec![rax.clone(), rhs_vn])
+ .with_note(format!("{} rdx", mnem)),
+ );
+ }
+ ops.extend(lift_arith_flags(rax, op_int));
+ return ops;
+ }
+ // CMOVcc r, r/m — modeled as a conditional Copy from source to dst,
+ // guarded by the same flag lattice the jcc form uses. We emit the
+ // condition once, then a `CBranch`-like predicated Copy using a
+ // pair of Copy ops so SSA sees a clear def either way. Since we
+ // don't (yet) have `INDIRECT`, materialize as `dst = cond ? src : dst`
+ // via `BoolNegate` + two IntAnd-style guards is overkill: keep it
+ // simple with a Copy + Unimplemented "predicated" note so DCE can
+ // still walk it. Ghidra's real MULTIEQUAL is a Phase B follow-up.
+ m if is_cmov(m) => {
+ let jcc_form = format!("j{}", &m[4..]);
+ let (mut cond_ops, _cond_vn) = jcc_condition(&jcc_form, &mut ctx.unique_id);
+ let out_ops = if parts.len() == 2 {
+ let (dst_vn, src_vn) = if let (Some((d, dsz)), Some((s, _))) =
+ (parse_reg(parts[0]), parse_reg(parts[1]))
+ {
+ (d.as_varnode(dsz), s.as_varnode(dsz))
+ } else if let (Some((d, dsz)), Some(mem)) =
+ (parse_reg(parts[0]), parse_mem(parts[1]))
+ {
+ let (load_ops, v) = load_from(ctx, &mem, dsz, addr, len);
+ cond_ops.extend(load_ops);
+ (d.as_varnode(dsz), v)
+ } else {
+ return vec![PcodeOp::unimplemented(format!("{} {}", m, insn.operands))];
+ };
+ vec![PcodeOp::new(OpCode::Copy, Some(dst_vn), vec![src_vn])
+ .with_note(format!("{} {}", m, insn.operands))]
+ } else {
+ vec![PcodeOp::unimplemented(format!("{} {}", m, insn.operands))]
+ };
+ cond_ops.extend(out_ops);
+ return cond_ops;
+ }
+ // SETcc r/m8 — condition + Copy to a byte destination.
+ m if is_setcc(m) => {
+ let jcc_form = format!("j{}", &m[3..]);
+ let (mut cond_ops, cond_vn) = jcc_condition(&jcc_form, &mut ctx.unique_id);
+ if let Some(first) = parts.first() {
+ if let Some((reg, _)) = parse_reg(first) {
+ let dst = reg.as_varnode(1);
+ cond_ops.push(
+ PcodeOp::new(OpCode::Copy, Some(dst), vec![cond_vn])
+ .with_note(format!("{} {}", m, insn.operands)),
+ );
+ return cond_ops;
+ }
+ if let Some(mem) = parse_mem(first) {
+ cond_ops.extend(store_to(ctx, &mem, cond_vn, addr, len));
+ return cond_ops;
+ }
+ }
+ }
+ // MOVZX / MOVSX / MOVSXD — sized copy through IntZExt / IntSExt.
+ "movzx" | "movsx" | "movsxd" if parts.len() == 2 => {
+ let opcode = if mnem == "movzx" {
+ OpCode::IntZExt
+ } else {
+ OpCode::IntSExt
+ };
+ if let Some((d, dsz)) = parse_reg(parts[0]) {
+ let dst = d.as_varnode(dsz);
+ if let Some((s, ssz)) = parse_reg(parts[1]) {
+ return vec![PcodeOp::new(opcode, Some(dst), vec![s.as_varnode(ssz)])
+ .with_note(format!("{} {}", mnem, insn.operands))];
+ }
+ if let Some(mem) = parse_mem(parts[1]) {
+ let (mut ops, val) = load_from(ctx, &mem, mem.size, addr, len);
+ ops.push(
+ PcodeOp::new(opcode, Some(dst), vec![val])
+ .with_note(format!("{} {}", mnem, insn.operands)),
+ );
+ return ops;
+ }
+ }
+ }
+ // ROL / ROR — no direct IR opcode yet; model via IntLeft / IntRight
+ // preserving the operand shape so Stage-1 emits a shift and note
+ // preserves the original rotate mnemonic.
+ "rol" | "ror" | "rcl" | "rcr" if parts.len() == 2 => {
+ let opcode = if mnem == "rol" || mnem == "rcl" {
+ OpCode::IntLeft
+ } else {
+ OpCode::IntRight
+ };
+ if let Some(ops) = lift_shift(ctx, opcode, parts[0], parts[1], mnem, &insn.operands) {
+ return ops;
+ }
+ }
+ "xchg" if parts.len() == 2 => {
+ // xchg a, b → tmp = a; a = b; b = tmp.
+ if let (Some((a, asz)), Some((b, bsz))) = (parse_reg(parts[0]), parse_reg(parts[1])) {
+ let sz = asz.min(bsz);
+ let a_vn = a.as_varnode(sz);
+ let b_vn = b.as_varnode(sz);
+ let tmp = ctx.take_unique(sz);
+ return vec![
+ PcodeOp::new(OpCode::Copy, Some(tmp.clone()), vec![a_vn.clone()])
+ .with_note("xchg tmp"),
+ PcodeOp::new(OpCode::Copy, Some(a_vn), vec![b_vn.clone()])
+ .with_note(format!("xchg {}", insn.operands)),
+ PcodeOp::new(OpCode::Copy, Some(b_vn), vec![tmp])
+ .with_note("xchg tmp"),
+ ];
+ }
}
"call" => {
if let Some(first) = parts.first() {
@@ -1068,6 +1462,8 @@ mod tests {
MemOperand {
segment: None,
base: Some(X86Reg::Rbp),
+ index: None,
+ scale: 1,
rip_relative: false,
displacement: -0x8,
size: 8,
@@ -1078,6 +1474,8 @@ mod tests {
MemOperand {
segment: None,
base: None,
+ index: None,
+ scale: 1,
rip_relative: true,
displacement: 0x2000,
size: 8,
@@ -1088,6 +1486,8 @@ mod tests {
MemOperand {
segment: None,
base: Some(X86Reg::Rax),
+ index: None,
+ scale: 1,
rip_relative: false,
displacement: 0,
size: 8,
@@ -1095,6 +1495,117 @@ mod tests {
);
}
+ #[test]
+ fn parse_mem_supports_sib_scale() {
+ let m = parse_mem("[rax+rcx*4]").unwrap();
+ assert_eq!(m.base, Some(X86Reg::Rax));
+ assert_eq!(m.index, Some(X86Reg::Rcx));
+ assert_eq!(m.scale, 4);
+ assert_eq!(m.displacement, 0);
+ let m2 = parse_mem("qword ptr [rbp+rdx*8-0x10]").unwrap();
+ assert_eq!(m2.base, Some(X86Reg::Rbp));
+ assert_eq!(m2.index, Some(X86Reg::Rdx));
+ assert_eq!(m2.scale, 8);
+ assert_eq!(m2.displacement, -0x10);
+ }
+
+ #[test]
+ fn lift_movzx_produces_zext() {
+ // 0f b6 c1 movzx eax, cl
+ let insns = decode_bytes(&[0x0f, 0xb6, 0xc1], 0x8000, 4).unwrap();
+ let seq = lift_instructions(&insns);
+ assert!(
+ seq.ops.iter().any(|o| o.opcode == OpCode::IntZExt),
+ "movzx should lift to IntZExt: {:?}",
+ seq.ops
+ );
+ }
+
+ #[test]
+ fn lift_movsxd_produces_sext() {
+ // 48 63 c1 movsxd rax, ecx
+ let insns = decode_bytes(&[0x48, 0x63, 0xc1], 0x9000, 4).unwrap();
+ let seq = lift_instructions(&insns);
+ assert!(
+ seq.ops.iter().any(|o| o.opcode == OpCode::IntSExt),
+ "movsxd should lift to IntSExt: {:?}",
+ seq.ops
+ );
+ }
+
+ #[test]
+ fn lift_int3_becomes_trap_not_unimplemented() {
+ // Baseline was `int3` → OpCode::Unimplemented; Phase A models it
+ // as a proper Trap op so lift coverage counts it.
+ let insns = decode_bytes(&[0xcc], 0xa000, 4).unwrap();
+ let seq = lift_instructions(&insns);
+ assert_eq!(seq.ops[0].opcode, OpCode::Trap);
+ let cov = coverage(&seq, insns.len());
+ assert!(
+ (cov.ratio() - 1.0).abs() < 1e-6,
+ "int3 should now be a lifted Trap, got ratio={}",
+ cov.ratio()
+ );
+ }
+
+ #[test]
+ fn lift_cmov_emits_condition_and_copy() {
+ // 48 0f 45 c8 cmovne rcx, rax
+ let insns = decode_bytes(&[0x48, 0x0f, 0x45, 0xc8], 0xb000, 4).unwrap();
+ let seq = lift_instructions(&insns);
+ assert!(seq.ops.iter().any(|o| o.opcode == OpCode::Copy));
+ assert!(seq.ops.iter().any(|o| matches!(
+ o.opcode,
+ OpCode::Copy | OpCode::BoolNegate | OpCode::BoolOr | OpCode::IntNotEqual
+ )));
+ }
+
+ #[test]
+ fn lift_setcc_emits_condition_and_byte_dst() {
+ // 0f 94 c0 sete al
+ let insns = decode_bytes(&[0x0f, 0x94, 0xc0], 0xc000, 4).unwrap();
+ let seq = lift_instructions(&insns);
+ let copy = seq
+ .ops
+ .iter()
+ .find(|o| o.opcode == OpCode::Copy)
+ .expect("setcc should end in Copy");
+ assert_eq!(copy.output.as_ref().map(|v| v.size), Some(1));
+ }
+
+ #[test]
+ fn lift_shl_imm_produces_intleft_via_c1_encoding() {
+ // c1 e0 03 shl eax, 3 (real decoder path, not synthetic).
+ let insns = decode_bytes(&[0xc1, 0xe0, 0x03], 0xd000, 4).unwrap();
+ let seq = lift_instructions(&insns);
+ assert!(seq.ops.iter().any(|o| o.opcode == OpCode::IntLeft));
+ }
+
+ #[test]
+ fn lift_shl_by_cl_via_d3_encoding() {
+ // d3 e0 shl eax, cl
+ let insns = decode_bytes(&[0xd3, 0xe0], 0xe000, 4).unwrap();
+ let seq = lift_instructions(&insns);
+ assert!(seq.ops.iter().any(|o| o.opcode == OpCode::IntLeft));
+ }
+
+ #[test]
+ fn lift_neg_eax_via_f7_group() {
+ // f7 d8 neg eax
+ let insns = decode_bytes(&[0xf7, 0xd8], 0xf000, 4).unwrap();
+ let seq = lift_instructions(&insns);
+ assert!(seq.ops.iter().any(|o| o.opcode == OpCode::IntNegate));
+ }
+
+ #[test]
+ fn lift_idiv_produces_sdiv_and_srem() {
+ // f7 f9 idiv ecx (single-operand form; writes rax=quot rdx=rem)
+ let insns = decode_bytes(&[0xf7, 0xf9], 0x10000, 4).unwrap();
+ let seq = lift_instructions(&insns);
+ assert!(seq.ops.iter().any(|o| o.opcode == OpCode::IntSDiv));
+ assert!(seq.ops.iter().any(|o| o.opcode == OpCode::IntSRem));
+ }
+
#[test]
fn lift_lea_encodes_effective_address() {
// 48 8d 45 08 lea rax, [rbp+8]
diff --git a/crates/ghidrust-ssa/src/lib.rs b/crates/ghidrust-ssa/src/lib.rs
index 2a63761..cc9fe71 100644
--- a/crates/ghidrust-ssa/src/lib.rs
+++ b/crates/ghidrust-ssa/src/lib.rs
@@ -24,8 +24,8 @@
pub mod ssa;
pub use ssa::{
- build_ssa, copy_propagate, dump_ssa, PhiNode, SsaBlock, SsaFunction, SsaOp, SsaOperand,
- SsaValue,
+ build_ssa, const_fold, copy_propagate, dead_code_eliminate, dump_ssa, load_store_propagate,
+ PhiNode, SsaBlock, SsaFunction, SsaOp, SsaOperand, SsaValue,
};
use ghidrust_ir::{BasicBlock, IrSequence, OpCode, PcodeOp, Varnode};
diff --git a/crates/ghidrust-ssa/src/ssa.rs b/crates/ghidrust-ssa/src/ssa.rs
index eff63ff..2eedd46 100644
--- a/crates/ghidrust-ssa/src/ssa.rs
+++ b/crates/ghidrust-ssa/src/ssa.rs
@@ -418,6 +418,328 @@ fn format_operand(op: &SsaOperand) -> String {
}
}
+/// Constant fold pure arithmetic on `SsaOp` inputs.
+///
+/// Iterates until fixed point (bounded by a small max) rewriting ops whose
+/// inputs are both constants into a `Copy` from a fresh
+/// [`SsaOperand::Const`] with the folded value. Only wraps arithmetic that
+/// has a well-defined 64-bit two's-complement semantic (add/sub/xor/and/or,
+/// small shifts, negate, not, equality) — anything that would require
+/// full-width overflow reasoning (mul, sdiv) is left alone.
+///
+/// Returns the total number of ops rewritten.
+pub fn const_fold(func: &mut SsaFunction) -> usize {
+ let mut total = 0usize;
+ for _ in 0..8 {
+ let mut rewrote = 0usize;
+ for b in &mut func.blocks {
+ for op in &mut b.ops {
+ let Some(dst) = op.output else {
+ continue;
+ };
+ let a_const = op.inputs.first().and_then(SsaOperand::as_const);
+ let b_const = op.inputs.get(1).and_then(SsaOperand::as_const);
+ let width = dst.size.max(1);
+ let mask = if width >= 8 { u64::MAX } else { (1u64 << (width * 8)) - 1 };
+ let folded = match op.opcode {
+ OpCode::IntAdd => match (a_const, b_const) {
+ (Some(a), Some(b)) => Some(a.wrapping_add(b) & mask),
+ _ => None,
+ },
+ OpCode::IntSub => match (a_const, b_const) {
+ (Some(a), Some(b)) => Some(a.wrapping_sub(b) & mask),
+ _ => None,
+ },
+ OpCode::IntXor => match (a_const, b_const) {
+ (Some(a), Some(b)) => Some((a ^ b) & mask),
+ _ => None,
+ },
+ OpCode::IntAnd => match (a_const, b_const) {
+ (Some(a), Some(b)) => Some((a & b) & mask),
+ _ => None,
+ },
+ OpCode::IntOr => match (a_const, b_const) {
+ (Some(a), Some(b)) => Some((a | b) & mask),
+ _ => None,
+ },
+ OpCode::IntLeft => match (a_const, b_const) {
+ (Some(a), Some(b)) if b < 64 => Some((a.wrapping_shl(b as u32)) & mask),
+ _ => None,
+ },
+ OpCode::IntRight => match (a_const, b_const) {
+ (Some(a), Some(b)) if b < 64 => Some((a.wrapping_shr(b as u32)) & mask),
+ _ => None,
+ },
+ OpCode::IntSRight => match (a_const, b_const) {
+ (Some(a), Some(b)) if b < 64 => {
+ Some((((a as i64).wrapping_shr(b as u32)) as u64) & mask)
+ }
+ _ => None,
+ },
+ OpCode::IntNegate => a_const.map(|a| (0u64.wrapping_sub(a)) & mask),
+ OpCode::IntNot => a_const.map(|a| (!a) & mask),
+ OpCode::IntEqual => match (a_const, b_const) {
+ (Some(a), Some(b)) => Some(if a == b { 1 } else { 0 }),
+ _ => None,
+ },
+ OpCode::IntNotEqual => match (a_const, b_const) {
+ (Some(a), Some(b)) => Some(if a != b { 1 } else { 0 }),
+ _ => None,
+ },
+ OpCode::IntLess => match (a_const, b_const) {
+ (Some(a), Some(b)) => Some(if a < b { 1 } else { 0 }),
+ _ => None,
+ },
+ OpCode::IntLessEqual => match (a_const, b_const) {
+ (Some(a), Some(b)) => Some(if a <= b { 1 } else { 0 }),
+ _ => None,
+ },
+ OpCode::IntSLess => match (a_const, b_const) {
+ (Some(a), Some(b)) => Some(if (a as i64) < (b as i64) { 1 } else { 0 }),
+ _ => None,
+ },
+ OpCode::IntSLessEqual => match (a_const, b_const) {
+ (Some(a), Some(b)) => {
+ Some(if (a as i64) <= (b as i64) { 1 } else { 0 })
+ }
+ _ => None,
+ },
+ OpCode::IntZExt | OpCode::IntSExt | OpCode::Copy | OpCode::Cast => {
+ // Extension of a const is that const truncated /
+ // sign-extended to the destination width.
+ a_const.map(|a| match op.opcode {
+ OpCode::IntSExt => {
+ let src_size = op
+ .inputs
+ .first()
+ .map(|v| v.varnode().size)
+ .unwrap_or(width);
+ if src_size >= 8 {
+ a & mask
+ } else {
+ let bits = (src_size * 8) as u32;
+ let sign_bit = 1u64 << (bits - 1);
+ if a & sign_bit != 0 {
+ let ext = !((1u64 << bits) - 1);
+ (a | ext) & mask
+ } else {
+ a & mask
+ }
+ }
+ }
+ _ => a & mask,
+ })
+ }
+ _ => None,
+ };
+ if let Some(v) = folded {
+ op.opcode = OpCode::Copy;
+ op.inputs = vec![SsaOperand::Const(Varnode {
+ space: AddrSpace::Constant,
+ offset: v,
+ size: dst.size,
+ })];
+ rewrote += 1;
+ }
+ }
+ }
+ total += rewrote;
+ if rewrote == 0 {
+ break;
+ }
+ // Re-run copy propagation between folds so downstream ops see the
+ // new constants immediately.
+ copy_propagate(func);
+ }
+ total
+}
+
+/// Dead-code elimination: drop `SsaOp`s whose output is never used and
+/// whose opcode has no side effect. Phis with unused outputs are also
+/// dropped. Ops that touch memory / control flow (`Load`, `Store`, `Call`,
+/// `Push`, `Pop`, `Return`, branch family, `Trap`, `Nop`, `Unimplemented`)
+/// are always kept — DCE deliberately preserves any op that could observe
+/// or perturb program state.
+///
+/// Returns the number of ops (including phis) removed. May be called
+/// repeatedly until it returns zero.
+pub fn dead_code_eliminate(func: &mut SsaFunction) -> usize {
+ let mut total = 0usize;
+ for _ in 0..32 {
+ // Collect all values used anywhere.
+ let mut used: BTreeSet<SsaValue> = BTreeSet::new();
+ // Seed "return-value" registers as implicit uses so ABI-visible
+ // writes (e.g. `xor eax, eax` before `ret`) aren't discarded. On
+ // x86-64 SysV / Windows the integer return register is rax (offset
+ // 0); we also treat rdx (offset 2) as a potential high-half return
+ // to be safe. This matches Ghidra Decompiler's default liveness for
+ // integer functions — we don't yet track floating-point returns.
+ for b in &func.blocks {
+ for op in &b.ops {
+ if let Some(out) = op.output {
+ if out.space == AddrSpace::Register && (out.offset == 0 || out.offset == 2) {
+ used.insert(out);
+ }
+ }
+ }
+ for phi in &b.phis {
+ if phi.out.space == AddrSpace::Register
+ && (phi.out.offset == 0 || phi.out.offset == 2)
+ {
+ used.insert(phi.out);
+ }
+ }
+ }
+ for b in &func.blocks {
+ for op in &b.ops {
+ mark_used(&op.inputs, &mut used);
+ }
+ for phi in &b.phis {
+ for (_, val) in &phi.incoming {
+ if let Some(v) = val {
+ used.insert(*v);
+ }
+ }
+ }
+ }
+ let mut removed = 0usize;
+ for b in &mut func.blocks {
+ let before = b.ops.len();
+ b.ops.retain(|op| {
+ if !opcode_pure(op.opcode) {
+ return true;
+ }
+ match op.output {
+ Some(out) => used.contains(&out),
+ None => true,
+ }
+ });
+ removed += before - b.ops.len();
+ let before_phi = b.phis.len();
+ b.phis.retain(|phi| used.contains(&phi.out));
+ removed += before_phi - b.phis.len();
+ }
+ total += removed;
+ if removed == 0 {
+ break;
+ }
+ }
+ total
+}
+
+fn mark_used(inputs: &[SsaOperand], used: &mut BTreeSet<SsaValue>) {
+ for inp in inputs {
+ if let SsaOperand::Value(v) = inp {
+ used.insert(*v);
+ }
+ }
+}
+
+/// True when the opcode has no observable side-effect beyond writing its
+/// SSA output. DCE is only safe to drop these when the output is dead.
+fn opcode_pure(op: OpCode) -> bool {
+ matches!(
+ op,
+ OpCode::Copy
+ | OpCode::IntAdd
+ | OpCode::IntSub
+ | OpCode::IntXor
+ | OpCode::IntAnd
+ | OpCode::IntOr
+ | OpCode::IntMult
+ | OpCode::IntDiv
+ | OpCode::IntSDiv
+ | OpCode::IntRem
+ | OpCode::IntSRem
+ | OpCode::IntLeft
+ | OpCode::IntRight
+ | OpCode::IntSRight
+ | OpCode::IntNegate
+ | OpCode::IntNot
+ | OpCode::IntEqual
+ | OpCode::IntNotEqual
+ | OpCode::IntLess
+ | OpCode::IntLessEqual
+ | OpCode::IntSLess
+ | OpCode::IntSLessEqual
+ | OpCode::IntSExt
+ | OpCode::IntZExt
+ | OpCode::BoolAnd
+ | OpCode::BoolOr
+ | OpCode::BoolNegate
+ | OpCode::Cast
+ | OpCode::Piece
+ | OpCode::Subpiece
+ | OpCode::Ptradd
+ )
+}
+
+/// Load / store propagation (conservative alias rules).
+///
+/// Recognises the specific idiom `Store addr, val` followed later in the
+/// same block by `Load addr` where `addr` is exactly the same SSA operand
+/// (including version). The subsequent load's output is rewritten to
+/// forward the stored value directly, which lets downstream copy-prop and
+/// DCE remove the redundant round-trip. Anything with even weak aliasing
+/// ambiguity (different address versions, another store between, a call in
+/// between, a different address space) is left untouched.
+///
+/// Returns the number of load ops rewritten. Loads that were replaced
+/// stay as `Copy` from the propagated value so `SsaFunction` invariants
+/// (per-value single-def in SSA) hold.
+pub fn load_store_propagate(func: &mut SsaFunction) -> usize {
+ let mut rewrote = 0usize;
+ for b in &mut func.blocks {
+ // Iterate index-by-index because we may mutate later ops.
+ for i in 0..b.ops.len() {
+ let (addr_key, stored_val) = match &b.ops[i] {
+ op if op.opcode == OpCode::Store => {
+ let Some(addr) = op.inputs.first() else {
+ continue;
+ };
+ let Some(val) = op.inputs.get(1) else {
+ continue;
+ };
+ (addr.clone(), val.clone())
+ }
+ _ => continue,
+ };
+ // Walk forward until an alias-breaking op or the next definition
+ // of `addr` / a load of the same addr.
+ for j in (i + 1)..b.ops.len() {
+ let opcode_j = b.ops[j].opcode;
+ // Bail on anything that could redefine memory beneath us.
+ if matches!(
+ opcode_j,
+ OpCode::Store
+ | OpCode::Call
+ | OpCode::CallInd
+ | OpCode::Return
+ | OpCode::Push
+ | OpCode::Pop
+ | OpCode::Trap
+ ) {
+ break;
+ }
+ if opcode_j == OpCode::Load {
+ let Some(load_addr) = b.ops[j].inputs.first().cloned() else {
+ break;
+ };
+ if load_addr == addr_key {
+ // Rewrite the load's op stream to a Copy of the
+ // stored value; leave the output def alone so SSA
+ // continues to type-check.
+ b.ops[j].opcode = OpCode::Copy;
+ b.ops[j].inputs = vec![stored_val.clone()];
+ rewrote += 1;
+ }
+ }
+ }
+ }
+ }
+ rewrote
+}
+
/// Copy-propagation: replace a chain of `Copy` ops with the ultimate source,
/// when the source itself is a value / const (not another chain). Runs after
/// [`build_ssa`] and mutates the function in place. Returns the number of
@@ -432,6 +754,13 @@ pub fn copy_propagate(func: &mut SsaFunction) -> usize {
for op in &b.ops {
if op.opcode == OpCode::Copy {
if let (Some(out), Some(src)) = (op.output, op.inputs.first()) {
+ // Skip identity copies (`x = x`) that would introduce a
+ // self-cycle in the source table.
+ if let SsaOperand::Value(v) = src {
+ if *v == out {
+ continue;
+ }
+ }
sources.insert(out, src.clone());
}
}
@@ -600,6 +929,131 @@ mod tests {
assert!(dump.contains("reg0#"), "dump should show versioned rax: {dump}");
}
+ #[test]
+ fn const_fold_reduces_add_of_two_constants() {
+ // t0 = 0x100; t1 = 0x20; t2 = t0 + t1; return t2
+ let mut seq = IrSequence::new();
+ let t0 = Varnode::unique(0, 8);
+ let t1 = Varnode::unique(1, 8);
+ let t2 = Varnode::unique(2, 8);
+ seq.push_addressed(
+ 0x0,
+ 1,
+ PcodeOp::new(OpCode::Copy, Some(t0.clone()), vec![Varnode::constant(0x100, 8)]),
+ );
+ seq.push_addressed(
+ 0x1,
+ 1,
+ PcodeOp::new(OpCode::Copy, Some(t1.clone()), vec![Varnode::constant(0x20, 8)]),
+ );
+ seq.push_addressed(
+ 0x2,
+ 1,
+ PcodeOp::new(OpCode::IntAdd, Some(t2.clone()), vec![t0, t1]),
+ );
+ seq.push_addressed(0x3, 1, PcodeOp::new(OpCode::Return, None, vec![t2]));
+ let cfg = build_cfg(&seq, 0x0, 0x4);
+ let mut func = build_ssa(&cfg);
+ copy_propagate(&mut func);
+ let rewrote = const_fold(&mut func);
+ assert!(rewrote > 0, "const_fold should rewrite the add");
+ let ret = func.blocks[0]
+ .ops
+ .iter()
+ .find(|o| o.opcode == OpCode::Return)
+ .expect("return");
+ assert_eq!(ret.inputs[0].as_const(), Some(0x120));
+ }
+
+ #[test]
+ fn dce_drops_unused_pure_ops() {
+ // t0 = 1; t1 = 2; t2 = t0 + t1; (t2 is never used → DCE drops all three)
+ // return (no operands)
+ let mut seq = IrSequence::new();
+ let t0 = Varnode::unique(0, 8);
+ let t1 = Varnode::unique(1, 8);
+ let t2 = Varnode::unique(2, 8);
+ seq.push_addressed(
+ 0x0,
+ 1,
+ PcodeOp::new(OpCode::Copy, Some(t0.clone()), vec![Varnode::constant(1, 8)]),
+ );
+ seq.push_addressed(
+ 0x1,
+ 1,
+ PcodeOp::new(OpCode::Copy, Some(t1.clone()), vec![Varnode::constant(2, 8)]),
+ );
+ seq.push_addressed(
+ 0x2,
+ 1,
+ PcodeOp::new(OpCode::IntAdd, Some(t2), vec![t0, t1]),
+ );
+ seq.push_addressed(0x3, 1, PcodeOp::new(OpCode::Return, None, vec![]));
+ let cfg = build_cfg(&seq, 0x0, 0x4);
+ let mut func = build_ssa(&cfg);
+ let before = func.blocks[0].ops.len();
+ let removed = dead_code_eliminate(&mut func);
+ assert!(removed >= 3, "expected at least 3 dead ops removed; got {removed}");
+ assert!(func.blocks[0].ops.len() < before);
+ // Return must survive because it's a control-flow op.
+ assert!(func.blocks[0]
+ .ops
+ .iter()
+ .any(|o| o.opcode == OpCode::Return));
+ }
+
+ #[test]
+ fn load_store_propagate_forwards_stored_value() {
+ // *addr = t0; t1 = *addr; return t1
+ let mut seq = IrSequence::new();
+ let addr = Varnode::unique(9, 8);
+ let val = Varnode::unique(10, 8);
+ let dst = Varnode::unique(11, 8);
+ seq.push_addressed(
+ 0x0,
+ 1,
+ PcodeOp::new(
+ OpCode::Copy,
+ Some(addr.clone()),
+ vec![Varnode::constant(0x1000, 8)],
+ ),
+ );
+ seq.push_addressed(
+ 0x1,
+ 1,
+ PcodeOp::new(
+ OpCode::Copy,
+ Some(val.clone()),
+ vec![Varnode::constant(0xabcd, 8)],
+ ),
+ );
+ seq.push_addressed(
+ 0x2,
+ 1,
+ PcodeOp::new(OpCode::Store, None, vec![addr.clone(), val.clone()]),
+ );
+ seq.push_addressed(
+ 0x3,
+ 1,
+ PcodeOp::new(OpCode::Load, Some(dst.clone()), vec![addr]),
+ );
+ seq.push_addressed(0x4, 1, PcodeOp::new(OpCode::Return, None, vec![dst]));
+ let cfg = build_cfg(&seq, 0x0, 0x5);
+ let mut func = build_ssa(&cfg);
+ let rewrote = load_store_propagate(&mut func);
+ assert!(rewrote > 0, "load should have been forwarded");
+ // The Load turned into a Copy; run copy_propagate + const_fold to
+ // show the final return propagated the constant.
+ copy_propagate(&mut func);
+ let _ = const_fold(&mut func);
+ let ret = func.blocks[0]
+ .ops
+ .iter()
+ .find(|o| o.opcode == OpCode::Return)
+ .expect("return");
+ assert_eq!(ret.inputs[0].as_const(), Some(0xabcd));
+ }
+
#[test]
fn copy_propagate_forwards_through_copies() {
// Synthetic: t0 = 0x1234, t1 = t0, t2 = t1; return t2 → should
diff --git a/crates/ghidrust-structure/src/lib.rs b/crates/ghidrust-structure/src/lib.rs
index e24f095..6d210f8 100644
--- a/crates/ghidrust-structure/src/lib.rs
+++ b/crates/ghidrust-structure/src/lib.rs
@@ -119,6 +119,16 @@ pub enum Region {
},
/// `return;` — a block whose terminator is [`OpCode::Return`].
Return(u32),
+ /// `break;` — an edge from inside a natural loop to the loop's
+ /// canonical exit block. Emitted by the structurer when the target of
+ /// what would otherwise be a `Goto(exit)` is exactly the enclosing
+ /// loop's exit successor. Falls back to `Goto` when the exit set is
+ /// ambiguous.
+ Break,
+ /// `continue;` — an edge from inside a natural loop back to the loop
+ /// header that isn't the natural latch. Rendered by Stage-1 as a bare
+ /// `continue;` inside the enclosing `while`/`for`/`do-while`.
+ Continue,
/// `goto block_<id>;` — unstructured fallback for edges that don't fit
/// any pattern (irreducible graphs, unresolved indirect branches).
Goto(u32),
@@ -185,6 +195,7 @@ impl Region {
pub fn block_count(&self) -> usize {
match self {
Region::Block(_) | Region::Return(_) | Region::Goto(_) => 1,
+ Region::Break | Region::Continue => 1,
Region::Seq(rs) => rs.iter().map(|r| r.block_count()).sum(),
Region::IfThen { then_branch, .. } => 1 + then_branch.block_count(),
Region::IfThenElse {
@@ -214,6 +225,7 @@ impl Region {
pub fn depth(&self) -> usize {
match self {
Region::Block(_) | Region::Return(_) | Region::Goto(_) => 0,
+ Region::Break | Region::Continue => 0,
Region::Seq(rs) => rs.iter().map(|r| r.depth()).max().unwrap_or(0),
Region::IfThen { then_branch, .. } => 1 + then_branch.depth(),
Region::IfThenElse {
@@ -257,6 +269,7 @@ impl Region {
Region::Block(b) | Region::Return(b) | Region::Goto(b) => {
set.insert(*b);
}
+ Region::Break | Region::Continue => {}
Region::Seq(rs) => rs.iter().for_each(|r| r.collect_blocks(set)),
Region::IfThen { header, then_branch } => {
set.insert(*header);
@@ -365,6 +378,7 @@ pub fn structure_function_with_hints(
pdom: &pdom,
loops: &loops,
switches: &switch_targets,
+ loop_stack: Vec::new(),
};
let mut visited: HashSet<u32> = HashSet::new();
let raw = ctx.build_region_from(ENTRY_BLOCK, None, &mut visited);
@@ -497,6 +511,19 @@ struct StructCtx<'a> {
pdom: &'a [u32],
loops: &'a [NaturalLoop],
switches: &'a BTreeMap<u32, ResolvedSwitch>,
+ /// Stack of enclosing loops so nested regions can emit `break;` /
+ /// `continue;` instead of goto when they hit the loop's canonical exit
+ /// or its header. The innermost loop is at the top of the stack.
+ loop_stack: Vec<LoopFrame>,
+}
+
+#[derive(Debug, Clone)]
+struct LoopFrame {
+ header: u32,
+ /// Canonical exit block for this loop (first successor of any body
+ /// block that leaves the loop). `None` means the loop has no natural
+ /// exit successor and `Break` won't be synthesised.
+ exit: Option<u32>,
}
impl<'a> StructCtx<'a> {
@@ -513,14 +540,11 @@ impl<'a> StructCtx<'a> {
break;
}
if !visited.insert(b) {
- // Already emitted somewhere else — stop expansion but leave
- // a goto so control-flow is still visible in the printed
- // structure.
- if !seq.is_empty() {
- // Terminate the chain here; the outer emit_region will
- // print a `goto block_<b>;` as its last statement.
- }
- seq.push(Region::Goto(b));
+ // Already emitted somewhere else. Prefer break/continue
+ // over goto when the target matches the enclosing loop's
+ // exit or header — that keeps the printed structure
+ // gotoless for the common Cifuentes shapes.
+ seq.push(self.loop_terminator_for(b));
break;
}
@@ -620,12 +644,22 @@ impl<'a> StructCtx<'a> {
seq.push(Region::Block(b));
let next: Option<u32> = match succs.as_slice() {
[] => None,
- [s] => Some(*s),
+ [s] => {
+ // If this single-successor edge would leave the
+ // enclosing loop, emit a `break;` instead of a
+ // fall-through so the loop body stays gotoless.
+ if let Some(term) = self.loop_exit_terminator(*s) {
+ seq.push(term);
+ None
+ } else {
+ Some(*s)
+ }
+ }
_ => {
// >2 successors (e.g. switch, indirect) — fall through
// to goto for the first, others are unreachable at this
// stage. Switch structuring is deferred.
- seq.push(Region::Goto(succs[0]));
+ seq.push(self.loop_terminator_for(succs[0]));
None
}
};
@@ -634,6 +668,82 @@ impl<'a> StructCtx<'a> {
collapse_seq(seq)
}
+ /// Pick the "cheapest" terminator for a control-flow edge from the
+ /// current context to `target`: prefer `Continue` when the target is
+ /// the innermost enclosing loop header, `Break` when it's that
+ /// loop's canonical exit, an inline `Return(target)` when the target
+ /// is a return-only block (Cifuentes' return-duplication rule keeps
+ /// gotos out of arms that would otherwise re-emit the same trivial
+ /// return), and fall back to `Goto` otherwise.
+ fn loop_terminator_for(&self, target: u32) -> Region {
+ for frame in self.loop_stack.iter().rev() {
+ if frame.header == target {
+ return Region::Continue;
+ }
+ if frame.exit == Some(target) {
+ return Region::Break;
+ }
+ }
+ if self.is_trivial_return_block(target) {
+ return Region::Return(target);
+ }
+ Region::Goto(target)
+ }
+
+ /// A "trivial" return block has zero side-effecting ops before its
+ /// terminating `Return` — safe to duplicate inline in place of a
+ /// `goto block_<id>;` that would otherwise re-target the same
+ /// register-writing return. Intermediate Return ops (from post-ret
+ /// dead-code that the leader analysis chose not to split off) are
+ /// accepted because the emitted `return;` collapses them.
+ fn is_trivial_return_block(&self, b: u32) -> bool {
+ let Some(block) = self.ssa.blocks.get(b as usize) else {
+ return false;
+ };
+ if !matches!(block.ops.last().map(|o| o.opcode), Some(OpCode::Return)) {
+ return false;
+ }
+ for op in block.ops.iter().take(block.ops.len().saturating_sub(1)) {
+ match op.opcode {
+ OpCode::Nop | OpCode::Return => {}
+ OpCode::Copy
+ | OpCode::IntXor
+ | OpCode::IntAnd
+ | OpCode::IntOr
+ | OpCode::IntAdd
+ | OpCode::IntSub
+ | OpCode::IntEqual
+ | OpCode::IntNotEqual
+ | OpCode::IntLess
+ | OpCode::IntLessEqual
+ | OpCode::IntSLess
+ | OpCode::IntSLessEqual
+ | OpCode::IntSExt
+ | OpCode::IntZExt => {
+ if op.output.is_none() {
+ return false;
+ }
+ }
+ _ => return false,
+ }
+ }
+ true
+ }
+
+ /// When `succ` is the innermost enclosing loop's exit, return
+ /// `Some(Break)`. Otherwise return `None` so the caller keeps the
+ /// natural fall-through.
+ fn loop_exit_terminator(&self, succ: u32) -> Option<Region> {
+ let frame = self.loop_stack.last()?;
+ if frame.exit == Some(succ) {
+ Some(Region::Break)
+ } else if frame.header == succ {
+ Some(Region::Continue)
+ } else {
+ None
+ }
+ }
+
/// Find the loop whose header is `b`, if any.
fn loop_at(&self, b: u32) -> Option<&'a NaturalLoop> {
self.loops.iter().find(|l| l.header == b)
@@ -661,6 +771,14 @@ impl<'a> StructCtx<'a> {
.find(|s| l.body.contains(s))
.unwrap_or(l.header);
+ // Push a loop frame so descendant regions can emit `break;` /
+ // `continue;` for edges that hit the exit / header.
+ let exit = self.loop_exit(l);
+ self.loop_stack.push(LoopFrame {
+ header: l.header,
+ exit,
+ });
+
let body_region = if header_cbr {
// Emit body starting from the loop-body successor, stopping at the
// header itself (natural back-edge).
@@ -670,6 +788,8 @@ impl<'a> StructCtx<'a> {
self.build_region_from(l.header, Some(l.header), &mut inner_visited)
};
+ self.loop_stack.pop();
+
// Restore the outer visited set + record the whole loop body.
*visited = outer_visited;
for b in &l.body {
@@ -935,6 +1055,8 @@ fn render(r: &Region, indent: usize, out: &mut String) {
match r {
Region::Block(b) => out.push_str(&format!("{pad}block_{b};\n")),
Region::Return(b) => out.push_str(&format!("{pad}return; // block_{b}\n")),
+ Region::Break => out.push_str(&format!("{pad}break;\n")),
+ Region::Continue => out.push_str(&format!("{pad}continue;\n")),
Region::Goto(b) => out.push_str(&format!("{pad}goto block_{b};\n")),
Region::Seq(rs) => {
for r in rs {
@@ -1079,7 +1201,11 @@ pub fn flatten_short_circuit(r: Region, ssa: &SsaFunction) -> Region {
then_branch: Box::new(flatten_short_circuit(*then_branch, ssa)),
else_branch: else_branch.map(|e| Box::new(flatten_short_circuit(*e, ssa))),
},
- leaf @ (Region::Block(_) | Region::Return(_) | Region::Goto(_)) => leaf,
+ leaf @ (Region::Block(_)
+ | Region::Return(_)
+ | Region::Goto(_)
+ | Region::Break
+ | Region::Continue) => leaf,
}
}
@@ -1210,6 +1336,82 @@ pub fn loop_count(report: &StructureReport) -> usize {
report.loops.len()
}
+/// Count of `Region::Goto` leaves in the recovered structure tree — the
+/// primary "unstructured escape" indicator. Break/Continue don't count
+/// (they're structured escapes). Combined with [`region_leaf_count`] this
+/// yields the Phase D `goto_rate` metric.
+pub fn goto_count(region: &Region) -> usize {
+ match region {
+ Region::Goto(_) => 1,
+ Region::Seq(rs) => rs.iter().map(goto_count).sum(),
+ Region::IfThen { then_branch, .. } => goto_count(then_branch),
+ Region::IfThenElse {
+ then_branch,
+ else_branch,
+ ..
+ } => goto_count(then_branch) + goto_count(else_branch),
+ Region::While { body, .. }
+ | Region::DoWhile { body, .. }
+ | Region::Loop { body, .. } => goto_count(body),
+ Region::Switch { cases, default, .. } => {
+ cases.iter().map(|c| goto_count(&c.body)).sum::<usize>()
+ + default.as_ref().map(|d| goto_count(d)).unwrap_or(0)
+ }
+ Region::ShortCircuit {
+ then_branch,
+ else_branch,
+ ..
+ } => {
+ goto_count(then_branch)
+ + else_branch.as_ref().map(|e| goto_count(e)).unwrap_or(0)
+ }
+ _ => 0,
+ }
+}
+
+/// Count of every leaf statement in a region — used as the denominator
+/// for the `goto_rate` metric. Every terminal region (Block, Return, Goto,
+/// Break, Continue) counts as one leaf.
+pub fn region_leaf_count(region: &Region) -> usize {
+ match region {
+ Region::Block(_)
+ | Region::Return(_)
+ | Region::Goto(_)
+ | Region::Break
+ | Region::Continue => 1,
+ Region::Seq(rs) => rs.iter().map(region_leaf_count).sum(),
+ Region::IfThen { then_branch, .. } => 1 + region_leaf_count(then_branch),
+ Region::IfThenElse {
+ then_branch,
+ else_branch,
+ ..
+ } => 1 + region_leaf_count(then_branch) + region_leaf_count(else_branch),
+ Region::While { body, .. }
+ | Region::DoWhile { body, .. }
+ | Region::Loop { body, .. } => 1 + region_leaf_count(body),
+ Region::Switch { cases, default, .. } => {
+ 1 + cases.iter().map(|c| region_leaf_count(&c.body)).sum::<usize>()
+ + default.as_ref().map(|d| region_leaf_count(d)).unwrap_or(0)
+ }
+ Region::ShortCircuit {
+ then_branch,
+ else_branch,
+ ..
+ } => {
+ 1 + region_leaf_count(then_branch)
+ + else_branch.as_ref().map(|e| region_leaf_count(e)).unwrap_or(0)
+ }
+ }
+}
+
+/// `goto_rate = goto_count / max(1, region_leaf_count)`. The Phase D gate
+/// is < 0.15 on the lab fixture; consumers can also report this metric
+/// on shared-entry corpora.
+pub fn goto_rate(region: &Region) -> f32 {
+ let leaves = region_leaf_count(region).max(1);
+ goto_count(region) as f32 / leaves as f32
+}
+
/// Convenience: how many distinct blocks the structured tree references.
pub fn coverage(report: &StructureReport) -> usize {
report.region.touched_blocks().len()
@@ -1456,6 +1658,69 @@ mod tests {
assert!(text.contains("&&"), "compound && should render:\n{text}");
}
+ #[test]
+ fn loop_with_body_exit_emits_break_instead_of_goto() {
+ // 0x0: unconditional jmp → 0x2 (loop header, block b1)
+ // 0x2: cbranch to 0x8 (exit) fallthrough 0x4
+ // 0x4: unconditional jmp → 0x6 (body block)
+ // 0x6: unconditional jmp → 0x2 (latch)
+ // 0x8: return
+ // Body path (0x4→0x6→0x2) forms the loop; an artificial "escape" is
+ // not present in this shape but the header cbranch itself already
+ // exits to 0x8 → the exit is 0x8. The re-visit of the header from
+ // the latch should be a Continue.
+ let mut seq = IrSequence::new();
+ seq.push_addressed(
+ 0x0,
+ 2,
+ PcodeOp::new(OpCode::Branch, None, vec![Varnode::constant(0x2, 8)]),
+ );
+ seq.push_addressed(
+ 0x2,
+ 2,
+ PcodeOp::new(
+ OpCode::CBranch,
+ None,
+ vec![Varnode::unique(0, 1), Varnode::constant(0x8, 8)],
+ ),
+ );
+ seq.push_addressed(
+ 0x4,
+ 2,
+ PcodeOp::new(OpCode::Branch, None, vec![Varnode::constant(0x6, 8)]),
+ );
+ seq.push_addressed(
+ 0x6,
+ 2,
+ PcodeOp::new(OpCode::Branch, None, vec![Varnode::constant(0x2, 8)]),
+ );
+ seq.push_addressed(0x8, 1, PcodeOp::new(OpCode::Return, None, vec![]));
+ let cfg = build_cfg(&seq, 0x0, 0x9);
+ let ssa = build_ssa(&cfg);
+ let rep = structure_function(&cfg, &ssa);
+ let text = dump_region(&rep.region);
+ // With break/continue plumbing, the structured region should be a
+ // While over the header with no `goto block_` in the body.
+ assert!(text.contains("while"), "expected while:\n{text}");
+ assert!(
+ goto_count(&rep.region) == 0,
+ "expected zero gotos, tree:\n{text}"
+ );
+ }
+
+ #[test]
+ fn goto_rate_zero_on_diamond() {
+ let bytes = [0x39, 0xc1, 0x74, 0x02, 0x31, 0xc0, 0xc3, 0x31, 0xc9, 0xc3];
+ let rep = structure_bytes(&bytes, 0x2000);
+ let rate = goto_rate(&rep.region);
+ assert!(
+ rate < 0.15,
+ "diamond should have goto_rate <0.15, got {}\nRegion tree:\n{}",
+ rate,
+ dump_region(&rep.region)
+ );
+ }
+
#[test]
fn short_circuit_or_flattens_matching_then_bodies() {
// IfThenElse { A, then=Return(2), else = IfThen { B, Return(2) } } → A || B
diff --git a/crates/ghidrust-types/src/lib.rs b/crates/ghidrust-types/src/lib.rs
index 35a866d..5d91201 100644
--- a/crates/ghidrust-types/src/lib.rs
+++ b/crates/ghidrust-types/src/lib.rs
@@ -41,7 +41,13 @@ use std::collections::{BTreeMap, BTreeSet};
/// Small type lattice — see module docs. Kept intentionally compact; new
/// buckets should join in through `join` / `refine` without breaking the
/// existing monotonicity contract.
-#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
+///
+/// Phase-C additions carry structural shape information without turning the
+/// lattice into a full C type system: pointer-target width, void return, and
+/// struct/array seeds. The join rule keeps everything monotone — new
+/// observations either widen a width, promote a scalar to a struct-typed
+/// pointer, or collapse to `Any` when observations conflict.
+#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum RustType {
/// No info observed yet.
Bottom,
@@ -52,11 +58,28 @@ pub enum RustType {
/// Width in bytes (1, 2, 4, 8).
width: u32,
},
+ /// Signed integer variant. Introduced by explicit `IntSExt` /
+ /// `IntSLess*` seeds so Stage-1 emit can print `int32_t` instead of the
+ /// unsigned default. Widths match [`RustType::IntN`].
+ IntSigned { width: u32 },
/// A pointer produced by a `Load`/`Store` address computation.
Ptr {
/// Pointee width in bytes when known; `0` when unknown.
pointee_width: u32,
},
+ /// Void — used for function return type when no register is written.
+ Void,
+ /// A pointer to a recovered struct seed (`ptr_key`), so Stage-1 emit
+ /// can print `struct s_<key>*` and print field accesses as `p->field_N`
+ /// instead of raw `*(uint64_t*)(p + K)`.
+ StructPtr {
+ /// Stable key into [`TypeRecovery::structs`].
+ key: u32,
+ },
+ /// A pointer to a recovered array seed: element width in bytes and the
+ /// count of distinct constant-index touches we observed. `count == 0`
+ /// means unknown / open-ended.
+ ArrayPtr { elem_width: u32, count: u32 },
/// Conflicting observations (top).
Any,
}
@@ -65,9 +88,18 @@ impl RustType {
pub fn int(width: u32) -> Self {
Self::IntN { width }
}
+ pub fn signed(width: u32) -> Self {
+ Self::IntSigned { width }
+ }
pub fn ptr(pointee_width: u32) -> Self {
Self::Ptr { pointee_width }
}
+ pub fn struct_ptr(key: u32) -> Self {
+ Self::StructPtr { key }
+ }
+ pub fn array_ptr(elem_width: u32, count: u32) -> Self {
+ Self::ArrayPtr { elem_width, count }
+ }
/// Least upper bound in the lattice — the meet of two observations.
pub fn join(self, other: Self) -> Self {
@@ -78,13 +110,61 @@ impl RustType {
(IntN { width: a }, IntN { width: b }) => IntN {
width: a.max(b),
},
+ (IntSigned { width: a }, IntSigned { width: b }) => IntSigned {
+ width: a.max(b),
+ },
+ // A signed observation combined with the same-width unsigned
+ // one prefers the signed shape — Stage-1 emit reads the operand
+ // as a signed compare / sext output which is more informative
+ // than the width-only unsigned bucket.
+ (IntSigned { width: a }, IntN { width: b })
+ | (IntN { width: b }, IntSigned { width: a }) => IntSigned {
+ width: a.max(b),
+ },
(Ptr { pointee_width: a }, Ptr { pointee_width: b }) => Ptr {
pointee_width: a.max(b),
},
+ // A struct pointer subsumes an untyped raw pointer with the same
+ // key already known; conflicting keys collapse to `Any`.
+ (StructPtr { key: a }, StructPtr { key: b }) if a == b => StructPtr { key: a },
+ (StructPtr { key }, Ptr { .. }) | (Ptr { .. }, StructPtr { key }) => {
+ StructPtr { key }
+ }
+ // Struct/Array pointer observations subsume the same-width raw
+ // integer seed on the base register (from the ambient Copy /
+ // IntAdd chain that computed the address). This lets Stage-1
+ // treat `rdi` as `struct s_1*` even though the base first flowed
+ // through a `Copy` that seeded `IntN{8}`.
+ (StructPtr { key }, IntN { width: 8 }) | (IntN { width: 8 }, StructPtr { key }) => {
+ StructPtr { key }
+ }
+ (ArrayPtr { elem_width: aw, count: ac }, ArrayPtr { elem_width: bw, count: bc })
+ if aw == bw =>
+ {
+ ArrayPtr { elem_width: aw, count: ac.max(bc) }
+ }
+ (ArrayPtr { elem_width, count }, Ptr { pointee_width })
+ | (Ptr { pointee_width }, ArrayPtr { elem_width, count })
+ if pointee_width == 0 || pointee_width == elem_width =>
+ {
+ ArrayPtr { elem_width, count }
+ }
+ (ArrayPtr { elem_width, count }, IntN { width: 8 })
+ | (IntN { width: 8 }, ArrayPtr { elem_width, count }) => {
+ ArrayPtr { elem_width, count }
+ }
_ => Any,
}
}
+ /// Refine this type toward another observation without ever narrowing
+ /// (monotone). Convenience wrapper over [`Self::join`] that keeps the
+ /// call site readable when we intentionally want side-effect updates.
+ pub fn refine(&mut self, other: Self) {
+ let old = std::mem::replace(self, RustType::Bottom);
+ *self = old.join(other);
+ }
+
pub fn c_style(&self) -> String {
match self {
RustType::Bottom => "undefined".into(),
@@ -96,6 +176,13 @@ impl RustType {
8 => "uint64_t".into(),
w => format!("uint{}_t", w * 8),
},
+ RustType::IntSigned { width } => match width {
+ 1 => "int8_t".into(),
+ 2 => "int16_t".into(),
+ 4 => "int32_t".into(),
+ 8 => "int64_t".into(),
+ w => format!("int{}_t", w * 8),
+ },
RustType::Ptr { pointee_width } => match pointee_width {
0 => "void*".into(),
1 => "uint8_t*".into(),
@@ -104,9 +191,36 @@ impl RustType {
8 => "uint64_t*".into(),
w => format!("uint{}_t*", w * 8),
},
+ RustType::Void => "void".into(),
+ RustType::StructPtr { key } => format!("struct s_{:x}*", key),
+ RustType::ArrayPtr { elem_width, count } => {
+ let base = match elem_width {
+ 1 => "uint8_t".to_string(),
+ 2 => "uint16_t".to_string(),
+ 4 => "uint32_t".to_string(),
+ 8 => "uint64_t".to_string(),
+ w => format!("uint{}_t", w * 8),
+ };
+ if *count == 0 {
+ format!("{base}*")
+ } else {
+ format!("{base}*/*[{count}]*/")
+ }
+ }
RustType::Any => "void*".into(),
}
}
+
+ /// Width in bytes for scalar types; 0 for aggregates / unknown / void.
+ /// Used by prototype rendering when we want a bare `uintN_t` size hint.
+ pub fn scalar_width(&self) -> u32 {
+ match self {
+ RustType::Bool => 1,
+ RustType::IntN { width } | RustType::IntSigned { width } => *width,
+ RustType::Ptr { .. } | RustType::StructPtr { .. } | RustType::ArrayPtr { .. } => 8,
+ _ => 0,
+ }
+ }
}
/// Recovered per-`(space, offset)` types after propagation.
@@ -115,11 +229,14 @@ pub struct TypeMap(pub BTreeMap<(AddrSpace, u64), RustType>);
impl TypeMap {
pub fn get(&self, space: AddrSpace, offset: u64) -> RustType {
- self.0.get(&(space, offset)).copied().unwrap_or(RustType::Bottom)
+ self.0
+ .get(&(space, offset))
+ .cloned()
+ .unwrap_or(RustType::Bottom)
}
pub fn set(&mut self, space: AddrSpace, offset: u64, t: RustType) {
let e = self.0.entry((space, offset)).or_insert(RustType::Bottom);
- *e = e.join(t);
+ *e = e.clone().join(t);
}
pub fn len(&self) -> usize {
self.0.len()
@@ -129,6 +246,40 @@ impl TypeMap {
}
}
+/// One recovered struct: pointer-target seed with concrete field offsets
+/// observed on `Load` / `Store` addresses that read `base + K`.
+///
+/// The `key` is a stable id issued during recovery; Stage-1 emit prints
+/// `struct s_<key>` for typed pointers. Fields are keyed by byte offset
+/// from the base; each field carries the widest access we saw.
+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
+pub struct StructSeed {
+ pub key: u32,
+ /// Byte-offset → (widest width in bytes, refined field type).
+ pub fields: BTreeMap<u64, StructField>,
+ /// Human tag — usually `s_<key>`; can be renamed by the caller.
+ pub tag: String,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct StructField {
+ pub offset: u64,
+ pub width: u32,
+ pub ty: RustType,
+}
+
+impl StructSeed {
+ /// Total observed size in bytes (last field offset + width). Zero for
+ /// empty seeds.
+ pub fn observed_size(&self) -> u64 {
+ self.fields
+ .iter()
+ .last()
+ .map(|(off, f)| off + f.width as u64)
+ .unwrap_or(0)
+ }
+}
+
/// One recovered stack local.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct StackLocal {
@@ -155,19 +306,32 @@ impl LocalMap {
}
}
+/// Where a parameter's storage lives on entry — register or stack slot.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub enum ParamStorage {
+ /// Passed in an integer register (see [`Parameter::register`]).
+ Register(String),
+ /// Passed on the caller-set-up stack slot at `offset` bytes above the
+ /// return address (i.e. after the shadow space on Windows, or the
+ /// spill area on SysV).
+ Stack { offset: u64 },
+}
+
/// One recovered parameter.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Parameter {
/// Zero-based param index in the calling convention order.
pub index: usize,
- /// x86-64 register name (as `ghidrust_lift::X86Reg` label).
+ /// x86-64 register name (as `ghidrust_lift::X86Reg` label). Empty when
+ /// the parameter is stack-passed.
pub register: String,
+ pub storage: ParamStorage,
pub width: u32,
pub name: String,
pub ty: RustType,
}
-#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct ParamList(pub Vec<Parameter>);
impl ParamList {
@@ -191,12 +355,82 @@ pub enum CallConv {
Windows,
}
-/// Full recovery result for a function: types, stack locals, parameters.
+impl Default for RustType {
+ fn default() -> Self {
+ RustType::Bottom
+ }
+}
+
+/// A recovered function signature — the object Stage-1 emit and GUI
+/// `Commit Params / Return` write into `ProgramEdits`.
+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
+pub struct FunctionSignature {
+ pub name: String,
+ pub calling_convention: String,
+ pub return_type: RustType,
+ /// Prototype params in declaration order — includes stack slots when the
+ /// entry block reads them. Each carries recovered type + register/stack
+ /// storage so the caller can render Windows __fastcall or SysV.
+ pub params: ParamList,
+}
+
+impl FunctionSignature {
+ /// Render the signature as a C prototype string:
+ /// `<ret> <name>(<param0>, <param1>, …)` (or `void` for no params).
+ pub fn to_prototype(&self) -> String {
+ let ret = self.return_type.c_style();
+ let mut s = format!("{ret} {}(", self.name);
+ if self.params.is_empty() {
+ s.push_str("void");
+ } else {
+ for (i, p) in self.params.iter().enumerate() {
+ if i > 0 {
+ s.push_str(", ");
+ }
+ s.push_str(&format!("{} {}", p.ty.c_style(), p.name));
+ }
+ }
+ s.push(')');
+ s
+ }
+
+ /// Same as [`Self::to_prototype`] but with the calling-convention keyword
+ /// (`__fastcall` for Windows) inserted before the function name.
+ pub fn to_prototype_with_cc(&self) -> String {
+ let cc = match self.calling_convention.as_str() {
+ "Windows" => "__fastcall ",
+ _ => "",
+ };
+ let ret = self.return_type.c_style();
+ let mut s = format!("{ret} {cc}{}(", self.name);
+ if self.params.is_empty() {
+ s.push_str("void");
+ } else {
+ for (i, p) in self.params.iter().enumerate() {
+ if i > 0 {
+ s.push_str(", ");
+ }
+ s.push_str(&format!("{} {}", p.ty.c_style(), p.name));
+ }
+ }
+ s.push(')');
+ s
+ }
+}
+
+/// Full recovery result for a function: types, stack locals, parameters,
+/// structs, and the resulting prototype.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct TypeRecovery {
pub types: TypeMap,
pub locals: LocalMap,
pub params: ParamList,
+ /// Recovered struct seeds keyed by their stable id.
+ pub structs: BTreeMap<u32, StructSeed>,
+ /// Whole-function prototype (built from `params` + return-type recovery
+ /// after seeding). The `name` field is empty until [`recover_with_name`]
+ /// is called.
+ pub signature: FunctionSignature,
}
impl TypeRecovery {
@@ -251,24 +485,46 @@ fn seed_op(op: &SsaOp, map: &mut TypeMap, flags: &BTreeSet<u64>) {
OpCode::IntEqual
| OpCode::IntNotEqual
| OpCode::IntLess
- | OpCode::IntLessEqual
- | OpCode::IntSLess
- | OpCode::IntSLessEqual => {
+ | OpCode::IntLessEqual => {
+ if let Some(out) = op.output {
+ map.set(out.space, out.offset, RustType::Bool);
+ }
+ }
+ OpCode::IntSLess | OpCode::IntSLessEqual => {
+ // Signed comparison output is bool. We intentionally do NOT
+ // propagate a signed hint back to the inputs — flag setup
+ // (`sf = IntSLess(dst, 0)`) fires on every arithmetic op and
+ // would otherwise blanket-tag registers as signed.
if let Some(out) = op.output {
map.set(out.space, out.offset, RustType::Bool);
}
}
+ OpCode::IntSDiv | OpCode::IntSRem | OpCode::IntSRight => {
+ // Genuine signed arithmetic — outputs are strictly signed.
+ if let Some(out) = op.output {
+ map.set(out.space, out.offset, RustType::signed(out.size));
+ }
+ }
OpCode::Load => {
if let Some(out) = op.output {
map.set(out.space, out.offset, RustType::int(out.size));
}
if let Some(addr) = op.inputs.first().and_then(SsaOperand::as_value) {
- map.set(addr.space, addr.offset, RustType::ptr(op.output.map(|o| o.size).unwrap_or(0)));
+ map.set(
+ addr.space,
+ addr.offset,
+ RustType::ptr(op.output.map(|o| o.size).unwrap_or(0)),
+ );
}
}
OpCode::Store => {
if let Some(addr) = op.inputs.first().and_then(SsaOperand::as_value) {
- let pointee = op.inputs.get(1).and_then(SsaOperand::as_value).map(|v| v.size).unwrap_or(0);
+ let pointee = op
+ .inputs
+ .get(1)
+ .and_then(SsaOperand::as_value)
+ .map(|v| v.size)
+ .unwrap_or(0);
map.set(addr.space, addr.offset, RustType::ptr(pointee));
}
}
@@ -278,12 +534,17 @@ fn seed_op(op: &SsaOp, map: &mut TypeMap, flags: &BTreeSet<u64>) {
| OpCode::IntAnd
| OpCode::IntOr
| OpCode::IntMult
+ | OpCode::IntDiv
+ | OpCode::IntRem
| OpCode::IntLeft
| OpCode::IntRight
- | OpCode::IntSRight
| OpCode::IntNegate
| OpCode::IntNot
- | OpCode::Copy => {
+ | OpCode::IntZExt
+ | OpCode::Copy
+ | OpCode::Cast
+ | OpCode::Piece
+ | OpCode::Subpiece => {
if let Some(out) = op.output {
let t = if flags.contains(&out.offset) && out.space == AddrSpace::Register {
RustType::Bool
@@ -293,6 +554,15 @@ fn seed_op(op: &SsaOp, map: &mut TypeMap, flags: &BTreeSet<u64>) {
map.set(out.space, out.offset, t);
}
}
+ OpCode::Ptradd => {
+ if let Some(out) = op.output {
+ // `base + index * elem_size` — output is address-shaped.
+ map.set(out.space, out.offset, RustType::ptr(0));
+ }
+ if let Some(base) = op.inputs.first().and_then(SsaOperand::as_value) {
+ map.set(base.space, base.offset, RustType::ptr(0));
+ }
+ }
_ => {}
}
}
@@ -342,6 +612,162 @@ pub fn recover_locals(func: &SsaFunction, types: &TypeMap) -> LocalMap {
map
}
+/// Detect struct/array seeds by scanning `Load` / `Store` addresses that
+/// look like `base + K` for multiple constant `K` values on the same SSA
+/// base value. Each recovered pattern is either promoted to a
+/// [`StructSeed`] (distinct offsets) or an array shape (equal-stride
+/// accesses).
+///
+/// Populates [`TypeRecovery::structs`] and refines [`TypeMap`] entries for
+/// the pointer register to [`RustType::StructPtr`] or
+/// [`RustType::ArrayPtr`] as appropriate. Conservative — we never seed a
+/// struct from a single access; two distinct offsets are the minimum.
+pub fn recover_structs(func: &SsaFunction, types: &mut TypeMap) -> BTreeMap<u32, StructSeed> {
+ use ghidrust_ssa::SsaValue;
+ let mut per_base: BTreeMap<SsaValue, BTreeMap<u64, u32>> = BTreeMap::new();
+ for b in &func.blocks {
+ for op in &b.ops {
+ let (addr_operand, access_size) = match op.opcode {
+ OpCode::Load => (op.inputs.first(), op.output.map(|v| v.size).unwrap_or(0)),
+ OpCode::Store => (
+ op.inputs.first(),
+ op.inputs
+ .get(1)
+ .and_then(SsaOperand::as_value)
+ .map(|v| v.size)
+ .unwrap_or(0),
+ ),
+ _ => continue,
+ };
+ let Some(addr) = addr_operand else { continue };
+ let (base, offset) = decompose_addr(addr, func);
+ let Some(base) = base else { continue };
+ if base.space == AddrSpace::Constant {
+ continue;
+ }
+ let entry = per_base.entry(base).or_default();
+ let field = entry.entry(offset).or_insert(0);
+ *field = (*field).max(access_size.max(1));
+ }
+ }
+ let mut structs: BTreeMap<u32, StructSeed> = BTreeMap::new();
+ let mut next_key: u32 = 1;
+ for (base, fields) in per_base {
+ if fields.len() < 2 {
+ continue;
+ }
+ // Array vs struct heuristic: if every field width is equal and the
+ // offsets form an arithmetic progression, promote to array.
+ let widths: BTreeSet<u32> = fields.values().copied().collect();
+ let offs: Vec<u64> = fields.keys().copied().collect();
+ let elem_w = *widths.iter().next().unwrap_or(&0);
+ let is_array = widths.len() == 1
+ && elem_w > 0
+ && offs.windows(2).all(|w| w[1] - w[0] == elem_w as u64);
+ if is_array {
+ types.set(
+ base.space,
+ base.offset,
+ RustType::array_ptr(elem_w, offs.len() as u32),
+ );
+ continue;
+ }
+ let key = next_key;
+ next_key += 1;
+ let mut seed = StructSeed {
+ key,
+ fields: BTreeMap::new(),
+ tag: format!("s_{key:x}"),
+ };
+ for (off, w) in fields {
+ seed.fields.insert(
+ off,
+ StructField {
+ offset: off,
+ width: w,
+ ty: RustType::int(w),
+ },
+ );
+ }
+ types.set(base.space, base.offset, RustType::struct_ptr(key));
+ structs.insert(key, seed);
+ }
+ structs
+}
+
+/// Try to decompose an address operand into `(base_value, constant_offset)`
+/// by walking one hop through preceding `IntAdd`/`Ptradd` chains recorded
+/// as the operand's def. Falls back to `(operand_as_value, 0)` for the
+/// direct-load case (`*base`).
+fn decompose_addr(
+ addr: &SsaOperand,
+ func: &SsaFunction,
+) -> (Option<ghidrust_ssa::SsaValue>, u64) {
+ let SsaOperand::Value(v) = addr else {
+ return (None, 0);
+ };
+ // Search all blocks for the defining op — small n; SSA lookup by output
+ // value is cheap for the fixture corpus. A future refinement can cache
+ // this map per function.
+ for b in &func.blocks {
+ for op in &b.ops {
+ let Some(out) = op.output else { continue };
+ if out == *v && matches!(op.opcode, OpCode::IntAdd | OpCode::Ptradd) {
+ let a = op.inputs.first();
+ let c = op.inputs.get(1);
+ let base = a.and_then(|o| o.as_value());
+ let offset = c.and_then(SsaOperand::as_const).unwrap_or(0);
+ if base.is_some() {
+ return (base, offset);
+ }
+ }
+ }
+ }
+ (Some(*v), 0)
+}
+
+/// Recover the function's return type by looking at the value written to
+/// RAX at return blocks. When no value is written or when RAX only carries
+/// the phi of an entry-live value (i.e. we return whatever the caller had),
+/// the type is [`RustType::Void`].
+pub fn recover_return_type(func: &SsaFunction, types: &TypeMap) -> RustType {
+ if func.blocks.is_empty() {
+ return RustType::Void;
+ }
+ let mut best = RustType::Bottom;
+ let mut wrote_rax = false;
+ for b in &func.blocks {
+ let Some(last) = b.ops.last() else { continue };
+ if last.opcode != OpCode::Return {
+ continue;
+ }
+ // Look for the most recent definition of RAX (offset 0) in this
+ // block that isn't a live-in phi passthrough.
+ for op in b.ops.iter().rev() {
+ let Some(out) = op.output else { continue };
+ if out.space == AddrSpace::Register && out.offset == 0 {
+ wrote_rax = true;
+ let t = types.get(AddrSpace::Register, 0);
+ let t = if t == RustType::Bottom {
+ RustType::int(out.size)
+ } else {
+ t
+ };
+ best = best.clone().join(t);
+ break;
+ }
+ }
+ }
+ if !wrote_rax {
+ return RustType::Void;
+ }
+ if best == RustType::Bottom {
+ RustType::int(8)
+ } else {
+ best
+ }
+}
+
/// Recover parameter register slots by looking at the entry block's live-
/// in values (uses that were never previously defined). Only integer
/// register slots that match the selected calling convention are counted.
@@ -398,7 +824,10 @@ pub fn recover_params(func: &SsaFunction, types: &TypeMap, conv: CallConv) -> Pa
};
let mut params = Vec::new();
for (index, &(reg_off, reg_name)) in order.iter().enumerate() {
- let width_opt = live_in.iter().find(|(off, _)| *off == reg_off).map(|(_, w)| *w);
+ let width_opt = live_in
+ .iter()
+ .find(|(off, _)| *off == reg_off)
+ .map(|(_, w)| *w);
if let Some(width) = width_opt {
let ty = types.get(AddrSpace::Register, reg_off);
let ty = if ty == RustType::Bottom {
@@ -409,24 +838,92 @@ pub fn recover_params(func: &SsaFunction, types: &TypeMap, conv: CallConv) -> Pa
params.push(Parameter {
index,
register: reg_name.to_string(),
+ storage: ParamStorage::Register(reg_name.to_string()),
width,
name: format!("param_{}", index + 1),
ty,
});
}
}
+
+ // Detect stack-passed parameters as positive-offset reads of the
+ // caller-set-up stack (offsets above the return-address slot). Ghidrust
+ // stack-space offsets are relative to the frame base, so positive
+ // offsets correspond to caller arguments. We stop at the first gap so
+ // spilled locals aren't confused for parameters.
+ let base = params.len();
+ let mut stack_live_ins: BTreeMap<u64, u32> = BTreeMap::new();
+ let mut defined_stack: BTreeSet<u64> = BTreeSet::new();
+ for op in &entry_block.ops {
+ for inp in &op.inputs {
+ if let Some(v) = inp.as_value() {
+ if v.space == AddrSpace::Stack
+ && v.version == 0
+ && !defined_stack.contains(&v.offset)
+ && (v.offset as i64) > 0
+ {
+ stack_live_ins.entry(v.offset).or_insert(v.size);
+ }
+ }
+ }
+ if let Some(out) = op.output {
+ if out.space == AddrSpace::Stack {
+ defined_stack.insert(out.offset);
+ }
+ }
+ }
+ for (idx, (off, width)) in stack_live_ins.into_iter().enumerate() {
+ let ty = types.get(AddrSpace::Stack, off);
+ let ty = if ty == RustType::Bottom {
+ RustType::int(width)
+ } else {
+ ty
+ };
+ let index = base + idx;
+ params.push(Parameter {
+ index,
+ register: String::new(),
+ storage: ParamStorage::Stack { offset: off },
+ width,
+ name: format!("param_{}", index + 1),
+ ty,
+ });
+ }
ParamList(params)
}
/// One-shot: run type inference + local + param recovery on `func`.
pub fn recover(func: &SsaFunction, conv: CallConv) -> TypeRecovery {
- let types = infer_types(func);
+ recover_with_name(func, conv, "")
+}
+
+/// Same as [`recover`] but seeds the resulting [`FunctionSignature`] with
+/// the caller's function name so the whole result set can be handed
+/// straight to a GUI `Commit Params/Return` action or serialized into
+/// `ProgramEdits`.
+pub fn recover_with_name(func: &SsaFunction, conv: CallConv, name: &str) -> TypeRecovery {
+ let mut types = infer_types(func);
+ let structs = recover_structs(func, &mut types);
let locals = recover_locals(func, &types);
+ // Refine local types using the newly-known struct/array pointer keys.
let params = recover_params(func, &types, conv);
+ let return_type = recover_return_type(func, &types);
+ let cc_name = match conv {
+ CallConv::SystemV => "SystemV",
+ CallConv::Windows => "Windows",
+ };
+ let signature = FunctionSignature {
+ name: name.to_string(),
+ calling_convention: cc_name.to_string(),
+ return_type,
+ params: params.clone(),
+ };
TypeRecovery {
types,
locals,
params,
+ structs,
+ signature,
}
}
@@ -537,9 +1034,9 @@ mod tests {
fn type_lattice_join_widens_widths() {
let a = RustType::int(4);
let b = RustType::int(8);
- assert_eq!(a.join(b), RustType::int(8));
+ assert_eq!(a.clone().join(b), RustType::int(8));
assert_eq!(RustType::Bool.join(RustType::int(1)), RustType::Any);
- assert_eq!(RustType::Bottom.join(a), a);
+ assert_eq!(RustType::Bottom.join(a.clone()), a);
}
#[test]
@@ -547,5 +1044,180 @@ mod tests {
assert_eq!(RustType::int(4).c_style(), "uint32_t");
assert_eq!(RustType::Bool.c_style(), "bool");
assert_eq!(RustType::ptr(4).c_style(), "uint32_t*");
+ assert_eq!(RustType::signed(4).c_style(), "int32_t");
+ assert_eq!(RustType::Void.c_style(), "void");
+ assert_eq!(
+ RustType::struct_ptr(3).c_style(),
+ "struct s_3*"
+ );
+ assert_eq!(
+ RustType::array_ptr(4, 5).c_style(),
+ "uint32_t*/*[5]*/"
+ );
+ }
+
+ #[test]
+ fn signed_join_wins_against_same_width_unsigned() {
+ let s = RustType::signed(4);
+ let u = RustType::int(4);
+ assert!(matches!(s.clone().join(u), RustType::IntSigned { width: 4 }));
+ }
+
+ #[test]
+ fn struct_ptr_and_raw_ptr_join_prefers_struct() {
+ let s = RustType::struct_ptr(1);
+ let p = RustType::ptr(0);
+ assert!(matches!(s.clone().join(p), RustType::StructPtr { key: 1 }));
+ }
+
+ #[test]
+ fn return_type_void_when_rax_not_written() {
+ // Only reads rdi and returns → rax never written, so return type is
+ // void.
+ // 48 89 c1 mov rcx, rax (rax read; rcx write)
+ // c3 ret
+ let bytes = [0x48, 0x89, 0xc1, 0xc3];
+ let rec = recover_bytes(&bytes, 0x9000, CallConv::SystemV);
+ assert_eq!(rec.signature.return_type, RustType::Void, "rax not written");
+ }
+
+ #[test]
+ fn return_type_int_when_rax_written() {
+ // mov rax, rdi ; ret
+ let bytes = [0x48, 0x89, 0xf8, 0xc3];
+ let rec = recover_bytes(&bytes, 0xa000, CallConv::SystemV);
+ assert!(
+ matches!(rec.signature.return_type, RustType::IntN { .. } | RustType::Ptr { .. }),
+ "expected typed return, got {:?}",
+ rec.signature.return_type
+ );
+ }
+
+ #[test]
+ fn prototype_string_renders_calling_convention() {
+ let bytes = [0x48, 0x89, 0xf8, 0xc3];
+ let mut rec = recover_bytes(&bytes, 0xb000, CallConv::Windows);
+ rec.signature.name = "myfn".into();
+ let proto = rec.signature.to_prototype_with_cc();
+ assert!(proto.contains("__fastcall myfn"), "proto: {proto}");
+ assert!(proto.starts_with(&rec.signature.return_type.c_style()));
+ }
+
+ #[test]
+ fn struct_seed_recovered_from_two_field_load_pattern() {
+ // Two Load ops from base+0 (uint32_t) and base+8 (uint64_t) →
+ // mixed-width fields prevent the array heuristic from firing so
+ // the pointer promotes to a struct seed.
+ use ghidrust_ir::{IrSequence, PcodeOp, Varnode};
+ let mut seq = IrSequence::new();
+ // t0 = rdi (base pointer)
+ let t_base = Varnode::unique(1, 8);
+ // t1 = t0 + 0
+ let t1 = Varnode::unique(2, 8);
+ // load4(t1) → t2
+ let t2 = Varnode::unique(3, 4);
+ // t3 = t0 + 8
+ let t3 = Varnode::unique(4, 8);
+ // load8(t3) → t4
+ let t4 = Varnode::unique(5, 8);
+ seq.push_addressed(
+ 0x0,
+ 1,
+ PcodeOp::new(
+ OpCode::Copy,
+ Some(t_base.clone()),
+ vec![Varnode::register(7, 8)],
+ ),
+ );
+ seq.push_addressed(
+ 0x1,
+ 1,
+ PcodeOp::new(
+ OpCode::IntAdd,
+ Some(t1.clone()),
+ vec![t_base.clone(), Varnode::constant(0, 8)],
+ ),
+ );
+ seq.push_addressed(
+ 0x2,
+ 1,
+ PcodeOp::new(OpCode::Load, Some(t2), vec![t1]),
+ );
+ seq.push_addressed(
+ 0x3,
+ 1,
+ PcodeOp::new(
+ OpCode::IntAdd,
+ Some(t3.clone()),
+ vec![t_base.clone(), Varnode::constant(8, 8)],
+ ),
+ );
+ seq.push_addressed(
+ 0x4,
+ 1,
+ PcodeOp::new(OpCode::Load, Some(t4), vec![t3]),
+ );
+ seq.push_addressed(0x5, 1, PcodeOp::new(OpCode::Return, None, vec![]));
+ let cfg = build_cfg(&seq, 0x0, 0x6);
+ let ssa = build_ssa(&cfg);
+ let rec = recover(&ssa, CallConv::SystemV);
+ assert!(
+ !rec.structs.is_empty(),
+ "expected recovered struct seed, got {} structs",
+ rec.structs.len()
+ );
+ let s = rec.structs.values().next().unwrap();
+ assert!(s.fields.contains_key(&0), "field @ 0 missing: {:?}", s.fields);
+ assert!(s.fields.contains_key(&8), "field @ 8 missing: {:?}", s.fields);
+ }
+
+ #[test]
+ fn array_seed_recovered_from_equal_stride_pattern() {
+ // Three loads at base+0, base+4, base+8 (all width 4) → array of
+ // uint32_t*.
+ use ghidrust_ir::{IrSequence, PcodeOp, Varnode};
+ let mut seq = IrSequence::new();
+ let t_base = Varnode::unique(0, 8);
+ seq.push_addressed(
+ 0x0,
+ 1,
+ PcodeOp::new(
+ OpCode::Copy,
+ Some(t_base.clone()),
+ vec![Varnode::register(7, 8)],
+ ),
+ );
+ for (i, off) in [(1u64, 0u64), (2, 4), (3, 8)] {
+ let addr = Varnode::unique(100 + i, 8);
+ seq.push_addressed(
+ 0x0 + i,
+ 1,
+ PcodeOp::new(
+ OpCode::IntAdd,
+ Some(addr.clone()),
+ vec![t_base.clone(), Varnode::constant(off, 8)],
+ ),
+ );
+ let out = Varnode::unique(200 + i, 4);
+ seq.push_addressed(
+ 0x10 + i,
+ 1,
+ PcodeOp::new(OpCode::Load, Some(out), vec![addr]),
+ );
+ }
+ seq.push_addressed(0x100, 1, PcodeOp::new(OpCode::Return, None, vec![]));
+ let cfg = build_cfg(&seq, 0x0, 0x101);
+ let ssa = build_ssa(&cfg);
+ let rec = recover(&ssa, CallConv::SystemV);
+ // No struct seeded — should be array. Look for ArrayPtr in the
+ // type map on the base register.
+ let arr_present = rec.types.0.values().any(|t| {
+ matches!(t, RustType::ArrayPtr { elem_width: 4, count } if *count >= 3)
+ });
+ assert!(
+ arr_present,
+ "expected ArrayPtr in type map: {:?}",
+ rec.types.0
+ );
}
}
diff --git a/docs/GHIDRA_HEADTOHEAD.md b/docs/GHIDRA_HEADTOHEAD.md
index 280d0b6..63bc588 100644
--- a/docs/GHIDRA_HEADTOHEAD.md
+++ b/docs/GHIDRA_HEADTOHEAD.md
@@ -1,39 +1,49 @@
# Ghidrust ↔ Ghidra head-to-head oracle
-**Status:** Phase C · **live spawn wired** · captured-input fallback · **no fabricated timings**.
+**Status:** Phase E · **shared-entry set** · **Stage-1 default** ·
+**token/AST similarity metric** · **no fabricated timings**.
This document is the runbook for the `ghidrust ghidra-headtohead` subcommand
and the underlying [`ghidrust_decomp::ghidra_oracle`] library API. It aligns
-with the [decompiler superiority roadmap](../../.cursor/plans/decompiler_superiority_roadmap.plan.md)
-— specifically **Phase C** ("Faster than Ghidra") which requires captured
-head-to-head numbers, never invented ones.
+with the decompiler pcode-parity plan
+(`.cursor/plans/decompiler_pcode_parity_9377412d.plan.md`) — specifically
+**Phase E** ("Fair Ghidra parity measurement"), which replaced the earlier
+brace-count proxy and stage-mismatched comparison with a shared-entry,
+Stage-1-vs-`DecompInterface`, normalized-token metric.
`ghidra-headtohead --ghidra <DIR>` auto-spawns `analyzeHeadless` with an
embedded `DecompileAndReport.java` post-script (see
`crates/ghidrust-decomp/src/ghidra_oracle.rs`). Spawn failures leave the
-Ghidra column blank — no fabricated numbers. **Do not treat current
-ledger rows as a quality or speed win over Ghidra** until both sides
-share the same function-entry list and a real quality metric (see §5).
+Ghidra column blank — no fabricated numbers. **Every row that appears in
+a published table must be in the shared entry set** and must carry both
+a Stage-1 wall-time and a token-similarity score.
---
-## Design contract
-
-1. **Same corpus, same machine.** Both sides decompile the exact bytes at
- the exact function entries. Ghidrust decodes via its shipped `disasm`
- path (`ghidrust-decode` + `ghidrust-lift`), Ghidra via its native
- `analyzeHeadless` + `DecompInterface` API.
-2. **No invented Ghidra timings.** When Ghidra isn't available (no
+## Design contract (Phase E, current)
+
+1. **Shared entry list.** When a Ghidra capture is available the Ghidrust
+ side re-runs on the intersection of Ghidra's captured entries and the
+ Ghidrust analyzer's function list. Neither side is allowed to pick a
+ corpus the other one hasn't decompiled — [`shared_entry_list`] and
+ [`bench_program_stage1`] enforce this from the library API.
+2. **Stage-1 by default.** `GhidrustStage::Stage1` is now the default
+ emit stage for the head-to-head. Stage-0 / Stage-0.5 remain available
+ as regression oracles but no published table may combine them with
+ Ghidra `DecompInterface` timings.
+3. **Token/AST similarity, not brace counts.** Rows now carry
+ `token_similarity ∈ [0, 1]` — a Jaccard over normalized C tokens
+ (identifiers, integer literals, control-flow keywords, with
+ local/param/temp names folded to canonical buckets). This is the
+ published quality metric, and it is `None` when either side is
+ missing output rather than fabricated.
+4. **No invented Ghidra timings.** When Ghidra isn't available (no
`--ghidra` flag, no `--captured` JSON), the report is explicitly
*methodology-only*: it enumerates every Ghidrust row but leaves the
- Ghidra column blank with `unavailable=true`. The JSON schema for the
- Ghidra half is nullable so downstream consumers can filter out
- methodology-only rows.
-3. **Structural, not string-equal.** The comparison is [`StructuralMatch`]:
- we align by function entry, count blocks (Ghidrust: from `bench_program`;
- Ghidra: coarse `{`-brace count), and classify each row as
- `Similar` / `Divergent` / `MissingGhidra` / `MissingGhidrust`. A future
- phase adds AST-token diffs.
+ Ghidra column blank with `unavailable=true`.
+5. **Timings on shared entries only.** `ghidra_total_us` sums only
+ entries in the shared set; `ghidrust.stage1_total_us` mirrors the
+ same set so wall-time comparisons are apples-to-apples.
---
@@ -150,20 +160,21 @@ The report includes:
### 5. What this harness is (and is not) for
-**Useful for:** wiring a reproducible spawn/capture path, locking Ghidrust
-baselines (`--json` without Ghidra), and future *fair* comparisons once both
-sides decompile the **same entry addresses**.
-
-**Not useful for marketing “we beat Ghidra” today.** Early live runs showed
-large `MissingGhidra` counts because each tool took its own first *N*
-functions — different work sets, so summed timings are not comparable. The
-`Similar` label is only a coarse block-count proxy (`floor(ir_ops/8)` vs `{`
-count in Ghidra C), not “same C.” Those run tables were **removed** from this
-doc so we do not publish an inaccurate head-to-head.
-
-**Fair comparison (future):** fix a shared address list (same entries both
-sides), measure Stage-1 vs Ghidra C on those entries, and compare quality with
-a real structural/AST metric — then publish tables under `docs/headtohead/`.
+**Useful for:** publishable Ghidrust-vs-Ghidra tables on a shared entry
+set with the token-similarity metric, and locking Ghidrust-only baselines
+(`--json` without Ghidra).
+
+**Not useful for marketing "we beat Ghidra"** on any table where
+`token_similarity` is missing or where the row set is not the shared
+intersection. The oracle refuses to emit such tables in the default
+Stage-1 configuration; Stage-0 rows must be explicitly opted into and
+should carry a note stating they aren't for external comparison.
+
+**Publishable table shape (Phase E):** for each shared entry, one row
+with `entry`, `ghidrust_stage1_us`, `ghidra_wall_us`, `token_similarity`,
+`match_kind`. Aggregate: mean/median similarity, mean speed ratio,
+`goto_rate` on the Ghidrust Stage-1 side. All numbers come from the
+oracle output — no post-hoc massage.
### Why Ghidrust Stage-0 / 0.5 looks “impossibly fast”
diff --git a/skill/SKILL.md b/skill/SKILL.md
index fdf88c5..eef65a9 100644
--- a/skill/SKILL.md
+++ b/skill/SKILL.md
@@ -60,21 +60,30 @@ Need full matrix bench?
Need decompiled C?
→ Staged capability (be honest about which stage you have):
- Stage-0 (default): `decompile PATH` / `gpu-decompile PATH` → CFG→goto / mnemonic-style pseudo-C
- Stage-0.5 (opt-in): `decompile PATH --stage05` → IR-informed emit (xor a,a → a=0, augmented assign,
- push/pop, direct call, flag-driven jcc). Falls back to Stage-0 scaffolding for
- anything the lifter doesn't cover yet — never fabricated C.
- Stage-1 (opt-in): SSA + structure + types → structured if/while/do-while/return with typed locals
- (`local_<off>`), SysV/Windows params (`param_1`, `param_2`, …), and (new)
- `switch { case … }` regions sourced from the shipped Decompiler Switch
- Analysis analyzer plus compound `if (A && B)` / `if (A || B)` short-circuit
- predicates. GUI has a Decompiler pane stage picker; MCP/library callers use
+ Stage-1 (**default**, Phase F): SSA + structure + types → structured if/while/do-while/return
+ with typed params (`param_1: uint32_t`, `param_2: struct s_1*`, …),
+ recovered return type, `local_<off>` stack locals, `switch { case … }`
+ from the shipped Decompiler Switch Analysis analyzer, compound
+ `if (A && B)` / `if (A || B)` short-circuits, and `break;` /
+ `continue;` inside natural loops (goto rate <0.15 on lab). Struct
+ seeds render as `p->field_<off>`; array seeds as `p[i]`. CLI:
+ `decompile PATH` (or explicit `--stage1`); GUI: Decompiler pane
+ stage picker (Stage-1 preselected); MCP: `decompile` tool with
+ `stage='stage1'` default; library:
`ghidrust_decomp::decompile_stage1_at`. Falls back to Stage-0.5-shaped
- scaffolding when lift ratio <50% or the region is irreducible — no fabrication.
- typed-C (roadmap): Hex-Rays-class quality (union/bitfield, EH, idiom-lift) — after Ghidra bar met.
+ scaffolding when lift ratio <50% or the region is irreducible —
+ no fabrication.
+ Stage-0 (oracle): `decompile PATH --stage0` → CFG→goto / mnemonic-style pseudo-C.
+ Kept as regression baseline; Phase E head-to-head uses this only
+ for pre-Stage-1 checks, never for external comparison tables.
+ Stage-0.5 (oracle): `decompile PATH --stage05` → IR-informed emit (xor a,a → a=0, augmented
+ assign, push/pop, direct call, flag-driven jcc). Same fallback
+ rules — Stage-0.5 is IR-informed but pre-SSA.
+ typed-C (roadmap): Hex-Rays-class quality (union/bitfield, EH, idiom-lift) — after Ghidra
+ bar met.
→ Do not invent Hex-Rays-quality C; emit only what the current stage produces.
-Need Stage-0 vs Stage-0.5 wall-clock + lift-ratio numbers?
+Need Stage-0 vs Stage-0.5 vs Stage-1 wall-clock + lift-ratio numbers?
→ `decompile-bench PATH [--functions N] [--count N] [--out FILE] [--json]`
Need Ghidra ↔ Ghidrust head-to-head?
@@ -160,10 +169,11 @@ 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 Stage-0 pseudo-C) | `ghidrust decompile <path>` |
-| Decompile (Stage-0.5 IR-informed) | `ghidrust decompile <path> --stage05` |
-| Decompile bench (Stage-0 vs Stage-0.5) | `ghidrust decompile-bench <path> [--functions N] [--count N] [--out F]` |
-| Ghidra head-to-head oracle | `ghidrust ghidra-headtohead <path> [--ghidra DIR] [--captured JSON] [--out F]` |
+| Decompile (Stage-1 default, SSA + structure + types) | `ghidrust decompile <path>` |
+| Decompile (Stage-0 CFG scaffolding, oracle) | `ghidrust decompile <path> --stage0` |
+| Decompile (Stage-0.5 IR-informed, oracle) | `ghidrust decompile <path> --stage05` |
+| Decompile bench (Stage-0 vs Stage-0.5 vs Stage-1) | `ghidrust decompile-bench <path> [--functions N] [--count N] [--out F]` |
+| Ghidra head-to-head (Phase E, shared-entry, Stage-1) | `ghidrust ghidra-headtohead <path> [--ghidra DIR] [--captured JSON] [--out F]` |
| **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]` |
@@ -275,10 +285,11 @@ the exact evidence (blocks / insns / ir_ops / lift ratio / GPU backend).
| Method | CLI | What you get | Output shape |
|---|---|---|---|
-| **Stage-0** (default) | `ghidrust decompile PATH [--addr HEX] [--count N]` | CFG → pseudo-C: `void FUN_<va>() { block_0: … goto/return; }`. Mnemonic-style scaffolding — no fabricated locals or types. | stdout `pseudo_c`; stderr `[name] stage=0 blocks=… edges=… insns=… lines=…`; `--json` ⇒ `Decompile { name, blocks[], edges[], insn_count, pseudo_c }`. |
-| **Stage-0.5 IR** | `ghidrust decompile PATH --stage05 [--addr HEX] [--count N]` | IR-informed emit from x86-64 lifter → `ghidrust-ir`: `xor a,a → a=0`, augmented assign, `push`/`pop`, direct `call`, flag-driven `jcc`. Falls back to Stage-0 for uncovered ops. Pseudo-C header line is `// Ghidrust Stage-0.5 IR emit — function …`. | stdout `pseudo_c`; stderr adds `ir_ops=… lift=…%`; `--json` ⇒ `{decompile: …, lift_coverage: {total_ops, unimplemented_ops, source_instructions, ratio}}`. |
-| **decompile-bench** | `ghidrust decompile-bench PATH [--functions N] [--count N] [--out F]` | Runs default analyzers, then benches Stage-0 vs Stage-0.5 across all discovered functions: totals `insns`, `ir_ops`, per-stage `µs`, avg `lift_ratio`. | Text (or JSON via `--json`); writes to `--out FILE` too. Eval sample: 6 fns, 33 insns, 48 IR ops, avg lift 0.96. |
-| **ghidra-headtohead** | `ghidrust ghidra-headtohead PATH [--functions N] [--count N] [--ghidra DIR] [--captured JSON] [--out F]` | Optional oracle: run Ghidra headless (`--ghidra DIR`) or ingest captured JSON (`--captured …`) and diff Stage-0 / Stage-0.5 vs Ghidra decomp lines. | Text or JSON; without Ghidra, report still generates but oracle rows note unavailability. Not part of the eval sweep. |
+| **Stage-1** (**default**) | `ghidrust decompile PATH [--addr HEX] [--count N]` | Full SSA → structure → types → typed pseudo-C: recovered return type, `param_N: T` prototype, `local_<off>: T` stack locals, `struct s_<key> { field_<off>: T; }` seeds from load/store patterns, `switch { case … }` from Decompiler Switch Analysis, compound `&&`/`\|\|`, and `break;` / `continue;` inside natural loops (goto rate <0.15 on lab). | stdout `pseudo_c`; stderr `[name] stage=1 blocks=… phis=… loops=… locals=… params=… lift=…%`; `--json` ⇒ `{decompile, stage1: {loops, phis, locals, params, structs, lift_ratio, goto_rate, return_type, prototype, total_ops}}`. |
+| **Stage-0** (oracle) | `ghidrust decompile PATH --stage0 [--addr HEX] [--count N]` | CFG → pseudo-C: `void FUN_<va>() { block_0: … goto/return; }`. Mnemonic-style scaffolding — no fabricated locals or types. | stdout `pseudo_c`; stderr `[name] stage=0 blocks=… edges=… insns=… lines=…`; `--json` ⇒ `Decompile { name, blocks[], edges[], insn_count, pseudo_c }`. |
+| **Stage-0.5 IR** (oracle) | `ghidrust decompile PATH --stage05 [--addr HEX] [--count N]` | IR-informed emit from x86-64 lifter → `ghidrust-ir`: `xor a,a → a=0`, augmented assign, `push`/`pop`, direct `call`, flag-driven `jcc`. Falls back to Stage-0 for uncovered ops. | stdout `pseudo_c`; stderr adds `ir_ops=… lift=…%`; `--json` ⇒ `{decompile: …, lift_coverage: {total_ops, unimplemented_ops, source_instructions, ratio}}`. |
+| **decompile-bench** | `ghidrust decompile-bench PATH [--functions N] [--count N] [--out F]` | Runs default analyzers, then benches Stage-0 vs Stage-0.5 vs Stage-1 across all discovered functions: totals `insns`, `ir_ops`, per-stage `µs`, avg `lift_ratio`. | Text (or JSON via `--json`); writes to `--out FILE` too. |
+| **ghidra-headtohead** (Phase E) | `ghidrust ghidra-headtohead PATH [--functions N] [--count N] [--ghidra DIR] [--captured JSON] [--out F]` | Fair oracle: shared-entry intersection between Ghidra `DecompInterface` output and Ghidrust analyzer function list; compares Stage-1 vs Ghidra with normalized-token similarity metric and per-entry Stage-1 wall-time. Without `--ghidra` / `--captured` the report is methodology-only. | Text or JSON; rows carry `token_similarity`, `ghidrust_stage1_us`, `ghidra_wall_us`. |
| **gpu-decompile** | `ghidrust gpu-decompile PATH [--out F] [--metrics F]` | Full GPU-resident VRAM multipass decompile of entry: decode → leaders → blocks → emit; single final download; asserts `mid_pipeline_host_reads == 0` and matches CPU multipass oracle. | `.gdecomp` binary dump; stdout `pseudo_c`; `--json`/`--metrics` ⇒ `{gpu_backend, gpu_device, gpu_ms, mid_pipeline_host_reads, kernels, dump_path, dump_bytes, gpu_ir_count, gpu_block_count, gpu_edge_count, equivalence_multipass, pseudo_c_head}`. Non-zero exit on equivalence break. |
| **re-bench** | `ghidrust re-bench PATH [--out F]` | CPU decompile of entry + bulk RE on a padded haystack, once on CPU parallel and once on GPU/fallback. Asserts equal bulk hit counts. | Text (or JSON): `decompile_cpu {backend, ms, entry, name, blocks, edges, insns, lines, chars, pseudo_c_head}`, `bulk_cpu`, `bulk_gpu` (each: `{mode, backend, ms, hits, haystack_bytes}`), `note`. |