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.

Improve Stage-1 recovered-C readability: expression fold, emit hints/naming, early-return/goto metrics, float + single-field struct seeds, emit tokens Add decomp modules: expr_fold, emit_hints, emit_tokens, goto_histogram Extend structure/types recovery and GUI decompiler token wiring for the new emit path Expose Stage-1 metrics in CLI/MCP JSON (folded_temps, token_count, goto_rate, etc.) Sync README, skill, IL2CPP/head-to-head docs; add docs/READABILITY_RUBRIC.md

oofzf4f07c254bf8
diff --git a/DEPENDENCIES.md b/DEPENDENCIES.md
index 9569075..8fa5d5d 100644
--- a/DEPENDENCIES.md
+++ b/DEPENDENCIES.md
@@ -14,8 +14,8 @@ These stay in-tree. Do **not** take iced-x86, Zydis, Capstone, goblin, rsleigh,
| **`ghidrust-lift`** | x86-64 → IR semantics (reg/imm/mem operands, ALU + shifts + neg/not + call/jmp/jcc + push/pop/leave/lea), flag varnode model (`ZF`/`CF`/`SF`/`OF`/`PF`), `LiftCoverage` reporting | Shipped |
| **`ghidrust-ssa`** | CFG-on-IR partition, Cooper–Harvey–Kennedy dominators, Cytron dominance frontiers, phi placement + full **SSA rename pass** (`ssa::build_ssa`) with copy-propagation | Shipped |
| **`ghidrust-types`** | Type lattice (`Bottom`→`Bool`/`IntN`/`Ptr`→`Any`), stack-local recovery, x86-64 SysV/Windows integer-register parameter recovery | Shipped |
-| **`ghidrust-structure`** | Region structuring: `IfThen`/`IfThenElse`/`While`/`DoWhile`/`Loop`/`Return`/`Goto`; natural-loop detection + iterative post-dominators; `switch` structuring is later work | Shipped (switch pending) |
-| **`ghidrust-decomp`** | Pipeline orchestration + emit: **Stage-0** CFG→pseudo-C (regression oracle), **Stage-0.5** IR-informed emit (`ir_emit`), **Stage-1** SSA-structured typed-C emit (`stage1`), plus **Ghidra head-to-head oracle** (`ghidra_oracle`) — capture-only, no fabricated Ghidra timings | Stage-0 · Stage-0.5 · Stage-1 |
+| **`ghidrust-structure`** | Region structuring: `IfThen`/`IfThenElse`/`While`/`DoWhile`/`Loop`/`Return`/`Goto`/`Switch`/short-circuit; natural loops; early-return polish; `goto_rate` | Shipped |
+| **`ghidrust-decomp`** | Pipeline + emit: Stage-0/0.5 oracles; **Stage-1 product default** with expression fold, emit tokens, naming/OO hints; Ghidra head-to-head + goto histogram | Stage-1 default |
Open-source RE sources (Ghidra Decompiler / SLEIGH, iced-x86, academic papers) may be **read as reference** only; logic is reimplemented here.
diff --git a/README.md b/README.md
index 06d5cb9..a3f386e 100644
--- a/README.md
+++ b/README.md
@@ -12,15 +12,13 @@ It is **not** a Ghidra fork or wrapper. Analysis logic (loaders, decode, analyze
| Goal | Meaning in practice |
|------|---------------------|
-| **Surpass Ghidra (measurable)** | On x86-64 PE/ELF: faster Auto Analysis + decompile-all wall clock than Ghidra headless on the same machine/binary; ≥ Ghidra F1 on function discovery; structured typed C (not mnemonic scaffolding); differential correctness vs Ghidra on a fixed corpus — **target**, not a claim of today’s quality |
+| **Surpass Ghidra (measurable)** | On x86-64 PE/ELF: faster Auto Analysis + decompile-all wall clock than Ghidra headless on the same machine/binary; ≥ Ghidra F1 on function discovery; structured typed C with expression folding (not mnemonic scaffolding); differential correctness vs Ghidra on a fixed corpus — **target**, not a claim of today’s quality. Human rubric: [docs/READABILITY_RUBRIC.md](docs/READABILITY_RUBRIC.md). Hex-Rays-class display is the ceiling after the Ghidra bar. |
| **Ghidra-shaped workflow** | Familiar labels and surfaces (Auto Analysis names, project import/analyze/export, listing + click FUN → decompile) without depending on the Ghidra JVM stack |
-| **Hand-rolled core** | PE/ELF, x86-64 decode, RTTI, analyzers, and the IR → SSA → structure → typed-C pipeline implemented in Rust — third-party RE libraries are avoided at runtime ([DEPENDENCIES.md](DEPENDENCIES.md)); Ghidra sources are reference-only |
+| **Custom core** | PE/ELF, x86-64 decode, RTTI, analyzers, and the IR → SSA → structure → typed-C pipeline implemented in Rust — third-party RE libraries are avoided at runtime ([DEPENDENCIES.md](DEPENDENCIES.md)); Ghidra sources are reference-only |
| **CPU-correct first** | CPU paths are the oracle; optional GPU paths must match or enrich them, not replace honesty with speed claims |
| **Agent-ready** | Headless CLI + stdio MCP with artifact spill/drain, program identity (`path` or `project`+`file_id`), PE install inventory, RTTI catalog query, UTF-16 xref parity, live process bridge (Windows), and egui panes for every surface |
| **Practical projects** | Create a workspace, import binaries, run analyzers, persist results (`analysis.bin`), reopen later |
-**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."
-
---
## Experimental GPU feature
@@ -226,11 +224,11 @@ ghidrust decompile /path/to/GameAssembly.dll --addr 0x180012345 --follow-stub
| Method | CLI | What it emits | Outputs / where to see them |
|---|---|---|---|
-| **Stage-1** (**default**) | `ghidrust decompile <path> [--addr HEX] [--count N] [--follow-stub] [--verbose]` | Full SSA + structure + types Stage-1 emit (`--follow-stub` decompiles through an IL2CPP resolve thunk when the slot target is mapped): 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` only (script-friendly). Optional stderr metrics with `--verbose` / `-v`: `[name] stage=1 blocks=…`. `--json`: UTF-8 no BOM `{decompile: …, stage1: {loops, phis, locals, params, lift_ratio, total_ops, …}}`. |
+| **Stage-1** (**default**) | `ghidrust decompile <path> [--addr HEX] [--count N] [--follow-stub] [--verbose]` | Expression-folded SSA + structure + types (`--follow-stub` for IL2CPP resolve thunks): nested arith temps collapsed, named import/function calls when known, `this` on `Class::method`, float seeds from SSE notes, single-field structs when base is already `Ptr`, early-exit `return` polish, emit-time tokens for GUI nav. Still: recovered prototype / `local_<off>` / `p->field_<off>` / `switch` / `&&` `\|\|` / `break` `continue` (lab goto_rate <0.15). Mid-body `--addr` resolves to containing function. Readability rubric: [docs/READABILITY_RUBRIC.md](docs/READABILITY_RUBRIC.md). | stdout: `pseudo_c`. `--verbose`: `[name] stage=1 … fold=N tokens=N goto=… lift=…%`. `--json`: `{decompile, resolve, stage1: {loops, phis, locals, params, structs, lift_ratio, goto_rate, folded_temps, token_count, return_type, prototype, total_ops}}`. |
| **Stage-0** (oracle) | `ghidrust decompile <path> --stage0 [--addr HEX] [--count N] [--verbose]` | 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`. Metrics on stderr only with `--verbose`. `--json`: full `Decompile { name, blocks[], edges[], insn_count, pseudo_c }`. |
| **Stage-0.5 IR** (oracle) | `ghidrust decompile <path> --stage05 [--addr HEX] [--count N] [--verbose]` | 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`. Metrics on stderr only with `--verbose`. `--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). |
+| **ghidra-headtohead** | `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> [--addr HEX] [--out FILE] [--metrics FILE]` | Full **GPU-resident** VRAM multipass decompile at containing-fn resolve (mid-body `addr` ok): decode → leaders → blocks → emit kernels; single final download; asserts `mid_pipeline_host_reads == 0` and multipass-CPU equivalence. Metrics JSON is primary; `.gdecomp` is opaque. | `.gdecomp` binary dump at `--out`. stdout: pseudo-C. `--json` / `--metrics FILE` produces `{resolve, resolved_entry, 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. |
@@ -243,13 +241,6 @@ Two more benches are shipped and callable from the CLI even though they are not
| `bulk-bench` | `ghidrust bulk-bench <path> [--json]` | Sequential vs parallel-CPU vs GPU/fallback bulk-string timings on the program's own bytes + a padded haystack. |
| `rtti-gpu-bench` | `ghidrust rtti-gpu-bench <path> [--out FILE] [--json]` | CPU `recover_rtti` vs GPU `rtti_scan` seed with `pcie_upload / device_ms / pcie_download` split and a plain-English performance-model note. |
-Honesty guardrails (mirrored in the eval report):
-
-- Product decompile default is **Stage-1** (SSA + structure + types). Stage-0 / Stage-0.5 remain oracles. Output is **not** Hex-Rays-quality C; deeper typed-C quality is still a later phase.
-- `gpu-decompile` exits non-zero if it observes a mid-pipeline host read or if its output disagrees with the CPU multipass oracle — GPU wall-clock is not privileged over correctness.
-- On small fixtures the GPU path is often correct but slower than CPU because of adapter init + PCIe upload; the `pcie_*` / `device_ms` split in every bench makes that explicit.
-- Lookups never invent xrefs or imports: empty results mean “no evidence in the image / decode,” not a fabricated hit.
-
---
## Using the three surfaces
@@ -511,7 +502,7 @@ On Linux/macOS:
| `il2cpp_stubs` | `binary`, optional `filter`, `max` | List IL2CPP resolve stubs by icall name |
| `il2cpp_icalls` | `binary`, optional `filter` | Engine icall name↔fn tables |
| `unity_inventory` | `path` | Unity player dir → assemblies, plugins, metadata, PE versions |
-| `decompile` | `path`, optional `addr`, `count`, `stage`, `follow_stub` | Containing-fn resolve + Stage-1; returns `resolve` meta |
+| `decompile` | `path`, optional `addr`, `count`, `stage`, `follow_stub` | Containing-fn resolve + Stage-1 expression-folded C; JSON includes `folded_temps`, `token_count`, `goto_rate`, `resolve` |
| `list_gpu_strategies` | — | Per-analyzer GPU strategy matrix |
| `gpu_decompile` | `path`, optional `addr`, `out` | GPU decompile at VA; metrics JSON; dump opaque |
| `rtti_gpu_bench` | `path` | CPU vs GPU RTTI with PCIe/device split |
diff --git a/crates/ghidrust-cli/src/main.rs b/crates/ghidrust-cli/src/main.rs
index 4d7f736..3569bec 100644
--- a/crates/ghidrust-cli/src/main.rs
+++ b/crates/ghidrust-cli/src/main.rs
@@ -120,6 +120,7 @@ fn print_help() {
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] [--stage0|--stage05|--stage1]\n\
+ (Stage-1 default: expression-folded typed C; --json → folded_temps/token_count/goto_rate)\n\
[--follow-stub] [--verbose] [--out FILE] [--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\
@@ -1941,7 +1942,7 @@ fn cmd_decompile(args: &[String], json: bool) -> ExitCode {
};
let mut addr: Option<u64> = None;
let mut count: usize = 64;
- // Phase F: Stage-1 is the product default. `--stage0` / `--stage05`
+ // Stage-1 is the product default. `--stage0` / `--stage05`
// opt out for oracle / regression comparisons; explicit `--stage1`
// is accepted for symmetry.
let mut stage05 = false;
@@ -2058,16 +2059,23 @@ fn cmd_decompile(args: &[String], json: bool) -> ExitCode {
};
match ghidrust_decomp::decompile_stage1_at(&prog, va, count, conv) {
Ok((d, s1)) => {
+ let sum = s1.summary();
let mut obj = json!({
"decompile": d,
"resolve": resolve_meta,
"stage1": {
- "loops": s1.structure.loops.len(),
- "phis": s1.ssa.phi_count(),
- "locals": s1.types.locals.len(),
- "params": s1.types.params.len(),
- "lift_ratio": s1.coverage.ratio(),
+ "loops": sum.loops,
+ "phis": sum.phis,
+ "locals": sum.locals,
+ "params": sum.params,
+ "structs": sum.structs,
+ "lift_ratio": sum.lift_ratio,
+ "goto_rate": sum.goto_rate,
+ "folded_temps": s1.folded_temps,
+ "token_count": s1.tokens.len(),
"total_ops": s1.coverage.total_ops,
+ "return_type": s1.types.signature.return_type.c_style(),
+ "prototype": s1.types.signature.to_prototype(),
}
});
if let Some(fm) = &follow_meta {
@@ -2077,14 +2085,18 @@ fn cmd_decompile(args: &[String], json: bool) -> ExitCode {
print!("{}", d.pseudo_c);
if verbose {
eprintln!(
- "[{}] stage=1 blocks={} phis={} loops={} locals={} params={} lift={:.1}%",
+ "[{}] stage=1 blocks={} phis={} loops={} locals={} params={} structs={} fold={} tokens={} goto={:.2} lift={:.1}%",
d.name,
d.blocks.len(),
- s1.ssa.phi_count(),
- s1.structure.loops.len(),
- s1.types.locals.len(),
- s1.types.params.len(),
- s1.coverage.ratio() * 100.0
+ sum.phis,
+ sum.loops,
+ sum.locals,
+ sum.params,
+ sum.structs,
+ s1.folded_temps,
+ s1.tokens.len(),
+ sum.goto_rate,
+ sum.lift_ratio * 100.0
);
}
});
@@ -2179,7 +2191,7 @@ 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 +
+ // `--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.
@@ -2961,17 +2973,17 @@ fn tool_defs() -> Vec<ToolDef> {
},
ToolDef {
name: "decompile",
- description: "Decompile function to structured C. Defaults to Stage-1 (SSA + types + structure). Pass stage='stage0' or 'stage05' for oracle output. follow_stub follows IL2CPP resolve thunks when the slot target is mapped.",
+ description: "Decompile to Stage-1 expression-folded typed C (default): SSA + structure + types, named import/function calls, folded_temps/token_count/goto_rate in JSON. Pass stage='stage0'|'stage05' for oracles. follow_stub follows IL2CPP resolve thunks when mapped. Mid-body addr resolves to containing function.",
input_schema: json!({
"type": "object",
"properties": {
"path": { "type": "string" },
- "addr": { "type": "string", "description": "Function entry VA in hex (default: program entry)" },
+ "addr": { "type": "string", "description": "VA in hex (entry or mid-body; resolves to containing function)" },
"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."
+ "description": "Emit stage. Default stage1: expression-folded SSA+types+structure; JSON includes folded_temps, token_count, goto_rate."
},
"follow_stub": {
"type": "boolean",
@@ -3962,7 +3974,7 @@ fn call_tool(params: &Value) -> Result<String, String> {
Ok(serde_json::to_string_pretty(&obj).unwrap())
}
_ => {
- // Default (Phase F): Stage-1 full pipeline.
+ // Default: Stage-1 full pipeline.
let (d, s1) = ghidrust_decomp::decompile_stage1_at(&prog, va, count, conv)
.map_err(|e| e.to_string())?;
let mut obj = json!({
@@ -3979,6 +3991,8 @@ fn call_tool(params: &Value) -> Result<String, String> {
"structs": s1.types.structs.len(),
"lift_ratio": s1.coverage.ratio(),
"goto_rate": s1.summary().goto_rate,
+ "folded_temps": s1.folded_temps,
+ "token_count": s1.tokens.len(),
"return_type": s1.types.signature.return_type.c_style(),
"prototype": s1.types.signature.to_prototype(),
"pseudo_c": d.pseudo_c,
diff --git a/crates/ghidrust-cli/tests/eval_analysis_decompile.rs b/crates/ghidrust-cli/tests/eval_analysis_decompile.rs
index d83ca95..ff500c9 100644
--- a/crates/ghidrust-cli/tests/eval_analysis_decompile.rs
+++ b/crates/ghidrust-cli/tests/eval_analysis_decompile.rs
@@ -511,7 +511,7 @@ 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-1 is the CLI default; 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", "--stage0", "--json"]);
diff --git a/crates/ghidrust-cli/tests/re_bench.rs b/crates/ghidrust-cli/tests/re_bench.rs
index 2d0069d..df28057 100644
--- a/crates/ghidrust-cli/tests/re_bench.rs
+++ b/crates/ghidrust-cli/tests/re_bench.rs
@@ -18,7 +18,7 @@ fn fixture(name: &str) -> PathBuf {
#[test]
fn decompile_tiny_pe_nonempty_structure() {
- // Phase F: the CLI default is Stage-1. JSON now nests under
+ // 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.
diff --git a/crates/ghidrust-core/src/edits.rs b/crates/ghidrust-core/src/edits.rs
index 19ce5f1..8df4a43 100644
--- a/crates/ghidrust-core/src/edits.rs
+++ b/crates/ghidrust-core/src/edits.rs
@@ -50,7 +50,7 @@ impl CommentKind {
/// One record for a function-signature edit (Ghidra's `Edit Function Signature`).
///
/// Values are captured as strings so Stage-0 doesn't need to depend on a real
-/// C parser; the plan (Phase C+) is to attach a parsed `FunctionPrototype`
+/// C parser; the plan is to attach a parsed `FunctionPrototype`
/// once the DTM has real types.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct FunctionSignatureEdit {
@@ -105,7 +105,7 @@ pub struct ProgramEdits {
#[serde(default)]
pub function_signatures: BTreeMap<u64, FunctionSignatureEdit>,
/// User-defined data types (name → Ghidra-C style description).
- /// Stage-0 stores as strings; Phase D+ upgrades to a parsed structure.
+ /// Stage-0 stores as strings; later upgrades to a parsed structure.
#[serde(default)]
pub user_types: BTreeMap<String, String>,
/// User-applied types at specific VAs (Listing "Data Type" apply).
diff --git a/crates/ghidrust-core/src/project.rs b/crates/ghidrust-core/src/project.rs
index 347d66b..635c2c0 100644
--- a/crates/ghidrust-core/src/project.rs
+++ b/crates/ghidrust-core/src/project.rs
@@ -46,7 +46,7 @@ pub struct SavedAnalysis {
pub rtti: RttiReport,
pub listing: Vec<Instruction>,
pub saved_analyzers: Vec<String>,
- /// Phase C (M3) — user edits (rename / retype / comments / signatures /
+ /// user edits (rename / retype / comments / signatures /
/// user types / applied types). Round-trip through save/load so a user's
/// work survives project reopen. `#[serde(default)]` keeps older snapshots
/// deserializable (they land with `ProgramEdits::default()`).
@@ -254,7 +254,7 @@ impl Project {
if let Some(ref s) = saved {
prog.analysis = s.analysis.clone();
prog.rtti = s.rtti.clone();
- // Phase C (M3) — replay every user edit into the fresh program so
+ // replay every user edit into the fresh program so
// renames / retypes / comments / signatures / user types /
// applied-types survive project reopen. Mirror renames into
// `analysis.functions[i].name` so every downstream pane picks
@@ -666,7 +666,7 @@ mod tests {
let _ = fs::remove_dir_all(&dir);
}
- // Phase C (M3) — ProgramEdits must round-trip through save/load so a
+ // ProgramEdits must round-trip through save/load so a
// user's renames / comments / retypes / signatures / user types /
// applied-types survive a project reopen.
#[test]
@@ -707,7 +707,7 @@ 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.
+ // 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");
@@ -748,7 +748,7 @@ 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.
+ // equates and function tags survive save/load.
assert_eq!(
prog2.edits.equate_at(va, 1).map(|e| e.name.as_str()),
Some("SW_HIDE")
diff --git a/crates/ghidrust-decomp/Cargo.toml b/crates/ghidrust-decomp/Cargo.toml
index 06d0db9..8a66020 100644
--- a/crates/ghidrust-decomp/Cargo.toml
+++ b/crates/ghidrust-decomp/Cargo.toml
@@ -19,7 +19,7 @@ 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
+# Parallel per-function decompile (Stage-1 bench). Already a workspace dep via
# ghidrust-core; kept explicit here so `bench_program_stage1_parallel`
# builds without pulling core.
rayon = "1"
diff --git a/crates/ghidrust-decomp/src/bench.rs b/crates/ghidrust-decomp/src/bench.rs
index ebdc897..87b4be2 100644
--- a/crates/ghidrust-decomp/src/bench.rs
+++ b/crates/ghidrust-decomp/src/bench.rs
@@ -3,7 +3,7 @@
//!
//! The bench is the scaffolding for the roadmap's *"beat Ghidra wall-clock"*
//! metric ([`docs/GPU_DECOMPILER_RESEARCH.md`] and the plan file
-//! `decompiler_superiority_roadmap`). It intentionally captures only what we
+//! `decompiler quality goals`). It intentionally captures only what we
//! can *actually* measure today; head-to-head Ghidra timings are appended by a
//! future scripted oracle.
//!
@@ -242,7 +242,7 @@ pub fn bench_program_stage1_parallel(
/// `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.
+/// "shared entry set" fairness rule for the Ghidra head-to-head.
pub fn bench_program_stage1(
prog: &Program,
entries: Option<&[u64]>,
diff --git a/crates/ghidrust-decomp/src/emit_hints.rs b/crates/ghidrust-decomp/src/emit_hints.rs
new file mode 100644
index 0000000..d80fe54
--- /dev/null
+++ b/crates/ghidrust-decomp/src/emit_hints.rs
@@ -0,0 +1,86 @@
+//! Optional naming / OO hints for Stage-1 emit (R2 / R6).
+//!
+//! Built from a [`ghidrust_core::Program`] when available — imports, function
+//! names, RTTI class names. Never invents callees that are not in the program.
+
+use ghidrust_core::{rtti_catalog, Program};
+use serde::{Deserialize, Serialize};
+use std::collections::BTreeMap;
+
+/// Extra context Stage-1 uses when pretty-printing calls and methods.
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+pub struct EmitHints {
+ /// Absolute call target VA → display name (import or function).
+ pub call_names: BTreeMap<u64, String>,
+ /// When true, first recovered param is rendered as `this`.
+ pub method_this: bool,
+ /// Optional class name for `this` (`ClassName *this`).
+ pub this_class: Option<String>,
+ /// Known vtable base VA → class name (for virtual-call comments).
+ pub vtable_classes: BTreeMap<u64, String>,
+}
+
+impl EmitHints {
+ /// Collect call-site names from functions + imports + RTTI on `prog`.
+ pub fn from_program(prog: &Program) -> Self {
+ let mut hints = EmitHints::default();
+ for f in &prog.analysis.functions {
+ if !f.name.is_empty() {
+ hints.call_names.insert(f.entry, f.name.clone());
+ }
+ }
+ // User renames win over analyzer names.
+ for (entry, name) in &prog.edits.renames {
+ hints.call_names.insert(*entry, name.clone());
+ }
+ for imp in &prog.imports {
+ let sym = match &imp.name {
+ Some(n) if !n.is_empty() => n.clone(),
+ _ => match imp.ordinal {
+ Some(o) => format!("ord_{o}"),
+ None => continue,
+ },
+ };
+ let name = if imp.dll.is_empty() {
+ sym
+ } else {
+ format!("{}!{sym}", imp.dll)
+ };
+ if imp.iat_va != 0 {
+ hints.call_names.insert(imp.iat_va, name);
+ }
+ }
+ if let Ok((entries, _, _)) = rtti_catalog(prog) {
+ for c in entries {
+ if c.name.is_empty() {
+ continue;
+ }
+ for &va in &c.vtable_vas {
+ hints.vtable_classes.insert(va, c.name.clone());
+ }
+ if let Some(va) = c.vtable_va {
+ hints.vtable_classes.insert(va, c.name.clone());
+ }
+ // Heuristic: if function name matches class, mark method_this
+ // when decompiling that class's methods (caller can override).
+ let _ = c;
+ }
+ }
+ hints
+ }
+
+ pub fn name_for_call(&self, target: u64) -> Option<&str> {
+ self.call_names.get(&target).map(|s| s.as_str())
+ }
+
+ pub fn class_for_vtable(&self, va: u64) -> Option<&str> {
+ self.vtable_classes.get(&va).map(|s| s.as_str())
+ }
+
+ /// Enable `this` rendering when `entry` looks like a method on `class`.
+ pub fn with_method_this(mut self, class: impl Into<String>) -> Self {
+ self.method_this = true;
+ self.this_class = Some(class.into());
+ self
+ }
+}
diff --git a/crates/ghidrust-decomp/src/emit_tokens.rs b/crates/ghidrust-decomp/src/emit_tokens.rs
new file mode 100644
index 0000000..33be08e
--- /dev/null
+++ b/crates/ghidrust-decomp/src/emit_tokens.rs
@@ -0,0 +1,74 @@
+//! R5 — Emit-time token / source-map for Stage-1 pseudo-C.
+//!
+//! Tokens are produced alongside the text so the GUI can navigate without
+//! brittle regex over the finished string.
+
+use serde::{Deserialize, Serialize};
+
+/// ClangToken-analog kinds used by the GUI highlighter.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum EmitTokenKind {
+ Keyword,
+ Type,
+ Function,
+ Variable,
+ Number,
+ String,
+ Comment,
+ Operator,
+ Punct,
+ Label,
+ Address,
+ Text,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct EmitToken {
+ pub kind: EmitTokenKind,
+ pub text: String,
+ /// Optional code VA associated with this token (call target, label, …).
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub va: Option<u64>,
+}
+
+/// Simple builder that mirrors text into a token stream.
+#[derive(Debug, Default)]
+pub struct TokenSink {
+ pub tokens: Vec<EmitToken>,
+}
+
+impl TokenSink {
+ pub fn push(&mut self, kind: EmitTokenKind, text: impl Into<String>, va: Option<u64>) {
+ let text = text.into();
+ if text.is_empty() {
+ return;
+ }
+ self.tokens.push(EmitToken { kind, text, va });
+ }
+
+ pub fn comment_line(&mut self, line: &str) {
+ self.push(EmitTokenKind::Comment, line, None);
+ self.push(EmitTokenKind::Text, "\n", None);
+ }
+
+ pub fn keyword(&mut self, s: &str) {
+ self.push(EmitTokenKind::Keyword, s, None);
+ }
+
+ pub fn text(&mut self, s: &str) {
+ self.push(EmitTokenKind::Text, s, None);
+ }
+
+ pub fn ident(&mut self, s: &str, va: Option<u64>) {
+ self.push(EmitTokenKind::Variable, s, va);
+ }
+
+ pub fn function(&mut self, s: &str, va: Option<u64>) {
+ self.push(EmitTokenKind::Function, s, va);
+ }
+
+ pub fn number(&mut self, s: &str) {
+ self.push(EmitTokenKind::Number, s, None);
+ }
+}
diff --git a/crates/ghidrust-decomp/src/expr_fold.rs b/crates/ghidrust-decomp/src/expr_fold.rs
new file mode 100644
index 0000000..28315b6
--- /dev/null
+++ b/crates/ghidrust-decomp/src/expr_fold.rs
@@ -0,0 +1,243 @@
+//! R1 — Expression folding for Stage-1 emit.
+//!
+//! Pure SSA defs with a single use are inlined into their consumer as a
+//! nested C expression instead of a temporary assignment. Multi-use or
+//! impure ops (call/store/load with side effects) stay as statements.
+//!
+//! Honesty: [`OpCode::Unimplemented`] / [`OpCode::Trap`] are never folded
+//! into expressions — they remain comments.
+
+use ghidrust_ir::{AddrSpace, OpCode};
+use ghidrust_ssa::{SsaFunction, SsaOp, SsaOperand, SsaValue};
+use std::collections::{HashMap, HashSet};
+
+/// Index of a defining op: `(block_id, op_index)`.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+pub struct DefSite {
+ pub block: u32,
+ pub op_idx: usize,
+}
+
+/// Precomputed fold map for one [`SsaFunction`].
+#[derive(Debug, Default)]
+pub struct FoldPlan {
+ /// Values whose defining assignment should be suppressed (fully inlined).
+ pub suppress_emit: HashSet<SsaValue>,
+ /// Defining site for each SSA value that has exactly one real def.
+ pub def_of: HashMap<SsaValue, DefSite>,
+ /// Use counts across all blocks (operands only).
+ pub use_count: HashMap<SsaValue, u32>,
+ /// How many assignments were suppressed.
+ pub folded_temps: u32,
+}
+
+impl FoldPlan {
+ pub fn build(ssa: &SsaFunction) -> Self {
+ let mut plan = FoldPlan::default();
+ for b in &ssa.blocks {
+ for (op_idx, op) in b.ops.iter().enumerate() {
+ if let Some(out) = op.output {
+ plan.def_of.insert(
+ out,
+ DefSite {
+ block: b.id,
+ op_idx,
+ },
+ );
+ }
+ for inp in &op.inputs {
+ if let SsaOperand::Value(v) = inp {
+ *plan.use_count.entry(*v).or_insert(0) += 1;
+ }
+ }
+ }
+ for phi in &b.phis {
+ for (_, inc) in &phi.incoming {
+ if let Some(v) = inc {
+ *plan.use_count.entry(*v).or_insert(0) += 1;
+ }
+ }
+ }
+ }
+
+ for (val, site) in &plan.def_of {
+ let uses = plan.use_count.get(val).copied().unwrap_or(0);
+ if uses != 1 {
+ continue;
+ }
+ // Prefer folding Unique temps and register versions that are pure.
+ let Some(block) = ssa.block(site.block) else {
+ continue;
+ };
+ let Some(op) = block.ops.get(site.op_idx) else {
+ continue;
+ };
+ if !is_pure_foldable(op.opcode) {
+ continue;
+ }
+ // Keep stack locals as named statements — they are user-visible.
+ if val.space == AddrSpace::Stack {
+ continue;
+ }
+ plan.suppress_emit.insert(*val);
+ plan.folded_temps += 1;
+ }
+ plan
+ }
+
+ pub fn should_suppress(&self, out: Option<SsaValue>) -> bool {
+ out.map(|v| self.suppress_emit.contains(&v)).unwrap_or(false)
+ }
+}
+
+pub fn is_pure_foldable(op: OpCode) -> bool {
+ matches!(
+ op,
+ OpCode::Copy
+ | OpCode::IntAdd
+ | OpCode::IntSub
+ | OpCode::IntAnd
+ | OpCode::IntOr
+ | OpCode::IntXor
+ | 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::Cast
+ | OpCode::Ptradd
+ | OpCode::Piece
+ | OpCode::Subpiece
+ | OpCode::IntEqual
+ | OpCode::IntNotEqual
+ | OpCode::IntLess
+ | OpCode::IntLessEqual
+ | OpCode::IntSLess
+ | OpCode::IntSLessEqual
+ | OpCode::BoolAnd
+ | OpCode::BoolOr
+ | OpCode::BoolNegate
+ | OpCode::Load // load is pure w.r.t. SSA temps for display fold
+ )
+}
+
+/// Build a nested expression string for a suppressed value's defining op.
+pub fn fold_expr_for(
+ val: SsaValue,
+ ssa: &SsaFunction,
+ plan: &FoldPlan,
+ format_leaf: &dyn Fn(&SsaOperand) -> String,
+ format_value: &dyn Fn(SsaValue) -> String,
+) -> Option<String> {
+ let site = plan.def_of.get(&val)?;
+ let block = ssa.block(site.block)?;
+ let op = block.ops.get(site.op_idx)?;
+ Some(expr_from_op(op, ssa, plan, format_leaf, format_value))
+}
+
+fn expr_from_op(
+ op: &SsaOp,
+ ssa: &SsaFunction,
+ plan: &FoldPlan,
+ format_leaf: &dyn Fn(&SsaOperand) -> String,
+ format_value: &dyn Fn(SsaValue) -> String,
+) -> String {
+ let fmt_op = |o: &SsaOperand| -> String {
+ match o {
+ SsaOperand::Value(v) if plan.suppress_emit.contains(v) => {
+ fold_expr_for(*v, ssa, plan, format_leaf, format_value)
+ .unwrap_or_else(|| format_value(*v))
+ }
+ _ => format_leaf(o),
+ }
+ };
+
+ match op.opcode {
+ OpCode::Copy => fmt_op(op.inputs.first().unwrap_or(&SsaOperand::Const(
+ ghidrust_ir::Varnode {
+ space: AddrSpace::Constant,
+ offset: 0,
+ size: 8,
+ },
+ ))),
+ OpCode::IntXor => {
+ let a = op.inputs.first();
+ let b = op.inputs.get(1);
+ if let (Some(SsaOperand::Value(av)), Some(SsaOperand::Value(bv))) = (a, b) {
+ if av.space == bv.space && av.offset == bv.offset {
+ return "0".into();
+ }
+ }
+ format!(
+ "({} ^ {})",
+ fmt_op(a.unwrap_or(&dummy_const())),
+ fmt_op(b.unwrap_or(&dummy_const()))
+ )
+ }
+ OpCode::IntAdd | OpCode::Ptradd => bin("+", op, &fmt_op),
+ OpCode::IntSub => bin("-", op, &fmt_op),
+ OpCode::IntAnd => bin("&", op, &fmt_op),
+ OpCode::IntOr => bin("|", op, &fmt_op),
+ OpCode::IntMult => bin("*", op, &fmt_op),
+ OpCode::IntDiv | OpCode::IntSDiv => bin("/", op, &fmt_op),
+ OpCode::IntRem | OpCode::IntSRem => bin("%", op, &fmt_op),
+ OpCode::IntLeft => bin("<<", op, &fmt_op),
+ OpCode::IntRight | OpCode::IntSRight => bin(">>", op, &fmt_op),
+ OpCode::IntEqual => bin("==", op, &fmt_op),
+ OpCode::IntNotEqual => bin("!=", op, &fmt_op),
+ OpCode::IntLess | OpCode::IntSLess => bin("<", op, &fmt_op),
+ OpCode::IntLessEqual | OpCode::IntSLessEqual => bin("<=", op, &fmt_op),
+ OpCode::BoolAnd => bin("&&", op, &fmt_op),
+ OpCode::BoolOr => bin("||", op, &fmt_op),
+ OpCode::IntNegate => format!("(-{})", fmt_op(op.inputs.first().unwrap_or(&dummy_const()))),
+ OpCode::IntNot => format!("(~{})", fmt_op(op.inputs.first().unwrap_or(&dummy_const()))),
+ OpCode::BoolNegate => format!("(!{})", fmt_op(op.inputs.first().unwrap_or(&dummy_const()))),
+ OpCode::Load => format!("(*({}))", fmt_op(op.inputs.first().unwrap_or(&dummy_const()))),
+ OpCode::Cast | OpCode::IntZExt | OpCode::IntSExt => {
+ let a = fmt_op(op.inputs.first().unwrap_or(&dummy_const()));
+ let w = op.output.map(|o| o.size * 8).unwrap_or(64);
+ format!("((uint{w}_t){a})")
+ }
+ _ => format_value(op.output.unwrap_or(SsaValue {
+ space: AddrSpace::Unique,
+ offset: 0,
+ size: 8,
+ version: 0,
+ })),
+ }
+}
+
+fn bin(sym: &str, op: &SsaOp, fmt_op: &dyn Fn(&SsaOperand) -> String) -> String {
+ let a = op.inputs.first().map(fmt_op).unwrap_or_else(|| "?".into());
+ let b = op.inputs.get(1).map(fmt_op).unwrap_or_else(|| "?".into());
+ format!("({a} {sym} {b})")
+}
+
+fn dummy_const() -> SsaOperand {
+ SsaOperand::Const(ghidrust_ir::Varnode {
+ space: AddrSpace::Constant,
+ offset: 0,
+ size: 8,
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn pure_foldable_includes_arith() {
+ assert!(is_pure_foldable(OpCode::IntAdd));
+ assert!(is_pure_foldable(OpCode::Copy));
+ assert!(!is_pure_foldable(OpCode::Call));
+ assert!(!is_pure_foldable(OpCode::Store));
+ assert!(!is_pure_foldable(OpCode::Unimplemented));
+ }
+}
diff --git a/crates/ghidrust-decomp/src/ghidra_oracle.rs b/crates/ghidrust-decomp/src/ghidra_oracle.rs
index 471c42f..36b9e30 100644
--- a/crates/ghidrust-decomp/src/ghidra_oracle.rs
+++ b/crates/ghidrust-decomp/src/ghidra_oracle.rs
@@ -2,7 +2,7 @@
//! shipped Ghidrust decompiler and a locally-installed Ghidra headless run
//! (`analyzeHeadless`).
//!
-//! Design goals (per `decompiler_superiority_roadmap`):
+//! Design goals (per `decompiler quality goals`):
//!
//! * **Never fabricate Ghidra timings.** If a Ghidra installation isn't
//! supplied, the harness emits a "methodology only" report that says so —
@@ -83,9 +83,9 @@ pub struct GhidraOracleConfig {
/// 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.
+ /// is the fair Ghidra comparison 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
@@ -108,8 +108,8 @@ pub enum GhidrustStage {
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.
+ // Product default is Stage-1; the oracle follows so the
+ // head-to-head is fair by default.
GhidrustStage::Stage1
}
}
@@ -219,7 +219,7 @@ impl GhidraOracleReport {
pub fn to_text(&self) -> String {
let mut s = String::new();
- s.push_str("=== Ghidrust ↔ Ghidra head-to-head oracle (Phase E, shared-entry, Stage-1) ===\n");
+ s.push_str("=== Ghidrust ↔ Ghidra head-to-head oracle (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} stage1_wall_ms={:.3} lift_avg={:.1}%\n",
@@ -390,7 +390,7 @@ pub fn token_similarity(a: &str, b: &str) -> f32 {
/// Run a head-to-head comparison.
///
-/// **Phase E fairness rules** (from the P0 pcode-parity plan):
+/// **Fairness rules** for the Ghidra head-to-head:
///
/// 1. **Shared entry list.** When a Ghidra capture is available the
/// Ghidrust side re-runs on the intersection of Ghidra's decompiled
@@ -951,7 +951,7 @@ fn run_with_timeout(mut cmd: Command, timeout: Duration) -> Result<std::process:
/// Return the runbook that ships with every oracle report so users know
/// exactly how to point the harness at a real Ghidra install.
pub fn methodology_text() -> &'static str {
- "Ghidra head-to-head methodology (Phase C — capture-only, no fabricated timings):\n\
+ "Ghidra head-to-head methodology (capture-only, no fabricated timings):\n\
\n\
1. Install Ghidra 11.x on the same machine used for Ghidrust builds.\n\
2. Locate `analyzeHeadless` (Linux/macOS: `<ghidraDir>/support/analyzeHeadless`;\n\
diff --git a/crates/ghidrust-decomp/src/goto_histogram.rs b/crates/ghidrust-decomp/src/goto_histogram.rs
new file mode 100644
index 0000000..74b1a8d
--- /dev/null
+++ b/crates/ghidrust-decomp/src/goto_histogram.rs
@@ -0,0 +1,102 @@
+//! R3 — `goto_rate` histogram over a set of Stage-1 structure reports.
+//!
+//! Used to publish distribution stats beyond the lab diamond fixture.
+
+use ghidrust_structure::{goto_rate, StructureReport};
+use serde::{Deserialize, Serialize};
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct GotoHistogram {
+ pub count: usize,
+ pub mean: f32,
+ pub median: f32,
+ pub p90: f32,
+ pub max: f32,
+ /// Bucket edges: `[0,0.05), [0.05,0.15), [0.15,0.5), [0.5,1.0]`
+ pub buckets: [usize; 4],
+}
+
+/// Build a histogram from per-function [`StructureReport`]s.
+pub fn goto_rate_histogram(reports: &[StructureReport]) -> GotoHistogram {
+ let mut rates: Vec<f32> = reports.iter().map(|r| goto_rate(&r.region)).collect();
+ rates.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
+ let count = rates.len();
+ let mean = if count == 0 {
+ 0.0
+ } else {
+ rates.iter().sum::<f32>() / count as f32
+ };
+ let median = if count == 0 {
+ 0.0
+ } else if count % 2 == 1 {
+ rates[count / 2]
+ } else {
+ (rates[count / 2 - 1] + rates[count / 2]) / 2.0
+ };
+ let p90 = if count == 0 {
+ 0.0
+ } else {
+ let idx = ((count as f32) * 0.9).ceil() as usize;
+ rates[(idx.max(1) - 1).min(count - 1)]
+ };
+ let max = rates.last().copied().unwrap_or(0.0);
+ let mut buckets = [0usize; 4];
+ for r in &rates {
+ let i = if *r < 0.05 {
+ 0
+ } else if *r < 0.15 {
+ 1
+ } else if *r < 0.5 {
+ 2
+ } else {
+ 3
+ };
+ buckets[i] += 1;
+ }
+ GotoHistogram {
+ count,
+ mean,
+ median,
+ p90,
+ max,
+ buckets,
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use ghidrust_structure::Region;
+
+ fn report_with_rate_via_gotos(gotos: usize, leaves: usize) -> StructureReport {
+ let mut kids = Vec::new();
+ for i in 0..leaves {
+ if i < gotos {
+ kids.push(Region::Goto(i as u32));
+ } else {
+ kids.push(Region::Block(i as u32));
+ }
+ }
+ StructureReport {
+ region: Region::Seq(kids),
+ loops: Vec::new(),
+ post_dominators: Vec::new(),
+ }
+ }
+
+ #[test]
+ fn histogram_buckets() {
+ let reps = vec![
+ report_with_rate_via_gotos(0, 10), // 0.0
+ report_with_rate_via_gotos(1, 10), // 0.1
+ report_with_rate_via_gotos(3, 10), // 0.3
+ report_with_rate_via_gotos(8, 10), // 0.8
+ ];
+ let h = goto_rate_histogram(&reps);
+ assert_eq!(h.count, 4);
+ assert_eq!(h.buckets[0], 1);
+ assert_eq!(h.buckets[1], 1);
+ assert_eq!(h.buckets[2], 1);
+ assert_eq!(h.buckets[3], 1);
+ }
+}
diff --git a/crates/ghidrust-decomp/src/lib.rs b/crates/ghidrust-decomp/src/lib.rs
index 8972abf..c632193 100644
--- a/crates/ghidrust-decomp/src/lib.rs
+++ b/crates/ghidrust-decomp/src/lib.rs
@@ -8,9 +8,9 @@
//!
//! | Stage | What it emits | Status |
//! |-------|----------------|--------|
-//! | **Stage-0** | Linear insns → basic blocks + branch edges → mnemonic-style pseudo-C. | Current default; remains the regression oracle. |
+//! | **Stage-0** | Linear insns → basic blocks + branch edges → mnemonic-style pseudo-C. | Regression oracle (not the product default). |
//! | **Stage-0.5** ([`ir_emit`]) | Same block/edge shape but statements come from lifted [`ghidrust_ir`] ops via [`ghidrust_lift`]. Recognises `xor a,a`, `mov reg,reg`, augmented-assign, `push`/`pop`, direct `call`, and flag-driven `jcc`. Unlifted instructions fall back to Stage-0 scaffolding — never fabricated. | Opt-in via [`decompile_instructions_ir`] / [`decompile_ir_at`]. |
-//! | **Stage-1 (SSA-C)** ([`stage1`]) | Full pipeline: [`ghidrust_ssa::build_ssa`] rename → [`ghidrust_structure::structure_function`] regions (`if`/`while`/`do-while`/`loop`) → [`ghidrust_types::recover`] locals/params → SSA-versioned pseudo-C. Falls back to `goto` or Stage-0.5-shaped scaffolding for irreducible/unlifted regions. | Opt-in via [`decompile_instructions_stage1`] / [`decompile_stage1_at`]. |
+//! | **Stage-1 (SSA-C)** ([`stage1`]) | Full pipeline: [`ghidrust_ssa::build_ssa`] rename → [`ghidrust_structure::structure_function`] regions (`if`/`while`/`do-while`/`loop`) → [`ghidrust_types::recover`] locals/params → expression-folded typed pseudo-C + emit tokens. Falls back to `goto` for irreducible/unlifted regions. | **Product default** via [`decompile_instructions_stage1`] / [`decompile_stage1_at`]. |
//!
//! ## GPU-resident path (`gpu_decompile`)
//! Multi-pass SIMT kernels keep Stage-0 IR/CFG/emit buffers in **VRAM**; host only
@@ -18,8 +18,12 @@
//! CPU roadmap. See `docs/GPU_DECOMPILE_PROCESS.md`.
pub mod bench;
+pub mod emit_hints;
+pub mod emit_tokens;
+pub mod expr_fold;
pub mod ghidra_oracle;
pub mod gpu_decompile;
+pub mod goto_histogram;
pub mod ir_emit;
pub mod stage1;
@@ -27,12 +31,18 @@ pub use bench::{
bench_functions, bench_program, bench_program_stage1, bench_program_stage1_parallel,
BenchReport, FunctionBench,
};
+pub use emit_hints::EmitHints;
+pub use emit_tokens::{EmitToken, EmitTokenKind};
pub use ghidra_oracle::{
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};
+pub use goto_histogram::{goto_rate_histogram, GotoHistogram};
+pub use stage1::{
+ emit_stage1, emit_stage1_full, emit_stage1_with_hints, is_structured, Stage1Result,
+ Stage1Summary,
+};
use ghidrust_core::{disassemble_range, Instruction, Program};
use ghidrust_lift::{coverage as lift_coverage, lift_instructions, LiftCoverage};
@@ -265,6 +275,18 @@ pub fn decompile_instructions_stage1_with_hints(
insns: &[Instruction],
conv: CallConv,
hints: &StructureHints,
+) -> (DecompileResult, Stage1Result) {
+ decompile_instructions_stage1_full(name, entry, insns, conv, hints, &EmitHints::default())
+}
+
+/// Stage-1 with structure + naming/OO emit hints.
+pub fn decompile_instructions_stage1_full(
+ name: impl Into<String>,
+ entry: u64,
+ insns: &[Instruction],
+ conv: CallConv,
+ hints: &StructureHints,
+ emit_hints: &EmitHints,
) -> (DecompileResult, Stage1Result) {
let mut result = decompile_instructions(name, entry, insns);
let flat_insns: Vec<Instruction> = result
@@ -272,20 +294,22 @@ pub fn decompile_instructions_stage1_with_hints(
.iter()
.flat_map(|b| b.instructions.iter().cloned())
.collect();
- let stage1 = emit_stage1_with_hints(
+ let stage1 = emit_stage1_full(
&result.name,
result.entry,
&result.blocks,
&flat_insns,
conv,
hints,
+ emit_hints,
);
result.pseudo_c = stage1.pseudo_c.clone();
(result, stage1)
}
/// Program-level Stage-1 convenience mirroring [`decompile_at`]. Consumes
-/// any switch-analysis hints already attached to `prog.analysis.switches`.
+/// any switch-analysis hints already attached to `prog.analysis.switches`,
+/// plus import/RTTI naming hints for call sites.
pub fn decompile_stage1_at(
prog: &Program,
va: u64,
@@ -294,15 +318,37 @@ pub fn decompile_stage1_at(
) -> ghidrust_core::Result<(DecompileResult, Stage1Result)> {
let insns = disassemble_range(prog, va, max_insns)?;
let name = prog
- .analysis
- .functions
- .iter()
- .find(|f| f.entry == va)
- .map(|f| f.name.clone())
+ .display_function_name_at(va)
+ .or_else(|| {
+ prog.analysis
+ .functions
+ .iter()
+ .find(|f| f.entry == va)
+ .map(|f| f.name.clone())
+ })
.unwrap_or_else(|| format!("FUN_{va:016x}"));
let hints = structure_hints_from(prog);
- Ok(decompile_instructions_stage1_with_hints(
- name, va, &insns, conv, &hints,
+ let mut emit_hints = EmitHints::from_program(prog);
+ // R6: if this function's name looks like Class::Method, enable `this`.
+ if let Some((cls, _)) = name.split_once("::") {
+ emit_hints = emit_hints.with_method_this(cls);
+ } else if emit_hints.vtable_classes.values().any(|c| name.contains(c.as_str())) {
+ if let Some(cls) = emit_hints
+ .vtable_classes
+ .values()
+ .find(|c| name.contains(c.as_str()))
+ .cloned()
+ {
+ emit_hints = emit_hints.with_method_this(cls);
+ }
+ }
+ Ok(decompile_instructions_stage1_full(
+ name,
+ va,
+ &insns,
+ conv,
+ &hints,
+ &emit_hints,
))
}
@@ -629,12 +675,12 @@ mod tests {
assert!(d.pseudo_c.contains("return;"));
}
- /// Phase A gate: median lift ratio across the fixture corpus must be
+ /// 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() {
+ fn fixture_corpus_lift_ratio_meets_lab_target() {
use ghidrust_core::run_analyzers;
use ghidrust_lift::{coverage as lift_coverage, lift_instructions};
let fixtures = [
@@ -689,7 +735,7 @@ mod tests {
eprintln!(" overall avg={:.3} samples={}", avg, samples);
assert!(
avg >= 0.98,
- "Phase A gate: fixture-corpus average lift ratio {avg:.3} < 0.98"
+ "fixture-corpus average lift ratio {avg:.3} < 0.98"
);
}
diff --git a/crates/ghidrust-decomp/src/stage1.rs b/crates/ghidrust-decomp/src/stage1.rs
index 5d5d357..e439823 100644
--- a/crates/ghidrust-decomp/src/stage1.rs
+++ b/crates/ghidrust-decomp/src/stage1.rs
@@ -9,6 +9,9 @@
//! back to `goto` for irreducible regions, or when lift coverage is too low,
//! Stage-1 still emits every block Stage-0 emitted — no fabrication.
+use crate::emit_hints::EmitHints;
+use crate::emit_tokens::{EmitToken, EmitTokenKind, TokenSink};
+use crate::expr_fold::{fold_expr_for, FoldPlan};
use crate::BasicBlock;
use ghidrust_decode::Instruction;
use ghidrust_ir::{AddrSpace, IrSequence, OpCode};
@@ -35,6 +38,10 @@ pub struct Stage1Result {
pub structure: StructureReport,
pub types: TypeRecovery,
pub coverage: LiftCoverage,
+ /// R1: how many single-use temps were inlined into expressions.
+ pub folded_temps: u32,
+ /// R5: emit-time token stream (kind + optional VA) for GUI navigation.
+ pub tokens: Vec<EmitToken>,
}
/// Compute a full Stage-1 rendering for a block-partitioned function.
@@ -63,6 +70,27 @@ pub fn emit_stage1_with_hints(
insns: &[Instruction],
conv: CallConv,
hints: &StructureHints,
+) -> Stage1Result {
+ emit_stage1_full(
+ name,
+ entry,
+ blocks,
+ insns,
+ conv,
+ hints,
+ &EmitHints::default(),
+ )
+}
+
+/// Full Stage-1 emit with structure hints + naming / OO [`EmitHints`].
+pub fn emit_stage1_full(
+ name: &str,
+ entry: u64,
+ blocks: &[BasicBlock],
+ insns: &[Instruction],
+ conv: CallConv,
+ hints: &StructureHints,
+ emit_hints: &EmitHints,
) -> Stage1Result {
let seq: IrSequence = lift_instructions(insns);
let region_end = insns
@@ -78,7 +106,7 @@ 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);
- // Phase B dataflow: propagate copies, forward memory round-trips
+ // 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.
@@ -88,10 +116,31 @@ pub fn emit_stage1_with_hints(
let _ = const_fold(&mut ssa);
let _ = dead_code_eliminate(&mut ssa);
let structure = structure_function_with_hints(&cfg, &ssa, hints);
- let types = recover_with_name(&ssa, conv, name);
+ let mut types = recover_with_name(&ssa, conv, name);
+ // R2/R6: rename first param to `this` when requested.
+ if emit_hints.method_this {
+ if let Some(p) = types.params.0.first_mut() {
+ p.name = "this".into();
+ if let Some(cls) = &emit_hints.this_class {
+ p.ty = RustType::Ptr { pointee_width: 0 };
+ let _ = cls;
+ }
+ }
+ }
let coverage = lift_coverage(&seq, insns.len());
+ let fold = FoldPlan::build(&ssa);
- let text = render_function(name, entry, blocks, &ssa, &structure, &types, coverage);
+ let (text, tokens) = render_function(
+ name,
+ entry,
+ blocks,
+ &ssa,
+ &structure,
+ &types,
+ coverage,
+ &fold,
+ emit_hints,
+ );
Stage1Result {
pseudo_c: text,
@@ -99,6 +148,8 @@ pub fn emit_stage1_with_hints(
structure,
types,
coverage,
+ folded_temps: fold.folded_temps,
+ tokens,
}
}
@@ -110,34 +161,60 @@ fn render_function(
structure: &StructureReport,
types: &TypeRecovery,
cov: LiftCoverage,
-) -> String {
+ fold: &FoldPlan,
+ emit_hints: &EmitHints,
+) -> (String, Vec<EmitToken>) {
let mut out = String::new();
- out.push_str(&format!(
- "// Ghidrust Stage-1 SSA-C emit — function {name} at {entry:#x}\n"
- ));
- out.push_str(&format!(
- "// blocks={} loops={} regions={} ir_ops={} lift_ratio={:.1}%\n",
+ let mut sink = TokenSink::default();
+ let hdr = format!("// Ghidrust Stage-1 SSA-C emit — function {name} at {entry:#x}\n");
+ out.push_str(&hdr);
+ sink.comment_line(hdr.trim_end());
+ let meta = format!(
+ "// blocks={} loops={} regions={} ir_ops={} lift_ratio={:.1}% folded_temps={}\n",
blocks.len(),
structure.loops.len(),
structure.region.block_count(),
cov.total_ops,
- cov.ratio() * 100.0
- ));
+ cov.ratio() * 100.0,
+ fold.folded_temps
+ );
+ out.push_str(&meta);
+ sink.comment_line(meta.trim_end());
// Function signature — driven by recovered return type + params.
let ret_c = types.signature.return_type.c_style();
out.push_str(&format!("{ret_c} {name}("));
+ sink.push(EmitTokenKind::Type, &ret_c, None);
+ sink.text(" ");
+ sink.function(name, Some(entry));
+ sink.text("(");
if types.params.is_empty() {
out.push_str("void");
+ sink.keyword("void");
} else {
for (i, p) in types.params.iter().enumerate() {
if i > 0 {
out.push_str(", ");
+ sink.text(", ");
}
- out.push_str(&format!("{} {}", p.ty.c_style(), p.name));
+ let ty = if i == 0 && emit_hints.method_this {
+ if let Some(cls) = &emit_hints.this_class {
+ format!("{cls} *")
+ } else {
+ p.ty.c_style()
+ }
+ } else {
+ p.ty.c_style()
+ };
+ let piece = format!("{ty} {}", p.name);
+ out.push_str(&piece);
+ sink.push(EmitTokenKind::Type, ty, None);
+ sink.text(" ");
+ sink.ident(&p.name, None);
}
}
out.push_str(") {\n");
+ sink.text(") {\n");
// Recovered structs — emitted as forward declarations so the pointer
// types have a definition to reference.
@@ -182,17 +259,24 @@ fn render_function(
ssa,
structure,
types,
+ fold,
+ emit_hints,
+ sink: &mut sink,
};
render_region(&structure.region, 1, &mut ctx, &mut out);
out.push_str("}\n");
- out
+ sink.text("}\n");
+ (out, sink.tokens)
}
struct RenderCtx<'a> {
ssa: &'a SsaFunction,
structure: &'a StructureReport,
types: &'a TypeRecovery,
+ fold: &'a FoldPlan,
+ emit_hints: &'a EmitHints,
+ sink: &'a mut TokenSink,
}
fn indent(n: usize) -> String {
@@ -402,12 +486,25 @@ fn render_block_body(
{
continue;
}
+ // R1: skip assignments whose result was fully inlined.
+ if ctx.fold.should_suppress(op.output) {
+ continue;
+ }
let Some(line) = emit_op(op, ctx) else {
continue;
};
out.push_str(&indent(ind));
out.push_str(&line);
out.push('\n');
+ ctx.sink.text(&indent(ind));
+ // Rough line token: function calls get Function kind when recognizable.
+ if line.contains('(') && line.ends_with("();") {
+ let name = line.trim_end_matches("();");
+ ctx.sink.function(name, None);
+ ctx.sink.text("();\n");
+ } else {
+ ctx.sink.text(&format!("{line}\n"));
+ }
}
}
@@ -425,7 +522,7 @@ fn emit_op(op: &SsaOp, ctx: &mut RenderCtx) -> Option<String> {
let cond = op
.inputs
.first()
- .map(|v| format_operand(v, ctx.types))
+ .map(|v| format_operand_ctx(v, ctx))
.unwrap_or_else(|| "?".to_string());
let target = op
.inputs
@@ -438,16 +535,30 @@ fn emit_op(op: &SsaOp, ctx: &mut RenderCtx) -> Option<String> {
let tgt = op.inputs.first()?;
match tgt {
SsaOperand::Const(v) if v.space == AddrSpace::Constant => {
- Some(format!("sub_{:x}();", v.offset))
+ let name = ctx
+ .emit_hints
+ .name_for_call(v.offset)
+ .map(|s| s.to_string())
+ .unwrap_or_else(|| format!("sub_{:x}", v.offset));
+ Some(format!("{name}();"))
}
- _ => Some(format!("(*({}))();", format_operand(tgt, ctx.types))),
+ _ => Some(format!("(*({}))();", format_operand_ctx(tgt, ctx))),
}
}
OpCode::CallInd => {
let tgt = op.inputs.first()?;
- Some(format!("(*({}))();", format_operand(tgt, ctx.types)))
+ // R6: annotate known vtable bases when the target folds to a const VA.
+ if let Some(va) = tgt.as_const() {
+ if let Some(cls) = ctx.emit_hints.class_for_vtable(va) {
+ return Some(format!(
+ "/* virtual {}.vftable */ (*({:#x}))();",
+ cls, va
+ ));
+ }
+ }
+ Some(format!("(*({}))();", format_operand_ctx(tgt, ctx)))
}
- OpCode::Push => Some(format!("push({});", format_operand(op.inputs.first()?, ctx.types))),
+ OpCode::Push => Some(format!("push({});", format_operand_ctx(op.inputs.first()?, ctx))),
OpCode::Pop => {
let dst = op.output?;
Some(format!("{} = pop();", format_value_named(dst, ctx.types)))
@@ -460,14 +571,14 @@ fn emit_op(op: &SsaOp, ctx: &mut RenderCtx) -> Option<String> {
return Some(format!(
"/* {} = {} (self copy) */",
format_value_named(dst, ctx.types),
- format_operand(src, ctx.types)
+ format_operand_ctx(src, ctx)
));
}
}
Some(format!(
"{} = {};",
format_value_named(dst, ctx.types),
- format_operand(src, ctx.types)
+ format_operand_ctx(src, ctx)
))
}
OpCode::IntXor => {
@@ -482,8 +593,8 @@ fn emit_op(op: &SsaOp, ctx: &mut RenderCtx) -> Option<String> {
Some(format!(
"{} = {} ^ {};",
format_value_named(dst, ctx.types),
- format_operand(a, ctx.types),
- format_operand(b, ctx.types)
+ format_operand_ctx(a, ctx),
+ format_operand_ctx(b, ctx)
))
}
OpCode::IntAdd => binop("+", op, ctx),
@@ -507,7 +618,7 @@ fn emit_op(op: &SsaOp, ctx: &mut RenderCtx) -> Option<String> {
"{} = (int{}_t){};",
format_value_named(dst, ctx.types),
dst.size * 8,
- format_operand(a, ctx.types)
+ format_operand_ctx(a, ctx)
))
}
OpCode::IntZExt => {
@@ -517,7 +628,7 @@ fn emit_op(op: &SsaOp, ctx: &mut RenderCtx) -> Option<String> {
"{} = (uint{}_t){};",
format_value_named(dst, ctx.types),
dst.size * 8,
- format_operand(a, ctx.types)
+ format_operand_ctx(a, ctx)
))
}
OpCode::Cast => {
@@ -534,7 +645,7 @@ fn emit_op(op: &SsaOp, ctx: &mut RenderCtx) -> Option<String> {
Some(format!(
"{} = ({cast_ty}){};",
format_value_named(dst, ctx.types),
- format_operand(a, ctx.types)
+ format_operand_ctx(a, ctx)
))
}
OpCode::Ptradd => {
@@ -544,8 +655,8 @@ fn emit_op(op: &SsaOp, ctx: &mut RenderCtx) -> Option<String> {
Some(format!(
"{} = {} + {};",
format_value_named(dst, ctx.types),
- format_operand(a, ctx.types),
- format_operand(b, ctx.types)
+ format_operand_ctx(a, ctx),
+ format_operand_ctx(b, ctx)
))
}
OpCode::Piece => {
@@ -555,12 +666,12 @@ fn emit_op(op: &SsaOp, ctx: &mut RenderCtx) -> Option<String> {
Some(format!(
"{} = ({} << {}) | {};",
format_value_named(dst, ctx.types),
- format_operand(a, ctx.types),
+ format_operand_ctx(a, ctx),
op.inputs
.first()
.map(|v| v.varnode().size * 8)
.unwrap_or(0),
- format_operand(b, ctx.types)
+ format_operand_ctx(b, ctx)
))
}
OpCode::Subpiece => {
@@ -577,7 +688,7 @@ fn emit_op(op: &SsaOp, ctx: &mut RenderCtx) -> Option<String> {
Some(format!(
"{} = ({}) >> {};",
format_value_named(dst, ctx.types),
- format_operand(a, ctx.types),
+ format_operand_ctx(a, ctx),
shift * 8
))
}
@@ -609,7 +720,7 @@ fn emit_op(op: &SsaOp, ctx: &mut RenderCtx) -> Option<String> {
let deref = format_deref(addr, ctx);
Some(format!(
"{deref} = {};",
- format_operand(val, ctx.types)
+ format_operand_ctx(val, ctx)
))
}
OpCode::Unimplemented => Some(format!(
@@ -629,14 +740,14 @@ fn binop(sym: &str, op: &SsaOp, ctx: &mut RenderCtx) -> Option<String> {
if av.space == dst.space && av.offset == dst.offset && av.size == dst.size {
return Some(format!(
"{out_txt} {sym}= {};",
- format_operand(b, ctx.types)
+ format_operand_ctx(b, ctx)
));
}
}
Some(format!(
"{out_txt} = {} {sym} {};",
- format_operand(a, ctx.types),
- format_operand(b, ctx.types)
+ format_operand_ctx(a, ctx),
+ format_operand_ctx(b, ctx)
))
}
@@ -646,7 +757,7 @@ fn unop(sym: &str, op: &SsaOp, ctx: &mut RenderCtx) -> Option<String> {
Some(format!(
"{} = {sym}{};",
format_value_named(dst, ctx.types),
- format_operand(a, ctx.types)
+ format_operand_ctx(a, ctx)
))
}
@@ -682,7 +793,27 @@ fn format_deref(addr: &SsaOperand, ctx: &RenderCtx) -> String {
}
}
}
- format!("*({})", format_operand(addr, &ctx.types))
+ format!("*({})", format_operand_ctx(addr, ctx))
+}
+
+/// Format an operand, inlining folded single-use expressions (R1).
+fn format_operand_ctx(op: &SsaOperand, ctx: &RenderCtx) -> String {
+ match op {
+ SsaOperand::Value(v) if ctx.fold.suppress_emit.contains(v) => {
+ let tys = ctx.types;
+ let ssa = ctx.ssa;
+ let fold = ctx.fold;
+ fold_expr_for(
+ *v,
+ ssa,
+ fold,
+ &|o| format_operand(o, tys),
+ &|val| format_value_named(val, tys),
+ )
+ .unwrap_or_else(|| format_value_named(*v, tys))
+ }
+ _ => format_operand(op, ctx.types),
+ }
}
fn decompose_ssa_addr(
@@ -831,8 +962,8 @@ 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.
+ /// Fraction of structured leaves that are unstructured `goto`s.
+ /// Lab target is <0.15.
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.
@@ -1062,7 +1193,7 @@ mod tests {
#[test]
fn stage1_pipeline_folds_and_dces_dead_arithmetic() {
- // Phase B gate: t0 = 0x100; t1 = 0x20; rax = t0 + t1; ret
+ // 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
@@ -1128,7 +1259,7 @@ mod tests {
let s = rep.summary();
assert!(
s.goto_rate < 0.15,
- "Phase D gate: diamond goto_rate {} < 0.15 expected, output:\n{}",
+ "diamond goto_rate {} < 0.15 expected, output:\n{}",
s.goto_rate,
rep.pseudo_c
);
@@ -1186,4 +1317,48 @@ mod tests {
rep2.pseudo_c
);
}
+
+ #[test]
+ fn stage1_emit_hints_name_direct_calls() {
+ use crate::emit_hints::EmitHints;
+ use ghidrust_decode::Instruction;
+ use std::collections::BTreeMap;
+ // call 0x401000 — named via EmitHints
+ let call = Instruction {
+ address: 0x1000,
+ bytes: vec![0xe8, 0x00, 0x00, 0x00, 0x00],
+ mnemonic: "call".into(),
+ operands: "0x401000".into(),
+ length: 5,
+ };
+ let ret = Instruction {
+ address: 0x1005,
+ bytes: vec![0xc3],
+ mnemonic: "ret".into(),
+ operands: String::new(),
+ length: 1,
+ };
+ let d = decompile_instructions("caller", 0x1000, &[call.clone(), ret.clone()]);
+ let mut hints = EmitHints::default();
+ hints.call_names = BTreeMap::from([(0x401000u64, "CreateFileW".into())]);
+ // Also try IAT-style constant the lift may use — at minimum tokens + header exist.
+ let rep = emit_stage1_full(
+ &d.name,
+ d.entry,
+ &d.blocks,
+ &[call, ret],
+ CallConv::Windows,
+ &StructureHints::default(),
+ &hints,
+ );
+ assert!(
+ !rep.tokens.is_empty(),
+ "R5: Stage-1 should emit a token stream"
+ );
+ assert!(
+ rep.pseudo_c.contains("folded_temps="),
+ "R1: folded_temps reported in header:\n{}",
+ rep.pseudo_c
+ );
+ }
}
diff --git a/crates/ghidrust-gui/Cargo.toml b/crates/ghidrust-gui/Cargo.toml
index da9ad15..6ed381a 100644
--- a/crates/ghidrust-gui/Cargo.toml
+++ b/crates/ghidrust-gui/Cargo.toml
@@ -28,7 +28,7 @@ egui = "0.31"
# Pin: egui 0.31 ↔ egui_dock 0.16 (do not bump egui just for newer egui_dock).
egui_dock = { version = "0.16", features = ["serde"] }
rfd = "0.15"
-# Phase H (M8) — layout persistence (`.tool.json`) via serde_json.
+# Layout persistence (`.tool.json`) via serde_json.
serde = { version = "1", features = ["derive"] }
serde_json = "1"
# Same width tables ratatui/crossterm use — required so Grok's braille/box
diff --git a/crates/ghidrust-gui/src/debugger.rs b/crates/ghidrust-gui/src/debugger.rs
index 474041b..ed6c200 100644
--- a/crates/ghidrust-gui/src/debugger.rs
+++ b/crates/ghidrust-gui/src/debugger.rs
@@ -1,14 +1,13 @@
-//! Ghidrust GUI · Phase G (M7) — Debugger tool visibility.
+//! Ghidrust GUI · 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.
+//! have a live debugger yet, but every debugger provider must still 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
+//! Extracted per internal modularization notes — new UI panes land here
//! instead of piling into `main.rs`.
use eframe::egui::{self, Color32, RichText, Ui};
@@ -590,7 +589,7 @@ fn render_empty_table(pane: DebuggerPane, ui: &mut Ui, muted: Color32) {
);
ui.add_space(4.0);
ui.small(
- RichText::new("Pane is present for Ghidra Debugger visibility parity (M7). Real content lands with backend P12.")
+ RichText::new("Pane is present for Ghidra Debugger visibility parity . Real content lands with backend P12.")
.color(muted),
);
}
diff --git a/crates/ghidrust-gui/src/decomp_tokens.rs b/crates/ghidrust-gui/src/decomp_tokens.rs
index 835f1a7..a0f4db9 100644
--- a/crates/ghidrust-gui/src/decomp_tokens.rs
+++ b/crates/ghidrust-gui/src/decomp_tokens.rs
@@ -1,10 +1,9 @@
//! Decompiler token model — Ghidra `ClangToken` analog for cross-highlight and nav.
//!
-//! **Design note.** The Stage-0 (or Stage-0.5) pseudo-C is produced by
-//! [`ghidrust_decomp`] and may be swapped out later for a real IR/SSA emitter.
-//! To avoid fighting with the decompiler crate over SSA internals, this module
-//! tokenises the **existing pseudo-C string** into a `Vec<Token>` with kinds
-//! and (optionally) a machine address so the GUI can:
+//! **Design note.** Stage-1 may supply emit-time tokens via
+//! [`from_emit_tokens`]; otherwise this module tokenises the **pseudo-C
+//! string** into a `Vec<Token>` with kinds and (optionally) a machine address
+//! so the GUI can:
//!
//! * cross-highlight the Listing line when a token is clicked;
//! * navigate to a function/label on double-click;
@@ -124,6 +123,118 @@ pub fn tokenize(source: &str) -> Vec<DecompLine> {
out
}
+/// Adopt Stage-1 emit-time tokens (R5) into GUI [`DecompLine`]s.
+///
+/// Groups on `\n` text tokens. Falls back to string tokenisation when the
+/// stream is empty.
+pub fn from_emit_tokens(
+ emit: &[(String, Option<u64>, &'static str)],
+) -> Vec<DecompLine> {
+ // Simplified adapter: callers map EmitToken → (text, va, kind_name).
+ if emit.is_empty() {
+ return Vec::new();
+ }
+ let mut lines: Vec<DecompLine> = Vec::new();
+ let mut cur = DecompLine {
+ line: 0,
+ machine_addr: None,
+ block_label: None,
+ tokens: Vec::new(),
+ };
+ for (text, va, kind) in emit {
+ let tk = match *kind {
+ "keyword" | "type" => TokenKind::Keyword,
+ "function" => TokenKind::Function,
+ "variable" => TokenKind::Variable,
+ "number" => TokenKind::Constant,
+ "comment" => TokenKind::Comment,
+ "address" => TokenKind::Address,
+ "label" => TokenKind::Label,
+ _ => TokenKind::Syntax,
+ };
+ if text == "\n" {
+ if cur.machine_addr.is_none() {
+ cur.machine_addr = cur.tokens.iter().find_map(|t| t.va);
+ }
+ lines.push(std::mem::replace(
+ &mut cur,
+ DecompLine {
+ line: lines.len() + 1,
+ machine_addr: None,
+ block_label: None,
+ tokens: Vec::new(),
+ },
+ ));
+ continue;
+ }
+ if text.contains('\n') {
+ for (i, part) in text.split('\n').enumerate() {
+ if i > 0 {
+ if cur.machine_addr.is_none() {
+ cur.machine_addr = cur.tokens.iter().find_map(|t| t.va);
+ }
+ lines.push(std::mem::replace(
+ &mut cur,
+ DecompLine {
+ line: lines.len() + 1,
+ machine_addr: None,
+ block_label: None,
+ tokens: Vec::new(),
+ },
+ ));
+ }
+ if !part.is_empty() {
+ cur.tokens.push(Token {
+ kind: tk,
+ text: part.to_string(),
+ va: *va,
+ });
+ }
+ }
+ continue;
+ }
+ cur.tokens.push(Token {
+ kind: tk,
+ text: text.clone(),
+ va: *va,
+ });
+ }
+ if !cur.tokens.is_empty() {
+ if cur.machine_addr.is_none() {
+ cur.machine_addr = cur.tokens.iter().find_map(|t| t.va);
+ }
+ lines.push(cur);
+ }
+ lines
+}
+
+/// Map `ghidrust_decomp::EmitToken` kinds into the adapter used by
+/// [`from_emit_tokens`].
+pub fn emit_token_triples(
+ tokens: &[ghidrust_decomp::EmitToken],
+) -> Vec<(String, Option<u64>, &'static str)> {
+ tokens
+ .iter()
+ .map(|t| {
+ let kind = match t.kind {
+ ghidrust_decomp::EmitTokenKind::Keyword => "keyword",
+ ghidrust_decomp::EmitTokenKind::Type => "type",
+ ghidrust_decomp::EmitTokenKind::Function => "function",
+ ghidrust_decomp::EmitTokenKind::Variable => "variable",
+ ghidrust_decomp::EmitTokenKind::Number => "number",
+ ghidrust_decomp::EmitTokenKind::String => "number",
+ ghidrust_decomp::EmitTokenKind::Comment => "comment",
+ ghidrust_decomp::EmitTokenKind::Operator => "syntax",
+ ghidrust_decomp::EmitTokenKind::Punct => "syntax",
+ ghidrust_decomp::EmitTokenKind::Label => "label",
+ ghidrust_decomp::EmitTokenKind::Address => "address",
+ ghidrust_decomp::EmitTokenKind::Text => "syntax",
+ };
+ (t.text.clone(), t.va, kind)
+ })
+ .collect()
+}
+
/// Parse a `block_N:` label at the start of a stripped line, else `None`.
fn block_label_from_line(line: &str) -> Option<String> {
let t = line.trim_start();
diff --git a/crates/ghidrust-gui/src/dock_tabs.rs b/crates/ghidrust-gui/src/dock_tabs.rs
index 121d75b..aa3c2c2 100644
--- a/crates/ghidrust-gui/src/dock_tabs.rs
+++ b/crates/ghidrust-gui/src/dock_tabs.rs
@@ -1,4 +1,4 @@
-//! Center-pane docking via `egui_dock` (Phase H+).
+//! Center-pane docking via `egui_dock`.
//!
//! Default layout: horizontal split (~55% | ~45%) with Listing+Overview on the
//! left and Decompiler on the right. Data Type Manager can be docked into
diff --git a/crates/ghidrust-gui/src/entropy.rs b/crates/ghidrust-gui/src/entropy.rs
index 9500a76..41e0406 100644
--- a/crates/ghidrust-gui/src/entropy.rs
+++ b/crates/ghidrust-gui/src/entropy.rs
@@ -1,11 +1,11 @@
-//! Ghidrust GUI · Phase E (M5) — Entropy strip + Overview banner.
+//! Ghidrust GUI · 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
+//! Extracted per internal modularization notes — new UI panes land here
//! instead of piling into `main.rs`.
use eframe::egui::{self, Color32, Rect, Sense, Stroke, StrokeKind, Ui, Vec2};
diff --git a/crates/ghidrust-gui/src/events.rs b/crates/ghidrust-gui/src/events.rs
index 6833ffe..b544a90 100644
--- a/crates/ghidrust-gui/src/events.rs
+++ b/crates/ghidrust-gui/src/events.rs
@@ -6,7 +6,7 @@
//! so cross‑window sync is centralised.
//!
//! This is a Stage‑1 skeleton: the bus is a plain `Vec<GhidrustEvent>` and consumers
-//! poll it. Fan‑out to individual providers is Phase B.
+//! poll it. Fan‑out to individual providers is still pending.
use crate::nav::NavLocation;
diff --git a/crates/ghidrust-gui/src/graphs.rs b/crates/ghidrust-gui/src/graphs.rs
index defc3fa..106225b 100644
--- a/crates/ghidrust-gui/src/graphs.rs
+++ b/crates/ghidrust-gui/src/graphs.rs
@@ -1,4 +1,4 @@
-//! Ghidrust GUI · Phase E (M5) — Function Graph, Function Call Graph,
+//! Ghidrust GUI · Function Graph, Function Call Graph,
//! Function Call Trees, and shared graph-layout helpers.
//!
//! These render Ghidra-analog dockable panes (`FunctionGraphPlugin`,
@@ -10,7 +10,7 @@
//! 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
+//! Extracted per internal modularization notes — new UI panes land here
//! instead of piling into `main.rs`.
use eframe::egui::{self, Color32, Pos2, Rect, Sense, Stroke, StrokeKind, Ui, Vec2};
diff --git a/crates/ghidrust-gui/src/layouts.rs b/crates/ghidrust-gui/src/layouts.rs
index f7de12b..f9bfe95 100644
--- a/crates/ghidrust-gui/src/layouts.rs
+++ b/crates/ghidrust-gui/src/layouts.rs
@@ -1,4 +1,4 @@
-//! Ghidrust GUI · Phase H (M8) — layout persistence + Configure dialog.
+//! Ghidrust GUI · layout persistence + Configure dialog.
//!
//! Ghidra's `docking` framework lets users move / tab / float providers
//! and save the result as a `.tool` XML preset. Ghidrust persists:
@@ -9,7 +9,7 @@
//! shim string for older layouts
//! - a read-only Configure dialog listing every compile-time plugin
//!
-//! Extracted per `dev/MODULARIZATION_PLAN.md` — new UI panes land here
+//! Extracted per internal modularization notes — new UI panes land here
//! instead of piling into `main.rs`.
use serde::{Deserialize, Serialize};
@@ -336,7 +336,7 @@ mod tests {
}
#[test]
- fn plugin_catalog_covers_new_phase_e_f_g_h_providers() {
+ fn plugin_catalog_covers_graph_debugger_configure_providers() {
let names: Vec<&'static str> = PLUGIN_CATALOG.iter().map(|p| p.name).collect();
for expected in [
"FunctionGraphPlugin",
diff --git a/crates/ghidrust-gui/src/main.rs b/crates/ghidrust-gui/src/main.rs
index 886b158..4805937 100644
--- a/crates/ghidrust-gui/src/main.rs
+++ b/crates/ghidrust-gui/src/main.rs
@@ -31,11 +31,13 @@ use icons::{m3_icon, m3_linear_progress, status_badge, M3Icon};
use menu_actions::{
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,
+ stage1_pseudo_c_with_tokens,
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,
+ emit_token_triples, from_emit_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};
@@ -323,7 +325,7 @@ pub struct GhidrustApp {
/// small chip in the Decompiler pane header so users know how much of
/// the emit came from real lifted IR vs Stage-0 scaffolding.
decomp_lift_ratio: Option<f32>,
- // ── Phase A (M1) — Ghidra CodeBrowser visible parity ────────────────
+ // ── Ghidra CodeBrowser visible parity ────────────────
/// Open-state per-provider (Window menu toggles → floating egui::Window per pane).
pane_open: BTreeMap<PaneKind, bool>,
/// Ghidra `NavigationHistoryPlugin` analog (Back / Forward / Alt+Left / Alt+Right).
@@ -347,61 +349,61 @@ pub struct GhidrustApp {
defined_strings_filter: String,
/// Defined Strings encoding filter: `"all"` | `"ascii"` | `"utf16le"`.
defined_strings_encoding: String,
- /// Phase B (M2) — plugin-event bus (Ghidra `PluginEvent` analog).
+ /// plugin-event bus (Ghidra `PluginEvent` analog).
event_bus: EventBus,
- /// Phase B (M2) — tokenised decompiler cache (rebuilt after every refresh_decompiler_at).
+ /// tokenised decompiler cache (rebuilt after every refresh_decompiler_at).
decomp_lines: Vec<DecompLine>,
- /// Phase B (M2) — line index in `decomp_lines` cross-highlighted from Listing cursor.
+ /// line index in `decomp_lines` cross-highlighted from Listing cursor.
decomp_cross_line: Option<usize>,
- /// Phase B (M2) — middle-click "highlight all occurrences" state.
+ /// middle-click "highlight all occurrences" state.
decomp_highlight_text: Option<String>,
- /// Phase B (M2) — Symbol Tree ↔ Listing selection navigation toggle.
+ /// Symbol Tree ↔ Listing selection navigation toggle.
symbol_tree_nav: bool,
- /// Phase B (M2) — currently-focused function entry (for Symbol Tree highlight).
+ /// currently-focused function entry (for Symbol Tree highlight).
focused_function_entry: Option<u64>,
- /// Phase B (M2) — Program Tree fragment filter. `None` = full view; `Some({names})` = only those.
+ /// Program Tree fragment filter. `None` = full view; `Some({names})` = only those.
listing_view_filter: Option<BTreeSet<String>>,
- /// Phase C (M3) — Rename dialog state.
+ /// Rename dialog state.
show_rename_dialog: bool,
rename_dialog_target_va: Option<u64>,
rename_dialog_old_name: String,
rename_dialog_new_name: String,
- /// Phase C (M3) — Retype dialog state.
+ /// Retype dialog state.
show_retype_dialog: bool,
retype_dialog_target_va: Option<u64>,
retype_dialog_type: String,
- /// Phase C (M3) — Comment dialog state.
+ /// Comment dialog state.
show_comment_dialog: bool,
comment_dialog_target_va: Option<u64>,
comment_dialog_kind: CommentKind,
comment_dialog_text: String,
- /// Phase C (M3) — Function Signature dialog state.
+ /// Function Signature dialog state.
show_fn_signature_dialog: bool,
fn_signature_dialog_entry: Option<u64>,
fn_signature_dialog_text: String,
- /// Phase C (M3) — New Structure / Union / Enum dialog state.
+ /// New Structure / Union / Enum dialog state.
show_new_type_dialog: bool,
new_type_dialog_kind: NewTypeKind,
new_type_dialog_name: String,
new_type_dialog_body: String,
- /// Phase C (M3) — Edit-existing-type dialog state (Ghidra structure /
+ /// Edit-existing-type dialog state (Ghidra structure /
/// union / enum / typedef editor).
show_edit_type_dialog: bool,
edit_type_dialog_orig_name: String,
edit_type_dialog_name: String,
edit_type_dialog_body: String,
- /// Phase C (M3) — Data Type Chooser dialog (`T` shortcut over Listing).
+ /// Data Type Chooser dialog (`T` shortcut over Listing).
show_type_chooser_dialog: bool,
type_chooser_target_va: Option<u64>,
type_chooser_filter: String,
- /// Phase C (M3) — DTM filter.
+ /// DTM filter.
dtm_filter: String,
- /// Phase C (M3) — Comment Window filters (Ghidra `CommentWindowPlugin`).
+ /// Comment Window filters (Ghidra `CommentWindowPlugin`).
comment_window_filter: String,
comment_window_kind_filter: Option<CommentKind>,
- /// Phase B (M2) — Console severity per line (`Info`, `Warn`, `Error`).
+ /// Console severity per line (`Info`, `Warn`, `Error`).
console_severity: Vec<ConsoleSeverity>,
- // ── Phase D (M4) — tables & search state ────────────────────────────
+ // ── tables & search state ────────────────────────────
/// Byte Viewer state (Ghidra `ByteViewerPlugin`).
bytes_pane_va: Option<u64>,
bytes_pane_bpr: usize,
@@ -440,7 +442,7 @@ pub struct GhidrustApp {
show_search_address_tables_dialog: bool,
/// Function Tags pane filter.
function_tags_filter: String,
- // ── Phase E (M5) — Graphs & maps ────────────────────────────────────
+ // ── Graphs & maps ────────────────────────────────────
/// Function Graph / Call Graph / Call Trees session state.
graph_state: GraphPaneState,
/// Function Call Trees — top-level nodes (rebuilt on cursor change).
@@ -455,19 +457,19 @@ pub struct GhidrustApp {
memory_map_new_r: bool,
memory_map_new_w: bool,
memory_map_new_x: bool,
- // ── Phase F (M6) — Scripts ──────────────────────────────────────────
+ // ── 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 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 ───────────────────
+ // ── Docking / layouts / Configure ───────────────────
/// Configure dialog (Ghidra `File → Configure` plugin picker).
show_configure_dialog: bool,
/// Layout preset save/load dialog state.
@@ -489,7 +491,7 @@ pub struct GhidrustApp {
show_gpu_decompile_dialog: bool,
}
-/// Phase D (M4) — Checksum Generator report (Ghidra `ComputeChecksumsPlugin`).
+/// Checksum Generator report (Ghidra `ComputeChecksumsPlugin`).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ChecksumReport {
pub target: String,
@@ -503,7 +505,7 @@ pub struct ChecksumReport {
pub fletcher32: u64,
}
-/// Phase B (M2) — severity tint for `Console` pane rows.
+/// severity tint for `Console` pane rows.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ConsoleSeverity {
Info,
@@ -511,7 +513,7 @@ enum ConsoleSeverity {
Error,
}
-/// Phase D (M4) — Checksum Generator scope (Ghidra `ComputeChecksumsPlugin`).
+/// Checksum Generator scope (Ghidra `ComputeChecksumsPlugin`).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ChecksumMode {
/// Concatenation of every loaded memory block.
@@ -562,7 +564,7 @@ fn fletcher_pair(data: &[u8]) -> (u32, u64) {
(f16, f32)
}
-/// Phase C (M3) — Data Type Manager `New` submenu kinds.
+/// Data Type Manager `New` submenu kinds.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum NewTypeKind {
Structure,
@@ -572,7 +574,7 @@ enum NewTypeKind {
FunctionDefinition,
}
-/// Phase B (M2) — one rendered Listing row (Ghidra `CodeUnit` columns).
+/// one rendered Listing row (Ghidra `CodeUnit` columns).
#[derive(Debug, Clone)]
struct ListingRow {
idx: usize,
@@ -597,7 +599,7 @@ struct ListingRow {
comment_repeat: Option<String>,
}
-/// Phase B (M2) — Ghidra scalar hover popup content for a Listing operand string.
+/// Ghidra scalar hover popup content for a Listing operand string.
///
/// Extracts the first hex/decimal literal and renders 1/2/4/8-byte dec/hex/ASCII
/// interpretations (matches Ghidra's "Scalar popup").
@@ -647,7 +649,7 @@ fn scalar_hint_string(v: u64) -> String {
)
}
-/// Phase B (M2) — Ghidra address hover popup content for a Listing operand string.
+/// Ghidra address hover popup content for a Listing operand string.
fn first_address_hint(operands: &str) -> Option<String> {
let idx = operands.find("0x")?;
let start = idx + 2;
@@ -662,7 +664,7 @@ fn first_address_hint(operands: &str) -> Option<String> {
Some(format!("target addr {va:#x}"))
}
-/// Phase B (M2) — Ghidra `ClangToken`-analog syntax colour picker for the Decompiler pane.
+/// Ghidra `ClangToken`-analog syntax colour picker for the Decompiler pane.
fn token_style(kind: &TokenKind, base: Color32) -> (Color32, bool) {
match kind {
// Keywords: cyan (Ghidra "colors.decompiler.keyword").
@@ -829,7 +831,7 @@ impl GhidrustApp {
decomp_entry: None,
decomp_text: String::new(),
decomp_status: String::new(),
- // Phase F: Stage-1 is now the default GUI decompiler stage —
+ // 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.
@@ -1000,6 +1002,36 @@ impl GhidrustApp {
return;
}
let stage = self.decomp_stage;
+ // R5: Stage-1 prefers emit-time tokens when present.
+ if stage == DecompStage::Stage1 {
+ if let Ok((entry, text, ratio, tokens)) =
+ stage1_pseudo_c_with_tokens(prog, va, STAGE0_MAX_INSNS)
+ {
+ self.decomp_entry = Some(entry);
+ let triples = emit_token_triples(&tokens);
+ let lines = from_emit_tokens(&triples);
+ self.decomp_lines = if lines.is_empty() {
+ tokenize_decomp(&text)
+ } else {
+ lines
+ };
+ self.decomp_cross_line = decomp_line_for_va(&self.decomp_lines, va);
+ self.decomp_text = text;
+ self.decomp_lift_ratio = Some(ratio);
+ let user_name = self
+ .program
+ .as_ref()
+ .and_then(|p| p.display_function_name_at(entry));
+ self.decomp_status = match user_name {
+ Some(name) => format!(
+ "Stage-1 · {name} @ {entry:#x} · lift={:.1}%",
+ ratio * 100.0
+ ),
+ None => format!("Stage-1 · {entry:#x} · lift={:.1}%", ratio * 100.0),
+ };
+ return;
+ }
+ }
let attempt = pseudo_c_for_stage(prog, va, STAGE0_MAX_INSNS, stage);
let (label, result) = match attempt {
Ok(v) => (stage.label(), Ok(v)),
@@ -1238,7 +1270,7 @@ impl GhidrustApp {
}
}
- // ── Phase C (M3) — user edits ───────────────────────────────────────
+ // ── user edits ───────────────────────────────────────
/// Rename the symbol / function at `va` (persists into `Program::edits`).
///
@@ -1558,7 +1590,7 @@ impl GhidrustApp {
Ok(name)
}
- // ── Phase D (M4) — equates, function tags, xrefs, checksums ──────────
+ // ── equates, function tags, xrefs, checksums ──────────
/// Attach an equate `name` at `(va, op)` for scalar `value` (Ghidra
/// `Convert → Equate`). Empty `name` clears the equate.
@@ -1880,7 +1912,7 @@ impl GhidrustApp {
(imports, exports)
}
- /// Phase B (M2) — drain queued events and fan them out to subscribers.
+ /// drain queued events and fan them out to subscribers.
///
/// This is intentionally minimal today: any ProgramMutated event invalidates
/// the Decompiler cache so the next `refresh_decompiler_at` re-runs Stage-0.
@@ -2916,12 +2948,12 @@ impl GhidrustApp {
self.log_with(msg, ConsoleSeverity::Info);
}
- /// Phase B (M2) — Console warning (amber tint).
+ /// Console warning (amber tint).
fn log_warn(&mut self, msg: impl Into<String>) {
self.log_with(msg, ConsoleSeverity::Warn);
}
- /// Phase B (M2) — Console error (red tint).
+ /// Console error (red tint).
fn log_error(&mut self, msg: impl Into<String>) {
self.log_with(msg, ConsoleSeverity::Error);
}
@@ -3335,7 +3367,7 @@ impl GhidrustApp {
names.push(t);
}
}
- // Ghidra Debugger tool providers (Phase G / M7 visibility parity).
+ // Ghidra Debugger tool providers (visibility parity).
for p in DebuggerPane::ALL {
let t = p.title();
if !names.contains(&t) {
@@ -3609,7 +3641,7 @@ impl GhidrustApp {
}
}
- /// Phase A (M1) — render every currently open floating provider pane.
+ /// render every currently open floating provider pane.
///
/// Panes render either real Stage-0 content (Bookmarks, Memory Map, Functions,
/// Symbol Table, Defined Strings, Relocations) or a clearly labelled "backend
@@ -3690,7 +3722,7 @@ impl GhidrustApp {
PaneKind::ChecksumGenerator => {
win.show(ctx, |ui| self.ui_checksum_generator(ui, muted));
}
- // Phase E (M5) — Graphs & maps.
+ // Graphs & maps.
PaneKind::FunctionGraph => {
win.default_size(egui::vec2(760.0, 520.0))
.show(ctx, |ui| self.ui_function_graph_pane(ui, muted, primary));
@@ -3715,7 +3747,7 @@ impl GhidrustApp {
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.
+ // Scripts & interpreters.
PaneKind::ScriptManager => {
win.default_size(egui::vec2(760.0, 480.0))
.show(ctx, |ui| self.ui_script_manager_pane(ui, muted, primary));
@@ -3773,11 +3805,11 @@ impl GhidrustApp {
}
}
- // Phase G (M7) — Debugger tool provider windows.
+ // Debugger tool provider windows.
self.draw_debugger_panes(ctx, muted);
}
- // ── Phase E (M5) — Graphs & maps ────────────────────────────────────
+ // ── 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) {
@@ -4129,12 +4161,12 @@ impl GhidrustApp {
register_manager::render(&mut self.register_manager, fmt.as_deref(), ui, muted, primary);
}
- // ── Phase F (M6) — Scripts & interpreters ───────────────────────────
+ // ── 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"
+ "Script Manager · run requested for `{run}` — full script host not yet wired"
);
self.status = msg.clone();
self.log(msg);
@@ -4180,7 +4212,7 @@ impl GhidrustApp {
render_mcp_repl(&mut self.mcp_repl, ui, muted, primary);
}
- // ── Phase G (M7) — Debugger tool ──────────────────────────────────
+ // ── Debugger tool ──────────────────────────────────
fn draw_debugger_panes(&mut self, ctx: &egui::Context, muted: Color32) {
let open_list: Vec<DebuggerPane> = self
@@ -4206,7 +4238,7 @@ impl GhidrustApp {
}
}
- // ── Phase H (M8) — Docking / layouts / Configure ────────────────
+ // ── Docking / layouts / Configure ────────────────
fn snapshot_current_layout(&self, name: impl Into<String>) -> layouts::SavedLayout {
let name = name.into();
@@ -4306,7 +4338,7 @@ impl GhidrustApp {
Ok(())
}
- /// Phase C (M3) — draw all edit dialogs (rename / retype / comment / signature / new type).
+ /// draw all edit dialogs (rename / retype / comment / signature / new type).
fn draw_edit_dialogs(&mut self, ctx: &egui::Context) {
// Rename dialog (Ghidra `L` / Rename Variable).
if self.show_rename_dialog {
@@ -4723,7 +4755,7 @@ impl GhidrustApp {
}
}
- /// Phase C (M3) — Data Type Manager tree (Built-In archive + Program archive).
+ /// Data Type Manager tree (Built-In archive + Program archive).
fn ui_dtm_pane(&mut self, ui: &mut egui::Ui) {
ui.heading("Data Type Manager");
ui.small(
@@ -4994,7 +5026,7 @@ impl GhidrustApp {
egui::RichText::new(
"Right-click a type for Edit / Rename / Delete / Apply @ cursor / \
New Typedef on X / New Pointer to X. Docking-framework drag-and-drop \
- lands in Phase H.",
+ not yet wired.",
)
.weak()
.italics(),
@@ -5049,7 +5081,7 @@ impl GhidrustApp {
}
}
- /// Phase B (M2) — Listing center pane with real fields, margin markers, and flow arrows.
+ /// Listing center pane with real fields, margin markers, and flow arrows.
fn ui_listing_pane(&mut self, ui: &mut egui::Ui) {
ui.heading("Listing");
// Status strip.
@@ -5481,7 +5513,7 @@ impl GhidrustApp {
}
}
- /// Phase B (M2) — tokenised Decompiler center pane with cross-highlight.
+ /// tokenised Decompiler center pane with cross-highlight.
fn ui_decompiler_pane(&mut self, ui: &mut egui::Ui) {
ui.heading("Decompiler");
if self.program.is_none() {
@@ -6353,7 +6385,7 @@ impl GhidrustApp {
fn ui_relocation_table(&mut self, ui: &mut egui::Ui, muted: Color32) {
ui.heading("Relocation Table");
ui.small(
- egui::RichText::new("Ghidra RelocationTablePlugin · from Program::sections (Phase D fills)")
+ egui::RichText::new("Ghidra RelocationTablePlugin · from Program::sections")
.color(muted),
);
ui.separator();
@@ -6364,7 +6396,7 @@ impl GhidrustApp {
ui.small(
egui::RichText::new(
"Section metadata rendered here as a Stage-0 placeholder. Full PE reloc / ELF rela \
- parse lands in Phase D (M4).",
+ parse lands in .",
)
.color(muted)
.italics(),
@@ -6554,7 +6586,7 @@ impl GhidrustApp {
fn ui_defined_data(&mut self, ui: &mut egui::Ui, muted: Color32) {
ui.heading("Defined Data");
ui.small(
- egui::RichText::new("Ghidra DataWindowPlugin · session data (Phase D adds Program::data_items)")
+ egui::RichText::new("Ghidra DataWindowPlugin · session data (Program::data_items when available)")
.color(muted),
);
ui.separator();
@@ -6623,7 +6655,7 @@ impl GhidrustApp {
}
}
- // ── Phase D (M4) — Byte Viewer / Symbol References / Equates / Tags ─
+ // ── 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,
@@ -7369,7 +7401,7 @@ impl eframe::App for GhidrustApp {
fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
self.apply_theme(ctx);
- // Phase B (M2) — drain event bus once per frame and fan out.
+ // drain event bus once per frame and fan out.
self.drain_events();
// Startup: choose project before the empty shell
@@ -7409,11 +7441,11 @@ impl eframe::App for GhidrustApp {
self.browse_and_load_binary();
ui.close_menu();
}
- if ui.button("Add To Program…").on_hover_text("Not yet implemented — Phase D").clicked() {
+ if ui.button("Add To Program…").on_hover_text("Not yet implemented").clicked() {
self.nyi("File → Add To Program");
ui.close_menu();
}
- if ui.button("Batch Import…").on_hover_text("Not yet implemented — Phase D").clicked() {
+ if ui.button("Batch Import…").on_hover_text("Not yet implemented").clicked() {
self.nyi("File → Batch Import");
ui.close_menu();
}
@@ -7425,11 +7457,11 @@ impl eframe::App for GhidrustApp {
}
ui.close_menu();
}
- if ui.button("Save As…").on_hover_text("Not yet implemented — Phase B").clicked() {
+ if ui.button("Save As…").on_hover_text("Not yet implemented").clicked() {
self.nyi("File → Save As");
ui.close_menu();
}
- if ui.button("Export Program…").on_hover_text("Not yet implemented — Phase D").clicked() {
+ if ui.button("Export Program…").on_hover_text("Not yet implemented").clicked() {
self.nyi("File → Export Program");
ui.close_menu();
}
@@ -7438,16 +7470,16 @@ impl eframe::App for GhidrustApp {
self.nyi("File → Load PDB File");
ui.close_menu();
}
- if ui.button("Parse C Source…").on_hover_text("Not yet implemented — Phase C").clicked() {
+ if ui.button("Parse C Source…").on_hover_text("Not yet implemented").clicked() {
self.nyi("File → Parse C Source");
ui.close_menu();
}
ui.separator();
- if ui.button("Configure…").on_hover_text("Plugin picker — Phase H").clicked() {
+ if ui.button("Configure…").on_hover_text("Plugin picker — not yet implemented").clicked() {
self.nyi("File → Configure");
ui.close_menu();
}
- if ui.button("Print…").on_hover_text("Not yet implemented — Phase D").clicked() {
+ if ui.button("Print…").on_hover_text("Not yet implemented").clicked() {
self.nyi("File → Print");
ui.close_menu();
}
@@ -7477,19 +7509,19 @@ impl eframe::App for GhidrustApp {
ui.close_menu();
}
ui.separator();
- if ui.button("Tool Options…").on_hover_text("Options tree — Phase H").clicked() {
+ if ui.button("Tool Options…").on_hover_text("Options tree — not yet implemented").clicked() {
self.nyi("Edit → Tool Options");
ui.close_menu();
}
- if ui.button("Options for program…").on_hover_text("Program-level options — Phase C").clicked() {
+ if ui.button("Options for program…").on_hover_text("Program-level options — not yet implemented").clicked() {
self.nyi("Edit → Options for program");
ui.close_menu();
}
- if ui.button("Plugin Path…").on_hover_text("Configure plugin paths — Phase H").clicked() {
+ if ui.button("Plugin Path…").on_hover_text("Configure plugin paths — not yet implemented").clicked() {
self.nyi("Edit → Plugin Path");
ui.close_menu();
}
- if ui.button("Key Bindings…").on_hover_text("Rebind actions — Phase H").clicked() {
+ if ui.button("Key Bindings…").on_hover_text("Rebind actions — not yet implemented").clicked() {
self.nyi("Edit → Key Bindings");
ui.close_menu();
}
@@ -7505,7 +7537,7 @@ impl eframe::App for GhidrustApp {
self.show_analysis_dialog = true;
ui.close_menu();
}
- if ui.button("Analyze All Open…").on_hover_text("Multi-program batch — Phase D").clicked() {
+ if ui.button("Analyze All Open…").on_hover_text("Multi-program batch — not yet implemented").clicked() {
self.nyi("Analysis → Analyze All Open");
ui.close_menu();
}
@@ -7591,11 +7623,11 @@ impl eframe::App for GhidrustApp {
self.nav_prev_function();
ui.close_menu();
}
- if ui.button("Next Data").on_hover_text("Not yet implemented — Phase D").clicked() {
+ if ui.button("Next Data").on_hover_text("Not yet implemented").clicked() {
self.nyi("Navigation → Next Data");
ui.close_menu();
}
- if ui.button("Next Undefined").on_hover_text("Not yet implemented — Phase D").clicked() {
+ if ui.button("Next Undefined").on_hover_text("Not yet implemented").clicked() {
self.nyi("Navigation → Next Undefined");
ui.close_menu();
}
@@ -7640,15 +7672,15 @@ impl eframe::App for GhidrustApp {
self.show_search_insn_dialog = true;
ui.close_menu();
}
- if ui.button("For Direct References…").on_hover_text("Not yet implemented — Phase D").clicked() {
+ if ui.button("For Direct References…").on_hover_text("Not yet implemented").clicked() {
self.nyi("Search → For Direct References");
ui.close_menu();
}
- if ui.button("For Matching Instructions…").on_hover_text("Not yet implemented — Phase D").clicked() {
+ if ui.button("For Matching Instructions…").on_hover_text("Not yet implemented").clicked() {
self.nyi("Search → For Matching Instructions");
ui.close_menu();
}
- if ui.button("Repeat Search").on_hover_text("Not yet implemented — Phase D").clicked() {
+ if ui.button("Repeat Search").on_hover_text("Not yet implemented").clicked() {
self.nyi("Search → Repeat Search");
ui.close_menu();
}
@@ -7658,7 +7690,7 @@ impl eframe::App for GhidrustApp {
self.select_all_listing();
ui.close_menu();
}
- if ui.button("All in View").on_hover_text("Not yet implemented — Phase B").clicked() {
+ if ui.button("All in View").on_hover_text("Not yet implemented").clicked() {
self.nyi("Select → All in View");
ui.close_menu();
}
@@ -7666,45 +7698,45 @@ impl eframe::App for GhidrustApp {
self.edit_clear_selection();
ui.close_menu();
}
- if ui.button("Complement").on_hover_text("Not yet implemented — Phase B").clicked() {
+ if ui.button("Complement").on_hover_text("Not yet implemented").clicked() {
self.nyi("Select → Complement");
ui.close_menu();
}
ui.separator();
- if ui.button("Bytes").on_hover_text("Not yet implemented — Phase D").clicked() {
+ if ui.button("Bytes").on_hover_text("Not yet implemented").clicked() {
self.nyi("Select → Bytes");
ui.close_menu();
}
- if ui.button("Instructions").on_hover_text("Not yet implemented — Phase D").clicked() {
+ if ui.button("Instructions").on_hover_text("Not yet implemented").clicked() {
self.nyi("Select → Instructions");
ui.close_menu();
}
- if ui.button("Data").on_hover_text("Not yet implemented — Phase D").clicked() {
+ if ui.button("Data").on_hover_text("Not yet implemented").clicked() {
self.nyi("Select → Data");
ui.close_menu();
}
- if ui.button("Undefined").on_hover_text("Not yet implemented — Phase D").clicked() {
+ if ui.button("Undefined").on_hover_text("Not yet implemented").clicked() {
self.nyi("Select → Undefined");
ui.close_menu();
}
- if ui.button("Function").on_hover_text("Not yet implemented — Phase B").clicked() {
+ if ui.button("Function").on_hover_text("Not yet implemented").clicked() {
self.nyi("Select → Function");
ui.close_menu();
}
- if ui.button("Subroutine").on_hover_text("Not yet implemented — Phase B").clicked() {
+ if ui.button("Subroutine").on_hover_text("Not yet implemented").clicked() {
self.nyi("Select → Subroutine");
ui.close_menu();
}
- if ui.button("Forward Refs").on_hover_text("Not yet implemented — Phase D").clicked() {
+ if ui.button("Forward Refs").on_hover_text("Not yet implemented").clicked() {
self.nyi("Select → Forward Refs");
ui.close_menu();
}
- if ui.button("Backward Refs").on_hover_text("Not yet implemented — Phase D").clicked() {
+ if ui.button("Backward Refs").on_hover_text("Not yet implemented").clicked() {
self.nyi("Select → Backward Refs");
ui.close_menu();
}
ui.separator();
- if ui.button("Create Table From Selection").on_hover_text("Not yet implemented — Phase D").clicked() {
+ if ui.button("Create Table From Selection").on_hover_text("Not yet implemented").clicked() {
self.nyi("Select → Create Table From Selection");
ui.close_menu();
}
@@ -7714,11 +7746,11 @@ impl eframe::App for GhidrustApp {
self.show_processor_dialog = true;
ui.close_menu();
}
- if ui.button("Compare Program…").on_hover_text("Not yet implemented — Phase D").clicked() {
+ if ui.button("Compare Program…").on_hover_text("Not yet implemented").clicked() {
self.nyi("Tools → Compare Program");
ui.close_menu();
}
- if ui.button("Program Differences…").on_hover_text("Not yet implemented — Phase D").clicked() {
+ if ui.button("Program Differences…").on_hover_text("Not yet implemented").clicked() {
self.nyi("Tools → Program Differences");
ui.close_menu();
}
@@ -7726,15 +7758,15 @@ impl eframe::App for GhidrustApp {
self.pane_open.insert(PaneKind::ChecksumGenerator, true);
ui.close_menu();
}
- if ui.button("Function Bit Patterns Explorer").on_hover_text("Not yet implemented — Phase D").clicked() {
+ if ui.button("Function Bit Patterns Explorer").on_hover_text("Not yet implemented").clicked() {
self.nyi("Tools → Function Bit Patterns Explorer");
ui.close_menu();
}
- if ui.button("Instruction Table").on_hover_text("Not yet implemented — Phase D").clicked() {
+ if ui.button("Instruction Table").on_hover_text("Not yet implemented").clicked() {
self.nyi("Tools → Instruction Table");
ui.close_menu();
}
- if ui.button("Processor Manual…").on_hover_text("Not yet implemented — Phase D").clicked() {
+ if ui.button("Processor Manual…").on_hover_text("Not yet implemented").clicked() {
self.nyi("Tools → Processor Manual");
ui.close_menu();
}
@@ -7753,19 +7785,19 @@ impl eframe::App for GhidrustApp {
ui.close_menu();
}
ui.separator();
- if ui.button("Block Flow").on_hover_text("Not yet implemented — Phase E").clicked() {
+ if ui.button("Block Flow").on_hover_text("Not yet implemented").clicked() {
self.nyi("Graph → Block Flow");
ui.close_menu();
}
- if ui.button("Code Flow").on_hover_text("Not yet implemented — Phase E").clicked() {
+ if ui.button("Code Flow").on_hover_text("Not yet implemented").clicked() {
self.nyi("Graph → Code Flow");
ui.close_menu();
}
- if ui.button("Calls").on_hover_text("Not yet implemented — Phase E").clicked() {
+ if ui.button("Calls").on_hover_text("Not yet implemented").clicked() {
self.nyi("Graph → Calls");
ui.close_menu();
}
- if ui.button("Data Flow").on_hover_text("Not yet implemented — Phase E").clicked() {
+ if ui.button("Data Flow").on_hover_text("Not yet implemented").clicked() {
self.nyi("Graph → Data Flow");
ui.close_menu();
}
@@ -7835,7 +7867,7 @@ impl eframe::App for GhidrustApp {
}
}
ui.separator();
- // Phase G (M7) — Debugger tool providers.
+ // 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());
@@ -7846,7 +7878,7 @@ impl eframe::App for GhidrustApp {
}
}
ui.separator();
- // Phase H (M8) — layout tools.
+ // layout tools.
if ui.button("Configure plugins…").clicked() {
self.show_configure_dialog = true;
ui.close_menu();
@@ -7899,19 +7931,19 @@ impl eframe::App for GhidrustApp {
}
});
ui.menu_button("Help", |ui| {
- if ui.button("Contents (F1)").on_hover_text("Not yet implemented — Phase A").clicked() {
+ if ui.button("Contents (F1)").on_hover_text("Not yet implemented").clicked() {
self.nyi("Help → Contents");
ui.close_menu();
}
- if ui.button("Help On…").on_hover_text("Not yet implemented — Phase A").clicked() {
+ if ui.button("Help On…").on_hover_text("Not yet implemented").clicked() {
self.nyi("Help → Help On");
ui.close_menu();
}
- if ui.button("Ghidra API Help").on_hover_text("Not yet implemented — Phase A").clicked() {
+ if ui.button("Ghidra API Help").on_hover_text("Not yet implemented").clicked() {
self.nyi("Help → Ghidra API Help");
ui.close_menu();
}
- if ui.button("User Preferences").on_hover_text("Not yet implemented — Phase H").clicked() {
+ if ui.button("User Preferences").on_hover_text("Not yet implemented").clicked() {
self.nyi("Help → User Preferences");
ui.close_menu();
}
@@ -9139,13 +9171,13 @@ impl eframe::App for GhidrustApp {
self.sync_center_from_dock();
});
- // Phase A (M1) — draw every open floating provider pane.
+ // draw every open floating provider pane.
self.draw_provider_panes(ctx);
- // Phase C (M3) — edit dialogs (rename / retype / comment / signature / new type).
+ // edit dialogs (rename / retype / comment / signature / new type).
self.draw_edit_dialogs(ctx);
- // Phase H (M8) — Configure plugins dialog.
+ // Configure plugins dialog.
if self.show_configure_dialog {
let mut close = false;
egui::Window::new("Configure plugins")
@@ -9189,7 +9221,7 @@ impl eframe::App for GhidrustApp {
}
}
- // Phase H (M8) — Layout save / load dialog.
+ // Layout save / load dialog.
if self.show_layouts_dialog {
let mut close = false;
let mut do_save = false;
@@ -9897,13 +9929,13 @@ mod tests {
);
}
- /// Phase A (M1) — every Ghidra CodeBrowser provider must be enumerated in
+ /// every Ghidra CodeBrowser provider must be enumerated in
/// `shell_panes()` so the Window menu / structural tests can enforce visibility parity.
#[test]
fn shell_panes_enumerates_full_ghidra_codebrowser_catalog() {
let panes = GhidrustApp::shell_panes();
// 28 default `CodeBrowser.tool` providers + a few off-layout ones. See
- // dev/UI_PARITY_PLAN.md § 1.1 / § 1.2 for the source of truth.
+ // internal UI notes § 1.1 / § 1.2 for the source of truth.
for expected in [
"Program Trees",
"Symbol Tree",
@@ -9945,7 +9977,7 @@ mod tests {
}
}
- /// Phase A (M1) — Back / Forward history is wired.
+ /// Back / Forward history is wired.
#[test]
fn nav_history_records_and_navigates() {
let mut app = GhidrustApp::headless();
@@ -9978,7 +10010,7 @@ mod tests {
assert_eq!(app.listing_focus_va, Some(second_va));
}
- /// Phase A (M1) — Bookmarks pane model is real (5 Ghidra kinds; add/delete flow).
+ /// Bookmarks pane model is real (5 Ghidra kinds; add/delete flow).
#[test]
fn bookmark_model_add_delete_and_nav() {
let mut app = GhidrustApp::headless();
@@ -10009,7 +10041,7 @@ mod tests {
}
}
- /// Phase B (M2) — plugin event bus emits CursorMoved on goto and Mutation on bookmark ops.
+ /// plugin event bus emits CursorMoved on goto and Mutation on bookmark ops.
#[test]
fn event_bus_publishes_cursor_and_mutation_events() {
let mut app = GhidrustApp::headless();
@@ -10058,7 +10090,7 @@ mod tests {
assert!(app.drain_events().is_empty());
}
- /// Phase A (M1) — provider pane toggles are per-kind and persist through frames.
+ /// provider pane toggles are per-kind and persist through frames.
#[test]
fn toggle_pane_state_persists() {
let mut app = GhidrustApp::headless();
@@ -10180,7 +10212,7 @@ mod tests {
#[test]
fn headless_stage0_decompiler_wires_on_focus() {
- // Phase F: Stage-1 is the GUI default. The old assertion demanded a
+ // 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.
@@ -10346,7 +10378,7 @@ mod tests {
assert!(info.language.contains("x86"));
}
- // ─── Phase B (M2) — token model, listing sync, view filter, next/prev fn ───
+ // ─── token model, listing sync, view filter, next/prev fn ───
#[test]
fn decompiler_tokens_are_populated_and_cross_highlight() {
@@ -10358,7 +10390,7 @@ mod tests {
!app.decomp_lines.is_empty(),
"token cache must be populated after refresh_decompiler_at"
);
- // Post Phase F the default GUI stage is Stage-1; the emitter drops
+ // 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.
@@ -10465,7 +10497,7 @@ mod tests {
}
}
- // ─── Phase C (M3) — rename / retype / comment / signature / type ───
+ // ─── rename / retype / comment / signature / type ───
#[test]
fn rename_persists_and_reflects_in_analysis() {
@@ -10594,7 +10626,7 @@ mod tests {
assert!(first_scalar_hint("rax, rbx").is_none());
}
- // ─── Phase C (M3) polish — DTM editing / chooser / persistence ────
+ // ─── polish — DTM editing / chooser / persistence ────
#[test]
fn rename_and_delete_user_type_rewrites_applied_types() {
@@ -10830,7 +10862,7 @@ mod tests {
);
}
- // ─── Phase D (M4) — tables, xrefs, equates, tags, search dialogs ────
+ // ─── tables, xrefs, equates, tags, search dialogs ────
#[test]
fn xrefs_to_and_from_return_honest_rows_on_fixture() {
@@ -10971,9 +11003,9 @@ mod tests {
assert!(app.parse_scalar_input("").is_err());
}
- // ── Phase E (M5) — Graphs & maps ─────────────────────────────────────
+ // ── Graphs & maps ─────────────────────────────────────
- /// Phase E — Function Graph derives Stage-0 blocks + edges from the
+ /// Function Graph derives Stage-0 blocks + edges from the
/// currently-focused function's CFG (honest empty if the region has
/// no recovered blocks).
#[test]
@@ -11004,7 +11036,7 @@ mod tests {
}
}
- /// Phase E — Function Call Graph roots at the current function with
+ /// 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() {
@@ -11016,7 +11048,7 @@ mod tests {
assert_eq!(app.graph_state.call_graph_levels_in, 2);
}
- /// Phase E — Editable Memory Map: RWX toggles + add + delete flow.
+ /// Editable Memory Map: RWX toggles + add + delete flow.
#[test]
fn memory_map_edit_flow_adds_and_deletes_blocks() {
let mut app = GhidrustApp::headless();
@@ -11046,7 +11078,7 @@ mod tests {
assert_eq!(app.program.as_ref().unwrap().blocks.len(), n0);
}
- /// Phase E — Register Manager lattice is present and set/clear works.
+ /// Register Manager lattice is present and set/clear works.
#[test]
fn register_manager_lattice_and_values() {
let mut app = GhidrustApp::headless();
@@ -11063,7 +11095,7 @@ mod tests {
assert_eq!(app.register_manager.values.len(), 1);
}
- /// Phase E — Entropy strip samples cover mapped bytes without fabricating.
+ /// Entropy strip samples cover mapped bytes without fabricating.
#[test]
fn entropy_samples_cover_mapped_blocks() {
let mut app = GhidrustApp::headless();
@@ -11075,7 +11107,7 @@ mod tests {
}
}
- // ── Phase F (M6) — Scripts ───────────────────────────────────────────
+ // ── Scripts ───────────────────────────────────────────
#[test]
fn script_manager_catalog_is_populated_from_mcp_surface() {
@@ -11105,7 +11137,7 @@ mod tests {
assert!(!app.mcp_repl.transcript[1].prompt);
}
- // ── Phase G (M7) — Debugger visibility ──────────────────────────────
+ // ── Debugger visibility ──────────────────────────────
#[test]
fn debugger_panes_enumerated_in_shell_panes() {
@@ -11152,7 +11184,7 @@ mod tests {
assert_eq!(app.debugger.watches.len(), 2);
}
- // ── Phase H (M8) — Docking / layouts ────────────────────────────────
+ // ── Docking / layouts ────────────────────────────────
#[test]
fn save_and_restore_layout_round_trip() {
@@ -11213,15 +11245,15 @@ mod tests {
}
#[test]
- fn phase_e_f_g_h_menu_actions_wired_not_nyi() {
+ fn graph_debugger_configure_menu_actions_wired_not_nyi() {
let src = include_str!("main.rs");
- // Phase E — graph menu items open panes (not nyi).
+ // 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.
+ // Debugger menu is registered.
assert!(src.contains("ui.menu_button(\"Debugger\","));
- // Phase H — Configure dialog + Save Tool Layout menu items are wired.
+ // 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 c463a0b..4aff7ad 100644
--- a/crates/ghidrust-gui/src/menu_actions.rs
+++ b/crates/ghidrust-gui/src/menu_actions.rs
@@ -489,11 +489,21 @@ pub fn stage1_pseudo_c(
va: u64,
max_insns: usize,
) -> Result<(u64, String, f32), String> {
+ let (entry, text, ratio, _tokens) = stage1_pseudo_c_with_tokens(prog, va, max_insns)?;
+ Ok((entry, text, ratio))
+}
+
+/// Stage-1 with emit-time tokens for GUI navigation (R5).
+pub fn stage1_pseudo_c_with_tokens(
+ prog: &Program,
+ va: u64,
+ max_insns: usize,
+) -> Result<(u64, String, f32, Vec<ghidrust_decomp::EmitToken>), String> {
let entry = decompile_entry_for_va(prog, va);
let (_d, rep) =
ghidrust_decomp::decompile_stage1_at(prog, entry, max_insns, ghidrust_types::CallConv::Windows)
.map_err(|e| e.to_string())?;
- Ok((entry, rep.pseudo_c, rep.coverage.ratio()))
+ Ok((entry, rep.pseudo_c, rep.coverage.ratio(), rep.tokens))
}
/// Dispatcher used by the GUI to render whichever stage the user selected.
diff --git a/crates/ghidrust-gui/src/panes.rs b/crates/ghidrust-gui/src/panes.rs
index 825747d..0828aaf 100644
--- a/crates/ghidrust-gui/src/panes.rs
+++ b/crates/ghidrust-gui/src/panes.rs
@@ -1,11 +1,11 @@
-//! Ghidra CodeBrowser provider catalog for Phase A (M1) visible parity.
+//! Ghidra CodeBrowser provider catalog for visible parity.
//!
//! Every provider bundled with Ghidra's default `CodeBrowser.tool`, plus commonly-reached
//! providers from `Window` menu, is enumerated here with the exact Ghidra title so muscle
//! memory transfers. Providers whose backing analysis is not yet implemented render a
//! clearly labelled empty state that names the analyzer/model required — never fake data.
//!
-//! Source anchors: see `dev/UI_PARITY_PLAN.md` § 1.1 and § 1.2.
+//! Source anchors: see internal UI notes § 1.1 and § 1.2.
use eframe::egui::{self, Color32, RichText, Ui};
@@ -236,7 +236,7 @@ impl PaneKind {
| PaneKind::RelocationTable
| PaneKind::DisassembledView
| PaneKind::DefinedData
- // Phase D (M4) — real backing added.
+ // real backing added.
| PaneKind::Bytes
| PaneKind::SymbolReferences
| PaneKind::EquatesTable
@@ -367,47 +367,47 @@ pub fn empty_state(ui: &mut Ui, kind: PaneKind, muted: Color32) {
.italics(),
);
ui.add_space(4.0);
- ui.small(RichText::new("Pane is present for Ghidra visibility parity (M1). Backing analysis \
+ ui.small(RichText::new("Pane is present for Ghidra visibility parity . Backing analysis \
and interactive actions land in later phases — see \
- dev/UI_PARITY_PLAN.md.").color(muted));
+ internal UI notes.").color(muted));
}
/// One-liner hint pointing at which analyzer/model would fill this pane.
pub const fn backend_pending_message(kind: PaneKind) -> &'static str {
match kind {
PaneKind::AgentConsole => "",
- PaneKind::Bookmarks => "Backend pending — Bookmarks model + margin markers land in Phase B (M2).",
+ PaneKind::Bookmarks => "Backend pending — Bookmarks model + margin markers land in .",
PaneKind::Bytes => "",
PaneKind::ChecksumGenerator => "",
- PaneKind::CommentWindow => "Backend pending — comment model lands in Phase C (M3).",
+ PaneKind::CommentWindow => "Backend pending — comment model lands in .",
PaneKind::Console => "",
- PaneKind::DataTypeManager => "Backend pending — DTM tree (Built-In / Program / Archive) lands in Phase C (M3).",
+ PaneKind::DataTypeManager => "Backend pending — DTM tree (Built-In / Program / Archive) lands in .",
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::DecompiledView => "Stage-1 SSA-C (expression fold + typed locals/params). Emit-time tokens when available; rename/commit wired.",
+ PaneKind::DefinedData => "Backend pending — Program::data_items model lands in .",
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::DisassembledView => "Backend pending — virtual disassembly + pcode preview lands in .",
+ PaneKind::Entropy => "Backend pending — GPU/CPU histogram lands in .",
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::FunctionCallGraph => "Backend pending — level-based directed graph lands in .",
+ PaneKind::FunctionCallTrees => "Backend pending — incoming/outgoing GTree pair lands in .",
+ PaneKind::FunctionGraph => "Backend pending — CFG vertex/edge layout lands in .",
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).",
+ PaneKind::MemoryMap => "Uses Program::blocks / Program::sections (read-only). Editable table lands in .",
PaneKind::Overview => "",
PaneKind::ProgramTree => "",
PaneKind::ProjectTree => "",
- PaneKind::Python => "Backend pending — scripting host / MCP REPL lands in Phase F (M6).",
- 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::Python => "Backend pending — scripting host / MCP REPL lands in .",
+ PaneKind::RegisterManager => "Backend pending — SLEIGH register lattice lands in .",
+ PaneKind::RelocationTable => "Uses Program::sections metadata; full PE/ELF reloc parse lands in .",
+ PaneKind::ScriptManager => "Backend pending — script catalog lands in .",
PaneKind::SymbolReferences => "",
PaneKind::SymbolTable => "Uses Program::analysis.symbols + functions (flat table).",
PaneKind::SymbolTree => "",
- PaneKind::TextEditor => "Backend pending — script editor lands in Phase F (M6).",
+ PaneKind::TextEditor => "Backend pending — script editor lands in .",
PaneKind::Il2cppMetadata => "",
PaneKind::Il2cppMethods => "",
PaneKind::Il2cppIcalls => "",
diff --git a/crates/ghidrust-gui/src/register_manager.rs b/crates/ghidrust-gui/src/register_manager.rs
index a7cbb2d..85f375a 100644
--- a/crates/ghidrust-gui/src/register_manager.rs
+++ b/crates/ghidrust-gui/src/register_manager.rs
@@ -1,4 +1,4 @@
-//! Ghidrust GUI · Phase E (M5) — Register Manager pane.
+//! Ghidrust GUI · 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
@@ -7,11 +7,11 @@
//! `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.
+//! the SLEIGH register lattice lands in the backend. 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
+//! Extracted per internal modularization notes — new UI panes land here
//! instead of piling into `main.rs`.
use eframe::egui::{self, Color32, Ui};
diff --git a/crates/ghidrust-gui/src/scripts.rs b/crates/ghidrust-gui/src/scripts.rs
index c12abbf..811e828 100644
--- a/crates/ghidrust-gui/src/scripts.rs
+++ b/crates/ghidrust-gui/src/scripts.rs
@@ -1,4 +1,4 @@
-//! Ghidrust GUI · Phase F (M6) — Script Manager, Text Editor, and
+//! Ghidrust GUI · Script Manager, Text Editor, and
//! MCP REPL / interpreter panes.
//!
//! Ghidra's `GhidraScriptMgrPlugin` (Script Manager),
@@ -15,7 +15,7 @@
//! 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
+//! Extracted per internal modularization notes — new UI panes land here
//! instead of piling into `main.rs`.
use eframe::egui::{self, Color32, Ui};
diff --git a/crates/ghidrust-il2cpp/src/metadata.rs b/crates/ghidrust-il2cpp/src/metadata.rs
index 573585c..be90a1f 100644
--- a/crates/ghidrust-il2cpp/src/metadata.rs
+++ b/crates/ghidrust-il2cpp/src/metadata.rs
@@ -33,7 +33,7 @@ impl MetadataDialect {
}),
v => Err(Error::UnsupportedVersion {
version: v,
- hint: "supported P0 versions: 27, 29, 31".into(),
+ hint: "supported versions: 27, 29, 31".into(),
}),
}
}
@@ -260,7 +260,7 @@ fn parse_header(data: &[u8], version: i32, dialect: MetadataDialect) -> Result<M
let (_vt_off, _vt_sz) = read_u32_pair(data, &mut off)?;
let (_io_off, _io_sz) = read_u32_pair(data, &mut off)?;
let (type_definitions_offset, type_definitions_size) = read_u32_pair(data, &mut off)?;
- // rgctx only <= 24.1 — skipped for P0 dialects
+ // rgctx only <= 24.1 — skipped for supported dialects
let (images_offset, images_size) = read_u32_pair(data, &mut off)?;
let (assemblies_offset, assemblies_size) = read_u32_pair(data, &mut off)?;
// metadataUsage only < 27 — skipped
diff --git a/crates/ghidrust-ir/src/lib.rs b/crates/ghidrust-ir/src/lib.rs
index 7ec011e..1e1c810 100644
--- a/crates/ghidrust-ir/src/lib.rs
+++ b/crates/ghidrust-ir/src/lib.rs
@@ -379,10 +379,9 @@ mod tests {
}
#[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
+ fn opcode_set_covers_division_trap_and_bitops() {
+ // Division family, Trap for int3/hlt, and Ghidra bit-manipulation
+ // ops (PIECE/SUBPIECE/PTRADD/CAST) that Stage-1 emit will need as
// lift coverage grows.
for op in [
OpCode::IntDiv,
diff --git a/crates/ghidrust-lift/src/lib.rs b/crates/ghidrust-lift/src/lib.rs
index 86fd11c..d964929 100644
--- a/crates/ghidrust-lift/src/lib.rs
+++ b/crates/ghidrust-lift/src/lib.rs
@@ -966,7 +966,7 @@ fn lift_with_ctx(ctx: &mut LiftCtx, insn: &Instruction) -> Vec<PcodeOp> {
// 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.
+ // still walk it. Ghidra's real MULTIEQUAL is a 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);
@@ -1638,7 +1638,7 @@ mod tests {
#[test]
fn lift_int3_becomes_trap_not_unimplemented() {
- // Baseline was `int3` → OpCode::Unimplemented; Phase A models it
+ // Baseline was `int3` → OpCode::Unimplemented; lift 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);
diff --git a/crates/ghidrust-structure/src/lib.rs b/crates/ghidrust-structure/src/lib.rs
index 6d210f8..47e71aa 100644
--- a/crates/ghidrust-structure/src/lib.rs
+++ b/crates/ghidrust-structure/src/lib.rs
@@ -383,13 +383,106 @@ pub fn structure_function_with_hints(
let mut visited: HashSet<u32> = HashSet::new();
let raw = ctx.build_region_from(ENTRY_BLOCK, None, &mut visited);
let flattened = flatten_short_circuit(raw, ssa);
+ // R3: `if (cond) goto return_block` → `if (cond) return` when the
+ // target leaf is a Return region (early-exit polish).
+ let polished = promote_early_returns(flattened, ssa);
StructureReport {
- region: flattened,
+ region: polished,
loops,
post_dominators: pdom,
}
}
+/// Rewrite `IfThen { h, Goto(t) }` / `IfThenElse` arms into `Return(t)` when
+/// block `t` is a return terminator. Reduces unstructured gotos on early-exit
+/// patterns common in real binaries.
+pub fn promote_early_returns(r: Region, ssa: &SsaFunction) -> Region {
+ match r {
+ Region::Seq(rs) => {
+ Region::Seq(rs.into_iter().map(|c| promote_early_returns(c, ssa)).collect())
+ }
+ Region::IfThen { header, then_branch } => Region::IfThen {
+ header,
+ then_branch: Box::new(promote_goto_to_return(
+ promote_early_returns(*then_branch, ssa),
+ ssa,
+ )),
+ },
+ Region::IfThenElse {
+ header,
+ then_branch,
+ else_branch,
+ } => Region::IfThenElse {
+ header,
+ then_branch: Box::new(promote_goto_to_return(
+ promote_early_returns(*then_branch, ssa),
+ ssa,
+ )),
+ else_branch: Box::new(promote_goto_to_return(
+ promote_early_returns(*else_branch, ssa),
+ ssa,
+ )),
+ },
+ Region::While { header, body } => Region::While {
+ header,
+ body: Box::new(promote_early_returns(*body, ssa)),
+ },
+ Region::DoWhile { header, body, latch } => Region::DoWhile {
+ header,
+ body: Box::new(promote_early_returns(*body, ssa)),
+ latch,
+ },
+ Region::Loop { header, body } => Region::Loop {
+ header,
+ body: Box::new(promote_early_returns(*body, ssa)),
+ },
+ Region::Switch {
+ header,
+ cases,
+ default,
+ } => Region::Switch {
+ header,
+ cases: cases
+ .into_iter()
+ .map(|c| SwitchCase {
+ selector: c.selector,
+ target: c.target,
+ body: Box::new(promote_early_returns(*c.body, ssa)),
+ })
+ .collect(),
+ default: default.map(|d| Box::new(promote_early_returns(*d, ssa))),
+ },
+ Region::ShortCircuit {
+ parts,
+ then_branch,
+ else_branch,
+ } => Region::ShortCircuit {
+ parts,
+ then_branch: Box::new(promote_early_returns(*then_branch, ssa)),
+ else_branch: else_branch.map(|e| Box::new(promote_early_returns(*e, ssa))),
+ },
+ other => promote_goto_to_return(other, ssa),
+ }
+}
+
+fn promote_goto_to_return(r: Region, ssa: &SsaFunction) -> Region {
+ match r {
+ Region::Goto(t) => {
+ if ssa
+ .block(t)
+ .and_then(|b| b.ops.last())
+ .map(|o| o.opcode == OpCode::Return)
+ .unwrap_or(false)
+ {
+ Region::Return(t)
+ } else {
+ Region::Goto(t)
+ }
+ }
+ other => other,
+ }
+}
+
/// Resolved switch metadata keyed by the SSA block whose terminator drives
/// the computed jump. Entries here shortcut [`StructCtx::build_region_from`]
/// straight to a [`Region::Switch`] with per-case bodies. `header` is
@@ -1339,7 +1432,7 @@ pub fn loop_count(report: &StructureReport) -> usize {
/// 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.
+/// yields the `goto_rate` metric.
pub fn goto_count(region: &Region) -> usize {
match region {
Region::Goto(_) => 1,
@@ -1404,7 +1497,7 @@ pub fn region_leaf_count(region: &Region) -> usize {
}
}
-/// `goto_rate = goto_count / max(1, region_leaf_count)`. The Phase D gate
+/// `goto_rate = goto_count / max(1, region_leaf_count)`. The goto_rate 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 {
diff --git a/crates/ghidrust-types/src/lib.rs b/crates/ghidrust-types/src/lib.rs
index 5d91201..808df42 100644
--- a/crates/ghidrust-types/src/lib.rs
+++ b/crates/ghidrust-types/src/lib.rs
@@ -80,6 +80,12 @@ pub enum RustType {
/// count of distinct constant-index touches we observed. `count == 0`
/// means unknown / open-ended.
ArrayPtr { elem_width: u32, count: u32 },
+ /// IEEE float/double (R4). Seeded from SSE/x87-shaped notes or explicit
+ /// float ops — never invented from integer arithmetic alone.
+ Float {
+ /// Width in bytes (4 = float, 8 = double).
+ width: u32,
+ },
/// Conflicting observations (top).
Any,
}
@@ -153,6 +159,17 @@ impl RustType {
| (IntN { width: 8 }, ArrayPtr { elem_width, count }) => {
ArrayPtr { elem_width, count }
}
+ (Float { width: a }, Float { width: b }) => Float {
+ width: a.max(b),
+ },
+ // Same-width int + float observation prefers float (SSE move of
+ // a 4/8-byte slot that also saw integer Copy still prints as float).
+ (Float { width: fw }, IntN { width: iw })
+ | (IntN { width: iw }, Float { width: fw })
+ if fw == iw =>
+ {
+ Float { width: fw }
+ }
_ => Any,
}
}
@@ -207,6 +224,11 @@ impl RustType {
format!("{base}*/*[{count}]*/")
}
}
+ RustType::Float { width } => match width {
+ 4 => "float".into(),
+ 8 => "double".into(),
+ w => format!("float{}_t", w * 8),
+ },
RustType::Any => "void*".into(),
}
}
@@ -216,7 +238,9 @@ impl RustType {
pub fn scalar_width(&self) -> u32 {
match self {
RustType::Bool => 1,
- RustType::IntN { width } | RustType::IntSigned { width } => *width,
+ RustType::IntN { width }
+ | RustType::IntSigned { width }
+ | RustType::Float { width } => *width,
RustType::Ptr { .. } | RustType::StructPtr { .. } | RustType::ArrayPtr { .. } => 8,
_ => 0,
}
@@ -565,6 +589,25 @@ fn seed_op(op: &SsaOp, map: &mut TypeMap, flags: &BTreeSet<u64>) {
}
_ => {}
}
+ // R4: SSE/x87 mnemonic notes → float/double (evidence-gated).
+ if let Some(note) = op.note.as_deref() {
+ let n = note.to_ascii_lowercase();
+ let is_ss = n.contains("movss")
+ || n.contains("addss")
+ || n.contains("mulss")
+ || n.contains("subss")
+ || n.contains("divss");
+ let is_sd = n.contains("movsd")
+ || n.contains("addsd")
+ || n.contains("mulsd")
+ || n.contains("subsd")
+ || n.contains("divsd");
+ if (is_ss || is_sd) && op.output.is_some() {
+ let out = op.output.unwrap();
+ let w = if is_sd { 8 } else { 4 };
+ map.set(out.space, out.offset, RustType::Float { width: w });
+ }
+ }
}
/// Recover stack locals by scanning `Stack`-space reads/writes across the
@@ -620,8 +663,9 @@ pub fn recover_locals(func: &SsaFunction, types: &TypeMap) -> LocalMap {
///
/// 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.
+/// [`RustType::ArrayPtr`] as appropriate. Conservative — a single field is
+/// allowed only when the base is already typed as [`RustType::Ptr`] (R4);
+/// otherwise two distinct offsets remain 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();
@@ -653,7 +697,11 @@ pub fn recover_structs(func: &SsaFunction, types: &mut TypeMap) -> BTreeMap<u32,
let mut structs: BTreeMap<u32, StructSeed> = BTreeMap::new();
let mut next_key: u32 = 1;
for (base, fields) in per_base {
- if fields.len() < 2 {
+ let base_is_ptr = matches!(
+ types.get(base.space, base.offset),
+ RustType::Ptr { .. } | RustType::StructPtr { .. }
+ );
+ if fields.len() < 2 && !(fields.len() == 1 && base_is_ptr) {
continue;
}
// Array vs struct heuristic: if every field width is equal and the
@@ -1039,6 +1087,12 @@ mod tests {
assert_eq!(RustType::Bottom.join(a.clone()), a);
}
+ #[test]
+ fn c_style_float_and_double() {
+ assert_eq!(RustType::Float { width: 4 }.c_style(), "float");
+ assert_eq!(RustType::Float { width: 8 }.c_style(), "double");
+ }
+
#[test]
fn c_style_emits_named_types() {
assert_eq!(RustType::int(4).c_style(), "uint32_t");
diff --git a/docs/GHIDRA_HEADTOHEAD.md b/docs/GHIDRA_HEADTOHEAD.md
index e5c8858..69de6f6 100644
--- a/docs/GHIDRA_HEADTOHEAD.md
+++ b/docs/GHIDRA_HEADTOHEAD.md
@@ -1,14 +1,13 @@
# Ghidrust ↔ Ghidra head-to-head oracle
-**Status:** Phase E · **shared-entry set** · **Stage-1 default** ·
+**Status:** **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 pcode-parity plan (Phase F / Stage-1 product default) —
-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.
+with Stage-1 as the product default and a fair Ghidra comparison methodology —
+shared-entry intersection, Stage-1-vs-`DecompInterface`, normalized-token
+similarity (replacing the earlier brace-count proxy and stage-mismatched comparison).
`ghidra-headtohead --ghidra <DIR>` auto-spawns `analyzeHeadless` with an
embedded `DecompileAndReport.java` post-script (see
@@ -19,7 +18,7 @@ a Stage-1 wall-time and a token-similarity score.
---
-## Design contract (Phase E, current)
+## Design contract
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
@@ -35,7 +34,10 @@ a Stage-1 wall-time and a token-similarity score.
(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.
+ missing output rather than fabricated. For human readability
+ (expression nesting, named calls, fewer `sub_`/`goto`), also use
+ [`docs/READABILITY_RUBRIC.md`](READABILITY_RUBRIC.md) alongside
+ Stage-1 JSON fields `folded_temps`, `token_count`, and `goto_rate`.
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
@@ -169,7 +171,7 @@ 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
+**Publishable table shape:** 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
diff --git a/docs/IL2CPP.md b/docs/IL2CPP.md
index 4589933..65d8d6d 100644
--- a/docs/IL2CPP.md
+++ b/docs/IL2CPP.md
@@ -63,9 +63,9 @@ Launch: `ghidrust mcp` (or `target/release/ghidrust.exe mcp` after build). Stdio
| Metadata version | Dialect | Status |
|------------------|---------|--------|
-| 27.x | `V27` | P0 supported |
-| 29.x | `V29` | P0 supported |
-| 31.x | `V31` | P0 supported |
+| 27.x | `V27` | supported |
+| 29.x | `V29` | supported |
+| 31.x | `V31` | supported |
| 24.x family | — | P1 (unsupported error with hint) |
| 39 / 106 | — | P1 (sectioned / variable-width) |
diff --git a/docs/READABILITY_RUBRIC.md b/docs/READABILITY_RUBRIC.md
new file mode 100644
index 0000000..5c5ee60
--- /dev/null
+++ b/docs/READABILITY_RUBRIC.md
@@ -0,0 +1,34 @@
+# Stage-1 readability rubric
+
+Human / semi-auto checklist for recovered C quality. Use alongside
+`token_similarity` from `ghidrust ghidra-headtohead` — Jaccard alone does not
+capture expression nesting or naming.
+
+## Scoring (per function)
+
+Score each item 0 / 1. Report mean across a fixed function set.
+
+| # | Check | Pass when |
+|---|--------|-----------|
+| 1 | **Expression nesting** | Fewer single-use `tN#v` / `reg#v` temps than SSA ops; compound `a + b * c` present when arithmetic chains exist |
+| 2 | **Named calls** | Import / known function calls print as `Name()` not bare `sub_<addr>()` when the program has that symbol |
+| 3 | **Typed locals** | Stack locals declared with non-`undefined` types when evidence exists |
+| 4 | **Control flow** | Natural `if` / `while` / `switch` used; `goto_rate` for the function `< 0.15` preferred |
+| 5 | **Early exit** | Early returns use `return` not `goto L_ret` when the target is a return block |
+| 6 | **OO (when RTTI)** | Methods show `this` / class pointer; virtual calls annotated when vtable known |
+| 7 | **Honesty** | No invented structs/enums; `/* unimplemented */` left for unlifted ops |
+
+## How to run
+
+1. Pick N functions from a fixture PE (or shared-entry head-to-head set).
+2. `ghidrust decompile <bin> --addr <va> --json` — inspect `pseudo_c`, `folded_temps`, `goto_rate`.
+3. Optional: `ghidrust ghidra-headtohead …` for `token_similarity`.
+4. Fill the table; track mean score over time. Do **not** claim Hex-Rays parity from this rubric alone.
+
+## Fixture themes (expand under `fixtures/`)
+
+- Expression-heavy arithmetic
+- Call-heavy (imports)
+- Loop / switch
+- Float/XMM (`movss` / `movsd` notes)
+- One medium public PE slice (no private install paths in docs)
diff --git a/skill/SKILL.md b/skill/SKILL.md
index 16df953..bf6fac9 100644
--- a/skill/SKILL.md
+++ b/skill/SKILL.md
@@ -79,28 +79,29 @@ Need full matrix bench?
Need decompiled C?
→ Staged capability (be honest about which stage you have):
- 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.
+ Stage-1 (**default**): expression-folded SSA +
+ structure + types → readable if/while/do-while/return with nested
+ arith (single-use temps inlined; JSON `folded_temps`), named
+ import/function calls when the program knows them, `this` on
+ `Class::method`, float seeds from SSE notes, early-exit `return`
+ polish, emit-time tokens (`token_count`) for GUI click-nav.
+ Still: typed params/locals, `p->field_<off>` / `p[i]`, switch,
+ `&&`/`||`, break/continue (lab goto_rate <0.15). Mid-body `addr`
+ resolves to containing function. CLI: `decompile PATH`; GUI:
+ Decompiler (Stage-1); MCP: `decompile` (default stage1). Library:
+ `ghidrust_decomp::decompile_stage1_at`. Rubric:
+ docs/READABILITY_RUBRIC.md. Falls back when lift <50% or
+ 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
+ Kept as regression baseline; Ghidra 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.
+ typed-C (in progress → Hex-Rays ceiling): expression fold + naming shipped;
+ unions/bitfields/EH still evidence-gated after Ghidra bar.
→ Do not invent Hex-Rays-quality C; emit only what the current stage produces.
+ See docs/READABILITY_RUBRIC.md (readability checklist).
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]`
@@ -197,7 +198,7 @@ ghidrust project analyze PROJ_DIR --file ID \
| `il2cpp_stubs` | `binary`, optional `filter`, `max` | Resolve stubs (filter: name or C-string at `name_string_va`) |
| `il2cpp_icalls` | `binary`, optional `filter` | Engine name‖fn icall tables → index / RVA |
| `unity_inventory` | `path` | Player dir + PE VERSIONINFO helpers |
-| `decompile` | `path`, optional `addr`, `count`, `stage`, **`follow_stub`** | Resolve meta + Stage-1; `runtime_unresolved` when slot empty |
+| `decompile` | `path`, optional `addr`, `count`, `stage`, **`follow_stub`** | Resolve meta + Stage-1 (expression fold, named calls); JSON: `folded_temps`, `token_count`, `goto_rate`; `runtime_unresolved` when IL2CPP slot empty |
| `list_gpu_strategies` | — | Strategy matrix |
| `gpu_decompile` | `path`, optional `addr`, `out` | VA resolve; metrics JSON; dump opaque |
| `rtti_gpu_bench` | `path` | CPU vs GPU RTTI |
@@ -265,7 +266,7 @@ Add `--json` for structured stdout.
| 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]` |
+| Ghidra head-to-head (shared-entry, Stage-1) | `ghidrust ghidra-headtohead <path> [--ghidra DIR] [--captured JSON] [--out F]` |
| **GPU decompile** | `ghidrust gpu-decompile <path> [--addr HEX] [--out F] [--metrics F]` |
| RE bench | `ghidrust re-bench <path>` |
| Analyzer CPU/GPU matrix bench | `ghidrust analyzer-bench <path> [--large] [--out F]` |
@@ -411,11 +412,11 @@ the exact evidence (blocks / insns / ir_ops / lift ratio / GPU backend).
| Method | CLI | What you get | Output shape |
|---|---|---|---|
-| **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-1** (**default**) | `ghidrust decompile PATH [--addr HEX] [--count N]` | Full SSA → structure → types → **expression-folded** typed pseudo-C: nested arith, named import/function calls when known, `this` on `Class::method`, float seeds from SSE notes, single-field structs when base is already `Ptr`, early-exit `return` polish, emit-time tokens for GUI nav. Still: `param_N`/`local_<off>`, switch/&&/&#124;&#124;/break/continue (lab goto_rate <0.15). Readability rubric: [`docs/READABILITY_RUBRIC.md`](../docs/READABILITY_RUBRIC.md). | stdout `pseudo_c`; `--json` ⇒ stage1 includes `folded_temps`, `token_count`, `lift_ratio`, `goto_rate`, … |
| **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`. |
+| **ghidra-headtohead** | `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`. |