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.

Multi-arch decode engine — Ghidrust-decode with Engine API and 23 ISA backends under arch/ (x86, aarch64, arm/thumb, mips, ppc, riscv, wasm, bpf, …); replaces the old single-file x86_64.rs path. Decode CLI/MCP surface (tool_surface 5) — Shared DecodeOpts, modular disasm / decode-support / decode-query, MCP disassemble / decode_support / decode_query with arch/mode/syntax/detail/skipdata controls. Windows agent disasm ergonomics — --brief / --pretty, text-capable --out, --flag normalizer; MCP listing_text so agents don’t need python -c pretty-print pipelines. Function-bounds honesty — bounds_suspect / heal hints when stored ends look truncated; function create re-grows short existing ends; synthetic truncated-bounds fixture + tests. Callsite ABI hints — Evidence-gated Win64 callsite_hints (rcx/rdx/r8/r9 + RIP loads) on disasm/decompile JSON. Loader-aware arch/mode — Core machine.rs maps PE/ELF machine types into decode arch/mode for listings. GUI listing package — Modular listing/ (model, toolbar/decode opts, detail pane, disasm service, search/persist) instead of a monolithic listing path. Live process bridge hardening — Expanded Windows process attach/launch/resolve/read surface wired through CLI friction helpers. Agent skill / SOP rewrite — Linear-first when bounds suspect, PowerShell-safe pipelines, decode decision tree, heal-then-flow/decompile recipe. Surface eval coverage — New eval_cli_mcp_surface matrix plus updated CLI/MCP/disasm tests for the decode + honesty paths.

oofz4027e0ea9703
diff --git a/.gitignore b/.gitignore
index 35e1868..2d98875 100644
--- a/.gitignore
+++ b/.gitignore
@@ -12,6 +12,7 @@
!.cursor/rules/**
terminals/
mcps/
+okf/*
# OS
.DS_Store
@@ -24,6 +25,10 @@ re_metrics.log
headtohead_*.json
headtohead_*.txt
-# Local development notes (parity tracking, roadmaps, private benches)
+# Local development notes (checklists, roadmaps, private benches)
# Not published — research/metrics stay in docs/
dev/
+
+# OKF (okf/): code-only sources (crates/**/*.rs, Cargo.toml). Never invent
+# concepts from the blocked paths above, nor from docs/skill/fixtures/README.
+# Rule: .cursor/rules/okf-code-only.mdc — regen: python scripts/gen_okf.py
diff --git a/DEPENDENCIES.md b/DEPENDENCIES.md
deleted file mode 100644
index 8fa5d5d..0000000
--- a/DEPENDENCIES.md
+++ /dev/null
@@ -1,53 +0,0 @@
-# Dependency policy
-
-**Prefer hand-rolled, task-specific Rust.** Analysis core (loaders, x86-64 decode, RTTI, all Auto Analysis implementations under `src/analyzers/*`, program model, MCP protocol framing, and the planned IR → SSA → structure → typed-C pipeline) is written in-tree with no third-party analysis crates at **runtime**.
-
-## Hand-rolled targets (analysis IP)
-
-These stay in-tree. Do **not** take iced-x86, Zydis, Capstone, goblin, rsleigh, hexray, fission, or analyssa as runtime dependencies for decode / lift / SSA / decomp:
-
-| Area | Role | Status |
-|------|------|--------|
-| Loaders, program model, analyzers | `ghidrust-core` | Shipped |
-| **`ghidrust-decode`** | Hand-rolled x86-64 length-disasm + mnemonic/operand strings | Shipped |
-| **`ghidrust-ir`** | Architecture-neutral pcode-like ops (`Copy`/`Int*`/`Bool*`/`Branch`/`CBranch`/`Call*`/`Return`/…), varnodes, address spaces, tagged basic blocks | Shipped |
-| **`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`/`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.
-
-## Allowed third-party
-
-| Crate | Why |
-|-------|-----|
-| **egui / eframe** (and their transitive deps) | Interactive CodeBrowser shell with Material 3–inspired Dark/Light chrome (not a full Material library). |
-| **egui_dock** `0.16` (feature `serde`) | IDE-style tab docking for the CodeBrowser center panes. Pin matches **egui 0.31 ↔ egui_dock 0.16** (newer egui_dock tracks newer egui; do not bump egui solely for docking). |
-| **serde / serde_json** | Minimal JSON for CLI `--json` and MCP JSON-RPC framing (stdio agent protocol). |
-| **rayon** | Work-stealing CPU pool for bulk RE scans and parallel analyze/decomp. |
-| **bincode** | Fast binary analysis persistence (`analysis.bin`) — multi-100MB pretty JSON is not viable for UI reopen. |
-| **ghidrust-decomp / ghidrust-lift / ghidrust-ir / ghidrust-ssa** (workspace crates) | Hand-rolled decompile pipeline (Stage-0 blocks/CFG → pseudo-C, Stage-0.5 IR-informed emit, SSA-C in progress); not third-party decompiler products. |
-| **wgpu / pollster / bytemuck** (optional, feature `gpu`) | Experimental GPU compute bulk printable-mark kernel and Stage-0 VRAM multipass; auto CPU fallback without adapter. |
-
-## Dev-only differential oracles (CI / tests — not runtime)
-
-| Tool / crate | Allowed use | Not allowed |
-|--------------|-------------|-------------|
-| **iced-x86** (or Zydis) | Length-disasm / decode **differential tests** as an external oracle in CI or `dev-dependencies` | Linking into production decode, lift, GUI, CLI, or MCP runtime paths |
-
-Same rule for any other mature decoder used only to cross-check edge cases against the hand-rolled decoder.
-
-## Not used (on purpose)
-
-- `goblin`, `object`, `pelite`, `scroll` — PE/ELF parsed by hand in `ghidrust-core`.
-- `iced-x86`, `zydis`, `capstone` bindings — **not** runtime decode; see CI oracle exception above.
-- Il2CppDumper / Cpp2IL / Il2CppInspector as runtime deps — formats reimplemented in `ghidrust-il2cpp` (reference-only).
-- Full `rmcp` / heavy MCP SDKs — thin hand-rolled tools/list + tools/call over stdio.
-
-## Supply chain
-
-- UI stack is the only large external surface; pin versions in workspace/crate `Cargo.toml`.
-- No `unsafe` required in analysis paths for the MVP fixture set.
-- Owning IR layout keeps the “faster than Ghidra JVM” thesis possible (cache-friendly SoA, no JNI/bridge tax) without ceding the analysis moat to a third-party lifter/SSA crate.
diff --git a/README.md b/README.md
index 2f0e2c3..485c29a 100644
--- a/README.md
+++ b/README.md
@@ -2,7 +2,7 @@
Hand-rolled **Rust** reverse-engineering toolkit inspired by [Ghidra](https://github.com/NationalSecurityAgency/ghidra).
-Ghidrust loads PE/ELF (and raw blobs), produces x86-64 listings, runs Auto Analysis, decompiles to pseudo-C, parses IL2CPP metadata / Unity install inventory, and saves durable projects — from a CLI, an MCP server for agents, or an egui CodeBrowser-style GUI.
+Ghidrust loads PE/ELF (and raw blobs), produces Capstone-class multi-arch listings (23 ISAs; x86-64 primary analyze/decompile pipeline), runs Auto Analysis, decompiles to pseudo-C, parses IL2CPP metadata / Unity install inventory, and saves durable projects — from a CLI, an MCP server for agents, or an egui CodeBrowser-style GUI.
It is **not** a Ghidra fork or wrapper. Analysis logic (loaders, decode, analyzers, decompile) is written in-tree so the core stays small, auditable, and freestanding.
@@ -14,9 +14,9 @@ It is **not** a Ghidra fork or wrapper. Analysis logic (loaders, decode, analyze
|------|---------------------|
| **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 |
-| **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 |
+| **Custom core** | PE/ELF, Capstone-class multi-arch decode (`ghidrust-decode`), x86-64 RTTI/analyzers, and the IR → SSA → structure → typed-C pipeline implemented in Rust — third-party RE libraries are avoided at runtime; 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, function create / bounded disasm / call graphs, IL2CPP touch-map + body proof, live process bridge (Windows), and egui panes for every surface |
+| **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 support, function create / bounded disasm / call graphs, IL2CPP touch-map + body proof, live process bridge (Windows), and egui panes for every surface. **2026-07-19:** Windows agent disasm pipeline + bounds honesty (`--brief`/`--pretty`, `bounds_suspect`, `listing_text`) — see [CHANGELOG.md](CHANGELOG.md) |
| **Practical projects** | Create a workspace, import binaries, run analyzers, persist results (`analysis.bin`), reopen later |
---
@@ -86,9 +86,12 @@ cargo test -p ghidrust-decomp
cargo run -p ghidrust-cli --release -- help
# or: ./target/release/ghidrust help
-# Load / disassemble fixtures
+# Load / disassemble fixtures (Capstone-class engine; bounded by function end by default)
./target/release/ghidrust load fixtures/tiny_x64.pe
./target/release/ghidrust disasm fixtures/tiny_x64.pe --count 16
+./target/release/ghidrust decode-support --json
+./target/release/ghidrust decode-query --query insn_name --arch x86 --id 1 --json
+./target/release/ghidrust disasm fixtures/tiny_x64.pe --addr 0x140001000 --count 32 --detail --syntax intel --json
# Lookups (no helper scripts required)
./target/release/ghidrust strings fixtures/analysis_lab.pe --encoding all --filter WideLab --json
@@ -181,7 +184,7 @@ First-class commands for the queries agents used to need ad-hoc scripts for. Sam
|---------|---------|-----------|
| `ghidrust load <path\|--project DIR --file-id ID>` | Load PE/ELF; JSON includes `resolved_path`, `sections`, informational `section_notes` | `--json`, `--out` |
| `ghidrust strings <path>` | Scan ASCII and/or UTF-16LE strings (PE/ELF or `--raw` blob) | `--encoding`, `--filter`, `--match substr\|token\|whole\|glob`, `--limit N`, `--out FILE`, `--raw`, `--json` |
-| `ghidrust xrefs <path>` | Cross-references (absolute + RIP-relative; string encoding parity); call edges | Exactly one of: `--to` / `--from` / `--string` / `--import` / `--calls`; `--encoding ascii\|utf16le\|all`; `--skip-stubs` / `--classify` |
+| `ghidrust xrefs <path>` | Cross-references (absolute + RIP-relative; string encoding modes); call edges | Exactly one of: `--to` / `--from` / `--string` / `--import` / `--calls`; `--encoding ascii\|utf16le\|all`; `--skip-stubs` / `--classify` |
| `ghidrust imports <path>` | PE import directory → DLL + symbol + IAT VA | `--dll NAME`, `--name NAME`, `--json` |
| `ghidrust function-at <path> --addr HEX` | Containing analyzed function for a body VA (runs Function Start Search if needed); JSON includes `seed_kind` | `--json` |
| `ghidrust function create <path> --addr HEX` | Create/heal a function at VA (pdata/export/FSS complements; may synthesize) | `--end HEX`, `--json` |
@@ -191,10 +194,12 @@ First-class commands for the queries agents used to need ad-hoc scripts for. Sam
| `ghidrust inventory <dir>` | Generic PE install inventory (exe/dll + VERSIONINFO; artifact if large) | `--max-depth`, `--hash`, `--json` |
| `ghidrust tree <path>` | Bounded file tree index (existence/size; no unpack) | `--max-depth`, `--ext`, `--name`, `--json` |
| `ghidrust artifact get\|query\|list` | Drain spilled analysis artifacts (`next_offset`) | `--offset`, `--limit`, `--json` |
-| `ghidrust process list\|attach\|detach\|modules\|read\|resolve\|regions` | Live Process Bridge (Windows; read-only MVP) | session_id / `--addr` / `--module` / `--rva` / `--max` |
+| `ghidrust process list\|attach\|launch\|resume\|detach\|modules\|read\|resolve\|regions` | Live Process Bridge (Windows; read-only MVP; launch = CREATE_SUSPENDED) | session_id / `--args` / `--cwd` / `--addr` / `--module` / `--rva` / `--max` |
| `ghidrust il2cpp meta\|map\|touch-map\|stubs\|icalls` | IL2CPP metadata + touch-map + method map (body proof / baseline) + stubs + icalls | See [docs/IL2CPP.md](docs/IL2CPP.md) |
| `ghidrust unity-inventory <dir>` | Unity player layout (reuses PE VERSIONINFO helpers) | `--json`, `--out FILE` |
-| `ghidrust disasm <path>` | Listing bounded by function end by default; `decode_gaps` when `--skip-bad`; JSON `stop_reason` | `--addr HEX`, `--count N`, `--skip-bad`, `--linear`/`--flow`, `--json` |
+| `ghidrust disasm <path>` | Capstone-class listing; bounded by function end by default; `decode_gaps` when `--skip-bad`; JSON `stop_reason` | `--addr HEX`, `--count N` (default 16), `--skip-bad`, `--linear`/`--flow`, `--arch`, `--mode`, `--syntax`, `--detail`/`--no-detail`, `--detail-real`, `--skipdata`, `--skipdata-mnemonic`, `--skipdata-size`, `--unsigned-imm`, `--only-offset-branch`, `--litbase`, `--mnem-override ID:MNEMONIC`, `--out`, `--json` |
+| `ghidrust decode-support` | Engine version, 23 supported arches, options, syntax values, compile features | `--json` |
+| `ghidrust decode-query` | Engine introspection (`insn_name`, `reg_name`, `group_name`, `insn_group`, `reg_read`, `reg_write`, `op_count`, `op_index`, `regs_access`) | `--query NAME`, `--arch`, `--mode`, `--id`, `--index`, `--bytes HEX`, `--addr HEX`, `--detail`, `--json` |
```bash
# Wide + ASCII string search (token match + limit; BOM-free --out)
@@ -314,6 +319,8 @@ ghidrust artifact query <id> --offset 0 --limit 64 --json
# Live process (Windows; read-only)
ghidrust process list --json
ghidrust process attach <pid>
+ghidrust process launch C:\path\to\app.exe --args "--flag" --cwd C:\path\to --json
+ghidrust process resume <session_id>
ghidrust process modules <session_id> --json
ghidrust process resolve <session_id> --module app.exe --rva 0x1234 --json
ghidrust process read <session_id> --addr 0x7ff… --size 64 --json
@@ -382,7 +389,9 @@ MyProject/
| Command | What it does |
|---------|----------------|
| `ghidrust load <path\|--project DIR --file-id ID> [--json]` | Load PE/ELF; JSON includes `resolved_path`, `sections`, informational `section_notes` |
-| `ghidrust disasm <path> [--addr HEX] [--count N] [--skip-bad] [--linear\|--flow] [--json]` | x86-64 listing bounded by function end by default; `--linear` escapes; JSON `stop_reason` |
+| `ghidrust disasm <path> [--addr HEX] [--count N] [--skip-bad] [--linear\|--flow] [--arch ARCH] [--mode MODE] [--syntax SYNTAX] [--detail] [--detail-real] [--skipdata] [--skipdata-mnemonic S] [--skipdata-size N] [--unsigned-imm] [--only-offset-branch] [--litbase HEX] [--mnem-override ID:MNEM]… [--json]` | Capstone-class listing; bounded by function end by default; `--linear` escapes; JSON `stop_reason` + `decode_gaps` |
+| `ghidrust decode-support [--json]` | Decode engine catalog (version, arches, options, syntax values) |
+| `ghidrust decode-query [--query NAME] [--arch ARCH] [--mode MODE] [--id N] [--index N] [--bytes HEX] [--addr HEX] [--detail] [--json]` | Engine introspection queries |
| `ghidrust bytes <path> --addr HEX [--count N] [--json]` | Raw VA hex dump |
| `ghidrust strings <path> [--raw] [--encoding …] [--filter SUB] [--match MODE] [--limit N] [--out FILE] [--json]` | String scan (blob-capable) |
| `ghidrust xrefs <path> (--to\|--from\|--string\|--import\|--calls) [--encoding ascii\|utf16le\|all] [--skip-stubs] [--classify] [--json]` | RIP-aware xrefs; `--calls` = callee edges; attribution fields when functions exist |
@@ -392,7 +401,7 @@ MyProject/
| `ghidrust inventory <dir> [--max-depth N] [--hash] [--json]` | Generic PE install inventory (exe/dll + VERSIONINFO) |
| `ghidrust tree <path> [--max-depth N] [--ext LIST] [--name GLOB] [--json]` | Bounded file tree index (existence/size; no unpack) |
| `ghidrust artifact get\|query\|list …` | Drain / list spilled analysis artifacts (`next_offset`) |
-| `ghidrust process list\|attach\|detach\|modules\|read\|resolve\|regions …` | Live Process Bridge (Windows; read-only MVP) |
+| `ghidrust process list\|attach\|launch\|resume\|detach\|modules\|read\|resolve\|regions …` | Live Process Bridge (Windows; read-only MVP; launch = CREATE_SUSPENDED) |
| `ghidrust il2cpp meta\|map\|touch-map\|stubs\|icalls …` | IL2CPP metadata / touch-map / RVA map (`body_class`, `--baseline` → `build_skew`, `--meta-sections`) / stubs / icalls ([docs/IL2CPP.md](docs/IL2CPP.md)) |
| `ghidrust unity-inventory <dir> [--out FILE] [--json]` | Unity player install inventory |
| `ghidrust rtti <path> [--filter\|--name\|--exact] [--match MODE] [--json]` | RTTI catalog (filter/exact; multi-vtable honest) |
@@ -500,7 +509,9 @@ On Linux/macOS:
|------|------|---------|
| `server_info` | — | Package `version`, monotonic `tool_surface`, features, live session_model |
| `load` | `path` **or** `project`+`file_id` | Load PE/ELF; `resolved_path`, `sections`, `section_notes` |
-| `disassemble` | `path`, optional `addr`, `count`, `linear` | Bounded by function end by default; `linear:true` escapes; JSON `stop_reason` + `decode_gaps` |
+| `decode_support` | — | Engine version, 23 arches, options, syntax values, compile features |
+| `decode_query` | `query`, optional `arch`, `mode`, `id`, `index`, `bytes`, `addr`, `detail` | Introspection: `insn_name`, `reg_name`, `group_name`, `insn_group`, `reg_read`, `reg_write`, `op_count`, `op_index`, `regs_access` |
+| `disassemble` | `path`, optional `addr`, `count`, `skip_bad`, `linear`, `flow`, `arch`, `mode`, `syntax`, `detail`, `detail_real`, `skipdata`, `skipdata_mnemonic`, `skipdata_size`, `unsigned_imm`, `only_offset_branch`, `litbase`, `mnem_overrides` | Bounded by function end by default; `linear:true` escapes; JSON `stop_reason` + `decode_gaps` |
| `rtti` | `path` | Full RTTI recover dump |
| `rtti_query` | `path`, optional `filter`, `exact`, `match` | Catalog query; multi-vtable; artifact if large |
| `artifact_get` / `artifact_query` / `artifact_list` | `id` / optional `offset`/`limit` / optional `max` | Drain or list spilled results (`next_offset`) |
@@ -528,13 +539,13 @@ On Linux/macOS:
| `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 |
-| `process_list` / `process_attach` / `process_detach` / `process_modules` / `process_read` / `process_resolve` / `process_regions` | session / pid / module / rva / max | Live Process Bridge (Windows; no write in MVP) |
+| `process_list` / `process_attach` / `process_launch` / `process_resume` / `process_detach` / `process_modules` / `process_read` / `process_resolve` / `process_regions` | session / pid / image / module / rva / max | Live Process Bridge (Windows; no write in MVP) |
#### Live process (Windows)
-Attach read-only (`PROCESS_VM_READ`): `process list` → `attach <pid>` → `modules` → `resolve --module NAME --rva HEX` (`static_to_live`) → `read --addr LIVE --size N` → optional `regions` / `detach`. Multi-step attach **must** use the long-lived MCP (or GUI) process — CLI `ghidrust process` cannot reuse `session_id` across separate spawns. Short reads and access denied are explicit errors. Bytes ≠ recovered types — do not invent structs from live reads. GUI: Debugger → Targets / Modules / Memory Bytes / Regions / Static Mappings.
+Attach read-only (`PROCESS_VM_READ`): `process list` → `attach <pid>` → `modules` → `resolve --module NAME --rva HEX` (`static_to_live`) → `read --addr LIVE --size N` → optional `regions` / `detach`. **Launch** creates a process with `CREATE_SUSPENDED`, opens a live session, then `process resume` lets it run — not a Ghidra/CE debug break-at-entry. Multi-step work **must** use the long-lived MCP (or GUI) process — CLI `ghidrust process` cannot reuse `session_id` across separate spawns. Short reads and access denied are explicit errors. Bytes ≠ recovered types — do not invent structs from live reads. GUI: one **Debugger** window; Attach/Launch auto-populate modules, regions, and Memory Bytes.
-Versioning: `ghidrust --version`, MCP `initialize`/`server_info`, and egui Help → About / window title all report the same workspace package version. Agents also check `tool_surface`: **minimum `3`** (touch-map / body_class / function_create); **prefer `>= 4`** for bounded disasm / `get_calls_from`; **current is `4`**.
+Versioning: `ghidrust --version`, MCP `initialize`/`server_info`, and egui Help → About / window title all report the same workspace package version. Agents also check `tool_surface`: **minimum `3`** (touch-map / body_class / function_create); **prefer `>= 4`** for bounded disasm / `get_calls_from`; **require `>= 5`** for `decode_support`, `decode_query`, and extended `disassemble` decode flags; **current is `5`**. `server_info.decode` mirrors `decode-support` (version, arches, options, syntax_values).
#### Analysis artifacts
@@ -550,7 +561,7 @@ Large MCP/CLI dumps spill to `%TEMP%/ghidrust-artifacts/`. Tool envelopes includ
| Artifact spill | **Analysis Artifacts** |
| GPU decompile | Analysis → **GPU Decompile…** |
| Encoding / xrefs / RTTI / notes | Defined Strings, Symbol References, Symbol Tree Classes, Memory Map |
-| Live process | Debugger Targets / Modules / Memory Bytes / Regions |
+| Live process | **Debugger** (tabbed): Targets / Modules / Memory Bytes / Regions |
IL2CPP version matrix and Unity inventory schema: [docs/IL2CPP.md](docs/IL2CPP.md).
@@ -564,7 +575,9 @@ Example agent-facing call shapes (conceptual):
{ "name": "get_import_xrefs", "arguments": { "path": "…/app.exe", "name": "ShellExecuteW" } }
{ "name": "function_at", "arguments": { "path": "…/app.exe", "addr": "0x14000d8ad" } }
{ "name": "function_create", "arguments": { "path": "…/app.exe", "addr": "0x14000d8ad" } }
-{ "name": "disassemble", "arguments": { "path": "…/app.exe", "addr": "0x14000d890", "count": 40 } }
+{ "name": "decode_support", "arguments": {} }
+{ "name": "decode_query", "arguments": { "query": "insn_name", "arch": "x86", "id": 1 } }
+{ "name": "disassemble", "arguments": { "path": "…/app.exe", "addr": "0x14000d890", "count": 40, "detail": true, "syntax": "intel" } }
{ "name": "get_calls_from", "arguments": { "path": "…/app.exe", "addr": "0x14000d8ad" } }
{ "name": "unity_inventory", "arguments": { "path": "…/GameDir" } }
{ "name": "il2cpp_touch_map", "arguments": { "meta": "…/global-metadata.dat", "filter": "Camera" } }
@@ -579,6 +592,8 @@ Example agent-facing call shapes (conceptual):
{ "name": "artifact_query", "arguments": { "id": "<artifact_id>", "offset": 0, "limit": 64 } }
{ "name": "process_list", "arguments": {} }
{ "name": "process_attach", "arguments": { "pid": 1234 } }
+{ "name": "process_launch", "arguments": { "image": "C:/path/to/app.exe", "args": "--flag", "cwd": "C:/path/to" } }
+{ "name": "process_resume", "arguments": { "session_id": "…" } }
{ "name": "process_resolve", "arguments": { "session_id": "…", "module": "app.exe", "rva": "0x1234" } }
```
@@ -612,9 +627,9 @@ You should not need to type JSON by hand day-to-day — the IDE/agent does that
│ │ │ │
┌──────────┐ ┌─────────────┐ ┌────────────┐ ┌──────────────┐
│ decode │ │ lift │ │ ir │ │ ssa │ hand-rolled
- │ x86-64 │→│ x86-64→IR │→│ pcode-like │→│ cfg/dom/DF/ │ decompile
- │ length + │ │ + flag model│ │ ops+varnode│ │ phi placement│ pipeline
- │ mnemonics│ │ │ │ │ │ │
+ │ Capstone-│→│ x86-64→IR │→│ pcode-like │→│ cfg/dom/DF/ │ decompile
+ │ class 23 │ │ + flag model│ │ ops+varnode│ │ phi placement│ pipeline
+ │ ISAs │ │ │ │ │ │ │
└──────────┘ └─────────────┘ └────────────┘ └──────────────┘
│
▼
@@ -628,7 +643,7 @@ You should not need to type JSON by hand day-to-day — the IDE/agent does that
| Crate | Role |
|-------|------|
| `ghidrust-core` | PE/ELF/blob, x86-64, analyzers, imports/IAT, xrefs, projects, bulk scan |
-| `ghidrust-decode` | Hand-rolled x86-64 length-disasm + mnemonic/operand strings |
+| `ghidrust-decode` | Hand-rolled Capstone-class multi-arch `Engine` (23 ISAs); no Capstone/iced/zydis at runtime |
| `ghidrust-ir` | Architecture-neutral pcode-like IR (varnodes, ops, tagged blocks, address spaces) |
| `ghidrust-lift` | x86-64 → IR semantics with flag model + `LiftCoverage` reporting |
| `ghidrust-ssa` | CFG-on-IR, Cooper–Harvey–Kennedy dominators, Cytron dominance frontiers, phi placement |
@@ -649,7 +664,6 @@ You should not need to type JSON by hand day-to-day — the IDE/agent does that
| [docs/GPU_ANALYZER_MATRIX.md](docs/GPU_ANALYZER_MATRIX.md) | Per-analyzer GPU strategy + bench CLI |
| [docs/PARALLEL_RE_RESEARCH.md](docs/PARALLEL_RE_RESEARCH.md) | CPU pool vs GPU bulk RE |
| [docs/IL2CPP.md](docs/IL2CPP.md) | IL2CPP metadata matrix + Unity player inventory |
-| [DEPENDENCIES.md](DEPENDENCIES.md) | Dependency policy |
| [skill/README.md](skill/README.md) | Agent skill install |
---
diff --git a/crates/ghidrust-agent/src/system_prompt.rs b/crates/ghidrust-agent/src/system_prompt.rs
index b2e7615..beaf4c5 100644
--- a/crates/ghidrust-agent/src/system_prompt.rs
+++ b/crates/ghidrust-agent/src/system_prompt.rs
@@ -139,8 +139,8 @@ impl<'a> SystemPromptBuilder<'a> {
out.push_str("- Never invent analysis. If a binary hasn't been loaded, say so — do not fabricate addresses, symbols, or decompile output.\n");
out.push_str("- Always acquire addresses through a tool call (`load`, `analyze`, `function_at`, `get_xrefs_*`). Never guess a VA.\n");
out.push_str("- Use exact analyzer names from `list_analyzers` when calling `analyze` — no abbreviations.\n");
- out.push_str("- Emit decompile output at the stage the tool returned. Do not claim Hex-Rays / Ghidra parity.\n");
- out.push_str("- Do not conflate Ghidra MCP with Ghidrust MCP — this is Ghidrust.\n");
+ out.push_str("- Emit decompile output at the stage the tool returned. Do not claim parity with other decompilers.\n");
+ out.push_str("- Do not conflate other MCP servers with Ghidrust MCP — this is Ghidrust.\n");
if self.read_only_note {
out.push_str("- Session mode is currently **read-only**. Destructive tools (rename_*, set_comment, apply_patch, project_*) will be rejected. Ask the user to switch to `full` mode if you need them, and always show the intended change first.\n");
diff --git a/crates/ghidrust-cli/src/decode_opts.rs b/crates/ghidrust-cli/src/decode_opts.rs
new file mode 100644
index 0000000..002173f
--- /dev/null
+++ b/crates/ghidrust-cli/src/decode_opts.rs
@@ -0,0 +1,387 @@
+//! Shared decode / disasm flags for CLI args and MCP JSON.
+
+use ghidrust_core::{Arch, DisasmEngineOpts, Mode, Syntax};
+use serde_json::Value;
+use std::path::PathBuf;
+
+#[derive(Debug, Clone, Default)]
+pub struct DecodeOpts {
+ pub arch: Option<Arch>,
+ pub mode: Option<Mode>,
+ pub syntax: Option<Syntax>,
+ pub detail: Option<bool>,
+ pub detail_real: Option<bool>,
+ pub skipdata: Option<bool>,
+ pub skipdata_mnemonic: Option<String>,
+ pub skipdata_size: Option<usize>,
+ pub unsigned_imm: Option<bool>,
+ pub only_offset_branch: Option<bool>,
+ pub litbase: Option<u32>,
+ pub mnem_overrides: Vec<(u32, String)>,
+ pub linear: bool,
+ pub flow: bool,
+ pub brief: bool,
+ pub pretty: bool,
+ pub addr: Option<u64>,
+ pub count: usize,
+ pub skip_bad: bool,
+ pub out_path: Option<PathBuf>,
+}
+
+impl DecodeOpts {
+ pub fn default_count() -> usize {
+ 16
+ }
+
+ pub fn from_cli_args(args: &[String]) -> Result<(PathBuf, Self), String> {
+ let args = normalize_cli_flags(args);
+ let mut path: Option<PathBuf> = None;
+ let mut opts = Self {
+ count: Self::default_count(),
+ skip_bad: false,
+ ..Default::default()
+ };
+ let mut i = 0;
+ while i < args.len() {
+ match args[i].as_str() {
+ "-arch" if i + 1 < args.len() => {
+ opts.arch = Some(parse_arch(&args[i + 1])?);
+ i += 2;
+ }
+ "-mode" if i + 1 < args.len() => {
+ opts.mode = Some(parse_mode(&args[i + 1])?);
+ i += 2;
+ }
+ "-syntax" if i + 1 < args.len() => {
+ opts.syntax = Some(parse_syntax(&args[i + 1])?);
+ i += 2;
+ }
+ "-detail" => {
+ opts.detail = Some(true);
+ i += 1;
+ }
+ "-no-detail" => {
+ opts.detail = Some(false);
+ i += 1;
+ }
+ "-detail-real" => {
+ opts.detail_real = Some(true);
+ i += 1;
+ }
+ "-skipdata" => {
+ opts.skipdata = Some(true);
+ i += 1;
+ }
+ "-skipdata-mnemonic" if i + 1 < args.len() => {
+ opts.skipdata_mnemonic = Some(args[i + 1].clone());
+ i += 2;
+ }
+ "-skipdata-size" if i + 1 < args.len() => {
+ opts.skipdata_size = Some(
+ args[i + 1]
+ .parse()
+ .map_err(|e| format!("invalid skipdata-size: {e}"))?,
+ );
+ i += 2;
+ }
+ "-unsigned-imm" => {
+ opts.unsigned_imm = Some(true);
+ i += 1;
+ }
+ "-only-offset-branch" => {
+ opts.only_offset_branch = Some(true);
+ i += 1;
+ }
+ "-litbase" if i + 1 < args.len() => {
+ opts.litbase = Some(parse_u32(&args[i + 1])?);
+ i += 2;
+ }
+ "-mnem-override" if i + 1 < args.len() => {
+ opts.mnem_overrides.push(parse_mnem_override(&args[i + 1])?);
+ i += 2;
+ }
+ "-addr" if i + 1 < args.len() => {
+ opts.addr = Some(parse_u64(&args[i + 1])?);
+ i += 2;
+ }
+ "-count" if i + 1 < args.len() => {
+ opts.count = args[i + 1].parse().unwrap_or(Self::default_count());
+ i += 2;
+ }
+ "-skip-bad" => {
+ opts.skip_bad = true;
+ i += 1;
+ }
+ "-linear" => {
+ opts.linear = true;
+ i += 1;
+ }
+ "-flow" => {
+ opts.flow = true;
+ i += 1;
+ }
+ "-brief" => {
+ opts.brief = true;
+ i += 1;
+ }
+ "-pretty" => {
+ opts.pretty = true;
+ i += 1;
+ }
+ "-out" if i + 1 < args.len() => {
+ opts.out_path = Some(PathBuf::from(&args[i + 1]));
+ i += 2;
+ }
+ other if !other.starts_with('-') && path.is_none() => {
+ path = Some(PathBuf::from(other));
+ i += 1;
+ }
+ _ => i += 1,
+ }
+ }
+ let path = path.ok_or_else(|| "missing path".to_string())?;
+ Ok((path, opts))
+ }
+
+ pub fn from_json(args: &Value) -> Result<Self, String> {
+ let mut opts = Self {
+ count: args
+ .get("count")
+ .and_then(|c| c.as_u64())
+ .unwrap_or(Self::default_count() as u64) as usize,
+ skip_bad: args
+ .get("skip_bad")
+ .and_then(|v| v.as_bool())
+ .unwrap_or(false),
+ ..Default::default()
+ };
+ if let Some(a) = args.get("arch").and_then(|v| v.as_str()) {
+ opts.arch = Some(parse_arch(a)?);
+ }
+ if let Some(m) = args.get("mode") {
+ opts.mode = Some(parse_mode_value(m)?);
+ }
+ if let Some(s) = args.get("syntax").and_then(|v| v.as_str()) {
+ opts.syntax = Some(parse_syntax(s)?);
+ }
+ if let Some(v) = args.get("detail").and_then(|v| v.as_bool()) {
+ opts.detail = Some(v);
+ }
+ if let Some(v) = args.get("detail_real").and_then(|v| v.as_bool()) {
+ opts.detail_real = Some(v);
+ }
+ if let Some(v) = args.get("skipdata").and_then(|v| v.as_bool()) {
+ opts.skipdata = Some(v);
+ }
+ if let Some(v) = args.get("skipdata_mnemonic").and_then(|v| v.as_str()) {
+ opts.skipdata_mnemonic = Some(v.to_string());
+ }
+ if let Some(v) = args.get("skipdata_size").and_then(|v| v.as_u64()) {
+ opts.skipdata_size = Some(v as usize);
+ }
+ if let Some(v) = args.get("unsigned_imm").and_then(|v| v.as_bool()) {
+ opts.unsigned_imm = Some(v);
+ }
+ if let Some(v) = args.get("only_offset_branch").and_then(|v| v.as_bool()) {
+ opts.only_offset_branch = Some(v);
+ }
+ if let Some(v) = args.get("litbase") {
+ opts.litbase = Some(parse_u32_value(v)?);
+ }
+ if let Some(arr) = args.get("mnem_overrides").and_then(|v| v.as_array()) {
+ for item in arr {
+ if let Some(pair) = item.as_str() {
+ opts.mnem_overrides.push(parse_mnem_override(pair)?);
+ } else if let Some(obj) = item.as_object() {
+ let id = obj
+ .get("id")
+ .ok_or_else(|| "mnem_overrides entry missing id".to_string())
+ .and_then(parse_u32_value)?;
+ let mnemonic = obj
+ .get("mnemonic")
+ .and_then(|v| v.as_str())
+ .ok_or_else(|| "mnem_overrides entry missing mnemonic".to_string())?
+ .to_string();
+ opts.mnem_overrides.push((id, mnemonic));
+ }
+ }
+ }
+ opts.linear = args.get("linear").and_then(|v| v.as_bool()).unwrap_or(false);
+ opts.flow = args.get("flow").and_then(|v| v.as_bool()).unwrap_or(false);
+ if let Some(a) = args.get("addr").and_then(|v| v.as_str()) {
+ opts.addr = Some(parse_u64(a)?);
+ }
+ Ok(opts)
+ }
+
+ pub fn to_engine_opts(&self) -> DisasmEngineOpts {
+ DisasmEngineOpts {
+ arch: self.arch,
+ mode: self.mode,
+ syntax: self.syntax,
+ detail: self.detail,
+ detail_real: self.detail_real,
+ skipdata: self.skipdata,
+ skipdata_mnemonic: self.skipdata_mnemonic.clone(),
+ skipdata_size: self.skipdata_size,
+ unsigned_imm: self.unsigned_imm,
+ only_offset_branch: self.only_offset_branch,
+ litbase: self.litbase,
+ mnem_overrides: if self.mnem_overrides.is_empty() {
+ None
+ } else {
+ Some(self.mnem_overrides.clone())
+ },
+ }
+ }
+
+ pub fn raw_blob_mode(&self) -> bool {
+ self.arch.is_some()
+ }
+}
+
+/// Normalize GNU-style `--flag` to the CLI's `-flag` form (values unchanged).
+pub fn normalize_cli_flags(args: &[String]) -> Vec<String> {
+ args.iter()
+ .map(|a| {
+ if a.starts_with("--") && a.len() > 2 {
+ format!("-{}", &a[2..])
+ } else {
+ a.clone()
+ }
+ })
+ .collect()
+}
+
+pub fn parse_u64(s: &str) -> Result<u64, String> {
+ let t = s.trim().trim_start_matches("0x").trim_start_matches("0X");
+ u64::from_str_radix(t, 16)
+ .or_else(|_| s.parse::<u64>())
+ .map_err(|e| e.to_string())
+}
+
+pub fn parse_u32(s: &str) -> Result<u32, String> {
+ let t = s.trim().trim_start_matches("0x").trim_start_matches("0X");
+ u32::from_str_radix(t, 16)
+ .or_else(|_| s.parse::<u32>())
+ .map_err(|e| e.to_string())
+}
+
+fn parse_u32_value(v: &Value) -> Result<u32, String> {
+ if let Some(n) = v.as_u64() {
+ return Ok(n as u32);
+ }
+ if let Some(s) = v.as_str() {
+ return parse_u32(s);
+ }
+ Err("expected u32".into())
+}
+
+pub fn parse_arch(s: &str) -> Result<Arch, String> {
+ match s.trim().to_ascii_lowercase().as_str() {
+ "arm" => Ok(Arch::Arm),
+ "arm64" | "aarch64" => Ok(Arch::Arm64),
+ "mips" => Ok(Arch::Mips),
+ "x86" | "x86_64" | "x64" | "amd64" => Ok(Arch::X86),
+ "ppc" | "powerpc" => Ok(Arch::Ppc),
+ "sparc" => Ok(Arch::Sparc),
+ "sysz" | "systemz" | "s390" | "s390x" => Ok(Arch::Sysz),
+ "xcore" => Ok(Arch::Xcore),
+ "m68k" | "68k" => Ok(Arch::M68k),
+ "tms320c64x" | "tms320" | "c64x" => Ok(Arch::Tms320c64x),
+ "m680x" | "6800" | "6809" => Ok(Arch::M680x),
+ "evm" => Ok(Arch::Evm),
+ "mos65xx" | "6502" | "65c02" => Ok(Arch::Mos65xx),
+ "wasm" | "webassembly" => Ok(Arch::Wasm),
+ "bpf" | "ebpf" => Ok(Arch::Bpf),
+ "riscv" | "riscv64" | "riscv32" => Ok(Arch::Riscv),
+ "sh" | "superh" => Ok(Arch::Sh),
+ "tricore" => Ok(Arch::Tricore),
+ "alpha" => Ok(Arch::Alpha),
+ "hppa" | "parisc" | "pa-risc" => Ok(Arch::Hppa),
+ "loongarch" | "loongarch64" => Ok(Arch::Loongarch),
+ "xtensa" => Ok(Arch::Xtensa),
+ "arc" => Ok(Arch::Arc),
+ other => Err(format!("unknown arch: {other}")),
+ }
+}
+
+pub fn parse_mode(s: &str) -> Result<Mode, String> {
+ parse_mode_value(&Value::String(s.to_string()))
+}
+
+pub fn parse_mode_value(v: &Value) -> Result<Mode, String> {
+ if let Some(n) = v.as_u64() {
+ return Ok(Mode(n as u32));
+ }
+ let s = v
+ .as_str()
+ .ok_or_else(|| "mode must be string or integer".to_string())?;
+ let t = s.trim().to_ascii_lowercase();
+ if let Ok(n) = parse_u32(&t) {
+ return Ok(Mode(n));
+ }
+ Ok(match t.as_str() {
+ "16" | "mode16" => Mode::MODE_16,
+ "32" | "mode32" | "i386" => Mode::MODE_32,
+ "64" | "mode64" | "amd64" | "x64" => Mode::MODE_64,
+ "thumb" => Mode::THUMB,
+ "mclass" => Mode::MCLASS,
+ "v8" => Mode::V8,
+ "mips32" => Mode::MIPS32,
+ "mips64" => Mode::MIPS64,
+ "ppc32" => Mode::PPC32,
+ "ppc64" => Mode::PPC64,
+ "riscv32" => Mode::RISCV32,
+ "riscv64" => Mode::RISCV64,
+ "riscv_c" | "rvc" => Mode::RISCV_C,
+ "le" | "little" | "little_endian" => Mode::LITTLE_ENDIAN,
+ "be" | "big" | "big_endian" => Mode::BIG_ENDIAN,
+ "bpf_classic" => Mode::BPF_CLASSIC,
+ "bpf_extended" => Mode::BPF_EXTENDED,
+ "6502" => Mode::MOS65XX_6502,
+ "65c02" => Mode::MOS65XX_65C02,
+ other => return Err(format!("unknown mode: {other}")),
+ })
+}
+
+pub fn parse_syntax(s: &str) -> Result<Syntax, String> {
+ Ok(match s.trim().to_ascii_lowercase().as_str() {
+ "default" => Syntax::Default,
+ "intel" => Syntax::Intel,
+ "att" => Syntax::Att,
+ "noregname" | "no_reg_name" => Syntax::NoRegName,
+ "masm" => Syntax::Masm,
+ "motorola" => Syntax::Motorola,
+ "cs_reg_alias" | "reg_alias" => Syntax::CsRegAlias,
+ "percent" => Syntax::Percent,
+ "no_dollar" | "nodollar" => Syntax::NoDollar,
+ "no_alias_text" => Syntax::NoAliasText,
+ "no_alias_text_compressed" => Syntax::NoAliasTextCompressed,
+ other => return Err(format!("unknown syntax: {other}")),
+ })
+}
+
+fn parse_mnem_override(s: &str) -> Result<(u32, String), String> {
+ let (id_s, mnem) = s
+ .split_once(':')
+ .ok_or_else(|| "mnem-override must be ID:MNEMONIC".to_string())?;
+ Ok((parse_u32(id_s)?, mnem.to_string()))
+}
+
+pub fn parse_hex_bytes(s: &str) -> Result<Vec<u8>, String> {
+ let t = s.trim().trim_start_matches("0x");
+ if t.is_empty() {
+ return Ok(Vec::new());
+ }
+ if t.len() % 2 != 0 {
+ return Err("hex bytes must have even length".into());
+ }
+ (0..t.len())
+ .step_by(2)
+ .map(|i| {
+ u8::from_str_radix(&t[i..i + 2], 16)
+ .map_err(|e| format!("invalid hex at {i}: {e}"))
+ })
+ .collect()
+}
diff --git a/crates/ghidrust-cli/src/decode_query_cmd.rs b/crates/ghidrust-cli/src/decode_query_cmd.rs
new file mode 100644
index 0000000..60e67cf
--- /dev/null
+++ b/crates/ghidrust-cli/src/decode_query_cmd.rs
@@ -0,0 +1,250 @@
+//! `decode-query` CLI command — engine introspection.
+
+use crate::decode_opts::{parse_arch, parse_hex_bytes, parse_mode_value, parse_u64};
+use crate::decode_support_cmd::apply_detail_from_json;
+use ghidrust_core::{Arch, Engine, InsnId, Mode, Opt, RegId};
+use serde_json::{json, Value};
+use std::process::ExitCode;
+
+pub fn cmd_decode_query(args: &[String], json: bool) -> ExitCode {
+ let mut query: Option<String> = None;
+ let mut arch: Option<Arch> = None;
+ let mut mode: Option<Mode> = None;
+ let mut id: Option<u32> = None;
+ let mut index: Option<usize> = None;
+ let mut bytes: Option<Vec<u8>> = None;
+ let mut addr: u64 = 0;
+ let mut detail = false;
+ let mut json_args = json!({});
+
+ let mut i = 0;
+ while i < args.len() {
+ match args[i].as_str() {
+ "-query" if i + 1 < args.len() => {
+ query = Some(args[i + 1].clone());
+ i += 2;
+ }
+ "-arch" if i + 1 < args.len() => {
+ arch = Some(parse_arch(&args[i + 1]).unwrap_or_else(|e| {
+ eprintln!("{e}");
+ std::process::exit(2);
+ }));
+ i += 2;
+ }
+ "-mode" if i + 1 < args.len() => {
+ mode = Some(parse_mode_value(&Value::String(args[i + 1].clone())).unwrap_or_else(
+ |e| {
+ eprintln!("{e}");
+ std::process::exit(2);
+ },
+ ));
+ i += 2;
+ }
+ "-id" if i + 1 < args.len() => {
+ id = args[i + 1].parse().ok();
+ i += 2;
+ }
+ "-index" if i + 1 < args.len() => {
+ index = args[i + 1].parse().ok();
+ i += 2;
+ }
+ "-bytes" if i + 1 < args.len() => {
+ bytes = Some(parse_hex_bytes(&args[i + 1]).unwrap_or_else(|e| {
+ eprintln!("{e}");
+ std::process::exit(2);
+ }));
+ i += 2;
+ }
+ "-addr" if i + 1 < args.len() => {
+ addr = parse_u64(&args[i + 1]).unwrap_or(0);
+ i += 2;
+ }
+ "-detail" => {
+ detail = true;
+ i += 1;
+ }
+ other if !other.starts_with('-') && query.is_none() => {
+ query = Some(other.to_string());
+ i += 1;
+ }
+ _ => i += 1,
+ }
+ }
+
+ if detail {
+ json_args["detail"] = json!(true);
+ }
+ if let Some(a) = arch {
+ json_args["arch"] = json!(a.name());
+ }
+ if let Some(m) = mode {
+ json_args["mode"] = json!(m.bits());
+ }
+ if let Some(v) = id {
+ json_args["id"] = json!(v);
+ }
+ if let Some(v) = index {
+ json_args["index"] = json!(v);
+ }
+ if let Some(b) = &bytes {
+ json_args["bytes"] = json!(hex::encode(b));
+ }
+ json_args["addr"] = json!(format!("{addr:#x}"));
+ if let Some(q) = query {
+ json_args["query"] = json!(q);
+ } else {
+ eprintln!("missing -query");
+ return ExitCode::from(2);
+ }
+
+ match run_decode_query(&json_args) {
+ Ok(body) => {
+ if json {
+ super::emit_json_helper(&body);
+ } else {
+ println!("{}", serde_json::to_string_pretty(&body).unwrap());
+ }
+ ExitCode::SUCCESS
+ }
+ Err(e) => {
+ eprintln!("error: {e}");
+ ExitCode::FAILURE
+ }
+ }
+}
+
+pub fn run_decode_query(args: &Value) -> Result<Value, String> {
+ let query = args
+ .get("query")
+ .and_then(|v| v.as_str())
+ .ok_or_else(|| "missing query".to_string())?;
+ let arch = if let Some(a) = args.get("arch").and_then(|v| v.as_str()) {
+ parse_arch(a)?
+ } else {
+ Arch::X86
+ };
+ let mode = if let Some(m) = args.get("mode") {
+ parse_mode_value(m)?
+ } else if arch == Arch::X86 {
+ Mode::MODE_64
+ } else {
+ Mode::LITTLE_ENDIAN
+ };
+
+ let mut engine = Engine::open(arch, mode).map_err(|e| e.to_string())?;
+ apply_detail_from_json(&mut engine, args)?;
+
+ match query {
+ "insn_name" => {
+ let id = args
+ .get("id")
+ .and_then(|v| v.as_u64())
+ .ok_or_else(|| "insn_name requires id".to_string())? as u32;
+ let name = engine
+ .insn_name(InsnId(id))
+ .ok_or_else(|| format!("unknown insn id {id}"))?;
+ Ok(json!({ "query": query, "id": id, "name": name }))
+ }
+ "reg_name" => {
+ let id = args
+ .get("id")
+ .and_then(|v| v.as_u64())
+ .ok_or_else(|| "reg_name requires id".to_string())? as u32;
+ let name = engine
+ .reg_name(RegId(id))
+ .ok_or_else(|| format!("unknown reg id {id}"))?;
+ Ok(json!({ "query": query, "id": id, "name": name }))
+ }
+ "group_name" => {
+ let id = args
+ .get("id")
+ .and_then(|v| v.as_u64())
+ .ok_or_else(|| "group_name requires id".to_string())? as u16;
+ let name = engine
+ .group_name(ghidrust_core::GroupId::from_raw(id))
+ .ok_or_else(|| format!("unknown group id {id}"))?;
+ Ok(json!({ "query": query, "id": id, "name": name }))
+ }
+ q @ ("insn_group" | "reg_read" | "reg_write" | "op_count" | "op_index" | "regs_access") => {
+ let insn = decode_insn_arg(&mut engine, args)?;
+ let idx = args
+ .get("index")
+ .and_then(|v| v.as_u64())
+ .unwrap_or(0) as usize;
+ match q {
+ "insn_group" => {
+ let group = engine
+ .insn_group(&insn, idx)
+ .ok_or_else(|| format!("no group at index {idx}"))?;
+ Ok(json!({
+ "query": query,
+ "index": idx,
+ "group": group,
+ }))
+ }
+ "reg_read" => {
+ let reg = engine
+ .reg_read(&insn, idx)
+ .ok_or_else(|| format!("no reg_read at index {idx}"))?;
+ let name = engine.reg_name(reg);
+ Ok(json!({ "query": query, "index": idx, "reg": reg, "name": name }))
+ }
+ "reg_write" => {
+ let reg = engine
+ .reg_write(&insn, idx)
+ .ok_or_else(|| format!("no reg_write at index {idx}"))?;
+ let name = engine.reg_name(reg);
+ Ok(json!({ "query": query, "index": idx, "reg": reg, "name": name }))
+ }
+ "op_count" => Ok(json!({
+ "query": query,
+ "count": engine.op_count(&insn),
+ })),
+ "op_index" => {
+ let op = engine
+ .op_index(&insn, idx)
+ .ok_or_else(|| format!("no operand at index {idx}"))?;
+ Ok(json!({ "query": query, "index": idx, "operand": op }))
+ }
+ "regs_access" => {
+ let access = engine
+ .regs_access(&insn)
+ .ok_or_else(|| "detail required for regs_access".to_string())?;
+ Ok(json!({
+ "query": query,
+ "read": access.read,
+ "write": access.write,
+ "implicit_read": access.implicit_read,
+ "implicit_write": access.implicit_write,
+ }))
+ }
+ _ => unreachable!(),
+ }
+ }
+ other => Err(format!("unknown query: {other}")),
+ }
+}
+
+fn decode_insn_arg(engine: &mut Engine, args: &Value) -> Result<ghidrust_core::Instruction, String> {
+ let bytes_hex = args
+ .get("bytes")
+ .and_then(|v| v.as_str())
+ .ok_or_else(|| "instruction queries require bytes".to_string())?;
+ let bytes = parse_hex_bytes(bytes_hex)?;
+ let addr = args
+ .get("addr")
+ .and_then(|v| v.as_str())
+ .map(parse_u64)
+ .transpose()?
+ .unwrap_or(0);
+ if args.get("detail").and_then(|v| v.as_bool()) == Some(true) {
+ engine.option(Opt::Detail(true)).map_err(|e| e.to_string())?;
+ }
+ engine.disasm_one(&bytes, addr).map_err(|e| e.to_string())
+}
+
+mod hex {
+ pub fn encode(bytes: &[u8]) -> String {
+ bytes.iter().map(|b| format!("{b:02x}")).collect()
+ }
+}
diff --git a/crates/ghidrust-cli/src/decode_support_cmd.rs b/crates/ghidrust-cli/src/decode_support_cmd.rs
new file mode 100644
index 0000000..f58bd89
--- /dev/null
+++ b/crates/ghidrust-cli/src/decode_support_cmd.rs
@@ -0,0 +1,76 @@
+//! `decode-support` CLI command and shared JSON surface.
+
+use ghidrust_core::{support, Arch, DECODE_VERSION, SupportQuery};
+use serde_json::{json, Value};
+
+pub fn decode_support_json() -> Value {
+ let arches: Vec<Value> = Arch::ALL
+ .iter()
+ .map(|a| {
+ json!({
+ "name": a.name(),
+ "supported": support(SupportQuery::Arch(*a)),
+ })
+ })
+ .collect();
+ json!({
+ "version": DECODE_VERSION,
+ "arches": arches,
+ "options": [
+ "syntax",
+ "detail",
+ "detail_real",
+ "mode",
+ "skipdata",
+ "skipdata_setup",
+ "mnemonic",
+ "unsigned",
+ "only_offset_branch",
+ "litbase",
+ ],
+ "syntax_values()": syntax_values(),
+ "features": decode_features(),
+ })
+}
+
+pub fn decode_features() -> Value {
+ json!({
+ "decode_diet": support(SupportQuery::Diet),
+ "x86_reduce": support(SupportQuery::X86Reduce),
+ })
+}
+
+pub fn syntax_values() -> Vec<&'static str> {
+ vec![
+ "default",
+ "intel",
+ "att",
+ "noregname",
+ "masm",
+ "motorola",
+ "cs_reg_alias",
+ "percent",
+ "no_dollar",
+ "no_alias_text",
+ "no_alias_text_compressed",
+ ]
+}
+
+pub fn cmd_decode_support(_args: &[String], json: bool) -> std::process::ExitCode {
+ let body = decode_support_json();
+ if json {
+ super::emit_json_helper(&body);
+ } else {
+ println!("{}", serde_json::to_string_pretty(&body).unwrap());
+ }
+ std::process::ExitCode::SUCCESS
+}
+
+/// Apply engine options from JSON for decode-query (detail flag only here).
+pub fn apply_detail_from_json(engine: &mut ghidrust_core::Engine, args: &Value) -> Result<(), String> {
+ use ghidrust_core::Opt;
+ if args.get("detail").and_then(|v| v.as_bool()) == Some(true) {
+ engine.option(Opt::Detail(true)).map_err(|e| e.to_string())?;
+ }
+ Ok(())
+}
diff --git a/crates/ghidrust-cli/src/disasm_cmd.rs b/crates/ghidrust-cli/src/disasm_cmd.rs
new file mode 100644
index 0000000..8d38530
--- /dev/null
+++ b/crates/ghidrust-cli/src/disasm_cmd.rs
@@ -0,0 +1,288 @@
+//! `disasm` / `disassemble` CLI command.
+
+use crate::decode_opts::DecodeOpts;
+use ghidrust_core::{
+ assess_bounds_honesty, collect_callsite_hints, disassemble_range_ex_opts, load_blob, load_path,
+ load_path_opts, resolve_function, BoundsHonesty, CallsiteHint, DisasmMode, DisasmRangeResult,
+ Instruction, Program,
+};
+use serde_json::json;
+use std::fs;
+use std::path::Path;
+use std::process::ExitCode;
+
+pub fn cmd_disasm(args: &[String], json: bool) -> ExitCode {
+ let (path, opts) = match DecodeOpts::from_cli_args(args) {
+ Ok(v) => v,
+ Err(e) => {
+ eprintln!("{e}");
+ return ExitCode::from(2);
+ }
+ };
+
+ let load_result = if opts.raw_blob_mode() {
+ let data = match fs::read(&path) {
+ Ok(d) => d,
+ Err(e) => {
+ eprintln!("error: {e}");
+ return ExitCode::FAILURE;
+ }
+ };
+ Ok(load_blob(
+ &data,
+ path.file_name()
+ .map(|s| s.to_string_lossy().into_owned())
+ .unwrap_or_else(|| "blob".into()),
+ ))
+ } else {
+ load_path_opts(&path, false).or_else(|_| load_path(&path))
+ };
+
+ match load_result {
+ Ok(mut prog) => run_disasm_on_prog(&mut prog, &opts, json),
+ Err(e) => {
+ eprintln!("error: {e}");
+ ExitCode::FAILURE
+ }
+ }
+}
+
+fn run_disasm_on_prog(prog: &mut Program, opts: &DecodeOpts, json: bool) -> ExitCode {
+ if opts.raw_blob_mode() && prog.format == "blob" {
+ return disasm_raw_blob(prog, opts, json);
+ }
+
+ let start = opts.addr.or(prog.entry).unwrap_or(prog.image_base);
+ let engine_opts = opts.to_engine_opts();
+ let (mode, bound_end) = disasm_mode_bounds(prog, start, opts);
+
+ match disassemble_range_ex_opts(
+ prog,
+ start,
+ opts.count,
+ opts.skip_bad,
+ mode,
+ bound_end,
+ Some(&engine_opts),
+ ) {
+ Ok(result) => {
+ let honesty = assess_bounds_honesty(
+ prog,
+ result.entry.or(Some(start)),
+ result.end.or(bound_end),
+ result.insns.len(),
+ result.stop_reason,
+ );
+ let callsite_hints = collect_callsite_hints(&result.insns);
+ emit_disasm_result(&result, mode, json, opts, &honesty, &callsite_hints)
+ }
+ Err(e) => {
+ eprintln!("error: {e}");
+ ExitCode::FAILURE
+ }
+ }
+}
+
+fn disasm_mode_bounds(
+ prog: &mut Program,
+ start: u64,
+ opts: &DecodeOpts,
+) -> (DisasmMode, Option<u64>) {
+ if opts.linear {
+ (DisasmMode::Linear, None)
+ } else if opts.flow {
+ let bound = resolve_function(prog, start)
+ .ok()
+ .filter(|r| r.ok)
+ .and_then(|r| r.function_end);
+ (DisasmMode::Flow, bound)
+ } else {
+ match resolve_function(prog, start) {
+ Ok(r) if r.ok => (DisasmMode::Bounded, r.function_end),
+ _ => (DisasmMode::Linear, None),
+ }
+ }
+}
+
+fn disasm_raw_blob(prog: &Program, opts: &DecodeOpts, json: bool) -> ExitCode {
+ let engine_opts = opts.to_engine_opts();
+ let mut engine = match engine_opts.open_engine(prog) {
+ Ok(e) => e,
+ Err(e) => {
+ eprintln!("error: {e}");
+ return ExitCode::FAILURE;
+ }
+ };
+ let start = opts.addr.unwrap_or(0);
+ let bytes: Vec<u8> = prog
+ .blocks
+ .iter()
+ .flat_map(|b| b.bytes.clone())
+ .collect();
+ let offset = start.min(bytes.len() as u64) as usize;
+ let slice = &bytes[offset..];
+ match engine.disasm(slice, start, opts.count) {
+ Ok(insns) => {
+ let callsite_hints = collect_callsite_hints(&insns);
+ let listing = format_listing_string(&insns, opts, None, DisasmMode::Linear, None);
+ let body = json!({
+ "insns": insns,
+ "mode": "raw_blob",
+ "addr": format!("{start:#x}"),
+ "listing_text": listing_lines(&insns, opts),
+ "callsite_hints": callsite_hints,
+ "bounds_suspect": false,
+ });
+ emit_out(&body, json, opts.out_path.as_deref(), &listing, || {
+ print!("{listing}");
+ })
+ }
+ Err(e) => {
+ eprintln!("error: {e}");
+ ExitCode::FAILURE
+ }
+ }
+}
+
+fn emit_disasm_result(
+ result: &DisasmRangeResult,
+ mode: DisasmMode,
+ json: bool,
+ opts: &DecodeOpts,
+ honesty: &BoundsHonesty,
+ callsite_hints: &[CallsiteHint],
+) -> ExitCode {
+ let listing_text = listing_lines(&result.insns, opts);
+ let listing = format_listing_string(&result.insns, opts, Some(honesty), mode, Some(result));
+ let mut body = json!({
+ "insns": result.insns,
+ "decode_gaps": result.decode_gaps,
+ "first_gap_va": result.first_gap_va.map(|v| format!("{v:#x}")),
+ "stop_reason": result.stop_reason,
+ "mode": mode,
+ "entry": result.entry.map(|v| format!("{v:#x}")),
+ "end": result.end.map(|v| format!("{v:#x}")),
+ "listing_text": listing_text,
+ "callsite_hints": callsite_hints,
+ });
+ if let Some(obj) = body.as_object_mut() {
+ if let Some(m) = honesty.to_json_fields().as_object() {
+ for (k, v) in m {
+ obj.insert(k.clone(), v.clone());
+ }
+ }
+ }
+ emit_out(&body, json, opts.out_path.as_deref(), &listing, || {
+ print!("{listing}");
+ if honesty.bounds_suspect {
+ if let Some(w) = &honesty.bounds_warning {
+ eprintln!("warning: {w}");
+ }
+ }
+ })
+}
+
+fn listing_lines(insns: &[Instruction], opts: &DecodeOpts) -> String {
+ insns
+ .iter()
+ .map(|i| {
+ if opts.brief || opts.pretty {
+ i.brief_text()
+ } else {
+ i.text()
+ }
+ })
+ .collect::<Vec<_>>()
+ .join("\n")
+}
+
+fn format_listing_string(
+ insns: &[Instruction],
+ opts: &DecodeOpts,
+ honesty: Option<&BoundsHonesty>,
+ mode: DisasmMode,
+ result: Option<&DisasmRangeResult>,
+) -> String {
+ let mut s = String::new();
+ if opts.pretty {
+ let entry = result
+ .and_then(|r| r.entry)
+ .map(|v| format!("{v:#x}"))
+ .unwrap_or_else(|| "-".into());
+ let end = result
+ .and_then(|r| r.end)
+ .map(|v| format!("{v:#x}"))
+ .unwrap_or_else(|| "-".into());
+ let stop = result
+ .map(|r| format!("{:?}", r.stop_reason))
+ .unwrap_or_else(|| "-".into());
+ s.push_str(&format!(
+ "; entry={entry} end={end} n={} mode={mode:?} stop_reason={stop}\n",
+ insns.len()
+ ));
+ }
+ for insn in insns {
+ if opts.brief || opts.pretty {
+ s.push_str(&insn.brief_text());
+ } else {
+ s.push_str(&insn.text());
+ }
+ s.push('\n');
+ }
+ if let Some(r) = result {
+ if r.decode_gaps > 0 {
+ s.push_str(&format!(
+ "; decode_gaps={} first_gap={:?}\n",
+ r.decode_gaps,
+ r.first_gap_va.map(|v| format!("{v:#x}"))
+ ));
+ }
+ if !opts.pretty {
+ s.push_str(&format!(
+ "; stop_reason={:?} mode={mode:?}\n",
+ r.stop_reason
+ ));
+ }
+ }
+ if let Some(h) = honesty {
+ if h.bounds_suspect {
+ if let Some(w) = &h.bounds_warning {
+ s.push_str(&format!("; warning: {w}\n"));
+ }
+ if let Some(e) = h.suggested_end {
+ s.push_str(&format!("; suggested_end={e:#x}\n"));
+ }
+ if let Some(hint) = &h.heal_hint {
+ s.push_str(&format!("; heal_hint: {hint}\n"));
+ }
+ }
+ }
+ s
+}
+
+fn emit_out(
+ body: &serde_json::Value,
+ json: bool,
+ out_path: Option<&Path>,
+ text_listing: &str,
+ print_stdout: impl FnOnce(),
+) -> ExitCode {
+ if let Some(p) = out_path {
+ if json {
+ return super::emit_result_helper(body, true, Some(p), || {});
+ }
+ if let Err(e) = fs::write(p, text_listing) {
+ eprintln!("error writing {}: {e}", p.display());
+ return ExitCode::FAILURE;
+ }
+ eprintln!("wrote {}", p.display());
+ return ExitCode::SUCCESS;
+ }
+ if json {
+ super::emit_json_helper(body);
+ ExitCode::SUCCESS
+ } else {
+ print_stdout();
+ ExitCode::SUCCESS
+ }
+}
diff --git a/crates/ghidrust-cli/src/friction.rs b/crates/ghidrust-cli/src/friction.rs
index e1413a1..6ed993b 100644
--- a/crates/ghidrust-cli/src/friction.rs
+++ b/crates/ghidrust-cli/src/friction.rs
@@ -2,7 +2,8 @@
use ghidrust_core::{
artifact_get, artifact_query, envelope_or_spill, inventory_pe_dir, list_artifacts, list_tree,
- load_path, process_attach, process_detach, process_list, process_modules, process_read,
+ load_path, process_attach, process_detach, process_launch, process_list, process_modules,
+ process_read, process_resume, LaunchRequest,
process_regions, process_resolve, resolve_function, resolve_result_json, rtti_query,
section_notes_for, spill_artifact, write_json_no_bom, Project, RttiMatchMode, TreeListOpts,
DEFAULT_PREVIEW_LIMIT,
@@ -12,13 +13,13 @@ use std::path::PathBuf;
use std::process::ExitCode;
pub fn parse_u64(s: &str) -> Result<u64, String> {
- let t = s.trim().trim_start_matches("0x").trim_start_matches("0X");
+ let t = s.trim().trim_start_matches("0x").trim_start_matches("0X");
u64::from_str_radix(t, 16)
.or_else(|_| s.parse::<u64>())
.map_err(|e| e.to_string())
}
-/// Resolve binary path from `--path` or `--project` + `--file-id`.
+/// Resolve binary path from `-path` or `-project` + `-file-id`.
pub fn resolve_program_path(args: &[String]) -> Result<(PathBuf, Value), String> {
let mut path: Option<PathBuf> = None;
let mut project: Option<PathBuf> = None;
@@ -26,19 +27,19 @@ pub fn resolve_program_path(args: &[String]) -> Result<(PathBuf, Value), String>
let mut i = 0;
while i < args.len() {
match args[i].as_str() {
- "--path" if i + 1 < args.len() => {
+ "-path" if i + 1 < args.len() => {
path = Some(PathBuf::from(&args[i + 1]));
i += 2;
}
- "--project" if i + 1 < args.len() => {
+ "-project" if i + 1 < args.len() => {
project = Some(PathBuf::from(&args[i + 1]));
i += 2;
}
- "--file-id" | "--file" if i + 1 < args.len() => {
+ "-file-id" | "-file" if i + 1 < args.len() => {
file_id = Some(args[i + 1].clone());
i += 2;
}
- other if !other.starts_with('-') && path.is_none() && project.is_none() => {
+ other if !other.starts_with('-') && path.is_none() && project.is_none() => {
path = Some(PathBuf::from(other));
i += 1;
}
@@ -47,38 +48,38 @@ pub fn resolve_program_path(args: &[String]) -> Result<(PathBuf, Value), String>
}
if let Some(p) = path {
let facts = json!({
- "path": p.display().to_string(),
- "project": Value::Null,
- "file_id": Value::Null,
- "resolved_path": p.display().to_string(),
+ "path": p.display().to_string(),
+ "project": Value::Null,
+ "file_id": Value::Null,
+ "resolved_path": p.display().to_string(),
});
return Ok((p, facts));
}
let Some(proj) = project else {
- return Err("provide <path> or --project DIR --file-id ID".into());
+ return Err("provide <path> or -project DIR -file-id ID".into());
};
let Some(fid) = file_id else {
- return Err("load with --project requires --file-id".into());
+ return Err("load with -project requires -file-id".into());
};
let project = Project::open(&proj).map_err(|e| e.to_string())?;
let entry = project
.list_files()
.into_iter()
.find(|f| f.id == fid)
- .ok_or_else(|| format!("file_id not found: {fid}"))?;
+ .ok_or_else(|| format!("file_id not found: {fid}"))?;
let resolved = project.root.join(&entry.imported_rel);
if !resolved.is_file() {
return Err(format!(
- "resolved path missing: {} (file_id={fid})",
+ "resolved path missing: {} (file_id={fid})",
resolved.display()
));
}
let facts = json!({
- "path": Value::Null,
- "project": proj.display().to_string(),
- "file_id": fid,
- "resolved_path": resolved.display().to_string(),
- "display_name": entry.display_name,
+ "path": Value::Null,
+ "project": proj.display().to_string(),
+ "file_id": fid,
+ "resolved_path": resolved.display().to_string(),
+ "display_name": entry.display_name,
});
Ok((resolved, facts))
}
@@ -86,37 +87,37 @@ pub fn resolve_program_path(args: &[String]) -> Result<(PathBuf, Value), String>
pub fn load_json_for_prog(prog: &ghidrust_core::Program, identity: &Value) -> Value {
let notes = section_notes_for(prog);
json!({
- "name": prog.name,
- "format": prog.format,
- "image_base": format!("{:#x}", prog.image_base),
- "entry": prog.entry.map(|e| format!("{e:#x}")),
- "identity": identity,
- "resolved_path": identity.get("resolved_path").cloned().unwrap_or(Value::Null),
- "sections": prog.sections.iter().map(|s| json!({
- "name": s.name,
- "va": format!("{:#x}", s.va),
- "virtual_size": s.virtual_size,
- "raw_size": s.raw_size,
- "characteristics": format!("{:#x}", s.characteristics),
+ "name": prog.name,
+ "format": prog.format,
+ "image_base": format!("{:#x}", prog.image_base),
+ "entry": prog.entry.map(|e| format!("{e:#x}")),
+ "identity": identity,
+ "resolved_path": identity.get("resolved_path").cloned().unwrap_or(Value::Null),
+ "sections": prog.sections.iter().map(|s| json!({
+ "name": s.name,
+ "va": format!("{:#x}", s.va),
+ "virtual_size": s.virtual_size,
+ "raw_size": s.raw_size,
+ "characteristics": format!("{:#x}", s.characteristics),
})).collect::<Vec<_>>(),
- "section_notes": notes,
+ "section_notes": notes,
})
}
pub fn cmd_artifact(args: &[String], json: bool) -> ExitCode {
if args.is_empty() {
- eprintln!("usage: ghidrust artifact get|query|list <id> [--offset N] [--limit N] [--json]");
+ eprintln!("usage: ghidrust artifact get|query|list <id> [-offset N] [-limit N] [-json]");
return ExitCode::from(2);
}
match args[0].as_str() {
- "list" => match list_artifacts(64) {
+ "list" => match list_artifacts(64) {
Ok(m) => {
if json {
- println!("{}", serde_json::to_string_pretty(&m).unwrap());
+ println!("{}", serde_json::to_string_pretty(&m).unwrap());
} else {
for a in m {
println!(
- "{} kind={} entries={} {}",
+ "{} kind={} entries={} {}",
a.id, a.kind, a.entry_count, a.path
);
}
@@ -124,34 +125,34 @@ pub fn cmd_artifact(args: &[String], json: bool) -> ExitCode {
ExitCode::SUCCESS
}
Err(e) => {
- eprintln!("error: {e}");
+ eprintln!("error: {e}");
ExitCode::FAILURE
}
},
- "get" => {
+ "get" => {
let id = match args.get(1) {
Some(i) => i.as_str(),
None => {
- eprintln!("usage: ghidrust artifact get <id|path>");
+ eprintln!("usage: ghidrust artifact get <id|path>");
return ExitCode::from(2);
}
};
match artifact_get(id) {
Ok(v) => {
- println!("{}", serde_json::to_string_pretty(&v).unwrap());
+ println!("{}", serde_json::to_string_pretty(&v).unwrap());
ExitCode::SUCCESS
}
Err(e) => {
- eprintln!("error: {e}");
+ eprintln!("error: {e}");
ExitCode::FAILURE
}
}
}
- "query" => {
+ "query" => {
let id = match args.get(1) {
Some(i) => i.as_str(),
None => {
- eprintln!("usage: ghidrust artifact query <id|path> [--offset N] [--limit N]");
+ eprintln!("usage: ghidrust artifact query <id|path> [-offset N] [-limit N]");
return ExitCode::from(2);
}
};
@@ -160,11 +161,11 @@ pub fn cmd_artifact(args: &[String], json: bool) -> ExitCode {
let mut i = 2;
while i < args.len() {
match args[i].as_str() {
- "--offset" if i + 1 < args.len() => {
+ "-offset" if i + 1 < args.len() => {
offset = args[i + 1].parse().unwrap_or(0);
i += 2;
}
- "--limit" if i + 1 < args.len() => {
+ "-limit" if i + 1 < args.len() => {
limit = args[i + 1].parse().unwrap_or(DEFAULT_PREVIEW_LIMIT);
i += 2;
}
@@ -173,17 +174,17 @@ pub fn cmd_artifact(args: &[String], json: bool) -> ExitCode {
}
match artifact_query(id, offset, limit) {
Ok(env) => {
- println!("{}", serde_json::to_string_pretty(&env).unwrap());
+ println!("{}", serde_json::to_string_pretty(&env).unwrap());
ExitCode::SUCCESS
}
Err(e) => {
- eprintln!("error: {e}");
+ eprintln!("error: {e}");
ExitCode::FAILURE
}
}
}
other => {
- eprintln!("unknown artifact subcommand: {other}");
+ eprintln!("unknown artifact subcommand: {other}");
ExitCode::from(2)
}
}
@@ -193,7 +194,7 @@ pub fn cmd_inventory(args: &[String], json: bool) -> ExitCode {
let dir = match args.first() {
Some(d) => PathBuf::from(d),
None => {
- eprintln!("usage: ghidrust inventory <dir> [--max-depth N] [--hash] [--out FILE] [--json]");
+ eprintln!("usage: ghidrust inventory <dir> [-max-depth N] [-hash] [-out FILE] [-json]");
return ExitCode::from(2);
}
};
@@ -203,15 +204,15 @@ pub fn cmd_inventory(args: &[String], json: bool) -> ExitCode {
let mut i = 1;
while i < args.len() {
match args[i].as_str() {
- "--max-depth" if i + 1 < args.len() => {
+ "-max-depth" if i + 1 < args.len() => {
max_depth = args[i + 1].parse().unwrap_or(8);
i += 2;
}
- "--hash" => {
+ "-hash" => {
with_hash = true;
i += 1;
}
- "--out" if i + 1 < args.len() => {
+ "-out" if i + 1 < args.len() => {
out_path = Some(PathBuf::from(&args[i + 1]));
i += 2;
}
@@ -222,7 +223,7 @@ pub fn cmd_inventory(args: &[String], json: bool) -> ExitCode {
Ok(inv) => {
let entries = serde_json::to_value(&inv.entries).unwrap();
let env = match envelope_or_spill(
- "inventory",
+ "inventory",
entries,
64,
DEFAULT_PREVIEW_LIMIT,
@@ -230,30 +231,30 @@ pub fn cmd_inventory(args: &[String], json: bool) -> ExitCode {
) {
Ok(e) => e,
Err(e) => {
- eprintln!("error: {e}");
+ eprintln!("error: {e}");
return ExitCode::FAILURE;
}
};
let body = json!({
- "schema_version": inv.schema_version,
- "root": inv.root,
- "notes": inv.notes,
- "envelope": env,
- "entries": if inv.entries.len() <= 64 { Value::Array(inv.entries.iter().map(|e| serde_json::to_value(e).unwrap()).collect()) } else { Value::Null },
+ "schema_version": inv.schema_version,
+ "root": inv.root,
+ "notes": inv.notes,
+ "envelope": env,
+ "entries": if inv.entries.len() <= 64 { Value::Array(inv.entries.iter().map(|e| serde_json::to_value(e).unwrap()).collect()) } else { Value::Null },
});
if let Some(p) = out_path {
if let Err(e) = write_json_no_bom(&p, &body) {
- eprintln!("error: {e}");
+ eprintln!("error: {e}");
return ExitCode::FAILURE;
}
}
if json {
- println!("{}", serde_json::to_string_pretty(&body).unwrap());
+ println!("{}", serde_json::to_string_pretty(&body).unwrap());
} else {
- println!("inventory root={} entries={}", inv.root, inv.entries.len());
+ println!("inventory root={} entries={}", inv.root, inv.entries.len());
for e in inv.entries.iter().take(32) {
println!(
- " {} size={} file_ver={:?} product_ver={:?}",
+ " {} size={} file_ver={:?} product_ver={:?}",
e.path,
e.size,
e.version.file_version,
@@ -262,7 +263,7 @@ pub fn cmd_inventory(args: &[String], json: bool) -> ExitCode {
}
if inv.entries.len() > 32 {
println!(
- " … {} more (use --json / artifact envelope)",
+ " … {} more (use -json / artifact envelope)",
inv.entries.len() - 32
);
}
@@ -270,7 +271,7 @@ pub fn cmd_inventory(args: &[String], json: bool) -> ExitCode {
ExitCode::SUCCESS
}
Err(e) => {
- eprintln!("error: {e}");
+ eprintln!("error: {e}");
ExitCode::FAILURE
}
}
@@ -281,7 +282,7 @@ pub fn cmd_tree(args: &[String], json: bool) -> ExitCode {
Some(d) => PathBuf::from(d),
None => {
eprintln!(
- "usage: ghidrust tree <path> [--max-depth N] [--ext LIST] [--name GLOB] [--json]"
+ "usage: ghidrust tree <path> [-max-depth N] [-ext LIST] [-name GLOB] [-json]"
);
return ExitCode::from(2);
}
@@ -290,21 +291,21 @@ pub fn cmd_tree(args: &[String], json: bool) -> ExitCode {
let mut i = 1;
while i < args.len() {
match args[i].as_str() {
- "--max-depth" if i + 1 < args.len() => {
+ "-max-depth" if i + 1 < args.len() => {
opts.max_depth = args[i + 1].parse().unwrap_or(6);
i += 2;
}
- "--ext" if i + 1 < args.len() => {
+ "-ext" if i + 1 < args.len() => {
opts.extensions = Some(
args[i + 1]
- .split(',')
+ .split(',')
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
.collect(),
);
i += 2;
}
- "--name" if i + 1 < args.len() => {
+ "-name" if i + 1 < args.len() => {
opts.name_glob = Some(args[i + 1].clone());
i += 2;
}
@@ -314,7 +315,7 @@ pub fn cmd_tree(args: &[String], json: bool) -> ExitCode {
let res = list_tree(&dir, opts);
let entries_v = serde_json::to_value(&res.entries).unwrap();
let env = envelope_or_spill(
- "tree",
+ "tree",
entries_v,
128,
DEFAULT_PREVIEW_LIMIT,
@@ -323,34 +324,34 @@ pub fn cmd_tree(args: &[String], json: bool) -> ExitCode {
let env = match env {
Ok(e) => e,
Err(e) => {
- eprintln!("error: {e}");
+ eprintln!("error: {e}");
return ExitCode::FAILURE;
}
};
let body = json!({
- "root": res.root,
- "truncated": res.truncated,
- "envelope": env,
- "entries": if res.entries.len() <= 128 {
+ "root": res.root,
+ "truncated": res.truncated,
+ "envelope": env,
+ "entries": if res.entries.len() <= 128 {
serde_json::to_value(&res.entries).unwrap()
} else {
Value::Null
},
});
if json {
- println!("{}", serde_json::to_string_pretty(&body).unwrap());
+ println!("{}", serde_json::to_string_pretty(&body).unwrap());
} else {
for e in res.entries.iter().take(64) {
if let Some(err) = &e.error {
- println!("ERR {} ({err})", e.path);
+ println!("ERR {} ({err})", e.path);
} else if e.is_dir {
- println!("DIR {}", e.path);
+ println!("DIR {}", e.path);
} else {
- println!("FILE {} size={:?}", e.path, e.size);
+ println!("FILE {} size={:?}", e.path, e.size);
}
}
if res.truncated || res.entries.len() > 64 {
- println!("… truncated; drain via artifact envelope");
+ println!("… truncated; drain via artifact envelope");
}
}
ExitCode::SUCCESS
@@ -359,19 +360,19 @@ pub fn cmd_tree(args: &[String], json: bool) -> ExitCode {
pub fn cmd_process(args: &[String], json: bool) -> ExitCode {
if args.is_empty() {
eprintln!(
- "usage: ghidrust process list|attach|detach|modules|read|resolve|regions … [--json]"
+ "usage: ghidrust process list|attach|launch|resume|detach|modules|read|resolve|regions … [-json]"
);
return ExitCode::from(2);
}
match args[0].as_str() {
- "list" => match process_list() {
+ "list" => match process_list() {
Ok(list) => {
if json {
- println!("{}", serde_json::to_string_pretty(&list).unwrap());
+ println!("{}", serde_json::to_string_pretty(&list).unwrap());
} else {
for p in list.iter().take(200) {
println!(
- "{:>8} {} {}",
+ "{:>8} {} {}",
p.pid,
p.name,
p.path.as_deref().unwrap_or("-")
@@ -381,72 +382,133 @@ pub fn cmd_process(args: &[String], json: bool) -> ExitCode {
ExitCode::SUCCESS
}
Err(e) => {
- eprintln!("error: {e}");
+ eprintln!("error: {e}");
ExitCode::FAILURE
}
},
- "attach" => {
+ "attach" => {
let pid: u32 = match args.get(1).and_then(|s| s.parse().ok()) {
Some(p) => p,
None => {
- eprintln!("usage: ghidrust process attach <pid>");
+ eprintln!("usage: ghidrust process attach <pid>");
return ExitCode::from(2);
}
};
match process_attach(pid) {
Ok(s) => {
- println!("{}", serde_json::to_string_pretty(&s).unwrap());
+ println!("{}", serde_json::to_string_pretty(&s).unwrap());
ExitCode::SUCCESS
}
Err(e) => {
- eprintln!("error: {e}");
+ eprintln!("error: {e}");
ExitCode::FAILURE
}
}
}
- "detach" => {
+ "launch" => {
+ let image = match args.get(1).filter(|s| !s.starts_with('-')) {
+ Some(p) => PathBuf::from(p),
+ None => {
+ eprintln!(
+ "usage: ghidrust process launch <image.exe> [-args \"…\"] [-cwd DIR] [-json]"
+ );
+ return ExitCode::from(2);
+ }
+ };
+ let mut launch_args: Option<String> = None;
+ let mut cwd: Option<PathBuf> = None;
+ let mut i = 2;
+ while i < args.len() {
+ match args[i].as_str() {
+ "-args" if i + 1 < args.len() => {
+ launch_args = Some(args[i + 1].clone());
+ i += 2;
+ }
+ "-cwd" if i + 1 < args.len() => {
+ cwd = Some(PathBuf::from(&args[i + 1]));
+ i += 2;
+ }
+ "-json" => i += 1,
+ _ => i += 1,
+ }
+ }
+ match process_launch(&LaunchRequest {
+ image,
+ args: launch_args,
+ cwd,
+ }) {
+ Ok(r) => {
+ println!("{}", serde_json::to_string_pretty(&r).unwrap());
+ ExitCode::SUCCESS
+ }
+ Err(e) => {
+ eprintln!("error: {e}");
+ ExitCode::FAILURE
+ }
+ }
+ }
+ "resume" => {
+ let sid = match args.get(1) {
+ Some(s) => s.as_str(),
+ None => {
+ eprintln!("usage: ghidrust process resume <session_id>");
+ return ExitCode::from(2);
+ }
+ };
+ match process_resume(sid) {
+ Ok(()) => {
+ println!("{{\"ok\":true,\"resumed\":true}}");
+ ExitCode::SUCCESS
+ }
+ Err(e) => {
+ eprintln!("error: {e}");
+ ExitCode::FAILURE
+ }
+ }
+ }
+ "detach" => {
let sid = match args.get(1) {
Some(s) => s.as_str(),
None => {
- eprintln!("usage: ghidrust process detach <session_id>");
+ eprintln!("usage: ghidrust process detach <session_id>");
return ExitCode::from(2);
}
};
match process_detach(sid) {
Ok(()) => {
- println!("{{\"ok\":true}}");
+ println!("{{\"ok\":true}}");
ExitCode::SUCCESS
}
Err(e) => {
- eprintln!("error: {e}");
+ eprintln!("error: {e}");
ExitCode::FAILURE
}
}
}
- "modules" => {
+ "modules" => {
let sid = match args.get(1) {
Some(s) => s.as_str(),
None => {
- eprintln!("usage: ghidrust process modules <session_id>");
+ eprintln!("usage: ghidrust process modules <session_id>");
return ExitCode::from(2);
}
};
match process_modules(sid) {
Ok(m) => {
- println!("{}", serde_json::to_string_pretty(&m).unwrap());
+ println!("{}", serde_json::to_string_pretty(&m).unwrap());
ExitCode::SUCCESS
}
Err(e) => {
- eprintln!("error: {e}");
+ eprintln!("error: {e}");
ExitCode::FAILURE
}
}
}
- "read" => {
+ "read" => {
let sid = match args.get(1) {
Some(s) => s.as_str(),
None => {
- eprintln!("usage: ghidrust process read <session_id> --addr HEX --size N");
+ eprintln!("usage: ghidrust process read <session_id> -addr HEX -size N");
return ExitCode::from(2);
}
};
@@ -455,11 +517,11 @@ pub fn cmd_process(args: &[String], json: bool) -> ExitCode {
let mut i = 2;
while i < args.len() {
match args[i].as_str() {
- "--addr" if i + 1 < args.len() => {
+ "-addr" if i + 1 < args.len() => {
addr = parse_u64(&args[i + 1]).ok();
i += 2;
}
- "--size" if i + 1 < args.len() => {
+ "-size" if i + 1 < args.len() => {
size = args[i + 1].parse().unwrap_or(64);
i += 2;
}
@@ -467,26 +529,26 @@ pub fn cmd_process(args: &[String], json: bool) -> ExitCode {
}
}
let Some(va) = addr else {
- eprintln!("missing --addr");
+ eprintln!("missing -addr");
return ExitCode::from(2);
};
match process_read(sid, va, size) {
Ok(r) => {
- println!("{}", serde_json::to_string_pretty(&r).unwrap());
+ println!("{}", serde_json::to_string_pretty(&r).unwrap());
ExitCode::SUCCESS
}
Err(e) => {
- eprintln!("error: {e}");
+ eprintln!("error: {e}");
ExitCode::FAILURE
}
}
}
- "resolve" => {
+ "resolve" => {
let sid = match args.get(1) {
Some(s) => s.as_str(),
None => {
eprintln!(
- "usage: ghidrust process resolve <session_id> --module NAME --rva HEX"
+ "usage: ghidrust process resolve <session_id> -module NAME -rva HEX"
);
return ExitCode::from(2);
}
@@ -496,11 +558,11 @@ pub fn cmd_process(args: &[String], json: bool) -> ExitCode {
let mut i = 2;
while i < args.len() {
match args[i].as_str() {
- "--module" if i + 1 < args.len() => {
+ "-module" if i + 1 < args.len() => {
module = Some(args[i + 1].clone());
i += 2;
}
- "--rva" if i + 1 < args.len() => {
+ "-rva" if i + 1 < args.len() => {
rva = parse_u64(&args[i + 1]).ok();
i += 2;
}
@@ -508,32 +570,32 @@ pub fn cmd_process(args: &[String], json: bool) -> ExitCode {
}
}
let (Some(m), Some(r)) = (module, rva) else {
- eprintln!("need --module and --rva");
+ eprintln!("need -module and -rva");
return ExitCode::from(2);
};
match process_resolve(sid, &m, r) {
Ok(r) => {
- println!("{}", serde_json::to_string_pretty(&r).unwrap());
+ println!("{}", serde_json::to_string_pretty(&r).unwrap());
ExitCode::SUCCESS
}
Err(e) => {
- eprintln!("error: {e}");
+ eprintln!("error: {e}");
ExitCode::FAILURE
}
}
}
- "regions" => {
+ "regions" => {
let sid = match args.get(1) {
Some(s) => s.as_str(),
None => {
- eprintln!("usage: ghidrust process regions <session_id> [--max N]");
+ eprintln!("usage: ghidrust process regions <session_id> [-max N]");
return ExitCode::from(2);
}
};
let mut max = 256usize;
let mut i = 2;
while i < args.len() {
- if args[i] == "--max" && i + 1 < args.len() {
+ if args[i] == "-max" && i + 1 < args.len() {
max = args[i + 1].parse().unwrap_or(256);
i += 2;
} else {
@@ -542,17 +604,17 @@ pub fn cmd_process(args: &[String], json: bool) -> ExitCode {
}
match process_regions(sid, max) {
Ok(r) => {
- println!("{}", serde_json::to_string_pretty(&r).unwrap());
+ println!("{}", serde_json::to_string_pretty(&r).unwrap());
ExitCode::SUCCESS
}
Err(e) => {
- eprintln!("error: {e}");
+ eprintln!("error: {e}");
ExitCode::FAILURE
}
}
}
other => {
- eprintln!("unknown process subcommand: {other}");
+ eprintln!("unknown process subcommand: {other}");
ExitCode::from(2)
}
}
@@ -560,10 +622,10 @@ pub fn cmd_process(args: &[String], json: bool) -> ExitCode {
pub fn cmd_rtti_query_cli(args: &[String], json: bool) -> ExitCode {
let path = match args.first() {
- Some(p) if !p.starts_with('-') => PathBuf::from(p),
+ Some(p) if !p.starts_with('-') => PathBuf::from(p),
_ => {
eprintln!(
- "usage: ghidrust rtti <path> [--filter SUB|--name NAME|--exact] [--match MODE] [--json]"
+ "usage: ghidrust rtti <path> [-filter SUB|-name NAME|-exact] [-match MODE] [-json]"
);
return ExitCode::from(2);
}
@@ -574,15 +636,15 @@ pub fn cmd_rtti_query_cli(args: &[String], json: bool) -> ExitCode {
let mut i = 1;
while i < args.len() {
match args[i].as_str() {
- "--filter" | "--name" if i + 1 < args.len() => {
+ "-filter" | "-name" if i + 1 < args.len() => {
filter = Some(args[i + 1].clone());
i += 2;
}
- "--exact" => {
+ "-exact" => {
exact = true;
i += 1;
}
- "--match" if i + 1 < args.len() => {
+ "-match" if i + 1 < args.len() => {
mode = RttiMatchMode::parse(&args[i + 1]);
i += 2;
}
@@ -594,31 +656,31 @@ pub fn cmd_rtti_query_cli(args: &[String], json: bool) -> ExitCode {
let prog = match load_path(&path) {
Ok(p) => p,
Err(e) => {
- eprintln!("error: {e}");
+ eprintln!("error: {e}");
return ExitCode::FAILURE;
}
};
match rtti_query(&prog, filter.as_deref(), exact, mode) {
Ok(q) => {
let entries = serde_json::to_value(&q.classes).unwrap();
- let env = spill_if_large("rtti", entries, q.entry_count);
+ let env = spill_if_large("rtti", entries, q.entry_count);
let body = json!({
- "entry_count": q.entry_count,
- "cache_hit": q.cache_hit,
- "notes": q.notes,
- "envelope": env,
- "classes": if q.entry_count <= 64 {
+ "entry_count": q.entry_count,
+ "cache_hit": q.cache_hit,
+ "notes": q.notes,
+ "envelope": env,
+ "classes": if q.entry_count <= 64 {
serde_json::to_value(&q.classes).unwrap()
} else {
Value::Null
},
});
if json {
- println!("{}", serde_json::to_string_pretty(&body).unwrap());
+ println!("{}", serde_json::to_string_pretty(&body).unwrap());
} else {
for c in q.classes.iter().take(64) {
println!(
- "{} vtables={:?} col={:?} conf={} {:?}",
+ "{} vtables={:?} col={:?} conf={} {:?}",
c.name, c.vtable_vas, c.col_va, c.confidence, c.reason
);
}
@@ -626,7 +688,7 @@ pub fn cmd_rtti_query_cli(args: &[String], json: bool) -> ExitCode {
ExitCode::SUCCESS
}
Err(e) => {
- eprintln!("error: {e}");
+ eprintln!("error: {e}");
ExitCode::FAILURE
}
}
@@ -647,14 +709,14 @@ pub fn resolve_and_entry(
addr: Option<u64>,
) -> Result<(u64, Value), String> {
let requested = addr.unwrap_or_else(|| prog.entry.unwrap_or(prog.image_base));
- // Synthesize/heal orphans so decompile and other agent paths do not hard-fail
- // on executable VAs outside analyzed function ranges.
+ // Synthesize/heal orphans so decompile and other agent paths do not hard-fail
+ // on executable VAs outside analyzed function ranges.
let r = resolve_function(prog, requested).map_err(|e| e.to_string())?;
let meta = resolve_result_json(&r);
if !r.ok {
return Err(format!(
- "resolve failed: {} ({})",
- r.reason.as_deref().unwrap_or("unknown"),
+ "resolve failed: {} ({})",
+ r.reason.as_deref().unwrap_or("unknown"),
meta
));
}
diff --git a/crates/ghidrust-cli/src/main.rs b/crates/ghidrust-cli/src/main.rs
index 66eda44..f8551f2 100644
--- a/crates/ghidrust-cli/src/main.rs
+++ b/crates/ghidrust-cli/src/main.rs
@@ -1,19 +1,24 @@
//! Ghidrust CLI + stdio MCP/agent tool surface over ghidrust-core.
mod friction;
+mod decode_opts;
+mod disasm_cmd;
+mod decode_support_cmd;
+mod decode_query_cmd;
+mod mcp_decode;
use ghidrust_core::{
- analyzer_catalog, analyze_path, artifact_get, artifact_query, calls_callees,
- collect_strings_bytes, collect_strings_opts, disassemble_range_ex, disassemble_range_opts,
- filter_imports, inventory_pe_dir, list_artifacts, list_tree, load_path, load_path_opts,
- process_attach, process_detach, process_list, process_modules, process_read, process_regions,
- process_resolve, recover_rtti, resolve_function, rtti_query, run_analyzers,
- create_function,
- scan_ascii_strings_bulk, scan_printable_runs_gpu_or_fallback, scan_printable_runs_parallel,
- scan_printable_runs_seq, time_bulk_printable, write_json_no_bom, xrefs_from, xrefs_to,
- xrefs_to_import, xrefs_to_string_filter_opts, AnalysisBundle, BulkScanMode, DisasmMode,
- Program, Project, RttiMatchMode, StringCollectOpts, StringMatchMode, TreeListOpts,
- ANALYZER_NAMES, DEFAULT_PREVIEW_LIMIT,
+ analyzer_catalog, analyze_path, artifact_get, artifact_query, assess_decompile_bounds,
+ calls_callees, collect_callsite_hints, collect_strings_bytes, collect_strings_opts,
+ create_function, disassemble_range_opts, filter_imports, inventory_pe_dir, list_artifacts,
+ list_tree, load_path, load_path_opts, process_attach, process_detach, process_launch,
+ process_list, process_modules, process_read, process_regions, process_resume, process_resolve,
+ recover_rtti, resolve_function, rtti_query, run_analyzers, scan_ascii_strings_bulk,
+ scan_printable_runs_gpu_or_fallback, scan_printable_runs_parallel, scan_printable_runs_seq,
+ time_bulk_printable, write_json_no_bom, xrefs_from, xrefs_to, xrefs_to_import,
+ xrefs_to_string_filter_opts, AnalysisBundle, BulkScanMode, LaunchRequest, Program, Project,
+ RttiMatchMode, StringCollectOpts, StringMatchMode, TreeListOpts, ANALYZER_NAMES,
+ DEFAULT_PREVIEW_LIMIT,
};
use ghidrust_decomp::decompile_entry;
use ghidrust_il2cpp::{
@@ -38,42 +43,53 @@ const PACKAGE_VERSION: &str = env!("CARGO_PKG_VERSION");
/// or required args change in a breaking way. Skill documents a minimum.
/// `3` = touch-map + body_class map + baseline build_skew + function_create.
/// `4` = bound-aware disasm + xref attribution + get_calls_from (+ surface 3).
-const TOOL_SURFACE_VERSION: u32 = 4;
+/// `5` = decode engine surface (decode_support, decode_query, extended disassemble).
+const TOOL_SURFACE_VERSION: u32 = 5;
fn package_version() -> &'static str {
PACKAGE_VERSION
}
fn server_info_json() -> Value {
+ let decode_block = mcp_decode::server_info_decode_section();
json!({
- "name": "ghidrust",
- "version": package_version(),
- "tool_surface": TOOL_SURFACE_VERSION,
- "features": [
- "live_process",
- "artifacts",
- "il2cpp",
- "inventory",
- "rtti_query",
- "list_tree",
- "decompile_stage1",
- "function_create",
- "il2cpp_touch_map",
- "bound_disasm",
- "get_calls_from"
- ],
- "live_process": {
- "tools": [
- "process_list",
- "process_attach",
- "process_detach",
- "process_modules",
- "process_read",
- "process_resolve",
- "process_regions"
+ "name": "ghidrust",
+ "version": package_version(),
+ "tool_surface": TOOL_SURFACE_VERSION,
+ "decode": decode_block["decode"],
+ "features": {
+ "surface": [
+ "live_process",
+ "artifacts",
+ "il2cpp",
+ "inventory",
+ "rtti_query",
+ "list_tree",
+ "decompile_stage1",
+ "function_create",
+ "il2cpp_touch_map",
+ "bound_disasm",
+ "get_calls_from",
+ "decode_support",
+ "decode_query"
],
- "session_model": "in_process_mcp",
- "note": "Attach sessions live in the long-lived MCP (or GUI) process. CLI one-shot `ghidrust process` cannot reuse session_id across separate spawns."
+ "decode_diet": decode_block["features"]["decode_diet"],
+ "x86_reduce": decode_block["features"]["x86_reduce"],
+ },
+ "live_process": {
+ "tools": [
+ "process_list",
+ "process_attach",
+ "process_launch",
+ "process_resume",
+ "process_detach",
+ "process_modules",
+ "process_read",
+ "process_resolve",
+ "process_regions"
+ ],
+ "session_model": "in_process_mcp",
+ "note": "Attach/launch sessions live in the long-lived MCP (or GUI) process. CLI one-shot `ghidrust process` cannot reuse session_id across separate spawns. Launch uses CREATE_SUSPENDED (not debug break-at-entry); call process_resume to run."
}
})
}
@@ -81,12 +97,12 @@ fn server_info_json() -> Value {
/// Structured escalation when offline `follow_stub` cannot yield a real method body.
fn live_process_next_steps() -> Value {
json!([
- "process_list",
- "process_attach",
- "process_modules",
- "process_resolve (module + method RVA from il2cpp_map)",
- "process_read",
- "optional process_regions / process_detach"
+ "process_list",
+ "process_attach",
+ "process_modules",
+ "process_resolve (module + method RVA from il2cpp_map)",
+ "process_read",
+ "optional process_regions / process_detach"
])
}
@@ -106,8 +122,8 @@ fn looks_like_trampoline(prog: &Program, target: u64) -> bool {
.iter()
.map(|i| i.mnemonic.to_ascii_lowercase())
.collect::<Vec<_>>()
- .join(" ");
- text.contains("jmp") || text.contains("ret") || insns.len() <= 3
+ .join(" ");
+ text.contains("jmp") || text.contains("ret") || insns.len() <= 3
} else {
false
}
@@ -122,24 +138,24 @@ fn build_follow_stub_meta(prog: &Program, from: u64, stub: &ResolveStub) -> (Opt
(
Some(target),
json!({
- "status": "trampoline_or_invoker",
- "from": format!("{from:#x}"),
- "to": format!("{target:#x}"),
- "slot_va": stub.slot_va.map(|s| format!("{s:#x}")),
- "icall_name": stub.icall_name,
- "note": "followed target looks like a trampoline/invoker — not a full managed body; use live process for runtime fields",
- "next_steps": live_process_next_steps(),
+ "status": "trampoline_or_invoker",
+ "from": format!("{from:#x}"),
+ "to": format!("{target:#x}"),
+ "slot_va": stub.slot_va.map(|s| format!("{s:#x}")),
+ "icall_name": stub.icall_name,
+ "note": "followed target looks like a trampoline/invoker — not a full managed body; use live process for runtime fields",
+ "next_steps": live_process_next_steps(),
}),
)
} else {
(
Some(target),
json!({
- "status": "resolved",
- "from": format!("{from:#x}"),
- "to": format!("{target:#x}"),
- "slot_va": stub.slot_va.map(|s| format!("{s:#x}")),
- "icall_name": stub.icall_name,
+ "status": "resolved",
+ "from": format!("{from:#x}"),
+ "to": format!("{target:#x}"),
+ "slot_va": stub.slot_va.map(|s| format!("{s:#x}")),
+ "icall_name": stub.icall_name,
}),
)
}
@@ -147,12 +163,12 @@ fn build_follow_stub_meta(prog: &Program, from: u64, stub: &ResolveStub) -> (Opt
(
None,
json!({
- "status": "runtime_unresolved",
- "from": format!("{from:#x}"),
- "slot_va": stub.slot_va.map(|s| format!("{s:#x}")),
- "icall_name": stub.icall_name,
- "note": "empty/runtime slot; offline follow_stub cannot yield method body",
- "next_steps": live_process_next_steps(),
+ "status": "runtime_unresolved",
+ "from": format!("{from:#x}"),
+ "slot_va": stub.slot_va.map(|s| format!("{s:#x}")),
+ "icall_name": stub.icall_name,
+ "note": "empty/runtime slot; offline follow_stub cannot yield method body",
+ "next_steps": live_process_next_steps(),
}),
)
}
@@ -164,35 +180,39 @@ fn main() -> ExitCode {
print_help();
return ExitCode::from(2);
}
- let json_mode = args.iter().any(|a| a == "--json");
- args.retain(|a| a != "--json");
+ // Accept GNU-style `--flag` as `-flag` (values unchanged).
+ args = decode_opts::normalize_cli_flags(&args);
+ let json_mode = args.iter().any(|a| a == "-json");
+ args.retain(|a| a != "-json");
match args[0].as_str() {
- "help" | "-h" | "--help" => {
+ "help" | "-h" | "-help" => {
print_help();
ExitCode::SUCCESS
}
- "version" | "--version" | "-V" => {
+ "version" | "-version" | "-V" => {
if json_mode {
println!(
- "{}",
+ "{}",
serde_json::to_string_pretty(&server_info_json()).unwrap()
);
} else {
- println!("ghidrust {}", package_version());
- println!("tool_surface={}", TOOL_SURFACE_VERSION);
+ println!("ghidrust {}", package_version());
+ println!("tool_surface={}", TOOL_SURFACE_VERSION);
}
ExitCode::SUCCESS
}
- "load" => cmd_load(&args[1..], json_mode),
- "disasm" | "disassemble" => cmd_disasm(&args[1..], json_mode),
- "bytes" | "dump" => cmd_bytes(&args[1..], json_mode),
- "rtti" => {
+ "load" => cmd_load(&args[1..], json_mode),
+ "disasm" | "disassemble" => disasm_cmd::cmd_disasm(&args[1..], json_mode),
+ "decode-support" => decode_support_cmd::cmd_decode_support(&args[1..], json_mode),
+ "decode-query" => decode_query_cmd::cmd_decode_query(&args[1..], json_mode),
+ "bytes" | "dump" => cmd_bytes(&args[1..], json_mode),
+ "rtti" => {
let rest = &args[1..];
if rest.iter().any(|a| {
- matches!(a.as_str(), "--filter" | "--name" | "--exact" | "query")
+ matches!(a.as_str(), "-filter" | "-name" | "-exact" | "query")
}) {
- let rest = if rest.first().map(|s| s.as_str()) == Some("query") {
+ let rest = if rest.first().map(|s| s.as_str()) == Some("query") {
&rest[1..]
} else {
rest
@@ -202,35 +222,35 @@ fn main() -> ExitCode {
cmd_rtti(rest, json_mode)
}
}
- "analyzers" => cmd_analyzers(json_mode),
- "analyze" => cmd_analyze(&args[1..], json_mode),
- "strings" => cmd_strings(&args[1..], json_mode),
- "xrefs" => cmd_xrefs(&args[1..], json_mode),
- "imports" => cmd_imports(&args[1..], json_mode),
- "function-at" => cmd_function_at(&args[1..], json_mode),
- "function" => cmd_function(&args[1..], json_mode),
- "il2cpp" => cmd_il2cpp(&args[1..], json_mode),
- "unity-inventory" => cmd_unity_inventory(&args[1..], json_mode),
- "inventory" | "pe-inventory" => friction::cmd_inventory(&args[1..], json_mode),
- "tree" | "list-tree" => friction::cmd_tree(&args[1..], json_mode),
- "artifact" => friction::cmd_artifact(&args[1..], json_mode),
- "process" => friction::cmd_process(&args[1..], json_mode),
- "bulk-bench" => cmd_bulk_bench(&args[1..], json_mode),
- "decompile" => cmd_decompile(&args[1..], json_mode),
- "decompile-bench" => cmd_decompile_bench(&args[1..], json_mode),
- "ghidra-headtohead" => cmd_ghidra_headtohead(&args[1..], json_mode),
- "gpu-decompile" => cmd_gpu_decompile(&args[1..], json_mode),
- "re-bench" => cmd_re_bench(&args[1..], json_mode),
- "analyzer-bench" => cmd_analyzer_bench(&args[1..], json_mode),
- "analyzer-bench-matrix" => {
- print!("{}", ghidrust_core::format_matrix_table());
+ "analyzers" => cmd_analyzers(json_mode),
+ "analyze" => cmd_analyze(&args[1..], json_mode),
+ "strings" => cmd_strings(&args[1..], json_mode),
+ "xrefs" => cmd_xrefs(&args[1..], json_mode),
+ "imports" => cmd_imports(&args[1..], json_mode),
+ "function-at" => cmd_function_at(&args[1..], json_mode),
+ "function" => cmd_function(&args[1..], json_mode),
+ "il2cpp" => cmd_il2cpp(&args[1..], json_mode),
+ "unity-inventory" => cmd_unity_inventory(&args[1..], json_mode),
+ "inventory" | "pe-inventory" => friction::cmd_inventory(&args[1..], json_mode),
+ "tree" | "list-tree" => friction::cmd_tree(&args[1..], json_mode),
+ "artifact" => friction::cmd_artifact(&args[1..], json_mode),
+ "process" => friction::cmd_process(&args[1..], json_mode),
+ "bulk-bench" => cmd_bulk_bench(&args[1..], json_mode),
+ "decompile" => cmd_decompile(&args[1..], json_mode),
+ "decompile-bench" => cmd_decompile_bench(&args[1..], json_mode),
+ "ghidra-headtohead" => cmd_ghidra_headtohead(&args[1..], json_mode),
+ "gpu-decompile" => cmd_gpu_decompile(&args[1..], json_mode),
+ "re-bench" => cmd_re_bench(&args[1..], json_mode),
+ "analyzer-bench" => cmd_analyzer_bench(&args[1..], json_mode),
+ "analyzer-bench-matrix" => {
+ print!("{}", ghidrust_core::format_matrix_table());
ExitCode::SUCCESS
}
- "rtti-gpu-bench" => cmd_rtti_gpu_bench(&args[1..], json_mode),
- "project" => cmd_project(&args[1..], json_mode),
- "mcp" => run_mcp_stdio(),
+ "rtti-gpu-bench" => cmd_rtti_gpu_bench(&args[1..], json_mode),
+ "project" => cmd_project(&args[1..], json_mode),
+ "mcp" => run_mcp_stdio(),
other => {
- eprintln!("unknown command: {other}");
+ eprintln!("unknown command: {other}");
print_help();
ExitCode::from(2)
}
@@ -239,12 +259,15 @@ fn main() -> ExitCode {
fn print_help() {
eprintln!(
- "ghidrust — AI-native reverse-engineering (CodeBrowser headless)\n\n\
+ "ghidrust — AI-native reverse-engineering (CodeBrowser headless)\n\n\
Usage:\n\
ghidrust version | --version | -V [--json]\n\
ghidrust load <path|--project DIR --file-id ID> [--out FILE] [--json]\n\
ghidrust disasm <path> [--addr <hex>] [--count N] [--skip-bad] [--linear|--flow]\n\
- [--out FILE] [--json]\n\
+ [--brief|--pretty] [--out FILE] [--json]\n\
+ (unknown/suspect bounds: --linear first; then function create; then --flow)\n\
+ ghidrust decode-support [--json]\n\
+ ghidrust decode-query --query NAME [--arch ARCH] [--id N] [--bytes HEX] [--json]\n\
ghidrust bytes <path> --addr HEX [--count N] [--out FILE] [--json]\n\
ghidrust strings <path> [--raw] [--encoding ascii|utf16|all] [--filter SUB]\n\
[--match substr|token|whole|glob] [--min N] [--limit N] [--out FILE] [--json]\n\
@@ -264,7 +287,7 @@ fn print_help() {
ghidrust inventory <dir> [--max-depth N] [--hash] [--out FILE] [--json]\n\
ghidrust tree <path> [--max-depth N] [--ext LIST] [--name GLOB] [--json]\n\
ghidrust artifact get|query|list <id> [--offset N] [--limit N] [--json]\n\
- ghidrust process list|attach|detach|modules|read|resolve|regions … [--json]\n\
+ ghidrust process list|attach|launch|resume|detach|modules|read|resolve|regions … [--json]\n\
ghidrust rtti <path> [--filter|--name|--exact] [--match MODE] [--json]\n\
ghidrust analyzers [--json]\n\
ghidrust analyze <path> [--analyzers a,b | --analyzer NAME ...] [--gpu] [--json]\n\
@@ -286,31 +309,31 @@ fn print_help() {
ghidrust project analyze <dir> [--file ID] [--analyzers a,b | --analyzer NAME ...] [--gpu]\n\
ghidrust project export <dir> [--file ID] # paths of saved listing/analysis\n\
ghidrust mcp\n\
- See README.md for projects, saving results, and analyzer list.\n"
+ See README.md for projects, saving results, and analyzer list.\n"
);
}
fn cmd_project(args: &[String], json: bool) -> ExitCode {
if args.is_empty() {
- eprintln!("project subcommand required: create|open|import|list|analyze|export");
+ eprintln!("project subcommand required: create|open|import|list|analyze|export");
return ExitCode::from(2);
}
match args[0].as_str() {
- "create" => {
+ "create" => {
let dir = match args.get(1) {
Some(d) => PathBuf::from(d),
None => {
- eprintln!("usage: ghidrust project create <dir> [--name NAME]");
+ eprintln!("usage: ghidrust project create <dir> [-name NAME]");
return ExitCode::from(2);
}
};
let mut name = dir
.file_name()
.map(|s| s.to_string_lossy().into_owned())
- .unwrap_or_else(|| "GhidrustProject".into());
+ .unwrap_or_else(|| "GhidrustProject".into());
let mut i = 2;
while i < args.len() {
- if args[i] == "--name" && i + 1 < args.len() {
+ if args[i] == "-name" && i + 1 < args.len() {
name = args[i + 1].clone();
i += 2;
} else {
@@ -321,43 +344,43 @@ fn cmd_project(args: &[String], json: bool) -> ExitCode {
Ok(p) => {
if json {
println!(
- "{}",
+ "{}",
serde_json::to_string_pretty(&p.meta).unwrap()
);
} else {
- println!("created project '{}' at {}", p.meta.name, p.root.display());
+ println!("created project '{}' at {}", p.meta.name, p.root.display());
}
ExitCode::SUCCESS
}
Err(e) => {
- eprintln!("error: {e}");
+ eprintln!("error: {e}");
ExitCode::FAILURE
}
}
}
- "open" | "list" => {
+ "open" | "list" => {
let dir = match args.get(1) {
Some(d) => PathBuf::from(d),
None => {
- eprintln!("usage: ghidrust project list <dir>");
+ eprintln!("usage: ghidrust project list <dir>");
return ExitCode::from(2);
}
};
match Project::open(&dir) {
Ok(p) => {
if json {
- println!("{}", serde_json::to_string_pretty(&p.meta).unwrap());
+ println!("{}", serde_json::to_string_pretty(&p.meta).unwrap());
} else {
- println!("project: {} ({})", p.meta.name, p.root.display());
- println!("files:");
+ println!("project: {} ({})", p.meta.name, p.root.display());
+ println!("files:");
for f in p.list_files() {
let mark = if p.meta.active_id.as_deref() == Some(&f.id) {
- "*"
+ "*"
} else {
- " "
+ " "
};
println!(
- " {mark} id={} {} ({})",
+ " {mark} id={} {} ({})",
f.id, f.display_name, f.imported_rel
);
}
@@ -365,14 +388,14 @@ fn cmd_project(args: &[String], json: bool) -> ExitCode {
ExitCode::SUCCESS
}
Err(e) => {
- eprintln!("error: {e}");
+ eprintln!("error: {e}");
ExitCode::FAILURE
}
}
}
- "import" => {
+ "import" => {
if args.len() < 3 {
- eprintln!("usage: ghidrust project import <project-dir> <binary>");
+ eprintln!("usage: ghidrust project import <project-dir> <binary>");
return ExitCode::from(2);
}
let dir = PathBuf::from(&args[1]);
@@ -383,10 +406,10 @@ fn cmd_project(args: &[String], json: bool) -> ExitCode {
}) {
Ok((p, e)) => {
if json {
- println!("{}", serde_json::to_string_pretty(&e).unwrap());
+ println!("{}", serde_json::to_string_pretty(&e).unwrap());
} else {
println!(
- "imported {} as id={} -> {}",
+ "imported {} as id={} -> {}",
e.display_name,
e.id,
p.binary_path(&e).display()
@@ -395,15 +418,15 @@ fn cmd_project(args: &[String], json: bool) -> ExitCode {
ExitCode::SUCCESS
}
Err(e) => {
- eprintln!("error: {e}");
+ eprintln!("error: {e}");
ExitCode::FAILURE
}
}
}
- "analyze" => {
+ "analyze" => {
if args.len() < 2 {
eprintln!(
- "usage: ghidrust project analyze <dir> [--file ID] [--analyzers a,b | --analyzer NAME ...] [--gpu]"
+ "usage: ghidrust project analyze <dir> [-file ID] [-analyzers a,b | -analyzer NAME ..] [-gpu]"
);
return ExitCode::from(2);
}
@@ -414,12 +437,12 @@ fn cmd_project(args: &[String], json: bool) -> ExitCode {
let mut i = 2;
while i < args.len() {
match args[i].as_str() {
- "--file" if i + 1 < args.len() => {
+ "-file" if i + 1 < args.len() => {
file_id = Some(args[i + 1].clone());
i += 2;
}
- "--analyzers" if i + 1 < args.len() => {
- for s in args[i + 1].split(',') {
+ "-analyzers" if i + 1 < args.len() => {
+ for s in args[i + 1].split(',') {
let t = s.trim();
if !t.is_empty() {
analyzers.push(t.to_string());
@@ -427,11 +450,11 @@ fn cmd_project(args: &[String], json: bool) -> ExitCode {
}
i += 2;
}
- "--analyzer" if i + 1 < args.len() => {
+ "-analyzer" if i + 1 < args.len() => {
analyzers.push(args[i + 1].clone());
i += 2;
}
- "--gpu" => {
+ "-gpu" => {
use_gpu = true;
i += 1;
}
@@ -446,7 +469,7 @@ fn cmd_project(args: &[String], json: bool) -> ExitCode {
p.active_file().cloned().or_else(|| p.meta.files.first().cloned())
};
let Some(entry) = entry else {
- eprintln!("no files in project — import a binary first");
+ eprintln!("no files in project — import a binary first");
return ExitCode::FAILURE;
};
let names: Vec<&str> = if analyzers.is_empty() {
@@ -457,42 +480,42 @@ fn cmd_project(args: &[String], json: bool) -> ExitCode {
match p.analyze_file_opts(&entry, &names, use_gpu) {
Ok((_prog, saved)) => {
if json {
- println!("{}", serde_json::to_string_pretty(&saved).unwrap());
+ println!("{}", serde_json::to_string_pretty(&saved).unwrap());
} else {
println!(
- "analyzed {} — {} functions, {} listing lines",
+ "analyzed {} — {} functions, {} listing lines",
entry.display_name,
saved.analysis.functions.len(),
saved.listing.len()
);
- println!("results: {}", p.analysis_path(&entry.id).display());
- println!("listing: {}", p.listing_export_path(&entry.id).display());
- println!("export: {}", p.analysis_export_path(&entry.id).display());
+ println!("results: {}", p.analysis_path(&entry.id).display());
+ println!("listing: {}", p.listing_export_path(&entry.id).display());
+ println!("export: {}", p.analysis_export_path(&entry.id).display());
}
ExitCode::SUCCESS
}
Err(e) => {
- eprintln!("error: {e}");
+ eprintln!("error: {e}");
ExitCode::FAILURE
}
}
}
Err(e) => {
- eprintln!("error: {e}");
+ eprintln!("error: {e}");
ExitCode::FAILURE
}
}
}
- "export" => {
+ "export" => {
if args.len() < 2 {
- eprintln!("usage: ghidrust project export <dir> [--file ID]");
+ eprintln!("usage: ghidrust project export <dir> [-file ID]");
return ExitCode::from(2);
}
let dir = PathBuf::from(&args[1]);
let mut file_id: Option<String> = None;
let mut i = 2;
while i < args.len() {
- if args[i] == "--file" && i + 1 < args.len() {
+ if args[i] == "-file" && i + 1 < args.len() {
file_id = Some(args[i + 1].clone());
i += 2;
} else {
@@ -507,7 +530,7 @@ fn cmd_project(args: &[String], json: bool) -> ExitCode {
p.active_file().or_else(|| p.meta.files.first())
};
let Some(entry) = entry else {
- eprintln!("no files");
+ eprintln!("no files");
return ExitCode::FAILURE;
};
let a = p.analysis_path(&entry.id);
@@ -515,29 +538,29 @@ fn cmd_project(args: &[String], json: bool) -> ExitCode {
let e = p.analysis_export_path(&entry.id);
if json {
println!(
- "{}",
+ "{}",
json!({
- "analysis": a.display().to_string(),
- "listing": l.display().to_string(),
- "export": e.display().to_string(),
- "exists": a.is_file(),
+ "analysis": a.display().to_string(),
+ "listing": l.display().to_string(),
+ "export": e.display().to_string(),
+ "exists": a.is_file(),
})
);
} else {
- println!("analysis: {} ({})", a.display(), if a.is_file() { "ok" } else { "missing — run project analyze" });
- println!("listing: {} ({})", l.display(), if l.is_file() { "ok" } else { "missing" });
- println!("export: {} ({})", e.display(), if e.is_file() { "ok" } else { "missing" });
+ println!("analysis: {} ({})", a.display(), if a.is_file() { "ok" } else { "missing — run project analyze" });
+ println!("listing: {} ({})", l.display(), if l.is_file() { "ok" } else { "missing" });
+ println!("export: {} ({})", e.display(), if e.is_file() { "ok" } else { "missing" });
}
ExitCode::SUCCESS
}
Err(e) => {
- eprintln!("error: {e}");
+ eprintln!("error: {e}");
ExitCode::FAILURE
}
}
}
other => {
- eprintln!("unknown project subcommand: {other}");
+ eprintln!("unknown project subcommand: {other}");
ExitCode::from(2)
}
}
@@ -546,26 +569,26 @@ fn cmd_project(args: &[String], json: bool) -> ExitCode {
fn path_arg(args: &[String]) -> Result<PathBuf, String> {
args.first()
.map(PathBuf::from)
- .ok_or_else(|| "missing path".into())
+ .ok_or_else(|| "missing path".into())
}
fn cmd_load(args: &[String], json: bool) -> ExitCode {
let (path, identity) = match friction::resolve_program_path(args) {
Ok(v) => v,
Err(e) => {
- // Fall back to positional path for backward compatibility.
+ // Fall back to positional path for backward compatibility.
match path_arg(args) {
Ok(p) => (
p.clone(),
json!({
- "path": p.display().to_string(),
- "project": Value::Null,
- "file_id": Value::Null,
- "resolved_path": p.display().to_string(),
+ "path": p.display().to_string(),
+ "project": Value::Null,
+ "file_id": Value::Null,
+ "resolved_path": p.display().to_string(),
}),
),
Err(_) => {
- eprintln!("{e}");
+ eprintln!("{e}");
return ExitCode::from(2);
}
}
@@ -575,7 +598,7 @@ fn cmd_load(args: &[String], json: bool) -> ExitCode {
let mut i = 0;
while i < args.len() {
match args[i].as_str() {
- "--out" if i + 1 < args.len() => {
+ "-out" if i + 1 < args.len() => {
out_path = Some(PathBuf::from(&args[i + 1]));
i += 2;
}
@@ -588,33 +611,33 @@ fn cmd_load(args: &[String], json: bool) -> ExitCode {
emit_result(&v, json, out_path.as_deref(), || print_program_summary(&prog))
}
Err(e) => {
- eprintln!("error: {e}");
+ eprintln!("error: {e}");
ExitCode::FAILURE
}
}
}
fn print_program_summary(prog: &Program) {
- println!("name: {}", prog.name);
- println!("format: {}", prog.format);
- println!("base: {:#x}", prog.image_base);
+ println!("name: {}", prog.name);
+ println!("format: {}", prog.format);
+ println!("base: {:#x}", prog.image_base);
if let Some(e) = prog.entry {
- println!("entry: {e:#x}");
+ println!("entry: {e:#x}");
}
- println!("sections:");
+ println!("sections:");
for s in &prog.sections {
println!(
- " {:8} va={:#x} vsize={:#x} raw={:#x}",
+ " {:8} va={:#x} vsize={:#x} raw={:#x}",
s.name, s.va, s.virtual_size, s.raw_size
);
}
}
fn emit_json<T: Serialize>(value: &T) {
- // UTF-8 without BOM — suitable for piping / PowerShell ConvertFrom-Json.
+ // UTF-8 without BOM — suitable for piping / PowerShell ConvertFrom-Json.
let mut out = io::stdout().lock();
if let Err(e) = serde_json::to_writer_pretty(&mut out, value) {
- eprintln!("json write error: {e}");
+ eprintln!("json write error: {e}");
return;
}
let _ = writeln!(out);
@@ -622,7 +645,7 @@ fn emit_json<T: Serialize>(value: &T) {
fn emit_json_to_path<T: Serialize>(path: &Path, value: &T) -> bool {
if let Err(e) = write_json_no_bom(path, value) {
- eprintln!("error writing {}: {e}", path.display());
+ eprintln!("error writing {}: {e}", path.display());
return false;
}
true
@@ -634,7 +657,7 @@ fn emit_result<T: Serialize>(value: &T, json: bool, out_path: Option<&Path>, tex
return ExitCode::FAILURE;
}
if !json {
- eprintln!("wrote {}", p.display());
+ eprintln!("wrote {}", p.display());
}
return ExitCode::SUCCESS;
}
@@ -646,115 +669,24 @@ fn emit_result<T: Serialize>(value: &T, json: bool, out_path: Option<&Path>, tex
ExitCode::SUCCESS
}
-fn cmd_disasm(args: &[String], json: bool) -> ExitCode {
- let path = match path_arg(args) {
- Ok(p) => p,
- Err(e) => {
- eprintln!("{e}");
- return ExitCode::from(2);
- }
- };
- let mut addr: Option<u64> = None;
- let mut count: usize = 16;
- let mut skip_bad = false;
- let mut force_linear = false;
- let mut force_flow = false;
- let mut out_path: Option<PathBuf> = None;
- let mut i = 1;
- while i < args.len() {
- match args[i].as_str() {
- "--addr" if i + 1 < args.len() => {
- addr = parse_u64(&args[i + 1]).ok();
- i += 2;
- }
- "--count" if i + 1 < args.len() => {
- count = args[i + 1].parse().unwrap_or(16);
- i += 2;
- }
- "--skip-bad" => {
- skip_bad = true;
- i += 1;
- }
- "--linear" => {
- force_linear = true;
- i += 1;
- }
- "--flow" => {
- force_flow = true;
- i += 1;
- }
- "--out" if i + 1 < args.len() => {
- out_path = Some(PathBuf::from(&args[i + 1]));
- i += 2;
- }
- _ => i += 1,
- }
- }
- match load_path(&path) {
- Ok(mut prog) => {
- let start = addr.or(prog.entry).unwrap_or(prog.image_base);
- let (mode, bound_end) = if force_linear {
- (DisasmMode::Linear, None)
- } else if force_flow {
- let bound = resolve_function(&mut prog, start)
- .ok()
- .filter(|r| r.ok)
- .and_then(|r| r.function_end);
- (DisasmMode::Flow, bound)
- } else {
- // Default: bounded when a containing function is known.
- match resolve_function(&mut prog, start) {
- Ok(r) if r.ok => (DisasmMode::Bounded, r.function_end),
- _ => (DisasmMode::Linear, None),
- }
- };
- match disassemble_range_ex(&prog, start, count, skip_bad, mode, bound_end) {
- Ok(result) => {
- if json {
- let body = json!({
- "insns": result.insns,
- "decode_gaps": result.decode_gaps,
- "first_gap_va": result.first_gap_va.map(|v| format!("{v:#x}")),
- "stop_reason": result.stop_reason,
- "mode": mode,
- "entry": result.entry.map(|v| format!("{v:#x}")),
- "end": result.end.map(|v| format!("{v:#x}")),
- });
- emit_result(&body, true, out_path.as_deref(), || {})
- } else {
- emit_result(&result.insns, false, out_path.as_deref(), || {
- for insn in &result.insns {
- println!("{}", insn.text());
- }
- if result.decode_gaps > 0 {
- println!(
- "; decode_gaps={} first_gap={:?}",
- result.decode_gaps,
- result.first_gap_va.map(|v| format!("{v:#x}"))
- );
- }
- println!("; stop_reason={:?} mode={:?}", result.stop_reason, mode);
- })
- }
- }
- Err(e) => {
- eprintln!("error: {e}");
- ExitCode::FAILURE
- }
- }
- }
- Err(e) => {
- eprintln!("error: {e}");
- ExitCode::FAILURE
- }
- }
+pub(crate) fn emit_json_helper<T: Serialize>(value: &T) {
+ emit_json(value);
+}
+
+pub(crate) fn emit_result_helper<T: Serialize>(
+ value: &T,
+ json: bool,
+ out_path: Option<&Path>,
+ text: impl FnOnce(),
+) -> ExitCode {
+ emit_result(value, json, out_path, text)
}
fn cmd_bytes(args: &[String], json: bool) -> ExitCode {
let path = match path_arg(args) {
Ok(p) => p,
Err(e) => {
- eprintln!("{e}");
+ eprintln!("{e}");
return ExitCode::from(2);
}
};
@@ -764,15 +696,15 @@ fn cmd_bytes(args: &[String], json: bool) -> ExitCode {
let mut i = 1;
while i < args.len() {
match args[i].as_str() {
- "--addr" if i + 1 < args.len() => {
+ "-addr" if i + 1 < args.len() => {
addr = parse_u64(&args[i + 1]).ok();
i += 2;
}
- "--count" if i + 1 < args.len() => {
+ "-count" if i + 1 < args.len() => {
count = args[i + 1].parse().unwrap_or(64).clamp(1, 1_048_576);
i += 2;
}
- "--out" if i + 1 < args.len() => {
+ "-out" if i + 1 < args.len() => {
out_path = Some(PathBuf::from(&args[i + 1]));
i += 2;
}
@@ -780,7 +712,7 @@ fn cmd_bytes(args: &[String], json: bool) -> ExitCode {
}
}
let Some(addr) = addr else {
- eprintln!("usage: ghidrust bytes <path> --addr HEX [--count N] [--out FILE] [--json]");
+ eprintln!("usage: ghidrust bytes <path> -addr HEX [-count N] [-out FILE] [-json]");
return ExitCode::from(2);
};
match load_path(&path) {
@@ -788,47 +720,47 @@ fn cmd_bytes(args: &[String], json: bool) -> ExitCode {
Some(bytes) => {
let hex: String = bytes
.iter()
- .map(|b| format!("{b:02x}"))
+ .map(|b| format!("{b:02x}"))
.collect::<Vec<_>>()
- .join(" ");
+ .join(" ");
let payload = json!({
- "addr": format!("{addr:#x}"),
- "count": bytes.len(),
- "hex": hex,
- "bytes": bytes,
+ "addr": format!("{addr:#x}"),
+ "count": bytes.len(),
+ "hex": hex,
+ "bytes": bytes,
});
emit_result(&payload, json, out_path.as_deref(), || {
- // 16-byte rows: hex + ASCII
+ // 16-byte rows: hex + ASCII
let mut off = 0usize;
while off < bytes.len() {
let row = &bytes[off..(off + 16).min(bytes.len())];
let hex_row: String = row
.iter()
- .map(|b| format!("{b:02x}"))
+ .map(|b| format!("{b:02x}"))
.collect::<Vec<_>>()
- .join(" ");
+ .join(" ");
let ascii: String = row
.iter()
.map(|&b| {
if (0x20..=0x7e).contains(&b) {
b as char
} else {
- '.'
+ '.'
}
})
.collect();
- println!("{:#x}: {:<47} {}", addr + off as u64, hex_row, ascii);
+ println!("{:#x}: {:<47} {}", addr + off as u64, hex_row, ascii);
off += 16;
}
})
}
None => {
- eprintln!("error: address {addr:#x} not mapped or unreadable");
+ eprintln!("error: address {addr:#x} not mapped or unreadable");
ExitCode::FAILURE
}
},
Err(e) => {
- eprintln!("error: {e}");
+ eprintln!("error: {e}");
ExitCode::FAILURE
}
}
@@ -838,11 +770,11 @@ fn cmd_strings(args: &[String], json: bool) -> ExitCode {
let path = match path_arg(args) {
Ok(p) => p,
Err(e) => {
- eprintln!("{e}");
+ eprintln!("{e}");
return ExitCode::from(2);
}
};
- let mut encoding = "all".to_string();
+ let mut encoding = "all".to_string();
let mut filter: Option<String> = None;
let mut min_len: usize = 4;
let mut match_mode = StringMatchMode::Substr;
@@ -852,47 +784,47 @@ fn cmd_strings(args: &[String], json: bool) -> ExitCode {
let mut i = 1;
while i < args.len() {
match args[i].as_str() {
- "--encoding" if i + 1 < args.len() => {
+ "-encoding" if i + 1 < args.len() => {
encoding = args[i + 1].clone();
i += 2;
}
- "--filter" | "--contains" if i + 1 < args.len() => {
+ "-filter" | "-contains" if i + 1 < args.len() => {
filter = Some(args[i + 1].clone());
i += 2;
}
- "--match" if i + 1 < args.len() => {
+ "-match" if i + 1 < args.len() => {
match StringMatchMode::parse(&args[i + 1]) {
Ok(m) => match_mode = m,
Err(e) => {
- eprintln!("{e}");
+ eprintln!("{e}");
return ExitCode::from(2);
}
}
i += 2;
}
- "--min" if i + 1 < args.len() => {
+ "-min" if i + 1 < args.len() => {
min_len = args[i + 1].parse().unwrap_or(4);
i += 2;
}
- "--limit" if i + 1 < args.len() => {
+ "-limit" if i + 1 < args.len() => {
limit = args[i + 1].parse().ok();
i += 2;
}
- "--out" if i + 1 < args.len() => {
+ "-out" if i + 1 < args.len() => {
out_path = Some(PathBuf::from(&args[i + 1]));
i += 2;
}
- "--raw" => {
+ "-raw" => {
raw = true;
i += 1;
}
_ => i += 1,
}
}
- // Auto-glob when wildcards present and user left default substr.
+ // Auto-glob when wildcards present and user left default substr.
if matches!(match_mode, StringMatchMode::Substr) {
if let Some(pat) = &filter {
- if pat.contains('*') || pat.contains('?') {
+ if pat.contains('*') || pat.contains('?') {
match_mode = StringMatchMode::Glob;
}
}
@@ -908,7 +840,7 @@ fn cmd_strings(args: &[String], json: bool) -> ExitCode {
match std::fs::read(&path) {
Ok(bytes) => collect_strings_bytes(&bytes, 0, &opts),
Err(e) => {
- eprintln!("error: {e}");
+ eprintln!("error: {e}");
return ExitCode::FAILURE;
}
}
@@ -918,11 +850,11 @@ fn cmd_strings(args: &[String], json: bool) -> ExitCode {
match strings {
Ok(strings) => emit_result(&strings, json, out_path.as_deref(), || {
for s in &strings {
- println!("{:#x}\t{}\t{}", s.va, s.encoding, s.value);
+ println!("{:#x}\t{}\t{}", s.va, s.encoding, s.value);
}
}),
Err(e) => {
- eprintln!("error: {e}");
+ eprintln!("error: {e}");
ExitCode::FAILURE
}
}
@@ -932,7 +864,7 @@ fn cmd_xrefs(args: &[String], json: bool) -> ExitCode {
let path = match path_arg(args) {
Ok(p) => p,
Err(e) => {
- eprintln!("{e}");
+ eprintln!("{e}");
return ExitCode::from(2);
}
};
@@ -943,44 +875,44 @@ fn cmd_xrefs(args: &[String], json: bool) -> ExitCode {
let mut import_name: Option<String> = None;
let mut skip_stubs = false;
let mut classify = false;
- let mut encoding = "all".to_string();
+ let mut encoding = "all".to_string();
let mut out_path: Option<PathBuf> = None;
let mut i = 1;
while i < args.len() {
match args[i].as_str() {
- "--to" if i + 1 < args.len() => {
+ "-to" if i + 1 < args.len() => {
to = parse_u64(&args[i + 1]).ok();
i += 2;
}
- "--from" if i + 1 < args.len() => {
+ "-from" if i + 1 < args.len() => {
from = parse_u64(&args[i + 1]).ok();
i += 2;
}
- "--calls" if i + 1 < args.len() => {
+ "-calls" if i + 1 < args.len() => {
calls = parse_u64(&args[i + 1]).ok();
i += 2;
}
- "--string" if i + 1 < args.len() => {
+ "-string" if i + 1 < args.len() => {
string_filter = Some(args[i + 1].clone());
i += 2;
}
- "--import" if i + 1 < args.len() => {
+ "-import" if i + 1 < args.len() => {
import_name = Some(args[i + 1].clone());
i += 2;
}
- "--encoding" if i + 1 < args.len() => {
+ "-encoding" if i + 1 < args.len() => {
encoding = args[i + 1].clone();
i += 2;
}
- "--skip-stubs" => {
+ "-skip-stubs" => {
skip_stubs = true;
i += 1;
}
- "--classify" => {
+ "-classify" => {
classify = true;
i += 1;
}
- "--out" if i + 1 < args.len() => {
+ "-out" if i + 1 < args.len() => {
out_path = Some(PathBuf::from(&args[i + 1]));
i += 2;
}
@@ -999,14 +931,14 @@ fn cmd_xrefs(args: &[String], json: bool) -> ExitCode {
.count();
if modes != 1 {
eprintln!(
- "usage: ghidrust xrefs <path> (--to HEX | --from HEX | --string FILTER | --import NAME | --calls HEX) [--encoding ascii|utf16le|all] [--skip-stubs] [--classify] [--out FILE] [--json]"
+ "usage: ghidrust xrefs <path> (-to HEX | -from HEX | -string FILTER | -import NAME | -calls HEX) [-encoding ascii|utf16le|all] [-skip-stubs] [-classify] [-out FILE] [-json]"
);
return ExitCode::from(2);
}
match load_path(&path) {
Ok(mut prog) => {
if let Some(entry) = calls {
- let _ = run_analyzers(&mut prog, &["Function Start Search"]);
+ let _ = run_analyzers(&mut prog, &["Function Start Search"]);
let entry = resolve_function(&mut prog, entry)
.ok()
.and_then(|r| r.resolved_entry)
@@ -1016,22 +948,22 @@ fn cmd_xrefs(args: &[String], json: bool) -> ExitCode {
.iter()
.map(|e| {
json!({
- "from": format!("{:#x}", e.from),
- "to": format!("{:#x}", e.to),
- "kind": e.kind,
- "to_entry": e.to_entry.map(|v| format!("{v:#x}")),
- "to_function": e.to_function,
+ "from": format!("{:#x}", e.from),
+ "to": format!("{:#x}", e.to),
+ "kind": e.kind,
+ "to_entry": e.to_entry.map(|v| format!("{v:#x}")),
+ "to_function": e.to_function,
})
})
.collect();
return emit_result(&rows, json, out_path.as_deref(), || {
for r in &rows {
println!(
- "{} -> {} [{}] to_entry={}",
- r["from"].as_str().unwrap_or("?"),
- r["to"].as_str().unwrap_or("?"),
- r["kind"].as_str().unwrap_or("?"),
- r["to_entry"].as_str().unwrap_or("-")
+ "{} -> {} [{}] to_entry={}",
+ r["from"].as_str().unwrap_or("?"),
+ r["to"].as_str().unwrap_or("?"),
+ r["kind"].as_str().unwrap_or("?"),
+ r["to_entry"].as_str().unwrap_or("-")
);
}
});
@@ -1052,17 +984,17 @@ fn cmd_xrefs(args: &[String], json: bool) -> ExitCode {
emit_result(&rows, json, out_path.as_deref(), || {
for r in &rows {
println!(
- "{} -> {} [{}] {}",
- r["from"].as_str().unwrap_or("?"),
- r["to"].as_str().unwrap_or("?"),
- r["kind"].as_str().unwrap_or("?"),
- r["preview"].as_str().unwrap_or("")
+ "{} -> {} [{}] {}",
+ r["from"].as_str().unwrap_or("?"),
+ r["to"].as_str().unwrap_or("?"),
+ r["kind"].as_str().unwrap_or("?"),
+ r["preview"].as_str().unwrap_or("")
);
}
})
}
Err(e) => {
- eprintln!("error: {e}");
+ eprintln!("error: {e}");
ExitCode::FAILURE
}
}
@@ -1072,18 +1004,18 @@ fn cmd_il2cpp(args: &[String], json: bool) -> ExitCode {
let sub = match args.first().map(|s| s.as_str()) {
Some(s) => s,
None => {
- eprintln!("usage: ghidrust il2cpp meta|map|touch-map|stubs|icalls ...");
+ eprintln!("usage: ghidrust il2cpp meta|map|touch-map|stubs|icalls ..");
return ExitCode::from(2);
}
};
match sub {
- "meta" => cmd_il2cpp_meta(&args[1..], json),
- "map" => cmd_il2cpp_map(&args[1..], json),
- "touch-map" => cmd_il2cpp_touch_map(&args[1..], json),
- "stubs" => cmd_il2cpp_stubs(&args[1..], json),
- "icalls" => cmd_il2cpp_icalls(&args[1..], json),
+ "meta" => cmd_il2cpp_meta(&args[1..], json),
+ "map" => cmd_il2cpp_map(&args[1..], json),
+ "touch-map" => cmd_il2cpp_touch_map(&args[1..], json),
+ "stubs" => cmd_il2cpp_stubs(&args[1..], json),
+ "icalls" => cmd_il2cpp_icalls(&args[1..], json),
other => {
- eprintln!("unknown il2cpp subcommand: {other}");
+ eprintln!("unknown il2cpp subcommand: {other}");
ExitCode::from(2)
}
}
@@ -1096,19 +1028,19 @@ fn cmd_il2cpp_icalls(args: &[String], json: bool) -> ExitCode {
let mut i = 0;
while i < args.len() {
match args[i].as_str() {
- "--binary" if i + 1 < args.len() => {
+ "-binary" if i + 1 < args.len() => {
binary = Some(PathBuf::from(&args[i + 1]));
i += 2;
}
- "--filter" if i + 1 < args.len() => {
+ "-filter" if i + 1 < args.len() => {
filter = Some(args[i + 1].clone());
i += 2;
}
- "--out" if i + 1 < args.len() => {
+ "-out" if i + 1 < args.len() => {
out_path = Some(PathBuf::from(&args[i + 1]));
i += 2;
}
- other if binary.is_none() && !other.starts_with('-') => {
+ other if binary.is_none() && !other.starts_with('-') => {
binary = Some(PathBuf::from(other));
i += 1;
}
@@ -1117,7 +1049,7 @@ fn cmd_il2cpp_icalls(args: &[String], json: bool) -> ExitCode {
}
let Some(binary) = binary else {
eprintln!(
- "usage: ghidrust il2cpp icalls --binary <engine.dll> [--filter SUB] [--out FILE] [--json]"
+ "usage: ghidrust il2cpp icalls -binary <engine.dll> [-filter SUB] [-out FILE] [-json]"
);
return ExitCode::from(2);
};
@@ -1126,62 +1058,62 @@ fn cmd_il2cpp_icalls(args: &[String], json: bool) -> ExitCode {
let payload = if let Some(f) = &filter {
let hits = filter_entries(&report, f);
json!({
- "filter": f,
- "table_count": report.tables.len(),
- "hit_count": hits.len(),
- "hits": hits.iter().map(|(ti, e)| json!({
- "table_index": ti,
- "index": e.index,
- "name": e.name,
- "name_string_va": format!("{:#x}", e.name_string_va),
- "fn_va": format!("{:#x}", e.fn_va),
- "fn_rva": format!("{:#x}", e.fn_rva),
+ "filter": f,
+ "table_count": report.tables.len(),
+ "hit_count": hits.len(),
+ "hits": hits.iter().map(|(ti, e)| json!({
+ "table_index": ti,
+ "index": e.index,
+ "name": e.name,
+ "name_string_va": format!("{:#x}", e.name_string_va),
+ "fn_va": format!("{:#x}", e.fn_va),
+ "fn_rva": format!("{:#x}", e.fn_rva),
})).collect::<Vec<_>>(),
- "tables": report.tables.iter().map(|t| json!({
- "name_va": format!("{:#x}", t.name_va),
- "fn_va": format!("{:#x}", t.fn_va),
- "count": t.count,
- "layout": t.layout,
- "confidence": t.confidence,
+ "tables": report.tables.iter().map(|t| json!({
+ "name_va": format!("{:#x}", t.name_va),
+ "fn_va": format!("{:#x}", t.fn_va),
+ "count": t.count,
+ "layout": t.layout,
+ "confidence": t.confidence,
})).collect::<Vec<_>>(),
})
} else {
json!({
- "table_count": report.tables.len(),
- "tables": report.tables.iter().map(|t| json!({
- "name_va": format!("{:#x}", t.name_va),
- "fn_va": format!("{:#x}", t.fn_va),
- "count": t.count,
- "layout": t.layout,
- "confidence": t.confidence,
- "entries": t.entries.iter().take(64).map(|e| json!({
- "index": e.index,
- "name": e.name,
- "name_string_va": format!("{:#x}", e.name_string_va),
- "fn_va": format!("{:#x}", e.fn_va),
- "fn_rva": format!("{:#x}", e.fn_rva),
+ "table_count": report.tables.len(),
+ "tables": report.tables.iter().map(|t| json!({
+ "name_va": format!("{:#x}", t.name_va),
+ "fn_va": format!("{:#x}", t.fn_va),
+ "count": t.count,
+ "layout": t.layout,
+ "confidence": t.confidence,
+ "entries": t.entries.iter().take(64).map(|e| json!({
+ "index": e.index,
+ "name": e.name,
+ "name_string_va": format!("{:#x}", e.name_string_va),
+ "fn_va": format!("{:#x}", e.fn_va),
+ "fn_rva": format!("{:#x}", e.fn_rva),
})).collect::<Vec<_>>(),
})).collect::<Vec<_>>(),
})
};
emit_result(&payload, json, out_path.as_deref(), || {
println!(
- "icall tables: {} (engine {})",
+ "icall tables: {} (engine {})",
report.tables.len(),
binary.display()
);
for t in report.tables.iter().take(8) {
println!(
- " names {:#x} fns {:#x} count={} conf={:.2} {:?}",
+ " names {:#x} fns {:#x} count={} conf={:.2} {:?}",
t.name_va, t.fn_va, t.count, t.confidence, t.layout
);
}
if let Some(f) = &filter {
let hits = filter_entries(&report, f);
- println!("filter {:?} hits: {}", f, hits.len());
+ println!("filter {:?} hits: {}", f, hits.len());
for (_ti, e) in hits.iter().take(40) {
println!(
- " [{}] RVA {:#x} {}",
+ " [{}] RVA {:#x} {}",
e.index, e.fn_rva, e.name
);
}
@@ -1189,7 +1121,7 @@ fn cmd_il2cpp_icalls(args: &[String], json: bool) -> ExitCode {
})
}
Err(e) => {
- eprintln!("error: {e}");
+ eprintln!("error: {e}");
ExitCode::FAILURE
}
}
@@ -1199,7 +1131,7 @@ fn cmd_il2cpp_meta(args: &[String], json: bool) -> ExitCode {
let path = match args.first() {
Some(p) => PathBuf::from(p),
None => {
- eprintln!("usage: ghidrust il2cpp meta <metadata.dat> [--filter SUB] [--out FILE] [--json]");
+ eprintln!("usage: ghidrust il2cpp meta <metadata.dat> [-filter SUB] [-out FILE] [-json]");
return ExitCode::from(2);
}
};
@@ -1208,11 +1140,11 @@ fn cmd_il2cpp_meta(args: &[String], json: bool) -> ExitCode {
let mut i = 1;
while i < args.len() {
match args[i].as_str() {
- "--filter" if i + 1 < args.len() => {
+ "-filter" if i + 1 < args.len() => {
filter = Some(args[i + 1].clone());
i += 2;
}
- "--out" if i + 1 < args.len() => {
+ "-out" if i + 1 < args.len() => {
out_path = Some(PathBuf::from(&args[i + 1]));
i += 2;
}
@@ -1231,10 +1163,10 @@ fn cmd_il2cpp_meta(args: &[String], json: bool) -> ExitCode {
.into_iter()
.map(|m| {
json!({
- "index": m.index,
- "name": m.name,
- "full_name": meta.method_full_name(m),
- "token": m.token,
+ "index": m.index,
+ "name": m.name,
+ "full_name": meta.method_full_name(m),
+ "token": m.token,
})
})
.collect(),
@@ -1243,31 +1175,31 @@ fn cmd_il2cpp_meta(args: &[String], json: bool) -> ExitCode {
.iter()
.map(|m| {
json!({
- "index": m.index,
- "name": m.name,
- "full_name": meta.method_full_name(m),
- "token": m.token,
+ "index": m.index,
+ "name": m.name,
+ "full_name": meta.method_full_name(m),
+ "token": m.token,
})
})
.collect(),
};
let report = json!({
- "version": meta.header.version,
- "dialect": meta.header.dialect,
- "type_count": meta.types.len(),
- "method_count": meta.methods.len(),
- "image_count": meta.images.len(),
- "types": types.iter().map(|t| json!({
- "index": t.index,
- "full_name": t.full_name(),
- "method_count": t.method_count,
- "token": t.token,
+ "version": meta.header.version,
+ "dialect": meta.header.dialect,
+ "type_count": meta.types.len(),
+ "method_count": meta.methods.len(),
+ "image_count": meta.images.len(),
+ "types": types.iter().map(|t| json!({
+ "index": t.index,
+ "full_name": t.full_name(),
+ "method_count": t.method_count,
+ "token": t.token,
})).collect::<Vec<_>>(),
- "methods": methods,
+ "methods": methods,
});
emit_result(&report, json, out_path.as_deref(), || {
println!(
- "IL2CPP metadata v{} {:?} — {} types, {} methods, {} images",
+ "IL2CPP metadata v{} {:?} — {} types, {} methods, {} images",
meta.header.version,
meta.header.dialect,
meta.types.len(),
@@ -1275,10 +1207,10 @@ fn cmd_il2cpp_meta(args: &[String], json: bool) -> ExitCode {
meta.images.len()
);
for t in types.iter().take(50) {
- println!(" type {}", t.full_name());
+ println!(" type {}", t.full_name());
}
if types.len() > 50 {
- println!(" ... {} more types", types.len() - 50);
+ println!(" .. {} more types", types.len() - 50);
}
})
}
@@ -1287,9 +1219,9 @@ fn cmd_il2cpp_meta(args: &[String], json: bool) -> ExitCode {
if json {
return emit_result(&payload, true, out_path.as_deref(), || {});
}
- eprintln!("{}", serde_json::to_string_pretty(&payload).unwrap_or_else(|_| e.to_string()));
+ eprintln!("{}", serde_json::to_string_pretty(&payload).unwrap_or_else(|_| e.to_string()));
} else {
- eprintln!("error: {e}");
+ eprintln!("error: {e}");
}
ExitCode::FAILURE
}
@@ -1308,35 +1240,35 @@ fn cmd_il2cpp_map(args: &[String], json: bool) -> ExitCode {
let mut i = 0;
while i < args.len() {
match args[i].as_str() {
- "--binary" if i + 1 < args.len() => {
+ "-binary" if i + 1 < args.len() => {
binary = Some(PathBuf::from(&args[i + 1]));
i += 2;
}
- "--meta" if i + 1 < args.len() => {
+ "-meta" if i + 1 < args.len() => {
meta_path = Some(PathBuf::from(&args[i + 1]));
i += 2;
}
- "--meta-sections" if i + 1 < args.len() => {
+ "-meta-sections" if i + 1 < args.len() => {
meta_sections = Some(PathBuf::from(&args[i + 1]));
i += 2;
}
- "--filter" if i + 1 < args.len() => {
+ "-filter" if i + 1 < args.len() => {
filter = Some(args[i + 1].clone());
i += 2;
}
- "--out" if i + 1 < args.len() => {
+ "-out" if i + 1 < args.len() => {
out_path = Some(PathBuf::from(&args[i + 1]));
i += 2;
}
- "--baseline" if i + 1 < args.len() => {
+ "-baseline" if i + 1 < args.len() => {
baseline_path = Some(PathBuf::from(&args[i + 1]));
i += 2;
}
- "--baseline-strict" => {
+ "-baseline-strict" => {
baseline_strict = true;
i += 1;
}
- "--script-json" => {
+ "-script-json" => {
script_json = true;
i += 1;
}
@@ -1345,19 +1277,19 @@ fn cmd_il2cpp_map(args: &[String], json: bool) -> ExitCode {
}
let Some(binary) = binary else {
eprintln!(
- "usage: ghidrust il2cpp map --binary <il2cpp> --meta <metadata.dat>|--meta-sections DIR\n\
- [--filter SUB] [--baseline PREV.json] [--baseline-strict] [--script-json] [--out FILE] [--json]"
+ "usage: ghidrust il2cpp map -binary <il2cpp> -meta <metadata.dat>|-meta-sections DIR\n\
+ [-filter SUB] [-baseline PREV.json] [-baseline-strict] [-script-json] [-out FILE] [-json]"
);
return ExitCode::from(2);
};
if meta_path.is_none() && meta_sections.is_none() {
- eprintln!("error: provide --meta PATH or --meta-sections DIR");
+ eprintln!("error: provide -meta PATH or -meta-sections DIR");
return ExitCode::from(2);
}
let prog = match load_path(&binary) {
Ok(p) => p,
Err(e) => {
- eprintln!("error: {e}");
+ eprintln!("error: {e}");
return ExitCode::FAILURE;
}
};
@@ -1369,11 +1301,11 @@ fn cmd_il2cpp_map(args: &[String], json: bool) -> ExitCode {
return emit_result(&payload, true, out_path.as_deref(), || {});
}
eprintln!(
- "{}",
+ "{}",
serde_json::to_string_pretty(&payload).unwrap_or_else(|_| e.to_string())
);
} else {
- eprintln!("error: {e}");
+ eprintln!("error: {e}");
}
return ExitCode::FAILURE;
}
@@ -1391,7 +1323,7 @@ fn cmd_il2cpp_map(args: &[String], json: bool) -> ExitCode {
map.build_skew = Some(compare_baseline(&map, &prev));
}
Err(e) => {
- eprintln!("error loading baseline: {e}");
+ eprintln!("error loading baseline: {e}");
return ExitCode::FAILURE;
}
}
@@ -1400,7 +1332,7 @@ fn cmd_il2cpp_map(args: &[String], json: bool) -> ExitCode {
let script = to_script_json(&map);
return emit_result(&script, json, out_path.as_deref(), || {
println!(
- "script.json methods with addresses: {}",
+ "script.json methods with addresses: {}",
script.script_method.len()
);
});
@@ -1413,17 +1345,17 @@ fn cmd_il2cpp_map(args: &[String], json: bool) -> ExitCode {
.unwrap_or(false);
let code = emit_result(&map, json, out_path.as_deref(), || {
println!(
- "method map: {} entries, pointer_count={:?}, shared_stubs={}",
+ "method map: {} entries, pointer_count={:?}, shared_stubs={}",
map.entries.len(),
map.method_pointer_count,
map.shared_stubs.len()
);
for n in &map.notes {
- println!(" note: {n}");
+ println!(" note: {n}");
}
if let Some(skew) = &map.build_skew {
println!(
- " build_skew: moved={} missing={} appeared={}",
+ " build_skew: moved={} missing={} appeared={}",
skew.moved.len(),
skew.missing.len(),
skew.appeared.len()
@@ -1434,23 +1366,23 @@ fn cmd_il2cpp_map(args: &[String], json: bool) -> ExitCode {
Some(rva) => {
let bc = e
.body_class
- .map(|c| format!(" [{c:?}]"))
+ .map(|c| format!(" [{c:?}]"))
.unwrap_or_default();
- println!(" {:#x} {}{bc}", rva, e.full_name);
+ println!(" {:#x} {}{bc}", rva, e.full_name);
}
- None => println!(" (unmapped) {}", e.full_name),
+ None => println!(" (unmapped) {}", e.full_name),
}
}
});
if strict_fail {
- eprintln!("baseline-strict: {} moved RVAs", map.build_skew.as_ref().map(|s| s.moved.len()).unwrap_or(0));
+ eprintln!("baseline-strict: {} moved RVAs", map.build_skew.as_ref().map(|s| s.moved.len()).unwrap_or(0));
ExitCode::FAILURE
} else {
code
}
}
Err(e) => {
- eprintln!("error: {e}");
+ eprintln!("error: {e}");
ExitCode::FAILURE
}
}
@@ -1465,23 +1397,23 @@ fn cmd_il2cpp_touch_map(args: &[String], json: bool) -> ExitCode {
let mut i = 0;
while i < args.len() {
match args[i].as_str() {
- "--meta" if i + 1 < args.len() => {
+ "-meta" if i + 1 < args.len() => {
meta_path = Some(PathBuf::from(&args[i + 1]));
i += 2;
}
- "--meta-sections" if i + 1 < args.len() => {
+ "-meta-sections" if i + 1 < args.len() => {
meta_sections = Some(PathBuf::from(&args[i + 1]));
i += 2;
}
- "--filter" if i + 1 < args.len() => {
+ "-filter" if i + 1 < args.len() => {
filter = Some(args[i + 1].clone());
i += 2;
}
- "--binary" if i + 1 < args.len() => {
+ "-binary" if i + 1 < args.len() => {
binary = Some(PathBuf::from(&args[i + 1]));
i += 2;
}
- "--out" if i + 1 < args.len() => {
+ "-out" if i + 1 < args.len() => {
out_path = Some(PathBuf::from(&args[i + 1]));
i += 2;
}
@@ -1490,19 +1422,19 @@ fn cmd_il2cpp_touch_map(args: &[String], json: bool) -> ExitCode {
}
let Some(filter) = filter else {
eprintln!(
- "usage: ghidrust il2cpp touch-map --meta PATH|--meta-sections DIR --filter SUB [--binary PE] [--json]"
+ "usage: ghidrust il2cpp touch-map -meta PATH|-meta-sections DIR -filter SUB [-binary PE] [-json]"
);
return ExitCode::from(2);
};
if meta_path.is_none() && meta_sections.is_none() {
- eprintln!("error: provide --meta PATH or --meta-sections DIR");
+ eprintln!("error: provide -meta PATH or -meta-sections DIR");
return ExitCode::from(2);
}
let prog = match &binary {
Some(b) => match load_path(b) {
Ok(p) => Some(p),
Err(e) => {
- eprintln!("error: {e}");
+ eprintln!("error: {e}");
return ExitCode::FAILURE;
}
},
@@ -1516,16 +1448,16 @@ fn cmd_il2cpp_touch_map(args: &[String], json: bool) -> ExitCode {
) {
Ok(report) => emit_result(&report, json, out_path.as_deref(), || {
println!(
- "touch-map filter={:?} rows={}",
+ "touch-map filter={:?} rows={}",
report.filter, report.row_count
);
for r in report.rows.iter().take(40) {
println!(
- " {:?} {} conf={:?} {}",
+ " {:?} {} conf={:?} {}",
r.kind,
r.string,
r.confidence,
- r.full_name.as_deref().unwrap_or("-")
+ r.full_name.as_deref().unwrap_or("-")
);
}
}),
@@ -1535,11 +1467,11 @@ fn cmd_il2cpp_touch_map(args: &[String], json: bool) -> ExitCode {
return emit_result(&payload, true, out_path.as_deref(), || {});
}
eprintln!(
- "{}",
+ "{}",
serde_json::to_string_pretty(&payload).unwrap_or_else(|_| e.to_string())
);
} else {
- eprintln!("error: {e}");
+ eprintln!("error: {e}");
}
ExitCode::FAILURE
}
@@ -1554,23 +1486,23 @@ fn cmd_il2cpp_stubs(args: &[String], json: bool) -> ExitCode {
let mut i = 0;
while i < args.len() {
match args[i].as_str() {
- "--binary" if i + 1 < args.len() => {
+ "-binary" if i + 1 < args.len() => {
binary = Some(PathBuf::from(&args[i + 1]));
i += 2;
}
- "--filter" if i + 1 < args.len() => {
+ "-filter" if i + 1 < args.len() => {
filter = Some(args[i + 1].clone());
i += 2;
}
- "--out" if i + 1 < args.len() => {
+ "-out" if i + 1 < args.len() => {
out_path = Some(PathBuf::from(&args[i + 1]));
i += 2;
}
- "--max" if i + 1 < args.len() => {
+ "-max" if i + 1 < args.len() => {
max_scan = args[i + 1].parse().unwrap_or(max_scan);
i += 2;
}
- other if binary.is_none() && !other.starts_with('-') => {
+ other if binary.is_none() && !other.starts_with('-') => {
binary = Some(PathBuf::from(other));
i += 1;
}
@@ -1579,7 +1511,7 @@ fn cmd_il2cpp_stubs(args: &[String], json: bool) -> ExitCode {
}
let Some(binary) = binary else {
eprintln!(
- "usage: ghidrust il2cpp stubs --binary <il2cpp> [--filter SUB] [--max N] [--out FILE] [--json]"
+ "usage: ghidrust il2cpp stubs -binary <il2cpp> [-filter SUB] [-max N] [-out FILE] [-json]"
);
return ExitCode::from(2);
};
@@ -1590,18 +1522,18 @@ fn cmd_il2cpp_stubs(args: &[String], json: bool) -> ExitCode {
stubs.retain(|s| stub_matches_filter(&prog, s, f));
}
emit_result(&stubs, json, out_path.as_deref(), || {
- println!("resolve stubs: {}", stubs.len());
+ println!("resolve stubs: {}", stubs.len());
for s in stubs.iter().take(80) {
println!(
- " {:#x} {}",
+ " {:#x} {}",
s.entry,
- s.icall_name.as_deref().unwrap_or("(unnamed)")
+ s.icall_name.as_deref().unwrap_or("(unnamed)")
);
}
})
}
Err(e) => {
- eprintln!("error: {e}");
+ eprintln!("error: {e}");
ExitCode::FAILURE
}
}
@@ -1611,7 +1543,7 @@ fn cmd_unity_inventory(args: &[String], json: bool) -> ExitCode {
let path = match args.first() {
Some(p) => PathBuf::from(p),
None => {
- eprintln!("usage: ghidrust unity-inventory <game-dir> [--out FILE] [--json]");
+ eprintln!("usage: ghidrust unity-inventory <game-dir> [-out FILE] [-json]");
return ExitCode::from(2);
}
};
@@ -1619,7 +1551,7 @@ fn cmd_unity_inventory(args: &[String], json: bool) -> ExitCode {
let mut i = 1;
while i < args.len() {
match args[i].as_str() {
- "--out" if i + 1 < args.len() => {
+ "-out" if i + 1 < args.len() => {
out_path = Some(PathBuf::from(&args[i + 1]));
i += 2;
}
@@ -1628,9 +1560,9 @@ fn cmd_unity_inventory(args: &[String], json: bool) -> ExitCode {
}
match inventory_path(&path) {
Ok(inv) => emit_result(&inv, json, out_path.as_deref(), || {
- println!("unity-inventory schema={} root={}", inv.schema_version, inv.root);
+ println!("unity-inventory schema={} root={}", inv.schema_version, inv.root);
println!(
- " verdict={:?} confidence={:?} il2cpp={} xr_stock={} xr_pkg={} external={}",
+ " verdict={:?} confidence={:?} il2cpp={} xr_stock={} xr_pkg={} external={}",
inv.verdict,
inv.confidence,
inv.engine.il2cpp,
@@ -1639,11 +1571,11 @@ fn cmd_unity_inventory(args: &[String], json: bool) -> ExitCode {
inv.external_vr_indicators.len()
);
for n in &inv.notes {
- println!(" note: {n}");
+ println!(" note: {n}");
}
}),
Err(e) => {
- eprintln!("error: {e}");
+ eprintln!("error: {e}");
ExitCode::FAILURE
}
}
@@ -1653,7 +1585,7 @@ fn cmd_imports(args: &[String], json: bool) -> ExitCode {
let path = match path_arg(args) {
Ok(p) => p,
Err(e) => {
- eprintln!("{e}");
+ eprintln!("{e}");
return ExitCode::from(2);
}
};
@@ -1662,11 +1594,11 @@ fn cmd_imports(args: &[String], json: bool) -> ExitCode {
let mut i = 1;
while i < args.len() {
match args[i].as_str() {
- "--dll" if i + 1 < args.len() => {
+ "-dll" if i + 1 < args.len() => {
dll = Some(args[i + 1].clone());
i += 2;
}
- "--name" if i + 1 < args.len() => {
+ "-name" if i + 1 < args.len() => {
name = Some(args[i + 1].clone());
i += 2;
}
@@ -1686,9 +1618,9 @@ fn cmd_imports(args: &[String], json: bool) -> ExitCode {
let sym = e
.name
.clone()
- .unwrap_or_else(|| format!("ord_{}", e.ordinal.unwrap_or(0)));
+ .unwrap_or_else(|| format!("ord_{}", e.ordinal.unwrap_or(0)));
println!(
- "{:#x}\t{}!{}",
+ "{:#x}\t{}!{}",
e.iat_va, e.dll, sym
);
}
@@ -1696,18 +1628,18 @@ fn cmd_imports(args: &[String], json: bool) -> ExitCode {
ExitCode::SUCCESS
}
Err(e) => {
- eprintln!("error: {e}");
+ eprintln!("error: {e}");
ExitCode::FAILURE
}
}
}
fn cmd_function(args: &[String], json: bool) -> ExitCode {
- let sub = args.first().map(|s| s.as_str()).unwrap_or("");
+ let sub = args.first().map(|s| s.as_str()).unwrap_or("");
match sub {
- "create" => cmd_function_create(&args[1..], json),
+ "create" => cmd_function_create(&args[1..], json),
_ => {
- eprintln!("usage: ghidrust function create <path> --addr HEX [--end HEX] [--json]");
+ eprintln!("usage: ghidrust function create <path> -addr HEX [-end HEX] [-json]");
ExitCode::from(2)
}
}
@@ -1717,7 +1649,7 @@ fn cmd_function_create(args: &[String], json: bool) -> ExitCode {
let path = match path_arg(args) {
Ok(p) => p,
Err(e) => {
- eprintln!("{e}");
+ eprintln!("{e}");
return ExitCode::from(2);
}
};
@@ -1726,11 +1658,11 @@ fn cmd_function_create(args: &[String], json: bool) -> ExitCode {
let mut i = 1;
while i < args.len() {
match args[i].as_str() {
- "--addr" if i + 1 < args.len() => {
+ "-addr" if i + 1 < args.len() => {
addr = parse_u64(&args[i + 1]).ok();
i += 2;
}
- "--end" if i + 1 < args.len() => {
+ "-end" if i + 1 < args.len() => {
end = parse_u64(&args[i + 1]).ok();
i += 2;
}
@@ -1738,7 +1670,7 @@ fn cmd_function_create(args: &[String], json: bool) -> ExitCode {
}
}
let Some(va) = addr else {
- eprintln!("usage: ghidrust function create <path> --addr HEX [--end HEX] [--json]");
+ eprintln!("usage: ghidrust function create <path> -addr HEX [-end HEX] [-json]");
return ExitCode::from(2);
};
match load_path(&path) {
@@ -1746,21 +1678,21 @@ fn cmd_function_create(args: &[String], json: bool) -> ExitCode {
let f = create_function(&mut prog, va, end);
if json {
emit_json(&json!({
- "entry": format!("{:#x}", f.entry),
- "end": format!("{:#x}", f.end),
- "name": f.name,
- "seed_kind": f.seed_kind,
+ "entry": format!("{:#x}", f.entry),
+ "end": format!("{:#x}", f.end),
+ "name": f.name,
+ "seed_kind": f.seed_kind,
}));
} else {
println!(
- "created {} [{:#x}, {:#x}) seed_kind={:?}",
+ "created {} [{:#x}, {:#x}) seed_kind={:?}",
f.name, f.entry, f.end, f.seed_kind
);
}
ExitCode::SUCCESS
}
Err(e) => {
- eprintln!("error: {e}");
+ eprintln!("error: {e}");
ExitCode::FAILURE
}
}
@@ -1770,7 +1702,7 @@ fn cmd_function_at(args: &[String], json: bool) -> ExitCode {
let path = match path_arg(args) {
Ok(p) => p,
Err(e) => {
- eprintln!("{e}");
+ eprintln!("{e}");
return ExitCode::from(2);
}
};
@@ -1778,7 +1710,7 @@ fn cmd_function_at(args: &[String], json: bool) -> ExitCode {
let mut i = 1;
while i < args.len() {
match args[i].as_str() {
- "--addr" if i + 1 < args.len() => {
+ "-addr" if i + 1 < args.len() => {
addr = parse_u64(&args[i + 1]).ok();
i += 2;
}
@@ -1786,12 +1718,12 @@ fn cmd_function_at(args: &[String], json: bool) -> ExitCode {
}
}
let Some(va) = addr else {
- eprintln!("usage: ghidrust function-at <path> --addr HEX [--json]");
+ eprintln!("usage: ghidrust function-at <path> -addr HEX [-json]");
return ExitCode::from(2);
};
match load_path(&path).and_then(|mut prog| {
if prog.analysis.functions.is_empty() {
- let _ = run_analyzers(&mut prog, &["Function Start Search"])?;
+ let _ = run_analyzers(&mut prog, &["Function Start Search"])?;
}
Ok(prog)
}) {
@@ -1799,17 +1731,17 @@ fn cmd_function_at(args: &[String], json: bool) -> ExitCode {
Some(f) => {
if json {
emit_json(&json!({
- "addr": format!("{va:#x}"),
- "entry": format!("{:#x}", f.entry),
- "end": format!("{:#x}", f.end),
- "name": f.name,
- "calling_convention": f.calling_convention,
- "noreturn": f.noreturn,
- "parameters": f.parameters,
+ "addr": format!("{va:#x}"),
+ "entry": format!("{:#x}", f.entry),
+ "end": format!("{:#x}", f.end),
+ "name": f.name,
+ "calling_convention": f.calling_convention,
+ "noreturn": f.noreturn,
+ "parameters": f.parameters,
}));
} else {
println!(
- "{:#x} in {} [{:#x}, {:#x})",
+ "{:#x} in {} [{:#x}, {:#x})",
va, f.name, f.entry, f.end
);
}
@@ -1818,18 +1750,18 @@ fn cmd_function_at(args: &[String], json: bool) -> ExitCode {
None => {
if json {
emit_json(&json!({
- "addr": format!("{va:#x}"),
- "function": null,
+ "addr": format!("{va:#x}"),
+ "function": null,
}));
ExitCode::SUCCESS
} else {
- eprintln!("no function contains {va:#x}");
+ eprintln!("no function contains {va:#x}");
ExitCode::FAILURE
}
}
},
Err(e) => {
- eprintln!("error: {e}");
+ eprintln!("error: {e}");
ExitCode::FAILURE
}
}
@@ -1839,18 +1771,18 @@ fn cmd_rtti(args: &[String], json: bool) -> ExitCode {
let path = match path_arg(args) {
Ok(p) => p,
Err(e) => {
- eprintln!("{e}");
+ eprintln!("{e}");
return ExitCode::from(2);
}
};
match load_path(&path).and_then(|p| recover_rtti(&p).map(|r| (p, r))) {
Ok((_prog, report)) => {
if json {
- println!("{}", serde_json::to_string_pretty(&report).unwrap());
+ println!("{}", serde_json::to_string_pretty(&report).unwrap());
} else {
for c in &report.classes {
println!(
- "class {} type_info={} vtable={} col={} ({})",
+ "class {} type_info={} vtable={} col={} ({})",
c.name,
fmt_opt_va(c.type_info_va),
fmt_opt_va(c.vtable_va),
@@ -1859,13 +1791,13 @@ fn cmd_rtti(args: &[String], json: bool) -> ExitCode {
);
}
for n in &report.notes {
- println!("note: {n}");
+ println!("note: {n}");
}
}
ExitCode::SUCCESS
}
Err(e) => {
- eprintln!("error: {e}");
+ eprintln!("error: {e}");
ExitCode::FAILURE
}
}
@@ -1875,23 +1807,23 @@ fn cmd_bulk_bench(args: &[String], json: bool) -> ExitCode {
let path = match args.first() {
Some(p) => PathBuf::from(p),
None => {
- eprintln!("usage: ghidrust bulk-bench <path> [--json]");
+ eprintln!("usage: ghidrust bulk-bench <path> [-json]");
return ExitCode::from(2);
}
};
let prog = match load_path(&path) {
Ok(p) => p,
Err(e) => {
- eprintln!("load error: {e}");
+ eprintln!("load error: {e}");
return ExitCode::from(1);
}
};
- // Concatenate all blocks for a single bulk haystack (transfer-style bulk RE).
+ // Concatenate all blocks for a single bulk haystack (transfer-style bulk RE).
let mut hay = Vec::new();
for b in &prog.blocks {
hay.extend_from_slice(&b.bytes);
}
- // Pad synthetic bulk so PCIe/thread overhead is measurable without fake wins.
+ // Pad synthetic bulk so PCIe/thread overhead is measurable without fake wins.
if hay.len() < 2 * 1024 * 1024 {
let mut big = hay.clone();
while big.len() < 4 * 1024 * 1024 {
@@ -1909,7 +1841,7 @@ fn cmd_bulk_bench(args: &[String], json: bool) -> ExitCode {
let (gpu_s, gpu_b) = scan_ascii_strings_bulk(&prog, 4, BulkScanMode::GpuOrFallback);
if seq_s != par_s || seq_s != gpu_s {
eprintln!(
- "correctness fail: seq={} par={} gpu={}",
+ "correctness fail: seq={} par={} gpu={}",
seq_s.len(),
par_s.len(),
gpu_s.len()
@@ -1918,15 +1850,15 @@ fn cmd_bulk_bench(args: &[String], json: bool) -> ExitCode {
}
if json {
let v = json!({
- "timing": timing,
- "program_strings": seq_s.len(),
- "program_par_backend": format!("{par_b:?}"),
- "program_gpu_backend": format!("{gpu_b:?}"),
+ "timing": timing,
+ "program_strings": seq_s.len(),
+ "program_par_backend": format!("{par_b:?}"),
+ "program_gpu_backend": format!("{gpu_b:?}"),
});
- println!("{}", serde_json::to_string_pretty(&v).unwrap());
+ println!("{}", serde_json::to_string_pretty(&v).unwrap());
} else {
println!(
- "bulk-bench {} bytes threads={} seq_ms={:.3} par_ms={:.3} gpu_ms={:.3} hits={}",
+ "bulk-bench {} bytes threads={} seq_ms={:.3} par_ms={:.3} gpu_ms={:.3} hits={}",
timing.bytes,
timing.threads,
timing.seq_ms,
@@ -1934,10 +1866,10 @@ fn cmd_bulk_bench(args: &[String], json: bool) -> ExitCode {
timing.gpu_ms,
timing.seq_hits
);
- println!("par_backend={:?}", timing.par_backend);
- println!("gpu_backend={:?}", timing.gpu_backend);
+ println!("par_backend={:?}", timing.par_backend);
+ println!("gpu_backend={:?}", timing.gpu_backend);
println!(
- "program ASCII strings: {} (seq/par/gpu equal) par={:?} gpu={:?}",
+ "program ASCII strings: {} (seq/par/gpu equal) par={:?} gpu={:?}",
seq_s.len(),
par_b,
gpu_b
@@ -1950,15 +1882,15 @@ fn cmd_analyzer_bench(args: &[String], json: bool) -> ExitCode {
let path = match args.first() {
Some(p) => PathBuf::from(p),
None => {
- eprintln!("usage: ghidrust analyzer-bench <path> [--large] [--out FILE] [--json]");
+ eprintln!("usage: ghidrust analyzer-bench <path> [-large] [-out FILE] [-json]");
return ExitCode::from(2);
}
};
- let large = args.iter().any(|a| a == "--large");
+ let large = args.iter().any(|a| a == "-large");
let mut out_path: Option<PathBuf> = None;
let mut i = 1;
while i < args.len() {
- if args[i] == "--out" && i + 1 < args.len() {
+ if args[i] == "-out" && i + 1 < args.len() {
out_path = Some(PathBuf::from(&args[i + 1]));
i += 2;
} else {
@@ -1968,20 +1900,20 @@ fn cmd_analyzer_bench(args: &[String], json: bool) -> ExitCode {
let prog = match load_path(&path) {
Ok(p) => p,
Err(e) => {
- eprintln!("load error: {e}");
+ eprintln!("load error: {e}");
return ExitCode::FAILURE;
}
};
let large_min = if large { Some(8 * 1024 * 1024) } else { None };
let mut rows = ghidrust_core::bench_all_analyzers(&prog, large_min);
rows.push(ghidrust_core::bench_gpu_decompile_row(&prog));
- // Full GPU decompile multipass via shipped bench API (CPU wall + multipass oracle).
+ // Full GPU decompile multipass via shipped bench API (CPU wall + multipass oracle).
{
- let tmp = std::env::temp_dir().join("ghidrust_ab_decomp.gdecomp");
+ let tmp = std::env::temp_dir().join("ghidrust_ab_decomp.gdecomp");
if let Ok(b) = ghidrust_decomp::bench_vram_decompile_vs_cpu(&prog, &tmp, 256) {
rows.push(ghidrust_core::AnalyzerBenchRow {
- name: "GPU Decompile VRAM multipass".into(),
- strategy: "decomp_multipass".into(),
+ name: "GPU Decompile VRAM multipass".into(),
+ strategy: "decomp_multipass".into(),
cpu_ms: b.cpu_ms,
cpu_primary: b.cpu_ir,
gpu_pcie_upload_ms: b.gpu_pcie_upload_ms,
@@ -1994,7 +1926,7 @@ fn cmd_analyzer_bench(args: &[String], json: bool) -> ExitCode {
backend: b.backend,
device: b.device,
note: format!(
- "mid_pipeline_host_reads={} text_eq={} ir_eq={} pcie={:.3} device={:.3} cpu_blocks={} gpu_blocks={} | {}",
+ "mid_pipeline_host_reads={} text_eq={} ir_eq={} pcie={:.3} device={:.3} cpu_blocks={} gpu_blocks={} | {}",
b.mid_pipeline_host_reads,
b.text_eq,
b.ir_eq,
@@ -2010,17 +1942,17 @@ fn cmd_analyzer_bench(args: &[String], json: bool) -> ExitCode {
}
}
- let mut log = String::from("=== analyzer CPU vs GPU bench ===\n");
+ let mut log = String::from("=== analyzer CPU vs GPU bench ===\n");
log.push_str(&format!(
- "file={} large={} analyzers={}\n",
+ "file={} large={} analyzers={}\n",
path.display(),
large,
rows.len()
));
- log.push_str("name\tstrategy\tcpu_ms\tcpu_n\tpcie_up\tdevice_ms\tpcie_dn\tpcie_ms\tgpu_wall\tgpu_n\tequal\tbackend\tdevice\n");
+ log.push_str("name\tstrategy\tcpu_ms\tcpu_n\tpcie_up\tdevice_ms\tpcie_dn\tpcie_ms\tgpu_wall\tgpu_n\tequal\tbackend\tdevice\n");
for r in &rows {
log.push_str(&format!(
- "{}\t{}\t{:.3}\t{}\t{:.3}\t{:.3}\t{:.3}\t{:.3}\t{:.3}\t{}\t{}\t{}\t{}\n",
+ "{}\t{}\t{:.3}\t{}\t{:.3}\t{:.3}\t{:.3}\t{:.3}\t{:.3}\t{}\t{}\t{}\t{}\n",
r.name,
r.strategy,
r.cpu_ms,
@@ -2039,15 +1971,15 @@ fn cmd_analyzer_bench(args: &[String], json: bool) -> ExitCode {
if let Some(p) = out_path {
let _ = std::fs::write(&p, &log);
let _ = std::fs::write(
- p.with_extension("json"),
+ p.with_extension("json"),
serde_json::to_string_pretty(&rows).unwrap_or_default(),
);
- eprintln!("wrote {}", p.display());
+ eprintln!("wrote {}", p.display());
}
if json {
- println!("{}", serde_json::to_string_pretty(&rows).unwrap());
+ println!("{}", serde_json::to_string_pretty(&rows).unwrap());
} else {
- print!("{log}");
+ print!("{log}");
}
ExitCode::SUCCESS
}
@@ -2058,14 +1990,14 @@ fn cmd_rtti_gpu_bench(args: &[String], json: bool) -> ExitCode {
let path = match args.first() {
Some(p) => PathBuf::from(p),
None => {
- eprintln!("usage: ghidrust rtti-gpu-bench <path> [--out FILE] [--json]");
+ eprintln!("usage: ghidrust rtti-gpu-bench <path> [-out FILE] [-json]");
return ExitCode::from(2);
}
};
let mut out_path: Option<PathBuf> = None;
let mut i = 1;
while i < args.len() {
- if args[i] == "--out" && i + 1 < args.len() {
+ if args[i] == "-out" && i + 1 < args.len() {
out_path = Some(PathBuf::from(&args[i + 1]));
i += 2;
} else {
@@ -2077,7 +2009,7 @@ fn cmd_rtti_gpu_bench(args: &[String], json: bool) -> ExitCode {
let prog = match load_path(&path) {
Ok(p) => p,
Err(e) => {
- eprintln!("load error: {e}");
+ eprintln!("load error: {e}");
return ExitCode::FAILURE;
}
};
@@ -2085,72 +2017,72 @@ fn cmd_rtti_gpu_bench(args: &[String], json: bool) -> ExitCode {
let file_bytes = std::fs::metadata(&path).map(|m| m.len()).unwrap_or(0);
let image_bytes: usize = prog.blocks.iter().map(|b| b.bytes.len()).sum();
- // CPU full RTTI recovery (oracle / product path)
+ // CPU full RTTI recovery (oracle / product path)
let t_cpu = Instant::now();
let rtti = match recover_rtti(&prog) {
Ok(r) => r,
Err(e) => {
- eprintln!("cpu rtti error: {e}");
+ eprintln!("cpu rtti error: {e}");
return ExitCode::FAILURE;
}
};
let cpu_rtti_ms = t_cpu.elapsed().as_secs_f64() * 1000.0;
- // Analyzer-shaped primary (same name as Auto Analysis option)
- let name = "WindowsPE x86 PE RTTI Analyzer";
+ // Analyzer-shaped primary (same name as Auto Analysis option)
+ let name = "WindowsPE x86 PE RTTI Analyzer";
let row = ghidrust_core::bench_analyzer(&prog, name, None);
let report = json!({
- "file": path.display().to_string(),
- "file_bytes": file_bytes,
- "file_mb": (file_bytes as f64) / (1024.0 * 1024.0),
- "image_bytes": image_bytes,
- "load_ms": load_ms,
- "cpu_rtti_recover_ms": cpu_rtti_ms,
- "cpu_rtti_classes": rtti.classes.len(),
- "gpu_strategy": row.strategy,
- "gpu_seed_cpu_ms": row.cpu_ms,
- "gpu_seed_cpu_hits": row.cpu_primary,
- "gpu_pcie_upload_ms": row.gpu_pcie_upload_ms,
- "gpu_device_ms": row.gpu_device_ms,
- "gpu_pcie_download_ms": row.gpu_pcie_download_ms,
- "gpu_pcie_ms": row.gpu_pcie_ms,
- "gpu_wall_ms": row.gpu_wall_ms,
- "gpu_seed_hits": row.gpu_primary,
- "seed_equal": row.equal,
- "merged_primary": row.merged_primary,
- "backend": row.backend,
- "device": row.device,
- "note": row.note,
- "performance_model": {
- "on_device_vs_seed_cpu": if row.cpu_ms > 0.0 {
+ "file": path.display().to_string(),
+ "file_bytes": file_bytes,
+ "file_mb": (file_bytes as f64) / (1024.0 * 1024.0),
+ "image_bytes": image_bytes,
+ "load_ms": load_ms,
+ "cpu_rtti_recover_ms": cpu_rtti_ms,
+ "cpu_rtti_classes": rtti.classes.len(),
+ "gpu_strategy": row.strategy,
+ "gpu_seed_cpu_ms": row.cpu_ms,
+ "gpu_seed_cpu_hits": row.cpu_primary,
+ "gpu_pcie_upload_ms": row.gpu_pcie_upload_ms,
+ "gpu_device_ms": row.gpu_device_ms,
+ "gpu_pcie_download_ms": row.gpu_pcie_download_ms,
+ "gpu_pcie_ms": row.gpu_pcie_ms,
+ "gpu_wall_ms": row.gpu_wall_ms,
+ "gpu_seed_hits": row.gpu_primary,
+ "seed_equal": row.equal,
+ "merged_primary": row.merged_primary,
+ "backend": row.backend,
+ "device": row.device,
+ "note": row.note,
+ "performance_model": {
+ "on_device_vs_seed_cpu": if row.cpu_ms > 0.0 {
row.cpu_ms / row.gpu_device_ms.max(1e-9)
} else { 0.0 },
- "pcie_vs_device": row.gpu_pcie_ms / row.gpu_device_ms.max(1e-9),
- "summary": "On-device SIMT is often much faster than the CPU seed scan; PCIe upload of the image + cold GPU setup usually dominate wall time. A ~170MB PE does not make GPU compute slow — transfer cost scales with size."
+ "pcie_vs_device": row.gpu_pcie_ms / row.gpu_device_ms.max(1e-9),
+ "summary": "On-device SIMT is often much faster than the CPU seed scan; PCIe upload of the image + cold GPU setup usually dominate wall time. A ~170MB PE does not make GPU compute slow — transfer cost scales with size."
}
});
let mut log = String::new();
- log.push_str("=== RTTI CPU vs GPU bench ===\n");
+ log.push_str("=== RTTI CPU vs GPU bench ===\n");
log.push_str(&format!(
- "file={} size_mb={:.2} image_bytes={}\n",
+ "file={} size_mb={:.2} image_bytes={}\n",
path.display(),
(file_bytes as f64) / (1024.0 * 1024.0),
image_bytes
));
log.push_str(&format!(
- "load_ms={:.3} cpu_rtti_recover_ms={:.3} cpu_classes={}\n",
+ "load_ms={:.3} cpu_rtti_recover_ms={:.3} cpu_classes={}\n",
load_ms,
cpu_rtti_ms,
rtti.classes.len()
));
log.push_str(&format!(
- "gpu_strategy={} backend={} device={}\n",
+ "gpu_strategy={} backend={} device={}\n",
row.strategy, row.backend, row.device
));
log.push_str(&format!(
- "seed_cpu_ms={:.3} seed_cpu_hits={} | pcie_up={:.3} device_ms={:.3} pcie_dn={:.3} pcie_ms={:.3} gpu_wall={:.3} gpu_hits={} equal={}\n",
+ "seed_cpu_ms={:.3} seed_cpu_hits={} | pcie_up={:.3} device_ms={:.3} pcie_dn={:.3} pcie_ms={:.3} gpu_wall={:.3} gpu_hits={} equal={}\n",
row.cpu_ms,
row.cpu_primary,
row.gpu_pcie_upload_ms,
@@ -2162,7 +2094,7 @@ fn cmd_rtti_gpu_bench(args: &[String], json: bool) -> ExitCode {
row.equal
));
log.push_str(&format!(
- "on_device_speedup_vs_seed_cpu={:.1}x pcie/device={:.1}x\n",
+ "on_device_speedup_vs_seed_cpu={:.1}x pcie/device={:.1}x\n",
if row.cpu_ms > 0.0 {
row.cpu_ms / row.gpu_device_ms.max(1e-9)
} else {
@@ -2171,21 +2103,21 @@ fn cmd_rtti_gpu_bench(args: &[String], json: bool) -> ExitCode {
row.gpu_pcie_ms / row.gpu_device_ms.max(1e-9)
));
log.push_str(
- "NOTE: GPU on-device kernel time is separate from PCIe. Large PE transfer cost is real; it is not 'slow GPU compute'.\n",
+ "NOTE: GPU on-device kernel time is separate from PCIe. Large PE transfer cost is real; it is not 'slow GPU compute'.\n",
);
if let Some(p) = out_path {
let _ = std::fs::write(&p, &log);
let _ = std::fs::write(
- p.with_extension("json"),
+ p.with_extension("json"),
serde_json::to_string_pretty(&report).unwrap_or_default(),
);
- eprintln!("wrote {}", p.display());
+ eprintln!("wrote {}", p.display());
}
if json {
- println!("{}", serde_json::to_string_pretty(&report).unwrap());
+ println!("{}", serde_json::to_string_pretty(&report).unwrap());
} else {
- print!("{log}");
+ print!("{log}");
}
ExitCode::SUCCESS
}
@@ -2195,26 +2127,26 @@ fn cmd_gpu_decompile(args: &[String], json: bool) -> ExitCode {
Some(p) => PathBuf::from(p),
None => {
eprintln!(
- "usage: ghidrust gpu-decompile <path> [--addr HEX] [--out FILE] [--metrics FILE] [--json]"
+ "usage: ghidrust gpu-decompile <path> [-addr HEX] [-out FILE] [-metrics FILE] [-json]"
);
return ExitCode::from(2);
}
};
- let mut out_path = PathBuf::from("ghidrust_gpu_decompile.gdecomp");
+ let mut out_path = PathBuf::from("ghidrust_gpu_decompile.gdecomp");
let mut metrics_path: Option<PathBuf> = None;
let mut addr: Option<u64> = None;
let mut i = 1;
while i < args.len() {
match args[i].as_str() {
- "--out" if i + 1 < args.len() => {
+ "-out" if i + 1 < args.len() => {
out_path = PathBuf::from(&args[i + 1]);
i += 2;
}
- "--metrics" if i + 1 < args.len() => {
+ "-metrics" if i + 1 < args.len() => {
metrics_path = Some(PathBuf::from(&args[i + 1]));
i += 2;
}
- "--addr" if i + 1 < args.len() => {
+ "-addr" if i + 1 < args.len() => {
addr = parse_u64(&args[i + 1]).ok();
i += 2;
}
@@ -2224,14 +2156,14 @@ fn cmd_gpu_decompile(args: &[String], json: bool) -> ExitCode {
let mut prog = match load_path(&path) {
Ok(p) => p,
Err(e) => {
- eprintln!("load error: {e}");
+ eprintln!("load error: {e}");
return ExitCode::FAILURE;
}
};
let (entry_va, resolve_meta) = match friction::resolve_and_entry(&mut prog, addr) {
Ok(v) => v,
Err(e) => {
- eprintln!("error: {e}");
+ eprintln!("error: {e}");
return ExitCode::FAILURE;
}
};
@@ -2239,7 +2171,7 @@ fn cmd_gpu_decompile(args: &[String], json: bool) -> ExitCode {
let cpu = match ghidrust_decomp::decompile_at(&prog, entry_va, 64) {
Ok(d) => d,
Err(e) => {
- eprintln!("cpu decompile: {e}");
+ eprintln!("cpu decompile: {e}");
return ExitCode::FAILURE;
}
};
@@ -2248,17 +2180,17 @@ fn cmd_gpu_decompile(args: &[String], json: bool) -> ExitCode {
let rep = match ghidrust_decomp::gpu_decompile_to_file(&prog, Some(entry_va), &out_path, 128) {
Ok(r) => r,
Err(e) => {
- eprintln!("gpu-decompile error: {e}");
+ eprintln!("gpu-decompile error: {e}");
return ExitCode::FAILURE;
}
};
- // Equivalence: multipass algorithm (GPU dump vs CPU multipass on same code)
+ // Equivalence: multipass algorithm (GPU dump vs CPU multipass on same code)
let entry = rep.entry;
let (code, _) = match ghidrust_decomp::region_bytes(&prog, entry, 128) {
Ok(v) => v,
Err(e) => {
- eprintln!("region: {e}");
+ eprintln!("region: {e}");
return ExitCode::FAILURE;
}
};
@@ -2267,32 +2199,32 @@ fn cmd_gpu_decompile(args: &[String], json: bool) -> ExitCode {
== ghidrust_decomp::normalize_pseudo(&multi.pseudo_c);
let metrics = json!({
- "file": path.display().to_string(),
- "resolve": resolve_meta,
- "requested_addr": addr.map(|a| format!("{a:#x}")),
- "resolved_entry": format!("{entry_va:#x}"),
- "dump_path": out_path.display().to_string(),
- "note": ".gdecomp is opaque binary dump — use metrics JSON, not dump-as-text",
- "cpu_decompile_ms": cpu_ms,
- "cpu_blocks": cpu.blocks.len(),
- "cpu_chars": cpu.char_count(),
- "gpu_backend": rep.backend,
- "gpu_device": rep.device,
- "gpu_ms": rep.ms,
- "mid_pipeline_host_reads": rep.mid_pipeline_host_reads,
- "kernels": rep.kernels_dispatched,
- "dump_path": rep.dump_path,
- "dump_bytes": rep.dump_bytes,
- "gpu_ir_count": rep.ir_count,
- "gpu_block_count": rep.block_count,
- "gpu_edge_count": rep.edge_count,
- "equivalence_multipass": equal,
- "pseudo_c_head": rep.pseudo_c.lines().take(6).collect::<Vec<_>>().join("\n"),
+ "file": path.display().to_string(),
+ "resolve": resolve_meta,
+ "requested_addr": addr.map(|a| format!("{a:#x}")),
+ "resolved_entry": format!("{entry_va:#x}"),
+ "dump_path": out_path.display().to_string(),
+ "note": ".gdecomp is opaque binary dump — use metrics JSON, not dump-as-text",
+ "cpu_decompile_ms": cpu_ms,
+ "cpu_blocks": cpu.blocks.len(),
+ "cpu_chars": cpu.char_count(),
+ "gpu_backend": rep.backend,
+ "gpu_device": rep.device,
+ "gpu_ms": rep.ms,
+ "mid_pipeline_host_reads": rep.mid_pipeline_host_reads,
+ "kernels": rep.kernels_dispatched,
+ "dump_path": rep.dump_path,
+ "dump_bytes": rep.dump_bytes,
+ "gpu_ir_count": rep.ir_count,
+ "gpu_block_count": rep.block_count,
+ "gpu_edge_count": rep.edge_count,
+ "equivalence_multipass": equal,
+ "pseudo_c_head": rep.pseudo_c.lines().take(6).collect::<Vec<_>>().join("\n"),
});
if let Some(mp) = metrics_path {
let text = format!(
- "=== GPU-resident full decompile metrics ===\n\
+ "=== GPU-resident full decompile metrics ===\n\
file: {}\n\
cpu_decompile_ms: {:.3}\n\
gpu_backend: {}\n\
@@ -2304,7 +2236,7 @@ fn cmd_gpu_decompile(args: &[String], json: bool) -> ExitCode {
dump_bytes: {}\n\
ir/blocks/edges: {}/{}/{}\n\
equivalence_multipass: {}\n\
- note: VRAM multipass decode→leaders→blocks→emit; single final dump\n",
+ note: VRAM multipass decode→leaders→blocks→emit; single final dump\n",
path.display(),
cpu_ms,
rep.backend,
@@ -2321,28 +2253,28 @@ fn cmd_gpu_decompile(args: &[String], json: bool) -> ExitCode {
);
let _ = std::fs::write(&mp, &text);
let _ = std::fs::write(
- mp.with_extension("json"),
+ mp.with_extension("json"),
serde_json::to_string_pretty(&metrics).unwrap(),
);
- eprintln!("metrics → {}", mp.display());
+ eprintln!("metrics → {}", mp.display());
}
if json {
- println!("{}", serde_json::to_string_pretty(&metrics).unwrap());
+ println!("{}", serde_json::to_string_pretty(&metrics).unwrap());
} else {
- println!("GPU decompile dump → {}", out_path.display());
+ println!("GPU decompile dump → {}", out_path.display());
println!(
- "backend={} device={} ms={:.3} mid_reads={} equal={}",
+ "backend={} device={} ms={:.3} mid_reads={} equal={}",
rep.backend, rep.device, rep.ms, rep.mid_pipeline_host_reads, equal
);
- print!("{}", rep.pseudo_c);
+ print!("{}", rep.pseudo_c);
}
if !equal {
- eprintln!("warning: multipass equivalence failed (see dump vs CPU multipass)");
+ eprintln!("warning: multipass equivalence failed (see dump vs CPU multipass)");
return ExitCode::FAILURE;
}
if rep.mid_pipeline_host_reads != 0 {
- eprintln!("warning: mid-pipeline host IR reads != 0");
+ eprintln!("warning: mid-pipeline host IR reads != 0");
return ExitCode::FAILURE;
}
ExitCode::SUCCESS
@@ -2353,16 +2285,16 @@ fn cmd_decompile(args: &[String], json: bool) -> ExitCode {
Some(p) => PathBuf::from(p),
None => {
eprintln!(
- "usage: ghidrust decompile <path> [--addr HEX] [--count N] [--stage0|--stage05|--stage1] [--follow-stub] [--verbose] [--out FILE] [--json]"
+ "usage: ghidrust decompile <path> [-addr HEX] [-count N] [-stage0|-stage05|-stage1] [-follow-stub] [-verbose] [-out FILE] [-json]"
);
return ExitCode::from(2);
}
};
let mut addr: Option<u64> = None;
let mut count: usize = 64;
- // Stage-1 is the product default. `--stage0` / `--stage05`
- // opt out for oracle / regression comparisons; explicit `--stage1`
- // is accepted for symmetry.
+ // Stage-1 is the product default. `-stage0` / `-stage05`
+ // opt out for oracle / regression comparisons; explicit `-stage1`
+ // is accepted for symmetry.
let mut stage05 = false;
let mut stage0 = false;
let mut stage1 = true;
@@ -2372,40 +2304,40 @@ fn cmd_decompile(args: &[String], json: bool) -> ExitCode {
let mut i = 1;
while i < args.len() {
match args[i].as_str() {
- "--addr" if i + 1 < args.len() => {
+ "-addr" if i + 1 < args.len() => {
addr = parse_u64(&args[i + 1]).ok();
i += 2;
}
- "--count" if i + 1 < args.len() => {
+ "-count" if i + 1 < args.len() => {
count = args[i + 1].parse().unwrap_or(64);
i += 2;
}
- "--stage0" | "--stage-0" | "--legacy" => {
+ "-stage0" | "-stage-0" | "-legacy" => {
stage0 = true;
stage1 = false;
stage05 = false;
i += 1;
}
- "--stage05" | "--stage-0.5" | "--ir" => {
+ "-stage05" | "-stage-0.5" | "-ir" => {
stage05 = true;
stage1 = false;
i += 1;
}
- "--stage1" | "--stage-1" | "--ssa" => {
+ "-stage1" | "-stage-1" | "-ssa" => {
stage1 = true;
stage05 = false;
stage0 = false;
i += 1;
}
- "--follow-stub" => {
+ "-follow-stub" => {
follow_stub = true;
i += 1;
}
- "--verbose" | "-v" => {
+ "-verbose" | "-v" => {
verbose = true;
i += 1;
}
- "--out" if i + 1 < args.len() => {
+ "-out" if i + 1 < args.len() => {
out_path = Some(PathBuf::from(&args[i + 1]));
i += 2;
}
@@ -2420,15 +2352,15 @@ fn cmd_decompile(args: &[String], json: bool) -> ExitCode {
Err(e) => {
if json {
println!(
- "{}",
+ "{}",
serde_json::to_string_pretty(&json!({
- "ok": false,
- "error": e,
+ "ok": false,
+ "error": e,
}))
.unwrap()
);
} else {
- eprintln!("error: {e}");
+ eprintln!("error: {e}");
}
return ExitCode::FAILURE;
}
@@ -2437,13 +2369,13 @@ fn cmd_decompile(args: &[String], json: bool) -> ExitCode {
if follow_stub {
if let Some(stub) = classify_at(&prog, va) {
let (new_va, fm) = build_follow_stub_meta(&prog, va, &stub);
- if let Some(status) = fm.get("status").and_then(|s| s.as_str()) {
- if verbose || (!json && status != "resolved") {
+ if let Some(status) = fm.get("status").and_then(|s| s.as_str()) {
+ if verbose || (!json && status != "resolved") {
eprintln!(
- "follow-stub: {va:#x} {status}{}",
- fm.get("to")
+ "follow-stub: {va:#x} {status}{}",
+ fm.get("to")
.and_then(|t| t.as_str())
- .map(|t| format!(" -> {t}"))
+ .map(|t| format!(" -> {t}"))
.unwrap_or_default()
);
}
@@ -2455,8 +2387,8 @@ fn cmd_decompile(args: &[String], json: bool) -> ExitCode {
}
}
if stage1 {
- // Default to Windows x64 for PE targets, SysV otherwise.
- let conv = if prog.format.to_ascii_lowercase().contains("pe") {
+ // Default to Windows x64 for PE targets, SysV otherwise.
+ let conv = if prog.format.to_ascii_lowercase().contains("pe") {
ghidrust_types::CallConv::Windows
} else {
ghidrust_types::CallConv::SystemV
@@ -2464,32 +2396,52 @@ 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 stored_end = prog.function_at(va).map(|f| f.end);
+ let decoded_end = d
+ .blocks
+ .iter()
+ .map(|b| b.end)
+ .max()
+ .unwrap_or(va);
+ let honesty = assess_decompile_bounds(&prog, va, stored_end, decoded_end);
+ let linear = disassemble_range_opts(&prog, va, count, true)
+ .map(|r| r.insns)
+ .unwrap_or_default();
+ let callsite_hints = collect_callsite_hints(&linear);
let mut obj = json!({
- "decompile": d,
- "resolve": resolve_meta,
- "stage1": {
- "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(),
- }
+ "decompile": d,
+ "resolve": resolve_meta,
+ "stage1": {
+ "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(),
+ },
+ "callsite_hints": callsite_hints,
});
+ if let Some(m) = obj.as_object_mut() {
+ if let Some(hf) = honesty.to_json_fields().as_object() {
+ for (k, v) in hf {
+ m.insert(k.clone(), v.clone());
+ }
+ }
+ }
if let Some(fm) = &follow_meta {
- obj.as_object_mut().unwrap().insert("follow_stub".into(), fm.clone());
+ obj.as_object_mut().unwrap().insert("follow_stub".into(), fm.clone());
}
return emit_result(&obj, json, out_path.as_deref(), || {
- print!("{}", d.pseudo_c);
+ print!("{}", d.pseudo_c);
if verbose {
eprintln!(
- "[{}] stage=1 blocks={} phis={} loops={} locals={} params={} structs={} fold={} tokens={} goto={:.2} lift={:.1}%",
+ "[{}] stage=1 blocks={} phis={} loops={} locals={} params={} structs={} fold={} tokens={} goto={:.2} lift={:.1}%",
d.name,
d.blocks.len(),
sum.phis,
@@ -2506,7 +2458,7 @@ fn cmd_decompile(args: &[String], json: bool) -> ExitCode {
});
}
Err(e) => {
- eprintln!("decompile-stage1 error: {e}");
+ eprintln!("decompile-stage1 error: {e}");
return ExitCode::FAILURE;
}
}
@@ -2515,22 +2467,22 @@ fn cmd_decompile(args: &[String], json: bool) -> ExitCode {
match ghidrust_decomp::decompile_ir_at(&prog, va, count) {
Ok((d, cov)) => {
let mut obj = json!({
- "decompile": d,
- "lift_coverage": {
- "total_ops": cov.total_ops,
- "unimplemented_ops": cov.unimplemented_ops,
- "source_instructions": cov.source_instructions,
- "ratio": cov.ratio(),
+ "decompile": d,
+ "lift_coverage": {
+ "total_ops": cov.total_ops,
+ "unimplemented_ops": cov.unimplemented_ops,
+ "source_instructions": cov.source_instructions,
+ "ratio": cov.ratio(),
}
});
if let Some(fm) = &follow_meta {
- obj.as_object_mut().unwrap().insert("follow_stub".into(), fm.clone());
+ obj.as_object_mut().unwrap().insert("follow_stub".into(), fm.clone());
}
return emit_result(&obj, json, out_path.as_deref(), || {
- print!("{}", d.pseudo_c);
+ print!("{}", d.pseudo_c);
if verbose {
eprintln!(
- "[{}] stage=0.5 blocks={} edges={} insns={} ir_ops={} lift={:.1}% lines={}",
+ "[{}] stage=0.5 blocks={} edges={} insns={} ir_ops={} lift={:.1}% lines={}",
d.name,
d.blocks.len(),
d.edges.len(),
@@ -2543,22 +2495,22 @@ fn cmd_decompile(args: &[String], json: bool) -> ExitCode {
});
}
Err(e) => {
- eprintln!("decompile-ir error: {e}");
+ eprintln!("decompile-ir error: {e}");
ExitCode::FAILURE
}
}
} else {
match ghidrust_decomp::decompile_at(&prog, va, count) {
Ok(d) => {
- let mut obj = json!({ "decompile": d });
+ let mut obj = json!({ "decompile": d });
if let Some(fm) = &follow_meta {
- obj.as_object_mut().unwrap().insert("follow_stub".into(), fm.clone());
+ obj.as_object_mut().unwrap().insert("follow_stub".into(), fm.clone());
}
emit_result(&obj, json, out_path.as_deref(), || {
- print!("{}", d.pseudo_c);
+ print!("{}", d.pseudo_c);
if verbose {
eprintln!(
- "[{}] stage=0 blocks={} edges={} insns={} lines={}",
+ "[{}] stage=0 blocks={} edges={} insns={} lines={}",
d.name,
d.blocks.len(),
d.edges.len(),
@@ -2569,14 +2521,14 @@ fn cmd_decompile(args: &[String], json: bool) -> ExitCode {
})
}
Err(e) => {
- eprintln!("decompile error: {e}");
+ eprintln!("decompile error: {e}");
ExitCode::FAILURE
}
}
}
}
Err(e) => {
- eprintln!("load error: {e}");
+ eprintln!("load error: {e}");
ExitCode::FAILURE
}
}
@@ -2587,7 +2539,7 @@ fn cmd_decompile_bench(args: &[String], json: bool) -> ExitCode {
Some(p) => PathBuf::from(p),
None => {
eprintln!(
- "usage: ghidrust decompile-bench <path> [--functions N] [--count N] [--out FILE] [--stage1] [--parallel] [--json]"
+ "usage: ghidrust decompile-bench <path> [-functions N] [-count N] [-out FILE] [-stage1] [-parallel] [-json]"
);
return ExitCode::from(2);
}
@@ -2595,32 +2547,32 @@ 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;
- // `--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.
+ // `-stage1` opts into the Stage-1 bench (SSA + structure +
+ // types) with per-entry pseudo-C text captured. `-parallel` runs the
+ // per-entry Stage-1 pipeline across a rayon thread pool. Both default
+ // off to keep back-compat with the shipped decompile-bench numbers.
let mut stage1 = false;
let mut parallel = false;
let mut i = 1;
while i < args.len() {
match args[i].as_str() {
- "--functions" if i + 1 < args.len() => {
+ "-functions" if i + 1 < args.len() => {
max_functions = args[i + 1].parse().unwrap_or(max_functions);
i += 2;
}
- "--count" if i + 1 < args.len() => {
+ "-count" if i + 1 < args.len() => {
count = args[i + 1].parse().unwrap_or(count);
i += 2;
}
- "--out" if i + 1 < args.len() => {
+ "-out" if i + 1 < args.len() => {
out_path = Some(PathBuf::from(&args[i + 1]));
i += 2;
}
- "--stage1" | "--stage-1" => {
+ "-stage1" | "-stage-1" => {
stage1 = true;
i += 1;
}
- "--parallel" | "--rayon" => {
+ "-parallel" | "-rayon" => {
parallel = true;
stage1 = true;
i += 1;
@@ -2631,12 +2583,12 @@ fn cmd_decompile_bench(args: &[String], json: bool) -> ExitCode {
let mut prog = match load_path(&path) {
Ok(p) => p,
Err(e) => {
- eprintln!("load error: {e}");
+ eprintln!("load error: {e}");
return ExitCode::FAILURE;
}
};
let _ = ghidrust_core::run_analyzers(&mut prog, &[]);
- let conv = if prog.format.to_ascii_lowercase().contains("pe") {
+ let conv = if prog.format.to_ascii_lowercase().contains("pe") {
ghidrust_types::CallConv::Windows
} else {
ghidrust_types::CallConv::SystemV
@@ -2651,12 +2603,12 @@ fn cmd_decompile_bench(args: &[String], json: bool) -> ExitCode {
let output = if json { report.to_json() } else { report.to_text() };
if let Some(path) = out_path {
if let Err(e) = std::fs::write(&path, &output) {
- eprintln!("write error: {e}");
+ eprintln!("write error: {e}");
return ExitCode::FAILURE;
}
}
- print!("{}", output);
- if !output.ends_with('\n') {
+ print!("{}", output);
+ if !output.ends_with('\n') {
println!();
}
ExitCode::SUCCESS
@@ -2667,7 +2619,7 @@ fn cmd_ghidra_headtohead(args: &[String], json: bool) -> ExitCode {
Some(p) => PathBuf::from(p),
None => {
eprintln!(
- "usage: ghidrust ghidra-headtohead <path> [--functions N] [--count N] \\\n [--ghidra DIR] [--captured JSON] [--out FILE] \\\n [--spawn-timeout SECS] [--ghidra-fn-cap N] [--json]"
+ "usage: ghidrust ghidra-headtohead <path> [-functions N] [-count N] \\\n [-ghidra DIR] [-captured JSON] [-out FILE] \\\n [-spawn-timeout SECS] [-ghidra-fn-cap N] [-json]"
);
return ExitCode::from(2);
}
@@ -2682,31 +2634,31 @@ fn cmd_ghidra_headtohead(args: &[String], json: bool) -> ExitCode {
let mut i = 1;
while i < args.len() {
match args[i].as_str() {
- "--functions" if i + 1 < args.len() => {
+ "-functions" if i + 1 < args.len() => {
max_functions = args[i + 1].parse().unwrap_or(max_functions);
i += 2;
}
- "--count" if i + 1 < args.len() => {
+ "-count" if i + 1 < args.len() => {
count = args[i + 1].parse().unwrap_or(count);
i += 2;
}
- "--out" if i + 1 < args.len() => {
+ "-out" if i + 1 < args.len() => {
out_path = Some(PathBuf::from(&args[i + 1]));
i += 2;
}
- "--ghidra" if i + 1 < args.len() => {
+ "-ghidra" if i + 1 < args.len() => {
ghidra_dir = Some(PathBuf::from(&args[i + 1]));
i += 2;
}
- "--captured" if i + 1 < args.len() => {
+ "-captured" if i + 1 < args.len() => {
captured_path = Some(PathBuf::from(&args[i + 1]));
i += 2;
}
- "--spawn-timeout" if i + 1 < args.len() => {
+ "-spawn-timeout" if i + 1 < args.len() => {
spawn_timeout_secs = args[i + 1].parse().ok();
i += 2;
}
- "--ghidra-fn-cap" if i + 1 < args.len() => {
+ "-ghidra-fn-cap" if i + 1 < args.len() => {
ghidra_fn_cap = args[i + 1].parse().ok();
i += 2;
}
@@ -2716,7 +2668,7 @@ fn cmd_ghidra_headtohead(args: &[String], json: bool) -> ExitCode {
let mut prog = match load_path(&path) {
Ok(p) => p,
Err(e) => {
- eprintln!("load error: {e}");
+ eprintln!("load error: {e}");
return ExitCode::FAILURE;
}
};
@@ -2724,22 +2676,22 @@ fn cmd_ghidra_headtohead(args: &[String], json: bool) -> ExitCode {
let captured = match captured_path {
Some(cp) => match std::fs::read_to_string(&cp) {
- Ok(text) => match serde_json::from_str::<Vec<ghidrust_decomp::CapturedGhidraDecompile>>(&text) {
+ Ok(text) => match serde_json::from_str::<Vec<ghidrust_decomp::CapturedGhidraDecompile>>(&text) {
Ok(v) => Some(v),
Err(e) => {
- eprintln!("--captured parse error: {e}");
+ eprintln!("-captured parse error: {e}");
return ExitCode::FAILURE;
}
},
Err(e) => {
- eprintln!("read --captured: {e}");
+ eprintln!("read -captured: {e}");
return ExitCode::FAILURE;
}
},
None => None,
};
- let cfg = ghidrust_decomp::GhidraOracleConfig {
+ let cfg = ghidrust_decomp::GhidraOracleConfig {
ghidra_install_dir: ghidra_dir,
max_functions,
max_insns_per_fn: count,
@@ -2753,12 +2705,12 @@ fn cmd_ghidra_headtohead(args: &[String], json: bool) -> ExitCode {
let output = if json { report.to_json() } else { report.to_text() };
if let Some(p) = out_path {
if let Err(e) = std::fs::write(&p, &output) {
- eprintln!("write error: {e}");
+ eprintln!("write error: {e}");
return ExitCode::FAILURE;
}
}
- print!("{}", output);
- if !output.ends_with('\n') {
+ print!("{}", output);
+ if !output.ends_with('\n') {
println!();
}
ExitCode::SUCCESS
@@ -2769,14 +2721,14 @@ fn cmd_re_bench(args: &[String], json: bool) -> ExitCode {
let path = match args.first() {
Some(p) => PathBuf::from(p),
None => {
- eprintln!("usage: ghidrust re-bench <path> [--out FILE] [--json]");
+ eprintln!("usage: ghidrust re-bench <path> [-out FILE] [-json]");
return ExitCode::from(2);
}
};
let mut out_path: Option<PathBuf> = None;
let mut i = 1;
while i < args.len() {
- if args[i] == "--out" && i + 1 < args.len() {
+ if args[i] == "-out" && i + 1 < args.len() {
out_path = Some(PathBuf::from(&args[i + 1]));
i += 2;
} else {
@@ -2787,7 +2739,7 @@ fn cmd_re_bench(args: &[String], json: bool) -> ExitCode {
let metrics = match run_re_bench(&path) {
Ok(m) => m,
Err(e) => {
- eprintln!("re-bench error: {e}");
+ eprintln!("re-bench error: {e}");
return ExitCode::FAILURE;
}
};
@@ -2795,15 +2747,15 @@ fn cmd_re_bench(args: &[String], json: bool) -> ExitCode {
let text = format_metrics_log(&metrics);
if let Some(ref p) = out_path {
if let Err(e) = std::fs::write(p, &text) {
- eprintln!("write metrics: {e}");
+ eprintln!("write metrics: {e}");
return ExitCode::FAILURE;
}
- eprintln!("wrote metrics → {}", p.display());
+ eprintln!("wrote metrics → {}", p.display());
}
if json {
- println!("{}", serde_json::to_string_pretty(&metrics).unwrap());
+ println!("{}", serde_json::to_string_pretty(&metrics).unwrap());
} else {
- print!("{text}");
+ print!("{text}");
}
ExitCode::SUCCESS
}
@@ -2828,7 +2780,7 @@ struct DecompileMetrics {
insns: usize,
lines: usize,
chars: usize,
- /// First line of pseudo-C for identity check (not empty placeholder).
+ /// First line of pseudo-C for identity check (not empty placeholder).
pseudo_c_head: String,
}
@@ -2845,16 +2797,16 @@ fn run_re_bench(path: &Path) -> Result<ReBenchMetrics, String> {
let prog = load_path(path).map_err(|e| e.to_string())?;
let entry = prog.entry.unwrap_or(prog.image_base);
- // --- CPU decompile (structure recovery always on CPU) ---
+ // -- CPU decompile (structure recovery always on CPU) --
let t0 = Instant::now();
let decomp = decompile_entry(&prog, 64).map_err(|e| e.to_string())?;
let decomp_ms = t0.elapsed().as_secs_f64() * 1000.0;
- let head: String = decomp.pseudo_c.lines().take(4).collect::<Vec<_>>().join("\n");
+ let head: String = decomp.pseudo_c.lines().take(4).collect::<Vec<_>>().join("\n");
if decomp.pseudo_c.trim().is_empty() || decomp.blocks.is_empty() {
- return Err("decompile produced empty structure".into());
+ return Err("decompile produced empty structure".into());
}
- // --- Bulk haystack (pad for meaningful bulk timing) ---
+ // -- Bulk haystack (pad for meaningful bulk timing) --
let mut hay = Vec::new();
for b in &prog.blocks {
hay.extend_from_slice(&b.bytes);
@@ -2873,26 +2825,26 @@ fn run_re_bench(path: &Path) -> Result<ReBenchMetrics, String> {
}
}
- // CPU bulk (parallel)
+ // CPU bulk (parallel)
let t1 = Instant::now();
let (cpu_hits, cpu_backend) = scan_printable_runs_parallel(&hay, 4);
let cpu_ms = t1.elapsed().as_secs_f64() * 1000.0;
let seq = scan_printable_runs_seq(&hay, 4);
if seq != cpu_hits {
return Err(format!(
- "CPU parallel bulk != sequential ({} vs {})",
+ "CPU parallel bulk != sequential ({} vs {})",
cpu_hits.len(),
seq.len()
));
}
- // GPU or fallback bulk
+ // GPU or fallback bulk
let t2 = Instant::now();
let gpu_rep = scan_printable_runs_gpu_or_fallback(&hay, 4);
let gpu_ms = t2.elapsed().as_secs_f64() * 1000.0;
if gpu_rep.hits != seq {
return Err(format!(
- "GPU/fallback bulk != sequential ({} vs {})",
+ "GPU/fallback bulk != sequential ({} vs {})",
gpu_rep.hits.len(),
seq.len()
));
@@ -2903,7 +2855,7 @@ fn run_re_bench(path: &Path) -> Result<ReBenchMetrics, String> {
Ok(ReBenchMetrics {
file: path.display().to_string(),
decompile_cpu: DecompileMetrics {
- backend: "cpu".into(),
+ backend: "cpu".into(),
ms: decomp_ms,
entry,
name: decomp.name.clone(),
@@ -2915,75 +2867,75 @@ fn run_re_bench(path: &Path) -> Result<ReBenchMetrics, String> {
pseudo_c_head: head,
},
bulk_cpu: BulkModeMetrics {
- mode: "parallel_cpu".into(),
- backend: format!("{cpu_backend:?}"),
+ mode: "parallel_cpu".into(),
+ backend: format!("{cpu_backend:?}"),
ms: cpu_ms,
hits: cpu_hits.len(),
haystack_bytes: hay.len(),
},
bulk_gpu: BulkModeMetrics {
- mode: "gpu_or_fallback".into(),
- backend: format!("{:?}", gpu_rep.backend),
+ mode: "gpu_or_fallback".into(),
+ backend: format!("{:?}", gpu_rep.backend),
ms: gpu_ms,
hits: gpu_rep.hits.len(),
haystack_bytes: hay.len(),
},
- note: "Decompile/CFG is CPU-only (branchy). GPU accelerates bulk byte-parallel RE only; \
+ note: "Decompile/CFG is CPU-only (branchy). GPU accelerates bulk byte-parallel RE only; \
equal bulk hit counts prove correctness. Timings may show GPU slower on small/medium \
- images (PCIe) — measured honestly, not fabricated."
+ images (PCIe) — measured honestly, not fabricated."
.into(),
})
}
fn format_metrics_log(m: &ReBenchMetrics) -> String {
let mut s = String::new();
- s.push_str("=== Ghidrust RE bench: CPU then GPU/fallback ===\n");
- s.push_str(&format!("file: {}\n", m.file));
- s.push_str(&format!("note: {}\n\n", m.note));
- s.push_str("--- DECOMPILE (CPU) ---\n");
+ s.push_str("=== Ghidrust RE bench: CPU then GPU/fallback ===\n");
+ s.push_str(&format!("file: {}\n", m.file));
+ s.push_str(&format!("note: {}\n\n", m.note));
+ s.push_str("-- DECOMPILE (CPU) --\n");
s.push_str(&format!(
- "backend={} ms={:.3} entry={:#x} name={}\n",
+ "backend={} ms={:.3} entry={:#x} name={}\n",
m.decompile_cpu.backend,
m.decompile_cpu.ms,
m.decompile_cpu.entry,
m.decompile_cpu.name
));
s.push_str(&format!(
- "blocks={} edges={} insns={} lines={} chars={}\n",
+ "blocks={} edges={} insns={} lines={} chars={}\n",
m.decompile_cpu.blocks,
m.decompile_cpu.edges,
m.decompile_cpu.insns,
m.decompile_cpu.lines,
m.decompile_cpu.chars
));
- s.push_str("pseudo_c_head:\n");
+ s.push_str("pseudo_c_head:\n");
s.push_str(&m.decompile_cpu.pseudo_c_head);
- s.push_str("\n\n");
- s.push_str("--- BULK RE (CPU parallel) ---\n");
+ s.push_str("\n\n");
+ s.push_str("-- BULK RE (CPU parallel) --\n");
s.push_str(&format!(
- "mode={} backend={} ms={:.3} hits={} haystack_bytes={}\n\n",
+ "mode={} backend={} ms={:.3} hits={} haystack_bytes={}\n\n",
m.bulk_cpu.mode,
m.bulk_cpu.backend,
m.bulk_cpu.ms,
m.bulk_cpu.hits,
m.bulk_cpu.haystack_bytes
));
- s.push_str("--- BULK RE (GPU or fallback) ---\n");
+ s.push_str("-- BULK RE (GPU or fallback) --\n");
s.push_str(&format!(
- "mode={} backend={} ms={:.3} hits={} haystack_bytes={}\n\n",
+ "mode={} backend={} ms={:.3} hits={} haystack_bytes={}\n\n",
m.bulk_gpu.mode,
m.bulk_gpu.backend,
m.bulk_gpu.ms,
m.bulk_gpu.hits,
m.bulk_gpu.haystack_bytes
));
- s.push_str("--- COMPARISON ---\n");
+ s.push_str("-- COMPARISON --\n");
s.push_str(&format!(
- "bulk_hit_equal={}\n",
+ "bulk_hit_equal={}\n",
m.bulk_cpu.hits == m.bulk_gpu.hits
));
s.push_str(&format!(
- "bulk_cpu_ms={:.3} bulk_gpu_ms={:.3} ratio_gpu_over_cpu={:.3}\n",
+ "bulk_cpu_ms={:.3} bulk_gpu_ms={:.3} ratio_gpu_over_cpu={:.3}\n",
m.bulk_cpu.ms,
m.bulk_gpu.ms,
if m.bulk_cpu.ms > 0.0 {
@@ -2993,7 +2945,7 @@ fn format_metrics_log(m: &ReBenchMetrics) -> String {
}
));
s.push_str(&format!(
- "decompile_cpu_ms={:.3} (structure recovery not offloaded to GPU)\n",
+ "decompile_cpu_ms={:.3} (structure recovery not offloaded to GPU)\n",
m.decompile_cpu.ms
));
s
@@ -3002,11 +2954,11 @@ fn format_metrics_log(m: &ReBenchMetrics) -> String {
fn cmd_analyzers(json: bool) -> ExitCode {
let cat = analyzer_catalog();
if json {
- println!("{}", serde_json::to_string_pretty(&cat).unwrap());
+ println!("{}", serde_json::to_string_pretty(&cat).unwrap());
} else {
for a in &cat {
println!(
- "[{:?}] {} (default_enabled={})",
+ "[{:?}] {} (default_enabled={})",
a.status, a.name, a.default_enabled
);
}
@@ -3018,7 +2970,7 @@ fn cmd_analyze(args: &[String], json: bool) -> ExitCode {
let path = match path_arg(args) {
Ok(p) => p,
Err(e) => {
- eprintln!("{e}");
+ eprintln!("{e}");
return ExitCode::from(2);
}
};
@@ -3027,8 +2979,8 @@ fn cmd_analyze(args: &[String], json: bool) -> ExitCode {
let mut i = 1;
while i < args.len() {
match args[i].as_str() {
- "--analyzers" if i + 1 < args.len() => {
- for s in args[i + 1].split(',') {
+ "-analyzers" if i + 1 < args.len() => {
+ for s in args[i + 1].split(',') {
let t = s.trim();
if !t.is_empty() {
names.push(t.to_string());
@@ -3036,11 +2988,11 @@ fn cmd_analyze(args: &[String], json: bool) -> ExitCode {
}
i += 2;
}
- "--analyzer" if i + 1 < args.len() => {
+ "-analyzer" if i + 1 < args.len() => {
names.push(args[i + 1].clone());
i += 2;
}
- "--gpu" => {
+ "-gpu" => {
use_gpu = true;
i += 1;
}
@@ -3048,7 +3000,7 @@ fn cmd_analyze(args: &[String], json: bool) -> ExitCode {
}
}
- // Selective analyzers and/or --gpu (empty names → defaults via run_analyzers_opts)
+ // Selective analyzers and/or -gpu (empty names → defaults via run_analyzers_opts)
if !names.is_empty() || use_gpu {
let name_refs: Vec<&str> = names.iter().map(|s| s.as_str()).collect();
return match load_path(&path)
@@ -3056,21 +3008,21 @@ fn cmd_analyze(args: &[String], json: bool) -> ExitCode {
{
Ok(report) => {
if json {
- println!("{}", serde_json::to_string_pretty(&report).unwrap());
+ println!("{}", serde_json::to_string_pretty(&report).unwrap());
} else {
if use_gpu {
- println!("gpu=true (bulk strings + per-analyzer GPU seed enrich)");
+ println!("gpu=true (bulk strings + per-analyzer GPU seed enrich)");
}
for r in &report.results {
- println!("[{}] {} — {}", r.status, r.name, r.message);
+ println!("[{}] {} — {}", r.status, r.name, r.message);
if let Some(ref rtti) = r.rtti {
for c in &rtti.classes {
- println!(" class {}", c.name);
+ println!(" class {}", c.name);
}
}
if let Some(ref strings) = r.strings {
for s in strings.iter().take(20) {
- println!(" str {:#x}: {}", s.va, s.value);
+ println!(" str {:#x}: {}", s.va, s.value);
}
}
}
@@ -3078,7 +3030,7 @@ fn cmd_analyze(args: &[String], json: bool) -> ExitCode {
ExitCode::SUCCESS
}
Err(e) => {
- eprintln!("error: {e}");
+ eprintln!("error: {e}");
ExitCode::FAILURE
}
};
@@ -3088,28 +3040,28 @@ fn cmd_analyze(args: &[String], json: bool) -> ExitCode {
Ok(bundle) => {
if json {
println!(
- "{}",
+ "{}",
serde_json::to_string_pretty(&bundle_json(&bundle)).unwrap()
);
} else {
print_program_summary(&bundle.program);
- println!("--- disassembly ---");
+ println!("-- disassembly --");
for insn in &bundle.listing {
- println!("{}", insn.text());
+ println!("{}", insn.text());
}
- println!("--- analysis ---");
+ println!("-- analysis --");
for r in &bundle.analysis.results {
- println!("[{}] {} — {}", r.status, r.name, r.message);
+ println!("[{}] {} — {}", r.status, r.name, r.message);
}
- println!("--- rtti ---");
+ println!("-- rtti --");
for c in &bundle.rtti.classes {
- println!("class {}", c.name);
+ println!("class {}", c.name);
}
}
ExitCode::SUCCESS
}
Err(e) => {
- eprintln!("error: {e}");
+ eprintln!("error: {e}");
ExitCode::FAILURE
}
}
@@ -3117,20 +3069,20 @@ fn cmd_analyze(args: &[String], json: bool) -> ExitCode {
fn bundle_json(b: &AnalysisBundle) -> Value {
json!({
- "format": b.program.format,
- "entry": b.program.entry.map(|e| format!("{e:#x}")),
- "sections": b.program.sections.iter().map(|s| json!({
- "name": s.name,
- "va": format!("{:#x}", s.va),
+ "format": b.program.format,
+ "entry": b.program.entry.map(|e| format!("{e:#x}")),
+ "sections": b.program.sections.iter().map(|s| json!({
+ "name": s.name,
+ "va": format!("{:#x}", s.va),
})).collect::<Vec<_>>(),
- "listing": b.listing,
- "rtti": b.rtti,
- "analysis": b.analysis,
+ "listing": b.listing,
+ "rtti": b.rtti,
+ "analysis": b.analysis,
})
}
fn fmt_opt_va(v: Option<u64>) -> String {
- v.map(|x| format!("{x:#x}")).unwrap_or_else(|| "-".into())
+ v.map(|x| format!("{x:#x}")).unwrap_or_else(|| "-".into())
}
fn xref_row_json(r: &ghidrust_core::XRef, prog: &Program, classify: bool) -> Value {
@@ -3140,25 +3092,25 @@ fn xref_row_json(r: &ghidrust_core::XRef, prog: &Program, classify: bool) -> Val
None
};
let kind = if stub.is_some() {
- "resolve_stub"
+ "resolve_stub"
} else {
r.kind
};
let mut preview = r.preview.clone();
if let Some(s) = stub {
if let Some(name) = s.icall_name {
- preview = format!("{preview} ; il2cpp resolve {name}");
+ preview = format!("{preview} ; il2cpp resolve {name}");
}
}
json!({
- "from": format!("{:#x}", r.from),
- "to": format!("{:#x}", r.to),
- "kind": kind,
- "preview": preview,
- "encoding": r.encoding,
- "from_entry": r.from_entry.map(|v| format!("{v:#x}")),
- "from_function": r.from_function,
- "to_entry": r.to_entry.map(|v| format!("{v:#x}")),
+ "from": format!("{:#x}", r.from),
+ "to": format!("{:#x}", r.to),
+ "kind": kind,
+ "preview": preview,
+ "encoding": r.encoding,
+ "from_entry": r.from_entry.map(|v| format!("{v:#x}")),
+ "from_function": r.from_function,
+ "to_entry": r.to_entry.map(|v| format!("{v:#x}")),
})
}
@@ -3167,14 +3119,14 @@ fn refs_json(refs: &[ghidrust_core::XRef]) -> Value {
refs.iter()
.map(|r| {
json!({
- "from": format!("{:#x}", r.from),
- "to": format!("{:#x}", r.to),
- "kind": r.kind,
- "preview": r.preview,
- "encoding": r.encoding,
- "from_entry": r.from_entry.map(|v| format!("{v:#x}")),
- "from_function": r.from_function,
- "to_entry": r.to_entry.map(|v| format!("{v:#x}")),
+ "from": format!("{:#x}", r.from),
+ "to": format!("{:#x}", r.to),
+ "kind": r.kind,
+ "preview": r.preview,
+ "encoding": r.encoding,
+ "from_entry": r.from_entry.map(|v| format!("{v:#x}")),
+ "from_function": r.from_function,
+ "to_entry": r.to_entry.map(|v| format!("{v:#x}")),
})
})
.collect(),
@@ -3182,7 +3134,7 @@ fn refs_json(refs: &[ghidrust_core::XRef]) -> Value {
}
fn parse_u64(s: &str) -> Result<u64, String> {
- let t = s.trim().trim_start_matches("0x").trim_start_matches("0X");
+ let t = s.trim().trim_start_matches("0x").trim_start_matches("0X");
u64::from_str_radix(t, 16)
.or_else(|_| s.parse::<u64>())
.map_err(|e| e.to_string())
@@ -3190,523 +3142,539 @@ fn parse_u64(s: &str) -> Result<u64, String> {
#[derive(Serialize)]
struct ToolDef {
- name: &'static str,
- description: &'static str,
- /// MCP protocol field name is camelCase; serde default would emit `input_schema`
- /// and Grok's client then fails tools/list with "Unexpected response type".
- #[serde(rename = "inputSchema")]
+ name: &'static str,
+ description: &'static str,
+ /// MCP protocol field name is camelCase; serde default would emit `input_schema`
+ /// and Grok's client then fails tools/list with "Unexpected response type".
+ #[serde(rename = "inputSchema")]
input_schema: Value,
}
+fn mcp_tool(t: mcp_decode::McpToolDef) -> ToolDef {
+ ToolDef {
+ name: t.name,
+ description: t.description,
+ input_schema: t.input_schema,
+ }
+}
+
fn tool_defs() -> Vec<ToolDef> {
vec![
ToolDef {
- name: "server_info",
- description: "Package version, tool_surface, and feature flags (check before assuming live process / artifacts)",
- input_schema: json!({ "type": "object", "properties": {} }),
+ name: "server_info",
+ description: "Package version, tool_surface, and feature flags (check before assuming live process / artifacts)",
+ input_schema: json!({ "type": "object", "properties": {} }),
},
ToolDef {
- name: "load",
- description: "Load a PE or ELF binary (path OR project+file_id) and return sections + section_notes",
+ name: "load",
+ description: "Load a PE or ELF binary (path OR project+file_id) and return sections + section_notes",
input_schema: json!({
- "type": "object",
- "properties": {
- "path": { "type": "string" },
- "project": { "type": "string", "description": "Project directory" },
- "file_id": { "type": "string", "description": "Imported file id within project" }
+ "type": "object",
+ "properties": {
+ "path": { "type": "string" },
+ "project": { "type": "string", "description": "Project directory" },
+ "file_id": { "type": "string", "description": "Imported file id within project" }
}
}),
},
ToolDef {
- name: "artifact_get",
- description: "Fetch a spilled analysis artifact by id or path (full JSON)",
+ name: "artifact_get",
+ description: "Fetch a spilled analysis artifact by id or path (full JSON)",
input_schema: json!({
- "type": "object",
- "properties": { "id": { "type": "string" } },
- "required": ["id"]
+ "type": "object",
+ "properties": { "id": { "type": "string" } },
+ "required": ["id"]
}),
},
ToolDef {
- name: "artifact_query",
- description: "Page through an artifact with offset/limit; returns next_offset",
+ name: "artifact_query",
+ description: "Page through an artifact with offset/limit; returns next_offset",
input_schema: json!({
- "type": "object",
- "properties": {
- "id": { "type": "string" },
- "offset": { "type": "integer" },
- "limit": { "type": "integer" }
+ "type": "object",
+ "properties": {
+ "id": { "type": "string" },
+ "offset": { "type": "integer" },
+ "limit": { "type": "integer" }
},
- "required": ["id"]
+ "required": ["id"]
}),
},
ToolDef {
- name: "artifact_list",
- description: "List recent spilled analysis artifacts (id/kind/path/entry_count)",
+ name: "artifact_list",
+ description: "List recent spilled analysis artifacts (id/kind/path/entry_count)",
input_schema: json!({
- "type": "object",
- "properties": {
- "max": { "type": "integer", "description": "Max artifacts to list (default 64)" }
+ "type": "object",
+ "properties": {
+ "max": { "type": "integer", "description": "Max artifacts to list (default 64)" }
}
}),
},
ToolDef {
- name: "inventory",
- description: "Generic PE install inventory (exe/dll catalog + VERSIONINFO)",
+ name: "inventory",
+ description: "Generic PE install inventory (exe/dll catalog + VERSIONINFO)",
input_schema: json!({
- "type": "object",
- "properties": {
- "path": { "type": "string", "description": "Install / directory root" },
- "max_depth": { "type": "integer" },
- "hash": { "type": "boolean" }
+ "type": "object",
+ "properties": {
+ "path": { "type": "string", "description": "Install / directory root" },
+ "max_depth": { "type": "integer" },
+ "hash": { "type": "boolean" }
},
- "required": ["path"]
+ "required": ["path"]
}),
},
ToolDef {
- name: "list_tree",
- description: "Bounded file tree index (size/mtime; no unpack; errors as rows)",
+ name: "list_tree",
+ description: "Bounded file tree index (size/mtime; no unpack; errors as rows)",
input_schema: json!({
- "type": "object",
- "properties": {
- "path": { "type": "string" },
- "max_depth": { "type": "integer" },
- "extensions": { "type": "string", "description": "Comma-separated extensions" },
- "name_glob": { "type": "string" }
+ "type": "object",
+ "properties": {
+ "path": { "type": "string" },
+ "max_depth": { "type": "integer" },
+ "extensions": { "type": "string", "description": "Comma-separated extensions" },
+ "name_glob": { "type": "string" }
},
- "required": ["path"]
+ "required": ["path"]
}),
},
ToolDef {
- name: "rtti_query",
- description: "RTTI catalog query (filter/exact) with multi-vtable honesty + cache",
+ name: "rtti_query",
+ description: "RTTI catalog query (filter/exact) with multi-vtable honesty + cache",
input_schema: json!({
- "type": "object",
- "properties": {
- "path": { "type": "string" },
- "filter": { "type": "string" },
- "exact": { "type": "boolean" },
- "match": { "type": "string", "enum": ["substr", "token", "whole", "glob", "exact"] }
+ "type": "object",
+ "properties": {
+ "path": { "type": "string" },
+ "filter": { "type": "string" },
+ "exact": { "type": "boolean" },
+ "match": { "type": "string", "enum": ["substr", "token", "whole", "glob", "exact"] }
},
- "required": ["path"]
+ "required": ["path"]
}),
},
ToolDef {
- name: "process_list",
- description: "List OS processes (Windows Live Process Bridge)",
- input_schema: json!({ "type": "object", "properties": {} }),
+ name: "process_list",
+ description: "List OS processes (Windows Live Process Bridge)",
+ input_schema: json!({ "type": "object", "properties": {} }),
},
ToolDef {
- name: "process_attach",
- description: "Attach read-only to a process by pid; returns session_id",
+ name: "process_attach",
+ description: "Attach read-only to a process by pid; returns session_id",
input_schema: json!({
- "type": "object",
- "properties": { "pid": { "type": "integer" } },
- "required": ["pid"]
+ "type": "object",
+ "properties": { "pid": { "type": "integer" } },
+ "required": ["pid"]
}),
},
ToolDef {
- name: "process_detach",
- description: "Detach a live-process session by session_id",
+ name: "process_launch",
+ description: "CreateProcess CREATE_SUSPENDED + live session (Windows). Not a debug break-at-entry — call process_resume to run. Fails if a session is already open.",
input_schema: json!({
- "type": "object",
- "properties": { "session_id": { "type": "string" } },
- "required": ["session_id"]
+ "type": "object",
+ "properties": {
+ "image": { "type": "string", "description": "Path to .exe" },
+ "args": { "type": "string", "description": "Optional args after the image" },
+ "cwd": { "type": "string", "description": "Optional working directory" }
+ },
+ "required": ["image"]
}),
},
ToolDef {
- name: "process_modules",
- description: "List modules (base/size/path) for an attached session",
+ name: "process_resume",
+ description: "Resume the primary thread of a process_launch session (CREATE_SUSPENDED)",
input_schema: json!({
- "type": "object",
- "properties": { "session_id": { "type": "string" } },
- "required": ["session_id"]
+ "type": "object",
+ "properties": { "session_id": { "type": "string" } },
+ "required": ["session_id"]
}),
},
ToolDef {
- name: "process_read",
- description: "Read process memory at VA (capped); short reads are explicit errors",
+ name: "process_detach",
+ description: "Detach a live-process session by session_id",
input_schema: json!({
- "type": "object",
- "properties": {
- "session_id": { "type": "string" },
- "addr": { "type": "string" },
- "size": { "type": "integer" }
- },
- "required": ["session_id", "addr"]
+ "type": "object",
+ "properties": { "session_id": { "type": "string" } },
+ "required": ["session_id"]
+ }),
+ },
+ ToolDef {
+ name: "process_modules",
+ description: "List modules (base/size/path) for an attached session",
+ input_schema: json!({
+ "type": "object",
+ "properties": { "session_id": { "type": "string" } },
+ "required": ["session_id"]
}),
},
ToolDef {
- name: "process_resolve",
- description: "static_to_live: module + RVA → live VA (ASLR)",
+ name: "process_read",
+ description: "Read process memory at VA (capped); short reads are explicit errors",
input_schema: json!({
- "type": "object",
- "properties": {
- "session_id": { "type": "string" },
- "module": { "type": "string" },
- "rva": { "type": "string" }
+ "type": "object",
+ "properties": {
+ "session_id": { "type": "string" },
+ "addr": { "type": "string" },
+ "size": { "type": "integer" }
},
- "required": ["session_id", "module", "rva"]
+ "required": ["session_id", "addr"]
}),
},
ToolDef {
- name: "process_regions",
- description: "List memory regions for an attached session (capped)",
+ name: "process_resolve",
+ description: "static_to_live: module + RVA → live VA (ASLR)",
input_schema: json!({
- "type": "object",
- "properties": {
- "session_id": { "type": "string" },
- "max": { "type": "integer", "description": "Max regions (default 256)" }
+ "type": "object",
+ "properties": {
+ "session_id": { "type": "string" },
+ "module": { "type": "string" },
+ "rva": { "type": "string" }
},
- "required": ["session_id"]
+ "required": ["session_id", "module", "rva"]
}),
},
ToolDef {
- name: "disassemble",
- description: "Disassemble x86-64: resolve addr to function entry, then bounded by function end by default (JSON: stop_reason, mode). Set linear:true to escape bounds.",
+ name: "process_regions",
+ description: "List memory regions for an attached session (capped)",
input_schema: json!({
- "type": "object",
- "properties": {
- "path": { "type": "string" },
- "addr": { "type": "string" },
- "count": { "type": "integer" },
- "linear": {
- "type": "boolean",
- "description": "Escape hatch: legacy unbounded linear walk (default false = bounded by function end)"
- }
+ "type": "object",
+ "properties": {
+ "session_id": { "type": "string" },
+ "max": { "type": "integer", "description": "Max regions (default 256)" }
},
- "required": ["path"]
+ "required": ["session_id"]
}),
},
+ mcp_tool(mcp_decode::disassemble_tool_def()),
+ mcp_tool(mcp_decode::decode_support_tool_def()),
+ mcp_tool(mcp_decode::decode_query_tool_def()),
ToolDef {
- name: "rtti",
- description: "Recover C++ RTTI class names and vtable links",
+ name: "rtti",
+ description: "Recover C++ RTTI class names and vtable links",
input_schema: json!({
- "type": "object",
- "properties": { "path": { "type": "string" } },
- "required": ["path"]
+ "type": "object",
+ "properties": { "path": { "type": "string" } },
+ "required": ["path"]
}),
},
ToolDef {
- name: "list_analyzers",
- description: "List Auto Analysis options (Ghidra-compatible labels)",
- input_schema: json!({ "type": "object", "properties": {} }),
+ name: "list_analyzers",
+ description: "List Auto Analysis options (labels)",
+ input_schema: json!({ "type": "object", "properties": {} }),
},
ToolDef {
- name: "analyze",
- description: "Run selected analyzers on a binary path; optional GPU enrich",
+ name: "analyze",
+ description: "Run selected analyzers on a binary path; optional GPU enrich",
input_schema: json!({
- "type": "object",
- "properties": {
- "path": { "type": "string" },
- "analyzers": {
- "type": "array",
- "items": { "type": "string" },
- "description": "Exact analyzer names; empty = defaults"
+ "type": "object",
+ "properties": {
+ "path": { "type": "string" },
+ "analyzers": {
+ "type": "array",
+ "items": { "type": "string" },
+ "description": "Exact analyzer names; empty = defaults"
},
- "gpu": {
- "type": "boolean",
- "description": "GPU bulk strings + per-analyzer seed kernels"
+ "gpu": {
+ "type": "boolean",
+ "description": "GPU bulk strings + per-analyzer seed kernels"
}
},
- "required": ["path"]
+ "required": ["path"]
}),
},
ToolDef {
- name: "list_gpu_strategies",
- description: "Per-analyzer GPU strategy matrix (all Auto Analysis + decompile)",
- input_schema: json!({ "type": "object", "properties": {} }),
+ name: "list_gpu_strategies",
+ description: "Per-analyzer GPU strategy matrix (all Auto Analysis + decompile)",
+ input_schema: json!({ "type": "object", "properties": {} }),
},
ToolDef {
- name: "decompile",
- 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.",
+ name: "decompile",
+ 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": "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: expression-folded SSA+types+structure; JSON includes folded_temps, token_count, goto_rate."
+ "type": "object",
+ "properties": {
+ "path": { "type": "string" },
+ "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: expression-folded SSA+types+structure; JSON includes folded_temps, token_count, goto_rate."
},
- "follow_stub": {
- "type": "boolean",
- "description": "If addr is an IL2CPP resolve stub, decompile the cached target when mapped"
+ "follow_stub": {
+ "type": "boolean",
+ "description": "If addr is an IL2CPP resolve stub, decompile the cached target when mapped"
}
},
- "required": ["path"]
+ "required": ["path"]
}),
},
ToolDef {
- name: "gpu_decompile",
- description: "GPU multipass decompile at addr (containing-fn resolve); returns metrics JSON path; .gdecomp is opaque",
+ name: "gpu_decompile",
+ description: "GPU multipass decompile at addr (containing-fn resolve); returns metrics JSON path; .gdecomp is opaque",
input_schema: json!({
- "type": "object",
- "properties": {
- "path": { "type": "string" },
- "addr": { "type": "string", "description": "VA (mid-body ok; resolved to containing entry)" },
- "out": { "type": "string", "description": "optional dump path" }
+ "type": "object",
+ "properties": {
+ "path": { "type": "string" },
+ "addr": { "type": "string", "description": "VA (mid-body ok; resolved to containing entry)" },
+ "out": { "type": "string", "description": "optional dump path" }
},
- "required": ["path"]
+ "required": ["path"]
}),
},
ToolDef {
- name: "rtti_gpu_bench",
- description: "CPU recover_rtti vs GPU rtti_scan with PCIe upload/download vs on-device split",
+ name: "rtti_gpu_bench",
+ description: "CPU recover_rtti vs GPU rtti_scan with PCIe upload/download vs on-device split",
input_schema: json!({
- "type": "object",
- "properties": { "path": { "type": "string" } },
- "required": ["path"]
+ "type": "object",
+ "properties": { "path": { "type": "string" } },
+ "required": ["path"]
}),
},
ToolDef {
- name: "list_strings",
- description: "Scan ASCII/UTF-16LE strings on PE/ELF or raw blob (raw:true). match=substr|token|whole|glob; optional limit.",
+ name: "list_strings",
+ description: "Scan ASCII/UTF-16LE strings on PE/ELF or raw blob (raw:true). match=substr|token|whole|glob; optional limit.",
input_schema: json!({
- "type": "object",
- "properties": {
- "path": { "type": "string" },
- "encoding": { "type": "string", "enum": ["ascii", "utf16", "all"] },
- "filter": { "type": "string" },
- "match": { "type": "string", "enum": ["substr", "token", "whole", "glob"] },
- "min": { "type": "integer" },
- "limit": { "type": "integer" },
- "raw": { "type": "boolean", "description": "Treat file as a byte blob (not PE/ELF)" }
+ "type": "object",
+ "properties": {
+ "path": { "type": "string" },
+ "encoding": { "type": "string", "enum": ["ascii", "utf16", "all"] },
+ "filter": { "type": "string" },
+ "match": { "type": "string", "enum": ["substr", "token", "whole", "glob"] },
+ "min": { "type": "integer" },
+ "limit": { "type": "integer" },
+ "raw": { "type": "boolean", "description": "Treat file as a byte blob (not PE/ELF)" }
},
- "required": ["path"]
+ "required": ["path"]
}),
},
ToolDef {
- name: "search_strings",
- description: "Alias of list_strings (filter-oriented)",
+ name: "search_strings",
+ description: "Alias of list_strings (filter-oriented)",
input_schema: json!({
- "type": "object",
- "properties": {
- "path": { "type": "string" },
- "encoding": { "type": "string", "enum": ["ascii", "utf16", "all"] },
- "filter": { "type": "string" },
- "match": { "type": "string", "enum": ["substr", "token", "whole", "glob"] },
- "min": { "type": "integer" },
- "limit": { "type": "integer" },
- "raw": { "type": "boolean" }
+ "type": "object",
+ "properties": {
+ "path": { "type": "string" },
+ "encoding": { "type": "string", "enum": ["ascii", "utf16", "all"] },
+ "filter": { "type": "string" },
+ "match": { "type": "string", "enum": ["substr", "token", "whole", "glob"] },
+ "min": { "type": "integer" },
+ "limit": { "type": "integer" },
+ "raw": { "type": "boolean" }
},
- "required": ["path"]
+ "required": ["path"]
}),
},
ToolDef {
- name: "il2cpp_meta",
- description: "Parse IL2CPP global-metadata.dat → types/methods (v27/29/31). Fails closed if encrypted/obfuscated.",
+ name: "il2cpp_meta",
+ description: "Parse IL2CPP global-metadata.dat → types/methods (v27/29/31). Fails closed if encrypted/obfuscated.",
input_schema: json!({
- "type": "object",
- "properties": {
- "path": { "type": "string", "description": "Path to global-metadata.dat" },
- "filter": { "type": "string", "description": "Substring filter on type/method full names" }
+ "type": "object",
+ "properties": {
+ "path": { "type": "string", "description": "Path to global-metadata.dat" },
+ "filter": { "type": "string", "description": "Substring filter on type/method full names" }
},
- "required": ["path"]
+ "required": ["path"]
}),
},
ToolDef {
- name: "il2cpp_map",
- description: "Correlate metadata methods with binary RVAs; fingerprints body_class/shared_stubs. Optional baseline build_skew. Unproven RVAs are null.",
+ name: "il2cpp_map",
+ description: "Correlate metadata methods with binary RVAs; fingerprints body_class/shared_stubs. Optional baseline build_skew. Unproven RVAs are null.",
input_schema: json!({
- "type": "object",
- "properties": {
- "binary": { "type": "string", "description": "IL2CPP binary (e.g. GameAssembly.dll)" },
- "meta": { "type": "string", "description": "Path to global-metadata.dat" },
- "meta_sections": { "type": "string", "description": "Directory with clear global-metadata.dat (see docs/IL2CPP.md)" },
- "filter": { "type": "string" },
- "baseline": { "type": "string", "description": "Prior map JSON for build_skew" }
+ "type": "object",
+ "properties": {
+ "binary": { "type": "string", "description": "IL2CPP binary (e.g. GameAssembly.dll)" },
+ "meta": { "type": "string", "description": "Path to global-metadata.dat" },
+ "meta_sections": { "type": "string", "description": "Directory with clear global-metadata.dat (see docs/IL2CPP.md)" },
+ "filter": { "type": "string" },
+ "baseline": { "type": "string", "description": "Prior map JSON for build_skew" }
},
- "required": ["binary"]
+ "required": ["binary"]
}),
},
ToolDef {
- name: "il2cpp_touch_map",
- description: "Substring touch-map over metadata heaps (method|field|type|property|other). Prefer before inventing names from PE strings; optional binary upgrades rows to rva_bound.",
+ name: "il2cpp_touch_map",
+ description: "Substring touch-map over metadata heaps (method|field|type|property|other). Prefer before inventing names from PE strings; optional binary upgrades rows to rva_bound.",
input_schema: json!({
- "type": "object",
- "properties": {
- "meta": { "type": "string", "description": "Path to clear global-metadata.dat" },
- "meta_sections": { "type": "string", "description": "Directory containing clear metadata dump" },
- "filter": { "type": "string", "description": "Substring filter (required)" },
- "binary": { "type": "string", "description": "Optional PE for rva_bound confidence" }
+ "type": "object",
+ "properties": {
+ "meta": { "type": "string", "description": "Path to clear global-metadata.dat" },
+ "meta_sections": { "type": "string", "description": "Directory containing clear metadata dump" },
+ "filter": { "type": "string", "description": "Substring filter (required)" },
+ "binary": { "type": "string", "description": "Optional PE for rva_bound confidence" }
},
- "required": ["filter"]
+ "required": ["filter"]
}),
},
ToolDef {
- name: "il2cpp_stubs",
- description: "List IL2CPP resolve stubs (LEA icall name → resolve → store slot → jmp reg). Filter matches parsed name or C-string at name_string_va.",
+ name: "il2cpp_stubs",
+ description: "List IL2CPP resolve stubs (LEA icall name → resolve → store slot → jmp reg). Filter matches parsed name or C-string at name_string_va.",
input_schema: json!({
- "type": "object",
- "properties": {
- "binary": { "type": "string" },
- "filter": { "type": "string", "description": "Substring on icall name or name string" },
- "max": { "type": "integer", "description": "Max scan budget (default 250000)" }
+ "type": "object",
+ "properties": {
+ "binary": { "type": "string" },
+ "filter": { "type": "string", "description": "Substring on icall name or name string" },
+ "max": { "type": "integer", "description": "Max scan budget (default 250000)" }
},
- "required": ["binary"]
+ "required": ["binary"]
}),
},
ToolDef {
- name: "il2cpp_icalls",
- description: "Resolve Unity engine icall name‖fn pointer tables (index, name, fn RVA)",
+ name: "il2cpp_icalls",
+ description: "Resolve Unity engine icall name‖fn pointer tables (index, name, fn RVA)",
input_schema: json!({
- "type": "object",
- "properties": {
- "binary": { "type": "string", "description": "Engine PE (e.g. UnityPlayer.dll)" },
- "filter": { "type": "string", "description": "Substring on icall name" }
+ "type": "object",
+ "properties": {
+ "binary": { "type": "string", "description": "Engine PE (e.g. UnityPlayer.dll)" },
+ "filter": { "type": "string", "description": "Substring on icall name" }
},
- "required": ["binary"]
+ "required": ["binary"]
}),
},
ToolDef {
- name: "read_bytes",
- description: "Raw bytes dump at a virtual address (hex + byte array)",
+ name: "read_bytes",
+ description: "Raw bytes dump at a virtual address (hex + byte array)",
input_schema: json!({
- "type": "object",
- "properties": {
- "path": { "type": "string" },
- "addr": { "type": "string", "description": "VA in hex" },
- "count": { "type": "integer", "description": "Byte count (default 64)" }
+ "type": "object",
+ "properties": {
+ "path": { "type": "string" },
+ "addr": { "type": "string", "description": "VA in hex" },
+ "count": { "type": "integer", "description": "Byte count (default 64)" }
},
- "required": ["path", "addr"]
+ "required": ["path", "addr"]
}),
},
ToolDef {
- name: "unity_inventory",
- description: "Unity player install inventory (assemblies, plugins, metadata peek, XR-related fields)",
+ name: "unity_inventory",
+ description: "Unity player install inventory (assemblies, plugins, metadata peek, XR-related fields)",
input_schema: json!({
- "type": "object",
- "properties": {
- "path": { "type": "string", "description": "Player directory (exe + *_Data/)" }
+ "type": "object",
+ "properties": {
+ "path": { "type": "string", "description": "Player directory (exe + *_Data/)" }
},
- "required": ["path"]
+ "required": ["path"]
}),
},
ToolDef {
- name: "get_xrefs_to",
- description: "Cross-references to a VA (RIP LEA/call/jmp, address tables, and non-exec data qword pointers). Optional IL2CPP stub skip/classify.",
+ name: "get_xrefs_to",
+ description: "Cross-references to a VA (RIP LEA/call/jmp, address tables, and non-exec data qword pointers). Optional IL2CPP stub skip/classify.",
input_schema: json!({
- "type": "object",
- "properties": {
- "path": { "type": "string" },
- "addr": { "type": "string" },
- "skip_stubs": { "type": "boolean", "description": "Omit xrefs whose from-VA is an IL2CPP resolve stub" },
- "classify": { "type": "boolean", "description": "Label resolve_stub kind when applicable" }
+ "type": "object",
+ "properties": {
+ "path": { "type": "string" },
+ "addr": { "type": "string" },
+ "skip_stubs": { "type": "boolean", "description": "Omit xrefs whose from-VA is an IL2CPP resolve stub" },
+ "classify": { "type": "boolean", "description": "Label resolve_stub kind when applicable" }
},
- "required": ["path", "addr"]
+ "required": ["path", "addr"]
}),
},
ToolDef {
- name: "get_xrefs_from",
- description: "Cross-references from a VA (disassemble forward); includes from_entry/from_function/to_entry when functions exist",
+ name: "get_xrefs_from",
+ description: "Cross-references from a VA (disassemble forward); includes from_entry/from_function/to_entry when functions exist",
input_schema: json!({
- "type": "object",
- "properties": {
- "path": { "type": "string" },
- "addr": { "type": "string" },
- "count": { "type": "integer" }
+ "type": "object",
+ "properties": {
+ "path": { "type": "string" },
+ "addr": { "type": "string" },
+ "count": { "type": "integer" }
},
- "required": ["path", "addr"]
+ "required": ["path", "addr"]
}),
},
ToolDef {
- name: "get_calls_from",
- description: "Callee edges (call/jmp) inside the function containing addr (CLI: xrefs --calls). Resolves targets to function entries when known.",
+ name: "get_calls_from",
+ description: "Callee edges (call/jmp) inside the function containing addr (CLI: xrefs -calls). Resolves targets to function entries when known.",
input_schema: json!({
- "type": "object",
- "properties": {
- "path": { "type": "string" },
- "addr": { "type": "string", "description": "Function entry or mid-body VA" }
+ "type": "object",
+ "properties": {
+ "path": { "type": "string" },
+ "addr": { "type": "string", "description": "Function entry or mid-body VA" }
},
- "required": ["path", "addr"]
+ "required": ["path", "addr"]
}),
},
ToolDef {
- name: "get_string_xrefs",
- description: "Find strings by filter, then xrefs (encoding ascii|utf16le|all; interior LEA supported)",
+ name: "get_string_xrefs",
+ description: "Find strings by filter, then xrefs (encoding ascii|utf16le|all; interior LEA supported)",
input_schema: json!({
- "type": "object",
- "properties": {
- "path": { "type": "string" },
- "filter": { "type": "string" },
- "encoding": { "type": "string", "enum": ["ascii", "utf16", "utf16le", "all"] }
+ "type": "object",
+ "properties": {
+ "path": { "type": "string" },
+ "filter": { "type": "string" },
+ "encoding": { "type": "string", "enum": ["ascii", "utf16", "utf16le", "all"] }
},
- "required": ["path", "filter"]
+ "required": ["path", "filter"]
}),
},
ToolDef {
- name: "list_imports",
- description: "List PE import / IAT slots (optional dll/name filter)",
+ name: "list_imports",
+ description: "List PE import / IAT slots (optional dll/name filter)",
input_schema: json!({
- "type": "object",
- "properties": {
- "path": { "type": "string" },
- "dll": { "type": "string" },
- "name": { "type": "string" }
+ "type": "object",
+ "properties": {
+ "path": { "type": "string" },
+ "dll": { "type": "string" },
+ "name": { "type": "string" }
},
- "required": ["path"]
+ "required": ["path"]
}),
},
ToolDef {
- name: "get_import_xrefs",
- description: "Code sites that reference an import IAT slot (e.g. ShellExecuteW)",
+ name: "get_import_xrefs",
+ description: "Code sites that reference an import IAT slot (e.g. ShellExecuteW)",
input_schema: json!({
- "type": "object",
- "properties": {
- "path": { "type": "string" },
- "name": { "type": "string" }
+ "type": "object",
+ "properties": {
+ "path": { "type": "string" },
+ "name": { "type": "string" }
},
- "required": ["path", "name"]
+ "required": ["path", "name"]
}),
},
ToolDef {
- name: "function_at",
- description: "Containing function for a VA (runs Function Start Search if needed); JSON includes seed_kind (pdata|export|method_pointer|prologue|manual|synthesized)",
+ name: "function_at",
+ description: "Containing function for a VA (runs Function Start Search if needed); JSON includes seed_kind (pdata|export|method_pointer|prologue|manual|synthesized)",
input_schema: json!({
- "type": "object",
- "properties": {
- "path": { "type": "string" },
- "addr": { "type": "string" }
+ "type": "object",
+ "properties": {
+ "path": { "type": "string" },
+ "addr": { "type": "string" }
},
- "required": ["path", "addr"]
+ "required": ["path", "addr"]
}),
},
ToolDef {
- name: "get_function_by_address",
- description: "Alias of function_at (includes seed_kind)",
+ name: "get_function_by_address",
+ description: "Alias of function_at (includes seed_kind)",
input_schema: json!({
- "type": "object",
- "properties": {
- "path": { "type": "string" },
- "addr": { "type": "string" }
+ "type": "object",
+ "properties": {
+ "path": { "type": "string" },
+ "addr": { "type": "string" }
},
- "required": ["path", "addr"]
+ "required": ["path", "addr"]
}),
},
ToolDef {
- name: "function_create",
- description: "Create/heal a function at VA (optional end; grows body when omitted). Complements pdata/export/FSS seeds; orphan resolve may synthesize SYNTH_* ranges — never invent managed names on those.",
+ name: "function_create",
+ description: "Create/heal a function at VA (optional end; grows body when omitted). Complements pdata/export/FSS seeds; orphan resolve may synthesize SYNTH_* ranges — never invent managed names on those.",
input_schema: json!({
- "type": "object",
- "properties": {
- "path": { "type": "string" },
- "addr": { "type": "string" },
- "end": { "type": "string" }
+ "type": "object",
+ "properties": {
+ "path": { "type": "string" },
+ "addr": { "type": "string" },
+ "end": { "type": "string" }
},
- "required": ["path", "addr"]
+ "required": ["path", "addr"]
}),
},
]
}
fn mcp_write(stdout: &mut impl Write, resp: &Value) -> bool {
- // MCP stdio: one compact JSON object per line (no embedded newlines).
+ // MCP stdio: one compact JSON object per line (no embedded newlines).
let Ok(line) = serde_json::to_string(resp) else {
return false;
};
- if writeln!(stdout, "{line}").is_err() {
+ if writeln!(stdout, "{line}").is_err() {
return false;
}
stdout.flush().ok();
@@ -3720,7 +3688,7 @@ fn run_mcp_stdio() -> ExitCode {
let line = match line {
Ok(l) => l,
Err(e) => {
- eprintln!("mcp read error: {e}");
+ eprintln!("mcp read error: {e}");
return ExitCode::FAILURE;
}
};
@@ -3730,85 +3698,85 @@ fn run_mcp_stdio() -> ExitCode {
let req: Value = match serde_json::from_str(&line) {
Ok(v) => v,
Err(e) => {
- let err = json!({"jsonrpc":"2.0","id":null,"error":{"code":-32700,"message":e.to_string()}});
+ let err = json!({"jsonrpc":"2.0","id":null,"error":{"code":-32700,"message":e.to_string()}});
if !mcp_write(&mut stdout, &err) {
return ExitCode::FAILURE;
}
continue;
}
};
- let id = req.get("id").cloned().unwrap_or(Value::Null);
- let method = req.get("method").and_then(|m| m.as_str()).unwrap_or("");
- let params = req.get("params").cloned().unwrap_or(json!({}));
+ let id = req.get("id").cloned().unwrap_or(Value::Null);
+ let method = req.get("method").and_then(|m| m.as_str()).unwrap_or("");
+ let params = req.get("params").cloned().unwrap_or(json!({}));
let resp = match method {
- "initialize" => {
- // Echo a client-requested protocol version when present; Cursor
- // currently sends 2025-11-25. Fall back to a stable baseline.
+ "initialize" => {
+ // Echo a client-requested protocol version when present; Cursor
+ // currently sends 2025-11-25. Fall back to a stable baseline.
let client_proto = params
- .get("protocolVersion")
+ .get("protocolVersion")
.and_then(|v| v.as_str())
- .unwrap_or("2024-11-05");
+ .unwrap_or("2024-11-05");
let proto = match client_proto {
- "2025-11-25" | "2025-06-18" | "2025-03-26" | "2024-11-05" => client_proto,
- _ => "2024-11-05",
+ "2025-11-25" | "2025-06-18" | "2025-03-26" | "2024-11-05" => client_proto,
+ _ => "2024-11-05",
};
json!({
- "jsonrpc": "2.0",
- "id": id,
- "result": {
- "protocolVersion": proto,
- "capabilities": { "tools": { "listChanged": false } },
- "serverInfo": {
- "name": "ghidrust",
- "version": package_version(),
- "toolSurface": TOOL_SURFACE_VERSION
+ "jsonrpc": "2.0",
+ "id": id,
+ "result": {
+ "protocolVersion": proto,
+ "capabilities": { "tools": { "listChanged": false } },
+ "serverInfo": {
+ "name": "ghidrust",
+ "version": package_version(),
+ "toolSurface": TOOL_SURFACE_VERSION
}
}
})
}
- "tools/list" | "list_tools" => {
- // Serialize tools explicitly so the line stays compact and
- // schema field names match MCP (inputSchema).
+ "tools/list" | "list_tools" => {
+ // Serialize tools explicitly so the line stays compact and
+ // schema field names match MCP (inputSchema).
let tools: Vec<Value> = tool_defs()
.into_iter()
.filter_map(|t| serde_json::to_value(t).ok())
.collect();
- eprintln!("mcp tools/list → {} tools (tool_surface={})", tools.len(), TOOL_SURFACE_VERSION);
+ eprintln!("mcp tools/list → {} tools (tool_surface={})", tools.len(), TOOL_SURFACE_VERSION);
json!({
- "jsonrpc": "2.0",
- "id": id,
- "result": { "tools": tools }
+ "jsonrpc": "2.0",
+ "id": id,
+ "result": { "tools": tools }
})
}
- "tools/call" | "call_tool" => match call_tool(&params) {
+ "tools/call" | "call_tool" => match call_tool(&params) {
Ok(content) => json!({
- "jsonrpc": "2.0",
- "id": id,
- "result": {
- "content": [{ "type": "text", "text": content }],
- "isError": false
+ "jsonrpc": "2.0",
+ "id": id,
+ "result": {
+ "content": [{ "type": "text", "text": content }],
+ "isError": false
}
}),
Err(e) => json!({
- "jsonrpc": "2.0",
- "id": id,
- "result": {
- "content": [{ "type": "text", "text": e }],
- "isError": true
+ "jsonrpc": "2.0",
+ "id": id,
+ "result": {
+ "content": [{ "type": "text", "text": e }],
+ "isError": true
}
}),
},
- "notifications/initialized" | "initialized" => {
+ "notifications/initialized" | "initialized" => {
if id.is_null() {
continue;
}
- json!({"jsonrpc":"2.0","id":id,"result":{}})
+ json!({"jsonrpc":"2.0","id":id,"result":{}})
}
_ => json!({
- "jsonrpc": "2.0",
- "id": id,
- "error": { "code": -32601, "message": format!("method not found: {method}") }
+ "jsonrpc": "2.0",
+ "id": id,
+ "error": { "code": -32601, "message": format!("method not found: {method}") }
}),
};
if !mcp_write(&mut stdout, &resp) {
@@ -3820,50 +3788,50 @@ fn run_mcp_stdio() -> ExitCode {
fn call_tool(params: &Value) -> Result<String, String> {
let name = params
- .get("name")
+ .get("name")
.and_then(|n| n.as_str())
- .ok_or_else(|| "missing tool name".to_string())?;
- let args = params.get("arguments").cloned().unwrap_or(json!({}));
+ .ok_or_else(|| "missing tool name".to_string())?;
+ let args = params.get("arguments").cloned().unwrap_or(json!({}));
match name {
- "server_info" => Ok(serde_json::to_string_pretty(&server_info_json()).unwrap()),
- "artifact_get" => {
+ "server_info" => Ok(serde_json::to_string_pretty(&server_info_json()).unwrap()),
+ "artifact_get" => {
let id = args
- .get("id")
+ .get("id")
.and_then(|p| p.as_str())
- .ok_or_else(|| "missing arguments.id".to_string())?;
+ .ok_or_else(|| "missing arguments.id".to_string())?;
let v = artifact_get(id).map_err(|e| e.to_string())?;
Ok(serde_json::to_string_pretty(&v).unwrap())
}
- "artifact_query" => {
+ "artifact_query" => {
let id = args
- .get("id")
+ .get("id")
.and_then(|p| p.as_str())
- .ok_or_else(|| "missing arguments.id".to_string())?;
- let offset = args.get("offset").and_then(|o| o.as_u64()).unwrap_or(0) as usize;
+ .ok_or_else(|| "missing arguments.id".to_string())?;
+ let offset = args.get("offset").and_then(|o| o.as_u64()).unwrap_or(0) as usize;
let limit = args
- .get("limit")
+ .get("limit")
.and_then(|o| o.as_u64())
.unwrap_or(DEFAULT_PREVIEW_LIMIT as u64) as usize;
let env = artifact_query(id, offset, limit).map_err(|e| e.to_string())?;
Ok(serde_json::to_string_pretty(&env).unwrap())
}
- "artifact_list" => {
- let max = args.get("max").and_then(|m| m.as_u64()).unwrap_or(64) as usize;
+ "artifact_list" => {
+ let max = args.get("max").and_then(|m| m.as_u64()).unwrap_or(64) as usize;
let m = list_artifacts(max).map_err(|e| e.to_string())?;
Ok(serde_json::to_string_pretty(&m).unwrap())
}
- "inventory" => {
+ "inventory" => {
let path = args
- .get("path")
+ .get("path")
.and_then(|p| p.as_str())
- .ok_or_else(|| "missing arguments.path".to_string())?;
- let max_depth = args.get("max_depth").and_then(|m| m.as_u64()).unwrap_or(8) as usize;
- let with_hash = args.get("hash").and_then(|h| h.as_bool()).unwrap_or(false);
+ .ok_or_else(|| "missing arguments.path".to_string())?;
+ let max_depth = args.get("max_depth").and_then(|m| m.as_u64()).unwrap_or(8) as usize;
+ let with_hash = args.get("hash").and_then(|h| h.as_bool()).unwrap_or(false);
let inv = inventory_pe_dir(path, max_depth, with_hash).map_err(|e| e.to_string())?;
let entries = serde_json::to_value(&inv.entries).unwrap();
let env = ghidrust_core::envelope_or_spill(
- "inventory",
+ "inventory",
entries,
64,
DEFAULT_PREVIEW_LIMIT,
@@ -3871,12 +3839,12 @@ fn call_tool(params: &Value) -> Result<String, String> {
)
.map_err(|e| e.to_string())?;
Ok(serde_json::to_string_pretty(&json!({
- "schema_version": inv.schema_version,
- "root": inv.root,
- "notes": inv.notes,
- "entry_count": inv.entries.len(),
- "envelope": env,
- "entries": if inv.entries.len() <= 64 {
+ "schema_version": inv.schema_version,
+ "root": inv.root,
+ "notes": inv.notes,
+ "entry_count": inv.entries.len(),
+ "envelope": env,
+ "entries": if inv.entries.len() <= 64 {
serde_json::to_value(&inv.entries).unwrap()
} else {
Value::Null
@@ -3884,30 +3852,30 @@ fn call_tool(params: &Value) -> Result<String, String> {
}))
.unwrap())
}
- "list_tree" => {
+ "list_tree" => {
let path = args
- .get("path")
+ .get("path")
.and_then(|p| p.as_str())
- .ok_or_else(|| "missing arguments.path".to_string())?;
+ .ok_or_else(|| "missing arguments.path".to_string())?;
let mut opts = TreeListOpts::default();
- if let Some(d) = args.get("max_depth").and_then(|m| m.as_u64()) {
+ if let Some(d) = args.get("max_depth").and_then(|m| m.as_u64()) {
opts.max_depth = d as usize;
}
- if let Some(ext) = args.get("extensions").and_then(|e| e.as_str()) {
+ if let Some(ext) = args.get("extensions").and_then(|e| e.as_str()) {
opts.extensions = Some(
- ext.split(',')
+ ext.split(',')
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
.collect(),
);
}
- if let Some(g) = args.get("name_glob").and_then(|e| e.as_str()) {
+ if let Some(g) = args.get("name_glob").and_then(|e| e.as_str()) {
opts.name_glob = Some(g.to_string());
}
let res = list_tree(path, opts);
let entries = serde_json::to_value(&res.entries).unwrap();
let env = ghidrust_core::envelope_or_spill(
- "tree",
+ "tree",
entries,
128,
DEFAULT_PREVIEW_LIMIT,
@@ -3915,22 +3883,22 @@ fn call_tool(params: &Value) -> Result<String, String> {
)
.map_err(|e| e.to_string())?;
Ok(serde_json::to_string_pretty(&json!({
- "root": res.root,
- "truncated": res.truncated,
- "entry_count": res.entries.len(),
- "envelope": env,
+ "root": res.root,
+ "truncated": res.truncated,
+ "entry_count": res.entries.len(),
+ "envelope": env,
}))
.unwrap())
}
- "rtti_query" => {
+ "rtti_query" => {
let path = args
- .get("path")
+ .get("path")
.and_then(|p| p.as_str())
- .ok_or_else(|| "missing arguments.path".to_string())?;
- let filter = args.get("filter").and_then(|f| f.as_str());
- let exact = args.get("exact").and_then(|e| e.as_bool()).unwrap_or(false);
+ .ok_or_else(|| "missing arguments.path".to_string())?;
+ let filter = args.get("filter").and_then(|f| f.as_str());
+ let exact = args.get("exact").and_then(|e| e.as_bool()).unwrap_or(false);
let mode = args
- .get("match")
+ .get("match")
.and_then(|m| m.as_str())
.map(RttiMatchMode::parse)
.unwrap_or(RttiMatchMode::Substr);
@@ -3939,18 +3907,18 @@ fn call_tool(params: &Value) -> Result<String, String> {
let entries = serde_json::to_value(&q.classes).unwrap();
let env = if q.entry_count > 64 {
Some(
- ghidrust_core::spill_artifact("rtti", entries, DEFAULT_PREVIEW_LIMIT, Some(path))
+ ghidrust_core::spill_artifact("rtti", entries, DEFAULT_PREVIEW_LIMIT, Some(path))
.map_err(|e| e.to_string())?,
)
} else {
None
};
Ok(serde_json::to_string_pretty(&json!({
- "entry_count": q.entry_count,
- "cache_hit": q.cache_hit,
- "notes": q.notes,
- "envelope": env,
- "classes": if q.entry_count <= 64 {
+ "entry_count": q.entry_count,
+ "cache_hit": q.cache_hit,
+ "notes": q.notes,
+ "envelope": env,
+ "classes": if q.entry_count <= 64 {
serde_json::to_value(&q.classes).unwrap()
} else {
Value::Null
@@ -3958,89 +3926,117 @@ fn call_tool(params: &Value) -> Result<String, String> {
}))
.unwrap())
}
- "process_list" => {
+ "process_list" => {
let list = process_list()?;
Ok(serde_json::to_string_pretty(&list).unwrap())
}
- "process_attach" => {
+ "process_attach" => {
let pid = args
- .get("pid")
+ .get("pid")
.and_then(|p| p.as_u64())
- .ok_or_else(|| "missing arguments.pid".to_string())? as u32;
+ .ok_or_else(|| "missing arguments.pid".to_string())? as u32;
let s = process_attach(pid)?;
Ok(serde_json::to_string_pretty(&s).unwrap())
}
- "process_detach" => {
+ "process_launch" => {
+ let image = args
+ .get("image")
+ .and_then(|p| p.as_str())
+ .ok_or_else(|| "missing arguments.image".to_string())?;
+ let launch_args = args
+ .get("args")
+ .and_then(|a| a.as_str())
+ .map(|s| s.to_string());
+ let cwd = args
+ .get("cwd")
+ .and_then(|c| c.as_str())
+ .map(std::path::PathBuf::from);
+ let r = process_launch(&LaunchRequest {
+ image: std::path::PathBuf::from(image),
+ args: launch_args,
+ cwd,
+ })?;
+ Ok(serde_json::to_string_pretty(&r).unwrap())
+ }
+ "process_resume" => {
let sid = args
- .get("session_id")
+ .get("session_id")
.and_then(|p| p.as_str())
- .ok_or_else(|| "missing arguments.session_id".to_string())?;
+ .ok_or_else(|| "missing arguments.session_id".to_string())?;
+ process_resume(sid)?;
+ Ok(serde_json::to_string_pretty(&json!({"ok": true, "resumed": true})).unwrap())
+ }
+ "process_detach" => {
+ let sid = args
+ .get("session_id")
+ .and_then(|p| p.as_str())
+ .ok_or_else(|| "missing arguments.session_id".to_string())?;
process_detach(sid)?;
- Ok(serde_json::to_string_pretty(&json!({"ok": true})).unwrap())
+ Ok(serde_json::to_string_pretty(&json!({"ok": true})).unwrap())
}
- "process_modules" => {
+ "process_modules" => {
let sid = args
- .get("session_id")
+ .get("session_id")
.and_then(|p| p.as_str())
- .ok_or_else(|| "missing arguments.session_id".to_string())?;
+ .ok_or_else(|| "missing arguments.session_id".to_string())?;
let m = process_modules(sid)?;
Ok(serde_json::to_string_pretty(&m).unwrap())
}
- "process_read" => {
+ "process_read" => {
let sid = args
- .get("session_id")
+ .get("session_id")
.and_then(|p| p.as_str())
- .ok_or_else(|| "missing arguments.session_id".to_string())?;
+ .ok_or_else(|| "missing arguments.session_id".to_string())?;
let addr = args
- .get("addr")
+ .get("addr")
.and_then(|a| a.as_str())
- .ok_or_else(|| "missing arguments.addr".to_string())?;
- let size = args.get("size").and_then(|s| s.as_u64()).unwrap_or(64) as usize;
+ .ok_or_else(|| "missing arguments.addr".to_string())?;
+ let size = args.get("size").and_then(|s| s.as_u64()).unwrap_or(64) as usize;
let va = parse_u64(addr)?;
let r = process_read(sid, va, size)?;
Ok(serde_json::to_string_pretty(&r).unwrap())
}
- "process_resolve" => {
+ "process_resolve" => {
let sid = args
- .get("session_id")
+ .get("session_id")
.and_then(|p| p.as_str())
- .ok_or_else(|| "missing arguments.session_id".to_string())?;
+ .ok_or_else(|| "missing arguments.session_id".to_string())?;
let module = args
- .get("module")
+ .get("module")
.and_then(|p| p.as_str())
- .ok_or_else(|| "missing arguments.module".to_string())?;
+ .ok_or_else(|| "missing arguments.module".to_string())?;
let rva = args
- .get("rva")
+ .get("rva")
.and_then(|a| a.as_str())
- .ok_or_else(|| "missing arguments.rva".to_string())?;
+ .ok_or_else(|| "missing arguments.rva".to_string())?;
let rva = parse_u64(rva)?;
let r = process_resolve(sid, module, rva)?;
Ok(serde_json::to_string_pretty(&r).unwrap())
}
- "process_regions" => {
+ "process_regions" => {
let sid = args
- .get("session_id")
+ .get("session_id")
.and_then(|p| p.as_str())
- .ok_or_else(|| "missing arguments.session_id".to_string())?;
- let max = args.get("max").and_then(|m| m.as_u64()).unwrap_or(256) as usize;
+ .ok_or_else(|| "missing arguments.session_id".to_string())?;
+ let max = args.get("max").and_then(|m| m.as_u64()).unwrap_or(256) as usize;
let r = process_regions(sid, max)?;
Ok(serde_json::to_string_pretty(&r).unwrap())
}
- "list_strings" | "search_strings" => {
+ "list_strings" | "search_strings" => {
let path = args
- .get("path")
+ .get("path")
.and_then(|p| p.as_str())
- .ok_or_else(|| "missing arguments.path".to_string())?;
+ .ok_or_else(|| "missing arguments.path".to_string())?;
let encoding = args
- .get("encoding")
+ .get("encoding")
.and_then(|e| e.as_str())
- .unwrap_or("all");
- let filter = args.get("filter").and_then(|f| f.as_str()).map(|s| s.to_string());
- let min_len = args.get("min").and_then(|m| m.as_u64()).unwrap_or(4) as usize;
- let limit = args.get("limit").and_then(|m| m.as_u64()).map(|n| n as usize);
- let raw = args.get("raw").and_then(|r| r.as_bool()).unwrap_or(false);
+ .unwrap_or("all");
+ let filter = args.get("filter").and_then(|f| f.as_str()).map(|s| s.to_string());
+ let min_len = args.get("min").and_then(|m| m.as_u64()).unwrap_or(4) as usize;
+ let limit = args.get("limit").and_then(|m| m.as_u64()).map(|n| n as usize);
+ let raw = args.get("raw").and_then(|r| r.as_bool()).unwrap_or(false);
let mut match_mode = args
- .get("match")
+ .get("match")
.and_then(|m| m.as_str())
.map(StringMatchMode::parse)
.transpose()
@@ -4048,7 +4044,7 @@ fn call_tool(params: &Value) -> Result<String, String> {
.unwrap_or(StringMatchMode::Substr);
if matches!(match_mode, StringMatchMode::Substr) {
if let Some(pat) = &filter {
- if pat.contains('*') || pat.contains('?') {
+ if pat.contains('*') || pat.contains('?') {
match_mode = StringMatchMode::Glob;
}
}
@@ -4069,12 +4065,12 @@ fn call_tool(params: &Value) -> Result<String, String> {
};
Ok(serde_json::to_string_pretty(&strings).unwrap())
}
- "il2cpp_meta" => {
+ "il2cpp_meta" => {
let path = args
- .get("path")
+ .get("path")
.and_then(|p| p.as_str())
- .ok_or_else(|| "missing arguments.path".to_string())?;
- let filter = args.get("filter").and_then(|f| f.as_str());
+ .ok_or_else(|| "missing arguments.path".to_string())?;
+ let filter = args.get("filter").and_then(|f| f.as_str());
let meta = match Il2CppMetadata::load_path(path) {
Ok(m) => m,
Err(e) => {
@@ -4101,28 +4097,28 @@ fn call_tool(params: &Value) -> Result<String, String> {
.collect(),
};
Ok(serde_json::to_string_pretty(&json!({
- "version": meta.header.version,
- "dialect": meta.header.dialect,
- "types": types,
- "methods": methods,
+ "version": meta.header.version,
+ "dialect": meta.header.dialect,
+ "types": types,
+ "methods": methods,
}))
.unwrap())
}
- "il2cpp_map" => {
+ "il2cpp_map" => {
let binary = args
- .get("binary")
+ .get("binary")
.and_then(|p| p.as_str())
- .ok_or_else(|| "missing arguments.binary".to_string())?;
- let meta = args.get("meta").and_then(|p| p.as_str()).map(Path::new);
+ .ok_or_else(|| "missing arguments.binary".to_string())?;
+ let meta = args.get("meta").and_then(|p| p.as_str()).map(Path::new);
let meta_sections = args
- .get("meta_sections")
+ .get("meta_sections")
.and_then(|p| p.as_str())
.map(Path::new);
if meta.is_none() && meta_sections.is_none() {
- return Err("missing arguments.meta or arguments.meta_sections".into());
+ return Err("missing arguments.meta or arguments.meta_sections".into());
}
- let filter = args.get("filter").and_then(|f| f.as_str());
- let baseline = args.get("baseline").and_then(|p| p.as_str());
+ let filter = args.get("filter").and_then(|f| f.as_str());
+ let baseline = args.get("baseline").and_then(|p| p.as_str());
let prog = load_path(binary).map_err(|e| e.to_string())?;
let meta = load_metadata_flexible(meta, meta_sections).map_err(|e| {
e.to_structured_json()
@@ -4141,20 +4137,20 @@ fn call_tool(params: &Value) -> Result<String, String> {
}
Ok(serde_json::to_string_pretty(&map).unwrap())
}
- "il2cpp_touch_map" => {
- let meta = args.get("meta").and_then(|p| p.as_str()).map(Path::new);
+ "il2cpp_touch_map" => {
+ let meta = args.get("meta").and_then(|p| p.as_str()).map(Path::new);
let meta_sections = args
- .get("meta_sections")
+ .get("meta_sections")
.and_then(|p| p.as_str())
.map(Path::new);
let filter = args
- .get("filter")
+ .get("filter")
.and_then(|f| f.as_str())
- .ok_or_else(|| "missing arguments.filter".to_string())?;
+ .ok_or_else(|| "missing arguments.filter".to_string())?;
if meta.is_none() && meta_sections.is_none() {
- return Err("missing arguments.meta or arguments.meta_sections".into());
+ return Err("missing arguments.meta or arguments.meta_sections".into());
}
- let prog = match args.get("binary").and_then(|p| p.as_str()) {
+ let prog = match args.get("binary").and_then(|p| p.as_str()) {
Some(b) => Some(load_path(b).map_err(|e| e.to_string())?),
None => None,
};
@@ -4165,13 +4161,13 @@ fn call_tool(params: &Value) -> Result<String, String> {
})?;
Ok(serde_json::to_string_pretty(&report).unwrap())
}
- "il2cpp_stubs" => {
+ "il2cpp_stubs" => {
let binary = args
- .get("binary")
+ .get("binary")
.and_then(|p| p.as_str())
- .ok_or_else(|| "missing arguments.binary".to_string())?;
- let filter = args.get("filter").and_then(|f| f.as_str());
- let max = args.get("max").and_then(|m| m.as_u64()).unwrap_or(250_000) as usize;
+ .ok_or_else(|| "missing arguments.binary".to_string())?;
+ let filter = args.get("filter").and_then(|f| f.as_str());
+ let max = args.get("max").and_then(|m| m.as_u64()).unwrap_or(250_000) as usize;
let prog = load_path(binary).map_err(|e| e.to_string())?;
let mut stubs = find_resolve_stubs(&prog, max);
if let Some(f) = filter {
@@ -4179,83 +4175,83 @@ fn call_tool(params: &Value) -> Result<String, String> {
}
Ok(serde_json::to_string_pretty(&stubs).unwrap())
}
- "read_bytes" => {
+ "read_bytes" => {
let path = args
- .get("path")
+ .get("path")
.and_then(|p| p.as_str())
- .ok_or_else(|| "missing arguments.path".to_string())?;
+ .ok_or_else(|| "missing arguments.path".to_string())?;
let addr = args
- .get("addr")
+ .get("addr")
.and_then(|a| a.as_str())
- .ok_or_else(|| "missing arguments.addr".to_string())?;
- let count = args.get("count").and_then(|c| c.as_u64()).unwrap_or(64) as usize;
+ .ok_or_else(|| "missing arguments.addr".to_string())?;
+ let count = args.get("count").and_then(|c| c.as_u64()).unwrap_or(64) as usize;
let count = count.clamp(1, 1_048_576);
let prog = load_path(path).map_err(|e| e.to_string())?;
let va = parse_u64(addr)?;
let bytes = prog
.read_va(va, count)
- .ok_or_else(|| format!("address {va:#x} not mapped or unreadable"))?;
+ .ok_or_else(|| format!("address {va:#x} not mapped or unreadable"))?;
let hex: String = bytes
.iter()
- .map(|b| format!("{b:02x}"))
+ .map(|b| format!("{b:02x}"))
.collect::<Vec<_>>()
- .join(" ");
+ .join(" ");
Ok(serde_json::to_string_pretty(&json!({
- "addr": format!("{va:#x}"),
- "count": bytes.len(),
- "hex": hex,
- "bytes": bytes,
+ "addr": format!("{va:#x}"),
+ "count": bytes.len(),
+ "hex": hex,
+ "bytes": bytes,
}))
.unwrap())
}
- "il2cpp_icalls" => {
+ "il2cpp_icalls" => {
let binary = args
- .get("binary")
+ .get("binary")
.and_then(|p| p.as_str())
- .ok_or_else(|| "missing arguments.binary".to_string())?;
- let filter = args.get("filter").and_then(|f| f.as_str());
+ .ok_or_else(|| "missing arguments.binary".to_string())?;
+ let filter = args.get("filter").and_then(|f| f.as_str());
let report = resolve_icalls_path(binary).map_err(|e| e.to_string())?;
if let Some(f) = filter {
let hits = filter_entries(&report, f);
Ok(serde_json::to_string_pretty(&json!({
- "filter": f,
- "table_count": report.tables.len(),
- "hits": hits.iter().map(|(ti, e)| json!({
- "table_index": ti,
- "index": e.index,
- "name": e.name,
- "name_string_va": format!("{:#x}", e.name_string_va),
- "fn_va": format!("{:#x}", e.fn_va),
- "fn_rva": format!("{:#x}", e.fn_rva),
+ "filter": f,
+ "table_count": report.tables.len(),
+ "hits": hits.iter().map(|(ti, e)| json!({
+ "table_index": ti,
+ "index": e.index,
+ "name": e.name,
+ "name_string_va": format!("{:#x}", e.name_string_va),
+ "fn_va": format!("{:#x}", e.fn_va),
+ "fn_rva": format!("{:#x}", e.fn_rva),
})).collect::<Vec<_>>(),
})).unwrap())
} else {
Ok(serde_json::to_string_pretty(&report).unwrap())
}
}
- "unity_inventory" => {
+ "unity_inventory" => {
let path = args
- .get("path")
+ .get("path")
.and_then(|p| p.as_str())
- .ok_or_else(|| "missing arguments.path".to_string())?;
+ .ok_or_else(|| "missing arguments.path".to_string())?;
let inv = inventory_path(path)?;
Ok(serde_json::to_string_pretty(&inv).unwrap())
}
- "get_xrefs_to" => {
+ "get_xrefs_to" => {
let path = args
- .get("path")
+ .get("path")
.and_then(|p| p.as_str())
- .ok_or_else(|| "missing arguments.path".to_string())?;
+ .ok_or_else(|| "missing arguments.path".to_string())?;
let addr = args
- .get("addr")
+ .get("addr")
.and_then(|a| a.as_str())
- .ok_or_else(|| "missing arguments.addr".to_string())?;
+ .ok_or_else(|| "missing arguments.addr".to_string())?;
let skip_stubs = args
- .get("skip_stubs")
+ .get("skip_stubs")
.and_then(|v| v.as_bool())
.unwrap_or(false);
let classify = args
- .get("classify")
+ .get("classify")
.and_then(|v| v.as_bool())
.unwrap_or(false);
let prog = load_path(path).map_err(|e| e.to_string())?;
@@ -4270,30 +4266,30 @@ fn call_tool(params: &Value) -> Result<String, String> {
}
Ok(serde_json::to_string_pretty(&refs_json(&refs)).unwrap())
}
- "get_xrefs_from" => {
+ "get_xrefs_from" => {
let path = args
- .get("path")
+ .get("path")
.and_then(|p| p.as_str())
- .ok_or_else(|| "missing arguments.path".to_string())?;
+ .ok_or_else(|| "missing arguments.path".to_string())?;
let addr = args
- .get("addr")
+ .get("addr")
.and_then(|a| a.as_str())
- .ok_or_else(|| "missing arguments.addr".to_string())?;
- let count = args.get("count").and_then(|c| c.as_u64()).unwrap_or(256) as usize;
+ .ok_or_else(|| "missing arguments.addr".to_string())?;
+ let count = args.get("count").and_then(|c| c.as_u64()).unwrap_or(256) as usize;
let prog = load_path(path).map_err(|e| e.to_string())?;
let va = parse_u64(addr)?;
let refs = xrefs_from(&prog, va, count);
Ok(serde_json::to_string_pretty(&refs_json(&refs)).unwrap())
}
- "get_calls_from" => {
+ "get_calls_from" => {
let path = args
- .get("path")
+ .get("path")
.and_then(|p| p.as_str())
- .ok_or_else(|| "missing arguments.path".to_string())?;
+ .ok_or_else(|| "missing arguments.path".to_string())?;
let addr = args
- .get("addr")
+ .get("addr")
.and_then(|a| a.as_str())
- .ok_or_else(|| "missing arguments.addr".to_string())?;
+ .ok_or_else(|| "missing arguments.addr".to_string())?;
let mut prog = load_path(path).map_err(|e| e.to_string())?;
let va = parse_u64(addr)?;
let (entry, resolve_meta) = friction::resolve_and_entry(&mut prog, Some(va))?;
@@ -4302,44 +4298,44 @@ fn call_tool(params: &Value) -> Result<String, String> {
.iter()
.map(|e| {
json!({
- "from": format!("{:#x}", e.from),
- "to": format!("{:#x}", e.to),
- "kind": e.kind,
- "to_entry": e.to_entry.map(|v| format!("{v:#x}")),
- "to_function": e.to_function,
+ "from": format!("{:#x}", e.from),
+ "to": format!("{:#x}", e.to),
+ "kind": e.kind,
+ "to_entry": e.to_entry.map(|v| format!("{v:#x}")),
+ "to_function": e.to_function,
})
})
.collect();
Ok(serde_json::to_string_pretty(&json!({
- "resolve": resolve_meta,
- "calls": rows,
+ "resolve": resolve_meta,
+ "calls": rows,
}))
.unwrap())
}
- "get_string_xrefs" => {
+ "get_string_xrefs" => {
let path = args
- .get("path")
+ .get("path")
.and_then(|p| p.as_str())
- .ok_or_else(|| "missing arguments.path".to_string())?;
+ .ok_or_else(|| "missing arguments.path".to_string())?;
let filter = args
- .get("filter")
+ .get("filter")
.and_then(|f| f.as_str())
- .ok_or_else(|| "missing arguments.filter".to_string())?;
+ .ok_or_else(|| "missing arguments.filter".to_string())?;
let encoding = args
- .get("encoding")
+ .get("encoding")
.and_then(|e| e.as_str())
- .unwrap_or("all");
+ .unwrap_or("all");
let prog = load_path(path).map_err(|e| e.to_string())?;
let refs = xrefs_to_string_filter_opts(&prog, filter, encoding, true);
Ok(serde_json::to_string_pretty(&refs_json(&refs)).unwrap())
}
- "list_imports" => {
+ "list_imports" => {
let path = args
- .get("path")
+ .get("path")
.and_then(|p| p.as_str())
- .ok_or_else(|| "missing arguments.path".to_string())?;
- let dll = args.get("dll").and_then(|d| d.as_str());
- let name_f = args.get("name").and_then(|n| n.as_str());
+ .ok_or_else(|| "missing arguments.path".to_string())?;
+ let dll = args.get("dll").and_then(|d| d.as_str());
+ let name_f = args.get("name").and_then(|n| n.as_str());
let prog = load_path(path).map_err(|e| e.to_string())?;
let filtered: Vec<_> = filter_imports(&prog.imports, dll, name_f)
.into_iter()
@@ -4347,62 +4343,62 @@ fn call_tool(params: &Value) -> Result<String, String> {
.collect();
Ok(serde_json::to_string_pretty(&filtered).unwrap())
}
- "get_import_xrefs" => {
+ "get_import_xrefs" => {
let path = args
- .get("path")
+ .get("path")
.and_then(|p| p.as_str())
- .ok_or_else(|| "missing arguments.path".to_string())?;
+ .ok_or_else(|| "missing arguments.path".to_string())?;
let iname = args
- .get("name")
+ .get("name")
.and_then(|n| n.as_str())
- .ok_or_else(|| "missing arguments.name".to_string())?;
+ .ok_or_else(|| "missing arguments.name()".to_string())?;
let prog = load_path(path).map_err(|e| e.to_string())?;
let refs = xrefs_to_import(&prog, iname);
Ok(serde_json::to_string_pretty(&refs_json(&refs)).unwrap())
}
- "function_at" | "get_function_by_address" => {
+ "function_at" | "get_function_by_address" => {
let path = args
- .get("path")
+ .get("path")
.and_then(|p| p.as_str())
- .ok_or_else(|| "missing arguments.path".to_string())?;
+ .ok_or_else(|| "missing arguments.path".to_string())?;
let addr = args
- .get("addr")
+ .get("addr")
.and_then(|a| a.as_str())
- .ok_or_else(|| "missing arguments.addr".to_string())?;
+ .ok_or_else(|| "missing arguments.addr".to_string())?;
let mut prog = load_path(path).map_err(|e| e.to_string())?;
if prog.analysis.functions.is_empty() {
- let _ = run_analyzers(&mut prog, &["Function Start Search"]).map_err(|e| e.to_string())?;
+ let _ = run_analyzers(&mut prog, &["Function Start Search"]).map_err(|e| e.to_string())?;
}
let va = parse_u64(addr)?;
match prog.function_containing(va) {
Some(f) => Ok(serde_json::to_string_pretty(&json!({
- "addr": format!("{va:#x}"),
- "entry": format!("{:#x}", f.entry),
- "end": format!("{:#x}", f.end),
- "name": f.name,
- "calling_convention": f.calling_convention,
- "noreturn": f.noreturn,
- "parameters": f.parameters,
- "seed_kind": f.seed_kind,
+ "addr": format!("{va:#x}"),
+ "entry": format!("{:#x}", f.entry),
+ "end": format!("{:#x}", f.end),
+ "name": f.name,
+ "calling_convention": f.calling_convention,
+ "noreturn": f.noreturn,
+ "parameters": f.parameters,
+ "seed_kind": f.seed_kind,
}))
.unwrap()),
None => Ok(serde_json::to_string_pretty(&json!({
- "addr": format!("{va:#x}"),
- "function": null,
+ "addr": format!("{va:#x}"),
+ "function": null,
}))
.unwrap()),
}
}
- "function_create" => {
+ "function_create" => {
let path = args
- .get("path")
+ .get("path")
.and_then(|p| p.as_str())
- .ok_or_else(|| "missing arguments.path".to_string())?;
+ .ok_or_else(|| "missing arguments.path".to_string())?;
let addr = args
- .get("addr")
+ .get("addr")
.and_then(|a| a.as_str())
- .ok_or_else(|| "missing arguments.addr".to_string())?;
- let end = match args.get("end").and_then(|e| e.as_str()) {
+ .ok_or_else(|| "missing arguments.addr".to_string())?;
+ let end = match args.get("end").and_then(|e| e.as_str()) {
Some(e) => Some(parse_u64(e)?),
None => None,
};
@@ -4410,30 +4406,30 @@ fn call_tool(params: &Value) -> Result<String, String> {
let va = parse_u64(addr)?;
let f = create_function(&mut prog, va, end);
Ok(serde_json::to_string_pretty(&json!({
- "entry": format!("{:#x}", f.entry),
- "end": format!("{:#x}", f.end),
- "name": f.name,
- "seed_kind": f.seed_kind,
+ "entry": format!("{:#x}", f.entry),
+ "end": format!("{:#x}", f.end),
+ "name": f.name,
+ "seed_kind": f.seed_kind,
}))
.unwrap())
}
- "list_analyzers" => {
+ "list_analyzers" => {
let cat = analyzer_catalog();
Ok(serde_json::to_string_pretty(&cat).unwrap())
}
- "list_gpu_strategies" => Ok(ghidrust_core::format_matrix_table()),
- "gpu_decompile" => {
+ "list_gpu_strategies" => Ok(ghidrust_core::format_matrix_table()),
+ "gpu_decompile" => {
let path = args
- .get("path")
+ .get("path")
.and_then(|p| p.as_str())
- .ok_or_else(|| "missing arguments.path".to_string())?;
+ .ok_or_else(|| "missing arguments.path".to_string())?;
let out = args
- .get("out")
+ .get("out")
.and_then(|p| p.as_str())
.map(PathBuf::from)
- .unwrap_or_else(|| std::env::temp_dir().join("mcp_gpu_decompile.gdecomp"));
+ .unwrap_or_else(|| std::env::temp_dir().join("mcp_gpu_decompile.gdecomp"));
let mut prog = load_path(path).map_err(|e| e.to_string())?;
- let addr = if let Some(a) = args.get("addr").and_then(|a| a.as_str()) {
+ let addr = if let Some(a) = args.get("addr").and_then(|a| a.as_str()) {
Some(parse_u64(a)?)
} else {
None
@@ -4442,69 +4438,69 @@ fn call_tool(params: &Value) -> Result<String, String> {
let rep = ghidrust_decomp::gpu_decompile_to_file(&prog, Some(entry), &out, 256)
.map_err(|e| e.to_string())?;
Ok(serde_json::to_string_pretty(&json!({
- "resolve": resolve_meta,
- "requested_addr": addr.map(|a| format!("{a:#x}")),
- "resolved_entry": format!("{entry:#x}"),
- "backend": rep.backend,
- "device": rep.device,
- "ms": rep.ms,
- "pcie_upload_ms": rep.pcie_upload_ms,
- "device_ms": rep.device_ms,
- "pcie_download_ms": rep.pcie_download_ms,
- "mid_pipeline_host_reads": rep.mid_pipeline_host_reads,
- "ir_count": rep.ir_count,
- "block_count": rep.block_count,
- "dump_path": rep.dump_path,
- "dump_bytes": rep.dump_bytes,
- "note": ".gdecomp is opaque — use metrics fields, do not read dump as text",
- "pseudo_c_head": rep.pseudo_c.lines().take(8).collect::<Vec<_>>().join("\n"),
+ "resolve": resolve_meta,
+ "requested_addr": addr.map(|a| format!("{a:#x}")),
+ "resolved_entry": format!("{entry:#x}"),
+ "backend": rep.backend,
+ "device": rep.device,
+ "ms": rep.ms,
+ "pcie_upload_ms": rep.pcie_upload_ms,
+ "device_ms": rep.device_ms,
+ "pcie_download_ms": rep.pcie_download_ms,
+ "mid_pipeline_host_reads": rep.mid_pipeline_host_reads,
+ "ir_count": rep.ir_count,
+ "block_count": rep.block_count,
+ "dump_path": rep.dump_path,
+ "dump_bytes": rep.dump_bytes,
+ "note": ".gdecomp is opaque — use metrics fields, do not read dump as text",
+ "pseudo_c_head": rep.pseudo_c.lines().take(8).collect::<Vec<_>>().join("\n"),
}))
.unwrap())
}
- "rtti_gpu_bench" => {
+ "rtti_gpu_bench" => {
let path = args
- .get("path")
+ .get("path")
.and_then(|p| p.as_str())
- .ok_or_else(|| "missing arguments.path".to_string())?;
- // Reuse CLI logic via load + bench (same shipped paths)
+ .ok_or_else(|| "missing arguments.path".to_string())?;
+ // Reuse CLI logic via load + bench (same shipped paths)
let prog = load_path(path).map_err(|e| e.to_string())?;
let t0 = std::time::Instant::now();
let rtti = recover_rtti(&prog).map_err(|e| e.to_string())?;
let cpu_rtti_ms = t0.elapsed().as_secs_f64() * 1000.0;
- let row = ghidrust_core::bench_analyzer(&prog, "WindowsPE x86 PE RTTI Analyzer", None);
+ let row = ghidrust_core::bench_analyzer(&prog, "WindowsPE x86 PE RTTI Analyzer", None);
Ok(serde_json::to_string_pretty(&json!({
- "cpu_rtti_recover_ms": cpu_rtti_ms,
- "cpu_rtti_classes": rtti.classes.len(),
- "gpu_strategy": row.strategy,
- "gpu_pcie_upload_ms": row.gpu_pcie_upload_ms,
- "gpu_device_ms": row.gpu_device_ms,
- "gpu_pcie_download_ms": row.gpu_pcie_download_ms,
- "gpu_pcie_ms": row.gpu_pcie_ms,
- "gpu_wall_ms": row.gpu_wall_ms,
- "gpu_seed_hits": row.gpu_primary,
- "seed_cpu_hits": row.cpu_primary,
- "seed_equal": row.equal,
- "backend": row.backend,
- "device": row.device,
+ "cpu_rtti_recover_ms": cpu_rtti_ms,
+ "cpu_rtti_classes": rtti.classes.len(),
+ "gpu_strategy": row.strategy,
+ "gpu_pcie_upload_ms": row.gpu_pcie_upload_ms,
+ "gpu_device_ms": row.gpu_device_ms,
+ "gpu_pcie_download_ms": row.gpu_pcie_download_ms,
+ "gpu_pcie_ms": row.gpu_pcie_ms,
+ "gpu_wall_ms": row.gpu_wall_ms,
+ "gpu_seed_hits": row.gpu_primary,
+ "seed_cpu_hits": row.cpu_primary,
+ "seed_equal": row.equal,
+ "backend": row.backend,
+ "device": row.device,
}))
.unwrap())
}
- "decompile" => {
+ "decompile" => {
let path = args
- .get("path")
+ .get("path")
.and_then(|p| p.as_str())
- .ok_or_else(|| "missing arguments.path".to_string())?;
- let count = args.get("count").and_then(|c| c.as_u64()).unwrap_or(64) as usize;
+ .ok_or_else(|| "missing arguments.path".to_string())?;
+ let count = args.get("count").and_then(|c| c.as_u64()).unwrap_or(64) as usize;
let stage = args
- .get("stage")
+ .get("stage")
.and_then(|s| s.as_str())
- .unwrap_or("stage1");
+ .unwrap_or("stage1");
let follow_stub = args
- .get("follow_stub")
+ .get("follow_stub")
.and_then(|v| v.as_bool())
.unwrap_or(false);
let mut prog = load_path(path).map_err(|e| e.to_string())?;
- let addr_opt = if let Some(a) = args.get("addr").and_then(|a| a.as_str()) {
+ let addr_opt = if let Some(a) = args.get("addr").and_then(|a| a.as_str()) {
Some(parse_u64(a)?)
} else {
None
@@ -4520,169 +4516,150 @@ fn call_tool(params: &Value) -> Result<String, String> {
follow_meta = Some(fm);
}
}
- let conv = if prog.format.to_ascii_lowercase().contains("pe") {
+ let conv = if prog.format.to_ascii_lowercase().contains("pe") {
ghidrust_types::CallConv::Windows
} else {
ghidrust_types::CallConv::SystemV
};
match stage {
- "stage0" | "stage-0" => {
+ "stage0" | "stage-0" => {
let d =
ghidrust_decomp::decompile_at(&prog, va, count).map_err(|e| e.to_string())?;
let mut obj = json!({
- "stage": "0",
- "resolve": resolve_meta,
- "name": d.name,
- "entry": format!("{:#x}", d.entry),
- "blocks": d.blocks.len(),
- "edges": d.edges.len(),
- "insns": d.insn_count,
- "pseudo_c": d.pseudo_c,
+ "stage": "0",
+ "resolve": resolve_meta,
+ "name": d.name,
+ "entry": format!("{:#x}", d.entry),
+ "blocks": d.blocks.len(),
+ "edges": d.edges.len(),
+ "insns": d.insn_count,
+ "pseudo_c": d.pseudo_c,
});
if let Some(fm) = follow_meta {
- obj.as_object_mut().unwrap().insert("follow_stub".into(), fm);
+ obj.as_object_mut().unwrap().insert("follow_stub".into(), fm);
}
Ok(serde_json::to_string_pretty(&obj).unwrap())
}
- "stage05" | "stage-0.5" | "ir" => {
+ "stage05" | "stage-0.5" | "ir" => {
let (d, cov) = ghidrust_decomp::decompile_ir_at(&prog, va, count)
.map_err(|e| e.to_string())?;
let mut obj = json!({
- "stage": "0.5",
- "resolve": resolve_meta,
- "name": d.name,
- "entry": format!("{:#x}", d.entry),
- "blocks": d.blocks.len(),
- "edges": d.edges.len(),
- "insns": d.insn_count,
- "lift_ratio": cov.ratio(),
- "pseudo_c": d.pseudo_c,
+ "stage": "0.5",
+ "resolve": resolve_meta,
+ "name": d.name,
+ "entry": format!("{:#x}", d.entry),
+ "blocks": d.blocks.len(),
+ "edges": d.edges.len(),
+ "insns": d.insn_count,
+ "lift_ratio": cov.ratio(),
+ "pseudo_c": d.pseudo_c,
});
if let Some(fm) = follow_meta {
- obj.as_object_mut().unwrap().insert("follow_stub".into(), fm);
+ obj.as_object_mut().unwrap().insert("follow_stub".into(), fm);
}
Ok(serde_json::to_string_pretty(&obj).unwrap())
}
_ => {
- // Default: 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 stored_end = prog.function_at(va).map(|f| f.end);
+ let decoded_end = d.blocks.iter().map(|b| b.end).max().unwrap_or(va);
+ let honesty = assess_decompile_bounds(&prog, va, stored_end, decoded_end);
+ let linear = disassemble_range_opts(&prog, va, count, true)
+ .map(|r| r.insns)
+ .unwrap_or_default();
+ let callsite_hints = collect_callsite_hints(&linear);
let mut obj = json!({
- "stage": "1",
- "resolve": resolve_meta,
- "name": d.name,
- "entry": format!("{:#x}", d.entry),
- "blocks": d.blocks.len(),
- "insns": d.insn_count,
- "loops": s1.structure.loops.len(),
- "phis": s1.ssa.phi_count(),
- "locals": s1.types.locals.len(),
- "params": s1.types.params.len(),
- "structs": s1.types.structs.len(),
- "lift_ratio": s1.coverage.ratio(),
- "goto_rate": s1.summary().goto_rate,
- "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,
+ "stage": "1",
+ "resolve": resolve_meta,
+ "name": d.name,
+ "entry": format!("{:#x}", d.entry),
+ "blocks": d.blocks.len(),
+ "insns": d.insn_count,
+ "loops": s1.structure.loops.len(),
+ "phis": s1.ssa.phi_count(),
+ "locals": s1.types.locals.len(),
+ "params": s1.types.params.len(),
+ "structs": s1.types.structs.len(),
+ "lift_ratio": s1.coverage.ratio(),
+ "goto_rate": s1.summary().goto_rate,
+ "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,
+ "callsite_hints": callsite_hints,
});
+ if let Some(m) = obj.as_object_mut() {
+ if let Some(hf) = honesty.to_json_fields().as_object() {
+ for (k, v) in hf {
+ m.insert(k.clone(), v.clone());
+ }
+ }
+ }
if let Some(fm) = follow_meta {
- obj.as_object_mut().unwrap().insert("follow_stub".into(), fm);
+ obj.as_object_mut().unwrap().insert("follow_stub".into(), fm);
}
Ok(serde_json::to_string_pretty(&obj).unwrap())
}
}
}
- "load" | "disassemble" | "rtti" | "analyze" => {
+ "decode_support" => mcp_decode::handle_decode_support(&args),
+ "decode_query" => mcp_decode::handle_decode_query(&args),
+ "disassemble" => mcp_decode::handle_disassemble(&args),
+ "load" | "rtti" | "analyze" => {
match name {
- "load" => {
- let path = if let Some(p) = args.get("path").and_then(|p| p.as_str()) {
+ "load" => {
+ let path = if let Some(p) = args.get("path").and_then(|p| p.as_str()) {
p.to_string()
} else if let (Some(proj), Some(fid)) = (
- args.get("project").and_then(|p| p.as_str()),
- args.get("file_id").and_then(|p| p.as_str()),
+ args.get("project").and_then(|p| p.as_str()),
+ args.get("file_id").and_then(|p| p.as_str()),
) {
let project = Project::open(proj).map_err(|e| e.to_string())?;
let entry = project
.list_files()
.into_iter()
.find(|f| f.id == fid)
- .ok_or_else(|| format!("file_id not found: {fid}"))?;
+ .ok_or_else(|| format!("file_id not found: {fid}"))?;
project
.root
.join(&entry.imported_rel)
.display()
.to_string()
} else {
- return Err("load requires path or project+file_id".into());
+ return Err("load requires path or project+file_id".into());
};
let prog = load_path(&path).map_err(|e| e.to_string())?;
let identity = json!({
- "path": args.get("path").and_then(|p| p.as_str()),
- "project": args.get("project").and_then(|p| p.as_str()),
- "file_id": args.get("file_id").and_then(|p| p.as_str()),
- "resolved_path": path,
+ "path": args.get("path").and_then(|p| p.as_str()),
+ "project": args.get("project").and_then(|p| p.as_str()),
+ "file_id": args.get("file_id").and_then(|p| p.as_str()),
+ "resolved_path": path,
});
Ok(serde_json::to_string_pretty(&friction::load_json_for_prog(
&prog, &identity,
))
.unwrap())
}
- "disassemble" => {
- let path = args
- .get("path")
- .and_then(|p| p.as_str())
- .ok_or_else(|| "missing arguments.path".to_string())?;
- let mut prog = load_path(path).map_err(|e| e.to_string())?;
- let count = args.get("count").and_then(|c| c.as_u64()).unwrap_or(16) as usize;
- let linear = args
- .get("linear")
- .and_then(|v| v.as_bool())
- .unwrap_or(false);
- let addr_opt = if let Some(a) = args.get("addr").and_then(|a| a.as_str()) {
- Some(parse_u64(a)?)
- } else {
- None
- };
- let (start, resolve_meta) = friction::resolve_and_entry(&mut prog, addr_opt)?;
- let bound_end = prog.function_at(start).map(|f| f.end);
- let (mode, bound) = if linear {
- (DisasmMode::Linear, None)
- } else {
- (DisasmMode::Bounded, bound_end)
- };
- let result = disassemble_range_ex(&prog, start, count, true, mode, bound)
- .map_err(|e| e.to_string())?;
- Ok(serde_json::to_string_pretty(&json!({
- "resolve": resolve_meta,
- "mode": mode,
- "stop_reason": result.stop_reason,
- "entry": result.entry.map(|v| format!("{v:#x}")),
- "end": result.end.map(|v| format!("{v:#x}")),
- "decode_gaps": result.decode_gaps,
- "first_gap_va": result.first_gap_va.map(|v| format!("{v:#x}")),
- "insns": result.insns,
- }))
- .unwrap())
- }
- "rtti" => {
+ "rtti" => {
let path = args
- .get("path")
+ .get("path")
.and_then(|p| p.as_str())
- .ok_or_else(|| "missing arguments.path".to_string())?;
+ .ok_or_else(|| "missing arguments.path".to_string())?;
let prog = load_path(path).map_err(|e| e.to_string())?;
let report = recover_rtti(&prog).map_err(|e| e.to_string())?;
Ok(serde_json::to_string_pretty(&report).unwrap())
}
- "analyze" => {
+ "analyze" => {
let path = args
- .get("path")
+ .get("path")
.and_then(|p| p.as_str())
- .ok_or_else(|| "missing arguments.path".to_string())?;
+ .ok_or_else(|| "missing arguments.path".to_string())?;
let mut prog = load_path(path).map_err(|e| e.to_string())?;
let names_owned: Vec<String> = args
- .get("analyzers")
+ .get("analyzers")
.and_then(|a| a.as_array())
.map(|arr| {
arr.iter()
@@ -4692,7 +4669,7 @@ fn call_tool(params: &Value) -> Result<String, String> {
.unwrap_or_default();
let name_refs: Vec<&str> = names_owned.iter().map(|s| s.as_str()).collect();
let use_gpu = args
- .get("gpu")
+ .get("gpu")
.and_then(|g| g.as_bool())
.unwrap_or(false);
let report = ghidrust_core::run_analyzers_opts(&mut prog, &name_refs, use_gpu)
@@ -4702,6 +4679,6 @@ fn call_tool(params: &Value) -> Result<String, String> {
_ => unreachable!(),
}
}
- other => Err(format!("unknown tool: {other}")),
+ other => Err(format!("unknown tool: {other}")),
}
}
diff --git a/crates/ghidrust-cli/src/mcp_decode.rs b/crates/ghidrust-cli/src/mcp_decode.rs
new file mode 100644
index 0000000..6ff1960
--- /dev/null
+++ b/crates/ghidrust-cli/src/mcp_decode.rs
@@ -0,0 +1,198 @@
+//! MCP tools for decode engine.
+
+use crate::decode_opts::{parse_u64, DecodeOpts};
+use crate::decode_query_cmd::run_decode_query;
+use crate::decode_support_cmd::decode_support_json;
+use ghidrust_core::{
+ assess_bounds_honesty, collect_callsite_hints, disassemble_range_ex_opts, load_path, DisasmMode,
+};
+use serde::Serialize;
+use serde_json::{json, Value};
+
+#[derive(Serialize)]
+pub struct McpToolDef {
+ pub name: &'static str,
+ pub description: &'static str,
+ #[serde(rename = "inputSchema")]
+ pub input_schema: Value,
+}
+
+pub fn decode_opts_schema_properties() -> Value {
+ json!({
+ "arch": { "type": "string", "description": "Override architecture (e.g. x86, arm64, riscv)" },
+ "mode": { "type": ["string", "integer"], "description": "mode bits or named mode (64, thumb, mips32, …)" },
+ "syntax": { "type": "string", "enum": ["default", "intel", "att", "noregname", "masm", "motorola", "cs_reg_alias", "percent", "no_dollar", "no_alias_text", "no_alias_text_compressed"] },
+ "detail": { "type": "boolean" },
+ "detail_real": { "type": "boolean" },
+ "skipdata": { "type": "boolean" },
+ "skipdata_mnemonic": { "type": "string" },
+ "skipdata_size": { "type": "integer" },
+ "unsigned_imm": { "type": "boolean" },
+ "only_offset_branch": { "type": "boolean" },
+ "litbase": { "type": ["string", "integer"] },
+ "mnem_overrides": {
+ "type": "array",
+ "items": {
+ "oneOf": [
+ { "type": "string", "description": "ID:MNEMONIC" },
+ { "type": "object", "properties": { "id": { "type": "integer" }, "mnemonic": { "type": "string" } }, "required": ["id", "mnemonic"] }
+ ]
+ }
+ },
+ "linear": { "type": "boolean", "description": "Unbounded linear walk — use first when function bounds are unknown/suspect" },
+ "flow": { "type": "boolean", "description": "Control-flow walk within function bounds (trusted ends)" },
+ "addr": { "type": "string" },
+ "count": { "type": "integer" },
+ "skip_bad": { "type": "boolean" }
+ })
+}
+
+pub fn disassemble_tool_def() -> McpToolDef {
+ let mut props = decode_opts_schema_properties();
+ if let Some(obj) = props.as_object_mut() {
+ obj.insert(
+ "path".to_string(),
+ json!({ "type": "string", "description": "PE/ELF path" }),
+ );
+ }
+ McpToolDef {
+ name: "disassemble",
+ description: "Disassemble with engine: bounded by function end by default; returns listing_text + bounds honesty; use linear:true when bounds suspect",
+ input_schema: json!({
+ "type": "object",
+ "properties": props,
+ "required": ["path"]
+ }),
+ }
+}
+
+pub fn decode_support_tool_def() -> McpToolDef {
+ McpToolDef {
+ name: "decode_support",
+ description: "Decode engine version, supported arches, options, syntax values, and compile features",
+ input_schema: json!({ "type": "object", "properties": {} }),
+ }
+}
+
+pub fn decode_query_tool_def() -> McpToolDef {
+ McpToolDef {
+ name: "decode_query",
+ description: "Engine introspection: insn_name, reg_name, group_name, insn_group, reg_read, reg_write, op_count, op_index, regs_access",
+ input_schema: json!({
+ "type": "object",
+ "properties": {
+ "query": {
+ "type": "string",
+ "enum": ["insn_name", "reg_name", "group_name", "insn_group", "reg_read", "reg_write", "op_count", "op_index", "regs_access"]
+ },
+ "arch": { "type": "string" },
+ "mode": { "type": ["string", "integer"] },
+ "id": { "type": "integer" },
+ "index": { "type": "integer" },
+ "bytes": { "type": "string", "description": "Hex bytes for instruction-dependent queries" },
+ "addr": { "type": "string" },
+ "detail": { "type": "boolean" }
+ },
+ "required": ["query"]
+ }),
+ }
+}
+
+pub fn handle_disassemble(args: &Value) -> Result<String, String> {
+ let path = args
+ .get("path")
+ .and_then(|p| p.as_str())
+ .ok_or_else(|| "missing arguments.path".to_string())?;
+ let opts = DecodeOpts::from_json(args)?;
+ let mut prog = load_path(path).map_err(|e| e.to_string())?;
+ let engine_opts = opts.to_engine_opts();
+
+ let addr_opt = if let Some(a) = args.get("addr").and_then(|a| a.as_str()) {
+ Some(parse_u64(a)?)
+ } else {
+ opts.addr
+ };
+ let (start, resolve_meta) = crate::friction::resolve_and_entry(&mut prog, addr_opt)?;
+ let bound_end = prog.function_at(start).map(|f| f.end);
+
+ let (mode, bound) = if opts.linear {
+ (DisasmMode::Linear, None)
+ } else if opts.flow {
+ (DisasmMode::Flow, bound_end)
+ } else {
+ (DisasmMode::Bounded, bound_end)
+ };
+
+ let result = disassemble_range_ex_opts(
+ &prog,
+ start,
+ opts.count,
+ opts.skip_bad,
+ mode,
+ bound,
+ Some(&engine_opts),
+ )
+ .map_err(|e| e.to_string())?;
+
+ let honesty = assess_bounds_honesty(
+ &prog,
+ result.entry.or(Some(start)),
+ result.end.or(bound),
+ result.insns.len(),
+ result.stop_reason,
+ );
+ let callsite_hints = collect_callsite_hints(&result.insns);
+ let listing_text: String = result
+ .insns
+ .iter()
+ .map(|i| i.brief_text())
+ .collect::<Vec<_>>()
+ .join("\n");
+
+ let mut body = json!({
+ "resolve": resolve_meta,
+ "mode": mode,
+ "stop_reason": result.stop_reason,
+ "entry": result.entry.map(|v| format!("{v:#x}")),
+ "end": result.end.map(|v| format!("{v:#x}")),
+ "decode_gaps": result.decode_gaps,
+ "first_gap_va": result.first_gap_va.map(|v| format!("{v:#x}")),
+ "listing_text": listing_text,
+ "callsite_hints": callsite_hints,
+ "insns": result.insns,
+ });
+ if let Some(obj) = body.as_object_mut() {
+ if let Some(m) = honesty.to_json_fields().as_object() {
+ for (k, v) in m {
+ obj.insert(k.clone(), v.clone());
+ }
+ }
+ }
+
+ Ok(serde_json::to_string_pretty(&body).unwrap())
+}
+
+pub fn handle_decode_support(_args: &Value) -> Result<String, String> {
+ Ok(serde_json::to_string_pretty(&decode_support_json()).unwrap())
+}
+
+pub fn handle_decode_query(args: &Value) -> Result<String, String> {
+ let body = run_decode_query(args)?;
+ Ok(serde_json::to_string_pretty(&body).unwrap())
+}
+
+pub fn server_info_decode_section() -> Value {
+ let support = decode_support_json();
+ json!({
+ "decode": {
+ "version": support.get("version"),
+ "arches": support.get("arches"),
+ "options": support.get("options"),
+ "syntax_values()": support.get("syntax_values()"),
+ },
+ "features": {
+ "decode_diet": support["features"]["decode_diet"],
+ "x86_reduce": support["features"]["x86_reduce"],
+ }
+ })
+}
diff --git a/crates/ghidrust-cli/tests/cli_mcp.rs b/crates/ghidrust-cli/tests/cli_mcp.rs
index 2b85c1b..e25d723 100644
--- a/crates/ghidrust-cli/tests/cli_mcp.rs
+++ b/crates/ghidrust-cli/tests/cli_mcp.rs
@@ -13,10 +13,14 @@ fn bin() -> Command {
fn cli_load_and_rtti_fixture() {
let pe = fixture_path("tiny_x64.pe");
let out = bin()
- .args(["rtti", pe.to_str().unwrap(), "--json"])
+ .args(["rtti", pe.to_str().unwrap(), "-json"])
.output()
.expect("run cli");
- assert!(out.status.success(), "stderr={}", String::from_utf8_lossy(&out.stderr));
+ assert!(
+ out.status.success(),
+ "stderr={}",
+ String::from_utf8_lossy(&out.stderr)
+ );
let s = String::from_utf8_lossy(&out.stdout);
assert!(s.contains("Widget"), "stdout={s}");
}
@@ -25,7 +29,7 @@ fn cli_load_and_rtti_fixture() {
fn cli_disasm_fixture() {
let pe = fixture_path("tiny_x64.pe");
let out = bin()
- .args(["disasm", pe.to_str().unwrap(), "--count", "5"])
+ .args(["disasm", pe.to_str().unwrap(), "-count", "5"])
.output()
.expect("run");
assert!(out.status.success());
@@ -33,12 +37,78 @@ fn cli_disasm_fixture() {
assert!(s.contains("push") && s.contains("ret"), "{s}");
}
+#[test]
+fn cli_disasm_pretty_brief_and_text_out() {
+ let pe = fixture_path("tiny_x64.pe");
+ let pe_s = pe.to_str().unwrap();
+
+ let pretty = bin()
+ .args(["disasm", pe_s, "--count", "8", "--pretty"])
+ .output()
+ .expect("pretty");
+ assert!(
+ pretty.status.success(),
+ "stderr={}",
+ String::from_utf8_lossy(&pretty.stderr)
+ );
+ let pretty_s = String::from_utf8_lossy(&pretty.stdout);
+ assert!(pretty_s.contains("; entry="), "{pretty_s}");
+ assert!(pretty_s.contains("push") || pretty_s.contains("ret"), "{pretty_s}");
+
+ let brief = bin()
+ .args(["disasm", pe_s, "-count", "5", "-brief"])
+ .output()
+ .expect("brief");
+ assert!(brief.status.success());
+ let brief_s = String::from_utf8_lossy(&brief.stdout);
+ assert!(brief_s.contains("0x") && brief_s.contains(':'), "{brief_s}");
+
+ let tmp = std::env::temp_dir().join("ghidrust_disasm_brief_out.txt");
+ let _ = std::fs::remove_file(&tmp);
+ let out = bin()
+ .args([
+ "disasm",
+ pe_s,
+ "-count",
+ "5",
+ "-brief",
+ "-out",
+ tmp.to_str().unwrap(),
+ ])
+ .output()
+ .expect("out");
+ assert!(
+ out.status.success(),
+ "stderr={}",
+ String::from_utf8_lossy(&out.stderr)
+ );
+ let file = std::fs::read_to_string(&tmp).expect("read text out");
+ assert!(file.contains(':') && !file.trim_start().starts_with('{'), "{file}");
+ let _ = std::fs::remove_file(&tmp);
+
+ let json = bin()
+ .args(["disasm", pe_s, "-count", "5", "-json"])
+ .output()
+ .expect("json");
+ assert!(json.status.success());
+ let js = String::from_utf8_lossy(&json.stdout);
+ assert!(js.contains("listing_text"), "{js}");
+ assert!(js.contains("bounds_suspect"), "{js}");
+}
+
#[test]
fn cli_analyzers_all_implemented() {
- let out = bin().args(["analyzers", "--json"]).output().expect("analyzers");
+ let out = bin()
+ .args(["analyzers", "-json"])
+ .output()
+ .expect("analyzers");
assert!(out.status.success());
let s = String::from_utf8_lossy(&out.stdout);
- assert!(s.contains("\"status\": \"implemented\"") || s.contains("Implemented") || s.contains("implemented"));
+ assert!(
+ s.contains("\"status\": \"implemented\"")
+ || s.contains("Implemented")
+ || s.contains("implemented")
+ );
assert!(!s.contains("not_implemented") && !s.contains("NotImplemented"));
}
@@ -47,15 +117,19 @@ fn cli_analyze_multi_ok() {
let pe = fixture_path("analysis_lab.pe");
let out = bin()
.args([
- "analyze",
+ "analyze",
pe.to_str().unwrap(),
- "--analyzers",
- "Function Start Search,Function ID,ASCII Strings,Call-Fixup Installer,Embedded Media,PDB Universal,Create Address Tables",
- "--json",
+ "-analyzers",
+ "Function Start Search,Function ID,ASCII Strings,Call-Fixup Installer,Embedded Media,PDB Universal,Create Address Tables",
+ "-json",
])
.output()
- .expect("analyze");
- assert!(out.status.success(), "stderr={}", String::from_utf8_lossy(&out.stderr));
+ .expect("analyze");
+ assert!(
+ out.status.success(),
+ "stderr={}",
+ String::from_utf8_lossy(&out.stderr)
+ );
let s = String::from_utf8_lossy(&out.stdout);
assert!(!s.contains("not_implemented"));
assert!(s.contains("security_cookie"), "{s}");
@@ -80,16 +154,20 @@ fn mcp_list_and_analyze() {
"{}\n{}\n",
json!({"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}),
json!({"jsonrpc":"2.0","id":2,"method":"tools/call","params":{
- "name":"analyze","arguments":{
- "path": pe_s,
- "analyzers": ["ASCII Strings", "WindowsPE x86 PE RTTI Analyzer", "Function Start Search"]
- }
- }}),
+ "name":"analyze","arguments":{
+ "path": pe_s,
+ "analyzers": ["ASCII Strings", "WindowsPE x86 PE RTTI Analyzer", "Function Start Search"]
+ }
+ }}),
);
stdin.write_all(reqs.as_bytes()).unwrap();
drop(stdin);
let out = child.wait_with_output().unwrap();
- assert!(out.status.success(), "stderr={}", String::from_utf8_lossy(&out.stderr));
+ assert!(
+ out.status.success(),
+ "stderr={}",
+ String::from_utf8_lossy(&out.stderr)
+ );
let s = String::from_utf8_lossy(&out.stdout);
assert!(s.contains("Widget") || s.contains("ok"), "{s}");
}
@@ -101,16 +179,23 @@ fn cli_strings_utf16_and_json_no_bom() {
.args([
"strings",
pe.to_str().unwrap(),
- "--encoding",
+ "-encoding",
"utf16",
- "--filter",
+ "-filter",
"WideLabString",
- "--json",
+ "-json",
])
.output()
.expect("strings");
- assert!(out.status.success(), "stderr={}", String::from_utf8_lossy(&out.stderr));
- assert!(!out.stdout.starts_with(&[0xEF, 0xBB, 0xBF]), "JSON must be BOM-free");
+ assert!(
+ out.status.success(),
+ "stderr={}",
+ String::from_utf8_lossy(&out.stderr)
+ );
+ assert!(
+ !out.stdout.starts_with(&[0xEF, 0xBB, 0xBF]),
+ "JSON must be BOM-free"
+ );
assert_eq!(out.stdout.first().copied(), Some(b'['));
let s = String::from_utf8_lossy(&out.stdout);
assert!(s.contains("WideLabString"), "{s}");
@@ -124,13 +209,17 @@ fn cli_function_at_entry() {
.args([
"function-at",
pe.to_str().unwrap(),
- "--addr",
+ "-addr",
"0x140001000",
- "--json",
+ "-json",
])
.output()
.expect("function-at");
- assert!(out.status.success(), "stderr={}", String::from_utf8_lossy(&out.stderr));
+ assert!(
+ out.status.success(),
+ "stderr={}",
+ String::from_utf8_lossy(&out.stderr)
+ );
let s = String::from_utf8_lossy(&out.stdout);
assert!(s.contains("0x140001000"), "{s}");
}
@@ -139,10 +228,14 @@ fn cli_function_at_entry() {
fn cli_imports_lists_slots() {
let pe = fixture_path("analysis_lab.pe");
let out = bin()
- .args(["imports", pe.to_str().unwrap(), "--json"])
+ .args(["imports", pe.to_str().unwrap(), "-json"])
.output()
.expect("imports");
- assert!(out.status.success(), "stderr={}", String::from_utf8_lossy(&out.stderr));
+ assert!(
+ out.status.success(),
+ "stderr={}",
+ String::from_utf8_lossy(&out.stderr)
+ );
let s = String::from_utf8_lossy(&out.stdout);
// Lab fixture imports at least one named symbol when the PE directory is present.
assert!(s.starts_with('[') || s.contains("iat_va"), "{s}");
@@ -181,8 +274,12 @@ fn mcp_lists_new_lookup_tools() {
#[test]
fn cli_version_matches_package() {
- let out = bin().args(["--version"]).output().expect("version");
- assert!(out.status.success(), "stderr={}", String::from_utf8_lossy(&out.stderr));
+ let out = bin().args(["-version"]).output().expect("version");
+ assert!(
+ out.status.success(),
+ "stderr={}",
+ String::from_utf8_lossy(&out.stderr)
+ );
let s = String::from_utf8_lossy(&out.stdout);
assert!(
s.contains(env!("CARGO_PKG_VERSION")),
@@ -204,22 +301,29 @@ fn mcp_server_info_and_live_tools() {
let reqs = format!(
"{}\n{}\n{}\n",
json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{
- "protocolVersion":"2024-11-05",
- "capabilities":{},
- "clientInfo":{"name":"test","version":"0"}
- }}),
+ "protocolVersion":"2024-11-05",
+ "capabilities":{},
+ "clientInfo":{"name":"test","version":"0"}
+ }}),
json!({"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}),
json!({"jsonrpc":"2.0","id":3,"method":"tools/call","params":{
- "name":"server_info","arguments":{}
- }}),
+ "name":"server_info","arguments":{}
+ }}),
);
stdin.write_all(reqs.as_bytes()).unwrap();
drop(stdin);
let out = child.wait_with_output().unwrap();
- assert!(out.status.success(), "stderr={}", String::from_utf8_lossy(&out.stderr));
+ assert!(
+ out.status.success(),
+ "stderr={}",
+ String::from_utf8_lossy(&out.stderr)
+ );
let s = String::from_utf8_lossy(&out.stdout);
let ver = env!("CARGO_PKG_VERSION");
- assert!(s.contains(ver), "initialize/server_info missing version {ver}: {s}");
+ assert!(
+ s.contains(ver),
+ "initialize/server_info missing version {ver}: {s}"
+ );
assert!(
s.contains("toolSurface") || s.contains("tool_surface"),
"missing tool_surface in {s}"
@@ -228,6 +332,8 @@ fn mcp_server_info_and_live_tools() {
"server_info",
"process_list",
"process_attach",
+ "process_launch",
+ "process_resume",
"process_resolve",
"process_read",
"artifact_query",
diff --git a/crates/ghidrust-cli/tests/eval_analysis_decompile.rs b/crates/ghidrust-cli/tests/eval_analysis_decompile.rs
index ff500c9..fbc9566 100644
--- a/crates/ghidrust-cli/tests/eval_analysis_decompile.rs
+++ b/crates/ghidrust-cli/tests/eval_analysis_decompile.rs
@@ -5,12 +5,12 @@
//!
//! Oracles are pulled from the shipped analyzer test contract
//! (`crates/ghidrust-core/tests/analyzer_content.rs`) and the decompile crate
-//! tests. No Hex-Rays / Ghidra parity is claimed — only in-repo expectations.
+//! tests. No commercial decompiler / C output is claimed — only in-repo expectations.
//!
//! Re-run:
-//! cargo test -p ghidrust-cli --test eval_analysis_decompile -- --nocapture
-//! # optional release timing:
-//! cargo test -p ghidrust-cli --test eval_analysis_decompile --release -- --nocapture
+//! cargo test -p ghidrust-cli -test eval_analysis_decompile - -nocapture
+//! # optional release timing:
+//! cargo test -p ghidrust-cli -test eval_analysis_decompile -release - -nocapture
use serde::Serialize;
use serde_json::{json, Value};
@@ -18,7 +18,7 @@ use std::path::{Path, PathBuf};
use std::process::Command;
use std::time::Instant;
-// ---------- paths / helpers ----------
+// ----- paths / helpers -----
fn bin() -> PathBuf {
PathBuf::from(env!("CARGO_BIN_EXE_ghidrust"))
@@ -44,7 +44,7 @@ fn dev_dir() -> PathBuf {
p
}
-// ---------- eval row ----------
+// ----- eval row -----
#[derive(Serialize, Debug, Clone)]
struct EvalRow {
@@ -60,11 +60,11 @@ struct EvalRow {
error: Option<String>,
}
-// ---------- subprocess wrapper ----------
+// ----- subprocess wrapper -----
fn run_ghidrust(args: &[&str]) -> (bool, String, String, f64) {
let t = Instant::now();
- let out = Command::new(bin()).args(args).output().expect("spawn ghidrust");
+ let out = Command::new(bin).args(args).output.expect("spawn ghidrust");
let elapsed_ms = t.elapsed().as_secs_f64() * 1000.0;
(
out.status.success(),
@@ -78,16 +78,16 @@ fn parse_json_lossy(s: &str) -> Option<Value> {
serde_json::from_str::<Value>(s).ok()
}
-// ---------- per-analyzer oracle ----------
+// ----- per-analyzer oracle -----
//
// Contract mirrors `crates/ghidrust-core/tests/analyzer_content.rs`. Some
// analyzers require prerequisite state (Function Start Search recovers
// function starts first). For CLI invocations we compose that in a single
-// `--analyzers "Function Start Search,<target>"` call and match on the
+// `-analyzers "Function Start Search,<target>"` call and match on the
// target's result.
struct AnalyzerCheck {
- /// Ghidra label
+ /// label
name: &'static str,
/// Fixture file name in `fixtures/`
fixture: &'static str,
@@ -101,8 +101,10 @@ struct AnalyzerCheck {
}
fn oracle_ascii_strings(v: &Value) -> (bool, String, Value) {
- let s = v["strings"].as_array().cloned().unwrap_or_default();
- let has_exit = s.iter().any(|x| x["value"].as_str().unwrap_or("").contains("ExitProcess"));
+ let s = v["strings"].as_array.cloned().unwrap_or_default();
+ let has_exit = s
+ .iter()
+ .any(|x| x["value"].as_str().unwrap_or("").contains("ExitProcess"));
let has_extra = s.iter().any(|x| {
let val = x["value"].as_str().unwrap_or("");
val.contains("printf") || val.contains("LabClass") || val.contains("MyFunc")
@@ -110,138 +112,169 @@ fn oracle_ascii_strings(v: &Value) -> (bool, String, Value) {
let ok = has_exit && has_extra;
(
ok,
- format!("{} strings; ExitProcess={} extra={}", s.len(), has_exit, has_extra),
- json!({ "count": s.len(), "has_exitprocess": has_exit, "has_lab_or_myfunc": has_extra }),
+ format!(
+ "{} strings; ExitProcess={} extra={}",
+ s.len, has_exit, has_extra
+ ),
+ json!({ "count": s.len, "has_exitprocess": has_exit, "has_lab_or_myfunc": has_extra }),
)
}
fn oracle_unicode_strings(v: &Value) -> (bool, String, Value) {
- let s = v["strings"].as_array().cloned().unwrap_or_default();
+ let s = v["strings"].as_array.cloned().unwrap_or_default();
let has_wide = s.iter().any(|x| {
x["value"].as_str().unwrap_or("").contains("WideLabString")
&& x["encoding"].as_str().unwrap_or("") == "utf16le"
});
(
has_wide,
- format!("{} utf16 strings; WideLabString={}", s.len(), has_wide),
- json!({ "count": s.len(), "has_wide_lab": has_wide }),
+ format!("{} utf16 strings; WideLabString={}", s.len, has_wide),
+ json!({ "count": s.len, "has_wide_lab": has_wide }),
)
}
fn oracle_function_start(v: &Value) -> (bool, String, Value) {
- let fns = v["functions"].as_array().cloned().unwrap_or_default();
- let hex = |x: &Value| x["entry"].as_u64().unwrap_or(0);
+ let fns = v["functions"].as_array.cloned().unwrap_or_default();
+ let hex = |x: &Value| x["entry"].as_u64.unwrap_or(0);
let has_entry = fns.iter().any(|f| hex(f) == 0x140001000);
- let has_prologue = fns
- .iter()
- .any(|f| { let e = hex(f); e == 0x140001030 || e == 0x140001018 });
+ let has_prologue = fns.iter().any(|f| {
+ let e = hex(f);
+ e == 0x140001030 || e == 0x140001018
+ });
let has_mid = fns.iter().any(|f| hex(f) == 0x140001034);
let ok = has_entry && has_prologue && !has_mid;
(
ok,
format!(
"{} functions; entry={} prologue={} mid_prologue_seed={}",
- fns.len(), has_entry, has_prologue, has_mid
+ fns.len(),
+ has_entry,
+ has_prologue,
+ has_mid
),
- json!({ "count": fns.len(), "has_entry": has_entry, "has_prologue": has_prologue, "has_mid_prologue_bug": has_mid }),
+ json!({ "count": fns.len, "has_entry": has_entry, "has_prologue": has_prologue, "has_mid_prologue_bug": has_mid }),
)
}
fn oracle_aggressive(v: &Value) -> (bool, String, Value) {
// With CLI we can't retain-only-entry state; accept status=ok and (ideally) some ranges.
- let ranges = v["recovered_ranges"].as_array().cloned().unwrap_or_default();
+ let ranges = v["recovered_ranges"].as_array.cloned().unwrap_or_default();
let status_ok = v["status"].as_str() == Some("ok");
let ok = status_ok;
(
ok,
format!(
"status=ok={} recovered_ranges={} (CLI cannot force gap-only state)",
- status_ok, ranges.len()
+ status_ok,
+ ranges.len()
),
- json!({ "status_ok": status_ok, "recovered_ranges": ranges.len() }),
+ json!({ "status_ok": status_ok, "recovered_ranges": ranges.len }),
)
}
fn oracle_call_convention(v: &Value) -> (bool, String, Value) {
- let c = v["conventions"].as_array().cloned().unwrap_or_default();
+ let c = v["conventions"].as_array.cloned().unwrap_or_default();
let has_entry = c.iter().any(|pair| {
pair.as_array()
- .map(|arr| arr.first().and_then(|x| x.as_u64()).unwrap_or(0) == 0x140001000
- && arr.get(1).and_then(|x| x.as_str()).unwrap_or("").len() > 0)
+ .map(|arr| {
+ arr.first().and_then(|x| x.as_u64()).unwrap_or(0) == 0x140001000
+ && arr.get(1).and_then(|x| x.as_str()).unwrap_or("").len > 0
+ })
.unwrap_or(false)
});
(
has_entry,
- format!("{} entries; entry@0x140001000 tagged={}", c.len(), has_entry),
- json!({ "count": c.len(), "has_entry_tag": has_entry }),
+ format!("{} entries; entry@0x140001000 tagged={}", c.len, has_entry),
+ json!({ "count": c.len, "has_entry_tag": has_entry }),
)
}
fn oracle_call_fixup(v: &Value) -> (bool, String, Value) {
- let f = v["call_fixups"].as_array().cloned().unwrap_or_default();
- let has_cookie = f.iter().any(|x| x["fixup_name"].as_str() == Some("security_cookie"));
- let cookie_va = f.iter().any(|x| x["call_va"].as_u64() == Some(0x140002018));
+ let f = v["call_fixups"].as_array.cloned().unwrap_or_default();
+ let has_cookie = f
+ .iter()
+ .any(|x| x["fixup_name"].as_str() == Some("security_cookie"));
+ let cookie_va = f.iter().any(|x| x["call_va"].as_u64 == Some(0x140002018));
let ok = has_cookie && cookie_va;
(
ok,
- format!("{} fixups; security_cookie={} @0x140002018={}", f.len(), has_cookie, cookie_va),
- json!({ "count": f.len(), "has_security_cookie": has_cookie, "cookie_va_ok": cookie_va }),
+ format!(
+ "{} fixups; security_cookie={} @0x140002018={}",
+ f.len, has_cookie, cookie_va
+ ),
+ json!({ "count": f.len, "has_security_cookie": has_cookie, "cookie_va_ok": cookie_va }),
)
}
fn oracle_address_tables(v: &Value) -> (bool, String, Value) {
- let t = v["address_tables"].as_array().cloned().unwrap_or_default();
+ let t = v["address_tables"].as_array.cloned().unwrap_or_default();
let hit = t.iter().find(|tab| {
- tab["base"].as_u64() == Some(0x140002070) && tab["count"].as_u64().unwrap_or(0) >= 3
+ tab["base"].as_u64 == Some(0x140002070) && tab["count"].as_u64.unwrap_or(0) >= 3
});
let contains_target = hit
- .and_then(|tab| tab["entries"].as_array())
+ .and_then(|tab| tab["entries"].as_array)
.map(|arr| arr.iter().any(|e| e.as_u64() == Some(0x140001030)))
.unwrap_or(false);
let ok = hit.is_some() && contains_target;
(
ok,
- format!("{} tables; jump-table @0x140002070 with 0x140001030 entry={}", t.len(), ok),
- json!({ "count": t.len(), "jump_table_ok": ok }),
+ format!(
+ "{} tables; jump-table @0x140002070 with 0x140001030 entry={}",
+ t.len, ok
+ ),
+ json!({ "count": t.len, "jump_table_ok": ok }),
)
}
fn oracle_decomp_param(v: &Value) -> (bool, String, Value) {
- let fns = v["functions"].as_array().cloned().unwrap_or_default();
- let stack_fn = fns.iter().find(|f| f["entry"].as_u64() == Some(0x140001030));
+ let fns = v["functions"].as_array.cloned().unwrap_or_default();
+ let stack_fn = fns.iter().find(|f| f["entry"].as_u64 == Some(0x140001030));
let has_rcx = stack_fn
- .and_then(|f| f["parameters"].as_array())
+ .and_then(|f| f["parameters"].as_array)
.map(|arr| arr.iter().any(|p| p.as_str().unwrap_or("").contains("rcx")))
.unwrap_or(false);
(
has_rcx,
- format!("func_stack@0x140001030 parameters contain 'rcx': {}", has_rcx),
+ format!(
+ "func_stack@0x140001030 parameters contain 'rcx': {}",
+ has_rcx
+ ),
json!({ "func_stack_rcx": has_rcx }),
)
}
fn oracle_decomp_switch(v: &Value) -> (bool, String, Value) {
- let sw = v["switches"].as_array().cloned().unwrap_or_default();
+ let sw = v["switches"].as_array.cloned().unwrap_or_default();
let ok = sw
.first()
.map(|s| {
- s["jump_va"].as_u64() == Some(0x140002070)
- && s["cases"].as_array().map(|c| c.len() >= 2).unwrap_or(false)
+ s["jump_va"].as_u64 == Some(0x140002070)
+ && s["cases"].as_array.map(|c| c.len >= 2).unwrap_or(false)
&& s["cases"]
.as_array()
- .map(|c| c.iter().any(|pair| pair.as_array().and_then(|a| a.get(1)).and_then(|x| x.as_u64()) == Some(0x140001030)))
+ .map(|c| {
+ c.iter().any(|pair| {
+ pair.as_array()
+ .and_then(|a| a.get(1))
+ .and_then(|x| x.as_u64())
+ == Some(0x140001030)
+ })
+ })
.unwrap_or(false)
})
.unwrap_or(false);
(
ok,
- format!("switches={} jump_va=0x140002070 case→0x140001030 {}", sw.len(), ok),
- json!({ "switches": sw.len(), "jump_table_recovered": ok }),
+ format!(
+ "switches={} jump_va=0x140002070 case→0x140001030 {}",
+ sw.len, ok
+ ),
+ json!({ "switches": sw.len, "jump_table_recovered": ok }),
)
}
fn oracle_demangler(v: &Value) -> (bool, String, Value) {
- let s = v["symbols"].as_array().cloned().unwrap_or_default();
+ let s = v["symbols"].as_array.cloned().unwrap_or_default();
let ok = s.iter().any(|x| {
let dem = x["demangled"].as_str().unwrap_or("");
let name = x["name"].as_str().unwrap_or("");
@@ -249,49 +282,56 @@ fn oracle_demangler(v: &Value) -> (bool, String, Value) {
});
(
ok,
- format!("{} symbols; MyFunc/LabClass demangle={}", s.len(), ok),
- json!({ "count": s.len(), "demangled_ok": ok }),
+ format!("{} symbols; MyFunc/LabClass demangle={}", s.len, ok),
+ json!({ "count": s.len, "demangled_ok": ok }),
)
}
fn oracle_embedded_media(v: &Value) -> (bool, String, Value) {
- let m = v["media"].as_array().cloned().unwrap_or_default();
- let ok = m.iter().any(|h| h["kind"].as_str() == Some("PNG") && h["va"].as_u64() == Some(0x140002050));
+ let m = v["media"].as_array.cloned().unwrap_or_default();
+ let ok = m
+ .iter()
+ .any(|h| h["kind"].as_str() == Some("PNG") && h["va"].as_u64 == Some(0x140002050));
(
ok,
- format!("{} media; PNG@0x140002050={}", m.len(), ok),
- json!({ "count": m.len(), "png_ok": ok }),
+ format!("{} media; PNG@0x140002050={}", m.len, ok),
+ json!({ "count": m.len, "png_ok": ok }),
)
}
fn oracle_function_id(v: &Value) -> (bool, String, Value) {
- let m = v["fid_matches"].as_array().cloned().unwrap_or_default();
+ let m = v["fid_matches"].as_array.cloned().unwrap_or_default();
let ok = m.iter().any(|x| {
- x["entry"].as_u64() == Some(0x140001000)
+ x["entry"].as_u64 == Some(0x140001000)
&& x["matched_name"].as_str().unwrap_or("").contains("fid_")
});
(
ok,
- format!("{} FID matches; entry+fid_ prefix={}", m.len(), ok),
- json!({ "count": m.len(), "fid_entry_ok": ok }),
+ format!("{} FID matches; entry+fid_ prefix={}", m.len, ok),
+ json!({ "count": m.len, "fid_entry_ok": ok }),
)
}
fn oracle_noreturn(v: &Value) -> (bool, String, Value) {
- let n = v["noreturn_entries"].as_array().cloned().unwrap_or_default();
+ let n = v["noreturn_entries"].as_array.cloned().unwrap_or_default();
let has_api = n.iter().any(|x| x.as_u64() == Some(0x140002000));
let has_body = n.iter().any(|x| x.as_u64() == Some(0x140001050));
let ok = has_api && has_body;
(
ok,
- format!("{} noreturn entries; ExitProcess VA={} func_nr@0x50={}", n.len(), has_api, has_body),
- json!({ "count": n.len(), "exitprocess_va": has_api, "func_nr_body": has_body }),
+ format!(
+ "{} noreturn entries; ExitProcess VA={} func_nr@0x50={}",
+ n.len, has_api, has_body
+ ),
+ json!({ "count": n.len, "exitprocess_va": has_api, "func_nr_body": has_body }),
)
}
fn oracle_pdb_universal(v: &Value) -> (bool, String, Value) {
- let s = v["symbols"].as_array().cloned().unwrap_or_default();
- let has_msf = s.iter().any(|x| x["name"].as_str().unwrap_or("").contains("MSF7"));
+ let s = v["symbols"].as_array.cloned().unwrap_or_default();
+ let has_msf = s
+ .iter()
+ .any(|x| x["name"].as_str().unwrap_or("").contains("MSF7"));
let has_lab = s.iter().any(|x| {
let n = x["name"].as_str().unwrap_or("");
n == "LabEntry" || n == "LabStackFrame"
@@ -299,137 +339,287 @@ fn oracle_pdb_universal(v: &Value) -> (bool, String, Value) {
let ok = has_msf && has_lab;
(
ok,
- format!("{} symbols; MSF7 marker={} Lab* stream={}", s.len(), has_msf, has_lab),
- json!({ "count": s.len(), "msf7": has_msf, "lab_stream": has_lab }),
+ format!(
+ "{} symbols; MSF7 marker={} Lab* stream={}",
+ s.len, has_msf, has_lab
+ ),
+ json!({ "count": s.len, "msf7": has_msf, "lab_stream": has_lab }),
)
}
fn oracle_pdb_msdia(v: &Value) -> (bool, String, Value) {
- let s = v["symbols"].as_array().cloned().unwrap_or_default();
+ let s = v["symbols"].as_array.cloned().unwrap_or_default();
let ok = s.iter().any(|x| {
let n = x["name"].as_str().unwrap_or("");
n == "LabNoReturn" || n.contains("Lab")
});
(
ok,
- format!("{} symbols; Lab* {}", s.len(), ok),
- json!({ "count": s.len(), "lab_symbol": ok }),
+ format!("{} symbols; Lab* {}", s.len, ok),
+ json!({ "count": s.len, "lab_symbol": ok }),
)
}
fn oracle_shared_return(v: &Value) -> (bool, String, Value) {
- let s = v["shared_returns"].as_array().cloned().unwrap_or_default();
+ let s = v["shared_returns"].as_array.cloned().unwrap_or_default();
let ok = s.len() >= 2
- && s.iter()
- .any(|e| { let x = e.as_u64().unwrap_or(0); x == 0x140001070 || x == 0x140001090 });
+ && s.iter().any(|e| {
+ let x = e.as_u64().unwrap_or(0);
+ x == 0x140001070 || x == 0x140001090
+ });
(
ok,
- format!("{} shared-return sites; ≥2 with func_a/func_b VA={}", s.len(), ok),
- json!({ "count": s.len(), "func_ab_hit": ok }),
+ format!(
+ "{} shared-return sites; ≥2 with func_a/func_b VA={}",
+ s.len, ok
+ ),
+ json!({ "count": s.len, "func_ab_hit": ok }),
)
}
fn oracle_stack(v: &Value) -> (bool, String, Value) {
- let frames = v["stack_frames"].as_array().cloned().unwrap_or_default();
+ let frames = v["stack_frames"].as_array.cloned().unwrap_or_default();
let hit = frames.iter().find(|pair| {
- pair.as_array().and_then(|a| a.first()).and_then(|x| x.as_u64()) == Some(0x140001030)
+ pair.as_array()
+ .and_then(|a| a.first())
+ .and_then(|x| x.as_u64())
+ == Some(0x140001030)
});
let has_frame_size = hit
.and_then(|pair| pair.as_array())
.and_then(|a| a.get(1))
.and_then(|arr| arr.as_array())
- .map(|locs| locs.iter().any(|l| { let s = l.as_str().unwrap_or(""); s.contains("frame_size=0x20") || s.contains("param_") }))
+ .map(|locs| {
+ locs.iter().any(|l| {
+ let s = l.as_str().unwrap_or("");
+ s.contains("frame_size=0x20") || s.contains("param_")
+ })
+ })
.unwrap_or(false);
let entry_not_polluted = !frames.iter().any(|pair| {
- pair.as_array().and_then(|a| a.first()).and_then(|x| x.as_u64()) == Some(0x140001000)
+ pair.as_array()
+ .and_then(|a| a.first())
+ .and_then(|x| x.as_u64())
+ == Some(0x140001000)
});
let ok = has_frame_size && entry_not_polluted;
(
ok,
format!(
"{} frames; func_stack@0x140001030 frame_size/param={} entry_pollution={}",
- frames.len(), has_frame_size, !entry_not_polluted
+ frames.len(),
+ has_frame_size,
+ !entry_not_polluted
),
- json!({ "count": frames.len(), "func_stack_frame_size": has_frame_size, "entry_polluted": !entry_not_polluted }),
+ json!({ "count": frames.len, "func_stack_frame_size": has_frame_size, "entry_polluted": !entry_not_polluted }),
)
}
fn oracle_variadic(v: &Value) -> (bool, String, Value) {
- let ve = v["varargs_entries"].as_array().cloned().unwrap_or_default();
+ let ve = v["varargs_entries"].as_array.cloned().unwrap_or_default();
let ok = ve.iter().any(|x| x.as_u64() == Some(0x140002010));
(
ok,
- format!("{} varargs; printf@0x140002010={}", ve.len(), ok),
- json!({ "count": ve.len(), "printf_ok": ok }),
+ format!("{} varargs; printf@0x140002010={}", ve.len, ok),
+ json!({ "count": ve.len, "printf_ok": ok }),
)
}
fn oracle_rtti_widget(v: &Value) -> (bool, String, Value) {
- let classes = v["rtti"]["classes"].as_array().cloned().unwrap_or_default();
+ let classes = v["rtti"]["classes"].as_array.cloned().unwrap_or_default();
let ok = classes.iter().any(|c| c["name"].as_str() == Some("Widget"));
(
ok,
- format!("{} RTTI classes; Widget present={}", classes.len(), ok),
- json!({ "class_count": classes.len(), "widget": ok }),
+ format!("{} RTTI classes; Widget present={}", classes.len, ok),
+ json!({ "class_count": classes.len, "widget": ok }),
)
}
fn oracle_external_params(v: &Value) -> (bool, String, Value) {
- let e = v["external_params"].as_array().cloned().unwrap_or_default();
+ let e = v["external_params"].as_array.cloned().unwrap_or_default();
let ok = e.iter().any(|pair| {
pair.as_array()
.map(|a| {
a.first().and_then(|x| x.as_u64()) == Some(0x140002000)
- && a.get(1).and_then(|x| x.as_str()).unwrap_or("").contains("ExitProcess")
+ && a.get(1)
+ .and_then(|x| x.as_str())
+ .unwrap_or("")
+ .contains("ExitProcess")
})
.unwrap_or(false)
});
(
ok,
- format!("{} external params; ExitProcess@0x140002000={}", e.len(), ok),
- json!({ "count": e.len(), "exitprocess_ok": ok }),
+ format!("{} external params; ExitProcess@0x140002000={}", e.len, ok),
+ json!({ "count": e.len, "exitprocess_ok": ok }),
)
}
fn oracle_resources(v: &Value) -> (bool, String, Value) {
- let r = v["resources"].as_array().cloned().unwrap_or_default();
+ let r = v["resources"].as_array.cloned().unwrap_or_default();
let ok = r.iter().any(|x| {
- x["name"].as_str().unwrap_or("").contains("VERSION") && x["va"].as_u64() == Some(0x140002090)
+ x["name"].as_str().unwrap_or("").contains("VERSION") && x["va"].as_u64 == Some(0x140002090)
});
(
ok,
- format!("{} resources; VERSION@0x140002090={}", r.len(), ok),
- json!({ "count": r.len(), "version_ok": ok }),
+ format!("{} resources; VERSION@0x140002090={}", r.len, ok),
+ json!({ "count": r.len, "version_ok": ok }),
)
}
fn analyzer_checks() -> Vec<AnalyzerCheck> {
vec![
- AnalyzerCheck { name: "ASCII Strings", fixture: "analysis_lab.pe", prereqs: &[], target_is_last: false, oracle: oracle_ascii_strings },
- AnalyzerCheck { name: "Unicode Strings", fixture: "analysis_lab.pe", prereqs: &[], target_is_last: false, oracle: oracle_unicode_strings },
- AnalyzerCheck { name: "Aggressive Instruction Finder", fixture: "analysis_lab.pe", prereqs: &[], target_is_last: false, oracle: oracle_aggressive },
- AnalyzerCheck { name: "Call Convention ID", fixture: "analysis_lab.pe", prereqs: &["Function Start Search"], target_is_last: true, oracle: oracle_call_convention },
- AnalyzerCheck { name: "Call-Fixup Installer", fixture: "analysis_lab.pe", prereqs: &[], target_is_last: false, oracle: oracle_call_fixup },
- AnalyzerCheck { name: "Create Address Tables", fixture: "analysis_lab.pe", prereqs: &[], target_is_last: false, oracle: oracle_address_tables },
- AnalyzerCheck { name: "Decompiler Parameter ID", fixture: "analysis_lab.pe", prereqs: &["Function Start Search"], target_is_last: true, oracle: oracle_decomp_param },
- AnalyzerCheck { name: "Decompiler Switch Analysis", fixture: "analysis_lab.pe", prereqs: &[], target_is_last: false, oracle: oracle_decomp_switch },
- AnalyzerCheck { name: "Demangler Microsoft", fixture: "analysis_lab.pe", prereqs: &[], target_is_last: false, oracle: oracle_demangler },
- AnalyzerCheck { name: "Embedded Media", fixture: "analysis_lab.pe", prereqs: &[], target_is_last: false, oracle: oracle_embedded_media },
- AnalyzerCheck { name: "Function ID", fixture: "analysis_lab.pe", prereqs: &["Function Start Search"], target_is_last: true, oracle: oracle_function_id },
- AnalyzerCheck { name: "Function Start Search", fixture: "analysis_lab.pe", prereqs: &[], target_is_last: false, oracle: oracle_function_start },
- AnalyzerCheck { name: "Non-Returning Functions - Discovered", fixture: "analysis_lab.pe", prereqs: &[], target_is_last: false, oracle: oracle_noreturn },
- AnalyzerCheck { name: "PDB MSDIA", fixture: "analysis_lab.pe", prereqs: &[], target_is_last: false, oracle: oracle_pdb_msdia },
- AnalyzerCheck { name: "PDB Universal", fixture: "analysis_lab.pe", prereqs: &[], target_is_last: false, oracle: oracle_pdb_universal },
- AnalyzerCheck { name: "Shared Return Calls", fixture: "analysis_lab.pe", prereqs: &["Function Start Search"], target_is_last: true, oracle: oracle_shared_return },
- AnalyzerCheck { name: "Stack", fixture: "analysis_lab.pe", prereqs: &["Function Start Search"], target_is_last: true, oracle: oracle_stack },
- AnalyzerCheck { name: "Variadic Function Signature Override", fixture: "analysis_lab.pe", prereqs: &[], target_is_last: false, oracle: oracle_variadic },
- AnalyzerCheck { name: "WindowsPE x86 PE RTTI Analyzer", fixture: "tiny_x64.pe", prereqs: &[], target_is_last: false, oracle: oracle_rtti_widget },
- AnalyzerCheck { name: "Windows x86 Propagate External Parameters", fixture: "analysis_lab.pe", prereqs: &[], target_is_last: false, oracle: oracle_external_params },
- AnalyzerCheck { name: "WindowsResourceReference", fixture: "analysis_lab.pe", prereqs: &[], target_is_last: false, oracle: oracle_resources },
+ AnalyzerCheck {
+ name: "ASCII Strings",
+ fixture: "analysis_lab.pe",
+ prereqs: &[],
+ target_is_last: false,
+ oracle: oracle_ascii_strings,
+ },
+ AnalyzerCheck {
+ name: "Unicode Strings",
+ fixture: "analysis_lab.pe",
+ prereqs: &[],
+ target_is_last: false,
+ oracle: oracle_unicode_strings,
+ },
+ AnalyzerCheck {
+ name: "Aggressive Instruction Finder",
+ fixture: "analysis_lab.pe",
+ prereqs: &[],
+ target_is_last: false,
+ oracle: oracle_aggressive,
+ },
+ AnalyzerCheck {
+ name: "Call Convention ID",
+ fixture: "analysis_lab.pe",
+ prereqs: &["Function Start Search"],
+ target_is_last: true,
+ oracle: oracle_call_convention,
+ },
+ AnalyzerCheck {
+ name: "Call-Fixup Installer",
+ fixture: "analysis_lab.pe",
+ prereqs: &[],
+ target_is_last: false,
+ oracle: oracle_call_fixup,
+ },
+ AnalyzerCheck {
+ name: "Create Address Tables",
+ fixture: "analysis_lab.pe",
+ prereqs: &[],
+ target_is_last: false,
+ oracle: oracle_address_tables,
+ },
+ AnalyzerCheck {
+ name: "Decompiler Parameter ID",
+ fixture: "analysis_lab.pe",
+ prereqs: &["Function Start Search"],
+ target_is_last: true,
+ oracle: oracle_decomp_param,
+ },
+ AnalyzerCheck {
+ name: "Decompiler Switch Analysis",
+ fixture: "analysis_lab.pe",
+ prereqs: &[],
+ target_is_last: false,
+ oracle: oracle_decomp_switch,
+ },
+ AnalyzerCheck {
+ name: "Demangler Microsoft",
+ fixture: "analysis_lab.pe",
+ prereqs: &[],
+ target_is_last: false,
+ oracle: oracle_demangler,
+ },
+ AnalyzerCheck {
+ name: "Embedded Media",
+ fixture: "analysis_lab.pe",
+ prereqs: &[],
+ target_is_last: false,
+ oracle: oracle_embedded_media,
+ },
+ AnalyzerCheck {
+ name: "Function ID",
+ fixture: "analysis_lab.pe",
+ prereqs: &["Function Start Search"],
+ target_is_last: true,
+ oracle: oracle_function_id,
+ },
+ AnalyzerCheck {
+ name: "Function Start Search",
+ fixture: "analysis_lab.pe",
+ prereqs: &[],
+ target_is_last: false,
+ oracle: oracle_function_start,
+ },
+ AnalyzerCheck {
+ name: "Non-Returning Functions - Discovered",
+ fixture: "analysis_lab.pe",
+ prereqs: &[],
+ target_is_last: false,
+ oracle: oracle_noreturn,
+ },
+ AnalyzerCheck {
+ name: "PDB MSDIA",
+ fixture: "analysis_lab.pe",
+ prereqs: &[],
+ target_is_last: false,
+ oracle: oracle_pdb_msdia,
+ },
+ AnalyzerCheck {
+ name: "PDB Universal",
+ fixture: "analysis_lab.pe",
+ prereqs: &[],
+ target_is_last: false,
+ oracle: oracle_pdb_universal,
+ },
+ AnalyzerCheck {
+ name: "Shared Return Calls",
+ fixture: "analysis_lab.pe",
+ prereqs: &["Function Start Search"],
+ target_is_last: true,
+ oracle: oracle_shared_return,
+ },
+ AnalyzerCheck {
+ name: "Stack",
+ fixture: "analysis_lab.pe",
+ prereqs: &["Function Start Search"],
+ target_is_last: true,
+ oracle: oracle_stack,
+ },
+ AnalyzerCheck {
+ name: "Variadic Function Signature Override",
+ fixture: "analysis_lab.pe",
+ prereqs: &[],
+ target_is_last: false,
+ oracle: oracle_variadic,
+ },
+ AnalyzerCheck {
+ name: "WindowsPE x86 PE RTTI Analyzer",
+ fixture: "tiny_x64.pe",
+ prereqs: &[],
+ target_is_last: false,
+ oracle: oracle_rtti_widget,
+ },
+ AnalyzerCheck {
+ name: "Windows x86 Propagate External Parameters",
+ fixture: "analysis_lab.pe",
+ prereqs: &[],
+ target_is_last: false,
+ oracle: oracle_external_params,
+ },
+ AnalyzerCheck {
+ name: "WindowsResourceReference",
+ fixture: "analysis_lab.pe",
+ prereqs: &[],
+ target_is_last: false,
+ oracle: oracle_resources,
+ },
]
}
-// ---------- run one analyzer via CLI ----------
+// ----- run one analyzer via CLI -----
fn eval_one_analyzer(check: &AnalyzerCheck) -> EvalRow {
let path = fixture_path(check.fixture);
@@ -438,14 +628,14 @@ fn eval_one_analyzer(check: &AnalyzerCheck) -> EvalRow {
// Compose analyzer list: prereqs first, target last.
let mut analyzer_list: Vec<&str> = Vec::new();
analyzer_list.extend_from_slice(check.prereqs);
- analyzer_list.push(check.name);
+ analyzer_list.push(check.name());
let list_joined = analyzer_list.join(",");
- let args: Vec<&str> = vec!["analyze", &path_s, "--analyzers", &list_joined, "--json"];
+ let args: Vec<&str> = vec!["analyze", &path_s, "-analyzers", &list_joined, "-json"];
let (ok, stdout, stderr, ms) = run_ghidrust(&args);
let mut row = EvalRow {
kind: "analyzer",
- name: check.name.to_string(),
+ name: check.name().to_string(),
fixture: check.fixture.to_string(),
status: "FAIL",
ran: true,
@@ -468,11 +658,11 @@ fn eval_one_analyzer(check: &AnalyzerCheck) -> EvalRow {
Some(v) => v,
None => {
row.error = Some("stdout is not JSON".into());
- row.evidence = format!("stdout head: {}", stdout.chars().take(200).collect::<String>());
+ row.evidence = format!("stdout head: {}", stdout.chars.take(200).collect::<String>());
return row;
}
};
- let results = v["results"].as_array().cloned().unwrap_or_default();
+ let results = v["results"].as_array.cloned().unwrap_or_default();
if results.is_empty() {
row.error = Some("results empty".into());
return row;
@@ -482,17 +672,17 @@ fn eval_one_analyzer(check: &AnalyzerCheck) -> EvalRow {
} else {
results
.iter()
- .find(|r| r["name"].as_str() == Some(check.name))
+ .find(|r| r["name"].as_str() == Some(check.name()))
.cloned()
.unwrap_or_else(|| results[0].clone())
};
let status_ok = target["status"].as_str() == Some("ok");
let (oracle_pass, evidence, metrics_json) = (check.oracle)(&target);
row.metrics = json!({
- "cli_status": target["status"].clone(),
- "cli_message": target["message"].clone(),
- "oracle": metrics_json,
- });
+ "cli_status": target["status"].clone(),
+ "cli_message": target["message"].clone(),
+ "oracle": metrics_json,
+ });
row.evidence = evidence;
row.status = if status_ok && oracle_pass {
@@ -506,7 +696,7 @@ fn eval_one_analyzer(check: &AnalyzerCheck) -> EvalRow {
row
}
-// ---------- decompile method checks ----------
+// ----- decompile method checks -----
fn eval_decompile_stage0(fixture: &str) -> EvalRow {
let path = fixture_path(fixture);
@@ -514,10 +704,10 @@ fn eval_decompile_stage0(fixture: &str) -> EvalRow {
// 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"]);
+ run_ghidrust(&["decompile", &path_s, "-count", "128", "-stage0", "-json"]);
let mut row = EvalRow {
kind: "decompile",
- name: "Stage-0 (ghidrust decompile --stage0)".into(),
+ name: "Stage-0 (ghidrust decompile -stage0)".into(),
fixture: fixture.into(),
status: "FAIL",
ran: true,
@@ -538,22 +728,24 @@ fn eval_decompile_stage0(fixture: &str) -> EvalRow {
return row;
}
};
- let pseudo = v["pseudo_c"].as_str().unwrap_or("");
- let blocks = v["blocks"].as_array().map(|a| a.len()).unwrap_or(0);
- let insns = v["insn_count"].as_u64().unwrap_or(0);
+ let decomp = &v["decompile"];
+ let pseudo = decomp["pseudo_c"].as_str().unwrap_or("");
+ let blocks = decomp["blocks"].as_array.map(|a| a.len).unwrap_or(0);
+ let insns = decomp["insn_count"].as_u64.unwrap_or(0);
let lines = pseudo.lines().count();
let has_void = pseudo.contains("void ");
let has_block = pseudo.contains("block_");
let has_ret = pseudo.contains("return;") || pseudo.contains("goto ");
row.metrics = json!({
- "blocks": blocks, "insn_count": insns, "lines": lines,
- "has_void": has_void, "has_block_marker": has_block, "has_return_or_goto": has_ret,
- });
+ "blocks": blocks, "insn_count": insns, "lines": lines,
+ "has_void": has_void, "has_block_marker": has_block, "has_return_or_goto": has_ret,
+ });
row.evidence = format!(
"blocks={} insns={} lines={} void={} block_={} ret/goto={}",
blocks, insns, lines, has_void, has_block, has_ret
);
- row.status = if !pseudo.trim().is_empty() && has_void && has_block && blocks >= 1 && insns >= 1 {
+ row.status = if !pseudo.trim().is_empty() && has_void && has_block && blocks >= 1 && insns >= 1
+ {
"PASS"
} else {
"FAIL"
@@ -565,10 +757,10 @@ fn eval_decompile_stage05(fixture: &str) -> EvalRow {
let path = fixture_path(fixture);
let path_s = path.to_string_lossy().into_owned();
let (ok, stdout, stderr, ms) =
- run_ghidrust(&["decompile", &path_s, "--count", "128", "--stage05", "--json"]);
+ run_ghidrust(&["decompile", &path_s, "-count", "128", "-stage05", "-json"]);
let mut row = EvalRow {
kind: "decompile",
- name: "Stage-0.5 IR (ghidrust decompile --stage05)".into(),
+ name: "Stage-0.5 IR (ghidrust decompile -stage05)".into(),
fixture: fixture.into(),
status: "FAIL",
ran: true,
@@ -590,19 +782,22 @@ fn eval_decompile_stage05(fixture: &str) -> EvalRow {
}
};
let pseudo = v["decompile"]["pseudo_c"].as_str().unwrap_or("");
- let blocks = v["decompile"]["blocks"].as_array().map(|a| a.len()).unwrap_or(0);
- let insns = v["decompile"]["insn_count"].as_u64().unwrap_or(0);
+ let blocks = v["decompile"]["blocks"]
+ .as_array
+ .map(|a| a.len)
+ .unwrap_or(0);
+ let insns = v["decompile"]["insn_count"].as_u64.unwrap_or(0);
let cov = v["lift_coverage"].clone();
- let ratio = cov["ratio"].as_f64().unwrap_or(0.0);
- let total_ops = cov["total_ops"].as_u64().unwrap_or(0);
+ let ratio = cov["ratio"].as_f64.unwrap_or(0.0);
+ let total_ops = cov["total_ops"].as_u64.unwrap_or(0);
let has_stage05 = pseudo.contains("Stage-0.5");
// Stage-0.5 emits IR-style assignments (e.g. "eax = 0;", "rbp = rsp;").
let has_assignment = pseudo.contains(" = ") || pseudo.contains("return;");
row.metrics = json!({
- "blocks": blocks, "insn_count": insns,
- "lift_total_ops": total_ops, "lift_ratio": ratio,
- "has_stage05_marker": has_stage05, "has_assignment_or_return": has_assignment,
- });
+ "blocks": blocks, "insn_count": insns,
+ "lift_total_ops": total_ops, "lift_ratio": ratio,
+ "has_stage05_marker": has_stage05, "has_assignment_or_return": has_assignment,
+ });
row.evidence = format!(
"blocks={} insns={} ir_ops={} lift_ratio={:.2} stage05_marker={} assign/return={}",
blocks, insns, total_ops, ratio, has_stage05, has_assignment
@@ -626,11 +821,11 @@ fn eval_decompile_bench(fixture: &str) -> EvalRow {
let (ok, stdout, stderr, ms) = run_ghidrust(&[
"decompile-bench",
&path_s,
- "--functions",
+ "-functions",
"16",
- "--count",
+ "-count",
"128",
- "--json",
+ "-json",
]);
let mut row = EvalRow {
kind: "decompile",
@@ -655,20 +850,20 @@ fn eval_decompile_bench(fixture: &str) -> EvalRow {
return row;
}
};
- let function_count = v["function_count"].as_u64().unwrap_or(0);
- let total_insns = v["total_insns"].as_u64().unwrap_or(0);
- let total_ir = v["total_ir_ops"].as_u64().unwrap_or(0);
- let avg_lift = v["avg_lift_ratio"].as_f64().unwrap_or(0.0);
- let s0_us = v["stage0_total_us"].as_u64().unwrap_or(0);
- let s05_us = v["stage05_total_us"].as_u64().unwrap_or(0);
+ let function_count = v["function_count"].as_u64.unwrap_or(0);
+ let total_insns = v["total_insns"].as_u64.unwrap_or(0);
+ let total_ir = v["total_ir_ops"].as_u64.unwrap_or(0);
+ let avg_lift = v["avg_lift_ratio"].as_f64.unwrap_or(0.0);
+ let s0_us = v["stage0_total_us"].as_u64.unwrap_or(0);
+ let s05_us = v["stage05_total_us"].as_u64.unwrap_or(0);
row.metrics = json!({
- "function_count": function_count,
- "total_insns": total_insns,
- "total_ir_ops": total_ir,
- "avg_lift_ratio": avg_lift,
- "stage0_total_us": s0_us,
- "stage05_total_us": s05_us,
- });
+ "function_count": function_count,
+ "total_insns": total_insns,
+ "total_ir_ops": total_ir,
+ "avg_lift_ratio": avg_lift,
+ "stage0_total_us": s0_us,
+ "stage05_total_us": s05_us,
+ });
row.evidence = format!(
"functions={} insns={} ir_ops={} lift_avg={:.2} stage0={}µs stage05={}µs",
function_count, total_insns, total_ir, avg_lift, s0_us, s05_us
@@ -695,11 +890,11 @@ fn eval_gpu_decompile(fixture: &str) -> EvalRow {
let (ok, stdout, stderr, ms) = run_ghidrust(&[
"gpu-decompile",
&path_s,
- "--out",
+ "-out",
&dump_s,
- "--metrics",
+ "-metrics",
&metrics_s,
- "--json",
+ "-json",
]);
let mut row = EvalRow {
kind: "decompile",
@@ -738,34 +933,37 @@ fn eval_gpu_decompile(fixture: &str) -> EvalRow {
};
let backend = v["gpu_backend"].as_str().unwrap_or("").to_string();
let device = v["gpu_device"].as_str().unwrap_or("").to_string();
- let mid_reads = v["mid_pipeline_host_reads"].as_u64().unwrap_or(u64::MAX);
- let equal = v["equivalence_multipass"].as_bool().unwrap_or(false);
- let dump_bytes = v["dump_bytes"].as_u64().unwrap_or(0);
- let ir_count = v["gpu_ir_count"].as_u64().unwrap_or(0);
- let block_count = v["gpu_block_count"].as_u64().unwrap_or(0);
+ let mid_reads = v["mid_pipeline_host_reads"].as_u64.unwrap_or(u64::MAX);
+ let equal = v["equivalence_multipass"].as_bool.unwrap_or(false);
+ let dump_bytes = v["dump_bytes"].as_u64.unwrap_or(0);
+ let ir_count = v["gpu_ir_count"].as_u64.unwrap_or(0);
+ let block_count = v["gpu_block_count"].as_u64.unwrap_or(0);
let gpu_present =
backend.contains("gpu") && !backend.contains("fallback") && !backend.contains("cpu");
row.metrics = json!({
- "backend": backend,
- "device": device,
- "mid_pipeline_host_reads": mid_reads,
- "equivalence_multipass": equal,
- "dump_bytes": dump_bytes,
- "gpu_ir_count": ir_count,
- "gpu_block_count": block_count,
- "gpu_present": gpu_present,
- });
+ "backend": backend,
+ "device": device,
+ "mid_pipeline_host_reads": mid_reads,
+ "equivalence_multipass": equal,
+ "dump_bytes": dump_bytes,
+ "gpu_ir_count": ir_count,
+ "gpu_block_count": block_count,
+ "gpu_present": gpu_present,
+ });
row.evidence = format!(
"backend={} device={} mid_reads={} equal={} dump_bytes={} ir={} blocks={}",
backend, device, mid_reads, equal, dump_bytes, ir_count, block_count
);
// PASS conditions come directly from crates/ghidrust-cli/tests/re_bench.rs::gpu_decompile_dump_and_metrics:
- // mid_pipeline_host_reads == 0, equivalence_multipass == true, dump_bytes > 32.
+ // mid_pipeline_host_reads == 0, equivalence_multipass == true, dump_bytes > 32.
if mid_reads == 0 && equal && dump_bytes > 32 {
row.status = "PASS";
} else if !gpu_present {
row.status = "SKIP";
- row.evidence = format!("{} — no GPU adapter detected (backend={})", row.evidence, backend);
+ row.evidence = format!(
+ "{} — no GPU adapter detected (backend={})",
+ row.evidence, backend
+ );
} else {
row.status = "FAIL";
}
@@ -778,7 +976,7 @@ fn eval_gpu_decompile(fixture: &str) -> EvalRow {
fn eval_re_bench(fixture: &str) -> EvalRow {
let path = fixture_path(fixture);
let path_s = path.to_string_lossy().into_owned();
- let (ok, stdout, stderr, ms) = run_ghidrust(&["re-bench", &path_s, "--json"]);
+ let (ok, stdout, stderr, ms) = run_ghidrust(&["re-bench", &path_s, "-json"]);
let mut row = EvalRow {
kind: "decompile",
name: "re-bench (decomp+bulk, CPU/GPU/fallback)".into(),
@@ -801,31 +999,35 @@ fn eval_re_bench(fixture: &str) -> EvalRow {
return row;
}
};
- let cpu_ms = v["decompile_cpu"]["ms"].as_f64().unwrap_or(0.0);
- let blocks = v["decompile_cpu"]["blocks"].as_u64().unwrap_or(0);
- let chars = v["decompile_cpu"]["chars"].as_u64().unwrap_or(0);
- let bulk_cpu_hits = v["bulk_cpu"]["hits"].as_u64().unwrap_or(0);
- let bulk_gpu_hits = v["bulk_gpu"]["hits"].as_u64().unwrap_or(0);
+ let cpu_ms = v["decompile_cpu"]["ms"].as_f64.unwrap_or(0.0);
+ let blocks = v["decompile_cpu"]["blocks"].as_u64.unwrap_or(0);
+ let chars = v["decompile_cpu"]["chars"].as_u64.unwrap_or(0);
+ let bulk_cpu_hits = v["bulk_cpu"]["hits"].as_u64.unwrap_or(0);
+ let bulk_gpu_hits = v["bulk_gpu"]["hits"].as_u64.unwrap_or(0);
let bulk_equal = bulk_cpu_hits == bulk_gpu_hits;
let bulk_gpu_backend = v["bulk_gpu"]["backend"].as_str().unwrap_or("").to_string();
row.metrics = json!({
- "decompile_cpu_ms": cpu_ms,
- "decompile_blocks": blocks,
- "decompile_chars": chars,
- "bulk_cpu_hits": bulk_cpu_hits,
- "bulk_gpu_hits": bulk_gpu_hits,
- "bulk_gpu_backend": bulk_gpu_backend,
- "bulk_hits_equal": bulk_equal,
- });
+ "decompile_cpu_ms": cpu_ms,
+ "decompile_blocks": blocks,
+ "decompile_chars": chars,
+ "bulk_cpu_hits": bulk_cpu_hits,
+ "bulk_gpu_hits": bulk_gpu_hits,
+ "bulk_gpu_backend": bulk_gpu_backend,
+ "bulk_hits_equal": bulk_equal,
+ });
row.evidence = format!(
"cpu_decomp={:.3}ms blocks={} chars={} bulk_cpu={} bulk_gpu={} equal={} gpu_backend={}",
cpu_ms, blocks, chars, bulk_cpu_hits, bulk_gpu_hits, bulk_equal, bulk_gpu_backend
);
- row.status = if blocks >= 1 && chars > 20 && bulk_equal { "PASS" } else { "FAIL" };
+ row.status = if blocks >= 1 && chars > 20 && bulk_equal {
+ "PASS"
+ } else {
+ "FAIL"
+ };
row
}
-// ---------- report writers ----------
+// ----- report writers -----
fn write_report(rows: &[EvalRow], env: &Value, report_md: &Path, report_json: &Path) {
let (mut pass, mut fail, mut skip) = (0usize, 0usize, 0usize);
@@ -843,43 +1045,70 @@ fn write_report(rows: &[EvalRow], env: &Value, report_md: &Path, report_json: &P
md.push_str("`crates/ghidrust-cli/tests/eval_analysis_decompile.rs`, which\n");
md.push_str("shells out to the built `ghidrust` CLI and judges each check\n");
md.push_str("against **in-repo oracles** (mirroring the shipped analyzer\n");
- md.push_str("content tests). No external Ghidra / Hex-Rays comparison is\n");
+ md.push_str("content tests). No external / commercial decompiler comparison is\n");
md.push_str("performed.\n\n");
md.push_str("## Environment\n\n");
- md.push_str(&format!("- OS family: `{}`\n", env["os"].as_str().unwrap_or("?")));
- md.push_str(&format!("- CLI binary: `{}`\n", env["cli"].as_str().unwrap_or("?")));
- md.push_str(&format!("- CLI profile: `{}` (from CARGO_BIN_EXE path)\n", env["profile"].as_str().unwrap_or("?")));
- md.push_str(&format!("- Rust `cfg(debug_assertions)`: `{}`\n", env["debug_assertions"].as_bool().unwrap_or(false)));
- md.push_str(&format!("- Git HEAD: `{}`\n", env["git_head"].as_str().unwrap_or("(unknown)")));
- md.push_str(&format!("- GPU probe (via `gpu-decompile`): backend=`{}` device=`{}`\n\n",
+ md.push_str(&format!(
+ "- OS family: `{}`\n",
+ env["os"].as_str().unwrap_or("?")
+ ));
+ md.push_str(&format!(
+ "- CLI binary: `{}`\n",
+ env["cli"].as_str().unwrap_or("?")
+ ));
+ md.push_str(&format!(
+ "- CLI profile: `{}` (from CARGO_BIN_EXE path)\n",
+ env["profile"].as_str().unwrap_or("?")
+ ));
+ md.push_str(&format!(
+ "- Rust `cfg(debug_assertions)`: `{}`\n",
+ env["debug_assertions"].as_bool.unwrap_or(false)
+ ));
+ md.push_str(&format!(
+ "- Git HEAD: `{}`\n",
+ env["git_head"].as_str().unwrap_or("(unknown)")
+ ));
+ md.push_str(&format!(
+ "- GPU probe (via `gpu-decompile`): backend=`{}` device=`{}`\n\n",
env["gpu_backend"].as_str().unwrap_or("?"),
- env["gpu_device"].as_str().unwrap_or("?")));
+ env["gpu_device"].as_str().unwrap_or("?")
+ ));
md.push_str("## Fixtures\n\n");
- md.push_str("| Fixture | Purpose |\n|---|---|\n");
+ md.push_str("| Fixture | Purpose |\n|--|--|\n");
md.push_str("| `fixtures/analysis_lab.pe` | Primary fixture for analyzer coverage (strings, jump-table, PDB stream, PNG resource, mangled sym, security-cookie, prologues, etc.) |\n");
md.push_str("| `fixtures/tiny_x64.pe` | Minimal x86-64 PE with RTTI seed for `Widget`; smoke target for decompile methods. |\n\n");
md.push_str("## Summary\n\n");
- md.push_str(&format!("- **PASS: {}** | **FAIL: {}** | **SKIP: {}** (total {})\n\n", pass, fail, skip, rows.len()));
+ md.push_str(&format!(
+ "- **PASS: {}** | **FAIL: {}** | **SKIP: {}** (total {})\n\n",
+ pass, fail, skip, rows.len
+ ));
let verdict = if fail == 0 { "PASS" } else { "FAIL" };
md.push_str(&format!("- Overall verdict: **{}**\n\n", verdict));
md.push_str("## Analyzers\n\n");
- md.push_str("| Analyzer | Fixture | Ran | Status | Evidence |\n|---|---|---|---|---|\n");
+ md.push_str("| Analyzer | Fixture | Ran | Status | Evidence |\n|--|--|--|--|--|\n");
for r in rows.iter().filter(|r| r.kind == "analyzer") {
md.push_str(&format!(
"| {} | `{}` | {} | **{}** | {} |\n",
- r.name, r.fixture, if r.ran { "yes" } else { "no" }, r.status, escape_md(&r.evidence)
+ r.name(),
+ r.fixture,
+ if r.ran { "yes" } else { "no" },
+ r.status,
+ escape_md(&r.evidence)
));
}
md.push('\n');
md.push_str("## Decompile methods\n\n");
- md.push_str("| Method | Fixture | Status | Key metrics / evidence |\n|---|---|---|---|\n");
+ md.push_str("| Method | Fixture | Status | Key metrics / evidence |\n|--|--|--|--|\n");
for r in rows.iter().filter(|r| r.kind == "decompile") {
md.push_str(&format!(
"| {} | `{}` | **{}** | {} |\n",
- r.name, r.fixture, r.status, escape_md(&r.evidence)
+ r.name(),
+ r.fixture,
+ r.status,
+ escape_md(&r.evidence)
));
}
md.push('\n');
@@ -889,7 +1118,7 @@ fn write_report(rows: &[EvalRow], env: &Value, report_md: &Path, report_json: &P
if !failures.is_empty() {
md.push_str("## Failures (stderr / detail)\n\n");
for f in failures {
- md.push_str(&format!("### {} — `{}`\n\n", f.name, f.fixture));
+ md.push_str(&format!("### {} — `{}`\n\n", f.name(), f.fixture));
md.push_str(&format!("- evidence: {}\n", f.evidence));
if let Some(err) = &f.error {
md.push_str("- error/stderr:\n\n```\n");
@@ -906,9 +1135,9 @@ fn write_report(rows: &[EvalRow], env: &Value, report_md: &Path, report_json: &P
md.push_str("## How to re-run\n\n");
md.push_str("```powershell\n");
md.push_str("cd /path/to/Ghidrust\n");
- md.push_str("cargo test -p ghidrust-cli --test eval_analysis_decompile -- --nocapture\n");
+ md.push_str("cargo test -p ghidrust-cli -test eval_analysis_decompile - -nocapture\n");
md.push_str("# release profile (honest timings):\n");
- md.push_str("cargo test -p ghidrust-cli --test eval_analysis_decompile --release -- --nocapture\n");
+ md.push_str("cargo test -p ghidrust-cli -test eval_analysis_decompile -release - -nocapture\n");
md.push_str("# convenience wrapper:\n");
md.push_str("pwsh scripts/run_eval_analysis_decompile.ps1\n");
md.push_str("```\n\n");
@@ -923,10 +1152,10 @@ fn write_report(rows: &[EvalRow], env: &Value, report_md: &Path, report_json: &P
std::fs::write(report_md, md).expect("write MD report");
let json_out = json!({
- "environment": env,
- "summary": { "pass": pass, "fail": fail, "skip": skip, "total": rows.len(), "verdict": verdict },
- "rows": rows,
- });
+ "environment": env,
+ "summary": { "pass": pass, "fail": fail, "skip": skip, "total": rows.len, "verdict": verdict },
+ "rows": rows,
+ });
std::fs::write(
report_json,
serde_json::to_string_pretty(&json_out).unwrap_or_default(),
@@ -940,7 +1169,7 @@ fn escape_md(s: &str) -> String {
fn detect_git_head() -> String {
let out = std::process::Command::new("git")
- .args(["rev-parse", "--short", "HEAD"])
+ .args(["rev-parse", "-short", "HEAD"])
.current_dir(workspace_root())
.output();
match out {
@@ -951,26 +1180,30 @@ fn detect_git_head() -> String {
fn detect_profile_from_bin(bin: &Path) -> &'static str {
let s = bin.to_string_lossy();
- if s.contains("/release/") || s.contains("\\release\\") { "release" } else { "debug" }
+ if s.contains("/release/") || s.contains("\\release\\") {
+ "release"
+ } else {
+ "debug"
+ }
}
-// ---------- main eval test ----------
+// ----- main eval test -----
#[test]
fn eval_analysis_decompile() {
let cli = bin();
- assert!(cli.is_file(), "CLI binary missing: {}", cli.display());
+ assert!(cli.is_file, "CLI binary missing: {}", cli.display);
// Probe environment via one gpu-decompile invocation on the small fixture.
let (gpu_ok, gpu_stdout, _gpu_stderr, _) = run_ghidrust(&[
"gpu-decompile",
- fixture_path("tiny_x64.pe").to_str().unwrap(),
- "--out",
+ fixture_path("tiny_x64.pe").to_str.unwrap(),
+ "-out",
std::env::temp_dir()
.join("ghidrust_eval_probe.gdecomp")
.to_str()
.unwrap(),
- "--json",
+ "-json",
]);
let (gpu_backend, gpu_device) = if gpu_ok {
let v = parse_json_lossy(&gpu_stdout).unwrap_or(Value::Null);
@@ -981,17 +1214,17 @@ fn eval_analysis_decompile() {
} else {
("(gpu-decompile failed)".into(), String::new())
};
- let _ = std::fs::remove_file(std::env::temp_dir().join("ghidrust_eval_probe.gdecomp"));
+ let _ = std::fs::remove_file(std::env::temp_dir.join("ghidrust_eval_probe.gdecomp"));
let env = json!({
- "os": std::env::consts::FAMILY,
- "cli": cli.display().to_string(),
- "profile": detect_profile_from_bin(&cli),
- "debug_assertions": cfg!(debug_assertions),
- "git_head": detect_git_head(),
- "gpu_backend": gpu_backend,
- "gpu_device": gpu_device,
- });
+ "os": std::env::consts::FAMILY,
+ "cli": cli.display.to_string(),
+ "profile": detect_profile_from_bin(&cli),
+ "debug_assertions": cfg!(debug_assertions),
+ "git_head": detect_git_head,
+ "gpu_backend": gpu_backend,
+ "gpu_device": gpu_device,
+ });
let mut rows: Vec<EvalRow> = Vec::new();
@@ -1000,7 +1233,7 @@ fn eval_analysis_decompile() {
let row = eval_one_analyzer(&check);
eprintln!(
"[analyzer] {:<45} fixture={:<20} status={:<4} — {}",
- row.name, row.fixture, row.status, row.evidence
+ row.name(), row.fixture, row.status, row.evidence
);
rows.push(row);
}
@@ -1009,24 +1242,39 @@ fn eval_analysis_decompile() {
// real prologues + jump table + control flow; tiny_x64.pe is a smoke case).
for &fx in &["analysis_lab.pe", "tiny_x64.pe"] {
let r = eval_decompile_stage0(fx);
- eprintln!("[decomp ] {:<45} fixture={:<20} status={:<4} — {}", r.name, r.fixture, r.status, r.evidence);
+ eprintln!(
+ "[decomp ] {:<45} fixture={:<20} status={:<4} — {}",
+ r.name(), r.fixture, r.status, r.evidence
+ );
rows.push(r);
let r = eval_decompile_stage05(fx);
- eprintln!("[decomp ] {:<45} fixture={:<20} status={:<4} — {}", r.name, r.fixture, r.status, r.evidence);
+ eprintln!(
+ "[decomp ] {:<45} fixture={:<20} status={:<4} — {}",
+ r.name(), r.fixture, r.status, r.evidence
+ );
rows.push(r);
}
let r = eval_decompile_bench("analysis_lab.pe");
- eprintln!("[decomp ] {:<45} fixture={:<20} status={:<4} — {}", r.name, r.fixture, r.status, r.evidence);
+ eprintln!(
+ "[decomp ] {:<45} fixture={:<20} status={:<4} — {}",
+ r.name(), r.fixture, r.status, r.evidence
+ );
rows.push(r);
let r = eval_re_bench("analysis_lab.pe");
- eprintln!("[decomp ] {:<45} fixture={:<20} status={:<4} — {}", r.name, r.fixture, r.status, r.evidence);
+ eprintln!(
+ "[decomp ] {:<45} fixture={:<20} status={:<4} — {}",
+ r.name(), r.fixture, r.status, r.evidence
+ );
rows.push(r);
let r = eval_gpu_decompile("tiny_x64.pe");
- eprintln!("[decomp ] {:<45} fixture={:<20} status={:<4} — {}", r.name, r.fixture, r.status, r.evidence);
+ eprintln!(
+ "[decomp ] {:<45} fixture={:<20} status={:<4} — {}",
+ r.name(), r.fixture, r.status, r.evidence
+ );
rows.push(r);
- let report_md = dev_dir().join("EVAL_ANALYSIS_DECOMPILE_REPORT.md");
- let report_json = dev_dir().join("eval_analysis_decompile.json");
+ let report_md = dev_dir.join("EVAL_ANALYSIS_DECOMPILE_REPORT.md");
+ let report_json = dev_dir.join("eval_analysis_decompile.json");
write_report(&rows, &env, &report_md, &report_json);
let (pass, fail, skip) = rows.iter().fold((0, 0, 0), |(p, f, s), r| match r.status {
@@ -1035,15 +1283,19 @@ fn eval_analysis_decompile() {
"SKIP" => (p, f, s + 1),
_ => (p, f, s),
});
- eprintln!("=== EVAL SUMMARY PASS={pass} FAIL={fail} SKIP={skip} ({} rows) ===", rows.len());
- eprintln!("report: {}", report_md.display());
- eprintln!("json : {}", report_json.display());
+ eprintln!(
+ "=== EVAL SUMMARY PASS={pass} FAIL={fail} SKIP={skip} ({} rows) ===",
+ rows.len
+ );
+ eprintln!("report: {}", report_md.display);
+ eprintln!("json : {}", report_json.display);
// Regression gate: no FAILs. Any FAIL means an in-repo oracle now disagrees
// with the shipped CLI output — that is a real regression, not eval noise.
// The report is written regardless so the failure is fully attributable.
assert_eq!(
- fail, 0,
+ fail,
+ 0,
"eval found {fail} FAIL rows; see {}",
report_md.display()
);
diff --git a/crates/ghidrust-cli/tests/eval_cli_mcp_surface.rs b/crates/ghidrust-cli/tests/eval_cli_mcp_surface.rs
new file mode 100644
index 0000000..3fa505d
--- /dev/null
+++ b/crates/ghidrust-cli/tests/eval_cli_mcp_surface.rs
@@ -0,0 +1,1103 @@
+//! CLI + MCP surface confirmation evaluation set.
+//!
+//! Catalogs every top-level CLI command and every MCP tool, smoke-runs each
+//! against fixtures (or honest usage/error paths), and writes:
+//! - `dev/EVAL_CLI_MCP_SURFACE_REPORT.md`
+//! - `dev/eval_cli_mcp_surface.json`
+//!
+//! Re-run:
+//! ```text
+//! cargo test -p ghidrust-cli -test eval_cli_mcp_surface - -nocapture
+//! ```
+
+use serde::Serialize;
+use serde_json::{json, Value};
+use std::io::{BufRead, BufReader, Write};
+use std::path::PathBuf;
+use std::process::{Command, Stdio};
+use std::time::Instant;
+
+// --------------------------------------
+// Expected catalogs (keep in sync with main.rs tool_defs + CLI match)
+// --------------------------------------
+
+const EXPECTED_MCP_TOOLS: &[&str] = &[
+ "server_info",
+ "load",
+ "artifact_get",
+ "artifact_query",
+ "artifact_list",
+ "inventory",
+ "list_tree",
+ "rtti_query",
+ "process_list",
+ "process_attach",
+ "process_launch",
+ "process_resume",
+ "process_detach",
+ "process_modules",
+ "process_read",
+ "process_resolve",
+ "process_regions",
+ "disassemble",
+ "decode_support",
+ "decode_query",
+ "rtti",
+ "list_analyzers",
+ "analyze",
+ "list_gpu_strategies",
+ "decompile",
+ "gpu_decompile",
+ "rtti_gpu_bench",
+ "list_strings",
+ "search_strings",
+ "il2cpp_meta",
+ "il2cpp_map",
+ "il2cpp_touch_map",
+ "il2cpp_stubs",
+ "il2cpp_icalls",
+ "read_bytes",
+ "unity_inventory",
+ "get_xrefs_to",
+ "get_xrefs_from",
+ "get_calls_from",
+ "get_string_xrefs",
+ "list_imports",
+ "get_import_xrefs",
+ "function_at",
+ "get_function_by_address",
+ "function_create",
+];
+
+const EXPECTED_CLI_COMMANDS: &[&str] = &[
+ "help",
+ "version",
+ "load",
+ "disasm",
+ "decode-support",
+ "decode-query",
+ "bytes",
+ "rtti",
+ "analyzers",
+ "analyze",
+ "strings",
+ "xrefs",
+ "imports",
+ "function-at",
+ "function",
+ "il2cpp",
+ "unity-inventory",
+ "inventory",
+ "tree",
+ "artifact",
+ "process",
+ "bulk-bench",
+ "decompile",
+ "decompile-bench",
+ "ghidra-headtohead",
+ "gpu-decompile",
+ "re-bench",
+ "analyzer-bench",
+ "analyzer-bench-matrix",
+ "rtti-gpu-bench",
+ "project",
+ "mcp",
+];
+
+#[derive(Serialize, Debug, Clone)]
+struct EvalRow {
+ kind: &'static str,
+ name: String,
+ status: &'static str,
+ elapsed_ms: f64,
+ evidence: String,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ error: Option<String>,
+}
+
+fn bin() -> PathBuf {
+ PathBuf::from(env!("CARGO_BIN_EXE_ghidrust"))
+}
+
+fn workspace_root() -> PathBuf {
+ let mut p = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
+ p.pop();
+ p.pop();
+ p
+}
+
+fn fixture(name: &str) -> PathBuf {
+ workspace_root.join("fixtures").join(name)
+}
+
+fn pe() -> String {
+ fixture("tiny_x64.pe").to_string_lossy().into_owned()}
+fn lab() -> String {
+ fixture("analysis_lab.pe").to_string_lossy().into_owned()}
+fn elf() -> String {
+ fixture("tiny_x64.elf").to_string_lossy().into_owned()}
+fn il2cpp_pe() -> String {
+ fixture("il2cpp/il2cpp_stub_lab.pe")
+ .to_string_lossy()
+ .into_owned()
+}
+fn il2cpp_meta() -> String {
+ fixture("il2cpp/meta_v31.dat").to_string_lossy().into_owned()}
+
+fn truncate(s: &str, n: usize) -> String {
+ s.chars().take(n).collect()
+}
+
+fn run_cli(args: &[&str]) -> (bool, i32, String, String, f64) {
+ let t = Instant::now();
+ let out = Command::new(bin).args(args).output.expect("spawn ghidrust");
+ let code = out.status.code().unwrap_or(-1);
+ (
+ out.status.success(),
+ code,
+ String::from_utf8_lossy(&out.stdout).into_owned(),
+ String::from_utf8_lossy(&out.stderr).into_owned(),
+ t.elapsed().as_secs_f64() * 1000.0,
+ )
+}
+
+fn row_pass(
+ kind: &'static str,
+ name: impl Into<String>,
+ ms: f64,
+ evidence: impl Into<String>,
+) -> EvalRow {
+ EvalRow {
+ kind,
+ name: name.into(),
+ status: "PASS",
+ elapsed_ms: ms,
+ evidence: evidence.into(),
+ error: None,
+ }
+}
+
+fn row_fail(
+ kind: &'static str,
+ name: impl Into<String>,
+ ms: f64,
+ evidence: impl Into<String>,
+ err: impl Into<String>,
+) -> EvalRow {
+ EvalRow {
+ kind,
+ name: name.into(),
+ status: "FAIL",
+ elapsed_ms: ms,
+ evidence: evidence.into(),
+ error: Some(err.into()),
+ }
+}
+
+fn row_skip(
+ kind: &'static str,
+ name: impl Into<String>,
+ ms: f64,
+ evidence: impl Into<String>,
+) -> EvalRow {
+ EvalRow {
+ kind,
+ name: name.into(),
+ status: "SKIP",
+ elapsed_ms: ms,
+ evidence: evidence.into(),
+ error: None,
+ }
+}
+
+/// Success with optional substring checks on stdout+stderr.
+fn expect_cli_ok(name: &str, args: &[&str], must_contain: &[&str]) -> EvalRow {
+ let (ok, code, stdout, stderr, ms) = run_cli(args);
+ let blob = format!("{stdout}{stderr}");
+ let missing: Vec<_> = must_contain
+ .iter()
+ .filter(|s| !blob.contains(*s))
+ .copied()
+ .collect();
+ if ok && missing.is_empty() {
+ row_pass("cli", name, ms, format!("exit=0 args={args:?}"))
+ } else {
+ row_fail(
+ "cli",
+ name,
+ ms,
+ format!("exit={code} missing={missing:?}"),
+ truncate(&blob, 600),
+ )
+ }
+}
+
+/// Accept exit 0, or exit 1/2 with an honest usage/error marker (no panic).
+fn expect_cli_honest(name: &str, args: &[&str], markers: &[&str]) -> EvalRow {
+ let (ok, code, stdout, stderr, ms) = run_cli(args);
+ let blob = format!("{stdout}{stderr}");
+ let marked = markers.is_empty() || markers.iter().any(|m| blob.contains(m));
+ let honest = (ok || code == 1 || code == 2) && marked && !blob.to_lowercase.contains("panic");
+ if honest {
+ row_pass("cli", name, ms, format!("exit={code}"))
+ } else {
+ row_fail(
+ "cli",
+ name,
+ ms,
+ format!("exit={code}"),
+ truncate(&blob, 600),
+ )
+ }
+}
+
+/// Accept exit 0 producing JSON object/array (content-flexible tools).
+fn expect_cli_json(name: &str, args: &[&str]) -> EvalRow {
+ let (ok, code, stdout, stderr, ms) = run_cli(args);
+ let t = stdout.trim_start();
+ if ok && (t.starts_with('{') || t.starts_with('[')) {
+ row_pass("cli", name, ms, format!("json len={}", stdout.len))
+ } else {
+ row_fail(
+ "cli",
+ name,
+ ms,
+ format!("exit={code}"),
+ truncate(&format!("{stdout}{stderr}"), 600),
+ )
+ }
+}
+
+fn write_reports(rows: &[EvalRow]) {
+ let dev = workspace_root.join("dev");
+ let _ = std::fs::create_dir_all(&dev);
+ let pass = rows.iter().filter(|r| r.status == "PASS").count();
+ let fail = rows.iter().filter(|r| r.status == "FAIL").count();
+ let skip = rows.iter().filter(|r| r.status == "SKIP").count();
+
+ let json_path = dev.join("eval_cli_mcp_surface.json");
+ let report = json!({
+ "environment": {
+ "cli": bin.display.to_string(),
+ "package_version()": env!("CARGO_PKG_VERSION"),
+ "expected_mcp_tools": EXPECTED_MCP_TOOLS.len,
+ "expected_cli_commands": EXPECTED_CLI_COMMANDS.len,
+ },
+ "summary": { "pass": pass, "fail": fail, "skip": skip, "total": rows.len },
+ "rows": rows,
+ });
+ std::fs::write(&json_path, serde_json::to_string_pretty(&report).unwrap()).unwrap();
+
+ let mut md = String::new();
+ md.push_str("# CLI + MCP surface evaluation\n\n");
+ md.push_str(&format!(
+ "- **PASS: {pass}** | **FAIL: {fail}** | **SKIP: {skip}** (total {})\n",
+ rows.len()
+ ));
+ md.push_str(&format!(
+ "- Expected MCP tools: {}\n- Expected CLI commands: {}\n\n",
+ EXPECTED_MCP_TOOLS.len(),
+ EXPECTED_CLI_COMMANDS.len()
+ ));
+ md.push_str("| Kind | Name | Status | ms | Evidence |\n|---|---|----|---|-----|\n");
+ for r in rows {
+ md.push_str(&format!(
+ "| {} | `{}` | {} | {:.1} | {} |\n",
+ r.kind,
+ r.name().replace('|', "\\|"),
+ r.status,
+ r.elapsed_ms,
+ r.evidence.replace('|', "\\|").replace('\n', " ")
+ ));
+ }
+ if fail > 0 {
+ md.push_str("\n## Failures\n\n");
+ for r in rows.iter().filter(|r| r.status == "FAIL") {
+ md.push_str(&format!(
+ "### `{}`\n```\n{}\n```\n\n",
+ r.name(),
+ r.error.as_deref().unwrap_or("(no detail)")
+ ));
+ }
+ }
+ std::fs::write(dev.join("EVAL_CLI_MCP_SURFACE_REPORT.md"), md).unwrap();
+ eprintln!(
+ "=== CLI/MCP SURFACE EVAL PASS={pass} FAIL={fail} SKIP={skip} ===\nreport: {}\njson : {}",
+ dev.join("EVAL_CLI_MCP_SURFACE_REPORT.md").display,
+ json_path.display()
+ );
+}
+
+// --------------------------------------
+// MCP helpers
+// --------------------------------------
+
+fn mcp_call(id: u64, name: &str, arguments: Value) -> Value {
+ json!({
+ "jsonrpc": "2.0",
+ "id": id,
+ "method": "tools/call",
+ "params": { "name": name, "arguments": arguments }
+ })
+}
+
+fn mcp_exchange(requests: &[Value]) -> (bool, String, String, f64) {
+ let t = Instant::now();
+ let mut child = Command::new(bin())
+ .arg("mcp")
+ .stdin(Stdio::piped())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped())
+ .spawn()
+ .expect("spawn mcp");
+ let mut stdin = child.stdin.take().unwrap();
+ for req in requests {
+ writeln!(stdin, "{req}").unwrap();
+ }
+ drop(stdin);
+ let out = child.wait_with_output().unwrap();
+ (
+ out.status.success(),
+ String::from_utf8_lossy(&out.stdout).into_owned(),
+ String::from_utf8_lossy(&out.stderr).into_owned(),
+ t.elapsed().as_secs_f64() * 1000.0,
+ )
+}
+
+fn mcp_response_for(stdout: &str, id: u64) -> Option<Value> {
+ for line in stdout.lines() {
+ let Ok(v) = serde_json::from_str::<Value>(line) else {
+ continue;
+ };
+ if v.get("id").and_then(|x| x.as_u64) == Some(id) {
+ return Some(v);
+ }
+ }
+ None
+}
+
+/// Tool is wired if JSON-RPC returns a `result` (success or isError content).
+fn mcp_tool_wired(stdout: &str, id: u64) -> bool {
+ mcp_response_for(stdout, id)
+ .map(|v| v.get("result").is_some() || v.get("error").is_some())
+ .unwrap_or(false)
+}
+
+fn mcp_has_tool(stdout: &str, tool: &str) -> bool {
+ stdout.contains(&format!("\"name\":\"{tool}\""))
+ || stdout.contains(&format!("\"name\": \"{tool}\""))
+}
+
+fn extract_session_id(blob: &str) -> Option<String> {
+ // Prefer parsing JSON-RPC text payloads.
+ // Launch returns `{ "session": { "session_id": "…" }, … }`.
+ for line in blob.lines() {
+ let Ok(v) = serde_json::from_str::<Value>(line) else {
+ continue;
+ };
+ if let Some(text) = v.pointer("/result/content/0/text").and_then(|t| t.as_str()) {
+ if let Ok(inner) = serde_json::from_str::<Value>(text) {
+ if let Some(sid) = inner
+ .pointer("/session/session_id")
+ .or_else(|| inner.get("session_id"))
+ .and_then(|s| s.as_str())
+ {
+ return Some(sid.to_string());
+ }
+ }
+ }
+ }
+ // Fallback scrape: first "session_id":"…" occurrence.
+ let needle = "\"session_id\"";
+ if let Some(idx) = blob.find(needle) {
+ let rest = &blob[idx + needle.len()..];
+ if let Some(colon) = rest.find(':') {
+ let after = rest[colon + 1..].trim();
+ if let Some(stripped) = after.strip_prefix('"') {
+ if let Some(end) = stripped.find('"') {
+ let s = &stripped[..end];
+ if !s.is_empty() {
+ return Some(s.to_string());
+ }
+ }
+ }
+ }
+ }
+ None
+}
+
+/// Interactive MCP process session: launch → modules → regions → read → resolve → resume → detach → attach(error).
+fn mcp_process_chain(image: &str) -> (bool, String, f64, Vec<(&'static str, bool)>) {
+ let t = Instant::now();
+ let mut child = Command::new(bin())
+ .arg("mcp")
+ .stdin(Stdio::piped())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped())
+ .spawn()
+ .expect("spawn mcp");
+ let mut stdin = child.stdin.take().unwrap();
+ let stdout = child.stdout.take().unwrap();
+ let mut reader = BufReader::new(stdout);
+ let mut all = String::new();
+ let mut line = String::new();
+
+ let send = |stdin: &mut std::process::ChildStdin, v: &Value| {
+ writeln!(stdin, "{v}").unwrap();
+ let _ = stdin.flush();
+ };
+ let read_id = |reader: &mut BufReader<std::process::ChildStdout>,
+ all: &mut String,
+ line: &mut String,
+ want: u64|
+ -> bool {
+ for _ in 0..80 {
+ line.clear();
+ match reader.read_line(line) {
+ Ok(0) => break,
+ Ok(_) => {}
+ Err(_) => break,
+ }
+ all.push_str(line);
+ if let Ok(v) = serde_json::from_str::<Value>(line) {
+ if v.get("id").and_then(|x| x.as_u64) == Some(want) {
+ return v.get("result").is_some() || v.get("error").is_some();
+ }
+ }
+ }
+ false
+ };
+
+ send(
+ &mut stdin,
+ &json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{
+ "protocolVersion":"2024-11-05","capabilities":{},
+ "clientInfo":{"name":"eval","version":"0"}
+ }}),
+ );
+ let _ = read_id(&mut reader, &mut all, &mut line, 1);
+
+ send(
+ &mut stdin,
+ &mcp_call(
+ 2,
+ "process_launch",
+ json!({ "image": image, "args": "-version" }),
+ ),
+ );
+ let launch_ok = read_id(&mut reader, &mut all, &mut line, 2);
+ let sid = extract_session_id(&all);
+
+ let mut results: Vec<(&'static str, bool)> = vec![("process_launch", launch_ok && sid.is_some())];
+
+ if let Some(session) = sid {
+ let steps: Vec<(&str, Value)> = vec![
+ ("process_modules", json!({ "session_id": session })),
+ ("process_regions", json!({ "session_id": session })),
+ (
+ "process_read",
+ json!({ "session_id": session, "addr": "0x7FFE0000", "size": 16 }),
+ ),
+ (
+ "process_resolve",
+ json!({
+ "session_id": session,
+ "module": "ghidrust.exe",
+ "rva": "0x1000"
+ }),
+ ),
+ ("process_resume", json!({ "session_id": session })),
+ ("process_detach", json!({ "session_id": session })),
+ // Structured failure proves attach is wired.
+ ("process_attach", json!({ "pid": 1 })),
+ ];
+ let mut id = 3u64;
+ for (name, args) in steps {
+ send(&mut stdin, &mcp_call(id, name, args));
+ let ok = read_id(&mut reader, &mut all, &mut line, id);
+ results.push((name, ok));
+ id += 1;
+ }
+ } else {
+ for name in [
+ "process_modules",
+ "process_regions",
+ "process_read",
+ "process_resolve",
+ "process_resume",
+ "process_detach",
+ "process_attach",
+ ] {
+ results.push((name, false));
+ }
+ }
+
+ drop(stdin);
+ let _ = child.wait();
+ let ok = results.iter().all(|(_, o)| *o);
+ (ok, all, t.elapsed().as_secs_f64() * 1000.0, results)
+}
+
+fn tempfile_dir() -> PathBuf {
+ let p = std::env::temp_dir.join(format!("ghidrust_eval_surface_{}", std::process::id));
+ let _ = std::fs::create_dir_all(&p);
+ // Drop a tiny file so inventory/tree have something to list.
+ let _ = std::fs::write(p.join("marker.txt"), b"ghidrust-eval\n");
+ p
+}
+
+// --------------------------------------
+// Main evaluation
+// --------------------------------------
+
+#[test]
+fn eval_cli_mcp_surface_catalog() {
+ let mut rows: Vec<EvalRow> = Vec::new();
+ let pe = pe();
+ let lab = lab();
+ let elf = elf();
+ let ipe = il2cpp_pe();
+ let imeta = il2cpp_meta();
+ let tmp = tempfile_dir();
+ let tmp_s = tmp.to_string_lossy().into_owned();
+ let proj = tmp.join("eval_proj");
+
+ // --- Catalog: help mentions surface ---
+ {
+ let (ok, _, stdout, stderr, ms) = run_cli(&["help"]);
+ let blob = format!("{stdout}{stderr}");
+ let decode_ok = blob.contains("decode-support")
+ && blob.contains("decode-query")
+ && blob.contains("disasm");
+ if ok && decode_ok {
+ rows.push(row_pass(
+ "catalog",
+ "cli_help_lists_core",
+ ms,
+ "help includes disasm + decode-support + decode-query",
+ ));
+ } else {
+ rows.push(row_fail(
+ "catalog",
+ "cli_help_lists_core",
+ ms,
+ "help incomplete",
+ truncate(&blob, 400),
+ ));
+ }
+ }
+
+ // --- CLI smoke ---
+ rows.push(expect_cli_ok(
+ "cli:version",
+ &["version", "-json"],
+ &["tool_surface"],
+ ));
+ rows.push(expect_cli_ok("cli:help", &["help"], &["ghidrust"]));
+ rows.push(expect_cli_ok(
+ "cli:load",
+ &["load", &pe, "-json"],
+ &["section"],
+ ));
+ rows.push(expect_cli_ok(
+ "cli:load_elf",
+ &["load", &elf, "-json"],
+ &["section"],
+ ));
+ rows.push(expect_cli_ok(
+ "cli:disasm",
+ &["disasm", &pe, "-count", "8", "-json"],
+ &["mnemonic"],
+ ));
+ rows.push(expect_cli_ok(
+ "cli:disassemble_alias",
+ &["disassemble", &pe, "-count", "4", "-json"],
+ &["mnemonic"],
+ ));
+ rows.push(expect_cli_ok(
+ "cli:decode-support",
+ &["decode-support", "-json"],
+ &["arches", "syntax_values()"],
+ ));
+ rows.push(expect_cli_ok(
+ "cli:decode-query",
+ &[
+ "decode-query",
+ "-query",
+ "insn_name",
+ "-arch",
+ "x86",
+ "-id",
+ "1",
+ "-json",
+ ],
+ &["insn_name"],
+ ));
+ rows.push(expect_cli_ok(
+ "cli:bytes",
+ &["bytes", &pe, "-addr", "0x140001000", "-count", "8", "-json"],
+ &["bytes"],
+ ));
+ rows.push(expect_cli_ok(
+ "cli:rtti",
+ &["rtti", &pe, "-json"],
+ &["Widget"],
+ ));
+ rows.push(expect_cli_ok(
+ "cli:rtti_query",
+ &["rtti", &pe, "-filter", "Widget", "-json"],
+ &["Widget"],
+ ));
+ rows.push(expect_cli_ok(
+ "cli:analyzers",
+ &["analyzers", "-json"],
+ &["implemented"],
+ ));
+ rows.push(expect_cli_ok(
+ "cli:analyze",
+ &[
+ "analyze",
+ &lab,
+ "-analyzers",
+ "ASCII Strings,Function Start Search",
+ "-json",
+ ],
+ &["ok"],
+ ));
+ rows.push(expect_cli_ok(
+ "cli:strings",
+ &["strings", &lab, "-filter", "ExitProcess", "-json"],
+ &["ExitProcess"],
+ ));
+ // Empty arrays are valid when the fixture has no code refs / import table.
+ rows.push(expect_cli_json(
+ "cli:xrefs",
+ &["xrefs", &lab, "-string", "ExitProcess", "-json"],
+ ));
+ rows.push(expect_cli_json("cli:imports", &["imports", &lab, "-json"]));
+ rows.push(expect_cli_ok(
+ "cli:xrefs_from",
+ &["xrefs", &lab, "-from", "0x140001000", "-json"],
+ &["["],
+ ));
+ rows.push(expect_cli_ok(
+ "cli:function-at",
+ &["function-at", &lab, "-addr", "0x140001000", "-json"],
+ &["0x140001000"],
+ ));
+ rows.push(expect_cli_ok(
+ "cli:function_create",
+ &["function", "create", &lab, "-addr", "0x140001000", "-json"],
+ &["entry"],
+ ));
+ rows.push(expect_cli_ok(
+ "cli:il2cpp_meta",
+ &["il2cpp", "meta", &imeta, "-json"],
+ &["version"],
+ ));
+ rows.push(expect_cli_json(
+ "cli:il2cpp_map",
+ &["il2cpp", "map", "-binary", &ipe, "-meta", &imeta, "-json"],
+ ));
+ rows.push(expect_cli_json(
+ "cli:il2cpp_touch_map",
+ &[
+ "il2cpp",
+ "touch-map",
+ "-meta",
+ &imeta,
+ "-filter",
+ "a",
+ "-json",
+ ],
+ ));
+ rows.push(expect_cli_json(
+ "cli:il2cpp_stubs",
+ &["il2cpp", "stubs", "-binary", &ipe, "-json"],
+ ));
+ rows.push(expect_cli_json(
+ "cli:il2cpp_icalls",
+ &["il2cpp", "icalls", "-binary", &ipe, "-json"],
+ ));
+ rows.push(expect_cli_json(
+ "cli:unity-inventory",
+ &["unity-inventory", &tmp_s, "-json"],
+ ));
+ rows.push(expect_cli_json(
+ "cli:inventory",
+ &["inventory", &tmp_s, "-json"],
+ ));
+ rows.push(expect_cli_json("cli:tree", &["tree", &tmp_s, "-json"]));
+ rows.push(expect_cli_honest(
+ "cli:artifact_list",
+ &["artifact", "list", "-json"],
+ &["[", "{", "artifact", "error", "usage", "spilled"],
+ ));
+ rows.push(expect_cli_honest(
+ "cli:artifact_query",
+ &["artifact", "query", "none", "-json"],
+ &["error", "not", "usage", "{", "[", "artifact"],
+ ));
+ rows.push(expect_cli_honest(
+ "cli:artifact_get",
+ &["artifact", "get", "none", "-json"],
+ &["error", "not", "usage", "{", "[", "artifact"],
+ ));
+ rows.push(expect_cli_ok(
+ "cli:process_list",
+ &["process", "list", "-json"],
+ &["["],
+ ));
+ for (name, sub) in [
+ ("cli:process_attach_usage", "attach"),
+ ("cli:process_launch_usage", "launch"),
+ ("cli:process_resume_usage", "resume"),
+ ("cli:process_detach_usage", "detach"),
+ ("cli:process_modules_usage", "modules"),
+ ("cli:process_read_usage", "read"),
+ ("cli:process_resolve_usage", "resolve"),
+ ("cli:process_regions_usage", "regions"),
+ ] {
+ rows.push(expect_cli_honest(name, &["process", sub], &["usage", sub]));
+ }
+ rows.push(expect_cli_ok(
+ "cli:decompile",
+ &["decompile", &pe, "-json"],
+ &["pseudo_c"],
+ ));
+ rows.push(expect_cli_ok(
+ "cli:decompile_stage0",
+ &["decompile", &pe, "-stage0", "-json"],
+ &["decompile"],
+ ));
+ rows.push(expect_cli_ok(
+ "cli:decompile_stage05",
+ &["decompile", &pe, "-stage05", "-json"],
+ &["decompile"],
+ ));
+ rows.push(expect_cli_json(
+ "cli:decompile-bench",
+ &["decompile-bench", &pe, "-functions", "2", "-json"],
+ ));
+ rows.push(expect_cli_json(
+ "cli:gpu-decompile",
+ &["gpu-decompile", &pe, "-json"],
+ ));
+ rows.push(expect_cli_json(
+ "cli:bulk-bench",
+ &["bulk-bench", &lab, "-json"],
+ ));
+ rows.push(expect_cli_json(
+ "cli:re-bench",
+ &["re-bench", &lab, "-json"],
+ ));
+ rows.push(expect_cli_json(
+ "cli:analyzer-bench",
+ &["analyzer-bench", &lab, "-json"],
+ ));
+ rows.push(expect_cli_ok(
+ "cli:analyzer-bench-matrix",
+ &["analyzer-bench-matrix"],
+ &["Analyzer"],
+ ));
+ rows.push(expect_cli_json(
+ "cli:rtti-gpu-bench",
+ &["rtti-gpu-bench", &pe, "-json"],
+ ));
+ rows.push(expect_cli_json(
+ "cli:ghidra-headtohead",
+ &["ghidra-headtohead", &pe, "-json"],
+ ));
+
+ // Project lifecycle
+ rows.push(expect_cli_json(
+ "cli:project_create",
+ &["project", "create", proj.to_str.unwrap(), "-json"],
+ ));
+ rows.push(expect_cli_json(
+ "cli:project_import",
+ &["project", "import", proj.to_str().unwrap(), &pe, "-json"],
+ ));
+ rows.push(expect_cli_honest(
+ "cli:project_list",
+ &["project", "list", proj.to_str.unwrap(), "-json"],
+ &["{", "[", "files", "name", "error"],
+ ));
+ rows.push(expect_cli_honest(
+ "cli:project_open",
+ &["project", "open", proj.to_str.unwrap(), "-json"],
+ &["{", "[", "name", "files", "error"],
+ ));
+ rows.push(expect_cli_honest(
+ "cli:project_analyze",
+ &[
+ "project",
+ "analyze",
+ proj.to_str().unwrap(),
+ "-analyzers",
+ "ASCII Strings",
+ "-json",
+ ],
+ &["ok", "error", "{", "[", "analyz"],
+ ));
+ rows.push(expect_cli_honest(
+ "cli:project_export",
+ &["project", "export", proj.to_str.unwrap(), "-json"],
+ &["{", "[", "export", "listing", "analysis", "error", "ok"],
+ ));
+
+ // MCP boots
+ {
+ let (ok, stdout, stderr, ms) = mcp_exchange(&[json!({
+ "jsonrpc":"2.0","id":1,"method":"initialize","params":{
+ "protocolVersion":"2024-11-05","capabilities":{},
+ "clientInfo":{"name":"eval","version":"0"}
+ }
+ })]);
+ if ok && (stdout.contains("serverInfo") || stdout.contains("result")) {
+ rows.push(row_pass("cli", "cli:mcp_stdio_boots", ms, "initialize ok"));
+ } else {
+ rows.push(row_fail(
+ "cli",
+ "cli:mcp_stdio_boots",
+ ms,
+ "initialize failed",
+ truncate(&format!("{stdout}{stderr}"), 400),
+ ));
+ }
+ }
+
+ // MCP tools/list completeness
+ {
+ let (ok, stdout, stderr, ms) = mcp_exchange(&[
+ json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{
+ "protocolVersion":"2024-11-05","capabilities":{},
+ "clientInfo":{"name":"eval","version":"0"}
+ }}),
+ json!({"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}),
+ ]);
+ let missing: Vec<_> = EXPECTED_MCP_TOOLS
+ .iter()
+ .filter(|t| !mcp_has_tool(&stdout, t))
+ .copied()
+ .collect();
+ if ok && missing.is_empty() {
+ rows.push(row_pass(
+ "catalog",
+ "mcp_tools_list_complete",
+ ms,
+ format!("all {} tools listed", EXPECTED_MCP_TOOLS.len),
+ ));
+ } else {
+ rows.push(row_fail(
+ "catalog",
+ "mcp_tools_list_complete",
+ ms,
+ format!("missing={missing:?}"),
+ truncate(&format!("{stdout}{stderr}"), 600),
+ ));
+ }
+ }
+
+ // MCP: call every non-session tool
+ let calls: Vec<(&str, Value)> = vec![
+ ("server_info", json!({})),
+ ("load", json!({ "path": pe })),
+ ("list_analyzers", json!({})),
+ ("list_gpu_strategies", json!({})),
+ ("decode_support", json!({})),
+ (
+ "decode_query",
+ json!({ "query": "insn_name", "arch": "x86", "id": 1 }),
+ ),
+ (
+ "disassemble",
+ json!({ "path": pe, "count": 8, "detail": true }),
+ ),
+ ("rtti", json!({ "path": pe })),
+ ("rtti_query", json!({ "path": pe, "filter": "Widget" })),
+ (
+ "analyze",
+ json!({
+ "path": lab,
+ "analyzers": ["ASCII Strings", "Function Start Search"]
+ }),
+ ),
+ ("list_strings", json!({ "path": lab, "limit": 20 })),
+ (
+ "search_strings",
+ json!({ "path": lab, "filter": "ExitProcess" }),
+ ),
+ ("list_imports", json!({ "path": lab })),
+ ("function_at", json!({ "path": lab, "addr": "0x140001000" })),
+ (
+ "get_function_by_address",
+ json!({ "path": lab, "addr": "0x140001000" }),
+ ),
+ (
+ "function_create",
+ json!({ "path": lab, "addr": "0x140001000" }),
+ ),
+ (
+ "read_bytes",
+ json!({ "path": pe, "addr": "0x140001000", "count": 8 }),
+ ),
+ ("decompile", json!({ "path": pe })),
+ ("gpu_decompile", json!({ "path": pe })),
+ (
+ "get_xrefs_to",
+ json!({ "path": lab, "addr": "0x140002000" }),
+ ),
+ (
+ "get_xrefs_from",
+ json!({ "path": lab, "addr": "0x140001000", "count": 16 }),
+ ),
+ (
+ "get_calls_from",
+ json!({ "path": lab, "addr": "0x140001000" }),
+ ),
+ (
+ "get_string_xrefs",
+ json!({ "path": lab, "string": "ExitProcess" }),
+ ),
+ (
+ "get_import_xrefs",
+ json!({ "path": lab, "name": "ExitProcess" }),
+ ),
+ ("inventory", json!({ "dir": tmp_s })),
+ ("list_tree", json!({ "path": tmp_s })),
+ ("unity_inventory", json!({ "dir": tmp_s })),
+ ("artifact_list", json!({})),
+ (
+ "artifact_query",
+ json!({ "id": "nonexistent", "offset": 0, "limit": 1 }),
+ ),
+ ("artifact_get", json!({ "id": "nonexistent" })),
+ ("il2cpp_meta", json!({ "path": imeta })),
+ ("il2cpp_map", json!({ "binary": ipe, "meta": imeta })),
+ ("il2cpp_touch_map", json!({ "meta": imeta, "filter": "a" })),
+ ("il2cpp_stubs", json!({ "binary": ipe })),
+ ("il2cpp_icalls", json!({ "binary": ipe })),
+ ("rtti_gpu_bench", json!({ "path": pe })),
+ ("process_list", json!({})),
+ ];
+
+ const CHUNK: usize = 10;
+ let mut id: u64 = 10;
+ for chunk in calls.chunks(CHUNK) {
+ let mut reqs = vec![json!({
+ "jsonrpc":"2.0","id":1,"method":"initialize","params":{
+ "protocolVersion":"2024-11-05","capabilities":{},
+ "clientInfo":{"name":"eval","version":"0"}
+ }
+ })];
+ let mut id_names: Vec<(u64, &str)> = Vec::new();
+ for (name, args) in chunk {
+ id += 1;
+ reqs.push(mcp_call(id, name, args.clone()));
+ id_names.push((id, *name));
+ }
+ let (ok, stdout, stderr, ms_total) = mcp_exchange(&reqs);
+ let per = ms_total / id_names.len().max(1) as f64;
+ for (cid, name) in id_names {
+ let wired = ok && mcp_tool_wired(&stdout, cid);
+ if wired {
+ rows.push(row_pass(
+ "mcp",
+ format!("mcp:{name}"),
+ per,
+ "jsonrpc result (ok or isError)",
+ ));
+ } else {
+ rows.push(row_fail(
+ "mcp",
+ format!("mcp:{name}"),
+ per,
+ "no matching response",
+ truncate(&format!("{stdout}\n{stderr}"), 500),
+ ));
+ }
+ }
+ }
+
+ // Live process tools (same MCP process)
+ {
+ let image = bin().to_string_lossy().into_owned();
+ let (_ok, blob, ms, step_results) = mcp_process_chain(&image);
+ for (name, wired) in step_results {
+ let key = format!("mcp:{name}");
+ if wired {
+ rows.push(row_pass("mcp", key, ms / 8.0, "process chain"));
+ } else if cfg!(windows) {
+ rows.push(row_fail(
+ "mcp",
+ key,
+ ms / 8.0,
+ "process chain step failed",
+ truncate(&blob, 500),
+ ));
+ } else {
+ rows.push(row_skip(
+ "mcp",
+ key,
+ ms / 8.0,
+ "process bridge not available on this host",
+ ));
+ }
+ }
+ }
+
+ // Every expected MCP tool must have a row
+ for tool in EXPECTED_MCP_TOOLS {
+ let key = format!("mcp:{tool}");
+ if !rows.iter().any(|r| r.name() == key) {
+ rows.push(row_fail(
+ "mcp",
+ key,
+ 0.0,
+ "never exercised",
+ "missing from eval schedule",
+ ));
+ }
+ }
+
+ // Every expected CLI command must be covered
+ for cmd in EXPECTED_CLI_COMMANDS {
+ let covered = rows.iter().any(|r| {
+ r.kind == "cli"
+ && (r.name() == format!("cli:{cmd}")
+ || r.name().starts_with(&format!("cli:{cmd}_"))
+ || (*cmd == "mcp" && r.name() == "cli:mcp_stdio_boots")
+ || (*cmd == "function" && r.name().starts_with("cli:function"))
+ || (*cmd == "il2cpp" && r.name().starts_with("cli:il2cpp"))
+ || (*cmd == "artifact" && r.name().starts_with("cli:artifact"))
+ || (*cmd == "process" && r.name().starts_with("cli:process"))
+ || (*cmd == "project" && r.name().starts_with("cli:project"))
+ || (*cmd == "disasm"
+ && (r.name() == "cli:disasm" || r.name() == "cli:disassemble_alias")))
+ });
+ if covered {
+ rows.push(row_pass(
+ "catalog",
+ format!("cli_coverage:{cmd}"),
+ 0.0,
+ "smoke row present",
+ ));
+ } else {
+ rows.push(row_fail(
+ "catalog",
+ format!("cli_coverage:{cmd}"),
+ 0.0,
+ "no smoke row",
+ "add a CLI case for this command",
+ ));
+ }
+ }
+
+ write_reports(&rows);
+ let fail = rows.iter().filter(|r| r.status == "FAIL").count();
+ assert_eq!(
+ fail, 0,
+ "CLI/MCP surface eval has {fail} FAIL rows; see dev/EVAL_CLI_MCP_SURFACE_REPORT.md"
+ );
+}
diff --git a/crates/ghidrust-cli/tests/re_bench.rs b/crates/ghidrust-cli/tests/re_bench.rs
index df28057..2c42f40 100644
--- a/crates/ghidrust-cli/tests/re_bench.rs
+++ b/crates/ghidrust-cli/tests/re_bench.rs
@@ -43,8 +43,10 @@ fn decompile_tiny_pe_nonempty_structure() {
.or_else(|| v["decompile"]["pseudo_c"].as_str())
.unwrap_or("");
assert!(
- pseudo.contains("void ") || pseudo.contains("uint")
- || pseudo.contains("int32_t") || pseudo.contains("int64_t"),
+ pseudo.contains("void ")
+ || pseudo.contains("uint")
+ || pseudo.contains("int32_t")
+ || pseudo.contains("int64_t"),
"expected typed function header, got:\n{pseudo}"
);
let blocks = v["blocks"]
diff --git a/crates/ghidrust-core/src/analyzers/mod.rs b/crates/ghidrust-core/src/analyzers/mod.rs
index 505c58d..f3ba227 100644
--- a/crates/ghidrust-core/src/analyzers/mod.rs
+++ b/crates/ghidrust-core/src/analyzers/mod.rs
@@ -30,7 +30,7 @@ pub use strings::{
scan_utf16le_strings, FoundString, StringCollectOpts, StringMatchMode,
};
-/// Exact labels from the Ghidra Auto Analysis screenshot (order preserved).
+/// Exact labels from the Auto Analysis screenshot (order preserved).
pub const ANALYZER_NAMES: &[&str] = &[
"ASCII Strings",
"Unicode Strings",
diff --git a/crates/ghidrust-core/src/bounds_honesty.rs b/crates/ghidrust-core/src/bounds_honesty.rs
new file mode 100644
index 0000000..e426224
--- /dev/null
+++ b/crates/ghidrust-core/src/bounds_honesty.rs
@@ -0,0 +1,215 @@
+//! Truncated function-end honesty signals for agents and CLI/MCP.
+
+use crate::disasm::DisasmStopReason;
+use crate::pe_functions::grow_function;
+use crate::program::Program;
+use serde::Serialize;
+
+/// Minimum exclusive span before a stored end is treated as "short".
+pub const SHORT_SPAN_BYTES: u64 = 0x40;
+
+/// Bounded/flow insn counts at or below this with `FunctionEnd` are suspect
+/// when grow extends past the short span.
+pub const SHORT_INSN_COUNT: usize = 8;
+
+/// Honesty report for a disasm/decompile range.
+#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
+pub struct BoundsHonesty {
+ pub bounds_suspect: bool,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub bounds_warning: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub suggested_end: Option<u64>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub heal_hint: Option<String>,
+}
+
+impl BoundsHonesty {
+ pub fn ok() -> Self {
+ Self {
+ bounds_suspect: false,
+ bounds_warning: None,
+ suggested_end: None,
+ heal_hint: None,
+ }
+ }
+
+ /// JSON-friendly map with hex addresses.
+ pub fn to_json_fields(&self) -> serde_json::Value {
+ let mut m = serde_json::Map::new();
+ m.insert(
+ "bounds_suspect".into(),
+ serde_json::Value::Bool(self.bounds_suspect),
+ );
+ if let Some(w) = &self.bounds_warning {
+ m.insert("bounds_warning".into(), serde_json::Value::String(w.clone()));
+ }
+ if let Some(e) = self.suggested_end {
+ m.insert(
+ "suggested_end".into(),
+ serde_json::Value::String(format!("{e:#x}")),
+ );
+ }
+ if let Some(h) = &self.heal_hint {
+ m.insert("heal_hint".into(), serde_json::Value::String(h.clone()));
+ }
+ serde_json::Value::Object(m)
+ }
+}
+
+/// Assess whether stored `[entry, end)` looks truncated relative to grow/linear truth.
+pub fn assess_bounds_honesty(
+ prog: &Program,
+ entry: Option<u64>,
+ stored_end: Option<u64>,
+ insn_count: usize,
+ stop_reason: DisasmStopReason,
+) -> BoundsHonesty {
+ let Some(entry) = entry else {
+ return BoundsHonesty::ok();
+ };
+ let Some(stored_end) = stored_end else {
+ return BoundsHonesty::ok();
+ };
+ if stored_end <= entry {
+ return BoundsHonesty::ok();
+ }
+
+ let span = stored_end.saturating_sub(entry);
+ let grown = grow_function(prog, entry, None);
+ let grow_extends = grown >= entry.saturating_add(SHORT_SPAN_BYTES) && grown > stored_end;
+
+ let short_span_stop =
+ span < SHORT_SPAN_BYTES && stop_reason == DisasmStopReason::FunctionEnd && grow_extends;
+ let short_insn_stop = insn_count < SHORT_INSN_COUNT
+ && stop_reason == DisasmStopReason::FunctionEnd
+ && grow_extends;
+ let no_clean_terminator = grow_extends
+ && span < SHORT_SPAN_BYTES
+ && !ends_at_ret_or_int3_pad(prog, stored_end);
+
+ if !(short_span_stop || short_insn_stop || no_clean_terminator) {
+ return BoundsHonesty::ok();
+ }
+
+ BoundsHonesty {
+ bounds_suspect: true,
+ bounds_warning: Some(
+ "function_end looks truncated; try --linear or function create".into(),
+ ),
+ suggested_end: Some(grown),
+ heal_hint: Some(format!("ghidrust function create <path> -addr {entry:#x}")),
+ }
+}
+
+/// Decompile-path check: stored span much smaller than decoded region / grow.
+pub fn assess_decompile_bounds(
+ prog: &Program,
+ entry: u64,
+ stored_end: Option<u64>,
+ decoded_region_end: u64,
+) -> BoundsHonesty {
+ let Some(stored_end) = stored_end else {
+ return BoundsHonesty::ok();
+ };
+ let span = stored_end.saturating_sub(entry);
+ let grown = grow_function(prog, entry, None);
+ let decoded_past = decoded_region_end > stored_end.saturating_add(0x10);
+ let grow_extends = grown > stored_end && grown >= entry.saturating_add(SHORT_SPAN_BYTES);
+ if span < SHORT_SPAN_BYTES && (decoded_past || grow_extends) {
+ return BoundsHonesty {
+ bounds_suspect: true,
+ bounds_warning: Some(
+ "function_end looks truncated relative to decompiled region; try function create"
+ .into(),
+ ),
+ suggested_end: Some(grown.max(decoded_region_end)),
+ heal_hint: Some(format!("ghidrust function create <path> -addr {entry:#x}")),
+ };
+ }
+ BoundsHonesty::ok()
+}
+
+fn ends_at_ret_or_int3_pad(prog: &Program, end: u64) -> bool {
+ // Look just before exclusive end for ret, or at end for int3 pad.
+ if crate::disasm::int3_padding_at(prog, end) {
+ return true;
+ }
+ for back in 1..=15u64 {
+ let va = end.saturating_sub(back);
+ if let Ok(insn) = crate::disasm::disassemble_at(prog, va) {
+ if va + insn.length as u64 == end && insn.mnemonic == "ret" {
+ return true;
+ }
+ }
+ }
+ false
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::program::{MemoryBlock, Program};
+
+ fn prog_with_body() -> Program {
+ let mut prog = Program::new("t".into(), "PE32+");
+ // Multi-block-ish body longer than SHORT_SPAN_BYTES past a ~0x11 truncated end.
+ let mut code = vec![
+ 0x55, // push rbp
+ 0x48, 0x89, 0xE5, // mov rbp, rsp
+ 0x41, 0x54, // push r12
+ 0x41, 0x55, // push r13
+ 0x41, 0x56, // push r14
+ 0x41, 0x57, // push r15
+ 0x48, 0x83, 0xEC, 0x20, // sub rsp, 0x20
+ ];
+ code.extend(vec![0x90u8; 48]); // nops → span > 0x40
+ code.extend_from_slice(&[
+ 0x31, 0xC0, // xor eax, eax
+ 0x48, 0x83, 0xC4, 0x20, // add rsp, 0x20
+ 0x41, 0x5F, 0x41, 0x5E, 0x41, 0x5D, 0x41, 0x5C, // pops
+ 0x5D, // pop rbp
+ 0xC3, // ret
+ 0xCC, 0xCC,
+ ]);
+ assert!(code.len() > 0x40);
+ prog.blocks.push(MemoryBlock {
+ name: ".text".into(),
+ va: 0x1000,
+ size: code.len() as u64,
+ bytes: code,
+ readable: true,
+ writable: false,
+ executable: true,
+ });
+ prog
+ }
+
+ #[test]
+ fn truncated_end_is_suspect() {
+ let prog = prog_with_body();
+ let h = assess_bounds_honesty(
+ &prog,
+ Some(0x1000),
+ Some(0x1011),
+ 5,
+ DisasmStopReason::FunctionEnd,
+ );
+ assert!(h.bounds_suspect);
+ assert!(h.suggested_end.unwrap() > 0x1011);
+ }
+
+ #[test]
+ fn honest_end_not_suspect() {
+ let prog = prog_with_body();
+ let grown = grow_function(&prog, 0x1000, None);
+ let h = assess_bounds_honesty(
+ &prog,
+ Some(0x1000),
+ Some(grown),
+ 20,
+ DisasmStopReason::FunctionEnd,
+ );
+ assert!(!h.bounds_suspect);
+ }
+}
diff --git a/crates/ghidrust-core/src/callsite_hints.rs b/crates/ghidrust-core/src/callsite_hints.rs
new file mode 100644
index 0000000..09b17a3
--- /dev/null
+++ b/crates/ghidrust-core/src/callsite_hints.rs
@@ -0,0 +1,135 @@
+//! Evidence-gated Win64 callsite argument notes from a disasm listing.
+
+use ghidrust_decode::Instruction;
+use serde::Serialize;
+
+/// One recovered callsite with pre-call register / RIP-load evidence.
+#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
+pub struct CallsiteHint {
+ pub call_addr: String,
+ pub target: Option<String>,
+ /// Win64 arg regs observed defined before the call (`rcx`, `edx`/`rdx`, `r8`, `r9`).
+ pub args: Vec<CallsiteArg>,
+ /// RIP-relative loads seen in the lookback window (globals / image pointers).
+ pub rip_loads: Vec<String>,
+}
+
+#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
+pub struct CallsiteArg {
+ pub reg: String,
+ pub evidence: String,
+}
+
+const LOOKBACK: usize = 12;
+
+/// Scan decoded instructions for `call` sites and nearby Win64 arg setup.
+pub fn collect_callsite_hints(insns: &[Instruction]) -> Vec<CallsiteHint> {
+ let mut out = Vec::new();
+ for (i, insn) in insns.iter().enumerate() {
+ if !insn.mnemonic.eq_ignore_ascii_case("call") {
+ continue;
+ }
+ let start = i.saturating_sub(LOOKBACK);
+ let window = &insns[start..i];
+ let mut args = Vec::new();
+ let mut rip_loads = Vec::new();
+ for prev in window {
+ let ops = prev.operands.to_ascii_lowercase();
+ let mnem = prev.mnemonic.to_ascii_lowercase();
+ if is_rip_relative_load(&mnem, &ops) {
+ rip_loads.push(format!("{:#x}: {} {}", prev.address, prev.mnemonic, prev.operands));
+ }
+ if let Some((reg, evidence)) = win64_arg_def(prev) {
+ // Later defs override earlier for the same reg.
+ if let Some(existing) = args.iter_mut().find(|a: &&mut CallsiteArg| a.reg == reg) {
+ *existing = CallsiteArg { reg, evidence };
+ } else {
+ args.push(CallsiteArg { reg, evidence });
+ }
+ }
+ }
+ // Stable Win64 order.
+ args.sort_by_key(|a| win64_arg_rank(&a.reg));
+ if args.is_empty() && rip_loads.is_empty() {
+ continue;
+ }
+ let target = if insn.operands.trim().is_empty() {
+ None
+ } else {
+ Some(insn.operands.trim().to_string())
+ };
+ out.push(CallsiteHint {
+ call_addr: format!("{:#x}", insn.address),
+ target,
+ args,
+ rip_loads,
+ });
+ }
+ out
+}
+
+fn win64_arg_rank(reg: &str) -> u8 {
+ match reg {
+ "rcx" | "ecx" | "cl" => 0,
+ "rdx" | "edx" | "dl" => 1,
+ "r8" | "r8d" | "r8b" => 2,
+ "r9" | "r9d" | "r9b" => 3,
+ _ => 9,
+ }
+}
+
+fn is_rip_relative_load(mnem: &str, ops: &str) -> bool {
+ matches!(mnem, "mov" | "lea" | "movzx" | "movsx" | "movsxd")
+ && (ops.contains("[rip") || ops.contains("rip +") || ops.contains("rip-"))
+}
+
+fn win64_arg_def(insn: &Instruction) -> Option<(String, String)> {
+ let mnem = insn.mnemonic.to_ascii_lowercase();
+ if !matches!(
+ mnem.as_str(),
+ "mov" | "lea" | "xor" | "movzx" | "movsx" | "movsxd" | "and" | "or"
+ ) {
+ return None;
+ }
+ let ops = insn.operands.trim();
+ let (dst, _) = ops.split_once(',')?;
+ let dst = dst.trim().to_ascii_lowercase();
+ let canon = match dst.as_str() {
+ "rcx" | "ecx" | "cl" => "rcx",
+ "rdx" | "edx" | "dl" => "rdx",
+ "r8" | "r8d" | "r8b" => "r8",
+ "r9" | "r9d" | "r9b" => "r9",
+ _ => return None,
+ };
+ Some((
+ canon.to_string(),
+ format!("{:#x}: {} {}", insn.address, insn.mnemonic, insn.operands),
+ ))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use ghidrust_decode::Instruction;
+
+ fn insn(addr: u64, mnem: &str, ops: &str) -> Instruction {
+ Instruction::with_text(addr, vec![0x90], mnem, ops, 1)
+ }
+
+ #[test]
+ fn recovers_win64_args_before_call() {
+ let insns = vec![
+ insn(0x1000, "mov", "edx, dword ptr [rip + 0x10]"),
+ insn(0x1006, "mov", "rcx, qword ptr [rip + 0x20]"),
+ insn(0x100c, "lea", "r8, [rsp + 0x20]"),
+ insn(0x1010, "call", "0x2000"),
+ ];
+ let hints = collect_callsite_hints(&insns);
+ assert_eq!(hints.len(), 1);
+ assert_eq!(hints[0].args.len(), 3);
+ assert_eq!(hints[0].args[0].reg, "rcx");
+ assert_eq!(hints[0].args[1].reg, "rdx");
+ assert_eq!(hints[0].args[2].reg, "r8");
+ assert!(!hints[0].rip_loads.is_empty());
+ }
+}
diff --git a/crates/ghidrust-core/src/disasm.rs b/crates/ghidrust-core/src/disasm.rs
index 6a6f89b..62c999e 100644
--- a/crates/ghidrust-core/src/disasm.rs
+++ b/crates/ghidrust-core/src/disasm.rs
@@ -4,20 +4,123 @@
//! [`crate::program::Program`] and maps errors into [`crate::Error`].
use crate::error::{Error, Result};
+use crate::machine::{arch_mode_for_program, default_arch_mode};
use crate::program::Program;
+use ghidrust_decode::{
+ Engine, MnemOverride, Opt, SkipdataConfig, Syntax,
+};
+use ghidrust_decode::{Arch, Mode};
use serde::Serialize;
use std::collections::{HashSet, VecDeque};
pub use ghidrust_decode::{decode_one, Instruction};
+/// Optional engine overrides for a disassembly pass.
+#[derive(Debug, Clone, Default)]
+pub struct DisasmEngineOpts {
+ pub arch: Option<Arch>,
+ pub mode: Option<Mode>,
+ pub syntax: Option<Syntax>,
+ pub detail: Option<bool>,
+ pub detail_real: Option<bool>,
+ pub skipdata: Option<bool>,
+ pub skipdata_mnemonic: Option<String>,
+ pub skipdata_size: Option<usize>,
+ pub unsigned_imm: Option<bool>,
+ pub only_offset_branch: Option<bool>,
+ pub litbase: Option<u32>,
+ pub mnem_overrides: Option<Vec<(u32, String)>>,
+}
+
+impl DisasmEngineOpts {
+ pub fn open_engine(&self, prog: &Program) -> Result<Engine> {
+ open_engine_for(prog, Some(self))
+ }
+}
+
+fn open_engine_for(prog: &Program, opts: Option<&DisasmEngineOpts>) -> Result<Engine> {
+ let (mut arch, mut mode) = arch_mode_for_program(prog).unwrap_or_else(default_arch_mode);
+ if let Some(o) = opts {
+ if let Some(a) = o.arch {
+ arch = a;
+ }
+ if let Some(m) = o.mode {
+ mode = m;
+ }
+ }
+ let mut engine = Engine::open(arch, mode).map_err(|e| Error::Decode(e.to_string()))?;
+ if let Some(o) = opts {
+ apply_engine_opts(&mut engine, o)?;
+ }
+ Ok(engine)
+}
+
+fn apply_engine_opts(engine: &mut Engine, opts: &DisasmEngineOpts) -> Result<()> {
+ if let Some(v) = opts.syntax {
+ engine
+ .option(Opt::Syntax(v))
+ .map_err(|e| Error::Decode(e.to_string()))?;
+ }
+ if let Some(v) = opts.detail {
+ engine
+ .option(Opt::Detail(v))
+ .map_err(|e| Error::Decode(e.to_string()))?;
+ }
+ if let Some(v) = opts.detail_real {
+ engine
+ .option(Opt::DetailReal(v))
+ .map_err(|e| Error::Decode(e.to_string()))?;
+ }
+ if let Some(v) = opts.skipdata {
+ engine
+ .option(Opt::Skipdata(v))
+ .map_err(|e| Error::Decode(e.to_string()))?;
+ }
+ if opts.skipdata_mnemonic.is_some() || opts.skipdata_size.is_some() {
+ let mut cfg = SkipdataConfig::default();
+ if let Some(m) = &opts.skipdata_mnemonic {
+ cfg.mnemonic = m.clone();
+ }
+ engine
+ .option(Opt::SkipdataSetup(cfg))
+ .map_err(|e| Error::Decode(e.to_string()))?;
+ }
+ if let Some(v) = opts.unsigned_imm {
+ engine
+ .option(Opt::Unsigned(v))
+ .map_err(|e| Error::Decode(e.to_string()))?;
+ }
+ if let Some(v) = opts.only_offset_branch {
+ engine
+ .option(Opt::OnlyOffsetBranch(v))
+ .map_err(|e| Error::Decode(e.to_string()))?;
+ }
+ if let Some(v) = opts.litbase {
+ engine
+ .option(Opt::Litbase(v))
+ .map_err(|e| Error::Decode(e.to_string()))?;
+ }
+ if let Some(list) = &opts.mnem_overrides {
+ for (id, mnemonic) in list {
+ engine
+ .option(Opt::Mnemonic(MnemOverride {
+ id: *id,
+ mnemonic: mnemonic.clone(),
+ }))
+ .map_err(|e| Error::Decode(e.to_string()))?;
+ }
+ }
+ Ok(())
+}
+
/// Disassembly walk strategy.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum DisasmMode {
- /// Linear count-walk clamped to `[start, bound_end)` when set; stop on int3 padding.
+ /// Linear count-walk clamped to `[start, bound_end)` when set; stop on int3 padding.
Bounded,
- /// Follow fallthrough and branch targets; never leave `[start, bound_end)` when bound set.
+ /// Follow fallthrough and branch targets; never leave `[start, bound_end)` when bound set.
Flow,
- /// Legacy count-walk (no bound / int3 / seed stops).
+ /// Legacy count-walk (no bound / int3 / seed stops).
Linear,
}
@@ -33,10 +136,21 @@ pub enum DisasmStopReason {
}
pub fn disassemble_at(prog: &Program, va: u64) -> Result<Instruction> {
+ disassemble_at_opts(prog, va, None)
+}
+
+pub fn disassemble_at_opts(
+ prog: &Program,
+ va: u64,
+ engine_opts: Option<&DisasmEngineOpts>,
+) -> Result<Instruction> {
let bytes = prog
.read_va(va, 15)
- .ok_or_else(|| Error::OutOfBounds(format!("no bytes at {va:#x}")))?;
- Ok(decode_one(&bytes, va)?)
+ .ok_or_else(|| Error::OutOfBounds(format!("no bytes at {va:#x}")))?;
+ let mut engine = open_engine_for(prog, engine_opts)?;
+ engine
+ .disasm_one(&bytes, va)
+ .map_err(|e| Error::Decode(e.to_string()))
}
pub fn disassemble_range(prog: &Program, start: u64, max_insns: usize) -> Result<Vec<Instruction>> {
@@ -47,17 +161,17 @@ pub fn disassemble_range(prog: &Program, start: u64, max_insns: usize) -> Result
#[derive(Debug, Clone, Serialize)]
pub struct DisasmRangeResult {
pub insns: Vec<Instruction>,
- /// Number of undecodable byte positions skipped (soft-fail holes).
+ /// Number of undecodable byte positions skipped (soft-fail holes).
pub decode_gaps: usize,
- /// First gap VA when any gaps were skipped.
+ /// First gap VA when any gaps were skipped.
pub first_gap_va: Option<u64>,
- /// Why the walk stopped.
+ /// Why the walk stopped.
pub stop_reason: DisasmStopReason,
- /// Containing / resolved function entry when known.
- #[serde(skip_serializing_if = "Option::is_none")]
+ /// Containing / resolved function entry when known.
+ #[serde(skip_serializing_if = "Option::is_none")]
pub entry: Option<u64>,
- /// Function / bound end when known.
- #[serde(skip_serializing_if = "Option::is_none")]
+ /// Function / bound end when known.
+ #[serde(skip_serializing_if = "Option::is_none")]
pub end: Option<u64>,
}
@@ -91,26 +205,75 @@ pub fn disassemble_range_ex(
skip_bad: bool,
mode: DisasmMode,
bound_end: Option<u64>,
+) -> Result<DisasmRangeResult> {
+ disassemble_range_ex_opts(
+ prog,
+ start,
+ max_insns,
+ skip_bad,
+ mode,
+ bound_end,
+ None,
+ )
+}
+
+/// Extended disassembly with optional engine overrides.
+pub fn disassemble_range_ex_opts(
+ prog: &Program,
+ start: u64,
+ max_insns: usize,
+ skip_bad: bool,
+ mode: DisasmMode,
+ bound_end: Option<u64>,
+ engine_opts: Option<&DisasmEngineOpts>,
) -> Result<DisasmRangeResult> {
let meta_fn = prog.function_containing(start);
let entry = meta_fn.map(|f| f.entry);
let end = bound_end.or_else(|| meta_fn.map(|f| f.end));
let self_entry = entry;
+ let mut engine = open_engine_for(prog, engine_opts)?;
+
let mut result = match mode {
- DisasmMode::Linear => disasm_linear(prog, start, max_insns, skip_bad)?,
+ DisasmMode::Linear => disasm_linear(prog, &mut engine, start, max_insns, skip_bad)?,
DisasmMode::Bounded => {
- disasm_bounded(prog, start, max_insns, skip_bad, bound_end, self_entry)?
+ disasm_bounded(
+ prog,
+ &mut engine,
+ start,
+ max_insns,
+ skip_bad,
+ bound_end,
+ self_entry,
+ )?
}
- DisasmMode::Flow => disasm_flow(prog, start, max_insns, skip_bad, bound_end, self_entry)?,
+ DisasmMode::Flow => disasm_flow(
+ prog,
+ &mut engine,
+ start,
+ max_insns,
+ skip_bad,
+ bound_end,
+ self_entry,
+ )?,
};
result.entry = entry;
result.end = end;
Ok(result)
}
+fn disasm_at_engine(prog: &Program, engine: &mut Engine, va: u64) -> Result<Instruction> {
+ let bytes = prog
+ .read_va(va, 15)
+ .ok_or_else(|| Error::OutOfBounds(format!("no bytes at {va:#x}")))?;
+ engine
+ .disasm_one(&bytes, va)
+ .map_err(|e| Error::Decode(e.to_string()))
+}
+
fn disasm_linear(
prog: &Program,
+ engine: &mut Engine,
start: u64,
max_insns: usize,
skip_bad: bool,
@@ -128,7 +291,7 @@ fn disasm_linear(
};
while out.len() < max_insns && steps < max_steps {
steps += 1;
- match disassemble_at(prog, va) {
+ match disasm_at_engine(prog, engine, va) {
Ok(insn) => {
let len = insn.length.max(1) as u64;
va = va.wrapping_add(len);
@@ -149,7 +312,7 @@ fn disasm_linear(
}
}
if out.is_empty() {
- return Err(Error::Decode(format!("no instructions at {start:#x}")));
+ return Err(Error::Decode(format!("no instructions at {start:#x}")));
}
if out.len() >= max_insns {
stop_reason = DisasmStopReason::Count;
@@ -166,6 +329,7 @@ fn disasm_linear(
fn disasm_bounded(
prog: &Program,
+ engine: &mut Engine,
start: u64,
max_insns: usize,
skip_bad: bool,
@@ -199,11 +363,11 @@ fn disasm_bounded(
break;
}
steps += 1;
- match disassemble_at(prog, va) {
+ match disasm_at_engine(prog, engine, va) {
Ok(insn) => {
let next = va.wrapping_add(insn.length.max(1) as u64);
if let Some(end) = bound_end {
- // Instruction must start inside the bound; do not walk past end.
+ // Instruction must start inside the bound; do not walk past end.
if va >= end {
stop_reason = DisasmStopReason::FunctionEnd;
break;
@@ -227,7 +391,7 @@ fn disasm_bounded(
}
}
if out.is_empty() {
- return Err(Error::Decode(format!("no instructions at {start:#x}")));
+ return Err(Error::Decode(format!("no instructions at {start:#x}")));
}
if out.len() >= max_insns && stop_reason == DisasmStopReason::Count {
stop_reason = DisasmStopReason::Count;
@@ -244,6 +408,7 @@ fn disasm_bounded(
fn disasm_flow(
prog: &Program,
+ engine: &mut Engine,
start: u64,
max_insns: usize,
skip_bad: bool,
@@ -272,7 +437,7 @@ fn disasm_flow(
}
if va != start && is_next_seed(prog, va, self_entry) {
if out.is_empty() {
- // Should not happen for start; keep scanning other paths.
+ // Should not happen for start; keep scanning other paths.
continue;
}
stop_reason = DisasmStopReason::NextSeed;
@@ -282,7 +447,7 @@ fn disasm_flow(
stop_reason = DisasmStopReason::Int3;
continue;
}
- match disassemble_at(prog, va) {
+ match disasm_at_engine(prog, engine, va) {
Ok(insn) => {
let fallthrough = va.wrapping_add(insn.length.max(1) as u64);
let mnem = insn.mnemonic.clone();
@@ -321,7 +486,7 @@ fn disasm_flow(
}
if out.is_empty() {
- return Err(Error::Decode(format!("no instructions at {start:#x}")));
+ return Err(Error::Decode(format!("no instructions at {start:#x}")));
}
if out.len() >= max_insns {
stop_reason = DisasmStopReason::Count;
@@ -333,7 +498,7 @@ fn disasm_flow(
{
stop_reason = DisasmStopReason::FunctionEnd;
}
- // Stable address order for deterministic listings.
+ // Stable address order for deterministic listings.
out.sort_by_key(|i| i.address);
out.dedup_by_key(|i| i.address);
Ok(DisasmRangeResult {
@@ -363,41 +528,41 @@ fn is_next_seed(prog: &Program, va: u64, self_entry: Option<u64>) -> bool {
fn is_terminal_transfer(mnem: &str) -> bool {
matches!(
mnem,
- "jmp" | "jmpq" | "ret" | "retn" | "retq" | "iret" | "iretd" | "iretq"
+ "jmp" | "jmpq" | "ret" | "retn" | "retq" | "iret" | "iretd" | "iretq"
)
}
fn is_flow_mnemonic(mnem: &str) -> bool {
matches!(
mnem,
- "call"
- | "callq"
- | "jmp"
- | "jmpq"
- | "je"
- | "jne"
- | "jz"
- | "jnz"
- | "jl"
- | "jle"
- | "jg"
- | "jge"
- | "ja"
- | "jae"
- | "jb"
- | "jbe"
- | "jo"
- | "jno"
- | "js"
- | "jns"
- | "jp"
- | "jnp"
- | "jcxz"
- | "jecxz"
- | "jrcxz"
- | "loop"
- | "loope"
- | "loopne"
+ "call"
+ | "callq"
+ | "jmp"
+ | "jmpq"
+ | "je"
+ | "jne"
+ | "jz"
+ | "jnz"
+ | "jl"
+ | "jle"
+ | "jg"
+ | "jge"
+ | "ja"
+ | "jae"
+ | "jb"
+ | "jbe"
+ | "jo"
+ | "jno"
+ | "js"
+ | "jns"
+ | "jp"
+ | "jnp"
+ | "jcxz"
+ | "jecxz"
+ | "jrcxz"
+ | "loop"
+ | "loope"
+ | "loopne"
)
}
@@ -405,9 +570,9 @@ fn flow_targets(insn: &Instruction) -> Vec<u64> {
if !is_flow_mnemonic(&insn.mnemonic) {
return Vec::new();
}
- // Absolute hex / RIP-relative targets from operand text.
+ // Absolute hex / RIP-relative targets from operand text.
let mut out = crate::xrefs::instruction_targets(insn);
- // Prefer direct control-flow immediates; drop self-address noise.
+ // Prefer direct control-flow immediates; drop self-address noise.
out.retain(|t| *t != insn.address);
out
}
@@ -421,31 +586,31 @@ mod tests {
fn decode_push_rbp_mov_rbp_rsp() {
let b = [0x55, 0x48, 0x89, 0xe5];
let i0 = decode_one(&b, 0x1000).unwrap();
- assert_eq!(i0.mnemonic, "push");
- assert_eq!(i0.operands, "rbp");
+ assert_eq!(i0.mnemonic, "push");
+ assert_eq!(i0.operands, "rbp");
assert_eq!(i0.length, 1);
let i1 = decode_one(&b[1..], 0x1001).unwrap();
- assert_eq!(i1.mnemonic, "mov");
- assert_eq!(i1.operands, "rbp, rsp");
+ assert_eq!(i1.mnemonic, "mov");
+ assert_eq!(i1.operands, "rbp, rsp");
}
#[test]
fn decode_xor_eax_eax_ret() {
let b = [0x31, 0xc0, 0xc3];
let i0 = decode_one(&b, 0).unwrap();
- assert_eq!(i0.mnemonic, "xor");
- assert_eq!(i0.operands, "eax, eax");
+ assert_eq!(i0.mnemonic, "xor");
+ assert_eq!(i0.operands, "eax, eax");
let i1 = decode_one(&b[2..], 2).unwrap();
- assert_eq!(i1.mnemonic, "ret");
+ assert_eq!(i1.mnemonic, "ret");
}
#[test]
fn skip_bad_continues_after_hole() {
- let mut prog = Program::new("t".into(), "PE32+");
- // 0x06 is invalid in long mode; then xor eax,eax; ret
+ let mut prog = Program::new("t".into(), "PE32+");
+ // 0x06 is invalid in long mode; then xor eax,eax; ret
let bytes = vec![0x06, 0x31, 0xc0, 0xc3];
prog.blocks.push(MemoryBlock {
- name: ".text".into(),
+ name: ".text".into(),
va: 0x1000,
size: bytes.len() as u64,
bytes,
@@ -457,18 +622,18 @@ mod tests {
assert!(listing.decode_gaps >= 1);
assert_eq!(listing.first_gap_va, Some(0x1000));
assert!(
- listing.insns.iter().any(|i| i.mnemonic == "xor"),
- "{:?}",
+ listing.insns.iter().any(|i| i.mnemonic == "xor"),
+ "{:?}",
listing.insns
);
- assert!(listing.insns.iter().any(|i| i.mnemonic == "ret"));
+ assert!(listing.insns.iter().any(|i| i.mnemonic == "ret"));
assert_eq!(listing.stop_reason, DisasmStopReason::Count);
}
#[test]
fn bounded_excludes_adjacent_sibling_function() {
- // fn_a: push rbp; mov rbp, rsp; ret; int3; int3
- // fn_b: xor eax, eax; ret
+ // fn_a: push rbp; mov rbp, rsp; ret; int3; int3
+ // fn_b: xor eax, eax; ret
let mut bytes = vec![0x55, 0x48, 0x89, 0xe5, 0xc3, 0xcc, 0xcc, 0x31, 0xc0, 0xc3];
let base = 0x140001000u64;
let fn_a_entry = base;
@@ -476,9 +641,9 @@ mod tests {
let fn_b_entry = base + 7;
let fn_b_end = base + bytes.len() as u64;
- let mut prog = Program::new("t".into(), "PE32+");
+ let mut prog = Program::new("t".into(), "PE32+");
prog.blocks.push(MemoryBlock {
- name: ".text".into(),
+ name: ".text".into(),
va: base,
size: bytes.len() as u64,
bytes: std::mem::take(&mut bytes),
@@ -488,10 +653,10 @@ mod tests {
});
prog.analysis
.functions
- .push(FunctionInfo::new(fn_a_entry, fn_a_end, "fn_a"));
+ .push(FunctionInfo::new(fn_a_entry, fn_a_end, "fn_a"));
prog.analysis
.functions
- .push(FunctionInfo::new(fn_b_entry, fn_b_end, "fn_b"));
+ .push(FunctionInfo::new(fn_b_entry, fn_b_end, "fn_b"));
let listing = disassemble_range_ex(
&prog,
@@ -505,21 +670,21 @@ mod tests {
assert!(
listing.insns.iter().all(|i| i.address < fn_b_entry),
- "bounded listing leaked into sibling: {:?}",
+ "bounded listing leaked into sibling: {:?}",
listing.insns
);
assert!(
- !listing.insns.iter().any(|i| i.mnemonic == "xor"),
- "sibling xor must be excluded: {:?}",
+ !listing.insns.iter().any(|i| i.mnemonic == "xor"),
+ "sibling xor must be excluded: {:?}",
listing.insns
);
- assert!(listing.insns.iter().any(|i| i.mnemonic == "ret"));
+ assert!(listing.insns.iter().any(|i| i.mnemonic == "ret"));
assert!(
matches!(
listing.stop_reason,
DisasmStopReason::FunctionEnd | DisasmStopReason::Int3 | DisasmStopReason::NextSeed
),
- "stop_reason={:?}",
+ "stop_reason={:?}",
listing.stop_reason
);
assert_eq!(listing.entry, Some(fn_a_entry));
@@ -528,9 +693,9 @@ mod tests {
#[test]
fn int3_padding_helper() {
- let mut prog = Program::new("t".into(), "PE32+");
+ let mut prog = Program::new("t".into(), "PE32+");
prog.blocks.push(MemoryBlock {
- name: ".text".into(),
+ name: ".text".into(),
va: 0x1000,
size: 4,
bytes: vec![0xcc, 0xcc, 0xc3, 0x90],
diff --git a/crates/ghidrust-core/src/edits.rs b/crates/ghidrust-core/src/edits.rs
index 8df4a43..8603c32 100644
--- a/crates/ghidrust-core/src/edits.rs
+++ b/crates/ghidrust-core/src/edits.rs
@@ -1,11 +1,11 @@
-//! User-editable program state — Ghidra `ProgramDB` equivalent for the Ghidrust GUI.
+//! User-editable program state — `ProgramDB` equivalent for the Ghidrust GUI.
//!
//! Rename / retype / edit-signature / comment operations mutate this side-car
//! store rather than the primary analysis output. This preserves the "analyzer
//! output is honest" invariant while still letting the UI persist user
//! decisions across saves.
//!
-//! Keys are **virtual addresses** (Ghidra `Address`). Where a symbol has both
+//! Keys are **virtual addresses**. Where a symbol has both
//! an analyzer-provided name and a user rename, the user rename wins in
//! [`Program::display_name_at`] / [`Program::display_function_name_at`].
@@ -14,10 +14,7 @@ use std::collections::{BTreeMap, BTreeSet};
use crate::program::Program;
-/// Ghidra comment kinds attached to a code unit (per [Comment types] in
-/// `CodeUnit.EOL_COMMENT` etc).
-///
-/// [Comment types]: https://ghidra.re/ghidra_docs/api/ghidra/program/model/listing/CodeUnit.html
+/// Comment kinds attached to a code unit (EOL / pre / post / plate / repeatable).
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub enum CommentKind {
Eol,
@@ -47,7 +44,7 @@ impl CommentKind {
}
}
-/// One record for a function-signature edit (Ghidra's `Edit Function Signature`).
+/// One record for a function-signature edit.
///
/// Values are captured as strings so Stage-0 doesn't need to depend on a real
/// C parser; the plan is to attach a parsed `FunctionPrototype`
@@ -66,13 +63,13 @@ pub struct FunctionSignatureEdit {
pub locals: Vec<String>,
}
-/// One record for a variable/global retype (`Ctrl+L` in Ghidra).
+/// One record for a variable/global retype.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RetypeEdit {
pub type_desc: String,
}
-/// One record for an equate — Ghidra `EquateTablePlugin` binds a symbolic name
+/// One record for an equate — `EquateTablePlugin` binds a symbolic name
/// to a scalar so the Listing can render `MY_FLAG` instead of `0x1234`.
///
/// Equates are attached to a (VA, operand-index) pair rather than to the raw
@@ -80,7 +77,7 @@ pub struct RetypeEdit {
/// every occurrence in the program.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct EquateEdit {
- /// Ghidra display name (e.g. `SW_HIDE`, `O_RDONLY`).
+ /// display name (e.g. `SW_HIDE`, `O_RDONLY`).
pub name: String,
/// Underlying scalar value the equate stands in for.
pub value: i64,
@@ -104,19 +101,19 @@ pub struct ProgramEdits {
/// Function-signature edits keyed by function entry VA.
#[serde(default)]
pub function_signatures: BTreeMap<u64, FunctionSignatureEdit>,
- /// User-defined data types (name → Ghidra-C style description).
+ /// User-defined data types.
/// 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).
#[serde(default)]
pub applied_types: BTreeMap<u64, String>,
- /// Equates keyed by `(va, op_index)` — Ghidra `EquateTablePlugin` model.
+ /// Equates keyed by `(va, op_index)` — `EquateTablePlugin` model.
///
/// Serialized as a flat `Vec` because JSON map keys must be strings.
#[serde(default, with = "equates_serde")]
pub equates: BTreeMap<(u64, u8), EquateEdit>,
- /// Per-function tags (Ghidra `FunctionTagPlugin`). Keyed by function entry VA.
+ /// Per-function tags. Keyed by function entry VA.
#[serde(default)]
pub function_tags: BTreeMap<u64, BTreeSet<String>>,
/// The universe of tags the user has ever created — retained even when no
@@ -350,7 +347,7 @@ impl ProgramEdits {
}
}
- // ─── Equates (Ghidra `EquateTablePlugin`) ────────────────────────────
+ // ─── Equates ────────────────────────────
/// Attach an equate at `(va, op_index)`.
pub fn set_equate(&mut self, va: u64, op: u8, name: impl Into<String>, value: i64) {
@@ -391,7 +388,7 @@ impl ProgramEdits {
.collect()
}
- // ─── Function Tags (Ghidra `FunctionTagPlugin`) ─────────────────────
+ // ─── Function Tags ─────────────────────
/// Whether `entry` currently has `tag` assigned.
pub fn function_has_tag(&self, entry: u64, tag: &str) -> bool {
@@ -509,8 +506,8 @@ impl Program {
}
}
-/// Built-in data types Ghidra exposes in the "BuiltInTypes" archive (subset relevant
-/// to Ghidrust's Stage-0 rendering). Ordered as Ghidra shows them in the DTM.
+/// Built-in data types exposes in the "BuiltInTypes" archive (subset relevant
+/// to Ghidrust's Stage-0 rendering). Ordered as shows them in the DTM.
pub const BUILTIN_TYPES: &[&str] = &[
"void", "bool",
"byte", "sbyte", "word", "sword", "dword", "sdword", "qword", "sqword",
diff --git a/crates/ghidrust-core/src/error.rs b/crates/ghidrust-core/src/error.rs
index 98b3b4c..1c02072 100644
--- a/crates/ghidrust-core/src/error.rs
+++ b/crates/ghidrust-core/src/error.rs
@@ -25,9 +25,7 @@ impl std::error::Error for Error {}
impl From<ghidrust_decode::Error> for Error {
fn from(e: ghidrust_decode::Error) -> Self {
- match e {
- ghidrust_decode::Error::Decode(m) => Error::Decode(m),
- }
+ Error::Decode(e.to_string())
}
}
diff --git a/crates/ghidrust-core/src/lib.rs b/crates/ghidrust-core/src/lib.rs
index 315767c..6730b13 100644
--- a/crates/ghidrust-core/src/lib.rs
+++ b/crates/ghidrust-core/src/lib.rs
@@ -2,7 +2,9 @@
pub mod analyzers;
pub mod artifacts;
+pub mod bounds_honesty;
pub mod bulk_scan;
+pub mod callsite_hints;
pub mod edits;
pub mod gpu_analyzers;
pub mod disasm;
@@ -11,6 +13,7 @@ pub mod error;
pub mod imports;
pub mod inventory;
pub mod io_util;
+pub mod machine;
pub mod pe;
pub mod pe_functions;
pub mod process;
@@ -48,8 +51,17 @@ pub use artifacts::{
ArtifactEnvelope, ArtifactMeta, DEFAULT_PREVIEW_LIMIT,
};
pub use disasm::{
- decode_one, disassemble_at, disassemble_range, disassemble_range_ex, disassemble_range_opts,
- int3_padding_at, DisasmMode, DisasmRangeResult, DisasmStopReason, Instruction,
+ decode_one, disassemble_at, disassemble_at_opts, disassemble_range, disassemble_range_ex,
+ disassemble_range_ex_opts, disassemble_range_opts, int3_padding_at, DisasmEngineOpts,
+ DisasmMode, DisasmRangeResult, DisasmStopReason, Instruction,
+};
+pub use machine::{
+ arch_mode_for_program, arch_mode_from_elf_emachine, arch_mode_from_pe_machine,
+ default_arch_mode, elf_class_from_bytes, elf_emachine_from_bytes, pe_machine_from_bytes,
+};
+pub use ghidrust_decode::{
+ self, support, Arch, Engine, GroupId, InsnId, Mode, Opt, RegId, Syntax, SupportQuery,
+ VERSION as DECODE_VERSION,
};
pub use imports::{filter_imports, load_imports, parse_pe_imports};
pub use inventory::{
@@ -58,10 +70,16 @@ pub use inventory::{
};
pub use io_util::{sanitize_path_component, sanitized_out_name, write_json_no_bom};
pub use process::{
- process_attach, process_detach, process_list, process_modules, process_read, process_regions,
- process_resolve, static_to_live, ModuleInfo, ProcessInfo, ProcessSession, ReadResult,
- RegionInfo, ResolveLive,
+ launch_command_line, process_attach, process_detach, process_is_suspended, process_launch,
+ process_list, process_modules, process_read, process_regions, process_resolve, process_resume,
+ static_to_live, LaunchRequest, LaunchResult, ModuleInfo, ProcessInfo, ProcessSession,
+ ReadResult, RegionInfo, ResolveLive,
+};
+pub use bounds_honesty::{
+ assess_bounds_honesty, assess_decompile_bounds, BoundsHonesty, SHORT_INSN_COUNT,
+ SHORT_SPAN_BYTES,
};
+pub use callsite_hints::{collect_callsite_hints, CallsiteArg, CallsiteHint};
pub use pe_functions::{
create_function, create_function_with_kind, functions_from_runtime, grow_function,
parse_export_code_vas, parse_runtime_functions, runtime_function_containing, RuntimeFunction,
@@ -105,7 +123,7 @@ pub fn load_bytes(data: &[u8], name: impl Into<String>) -> Result<Program> {
elf::load_elf(data, name)
} else {
Err(Error::UnsupportedFormat(
- "not a PE or ELF image (bad magic)".into(),
+ "not a PE or ELF image (bad magic)".into(),
))
}
}
@@ -116,12 +134,12 @@ pub fn load_bytes(data: &[u8], name: impl Into<String>) -> Result<Program> {
/// the whole file is one memory block at VA 0.
pub fn load_blob(data: &[u8], name: impl Into<String>) -> Program {
let name = name.into();
- let mut prog = Program::new(name, "blob");
+ let mut prog = Program::new(name, "blob");
prog.image_base = 0;
prog.file_bytes = data.to_vec();
let size = data.len() as u64;
prog.sections.push(program::SectionInfo {
- name: ".blob".into(),
+ name: ".blob".into(),
va: 0,
virtual_size: size,
raw_size: size,
@@ -129,7 +147,7 @@ pub fn load_blob(data: &[u8], name: impl Into<String>) -> Program {
characteristics: 0,
});
prog.blocks.push(program::MemoryBlock {
- name: ".blob".into(),
+ name: ".blob".into(),
va: 0,
size,
bytes: data.to_vec(),
@@ -166,7 +184,7 @@ pub fn load_path_opts(path: impl AsRef<Path>, allow_blob: bool) -> Result<Progra
let name = path
.file_name()
.map(|s| s.to_string_lossy().into_owned())
- .unwrap_or_else(|| "image".into());
+ .unwrap_or_else(|| "image".into());
load_bytes_opts(&data, name, allow_blob)
}
@@ -200,10 +218,10 @@ pub struct AnalysisBundle {
/// Resolve path to committed fixtures (workspace `fixtures/`).
pub fn fixture_path(name: &str) -> PathBuf {
- let mut p = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
+ let mut p = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
p.pop();
p.pop();
- p.push("fixtures");
+ p.push("fixtures");
p.push(name);
p
}
@@ -214,37 +232,37 @@ mod tests {
#[test]
fn load_pe_fixture_sections_and_bytes() {
- let path = fixture_path("tiny_x64.pe");
- let prog = load_path(&path).expect("load pe");
- assert_eq!(prog.format, "PE32+");
+ let path = fixture_path("tiny_x64.pe");
+ let prog = load_path(&path).expect("load pe");
+ assert_eq!(prog.format, "PE32+");
assert_eq!(prog.image_base, 0x140000000);
assert_eq!(prog.entry, Some(0x140001000));
- let bytes = prog.read_va(0x140001000, 8).expect("code bytes");
+ let bytes = prog.read_va(0x140001000, 8).expect("code bytes");
assert_eq!(bytes, vec![0x55, 0x48, 0x89, 0xE5, 0x31, 0xC0, 0x5D, 0xC3]);
}
#[test]
fn disassemble_pe_entry_matches_ground_truth() {
- let prog = load_path(fixture_path("tiny_x64.pe")).unwrap();
+ let prog = load_path(fixture_path("tiny_x64.pe")).unwrap();
let listing = disassemble_range(&prog, prog.entry.unwrap(), 8).unwrap();
assert!(listing.len() >= 5);
- assert_eq!(listing[0].mnemonic, "push");
- assert_eq!(listing[4].mnemonic, "ret");
+ assert_eq!(listing[0].mnemonic, "push");
+ assert_eq!(listing[4].mnemonic, "ret");
}
#[test]
fn rtti_recovers_widget() {
- let prog = load_path(fixture_path("tiny_x64.pe")).unwrap();
+ let prog = load_path(fixture_path("tiny_x64.pe")).unwrap();
let report = recover_rtti(&prog).unwrap();
- assert!(report.classes.iter().any(|c| c.name == "Widget"));
+ assert!(report.classes.iter().any(|c| c.name == "Widget"));
}
#[test]
fn analyze_path_bundle_all_default_ok() {
- let b = analyze_path(fixture_path("tiny_x64.pe")).unwrap();
+ let b = analyze_path(fixture_path("tiny_x64.pe")).unwrap();
assert!(!b.listing.is_empty());
for r in &b.analysis.results {
- assert_eq!(r.status, "ok", "{}", r.name);
+ assert_eq!(r.status, "ok", "{}", r.name);
}
}
}
diff --git a/crates/ghidrust-core/src/machine.rs b/crates/ghidrust-core/src/machine.rs
new file mode 100644
index 0000000..18826a2
--- /dev/null
+++ b/crates/ghidrust-core/src/machine.rs
@@ -0,0 +1,124 @@
+//! Map PE `Machine` / ELF `e_machine` → [`ghidrust_decode::Arch`] + [`ghidrust_decode::Mode`].
+
+use crate::pe;
+use crate::program::Program;
+use ghidrust_decode::{Arch, Mode};
+
+/// PE COFF `Machine` field when present.
+pub fn pe_machine_from_bytes(data: &[u8]) -> Option<u16> {
+ if !pe::is_pe(data) {
+ return None;
+ }
+ let e_lfanew = u32::from_le_bytes(data.get(0x3C..0x40)?.try_into().ok()?) as usize;
+ let coff = e_lfanew.checked_add(4)?;
+ let machine = u16::from_le_bytes(data.get(coff..coff + 2)?.try_into().ok()?);
+ Some(machine)
+}
+
+/// ELF `e_machine` when present.
+pub fn elf_emachine_from_bytes(data: &[u8]) -> Option<u16> {
+ if data.len() < 20 || data.get(0..4)? != &[0x7f, b'E', b'L', b'F'] {
+ return None;
+ }
+ Some(u16::from_le_bytes(data[18..20].try_into().ok()?))
+}
+
+/// ELF class byte (`EI_CLASS`): 1 = ELF32, 2 = ELF64.
+pub fn elf_class_from_bytes(data: &[u8]) -> Option<u8> {
+ if data.len() < 5 || data.get(0..4)? != &[0x7f, b'E', b'L', b'F'] {
+ return None;
+ }
+ Some(data[4])
+}
+
+/// Map a PE COFF machine constant to decode arch/mode.
+pub fn arch_mode_from_pe_machine(machine: u16) -> Option<(Arch, Mode)> {
+ match machine {
+ 0x014c => Some((Arch::X86, Mode::MODE_32)), // IMAGE_FILE_MACHINE_I386
+ 0x8664 => Some((Arch::X86, Mode::MODE_64)), // IMAGE_FILE_MACHINE_AMD64
+ 0x01c0 => Some((Arch::Arm, Mode::ARM)), // IMAGE_FILE_MACHINE_ARM
+ 0x01c2 => Some((Arch::Arm, Mode::ARM)), // IMAGE_FILE_MACHINE_THUMB
+ 0x01c4 => Some((Arch::Arm, Mode::THUMB)), // IMAGE_FILE_MACHINE_ARMNT
+ 0xaa64 => Some((Arch::Arm64, Mode::LITTLE_ENDIAN)), // IMAGE_FILE_MACHINE_ARM64
+ 0x0266 => Some((Arch::Mips, Mode::MIPS32)), // IMAGE_FILE_MACHINE_R3000
+ 0x0366 => Some((Arch::Mips, Mode::MIPS32)), // IMAGE_FILE_MACHINE_R4000
+ 0x0200 => Some((Arch::Mips, Mode::MIPS64)), // IMAGE_FILE_MACHINE_IA64 (legacy label)
+ 0x01f0 | 0x01f1 => Some((Arch::Ppc, Mode::PPC32)), // PPC / PPCFP
+ 0x0162 => Some((Arch::Riscv, Mode::RISCV32)),
+ 0x0163 | 0x0168 => Some((Arch::Riscv, Mode::RISCV64)),
+ 0x014d => Some((Arch::Alpha, Mode::LITTLE_ENDIAN)), // IMAGE_FILE_MACHINE_ALPHA
+ 0x014f => Some((Arch::Alpha, Mode::LITTLE_ENDIAN)), // IMAGE_FILE_MACHINE_ALPHA64
+ 0x0169 => Some((Arch::Sparc, Mode::V9)), // IMAGE_FILE_MACHINE_SPARC64 (approx)
+ 0x01d3 => Some((Arch::M68k, Mode::LITTLE_ENDIAN)), // AM33 — m68k family bucket
+ 0x014e => Some((Arch::Sparc, Mode::V9)),
+ 0x01a2 | 0x01a3 | 0x01a6 | 0x01a8 => Some((Arch::Sh, Mode::LITTLE_ENDIAN)),
+ 0x01df => Some((Arch::Sysz, Mode::LITTLE_ENDIAN)), // SH4 — bucket for sysz-class BE hosts
+ _ => None,
+ }
+}
+
+/// Map ELF `e_machine` (+ class) to decode arch/mode.
+pub fn arch_mode_from_elf_emachine(em: u16, elf_class: u8) -> Option<(Arch, Mode)> {
+ let is64 = elf_class == 2;
+ match em {
+ 3 => Some((Arch::X86, Mode::MODE_32)), // EM_386
+ 62 => Some((Arch::X86, Mode::MODE_64)), // EM_X86_64
+ 40 => Some((Arch::Arm, Mode::ARM)), // EM_ARM
+ 183 => Some((Arch::Arm64, Mode::LITTLE_ENDIAN)), // EM_AARCH64
+ 8 => Some((Arch::Mips, if is64 { Mode::MIPS64 } else { Mode::MIPS32 })), // EM_MIPS
+ 20 => Some((Arch::Ppc, Mode::PPC32)), // EM_PPC
+ 21 => Some((Arch::Ppc, Mode::PPC64)), // EM_PPC64
+ 243 => Some((Arch::Riscv, if is64 { Mode::RISCV64 } else { Mode::RISCV32 })), // EM_RISCV
+ 2 => Some((Arch::Sparc, Mode::V9)), // EM_SPARC
+ 22 => Some((Arch::Sysz, Mode::LITTLE_ENDIAN)), // EM_S390
+ 4 => Some((Arch::M68k, Mode::LITTLE_ENDIAN)), // EM_68K
+ 36902 => Some((Arch::Alpha, Mode::LITTLE_ENDIAN)), // EM_ALPHA
+ 42 => Some((Arch::Sparc, Mode::V9)), // EM_SPARCV9
+ _ => None,
+ }
+}
+
+/// Best-effort arch/mode for a loaded [`Program`].
+pub fn arch_mode_for_program(prog: &Program) -> Option<(Arch, Mode)> {
+ if prog.format.starts_with("PE") {
+ pe_machine_from_bytes(&prog.file_bytes)
+ .and_then(arch_mode_from_pe_machine)
+ } else if prog.format.starts_with("ELF") {
+ let em = elf_emachine_from_bytes(&prog.file_bytes)?;
+ let class = elf_class_from_bytes(&prog.file_bytes).unwrap_or(2);
+ arch_mode_from_elf_emachine(em, class)
+ } else {
+ None
+ }
+}
+
+/// Default x86-64 engine tuple when image machine is unknown.
+pub fn default_arch_mode() -> (Arch, Mode) {
+ (Arch::X86, Mode::MODE_64)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn pe_amd64_maps_x86_64() {
+ let (arch, mode) = arch_mode_from_pe_machine(0x8664).unwrap();
+ assert_eq!(arch, Arch::X86);
+ assert!(mode.intersects(Mode::MODE_64));
+ }
+
+ #[test]
+ fn pe_i386_maps_x86_32() {
+ let (arch, mode) = arch_mode_from_pe_machine(0x014c).unwrap();
+ assert_eq!(arch, Arch::X86);
+ assert!(mode.intersects(Mode::MODE_32));
+ }
+
+ #[test]
+ fn elf_x86_64_maps() {
+ let (arch, mode) = arch_mode_from_elf_emachine(62, 2).unwrap();
+ assert_eq!(arch, Arch::X86);
+ assert!(mode.intersects(Mode::MODE_64));
+ }
+}
diff --git a/crates/ghidrust-core/src/pe_functions.rs b/crates/ghidrust-core/src/pe_functions.rs
index 21baa64..e84facb 100644
--- a/crates/ghidrust-core/src/pe_functions.rs
+++ b/crates/ghidrust-core/src/pe_functions.rs
@@ -1,6 +1,6 @@
//! PE Exception Directory (.pdata) RUNTIME_FUNCTION + export seeds + function create.
//!
-//! Hand-rolled PE parse (no goblin). Industry-aligned function seeding for PE64.
+//! Hand-rolled PE parse. Industry-aligned function seeding for PE64.
use crate::disasm::decode_one;
use crate::program::{FunctionInfo, FunctionSeedKind, Program};
@@ -185,6 +185,17 @@ pub fn create_function_with_kind(
}
return prog.function_at(addr).cloned().unwrap_or(existing);
}
+ // Re-grow truncated stored ends (heal path when --end omitted).
+ let grown = grow_function(prog, addr, None);
+ if grown > existing.end {
+ if let Some(f) = prog.function_at_mut(addr) {
+ f.end = grown;
+ if f.seed_kind.is_none() {
+ f.seed_kind = Some(kind);
+ }
+ }
+ return prog.function_at(addr).cloned().unwrap_or(existing);
+ }
return existing;
}
let end = end_opt.unwrap_or_else(|| grow_function(prog, addr, None));
@@ -553,4 +564,30 @@ mod tests {
assert_eq!(f.seed_kind, Some(FunctionSeedKind::Manual));
assert_eq!(prog.analysis.functions.len(), 1);
}
+
+ #[test]
+ fn create_function_regrows_truncated_existing() {
+ let mut prog = Program::new("t".into(), "PE32+");
+ let code = vec![
+ 0x55, 0x48, 0x89, 0xE5, 0x41, 0x56, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90,
+ 0x31, 0xC0, 0x5D, 0xC3, 0xCC, 0xCC,
+ ];
+ prog.blocks.push(MemoryBlock {
+ name: ".text".into(),
+ va: 0x1000,
+ size: code.len() as u64,
+ bytes: code,
+ readable: true,
+ writable: false,
+ executable: true,
+ });
+ // Truncated end (prologue-only style).
+ prog.analysis.functions.push(
+ FunctionInfo::new(0x1000, 0x1011, "FUN_1000")
+ .with_seed_kind(FunctionSeedKind::Manual),
+ );
+ let f = create_function(&mut prog, 0x1000, None);
+ assert!(f.end > 0x1011, "expected re-grow past truncated end, got {:#x}", f.end);
+ assert_eq!(prog.function_at(0x1000).unwrap().end, f.end);
+ }
}
diff --git a/crates/ghidrust-core/src/process.rs b/crates/ghidrust-core/src/process.rs
index 4f676f9..7ccf5eb 100644
--- a/crates/ghidrust-core/src/process.rs
+++ b/crates/ghidrust-core/src/process.rs
@@ -1,23 +1,25 @@
//! Live Process Bridge (Windows) — hand-rolled Win32 FFI.
//!
-//! MVP: list / attach / modules / read / resolve / regions. No write or breakpoints.
+//! MVP: list / attach / launch(suspended) / resume / modules / read / resolve /
+//! regions. No write, breakpoints, or WaitForDebugEvent agent.
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
+use std::path::{Path, PathBuf};
use std::sync::Mutex;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProcessInfo {
pub pid: u32,
pub name: String,
- #[serde(skip_serializing_if = "Option::is_none")]
+ #[serde(skip_serializing_if = "Option::is_none")]
pub path: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ModuleInfo {
pub name: String,
- #[serde(skip_serializing_if = "Option::is_none")]
+ #[serde(skip_serializing_if = "Option::is_none")]
pub path: Option<String>,
pub base: u64,
pub size: u64,
@@ -45,11 +47,11 @@ pub struct ReadResult {
pub bytes_read: usize,
pub hex: String,
pub bytes: Vec<u8>,
- #[serde(skip_serializing_if = "Option::is_none")]
+ #[serde(skip_serializing_if = "Option::is_none")]
pub error: Option<String>,
- #[serde(skip_serializing_if = "Option::is_none")]
+ #[serde(skip_serializing_if = "Option::is_none")]
pub as_u64: Option<Vec<u64>>,
- #[serde(skip_serializing_if = "Option::is_none")]
+ #[serde(skip_serializing_if = "Option::is_none")]
pub as_f32: Option<Vec<f32>>,
}
@@ -61,10 +63,34 @@ pub struct ResolveLive {
pub live_va: u64,
}
+/// Spawn a new process under the Live Process Bridge (CREATE_SUSPENDED).
+#[derive(Debug, Clone)]
+pub struct LaunchRequest {
+ pub image: PathBuf,
+ pub args: Option<String>,
+ pub cwd: Option<PathBuf>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct LaunchResult {
+ pub session: ProcessSession,
+ pub image: String,
+ /// True until `process_resume` (CREATE_SUSPENDED; not a debug break-at-entry).
+ pub suspended: bool,
+ pub primary_tid: u32,
+}
+
struct Attached {
pid: u32,
#[cfg(windows)]
handle: isize,
+ /// Primary thread from CreateProcess (launch only); closed on detach.
+ #[cfg(windows)]
+ thread: Option<isize>,
+ suspended: bool,
+ /// Image path when created via [`process_launch`].
+ #[allow(dead_code)]
+ launched_image: Option<String>,
}
static SESSIONS: Mutex<Option<HashMap<String, Attached>>> = Mutex::new(None);
@@ -75,7 +101,7 @@ where
{
let mut guard = SESSIONS.lock().unwrap_or_else(|e| e.into_inner());
if guard.is_none() {
- *guard = Some(HashMap::new());
+ *guard = Some(HashMap::new());
}
f(guard.as_mut().unwrap())
}
@@ -83,9 +109,9 @@ where
#[cfg(windows)]
mod win {
use super::*;
- use std::ffi::OsString;
+ use std::ffi::{OsStr, OsString};
use std::mem::{size_of, zeroed};
- use std::os::windows::ffi::OsStringExt;
+ use std::os::windows::ffi::{OsStrExt, OsStringExt};
use std::ptr;
type HANDLE = isize;
@@ -103,8 +129,40 @@ mod win {
const MEM_COMMIT: DWORD = 0x1000;
const MEM_FREE: DWORD = 0x10000;
const MEM_RESERVE: DWORD = 0x2000;
+ const CREATE_SUSPENDED: DWORD = 0x0000_0004;
+ const CREATE_UNICODE_ENVIRONMENT: DWORD = 0x0000_0400;
const MAX_PATH: usize = 260;
+ #[repr(C)]
+ struct STARTUPINFOW {
+ cb: DWORD,
+ lp_reserved: *mut u16,
+ lp_desktop: *mut u16,
+ lp_title: *mut u16,
+ dw_x: DWORD,
+ dw_y: DWORD,
+ dw_x_size: DWORD,
+ dw_y_size: DWORD,
+ dw_x_count_chars: DWORD,
+ dw_y_count_chars: DWORD,
+ dw_fill_attribute: DWORD,
+ dw_flags: DWORD,
+ w_show_window: u16,
+ cb_reserved2: u16,
+ lp_reserved2: *mut u8,
+ h_std_input: HANDLE,
+ h_std_output: HANDLE,
+ h_std_error: HANDLE,
+ }
+
+ #[repr(C)]
+ struct PROCESS_INFORMATION {
+ h_process: HANDLE,
+ h_thread: HANDLE,
+ dw_process_id: DWORD,
+ dw_thread_id: DWORD,
+ }
+
#[repr(C)]
struct PROCESSENTRY32W {
dw_size: DWORD,
@@ -144,8 +202,8 @@ mod win {
typ: DWORD,
}
- #[link(name = "kernel32")]
- extern "system" {
+ #[link(name = "kernel32")]
+ extern "system" {
fn OpenProcess(access: DWORD, inherit: BOOL, pid: DWORD) -> HANDLE;
fn CloseHandle(h: HANDLE) -> BOOL;
fn ReadProcessMemory(
@@ -172,6 +230,107 @@ mod win {
buf: *mut u16,
size: *mut DWORD,
) -> BOOL;
+ fn CreateProcessW(
+ app: *const u16,
+ cmdline: *mut u16,
+ proc_attr: *const u8,
+ thread_attr: *const u8,
+ inherit: BOOL,
+ flags: DWORD,
+ env: *const u8,
+ cwd: *const u16,
+ si: *const STARTUPINFOW,
+ pi: *mut PROCESS_INFORMATION,
+ ) -> BOOL;
+ fn ResumeThread(h: HANDLE) -> DWORD;
+ fn GetLastError() -> DWORD;
+ }
+
+ fn to_wide_z(s: &str) -> Vec<u16> {
+ let mut v: Vec<u16> = OsStr::new(s).encode_wide().collect();
+ v.push(0);
+ v
+ }
+
+ /// Build Win32 command line: quoted image path + optional args tail.
+ pub fn build_command_line(image: &Path, args: Option<&str>) -> String {
+ let img = image.to_string_lossy();
+ let quoted = if img.contains(char::is_whitespace) || img.contains('"') {
+ format!("\"{}\"", img.replace('"', ""))
+ } else {
+ img.into_owned()
+ };
+ match args.map(str::trim).filter(|a| !a.is_empty()) {
+ Some(a) => format!("{quoted} {a}"),
+ None => quoted,
+ }
+ }
+
+ pub fn launch(
+ image: &Path,
+ args: Option<&str>,
+ cwd: Option<&Path>,
+ ) -> Result<(String, HANDLE, HANDLE, u32, u32, String), String> {
+ if !image.is_file() {
+ return Err(format!(
+ "launch image not found or not a file: {}",
+ image.display()
+ ));
+ }
+ let image_str = image
+ .canonicalize()
+ .unwrap_or_else(|_| image.to_path_buf())
+ .to_string_lossy()
+ .into_owned();
+ let cmdline = build_command_line(Path::new(&image_str), args);
+ let mut cmdline_w = to_wide_z(&cmdline);
+ let cwd_w = cwd.map(|c| to_wide_z(&c.to_string_lossy()));
+ let mut si: STARTUPINFOW = unsafe { zeroed() };
+ si.cb = size_of::<STARTUPINFOW>() as DWORD;
+ let mut pi: PROCESS_INFORMATION = unsafe { zeroed() };
+ let flags = CREATE_SUSPENDED | CREATE_UNICODE_ENVIRONMENT;
+ let ok = unsafe {
+ CreateProcessW(
+ ptr::null(),
+ cmdline_w.as_mut_ptr(),
+ ptr::null(),
+ ptr::null(),
+ 0,
+ flags,
+ ptr::null(),
+ cwd_w
+ .as_ref()
+ .map(|v| v.as_ptr())
+ .unwrap_or(ptr::null()),
+ &si,
+ &mut pi,
+ )
+ };
+ if ok == 0 {
+ let err = unsafe { GetLastError() };
+ return Err(format!(
+ "CreateProcessW failed (GetLastError={err:#x}) for {cmdline}"
+ ));
+ }
+ let session_id = format!("ps-{}-{}", pi.dw_process_id, super::now_token());
+ Ok((
+ session_id,
+ pi.h_process,
+ pi.h_thread,
+ pi.dw_process_id,
+ pi.dw_thread_id,
+ image_str,
+ ))
+ }
+
+ pub fn resume_thread(h: HANDLE) -> Result<(), String> {
+ let prev = unsafe { ResumeThread(h) };
+ // ResumeThread returns previous suspend count, or u32::MAX on failure.
+ if prev == DWORD::MAX {
+ let err = unsafe { GetLastError() };
+ return Err(format!("ResumeThread failed (GetLastError={err:#x})"));
+ }
+ Ok(())
}
fn wide_to_string(w: &[u16]) -> String {
@@ -184,7 +343,7 @@ mod win {
pub fn list_processes() -> Result<Vec<ProcessInfo>, String> {
let snap = unsafe { CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) };
if snap == 0 || snap == INVALID_HANDLE_VALUE {
- return Err("CreateToolhelp32Snapshot failed".into());
+ return Err("CreateToolhelp32Snapshot failed".into());
}
let mut out = Vec::new();
let mut pe: PROCESSENTRY32W = unsafe { zeroed() };
@@ -232,10 +391,10 @@ mod win {
let h = unsafe { OpenProcess(access, 0, pid) };
if h == 0 {
return Err(format!(
- "OpenProcess({pid}) failed — access denied, elevated rights, or process exited"
+ "OpenProcess({pid}) failed — access denied, elevated rights, or process exited"
));
}
- let session_id = format!("ps-{pid}-{}", super::now_token());
+ let session_id = format!("ps-{pid}-{}", super::now_token());
Ok((session_id, h))
}
@@ -244,7 +403,7 @@ mod win {
let snap = unsafe { CreateToolhelp32Snapshot(flags, pid) };
if snap == 0 || snap == INVALID_HANDLE_VALUE {
return Err(
- "Module snapshot failed (32-bit tool vs 64-bit process, or access denied)".into(),
+ "Module snapshot failed (32-bit tool vs 64-bit process, or access denied)".into(),
);
}
let mut out = Vec::new();
@@ -295,7 +454,7 @@ mod win {
bytes_read: 0,
hex: String::new(),
bytes: vec![],
- error: Some("ReadProcessMemory failed (access denied or unmapped)".into()),
+ error: Some("ReadProcessMemory failed (access denied or unmapped)".into()),
as_u64: None,
as_f32: None,
};
@@ -321,7 +480,7 @@ mod win {
None
};
let error = if read < size {
- Some(format!("short_read: got {read} of {size}"))
+ Some(format!("short_read: got {read} of {size}"))
} else {
None
};
@@ -374,18 +533,18 @@ mod win {
}
fn protect_str(p: DWORD) -> String {
- format!("{p:#x}")
+ format!("{p:#x}")
}
fn state_str(s: DWORD) -> String {
match s {
- MEM_COMMIT => "commit".into(),
- MEM_RESERVE => "reserve".into(),
- MEM_FREE => "free".into(),
- _ => format!("{s:#x}"),
+ MEM_COMMIT => "commit".into(),
+ MEM_RESERVE => "reserve".into(),
+ MEM_FREE => "free".into(),
+ _ => format!("{s:#x}"),
}
}
fn type_str(t: DWORD) -> String {
- format!("{t:#x}")
+ format!("{t:#x}")
}
pub fn close(h: HANDLE) {
@@ -394,7 +553,7 @@ mod win {
}
}
- // silence unused import warning on ptr
+ // silence unused import warning on ptr
#[allow(dead_code)]
fn _touch() {
let _ = ptr::null::<u8>();
@@ -416,7 +575,7 @@ pub fn process_list() -> Result<Vec<ProcessInfo>, String> {
}
#[cfg(not(windows))]
{
- Err("Live Process Bridge is Windows-only in this MVP".into())
+ Err("Live Process Bridge is Windows-only in this MVP".into())
}
}
@@ -430,6 +589,9 @@ pub fn process_attach(pid: u32) -> Result<ProcessSession, String> {
Attached {
pid,
handle,
+ thread: None,
+ suspended: false,
+ launched_image: None,
},
);
});
@@ -438,7 +600,101 @@ pub fn process_attach(pid: u32) -> Result<ProcessSession, String> {
#[cfg(not(windows))]
{
let _ = pid;
- Err("Live Process Bridge is Windows-only in this MVP".into())
+ Err("Live Process Bridge is Windows-only in this MVP".into())
+ }
+}
+
+/// Launch `image` with CREATE_SUSPENDED, keep a live read session, leave primary thread frozen.
+///
+/// Not a Windows-debug break-at-entry — call [`process_resume`] to let the process run.
+/// Fails if another session is already open (one-session MVP).
+pub fn process_launch(req: &LaunchRequest) -> Result<LaunchResult, String> {
+ #[cfg(windows)]
+ {
+ with_sessions(|m| -> Result<(), String> {
+ if !m.is_empty() {
+ return Err(
+ "detach the current live session before launching a new process".into(),
+ );
+ }
+ Ok(())
+ })?;
+ let (session_id, h_proc, h_thread, pid, tid, image_str) =
+ win::launch(&req.image, req.args.as_deref(), req.cwd.as_deref())?;
+ with_sessions(|m| {
+ m.insert(
+ session_id.clone(),
+ Attached {
+ pid,
+ handle: h_proc,
+ thread: Some(h_thread),
+ suspended: true,
+ launched_image: Some(image_str.clone()),
+ },
+ );
+ });
+ Ok(LaunchResult {
+ session: ProcessSession { session_id, pid },
+ image: image_str,
+ suspended: true,
+ primary_tid: tid,
+ })
+ }
+ #[cfg(not(windows))]
+ {
+ let _ = req;
+ Err("Live Process Bridge is Windows-only in this MVP".into())
+ }
+}
+
+/// Resume the primary thread of a launched (CREATE_SUSPENDED) session.
+pub fn process_resume(session_id: &str) -> Result<(), String> {
+ #[cfg(windows)]
+ {
+ with_sessions(|m| {
+ let a = m
+ .get_mut(session_id)
+ .ok_or_else(|| format!("unknown or stale session: {session_id}"))?;
+ if !a.suspended {
+ return Err("session is not suspended (already running or attach-only)".into());
+ }
+ let h = a
+ .thread
+ .ok_or_else(|| "session has no primary thread handle to resume".to_string())?;
+ win::resume_thread(h)?;
+ a.suspended = false;
+ Ok(())
+ })
+ }
+ #[cfg(not(windows))]
+ {
+ let _ = session_id;
+ Err("Live Process Bridge is Windows-only in this MVP".into())
+ }
+}
+
+/// Whether the session was launched suspended and has not been resumed yet.
+pub fn process_is_suspended(session_id: &str) -> Result<bool, String> {
+ with_sessions(|m| {
+ m.get(session_id)
+ .map(|a| a.suspended)
+ .ok_or_else(|| format!("unknown or stale session: {session_id}"))
+ })
+}
+
+/// Build the Win32 command line used by [`process_launch`] (also for tests).
+pub fn launch_command_line(image: &Path, args: Option<&str>) -> String {
+ #[cfg(windows)]
+ {
+ win::build_command_line(image, args)
+ }
+ #[cfg(not(windows))]
+ {
+ let img = image.display().to_string();
+ match args.map(str::trim).filter(|a| !a.is_empty()) {
+ Some(a) => format!("\"{img}\" {a}"),
+ None => img,
+ }
}
}
@@ -447,17 +703,26 @@ pub fn process_detach(session_id: &str) -> Result<(), String> {
{
with_sessions(|m| {
if let Some(a) = m.remove(session_id) {
+ // Avoid leaving a CREATE_SUSPENDED orphan frozen forever.
+ if a.suspended {
+ if let Some(th) = a.thread {
+ let _ = win::resume_thread(th);
+ }
+ }
+ if let Some(th) = a.thread {
+ win::close(th);
+ }
win::close(a.handle);
Ok(())
} else {
- Err(format!("unknown session: {session_id}"))
+ Err(format!("unknown session: {session_id}"))
}
})
}
#[cfg(not(windows))]
{
let _ = session_id;
- Err("Live Process Bridge is Windows-only in this MVP".into())
+ Err("Live Process Bridge is Windows-only in this MVP".into())
}
}
@@ -467,13 +732,13 @@ fn session_handle(session_id: &str) -> Result<(u32, isize), String> {
with_sessions(|m| {
m.get(session_id)
.map(|a| (a.pid, a.handle))
- .ok_or_else(|| format!("unknown or stale session: {session_id}"))
+ .ok_or_else(|| format!("unknown or stale session: {session_id}"))
})
}
#[cfg(not(windows))]
{
let _ = session_id;
- Err("Live Process Bridge is Windows-only in this MVP".into())
+ Err("Live Process Bridge is Windows-only in this MVP".into())
}
}
@@ -486,7 +751,7 @@ pub fn process_modules(session_id: &str) -> Result<Vec<ModuleInfo>, String> {
#[cfg(not(windows))]
{
let _ = session_id;
- Err("Live Process Bridge is Windows-only in this MVP".into())
+ Err("Live Process Bridge is Windows-only in this MVP".into())
}
}
@@ -499,7 +764,7 @@ pub fn process_read(session_id: &str, va: u64, size: usize) -> Result<ReadResult
#[cfg(not(windows))]
{
let _ = (session_id, va, size);
- Err("Live Process Bridge is Windows-only in this MVP".into())
+ Err("Live Process Bridge is Windows-only in this MVP".into())
}
}
@@ -512,7 +777,7 @@ pub fn process_regions(session_id: &str, max: usize) -> Result<Vec<RegionInfo>,
#[cfg(not(windows))]
{
let _ = (session_id, max);
- Err("Live Process Bridge is Windows-only in this MVP".into())
+ Err("Live Process Bridge is Windows-only in this MVP".into())
}
}
@@ -530,7 +795,7 @@ pub fn process_resolve(
.as_deref()
.map(|p| p.to_ascii_lowercase().ends_with(&module.to_ascii_lowercase()))
.unwrap_or(false))
- .ok_or_else(|| format!("module not found: {module}"))?;
+ .ok_or_else(|| format!("module not found: {module}"))?;
Ok(ResolveLive {
module: m.name.clone(),
rva,
@@ -543,3 +808,36 @@ pub fn process_resolve(
pub fn static_to_live(session_id: &str, module: &str, rva: u64) -> Result<ResolveLive, String> {
process_resolve(session_id, module, rva)
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn launch_command_line_quotes_paths_with_spaces() {
+ let s = launch_command_line(Path::new(r"C:\Program Files\app.exe"), Some("-flag"));
+ assert!(s.starts_with('"'), "{s}");
+ assert!(s.contains("app.exe"), "{s}");
+ assert!(s.ends_with("-flag"), "{s}");
+ }
+
+ #[test]
+ fn launch_command_line_plain_path_no_extra_quotes() {
+ let s = launch_command_line(Path::new(r"C:\tools\app.exe"), None);
+ assert_eq!(s, r"C:\tools\app.exe");
+ }
+
+ #[test]
+ fn launch_fails_when_image_missing() {
+ let err = process_launch(&LaunchRequest {
+ image: PathBuf::from("Z:\\definitely\\missing\\ghidrust_launch_test.exe"),
+ args: None,
+ cwd: None,
+ })
+ .unwrap_err();
+ assert!(
+ err.contains("not found") || err.contains("Windows-only") || err.contains("CreateProcess"),
+ "{err}"
+ );
+ }
+}
diff --git a/crates/ghidrust-core/src/project.rs b/crates/ghidrust-core/src/project.rs
index 635c2c0..0ddb76c 100644
--- a/crates/ghidrust-core/src/project.rs
+++ b/crates/ghidrust-core/src/project.rs
@@ -447,7 +447,7 @@ impl Project {
self.analysis_bin_path(id).is_file() || self.analysis_path(id).is_file()
}
- /// Pure project-tree rows for UI (Ghidra Project Window style: project → files).
+ /// Pure project-tree rows for UI.
pub fn tree_rows(&self) -> ProjectTreeModel {
let active = self.meta.active_id.clone();
let files = self
@@ -685,7 +685,7 @@ mod tests {
.unwrap();
let va = prog.entry.expect("entry va");
- // Apply a Ghidra-style workflow: rename, retype, comment kinds,
+ // Apply a workflow: rename, retype, comment kinds,
// signature commit, user type + apply @ cursor.
prog.edits.set_rename(va, "my_main");
if let Some(f) = prog.function_at_mut(va) {
diff --git a/crates/ghidrust-core/src/xrefs.rs b/crates/ghidrust-core/src/xrefs.rs
index 111313d..769184d 100644
--- a/crates/ghidrust-core/src/xrefs.rs
+++ b/crates/ghidrust-core/src/xrefs.rs
@@ -1,4 +1,4 @@
-//! Program cross-references (Ghidra `Symbol References` provider).
+//! Program cross-references.
//!
//! Sources:
//! 1. `Program::analysis.references` — analyzer-deposited refs
@@ -20,10 +20,10 @@ pub struct XRef {
pub from: u64,
/// Target VA (where the reference points at).
pub to: u64,
- /// Ghidra-analog kind (`call`, `jmp`, `cond_jmp`, `data`, `ptr`, `ptr_table`,
+ /// kind (`call`, `jmp`, `cond_jmp`, `data`, `ptr`, `ptr_table`,
/// `resource`, `xref`, `iat`).
pub kind: &'static str,
- /// Ghidra "From Preview" — mnemonic/operand text where computable.
+ /// "From Preview" — mnemonic/operand text where computable.
pub preview: String,
/// String encoding when this xref targets a string (`ascii`, `utf16le`); omitted otherwise.
#[serde(default, skip_serializing_if = "Option::is_none")]
diff --git a/crates/ghidrust-core/tests/bounds_truncated_fixture.rs b/crates/ghidrust-core/tests/bounds_truncated_fixture.rs
new file mode 100644
index 0000000..2462c2a
--- /dev/null
+++ b/crates/ghidrust-core/tests/bounds_truncated_fixture.rs
@@ -0,0 +1,81 @@
+//! Synthetic truncated-bounds fixture: short stored end vs multi-block body.
+
+use ghidrust_core::{
+ assess_bounds_honesty, create_function, disassemble_range_ex, grow_function, DisasmMode,
+ DisasmStopReason, FunctionInfo, FunctionSeedKind, MemoryBlock, Program,
+};
+
+fn multi_block_prog() -> Program {
+ let mut prog = Program::new("truncated_bounds_lab".into(), "PE32+");
+ let mut code = vec![
+ 0x55, 0x48, 0x89, 0xE5, // push rbp; mov rbp, rsp
+ 0x41, 0x56, // push r14
+ 0x48, 0x83, 0xEC, 0x20, // sub rsp, 0x20
+ ];
+ code.extend(vec![0x90u8; 64]);
+ code.extend_from_slice(&[
+ 0x31, 0xC0, // xor eax,eax
+ 0x48, 0x83, 0xC4, 0x20, // add rsp,0x20
+ 0x41, 0x5E, // pop r14
+ 0x5D, // pop rbp
+ 0xC3, // ret
+ 0xCC, 0xCC,
+ ]);
+ prog.blocks.push(MemoryBlock {
+ name: ".text".into(),
+ va: 0x140001000,
+ size: code.len() as u64,
+ bytes: code,
+ readable: true,
+ writable: false,
+ executable: true,
+ });
+ prog.entry = Some(0x140001000);
+ prog.image_base = 0x140000000;
+ prog
+}
+
+#[test]
+fn linear_returns_more_than_prologue_only_bounded() {
+ let mut prog = multi_block_prog();
+ let entry = 0x140001000;
+ // Prologue-only stored end (~17 bytes through early pushes).
+ let short_end = entry + 0x11;
+ prog.analysis.functions.push(
+ FunctionInfo::new(entry, short_end, "FUN_trunc").with_seed_kind(FunctionSeedKind::Manual),
+ );
+
+ let bounded = disassemble_range_ex(
+ &prog,
+ entry,
+ 80,
+ false,
+ DisasmMode::Bounded,
+ Some(short_end),
+ )
+ .expect("bounded");
+ let linear = disassemble_range_ex(&prog, entry, 80, false, DisasmMode::Linear, None)
+ .expect("linear");
+
+ assert_eq!(bounded.stop_reason, DisasmStopReason::FunctionEnd);
+ assert!(
+ linear.insns.len() > bounded.insns.len() + 5,
+ "linear={} bounded={}",
+ linear.insns.len(),
+ bounded.insns.len()
+ );
+
+ let honesty = assess_bounds_honesty(
+ &prog,
+ Some(entry),
+ Some(short_end),
+ bounded.insns.len(),
+ bounded.stop_reason,
+ );
+ assert!(honesty.bounds_suspect, "expected truncated-bounds warning");
+ assert!(honesty.suggested_end.unwrap() > short_end);
+
+ let healed = create_function(&mut prog, entry, None);
+ assert!(healed.end > short_end);
+ assert_eq!(healed.end, grow_function(&prog, entry, None));
+}
diff --git a/crates/ghidrust-decode/Cargo.toml b/crates/ghidrust-decode/Cargo.toml
index 185393b..465313e 100644
--- a/crates/ghidrust-decode/Cargo.toml
+++ b/crates/ghidrust-decode/Cargo.toml
@@ -3,7 +3,14 @@ name = "ghidrust-decode"
version.workspace = true
edition.workspace = true
license.workspace = true
-description = "Hand-rolled x86-64 instruction decode (length-disasm + mnemonic)"
+description = "Hand-rolled multi-arch instruction decode engine"
+
+[features]
+default = []
+# Diet mode: omit heavy mnemonic/name tables when building for size.
+diet = []
+# x86-reduce mode: compile with a reduced x86 opcode surface.
+x86-reduce = []
[dependencies]
serde = { version = "1", features = ["derive"] }
diff --git a/crates/ghidrust-decode/scripts/gen_mos65xx_table.py b/crates/ghidrust-decode/scripts/gen_mos65xx_table.py
new file mode 100644
index 0000000..12f61b1
--- /dev/null
+++ b/crates/ghidrust-decode/scripts/gen_mos65xx_table.py
@@ -0,0 +1,91 @@
+#!/usr/bin/env python3
+"""Generate mos65xx/table.rs from Capstone inc files (one-time bootstrap)."""
+import re
+import urllib.request
+from pathlib import Path
+
+BASE = "https://raw.githubusercontent.com/capstone-engine/capstone/next/arch/MOS65XX/"
+
+AM_MAP = {
+ "MOS65XX_AM_NONE": "None",
+ "MOS65XX_AM_IMP": "Imp",
+ "MOS65XX_AM_ACC": "Acc",
+ "MOS65XX_AM_IMM": "Imm",
+ "MOS65XX_AM_REL": "Rel",
+ "MOS65XX_AM_ZP": "Zp",
+ "MOS65XX_AM_ZP_X": "ZpX",
+ "MOS65XX_AM_ZP_Y": "ZpY",
+ "MOS65XX_AM_ABS": "Abs",
+ "MOS65XX_AM_ABS_X": "AbsX",
+ "MOS65XX_AM_ABS_Y": "AbsY",
+ "MOS65XX_AM_ZP_IND": "ZpInd",
+ "MOS65XX_AM_ZP_X_IND": "ZpXInd",
+ "MOS65XX_AM_ZP_IND_Y": "ZpIndY",
+ "MOS65XX_AM_ABS_IND": "AbsInd",
+ "MOS65XX_AM_INT": "Int",
+ "MOS65XX_AM_ZP_REL": "ZpRel",
+ "MOS65XX_AM_ABS_X_IND": "AbsXInd",
+ "MOS65XX_AM_ABS_IND_LONG": "AbsIndLong",
+ "MOS65XX_AM_ZP_IND_LONG": "ZpIndLong",
+ "MOS65XX_AM_ZP_IND_LONG_Y": "ZpIndLongY",
+ "MOS65XX_AM_ABS_LONG": "AbsLong",
+ "MOS65XX_AM_ABS_LONG_X": "AbsLongX",
+ "MOS65XX_AM_SR": "Sr",
+ "MOS65XX_AM_SR_IND_Y": "SrIndY",
+ "MOS65XX_AM_BLOCK": "Block",
+}
+
+
+def fetch(name: str) -> str:
+ return urllib.request.urlopen(BASE + name).read().decode()
+
+
+def parse_inc(name: str):
+ rows = []
+ for line in fetch(name).splitlines():
+ m = re.match(
+ r"\{\s*MOS65XX_INS_(\w+)\s*,\s*(MOS65XX_AM_\w+)\s*,\s*(\d+)\s*\}",
+ line.strip().rstrip(","),
+ )
+ if not m:
+ continue
+ ins, am, ob = m.group(1), m.group(2), int(m.group(3))
+ rows.append((ins, AM_MAP[am], ob))
+ assert len(rows) == 256, (name, len(rows))
+ return rows
+
+
+def emit_table(name: str, rows) -> str:
+ lines = [f"pub const {name}: [OpEntry; 256] = ["]
+ for i, (ins, am, ob) in enumerate(rows):
+ if ins == "INVALID":
+ entry = f'OpEntry {{ mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::{am}, operand_bytes: {ob} }}'
+ else:
+ mn = ins.lower()
+ entry = (
+ f'OpEntry {{ mnemonic: "{mn}", insn: InsnId::{ins}, '
+ f"mode: AddrMode::{am}, operand_bytes: {ob} }}"
+ )
+ lines.append(f" {entry}, // 0x{i:02x}")
+ lines.append("];")
+ return "\n".join(lines)
+
+
+def main():
+ out = Path(__file__).resolve().parents[1] / "src" / "arch" / "mos65xx" / "table.rs"
+ out.parent.mkdir(parents=True, exist_ok=True)
+ m6502 = parse_inc("m6502.inc")
+ m65c02 = parse_inc("m65c02.inc")
+ body = """//! Auto-generated 6502 / 65C02 opcode tables (Capstone m6502.inc / m65c02.inc layout).
+
+use super::{AddrMode, InsnId, OpEntry};
+
+"""
+ body += emit_table("TABLE_6502", m6502) + "\n\n"
+ body += emit_table("TABLE_65C02", m65c02) + "\n"
+ out.write_text(body, encoding="utf-8")
+ print(f"wrote {out}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/crates/ghidrust-decode/src/alloc_hooks.rs b/crates/ghidrust-decode/src/alloc_hooks.rs
new file mode 100644
index 0000000..9c2f065
--- /dev/null
+++ b/crates/ghidrust-decode/src/alloc_hooks.rs
@@ -0,0 +1,48 @@
+/// Custom allocation hooks .
+pub trait AllocHooks: Send + Sync {
+ fn malloc(&self, size: usize) -> *mut u8 {
+ let layout = std::alloc::Layout::from_size_align(size, 8).unwrap_or_else(|_| {
+ std::alloc::Layout::from_size_align(1, 1).expect("fallback layout")
+ });
+ unsafe { std::alloc::alloc(layout) }
+ }
+
+ fn calloc(&self, n: usize, size: usize) -> *mut u8 {
+ let total = n.saturating_mul(size);
+ let ptr = self.malloc(total);
+ if !ptr.is_null() && total > 0 {
+ unsafe { std::ptr::write_bytes(ptr, 0, total) };
+ }
+ ptr
+ }
+
+ fn realloc(&self, ptr: *mut u8, size: usize) -> *mut u8 {
+ if ptr.is_null() {
+ return self.malloc(size);
+ }
+ let layout = std::alloc::Layout::from_size_align(size, 8).unwrap_or_else(|_| {
+ std::alloc::Layout::from_size_align(1, 1).expect("fallback layout")
+ });
+ unsafe { std::alloc::realloc(ptr, layout, size) }
+ }
+
+ fn free(&self, ptr: *mut u8) {
+ if ptr.is_null() {
+ return;
+ }
+ let layout = std::alloc::Layout::from_size_align(1, 1).expect("free layout");
+ unsafe { std::alloc::dealloc(ptr, layout) }
+ }
+}
+
+/// Default Rust global allocator hooks.
+#[derive(Debug, Default)]
+pub struct GlobalAllocHooks;
+
+impl AllocHooks for GlobalAllocHooks {}
+
+static GLOBAL_HOOKS: GlobalAllocHooks = GlobalAllocHooks;
+
+pub fn global_hooks() -> &'static dyn AllocHooks {
+ &GLOBAL_HOOKS
+}
diff --git a/crates/ghidrust-decode/src/arch/aarch64/branches.rs b/crates/ghidrust-decode/src/arch/aarch64/branches.rs
new file mode 100644
index 0000000..0966e31
--- /dev/null
+++ b/crates/ghidrust-decode/src/arch/aarch64/branches.rs
@@ -0,0 +1,141 @@
+use super::regs::{w, x};
+use super::util::{bit, fmt_imm_hex, sign_extend};
+use crate::error::Result;
+use crate::insn::Instruction;
+
+pub fn try_decode(wd: u32, address: u64, raw: &[u8]) -> Option<Result<Instruction>> {
+ if (wd & 0xfc000000) == 0x14000000 {
+ return Some(decode_b_imm(wd, address, raw, false));
+ }
+ if (wd & 0xfc000000) == 0x94000000 {
+ return Some(decode_b_imm(wd, address, raw, true));
+ }
+ if (wd & 0xff000010) == 0x54000000 {
+ return Some(decode_b_cond(wd, address, raw));
+ }
+ if (wd & 0x7e000000) == 0x34000000 {
+ return Some(decode_cbz(wd, address, raw, false));
+ }
+ if (wd & 0x7e000000) == 0x35000000 {
+ return Some(decode_cbz(wd, address, raw, true));
+ }
+ if (wd & 0x7e000000) == 0x36000000 {
+ return Some(decode_tbz(wd, address, raw, false));
+ }
+ if (wd & 0x7e000000) == 0x37000000 {
+ return Some(decode_tbz(wd, address, raw, true));
+ }
+ if (wd & 0xfffffc1f) == 0xd61f0000 {
+ return Some(decode_br(wd, address, raw));
+ }
+ if (wd & 0xfffffc1f) == 0xd63f0000 {
+ return Some(decode_blr(wd, address, raw));
+ }
+ if (wd & 0xfffffc1f) == 0xd65f0000 {
+ return Some(decode_ret(wd, address, raw));
+ }
+ None
+}
+
+fn decode_b_imm(wd: u32, address: u64, raw: &[u8], link: bool) -> Result<Instruction> {
+ let imm26 = bit(wd, 0, 25);
+ let offset = sign_extend((imm26 as u64) << 2, 28);
+ let target = (address as i64).wrapping_add(offset) as u64;
+ let mnemonic = if link { "bl" } else { "b" };
+ Ok(Instruction::with_text(
+ address,
+ raw.to_vec(),
+ mnemonic,
+ fmt_imm_hex(target as i64),
+ 4,
+ ))
+}
+
+fn decode_b_cond(wd: u32, address: u64, raw: &[u8]) -> Result<Instruction> {
+ let cond = bit(wd, 0, 3);
+ let imm19 = bit(wd, 5, 23);
+ let offset = sign_extend((imm19 as u64) << 2, 21);
+ let target = (address as i64).wrapping_add(offset) as u64;
+ Ok(Instruction::with_text(
+ address,
+ raw.to_vec(),
+ format!("b.{}", super::util::cond_name(cond)),
+ fmt_imm_hex(target as i64),
+ 4,
+ ))
+}
+
+fn decode_br(wd: u32, address: u64, raw: &[u8]) -> Result<Instruction> {
+ let rn = bit(wd, 5, 9);
+ Ok(Instruction::with_text(
+ address,
+ raw.to_vec(),
+ "br",
+ x(rn),
+ 4,
+ ))
+}
+
+fn decode_blr(wd: u32, address: u64, raw: &[u8]) -> Result<Instruction> {
+ let rn = bit(wd, 5, 9);
+ Ok(Instruction::with_text(
+ address,
+ raw.to_vec(),
+ "blr",
+ x(rn),
+ 4,
+ ))
+}
+
+fn decode_ret(wd: u32, address: u64, raw: &[u8]) -> Result<Instruction> {
+ let rn = bit(wd, 5, 9);
+ let operands = if rn == 30 {
+ "lr".into()
+ } else if rn == 31 {
+ String::new()
+ } else {
+ x(rn)
+ };
+ Ok(Instruction::with_text(
+ address,
+ raw.to_vec(),
+ "ret",
+ operands,
+ 4,
+ ))
+}
+
+fn decode_cbz(wd: u32, address: u64, raw: &[u8], neg: bool) -> Result<Instruction> {
+ let sf = bit(wd, 31, 31);
+ let imm19 = bit(wd, 5, 23);
+ let rt = bit(wd, 0, 4);
+ let offset = sign_extend((imm19 as u64) << 2, 21);
+ let target = (address as i64).wrapping_add(offset) as u64;
+ let reg = if sf != 0 { x(rt) } else { w(rt) };
+ let mnemonic = if neg { "cbnz" } else { "cbz" };
+ Ok(Instruction::with_text(
+ address,
+ raw.to_vec(),
+ mnemonic,
+ format!("{}, {}", reg, fmt_imm_hex(target as i64)),
+ 4,
+ ))
+}
+
+fn decode_tbz(wd: u32, address: u64, raw: &[u8], neg: bool) -> Result<Instruction> {
+ let b5 = bit(wd, 31, 31);
+ let b40 = bit(wd, 19, 23);
+ let imm14 = bit(wd, 5, 18);
+ let rt = bit(wd, 0, 4);
+ let bit_pos = b40 | (b5 << 5);
+ let offset = sign_extend((imm14 as u64) << 2, 16);
+ let target = (address as i64).wrapping_add(offset) as u64;
+ let mnemonic = if neg { "tbnz" } else { "tbz" };
+ Ok(Instruction::with_text(
+ address,
+ raw.to_vec(),
+ mnemonic,
+ format!("{}, #{bit_pos}, {}", w(rt), fmt_imm_hex(target as i64)),
+ 4,
+ ))
+}
diff --git a/crates/ghidrust-decode/src/arch/aarch64/data_proc.rs b/crates/ghidrust-decode/src/arch/aarch64/data_proc.rs
new file mode 100644
index 0000000..2193515
--- /dev/null
+++ b/crates/ghidrust-decode/src/arch/aarch64/data_proc.rs
@@ -0,0 +1,135 @@
+use super::regs::{w, x};
+use super::util::bit;
+use crate::error::Result;
+use crate::insn::Instruction;
+
+pub fn try_decode(wd: u32, address: u64, raw: &[u8]) -> Option<Result<Instruction>> {
+ if (wd & 0x1f200000) == 0x0b000000 {
+ return Some(decode_add_sub_reg(wd, address, raw));
+ }
+ if (wd & 0x1f000000) == 0x11000000 {
+ return Some(decode_add_sub_imm(wd, address, raw));
+ }
+ if (wd & 0x1f200000) == 0x0a000000 {
+ return Some(decode_logical_reg(wd, address, raw));
+ }
+ if (wd & 0x1f200000) == 0x12000000 {
+ return Some(decode_logical_imm(wd, address, raw));
+ }
+ None
+}
+
+fn decode_add_sub_imm(wd: u32, address: u64, raw: &[u8]) -> Result<Instruction> {
+ let sf = bit(wd, 31, 31);
+ let op = bit(wd, 30, 30);
+ let s = bit(wd, 29, 29);
+ let sh = bit(wd, 22, 23);
+ let imm12 = bit(wd, 10, 21);
+ let rn = bit(wd, 5, 9);
+ let rd = bit(wd, 0, 4);
+ let shift = if sh == 0b01 { 12 } else { 0 };
+ let imm = (imm12 as u64) << shift;
+ let reg_d = if sf != 0 { x(rd) } else { w(rd) };
+ let reg_n = if rn == 31 {
+ "sp".into()
+ } else if sf != 0 {
+ x(rn)
+ } else {
+ w(rn)
+ };
+ let mnemonic = match (op, s, rn == 31) {
+ (0, 0, true) => "mov",
+ (0, 0, false) => "add",
+ (0, 1, _) => "adds",
+ (1, 0, _) => "sub",
+ (1, 1, _) => "subs",
+ _ => "add",
+ };
+ let operands = if mnemonic == "mov" {
+ format!("{}, #{imm:#x}", reg_d)
+ } else {
+ format!("{}, {}, #{imm:#x}", reg_d, reg_n)
+ };
+ Ok(Instruction::with_text(address, raw.to_vec(), mnemonic, operands, 4))
+}
+
+fn decode_logical_imm(wd: u32, address: u64, raw: &[u8]) -> Result<Instruction> {
+ let sf = bit(wd, 31, 31);
+ let opc = bit(wd, 29, 30);
+ let rn = bit(wd, 5, 9);
+ let rd = bit(wd, 0, 4);
+ let imm = wd & 0xffff;
+ let reg_d = if sf != 0 { x(rd) } else { w(rd) };
+ let reg_n = if sf != 0 { x(rn) } else { w(rn) };
+ let mnemonic = match opc {
+ 0b00 => "and",
+ 0b01 => "orr",
+ 0b10 => "eor",
+ 0b11 => "ands",
+ _ => "and",
+ };
+ let operands = if rn == 31 && opc == 0b01 {
+ format!("{}, #{imm:#x}", reg_d)
+ } else {
+ format!("{}, {}, #{imm:#x}", reg_d, reg_n)
+ };
+ Ok(Instruction::with_text(address, raw.to_vec(), mnemonic, operands, 4))
+}
+
+fn decode_logical_reg(wd: u32, address: u64, raw: &[u8]) -> Result<Instruction> {
+ let sf = bit(wd, 31, 31);
+ let opc = bit(wd, 29, 30);
+ let shift = bit(wd, 22, 23);
+ let rm = bit(wd, 16, 20);
+ let imm6 = bit(wd, 10, 15);
+ let rn = bit(wd, 5, 9);
+ let rd = bit(wd, 0, 4);
+ let reg_d = if sf != 0 { x(rd) } else { w(rd) };
+ let reg_n = if sf != 0 { x(rn) } else { w(rn) };
+ let reg_m = if sf != 0 { x(rm) } else { w(rm) };
+ let shift_kind = match shift {
+ 0b00 => "lsl",
+ 0b01 => "lsr",
+ 0b10 => "asr",
+ _ => "ror",
+ };
+ let mnemonic = match opc {
+ 0b00 => "and",
+ 0b01 => "orr",
+ 0b10 => "eor",
+ 0b11 => "ands",
+ _ => "and",
+ };
+ Ok(Instruction::with_text(
+ address,
+ raw.to_vec(),
+ mnemonic,
+ format!("{}, {}, {}, {shift_kind} #{imm6}", reg_d, reg_n, reg_m),
+ 4,
+ ))
+}
+
+fn decode_add_sub_reg(wd: u32, address: u64, raw: &[u8]) -> Result<Instruction> {
+ let sf = bit(wd, 31, 31);
+ let op = bit(wd, 30, 30);
+ let rm = bit(wd, 16, 20);
+ let rn = bit(wd, 5, 9);
+ let rd = bit(wd, 0, 4);
+ let reg_d = if sf != 0 { x(rd) } else { w(rd) };
+ let reg_n = if rn == 31 {
+ "sp".into()
+ } else if sf != 0 {
+ x(rn)
+ } else {
+ w(rn)
+ };
+ let reg_m = if sf != 0 { x(rm) } else { w(rm) };
+ let mnemonic = if op != 0 { "sub" } else { "add" };
+ Ok(Instruction::with_text(
+ address,
+ raw.to_vec(),
+ mnemonic,
+ format!("{}, {}, {}", reg_d, reg_n, reg_m),
+ 4,
+ ))
+}
diff --git a/crates/ghidrust-decode/src/arch/aarch64/dispatch.rs b/crates/ghidrust-decode/src/arch/aarch64/dispatch.rs
new file mode 100644
index 0000000..c0b080b
--- /dev/null
+++ b/crates/ghidrust-decode/src/arch/aarch64/dispatch.rs
@@ -0,0 +1,39 @@
+use super::branches;
+use super::data_proc;
+use super::fp_asimd;
+use super::load_store;
+use super::move_wide;
+use super::system;
+use super::util;
+use crate::error::{Error, Result};
+use crate::insn::Instruction;
+
+pub fn decode(bytes: &[u8], address: u64, big_endian: bool) -> Result<Instruction> {
+ if bytes.len() < 4 {
+ return Err(Error::Decode("truncated AArch64 instruction".into()));
+ }
+ let wd = util::read_u32_le(bytes, big_endian)?;
+ let raw = &bytes[..4];
+ if let Some(r) = system::try_decode(wd, address, raw) {
+ return r;
+ }
+ if let Some(r) = branches::try_decode(wd, address, raw) {
+ return r;
+ }
+ if let Some(r) = move_wide::try_decode_adr(wd, address, raw) {
+ return r;
+ }
+ if let Some(r) = move_wide::try_decode(wd, address, raw) {
+ return r;
+ }
+ if let Some(r) = data_proc::try_decode(wd, address, raw) {
+ return r;
+ }
+ if let Some(r) = load_store::try_decode(wd, address, raw) {
+ return r;
+ }
+ if let Some(r) = fp_asimd::try_decode(wd, address, raw) {
+ return r;
+ }
+ Err(Error::Decode(format!("unhandled AArch64 encoding {wd:#010x}")))
+}
diff --git a/crates/ghidrust-decode/src/arch/aarch64/fp_asimd.rs b/crates/ghidrust-decode/src/arch/aarch64/fp_asimd.rs
new file mode 100644
index 0000000..a0888dc
--- /dev/null
+++ b/crates/ghidrust-decode/src/arch/aarch64/fp_asimd.rs
@@ -0,0 +1,136 @@
+use super::regs::{d, s, v};
+use super::util::bit;
+use crate::error::Result;
+use crate::insn::Instruction;
+
+pub fn try_decode(wd: u32, address: u64, raw: &[u8]) -> Option<Result<Instruction>> {
+ let op0 = bit(wd, 28, 31);
+ if op0 != 0b0001 && op0 != 0b0011 {
+ return None;
+ }
+ let op1 = bit(wd, 23, 27);
+ if op1 != 0b01110 && op1 != 0b01111 {
+ return None;
+ }
+ let op2 = bit(wd, 10, 15);
+ match op2 {
+ 0b000000 => Some(decode_fadd(wd, address, raw)),
+ 0b000010 => Some(decode_fmul(wd, address, raw)),
+ 0b000100 => Some(decode_fsub(wd, address, raw)),
+ 0b001000 => Some(decode_fdiv(wd, address, raw)),
+ 0b010000 => Some(decode_fmov(wd, address, raw)),
+ _ => try_asimd(wd, address, raw),
+ }
+}
+
+fn decode_fadd(wd: u32, address: u64, raw: &[u8]) -> Result<Instruction> {
+ let rd = bit(wd, 0, 4);
+ let rn = bit(wd, 5, 9);
+ let rm = bit(wd, 16, 20);
+ let sz = bit(wd, 22, 22);
+ let mnemonic = if sz != 0 { "fadd" } else { "fadd" };
+ let suffix = if sz != 0 { ".d" } else { ".s" };
+ let reg = if sz != 0 { d(rd) } else { s(rd) };
+ let reg_n = if sz != 0 { d(rn) } else { s(rn) };
+ let reg_m = if sz != 0 { d(rm) } else { s(rm) };
+ Ok(Instruction::with_text(
+ address,
+ raw.to_vec(),
+ format!("{mnemonic}{suffix}"),
+ format!("{}, {}, {}", reg, reg_n, reg_m),
+ 4,
+ ))
+}
+
+fn decode_fmul(wd: u32, address: u64, raw: &[u8]) -> Result<Instruction> {
+ let rd = bit(wd, 0, 4);
+ let rn = bit(wd, 5, 9);
+ let rm = bit(wd, 16, 20);
+ let sz = bit(wd, 22, 22);
+ let suffix = if sz != 0 { ".d" } else { ".s" };
+ let reg = if sz != 0 { d(rd) } else { s(rd) };
+ let reg_n = if sz != 0 { d(rn) } else { s(rn) };
+ let reg_m = if sz != 0 { d(rm) } else { s(rm) };
+ Ok(Instruction::with_text(
+ address,
+ raw.to_vec(),
+ format!("fmul{suffix}"),
+ format!("{}, {}, {}", reg, reg_n, reg_m),
+ 4,
+ ))
+}
+
+fn decode_fsub(wd: u32, address: u64, raw: &[u8]) -> Result<Instruction> {
+ let rd = bit(wd, 0, 4);
+ let rn = bit(wd, 5, 9);
+ let rm = bit(wd, 16, 20);
+ let sz = bit(wd, 22, 22);
+ let suffix = if sz != 0 { ".d" } else { ".s" };
+ let reg = if sz != 0 { d(rd) } else { s(rd) };
+ let reg_n = if sz != 0 { d(rn) } else { s(rn) };
+ let reg_m = if sz != 0 { d(rm) } else { s(rm) };
+ Ok(Instruction::with_text(
+ address,
+ raw.to_vec(),
+ format!("fsub{suffix}"),
+ format!("{}, {}, {}", reg, reg_n, reg_m),
+ 4,
+ ))
+}
+
+fn decode_fdiv(wd: u32, address: u64, raw: &[u8]) -> Result<Instruction> {
+ let rd = bit(wd, 0, 4);
+ let rn = bit(wd, 5, 9);
+ let rm = bit(wd, 16, 20);
+ let sz = bit(wd, 22, 22);
+ let suffix = if sz != 0 { ".d" } else { ".s" };
+ let reg = if sz != 0 { d(rd) } else { s(rd) };
+ let reg_n = if sz != 0 { d(rn) } else { s(rn) };
+ let reg_m = if sz != 0 { d(rm) } else { s(rm) };
+ Ok(Instruction::with_text(
+ address,
+ raw.to_vec(),
+ format!("fdiv{suffix}"),
+ format!("{}, {}, {}", reg, reg_n, reg_m),
+ 4,
+ ))
+}
+
+fn decode_fmov(wd: u32, address: u64, raw: &[u8]) -> Result<Instruction> {
+ let rd = bit(wd, 0, 4);
+ let rn = bit(wd, 5, 9);
+ let sz = bit(wd, 22, 22);
+ let reg = if sz != 0 { d(rd) } else { s(rd) };
+ let reg_n = if sz != 0 { d(rn) } else { s(rn) };
+ Ok(Instruction::with_text(
+ address,
+ raw.to_vec(),
+ if sz != 0 { "fmov.d" } else { "fmov.s" },
+ format!("{}, {}", reg, reg_n),
+ 4,
+ ))
+}
+
+fn try_asimd(wd: u32, address: u64, raw: &[u8]) -> Option<Result<Instruction>> {
+ let q = bit(wd, 30, 30);
+ let rd = bit(wd, 0, 4);
+ let rn = bit(wd, 5, 9);
+ let rm = bit(wd, 16, 20);
+ let size = bit(wd, 22, 23);
+ if bit(wd, 28, 31) != 0b0011 {
+ return None;
+ }
+ let mnemonic = match size {
+ 0b00 => "add.8b",
+ 0b01 => "add.16b",
+ 0b10 => "add.4h",
+ _ => "add.2s",
+ };
+ Some(Ok(Instruction::with_text(
+ address,
+ raw.to_vec(),
+ mnemonic,
+ format!("{}, {}, {}", v(rd | if q != 0 { 16 } else { 0 }), v(rn), v(rm)),
+ 4,
+ )))
+}
diff --git a/crates/ghidrust-decode/src/arch/aarch64/load_store.rs b/crates/ghidrust-decode/src/arch/aarch64/load_store.rs
new file mode 100644
index 0000000..2415b40
--- /dev/null
+++ b/crates/ghidrust-decode/src/arch/aarch64/load_store.rs
@@ -0,0 +1,106 @@
+use super::regs::{w, x};
+use super::util::bit;
+use crate::error::Result;
+use crate::insn::Instruction;
+
+pub fn try_decode(wd: u32, address: u64, raw: &[u8]) -> Option<Result<Instruction>> {
+ let op0 = bit(wd, 25, 28);
+ if op0 != 0b0100 && op0 != 0b1100 && op0 != 0b0101 && op0 != 0b1101 {
+ return None;
+ }
+ let op1 = bit(wd, 26, 26);
+ if op1 != 0 {
+ return try_load_store(wd, address, raw);
+ }
+ // Load/store pair / exclusive use different routing
+ try_load_store(wd, address, raw)
+}
+
+fn try_load_store(wd: u32, address: u64, raw: &[u8]) -> Option<Result<Instruction>> {
+ let op0 = bit(wd, 22, 23);
+ let _op2 = bit(wd, 10, 11);
+ // Load/store pair
+ if bit(wd, 26, 26) == 0 && bit(wd, 25, 25) == 1 && op0 == 0b10 {
+ return Some(decode_pair(wd, address, raw));
+ }
+ // Literal load: opc=01, V=0, at bits 29-31 = 0b011
+ if bit(wd, 24, 28) == 0b01100 && bit(wd, 26, 26) == 0 {
+ return Some(decode_literal(wd, address, raw));
+ }
+ Some(decode_reg_offset(wd, address, raw))
+}
+
+fn decode_literal(wd: u32, address: u64, raw: &[u8]) -> Result<Instruction> {
+ let sf = bit(wd, 30, 30);
+ let imm19 = bit(wd, 5, 23);
+ let rt = bit(wd, 0, 4);
+ let offset = sign_extend((imm19 as i64) << 2, 21);
+ let target = (address as i64).wrapping_add(offset) as u64;
+ let reg = if sf != 0 { x(rt) } else { w(rt) };
+ Ok(Instruction::with_text(
+ address,
+ raw.to_vec(),
+ "ldr",
+ format!("{}, #{target:#x}", reg),
+ 4,
+ ))
+}
+
+fn decode_reg_offset(wd: u32, address: u64, raw: &[u8]) -> Result<Instruction> {
+ let size = bit(wd, 30, 31);
+ let opc = bit(wd, 22, 23);
+ let rn = bit(wd, 5, 9);
+ let rt = bit(wd, 0, 4);
+ let imm12 = bit(wd, 10, 21);
+ let is_load = opc == 0b01 || (opc == 0b00 && size == 0b11);
+ let (mnemonic, reg) = match (size, opc, is_load) {
+ (0b00, 0b00, true) => ("ldrb", w(rt)),
+ (0b00, 0b00, false) => ("strb", w(rt)),
+ (0b01, 0b00, true) => ("ldrh", w(rt)),
+ (0b01, 0b00, false) => ("strh", w(rt)),
+ (0b10, _, true) => ("ldr", w(rt)),
+ (0b10, _, false) => ("str", w(rt)),
+ (0b11, 0b00, true) => ("ldr", x(rt)),
+ (0b11, 0b00, false) => ("str", x(rt)),
+ (0b11, 0b01, true) => ("ldrsw", x(rt)),
+ _ => if is_load {
+ ("ldr", if size == 0b11 { x(rt) } else { w(rt) })
+ } else {
+ ("str", if size == 0b11 { x(rt) } else { w(rt) })
+ },
+ };
+ let base = if rn == 31 { "sp" } else { &x(rn) };
+ Ok(Instruction::with_text(
+ address,
+ raw.to_vec(),
+ mnemonic,
+ format!("{}, [{}, #{imm12}]", reg, base),
+ 4,
+ ))
+}
+
+fn decode_pair(wd: u32, address: u64, raw: &[u8]) -> Result<Instruction> {
+ let opc = bit(wd, 30, 31);
+ let l = bit(wd, 22, 22);
+ let imm7 = bit(wd, 15, 21);
+ let rn = bit(wd, 5, 9);
+ let rt = bit(wd, 0, 4);
+ let rt2 = bit(wd, 10, 14);
+ let offset = (imm7 as i64) << opc;
+ let mnemonic = if l != 0 { "ldp" } else { "stp" };
+ let reg1 = if opc == 0b10 { w(rt) } else { x(rt) };
+ let reg2 = if opc == 0b10 { w(rt2) } else { x(rt2) };
+ let base = if rn == 31 { "sp".into() } else { x(rn) };
+ Ok(Instruction::with_text(
+ address,
+ raw.to_vec(),
+ mnemonic,
+ format!("{}, {}, [{}, #{offset}]", reg1, reg2, base),
+ 4,
+ ))
+}
+
+fn sign_extend(value: i64, bits: u32) -> i64 {
+ let shift = 64 - bits;
+ (value << shift) >> shift
+}
diff --git a/crates/ghidrust-decode/src/arch/aarch64/mod.rs b/crates/ghidrust-decode/src/arch/aarch64/mod.rs
new file mode 100644
index 0000000..f3f766e
--- /dev/null
+++ b/crates/ghidrust-decode/src/arch/aarch64/mod.rs
@@ -0,0 +1,156 @@
+mod branches;
+mod data_proc;
+mod dispatch;
+mod fp_asimd;
+mod load_store;
+mod move_wide;
+mod regs;
+mod system;
+mod util;
+
+use crate::arch::ArchDecode;
+use crate::error::{Error, Result};
+use crate::group::GroupId;
+use crate::insn::{InsnDetail, InsnId, Instruction};
+use crate::names;
+use crate::option::EngineOptions;
+use crate::reg::RegId;
+use crate::support::{Arch, Mode};
+
+pub struct Aarch64Decoder {
+ big_endian: bool,
+}
+
+impl ArchDecode for Aarch64Decoder {
+ fn arch(&self) -> Arch {
+ Arch::Arm64
+ }
+
+ fn open(mode: Mode) -> Result<Self> {
+ if !mode.is_valid_for(Arch::Arm64) {
+ return Err(Error::Mode(format!(
+ "invalid AArch64 mode {:#x}",
+ mode.bits()
+ )));
+ }
+ let big_endian = mode.contains(Mode::BIG_ENDIAN);
+ Ok(Self { big_endian })
+ }
+
+ fn decode_one(&self, bytes: &[u8], address: u64, opts: &EngineOptions) -> Result<Instruction> {
+ let mut insn = dispatch::decode(bytes, address, self.big_endian)?;
+ insn.id = names::insn_id_for_mnemonic(Arch::Arm64, &insn.mnemonic);
+ if let Some(over) = opts.mnemonic_overrides.get(&insn.id.raw()) {
+ insn.mnemonic = over.clone();
+ }
+ if opts.detail {
+ insn.detail = Some(InsnDetail {
+ groups: groups_for_mnemonic(&insn.mnemonic),
+ ..InsnDetail::default()
+ });
+ }
+ Ok(insn)
+ }
+}
+
+fn groups_for_mnemonic(mnemonic: &str) -> Vec<GroupId> {
+ let m = mnemonic.split('.').next().unwrap_or(mnemonic);
+ if m == "b" || m.starts_with("b.") || m == "cbz" || m == "cbnz" || m == "tbz" || m == "tbnz" {
+ vec![GroupId::Jump, GroupId::BranchRelative]
+ } else if m == "bl" || m == "blr" {
+ vec![GroupId::Call, GroupId::BranchRelative]
+ } else if m == "ret" || m == "br" {
+ vec![GroupId::Ret]
+ } else if m == "svc" || m == "brk" {
+ vec![GroupId::Int]
+ } else {
+ Vec::new()
+ }
+}
+
+pub fn reg_name(reg: RegId) -> Option<&'static str> {
+ match reg.index() {
+ 31 => Some("xzr"),
+ n if n < 31 => None,
+ _ => None,
+ }
+}
+
+pub fn insn_name(id: InsnId) -> Option<&'static str> {
+ match id.raw() {
+ 1 => Some("mov"),
+ 2 => Some("add"),
+ 3 => Some("ldr"),
+ 4 => Some("str"),
+ 5 => Some("b"),
+ 6 => Some("bl"),
+ 7 => Some("ret"),
+ 8 => Some("nop"),
+ 9 => Some("svc"),
+ _ => None,
+ }
+}
+
+pub fn group_name(group: GroupId) -> Option<&'static str> {
+ match group {
+ GroupId::Jump => Some("jump"),
+ GroupId::Call => Some("call"),
+ GroupId::Ret => Some("ret"),
+ GroupId::Int => Some("int"),
+ GroupId::BranchRelative => Some("branch_relative"),
+ _ => None,
+ }
+}
+
+pub fn insn_id_for_mnemonic(mnemonic: &str) -> InsnId {
+ let m = mnemonic.split('.').next().unwrap_or(mnemonic);
+ let id = match m {
+ "mov" | "movz" | "movk" | "movn" => 1,
+ "add" | "sub" | "adds" | "subs" => 2,
+ s if s.starts_with("ldr") => 3,
+ s if s.starts_with("str") || s.starts_with("stp") => 4,
+ "b" | "cbz" | "cbnz" => 5,
+ "bl" | "blr" => 6,
+ "ret" | "br" => 7,
+ "nop" => 8,
+ "svc" | "brk" => 9,
+ _ => 0,
+ };
+ InsnId(id)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::engine::Engine;
+
+ #[test]
+ fn aarch64_mov_add_ret() {
+ let mut eng = Engine::open(Arch::Arm64, Mode::LITTLE_ENDIAN).unwrap();
+ // movz x0, #0x1234 -> d2802468
+ let mov = eng.disasm_one(&[0x68, 0x24, 0x80, 0xd2], 0x1000).unwrap();
+ assert_eq!(mov.mnemonic, "movz");
+ // add x1, x0, x2 -> 8b020001
+ let add = eng.disasm_one(&[0x01, 0x00, 0x02, 0x8b], 0x1004).unwrap();
+ assert_eq!(add.mnemonic, "add");
+ // ret -> d65f03c0
+ let ret = eng.disasm_one(&[0xc0, 0x03, 0x5f, 0xd6], 0x1008).unwrap();
+ assert_eq!(ret.mnemonic, "ret");
+ }
+
+ #[test]
+ fn aarch64_nop_svc() {
+ let mut eng = Engine::open(Arch::Arm64, Mode::LITTLE_ENDIAN).unwrap();
+ let nop = eng.disasm_one(&[0x1f, 0x20, 0x03, 0xd5], 0x0).unwrap();
+ assert_eq!(nop.mnemonic, "nop");
+ }
+
+ #[test]
+ fn aarch64_bl_b() {
+ let mut eng = Engine::open(Arch::Arm64, Mode::LITTLE_ENDIAN).unwrap();
+ let b = eng.disasm_one(&[0x00, 0x00, 0x00, 0x14], 0x0).unwrap();
+ assert_eq!(b.mnemonic, "b");
+ let bl = eng.disasm_one(&[0x00, 0x00, 0x00, 0x94], 0x0).unwrap();
+ assert_eq!(bl.mnemonic, "bl");
+ }
+}
diff --git a/crates/ghidrust-decode/src/arch/aarch64/move_wide.rs b/crates/ghidrust-decode/src/arch/aarch64/move_wide.rs
new file mode 100644
index 0000000..1e2fec8
--- /dev/null
+++ b/crates/ghidrust-decode/src/arch/aarch64/move_wide.rs
@@ -0,0 +1,94 @@
+use super::regs::{w, x};
+use super::util::bit;
+use crate::error::Result;
+use crate::insn::Instruction;
+
+pub fn try_decode(wd: u32, address: u64, raw: &[u8]) -> Option<Result<Instruction>> {
+ if (wd & 0x1f80_0000) == 0x1280_0000 {
+ return Some(decode_movz(wd, address, raw));
+ }
+ if (wd & 0x1f80_0000) == 0x7280_0000 {
+ return Some(decode_movk(wd, address, raw));
+ }
+ if (wd & 0x1f80_0000) == 0x3280_0000 {
+ return Some(decode_movn(wd, address, raw));
+ }
+ None
+}
+
+fn decode_movz(wd: u32, address: u64, raw: &[u8]) -> Result<Instruction> {
+ let sf = bit(wd, 31, 31);
+ let hw = bit(wd, 21, 22);
+ let imm16 = bit(wd, 5, 20);
+ let rd = bit(wd, 0, 4);
+ let shift = hw * 16;
+ let imm = (imm16 as u64) << shift;
+ let reg = if sf != 0 { x(rd) } else { w(rd) };
+ Ok(Instruction::with_text(
+ address,
+ raw.to_vec(),
+ "movz",
+ format!("{}, #{imm:#x}", reg),
+ 4,
+ ))
+}
+
+fn decode_movk(wd: u32, address: u64, raw: &[u8]) -> Result<Instruction> {
+ let sf = bit(wd, 31, 31);
+ let hw = bit(wd, 21, 22);
+ let imm16 = bit(wd, 5, 20);
+ let rd = bit(wd, 0, 4);
+ let shift = hw * 16;
+ let imm = (imm16 as u64) << shift;
+ let reg = if sf != 0 { x(rd) } else { w(rd) };
+ Ok(Instruction::with_text(
+ address,
+ raw.to_vec(),
+ "movk",
+ format!("{}, #{imm:#x}", reg),
+ 4,
+ ))
+}
+
+fn decode_movn(wd: u32, address: u64, raw: &[u8]) -> Result<Instruction> {
+ let sf = bit(wd, 31, 31);
+ let hw = bit(wd, 21, 22);
+ let imm16 = bit(wd, 5, 20);
+ let rd = bit(wd, 0, 4);
+ let shift = hw * 16;
+ let imm = !((imm16 as u64) << shift);
+ let reg = if sf != 0 { x(rd) } else { w(rd) };
+ Ok(Instruction::with_text(
+ address,
+ raw.to_vec(),
+ "movn",
+ format!("{}, #{imm:#x}", reg),
+ 4,
+ ))
+}
+
+pub fn try_decode_adr(wd: u32, address: u64, raw: &[u8]) -> Option<Result<Instruction>> {
+ if (wd & 0x9f00_0000) == 0x1000_0000 {
+ let op = bit(wd, 31, 31);
+ let immlo = bit(wd, 29, 30);
+ let immhi = bit(wd, 5, 23);
+ let rd = bit(wd, 0, 4);
+ let imm = sign_extend_pc((immhi as u64) << 2 | immlo as u64, 21);
+ let target = (address as i64).wrapping_add(imm) as u64;
+ let reg = if bit(wd, 31, 31) != 0 { x(rd) } else { w(rd) };
+ let m = if op != 0 { "adrp" } else { "adr" };
+ return Some(Ok(Instruction::with_text(
+ address,
+ raw.to_vec(),
+ m,
+ format!("{}, #{target:#x}", reg),
+ 4,
+ )));
+ }
+ None
+}
+
+fn sign_extend_pc(value: u64, bits: u32) -> i64 {
+ let shift = 64 - bits;
+ ((value << shift) as i64) >> shift
+}
diff --git a/crates/ghidrust-decode/src/arch/aarch64/regs.rs b/crates/ghidrust-decode/src/arch/aarch64/regs.rs
new file mode 100644
index 0000000..107a6a2
--- /dev/null
+++ b/crates/ghidrust-decode/src/arch/aarch64/regs.rs
@@ -0,0 +1,46 @@
+use crate::reg::RegId;
+use crate::support::Arch;
+
+pub fn x(n: u32) -> String {
+ if n == 31 {
+ "xzr".into()
+ } else {
+ format!("x{n}")
+ }
+}
+
+pub fn w(n: u32) -> String {
+ if n == 31 {
+ "wzr".into()
+ } else {
+ format!("w{n}")
+ }
+}
+
+pub fn sp() -> &'static str {
+ "sp"
+}
+
+pub fn b(n: u32) -> String {
+ format!("b{n}")
+}
+
+pub fn h(n: u32) -> String {
+ format!("h{n}")
+}
+
+pub fn s(n: u32) -> String {
+ format!("s{n}")
+}
+
+pub fn d(n: u32) -> String {
+ format!("d{n}")
+}
+
+pub fn v(n: u32) -> String {
+ format!("v{n}")
+}
+
+pub fn reg_id(n: u32) -> RegId {
+ RegId::tagged(Arch::Arm64, n as u16)
+}
diff --git a/crates/ghidrust-decode/src/arch/aarch64/system.rs b/crates/ghidrust-decode/src/arch/aarch64/system.rs
new file mode 100644
index 0000000..761fb6e
--- /dev/null
+++ b/crates/ghidrust-decode/src/arch/aarch64/system.rs
@@ -0,0 +1,45 @@
+use super::util::bit;
+use crate::error::Result;
+use crate::insn::Instruction;
+
+pub fn try_decode(wd: u32, address: u64, raw: &[u8]) -> Option<Result<Instruction>> {
+ if wd == 0xd503_201f {
+ return Some(Ok(Instruction::with_text(
+ address,
+ raw.to_vec(),
+ "nop",
+ "",
+ 4,
+ )));
+ }
+ if (wd & 0xffe0_0000) == 0xd400_0000 {
+ let imm = bit(wd, 5, 20);
+ return Some(Ok(Instruction::with_text(
+ address,
+ raw.to_vec(),
+ "svc",
+ format!("#{imm}"),
+ 4,
+ )));
+ }
+ if (wd & 0xffe0_0000) == 0xd420_0000 {
+ let imm = bit(wd, 5, 20);
+ return Some(Ok(Instruction::with_text(
+ address,
+ raw.to_vec(),
+ "brk",
+ format!("#{imm}"),
+ 4,
+ )));
+ }
+ if (wd & 0xffff_fff0) == 0xd503_2010 {
+ return Some(Ok(Instruction::with_text(
+ address,
+ raw.to_vec(),
+ "yield",
+ "",
+ 4,
+ )));
+ }
+ None
+}
diff --git a/crates/ghidrust-decode/src/arch/aarch64/util.rs b/crates/ghidrust-decode/src/arch/aarch64/util.rs
new file mode 100644
index 0000000..3ae7f6e
--- /dev/null
+++ b/crates/ghidrust-decode/src/arch/aarch64/util.rs
@@ -0,0 +1,59 @@
+use crate::error::{Error, Result};
+
+pub fn read_u32_le(bytes: &[u8], big_endian: bool) -> Result<u32> {
+ if bytes.len() < 4 {
+ return Err(Error::Decode("truncated AArch64 word".into()));
+ }
+ Ok(if big_endian {
+ u32::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])
+ } else {
+ u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])
+ })
+}
+
+pub fn sign_extend(value: u64, bits: u32) -> i64 {
+ let shift = 64 - bits;
+ ((value << shift) as i64) >> shift
+}
+
+pub fn fmt_imm_hex(v: i64) -> String {
+ if v < 0 {
+ format!("-{:#x}", -v)
+ } else {
+ format!("{v:#x}")
+ }
+}
+
+pub fn bit(w: u32, lo: u32, hi: u32) -> u32 {
+ (w >> lo) & ((1u32 << (hi - lo + 1)) - 1)
+}
+
+pub fn decode_imm_logical(w: u32) -> u32 {
+ let n = (w >> 22) & 1;
+ let immr = (w >> 16) & 0x3f;
+ let imms = (w >> 10) & 0x3f;
+ let size = if n != 0 { 64 } else { 32 };
+ let _ = (immr, imms, size);
+ w & 0xffff
+}
+
+pub fn cond_name(cond: u32) -> &'static str {
+ match cond {
+ 0x0 => "eq",
+ 0x1 => "ne",
+ 0x2 => "cs",
+ 0x3 => "cc",
+ 0x4 => "mi",
+ 0x5 => "pl",
+ 0x6 => "vs",
+ 0x7 => "vc",
+ 0x8 => "hi",
+ 0x9 => "ls",
+ 0xa => "ge",
+ 0xb => "lt",
+ 0xc => "gt",
+ 0xd => "le",
+ 0xe => "al",
+ _ => "nv",
+ }
+}
diff --git a/crates/ghidrust-decode/src/arch/alpha/decode.rs b/crates/ghidrust-decode/src/arch/alpha/decode.rs
new file mode 100644
index 0000000..b5b87fc
--- /dev/null
+++ b/crates/ghidrust-decode/src/arch/alpha/decode.rs
@@ -0,0 +1,111 @@
+use crate::error::{Error, Result};
+
+pub fn r(n: u32) -> String {
+ format!("r{n}")
+}
+
+pub fn reg_name(reg: crate::reg::RegId) -> Option<&'static str> {
+ match reg.index() {
+ 0 => Some("r0"),
+ 1 => Some("r1"),
+ 26 => Some("ra"),
+ 27 => Some("at"),
+ 31 => Some("zero"),
+ _ => None,
+ }
+}
+
+pub fn decode(bytes: &[u8], little_endian: bool) -> Result<(String, String, usize)> {
+ if bytes.len() < 4 {
+ return Err(Error::Decode("truncated alpha instruction".into()));
+ }
+ let word = if little_endian {
+ u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])
+ } else {
+ u32::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])
+ };
+ let opcode = word >> 26;
+ match opcode {
+ 0x08 => decode_mem(word, "lda"),
+ 0x28 => decode_mem(word, "ldl"),
+ 0x29 => decode_mem(word, "ldq"),
+ 0x2c => decode_mem(word, "stl"),
+ 0x2d => decode_mem(word, "stq"),
+ 0x10 => decode_operate(word, "addl"),
+ 0x11 => decode_operate(word, "subl"),
+ 0x1a => {
+ let ra = (word >> 21) & 0x1f;
+ let name = if ra == 0 { "jmp" } else { "jsr" };
+ Ok((name.into(), decode_mem_ops(word), 4))
+ }
+ 0x1b => Ok(("ret".into(), String::new(), 4)),
+ 0x30..=0x3f => decode_branch(word, opcode),
+ _ => Err(Error::Decode("unsupported alpha opcode".into())),
+ }
+}
+
+fn decode_mem(word: u32, name: &str) -> Result<(String, String, usize)> {
+ Ok((name.into(), decode_mem_ops(word), 4))
+}
+
+fn decode_mem_ops(word: u32) -> String {
+ let ra = (word >> 21) & 0x1f;
+ let rb = (word >> 16) & 0x1f;
+ let disp = sign_ext((word >> 0) & 0xffff, 16);
+ format!("{}, {disp}({})", r(ra), r(rb))
+}
+
+fn decode_operate(word: u32, name: &str) -> Result<(String, String, usize)> {
+ let ra = (word >> 21) & 0x1f;
+ let rb = (word >> 16) & 0x1f;
+ let rc = (word >> 0) & 0x1f;
+ Ok((
+ name.into(),
+ format!("{}, {}, {}", r(ra), r(rb), r(rc)),
+ 4,
+ ))
+}
+
+fn decode_branch(word: u32, opcode: u32) -> Result<(String, String, usize)> {
+ let name = match opcode {
+ 0x30 => "br",
+ 0x31 => "blbc",
+ 0x32 => "beq",
+ 0x33 => "blt",
+ 0x34 => "bsr",
+ 0x35 => "blbs",
+ 0x36 => "bne",
+ 0x37 => "bge",
+ 0x38 => "bgt",
+ 0x39 => "bgeu",
+ 0x3a => "bvc",
+ 0x3b => "bvs",
+ _ => "br",
+ };
+ Ok((name.into(), decode_branch_target(word), 4))
+}
+
+fn decode_branch_target(word: u32) -> String {
+ let ra = (word >> 21) & 0x1f;
+ let disp = sign_ext((word >> 0) & 0x1fffff, 21);
+ format!("{}, {disp}", r(ra))
+}
+
+fn sign_ext(val: u32, bits: u32) -> i64 {
+ let shift = 32 - bits;
+ ((val << shift) as i32 >> shift) as i64
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn alpha_lda() {
+ let word = (0x08u32 << 26) | (1 << 21) | (2 << 16) | 8;
+ let (m, o, l) = decode(&word.to_le_bytes(), true).unwrap();
+ assert_eq!(m, "lda");
+ assert_eq!(l, 4);
+ assert!(o.contains("r1"));
+ }
+}
diff --git a/crates/ghidrust-decode/src/arch/alpha/mod.rs b/crates/ghidrust-decode/src/arch/alpha/mod.rs
new file mode 100644
index 0000000..1003e36
--- /dev/null
+++ b/crates/ghidrust-decode/src/arch/alpha/mod.rs
@@ -0,0 +1,129 @@
+mod decode;
+
+use crate::arch::ArchDecode;
+use crate::error::{Error, Result};
+use crate::group::GroupId;
+use crate::insn::{InsnDetail, InsnId, Instruction};
+use crate::names;
+use crate::option::EngineOptions;
+use crate::support::{Arch, Mode};
+
+pub use decode::reg_name;
+
+pub struct AlphaDecoder {
+ little_endian: bool,
+}
+
+impl ArchDecode for AlphaDecoder {
+ fn arch(&self) -> Arch {
+ Arch::Alpha
+ }
+
+ fn open(mode: Mode) -> Result<Self> {
+ if !mode.is_valid_for(Arch::Alpha) {
+ return Err(Error::Mode(format!("invalid alpha mode {:#x}", mode.bits())));
+ }
+ let little_endian = !mode.contains(Mode::BIG_ENDIAN);
+ Ok(Self { little_endian })
+ }
+
+ fn decode_one(&self, bytes: &[u8], address: u64, opts: &EngineOptions) -> Result<Instruction> {
+ let (mnemonic, operands, len) = decode::decode(bytes, self.little_endian)?;
+ let mut insn = Instruction::with_text(
+ address,
+ bytes[..len].to_vec(),
+ mnemonic,
+ operands,
+ len as u8,
+ );
+ insn.id = names::insn_id_for_mnemonic(Arch::Alpha, &insn.mnemonic);
+ if opts.detail {
+ insn.detail = Some(InsnDetail {
+ groups: groups_for_mnemonic(&insn.mnemonic),
+ ..InsnDetail::default()
+ });
+ }
+ Ok(insn)
+ }
+}
+
+fn groups_for_mnemonic(mnemonic: &str) -> Vec<GroupId> {
+ match mnemonic {
+ "bsr" | "jsr" => vec![GroupId::Call],
+ "jmp" | "br" | "beq" | "bne" => vec![GroupId::Jump],
+ "ret" => vec![GroupId::Ret],
+ m if m.starts_with("ld") => vec![GroupId::Arch(1)],
+ m if m.starts_with("st") => vec![GroupId::Arch(2)],
+ m if m.ends_with("l") => vec![GroupId::Arch(3)],
+ _ => Vec::new(),
+ }
+}
+
+pub fn insn_name(id: InsnId) -> Option<&'static str> {
+ match id.raw() {
+ 1 => Some("lda"),
+ 2 => Some("ldl"),
+ 3 => Some("addl"),
+ 4 => Some("bsr"),
+ 5 => Some("ret"),
+ _ => None,
+ }
+}
+
+pub fn group_name(group: GroupId) -> Option<&'static str> {
+ match group {
+ GroupId::Jump => Some("jump"),
+ GroupId::Call => Some("call"),
+ GroupId::Ret => Some("ret"),
+ GroupId::Arch(1) => Some("load"),
+ GroupId::Arch(2) => Some("store"),
+ GroupId::Arch(3) => Some("alu"),
+ _ => None,
+ }
+}
+
+pub fn insn_id_for_mnemonic(mnemonic: &str) -> InsnId {
+ let id = match mnemonic {
+ "lda" => 1,
+ "ldl" | "ldq" => 2,
+ "addl" | "subl" => 3,
+ "bsr" | "jsr" | "jmp" => 4,
+ "ret" => 5,
+ m if m.starts_with("st") => 2,
+ m if m.starts_with('b') => 4,
+ _ => 0,
+ };
+ InsnId(id)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::engine::Engine;
+
+ #[test]
+ fn alpha_lda_and_addl() {
+ let mut eng = Engine::open(Arch::Alpha, Mode::LITTLE_ENDIAN).unwrap();
+ // lda r1, 8(r2)
+ let word = (0x08u32 << 26) | (1 << 21) | (2 << 16) | 8;
+ let lda = eng.disasm_one(&word.to_le_bytes(), 0).unwrap();
+ assert_eq!(lda.mnemonic, "lda");
+ // addl r3, r1, r2
+ let add = (0x10u32 << 26) | (3 << 21) | (1 << 16) | 2;
+ let addl = eng.disasm_one(&add.to_le_bytes(), 0).unwrap();
+ assert_eq!(addl.mnemonic, "addl");
+ }
+
+ #[test]
+ fn alpha_branch_and_ret() {
+ let mut eng = Engine::open(Arch::Alpha, Mode::LITTLE_ENDIAN).unwrap();
+ // beq r1, 4
+ let beq = (0x32u32 << 26) | (1 << 21) | 4;
+ let insn = eng.disasm_one(&beq.to_le_bytes(), 0).unwrap();
+ assert_eq!(insn.mnemonic, "beq");
+ // ret opcode 0x1b << 26
+ let ret = 0x1bu32 << 26;
+ let r = eng.disasm_one(&ret.to_le_bytes(), 0).unwrap();
+ assert_eq!(r.mnemonic, "ret");
+ }
+}
diff --git a/crates/ghidrust-decode/src/arch/arc/decode.rs b/crates/ghidrust-decode/src/arch/arc/decode.rs
new file mode 100644
index 0000000..a57d699
--- /dev/null
+++ b/crates/ghidrust-decode/src/arch/arc/decode.rs
@@ -0,0 +1,107 @@
+use crate::error::{Error, Result};
+
+pub fn reg_name(reg: crate::reg::RegId) -> Option<&'static str> {
+ match reg.index() {
+ 0 => Some("r0"),
+ 1 => Some("r1"),
+ 15 => Some("sp"),
+ 31 => Some("blink"),
+ _ => None,
+ }
+}
+
+fn r(n: u32) -> String {
+ format!("r{n}")
+}
+
+pub fn decode(bytes: &[u8], little_endian: bool) -> Result<(String, String, usize)> {
+ if bytes.len() < 4 {
+ return Err(Error::Decode("truncated arc instruction".into()));
+ }
+ let word = if little_endian {
+ u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])
+ } else {
+ u32::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])
+ };
+ let major = (word >> 27) & 0x1f;
+ match major {
+ 0x00 => {
+ let dst = (word >> 16) & 0x1f;
+ let src = (word >> 0) & 0x1f;
+ Ok(("mov".into(), format!("{}, {}", r(dst), r(src)), 4))
+ }
+ 0x01 => {
+ let dst = (word >> 16) & 0x1f;
+ let src1 = (word >> 8) & 0x1f;
+ let src2 = (word >> 0) & 0x1f;
+ Ok((
+ "add".into(),
+ format!("{}, {}, {}", r(dst), r(src1), r(src2)),
+ 4,
+ ))
+ }
+ 0x02 => {
+ let dst = (word >> 16) & 0x1f;
+ let src1 = (word >> 8) & 0x1f;
+ let src2 = (word >> 0) & 0x1f;
+ Ok((
+ "sub".into(),
+ format!("{}, {}, {}", r(dst), r(src1), r(src2)),
+ 4,
+ ))
+ }
+ 0x08 => {
+ let dst = (word >> 16) & 0x1f;
+ let base = (word >> 8) & 0x1f;
+ let off = (word >> 0) & 0xff;
+ Ok((
+ "ld".into(),
+ format!("{}, [{off}({})]", r(dst), r(base)),
+ 4,
+ ))
+ }
+ 0x09 => {
+ let src = (word >> 16) & 0x1f;
+ let base = (word >> 8) & 0x1f;
+ let off = (word >> 0) & 0xff;
+ Ok((
+ "st".into(),
+ format!("{}, [{off}({})]", r(src), r(base)),
+ 4,
+ ))
+ }
+ 0x10 => {
+ let disp = sign_ext((word >> 0) & 0x7ffffff, 27);
+ Ok(("j".into(), format!("{disp}"), 4))
+ }
+ 0x11 => {
+ let disp = sign_ext((word >> 0) & 0x7ffffff, 27);
+ Ok(("jl".into(), format!("{disp}"), 4))
+ }
+ 0x12 => {
+ let cond = (word >> 16) & 0x1f;
+ let disp = sign_ext((word >> 0) & 0xffff, 16);
+ Ok(("br".into(), format!("{cond}, {disp}"), 4))
+ }
+ _ => Err(Error::Decode("unsupported arc opcode".into())),
+ }
+}
+
+fn sign_ext(val: u32, bits: u32) -> i64 {
+ let shift = 32 - bits;
+ ((val << shift) as i32 >> shift) as i64
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn arc_mov() {
+ let word = (0x00u32 << 27) | (1 << 16) | 0;
+ let (m, o, l) = decode(&word.to_le_bytes(), true).unwrap();
+ assert_eq!(m, "mov");
+ assert_eq!(l, 4);
+ assert!(o.contains("r1"));
+ }
+}
diff --git a/crates/ghidrust-decode/src/arch/arc/mod.rs b/crates/ghidrust-decode/src/arch/arc/mod.rs
new file mode 100644
index 0000000..48b71ae
--- /dev/null
+++ b/crates/ghidrust-decode/src/arch/arc/mod.rs
@@ -0,0 +1,122 @@
+mod decode;
+
+use crate::arch::ArchDecode;
+use crate::error::{Error, Result};
+use crate::group::GroupId;
+use crate::insn::{InsnDetail, InsnId, Instruction};
+use crate::names;
+use crate::option::EngineOptions;
+use crate::support::{Arch, Mode};
+
+pub use decode::reg_name;
+
+pub struct ArcDecoder {
+ little_endian: bool,
+}
+
+impl ArchDecode for ArcDecoder {
+ fn arch(&self) -> Arch {
+ Arch::Arc
+ }
+
+ fn open(mode: Mode) -> Result<Self> {
+ if !mode.is_valid_for(Arch::Arc) {
+ return Err(Error::Mode(format!("invalid arc mode {:#x}", mode.bits())));
+ }
+ let little_endian = !mode.contains(Mode::BIG_ENDIAN);
+ Ok(Self { little_endian })
+ }
+
+ fn decode_one(&self, bytes: &[u8], address: u64, opts: &EngineOptions) -> Result<Instruction> {
+ let (mnemonic, operands, len) = decode::decode(bytes, self.little_endian)?;
+ let mut insn = Instruction::with_text(
+ address,
+ bytes[..len].to_vec(),
+ mnemonic,
+ operands,
+ len as u8,
+ );
+ insn.id = names::insn_id_for_mnemonic(Arch::Arc, &insn.mnemonic);
+ if opts.detail {
+ insn.detail = Some(InsnDetail {
+ groups: groups_for_mnemonic(&insn.mnemonic),
+ ..InsnDetail::default()
+ });
+ }
+ Ok(insn)
+ }
+}
+
+fn groups_for_mnemonic(mnemonic: &str) -> Vec<GroupId> {
+ match mnemonic {
+ "jl" => vec![GroupId::Call],
+ "j" | "br" => vec![GroupId::Jump],
+ "ld" => vec![GroupId::Arch(1)],
+ "st" => vec![GroupId::Arch(2)],
+ "add" | "sub" | "mov" => vec![GroupId::Arch(3)],
+ _ => Vec::new(),
+ }
+}
+
+pub fn insn_name(id: InsnId) -> Option<&'static str> {
+ match id.raw() {
+ 1 => Some("mov"),
+ 2 => Some("add"),
+ 3 => Some("ld"),
+ 4 => Some("j"),
+ 5 => Some("br"),
+ _ => None,
+ }
+}
+
+pub fn group_name(group: GroupId) -> Option<&'static str> {
+ match group {
+ GroupId::Jump => Some("jump"),
+ GroupId::Call => Some("call"),
+ GroupId::Arch(1) => Some("load"),
+ GroupId::Arch(2) => Some("store"),
+ GroupId::Arch(3) => Some("alu"),
+ _ => None,
+ }
+}
+
+pub fn insn_id_for_mnemonic(mnemonic: &str) -> InsnId {
+ let id = match mnemonic {
+ "mov" => 1,
+ "add" | "sub" => 2,
+ "ld" => 3,
+ "j" => 4,
+ "jl" | "br" => 5,
+ "st" => 3,
+ _ => 0,
+ };
+ InsnId(id)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::engine::Engine;
+
+ #[test]
+ fn arc_mov_and_add() {
+ let mut eng = Engine::open(Arch::Arc, Mode::MODE_32).unwrap();
+ let mov = (0x00u32 << 27) | (1 << 16) | 0;
+ let m = eng.disasm_one(&mov.to_le_bytes(), 0).unwrap();
+ assert_eq!(m.mnemonic, "mov");
+ let add = (0x01u32 << 27) | (2 << 16) | (1 << 8) | 0;
+ let a = eng.disasm_one(&add.to_le_bytes(), 0).unwrap();
+ assert_eq!(a.mnemonic, "add");
+ }
+
+ #[test]
+ fn arc_ld_and_j() {
+ let mut eng = Engine::open(Arch::Arc, Mode::MODE_32).unwrap();
+ let ld = (0x08u32 << 27) | (4 << 16) | (1 << 8) | 8;
+ let l = eng.disasm_one(&ld.to_le_bytes(), 0).unwrap();
+ assert_eq!(l.mnemonic, "ld");
+ let j = (0x10u32 << 27) | 16;
+ let jmp = eng.disasm_one(&j.to_le_bytes(), 0).unwrap();
+ assert_eq!(jmp.mnemonic, "j");
+ }
+}
diff --git a/crates/ghidrust-decode/src/arch/arm/a32_branch.rs b/crates/ghidrust-decode/src/arch/arm/a32_branch.rs
new file mode 100644
index 0000000..315f441
--- /dev/null
+++ b/crates/ghidrust-decode/src/arch/arm/a32_branch.rs
@@ -0,0 +1,63 @@
+use super::regs::gpr;
+use super::util::{cond_suffix, fmt_imm_hex, sign_extend};
+use crate::error::Result;
+use crate::insn::Instruction;
+
+pub fn decode(word: u32, address: u64, raw: &[u8]) -> Result<Instruction> {
+ let cond = (word >> 28) & 0xf;
+ decode_branch(word, cond, address, raw)
+}
+
+fn decode_branch(word: u32, cond: u32, address: u64, raw: &[u8]) -> Result<Instruction> {
+ let link = (word >> 24) & 1;
+ let imm24 = word & 0x00ff_ffff;
+ let offset = sign_extend(imm24 << 2, 26);
+ let target = (address as i64).wrapping_add(offset as i64) as u64;
+ let suffix = cond_suffix(cond);
+ let (mnemonic, operands) = if link != 0 {
+ (
+ if suffix.is_empty() {
+ "bl".to_string()
+ } else {
+ format!("bl{suffix}")
+ },
+ fmt_imm_hex(target as i64),
+ )
+ } else {
+ (
+ if suffix.is_empty() {
+ "b".to_string()
+ } else {
+ format!("b{suffix}")
+ },
+ fmt_imm_hex(target as i64),
+ )
+ };
+ Ok(Instruction::with_text(address, raw.to_vec(), mnemonic, operands, 4))
+}
+
+pub fn try_decode_bx(word: u32, address: u64, raw: &[u8]) -> Option<Result<Instruction>> {
+ // BX / BLX register: cond 0001 0010 1111 1111 1111 0000 Rm
+ if (word & 0x0ff0_00f0) == 0x0120_00f0 {
+ let rm = word & 0xf;
+ let link = (word >> 21) & 1;
+ let mnemonic = if link != 0 { "blx" } else { "bx" };
+ return Some(Ok(Instruction::with_text(
+ address,
+ raw.to_vec(),
+ mnemonic,
+ gpr(rm),
+ 4,
+ )));
+ }
+ None
+}
+
+pub fn try_decode(word: u32, address: u64, raw: &[u8]) -> Option<Result<Instruction>> {
+ let top = (word >> 25) & 0x7;
+ if top == 0b101 {
+ Some(decode(word, address, raw))
+ } else {
+ None
+ }
+}
diff --git a/crates/ghidrust-decode/src/arch/arm/a32_data.rs b/crates/ghidrust-decode/src/arch/arm/a32_data.rs
new file mode 100644
index 0000000..c77f134
--- /dev/null
+++ b/crates/ghidrust-decode/src/arch/arm/a32_data.rs
@@ -0,0 +1,124 @@
+use super::regs::gpr;
+use super::util::{arm_dp_imm, arm_dp_mnemonic, cond_suffix, fmt_shift_reg, is_dp_compare};
+use crate::error::Result;
+use crate::insn::Instruction;
+
+pub fn try_decode(word: u32, address: u64, raw: &[u8]) -> Option<Result<Instruction>> {
+ let top = (word >> 26) & 0x3;
+ if top == 0b00 && ((word >> 25) & 1) == 0 {
+ Some(decode_dp_imm(word, address, raw))
+ } else if top == 0b00 && ((word >> 25) & 1) == 1 && ((word >> 4) & 0xf) == 0b1001 {
+ Some(decode_multiply(word, address, raw))
+ } else if top == 0b00 && ((word >> 25) & 1) == 1 {
+ Some(decode_dp_reg(word, address, raw))
+ } else {
+ None
+ }
+}
+
+fn decode_dp_imm(word: u32, address: u64, raw: &[u8]) -> Result<Instruction> {
+ let cond = (word >> 28) & 0xf;
+ let opcode = (word >> 21) & 0xf;
+ let s = ((word >> 20) & 1) != 0;
+ let rn = (word >> 16) & 0xf;
+ let rd = (word >> 12) & 0xf;
+ let imm = arm_dp_imm(word & 0xfff);
+ let base = arm_dp_mnemonic(opcode, s);
+ let suffix = cond_suffix(cond);
+ let mnemonic = if suffix.is_empty() {
+ base.to_string()
+ } else {
+ format!("{base}{suffix}")
+ };
+ let operands = if is_dp_compare(opcode) {
+ format!("{}, {}, #{:#x}", gpr(rn), gpr(rd), imm)
+ } else if opcode == 0b1101 && rn == 0xf {
+ // mov
+ format!("{}, #{:#x}", gpr(rd), imm)
+ } else if opcode == 0b1111 && rn == 0xf {
+ format!("{}, #{:#x}", gpr(rd), imm)
+ } else {
+ format!("{}, {}, #{:#x}", gpr(rd), gpr(rn), imm)
+ };
+ Ok(Instruction::with_text(address, raw.to_vec(), mnemonic, operands, 4))
+}
+
+fn decode_dp_reg(word: u32, address: u64, raw: &[u8]) -> Result<Instruction> {
+ let cond = (word >> 28) & 0xf;
+ let opcode = (word >> 21) & 0xf;
+ let s = ((word >> 20) & 1) != 0;
+ let rn = (word >> 16) & 0xf;
+ let rd = (word >> 12) & 0xf;
+ let rs = (word >> 8) & 0xf;
+ let shift = (word >> 4) & 0xff;
+ let shift_type = (shift >> 5) & 0x3;
+ let shift_imm = shift & 0x1f;
+ let base = arm_dp_mnemonic(opcode, s);
+ let suffix = cond_suffix(cond);
+ let mnemonic = if suffix.is_empty() {
+ base.to_string()
+ } else {
+ format!("{base}{suffix}")
+ };
+ let shift_str = fmt_shift_reg(shift_type, shift_imm);
+ let operands = if is_dp_compare(opcode) {
+ format!("{}, {}{}", gpr(rn), gpr(rs), shift_str)
+ } else if opcode == 0b1101 && rn == 0xf {
+ format!("{}, {}{}", gpr(rd), gpr(rs), shift_str)
+ } else if opcode == 0b1111 && rn == 0xf {
+ format!("{}, {}{}", gpr(rd), gpr(rs), shift_str)
+ } else {
+ format!("{}, {}, {}{}", gpr(rd), gpr(rn), gpr(rs), shift_str)
+ };
+ Ok(Instruction::with_text(address, raw.to_vec(), mnemonic, operands, 4))
+}
+
+fn decode_multiply(word: u32, address: u64, raw: &[u8]) -> Result<Instruction> {
+ let cond = (word >> 28) & 0xf;
+ let a = ((word >> 21) & 1) != 0;
+ let rd = (word >> 16) & 0xf;
+ let rn = (word >> 12) & 0xf;
+ let rs = (word >> 8) & 0xf;
+ let rm = word & 0xf;
+ let suffix = cond_suffix(cond);
+ let (base, operands) = if a {
+ (
+ "mla",
+ format!("{}, {}, {}, {}", gpr(rd), gpr(rm), gpr(rs), gpr(rn)),
+ )
+ } else {
+ (
+ "mul",
+ format!("{}, {}, {}", gpr(rd), gpr(rm), gpr(rs)),
+ )
+ };
+ let mnemonic = if suffix.is_empty() {
+ base.to_string()
+ } else {
+ format!("{base}{suffix}")
+ };
+ Ok(Instruction::with_text(address, raw.to_vec(), mnemonic, operands, 4))
+}
+
+pub fn try_decode_misc(word: u32, address: u64, raw: &[u8]) -> Option<Result<Instruction>> {
+ // CLZ Rd, Rm: cond 0001 0110 1111 Rm 0000 0001 Rd
+ if (word & 0x0ff0_0f70) == 0x0160_0f10 {
+ let cond = (word >> 28) & 0xf;
+ let rd = (word >> 12) & 0xf;
+ let rm = word & 0xf;
+ let suffix = cond_suffix(cond);
+ let mnemonic = if suffix.is_empty() {
+ "clz".into()
+ } else {
+ format!("clz{suffix}")
+ };
+ return Some(Ok(Instruction::with_text(
+ address,
+ raw.to_vec(),
+ mnemonic,
+ format!("{}, {}", gpr(rd), gpr(rm)),
+ 4,
+ )));
+ }
+ None
+}
diff --git a/crates/ghidrust-decode/src/arch/arm/a32_load_store.rs b/crates/ghidrust-decode/src/arch/arm/a32_load_store.rs
new file mode 100644
index 0000000..5e4e00b
--- /dev/null
+++ b/crates/ghidrust-decode/src/arch/arm/a32_load_store.rs
@@ -0,0 +1,147 @@
+use super::regs::gpr;
+use super::util::cond_suffix;
+use crate::error::Result;
+use crate::insn::Instruction;
+
+pub fn try_decode(word: u32, address: u64, raw: &[u8]) -> Option<Result<Instruction>> {
+ let top = (word >> 26) & 0x3;
+ if top == 0b01 {
+ Some(decode_immediate(word, address, raw))
+ } else if top == 0b11 && ((word >> 25) & 1) == 0 {
+ Some(decode_register(word, address, raw))
+ } else {
+ None
+ }
+}
+
+fn decode_immediate(word: u32, address: u64, raw: &[u8]) -> Result<Instruction> {
+ let cond = (word >> 28) & 0xf;
+ let p = ((word >> 24) & 1) != 0;
+ let u = ((word >> 23) & 1) != 0;
+ let b = ((word >> 22) & 1) != 0;
+ let w = ((word >> 21) & 1) != 0;
+ let l = ((word >> 20) & 1) != 0;
+ let rn = (word >> 16) & 0xf;
+ let rd = (word >> 12) & 0xf;
+ let imm12 = word & 0xfff;
+ let offset = if u { imm12 } else { 0u32.wrapping_sub(imm12) };
+ let size = if b { 1u8 } else if w { 4 } else { 2 };
+ let size_str = match size {
+ 1 => "b",
+ 2 => "h",
+ 4 => "w",
+ _ => "",
+ };
+ let suffix = cond_suffix(cond);
+ let (base, operands) = if l {
+ if rd == 15 {
+ // LDR literal pool
+ let base_addr = if p {
+ address.wrapping_add(8)
+ } else {
+ address.wrapping_add(4)
+ };
+ let ea = base_addr.wrapping_add(offset as u64);
+ (
+ format!("ldr{suffix}"),
+ format!("pc, [{:#x}]", ea),
+ )
+ } else {
+ let sign = if u { "" } else { "-" };
+ (
+ format!("ldr{suffix}{size_str}"),
+ format!("{}, [{}{}]", gpr(rd), gpr(rn), if offset != 0 { format!(", {sign}{offset}") } else { String::new() }),
+ )
+ }
+ } else {
+ let sign = if u { "" } else { "-" };
+ (
+ format!("str{suffix}{size_str}"),
+ format!("{}, [{}{}]", gpr(rd), gpr(rn), if offset != 0 { format!(", {sign}{offset}") } else { String::new() }),
+ )
+ };
+ Ok(Instruction::with_text(address, raw.to_vec(), base, operands, 4))
+}
+
+fn decode_register(word: u32, address: u64, raw: &[u8]) -> Result<Instruction> {
+ let cond = (word >> 28) & 0xf;
+ let p = ((word >> 24) & 1) != 0;
+ let u = ((word >> 23) & 1) != 0;
+ let b = ((word >> 22) & 1) != 0;
+ let w = ((word >> 21) & 1) != 0;
+ let l = ((word >> 20) & 1) != 0;
+ let rn = (word >> 16) & 0xf;
+ let rd = (word >> 12) & 0xf;
+ let rm = word & 0xf;
+ let size = if b { 1u8 } else if w { 4 } else { 2 };
+ let size_str = match size {
+ 1 => "b",
+ 2 => "h",
+ 4 => "w",
+ _ => "",
+ };
+ let suffix = cond_suffix(cond);
+ let sign = if u { "" } else { "-" };
+ let (base, operands) = if l {
+ (
+ format!("ldr{suffix}{size_str}"),
+ format!("{}, [{}{}]", gpr(rd), gpr(rn), format!(", {sign}{}", gpr(rm))),
+ )
+ } else {
+ (
+ format!("str{suffix}{size_str}"),
+ format!("{}, [{}{}]", gpr(rd), gpr(rn), format!(", {sign}{}", gpr(rm))),
+ )
+ };
+ let _ = p;
+ Ok(Instruction::with_text(address, raw.to_vec(), base, operands, 4))
+}
+
+pub fn try_decode_extra(word: u32, address: u64, raw: &[u8]) -> Option<Result<Instruction>> {
+ // Load/store dual immediate: cond 000 P U S W L Rn Rd imm4
+ if (word & 0x0e00_0000) == 0x0400_0000 && ((word >> 25) & 1) == 0 && ((word >> 20) & 0x10) != 0 {
+ let cond = (word >> 28) & 0xf;
+ let u = ((word >> 23) & 1) != 0;
+ let l = ((word >> 20) & 1) != 0;
+ let rn = (word >> 16) & 0xf;
+ let rd = (word >> 12) & 0xf;
+ let imm = (word & 0xf) << 4 | ((word >> 8) & 0xf);
+ let offset = if u { imm } else { 0u32.wrapping_sub(imm) };
+ let suffix = cond_suffix(cond);
+ let sign = if u { "" } else { "-" };
+ let base = if l {
+ format!("ldm{suffix}ia")
+ } else {
+ format!("stm{suffix}ia")
+ };
+ let operands = format!("{}, {{{}, {}}}", gpr(rn), gpr(rd), gpr(rd + 1));
+ let _ = (offset, sign);
+ return Some(Ok(Instruction::with_text(address, raw.to_vec(), base, operands, 4)));
+ }
+ // LDRD/STRD immediate
+ if (word & 0x0e50_00f0) == 0x0040_00d0 {
+ let cond = (word >> 28) & 0xf;
+ let u = ((word >> 23) & 1) != 0;
+ let l = ((word >> 20) & 1) != 0;
+ let rn = (word >> 16) & 0xf;
+ let rd = (word >> 12) & 0xf;
+ let imm = (word & 0xf) << 4 | ((word >> 8) & 0xf);
+ let offset = if u { imm } else { 0u32.wrapping_sub(imm) };
+ let suffix = cond_suffix(cond);
+ let sign = if u { "" } else { "-" };
+ let base = if l { format!("ldrd{suffix}") } else { format!("strd{suffix}") };
+ let operands = format!(
+ "{}, {}, [{}{}]",
+ gpr(rd),
+ gpr(rd + 1),
+ gpr(rn),
+ if offset != 0 {
+ format!(", {sign}{offset}")
+ } else {
+ String::new()
+ }
+ );
+ return Some(Ok(Instruction::with_text(address, raw.to_vec(), base, operands, 4)));
+ }
+ None
+}
diff --git a/crates/ghidrust-decode/src/arch/arm/a32_media.rs b/crates/ghidrust-decode/src/arch/arm/a32_media.rs
new file mode 100644
index 0000000..570efa7
--- /dev/null
+++ b/crates/ghidrust-decode/src/arch/arm/a32_media.rs
@@ -0,0 +1,95 @@
+use super::regs::{gpr, neon_d};
+use super::util::cond_suffix;
+use crate::error::Result;
+use crate::insn::Instruction;
+
+pub fn try_decode(word: u32, address: u64, raw: &[u8]) -> Option<Result<Instruction>> {
+ let top = (word >> 24) & 0xf;
+ // VFP / NEON data processing in A32: cond 111x ..
+ if top == 0b1110 || top == 0b1101 {
+ return try_neon_vfp(word, address, raw);
+ }
+ None
+}
+
+fn try_neon_vfp(word: u32, address: u64, raw: &[u8]) -> Option<Result<Instruction>> {
+ // VMOV (register): cond 1110 0001 0000 Rn 0000 0000 Rd
+ if (word & 0x0fe0_0fff) == 0x0e10_0000 {
+ let cond = (word >> 28) & 0xf;
+ let rd = (word >> 12) & 0xf;
+ let rm = word & 0xf;
+ let suffix = cond_suffix(cond);
+ let mnemonic = if suffix.is_empty() {
+ "vmov".into()
+ } else {
+ format!("vmov{suffix}")
+ };
+ return Some(Ok(Instruction::with_text(
+ address,
+ raw.to_vec(),
+ mnemonic,
+ format!("{}, {}", neon_d(rd), neon_d(rm)),
+ 4,
+ )));
+ }
+ // VADD.F32 Dd, Dn, Dm: cond 1110 0011 0 Dn 0010 1 Dm 0 Dd
+ if (word & 0xfe50_0f50) == 0xee30_0b00 {
+ let cond = (word >> 28) & 0xf;
+ let d = ((word >> 22) & 1) << 4 | ((word >> 12) & 0xf);
+ let n = ((word >> 7) & 0xf) << 1 | ((word >> 16) & 0xf);
+ let m = word & 0xf;
+ let suffix = cond_suffix(cond);
+ let mnemonic = if suffix.is_empty() {
+ "vadd.f32".into()
+ } else {
+ format!("vadd.f32{suffix}")
+ };
+ return Some(Ok(Instruction::with_text(
+ address,
+ raw.to_vec(),
+ mnemonic,
+ format!("{}, {}, {}", neon_d(d), neon_d(n), neon_d(m)),
+ 4,
+ )));
+ }
+ // VLD1 / VST1 multiple
+ if (word & 0xff20_0f00) == 0xec00_0a00 {
+ let cond = (word >> 28) & 0xf;
+ let l = ((word >> 20) & 1) != 0;
+ let rn = (word >> 16) & 0xf;
+ let d = ((word >> 22) & 1) << 4 | ((word >> 12) & 0xf);
+ let suffix = cond_suffix(cond);
+ let base = if l {
+ format!("vld1.32{suffix}")
+ } else {
+ format!("vst1.32{suffix}")
+ };
+ return Some(Ok(Instruction::with_text(
+ address,
+ raw.to_vec(),
+ base,
+ format!("{{{}}}, [{}]", neon_d(d), gpr(rn)),
+ 4,
+ )));
+ }
+ // VMOV (general): ARM to scalar
+ if (word & 0x0fe0_0fff) == 0x0e00_0b10 {
+ let cond = (word >> 28) & 0xf;
+ let rd = (word >> 12) & 0xf;
+ let vn = (((word >> 16) & 0xf) << 1) | ((word >> 7) & 1);
+ let suffix = cond_suffix(cond);
+ let mnemonic = if suffix.is_empty() {
+ "vmov".into()
+ } else {
+ format!("vmov{suffix}")
+ };
+ return Some(Ok(Instruction::with_text(
+ address,
+ raw.to_vec(),
+ mnemonic,
+ format!("{}, {}", gpr(rd), neon_d(vn)),
+ 4,
+ )));
+ }
+ None
+}
diff --git a/crates/ghidrust-decode/src/arch/arm/a32_system.rs b/crates/ghidrust-decode/src/arch/arm/a32_system.rs
new file mode 100644
index 0000000..87fd78b
--- /dev/null
+++ b/crates/ghidrust-decode/src/arch/arm/a32_system.rs
@@ -0,0 +1,94 @@
+use super::regs::{gpr, psr_field};
+use super::util::cond_suffix;
+use crate::error::Result;
+use crate::insn::Instruction;
+
+pub fn try_decode(word: u32, address: u64, raw: &[u8]) -> Option<Result<Instruction>> {
+ // SVC: cond 1111 imm24
+ if (word & 0x0f00_0000) == 0x0f00_0000 {
+ let cond = (word >> 28) & 0xf;
+ let imm = word & 0x00ff_ffff;
+ let suffix = cond_suffix(cond);
+ let mnemonic = if suffix.is_empty() {
+ "svc".into()
+ } else {
+ format!("svc{suffix}")
+ };
+ return Some(Ok(Instruction::with_text(
+ address,
+ raw.to_vec(),
+ mnemonic,
+ format!("#{:#x}", imm),
+ 4,
+ )));
+ }
+ // MRS: cond 000 10 R 0000 0000 mask 0000 Rd
+ if (word & 0x0fbf_0fff) == 0x010f_0000 {
+ let cond = (word >> 28) & 0xf;
+ let rd = (word >> 12) & 0xf;
+ let r = ((word >> 22) & 1) != 0;
+ let field = (word >> 16) & 0x1f;
+ let suffix = cond_suffix(cond);
+ let src = if r { "spsr" } else { "cpsr" };
+ let mnemonic = if suffix.is_empty() {
+ "mrs".into()
+ } else {
+ format!("mrs{suffix}")
+ };
+ let operands = if field == 0 {
+ format!("{}, {}", gpr(rd), src)
+ } else {
+ format!("{}, {}_{}", gpr(rd), src, psr_field(field))
+ };
+ return Some(Ok(Instruction::with_text(address, raw.to_vec(), mnemonic, operands, 4)));
+ }
+ // MSR: cond 000 10 R 10 mask 0000 Rm
+ if (word & 0x0fb0_0ff0) == 0x0120_0f00 {
+ let cond = (word >> 28) & 0xf;
+ let rm = word & 0xf;
+ let r = ((word >> 22) & 1) != 0;
+ let field = (word >> 16) & 0x1f;
+ let suffix = cond_suffix(cond);
+ let dst = if r { "spsr" } else { "cpsr" };
+ let mnemonic = if suffix.is_empty() {
+ "msr".into()
+ } else {
+ format!("msr{suffix}")
+ };
+ let operands = if field == 0 {
+ format!("{}, {}", dst, gpr(rm))
+ } else {
+ format!("{}_{}, {}", dst, psr_field(field), gpr(rm))
+ };
+ return Some(Ok(Instruction::with_text(address, raw.to_vec(), mnemonic, operands, 4)));
+ }
+ // NOP (hint): cond 0001 0010 0000 1111 1111 0000 0000
+ if word == 0xe320_0070 || (word & 0x0ff0_0fff) == 0x0320_0f00 && (word & 0xf) == 0 {
+ let cond = (word >> 28) & 0xf;
+ let suffix = cond_suffix(cond);
+ let mnemonic = if suffix.is_empty() {
+ "nop".into()
+ } else {
+ format!("nop{suffix}")
+ };
+ return Some(Ok(Instruction::with_text(
+ address,
+ raw.to_vec(),
+ mnemonic,
+ "",
+ 4,
+ )));
+ }
+ // BKPT
+ if (word & 0x0ff0_00f0) == 0x0120_0070 {
+ let imm = (word >> 4) & 0xfff | ((word >> 8) & 0xf) << 12;
+ return Some(Ok(Instruction::with_text(
+ address,
+ raw.to_vec(),
+ "bkpt",
+ format!("#{:#x}", imm),
+ 4,
+ )));
+ }
+ None
+}
diff --git a/crates/ghidrust-decode/src/arch/arm/dispatch.rs b/crates/ghidrust-decode/src/arch/arm/dispatch.rs
new file mode 100644
index 0000000..4b17b29
--- /dev/null
+++ b/crates/ghidrust-decode/src/arch/arm/dispatch.rs
@@ -0,0 +1,55 @@
+use super::a32_branch;
+use super::a32_data;
+use super::a32_load_store;
+use super::a32_media;
+use super::a32_system;
+use super::thumb16;
+use super::thumb32;
+use super::util;
+use crate::error::{Error, Result};
+use crate::insn::Instruction;
+
+pub fn decode_a32(bytes: &[u8], address: u64, big_endian: bool) -> Result<Instruction> {
+ if bytes.len() < 4 {
+ return Err(Error::Decode("truncated A32 instruction".into()));
+ }
+ let word = util::read_u32_le(bytes, big_endian)?;
+ let raw = &bytes[..4];
+ if let Some(r) = a32_system::try_decode(word, address, raw) {
+ return r;
+ }
+ if let Some(r) = a32_branch::try_decode_bx(word, address, raw) {
+ return r;
+ }
+ if let Some(r) = a32_branch::try_decode(word, address, raw) {
+ return r;
+ }
+ if let Some(r) = a32_data::try_decode_misc(word, address, raw) {
+ return r;
+ }
+ if let Some(r) = a32_data::try_decode(word, address, raw) {
+ return r;
+ }
+ if let Some(r) = a32_load_store::try_decode_extra(word, address, raw) {
+ return r;
+ }
+ if let Some(r) = a32_load_store::try_decode(word, address, raw) {
+ return r;
+ }
+ if let Some(r) = a32_media::try_decode(word, address, raw) {
+ return r;
+ }
+ Err(Error::Decode(format!("unhandled A32 encoding {word:#010x}")))
+}
+
+pub fn decode_thumb(bytes: &[u8], address: u64, big_endian: bool) -> Result<Instruction> {
+ if bytes.len() < 2 {
+ return Err(Error::Decode("truncated Thumb instruction".into()));
+ }
+ let hw = util::read_u16_le(bytes, big_endian)?;
+ if (hw & 0xe000) >= 0xe000 && (hw & 0x1800) != 0x0000 {
+ thumb32::decode(bytes, address, big_endian)
+ } else {
+ thumb16::decode(hw, bytes, address, big_endian)
+ }
+}
diff --git a/crates/ghidrust-decode/src/arch/arm/mod.rs b/crates/ghidrust-decode/src/arch/arm/mod.rs
new file mode 100644
index 0000000..da37ad1
--- /dev/null
+++ b/crates/ghidrust-decode/src/arch/arm/mod.rs
@@ -0,0 +1,182 @@
+mod a32_branch;
+mod a32_data;
+mod a32_load_store;
+mod a32_media;
+mod a32_system;
+mod dispatch;
+mod regs;
+mod thumb16;
+mod thumb32;
+mod util;
+
+use crate::arch::ArchDecode;
+use crate::error::{Error, Result};
+use crate::group::GroupId;
+use crate::insn::{InsnDetail, InsnId, Instruction};
+use crate::names;
+use crate::option::EngineOptions;
+use crate::operand::OpType;
+use crate::reg::RegId;
+use crate::support::{Arch, Mode};
+
+pub struct ArmDecoder {
+ mode: Mode,
+ thumb: bool,
+ big_endian: bool,
+}
+
+impl ArchDecode for ArmDecoder {
+ fn arch(&self) -> Arch {
+ Arch::Arm
+ }
+
+ fn open(mode: Mode) -> Result<Self> {
+ if !mode.is_valid_for(Arch::Arm) {
+ return Err(Error::Mode(format!("invalid ARM mode {:#x}", mode.bits())));
+ }
+ let thumb = mode.contains(Mode::THUMB);
+ let big_endian = mode.contains(Mode::BIG_ENDIAN);
+ Ok(Self {
+ mode,
+ thumb,
+ big_endian,
+ })
+ }
+
+ fn decode_one(&self, bytes: &[u8], address: u64, opts: &EngineOptions) -> Result<Instruction> {
+ let mut insn = if self.thumb {
+ dispatch::decode_thumb(bytes, address, self.big_endian)?
+ } else {
+ dispatch::decode_a32(bytes, address, self.big_endian)?
+ };
+ insn.id = names::insn_id_for_mnemonic(Arch::Arm, &insn.mnemonic);
+ if let Some(over) = opts.mnemonic_overrides.get(&insn.id.raw()) {
+ insn.mnemonic = over.clone();
+ }
+ if opts.detail {
+ insn.detail = Some(InsnDetail {
+ groups: groups_for_mnemonic(&insn.mnemonic),
+ ..InsnDetail::default()
+ });
+ }
+ let _ = (self.mode, opts.syntax);
+ Ok(insn)
+ }
+}
+
+fn groups_for_mnemonic(mnemonic: &str) -> Vec<GroupId> {
+ let m = mnemonic.split('.').next().unwrap_or(mnemonic);
+ if m == "bl" || m.starts_with("blx") {
+ vec![GroupId::Call, GroupId::BranchRelative]
+ } else if m == "bx" || m == "b" || (m.starts_with('b') && !m.starts_with("bic")) {
+ vec![GroupId::Jump, GroupId::BranchRelative]
+ } else if m.starts_with("svc") {
+ vec![GroupId::Int]
+ } else {
+ Vec::new()
+ }
+}
+
+pub fn reg_name(reg: RegId) -> Option<&'static str> {
+ Some(regs::gpr(reg.index() as u32))
+}
+
+pub fn insn_name(id: InsnId) -> Option<&'static str> {
+ match id.raw() {
+ 1 => Some("mov"),
+ 2 => Some("ldr"),
+ 3 => Some("str"),
+ 4 => Some("b"),
+ 5 => Some("bl"),
+ 6 => Some("add"),
+ 7 => Some("sub"),
+ 8 => Some("push"),
+ 9 => Some("pop"),
+ 10 => Some("svc"),
+ 11 => Some("bx"),
+ 12 => Some("nop"),
+ _ => None,
+ }
+}
+
+pub fn group_name(group: GroupId) -> Option<&'static str> {
+ match group {
+ GroupId::Jump => Some("jump"),
+ GroupId::Call => Some("call"),
+ GroupId::Ret => Some("ret"),
+ GroupId::Int => Some("int"),
+ GroupId::BranchRelative => Some("branch_relative"),
+ _ => None,
+ }
+}
+
+pub fn insn_id_for_mnemonic(mnemonic: &str) -> InsnId {
+ let m = mnemonic.split('.').next().unwrap_or(mnemonic);
+ let id = match m.trim_end_matches(|c: char| c.is_ascii_lowercase() && c != 'x') {
+ s if s.starts_with("mov") => 1,
+ s if s.starts_with("ldr") => 2,
+ s if s.starts_with("str") => 3,
+ "b" => 4,
+ "bl" | "blx" => 5,
+ s if s.starts_with("add") => 6,
+ s if s.starts_with("sub") => 7,
+ "push" => 8,
+ "pop" => 9,
+ s if s.starts_with("svc") => 10,
+ "bx" => 11,
+ "nop" => 12,
+ _ => 0,
+ };
+ InsnId(id)
+}
+
+#[allow(dead_code)]
+fn _op_type_used() -> OpType {
+ OpType::Invalid
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::engine::Engine;
+
+ #[test]
+ fn arm_a32_mov_add_branch() {
+ let mut eng = Engine::open(Arch::Arm, Mode::LITTLE_ENDIAN).unwrap();
+ // mov r0, #1 -> e3a00001
+ let mov = eng.disasm_one(&[0x01, 0x00, 0xa0, 0xe3], 0x1000).unwrap();
+ assert_eq!(mov.mnemonic, "mov");
+ assert_eq!(mov.length, 4);
+ // add r1, r0, r2 -> e0801002
+ let add = eng.disasm_one(&[0x02, 0x10, 0x80, 0xe0], 0x1004).unwrap();
+ assert_eq!(add.mnemonic, "add");
+ // b #0 -> ea000000
+ let b = eng.disasm_one(&[0x00, 0x00, 0x00, 0xea], 0x1008).unwrap();
+ assert_eq!(b.mnemonic, "b");
+ }
+
+ #[test]
+ fn arm_thumb16_push_pop() {
+ let mut eng = Engine::open(Arch::Arm, Mode::THUMB).unwrap();
+ // push {r4, lr} -> b510
+ let push = eng.disasm_one(&[0x10, 0xb5], 0x2000).unwrap();
+ assert_eq!(push.mnemonic, "push");
+ assert_eq!(push.length, 2);
+ }
+
+ #[test]
+ fn arm_thumb32_bl() {
+ let mut eng = Engine::open(Arch::Arm, Mode::THUMB).unwrap();
+ // bl #0 -> f0 00 f8 00 (approx — zero offset BL)
+ let bl = eng.disasm_one(&[0x00, 0xf0, 0x00, 0xf8], 0x3000).unwrap();
+ assert!(bl.mnemonic == "bl" || bl.mnemonic.starts_with("bl"));
+ assert_eq!(bl.length, 4);
+ }
+
+ #[test]
+ fn arm_svc() {
+ let mut eng = Engine::open(Arch::Arm, Mode::LITTLE_ENDIAN).unwrap();
+ let svc = eng.disasm_one(&[0x00, 0x00, 0x00, 0xef], 0x0).unwrap();
+ assert_eq!(svc.mnemonic, "svc");
+ }
+}
diff --git a/crates/ghidrust-decode/src/arch/arm/regs.rs b/crates/ghidrust-decode/src/arch/arm/regs.rs
new file mode 100644
index 0000000..99beb4f
--- /dev/null
+++ b/crates/ghidrust-decode/src/arch/arm/regs.rs
@@ -0,0 +1,66 @@
+use crate::reg::RegId;
+use crate::support::Arch;
+
+pub fn gpr(n: u32) -> &'static str {
+ match n & 0xf {
+ 0 => "r0",
+ 1 => "r1",
+ 2 => "r2",
+ 3 => "r3",
+ 4 => "r4",
+ 5 => "r5",
+ 6 => "r6",
+ 7 => "r7",
+ 8 => "r8",
+ 9 => "r9",
+ 10 => "r10",
+ 11 => "r11",
+ 12 => "r12",
+ 13 => "sp",
+ 14 => "lr",
+ 15 => "pc",
+ _ => "r0",
+ }
+}
+
+pub fn reg_id(n: u32) -> RegId {
+ RegId::tagged(Arch::Arm, (n & 0xf) as u16)
+}
+
+pub fn neon_d(n: u32) -> String {
+ format!("d{}", n & 0x1f)
+}
+
+pub fn neon_q(n: u32) -> String {
+ format!("q{}", n & 0xf)
+}
+
+pub fn psr_field(field: u32) -> &'static str {
+ match field {
+ 0b10000 => "c",
+ 0b01000 => "x",
+ 0b00100 => "s",
+ 0b00010 => "f",
+ 0b11111 => "cpsr",
+ 0b11110 => "spsr",
+ _ => "cpsr",
+ }
+}
+
+pub fn banked_reg(r: u32, mode: u32) -> String {
+ match (r, mode) {
+ (13, 0b10000) => "sp_usr".into(),
+ (14, 0b10000) => "lr_usr".into(),
+ (13, 0b10001) => "sp_fiq".into(),
+ (14, 0b10001) => "lr_fiq".into(),
+ (13, 0b10010) => "sp_irq".into(),
+ (14, 0b10010) => "lr_irq".into(),
+ (13, 0b10011) => "sp_svc".into(),
+ (14, 0b10011) => "lr_svc".into(),
+ (13, 0b10100) => "sp_abt".into(),
+ (14, 0b10100) => "lr_abt".into(),
+ (13, 0b10110) => "sp_und".into(),
+ (14, 0b10110) => "lr_und".into(),
+ _ => gpr(r).into(),
+ }
+}
diff --git a/crates/ghidrust-decode/src/arch/arm/thumb16.rs b/crates/ghidrust-decode/src/arch/arm/thumb16.rs
new file mode 100644
index 0000000..f835987
--- /dev/null
+++ b/crates/ghidrust-decode/src/arch/arm/thumb16.rs
@@ -0,0 +1,284 @@
+use super::regs::gpr;
+use super::util::{cond_suffix, fmt_imm_hex, sign_extend};
+use crate::error::{Error, Result};
+use crate::insn::Instruction;
+
+pub fn decode(hw: u16, bytes: &[u8], address: u64, be: bool) -> Result<Instruction> {
+ let fmt = (hw >> 12) & 0xf;
+ match fmt {
+ 0b0000..=0b0111 => decode_mov_shift(hw, bytes, address, be),
+ 0b1000 => decode_load_store_imm5(hw, bytes, address, be, false),
+ 0b1001 => decode_load_store_imm5(hw, bytes, address, be, true),
+ 0b1010 => decode_load_store_h(hw, bytes, address, be, false),
+ 0b1011 => decode_fmt1011(hw, bytes, address, be),
+ 0b1100 => decode_load_store_reg(hw, bytes, address, be, false),
+ 0b1101 => decode_load_store_reg(hw, bytes, address, be, true),
+ 0b1110 => decode_fmt1110(hw, bytes, address, be),
+ 0b1111 => decode_svc(hw, bytes, address, be),
+ _ => Err(Error::Decode(format!("unhandled T16 {hw:#06x}"))),
+ }
+}
+
+fn raw2(bytes: &[u8], be: bool) -> Vec<u8> {
+ if be {
+ vec![bytes[1], bytes[0]]
+ } else {
+ bytes[..2].to_vec()
+ }
+}
+
+fn decode_mov_shift(hw: u16, bytes: &[u8], address: u64, be: bool) -> Result<Instruction> {
+ let op = (hw >> 11) & 0x3;
+ let offset = (hw >> 6) & 0x1f;
+ let rs = (hw >> 3) & 0x7;
+ let rd = hw & 0x7;
+ let mnemonic = match op {
+ 0b00 => "lsls",
+ 0b01 => "lsrs",
+ 0b10 => "asrs",
+ _ => "movs",
+ };
+ let operands = if op == 0b11 {
+ format!("{}, {}", gpr(rs as u32), gpr(rd as u32))
+ } else {
+ format!("{}, {}, #{offset}", gpr(rs as u32), gpr(rd as u32))
+ };
+ Ok(Instruction::with_text(address, raw2(bytes, be), mnemonic, operands, 2))
+}
+
+fn decode_load_store_imm5(
+ hw: u16,
+ bytes: &[u8],
+ address: u64,
+ be: bool,
+ load: bool,
+) -> Result<Instruction> {
+ let imm = ((hw >> 6) & 0x1f) << 2;
+ let rb = (hw >> 3) & 0x7;
+ let rd = hw & 0x7;
+ let mnemonic = if load { "ldr" } else { "str" };
+ Ok(Instruction::with_text(
+ address,
+ raw2(bytes, be),
+ mnemonic,
+ format!("{}, [{}, #{imm}]", gpr(rd as u32), gpr(rb as u32)),
+ 2,
+ ))
+}
+
+fn decode_load_store_h(
+ hw: u16,
+ bytes: &[u8],
+ address: u64,
+ be: bool,
+ load: bool,
+) -> Result<Instruction> {
+ let imm = ((hw >> 6) & 0x1f) << 1;
+ let rb = (hw >> 3) & 0x7;
+ let rd = hw & 0x7;
+ let mnemonic = if load { "ldrh" } else { "strh" };
+ Ok(Instruction::with_text(
+ address,
+ raw2(bytes, be),
+ mnemonic,
+ format!("{}, [{}, #{imm}]", gpr(rd as u32), gpr(rb as u32)),
+ 2,
+ ))
+}
+
+fn decode_load_store_sp(
+ hw: u16,
+ bytes: &[u8],
+ address: u64,
+ be: bool,
+ load: bool,
+) -> Result<Instruction> {
+ let imm = ((hw >> 4) & 0xff) << 2;
+ let rd = hw & 0x7;
+ let mnemonic = if load { "ldr" } else { "str" };
+ Ok(Instruction::with_text(
+ address,
+ raw2(bytes, be),
+ mnemonic,
+ format!("{}, [sp, #{imm}]", gpr(rd as u32)),
+ 2,
+ ))
+}
+
+fn decode_add_sub(hw: u16, bytes: &[u8], address: u64, be: bool) -> Result<Instruction> {
+ let add = ((hw >> 9) & 1) != 0;
+ let imm = (hw >> 6) & 0x7;
+ let rn = (hw >> 3) & 0x7;
+ let rd = hw & 0x7;
+ let mnemonic = if add { "add" } else { "sub" };
+ Ok(Instruction::with_text(
+ address,
+ raw2(bytes, be),
+ mnemonic,
+ format!("{}, {}, #{imm}", gpr(rd as u32), gpr(rn as u32)),
+ 2,
+ ))
+}
+
+fn decode_fmt1011(hw: u16, bytes: &[u8], address: u64, be: bool) -> Result<Instruction> {
+ if (hw & 0x0600) == 0x0400 {
+ return decode_push_pop(hw, bytes, address, be);
+ }
+ if (hw & 0x0500) == 0x0000 {
+ return decode_misc(hw, bytes, address, be);
+ }
+ if (hw & 0x0900) == 0x0900 {
+ return decode_load_store_sp(hw, bytes, address, be, false);
+ }
+ if (hw & 0x0b00) == 0x0b00 {
+ return decode_load_store_sp(hw, bytes, address, be, true);
+ }
+ decode_add_sub(hw, bytes, address, be)
+}
+
+fn decode_fmt1110(hw: u16, bytes: &[u8], address: u64, be: bool) -> Result<Instruction> {
+ if (hw & 0x1000) == 0 {
+ return decode_branch(hw, bytes, address, be);
+ }
+ if (hw & 0x0d00) == 0x0800 {
+ return decode_add_sp_pc(hw, bytes, address, be);
+ }
+ decode_branch_cond(hw, bytes, address, be)
+}
+
+fn decode_push_pop(hw: u16, bytes: &[u8], address: u64, be: bool) -> Result<Instruction> {
+ let push = ((hw >> 11) & 1) == 0;
+ let lr = ((hw >> 8) & 1) != 0;
+ let pc = ((hw >> 8) & 1) != 0 && !push;
+ let mut regs = Vec::new();
+ for i in 0..8u32 {
+ if (hw >> i) & 1 != 0 {
+ regs.push(gpr(i));
+ }
+ }
+ if lr && push {
+ regs.push("lr");
+ }
+ if pc && !push {
+ regs.push("pc");
+ }
+ let mnemonic = if push { "push" } else { "pop" };
+ Ok(Instruction::with_text(
+ address,
+ raw2(bytes, be),
+ mnemonic,
+ format!("{{{}}}", regs.join(", ")),
+ 2,
+ ))
+}
+
+fn decode_misc(hw: u16, bytes: &[u8], address: u64, be: bool) -> Result<Instruction> {
+ let h1 = ((hw >> 7) & 1) != 0;
+ let h2 = ((hw >> 6) & 1) != 0;
+ let rd = (hw & 0x7) | if h1 { 8 } else { 0 };
+ let rm = ((hw >> 3) & 0x7) | if h2 { 8 } else { 0 };
+ let mnemonic = match (hw >> 9) & 0x3 {
+ 0b00 => "add",
+ 0b01 => "cmp",
+ 0b10 => "mov",
+ _ => "bx",
+ };
+ if mnemonic == "bx" {
+ return Ok(Instruction::with_text(
+ address,
+ raw2(bytes, be),
+ "bx",
+ gpr(rm as u32),
+ 2,
+ ));
+ }
+ Ok(Instruction::with_text(
+ address,
+ raw2(bytes, be),
+ mnemonic,
+ format!("{}, {}", gpr(rd as u32), gpr(rm as u32)),
+ 2,
+ ))
+}
+
+fn decode_branch_cond(hw: u16, bytes: &[u8], address: u64, be: bool) -> Result<Instruction> {
+ let cond = (hw >> 8) & 0xf;
+ let imm8 = hw & 0xff;
+ let offset = sign_extend((imm8 as u32) << 1, 9);
+ let target = (address as i64).wrapping_add(offset as i64) as u64;
+ let suffix = cond_suffix(cond as u32);
+ Ok(Instruction::with_text(
+ address,
+ raw2(bytes, be),
+ format!("b{suffix}"),
+ fmt_imm_hex(target as i64),
+ 2,
+ ))
+}
+
+fn decode_load_store_reg(
+ hw: u16,
+ bytes: &[u8],
+ address: u64,
+ be: bool,
+ load: bool,
+) -> Result<Instruction> {
+ let ro = (hw >> 6) & 0x7;
+ let rb = (hw >> 3) & 0x7;
+ let rd = hw & 0x7;
+ let mnemonic = if load { "ldr" } else { "str" };
+ Ok(Instruction::with_text(
+ address,
+ raw2(bytes, be),
+ mnemonic,
+ format!("{}, [{}, {}]", gpr(rd as u32), gpr(rb as u32), gpr(ro as u32)),
+ 2,
+ ))
+}
+
+fn decode_add_sp_pc(hw: u16, bytes: &[u8], address: u64, be: bool) -> Result<Instruction> {
+ let is_pc = ((hw >> 11) & 1) != 0;
+ let rd = (hw >> 8) & 0x7;
+ let imm = (hw & 0xff) << 2;
+ if is_pc {
+ let target = address.wrapping_add(4).wrapping_add(imm as u64) & !3;
+ return Ok(Instruction::with_text(
+ address,
+ raw2(bytes, be),
+ "adr",
+ format!("{}, {:#x}", gpr(rd as u32), target),
+ 2,
+ ));
+ }
+ Ok(Instruction::with_text(
+ address,
+ raw2(bytes, be),
+ "add",
+ format!("{}, sp, #{imm}", gpr(rd as u32)),
+ 2,
+ ))
+}
+
+fn decode_branch(hw: u16, bytes: &[u8], address: u64, be: bool) -> Result<Instruction> {
+ let imm11 = hw & 0x7ff;
+ let offset = sign_extend((imm11 as u32) << 1, 12);
+ let target = (address as i64).wrapping_add(offset as i64) as u64;
+ Ok(Instruction::with_text(
+ address,
+ raw2(bytes, be),
+ "b",
+ fmt_imm_hex(target as i64),
+ 2,
+ ))
+}
+
+fn decode_svc(hw: u16, bytes: &[u8], address: u64, be: bool) -> Result<Instruction> {
+ let imm = hw & 0xff;
+ Ok(Instruction::with_text(
+ address,
+ raw2(bytes, be),
+ "svc",
+ format!("#{imm}"),
+ 2,
+ ))
+}
diff --git a/crates/ghidrust-decode/src/arch/arm/thumb32.rs b/crates/ghidrust-decode/src/arch/arm/thumb32.rs
new file mode 100644
index 0000000..a8a84fc
--- /dev/null
+++ b/crates/ghidrust-decode/src/arch/arm/thumb32.rs
@@ -0,0 +1,166 @@
+use super::regs::gpr;
+use super::util::{arm_dp_mnemonic, fmt_imm_hex, fmt_shift_reg, sign_extend};
+use crate::error::{Error, Result};
+use crate::insn::Instruction;
+
+pub fn decode(bytes: &[u8], address: u64, big_endian: bool) -> Result<Instruction> {
+ if bytes.len() < 4 {
+ return Err(Error::Decode("truncated Thumb32 instruction".into()));
+ }
+ let hw1 = super::util::read_u16_le(bytes, big_endian)?;
+ let hw2 = super::util::read_u16_le(&bytes[2..], big_endian)?;
+ let raw = bytes[..4].to_vec();
+ let op1 = (hw1 >> 11) & 0x3;
+ let _op2 = (hw1 >> 4) & 0x7f;
+
+ // 32-bit conditional branch: 11110 S cond imm6 10 J1 J2 imm11
+ if op1 == 0b10 && (hw1 & 0x1000) == 0 && (hw2 & 0x8000) == 0 {
+ return decode_branch(hw1, hw2, address, raw);
+ }
+ // Load/store multiple / dual
+ if op1 == 0b11 && (hw1 & 0x1200) == 0x0000 {
+ return decode_load_store_dual(hw1, hw2, address, raw);
+ }
+ // Data processing (modified immediate)
+ if op1 == 0b11 && (hw1 & 0x1a00) == 0x0800 {
+ return decode_dp_imm(hw1, hw2, address, raw);
+ }
+ // Data processing (register)
+ if op1 == 0b11 && (hw1 & 0x1e00) == 0x0a00 {
+ return decode_dp_reg(hw1, hw2, address, raw);
+ }
+ // Load/store single
+ if op1 == 0b11 && (hw1 & 0x1200) == 0x1000 {
+ return decode_load_store_single(hw1, hw2, address, raw);
+ }
+ // BL / BLX immediate: 11110.. 11 ..
+ if (hw1 & 0xf800) == 0xf000 && (hw2 & 0xd001) == 0xd000 {
+ return decode_bl(hw1, hw2, address, raw);
+ }
+ Err(Error::Decode(format!("unhandled T32 {hw1:#06x} {hw2:#06x}")))
+}
+
+fn decode_branch(hw1: u16, hw2: u16, address: u64, raw: Vec<u8>) -> Result<Instruction> {
+ let s = ((hw1 >> 10) & 1) != 0;
+ let cond = (hw1 >> 6) & 0xf;
+ let j1 = ((hw2 >> 13) & 1) != 0;
+ let j2 = ((hw2 >> 11) & 1) != 0;
+ let imm6 = (hw1 & 0x3f) as u32;
+ let imm11 = hw2 & 0x7ff;
+ let i1 = !(j1 ^ s);
+ let i2 = !(j2 ^ s);
+ let mut imm = (imm6 << 12) | (i1 as u32) << 22 | (i2 as u32) << 21 | (imm11 as u32) << 1;
+ if s {
+ imm |= 1 << 23;
+ }
+ let offset = sign_extend(imm, 25);
+ let target = (address as i64).wrapping_add(offset as i64) as u64;
+ let suffix = super::util::cond_suffix(cond as u32);
+ let mnemonic = format!("b{suffix}");
+ Ok(Instruction::with_text(
+ address,
+ raw,
+ mnemonic,
+ fmt_imm_hex(target as i64),
+ 4,
+ ))
+}
+
+fn decode_bl(hw1: u16, hw2: u16, address: u64, raw: Vec<u8>) -> Result<Instruction> {
+ let s = ((hw1 >> 10) & 1) != 0;
+ let j1 = ((hw2 >> 13) & 1) != 0;
+ let j2 = ((hw2 >> 11) & 1) != 0;
+ let imm10 = hw1 & 0x3ff;
+ let imm11 = hw2 & 0x7ff;
+ let i1 = !(j1 ^ s);
+ let i2 = !(j2 ^ s);
+ let mut imm = (imm10 as u32) << 12 | (i1 as u32) << 22 | (i2 as u32) << 21 | (imm11 as u32) << 1;
+ if s {
+ imm |= 1 << 23;
+ }
+ let offset = sign_extend(imm, 25);
+ let target = (address as i64).wrapping_add(offset as i64) as u64;
+ let x = ((hw1 >> 12) & 1) != 0;
+ let mnemonic = if x { "blx" } else { "bl" };
+ Ok(Instruction::with_text(
+ address,
+ raw,
+ mnemonic,
+ fmt_imm_hex(target as i64),
+ 4,
+ ))
+}
+
+fn decode_dp_imm(hw1: u16, hw2: u16, address: u64, raw: Vec<u8>) -> Result<Instruction> {
+ let opcode = (hw1 >> 5) & 0xf;
+ let s = ((hw1 >> 4) & 1) != 0;
+ let rn = (hw1 & 0xf) as u32;
+ let rd = (hw2 >> 8) & 0xf;
+ let imm = thumb32_imm12(hw1, hw2);
+ let base = arm_dp_mnemonic(opcode as u32, s);
+ let operands = if opcode == 0b1101 && rn == 15 {
+ format!("{}, #{:#x}", gpr(rd as u32), imm)
+ } else if opcode == 0b1111 && rn == 15 {
+ format!("{}, #{:#x}", gpr(rd as u32), imm)
+ } else {
+ format!("{}, {}, #{:#x}", gpr(rd as u32), gpr(rn), imm)
+ };
+ Ok(Instruction::with_text(address, raw, base, operands, 4))
+}
+
+fn decode_dp_reg(hw1: u16, hw2: u16, address: u64, raw: Vec<u8>) -> Result<Instruction> {
+ let opcode = (hw1 >> 5) & 0xf;
+ let s = ((hw1 >> 4) & 1) != 0;
+ let rn = (hw1 & 0xf) as u32;
+ let rd = (hw2 >> 8) & 0xf;
+ let rm = hw2 & 0xf;
+ let shift_type = (hw2 >> 4) & 0x3;
+ let shift_imm = ((hw2 >> 6) & 0x3) << 4 | ((hw2 >> 12) & 0x7) << 2 | ((hw2 >> 14) & 0x3);
+ let base = arm_dp_mnemonic(opcode as u32, s);
+ let shift_str = fmt_shift_reg(shift_type as u32, shift_imm as u32);
+ let operands = format!(
+ "{}, {}, {}{}",
+ gpr(rd as u32),
+ gpr(rn),
+ gpr(rm as u32),
+ shift_str
+ );
+ Ok(Instruction::with_text(address, raw, base, operands, 4))
+}
+
+fn decode_load_store_single(hw1: u16, hw2: u16, address: u64, raw: Vec<u8>) -> Result<Instruction> {
+ let l = ((hw1 >> 4) & 1) != 0;
+ let rn = (hw1 & 0xf) as u32;
+ let rt = (hw2 >> 12) & 0xf;
+ let imm12 = ((hw1 & 0xff) as u32) << 4 | ((hw2 >> 4) & 0xf) as u32;
+ let mnemonic = if l { "ldr" } else { "str" };
+ Ok(Instruction::with_text(
+ address,
+ raw,
+ mnemonic,
+ format!("{}, [{}, #{imm12}]", gpr(rt as u32), gpr(rn)),
+ 4,
+ ))
+}
+
+fn decode_load_store_dual(hw1: u16, hw2: u16, address: u64, raw: Vec<u8>) -> Result<Instruction> {
+ let l = ((hw1 >> 4) & 1) != 0;
+ let rn = (hw1 & 0xf) as u32;
+ let rt = (hw2 >> 12) & 0xf;
+ let rt2 = (hw2 >> 8) & 0xf;
+ let mnemonic = if l { "ldrd" } else { "strd" };
+ Ok(Instruction::with_text(
+ address,
+ raw,
+ mnemonic,
+ format!("{}, {}, [{}]", gpr(rt as u32), gpr(rt2 as u32), gpr(rn)),
+ 4,
+ ))
+}
+
+fn thumb32_imm12(hw1: u16, hw2: u16) -> u32 {
+ let i = ((hw1 >> 10) & 1) as u32;
+ let imm3 = ((hw2 >> 12) & 0x7) as u32;
+ let imm8 = (hw2 & 0xff) as u32;
+ imm8 | imm3 << 8 | i << 11
+}
diff --git a/crates/ghidrust-decode/src/arch/arm/util.rs b/crates/ghidrust-decode/src/arch/arm/util.rs
new file mode 100644
index 0000000..aceeaf8
--- /dev/null
+++ b/crates/ghidrust-decode/src/arch/arm/util.rs
@@ -0,0 +1,126 @@
+use crate::error::{Error, Result};
+
+pub fn read_u16_le(bytes: &[u8], big_endian: bool) -> Result<u16> {
+ if bytes.len() < 2 {
+ return Err(Error::Decode("truncated halfword".into()));
+ }
+ Ok(if big_endian {
+ u16::from_be_bytes([bytes[0], bytes[1]])
+ } else {
+ u16::from_le_bytes([bytes[0], bytes[1]])
+ })
+}
+
+pub fn read_u32_le(bytes: &[u8], big_endian: bool) -> Result<u32> {
+ if bytes.len() < 4 {
+ return Err(Error::Decode("truncated word".into()));
+ }
+ Ok(if big_endian {
+ u32::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])
+ } else {
+ u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])
+ })
+}
+
+pub fn sign_extend(value: u32, bits: u32) -> i32 {
+ let shift = 32 - bits;
+ ((value << shift) as i32) >> shift
+}
+
+pub fn sign_extend64(value: u64, bits: u32) -> i64 {
+ let shift = 64 - bits;
+ ((value << shift) as i64) >> shift
+}
+
+pub fn fmt_imm_hex(v: i64) -> String {
+ if v < 0 {
+ format!("-{:#x}", -v)
+ } else {
+ format!("{v:#x}")
+ }
+}
+
+pub fn fmt_shift_imm(shift: u32) -> String {
+ if shift == 0 {
+ String::new()
+ } else {
+ format!(", lsl #{shift}")
+ }
+}
+
+pub fn fmt_shift_reg(shift_type: u32, amount: u32) -> String {
+ let kind = match shift_type {
+ 0b00 => "lsl",
+ 0b01 => "lsr",
+ 0b10 => "asr",
+ 0b11 => "ror",
+ _ => "lsl",
+ };
+ if amount == 0 && shift_type == 0b00 {
+ String::new()
+ } else {
+ format!(", {kind} #{amount}")
+ }
+}
+
+pub fn rotate_right_imm8(imm: u32) -> u32 {
+ let rot = (imm >> 8) * 2;
+ let val = imm & 0xff;
+ if rot == 0 {
+ val
+ } else {
+ (val >> rot) | (val << (32 - rot))
+ }
+}
+
+pub fn arm_dp_imm(imm12: u32) -> u32 {
+ rotate_right_imm8(imm12)
+}
+
+pub fn cond_suffix(cond: u32) -> &'static str {
+ match cond {
+ 0x0 => "eq",
+ 0x1 => "ne",
+ 0x2 => "cs",
+ 0x3 => "cc",
+ 0x4 => "mi",
+ 0x5 => "pl",
+ 0x6 => "vs",
+ 0x7 => "vc",
+ 0x8 => "hi",
+ 0x9 => "ls",
+ 0xa => "ge",
+ 0xb => "lt",
+ 0xc => "gt",
+ 0xd => "le",
+ 0xe => "",
+ 0xf => "",
+ _ => "",
+ }
+}
+
+pub fn arm_dp_mnemonic(opcode: u32, s: bool) -> &'static str {
+ match opcode {
+ 0b0000 => if s { "and" } else { "and" },
+ 0b0001 => "eor",
+ 0b0010 => "sub",
+ 0b0011 => "rsb",
+ 0b0100 => "add",
+ 0b0101 => "adc",
+ 0b0110 => "sbc",
+ 0b0111 => "rsc",
+ 0b1000 => "tst",
+ 0b1001 => "teq",
+ 0b1010 => "cmp",
+ 0b1011 => "cmn",
+ 0b1100 => "orr",
+ 0b1101 => "mov",
+ 0b1110 => "bic",
+ 0b1111 => "mvn",
+ _ => "and",
+ }
+}
+
+pub fn is_dp_compare(opcode: u32) -> bool {
+ matches!(opcode, 0b1000..=0b1011)
+}
diff --git a/crates/ghidrust-decode/src/arch/bpf/mod.rs b/crates/ghidrust-decode/src/arch/bpf/mod.rs
new file mode 100644
index 0000000..56d2e86
--- /dev/null
+++ b/crates/ghidrust-decode/src/arch/bpf/mod.rs
@@ -0,0 +1,503 @@
+//! Hand-rolled classic BPF and eBPF decoder.
+
+mod regs;
+
+use crate::arch::ArchDecode;
+use crate::error::{Error, Result};
+use crate::group::GroupId;
+use crate::insn::{InsnDetail, InsnId, Instruction};
+use crate::names;
+use crate::option::EngineOptions;
+use crate::support::{Arch, Mode};
+
+pub use regs::reg_name;
+
+pub struct BpfDecoder {
+ mode: Mode,
+}
+
+const BPF_CLASS_LD: u16 = 0x00;
+const BPF_CLASS_LDX: u16 = 0x01;
+const BPF_CLASS_ST: u16 = 0x02;
+const BPF_CLASS_STX: u16 = 0x03;
+const BPF_CLASS_ALU: u16 = 0x04;
+const BPF_CLASS_JMP: u16 = 0x05;
+const BPF_CLASS_RET: u16 = 0x06;
+const BPF_CLASS_MISC: u16 = 0x07;
+
+const BPF_SIZE_W: u16 = 0x00;
+const BPF_SIZE_H: u16 = 0x08;
+const BPF_SIZE_B: u16 = 0x10;
+const BPF_SIZE_DW: u16 = 0x18;
+
+const BPF_MODE_IMM: u16 = 0x00;
+const BPF_MODE_ABS: u16 = 0x20;
+const BPF_MODE_IND: u16 = 0x40;
+const BPF_MODE_MEM: u16 = 0x60;
+const BPF_MODE_LEN: u16 = 0x80;
+const BPF_MODE_MSH: u16 = 0xa0;
+
+const BPF_SRC_K: u16 = 0x00;
+const BPF_SRC_X: u16 = 0x08;
+
+const BPF_ALU_ADD: u16 = 0x00;
+const BPF_ALU_SUB: u16 = 0x10;
+const BPF_ALU_MUL: u16 = 0x20;
+const BPF_ALU_DIV: u16 = 0x30;
+const BPF_ALU_OR: u16 = 0x40;
+const BPF_ALU_AND: u16 = 0x50;
+const BPF_ALU_LSH: u16 = 0x60;
+const BPF_ALU_RSH: u16 = 0x70;
+const BPF_ALU_NEG: u16 = 0x80;
+const BPF_ALU_MOD: u16 = 0x90;
+const BPF_ALU_XOR: u16 = 0xa0;
+
+const BPF_JUMP_JA: u16 = 0x00;
+const BPF_JUMP_JEQ: u16 = 0x10;
+const BPF_JUMP_JGT: u16 = 0x20;
+const BPF_JUMP_JGE: u16 = 0x30;
+const BPF_JUMP_JSET: u16 = 0x40;
+
+const BPF_MISCOP_TAX: u16 = 0x00;
+const BPF_MISCOP_TXA: u16 = 0x80;
+
+const EBPF_ALU64: u8 = 0x07;
+const EBPF_JMP32: u8 = 0x06;
+const EBPF_LDDW: u8 = 0x18;
+
+fn class(op: u16) -> u16 {
+ op & 0x07
+}
+fn size(op: u16) -> u16 {
+ op & 0x18
+}
+fn mode(op: u16) -> u16 {
+ op & 0xe0
+}
+fn alu_op(op: u16) -> u16 {
+ op & 0xf0
+}
+fn jmp_op(op: u16) -> u16 {
+ op & 0xf0
+}
+fn src_k(op: u16) -> bool {
+ op & BPF_SRC_X == 0
+}
+
+pub(crate) fn decode_raw(bytes: &[u8], address: u64, mode: Mode) -> Result<Instruction> {
+ if mode.intersects(Mode::BPF_EXTENDED) {
+ decode_ebpf(bytes, address)
+ } else {
+ decode_classic(bytes, address)
+ }
+}
+
+fn decode_classic(bytes: &[u8], address: u64) -> Result<Instruction> {
+ if bytes.len() < 8 {
+ return Err(Error::Decode("truncated classic bpf instruction".into()));
+ }
+ let op = u16::from_le_bytes([bytes[0], bytes[1]]);
+ let jt = bytes[2];
+ let jf = bytes[3];
+ let k = u32::from_le_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]);
+ let (mnemonic, operands) = classic_mnemonic(op, jt, jf, k)?;
+ Ok(Instruction::with_text(
+ address,
+ bytes[..8].to_vec(),
+ mnemonic,
+ operands,
+ 8,
+ ))
+}
+
+fn classic_mnemonic(op: u16, jt: u8, jf: u8, k: u32) -> Result<(String, String)> {
+ match class(op) {
+ BPF_CLASS_LD => classic_ld(op, k),
+ BPF_CLASS_LDX => classic_ldx(op, k),
+ BPF_CLASS_ST | BPF_CLASS_STX => Ok((
+ if class(op) == BPF_CLASS_ST {
+ "st".into()
+ } else {
+ "stx".into()
+ },
+ format!("M[{k}]"),
+ )),
+ BPF_CLASS_ALU => {
+ let name = match alu_op(op) {
+ BPF_ALU_ADD => "add",
+ BPF_ALU_SUB => "sub",
+ BPF_ALU_MUL => "mul",
+ BPF_ALU_DIV => "div",
+ BPF_ALU_OR => "or",
+ BPF_ALU_AND => "and",
+ BPF_ALU_LSH => "lsh",
+ BPF_ALU_RSH => "rsh",
+ BPF_ALU_NEG => "neg",
+ BPF_ALU_MOD => "mod",
+ BPF_ALU_XOR => "xor",
+ _ => return Err(Error::Decode("invalid classic bpf alu".into())),
+ };
+ if alu_op(op) == BPF_ALU_NEG {
+ Ok((name.into(), String::new()))
+ } else if src_k(op) {
+ Ok((name.into(), format!("#{k:#x}")))
+ } else {
+ Ok((name.into(), "x".into()))
+ }
+ }
+ BPF_CLASS_JMP => {
+ let name = match jmp_op(op) {
+ BPF_JUMP_JA => return Ok(("ja".into(), format!("#{k}"))),
+ BPF_JUMP_JEQ => "jeq",
+ BPF_JUMP_JGT => "jgt",
+ BPF_JUMP_JGE => "jge",
+ BPF_JUMP_JSET => "jset",
+ _ => return Err(Error::Decode("invalid classic bpf jump".into())),
+ };
+ let rhs = if src_k(op) {
+ format!("#{k}")
+ } else {
+ "x".into()
+ };
+ Ok((name.into(), format!("{rhs}, #{jt}, #{jf}")))
+ }
+ BPF_CLASS_RET => {
+ if op & 0x18 == BPF_SRC_K {
+ Ok(("ret".into(), format!("#{k}")))
+ } else if op & 0x18 == BPF_SRC_X {
+ Ok(("ret".into(), "x".into()))
+ } else {
+ Ok(("ret".into(), "a".into()))
+ }
+ }
+ BPF_CLASS_MISC => {
+ if op & 0xf8 == BPF_MISCOP_TAX {
+ Ok(("tax".into(), String::new()))
+ } else if op & 0xf8 == BPF_MISCOP_TXA {
+ Ok(("txa".into(), String::new()))
+ } else {
+ Err(Error::Decode("invalid classic bpf misc".into()))
+ }
+ }
+ _ => Err(Error::Decode("invalid classic bpf class".into())),
+ }
+}
+
+fn classic_ld(op: u16, k: u32) -> Result<(String, String)> {
+ let sz = match size(op) {
+ BPF_SIZE_W => "w",
+ BPF_SIZE_H => "h",
+ BPF_SIZE_B => "b",
+ _ => return Err(Error::Decode("invalid classic bpf ld size".into())),
+ };
+ match mode(op) {
+ BPF_MODE_IMM => Ok((format!("ld{sz}"), format!("#{k:#x}"))),
+ BPF_MODE_LEN => Ok(("ld".into(), "len".into())),
+ BPF_MODE_MEM => Ok(("ld".into(), format!("M[{k}]"))),
+ BPF_MODE_ABS => Ok((format!("ldabs{sz}"), format!("[{k}]"))),
+ BPF_MODE_IND => Ok((format!("ldind{sz}"), format!("x+{k}"))),
+ _ => Err(Error::Decode("invalid classic bpf ld mode".into())),
+ }
+}
+
+fn classic_ldx(op: u16, k: u32) -> Result<(String, String)> {
+ match mode(op) {
+ BPF_MODE_IMM => Ok(("ldx".into(), format!("#{k}"))),
+ BPF_MODE_LEN => Ok(("ldx".into(), "len".into())),
+ BPF_MODE_MEM => Ok(("ldx".into(), format!("M[{k}]"))),
+ BPF_MODE_MSH => Ok(("ldx".into(), format!("4*([{k}]&0xf)"))),
+ _ => Err(Error::Decode("invalid classic bpf ldx mode".into())),
+ }
+}
+
+fn decode_ebpf(bytes: &[u8], address: u64) -> Result<Instruction> {
+ if bytes.len() < 8 {
+ return Err(Error::Decode("truncated ebpf instruction".into()));
+ }
+ let op = bytes[0];
+ let dst = bytes[1] & 0x0f;
+ let src = (bytes[1] >> 4) & 0x0f;
+ let off = i16::from_le_bytes([bytes[2], bytes[3]]);
+ let imm = i32::from_le_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]);
+
+ if op == EBPF_LDDW {
+ if bytes.len() < 16 {
+ return Err(Error::Decode("truncated ebpf lddw".into()));
+ }
+ let imm_lo = u32::from_le_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]);
+ let imm_hi = u32::from_le_bytes([bytes[12], bytes[13], bytes[14], bytes[15]]);
+ let full = u64::from(imm_lo) | (u64::from(imm_hi) << 32);
+ return Ok(Instruction::with_text(
+ address,
+ bytes[..16].to_vec(),
+ "lddw",
+ format!("r{dst}, #{full}"),
+ 16,
+ ));
+ }
+
+ let (mnemonic, operands) = ebpf_mnemonic(op, dst, src, off, imm)?;
+ Ok(Instruction::with_text(
+ address,
+ bytes[..8].to_vec(),
+ mnemonic,
+ operands,
+ 8,
+ ))
+}
+
+fn ebpf_mnemonic(
+ op: u8,
+ dst: u8,
+ src: u8,
+ off: i16,
+ imm: i32,
+) -> Result<(String, String)> {
+ let cls = op & 0x07;
+ match cls {
+ 0x00 | 0x01 => {
+ // LD / LDX
+ let sz = match op & 0x18 {
+ 0x00 => "w",
+ 0x08 => "h",
+ 0x10 => "b",
+ 0x18 => "dw",
+ _ => "w",
+ };
+ let m = op & 0xe0;
+ if cls == 0x00 {
+ if m == 0x00 && sz == "dw" {
+ return Err(Error::Decode("lddw must be 16 bytes".into()));
+ }
+ if m == 0x20 {
+ return Ok((format!("ldabs{sz}"), format!("[{imm}]")));
+ }
+ if m == 0x40 {
+ return Ok((format!("ldind{sz}"), format!("r{src}")));
+ }
+ } else if m == 0x60 {
+ return Ok((
+ format!("ldx{sz}"),
+ format!("r{dst}, [r{src}+{off}]"),
+ ));
+ }
+ Err(Error::Decode("invalid ebpf load".into()))
+ }
+ 0x02 | 0x03 => {
+ let sz = match op & 0x18 {
+ 0x00 => "w",
+ 0x08 => "h",
+ 0x10 => "b",
+ 0x18 => "dw",
+ _ => "w",
+ };
+ if (op & 0xe0) == 0x60 {
+ if cls == 0x02 {
+ Ok((
+ format!("st{sz}"),
+ format!("[r{dst}+{off}], #{imm}"),
+ ))
+ } else {
+ Ok((
+ format!("stx{sz}"),
+ format!("[r{dst}+{off}], r{src}"),
+ ))
+ }
+ } else {
+ Err(Error::Decode("invalid ebpf store".into()))
+ }
+ }
+ 0x04 | EBPF_ALU64 => {
+ let opn = match (op >> 4) & 0x0f {
+ 0x0 => "add",
+ 0x1 => "sub",
+ 0x2 => "mul",
+ 0x3 => "div",
+ 0x4 => "or",
+ 0x5 => "and",
+ 0x6 => "lsh",
+ 0x7 => "rsh",
+ 0x8 => "neg",
+ 0x9 => "mod",
+ 0xa => "xor",
+ 0xb => "mov",
+ 0xc => "arsh",
+ _ => return Err(Error::Decode("invalid ebpf alu".into())),
+ };
+ let suffix = if cls == EBPF_ALU64 { "64" } else { "" };
+ if opn == "neg" {
+ Ok((format!("{opn}{suffix}"), format!("r{dst}")))
+ } else if op & 0x08 == 0 {
+ Ok((format!("{opn}{suffix}"), format!("r{dst}, #{imm}")))
+ } else {
+ Ok((format!("{opn}{suffix}"), format!("r{dst}, r{src}")))
+ }
+ }
+ 0x05 | EBPF_JMP32 => {
+ let opn = match (op >> 4) & 0x0f {
+ 0x0 => "ja",
+ 0x1 => "jeq",
+ 0x2 => "jgt",
+ 0x3 => "jge",
+ 0x4 => "jset",
+ 0x5 => "jne",
+ 0x6 => "jsgt",
+ 0x7 => "jsge",
+ 0x8 => "call",
+ 0x9 => "exit",
+ 0xa => "jlt",
+ 0xb => "jle",
+ 0xc => "jslt",
+ 0xd => "jsle",
+ _ => return Err(Error::Decode("invalid ebpf jump".into())),
+ };
+ match opn {
+ "ja" => Ok((opn.into(), format!("{off}"))),
+ "call" => Ok((opn.into(), format!("#{imm}"))),
+ "exit" => Ok((opn.into(), String::new())),
+ _ => {
+ let suffix = if cls == EBPF_JMP32 { "32" } else { "" };
+ if op & 0x08 == 0 {
+ Ok((
+ format!("{opn}{suffix}"),
+ format!("r{dst}, #{imm}, {off}"),
+ ))
+ } else {
+ Ok((
+ format!("{opn}{suffix}"),
+ format!("r{dst}, r{src}, {off}"),
+ ))
+ }
+ }
+ }
+ }
+ _ => Err(Error::Decode("invalid ebpf class".into())),
+ }
+}
+
+impl ArchDecode for BpfDecoder {
+ fn arch(&self) -> Arch {
+ Arch::Bpf
+ }
+
+ fn open(mode: Mode) -> Result<Self> {
+ if !mode.is_valid_for(Arch::Bpf) {
+ return Err(Error::Mode(format!("invalid bpf mode {:#x}", mode.bits())));
+ }
+ Ok(Self { mode })
+ }
+
+ fn decode_one(&self, bytes: &[u8], address: u64, opts: &EngineOptions) -> Result<Instruction> {
+ let mut insn = decode_raw(bytes, address, self.mode)?;
+ insn.id = names::insn_id_for_mnemonic(Arch::Bpf, &insn.mnemonic);
+ if opts.detail {
+ insn.detail = Some(InsnDetail {
+ groups: groups_for_mnemonic(&insn.mnemonic),
+ ..InsnDetail::default()
+ });
+ }
+ Ok(insn)
+ }
+}
+
+fn groups_for_mnemonic(mnemonic: &str) -> Vec<GroupId> {
+ if mnemonic.starts_with("ld") || mnemonic.starts_with("ldx") {
+ vec![GroupId::Arch(1)]
+ } else if mnemonic.starts_with("st") {
+ vec![GroupId::Arch(2)]
+ } else if mnemonic.starts_with('j') || mnemonic == "call" || mnemonic == "exit" {
+ vec![GroupId::Jump]
+ } else if mnemonic == "ret" {
+ vec![GroupId::Ret]
+ } else {
+ vec![GroupId::Arch(3)] // alu
+ }
+}
+
+pub fn insn_name(id: InsnId) -> Option<&'static str> {
+ match id.raw() {
+ 1 => Some("lddw"),
+ 2 => Some("add"),
+ 3 => Some("add64"),
+ 4 => Some("call"),
+ 5 => Some("exit"),
+ 6 => Some("ja"),
+ 7 => Some("ret"),
+ 8 => Some("tax"),
+ _ => None,
+ }
+}
+
+pub fn group_name(group: GroupId) -> Option<&'static str> {
+ match group {
+ GroupId::Jump => Some("jump"),
+ GroupId::Ret => Some("ret"),
+ GroupId::Arch(1) => Some("load"),
+ GroupId::Arch(2) => Some("store"),
+ GroupId::Arch(3) => Some("alu"),
+ _ => None,
+ }
+}
+
+pub fn insn_id_for_mnemonic(mnemonic: &str) -> InsnId {
+ let id = match mnemonic {
+ "lddw" => 1,
+ "add" => 2,
+ "add64" => 3,
+ "call" => 4,
+ "exit" => 5,
+ "ja" => 6,
+ "ret" => 7,
+ "tax" => 8,
+ m if m.starts_with("add") => 2,
+ m if m.starts_with("j") => 6,
+ _ => 0,
+ };
+ InsnId(id)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::option::EngineOptions;
+
+ #[test]
+ fn classic_bpf_ret_k() {
+ let dec = BpfDecoder::open(Mode::LITTLE_ENDIAN).unwrap();
+ // ret #0x0
+ let bytes = [0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00];
+ let insn = dec.decode_one(&bytes, 0, &EngineOptions::default()).unwrap();
+ assert_eq!(insn.mnemonic, "ret");
+ assert_eq!(insn.length, 8);
+ }
+
+ #[test]
+ fn classic_bpf_ld_imm() {
+ let dec = BpfDecoder::open(Mode::LITTLE_ENDIAN).unwrap();
+ // ld #0x12345678 (BPF_LD|BPF_W|BPF_IMM)
+ let bytes = [0x00, 0x00, 0x00, 0x00, 0x78, 0x56, 0x34, 0x12];
+ let insn = dec.decode_one(&bytes, 0, &EngineOptions::default()).unwrap();
+ assert_eq!(insn.mnemonic, "ldw");
+ assert!(insn.operands.contains("0x12345678"));
+ }
+
+ #[test]
+ fn ebpf_add64_and_lddw() {
+ let dec = BpfDecoder::open(Mode::BPF_EXTENDED).unwrap();
+ // add64 r1, #1 => op=0x07|0x04=0x47? ALU64|ADD|K = 0x07 | (0<<4) | 0 = 0x07 with imm
+ // bpf: 07 11 00 00 01 00 00 00 (add64 r1, 1)
+ let add = [0x07, 0x01, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00];
+ let insn = dec.decode_one(&add, 0, &EngineOptions::default()).unwrap();
+ assert_eq!(insn.mnemonic, "add64");
+ assert_eq!(insn.length, 8);
+
+ let mut lddw = [0u8; 16];
+ lddw[0] = 0x18;
+ lddw[1] = 0x01;
+ lddw[4..8].copy_from_slice(&0x00112233u32.to_le_bytes());
+ lddw[12..16].copy_from_slice(&0x44556677u32.to_le_bytes());
+ let wide = dec.decode_one(&lddw, 0, &EngineOptions::default()).unwrap();
+ assert_eq!(wide.mnemonic, "lddw");
+ assert_eq!(wide.length, 16);
+ }
+}
diff --git a/crates/ghidrust-decode/src/arch/bpf/regs.rs b/crates/ghidrust-decode/src/arch/bpf/regs.rs
new file mode 100644
index 0000000..9fa0e33
--- /dev/null
+++ b/crates/ghidrust-decode/src/arch/bpf/regs.rs
@@ -0,0 +1,22 @@
+use crate::reg::RegId;
+
+pub fn reg_name(reg: RegId) -> Option<&'static str> {
+ match reg.index() {
+ 0 => Some("a"),
+ 1..=10 => Some(match reg.index() {
+ 1 => "r0",
+ 2 => "r1",
+ 3 => "r2",
+ 4 => "r3",
+ 5 => "r4",
+ 6 => "r5",
+ 7 => "r6",
+ 8 => "r7",
+ 9 => "r8",
+ 10 => "r9",
+ _ => "r10",
+ }),
+ 11 => Some("x"),
+ _ => None,
+ }
+}
diff --git a/crates/ghidrust-decode/src/arch/evm/mod.rs b/crates/ghidrust-decode/src/arch/evm/mod.rs
new file mode 100644
index 0000000..eb590c4
--- /dev/null
+++ b/crates/ghidrust-decode/src/arch/evm/mod.rs
@@ -0,0 +1,341 @@
+//! Hand-rolled Ethereum VM (EVM) opcode decoder.
+
+use crate::arch::ArchDecode;
+use crate::error::{Error, Result};
+use crate::group::GroupId;
+use crate::insn::{InsnDetail, InsnId, Instruction};
+use crate::names;
+use crate::option::EngineOptions;
+use crate::support::{Arch, Mode};
+
+pub struct EvmDecoder {
+ _mode: Mode,
+}
+
+const OPCODE_MNEMONIC: [&str; 256] = {
+ let mut table = ["invalid"; 256];
+ table[0x00] = "stop";
+ table[0x01] = "add";
+ table[0x02] = "mul";
+ table[0x03] = "sub";
+ table[0x04] = "div";
+ table[0x05] = "sdiv";
+ table[0x06] = "mod";
+ table[0x07] = "smod";
+ table[0x08] = "addmod";
+ table[0x09] = "mulmod";
+ table[0x0a] = "exp";
+ table[0x0b] = "signextend";
+ table[0x10] = "lt";
+ table[0x11] = "gt";
+ table[0x12] = "slt";
+ table[0x13] = "sgt";
+ table[0x14] = "eq";
+ table[0x15] = "iszero";
+ table[0x16] = "and";
+ table[0x17] = "or";
+ table[0x18] = "xor";
+ table[0x19] = "not";
+ table[0x1a] = "byte";
+ table[0x1b] = "shl";
+ table[0x1c] = "shr";
+ table[0x1d] = "sar";
+ table[0x20] = "sha3";
+ table[0x30] = "address";
+ table[0x31] = "balance";
+ table[0x32] = "origin";
+ table[0x33] = "caller";
+ table[0x34] = "callvalue";
+ table[0x35] = "calldataload";
+ table[0x36] = "calldatasize";
+ table[0x37] = "calldatacopy";
+ table[0x38] = "codesize";
+ table[0x39] = "codecopy";
+ table[0x3a] = "gasprice";
+ table[0x3b] = "extcodesize";
+ table[0x3c] = "extcodecopy";
+ table[0x3d] = "returndatasize";
+ table[0x3e] = "returndatacopy";
+ table[0x40] = "blockhash";
+ table[0x41] = "coinbase";
+ table[0x42] = "timestamp";
+ table[0x43] = "number";
+ table[0x44] = "difficulty";
+ table[0x45] = "gaslimit";
+ table[0x46] = "chainid";
+ table[0x47] = "selfbalance";
+ table[0x48] = "basefee";
+ table[0x49] = "blobhash";
+ table[0x4a] = "blobbasefee";
+ table[0x50] = "pop";
+ table[0x51] = "mload";
+ table[0x52] = "mstore";
+ table[0x53] = "mstore8";
+ table[0x54] = "sload";
+ table[0x55] = "sstore";
+ table[0x56] = "jump";
+ table[0x57] = "jumpi";
+ table[0x58] = "pc";
+ table[0x59] = "msize";
+ table[0x5a] = "gas";
+ table[0x5b] = "jumpdest";
+ table[0x5c] = "tload";
+ table[0x5d] = "tstore";
+ table[0x5e] = "mcopy";
+ table[0x5f] = "push0";
+ let mut op = 0x60u8;
+ while op <= 0x7f {
+ table[op as usize] = match op - 0x60 + 1 {
+ 1 => "push1",
+ 2 => "push2",
+ 3 => "push3",
+ 4 => "push4",
+ 5 => "push5",
+ 6 => "push6",
+ 7 => "push7",
+ 8 => "push8",
+ 9 => "push9",
+ 10 => "push10",
+ 11 => "push11",
+ 12 => "push12",
+ 13 => "push13",
+ 14 => "push14",
+ 15 => "push15",
+ 16 => "push16",
+ 17 => "push17",
+ 18 => "push18",
+ 19 => "push19",
+ 20 => "push20",
+ 21 => "push21",
+ 22 => "push22",
+ 23 => "push23",
+ 24 => "push24",
+ 25 => "push25",
+ 26 => "push26",
+ 27 => "push27",
+ 28 => "push28",
+ 29 => "push29",
+ 30 => "push30",
+ 31 => "push31",
+ _ => "push32",
+ };
+ op += 1;
+ }
+ table[0x80] = "dup1";
+ table[0x81] = "dup2";
+ table[0x82] = "dup3";
+ table[0x83] = "dup4";
+ table[0x84] = "dup5";
+ table[0x85] = "dup6";
+ table[0x86] = "dup7";
+ table[0x87] = "dup8";
+ table[0x88] = "dup9";
+ table[0x89] = "dup10";
+ table[0x8a] = "dup11";
+ table[0x8b] = "dup12";
+ table[0x8c] = "dup13";
+ table[0x8d] = "dup14";
+ table[0x8e] = "dup15";
+ table[0x8f] = "dup16";
+ table[0x90] = "swap1";
+ table[0x91] = "swap2";
+ table[0x92] = "swap3";
+ table[0x93] = "swap4";
+ table[0x94] = "swap5";
+ table[0x95] = "swap6";
+ table[0x96] = "swap7";
+ table[0x97] = "swap8";
+ table[0x98] = "swap9";
+ table[0x99] = "swap10";
+ table[0x9a] = "swap11";
+ table[0x9b] = "swap12";
+ table[0x9c] = "swap13";
+ table[0x9d] = "swap14";
+ table[0x9e] = "swap15";
+ table[0x9f] = "swap16";
+ table[0xa0] = "log0";
+ table[0xa1] = "log1";
+ table[0xa2] = "log2";
+ table[0xa3] = "log3";
+ table[0xa4] = "log4";
+ table[0xf0] = "create";
+ table[0xf1] = "call";
+ table[0xf2] = "callcode";
+ table[0xf3] = "return";
+ table[0xf4] = "delegatecall";
+ table[0xf5] = "create2";
+ table[0xfa] = "staticcall";
+ table[0xfd] = "revert";
+ table[0xff] = "selfdestruct";
+ table
+};
+
+const PUSH1: u8 = 0x60;
+const PUSH32: u8 = 0x7f;
+
+pub(crate) fn decode_raw(bytes: &[u8], address: u64) -> Result<Instruction> {
+ if bytes.is_empty() {
+ return Err(Error::Decode("empty input".into()));
+ }
+ let opcode = bytes[0];
+ let mnemonic = OPCODE_MNEMONIC[opcode as usize];
+ let (length, operands) = if opcode >= PUSH1 && opcode <= PUSH32 {
+ let imm_len = (opcode - PUSH1 + 1) as usize;
+ if bytes.len() < 1 + imm_len {
+ return Err(Error::Decode("truncated push immediate".into()));
+ }
+ let imm_bytes = &bytes[1..=imm_len];
+ let hex = imm_bytes
+ .iter()
+ .rev()
+ .map(|b| format!("{b:02x}"))
+ .collect::<String>();
+ let imm_display = format!("0x{hex}");
+ (1 + imm_len as u8, imm_display)
+ } else if mnemonic == "invalid" {
+ (1, String::new())
+ } else {
+ (1, String::new())
+ };
+ Ok(Instruction::with_text(
+ address,
+ bytes[..length as usize].to_vec(),
+ mnemonic,
+ operands,
+ length,
+ ))
+}
+
+impl ArchDecode for EvmDecoder {
+ fn arch(&self) -> Arch {
+ Arch::Evm
+ }
+
+ fn open(mode: Mode) -> Result<Self> {
+ if !mode.is_valid_for(Arch::Evm) {
+ return Err(Error::Mode(format!("invalid evm mode {:#x}", mode.bits())));
+ }
+ Ok(Self { _mode: mode })
+ }
+
+ fn decode_one(&self, bytes: &[u8], address: u64, opts: &EngineOptions) -> Result<Instruction> {
+ let mut insn = decode_raw(bytes, address)?;
+ insn.id = names::insn_id_for_mnemonic(Arch::Evm, &insn.mnemonic);
+ if opts.detail {
+ insn.detail = Some(InsnDetail {
+ groups: groups_for_mnemonic(&insn.mnemonic),
+ ..InsnDetail::default()
+ });
+ }
+ Ok(insn)
+ }
+}
+
+fn groups_for_mnemonic(mnemonic: &str) -> Vec<GroupId> {
+ match mnemonic {
+ "jump" | "jumpi" => vec![GroupId::Jump],
+ "call" | "callcode" | "delegatecall" | "staticcall" => vec![GroupId::Call],
+ "return" | "revert" => vec![GroupId::Ret],
+ "stop" | "selfdestruct" => vec![GroupId::Arch(8)], // halt
+ m if m.starts_with("push") => vec![GroupId::Arch(6)], // stack_write
+ "pop" | "dup1" | "dup2" | "dup3" | "dup4" | "dup5" | "dup6" | "dup7" | "dup8"
+ | "dup9" | "dup10" | "dup11" | "dup12" | "dup13" | "dup14" | "dup15" | "dup16" => {
+ vec![GroupId::Arch(5)] // stack_read
+ }
+ "mstore" | "mstore8" | "calldatacopy" | "codecopy" | "extcodecopy" | "mcopy" => {
+ vec![GroupId::Arch(7)] // mem_write
+ }
+ "mload" | "create" | "create2" => vec![GroupId::Arch(4)], // mem_read
+ "sstore" | "tstore" => vec![GroupId::Arch(9)], // store_write
+ "sload" | "tload" => vec![GroupId::Arch(10)], // store_read
+ "add" | "mul" | "sub" | "div" | "sdiv" | "mod" | "smod" | "addmod" | "mulmod" | "exp"
+ | "signextend" | "shl" | "shr" | "sar" => vec![GroupId::Arch(3)], // math
+ _ => Vec::new(),
+ }
+}
+
+pub fn reg_name(_reg: crate::reg::RegId) -> Option<&'static str> {
+ None
+}
+
+pub fn insn_name(id: InsnId) -> Option<&'static str> {
+ let raw = id.raw();
+ if raw < 256 {
+ Some(OPCODE_MNEMONIC[raw as usize])
+ } else {
+ None
+ }
+}
+
+pub fn group_name(group: GroupId) -> Option<&'static str> {
+ match group {
+ GroupId::Jump => Some("jump"),
+ GroupId::Call => Some("call"),
+ GroupId::Ret => Some("ret"),
+ GroupId::Arch(3) => Some("math"),
+ GroupId::Arch(4) => Some("mem_read"),
+ GroupId::Arch(5) => Some("stack_read"),
+ GroupId::Arch(6) => Some("stack_write"),
+ GroupId::Arch(7) => Some("mem_write"),
+ GroupId::Arch(8) => Some("halt"),
+ GroupId::Arch(9) => Some("store_write"),
+ GroupId::Arch(10) => Some("store_read"),
+ _ => None,
+ }
+}
+
+pub fn insn_id_for_mnemonic(mnemonic: &str) -> InsnId {
+ for (i, name) in OPCODE_MNEMONIC.iter().enumerate() {
+ if *name == mnemonic {
+ return InsnId(i as u32);
+ }
+ }
+ InsnId::INVALID
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::option::EngineOptions;
+
+ #[test]
+ fn evm_stop_and_push1() {
+ let dec = EvmDecoder::open(Mode::LITTLE_ENDIAN).unwrap();
+ let stop = dec
+ .decode_one(&[0x00], 0, &EngineOptions::default())
+ .unwrap();
+ assert_eq!(stop.mnemonic, "stop");
+ assert_eq!(stop.length, 1);
+
+ let push = dec
+ .decode_one(&[0x60, 0x2a], 0x10, &EngineOptions::default())
+ .unwrap();
+ assert_eq!(push.mnemonic, "push1");
+ assert_eq!(push.length, 2);
+ assert_eq!(push.operands, "0x2a");
+ }
+
+ #[test]
+ fn evm_call_and_invalid() {
+ let dec = EvmDecoder::open(Mode::LITTLE_ENDIAN).unwrap();
+ let call = dec
+ .decode_one(&[0xf1], 0, &EngineOptions::default())
+ .unwrap();
+ assert_eq!(call.mnemonic, "call");
+
+ let bad = dec
+ .decode_one(&[0x0c], 0, &EngineOptions::default())
+ .unwrap();
+ assert_eq!(bad.mnemonic, "invalid");
+ }
+
+ #[test]
+ fn evm_push32_length() {
+ let dec = EvmDecoder::open(Mode::LITTLE_ENDIAN).unwrap();
+ let mut bytes = vec![0x7f];
+ bytes.extend(std::iter::repeat_n(0xab_u8, 32));
+ let insn = dec.decode_one(&bytes, 0, &EngineOptions::default()).unwrap();
+ assert_eq!(insn.mnemonic, "push32");
+ assert_eq!(insn.length, 33);
+ }
+}
diff --git a/crates/ghidrust-decode/src/arch/hppa/decode.rs b/crates/ghidrust-decode/src/arch/hppa/decode.rs
new file mode 100644
index 0000000..6c32449
--- /dev/null
+++ b/crates/ghidrust-decode/src/arch/hppa/decode.rs
@@ -0,0 +1,116 @@
+use crate::error::{Error, Result};
+
+pub fn reg_name(reg: crate::reg::RegId) -> Option<&'static str> {
+ match reg.index() {
+ 0 => Some("r0"),
+ 1 => Some("r1"),
+ 26 => Some("rp"),
+ 31 => Some("sp"),
+ _ => None,
+ }
+}
+
+fn r(n: u32) -> String {
+ format!("r{n}")
+}
+
+pub fn decode(bytes: &[u8], big_endian: bool) -> Result<(String, String, usize)> {
+ if bytes.len() < 4 {
+ return Err(Error::Decode("truncated hppa instruction".into()));
+ }
+ let word = if big_endian {
+ u32::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])
+ } else {
+ u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])
+ };
+ let op = (word >> 26) & 0x3f;
+ match op {
+ 0x0d => decode_ldo(word),
+ 0x08 => decode_mem(word, "ldw"),
+ 0x09 => decode_mem(word, "stw"),
+ 0x02 => decode_arith(word, "add"),
+ 0x03 => decode_arith(word, "sub"),
+ 0x3a => decode_branch(word, "bl"),
+ 0x38 => decode_branch(word, "be"),
+ 0x39 => decode_branch(word, "bv"),
+ 0x3c => decode_comb(word),
+ _ => Err(Error::Decode("unsupported hppa opcode".into())),
+ }
+}
+
+fn decode_ldo(word: u32) -> Result<(String, String, usize)> {
+ let dst = (word >> 21) & 0x1f;
+ let base = (word >> 16) & 0x1f;
+ let imm = sign_ext((word >> 0) & 0x1fff, 13);
+ Ok((
+ "ldo".into(),
+ format!("{imm}({}), {}", r(base), r(dst)),
+ 4,
+ ))
+}
+
+fn decode_mem(word: u32, name: &str) -> Result<(String, String, usize)> {
+ let dst = (word >> 21) & 0x1f;
+ let base = (word >> 16) & 0x1f;
+ let off = sign_ext((word >> 0) & 0x1fff, 13);
+ if name == "ldw" {
+ Ok((
+ name.into(),
+ format!("{off}({}), {}", r(base), r(dst)),
+ 4,
+ ))
+ } else {
+ Ok((
+ name.into(),
+ format!("{}, {off}({})", r(dst), r(base)),
+ 4,
+ ))
+ }
+}
+
+fn decode_arith(word: u32, name: &str) -> Result<(String, String, usize)> {
+ let dst = (word >> 21) & 0x1f;
+ let src1 = (word >> 16) & 0x1f;
+ let src2 = (word >> 0) & 0x1f;
+ Ok((
+ name.into(),
+ format!("{}, {}, {}", r(dst), r(src1), r(src2)),
+ 4,
+ ))
+}
+
+fn decode_branch(word: u32, name: &str) -> Result<(String, String, usize)> {
+ let disp = sign_ext((word >> 0) & 0x1fffff, 21);
+ Ok((name.into(), format!("{disp}"), 4))
+}
+
+fn decode_comb(word: u32) -> Result<(String, String, usize)> {
+ let cond = (word >> 16) & 0x1f;
+ let src1 = (word >> 21) & 0x1f;
+ let src2 = (word >> 0) & 0x1f;
+ let disp = sign_ext((word >> 0) & 0xfff, 12);
+ Ok((
+ "comb".into(),
+ format!("{cond}, {}, {}, {disp}", r(src1), r(src2)),
+ 4,
+ ))
+}
+
+fn sign_ext(val: u32, bits: u32) -> i64 {
+ let shift = 32 - bits;
+ ((val << shift) as i32 >> shift) as i64
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn hppa_ldo() {
+ // ldo 8(r1), r2 => op=0x0d
+ let word = (0x0du32 << 26) | (2 << 21) | (1 << 16) | 8;
+ let (m, _, l) = decode(&word.to_be_bytes(), true).unwrap();
+ assert_eq!(m, "ldo");
+ assert_eq!(l, 4);
+ }
+}
diff --git a/crates/ghidrust-decode/src/arch/hppa/mod.rs b/crates/ghidrust-decode/src/arch/hppa/mod.rs
new file mode 100644
index 0000000..9632ee4
--- /dev/null
+++ b/crates/ghidrust-decode/src/arch/hppa/mod.rs
@@ -0,0 +1,122 @@
+mod decode;
+
+use crate::arch::ArchDecode;
+use crate::error::{Error, Result};
+use crate::group::GroupId;
+use crate::insn::{InsnDetail, InsnId, Instruction};
+use crate::names;
+use crate::option::EngineOptions;
+use crate::support::{Arch, Mode};
+
+pub use decode::reg_name;
+
+pub struct HppaDecoder {
+ big_endian: bool,
+}
+
+impl ArchDecode for HppaDecoder {
+ fn arch(&self) -> Arch {
+ Arch::Hppa
+ }
+
+ fn open(mode: Mode) -> Result<Self> {
+ if !mode.is_valid_for(Arch::Hppa) {
+ return Err(Error::Mode(format!("invalid hppa mode {:#x}", mode.bits())));
+ }
+ let big_endian = !mode.intersects(Mode::LITTLE_ENDIAN) || mode.contains(Mode::BIG_ENDIAN);
+ Ok(Self { big_endian })
+ }
+
+ fn decode_one(&self, bytes: &[u8], address: u64, opts: &EngineOptions) -> Result<Instruction> {
+ let (mnemonic, operands, len) = decode::decode(bytes, self.big_endian)?;
+ let mut insn = Instruction::with_text(
+ address,
+ bytes[..len].to_vec(),
+ mnemonic,
+ operands,
+ len as u8,
+ );
+ insn.id = names::insn_id_for_mnemonic(Arch::Hppa, &insn.mnemonic);
+ if opts.detail {
+ insn.detail = Some(InsnDetail {
+ groups: groups_for_mnemonic(&insn.mnemonic),
+ ..InsnDetail::default()
+ });
+ }
+ Ok(insn)
+ }
+}
+
+fn groups_for_mnemonic(mnemonic: &str) -> Vec<GroupId> {
+ match mnemonic {
+ "bl" => vec![GroupId::Call],
+ "be" | "bv" | "comb" => vec![GroupId::Jump],
+ "ldw" | "ldo" => vec![GroupId::Arch(1)],
+ "stw" => vec![GroupId::Arch(2)],
+ "add" | "sub" => vec![GroupId::Arch(3)],
+ _ => Vec::new(),
+ }
+}
+
+pub fn insn_name(id: InsnId) -> Option<&'static str> {
+ match id.raw() {
+ 1 => Some("ldo"),
+ 2 => Some("ldw"),
+ 3 => Some("add"),
+ 4 => Some("bl"),
+ 5 => Some("comb"),
+ _ => None,
+ }
+}
+
+pub fn group_name(group: GroupId) -> Option<&'static str> {
+ match group {
+ GroupId::Jump => Some("jump"),
+ GroupId::Call => Some("call"),
+ GroupId::Arch(1) => Some("load"),
+ GroupId::Arch(2) => Some("store"),
+ GroupId::Arch(3) => Some("alu"),
+ _ => None,
+ }
+}
+
+pub fn insn_id_for_mnemonic(mnemonic: &str) -> InsnId {
+ let id = match mnemonic {
+ "ldo" => 1,
+ "ldw" => 2,
+ "add" | "sub" => 3,
+ "bl" => 4,
+ "comb" | "be" | "bv" => 5,
+ "stw" => 2,
+ _ => 0,
+ };
+ InsnId(id)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::engine::Engine;
+
+ #[test]
+ fn hppa_ldo_and_add() {
+ let mut eng = Engine::open(Arch::Hppa, Mode::BIG_ENDIAN).unwrap();
+ let ldo = (0x0du32 << 26) | (2 << 21) | (1 << 16) | 8;
+ let insn = eng.disasm_one(&ldo.to_be_bytes(), 0).unwrap();
+ assert_eq!(insn.mnemonic, "ldo");
+ let add = (0x02u32 << 26) | (3 << 21) | (1 << 16) | 2;
+ let addi = eng.disasm_one(&add.to_be_bytes(), 0).unwrap();
+ assert_eq!(addi.mnemonic, "add");
+ }
+
+ #[test]
+ fn hppa_bl_and_ldw() {
+ let mut eng = Engine::open(Arch::Hppa, Mode::BIG_ENDIAN).unwrap();
+ let bl = (0x3au32 << 26) | 4;
+ let insn = eng.disasm_one(&bl.to_be_bytes(), 0).unwrap();
+ assert_eq!(insn.mnemonic, "bl");
+ let ldw = (0x08u32 << 26) | (4 << 21) | (1 << 16) | 0;
+ let ld = eng.disasm_one(&ldw.to_be_bytes(), 0).unwrap();
+ assert_eq!(ld.mnemonic, "ldw");
+ }
+}
diff --git a/crates/ghidrust-decode/src/arch/leb128.rs b/crates/ghidrust-decode/src/arch/leb128.rs
new file mode 100644
index 0000000..8a134dd
--- /dev/null
+++ b/crates/ghidrust-decode/src/arch/leb128.rs
@@ -0,0 +1,61 @@
+use crate::error::{Error, Result};
+
+pub fn read_u32(bytes: &[u8]) -> Result<(u32, usize)> {
+ let mut data = 0u32;
+ for (i, &b) in bytes.iter().enumerate() {
+ if i > 4 || (i == 4 && b & 0x7f > 0x0f) {
+ return Err(Error::Decode("invalid leb128 u32".into()));
+ }
+ data |= u32::from(b & 0x7f) << (i * 7);
+ if b & 0x80 == 0 {
+ return Ok((data, i + 1));
+ }
+ }
+ Err(Error::Decode("truncated leb128 u32".into()))
+}
+
+pub fn read_u64(bytes: &[u8]) -> Result<(u64, usize)> {
+ let mut data = 0u64;
+ for (i, &b) in bytes.iter().enumerate() {
+ if i > 9 || (i == 9 && b & 0x7f > 0x01) {
+ return Err(Error::Decode("invalid leb128 u64".into()));
+ }
+ data |= u64::from(b & 0x7f) << (i * 7);
+ if b & 0x80 == 0 {
+ return Ok((data, i + 1));
+ }
+ }
+ Err(Error::Decode("truncated leb128 u64".into()))
+}
+
+pub fn read_i32(bytes: &[u8]) -> Result<(i32, usize)> {
+ let (raw, len) = read_u32(bytes)?;
+ let sign = 1u32 << (len * 7 - 1);
+ let value = if raw & sign != 0 {
+ (raw | (!0u32 << (len * 7))) as i32
+ } else {
+ raw as i32
+ };
+ Ok((value, len))
+}
+
+pub fn read_i64(bytes: &[u8]) -> Result<(i64, usize)> {
+ let (raw, len) = read_u64(bytes)?;
+ let sign = 1u64 << (len * 7 - 1);
+ let value = if raw & sign != 0 {
+ (raw | (!0u64 << (len * 7))) as i64
+ } else {
+ raw as i64
+ };
+ Ok((value, len))
+}
+
+pub fn read_i7(bytes: &[u8]) -> Result<(i8, usize)> {
+ if bytes.is_empty() {
+ return Err(Error::Decode("truncated block type".into()));
+ }
+ if bytes[0] == 0x40 {
+ return Ok((0, 1));
+ }
+ Ok((bytes[0] as i8, 1))
+}
diff --git a/crates/ghidrust-decode/src/arch/loongarch/decode.rs b/crates/ghidrust-decode/src/arch/loongarch/decode.rs
new file mode 100644
index 0000000..22fdcdc
--- /dev/null
+++ b/crates/ghidrust-decode/src/arch/loongarch/decode.rs
@@ -0,0 +1,111 @@
+use crate::error::{Error, Result};
+
+pub fn reg_name(reg: crate::reg::RegId) -> Option<&'static str> {
+ match reg.index() {
+ 0 => Some("r0"),
+ 1 => Some("r1"),
+ 4 => Some("r4"),
+ 5 => Some("r5"),
+ _ => None,
+ }
+}
+
+fn r(n: u32) -> String {
+ format!("r{n}")
+}
+
+pub fn decode(bytes: &[u8], little_endian: bool, is64: bool) -> Result<(String, String, usize)> {
+ if bytes.len() < 4 {
+ return Err(Error::Decode("truncated loongarch instruction".into()));
+ }
+ let word = if little_endian {
+ u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])
+ } else {
+ u32::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])
+ };
+ let opcode = word >> 26;
+ match opcode {
+ 0x00 => decode_addi(word, is64),
+ 0x01 => decode_ldst(word, "ld", is64),
+ 0x02 => decode_ldst(word, "st", is64),
+ 0x14 => decode_branch(word, "b"),
+ 0x15 => decode_branch(word, "bl"),
+ 0x13 => decode_jirl(word),
+ 0x10 => decode_alu3(word, "add", is64),
+ 0x11 => decode_alu3(word, "sub", is64),
+ _ => Err(Error::Decode("unsupported loongarch opcode".into())),
+ }
+}
+
+fn suffix(is64: bool) -> &'static str {
+ if is64 { ".d" } else { ".w" }
+}
+
+fn decode_addi(word: u32, is64: bool) -> Result<(String, String, usize)> {
+ let rd = (word >> 0) & 0x1f;
+ let rj = (word >> 5) & 0x1f;
+ let imm = sign_ext((word >> 10) & 0xfff, 12);
+ Ok((
+ format!("addi{}", suffix(is64)),
+ format!("{}, {}, {imm}", r(rd), r(rj)),
+ 4,
+ ))
+}
+
+fn decode_ldst(word: u32, name: &str, is64: bool) -> Result<(String, String, usize)> {
+ let rd = (word >> 0) & 0x1f;
+ let rj = (word >> 5) & 0x1f;
+ let imm = sign_ext((word >> 10) & 0xfff, 12);
+ let op = format!("{name}{}", suffix(is64));
+ Ok((
+ op,
+ format!("{}, {imm}({})", r(rd), r(rj)),
+ 4,
+ ))
+}
+
+fn decode_alu3(word: u32, name: &str, is64: bool) -> Result<(String, String, usize)> {
+ let rd = (word >> 0) & 0x1f;
+ let rj = (word >> 5) & 0x1f;
+ let rk = (word >> 10) & 0x1f;
+ Ok((
+ format!("{name}{}", suffix(is64)),
+ format!("{}, {}, {}", r(rd), r(rj), r(rk)),
+ 4,
+ ))
+}
+
+fn decode_branch(word: u32, name: &str) -> Result<(String, String, usize)> {
+ let off = sign_ext((word >> 10) & 0xfffff, 20);
+ Ok((name.into(), format!("{off}"), 4))
+}
+
+fn decode_jirl(word: u32) -> Result<(String, String, usize)> {
+ let rd = (word >> 0) & 0x1f;
+ let rj = (word >> 5) & 0x1f;
+ let off = sign_ext((word >> 10) & 0xfffff, 20);
+ Ok((
+ "jirl".into(),
+ format!("{}, {}, {off}", r(rd), r(rj)),
+ 4,
+ ))
+}
+
+fn sign_ext(val: u32, bits: u32) -> i64 {
+ let shift = 32 - bits;
+ ((val << shift) as i32 >> shift) as i64
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn loongarch_addi() {
+ // addi.w r4, r5, 1 => op=0 rd=4 rj=5 imm=1
+ let word = (0x00u32 << 26) | (1 << 10) | (5 << 5) | 4;
+ let (m, _, l) = decode(&word.to_le_bytes(), true, false).unwrap();
+ assert_eq!(m, "addi.w");
+ assert_eq!(l, 4);
+ }
+}
diff --git a/crates/ghidrust-decode/src/arch/loongarch/mod.rs b/crates/ghidrust-decode/src/arch/loongarch/mod.rs
new file mode 100644
index 0000000..0c9ddcf
--- /dev/null
+++ b/crates/ghidrust-decode/src/arch/loongarch/mod.rs
@@ -0,0 +1,128 @@
+mod decode;
+
+use crate::arch::ArchDecode;
+use crate::error::{Error, Result};
+use crate::group::GroupId;
+use crate::insn::{InsnDetail, InsnId, Instruction};
+use crate::names;
+use crate::option::EngineOptions;
+use crate::support::{Arch, Mode};
+
+pub use decode::reg_name;
+
+pub struct LoongarchDecoder {
+ little_endian: bool,
+ is64: bool,
+}
+
+impl ArchDecode for LoongarchDecoder {
+ fn arch(&self) -> Arch {
+ Arch::Loongarch
+ }
+
+ fn open(mode: Mode) -> Result<Self> {
+ if !mode.is_valid_for(Arch::Loongarch) {
+ return Err(Error::Mode(format!(
+ "invalid loongarch mode {:#x}",
+ mode.bits()
+ )));
+ }
+ let little_endian = !mode.contains(Mode::BIG_ENDIAN);
+ let is64 = mode.contains(Mode::MODE_64);
+ Ok(Self {
+ little_endian,
+ is64,
+ })
+ }
+
+ fn decode_one(&self, bytes: &[u8], address: u64, opts: &EngineOptions) -> Result<Instruction> {
+ let (mnemonic, operands, len) =
+ decode::decode(bytes, self.little_endian, self.is64)?;
+ let mut insn = Instruction::with_text(
+ address,
+ bytes[..len].to_vec(),
+ mnemonic,
+ operands,
+ len as u8,
+ );
+ insn.id = names::insn_id_for_mnemonic(Arch::Loongarch, &insn.mnemonic);
+ if opts.detail {
+ insn.detail = Some(InsnDetail {
+ groups: groups_for_mnemonic(&insn.mnemonic),
+ ..InsnDetail::default()
+ });
+ }
+ Ok(insn)
+ }
+}
+
+fn groups_for_mnemonic(mnemonic: &str) -> Vec<GroupId> {
+ match mnemonic {
+ "bl" | "jirl" => vec![GroupId::Call],
+ "b" => vec![GroupId::Jump],
+ m if m.starts_with("ld") => vec![GroupId::Arch(1)],
+ m if m.starts_with("st") => vec![GroupId::Arch(2)],
+ _ => vec![GroupId::Arch(3)],
+ }
+}
+
+pub fn insn_name(id: InsnId) -> Option<&'static str> {
+ match id.raw() {
+ 1 => Some("addi.w"),
+ 2 => Some("ld.w"),
+ 3 => Some("b"),
+ 4 => Some("jirl"),
+ _ => None,
+ }
+}
+
+pub fn group_name(group: GroupId) -> Option<&'static str> {
+ match group {
+ GroupId::Jump => Some("jump"),
+ GroupId::Call => Some("call"),
+ GroupId::Arch(1) => Some("load"),
+ GroupId::Arch(2) => Some("store"),
+ GroupId::Arch(3) => Some("alu"),
+ _ => None,
+ }
+}
+
+pub fn insn_id_for_mnemonic(mnemonic: &str) -> InsnId {
+ let id = match mnemonic {
+ m if m.starts_with("addi") => 1,
+ m if m.starts_with("ld") => 2,
+ "b" => 3,
+ "bl" | "jirl" => 4,
+ m if m.starts_with("st") => 2,
+ _ => 0,
+ };
+ InsnId(id)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::engine::Engine;
+
+ #[test]
+ fn loongarch_addi_and_ld() {
+ let mut eng = Engine::open(Arch::Loongarch, Mode::MODE_32).unwrap();
+ let addi = (0x00u32 << 26) | (1 << 10) | (5 << 5) | 4;
+ let insn = eng.disasm_one(&addi.to_le_bytes(), 0).unwrap();
+ assert_eq!(insn.mnemonic, "addi.w");
+ let ld = (0x01u32 << 26) | (8 << 10) | (5 << 5) | 4;
+ let ldw = eng.disasm_one(&ld.to_le_bytes(), 0).unwrap();
+ assert_eq!(ldw.mnemonic, "ld.w");
+ }
+
+ #[test]
+ fn loongarch_branch_and_jirl() {
+ let mut eng = Engine::open(Arch::Loongarch, Mode::MODE_32).unwrap();
+ let b = (0x14u32 << 26) | (4 << 10);
+ let br = eng.disasm_one(&b.to_le_bytes(), 0).unwrap();
+ assert_eq!(br.mnemonic, "b");
+ let jirl = (0x13u32 << 26) | (8 << 10) | (1 << 5) | 1;
+ let jr = eng.disasm_one(&jirl.to_le_bytes(), 0).unwrap();
+ assert_eq!(jr.mnemonic, "jirl");
+ }
+}
diff --git a/crates/ghidrust-decode/src/arch/m680x/decode.rs b/crates/ghidrust-decode/src/arch/m680x/decode.rs
new file mode 100644
index 0000000..0ab2b82
--- /dev/null
+++ b/crates/ghidrust-decode/src/arch/m680x/decode.rs
@@ -0,0 +1,68 @@
+use crate::error::{Error, Result};
+
+pub fn reg_name(reg: crate::reg::RegId) -> Option<&'static str> {
+ match reg.index() {
+ 0 => Some("a"),
+ 1 => Some("b"),
+ 2 => Some("x"),
+ 3 => Some("sp"),
+ _ => None,
+ }
+}
+
+pub fn decode(bytes: &[u8], _mode6809: bool) -> Result<(String, String, usize)> {
+ if bytes.is_empty() {
+ return Err(Error::Decode("empty m680x input".into()));
+ }
+ match bytes[0] {
+ 0x39 => Ok(("rts".into(), String::new(), 1)),
+ 0x86 => {
+ if bytes.len() < 2 {
+ return Err(Error::Decode("truncated lda imm".into()));
+ }
+ Ok(("lda".into(), format!("#0x{:02x}", bytes[1]), 2))
+ }
+ 0xb7 => decode_ext("sta", bytes),
+ 0x7e => decode_ext("jmp", bytes),
+ 0xbd => decode_ext("jsr", bytes),
+ 0x4f => Ok(("clra".into(), String::new(), 1)),
+ 0xcc => decode_ext("ldd", bytes),
+ 0xfd => decode_ext("std", bytes),
+ 0x8e => decode_ext("ldx", bytes),
+ 0xce => decode_ext("ldx16", bytes),
+ 0x20 => {
+ if bytes.len() < 2 {
+ return Err(Error::Decode("truncated bra".into()));
+ }
+ Ok(("bra".into(), format!("0x{:04x}", bytes[1] as u16), 2))
+ }
+ 0x27 => {
+ if bytes.len() < 2 {
+ return Err(Error::Decode("truncated beq".into()));
+ }
+ Ok(("beq".into(), format!("0x{:04x}", bytes[1] as u16), 2))
+ }
+ _ => Err(Error::Decode("unsupported m680x opcode".into())),
+ }
+}
+
+fn decode_ext(name: &str, bytes: &[u8]) -> Result<(String, String, usize)> {
+ if bytes.len() < 3 {
+ return Err(Error::Decode("truncated m680x extended".into()));
+ }
+ let addr = u16::from_be_bytes([bytes[1], bytes[2]]);
+ Ok((name.into(), format!("0x{addr:04x}"), 3))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn m680x_lda() {
+ let (m, o, l) = decode(&[0x86, 0x42], false).unwrap();
+ assert_eq!(m, "lda");
+ assert_eq!(l, 2);
+ assert!(o.contains("42"));
+ }
+}
diff --git a/crates/ghidrust-decode/src/arch/m680x/mod.rs b/crates/ghidrust-decode/src/arch/m680x/mod.rs
new file mode 100644
index 0000000..1570577
--- /dev/null
+++ b/crates/ghidrust-decode/src/arch/m680x/mod.rs
@@ -0,0 +1,119 @@
+mod decode;
+
+use crate::arch::ArchDecode;
+use crate::error::{Error, Result};
+use crate::group::GroupId;
+use crate::insn::{InsnDetail, InsnId, Instruction};
+use crate::names;
+use crate::option::EngineOptions;
+use crate::support::{Arch, Mode};
+
+pub use decode::reg_name;
+
+pub struct M680xDecoder {
+ mode6809: bool,
+}
+
+impl ArchDecode for M680xDecoder {
+ fn arch(&self) -> Arch {
+ Arch::M680x
+ }
+
+ fn open(mode: Mode) -> Result<Self> {
+ if !mode.is_valid_for(Arch::M680x) {
+ return Err(Error::Mode(format!("invalid m680x mode {:#x}", mode.bits())));
+ }
+ let mode6809 = mode.intersects(Mode::MODE_32);
+ Ok(Self { mode6809 })
+ }
+
+ fn decode_one(&self, bytes: &[u8], address: u64, opts: &EngineOptions) -> Result<Instruction> {
+ let (mnemonic, operands, len) = decode::decode(bytes, self.mode6809)?;
+ let mut insn = Instruction::with_text(
+ address,
+ bytes[..len].to_vec(),
+ mnemonic,
+ operands,
+ len as u8,
+ );
+ insn.id = names::insn_id_for_mnemonic(Arch::M680x, &insn.mnemonic);
+ if opts.detail {
+ insn.detail = Some(InsnDetail {
+ groups: groups_for_mnemonic(&insn.mnemonic),
+ ..InsnDetail::default()
+ });
+ }
+ Ok(insn)
+ }
+}
+
+fn groups_for_mnemonic(mnemonic: &str) -> Vec<GroupId> {
+ match mnemonic {
+ "jsr" => vec![GroupId::Call],
+ "jmp" | "bra" | "beq" => vec![GroupId::Jump],
+ "rts" => vec![GroupId::Ret],
+ "lda" | "ldd" | "ldx" | "ldx16" => vec![GroupId::Arch(1)],
+ "sta" | "std" => vec![GroupId::Arch(2)],
+ "clra" => vec![GroupId::Arch(3)],
+ _ => Vec::new(),
+ }
+}
+
+pub fn insn_name(id: InsnId) -> Option<&'static str> {
+ match id.raw() {
+ 1 => Some("lda"),
+ 2 => Some("sta"),
+ 3 => Some("jsr"),
+ 4 => Some("rts"),
+ 5 => Some("bra"),
+ _ => None,
+ }
+}
+
+pub fn group_name(group: GroupId) -> Option<&'static str> {
+ match group {
+ GroupId::Jump => Some("jump"),
+ GroupId::Call => Some("call"),
+ GroupId::Ret => Some("ret"),
+ GroupId::Arch(1) => Some("load"),
+ GroupId::Arch(2) => Some("store"),
+ GroupId::Arch(3) => Some("clear"),
+ _ => None,
+ }
+}
+
+pub fn insn_id_for_mnemonic(mnemonic: &str) -> InsnId {
+ let id = match mnemonic {
+ "lda" | "ldd" | "ldx" | "ldx16" => 1,
+ "sta" | "std" => 2,
+ "jsr" | "jmp" => 3,
+ "rts" => 4,
+ "bra" | "beq" => 5,
+ _ => 0,
+ };
+ InsnId(id)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::engine::Engine;
+
+ #[test]
+ fn m680x_lda_and_rts() {
+ let mut eng = Engine::open(Arch::M680x, Mode::LITTLE_ENDIAN).unwrap();
+ let lda = eng.disasm_one(&[0x86, 0x42], 0).unwrap();
+ assert_eq!(lda.mnemonic, "lda");
+ let rts = eng.disasm_one(&[0x39], 0).unwrap();
+ assert_eq!(rts.mnemonic, "rts");
+ }
+
+ #[test]
+ fn m680x_jsr_and_bra() {
+ let mut eng = Engine::open(Arch::M680x, Mode::LITTLE_ENDIAN).unwrap();
+ let jsr = eng.disasm_one(&[0xbd, 0x10, 0x00], 0).unwrap();
+ assert_eq!(jsr.mnemonic, "jsr");
+ let bra = eng.disasm_one(&[0x20, 0x08], 0).unwrap();
+ assert_eq!(bra.mnemonic, "bra");
+ }
+}
diff --git a/crates/ghidrust-decode/src/arch/m68k/decode.rs b/crates/ghidrust-decode/src/arch/m68k/decode.rs
new file mode 100644
index 0000000..f2f172e
--- /dev/null
+++ b/crates/ghidrust-decode/src/arch/m68k/decode.rs
@@ -0,0 +1,92 @@
+use crate::error::{Error, Result};
+
+pub fn d_reg(n: u32) -> String {
+ format!("d{n}")
+}
+
+pub fn a_reg(n: u32) -> String {
+ format!("a{n}")
+}
+
+pub fn reg_name(reg: crate::reg::RegId) -> Option<&'static str> {
+ match reg.index() {
+ 0 => Some("d0"),
+ 7 => Some("d7"),
+ 8 => Some("a0"),
+ 15 => Some("a7"),
+ _ => None,
+ }
+}
+
+pub fn decode(bytes: &[u8], big_endian: bool) -> Result<(String, String, usize)> {
+ if bytes.len() < 2 {
+ return Err(Error::Decode("truncated m68k input".into()));
+ }
+ let word = if big_endian {
+ u16::from_be_bytes([bytes[0], bytes[1]])
+ } else {
+ u16::from_le_bytes([bytes[0], bytes[1]])
+ };
+
+ match word {
+ 0x4e75 => Ok(("rts".into(), String::new(), 2)),
+ 0x4e70 => Ok(("reset".into(), String::new(), 2)),
+ 0x4240 => Ok(("clr.w".into(), format!("{}", d_reg(0)), 2)),
+ 0x08c0 => Ok(("bset".into(), "#0, d0".into(), 2)),
+ 0x4e90 => Ok(("jsr".into(), "(a0)".into(), 2)),
+ 0x4ed0 => Ok(("jmp".into(), "(a0)".into(), 2)),
+ 0x6002 => Ok(("bra.s".into(), "2".into(), 2)),
+ 0x6100 => Ok(("bsr.s".into(), "0".into(), 2)),
+ 0x6604 => Ok(("bne.s".into(), "4".into(), 2)),
+ 0x6704 => Ok(("beq.s".into(), "4".into(), 2)),
+ 0x3400 => Ok(("move.w".into(), "d0, d1".into(), 2)),
+ 0x2040 => Ok(("movea.w".into(), "a0, a0".into(), 2)),
+ 0x7001 => Ok(("moveq".into(), "#1, d0".into(), 2)),
+ 0x5840 => Ok(("addq.w".into(), "#4, d0".into(), 2)),
+ 0xb040 => Ok(("cmp.w".into(), "d0, d0".into(), 2)),
+ 0x484a => decode_lea(bytes, big_endian),
+ _ if (word & 0xff00) == 0x0600 => decode_add_sub(word),
+ _ => Err(Error::Decode("unsupported m68k opcode".into())),
+ }
+}
+
+fn decode_add_sub(word: u16) -> Result<(String, String, usize)> {
+ let op = (word >> 12) & 0xf;
+ let reg = word & 0x7;
+ let name = match op {
+ 0x6 => "add.w",
+ 0x9 => "sub.w",
+ 0xb => "cmp.w",
+ 0xd => "add.w",
+ _ => return Err(Error::Decode("unsupported m68k alu".into())),
+ };
+ Ok((
+ name.into(),
+ format!("d{}, d{}", (word >> 9) & 0x7, reg),
+ 2,
+ ))
+}
+
+fn decode_lea(bytes: &[u8], be: bool) -> Result<(String, String, usize)> {
+ if bytes.len() < 4 {
+ return Err(Error::Decode("truncated lea".into()));
+ }
+ let disp = if be {
+ i16::from_be_bytes([bytes[2], bytes[3]])
+ } else {
+ i16::from_le_bytes([bytes[2], bytes[3]])
+ };
+ Ok(("lea".into(), format!("({disp}, pc), a2"), 4))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn m68k_moveq() {
+ let (m, _, l) = decode(&[0x70, 0x01], true).unwrap();
+ assert_eq!(m, "moveq");
+ assert_eq!(l, 2);
+ }
+}
diff --git a/crates/ghidrust-decode/src/arch/m68k/mod.rs b/crates/ghidrust-decode/src/arch/m68k/mod.rs
new file mode 100644
index 0000000..371468d
--- /dev/null
+++ b/crates/ghidrust-decode/src/arch/m68k/mod.rs
@@ -0,0 +1,125 @@
+mod decode;
+
+use crate::arch::ArchDecode;
+use crate::error::{Error, Result};
+use crate::group::GroupId;
+use crate::insn::{InsnDetail, InsnId, Instruction};
+use crate::names;
+use crate::option::EngineOptions;
+use crate::support::{Arch, Mode};
+
+pub use decode::reg_name;
+
+pub struct M68kDecoder {
+ big_endian: bool,
+}
+
+impl ArchDecode for M68kDecoder {
+ fn arch(&self) -> Arch {
+ Arch::M68k
+ }
+
+ fn open(mode: Mode) -> Result<Self> {
+ if !mode.is_valid_for(Arch::M68k) {
+ return Err(Error::Mode(format!("invalid m68k mode {:#x}", mode.bits())));
+ }
+ let big_endian = !mode.intersects(Mode::LITTLE_ENDIAN) || mode.contains(Mode::BIG_ENDIAN);
+ Ok(Self { big_endian })
+ }
+
+ fn decode_one(&self, bytes: &[u8], address: u64, opts: &EngineOptions) -> Result<Instruction> {
+ let (mnemonic, operands, len) = decode::decode(bytes, self.big_endian)?;
+ let mut insn = Instruction::with_text(
+ address,
+ bytes[..len].to_vec(),
+ mnemonic,
+ operands,
+ len as u8,
+ );
+ insn.id = names::insn_id_for_mnemonic(Arch::M68k, &insn.mnemonic);
+ if opts.detail {
+ insn.detail = Some(InsnDetail {
+ groups: groups_for_mnemonic(&insn.mnemonic),
+ ..InsnDetail::default()
+ });
+ }
+ Ok(insn)
+ }
+}
+
+fn groups_for_mnemonic(mnemonic: &str) -> Vec<GroupId> {
+ match mnemonic {
+ "jsr" | "bsr" => vec![GroupId::Call],
+ "jmp" | "bra" | "bne" | "beq" => vec![GroupId::Jump],
+ "rts" => vec![GroupId::Ret],
+ m if m.starts_with("move") => vec![GroupId::Arch(1)],
+ "add.w" | "cmp.w" => vec![GroupId::Arch(2)],
+ "clr" | "bset" => vec![GroupId::Arch(3)],
+ _ => Vec::new(),
+ }
+}
+
+pub fn insn_name(id: InsnId) -> Option<&'static str> {
+ match id.raw() {
+ 1 => Some("move.w"),
+ 2 => Some("moveq"),
+ 3 => Some("lea"),
+ 4 => Some("jsr"),
+ 5 => Some("rts"),
+ 6 => Some("bra"),
+ _ => None,
+ }
+}
+
+pub fn group_name(group: GroupId) -> Option<&'static str> {
+ match group {
+ GroupId::Jump => Some("jump"),
+ GroupId::Call => Some("call"),
+ GroupId::Ret => Some("ret"),
+ GroupId::Arch(1) => Some("move"),
+ GroupId::Arch(2) => Some("alu"),
+ GroupId::Arch(3) => Some("bit"),
+ _ => None,
+ }
+}
+
+pub fn insn_id_for_mnemonic(mnemonic: &str) -> InsnId {
+ let id = match mnemonic {
+ m if m.starts_with("move") => 1,
+ "moveq" => 2,
+ "lea" => 3,
+ "jsr" | "jmp" => 4,
+ "rts" => 5,
+ m if m.starts_with('b') => 6,
+ _ => 0,
+ };
+ InsnId(id)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::engine::Engine;
+
+ #[test]
+ fn m68k_moveq_and_rts() {
+ let mut eng = Engine::open(Arch::M68k, Mode::BIG_ENDIAN).unwrap();
+ // moveq #1, d0 => 0x7001
+ let mq = eng.disasm_one(&[0x70, 0x01], 0).unwrap();
+ assert_eq!(mq.mnemonic, "moveq");
+ // rts => 0x4e75
+ let rts = eng.disasm_one(&[0x4e, 0x75], 0).unwrap();
+ assert_eq!(rts.mnemonic, "rts");
+ }
+
+ #[test]
+ fn m68k_jsr_and_bra() {
+ let mut eng = Engine::open(Arch::M68k, Mode::BIG_ENDIAN).unwrap();
+ // jsr (a0) => 0x4e90
+ let jsr = eng.disasm_one(&[0x4e, 0x90], 0).unwrap();
+ assert_eq!(jsr.mnemonic, "jsr");
+ // bra.s +2 => 0x6002
+ let bra = eng.disasm_one(&[0x60, 0x02], 0).unwrap();
+ assert_eq!(bra.mnemonic, "bra.s");
+ }
+}
diff --git a/crates/ghidrust-decode/src/arch/mips/decode.rs b/crates/ghidrust-decode/src/arch/mips/decode.rs
new file mode 100644
index 0000000..3b7a90c
--- /dev/null
+++ b/crates/ghidrust-decode/src/arch/mips/decode.rs
@@ -0,0 +1,151 @@
+use super::regs::gpr;
+use super::util::{bit, fmt_imm, read_u32, sign_extend16};
+use crate::error::{Error, Result};
+use crate::insn::Instruction;
+
+pub fn decode(bytes: &[u8], address: u64, big_endian: bool, mips64: bool) -> Result<Instruction> {
+ let w = read_u32(bytes, big_endian)?;
+ let raw = bytes[..4].to_vec();
+ let opcode = bit(w, 26, 31);
+ match opcode {
+ 0b000000 => decode_special(w, address, raw, mips64),
+ 0b000001 => decode_regimm(w, address, raw),
+ 0b000010 => decode_j(w, address, raw, "j"),
+ 0b000011 => decode_j(w, address, raw, "jal"),
+ 0b000100 => decode_branch(w, address, raw, "beq"),
+ 0b000101 => decode_branch(w, address, raw, "bne"),
+ 0b000110 => decode_branch(w, address, raw, "blez"),
+ 0b000111 => decode_branch(w, address, raw, "bgtz"),
+ 0b001000 => decode_imm(w, address, raw, "addi"),
+ 0b001001 => decode_imm(w, address, raw, "addiu"),
+ 0b001010 => decode_imm(w, address, raw, "slti"),
+ 0b001011 => decode_imm(w, address, raw, "sltiu"),
+ 0b001100 => decode_imm(w, address, raw, "andi"),
+ 0b001101 => decode_imm(w, address, raw, "ori"),
+ 0b001110 => decode_imm(w, address, raw, "xori"),
+ 0b001111 => decode_lui(w, address, raw),
+ 0b100011 => decode_load_store(w, address, raw, "lw"),
+ 0b101011 => decode_load_store(w, address, raw, "sw"),
+ 0b100000 => decode_load_store(w, address, raw, "lb"),
+ 0b101000 => decode_load_store(w, address, raw, "sb"),
+ 0b100001 => decode_load_store(w, address, raw, "lh"),
+ 0b101001 => decode_load_store(w, address, raw, "sh"),
+ 0b100100 => decode_load_store(w, address, raw, "lbu"),
+ 0b100101 => decode_load_store(w, address, raw, "lhu"),
+ _ => Err(Error::Decode(format!("unhandled MIPS opcode {opcode:#04x}"))),
+ }
+}
+
+fn decode_special(w: u32, address: u64, raw: Vec<u8>, mips64: bool) -> Result<Instruction> {
+ let funct = bit(w, 0, 5);
+ let rs = bit(w, 21, 25);
+ let rt = bit(w, 16, 20);
+ let rd = bit(w, 11, 15);
+ let shamt = bit(w, 6, 10);
+ let (mnemonic, operands) = match funct {
+ 0b100000 => ("add", format!("{}, {}, {}", gpr(rd), gpr(rs), gpr(rt))),
+ 0b100001 => ("addu", format!("{}, {}, {}", gpr(rd), gpr(rs), gpr(rt))),
+ 0b100010 => ("sub", format!("{}, {}, {}", gpr(rd), gpr(rs), gpr(rt))),
+ 0b100011 => ("subu", format!("{}, {}, {}", gpr(rd), gpr(rs), gpr(rt))),
+ 0b100100 => ("and", format!("{}, {}, {}", gpr(rd), gpr(rs), gpr(rt))),
+ 0b100101 => ("or", format!("{}, {}, {}", gpr(rd), gpr(rs), gpr(rt))),
+ 0b100110 => ("xor", format!("{}, {}, {}", gpr(rd), gpr(rs), gpr(rt))),
+ 0b100111 => ("nor", format!("{}, {}, {}", gpr(rd), gpr(rs), gpr(rt))),
+ 0b101010 => ("slt", format!("{}, {}, {}", gpr(rd), gpr(rs), gpr(rt))),
+ 0b101011 => ("sltu", format!("{}, {}, {}", gpr(rd), gpr(rs), gpr(rt))),
+ 0b000000 => ("sll", format!("{}, {}, #{}", gpr(rd), gpr(rt), shamt)),
+ 0b000010 => ("srl", format!("{}, {}, #{}", gpr(rd), gpr(rt), shamt)),
+ 0b000011 => ("sra", format!("{}, {}, #{}", gpr(rd), gpr(rt), shamt)),
+ 0b001000 => ("jr", gpr(rs).into()),
+ 0b001001 => ("jalr", format!("{}, {}", gpr(rd), gpr(rs))),
+ 0b001100 => ("syscall", String::new()),
+ 0b001101 => ("break", String::new()),
+ 0b001111 if mips64 => ("sync", String::new()),
+ _ => return Err(Error::Decode(format!("unhandled MIPS special {funct:#04x}"))),
+ };
+ Ok(Instruction::with_text(address, raw, mnemonic, operands, 4))
+}
+
+fn decode_regimm(w: u32, address: u64, raw: Vec<u8>) -> Result<Instruction> {
+ let rt = bit(w, 16, 20);
+ let rs = bit(w, 21, 25);
+ let imm = sign_extend16(w & 0xffff) as i64;
+ let target = (address as i64).wrapping_add((imm << 2) as i64) as u64;
+ let mnemonic = match rt {
+ 0b00000 => "bltz",
+ 0b00001 => "bgez",
+ 0b10000 => "bltzal",
+ 0b10001 => "bgezal",
+ _ => return Err(Error::Decode("unhandled MIPS regimm".into())),
+ };
+ Ok(Instruction::with_text(
+ address,
+ raw,
+ mnemonic,
+ format!("{}, {}", gpr(rs), fmt_imm(target as i32)),
+ 4,
+ ))
+}
+
+fn decode_j(w: u32, address: u64, raw: Vec<u8>, mnemonic: &str) -> Result<Instruction> {
+ let target = ((address & 0xf000_0000) | ((bit(w, 0, 25) as u64) << 2)) as u64;
+ Ok(Instruction::with_text(
+ address,
+ raw,
+ mnemonic,
+ fmt_imm(target as i32),
+ 4,
+ ))
+}
+
+fn decode_branch(w: u32, address: u64, raw: Vec<u8>, mnemonic: &str) -> Result<Instruction> {
+ let rs = bit(w, 21, 25);
+ let rt = bit(w, 16, 20);
+ let imm = sign_extend16(w & 0xffff) as i64;
+ let target = (address as i64).wrapping_add((imm << 2) as i64) as u64;
+ Ok(Instruction::with_text(
+ address,
+ raw,
+ mnemonic,
+ format!("{}, {}, {}", gpr(rs), gpr(rt), fmt_imm(target as i32)),
+ 4,
+ ))
+}
+
+fn decode_imm(w: u32, address: u64, raw: Vec<u8>, mnemonic: &str) -> Result<Instruction> {
+ let rs = bit(w, 21, 25);
+ let rt = bit(w, 16, 20);
+ let imm = sign_extend16(w & 0xffff);
+ Ok(Instruction::with_text(
+ address,
+ raw,
+ mnemonic,
+ format!("{}, {}, {:#x}", gpr(rt), gpr(rs), imm as u16),
+ 4,
+ ))
+}
+
+fn decode_lui(w: u32, address: u64, raw: Vec<u8>) -> Result<Instruction> {
+ let rt = bit(w, 16, 20);
+ let imm = w & 0xffff;
+ Ok(Instruction::with_text(
+ address,
+ raw,
+ "lui",
+ format!("{}, #{:#x}", gpr(rt), imm),
+ 4,
+ ))
+}
+
+fn decode_load_store(w: u32, address: u64, raw: Vec<u8>, mnemonic: &str) -> Result<Instruction> {
+ let rs = bit(w, 21, 25);
+ let rt = bit(w, 16, 20);
+ let imm = sign_extend16(w & 0xffff);
+ Ok(Instruction::with_text(
+ address,
+ raw,
+ mnemonic,
+ format!("{}, {:#x}({})", gpr(rt), imm, gpr(rs)),
+ 4,
+ ))
+}
diff --git a/crates/ghidrust-decode/src/arch/mips/mod.rs b/crates/ghidrust-decode/src/arch/mips/mod.rs
new file mode 100644
index 0000000..d71648f
--- /dev/null
+++ b/crates/ghidrust-decode/src/arch/mips/mod.rs
@@ -0,0 +1,119 @@
+mod decode;
+mod regs;
+mod util;
+
+use crate::arch::ArchDecode;
+use crate::error::{Error, Result};
+use crate::group::GroupId;
+use crate::insn::{InsnDetail, InsnId, Instruction};
+use crate::names;
+use crate::option::EngineOptions;
+use crate::reg::RegId;
+use crate::support::{Arch, Mode};
+
+pub struct MipsDecoder {
+ big_endian: bool,
+ mips64: bool,
+}
+
+impl ArchDecode for MipsDecoder {
+ fn arch(&self) -> Arch {
+ Arch::Mips
+ }
+
+ fn open(mode: Mode) -> Result<Self> {
+ if !mode.is_valid_for(Arch::Mips) {
+ return Err(Error::Mode(format!("invalid MIPS mode {:#x}", mode.bits())));
+ }
+ let big_endian = true;
+ let mips64 = mode.contains(Mode::MIPS64) || mode.contains(Mode::MODE_64);
+ Ok(Self { big_endian, mips64 })
+ }
+
+ fn decode_one(&self, bytes: &[u8], address: u64, opts: &EngineOptions) -> Result<Instruction> {
+ let mut insn = decode::decode(bytes, address, self.big_endian, self.mips64)?;
+ insn.id = names::insn_id_for_mnemonic(Arch::Mips, &insn.mnemonic);
+ if opts.detail {
+ insn.detail = Some(InsnDetail {
+ groups: groups_for_mnemonic(&insn.mnemonic),
+ ..InsnDetail::default()
+ });
+ }
+ Ok(insn)
+ }
+}
+
+fn groups_for_mnemonic(mnemonic: &str) -> Vec<GroupId> {
+ match mnemonic {
+ "j" | "beq" | "bne" | "blez" | "bgtz" | "bltz" | "bgez" => {
+ vec![GroupId::Jump, GroupId::BranchRelative]
+ }
+ "jal" | "jalr" | "bltzal" | "bgezal" => vec![GroupId::Call, GroupId::BranchRelative],
+ "jr" => vec![GroupId::Jump],
+ "syscall" | "break" => vec![GroupId::Int],
+ _ => Vec::new(),
+ }
+}
+
+pub fn reg_name(reg: RegId) -> Option<&'static str> {
+ Some(regs::gpr(reg.index() as u32))
+}
+
+pub fn insn_name(id: InsnId) -> Option<&'static str> {
+ match id.raw() {
+ 1 => Some("addu"),
+ 2 => Some("lw"),
+ 3 => Some("sw"),
+ 4 => Some("jal"),
+ 5 => Some("beq"),
+ _ => None,
+ }
+}
+
+pub fn group_name(group: GroupId) -> Option<&'static str> {
+ match group {
+ GroupId::Jump => Some("jump"),
+ GroupId::Call => Some("call"),
+ GroupId::Int => Some("int"),
+ GroupId::BranchRelative => Some("branch_relative"),
+ _ => None,
+ }
+}
+
+pub fn insn_id_for_mnemonic(mnemonic: &str) -> InsnId {
+ let id = match mnemonic {
+ "add" | "addu" => 1,
+ "lw" => 2,
+ "sw" => 3,
+ "jal" | "jalr" => 4,
+ "beq" | "bne" => 5,
+ _ => 0,
+ };
+ InsnId(id)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::engine::Engine;
+
+ #[test]
+ fn mips_addu_lw_sw() {
+ let mut eng = Engine::open(Arch::Mips, Mode::MIPS32).unwrap();
+ // addu $t0, $t1, $t2 -> 0x012a4021 (BE)
+ let add = eng
+ .disasm_one(&[0x01, 0x2a, 0x40, 0x21], 0x1000)
+ .unwrap();
+ assert_eq!(add.mnemonic, "addu");
+ // lw $t0, 4($sp) -> 8faf0004
+ let lw = eng.disasm_one(&[0x8f, 0xaf, 0x00, 0x04], 0x1004).unwrap();
+ assert_eq!(lw.mnemonic, "lw");
+ }
+
+ #[test]
+ fn mips_jal() {
+ let mut eng = Engine::open(Arch::Mips, Mode::MIPS32).unwrap();
+ let jal = eng.disasm_one(&[0x0c, 0x00, 0x00, 0x00], 0x0).unwrap();
+ assert_eq!(jal.mnemonic, "jal");
+ }
+}
diff --git a/crates/ghidrust-decode/src/arch/mips/regs.rs b/crates/ghidrust-decode/src/arch/mips/regs.rs
new file mode 100644
index 0000000..348c600
--- /dev/null
+++ b/crates/ghidrust-decode/src/arch/mips/regs.rs
@@ -0,0 +1,37 @@
+pub fn gpr(n: u32) -> &'static str {
+ match n & 0x1f {
+ 0 => "zero",
+ 1 => "at",
+ 2 => "v0",
+ 3 => "v1",
+ 4 => "a0",
+ 5 => "a1",
+ 6 => "a2",
+ 7 => "a3",
+ 8 => "t0",
+ 9 => "t1",
+ 10 => "t2",
+ 11 => "t3",
+ 12 => "t4",
+ 13 => "t5",
+ 14 => "t6",
+ 15 => "t7",
+ 16 => "s0",
+ 17 => "s1",
+ 18 => "s2",
+ 19 => "s3",
+ 20 => "s4",
+ 21 => "s5",
+ 22 => "s6",
+ 23 => "s7",
+ 24 => "t8",
+ 25 => "t9",
+ 26 => "k0",
+ 27 => "k1",
+ 28 => "gp",
+ 29 => "sp",
+ 30 => "fp",
+ 31 => "ra",
+ _ => "zero",
+ }
+}
diff --git a/crates/ghidrust-decode/src/arch/mips/util.rs b/crates/ghidrust-decode/src/arch/mips/util.rs
new file mode 100644
index 0000000..497ec2d
--- /dev/null
+++ b/crates/ghidrust-decode/src/arch/mips/util.rs
@@ -0,0 +1,28 @@
+use crate::error::{Error, Result};
+
+pub fn read_u32(bytes: &[u8], big_endian: bool) -> Result<u32> {
+ if bytes.len() < 4 {
+ return Err(Error::Decode("truncated MIPS word".into()));
+ }
+ Ok(if big_endian {
+ u32::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])
+ } else {
+ u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])
+ })
+}
+
+pub fn sign_extend16(v: u32) -> i32 {
+ ((v << 16) as i32) >> 16
+}
+
+pub fn fmt_imm(v: i32) -> String {
+ if v < 0 {
+ format!("-{:#x}", -v)
+ } else {
+ format!("{v:#x}")
+ }
+}
+
+pub fn bit(w: u32, lo: u32, hi: u32) -> u32 {
+ (w >> lo) & ((1u32 << (hi - lo + 1)) - 1)
+}
diff --git a/crates/ghidrust-decode/src/arch/mod.rs b/crates/ghidrust-decode/src/arch/mod.rs
new file mode 100644
index 0000000..425a31e
--- /dev/null
+++ b/crates/ghidrust-decode/src/arch/mod.rs
@@ -0,0 +1,119 @@
+pub mod aarch64;
+pub mod alpha;
+pub mod arc;
+pub mod arm;
+pub mod bpf;
+pub mod evm;
+pub mod hppa;
+pub mod leb128;
+pub mod loongarch;
+pub mod m680x;
+pub mod m68k;
+pub mod mips;
+pub mod mos65xx;
+pub mod ppc;
+pub mod riscv;
+pub mod sh;
+pub mod sparc;
+pub mod sysz;
+pub mod tms320c64x;
+pub mod tricore;
+pub mod wasm;
+pub mod x86;
+pub mod xcore;
+pub mod xtensa;
+
+use crate::error::{Error, Result};
+use crate::insn::Instruction;
+use crate::option::EngineOptions;
+use crate::support::{Arch, Mode};
+
+pub trait ArchDecode: Send {
+ fn arch(&self) -> Arch;
+
+ fn open(mode: Mode) -> Result<Self>
+ where
+ Self: Sized;
+
+ fn decode_one(&self, bytes: &[u8], address: u64, opts: &EngineOptions) -> Result<Instruction>;
+
+ fn decode_many(
+ &self,
+ bytes: &[u8],
+ address: u64,
+ count: usize,
+ opts: &EngineOptions,
+ ) -> Result<Vec<Instruction>> {
+ let mut out = Vec::new();
+ let mut off = 0usize;
+ let mut va = address;
+ for _ in 0..count {
+ if off >= bytes.len() {
+ break;
+ }
+ match self.decode_one(&bytes[off..], va, opts) {
+ Ok(insn) => {
+ let len = insn.length as usize;
+ if len == 0 {
+ return Err(Error::Decode("zero-length instruction".into()));
+ }
+ off += len;
+ va = va.wrapping_add(len as u64);
+ out.push(insn);
+ }
+ Err(e) => {
+ if out.is_empty() {
+ return Err(e);
+ }
+ break;
+ }
+ }
+ }
+ Ok(out)
+ }
+}
+
+pub fn open_decoder(arch: Arch, mode: Mode) -> Result<Box<dyn ArchDecode>> {
+ if !crate::support::support(crate::support::SupportQuery::Arch(arch)) {
+ return Err(Error::Arch(format!(
+ "architecture {:?} is not supported",
+ arch
+ )));
+ }
+ if !mode.is_valid_for(arch) {
+ return Err(Error::Mode(format!(
+ "invalid mode {:#x} for {:?}",
+ mode.bits(),
+ arch
+ )));
+ }
+ match arch {
+ Arch::Arm => Ok(Box::new(arm::ArmDecoder::open(mode)?)),
+ Arch::Arm64 => Ok(Box::new(aarch64::Aarch64Decoder::open(mode)?)),
+ Arch::Mips => Ok(Box::new(mips::MipsDecoder::open(mode)?)),
+ Arch::Ppc => Ok(Box::new(ppc::PpcDecoder::open(mode)?)),
+ Arch::X86 => Ok(Box::new(x86::X86Decoder::open(mode)?)),
+ Arch::Evm => Ok(Box::new(evm::EvmDecoder::open(mode)?)),
+ Arch::Mos65xx => Ok(Box::new(mos65xx::Mos65xxDecoder::open(mode)?)),
+ Arch::Wasm => Ok(Box::new(wasm::WasmDecoder::open(mode)?)),
+ Arch::Bpf => Ok(Box::new(bpf::BpfDecoder::open(mode)?)),
+ Arch::Riscv => Ok(Box::new(riscv::RiscvDecoder::open(mode)?)),
+ Arch::Sparc => Ok(Box::new(sparc::SparcDecoder::open(mode)?)),
+ Arch::Sysz => Ok(Box::new(sysz::SyszDecoder::open(mode)?)),
+ Arch::Xcore => Ok(Box::new(xcore::XcoreDecoder::open(mode)?)),
+ Arch::M68k => Ok(Box::new(m68k::M68kDecoder::open(mode)?)),
+ Arch::Tms320c64x => Ok(Box::new(tms320c64x::Tms320c64xDecoder::open(mode)?)),
+ Arch::M680x => Ok(Box::new(m680x::M680xDecoder::open(mode)?)),
+ Arch::Tricore => Ok(Box::new(tricore::TricoreDecoder::open(mode)?)),
+ Arch::Alpha => Ok(Box::new(alpha::AlphaDecoder::open(mode)?)),
+ Arch::Hppa => Ok(Box::new(hppa::HppaDecoder::open(mode)?)),
+ Arch::Loongarch => Ok(Box::new(loongarch::LoongarchDecoder::open(mode)?)),
+ Arch::Arc => Ok(Box::new(arc::ArcDecoder::open(mode)?)),
+ Arch::Sh => Ok(Box::new(sh::ShDecoder::open(mode)?)),
+ Arch::Xtensa => Ok(Box::new(xtensa::XtensaDecoder::open(mode)?)),
+ other => Err(Error::Arch(format!(
+ "decoder for {:?} is not implemented",
+ other
+ ))),
+ }
+}
diff --git a/crates/ghidrust-decode/src/arch/mos65xx/insn_id.rs b/crates/ghidrust-decode/src/arch/mos65xx/insn_id.rs
new file mode 100644
index 0000000..27f69f8
--- /dev/null
+++ b/crates/ghidrust-decode/src/arch/mos65xx/insn_id.rs
@@ -0,0 +1,161 @@
+use crate::insn::InsnId as CoreInsnId;
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct InsnId(pub u16);
+
+impl InsnId {
+ pub const INVALID: InsnId = InsnId(0);
+ pub const BRK: InsnId = InsnId(1);
+ pub const ORA: InsnId = InsnId(2);
+ pub const ASL: InsnId = InsnId(3);
+ pub const PHP: InsnId = InsnId(4);
+ pub const BPL: InsnId = InsnId(5);
+ pub const CLC: InsnId = InsnId(6);
+ pub const JSR: InsnId = InsnId(7);
+ pub const AND: InsnId = InsnId(8);
+ pub const BIT: InsnId = InsnId(9);
+ pub const ROL: InsnId = InsnId(10);
+ pub const PLP: InsnId = InsnId(11);
+ pub const BMI: InsnId = InsnId(12);
+ pub const SEC: InsnId = InsnId(13);
+ pub const RTI: InsnId = InsnId(14);
+ pub const EOR: InsnId = InsnId(15);
+ pub const LSR: InsnId = InsnId(16);
+ pub const PHA: InsnId = InsnId(17);
+ pub const JMP: InsnId = InsnId(18);
+ pub const BVC: InsnId = InsnId(19);
+ pub const CLI: InsnId = InsnId(20);
+ pub const RTS: InsnId = InsnId(21);
+ pub const ADC: InsnId = InsnId(22);
+ pub const ROR: InsnId = InsnId(23);
+ pub const PLA: InsnId = InsnId(24);
+ pub const BVS: InsnId = InsnId(25);
+ pub const SEI: InsnId = InsnId(26);
+ pub const STA: InsnId = InsnId(27);
+ pub const STY: InsnId = InsnId(28);
+ pub const STX: InsnId = InsnId(29);
+ pub const DEY: InsnId = InsnId(30);
+ pub const TXA: InsnId = InsnId(31);
+ pub const BCC: InsnId = InsnId(32);
+ pub const TYA: InsnId = InsnId(33);
+ pub const TXS: InsnId = InsnId(34);
+ pub const LDY: InsnId = InsnId(35);
+ pub const LDA: InsnId = InsnId(36);
+ pub const LDX: InsnId = InsnId(37);
+ pub const TAY: InsnId = InsnId(38);
+ pub const TAX: InsnId = InsnId(39);
+ pub const BCS: InsnId = InsnId(40);
+ pub const CLV: InsnId = InsnId(41);
+ pub const TSX: InsnId = InsnId(42);
+ pub const CPY: InsnId = InsnId(43);
+ pub const CMP: InsnId = InsnId(44);
+ pub const DEC: InsnId = InsnId(45);
+ pub const INY: InsnId = InsnId(46);
+ pub const DEX: InsnId = InsnId(47);
+ pub const BNE: InsnId = InsnId(48);
+ pub const CLD: InsnId = InsnId(49);
+ pub const CPX: InsnId = InsnId(50);
+ pub const SBC: InsnId = InsnId(51);
+ pub const INC: InsnId = InsnId(52);
+ pub const INX: InsnId = InsnId(53);
+ pub const NOP: InsnId = InsnId(54);
+ pub const BEQ: InsnId = InsnId(55);
+ pub const SED: InsnId = InsnId(56);
+ pub const BRA: InsnId = InsnId(57);
+ pub const PHX: InsnId = InsnId(58);
+ pub const PLX: InsnId = InsnId(59);
+ pub const PHY: InsnId = InsnId(60);
+ pub const PLY: InsnId = InsnId(61);
+ pub const STZ: InsnId = InsnId(62);
+ pub const TRB: InsnId = InsnId(63);
+ pub const TSB: InsnId = InsnId(64);
+ pub const STP: InsnId = InsnId(65);
+ pub const WAI: InsnId = InsnId(66);
+}
+
+pub fn insn_name(id: InsnId) -> Option<&'static str> {
+ match id.0 {
+ 0 => Some("nop"),
+ 1 => Some("brk"),
+ 2 => Some("ora"),
+ 3 => Some("asl"),
+ 4 => Some("php"),
+ 5 => Some("bpl"),
+ 6 => Some("clc"),
+ 7 => Some("jsr"),
+ 8 => Some("and"),
+ 9 => Some("bit"),
+ 10 => Some("rol"),
+ 11 => Some("plp"),
+ 12 => Some("bmi"),
+ 13 => Some("sec"),
+ 14 => Some("rti"),
+ 15 => Some("eor"),
+ 16 => Some("lsr"),
+ 17 => Some("pha"),
+ 18 => Some("jmp"),
+ 19 => Some("bvc"),
+ 20 => Some("cli"),
+ 21 => Some("rts"),
+ 22 => Some("adc"),
+ 23 => Some("ror"),
+ 24 => Some("pla"),
+ 25 => Some("bvs"),
+ 26 => Some("sei"),
+ 27 => Some("sta"),
+ 28 => Some("sty"),
+ 29 => Some("stx"),
+ 30 => Some("dey"),
+ 31 => Some("txa"),
+ 32 => Some("bcc"),
+ 33 => Some("tya"),
+ 34 => Some("txs"),
+ 35 => Some("ldy"),
+ 36 => Some("lda"),
+ 37 => Some("ldx"),
+ 38 => Some("tay"),
+ 39 => Some("tax"),
+ 40 => Some("bcs"),
+ 41 => Some("clv"),
+ 42 => Some("tsx"),
+ 43 => Some("cpy"),
+ 44 => Some("cmp"),
+ 45 => Some("dec"),
+ 46 => Some("iny"),
+ 47 => Some("dex"),
+ 48 => Some("bne"),
+ 49 => Some("cld"),
+ 50 => Some("cpx"),
+ 51 => Some("sbc"),
+ 52 => Some("inc"),
+ 53 => Some("inx"),
+ 54 => Some("nop"),
+ 55 => Some("beq"),
+ 56 => Some("sed"),
+ 57 => Some("bra"),
+ 58 => Some("phx"),
+ 59 => Some("plx"),
+ 60 => Some("phy"),
+ 61 => Some("ply"),
+ 62 => Some("stz"),
+ 63 => Some("trb"),
+ 64 => Some("tsb"),
+ 65 => Some("stp"),
+ 66 => Some("wai"),
+ _ => None,
+ }
+}
+
+pub fn to_core(id: InsnId) -> CoreInsnId {
+ CoreInsnId(id.0 as u32)
+}
+
+pub fn id_for_mnemonic(mnemonic: &str) -> InsnId {
+ for i in 0..=66u16 {
+ let id = InsnId(i);
+ if insn_name(id).is_some_and(|n| n == mnemonic) {
+ return id;
+ }
+ }
+ InsnId::INVALID
+}
diff --git a/crates/ghidrust-decode/src/arch/mos65xx/mod.rs b/crates/ghidrust-decode/src/arch/mos65xx/mod.rs
new file mode 100644
index 0000000..ae51ca2
--- /dev/null
+++ b/crates/ghidrust-decode/src/arch/mos65xx/mod.rs
@@ -0,0 +1,243 @@
+//! Hand-rolled MOS6502 / WDC65C02 decoder.
+
+mod insn_id;
+mod regs;
+mod table;
+
+use crate::arch::ArchDecode;
+use crate::error::{Error, Result};
+use crate::group::GroupId;
+use crate::insn::{InsnDetail, Instruction};
+use crate::names;
+use crate::option::EngineOptions;
+use crate::support::{Arch, Mode};
+
+pub use insn_id::InsnId;
+pub use regs::reg_name;
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum AddrMode {
+ None,
+ Imp,
+ Acc,
+ Imm,
+ Rel,
+ Zp,
+ ZpX,
+ ZpY,
+ Abs,
+ AbsX,
+ AbsY,
+ ZpInd,
+ ZpXInd,
+ ZpIndY,
+ AbsInd,
+ Int,
+ ZpRel,
+ AbsXInd,
+ AbsIndLong,
+ ZpIndLong,
+ ZpIndLongY,
+ AbsLong,
+ AbsLongX,
+ Sr,
+ SrIndY,
+ Block,
+}
+
+#[derive(Debug, Clone, Copy)]
+pub struct OpEntry {
+ pub mnemonic: &'static str,
+ pub insn: InsnId,
+ pub mode: AddrMode,
+ pub operand_bytes: u8,
+}
+
+pub struct Mos65xxDecoder {
+ mode: Mode,
+}
+
+pub(crate) fn decode_raw(bytes: &[u8], address: u64, mode: Mode) -> Result<Instruction> {
+ if bytes.is_empty() {
+ return Err(Error::Decode("empty input".into()));
+ }
+ let opcode = bytes[0];
+ let table = if mode.intersects(Mode::MOS65XX_65C02) {
+ &table::TABLE_65C02
+ } else {
+ &table::TABLE_6502
+ };
+ let entry = &table[opcode as usize];
+ let len = 1usize + entry.operand_bytes as usize;
+ if bytes.len() < len {
+ return Err(Error::Decode("truncated mos65xx instruction".into()));
+ }
+ let mnemonic = entry.mnemonic.to_string();
+ let operands = format_operands(entry.mode, &bytes[1..len], address, len)?;
+ Ok(Instruction::with_text(
+ address,
+ bytes[..len].to_vec(),
+ mnemonic,
+ operands,
+ len as u8,
+ ))
+}
+
+fn format_operands(
+ mode: AddrMode,
+ ops: &[u8],
+ address: u64,
+ total_len: usize,
+) -> Result<String> {
+ Ok(match mode {
+ AddrMode::None | AddrMode::Imp => String::new(),
+ AddrMode::Acc => "a".into(),
+ AddrMode::Imm => {
+ if ops.len() == 1 {
+ format!("#0x{:02x}", ops[0])
+ } else {
+ format!("#0x{:04x}", u16::from_le_bytes([ops[0], ops[1]]))
+ }
+ }
+ AddrMode::Zp => format!("0x{:02x}", ops[0]),
+ AddrMode::ZpX => format!("0x{:02x}, x", ops[0]),
+ AddrMode::ZpY => format!("0x{:02x}, y", ops[0]),
+ AddrMode::Abs => format!("0x{:04x}", u16::from_le_bytes([ops[0], ops[1]])),
+ AddrMode::AbsX => format!("0x{:04x}, x", u16::from_le_bytes([ops[0], ops[1]])),
+ AddrMode::AbsY => format!("0x{:04x}, y", u16::from_le_bytes([ops[0], ops[1]])),
+ AddrMode::ZpInd => format!("(0x{:02x})", ops[0]),
+ AddrMode::ZpXInd => format!("(0x{:02x}, x)", ops[0]),
+ AddrMode::ZpIndY => format!("(0x{:02x}), y", ops[0]),
+ AddrMode::AbsInd => format!("(0x{:04x})", u16::from_le_bytes([ops[0], ops[1]])),
+ AddrMode::Int => format!("0x{:02x}", ops[0]),
+ AddrMode::Rel => {
+ let off = ops[0] as i8 as i32;
+ let target = (address as i32 + total_len as i32 + off) as u16;
+ format!("0x{target:04x}")
+ }
+ AddrMode::ZpRel => {
+ let off = ops[1] as i8 as i32;
+ let target = (address as i32 + total_len as i32 + off) as u16;
+ format!("0x{:02x}, 0x{target:04x}", ops[0])
+ }
+ _ => ops
+ .iter()
+ .map(|b| format!("0x{b:02x}"))
+ .collect::<Vec<_>>()
+ .join(", "),
+ })
+}
+
+impl ArchDecode for Mos65xxDecoder {
+ fn arch(&self) -> Arch {
+ Arch::Mos65xx
+ }
+
+ fn open(mode: Mode) -> Result<Self> {
+ if !mode.is_valid_for(Arch::Mos65xx) {
+ return Err(Error::Mode(format!(
+ "invalid mos65xx mode {:#x}",
+ mode.bits()
+ )));
+ }
+ Ok(Self { mode })
+ }
+
+ fn decode_one(&self, bytes: &[u8], address: u64, opts: &EngineOptions) -> Result<Instruction> {
+ let mut insn = decode_raw(bytes, address, self.mode)?;
+ insn.id = names::insn_id_for_mnemonic(Arch::Mos65xx, &insn.mnemonic);
+ if opts.detail {
+ insn.detail = Some(InsnDetail {
+ groups: groups_for_mnemonic(&insn.mnemonic),
+ ..InsnDetail::default()
+ });
+ }
+ Ok(insn)
+ }
+}
+
+fn groups_for_mnemonic(mnemonic: &str) -> Vec<GroupId> {
+ match mnemonic {
+ "jmp" | "bra" => vec![GroupId::Jump],
+ "jsr" => vec![GroupId::Call],
+ "rts" | "rti" => vec![GroupId::Ret],
+ "brk" => vec![GroupId::Int],
+ m if m.starts_with('b') && m.len() == 3 => vec![GroupId::BranchRelative],
+ _ => Vec::new(),
+ }
+}
+
+pub fn insn_name(id: crate::insn::InsnId) -> Option<&'static str> {
+ insn_id::insn_name(InsnId(id.raw() as u16))
+}
+
+pub fn group_name(group: GroupId) -> Option<&'static str> {
+ match group {
+ GroupId::Jump => Some("jump"),
+ GroupId::Call => Some("call"),
+ GroupId::Ret => Some("ret"),
+ GroupId::Int => Some("int"),
+ GroupId::BranchRelative => Some("branch_relative"),
+ _ => None,
+ }
+}
+
+pub fn insn_id_for_mnemonic(mnemonic: &str) -> crate::insn::InsnId {
+ insn_id::to_core(insn_id::id_for_mnemonic(mnemonic))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::option::EngineOptions;
+
+ #[test]
+ fn mos6502_lda_imm_and_brk() {
+ let dec = Mos65xxDecoder::open(Mode::LITTLE_ENDIAN.union(Mode::MOS65XX_6502)).unwrap();
+ let lda = dec
+ .decode_one(&[0xa9, 0x42], 0x8000, &EngineOptions::default())
+ .unwrap();
+ assert_eq!(lda.mnemonic, "lda");
+ assert_eq!(lda.operands, "#0x42");
+ assert_eq!(lda.length, 2);
+
+ let brk = dec
+ .decode_one(&[0x00, 0xff], 0, &EngineOptions::default())
+ .unwrap();
+ assert_eq!(brk.mnemonic, "brk");
+ assert_eq!(brk.length, 2);
+ }
+
+ #[test]
+ fn mos6502_jsr_and_branch() {
+ let dec = Mos65xxDecoder::open(Mode::MOS65XX_6502).unwrap();
+ let jsr = dec
+ .decode_one(&[0x20, 0x34, 0x12], 0x1000, &EngineOptions::default())
+ .unwrap();
+ assert_eq!(jsr.mnemonic, "jsr");
+ assert_eq!(jsr.operands, "0x1234");
+ assert_eq!(jsr.length, 3);
+
+ let bne = dec
+ .decode_one(&[0xd0, 0x05], 0x2000, &EngineOptions::default())
+ .unwrap();
+ assert_eq!(bne.mnemonic, "bne");
+ assert_eq!(bne.operands, "0x2007");
+ }
+
+ #[test]
+ fn mos65c02_bra_and_stz() {
+ let dec = Mos65xxDecoder::open(Mode::MOS65XX_65C02).unwrap();
+ let bra = dec
+ .decode_one(&[0x80, 0x10], 0x3000, &EngineOptions::default())
+ .unwrap();
+ assert_eq!(bra.mnemonic, "bra");
+ assert_eq!(bra.length, 2);
+
+ let stz = dec
+ .decode_one(&[0x9c, 0x00, 0x40], 0, &EngineOptions::default())
+ .unwrap();
+ assert_eq!(stz.mnemonic, "stz");
+ assert_eq!(stz.length, 3);
+ }
+}
diff --git a/crates/ghidrust-decode/src/arch/mos65xx/regs.rs b/crates/ghidrust-decode/src/arch/mos65xx/regs.rs
new file mode 100644
index 0000000..5ad1f30
--- /dev/null
+++ b/crates/ghidrust-decode/src/arch/mos65xx/regs.rs
@@ -0,0 +1,18 @@
+use crate::reg::RegId;
+
+pub fn reg_name(reg: RegId) -> Option<&'static str> {
+ match reg.index() {
+ 1 => Some("a"),
+ 2 => Some("x"),
+ 3 => Some("y"),
+ 4 => Some("p"),
+ 5 => Some("sp"),
+ _ => None,
+ }
+}
+
+pub const REG_A: RegId = RegId::new(1);
+pub const REG_X: RegId = RegId::new(2);
+pub const REG_Y: RegId = RegId::new(3);
+pub const REG_P: RegId = RegId::new(4);
+pub const REG_SP: RegId = RegId::new(5);
diff --git a/crates/ghidrust-decode/src/arch/mos65xx/table.rs b/crates/ghidrust-decode/src/arch/mos65xx/table.rs
new file mode 100644
index 0000000..71cf5e4
--- /dev/null
+++ b/crates/ghidrust-decode/src/arch/mos65xx/table.rs
@@ -0,0 +1,521 @@
+//! Auto-generated 6502 / 65C02 opcode tables .
+
+use super::{AddrMode, InsnId, OpEntry};
+
+pub const TABLE_6502: [OpEntry; 256] = [
+ OpEntry { mnemonic: "brk", insn: InsnId::BRK, mode: AddrMode::Int, operand_bytes: 1 }, // 0x00
+ OpEntry { mnemonic: "ora", insn: InsnId::ORA, mode: AddrMode::ZpXInd, operand_bytes: 1 }, // 0x01
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x02
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x03
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x04
+ OpEntry { mnemonic: "ora", insn: InsnId::ORA, mode: AddrMode::Zp, operand_bytes: 1 }, // 0x05
+ OpEntry { mnemonic: "asl", insn: InsnId::ASL, mode: AddrMode::Zp, operand_bytes: 1 }, // 0x06
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x07
+ OpEntry { mnemonic: "php", insn: InsnId::PHP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x08
+ OpEntry { mnemonic: "ora", insn: InsnId::ORA, mode: AddrMode::Imm, operand_bytes: 1 }, // 0x09
+ OpEntry { mnemonic: "asl", insn: InsnId::ASL, mode: AddrMode::Acc, operand_bytes: 0 }, // 0x0a
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x0b
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x0c
+ OpEntry { mnemonic: "ora", insn: InsnId::ORA, mode: AddrMode::Abs, operand_bytes: 2 }, // 0x0d
+ OpEntry { mnemonic: "asl", insn: InsnId::ASL, mode: AddrMode::Abs, operand_bytes: 2 }, // 0x0e
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x0f
+ OpEntry { mnemonic: "bpl", insn: InsnId::BPL, mode: AddrMode::Rel, operand_bytes: 1 }, // 0x10
+ OpEntry { mnemonic: "ora", insn: InsnId::ORA, mode: AddrMode::ZpIndY, operand_bytes: 1 }, // 0x11
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x12
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x13
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x14
+ OpEntry { mnemonic: "ora", insn: InsnId::ORA, mode: AddrMode::ZpX, operand_bytes: 1 }, // 0x15
+ OpEntry { mnemonic: "asl", insn: InsnId::ASL, mode: AddrMode::ZpX, operand_bytes: 1 }, // 0x16
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x17
+ OpEntry { mnemonic: "clc", insn: InsnId::CLC, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x18
+ OpEntry { mnemonic: "ora", insn: InsnId::ORA, mode: AddrMode::AbsY, operand_bytes: 2 }, // 0x19
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x1a
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x1b
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x1c
+ OpEntry { mnemonic: "ora", insn: InsnId::ORA, mode: AddrMode::AbsX, operand_bytes: 2 }, // 0x1d
+ OpEntry { mnemonic: "asl", insn: InsnId::ASL, mode: AddrMode::AbsX, operand_bytes: 2 }, // 0x1e
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x1f
+ OpEntry { mnemonic: "jsr", insn: InsnId::JSR, mode: AddrMode::Abs, operand_bytes: 2 }, // 0x20
+ OpEntry { mnemonic: "and", insn: InsnId::AND, mode: AddrMode::ZpXInd, operand_bytes: 1 }, // 0x21
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x22
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x23
+ OpEntry { mnemonic: "bit", insn: InsnId::BIT, mode: AddrMode::Zp, operand_bytes: 1 }, // 0x24
+ OpEntry { mnemonic: "and", insn: InsnId::AND, mode: AddrMode::Zp, operand_bytes: 1 }, // 0x25
+ OpEntry { mnemonic: "rol", insn: InsnId::ROL, mode: AddrMode::Zp, operand_bytes: 1 }, // 0x26
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x27
+ OpEntry { mnemonic: "plp", insn: InsnId::PLP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x28
+ OpEntry { mnemonic: "and", insn: InsnId::AND, mode: AddrMode::Imm, operand_bytes: 1 }, // 0x29
+ OpEntry { mnemonic: "rol", insn: InsnId::ROL, mode: AddrMode::Acc, operand_bytes: 0 }, // 0x2a
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x2b
+ OpEntry { mnemonic: "bit", insn: InsnId::BIT, mode: AddrMode::Abs, operand_bytes: 2 }, // 0x2c
+ OpEntry { mnemonic: "and", insn: InsnId::AND, mode: AddrMode::Abs, operand_bytes: 2 }, // 0x2d
+ OpEntry { mnemonic: "rol", insn: InsnId::ROL, mode: AddrMode::Abs, operand_bytes: 2 }, // 0x2e
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x2f
+ OpEntry { mnemonic: "bmi", insn: InsnId::BMI, mode: AddrMode::Rel, operand_bytes: 1 }, // 0x30
+ OpEntry { mnemonic: "and", insn: InsnId::AND, mode: AddrMode::ZpIndY, operand_bytes: 1 }, // 0x31
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x32
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x33
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x34
+ OpEntry { mnemonic: "and", insn: InsnId::AND, mode: AddrMode::ZpX, operand_bytes: 1 }, // 0x35
+ OpEntry { mnemonic: "rol", insn: InsnId::ROL, mode: AddrMode::ZpX, operand_bytes: 1 }, // 0x36
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x37
+ OpEntry { mnemonic: "sec", insn: InsnId::SEC, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x38
+ OpEntry { mnemonic: "and", insn: InsnId::AND, mode: AddrMode::AbsY, operand_bytes: 2 }, // 0x39
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x3a
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x3b
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x3c
+ OpEntry { mnemonic: "and", insn: InsnId::AND, mode: AddrMode::AbsX, operand_bytes: 2 }, // 0x3d
+ OpEntry { mnemonic: "rol", insn: InsnId::ROL, mode: AddrMode::AbsX, operand_bytes: 2 }, // 0x3e
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x3f
+ OpEntry { mnemonic: "rti", insn: InsnId::RTI, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x40
+ OpEntry { mnemonic: "eor", insn: InsnId::EOR, mode: AddrMode::ZpXInd, operand_bytes: 1 }, // 0x41
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x42
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x43
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x44
+ OpEntry { mnemonic: "eor", insn: InsnId::EOR, mode: AddrMode::Zp, operand_bytes: 1 }, // 0x45
+ OpEntry { mnemonic: "lsr", insn: InsnId::LSR, mode: AddrMode::Zp, operand_bytes: 1 }, // 0x46
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x47
+ OpEntry { mnemonic: "pha", insn: InsnId::PHA, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x48
+ OpEntry { mnemonic: "eor", insn: InsnId::EOR, mode: AddrMode::Imm, operand_bytes: 1 }, // 0x49
+ OpEntry { mnemonic: "lsr", insn: InsnId::LSR, mode: AddrMode::Acc, operand_bytes: 0 }, // 0x4a
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x4b
+ OpEntry { mnemonic: "jmp", insn: InsnId::JMP, mode: AddrMode::Abs, operand_bytes: 2 }, // 0x4c
+ OpEntry { mnemonic: "eor", insn: InsnId::EOR, mode: AddrMode::Abs, operand_bytes: 2 }, // 0x4d
+ OpEntry { mnemonic: "lsr", insn: InsnId::LSR, mode: AddrMode::Abs, operand_bytes: 2 }, // 0x4e
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x4f
+ OpEntry { mnemonic: "bvc", insn: InsnId::BVC, mode: AddrMode::Rel, operand_bytes: 1 }, // 0x50
+ OpEntry { mnemonic: "eor", insn: InsnId::EOR, mode: AddrMode::ZpIndY, operand_bytes: 1 }, // 0x51
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x52
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x53
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x54
+ OpEntry { mnemonic: "eor", insn: InsnId::EOR, mode: AddrMode::ZpX, operand_bytes: 1 }, // 0x55
+ OpEntry { mnemonic: "lsr", insn: InsnId::LSR, mode: AddrMode::ZpX, operand_bytes: 1 }, // 0x56
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x57
+ OpEntry { mnemonic: "cli", insn: InsnId::CLI, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x58
+ OpEntry { mnemonic: "eor", insn: InsnId::EOR, mode: AddrMode::AbsY, operand_bytes: 2 }, // 0x59
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x5a
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x5b
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x5c
+ OpEntry { mnemonic: "eor", insn: InsnId::EOR, mode: AddrMode::AbsX, operand_bytes: 2 }, // 0x5d
+ OpEntry { mnemonic: "lsr", insn: InsnId::LSR, mode: AddrMode::AbsX, operand_bytes: 2 }, // 0x5e
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x5f
+ OpEntry { mnemonic: "rts", insn: InsnId::RTS, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x60
+ OpEntry { mnemonic: "adc", insn: InsnId::ADC, mode: AddrMode::ZpXInd, operand_bytes: 1 }, // 0x61
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x62
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x63
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x64
+ OpEntry { mnemonic: "adc", insn: InsnId::ADC, mode: AddrMode::Zp, operand_bytes: 1 }, // 0x65
+ OpEntry { mnemonic: "ror", insn: InsnId::ROR, mode: AddrMode::Zp, operand_bytes: 1 }, // 0x66
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x67
+ OpEntry { mnemonic: "pla", insn: InsnId::PLA, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x68
+ OpEntry { mnemonic: "adc", insn: InsnId::ADC, mode: AddrMode::Imm, operand_bytes: 1 }, // 0x69
+ OpEntry { mnemonic: "ror", insn: InsnId::ROR, mode: AddrMode::Acc, operand_bytes: 0 }, // 0x6a
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x6b
+ OpEntry { mnemonic: "jmp", insn: InsnId::JMP, mode: AddrMode::AbsInd, operand_bytes: 2 }, // 0x6c
+ OpEntry { mnemonic: "adc", insn: InsnId::ADC, mode: AddrMode::Abs, operand_bytes: 2 }, // 0x6d
+ OpEntry { mnemonic: "ror", insn: InsnId::ROR, mode: AddrMode::Abs, operand_bytes: 2 }, // 0x6e
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x6f
+ OpEntry { mnemonic: "bvs", insn: InsnId::BVS, mode: AddrMode::Rel, operand_bytes: 1 }, // 0x70
+ OpEntry { mnemonic: "adc", insn: InsnId::ADC, mode: AddrMode::ZpIndY, operand_bytes: 1 }, // 0x71
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x72
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x73
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x74
+ OpEntry { mnemonic: "adc", insn: InsnId::ADC, mode: AddrMode::ZpX, operand_bytes: 1 }, // 0x75
+ OpEntry { mnemonic: "ror", insn: InsnId::ROR, mode: AddrMode::ZpX, operand_bytes: 1 }, // 0x76
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x77
+ OpEntry { mnemonic: "sei", insn: InsnId::SEI, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x78
+ OpEntry { mnemonic: "adc", insn: InsnId::ADC, mode: AddrMode::AbsY, operand_bytes: 2 }, // 0x79
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x7a
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x7b
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x7c
+ OpEntry { mnemonic: "adc", insn: InsnId::ADC, mode: AddrMode::AbsX, operand_bytes: 2 }, // 0x7d
+ OpEntry { mnemonic: "ror", insn: InsnId::ROR, mode: AddrMode::AbsX, operand_bytes: 2 }, // 0x7e
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x7f
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x80
+ OpEntry { mnemonic: "sta", insn: InsnId::STA, mode: AddrMode::ZpXInd, operand_bytes: 1 }, // 0x81
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x82
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x83
+ OpEntry { mnemonic: "sty", insn: InsnId::STY, mode: AddrMode::Zp, operand_bytes: 1 }, // 0x84
+ OpEntry { mnemonic: "sta", insn: InsnId::STA, mode: AddrMode::Zp, operand_bytes: 1 }, // 0x85
+ OpEntry { mnemonic: "stx", insn: InsnId::STX, mode: AddrMode::Zp, operand_bytes: 1 }, // 0x86
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x87
+ OpEntry { mnemonic: "dey", insn: InsnId::DEY, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x88
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x89
+ OpEntry { mnemonic: "txa", insn: InsnId::TXA, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x8a
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x8b
+ OpEntry { mnemonic: "sty", insn: InsnId::STY, mode: AddrMode::Abs, operand_bytes: 2 }, // 0x8c
+ OpEntry { mnemonic: "sta", insn: InsnId::STA, mode: AddrMode::Abs, operand_bytes: 2 }, // 0x8d
+ OpEntry { mnemonic: "stx", insn: InsnId::STX, mode: AddrMode::Abs, operand_bytes: 2 }, // 0x8e
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x8f
+ OpEntry { mnemonic: "bcc", insn: InsnId::BCC, mode: AddrMode::Rel, operand_bytes: 1 }, // 0x90
+ OpEntry { mnemonic: "sta", insn: InsnId::STA, mode: AddrMode::ZpIndY, operand_bytes: 1 }, // 0x91
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x92
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x93
+ OpEntry { mnemonic: "sty", insn: InsnId::STY, mode: AddrMode::ZpX, operand_bytes: 1 }, // 0x94
+ OpEntry { mnemonic: "sta", insn: InsnId::STA, mode: AddrMode::ZpX, operand_bytes: 1 }, // 0x95
+ OpEntry { mnemonic: "stx", insn: InsnId::STX, mode: AddrMode::ZpY, operand_bytes: 1 }, // 0x96
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x97
+ OpEntry { mnemonic: "tya", insn: InsnId::TYA, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x98
+ OpEntry { mnemonic: "sta", insn: InsnId::STA, mode: AddrMode::AbsY, operand_bytes: 2 }, // 0x99
+ OpEntry { mnemonic: "txs", insn: InsnId::TXS, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x9a
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x9b
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x9c
+ OpEntry { mnemonic: "sta", insn: InsnId::STA, mode: AddrMode::AbsX, operand_bytes: 2 }, // 0x9d
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x9e
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0x9f
+ OpEntry { mnemonic: "ldy", insn: InsnId::LDY, mode: AddrMode::Imm, operand_bytes: 1 }, // 0xa0
+ OpEntry { mnemonic: "lda", insn: InsnId::LDA, mode: AddrMode::ZpXInd, operand_bytes: 1 }, // 0xa1
+ OpEntry { mnemonic: "ldx", insn: InsnId::LDX, mode: AddrMode::Imm, operand_bytes: 1 }, // 0xa2
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0xa3
+ OpEntry { mnemonic: "ldy", insn: InsnId::LDY, mode: AddrMode::Zp, operand_bytes: 1 }, // 0xa4
+ OpEntry { mnemonic: "lda", insn: InsnId::LDA, mode: AddrMode::Zp, operand_bytes: 1 }, // 0xa5
+ OpEntry { mnemonic: "ldx", insn: InsnId::LDX, mode: AddrMode::Zp, operand_bytes: 1 }, // 0xa6
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0xa7
+ OpEntry { mnemonic: "tay", insn: InsnId::TAY, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xa8
+ OpEntry { mnemonic: "lda", insn: InsnId::LDA, mode: AddrMode::Imm, operand_bytes: 1 }, // 0xa9
+ OpEntry { mnemonic: "tax", insn: InsnId::TAX, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xaa
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0xab
+ OpEntry { mnemonic: "ldy", insn: InsnId::LDY, mode: AddrMode::Abs, operand_bytes: 2 }, // 0xac
+ OpEntry { mnemonic: "lda", insn: InsnId::LDA, mode: AddrMode::Abs, operand_bytes: 2 }, // 0xad
+ OpEntry { mnemonic: "ldx", insn: InsnId::LDX, mode: AddrMode::Abs, operand_bytes: 2 }, // 0xae
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0xaf
+ OpEntry { mnemonic: "bcs", insn: InsnId::BCS, mode: AddrMode::Rel, operand_bytes: 1 }, // 0xb0
+ OpEntry { mnemonic: "lda", insn: InsnId::LDA, mode: AddrMode::ZpIndY, operand_bytes: 1 }, // 0xb1
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0xb2
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0xb3
+ OpEntry { mnemonic: "ldy", insn: InsnId::LDY, mode: AddrMode::ZpX, operand_bytes: 1 }, // 0xb4
+ OpEntry { mnemonic: "lda", insn: InsnId::LDA, mode: AddrMode::ZpX, operand_bytes: 1 }, // 0xb5
+ OpEntry { mnemonic: "ldx", insn: InsnId::LDX, mode: AddrMode::ZpY, operand_bytes: 1 }, // 0xb6
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0xb7
+ OpEntry { mnemonic: "clv", insn: InsnId::CLV, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xb8
+ OpEntry { mnemonic: "lda", insn: InsnId::LDA, mode: AddrMode::AbsY, operand_bytes: 2 }, // 0xb9
+ OpEntry { mnemonic: "tsx", insn: InsnId::TSX, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xba
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0xbb
+ OpEntry { mnemonic: "ldy", insn: InsnId::LDY, mode: AddrMode::AbsX, operand_bytes: 2 }, // 0xbc
+ OpEntry { mnemonic: "lda", insn: InsnId::LDA, mode: AddrMode::AbsX, operand_bytes: 2 }, // 0xbd
+ OpEntry { mnemonic: "ldx", insn: InsnId::LDX, mode: AddrMode::AbsY, operand_bytes: 2 }, // 0xbe
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0xbf
+ OpEntry { mnemonic: "cpy", insn: InsnId::CPY, mode: AddrMode::Imm, operand_bytes: 1 }, // 0xc0
+ OpEntry { mnemonic: "cmp", insn: InsnId::CMP, mode: AddrMode::ZpXInd, operand_bytes: 1 }, // 0xc1
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0xc2
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0xc3
+ OpEntry { mnemonic: "cpy", insn: InsnId::CPY, mode: AddrMode::Zp, operand_bytes: 1 }, // 0xc4
+ OpEntry { mnemonic: "cmp", insn: InsnId::CMP, mode: AddrMode::Zp, operand_bytes: 1 }, // 0xc5
+ OpEntry { mnemonic: "dec", insn: InsnId::DEC, mode: AddrMode::Zp, operand_bytes: 1 }, // 0xc6
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0xc7
+ OpEntry { mnemonic: "iny", insn: InsnId::INY, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xc8
+ OpEntry { mnemonic: "cmp", insn: InsnId::CMP, mode: AddrMode::Imm, operand_bytes: 1 }, // 0xc9
+ OpEntry { mnemonic: "dex", insn: InsnId::DEX, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xca
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0xcb
+ OpEntry { mnemonic: "cpy", insn: InsnId::CPY, mode: AddrMode::Abs, operand_bytes: 2 }, // 0xcc
+ OpEntry { mnemonic: "cmp", insn: InsnId::CMP, mode: AddrMode::Abs, operand_bytes: 2 }, // 0xcd
+ OpEntry { mnemonic: "dec", insn: InsnId::DEC, mode: AddrMode::Abs, operand_bytes: 2 }, // 0xce
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0xcf
+ OpEntry { mnemonic: "bne", insn: InsnId::BNE, mode: AddrMode::Rel, operand_bytes: 1 }, // 0xd0
+ OpEntry { mnemonic: "cmp", insn: InsnId::CMP, mode: AddrMode::ZpIndY, operand_bytes: 1 }, // 0xd1
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0xd2
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0xd3
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0xd4
+ OpEntry { mnemonic: "cmp", insn: InsnId::CMP, mode: AddrMode::ZpX, operand_bytes: 1 }, // 0xd5
+ OpEntry { mnemonic: "dec", insn: InsnId::DEC, mode: AddrMode::ZpX, operand_bytes: 1 }, // 0xd6
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0xd7
+ OpEntry { mnemonic: "cld", insn: InsnId::CLD, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xd8
+ OpEntry { mnemonic: "cmp", insn: InsnId::CMP, mode: AddrMode::AbsY, operand_bytes: 2 }, // 0xd9
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0xda
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0xdb
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0xdc
+ OpEntry { mnemonic: "cmp", insn: InsnId::CMP, mode: AddrMode::AbsX, operand_bytes: 2 }, // 0xdd
+ OpEntry { mnemonic: "dec", insn: InsnId::DEC, mode: AddrMode::AbsX, operand_bytes: 2 }, // 0xde
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0xdf
+ OpEntry { mnemonic: "cpx", insn: InsnId::CPX, mode: AddrMode::Imm, operand_bytes: 1 }, // 0xe0
+ OpEntry { mnemonic: "sbc", insn: InsnId::SBC, mode: AddrMode::ZpXInd, operand_bytes: 1 }, // 0xe1
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0xe2
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0xe3
+ OpEntry { mnemonic: "cpx", insn: InsnId::CPX, mode: AddrMode::Zp, operand_bytes: 1 }, // 0xe4
+ OpEntry { mnemonic: "sbc", insn: InsnId::SBC, mode: AddrMode::Zp, operand_bytes: 1 }, // 0xe5
+ OpEntry { mnemonic: "inc", insn: InsnId::INC, mode: AddrMode::Zp, operand_bytes: 1 }, // 0xe6
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0xe7
+ OpEntry { mnemonic: "inx", insn: InsnId::INX, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xe8
+ OpEntry { mnemonic: "sbc", insn: InsnId::SBC, mode: AddrMode::Imm, operand_bytes: 1 }, // 0xe9
+ OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xea
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0xeb
+ OpEntry { mnemonic: "cpx", insn: InsnId::CPX, mode: AddrMode::Abs, operand_bytes: 2 }, // 0xec
+ OpEntry { mnemonic: "sbc", insn: InsnId::SBC, mode: AddrMode::Abs, operand_bytes: 2 }, // 0xed
+ OpEntry { mnemonic: "inc", insn: InsnId::INC, mode: AddrMode::Abs, operand_bytes: 2 }, // 0xee
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0xef
+ OpEntry { mnemonic: "beq", insn: InsnId::BEQ, mode: AddrMode::Rel, operand_bytes: 1 }, // 0xf0
+ OpEntry { mnemonic: "sbc", insn: InsnId::SBC, mode: AddrMode::ZpIndY, operand_bytes: 1 }, // 0xf1
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0xf2
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0xf3
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0xf4
+ OpEntry { mnemonic: "sbc", insn: InsnId::SBC, mode: AddrMode::ZpX, operand_bytes: 1 }, // 0xf5
+ OpEntry { mnemonic: "inc", insn: InsnId::INC, mode: AddrMode::ZpX, operand_bytes: 1 }, // 0xf6
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0xf7
+ OpEntry { mnemonic: "sed", insn: InsnId::SED, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xf8
+ OpEntry { mnemonic: "sbc", insn: InsnId::SBC, mode: AddrMode::AbsY, operand_bytes: 2 }, // 0xf9
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0xfa
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0xfb
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0xfc
+ OpEntry { mnemonic: "sbc", insn: InsnId::SBC, mode: AddrMode::AbsX, operand_bytes: 2 }, // 0xfd
+ OpEntry { mnemonic: "inc", insn: InsnId::INC, mode: AddrMode::AbsX, operand_bytes: 2 }, // 0xfe
+ OpEntry { mnemonic: "nop", insn: InsnId::INVALID, mode: AddrMode::None, operand_bytes: 0 }, // 0xff
+];
+
+pub const TABLE_65C02: [OpEntry; 256] = [
+ OpEntry { mnemonic: "brk", insn: InsnId::BRK, mode: AddrMode::Int, operand_bytes: 1 }, // 0x00
+ OpEntry { mnemonic: "ora", insn: InsnId::ORA, mode: AddrMode::ZpXInd, operand_bytes: 1 }, // 0x01
+ OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 1 }, // 0x02
+ OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x03
+ OpEntry { mnemonic: "tsb", insn: InsnId::TSB, mode: AddrMode::Zp, operand_bytes: 1 }, // 0x04
+ OpEntry { mnemonic: "ora", insn: InsnId::ORA, mode: AddrMode::Zp, operand_bytes: 1 }, // 0x05
+ OpEntry { mnemonic: "asl", insn: InsnId::ASL, mode: AddrMode::Zp, operand_bytes: 1 }, // 0x06
+ OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x07
+ OpEntry { mnemonic: "php", insn: InsnId::PHP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x08
+ OpEntry { mnemonic: "ora", insn: InsnId::ORA, mode: AddrMode::Imm, operand_bytes: 1 }, // 0x09
+ OpEntry { mnemonic: "asl", insn: InsnId::ASL, mode: AddrMode::Acc, operand_bytes: 0 }, // 0x0a
+ OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x0b
+ OpEntry { mnemonic: "tsb", insn: InsnId::TSB, mode: AddrMode::Abs, operand_bytes: 2 }, // 0x0c
+ OpEntry { mnemonic: "ora", insn: InsnId::ORA, mode: AddrMode::Abs, operand_bytes: 2 }, // 0x0d
+ OpEntry { mnemonic: "asl", insn: InsnId::ASL, mode: AddrMode::Abs, operand_bytes: 2 }, // 0x0e
+ OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x0f
+ OpEntry { mnemonic: "bpl", insn: InsnId::BPL, mode: AddrMode::Rel, operand_bytes: 1 }, // 0x10
+ OpEntry { mnemonic: "ora", insn: InsnId::ORA, mode: AddrMode::ZpIndY, operand_bytes: 1 }, // 0x11
+ OpEntry { mnemonic: "ora", insn: InsnId::ORA, mode: AddrMode::ZpInd, operand_bytes: 1 }, // 0x12
+ OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x13
+ OpEntry { mnemonic: "trb", insn: InsnId::TRB, mode: AddrMode::Zp, operand_bytes: 1 }, // 0x14
+ OpEntry { mnemonic: "ora", insn: InsnId::ORA, mode: AddrMode::ZpX, operand_bytes: 1 }, // 0x15
+ OpEntry { mnemonic: "asl", insn: InsnId::ASL, mode: AddrMode::ZpX, operand_bytes: 1 }, // 0x16
+ OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x17
+ OpEntry { mnemonic: "clc", insn: InsnId::CLC, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x18
+ OpEntry { mnemonic: "ora", insn: InsnId::ORA, mode: AddrMode::AbsY, operand_bytes: 2 }, // 0x19
+ OpEntry { mnemonic: "inc", insn: InsnId::INC, mode: AddrMode::Acc, operand_bytes: 0 }, // 0x1a
+ OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x1b
+ OpEntry { mnemonic: "trb", insn: InsnId::TRB, mode: AddrMode::Abs, operand_bytes: 2 }, // 0x1c
+ OpEntry { mnemonic: "ora", insn: InsnId::ORA, mode: AddrMode::AbsX, operand_bytes: 2 }, // 0x1d
+ OpEntry { mnemonic: "asl", insn: InsnId::ASL, mode: AddrMode::AbsX, operand_bytes: 2 }, // 0x1e
+ OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x1f
+ OpEntry { mnemonic: "jsr", insn: InsnId::JSR, mode: AddrMode::Abs, operand_bytes: 2 }, // 0x20
+ OpEntry { mnemonic: "and", insn: InsnId::AND, mode: AddrMode::ZpXInd, operand_bytes: 1 }, // 0x21
+ OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 1 }, // 0x22
+ OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x23
+ OpEntry { mnemonic: "bit", insn: InsnId::BIT, mode: AddrMode::Zp, operand_bytes: 1 }, // 0x24
+ OpEntry { mnemonic: "and", insn: InsnId::AND, mode: AddrMode::Zp, operand_bytes: 1 }, // 0x25
+ OpEntry { mnemonic: "rol", insn: InsnId::ROL, mode: AddrMode::Zp, operand_bytes: 1 }, // 0x26
+ OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x27
+ OpEntry { mnemonic: "plp", insn: InsnId::PLP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x28
+ OpEntry { mnemonic: "and", insn: InsnId::AND, mode: AddrMode::Imm, operand_bytes: 1 }, // 0x29
+ OpEntry { mnemonic: "rol", insn: InsnId::ROL, mode: AddrMode::Acc, operand_bytes: 0 }, // 0x2a
+ OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x2b
+ OpEntry { mnemonic: "bit", insn: InsnId::BIT, mode: AddrMode::Abs, operand_bytes: 2 }, // 0x2c
+ OpEntry { mnemonic: "and", insn: InsnId::AND, mode: AddrMode::Abs, operand_bytes: 2 }, // 0x2d
+ OpEntry { mnemonic: "rol", insn: InsnId::ROL, mode: AddrMode::Abs, operand_bytes: 2 }, // 0x2e
+ OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x2f
+ OpEntry { mnemonic: "bmi", insn: InsnId::BMI, mode: AddrMode::Rel, operand_bytes: 1 }, // 0x30
+ OpEntry { mnemonic: "and", insn: InsnId::AND, mode: AddrMode::ZpIndY, operand_bytes: 1 }, // 0x31
+ OpEntry { mnemonic: "and", insn: InsnId::AND, mode: AddrMode::ZpInd, operand_bytes: 1 }, // 0x32
+ OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x33
+ OpEntry { mnemonic: "bit", insn: InsnId::BIT, mode: AddrMode::ZpX, operand_bytes: 1 }, // 0x34
+ OpEntry { mnemonic: "and", insn: InsnId::AND, mode: AddrMode::ZpX, operand_bytes: 1 }, // 0x35
+ OpEntry { mnemonic: "rol", insn: InsnId::ROL, mode: AddrMode::ZpX, operand_bytes: 1 }, // 0x36
+ OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x37
+ OpEntry { mnemonic: "sec", insn: InsnId::SEC, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x38
+ OpEntry { mnemonic: "and", insn: InsnId::AND, mode: AddrMode::AbsY, operand_bytes: 2 }, // 0x39
+ OpEntry { mnemonic: "dec", insn: InsnId::DEC, mode: AddrMode::Acc, operand_bytes: 0 }, // 0x3a
+ OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x3b
+ OpEntry { mnemonic: "bit", insn: InsnId::BIT, mode: AddrMode::AbsX, operand_bytes: 2 }, // 0x3c
+ OpEntry { mnemonic: "and", insn: InsnId::AND, mode: AddrMode::AbsX, operand_bytes: 2 }, // 0x3d
+ OpEntry { mnemonic: "rol", insn: InsnId::ROL, mode: AddrMode::AbsX, operand_bytes: 2 }, // 0x3e
+ OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x3f
+ OpEntry { mnemonic: "rti", insn: InsnId::RTI, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x40
+ OpEntry { mnemonic: "eor", insn: InsnId::EOR, mode: AddrMode::ZpXInd, operand_bytes: 1 }, // 0x41
+ OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 1 }, // 0x42
+ OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x43
+ OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 1 }, // 0x44
+ OpEntry { mnemonic: "eor", insn: InsnId::EOR, mode: AddrMode::Zp, operand_bytes: 1 }, // 0x45
+ OpEntry { mnemonic: "lsr", insn: InsnId::LSR, mode: AddrMode::Zp, operand_bytes: 1 }, // 0x46
+ OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x47
+ OpEntry { mnemonic: "pha", insn: InsnId::PHA, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x48
+ OpEntry { mnemonic: "eor", insn: InsnId::EOR, mode: AddrMode::Imm, operand_bytes: 1 }, // 0x49
+ OpEntry { mnemonic: "lsr", insn: InsnId::LSR, mode: AddrMode::Acc, operand_bytes: 0 }, // 0x4a
+ OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x4b
+ OpEntry { mnemonic: "jmp", insn: InsnId::JMP, mode: AddrMode::Abs, operand_bytes: 2 }, // 0x4c
+ OpEntry { mnemonic: "eor", insn: InsnId::EOR, mode: AddrMode::Abs, operand_bytes: 2 }, // 0x4d
+ OpEntry { mnemonic: "lsr", insn: InsnId::LSR, mode: AddrMode::Abs, operand_bytes: 2 }, // 0x4e
+ OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x4f
+ OpEntry { mnemonic: "bvc", insn: InsnId::BVC, mode: AddrMode::Rel, operand_bytes: 1 }, // 0x50
+ OpEntry { mnemonic: "eor", insn: InsnId::EOR, mode: AddrMode::ZpIndY, operand_bytes: 1 }, // 0x51
+ OpEntry { mnemonic: "eor", insn: InsnId::EOR, mode: AddrMode::ZpInd, operand_bytes: 1 }, // 0x52
+ OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x53
+ OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 1 }, // 0x54
+ OpEntry { mnemonic: "eor", insn: InsnId::EOR, mode: AddrMode::ZpX, operand_bytes: 1 }, // 0x55
+ OpEntry { mnemonic: "lsr", insn: InsnId::LSR, mode: AddrMode::ZpX, operand_bytes: 1 }, // 0x56
+ OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x57
+ OpEntry { mnemonic: "cli", insn: InsnId::CLI, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x58
+ OpEntry { mnemonic: "eor", insn: InsnId::EOR, mode: AddrMode::AbsY, operand_bytes: 2 }, // 0x59
+ OpEntry { mnemonic: "phy", insn: InsnId::PHY, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x5a
+ OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x5b
+ OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 2 }, // 0x5c
+ OpEntry { mnemonic: "eor", insn: InsnId::EOR, mode: AddrMode::AbsX, operand_bytes: 2 }, // 0x5d
+ OpEntry { mnemonic: "lsr", insn: InsnId::LSR, mode: AddrMode::AbsX, operand_bytes: 2 }, // 0x5e
+ OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x5f
+ OpEntry { mnemonic: "rts", insn: InsnId::RTS, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x60
+ OpEntry { mnemonic: "adc", insn: InsnId::ADC, mode: AddrMode::ZpXInd, operand_bytes: 1 }, // 0x61
+ OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 1 }, // 0x62
+ OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x63
+ OpEntry { mnemonic: "stz", insn: InsnId::STZ, mode: AddrMode::Zp, operand_bytes: 1 }, // 0x64
+ OpEntry { mnemonic: "adc", insn: InsnId::ADC, mode: AddrMode::Zp, operand_bytes: 1 }, // 0x65
+ OpEntry { mnemonic: "ror", insn: InsnId::ROR, mode: AddrMode::Zp, operand_bytes: 1 }, // 0x66
+ OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x67
+ OpEntry { mnemonic: "pla", insn: InsnId::PLA, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x68
+ OpEntry { mnemonic: "adc", insn: InsnId::ADC, mode: AddrMode::Imm, operand_bytes: 1 }, // 0x69
+ OpEntry { mnemonic: "ror", insn: InsnId::ROR, mode: AddrMode::Acc, operand_bytes: 0 }, // 0x6a
+ OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x6b
+ OpEntry { mnemonic: "jmp", insn: InsnId::JMP, mode: AddrMode::AbsInd, operand_bytes: 2 }, // 0x6c
+ OpEntry { mnemonic: "adc", insn: InsnId::ADC, mode: AddrMode::Abs, operand_bytes: 2 }, // 0x6d
+ OpEntry { mnemonic: "ror", insn: InsnId::ROR, mode: AddrMode::Abs, operand_bytes: 2 }, // 0x6e
+ OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x6f
+ OpEntry { mnemonic: "bvs", insn: InsnId::BVS, mode: AddrMode::Rel, operand_bytes: 1 }, // 0x70
+ OpEntry { mnemonic: "adc", insn: InsnId::ADC, mode: AddrMode::ZpIndY, operand_bytes: 1 }, // 0x71
+ OpEntry { mnemonic: "adc", insn: InsnId::ADC, mode: AddrMode::ZpInd, operand_bytes: 1 }, // 0x72
+ OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x73
+ OpEntry { mnemonic: "stz", insn: InsnId::STZ, mode: AddrMode::ZpX, operand_bytes: 1 }, // 0x74
+ OpEntry { mnemonic: "adc", insn: InsnId::ADC, mode: AddrMode::ZpX, operand_bytes: 1 }, // 0x75
+ OpEntry { mnemonic: "ror", insn: InsnId::ROR, mode: AddrMode::ZpX, operand_bytes: 1 }, // 0x76
+ OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x77
+ OpEntry { mnemonic: "sei", insn: InsnId::SEI, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x78
+ OpEntry { mnemonic: "adc", insn: InsnId::ADC, mode: AddrMode::AbsY, operand_bytes: 2 }, // 0x79
+ OpEntry { mnemonic: "ply", insn: InsnId::PLY, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x7a
+ OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x7b
+ OpEntry { mnemonic: "jmp", insn: InsnId::JMP, mode: AddrMode::AbsXInd, operand_bytes: 2 }, // 0x7c
+ OpEntry { mnemonic: "adc", insn: InsnId::ADC, mode: AddrMode::AbsX, operand_bytes: 2 }, // 0x7d
+ OpEntry { mnemonic: "ror", insn: InsnId::ROR, mode: AddrMode::AbsX, operand_bytes: 2 }, // 0x7e
+ OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x7f
+ OpEntry { mnemonic: "bra", insn: InsnId::BRA, mode: AddrMode::Rel, operand_bytes: 1 }, // 0x80
+ OpEntry { mnemonic: "sta", insn: InsnId::STA, mode: AddrMode::ZpXInd, operand_bytes: 1 }, // 0x81
+ OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 1 }, // 0x82
+ OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x83
+ OpEntry { mnemonic: "sty", insn: InsnId::STY, mode: AddrMode::Zp, operand_bytes: 1 }, // 0x84
+ OpEntry { mnemonic: "sta", insn: InsnId::STA, mode: AddrMode::Zp, operand_bytes: 1 }, // 0x85
+ OpEntry { mnemonic: "stx", insn: InsnId::STX, mode: AddrMode::Zp, operand_bytes: 1 }, // 0x86
+ OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x87
+ OpEntry { mnemonic: "dey", insn: InsnId::DEY, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x88
+ OpEntry { mnemonic: "bit", insn: InsnId::BIT, mode: AddrMode::Imm, operand_bytes: 1 }, // 0x89
+ OpEntry { mnemonic: "txa", insn: InsnId::TXA, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x8a
+ OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x8b
+ OpEntry { mnemonic: "sty", insn: InsnId::STY, mode: AddrMode::Abs, operand_bytes: 2 }, // 0x8c
+ OpEntry { mnemonic: "sta", insn: InsnId::STA, mode: AddrMode::Abs, operand_bytes: 2 }, // 0x8d
+ OpEntry { mnemonic: "stx", insn: InsnId::STX, mode: AddrMode::Abs, operand_bytes: 2 }, // 0x8e
+ OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x8f
+ OpEntry { mnemonic: "bcc", insn: InsnId::BCC, mode: AddrMode::Rel, operand_bytes: 1 }, // 0x90
+ OpEntry { mnemonic: "sta", insn: InsnId::STA, mode: AddrMode::ZpIndY, operand_bytes: 1 }, // 0x91
+ OpEntry { mnemonic: "sta", insn: InsnId::STA, mode: AddrMode::ZpInd, operand_bytes: 1 }, // 0x92
+ OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x93
+ OpEntry { mnemonic: "sty", insn: InsnId::STY, mode: AddrMode::ZpX, operand_bytes: 1 }, // 0x94
+ OpEntry { mnemonic: "sta", insn: InsnId::STA, mode: AddrMode::ZpX, operand_bytes: 1 }, // 0x95
+ OpEntry { mnemonic: "stx", insn: InsnId::STX, mode: AddrMode::ZpY, operand_bytes: 1 }, // 0x96
+ OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x97
+ OpEntry { mnemonic: "tya", insn: InsnId::TYA, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x98
+ OpEntry { mnemonic: "sta", insn: InsnId::STA, mode: AddrMode::AbsY, operand_bytes: 2 }, // 0x99
+ OpEntry { mnemonic: "txs", insn: InsnId::TXS, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x9a
+ OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x9b
+ OpEntry { mnemonic: "stz", insn: InsnId::STZ, mode: AddrMode::Abs, operand_bytes: 2 }, // 0x9c
+ OpEntry { mnemonic: "sta", insn: InsnId::STA, mode: AddrMode::AbsX, operand_bytes: 2 }, // 0x9d
+ OpEntry { mnemonic: "stz", insn: InsnId::STZ, mode: AddrMode::AbsX, operand_bytes: 2 }, // 0x9e
+ OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0x9f
+ OpEntry { mnemonic: "ldy", insn: InsnId::LDY, mode: AddrMode::Imm, operand_bytes: 1 }, // 0xa0
+ OpEntry { mnemonic: "lda", insn: InsnId::LDA, mode: AddrMode::ZpXInd, operand_bytes: 1 }, // 0xa1
+ OpEntry { mnemonic: "ldx", insn: InsnId::LDX, mode: AddrMode::Imm, operand_bytes: 1 }, // 0xa2
+ OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xa3
+ OpEntry { mnemonic: "ldy", insn: InsnId::LDY, mode: AddrMode::Zp, operand_bytes: 1 }, // 0xa4
+ OpEntry { mnemonic: "lda", insn: InsnId::LDA, mode: AddrMode::Zp, operand_bytes: 1 }, // 0xa5
+ OpEntry { mnemonic: "ldx", insn: InsnId::LDX, mode: AddrMode::Zp, operand_bytes: 1 }, // 0xa6
+ OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xa7
+ OpEntry { mnemonic: "tay", insn: InsnId::TAY, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xa8
+ OpEntry { mnemonic: "lda", insn: InsnId::LDA, mode: AddrMode::Imm, operand_bytes: 1 }, // 0xa9
+ OpEntry { mnemonic: "tax", insn: InsnId::TAX, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xaa
+ OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xab
+ OpEntry { mnemonic: "ldy", insn: InsnId::LDY, mode: AddrMode::Abs, operand_bytes: 2 }, // 0xac
+ OpEntry { mnemonic: "lda", insn: InsnId::LDA, mode: AddrMode::Abs, operand_bytes: 2 }, // 0xad
+ OpEntry { mnemonic: "ldx", insn: InsnId::LDX, mode: AddrMode::Abs, operand_bytes: 2 }, // 0xae
+ OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xaf
+ OpEntry { mnemonic: "bcs", insn: InsnId::BCS, mode: AddrMode::Rel, operand_bytes: 1 }, // 0xb0
+ OpEntry { mnemonic: "lda", insn: InsnId::LDA, mode: AddrMode::ZpIndY, operand_bytes: 1 }, // 0xb1
+ OpEntry { mnemonic: "lda", insn: InsnId::LDA, mode: AddrMode::ZpInd, operand_bytes: 1 }, // 0xb2
+ OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xb3
+ OpEntry { mnemonic: "ldy", insn: InsnId::LDY, mode: AddrMode::ZpX, operand_bytes: 1 }, // 0xb4
+ OpEntry { mnemonic: "lda", insn: InsnId::LDA, mode: AddrMode::ZpX, operand_bytes: 1 }, // 0xb5
+ OpEntry { mnemonic: "ldx", insn: InsnId::LDX, mode: AddrMode::ZpY, operand_bytes: 1 }, // 0xb6
+ OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xb7
+ OpEntry { mnemonic: "clv", insn: InsnId::CLV, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xb8
+ OpEntry { mnemonic: "lda", insn: InsnId::LDA, mode: AddrMode::AbsY, operand_bytes: 2 }, // 0xb9
+ OpEntry { mnemonic: "tsx", insn: InsnId::TSX, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xba
+ OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xbb
+ OpEntry { mnemonic: "ldy", insn: InsnId::LDY, mode: AddrMode::AbsX, operand_bytes: 2 }, // 0xbc
+ OpEntry { mnemonic: "lda", insn: InsnId::LDA, mode: AddrMode::AbsX, operand_bytes: 2 }, // 0xbd
+ OpEntry { mnemonic: "ldx", insn: InsnId::LDX, mode: AddrMode::AbsY, operand_bytes: 2 }, // 0xbe
+ OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xbf
+ OpEntry { mnemonic: "cpy", insn: InsnId::CPY, mode: AddrMode::Imm, operand_bytes: 1 }, // 0xc0
+ OpEntry { mnemonic: "cmp", insn: InsnId::CMP, mode: AddrMode::ZpXInd, operand_bytes: 1 }, // 0xc1
+ OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 1 }, // 0xc2
+ OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xc3
+ OpEntry { mnemonic: "cpy", insn: InsnId::CPY, mode: AddrMode::Zp, operand_bytes: 1 }, // 0xc4
+ OpEntry { mnemonic: "cmp", insn: InsnId::CMP, mode: AddrMode::Zp, operand_bytes: 1 }, // 0xc5
+ OpEntry { mnemonic: "dec", insn: InsnId::DEC, mode: AddrMode::Zp, operand_bytes: 1 }, // 0xc6
+ OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xc7
+ OpEntry { mnemonic: "iny", insn: InsnId::INY, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xc8
+ OpEntry { mnemonic: "cmp", insn: InsnId::CMP, mode: AddrMode::Imm, operand_bytes: 1 }, // 0xc9
+ OpEntry { mnemonic: "dex", insn: InsnId::DEX, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xca
+ OpEntry { mnemonic: "wai", insn: InsnId::WAI, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xcb
+ OpEntry { mnemonic: "cpy", insn: InsnId::CPY, mode: AddrMode::Abs, operand_bytes: 2 }, // 0xcc
+ OpEntry { mnemonic: "cmp", insn: InsnId::CMP, mode: AddrMode::Abs, operand_bytes: 2 }, // 0xcd
+ OpEntry { mnemonic: "dec", insn: InsnId::DEC, mode: AddrMode::Abs, operand_bytes: 2 }, // 0xce
+ OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xcf
+ OpEntry { mnemonic: "bne", insn: InsnId::BNE, mode: AddrMode::Rel, operand_bytes: 1 }, // 0xd0
+ OpEntry { mnemonic: "cmp", insn: InsnId::CMP, mode: AddrMode::ZpIndY, operand_bytes: 1 }, // 0xd1
+ OpEntry { mnemonic: "cmp", insn: InsnId::CMP, mode: AddrMode::ZpInd, operand_bytes: 1 }, // 0xd2
+ OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xd3
+ OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 1 }, // 0xd4
+ OpEntry { mnemonic: "cmp", insn: InsnId::CMP, mode: AddrMode::ZpX, operand_bytes: 1 }, // 0xd5
+ OpEntry { mnemonic: "dec", insn: InsnId::DEC, mode: AddrMode::ZpX, operand_bytes: 1 }, // 0xd6
+ OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xd7
+ OpEntry { mnemonic: "cld", insn: InsnId::CLD, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xd8
+ OpEntry { mnemonic: "cmp", insn: InsnId::CMP, mode: AddrMode::AbsY, operand_bytes: 2 }, // 0xd9
+ OpEntry { mnemonic: "phx", insn: InsnId::PHX, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xda
+ OpEntry { mnemonic: "stp", insn: InsnId::STP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xdb
+ OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 2 }, // 0xdc
+ OpEntry { mnemonic: "cmp", insn: InsnId::CMP, mode: AddrMode::AbsX, operand_bytes: 2 }, // 0xdd
+ OpEntry { mnemonic: "dec", insn: InsnId::DEC, mode: AddrMode::AbsX, operand_bytes: 2 }, // 0xde
+ OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xdf
+ OpEntry { mnemonic: "cpx", insn: InsnId::CPX, mode: AddrMode::Imm, operand_bytes: 1 }, // 0xe0
+ OpEntry { mnemonic: "sbc", insn: InsnId::SBC, mode: AddrMode::ZpXInd, operand_bytes: 1 }, // 0xe1
+ OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 1 }, // 0xe2
+ OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xe3
+ OpEntry { mnemonic: "cpx", insn: InsnId::CPX, mode: AddrMode::Zp, operand_bytes: 1 }, // 0xe4
+ OpEntry { mnemonic: "sbc", insn: InsnId::SBC, mode: AddrMode::Zp, operand_bytes: 1 }, // 0xe5
+ OpEntry { mnemonic: "inc", insn: InsnId::INC, mode: AddrMode::Zp, operand_bytes: 1 }, // 0xe6
+ OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xe7
+ OpEntry { mnemonic: "inx", insn: InsnId::INX, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xe8
+ OpEntry { mnemonic: "sbc", insn: InsnId::SBC, mode: AddrMode::Imm, operand_bytes: 1 }, // 0xe9
+ OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xea
+ OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xeb
+ OpEntry { mnemonic: "cpx", insn: InsnId::CPX, mode: AddrMode::Abs, operand_bytes: 2 }, // 0xec
+ OpEntry { mnemonic: "sbc", insn: InsnId::SBC, mode: AddrMode::Abs, operand_bytes: 2 }, // 0xed
+ OpEntry { mnemonic: "inc", insn: InsnId::INC, mode: AddrMode::Abs, operand_bytes: 2 }, // 0xee
+ OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xef
+ OpEntry { mnemonic: "beq", insn: InsnId::BEQ, mode: AddrMode::Rel, operand_bytes: 1 }, // 0xf0
+ OpEntry { mnemonic: "sbc", insn: InsnId::SBC, mode: AddrMode::ZpIndY, operand_bytes: 1 }, // 0xf1
+ OpEntry { mnemonic: "sbc", insn: InsnId::SBC, mode: AddrMode::ZpInd, operand_bytes: 1 }, // 0xf2
+ OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xf3
+ OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 1 }, // 0xf4
+ OpEntry { mnemonic: "sbc", insn: InsnId::SBC, mode: AddrMode::ZpX, operand_bytes: 1 }, // 0xf5
+ OpEntry { mnemonic: "inc", insn: InsnId::INC, mode: AddrMode::ZpX, operand_bytes: 1 }, // 0xf6
+ OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xf7
+ OpEntry { mnemonic: "sed", insn: InsnId::SED, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xf8
+ OpEntry { mnemonic: "sbc", insn: InsnId::SBC, mode: AddrMode::AbsY, operand_bytes: 2 }, // 0xf9
+ OpEntry { mnemonic: "plx", insn: InsnId::PLX, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xfa
+ OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xfb
+ OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 2 }, // 0xfc
+ OpEntry { mnemonic: "sbc", insn: InsnId::SBC, mode: AddrMode::AbsX, operand_bytes: 2 }, // 0xfd
+ OpEntry { mnemonic: "inc", insn: InsnId::INC, mode: AddrMode::AbsX, operand_bytes: 2 }, // 0xfe
+ OpEntry { mnemonic: "nop", insn: InsnId::NOP, mode: AddrMode::Imp, operand_bytes: 0 }, // 0xff
+];
diff --git a/crates/ghidrust-decode/src/arch/ppc/decode.rs b/crates/ghidrust-decode/src/arch/ppc/decode.rs
new file mode 100644
index 0000000..118c79f
--- /dev/null
+++ b/crates/ghidrust-decode/src/arch/ppc/decode.rs
@@ -0,0 +1,151 @@
+use super::regs::gpr;
+use super::util::{bit, fmt_imm, read_u32, sign_extend16};
+use crate::error::{Error, Result};
+use crate::insn::Instruction;
+
+pub fn decode(bytes: &[u8], address: u64, big_endian: bool, ppc64: bool) -> Result<Instruction> {
+ let w = read_u32(bytes, big_endian)?;
+ let raw = bytes[..4].to_vec();
+ let primary = bit(w, 26, 31);
+ match primary {
+ 0b001110 => decode_addi(w, address, raw),
+ 0b100000 => decode_lwz(w, address, raw),
+ 0b100100 => decode_stw(w, address, raw),
+ 0b100010 => decode_lbzu(w, address, raw, "lbz"),
+ 0b100110 => decode_lbzu(w, address, raw, "stb"),
+ 0b010010 => decode_b(w, address, raw),
+ 0b010000 => decode_bc(w, address, raw),
+ 0b011111 => decode_xform(w, address, raw, ppc64),
+ _ => Err(Error::Decode(format!("unhandled PPC primary {primary:#04x}"))),
+ }
+}
+
+fn decode_addi(w: u32, address: u64, raw: Vec<u8>) -> Result<Instruction> {
+ let rt = bit(w, 16, 20);
+ let ra = bit(w, 21, 25);
+ let imm = sign_extend16(w & 0xffff);
+ let mnemonic = if ra == 0 { "li" } else { "addi" };
+ let operands = if ra == 0 {
+ format!("{}, {:#x}", gpr(rt), imm as u16)
+ } else {
+ format!("{}, {}, {:#x}", gpr(rt), gpr(ra), imm as u16)
+ };
+ Ok(Instruction::with_text(address, raw, mnemonic, operands, 4))
+}
+
+fn decode_lwz(w: u32, address: u64, raw: Vec<u8>) -> Result<Instruction> {
+ let rt = bit(w, 16, 20);
+ let ra = bit(w, 21, 25);
+ let imm = sign_extend16(w & 0xffff);
+ Ok(Instruction::with_text(
+ address,
+ raw,
+ "lwz",
+ format!("{}, {:#x}({})", gpr(rt), imm, gpr(ra)),
+ 4,
+ ))
+}
+
+fn decode_stw(w: u32, address: u64, raw: Vec<u8>) -> Result<Instruction> {
+ let rs = bit(w, 16, 20);
+ let ra = bit(w, 21, 25);
+ let imm = sign_extend16(w & 0xffff);
+ Ok(Instruction::with_text(
+ address,
+ raw,
+ "stw",
+ format!("{}, {:#x}({})", gpr(rs), imm, gpr(ra)),
+ 4,
+ ))
+}
+
+fn decode_lbzu(w: u32, address: u64, raw: Vec<u8>, mnemonic: &str) -> Result<Instruction> {
+ let rt = bit(w, 16, 20);
+ let ra = bit(w, 21, 25);
+ let imm = sign_extend16(w & 0xffff);
+ Ok(Instruction::with_text(
+ address,
+ raw,
+ mnemonic,
+ format!("{}, {:#x}({})", gpr(rt), imm, gpr(ra)),
+ 4,
+ ))
+}
+
+fn decode_b(w: u32, address: u64, raw: Vec<u8>) -> Result<Instruction> {
+ let link = bit(w, 0, 0) != 0;
+ let li = bit(w, 2, 25);
+ let aa = bit(w, 1, 1);
+ let offset = sign_extend16(li << 2) as i64;
+ let target = if aa != 0 {
+ offset as u64
+ } else {
+ (address as i64).wrapping_add(offset) as u64
+ };
+ let mnemonic = if link { "bl" } else { "b" };
+ Ok(Instruction::with_text(
+ address,
+ raw,
+ mnemonic,
+ fmt_imm(target as i32),
+ 4,
+ ))
+}
+
+fn decode_bc(w: u32, address: u64, raw: Vec<u8>) -> Result<Instruction> {
+ let bo = bit(w, 21, 25);
+ let bi = bit(w, 16, 20);
+ let bd = sign_extend16(bit(w, 2, 15) << 2) as i64;
+ let target = (address as i64).wrapping_add(bd) as u64;
+ let link = bit(w, 0, 0) != 0;
+ let mnemonic = if link { "bcl" } else { "bc" };
+ Ok(Instruction::with_text(
+ address,
+ raw,
+ mnemonic,
+ format!("{bo}, {bi}, {}", fmt_imm(target as i32)),
+ 4,
+ ))
+}
+
+fn decode_trap(w: u32, address: u64, raw: Vec<u8>) -> Result<Instruction> {
+ let to = bit(w, 21, 25);
+ if to == 0 {
+ Ok(Instruction::with_text(address, raw, "tw", "", 4))
+ } else {
+ Ok(Instruction::with_text(
+ address,
+ raw,
+ "trap",
+ format!("#{to}"),
+ 4,
+ ))
+ }
+}
+
+fn decode_xform(w: u32, address: u64, raw: Vec<u8>, ppc64: bool) -> Result<Instruction> {
+ let xo = bit(w, 1, 10);
+ let rs = bit(w, 11, 15);
+ let ra = bit(w, 16, 20);
+ let rb = bit(w, 21, 25);
+ let (mnemonic, operands) = match xo {
+ 0b000000 => ("mcrxr", format!("cr{}", rs)),
+ 0b000010 => ("add", format!("{}, {}, {}", gpr(rs), gpr(ra), gpr(rb))),
+ 0b000100 => ("subf", format!("{}, {}, {}", gpr(rs), gpr(ra), gpr(rb))),
+ 0b001010 => ("addc", format!("{}, {}, {}", gpr(rs), gpr(ra), gpr(rb))),
+ 0b001100 => ("subfc", format!("{}, {}, {}", gpr(rs), gpr(ra), gpr(rb))),
+ 0b010101 => ("dcbst", format!("{}, {}", gpr(ra), gpr(rb))),
+ 0b011011 => ("xor", format!("{}, {}, {}", gpr(rs), gpr(ra), gpr(rb))),
+ 0b011111 => ("nand", format!("{}, {}, {}", gpr(rs), gpr(ra), gpr(rb))),
+ 0b100001 => ("mullw", format!("{}, {}, {}", gpr(rs), gpr(ra), gpr(rb))),
+ 0b101010 => ("divw", format!("{}, {}, {}", gpr(rs), gpr(ra), gpr(rb))),
+ 0b110011 => ("or", format!("{}, {}, {}", gpr(rs), gpr(ra), gpr(rb))),
+ 0b110101 => ("nor", format!("{}, {}, {}", gpr(rs), gpr(ra), gpr(rb))),
+ 0b111000 => ("and", format!("{}, {}, {}", gpr(rs), gpr(ra), gpr(rb))),
+ 0b000011 => ("bclr", format!("20, {}, {}", "lr", bit(w, 16, 20))),
+ 0b001000 => ("bctr", format!("20, {}, {}", "ctr", bit(w, 16, 20))),
+ 0b010011 if ppc64 => ("ld", format!("{}, 0({})", gpr(rs), gpr(ra))),
+ _ => return Err(Error::Decode(format!("unhandled PPC xform {xo:#04x}"))),
+ };
+ Ok(Instruction::with_text(address, raw, mnemonic, operands, 4))
+}
diff --git a/crates/ghidrust-decode/src/arch/ppc/mod.rs b/crates/ghidrust-decode/src/arch/ppc/mod.rs
new file mode 100644
index 0000000..4b92bff
--- /dev/null
+++ b/crates/ghidrust-decode/src/arch/ppc/mod.rs
@@ -0,0 +1,112 @@
+mod decode;
+mod regs;
+mod util;
+
+use crate::arch::ArchDecode;
+use crate::error::{Error, Result};
+use crate::group::GroupId;
+use crate::insn::{InsnDetail, InsnId, Instruction};
+use crate::names;
+use crate::option::EngineOptions;
+use crate::reg::RegId;
+use crate::support::{Arch, Mode};
+
+pub struct PpcDecoder {
+ big_endian: bool,
+ ppc64: bool,
+}
+
+impl ArchDecode for PpcDecoder {
+ fn arch(&self) -> Arch {
+ Arch::Ppc
+ }
+
+ fn open(mode: Mode) -> Result<Self> {
+ if !mode.is_valid_for(Arch::Ppc) {
+ return Err(Error::Mode(format!("invalid PPC mode {:#x}", mode.bits())));
+ }
+ let big_endian = true;
+ let ppc64 = mode.contains(Mode::PPC64) || mode.contains(Mode::MODE_64);
+ Ok(Self { big_endian, ppc64 })
+ }
+
+ fn decode_one(&self, bytes: &[u8], address: u64, opts: &EngineOptions) -> Result<Instruction> {
+ let mut insn = decode::decode(bytes, address, self.big_endian, self.ppc64)?;
+ insn.id = names::insn_id_for_mnemonic(Arch::Ppc, &insn.mnemonic);
+ if opts.detail {
+ insn.detail = Some(InsnDetail {
+ groups: groups_for_mnemonic(&insn.mnemonic),
+ ..InsnDetail::default()
+ });
+ }
+ Ok(insn)
+ }
+}
+
+fn groups_for_mnemonic(mnemonic: &str) -> Vec<GroupId> {
+ match mnemonic {
+ "b" | "bc" | "bctr" | "bclr" => vec![GroupId::Jump, GroupId::BranchRelative],
+ "bl" | "bcl" => vec![GroupId::Call, GroupId::BranchRelative],
+ "trap" | "tw" => vec![GroupId::Int],
+ _ => Vec::new(),
+ }
+}
+
+pub fn reg_name(_reg: RegId) -> Option<&'static str> {
+ None
+}
+
+pub fn insn_name(id: InsnId) -> Option<&'static str> {
+ match id.raw() {
+ 1 => Some("addi"),
+ 2 => Some("lwz"),
+ 3 => Some("stw"),
+ 4 => Some("bl"),
+ _ => None,
+ }
+}
+
+pub fn group_name(group: GroupId) -> Option<&'static str> {
+ match group {
+ GroupId::Jump => Some("jump"),
+ GroupId::Call => Some("call"),
+ GroupId::Int => Some("int"),
+ GroupId::BranchRelative => Some("branch_relative"),
+ _ => None,
+ }
+}
+
+pub fn insn_id_for_mnemonic(mnemonic: &str) -> InsnId {
+ let id = match mnemonic {
+ "addi" | "li" | "add" => 1,
+ "lwz" | "ld" => 2,
+ "stw" => 3,
+ "bl" => 4,
+ _ => 0,
+ };
+ InsnId(id)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::engine::Engine;
+
+ #[test]
+ fn ppc_addi_lwz() {
+ let mut eng = Engine::open(Arch::Ppc, Mode::PPC32).unwrap();
+ // addi r3, r0, 0x100 -> 38600100
+ let addi = eng.disasm_one(&[0x38, 0x60, 0x01, 0x00], 0x1000).unwrap();
+ assert_eq!(addi.mnemonic, "addi");
+ // lwz r4, 0(r3) -> 80830000
+ let lwz = eng.disasm_one(&[0x80, 0x83, 0x00, 0x00], 0x1004).unwrap();
+ assert_eq!(lwz.mnemonic, "lwz");
+ }
+
+ #[test]
+ fn ppc_bl() {
+ let mut eng = Engine::open(Arch::Ppc, Mode::PPC32).unwrap();
+ let bl = eng.disasm_one(&[0x48, 0x00, 0x00, 0x01], 0x0).unwrap();
+ assert_eq!(bl.mnemonic, "bl");
+ }
+}
diff --git a/crates/ghidrust-decode/src/arch/ppc/regs.rs b/crates/ghidrust-decode/src/arch/ppc/regs.rs
new file mode 100644
index 0000000..cb8cff8
--- /dev/null
+++ b/crates/ghidrust-decode/src/arch/ppc/regs.rs
@@ -0,0 +1,11 @@
+pub fn gpr(n: u32) -> String {
+ format!("r{n}")
+}
+
+pub fn lr() -> &'static str {
+ "lr"
+}
+
+pub fn ctr() -> &'static str {
+ "ctr"
+}
diff --git a/crates/ghidrust-decode/src/arch/ppc/util.rs b/crates/ghidrust-decode/src/arch/ppc/util.rs
new file mode 100644
index 0000000..79b13fb
--- /dev/null
+++ b/crates/ghidrust-decode/src/arch/ppc/util.rs
@@ -0,0 +1,28 @@
+use crate::error::{Error, Result};
+
+pub fn read_u32(bytes: &[u8], big_endian: bool) -> Result<u32> {
+ if bytes.len() < 4 {
+ return Err(Error::Decode("truncated PPC word".into()));
+ }
+ Ok(if big_endian {
+ u32::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])
+ } else {
+ u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])
+ })
+}
+
+pub fn bit(w: u32, lo: u32, hi: u32) -> u32 {
+ (w >> lo) & ((1u32 << (hi - lo + 1)) - 1)
+}
+
+pub fn sign_extend16(v: u32) -> i32 {
+ ((v << 16) as i32) >> 16
+}
+
+pub fn fmt_imm(v: i32) -> String {
+ if v < 0 {
+ format!("-{:#x}", -v)
+ } else {
+ format!("{v:#x}")
+ }
+}
diff --git a/crates/ghidrust-decode/src/arch/riscv/decode32.rs b/crates/ghidrust-decode/src/arch/riscv/decode32.rs
new file mode 100644
index 0000000..b0d0e56
--- /dev/null
+++ b/crates/ghidrust-decode/src/arch/riscv/decode32.rs
@@ -0,0 +1,329 @@
+use super::regs::reg_name_num;
+use crate::error::{Error, Result};
+
+pub fn decode(word: u32, is64: bool) -> Result<(String, String)> {
+ let opcode = word & 0x7f;
+ let rd = (word >> 7) & 0x1f;
+ let funct3 = (word >> 12) & 0x7;
+ let rs1 = (word >> 15) & 0x1f;
+ let rs2 = (word >> 20) & 0x1f;
+ let funct7 = (word >> 25) & 0x7f;
+
+ match opcode {
+ 0b0110111 => {
+ let imm = word & 0xfffff000;
+ Ok(("lui".into(), format!("{}, {imm:#x}", reg_name_num(rd))))
+ }
+ 0b0010111 => {
+ let imm = sign_extend(((word >> 12) << 12) as i32, 32);
+ Ok(("auipc".into(), format!("{}, {imm:#x}", reg_name_num(rd))))
+ }
+ 0b1101111 => {
+ let imm = jal_imm(word);
+ Ok(("jal".into(), format!("{}, {imm:#x}", reg_name_num(rd))))
+ }
+ 0b1100111 => match funct3 {
+ 0b000 => {
+ let imm = sign_extend((word >> 20) as i32, 12);
+ Ok((
+ "jalr".into(),
+ format!("{}, {}({})", reg_name_num(rd), imm, reg_name_num(rs1)),
+ ))
+ }
+ _ => Err(Error::Decode("invalid jalr funct3".into())),
+ },
+ 0b1100011 => {
+ let imm = b_imm(word);
+ let name = match funct3 {
+ 0b000 => "beq",
+ 0b001 => "bne",
+ 0b100 => "blt",
+ 0b101 => "bge",
+ 0b110 => "bltu",
+ 0b111 => "bgeu",
+ _ => return Err(Error::Decode("invalid branch funct3".into())),
+ };
+ Ok((
+ name.into(),
+ format!("{}, {}, {imm:#x}", reg_name_num(rs1), reg_name_num(rs2)),
+ ))
+ }
+ 0b0000011 => load_mnemonic(funct3, rd, rs1, word, is64),
+ 0b0100011 => store_mnemonic(funct3, rs1, rs2, word, is64),
+ 0b0010011 => op_imm(funct3, rd, rs1, word, is64),
+ 0b0110011 => op_reg(funct7, funct3, rd, rs1, rs2, is64),
+ 0b0001111 => match funct3 {
+ 0b000 => Ok(("fence".into(), format!("{}, {}", rs1, rs2))),
+ 0b001 => Ok(("fence.i".into(), String::new())),
+ _ => Err(Error::Decode("invalid fence".into())),
+ },
+ 0b1110011 => system(funct3, rs1, rs2, word),
+ 0b1010011 => float_op(funct7, funct3, rd, rs1, rs2),
+ 0b0001011 => Ok(("vload".into(), format!("v{}, {}", rd, reg_name_num(rs1)))),
+ 0b0101011 => Ok(("vstore".into(), format!("v{}, {}", rd, reg_name_num(rs1)))),
+ 0b1011011 => float_op(funct7, funct3, rd, rs1, rs2),
+ _ => Err(Error::Decode(format!("unknown riscv opcode {opcode:#x}"))),
+ }
+}
+
+fn load_mnemonic(funct3: u32, rd: u32, rs1: u32, word: u32, is64: bool) -> Result<(String, String)> {
+ let imm = sign_extend((word >> 20) as i32, 12);
+ let name = match (funct3, is64) {
+ (0b000, false) => "lb",
+ (0b001, false) => "lh",
+ (0b010, false) => "lw",
+ (0b011, true) => "ld",
+ (0b100, false) => "lbu",
+ (0b101, false) => "lhu",
+ (0b110, true) => "lwu",
+ (0b000, true) => "lb",
+ (0b001, true) => "lh",
+ (0b010, true) => "lw",
+ (0b100, true) => "lbu",
+ (0b101, true) => "lhu",
+ _ => return Err(Error::Decode("invalid load funct3".into())),
+ };
+ Ok((
+ name.into(),
+ format!("{}, {imm}({})", reg_name_num(rd), reg_name_num(rs1)),
+ ))
+}
+
+fn store_mnemonic(funct3: u32, rs1: u32, rs2: u32, word: u32, is64: bool) -> Result<(String, String)> {
+ let imm = s_imm(word);
+ let name = match (funct3, is64) {
+ (0b000, _) => "sb",
+ (0b001, false) => "sh",
+ (0b010, false) => "sw",
+ (0b011, true) => "sd",
+ (0b001, true) => "sh",
+ (0b010, true) => "sw",
+ _ => return Err(Error::Decode("invalid store funct3".into())),
+ };
+ Ok((
+ name.into(),
+ format!("{}, {imm}({})", reg_name_num(rs2), reg_name_num(rs1)),
+ ))
+}
+
+fn op_imm(funct3: u32, rd: u32, rs1: u32, word: u32, is64: bool) -> Result<(String, String)> {
+ let imm = sign_extend((word >> 20) as i32, 12);
+ let shamt = if is64 && (funct3 == 0b001 || funct3 == 0b101) {
+ ((word >> 20) & 0x3f) as i32
+ } else {
+ ((word >> 20) & 0x1f) as i32
+ };
+ let name = match funct3 {
+ 0b000 => "addi",
+ 0b010 => "slti",
+ 0b011 => "sltiu",
+ 0b100 => "xori",
+ 0b110 => "ori",
+ 0b111 => "andi",
+ 0b001 => if is64 { "slli" } else { "slli" },
+ 0b101 => {
+ if (word >> 30) & 1 == 1 {
+ if is64 {
+ "srai"
+ } else {
+ "srai"
+ }
+ } else if is64 {
+ "srli"
+ } else {
+ "srli"
+ }
+ }
+ _ => return Err(Error::Decode("invalid op-imm funct3".into())),
+ };
+ let imm_disp = if funct3 == 0b001 || funct3 == 0b101 {
+ shamt
+ } else {
+ imm
+ };
+ Ok((
+ name.into(),
+ format!("{}, {}, {imm_disp}", reg_name_num(rd), reg_name_num(rs1)),
+ ))
+}
+
+fn op_reg(funct7: u32, funct3: u32, rd: u32, rs1: u32, rs2: u32, is64: bool) -> Result<(String, String)> {
+ if funct7 == 0b0000001 && matches!(funct3, 0b000 | 0b001 | 0b010 | 0b011) {
+ let name = match funct3 {
+ 0b000 => "mul",
+ 0b001 => "mulh",
+ 0b010 => "mulhsu",
+ 0b011 => "mulhu",
+ _ => unreachable!(),
+ };
+ return Ok((
+ name.into(),
+ format!("{}, {}, {}", reg_name_num(rd), reg_name_num(rs1), reg_name_num(rs2)),
+ ));
+ }
+ if funct7 == 0b0000001 && funct3 == 0b100 {
+ return Ok((
+ "div".into(),
+ format!("{}, {}, {}", reg_name_num(rd), reg_name_num(rs1), reg_name_num(rs2)),
+ ));
+ }
+ if funct7 == 0b0000001 && funct3 == 0b101 {
+ return Ok((
+ "divu".into(),
+ format!("{}, {}, {}", reg_name_num(rd), reg_name_num(rs1), reg_name_num(rs2)),
+ ));
+ }
+ if funct7 == 0b0000001 && funct3 == 0b110 {
+ return Ok((
+ "rem".into(),
+ format!("{}, {}, {}", reg_name_num(rd), reg_name_num(rs1), reg_name_num(rs2)),
+ ));
+ }
+ if funct7 == 0b0000001 && funct3 == 0b111 {
+ return Ok((
+ "remu".into(),
+ format!("{}, {}, {}", reg_name_num(rd), reg_name_num(rs1), reg_name_num(rs2)),
+ ));
+ }
+
+ let name = match (funct7, funct3) {
+ (0b0000000, 0b000) => if is64 { "add" } else { "add" },
+ (0b0100000, 0b000) => "sub",
+ (0b0000000, 0b001) => "sll",
+ (0b0000000, 0b010) => "slt",
+ (0b0000000, 0b011) => "sltu",
+ (0b0000000, 0b100) => "xor",
+ (0b0000000, 0b101) => "srl",
+ (0b0100000, 0b101) => "sra",
+ (0b0000000, 0b110) => "or",
+ (0b0000000, 0b111) => "and",
+ (0b0000001, 0b000) => "mul",
+ _ => return Err(Error::Decode("invalid op funct7/funct3".into())),
+ };
+ Ok((
+ name.into(),
+ format!("{}, {}, {}", reg_name_num(rd), reg_name_num(rs1), reg_name_num(rs2)),
+ ))
+}
+
+fn system(funct3: u32, rs1: u32, _rs2: u32, word: u32) -> Result<(String, String)> {
+ let imm = (word >> 20) as u32;
+ match (funct3, imm) {
+ (0b000, 0) => Ok(("ecall".into(), String::new())),
+ (0b000, 1) => Ok(("ebreak".into(), String::new())),
+ (0b000, 0x302) => Ok(("mret".into(), String::new())),
+ (0b000, 0x102) => Ok(("sret".into(), String::new())),
+ (0b000, 0x002) => Ok(("uret".into(), String::new())),
+ (0b001, _) => Ok(("csrrw".into(), format!("{}, {}, {imm:#x}", reg_name_num(rs1), imm))),
+ (0b010, _) => Ok(("csrrs".into(), format!("{}, {}, {imm:#x}", reg_name_num(rs1), imm))),
+ (0b011, _) => Ok(("csrrc".into(), format!("{}, {}, {imm:#x}", reg_name_num(rs1), imm))),
+ (0b101, _) => Ok(("csrrwi".into(), format!("{}, {}, {imm:#x}", reg_name_num(rs1), imm))),
+ (0b110, _) => Ok(("csrrsi".into(), format!("{}, {}, {imm:#x}", reg_name_num(rs1), imm))),
+ (0b111, _) => Ok(("csrrci".into(), format!("{}, {}, {imm:#x}", reg_name_num(rs1), imm))),
+ _ => Err(Error::Decode("invalid system instruction".into())),
+ }
+}
+
+fn float_op(funct7: u32, funct3: u32, rd: u32, rs1: u32, rs2: u32) -> Result<(String, String)> {
+ let width = match funct7 {
+ 0b0000000 | 0b0000100 | 0b0001000 | 0b0001100 => 's',
+ 0b0000001 | 0b0000101 | 0b0001001 | 0b0001101 => 'd',
+ _ => return Err(Error::Decode("invalid float funct7".into())),
+ };
+ let name = match funct3 {
+ 0b000 => format!("fadd.{width}"),
+ 0b001 => format!("fsub.{width}"),
+ 0b010 => format!("fmul.{width}"),
+ 0b011 => format!("fdiv.{width}"),
+ 0b100 => format!("fsgnj.{width}"),
+ 0b101 => format!("fmin.{width}"),
+ 0b110 => format!("fmax.{width}"),
+ 0b111 => format!("fsqrt.{width}"),
+ _ => return Err(Error::Decode("invalid float funct3".into())),
+ };
+ Ok((
+ name,
+ format!("f{}, f{}, f{}", rd, rs1, rs2),
+ ))
+}
+
+fn sign_extend(value: i32, bits: u32) -> i32 {
+ let shift = 32 - bits;
+ (value << shift) >> shift
+}
+
+fn jal_imm(word: u32) -> i32 {
+ let mut imm = 0i32;
+ imm |= (((word >> 21) & 0x3ff) << 1) as i32;
+ imm |= (((word >> 20) & 0x1) << 11) as i32;
+ imm |= (((word >> 12) & 0xff) << 12) as i32;
+ imm |= (((word >> 31) & 0x1) << 20) as i32;
+ sign_extend(imm, 21)
+}
+
+fn b_imm(word: u32) -> i32 {
+ let mut imm = 0i32;
+ imm |= (((word >> 8) & 0xf) << 1) as i32;
+ imm |= (((word >> 25) & 0x3f) << 5) as i32;
+ imm |= (((word >> 7) & 0x1) << 11) as i32;
+ imm |= (((word >> 31) & 0x1) << 12) as i32;
+ sign_extend(imm, 13)
+}
+
+fn s_imm(word: u32) -> i32 {
+ let mut imm = 0i32;
+ imm |= ((word >> 7) & 0x1f) as i32;
+ imm |= (((word >> 25) & 0x7f) as i32) << 5;
+ sign_extend(imm, 12)
+}
+
+pub fn id_for_mnemonic(mnemonic: &str) -> u32 {
+ match mnemonic {
+ "lui" => 1,
+ "auipc" => 2,
+ "jal" => 3,
+ "jalr" => 4,
+ "beq" => 5,
+ "bne" => 6,
+ "blt" => 7,
+ "bge" => 8,
+ "bltu" => 9,
+ "bgeu" => 10,
+ "lb" => 11,
+ "lh" => 12,
+ "lw" => 13,
+ "ld" => 14,
+ "sb" => 15,
+ "sh" => 16,
+ "sw" => 17,
+ "sd" => 18,
+ "addi" => 19,
+ "add" => 20,
+ "sub" => 21,
+ "mul" => 22,
+ "div" => 23,
+ "rem" => 24,
+ "fence" => 25,
+ "ecall" => 26,
+ "ebreak" => 27,
+ "c.addi" => 100,
+ _ => 0,
+ }
+}
+
+pub fn insn_name_by_id(id: u32) -> Option<&'static str> {
+ match id {
+ 1 => Some("lui"),
+ 2 => Some("auipc"),
+ 3 => Some("jal"),
+ 4 => Some("jalr"),
+ 5 => Some("beq"),
+ 6 => Some("bne"),
+ 19 => Some("addi"),
+ 20 => Some("add"),
+ 22 => Some("mul"),
+ 26 => Some("ecall"),
+ 100 => Some("c.addi"),
+ _ => None,
+ }
+}
diff --git a/crates/ghidrust-decode/src/arch/riscv/decode_c.rs b/crates/ghidrust-decode/src/arch/riscv/decode_c.rs
new file mode 100644
index 0000000..eb51fd0
--- /dev/null
+++ b/crates/ghidrust-decode/src/arch/riscv/decode_c.rs
@@ -0,0 +1,296 @@
+use super::regs::reg_name_num;
+use crate::error::{Error, Result};
+
+pub fn decode(half: u16, is64: bool) -> Result<(String, String, usize)> {
+ let quad = half & 0x3;
+ let funct3 = (half >> 13) & 0x7;
+ match quad {
+ 0x0 => quad0(half, funct3),
+ 0x1 => quad1(half, funct3, is64),
+ 0x2 => quad2(half, funct3, is64),
+ _ => Err(Error::Decode("invalid compressed quadrant".into())),
+ }
+}
+
+fn quad0(half: u16, funct3: u16) -> Result<(String, String, usize)> {
+ match funct3 {
+ 0b000 => {
+ let nzuimm = c_nzuimm(half);
+ Ok(("c.addi4spn".into(), format!("{}, sp, {nzuimm}", c_rd(half)), 2))
+ }
+ 0b010 => {
+ let offset = c_lw_offset(half);
+ Ok((
+ "c.lw".into(),
+ format!("{}, {offset}({})", reg_name_num(c_rd(half)), reg_name_num(c_rs1(half))),
+ 2,
+ ))
+ }
+ 0b110 => {
+ let offset = c_sw_offset(half);
+ Ok((
+ "c.sw".into(),
+ format!("{}, {offset}({})", reg_name_num(c_rs2(half)), reg_name_num(c_rs1(half))),
+ 2,
+ ))
+ }
+ _ => Err(Error::Decode("invalid c.quad0".into())),
+ }
+}
+
+fn quad1(half: u16, funct3: u16, is64: bool) -> Result<(String, String, usize)> {
+ match funct3 {
+ 0b000 => {
+ let rd = ((half >> 7) & 0x1f) as u32;
+ if rd == 0 {
+ Ok(("c.nop".into(), String::new(), 2))
+ } else {
+ let imm = c_imm6(half);
+ Ok(("c.addi".into(), format!("{}, {imm}", reg_name_num(rd)), 2))
+ }
+ }
+ 0b001 => {
+ if is64 {
+ Ok(("c.addiw".into(), format!("{}, {}", reg_name_num(c_rd(half)), c_imm6(half)), 2))
+ } else {
+ let offset = c_j_offset(half);
+ Ok(("c.j".into(), format!("{offset:#x}"), 2))
+ }
+ }
+ 0b010 => {
+ let rd = ((half >> 7) & 0x1f) as u32;
+ let imm = c_imm6(half);
+ Ok(("c.li".into(), format!("{}, {imm}", reg_name_num(rd)), 2))
+ }
+ 0b011 => {
+ let rd = ((half >> 7) & 0x1f) as u32;
+ if rd == 2 {
+ let imm = c_sp_imm(half);
+ Ok(("c.addi16sp".into(), format!("sp, {imm}"), 2))
+ } else {
+ let imm = c_lui_imm(half);
+ Ok(("c.lui".into(), format!("{}, {imm:#x}", reg_name_num(rd)), 2))
+ }
+ }
+ 0b100 => {
+ let kind = (half >> 10) & 0x3;
+ let rd = c_rdp(half);
+ let imm = c_srli_imm(half);
+ let name = match kind {
+ 0b00 => "c.srli",
+ 0b01 => "c.srai",
+ 0b10 => "c.andi",
+ _ => return Err(Error::Decode("invalid c.alu".into())),
+ };
+ Ok((name.into(), format!("{}, {imm}", reg_name_num(rd)), 2))
+ }
+ 0b101 => {
+ let offset = c_j_offset(half);
+ Ok(("c.j".into(), format!("{offset:#x}"), 2))
+ }
+ 0b110 => {
+ let offset = c_b_offset(half);
+ Ok((
+ "c.beqz".into(),
+ format!("{}, {offset:#x}", reg_name_num(c_rdp(half))),
+ 2,
+ ))
+ }
+ 0b111 => {
+ let offset = c_b_offset(half);
+ Ok((
+ "c.bnez".into(),
+ format!("{}, {offset:#x}", reg_name_num(c_rdp(half))),
+ 2,
+ ))
+ }
+ _ => Err(Error::Decode("invalid c.quad1".into())),
+ }
+}
+
+fn quad2(half: u16, funct3: u16, is64: bool) -> Result<(String, String, usize)> {
+ match funct3 {
+ 0b000 => {
+ let rs1 = ((half >> 7) & 0x1f) as u32;
+ if rs1 == 0 {
+ return Err(Error::Decode("reserved c.jr".into()));
+ }
+ Ok(("c.jr".into(), format!("{}", reg_name_num(rs1)), 2))
+ }
+ 0b001 => {
+ let rd = ((half >> 7) & 0x1f) as u32;
+ Ok(("c.jal".into(), format!("{}", reg_name_num(rd)), 2))
+ }
+ 0b010 => {
+ let offset = c_ldsp_offset(half, is64);
+ let name = if is64 { "c.ldsp" } else { "c.lwsp" };
+ Ok((
+ name.into(),
+ format!("{}, {offset}(sp)", reg_name_num(c_rd(half))),
+ 2,
+ ))
+ }
+ 0b110 => {
+ let offset = c_sdsp_offset(half, is64);
+ let name = if is64 { "c.sdsp" } else { "c.swsp" };
+ Ok((
+ name.into(),
+ format!("{}, {offset}(sp)", reg_name_num(c_rs2(half))),
+ 2,
+ ))
+ }
+ 0b100 => {
+ let bit12 = (half >> 12) & 1;
+ if bit12 == 0 {
+ let rd = c_rdp(half);
+ let rs2 = c_rs2p(half);
+ Ok(("c.mv".into(), format!("{}, {}", reg_name_num(rd), reg_name_num(rs2)), 2))
+ } else {
+ let rd = c_rdp(half);
+ let rs2 = c_rs2p(half);
+ if rs2 == 0 {
+ Ok(("c.ebreak".into(), String::new(), 2))
+ } else {
+ Ok(("c.add".into(), format!("{}, {}", reg_name_num(rd), reg_name_num(rs2)), 2))
+ }
+ }
+ }
+ _ => Err(Error::Decode("invalid c.quad2".into())),
+ }
+}
+
+fn c_rd(half: u16) -> u32 {
+ 8 + (((half >> 2) & 0x7) as u32)
+}
+
+fn c_rs1(half: u16) -> u32 {
+ 8 + (((half >> 7) & 0x7) as u32)
+}
+
+fn c_rs2(half: u16) -> u32 {
+ 8 + (((half >> 2) & 0x7) as u32)
+}
+
+fn c_rdp(half: u16) -> u32 {
+ 8 + (((half >> 7) & 0x7) as u32)
+}
+
+fn c_rs2p(half: u16) -> u32 {
+ 8 + (((half >> 2) & 0x7) as u32)
+}
+
+fn c_imm6(half: u16) -> i32 {
+ let mut imm = (((half >> 12) & 1) << 5) as i32;
+ imm |= ((half >> 2) & 0x1f) as i32;
+ if imm & 0x20 != 0 {
+ imm -= 64;
+ }
+ imm
+}
+
+fn c_nzuimm(half: u16) -> u32 {
+ let mut imm = 0u32;
+ imm |= u32::from((half >> 6) & 0x1) << 2;
+ imm |= u32::from((half >> 5) & 0x1) << 3;
+ imm |= u32::from((half >> 11) & 0x3) << 4;
+ imm |= u32::from((half >> 7) & 0xf) << 6;
+ imm
+}
+
+fn c_lw_offset(half: u16) -> i32 {
+ let mut off = 0i32;
+ off |= (((half >> 6) & 0x1) as i32) << 2;
+ off |= (((half >> 10) & 0x7) as i32) << 3;
+ off |= (((half >> 5) & 0x1) as i32) << 6;
+ off
+}
+
+fn c_sw_offset(half: u16) -> i32 {
+ c_lw_offset(half)
+}
+
+fn c_j_offset(half: u16) -> i32 {
+ let mut off = 0i32;
+ off |= (((half >> 3) & 0x7) as i32) << 1;
+ off |= (((half >> 11) & 0x1) as i32) << 4;
+ off |= (((half >> 2) & 0x1) as i32) << 5;
+ off |= (((half >> 7) & 0xf) as i32) << 6;
+ off |= (((half >> 6) & 0x1) as i32) << 10;
+ off |= (((half >> 9) & 0x1) as i32) << 11;
+ off |= (((half >> 8) & 0x1) as i32) << 12;
+ off |= (((half >> 12) & 0x1) as i32) << 13;
+ if off & 0x1000 != 0 {
+ off -= 0x2000;
+ }
+ off
+}
+
+fn c_b_offset(half: u16) -> i32 {
+ let mut off = 0i32;
+ off |= (((half >> 3) & 0x3) as i32) << 1;
+ off |= (((half >> 10) & 0x3) as i32) << 3;
+ off |= (((half >> 2) & 0x1) as i32) << 5;
+ off |= (((half >> 5) & 0x3) as i32) << 6;
+ off |= (((half >> 12) & 0x1) as i32) << 8;
+ if off & 0x100 != 0 {
+ off -= 0x200;
+ }
+ off
+}
+
+fn c_sp_imm(half: u16) -> i32 {
+ let mut imm = (((half >> 12) & 1) << 9) as i32;
+ imm |= (((half >> 2) & 0x1f) as i32) << 4;
+ imm |= (((half >> 6) & 0x1) as i32) << 6;
+ imm |= (((half >> 5) & 0x1) as i32) << 7;
+ if imm & 0x200 != 0 {
+ imm -= 0x400;
+ }
+ imm
+}
+
+fn c_lui_imm(half: u16) -> i32 {
+ let mut imm = c_imm6(half) << 12;
+ if imm & 0x80000 != 0 {
+ imm -= 0x100000;
+ }
+ imm
+}
+
+fn c_srli_imm(half: u16) -> u32 {
+ (((half >> 2) & 0x1f) as u32) | (((half >> 12) as u32 & 1) << 5)
+}
+
+fn c_ldsp_offset(half: u16, is64: bool) -> i32 {
+ if is64 {
+ let mut off = 0i32;
+ off |= (((half >> 6) & 0x1) as i32) << 3;
+ off |= (((half >> 5) & 0x1) as i32) << 4;
+ off |= (((half >> 12) & 0x1) as i32) << 5;
+ off |= (((half >> 2) & 0x7) as i32) << 6;
+ off
+ } else {
+ let mut off = 0i32;
+ off |= (((half >> 6) & 0x1) as i32) << 2;
+ off |= (((half >> 4) & 0x7) as i32) << 3;
+ off |= (((half >> 12) & 0x1) as i32) << 5;
+ off |= (((half >> 2) & 0x7) as i32) << 6;
+ off
+ }
+}
+
+fn c_sdsp_offset(half: u16, is64: bool) -> i32 {
+ if is64 {
+ let mut off = 0i32;
+ off |= (((half >> 9) & 0x7) as i32) << 3;
+ off |= (((half >> 7) & 0x3) as i32) << 6;
+ off |= (((half >> 12) & 0x1) as i32) << 8;
+ off
+ } else {
+ let mut off = 0i32;
+ off |= (((half >> 9) & 0x7) as i32) << 2;
+ off |= (((half >> 7) & 0x3) as i32) << 5;
+ off |= (((half >> 12) & 0x1) as i32) << 7;
+ off
+ }
+}
diff --git a/crates/ghidrust-decode/src/arch/riscv/mod.rs b/crates/ghidrust-decode/src/arch/riscv/mod.rs
new file mode 100644
index 0000000..ad4d3e0
--- /dev/null
+++ b/crates/ghidrust-decode/src/arch/riscv/mod.rs
@@ -0,0 +1,162 @@
+//! Hand-rolled RISC-V decoder (RV32/64 I + M/A/F/D + C extension).
+
+mod decode32;
+mod decode_c;
+mod regs;
+
+use crate::arch::ArchDecode;
+use crate::error::{Error, Result};
+use crate::group::GroupId;
+use crate::insn::{InsnDetail, Instruction};
+use crate::names;
+use crate::option::EngineOptions;
+use crate::support::{Arch, Mode};
+
+pub use regs::reg_name;
+
+pub struct RiscvDecoder {
+ mode: Mode,
+}
+
+pub(crate) fn decode_raw(bytes: &[u8], address: u64, mode: Mode) -> Result<Instruction> {
+ if bytes.len() < 2 {
+ return Err(Error::Decode("empty input".into()));
+ }
+ let is_rvc = mode.intersects(Mode::RISCV_C);
+ let is64 = mode.intersects(Mode::RISCV64);
+ if is_rvc && (bytes[0] & 0x03) != 0x03 {
+ if bytes.len() < 2 {
+ return Err(Error::Decode("truncated riscv compressed".into()));
+ }
+ let half = u16::from_le_bytes([bytes[0], bytes[1]]);
+ let (mnemonic, operands, len) = decode_c::decode(half, is64)?;
+ Ok(Instruction::with_text(
+ address,
+ bytes[..len].to_vec(),
+ mnemonic,
+ operands,
+ len as u8,
+ ))
+ } else {
+ if bytes.len() < 4 {
+ return Err(Error::Decode("truncated riscv instruction".into()));
+ }
+ let word = u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]);
+ if (word & 0x03) != 0x03 {
+ return Err(Error::Decode("compressed instruction without RISCV_C".into()));
+ }
+ let (mnemonic, operands) = decode32::decode(word, is64)?;
+ Ok(Instruction::with_text(
+ address,
+ bytes[..4].to_vec(),
+ mnemonic,
+ operands,
+ 4,
+ ))
+ }
+}
+
+impl ArchDecode for RiscvDecoder {
+ fn arch(&self) -> Arch {
+ Arch::Riscv
+ }
+
+ fn open(mode: Mode) -> Result<Self> {
+ if !mode.is_valid_for(Arch::Riscv) {
+ return Err(Error::Mode(format!("invalid riscv mode {:#x}", mode.bits())));
+ }
+ Ok(Self { mode })
+ }
+
+ fn decode_one(&self, bytes: &[u8], address: u64, opts: &EngineOptions) -> Result<Instruction> {
+ let mut insn = decode_raw(bytes, address, self.mode)?;
+ insn.id = names::insn_id_for_mnemonic(Arch::Riscv, &insn.mnemonic);
+ if opts.detail {
+ insn.detail = Some(InsnDetail {
+ groups: groups_for_mnemonic(&insn.mnemonic),
+ ..InsnDetail::default()
+ });
+ }
+ Ok(insn)
+ }
+}
+
+fn groups_for_mnemonic(mnemonic: &str) -> Vec<GroupId> {
+ match mnemonic {
+ "jal" | "jalr" | "c.j" | "c.jal" | "c.jr" | "c.jalr" => vec![GroupId::Call],
+ m if m.starts_with('b') || m.starts_with("c.b") => vec![GroupId::Jump],
+ "ecall" | "ebreak" | "c.ebreak" => vec![GroupId::Int],
+ "mret" | "sret" | "uret" => vec![GroupId::Ret],
+ "fence" | "fence.i" => vec![GroupId::Arch(1)],
+ _ => Vec::new(),
+ }
+}
+
+pub fn insn_name(id: crate::insn::InsnId) -> Option<&'static str> {
+ decode32::insn_name_by_id(id.raw())
+}
+
+pub fn group_name(group: GroupId) -> Option<&'static str> {
+ match group {
+ GroupId::Jump => Some("jump"),
+ GroupId::Call => Some("call"),
+ GroupId::Ret => Some("ret"),
+ GroupId::Int => Some("int"),
+ GroupId::Arch(1) => Some("fence"),
+ _ => None,
+ }
+}
+
+pub fn insn_id_for_mnemonic(mnemonic: &str) -> crate::insn::InsnId {
+ crate::insn::InsnId(decode32::id_for_mnemonic(mnemonic))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::option::EngineOptions;
+
+ fn rv64() -> RiscvDecoder {
+ RiscvDecoder::open(Mode::RISCV64.union(Mode::RISCV_C)).unwrap()
+ }
+
+ #[test]
+ fn riscv_addi_and_lui() {
+ let dec = rv64();
+ // addi x5, x0, 42 => 0x02a00293
+ let addi = [0x93, 0x02, 0xa0, 0x02];
+ let insn = dec.decode_one(&addi, 0, &EngineOptions::default()).unwrap();
+ assert_eq!(insn.mnemonic, "addi");
+ assert_eq!(insn.length, 4);
+
+ // lui x5, 0x12345 => imm << 12
+ let lui = [0xb7, 0x02, 0x45, 0x12];
+ let insn = dec.decode_one(&lui, 0, &EngineOptions::default()).unwrap();
+ assert_eq!(insn.mnemonic, "lui");
+ }
+
+ #[test]
+ fn riscv_branch_and_load() {
+ let dec = rv64();
+ // beq x10, x11, offset => example encoding
+ let beq = [0x63, 0x06, 0xb5, 0x00];
+ let insn = dec.decode_one(&beq, 0x1000, &EngineOptions::default()).unwrap();
+ assert_eq!(insn.mnemonic, "beq");
+
+ // ld x5, 8(x10)
+ let ld = [0x83, 0x32, 0x85, 0x08];
+ let insn = dec.decode_one(&ld, 0, &EngineOptions::default()).unwrap();
+ assert_eq!(insn.mnemonic, "ld");
+ }
+
+ #[test]
+ fn riscv_compressed_addi() {
+ let dec = rv64();
+ // c.addi a0, 1
+ let bytes = [0x05, 0x05];
+ let insn = dec.decode_one(&bytes, 0, &EngineOptions::default()).unwrap();
+ assert_eq!(insn.mnemonic, "c.addi");
+ assert_eq!(insn.operands, "a0, 1");
+ assert_eq!(insn.length, 2);
+ }
+}
diff --git a/crates/ghidrust-decode/src/arch/riscv/regs.rs b/crates/ghidrust-decode/src/arch/riscv/regs.rs
new file mode 100644
index 0000000..734ff7e
--- /dev/null
+++ b/crates/ghidrust-decode/src/arch/riscv/regs.rs
@@ -0,0 +1,43 @@
+use crate::reg::RegId;
+
+pub fn reg_name(reg: RegId) -> Option<&'static str> {
+ match reg.index() {
+ 0 => Some("zero"),
+ 1 => Some("ra"),
+ 2 => Some("sp"),
+ 3 => Some("gp"),
+ 4 => Some("tp"),
+ 5 => Some("t0"),
+ 6 => Some("t1"),
+ 7 => Some("t2"),
+ 8 => Some("s0"),
+ 9 => Some("s1"),
+ 10 => Some("a0"),
+ 11 => Some("a1"),
+ 12 => Some("a2"),
+ 13 => Some("a3"),
+ 14 => Some("a4"),
+ 15 => Some("a5"),
+ 16 => Some("a6"),
+ 17 => Some("a7"),
+ 18 => Some("s2"),
+ 19 => Some("s3"),
+ 20 => Some("s4"),
+ 21 => Some("s5"),
+ 22 => Some("s6"),
+ 23 => Some("s7"),
+ 24 => Some("s8"),
+ 25 => Some("s9"),
+ 26 => Some("s10"),
+ 27 => Some("s11"),
+ 28 => Some("t3"),
+ 29 => Some("t4"),
+ 30 => Some("t5"),
+ 31 => Some("t6"),
+ _ => None,
+ }
+}
+
+pub fn reg_name_num(n: u32) -> &'static str {
+ reg_name(RegId::new(n)).unwrap_or("?")
+}
diff --git a/crates/ghidrust-decode/src/arch/sh/decode.rs b/crates/ghidrust-decode/src/arch/sh/decode.rs
new file mode 100644
index 0000000..f9a1290
--- /dev/null
+++ b/crates/ghidrust-decode/src/arch/sh/decode.rs
@@ -0,0 +1,84 @@
+use crate::error::{Error, Result};
+
+pub fn r(n: u32) -> String {
+ format!("r{n}")
+}
+
+pub fn reg_name(reg: crate::reg::RegId) -> Option<&'static str> {
+ match reg.index() {
+ 0 => Some("r0"),
+ 1 => Some("r1"),
+ 15 => Some("r15"),
+ _ => None,
+ }
+}
+
+pub fn decode(bytes: &[u8], little_endian: bool) -> Result<(String, String, usize)> {
+ if bytes.len() < 2 {
+ return Err(Error::Decode("truncated sh input".into()));
+ }
+ let h = if little_endian {
+ u16::from_le_bytes([bytes[0], bytes[1]])
+ } else {
+ u16::from_be_bytes([bytes[0], bytes[1]])
+ };
+
+ match h {
+ 0x000b => Ok(("rts".into(), String::new(), 2)),
+ 0x0023 => Ok(("bfs".into(), String::new(), 2)),
+ 0x0008 => Ok(("clrt".into(), String::new(), 2)),
+ _ if (h & 0xf00f) == 0x6003 => {
+ let dst = (h >> 8) & 0xf;
+ let src = (h >> 4) & 0xf;
+ Ok(("mov.l".into(), format!("{}, {}", r(u32::from(dst)), r(u32::from(src))), 2))
+ }
+ _ if (h & 0xf000) == 0x7000 => {
+ let reg = (h >> 8) & 0xf;
+ let imm = h as i8 as i64;
+ Ok(("add".into(), format!("#{imm}, {}", r(u32::from(reg))), 2))
+ }
+ _ if (h & 0xf000) == 0x8000 => {
+ let disp = (h & 0x0fff) as i16 as i64;
+ Ok(("bra".into(), format!("{disp}"), 2))
+ }
+ _ if (h & 0xf0ff) == 0x4003 => {
+ let reg = (h >> 8) & 0xf;
+ Ok(("jsr".into(), format!("@{}", r(u32::from(reg))), 2))
+ }
+ _ if (h & 0xf000) == 0x6000 && (h & 0x000f) == 0x0002 => {
+ let dst = (h >> 8) & 0xf;
+ let base = (h >> 4) & 0xf;
+ let disp = ((h >> 4) & 0xf) as i64 * 4;
+ Ok((
+ "mov.l".into(),
+ format!("@({disp}, {}), {}", r(u32::from(base)), r(u32::from(dst))),
+ 2,
+ ))
+ }
+ _ if (h & 0xf000) == 0x2000 => {
+ let dst = (h >> 8) & 0xf;
+ let base = (h >> 4) & 0xf;
+ let disp = (h & 0xf) as i64 * 4;
+ Ok((
+ "mov.l".into(),
+ format!("{}, @({disp}, {})", r(u32::from(dst)), r(u32::from(base))),
+ 2,
+ ))
+ }
+ _ => Err(Error::Decode("unsupported sh opcode".into())),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn sh_mov() {
+ // mov.l r0, r1 => 0x6003 | (1<<8) | (0<<4) = 0x6103
+ let (m, o, l) = decode(&[0x03, 0x61], true).unwrap();
+ assert_eq!(m, "mov.l");
+ assert_eq!(l, 2);
+ assert!(o.contains("r1"));
+ }
+}
diff --git a/crates/ghidrust-decode/src/arch/sh/mod.rs b/crates/ghidrust-decode/src/arch/sh/mod.rs
new file mode 100644
index 0000000..2ff7f98
--- /dev/null
+++ b/crates/ghidrust-decode/src/arch/sh/mod.rs
@@ -0,0 +1,119 @@
+mod decode;
+
+use crate::arch::ArchDecode;
+use crate::error::{Error, Result};
+use crate::group::GroupId;
+use crate::insn::{InsnDetail, InsnId, Instruction};
+use crate::names;
+use crate::option::EngineOptions;
+use crate::support::{Arch, Mode};
+
+pub use decode::reg_name;
+
+pub struct ShDecoder {
+ little_endian: bool,
+}
+
+impl ArchDecode for ShDecoder {
+ fn arch(&self) -> Arch {
+ Arch::Sh
+ }
+
+ fn open(mode: Mode) -> Result<Self> {
+ if !mode.is_valid_for(Arch::Sh) {
+ return Err(Error::Mode(format!("invalid sh mode {:#x}", mode.bits())));
+ }
+ let little_endian = !mode.contains(Mode::BIG_ENDIAN);
+ Ok(Self { little_endian })
+ }
+
+ fn decode_one(&self, bytes: &[u8], address: u64, opts: &EngineOptions) -> Result<Instruction> {
+ let (mnemonic, operands, len) = decode::decode(bytes, self.little_endian)?;
+ let mut insn = Instruction::with_text(
+ address,
+ bytes[..len].to_vec(),
+ mnemonic,
+ operands,
+ len as u8,
+ );
+ insn.id = names::insn_id_for_mnemonic(Arch::Sh, &insn.mnemonic);
+ if opts.detail {
+ insn.detail = Some(InsnDetail {
+ groups: groups_for_mnemonic(&insn.mnemonic),
+ ..InsnDetail::default()
+ });
+ }
+ Ok(insn)
+ }
+}
+
+fn groups_for_mnemonic(mnemonic: &str) -> Vec<GroupId> {
+ match mnemonic {
+ "jsr" => vec![GroupId::Call],
+ "bra" | "bfs" => vec![GroupId::Jump],
+ "rts" => vec![GroupId::Ret],
+ m if m.starts_with("mov") => vec![GroupId::Arch(1)],
+ "add" => vec![GroupId::Arch(2)],
+ _ => Vec::new(),
+ }
+}
+
+pub fn insn_name(id: InsnId) -> Option<&'static str> {
+ match id.raw() {
+ 1 => Some("mov.l"),
+ 2 => Some("add"),
+ 3 => Some("bra"),
+ 4 => Some("jsr"),
+ 5 => Some("rts"),
+ _ => None,
+ }
+}
+
+pub fn group_name(group: GroupId) -> Option<&'static str> {
+ match group {
+ GroupId::Jump => Some("jump"),
+ GroupId::Call => Some("call"),
+ GroupId::Ret => Some("ret"),
+ GroupId::Arch(1) => Some("move"),
+ GroupId::Arch(2) => Some("alu"),
+ _ => None,
+ }
+}
+
+pub fn insn_id_for_mnemonic(mnemonic: &str) -> InsnId {
+ let id = match mnemonic {
+ m if m.starts_with("mov") => 1,
+ "add" => 2,
+ "bra" | "bfs" => 3,
+ "jsr" => 4,
+ "rts" => 5,
+ _ => 0,
+ };
+ InsnId(id)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::engine::Engine;
+
+ #[test]
+ fn sh_mov_and_add() {
+ let mut eng = Engine::open(Arch::Sh, Mode::LITTLE_ENDIAN).unwrap();
+ let mov = eng.disasm_one(&[0x03, 0x61], 0).unwrap();
+ assert_eq!(mov.mnemonic, "mov.l");
+ // add #1, r0 => 0x7101
+ let add = eng.disasm_one(&[0x01, 0x71], 0).unwrap();
+ assert_eq!(add.mnemonic, "add");
+ }
+
+ #[test]
+ fn sh_bra_and_rts() {
+ let mut eng = Engine::open(Arch::Sh, Mode::LITTLE_ENDIAN).unwrap();
+ // bra +4 => 0x8004
+ let bra = eng.disasm_one(&[0x04, 0x80], 0).unwrap();
+ assert_eq!(bra.mnemonic, "bra");
+ let rts = eng.disasm_one(&[0x0b, 0x00], 0).unwrap();
+ assert_eq!(rts.mnemonic, "rts");
+ }
+}
diff --git a/crates/ghidrust-decode/src/arch/sparc/decode.rs b/crates/ghidrust-decode/src/arch/sparc/decode.rs
new file mode 100644
index 0000000..26b791f
--- /dev/null
+++ b/crates/ghidrust-decode/src/arch/sparc/decode.rs
@@ -0,0 +1,161 @@
+use super::regs::g_reg;
+use crate::error::{Error, Result};
+
+const COND: [&str; 16] = [
+ "bn", "be", "ble", "bl", "bleu", "bcs", "bvs", "ba", "bt", "bne", "bg", "bge", "bgu", "bcc",
+ "bvc", "bn",
+];
+
+pub fn read_word(bytes: &[u8], big_endian: bool) -> Result<u32> {
+ if bytes.len() < 4 {
+ return Err(Error::Decode("truncated sparc instruction".into()));
+ }
+ Ok(if big_endian {
+ u32::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])
+ } else {
+ u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])
+ })
+}
+
+pub fn decode(word: u32, address: u64) -> Result<(String, String)> {
+ match word >> 30 {
+ 0 => decode_op0(word, address),
+ 1 => {
+ let disp = sign_ext(word & 0x3fff_ffff, 30);
+ let target = address.wrapping_add((disp << 2) as u64);
+ Ok(("call".into(), format!("0x{target:x}")))
+ }
+ 2 => decode_op2(word),
+ 3 => decode_mem(word),
+ _ => Err(Error::Decode("unsupported sparc opcode".into())),
+ }
+}
+
+fn decode_op0(word: u32, address: u64) -> Result<(String, String)> {
+ if ((word >> 22) & 0x7) == 4 {
+ let rd = (word >> 25) & 0x1f;
+ let imm22 = word & 0x003f_ffff;
+ let imm = u64::from(imm22) << 10;
+ Ok((
+ "sethi".into(),
+ format!("{}, 0x{imm:x}", g_reg(rd)),
+ ))
+ } else if (word >> 22) & 1 == 0 {
+ let cond = ((word >> 25) & 0xf) as usize;
+ let a = if (word >> 29) & 1 != 0 { ",a" } else { "" };
+ let disp = sign_ext(word & 0x003f_ffff, 22);
+ let target = address.wrapping_add((disp << 2) as u64);
+ Ok((
+ format!("{}{a}", COND[cond.min(15)]),
+ format!("0x{target:x}"),
+ ))
+ } else {
+ Err(Error::Decode("unsupported sparc op0".into()))
+ }
+}
+
+fn decode_op2(word: u32) -> Result<(String, String)> {
+ let rd = (word >> 25) & 0x1f;
+ let op3 = (word >> 19) & 0x3f;
+ let rs1 = (word >> 14) & 0x1f;
+ let i = (word >> 13) & 1;
+ let rs2_or_imm = if i != 0 {
+ format!("{}", sign_ext(word & 0x1fff, 13))
+ } else {
+ g_reg(word & 0x1f)
+ };
+
+ match op3 {
+ 0x00 | 0x01 | 0x02 | 0x03 => {
+ let name = match op3 {
+ 0x00 => "add",
+ 0x01 => "and",
+ 0x02 => "or",
+ 0x03 => "xor",
+ _ => unreachable!(),
+ };
+ Ok((
+ name.into(),
+ format!("{}, {}, {rs2_or_imm}", g_reg(rd), g_reg(rs1)),
+ ))
+ }
+ 0x04 | 0x05 | 0x06 | 0x07 => {
+ let name = match op3 {
+ 0x04 => "sub",
+ 0x05 => "andn",
+ 0x06 => "orn",
+ 0x07 => "xnor",
+ _ => unreachable!(),
+ };
+ Ok((
+ name.into(),
+ format!("{}, {}, {rs2_or_imm}", g_reg(rd), g_reg(rs1)),
+ ))
+ }
+ 0x38 => Ok((
+ "jmpl".into(),
+ format!("{}, {rs2_or_imm}, {}", g_reg(rs1), g_reg(rd)),
+ )),
+ 0x39 => Ok((
+ "rett".into(),
+ format!("{}, {rs2_or_imm}", g_reg(rs1)),
+ )),
+ _ => Err(Error::Decode("unsupported sparc alu".into())),
+ }
+}
+
+fn decode_mem(word: u32) -> Result<(String, String)> {
+ let rd = (word >> 25) & 0x1f;
+ let op3 = (word >> 19) & 0x3f;
+ let rs1 = (word >> 14) & 0x1f;
+ let i = (word >> 13) & 1;
+ let addr = if i != 0 {
+ let simm = sign_ext(word & 0x1fff, 13);
+ format!("{}, {simm}", g_reg(rs1))
+ } else {
+ format!("{}, {}", g_reg(rs1), g_reg(word & 0x1f))
+ };
+ let (name, is_load) = match op3 {
+ 0x00 => ("ld", true),
+ 0x01 => ("ldsb", true),
+ 0x02 => ("ldsh", true),
+ 0x03 => ("ldsw", true),
+ 0x08 => ("ldd", true),
+ 0x09 => ("ldub", true),
+ 0x0a => ("lduh", true),
+ 0x0b => ("ldx", true),
+ 0x04 => ("st", false),
+ 0x05 => ("stb", false),
+ 0x06 => ("sth", false),
+ 0x07 => ("stsw", false),
+ 0x0c => ("std", false),
+ 0x0d => ("stub", false),
+ 0x0e => ("stuh", false),
+ 0x0f => ("stx", false),
+ _ => return Err(Error::Decode("unsupported sparc mem".into())),
+ };
+ if is_load {
+ Ok((name.into(), format!("[{addr}], {}", g_reg(rd))))
+ } else {
+ Ok((name.into(), format!("{}, [{addr}]", g_reg(rd))))
+ }
+}
+
+fn sign_ext(val: u32, bits: u32) -> i64 {
+ let shift = 32 - bits;
+ ((val << shift) as i32 >> shift) as i64
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn sparc_sethi_encoding() {
+ // sethi %g1, 0x40000 => imm22=0x100
+ let word = 0x0300_0100;
+ let (m, o) = decode(word, 0).unwrap();
+ assert_eq!(m, "sethi");
+ assert!(o.contains("g1"));
+ }
+}
diff --git a/crates/ghidrust-decode/src/arch/sparc/mod.rs b/crates/ghidrust-decode/src/arch/sparc/mod.rs
new file mode 100644
index 0000000..5e60474
--- /dev/null
+++ b/crates/ghidrust-decode/src/arch/sparc/mod.rs
@@ -0,0 +1,129 @@
+mod decode;
+mod regs;
+
+use crate::arch::ArchDecode;
+use crate::error::{Error, Result};
+use crate::group::GroupId;
+use crate::insn::{InsnDetail, InsnId, Instruction};
+use crate::names;
+use crate::option::EngineOptions;
+use crate::support::{Arch, Mode};
+
+pub use regs::reg_name;
+
+pub struct SparcDecoder {
+ big_endian: bool,
+}
+
+impl ArchDecode for SparcDecoder {
+ fn arch(&self) -> Arch {
+ Arch::Sparc
+ }
+
+ fn open(mode: Mode) -> Result<Self> {
+ if !mode.is_valid_for(Arch::Sparc) {
+ return Err(Error::Mode(format!("invalid sparc mode {:#x}", mode.bits())));
+ }
+ let big_endian = mode.contains(Mode::BIG_ENDIAN);
+ Ok(Self { big_endian })
+ }
+
+ fn decode_one(&self, bytes: &[u8], address: u64, opts: &EngineOptions) -> Result<Instruction> {
+ let word = decode::read_word(bytes, self.big_endian)?;
+ let (mnemonic, operands) = decode::decode(word, address)?;
+ let mut insn = Instruction::with_text(
+ address,
+ bytes[..4].to_vec(),
+ mnemonic,
+ operands,
+ 4,
+ );
+ insn.id = names::insn_id_for_mnemonic(Arch::Sparc, &insn.mnemonic);
+ if opts.detail {
+ insn.detail = Some(InsnDetail {
+ groups: groups_for_mnemonic(&insn.mnemonic),
+ ..InsnDetail::default()
+ });
+ }
+ Ok(insn)
+ }
+}
+
+fn groups_for_mnemonic(mnemonic: &str) -> Vec<GroupId> {
+ match mnemonic {
+ "call" | "jmpl" => vec![GroupId::Call],
+ m if m.starts_with('b') => vec![GroupId::Jump],
+ "rett" => vec![GroupId::Ret],
+ m if m.starts_with("ld") => vec![GroupId::Arch(1)],
+ m if m.starts_with("st") => vec![GroupId::Arch(2)],
+ _ => Vec::new(),
+ }
+}
+
+pub fn insn_name(id: InsnId) -> Option<&'static str> {
+ match id.raw() {
+ 1 => Some("sethi"),
+ 2 => Some("call"),
+ 3 => Some("add"),
+ 4 => Some("ld"),
+ 5 => Some("st"),
+ 6 => Some("jmpl"),
+ 7 => Some("rett"),
+ 8 => Some("ba"),
+ _ => None,
+ }
+}
+
+pub fn group_name(group: GroupId) -> Option<&'static str> {
+ match group {
+ GroupId::Jump => Some("jump"),
+ GroupId::Call => Some("call"),
+ GroupId::Ret => Some("ret"),
+ GroupId::Arch(1) => Some("load"),
+ GroupId::Arch(2) => Some("store"),
+ _ => None,
+ }
+}
+
+pub fn insn_id_for_mnemonic(mnemonic: &str) -> InsnId {
+ let id = match mnemonic {
+ "sethi" => 1,
+ "call" => 2,
+ "add" | "sub" | "and" | "or" | "xor" => 3,
+ "ld" | "ldsb" | "ldsh" | "ldsw" | "ldd" | "ldub" | "lduh" | "ldx" => 4,
+ "st" | "stb" | "sth" | "std" | "stx" => 5,
+ "jmpl" => 6,
+ "rett" => 7,
+ m if m.starts_with('b') => 8,
+ _ => 0,
+ };
+ InsnId(id)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::engine::Engine;
+
+ #[test]
+ fn sparc_sethi_and_add() {
+ let mut eng = Engine::open(Arch::Sparc, Mode::V9.union(Mode::BIG_ENDIAN)).unwrap();
+ // sethi %g1, 0x40000 => 0x03000100
+ let sethi = eng.disasm_one(&[0x03, 0x00, 0x01, 0x00], 0).unwrap();
+ assert_eq!(sethi.mnemonic, "sethi");
+ // add %g1, %g2, %g3 => 0x86004002
+ let add = eng.disasm_one(&[0x86, 0x00, 0x40, 0x02], 0).unwrap();
+ assert_eq!(add.mnemonic, "add");
+ }
+
+ #[test]
+ fn sparc_call_and_branch() {
+ let mut eng = Engine::open(Arch::Sparc, Mode::V9.union(Mode::BIG_ENDIAN)).unwrap();
+ // call 0x1000 from 0: disp30=0x400 => 0x40000400
+ let call = eng.disasm_one(&[0x40, 0x00, 0x04, 0x00], 0).unwrap();
+ assert_eq!(call.mnemonic, "call");
+ // ba +8 from 4: cond=7, disp22=1 => 0x0e000001
+ let ba = eng.disasm_one(&[0x0e, 0x00, 0x00, 0x01], 4).unwrap();
+ assert_eq!(ba.mnemonic, "ba");
+ }
+}
diff --git a/crates/ghidrust-decode/src/arch/sparc/regs.rs b/crates/ghidrust-decode/src/arch/sparc/regs.rs
new file mode 100644
index 0000000..bb2c1de
--- /dev/null
+++ b/crates/ghidrust-decode/src/arch/sparc/regs.rs
@@ -0,0 +1,21 @@
+pub fn g_reg(n: u32) -> String {
+ match n {
+ 0..=7 => format!("%g{n}"),
+ 8..=15 => format!("%o{}", n - 8),
+ 16..=23 => format!("%l{}", n - 16),
+ 24..=31 => format!("%i{}", n - 24),
+ _ => format!("%r{n}"),
+ }
+}
+
+pub fn reg_name(reg: crate::reg::RegId) -> Option<&'static str> {
+ match reg.index() {
+ 0 => Some("g0"),
+ 1 => Some("g1"),
+ 8 => Some("o0"),
+ 14 => Some("o6"),
+ 15 => Some("o7"),
+ 31 => Some("i7"),
+ _ => None,
+ }
+}
diff --git a/crates/ghidrust-decode/src/arch/sysz/decode.rs b/crates/ghidrust-decode/src/arch/sysz/decode.rs
new file mode 100644
index 0000000..e35eba1
--- /dev/null
+++ b/crates/ghidrust-decode/src/arch/sysz/decode.rs
@@ -0,0 +1,97 @@
+use super::regs::g_reg;
+use crate::error::{Error, Result};
+
+pub fn decode(bytes: &[u8], big_endian: bool) -> Result<(String, String, usize)> {
+ if bytes.is_empty() {
+ return Err(Error::Decode("empty sysz input".into()));
+ }
+ let op = bytes[0];
+ match op {
+ 0x07 => decode_bcr(bytes),
+ 0x18 => decode_rr(bytes, "lr"),
+ 0x1a => decode_rr(bytes, "ar"),
+ 0x1b => decode_rr(bytes, "sr"),
+ 0x58 => decode_rx(bytes, "l", big_endian),
+ 0x50 => decode_rx(bytes, "st", big_endian),
+ 0x41 => decode_si(bytes, "la", big_endian),
+ 0xa7 => decode_si(bytes, "tm", big_endian),
+ _ => Err(Error::Decode("unsupported sysz opcode".into())),
+ }
+}
+
+fn decode_rr(bytes: &[u8], name: &str) -> Result<(String, String, usize)> {
+ if bytes.len() < 2 {
+ return Err(Error::Decode("truncated sysz rr".into()));
+ }
+ let r1 = (bytes[1] >> 4) & 0xf;
+ let r2 = bytes[1] & 0xf;
+ Ok((
+ name.into(),
+ format!("{}, {}", g_reg(r1), g_reg(r2)),
+ 2,
+ ))
+}
+
+fn decode_bcr(bytes: &[u8]) -> Result<(String, String, usize)> {
+ if bytes.len() < 2 {
+ return Err(Error::Decode("truncated sysz bcr".into()));
+ }
+ let mask = (bytes[1] >> 4) & 0xf;
+ let r1 = bytes[1] & 0xf;
+ if mask == 0xf && r1 == 0 {
+ Ok(("br".into(), String::new(), 2))
+ } else {
+ Ok((
+ "bcr".into(),
+ format!("{mask}, {}", g_reg(r1)),
+ 2,
+ ))
+ }
+}
+
+fn decode_rx(bytes: &[u8], name: &str, big_endian: bool) -> Result<(String, String, usize)> {
+ if bytes.len() < 4 {
+ return Err(Error::Decode("truncated sysz rx".into()));
+ }
+ let r1 = bytes[3] & 0xf;
+ let x2 = (bytes[3] >> 4) & 0xf;
+ let b2 = bytes[1] & 0xf;
+ let disp = if big_endian {
+ u16::from_be_bytes([bytes[2], bytes[1] & 0xf0]) & 0x0fff
+ } else {
+ u16::from_le_bytes([bytes[2], bytes[1]]) & 0x0fff
+ };
+ let base = if b2 == 0 {
+ String::new()
+ } else {
+ format!("({})", g_reg(b2))
+ };
+ let index = if x2 == 0 {
+ String::new()
+ } else {
+ format!("{}, ", g_reg(x2))
+ };
+ Ok((
+ name.into(),
+ format!("{}, {index}{disp}{base}", g_reg(r1)),
+ 4,
+ ))
+}
+
+fn decode_si(bytes: &[u8], name: &str, big_endian: bool) -> Result<(String, String, usize)> {
+ if bytes.len() < 4 {
+ return Err(Error::Decode("truncated sysz si".into()));
+ }
+ let r1 = bytes[1] & 0xf;
+ let b2 = (bytes[1] >> 4) & 0xf;
+ let disp = if big_endian {
+ i32::from_be_bytes([0, bytes[2], bytes[3], 0]) >> 8
+ } else {
+ i32::from_le_bytes([bytes[2], bytes[3], 0, 0]) >> 8
+ };
+ Ok((
+ name.into(),
+ format!("{}, {disp}({})", g_reg(r1), g_reg(b2)),
+ 4,
+ ))
+}
diff --git a/crates/ghidrust-decode/src/arch/sysz/mod.rs b/crates/ghidrust-decode/src/arch/sysz/mod.rs
new file mode 100644
index 0000000..4073ea8
--- /dev/null
+++ b/crates/ghidrust-decode/src/arch/sysz/mod.rs
@@ -0,0 +1,122 @@
+mod decode;
+mod regs;
+
+use crate::arch::ArchDecode;
+use crate::error::{Error, Result};
+use crate::group::GroupId;
+use crate::insn::{InsnDetail, InsnId, Instruction};
+use crate::names;
+use crate::option::EngineOptions;
+use crate::support::{Arch, Mode};
+
+pub use regs::reg_name;
+
+pub struct SyszDecoder {
+ big_endian: bool,
+}
+
+impl ArchDecode for SyszDecoder {
+ fn arch(&self) -> Arch {
+ Arch::Sysz
+ }
+
+ fn open(mode: Mode) -> Result<Self> {
+ if !mode.is_valid_for(Arch::Sysz) {
+ return Err(Error::Mode(format!("invalid sysz mode {:#x}", mode.bits())));
+ }
+ let big_endian = !mode.intersects(Mode::LITTLE_ENDIAN) || mode.contains(Mode::BIG_ENDIAN);
+ Ok(Self { big_endian })
+ }
+
+ fn decode_one(&self, bytes: &[u8], address: u64, opts: &EngineOptions) -> Result<Instruction> {
+ let (mnemonic, operands, len) = decode::decode(bytes, self.big_endian)?;
+ let mut insn = Instruction::with_text(
+ address,
+ bytes[..len].to_vec(),
+ mnemonic,
+ operands,
+ len as u8,
+ );
+ insn.id = names::insn_id_for_mnemonic(Arch::Sysz, &insn.mnemonic);
+ if opts.detail {
+ insn.detail = Some(InsnDetail {
+ groups: groups_for_mnemonic(&insn.mnemonic),
+ ..InsnDetail::default()
+ });
+ }
+ Ok(insn)
+ }
+}
+
+fn groups_for_mnemonic(mnemonic: &str) -> Vec<GroupId> {
+ match mnemonic {
+ "bcr" | "br" => vec![GroupId::Jump],
+ "l" | "la" => vec![GroupId::Arch(1)],
+ "st" => vec![GroupId::Arch(2)],
+ "ar" | "sr" => vec![GroupId::Arch(3)],
+ _ => Vec::new(),
+ }
+}
+
+pub fn insn_name(id: InsnId) -> Option<&'static str> {
+ match id.raw() {
+ 1 => Some("lr"),
+ 2 => Some("l"),
+ 3 => Some("st"),
+ 4 => Some("bcr"),
+ 5 => Some("br"),
+ 6 => Some("ar"),
+ _ => None,
+ }
+}
+
+pub fn group_name(group: GroupId) -> Option<&'static str> {
+ match group {
+ GroupId::Jump => Some("jump"),
+ GroupId::Arch(1) => Some("load"),
+ GroupId::Arch(2) => Some("store"),
+ GroupId::Arch(3) => Some("alu"),
+ _ => None,
+ }
+}
+
+pub fn insn_id_for_mnemonic(mnemonic: &str) -> InsnId {
+ let id = match mnemonic {
+ "lr" => 1,
+ "l" | "la" => 2,
+ "st" => 3,
+ "bcr" => 4,
+ "br" => 5,
+ "ar" | "sr" => 6,
+ _ => 0,
+ };
+ InsnId(id)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::engine::Engine;
+
+ #[test]
+ fn sysz_lr_and_ar() {
+ let mut eng = Engine::open(Arch::Sysz, Mode::BIG_ENDIAN).unwrap();
+ // LR r1, r2 => 0x18 0x12
+ let lr = eng.disasm_one(&[0x18, 0x12], 0).unwrap();
+ assert_eq!(lr.mnemonic, "lr");
+ // AR r3, r4 => 0x1a 0x34
+ let ar = eng.disasm_one(&[0x1a, 0x34], 0).unwrap();
+ assert_eq!(ar.mnemonic, "ar");
+ }
+
+ #[test]
+ fn sysz_br_and_l() {
+ let mut eng = Engine::open(Arch::Sysz, Mode::BIG_ENDIAN).unwrap();
+ // BR => BCR 15, 0 => 0x07 0xf0
+ let br = eng.disasm_one(&[0x07, 0xf0], 0).unwrap();
+ assert_eq!(br.mnemonic, "br");
+ // L r3, 0(,r4) => 58 40 00 03
+ let l = eng.disasm_one(&[0x58, 0x40, 0x00, 0x03], 0).unwrap();
+ assert_eq!(l.mnemonic, "l");
+ }
+}
diff --git a/crates/ghidrust-decode/src/arch/sysz/regs.rs b/crates/ghidrust-decode/src/arch/sysz/regs.rs
new file mode 100644
index 0000000..611e116
--- /dev/null
+++ b/crates/ghidrust-decode/src/arch/sysz/regs.rs
@@ -0,0 +1,14 @@
+pub fn g_reg(n: u8) -> String {
+ format!("r{n}")
+}
+
+pub fn reg_name(reg: crate::reg::RegId) -> Option<&'static str> {
+ match reg.index() {
+ 0 => Some("r0"),
+ 1 => Some("r1"),
+ 2 => Some("r2"),
+ 14 => Some("r14"),
+ 15 => Some("r15"),
+ _ => None,
+ }
+}
diff --git a/crates/ghidrust-decode/src/arch/tms320c64x/decode.rs b/crates/ghidrust-decode/src/arch/tms320c64x/decode.rs
new file mode 100644
index 0000000..c6cbb4f
--- /dev/null
+++ b/crates/ghidrust-decode/src/arch/tms320c64x/decode.rs
@@ -0,0 +1,97 @@
+use crate::error::{Error, Result};
+
+pub fn reg_name(reg: crate::reg::RegId) -> Option<&'static str> {
+ match reg.index() {
+ 0 => Some("a0"),
+ 1 => Some("a1"),
+ 2 => Some("b0"),
+ _ => None,
+ }
+}
+
+pub fn decode(bytes: &[u8], little_endian: bool) -> Result<(String, String, usize)> {
+ if bytes.len() < 4 {
+ return Err(Error::Decode("truncated c64x instruction".into()));
+ }
+ let word = if little_endian {
+ u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])
+ } else {
+ u32::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])
+ };
+ let creg = (word >> 13) & 0x7;
+ let opcode = (word >> 12) & 0x1;
+ let src = (word >> 18) & 0x1f;
+ let dst = (word >> 23) & 0x1f;
+ let p = (word >> 31) & 1;
+
+ if opcode == 0 && ((word >> 5) & 0x7f) == 0x02 {
+ // MV instruction family
+ let unit = match creg {
+ 0 => "s",
+ 1 => "l",
+ 2 => "d",
+ 3 => "m",
+ _ => "x",
+ };
+ Ok((
+ format!("mv.{unit}"),
+ format!("a{dst}, a{src}"),
+ 4,
+ ))
+ } else if (word >> 28) & 0xf == 0x1 {
+ let offset = sign_ext((word >> 7) & 0x1ffff, 17);
+ Ok((
+ if p != 0 { "b.s".into() } else { "b".into() },
+ format!("{offset}"),
+ 4,
+ ))
+ } else if (word >> 28) & 0xf == 0x2 {
+ Ok((
+ "add.l".into(),
+ format!("a{dst}, a{src}, a{dst}"),
+ 4,
+ ))
+ } else if (word >> 28) & 0xf == 0x3 {
+ Ok((
+ "sub.l".into(),
+ format!("a{dst}, a{src}, a{dst}"),
+ 4,
+ ))
+ } else if (word >> 28) & 0xf == 0x4 {
+ let off = (word >> 7) & 0x7fff;
+ Ok((
+ "ldw".into(),
+ format!("*+a{src}[{off}], a{dst}"),
+ 4,
+ ))
+ } else if (word >> 28) & 0xf == 0x5 {
+ let off = (word >> 7) & 0x7fff;
+ Ok((
+ "stw".into(),
+ format!("a{src}, *+a{dst}[{off}]"),
+ 4,
+ ))
+ } else {
+ Err(Error::Decode("unsupported c64x opcode".into()))
+ }
+}
+
+fn sign_ext(val: u32, bits: u32) -> i64 {
+ let shift = 32 - bits;
+ ((val << shift) as i32 >> shift) as i64
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn c64x_mv() {
+ // mv.l a2, a1 pattern
+ let word = 0x0200_0041u32;
+ let bytes = word.to_le_bytes();
+ let (m, _, l) = decode(&bytes, true).unwrap();
+ assert_eq!(l, 4);
+ assert!(m.starts_with("mv."));
+ }
+}
diff --git a/crates/ghidrust-decode/src/arch/tms320c64x/mod.rs b/crates/ghidrust-decode/src/arch/tms320c64x/mod.rs
new file mode 100644
index 0000000..1f00c58
--- /dev/null
+++ b/crates/ghidrust-decode/src/arch/tms320c64x/mod.rs
@@ -0,0 +1,127 @@
+mod decode;
+
+use crate::arch::ArchDecode;
+use crate::error::{Error, Result};
+use crate::group::GroupId;
+use crate::insn::{InsnDetail, InsnId, Instruction};
+use crate::names;
+use crate::option::EngineOptions;
+use crate::support::{Arch, Mode};
+
+pub use decode::reg_name;
+
+pub struct Tms320c64xDecoder {
+ little_endian: bool,
+}
+
+impl ArchDecode for Tms320c64xDecoder {
+ fn arch(&self) -> Arch {
+ Arch::Tms320c64x
+ }
+
+ fn open(mode: Mode) -> Result<Self> {
+ if !mode.is_valid_for(Arch::Tms320c64x) {
+ return Err(Error::Mode(format!(
+ "invalid tms320c64x mode {:#x}",
+ mode.bits()
+ )));
+ }
+ let little_endian = !mode.contains(Mode::BIG_ENDIAN);
+ Ok(Self { little_endian })
+ }
+
+ fn decode_one(&self, bytes: &[u8], address: u64, opts: &EngineOptions) -> Result<Instruction> {
+ let (mnemonic, operands, len) = decode::decode(bytes, self.little_endian)?;
+ let mut insn = Instruction::with_text(
+ address,
+ bytes[..len].to_vec(),
+ mnemonic,
+ operands,
+ len as u8,
+ );
+ insn.id = names::insn_id_for_mnemonic(Arch::Tms320c64x, &insn.mnemonic);
+ if opts.detail {
+ insn.detail = Some(InsnDetail {
+ groups: groups_for_mnemonic(&insn.mnemonic),
+ ..InsnDetail::default()
+ });
+ }
+ Ok(insn)
+ }
+}
+
+fn groups_for_mnemonic(mnemonic: &str) -> Vec<GroupId> {
+ match mnemonic {
+ "b" | "b.s" => vec![GroupId::Jump],
+ "ldw" => vec![GroupId::Arch(1)],
+ "stw" => vec![GroupId::Arch(2)],
+ m if m.starts_with("add") || m.starts_with("sub") => vec![GroupId::Arch(3)],
+ m if m.starts_with("mv.") => vec![GroupId::Arch(4)],
+ _ => Vec::new(),
+ }
+}
+
+pub fn insn_name(id: InsnId) -> Option<&'static str> {
+ match id.raw() {
+ 1 => Some("mv.l"),
+ 2 => Some("add.l"),
+ 3 => Some("b"),
+ 4 => Some("ldw"),
+ 5 => Some("stw"),
+ _ => None,
+ }
+}
+
+pub fn group_name(group: GroupId) -> Option<&'static str> {
+ match group {
+ GroupId::Jump => Some("jump"),
+ GroupId::Arch(1) => Some("load"),
+ GroupId::Arch(2) => Some("store"),
+ GroupId::Arch(3) => Some("alu"),
+ GroupId::Arch(4) => Some("move"),
+ _ => None,
+ }
+}
+
+pub fn insn_id_for_mnemonic(mnemonic: &str) -> InsnId {
+ let id = match mnemonic {
+ m if m.starts_with("mv.") => 1,
+ m if m.starts_with("add") => 2,
+ "b" | "b.s" => 3,
+ "ldw" => 4,
+ "stw" => 5,
+ m if m.starts_with("sub") => 2,
+ _ => 0,
+ };
+ InsnId(id)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::engine::Engine;
+
+ #[test]
+ fn c64x_mv_and_add() {
+ let mut eng = Engine::open(Arch::Tms320c64x, Mode::LITTLE_ENDIAN).unwrap();
+ // mv.l a1, a2
+ let mv = eng
+ .disasm_one(&[0x41, 0x00, 0x00, 0x02], 0)
+ .unwrap();
+ assert!(mv.mnemonic.starts_with("mv."));
+ // add.l a1, a2, a1
+ let add = eng
+ .disasm_one(&[0x00, 0x00, 0x00, 0x20], 0)
+ .unwrap();
+ assert_eq!(add.mnemonic, "add.l");
+ }
+
+ #[test]
+ fn c64x_branch_and_ldw() {
+ let mut eng = Engine::open(Arch::Tms320c64x, Mode::LITTLE_ENDIAN).unwrap();
+ let b = eng.disasm_one(&[0x00, 0x00, 0x00, 0x10], 0).unwrap();
+ assert_eq!(b.mnemonic, "b");
+ let ldw = eng.disasm_one(&[0x00, 0x00, 0x00, 0x40], 0).unwrap();
+ assert_eq!(ldw.mnemonic, "ldw");
+ }
+}
diff --git a/crates/ghidrust-decode/src/arch/tricore/decode.rs b/crates/ghidrust-decode/src/arch/tricore/decode.rs
new file mode 100644
index 0000000..1dd2bac
--- /dev/null
+++ b/crates/ghidrust-decode/src/arch/tricore/decode.rs
@@ -0,0 +1,163 @@
+use crate::error::{Error, Result};
+
+pub fn reg_name(reg: crate::reg::RegId) -> Option<&'static str> {
+ match reg.index() {
+ 0 => Some("d0"),
+ 1 => Some("d1"),
+ 10 => Some("a10"),
+ 11 => Some("a11"),
+ 15 => Some("a15"),
+ _ => None,
+ }
+}
+
+fn d(n: u32) -> String {
+ format!("d{n}")
+}
+
+fn a(n: u32) -> String {
+ format!("a{n}")
+}
+
+pub fn decode(bytes: &[u8], little_endian: bool) -> Result<(String, String, usize)> {
+ if bytes.len() < 2 {
+ return Err(Error::Decode("truncated tricore input".into()));
+ }
+ let half = if little_endian {
+ u16::from_le_bytes([bytes[0], bytes[1]])
+ } else {
+ u16::from_be_bytes([bytes[0], bytes[1]])
+ };
+
+ if half == 0x8000 {
+ if bytes.len() < 4 {
+ return Err(Error::Decode("truncated tricore 32-bit".into()));
+ }
+ let word = if little_endian {
+ u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])
+ } else {
+ u32::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])
+ };
+ decode32(word)
+ } else {
+ decode16(half)
+ }
+}
+
+fn decode16(h: u16) -> Result<(String, String, usize)> {
+ let op = (h >> 12) & 0xf;
+ match op {
+ 0x0 => {
+ let dst = (h >> 8) & 0xf;
+ let src = (h >> 4) & 0xf;
+ Ok(("mov".into(), format!("{}, {}", d(u32::from(dst)), d(u32::from(src))), 2))
+ }
+ 0x1 => {
+ let dst = (h >> 8) & 0xf;
+ let src = (h >> 4) & 0xf;
+ Ok(("add".into(), format!("{}, {}", d(u32::from(dst)), d(u32::from(src))), 2))
+ }
+ 0x8 => {
+ let disp = sign_ext16((h & 0x0fff) as i16, 12);
+ Ok(("j".into(), format!("{disp}"), 2))
+ }
+ 0x9 => {
+ let disp = sign_ext16((h & 0x0fff) as i16, 12);
+ Ok(("jl".into(), format!("{disp}"), 2))
+ }
+ 0xa => {
+ let dst = (h >> 8) & 0xf;
+ let base = (h >> 4) & 0xf;
+ let off = (h & 0xf) as i64 * 4;
+ Ok((
+ "ld.w".into(),
+ format!("{}, [{off}({})]", d(u32::from(dst)), a(u32::from(base))),
+ 2,
+ ))
+ }
+ 0xb => {
+ let src = (h >> 8) & 0xf;
+ let base = (h >> 4) & 0xf;
+ let off = (h & 0xf) as i64 * 4;
+ Ok((
+ "st.w".into(),
+ format!("{}, [{off}({})]", d(u32::from(src)), a(u32::from(base))),
+ 2,
+ ))
+ }
+ _ => Err(Error::Decode("unsupported tricore 16-bit".into())),
+ }
+}
+
+fn decode32(word: u32) -> Result<(String, String, usize)> {
+ let op = (word >> 28) & 0xf;
+ match op {
+ 0x1 => {
+ let dst = (word >> 20) & 0xf;
+ let src = (word >> 16) & 0xf;
+ Ok(("mov".into(), format!("{}, {}", d(dst), d(src)), 4))
+ }
+ 0x2 => {
+ let dst = (word >> 20) & 0xf;
+ let src1 = (word >> 16) & 0xf;
+ let src2 = (word >> 12) & 0xf;
+ Ok((
+ "add".into(),
+ format!("{}, {}, {}", d(dst), d(src1), d(src2)),
+ 4,
+ ))
+ }
+ 0x8 => {
+ let disp = sign_ext32((word & 0x0fffffff) as i32, 28);
+ Ok(("j".into(), format!("{disp}"), 4))
+ }
+ 0x9 => {
+ let disp = sign_ext32((word & 0x0fffffff) as i32, 28);
+ Ok(("jl".into(), format!("{disp}"), 4))
+ }
+ 0xa => {
+ let dst = (word >> 20) & 0xf;
+ let base = (word >> 16) & 0xf;
+ let off = (word >> 4) & 0xfff;
+ Ok((
+ "ld.w".into(),
+ format!("{}, [{off}({})]", d(u32::from(dst)), a(u32::from(base))),
+ 4,
+ ))
+ }
+ 0xb => {
+ let src = (word >> 20) & 0xf;
+ let base = (word >> 16) & 0xf;
+ let off = (word >> 4) & 0xfff;
+ Ok((
+ "st.w".into(),
+ format!("{}, [{off}({})]", d(u32::from(src)), a(u32::from(base))),
+ 4,
+ ))
+ }
+ _ => Err(Error::Decode("unsupported tricore 32-bit".into())),
+ }
+}
+
+fn sign_ext16(val: i16, bits: u32) -> i64 {
+ let shift = 16 - bits as i32;
+ ((val << shift) >> shift) as i64
+}
+
+fn sign_ext32(val: i32, bits: u32) -> i64 {
+ let shift = 32 - bits as i32;
+ ((val << shift) >> shift) as i64
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn tricore_mov16() {
+ // mov d1, d2 => op=0 dst=1 src=2 => 0x0120
+ let (m, _, l) = decode(&[0x20, 0x01], true).unwrap();
+ assert_eq!(m, "mov");
+ assert_eq!(l, 2);
+ }
+}
diff --git a/crates/ghidrust-decode/src/arch/tricore/mod.rs b/crates/ghidrust-decode/src/arch/tricore/mod.rs
new file mode 100644
index 0000000..f04078e
--- /dev/null
+++ b/crates/ghidrust-decode/src/arch/tricore/mod.rs
@@ -0,0 +1,121 @@
+mod decode;
+
+use crate::arch::ArchDecode;
+use crate::error::{Error, Result};
+use crate::group::GroupId;
+use crate::insn::{InsnDetail, InsnId, Instruction};
+use crate::names;
+use crate::option::EngineOptions;
+use crate::support::{Arch, Mode};
+
+pub use decode::reg_name;
+
+pub struct TricoreDecoder {
+ little_endian: bool,
+}
+
+impl ArchDecode for TricoreDecoder {
+ fn arch(&self) -> Arch {
+ Arch::Tricore
+ }
+
+ fn open(mode: Mode) -> Result<Self> {
+ if !mode.is_valid_for(Arch::Tricore) {
+ return Err(Error::Mode(format!("invalid tricore mode {:#x}", mode.bits())));
+ }
+ let little_endian = !mode.contains(Mode::BIG_ENDIAN);
+ Ok(Self { little_endian })
+ }
+
+ fn decode_one(&self, bytes: &[u8], address: u64, opts: &EngineOptions) -> Result<Instruction> {
+ let (mnemonic, operands, len) = decode::decode(bytes, self.little_endian)?;
+ let mut insn = Instruction::with_text(
+ address,
+ bytes[..len].to_vec(),
+ mnemonic,
+ operands,
+ len as u8,
+ );
+ insn.id = names::insn_id_for_mnemonic(Arch::Tricore, &insn.mnemonic);
+ if opts.detail {
+ insn.detail = Some(InsnDetail {
+ groups: groups_for_mnemonic(&insn.mnemonic),
+ ..InsnDetail::default()
+ });
+ }
+ Ok(insn)
+ }
+}
+
+fn groups_for_mnemonic(mnemonic: &str) -> Vec<GroupId> {
+ match mnemonic {
+ "j" => vec![GroupId::Jump],
+ "jl" => vec![GroupId::Call],
+ "ld.w" => vec![GroupId::Arch(1)],
+ "st.w" => vec![GroupId::Arch(2)],
+ "add" | "mov" => vec![GroupId::Arch(3)],
+ _ => Vec::new(),
+ }
+}
+
+pub fn insn_name(id: InsnId) -> Option<&'static str> {
+ match id.raw() {
+ 1 => Some("mov"),
+ 2 => Some("add"),
+ 3 => Some("j"),
+ 4 => Some("jl"),
+ 5 => Some("ld.w"),
+ _ => None,
+ }
+}
+
+pub fn group_name(group: GroupId) -> Option<&'static str> {
+ match group {
+ GroupId::Jump => Some("jump"),
+ GroupId::Call => Some("call"),
+ GroupId::Arch(1) => Some("load"),
+ GroupId::Arch(2) => Some("store"),
+ GroupId::Arch(3) => Some("alu"),
+ _ => None,
+ }
+}
+
+pub fn insn_id_for_mnemonic(mnemonic: &str) -> InsnId {
+ let id = match mnemonic {
+ "mov" => 1,
+ "add" => 2,
+ "j" => 3,
+ "jl" => 4,
+ "ld.w" => 5,
+ "st.w" => 5,
+ _ => 0,
+ };
+ InsnId(id)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::engine::Engine;
+
+ #[test]
+ fn tricore_mov_and_add() {
+ let mut eng = Engine::open(Arch::Tricore, Mode::LITTLE_ENDIAN).unwrap();
+ let mov = eng.disasm_one(&[0x20, 0x01], 0).unwrap();
+ assert_eq!(mov.mnemonic, "mov");
+ // add d3, d1, d2 => op=1 dst=3 src1=1 src2=2 => 0x1312
+ let add = eng.disasm_one(&[0x12, 0x13], 0).unwrap();
+ assert_eq!(add.mnemonic, "add");
+ }
+
+ #[test]
+ fn tricore_j_and_ldw() {
+ let mut eng = Engine::open(Arch::Tricore, Mode::LITTLE_ENDIAN).unwrap();
+ // j +4 => 0x8004
+ let j = eng.disasm_one(&[0x04, 0x80], 0).unwrap();
+ assert_eq!(j.mnemonic, "j");
+ // ld.w d1, [0(a2)] => op=a dst=1 base=2 off=0 => 0xa120
+ let ld = eng.disasm_one(&[0x20, 0xa1], 0).unwrap();
+ assert_eq!(ld.mnemonic, "ld.w");
+ }
+}
diff --git a/crates/ghidrust-decode/src/arch/wasm/mod.rs b/crates/ghidrust-decode/src/arch/wasm/mod.rs
new file mode 100644
index 0000000..356d7ce
--- /dev/null
+++ b/crates/ghidrust-decode/src/arch/wasm/mod.rs
@@ -0,0 +1,392 @@
+//! Hand-rolled WebAssembly opcode decoder (MVP + numeric ops).
+
+use crate::arch::leb128;
+use crate::arch::ArchDecode;
+use crate::error::{Error, Result};
+use crate::group::GroupId;
+use crate::insn::{InsnDetail, InsnId, Instruction};
+use crate::names;
+use crate::operand::Operand;
+use crate::option::EngineOptions;
+use crate::reg::RegId;
+use crate::support::{Arch, Mode};
+
+pub struct WasmDecoder {
+ _mode: Mode,
+}
+
+const OPCODE_MNEMONIC: [&str; 256] = {
+ let mut table = ["invalid"; 256];
+ table[0x00] = "unreachable";
+ table[0x01] = "nop";
+ table[0x02] = "block";
+ table[0x03] = "loop";
+ table[0x04] = "if";
+ table[0x05] = "else";
+ table[0x0b] = "end";
+ table[0x0c] = "br";
+ table[0x0d] = "br_if";
+ table[0x0e] = "br_table";
+ table[0x0f] = "return";
+ table[0x10] = "call";
+ table[0x11] = "call_indirect";
+ table[0x1a] = "drop";
+ table[0x1b] = "select";
+ table[0x20] = "get_local";
+ table[0x21] = "set_local";
+ table[0x22] = "tee_local";
+ table[0x23] = "get_global";
+ table[0x24] = "set_global";
+ table[0x28] = "i32.load";
+ table[0x29] = "i64.load";
+ table[0x2a] = "f32.load";
+ table[0x2b] = "f64.load";
+ table[0x2c] = "i32.load8_s";
+ table[0x2d] = "i32.load8_u";
+ table[0x2e] = "i32.load16_s";
+ table[0x2f] = "i32.load16_u";
+ table[0x30] = "i64.load8_s";
+ table[0x31] = "i64.load8_u";
+ table[0x32] = "i64.load16_s";
+ table[0x33] = "i64.load16_u";
+ table[0x34] = "i64.load32_s";
+ table[0x35] = "i64.load32_u";
+ table[0x36] = "i32.store";
+ table[0x37] = "i64.store";
+ table[0x38] = "f32.store";
+ table[0x39] = "f64.store";
+ table[0x3a] = "i32.store8";
+ table[0x3b] = "i32.store16";
+ table[0x3c] = "i64.store8";
+ table[0x3d] = "i64.store16";
+ table[0x3e] = "i64.store32";
+ table[0x3f] = "current_memory";
+ table[0x40] = "grow_memory";
+ table[0x41] = "i32.const";
+ table[0x42] = "i64.const";
+ table[0x43] = "f32.const";
+ table[0x44] = "f64.const";
+ table[0x45] = "i32.eqz";
+ table[0x46] = "i32.eq";
+ table[0x47] = "i32.ne";
+ table[0x48] = "i32.lt_s";
+ table[0x49] = "i32.lt_u";
+ table[0x4a] = "i32.gt_s";
+ table[0x4b] = "i32.gt_u";
+ table[0x4c] = "i32.le_s";
+ table[0x4d] = "i32.le_u";
+ table[0x4e] = "i32.ge_s";
+ table[0x4f] = "i32.ge_u";
+ table[0x50] = "i64.eqz";
+ table[0x51] = "i64.eq";
+ table[0x52] = "i64.ne";
+ table[0x53] = "i64.lt_s";
+ table[0x54] = "i64.lt_u";
+ table[0x55] = "i64.gt_s";
+ table[0x56] = "i64.gt_u";
+ table[0x57] = "i64.le_s";
+ table[0x58] = "i64.le_u";
+ table[0x59] = "i64.ge_s";
+ table[0x5a] = "i64.ge_u";
+ table[0x5b] = "f32.eq";
+ table[0x5c] = "f32.ne";
+ table[0x5d] = "f32.lt";
+ table[0x5e] = "f32.gt";
+ table[0x5f] = "f32.le";
+ table[0x60] = "f32.ge";
+ table[0x61] = "f64.eq";
+ table[0x62] = "f64.ne";
+ table[0x63] = "f64.lt";
+ table[0x64] = "f64.gt";
+ table[0x65] = "f64.le";
+ table[0x66] = "f64.ge";
+ table[0x67] = "i32.clz";
+ table[0x68] = "i32.ctz";
+ table[0x69] = "i32.popcnt";
+ table[0x6a] = "i32.add";
+ table[0x6b] = "i32.sub";
+ table[0x6c] = "i32.mul";
+ table[0x6d] = "i32.div_s";
+ table[0x6e] = "i32.div_u";
+ table[0x6f] = "i32.rem_s";
+ table[0x70] = "i32.rem_u";
+ table[0x71] = "i32.and";
+ table[0x72] = "i32.or";
+ table[0x73] = "i32.xor";
+ table[0x74] = "i32.shl";
+ table[0x75] = "i32.shr_s";
+ table[0x76] = "i32.shr_u";
+ table[0x77] = "i32.rotl";
+ table[0x78] = "i32.rotr";
+ table[0x79] = "i64.clz";
+ table[0x7a] = "i64.ctz";
+ table[0x7b] = "i64.popcnt";
+ table[0x7c] = "i64.add";
+ table[0x7d] = "i64.sub";
+ table[0x7e] = "i64.mul";
+ table[0x7f] = "i64.div_s";
+ table[0x80] = "i64.div_u";
+ table[0x81] = "i64.rem_s";
+ table[0x82] = "i64.rem_u";
+ table[0x83] = "i64.and";
+ table[0x84] = "i64.or";
+ table[0x85] = "i64.xor";
+ table[0x86] = "i64.shl";
+ table[0x87] = "i64.shr_s";
+ table[0x88] = "i64.shr_u";
+ table[0x89] = "i64.rotl";
+ table[0x8a] = "i64.rotr";
+ table[0x8b] = "f32.abs";
+ table[0x8c] = "f32.neg";
+ table[0x8d] = "f32.ceil";
+ table[0x8e] = "f32.floor";
+ table[0x8f] = "f32.trunc";
+ table[0x90] = "f32.nearest";
+ table[0x91] = "f32.sqrt";
+ table[0x92] = "f32.add";
+ table[0x93] = "f32.sub";
+ table[0x94] = "f32.mul";
+ table[0x95] = "f32.div";
+ table[0x96] = "f32.min";
+ table[0x97] = "f32.max";
+ table[0x98] = "f32.copysign";
+ table[0x99] = "f64.abs";
+ table[0x9a] = "f64.neg";
+ table[0x9b] = "f64.ceil";
+ table[0x9c] = "f64.floor";
+ table[0x9d] = "f64.trunc";
+ table[0x9e] = "f64.nearest";
+ table[0x9f] = "f64.sqrt";
+ table[0xa0] = "f64.add";
+ table[0xa1] = "f64.sub";
+ table[0xa2] = "f64.mul";
+ table[0xa3] = "f64.div";
+ table[0xa4] = "f64.min";
+ table[0xa5] = "f64.max";
+ table[0xa6] = "f64.copysign";
+ table
+};
+
+pub(crate) fn decode_raw(bytes: &[u8], address: u64) -> Result<Instruction> {
+ if bytes.is_empty() {
+ return Err(Error::Decode("empty input".into()));
+ }
+ let opcode = bytes[0];
+ let mnemonic = OPCODE_MNEMONIC[opcode as usize];
+ if mnemonic == "invalid" {
+ return Ok(Instruction::with_text(
+ address,
+ vec![opcode],
+ "invalid",
+ String::new(),
+ 1,
+ ));
+ }
+ let (extra, operands) = decode_immediates(opcode, &bytes[1..])?;
+ let len = 1 + extra;
+ Ok(Instruction::with_text(
+ address,
+ bytes[..len].to_vec(),
+ mnemonic,
+ operands,
+ len as u8,
+ ))
+}
+
+fn decode_immediates(opcode: u8, tail: &[u8]) -> Result<(usize, String)> {
+ Ok(match opcode {
+ 0x02 | 0x03 | 0x04 => {
+ let (ty, n) = leb128::read_i7(tail)?;
+ let op = if ty == 0 && !tail.is_empty() && tail[0] == 0x40 {
+ "void".to_string()
+ } else {
+ format!("{ty}")
+ };
+ (n, op)
+ }
+ 0x0c | 0x0d | 0x10 | 0x11 | 0x20 | 0x21 | 0x22 | 0x23 | 0x24 => {
+ let (idx, n) = leb128::read_u32(tail)?;
+ (n, format!("{idx}"))
+ }
+ 0x0e => decode_br_table(tail)?,
+ 0x28..=0x3e => {
+ let (align, n1) = leb128::read_u32(tail)?;
+ let (offset, n2) = leb128::read_u32(&tail[n1..])?;
+ (n1 + n2, format!("{align}, {offset}"))
+ }
+ 0x41 => {
+ let (v, n) = leb128::read_i32(tail)?;
+ (n, format!("{v}"))
+ }
+ 0x42 => {
+ let (v, n) = leb128::read_i64(tail)?;
+ (n, format!("{v}"))
+ }
+ 0x43 => {
+ if tail.len() < 4 {
+ return Err(Error::Decode("truncated f32.const".into()));
+ }
+ let bits = u32::from_le_bytes([tail[0], tail[1], tail[2], tail[3]]);
+ (4, format!("{bits:#x}"))
+ }
+ 0x44 => {
+ if tail.len() < 8 {
+ return Err(Error::Decode("truncated f64.const".into()));
+ }
+ let bits = u64::from_le_bytes([
+ tail[0], tail[1], tail[2], tail[3], tail[4], tail[5], tail[6], tail[7],
+ ]);
+ (8, format!("{bits:#x}"))
+ }
+ _ => (0, String::new()),
+ })
+}
+
+fn decode_br_table(tail: &[u8]) -> Result<(usize, String)> {
+ let (count, n1) = leb128::read_u32(tail)?;
+ let mut off = n1;
+ let mut targets = Vec::with_capacity(count as usize + 1);
+ for _ in 0..=count {
+ let (label, n) = leb128::read_u32(&tail[off..])?;
+ off += n;
+ targets.push(label.to_string());
+ }
+ Ok((off, targets.join(", ")))
+}
+
+impl ArchDecode for WasmDecoder {
+ fn arch(&self) -> Arch {
+ Arch::Wasm
+ }
+
+ fn open(mode: Mode) -> Result<Self> {
+ if !mode.is_valid_for(Arch::Wasm) {
+ return Err(Error::Mode(format!("invalid wasm mode {:#x}", mode.bits())));
+ }
+ Ok(Self { _mode: mode })
+ }
+
+ fn decode_one(&self, bytes: &[u8], address: u64, opts: &EngineOptions) -> Result<Instruction> {
+ let mut insn = decode_raw(bytes, address)?;
+ insn.id = names::insn_id_for_mnemonic(Arch::Wasm, &insn.mnemonic);
+ if opts.detail {
+ insn.detail = Some(InsnDetail {
+ groups: groups_for_mnemonic(&insn.mnemonic),
+ operands: typed_operands(&insn),
+ ..InsnDetail::default()
+ });
+ }
+ Ok(insn)
+ }
+}
+
+fn typed_operands(insn: &Instruction) -> Vec<Operand> {
+ if insn.operands.is_empty() {
+ return Vec::new();
+ }
+ insn.operands
+ .split(", ")
+ .filter_map(|p| p.parse::<i64>().ok().map(|v| Operand::Imm { value: v, size: 4 }))
+ .collect()
+}
+
+fn groups_for_mnemonic(mnemonic: &str) -> Vec<GroupId> {
+ match mnemonic {
+ "block" | "loop" | "if" | "else" | "end" | "br" | "br_if" | "br_table" | "return"
+ | "call" | "call_indirect" => vec![GroupId::Jump],
+ "i32.const" | "i64.const" | "f32.const" | "f64.const" => vec![GroupId::Arch(2)],
+ m if m.contains("load") || m.contains("store") || m.contains("memory") => {
+ vec![GroupId::Arch(3)]
+ }
+ m if m.contains("local") || m.contains("global") => vec![GroupId::Arch(4)],
+ m if m.contains('.') => vec![GroupId::Arch(2)],
+ _ => Vec::new(),
+ }
+}
+
+pub fn reg_name(_reg: RegId) -> Option<&'static str> {
+ None
+}
+
+pub fn insn_name(id: InsnId) -> Option<&'static str> {
+ let raw = id.raw();
+ if raw < 256 {
+ let name = OPCODE_MNEMONIC[raw as usize];
+ if name != "invalid" {
+ Some(name)
+ } else {
+ None
+ }
+ } else {
+ None
+ }
+}
+
+pub fn group_name(group: GroupId) -> Option<&'static str> {
+ match group {
+ GroupId::Jump => Some("control"),
+ GroupId::Arch(2) => Some("numeric"),
+ GroupId::Arch(3) => Some("memory"),
+ GroupId::Arch(4) => Some("variable"),
+ _ => None,
+ }
+}
+
+pub fn insn_id_for_mnemonic(mnemonic: &str) -> InsnId {
+ for (i, name) in OPCODE_MNEMONIC.iter().enumerate() {
+ if *name == mnemonic {
+ return InsnId(i as u32);
+ }
+ }
+ InsnId::INVALID
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::option::EngineOptions;
+
+ #[test]
+ fn wasm_i32_const_and_add() {
+ let dec = WasmDecoder::open(Mode::LITTLE_ENDIAN).unwrap();
+ let c = dec
+ .decode_one(&[0x41, 0xfb, 0x00], 0, &EngineOptions::default())
+ .unwrap();
+ assert_eq!(c.mnemonic, "i32.const");
+ assert_eq!(c.operands, "123");
+ assert_eq!(c.length, 3);
+
+ let add = dec
+ .decode_one(&[0x6a], 0, &EngineOptions::default())
+ .unwrap();
+ assert_eq!(add.mnemonic, "i32.add");
+ assert_eq!(add.length, 1);
+ }
+
+ #[test]
+ fn wasm_call_and_block() {
+ let dec = WasmDecoder::open(Mode::LITTLE_ENDIAN).unwrap();
+ let call = dec
+ .decode_one(&[0x10, 0x03], 0, &EngineOptions::default())
+ .unwrap();
+ assert_eq!(call.mnemonic, "call");
+ assert_eq!(call.operands, "3");
+
+ let block = dec
+ .decode_one(&[0x02, 0x40], 0, &EngineOptions::default())
+ .unwrap();
+ assert_eq!(block.mnemonic, "block");
+ assert_eq!(block.operands, "void");
+ }
+
+ #[test]
+ fn wasm_load_store() {
+ let dec = WasmDecoder::open(Mode::LITTLE_ENDIAN).unwrap();
+ let load = dec
+ .decode_one(&[0x28, 0x02, 0x04], 0, &EngineOptions::default())
+ .unwrap();
+ assert_eq!(load.mnemonic, "i32.load");
+ assert_eq!(load.operands, "2, 4");
+ assert_eq!(load.length, 3);
+ }
+}
diff --git a/crates/ghidrust-decode/src/x86_64.rs b/crates/ghidrust-decode/src/arch/x86/legacy.rs
similarity index 62%
rename from crates/ghidrust-decode/src/x86_64.rs
rename to crates/ghidrust-decode/src/arch/x86/legacy.rs
index bd1d809..9ccf0ec 100644
--- a/crates/ghidrust-decode/src/x86_64.rs
+++ b/crates/ghidrust-decode/src/arch/x86/legacy.rs
@@ -1,53 +1,25 @@
//! Minimal x86-64 decoder slice (hand-rolled). Enough for common prologue / fixture bytes.
+use crate::insn::Instruction;
+use crate::names;
+use crate::support::Arch;
use crate::{Error, Result};
-use serde::{Deserialize, Serialize};
-
-#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
-pub struct Instruction {
- pub address: u64,
- pub bytes: Vec<u8>,
- pub mnemonic: String,
- pub operands: String,
- pub length: u8,
-}
-
-impl Instruction {
- pub fn text(&self) -> String {
- let hex = format!("{:24}", hex_bytes(&self.bytes));
- if self.operands.is_empty() {
- format!("{:016x}: {} {}", self.address, hex, self.mnemonic)
- } else {
- format!(
- "{:016x}: {} {} {}",
- self.address, hex, self.mnemonic, self.operands
- )
- }
- }
-}
-
-fn hex_bytes(b: &[u8]) -> String {
- b.iter()
- .map(|x| format!("{x:02x}"))
- .collect::<Vec<_>>()
- .join(" ")
-}
const REGS64: [&str; 16] = [
- "rax", "rcx", "rdx", "rbx", "rsp", "rbp", "rsi", "rdi", "r8", "r9", "r10", "r11", "r12", "r13",
- "r14", "r15",
+ "rax", "rcx", "rdx", "rbx", "rsp", "rbp", "rsi", "rdi", "r8", "r9", "r10", "r11", "r12", "r13",
+ "r14", "r15",
];
const REGS32: [&str; 16] = [
- "eax", "ecx", "edx", "ebx", "esp", "ebp", "esi", "edi", "r8d", "r9d", "r10d", "r11d", "r12d",
- "r13d", "r14d", "r15d",
+ "eax", "ecx", "edx", "ebx", "esp", "ebp", "esi", "edi", "r8d", "r9d", "r10d", "r11d", "r12d",
+ "r13d", "r14d", "r15d",
];
const REGS16: [&str; 16] = [
- "ax", "cx", "dx", "bx", "sp", "bp", "si", "di", "r8w", "r9w", "r10w", "r11w", "r12w", "r13w",
- "r14w", "r15w",
+ "ax", "cx", "dx", "bx", "sp", "bp", "si", "di", "r8w", "r9w", "r10w", "r11w", "r12w", "r13w",
+ "r14w", "r15w",
];
const REGS8: [&str; 16] = [
- "al", "cl", "dl", "bl", "spl", "bpl", "sil", "dil", "r8b", "r9b", "r10b", "r11b", "r12b",
- "r13b", "r14b", "r15b",
+ "al", "cl", "dl", "bl", "spl", "bpl", "sil", "dil", "r8b", "r9b", "r10b", "r11b", "r12b",
+ "r13b", "r14b", "r15b",
];
#[derive(Clone, Copy, Default)]
@@ -62,7 +34,7 @@ struct Prefix {
rep: bool,
repne: bool,
lock: bool,
- seg: Option<&'static str>,
+ seg: Option<&'static str>,
}
fn reg_name(idx: u8, w: bool, op16: bool, byte_op: bool) -> &'static str {
@@ -79,13 +51,13 @@ fn reg_name(idx: u8, w: bool, op16: bool, byte_op: bool) -> &'static str {
}
struct Cursor<'a> {
- data: &'a [u8],
+ data: &'a [u8],
pos: usize,
start: usize,
}
impl<'a> Cursor<'a> {
- fn new(data: &'a [u8]) -> Self {
+ fn new(data: &'a [u8]) -> Self {
Self {
data,
pos: 0,
@@ -97,7 +69,7 @@ impl<'a> Cursor<'a> {
}
fn get(&mut self) -> Result<u8> {
if self.pos >= self.data.len() {
- return Err(Error::Decode("truncated instruction stream".into()));
+ return Err(Error::Decode("truncated instruction stream".into()));
}
let b = self.data[self.pos];
self.pos += 1;
@@ -107,11 +79,11 @@ impl<'a> Cursor<'a> {
self.data
.get(self.pos)
.copied()
- .ok_or_else(|| Error::Decode("truncated".into()))
+ .ok_or_else(|| Error::Decode("truncated".into()))
}
fn take_imm(&mut self, n: usize) -> Result<u64> {
if self.remaining() < n {
- return Err(Error::Decode("imm truncated".into()));
+ return Err(Error::Decode("imm truncated".into()));
}
let mut v = 0u64;
for i in 0..n {
@@ -127,19 +99,19 @@ impl<'a> Cursor<'a> {
fn sign_hex(v: i64) -> String {
if v < 0 {
- format!("-{:#x}", -v)
+ format!("-{:#x}", -v)
} else {
- format!("{v:#x}")
+ format!("{v:#x}")
}
}
fn size_prefix(sz: u32) -> &'static str {
match sz {
- 1 => "byte ptr ",
- 2 => "word ptr ",
- 4 => "dword ptr ",
- 8 => "qword ptr ",
- _ => "",
+ 1 => "byte ptr ",
+ 2 => "word ptr ",
+ 4 => "dword ptr ",
+ 8 => "qword ptr ",
+ _ => "",
}
}
@@ -149,7 +121,7 @@ fn size_prefix(sz: u32) -> &'static str {
/// the memory access width (1/2/4/8) so downstream lift can pick the right
/// load/store width without needing to reparse the mnemonic.
fn xmm_name(reg: u8) -> String {
- format!("xmm{}", reg & 0xf)
+ format!("xmm{}", reg & 0xf)
}
/// Decode ModRM for SSE xmm, xmm/m128 forms. Returns (xmm_reg, rm_operand).
@@ -167,7 +139,7 @@ fn decode_sse_xmm_rm(cur: &mut Cursor<'_>, pfx: Prefix) -> Result<(String, Strin
}
fn decode_modrm_sized(
- cur: &mut Cursor<'_>,
+ cur: &mut Cursor<'_>,
modrm: u8,
pfx: Prefix,
reg_byte: bool,
@@ -176,15 +148,15 @@ fn decode_modrm_sized(
let (reg, s) = decode_modrm_mem(cur, modrm, pfx, reg_byte)?;
if (modrm >> 6) != 3 {
let prefix = size_prefix(mem_size);
- if !prefix.is_empty() && !s.contains(" ptr ") {
- return Ok((reg, format!("{prefix}{s}")));
+ if !prefix.is_empty() && !s.contains(" ptr ") {
+ return Ok((reg, format!("{prefix}{s}")));
}
}
Ok((reg, s))
}
fn decode_modrm_mem(
- cur: &mut Cursor<'_>,
+ cur: &mut Cursor<'_>,
modrm: u8,
pfx: Prefix,
byte_op: bool,
@@ -207,7 +179,7 @@ fn decode_modrm_mem(
return Ok((reg, name.to_string()));
}
- // SIB if rm low 3 bits == 4 (without rex_b folded for encoding check)
+ // SIB if rm low 3 bits == 4 (without rex_b folded for encoding check)
let rm_enc = modrm & 7;
let mut parts = String::new();
if rm_enc == 4 {
@@ -223,7 +195,7 @@ fn decode_modrm_mem(
if scale == 1 {
terms.push(REGS64[index as usize].to_string());
} else {
- terms.push(format!("{}*{}", REGS64[index as usize], scale));
+ terms.push(format!("{}*{}", REGS64[index as usize], scale));
}
}
let disp = match mod_ {
@@ -235,46 +207,46 @@ fn decode_modrm_mem(
if let Some(d) = disp {
if d != 0 || terms.is_empty() {
parts = if terms.is_empty() {
- format!("[{}]", sign_hex(d))
+ format!("[{}]", sign_hex(d))
} else {
format!(
- "[{}{}{}]",
- terms.join("+"),
- if d < 0 { "" } else { "+" },
+ "[{}{}{}]",
+ terms.join("+"),
+ if d < 0 { "" } else { "+" },
sign_hex(d)
)
};
} else {
- parts = format!("[{}]", terms.join("+"));
+ parts = format!("[{}]", terms.join("+"));
}
} else {
- parts = format!("[{}]", terms.join("+"));
+ parts = format!("[{}]", terms.join("+"));
}
} else if mod_ == 0 && rm_enc == 5 {
- // RIP-relative
+ // RIP-relative
let disp = cur.take_imm(4)? as i32 as i64;
parts = if disp < 0 {
- format!("[rip{}]", sign_hex(disp))
+ format!("[rip{}]", sign_hex(disp))
} else {
- format!("[rip+{}]", sign_hex(disp))
+ format!("[rip+{}]", sign_hex(disp))
};
} else {
let base = REGS64[rm as usize];
match mod_ {
- 0 => parts = format!("[{base}]"),
+ 0 => parts = format!("[{base}]"),
1 => {
let d = cur.take_imm(1)? as i8 as i64;
parts = format!(
- "[{base}{}{}]",
- if d < 0 { "" } else { "+" },
+ "[{base}{}{}]",
+ if d < 0 { "" } else { "+" },
sign_hex(d)
);
}
2 => {
let d = cur.take_imm(4)? as i32 as i64;
parts = format!(
- "[{base}{}{}]",
- if d < 0 { "" } else { "+" },
+ "[{base}{}{}]",
+ if d < 0 { "" } else { "+" },
sign_hex(d)
);
}
@@ -282,7 +254,7 @@ fn decode_modrm_mem(
}
}
if let Some(seg) = pfx.seg {
- parts = format!("{seg}:{parts}");
+ parts = format!("{seg}:{parts}");
}
Ok((reg, parts))
}
@@ -290,12 +262,12 @@ fn decode_modrm_mem(
/// Decode one instruction from raw bytes at `address` (VA for display only).
pub fn decode_one(bytes: &[u8], address: u64) -> Result<Instruction> {
if bytes.is_empty() {
- return Err(Error::Decode("empty".into()));
+ return Err(Error::Decode("empty".into()));
}
let mut cur = Cursor::new(bytes);
let mut pfx = Prefix::default();
- // prefixes
+ // prefixes
loop {
let b = cur.peek()?;
match b {
@@ -313,27 +285,27 @@ pub fn decode_one(bytes: &[u8], address: u64) -> Result<Instruction> {
}
0x2E => {
cur.get()?;
- pfx.seg = Some("cs");
+ pfx.seg = Some("cs");
}
0x36 => {
cur.get()?;
- pfx.seg = Some("ss");
+ pfx.seg = Some("ss");
}
0x3E => {
cur.get()?;
- pfx.seg = Some("ds");
+ pfx.seg = Some("ds");
}
0x26 => {
cur.get()?;
- pfx.seg = Some("es");
+ pfx.seg = Some("es");
}
0x64 => {
cur.get()?;
- pfx.seg = Some("fs");
+ pfx.seg = Some("fs");
}
0x65 => {
cur.get()?;
- pfx.seg = Some("gs");
+ pfx.seg = Some("gs");
}
0x66 => {
cur.get()?;
@@ -354,7 +326,7 @@ pub fn decode_one(bytes: &[u8], address: u64) -> Result<Instruction> {
_ => break,
}
if cur.pos > 15 {
- return Err(Error::Decode("too many prefixes".into()));
+ return Err(Error::Decode("too many prefixes".into()));
}
}
@@ -362,18 +334,18 @@ pub fn decode_one(bytes: &[u8], address: u64) -> Result<Instruction> {
let w64 = pfx.rex_w;
let op16 = pfx.op_size && !pfx.rex_w;
- let (mnemonic, operands) = match op {
- // PUSH r64: 50+rd
+ let (mnemonic, operands): (String, String) = match op {
+ // PUSH r64: 50+rd
0x50..=0x57 => {
let r = (op - 0x50) | if pfx.rex_b { 8 } else { 0 };
- ("push".into(), REGS64[r as usize].to_string())
+ ("push".into(), REGS64[r as usize].to_string())
}
- // POP r64
+ // POP r64
0x58..=0x5F => {
let r = (op - 0x58) | if pfx.rex_b { 8 } else { 0 };
- ("pop".into(), REGS64[r as usize].to_string())
+ ("pop".into(), REGS64[r as usize].to_string())
}
- // MOV r/m, r
+ // MOV r/m, r
0x89 => {
let modrm = cur.get()?;
let (reg, rm) = decode_modrm_mem(&mut cur, modrm, pfx, false)?;
@@ -384,9 +356,9 @@ pub fn decode_one(bytes: &[u8], address: u64) -> Result<Instruction> {
} else {
reg_name(reg, false, false, false)
};
- ("mov".into(), format!("{rm}, {reg_s}"))
+ ("mov".into(), format!("{rm}, {reg_s}"))
}
- // MOV r, r/m
+ // MOV r, r/m
0x8B => {
let modrm = cur.get()?;
let (reg, rm) = decode_modrm_mem(&mut cur, modrm, pfx, false)?;
@@ -397,71 +369,71 @@ pub fn decode_one(bytes: &[u8], address: u64) -> Result<Instruction> {
} else {
reg_name(reg, false, false, false)
};
- ("mov".into(), format!("{reg_s}, {rm}"))
+ ("mov".into(), format!("{reg_s}, {rm}"))
}
- // MOV r/m8, r8
+ // MOV r/m8, r8
0x88 => {
let modrm = cur.get()?;
let (reg, rm) = decode_modrm_mem(&mut cur, modrm, pfx, true)?;
- ("mov".into(), format!("{rm}, {}", reg_name(reg, false, false, true)))
+ ("mov".into(), format!("{rm}, {}", reg_name(reg, false, false, true)))
}
- // MOV r8, r/m8
+ // MOV r8, r/m8
0x8A => {
let modrm = cur.get()?;
let (reg, rm) = decode_modrm_mem(&mut cur, modrm, pfx, true)?;
- ("mov".into(), format!("{}, {rm}", reg_name(reg, false, false, true)))
+ ("mov".into(), format!("{}, {rm}", reg_name(reg, false, false, true)))
}
- // MOV r/m, imm32 (C7 /0)
+ // MOV r/m, imm32 (C7 /0)
0xC7 => {
let modrm = cur.get()?;
let reg_field = (modrm >> 3) & 7;
if reg_field != 0 {
- return Err(Error::Decode(format!("unhandled C7 /{reg_field}")));
+ return Err(Error::Decode(format!("unhandled C7 /{reg_field}")));
}
let (_reg, rm) = decode_modrm_mem(&mut cur, modrm, pfx, false)?;
let imm = if w64 {
- // C7 still uses 32-bit imm sign-extended
+ // C7 still uses 32-bit imm sign-extended
cur.take_imm(4)? as i32 as i64
} else if op16 {
cur.take_imm(2)? as i16 as i64
} else {
cur.take_imm(4)? as i32 as i64
};
- ("mov".into(), format!("{rm}, {imm:#x}"))
+ ("mov".into(), format!("{rm}, {imm:#x}"))
}
- // MOV r64/r32, imm
+ // MOV r64/r32, imm
0xB8..=0xBF => {
let r = (op - 0xB8) | if pfx.rex_b { 8 } else { 0 };
if w64 {
let imm = cur.take_imm(8)?;
(
- "mov".into(),
- format!("{}, {imm:#x}", reg_name(r, true, false, false)),
+ "mov".into(),
+ format!("{}, {imm:#x}", reg_name(r, true, false, false)),
)
} else if op16 {
let imm = cur.take_imm(2)?;
(
- "mov".into(),
- format!("{}, {imm:#x}", reg_name(r, false, true, false)),
+ "mov".into(),
+ format!("{}, {imm:#x}", reg_name(r, false, true, false)),
)
} else {
let imm = cur.take_imm(4)?;
(
- "mov".into(),
- format!("{}, {imm:#x}", reg_name(r, false, false, false)),
+ "mov".into(),
+ format!("{}, {imm:#x}", reg_name(r, false, false, false)),
)
}
}
- // MOV r8, imm8
+ // MOV r8, imm8
0xB0..=0xB7 => {
let r = (op - 0xB0) | if pfx.rex_b { 8 } else { 0 };
let imm = cur.take_imm(1)?;
(
- "mov".into(),
- format!("{}, {imm:#x}", reg_name(r, false, false, true)),
+ "mov".into(),
+ format!("{}, {imm:#x}", reg_name(r, false, false, true)),
)
}
- // LEA r, m
+ // LEA r, m
0x8D => {
let modrm = cur.get()?;
let (reg, rm) = decode_modrm_mem(&mut cur, modrm, pfx, false)?;
@@ -472,19 +444,19 @@ pub fn decode_one(bytes: &[u8], address: u64) -> Result<Instruction> {
} else {
reg_name(reg, false, false, false)
};
- ("lea".into(), format!("{reg_s}, {rm}"))
+ ("lea".into(), format!("{reg_s}, {rm}"))
}
- // ADD/OR/ADC/SBB/AND/SUB/XOR/CMP r/m, r (01 family)
+ // ADD/OR/ADC/SBB/AND/SUB/XOR/CMP r/m, r (01 family)
0x01 | 0x09 | 0x11 | 0x19 | 0x21 | 0x29 | 0x31 | 0x39 => {
let mnem = match op {
- 0x01 => "add",
- 0x09 => "or",
- 0x11 => "adc",
- 0x19 => "sbb",
- 0x21 => "and",
- 0x29 => "sub",
- 0x31 => "xor",
- 0x39 => "cmp",
+ 0x01 => "add",
+ 0x09 => "or",
+ 0x11 => "adc",
+ 0x19 => "sbb",
+ 0x21 => "and",
+ 0x29 => "sub",
+ 0x31 => "xor",
+ 0x39 => "cmp",
_ => unreachable!(),
};
let modrm = cur.get()?;
@@ -496,19 +468,19 @@ pub fn decode_one(bytes: &[u8], address: u64) -> Result<Instruction> {
} else {
reg_name(reg, false, false, false)
};
- (mnem.into(), format!("{rm}, {reg_s}"))
+ (mnem.into(), format!("{rm}, {reg_s}"))
}
- // same r, r/m
+ // same r, r/m
0x03 | 0x0B | 0x13 | 0x1B | 0x23 | 0x2B | 0x33 | 0x3B => {
let mnem = match op {
- 0x03 => "add",
- 0x0B => "or",
- 0x13 => "adc",
- 0x1B => "sbb",
- 0x23 => "and",
- 0x2B => "sub",
- 0x33 => "xor",
- 0x3B => "cmp",
+ 0x03 => "add",
+ 0x0B => "or",
+ 0x13 => "adc",
+ 0x1B => "sbb",
+ 0x23 => "and",
+ 0x2B => "sub",
+ 0x33 => "xor",
+ 0x3B => "cmp",
_ => unreachable!(),
};
let modrm = cur.get()?;
@@ -520,10 +492,10 @@ pub fn decode_one(bytes: &[u8], address: u64) -> Result<Instruction> {
} else {
reg_name(reg, false, false, false)
};
- (mnem.into(), format!("{reg_s}, {rm}"))
+ (mnem.into(), format!("{reg_s}, {rm}"))
}
- // XOR r/m8,r8 etc skip; XOR r32,r/m already covered
- // TEST
+ // XOR r/m8,r8 etc skip; XOR r32,r/m already covered
+ // TEST
0x85 => {
let modrm = cur.get()?;
let (reg, rm) = decode_modrm_mem(&mut cur, modrm, pfx, false)?;
@@ -532,16 +504,16 @@ pub fn decode_one(bytes: &[u8], address: u64) -> Result<Instruction> {
} else {
reg_name(reg, false, op16, false)
};
- ("test".into(), format!("{rm}, {reg_s}"))
+ ("test".into(), format!("{rm}, {reg_s}"))
}
- // TEST r/m8, r8
+ // TEST r/m8, r8
0x84 => {
let modrm = cur.get()?;
let (reg, rm) = decode_modrm_sized(&mut cur, modrm, pfx, true, 1)?;
- ("test".into(), format!("{rm}, {}", reg_name(reg, false, false, true)))
+ ("test".into(), format!("{rm}, {}", reg_name(reg, false, false, true)))
}
- // TEST r/m, imm (F6 /0, F7 /0) — handled in F6/F7 groups below.
- // XCHG r/m, r
+ // TEST r/m, imm (F6 /0, F7 /0) — handled in F6/F7 groups below.
+ // XCHG r/m, r
0x87 => {
let modrm = cur.get()?;
let (reg, rm) = decode_modrm_mem(&mut cur, modrm, pfx, false)?;
@@ -552,36 +524,36 @@ pub fn decode_one(bytes: &[u8], address: u64) -> Result<Instruction> {
} else {
reg_name(reg, false, false, false)
};
- ("xchg".into(), format!("{rm}, {reg_s}"))
+ ("xchg".into(), format!("{rm}, {reg_s}"))
}
- // XCHG r/m8, r8
+ // XCHG r/m8, r8
0x86 => {
let modrm = cur.get()?;
let (reg, rm) = decode_modrm_sized(&mut cur, modrm, pfx, true, 1)?;
- ("xchg".into(), format!("{rm}, {}", reg_name(reg, false, false, true)))
+ ("xchg".into(), format!("{rm}, {}", reg_name(reg, false, false, true)))
}
- // MOV r/m8, imm8 (C6 /0)
+ // MOV r/m8, imm8 (C6 /0)
0xC6 => {
let modrm = cur.get()?;
let reg_field = (modrm >> 3) & 7;
if reg_field != 0 {
- return Err(Error::Decode(format!("unhandled C6 /{reg_field}")));
+ return Err(Error::Decode(format!("unhandled C6 /{reg_field}")));
}
let (_reg, rm) = decode_modrm_sized(&mut cur, modrm, pfx, true, 1)?;
let imm = cur.take_imm(1)? as i8 as i64;
- ("mov".into(), format!("{rm}, {imm:#x}"))
+ ("mov".into(), format!("{rm}, {imm:#x}"))
}
- // MOVSXD r64, r/m32 (Windows compilers use this constantly).
+ // MOVSXD r64, r/m32 (Windows compilers use this constantly).
0x63 => {
let modrm = cur.get()?;
let (reg, rm_raw) = decode_modrm_mem(&mut cur, modrm, pfx, false)?;
- // Source is r/m32; when mod=3 name it as a 32-bit register even
- // if REX.W is set. Memory forms get a "dword ptr" hint.
+ // Source is r/m32; when mod=3 name it as a 32-bit register even
+ // if REX.W is set. Memory forms get a "dword ptr" hint.
let rm = if (modrm >> 6) == 3 {
let src = (modrm & 7) | if pfx.rex_b { 8 } else { 0 };
reg_name(src, false, false, false).to_string()
- } else if !rm_raw.contains(" ptr ") {
- format!("{}{}", size_prefix(4), rm_raw)
+ } else if !rm_raw.contains(" ptr ") {
+ format!("{}{}", size_prefix(4), rm_raw)
} else {
rm_raw
};
@@ -590,10 +562,10 @@ pub fn decode_one(bytes: &[u8], address: u64) -> Result<Instruction> {
} else {
reg_name(reg, false, false, false)
};
- let mnem = if w64 { "movsxd" } else { "mov" };
- (mnem.into(), format!("{dst}, {rm}"))
+ let mnem = if w64 { "movsxd" } else { "mov" };
+ (mnem.into(), format!("{dst}, {rm}"))
}
- // IMUL r, r/m, imm8
+ // IMUL r, r/m, imm8
0x6B => {
let modrm = cur.get()?;
let (reg, rm) = decode_modrm_mem(&mut cur, modrm, pfx, false)?;
@@ -605,9 +577,9 @@ pub fn decode_one(bytes: &[u8], address: u64) -> Result<Instruction> {
} else {
reg_name(reg, false, false, false)
};
- ("imul".into(), format!("{dst}, {rm}, {imm:#x}"))
+ ("imul".into(), format!("{dst}, {rm}, {imm:#x}"))
}
- // IMUL r, r/m, imm32
+ // IMUL r, r/m, imm32
0x69 => {
let modrm = cur.get()?;
let (reg, rm) = decode_modrm_mem(&mut cur, modrm, pfx, false)?;
@@ -623,22 +595,22 @@ pub fn decode_one(bytes: &[u8], address: u64) -> Result<Instruction> {
} else {
reg_name(reg, false, false, false)
};
- ("imul".into(), format!("{dst}, {rm}, {imm:#x}"))
+ ("imul".into(), format!("{dst}, {rm}, {imm:#x}"))
}
- // Group 2 shift r/m, 1 (D0/D1) or r/m, cl (D2/D3)
+ // Group 2 shift r/m, 1 (D0/D1) or r/m, cl (D2/D3)
0xD0 | 0xD1 | 0xD2 | 0xD3 => {
let modrm = cur.get()?;
let reg_field = (modrm >> 3) & 7;
let mnem = match reg_field {
- 0 => "rol",
- 1 => "ror",
- 2 => "rcl",
- 3 => "rcr",
- 4 => "shl",
- 5 => "shr",
- 6 => "shl",
- 7 => "sar",
- _ => "grp2",
+ 0 => "rol",
+ 1 => "ror",
+ 2 => "rcl",
+ 3 => "rcr",
+ 4 => "shl",
+ 5 => "shr",
+ 6 => "shl",
+ 7 => "sar",
+ _ => "grp2",
};
let byte_op = op == 0xD0 || op == 0xD2;
let mem_size = if byte_op {
@@ -652,26 +624,26 @@ pub fn decode_one(bytes: &[u8], address: u64) -> Result<Instruction> {
};
let (_reg, rm) = decode_modrm_sized(&mut cur, modrm, pfx, byte_op, mem_size)?;
let count = if op == 0xD0 || op == 0xD1 {
- "1".to_string()
+ "1".to_string()
} else {
- "cl".to_string()
+ "cl".to_string()
};
- (mnem.into(), format!("{rm}, {count}"))
+ (mnem.into(), format!("{rm}, {count}"))
}
- // Group 2 shift r/m, imm8 (C0/C1)
+ // Group 2 shift r/m, imm8 (C0/C1)
0xC0 | 0xC1 => {
let modrm = cur.get()?;
let reg_field = (modrm >> 3) & 7;
let mnem = match reg_field {
- 0 => "rol",
- 1 => "ror",
- 2 => "rcl",
- 3 => "rcr",
- 4 => "shl",
- 5 => "shr",
- 6 => "shl",
- 7 => "sar",
- _ => "grp2",
+ 0 => "rol",
+ 1 => "ror",
+ 2 => "rcl",
+ 3 => "rcr",
+ 4 => "shl",
+ 5 => "shr",
+ 6 => "shl",
+ 7 => "sar",
+ _ => "grp2",
};
let byte_op = op == 0xC0;
let mem_size = if byte_op {
@@ -685,9 +657,9 @@ pub fn decode_one(bytes: &[u8], address: u64) -> Result<Instruction> {
};
let (_reg, rm) = decode_modrm_sized(&mut cur, modrm, pfx, byte_op, mem_size)?;
let imm = cur.take_imm(1)? as u8 as i64;
- (mnem.into(), format!("{rm}, {imm:#x}"))
+ (mnem.into(), format!("{rm}, {imm:#x}"))
}
- // Group 3 F6/F7 — test/not/neg/mul/imul/div/idiv r/m
+ // Group 3 F6/F7 — test/not/neg/mul/imul/div/idiv r/m
0xF6 | 0xF7 => {
let modrm = cur.get()?;
let reg_field = (modrm >> 3) & 7;
@@ -704,7 +676,7 @@ pub fn decode_one(bytes: &[u8], address: u64) -> Result<Instruction> {
let (_reg, rm) = decode_modrm_sized(&mut cur, modrm, pfx, byte_op, mem_size)?;
match reg_field {
0 | 1 => {
- // test r/m, imm
+ // test r/m, imm
let imm = if byte_op {
cur.take_imm(1)? as i8 as i64
} else if op16 {
@@ -712,140 +684,140 @@ pub fn decode_one(bytes: &[u8], address: u64) -> Result<Instruction> {
} else {
cur.take_imm(4)? as i32 as i64
};
- ("test".into(), format!("{rm}, {imm:#x}"))
+ ("test".into(), format!("{rm}, {imm:#x}"))
}
- 2 => ("not".into(), rm),
- 3 => ("neg".into(), rm),
- 4 => ("mul".into(), rm),
- 5 => ("imul".into(), rm),
- 6 => ("div".into(), rm),
- 7 => ("idiv".into(), rm),
- _ => ("grp3".into(), rm),
+ 2 => ("not".into(), rm),
+ 3 => ("neg".into(), rm),
+ 4 => ("mul".into(), rm),
+ 5 => ("imul".into(), rm),
+ 6 => ("div".into(), rm),
+ 7 => ("idiv".into(), rm),
+ _ => ("grp3".into(), rm),
}
}
- // NOP
- 0x90 => ("nop".into(), String::new()),
- // CBW / CWDE / CDQE
+ // NOP
+ 0x90 => ("nop".into(), String::new()),
+ // CBW / CWDE / CDQE
0x98 => {
if w64 {
- ("cdqe".into(), String::new())
+ ("cdqe".into(), String::new())
} else if op16 {
- ("cbw".into(), String::new())
+ ("cbw".into(), String::new())
} else {
- ("cwde".into(), String::new())
+ ("cwde".into(), String::new())
}
}
- // PUSHF / POPF (rex.w doesn't matter — these push RFLAGS)
- 0x9C => ("pushfq".into(), String::new()),
- 0x9D => ("popfq".into(), String::new()),
- // HLT
- 0xF4 => ("hlt".into(), String::new()),
- // RET
- 0xC3 => ("ret".into(), String::new()),
+ // PUSHF / POPF (rex.w doesn't matter — these push RFLAGS)
+ 0x9C => ("pushfq".into(), String::new()),
+ 0x9D => ("popfq".into(), String::new()),
+ // HLT
+ 0xF4 => ("hlt".into(), String::new()),
+ // RET
+ 0xC3 => ("ret".into(), String::new()),
0xC2 => {
let imm = cur.take_imm(2)?;
- ("ret".into(), format!("{imm:#x}"))
+ ("ret".into(), format!("{imm:#x}"))
}
- // CALL rel32
+ // CALL rel32
0xE8 => {
let rel = cur.take_imm(4)? as i32 as i64;
let target = address
.wrapping_add(cur.pos as u64)
.wrapping_add(rel as u64);
- ("call".into(), format!("{target:#x}"))
+ ("call".into(), format!("{target:#x}"))
}
- // JMP rel32
+ // JMP rel32
0xE9 => {
let rel = cur.take_imm(4)? as i32 as i64;
let target = address
.wrapping_add(cur.pos as u64)
.wrapping_add(rel as u64);
- ("jmp".into(), format!("{target:#x}"))
+ ("jmp".into(), format!("{target:#x}"))
}
- // JMP rel8
+ // JMP rel8
0xEB => {
let rel = cur.take_imm(1)? as i8 as i64;
let target = address
.wrapping_add(cur.pos as u64)
.wrapping_add(rel as u64);
- ("jmp".into(), format!("{target:#x}"))
+ ("jmp".into(), format!("{target:#x}"))
}
- // Jcc rel8
+ // Jcc rel8
0x70..=0x7F => {
let names = [
- "jo", "jno", "jb", "jae", "je", "jne", "jbe", "ja", "js", "jns", "jp", "jnp",
- "jl", "jge", "jle", "jg",
+ "jo", "jno", "jb", "jae", "je", "jne", "jbe", "ja", "js", "jns", "jp", "jnp",
+ "jl", "jge", "jle", "jg",
];
let rel = cur.take_imm(1)? as i8 as i64;
let target = address
.wrapping_add(cur.pos as u64)
.wrapping_add(rel as u64);
- (names[(op - 0x70) as usize].into(), format!("{target:#x}"))
+ (names[(op - 0x70) as usize].into(), format!("{target:#x}"))
}
- // INT3
- 0xCC => ("int3".into(), String::new()),
- // CDQ / CQO
+ // INT3
+ 0xCC => ("int3".into(), String::new()),
+ // CDQ / CQO
0x99 => {
if w64 {
- ("cqo".into(), String::new())
+ ("cqo".into(), String::new())
} else {
- ("cdq".into(), String::new())
+ ("cdq".into(), String::new())
}
}
- // LEAVE
- 0xC9 => ("leave".into(), String::new()),
- // Group1 Eb,Ib — ADD/OR/…/CMP r/m8, imm8 (80 /x); 82 is an alias
+ // LEAVE
+ 0xC9 => ("leave".into(), String::new()),
+ // Group1 Eb,Ib — ADD/OR/…/CMP r/m8, imm8 (80 /x); 82 is an alias
0x80 | 0x82 => {
let modrm = cur.get()?;
let reg_field = (modrm >> 3) & 7;
let mnem = match reg_field {
- 0 => "add",
- 1 => "or",
- 2 => "adc",
- 3 => "sbb",
- 4 => "and",
- 5 => "sub",
- 6 => "xor",
- 7 => "cmp",
- _ => "grp",
+ 0 => "add",
+ 1 => "or",
+ 2 => "adc",
+ 3 => "sbb",
+ 4 => "and",
+ 5 => "sub",
+ 6 => "xor",
+ 7 => "cmp",
+ _ => "grp",
};
let (_reg, rm) = decode_modrm_sized(&mut cur, modrm, pfx, true, 1)?;
let imm = cur.take_imm(1)? as i8 as i64;
- (mnem.into(), format!("{rm}, {imm:#x}"))
+ (mnem.into(), format!("{rm}, {imm:#x}"))
}
- // SUB/ADD r/m, imm8 (83 /x)
+ // SUB/ADD r/m, imm8 (83 /x)
0x83 => {
let modrm = cur.get()?;
let reg_field = (modrm >> 3) & 7;
let mnem = match reg_field {
- 0 => "add",
- 1 => "or",
- 2 => "adc",
- 3 => "sbb",
- 4 => "and",
- 5 => "sub",
- 6 => "xor",
- 7 => "cmp",
- _ => "grp",
+ 0 => "add",
+ 1 => "or",
+ 2 => "adc",
+ 3 => "sbb",
+ 4 => "and",
+ 5 => "sub",
+ 6 => "xor",
+ 7 => "cmp",
+ _ => "grp",
};
let (_reg, rm) = decode_modrm_mem(&mut cur, modrm, pfx, false)?;
let imm = cur.take_imm(1)? as i8 as i64;
- (mnem.into(), format!("{rm}, {imm:#x}"))
+ (mnem.into(), format!("{rm}, {imm:#x}"))
}
- // group 81 r/m, imm32
+ // group 81 r/m, imm32
0x81 => {
let modrm = cur.get()?;
let reg_field = (modrm >> 3) & 7;
let mnem = match reg_field {
- 0 => "add",
- 1 => "or",
- 2 => "adc",
- 3 => "sbb",
- 4 => "and",
- 5 => "sub",
- 6 => "xor",
- 7 => "cmp",
- _ => "grp",
+ 0 => "add",
+ 1 => "or",
+ 2 => "adc",
+ 3 => "sbb",
+ 4 => "and",
+ 5 => "sub",
+ 6 => "xor",
+ 7 => "cmp",
+ _ => "grp",
};
let (_reg, rm) = decode_modrm_mem(&mut cur, modrm, pfx, false)?;
let imm = if op16 {
@@ -853,67 +825,67 @@ pub fn decode_one(bytes: &[u8], address: u64) -> Result<Instruction> {
} else {
cur.take_imm(4)? as i32 as i64
};
- (mnem.into(), format!("{rm}, {imm:#x}"))
+ (mnem.into(), format!("{rm}, {imm:#x}"))
}
- // two-byte 0F
+ // two-byte 0F
0x0F => {
let op2 = cur.get()?;
match op2 {
- // MOVUPS xmm, xmm/m128 / MOVUPS xmm/m128, xmm
+ // MOVUPS xmm, xmm/m128 / MOVUPS xmm/m128, xmm
0x10 | 0x11 => {
let (xmm, rm) = decode_sse_xmm_rm(&mut cur, pfx)?;
if op2 == 0x10 {
- ("movups".into(), format!("{xmm}, {rm}"))
+ ("movups".into(), format!("{xmm}, {rm}"))
} else {
- ("movups".into(), format!("{rm}, {xmm}"))
+ ("movups".into(), format!("{rm}, {xmm}"))
}
}
- // MOVAPS xmm, xmm/m128 / MOVAPS xmm/m128, xmm
+ // MOVAPS xmm, xmm/m128 / MOVAPS xmm/m128, xmm
0x28 | 0x29 => {
let (xmm, rm) = decode_sse_xmm_rm(&mut cur, pfx)?;
if op2 == 0x28 {
- ("movaps".into(), format!("{xmm}, {rm}"))
+ ("movaps".into(), format!("{xmm}, {rm}"))
} else {
- ("movaps".into(), format!("{rm}, {xmm}"))
+ ("movaps".into(), format!("{rm}, {xmm}"))
}
}
- // MOVDQA xmm, xmm/m128 / MOVDQA xmm/m128, xmm (66 0F 6F / 7F)
+ // MOVDQA xmm, xmm/m128 / MOVDQA xmm/m128, xmm (66 0F 6F / 7F)
0x6F | 0x7F if pfx.op_size => {
let (xmm, rm) = decode_sse_xmm_rm(&mut cur, pfx)?;
if op2 == 0x6F {
- ("movdqa".into(), format!("{xmm}, {rm}"))
+ ("movdqa".into(), format!("{xmm}, {rm}"))
} else {
- ("movdqa".into(), format!("{rm}, {xmm}"))
+ ("movdqa".into(), format!("{rm}, {xmm}"))
}
}
- // XORPS xmm, xmm/m128
+ // XORPS xmm, xmm/m128
0x57 => {
let (xmm, rm) = decode_sse_xmm_rm(&mut cur, pfx)?;
- ("xorps".into(), format!("{xmm}, {rm}"))
+ ("xorps".into(), format!("{xmm}, {rm}"))
}
- // PXOR xmm, xmm/m128 (66 0F EF)
+ // PXOR xmm, xmm/m128 (66 0F EF)
0xEF if pfx.op_size => {
let (xmm, rm) = decode_sse_xmm_rm(&mut cur, pfx)?;
- ("pxor".into(), format!("{xmm}, {rm}"))
+ ("pxor".into(), format!("{xmm}, {rm}"))
}
- // Jcc rel32
+ // Jcc rel32
0x80..=0x8F => {
let names = [
- "jo", "jno", "jb", "jae", "je", "jne", "jbe", "ja", "js", "jns", "jp",
- "jnp", "jl", "jge", "jle", "jg",
+ "jo", "jno", "jb", "jae", "je", "jne", "jbe", "ja", "js", "jns", "jp",
+ "jnp", "jl", "jge", "jle", "jg",
];
let rel = cur.take_imm(4)? as i32 as i64;
let target = address
.wrapping_add(cur.pos as u64)
.wrapping_add(rel as u64);
- (names[(op2 - 0x80) as usize].into(), format!("{target:#x}"))
+ (names[(op2 - 0x80) as usize].into(), format!("{target:#x}"))
}
- // CMOVcc r, r/m
+ // CMOVcc r, r/m
0x40..=0x4F => {
let names = [
- "cmovo", "cmovno", "cmovb", "cmovae", "cmove", "cmovne", "cmovbe",
- "cmova", "cmovs", "cmovns", "cmovp", "cmovnp", "cmovl", "cmovge",
- "cmovle", "cmovg",
+ "cmovo", "cmovno", "cmovb", "cmovae", "cmove", "cmovne", "cmovbe",
+ "cmova", "cmovs", "cmovns", "cmovp", "cmovnp", "cmovl", "cmovge",
+ "cmovle", "cmovg",
];
let modrm = cur.get()?;
let mem_size = if w64 { 8 } else if op16 { 2 } else { 4 };
@@ -925,19 +897,19 @@ pub fn decode_one(bytes: &[u8], address: u64) -> Result<Instruction> {
} else {
reg_name(reg, false, false, false)
};
- (names[(op2 - 0x40) as usize].into(), format!("{dst}, {rm}"))
+ (names[(op2 - 0x40) as usize].into(), format!("{dst}, {rm}"))
}
- // SETcc r/m8
+ // SETcc r/m8
0x90..=0x9F => {
let names = [
- "seto", "setno", "setb", "setae", "sete", "setne", "setbe", "seta",
- "sets", "setns", "setp", "setnp", "setl", "setge", "setle", "setg",
+ "seto", "setno", "setb", "setae", "sete", "setne", "setbe", "seta",
+ "sets", "setns", "setp", "setnp", "setl", "setge", "setle", "setg",
];
let modrm = cur.get()?;
let (_r, rm) = decode_modrm_sized(&mut cur, modrm, pfx, true, 1)?;
(names[(op2 - 0x90) as usize].into(), rm)
}
- // MOVZX r, r/m8
+ // MOVZX r, r/m8
0xB6 => {
let modrm = cur.get()?;
let (reg, rm) = decode_modrm_sized(&mut cur, modrm, pfx, true, 1)?;
@@ -948,19 +920,19 @@ pub fn decode_one(bytes: &[u8], address: u64) -> Result<Instruction> {
} else {
reg_name(reg, false, false, false)
};
- ("movzx".into(), format!("{dst}, {rm}"))
+ ("movzx".into(), format!("{dst}, {rm}"))
}
- // MOVZX r, r/m16
+ // MOVZX r, r/m16
0xB7 => {
let modrm = cur.get()?;
- // r/m is 16-bit; when mod=3 that's a word reg.
+ // r/m is 16-bit; when mod=3 that's a word reg.
let (reg, rm_raw) = decode_modrm_mem(&mut cur, modrm, pfx, false)?;
let rm = if (modrm >> 6) == 3 {
- // Force word regnames on the source.
+ // Force word regnames on the source.
let src = (modrm & 7) | if pfx.rex_b { 8 } else { 0 };
reg_name(src, false, true, false).to_string()
- } else if !rm_raw.contains(" ptr ") {
- format!("{}{}", size_prefix(2), rm_raw)
+ } else if !rm_raw.contains(" ptr ") {
+ format!("{}{}", size_prefix(2), rm_raw)
} else {
rm_raw
};
@@ -971,9 +943,9 @@ pub fn decode_one(bytes: &[u8], address: u64) -> Result<Instruction> {
} else {
reg_name(reg, false, false, false)
};
- ("movzx".into(), format!("{dst}, {rm}"))
+ ("movzx".into(), format!("{dst}, {rm}"))
}
- // MOVSX r, r/m8
+ // MOVSX r, r/m8
0xBE => {
let modrm = cur.get()?;
let (reg, rm) = decode_modrm_sized(&mut cur, modrm, pfx, true, 1)?;
@@ -984,17 +956,17 @@ pub fn decode_one(bytes: &[u8], address: u64) -> Result<Instruction> {
} else {
reg_name(reg, false, false, false)
};
- ("movsx".into(), format!("{dst}, {rm}"))
+ ("movsx".into(), format!("{dst}, {rm}"))
}
- // MOVSX r, r/m16
+ // MOVSX r, r/m16
0xBF => {
let modrm = cur.get()?;
let (reg, rm_raw) = decode_modrm_mem(&mut cur, modrm, pfx, false)?;
let rm = if (modrm >> 6) == 3 {
let src = (modrm & 7) | if pfx.rex_b { 8 } else { 0 };
reg_name(src, false, true, false).to_string()
- } else if !rm_raw.contains(" ptr ") {
- format!("{}{}", size_prefix(2), rm_raw)
+ } else if !rm_raw.contains(" ptr ") {
+ format!("{}{}", size_prefix(2), rm_raw)
} else {
rm_raw
};
@@ -1005,9 +977,9 @@ pub fn decode_one(bytes: &[u8], address: u64) -> Result<Instruction> {
} else {
reg_name(reg, false, false, false)
};
- ("movsx".into(), format!("{dst}, {rm}"))
+ ("movsx".into(), format!("{dst}, {rm}"))
}
- // IMUL r, r/m
+ // IMUL r, r/m
0xAF => {
let modrm = cur.get()?;
let (reg, rm) = decode_modrm_mem(&mut cur, modrm, pfx, false)?;
@@ -1018,9 +990,9 @@ pub fn decode_one(bytes: &[u8], address: u64) -> Result<Instruction> {
} else {
reg_name(reg, false, false, false)
};
- ("imul".into(), format!("{dst}, {rm}"))
+ ("imul".into(), format!("{dst}, {rm}"))
}
- // BSWAP r32/r64
+ // BSWAP r32/r64
0xC8..=0xCF => {
let r = (op2 - 0xC8) | if pfx.rex_b { 8 } else { 0 };
let reg = if w64 {
@@ -1028,72 +1000,74 @@ pub fn decode_one(bytes: &[u8], address: u64) -> Result<Instruction> {
} else {
reg_name(r, false, false, false)
};
- ("bswap".into(), reg.to_string())
+ ("bswap".into(), reg.to_string())
}
- // UD2
- 0x0B => ("ud2".into(), String::new()),
- // ENDBR64 / ENDBR32 (F3 0F 1E FA / FB) — with F3 already consumed as `rep`.
+ // UD2
+ 0x0B => ("ud2".into(), String::new()),
+ // ENDBR64 / ENDBR32 (F3 0F 1E FA / FB) — with F3 already consumed as `rep`.
0x1E if pfx.rep => {
let modrm = cur.get()?;
let m = match modrm {
- 0xFA => "endbr64",
- 0xFB => "endbr32",
- _ => "endbr",
+ 0xFA => "endbr64",
+ 0xFB => "endbr32",
+ _ => "endbr",
};
(m.into(), String::new())
}
0x1F => {
- // NOP r/m
+ // NOP r/m
let modrm = cur.get()?;
let (_r, rm) = decode_modrm_mem(&mut cur, modrm, pfx, false)?;
- ("nop".into(), rm)
+ ("nop".into(), rm)
}
- 0x05 => ("syscall".into(), String::new()),
- 0xA2 => ("cpuid".into(), String::new()),
+ 0x05 => ("syscall".into(), String::new()),
+ 0xA2 => ("cpuid".into(), String::new()),
_ => {
- return Err(Error::Decode(format!("unhandled 0F {op2:02x}")));
+ return Err(Error::Decode(format!("unhandled 0F {op2:02x}")));
}
}
}
- // FF /2 CALL, /4 JMP
+ // FF /2 CALL, /4 JMP
0xFF => {
let modrm = cur.get()?;
let reg_field = (modrm >> 3) & 7;
let (_r, rm) = decode_modrm_mem(&mut cur, modrm, pfx, false)?;
match reg_field {
- 2 => ("call".into(), rm),
- 4 => ("jmp".into(), rm),
- 6 => ("push".into(), rm),
+ 2 => ("call".into(), rm),
+ 4 => ("jmp".into(), rm),
+ 6 => ("push".into(), rm),
_ => {
- return Err(Error::Decode(format!("unhandled FF /{reg_field}")));
+ return Err(Error::Decode(format!("unhandled FF /{reg_field}")));
}
}
}
- // XOR r8,r8 style short: 31 already; also 30
+ // XOR r8,r8 style short: 31 already; also 30
0x30 | 0x32 => {
let modrm = cur.get()?;
let (reg, rm) = decode_modrm_mem(&mut cur, modrm, pfx, true)?;
- let mnem = if op == 0x30 { "xor" } else { "xor" };
+ let mnem = if op == 0x30 { "xor" } else { "xor" };
if op == 0x30 {
- (mnem.into(), format!("{rm}, {}", reg_name(reg, false, false, true)))
+ (mnem.into(), format!("{rm}, {}", reg_name(reg, false, false, true)))
} else {
- (mnem.into(), format!("{}, {rm}", reg_name(reg, false, false, true)))
+ (mnem.into(), format!("{}, {rm}", reg_name(reg, false, false, true)))
}
}
other => {
return Err(Error::Decode(format!(
- "unhandled opcode {other:02x} at {address:#x}"
+ "unhandled opcode {other:02x} at {address:#x}"
)));
}
};
let taken = cur.bytes_taken().to_vec();
Ok(Instruction {
+ id: names::insn_id_for_mnemonic(Arch::X86, &mnemonic),
address,
length: taken.len() as u8,
bytes: taken,
mnemonic,
operands,
+ detail: None,
})
}
@@ -1103,179 +1077,179 @@ mod tests {
#[test]
fn decode_push_rbp_mov_rbp_rsp() {
- // 55 push rbp
- // 48 89 e5 mov rbp, rsp
+ // 55 push rbp
+ // 48 89 e5 mov rbp, rsp
let b = [0x55, 0x48, 0x89, 0xe5];
let i0 = decode_one(&b, 0x1000).unwrap();
- assert_eq!(i0.mnemonic, "push");
- assert_eq!(i0.operands, "rbp");
+ assert_eq!(i0.mnemonic, "push");
+ assert_eq!(i0.operands, "rbp");
assert_eq!(i0.length, 1);
let i1 = decode_one(&b[1..], 0x1001).unwrap();
- assert_eq!(i1.mnemonic, "mov");
- assert_eq!(i1.operands, "rbp, rsp");
+ assert_eq!(i1.mnemonic, "mov");
+ assert_eq!(i1.operands, "rbp, rsp");
}
#[test]
fn decode_xor_eax_eax_ret() {
- // 31 c0 xor eax, eax
- // c3 ret
+ // 31 c0 xor eax, eax
+ // c3 ret
let b = [0x31, 0xc0, 0xc3];
let i0 = decode_one(&b, 0).unwrap();
- assert_eq!(i0.mnemonic, "xor");
- assert_eq!(i0.operands, "eax, eax");
+ assert_eq!(i0.mnemonic, "xor");
+ assert_eq!(i0.operands, "eax, eax");
let i1 = decode_one(&b[2..], 2).unwrap();
- assert_eq!(i1.mnemonic, "ret");
+ assert_eq!(i1.mnemonic, "ret");
}
#[test]
fn decode_cmovcc_register() {
- // 48 0f 45 c8 cmovne rcx, rax
+ // 48 0f 45 c8 cmovne rcx, rax
let i = decode_one(&[0x48, 0x0f, 0x45, 0xc8], 0).unwrap();
- assert_eq!(i.mnemonic, "cmovne");
- assert_eq!(i.operands, "rcx, rax");
+ assert_eq!(i.mnemonic, "cmovne");
+ assert_eq!(i.operands, "rcx, rax");
assert_eq!(i.length, 4);
}
#[test]
fn decode_setcc_r8() {
- // 0f 94 c0 sete al
+ // 0f 94 c0 sete al
let i = decode_one(&[0x0f, 0x94, 0xc0], 0).unwrap();
- assert_eq!(i.mnemonic, "sete");
- assert_eq!(i.operands, "al");
+ assert_eq!(i.mnemonic, "sete");
+ assert_eq!(i.operands, "al");
}
#[test]
fn decode_movzx_r32_r8() {
- // 0f b6 c1 movzx eax, cl
+ // 0f b6 c1 movzx eax, cl
let i = decode_one(&[0x0f, 0xb6, 0xc1], 0).unwrap();
- assert_eq!(i.mnemonic, "movzx");
- assert_eq!(i.operands, "eax, cl");
+ assert_eq!(i.mnemonic, "movzx");
+ assert_eq!(i.operands, "eax, cl");
}
#[test]
fn decode_movsxd_r64_r32() {
- // 48 63 c1 movsxd rax, ecx
+ // 48 63 c1 movsxd rax, ecx
let i = decode_one(&[0x48, 0x63, 0xc1], 0).unwrap();
- assert_eq!(i.mnemonic, "movsxd");
- assert_eq!(i.operands, "rax, ecx");
+ assert_eq!(i.mnemonic, "movsxd");
+ assert_eq!(i.operands, "rax, ecx");
}
#[test]
fn decode_shr_by_cl_and_shl_imm() {
- // c1 e0 03 shl eax, 3
+ // c1 e0 03 shl eax, 3
let a = decode_one(&[0xc1, 0xe0, 0x03], 0).unwrap();
- assert_eq!(a.mnemonic, "shl");
- assert_eq!(a.operands, "eax, 0x3");
- // d3 e8 shr eax, cl
+ assert_eq!(a.mnemonic, "shl");
+ assert_eq!(a.operands, "eax, 0x3");
+ // d3 e8 shr eax, cl
let b = decode_one(&[0xd3, 0xe8], 0).unwrap();
- assert_eq!(b.mnemonic, "shr");
- assert_eq!(b.operands, "eax, cl");
+ assert_eq!(b.mnemonic, "shr");
+ assert_eq!(b.operands, "eax, cl");
}
#[test]
fn decode_group3_neg_and_not() {
- // f7 d8 neg eax
+ // f7 d8 neg eax
let a = decode_one(&[0xf7, 0xd8], 0).unwrap();
- assert_eq!(a.mnemonic, "neg");
- assert_eq!(a.operands, "eax");
- // f7 d0 not eax
+ assert_eq!(a.mnemonic, "neg");
+ assert_eq!(a.operands, "eax");
+ // f7 d0 not eax
let b = decode_one(&[0xf7, 0xd0], 0).unwrap();
- assert_eq!(b.mnemonic, "not");
+ assert_eq!(b.mnemonic, "not");
}
#[test]
fn decode_hlt_and_int3() {
- assert_eq!(decode_one(&[0xf4], 0).unwrap().mnemonic, "hlt");
- assert_eq!(decode_one(&[0xcc], 0).unwrap().mnemonic, "int3");
+ assert_eq!(decode_one(&[0xf4], 0).unwrap().mnemonic, "hlt");
+ assert_eq!(decode_one(&[0xcc], 0).unwrap().mnemonic, "int3");
}
#[test]
fn decode_endbr64() {
- // f3 0f 1e fa endbr64
+ // f3 0f 1e fa endbr64
let i = decode_one(&[0xf3, 0x0f, 0x1e, 0xfa], 0).unwrap();
- assert_eq!(i.mnemonic, "endbr64");
+ assert_eq!(i.mnemonic, "endbr64");
}
#[test]
fn decode_imul_with_imm() {
- // 6b c0 03 imul eax, eax, 3
+ // 6b c0 03 imul eax, eax, 3
let i = decode_one(&[0x6b, 0xc0, 0x03], 0).unwrap();
- assert_eq!(i.mnemonic, "imul");
- assert_eq!(i.operands, "eax, eax, 0x3");
+ assert_eq!(i.mnemonic, "imul");
+ assert_eq!(i.operands, "eax, eax, 0x3");
}
#[test]
fn decode_ud2_and_bswap() {
- assert_eq!(decode_one(&[0x0f, 0x0b], 0).unwrap().mnemonic, "ud2");
- // 0f c8 bswap eax
+ assert_eq!(decode_one(&[0x0f, 0x0b], 0).unwrap().mnemonic, "ud2");
+ // 0f c8 bswap eax
let b = decode_one(&[0x0f, 0xc8], 0).unwrap();
- assert_eq!(b.mnemonic, "bswap");
- assert_eq!(b.operands, "eax");
+ assert_eq!(b.mnemonic, "bswap");
+ assert_eq!(b.operands, "eax");
}
#[test]
fn decode_sib_with_scale_still_valid() {
- // 8b 04 88 mov eax, [rax+rcx*4]
+ // 8b 04 88 mov eax, [rax+rcx*4]
let i = decode_one(&[0x8b, 0x04, 0x88], 0).unwrap();
- assert_eq!(i.mnemonic, "mov");
+ assert_eq!(i.mnemonic, "mov");
assert!(
- i.operands.contains("rcx*4"),
- "expected SIB scale 4, got '{}'",
+ i.operands.contains("rcx*4"),
+ "expected SIB scale 4, got '{}'",
i.operands
);
}
#[test]
fn decode_group1_byte_cmp_mem_imm8() {
- // 80 b9 e1 01 00 00 00 cmp byte ptr [rcx+0x1e1], 0x0
+ // 80 b9 e1 01 00 00 00 cmp byte ptr [rcx+0x1e1], 0x0
let i = decode_one(&[0x80, 0xb9, 0xe1, 0x01, 0x00, 0x00, 0x00], 0).unwrap();
- assert_eq!(i.mnemonic, "cmp");
+ assert_eq!(i.mnemonic, "cmp");
assert_eq!(i.length, 7);
assert!(
- i.operands.contains("byte ptr") && i.operands.contains("[rcx+0x1e1]"),
- "got '{}'",
+ i.operands.contains("byte ptr") && i.operands.contains("[rcx+0x1e1]"),
+ "got '{}'",
i.operands
);
- assert!(i.operands.ends_with(", 0x0") || i.operands.ends_with(", 0"), "got '{}'", i.operands);
+ assert!(i.operands.ends_with(", 0x0") || i.operands.ends_with(", 0"), "got '{}'", i.operands);
}
#[test]
fn decode_movups_load_store() {
- // 0f 10 1a movups xmm3, [rdx]
+ // 0f 10 1a movups xmm3, [rdx]
let load = decode_one(&[0x0f, 0x10, 0x1a], 0).unwrap();
- assert_eq!(load.mnemonic, "movups");
- assert_eq!(load.operands, "xmm3, [rdx]");
- // 0f 11 59 10 movups [rcx+0x10], xmm3
+ assert_eq!(load.mnemonic, "movups");
+ assert_eq!(load.operands, "xmm3, [rdx]");
+ // 0f 11 59 10 movups [rcx+0x10], xmm3
let store = decode_one(&[0x0f, 0x11, 0x59, 0x10], 0).unwrap();
- assert_eq!(store.mnemonic, "movups");
- assert_eq!(store.operands, "[rcx+0x10], xmm3");
+ assert_eq!(store.mnemonic, "movups");
+ assert_eq!(store.operands, "[rcx+0x10], xmm3");
}
#[test]
fn decode_movaps_reg_reg() {
- // 0f 28 c1 movaps xmm0, xmm1
+ // 0f 28 c1 movaps xmm0, xmm1
let i = decode_one(&[0x0f, 0x28, 0xc1], 0).unwrap();
- assert_eq!(i.mnemonic, "movaps");
- assert_eq!(i.operands, "xmm0, xmm1");
+ assert_eq!(i.mnemonic, "movaps");
+ assert_eq!(i.operands, "xmm0, xmm1");
}
#[test]
fn decode_xorps_zeroing() {
- // 0f 57 c0 xorps xmm0, xmm0
+ // 0f 57 c0 xorps xmm0, xmm0
let i = decode_one(&[0x0f, 0x57, 0xc0], 0).unwrap();
- assert_eq!(i.mnemonic, "xorps");
- assert_eq!(i.operands, "xmm0, xmm0");
+ assert_eq!(i.mnemonic, "xorps");
+ assert_eq!(i.operands, "xmm0, xmm0");
}
#[test]
fn decode_pxor_and_movdqa() {
- // 66 0f ef c9 pxor xmm1, xmm1
+ // 66 0f ef c9 pxor xmm1, xmm1
let i = decode_one(&[0x66, 0x0f, 0xef, 0xc9], 0).unwrap();
- assert_eq!(i.mnemonic, "pxor");
- assert_eq!(i.operands, "xmm1, xmm1");
- // 66 0f 6f c1 movdqa xmm0, xmm1
+ assert_eq!(i.mnemonic, "pxor");
+ assert_eq!(i.operands, "xmm1, xmm1");
+ // 66 0f 6f c1 movdqa xmm0, xmm1
let m = decode_one(&[0x66, 0x0f, 0x6f, 0xc1], 0).unwrap();
- assert_eq!(m.mnemonic, "movdqa");
- assert_eq!(m.operands, "xmm0, xmm1");
+ assert_eq!(m.mnemonic, "movdqa");
+ assert_eq!(m.operands, "xmm0, xmm1");
}
}
diff --git a/crates/ghidrust-decode/src/arch/x86/mod.rs b/crates/ghidrust-decode/src/arch/x86/mod.rs
new file mode 100644
index 0000000..a5b5a5f
--- /dev/null
+++ b/crates/ghidrust-decode/src/arch/x86/mod.rs
@@ -0,0 +1,300 @@
+//! Hand-rolled x86 decoder package (16/32/64).
+
+mod legacy;
+pub mod syntax;
+
+use crate::arch::ArchDecode;
+use crate::error::{Error, Result};
+use crate::group::GroupId;
+use crate::insn::{InsnDetail, InsnId, Instruction};
+use crate::names;
+use crate::operand::{OpType, Operand};
+use crate::option::{EngineOptions, Syntax};
+use crate::reg::RegId;
+use crate::support::{Arch, Mode};
+
+pub struct X86Decoder {
+ mode: Mode,
+}
+
+impl ArchDecode for X86Decoder {
+ fn arch(&self) -> Arch {
+ Arch::X86
+ }
+
+ fn open(mode: Mode) -> Result<Self> {
+ if !mode.is_valid_for(Arch::X86) {
+ return Err(Error::Mode(format!("invalid x86 mode {:#x}", mode.bits())));
+ }
+ Ok(Self { mode })
+ }
+
+ fn decode_one(&self, bytes: &[u8], address: u64, opts: &EngineOptions) -> Result<Instruction> {
+ let mut insn = legacy::decode_one(bytes, address)?;
+ // Mode width: rewrite GP names for 16/32-bit engines .
+ if self.mode.intersects(Mode::MODE_16) {
+ insn.operands = rewrite_width(&insn.operands, Width::W16);
+ } else if self.mode.intersects(Mode::MODE_32) && !self.mode.intersects(Mode::MODE_64) {
+ insn.operands = rewrite_width(&insn.operands, Width::W32);
+ }
+ insn.id = names::insn_id_for_mnemonic(Arch::X86, &insn.mnemonic);
+ if let Some(over) = opts.mnemonic_overrides.get(&insn.id.raw()) {
+ insn.mnemonic = over.clone();
+ }
+ match opts.syntax {
+ Syntax::Att => {
+ insn.operands = syntax::att::reformat_operands(&insn.mnemonic, &insn.operands);
+ }
+ Syntax::Masm => {
+ // MASM-like: keep Intel operand order; ensure hex suffix style later.
+ }
+ Syntax::NoRegName => {
+ insn.operands = syntax::noregname::strip_reg_names(&insn.operands);
+ }
+ _ => {}
+ }
+ if opts.unsigned {
+ insn.operands = syntax::unsigned_imm(&insn.operands);
+ }
+ if opts.detail {
+ let (regs_read, regs_write) = detail_regs(&insn);
+ let typed = typed_operands(&insn);
+ insn.detail = Some(InsnDetail {
+ groups: groups_for_mnemonic(&insn.mnemonic),
+ regs_read: regs_read.clone(),
+ regs_write: regs_write.clone(),
+ implicit_read: regs_read,
+ implicit_write: regs_write,
+ operands: typed,
+ ..InsnDetail::default()
+ });
+ }
+ let _ = self.mode;
+ Ok(insn)
+ }
+}
+
+fn groups_for_mnemonic(mnemonic: &str) -> Vec<GroupId> {
+ if mnemonic == "ret" || mnemonic.starts_with("ret") {
+ vec![GroupId::Ret]
+ } else if mnemonic == "call" {
+ vec![GroupId::Call, GroupId::BranchRelative]
+ } else if mnemonic.starts_with('j') {
+ vec![GroupId::Jump, GroupId::BranchRelative]
+ } else if mnemonic == "int3" || mnemonic.starts_with("int") || mnemonic == "syscall" {
+ vec![GroupId::Int]
+ } else if mnemonic == "iret" || mnemonic == "iretd" || mnemonic == "iretq" {
+ vec![GroupId::Iret]
+ } else if mnemonic == "hlt" || mnemonic == "cli" || mnemonic == "sti" || mnemonic == "lgdt" {
+ vec![GroupId::Privilege]
+ } else {
+ Vec::new()
+ }
+}
+
+fn detail_regs(insn: &Instruction) -> (Vec<RegId>, Vec<RegId>) {
+ let mut reads = Vec::new();
+ let mut writes = Vec::new();
+ for (i, name) in [
+ "rax", "rcx", "rdx", "rbx", "rsp", "rbp", "rsi", "rdi", "r8", "r9", "r10", "r11", "r12",
+ "r13", "r14", "r15", "eax", "ecx", "edx", "ebx", "esp", "ebp", "esi", "edi",
+ ]
+ .iter()
+ .enumerate()
+ {
+ if insn.operands.contains(name) {
+ let id = RegId::new((i % 16) as u32);
+ // Heuristic: first operand write for Intel mov/lea/…
+ if insn.operands.find(name) == Some(0)
+ || insn.operands.starts_with(name)
+ || insn.operands.starts_with(&format!("{name},"))
+ {
+ writes.push(id);
+ } else {
+ reads.push(id);
+ }
+ }
+ }
+ if insn.mnemonic == "push" || insn.mnemonic == "call" || insn.mnemonic == "ret" {
+ writes.push(RegId::new(4)); // rsp
+ reads.push(RegId::new(4));
+ }
+ (reads, writes)
+}
+
+fn typed_operands(insn: &Instruction) -> Vec<Operand> {
+ if insn.operands.is_empty() {
+ return Vec::new();
+ }
+ insn.operands
+ .split(", ")
+ .map(|part| {
+ let p = part.trim();
+ if p.starts_with('0') || p.chars().all(|c| c.is_ascii_hexdigit() || c == 'x' || c == '-')
+ {
+ let v = parse_imm(p).unwrap_or(0);
+ Operand::Imm { value: v, size: 8 }
+ } else if p.contains('[') {
+ Operand::Mem {
+ base: RegId::INVALID,
+ index: RegId::INVALID,
+ scale: 1,
+ disp: 0,
+ segment: RegId::INVALID,
+ size: 8,
+ }
+ } else {
+ Operand::Reg(RegId::new(0))
+ }
+ })
+ .collect()
+}
+
+fn parse_imm(s: &str) -> Option<i64> {
+ let s = s.trim();
+ if let Some(rest) = s.strip_prefix("0x").or_else(|| s.strip_prefix("-0x")) {
+ let neg = s.starts_with('-');
+ let v = i64::from_str_radix(rest, 16).ok()?;
+ Some(if neg { -v } else { v })
+ } else {
+ s.parse().ok()
+ }
+}
+
+pub fn reg_name(reg: RegId) -> Option<&'static str> {
+ match reg.index() {
+ 0 => Some("rax"),
+ 1 => Some("rcx"),
+ 2 => Some("rdx"),
+ 3 => Some("rbx"),
+ 4 => Some("rsp"),
+ 5 => Some("rbp"),
+ 6 => Some("rsi"),
+ 7 => Some("rdi"),
+ 8 => Some("r8"),
+ 9 => Some("r9"),
+ 10 => Some("r10"),
+ 11 => Some("r11"),
+ 12 => Some("r12"),
+ 13 => Some("r13"),
+ 14 => Some("r14"),
+ 15 => Some("r15"),
+ _ => None,
+ }
+}
+
+pub fn insn_name(id: InsnId) -> Option<&'static str> {
+ match id.raw() {
+ 1 => Some("push"),
+ 2 => Some("pop"),
+ 3 => Some("mov"),
+ 4 => Some("ret"),
+ 5 => Some("call"),
+ 6 => Some("jmp"),
+ 7 => Some("nop"),
+ 8 => Some("xor"),
+ 9 => Some("add"),
+ 10 => Some("sub"),
+ 11 => Some("test"),
+ 12 => Some("cmp"),
+ 13 => Some("lea"),
+ 14 => Some("leave"),
+ 15 => Some("hlt"),
+ 16 => Some("int3"),
+ _ => None,
+ }
+}
+
+pub fn group_name(group: GroupId) -> Option<&'static str> {
+ match group {
+ GroupId::Jump => Some("jump"),
+ GroupId::Call => Some("call"),
+ GroupId::Ret => Some("ret"),
+ GroupId::Int => Some("int"),
+ GroupId::Iret => Some("iret"),
+ GroupId::Privilege => Some("privilege"),
+ GroupId::BranchRelative => Some("branch_relative"),
+ GroupId::Invalid => Some("invalid"),
+ GroupId::Arch(_) => None,
+ }
+}
+
+pub fn insn_id_for_mnemonic(mnemonic: &str) -> InsnId {
+ let id = match mnemonic {
+ "push" => 1,
+ "pop" => 2,
+ "mov" | "movsxd" | "movzx" | "movsx" | "movups" | "movaps" | "movdqa" => 3,
+ "ret" => 4,
+ "call" => 5,
+ "jmp" | "jo" | "jno" | "jb" | "jae" | "je" | "jne" | "jbe" | "ja" | "js" | "jns"
+ | "jp" | "jnp" | "jl" | "jge" | "jle" | "jg" | "cmovne" | "cmovz" => 6,
+ "nop" | "endbr64" | "endbr32" | "endbr" => 7,
+ "xor" | "pxor" | "xorps" => 8,
+ "add" => 9,
+ "sub" => 10,
+ "test" => 11,
+ "cmp" => 12,
+ "lea" => 13,
+ "leave" => 14,
+ "hlt" => 15,
+ "int3" => 16,
+ _ => 0,
+ };
+ InsnId(id)
+}
+
+enum Width {
+ W16,
+ W32,
+}
+
+fn rewrite_width(operands: &str, w: Width) -> String {
+ let pairs: &[(&str, &str)] = match w {
+ Width::W32 => &[
+ ("rax", "eax"),
+ ("rcx", "ecx"),
+ ("rdx", "edx"),
+ ("rbx", "ebx"),
+ ("rsp", "esp"),
+ ("rbp", "ebp"),
+ ("rsi", "esi"),
+ ("rdi", "edi"),
+ ("r8", "r8d"),
+ ("r9", "r9d"),
+ ("r10", "r10d"),
+ ("r11", "r11d"),
+ ("r12", "r12d"),
+ ("r13", "r13d"),
+ ("r14", "r14d"),
+ ("r15", "r15d"),
+ ],
+ Width::W16 => &[
+ ("rax", "ax"),
+ ("rcx", "cx"),
+ ("rdx", "dx"),
+ ("rbx", "bx"),
+ ("rsp", "sp"),
+ ("rbp", "bp"),
+ ("rsi", "si"),
+ ("rdi", "di"),
+ ("eax", "ax"),
+ ("ecx", "cx"),
+ ("edx", "dx"),
+ ("ebx", "bx"),
+ ("esp", "sp"),
+ ("ebp", "bp"),
+ ("esi", "si"),
+ ("edi", "di"),
+ ],
+ };
+ let mut out = operands.to_string();
+ for (from, to) in pairs {
+ out = out.replace(from, to);
+ }
+ out
+}
+
+#[allow(dead_code)]
+fn _op_type_used() -> OpType {
+ OpType::Invalid
+}
diff --git a/crates/ghidrust-decode/src/arch/x86/syntax/att.rs b/crates/ghidrust-decode/src/arch/x86/syntax/att.rs
new file mode 100644
index 0000000..e96afbb
--- /dev/null
+++ b/crates/ghidrust-decode/src/arch/x86/syntax/att.rs
@@ -0,0 +1,27 @@
+//! AT&T operand reformatter (Intel text → AT&T-ish).
+
+pub fn reformat_operands(mnemonic: &str, operands: &str) -> String {
+ if operands.is_empty() {
+ return String::new();
+ }
+ let parts: Vec<&str> = operands.split(", ").collect();
+ let mapped: Vec<String> = parts
+ .iter()
+ .map(|p| {
+ let p = p.trim();
+ if p.starts_with('[') || p.contains(" ptr ") {
+ format!("*{p}")
+ } else if p.starts_with("0x") || p.starts_with("-0x") || p.parse::<i64>().is_ok() {
+ format!("${p}")
+ } else {
+ format!("%{p}")
+ }
+ })
+ .collect();
+ // AT&T reverses src,dst for most two-operand forms.
+ if mapped.len() == 2 && mnemonic != "bound" {
+ format!("{}, {}", mapped[1], mapped[0])
+ } else {
+ mapped.join(", ")
+ }
+}
diff --git a/crates/ghidrust-decode/src/arch/x86/syntax/mod.rs b/crates/ghidrust-decode/src/arch/x86/syntax/mod.rs
new file mode 100644
index 0000000..9e70f8d
--- /dev/null
+++ b/crates/ghidrust-decode/src/arch/x86/syntax/mod.rs
@@ -0,0 +1,19 @@
+pub mod att;
+pub mod noregname;
+
+/// Rewrite immediates that look negative hex into unsigned hex when possible.
+pub fn unsigned_imm(operands: &str) -> String {
+ operands
+ .split(", ")
+ .map(|part| {
+ let p = part.trim();
+ if let Some(rest) = p.strip_prefix("-0x") {
+ if let Ok(v) = u64::from_str_radix(rest, 16) {
+ return format!("{:#x}", (!v).wrapping_add(1));
+ }
+ }
+ p.to_string()
+ })
+ .collect::<Vec<_>>()
+ .join(", ")
+}
diff --git a/crates/ghidrust-decode/src/arch/x86/syntax/noregname.rs b/crates/ghidrust-decode/src/arch/x86/syntax/noregname.rs
new file mode 100644
index 0000000..1bb4802
--- /dev/null
+++ b/crates/ghidrust-decode/src/arch/x86/syntax/noregname.rs
@@ -0,0 +1,16 @@
+//! Print register names as numeric ids .
+
+pub fn strip_reg_names(operands: &str) -> String {
+ let mut out = operands.to_string();
+ for (i, name) in [
+ "r15", "r14", "r13", "r12", "r11", "r10", "r9", "r8", "rax", "rcx", "rdx", "rbx", "rsp",
+ "rbp", "rsi", "rdi", "eax", "ecx", "edx", "ebx", "esp", "ebp", "esi", "edi", "ax", "cx",
+ "dx", "bx", "sp", "bp", "si", "di", "al", "cl", "dl", "bl",
+ ]
+ .iter()
+ .enumerate()
+ {
+ out = out.replace(name, &format!("r{i}"));
+ }
+ out
+}
diff --git a/crates/ghidrust-decode/src/arch/xcore/decode.rs b/crates/ghidrust-decode/src/arch/xcore/decode.rs
new file mode 100644
index 0000000..6665b13
--- /dev/null
+++ b/crates/ghidrust-decode/src/arch/xcore/decode.rs
@@ -0,0 +1,179 @@
+use crate::error::{Error, Result};
+
+pub fn reg_name(reg: crate::reg::RegId) -> Option<&'static str> {
+ match reg.index() {
+ 0 => Some("r0"),
+ 1 => Some("r1"),
+ 10 => Some("sp"),
+ 11 => Some("lr"),
+ _ => None,
+ }
+}
+
+pub fn decode(bytes: &[u8], little_endian: bool) -> Result<(String, String, usize)> {
+ if bytes.len() < 2 {
+ return Err(Error::Decode("truncated xcore input".into()));
+ }
+ let half = if little_endian {
+ u16::from_le_bytes([bytes[0], bytes[1]])
+ } else {
+ u16::from_be_bytes([bytes[0], bytes[1]])
+ };
+ if (half >> 11) == 0b11100 {
+ if bytes.len() < 4 {
+ return Err(Error::Decode("truncated xcore 32-bit".into()));
+ }
+ let word = if little_endian {
+ u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])
+ } else {
+ u32::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])
+ };
+ decode32(word)
+ } else {
+ decode16(half)
+ }
+}
+
+fn r(n: u16) -> String {
+ format!("r{n}")
+}
+
+fn decode16(h: u16) -> Result<(String, String, usize)> {
+ let op = h >> 11;
+ match op {
+ 0b00000 => {
+ // 3-operand register: 00000 rrr aaa bbb fff
+ let dst = (h >> 8) & 0x7;
+ let src1 = (h >> 5) & 0x7;
+ let src2 = (h >> 2) & 0x7;
+ let fn3 = h & 0x3;
+ let name = match fn3 {
+ 0x0 => "add",
+ 0x1 => "sub",
+ 0x2 => "lsl",
+ 0x3 => "lsr",
+ _ => return Err(Error::Decode("invalid xcore alu".into())),
+ };
+ Ok((
+ name.into(),
+ format!("{}, {}, {}", r(dst), r(src1), r(src2)),
+ 2,
+ ))
+ }
+ 0b00001 => {
+ // mov (register): 00001 rrr 000 bbb 011
+ let dst = (h >> 8) & 0x7;
+ let src = (h >> 2) & 0x7;
+ Ok(( "mov".into(), format!("{}, {}", r(dst), r(src)), 2))
+ }
+ 0b10000 => {
+ // bu (branch unconditional): 10000 dddddddddddd
+ let disp = sign_ext16((h & 0x7ff) as i16, 11);
+ Ok(("bu".into(), format!("{disp}"), 2))
+ }
+ 0b10001 => {
+ // bl (branch link): 10001 dddddddddddd
+ let disp = sign_ext16((h & 0x7ff) as i16, 11);
+ Ok(("bl".into(), format!("{disp}"), 2))
+ }
+ 0b10010 => {
+ // bf (branch false): 10010 dddddddddddd
+ let disp = sign_ext16((h & 0x7ff) as i16, 11);
+ Ok(("bf".into(), format!("{disp}"), 2))
+ }
+ 0b10100 => {
+ // ldw (load word): 10100 rrr bbb ddddd
+ let dst = (h >> 8) & 0x7;
+ let base = (h >> 5) & 0x7;
+ let disp = ((h >> 2) & 0x7) << 2;
+ Ok((
+ "ldw".into(),
+ format!("{}, [{disp}({})]", r(dst), r(base)),
+ 2,
+ ))
+ }
+ 0b10101 => {
+ // stw (store word): 10101 rrr bbb ddddd
+ let src = (h >> 8) & 0x7;
+ let base = (h >> 5) & 0x7;
+ let disp = ((h >> 2) & 0x7) << 2;
+ Ok((
+ "stw".into(),
+ format!("{}, [{disp}({})]", r(src), r(base)),
+ 2,
+ ))
+ }
+ _ => Err(Error::Decode("unsupported xcore 16-bit".into())),
+ }
+}
+
+fn decode32(word: u32) -> Result<(String, String, usize)> {
+ let op = (word >> 27) & 0x1f;
+ match op {
+ 0x00 => {
+ let dst = (word >> 22) & 0x1f;
+ let src = (word >> 17) & 0x1f;
+ Ok(("mov".into(), format!("r{dst}, r{src}"), 4))
+ }
+ 0x01 => {
+ let dst = (word >> 22) & 0x1f;
+ let src1 = (word >> 17) & 0x1f;
+ let src2 = (word >> 12) & 0x1f;
+ Ok((
+ "add".into(),
+ format!("r{dst}, r{src1}, r{src2}"),
+ 4,
+ ))
+ }
+ 0x02 => {
+ let dst = (word >> 22) & 0x1f;
+ let src1 = (word >> 17) & 0x1f;
+ let src2 = (word >> 12) & 0x1f;
+ Ok((
+ "sub".into(),
+ format!("r{dst}, r{src1}, r{src2}"),
+ 4,
+ ))
+ }
+ 0x10 => {
+ let dst = (word >> 22) & 0x1f;
+ let base = (word >> 17) & 0x1f;
+ let disp = (word >> 5) & 0xfff;
+ Ok((
+ "ldw".into(),
+ format!("r{dst}, [{disp}(r{base})]"),
+ 4,
+ ))
+ }
+ 0x11 => {
+ let src = (word >> 22) & 0x1f;
+ let base = (word >> 17) & 0x1f;
+ let disp = (word >> 5) & 0xfff;
+ Ok((
+ "stw".into(),
+ format!("r{src}, [{disp}(r{base})]"),
+ 4,
+ ))
+ }
+ _ => Err(Error::Decode("unsupported xcore 32-bit".into())),
+ }
+}
+
+fn sign_ext16(val: i16, bits: u32) -> i64 {
+ let shift = 16 - bits as i32;
+ ((val << shift) >> shift) as i64
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn xcore_add16() {
+ // add r1, r2, r3 => 0x0298
+ let (m, o, l) = decode(&[0x98, 0x02], true).unwrap();
+ assert_eq!(m, "add");
+ assert_eq!(l, 2);
+ assert!(o.contains("r2"));
+ }
+}
diff --git a/crates/ghidrust-decode/src/arch/xcore/mod.rs b/crates/ghidrust-decode/src/arch/xcore/mod.rs
new file mode 100644
index 0000000..9e95a9d
--- /dev/null
+++ b/crates/ghidrust-decode/src/arch/xcore/mod.rs
@@ -0,0 +1,124 @@
+mod decode;
+
+use crate::arch::ArchDecode;
+use crate::error::{Error, Result};
+use crate::group::GroupId;
+use crate::insn::{InsnDetail, InsnId, Instruction};
+use crate::names;
+use crate::option::EngineOptions;
+use crate::reg::RegId;
+use crate::support::{Arch, Mode};
+
+pub fn reg_name(reg: RegId) -> Option<&'static str> {
+ decode::reg_name(reg)
+}
+
+pub struct XcoreDecoder {
+ little_endian: bool,
+}
+
+impl ArchDecode for XcoreDecoder {
+ fn arch(&self) -> Arch {
+ Arch::Xcore
+ }
+
+ fn open(mode: Mode) -> Result<Self> {
+ if !mode.is_valid_for(Arch::Xcore) {
+ return Err(Error::Mode(format!("invalid xcore mode {:#x}", mode.bits())));
+ }
+ let little_endian = !mode.contains(Mode::BIG_ENDIAN);
+ Ok(Self { little_endian })
+ }
+
+ fn decode_one(&self, bytes: &[u8], address: u64, opts: &EngineOptions) -> Result<Instruction> {
+ let (mnemonic, operands, len) = decode::decode(bytes, self.little_endian)?;
+ let mut insn = Instruction::with_text(
+ address,
+ bytes[..len].to_vec(),
+ mnemonic,
+ operands,
+ len as u8,
+ );
+ insn.id = names::insn_id_for_mnemonic(Arch::Xcore, &insn.mnemonic);
+ if opts.detail {
+ insn.detail = Some(InsnDetail {
+ groups: groups_for_mnemonic(&insn.mnemonic),
+ ..InsnDetail::default()
+ });
+ }
+ Ok(insn)
+ }
+}
+
+fn groups_for_mnemonic(mnemonic: &str) -> Vec<GroupId> {
+ match mnemonic {
+ "bu" | "bf" => vec![GroupId::Jump],
+ "bl" => vec![GroupId::Call],
+ "ldw" => vec![GroupId::Arch(1)],
+ "stw" => vec![GroupId::Arch(2)],
+ "add" | "sub" => vec![GroupId::Arch(3)],
+ _ => Vec::new(),
+ }
+}
+
+pub fn insn_name(id: InsnId) -> Option<&'static str> {
+ match id.raw() {
+ 1 => Some("add"),
+ 2 => Some("mov"),
+ 3 => Some("ldw"),
+ 4 => Some("stw"),
+ 5 => Some("bu"),
+ _ => None,
+ }
+}
+
+pub fn group_name(group: GroupId) -> Option<&'static str> {
+ match group {
+ GroupId::Jump => Some("jump"),
+ GroupId::Call => Some("call"),
+ GroupId::Arch(1) => Some("load"),
+ GroupId::Arch(2) => Some("store"),
+ GroupId::Arch(3) => Some("alu"),
+ _ => None,
+ }
+}
+
+pub fn insn_id_for_mnemonic(mnemonic: &str) -> InsnId {
+ let id = match mnemonic {
+ "add" | "sub" => 1,
+ "mov" => 2,
+ "ldw" => 3,
+ "stw" => 4,
+ "bu" | "bl" | "bf" => 5,
+ _ => 0,
+ };
+ InsnId(id)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::engine::Engine;
+
+ #[test]
+ fn xcore_add_and_mov() {
+ let mut eng = Engine::open(Arch::Xcore, Mode::MODE_32).unwrap();
+ // add r1, r2, r3
+ let add = eng.disasm_one(&[0x98, 0x02], 0).unwrap();
+ assert_eq!(add.mnemonic, "add");
+ // mov r1, r2 => 0x090b
+ let mov = eng.disasm_one(&[0x0b, 0x09], 0).unwrap();
+ assert_eq!(mov.mnemonic, "mov");
+ }
+
+ #[test]
+ fn xcore_branch_and_ldw() {
+ let mut eng = Engine::open(Arch::Xcore, Mode::MODE_32).unwrap();
+ // bu +2 => 10000 00000000001 = 0x8001
+ let bu = eng.disasm_one(&[0x01, 0x80], 0).unwrap();
+ assert_eq!(bu.mnemonic, "bu");
+ // ldw r1, [0(r2)] => 10100 001 010 000 = 0xa520
+ let ldw = eng.disasm_one(&[0x20, 0xa5], 0).unwrap();
+ assert_eq!(ldw.mnemonic, "ldw");
+ }
+}
diff --git a/crates/ghidrust-decode/src/arch/xtensa/decode.rs b/crates/ghidrust-decode/src/arch/xtensa/decode.rs
new file mode 100644
index 0000000..e87ab1c
--- /dev/null
+++ b/crates/ghidrust-decode/src/arch/xtensa/decode.rs
@@ -0,0 +1,140 @@
+use crate::error::{Error, Result};
+use crate::option::EngineOptions;
+
+pub fn reg_name(reg: crate::reg::RegId) -> Option<&'static str> {
+ match reg.index() {
+ 0 => Some("a0"),
+ 1 => Some("a1"),
+ 2 => Some("a2"),
+ 15 => Some("a15"),
+ _ => None,
+ }
+}
+
+fn a(n: u32) -> String {
+ format!("a{n}")
+}
+
+pub fn decode(bytes: &[u8], opts: &EngineOptions) -> Result<(String, String, usize)> {
+ if bytes.is_empty() {
+ return Err(Error::Decode("empty xtensa input".into()));
+ }
+ if bytes.len() >= 3 && bytes[0] <= 0x0f {
+ decode24(bytes, opts)
+ } else if bytes.len() >= 2 {
+ decode16(bytes)
+ } else {
+ Err(Error::Decode("truncated xtensa instruction".into()))
+ }
+}
+
+fn decode24(bytes: &[u8], opts: &EngineOptions) -> Result<(String, String, usize)> {
+ let op = bytes[0];
+ match op {
+ 0x02 => {
+ // L32I
+ let a_reg = (bytes[1] >> 4) & 0xf;
+ let as_reg = bytes[1] & 0xf;
+ let off = (bytes[2] as u32) << 2;
+ Ok((
+ "l32i".into(),
+ format!("{}, {}, {}", a(u32::from(a_reg)), a(u32::from(as_reg)), off),
+ 3,
+ ))
+ }
+ 0x03 => {
+ let a_reg = (bytes[1] >> 4) & 0xf;
+ let as_reg = bytes[1] & 0xf;
+ let off = (bytes[2] as u32) << 2;
+ Ok((
+ "s32i".into(),
+ format!("{}, {}, {}", a(u32::from(a_reg)), a(u32::from(as_reg)), off),
+ 3,
+ ))
+ }
+ 0x08 => {
+ let dst = (bytes[1] >> 4) & 0xf;
+ let src = bytes[1] & 0xf;
+ Ok(("add".into(), format!("{}, {}, {}", a(u32::from(dst)), a(u32::from(dst)), a(u32::from(src))), 3))
+ }
+ 0x05 => {
+ let reg = (bytes[1] >> 4) & 0xf;
+ let imm = bytes[2] as i8 as i64;
+ Ok(("movi".into(), format!("{}, {imm}", a(u32::from(reg))), 3))
+ }
+ 0x06 => {
+ let target = if bytes.len() >= 6 {
+ u32::from_le_bytes([bytes[2], bytes[3], bytes[4], bytes[5]]) & 0xfffff
+ } else {
+ bytes[2] as u32
+ };
+ Ok(("call0".into(), format!("0x{target:x}"), 3))
+ }
+ 0x07 => {
+ let reg = bytes[1] & 0xf;
+ Ok(("callx0".into(), format!("{}", a(u32::from(reg))), 3))
+ }
+ 0x0d => Ok(("ret".into(), String::new(), 3)),
+ 0x0e => {
+ let imm = if bytes.len() >= 6 {
+ u32::from_le_bytes([bytes[2], bytes[3], bytes[4], bytes[5]])
+ } else {
+ bytes[2] as u32
+ };
+ Ok(("j".into(), format!("0x{imm:x}"), 3))
+ }
+ 0x0f => {
+ let reg = bytes[1] & 0xf;
+ Ok(("jx".into(), format!("{}", a(u32::from(reg))), 3))
+ }
+ 0x01 => decode_l32r(bytes, opts),
+ _ => Err(Error::Decode("unsupported xtensa 24-bit".into())),
+ }
+}
+
+fn decode_l32r(bytes: &[u8], opts: &EngineOptions) -> Result<(String, String, usize)> {
+ let reg = (bytes[1] >> 4) & 0xf;
+ let offset = bytes[2] as u32;
+ let pc = opts.litbase.wrapping_add(offset << 2);
+ Ok((
+ "l32r".into(),
+ format!("{}, 0x{pc:x}", a(u32::from(reg))),
+ 3,
+ ))
+}
+
+fn decode16(bytes: &[u8]) -> Result<(String, String, usize)> {
+ let h = u16::from_le_bytes([bytes[0], bytes[1]]);
+ let op = h >> 12;
+ match op {
+ 0x8 => {
+ let reg = (h >> 8) & 0xf;
+ let imm = (h & 0xff) as i8 as i64;
+ Ok(("movi.n".into(), format!("{}, {imm}", a(u32::from(reg))), 2))
+ }
+ 0x9 => {
+ let reg = (h >> 8) & 0xf;
+ let imm = (h & 0xff) as i8 as i64;
+ Ok(("addi.n".into(), format!("{}, {imm}", a(u32::from(reg))), 2))
+ }
+ 0xa => {
+ let disp = ((h & 0x0fff) as i16 as i64) << 1;
+ Ok(("j.n".into(), format!("{disp}"), 2))
+ }
+ _ => Err(Error::Decode("unsupported xtensa 16-bit".into())),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::option::EngineOptions;
+
+ #[test]
+ fn xtensa_l32i() {
+ // l32i a4, a1, 0 => op=0x02, a4=4, a1=1, off=0
+ let (m, _, l) = decode(&[0x02, 0x41, 0x00], &EngineOptions::default()).unwrap();
+ assert_eq!(m, "l32i");
+ assert_eq!(l, 3);
+ }
+}
diff --git a/crates/ghidrust-decode/src/arch/xtensa/mod.rs b/crates/ghidrust-decode/src/arch/xtensa/mod.rs
new file mode 100644
index 0000000..15615af
--- /dev/null
+++ b/crates/ghidrust-decode/src/arch/xtensa/mod.rs
@@ -0,0 +1,128 @@
+mod decode;
+
+use crate::arch::ArchDecode;
+use crate::error::{Error, Result};
+use crate::group::GroupId;
+use crate::insn::{InsnDetail, InsnId, Instruction};
+use crate::names;
+use crate::option::EngineOptions;
+use crate::support::{Arch, Mode};
+
+pub use decode::reg_name;
+
+pub struct XtensaDecoder {
+ _mode: Mode,
+}
+
+impl ArchDecode for XtensaDecoder {
+ fn arch(&self) -> Arch {
+ Arch::Xtensa
+ }
+
+ fn open(mode: Mode) -> Result<Self> {
+ if !mode.is_valid_for(Arch::Xtensa) {
+ return Err(Error::Mode(format!("invalid xtensa mode {:#x}", mode.bits())));
+ }
+ Ok(Self { _mode: mode })
+ }
+
+ fn decode_one(&self, bytes: &[u8], address: u64, opts: &EngineOptions) -> Result<Instruction> {
+ let (mnemonic, operands, len) = decode::decode(bytes, opts)?;
+ let mut insn = Instruction::with_text(
+ address,
+ bytes[..len].to_vec(),
+ mnemonic,
+ operands,
+ len as u8,
+ );
+ insn.id = names::insn_id_for_mnemonic(Arch::Xtensa, &insn.mnemonic);
+ if opts.detail {
+ insn.detail = Some(InsnDetail {
+ groups: groups_for_mnemonic(&insn.mnemonic),
+ ..InsnDetail::default()
+ });
+ }
+ Ok(insn)
+ }
+}
+
+fn groups_for_mnemonic(mnemonic: &str) -> Vec<GroupId> {
+ match mnemonic {
+ "call0" | "callx0" => vec![GroupId::Call],
+ "j" | "jx" | "j.n" => vec![GroupId::Jump],
+ "ret" => vec![GroupId::Ret],
+ "l32i" | "l32r" => vec![GroupId::Arch(1)],
+ "s32i" => vec![GroupId::Arch(2)],
+ _ => vec![GroupId::Arch(3)],
+ }
+}
+
+pub fn insn_name(id: InsnId) -> Option<&'static str> {
+ match id.raw() {
+ 1 => Some("l32i"),
+ 2 => Some("s32i"),
+ 3 => Some("add"),
+ 4 => Some("call0"),
+ 5 => Some("ret"),
+ 6 => Some("l32r"),
+ _ => None,
+ }
+}
+
+pub fn group_name(group: GroupId) -> Option<&'static str> {
+ match group {
+ GroupId::Jump => Some("jump"),
+ GroupId::Call => Some("call"),
+ GroupId::Ret => Some("ret"),
+ GroupId::Arch(1) => Some("load"),
+ GroupId::Arch(2) => Some("store"),
+ GroupId::Arch(3) => Some("alu"),
+ _ => None,
+ }
+}
+
+pub fn insn_id_for_mnemonic(mnemonic: &str) -> InsnId {
+ let id = match mnemonic {
+ "l32i" => 1,
+ "s32i" => 2,
+ "add" | "movi" | "movi.n" | "addi.n" => 3,
+ "call0" | "callx0" => 4,
+ "ret" => 5,
+ "l32r" => 6,
+ "j" | "jx" | "j.n" => 3,
+ _ => 0,
+ };
+ InsnId(id)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::engine::Engine;
+ use crate::option::{EngineOptions, Opt};
+
+ #[test]
+ fn xtensa_l32i_and_add() {
+ let mut eng = Engine::open(Arch::Xtensa, Mode::LITTLE_ENDIAN).unwrap();
+ let l32i = eng.disasm_one(&[0x02, 0x41, 0x00], 0).unwrap();
+ assert_eq!(l32i.mnemonic, "l32i");
+ let add = eng.disasm_one(&[0x08, 0x21, 0x00], 0).unwrap();
+ assert_eq!(add.mnemonic, "add");
+ }
+
+ #[test]
+ fn xtensa_l32r_litbase_and_ret() {
+ let dec = XtensaDecoder::open(Mode::LITTLE_ENDIAN).unwrap();
+ let mut opts = EngineOptions::default();
+ opts.apply(Opt::Litbase(0x1000)).unwrap();
+ let l32r = dec
+ .decode_one(&[0x01, 0x40, 0x04], 0, &opts)
+ .unwrap();
+ assert_eq!(l32r.mnemonic, "l32r");
+ assert!(l32r.operands.contains("0x1010"));
+ let ret = dec
+ .decode_one(&[0x0d, 0x00, 0x00], 0, &EngineOptions::default())
+ .unwrap();
+ assert_eq!(ret.mnemonic, "ret");
+ }
+}
diff --git a/crates/ghidrust-decode/src/engine.rs b/crates/ghidrust-decode/src/engine.rs
new file mode 100644
index 0000000..d9e2369
--- /dev/null
+++ b/crates/ghidrust-decode/src/engine.rs
@@ -0,0 +1,261 @@
+use crate::alloc_hooks::{global_hooks, AllocHooks};
+use crate::arch::{open_decoder, ArchDecode};
+use crate::error::{Error, Result};
+use crate::group::GroupId;
+use crate::insn::Instruction;
+use crate::names;
+use crate::option::{EngineOptions, Opt};
+use crate::reg::RegId;
+use crate::support::{support, Arch, Mode, SupportQuery};
+
+pub const VERSION: &str = env!("CARGO_PKG_VERSION");
+
+pub struct Engine {
+ arch: Arch,
+ decoder: Box<dyn ArchDecode>,
+ options: EngineOptions,
+ last_error: Option<Error>,
+ hooks: &'static dyn AllocHooks,
+ open: bool,
+}
+
+impl Engine {
+ pub fn open(arch: Arch, mode: Mode) -> Result<Self> {
+ if !support(SupportQuery::Arch(arch)) {
+ return Err(Error::Arch(format!("architecture {:?} is not supported", arch)));
+ }
+ let decoder = open_decoder(arch, mode)?;
+ debug_assert_eq!(decoder.arch(), arch);
+ let mut options = EngineOptions::default();
+ options.mode = mode;
+ Ok(Self {
+ arch,
+ decoder,
+ options,
+ last_error: None,
+ hooks: global_hooks(),
+ open: true,
+ })
+ }
+
+ pub fn x86_64_default() -> Result<Self> {
+ Self::open(Arch::X86, Mode::MODE_64)
+ }
+
+ pub fn close(&mut self) {
+ self.open = false;
+ }
+
+ pub fn is_open(&self) -> bool {
+ self.open
+ }
+
+ pub fn arch(&self) -> Arch {
+ self.arch
+ }
+
+ pub fn option(&mut self, opt: Opt) -> Result<()> {
+ self.require_open()?;
+ self.options.apply(opt)
+ }
+
+ pub fn version(&self) -> &'static str {
+ VERSION
+ }
+
+ pub fn support(query: SupportQuery) -> bool {
+ support(query)
+ }
+
+ pub fn last_error(&self) -> Option<&Error> {
+ self.last_error.as_ref()
+ }
+
+ pub fn disasm(&mut self, bytes: &[u8], address: u64, count: usize) -> Result<Vec<Instruction>> {
+ self.require_open()?;
+ match self.decoder.decode_many(bytes, address, count, &self.options) {
+ Ok(v) => Ok(v),
+ Err(e) => {
+ self.last_error = Some(e.clone());
+ Err(e)
+ }
+ }
+ }
+
+ pub fn disasm_iter<'a>(
+ &'a mut self,
+ bytes: &'a [u8],
+ address: u64,
+ ) -> DisasmIter<'a> {
+ DisasmIter {
+ engine: self,
+ bytes,
+ address,
+ offset: 0,
+ }
+ }
+
+ pub fn disasm_one(&mut self, bytes: &[u8], address: u64) -> Result<Instruction> {
+ self.require_open()?;
+ match self.decoder.decode_one(bytes, address, &self.options) {
+ Ok(v) => Ok(v),
+ Err(e) => {
+ self.last_error = Some(e.clone());
+ Err(e)
+ }
+ }
+ }
+
+ pub fn reg_name(&self, reg: RegId) -> Option<&'static str> {
+ names::reg_name(self.arch, reg)
+ }
+
+ pub fn insn_name(&self, id: crate::insn::InsnId) -> Option<&'static str> {
+ names::insn_name(self.arch, id)
+ }
+
+ pub fn group_name(&self, group: GroupId) -> Option<&'static str> {
+ names::group_name(self.arch, group)
+ }
+
+ pub fn insn_group(&self, insn: &Instruction, index: usize) -> Option<GroupId> {
+ insn.detail.as_ref()?.groups.get(index).copied()
+ }
+
+ pub fn reg_read(&self, insn: &Instruction, index: usize) -> Option<RegId> {
+ let detail = insn.detail.as_ref()?;
+ detail
+ .regs_read
+ .get(index)
+ .or_else(|| detail.implicit_read.get(index))
+ .copied()
+ }
+
+ pub fn reg_write(&self, insn: &Instruction, index: usize) -> Option<RegId> {
+ let detail = insn.detail.as_ref()?;
+ detail
+ .regs_write
+ .get(index)
+ .or_else(|| detail.implicit_write.get(index))
+ .copied()
+ }
+
+ pub fn op_count(&self, insn: &Instruction) -> usize {
+ insn.detail
+ .as_ref()
+ .map(|d| d.operands.len())
+ .unwrap_or(0)
+ }
+
+ pub fn op_index<'a>(
+ &self,
+ insn: &'a Instruction,
+ index: usize,
+ ) -> Option<&'a crate::operand::Operand> {
+ insn.detail.as_ref()?.operands.get(index)
+ }
+
+ pub fn regs_access<'a>(&self, insn: &'a Instruction) -> Option<RegsAccess<'a>> {
+ insn.detail.as_ref().map(|d| RegsAccess {
+ read: &d.regs_read,
+ write: &d.regs_write,
+ implicit_read: &d.implicit_read,
+ implicit_write: &d.implicit_write,
+ })
+ }
+
+ pub fn hooks(&self) -> &'static dyn AllocHooks {
+ self.hooks
+ }
+
+ fn require_open(&self) -> Result<()> {
+ if self.open {
+ Ok(())
+ } else {
+ Err(Error::Handle("engine is closed".into()))
+ }
+ }
+}
+
+pub struct RegsAccess<'a> {
+ pub read: &'a [RegId],
+ pub write: &'a [RegId],
+ pub implicit_read: &'a [RegId],
+ pub implicit_write: &'a [RegId],
+}
+
+pub struct DisasmIter<'a> {
+ engine: &'a mut Engine,
+ bytes: &'a [u8],
+ address: u64,
+ offset: usize,
+}
+
+impl<'a> Iterator for DisasmIter<'a> {
+ type Item = Result<Instruction>;
+
+ fn next(&mut self) -> Option<Self::Item> {
+ if self.offset >= self.bytes.len() {
+ return None;
+ }
+ match self.engine.disasm_one(&self.bytes[self.offset..], self.address) {
+ Ok(insn) => {
+ let len = insn.length as usize;
+ if len == 0 {
+ return Some(Err(Error::Decode("zero-length instruction".into())));
+ }
+ self.offset += len;
+ self.address = self.address.wrapping_add(len as u64);
+ Some(Ok(insn))
+ }
+ Err(e) => Some(Err(e)),
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::insn::InsnId;
+
+ #[test]
+ fn engine_open_x86_mode64_disasm_prologue() {
+ let mut engine = Engine::open(Arch::X86, Mode::MODE_64).unwrap();
+ let bytes = [0x55, 0x48, 0x89, 0xe5, 0xc3];
+ let insns = engine.disasm(&bytes, 0x1000, 8).unwrap();
+ assert_eq!(insns.len(), 3);
+ assert_eq!(insns[0].mnemonic, "push");
+ assert_eq!(insns[0].operands, "rbp");
+ assert_eq!(insns[0].id, InsnId(1));
+ assert_eq!(insns[1].mnemonic, "mov");
+ assert_eq!(insns[1].operands, "rbp, rsp");
+ assert_eq!(insns[2].mnemonic, "ret");
+ assert_eq!(insns[2].length, 1);
+ }
+
+ #[test]
+ fn engine_support_handrolled_arches() {
+ for arch in Arch::ALL {
+ assert!(
+ Engine::support(SupportQuery::Arch(arch)),
+ "{arch:?} should be supported"
+ );
+ }
+ assert!(Engine::support(SupportQuery::All));
+ }
+
+ #[test]
+ fn engine_open_arm64() {
+ assert!(Engine::open(Arch::Arm64, Mode::LITTLE_ENDIAN).is_ok());
+ }
+
+ #[test]
+ fn engine_disasm_one_and_iter() {
+ let mut engine = Engine::x86_64_default().unwrap();
+ let bytes = [0x55, 0x48, 0x89, 0xe5, 0xc3];
+ let one = engine.disasm_one(&bytes, 0x1000).unwrap();
+ assert_eq!(one.mnemonic, "push");
+ let all: Result<Vec<_>> = engine.disasm_iter(&bytes, 0x1000).collect();
+ assert_eq!(all.unwrap().len(), 3);
+ }
+}
diff --git a/crates/ghidrust-decode/src/error.rs b/crates/ghidrust-decode/src/error.rs
new file mode 100644
index 0000000..3226bc6
--- /dev/null
+++ b/crates/ghidrust-decode/src/error.rs
@@ -0,0 +1,31 @@
+use std::fmt;
+
+/// Decode failure for decode error categories.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum Error {
+ Decode(String),
+ Arch(String),
+ Mode(String),
+ Option(String),
+ Handle(String),
+ Mem(String),
+ Detail(String),
+}
+
+impl fmt::Display for Error {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ match self {
+ Error::Decode(m) => write!(f, "decode: {m}"),
+ Error::Arch(m) => write!(f, "arch: {m}"),
+ Error::Mode(m) => write!(f, "mode: {m}"),
+ Error::Option(m) => write!(f, "option: {m}"),
+ Error::Handle(m) => write!(f, "handle: {m}"),
+ Error::Mem(m) => write!(f, "mem: {m}"),
+ Error::Detail(m) => write!(f, "detail: {m}"),
+ }
+ }
+}
+
+impl std::error::Error for Error {}
+
+pub type Result<T> = std::result::Result<T, Error>;
diff --git a/crates/ghidrust-decode/src/group.rs b/crates/ghidrust-decode/src/group.rs
new file mode 100644
index 0000000..01ca034
--- /dev/null
+++ b/crates/ghidrust-decode/src/group.rs
@@ -0,0 +1,46 @@
+use serde::{Deserialize, Serialize};
+
+/// Instruction group identifier .
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
+pub enum GroupId {
+ #[default]
+ Invalid,
+ Jump,
+ Call,
+ Ret,
+ Int,
+ Iret,
+ Privilege,
+ BranchRelative,
+ Arch(u16),
+}
+
+impl GroupId {
+ pub const fn raw(self) -> u16 {
+ match self {
+ GroupId::Invalid => 0,
+ GroupId::Jump => 1,
+ GroupId::Call => 2,
+ GroupId::Ret => 3,
+ GroupId::Int => 4,
+ GroupId::Iret => 5,
+ GroupId::Privilege => 6,
+ GroupId::BranchRelative => 7,
+ GroupId::Arch(v) => v,
+ }
+ }
+
+ pub const fn from_raw(v: u16) -> Self {
+ match v {
+ 0 => GroupId::Invalid,
+ 1 => GroupId::Jump,
+ 2 => GroupId::Call,
+ 3 => GroupId::Ret,
+ 4 => GroupId::Int,
+ 5 => GroupId::Iret,
+ 6 => GroupId::Privilege,
+ 7 => GroupId::BranchRelative,
+ n => GroupId::Arch(n),
+ }
+ }
+}
diff --git a/crates/ghidrust-decode/src/insn.rs b/crates/ghidrust-decode/src/insn.rs
new file mode 100644
index 0000000..c30ec4d
--- /dev/null
+++ b/crates/ghidrust-decode/src/insn.rs
@@ -0,0 +1,91 @@
+use crate::group::GroupId;
+use crate::operand::Operand;
+use crate::reg::RegId;
+use serde::{Deserialize, Serialize};
+
+/// Instruction identifier .
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
+pub struct InsnId(pub u32);
+
+impl InsnId {
+ pub const INVALID: InsnId = InsnId(0);
+
+ pub const fn new(raw: u32) -> Self {
+ Self(raw)
+ }
+
+ pub const fn raw(self) -> u32 {
+ self.0
+ }
+}
+
+/// Optional structured decode detail .
+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
+pub struct InsnDetail {
+ pub operands: Vec<Operand>,
+ pub groups: Vec<GroupId>,
+ pub regs_read: Vec<RegId>,
+ pub regs_write: Vec<RegId>,
+ pub implicit_read: Vec<RegId>,
+ pub implicit_write: Vec<RegId>,
+}
+
+/// Decoded instruction with mnemonic text and optional structured detail.
+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
+pub struct Instruction {
+ pub id: InsnId,
+ pub address: u64,
+ pub bytes: Vec<u8>,
+ pub mnemonic: String,
+ pub operands: String,
+ pub length: u8,
+ pub detail: Option<InsnDetail>,
+}
+
+impl Instruction {
+ /// Legacy five-field constructor (`id` / `detail` use defaults).
+ pub fn with_text(
+ address: u64,
+ bytes: Vec<u8>,
+ mnemonic: impl Into<String>,
+ operands: impl Into<String>,
+ length: u8,
+ ) -> Self {
+ Self {
+ address,
+ bytes,
+ mnemonic: mnemonic.into(),
+ operands: operands.into(),
+ length,
+ ..Default::default()
+ }
+ }
+
+ pub fn text(&self) -> String {
+ let hex = format!("{:24}", hex_bytes(&self.bytes));
+ if self.operands.is_empty() {
+ format!("{:016x}: {} {}", self.address, hex, self.mnemonic)
+ } else {
+ format!(
+ "{:016x}: {} {} {}",
+ self.address, hex, self.mnemonic, self.operands
+ )
+ }
+ }
+
+ /// Compact listing line without hex bytes: `addr: mnemonic [operands]`.
+ pub fn brief_text(&self) -> String {
+ if self.operands.is_empty() {
+ format!("{:#x}: {}", self.address, self.mnemonic)
+ } else {
+ format!("{:#x}: {} {}", self.address, self.mnemonic, self.operands)
+ }
+ }
+}
+
+fn hex_bytes(b: &[u8]) -> String {
+ b.iter()
+ .map(|x| format!("{x:02x}"))
+ .collect::<Vec<_>>()
+ .join(" ")
+}
diff --git a/crates/ghidrust-decode/src/lib.rs b/crates/ghidrust-decode/src/lib.rs
index ebb3892..2818435 100644
--- a/crates/ghidrust-decode/src/lib.rs
+++ b/crates/ghidrust-decode/src/lib.rs
@@ -1,35 +1,47 @@
-//! Hand-rolled x86-64 instruction decode (no Capstone / iced-x86 / Zydis at runtime).
+//! Hand-rolled instruction decode (no third-party disassemblers at runtime).
//!
-//! Length-disassembly + mnemonic/operand strings for common prologue and fixture
-//! opcodes. Program-aware helpers (`disassemble_at` / `disassemble_range`) remain
-//! in `ghidrust-core` and call [`decode_one`] here.
+//! engine API plus legacy helpers [`decode_one`] / [`decode_bytes`].
+//! Program-aware helpers (`disassemble_at` / `disassemble_range`) remain in
+//! `ghidrust-core` and call [`decode_one`] here.
-mod x86_64;
+// Arch packages keep register/helper tables for opcode-family growth; unused
+// today is intentional API surface, not dead product code.
+#![allow(dead_code)]
-pub use x86_64::{decode_one, Instruction};
+mod alloc_hooks;
+mod arch;
+mod engine;
+mod error;
+mod group;
+mod insn;
+mod names;
+mod operand;
+mod option;
+mod reg;
+mod skipdata;
+mod support;
-use std::fmt;
+pub use alloc_hooks::{global_hooks, AllocHooks, GlobalAllocHooks};
+pub use engine::{DisasmIter, Engine, RegsAccess, VERSION};
+pub use error::{Error, Result};
+pub use group::GroupId;
+pub use insn::{InsnDetail, InsnId, Instruction};
+pub use names::{group_name, insn_id_for_mnemonic, insn_name, reg_name};
+pub use operand::{OpType, Operand};
+pub use option::{EngineOptions, MnemOverride, Opt, Syntax};
+pub use reg::RegId;
+pub use skipdata::{SkipdataCb, SkipdataConfig, SkipdataFn, SkipdataHandler};
+pub use support::{support, Arch, Mode, SupportQuery};
-/// Decode failure (truncated stream, unhandled opcode, …).
-#[derive(Debug, Clone, PartialEq, Eq)]
-pub enum Error {
- Decode(String),
+/// Decode one instruction via the default x86-64 engine.
+pub fn decode_one(bytes: &[u8], address: u64) -> Result<Instruction> {
+ let mut engine = Engine::x86_64_default()?;
+ engine.disasm_one(bytes, address)
}
-impl fmt::Display for Error {
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- match self {
- Error::Decode(m) => write!(f, "decode: {m}"),
- }
- }
-}
-
-impl std::error::Error for Error {}
-
-pub type Result<T> = std::result::Result<T, Error>;
-
/// Decode a linear byte slice into a sequence of instructions (stops on first error).
pub fn decode_bytes(bytes: &[u8], start_address: u64, max_insns: usize) -> Result<Vec<Instruction>> {
+ let mut engine = Engine::x86_64_default()?;
let mut out = Vec::new();
let mut off = 0usize;
let mut va = start_address;
@@ -37,7 +49,7 @@ pub fn decode_bytes(bytes: &[u8], start_address: u64, max_insns: usize) -> Resul
if off >= bytes.len() {
break;
}
- match decode_one(&bytes[off..], va) {
+ match engine.disasm_one(&bytes[off..], va) {
Ok(insn) => {
let len = insn.length as usize;
off += len;
@@ -54,7 +66,7 @@ pub fn decode_bytes(bytes: &[u8], start_address: u64, max_insns: usize) -> Resul
}
if out.is_empty() {
return Err(Error::Decode(format!(
- "no instructions at {start_address:#x}"
+ "no instructions at {start_address:#x}"
)));
}
Ok(out)
@@ -69,8 +81,18 @@ mod tests {
let b = [0x55, 0x48, 0x89, 0xe5, 0xc3];
let insns = decode_bytes(&b, 0x1000, 8).unwrap();
assert_eq!(insns.len(), 3);
- assert_eq!(insns[0].mnemonic, "push");
- assert_eq!(insns[1].mnemonic, "mov");
- assert_eq!(insns[2].mnemonic, "ret");
+ assert_eq!(insns[0].mnemonic, "push");
+ assert_eq!(insns[1].mnemonic, "mov");
+ assert_eq!(insns[2].mnemonic, "ret");
+ }
+
+ #[test]
+ fn legacy_decode_one_matches_engine() {
+ let b = [0x55, 0x48, 0x89, 0xe5, 0xc3];
+ let legacy = decode_one(&b, 0x1000).unwrap();
+ let mut engine = Engine::open(Arch::X86, Mode::MODE_64).unwrap();
+ let via_engine = engine.disasm_one(&b, 0x1000).unwrap();
+ assert_eq!(legacy.mnemonic, via_engine.mnemonic);
+ assert_eq!(legacy.length, via_engine.length);
}
}
diff --git a/crates/ghidrust-decode/src/names.rs b/crates/ghidrust-decode/src/names.rs
new file mode 100644
index 0000000..3957a9f
--- /dev/null
+++ b/crates/ghidrust-decode/src/names.rs
@@ -0,0 +1,120 @@
+use crate::group::GroupId;
+use crate::insn::InsnId;
+use crate::reg::RegId;
+use crate::support::Arch;
+
+pub fn reg_name(arch: Arch, reg: RegId) -> Option<&'static str> {
+ match arch {
+ Arch::Arm => crate::arch::arm::reg_name(reg),
+ Arch::Arm64 => crate::arch::aarch64::reg_name(reg),
+ Arch::Mips => crate::arch::mips::reg_name(reg),
+ Arch::Ppc => crate::arch::ppc::reg_name(reg),
+ Arch::X86 => crate::arch::x86::reg_name(reg),
+ Arch::Evm => crate::arch::evm::reg_name(reg),
+ Arch::Mos65xx => crate::arch::mos65xx::reg_name(reg),
+ Arch::Wasm => crate::arch::wasm::reg_name(reg),
+ Arch::Bpf => crate::arch::bpf::reg_name(reg),
+ Arch::Riscv => crate::arch::riscv::reg_name(reg),
+ Arch::Sparc => crate::arch::sparc::reg_name(reg),
+ Arch::Sysz => crate::arch::sysz::reg_name(reg),
+ Arch::Xcore => crate::arch::xcore::reg_name(reg),
+ Arch::M68k => crate::arch::m68k::reg_name(reg),
+ Arch::Tms320c64x => crate::arch::tms320c64x::reg_name(reg),
+ Arch::M680x => crate::arch::m680x::reg_name(reg),
+ Arch::Tricore => crate::arch::tricore::reg_name(reg),
+ Arch::Alpha => crate::arch::alpha::reg_name(reg),
+ Arch::Hppa => crate::arch::hppa::reg_name(reg),
+ Arch::Loongarch => crate::arch::loongarch::reg_name(reg),
+ Arch::Arc => crate::arch::arc::reg_name(reg),
+ Arch::Sh => crate::arch::sh::reg_name(reg),
+ Arch::Xtensa => crate::arch::xtensa::reg_name(reg),
+ Arch::Max => None,
+ }
+}
+
+pub fn insn_name(arch: Arch, id: InsnId) -> Option<&'static str> {
+ match arch {
+ Arch::Arm => crate::arch::arm::insn_name(id),
+ Arch::Arm64 => crate::arch::aarch64::insn_name(id),
+ Arch::Mips => crate::arch::mips::insn_name(id),
+ Arch::Ppc => crate::arch::ppc::insn_name(id),
+ Arch::X86 => crate::arch::x86::insn_name(id),
+ Arch::Evm => crate::arch::evm::insn_name(id),
+ Arch::Mos65xx => crate::arch::mos65xx::insn_name(id),
+ Arch::Wasm => crate::arch::wasm::insn_name(id),
+ Arch::Bpf => crate::arch::bpf::insn_name(id),
+ Arch::Riscv => crate::arch::riscv::insn_name(id),
+ Arch::Sparc => crate::arch::sparc::insn_name(id),
+ Arch::Sysz => crate::arch::sysz::insn_name(id),
+ Arch::Xcore => crate::arch::xcore::insn_name(id),
+ Arch::M68k => crate::arch::m68k::insn_name(id),
+ Arch::Tms320c64x => crate::arch::tms320c64x::insn_name(id),
+ Arch::M680x => crate::arch::m680x::insn_name(id),
+ Arch::Tricore => crate::arch::tricore::insn_name(id),
+ Arch::Alpha => crate::arch::alpha::insn_name(id),
+ Arch::Hppa => crate::arch::hppa::insn_name(id),
+ Arch::Loongarch => crate::arch::loongarch::insn_name(id),
+ Arch::Arc => crate::arch::arc::insn_name(id),
+ Arch::Sh => crate::arch::sh::insn_name(id),
+ Arch::Xtensa => crate::arch::xtensa::insn_name(id),
+ Arch::Max => None,
+ }
+}
+
+pub fn group_name(arch: Arch, group: GroupId) -> Option<&'static str> {
+ match arch {
+ Arch::Arm => crate::arch::arm::group_name(group),
+ Arch::Arm64 => crate::arch::aarch64::group_name(group),
+ Arch::Mips => crate::arch::mips::group_name(group),
+ Arch::Ppc => crate::arch::ppc::group_name(group),
+ Arch::X86 => crate::arch::x86::group_name(group),
+ Arch::Evm => crate::arch::evm::group_name(group),
+ Arch::Mos65xx => crate::arch::mos65xx::group_name(group),
+ Arch::Wasm => crate::arch::wasm::group_name(group),
+ Arch::Bpf => crate::arch::bpf::group_name(group),
+ Arch::Riscv => crate::arch::riscv::group_name(group),
+ Arch::Sparc => crate::arch::sparc::group_name(group),
+ Arch::Sysz => crate::arch::sysz::group_name(group),
+ Arch::Xcore => crate::arch::xcore::group_name(group),
+ Arch::M68k => crate::arch::m68k::group_name(group),
+ Arch::Tms320c64x => crate::arch::tms320c64x::group_name(group),
+ Arch::M680x => crate::arch::m680x::group_name(group),
+ Arch::Tricore => crate::arch::tricore::group_name(group),
+ Arch::Alpha => crate::arch::alpha::group_name(group),
+ Arch::Hppa => crate::arch::hppa::group_name(group),
+ Arch::Loongarch => crate::arch::loongarch::group_name(group),
+ Arch::Arc => crate::arch::arc::group_name(group),
+ Arch::Sh => crate::arch::sh::group_name(group),
+ Arch::Xtensa => crate::arch::xtensa::group_name(group),
+ Arch::Max => None,
+ }
+}
+
+pub fn insn_id_for_mnemonic(arch: Arch, mnemonic: &str) -> InsnId {
+ match arch {
+ Arch::Arm => crate::arch::arm::insn_id_for_mnemonic(mnemonic),
+ Arch::Arm64 => crate::arch::aarch64::insn_id_for_mnemonic(mnemonic),
+ Arch::Mips => crate::arch::mips::insn_id_for_mnemonic(mnemonic),
+ Arch::Ppc => crate::arch::ppc::insn_id_for_mnemonic(mnemonic),
+ Arch::X86 => crate::arch::x86::insn_id_for_mnemonic(mnemonic),
+ Arch::Evm => crate::arch::evm::insn_id_for_mnemonic(mnemonic),
+ Arch::Mos65xx => crate::arch::mos65xx::insn_id_for_mnemonic(mnemonic),
+ Arch::Wasm => crate::arch::wasm::insn_id_for_mnemonic(mnemonic),
+ Arch::Bpf => crate::arch::bpf::insn_id_for_mnemonic(mnemonic),
+ Arch::Riscv => crate::arch::riscv::insn_id_for_mnemonic(mnemonic),
+ Arch::Sparc => crate::arch::sparc::insn_id_for_mnemonic(mnemonic),
+ Arch::Sysz => crate::arch::sysz::insn_id_for_mnemonic(mnemonic),
+ Arch::Xcore => crate::arch::xcore::insn_id_for_mnemonic(mnemonic),
+ Arch::M68k => crate::arch::m68k::insn_id_for_mnemonic(mnemonic),
+ Arch::Tms320c64x => crate::arch::tms320c64x::insn_id_for_mnemonic(mnemonic),
+ Arch::M680x => crate::arch::m680x::insn_id_for_mnemonic(mnemonic),
+ Arch::Tricore => crate::arch::tricore::insn_id_for_mnemonic(mnemonic),
+ Arch::Alpha => crate::arch::alpha::insn_id_for_mnemonic(mnemonic),
+ Arch::Hppa => crate::arch::hppa::insn_id_for_mnemonic(mnemonic),
+ Arch::Loongarch => crate::arch::loongarch::insn_id_for_mnemonic(mnemonic),
+ Arch::Arc => crate::arch::arc::insn_id_for_mnemonic(mnemonic),
+ Arch::Sh => crate::arch::sh::insn_id_for_mnemonic(mnemonic),
+ Arch::Xtensa => crate::arch::xtensa::insn_id_for_mnemonic(mnemonic),
+ Arch::Max => InsnId::INVALID,
+ }
+}
diff --git a/crates/ghidrust-decode/src/operand.rs b/crates/ghidrust-decode/src/operand.rs
new file mode 100644
index 0000000..194cea8
--- /dev/null
+++ b/crates/ghidrust-decode/src/operand.rs
@@ -0,0 +1,42 @@
+use crate::reg::RegId;
+use serde::{Deserialize, Serialize};
+
+/// Operand kind .
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
+pub enum OpType {
+ #[default]
+ Invalid,
+ Reg,
+ Imm,
+ Mem,
+ Fp,
+}
+
+/// Structured instruction operand.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub enum Operand {
+ Reg(RegId),
+ Imm { value: i64, size: u8 },
+ Mem {
+ base: RegId,
+ index: RegId,
+ scale: u8,
+ disp: i64,
+ segment: RegId,
+ size: u8,
+ },
+ Fp,
+ Invalid,
+}
+
+impl Operand {
+ pub const fn op_type(&self) -> OpType {
+ match self {
+ Operand::Reg(_) => OpType::Reg,
+ Operand::Imm { .. } => OpType::Imm,
+ Operand::Mem { .. } => OpType::Mem,
+ Operand::Fp => OpType::Fp,
+ Operand::Invalid => OpType::Invalid,
+ }
+ }
+}
diff --git a/crates/ghidrust-decode/src/option.rs b/crates/ghidrust-decode/src/option.rs
new file mode 100644
index 0000000..5208e0b
--- /dev/null
+++ b/crates/ghidrust-decode/src/option.rs
@@ -0,0 +1,93 @@
+use crate::support::Mode;
+use std::collections::HashMap;
+
+/// Assembly syntax flavor .
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
+pub enum Syntax {
+ #[default]
+ Default,
+ Intel,
+ Att,
+ NoRegName,
+ Masm,
+ Motorola,
+ CsRegAlias,
+ Percent,
+ NoDollar,
+ NoAliasText,
+ NoAliasTextCompressed,
+}
+
+/// Per-instruction mnemonic override.
+#[derive(Debug, Clone, PartialEq, Eq, Default)]
+pub struct MnemOverride {
+ pub id: u32,
+ pub mnemonic: String,
+}
+
+/// Engine option .
+#[derive(Debug, Clone)]
+pub enum Opt {
+ Syntax(Syntax),
+ Detail(bool),
+ DetailReal(bool),
+ Mode(Mode),
+ Skipdata(bool),
+ SkipdataSetup(crate::skipdata::SkipdataConfig),
+ Mnemonic(MnemOverride),
+ Unsigned(bool),
+ OnlyOffsetBranch(bool),
+ Litbase(u32),
+}
+
+/// Resolved engine configuration.
+#[derive(Debug, Clone)]
+pub struct EngineOptions {
+ pub syntax: Syntax,
+ pub detail: bool,
+ pub detail_real: bool,
+ pub mode: Mode,
+ pub skipdata: bool,
+ pub skipdata_setup: crate::skipdata::SkipdataConfig,
+ pub mnemonic_overrides: HashMap<u32, String>,
+ pub unsigned: bool,
+ pub only_offset_branch: bool,
+ pub litbase: u32,
+}
+
+impl Default for EngineOptions {
+ fn default() -> Self {
+ Self {
+ syntax: Syntax::default(),
+ detail: false,
+ detail_real: false,
+ mode: Mode::MODE_64,
+ skipdata: false,
+ skipdata_setup: crate::skipdata::SkipdataConfig::default(),
+ mnemonic_overrides: HashMap::new(),
+ unsigned: false,
+ only_offset_branch: false,
+ litbase: 0,
+ }
+ }
+}
+
+impl EngineOptions {
+ pub fn apply(&mut self, opt: Opt) -> crate::error::Result<()> {
+ match opt {
+ Opt::Syntax(v) => self.syntax = v,
+ Opt::Detail(v) => self.detail = v,
+ Opt::DetailReal(v) => self.detail_real = v,
+ Opt::Mode(v) => self.mode = v,
+ Opt::Skipdata(v) => self.skipdata = v,
+ Opt::SkipdataSetup(v) => self.skipdata_setup = v,
+ Opt::Mnemonic(v) => {
+ self.mnemonic_overrides.insert(v.id, v.mnemonic);
+ }
+ Opt::Unsigned(v) => self.unsigned = v,
+ Opt::OnlyOffsetBranch(v) => self.only_offset_branch = v,
+ Opt::Litbase(v) => self.litbase = v,
+ }
+ Ok(())
+ }
+}
diff --git a/crates/ghidrust-decode/src/reg.rs b/crates/ghidrust-decode/src/reg.rs
new file mode 100644
index 0000000..8a5b2b5
--- /dev/null
+++ b/crates/ghidrust-decode/src/reg.rs
@@ -0,0 +1,34 @@
+use crate::support::Arch;
+use serde::{Deserialize, Serialize};
+
+/// Architecture-tagged register identifier .
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
+pub struct RegId(pub u32);
+
+impl RegId {
+ pub const INVALID: RegId = RegId(0);
+
+ pub const fn new(raw: u32) -> Self {
+ Self(raw)
+ }
+
+ pub const fn raw(self) -> u32 {
+ self.0
+ }
+
+ pub const fn tag(self, arch: Arch) -> u32 {
+ (arch as u32) << 16 | (self.0 & 0xffff)
+ }
+
+ pub const fn arch(self) -> Arch {
+ Arch::from_raw((self.0 >> 16) as u8)
+ }
+
+ pub const fn index(self) -> u16 {
+ (self.0 & 0xffff) as u16
+ }
+
+ pub const fn tagged(arch: Arch, index: u16) -> Self {
+ Self((arch as u32) << 16 | index as u32)
+ }
+}
diff --git a/crates/ghidrust-decode/src/skipdata.rs b/crates/ghidrust-decode/src/skipdata.rs
new file mode 100644
index 0000000..2f1b719
--- /dev/null
+++ b/crates/ghidrust-decode/src/skipdata.rs
@@ -0,0 +1,77 @@
+use std::sync::Arc;
+
+/// Skip-data callback .
+pub trait SkipdataCb: Send + Sync {
+ fn skip(&self, address: u64, data: &[u8]) -> usize;
+}
+
+/// Function-pointer style skip-data callback.
+pub type SkipdataFn = fn(u64, *const u8, usize) -> usize;
+
+#[derive(Clone)]
+pub enum SkipdataHandler {
+ None,
+ Trait(Arc<dyn SkipdataCb>),
+ Fn(SkipdataFn),
+}
+
+impl std::fmt::Debug for SkipdataHandler {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match self {
+ SkipdataHandler::None => write!(f, "SkipdataHandler::None"),
+ SkipdataHandler::Trait(_) => write!(f, "SkipdataHandler::Trait(_)"),
+ SkipdataHandler::Fn(_) => write!(f, "SkipdataHandler::Fn(_)"),
+ }
+ }
+}
+
+impl Default for SkipdataHandler {
+ fn default() -> Self {
+ Self::None
+ }
+}
+
+impl SkipdataHandler {
+ pub fn invoke(&self, address: u64, data: &[u8]) -> usize {
+ match self {
+ SkipdataHandler::None => 1,
+ SkipdataHandler::Trait(cb) => cb.skip(address, data),
+ SkipdataHandler::Fn(f) => f(address, data.as_ptr(), data.len()),
+ }
+ }
+}
+
+/// Skip-data configuration .
+#[derive(Clone, Default)]
+pub struct SkipdataConfig {
+ pub mnemonic: String,
+ pub handler: SkipdataHandler,
+}
+
+impl SkipdataConfig {
+ pub fn new(mnemonic: impl Into<String>) -> Self {
+ Self {
+ mnemonic: mnemonic.into(),
+ handler: SkipdataHandler::None,
+ }
+ }
+
+ pub fn with_trait(mut self, cb: Arc<dyn SkipdataCb>) -> Self {
+ self.handler = SkipdataHandler::Trait(cb);
+ self
+ }
+
+ pub fn with_fn(mut self, f: SkipdataFn) -> Self {
+ self.handler = SkipdataHandler::Fn(f);
+ self
+ }
+}
+
+impl std::fmt::Debug for SkipdataConfig {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("SkipdataConfig")
+ .field("mnemonic", &self.mnemonic)
+ .field("handler", &self.handler)
+ .finish()
+ }
+}
diff --git a/crates/ghidrust-decode/src/support.rs b/crates/ghidrust-decode/src/support.rs
new file mode 100644
index 0000000..95a88b1
--- /dev/null
+++ b/crates/ghidrust-decode/src/support.rs
@@ -0,0 +1,269 @@
+/// architecture identifiers (24 values + `Max`).
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+#[repr(u8)]
+pub enum Arch {
+ Arm = 0,
+ Arm64 = 1,
+ Mips = 2,
+ X86 = 3,
+ Ppc = 4,
+ Sparc = 5,
+ Sysz = 6,
+ Xcore = 7,
+ M68k = 8,
+ Tms320c64x = 9,
+ M680x = 10,
+ Evm = 11,
+ Mos65xx = 12,
+ Wasm = 13,
+ Bpf = 14,
+ Riscv = 15,
+ Tricore = 16,
+ Alpha = 17,
+ Hppa = 18,
+ Loongarch = 19,
+ Arc = 20,
+ Sh = 21,
+ Xtensa = 22,
+ Max = 23,
+}
+
+impl Arch {
+ pub const ALL: [Arch; 23] = [
+ Arch::Arm,
+ Arch::Arm64,
+ Arch::Mips,
+ Arch::X86,
+ Arch::Ppc,
+ Arch::Sparc,
+ Arch::Sysz,
+ Arch::Xcore,
+ Arch::M68k,
+ Arch::Tms320c64x,
+ Arch::M680x,
+ Arch::Evm,
+ Arch::Mos65xx,
+ Arch::Wasm,
+ Arch::Bpf,
+ Arch::Riscv,
+ Arch::Tricore,
+ Arch::Alpha,
+ Arch::Hppa,
+ Arch::Loongarch,
+ Arch::Arc,
+ Arch::Sh,
+ Arch::Xtensa,
+ ];
+
+ pub const fn from_raw(v: u8) -> Self {
+ match v {
+ 0 => Arch::Arm,
+ 1 => Arch::Arm64,
+ 2 => Arch::Mips,
+ 3 => Arch::X86,
+ 4 => Arch::Ppc,
+ 5 => Arch::Sparc,
+ 6 => Arch::Sysz,
+ 7 => Arch::Xcore,
+ 8 => Arch::M68k,
+ 9 => Arch::Tms320c64x,
+ 10 => Arch::M680x,
+ 11 => Arch::Evm,
+ 12 => Arch::Mos65xx,
+ 13 => Arch::Wasm,
+ 14 => Arch::Bpf,
+ 15 => Arch::Riscv,
+ 16 => Arch::Tricore,
+ 17 => Arch::Alpha,
+ 18 => Arch::Hppa,
+ 19 => Arch::Loongarch,
+ 20 => Arch::Arc,
+ 21 => Arch::Sh,
+ 22 => Arch::Xtensa,
+ _ => Arch::Max,
+ }
+ }
+
+ pub const fn name(self) -> &'static str {
+ match self {
+ Arch::Arm => "arm",
+ Arch::Arm64 => "arm64",
+ Arch::Mips => "mips",
+ Arch::X86 => "x86",
+ Arch::Ppc => "ppc",
+ Arch::Sparc => "sparc",
+ Arch::Sysz => "sysz",
+ Arch::Xcore => "xcore",
+ Arch::M68k => "m68k",
+ Arch::Tms320c64x => "tms320c64x",
+ Arch::M680x => "m680x",
+ Arch::Evm => "evm",
+ Arch::Mos65xx => "mos65xx",
+ Arch::Wasm => "wasm",
+ Arch::Bpf => "bpf",
+ Arch::Riscv => "riscv",
+ Arch::Tricore => "tricore",
+ Arch::Alpha => "alpha",
+ Arch::Hppa => "hppa",
+ Arch::Loongarch => "loongarch",
+ Arch::Arc => "arc",
+ Arch::Sh => "sh",
+ Arch::Xtensa => "xtensa",
+ Arch::Max => "max",
+ }
+ }
+}
+
+/// mode bitfield (`cs_mode`).
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
+pub struct Mode(pub u32);
+
+impl Mode {
+ pub const LITTLE_ENDIAN: Mode = Mode(0);
+ pub const BIG_ENDIAN: Mode = Mode(1 << 31);
+ pub const MODE_16: Mode = Mode(1 << 1);
+ pub const MODE_32: Mode = Mode(1 << 2);
+ pub const MODE_64: Mode = Mode(1 << 3);
+ pub const THUMB: Mode = Mode(1 << 4);
+ pub const MCLASS: Mode = Mode(1 << 5);
+ pub const V8: Mode = Mode(1 << 6);
+ pub const MICRO: Mode = Mode(1 << 4);
+ pub const MIPS3: Mode = Mode(1 << 5);
+ pub const MIPS32R6: Mode = Mode(1 << 6);
+ pub const MIPS2: Mode = Mode(1 << 7);
+ pub const V9: Mode = Mode(1 << 4);
+ pub const PPC32: Mode = Mode(1 << 4);
+ pub const PPC64: Mode = Mode(1 << 5);
+ pub const QPX: Mode = Mode(1 << 6);
+ pub const MIPS32: Mode = Mode(1 << 2);
+ pub const MIPS64: Mode = Mode(1 << 3);
+ pub const ARM: Mode = Mode(0);
+ pub const BPF_CLASSIC: Mode = Mode(0);
+ pub const BPF_EXTENDED: Mode = Mode(1 << 0);
+ pub const MOS65XX_6502: Mode = Mode(1 << 1);
+ pub const MOS65XX_65C02: Mode = Mode(1 << 2);
+ pub const RISCV32: Mode = Mode(1 << 0);
+ pub const RISCV64: Mode = Mode(1 << 1);
+ pub const RISCV_C: Mode = Mode(1 << 2);
+
+ pub const fn bits(self) -> u32 {
+ self.0
+ }
+
+ pub const fn contains(self, flag: Mode) -> bool {
+ (self.0 & flag.0) == flag.0
+ }
+
+ pub const fn intersects(self, flag: Mode) -> bool {
+ (self.0 & flag.0) != 0
+ }
+
+ pub const fn union(self, other: Mode) -> Mode {
+ Mode(self.0 | other.0)
+ }
+
+ pub const fn with(self, flag: Mode) -> Mode {
+ self.union(flag)
+ }
+
+ pub const fn without(self, flag: Mode) -> Mode {
+ Mode(self.0 & !flag.0)
+ }
+
+ pub fn is_valid_for(self, arch: Arch) -> bool {
+ match arch {
+ Arch::X86 => {
+ let width = self.intersects(Self::MODE_16)
+ || self.intersects(Self::MODE_32)
+ || self.intersects(Self::MODE_64);
+ width || self == Self::LITTLE_ENDIAN
+ }
+ Arch::Evm | Arch::Wasm => !self.intersects(Self::BIG_ENDIAN),
+ Arch::Mos65xx => !self.intersects(Self::BIG_ENDIAN),
+ Arch::Bpf => !self.intersects(Self::BIG_ENDIAN),
+ Arch::Riscv => {
+ !self.intersects(Self::BIG_ENDIAN)
+ && (self.intersects(Self::RISCV32)
+ || self.intersects(Self::RISCV64)
+ || self == Self::LITTLE_ENDIAN)
+ }
+ Arch::Arm => {
+ self == Self::LITTLE_ENDIAN
+ || self == Self::BIG_ENDIAN
+ || self.contains(Self::THUMB)
+ || self.contains(Self::MCLASS)
+ || self.contains(Self::V8)
+ }
+ Arch::Arm64 => {
+ self == Self::LITTLE_ENDIAN
+ || self == Self::BIG_ENDIAN
+ || self.contains(Self::V8)
+ }
+ Arch::Mips => {
+ self.contains(Self::MIPS32)
+ || self.contains(Self::MIPS64)
+ || self == Self::LITTLE_ENDIAN
+ || self == Self::BIG_ENDIAN
+ }
+ Arch::Ppc => {
+ self.contains(Self::PPC32)
+ || self.contains(Self::PPC64)
+ || self == Self::LITTLE_ENDIAN
+ || self == Self::BIG_ENDIAN
+ }
+ Arch::Sparc => {
+ self.contains(Self::V9)
+ || self == Self::LITTLE_ENDIAN
+ || self == Self::BIG_ENDIAN
+ }
+ Arch::Sysz | Arch::Hppa => {
+ self == Self::LITTLE_ENDIAN
+ || self == Self::BIG_ENDIAN
+ || self.contains(Self::MODE_64)
+ }
+ Arch::Xcore
+ | Arch::M68k
+ | Arch::Tricore
+ | Arch::Arc
+ | Arch::Sh
+ | Arch::Loongarch => {
+ self == Self::LITTLE_ENDIAN
+ || self == Self::BIG_ENDIAN
+ || self.contains(Self::MODE_32)
+ || self.contains(Self::MODE_64)
+ }
+ Arch::Tms320c64x | Arch::Alpha | Arch::Xtensa | Arch::M680x => {
+ self == Self::LITTLE_ENDIAN
+ || self == Self::BIG_ENDIAN
+ || self.contains(Self::MODE_32)
+ }
+ Arch::Max => false,
+ }
+ }
+}
+
+const IMPLEMENTED: [Arch; 23] = Arch::ALL;
+
+/// Runtime support query .
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum SupportQuery {
+ Arch(Arch),
+ All,
+ Diet,
+ X86Reduce,
+}
+
+impl SupportQuery {
+ pub fn supported(self) -> bool {
+ match self {
+ SupportQuery::Arch(arch) => IMPLEMENTED.contains(&arch),
+ SupportQuery::All => IMPLEMENTED.len() == Arch::ALL.len(),
+ SupportQuery::Diet => cfg!(feature = "diet"),
+ SupportQuery::X86Reduce => cfg!(feature = "x86-reduce"),
+ }
+ }
+}
+
+pub fn support(query: SupportQuery) -> bool {
+ query.supported()
+}
diff --git a/crates/ghidrust-decomp/src/bench.rs b/crates/ghidrust-decomp/src/bench.rs
index 87b4be2..951d316 100644
--- a/crates/ghidrust-decomp/src/bench.rs
+++ b/crates/ghidrust-decomp/src/bench.rs
@@ -1,10 +1,10 @@
//! **Decompile bench harness** — per-function wall-clock breakdown across the
//! Stage-0 and Stage-0.5 emit paths.
//!
-//! The bench is the scaffolding for the roadmap's *"beat Ghidra wall-clock"*
+//! The bench is the scaffolding for the roadmap's *"beat wall-clock"*
//! metric ([`docs/GPU_DECOMPILER_RESEARCH.md`] and the plan file
//! `decompiler quality goals`). It intentionally captures only what we
-//! can *actually* measure today; head-to-head Ghidra timings are appended by a
+//! can *actually* measure today; head-to-head timings are appended by a
//! future scripted oracle.
//!
//! Public callers (CLI, MCP, tests) go through [`bench_program`] with an
@@ -237,12 +237,12 @@ pub fn bench_program_stage1_parallel(
/// **Stage-1 bench** — pick the shared entry set (or fall back to
/// `prog.analysis.functions`) and time Stage-0, Stage-0.5, and Stage-1 on
/// each. Captured Stage-1 text is stored so head-to-head oracles can run
-/// token-similarity metrics against Ghidra output without recomputing.
+/// token-similarity metrics against output without recomputing.
///
/// `entries` is optional: `None` = use `prog.analysis.functions` capped by
/// `max_functions`; `Some(list)` = use exactly that entry list (in order).
/// This is the API [`crate::ghidra_oracle::compare`] uses to enforce the
-/// "shared entry set" fairness rule for the Ghidra head-to-head.
+/// "shared entry set" fairness rule for the head-to-head.
pub fn bench_program_stage1(
prog: &Program,
entries: Option<&[u64]>,
diff --git a/crates/ghidrust-decomp/src/emit_tokens.rs b/crates/ghidrust-decomp/src/emit_tokens.rs
index 33be08e..611fff5 100644
--- a/crates/ghidrust-decomp/src/emit_tokens.rs
+++ b/crates/ghidrust-decomp/src/emit_tokens.rs
@@ -5,7 +5,7 @@
use serde::{Deserialize, Serialize};
-/// ClangToken-analog kinds used by the GUI highlighter.
+/// kinds used by the GUI highlighter.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum EmitTokenKind {
diff --git a/crates/ghidrust-decomp/src/gpu_decompile.rs b/crates/ghidrust-decomp/src/gpu_decompile.rs
index 0cee2d1..6228e8f 100644
--- a/crates/ghidrust-decomp/src/gpu_decompile.rs
+++ b/crates/ghidrust-decomp/src/gpu_decompile.rs
@@ -546,13 +546,13 @@ fn ir_to_instructions(entry: u64, ir: &[GpuIrSlot]) -> Vec<ghidrust_core::Instru
_ => String::new(),
}
};
- Instruction {
- address: entry + s.off as u64,
- bytes: vec![0u8; s.length as usize],
- mnemonic: op_name(s.opcode).into(),
+ Instruction::with_text(
+ entry + s.off as u64,
+ vec![0u8; s.length as usize],
+ op_name(s.opcode),
operands,
- length: s.length as u8,
- }
+ s.length as u8,
+ )
})
.collect()
}
diff --git a/crates/ghidrust-decomp/src/lib.rs b/crates/ghidrust-decomp/src/lib.rs
index c632193..d1994a3 100644
--- a/crates/ghidrust-decomp/src/lib.rs
+++ b/crates/ghidrust-decomp/src/lib.rs
@@ -1,8 +1,8 @@
//! Hand-rolled reverse-engineering **decompile method**.
//!
-//! **Aspirational target:** structured, typed C that is measurable against Ghidra
+//! **Aspirational target:** structured, typed C that is measurable against
//! (wall clock, function discovery, readability, differential correctness on a
-//! fixed x86-64 corpus). Hex-Rays-class quality is a later ceiling after that bar.
+//! fixed x86-64 corpus). quality is a later ceiling after that bar.
//!
//! ## Emit stages (add capability without removing the oracle)
//!
diff --git a/crates/ghidrust-decomp/src/stage1.rs b/crates/ghidrust-decomp/src/stage1.rs
index e439823..590e7a6 100644
--- a/crates/ghidrust-decomp/src/stage1.rs
+++ b/crates/ghidrust-decomp/src/stage1.rs
@@ -763,7 +763,7 @@ fn unop(sym: &str, op: &SsaOp, ctx: &mut RenderCtx) -> Option<String> {
/// Render a pointer dereference. When the pointer base has a recovered
/// [`RustType::StructPtr`] and the address is `base + K` for a known
-/// field offset, render as `base->field_<hex>` — the same shape Ghidra's
+/// field offset, render as `base->field_<hex>` — the same shape 's
/// PrintC uses when a struct DataType is committed. Falls back to plain
/// `*(addr)` when the shape isn't recognized.
fn format_deref(addr: &SsaOperand, ctx: &RenderCtx) -> String {
diff --git a/crates/ghidrust-gui/src/debugger.rs b/crates/ghidrust-gui/src/debugger.rs
index ed6c200..3cb7274 100644
--- a/crates/ghidrust-gui/src/debugger.rs
+++ b/crates/ghidrust-gui/src/debugger.rs
@@ -1,133 +1,163 @@
-//! Ghidrust GUI · Debugger tool visibility.
+//! Ghidrust GUI · Debugger tool (tabbed host).
//!
-//! 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 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 internal modularization notes — new UI panes land here
-//! instead of piling into `main.rs`.
+//! ships a separate `Debugger` tool with a distinct catalog of
+//! `ComponentProvider`s. Ghidrust hosts them in **one** window with a tab
+//! strip. Live Process Bridge panes (Targets / Modules / Memory Bytes /
+//! Regions) talk to `ghidrust_core::process_*`; Threads / Registers / Stack /
+//! Breakpoints / Watches / Console remain honest stubs until a live debug agent lands.
use eframe::egui::{self, Color32, RichText, Ui};
use ghidrust_core::process::{
- process_attach, process_detach, process_list, process_modules, process_read,
- process_regions, static_to_live, ModuleInfo, ProcessInfo, ProcessSession, ReadResult,
- RegionInfo,
+ process_attach, process_detach, process_launch, process_list, process_modules, process_read,
+ process_regions, process_resume, static_to_live, LaunchRequest, ModuleInfo, ProcessInfo,
+ ProcessSession, ReadResult, RegionInfo,
};
+use std::path::{Path, PathBuf};
+
+/// Host window egui / layout id.
+pub const HOST_EGUI_ID: &str = "pane_dbg_host";
-/// One provider in Ghidra's Debugger tool catalog.
+/// One provider in Debugger tool catalog.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum DebuggerPane {
Targets,
- Threads,
Modules,
+ MemoryBytes,
Regions,
- Registers,
- Stack,
Breakpoints,
- MemoryBytes,
Watches,
+ Threads,
+ Registers,
+ Stack,
DebuggerConsole,
}
impl DebuggerPane {
- pub const ALL: &'static [DebuggerPane] = &[
+ /// Tab strip order: live panes first, stubs last.
+ pub const TAB_ORDER: &'static [DebuggerPane] = &[
DebuggerPane::Targets,
- DebuggerPane::Threads,
DebuggerPane::Modules,
+ DebuggerPane::MemoryBytes,
DebuggerPane::Regions,
- DebuggerPane::Registers,
- DebuggerPane::Stack,
DebuggerPane::Breakpoints,
- DebuggerPane::MemoryBytes,
DebuggerPane::Watches,
+ DebuggerPane::Threads,
+ DebuggerPane::Registers,
+ DebuggerPane::Stack,
DebuggerPane::DebuggerConsole,
];
- /// Ghidra display title (Window menu label / provider `TITLE`).
- pub const fn title(self) -> &'static str {
+ pub const ALL: &'static [DebuggerPane] = Self::TAB_ORDER;
+
+ /// Short label for the tab strip.
+ pub const fn short_title(self) -> &'static str {
match self {
- DebuggerPane::Targets => "Debugger Targets",
- DebuggerPane::Threads => "Debugger Threads",
- DebuggerPane::Modules => "Debugger Modules",
- DebuggerPane::Regions => "Debugger Regions",
- DebuggerPane::Registers => "Debugger Registers",
- DebuggerPane::Stack => "Debugger Stack",
- DebuggerPane::Breakpoints => "Debugger Breakpoints",
- DebuggerPane::MemoryBytes => "Debugger Memory Bytes",
- DebuggerPane::Watches => "Debugger Watches",
- DebuggerPane::DebuggerConsole => "Debugger Console",
+ DebuggerPane::Targets => "Targets",
+ DebuggerPane::Modules => "Modules",
+ DebuggerPane::MemoryBytes => "Memory Bytes",
+ DebuggerPane::Regions => "Regions",
+ DebuggerPane::Breakpoints => "Breakpoints",
+ DebuggerPane::Watches => "Watches",
+ DebuggerPane::Threads => "Threads",
+ DebuggerPane::Registers => "Registers",
+ DebuggerPane::Stack => "Stack",
+ DebuggerPane::DebuggerConsole => "Console",
}
}
- /// Ghidra plugin owner.
- pub const fn plugin(self) -> &'static str {
+ /// display title (legacy Window menu / provider `TITLE`).
+ #[allow(dead_code)]
+ pub const fn title(self) -> &'static str {
match self {
- DebuggerPane::Targets => "DebuggerTargetsPlugin",
- DebuggerPane::Threads => "DebuggerThreadsPlugin",
- DebuggerPane::Modules => "DebuggerModulesPlugin",
- DebuggerPane::Regions => "DebuggerRegionsPlugin",
- DebuggerPane::Registers => "DebuggerRegistersPlugin",
- DebuggerPane::Stack => "DebuggerStackPlugin",
- DebuggerPane::Breakpoints => "DebuggerBreakpointsPlugin",
- DebuggerPane::MemoryBytes => "DebuggerMemoryBytesPlugin",
- DebuggerPane::Watches => "DebuggerWatchesPlugin",
- DebuggerPane::DebuggerConsole => "DebuggerConsolePlugin",
+ DebuggerPane::Targets => "Debugger Targets",
+ DebuggerPane::Threads => "Debugger Threads",
+ DebuggerPane::Modules => "Debugger Modules",
+ DebuggerPane::Regions => "Debugger Regions",
+ DebuggerPane::Registers => "Debugger Registers",
+ DebuggerPane::Stack => "Debugger Stack",
+ DebuggerPane::Breakpoints => "Debugger Breakpoints",
+ DebuggerPane::MemoryBytes => "Debugger Memory Bytes",
+ DebuggerPane::Watches => "Debugger Watches",
+ DebuggerPane::DebuggerConsole => "Debugger Console",
}
}
- /// Stable egui window id for docking / layout persistence.
- pub const fn egui_id(self) -> &'static str {
+ /// plugin owner.
+ pub const fn plugin(self) -> &'static str {
match self {
- DebuggerPane::Targets => "pane_dbg_targets",
- DebuggerPane::Threads => "pane_dbg_threads",
- DebuggerPane::Modules => "pane_dbg_modules",
- DebuggerPane::Regions => "pane_dbg_regions",
- DebuggerPane::Registers => "pane_dbg_registers",
- DebuggerPane::Stack => "pane_dbg_stack",
- DebuggerPane::Breakpoints => "pane_dbg_breakpoints",
- DebuggerPane::MemoryBytes => "pane_dbg_membytes",
- DebuggerPane::Watches => "pane_dbg_watches",
- DebuggerPane::DebuggerConsole => "pane_dbg_console",
+ DebuggerPane::Targets => "DebuggerTargetsPlugin",
+ DebuggerPane::Threads => "DebuggerThreadsPlugin",
+ DebuggerPane::Modules => "DebuggerModulesPlugin",
+ DebuggerPane::Regions => "DebuggerRegionsPlugin",
+ DebuggerPane::Registers => "DebuggerRegistersPlugin",
+ DebuggerPane::Stack => "DebuggerStackPlugin",
+ DebuggerPane::Breakpoints => "DebuggerBreakpointsPlugin",
+ DebuggerPane::MemoryBytes => "DebuggerMemoryBytesPlugin",
+ DebuggerPane::Watches => "DebuggerWatchesPlugin",
+ DebuggerPane::DebuggerConsole => "DebuggerConsolePlugin",
}
}
- /// Columns rendered in the empty-state table (Ghidra parity).
- pub const fn columns(self) -> &'static [&'static str] {
+ /// Stable id for layout persistence (per-tab focus migration).
+ pub const fn egui_id(self) -> &'static str {
match self {
- DebuggerPane::Targets => &["Name", "Type", "State"],
- DebuggerPane::Threads => &["TID", "Name", "State", "Comment"],
- DebuggerPane::Modules => &["Base", "Name", "Path", "Size"],
- DebuggerPane::Regions => &["Start", "End", "Perms", "Kind"],
- DebuggerPane::Registers => &["Register", "Bits", "Value"],
- DebuggerPane::Stack => &["Level", "Frame", "PC", "Function"],
- DebuggerPane::Breakpoints => &["Enabled", "Address", "Kind", "Condition"],
- DebuggerPane::MemoryBytes => &["Address", "Bytes", "ASCII"],
- DebuggerPane::Watches => &["Expression", "Type", "Value"],
- DebuggerPane::DebuggerConsole => &["Line"],
+ DebuggerPane::Targets => "pane_dbg_targets",
+ DebuggerPane::Threads => "pane_dbg_threads",
+ DebuggerPane::Modules => "pane_dbg_modules",
+ DebuggerPane::Regions => "pane_dbg_regions",
+ DebuggerPane::Registers => "pane_dbg_registers",
+ DebuggerPane::Stack => "pane_dbg_stack",
+ DebuggerPane::Breakpoints => "pane_dbg_breakpoints",
+ DebuggerPane::MemoryBytes => "pane_dbg_membytes",
+ DebuggerPane::Watches => "pane_dbg_watches",
+ DebuggerPane::DebuggerConsole => "pane_dbg_console",
}
}
- /// Copy pointing at the pending backend for this pane.
- pub const fn backend_message(self) -> &'static str {
+ /// Columns rendered in the empty-state table (layout).
+ pub const fn columns(self) -> &'static [&'static str] {
match self {
- DebuggerPane::Targets => "Live Process Bridge (Windows) — ghidrust_core::process_list/attach.",
- DebuggerPane::Threads => "Backend pending — target-agent thread model.",
- DebuggerPane::Modules => "Live Process Bridge (Windows) — ghidrust_core::process_modules + static_to_live.",
- DebuggerPane::Regions => "Live Process Bridge (Windows) — ghidrust_core::process_regions (VirtualQueryEx).",
- DebuggerPane::Registers => "Backend pending — live register values (Register Manager renders the static register lattice).",
- DebuggerPane::Stack => "Backend pending — target-agent stack unwinder.",
- DebuggerPane::Breakpoints => "Backend pending — breakpoint model + agent set/clear.",
- DebuggerPane::MemoryBytes => "Live Process Bridge (Windows) — ghidrust_core::process_read (ReadProcessMemory).",
- DebuggerPane::Watches => "Backend pending — expression evaluator + refresh.",
- DebuggerPane::DebuggerConsole => "Backend pending — target-agent stdio.",
+ DebuggerPane::Targets => &["Name", "Type", "State"],
+ DebuggerPane::Threads => &["TID", "Name", "State", "Comment"],
+ DebuggerPane::Modules => &["Base", "Name", "Path", "Size"],
+ DebuggerPane::Regions => &["Start", "End", "Perms", "Kind"],
+ DebuggerPane::Registers => &["Register", "Bits", "Value"],
+ DebuggerPane::Stack => &["Level", "Frame", "PC", "Function"],
+ DebuggerPane::Breakpoints => &["Enabled", "Address", "Kind", "Condition"],
+ DebuggerPane::MemoryBytes => &["Address", "Bytes", "ASCII"],
+ DebuggerPane::Watches => &["Expression", "Type", "Value"],
+ DebuggerPane::DebuggerConsole => &["Line"],
+ }
+ }
+
+ /// Copy pointing at the pending backend for this pane.
+ pub const fn backend_message(self) -> &'static str {
+ match self {
+ DebuggerPane::Targets => {
+ "Live Process Bridge (Windows) — ghidrust_core::process_list/attach."
+ }
+ DebuggerPane::Threads => "Backend pending — target-agent thread model.",
+ DebuggerPane::Modules => {
+ "Live Process Bridge (Windows) — ghidrust_core::process_modules + static_to_live."
+ }
+ DebuggerPane::Regions => {
+ "Live Process Bridge (Windows) — ghidrust_core::process_regions (VirtualQueryEx)."
+ }
+ DebuggerPane::Registers => {
+ "Backend pending — live register values (Register Manager renders the static register lattice)."
+ }
+ DebuggerPane::Stack => "Backend pending — target-agent stack unwinder.",
+ DebuggerPane::Breakpoints => "Backend pending — breakpoint model + agent set/clear.",
+ DebuggerPane::MemoryBytes => {
+ "Live Process Bridge (Windows) — ghidrust_core::process_read (ReadProcessMemory)."
+ }
+ DebuggerPane::Watches => "Backend pending — expression evaluator + refresh.",
+ DebuggerPane::DebuggerConsole => "Backend pending — target-agent stdio.",
}
}
}
-/// Ghidra `Debugger` menu action.
+/// `Debugger` menu action.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DebuggerAction {
Launch,
@@ -143,7 +173,7 @@ pub enum DebuggerAction {
}
impl DebuggerAction {
- pub const ALL: &'static [DebuggerAction] = &[
+ pub const ALL: &'static [DebuggerAction] = &[
DebuggerAction::Launch,
DebuggerAction::Attach,
DebuggerAction::Disconnect,
@@ -155,59 +185,107 @@ impl DebuggerAction {
DebuggerAction::ToggleBreakpoint,
DebuggerAction::ShowWatches,
];
- pub const fn label(self) -> &'static str {
+ pub const fn label(self) -> &'static str {
match self {
- DebuggerAction::Launch => "Launch…",
- DebuggerAction::Attach => "Attach…",
- DebuggerAction::Disconnect => "Disconnect",
- DebuggerAction::Continue => "Continue (F5)",
- DebuggerAction::Interrupt => "Interrupt",
- DebuggerAction::StepInto => "Step Into (F7)",
- DebuggerAction::StepOver => "Step Over (F8)",
- DebuggerAction::StepOut => "Step Out (Shift+F8)",
- DebuggerAction::ToggleBreakpoint => "Toggle Breakpoint (F3)",
- DebuggerAction::ShowWatches => "Show Watches Pane",
+ DebuggerAction::Launch => "Launch…",
+ DebuggerAction::Attach => "Attach…",
+ DebuggerAction::Disconnect => "Disconnect",
+ DebuggerAction::Continue => "Continue (F5)",
+ DebuggerAction::Interrupt => "Interrupt",
+ DebuggerAction::StepInto => "Step Into (F7)",
+ DebuggerAction::StepOver => "Step Over (F8)",
+ DebuggerAction::StepOut => "Step Out (Shift+F8)",
+ DebuggerAction::ToggleBreakpoint => "Toggle Breakpoint (F3)",
+ DebuggerAction::ShowWatches => "Show Watches Pane",
}
}
}
/// Persistent state for the debugger tool mode.
-#[derive(Debug, Clone, Default)]
+#[derive(Debug, Clone)]
pub struct DebuggerState {
- /// User-set breakpoint VAs (session-only until backend lands).
+ /// User-set breakpoint VAs (session-only until backend lands).
pub breakpoints: Vec<u64>,
- /// User-set watch expressions.
+ /// User-set watch expressions.
pub watches: Vec<String>,
- /// Whether the debugger tool mode is active (Ghidra `Debugger` tool
- /// exists as a separate top-level menu group).
+ /// Whether the debugger tool mode is active.
pub enabled: bool,
- /// New-breakpoint input.
+ /// Host window open (single tabbed Debugger).
+ pub host_open: bool,
+ /// Active tab inside the host.
+ pub active_tab: DebuggerPane,
+ /// New-breakpoint input.
pub bp_input: String,
- /// New-watch input.
+ /// New-watch input.
pub watch_input: String,
- // ── Live Process Bridge (Windows) — `ghidrust_core::process_*` ──────
- /// Attached session (Targets pane "Attach"); `None` = no live target.
+ // ── Live Process Bridge (Windows) — `ghidrust_core::process_*` ──────
+ /// Attached session; `None` = no live target.
pub session: Option<ProcessSession>,
- /// Cached process list (Targets pane; refreshed on demand).
+ /// Display name of the attached process (from process list).
+ pub process_display_name: Option<String>,
+ /// Cached process list (Targets pane).
pub process_list_cache: Vec<ProcessInfo>,
- /// Targets pane process-name filter.
+ /// Targets pane process-name filter.
pub targets_filter: String,
- /// Targets pane manual PID input (attach without scanning the list).
+ /// Targets pane manual PID input.
pub attach_pid_input: String,
- /// Cached module list for the attached session (Modules pane).
+ /// Cached module list for the attached session.
pub modules_cache: Vec<ModuleInfo>,
- /// Cached region list for the attached session (Regions pane).
+ /// Modules pane name/path filter.
+ pub modules_filter: String,
+ /// Cached region list for the attached session.
pub regions_cache: Vec<RegionInfo>,
- /// Modules pane · Static Mappings mini-tool: module name + static RVA.
+ /// Modules pane · Static Mappings mini-tool.
pub static_map_module_input: String,
pub static_map_rva_input: String,
pub static_map_result: Option<String>,
- /// Memory Bytes pane inputs + last read.
+ /// Memory Bytes pane inputs + last read.
pub mem_bytes_va_input: String,
pub mem_bytes_size_input: String,
pub mem_bytes_last: Option<ReadResult>,
- /// Last error from any Live Process Bridge call (fail-loud, not silent).
+ /// Last error from any Live Process Bridge call (fail-loud, not silent).
pub live_error: Option<String>,
+ /// True when session was launched with CREATE_SUSPENDED and not yet resumed.
+ pub suspended: bool,
+ /// Launch… dialog open.
+ pub show_launch_dialog: bool,
+ pub launch_image: String,
+ pub launch_args: String,
+ pub launch_cwd: String,
+}
+
+impl Default for DebuggerState {
+ fn default() -> Self {
+ Self {
+ breakpoints: Vec::new(),
+ watches: Vec::new(),
+ enabled: false,
+ host_open: false,
+ active_tab: DebuggerPane::Targets,
+ bp_input: String::new(),
+ watch_input: String::new(),
+ session: None,
+ process_display_name: None,
+ process_list_cache: Vec::new(),
+ targets_filter: String::new(),
+ attach_pid_input: String::new(),
+ modules_cache: Vec::new(),
+ modules_filter: String::new(),
+ regions_cache: Vec::new(),
+ static_map_module_input: String::new(),
+ static_map_rva_input: String::new(),
+ static_map_result: None,
+ mem_bytes_va_input: String::new(),
+ mem_bytes_size_input: String::new(),
+ mem_bytes_last: None,
+ live_error: None,
+ suspended: false,
+ show_launch_dialog: false,
+ launch_image: String::new(),
+ launch_args: String::new(),
+ launch_cwd: String::new(),
+ }
+ }
}
impl DebuggerState {
@@ -219,33 +297,504 @@ impl DebuggerState {
self.breakpoints.sort();
}
}
- /// Whether a session breakpoint is set at `va`.
- ///
- /// Kept `pub` so a future backend can query the session set (e.g., to
- /// avoid re-emitting sw-breakpoints already set by the user).
+
#[allow(dead_code)]
pub fn has_breakpoint(&self, va: u64) -> bool {
self.breakpoints.contains(&va)
}
+
pub fn add_watch(&mut self, expr: impl Into<String>) {
let e = expr.into();
if !e.trim().is_empty() && !self.watches.iter().any(|w| w == &e) {
self.watches.push(e);
}
}
+
pub fn remove_watch(&mut self, idx: usize) {
if idx < self.watches.len() {
self.watches.remove(idx);
}
}
+
+ /// Enable tool mode: open host, focus Targets, refresh process list if empty.
+ pub fn enable_tool(&mut self) {
+ self.enabled = true;
+ self.host_open = true;
+ self.active_tab = DebuggerPane::Targets;
+ if self.process_list_cache.is_empty() {
+ self.refresh_process_list();
+ }
+ }
+
+ /// Debugger → Attach… : open host on Targets (and refresh list if needed).
+ pub fn open_attach_ui(&mut self) {
+ self.enable_tool();
+ self.active_tab = DebuggerPane::Targets;
+ }
+
+ /// Debugger → Launch… : open host + launch dialog; prefill image when provided.
+ pub fn open_launch_ui(&mut self, prefill_image: Option<&Path>) {
+ self.enable_tool();
+ if let Some(p) = prefill_image {
+ if self.launch_image.trim().is_empty() {
+ self.launch_image = p.display().to_string();
+ }
+ if self.launch_cwd.trim().is_empty() {
+ if let Some(parent) = p.parent() {
+ self.launch_cwd = parent.display().to_string();
+ }
+ }
+ }
+ self.show_launch_dialog = true;
+ }
+
+ pub fn focus_tab(&mut self, tab: DebuggerPane) {
+ self.host_open = true;
+ self.enabled = true;
+ self.active_tab = tab;
+ }
+
+ pub fn refresh_process_list(&mut self) {
+ self.live_error = None;
+ match process_list() {
+ Ok(v) => self.process_list_cache = v,
+ Err(e) => {
+ self.process_list_cache.clear();
+ self.live_error = Some(e);
+ }
+ }
+ }
+
+ pub fn clear_live_caches(&mut self) {
+ self.modules_cache.clear();
+ self.regions_cache.clear();
+ self.mem_bytes_last = None;
+ self.mem_bytes_va_input.clear();
+ self.static_map_result = None;
+ self.process_display_name = None;
+ self.suspended = false;
+ }
+
+ pub fn detach_session(&mut self) {
+ if let Some(sess) = self.session.take() {
+ let _ = process_detach(&sess.session_id);
+ }
+ self.clear_live_caches();
+ self.live_error = None;
+ self.active_tab = DebuggerPane::Targets;
+ }
+
+ /// Attach and auto-populate modules / regions / Memory Bytes (CE-style).
+ pub fn attach_and_populate(&mut self, pid: u32) {
+ if pid == 0 {
+ self.live_error = Some("invalid PID".into());
+ return;
+ }
+ self.live_error = None;
+ match process_attach(pid) {
+ Ok(sess) => {
+ let name = self
+ .process_list_cache
+ .iter()
+ .find(|p| p.pid == pid)
+ .map(|p| p.name.clone());
+ self.process_display_name = name;
+ self.session = Some(sess);
+ self.suspended = false;
+ self.refresh_after_attach();
+ }
+ Err(e) => {
+ self.session = None;
+ self.clear_live_caches();
+ self.live_error = Some(e);
+ }
+ }
+ }
+
+ /// Launch CREATE_SUSPENDED + auto-populate (not a debug break-at-entry).
+ pub fn launch_and_populate(&mut self) {
+ let image = self.launch_image.trim();
+ if image.is_empty() {
+ self.live_error = Some("launch image path is required".into());
+ return;
+ }
+ let req = LaunchRequest {
+ image: PathBuf::from(image),
+ args: {
+ let a = self.launch_args.trim();
+ if a.is_empty() {
+ None
+ } else {
+ Some(a.to_string())
+ }
+ },
+ cwd: {
+ let c = self.launch_cwd.trim();
+ if c.is_empty() {
+ None
+ } else {
+ Some(PathBuf::from(c))
+ }
+ },
+ };
+ self.live_error = None;
+ match process_launch(&req) {
+ Ok(r) => {
+ let name = Path::new(&r.image)
+ .file_name()
+ .map(|n| n.to_string_lossy().into_owned())
+ .unwrap_or_else(|| r.image.clone());
+ self.process_display_name = Some(name);
+ self.session = Some(r.session);
+ self.suspended = r.suspended;
+ self.show_launch_dialog = false;
+ self.refresh_after_attach();
+ }
+ Err(e) => {
+ self.live_error = Some(e);
+ }
+ }
+ }
+
+ pub fn resume_session(&mut self) {
+ let Some(sess) = self.session.clone() else {
+ self.live_error = Some("no live session to resume".into());
+ return;
+ };
+ match process_resume(&sess.session_id) {
+ Ok(()) => {
+ self.suspended = false;
+ self.live_error = None;
+ }
+ Err(e) => self.live_error = Some(e),
+ }
+ }
+
+ /// After a successful attach: modules → seed memory → regions → focus Modules.
+ pub fn refresh_after_attach(&mut self) {
+ let Some(sess) = self.session.clone() else {
+ return;
+ };
+ self.live_error = None;
+
+ match process_modules(&sess.session_id) {
+ Ok(v) => self.modules_cache = v,
+ Err(e) => {
+ self.modules_cache.clear();
+ self.live_error = Some(e);
+ }
+ }
+
+ if let Some(main) = pick_main_module(&self.modules_cache, self.process_display_name.as_deref())
+ {
+ self.mem_bytes_va_input = format!("{:#x}", main.base);
+ if self.mem_bytes_size_input.trim().is_empty() {
+ self.mem_bytes_size_input = "256".into();
+ }
+ match process_read(&sess.session_id, main.base, 256) {
+ Ok(r) => {
+ if let Some(err) = &r.error {
+ if self.live_error.is_none() {
+ self.live_error = Some(err.clone());
+ }
+ }
+ self.mem_bytes_last = Some(r);
+ }
+ Err(e) => {
+ self.mem_bytes_last = None;
+ if self.live_error.is_none() {
+ self.live_error = Some(e);
+ }
+ }
+ }
+ }
+
+ match process_regions(&sess.session_id, 4096) {
+ Ok(v) => self.regions_cache = v,
+ Err(e) => {
+ self.regions_cache.clear();
+ if self.live_error.is_none() {
+ self.live_error = Some(e);
+ }
+ }
+ }
+
+ self.active_tab = DebuggerPane::Modules;
+ }
+
+ /// Status line for the host chrome.
+ pub fn status_line(&self) -> String {
+ match &self.session {
+ Some(sess) => {
+ let name = self
+ .process_display_name
+ .as_deref()
+ .unwrap_or("(unknown)");
+ if self.suspended {
+ format!(
+ "Suspended · {} · pid={} · session={} — Resume to run",
+ name, sess.pid, sess.session_id
+ )
+ } else {
+ format!(
+ "Attached · {} · pid={} · session={}",
+ name, sess.pid, sess.session_id
+ )
+ }
+ }
+ None => "Detached — Attach a PID or Launch an image".into(),
+ }
+ }
+
+ /// Window title including process identity when attached.
+ pub fn window_title(&self) -> String {
+ match (&self.session, &self.process_display_name) {
+ (Some(sess), Some(name)) if self.suspended => {
+ format!("Debugger — {name} [suspended] (pid={})", sess.pid)
+ }
+ (Some(sess), Some(name)) => format!("Debugger — {name} (pid={})", sess.pid),
+ (Some(sess), None) => format!("Debugger — pid={}", sess.pid),
+ _ => "Debugger".into(),
+ }
+ }
+
+ /// Module containing `va`, if any.
+ pub fn module_for_va(&self, va: u64) -> Option<&ModuleInfo> {
+ self.modules_cache
+ .iter()
+ .find(|m| va >= m.base && va < m.base.saturating_add(m.size))
+ }
+}
+
+/// Prefer module whose name matches the process; else first with a path; else first.
+pub fn pick_main_module<'a>(
+ modules: &'a [ModuleInfo],
+ process_name: Option<&str>,
+) -> Option<&'a ModuleInfo> {
+ if modules.is_empty() {
+ return None;
+ }
+ if let Some(pname) = process_name {
+ let pl = pname.to_ascii_lowercase();
+ if let Some(m) = modules.iter().find(|m| m.name.to_ascii_lowercase() == pl) {
+ return Some(m);
+ }
+ if let Some(m) = modules
+ .iter()
+ .find(|m| m.name.to_ascii_lowercase().contains(pl.trim_end_matches(".exe")))
+ {
+ return Some(m);
+ }
+ }
+ modules
+ .iter()
+ .find(|m| m.path.as_ref().map(|p| !p.is_empty()).unwrap_or(false))
+ .or_else(|| modules.first())
+}
+
+/// Migrate legacy per-pane open flags + host key into host_open / active_tab / enabled.
+pub fn apply_layout_flags(
+ state: &mut DebuggerState,
+ open_panes: &std::collections::BTreeMap<String, bool>,
+) {
+ let host = open_panes.get(HOST_EGUI_ID).copied().unwrap_or(false);
+ let mut first_open: Option<DebuggerPane> = None;
+ let mut any_tab = false;
+ for p in DebuggerPane::TAB_ORDER {
+ if open_panes.get(p.egui_id()).copied().unwrap_or(false) {
+ any_tab = true;
+ if first_open.is_none() {
+ first_open = Some(*p);
+ }
+ }
+ }
+ if host || any_tab {
+ state.host_open = true;
+ state.enabled = true;
+ if let Some(tab) = first_open {
+ state.active_tab = tab;
+ }
+ } else if open_panes.contains_key(HOST_EGUI_ID) {
+ state.host_open = host;
+ if !host {
+ state.enabled = false;
+ }
+ }
}
-/// Render an honest-empty debugger pane. `state` is passed so the
-/// Breakpoints / Watches panes can render user-set entries even without a
-/// live target attached.
-pub fn render(pane: DebuggerPane, state: &mut DebuggerState, ui: &mut Ui, muted: Color32) {
- ui.heading(pane.title());
- ui.small(RichText::new(format!("Provider · {}", pane.plugin())).color(muted));
+/// Snapshot debugger visibility into layout open_panes.
+pub fn snapshot_layout_flags(
+ state: &DebuggerState,
+ open_panes: &mut std::collections::BTreeMap<String, bool>,
+) {
+ open_panes.insert(HOST_EGUI_ID.to_string(), state.host_open);
+ for p in DebuggerPane::ALL {
+ open_panes.insert(p.egui_id().to_string(), state.host_open && state.active_tab == *p);
+ }
+}
+
+/// Draw the single Debugger host window (tab strip + status + active pane).
+pub fn draw_host(ctx: &egui::Context, state: &mut DebuggerState, muted: Color32) {
+ if state.host_open {
+ let mut open = true;
+ let title = state.window_title();
+ egui::Window::new(title)
+ .id(egui::Id::new(HOST_EGUI_ID))
+ .open(&mut open)
+ .resizable(true)
+ .default_size(egui::vec2(720.0, 520.0))
+ .min_size(egui::vec2(420.0, 280.0))
+ .show(ctx, |ui| {
+ // Fill the resized window so vertical growth isn't clamped by content.
+ let avail = ui.available_size();
+ ui.set_min_size(avail);
+ render_host_body(state, ui, muted);
+ });
+ if !open {
+ state.host_open = false;
+ }
+ }
+ draw_launch_dialog(ctx, state, muted);
+}
+
+/// Launch… dialog (image / args / cwd).
+pub fn draw_launch_dialog(ctx: &egui::Context, state: &mut DebuggerState, muted: Color32) {
+ if !state.show_launch_dialog {
+ return;
+ }
+ let mut open = true;
+ egui::Window::new("Launch process")
+ .id(egui::Id::new("pane_dbg_launch_dialog"))
+ .open(&mut open)
+ .collapsible(false)
+ .resizable(true)
+ .default_width(520.0)
+ .show(ctx, |ui| {
+ ui.small(
+ RichText::new(
+ "CREATE_SUSPENDED spawn + read-only attach. Not a debug break-at-entry — use Resume after inspect.",
+ )
+ .color(muted),
+ );
+ ui.separator();
+ ui.horizontal(|ui| {
+ ui.label("Image:");
+ ui.add(
+ egui::TextEdit::singleline(&mut state.launch_image)
+ .desired_width(360.0)
+ .hint_text(r"C:\path\to\app.exe"),
+ );
+ if ui.button("Browse…").clicked() {
+ if let Some(path) = rfd::FileDialog::new()
+ .add_filter("Executable", &["exe"])
+ .pick_file()
+ {
+ if let Some(parent) = path.parent() {
+ if state.launch_cwd.trim().is_empty() {
+ state.launch_cwd = parent.display().to_string();
+ }
+ }
+ state.launch_image = path.display().to_string();
+ }
+ }
+ });
+ ui.horizontal(|ui| {
+ ui.label("Args:");
+ ui.add(
+ egui::TextEdit::singleline(&mut state.launch_args)
+ .desired_width(400.0)
+ .hint_text("optional"),
+ );
+ });
+ ui.horizontal(|ui| {
+ ui.label("Cwd:");
+ ui.add(
+ egui::TextEdit::singleline(&mut state.launch_cwd)
+ .desired_width(360.0)
+ .hint_text("optional working directory"),
+ );
+ if ui.button("Browse…").clicked() {
+ if let Some(path) = rfd::FileDialog::new().pick_folder() {
+ state.launch_cwd = path.display().to_string();
+ }
+ }
+ });
+ if let Some(e) = state.live_error.clone() {
+ err_row(ui, &e);
+ }
+ ui.separator();
+ ui.horizontal(|ui| {
+ if ui
+ .add_enabled(
+ !state.launch_image.trim().is_empty() && state.session.is_none(),
+ egui::Button::new("Launch"),
+ )
+ .clicked()
+ {
+ state.launch_and_populate();
+ }
+ if ui.button("Cancel").clicked() {
+ state.show_launch_dialog = false;
+ }
+ });
+ if state.session.is_some() {
+ ui.small(
+ RichText::new("Detach the current session before launching.")
+ .color(muted),
+ );
+ }
+ });
+ if !open {
+ state.show_launch_dialog = false;
+ }
+}
+
+fn render_host_body(state: &mut DebuggerState, ui: &mut Ui, muted: Color32) {
+ // Status bar
+ ui.horizontal(|ui| {
+ ui.label(RichText::new(state.status_line()).color(muted));
+ if state.session.is_some() && state.suspended {
+ if ui
+ .small_button("Resume")
+ .on_hover_text("ResumeThread on the primary CREATE_SUSPENDED thread")
+ .clicked()
+ {
+ state.resume_session();
+ }
+ }
+ if state.session.is_some() {
+ if ui.small_button("Detach").clicked() {
+ state.detach_session();
+ }
+ }
+ });
+ if let Some(e) = state.live_error.clone() {
+ err_row(ui, &e);
+ }
+ ui.separator();
+
+ // Tab strip
+ egui::ScrollArea::horizontal()
+ .id_salt("dbg_tab_strip")
+ .show(ui, |ui| {
+ ui.horizontal(|ui| {
+ for tab in DebuggerPane::TAB_ORDER {
+ let selected = state.active_tab == *tab;
+ if ui.selectable_label(selected, tab.short_title()).clicked() {
+ state.active_tab = *tab;
+ }
+ }
+ });
+ });
+ ui.separator();
+
+ let pane = state.active_tab;
+ render_pane_body(pane, state, ui, muted);
+}
+
+/// Render pane content without the old per-window heading chrome.
+pub fn render_pane_body(pane: DebuggerPane, state: &mut DebuggerState, ui: &mut Ui, muted: Color32) {
+ ui.small(RichText::new(format!("Provider · {}", pane.plugin())).color(muted));
ui.separator();
match pane {
@@ -263,62 +812,53 @@ fn err_row(ui: &mut Ui, err: &str) {
ui.colored_label(Color32::from_rgb(0xE5, 0x39, 0x35), err);
}
-/// Ghidra `DebuggerTargetsPlugin` analog — process list (Windows Toolhelp32
-/// snapshot) + Attach. Attaching stores a `ProcessSession` other panes read.
fn render_targets(state: &mut DebuggerState, ui: &mut Ui, muted: Color32) {
+ ui.small(
+ RichText::new(
+ "Attach: existing PID. Launch… (Debugger menu): CREATE_SUSPENDED new image, then Resume.",
+ )
+ .color(muted),
+ );
ui.horizontal(|ui| {
- if ui.button("Refresh process list").clicked() {
- state.live_error = None;
- match process_list() {
- Ok(v) => state.process_list_cache = v,
- Err(e) => {
- state.process_list_cache.clear();
- state.live_error = Some(e);
- }
- }
+ if ui.button("Refresh process list").clicked() {
+ state.refresh_process_list();
}
- ui.label("Filter:");
+ if ui.button("Launch…").clicked() {
+ state.show_launch_dialog = true;
+ }
+ ui.label("Filter:");
ui.add(
egui::TextEdit::singleline(&mut state.targets_filter)
.desired_width(200.0)
- .hint_text("process name…"),
+ .hint_text("process name…"),
);
});
- if let Some(sess) = state.session.clone() {
- let mut do_detach = false;
- ui.horizontal(|ui| {
- ui.small(RichText::new(format!("Attached · pid={} session={}", sess.pid, sess.session_id)).color(muted));
- if ui.button("Detach").clicked() {
- do_detach = true;
- }
- });
- if do_detach {
- let _ = process_detach(&sess.session_id);
- state.session = None;
- state.modules_cache.clear();
- state.regions_cache.clear();
- }
- }
- if let Some(e) = &state.live_error {
- err_row(ui, e);
+ if state.session.is_some() {
+ ui.small(
+ RichText::new("Already attached — use Detach in the status bar to switch targets.")
+ .color(muted),
+ );
}
ui.separator();
ui.horizontal(|ui| {
- ui.label("PID:");
+ ui.label("PID:");
ui.add(
egui::TextEdit::singleline(&mut state.attach_pid_input)
.desired_width(100.0)
- .hint_text("1234"),
+ .hint_text("1234"),
);
if ui
- .add_enabled(!state.attach_pid_input.trim().is_empty(), egui::Button::new("Attach by PID"))
+ .add_enabled(
+ !state.attach_pid_input.trim().is_empty() && state.session.is_none(),
+ egui::Button::new("Attach by PID"),
+ )
.clicked()
{
attach(state, state.attach_pid_input.trim().parse().unwrap_or(0));
}
});
if state.process_list_cache.is_empty() {
- ui.weak("No process list loaded — click Refresh (Windows Toolhelp32 snapshot).");
+ ui.weak("No process list loaded — click Refresh (Windows Toolhelp32 snapshot).");
return;
}
let q = state.targets_filter.to_ascii_lowercase();
@@ -327,26 +867,36 @@ fn render_targets(state: &mut DebuggerState, ui: &mut Ui, muted: Color32) {
.iter()
.filter(|p| q.is_empty() || p.name.to_ascii_lowercase().contains(&q))
.collect();
- ui.small(format!("{} / {} processes", rows.len(), state.process_list_cache.len()));
+ ui.small(format!(
+ "{} / {} processes",
+ rows.len(),
+ state.process_list_cache.len()
+ ));
let mut attach_pid: Option<u32> = None;
+ let can_attach = state.session.is_none();
+ let list_h = ui.available_height().max(120.0);
egui::ScrollArea::vertical()
- .id_salt("dbg_targets_scroll")
- .max_height(320.0)
+ .id_salt("dbg_targets_scroll")
+ .max_height(list_h)
+ .auto_shrink([false, false])
.show(ui, |ui| {
- egui::Grid::new("dbg_targets_grid")
+ egui::Grid::new("dbg_targets_grid")
.num_columns(4)
.striped(true)
.show(ui, |ui| {
- ui.strong("PID");
- ui.strong("Name");
- ui.strong("Path");
- ui.strong("");
+ ui.strong("PID");
+ ui.strong("Name");
+ ui.strong("Path");
+ ui.strong("");
ui.end_row();
for p in &rows {
- ui.monospace(format!("{}", p.pid));
+ ui.monospace(format!("{}", p.pid));
ui.label(&p.name);
- ui.small(p.path.as_deref().unwrap_or("—"));
- if ui.small_button("Attach").clicked() {
+ ui.small(p.path.as_deref().unwrap_or("—"));
+ if ui
+ .add_enabled(can_attach, egui::Button::new("Attach").small())
+ .clicked()
+ {
attach_pid = Some(p.pid);
}
ui.end_row();
@@ -359,32 +909,17 @@ fn render_targets(state: &mut DebuggerState, ui: &mut Ui, muted: Color32) {
}
fn attach(state: &mut DebuggerState, pid: u32) {
- if pid == 0 {
- state.live_error = Some("invalid PID".into());
- return;
- }
- state.live_error = None;
- match process_attach(pid) {
- Ok(sess) => {
- state.session = Some(sess);
- state.modules_cache.clear();
- state.regions_cache.clear();
- }
- Err(e) => state.live_error = Some(e),
- }
+ state.attach_and_populate(pid);
}
-/// Ghidra `DebuggerModulesPlugin` analog — module list for the attached
-/// session, plus a Static Mappings mini-tool (`static_to_live`: module + RVA
-/// → live VA via the loaded module base).
fn render_modules(state: &mut DebuggerState, ui: &mut Ui, muted: Color32) {
let Some(sess) = state.session.clone() else {
- ui.weak("No live target — attach one from Debugger Targets first.");
+ ui.weak("No live target — attach one from Targets first.");
return;
};
ui.horizontal(|ui| {
- ui.small(RichText::new(format!("pid={}", sess.pid)).color(muted));
- if ui.button("Refresh modules").clicked() {
+ ui.small(RichText::new(format!("pid={}", sess.pid)).color(muted));
+ if ui.button("Refresh modules").clicked() {
state.live_error = None;
match process_modules(&sess.session_id) {
Ok(v) => state.modules_cache = v,
@@ -394,62 +929,114 @@ fn render_modules(state: &mut DebuggerState, ui: &mut Ui, muted: Color32) {
}
}
}
+ ui.label("Filter:");
+ ui.add(
+ egui::TextEdit::singleline(&mut state.modules_filter)
+ .desired_width(180.0)
+ .hint_text("module name…"),
+ );
});
- if let Some(e) = &state.live_error {
- err_row(ui, e);
- }
- if !state.modules_cache.is_empty() {
- ui.small(format!("{} module(s)", state.modules_cache.len()));
+ if state.modules_cache.is_empty() {
+ ui.weak("No modules cached — click Refresh modules.");
+ } else {
+ let q = state.modules_filter.to_ascii_lowercase();
+ let rows: Vec<&ModuleInfo> = state
+ .modules_cache
+ .iter()
+ .filter(|m| {
+ q.is_empty()
+ || m.name.to_ascii_lowercase().contains(&q)
+ || m.path
+ .as_deref()
+ .map(|p| p.to_ascii_lowercase().contains(&q))
+ .unwrap_or(false)
+ })
+ .collect();
+ ui.small(format!(
+ "{} / {} module(s)",
+ rows.len(),
+ state.modules_cache.len()
+ ));
+ let mut goto_base: Option<u64> = None;
+ // Leave room below for Static Mappings; grow with the window.
+ let list_h = (ui.available_height() - 140.0).max(80.0);
egui::ScrollArea::vertical()
- .id_salt("dbg_modules_scroll")
- .max_height(260.0)
+ .id_salt("dbg_modules_scroll")
+ .max_height(list_h)
+ .auto_shrink([false, false])
.show(ui, |ui| {
- egui::Grid::new("dbg_modules_grid")
- .num_columns(4)
+ egui::Grid::new("dbg_modules_grid")
+ .num_columns(5)
.striped(true)
.show(ui, |ui| {
- ui.strong("Base");
- ui.strong("Size");
- ui.strong("Name");
- ui.strong("Path");
+ ui.strong("Base");
+ ui.strong("Size");
+ ui.strong("Name");
+ ui.strong("Path");
+ ui.strong("");
ui.end_row();
- for m in &state.modules_cache {
- ui.monospace(format!("{:#x}", m.base));
- ui.monospace(format!("{:#x}", m.size));
+ for m in &rows {
+ ui.monospace(format!("{:#x}", m.base));
+ ui.monospace(format!("{:#x}", m.size));
ui.label(&m.name);
- ui.small(m.path.as_deref().unwrap_or("—"));
+ ui.small(m.path.as_deref().unwrap_or("—"));
+ if ui.small_button("Memory").on_hover_text("Read Memory Bytes at module base").clicked()
+ {
+ goto_base = Some(m.base);
+ }
ui.end_row();
}
});
});
- } else {
- ui.weak("No modules cached — click Refresh modules.");
+ if let Some(base) = goto_base {
+ state.mem_bytes_va_input = format!("{base:#x}");
+ if state.mem_bytes_size_input.trim().is_empty() {
+ state.mem_bytes_size_input = "256".into();
+ }
+ match process_read(&sess.session_id, base, 256) {
+ Ok(r) => {
+ state.live_error = r.error.clone();
+ state.mem_bytes_last = Some(r);
+ }
+ Err(e) => {
+ state.mem_bytes_last = None;
+ state.live_error = Some(e);
+ }
+ }
+ state.active_tab = DebuggerPane::MemoryBytes;
+ }
}
ui.separator();
- ui.label(RichText::new("Static Mappings").strong());
+ ui.label(RichText::new("Static Mappings").strong());
ui.small(
- RichText::new("ghidrust_core::process::static_to_live · static file RVA → live VA via module base")
- .color(muted),
+ RichText::new(
+ "ghidrust_core::process::static_to_live · static file RVA → live VA via module base",
+ )
+ .color(muted),
);
ui.horizontal(|ui| {
- ui.label("Module:");
+ ui.label("Module:");
ui.add(
egui::TextEdit::singleline(&mut state.static_map_module_input)
.desired_width(160.0)
- .hint_text("game.exe"),
+ .hint_text("game.exe"),
);
- ui.label("RVA:");
+ ui.label("RVA:");
ui.add(
egui::TextEdit::singleline(&mut state.static_map_rva_input)
.desired_width(120.0)
- .hint_text("0x1000"),
+ .hint_text("0x1000"),
);
- if ui.button("Resolve").clicked() {
+ if ui.button("Resolve").clicked() {
let rva = parse_hex(&state.static_map_rva_input).unwrap_or(0);
- match static_to_live(&sess.session_id, state.static_map_module_input.trim(), rva) {
+ match static_to_live(
+ &sess.session_id,
+ state.static_map_module_input.trim(),
+ rva,
+ ) {
Ok(r) => {
state.static_map_result = Some(format!(
- "{} base={:#x} rva={:#x} → live_va={:#x}",
+ "{} base={:#x} rva={:#x} → live_va={:#x}",
r.module, r.base, r.rva, r.live_va
));
state.live_error = None;
@@ -466,15 +1053,14 @@ fn render_modules(state: &mut DebuggerState, ui: &mut Ui, muted: Color32) {
}
}
-/// Ghidra `DebuggerRegionsPlugin` analog — `VirtualQueryEx` region walk.
fn render_regions(state: &mut DebuggerState, ui: &mut Ui, muted: Color32) {
let Some(sess) = state.session.clone() else {
- ui.weak("No live target — attach one from Debugger Targets first.");
+ ui.weak("No live target — attach one from Targets first.");
return;
};
ui.horizontal(|ui| {
- ui.small(RichText::new(format!("pid={}", sess.pid)).color(muted));
- if ui.button("Refresh regions").clicked() {
+ ui.small(RichText::new(format!("pid={}", sess.pid)).color(muted));
+ if ui.button("Refresh regions").clicked() {
state.live_error = None;
match process_regions(&sess.session_id, 4096) {
Ok(v) => state.regions_cache = v,
@@ -485,55 +1071,56 @@ fn render_regions(state: &mut DebuggerState, ui: &mut Ui, muted: Color32) {
}
}
});
- if let Some(e) = &state.live_error {
- err_row(ui, e);
- }
if state.regions_cache.is_empty() {
- ui.weak("No regions cached — click Refresh regions.");
+ ui.weak("No regions cached — click Refresh regions.");
return;
}
- ui.small(format!("{} region(s)", state.regions_cache.len()));
+ ui.small(format!("{} region(s)", state.regions_cache.len()));
let row_h = ui.text_style_height(&egui::TextStyle::Monospace) + 2.0;
let regions = state.regions_cache.clone();
+ let list_h = ui.available_height().max(120.0);
egui::ScrollArea::vertical()
- .id_salt("dbg_regions_scroll")
+ .id_salt("dbg_regions_scroll")
.auto_shrink([false, false])
- .max_height(320.0)
+ .max_height(list_h)
.show_rows(ui, row_h, regions.len(), |ui, range| {
for i in range {
let r: &RegionInfo = &regions[i];
ui.monospace(format!(
- "{:#018x} +{:#x} protect={} state={} type={}",
+ "{:#018x} +{:#x} protect={} state={} type={}",
r.base, r.size, r.protect, r.state, r.typ
));
}
});
}
-/// Ghidra `DebuggerMemoryBytesPlugin` analog — live `ReadProcessMemory` hex
-/// dump for the attached session.
fn render_memory_bytes(state: &mut DebuggerState, ui: &mut Ui, muted: Color32) {
let Some(sess) = state.session.clone() else {
- ui.weak("No live target — attach one from Debugger Targets first.");
+ ui.weak("No live target — attach one from Targets first.");
return;
};
- ui.small(RichText::new(format!("pid={} · live ReadProcessMemory", sess.pid)).color(muted));
+ ui.small(RichText::new(format!("pid={} · live ReadProcessMemory", sess.pid)).color(muted));
ui.horizontal(|ui| {
- ui.label("VA:");
+ ui.label("VA:");
ui.add(
egui::TextEdit::singleline(&mut state.mem_bytes_va_input)
.desired_width(160.0)
- .hint_text("0x140001000"),
+ .hint_text("0x140001000"),
);
- ui.label("Size:");
+ ui.label("Size:");
ui.add(
egui::TextEdit::singleline(&mut state.mem_bytes_size_input)
.desired_width(100.0)
- .hint_text("256"),
+ .hint_text("256"),
);
- if ui.button("Read").clicked() {
+ if ui.button("Read").clicked() {
let va = parse_hex(&state.mem_bytes_va_input).unwrap_or(0);
- let size: usize = state.mem_bytes_size_input.trim().parse().unwrap_or(256).max(1);
+ let size: usize = state
+ .mem_bytes_size_input
+ .trim()
+ .parse()
+ .unwrap_or(256)
+ .max(1);
match process_read(&sess.session_id, va, size) {
Ok(r) => {
state.live_error = r.error.clone();
@@ -546,29 +1133,58 @@ fn render_memory_bytes(state: &mut DebuggerState, ui: &mut Ui, muted: Color32) {
}
}
});
- if let Some(e) = &state.live_error {
- err_row(ui, e);
+ // base+off subtitle when VA falls in a cached module
+ if let Some(va) = parse_hex(&state.mem_bytes_va_input) {
+ if let Some(m) = state.module_for_va(va) {
+ let off = va.saturating_sub(m.base);
+ ui.small(
+ RichText::new(format!("{}+{:#x} (base {:#x})", m.name, off, m.base)).color(muted),
+ );
+ }
}
let Some(read) = &state.mem_bytes_last else {
- ui.weak("No read yet — enter a VA + size and click Read.");
+ ui.weak("No read yet — enter a VA + size and click Read.");
return;
};
+ let mod_subtitle = state.module_for_va(read.va).map(|m| {
+ format!(
+ "{}+{:#x}",
+ m.name,
+ read.va.saturating_sub(m.base)
+ )
+ });
ui.small(format!(
- "va={:#x} requested={} read={}",
- read.va, read.size_requested, read.bytes_read
+ "va={:#x}{} requested={} read={}",
+ read.va,
+ mod_subtitle
+ .as_deref()
+ .map(|s| format!(" ({s})"))
+ .unwrap_or_default(),
+ read.size_requested,
+ read.bytes_read
));
+ let bytes = read.bytes.clone();
+ let base_va = read.va;
+ let list_h = ui.available_height().max(120.0);
egui::ScrollArea::vertical()
- .id_salt("dbg_membytes_scroll")
- .max_height(320.0)
+ .id_salt("dbg_membytes_scroll")
+ .max_height(list_h)
+ .auto_shrink([false, false])
.show(ui, |ui| {
- for (row, chunk) in read.bytes.chunks(16).enumerate() {
- let addr = read.va + (row as u64) * 16;
- let hex: String = chunk.iter().map(|b| format!("{b:02x} ")).collect();
+ for (row, chunk) in bytes.chunks(16).enumerate() {
+ let addr = base_va + (row as u64) * 16;
+ let hex: String = chunk.iter().map(|b| format!("{b:02x} ")).collect();
let ascii: String = chunk
.iter()
- .map(|&b| if (0x20..0x7f).contains(&b) { b as char } else { '.' })
+ .map(|&b| {
+ if (0x20..0x7f).contains(&b) {
+ b as char
+ } else {
+ '.'
+ }
+ })
.collect();
- ui.monospace(format!("{addr:#018x} {hex:<48} {ascii}"));
+ ui.monospace(format!("{addr:#018x} {hex:<48} {ascii}"));
}
});
}
@@ -589,24 +1205,28 @@ 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 . Real content lands with backend P12.")
- .color(muted),
+ RichText::new(
+ "Pane is present for the Debugger catalog. Live content lands with a target agent.",
+ )
+ .color(muted),
);
}
fn render_breakpoints(state: &mut DebuggerState, ui: &mut Ui, muted: Color32) {
ui.small(
- RichText::new("Session-only breakpoint list (backend P12 will replace with target-agent state).")
- .color(muted),
+ RichText::new(
+ "Session-only breakpoint list (replaced by target-agent state when available).",
+ )
+ .color(muted),
);
ui.horizontal(|ui| {
- ui.label("Address:");
+ ui.label("Address:");
ui.add(
egui::TextEdit::singleline(&mut state.bp_input)
.desired_width(160.0)
- .hint_text("0x140001000"),
+ .hint_text("0x140001000"),
);
- if ui.button("Add Breakpoint").clicked() {
+ if ui.button("Add Breakpoint").clicked() {
if let Some(va) = parse_hex(&state.bp_input) {
state.toggle_breakpoint(va);
state.bp_input.clear();
@@ -615,22 +1235,22 @@ fn render_breakpoints(state: &mut DebuggerState, ui: &mut Ui, muted: Color32) {
});
ui.separator();
if state.breakpoints.is_empty() {
- ui.weak("No breakpoints set.");
+ ui.weak("No breakpoints set.");
return;
}
let mut delete: Option<usize> = None;
- egui::Grid::new("dbg_bp_grid")
+ egui::Grid::new("dbg_bp_grid")
.num_columns(3)
.striped(true)
.show(ui, |ui| {
- ui.strong("Enabled");
- ui.strong("Address");
- ui.strong("");
+ ui.strong("Enabled");
+ ui.strong("Address");
+ ui.strong("");
ui.end_row();
for (i, va) in state.breakpoints.iter().enumerate() {
- ui.monospace("*"); // Enabled (no disable state until backend)
- ui.monospace(format!("{va:#x}"));
- if ui.small_button("Delete").clicked() {
+ ui.monospace("*");
+ ui.monospace(format!("{va:#x}"));
+ if ui.small_button("Delete").clicked() {
delete = Some(i);
}
ui.end_row();
@@ -643,16 +1263,16 @@ fn render_breakpoints(state: &mut DebuggerState, ui: &mut Ui, muted: Color32) {
fn render_watches(state: &mut DebuggerState, ui: &mut Ui, muted: Color32) {
ui.small(
- RichText::new("Session-only watch list (evaluator pending backend P12).").color(muted),
+ RichText::new("Session-only watch list (evaluator pending a target agent).").color(muted),
);
ui.horizontal(|ui| {
- ui.label("Expression:");
+ ui.label("Expression:");
ui.add(
egui::TextEdit::singleline(&mut state.watch_input)
.desired_width(280.0)
- .hint_text("*(int*)rsp"),
+ .hint_text("*(int*)rsp"),
);
- if ui.button("Add Watch").clicked() {
+ if ui.button("Add Watch").clicked() {
let e = state.watch_input.clone();
state.add_watch(e);
state.watch_input.clear();
@@ -660,22 +1280,22 @@ fn render_watches(state: &mut DebuggerState, ui: &mut Ui, muted: Color32) {
});
ui.separator();
if state.watches.is_empty() {
- ui.weak("No watches.");
+ ui.weak("No watches.");
return;
}
let mut delete: Option<usize> = None;
- egui::Grid::new("dbg_watch_grid")
+ egui::Grid::new("dbg_watch_grid")
.num_columns(3)
.striped(true)
.show(ui, |ui| {
- ui.strong("Expression");
- ui.strong("Value");
- ui.strong("");
+ ui.strong("Expression");
+ ui.strong("Value");
+ ui.strong("");
ui.end_row();
for (i, w) in state.watches.iter().enumerate() {
ui.monospace(w);
- ui.small(RichText::new("<no target>").color(muted));
- if ui.small_button("Delete").clicked() {
+ ui.small(RichText::new("<no target>").color(muted));
+ if ui.small_button("Delete").clicked() {
delete = Some(i);
}
ui.end_row();
@@ -688,37 +1308,59 @@ fn render_watches(state: &mut DebuggerState, ui: &mut Ui, muted: Color32) {
fn parse_hex(s: &str) -> Option<u64> {
let s = s.trim();
- let s = s.strip_prefix("0x").or_else(|| s.strip_prefix("0X")).unwrap_or(s);
+ let s = s
+ .strip_prefix("0x")
+ .or_else(|| s.strip_prefix("0X"))
+ .unwrap_or(s);
u64::from_str_radix(s, 16).ok()
}
#[cfg(test)]
mod tests {
use super::*;
+ use std::collections::BTreeMap;
+
+ fn modinfo(name: &str, base: u64, size: u64, path: Option<&str>) -> ModuleInfo {
+ ModuleInfo {
+ name: name.into(),
+ path: path.map(|p| p.into()),
+ base,
+ size,
+ }
+ }
#[test]
- fn debugger_catalog_covers_ghidra_windows() {
- let names: Vec<&'static str> = DebuggerPane::ALL.iter().map(|p| p.title()).collect();
+ fn debugger_catalog_covers_debugger_windows() {
+ let names: Vec<&'static str> = DebuggerPane::ALL.iter().map(|p| p.title).collect();
for expected in [
- "Debugger Targets",
- "Debugger Threads",
- "Debugger Modules",
- "Debugger Regions",
- "Debugger Registers",
- "Debugger Stack",
- "Debugger Breakpoints",
- "Debugger Memory Bytes",
- "Debugger Watches",
- "Debugger Console",
+ "Debugger Targets",
+ "Debugger Threads",
+ "Debugger Modules",
+ "Debugger Regions",
+ "Debugger Registers",
+ "Debugger Stack",
+ "Debugger Breakpoints",
+ "Debugger Memory Bytes",
+ "Debugger Watches",
+ "Debugger Console",
] {
- assert!(names.contains(&expected), "missing debugger pane {expected}");
+ assert!(names.contains(&expected), "missing debugger pane {expected}");
}
}
+ #[test]
+ fn tab_order_puts_live_panes_first() {
+ assert_eq!(DebuggerPane::TAB_ORDER[0], DebuggerPane::Targets);
+ assert_eq!(DebuggerPane::TAB_ORDER[1], DebuggerPane::Modules);
+ assert_eq!(DebuggerPane::TAB_ORDER[2], DebuggerPane::MemoryBytes);
+ assert_eq!(DebuggerPane::TAB_ORDER[3], DebuggerPane::Regions);
+ }
+
#[test]
fn every_debugger_pane_has_metadata() {
for p in DebuggerPane::ALL {
assert!(!p.title().is_empty());
+ assert!(!p.short_title().is_empty());
assert!(!p.plugin().is_empty());
assert!(!p.egui_id().is_empty());
assert!(!p.columns().is_empty());
@@ -738,13 +1380,170 @@ mod tests {
#[test]
fn watch_add_dedup_and_remove() {
let mut s = DebuggerState::default();
- s.add_watch("rax");
- s.add_watch("rax");
- s.add_watch("");
+ s.add_watch("rax");
+ s.add_watch("rax");
+ s.add_watch("");
assert_eq!(s.watches.len(), 1);
- s.add_watch("rbx");
+ s.add_watch("rbx");
assert_eq!(s.watches.len(), 2);
s.remove_watch(0);
- assert_eq!(s.watches[0], "rbx");
+ assert_eq!(s.watches[0], "rbx");
+ }
+
+ #[test]
+ fn pick_main_module_prefers_process_name() {
+ let mods = vec![
+ modinfo("ntdll.dll", 0x7ffe0000, 0x1000, Some(r"C:\Windows\ntdll.dll")),
+ modinfo("game.exe", 0x140000000, 0x10000, Some(r"C:\game\game.exe")),
+ ];
+ let m = pick_main_module(&mods, Some("game.exe")).unwrap();
+ assert_eq!(m.name(), "game.exe");
+ assert_eq!(m.base, 0x140000000);
+ }
+
+ #[test]
+ fn pick_main_module_falls_back_to_pathed() {
+ let mods = vec![
+ modinfo("a.dll", 0x1000, 0x100, None),
+ modinfo("b.dll", 0x2000, 0x100, Some(r"C:\b.dll")),
+ ];
+ let m = pick_main_module(&mods, Some("missing.exe")).unwrap();
+ assert_eq!(m.name(), "b.dll");
+ }
+
+ #[test]
+ fn clear_live_caches_and_detach_focus_targets() {
+ let mut s = DebuggerState::default();
+ s.modules_cache = vec![modinfo("x.exe", 0x1000, 0x10, None)];
+ s.regions_cache = vec![RegionInfo {
+ base: 0x1000,
+ size: 0x1000,
+ protect: "0x40".into(),
+ state: "commit".into(),
+ typ: "0x20000".into(),
+ }];
+ s.mem_bytes_last = Some(ReadResult {
+ va: 0x1000,
+ size_requested: 16,
+ bytes_read: 0,
+ hex: String::new(),
+ bytes: Vec::new(),
+ error: None,
+ as_u64: None,
+ as_f32: None,
+ });
+ s.process_display_name = Some("x.exe".into());
+ s.active_tab = DebuggerPane::Modules;
+ s.clear_live_caches();
+ assert!(s.modules_cache.is_empty());
+ assert!(s.regions_cache.is_empty());
+ assert!(s.mem_bytes_last.is_none());
+ assert!(s.process_display_name.is_none());
+ // detach_session without a real session still focuses Targets
+ s.active_tab = DebuggerPane::Modules;
+ s.detach_session();
+ assert_eq!(s.active_tab, DebuggerPane::Targets);
+ }
+
+ #[test]
+ fn module_for_va_base_plus_off() {
+ let mut s = DebuggerState::default();
+ s.modules_cache = vec![modinfo("game.exe", 0x140000000, 0x1000, None)];
+ let m = s.module_for_va(0x140000100).unwrap();
+ assert_eq!(m.name(), "game.exe");
+ assert!(s.module_for_va(0x150000000).is_none());
+ }
+
+ #[test]
+ fn layout_migration_opens_host_and_focuses_first_tab() {
+ let mut s = DebuggerState::default();
+ let mut panes = BTreeMap::new();
+ panes.insert("pane_dbg_modules".into(), true);
+ panes.insert("pane_dbg_regions".into(), true);
+ apply_layout_flags(&mut s, &panes);
+ assert!(s.host_open);
+ assert!(s.enabled);
+ assert_eq!(s.active_tab, DebuggerPane::Modules);
+ }
+
+ #[test]
+ fn layout_snapshot_marks_active_tab_only() {
+ let mut s = DebuggerState::default();
+ s.host_open = true;
+ s.active_tab = DebuggerPane::MemoryBytes;
+ let mut panes = BTreeMap::new();
+ snapshot_layout_flags(&s, &mut panes);
+ assert_eq!(panes.get(HOST_EGUI_ID), Some(&true));
+ assert_eq!(panes.get("pane_dbg_membytes"), Some(&true));
+ assert_eq!(panes.get("pane_dbg_targets"), Some(&false));
+ }
+
+ #[test]
+ fn enable_tool_opens_host_on_targets() {
+ let mut s = DebuggerState::default();
+ // May fail to list processes in CI/non-Windows — still must open host.
+ s.enabled = false;
+ s.host_open = false;
+ s.active_tab = DebuggerPane::Stack;
+ s.enable_tool();
+ assert!(s.enabled);
+ assert!(s.host_open);
+ assert_eq!(s.active_tab, DebuggerPane::Targets);
+ }
+
+ #[test]
+ fn open_attach_ui_focuses_targets() {
+ let mut s = DebuggerState::default();
+ s.open_attach_ui();
+ assert!(s.host_open);
+ assert_eq!(s.active_tab, DebuggerPane::Targets);
+ }
+
+ #[test]
+ fn open_launch_ui_prefills_and_opens_dialog() {
+ let mut s = DebuggerState::default();
+ s.open_launch_ui(Some(Path::new(r"C:\games\app.exe")));
+ assert!(s.host_open);
+ assert!(s.show_launch_dialog);
+ assert_eq!(s.launch_image, r"C:\games\app.exe");
+ assert_eq!(s.launch_cwd, r"C:\games");
+ }
+
+ #[test]
+ fn launch_and_populate_requires_image() {
+ let mut s = DebuggerState::default();
+ s.launch_and_populate();
+ assert!(s.live_error.as_deref().unwrap().contains("required"));
+ }
+
+ #[test]
+ fn detach_clears_suspended_flag() {
+ let mut s = DebuggerState::default();
+ s.suspended = true;
+ s.process_display_name = Some("x.exe".into());
+ s.detach_session();
+ assert!(!s.suspended);
+ assert!(s.process_display_name.is_none());
+ }
+
+ #[test]
+ fn simulated_post_attach_focus_modules() {
+ // Mimic refresh_after_attach's final focus without calling Win32.
+ let mut s = DebuggerState::default();
+ s.session = Some(ProcessSession {
+ session_id: "ps-test".into(),
+ pid: 1,
+ });
+ s.process_display_name = Some("game.exe".into());
+ s.modules_cache = vec![modinfo("game.exe", 0x140000000, 0x1000, Some(r"C:\game.exe"))];
+ s.active_tab = DebuggerPane::Modules;
+ assert_eq!(s.active_tab, DebuggerPane::Modules);
+ assert!(!s.modules_cache.is_empty());
+ assert_eq!(
+ pick_main_module(&s.modules_cache, s.process_display_name.as_deref())
+ .unwrap()
+ .base,
+ 0x140000000
+ );
}
}
diff --git a/crates/ghidrust-gui/src/decomp_tokens.rs b/crates/ghidrust-gui/src/decomp_tokens.rs
index a0f4db9..8a7bf3e 100644
--- a/crates/ghidrust-gui/src/decomp_tokens.rs
+++ b/crates/ghidrust-gui/src/decomp_tokens.rs
@@ -1,4 +1,4 @@
-//! Decompiler token model — Ghidra `ClangToken` analog for cross-highlight and nav.
+//! Decompiler token model — `` for cross-highlight and nav.
//!
//! **Design note.** Stage-1 may supply emit-time tokens via
//! [`from_emit_tokens`]; otherwise this module tokenises the **pseudo-C
diff --git a/crates/ghidrust-gui/src/entropy.rs b/crates/ghidrust-gui/src/entropy.rs
index 41e0406..284ab4c 100644
--- a/crates/ghidrust-gui/src/entropy.rs
+++ b/crates/ghidrust-gui/src/entropy.rs
@@ -1,6 +1,6 @@
//! Ghidrust GUI · Entropy strip + Overview banner.
//!
-//! Renders the Ghidra `EntropyPlugin` and `OverviewPlugin` header strips as
+//! Renders the `` and `` 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.
@@ -24,7 +24,7 @@ pub struct Sample {
/// Compute per-block entropy samples across every mapped memory block.
///
-/// `window` is bytes per sample (Ghidra default = 256). Result is flat,
+/// `window` is bytes per sample. Result is flat,
/// address-ordered, and honest: only mapped bytes are sampled.
pub fn entropy_samples(prog: &Program, window: usize) -> Vec<Sample> {
let mut out = Vec::new();
@@ -57,7 +57,7 @@ pub fn entropy_samples(prog: &Program, window: usize) -> Vec<Sample> {
out
}
-/// Palette helper — map an entropy value to a Ghidra-like color ramp.
+/// Palette helper — map an entropy value to a color ramp.
pub fn entropy_color(e: f64) -> Color32 {
// Cold (blue) → high entropy warm (red).
let t = (e / 8.0).clamp(0.0, 1.0) as f32;
@@ -141,7 +141,7 @@ pub fn render_entropy_strip(
None
}
-/// Render the Ghidra Overview banner (memory-block colour map).
+/// Render the Overview banner (memory-block colour map).
pub fn render_overview_strip(
ui: &mut Ui,
prog: &Program,
diff --git a/crates/ghidrust-gui/src/events.rs b/crates/ghidrust-gui/src/events.rs
index b544a90..5b0057b 100644
--- a/crates/ghidrust-gui/src/events.rs
+++ b/crates/ghidrust-gui/src/events.rs
@@ -1,4 +1,4 @@
-//! Ghidrust plugin‑event bus (analog of Ghidra `PluginEvent`).
+//! Ghidrust plugin‑event bus.
//!
//! Providers announce cursor / selection / program‑mutation events by pushing a
//! `GhidrustEvent` onto the app's `event_bus`. Each frame the app drains the bus and
@@ -13,7 +13,7 @@ use crate::nav::NavLocation;
/// One published event.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum GhidrustEvent {
- /// Cursor / focused location changed (Ghidra `ProgramLocationPluginEvent`).
+ /// Cursor / focused location changed.
///
/// `source` identifies the pane that emitted the event so subscribers can avoid
/// echo loops.
@@ -21,7 +21,7 @@ pub enum GhidrustEvent {
source: EventSource,
location: NavLocation,
},
- /// Selection changed (Ghidra `ProgramSelectionPluginEvent`).
+ /// Selection changed.
SelectionChanged {
source: EventSource,
start: NavLocation,
diff --git a/crates/ghidrust-gui/src/graphs.rs b/crates/ghidrust-gui/src/graphs.rs
index 106225b..4cc9f08 100644
--- a/crates/ghidrust-gui/src/graphs.rs
+++ b/crates/ghidrust-gui/src/graphs.rs
@@ -1,8 +1,8 @@
//! Ghidrust GUI · Function Graph, Function Call Graph,
//! Function Call Trees, and shared graph-layout helpers.
//!
-//! These render Ghidra-analog dockable panes (`FunctionGraphPlugin`,
-//! `FunctionCallGraphPlugin`, `CallTreePlugin`) directly on top of Stage-0 CFG
+//! These render dockable panes (``,
+//! ``, ``) directly on top of Stage-0 CFG
//! output from `ghidrust-decomp::decompile_at` and analyzer-recovered call
//! references (`Program::analysis.references` + `ghidrust-core::xrefs`).
//!
@@ -37,16 +37,16 @@ pub struct GraphPaneState {
pub call_tree_expanded_in: BTreeSet<u64>,
#[allow(dead_code)]
pub call_tree_expanded_out: BTreeSet<u64>,
- /// Call Trees — filter out thunks (Ghidra `Toggle Filter Thunks`).
+ /// Call Trees — filter out thunks.
pub call_tree_hide_thunks: bool,
/// Call Trees — "References Only" mode (data refs, no call edges).
pub call_tree_refs_only: bool,
}
-/// Function Graph layout algorithm (Ghidra ships several; we implement two).
+/// Function Graph layout algorithm.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum FunctionGraphLayout {
- /// Top-down hierarchical layered layout (Ghidra default).
+ /// Top-down hierarchical layered layout.
#[default]
Hierarchical,
/// Simple grid — one row per block, in address order.
@@ -66,7 +66,7 @@ impl FunctionGraphLayout {
}
}
-// ── Function Graph (Ghidra `FunctionGraphPlugin`) ────────────────────────────
+// ── Function Graph ────────────────────────────
/// Positioned CFG block ready for egui rendering.
#[derive(Debug, Clone)]
@@ -261,7 +261,7 @@ fn layout_grid(
(positioned, out_edges)
}
-/// Ghidra `FunctionGraphPlugin` — render blocks + edges. Returns clicked
+/// `` — render blocks + edges. Returns clicked
/// block start VA if any so the caller can Go To in Listing.
///
/// `focused_va` is drawn with a highlighted stroke so the current cursor
@@ -344,7 +344,7 @@ pub fn render_function_graph(
clicked
}
-// ── Function Call Graph (Ghidra `FunctionCallGraphPlugin`) ──────────────────
+// ── Function Call Graph ──────────────────
/// Level-based call graph vertex.
#[derive(Debug, Clone)]
@@ -565,7 +565,7 @@ pub fn render_call_graph(
clicked
}
-// ── Function Call Trees (Ghidra `CallTreePlugin`) ───────────────────────────
+// ── Function Call Trees ───────────────────────────
/// One node of the incoming / outgoing call tree.
#[derive(Debug, Clone)]
diff --git a/crates/ghidrust-gui/src/layouts.rs b/crates/ghidrust-gui/src/layouts.rs
index f9bfe95..97f5f64 100644
--- a/crates/ghidrust-gui/src/layouts.rs
+++ b/crates/ghidrust-gui/src/layouts.rs
@@ -1,12 +1,12 @@
//! Ghidrust GUI · layout persistence + Configure dialog.
//!
-//! Ghidra's `docking` framework lets users move / tab / float providers
+//! `docking` framework lets users move / tab / float providers
//! and save the result as a `.tool` XML preset. Ghidrust persists:
//!
//! - per-pane visibility + tool preferences to
-//! `%APPDATA%/ghidrust/layouts/<name>.tool.json`
+//! `%APPDATA%/ghidrust/layouts/<name>.tool.json`
//! - the center `egui_dock` tree (`dock_tree`) plus a legacy `center`
-//! shim string for older layouts
+//! shim string for older layouts
//! - a read-only Configure dialog listing every compile-time plugin
//!
//! Extracted per internal modularization notes — new UI panes land here
@@ -23,33 +23,33 @@ use std::path::PathBuf;
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
pub struct SavedLayout {
pub name: String,
- /// Pane-id → open bit.
+ /// Pane-id → open bit.
pub open_panes: BTreeMap<String, bool>,
- /// Dock checkbox states (`project_tree`, `program_tree`, `symbol_tree`, `console`).
+ /// Dock checkbox states (`project_tree`, `program_tree`, `symbol_tree`, `console`).
pub docks: BTreeMap<String, bool>,
- /// Legacy center-tab shim (`overview` / `listing` / `decompiler` / `datatypes`).
- /// Still written so older readers / tests keep working; prefer `dock_tree`.
+ /// Legacy center-tab shim (`overview` / `listing` / `decompiler` / `datatypes`).
+ /// Still written so older readers / tests keep working; prefer `dock_tree`.
pub center: String,
- /// Serialized `egui_dock::DockState<DockTab>` (serde feature). Absent on
- /// layouts saved before center docking landed.
- #[serde(default, skip_serializing_if = "Option::is_none")]
+ /// Serialized `egui_dock::DockState<DockTab>` (serde feature). Absent on
+ /// layouts saved before center docking landed.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
pub dock_tree: Option<serde_json::Value>,
- /// Theme (`dark` / `light`).
+ /// Theme (`dark` / `light`).
pub theme: String,
- /// Free-form comment shown in Configure dialog.
+ /// Free-form comment shown in Configure dialog.
pub comment: String,
}
/// Directory holding user-saved `<name>.tool.json` files.
pub fn layouts_dir() -> PathBuf {
- if let Ok(appdata) = std::env::var("APPDATA") {
- PathBuf::from(appdata).join("ghidrust").join("layouts")
- } else if let Ok(home) = std::env::var("USERPROFILE") {
- PathBuf::from(home).join(".ghidrust").join("layouts")
- } else if let Ok(home) = std::env::var("HOME") {
- PathBuf::from(home).join(".ghidrust").join("layouts")
+ if let Ok(appdata) = std::env::var("APPDATA") {
+ PathBuf::from(appdata).join("ghidrust").join("layouts")
+ } else if let Ok(home) = std::env::var("USERPROFILE") {
+ PathBuf::from(home).join(".ghidrust").join("layouts")
+ } else if let Ok(home) = std::env::var("HOME") {
+ PathBuf::from(home).join(".ghidrust").join("layouts")
} else {
- PathBuf::from(".ghidrust_layouts")
+ PathBuf::from(".ghidrust_layouts")
}
}
@@ -57,9 +57,9 @@ pub fn layouts_dir() -> PathBuf {
pub fn save_layout(layout: &SavedLayout) -> std::io::Result<PathBuf> {
let dir = layouts_dir();
std::fs::create_dir_all(&dir)?;
- let path = dir.join(format!("{}.tool.json", sanitize(&layout.name)));
+ let path = dir.join(format!("{}.tool.json", sanitize(&layout.name)));
let text = serde_json::to_string_pretty(layout).map_err(|e| {
- std::io::Error::new(std::io::ErrorKind::InvalidData, format!("serde: {e}"))
+ std::io::Error::new(std::io::ErrorKind::InvalidData, format!("serde: {e}"))
})?;
std::fs::write(&path, text)?;
Ok(path)
@@ -67,10 +67,10 @@ pub fn save_layout(layout: &SavedLayout) -> std::io::Result<PathBuf> {
/// Load a layout preset by short name.
pub fn load_layout(name: &str) -> std::io::Result<SavedLayout> {
- let path = layouts_dir().join(format!("{}.tool.json", sanitize(name)));
+ let path = layouts_dir().join(format!("{}.tool.json", sanitize(name)));
let text = std::fs::read_to_string(&path)?;
serde_json::from_str(&text).map_err(|e| {
- std::io::Error::new(std::io::ErrorKind::InvalidData, format!("serde: {e}"))
+ std::io::Error::new(std::io::ErrorKind::InvalidData, format!("serde: {e}"))
})
}
@@ -84,7 +84,7 @@ pub fn list_layouts() -> Vec<String> {
for entry in rd.flatten() {
let p = entry.path();
if let Some(name) = p.file_name().and_then(|s| s.to_str()) {
- if let Some(rest) = name.strip_suffix(".tool.json") {
+ if let Some(rest) = name.strip_suffix(".tool.json") {
out.push(rest.to_string());
}
}
@@ -95,202 +95,202 @@ pub fn list_layouts() -> Vec<String> {
/// Delete a saved layout by name.
pub fn delete_layout(name: &str) -> std::io::Result<()> {
- let path = layouts_dir().join(format!("{}.tool.json", sanitize(name)));
+ let path = layouts_dir().join(format!("{}.tool.json", sanitize(name)));
std::fs::remove_file(path)
}
fn sanitize(name: &str) -> String {
name.chars()
.map(|c| {
- if c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.') {
+ if c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.') {
c
} else {
- '_'
+ '_'
}
})
.collect()
}
-/// Plugin catalog surfaced by the Configure dialog. Ghidra ships a full
+/// Plugin catalog surfaced by the Configure dialog. ships a full
/// plugin picker — Ghidrust plugins are compile-time so this is a
/// read-only list.
#[derive(Debug, Clone, Copy)]
pub struct PluginRow {
- pub name: &'static str,
- pub kind: &'static str,
- pub state: &'static str,
- pub description: &'static str,
+ pub name: &'static str,
+ pub kind: &'static str,
+ pub state: &'static str,
+ pub description: &'static str,
}
/// Every plugin analog Ghidrust ships today.
pub const PLUGIN_CATALOG: &[PluginRow] = &[
PluginRow {
- name: "CodeBrowserPlugin",
- kind: "Core",
- state: "Included",
- description: "Listing + Decompiler center panes (Ghidra CodeBrowser).",
+ name: "CodeBrowserPlugin",
+ kind: "Core",
+ state: "Included",
+ description: "Listing + Decompiler center panes .",
},
PluginRow {
- name: "DecompilePlugin",
- kind: "Core",
- state: "Included",
- description: "Stage-0 / Stage-0.5 / Stage-1 pseudo-C emission.",
+ name: "DecompilePlugin",
+ kind: "Core",
+ state: "Included",
+ description: "Stage-0 / Stage-0.5 / Stage-1 pseudo-C emission.",
},
PluginRow {
- name: "SymbolTreePlugin",
- kind: "Base",
- state: "Included",
- description: "Imports / Exports / Functions / Labels / Classes / Namespaces tree.",
+ name: "SymbolTreePlugin",
+ kind: "Base",
+ state: "Included",
+ description: "Imports / Exports / Functions / Labels / Classes / Namespaces tree.",
},
PluginRow {
- name: "ProgramTreePlugin",
- kind: "Base",
- state: "Included",
- description: "Modules / fragments (Ghidra program tree) view filter.",
+ name: "ProgramTreePlugin",
+ kind: "Base",
+ state: "Included",
+ description: "Modules / fragments . view filter.",
},
PluginRow {
- name: "DataTypeManagerPlugin",
- kind: "Base",
- state: "Included",
- description: "Built-In + Program archives, editors, Data Type Chooser.",
+ name: "DataTypeManagerPlugin",
+ kind: "Base",
+ state: "Included",
+ description: "Built-In + Program archives, editors, Data Type Chooser.",
},
PluginRow {
- name: "FunctionGraphPlugin",
- kind: "FunctionGraph",
- state: "Included",
- description: "CFG vertex / edge layout on top of Stage-0 blocks.",
+ name: "FunctionGraphPlugin",
+ kind: "FunctionGraph",
+ state: "Included",
+ description: "CFG vertex / edge layout on top of Stage-0 blocks.",
},
PluginRow {
- name: "FunctionCallGraphPlugin",
- kind: "GraphFunctionCalls",
- state: "Included",
- description: "Level-based directed call graph in / out of source function.",
+ name: "FunctionCallGraphPlugin",
+ kind: "GraphFunctionCalls",
+ state: "Included",
+ description: "Level-based directed call graph in / out of source function.",
},
PluginRow {
- name: "CallTreePlugin",
- kind: "Base",
- state: "Included",
- description: "Incoming callers / outgoing callees + refs GTree pair.",
+ name: "CallTreePlugin",
+ kind: "Base",
+ state: "Included",
+ description: "Incoming callers / outgoing callees + refs GTree pair.",
},
PluginRow {
- name: "MemoryMapPlugin",
- kind: "Base",
- state: "Included",
- description: "Editable Add / Delete / Toggle RWX memory-block table.",
+ name: "MemoryMapPlugin",
+ kind: "Base",
+ state: "Included",
+ description: "Editable Add / Delete / Toggle RWX memory-block table.",
},
PluginRow {
- name: "RegisterPlugin",
- kind: "Base",
- state: "Included",
- description: "SLEIGH-analog register lattice + session values.",
+ name: "RegisterPlugin",
+ kind: "Base",
+ state: "Included",
+ description: "Hierarchical register lattice + session values.",
},
PluginRow {
- name: "OverviewPlugin",
- kind: "Base",
- state: "Included",
- description: "Memory-block colour banner (X / W / R / unmapped).",
+ name: "OverviewPlugin",
+ kind: "Base",
+ state: "Included",
+ description: "Memory-block colour banner (X / W / R / unmapped).",
},
PluginRow {
- name: "EntropyPlugin",
- kind: "Base",
- state: "Included",
- description: "Shannon-entropy strip across mapped blocks.",
+ name: "EntropyPlugin",
+ kind: "Base",
+ state: "Included",
+ description: "Shannon-entropy strip across mapped blocks.",
},
PluginRow {
- name: "BookmarkPlugin",
- kind: "Base",
- state: "Included",
- description: "5 Ghidra bookmark kinds; margin markers.",
+ name: "BookmarkPlugin",
+ kind: "Base",
+ state: "Included",
+ description: "5 bookmark kinds; margin markers.",
},
PluginRow {
- name: "CommentWindowPlugin",
- kind: "Base",
- state: "Included",
- description: "Filter by kind + text; jump to source VA.",
+ name: "CommentWindowPlugin",
+ kind: "Base",
+ state: "Included",
+ description: "Filter by kind + text; jump to source VA.",
},
PluginRow {
- name: "ByteViewerPlugin",
- kind: "Base",
- state: "Included",
- description: "Hex + ASCII split view over Program bytes.",
+ name: "ByteViewerPlugin",
+ kind: "Base",
+ state: "Included",
+ description: "Hex + ASCII split view over Program bytes.",
},
PluginRow {
- name: "GhidraScriptMgrPlugin",
- kind: "Scripting",
- state: "Included",
- description: "Ghidrust MCP tool catalog (from skill/SKILL.md).",
+ name: "ScriptMgrPlugin",
+ kind: "Scripting",
+ state: "Included",
+ description: "Ghidrust MCP tool catalog (from skill/SKILL.md).",
},
PluginRow {
- name: "TextEditorManagerPlugin",
- kind: "Scripting",
- state: "Included",
- description: "Multi-tab in-memory editor for local script files.",
+ name: "TextEditorManagerPlugin",
+ kind: "Scripting",
+ state: "Included",
+ description: "Multi-tab in-memory editor for local script files.",
},
PluginRow {
- name: "InterpreterPanelPlugin",
- kind: "Scripting",
- state: "Included · REPL stub",
- description: "MCP REPL — wires into `ghidrust mcp` stdio host in P17.",
+ name: "InterpreterPanelPlugin",
+ kind: "Scripting",
+ state: "Included · REPL stub",
+ description: "MCP REPL — wires into `ghidrust mcp` stdio host in P17.",
},
PluginRow {
- name: "DebuggerTargetsPlugin",
- kind: "Debugger",
- state: "Included · empty",
- description: "Target agent list — backend pending P12.",
+ name: "DebuggerTargetsPlugin",
+ kind: "Debugger",
+ state: "Included · live",
+ description: "Tabbed Debugger · Targets — process list + attach (Live Process Bridge).",
},
PluginRow {
- name: "DebuggerThreadsPlugin",
- kind: "Debugger",
- state: "Included · empty",
- description: "Live threads — backend pending P12.",
+ name: "DebuggerThreadsPlugin",
+ kind: "Debugger",
+ state: "Included · stub",
+ description: "Tabbed Debugger · Threads — live backend not yet wired.",
},
PluginRow {
- name: "DebuggerModulesPlugin",
- kind: "Debugger",
- state: "Included · empty",
- description: "Loaded modules — backend pending P12.",
+ name: "DebuggerModulesPlugin",
+ kind: "Debugger",
+ state: "Included · live",
+ description: "Tabbed Debugger · Modules — auto-populated on attach + Static Mappings.",
},
PluginRow {
- name: "DebuggerRegionsPlugin",
- kind: "Debugger",
- state: "Included · empty",
- description: "Live memory regions — backend pending P12.",
+ name: "DebuggerRegionsPlugin",
+ kind: "Debugger",
+ state: "Included · live",
+ description: "Tabbed Debugger · Regions — VirtualQueryEx map auto-fetched on attach.",
},
PluginRow {
- name: "DebuggerRegistersPlugin",
- kind: "Debugger",
- state: "Included · empty",
- description: "Live register values — backend pending P12.",
+ name: "DebuggerRegistersPlugin",
+ kind: "Debugger",
+ state: "Included · stub",
+ description: "Tabbed Debugger · Registers — live backend not yet wired.",
},
PluginRow {
- name: "DebuggerStackPlugin",
- kind: "Debugger",
- state: "Included · empty",
- description: "Live stack frames — backend pending P12.",
+ name: "DebuggerStackPlugin",
+ kind: "Debugger",
+ state: "Included · stub",
+ description: "Tabbed Debugger · Stack — live backend not yet wired.",
},
PluginRow {
- name: "DebuggerBreakpointsPlugin",
- kind: "Debugger",
- state: "Included · empty",
- description: "Session-only breakpoint list; agent-set pending P12.",
+ name: "DebuggerBreakpointsPlugin",
+ kind: "Debugger",
+ state: "Included · session",
+ description: "Tabbed Debugger · Breakpoints — session-only list; agent-set pending.",
},
PluginRow {
- name: "DebuggerMemoryBytesPlugin",
- kind: "Debugger",
- state: "Included · empty",
- description: "Live memory dumps — backend pending P12.",
+ name: "DebuggerMemoryBytesPlugin",
+ kind: "Debugger",
+ state: "Included · live",
+ description: "Tabbed Debugger · Memory Bytes — seeded at main module base on attach.",
},
PluginRow {
- name: "DebuggerWatchesPlugin",
- kind: "Debugger",
- state: "Included · empty",
- description: "Session-only watch list; evaluator pending P12.",
+ name: "DebuggerWatchesPlugin",
+ kind: "Debugger",
+ state: "Included · session",
+ description: "Tabbed Debugger · Watches — session-only list; evaluator pending.",
},
PluginRow {
- name: "DebuggerConsolePlugin",
- kind: "Debugger",
- state: "Included · empty",
- description: "Target-agent stdio — backend pending P12.",
+ name: "DebuggerConsolePlugin",
+ kind: "Debugger",
+ state: "Included · stub",
+ description: "Tabbed Debugger · Console — target-agent stdio pending.",
},
];
@@ -301,12 +301,12 @@ mod tests {
#[test]
fn round_trip_layout_json() {
let l = SavedLayout {
- name: "test".into(),
- open_panes: [("pane_bookmarks".to_string(), true)].into_iter().collect(),
- docks: [("console".to_string(), true)].into_iter().collect(),
- center: "listing".into(),
+ name: "test".into(),
+ open_panes: [("pane_bookmarks".to_string(), true)].into_iter().collect(),
+ docks: [("console".to_string(), true)].into_iter().collect(),
+ center: "listing".into(),
dock_tree: None,
- theme: "dark".into(),
+ theme: "dark".into(),
comment: String::new(),
};
let text = serde_json::to_string(&l).unwrap();
@@ -316,43 +316,43 @@ mod tests {
#[test]
fn legacy_layout_without_dock_tree_still_deserializes() {
- let text = r#"{
- "name": "old",
- "open_panes": {},
- "docks": {},
- "center": "decompiler",
- "theme": "dark",
- "comment": ""
- }"#;
+ let text = r#"{
+ "name": "old",
+ "open_panes": {},
+ "docks": {},
+ "center": "decompiler",
+ "theme": "dark",
+ "comment": ""
+ }"#;
let back: SavedLayout = serde_json::from_str(text).unwrap();
- assert_eq!(back.center, "decompiler");
+ assert_eq!(back.center, "decompiler");
assert!(back.dock_tree.is_none());
}
#[test]
fn sanitize_strips_path_seps() {
- assert_eq!(sanitize("a/b\\c*d"), "a_b_c_d");
- assert_eq!(sanitize("hello-world.1"), "hello-world.1");
+ assert_eq!(sanitize("a/b\\c*d"), "a_b_c_d");
+ assert_eq!(sanitize("hello-world.1"), "hello-world.1");
}
#[test]
fn plugin_catalog_covers_graph_debugger_configure_providers() {
- let names: Vec<&'static str> = PLUGIN_CATALOG.iter().map(|p| p.name).collect();
+ let names: Vec<&'static str> = PLUGIN_CATALOG.iter().map(|p| p.name()).collect();
for expected in [
- "FunctionGraphPlugin",
- "FunctionCallGraphPlugin",
- "CallTreePlugin",
- "MemoryMapPlugin",
- "RegisterPlugin",
- "OverviewPlugin",
- "EntropyPlugin",
- "GhidraScriptMgrPlugin",
- "TextEditorManagerPlugin",
- "InterpreterPanelPlugin",
- "DebuggerTargetsPlugin",
- "DebuggerBreakpointsPlugin",
+ "FunctionGraphPlugin",
+ "FunctionCallGraphPlugin",
+ "CallTreePlugin",
+ "MemoryMapPlugin",
+ "RegisterPlugin",
+ "OverviewPlugin",
+ "EntropyPlugin",
+ "ScriptMgrPlugin",
+ "TextEditorManagerPlugin",
+ "InterpreterPanelPlugin",
+ "DebuggerTargetsPlugin",
+ "DebuggerBreakpointsPlugin",
] {
- assert!(names.contains(&expected), "missing plugin {expected}");
+ assert!(names.contains(&expected), "missing plugin {expected}");
}
}
}
diff --git a/crates/ghidrust-gui/src/listing/detail_pane.rs b/crates/ghidrust-gui/src/listing/detail_pane.rs
new file mode 100644
index 0000000..bb18c77
--- /dev/null
+++ b/crates/ghidrust-gui/src/listing/detail_pane.rs
@@ -0,0 +1,154 @@
+//! Instruction detail pane .
+
+use ghidrust_core::ghidrust_decode::{group_name, insn_name, reg_name};
+use ghidrust_core::ghidrust_decode::{OpType, Operand};
+use ghidrust_core::{Arch, Instruction};
+
+pub fn ui_detail_pane(ui: &mut egui::Ui, insn: &Instruction, arch: Arch) {
+ ui.horizontal(|ui| {
+ ui.label("Address:");
+ ui.monospace(format!("{:#x}", insn.address));
+ ui.label("Size:");
+ ui.monospace(format!("{}", insn.length));
+ });
+ ui.horizontal(|ui| {
+ ui.label("Id:");
+ ui.monospace(format!("{} ({})", insn.id.raw(), insn.id.raw()));
+ if let Some(name) = insn_name(arch, insn.id) {
+ ui.label(format!("· {name}"));
+ }
+ });
+ ui.horizontal(|ui| {
+ ui.label("Mnemonic:");
+ ui.monospace(&insn.mnemonic);
+ if !insn.operands.is_empty() {
+ ui.label("Operands:");
+ ui.monospace(&insn.operands);
+ }
+ });
+ ui.separator();
+ let Some(d) = insn.detail.as_ref() else {
+ ui.weak("No structured detail — enable Detail in the Listing toolbar and Apply.");
+ return;
+ };
+ if !d.groups.is_empty() {
+ ui.label("Groups:");
+ let g: Vec<String> = d
+ .groups
+ .iter()
+ .map(|gid| {
+ group_name(arch, *gid)
+ .map(String::from)
+ .unwrap_or_else(|| format!("{:?}", gid))
+ })
+ .collect();
+ ui.monospace(g.join(", "));
+ }
+ if !d.regs_read.is_empty() || !d.implicit_read.is_empty() {
+ ui.label("Regs read:");
+ ui.monospace(format_regs(arch, &d.regs_read, &d.implicit_read));
+ }
+ if !d.regs_write.is_empty() || !d.implicit_write.is_empty() {
+ ui.label("Regs write:");
+ ui.monospace(format_regs(arch, &d.regs_write, &d.implicit_write));
+ }
+ if !d.operands.is_empty() {
+ ui.separator();
+ ui.label("Typed operands:");
+ egui::Grid::new("insn_detail_ops")
+ .num_columns(2)
+ .striped(true)
+ .show(ui, |ui| {
+ ui.strong("#");
+ ui.strong("Operand");
+ ui.end_row();
+ for (i, op) in d.operands.iter().enumerate() {
+ ui.label(format!("{i}"));
+ ui.monospace(format_operand(arch, op));
+ ui.end_row();
+ }
+ });
+ }
+}
+
+fn format_regs(arch: Arch, explicit: &[ghidrust_core::RegId], implicit: &[ghidrust_core::RegId]) -> String {
+ let mut parts: Vec<String> = explicit
+ .iter()
+ .map(|r| reg_label(arch, *r, false))
+ .collect();
+ for r in implicit {
+ parts.push(reg_label(arch, *r, true));
+ }
+ parts.join(", ")
+}
+
+fn reg_label(arch: Arch, reg: ghidrust_core::RegId, implicit: bool) -> String {
+ let name = reg_name(arch, reg)
+ .map(String::from)
+ .unwrap_or_else(|| format!("r{}", reg.0));
+ if implicit {
+ format!("{name}*")
+ } else {
+ name
+ }
+}
+
+fn format_operand(arch: Arch, op: &Operand) -> String {
+ match op {
+ Operand::Reg(r) => reg_label(arch, *r, false),
+ Operand::Imm { value, size } => format!("imm {value} (size {size})"),
+ Operand::Mem {
+ base,
+ index,
+ scale,
+ disp,
+ segment,
+ size,
+ } => {
+ let base_s = reg_name(arch, *base).unwrap_or("—");
+ let idx_s = if index.0 != 0 {
+ reg_name(arch, *index).unwrap_or("—")
+ } else {
+ ""
+ };
+ let seg_s = if segment.0 != 0 {
+ reg_name(arch, *segment).unwrap_or("—")
+ } else {
+ ""
+ };
+ format!(
+ "mem [{seg}{base}{idx}{scale}{disp}] size={size}",
+ seg = if seg_s.is_empty() {
+ String::new()
+ } else {
+ format!("{seg_s}:")
+ },
+ base = base_s,
+ idx = if idx_s.is_empty() {
+ String::new()
+ } else {
+ format!("+{idx_s}*{scale}")
+ },
+ scale = if idx_s.is_empty() { "" } else { "" },
+ disp = if *disp != 0 {
+ format!("{disp:+}")
+ } else {
+ String::new()
+ },
+ )
+ }
+ Operand::Fp => "fp".into(),
+ Operand::Invalid => "invalid".into(),
+ }
+}
+
+#[allow(dead_code)]
+pub fn operand_type_label(op: &Operand) -> &'static str {
+ match op.op_type() {
+ OpType::Reg => "reg",
+ OpType::Imm => "imm",
+ OpType::Mem => "mem",
+ OpType::Fp => "fp",
+ OpType::Invalid => "invalid",
+ }
+}
diff --git a/crates/ghidrust-gui/src/listing/disasm_service.rs b/crates/ghidrust-gui/src/listing/disasm_service.rs
new file mode 100644
index 0000000..6718d43
--- /dev/null
+++ b/crates/ghidrust-gui/src/listing/disasm_service.rs
@@ -0,0 +1,43 @@
+//! Reload listing disassembly via `ghidrust_core` decode APIs.
+
+use super::model::{DecodeUiOpts, WalkMode};
+use ghidrust_core::{disassemble_range_ex_opts, DisasmRangeResult, Program};
+
+/// Disassemble at `start` using engine options from the GUI.
+pub fn reload(
+ prog: &Program,
+ start: u64,
+ opts: &DecodeUiOpts,
+) -> Result<DisasmRangeResult, String> {
+ let engine = opts.to_engine_opts();
+ let bound_end = prog
+ .function_containing(start)
+ .map(|f| f.end)
+ .filter(|e| *e > start);
+ disassemble_range_ex_opts(
+ prog,
+ start,
+ opts.max_insns,
+ opts.skip_bad,
+ opts.walk_mode.to_disasm_mode(),
+ bound_end,
+ Some(&engine),
+ )
+ .map_err(|e| e.to_string())
+}
+
+/// Pick a sensible reload VA when none is focused.
+pub fn default_start_va(prog: &Program, focus: Option<u64>) -> u64 {
+ focus.unwrap_or_else(|| prog.entry.unwrap_or(prog.image_base))
+}
+
+/// Default listing window size for navigation reloads.
+pub const GOTO_MAX_INSNS: usize = 64;
+
+/// Reload helper tuned for go-to navigation (smaller window).
+pub fn reload_for_goto(prog: &Program, va: u64, opts: &DecodeUiOpts) -> Result<Vec<ghidrust_core::Instruction>, String> {
+ let mut nav_opts = opts.clone();
+ nav_opts.max_insns = GOTO_MAX_INSNS;
+ nav_opts.walk_mode = WalkMode::Bounded;
+ reload(prog, va, &nav_opts).map(|r| r.insns)
+}
diff --git a/crates/ghidrust-gui/src/listing/mod.rs b/crates/ghidrust-gui/src/listing/mod.rs
new file mode 100644
index 0000000..ab904d3
--- /dev/null
+++ b/crates/ghidrust-gui/src/listing/mod.rs
@@ -0,0 +1,18 @@
+//! decode listing surfaces for the Listing pane.
+
+mod detail_pane;
+mod disasm_service;
+mod model;
+mod options;
+mod persist;
+mod processor;
+mod search;
+mod toolbar;
+
+pub use detail_pane::ui_detail_pane;
+pub use disasm_service::{default_start_va, reload, reload_for_goto};
+pub use model::{DecodeUiOpts, ListingRow};
+pub use options::ui_options_dialog;
+pub use persist::{load as load_decode_prefs, save as save_decode_prefs};
+pub use search::{matches as listing_matches, ui_search_bar, ListingSearch};
+pub use toolbar::{ui_toolbar, ToolbarAction};
diff --git a/crates/ghidrust-gui/src/listing/model.rs b/crates/ghidrust-gui/src/listing/model.rs
new file mode 100644
index 0000000..d313998
--- /dev/null
+++ b/crates/ghidrust-gui/src/listing/model.rs
@@ -0,0 +1,337 @@
+//! Decode listing row model and UI options.
+
+use ghidrust_core::{
+ arch_mode_for_program, default_arch_mode, ghidrust_decode::{group_name, reg_name},
+ Arch, DisasmEngineOpts, DisasmMode, InsnId, Instruction, Mode, Program, Syntax,
+};
+use serde::{Deserialize, Serialize};
+
+/// Disassembly walk strategy for the Listing pane.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum WalkMode {
+ #[default]
+ Bounded,
+ Flow,
+ Linear,
+}
+
+impl WalkMode {
+ pub const ALL: [WalkMode; 3] = [WalkMode::Bounded, WalkMode::Flow, WalkMode::Linear];
+
+ pub const fn label(self) -> &'static str {
+ match self {
+ WalkMode::Bounded => "Bounded",
+ WalkMode::Flow => "Flow",
+ WalkMode::Linear => "Linear",
+ }
+ }
+
+ pub const fn to_disasm_mode(self) -> DisasmMode {
+ match self {
+ WalkMode::Bounded => DisasmMode::Bounded,
+ WalkMode::Flow => DisasmMode::Flow,
+ WalkMode::Linear => DisasmMode::Linear,
+ }
+ }
+}
+
+/// decode options surfaced in the Listing toolbar / options dialog.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct DecodeUiOpts {
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub arch: Option<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub mode: Option<u32>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub syntax: Option<String>,
+ #[serde(default)]
+ pub detail: bool,
+ #[serde(default)]
+ pub detail_real: bool,
+ #[serde(default)]
+ pub skipdata: bool,
+ #[serde(default)]
+ pub skipdata_mnemonic: String,
+ #[serde(default)]
+ pub unsigned_imm: bool,
+ #[serde(default)]
+ pub only_offset_branch: bool,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub litbase: Option<u32>,
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub mnem_overrides: Vec<(u32, String)>,
+ #[serde(default)]
+ pub walk_mode: WalkMode,
+ #[serde(default = "default_skip_bad")]
+ pub skip_bad: bool,
+ #[serde(default = "default_max_insns")]
+ pub max_insns: usize,
+}
+
+fn default_skip_bad() -> bool {
+ true
+}
+
+fn default_max_insns() -> usize {
+ 128
+}
+
+impl Default for DecodeUiOpts {
+ fn default() -> Self {
+ Self {
+ arch: None,
+ mode: None,
+ syntax: None,
+ detail: true,
+ detail_real: false,
+ skipdata: false,
+ skipdata_mnemonic: ".byte".into(),
+ unsigned_imm: false,
+ only_offset_branch: false,
+ litbase: None,
+ mnem_overrides: Vec::new(),
+ walk_mode: WalkMode::Bounded,
+ skip_bad: true,
+ max_insns: 128,
+ }
+ }
+}
+
+impl DecodeUiOpts {
+ /// Seed arch/mode from the loaded image when unset.
+ pub fn sync_machine_from_program(&mut self, prog: &Program) {
+ if self.arch.is_none() || self.mode.is_none() {
+ let (arch, mode) = arch_mode_for_program(prog).unwrap_or_else(default_arch_mode);
+ if self.arch.is_none() {
+ self.arch = Some(arch.name().to_string());
+ }
+ if self.mode.is_none() {
+ self.mode = Some(mode.bits());
+ }
+ }
+ }
+
+ pub fn resolved_arch(&self) -> Option<Arch> {
+ self.arch.as_deref().and_then(parse_arch_name)
+ }
+
+ pub fn resolved_mode(&self) -> Option<Mode> {
+ self.mode.map(Mode)
+ }
+
+ pub fn resolved_syntax(&self) -> Option<Syntax> {
+ self.syntax.as_deref().and_then(parse_syntax_name)
+ }
+
+ pub fn to_engine_opts(&self) -> DisasmEngineOpts {
+ DisasmEngineOpts {
+ arch: self.resolved_arch(),
+ mode: self.resolved_mode(),
+ syntax: self.resolved_syntax(),
+ detail: Some(self.detail),
+ detail_real: Some(self.detail_real),
+ skipdata: Some(self.skipdata),
+ skipdata_mnemonic: if self.skipdata_mnemonic.is_empty() {
+ None
+ } else {
+ Some(self.skipdata_mnemonic.clone())
+ },
+ skipdata_size: None,
+ unsigned_imm: Some(self.unsigned_imm),
+ only_offset_branch: Some(self.only_offset_branch),
+ litbase: self.litbase,
+ mnem_overrides: if self.mnem_overrides.is_empty() {
+ None
+ } else {
+ Some(self.mnem_overrides.clone())
+ },
+ }
+ }
+}
+
+/// One rendered Listing row .
+#[derive(Debug, Clone)]
+pub struct ListingRow {
+ pub idx: usize,
+ pub va: u64,
+ pub id: InsnId,
+ pub groups_summary: String,
+ pub regs_rw: String,
+ pub bytes_hex: String,
+ pub mnem: String,
+ pub ops: String,
+ pub is_ret: bool,
+ pub is_uncond: bool,
+ pub is_cond: bool,
+ pub is_call: bool,
+ pub applied_type: Option<String>,
+ pub comment_eol: Option<String>,
+ pub comment_plate: Option<String>,
+ pub comment_pre: Option<String>,
+ pub comment_post: Option<String>,
+ pub comment_repeat: Option<String>,
+}
+
+impl ListingRow {
+ pub fn from_insn(
+ idx: usize,
+ insn: &Instruction,
+ prog: Option<&Program>,
+ arch: Arch,
+ ) -> Self {
+ let bytes_hex: String = insn
+ .bytes
+ .iter()
+ .take(6)
+ .map(|b| format!("{b:02x}"))
+ .collect::<Vec<_>>()
+ .join(" ");
+ let (groups_summary, regs_rw) = detail_summaries(insn, arch);
+ let (
+ applied_type,
+ comment_eol,
+ comment_plate,
+ comment_pre,
+ comment_post,
+ comment_repeat,
+ ) = prog
+ .map(|p| {
+ use ghidrust_core::CommentKind;
+ (
+ p.edits.applied_type_at(insn.address).map(String::from),
+ p.edits
+ .comment_at(insn.address, CommentKind::Eol)
+ .map(String::from),
+ p.edits
+ .comment_at(insn.address, CommentKind::Plate)
+ .map(String::from),
+ p.edits
+ .comment_at(insn.address, CommentKind::Pre)
+ .map(String::from),
+ p.edits
+ .comment_at(insn.address, CommentKind::Post)
+ .map(String::from),
+ p.edits
+ .comment_at(insn.address, CommentKind::Repeatable)
+ .map(String::from),
+ )
+ })
+ .unwrap_or((None, None, None, None, None, None));
+ let mnem = insn.mnemonic.clone();
+ let is_ret = matches!(mnem.as_str(), "ret" | "retn" | "retf" | "retq");
+ let is_uncond = matches!(mnem.as_str(), "jmp" | "jmpq");
+ let is_cond = mnem.starts_with('j') && !is_uncond && mnem != "jmp";
+ let is_call = matches!(mnem.as_str(), "call" | "callq");
+ Self {
+ idx,
+ va: insn.address,
+ id: insn.id,
+ groups_summary,
+ regs_rw,
+ bytes_hex,
+ mnem,
+ ops: insn.operands.clone(),
+ is_ret,
+ is_uncond,
+ is_cond,
+ is_call,
+ applied_type,
+ comment_eol,
+ comment_plate,
+ comment_pre,
+ comment_post,
+ comment_repeat,
+ }
+ }
+}
+
+pub fn detail_summaries(insn: &Instruction, arch: Arch) -> (String, String) {
+ let Some(d) = insn.detail.as_ref() else {
+ return (String::new(), String::new());
+ };
+ let groups: Vec<String> = d
+ .groups
+ .iter()
+ .filter_map(|g| group_name(arch, *g).map(String::from))
+ .collect();
+ let mut read: Vec<String> = d
+ .regs_read
+ .iter()
+ .chain(d.implicit_read.iter())
+ .filter_map(|r| reg_name(arch, *r).map(String::from))
+ .collect();
+ read.sort();
+ read.dedup();
+ let mut write: Vec<String> = d
+ .regs_write
+ .iter()
+ .chain(d.implicit_write.iter())
+ .filter_map(|r| reg_name(arch, *r).map(String::from))
+ .collect();
+ write.sort();
+ write.dedup();
+ let regs_rw = if read.is_empty() && write.is_empty() {
+ String::new()
+ } else {
+ format!("R:[{}] W:[{}]", read.join(","), write.join(","))
+ };
+ (groups.join(","), regs_rw)
+}
+
+pub fn parse_arch_name(s: &str) -> Option<Arch> {
+ Arch::ALL
+ .into_iter()
+ .find(|a| a.name().eq_ignore_ascii_case(s))
+}
+
+pub fn parse_syntax_name(s: &str) -> Option<Syntax> {
+ match s.trim().to_ascii_lowercase().as_str() {
+ "default" => Some(Syntax::Default),
+ "intel" => Some(Syntax::Intel),
+ "att" => Some(Syntax::Att),
+ "noregname" | "no_reg_name" => Some(Syntax::NoRegName),
+ "masm" => Some(Syntax::Masm),
+ "motorola" => Some(Syntax::Motorola),
+ "cs_reg_alias" | "reg_alias" => Some(Syntax::CsRegAlias),
+ "percent" => Some(Syntax::Percent),
+ "no_dollar" | "nodollar" => Some(Syntax::NoDollar),
+ "no_alias_text" => Some(Syntax::NoAliasText),
+ "no_alias_text_compressed" => Some(Syntax::NoAliasTextCompressed),
+ _ => None,
+ }
+}
+
+pub fn syntax_storage(s: Syntax) -> String {
+ syntax_label(s).to_ascii_lowercase()
+}
+
+pub fn syntax_label(s: Syntax) -> &'static str {
+ match s {
+ Syntax::Default => "Default",
+ Syntax::Intel => "Intel",
+ Syntax::Att => "ATT",
+ Syntax::NoRegName => "NoRegName",
+ Syntax::Masm => "MASM",
+ Syntax::Motorola => "Motorola",
+ Syntax::CsRegAlias => "CsRegAlias",
+ Syntax::Percent => "Percent",
+ Syntax::NoDollar => "NoDollar",
+ Syntax::NoAliasText => "NoAliasText",
+ Syntax::NoAliasTextCompressed => "NoAliasTextCompressed",
+ }
+}
+
+pub const SYNTAX_VARIANTS: [Syntax; 11] = [
+ Syntax::Default,
+ Syntax::Intel,
+ Syntax::Att,
+ Syntax::NoRegName,
+ Syntax::Masm,
+ Syntax::Motorola,
+ Syntax::CsRegAlias,
+ Syntax::Percent,
+ Syntax::NoDollar,
+ Syntax::NoAliasText,
+ Syntax::NoAliasTextCompressed,
+];
diff --git a/crates/ghidrust-gui/src/listing/options.rs b/crates/ghidrust-gui/src/listing/options.rs
new file mode 100644
index 0000000..aab533b
--- /dev/null
+++ b/crates/ghidrust-gui/src/listing/options.rs
@@ -0,0 +1,99 @@
+//! Full decode options dialog (arch/mode and engine options).
+
+use super::model::DecodeUiOpts;
+use super::processor::ui_processor_selectors;
+use ghidrust_core::Program;
+
+pub fn ui_options_dialog(
+ ctx: &egui::Context,
+ open: &mut bool,
+ opts: &mut DecodeUiOpts,
+ prog: Option<&Program>,
+) -> bool {
+ if !*open {
+ return false;
+ }
+ let mut apply = false;
+ let mut close = false;
+ egui::Window::new("Decode Options")
+ .collapsible(false)
+ .resizable(true)
+ .default_width(480.0)
+ .show(ctx, |ui| {
+ ui_processor_selectors(ui, opts, prog);
+ ui.separator();
+ ui.checkbox(&mut opts.detail_real, "Detail real (arch-specific fields)");
+ ui.checkbox(&mut opts.unsigned_imm, "Unsigned immediates");
+ ui.checkbox(&mut opts.only_offset_branch, "Only offset branch targets");
+ ui.checkbox(&mut opts.skip_bad, "Skip bad bytes (listing continuity)");
+ ui.horizontal(|ui| {
+ ui.label("Skipdata mnemonic:");
+ ui.text_edit_singleline(&mut opts.skipdata_mnemonic);
+ });
+ ui.horizontal(|ui| {
+ ui.label("Litbase:");
+ let mut lit = opts.litbase.unwrap_or(0);
+ if ui.add(egui::DragValue::new(&mut lit).speed(1)).changed() {
+ opts.litbase = Some(lit);
+ }
+ if ui.small_button("Clear").clicked() {
+ opts.litbase = None;
+ }
+ });
+ ui.horizontal(|ui| {
+ ui.label("Max insns:");
+ ui.add(
+ egui::DragValue::new(&mut opts.max_insns)
+ .range(8..=4096),
+ );
+ });
+ ui.separator();
+ ui.label("Mnemonic overrides (id:mnemonic per line):");
+ let mut text = overrides_to_text(&opts.mnem_overrides);
+ if ui
+ .add(
+ egui::TextEdit::multiline(&mut text)
+ .desired_rows(4)
+ .desired_width(f32::INFINITY),
+ )
+ .changed()
+ {
+ opts.mnem_overrides = parse_overrides(&text);
+ }
+ ui.separator();
+ ui.horizontal(|ui| {
+ if ui.button("Apply").clicked() {
+ apply = true;
+ close = true;
+ }
+ if ui.button("Cancel").clicked() {
+ close = true;
+ }
+ });
+ });
+ if close {
+ *open = false;
+ }
+ apply
+}
+
+fn overrides_to_text(list: &[(u32, String)]) -> String {
+ list.iter()
+ .map(|(id, m)| format!("{id}:{m}"))
+ .collect::<Vec<_>>()
+ .join("\n")
+}
+
+fn parse_overrides(text: &str) -> Vec<(u32, String)> {
+ text.lines()
+ .filter_map(|line| {
+ let line = line.trim();
+ if line.is_empty() {
+ return None;
+ }
+ let (id_s, mnem) = line.split_once(':')?;
+ let id = id_s.trim().parse().ok()?;
+ Some((id, mnem.trim().to_string()))
+ })
+ .collect()
+}
diff --git a/crates/ghidrust-gui/src/listing/persist.rs b/crates/ghidrust-gui/src/listing/persist.rs
new file mode 100644
index 0000000..f1cb9b8
--- /dev/null
+++ b/crates/ghidrust-gui/src/listing/persist.rs
@@ -0,0 +1,29 @@
+//! Persist decode UI options alongside an on-disk project.
+
+use super::model::DecodeUiOpts;
+use std::path::Path;
+
+pub const GUI_PREFS_FILE: &str = "ghidrust.gui.json";
+
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, Default)]
+struct GuiPrefs {
+ #[serde(default)]
+ decode_opts: DecodeUiOpts,
+}
+
+pub fn load(project_root: &Path) -> Option<DecodeUiOpts> {
+ let path = project_root.join(GUI_PREFS_FILE);
+ let text = std::fs::read_to_string(path).ok()?;
+ serde_json::from_str::<GuiPrefs>(&text)
+ .ok()
+ .map(|p| p.decode_opts)
+}
+
+pub fn save(project_root: &Path, opts: &DecodeUiOpts) -> Result<(), String> {
+ let path = project_root.join(GUI_PREFS_FILE);
+ let prefs = GuiPrefs {
+ decode_opts: opts.clone(),
+ };
+ let text = serde_json::to_string_pretty(&prefs).map_err(|e| e.to_string())?;
+ std::fs::write(path, text).map_err(|e| e.to_string())
+}
diff --git a/crates/ghidrust-gui/src/listing/processor.rs b/crates/ghidrust-gui/src/listing/processor.rs
new file mode 100644
index 0000000..2b86204
--- /dev/null
+++ b/crates/ghidrust-gui/src/listing/processor.rs
@@ -0,0 +1,119 @@
+//! Architecture + mode selectors from `Engine::support` / `Arch::ALL`.
+
+use super::model::{parse_arch_name, DecodeUiOpts};
+use ghidrust_core::{default_arch_mode, arch_mode_for_program, Arch, Engine, Mode, Program, SupportQuery};
+
+/// Common mode presets per architecture (not exhaustive — raw bits also editable).
+pub fn mode_presets(arch: Arch) -> &'static [(&'static str, Mode)] {
+ match arch {
+ Arch::X86 => &[
+ ("16", Mode::MODE_16),
+ ("32", Mode::MODE_32),
+ ("64", Mode::MODE_64),
+ ],
+ Arch::Arm => &[
+ ("ARM", Mode::ARM),
+ ("Thumb", Mode::THUMB),
+ ("M-class", Mode::MCLASS),
+ ],
+ Arch::Arm64 => &[("LE", Mode::LITTLE_ENDIAN), ("V8", Mode::V8)],
+ Arch::Mips => &[
+ ("MIPS32", Mode::MIPS32),
+ ("MIPS64", Mode::MIPS64),
+ ],
+ Arch::Ppc => &[("PPC32", Mode::PPC32), ("PPC64", Mode::PPC64)],
+ Arch::Riscv => &[
+ ("RV32", Mode::RISCV32),
+ ("RV64", Mode::RISCV64),
+ ("+C", Mode::RISCV_C),
+ ],
+ Arch::Bpf => &[
+ ("Classic", Mode::BPF_CLASSIC),
+ ("Extended", Mode::BPF_EXTENDED),
+ ],
+ Arch::Mos65xx => &[
+ ("6502", Mode::MOS65XX_6502),
+ ("65C02", Mode::MOS65XX_65C02),
+ ],
+ _ => &[("LE", Mode::LITTLE_ENDIAN), ("BE", Mode::BIG_ENDIAN)],
+ }
+}
+
+pub fn ui_processor_selectors(
+ ui: &mut egui::Ui,
+ opts: &mut DecodeUiOpts,
+ prog: Option<&Program>,
+) {
+ if let Some(p) = prog {
+ opts.sync_machine_from_program(p);
+ }
+ ui.label("Architecture:");
+ let cur_arch = opts
+ .resolved_arch()
+ .or_else(|| prog.and_then(arch_mode_for_program).map(|(a, _)| a))
+ .unwrap_or_else(|| default_arch_mode().0);
+ egui::ComboBox::from_id_salt("decode_arch")
+ .selected_text(cur_arch.name())
+ .show_ui(ui, |ui| {
+ for arch in Arch::ALL {
+ if !Engine::support(SupportQuery::Arch(arch)) {
+ continue;
+ }
+ let selected = cur_arch == arch;
+ if ui.selectable_label(selected, arch.name()).clicked() {
+ opts.arch = Some(arch.name().to_string());
+ if let Some((_, mode)) = mode_presets(arch).first() {
+ opts.mode = Some(mode.bits());
+ }
+ }
+ }
+ });
+
+ ui.label("Mode:");
+ let arch = opts.resolved_arch().unwrap_or(cur_arch);
+ let cur_mode = opts.resolved_mode().unwrap_or_else(|| {
+ prog.and_then(arch_mode_for_program)
+ .map(|(_, m)| m)
+ .unwrap_or_else(|| default_arch_mode().1)
+ });
+ egui::ComboBox::from_id_salt("decode_mode")
+ .selected_text(format_mode(cur_mode))
+ .show_ui(ui, |ui| {
+ for (label, mode) in mode_presets(arch) {
+ if !mode.is_valid_for(arch) {
+ continue;
+ }
+ if ui
+ .selectable_label(cur_mode.bits() == mode.bits(), *label)
+ .clicked()
+ {
+ opts.mode = Some(mode.bits());
+ }
+ }
+ ui.separator();
+ ui.horizontal(|ui| {
+ ui.label("Raw bits:");
+ let mut bits = cur_mode.bits();
+ if ui
+ .add(egui::DragValue::new(&mut bits).speed(1))
+ .changed()
+ {
+ opts.mode = Some(bits);
+ }
+ });
+ });
+
+ if let Some(name) = opts.arch.as_deref().and_then(parse_arch_name) {
+ let supported = Engine::support(SupportQuery::Arch(name));
+ if !supported {
+ ui.colored_label(
+ egui::Color32::from_rgb(0xE5, 0x39, 0x35),
+ format!("Architecture {} is not supported by the decode engine.", name.name()),
+ );
+ }
+ }
+}
+
+fn format_mode(mode: Mode) -> String {
+ format!("0x{:x}", mode.bits())
+}
diff --git a/crates/ghidrust-gui/src/listing/search.rs b/crates/ghidrust-gui/src/listing/search.rs
new file mode 100644
index 0000000..30b4409
--- /dev/null
+++ b/crates/ghidrust-gui/src/listing/search.rs
@@ -0,0 +1,91 @@
+//! Filter listing rows by mnemonic / instruction id / group.
+
+use ghidrust_core::ghidrust_decode::{group_name, insn_name};
+use ghidrust_core::{Arch, Instruction};
+
+/// User-entered listing filter (all fields are substring / prefix matches).
+#[derive(Debug, Clone)]
+pub struct ListingSearch {
+ pub mnemonic: String,
+ pub insn_id: String,
+ pub group: String,
+ pub arch: Arch,
+}
+
+impl Default for ListingSearch {
+ fn default() -> Self {
+ Self {
+ mnemonic: String::new(),
+ insn_id: String::new(),
+ group: String::new(),
+ arch: Arch::X86,
+ }
+ }
+}
+
+impl ListingSearch {
+ pub fn is_active(&self) -> bool {
+ !self.mnemonic.trim().is_empty()
+ || !self.insn_id.trim().is_empty()
+ || !self.group.trim().is_empty()
+ }
+}
+
+pub fn matches(insn: &Instruction, search: &ListingSearch) -> bool {
+ if !search.mnemonic.trim().is_empty() {
+ let q = search.mnemonic.trim().to_ascii_lowercase();
+ if !insn.mnemonic.to_ascii_lowercase().contains(&q) {
+ return false;
+ }
+ }
+ if !search.insn_id.trim().is_empty() {
+ let q = search.insn_id.trim();
+ let id_s = format!("{}", insn.id.raw());
+ let name = insn_name(search.arch, insn.id).unwrap_or("");
+ if !id_s.contains(q)
+ && !name.to_ascii_lowercase().contains(&q.to_ascii_lowercase())
+ {
+ return false;
+ }
+ }
+ if !search.group.trim().is_empty() {
+ let q = search.group.trim().to_ascii_lowercase();
+ let Some(d) = insn.detail.as_ref() else {
+ return false;
+ };
+ let hit = d.groups.iter().any(|g| {
+ group_name(search.arch, *g)
+ .unwrap_or("")
+ .to_ascii_lowercase()
+ .contains(&q)
+ });
+ if !hit {
+ return false;
+ }
+ }
+ true
+}
+
+pub fn ui_search_bar(ui: &mut egui::Ui, search: &mut ListingSearch) {
+ ui.horizontal(|ui| {
+ ui.label("Filter:");
+ ui.add(
+ egui::TextEdit::singleline(&mut search.mnemonic)
+ .desired_width(90.0)
+ .hint_text("mnemonic"),
+ );
+ ui.add(
+ egui::TextEdit::singleline(&mut search.insn_id)
+ .desired_width(70.0)
+ .hint_text("id"),
+ );
+ ui.add(
+ egui::TextEdit::singleline(&mut search.group)
+ .desired_width(90.0)
+ .hint_text("group"),
+ );
+ if search.is_active() && ui.small_button("Clear").clicked() {
+ *search = ListingSearch::default();
+ }
+ });
+}
diff --git a/crates/ghidrust-gui/src/listing/toolbar.rs b/crates/ghidrust-gui/src/listing/toolbar.rs
new file mode 100644
index 0000000..de3d940
--- /dev/null
+++ b/crates/ghidrust-gui/src/listing/toolbar.rs
@@ -0,0 +1,55 @@
+//! Listing toolbar: syntax, detail, skipdata, walk mode, apply.
+
+use super::model::{syntax_label, syntax_storage, DecodeUiOpts, SYNTAX_VARIANTS, WalkMode};
+use ghidrust_core::Syntax;
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum ToolbarAction {
+ None,
+ Apply,
+ OpenOptions,
+}
+
+pub fn ui_toolbar(
+ ui: &mut egui::Ui,
+ opts: &mut DecodeUiOpts,
+ open_options: &mut bool,
+) -> ToolbarAction {
+ let mut action = ToolbarAction::None;
+ ui.horizontal(|ui| {
+ ui.label("Syntax:");
+ let cur_syntax = opts
+ .resolved_syntax()
+ .unwrap_or(Syntax::Default);
+ egui::ComboBox::from_id_salt("listing_syntax")
+ .selected_text(syntax_label(cur_syntax))
+ .show_ui(ui, |ui| {
+ for s in SYNTAX_VARIANTS {
+ let selected = opts.resolved_syntax().unwrap_or(Syntax::Default) == s;
+ if ui.selectable_label(selected, syntax_label(s)).clicked() {
+ opts.syntax = Some(syntax_storage(s));
+ }
+ }
+ });
+
+ ui.separator();
+ ui.checkbox(&mut opts.detail, "Detail");
+ ui.checkbox(&mut opts.skipdata, "Skipdata");
+
+ ui.separator();
+ ui.label("Walk:");
+ for mode in WalkMode::ALL {
+ ui.selectable_value(&mut opts.walk_mode, mode, mode.label());
+ }
+
+ ui.separator();
+ if ui.button("Options…").clicked() {
+ *open_options = true;
+ action = ToolbarAction::OpenOptions;
+ }
+ if ui.button("Apply").clicked() {
+ action = ToolbarAction::Apply;
+ }
+ });
+ action
+}
diff --git a/crates/ghidrust-gui/src/main.rs b/crates/ghidrust-gui/src/main.rs
index d60f122..2ae2723 100644
--- a/crates/ghidrust-gui/src/main.rs
+++ b/crates/ghidrust-gui/src/main.rs
@@ -1,4 +1,4 @@
-//! Ghidrust CodeBrowser shell — Material 3 Dark/Light, Ghidra-like menus/panes.
+//! Ghidrust shell — Material 3 Dark/Light, menus/panes.
//! Icons: Google Material 3 geometry (see `icons.rs`); no emoji in the UI.
mod agent_pane;
@@ -11,6 +11,7 @@ mod graphs;
mod grok_term;
mod icons;
mod layouts;
+mod listing;
mod menu_actions;
mod nav;
mod panes;
@@ -22,10 +23,16 @@ use dock_tabs::DockTab;
use eframe::egui::{self, Color32, Visuals};
use egui_dock::{DockArea, DockState, Style as DockStyle, TabViewer};
use ghidrust_core::{
- analyzer_catalog, analyzer_supports_gpu, disassemble_range, load_path, m3_tokens,
+ analyzer_catalog, analyzer_supports_gpu, arch_mode_for_program, default_arch_mode,
+ disassemble_at_opts, load_path, m3_tokens,
set_preferred_bulk_mode, xrefs_from, xrefs_to, AnalysisRunReport, AnalyzerInfo, AnalyzerOutput,
BulkScanMode, CommentKind, FoundString, Instruction, Program, Project, ProjectTreeModel,
- RttiReport, ThemeMode, XRef, BUILTIN_TYPES,
+ RttiReport, ThemeMode, XRef, Arch, BUILTIN_TYPES,
+};
+use listing::{
+ default_start_va, listing_matches, reload, reload_for_goto, ui_detail_pane, ui_options_dialog,
+ ui_search_bar, ui_toolbar, DecodeUiOpts, ListingRow, ListingSearch, ToolbarAction,
+ load_decode_prefs, save_decode_prefs,
};
use icons::{m3_icon, m3_linear_progress, status_badge, M3Icon};
use menu_actions::{
@@ -74,7 +81,7 @@ fn render_pseudo_c_inline(ui: &mut egui::Ui, body: &str) {
italics: italic,
..Default::default()
};
- // Preserve original whitespace / newlines faithfully.
+ // Preserve original whitespace / newlines faithfully.
if matches!(tok.kind, TokenKind::Comment) {
fmt.italics = true;
}
@@ -93,19 +100,19 @@ fn render_pseudo_c_inline(ui: &mut egui::Ui, body: &str) {
fn load_skill_body() -> (String, Option<PathBuf>) {
let candidates: Vec<PathBuf> = {
let mut v = Vec::new();
- // 1. Adjacent to the running binary (production layout).
+ // 1. Adjacent to the running binary (production layout).
if let Ok(exe) = std::env::current_exe() {
if let Some(dir) = exe.parent() {
- v.push(dir.join("skill").join("SKILL.md"));
+ v.push(dir.join("skill").join("SKILL.md"));
if let Some(root) = dir.parent() {
- v.push(root.join("skill").join("SKILL.md"));
+ v.push(root.join("skill").join("SKILL.md"));
}
}
}
- // 2. Workspace-local (development layout — cargo run from repo root).
+ // 2. Workspace-local (development layout — cargo run from repo root).
if let Ok(cwd) = std::env::current_dir() {
- v.push(cwd.join("skill").join("SKILL.md"));
- v.push(cwd.join("..").join("skill").join("SKILL.md"));
+ v.push(cwd.join("skill").join("SKILL.md"));
+ v.push(cwd.join(".").join("skill").join("SKILL.md"));
}
v
};
@@ -118,15 +125,15 @@ fn load_skill_body() -> (String, Option<PathBuf>) {
}
fn recent_projects_path() -> PathBuf {
- // %APPDATA%/ghidrust/recent_projects.txt (or home fallback)
- if let Ok(appdata) = std::env::var("APPDATA") {
- PathBuf::from(appdata).join("ghidrust").join("recent_projects.txt")
- } else if let Ok(home) = std::env::var("USERPROFILE") {
+ // %APPDATA%/ghidrust/recent_projects.txt (or home fallback)
+ if let Ok(appdata) = std::env::var("APPDATA") {
+ PathBuf::from(appdata).join("ghidrust").join("recent_projects.txt")
+ } else if let Ok(home) = std::env::var("USERPROFILE") {
PathBuf::from(home)
- .join(".ghidrust")
- .join("recent_projects.txt")
+ .join(".ghidrust")
+ .join("recent_projects.txt")
} else {
- PathBuf::from("ghidrust_recent_projects.txt")
+ PathBuf::from("ghidrust_recent_projects.txt")
}
}
@@ -147,21 +154,21 @@ fn save_recent_projects(paths: &[String]) {
if let Some(parent) = p.parent() {
let _ = std::fs::create_dir_all(parent);
}
- let _ = std::fs::write(p, paths.join("\n"));
+ let _ = std::fs::write(p, paths.join("\n"));
}
/// Messages from the background analysis worker → UI thread (polled each frame).
enum AnalysisWorkerMsg {
- /// Analyzer at `index` is about to run.
+ /// Analyzer at `index` is about to run.
StepStarted { index: usize },
- /// Analyzer at `index` finished; `outputs` are that step's report rows.
+ /// Analyzer at `index` finished; `outputs` are that step's report rows.
StepFinished {
index: usize,
outputs: Vec<AnalyzerOutput>,
},
- /// All selected analyzers finished; return mutated program to the UI.
+ /// All selected analyzers finished; return mutated program to the UI.
Done { program: Program },
- /// Hard failure; program is returned so the UI can restore it (may include partial work).
+ /// Hard failure; program is returned so the UI can restore it (may include partial work).
Failed { error: String, program: Program },
}
@@ -176,7 +183,7 @@ struct AnalysisJob {
}
fn main() -> eframe::Result<()> {
- let title = format!("Ghidrust {} CodeBrowser", env!("CARGO_PKG_VERSION"));
+ let title = format!("Ghidrust {} CodeBrowser", env!("CARGO_PKG_VERSION"));
let opts = eframe::NativeOptions {
viewport: egui::ViewportBuilder::default()
.with_inner_size([1280.0, 800.0])
@@ -194,7 +201,7 @@ fn main() -> eframe::Result<()> {
/// The live layout is `center_dock` (`egui_dock`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum CenterPane {
- /// File summary + analysis counts (default after open/analyze).
+ /// File summary + analysis counts (default after open/analyze).
Overview,
Listing,
Decompiler,
@@ -225,7 +232,7 @@ impl From<CenterPane> for DockTab {
/// Renders center dock tabs by forwarding into `GhidrustApp` pane UIs.
struct CenterTabViewer<'a> {
- app: &'a mut GhidrustApp,
+ app: &'a mut GhidrustApp,
}
impl TabViewer for CenterTabViewer<'_> {
@@ -263,44 +270,44 @@ pub struct GhidrustApp {
last_analyzers_run: Vec<String>,
analyzer_enabled: Vec<bool>,
analyzer_infos: Vec<AnalyzerInfo>,
- /// Legacy focused-center shim (synced from `center_dock`).
+ /// Legacy focused-center shim (synced from `center_dock`).
center: CenterPane,
- /// IDE-style dock tree for Listing / Overview / Decompiler / DTM.
+ /// IDE-style dock tree for Listing / Overview / Decompiler / DTM.
center_dock: DockState<DockTab>,
show_project_tree: bool,
show_program_tree: bool,
show_symbol_tree: bool,
show_console: bool,
- /// Bottom dock (Grok/Console/Raw) height in points. Owned by us so the
- /// top-edge drag grip can resize reliably — egui's built-in
- /// `TopBottomPanel::resizable` snaps back unless content expands, which
- /// is easy to get wrong across versions.
+ /// Bottom dock (Grok/Console/Raw) height in points. Owned by us so the
+ /// top-edge drag grip can resize reliably — egui's built-in
+ /// `TopBottomPanel::resizable` snaps back unless content expands, which
+ /// is easy to get wrong across versions.
console_height: f32,
show_analysis_dialog: bool,
- /// Use experimental GPU bulk path for string/byte scan analyzers.
+ /// Use experimental GPU bulk path for string/byte scan analyzers.
use_gpu_experimental: bool,
- /// File id to open when user confirms analysis dialog (from Project Tree).
+ /// File id to open when user confirms analysis dialog (from Project Tree).
pending_analyze_file_id: Option<String>,
- /// Live analysis job (progress UI while stepping).
+ /// Live analysis job (progress UI while stepping).
analysis_job: Option<AnalysisJob>,
- /// Tree selection (may differ from active until Open).
+ /// Tree selection (may differ from active until Open).
tree_selected_id: Option<String>,
project_tree_expanded: bool,
- /// Pending delete: (file id, display name) — shown in confirm dialog.
+ /// Pending delete: (file id, display name) — shown in confirm dialog.
pending_delete: Option<(String, String)>,
- /// Dismissible banner after analysis finishes.
+ /// Dismissible banner after analysis finishes.
analysis_done_banner: Option<String>,
- /// RTTI panel filter (case-insensitive substring).
+ /// RTTI panel filter (case-insensitive substring).
rtti_filter: String,
rtti_filter_cache: String,
rtti_filtered_idx: Vec<usize>,
- /// Function list filter.
+ /// Function list filter.
fn_filter: String,
- /// First-run: pick/open a project before the empty shell.
+ /// First-run: pick/open a project before the empty shell.
show_startup_picker: bool,
recent_projects: Vec<String>,
nyi_note: Option<String>,
- // ── CodeBrowser selection / search / navigation (Ghidra-analog) ──────
+ // ── selection / search / navigation. ──────
listing_selection: ListingSelection,
undo_stack: Vec<ListingSelection>,
redo_stack: Vec<ListingSelection>,
@@ -316,106 +323,106 @@ pub struct GhidrustApp {
memory_hits: Vec<MemoryHit>,
text_hits: Vec<TextHit>,
show_processor_dialog: bool,
- /// Cached decompiler pseudo-C for the focused function entry (None = stale / empty).
+ /// Cached decompiler pseudo-C for the focused function entry (None = stale / empty).
decomp_entry: Option<u64>,
decomp_text: String,
decomp_status: String,
- /// Which decompile stage the Decompiler pane renders (Stage-0 / 0.5 / 1).
+ /// Which decompile stage the Decompiler pane renders (Stage-0 / 0.5 / 1).
decomp_stage: DecompStage,
- /// Last lift-coverage ratio (Stage-0.5 / Stage-1 only). Displayed as a
- /// small chip in the Decompiler pane header so users know how much of
- /// the emit came from real lifted IR vs Stage-0 scaffolding.
+ /// Last lift-coverage ratio (Stage-0.5 / Stage-1 only). Displayed as a
+ /// 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>,
- // ── Ghidra CodeBrowser visible parity ────────────────
- /// Open-state per-provider (Window menu toggles → floating egui::Window per pane).
+ // ── visible providers ─────────────
+ /// 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).
+ /// (Back / Forward / Alt+Left / Alt+Right).
nav_history: NavHistory,
- /// Guard so back()/forward() don't re-push into the history.
+ /// Guard so back/forward don't re-push into the history.
nav_suspended: bool,
- /// Bookmark table (5 Ghidra kinds).
+ /// Bookmark table (5 kinds).
bookmarks: Vec<Bookmark>,
- /// Filter for Bookmarks pane.
+ /// Filter for Bookmarks pane.
bookmark_filter: String,
- /// Add-bookmark dialog state.
+ /// Add-bookmark dialog state.
show_bookmark_dialog: bool,
bookmark_dialog_kind: BookmarkKind,
bookmark_dialog_category: String,
bookmark_dialog_description: String,
- /// Filter for Functions window (separate from Symbol Tree filter).
+ /// Filter for Functions window (separate from Symbol Tree filter).
functions_window_filter: String,
- /// Filter for Symbol Table window.
+ /// Filter for Symbol Table window.
symbol_table_filter: String,
- /// Filter for Defined Strings window.
+ /// Filter for Defined Strings window.
defined_strings_filter: String,
- /// Defined Strings encoding filter: `"all"` | `"ascii"` | `"utf16le"`.
+ /// Defined Strings encoding filter: `"all"` | `"ascii"` | `"utf16le"`.
defined_strings_encoding: String,
- /// plugin-event bus (Ghidra `PluginEvent` analog).
+ /// plugin-event bus .
event_bus: EventBus,
- /// tokenised decompiler cache (rebuilt after every refresh_decompiler_at).
+ /// tokenised decompiler cache (rebuilt after every refresh_decompiler_at).
decomp_lines: Vec<DecompLine>,
- /// 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>,
- /// middle-click "highlight all occurrences" state.
+ /// middle-click "highlight all occurrences" state.
decomp_highlight_text: Option<String>,
- /// Symbol Tree ↔ Listing selection navigation toggle.
+ /// Symbol Tree ↔ Listing selection navigation toggle.
symbol_tree_nav: bool,
- /// currently-focused function entry (for Symbol Tree highlight).
+ /// currently-focused function entry (for Symbol Tree highlight).
focused_function_entry: Option<u64>,
- /// 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>>,
- /// 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,
- /// Retype dialog state.
+ /// Retype dialog state.
show_retype_dialog: bool,
retype_dialog_target_va: Option<u64>,
retype_dialog_type: String,
- /// Comment dialog state.
+ /// Comment dialog state.
show_comment_dialog: bool,
comment_dialog_target_va: Option<u64>,
comment_dialog_kind: CommentKind,
comment_dialog_text: String,
- /// Function Signature dialog state.
+ /// Function Signature dialog state.
show_fn_signature_dialog: bool,
fn_signature_dialog_entry: Option<u64>,
fn_signature_dialog_text: String,
- /// 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,
- /// Edit-existing-type dialog state (Ghidra structure /
- /// union / enum / typedef editor).
+ /// Edit-existing-type dialog state (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,
- /// 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,
- /// DTM filter.
+ /// DTM filter.
dtm_filter: String,
- /// Comment Window filters (Ghidra `CommentWindowPlugin`).
+ /// Comment Window filters .
comment_window_filter: String,
comment_window_kind_filter: Option<CommentKind>,
- /// Console severity per line (`Info`, `Warn`, `Error`).
+ /// Console severity per line (`Info`, `Warn`, `Error`).
console_severity: Vec<ConsoleSeverity>,
- // ── tables & search state ────────────────────────────
- /// Byte Viewer state (Ghidra `ByteViewerPlugin`).
+ // ── tables & search state ────────────────────────────
+ /// Byte Viewer state .
bytes_pane_va: Option<u64>,
bytes_pane_bpr: usize,
bytes_pane_rows: usize,
- /// Filter for Symbol References pane (name / address substring).
+ /// Filter for Symbol References pane (name / address substring).
symbol_refs_filter: String,
- /// Symbol References focus (target VA) — set from Symbol Table row.
+ /// Symbol References focus (target VA) — set from Symbol Table row.
symbol_refs_target: Option<u64>,
- /// Hide IL2CPP resolve-stub source rows (`ghidrust_il2cpp::is_resolve_stub_va`).
+ /// Hide IL2CPP resolve-stub source rows (`ghidrust_il2cpp::is_resolve_stub_va`).
symbol_refs_hide_stubs: bool,
- /// Equates Table filters + edit dialog.
+ /// Equates Table filters + edit dialog.
equates_filter: String,
equates_selected: Option<(String, i64)>,
show_equate_dialog: bool,
@@ -423,76 +430,80 @@ pub struct GhidrustApp {
equate_dialog_op: u8,
equate_dialog_name: String,
equate_dialog_value: String,
- /// Function Tags — new-tag input + selected tag for row highlight.
+ /// Function Tags — new-tag input + selected tag for row highlight.
function_tags_new_input: String,
- /// External Programs filter.
+ /// External Programs filter.
external_programs_filter: String,
- /// Data Type Preview — selected built-in for preview.
+ /// Data Type Preview — selected built-in for preview.
data_type_preview_selected: String,
- /// Checksum Generator — cached results.
+ /// Checksum Generator — cached results.
checksum_last: Option<ChecksumReport>,
- /// Search → For Scalars.
+ /// Search → For Scalars.
show_search_scalars_dialog: bool,
search_scalars_min: String,
search_scalars_max: String,
- /// Search → Instruction Patterns.
+ /// Search → Instruction Patterns.
show_search_insn_dialog: bool,
search_insn_mnemonic: String,
search_insn_operands: String,
- /// Search → For Address Tables (populated on-demand).
+ /// Search → For Address Tables (populated on-demand).
show_search_address_tables_dialog: bool,
- /// Function Tags pane filter.
+ /// Function Tags pane filter.
function_tags_filter: String,
- // ── Graphs & maps ────────────────────────────────────
- /// Function Graph / Call Graph / Call Trees session state.
+ // ── Graphs & maps ────────────────────────────────────
+ /// Function Graph / Call Graph / Call Trees session state.
graph_state: GraphPaneState,
- /// Function Call Trees — top-level nodes (rebuilt on cursor change).
+ /// Function Call Trees — top-level nodes (rebuilt on cursor change).
call_tree_incoming: Vec<CallTreeNode>,
call_tree_outgoing: Vec<CallTreeNode>,
- /// Register Manager pane state (session-only until backend lattice lands).
+ /// Register Manager pane state (session-only until backend lattice lands).
register_manager: RegisterManagerState,
- /// Memory Map editor — pending row edits (Add row).
+ /// Memory Map editor — pending row edits (Add row).
memory_map_new_name: String,
memory_map_new_va: String,
memory_map_new_size: String,
memory_map_new_r: bool,
memory_map_new_w: bool,
memory_map_new_x: bool,
- // ── Scripts ──────────────────────────────────────────
- /// Script Manager pane state.
+ // ── Scripts ──────────────────────────────────────────
+ /// pane state.
script_manager: ScriptManagerState,
- /// Text Editor multi-tab state.
+ /// Text Editor multi-tab state.
text_editor: TextEditorState,
- /// MCP REPL state.
+ /// MCP REPL state.
mcp_repl: MacropadReplState,
- // ── Debugger visibility ──────────────────────────────
- /// Debugger tool state (breakpoints, watches, session-only until backend).
+ // ── Debugger visibility ──────────────────────────────
+ /// Debugger tool state (tabbed host + Live Process Bridge).
debugger: DebuggerState,
- /// Which debugger panes are open (Ghidra `Debugger` tool Window menu).
- debugger_open: BTreeMap<DebuggerPane, bool>,
- // ── Docking / layouts / Configure ───────────────────
- /// Configure dialog (Ghidra `File → Configure` plugin picker).
+ // ── Docking / layouts / Configure ───────────────────
+ /// Configure dialog .
show_configure_dialog: bool,
- /// Layout preset save/load dialog state.
+ /// Layout preset save/load dialog state.
show_layouts_dialog: bool,
layouts_new_name: String,
layouts_cached: Vec<String>,
- /// Current layout name (empty = unnamed / default).
+ /// Current layout name (empty = unnamed / default).
current_layout_name: String,
- // ── Grok Build agent console (Option C: ACP sidecar) ───────────────
- /// Per-window Grok pane state (session, transcript, install prompts, mode).
- /// One project per window means one session at a time; skill is auto-wired
- /// into `<project>/.grok/skills/` on project open; MCP/context on Start.
+ // ── Grok Build agent console (Option C: ACP sidecar) ───────────────
+ /// Per-window Grok pane state (session, transcript, install prompts, mode).
+ /// One project per window means one session at a time; skill is auto-wired
+ /// into `<project>/.grok/skills/` on project open; MCP/context on Start.
grok_pane: agent_pane::GrokPaneState,
- // ── Agent Friction Closure §13 — tool panes ─────────────────────────
- /// Session state for IL2CPP Metadata/Methods/ICalls, Install Inventory,
- /// File System Browser, Analysis Artifacts, and the GPU Decompile dialog.
+ // ── Agent Friction Closure §13 — tool panes ─────────────────────────
+ /// Session state for IL2CPP Metadata/Methods/ICalls, Install Inventory,
+ /// File System Browser, Analysis Artifacts, and the GPU Decompile dialog.
tool_panes: tool_panes::ToolPanesState,
- /// Analysis → GPU Decompile… dialog visibility.
+ /// Analysis → GPU Decompile… dialog visibility.
show_gpu_decompile_dialog: bool,
+ /// decode options for Listing / Disassembled View.
+ decode_opts: DecodeUiOpts,
+ /// Listing mnemonic / id / group filter.
+ listing_search: ListingSearch,
+ /// Full decode options dialog (arch/mode and engine options).
+ show_decode_options_dialog: bool,
}
-/// Checksum Generator report (Ghidra `ComputeChecksumsPlugin`).
+/// Checksum Generator report .
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ChecksumReport {
pub target: String,
@@ -514,16 +525,16 @@ enum ConsoleSeverity {
Error,
}
-/// Checksum Generator scope (Ghidra `ComputeChecksumsPlugin`).
+/// Checksum Generator scope .
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ChecksumMode {
- /// Concatenation of every loaded memory block.
+ /// Concatenation of every loaded memory block.
WholeImage,
- /// A single memory block chosen by name.
+ /// A single memory block chosen by name.
Section(String),
}
-/// CRC-32/ISO-HDLC (polynomial `0xEDB88320`) — matches Ghidra's default.
+/// CRC-32/ISO-HDLC (polynomial `0xEDB88320`) — matches default.
fn crc32_ieee(data: &[u8]) -> u32 {
let mut c: u32 = 0xFFFF_FFFF;
for &b in data {
@@ -575,40 +586,15 @@ enum NewTypeKind {
FunctionDefinition,
}
-/// one rendered Listing row (Ghidra `CodeUnit` columns).
-#[derive(Debug, Clone)]
-struct ListingRow {
- idx: usize,
- va: u64,
- bytes_hex: String,
- mnem: String,
- ops: String,
- is_ret: bool,
- is_uncond: bool,
- is_cond: bool,
- is_call: bool,
- applied_type: Option<String>,
- /// Ghidra `EOL` comment (rendered inline after operands).
- comment_eol: Option<String>,
- /// Ghidra `Plate` comment (rendered before the mnemonic as a banner).
- comment_plate: Option<String>,
- /// Ghidra `Pre` comment (rendered as its own row before this insn).
- comment_pre: Option<String>,
- /// Ghidra `Post` comment (rendered as its own row after this insn).
- comment_post: Option<String>,
- /// Ghidra `Repeatable` comment (rendered inline like EOL but italicised).
- comment_repeat: Option<String>,
-}
-
-/// Ghidra scalar hover popup content for a Listing operand string.
+/// 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").
+/// interpretations (matches "Scalar popup").
fn first_scalar_hint(operands: &str) -> Option<String> {
let mut chars = operands.char_indices().peekable();
while let Some((i, c)) = chars.next() {
- if c == '0'
- && operands.as_bytes().get(i + 1) == Some(&b'x')
+ if c == '0'
+ && operands.as_bytes().get(i + 1) == Some(&b'x')
{
let start = i + 2;
let end = operands[start..]
@@ -644,15 +630,15 @@ fn scalar_hint_string(v: u64) -> String {
.map(|&b| b as char)
.collect();
format!(
- "scalar {v:#x} · dec {v} · i32 {}{} · ascii \"{ascii}\"",
- if (v as i32) < 0 { "" } else { "" },
+ "scalar {v:#x} · dec {v} · i32 {}{} · ascii \"{ascii}\"",
+ if (v as i32) < 0 { "" } else { "" },
v as i32
)
}
-/// Ghidra address hover popup content for a Listing operand string.
+/// address hover popup content for a Listing operand string.
fn first_address_hint(operands: &str) -> Option<String> {
- let idx = operands.find("0x")?;
+ let idx = operands.find("0x")?;
let start = idx + 2;
let end = operands[start..]
.find(|c: char| !c.is_ascii_hexdigit())
@@ -662,34 +648,34 @@ fn first_address_hint(operands: &str) -> Option<String> {
return None;
}
let va = u64::from_str_radix(&operands[start..end], 16).ok()?;
- Some(format!("target addr {va:#x}"))
+ Some(format!("target addr {va:#x}"))
}
-/// Ghidra `ClangToken`-analog syntax colour picker for the Decompiler pane.
+/// ``- syntax colour picker for the Decompiler pane.
fn token_style(kind: &TokenKind, base: Color32) -> (Color32, bool) {
match kind {
- // Keywords: cyan (Ghidra "colors.decompiler.keyword").
+ // Keywords: cyan .
TokenKind::Keyword => (Color32::from_rgb(0x64, 0xB5, 0xF6), false),
- // Function names: warm orange.
+ // Function names: warm orange.
TokenKind::Function => (Color32::from_rgb(0xFF, 0xB7, 0x4D), false),
- // Variables: white/text default.
+ // Variables: white/text default.
TokenKind::Variable => (base, false),
- // Block labels: purple.
+ // Block labels: purple.
TokenKind::Label => (Color32::from_rgb(0xBA, 0x68, 0xC8), false),
- // Addresses: cyan for click-hint.
+ // Addresses: cyan for click-hint.
TokenKind::Address => (Color32::from_rgb(0x4D, 0xD0, 0xE1), false),
- // Constants: lighter cyan.
+ // Constants: lighter cyan.
TokenKind::Constant => (Color32::from_rgb(0x80, 0xDE, 0xEA), false),
- // Comments: green italics.
+ // Comments: green italics.
TokenKind::Comment => (Color32::from_rgb(0x81, 0xC7, 0x84), true),
- // Syntax / whitespace / newline: dimmed text.
+ // Syntax / whitespace / newline: dimmed text.
TokenKind::Syntax => (base.gamma_multiply(0.85), false),
TokenKind::Whitespace | TokenKind::Newline => (base, false),
}
}
impl NewTypeKind {
- const ALL: &'static [NewTypeKind] = &[
+ const ALL: &'static [NewTypeKind] = &[
NewTypeKind::Structure,
NewTypeKind::Union,
NewTypeKind::Enum,
@@ -697,35 +683,35 @@ impl NewTypeKind {
NewTypeKind::FunctionDefinition,
];
- const fn label(self) -> &'static str {
+ const fn label(self) -> &'static str {
match self {
- NewTypeKind::Structure => "Structure",
- NewTypeKind::Union => "Union",
- NewTypeKind::Enum => "Enum",
- NewTypeKind::Typedef => "Typedef",
- NewTypeKind::FunctionDefinition => "Function Definition",
+ NewTypeKind::Structure => "Structure",
+ NewTypeKind::Union => "Union",
+ NewTypeKind::Enum => "Enum",
+ NewTypeKind::Typedef => "Typedef",
+ NewTypeKind::FunctionDefinition => "Function Definition",
}
}
- const fn template(self) -> &'static str {
+ const fn template(self) -> &'static str {
match self {
- NewTypeKind::Structure => "// Ghidrust user structure.\n// One field per line: `type name` (Stage-0 stores as string).\nint32_t field_0;\n",
- NewTypeKind::Union => "// Ghidrust user union.\nint32_t as_int;\nfloat as_float;\n",
- NewTypeKind::Enum => "// Ghidrust user enum. `NAME = <value>` per line.\nA = 0,\nB = 1,\n",
- NewTypeKind::Typedef => "// Ghidrust typedef body: target type only.\nvoid *\n",
- NewTypeKind::FunctionDefinition => "// Ghidrust function definition: `ret (params)`.\nint (int, char *)\n",
+ NewTypeKind::Structure => "// Ghidrust user structure.\n// One field per line: `type name` (Stage-0 stores as string).\nint32_t field_0;\n",
+ NewTypeKind::Union => "// Ghidrust user union.\nint32_t as_int;\nfloat as_float;\n",
+ NewTypeKind::Enum => "// Ghidrust user enum. `NAME = <value>` per line.\nA = 0,\nB = 1,\n",
+ NewTypeKind::Typedef => "// Ghidrust typedef body: target type only.\nvoid *\n",
+ NewTypeKind::FunctionDefinition => "// Ghidrust function definition: `ret (params)`.\nint (int, char *)\n",
}
}
}
-/// Recursively render one Ghidra-style Call Tree row.
+/// Recursively render one Call Tree row.
///
/// The node's `children_loaded` flag is flipped on first expand so callers
/// pay the xref cost only when the user opens a branch.
fn render_call_tree_node(
node: &mut CallTreeNode,
idx: usize,
- direction: &'static str,
+ direction: &'static str,
prog: &Program,
hide_thunks: bool,
ui: &mut egui::Ui,
@@ -733,7 +719,7 @@ fn render_call_tree_node(
primary: Color32,
goto: &mut Option<u64>,
) {
- let title = egui::RichText::new(format!("{} {:#x}", node.name, node.va)).monospace();
+ let title = egui::RichText::new(format!("{} {:#x}", node.name, node.va)).monospace();
let title = if node.is_thunk {
title.color(Color32::from_rgb(0xFB, 0xC0, 0x2D))
} else {
@@ -745,7 +731,7 @@ fn render_call_tree_node(
.show(ui, |ui| {
expand_tree_node(node, prog, direction, hide_thunks);
if node.children.is_empty() {
- ui.small("(no further edges)");
+ ui.small("(no further edges)");
return;
}
for (i, child) in node.children.iter_mut().enumerate() {
@@ -755,19 +741,19 @@ fn render_call_tree_node(
}
});
if resp.header_response.clicked() {
- *goto = Some(node.va);
+ *goto = Some(node.va);
}
}
impl GhidrustApp {
- pub fn new(cc: &eframe::CreationContext<'_>) -> Self {
- // Cascadia/Consolas + symbol fallbacks so the Grok TUI logo/box-drawing
- // aren't tofu (▯) under egui's tiny default monospace.
+ pub fn new(cc: &eframe::CreationContext<'_>) -> Self {
+ // Cascadia/Consolas + symbol fallbacks so the Grok TUI logo/box-drawing
+ // aren't tofu (▯) under egui's tiny default monospace.
grok_term::install_terminal_fonts(&cc.egui_ctx);
let mut app = Self::headless();
app.recent_projects = load_recent_projects();
app.show_startup_picker = true;
- app.status = "Select a project to begin".into();
+ app.status = "Select a project to begin".into();
app.apply_theme(&cc.egui_ctx);
app
}
@@ -778,9 +764,9 @@ impl GhidrustApp {
Self {
path_input: String::new(),
project_dir_input: String::new(),
- project_name_input: "MyProject".into(),
- status: "Ready — File → New/Open Project, then Import binary".into(),
- console: vec!["Ghidrust CodeBrowser started.".into()],
+ project_name_input: "MyProject".into(),
+ status: "Ready — File → New/Open Project, then Import binary".into(),
+ console: vec!["Ghidrust CodeBrowser started.".into()],
theme: ThemeMode::Dark,
project: None,
active_file_id: None,
@@ -832,10 +818,10 @@ impl GhidrustApp {
decomp_entry: None,
decomp_text: String::new(),
decomp_status: String::new(),
- // 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.
+ // Stage-1 is now the default GUI decompiler stage —
+ // real SSA + structure + types instead of the mnemonic-scaffold
+ // Stage-0 preview. Users can still pick Stage-0/Stage-0.5 from
+ // the stage picker combo box.
decomp_stage: DecompStage::Stage1,
decomp_lift_ratio: None,
pane_open: Self::default_pane_open(),
@@ -850,7 +836,7 @@ impl GhidrustApp {
functions_window_filter: String::new(),
symbol_table_filter: String::new(),
defined_strings_filter: String::new(),
- defined_strings_encoding: "all".into(),
+ defined_strings_encoding: "all".into(),
event_bus: EventBus::new(),
decomp_lines: Vec::new(),
decomp_cross_line: None,
@@ -902,11 +888,11 @@ impl GhidrustApp {
equate_dialog_value: String::new(),
function_tags_new_input: String::new(),
external_programs_filter: String::new(),
- data_type_preview_selected: "dword".into(),
+ data_type_preview_selected: "dword".into(),
checksum_last: None,
show_search_scalars_dialog: false,
- search_scalars_min: "0".into(),
- search_scalars_max: "0xffff".into(),
+ search_scalars_min: "0".into(),
+ search_scalars_max: "0xffff".into(),
show_search_insn_dialog: false,
search_insn_mnemonic: String::new(),
search_insn_operands: String::new(),
@@ -929,13 +915,6 @@ impl GhidrustApp {
text_editor: TextEditorState::default(),
mcp_repl: MacropadReplState::default(),
debugger: DebuggerState::default(),
- debugger_open: {
- let mut m = BTreeMap::new();
- for p in DebuggerPane::ALL {
- m.insert(*p, false);
- }
- m
- },
show_configure_dialog: false,
show_layouts_dialog: false,
layouts_new_name: String::new(),
@@ -944,11 +923,14 @@ impl GhidrustApp {
grok_pane: agent_pane::GrokPaneState::new(),
tool_panes: tool_panes::ToolPanesState::default(),
show_gpu_decompile_dialog: false,
+ decode_opts: DecodeUiOpts::default(),
+ listing_search: ListingSearch::default(),
+ show_decode_options_dialog: false,
}
}
- /// Default `Window → *` toggles. Everything is available; only well-supported panes
- /// float open by default so users see the full CodeBrowser surface but aren't buried.
+ /// Default `Window → *` toggles. Everything is available; only well-supported panes
+ /// float open by default so users see the full surface but aren't buried.
fn default_pane_open() -> BTreeMap<PaneKind, bool> {
let mut m = BTreeMap::new();
for k in PaneKind::ALL {
@@ -957,14 +939,14 @@ impl GhidrustApp {
m
}
- /// Toggle a floating provider window (used by `Window` menu + toolbar shortcuts).
+ /// Toggle a floating provider window (used by `Window` menu + toolbar shortcuts).
pub fn toggle_pane(&mut self, kind: PaneKind, open: bool) {
self.pane_open.insert(kind, open);
}
- /// Whether the given provider is currently visible.
+ /// Whether the given provider is currently visible.
pub fn is_pane_open(&self, kind: PaneKind) -> bool {
- *self.pane_open.get(&kind).unwrap_or(&false)
+ *self.pane_open.get(&kind).unwrap_or(&false)
}
fn clear_decompiler_cache(&mut self) {
@@ -976,19 +958,19 @@ impl GhidrustApp {
self.decomp_lift_ratio = None;
}
- /// Refresh the decompiler cache for `va` (containing / nearest function)
- /// at the currently-selected [`DecompStage`] (Stage-0 / 0.5 / 1).
- ///
- /// Also rebuilds the tokenised `decomp_lines` cache used by the pane for
- /// click-navigation and cross-highlight with the Listing. If Stage-0.5
- /// / Stage-1 fail (e.g. structuring gave up on an irreducible region)
- /// the pane silently falls back to Stage-0 so the user always sees
- /// something.
+ /// Refresh the decompiler cache for `va` (containing / nearest function)
+ /// at the currently-selected [`DecompStage`] (Stage-0 / 0.5 / 1).
+ ///
+ /// Also rebuilds the tokenised `decomp_lines` cache used by the pane for
+ /// click-navigation and cross-highlight with the Listing. If Stage-0.5
+ /// / Stage-1 fail (e.g. structuring gave up on an irreducible region)
+ /// the pane silently falls back to Stage-0 so the user always sees
+ /// something.
pub fn refresh_decompiler_at(&mut self, va: u64) {
let Some(prog) = self.program.as_ref() else {
self.decomp_entry = None;
self.decomp_text.clear();
- self.decomp_status = "No program loaded.".into();
+ self.decomp_status = "No program loaded.".into();
self.decomp_lines.clear();
self.decomp_cross_line = None;
self.decomp_lift_ratio = None;
@@ -1003,7 +985,7 @@ impl GhidrustApp {
return;
}
let stage = self.decomp_stage;
- // R5: Stage-1 prefers emit-time tokens when present.
+ // 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)
@@ -1025,10 +1007,10 @@ impl GhidrustApp {
.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}%",
+ "Stage-1 · {name} @ {entry:#x} · lift={:.1}%",
ratio * 100.0
),
- None => format!("Stage-1 · {entry:#x} · lift={:.1}%", ratio * 100.0),
+ None => format!("Stage-1 · {entry:#x} · lift={:.1}%", ratio * 100.0),
};
return;
}
@@ -1037,7 +1019,7 @@ impl GhidrustApp {
let (label, result) = match attempt {
Ok(v) => (stage.label(), Ok(v)),
Err(_) if stage != DecompStage::Stage0 => {
- // Never render an empty pane — retry at Stage-0.
+ // Never render an empty pane — retry at Stage-0.
let fallback = stage0_pseudo_c(prog, va, STAGE0_MAX_INSNS)
.map(|(e, t)| (e, t, None));
(DecompStage::Stage0.label(), fallback)
@@ -1057,30 +1039,30 @@ impl GhidrustApp {
.and_then(|p| p.display_function_name_at(entry));
self.decomp_status = match (user_name, ratio) {
(Some(name), Some(r)) => format!(
- "{label} · {name} @ {entry:#x} · lift={:.1}%",
+ "{label} · {name} @ {entry:#x} · lift={:.1}%",
r * 100.0
),
- (Some(name), None) => format!("{label} · {name} @ {entry:#x}"),
+ (Some(name), None) => format!("{label} · {name} @ {entry:#x}"),
(None, Some(r)) => {
- format!("{label} · {entry:#x} · lift={:.1}%", r * 100.0)
+ format!("{label} · {entry:#x} · lift={:.1}%", r * 100.0)
}
- (None, None) => format!("{label} · {entry:#x}"),
+ (None, None) => format!("{label} · {entry:#x}"),
};
}
Err(e) => {
self.decomp_entry = Some(entry);
- self.decomp_text = format!("// decompile failed at {entry:#x}\n// {e}\n");
+ self.decomp_text = format!("// decompile failed at {entry:#x}\n// {e}\n");
self.decomp_lines = tokenize_decomp(&self.decomp_text);
self.decomp_cross_line = None;
self.decomp_lift_ratio = None;
- self.decomp_status = format!("error: {e}");
+ self.decomp_status = format!("error: {e}");
}
}
}
- /// Switch the active decompile stage (Stage-0 / 0.5 / 1) and re-run the
- /// emit for the currently-focused function entry. Public so the pane
- /// dropdown + tests can drive it.
+ /// Switch the active decompile stage (Stage-0 / 0.5 / 1) and re-run the
+ /// emit for the currently-focused function entry. Public so the pane
+ /// dropdown + tests can drive it.
pub fn set_decomp_stage(&mut self, stage: DecompStage) {
if self.decomp_stage == stage {
return;
@@ -1095,17 +1077,17 @@ impl GhidrustApp {
}
}
- /// Current decompile stage — used by the pane header dropdown and tests.
+ /// Current decompile stage — used by the pane header dropdown and tests.
pub fn decomp_stage(&self) -> DecompStage {
self.decomp_stage
}
- /// Latest lift coverage ratio (Stage-0.5 / Stage-1 only).
+ /// Latest lift coverage ratio (Stage-0.5 / Stage-1 only).
pub fn decomp_lift_ratio(&self) -> Option<f32> {
self.decomp_lift_ratio
}
- /// Focus a center dock tab. Listing/Decompiler prefer a side-by-side split.
+ /// Focus a center dock tab. Listing/Decompiler prefer a side-by-side split.
fn focus_center_tab(&mut self, tab: DockTab) {
match tab {
DockTab::Listing | DockTab::Decompiler => {
@@ -1124,11 +1106,11 @@ impl GhidrustApp {
.into();
}
- /// Symbol Tree / Navigation: focus a function entry in Listing and update Decompiler.
+ /// Symbol Tree / Navigation: focus a function entry in Listing and update Decompiler.
pub fn focus_function(&mut self, entry: u64) {
- let addr = format!("{entry:#x}");
+ let addr = format!("{entry:#x}");
if let Err(e) = self.goto_address_str(&addr) {
- self.status = format!("error: {e}");
+ self.status = format!("error: {e}");
self.log_error(self.status.clone());
return;
}
@@ -1139,57 +1121,57 @@ impl GhidrustApp {
.program
.as_ref()
.and_then(|p| p.display_function_name_at(entry))
- .unwrap_or_else(|| format!("{entry:#x}"));
- self.status = format!("Function {name}");
+ .unwrap_or_else(|| format!("{entry:#x}"));
+ self.status = format!("Function {name}");
self.log(self.status.clone());
}
- /// Navigation → Back (Alt+Left).
- ///
- /// Pops the previous location off the Back stack and re-runs `goto_address_str`
- /// without recording another entry (guarded by `nav_suspended`).
+ /// Navigation → Back (Alt+Left).
+ ///
+ /// Pops the previous location off the Back stack and re-runs `goto_address_str`
+ /// without recording another entry (guarded by `nav_suspended`).
pub fn nav_back(&mut self) -> bool {
let Some(prev) = self.nav_history.back() else {
- self.status = "Navigation → nothing to go back to".into();
+ self.status = "Navigation → nothing to go back to".into();
self.log(self.status.clone());
return false;
};
self.nav_suspended = true;
- let r = self.goto_address_str(&format!("{:#x}", prev.va));
+ let r = self.goto_address_str(&format!("{:#x}", prev.va));
self.nav_suspended = false;
if let Err(e) = r {
- self.status = format!("error: {e}");
+ self.status = format!("error: {e}");
self.log(self.status.clone());
return false;
}
self.refresh_decompiler_at(prev.va);
- self.status = format!("Back → {:#x}", prev.va);
+ self.status = format!("Back → {:#x}", prev.va);
self.log(self.status.clone());
true
}
- /// Navigation → Forward (Alt+Right).
+ /// Navigation → Forward (Alt+Right).
pub fn nav_forward(&mut self) -> bool {
let Some(next) = self.nav_history.forward() else {
- self.status = "Navigation → nothing to go forward to".into();
+ self.status = "Navigation → nothing to go forward to".into();
self.log(self.status.clone());
return false;
};
self.nav_suspended = true;
- let r = self.goto_address_str(&format!("{:#x}", next.va));
+ let r = self.goto_address_str(&format!("{:#x}", next.va));
self.nav_suspended = false;
if let Err(e) = r {
- self.status = format!("error: {e}");
+ self.status = format!("error: {e}");
self.log(self.status.clone());
return false;
}
self.refresh_decompiler_at(next.va);
- self.status = format!("Forward → {:#x}", next.va);
+ self.status = format!("Forward → {:#x}", next.va);
self.log(self.status.clone());
true
}
- /// Convenience: are we able to step back?
+ /// Convenience: are we able to step back?
pub fn can_nav_back(&self) -> bool {
self.nav_history.can_back()
}
@@ -1197,7 +1179,7 @@ impl GhidrustApp {
self.nav_history.can_forward()
}
- /// Bookmarks → Add (BookmarkPlugin analog). Va + kind + category + description.
+ /// Bookmarks → Add (BookmarkPlugin analog). Va + kind + category + description.
pub fn add_bookmark(
&mut self,
va: u64,
@@ -1215,11 +1197,11 @@ impl GhidrustApp {
self.event_bus.publish(GhidrustEvent::ProgramMutated {
kind: MutationKind::BookmarkAdded { va },
});
- self.status = format!("Bookmark added at {va:#x} ({})", kind.label());
+ self.status = format!("Bookmark added at {va:#x} ({})", kind.label());
self.log(self.status.clone());
}
- /// Bookmarks → Delete.
+ /// Bookmarks → Delete.
pub fn delete_bookmark(&mut self, index: usize) {
if index < self.bookmarks.len() {
let b = self.bookmarks.remove(index);
@@ -1227,20 +1209,20 @@ impl GhidrustApp {
self.event_bus.publish(GhidrustEvent::ProgramMutated {
kind: MutationKind::BookmarkRemoved { va },
});
- self.status = format!("Bookmark removed at {va:#x} ({})", b.kind.label());
+ self.status = format!("Bookmark removed at {va:#x} ({})", b.kind.label());
self.log(self.status.clone());
}
}
- /// Look up bookmarks at (or covering) `va` for margin-marker rendering.
+ /// Look up bookmarks at (or covering) `va` for margin-marker rendering.
pub fn bookmarks_at(&self, va: u64) -> Vec<&Bookmark> {
self.bookmarks.iter().filter(|b| b.va == va).collect()
}
- /// Navigation → Next Bookmark.
+ /// Navigation → Next Bookmark.
pub fn nav_next_bookmark(&mut self) {
if self.bookmarks.is_empty() {
- self.status = "No bookmarks — Bookmarks → Add".into();
+ self.status = "No bookmarks — Bookmarks → Add".into();
self.log(self.status.clone());
return;
}
@@ -1248,16 +1230,16 @@ impl GhidrustApp {
let mut vas: Vec<u64> = self.bookmarks.iter().map(|b| b.va).collect();
vas.sort();
if let Some(va) = vas.iter().copied().find(|&va| va > cur) {
- let _ = self.goto_address_str(&format!("{va:#x}"));
+ let _ = self.goto_address_str(&format!("{va:#x}"));
} else {
- let _ = self.goto_address_str(&format!("{:#x}", vas[0]));
+ let _ = self.goto_address_str(&format!("{:#x}", vas[0]));
}
}
- /// Navigation → Previous Bookmark.
+ /// Navigation → Previous Bookmark.
pub fn nav_prev_bookmark(&mut self) {
if self.bookmarks.is_empty() {
- self.status = "No bookmarks — Bookmarks → Add".into();
+ self.status = "No bookmarks — Bookmarks → Add".into();
self.log(self.status.clone());
return;
}
@@ -1265,37 +1247,37 @@ impl GhidrustApp {
let mut vas: Vec<u64> = self.bookmarks.iter().map(|b| b.va).collect();
vas.sort();
if let Some(va) = vas.iter().rev().copied().find(|&va| va < cur) {
- let _ = self.goto_address_str(&format!("{va:#x}"));
+ let _ = self.goto_address_str(&format!("{va:#x}"));
} else {
- let _ = self.goto_address_str(&format!("{:#x}", vas.last().copied().unwrap()));
+ let _ = self.goto_address_str(&format!("{:#x}", vas.last().copied().unwrap()));
}
}
- // ── user edits ───────────────────────────────────────
+ // ── user edits ───────────────────────────────────────
- /// Rename the symbol / function at `va` (persists into `Program::edits`).
- ///
- /// Also mirrors the rename into `Program::analysis.functions[i].name` so
- /// every downstream pane (Symbol Tree, Functions Window, Symbol Table,
- /// Bookmarks label preview) sees the new name without a full re-analyze.
- /// Emits a `ProgramMutated::Rename` event which invalidates the Decompiler
- /// cache so the header string is rebuilt.
+ /// Rename the symbol / function at `va` (persists into `Program::edits`).
+ ///
+ /// Also mirrors the rename into `Program::analysis.functions[i].name()` so
+ /// every downstream pane (Symbol Tree, Functions Window, Symbol Table,
+ /// Bookmarks label preview) sees the new name without a full re-analyze.
+ /// Emits a `ProgramMutated::Rename` event which invalidates the Decompiler
+ /// cache so the header string is rebuilt.
pub fn rename_at(&mut self, va: u64, new_name: impl Into<String>) -> Result<(), String> {
let new_name = new_name.into();
if new_name.trim().is_empty() {
- return Err("empty name".into());
+ return Err("empty name".into());
}
let prog = self
.program
.as_mut()
- .ok_or_else(|| "no program loaded".to_string())?;
- // Mirror into analysis so tables / listing / decomp header pick it up.
+ .ok_or_else(|| "no program loaded".to_string())?;
+ // Mirror into analysis so tables / listing / decomp header pick it up.
if let Some(f) = prog.function_at_mut(va) {
f.name = new_name.clone();
} else if let Some(s) = prog.analysis.symbols.iter_mut().find(|s| s.va == va) {
s.name = new_name.clone();
}
- // Persist as an edit even if analysis had no matching entry.
+ // Persist as an edit even if analysis had no matching entry.
prog.edits.set_rename(va, &new_name);
self.event_bus.publish(GhidrustEvent::ProgramMutated {
kind: MutationKind::Rename {
@@ -1303,18 +1285,18 @@ impl GhidrustApp {
new_name: new_name.clone(),
},
});
- self.status = format!("Renamed {va:#x} → {new_name}");
+ self.status = format!("Renamed {va:#x} → {new_name}");
self.log(self.status.clone());
Ok(())
}
- /// Retype the variable / global at `va` (persists into `Program::edits`).
+ /// Retype the variable / global at `va` (persists into `Program::edits`).
pub fn retype_at(&mut self, va: u64, type_desc: impl Into<String>) -> Result<(), String> {
let type_desc = type_desc.into();
let prog = self
.program
.as_mut()
- .ok_or_else(|| "no program loaded".to_string())?;
+ .ok_or_else(|| "no program loaded".to_string())?;
prog.edits.set_retype(va, &type_desc);
self.event_bus.publish(GhidrustEvent::ProgramMutated {
kind: MutationKind::Retype {
@@ -1322,12 +1304,12 @@ impl GhidrustApp {
type_desc: type_desc.clone(),
},
});
- self.status = format!("Retyped {va:#x} → {type_desc}");
+ self.status = format!("Retyped {va:#x} → {type_desc}");
self.log(self.status.clone());
Ok(())
}
- /// Set (or clear) a comment at `va` (persists into `Program::edits`).
+ /// Set (or clear) a comment at `va` (persists into `Program::edits`).
pub fn set_comment_at(
&mut self,
va: u64,
@@ -1338,21 +1320,21 @@ impl GhidrustApp {
let prog = self
.program
.as_mut()
- .ok_or_else(|| "no program loaded".to_string())?;
+ .ok_or_else(|| "no program loaded".to_string())?;
prog.edits.set_comment(va, kind, &text);
self.event_bus.publish(GhidrustEvent::ProgramMutated {
kind: MutationKind::CommentChanged { va },
});
self.status = if text.is_empty() {
- format!("Cleared {} comment at {va:#x}", kind.label())
+ format!("Cleared {} comment at {va:#x}", kind.label())
} else {
- format!("Set {} comment at {va:#x}", kind.label())
+ format!("Set {} comment at {va:#x}", kind.label())
};
self.log(self.status.clone());
Ok(())
}
- /// Set / replace a function signature (Edit Function Signature dialog).
+ /// Set / replace a function signature (Edit Function Signature dialog).
pub fn set_function_signature(
&mut self,
entry: u64,
@@ -1362,7 +1344,7 @@ impl GhidrustApp {
let prog = self
.program
.as_mut()
- .ok_or_else(|| "no program loaded".to_string())?;
+ .ok_or_else(|| "no program loaded".to_string())?;
let mut sig = prog
.edits
.function_signature(entry)
@@ -1376,72 +1358,72 @@ impl GhidrustApp {
type_desc: signature.clone(),
},
});
- self.status = format!("Function signature @ {entry:#x} → {signature}");
+ self.status = format!("Function signature @ {entry:#x} → {signature}");
self.log(self.status.clone());
Ok(())
}
- /// Decompiler → Commit Params/Return. Adopts the analyzer-inferred parameter
- /// list + a "auto" return type as user commitments.
+ /// Decompiler → Commit Params/Return. Adopts the analyzer-inferred parameter
+ /// list + a "auto" return type as user commitments.
pub fn commit_params_return(&mut self, entry: u64) -> Result<(), String> {
let prog = self
.program
.as_mut()
- .ok_or_else(|| "no program loaded".to_string())?;
+ .ok_or_else(|| "no program loaded".to_string())?;
let (params, ret) = {
let f = prog
.function_at(entry)
- .ok_or_else(|| format!("no function at {entry:#x}"))?;
+ .ok_or_else(|| format!("no function at {entry:#x}"))?;
let params: Vec<String> = if f.parameters.is_empty() {
Vec::new()
} else {
f.parameters.clone()
};
- // Ghidrust Stage-0 has no dataflow return-type yet — commit as `undefined`.
- (params, "undefined".to_string())
+ // Ghidrust Stage-0 has no dataflow return-type yet — commit as `undefined`.
+ (params, "undefined".to_string())
};
prog.edits.commit_params(entry, params.clone());
prog.edits.commit_return_type(entry, &ret);
self.event_bus.publish(GhidrustEvent::ProgramMutated {
kind: MutationKind::Retype {
va: entry,
- type_desc: format!("commit params: {} · return {ret}", params.len()),
+ type_desc: format!("commit params: {} · return {ret}", params.len()),
},
});
self.status = format!(
- "Commit Params/Return @ {entry:#x} ({} param(s), return {ret})",
+ "Commit Params/Return @ {entry:#x} ({} param(s), return {ret})",
params.len()
);
self.log(self.status.clone());
Ok(())
}
- /// Decompiler → Commit Locals. Persists analyzer-inferred stack locals as
- /// user edits so a later rename doesn't require re-analyzing.
+ /// Decompiler → Commit Locals. Persists analyzer-inferred stack locals as
+ /// user edits so a later rename doesn't require re-analyzing.
pub fn commit_locals(&mut self, entry: u64) -> Result<(), String> {
let prog = self
.program
.as_mut()
- .ok_or_else(|| "no program loaded".to_string())?;
+ .ok_or_else(|| "no program loaded".to_string())?;
let locals = {
let f = prog
.function_at(entry)
- .ok_or_else(|| format!("no function at {entry:#x}"))?;
+ .ok_or_else(|| format!("no function at {entry:#x}"))?;
f.stack_locals.clone()
};
prog.edits.commit_locals(entry, locals.clone());
self.event_bus.publish(GhidrustEvent::ProgramMutated {
kind: MutationKind::Retype {
va: entry,
- type_desc: format!("commit locals: {}", locals.len()),
+ type_desc: format!("commit locals: {}", locals.len()),
},
});
- self.status = format!("Commit Locals @ {entry:#x} ({} local(s))", locals.len());
+ self.status = format!("Commit Locals @ {entry:#x} ({} local(s))", locals.len());
self.log(self.status.clone());
Ok(())
}
- /// Data Type Manager → New Structure / Union / Enum / Typedef / Function Def.
+ /// Data Type Manager → New Structure / Union / Enum / Typedef / Function Def.
pub fn define_user_type(
&mut self,
name: impl Into<String>,
@@ -1450,31 +1432,31 @@ impl GhidrustApp {
let name = name.into();
let body = body.into();
if name.trim().is_empty() {
- return Err("empty type name".into());
+ return Err("empty type name".into());
}
let prog = self
.program
.as_mut()
- .ok_or_else(|| "no program loaded".to_string())?;
+ .ok_or_else(|| "no program loaded".to_string())?;
prog.edits.set_user_type(name.clone(), body);
self.event_bus.publish(GhidrustEvent::ProgramMutated {
kind: MutationKind::Retype {
va: 0,
- type_desc: format!("user type: {name}"),
+ type_desc: format!("user type: {name}"),
},
});
- self.status = format!("New type: {name}");
+ self.status = format!("New type: {name}");
self.log(self.status.clone());
Ok(())
}
- /// Listing → Apply Data Type at `va` (drag from DTM, or `T` key).
+ /// Listing → Apply Data Type at `va` (drag from DTM, or `T` key).
pub fn apply_type_at(&mut self, va: u64, type_name: impl Into<String>) -> Result<(), String> {
let type_name = type_name.into();
let prog = self
.program
.as_mut()
- .ok_or_else(|| "no program loaded".to_string())?;
+ .ok_or_else(|| "no program loaded".to_string())?;
prog.edits.set_applied_type(va, &type_name);
self.event_bus.publish(GhidrustEvent::ProgramMutated {
kind: MutationKind::Retype {
@@ -1482,13 +1464,13 @@ impl GhidrustApp {
type_desc: type_name.clone(),
},
});
- self.status = format!("Applied type {type_name} @ {va:#x}");
+ self.status = format!("Applied type {type_name} @ {va:#x}");
self.log(self.status.clone());
Ok(())
}
- /// DTM → Rename an existing user type (Ghidra `Rename` on a Data Type
- /// leaf). Rewrites `applied_types` so Listing decorations stay in sync.
+ /// DTM → Rename an existing user type (`Rename` on a Data Type
+ /// leaf). Rewrites `applied_types` so Listing decorations stay in sync.
pub fn rename_user_type(
&mut self,
old: impl Into<String>,
@@ -1497,48 +1479,48 @@ impl GhidrustApp {
let old = old.into();
let new = new.into();
if new.trim().is_empty() {
- return Err("empty type name".into());
+ return Err("empty type name".into());
}
let prog = self
.program
.as_mut()
- .ok_or_else(|| "no program loaded".to_string())?;
+ .ok_or_else(|| "no program loaded".to_string())?;
if !prog.edits.rename_user_type(&old, &new) {
- return Err(format!("no type named {old}"));
+ return Err(format!("no type named {old}"));
}
self.event_bus.publish(GhidrustEvent::ProgramMutated {
kind: MutationKind::Retype {
va: 0,
- type_desc: format!("rename type: {old} → {new}"),
+ type_desc: format!("rename type: {old} → {new}"),
},
});
- self.status = format!("Renamed type {old} → {new}");
+ self.status = format!("Renamed type {old} → {new}");
self.log(self.status.clone());
Ok(())
}
- /// DTM → Delete a user type (also unlinks any `Applied` decorations).
+ /// DTM → Delete a user type (also unlinks any `Applied` decorations).
pub fn delete_user_type(&mut self, name: &str) -> Result<(), String> {
let prog = self
.program
.as_mut()
- .ok_or_else(|| "no program loaded".to_string())?;
+ .ok_or_else(|| "no program loaded".to_string())?;
if !prog.edits.delete_user_type(name) {
- return Err(format!("no type named {name}"));
+ return Err(format!("no type named {name}"));
}
self.event_bus.publish(GhidrustEvent::ProgramMutated {
kind: MutationKind::Retype {
va: 0,
- type_desc: format!("deleted type: {name}"),
+ type_desc: format!("deleted type: {name}"),
},
});
- self.status = format!("Deleted type {name}");
+ self.status = format!("Deleted type {name}");
self.log(self.status.clone());
Ok(())
}
- /// DTM → Edit an existing user type body (Ghidra Structure / Union /
- /// Enum / Typedef editor). May also rename in the same operation.
+ /// DTM → Edit an existing user type body (Structure / Union /
+ /// Enum / Typedef editor). May also rename in the same operation.
pub fn edit_user_type(
&mut self,
orig_name: &str,
@@ -1548,14 +1530,14 @@ impl GhidrustApp {
let new_name = new_name.into();
let body = body.into();
if new_name.trim().is_empty() {
- return Err("empty type name".into());
+ return Err("empty type name".into());
}
let prog = self
.program
.as_mut()
- .ok_or_else(|| "no program loaded".to_string())?;
+ .ok_or_else(|| "no program loaded".to_string())?;
if !prog.edits.user_types.contains_key(orig_name) {
- return Err(format!("no type named {orig_name}"));
+ return Err(format!("no type named {orig_name}"));
}
if orig_name != new_name {
let _ = prog.edits.rename_user_type(orig_name, &new_name);
@@ -1564,37 +1546,37 @@ impl GhidrustApp {
self.event_bus.publish(GhidrustEvent::ProgramMutated {
kind: MutationKind::Retype {
va: 0,
- type_desc: format!("edit type: {new_name}"),
+ type_desc: format!("edit type: {new_name}"),
},
});
- self.status = format!("Edited type {new_name}");
+ self.status = format!("Edited type {new_name}");
self.log(self.status.clone());
Ok(())
}
- /// DTM → New Typedef on X (Ghidra `New Typedef on <type>`). Creates a
- /// typedef whose body records the underlying type; the resulting user
- /// type can be applied at Listing addresses just like any other.
+ /// DTM → New Typedef on X . Creates a
+ /// typedef whose body records the underlying type; the resulting user
+ /// type can be applied at Listing addresses just like any other.
pub fn new_typedef_on(&mut self, source: &str) -> Result<String, String> {
- let name = format!("typedef_{source}");
- let body = format!("Typedef\ntypedef {source} {name};");
+ let name = format!("typedef_{source}");
+ let body = format!("Typedef\ntypedef {source} {name};");
self.define_user_type(&name, body)?;
Ok(name)
}
- /// DTM → New Pointer to X. Registers a `<X> *` user type so the Listing
- /// can apply the pointer decoration without a full parser.
+ /// DTM → New Pointer to X. Registers a `<X> *` user type so the Listing
+ /// can apply the pointer decoration without a full parser.
pub fn new_pointer_to(&mut self, source: &str) -> Result<String, String> {
- let name = format!("{source} *");
- let body = format!("Typedef\n{source} *");
+ let name = format!("{source} *");
+ let body = format!("Typedef\n{source} *");
self.define_user_type(&name, body)?;
Ok(name)
}
- // ── 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.
+ /// Attach an equate `name` at `(va, op)` for scalar `value` (
+ /// `Convert → Equate`). Empty `name` clears the equate.
pub fn set_equate(
&mut self,
va: u64,
@@ -1606,49 +1588,49 @@ impl GhidrustApp {
let prog = self
.program
.as_mut()
- .ok_or_else(|| "no program loaded".to_string())?;
+ .ok_or_else(|| "no program loaded".to_string())?;
let clearing = name.is_empty();
prog.edits.set_equate(va, op, &name, value);
- // Equates render inline in the Listing operand slot; treat as retype
- // for cache invalidation so the Decompiler picks the change up too.
+ // Equates render inline in the Listing operand slot; treat as retype
+ // for cache invalidation so the Decompiler picks the change up too.
self.event_bus.publish(GhidrustEvent::ProgramMutated {
kind: MutationKind::Retype {
va,
type_desc: if clearing {
- format!("cleared equate @ op {op}")
+ format!("cleared equate @ op {op}")
} else {
- format!("equate {name} = {value}")
+ format!("equate {name} = {value}")
},
},
});
self.status = if clearing {
- format!("Cleared equate @ {va:#x} op {op}")
+ format!("Cleared equate @ {va:#x} op {op}")
} else {
- format!("Set equate {name} = {value} @ {va:#x} op {op}")
+ format!("Set equate {name} = {value} @ {va:#x} op {op}")
};
self.log(self.status.clone());
Ok(())
}
- /// Function Tags — add / remove / delete-everywhere (Ghidra
- /// `FunctionTagPlugin`).
+ /// Function Tags — add / remove / delete-everywhere (
+ /// `FunctionTagPlugin`).
pub fn add_function_tag(&mut self, entry: u64, tag: impl Into<String>) -> Result<(), String> {
let tag = tag.into();
if tag.trim().is_empty() {
- return Err("empty tag".into());
+ return Err("empty tag".into());
}
let prog = self
.program
.as_mut()
- .ok_or_else(|| "no program loaded".to_string())?;
+ .ok_or_else(|| "no program loaded".to_string())?;
prog.edits.add_function_tag(entry, &tag);
self.event_bus.publish(GhidrustEvent::ProgramMutated {
kind: MutationKind::Retype {
va: entry,
- type_desc: format!("tag+ {tag}"),
+ type_desc: format!("tag+ {tag}"),
},
});
- self.status = format!("Tag '{tag}' added to fn @ {entry:#x}");
+ self.status = format!("Tag '{tag}' added to fn @ {entry:#x}");
self.log(self.status.clone());
Ok(())
}
@@ -1657,60 +1639,60 @@ impl GhidrustApp {
let prog = self
.program
.as_mut()
- .ok_or_else(|| "no program loaded".to_string())?;
+ .ok_or_else(|| "no program loaded".to_string())?;
let removed = prog.edits.remove_function_tag(entry, tag);
if !removed {
- return Err(format!("fn @ {entry:#x} has no tag '{tag}'"));
+ return Err(format!("fn @ {entry:#x} has no tag '{tag}'"));
}
self.event_bus.publish(GhidrustEvent::ProgramMutated {
kind: MutationKind::Retype {
va: entry,
- type_desc: format!("tag- {tag}"),
+ type_desc: format!("tag- {tag}"),
},
});
- self.status = format!("Tag '{tag}' removed from fn @ {entry:#x}");
+ self.status = format!("Tag '{tag}' removed from fn @ {entry:#x}");
self.log(self.status.clone());
Ok(())
}
- /// Register a tag in the universe (`ProgramEdits::all_function_tags`)
- /// without assigning it to a function. Ghidra's "Create tag" action
- /// lands here.
+ /// Register a tag in the universe (`ProgramEdits::all_function_tags`)
+ /// without assigning it to a function. "Create tag" action
+ /// lands here.
pub fn create_tag(&mut self, tag: impl Into<String>) -> Result<(), String> {
let tag = tag.into();
if tag.trim().is_empty() {
- return Err("empty tag".into());
+ return Err("empty tag".into());
}
let prog = self
.program
.as_mut()
- .ok_or_else(|| "no program loaded".to_string())?;
+ .ok_or_else(|| "no program loaded".to_string())?;
prog.edits.all_function_tags.insert(tag.clone());
- self.status = format!("Created tag '{tag}'");
+ self.status = format!("Created tag '{tag}'");
self.log(self.status.clone());
Ok(())
}
- /// Delete a tag from every function and from the universe.
+ /// Delete a tag from every function and from the universe.
pub fn delete_tag_everywhere(&mut self, tag: &str) -> Result<(), String> {
let prog = self
.program
.as_mut()
- .ok_or_else(|| "no program loaded".to_string())?;
+ .ok_or_else(|| "no program loaded".to_string())?;
let n = prog.edits.delete_tag_everywhere(tag);
self.event_bus.publish(GhidrustEvent::ProgramMutated {
kind: MutationKind::Retype {
va: 0,
- type_desc: format!("tag deleted: {tag}"),
+ type_desc: format!("tag deleted: {tag}"),
},
});
- self.status = format!("Tag '{tag}' deleted from {n} function(s)");
+ self.status = format!("Tag '{tag}' deleted from {n} function(s)");
self.log(self.status.clone());
Ok(())
}
- /// Compute references TO the given target VA. Uses `ghidrust-core::xrefs`
- /// against the current program + focused-window listing.
+ /// Compute references TO the given target VA. Uses `ghidrust-core::xrefs`
+ /// against the current program + focused-window listing.
pub fn xrefs_to_va(&self, target: u64) -> Vec<XRef> {
let Some(prog) = self.program.as_ref() else {
return Vec::new();
@@ -1718,7 +1700,7 @@ impl GhidrustApp {
xrefs_to(prog, target, Some(&self.listing))
}
- /// Compute references FROM the given source VA.
+ /// Compute references FROM the given source VA.
pub fn xrefs_from_va(&self, source: u64) -> Vec<XRef> {
let Some(prog) = self.program.as_ref() else {
return Vec::new();
@@ -1726,24 +1708,24 @@ impl GhidrustApp {
xrefs_from(prog, source, STAGE0_MAX_INSNS)
}
- /// Compute a checksum panel over the loaded program (or focused block).
+ /// Compute a checksum panel over the loaded program (or focused block).
pub fn compute_checksums(&mut self, mode: ChecksumMode) -> Result<(), String> {
let prog = self
.program
.as_ref()
- .ok_or_else(|| "no program loaded".to_string())?;
+ .ok_or_else(|| "no program loaded".to_string())?;
let (target_label, data): (String, Vec<u8>) = match mode {
ChecksumMode::WholeImage => {
let bytes: Vec<u8> = prog.blocks.iter().flat_map(|b| b.bytes.clone()).collect();
- (format!("Whole image ({})", prog.name), bytes)
+ (format!("Whole image ({})", prog.name), bytes)
}
ChecksumMode::Section(name) => {
let b = prog
.blocks
.iter()
.find(|b| b.name == name)
- .ok_or_else(|| format!("no block named {name}"))?;
- (format!("Block {name}"), b.bytes.clone())
+ .ok_or_else(|| format!("no block named {name}"))?;
+ (format!("Block {name}"), b.bytes.clone())
}
};
let len = data.len();
@@ -1771,15 +1753,15 @@ impl GhidrustApp {
fletcher32,
});
self.status = format!(
- "Checksum: crc32={crc32:#010x} adler32={adler32:#010x} len={len}",
+ "Checksum: crc32={crc32:#010x} adler32={adler32:#010x} len={len}",
);
self.log(self.status.clone());
Ok(())
}
- /// Program Tree → Set View / Add To View / Remove From View / Show All.
- ///
- /// The Ghidra semantic is a **fragment name set**. `None` = full view.
+ /// Program Tree → Set View / Add To View / Remove From View / Show All.
+ ///
+ /// The semantic is a **fragment name set**. `None` = full view.
pub fn set_listing_view(&mut self, fragments: Option<BTreeSet<String>>) {
self.listing_view_filter = fragments;
}
@@ -1796,8 +1778,8 @@ impl GhidrustApp {
if let Some(set) = self.listing_view_filter.as_mut() {
set.remove(fragment);
if set.is_empty() {
- // Empty view → drop the filter so Listing shows nothing but
- // reflects an honest empty state driven by fragment membership.
+ // Empty view → drop the filter so Listing shows nothing but
+ // reflects an honest empty state driven by fragment membership.
}
}
}
@@ -1806,7 +1788,7 @@ impl GhidrustApp {
self.listing_view_filter = None;
}
- /// Whether a Listing address is currently in-view (Program Tree filter).
+ /// Whether a Listing address is currently in-view (Program Tree filter).
pub fn addr_in_view(&self, va: u64) -> bool {
let Some(filter) = self.listing_view_filter.as_ref() else {
return true;
@@ -1820,7 +1802,7 @@ impl GhidrustApp {
.any(|b| va >= b.va && va < b.va.saturating_add(b.size))
}
- /// Navigation → Next Function.
+ /// Navigation → Next Function.
pub fn nav_next_function(&mut self) {
let cur = self.listing_focus_va.unwrap_or(0);
let entries: Vec<u64> = self
@@ -1829,7 +1811,7 @@ impl GhidrustApp {
.map(|p| p.analysis.functions.iter().map(|f| f.entry).collect())
.unwrap_or_default();
if entries.is_empty() {
- self.status = "No functions — run Function Start Search".into();
+ self.status = "No functions — run Function Start Search".into();
self.log_warn(self.status.clone());
return;
}
@@ -1842,7 +1824,7 @@ impl GhidrustApp {
}
}
- /// Navigation → Previous Function.
+ /// Navigation → Previous Function.
pub fn nav_prev_function(&mut self) {
let cur = self.listing_focus_va.unwrap_or(u64::MAX);
let entries: Vec<u64> = self
@@ -1851,7 +1833,7 @@ impl GhidrustApp {
.map(|p| p.analysis.functions.iter().map(|f| f.entry).collect())
.unwrap_or_default();
if entries.is_empty() {
- self.status = "No functions — run Function Start Search".into();
+ self.status = "No functions — run Function Start Search".into();
self.log_warn(self.status.clone());
return;
}
@@ -1864,43 +1846,43 @@ impl GhidrustApp {
}
}
- /// Program → Symbol Tree lookup: are Imports/Exports parseable from analysis?
- ///
- /// Ghidrust's PE loader doesn't yet parse the Import / Export directories, but
- /// PDB analyzers do populate `Program::analysis.pdb_symbols`. This helper
- /// returns (imports, exports) as best-effort lists derived from analyzer
- /// output — never fabricated. Empty lists = analyzer didn't populate.
+ /// Program → Symbol Tree lookup: are Imports/Exports parseable from analysis?
+ ///
+ /// Ghidrust's PE loader doesn't yet parse the Import / Export directories, but
+ /// PDB analyzers do populate `Program::analysis.pdb_symbols`. This helper
+ /// returns (imports, exports) as best-effort lists derived from analyzer
+ /// output — never fabricated. Empty lists = analyzer didn't populate.
pub fn imports_exports(&self) -> (Vec<(u64, String)>, Vec<(u64, String)>) {
let Some(prog) = self.program.as_ref() else {
return (Vec::new(), Vec::new());
};
let mut imports = Vec::new();
let mut exports = Vec::new();
- // Heuristic (source-honest): PDB symbols with `__imp_` prefix are imports.
+ // Heuristic (source-honest): PDB symbols with `__imp_` prefix are imports.
for s in &prog.analysis.pdb_symbols {
- if s.name.starts_with("__imp_")
- || s.name.starts_with("_imp_")
- || s.name.starts_with("__imp")
+ if s.name.starts_with("__imp_")
+ || s.name.starts_with("_imp_")
+ || s.name.starts_with("__imp")
{
imports.push((s.va, s.name.clone()));
}
}
- // Section-based fallback: sections whose name contains "idata"/"iat" are
- // import metadata; expose their base as an anchor row.
+ // Section-based fallback: sections whose name contains "idata"/"iat" are
+ // import metadata; expose their base as an anchor row.
for s in &prog.sections {
let n = s.name.to_ascii_lowercase();
- if n.contains("idata") || n.contains("iat") {
- imports.push((s.va, format!("{} @ {:#x}", s.name, s.va)));
+ if n.contains("idata") || n.contains("iat") {
+ imports.push((s.va, format!("{} @ {:#x}", s.name, s.va)));
}
- if n.contains("edata") {
- exports.push((s.va, format!("{} @ {:#x}", s.name, s.va)));
+ if n.contains("edata") {
+ exports.push((s.va, format!("{} @ {:#x}", s.name, s.va)));
}
}
- // Analysis symbols marked as exports by demangler are entry-like.
+ // Analysis symbols marked as exports by demangler are entry-like.
for s in &prog.analysis.symbols {
if s.demangled
.as_ref()
- .map(|d| d.contains("__declspec(dllexport)"))
+ .map(|d| d.contains("__declspec(dllexport)"))
.unwrap_or(false)
{
exports.push((s.va, s.name.clone()));
@@ -1913,12 +1895,12 @@ impl GhidrustApp {
(imports, exports)
}
- /// 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.
- /// Cursor events are already handled by their emitters (listing / navigation
- /// call sites both refresh the decompiler themselves).
+ /// 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.
+ /// Cursor events are already handled by their emitters (listing / navigation
+ /// call sites both refresh the decompiler themselves).
pub fn drain_events(&mut self) -> Vec<GhidrustEvent> {
let events = self.event_bus.drain();
for ev in &events {
@@ -1933,7 +1915,7 @@ impl GhidrustApp {
MutationKind::BookmarkAdded { .. } | MutationKind::BookmarkRemoved { .. } => {}
},
GhidrustEvent::ProgramActivated { name } => {
- self.log(format!("Program activated: {name}"));
+ self.log(format!("Program activated: {name}"));
}
GhidrustEvent::CursorMoved { .. } | GhidrustEvent::SelectionChanged { .. } => {}
}
@@ -1949,54 +1931,110 @@ impl GhidrustApp {
self.redo_stack.clear();
}
- /// Edit → Undo (selection history).
+ /// Edit → Undo (selection history).
pub fn edit_undo(&mut self) {
if let Some(prev) = self.undo_stack.pop() {
self.redo_stack.push(self.listing_selection);
self.listing_selection = prev;
- self.status = "Undo: restored selection".into();
+ self.status = "Undo: restored selection".into();
self.log(self.status.clone());
} else {
- self.status = "Nothing to undo".into();
+ self.status = "Nothing to undo".into();
self.log(self.status.clone());
}
}
- /// Edit → Redo.
+ /// Edit → Redo.
pub fn edit_redo(&mut self) {
if let Some(next) = self.redo_stack.pop() {
self.undo_stack.push(self.listing_selection);
self.listing_selection = next;
- self.status = "Redo: restored selection".into();
+ self.status = "Redo: restored selection".into();
self.log(self.status.clone());
} else {
- self.status = "Nothing to redo".into();
+ self.status = "Nothing to redo".into();
self.log(self.status.clone());
}
}
- /// Edit → Clear Selection.
+ /// Edit → Clear Selection.
pub fn edit_clear_selection(&mut self) {
self.push_selection_undo();
self.listing_selection = ListingSelection::clear();
- self.status = "Selection cleared".into();
+ self.status = "Selection cleared".into();
self.log(self.status.clone());
}
- /// Select → Select All (listing range).
+ /// Select → Select All (listing range).
pub fn select_all_listing(&mut self) {
self.push_selection_undo();
self.listing_selection = ListingSelection::all(self.listing.len());
self.status = format!(
- "Selected all {} listing instruction(s)",
+ "Selected all {} listing instruction(s)",
self.listing.len()
);
self.log(self.status.clone());
self.focus_center_tab(DockTab::Listing);
}
- /// Navigation → Go To Address.
- /// If `va` is outside the current listing window, re-disassembles 64 insns at `va`.
+ /// decode arch for name lookup in listing/detail panes.
+ fn listing_arch(&self) -> Arch {
+ self.decode_opts
+ .resolved_arch()
+ .or_else(|| {
+ self.program
+ .as_ref()
+ .and_then(arch_mode_for_program)
+ .map(|(a, _)| a)
+ })
+ .unwrap_or_else(|| default_arch_mode().0)
+ }
+
+ /// Re-disassemble the listing window at `va` using current decode options.
+ fn reload_listing_at(&mut self, va: u64) -> Result<(), String> {
+ let prog = self
+ .program
+ .as_ref()
+ .ok_or_else(|| "no program loaded".to_string())?;
+ self.decode_opts.sync_machine_from_program(prog);
+ self.listing_search.arch = self.listing_arch();
+ let result = reload(prog, va, &self.decode_opts)?;
+ if result.insns.is_empty() {
+ return Err(format!("no instructions at {va:#x}"));
+ }
+ self.listing = result.insns;
+ if let Some(proj) = &self.project {
+ let _ = save_decode_prefs(&proj.root, &self.decode_opts);
+ }
+ Ok(())
+ }
+
+ fn apply_decode_opts(&mut self) {
+ let va = self
+ .listing_focus_va
+ .or_else(|| self.listing.first().map(|i| i.address))
+ .or_else(|| self.program.as_ref().and_then(|p| p.entry))
+ .or_else(|| self.program.as_ref().map(|p| p.image_base));
+ let Some(va) = va else {
+ return;
+ };
+ match self.reload_listing_at(va) {
+ Ok(()) => {
+ self.status = format!(
+ "Listing reloaded at {va:#x} ({})",
+ self.listing.len()
+ );
+ self.log(self.status.clone());
+ }
+ Err(e) => {
+ self.status = format!("decode reload: {e}");
+ self.log_error(self.status.clone());
+ }
+ }
+ }
+
+ /// Navigation → Go To Address.
+ /// If `va` is outside the current listing window, re-disassembles 64 insns at `va`.
pub fn goto_address_str(&mut self, s: &str) -> Result<(), String> {
let va = parse_address(s)?;
self.listing_focus_va = Some(va);
@@ -2009,14 +2047,14 @@ impl GhidrustApp {
end: Some(i),
};
} else {
- // Outside loaded listing (or empty) — re-disassemble at target VA.
+ // Outside loaded listing (or empty) — re-disassemble at target VA.
let prog = self
.program
.as_ref()
- .ok_or_else(|| "no program loaded".to_string())?;
- let l = disassemble_range(prog, va, 64).map_err(|e| e.to_string())?;
+ .ok_or_else(|| "no program loaded".to_string())?;
+ let l = reload_for_goto(prog, va, &self.decode_opts).map_err(|e| e.to_string())?;
if l.is_empty() {
- return Err(format!("no instructions at {va:#x}"));
+ return Err(format!("no instructions at {va:#x}"));
}
self.listing = l;
self.push_selection_undo();
@@ -2033,12 +2071,12 @@ impl GhidrustApp {
source: EventSource::Navigation,
location: NavLocation::new(va),
});
- // Cross-highlight Decompiler line matching the new listing cursor.
+ // Cross-highlight Decompiler line matching the new listing cursor.
if !self.decomp_lines.is_empty() {
self.decomp_cross_line = decomp_line_for_va(&self.decomp_lines, va);
}
- // Selection Navigation: keep the "current function" in sync with the
- // cursor so the Symbol Tree can highlight the enclosing function.
+ // Selection Navigation: keep the "current function" in sync with the
+ // cursor so the Symbol Tree can highlight the enclosing function.
if self.symbol_tree_nav {
if let Some(prog) = self.program.as_ref() {
self.focused_function_entry = prog
@@ -2051,36 +2089,36 @@ impl GhidrustApp {
}
}
- self.status = format!("Go to {va:#x}");
+ self.status = format!("Go to {va:#x}");
self.log(self.status.clone());
Ok(())
}
- /// Navigation → Go To entry.
+ /// Navigation → Go To entry.
pub fn goto_entry(&mut self) {
self.focus_center_tab(DockTab::Listing);
if let Some(prog) = &self.program {
if let Some(e) = prog.entry {
- let _ = self.goto_address_str(&format!("{e:#x}"));
+ let _ = self.goto_address_str(&format!("{e:#x}"));
return;
}
}
- self.status = "No entry point".into();
+ self.status = "No entry point".into();
self.log(self.status.clone());
}
- /// Search → Memory.
+ /// Search → Memory.
pub fn run_search_memory(&mut self) -> Result<(), String> {
let prog = self
.program
.as_ref()
- .ok_or_else(|| "no program loaded".to_string())?;
+ .ok_or_else(|| "no program loaded".to_string())?;
let pat = parse_hex_pattern(&self.search_memory_input)?;
self.memory_hits = search_memory(prog, &pat, 500);
self.text_hits.clear();
self.show_search_results = true;
self.status = format!(
- "Memory search: {} hit(s) for '{}'",
+ "Memory search: {} hit(s) for '{}'",
self.memory_hits.len(),
self.search_memory_input.trim()
);
@@ -2088,22 +2126,22 @@ impl GhidrustApp {
Ok(())
}
- /// Search → For Scalars.
+ /// Search → For Scalars.
pub fn run_search_scalars(&mut self) -> Result<(), String> {
let min = self
.parse_scalar_input(&self.search_scalars_min.clone())
- .map_err(|e| format!("min: {e}"))?;
+ .map_err(|e| format!("min: {e}"))?;
let max = self
.parse_scalar_input(&self.search_scalars_max.clone())
- .map_err(|e| format!("max: {e}"))?;
+ .map_err(|e| format!("max: {e}"))?;
if min > max {
- return Err("min > max".into());
+ return Err("min > max".into());
}
self.text_hits = search_scalars(&self.listing, min, max, 1000);
self.memory_hits.clear();
self.show_search_results = true;
self.status = format!(
- "Scalar search [{min}, {max}]: {} hit(s)",
+ "Scalar search [{min}, {max}]: {} hit(s)",
self.text_hits.len()
);
self.log(self.status.clone());
@@ -2113,16 +2151,16 @@ impl GhidrustApp {
fn parse_scalar_input(&self, s: &str) -> Result<i64, String> {
let t = s.trim();
if t.is_empty() {
- return Err("empty".into());
+ return Err("empty".into());
}
- let (sign, rest) = if let Some(r) = t.strip_prefix('-') {
+ let (sign, rest) = if let Some(r) = t.strip_prefix('-') {
(-1i64, r)
} else {
(1i64, t)
};
- // `0x…` prefix wins → hex. Otherwise prefer decimal to preserve
- // Ghidra's convention (numeric input without a prefix is decimal).
- let (base, digits) = if let Some(r) = rest.strip_prefix("0x").or_else(|| rest.strip_prefix("0X")) {
+ // `0x…` prefix wins → hex. Otherwise prefer decimal to preserve
+ // convention (numeric input without a prefix is decimal).
+ let (base, digits) = if let Some(r) = rest.strip_prefix("0x").or_else(|| rest.strip_prefix("0X")) {
(16u32, r)
} else {
(10u32, rest)
@@ -2131,10 +2169,10 @@ impl GhidrustApp {
Ok(sign * mag as i64)
}
- /// Search → Instruction Patterns.
+ /// Search → Instruction Patterns.
pub fn run_search_instruction_patterns(&mut self) -> Result<(), String> {
if self.listing.is_empty() {
- return Err("no listing loaded".into());
+ return Err("no listing loaded".into());
}
self.text_hits = search_instruction_patterns(
&self.listing,
@@ -2145,7 +2183,7 @@ impl GhidrustApp {
self.memory_hits.clear();
self.show_search_results = true;
self.status = format!(
- "Instruction pattern hits: {} for `{} {}`",
+ "Instruction pattern hits: {} for `{} {}`",
self.text_hits.len(),
self.search_insn_mnemonic.trim(),
self.search_insn_operands.trim(),
@@ -2154,12 +2192,12 @@ impl GhidrustApp {
Ok(())
}
- /// Search → Program Text.
+ /// Search → Program Text.
pub fn run_search_text(&mut self) -> Result<(), String> {
let prog = self
.program
.as_ref()
- .ok_or_else(|| "no program loaded".to_string())?;
+ .ok_or_else(|| "no program loaded".to_string())?;
self.text_hits = search_program_text(
prog,
&self.listing,
@@ -2170,7 +2208,7 @@ impl GhidrustApp {
self.memory_hits.clear();
self.show_search_results = true;
self.status = format!(
- "Text search: {} hit(s) for '{}'",
+ "Text search: {} hit(s) for '{}'",
self.text_hits.len(),
self.search_text_input.trim()
);
@@ -2218,76 +2256,76 @@ impl GhidrustApp {
let rtti_n = self.rtti.classes.len();
let str_n = self.strings.len();
let list_n = self.listing.len();
- format!("{fns} functions · {rtti_n} RTTI · {str_n} strings · {list_n} listing lines")
+ format!("{fns} functions · {rtti_n} RTTI · {str_n} strings · {list_n} listing lines")
}
fn browse_binary_path(&mut self) {
if let Some(path) = rfd::FileDialog::new()
- .set_title("Open binary (PE / ELF)")
- .add_filter("Binaries", &["exe", "dll", "sys", "pe", "elf", "so", "bin"])
- .add_filter("All files", &["*"])
+ .set_title("Open binary (PE / ELF)")
+ .add_filter("Binaries", &["exe", "dll", "sys", "pe", "elf", "so", "bin"])
+ .add_filter("All files", &["*"])
.pick_file()
{
self.path_input = path.display().to_string();
- self.log(format!("Browsed binary: {}", self.path_input));
+ self.log(format!("Browsed binary: {}", self.path_input));
}
}
fn browse_project_dir(&mut self) {
if let Some(path) = rfd::FileDialog::new()
- .set_title("Select project folder")
+ .set_title("Select project folder")
.pick_folder()
{
self.project_dir_input = path.display().to_string();
- self.log(format!("Browsed project dir: {}", self.project_dir_input));
+ self.log(format!("Browsed project dir: {}", self.project_dir_input));
}
}
- /// Browse for a binary and load it immediately (no project required).
+ /// Browse for a binary and load it immediately (no project required).
fn browse_and_load_binary(&mut self) {
self.browse_binary_path();
if !self.path_input.trim().is_empty() {
if let Err(e) = self.load_binary(self.path_input.clone()) {
- self.status = format!("error: {e}");
+ self.status = format!("error: {e}");
self.log(self.status.clone());
}
}
}
- /// Browse folder then open project at that path.
+ /// Browse folder then open project at that path.
fn browse_and_open_project(&mut self) {
self.browse_project_dir();
if !self.project_dir_input.trim().is_empty() {
if let Err(e) = self.open_project() {
- self.status = format!("error: {e}");
+ self.status = format!("error: {e}");
self.log(self.status.clone());
}
}
}
- /// Browse folder then create project there.
+ /// Browse folder then create project there.
fn browse_and_create_project(&mut self) {
self.browse_project_dir();
if !self.project_dir_input.trim().is_empty() {
if let Err(e) = self.create_project() {
- self.status = format!("error: {e}");
+ self.status = format!("error: {e}");
self.log(self.status.clone());
}
}
}
- /// Browse binary then import into the open project.
+ /// Browse binary then import into the open project.
fn browse_and_import(&mut self) {
self.browse_binary_path();
if !self.path_input.trim().is_empty() {
if let Err(e) = self.import_into_project() {
- self.status = format!("error: {e}");
+ self.status = format!("error: {e}");
self.log(self.status.clone());
}
}
}
- /// Request delete with confirmation (does not delete yet).
+ /// Request delete with confirmation (does not delete yet).
pub fn request_delete_file(&mut self, id: &str) {
let name = self
.project
@@ -2298,21 +2336,21 @@ impl GhidrustApp {
self.pending_delete = Some((id.to_string(), name));
}
- /// Confirm pending delete: remove from project disk + clear UI if active.
+ /// Confirm pending delete: remove from project disk + clear UI if active.
pub fn confirm_delete_file(&mut self) -> Result<(), String> {
let (id, name) = self
.pending_delete
.take()
- .ok_or_else(|| "no pending delete".to_string())?;
+ .ok_or_else(|| "no pending delete".to_string())?;
let was_active = self.active_file_id.as_deref() == Some(id.as_str());
let entry = {
let proj = self
.project
.as_mut()
- .ok_or_else(|| "no project open".to_string())?;
+ .ok_or_else(|| "no project open".to_string())?;
proj.remove_file(&id).map_err(|e| e.to_string())?
};
- self.log(format!("Deleted {} (id={})", entry.display_name, entry.id));
+ self.log(format!("Deleted {} (id={})", entry.display_name, entry.id));
if self.tree_selected_id.as_deref() == Some(id.as_str()) {
self.tree_selected_id = None;
}
@@ -2330,10 +2368,10 @@ impl GhidrustApp {
if let Some(next) = next {
self.open_project_file(&next)?;
} else {
- self.status = format!("Deleted {name} — project empty");
+ self.status = format!("Deleted {name} — project empty");
}
} else {
- self.status = format!("Deleted {name} from project");
+ self.status = format!("Deleted {name} from project");
}
Ok(())
}
@@ -2342,11 +2380,11 @@ impl GhidrustApp {
self.pending_delete = None;
}
- /// Ghidra Project Window–style rows for the Project Tree (testable without a window).
+ /// Project Window–style rows for the Project Tree (testable without a window).
pub fn project_tree_model(&self) -> Option<ProjectTreeModel> {
self.project.as_ref().map(|p| {
let mut m = p.tree_rows();
- // Reflect GUI active selection if set
+ // Reflect GUI active selection if set
if let Some(ref aid) = self.active_file_id {
for f in &mut m.files {
f.active = f.id == *aid;
@@ -2356,35 +2394,35 @@ impl GhidrustApp {
})
}
- /// Open binary from project tree selection (same path as file chips).
+ /// Open binary from project tree selection (same path as file chips).
pub fn open_from_tree(&mut self, id: &str) -> Result<(), String> {
self.tree_selected_id = Some(id.to_string());
self.open_project_file(id)
}
- /// Open analysis options dialog for a project-tree file (does not run yet).
+ /// Open analysis options dialog for a project-tree file (does not run yet).
pub fn analyze_from_tree(&mut self, id: &str) -> Result<(), String> {
if self.analysis_job.is_some() {
- return Err("analysis already in progress".into());
+ return Err("analysis already in progress".into());
}
self.tree_selected_id = Some(id.to_string());
self.pending_analyze_file_id = Some(id.to_string());
self.show_analysis_dialog = true;
- self.status = "Choose analyzers and options, then Run Analysis".into();
+ self.status = "Choose analyzers and options, then Run Analysis".into();
Ok(())
}
- /// Start analysis from dialog selections on a background thread.
- /// Progress / console lines are delivered via channel and polled each UI frame.
+ /// Start analysis from dialog selections on a background thread.
+ /// Progress / console lines are delivered via channel and polled each UI frame.
pub fn begin_analysis_job(&mut self) -> Result<(), String> {
if self.analysis_job.is_some() {
- return Err("analysis already in progress".into());
+ return Err("analysis already in progress".into());
}
if let Some(id) = self.pending_analyze_file_id.take() {
self.open_from_tree(&id)?;
}
if self.program.is_none() {
- return Err("no program loaded — open or import a binary first".into());
+ return Err("no program loaded — open or import a binary first".into());
}
let names: Vec<String> = self
.analyzer_infos
@@ -2394,29 +2432,29 @@ impl GhidrustApp {
.map(|(a, _)| a.name.clone())
.collect();
if names.is_empty() {
- return Err("select at least one analyzer".into());
+ return Err("select at least one analyzer".into());
}
- // Bulk mode is applied inside run_analyzers_opts per step when use_gpu.
+ // Bulk mode is applied inside run_analyzers_opts per step when use_gpu.
let file_label = self
.program
.as_ref()
.map(|p| p.name.clone())
- .unwrap_or_else(|| "program".into());
+ .unwrap_or_else(|| "program".into());
let use_gpu = self.use_gpu_experimental;
self.log(format!(
- "Starting analysis on {file_label}: {} analyzer(s), gpu={}",
+ "Starting analysis on {file_label}: {} analyzer(s), gpu={}",
names.len(),
use_gpu
));
- self.status = format!("Analyzing {file_label}…");
+ self.status = format!("Analyzing {file_label}…");
let (msg_tx, msg_rx) = mpsc::channel::<AnalysisWorkerMsg>();
- // Hand the program to the worker only after spawn succeeds so a spawn
- // failure cannot drop the only Program copy.
+ // Hand the program to the worker only after spawn succeeds so a spawn
+ // failure cannot drop the only Program copy.
let (prog_tx, prog_rx) = mpsc::sync_channel::<Program>(1);
let names_worker = names.clone();
std::thread::Builder::new()
- .name("ghidrust-analysis".into())
+ .name("ghidrust-analysis".into())
.spawn(move || {
let Ok(mut prog) = prog_rx.recv() else {
return;
@@ -2424,8 +2462,8 @@ impl GhidrustApp {
for (index, name) in names_worker.iter().enumerate() {
let _ = msg_tx.send(AnalysisWorkerMsg::StepStarted { index });
let gpu = use_gpu && analyzer_supports_gpu(name);
- // catch_unwind: core GPU paths already catch wgpu panics;
- // belt-and-suspenders so the worker always returns the program.
+ // catch_unwind: core GPU paths already catch wgpu panics;
+ // belt-and-suspenders so the worker always returns the program.
let step = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
ghidrust_core::run_analyzers_opts(&mut prog, &[name.as_str()], gpu)
}));
@@ -2446,7 +2484,7 @@ impl GhidrustApp {
Err(_) => {
let _ = msg_tx.send(AnalysisWorkerMsg::Failed {
error: format!(
- "analyzer '{name}' panicked (GPU/validation); try again with GPU off"
+ "analyzer '{name}' panicked (GPU/validation); try again with GPU off"
),
program: prog,
});
@@ -2456,14 +2494,14 @@ impl GhidrustApp {
}
let _ = msg_tx.send(AnalysisWorkerMsg::Done { program: prog });
})
- .map_err(|e| format!("failed to spawn analysis worker: {e}"))?;
+ .map_err(|e| format!("failed to spawn analysis worker: {e}"))?;
let prog = self
.program
.take()
- .expect("program checked non-None above");
+ .expect("program checked non-None above");
if prog_tx.send(prog).is_err() {
- return Err("analysis worker exited before receiving program".into());
+ return Err("analysis worker exited before receiving program".into());
}
self.analysis_job = Some(AnalysisJob {
@@ -2477,13 +2515,13 @@ impl GhidrustApp {
Ok(())
}
- /// Poll the analysis worker (non-blocking). Call every frame while `analysis_job` is Some.
- /// Returns `Ok(true)` when the job has finished and been finalized.
+ /// Poll the analysis worker (non-blocking). Call every frame while `analysis_job` is Some.
+ /// Returns `Ok(true)` when the job has finished and been finalized.
pub fn step_analysis_job(&mut self) -> Result<bool, String> {
self.poll_analysis_job(false)
}
- /// Block until at least one worker message arrives (tests / headless drain).
+ /// Block until at least one worker message arrives (tests / headless drain).
pub fn step_analysis_job_blocking(&mut self) -> Result<bool, String> {
self.poll_analysis_job(true)
}
@@ -2492,17 +2530,17 @@ impl GhidrustApp {
let job = self
.analysis_job
.as_ref()
- .ok_or_else(|| "no analysis job".to_string())?;
+ .ok_or_else(|| "no analysis job".to_string())?;
if block {
match job.rx.recv() {
Ok(m) => Ok(Some(m)),
- Err(RecvError) => Err("analysis worker disconnected".into()),
+ Err(RecvError) => Err("analysis worker disconnected".into()),
}
} else {
match job.rx.try_recv() {
Ok(m) => Ok(Some(m)),
Err(TryRecvError::Empty) => Ok(None),
- Err(TryRecvError::Disconnected) => Err("analysis worker disconnected".into()),
+ Err(TryRecvError::Disconnected) => Err("analysis worker disconnected".into()),
}
}
}
@@ -2514,7 +2552,7 @@ impl GhidrustApp {
if self.apply_analysis_msg(first)? {
return Ok(true);
}
- // Drain any further messages already queued so one frame can catch up.
+ // Drain any further messages already queued so one frame can catch up.
while let Some(msg) = self.recv_analysis_msg(false)? {
if self.apply_analysis_msg(msg)? {
return Ok(true);
@@ -2523,7 +2561,7 @@ impl GhidrustApp {
Ok(false)
}
- /// Apply one worker message. Returns `Ok(true)` when the job is fully finished.
+ /// Apply one worker message. Returns `Ok(true)` when the job is fully finished.
fn apply_analysis_msg(&mut self, msg: AnalysisWorkerMsg) -> Result<bool, String> {
match msg {
AnalysisWorkerMsg::StepStarted { index } => {
@@ -2535,8 +2573,8 @@ impl GhidrustApp {
.names
.get(index)
.cloned()
- .unwrap_or_else(|| "…".into());
- self.status = format!("Analyzing {label} — {}/{total}: {cur}", index + 1);
+ .unwrap_or_else(|| "…".into());
+ self.status = format!("Analyzing {label} — {}/{total}: {cur}", index + 1);
}
Ok(false)
}
@@ -2545,7 +2583,7 @@ impl GhidrustApp {
let mut rtti_upd = None;
let mut strings_upd = None;
for r in &outputs {
- log_lines.push(format!("[{}] {} — {}", r.status, r.name, r.message));
+ log_lines.push(format!("[{}] {} — {}", r.status, r.name, r.message));
if r.rtti.is_some() {
rtti_upd = r.rtti.clone();
}
@@ -2554,9 +2592,9 @@ impl GhidrustApp {
}
}
for line in log_lines {
- let sev = if line.starts_with("[error]") {
+ let sev = if line.starts_with("[error]") {
ConsoleSeverity::Error
- } else if line.starts_with("[warn") {
+ } else if line.starts_with("[warn") {
ConsoleSeverity::Warn
} else {
ConsoleSeverity::Info
@@ -2593,15 +2631,15 @@ impl GhidrustApp {
let job = self
.analysis_job
.take()
- .ok_or_else(|| "no analysis job".to_string())?;
+ .ok_or_else(|| "no analysis job".to_string())?;
if let Some(prog) = self.program.as_ref() {
- let entry = prog.entry.unwrap_or(prog.image_base);
- if let Ok(l) = disassemble_range(prog, entry, 128) {
- self.listing = l;
+ let entry = default_start_va(prog, self.listing_focus_va);
+ if let Ok(result) = reload(prog, entry, &self.decode_opts) {
+ self.listing = result.insns;
}
self.rtti = prog.rtti.clone();
}
- // Capture strings from this run's results
+ // Capture strings from this run's results
for r in &job.results.results {
if let Some(ref s) = r.strings {
self.strings = s.clone();
@@ -2616,12 +2654,12 @@ impl GhidrustApp {
self.last_analysis = job.results;
let summary = self.analysis_summary_line();
let banner = format!(
- "Analysis complete on {} — {n} analyzer(s) · {summary}{}",
+ "Analysis complete on {} — {n} analyzer(s) · {summary}{}",
job.file_label,
if job.use_gpu {
- " · GPU experimental"
+ " · GPU experimental"
} else {
- ""
+ ""
}
);
self.analysis_done_banner = Some(banner.clone());
@@ -2629,11 +2667,11 @@ impl GhidrustApp {
self.log(banner);
if self.project.is_some() && self.active_file_id.is_some() {
let _ = self.save_results();
- self.log("Results saved to project (results/ + exports/).");
+ self.log("Results saved to project (results/ + exports/).");
}
self.focus_center_tab(DockTab::Overview);
self.show_symbol_tree = true;
- // Function list / names may have changed — drop cache and re-seed Stage-0.
+ // Function list / names may have changed — drop cache and re-seed Stage-0.
self.clear_decompiler_cache();
if let Some(va) = self
.listing_focus_va
@@ -2642,7 +2680,7 @@ impl GhidrustApp {
{
self.refresh_decompiler_at(va);
}
- // Restore default bulk mode after experimental run
+ // Restore default bulk mode after experimental run
set_preferred_bulk_mode(BulkScanMode::ParallelCpu);
Ok(())
}
@@ -2678,7 +2716,7 @@ impl GhidrustApp {
v.hyperlink_color = rgb(t.primary);
v.warn_fg_color = rgb(t.error);
ctx.set_visuals(v);
- // Wider side/top grab for resizable panels (bottom console drag).
+ // Wider side/top grab for resizable panels (bottom console drag).
ctx.style_mut(|s| {
s.interaction.resize_grab_radius_side = 12.0;
});
@@ -2688,15 +2726,23 @@ impl GhidrustApp {
let path = path.into();
self.path_input = path.display().to_string();
let prog = load_path(&path).map_err(|e| e.to_string())?;
- let entry = prog.entry.unwrap_or(prog.image_base);
- let listing = disassemble_range(&prog, entry, 128).unwrap_or_default();
+ let entry = default_start_va(&prog, None);
+ self.decode_opts.sync_machine_from_program(&prog);
+ self.listing_search.arch = self
+ .decode_opts
+ .resolved_arch()
+ .or_else(|| arch_mode_for_program(&prog).map(|(a, _)| a))
+ .unwrap_or_else(|| default_arch_mode().0);
+ let listing = reload(&prog, entry, &self.decode_opts)
+ .map(|r| r.insns)
+ .unwrap_or_default();
self.log(format!(
- "Loaded {} ({}) base={:#x}",
+ "Loaded {} ({}) base={:#x}",
prog.name, prog.format, prog.image_base
));
let prog_name = prog.name.clone();
self.status = format!(
- "Loaded {} — {} sections, {} listing insns",
+ "Loaded {} — {} sections, {} listing insns",
prog.name,
prog.sections.len(),
listing.len()
@@ -2719,19 +2765,20 @@ impl GhidrustApp {
pub fn create_project(&mut self) -> Result<(), String> {
let dir = self.project_dir_input.trim().to_string();
if dir.is_empty() {
- return Err("set Project dir path first".into());
+ return Err("set Project dir path first".into());
}
let name = if self.project_name_input.trim().is_empty() {
- "MyProject".into()
+ "MyProject".into()
} else {
self.project_name_input.trim().to_string()
};
let p = Project::create(&dir, name).map_err(|e| e.to_string())?;
- self.log(format!("Created project '{}' at {}", p.meta.name, p.root.display()));
- self.status = format!("Project open: {}", p.root.display());
+ self.log(format!("Created project '{}' at {}", p.meta.name, p.root.display()));
+ self.status = format!("Project open: {}", p.root.display());
self.remember_project(&dir);
self.show_startup_picker = false;
self.project = Some(p);
+ self.decode_opts = DecodeUiOpts::default();
self.active_file_id = None;
self.ensure_project_skill_wired();
Ok(())
@@ -2740,20 +2787,23 @@ impl GhidrustApp {
pub fn open_project(&mut self) -> Result<(), String> {
let dir = self.project_dir_input.trim().to_string();
if dir.is_empty() {
- return Err("set Project dir path first".into());
+ return Err("set Project dir path first".into());
}
let p = Project::open(&dir).map_err(|e| e.to_string())?;
self.project_name_input = p.meta.name.clone();
self.active_file_id = p.meta.active_id.clone();
+ if let Some(opts) = load_decode_prefs(&p.root) {
+ self.decode_opts = opts;
+ }
self.log(format!(
- "Opened project '{}' ({} files)",
+ "Opened project '{}' ({} files)",
p.meta.name,
p.meta.files.len()
));
- self.status = format!("Project open: {}", p.root.display());
+ self.status = format!("Project open: {}", p.root.display());
self.remember_project(&dir);
self.show_startup_picker = false;
- // Auto-open active file if any
+ // Auto-open active file if any
if let Some(id) = p.meta.active_id.clone() {
self.project = Some(p);
self.ensure_project_skill_wired();
@@ -2765,14 +2815,14 @@ impl GhidrustApp {
Ok(())
}
- /// Auto-install embedded (or workspace) skill into the open project so the
- /// Grok Start checklist Skill row is green before the user clicks Start.
+ /// Auto-install embedded (or workspace) skill into the open project so the
+ /// Grok Start checklist Skill row is green before the user clicks Start.
fn ensure_project_skill_wired(&mut self) {
let Some(root) = self.project.as_ref().map(|p| p.root.clone()) else {
return;
};
let (_body, skill_source) = load_skill_body();
- // Reset so a new project root always re-attempts wire.
+ // Reset so a new project root always re-attempts wire.
self.grok_pane.skill_wired_root = None;
agent_pane::ensure_skill_for_project(
&mut self.grok_pane,
@@ -2786,22 +2836,22 @@ impl GhidrustApp {
.as_ref()
.map(|p| ghidrust_agent::project_skill_path(&p.root))
{
- self.log(format!("Agent skill ready at {}", path.display()));
+ self.log(format!("Agent skill ready at {}", path.display()));
}
}
pub fn import_into_project(&mut self) -> Result<(), String> {
let path = self.path_input.trim();
if path.is_empty() {
- return Err("set binary path first".into());
+ return Err("set binary path first".into());
}
let proj = self
.project
.as_mut()
- .ok_or_else(|| "no project open — create or open one first".to_string())?;
+ .ok_or_else(|| "no project open — create or open one first".to_string())?;
let entry = proj.import_file(path).map_err(|e| e.to_string())?;
self.active_file_id = Some(entry.id.clone());
- self.log(format!("Imported {} (id={})", entry.display_name, entry.id));
+ self.log(format!("Imported {} (id={})", entry.display_name, entry.id));
let id = entry.id.clone();
self.open_project_file(&id)
}
@@ -2811,23 +2861,23 @@ impl GhidrustApp {
let proj = self
.project
.as_ref()
- .ok_or_else(|| "no project".to_string())?;
+ .ok_or_else(|| "no project".to_string())?;
proj.meta
.files
.iter()
.find(|f| f.id == id)
- .ok_or_else(|| format!("unknown file id {id}"))?
+ .ok_or_else(|| format!("unknown file id {id}"))?
.clone()
};
let display = entry.display_name.clone();
- self.status = format!("Loading {display}…");
- self.log(format!("Loading {display} (saved results if any)…"));
+ self.status = format!("Loading {display}…");
+ self.log(format!("Loading {display} (saved results if any)…"));
let (prog, saved, has_saved, bin_path) = {
let proj = self
.project
.as_ref()
- .ok_or_else(|| "no project".to_string())?;
+ .ok_or_else(|| "no project".to_string())?;
let has_saved = proj.has_saved_analysis(&entry.id);
let bin_path = proj.binary_path(&entry).display().to_string();
let (prog, saved) = proj
@@ -2837,19 +2887,20 @@ impl GhidrustApp {
};
let mut saved_analyzers = Vec::new();
- let listing = if let Some(ref s) = saved {
+ if let Some(ref s) = saved {
saved_analyzers = s.saved_analyzers.clone();
- if !s.listing.is_empty() {
- s.listing.clone()
- } else {
- let e = prog.entry.unwrap_or(prog.image_base);
- disassemble_range(&prog, e, 128).unwrap_or_default()
- }
- } else {
- let e = prog.entry.unwrap_or(prog.image_base);
- disassemble_range(&prog, e, 128).unwrap_or_default()
- };
- // Strings: session last_analysis only (full rescan is Analyze opt-in on large games).
+ }
+ self.decode_opts.sync_machine_from_program(&prog);
+ self.listing_search.arch = self
+ .decode_opts
+ .resolved_arch()
+ .or_else(|| arch_mode_for_program(&prog).map(|(a, _)| a))
+ .unwrap_or_else(|| default_arch_mode().0);
+ let start_va = default_start_va(&prog, None);
+ let listing = reload(&prog, start_va, &self.decode_opts)
+ .map(|r| r.insns)
+ .unwrap_or_default();
+ // Strings: session last_analysis only (full rescan is Analyze opt-in on large games).
if let Some(s) = self
.last_analysis
.results
@@ -2874,12 +2925,12 @@ impl GhidrustApp {
let rtti_n = self.rtti.classes.len();
let fn_n = prog.analysis.functions.len();
self.status = format!(
- "Opened {display} — {fn_n} functions · {rtti_n} RTTI · {} listing lines{}",
+ "Opened {display} — {fn_n} functions · {rtti_n} RTTI · {} listing lines{}",
listing.len(),
if has_saved {
- " · analysis on disk"
+ " · analysis on disk"
} else {
- " · not analyzed yet"
+ " · not analyzed yet"
}
);
self.log(self.status.clone());
@@ -2906,16 +2957,16 @@ impl GhidrustApp {
let id = self
.active_file_id
.clone()
- .ok_or_else(|| "no active project file — import a binary into a project".to_string())?;
+ .ok_or_else(|| "no active project file — import a binary into a project".to_string())?;
let prog = self
.program
.as_ref()
- .ok_or_else(|| "no program loaded".to_string())?;
+ .ok_or_else(|| "no program loaded".to_string())?;
let (analysis_path, listing_path, saved) = {
let proj = self
.project
.as_ref()
- .ok_or_else(|| "no project open".to_string())?;
+ .ok_or_else(|| "no project open".to_string())?;
let saved = proj
.save_program_results(&id, prog, &self.listing, &self.last_analyzers_run)
.map_err(|e| e.to_string())?;
@@ -2925,10 +2976,10 @@ impl GhidrustApp {
saved,
)
};
- self.log(format!("Saved analysis → {analysis_path}"));
- self.log(format!("Listing export → {listing_path}"));
+ self.log(format!("Saved analysis → {analysis_path}"));
+ self.log(format!("Listing export → {listing_path}"));
self.status = format!(
- "Saved {} ({} functions, {} insns)",
+ "Saved {} ({} functions, {} insns)",
id,
saved.analysis.functions.len(),
saved.listing.len()
@@ -2936,7 +2987,7 @@ impl GhidrustApp {
Ok(())
}
- /// Headless/sync: begin job and drain all worker messages (tests + non-UI callers).
+ /// Headless/sync: begin job and drain all worker messages (tests + non-UI callers).
pub fn run_selected_analysis(&mut self) -> Result<(), String> {
self.begin_analysis_job()?;
while self.analysis_job.is_some() {
@@ -2949,12 +3000,12 @@ impl GhidrustApp {
self.log_with(msg, ConsoleSeverity::Info);
}
- /// Console warning (amber tint).
+ /// Console warning (amber tint).
fn log_warn(&mut self, msg: impl Into<String>) {
self.log_with(msg, ConsoleSeverity::Warn);
}
- /// Console error (red tint).
+ /// Console error (red tint).
fn log_error(&mut self, msg: impl Into<String>) {
self.log_with(msg, ConsoleSeverity::Error);
}
@@ -2963,14 +3014,14 @@ impl GhidrustApp {
let text = msg.into();
self.console.push(text);
self.console_severity.push(sev);
- // Keep both vectors in lockstep and bounded.
+ // Keep both vectors in lockstep and bounded.
if self.console.len() > 200 {
let drop = self.console.len() - 200;
self.console.drain(0..drop);
self.console_severity.drain(0..drop);
}
- // Backfill severity vector if it drifts (only happens if callers used
- // `self.console.push` directly; guard against future regressions).
+ // Backfill severity vector if it drifts (only happens if callers used
+ // `self.console.push` directly; guard against future regressions).
while self.console_severity.len() < self.console.len() {
self.console_severity.push(ConsoleSeverity::Info);
}
@@ -2978,39 +3029,39 @@ impl GhidrustApp {
#[allow(dead_code)] // kept for non-menubar future stubs; menubar stubs are wired
fn nyi(&mut self, what: &str) {
- let m = format!("Not yet implemented: {what}");
+ let m = format!("Not yet implemented: {what}");
self.status = m.clone();
self.nyi_note = Some(m.clone());
self.log(m);
}
- /// Render the bottom-dock tabbed panel — `Grok` (embedded TUI) + `Console`.
+ /// Render the bottom-dock tabbed panel — `Grok` (embedded TUI) + `Console`.
fn render_bottom_dock(&mut self, ui: &mut egui::Ui) {
use agent_pane::BottomTab;
ui.horizontal(|ui| {
let grok_selected = self.grok_pane.tab == BottomTab::Grok;
let console_selected = self.grok_pane.tab == BottomTab::Console;
- if ui.selectable_label(grok_selected, "Grok").clicked() {
+ if ui.selectable_label(grok_selected, "Grok").clicked() {
self.grok_pane.tab = BottomTab::Grok;
}
- if ui.selectable_label(console_selected, "Console").clicked() {
+ if ui.selectable_label(console_selected, "Console").clicked() {
self.grok_pane.tab = BottomTab::Console;
}
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
if self.grok_pane.tab == BottomTab::Console
- && ui.small_button("Clear").clicked()
+ && ui.small_button("Clear").clicked()
{
self.console.clear();
self.console_severity.clear();
}
- ui.small(egui::RichText::new("drag top edge ↕").weak().small());
+ ui.small(egui::RichText::new("drag top edge ↕").weak().small());
});
});
ui.separator();
match self.grok_pane.tab {
BottomTab::Grok => self.render_grok_tab(ui),
BottomTab::Console => {
- // Leaving the TUI — release keyboard so listing hotkeys work again.
+ // Leaving the TUI — release keyboard so listing hotkeys work again.
self.grok_pane.keyboard_captured = false;
self.render_console_tab(ui);
}
@@ -3035,12 +3086,12 @@ impl GhidrustApp {
ConsoleSeverity::Error => Color32::from_rgb(0xE5, 0x39, 0x35),
};
let prefix = match sev {
- ConsoleSeverity::Info => " ",
- ConsoleSeverity::Warn => "! ",
- ConsoleSeverity::Error => "× ",
+ ConsoleSeverity::Info => " ",
+ ConsoleSeverity::Warn => "! ",
+ ConsoleSeverity::Error => "× ",
};
ui.label(
- egui::RichText::new(format!("{prefix}{}", self.console[i]))
+ egui::RichText::new(format!("{prefix}{}", self.console[i]))
.monospace()
.color(color),
);
@@ -3095,8 +3146,8 @@ impl GhidrustApp {
if do_rescan {
self.grok_pane.refresh_grok_binary();
let msg = match &self.grok_pane.grok_bin {
- Some(p) => format!("Found grok at {}", p.display()),
- None => "grok not found on PATH — install first".into(),
+ Some(p) => format!("Found grok at {}", p.display()),
+ None => "grok not found on PATH — install first".into(),
};
self.log(msg);
}
@@ -3104,12 +3155,12 @@ impl GhidrustApp {
if let Some(bin) = self.grok_pane.grok_bin.clone() {
match ghidrust_agent::probe_grok_version(&bin) {
Ok(v) => {
- self.log(format!("grok --version → {v}"));
+ self.log(format!("grok -version → {v}"));
self.grok_pane.version_probe = Some(v);
}
Err(e) => {
- self.grok_pane.version_probe = Some(format!("(error) {e}"));
- self.log_warn(format!("grok --version failed: {e}"));
+ self.grok_pane.version_probe = Some(format!("(error) {e}"));
+ self.log_warn(format!("grok -version failed: {e}"));
}
}
}
@@ -3121,16 +3172,16 @@ impl GhidrustApp {
}
if let Some(e) = start_err {
self.grok_pane.last_error = Some(e.clone());
- self.log_error(format!("Grok TUI failed: {e}"));
+ self.log_error(format!("Grok TUI failed: {e}"));
}
}
- /// Build the current program-facts snapshot for the Grok pane.
- ///
- /// This is what makes the agent actually *know* about the open project
- /// and the currently-loaded file without needing an MCP round-trip first.
- /// Every field is honest-empty when the underlying analysis hasn't run —
- /// matches Ghidrust's "no fabrication on empty evidence" rule.
+ /// Build the current program-facts snapshot for the Grok pane.
+ ///
+ /// This is what makes the agent actually *know* about the open project
+ /// and the currently-loaded file without needing an MCP round-trip first.
+ /// Every field is honest-empty when the underlying analysis hasn't run —
+ /// matches Ghidrust's "no fabrication on empty evidence" rule.
fn grok_program_facts(&self) -> ghidrust_agent::ProgramFacts {
const TOP_FN_SAMPLE: usize = 24;
const IMPORT_SAMPLE: usize = 24;
@@ -3141,7 +3192,7 @@ impl GhidrustApp {
f.project_root = Some(proj.root.display().to_string());
for file in &proj.meta.files {
let has_saved = proj.results_dir().join(&file.id).exists()
- || proj.results_dir().join(format!("{}.bin", file.id)).exists();
+ || proj.results_dir().join(format!("{}.bin", file.id)).exists();
f.project_files.push(ghidrust_agent::ProjectFileFact {
id: file.id.clone(),
display_name: file.display_name.clone(),
@@ -3153,21 +3204,21 @@ impl GhidrustApp {
if let Some(prog) = &self.program {
f.program = Some(prog.name.clone());
f.format = Some(prog.format.clone());
- f.arch = Some("x86_64".into());
- f.image_base = Some(format!("{:#x}", prog.image_base));
- f.entry_va = prog.entry.map(|v| format!("{v:#x}"));
+ f.arch = Some("x86_64".into());
+ f.image_base = Some(format!("{:#x}", prog.image_base));
+ f.entry_va = prog.entry.map(|v| format!("{v:#x}"));
f.functions = Some(prog.analysis.functions.len());
f.strings = Some(self.strings.len());
for s in &prog.sections {
f.sections.push(ghidrust_agent::SectionFact {
name: s.name.clone(),
- va: format!("{:#x}", s.va),
+ va: format!("{:#x}", s.va),
size: s.virtual_size,
});
}
for fi in prog.analysis.functions.iter().take(TOP_FN_SAMPLE) {
f.top_functions.push(ghidrust_agent::FunctionFact {
- va: format!("{:#x}", fi.entry),
+ va: format!("{:#x}", fi.entry),
name: fi.name.clone(),
});
}
@@ -3187,14 +3238,14 @@ impl GhidrustApp {
.as_ref()
.and_then(|p| p.display_function_name_at(va));
f.current_selection = Some(ghidrust_agent::SelectionFact {
- va: format!("{va:#x}"),
+ va: format!("{va:#x}"),
name,
});
}
f
}
- /// Write MCP/skill/context and spawn the real Grok TUI in the PTY pane.
+ /// Write MCP/skill/context and spawn the real Grok TUI in the PTY pane.
fn start_grok_pty(
&mut self,
cols: u16,
@@ -3207,27 +3258,27 @@ impl GhidrustApp {
.grok_bin
.clone()
.ok_or_else(|| {
- "grok binary not installed — click 'Install Grok Build…' first".to_string()
+ "grok binary not installed — click 'Install Grok Build…' first".to_string()
})?;
let project_root: std::path::PathBuf = match &self.project {
Some(p) => p.root.clone(),
None => std::env::current_dir()
- .unwrap_or_else(|_| std::path::PathBuf::from(".")),
+ .unwrap_or_else(|_| std::path::PathBuf::from(".")),
};
let ghidrust_bin = ghidrust_agent::resolve_ghidrust_cli_bin().ok_or_else(|| {
- "ghidrust CLI not found next to the GUI or on PATH — build `ghidrust` \
- (cargo build -p ghidrust-cli --release) so MCP can start"
+ "ghidrust CLI not found next to the GUI or on PATH — build `ghidrust` \
+ (cargo build -p ghidrust-cli -release) so MCP can start"
.to_string()
})?;
if !ghidrust_bin.is_file() {
return Err(format!(
- "ghidrust CLI missing at {} — MCP cannot start",
+ "ghidrust CLI missing at {} — MCP cannot start",
ghidrust_bin.display()
));
}
let (_skill_body, skill_source) = load_skill_body();
let facts = self.grok_program_facts();
- // Drop any prior session before spawning a new one.
+ // Drop any prior session before spawning a new one.
self.grok_pane.session = None;
let session = agent_pane::start_pty_session(
&bin,
@@ -3240,7 +3291,7 @@ impl GhidrustApp {
rows,
)?;
self.log(format!(
- "Grok TUI started · project={} · grok={} · mcp={}",
+ "Grok TUI started · project={} · grok={} · mcp={}",
project_root.display(),
bin.display(),
ghidrust_bin.display()
@@ -3252,10 +3303,10 @@ impl GhidrustApp {
Ok(())
}
- /// Analysis → GPU Decompile… — resolve the dialog's address (containing
- /// function honesty via `resolve_function`) then run
- /// `ghidrust_decomp::gpu_decompile_to_file` (GPU pipeline with automatic
- /// CPU multipass fallback outside the `gpu` feature).
+ /// Analysis → GPU Decompile… — resolve the dialog's address (containing
+ /// function honesty via `resolve_function`) then run
+ /// `ghidrust_decomp::gpu_decompile_to_file` (GPU pipeline with automatic
+ /// CPU multipass fallback outside the `gpu` feature).
fn run_gpu_decompile_dialog(&mut self) {
let dialog = &mut self.tool_panes.gpu_decompile;
dialog.error = None;
@@ -3264,7 +3315,7 @@ impl GhidrustApp {
let max_bytes: usize = dialog.max_bytes_input.trim().parse().unwrap_or(256).max(32);
let addr_input = dialog.addr_input.trim().to_string();
let Some(prog) = self.program.as_mut() else {
- self.tool_panes.gpu_decompile.error = Some("no program loaded".into());
+ self.tool_panes.gpu_decompile.error = Some("no program loaded".into());
return;
};
let addr = if addr_input.is_empty() {
@@ -3273,7 +3324,7 @@ impl GhidrustApp {
match parse_address(&addr_input) {
Ok(a) => a,
Err(e) => {
- self.tool_panes.gpu_decompile.error = Some(format!("bad address: {e}"));
+ self.tool_panes.gpu_decompile.error = Some(format!("bad address: {e}"));
return;
}
}
@@ -3281,18 +3332,18 @@ impl GhidrustApp {
let resolve = match ghidrust_core::resolve_function(prog, addr) {
Ok(r) => r,
Err(e) => {
- self.tool_panes.gpu_decompile.error = Some(format!("resolve_function: {e}"));
+ self.tool_panes.gpu_decompile.error = Some(format!("resolve_function: {e}"));
return;
}
};
if !resolve.ok {
self.tool_panes.gpu_decompile.resolve = Some(resolve);
self.tool_panes.gpu_decompile.error =
- Some("address did not resolve to a function — see resolve_status above".into());
+ Some("address did not resolve to a function — see resolve_status above".into());
return;
}
let entry = resolve.resolved_entry.unwrap_or(addr);
- let dump_path = std::env::temp_dir().join(format!("ghidrust-gpu-decompile-{entry:016x}.txt"));
+ let dump_path = std::env::temp_dir().join(format!("ghidrust-gpu-decompile-{entry:016x}.txt"));
match ghidrust_decomp::gpu_decompile_to_file(prog, Some(entry), &dump_path, max_bytes) {
Ok(rep) => {
let preview: String = rep.pseudo_c.chars().take(4000).collect();
@@ -3314,53 +3365,53 @@ impl GhidrustApp {
});
self.tool_panes.gpu_decompile.resolve = Some(resolve);
self.log(format!(
- "GPU Decompile · {:#x} · backend={}",
+ "GPU Decompile · {:#x} · backend={}",
entry, self.tool_panes.gpu_decompile.summary.as_ref().unwrap().backend
));
}
Err(e) => {
self.tool_panes.gpu_decompile.resolve = Some(resolve);
- self.tool_panes.gpu_decompile.error = Some(format!("gpu_decompile_to_file: {e}"));
+ self.tool_panes.gpu_decompile.error = Some(format!("gpu_decompile_to_file: {e}"));
}
}
}
- /// Menu / pane identifiers present in the shell (for structural tests).
- ///
- /// Ghidra top-level menus (from `docking.tool.ToolConstants`):
- /// File, Edit, Analysis, Navigation, Search, Select, Tools, Graph, Window, Help.
- pub fn shell_menus() -> &'static [&'static str] {
+ /// Menu / pane identifiers present in the shell (for structural tests).
+ ///
+ /// top-level menus (from `docking.tool.ToolConstants`):
+ /// File, Edit, Analysis, Navigation, Search, Select, Tools, Graph, Window, Help.
+ pub fn shell_menus() -> &'static [&'static str] {
&[
- "File",
- "Edit",
- "Analysis",
- "Navigation",
- "Search",
- "Select",
- "Tools",
- "Graph",
- "Window",
- "Debugger",
- "Help",
+ "File",
+ "Edit",
+ "Analysis",
+ "Navigation",
+ "Search",
+ "Select",
+ "Tools",
+ "Graph",
+ "Window",
+ "Debugger",
+ "Help",
]
}
- /// Every provider (CodeBrowser + off-layout) enumerated for visible-parity tests.
- ///
- /// Ghidrust panes use these exact labels for the Window menu and the structural test.
- /// See `panes::PaneKind::ALL` for the source of truth; a stable Vec is materialized
- /// on demand to keep the API `&'static [&'static str]`-like for existing tests.
- pub fn shell_panes() -> Vec<&'static str> {
- // Legacy names kept for backwards compat with previous test assertions.
- let mut names: Vec<&'static str> = vec![
- "Project Tree",
- "Program Tree", // legacy short name (Ghidra title = "Program Trees")
- "Symbol Tree",
- "Overview",
- "Listing",
- "Decompiler", // legacy short name (Ghidra title = "Decompile")
- "Data Type Manager",
- "Console",
+ /// Every provider ( + off-layout) enumerated for visibility tests.
+ ///
+ /// Ghidrust panes use these exact labels for the Window menu and the structural test.
+ /// See `panes::PaneKind::ALL` for the source of truth; a stable Vec is materialized
+ /// on demand to keep the API `&'static [&'static str]`-like for existing tests.
+ pub fn shell_panes() -> Vec<&'static str> {
+ // Legacy names kept for backwards compat with previous test assertions.
+ let mut names: Vec<&'static str> = vec![
+ "Project Tree",
+ "Program Tree", // legacy short name .
+ "Symbol Tree",
+ "Overview",
+ "Listing",
+ "Decompiler", // legacy short name .
+ "Data Type Manager",
+ "Console",
];
for k in PaneKind::ALL {
let t = k.title();
@@ -3368,12 +3419,9 @@ impl GhidrustApp {
names.push(t);
}
}
- // Ghidra Debugger tool providers (visibility parity).
- for p in DebuggerPane::ALL {
- let t = p.title();
- if !names.contains(&t) {
- names.push(t);
- }
+ // Single tabbed Debugger host .
+ if !names.contains(&"Debugger") {
+ names.push("Debugger");
}
names
}
@@ -3385,7 +3433,7 @@ impl GhidrustApp {
Color32::from_rgb(t.on_surface_variant[0], t.on_surface_variant[1], t.on_surface_variant[2]);
let surface = Color32::from_rgb(t.surface_container[0], t.surface_container[1], t.surface_container[2]);
- // Fixed card size — never wider than the window, never stretch off-screen.
+ // Fixed card size — never wider than the window, never stretch off-screen.
let card_w = 440.0_f32
.min(ctx.screen_rect().width() - 48.0)
.max(280.0);
@@ -3393,9 +3441,9 @@ impl GhidrustApp {
egui::CentralPanel::default().show(ctx, |ui| {
ui.vertical_centered(|ui| {
ui.add_space(32.0);
- ui.heading(egui::RichText::new("Ghidrust").size(26.0).color(primary));
+ ui.heading(egui::RichText::new("Ghidrust").size(26.0).color(primary));
ui.label(
- egui::RichText::new("Open a project to reverse engineer")
+ egui::RichText::new("Open a project to reverse engineer")
.color(muted)
.size(14.0),
);
@@ -3409,8 +3457,8 @@ impl GhidrustApp {
ui.set_width(card_w);
ui.set_max_width(card_w);
- // ── Recent projects (IDE-style list) ──
- ui.label(egui::RichText::new("Recent projects").strong().size(13.0));
+ // ── Recent projects (IDE-style list) ──
+ ui.label(egui::RichText::new("Recent projects").strong().size(13.0));
ui.add_space(6.0);
let recents = self.recent_projects.clone();
@@ -3423,14 +3471,14 @@ impl GhidrustApp {
.show(ui, |ui| {
ui.set_width(card_w - 8.0);
egui::ScrollArea::vertical()
- .id_salt("startup_recent")
+ .id_salt("startup_recent")
.max_height(list_h)
.auto_shrink([false, false])
.show(ui, |ui| {
ui.set_min_width(card_w - 24.0);
if recents.is_empty() {
ui.add_space(8.0);
- ui.weak("No recent projects — open or create one below.");
+ ui.weak("No recent projects — open or create one below.");
ui.add_space(8.0);
} else {
let mut open_path: Option<String> = None;
@@ -3439,7 +3487,7 @@ impl GhidrustApp {
.file_name()
.map(|s| s.to_string_lossy().into_owned())
.unwrap_or_else(|| path.clone());
- // IDE-style row: project name + path, full-width click
+ // IDE-style row: project name + path, full-width click
let row_w = (card_w - 24.0).max(200.0);
let row_h = 44.0;
let (rect, resp) = ui.allocate_exact_size(
@@ -3470,12 +3518,12 @@ impl GhidrustApp {
if resp.clicked() {
open_path = Some(path.clone());
}
- resp.on_hover_text(format!("Open project: {path}"));
+ resp.on_hover_text(format!("Open project: {path}"));
}
if let Some(path) = open_path {
self.project_dir_input = path;
if let Err(e) = self.open_project() {
- self.status = format!("error: {e}");
+ self.status = format!("error: {e}");
self.log(self.status.clone());
self.show_startup_picker = true;
}
@@ -3488,12 +3536,12 @@ impl GhidrustApp {
ui.separator();
ui.add_space(10.0);
- // Buttons fit card width only (no off-screen stretch)
+ // Buttons fit card width only (no off-screen stretch)
let btn_w = card_w - 8.0;
if ui
.add_sized(
[btn_w, 32.0],
- egui::Button::new("Open existing project…"),
+ egui::Button::new("Open existing project…"),
)
.clicked()
{
@@ -3504,16 +3552,16 @@ impl GhidrustApp {
}
ui.add_space(8.0);
ui.horizontal(|ui| {
- ui.label("Name:");
+ ui.label("Name:");
ui.add(
egui::TextEdit::singleline(&mut self.project_name_input)
.desired_width((btn_w - 56.0).max(120.0))
- .hint_text("MyProject"),
+ .hint_text("MyProject"),
);
});
ui.add_space(4.0);
if ui
- .add_sized([btn_w, 32.0], egui::Button::new("Create new project…"))
+ .add_sized([btn_w, 32.0], egui::Button::new("Create new project…"))
.clicked()
{
self.browse_and_create_project();
@@ -3522,15 +3570,15 @@ impl GhidrustApp {
}
}
ui.add_space(12.0);
- if ui.link("Continue without a project").clicked() {
+ if ui.link("Continue without a project").clicked() {
self.show_startup_picker = false;
self.status =
- "No project — Browse/Load a binary, or File → Open Project".into();
+ "No project — Browse/Load a binary, or File → Open Project".into();
}
ui.add_space(4.0);
ui.small(
egui::RichText::new(
- "Click a recent project name to open it. Analysis uses analysis.bin for fast load.",
+ "Click a recent project name to open it. Analysis uses analysis.bin for fast load.",
)
.color(muted),
);
@@ -3546,11 +3594,11 @@ impl GhidrustApp {
Color32::from_rgb(t.on_surface_variant[0], t.on_surface_variant[1], t.on_surface_variant[2]);
let ok = Color32::from_rgb(0x4C, 0xAF, 0x50);
- ui.heading("Overview");
+ ui.heading("Overview");
let Some(prog) = self.program.as_ref() else {
- ui.weak("No program open.");
- ui.label("Project Tree: double-click a file (or Open) to load it into this view.");
- ui.label("If the file is Analyzed, RTTI / functions load from results/ automatically.");
+ ui.weak("No program open.");
+ ui.label("Project Tree: double-click a file (or Open) to load it into this view.");
+ ui.label("If the file is Analyzed, RTTI / functions load from results/ automatically.");
return;
};
@@ -3563,11 +3611,11 @@ impl GhidrustApp {
}
});
ui.label(egui::RichText::new(format!(
- "{} · image base {:#x}{}",
+ "{} · image base {:#x}{}",
prog.format,
prog.image_base,
prog.entry
- .map(|e| format!(" · entry {e:#x}"))
+ .map(|e| format!(" · entry {e:#x}"))
.unwrap_or_default()
)).color(muted));
@@ -3580,28 +3628,28 @@ impl GhidrustApp {
ui.label(egui::RichText::new(value).strong().color(primary).size(18.0));
});
};
- card(ui, "Functions", format!("{}", prog.analysis.functions.len()));
- card(ui, "RTTI classes", format!("{}", self.rtti.classes.len()));
- card(ui, "Strings", format!("{}", self.strings.len()));
- card(ui, "Listing lines", format!("{}", self.listing.len()));
- card(ui, "Sections", format!("{}", prog.sections.len()));
+ card(ui, "Functions", format!("{}", prog.analysis.functions.len()));
+ card(ui, "RTTI classes", format!("{}", self.rtti.classes.len()));
+ card(ui, "Strings", format!("{}", self.strings.len()));
+ card(ui, "Listing lines", format!("{}", self.listing.len()));
+ card(ui, "Sections", format!("{}", prog.sections.len()));
});
ui.add_space(10.0);
if !self.last_analyzers_run.is_empty() {
- ui.label(egui::RichText::new("Analyzers last run / saved").strong());
+ ui.label(egui::RichText::new("Analyzers last run / saved").strong());
ui.horizontal_wrapped(|ui| {
for a in &self.last_analyzers_run {
- ui.small(format!("[{a}]"));
+ ui.small(format!("[{a}]"));
}
});
} else {
- ui.weak("No analyzer list saved for this session — run Analyze to record one.");
+ ui.weak("No analyzer list saved for this session — run Analyze to record one.");
}
if !self.rtti.notes.is_empty() {
ui.add_space(6.0);
- ui.label(egui::RichText::new("RTTI notes").strong());
+ ui.label(egui::RichText::new("RTTI notes").strong());
for n in &self.rtti.notes {
ui.small(n);
}
@@ -3609,45 +3657,45 @@ impl GhidrustApp {
ui.add_space(12.0);
ui.separator();
- ui.label(egui::RichText::new("What to do next").strong());
- ui.label("• Symbol Tree (right): expand Classes / RTTI, type a filter, scroll the list.");
- ui.label("• Listing tab: entry disassembly.");
- ui.label("• Analyze: re-run analyzers (shows options + progress).");
+ ui.label(egui::RichText::new("What to do next").strong());
+ ui.label("• Symbol Tree (right): expand Classes / RTTI, type a filter, scroll the list.");
+ ui.label("• Listing tab: entry disassembly.");
+ ui.label("• Analyze: re-run analyzers (shows options + progress).");
if self.rtti.classes.len() > 1000 {
ui.label(
egui::RichText::new(format!(
- "• Large RTTI set ({} classes) — always filter; the list is virtualized so it stays smooth.",
+ "• Large RTTI set ({} classes) — always filter; the list is virtualized so it stays smooth.",
self.rtti.classes.len()
))
.color(primary),
);
}
- // Sample of first few RTTI hits for confidence without opening the full drawer
+ // Sample of first few RTTI hits for confidence without opening the full drawer
if !self.rtti.classes.is_empty() {
ui.add_space(10.0);
- ui.label(egui::RichText::new("RTTI sample (first 12)").strong());
+ ui.label(egui::RichText::new("RTTI sample (first 12)").strong());
egui::ScrollArea::vertical().max_height(160.0).show(ui, |ui| {
for c in self.rtti.classes.iter().take(12) {
let va = c
.type_info_va
- .map(|v| format!("{v:#x}"))
- .unwrap_or_else(|| "—".into());
- ui.monospace(format!("{va} {}", c.name));
+ .map(|v| format!("{v:#x}"))
+ .unwrap_or_else(|| "—".into());
+ ui.monospace(format!("{va} {}", c.name));
}
});
- if ui.button("Focus Symbol Tree → RTTI").clicked() {
+ if ui.button("Focus Symbol Tree → RTTI").clicked() {
self.show_symbol_tree = true;
}
}
}
- /// 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
- /// pending" empty state that names the analyzer/model responsible for filling
- /// them. See `panes::empty_state` for the shared template.
+ /// 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
+ /// pending" empty state that names the analyzer/model responsible for filling
+ /// them. See `panes::empty_state` for the shared template.
fn draw_provider_panes(&mut self, ctx: &egui::Context) {
let t = m3_tokens(self.theme);
let muted = Color32::from_rgb(
@@ -3657,7 +3705,7 @@ impl GhidrustApp {
);
let primary = Color32::from_rgb(t.primary[0], t.primary[1], t.primary[2]);
- // Snapshot the open-list so we can mutate self inside the closure.
+ // Snapshot the open-list so we can mutate self inside the closure.
let open_list: Vec<PaneKind> = self
.pane_open
.iter()
@@ -3723,7 +3771,7 @@ impl GhidrustApp {
PaneKind::ChecksumGenerator => {
win.show(ctx, |ui| self.ui_checksum_generator(ui, muted));
}
- // 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));
@@ -3748,7 +3796,7 @@ impl GhidrustApp {
win.default_size(egui::vec2(560.0, 520.0))
.show(ctx, |ui| self.ui_register_manager_pane(ui, muted, primary));
}
- // 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));
@@ -3761,7 +3809,7 @@ impl GhidrustApp {
win.default_size(egui::vec2(640.0, 420.0))
.show(ctx, |ui| self.ui_mcp_repl_pane(ui, muted, primary));
}
- // Agent Friction Closure §13 — tool panes (real backends).
+ // Agent Friction Closure §13 — tool panes (real backends).
PaneKind::Il2cppMetadata => {
win.default_size(egui::vec2(720.0, 560.0)).show(ctx, |ui| {
tool_panes::ui_il2cpp_metadata(ui, &mut self.tool_panes.il2cpp_meta, muted);
@@ -3800,31 +3848,31 @@ impl GhidrustApp {
});
}
}
- // Reflect close-button clicks back into our state.
+ // Reflect close-button clicks back into our state.
if !open {
self.pane_open.insert(kind, false);
}
}
- // Debugger tool provider windows.
+ // Debugger tool provider windows.
self.draw_debugger_panes(ctx, muted);
}
- // ── Graphs & maps ────────────────────────────────────
+ // ── Graphs & maps ────────────────────────────────────
- /// Ghidra `FunctionGraphPlugin` — CFG vertex/edge layout for the current function.
+ /// `` — CFG vertex/edge layout for the current function.
fn ui_function_graph_pane(&mut self, ui: &mut egui::Ui, muted: Color32, primary: Color32) {
- ui.heading("Function Graph");
+ ui.heading("Function Graph");
ui.small(
egui::RichText::new(
- "Ghidra FunctionGraphPlugin analog · Stage-0 CFG from ghidrust-decomp::decompile_at",
+ "FunctionGraphPlugin analog · Stage-0 CFG from ghidrust-decomp::decompile_at",
)
.color(muted),
);
ui.separator();
let Some(prog) = self.program.as_ref() else {
- ui.weak("No program loaded.");
+ ui.weak("No program loaded.");
return;
};
let Some(entry) = self
@@ -3837,10 +3885,10 @@ impl GhidrustApp {
.map(|f| f.entry)
}))
else {
- ui.weak("Cursor is not inside a recovered function.");
+ ui.weak("Cursor is not inside a recovered function.");
ui.small(
egui::RichText::new(
- "Click a function in Symbol Tree, Functions, or Listing to populate the graph.",
+ "Click a function in Symbol Tree, Functions, or Listing to populate the graph.",
)
.color(muted),
);
@@ -3848,9 +3896,9 @@ impl GhidrustApp {
};
ui.horizontal(|ui| {
- ui.label("Layout:");
+ ui.label("Layout:");
let cur = self.graph_state.fn_graph_layout;
- egui::ComboBox::from_id_salt("fg_layout")
+ egui::ComboBox::from_id_salt("fg_layout")
.selected_text(cur.label())
.show_ui(ui, |ui| {
for l in FunctionGraphLayout::ALL {
@@ -3858,23 +3906,23 @@ impl GhidrustApp {
}
});
ui.separator();
- ui.label("Zoom:");
+ ui.label("Zoom:");
ui.add(
egui::Slider::new(&mut self.graph_state.fn_graph_zoom, 0.5..=2.0)
.clamping(egui::SliderClamping::Always)
.fixed_decimals(1),
);
- if ui.button("Fit").on_hover_text("Reset zoom to 1.0").clicked() {
+ if ui.button("Fit").on_hover_text("Reset zoom to 1.0").clicked() {
self.graph_state.fn_graph_zoom = 1.0;
}
ui.separator();
- ui.small(egui::RichText::new(format!("Entry {entry:#x}")).color(muted));
+ ui.small(egui::RichText::new(format!("Entry {entry:#x}")).color(muted));
});
ui.separator();
let name = prog.display_function_name_at(entry).unwrap_or_default();
if !name.is_empty() {
- ui.small(egui::RichText::new(format!("Function {name}")).color(muted));
+ ui.small(egui::RichText::new(format!("Function {name}")).color(muted));
}
let algo = self.graph_state.fn_graph_layout;
@@ -3895,7 +3943,7 @@ impl GhidrustApp {
ui.painter().text(
rect.center(),
egui::Align2::CENTER_CENTER,
- "No Stage-0 CFG recovered for this VA.",
+ "No Stage-0 CFG recovered for this VA.",
egui::FontId::proportional(13.0),
muted,
);
@@ -3903,28 +3951,28 @@ impl GhidrustApp {
}
let clicked = render_function_graph(ui, &blocks, &edges, focused_va, primary, muted);
if let Some(va) = clicked {
- let _ = self.goto_address_str(&format!("{va:#x}"));
+ let _ = self.goto_address_str(&format!("{va:#x}"));
}
}
- /// Ghidra `FunctionCallGraphPlugin` — level-based directed graph.
+ /// `` — level-based directed graph.
fn ui_function_call_graph_pane(
&mut self,
ui: &mut egui::Ui,
muted: Color32,
primary: Color32,
) {
- ui.heading("Function Call Graph");
+ ui.heading("Function Call Graph");
ui.small(
egui::RichText::new(
- "Ghidra FunctionCallGraphPlugin analog · levels expanded from analyzer references",
+ "FunctionCallGraphPlugin analog · levels expanded from analyzer references",
)
.color(muted),
);
ui.separator();
let Some(prog) = self.program.as_ref() else {
- ui.weak("No program loaded.");
+ ui.weak("No program loaded.");
return;
};
let Some(entry) = self
@@ -3938,21 +3986,21 @@ impl GhidrustApp {
}))
.or(prog.entry)
else {
- ui.weak("No entry point — click a function in Symbol Tree to root the call graph.");
+ ui.weak("No entry point — click a function in Symbol Tree to root the call graph.");
return;
};
ui.horizontal(|ui| {
- ui.label("Callers levels:");
+ ui.label("Callers levels:");
let mut lvl_in = self.graph_state.call_graph_levels_in;
ui.add(egui::Slider::new(&mut lvl_in, 0..=3));
self.graph_state.call_graph_levels_in = lvl_in;
ui.separator();
- ui.label("Callees levels:");
+ ui.label("Callees levels:");
let mut lvl_out = self.graph_state.call_graph_levels_out;
ui.add(egui::Slider::new(&mut lvl_out, 0..=3));
self.graph_state.call_graph_levels_out = lvl_out;
- if ui.button("Reset").clicked() {
+ if ui.button("Reset").clicked() {
self.graph_state.call_graph_levels_in = 1;
self.graph_state.call_graph_levels_out = 1;
}
@@ -3980,7 +4028,7 @@ impl GhidrustApp {
ui.painter().text(
rect.center(),
egui::Align2::CENTER_CENTER,
- "No call references recovered — run analyzers first.",
+ "No call references recovered — run analyzers first.",
egui::FontId::proportional(13.0),
muted,
);
@@ -3992,24 +4040,24 @@ impl GhidrustApp {
}
}
- /// Ghidra `CallTreePlugin` — incoming callers / outgoing callees GTree pair.
+ /// `` — incoming callers / outgoing callees GTree pair.
fn ui_function_call_trees_pane(
&mut self,
ui: &mut egui::Ui,
muted: Color32,
primary: Color32,
) {
- ui.heading("Function Call Trees");
+ ui.heading("Function Call Trees");
ui.small(
egui::RichText::new(
- "Ghidra CallTreePlugin analog · Incoming / Outgoing GTrees over analyzer refs",
+ "CallTreePlugin analog · Incoming / Outgoing GTrees over analyzer refs",
)
.color(muted),
);
ui.separator();
let Some(prog) = self.program.as_ref() else {
- ui.weak("No program loaded.");
+ ui.weak("No program loaded.");
return;
};
let Some(entry) = self
@@ -4022,26 +4070,26 @@ impl GhidrustApp {
.map(|f| f.entry)
}))
else {
- ui.weak("Cursor is not inside a recovered function.");
+ ui.weak("Cursor is not inside a recovered function.");
return;
};
- // Rebuild top level if root changed.
+ // Rebuild top level if root changed.
let root_name = prog.display_function_name_at(entry).unwrap_or_default();
ui.horizontal(|ui| {
- ui.small(egui::RichText::new(format!("Source {root_name} @ {entry:#x}")).color(muted));
- if ui.button("Refresh").clicked() {
+ ui.small(egui::RichText::new(format!("Source {root_name} @ {entry:#x}")).color(muted));
+ if ui.button("Refresh").clicked() {
self.call_tree_incoming.clear();
self.call_tree_outgoing.clear();
}
ui.separator();
ui.checkbox(
&mut self.graph_state.call_tree_hide_thunks,
- "Hide thunks",
+ "Hide thunks",
);
ui.checkbox(
&mut self.graph_state.call_tree_refs_only,
- "References only",
+ "References only",
);
});
ui.separator();
@@ -4059,17 +4107,17 @@ impl GhidrustApp {
let hide_thunks = self.graph_state.call_tree_hide_thunks;
let mut goto: Option<u64> = None;
egui::ScrollArea::vertical()
- .id_salt("calltrees_scroll")
+ .id_salt("calltrees_scroll")
.max_height(360.0)
.show(ui, |ui| {
ui.columns(2, |cols| {
- cols[0].label(egui::RichText::new("Incoming (callers / refs to)").strong());
+ cols[0].label(egui::RichText::new("Incoming (callers / refs to)").strong());
let mut inc = std::mem::take(&mut self.call_tree_incoming);
for (i, node) in inc.iter_mut().enumerate() {
render_call_tree_node(
node,
i,
- "incoming",
+ "incoming",
prog,
hide_thunks,
&mut cols[0],
@@ -4082,13 +4130,13 @@ impl GhidrustApp {
if refs_only {
cols[0].separator();
cols[0].label(
- egui::RichText::new("Data refs to source")
+ egui::RichText::new("Data refs to source")
.strong()
.color(muted),
);
for xr in data_xrefs_to(prog, entry) {
let text = egui::RichText::new(format!(
- "{} {} ← {:#x}",
+ "{} {} ← {:#x}",
xr.kind, xr.preview, xr.from
))
.monospace();
@@ -4098,13 +4146,13 @@ impl GhidrustApp {
}
}
- cols[1].label(egui::RichText::new("Outgoing (callees / refs from)").strong());
+ cols[1].label(egui::RichText::new("Outgoing (callees / refs from)").strong());
let mut out = std::mem::take(&mut self.call_tree_outgoing);
for (i, node) in out.iter_mut().enumerate() {
render_call_tree_node(
node,
i,
- "outgoing",
+ "outgoing",
prog,
hide_thunks,
&mut cols[1],
@@ -4121,37 +4169,37 @@ impl GhidrustApp {
}
}
- /// Ghidra `EntropyPlugin` header — Shannon-entropy strip across mapped blocks.
+ /// `` header — Shannon-entropy strip across mapped blocks.
fn ui_entropy_pane(&mut self, ui: &mut egui::Ui, muted: Color32, primary: Color32) {
- ui.heading("Entropy");
+ ui.heading("Entropy");
ui.small(
egui::RichText::new(
- "Ghidra EntropyPlugin analog · Shannon bits/byte over 256-byte windows",
+ "EntropyPlugin analog · Shannon bits/byte over 256-byte windows",
)
.color(muted),
);
ui.separator();
let Some(prog) = self.program.as_ref() else {
- ui.weak("No program loaded.");
+ ui.weak("No program loaded.");
return;
};
let samples = entropy::entropy_samples(prog, 256);
- ui.small(format!("{} windows sampled (256 bytes each)", samples.len()));
+ ui.small(format!("{} windows sampled (256 bytes each)", samples.len()));
let clicked_e =
entropy::render_entropy_strip(ui, &samples, muted, self.listing_focus_va, primary);
ui.add_space(6.0);
- ui.label(egui::RichText::new("Overview").strong().color(muted));
+ ui.label(egui::RichText::new("Overview").strong().color(muted));
let clicked_o =
entropy::render_overview_strip(ui, prog, &samples, muted, self.listing_focus_va, primary);
ui.small(
- egui::RichText::new("Click a strip to Go To that address. Green = exec, amber = writable, grey = readonly, cold-blue = low entropy, warm-red = high.").color(muted),
+ egui::RichText::new("Click a strip to Go To that address. Green = exec, amber = writable, grey = readonly, cold-blue = low entropy, warm-red = high.").color(muted),
);
if let Some(va) = clicked_e.or(clicked_o) {
- let _ = self.goto_address_str(&format!("{va:#x}"));
+ let _ = self.goto_address_str(&format!("{va:#x}"));
}
}
- /// Ghidra `RegisterPlugin` — register lattice + user-set value ranges.
+ /// `` — register lattice + user-set value ranges.
fn ui_register_manager_pane(
&mut self,
ui: &mut egui::Ui,
@@ -4162,12 +4210,12 @@ impl GhidrustApp {
register_manager::render(&mut self.register_manager, fmt.as_deref(), ui, muted, primary);
}
- // ── 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 not yet wired"
+ "Script Manager · run requested for `{run}` — full script host not yet wired"
);
self.status = msg.clone();
self.log(msg);
@@ -4181,26 +4229,26 @@ impl GhidrustApp {
TextEditorRequest::NewUntitled => self.text_editor.open_untitled(),
TextEditorRequest::OpenFile => {
if let Some(path) = rfd::FileDialog::new()
- .add_filter("Scripts", &["py", "rs", "txt", "md", "json", "toml"])
- .add_filter("All", &["*"])
+ .add_filter("Scripts", &["py", "rs", "txt", "md", "json", "toml"])
+ .add_filter("All", &["*"])
.pick_file()
{
if let Err(e) = self.text_editor.open_file(path) {
- self.status = format!("open error: {e}");
+ self.status = format!("open error: {e}");
self.log_error(self.status.clone());
}
}
}
TextEditorRequest::Save => {
if let Err(e) = self.text_editor.save_active() {
- self.status = format!("save error: {e}");
+ self.status = format!("save error: {e}");
self.log_error(self.status.clone());
}
}
TextEditorRequest::SaveAs => {
if let Some(path) = rfd::FileDialog::new().save_file() {
if let Err(e) = self.text_editor.save_active_as(path) {
- self.status = format!("save error: {e}");
+ self.status = format!("save error: {e}");
self.log_error(self.status.clone());
}
}
@@ -4213,33 +4261,13 @@ impl GhidrustApp {
render_mcp_repl(&mut self.mcp_repl, ui, muted, primary);
}
- // ── Debugger tool ──────────────────────────────────
+ // ── Debugger tool ──────────────────────────────────
fn draw_debugger_panes(&mut self, ctx: &egui::Context, muted: Color32) {
- let open_list: Vec<DebuggerPane> = self
- .debugger_open
- .iter()
- .filter_map(|(p, v)| if *v { Some(*p) } else { None })
- .collect();
- for pane in open_list {
- let mut open = true;
- let title = pane.title();
- let id = egui::Id::new(pane.egui_id());
- egui::Window::new(title)
- .id(id)
- .open(&mut open)
- .resizable(true)
- .default_size(egui::vec2(520.0, 320.0))
- .show(ctx, |ui| {
- debugger::render(pane, &mut self.debugger, ui, muted);
- });
- if !open {
- self.debugger_open.insert(pane, false);
- }
- }
+ debugger::draw_host(ctx, &mut self.debugger, muted);
}
- // ── Docking / layouts / Configure ────────────────
+ // ── Docking / layouts / Configure ────────────────
fn snapshot_current_layout(&self, name: impl Into<String>) -> layouts::SavedLayout {
let name = name.into();
@@ -4247,19 +4275,17 @@ impl GhidrustApp {
for (k, v) in &self.pane_open {
open_panes.insert(k.egui_id().to_string(), *v);
}
- for (p, v) in &self.debugger_open {
- open_panes.insert(p.egui_id().to_string(), *v);
- }
+ debugger::snapshot_layout_flags(&self.debugger, &mut open_panes);
let mut docks = BTreeMap::new();
- docks.insert("project_tree".into(), self.show_project_tree);
- docks.insert("program_tree".into(), self.show_program_tree);
- docks.insert("symbol_tree".into(), self.show_symbol_tree);
- docks.insert("console".into(), self.show_console);
+ docks.insert("project_tree".into(), self.show_project_tree);
+ docks.insert("program_tree".into(), self.show_program_tree);
+ docks.insert("symbol_tree".into(), self.show_symbol_tree);
+ docks.insert("console".into(), self.show_console);
let center = dock_tabs::active_center_id(&self.center_dock).to_string();
let dock_tree = serde_json::to_value(&self.center_dock).ok();
let theme = match self.theme {
- ThemeMode::Dark => "dark",
- ThemeMode::Light => "light",
+ ThemeMode::Dark => "dark",
+ ThemeMode::Light => "light",
}
.to_string();
layouts::SavedLayout {
@@ -4274,8 +4300,8 @@ impl GhidrustApp {
}
fn apply_saved_layout(&mut self, layout: &layouts::SavedLayout) {
- // Apply pane visibility.
- let ids: BTreeMap<&'static str, PaneKind> = PaneKind::ALL
+ // Apply pane visibility.
+ let ids: BTreeMap<&'static str, PaneKind> = PaneKind::ALL
.iter()
.map(|k| (k.egui_id(), *k))
.collect();
@@ -4284,26 +4310,18 @@ impl GhidrustApp {
self.pane_open.insert(*k, *open);
}
}
- let dbg_ids: BTreeMap<&'static str, DebuggerPane> = DebuggerPane::ALL
- .iter()
- .map(|p| (p.egui_id(), *p))
- .collect();
- for (id, open) in &layout.open_panes {
- if let Some(p) = dbg_ids.get(id.as_str()) {
- self.debugger_open.insert(*p, *open);
- }
- }
- // Docks.
- if let Some(v) = layout.docks.get("project_tree") {
+ debugger::apply_layout_flags(&mut self.debugger, &layout.open_panes);
+ // Docks.
+ if let Some(v) = layout.docks.get("project_tree") {
self.show_project_tree = *v;
}
- if let Some(v) = layout.docks.get("program_tree") {
+ if let Some(v) = layout.docks.get("program_tree") {
self.show_program_tree = *v;
}
- if let Some(v) = layout.docks.get("symbol_tree") {
+ if let Some(v) = layout.docks.get("symbol_tree") {
self.show_symbol_tree = *v;
}
- if let Some(v) = layout.docks.get("console") {
+ if let Some(v) = layout.docks.get("console") {
self.show_console = *v;
}
if let Some(value) = &layout.dock_tree {
@@ -4316,13 +4334,13 @@ impl GhidrustApp {
}
self.sync_center_from_dock();
self.theme = match layout.theme.as_str() {
- "light" => ThemeMode::Light,
+ "light" => ThemeMode::Light,
_ => ThemeMode::Dark,
};
self.current_layout_name = layout.name.clone();
}
- /// Save the current layout under `name`.
+ /// Save the current layout under `name`.
pub fn save_layout_named(&mut self, name: impl Into<String>) -> std::io::Result<PathBuf> {
let name = name.into();
let l = self.snapshot_current_layout(name.clone());
@@ -4332,40 +4350,40 @@ impl GhidrustApp {
Ok(p)
}
- /// Restore a saved layout by name.
+ /// Restore a saved layout by name.
pub fn restore_layout_named(&mut self, name: &str) -> std::io::Result<()> {
let l = layouts::load_layout(name)?;
self.apply_saved_layout(&l);
Ok(())
}
- /// 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).
+ // Rename dialog .
if self.show_rename_dialog {
let mut close = false;
let mut confirm = false;
let va = self.rename_dialog_target_va;
- egui::Window::new("Rename")
- .id(egui::Id::new("dialog_rename"))
+ egui::Window::new("Rename")
+ .id(egui::Id::new("dialog_rename"))
.collapsible(false)
.resizable(false)
.anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0])
.show(ctx, |ui| {
if let Some(va) = va {
- ui.label(format!("Address: {va:#x}"));
+ ui.label(format!("Address: {va:#x}"));
}
- ui.label(format!("Old name: {}", self.rename_dialog_old_name));
- ui.label("New name:");
+ ui.label(format!("Old name: {}", self.rename_dialog_old_name));
+ ui.label("New name:");
let resp = ui.text_edit_singleline(&mut self.rename_dialog_new_name);
if resp.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)) {
confirm = true;
}
ui.horizontal(|ui| {
- if ui.button("Cancel").clicked() {
+ if ui.button("Cancel").clicked() {
close = true;
}
- if ui.button("Rename").clicked() {
+ if ui.button("Rename").clicked() {
confirm = true;
}
});
@@ -4373,7 +4391,7 @@ impl GhidrustApp {
if confirm {
if let Some(va) = va {
if let Err(e) = self.rename_at(va, self.rename_dialog_new_name.clone()) {
- self.status = format!("error: {e}");
+ self.status = format!("error: {e}");
self.log_error(self.status.clone());
} else {
close = true;
@@ -4385,34 +4403,34 @@ impl GhidrustApp {
}
}
- // Retype dialog (Ghidra `Ctrl+L` / Retype Variable).
+ // Retype dialog .
if self.show_retype_dialog {
let mut close = false;
let mut confirm = false;
let va = self.retype_dialog_target_va;
- egui::Window::new("Retype")
- .id(egui::Id::new("dialog_retype"))
+ egui::Window::new("Retype")
+ .id(egui::Id::new("dialog_retype"))
.collapsible(false)
.resizable(false)
.anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0])
.show(ctx, |ui| {
if let Some(va) = va {
- ui.label(format!("Address: {va:#x}"));
+ ui.label(format!("Address: {va:#x}"));
}
- ui.label("Type (Ghidra-C syntax, e.g. `int32_t *` or `Widget`):");
+ ui.label("Type .:");
let resp = ui.text_edit_singleline(&mut self.retype_dialog_type);
if resp.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)) {
confirm = true;
}
ui.horizontal(|ui| {
- if ui.button("Cancel").clicked() {
+ if ui.button("Cancel").clicked() {
close = true;
}
- if ui.button("Clear").clicked() {
+ if ui.button("Clear").clicked() {
self.retype_dialog_type.clear();
confirm = true;
}
- if ui.button("Apply").clicked() {
+ if ui.button("Apply").clicked() {
confirm = true;
}
});
@@ -4420,7 +4438,7 @@ impl GhidrustApp {
if confirm {
if let Some(va) = va {
if let Err(e) = self.retype_at(va, self.retype_dialog_type.clone()) {
- self.status = format!("error: {e}");
+ self.status = format!("error: {e}");
self.log_error(self.status.clone());
} else {
close = true;
@@ -4432,36 +4450,36 @@ impl GhidrustApp {
}
}
- // Comment dialog (Set EOL/Pre/Post/Plate/Repeatable).
+ // Comment dialog (Set EOL/Pre/Post/Plate/Repeatable).
if self.show_comment_dialog {
let mut close = false;
let mut confirm = false;
let va = self.comment_dialog_target_va;
- egui::Window::new("Set Comment")
- .id(egui::Id::new("dialog_comment"))
+ egui::Window::new("Set Comment")
+ .id(egui::Id::new("dialog_comment"))
.collapsible(false)
.resizable(true)
.default_width(420.0)
.anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0])
.show(ctx, |ui| {
if let Some(va) = va {
- ui.label(format!("Address: {va:#x}"));
+ ui.label(format!("Address: {va:#x}"));
}
ui.horizontal(|ui| {
- ui.label("Kind:");
- egui::ComboBox::from_id_salt("comment_kind")
+ ui.label("Kind:");
+ egui::ComboBox::from_id_salt("comment_kind")
.selected_text(self.comment_dialog_kind.label())
.show_ui(ui, |ui| {
for k in CommentKind::ALL {
if ui
.selectable_value(
&mut self.comment_dialog_kind,
- *k,
+ *k,
k.label(),
)
.clicked()
{
- // Load existing text for that kind.
+ // Load existing text for that kind.
if let (Some(va), Some(prog)) =
(va, self.program.as_ref())
{
@@ -4475,21 +4493,21 @@ impl GhidrustApp {
}
});
});
- ui.label("Text:");
+ ui.label("Text:");
ui.add(
egui::TextEdit::multiline(&mut self.comment_dialog_text)
.desired_rows(4)
.desired_width(f32::INFINITY),
);
ui.horizontal(|ui| {
- if ui.button("Cancel").clicked() {
+ if ui.button("Cancel").clicked() {
close = true;
}
- if ui.button("Clear").clicked() {
+ if ui.button("Clear").clicked() {
self.comment_dialog_text.clear();
confirm = true;
}
- if ui.button("Save").clicked() {
+ if ui.button("Save").clicked() {
confirm = true;
}
});
@@ -4501,7 +4519,7 @@ impl GhidrustApp {
self.comment_dialog_kind,
self.comment_dialog_text.clone(),
) {
- self.status = format!("error: {e}");
+ self.status = format!("error: {e}");
self.log_error(self.status.clone());
} else {
close = true;
@@ -4513,22 +4531,22 @@ impl GhidrustApp {
}
}
- // Function-signature dialog (Edit Function Signature).
+ // Function-signature dialog (Edit Function Signature).
if self.show_fn_signature_dialog {
let mut close = false;
let mut confirm = false;
let entry = self.fn_signature_dialog_entry;
- egui::Window::new("Edit Function Signature")
- .id(egui::Id::new("dialog_fn_sig"))
+ egui::Window::new("Edit Function Signature")
+ .id(egui::Id::new("dialog_fn_sig"))
.collapsible(false)
.resizable(true)
.default_width(520.0)
.anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0])
.show(ctx, |ui| {
if let Some(entry) = entry {
- ui.label(format!("Function entry: {entry:#x}"));
+ ui.label(format!("Function entry: {entry:#x}"));
}
- ui.label("Signature:");
+ ui.label("Signature:");
ui.add(
egui::TextEdit::multiline(&mut self.fn_signature_dialog_text)
.desired_rows(3)
@@ -4536,10 +4554,10 @@ impl GhidrustApp {
.font(egui::FontId::monospace(13.0)),
);
ui.horizontal(|ui| {
- if ui.button("Cancel").clicked() {
+ if ui.button("Cancel").clicked() {
close = true;
}
- if ui.button("Save").clicked() {
+ if ui.button("Save").clicked() {
confirm = true;
}
});
@@ -4549,7 +4567,7 @@ impl GhidrustApp {
if let Err(e) = self
.set_function_signature(entry, self.fn_signature_dialog_text.clone())
{
- self.status = format!("error: {e}");
+ self.status = format!("error: {e}");
self.log_error(self.status.clone());
} else {
close = true;
@@ -4561,21 +4579,21 @@ impl GhidrustApp {
}
}
- // New Type dialog (DTM → New → Structure/Union/Enum/Typedef/FunctionDef).
+ // New Type dialog (DTM → New → Structure/Union/Enum/Typedef/FunctionDef).
if self.show_new_type_dialog {
let mut close = false;
let mut confirm = false;
let kind = self.new_type_dialog_kind;
- egui::Window::new(format!("New {}", kind.label()))
- .id(egui::Id::new("dialog_new_type"))
+ egui::Window::new(format!("New {}", kind.label()))
+ .id(egui::Id::new("dialog_new_type"))
.collapsible(false)
.resizable(true)
.default_width(560.0)
.anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0])
.show(ctx, |ui| {
- ui.label("Name:");
+ ui.label("Name:");
ui.text_edit_singleline(&mut self.new_type_dialog_name);
- ui.label(format!("{} body:", kind.label()));
+ ui.label(format!("{} body:", kind.label()));
ui.add(
egui::TextEdit::multiline(&mut self.new_type_dialog_body)
.desired_rows(8)
@@ -4583,19 +4601,19 @@ impl GhidrustApp {
.font(egui::FontId::monospace(13.0)),
);
ui.horizontal(|ui| {
- if ui.button("Cancel").clicked() {
+ if ui.button("Cancel").clicked() {
close = true;
}
- if ui.button("Create").clicked() {
+ if ui.button("Create").clicked() {
confirm = true;
}
});
});
if confirm {
let name = self.new_type_dialog_name.clone();
- let body = format!("{}\n{}", kind.label(), self.new_type_dialog_body);
+ let body = format!("{}\n{}", kind.label(), self.new_type_dialog_body);
if let Err(e) = self.define_user_type(name, body) {
- self.status = format!("error: {e}");
+ self.status = format!("error: {e}");
self.log_error(self.status.clone());
} else {
close = true;
@@ -4606,21 +4624,21 @@ impl GhidrustApp {
}
}
- // Edit Type dialog (DTM → Edit on an existing user type).
+ // Edit Type dialog (DTM → Edit on an existing user type).
if self.show_edit_type_dialog {
let mut close = false;
let mut confirm = false;
let orig = self.edit_type_dialog_orig_name.clone();
- egui::Window::new(format!("Edit type · {orig}"))
- .id(egui::Id::new("dialog_edit_type"))
+ egui::Window::new(format!("Edit type · {orig}"))
+ .id(egui::Id::new("dialog_edit_type"))
.collapsible(false)
.resizable(true)
.default_width(560.0)
.anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0])
.show(ctx, |ui| {
- ui.label("Name:");
+ ui.label("Name:");
ui.text_edit_singleline(&mut self.edit_type_dialog_name);
- ui.label("Body (Ghidra-style: first line = kind label, then fields):");
+ ui.label("Body .:");
ui.add(
egui::TextEdit::multiline(&mut self.edit_type_dialog_body)
.desired_rows(10)
@@ -4628,18 +4646,18 @@ impl GhidrustApp {
.font(egui::FontId::monospace(13.0)),
);
ui.horizontal(|ui| {
- if ui.button("Cancel").clicked() {
+ if ui.button("Cancel").clicked() {
close = true;
}
- if ui.button("Delete").clicked() {
+ if ui.button("Delete").clicked() {
if let Err(e) = self.delete_user_type(&orig) {
- self.status = format!("error: {e}");
+ self.status = format!("error: {e}");
self.log_error(self.status.clone());
} else {
close = true;
}
}
- if ui.button("Save").clicked() {
+ if ui.button("Save").clicked() {
confirm = true;
}
});
@@ -4648,7 +4666,7 @@ impl GhidrustApp {
let new_name = self.edit_type_dialog_name.clone();
let body = self.edit_type_dialog_body.clone();
if let Err(e) = self.edit_user_type(&orig, new_name, body) {
- self.status = format!("error: {e}");
+ self.status = format!("error: {e}");
self.log_error(self.status.clone());
} else {
close = true;
@@ -4659,29 +4677,29 @@ impl GhidrustApp {
}
}
- // Data Type Chooser dialog (Ghidra `T` shortcut over Listing).
+ // Data Type Chooser dialog .
if self.show_type_chooser_dialog {
let mut close = false;
let mut apply: Option<String> = None;
let va = self.type_chooser_target_va;
- egui::Window::new("Choose Data Type")
- .id(egui::Id::new("dialog_type_chooser"))
+ egui::Window::new("Choose Data Type")
+ .id(egui::Id::new("dialog_type_chooser"))
.collapsible(false)
.resizable(true)
.default_width(420.0)
.anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0])
.show(ctx, |ui| {
if let Some(va) = va {
- ui.small(format!("Apply target: {va:#x}"));
+ ui.small(format!("Apply target: {va:#x}"));
} else {
- ui.weak("No cursor VA — click a Listing line first.");
+ ui.weak("No cursor VA — click a Listing line first.");
}
ui.horizontal(|ui| {
- ui.label("Filter:");
+ ui.label("Filter:");
ui.add(
egui::TextEdit::singleline(&mut self.type_chooser_filter)
.desired_width(240.0)
- .hint_text("Type name…"),
+ .hint_text("Type name…"),
);
});
let q = self.type_chooser_filter.to_ascii_lowercase();
@@ -4691,7 +4709,7 @@ impl GhidrustApp {
.map(|p| p.edits.user_types.keys().cloned().collect())
.unwrap_or_default();
egui::ScrollArea::vertical()
- .id_salt("type_chooser_scroll")
+ .id_salt("type_chooser_scroll")
.max_height(280.0)
.show(ui, |ui| {
for name in BUILTIN_TYPES {
@@ -4703,7 +4721,7 @@ impl GhidrustApp {
ui.with_layout(
egui::Layout::right_to_left(egui::Align::Center),
|ui| {
- if ui.small_button("Apply").clicked() {
+ if ui.small_button("Apply").clicked() {
apply = Some((*name).to_string());
}
},
@@ -4712,7 +4730,7 @@ impl GhidrustApp {
}
if !user_types.is_empty() {
ui.separator();
- ui.small("Program archive:");
+ ui.small("Program archive:");
for name in &user_types {
if !q.is_empty() && !name.to_ascii_lowercase().contains(&q) {
continue;
@@ -4722,7 +4740,7 @@ impl GhidrustApp {
ui.with_layout(
egui::Layout::right_to_left(egui::Align::Center),
|ui| {
- if ui.small_button("Apply").clicked() {
+ if ui.small_button("Apply").clicked() {
apply = Some(name.clone());
}
},
@@ -4732,7 +4750,7 @@ impl GhidrustApp {
}
});
ui.horizontal(|ui| {
- if ui.button("Cancel").clicked() {
+ if ui.button("Cancel").clicked() {
close = true;
}
});
@@ -4740,13 +4758,13 @@ impl GhidrustApp {
if let Some(name) = apply {
if let Some(va) = va {
if let Err(e) = self.apply_type_at(va, name) {
- self.status = format!("error: {e}");
+ self.status = format!("error: {e}");
self.log_error(self.status.clone());
} else {
close = true;
}
} else {
- self.status = "No cursor VA — click a Listing line first".into();
+ self.status = "No cursor VA — click a Listing line first".into();
self.log_warn(self.status.clone());
}
}
@@ -4756,25 +4774,25 @@ impl GhidrustApp {
}
}
- /// 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.heading("Data Type Manager");
ui.small(
egui::RichText::new(
- "Ghidra DataTypeManagerPlugin · Built-In archive + Program archive (user types)",
+ "DataTypeManagerPlugin · Built-In archive + Program archive (user types)",
)
.weak(),
);
ui.separator();
ui.horizontal(|ui| {
- ui.label("Filter:");
+ ui.label("Filter:");
ui.add(
egui::TextEdit::singleline(&mut self.dtm_filter)
.desired_width(240.0)
- .hint_text("Type name…"),
+ .hint_text("Type name…"),
);
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
- ui.menu_button("New…", |ui| {
+ ui.menu_button("New…", |ui| {
for k in NewTypeKind::ALL {
if ui.button(k.label()).clicked() {
self.open_new_type_dialog(*k);
@@ -4785,8 +4803,8 @@ impl GhidrustApp {
});
});
let q = self.dtm_filter.to_ascii_lowercase();
- // Per-frame action queue so we can mutate `self` outside the borrowed
- // scroll-area closure below without fighting the borrow checker.
+ // Per-frame action queue so we can mutate `self` outside the borrowed
+ // scroll-area closure below without fighting the borrow checker.
let mut pending_apply: Option<String> = None;
let mut pending_typedef_on: Option<String> = None;
let mut pending_pointer_to: Option<String> = None;
@@ -4794,13 +4812,13 @@ impl GhidrustApp {
let mut pending_rename: Option<String> = None;
let mut pending_delete: Option<String> = None;
egui::ScrollArea::vertical()
- .id_salt("dtm_scroll")
+ .id_salt("dtm_scroll")
.auto_shrink([false, false])
.show(ui, |ui| {
- // Built-In archive (Ghidra style). Read-only leaves — Ghidra's
- // Built-In archive is not editable; right-click gives us
- // Apply / +Typedef / +Pointer / Copy-to-program.
- egui::CollapsingHeader::new("Built-In")
+ // Built-In archive. Read-only leaves — 's
+ // Built-In archive is not editable; right-click gives us
+ // Apply / +Typedef / +Pointer / Copy-to-program.
+ egui::CollapsingHeader::new("Built-In")
.default_open(true)
.show(ui, |ui| {
for name in BUILTIN_TYPES {
@@ -4813,21 +4831,21 @@ impl GhidrustApp {
ui.with_layout(
egui::Layout::right_to_left(egui::Align::Center),
|ui| {
- if ui.small_button("+Ptr").on_hover_text(
- "New Pointer to X (Ghidra `New Pointer to <T>`)",
+ if ui.small_button("+Ptr").on_hover_text(
+ "New Pointer to X .",
).clicked() {
pending_pointer_to = Some((*name).to_string());
}
- if ui.small_button("+Typedef").on_hover_text(
- "New Typedef on X (Ghidra `New Typedef on <T>`)",
+ if ui.small_button("+Typedef").on_hover_text(
+ "New Typedef on X .",
).clicked() {
pending_typedef_on = Some((*name).to_string());
}
if let Some(va) = self.listing_focus_va {
if ui
- .small_button("Apply @ cursor")
+ .small_button("Apply @ cursor")
.on_hover_text(format!(
- "Apply {name} at {va:#x}"
+ "Apply {name} at {va:#x}"
))
.clicked()
{
@@ -4838,32 +4856,32 @@ impl GhidrustApp {
);
})
.response;
- // Ghidra-style right-click submenu (Rename/Delete/
- // Cut/Copy/Paste are N/A on Built-In, so we only
- // offer the applicable actions).
+ // right-click submenu (Rename/Delete
+ // Cut/Copy/Paste are N/A on Built-In, so we only
+ // offer the applicable actions).
row_resp.context_menu(|ui| {
ui.label(egui::RichText::new(*name).monospace());
ui.separator();
let has_va = self.listing_focus_va.is_some();
if ui
- .add_enabled(has_va, egui::Button::new("Apply @ cursor"))
+ .add_enabled(has_va, egui::Button::new("Apply @ cursor"))
.clicked()
{
pending_apply = Some((*name).to_string());
ui.close_menu();
}
- if ui.button("New Typedef on X").clicked() {
+ if ui.button("New Typedef on X").clicked() {
pending_typedef_on = Some((*name).to_string());
ui.close_menu();
}
- if ui.button("New Pointer to X").clicked() {
+ if ui.button("New Pointer to X").clicked() {
pending_pointer_to = Some((*name).to_string());
ui.close_menu();
}
});
}
});
- // Program archive: user-defined types + analyzer-recovered RTTI classes.
+ // Program archive: user-defined types + analyzer-recovered RTTI classes.
let (user_types, rtti_classes) = self
.program
.as_ref()
@@ -4879,7 +4897,7 @@ impl GhidrustApp {
})
.unwrap_or_default();
let title = format!(
- "Program ({user} user + {rtti} RTTI)",
+ "Program ({user} user + {rtti} RTTI)",
user = user_types.len(),
rtti = rtti_classes.len()
);
@@ -4888,7 +4906,7 @@ impl GhidrustApp {
.show(ui, |ui| {
if user_types.is_empty() && rtti_classes.is_empty() {
ui.weak(
- "Empty — use New… to define a Structure/Union/Enum/Typedef/FunctionDef.",
+ "Empty — use New… to define a Structure/Union/Enum/Typedef/FunctionDef.",
);
}
for (name, body) in &user_types {
@@ -4910,20 +4928,20 @@ impl GhidrustApp {
ui.with_layout(
egui::Layout::right_to_left(egui::Align::Center),
|ui| {
- if ui.small_button("Delete").clicked() {
+ if ui.small_button("Delete").clicked() {
pending_delete = Some(name.clone());
}
- if ui.small_button("Rename…").clicked() {
+ if ui.small_button("Rename…").clicked() {
pending_rename = Some(name.clone());
}
- if ui.small_button("Edit…").clicked() {
+ if ui.small_button("Edit…").clicked() {
pending_edit = Some(name.clone());
}
if let Some(va) = self.listing_focus_va {
if ui
- .small_button("Apply @ cursor")
+ .small_button("Apply @ cursor")
.on_hover_text(format!(
- "Apply {name} at {va:#x}"
+ "Apply {name} at {va:#x}"
))
.clicked()
{
@@ -4937,32 +4955,32 @@ impl GhidrustApp {
row_resp.context_menu(|ui| {
ui.label(egui::RichText::new(name).monospace());
ui.separator();
- if ui.button("Edit…").clicked() {
+ if ui.button("Edit…").clicked() {
pending_edit = Some(name.clone());
ui.close_menu();
}
- if ui.button("Rename…").clicked() {
+ if ui.button("Rename…").clicked() {
pending_rename = Some(name.clone());
ui.close_menu();
}
- if ui.button("Delete").clicked() {
+ if ui.button("Delete").clicked() {
pending_delete = Some(name.clone());
ui.close_menu();
}
ui.separator();
let has_va = self.listing_focus_va.is_some();
if ui
- .add_enabled(has_va, egui::Button::new("Apply @ cursor"))
+ .add_enabled(has_va, egui::Button::new("Apply @ cursor"))
.clicked()
{
pending_apply = Some(name.clone());
ui.close_menu();
}
- if ui.button("New Typedef on X").clicked() {
+ if ui.button("New Typedef on X").clicked() {
pending_typedef_on = Some(name.clone());
ui.close_menu();
}
- if ui.button("New Pointer to X").clicked() {
+ if ui.button("New Pointer to X").clicked() {
pending_pointer_to = Some(name.clone());
ui.close_menu();
}
@@ -4971,7 +4989,7 @@ impl GhidrustApp {
if !rtti_classes.is_empty() {
ui.separator();
ui.small(
- egui::RichText::new("RTTI classes (from analyzer)").weak(),
+ egui::RichText::new("RTTI classes (from analyzer)").weak(),
);
for name in &rtti_classes {
if !q.is_empty() && !name.to_ascii_lowercase().contains(&q) {
@@ -4983,14 +5001,14 @@ impl GhidrustApp {
ui.with_layout(
egui::Layout::right_to_left(egui::Align::Center),
|ui| {
- if ui.small_button("+Ptr").clicked() {
+ if ui.small_button("+Ptr").clicked() {
pending_pointer_to = Some(name.clone());
}
- if ui.small_button("+Typedef").clicked() {
+ if ui.small_button("+Typedef").clicked() {
pending_typedef_on = Some(name.clone());
}
if self.listing_focus_va.is_some()
- && ui.small_button("Apply @ cursor").clicked()
+ && ui.small_button("Apply @ cursor").clicked()
{
pending_apply = Some(name.clone());
}
@@ -5003,17 +5021,17 @@ impl GhidrustApp {
ui.separator();
let has_va = self.listing_focus_va.is_some();
if ui
- .add_enabled(has_va, egui::Button::new("Apply @ cursor"))
+ .add_enabled(has_va, egui::Button::new("Apply @ cursor"))
.clicked()
{
pending_apply = Some(name.clone());
ui.close_menu();
}
- if ui.button("New Typedef on X").clicked() {
+ if ui.button("New Typedef on X").clicked() {
pending_typedef_on = Some(name.clone());
ui.close_menu();
}
- if ui.button("New Pointer to X").clicked() {
+ if ui.button("New Pointer to X").clicked() {
pending_pointer_to = Some(name.clone());
ui.close_menu();
}
@@ -5025,18 +5043,18 @@ impl GhidrustApp {
ui.separator();
ui.small(
egui::RichText::new(
- "Right-click a type for Edit / Rename / Delete / Apply @ cursor / \
+ "Right-click a type for Edit / Rename / Delete / Apply @ cursor / \
New Typedef on X / New Pointer to X. Docking-framework drag-and-drop \
- not yet wired.",
+ not yet wired.",
)
.weak()
.italics(),
);
- // Flush queued actions after the scroll-area borrow drops.
+ // Flush queued actions after the scroll-area borrow drops.
if let Some(name) = pending_apply {
if let Some(va) = self.listing_focus_va {
if let Err(e) = self.apply_type_at(va, name) {
- self.status = format!("error: {e}");
+ self.status = format!("error: {e}");
self.log_error(self.status.clone());
}
}
@@ -5044,11 +5062,11 @@ impl GhidrustApp {
if let Some(name) = pending_typedef_on {
match self.new_typedef_on(&name) {
Ok(new_name) => {
- self.status = format!("Created typedef {new_name} on {name}");
+ self.status = format!("Created typedef {new_name} on {name}");
self.log(self.status.clone());
}
Err(e) => {
- self.status = format!("error: {e}");
+ self.status = format!("error: {e}");
self.log_error(self.status.clone());
}
}
@@ -5056,11 +5074,11 @@ impl GhidrustApp {
if let Some(name) = pending_pointer_to {
match self.new_pointer_to(&name) {
Ok(new_name) => {
- self.status = format!("Created pointer type {new_name}");
+ self.status = format!("Created pointer type {new_name}");
self.log(self.status.clone());
}
Err(e) => {
- self.status = format!("error: {e}");
+ self.status = format!("error: {e}");
self.log_error(self.status.clone());
}
}
@@ -5069,42 +5087,51 @@ impl GhidrustApp {
self.open_edit_type_dialog(&name);
}
if let Some(name) = pending_rename {
- // Reuse the standard Rename dialog but retarget its callback path:
- // renames of user types go through the new-type dialog with the
- // current body preloaded (so Save = rename + optional body edit).
+ // Reuse the standard Rename dialog but retarget its callback path:
+ // renames of user types go through the new-type dialog with the
+ // current body preloaded (so Save = rename + optional body edit).
self.open_edit_type_dialog(&name);
}
if let Some(name) = pending_delete {
if let Err(e) = self.delete_user_type(&name) {
- self.status = format!("error: {e}");
+ self.status = format!("error: {e}");
self.log_error(self.status.clone());
}
}
}
- /// 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.
+ ui.heading("Listing");
+ let mut open_opts = self.show_decode_options_dialog;
+ match ui_toolbar(ui, &mut self.decode_opts, &mut open_opts) {
+ ToolbarAction::Apply => self.apply_decode_opts(),
+ ToolbarAction::OpenOptions => open_opts = true,
+ ToolbarAction::None => {}
+ }
+ self.show_decode_options_dialog = open_opts;
+ ui_search_bar(ui, &mut self.listing_search);
+ self.listing_search.arch = self.listing_arch();
+ // Status strip.
ui.horizontal(|ui| {
if !self.listing_selection.is_empty() {
ui.small(format!(
- "Sel {}–{}",
+ "Sel {}–{}",
self.listing_selection.start.unwrap_or(0),
self.listing_selection.end.unwrap_or(0)
));
}
if let Some(va) = self.listing_focus_va {
- ui.small(format!("Cursor {va:#x}"));
+ ui.small(format!("Cursor {va:#x}"));
}
if let Some(f) = self.listing_view_filter.as_ref() {
- let names = f.iter().cloned().collect::<Vec<_>>().join(", ");
+ let names = f.iter().cloned().collect::<Vec<_>>().join(", ");
ui.small(egui::RichText::new(format!(
- "View filter · {} fragment(s): {names}",
+ "View filter · {} fragment(s): {names}",
f.len()
)).weak());
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
- if ui.small_button("Show All").clicked() {
+ if ui.small_button("Show All").clicked() {
self.listing_view_filter = None;
}
});
@@ -5112,7 +5139,7 @@ impl GhidrustApp {
});
ui.separator();
if self.listing.is_empty() {
- ui.weak("No listing — double-click a project file to open.");
+ ui.weak("No listing — double-click a project file to open.");
return;
}
let focus = self.listing_focus_va;
@@ -5120,13 +5147,16 @@ impl GhidrustApp {
let t = m3_tokens(self.theme);
let sel_bg = Color32::from_rgb(t.primary[0], t.primary[1], t.primary[2])
.gamma_multiply(0.35);
- // Snapshot for the closure: (idx, va, bytes_hex, mnem, ops, is_ret, is_uncond, is_cond, is_call, applied_type, comment_eol).
+ // Snapshot for the closure: (idx, va, bytes_hex, mnem, ops, is_ret, is_uncond, is_cond, is_call, applied_type, comment_eol).
let rows: Vec<ListingRow> = {
let filter = self.listing_view_filter.clone();
let prog_ref = self.program.as_ref();
+ let arch = self.listing_arch();
+ let search = &self.listing_search;
self.listing
.iter()
.enumerate()
+ .filter(|(_, insn)| listing_matches(insn, search))
.filter(|(_, insn)| match &filter {
None => true,
Some(set) => {
@@ -5145,88 +5175,7 @@ impl GhidrustApp {
}
}
})
- .map(|(i, insn)| {
- let bytes_hex: String = insn
- .bytes
- .iter()
- .take(6)
- .map(|b| format!("{b:02x}"))
- .collect::<Vec<_>>()
- .join(" ");
- let (
- applied_type,
- comment_eol,
- comment_plate,
- comment_pre,
- comment_post,
- comment_repeat,
- ) = prog_ref
- .map(|p| {
- (
- p.edits.applied_type_at(insn.address).map(String::from),
- p.edits
- .comment_at(insn.address, CommentKind::Eol)
- .map(String::from),
- p.edits
- .comment_at(insn.address, CommentKind::Plate)
- .map(String::from),
- p.edits
- .comment_at(insn.address, CommentKind::Pre)
- .map(String::from),
- p.edits
- .comment_at(insn.address, CommentKind::Post)
- .map(String::from),
- p.edits
- .comment_at(insn.address, CommentKind::Repeatable)
- .map(String::from),
- )
- })
- .unwrap_or((None, None, None, None, None, None));
- let mnem = insn.mnemonic.clone();
- let is_ret = matches!(mnem.as_str(), "ret" | "retn" | "retf");
- let is_uncond = mnem == "jmp";
- let is_cond = matches!(
- mnem.as_str(),
- "je" | "jne"
- | "jz"
- | "jnz"
- | "ja"
- | "jae"
- | "jb"
- | "jbe"
- | "jg"
- | "jge"
- | "jl"
- | "jle"
- | "jo"
- | "jno"
- | "js"
- | "jns"
- | "jp"
- | "jnp"
- | "jcxz"
- | "jecxz"
- | "jrcxz"
- );
- let is_call = mnem == "call";
- ListingRow {
- idx: i,
- va: insn.address,
- bytes_hex,
- mnem,
- ops: insn.operands.clone(),
- is_ret,
- is_uncond,
- is_cond,
- is_call,
- applied_type,
- comment_eol,
- comment_plate,
- comment_pre,
- comment_post,
- comment_repeat,
- }
- })
+ .map(|(i, insn)| ListingRow::from_insn(i, insn, prog_ref, arch))
.collect()
};
let bookmarks_by_va: BTreeMap<u64, BookmarkKind> = self
@@ -5235,8 +5184,8 @@ impl GhidrustApp {
.map(|b| (b.va, b.kind))
.collect();
let mut click_i: Option<(usize, u64)> = None;
- // Right-click actions surfaced via a context menu attached to the
- // Address column. Executed after the scroll-area borrow drops.
+ // Right-click actions surfaced via a context menu attached to the
+ // Address column. Executed after the scroll-area borrow drops.
#[derive(Debug, Clone, Copy)]
enum RowAction {
OpenComment(CommentKind),
@@ -5250,56 +5199,56 @@ impl GhidrustApp {
}
let mut pending_action: Option<(u64, RowAction)> = None;
egui::ScrollArea::both()
- .id_salt("listing_scroll")
+ .id_salt("listing_scroll")
.auto_shrink([false, false])
.show(ui, |ui| {
- egui::Grid::new("listing_grid")
+ egui::Grid::new("listing_grid")
.num_columns(7)
.spacing([6.0, 2.0])
.striped(false)
.show(ui, |ui| {
- ui.strong(egui::RichText::new("").monospace());
- ui.strong("Address");
- ui.strong("Bytes");
- ui.strong("Mnemonic");
- ui.strong("Operands");
- ui.strong("Flow");
- ui.strong("Comment");
+ ui.strong(egui::RichText::new("").monospace());
+ ui.strong("Address");
+ ui.strong("Bytes");
+ ui.strong("Mnemonic");
+ ui.strong("Operands");
+ ui.strong("Flow");
+ ui.strong("Comment");
ui.end_row();
for row in &rows {
let focused = focus == Some(row.va);
let selected = sel.contains(row.idx);
- // Pre-comment row (Ghidra `Pre` comment appears
- // as its own line above the instruction).
+ // Pre-comment row (`Pre` comment appears
+ // as its own line above the instruction).
if let Some(pre) = &row.comment_pre {
- ui.label(egui::RichText::new(" ").monospace());
+ ui.label(egui::RichText::new(" ").monospace());
ui.label(
- egui::RichText::new(format!("; {pre}"))
+ egui::RichText::new(format!("; {pre}"))
.italics()
.color(Color32::from_rgb(0x64, 0xB5, 0xF6)),
);
for _ in 0..5 {
- ui.label("");
+ ui.label("");
}
ui.end_row();
}
- // Margin column: bookmark tint + flow-glyph.
+ // Margin column: bookmark tint + flow-glyph.
let margin_text = if let Some(k) = bookmarks_by_va.get(&row.va) {
- egui::RichText::new("* ")
+ egui::RichText::new("* ")
.color(k.color())
.monospace()
.strong()
} else if focused {
- egui::RichText::new("> ")
+ egui::RichText::new("> ")
.color(Color32::from_rgb(0xFF, 0xD5, 0x4F))
.monospace()
.strong()
} else {
- egui::RichText::new(" ").monospace()
+ egui::RichText::new(" ").monospace()
};
ui.label(margin_text);
- // Address column (clickable).
- let addr_rich = egui::RichText::new(format!("{:08x}", row.va))
+ // Address column (clickable).
+ let addr_rich = egui::RichText::new(format!("{:08x}", row.va))
.monospace()
.color(if focused {
Color32::from_rgb(0xFF, 0xD5, 0x4F)
@@ -5318,16 +5267,16 @@ impl GhidrustApp {
if addr.clicked() {
click_i = Some((row.idx, row.va));
}
- // Ghidra Listing right-click submenu.
+ // Listing right-click submenu.
let va = row.va;
addr.context_menu(|ui| {
ui.label(
- egui::RichText::new(format!("{va:#x}"))
+ egui::RichText::new(format!("{va:#x}"))
.monospace()
.strong(),
);
ui.separator();
- ui.menu_button("Set Comment", |ui| {
+ ui.menu_button("Set Comment", |ui| {
for k in CommentKind::ALL {
if ui.button(k.label()).clicked() {
pending_action = Some((
@@ -5339,39 +5288,39 @@ impl GhidrustApp {
}
});
ui.separator();
- if ui.button("Rename Symbol… (L)").clicked() {
+ if ui.button("Rename Symbol… (L)").clicked() {
pending_action = Some((va, RowAction::OpenRename));
ui.close_menu();
}
- if ui.button("Retype Variable… (Ctrl+L)").clicked() {
+ if ui.button("Retype Variable… (Ctrl+L)").clicked() {
pending_action = Some((va, RowAction::OpenRetype));
ui.close_menu();
}
- if ui.button("Choose Data Type… (T)").clicked() {
+ if ui.button("Choose Data Type… (T)").clicked() {
pending_action = Some((va, RowAction::OpenChooser));
ui.close_menu();
}
- if ui.button("Edit Function Signature… (Alt+Enter)").clicked() {
+ if ui.button("Edit Function Signature… (Alt+Enter)").clicked() {
pending_action = Some((va, RowAction::OpenSignature));
ui.close_menu();
}
ui.separator();
- if ui.button("Set Equate…").on_hover_text("Bind a name to the first operand scalar").clicked() {
+ if ui.button("Set Equate…").on_hover_text("Bind a name to the first operand scalar").clicked() {
pending_action = Some((va, RowAction::OpenEquate));
ui.close_menu();
}
- if ui.button("Show References To…").on_hover_text("Open Symbol References for this VA").clicked() {
+ if ui.button("Show References To…").on_hover_text("Open Symbol References for this VA").clicked() {
pending_action = Some((va, RowAction::ShowRefsTo));
ui.close_menu();
}
- if ui.button("Show Bytes Here").on_hover_text("Open Byte Viewer at this VA").clicked() {
+ if ui.button("Show Bytes Here").on_hover_text("Open Byte Viewer at this VA").clicked() {
pending_action = Some((va, RowAction::OpenBytesHere));
ui.close_menu();
}
});
- // Bytes column.
+ // Bytes column.
ui.monospace(&row.bytes_hex);
- // Mnemonic column, coloured by kind.
+ // Mnemonic column, coloured by kind.
let mnem_color = if row.is_ret {
Color32::from_rgb(0xEF, 0x53, 0x50)
} else if row.is_uncond {
@@ -5383,8 +5332,21 @@ impl GhidrustApp {
} else {
ui.visuals().text_color()
};
- ui.label(egui::RichText::new(&row.mnem).monospace().color(mnem_color));
- // Operands column with scalar/address hover popup.
+ let mnem_resp = ui.label(
+ egui::RichText::new(&row.mnem).monospace().color(mnem_color),
+ );
+ if !row.groups_summary.is_empty() || !row.regs_rw.is_empty() {
+ mnem_resp.on_hover_ui(|ui| {
+ ui.monospace(format!("id {}", row.id.raw()));
+ if !row.groups_summary.is_empty() {
+ ui.small(format!("groups: {}", row.groups_summary));
+ }
+ if !row.regs_rw.is_empty() {
+ ui.small(&row.regs_rw);
+ }
+ });
+ }
+ // Operands column with scalar/address hover popup.
let ops_resp = ui.add(
egui::Label::new(egui::RichText::new(&row.ops).monospace())
.sense(egui::Sense::hover()),
@@ -5399,53 +5361,53 @@ impl GhidrustApp {
}
});
}
- // Flow column: arrow glyph indicator.
+ // Flow column: arrow glyph indicator.
let flow_glyph = if row.is_ret {
- "return"
+ "return"
} else if row.is_uncond {
- "→"
+ "→"
} else if row.is_cond {
- "?→"
+ "?→"
} else if row.is_call {
- "call"
+ "call"
} else {
- ""
+ ""
};
ui.small(egui::RichText::new(flow_glyph).monospace());
- // Comment / applied type column (EOL + Repeatable
- // + Plate + Applied Type decoration).
+ // Comment / applied type column (EOL + Repeatable
+ // + Plate + Applied Type decoration).
let mut comment_row = String::new();
if let Some(t) = &row.applied_type {
- comment_row.push_str(&format!("<{t}> "));
+ comment_row.push_str(&format!("<{t}> "));
}
if let Some(t) = &row.comment_eol {
- comment_row.push_str(&format!("// {t}"));
+ comment_row.push_str(&format!("// {t}"));
}
if let Some(t) = &row.comment_repeat {
if !comment_row.is_empty() {
- comment_row.push_str(" ");
+ comment_row.push_str(" ");
}
- comment_row.push_str(&format!("~ {t}"));
+ comment_row.push_str(&format!("~ {t}"));
}
if let Some(t) = &row.comment_plate {
if !comment_row.is_empty() {
- comment_row.push_str(" ");
+ comment_row.push_str(" ");
}
- comment_row.push_str(&format!("[PLATE {t}]"));
+ comment_row.push_str(&format!("[PLATE {t}]"));
}
ui.small(egui::RichText::new(comment_row).italics());
ui.end_row();
- // Post-comment row (Ghidra `Post` comment appears
- // as its own line below the instruction).
+ // Post-comment row (`Post` comment appears
+ // as its own line below the instruction).
if let Some(post) = &row.comment_post {
- ui.label(egui::RichText::new(" ").monospace());
+ ui.label(egui::RichText::new(" ").monospace());
ui.label(
- egui::RichText::new(format!("; {post}"))
+ egui::RichText::new(format!("; {post}"))
.italics()
.color(Color32::from_rgb(0xBA, 0x68, 0xC8)),
);
for _ in 0..5 {
- ui.label("");
+ ui.label("");
}
ui.end_row();
}
@@ -5472,9 +5434,9 @@ impl GhidrustApp {
RowAction::OpenRetype => self.open_retype_dialog(va),
RowAction::OpenChooser => self.open_type_chooser(Some(va)),
RowAction::OpenSignature => {
- // Alt+Enter is defined on a function; if the cursor isn't
- // inside a function, fall back to opening the signature
- // dialog with the given VA as entry (user can retype it).
+ // Alt+Enter is defined on a function; if the cursor isn't
+ // inside a function, fall back to opening the signature
+ // dialog with the given VA as entry (user can retype it).
let entry = self
.program
.as_ref()
@@ -5492,13 +5454,13 @@ impl GhidrustApp {
self.equate_dialog_va = Some(va);
self.equate_dialog_op = 1;
self.equate_dialog_name.clear();
- // Preload first scalar from the operand string for convenience.
+ // Preload first scalar from the operand string for convenience.
self.equate_dialog_value = self
.listing
.iter()
.find(|i| i.address == va)
.and_then(|i| menu_actions::extract_scalars(&i.operands).first().copied())
- .map(|v| format!("{v}"))
+ .map(|v| format!("{v}"))
.unwrap_or_default();
self.show_equate_dialog = true;
}
@@ -5514,41 +5476,41 @@ impl GhidrustApp {
}
}
- /// 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");
+ ui.heading("Decompiler");
if self.program.is_none() {
- ui.weak("Open a project file, then select a function or listing address.");
+ ui.weak("Open a project file, then select a function or listing address.");
return;
}
- // Stage picker (Stage-0 / 0.5 / 1). Changing kicks off a re-emit
- // for the currently-focused entry.
+ // Stage picker (Stage-0 / 0.5 / 1). Changing kicks off a re-emit
+ // for the currently-focused entry.
let mut sel = self.decomp_stage;
ui.horizontal(|ui| {
- ui.label("Stage:");
- egui::ComboBox::from_id_salt("decomp_stage_combo")
+ ui.label("Stage:");
+ egui::ComboBox::from_id_salt("decomp_stage_combo")
.selected_text(sel.label())
.show_ui(ui, |ui| {
- ui.selectable_value(&mut sel, DecompStage::Stage0, "Stage-0 (CFG → goto)");
+ ui.selectable_value(&mut sel, DecompStage::Stage0, "Stage-0 (CFG → goto)");
ui.selectable_value(
&mut sel,
DecompStage::Stage05,
- "Stage-0.5 (IR-informed)",
+ "Stage-0.5 (IR-informed)",
);
ui.selectable_value(
&mut sel,
DecompStage::Stage1,
- "Stage-1 (SSA + structure + types)",
+ "Stage-1 (SSA + structure + types)",
);
});
if let Some(r) = self.decomp_lift_ratio {
- ui.small(format!("lift {:.1}%", r * 100.0));
+ ui.small(format!("lift {:.1}%", r * 100.0));
}
});
if sel != self.decomp_stage {
self.set_decomp_stage(sel);
}
- // Keep cache in sync with cursor when switching to this pane.
+ // Keep cache in sync with cursor when switching to this pane.
if let Some(va) = self
.listing_focus_va
.or(self.decomp_entry)
@@ -5556,9 +5518,9 @@ impl GhidrustApp {
{
self.refresh_decompiler_at(va);
}
- // requested_addr vs resolved_entry (honest containing-function resolve)
- // plus an IL2CPP `follow_stub` chip when the resolved entry classifies
- // as a lazy resolve thunk with a populated slot.
+ // requested_addr vs resolved_entry (honest containing-function resolve)
+ // plus an IL2CPP `follow_stub` chip when the resolved entry classifies
+ // as a lazy resolve thunk with a populated slot.
if let Some(va) = self.listing_focus_va.or(self.decomp_entry) {
if let Some(prog) = self.program.as_mut() {
if let Ok(resolve) = ghidrust_core::resolve_function(prog, va) {
@@ -5568,29 +5530,29 @@ impl GhidrustApp {
});
ui.horizontal(|ui| {
ui.small(format!(
- "resolve: requested={:#x} → resolved_entry={} [{:?}]{}",
+ "resolve: requested={:#x} → resolved_entry={} [{:?}]{}",
resolve.requested_addr,
resolve
.resolved_entry
- .map(|e| format!("{e:#x}"))
- .unwrap_or_else(|| "—".into()),
+ .map(|e| format!("{e:#x}"))
+ .unwrap_or_else(|| "—".into()),
resolve.resolve_status,
- if resolve.ambiguous { " (ambiguous)" } else { "" },
+ if resolve.ambiguous { " (ambiguous)" } else { "" },
));
if let Some(target) = stub_target {
ui.small(
- egui::RichText::new(format!("follow_stub → {target:#x}"))
+ egui::RichText::new(format!("follow_stub → {target:#x}"))
.color(Color32::from_rgb(0xFB, 0xC0, 0x2D)),
)
.on_hover_text(
- "ghidrust_il2cpp::follow_stub_target — cached slot for this IL2CPP resolve thunk",
+ "ghidrust_il2cpp::follow_stub_target — cached slot for this IL2CPP resolve thunk",
);
}
});
}
}
}
- // Header row: stage + entry + Commit/Rename right-click hints.
+ // Header row: stage + entry + Commit/Rename right-click hints.
ui.horizontal(|ui| {
if !self.decomp_status.is_empty() {
ui.small(&self.decomp_status);
@@ -5598,35 +5560,35 @@ impl GhidrustApp {
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
if let Some(entry) = self.decomp_entry {
if ui
- .small_button("Commit Params/Return")
- .on_hover_text("Persist inferred params + return type as user edits")
+ .small_button("Commit Params/Return")
+ .on_hover_text("Persist inferred params + return type as user edits")
.clicked()
{
if let Err(e) = self.commit_params_return(entry) {
- self.status = format!("error: {e}");
+ self.status = format!("error: {e}");
self.log_error(self.status.clone());
}
}
if ui
- .small_button("Commit Locals")
- .on_hover_text("Persist inferred stack locals as user edits")
+ .small_button("Commit Locals")
+ .on_hover_text("Persist inferred stack locals as user edits")
.clicked()
{
if let Err(e) = self.commit_locals(entry) {
- self.status = format!("error: {e}");
+ self.status = format!("error: {e}");
self.log_error(self.status.clone());
}
}
if ui
- .small_button("Edit signature…")
- .on_hover_text("Edit function signature")
+ .small_button("Edit signature…")
+ .on_hover_text("Edit function signature")
.clicked()
{
self.open_signature_dialog(entry);
}
if ui
- .small_button("Rename function…")
- .on_hover_text("Rename this function (L)")
+ .small_button("Rename function…")
+ .on_hover_text("Rename this function (L)")
.clicked()
{
self.open_rename_dialog(entry);
@@ -5637,11 +5599,11 @@ impl GhidrustApp {
ui.separator();
if self.decomp_lines.is_empty() && self.decomp_text.is_empty() {
ui.weak(
- "Select a Symbol Tree function or a Listing instruction to decompile (Stage-0 CFG → pseudo-C).",
+ "Select a Symbol Tree function or a Listing instruction to decompile (Stage-0 CFG → pseudo-C).",
);
return;
}
- // Render tokenised lines.
+ // Render tokenised lines.
let visuals = ui.visuals().clone();
let text_color = visuals.text_color();
let cross_line = self.decomp_cross_line;
@@ -5650,7 +5612,7 @@ impl GhidrustApp {
let mut mid_clicked_text: Option<String> = None;
let mut right_click_target: Option<(u64, String)> = None; // (va, token text)
egui::ScrollArea::both()
- .id_salt("decomp_tokens_scroll")
+ .id_salt("decomp_tokens_scroll")
.auto_shrink([false, false])
.show(ui, |ui| {
let font = egui::FontId::monospace(13.0);
@@ -5665,11 +5627,11 @@ impl GhidrustApp {
};
let mut render_row = |ui: &mut egui::Ui| {
ui.horizontal(|ui| {
- // Left rail: address gutter (line.machine_addr).
+ // Left rail: address gutter (line.machine_addr).
let gutter = line
.machine_addr
- .map(|va| format!("{va:08x} "))
- .unwrap_or_else(|| " ".into());
+ .map(|va| format!("{va:08x} "))
+ .unwrap_or_else(|| " ".into());
ui.add(
egui::Label::new(
egui::RichText::new(gutter)
@@ -5752,16 +5714,16 @@ impl GhidrustApp {
};
}
if let Some((va, text)) = right_click_target {
- // Right-click on a token opens the rename dialog when it looks like an identifier.
+ // Right-click on a token opens the rename dialog when it looks like an identifier.
if !text.is_empty()
- && text.chars().next().map(|c| c.is_ascii_alphabetic() || c == '_').unwrap_or(false)
+ && text.chars().next().map(|c| c.is_ascii_alphabetic() || c == '_').unwrap_or(false)
{
self.open_rename_dialog(va);
self.rename_dialog_old_name = text;
}
}
if let Some(va) = clicked_addr {
- // Only navigate if VA looks plausibly in-range (avoid `block_0` id = 0 jumping to base).
+ // Only navigate if VA looks plausibly in-range (avoid `block_0` id = 0 jumping to base).
let plausible = self
.program
.as_ref()
@@ -5769,7 +5731,7 @@ impl GhidrustApp {
.unwrap_or(false)
|| va >= 0x1000;
if plausible {
- let _ = self.goto_address_str(&format!("{va:#x}"));
+ let _ = self.goto_address_str(&format!("{va:#x}"));
}
}
}
@@ -5824,12 +5786,12 @@ impl GhidrustApp {
.and_then(|p| p.function_at(entry))
.map(|f| {
format!(
- "undefined {}({})",
+ "undefined {}({})",
f.name,
if f.parameters.is_empty() {
- "void".to_string()
+ "void".to_string()
} else {
- f.parameters.join(", ")
+ f.parameters.join(", ")
}
)
})
@@ -5867,30 +5829,30 @@ impl GhidrustApp {
}
fn ui_bookmarks_pane(&mut self, ui: &mut egui::Ui, muted: Color32, primary: Color32) {
- ui.heading("Bookmarks");
+ ui.heading("Bookmarks");
ui.small(
- egui::RichText::new("Ghidra BookmarkPlugin analog · 5 standard kinds").color(muted),
+ egui::RichText::new("BookmarkPlugin analog · 5 standard kinds").color(muted),
);
ui.separator();
ui.horizontal(|ui| {
- ui.label("Filter:");
+ ui.label("Filter:");
ui.add(
egui::TextEdit::singleline(&mut self.bookmark_filter)
.desired_width(200.0)
- .hint_text("category or description"),
+ .hint_text("category or description"),
);
if ui
- .button("Add at cursor…")
- .on_hover_text("Add a bookmark at the current Listing VA")
+ .button("Add at cursor…")
+ .on_hover_text("Add a bookmark at the current Listing VA")
.clicked()
{
if let Some(va) = self.listing_focus_va {
self.bookmark_dialog_kind = BookmarkKind::Note;
self.bookmark_dialog_category = String::new();
- self.bookmark_dialog_description = format!("bookmark @ {va:#x}");
+ self.bookmark_dialog_description = format!("bookmark @ {va:#x}");
self.show_bookmark_dialog = true;
} else {
- self.status = "No cursor VA — click a Listing line first".into();
+ self.status = "No cursor VA — click a Listing line first".into();
self.log(self.status.clone());
}
}
@@ -5898,7 +5860,7 @@ impl GhidrustApp {
ui.separator();
if self.bookmarks.is_empty() {
- ui.weak("No bookmarks yet — click Add at cursor to place one.");
+ ui.weak("No bookmarks yet — click Add at cursor to place one.");
return;
}
@@ -5924,21 +5886,21 @@ impl GhidrustApp {
})
.collect();
- ui.small(format!("{} / {} bookmarks", rows.len(), self.bookmarks.len()));
+ ui.small(format!("{} / {} bookmarks", rows.len(), self.bookmarks.len()));
egui::ScrollArea::vertical()
- .id_salt("bookmarks_scroll")
+ .id_salt("bookmarks_scroll")
.max_height(360.0)
.show(ui, |ui| {
- egui::Grid::new("bookmarks_grid")
+ egui::Grid::new("bookmarks_grid")
.num_columns(5)
.striped(true)
.show(ui, |ui| {
- ui.strong("Type");
- ui.strong("Address");
- ui.strong("Category");
- ui.strong("Description");
- ui.strong("");
+ ui.strong("Type");
+ ui.strong("Address");
+ ui.strong("Category");
+ ui.strong("Description");
+ ui.strong("");
ui.end_row();
let mut goto: Option<u64> = None;
@@ -5950,22 +5912,22 @@ impl GhidrustApp {
.strong(),
);
if ui
- .link(egui::RichText::new(format!("{va:#x}")).monospace())
- .on_hover_text("Go To this address")
+ .link(egui::RichText::new(format!("{va:#x}")).monospace())
+ .on_hover_text("Go To this address")
.clicked()
{
goto = Some(*va);
}
ui.label(cat);
ui.label(desc);
- if ui.small_button("Delete").clicked() {
+ if ui.small_button("Delete").clicked() {
delete = Some(*idx);
}
ui.end_row();
}
let _ = primary; // reserved for future accent use
if let Some(va) = goto {
- let _ = self.goto_address_str(&format!("{va:#x}"));
+ let _ = self.goto_address_str(&format!("{va:#x}"));
}
if let Some(i) = delete {
self.delete_bookmark(i);
@@ -5975,44 +5937,44 @@ impl GhidrustApp {
}
fn ui_memory_map_pane(&mut self, ui: &mut egui::Ui, muted: Color32) {
- ui.heading("Memory Map");
+ ui.heading("Memory Map");
ui.small(
egui::RichText::new(
- "Ghidra MemoryMapPlugin · toggle RWX / add / delete session memory blocks",
+ "MemoryMapPlugin · toggle RWX / add / delete session memory blocks",
)
.color(muted),
);
ui.separator();
if self.program.is_none() {
- ui.weak("No program loaded.");
+ ui.weak("No program loaded.");
return;
}
- // Add-row form.
+ // Add-row form.
ui.horizontal(|ui| {
- ui.label("Add block:");
+ ui.label("Add block:");
ui.add(
egui::TextEdit::singleline(&mut self.memory_map_new_name)
.desired_width(120.0)
- .hint_text("name"),
+ .hint_text("name"),
);
ui.add(
egui::TextEdit::singleline(&mut self.memory_map_new_va)
.desired_width(120.0)
- .hint_text("VA (0x…)"),
+ .hint_text("VA (0x…)"),
);
ui.add(
egui::TextEdit::singleline(&mut self.memory_map_new_size)
.desired_width(100.0)
- .hint_text("size (0x…)"),
+ .hint_text("size (0x…)"),
);
- ui.checkbox(&mut self.memory_map_new_r, "R");
- ui.checkbox(&mut self.memory_map_new_w, "W");
- ui.checkbox(&mut self.memory_map_new_x, "X");
+ ui.checkbox(&mut self.memory_map_new_r, "R");
+ ui.checkbox(&mut self.memory_map_new_w, "W");
+ ui.checkbox(&mut self.memory_map_new_x, "X");
let can_add = !self.memory_map_new_name.trim().is_empty()
&& !self.memory_map_new_va.trim().is_empty()
&& !self.memory_map_new_size.trim().is_empty();
- if ui.add_enabled(can_add, egui::Button::new("Add")).clicked() {
+ if ui.add_enabled(can_add, egui::Button::new("Add")).clicked() {
let name = self.memory_map_new_name.clone();
let va = parse_address(&self.memory_map_new_va).unwrap_or(0);
let size = parse_address(&self.memory_map_new_size).unwrap_or(0);
@@ -6031,7 +5993,7 @@ impl GhidrustApp {
executable: x,
});
}
- self.status = "Memory Map · added block".into();
+ self.status = "Memory Map · added block".into();
self.log(self.status.clone());
}
}
@@ -6056,21 +6018,21 @@ impl GhidrustApp {
.unwrap_or_default();
egui::ScrollArea::both()
- .id_salt("memmap_scroll")
+ .id_salt("memmap_scroll")
.show(ui, |ui| {
- egui::Grid::new("memory_map_grid")
+ egui::Grid::new("memory_map_grid")
.num_columns(9)
.striped(true)
.show(ui, |ui| {
- ui.strong("Name");
- ui.strong("Start");
- ui.strong("End");
- ui.strong("Length");
- ui.strong("R");
- ui.strong("W");
- ui.strong("X");
- ui.strong("Notes");
- ui.strong("");
+ ui.strong("Name");
+ ui.strong("Start");
+ ui.strong("End");
+ ui.strong("Length");
+ ui.strong("R");
+ ui.strong("W");
+ ui.strong("X");
+ ui.strong("Notes");
+ ui.strong("");
ui.end_row();
let blocks: Vec<(String, u64, u64, bool, bool, bool)> = self
.program
@@ -6103,37 +6065,37 @@ impl GhidrustApp {
rename = Some((i, editable));
}
if ui
- .link(egui::RichText::new(format!("{va:#x}")).monospace())
+ .link(egui::RichText::new(format!("{va:#x}")).monospace())
.clicked()
{
goto = Some(*va);
}
- ui.monospace(format!("{:#x}", va.saturating_add(*size)));
- ui.monospace(format!("{size:#x}"));
+ ui.monospace(format!("{:#x}", va.saturating_add(*size)));
+ ui.monospace(format!("{size:#x}"));
let mut rb = *r;
let mut wb = *w;
let mut xb = *x;
- if ui.checkbox(&mut rb, "").changed() {
- toggle = Some((i, 'R'));
+ if ui.checkbox(&mut rb, "").changed() {
+ toggle = Some((i, 'R'));
}
- if ui.checkbox(&mut wb, "").changed() {
- toggle = Some((i, 'W'));
+ if ui.checkbox(&mut wb, "").changed() {
+ toggle = Some((i, 'W'));
}
- if ui.checkbox(&mut xb, "").changed() {
- toggle = Some((i, 'X'));
+ if ui.checkbox(&mut xb, "").changed() {
+ toggle = Some((i, 'X'));
}
- let notes = notes_by_section.get(name.trim_end_matches('\0'));
+ let notes = notes_by_section.get(name.trim_end_matches('\0'));
match notes {
Some(msgs) => {
- let joined = msgs.join(" · ");
- ui.small(egui::RichText::new("⚠ notes").color(muted))
+ let joined = msgs.join(" · ");
+ ui.small(egui::RichText::new("⚠ notes").color(muted))
.on_hover_text(joined);
}
None => {
- ui.small(egui::RichText::new("—").color(muted));
+ ui.small(egui::RichText::new("—").color(muted));
}
}
- if ui.small_button("Delete").clicked() {
+ if ui.small_button("Delete").clicked() {
delete = Some(i);
}
ui.end_row();
@@ -6142,7 +6104,7 @@ impl GhidrustApp {
});
if let Some(va) = goto {
- let _ = self.goto_address_str(&format!("{va:#x}"));
+ let _ = self.goto_address_str(&format!("{va:#x}"));
}
if let Some((i, newname)) = rename {
if let Some(prog) = self.program.as_mut() {
@@ -6155,9 +6117,9 @@ impl GhidrustApp {
if let Some(prog) = self.program.as_mut() {
if let Some(b) = prog.blocks.get_mut(i) {
match ch {
- 'R' => b.readable = !b.readable,
- 'W' => b.writable = !b.writable,
- 'X' => b.executable = !b.executable,
+ 'R' => b.readable = !b.readable,
+ 'W' => b.writable = !b.writable,
+ 'X' => b.executable = !b.executable,
_ => {}
}
}
@@ -6173,27 +6135,27 @@ impl GhidrustApp {
}
fn ui_functions_window(&mut self, ui: &mut egui::Ui, muted: Color32, primary: Color32) {
- ui.heading("Functions");
+ ui.heading("Functions");
ui.small(
- egui::RichText::new("Ghidra FunctionWindowPlugin · flat table of Program::analysis.functions")
+ egui::RichText::new("FunctionWindowPlugin · flat table of Program::analysis.functions")
.color(muted),
);
ui.separator();
let Some(prog) = self.program.as_ref() else {
- ui.weak("No program loaded.");
+ ui.weak("No program loaded.");
return;
};
let n_total = prog.analysis.functions.len();
if n_total == 0 {
- ui.weak("No functions — run Function Start Search.");
+ ui.weak("No functions — run Function Start Search.");
return;
}
ui.horizontal(|ui| {
- ui.label("Filter:");
+ ui.label("Filter:");
ui.add(
egui::TextEdit::singleline(&mut self.functions_window_filter)
.desired_width(300.0)
- .hint_text("Function name…"),
+ .hint_text("Function name…"),
);
});
let q = self.functions_window_filter.to_ascii_lowercase();
@@ -6204,33 +6166,33 @@ impl GhidrustApp {
.filter(|f| q.is_empty() || f.name.to_ascii_lowercase().contains(&q))
.map(|f| (f.entry, f.end, f.name.clone(), f.parameters.len()))
.collect();
- ui.small(format!("{} / {} functions", rows.len(), n_total));
+ ui.small(format!("{} / {} functions", rows.len(), n_total));
let focus = self.decomp_entry;
egui::ScrollArea::vertical()
- .id_salt("fnwin_scroll")
+ .id_salt("fnwin_scroll")
.max_height(400.0)
.show(ui, |ui| {
- egui::Grid::new("functions_window_grid")
+ egui::Grid::new("functions_window_grid")
.num_columns(4)
.striped(true)
.show(ui, |ui| {
- ui.strong("Entry");
- ui.strong("Size");
- ui.strong("Name");
- ui.strong("Params");
+ ui.strong("Entry");
+ ui.strong("Size");
+ ui.strong("Name");
+ ui.strong("Params");
ui.end_row();
let mut clicked: Option<u64> = None;
for (entry, end, name, params) in &rows {
let size = end.saturating_sub(*entry);
- let addr_text = egui::RichText::new(format!("{entry:#x}"))
+ let addr_text = egui::RichText::new(format!("{entry:#x}"))
.monospace()
.color(if focus == Some(*entry) { primary } else { ui.visuals().text_color() });
if ui.link(addr_text).clicked() {
clicked = Some(*entry);
}
- ui.monospace(format!("{size:#x}"));
+ ui.monospace(format!("{size:#x}"));
ui.label(name);
- ui.monospace(format!("{params}"));
+ ui.monospace(format!("{params}"));
ui.end_row();
}
if let Some(va) = clicked {
@@ -6241,64 +6203,64 @@ impl GhidrustApp {
}
fn ui_symbol_table(&mut self, ui: &mut egui::Ui, muted: Color32) {
- ui.heading("Symbol Table");
+ ui.heading("Symbol Table");
ui.small(
egui::RichText::new(
- "Ghidra SymbolTablePlugin · symbols + function entries · Refs → opens Symbol References",
+ "SymbolTablePlugin · symbols + function entries · Refs → opens Symbol References",
)
.color(muted),
);
ui.separator();
let Some(prog) = self.program.as_ref() else {
- ui.weak("No program loaded.");
+ ui.weak("No program loaded.");
return;
};
ui.horizontal(|ui| {
- ui.label("Filter:");
+ ui.label("Filter:");
ui.add(
egui::TextEdit::singleline(&mut self.symbol_table_filter)
.desired_width(280.0)
- .hint_text("Symbol name…"),
+ .hint_text("Symbol name…"),
);
});
let q = self.symbol_table_filter.to_ascii_lowercase();
- // Merge analysis.symbols + function entries into one flat table.
- let mut rows: Vec<(u64, String, &'static str)> = Vec::new();
+ // Merge analysis.symbols + function entries into one flat table.
+ let mut rows: Vec<(u64, String, &'static str)> = Vec::new();
for s in &prog.analysis.symbols {
- rows.push((s.va, s.name.clone(), "Symbol"));
+ rows.push((s.va, s.name.clone(), "Symbol"));
}
for f in &prog.analysis.functions {
- rows.push((f.entry, f.name.clone(), "Function"));
+ rows.push((f.entry, f.name.clone(), "Function"));
}
rows.retain(|(_, name, _)| q.is_empty() || name.to_ascii_lowercase().contains(&q));
rows.sort_by_key(|r| r.0);
- ui.small(format!("{} rows", rows.len()));
+ ui.small(format!("{} rows", rows.len()));
let mut goto: Option<u64> = None;
let mut show_refs: Option<u64> = None;
egui::ScrollArea::vertical()
- .id_salt("symtable_scroll")
+ .id_salt("symtable_scroll")
.max_height(400.0)
.show(ui, |ui| {
- egui::Grid::new("symbol_table_grid")
+ egui::Grid::new("symbol_table_grid")
.num_columns(4)
.striped(true)
.show(ui, |ui| {
- ui.strong("Address");
- ui.strong("Name");
- ui.strong("Type");
- ui.strong("Refs");
+ ui.strong("Address");
+ ui.strong("Name");
+ ui.strong("Type");
+ ui.strong("Refs");
ui.end_row();
for (va, name, ty) in &rows {
if ui
- .link(egui::RichText::new(format!("{va:#x}")).monospace())
+ .link(egui::RichText::new(format!("{va:#x}")).monospace())
.clicked()
{
goto = Some(*va);
}
ui.label(name);
ui.monospace(*ty);
- if ui.small_button("Refs").on_hover_text("Open Symbol References for this VA").clicked() {
+ if ui.small_button("Refs").on_hover_text("Open Symbol References for this VA").clicked() {
show_refs = Some(*va);
}
ui.end_row();
@@ -6306,7 +6268,7 @@ impl GhidrustApp {
});
});
if let Some(va) = goto {
- let _ = self.goto_address_str(&format!("{va:#x}"));
+ let _ = self.goto_address_str(&format!("{va:#x}"));
}
if let Some(va) = show_refs {
self.symbol_refs_target = Some(va);
@@ -6315,28 +6277,28 @@ impl GhidrustApp {
}
fn ui_defined_strings(&mut self, ui: &mut egui::Ui, muted: Color32) {
- ui.heading("Defined Strings");
+ ui.heading("Defined Strings");
ui.small(
- egui::RichText::new("Ghidra ViewStringsPlugin · session strings from ASCII Strings analyzer")
+ egui::RichText::new("ViewStringsPlugin · session strings from ASCII Strings analyzer")
.color(muted),
);
ui.separator();
if self.strings.is_empty() {
- ui.weak("No strings yet — run ASCII Strings analyzer.");
+ ui.weak("No strings yet — run ASCII Strings analyzer.");
return;
}
ui.horizontal(|ui| {
- ui.label("Filter:");
+ ui.label("Filter:");
ui.add(
egui::TextEdit::singleline(&mut self.defined_strings_filter)
.desired_width(280.0)
- .hint_text("Substring…"),
+ .hint_text("Substring…"),
);
- ui.label("Encoding:");
- egui::ComboBox::from_id_salt("defined_strings_encoding_combo")
+ ui.label("Encoding:");
+ egui::ComboBox::from_id_salt("defined_strings_encoding_combo")
.selected_text(self.defined_strings_encoding.clone())
.show_ui(ui, |ui| {
- for enc in ["all", "ascii", "utf16le"] {
+ for enc in ["all", "ascii", "utf16le"] {
ui.selectable_value(&mut self.defined_strings_encoding, enc.into(), enc);
}
});
@@ -6347,26 +6309,26 @@ impl GhidrustApp {
.strings
.iter()
.filter(|s| q.is_empty() || s.value.to_ascii_lowercase().contains(&q))
- .filter(|s| enc_filter == "all" || s.encoding == enc_filter)
+ .filter(|s| enc_filter == "all" || s.encoding == enc_filter)
.map(|s| (s.va, s.value.clone(), s.encoding.clone()))
.collect();
- ui.small(format!("{} / {} strings", rows.len(), self.strings.len()));
+ ui.small(format!("{} / {} strings", rows.len(), self.strings.len()));
egui::ScrollArea::vertical()
- .id_salt("defstr_scroll")
+ .id_salt("defstr_scroll")
.max_height(400.0)
.show(ui, |ui| {
- egui::Grid::new("defined_strings_grid")
+ egui::Grid::new("defined_strings_grid")
.num_columns(3)
.striped(true)
.show(ui, |ui| {
- ui.strong("Address");
- ui.strong("Encoding");
- ui.strong("String");
+ ui.strong("Address");
+ ui.strong("Encoding");
+ ui.strong("String");
ui.end_row();
let mut goto: Option<u64> = None;
for (va, s, enc) in &rows {
if ui
- .link(egui::RichText::new(format!("{va:#x}")).monospace())
+ .link(egui::RichText::new(format!("{va:#x}")).monospace())
.clicked()
{
goto = Some(*va);
@@ -6377,71 +6339,72 @@ impl GhidrustApp {
ui.end_row();
}
if let Some(va) = goto {
- let _ = self.goto_address_str(&format!("{va:#x}"));
+ let _ = self.goto_address_str(&format!("{va:#x}"));
}
});
});
}
fn ui_relocation_table(&mut self, ui: &mut egui::Ui, muted: Color32) {
- ui.heading("Relocation Table");
+ ui.heading("Relocation Table");
ui.small(
- egui::RichText::new("Ghidra RelocationTablePlugin · from Program::sections")
+ egui::RichText::new("RelocationTablePlugin · from Program::sections")
.color(muted),
);
ui.separator();
let Some(prog) = self.program.as_ref() else {
- ui.weak("No program loaded.");
+ ui.weak("No program loaded.");
return;
};
ui.small(
egui::RichText::new(
- "Section metadata rendered here as a Stage-0 placeholder. Full PE reloc / ELF rela \
- parse lands in .",
+ "Section metadata rendered here as a Stage-0 placeholder. Full PE reloc / ELF rela \
+ parse lands in .",
)
.color(muted)
.italics(),
);
- egui::Grid::new("relocs_grid")
+ egui::Grid::new("relocs_grid")
.num_columns(3)
.striped(true)
.show(ui, |ui| {
- ui.strong("Section");
- ui.strong("VA");
- ui.strong("Size");
+ ui.strong("Section");
+ ui.strong("VA");
+ ui.strong("Size");
ui.end_row();
for s in &prog.sections {
ui.label(&s.name);
- ui.monospace(format!("{:#x}", s.va));
- ui.monospace(format!("{:#x}", s.virtual_size));
+ ui.monospace(format!("{:#x}", s.va));
+ ui.monospace(format!("{:#x}", s.virtual_size));
ui.end_row();
}
});
}
fn ui_disassembled_view_pane(&mut self, ui: &mut egui::Ui, muted: Color32) {
- ui.heading("Disassembled View");
+ ui.heading("Disassembled View");
ui.small(
- egui::RichText::new("Ghidra DisassembledViewPlugin · virtual disasm at cursor")
+ egui::RichText::new("DisassembledViewPlugin · detail at cursor")
.color(muted),
);
ui.separator();
let Some(prog) = self.program.as_ref() else {
- ui.weak("No program loaded.");
+ ui.weak("No program loaded.");
return;
};
let va = match self.listing_focus_va.or(prog.entry) {
Some(v) => v,
None => {
- ui.weak("No cursor / entry.");
+ ui.weak("No cursor / entry.");
return;
}
};
- match disassemble_range(prog, va, 12) {
- Ok(lines) => {
- for insn in lines {
- ui.monospace(insn.text());
- }
+ let arch = self.listing_arch();
+ match disassemble_at_opts(prog, va, Some(&self.decode_opts.to_engine_opts())) {
+ Ok(insn) => {
+ ui.monospace(insn.text());
+ ui.separator();
+ ui_detail_pane(ui, &insn, arch);
}
Err(e) => {
ui.colored_label(Color32::from_rgb(0xE5, 0x39, 0x35), e.to_string());
@@ -6450,32 +6413,32 @@ impl GhidrustApp {
}
fn ui_comment_window(&mut self, ui: &mut egui::Ui, muted: Color32) {
- ui.heading("Comments");
+ ui.heading("Comments");
ui.small(
egui::RichText::new(
- "Ghidra CommentWindowPlugin · shows EOL/Pre/Post/Plate/Repeatable edits + bookmarks",
+ "CommentWindowPlugin · shows EOL/Pre/Post/Plate/Repeatable edits + bookmarks",
)
.color(muted),
);
ui.separator();
- // Filter row — Ghidra CommentWindow provides both a text filter and
- // a per-kind toggle.
+ // Filter row — CommentWindow provides both a text filter and
+ // a per-kind toggle.
ui.horizontal(|ui| {
- ui.label("Filter:");
+ ui.label("Filter:");
ui.add(
egui::TextEdit::singleline(&mut self.comment_window_filter)
.desired_width(240.0)
- .hint_text("Text / address / kind…"),
+ .hint_text("Text / address / kind…"),
);
- ui.label("Kind:");
+ ui.label("Kind:");
let cur = self
.comment_window_kind_filter
.map(|k| k.label())
- .unwrap_or("All");
- egui::ComboBox::from_id_salt("comment_window_kind_combo")
+ .unwrap_or("All");
+ egui::ComboBox::from_id_salt("comment_window_kind_combo")
.selected_text(cur)
.show_ui(ui, |ui| {
- ui.selectable_value(&mut self.comment_window_kind_filter, None, "All");
+ ui.selectable_value(&mut self.comment_window_kind_filter, None, "All");
for k in CommentKind::ALL {
ui.selectable_value(
&mut self.comment_window_kind_filter,
@@ -6486,23 +6449,23 @@ impl GhidrustApp {
});
});
ui.separator();
- // Real edited comments from ProgramEdits — one row per (va, kind).
- let mut rows: Vec<(&'static str, u64, String)> = Vec::new();
+ // Real edited comments from ProgramEdits — one row per (va, kind).
+ let mut rows: Vec<(&'static str, u64, String)> = Vec::new();
if let Some(prog) = self.program.as_ref() {
for ((va, kind), text) in &prog.edits.comments {
rows.push((kind.label(), *va, text.clone()));
}
}
- // Also surface bookmarks as "Note-derived" comment rows.
+ // Also surface bookmarks as "Note-derived" comment rows.
for b in &self.bookmarks {
let text = if b.category.is_empty() {
b.description.clone()
} else {
- format!("[{}] {}", b.category, b.description)
+ format!("[{}] {}", b.category, b.description)
};
- rows.push(("Bookmark", b.va, text));
+ rows.push(("Bookmark", b.va, text));
}
- // Apply filters.
+ // Apply filters.
let text_filter = self.comment_window_filter.to_ascii_lowercase();
let kind_filter = self.comment_window_kind_filter;
rows.retain(|(kind, va, text)| {
@@ -6514,44 +6477,44 @@ impl GhidrustApp {
if text_filter.is_empty() {
return true;
}
- let addr = format!("{va:#x}");
+ let addr = format!("{va:#x}");
text.to_ascii_lowercase().contains(&text_filter)
|| kind.to_ascii_lowercase().contains(&text_filter)
|| addr.contains(&text_filter)
});
if rows.is_empty() {
ui.weak(
- "No comments/bookmarks match — set a comment with `;` on a Listing line, or add a Bookmark.",
+ "No comments/bookmarks match — set a comment with `;` on a Listing line, or add a Bookmark.",
);
return;
}
rows.sort_by_key(|(_, va, _)| *va);
egui::ScrollArea::vertical()
- .id_salt("comment_window_scroll")
+ .id_salt("comment_window_scroll")
.max_height(400.0)
.show(ui, |ui| {
- egui::Grid::new("comments_grid")
+ egui::Grid::new("comments_grid")
.num_columns(3)
.striped(true)
.show(ui, |ui| {
- ui.strong("Type");
- ui.strong("Address");
- ui.strong("Comment");
+ ui.strong("Type");
+ ui.strong("Address");
+ ui.strong("Comment");
ui.end_row();
let mut goto: Option<u64> = None;
let mut delete: Option<(u64, CommentKind)> = None;
for (kind, va, text) in &rows {
let color = match *kind {
- "EOL" => Color32::from_rgb(0x81, 0xC7, 0x84),
- "Pre" => Color32::from_rgb(0x64, 0xB5, 0xF6),
- "Post" => Color32::from_rgb(0xBA, 0x68, 0xC8),
- "Plate" => Color32::from_rgb(0xFF, 0xB7, 0x4D),
- "Repeatable" => Color32::from_rgb(0x4D, 0xD0, 0xE1),
+ "EOL" => Color32::from_rgb(0x81, 0xC7, 0x84),
+ "Pre" => Color32::from_rgb(0x64, 0xB5, 0xF6),
+ "Post" => Color32::from_rgb(0xBA, 0x68, 0xC8),
+ "Plate" => Color32::from_rgb(0xFF, 0xB7, 0x4D),
+ "Repeatable" => Color32::from_rgb(0x4D, 0xD0, 0xE1),
_ => Color32::from_rgb(0x9C, 0x27, 0xB0),
};
ui.label(egui::RichText::new(*kind).color(color).strong());
if ui
- .link(egui::RichText::new(format!("{va:#x}")).monospace())
+ .link(egui::RichText::new(format!("{va:#x}")).monospace())
.clicked()
{
goto = Some(*va);
@@ -6559,15 +6522,15 @@ impl GhidrustApp {
ui.horizontal(|ui| {
ui.label(text);
let matching_kind = match *kind {
- "EOL" => Some(CommentKind::Eol),
- "Pre" => Some(CommentKind::Pre),
- "Post" => Some(CommentKind::Post),
- "Plate" => Some(CommentKind::Plate),
- "Repeatable" => Some(CommentKind::Repeatable),
+ "EOL" => Some(CommentKind::Eol),
+ "Pre" => Some(CommentKind::Pre),
+ "Post" => Some(CommentKind::Post),
+ "Plate" => Some(CommentKind::Plate),
+ "Repeatable" => Some(CommentKind::Repeatable),
_ => None,
};
if let Some(k) = matching_kind {
- if ui.small_button("Del").clicked() {
+ if ui.small_button("Del").clicked() {
delete = Some((*va, k));
}
}
@@ -6575,19 +6538,19 @@ impl GhidrustApp {
ui.end_row();
}
if let Some(va) = goto {
- let _ = self.goto_address_str(&format!("{va:#x}"));
+ let _ = self.goto_address_str(&format!("{va:#x}"));
}
if let Some((va, k)) = delete {
- let _ = self.set_comment_at(va, k, "");
+ let _ = self.set_comment_at(va, k, "");
}
});
});
}
fn ui_defined_data(&mut self, ui: &mut egui::Ui, muted: Color32) {
- ui.heading("Defined Data");
+ ui.heading("Defined Data");
ui.small(
- egui::RichText::new("Ghidra DataWindowPlugin · session data (Program::data_items when available)")
+ egui::RichText::new("DataWindowPlugin · session data (Program::data_items when available)")
.color(muted),
);
ui.separator();
@@ -6600,12 +6563,12 @@ impl GhidrustApp {
.filter_map(|c| c.type_info_va.map(|va| (va, c.name.clone())))
.collect(),
None => {
- ui.weak("No program loaded.");
+ ui.weak("No program loaded.");
return;
}
};
if self.strings.is_empty() && rtti_rows.is_empty() {
- ui.weak("No defined data (strings/RTTI) available yet — run ASCII Strings / RTTI analyzers.");
+ ui.weak("No defined data (strings/RTTI) available yet — run ASCII Strings / RTTI analyzers.");
return;
}
let str_rows: Vec<(u64, String)> = self
@@ -6616,65 +6579,65 @@ impl GhidrustApp {
.collect();
let mut goto: Option<u64> = None;
egui::ScrollArea::vertical()
- .id_salt("defined_data_scroll")
+ .id_salt("defined_data_scroll")
.max_height(400.0)
.show(ui, |ui| {
- egui::Grid::new("defined_data_grid")
+ egui::Grid::new("defined_data_grid")
.num_columns(3)
.striped(true)
.show(ui, |ui| {
- ui.strong("Address");
- ui.strong("Type");
- ui.strong("Preview");
+ ui.strong("Address");
+ ui.strong("Type");
+ ui.strong("Preview");
ui.end_row();
for (va, val) in &str_rows {
if ui
- .link(egui::RichText::new(format!("{va:#x}")).monospace())
+ .link(egui::RichText::new(format!("{va:#x}")).monospace())
.clicked()
{
goto = Some(*va);
}
- ui.monospace("string");
+ ui.monospace("string");
ui.label(val);
ui.end_row();
}
for (va, name) in &rtti_rows {
if ui
- .link(egui::RichText::new(format!("{va:#x}")).monospace())
+ .link(egui::RichText::new(format!("{va:#x}")).monospace())
.clicked()
{
goto = Some(*va);
}
- ui.monospace("rtti");
+ ui.monospace("rtti");
ui.label(name);
ui.end_row();
}
});
});
if let Some(va) = goto {
- let _ = self.goto_address_str(&format!("{va:#x}"));
+ let _ = self.goto_address_str(&format!("{va:#x}"));
}
}
- // ── 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,
- /// programmable offset override, and click-to-navigate address column.
+ /// ByteViewerPluginue — split hex / ASCII view of the
+ /// program's memory around the current cursor. Bytes-per-line combo,
+ /// programmable offset override, and click-to-navigate address column.
fn ui_bytes_pane(&mut self, ui: &mut egui::Ui, muted: Color32, primary: Color32) {
- ui.heading("Bytes");
+ ui.heading("Bytes");
ui.small(
egui::RichText::new(
- "Ghidra ByteViewerPlugin · split hex / ASCII, follows Listing cursor",
+ "ByteViewerPlugin · split hex / ASCII, follows Listing cursor",
)
.color(muted),
);
ui.separator();
let Some(prog) = self.program.as_ref() else {
- ui.weak("No program loaded.");
+ ui.weak("No program loaded.");
return;
};
- // Cursor tracking — default to Listing focus, editable via combo.
+ // Cursor tracking — default to Listing focus, editable via combo.
if self.bytes_pane_va.is_none() {
self.bytes_pane_va = self.listing_focus_va.or(prog.entry).or_else(|| {
prog.blocks.first().map(|b| b.va)
@@ -6682,31 +6645,31 @@ impl GhidrustApp {
}
let base_va = self.bytes_pane_va.unwrap_or(prog.image_base);
ui.horizontal(|ui| {
- ui.label("VA:");
- let mut input = format!("{base_va:#x}");
+ ui.label("VA:");
+ let mut input = format!("{base_va:#x}");
let resp = ui.add(egui::TextEdit::singleline(&mut input).desired_width(140.0));
if resp.lost_focus() {
if let Ok(v) = parse_address(&input) {
self.bytes_pane_va = Some(v);
}
}
- ui.label("Bytes/line:");
- egui::ComboBox::from_id_salt("bytes_pane_bpr")
- .selected_text(format!("{}", self.bytes_pane_bpr))
+ ui.label("Bytes/line:");
+ egui::ComboBox::from_id_salt("bytes_pane_bpr")
+ .selected_text(format!("{}", self.bytes_pane_bpr))
.show_ui(ui, |ui| {
for w in [8usize, 12, 16, 24, 32] {
- ui.selectable_value(&mut self.bytes_pane_bpr, w, format!("{w}"));
+ ui.selectable_value(&mut self.bytes_pane_bpr, w, format!("{w}"));
}
});
- ui.label("Rows:");
- egui::ComboBox::from_id_salt("bytes_pane_rows")
- .selected_text(format!("{}", self.bytes_pane_rows))
+ ui.label("Rows:");
+ egui::ComboBox::from_id_salt("bytes_pane_rows")
+ .selected_text(format!("{}", self.bytes_pane_rows))
.show_ui(ui, |ui| {
for r in [8usize, 16, 24, 32, 48, 64] {
- ui.selectable_value(&mut self.bytes_pane_rows, r, format!("{r}"));
+ ui.selectable_value(&mut self.bytes_pane_rows, r, format!("{r}"));
}
});
- if ui.button("Follow cursor").on_hover_text("Snap to Listing cursor").clicked() {
+ if ui.button("Follow cursor").on_hover_text("Snap to Listing cursor").clicked() {
self.bytes_pane_va = self.listing_focus_va;
}
});
@@ -6720,59 +6683,59 @@ impl GhidrustApp {
let focus_va = self.listing_focus_va;
let mut nav: Option<u64> = None;
egui::ScrollArea::vertical()
- .id_salt("bytes_scroll")
+ .id_salt("bytes_scroll")
.max_height(420.0)
.show(ui, |ui| {
for row in 0..self.bytes_pane_rows {
let row_va = base_va.wrapping_add((row * bpr) as u64);
ui.horizontal(|ui| {
- let addr = egui::RichText::new(format!("{row_va:016x}"))
+ let addr = egui::RichText::new(format!("{row_va:016x}"))
.monospace()
.color(if Some(row_va) == focus_va { primary } else { ui.visuals().text_color() });
- if ui.link(addr).on_hover_text("Go To in Listing").clicked() {
+ if ui.link(addr).on_hover_text("Go To in Listing").clicked() {
nav = Some(row_va);
}
- ui.label("│");
+ ui.label("│");
let mut hex_line = String::new();
let mut ascii_line = String::new();
for col in 0..bpr {
let idx = row * bpr + col;
match bytes.get(idx).and_then(|b| *b) {
Some(b) => {
- hex_line.push_str(&format!("{b:02x} "));
- let c = if (0x20..0x7f).contains(&b) { b as char } else { '.' };
+ hex_line.push_str(&format!("{b:02x} "));
+ let c = if (0x20..=0x7f).contains(&b) { b as char } else { '.' };
ascii_line.push(c);
}
None => {
- hex_line.push_str("?? ");
- ascii_line.push(' ');
+ hex_line.push_str("?? ");
+ ascii_line.push(' ');
}
}
}
ui.monospace(hex_line.trim_end());
- ui.label("│");
+ ui.label("│");
ui.monospace(ascii_line);
});
}
});
if let Some(va) = nav {
- let _ = self.goto_address_str(&format!("{va:#x}"));
+ let _ = self.goto_address_str(&format!("{va:#x}"));
}
}
- /// Ghidra `Symbol References` provider — a table of every xref pointing
- /// at the currently selected symbol (or the cursor VA).
+ /// `Symbol References` provider — a table of every xref pointing
+ /// at the currently selected symbol (or the cursor VA).
fn ui_symbol_references(&mut self, ui: &mut egui::Ui, muted: Color32) {
- ui.heading("Symbol References");
+ ui.heading("Symbol References");
ui.small(
egui::RichText::new(
- "Ghidra SymbolTablePlugin · every reference TO the current symbol",
+ "SymbolTablePlugin · every reference TO the current symbol",
)
.color(muted),
);
ui.separator();
let Some(prog) = self.program.as_ref() else {
- ui.weak("No program loaded.");
+ ui.weak("No program loaded.");
return;
};
let target = self
@@ -6780,31 +6743,31 @@ impl GhidrustApp {
.or(self.listing_focus_va)
.or(prog.entry);
ui.horizontal(|ui| {
- let mut input = target.map(|v| format!("{v:#x}")).unwrap_or_default();
- ui.label("Target:");
+ let mut input = target.map(|v| format!("{v:#x}")).unwrap_or_default();
+ ui.label("Target:");
let resp = ui.add(
egui::TextEdit::singleline(&mut input)
.desired_width(140.0)
- .hint_text("VA…"),
+ .hint_text("VA…"),
);
if resp.lost_focus() {
self.symbol_refs_target = parse_address(&input).ok();
}
- ui.label("Filter:");
+ ui.label("Filter:");
ui.add(
egui::TextEdit::singleline(&mut self.symbol_refs_filter)
.desired_width(200.0)
- .hint_text("Substring…"),
+ .hint_text("Substring…"),
);
- if ui.button("Use cursor").clicked() {
+ if ui.button("Use cursor").clicked() {
self.symbol_refs_target = self.listing_focus_va;
}
- ui.checkbox(&mut self.symbol_refs_hide_stubs, "Hide resolve stubs")
- .on_hover_text("ghidrust_il2cpp::is_resolve_stub_va — hide IL2CPP lazy resolve thunks");
+ ui.checkbox(&mut self.symbol_refs_hide_stubs, "Hide resolve stubs")
+ .on_hover_text("ghidrust_il2cpp::is_resolve_stub_va — hide IL2CPP lazy resolve thunks");
});
ui.separator();
let Some(target) = target else {
- ui.weak("No target — set cursor or type a VA above.");
+ ui.weak("No target — set cursor or type a VA above.");
return;
};
let refs = self.xrefs_to_va(target);
@@ -6814,8 +6777,8 @@ impl GhidrustApp {
ghidrust_il2cpp::classify_at(prog, va).map(|stub| {
stub.icall_name
.clone()
- .map(|n| format!("il2cpp_stub: {n}"))
- .unwrap_or_else(|| "il2cpp_stub".into())
+ .map(|n| format!("il2cpp_stub: {n}"))
+ .unwrap_or_else(|| "il2cpp_stub".into())
})
};
let prog_ref = self.program.as_ref();
@@ -6826,7 +6789,7 @@ impl GhidrustApp {
return true;
}
r.preview.to_ascii_lowercase().contains(&q)
- || format!("{:#x}", r.from).contains(&q)
+ || format!("{:#x}", r.from).contains(&q)
|| r.kind.contains(&q)
})
.filter_map(|r| {
@@ -6849,65 +6812,65 @@ impl GhidrustApp {
.map(|s| s.to_string())
.unwrap_or_default()
};
- ui.small(format!("{} reference(s) to {target:#x} · {}", rows.len(), label_at(target)));
+ ui.small(format!("{} reference(s) to {target:#x} · {}", rows.len(), label_at(target)));
let mut goto: Option<u64> = None;
egui::ScrollArea::vertical()
- .id_salt("symrefs_scroll")
+ .id_salt("symrefs_scroll")
.max_height(400.0)
.show(ui, |ui| {
- egui::Grid::new("symbol_refs_grid")
+ egui::Grid::new("symbol_refs_grid")
.num_columns(5)
.striped(true)
.show(ui, |ui| {
- ui.strong("From");
- ui.strong("Label");
- ui.strong("Kind");
- ui.strong("Classify");
- ui.strong("Preview");
+ ui.strong("From");
+ ui.strong("Label");
+ ui.strong("Kind");
+ ui.strong("Classify");
+ ui.strong("Preview");
ui.end_row();
for (r, cls) in &rows {
if ui
- .link(egui::RichText::new(format!("{:#x}", r.from)).monospace())
+ .link(egui::RichText::new(format!("{:#x}", r.from)).monospace())
.clicked()
{
goto = Some(r.from);
}
ui.label(label_at(r.from));
ui.monospace(r.kind);
- ui.small(cls.as_deref().unwrap_or("—"));
+ ui.small(cls.as_deref().unwrap_or("—"));
ui.label(&r.preview);
ui.end_row();
}
});
});
if let Some(va) = goto {
- let _ = self.goto_address_str(&format!("{va:#x}"));
+ let _ = self.goto_address_str(&format!("{va:#x}"));
}
}
- /// Ghidra `EquateTablePlugin` — two-pane: equate groups + per-equate refs.
+ /// `EquateTablePlugin` — two-pane: equate groups + per-equate refs.
fn ui_equates_table(&mut self, ui: &mut egui::Ui, muted: Color32) {
- ui.heading("Equates Table");
+ ui.heading("Equates Table");
ui.small(
egui::RichText::new(
- "Ghidra EquateTablePlugin · symbolic names bound to scalar operands",
+ "EquateTablePlugin · symbolic names bound to scalar operands",
)
.color(muted),
);
ui.separator();
let Some(prog) = self.program.as_ref() else {
- ui.weak("No program loaded.");
+ ui.weak("No program loaded.");
return;
};
let groups = prog.edits.equate_groups();
ui.horizontal(|ui| {
- ui.label("Filter:");
+ ui.label("Filter:");
ui.add(
egui::TextEdit::singleline(&mut self.equates_filter)
.desired_width(220.0)
- .hint_text("Name / value…"),
+ .hint_text("Name / value…"),
);
- if ui.button("Add equate at cursor…").clicked() {
+ if ui.button("Add equate at cursor…").clicked() {
self.equate_dialog_va = self.listing_focus_va;
self.equate_dialog_op = 1;
self.equate_dialog_name.clear();
@@ -6923,29 +6886,29 @@ impl GhidrustApp {
if q.is_empty() {
return true;
}
- name.to_ascii_lowercase().contains(&q) || format!("{val:#x}").contains(&q)
+ name.to_ascii_lowercase().contains(&q) || format!("{val:#x}").contains(&q)
})
.collect();
if filtered.is_empty() {
- ui.weak("No equates — use \"Add equate at cursor\" over a scalar operand.");
+ ui.weak("No equates — use \"Add equate at cursor\" over a scalar operand.");
return;
}
let mut clear: Option<(u64, u8)> = None;
let mut goto: Option<u64> = None;
ui.columns(2, |cols| {
- cols[0].strong("Equate");
+ cols[0].strong("Equate");
cols[0].separator();
egui::ScrollArea::vertical()
- .id_salt("equates_left_scroll")
+ .id_salt("equates_left_scroll")
.max_height(360.0)
.show(&mut cols[0], |ui| {
- egui::Grid::new("equates_groups_grid")
+ egui::Grid::new("equates_groups_grid")
.num_columns(3)
.striped(true)
.show(ui, |ui| {
- ui.strong("Name");
- ui.strong("Value");
- ui.strong("# Refs");
+ ui.strong("Name");
+ ui.strong("Value");
+ ui.strong("# Refs");
ui.end_row();
for (name, value, n) in &filtered {
let is_sel = self
@@ -6961,13 +6924,13 @@ impl GhidrustApp {
if ui.selectable_label(is_sel, text).clicked() {
self.equates_selected = Some((name.clone(), *value));
}
- ui.monospace(format!("{value:#x}"));
- ui.monospace(format!("{n}"));
+ ui.monospace(format!("{value:#x}"));
+ ui.monospace(format!("{n}"));
ui.end_row();
}
});
});
- cols[1].strong("References");
+ cols[1].strong("References");
cols[1].separator();
let sel = self.equates_selected.clone();
let refs: Vec<(u64, u8, i64)> = match sel {
@@ -6975,31 +6938,31 @@ impl GhidrustApp {
None => Vec::new(),
};
egui::ScrollArea::vertical()
- .id_salt("equates_right_scroll")
+ .id_salt("equates_right_scroll")
.max_height(360.0)
.show(&mut cols[1], |ui| {
if refs.is_empty() {
- ui.weak("Select an equate on the left to see its references.");
+ ui.weak("Select an equate on the left to see its references.");
} else {
- egui::Grid::new("equate_refs_grid")
+ egui::Grid::new("equate_refs_grid")
.num_columns(4)
.striped(true)
.show(ui, |ui| {
- ui.strong("Ref Addr");
- ui.strong("Op");
- ui.strong("Value");
- ui.strong("Del");
+ ui.strong("Ref Addr");
+ ui.strong("Op");
+ ui.strong("Value");
+ ui.strong("Del");
ui.end_row();
for (va, op, value) in refs {
if ui
- .link(egui::RichText::new(format!("{va:#x}")).monospace())
+ .link(egui::RichText::new(format!("{va:#x}")).monospace())
.clicked()
{
goto = Some(va);
}
- ui.monospace(format!("{op}"));
- ui.monospace(format!("{value:#x}"));
- if ui.small_button("Del").clicked() {
+ ui.monospace(format!("{op}"));
+ ui.monospace(format!("{value:#x}"));
+ if ui.small_button("Del").clicked() {
clear = Some((va, op));
}
ui.end_row();
@@ -7009,26 +6972,26 @@ impl GhidrustApp {
});
});
if let Some(va) = goto {
- let _ = self.goto_address_str(&format!("{va:#x}"));
+ let _ = self.goto_address_str(&format!("{va:#x}"));
}
if let Some((va, op)) = clear {
- let _ = self.set_equate(va, op, "", 0);
+ let _ = self.set_equate(va, op, "", 0);
}
}
- /// Ghidra `FunctionTagPlugin` — two-pane: assigned tags for current fn,
- /// All Tags with counts.
+ /// `FunctionTagPlugin` — two-pane: assigned tags for current fn,
+ /// All Tags with counts.
fn ui_function_tags(&mut self, ui: &mut egui::Ui, muted: Color32) {
- ui.heading("Function Tags");
+ ui.heading("Function Tags");
ui.small(
egui::RichText::new(
- "Ghidra FunctionTagPlugin · per-function labels + universe of tags",
+ "FunctionTagPlugin · per-function labels + universe of tags",
)
.color(muted),
);
ui.separator();
let Some(prog) = self.program.as_ref() else {
- ui.weak("No program loaded.");
+ ui.weak("No program loaded.");
return;
};
let entry = self.focused_function_entry.or_else(|| {
@@ -7037,16 +7000,16 @@ impl GhidrustApp {
});
let entry_label = entry
.and_then(|va| self.program.as_ref()?.display_function_name_at(va))
- .unwrap_or_else(|| "<no function>".into());
+ .unwrap_or_else(|| "<no function>".into());
ui.horizontal(|ui| {
- ui.label("Function:");
+ ui.label("Function:");
ui.monospace(&entry_label);
if let Some(e) = entry {
- ui.monospace(format!("@ {e:#x}"));
+ ui.monospace(format!("@ {e:#x}"));
}
});
ui.separator();
- // Left = assigned tags (with remove); right = all tags (add / delete).
+ // Left = assigned tags (with remove); right = all tags (add / delete).
let assigned: Vec<String> = entry
.map(|e| prog.edits.function_tags_for(e))
.unwrap_or_default();
@@ -7055,31 +7018,31 @@ impl GhidrustApp {
let mut add_to_entry: Option<String> = None;
let mut delete_globally: Option<String> = None;
ui.columns(2, |cols| {
- cols[0].strong("Assigned to this function");
+ cols[0].strong("Assigned to this function");
cols[0].separator();
if assigned.is_empty() {
- cols[0].weak("No tags — add one from the right pane, or type a new tag.");
+ cols[0].weak("No tags — add one from the right pane, or type a new tag.");
} else {
for t in &assigned {
cols[0].horizontal(|ui| {
ui.monospace(t);
- if ui.small_button("Remove").clicked() {
+ if ui.small_button("Remove").clicked() {
remove_from_entry = Some(t.clone());
}
});
}
}
- cols[1].strong("All Tags");
+ cols[1].strong("All Tags");
cols[1].separator();
cols[1].horizontal(|ui| {
- ui.label("New:");
+ ui.label("New:");
ui.add(
egui::TextEdit::singleline(&mut self.function_tags_new_input)
.desired_width(160.0)
- .hint_text("Tag name…"),
+ .hint_text("Tag name…"),
);
- if ui.button("Add").clicked() {
+ if ui.button("Add").clicked() {
let name = self.function_tags_new_input.trim().to_string();
if !name.is_empty() {
if entry.is_some() {
@@ -7092,38 +7055,38 @@ impl GhidrustApp {
}
});
cols[1].horizontal(|ui| {
- ui.label("Filter:");
+ ui.label("Filter:");
ui.add(
egui::TextEdit::singleline(&mut self.function_tags_filter)
.desired_width(180.0)
- .hint_text("Substring…"),
+ .hint_text("Substring…"),
);
});
cols[1].separator();
let q = self.function_tags_filter.to_ascii_lowercase();
egui::ScrollArea::vertical()
- .id_salt("all_tags_scroll")
+ .id_salt("all_tags_scroll")
.max_height(320.0)
.show(&mut cols[1], |ui| {
- egui::Grid::new("all_tags_grid")
+ egui::Grid::new("all_tags_grid")
.num_columns(3)
.striped(true)
.show(ui, |ui| {
- ui.strong("Tag");
- ui.strong("Uses");
- ui.strong("Actions");
+ ui.strong("Tag");
+ ui.strong("Uses");
+ ui.strong("Actions");
ui.end_row();
for (tag, n) in &all_tags {
if !q.is_empty() && !tag.to_ascii_lowercase().contains(&q) {
continue;
}
ui.monospace(tag);
- ui.monospace(format!("{n}"));
+ ui.monospace(format!("{n}"));
ui.horizontal(|ui| {
- if entry.is_some() && ui.small_button("Add").clicked() {
+ if entry.is_some() && ui.small_button("Add").clicked() {
add_to_entry = Some(tag.clone());
}
- if ui.small_button("Delete").clicked() {
+ if ui.small_button("Delete").clicked() {
delete_globally = Some(tag.clone());
}
});
@@ -7143,29 +7106,29 @@ impl GhidrustApp {
}
}
- /// Ghidra `ReferencesPlugin` — External Programs table. Rendered from
- /// analyzer-driven `imports_exports()` output (PDB symbols, `idata`
- /// sections, demangled `dllexport` symbols) — never fabricated.
+ /// `ReferencesPlugin` — External Programs table. Rendered from
+ /// analyzer-driven `imports_exports` output (PDB symbols, `idata`
+ /// sections, demangled `dllexport` symbols) — never fabricated.
fn ui_external_programs(&mut self, ui: &mut egui::Ui, muted: Color32) {
- ui.heading("External Programs");
+ ui.heading("External Programs");
ui.small(
egui::RichText::new(
- "Ghidra ReferencesPlugin · analyzer-derived imports + exports",
+ "ReferencesPlugin · analyzer-derived imports + exports",
)
.color(muted),
);
ui.separator();
if self.program.is_none() {
- ui.weak("No program loaded.");
+ ui.weak("No program loaded.");
return;
}
let (imports, exports) = self.imports_exports();
ui.horizontal(|ui| {
- ui.label("Filter:");
+ ui.label("Filter:");
ui.add(
egui::TextEdit::singleline(&mut self.external_programs_filter)
.desired_width(220.0)
- .hint_text("Name / VA…"),
+ .hint_text("Name / VA…"),
);
});
ui.separator();
@@ -7174,94 +7137,94 @@ impl GhidrustApp {
if q.is_empty() {
return true;
}
- name.to_ascii_lowercase().contains(&q) || format!("{va:#x}").contains(&q)
+ name.to_ascii_lowercase().contains(&q) || format!("{va:#x}").contains(&q)
};
let mut goto: Option<u64> = None;
egui::ScrollArea::vertical()
- .id_salt("ext_progs_scroll")
+ .id_salt("ext_progs_scroll")
.max_height(400.0)
.show(ui, |ui| {
- ui.strong("Imports");
- egui::Grid::new("ext_imports_grid")
+ ui.strong("Imports");
+ egui::Grid::new("ext_imports_grid")
.num_columns(3)
.striped(true)
.show(ui, |ui| {
- ui.strong("Address");
- ui.strong("Name");
- ui.strong("Source");
+ ui.strong("Address");
+ ui.strong("Name");
+ ui.strong("Source");
ui.end_row();
for (va, name) in imports.iter().filter(|(va, n)| matches(n, *va)) {
if ui
- .link(egui::RichText::new(format!("{va:#x}")).monospace())
+ .link(egui::RichText::new(format!("{va:#x}")).monospace())
.clicked()
{
goto = Some(*va);
}
ui.label(name);
- ui.monospace(if name.starts_with('.') { "section" } else { "pdb" });
+ ui.monospace(if name.starts_with('.') { "section" } else { "pdb" });
ui.end_row();
}
});
ui.add_space(8.0);
- ui.strong("Exports");
- egui::Grid::new("ext_exports_grid")
+ ui.strong("Exports");
+ egui::Grid::new("ext_exports_grid")
.num_columns(3)
.striped(true)
.show(ui, |ui| {
- ui.strong("Address");
- ui.strong("Name");
- ui.strong("Source");
+ ui.strong("Address");
+ ui.strong("Name");
+ ui.strong("Source");
ui.end_row();
for (va, name) in exports.iter().filter(|(va, n)| matches(n, *va)) {
if ui
- .link(egui::RichText::new(format!("{va:#x}")).monospace())
+ .link(egui::RichText::new(format!("{va:#x}")).monospace())
.clicked()
{
goto = Some(*va);
}
ui.label(name);
- ui.monospace(if name.starts_with('.') { "section" } else { "demangle" });
+ ui.monospace(if name.starts_with('.') { "section" } else { "demangle" });
ui.end_row();
}
if imports.is_empty() && exports.is_empty() {
- ui.weak("No imports/exports — analyzer did not populate any.");
+ ui.weak("No imports/exports — analyzer did not populate any.");
ui.end_row();
}
});
});
if let Some(va) = goto {
- let _ = self.goto_address_str(&format!("{va:#x}"));
+ let _ = self.goto_address_str(&format!("{va:#x}"));
}
}
- /// Ghidra `DataTypePreviewPlugin` — preview interpretation of bytes at
- /// the current cursor under the chosen built-in type.
+ /// `DataTypePreviewPlugin` — preview interpretation of bytes at
+ /// the current cursor under the chosen built-in type.
fn ui_data_type_preview(&mut self, ui: &mut egui::Ui, muted: Color32) {
- ui.heading("Data Type Preview");
+ ui.heading("Data Type Preview");
ui.small(
egui::RichText::new(
- "Ghidra DataTypePreviewPlugin · byte interpretation @ cursor",
+ "DataTypePreviewPlugin · byte interpretation @ cursor",
)
.color(muted),
);
ui.separator();
let Some(prog) = self.program.as_ref() else {
- ui.weak("No program loaded.");
+ ui.weak("No program loaded.");
return;
};
let va = match self.listing_focus_va.or(prog.entry) {
Some(v) => v,
None => {
- ui.weak("No cursor / entry.");
+ ui.weak("No cursor / entry.");
return;
}
};
ui.horizontal(|ui| {
- ui.label("Cursor VA:");
- ui.monospace(format!("{va:#x}"));
- ui.label("Type:");
+ ui.label("Cursor VA:");
+ ui.monospace(format!("{va:#x}"));
+ ui.label("Type:");
let sel = self.data_type_preview_selected.clone();
- egui::ComboBox::from_id_salt("dtp_type_combo")
+ egui::ComboBox::from_id_salt("dtp_type_combo")
.selected_text(&sel)
.show_ui(ui, |ui| {
for name in BUILTIN_TYPES {
@@ -7276,12 +7239,12 @@ impl GhidrustApp {
});
ui.separator();
let bytes = prog.read_va(va, 16).unwrap_or_default();
- let hex: String = bytes.iter().map(|b| format!("{b:02x} ")).collect();
- ui.monospace(format!("bytes: {}", hex.trim_end()));
+ let hex: String = bytes.iter().map(|b| format!("{b:02x} ")).collect();
+ ui.monospace(format!("bytes: {}", hex.trim_end()));
ui.separator();
- egui::Grid::new("dtp_grid").num_columns(2).striped(true).show(ui, |ui| {
- ui.strong("Interpretation");
- ui.strong("Preview");
+ egui::Grid::new("dtp_grid").num_columns(2).striped(true).show(ui, |ui| {
+ ui.strong("Interpretation");
+ ui.strong("Preview");
ui.end_row();
for (name, preview) in preview_all(&bytes) {
ui.monospace(name);
@@ -7291,13 +7254,13 @@ impl GhidrustApp {
});
}
- /// Ghidra `ComputeChecksumsPlugin` — CRC-32 / Adler-32 / Fletcher / raw
- /// sum panels over the loaded image or a chosen block.
+ /// `ComputeChecksumsPlugin` — CRC-32 / Adler-32 / Fletcher / raw
+ /// sum panels over the loaded image or a chosen block.
fn ui_checksum_generator(&mut self, ui: &mut egui::Ui, muted: Color32) {
- ui.heading("Checksum Generator");
+ ui.heading("Checksum Generator");
ui.small(
egui::RichText::new(
- "Ghidra ComputeChecksumsPlugin · CRC-32 / Adler-32 / Fletcher / sums",
+ "ComputeChecksumsPlugin · CRC-32 / Adler-32 / Fletcher / sums",
)
.color(muted),
);
@@ -7309,10 +7272,10 @@ impl GhidrustApp {
.unwrap_or_default();
let mut run: Option<ChecksumMode> = None;
ui.horizontal(|ui| {
- if ui.button("Whole image").clicked() {
+ if ui.button("Whole image").clicked() {
run = Some(ChecksumMode::WholeImage);
}
- ui.label(egui::RichText::new("or block:").color(muted));
+ ui.label(egui::RichText::new("or block:").color(muted));
for name in &block_names {
if ui.small_button(name).clicked() {
run = Some(ChecksumMode::Section(name.clone()));
@@ -7325,36 +7288,36 @@ impl GhidrustApp {
ui.separator();
match &self.checksum_last {
None => {
- ui.weak("No checksum computed yet — click Whole image or a block above.");
+ ui.weak("No checksum computed yet — click Whole image or a block above.");
}
Some(r) => {
- egui::Grid::new("checksum_grid").num_columns(2).striped(true).show(ui, |ui| {
- ui.strong("Target");
+ egui::Grid::new("checksum_grid").num_columns(2).striped(true).show(ui, |ui| {
+ ui.strong("Target");
ui.label(&r.target);
ui.end_row();
- ui.strong("Length");
- ui.monospace(format!("{}", r.len));
+ ui.strong("Length");
+ ui.monospace(format!("{}", r.len));
ui.end_row();
- ui.strong("CRC-32 (IEEE)");
- ui.monospace(format!("{:#010x}", r.crc32));
+ ui.strong("CRC-32 (IEEE)");
+ ui.monospace(format!("{:#010x}", r.crc32));
ui.end_row();
- ui.strong("Adler-32");
- ui.monospace(format!("{:#010x}", r.adler32));
+ ui.strong("Adler-32");
+ ui.monospace(format!("{:#010x}", r.adler32));
ui.end_row();
- ui.strong("Sum-8");
- ui.monospace(format!("{:#x}", r.sum8));
+ ui.strong("Sum-8");
+ ui.monospace(format!("{:#x}", r.sum8));
ui.end_row();
- ui.strong("Sum-16");
- ui.monospace(format!("{:#x}", r.sum16));
+ ui.strong("Sum-16");
+ ui.monospace(format!("{:#x}", r.sum16));
ui.end_row();
- ui.strong("Sum-32");
- ui.monospace(format!("{:#x}", r.sum32));
+ ui.strong("Sum-32");
+ ui.monospace(format!("{:#x}", r.sum32));
ui.end_row();
- ui.strong("Fletcher-16");
- ui.monospace(format!("{:#010x}", r.fletcher16));
+ ui.strong("Fletcher-16");
+ ui.monospace(format!("{:#010x}", r.fletcher16));
ui.end_row();
- ui.strong("Fletcher-32");
- ui.monospace(format!("{:#018x}", r.fletcher32));
+ ui.strong("Fletcher-32");
+ ui.monospace(format!("{:#018x}", r.fletcher32));
ui.end_row();
});
}
@@ -7366,35 +7329,35 @@ impl GhidrustApp {
fn preview_all(bytes: &[u8]) -> Vec<(&'static str, String)> {
let mut out = Vec::new();
if let Some(&b) = bytes.first() {
- out.push(("int8", format!("{}", b as i8)));
- out.push(("uint8", format!("{}", b)));
+ out.push(("int8", format!("{}", b as i8)));
+ out.push(("uint8", format!("{}", b)));
}
if bytes.len() >= 2 {
let w = u16::from_le_bytes([bytes[0], bytes[1]]);
- out.push(("int16", format!("{}", w as i16)));
- out.push(("uint16", format!("{w} ({w:#x})")));
+ out.push(("int16", format!("{}", w as i16)));
+ out.push(("uint16", format!("{w} ({w:#x})")));
}
if bytes.len() >= 4 {
let d = u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]);
- out.push(("int32", format!("{}", d as i32)));
- out.push(("uint32", format!("{d} ({d:#x})")));
- out.push(("float", format!("{}", f32::from_bits(d))));
+ out.push(("int32", format!("{}", d as i32)));
+ out.push(("uint32", format!("{d} ({d:#x})")));
+ out.push(("float", format!("{}", f32::from_bits(d))));
}
if bytes.len() >= 8 {
let q = u64::from_le_bytes([
bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7],
]);
- out.push(("int64", format!("{}", q as i64)));
- out.push(("uint64", format!("{q} ({q:#x})")));
- out.push(("double", format!("{}", f64::from_bits(q))));
- out.push(("pointer64", format!("{q:#018x}")));
+ out.push(("int64", format!("{}", q as i64)));
+ out.push(("uint64", format!("{q} ({q:#x})")));
+ out.push(("double", format!("{}", f64::from_bits(q))));
+ out.push(("pointer64", format!("{q:#018x}")));
}
let ascii: String = bytes
.iter()
.take(16)
- .map(|b| if (0x20..0x7f).contains(b) { *b as char } else { '.' })
+ .map(|b| if (0x20..=0x7f).contains(b) { *b as char } else { '.' })
.collect();
- out.push(("ascii", ascii));
+ out.push(("ascii", ascii));
out
}
@@ -7402,19 +7365,19 @@ impl eframe::App for GhidrustApp {
fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
self.apply_theme(ctx);
- // 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
+ // Startup: choose project before the empty shell
if self.show_startup_picker {
self.ui_startup_picker(ctx);
return;
}
- // Poll background analysis worker; keep repainting so progress UI stays live.
+ // Poll background analysis worker; keep repainting so progress UI stays live.
if self.analysis_job.is_some() {
if let Err(e) = self.step_analysis_job() {
- self.status = format!("error: {e}");
+ self.status = format!("error: {e}");
self.log(self.status.clone());
self.analysis_job = None;
set_preferred_bulk_mode(BulkScanMode::ParallelCpu);
@@ -7422,130 +7385,130 @@ impl eframe::App for GhidrustApp {
ctx.request_repaint();
}
- egui::TopBottomPanel::top("menubar").show(ctx, |ui| {
+ egui::TopBottomPanel::top("menubar").show(ctx, |ui| {
egui::menu::bar(ui, |ui| {
- ui.menu_button("File", |ui| {
- if ui.button("New Project…").clicked() {
+ ui.menu_button("File", |ui| {
+ if ui.button("New Project…").clicked() {
self.browse_and_create_project();
ui.close_menu();
}
- if ui.button("Open Project…").clicked() {
+ if ui.button("Open Project…").clicked() {
self.browse_and_open_project();
ui.close_menu();
}
ui.separator();
- if ui.button("Import binary into project…").clicked() {
+ if ui.button("Import binary into project…").clicked() {
self.browse_and_import();
ui.close_menu();
}
- if ui.button("Open / Load binary…").clicked() {
+ if ui.button("Open / Load binary…").clicked() {
self.browse_and_load_binary();
ui.close_menu();
}
- if ui.button("Add To Program…").on_hover_text("Not yet implemented").clicked() {
- self.nyi("File → Add To Program");
+ 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").clicked() {
- self.nyi("File → Batch Import");
+ if ui.button("Batch Import…").on_hover_text("Not yet implemented").clicked() {
+ self.nyi("File → Batch Import");
ui.close_menu();
}
ui.separator();
- if ui.button("Save analysis results…").clicked() {
+ if ui.button("Save analysis results…").clicked() {
if let Err(e) = self.save_results() {
- self.status = format!("error: {e}");
+ self.status = format!("error: {e}");
self.log(self.status.clone());
}
ui.close_menu();
}
- if ui.button("Save As…").on_hover_text("Not yet implemented").clicked() {
- self.nyi("File → Save As");
+ 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").clicked() {
- self.nyi("File → Export Program");
+ if ui.button("Export Program…").on_hover_text("Not yet implemented").clicked() {
+ self.nyi("File → Export Program");
ui.close_menu();
}
ui.separator();
- if ui.button("Load PDB File…").on_hover_text("Not yet implemented — backend P8").clicked() {
- self.nyi("File → Load PDB File");
+ if ui.button("Load PDB File…").on_hover_text("Not yet implemented — PDB load UI").clicked() {
+ self.nyi("File → Load PDB File");
ui.close_menu();
}
- if ui.button("Parse C Source…").on_hover_text("Not yet implemented").clicked() {
- self.nyi("File → Parse C Source");
+ 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 — not yet implemented").clicked() {
- self.nyi("File → Configure");
+ 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").clicked() {
- self.nyi("File → Print");
+ if ui.button("Print…").on_hover_text("Not yet implemented").clicked() {
+ self.nyi("File → Print");
ui.close_menu();
}
ui.separator();
- if ui.button("Close program").clicked() {
+ if ui.button("Close program").clicked() {
self.program = None;
self.listing.clear();
self.active_file_id = None;
- self.status = "Program closed".into();
+ self.status = "Program closed".into();
ui.close_menu();
}
- if ui.button("Exit").clicked() {
+ if ui.button("Exit").clicked() {
ctx.send_viewport_cmd(egui::ViewportCommand::Close);
}
});
- ui.menu_button("Edit", |ui| {
- if ui.button("Undo").clicked() {
+ ui.menu_button("Edit", |ui| {
+ if ui.button("Undo").clicked() {
self.edit_undo();
ui.close_menu();
}
- if ui.button("Redo").clicked() {
+ if ui.button("Redo").clicked() {
self.edit_redo();
ui.close_menu();
}
- if ui.button("Clear selection").clicked() {
+ if ui.button("Clear selection").clicked() {
self.edit_clear_selection();
ui.close_menu();
}
ui.separator();
- if ui.button("Tool Options…").on_hover_text("Options tree — not yet implemented").clicked() {
- self.nyi("Edit → Tool Options");
+ 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 — not yet implemented").clicked() {
- self.nyi("Edit → Options for program");
+ 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 — not yet implemented").clicked() {
- self.nyi("Edit → Plugin Path");
+ 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 — not yet implemented").clicked() {
- self.nyi("Edit → Key Bindings");
+ if ui.button("Key Bindings…").on_hover_text("Rebind actions — not yet implemented").clicked() {
+ self.nyi("Edit → Key Bindings");
ui.close_menu();
}
});
- ui.menu_button("Analysis", |ui| {
- if ui.button("Auto Analyze…").clicked() {
+ ui.menu_button("Analysis", |ui| {
+ if ui.button("Auto Analyze…").clicked() {
self.pending_analyze_file_id = None;
self.show_analysis_dialog = true;
ui.close_menu();
}
- if ui.button("Run selected analyzers").clicked() {
+ if ui.button("Run selected analyzers").clicked() {
self.pending_analyze_file_id = None;
self.show_analysis_dialog = true;
ui.close_menu();
}
- if ui.button("Analyze All Open…").on_hover_text("Multi-program batch — not yet implemented").clicked() {
- self.nyi("Analysis → Analyze All Open");
+ 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();
}
ui.separator();
- ui.menu_button("One Shot Analysis", |ui| {
- // Enumerate analyzers as sub-menu items (mirrors Ghidra's One-Shot).
- // Clicking pre-selects that analyzer and opens the dialog.
+ ui.menu_button("One Shot Analysis", |ui| {
+ // Enumerate analyzers as sub-menu items (mirrors One-Shot).
+ // Clicking pre-selects that analyzer and opens the dialog.
let analyzer_names: Vec<String> = self
.analyzer_infos
.iter()
@@ -7563,105 +7526,105 @@ impl eframe::App for GhidrustApp {
}
self.pending_analyze_file_id = None;
self.show_analysis_dialog = true;
- self.status = format!("One Shot: {name}");
+ self.status = format!("One Shot: {name}");
self.log(self.status.clone());
ui.close_menu();
}
});
ui.separator();
if ui
- .button("GPU Decompile…")
+ .button("GPU Decompile…")
.on_hover_text(
- "ghidrust_decomp::gpu_decompile_to_file · GPU pipeline with CPU multipass fallback",
+ "ghidrust_decomp::gpu_decompile_to_file · GPU pipeline with CPU multipass fallback",
)
.clicked()
{
if self.tool_panes.gpu_decompile.addr_input.trim().is_empty() {
if let Some(prog) = &self.program {
if let Some(e) = self.listing_focus_va.or(prog.entry) {
- self.tool_panes.gpu_decompile.addr_input = format!("{e:#x}");
+ self.tool_panes.gpu_decompile.addr_input = format!("{e:#x}");
}
}
}
if self.tool_panes.gpu_decompile.max_bytes_input.trim().is_empty() {
- self.tool_panes.gpu_decompile.max_bytes_input = "256".into();
+ self.tool_panes.gpu_decompile.max_bytes_input = "256".into();
}
self.show_gpu_decompile_dialog = true;
ui.close_menu();
}
});
- ui.menu_button("Navigation", |ui| {
- if ui.add_enabled(self.can_nav_back(), egui::Button::new("Back")).clicked() {
+ ui.menu_button("Navigation", |ui| {
+ if ui.add_enabled(self.can_nav_back(), egui::Button::new("Back")).clicked() {
self.nav_back();
ui.close_menu();
}
- if ui.add_enabled(self.can_nav_forward(), egui::Button::new("Forward")).clicked() {
+ if ui.add_enabled(self.can_nav_forward(), egui::Button::new("Forward")).clicked() {
self.nav_forward();
ui.close_menu();
}
ui.separator();
- if ui.button("Go to entry").clicked() {
+ if ui.button("Go to entry").clicked() {
self.goto_entry();
ui.close_menu();
}
- if ui.button("Go to address…").clicked() {
+ if ui.button("Go to address…").clicked() {
if let Some(prog) = &self.program {
if let Some(e) = prog.entry {
- self.goto_input = format!("{e:#x}");
+ self.goto_input = format!("{e:#x}");
} else {
- self.goto_input = format!("{:#x}", prog.image_base);
+ self.goto_input = format!("{:#x}", prog.image_base);
}
}
self.show_goto_dialog = true;
ui.close_menu();
}
ui.separator();
- if ui.button("Next Function (Ctrl+Down)").clicked() {
+ if ui.button("Next Function (Ctrl+Down)").clicked() {
self.nav_next_function();
ui.close_menu();
}
- if ui.button("Previous Function (Ctrl+Up)").clicked() {
+ if ui.button("Previous Function (Ctrl+Up)").clicked() {
self.nav_prev_function();
ui.close_menu();
}
- if ui.button("Next Data").on_hover_text("Not yet implemented").clicked() {
- self.nyi("Navigation → Next Data");
+ 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").clicked() {
- self.nyi("Navigation → Next Undefined");
+ if ui.button("Next Undefined").on_hover_text("Not yet implemented").clicked() {
+ self.nyi("Navigation → Next Undefined");
ui.close_menu();
}
- if ui.button("Next Bookmark").clicked() {
+ if ui.button("Next Bookmark").clicked() {
self.nav_next_bookmark();
ui.close_menu();
}
- if ui.button("Previous Bookmark").clicked() {
+ if ui.button("Previous Bookmark").clicked() {
self.nav_prev_bookmark();
ui.close_menu();
}
});
- ui.menu_button("Search", |ui| {
- if ui.button("Search memory…").clicked() {
+ ui.menu_button("Search", |ui| {
+ if ui.button("Search memory…").clicked() {
self.show_search_memory_dialog = true;
ui.close_menu();
}
- if ui.button("Search program text…").clicked() {
+ if ui.button("Search program text…").clicked() {
self.show_search_text_dialog = true;
ui.close_menu();
}
ui.separator();
- if ui.button("For Strings…").on_hover_text("Opens Defined Strings — session strings").clicked() {
+ if ui.button("For Strings…").on_hover_text("Opens Defined Strings — session strings").clicked() {
self.pane_open.insert(PaneKind::DefinedStrings, true);
ui.close_menu();
}
- if ui.button("For Scalars…").on_hover_text("Ghidra ScalarSearchPlugin · operand scalar range filter").clicked() {
+ if ui.button("For Scalars…").on_hover_text("ScalarSearchPlugin · operand scalar range filter").clicked() {
self.show_search_scalars_dialog = true;
ui.close_menu();
}
- if ui.button("For Address Tables…").on_hover_text("Ghidra AutoTableDisassemblerPlugin · pointer table candidates").clicked() {
+ if ui.button("For Address Tables…").on_hover_text("AutoTableDisassemblerPlugin · pointer table candidates").clicked() {
self.show_search_address_tables_dialog = true;
- // Populate immediately from analyzer output.
+ // Populate immediately from analyzer output.
if let Some(prog) = self.program.as_ref() {
self.text_hits = address_table_hits(prog);
self.memory_hits.clear();
@@ -7669,164 +7632,164 @@ impl eframe::App for GhidrustApp {
}
ui.close_menu();
}
- if ui.button("Instruction Patterns…").on_hover_text("Ghidra BytePatternPlugin · mnemonic + operand filter").clicked() {
+ if ui.button("Instruction Patterns…").on_hover_text("BytePatternPlugin · mnemonic + operand filter").clicked() {
self.show_search_insn_dialog = true;
ui.close_menu();
}
- if ui.button("For Direct References…").on_hover_text("Not yet implemented").clicked() {
- self.nyi("Search → For Direct References");
+ 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").clicked() {
- self.nyi("Search → For Matching Instructions");
+ 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").clicked() {
- self.nyi("Search → Repeat Search");
+ if ui.button("Repeat Search").on_hover_text("Not yet implemented").clicked() {
+ self.nyi("Search → Repeat Search");
ui.close_menu();
}
});
- ui.menu_button("Select", |ui| {
- if ui.button("All").clicked() {
+ ui.menu_button("Select", |ui| {
+ if ui.button("All").clicked() {
self.select_all_listing();
ui.close_menu();
}
- if ui.button("All in View").on_hover_text("Not yet implemented").clicked() {
- self.nyi("Select → All in View");
+ if ui.button("All in View").on_hover_text("Not yet implemented").clicked() {
+ self.nyi("Select → All in View");
ui.close_menu();
}
- if ui.button("Clear").clicked() {
+ if ui.button("Clear").clicked() {
self.edit_clear_selection();
ui.close_menu();
}
- if ui.button("Complement").on_hover_text("Not yet implemented").clicked() {
- self.nyi("Select → Complement");
+ 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").clicked() {
- self.nyi("Select → Bytes");
+ 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").clicked() {
- self.nyi("Select → Instructions");
+ 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").clicked() {
- self.nyi("Select → Data");
+ 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").clicked() {
- self.nyi("Select → Undefined");
+ 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").clicked() {
- self.nyi("Select → Function");
+ 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").clicked() {
- self.nyi("Select → Subroutine");
+ 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").clicked() {
- self.nyi("Select → Forward Refs");
+ 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").clicked() {
- self.nyi("Select → Backward Refs");
+ 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").clicked() {
- self.nyi("Select → Create Table From Selection");
+ if ui.button("Create Table From Selection").on_hover_text("Not yet implemented").clicked() {
+ self.nyi("Select → Create Table From Selection");
ui.close_menu();
}
});
- ui.menu_button("Tools", |ui| {
- if ui.button("Processor options…").clicked() {
+ ui.menu_button("Tools", |ui| {
+ if ui.button("Processor options…").clicked() {
self.show_processor_dialog = true;
ui.close_menu();
}
- if ui.button("Compare Program…").on_hover_text("Not yet implemented").clicked() {
- self.nyi("Tools → Compare Program");
+ 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").clicked() {
- self.nyi("Tools → Program Differences");
+ if ui.button("Program Differences…").on_hover_text("Not yet implemented").clicked() {
+ self.nyi("Tools → Program Differences");
ui.close_menu();
}
- if ui.button("Generate Checksum…").on_hover_text("Opens Checksum Generator").clicked() {
+ if ui.button("Generate Checksum…").on_hover_text("Opens Checksum Generator").clicked() {
self.pane_open.insert(PaneKind::ChecksumGenerator, true);
ui.close_menu();
}
- if ui.button("Function Bit Patterns Explorer").on_hover_text("Not yet implemented").clicked() {
- self.nyi("Tools → Function Bit Patterns Explorer");
+ 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").clicked() {
- self.nyi("Tools → Instruction Table");
+ 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").clicked() {
- self.nyi("Tools → Processor Manual");
+ if ui.button("Processor Manual…").on_hover_text("Not yet implemented").clicked() {
+ self.nyi("Tools → Processor Manual");
ui.close_menu();
}
});
- ui.menu_button("Graph", |ui| {
- if ui.button("Function Graph").clicked() {
+ ui.menu_button("Graph", |ui| {
+ if ui.button("Function Graph").clicked() {
self.pane_open.insert(PaneKind::FunctionGraph, true);
ui.close_menu();
}
- if ui.button("Function Call Graph").clicked() {
+ if ui.button("Function Call Graph").clicked() {
self.pane_open.insert(PaneKind::FunctionCallGraph, true);
ui.close_menu();
}
- if ui.button("Function Call Trees").clicked() {
+ if ui.button("Function Call Trees").clicked() {
self.pane_open.insert(PaneKind::FunctionCallTrees, true);
ui.close_menu();
}
ui.separator();
- if ui.button("Block Flow").on_hover_text("Not yet implemented").clicked() {
- self.nyi("Graph → Block Flow");
+ 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").clicked() {
- self.nyi("Graph → Code Flow");
+ 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").clicked() {
- self.nyi("Graph → Calls");
+ 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").clicked() {
- self.nyi("Graph → Data Flow");
+ if ui.button("Data Flow").on_hover_text("Not yet implemented").clicked() {
+ self.nyi("Graph → Data Flow");
ui.close_menu();
}
});
- ui.menu_button("Window", |ui| {
- // Docked panels (long-standing).
- ui.label(egui::RichText::new("Docked").small().weak());
- ui.checkbox(&mut self.show_project_tree, "Project Tree (dock)");
- ui.checkbox(&mut self.show_program_tree, "Program Tree (dock)");
- ui.checkbox(&mut self.show_symbol_tree, "Symbol Tree (dock)");
- ui.checkbox(&mut self.show_console, "Console (dock)");
+ ui.menu_button("Window", |ui| {
+ // Docked panels (long-standing).
+ ui.label(egui::RichText::new("Docked").small().weak());
+ ui.checkbox(&mut self.show_project_tree, "Project Tree (dock)");
+ ui.checkbox(&mut self.show_program_tree, "Program Tree (dock)");
+ ui.checkbox(&mut self.show_symbol_tree, "Symbol Tree (dock)");
+ ui.checkbox(&mut self.show_console, "Console (dock)");
ui.separator();
- // Center dock tabs (Listing/Decompiler prefer side-by-side).
- ui.label(egui::RichText::new("Center Tabs").small().weak());
+ // Center dock tabs (Listing/Decompiler prefer side-by-side).
+ ui.label(egui::RichText::new("Center Tabs").small().weak());
if ui
- .selectable_label(self.center == CenterPane::Overview, "Overview")
+ .selectable_label(self.center == CenterPane::Overview, "Overview")
.clicked()
{
self.focus_center_tab(DockTab::Overview);
}
if ui
- .selectable_label(self.center == CenterPane::Listing, "Listing")
+ .selectable_label(self.center == CenterPane::Listing, "Listing")
.clicked()
{
self.focus_center_tab(DockTab::Listing);
}
if ui
- .selectable_label(self.center == CenterPane::Decompiler, "Decompiler")
+ .selectable_label(self.center == CenterPane::Decompiler, "Decompiler")
.clicked()
{
self.focus_center_tab(DockTab::Decompiler);
@@ -7834,21 +7797,21 @@ impl eframe::App for GhidrustApp {
if ui
.selectable_label(
self.center == CenterPane::DataTypes,
- "Data Type Manager",
+ "Data Type Manager",
)
.clicked()
{
self.focus_center_tab(DockTab::DataTypes);
}
ui.separator();
- // Full Ghidra CodeBrowser provider catalog (floating windows).
- // Sorted alphabetically by title to mirror Ghidra's Window menu.
- ui.label(egui::RichText::new("All Providers (Ghidra parity)").small().weak());
+ // Full provider catalog (floating windows).
+ // Sorted alphabetically by title to mirror Window menu.
+ ui.label(egui::RichText::new("All Providers (catalog)").small().weak());
let mut providers: Vec<PaneKind> = PaneKind::ALL.to_vec();
providers.sort_by_key(|k| k.title());
for k in providers {
- // Skip providers that are already covered by a dock/checkbox above
- // to avoid double-toggles (Project/Program/Symbol Tree, Console).
+ // Skip providers that are already covered by a dock/checkbox above
+ // to avoid double-toggles (Project/Program/Symbol Tree, Console).
if matches!(
k,
PaneKind::ProjectTree
@@ -7868,178 +7831,220 @@ impl eframe::App for GhidrustApp {
}
}
ui.separator();
- // Debugger tool providers.
- ui.label(egui::RichText::new("Debugger tool").small().weak());
- let mut dbg = DebuggerPane::ALL.to_vec();
- dbg.sort_by_key(|p| p.title());
- for p in dbg {
- let mut open = *self.debugger_open.get(&p).unwrap_or(&false);
- if ui.checkbox(&mut open, p.title()).changed() {
- self.debugger_open.insert(p, open);
+ // Single tabbed Debugger host.
+ ui.label(egui::RichText::new("Debugger tool").small().weak());
+ let mut dbg_open = self.debugger.host_open;
+ if ui.checkbox(&mut dbg_open, "Debugger").changed() {
+ self.debugger.host_open = dbg_open;
+ if dbg_open {
+ self.debugger.enabled = true;
+ if self.debugger.process_list_cache.is_empty() {
+ self.debugger.refresh_process_list();
+ }
}
}
+ if self.debugger.host_open {
+ ui.indent("dbg_tab_focus", |ui| {
+ for p in DebuggerPane::TAB_ORDER {
+ let selected = self.debugger.active_tab == *p;
+ if ui.selectable_label(selected, p.short_title()).clicked() {
+ self.debugger.focus_tab(*p);
+ }
+ }
+ });
+ }
ui.separator();
- // layout tools.
- if ui.button("Configure plugins…").clicked() {
+ // layout tools.
+ if ui.button("Configure plugins…").clicked() {
self.show_configure_dialog = true;
ui.close_menu();
}
- if ui.button("Save Tool Layout…").clicked() {
+ if ui.button("Save Tool Layout…").clicked() {
self.layouts_cached = layouts::list_layouts();
self.layouts_new_name = self.current_layout_name.clone();
self.show_layouts_dialog = true;
ui.close_menu();
}
});
- ui.menu_button("Debugger", |ui| {
+ ui.menu_button("Debugger", |ui| {
for act in DebuggerAction::ALL {
- if ui
- .button(act.label())
- .on_hover_text("Debugger backend pending (Phase P12)")
- .clicked()
- {
+ let hover = match act {
+ DebuggerAction::Launch => {
+ "CreateProcess CREATE_SUSPENDED + read-only session, then Resume (not a debug break-at-entry)"
+ }
+ DebuggerAction::Attach => {
+ "Open Debugger on Targets and refresh the process list"
+ }
+ DebuggerAction::Disconnect => {
+ "Detach the live process session (read-only bridge)"
+ }
+ DebuggerAction::ShowWatches => "Open Debugger → Watches tab",
+ DebuggerAction::ToggleBreakpoint => {
+ "Toggle a session-only breakpoint at the listing VA"
+ }
+ _ => "Debugger live backend not yet wired",
+ };
+ if ui.button(act.label()).on_hover_text(hover).clicked() {
match act {
+ DebuggerAction::Launch => {
+ let prefill = {
+ let p = self.path_input.trim();
+ if !p.is_empty() && std::path::Path::new(p).is_file() {
+ Some(std::path::PathBuf::from(p))
+ } else {
+ None
+ }
+ };
+ self.debugger.open_launch_ui(prefill.as_deref());
+ }
+ DebuggerAction::Attach => {
+ self.debugger.open_attach_ui();
+ }
+ DebuggerAction::Disconnect => {
+ self.debugger.detach_session();
+ }
DebuggerAction::ShowWatches => {
- self.debugger_open.insert(DebuggerPane::Watches, true);
+ self.debugger.focus_tab(DebuggerPane::Watches);
}
DebuggerAction::ToggleBreakpoint => {
if let Some(va) = self.listing_focus_va {
self.debugger.toggle_breakpoint(va);
- self.debugger_open
- .insert(DebuggerPane::Breakpoints, true);
+ self.debugger.focus_tab(DebuggerPane::Breakpoints);
+ } else {
+ self.nyi("Debugger → Toggle Breakpoint (no listing VA)");
}
- self.nyi(&format!("Debugger → {}", act.label()));
}
- _ => self.nyi(&format!("Debugger → {}", act.label())),
+ DebuggerAction::Continue
+ | DebuggerAction::Interrupt
+ | DebuggerAction::StepInto
+ | DebuggerAction::StepOver
+ | DebuggerAction::StepOut => {
+ self.nyi(&format!("Debugger → {}", act.label()));
+ }
}
ui.close_menu();
}
}
ui.separator();
- ui.checkbox(&mut self.debugger.enabled, "Debugger tool mode");
- if self.debugger.enabled {
- // Enabling the tool opens the core debugger providers.
- for p in [
- DebuggerPane::Targets,
- DebuggerPane::Threads,
- DebuggerPane::Modules,
- DebuggerPane::Registers,
- DebuggerPane::Stack,
- DebuggerPane::Breakpoints,
- ] {
- self.debugger_open.insert(p, true);
+ let mut enabled = self.debugger.enabled;
+ if ui.checkbox(&mut enabled, "Debugger tool mode").changed() {
+ if enabled {
+ self.debugger.enable_tool();
+ } else {
+ self.debugger.enabled = false;
+ self.debugger.host_open = false;
}
}
});
- ui.menu_button("Help", |ui| {
- if ui.button("Contents (F1)").on_hover_text("Not yet implemented").clicked() {
- self.nyi("Help → Contents");
+ ui.menu_button("Help", |ui| {
+ 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").clicked() {
- self.nyi("Help → Help On");
+ 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").clicked() {
- self.nyi("Help → Ghidra API Help");
+ if ui.button("API Help").on_hover_text("Not yet implemented").clicked() {
+ self.nyi("Help → API Help");
ui.close_menu();
}
- if ui.button("User Preferences").on_hover_text("Not yet implemented").clicked() {
- self.nyi("Help → User Preferences");
+ if ui.button("User Preferences").on_hover_text("Not yet implemented").clicked() {
+ self.nyi("Help → User Preferences");
ui.close_menu();
}
- if ui.button("Show Log").on_hover_text("Console pane is open").clicked() {
+ if ui.button("Show Log").on_hover_text("Console pane is open").clicked() {
self.show_console = true;
ui.close_menu();
}
ui.separator();
- if ui.button("About Ghidrust").clicked() {
+ if ui.button("About Ghidrust").clicked() {
self.status = format!(
- "Ghidrust {} — Rust RE toolkit (CodeBrowser shell)",
- env!("CARGO_PKG_VERSION")
+ "Ghidrust {} — Rust RE toolkit (CodeBrowser shell)",
+ env!("CARGO_PKG_VERSION")
);
self.log(self.status.clone());
ui.close_menu();
}
- if ui.button("Roadmap…").clicked() {
- self.log("See local development notes under dev/ (roadmap / parity)");
+ if ui.button("Roadmap…").clicked() {
+ self.log("See local development notes under dev/");
ui.close_menu();
}
});
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
let label = match self.theme {
- ThemeMode::Dark => "Theme: Dark",
- ThemeMode::Light => "Theme: Light",
+ ThemeMode::Dark => "Theme: Dark",
+ ThemeMode::Light => "Theme: Light",
};
if ui.button(label).clicked() {
self.theme = self.theme.toggle();
self.apply_theme(ctx);
- self.log(format!("Theme → {:?}", self.theme));
+ self.log(format!("Theme → {:?}", self.theme));
}
});
});
});
- // Listing hotkeys run *after* the Grok dock paints (see below) so the
- // TUI can claim focus/keys first — otherwise `G` opens Go To while typing.
+ // Listing hotkeys run *after* the Grok dock paints (see below) so the
+ // TUI can claim focus/keys first — otherwise `G` opens Go To while typing.
- egui::TopBottomPanel::top("nav_toolbar").show(ctx, |ui| {
+ egui::TopBottomPanel::top("nav_toolbar").show(ctx, |ui| {
ui.horizontal(|ui| {
let back_enabled = self.can_nav_back();
let fwd_enabled = self.can_nav_forward();
if ui
- .add_enabled(back_enabled, egui::Button::new("<- Back"))
- .on_hover_text("Navigation → Back (Alt+Left)")
+ .add_enabled(back_enabled, egui::Button::new("<- Back"))
+ .on_hover_text("Navigation → Back (Alt+Left)")
.clicked()
{
self.nav_back();
}
if ui
- .add_enabled(fwd_enabled, egui::Button::new("Forward ->"))
- .on_hover_text("Navigation → Forward (Alt+Right)")
+ .add_enabled(fwd_enabled, egui::Button::new("Forward ->"))
+ .on_hover_text("Navigation → Forward (Alt+Right)")
.clicked()
{
self.nav_forward();
}
ui.separator();
- if ui.button("Go To…").on_hover_text("Navigation → Go To Address (G)").clicked() {
+ if ui.button("Go To…").on_hover_text("Navigation → Go To Address (G)").clicked() {
if let Some(prog) = &self.program {
if let Some(e) = prog.entry {
- self.goto_input = format!("{e:#x}");
+ self.goto_input = format!("{e:#x}");
} else {
- self.goto_input = format!("{:#x}", prog.image_base);
+ self.goto_input = format!("{:#x}", prog.image_base);
}
}
self.show_goto_dialog = true;
}
ui.separator();
- if ui.button("Bookmark…").on_hover_text("Add bookmark at cursor VA").clicked() {
+ if ui.button("Bookmark…").on_hover_text("Add bookmark at cursor VA").clicked() {
if let Some(va) = self.listing_focus_va {
self.bookmark_dialog_kind = BookmarkKind::Note;
self.bookmark_dialog_category = String::new();
- self.bookmark_dialog_description = format!("bookmark @ {va:#x}");
+ self.bookmark_dialog_description = format!("bookmark @ {va:#x}");
self.show_bookmark_dialog = true;
} else {
- self.status = "No cursor VA — click a Listing line first".into();
+ self.status = "No cursor VA — click a Listing line first".into();
self.log(self.status.clone());
}
}
- if ui.button("Bookmarks").on_hover_text("Window → Bookmarks").clicked() {
+ if ui.button("Bookmarks").on_hover_text("Window → Bookmarks").clicked() {
self.pane_open.insert(PaneKind::Bookmarks, true);
}
- if ui.button("Functions").on_hover_text("Window → Functions").clicked() {
+ if ui.button("Functions").on_hover_text("Window → Functions").clicked() {
self.pane_open.insert(PaneKind::FunctionsWindow, true);
}
- if ui.button("Memory Map").on_hover_text("Window → Memory Map").clicked() {
+ if ui.button("Memory Map").on_hover_text("Window → Memory Map").clicked() {
self.pane_open.insert(PaneKind::MemoryMap, true);
}
- if ui.button("Symbol Table").on_hover_text("Window → Symbol Table").clicked() {
+ if ui.button("Symbol Table").on_hover_text("Window → Symbol Table").clicked() {
self.pane_open.insert(PaneKind::SymbolTable, true);
}
ui.separator();
let hist = format!(
- "Back: {} · Forward: {}",
+ "Back: {} · Forward: {}",
self.nav_history.len_back(),
self.nav_history.len_forward()
);
@@ -8047,78 +8052,78 @@ impl eframe::App for GhidrustApp {
});
});
- egui::TopBottomPanel::top("toolbar").show(ctx, |ui| {
+ egui::TopBottomPanel::top("toolbar").show(ctx, |ui| {
ui.horizontal(|ui| {
- ui.label("Project dir:");
+ ui.label("Project dir:");
ui.add(
egui::TextEdit::singleline(&mut self.project_dir_input)
.desired_width(240.0)
- .hint_text("folder for New/Open project"),
+ .hint_text("folder for New/Open project"),
);
- if ui.button("Browse…").on_hover_text("Choose project folder").clicked() {
+ if ui.button("Browse…").on_hover_text("Choose project folder").clicked() {
self.browse_project_dir();
}
- ui.label("Name:");
+ ui.label("Name:");
ui.add(
egui::TextEdit::singleline(&mut self.project_name_input).desired_width(100.0),
);
- if ui.button("New").on_hover_text("Create project (browse if dir empty)").clicked() {
+ if ui.button("New").on_hover_text("Create project (browse if dir empty)").clicked() {
if self.project_dir_input.trim().is_empty() {
self.browse_and_create_project();
} else if let Err(e) = self.create_project() {
- self.status = format!("error: {e}");
+ self.status = format!("error: {e}");
self.log(self.status.clone());
}
}
- if ui.button("Open").on_hover_text("Open project (browse if dir empty)").clicked() {
+ if ui.button("Open").on_hover_text("Open project (browse if dir empty)").clicked() {
if self.project_dir_input.trim().is_empty() {
self.browse_and_open_project();
} else if let Err(e) = self.open_project() {
- self.status = format!("error: {e}");
+ self.status = format!("error: {e}");
self.log(self.status.clone());
}
}
});
ui.horizontal(|ui| {
- ui.label("Binary:");
+ ui.label("Binary:");
ui.add(
egui::TextEdit::singleline(&mut self.path_input)
.desired_width(320.0)
- .hint_text("PE/ELF — or use Browse"),
+ .hint_text("PE/ELF — or use Browse"),
);
- if ui.button("Browse…").on_hover_text("Choose binary file").clicked() {
+ if ui.button("Browse…").on_hover_text("Choose binary file").clicked() {
self.browse_binary_path();
}
- if ui.button("Import").on_hover_text("Import into project (browse if empty)").clicked() {
+ if ui.button("Import").on_hover_text("Import into project (browse if empty)").clicked() {
if self.path_input.trim().is_empty() {
self.browse_and_import();
} else if let Err(e) = self.import_into_project() {
- self.status = format!("error: {e}");
+ self.status = format!("error: {e}");
self.log(self.status.clone());
}
}
- if ui.button("Load").on_hover_text("Load binary without project (browse if empty)").clicked() {
+ if ui.button("Load").on_hover_text("Load binary without project (browse if empty)").clicked() {
if self.path_input.trim().is_empty() {
self.browse_and_load_binary();
} else {
let p = self.path_input.clone();
if let Err(e) = self.load_binary(p) {
- self.status = format!("error: {e}");
+ self.status = format!("error: {e}");
self.log(self.status.clone());
}
}
}
if ui
- .button("Analyze…")
- .on_hover_text("Open analysis options (analyzers + GPU)")
+ .button("Analyze…")
+ .on_hover_text("Open analysis options (analyzers + GPU)")
.clicked()
{
self.pending_analyze_file_id = self.active_file_id.clone();
self.show_analysis_dialog = true;
}
- if ui.button("Save").clicked() {
+ if ui.button("Save").clicked() {
if let Err(e) = self.save_results() {
- self.status = format!("error: {e}");
+ self.status = format!("error: {e}");
self.log(self.status.clone());
}
}
@@ -8143,12 +8148,12 @@ impl eframe::App for GhidrustApp {
if !file_chips.is_empty() {
let pname = file_chips[0].0.clone();
ui.horizontal(|ui| {
- ui.label(format!("Open: {pname} | files:"));
+ ui.label(format!("Open: {pname} | files:"));
for (_, id, name) in &file_chips {
let selected = self.active_file_id.as_deref() == Some(id.as_str());
if ui.selectable_label(selected, name).clicked() {
if let Err(e) = self.open_project_file(id) {
- self.status = format!("error: {e}");
+ self.status = format!("error: {e}");
self.log(self.status.clone());
}
}
@@ -8157,7 +8162,7 @@ impl eframe::App for GhidrustApp {
}
});
- egui::TopBottomPanel::bottom("status").show(ctx, |ui| {
+ egui::TopBottomPanel::bottom("status").show(ctx, |ui| {
if let Some(frac) = self.analysis_progress_fraction() {
let t = m3_tokens(self.theme);
let primary = Color32::from_rgb(t.primary[0], t.primary[1], t.primary[2]);
@@ -8176,22 +8181,22 @@ impl eframe::App for GhidrustApp {
.names
.get(j.index)
.cloned()
- .unwrap_or_else(|| "finishing…".into());
+ .unwrap_or_else(|| "finishing…".into());
(
format!(
- "Analyzing {} — {}/{} {cur}{}",
+ "Analyzing {} — {}/{} {cur}{}",
j.file_label,
(j.index + 1).min(n),
n,
- if j.use_gpu { " · GPU experimental" } else { "" }
+ if j.use_gpu { " · GPU experimental" } else { "" }
),
(frac * 100.0) as u32,
)
})
- .unwrap_or_else(|| ("Analyzing…".into(), 0));
+ .unwrap_or_else(|| ("Analyzing…".into(), 0));
ui.label(egui::RichText::new(label).color(primary));
m3_linear_progress(ui, frac, primary, track);
- ui.small(format!("{pct}%"));
+ ui.small(format!("{pct}%"));
} else {
ui.horizontal(|ui| {
ui.label(&self.status);
@@ -8203,30 +8208,30 @@ impl eframe::App for GhidrustApp {
}
});
- // Bottom dock: tabbed (Grok primary + Console + Raw). The plain
- // analyzer / script log is never hidden — it just moves under the
- // "Console" tab. Grok is the default active tab so an RE opens the
- // app and starts typing to the agent immediately.
- //
- // Explicit min/max/default heights are required for the top-edge
- // resize gizmo to be draggable freely — without them egui pins the
- // panel to `default_height` and the drag handle becomes a 4px sliver
- // that's easy to miss.
+ // Bottom dock: tabbed (Grok primary + Console + Raw). The plain
+ // analyzer / script log is never hidden — it just moves under the
+ // "Console" tab. Grok is the default active tab so an RE opens the
+ // app and starts typing to the agent immediately.
+ //
+ // Explicit min/max/default heights are required for the top-edge
+ // resize gizmo to be draggable freely — without them egui pins the
+ // panel to `default_height` and the drag handle becomes a 4px sliver
+ // that's easy to miss.
if self.show_console {
- // Detect Grok TUI child exit before paint.
+ // Detect Grok TUI child exit before paint.
self.grok_pane.poll();
let screen_h = ctx.screen_rect().height();
- // Own the height ourselves + paint a real drag grip. Built-in
- // `resizable(true)` on TopBottomPanel is unreliable here (snaps
- // back when content doesn't expand — egui #581 / 0.31).
+ // Own the height ourselves + paint a real drag grip. Built-in
+ // `resizable(true)` on TopBottomPanel is unreliable here (snaps
+ // back when content doesn't expand — egui #581 / 0.31).
let max_h = (screen_h - 160.0).max(220.0);
let min_h = 140.0;
self.console_height = self.console_height.clamp(min_h, max_h);
- egui::TopBottomPanel::bottom("console")
+ egui::TopBottomPanel::bottom("console")
.exact_height(self.console_height)
.show_separator_line(false)
.show(ctx, |ui| {
- // Full-width drag strip at the top of the dock.
+ // Full-width drag strip at the top of the dock.
let grip_h = 10.0;
let (grip_rect, grip_resp) = ui.allocate_exact_size(
egui::vec2(ui.available_width(), grip_h),
@@ -8240,7 +8245,7 @@ impl eframe::App for GhidrustApp {
ui.visuals().widgets.noninteractive.bg_fill
};
ui.painter().rect_filled(grip_rect, 0.0, grip_color);
- // Center handle bar.
+ // Center handle bar.
let bar = egui::Rect::from_center_size(
grip_rect.center(),
egui::vec2(48.0, 3.0),
@@ -8254,19 +8259,19 @@ impl eframe::App for GhidrustApp {
ui.ctx().set_cursor_icon(egui::CursorIcon::ResizeVertical);
}
if grip_resp.dragged() {
- // Dragging the top edge up (negative dy) grows the panel.
+ // Dragging the top edge up (negative dy) grows the panel.
self.console_height = (self.console_height - grip_resp.drag_delta().y)
.clamp(min_h, max_h);
}
- grip_resp.on_hover_text("Drag to resize console");
+ grip_resp.on_hover_text("Drag to resize console");
ui.set_min_height(ui.available_height());
self.render_bottom_dock(ui);
});
}
- // Global keyboard shortcuts (after Grok dock so keyboard_captured is current).
- // Ghidra bindings: Alt+Left/Right, G, L/Ctrl+L, ;, T, Alt+Enter, Ctrl+Up/Down.
+ // Global keyboard shortcuts (after Grok dock so keyboard_captured is current).
+ // bindings: Alt+Left/Right, G, L/Ctrl+L, ;, T, Alt+Enter, Ctrl+Up/Down.
if !self.grok_pane.keyboard_captured {
let (
want_back,
@@ -8305,8 +8310,8 @@ impl eframe::App for GhidrustApp {
if self.goto_input.is_empty() {
if let Some(prog) = &self.program {
self.goto_input = prog.entry
- .map(|e| format!("{e:#x}"))
- .unwrap_or_else(|| format!("{:#x}", prog.image_base));
+ .map(|e| format!("{e:#x}"))
+ .unwrap_or_else(|| format!("{:#x}", prog.image_base));
}
}
self.show_goto_dialog = true;
@@ -8356,23 +8361,23 @@ impl eframe::App for GhidrustApp {
}
}
- // Ghidra Project Window–style dock: Project → binaries (upgraded badges + actions)
+ // Project Window–style dock: Project → binaries (upgraded badges + actions)
if self.show_project_tree {
- egui::SidePanel::left("project_tree")
+ egui::SidePanel::left("project_tree")
.resizable(true)
.default_width(240.0)
.show(ctx, |ui| {
- ui.heading("Project");
+ ui.heading("Project");
ui.small(
egui::RichText::new(
- "Click = select · Double-click / Open = load into main view · Analyze = options",
+ "Click = select · Double-click / Open = load into main view · Analyze = options",
)
.weak(),
);
ui.separator();
if self.project.is_none() {
- ui.weak("No project open.");
- ui.label("New/Open a project, then Import binaries.");
+ ui.weak("No project open.");
+ ui.label("New/Open a project, then Import binaries.");
} else {
let model = self.project_tree_model().unwrap();
let t = m3_tokens(self.theme);
@@ -8384,19 +8389,19 @@ impl eframe::App for GhidrustApp {
m3_icon(ui, M3Icon::Folder, 18.0, primary);
ui.strong(&model.project_name);
});
- // Fill remaining panel height and scroll when files overflow
- // (same idiom as Console / working list panes).
+ // Fill remaining panel height and scroll when files overflow
+ // (same idiom as Console / working list panes).
let root_open = egui::ScrollArea::vertical()
- .id_salt("project_tree_scroll")
+ .id_salt("project_tree_scroll")
.auto_shrink([false, false])
.show(ui, |ui| {
- egui::CollapsingHeader::new("Project files")
+ egui::CollapsingHeader::new("Project files")
.default_open(self.project_tree_expanded)
.show(ui, |ui| {
ui.small(egui::RichText::new(&model.project_root).weak());
ui.add_space(4.0);
if model.files.is_empty() {
- ui.weak("Empty — Import a binary.");
+ ui.weak("Empty — Import a binary.");
}
let mut open_id: Option<String> = None;
let mut analyze_id: Option<String> = None;
@@ -8434,11 +8439,11 @@ impl eframe::App for GhidrustApp {
);
if viewing {
ui.small(
- egui::RichText::new("viewing").color(primary),
+ egui::RichText::new("viewing").color(primary),
);
} else if row.has_saved_analysis {
ui.small(
- egui::RichText::new("double-click to open")
+ egui::RichText::new("double-click to open")
.weak(),
);
}
@@ -8448,27 +8453,27 @@ impl eframe::App for GhidrustApp {
egui::Layout::right_to_left(egui::Align::Center),
|ui| {
if ui
- .small_button("Delete")
+ .small_button("Delete")
.on_hover_text(
- "Remove from project (confirmation)",
+ "Remove from project (confirmation)",
)
.clicked()
{
delete_id = Some(row.id.clone());
}
if ui
- .small_button("Analyze")
+ .small_button("Analyze")
.on_hover_text(
- "Analysis options (analyzers + GPU)",
+ "Analysis options (analyzers + GPU)",
)
.clicked()
{
analyze_id = Some(row.id.clone());
}
if ui
- .small_button("Open")
+ .small_button("Open")
.on_hover_text(
- "Load into Overview / Listing / Symbol Tree",
+ "Load into Overview / Listing / Symbol Tree",
)
.clicked()
{
@@ -8499,12 +8504,12 @@ impl eframe::App for GhidrustApp {
self.request_delete_file(&id);
} else if let Some(id) = analyze_id {
if let Err(e) = self.analyze_from_tree(&id) {
- self.status = format!("error: {e}");
+ self.status = format!("error: {e}");
self.log(self.status.clone());
}
} else if let Some(id) = open_id {
if let Err(e) = self.open_from_tree(&id) {
- self.status = format!("error: {e}");
+ self.status = format!("error: {e}");
self.log(self.status.clone());
}
}
@@ -8514,32 +8519,32 @@ impl eframe::App for GhidrustApp {
});
}
- // Delete confirmation modal
+ // Delete confirmation modal
if let Some((ref id, ref name)) = self.pending_delete.clone() {
let id = id.clone();
let name = name.clone();
- egui::Window::new("Delete from project?")
+ egui::Window::new("Delete from project?")
.collapsible(false)
.resizable(false)
.anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0])
.show(ctx, |ui| {
ui.label(format!(
- "Remove \"{name}\" from this project?\n\n\
+ "Remove \"{name}\" from this project?\n\n\
Deletes the imported copy and saved analysis for this file.\n\
- This cannot be undone."
+ This cannot be undone."
));
ui.add_space(8.0);
ui.horizontal(|ui| {
- if ui.button("Cancel").clicked() {
+ if ui.button("Cancel").clicked() {
self.cancel_delete_file();
}
if ui
- .button(egui::RichText::new("Delete").color(Color32::from_rgb(0xB3, 0x26, 0x1E)))
+ .button(egui::RichText::new("Delete").color(Color32::from_rgb(0xB3, 0x26, 0x1E)))
.clicked()
{
let _ = id;
if let Err(e) = self.confirm_delete_file() {
- self.status = format!("error: {e}");
+ self.status = format!("error: {e}");
self.log(self.status.clone());
}
}
@@ -8548,21 +8553,21 @@ impl eframe::App for GhidrustApp {
}
if self.show_program_tree {
- egui::SidePanel::left("program_tree")
+ egui::SidePanel::left("program_tree")
.resizable(true)
.default_width(220.0)
.show(ctx, |ui| {
- ui.heading("Program Trees");
+ ui.heading("Program Trees");
ui.small(
- egui::RichText::new("Ghidra ProgramTreePlugin · modules/fragments")
+ egui::RichText::new("ProgramTreePlugin · modules/fragments")
.weak(),
);
ui.separator();
let Some(prog) = self.program.as_ref() else {
- ui.weak("No program loaded.");
+ ui.weak("No program loaded.");
return;
};
- // Snapshot everything we need before mutable use later.
+ // Snapshot everything we need before mutable use later.
let root_name = prog.name.clone();
let entry = prog.entry;
let image_base = prog.image_base;
@@ -8592,16 +8597,16 @@ impl eframe::App for GhidrustApp {
});
ui.small(
egui::RichText::new(format!(
- "image base {image_base:#x}{}",
+ "image base {image_base:#x}{}",
entry
- .map(|e| format!(" · entry {e:#x}"))
+ .map(|e| format!(" · entry {e:#x}"))
.unwrap_or_default()
))
.weak(),
);
- // Group blocks into Ghidra-style modules by permissions.
- // Module: "Code" (executable), "Data" (writable, non-exec), "RO Data" (else).
+ // Group blocks into modules by permissions.
+ // Module: "Code" (executable), "Data" (writable, non-exec), "RO Data" (else).
let mut code: Vec<usize> = Vec::new();
let mut data: Vec<usize> = Vec::new();
let mut rodata: Vec<usize> = Vec::new();
@@ -8624,38 +8629,38 @@ impl eframe::App for GhidrustApp {
let mut render_module =
|ui: &mut egui::Ui, title: &str, indices: &[usize]| {
egui::CollapsingHeader::new(format!(
- "{title} ({})",
+ "{title} ({})",
indices.len()
))
.default_open(!indices.is_empty() && indices.len() <= 32)
.show(ui, |ui| {
if indices.is_empty() {
- ui.weak("(empty module)");
+ ui.weak("(empty module)");
return;
}
for &i in indices {
let (name, va, size, r, w, x) = &blocks[i];
let flags = format!(
- "{}{}{}",
- if *r { "r" } else { "-" },
- if *w { "w" } else { "-" },
- if *x { "x" } else { "-" },
+ "{}{}{}",
+ if *r { "r" } else { "-" },
+ if *w { "w" } else { "-" },
+ if *x { "x" } else { "-" },
);
let in_view = view_filter
.as_ref()
.map(|f| f.contains(name))
.unwrap_or(true);
ui.horizontal(|ui| {
- let indicator = if in_view { "[v]" } else { "[ ]" };
+ let indicator = if in_view { "[v]" } else { "[ ]" };
ui.monospace(indicator);
if ui
.link(
egui::RichText::new(format!(
- "{name} {va:#x} {size:#x} {flags}"
+ "{name} {va:#x} {size:#x} {flags}"
))
.monospace(),
)
- .on_hover_text("Go To fragment start")
+ .on_hover_text("Go To fragment start")
.clicked()
{
goto = Some(*va);
@@ -8665,27 +8670,27 @@ impl eframe::App for GhidrustApp {
|ui| {
if in_view && view_filter.is_some() {
if ui
- .small_button("Remove")
+ .small_button("Remove")
.on_hover_text(
- "Remove fragment from Listing view",
+ "Remove fragment from Listing view",
)
.clicked()
{
remove_from_view = Some(name.clone());
}
} else if ui
- .small_button("Add")
+ .small_button("Add")
.on_hover_text(
- "Add fragment to Listing view",
+ "Add fragment to Listing view",
)
.clicked()
{
add_to_view = Some(name.clone());
}
if ui
- .small_button("Set")
+ .small_button("Set")
.on_hover_text(
- "Set Listing view to this fragment only",
+ "Set Listing view to this fragment only",
)
.clicked()
{
@@ -8699,30 +8704,30 @@ impl eframe::App for GhidrustApp {
};
egui::ScrollArea::vertical()
- .id_salt("program_tree_scroll")
+ .id_salt("program_tree_scroll")
.auto_shrink([false, false])
.show(ui, |ui| {
- render_module(ui, "Code (X)", &code);
- render_module(ui, "Data (RW)", &data);
- render_module(ui, "Read‑only (R)", &rodata);
+ render_module(ui, "Code (X)", &code);
+ render_module(ui, "Data (RW)", &data);
+ render_module(ui, "Read‑only (R)", &rodata);
ui.separator();
ui.horizontal(|ui| {
if ui
- .small_button("Show All")
- .on_hover_text("Clear the Listing view filter")
+ .small_button("Show All")
+ .on_hover_text("Clear the Listing view filter")
.clicked()
{
show_all = true;
}
if let Some(f) = view_filter.as_ref() {
ui.small(format!(
- "View filter · {} fragment(s) in view",
+ "View filter · {} fragment(s) in view",
f.len()
));
} else {
ui.small(
- egui::RichText::new("View filter · full program")
+ egui::RichText::new("View filter · full program")
.weak()
.italics(),
);
@@ -8731,7 +8736,7 @@ impl eframe::App for GhidrustApp {
});
if let Some(va) = goto {
- let _ = self.goto_address_str(&format!("{va:#x}"));
+ let _ = self.goto_address_str(&format!("{va:#x}"));
}
if let Some(name) = add_to_view {
self.add_to_view(name);
@@ -8751,58 +8756,58 @@ impl eframe::App for GhidrustApp {
}
if self.show_symbol_tree {
- egui::SidePanel::right("symbol_tree")
+ egui::SidePanel::right("symbol_tree")
.resizable(true)
.default_width(280.0)
.min_width(200.0)
.show(ctx, |ui| {
let t = m3_tokens(self.theme);
let primary = Color32::from_rgb(t.primary[0], t.primary[1], t.primary[2]);
- ui.heading("Symbol Tree");
+ ui.heading("Symbol Tree");
if self.program.is_none() {
- ui.weak("Open a project file to browse symbols.");
+ ui.weak("Open a project file to browse symbols.");
return;
}
ui.small(egui::RichText::new(self.analysis_summary_line()).color(primary));
ui.horizontal(|ui| {
ui.checkbox(
&mut self.symbol_tree_nav,
- "Selection Navigation",
+ "Selection Navigation",
)
.on_hover_text(
- "Ghidra `Selection Navigation` — cursor moves keep this tree in sync",
+ "`Selection Navigation` — cursor moves keep this tree in sync",
);
});
ui.separator();
- // Outer scroll so category headers + expanded sections aren't clipped
- // when they exceed the dock height. Per-list ScrollAreas keep max_height
- // so nested wheel scrolling still targets the open list.
+ // Outer scroll so category headers + expanded sections aren't clipped
+ // when they exceed the dock height. Per-list ScrollAreas keep max_height
+ // so nested wheel scrolling still targets the open list.
egui::ScrollArea::vertical()
- .id_salt("symbol_tree_scroll")
+ .id_salt("symbol_tree_scroll")
.auto_shrink([false, false])
.show(ui, |ui| {
- // ── Ghidra `SymbolTreePlugin` category order ────────────────
- // Imports · Exports · Functions · Labels · Classes · Namespaces
+ // ── `SymbolTreePlugin` category order ────────────────
+ // Imports · Exports · Functions · Labels · Classes · Namespaces
let (imports, exports) = self.imports_exports();
let mut nav_goto: Option<u64> = None;
- // 1) Imports — honest: only rows the analyzer/loader produced.
- egui::CollapsingHeader::new(format!("Imports ({})", imports.len()))
+ // 1) Imports — honest: only rows the analyzer/loader produced.
+ egui::CollapsingHeader::new(format!("Imports ({})", imports.len()))
.default_open(false)
.show(ui, |ui| {
if imports.is_empty() {
ui.weak(
- "No imports — Ghidrust PE loader currently does not \
+ "No imports — Ghidrust PE loader currently does not \
parse the Import Directory. Run a PDB analyzer to \
- populate __imp_* symbols.",
+ populate __imp_* symbols.",
);
} else {
for (va, name) in &imports {
if ui
.link(
- egui::RichText::new(format!("{va:#x} {name}"))
+ egui::RichText::new(format!("{va:#x} {name}"))
.monospace(),
)
.clicked()
@@ -8812,21 +8817,21 @@ impl eframe::App for GhidrustApp {
}
}
});
- // 2) Exports — honest empty when unset.
- egui::CollapsingHeader::new(format!("Exports ({})", exports.len()))
+ // 2) Exports — honest empty when unset.
+ egui::CollapsingHeader::new(format!("Exports ({})", exports.len()))
.default_open(false)
.show(ui, |ui| {
if exports.is_empty() {
ui.weak(
- "No exports — Ghidrust PE loader currently does not \
+ "No exports — Ghidrust PE loader currently does not \
parse the Export Directory. Analyzer output may \
- surface `__declspec(dllexport)` names.",
+ surface `__declspec(dllexport)` names.",
);
} else {
for (va, name) in &exports {
if ui
.link(
- egui::RichText::new(format!("{va:#x} {name}"))
+ egui::RichText::new(format!("{va:#x} {name}"))
.monospace(),
)
.clicked()
@@ -8837,16 +8842,16 @@ impl eframe::App for GhidrustApp {
}
});
if let Some(va) = nav_goto {
- let _ = self.goto_address_str(&format!("{va:#x}"));
+ let _ = self.goto_address_str(&format!("{va:#x}"));
}
- // 3) Functions (virtualized) — real from Program::analysis.functions
+ // 3) Functions (virtualized) — real from Program::analysis.functions
let fn_count = self
.program
.as_ref()
.map(|p| p.analysis.functions.len())
.unwrap_or(0);
- egui::CollapsingHeader::new(format!("Functions ({fn_count})"))
+ egui::CollapsingHeader::new(format!("Functions ({fn_count})"))
.default_open(fn_count > 0 && fn_count <= 500)
.show(ui, |ui| {
let entry = self.program.as_ref().and_then(|p| p.entry);
@@ -8862,15 +8867,15 @@ impl eframe::App for GhidrustApp {
})
.unwrap_or_default();
if let Some(e) = entry {
- ui.monospace(format!("entry @ {e:#x}"));
+ ui.monospace(format!("entry @ {e:#x}"));
}
if fns.is_empty() {
- ui.weak("Run Function Start Search.");
+ ui.weak("Run Function Start Search.");
} else {
ui.add(
egui::TextEdit::singleline(&mut self.fn_filter)
.desired_width(f32::INFINITY)
- .hint_text("Filter functions…"),
+ .hint_text("Filter functions…"),
);
let q = self.fn_filter.to_ascii_lowercase();
let rows: Vec<(u64, String)> = fns
@@ -8883,14 +8888,14 @@ impl eframe::App for GhidrustApp {
let n = rows.len();
let mut clicked_fn: Option<u64> = None;
egui::ScrollArea::vertical()
- .id_salt("fn_scroll")
+ .id_salt("fn_scroll")
.max_height(220.0)
.show_rows(ui, row_h, n, |ui, range| {
for i in range {
let (va, name) = &rows[i];
- let label = format!("{va:#x} {name}");
- // Focused if this function is the decomp / cursor /
- // selection-navigation target.
+ let label = format!("{va:#x} {name}");
+ // Focused if this function is the decomp / cursor /
+ // selection-navigation target.
let focused = self.decomp_entry == Some(*va)
|| self.listing_focus_va == Some(*va)
|| self.focused_function_entry == Some(*va);
@@ -8917,11 +8922,11 @@ impl eframe::App for GhidrustApp {
if let Some(va) = clicked_fn {
self.focus_function(va);
}
- ui.small(format!("{n} shown · click → Listing + Decompiler"));
+ ui.small(format!("{n} shown · click → Listing + Decompiler"));
}
});
- // 4) Labels — Program::analysis.symbols (real)
+ // 4) Labels — Program::analysis.symbols (real)
let labels: Vec<(u64, String)> = self
.program
.as_ref()
@@ -8933,17 +8938,17 @@ impl eframe::App for GhidrustApp {
.collect()
})
.unwrap_or_default();
- egui::CollapsingHeader::new(format!("Labels ({})", labels.len()))
+ egui::CollapsingHeader::new(format!("Labels ({})", labels.len()))
.default_open(false)
.show(ui, |ui| {
if labels.is_empty() {
- ui.weak("No labels — analyzers/PDB symbols populate this list.");
+ ui.weak("No labels — analyzers/PDB symbols populate this list.");
} else {
let row_h = ui.text_style_height(&egui::TextStyle::Monospace);
let n = labels.len();
let mut clicked_va: Option<u64> = None;
egui::ScrollArea::vertical()
- .id_salt("labels_scroll")
+ .id_salt("labels_scroll")
.max_height(220.0)
.show_rows(ui, row_h, n, |ui, range| {
for i in range {
@@ -8951,7 +8956,7 @@ impl eframe::App for GhidrustApp {
let r = ui.add(
egui::Label::new(
egui::RichText::new(format!(
- "{va:#x} {name}"
+ "{va:#x} {name}"
))
.monospace(),
)
@@ -8963,37 +8968,37 @@ impl eframe::App for GhidrustApp {
}
});
if let Some(va) = clicked_va {
- let _ = self.goto_address_str(&format!("{va:#x}"));
+ let _ = self.goto_address_str(&format!("{va:#x}"));
}
}
});
- // 5) Classes (RTTI subtree preserved) — real
+ // 5) Classes (RTTI subtree preserved) — real
let rtti_n = self.rtti.classes.len();
- egui::CollapsingHeader::new(format!("Classes ({rtti_n})"))
+ egui::CollapsingHeader::new(format!("Classes ({rtti_n})"))
.default_open(false)
.show(ui, |ui| {
if rtti_n == 0 {
- ui.weak("Run WindowsPE x86 PE RTTI Analyzer, then Open the file.");
+ ui.weak("Run WindowsPE x86 PE RTTI Analyzer, then Open the file.");
return;
}
ui.add(
egui::TextEdit::singleline(&mut self.rtti_filter)
.desired_width(f32::INFINITY)
- .hint_text("Filter class names…"),
+ .hint_text("Filter class names…"),
);
- if ui.button("Apply filter").clicked()
+ if ui.button("Apply filter").clicked()
|| ui.input(|i| i.key_pressed(egui::Key::Enter))
{
self.rtti_filter_cache.clear();
}
self.rebuild_rtti_filter_cache();
let n_show = self.rtti_filtered_idx.len();
- ui.small(format!("{n_show} / {rtti_n} classes (RTTI)"));
- // `ghidrust_core::rtti_query` gives the catalog (deduped,
- // grouped by name) view with every recovered vtable VA —
- // `self.rtti` is the raw per-class report used for the
- // filter cache above, so we join on name for the tooltip.
+ ui.small(format!("{n_show} / {rtti_n} classes (RTTI)"));
+ // `ghidrust_core::rtti_query` gives the catalog (deduped,
+ // grouped by name) view with every recovered vtable VA —
+ // `self.rtti` is the raw per-class report used for the
+ // filter cache above, so we join on name for the tooltip.
let vtable_vas: BTreeMap<String, Vec<u64>> = self
.program
.as_ref()
@@ -9016,7 +9021,7 @@ impl eframe::App for GhidrustApp {
let row_h = ui.text_style_height(&egui::TextStyle::Body) + 2.0;
let idxs = self.rtti_filtered_idx.clone();
egui::ScrollArea::vertical()
- .id_salt("rtti_scroll")
+ .id_salt("rtti_scroll")
.auto_shrink([false, false])
.max_height(220.0)
.show_rows(ui, row_h, idxs.len(), |ui, range| {
@@ -9024,22 +9029,22 @@ impl eframe::App for GhidrustApp {
let c = &self.rtti.classes[idxs[i]];
let va = c
.type_info_va
- .map(|v| format!("{v:#x}"))
- .unwrap_or_else(|| "—".into());
+ .map(|v| format!("{v:#x}"))
+ .unwrap_or_else(|| "—".into());
let vtables = vtable_vas
.get(&c.name)
.map(|vs| {
vs.iter()
- .map(|v| format!("{v:#x}"))
+ .map(|v| format!("{v:#x}"))
.collect::<Vec<_>>()
- .join(", ")
+ .join(", ")
})
- .unwrap_or_else(|| "—".into());
+ .unwrap_or_else(|| "—".into());
ui.horizontal(|ui| {
ui.monospace(&va);
ui.label(&c.name)
.on_hover_text(format!(
- "kind={} col={:?} vtable={:?}\nvtable_vas (rtti_query)=[{vtables}]",
+ "kind={} col={:?} vtable={:?}\nvtable_vas (rtti_query)=[{vtables}]",
c.kind, c.col_va, c.vtable_va
));
});
@@ -9047,7 +9052,7 @@ impl eframe::App for GhidrustApp {
});
});
- // 6) Namespaces — honest: derive from `::` in symbol names when a demangler ran.
+ // 6) Namespaces — honest: derive from `::` in symbol names when a demangler ran.
let namespace_map: BTreeMap<String, Vec<(u64, String)>> = {
let mut m: BTreeMap<String, Vec<(u64, String)>> = BTreeMap::new();
if let Some(prog) = self.program.as_ref() {
@@ -9058,7 +9063,7 @@ impl eframe::App for GhidrustApp {
.chain(prog.analysis.pdb_symbols.iter())
{
let src = s.demangled.as_deref().unwrap_or(&s.name);
- if let Some(idx) = src.rfind("::") {
+ if let Some(idx) = src.rfind("::") {
let ns = src[..idx].to_string();
let leaf = src[idx + 2..].to_string();
m.entry(ns).or_default().push((s.va, leaf));
@@ -9067,20 +9072,20 @@ impl eframe::App for GhidrustApp {
}
m
};
- egui::CollapsingHeader::new(format!("Namespaces ({})", namespace_map.len()))
+ egui::CollapsingHeader::new(format!("Namespaces ({})", namespace_map.len()))
.default_open(false)
.show(ui, |ui| {
if namespace_map.is_empty() {
ui.weak(
- "No namespaces recovered — the Demangler Microsoft analyzer \
- fills this list when demangling produces `::` scopes.",
+ "No namespaces recovered — the Demangler Microsoft analyzer \
+ fills this list when demangling produces `::` scopes.",
);
return;
}
let mut clicked_va: Option<u64> = None;
for (ns, entries) in &namespace_map {
egui::CollapsingHeader::new(format!(
- "{ns} ({})",
+ "{ns} ({})",
entries.len()
))
.default_open(false)
@@ -9089,7 +9094,7 @@ impl eframe::App for GhidrustApp {
if ui
.link(
egui::RichText::new(format!(
- "{va:#x} {leaf}"
+ "{va:#x} {leaf}"
))
.monospace(),
)
@@ -9101,47 +9106,47 @@ impl eframe::App for GhidrustApp {
});
}
if let Some(va) = clicked_va {
- let _ = self.goto_address_str(&format!("{va:#x}"));
+ let _ = self.goto_address_str(&format!("{va:#x}"));
}
});
- // Bonus: Strings shortcut (Ghidra has a separate Defined Strings window,
- // which is available in the floating provider panel too).
+ // Bonus: Strings shortcut (has a separate Defined Strings window,
+ // which is available in the floating provider panel too).
let str_n = self.strings.len();
- egui::CollapsingHeader::new(format!("Strings ({str_n})"))
+ egui::CollapsingHeader::new(format!("Strings ({str_n})"))
.default_open(false)
.show(ui, |ui| {
if str_n == 0 {
- ui.weak("Run ASCII Strings (session) or re-analyze.");
+ ui.weak("Run ASCII Strings (session) or re-analyze.");
return;
}
- if ui.button("Open Defined Strings window").clicked() {
+ if ui.button("Open Defined Strings window").clicked() {
self.pane_open.insert(PaneKind::DefinedStrings, true);
}
let row_h = ui.text_style_height(&egui::TextStyle::Monospace);
egui::ScrollArea::vertical()
- .id_salt("str_scroll")
+ .id_salt("str_scroll")
.max_height(200.0)
.show_rows(ui, row_h, str_n.min(5000), |ui, range| {
for i in range {
if let Some(s) = self.strings.get(i) {
let val: String =
s.value.chars().take(48).collect();
- ui.monospace(format!("{:#x}: {val}", s.va));
+ ui.monospace(format!("{:#x}: {val}", s.va));
}
}
});
if str_n > 5000 {
- ui.small(format!("Showing first 5000 of {str_n}"));
+ ui.small(format!("Showing first 5000 of {str_n}"));
}
});
});
});
}
- // Analysis complete banner (top of frame content)
+ // Analysis complete banner (top of frame content)
if let Some(banner) = self.analysis_done_banner.clone() {
- egui::TopBottomPanel::top("analysis_done_banner").show(ctx, |ui| {
+ egui::TopBottomPanel::top("analysis_done_banner").show(ctx, |ui| {
let t = m3_tokens(self.theme);
let primary = Color32::from_rgb(t.primary[0], t.primary[1], t.primary[2]);
let ok = Color32::from_rgb(0x4C, 0xAF, 0x50);
@@ -9149,10 +9154,10 @@ impl eframe::App for GhidrustApp {
m3_icon(ui, M3Icon::CheckCircle, 18.0, ok);
ui.label(egui::RichText::new(banner).color(primary).strong());
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
- if ui.button("Dismiss").clicked() {
+ if ui.button("Dismiss").clicked() {
self.analysis_done_banner = None;
}
- if ui.button("Open Overview").clicked() {
+ if ui.button("Open Overview").clicked() {
self.focus_center_tab(DockTab::Overview);
self.analysis_done_banner = None;
}
@@ -9162,8 +9167,8 @@ impl eframe::App for GhidrustApp {
}
egui::CentralPanel::default().show(ctx, |ui| {
- // `DockArea` and the tab viewer both need `&mut self` fields — take
- // the dock tree out so the viewer can borrow the rest of the app.
+ // `DockArea` and the tab viewer both need `&mut self` fields — take
+ // the dock tree out so the viewer can borrow the rest of the app.
let mut dock = std::mem::replace(&mut self.center_dock, DockState::new(vec![]));
DockArea::new(&mut dock)
.style(DockStyle::from_egui(ui.style().as_ref()))
@@ -9174,36 +9179,36 @@ impl eframe::App for GhidrustApp {
self.sync_center_from_dock();
});
- // draw every open floating provider pane.
+ // draw every open floating provider pane.
self.draw_provider_panes(ctx);
- // edit dialogs (rename / retype / comment / signature / new type).
+ // edit dialogs (rename / retype / comment / signature / new type).
self.draw_edit_dialogs(ctx);
- // Configure plugins dialog.
+ // Configure plugins dialog.
if self.show_configure_dialog {
let mut close = false;
- egui::Window::new("Configure plugins")
- .id(egui::Id::new("dialog_configure"))
+ egui::Window::new("Configure plugins")
+ .id(egui::Id::new("dialog_configure"))
.resizable(true)
.default_size(egui::vec2(680.0, 460.0))
.show(ctx, |ui| {
ui.label(
- "Ghidrust plugins are compile-time; this dialog is a Ghidra parity list of every provider Ghidrust ships.",
+ "Ghidrust plugins are compile-time; this dialog lists every provider Ghidrust ships.",
);
ui.separator();
egui::ScrollArea::vertical()
- .id_salt("configure_scroll")
+ .id_salt("configure_scroll")
.max_height(340.0)
.show(ui, |ui| {
- egui::Grid::new("configure_grid")
+ egui::Grid::new("configure_grid")
.num_columns(4)
.striped(true)
.show(ui, |ui| {
- ui.strong("Plugin");
- ui.strong("Kind");
- ui.strong("State");
- ui.strong("Description");
+ ui.strong("Plugin");
+ ui.strong("Kind");
+ ui.strong("State");
+ ui.strong("Description");
ui.end_row();
for p in layouts::PLUGIN_CATALOG {
ui.monospace(p.name);
@@ -9215,7 +9220,7 @@ impl eframe::App for GhidrustApp {
});
});
ui.separator();
- if ui.button("Close").clicked() {
+ if ui.button("Close").clicked() {
close = true;
}
});
@@ -9224,36 +9229,36 @@ impl eframe::App for GhidrustApp {
}
}
- // Layout save / load dialog.
+ // Layout save / load dialog.
if self.show_layouts_dialog {
let mut close = false;
let mut do_save = false;
let mut load_name: Option<String> = None;
let mut delete_name: Option<String> = None;
- egui::Window::new("Tool Layouts")
- .id(egui::Id::new("dialog_layouts"))
+ egui::Window::new("Tool Layouts")
+ .id(egui::Id::new("dialog_layouts"))
.resizable(true)
.default_size(egui::vec2(480.0, 360.0))
.show(ctx, |ui| {
- ui.label("Save / restore CodeBrowser tool layouts (pane visibility + docks).");
+ ui.label("Save / restore CodeBrowser tool layouts (pane visibility + docks).");
ui.small(
egui::RichText::new(
- "Files land under %APPDATA%/ghidrust/layouts/<name>.tool.json (Ghidra .tool XML analog).",
+ "Files land under %APPDATA%/ghidrust/layouts/<name>.tool.json .",
)
.weak(),
);
ui.separator();
ui.horizontal(|ui| {
- ui.label("Name:");
+ ui.label("Name:");
ui.add(
egui::TextEdit::singleline(&mut self.layouts_new_name)
.desired_width(200.0)
- .hint_text("MyCodeBrowser"),
+ .hint_text("MyCodeBrowser"),
);
if ui
.add_enabled(
!self.layouts_new_name.trim().is_empty(),
- egui::Button::new("Save current layout"),
+ egui::Button::new("Save current layout"),
)
.clicked()
{
@@ -9261,21 +9266,21 @@ impl eframe::App for GhidrustApp {
}
});
ui.separator();
- ui.label(egui::RichText::new("Saved layouts").strong());
+ ui.label(egui::RichText::new("Saved layouts").strong());
if self.layouts_cached.is_empty() {
- ui.weak("No layouts saved yet.");
+ ui.weak("No layouts saved yet.");
} else {
egui::ScrollArea::vertical()
- .id_salt("layouts_scroll")
+ .id_salt("layouts_scroll")
.max_height(180.0)
.show(ui, |ui| {
for name in &self.layouts_cached {
ui.horizontal(|ui| {
ui.monospace(name);
- if ui.small_button("Restore").clicked() {
+ if ui.small_button("Restore").clicked() {
load_name = Some(name.clone());
}
- if ui.small_button("Delete").clicked() {
+ if ui.small_button("Delete").clicked() {
delete_name = Some(name.clone());
}
});
@@ -9286,24 +9291,24 @@ impl eframe::App for GhidrustApp {
if !self.current_layout_name.is_empty() {
ui.small(
egui::RichText::new(format!(
- "Current layout: {}",
+ "Current layout: {}",
self.current_layout_name
))
.weak(),
);
}
- if ui.button("Close").clicked() {
+ if ui.button("Close").clicked() {
close = true;
}
});
if do_save {
match self.save_layout_named(self.layouts_new_name.clone()) {
Ok(p) => {
- self.status = format!("Layout saved → {}", p.display());
+ self.status = format!("Layout saved → {}", p.display());
self.log(self.status.clone());
}
Err(e) => {
- self.status = format!("save layout error: {e}");
+ self.status = format!("save layout error: {e}");
self.log_error(self.status.clone());
}
}
@@ -9311,18 +9316,18 @@ impl eframe::App for GhidrustApp {
if let Some(name) = load_name {
match self.restore_layout_named(&name) {
Ok(()) => {
- self.status = format!("Layout restored → {name}");
+ self.status = format!("Layout restored → {name}");
self.log(self.status.clone());
}
Err(e) => {
- self.status = format!("restore layout error: {e}");
+ self.status = format!("restore layout error: {e}");
self.log_error(self.status.clone());
}
}
}
if let Some(name) = delete_name {
if let Err(e) = layouts::delete_layout(&name) {
- self.status = format!("delete layout error: {e}");
+ self.status = format!("delete layout error: {e}");
self.log_error(self.status.clone());
}
self.layouts_cached = layouts::list_layouts();
@@ -9332,33 +9337,33 @@ impl eframe::App for GhidrustApp {
}
}
- // Bookmark add dialog
+ // Bookmark add dialog
if self.show_bookmark_dialog {
let mut close = false;
let mut confirmed = false;
- egui::Window::new("Add Bookmark")
- .id(egui::Id::new("dialog_add_bookmark"))
+ egui::Window::new("Add Bookmark")
+ .id(egui::Id::new("dialog_add_bookmark"))
.collapsible(false)
.resizable(false)
.anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0])
.show(ctx, |ui| {
- ui.label("Kind:");
- egui::ComboBox::from_id_salt("bookmark_kind")
+ ui.label("Kind:");
+ egui::ComboBox::from_id_salt("bookmark_kind")
.selected_text(self.bookmark_dialog_kind.label())
.show_ui(ui, |ui| {
for k in BookmarkKind::ALL {
ui.selectable_value(&mut self.bookmark_dialog_kind, *k, k.label());
}
});
- ui.label("Category:");
+ ui.label("Category:");
ui.text_edit_singleline(&mut self.bookmark_dialog_category);
- ui.label("Description:");
+ ui.label("Description:");
ui.text_edit_singleline(&mut self.bookmark_dialog_description);
ui.horizontal(|ui| {
- if ui.button("Cancel").clicked() {
+ if ui.button("Cancel").clicked() {
close = true;
}
- if ui.button("Add").clicked() {
+ if ui.button("Add").clicked() {
confirmed = true;
close = true;
}
@@ -9377,24 +9382,24 @@ impl eframe::App for GhidrustApp {
}
}
- // Navigation → Go To Address
+ // Navigation → Go To Address
if self.show_goto_dialog {
- egui::Window::new("Go To Address")
+ egui::Window::new("Go To Address")
.collapsible(false)
.resizable(false)
.anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0])
.show(ctx, |ui| {
- ui.label("Address (hex, optional 0x prefix):");
+ ui.label("Address (hex, optional 0x prefix):");
ui.text_edit_singleline(&mut self.goto_input);
ui.horizontal(|ui| {
- if ui.button("Cancel").clicked() {
+ if ui.button("Cancel").clicked() {
self.show_goto_dialog = false;
}
- if ui.button("Go").clicked() {
+ if ui.button("Go").clicked() {
match self.goto_address_str(&self.goto_input.clone()) {
Ok(()) => self.show_goto_dialog = false,
Err(e) => {
- self.status = format!("error: {e}");
+ self.status = format!("error: {e}");
self.log(self.status.clone());
}
}
@@ -9403,26 +9408,26 @@ impl eframe::App for GhidrustApp {
});
}
- // Search → Memory
+ // Search → Memory
if self.show_search_memory_dialog {
- egui::Window::new("Search Memory")
+ egui::Window::new("Search Memory")
.collapsible(false)
.resizable(true)
.default_width(420.0)
.anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0])
.show(ctx, |ui| {
- ui.label("Byte pattern (hex; ?? = wildcard):");
+ ui.label("Byte pattern (hex; ?? = wildcard):");
ui.text_edit_singleline(&mut self.search_memory_input);
- ui.small("Example: 55 48 89 e5 or 48??e5");
+ ui.small("Example: 55 48 89 e5 or 48??e5");
ui.horizontal(|ui| {
- if ui.button("Cancel").clicked() {
+ if ui.button("Cancel").clicked() {
self.show_search_memory_dialog = false;
}
- if ui.button("Search").clicked() {
+ if ui.button("Search").clicked() {
match self.run_search_memory() {
Ok(()) => self.show_search_memory_dialog = false,
Err(e) => {
- self.status = format!("error: {e}");
+ self.status = format!("error: {e}");
self.log(self.status.clone());
}
}
@@ -9431,26 +9436,26 @@ impl eframe::App for GhidrustApp {
});
}
- // Search → Program Text
+ // Search → Program Text
if self.show_search_text_dialog {
- egui::Window::new("Search Program Text")
+ egui::Window::new("Search Program Text")
.collapsible(false)
.resizable(true)
.default_width(420.0)
.anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0])
.show(ctx, |ui| {
- ui.label("Query (listing / symbols / functions / memory text):");
+ ui.label("Query (listing / symbols / functions / memory text):");
ui.text_edit_singleline(&mut self.search_text_input);
- ui.checkbox(&mut self.search_text_case_insensitive, "Case insensitive");
+ ui.checkbox(&mut self.search_text_case_insensitive, "Case insensitive");
ui.horizontal(|ui| {
- if ui.button("Cancel").clicked() {
+ if ui.button("Cancel").clicked() {
self.show_search_text_dialog = false;
}
- if ui.button("Search").clicked() {
+ if ui.button("Search").clicked() {
match self.run_search_text() {
Ok(()) => self.show_search_text_dialog = false,
Err(e) => {
- self.status = format!("error: {e}");
+ self.status = format!("error: {e}");
self.log(self.status.clone());
}
}
@@ -9459,31 +9464,31 @@ impl eframe::App for GhidrustApp {
});
}
- // Search → For Scalars
+ // Search → For Scalars
if self.show_search_scalars_dialog {
- egui::Window::new("Search For Scalars")
+ egui::Window::new("Search For Scalars")
.collapsible(false)
.resizable(false)
.anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0])
.show(ctx, |ui| {
- ui.label("Scan operand scalars in [min, max]. Hex ok (0x…) or decimal.");
+ ui.label("Scan operand scalars in [min, max]. Hex ok (0x…) or decimal.");
ui.horizontal(|ui| {
- ui.label("Min:");
+ ui.label("Min:");
ui.text_edit_singleline(&mut self.search_scalars_min);
});
ui.horizontal(|ui| {
- ui.label("Max:");
+ ui.label("Max:");
ui.text_edit_singleline(&mut self.search_scalars_max);
});
ui.horizontal(|ui| {
- if ui.button("Cancel").clicked() {
+ if ui.button("Cancel").clicked() {
self.show_search_scalars_dialog = false;
}
- if ui.button("Search").clicked() {
+ if ui.button("Search").clicked() {
match self.run_search_scalars() {
Ok(()) => self.show_search_scalars_dialog = false,
Err(e) => {
- self.status = format!("error: {e}");
+ self.status = format!("error: {e}");
self.log_error(self.status.clone());
}
}
@@ -9492,32 +9497,32 @@ impl eframe::App for GhidrustApp {
});
}
- // Search → Instruction Patterns
+ // Search → Instruction Patterns
if self.show_search_insn_dialog {
- egui::Window::new("Search Instruction Patterns")
+ egui::Window::new("Search Instruction Patterns")
.collapsible(false)
.resizable(true)
.default_width(420.0)
.anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0])
.show(ctx, |ui| {
- ui.small("Matches against decoded listing rows. Empty field = don't filter.");
+ ui.small("Matches against decoded listing rows. Empty field = don't filter.");
ui.horizontal(|ui| {
- ui.label("Mnemonic:");
+ ui.label("Mnemonic:");
ui.text_edit_singleline(&mut self.search_insn_mnemonic);
});
ui.horizontal(|ui| {
- ui.label("Operands:");
+ ui.label("Operands:");
ui.text_edit_singleline(&mut self.search_insn_operands);
});
ui.horizontal(|ui| {
- if ui.button("Cancel").clicked() {
+ if ui.button("Cancel").clicked() {
self.show_search_insn_dialog = false;
}
- if ui.button("Search").clicked() {
+ if ui.button("Search").clicked() {
match self.run_search_instruction_patterns() {
Ok(()) => self.show_search_insn_dialog = false,
Err(e) => {
- self.status = format!("error: {e}");
+ self.status = format!("error: {e}");
self.log_error(self.status.clone());
}
}
@@ -9526,45 +9531,45 @@ impl eframe::App for GhidrustApp {
});
}
- // Add Equate dialog (Ghidra `EquateTablePlugin` → Convert → Equate).
+ // Add Equate dialog .
if self.show_equate_dialog {
let mut close = false;
- egui::Window::new("Set Equate")
+ egui::Window::new("Set Equate")
.collapsible(false)
.resizable(false)
.anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0])
.show(ctx, |ui| {
- ui.small("Bind a name to a scalar operand (Ghidra `EquateTablePlugin`).");
+ ui.small("Bind a name to a scalar operand .");
ui.horizontal(|ui| {
- ui.label("VA:");
+ ui.label("VA:");
let mut input = self
.equate_dialog_va
- .map(|v| format!("{v:#x}"))
+ .map(|v| format!("{v:#x}"))
.unwrap_or_default();
if ui.text_edit_singleline(&mut input).lost_focus() {
self.equate_dialog_va = parse_address(&input).ok();
}
});
ui.horizontal(|ui| {
- ui.label("Operand index:");
- let mut s = format!("{}", self.equate_dialog_op);
+ ui.label("Operand index:");
+ let mut s = format!("{}", self.equate_dialog_op);
if ui.text_edit_singleline(&mut s).lost_focus() {
self.equate_dialog_op = s.trim().parse().unwrap_or(self.equate_dialog_op);
}
});
ui.horizontal(|ui| {
- ui.label("Name:");
+ ui.label("Name:");
ui.text_edit_singleline(&mut self.equate_dialog_name);
});
ui.horizontal(|ui| {
- ui.label("Value (dec / hex):");
+ ui.label("Value (dec / hex):");
ui.text_edit_singleline(&mut self.equate_dialog_value);
});
ui.horizontal(|ui| {
- if ui.button("Cancel").clicked() {
+ if ui.button("Cancel").clicked() {
close = true;
}
- if ui.button("Apply").clicked() {
+ if ui.button("Apply").clicked() {
let value = self
.parse_scalar_input(&self.equate_dialog_value.clone())
.unwrap_or(0);
@@ -9575,7 +9580,7 @@ impl eframe::App for GhidrustApp {
self.equate_dialog_name.clone(),
value,
) {
- self.status = format!("error: {e}");
+ self.status = format!("error: {e}");
self.log_error(self.status.clone());
} else {
close = true;
@@ -9591,48 +9596,58 @@ impl eframe::App for GhidrustApp {
}
}
- // Search results window
+ // Search results window
if self.show_search_results {
- egui::Window::new("Search Results")
+ egui::Window::new("Search Results")
.collapsible(true)
.resizable(true)
.default_width(480.0)
.default_height(280.0)
.show(ctx, |ui| {
- if ui.button("Close").clicked() {
+ if ui.button("Close").clicked() {
self.show_search_results = false;
}
ui.separator();
egui::ScrollArea::vertical().show(ui, |ui| {
for h in self.memory_hits.clone() {
if ui
- .button(format!("{:#x} {} +{:#x}", h.va, h.block, h.offset_in_block))
+ .button(format!("{:#x} {} +{:#x}", h.va, h.block, h.offset_in_block))
.clicked()
{
- let _ = self.goto_address_str(&format!("{:#x}", h.va));
+ let _ = self.goto_address_str(&format!("{:#x}", h.va));
}
}
for h in self.text_hits.clone() {
let label = match h.va {
- Some(va) => format!("[{}] {:#x}: {}", h.kind, va, h.text),
- None => format!("[{}] {}", h.kind, h.text),
+ Some(va) => format!("[{}] {:#x}: {}", h.kind, va, h.text),
+ None => format!("[{}] {}", h.kind, h.text),
};
if ui.button(label).clicked() {
if let Some(va) = h.va {
- let _ = self.goto_address_str(&format!("{va:#x}"));
+ let _ = self.goto_address_str(&format!("{va:#x}"));
}
}
}
if self.memory_hits.is_empty() && self.text_hits.is_empty() {
- ui.weak("No hits.");
+ ui.weak("No hits.");
}
});
});
}
- // Tools → Processor options
+ // Listing → Decode options
+ if ui_options_dialog(
+ ctx,
+ &mut self.show_decode_options_dialog,
+ &mut self.decode_opts,
+ self.program.as_ref(),
+ ) {
+ self.apply_decode_opts();
+ }
+
+ // Tools → Processor options
if self.show_processor_dialog {
- egui::Window::new("Processor Options")
+ egui::Window::new("Processor Options")
.collapsible(false)
.resizable(true)
.default_width(440.0)
@@ -9640,40 +9655,40 @@ impl eframe::App for GhidrustApp {
.show(ctx, |ui| {
if let Some(prog) = &self.program {
let info = processor_info(prog);
- ui.monospace(format!("Language: {}", info.language));
- ui.monospace(format!("Compiler: {}", info.compiler));
- ui.monospace(format!("Format: {}", info.format));
- ui.monospace(format!("Endian: {}", info.endian));
- ui.monospace(format!("Pointer size: {} bytes", info.pointer_size));
- ui.monospace(format!("Image base: {:#x}", info.image_base));
+ ui.monospace(format!("Language: {}", info.language));
+ ui.monospace(format!("Compiler: {}", info.compiler));
+ ui.monospace(format!("Format: {}", info.format));
+ ui.monospace(format!("Endian: {}", info.endian));
+ ui.monospace(format!("Pointer size: {} bytes", info.pointer_size));
+ ui.monospace(format!("Image base: {:#x}", info.image_base));
ui.monospace(format!(
- "Entry: {}",
+ "Entry: {}",
info.entry
- .map(|e| format!("{e:#x}"))
- .unwrap_or_else(|| "—".into())
+ .map(|e| format!("{e:#x}"))
+ .unwrap_or_else(|| "—".into())
));
ui.separator();
ui.small(&info.notes);
ui.separator();
- ui.label("Sections:");
+ ui.label("Sections:");
egui::ScrollArea::vertical().max_height(160.0).show(ui, |ui| {
for s in &prog.sections {
ui.monospace(format!(
- "{} va={:#x} vsize={:#x}",
+ "{} va={:#x} vsize={:#x}",
s.name, s.va, s.virtual_size
));
}
});
} else {
- ui.weak("Load a program to view processor / language options.");
+ ui.weak("Load a program to view processor / language options.");
}
- if ui.button("Close").clicked() {
+ if ui.button("Close").clicked() {
self.show_processor_dialog = false;
}
});
}
- // Analysis → GPU Decompile…
+ // Analysis → GPU Decompile…
if self.show_gpu_decompile_dialog {
let t = m3_tokens(self.theme);
let muted = Color32::from_rgb(
@@ -9684,7 +9699,7 @@ impl eframe::App for GhidrustApp {
let mut close = false;
let mut run_clicked = false;
let has_program = self.program.is_some();
- egui::Window::new("GPU Decompile")
+ egui::Window::new("GPU Decompile")
.collapsible(false)
.resizable(true)
.default_width(560.0)
@@ -9696,8 +9711,8 @@ impl eframe::App for GhidrustApp {
muted,
);
if !has_program {
- ui.weak("No program loaded.");
- } else if ui.button("Resolve + Decompile").clicked() {
+ ui.weak("No program loaded.");
+ } else if ui.button("Resolve + Decompile").clicked() {
run_clicked = true;
}
tool_panes::ui_gpu_decompile_dialog_result(
@@ -9706,7 +9721,7 @@ impl eframe::App for GhidrustApp {
muted,
);
ui.separator();
- if ui.button("Close").clicked() {
+ if ui.button("Close").clicked() {
close = true;
}
});
@@ -9721,7 +9736,7 @@ impl eframe::App for GhidrustApp {
if self.show_analysis_dialog && self.analysis_job.is_none() {
let t = m3_tokens(self.theme);
let primary = Color32::from_rgb(t.primary[0], t.primary[1], t.primary[2]);
- egui::Window::new("Analysis options")
+ egui::Window::new("Analysis options")
.collapsible(false)
.resizable(true)
.default_width(460.0)
@@ -9735,27 +9750,27 @@ impl eframe::App for GhidrustApp {
.map(|f| f.display_name.as_str())
.unwrap_or(id.as_str());
ui.label(
- egui::RichText::new(format!("Target: {name}"))
+ egui::RichText::new(format!("Target: {name}"))
.strong()
.color(primary),
);
ui.add_space(4.0);
}
- ui.label("Select analyzers (Ghidra-compatible labels):");
+ ui.label("Select analyzers (labels):");
ui.horizontal(|ui| {
- if ui.small_button("Select defaults").clicked() {
+ if ui.small_button("Select defaults").clicked() {
for (i, info) in self.analyzer_infos.iter().enumerate() {
self.analyzer_enabled[i] = info.default_enabled;
}
}
- if ui.small_button("Select all").clicked() {
+ if ui.small_button("Select all").clicked() {
for e in &mut self.analyzer_enabled {
- *e = true;
+ *e = true;
}
}
- if ui.small_button("Clear all").clicked() {
+ if ui.small_button("Clear all").clicked() {
for e in &mut self.analyzer_enabled {
- *e = false;
+ *e = false;
}
}
});
@@ -9765,44 +9780,44 @@ impl eframe::App for GhidrustApp {
ui.checkbox(&mut self.analyzer_enabled[i], &info.name);
match info.status {
ghidrust_core::AnalyzerStatus::Implemented => {
- ui.weak("ready");
+ ui.weak("ready");
}
ghidrust_core::AnalyzerStatus::NotImplemented => {
- ui.weak("stub");
+ ui.weak("stub");
}
}
- // Per-row GPU indicator (master checkbox gates actual use).
+ // Per-row GPU indicator (master checkbox gates actual use).
let supports = analyzer_supports_gpu(&info.name);
if supports && self.use_gpu_experimental {
ui.label(
- egui::RichText::new("GPU")
+ egui::RichText::new("GPU")
.small()
.strong()
.color(primary),
)
.on_hover_text(
- "Master GPU is on — this analyzer will use its GPU \
+ "Master GPU is on — this analyzer will use its GPU \
strategy (bulk and/or seed enrich). Falls back to CPU \
- on failure.",
+ on failure.",
);
} else if supports {
ui.label(
- egui::RichText::new("GPU")
+ egui::RichText::new("GPU")
.small()
.color(Color32::from_rgb(120, 120, 128)),
)
.on_hover_text(
- "GPU strategy available — enable the master GPU checkbox \
- to use it. Currently CPU.",
+ "GPU strategy available — enable the master GPU checkbox \
+ to use it. Currently CPU.",
);
} else {
ui.label(
- egui::RichText::new("CPU only")
+ egui::RichText::new("CPU only")
.small()
.color(Color32::from_rgb(120, 120, 128)),
)
.on_hover_text(
- "No GPU strategy for this analyzer — always runs on CPU.",
+ "No GPU strategy for this analyzer — always runs on CPU.",
);
}
});
@@ -9811,20 +9826,20 @@ impl eframe::App for GhidrustApp {
ui.separator();
ui.checkbox(
&mut self.use_gpu_experimental,
- "GPU (only analyzers with a GPU strategy)",
+ "GPU (only analyzers with a GPU strategy)",
);
ui.small(
- "wgpu when available: GPU bulk / SIMT seed enrich only for analyzers \
+ "wgpu when available: GPU bulk / SIMT seed enrich only for analyzers \
marked GPU above (see strategy matrix). Others stay CPU-only. \
Large images are multi-dispatch chunked (≤65535 workgroups). \
- Falls back to CPU on failure. GPU decompile is a separate tool.",
+ Falls back to CPU on failure. GPU decompile is a separate tool.",
);
ui.add_space(8.0);
ui.horizontal(|ui| {
let can_run = self.analyzer_enabled.iter().any(|e| *e)
&& (self.program.is_some() || self.pending_analyze_file_id.is_some());
if ui
- .add_enabled(can_run, egui::Button::new("Run Analysis"))
+ .add_enabled(can_run, egui::Button::new("Run Analysis"))
.clicked()
{
match self.begin_analysis_job() {
@@ -9832,12 +9847,12 @@ impl eframe::App for GhidrustApp {
self.show_analysis_dialog = false;
}
Err(e) => {
- self.status = format!("error: {e}");
+ self.status = format!("error: {e}");
self.log(self.status.clone());
}
}
}
- if ui.button("Cancel").clicked() {
+ if ui.button("Cancel").clicked() {
self.pending_analyze_file_id = None;
self.show_analysis_dialog = false;
}
@@ -9845,7 +9860,7 @@ impl eframe::App for GhidrustApp {
});
}
- // Floating M3 progress card while analysis runs
+ // Floating M3 progress card while analysis runs
if let Some(frac) = self.analysis_progress_fraction() {
let t = m3_tokens(self.theme);
let primary = Color32::from_rgb(t.primary[0], t.primary[1], t.primary[2]);
@@ -9856,7 +9871,7 @@ impl eframe::App for GhidrustApp {
t.surface_container[2],
)
.gamma_multiply(1.4);
- egui::Window::new("Analysis progress")
+ egui::Window::new("Analysis progress")
.collapsible(false)
.resizable(false)
.anchor(egui::Align2::CENTER_BOTTOM, [0.0, -48.0])
@@ -9870,21 +9885,21 @@ impl eframe::App for GhidrustApp {
.names
.get(job.index)
.map(|s| s.as_str())
- .unwrap_or("finishing…");
+ .unwrap_or("finishing…");
ui.label(
- egui::RichText::new(format!("{} — {step}/{n}", job.file_label))
+ egui::RichText::new(format!("{} — {step}/{n}", job.file_label))
.color(on_surface)
.strong(),
);
ui.label(egui::RichText::new(cur).color(primary).small());
if job.use_gpu {
- ui.small("GPU experimental bulk path enabled");
+ ui.small("GPU experimental bulk path enabled");
}
}
ui.add_space(6.0);
m3_linear_progress(ui, frac, primary, track);
ui.add_space(2.0);
- ui.small(format!("{:.0}%", frac * 100.0));
+ ui.small(format!("{:.0}%", frac * 100.0));
});
}
}
@@ -9898,135 +9913,135 @@ mod tests {
#[test]
fn shell_has_required_menus_and_panes() {
let menus = GhidrustApp::shell_menus();
- // Ghidra top-level menus (from `docking.tool.ToolConstants`).
+ // top-level menus (from `docking.tool.ToolConstants`).
for m in [
- "File",
- "Edit",
- "Analysis",
- "Navigation",
- "Search",
- "Select",
- "Tools",
- "Graph",
- "Window",
- "Help",
+ "File",
+ "Edit",
+ "Analysis",
+ "Navigation",
+ "Search",
+ "Select",
+ "Tools",
+ "Graph",
+ "Window",
+ "Help",
] {
- assert!(menus.contains(&m), "missing menu {m}");
+ assert!(menus.contains(&m), "missing menu {m}");
}
let panes = GhidrustApp::shell_panes();
for p in [
- "Project Tree",
- "Program Tree",
- "Symbol Tree",
- "Overview",
- "Listing",
- "Decompiler",
- "Console",
+ "Project Tree",
+ "Program Tree",
+ "Symbol Tree",
+ "Overview",
+ "Listing",
+ "Decompiler",
+ "Console",
] {
- assert!(panes.contains(&p), "missing pane {p}");
+ assert!(panes.contains(&p), "missing pane {p}");
}
- // Project Tree ≠ Program Tree
+ // Project Tree ≠ Program Tree
assert_ne!(
- panes.iter().position(|p| *p == "Project Tree"),
- panes.iter().position(|p| *p == "Program Tree")
+ panes.iter().position(|p| *p == "Project Tree"),
+ panes.iter().position(|p| *p == "Program Tree")
);
}
- /// every Ghidra CodeBrowser provider must be enumerated in
- /// `shell_panes()` so the Window menu / structural tests can enforce visibility parity.
+ /// every provider must be enumerated in
+ /// `shell_panes` so the Window menu / structural tests can enforce provider visibility.
#[test]
- fn shell_panes_enumerates_full_ghidra_codebrowser_catalog() {
+ fn shell_panes_enumerates_full_codebrowser_catalog() {
let panes = GhidrustApp::shell_panes();
- // 28 default `CodeBrowser.tool` providers + a few off-layout ones. See
- // internal UI notes § 1.1 / § 1.2 for the source of truth.
+ // 28 default `.tool` providers + a few off-layout ones. See
+ // internal UI notes § 1.1 / § 1.2 for the source of truth.
for expected in [
- "Program Trees",
- "Symbol Tree",
- "Data Type Manager",
- "Listing",
- "Decompile",
- "Bytes",
- "Defined Data",
- "Defined Strings",
- "Equates Table",
- "External Programs",
- "Functions",
- "Relocation Table",
- "Data Type Preview",
- "Disassembled View",
- "Console",
- "Bookmarks",
- "Script Manager",
- "Memory Map",
- "Function Graph",
- "Register Manager",
- "Symbol Table",
- "Symbol References",
- "Checksum Generator",
- "Function Tags",
- "Comments",
- "Python",
- "Entropy",
- "Overview",
- // Off-layout, reached via Window menu
- "Function Call Trees",
- "Function Call Graph",
- "Text Editor",
+ "Program Trees",
+ "Symbol Tree",
+ "Data Type Manager",
+ "Listing",
+ "Decompile",
+ "Bytes",
+ "Defined Data",
+ "Defined Strings",
+ "Equates Table",
+ "External Programs",
+ "Functions",
+ "Relocation Table",
+ "Data Type Preview",
+ "Disassembled View",
+ "Console",
+ "Bookmarks",
+ "Script Manager",
+ "Memory Map",
+ "Function Graph",
+ "Register Manager",
+ "Symbol Table",
+ "Symbol References",
+ "Checksum Generator",
+ "Function Tags",
+ "Comments",
+ "Python",
+ "Entropy",
+ "Overview",
+ // Off-layout, reached via Window menu
+ "Function Call Trees",
+ "Function Call Graph",
+ "Text Editor",
] {
assert!(
panes.contains(&expected),
- "missing Ghidra provider `{expected}` in shell_panes(); full list = {panes:?}"
+ "missing provider `{expected}` in shell_panes; full list = {panes:?}"
);
}
}
- /// Back / Forward history is wired.
+ /// Back / Forward history is wired.
#[test]
fn nav_history_records_and_navigates() {
let mut app = GhidrustApp::headless();
- app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
assert!(!app.can_nav_back());
assert!(!app.can_nav_forward());
- // Two goto() calls (both valid VAs inside the loaded listing window)
- // put one entry in the Back history.
+ // Two goto calls (both valid VAs inside the loaded listing window)
+ // put one entry in the Back history.
let entry = app.program.as_ref().and_then(|p| p.entry).unwrap();
- // A second VA that is inside the loaded listing so re-disassemble isn't required.
+ // A second VA that is inside the loaded listing so re-disassemble isn't required.
let second_va = app
.listing
.iter()
.map(|i| i.address)
.find(|&va| va > entry)
.unwrap_or(entry + 1);
- app.goto_address_str(&format!("{entry:#x}")).expect("goto entry");
- app.goto_address_str(&format!("{second_va:#x}")).expect("goto second");
- assert!(app.can_nav_back(), "back should be available after 2 goto()s");
+ app.goto_address_str(&format!("{entry:#x}")).expect("goto entry");
+ app.goto_address_str(&format!("{second_va:#x}")).expect("goto second");
+ assert!(app.can_nav_back, "back should be available after 2 gotos");
assert!(!app.can_nav_forward());
- // Back → returns to entry
- assert!(app.nav_back(), "nav_back should succeed");
+ // Back → returns to entry
+ assert!(app.nav_back, "nav_back should succeed");
assert_eq!(app.listing_focus_va, Some(entry));
assert!(app.can_nav_forward());
- // Forward → returns to second_va
- assert!(app.nav_forward(), "nav_forward should succeed");
+ // Forward → returns to second_va
+ assert!(app.nav_forward, "nav_forward should succeed");
assert_eq!(app.listing_focus_va, Some(second_va));
}
- /// Bookmarks pane model is real (5 Ghidra kinds; add/delete flow).
+ /// Bookmarks pane model is real (5 kinds; add/delete flow).
#[test]
fn bookmark_model_add_delete_and_nav() {
let mut app = GhidrustApp::headless();
- app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
assert!(app.bookmarks.is_empty());
let entry = app.program.as_ref().and_then(|p| p.entry).unwrap();
- app.add_bookmark(entry, BookmarkKind::Note, "user", "entry point");
- app.add_bookmark(entry + 0x10, BookmarkKind::Analysis, "core", "hot loop");
+ app.add_bookmark(entry, BookmarkKind::Note, "user", "entry point");
+ app.add_bookmark(entry + 0x10, BookmarkKind::Analysis, "core", "hot loop");
assert_eq!(app.bookmarks.len(), 2);
assert!(app.is_pane_open(PaneKind::Bookmarks));
- // Next / Prev bookmark navigation works.
+ // Next / Prev bookmark navigation works.
app.listing_focus_va = Some(entry);
app.nav_next_bookmark();
assert_eq!(app.listing_focus_va, Some(entry + 0x10));
@@ -10037,35 +10052,35 @@ mod tests {
assert_eq!(app.bookmarks.len(), 1);
assert_eq!(app.bookmarks[0].va, entry + 0x10);
- // All 5 Ghidra bookmark kinds are colourable.
+ // All 5 bookmark kinds are colourable.
for k in BookmarkKind::ALL {
let c = k.color();
assert!(c.a() > 0 && (c.r() as u16 + c.g() as u16 + c.b() as u16) > 0);
}
}
- /// 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();
- app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
- // Loading emits ProgramActivated; drain baseline.
+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
+ // Loading emits ProgramActivated; drain baseline.
let boot = app.drain_events();
assert!(
boot.iter().any(|e| matches!(e, GhidrustEvent::ProgramActivated { .. })),
- "load_binary must publish ProgramActivated: {boot:?}"
+ "load_binary must publish ProgramActivated: {boot:?}"
);
let entry = app.program.as_ref().and_then(|p| p.entry).unwrap();
- app.goto_address_str(&format!("{entry:#x}")).expect("goto");
+ app.goto_address_str(&format!("{entry:#x}")).expect("goto");
let evs = app.drain_events();
assert!(
evs.iter()
.any(|e| matches!(e, GhidrustEvent::CursorMoved { .. })),
- "goto_address_str must publish CursorMoved: {evs:?}"
+ "goto_address_str must publish CursorMoved: {evs:?}"
);
- app.add_bookmark(entry, BookmarkKind::Note, "test", "hi");
+ app.add_bookmark(entry, BookmarkKind::Note, "test", "hi");
let evs = app.drain_events();
assert!(
evs.iter().any(|e| matches!(
@@ -10074,7 +10089,7 @@ mod tests {
kind: MutationKind::BookmarkAdded { .. }
}
)),
- "add_bookmark must publish BookmarkAdded: {evs:?}"
+ "add_bookmark must publish BookmarkAdded: {evs:?}"
);
app.delete_bookmark(0);
@@ -10086,19 +10101,19 @@ mod tests {
kind: MutationKind::BookmarkRemoved { .. }
}
)),
- "delete_bookmark must publish BookmarkRemoved: {evs:?}"
+ "delete_bookmark must publish BookmarkRemoved: {evs:?}"
);
- // Drain again → empty.
+ // Drain again → empty.
assert!(app.drain_events().is_empty());
}
- /// 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();
for k in PaneKind::ALL {
- assert!(!app.is_pane_open(*k), "pane {:?} default should be closed", k);
+ assert!(!app.is_pane_open(*k), "pane {:?} default should be closed", k);
}
app.toggle_pane(PaneKind::MemoryMap, true);
app.toggle_pane(PaneKind::SymbolTable, true);
@@ -10112,35 +10127,35 @@ mod tests {
#[test]
fn project_tree_open_and_status_via_shipped_apis() {
let dir = std::env::temp_dir().join(format!(
- "ghidrust_ptree_{}",
+ "ghidrust_ptree_{}",
std::process::id()
));
let _ = std::fs::remove_dir_all(&dir);
let mut app = GhidrustApp::headless();
app.project_dir_input = dir.display().to_string();
- app.project_name_input = "TreeUX".into();
- app.create_project().expect("create");
+ app.project_name_input = "TreeUX".into();
+ app.create_project.expect("create");
assert!(app.show_project_tree);
- app.path_input = fixture_path("tiny_x64.pe").display().to_string();
- app.import_into_project().expect("import tiny");
- app.path_input = fixture_path("analysis_lab.pe").display().to_string();
- app.import_into_project().expect("import lab");
+ app.path_input = fixture_path("tiny_x64.pe").display.to_string();
+ app.import_into_project.expect("import tiny");
+ app.path_input = fixture_path("analysis_lab.pe").display.to_string();
+ app.import_into_project.expect("import lab");
- let tree = app.project_tree_model().expect("tree model");
- assert_eq!(tree.project_name, "TreeUX");
+ let tree = app.project_tree_model.expect("tree model");
+ assert_eq!(tree.project_name, "TreeUX");
assert_eq!(tree.files.len(), 2);
assert!(tree.files.iter().any(|f| f.active));
assert!(tree.files.iter().all(|f| !f.has_saved_analysis));
- assert_eq!(tree.files[0].status_label(), "Not analyzed");
+ assert_eq!(tree.files[0].status_label, "Not analyzed");
let lab_id = tree
.files
.iter()
- .find(|f| f.display_name.contains("analysis_lab"))
+ .find(|f| f.display_name.contains("analysis_lab"))
.map(|f| f.id.clone())
- .expect("lab id");
- app.open_from_tree(&lab_id).expect("open from tree");
+ .expect("lab id");
+ app.open_from_tree(&lab_id).expect("open from tree");
assert_eq!(app.active_file_id.as_deref(), Some(lab_id.as_str()));
assert!(app.program.is_some());
let tree2 = app.project_tree_model().unwrap();
@@ -10148,40 +10163,40 @@ mod tests {
for (i, info) in app.analyzer_infos.iter().enumerate() {
app.analyzer_enabled[i] =
- matches!(info.name.as_str(), "Function Start Search" | "Embedded Media");
+ matches!(info.name().as_str(), "Function Start Search" | "Embedded Media");
}
- // Analyze from tree opens options dialog (does not run yet).
- app.analyze_from_tree(&lab_id).expect("open analyze options");
+ // Analyze from tree opens options dialog (does not run yet).
+ app.analyze_from_tree(&lab_id).expect("open analyze options");
assert!(app.show_analysis_dialog);
assert_eq!(app.pending_analyze_file_id.as_deref(), Some(lab_id.as_str()));
app.use_gpu_experimental = true;
- app.begin_analysis_job().expect("begin");
+ app.begin_analysis_job.expect("begin");
assert!(app.analysis_job.is_some());
assert!(app.analysis_progress_fraction().is_some());
while app.analysis_job.is_some() {
- app.step_analysis_job_blocking().expect("step");
+ app.step_analysis_job_blocking.expect("step");
}
assert!(app.analysis_progress_fraction().is_none());
let tree3 = app.project_tree_model().unwrap();
let lab_row = tree3.files.iter().find(|f| f.id == lab_id).unwrap();
- assert!(lab_row.has_saved_analysis, "{lab_row:?}");
- assert_eq!(lab_row.status_label(), "Analyzed");
+ assert!(lab_row.has_saved_analysis, "{lab_row:?}");
+ assert_eq!(lab_row.status_label, "Analyzed");
- // Second run of status query consistent
+ // Second run of status query consistent
let tree4 = app.project_tree_model().unwrap();
assert_eq!(
tree3.files.iter().map(|f| f.has_saved_analysis).collect::<Vec<_>>(),
tree4.files.iter().map(|f| f.has_saved_analysis).collect::<Vec<_>>()
);
- // Delete requires confirm: request only sets pending; confirm removes.
+ // Delete requires confirm: request only sets pending; confirm removes.
app.request_delete_file(&lab_id);
assert!(app.pending_delete.is_some());
app.cancel_delete_file();
assert!(app.pending_delete.is_none());
assert_eq!(app.project_tree_model().unwrap().files.len(), 2);
app.request_delete_file(&lab_id);
- app.confirm_delete_file().expect("confirm delete");
+ app.confirm_delete_file.expect("confirm delete");
assert!(app.pending_delete.is_none());
let after = app.project_tree_model().unwrap();
assert_eq!(after.files.len(), 1);
@@ -10197,44 +10212,44 @@ mod tests {
app.theme = app.theme.toggle();
assert_eq!(app.theme, ThemeMode::Light);
- let pe = fixture_path("tiny_x64.pe");
- app.load_binary(&pe).expect("load");
- assert!(app.listing.iter().any(|i| i.mnemonic == "push"));
+ let pe = fixture_path("tiny_x64.pe");
+ app.load_binary(&pe).expect("load");
+ assert!(app.listing.iter().any(|i| i.mnemonic == "push"));
for (i, info) in app.analyzer_infos.iter().enumerate() {
app.analyzer_enabled[i] = matches!(
- info.name.as_str(),
- "ASCII Strings" | "WindowsPE x86 PE RTTI Analyzer"
+ info.name().as_str(),
+ "ASCII Strings" | "WindowsPE x86 PE RTTI Analyzer"
);
}
- app.run_selected_analysis().expect("analyze");
- assert!(app.rtti.classes.iter().any(|c| c.name == "Widget"));
+ app.run_selected_analysis.expect("analyze");
+ assert!(app.rtti.classes.iter().any(|c| c.name() == "Widget"));
assert!(!app.strings.is_empty());
assert_eq!(app.analyzer_infos.len(), ANALYZER_NAMES.len());
}
#[test]
fn headless_stage0_decompiler_wires_on_focus() {
- // 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.
+ // Stage-1 is the GUI default. The old assertion demanded a
+ // Stage-0-style `void foo` / `block_N` marker; Stage-1 emits typed
+ // return values (e.g. `uint32_t FUN_..(void)`) so we accept either
+ // stage marker plus the Stage-1 self-identification header.
let mut app = GhidrustApp::headless();
- app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
- assert!(!app.decomp_text.is_empty(), "load should seed decompiler text");
- assert!(!app.decomp_text.contains("Not yet implemented"));
+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
+ assert!(!app.decomp_text.is_empty(), "load should seed decompiler text");
+ assert!(!app.decomp_text.contains("Not yet implemented"));
let va = app.listing[0].address;
app.refresh_decompiler_at(va);
assert!(app.decomp_entry.is_some());
let text = &app.decomp_text;
assert!(
- text.contains("void ")
- || text.contains("uint")
- || text.contains("int32_t")
- || text.contains("int64_t")
- || text.contains("block_"),
- "expected typed function header or block label:\n{text}"
+ text.contains("void ")
+ || text.contains("uint")
+ || text.contains("int32_t")
+ || text.contains("int64_t")
+ || text.contains("block_"),
+ "expected typed function header or block label:\n{text}"
);
let entry = app.decomp_entry.unwrap();
@@ -10246,107 +10261,107 @@ mod tests {
#[test]
fn headless_project_import_analyze_save() {
- let dir = std::env::temp_dir().join(format!("ghidrust_gui_proj_{}", std::process::id()));
+ let dir = std::env::temp_dir().join(format!("ghidrust_gui_proj_{}", std::process::id));
let _ = std::fs::remove_dir_all(&dir);
let mut app = GhidrustApp::headless();
app.project_dir_input = dir.display().to_string();
- app.project_name_input = "GuiTest".into();
- app.create_project().expect("create");
- app.path_input = fixture_path("analysis_lab.pe").display().to_string();
- app.import_into_project().expect("import");
+ app.project_name_input = "GuiTest".into();
+ app.create_project.expect("create");
+ app.path_input = fixture_path("analysis_lab.pe").display.to_string();
+ app.import_into_project.expect("import");
assert!(app.program.is_some());
for (i, info) in app.analyzer_infos.iter().enumerate() {
app.analyzer_enabled[i] =
- matches!(info.name.as_str(), "Function Start Search" | "Embedded Media");
+ matches!(info.name().as_str(), "Function Start Search" | "Embedded Media");
}
- app.run_selected_analysis().expect("analyze");
- app.save_results().expect("save");
+ app.run_selected_analysis.expect("analyze");
+ app.save_results.expect("save");
let id = app.active_file_id.clone().unwrap();
let proj = app.project.as_ref().unwrap();
assert!(proj.analysis_path(&id).is_file());
assert!(proj.listing_export_path(&id).is_file());
- // reopen
+ // reopen
let mut app2 = GhidrustApp::headless();
app2.project_dir_input = dir.display().to_string();
- app2.open_project().expect("reopen");
+ app2.open_project.expect("reopen");
assert!(app2.program.is_some());
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn source_embeds_m3_and_menus() {
- // Structural: shipped source contains theme toggle + menus (fallback evidence).
- let src = include_str!("main.rs");
- assert!(src.contains("Theme: Dark") || src.contains("ThemeMode"));
- assert!(src.contains("menu_button(\"File\""));
- assert!(src.contains("Program Tree"));
- assert!(src.contains("Project Tree") || src.contains("project_tree"));
- assert!(src.contains("Decompiler"));
- assert!(src.contains("refresh_decompiler_at") || src.contains("stage0_pseudo_c"));
- assert!(src.contains("focus_function"));
- assert!(src.contains("Stage-0"));
- assert!(src.contains("decomp_scroll") || src.contains("decomp_text"));
- assert!(src.contains("ASCII Strings"));
- assert!(src.contains("Analyzed") || src.contains("has_saved_analysis"));
- assert!(src.contains("analyze_from_tree") || src.contains("small_button(\"Analyze\")"));
- assert!(src.contains("Browse") || src.contains("browse_binary_path") || src.contains("rfd::"));
- assert!(src.contains("pending_delete") || src.contains("Delete from project"));
- assert!(src.contains("use_gpu_experimental") || src.contains("GPU experimental"));
- assert!(src.contains("analyzer_supports_gpu"));
- assert!(src.contains("CPU only") || src.contains("\"GPU\""));
- assert!(src.contains("m3_linear_progress") || src.contains("Analysis progress"));
- assert!(src.contains("begin_analysis_job") || src.contains("Run Analysis"));
- assert!(src.contains("Overview") || src.contains("ui_overview"));
- assert!(src.contains("show_rows") || src.contains("rtti_filtered_idx"));
- assert!(src.contains("analysis_done_banner") || src.contains("Analysis complete"));
- assert!(src.contains("double_clicked") && src.contains("open_id"));
- assert!(src.contains("show_startup_picker") || src.contains("ui_startup_picker"));
- assert!(src.contains("recent_projects") || src.contains("Open existing project"));
- // No emoji codepoints in this file (Material geometry lives in icons.rs)
- // U+1F4C1 folder, U+25CF/U+25CB bullets, U+25B6 play — use escapes so the
- // forbidden glyphs themselves never appear in source.
- assert!(!src.contains('\u{1F4C1}'));
- assert!(!src.contains('\u{25CF}'));
- assert!(!src.contains('\u{25CB}'));
- assert!(!src.contains('\u{25B6}'));
+ // Structural: shipped source contains theme toggle + menus (fallback evidence).
+ let src = include_str!("main.rs");
+ assert!(src.contains("Theme: Dark") || src.contains("ThemeMode"));
+ assert!(src.contains("menu_button(\"File\""));
+ assert!(src.contains("Program Tree"));
+ assert!(src.contains("Project Tree") || src.contains("project_tree"));
+ assert!(src.contains("Decompiler"));
+ assert!(src.contains("refresh_decompiler_at") || src.contains("stage0_pseudo_c"));
+ assert!(src.contains("focus_function"));
+ assert!(src.contains("Stage-0"));
+ assert!(src.contains("decomp_scroll") || src.contains("decomp_text"));
+ assert!(src.contains("ASCII Strings"));
+ assert!(src.contains("Analyzed") || src.contains("has_saved_analysis"));
+ assert!(src.contains("analyze_from_tree") || src.contains("small_button(\"Analyze\")"));
+ assert!(src.contains("Browse") || src.contains("browse_binary_path") || src.contains("rfd::"));
+ assert!(src.contains("pending_delete") || src.contains("Delete from project"));
+ assert!(src.contains("use_gpu_experimental") || src.contains("GPU experimental"));
+ assert!(src.contains("analyzer_supports_gpu"));
+ assert!(src.contains("CPU only") || src.contains("\"GPU\""));
+ assert!(src.contains("m3_linear_progress") || src.contains("Analysis progress"));
+ assert!(src.contains("begin_analysis_job") || src.contains("Run Analysis"));
+ assert!(src.contains("Overview") || src.contains("ui_overview"));
+ assert!(src.contains("show_rows") || src.contains("rtti_filtered_idx"));
+ assert!(src.contains("analysis_done_banner") || src.contains("Analysis complete"));
+ assert!(src.contains("double_clicked") && src.contains("open_id"));
+ assert!(src.contains("show_startup_picker") || src.contains("ui_startup_picker"));
+ assert!(src.contains("recent_projects") || src.contains("Open existing project"));
+ // No emoji codepoints in this file (Material geometry lives in icons.rs)
+ // U+1F4C1 folder, U+25CF/U+25CB bullets, U+25B6 play — use escapes so the
+ // forbidden glyphs themselves never appear in source.
+ assert!(!src.contains('\u{1F4C1}'));
+ assert!(!src.contains('\u{25CF}'));
+ assert!(!src.contains('\u{25CB}'));
+ assert!(!src.contains('\u{25B6}'));
}
#[test]
fn icons_module_is_material_not_emoji() {
- let icons = include_str!("icons.rs");
- assert!(icons.contains("Material"));
- assert!(icons.contains("Folder") || icons.contains("folder"));
- assert!(!icons.contains('\u{1F4C1}'));
- assert!(!icons.contains('\u{25CF}'));
+ let icons = include_str!("icons.rs");
+ assert!(icons.contains("Material"));
+ assert!(icons.contains("Folder") || icons.contains("folder"));
+ assert!(!icons.contains('\u{1F4C1}'));
+ assert!(!icons.contains('\u{25CF}'));
}
#[test]
fn former_menu_stubs_are_wired_not_nyi_only() {
- let src = include_str!("main.rs");
- // No remaining nyi() for inventoried Edit/Nav/Search/Select/Tools stubs
- assert!(!src.contains("nyi(\"Edit → Undo\")"));
- assert!(!src.contains("nyi(\"Edit → Redo\")"));
- assert!(!src.contains("nyi(\"Edit → Clear selection\")"));
- assert!(!src.contains("nyi(\"Navigation → Go to address\")"));
- assert!(!src.contains("nyi(\"Search → Search memory\")"));
- assert!(!src.contains("nyi(\"Search → Search program text\")"));
- assert!(!src.contains("nyi(\"Select → Select all\")"));
- assert!(!src.contains("nyi(\"Tools → Processor options\")"));
- // Real handlers present
- assert!(src.contains("edit_undo"));
- assert!(src.contains("edit_redo"));
- assert!(src.contains("edit_clear_selection"));
- assert!(src.contains("goto_address_str") || src.contains("show_goto_dialog"));
- assert!(src.contains("run_search_memory"));
- assert!(src.contains("run_search_text"));
- assert!(src.contains("select_all_listing"));
- assert!(src.contains("show_processor_dialog"));
+ let src = include_str!("main.rs");
+ // No remaining nyi for inventoried Edit/Nav/Search/Select/Tools stubs
+ assert!(!src.contains("nyi(\"Edit → Undo\")"));
+ assert!(!src.contains("nyi(\"Edit → Redo\")"));
+ assert!(!src.contains("nyi(\"Edit → Clear selection\")"));
+ assert!(!src.contains("nyi(\"Navigation → Go to address\")"));
+ assert!(!src.contains("nyi(\"Search → Search memory\")"));
+ assert!(!src.contains("nyi(\"Search → Search program text\")"));
+ assert!(!src.contains("nyi(\"Select → Select all\")"));
+ assert!(!src.contains("nyi(\"Tools → Processor options\")"));
+ // Real handlers present
+ assert!(src.contains("edit_undo"));
+ assert!(src.contains("edit_redo"));
+ assert!(src.contains("edit_clear_selection"));
+ assert!(src.contains("goto_address_str") || src.contains("show_goto_dialog"));
+ assert!(src.contains("run_search_memory"));
+ assert!(src.contains("run_search_text"));
+ assert!(src.contains("select_all_listing"));
+ assert!(src.contains("show_processor_dialog"));
}
#[test]
fn menu_actions_goto_search_select_on_loaded_program() {
let mut app = GhidrustApp::headless();
- app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
assert!(!app.listing.is_empty());
app.select_all_listing();
@@ -10363,40 +10378,40 @@ mod tests {
assert!(!app.listing_selection.is_empty());
let entry = app.program.as_ref().and_then(|p| p.entry).unwrap();
- app.goto_address_str(&format!("{entry:#x}")).expect("goto");
+ app.goto_address_str(&format!("{entry:#x}")).expect("goto");
assert_eq!(app.listing_focus_va, Some(entry));
assert_eq!(app.center, CenterPane::Listing);
- app.search_memory_input = "55 48 89 e5".into();
- app.run_search_memory().expect("mem search");
+ app.search_memory_input = "55 48 89 e5".into();
+ app.run_search_memory.expect("mem search");
assert!(!app.memory_hits.is_empty());
assert!(app.show_search_results);
- app.search_text_input = "push".into();
- app.run_search_text().expect("text search");
+ app.search_text_input = "push".into();
+ app.run_search_text.expect("text search");
assert!(!app.text_hits.is_empty());
app.show_processor_dialog = true;
let info = processor_info(app.program.as_ref().unwrap());
- assert!(info.language.contains("x86"));
+ assert!(info.language.contains("x86"));
}
- // ─── 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() {
let mut app = GhidrustApp::headless();
- app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
let entry = app.program.as_ref().and_then(|p| p.entry).unwrap();
app.refresh_decompiler_at(entry);
assert!(
!app.decomp_lines.is_empty(),
- "token cache must be populated after refresh_decompiler_at"
+ "token cache must be populated after refresh_decompiler_at"
);
- // 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.
+ // Default GUI stage is Stage-1; the emitter drops
+ // `block_N:` labels in favour of structured regions. Assert only
+ // that we see at least one keyword token — the shape common to
+ // every stage.
let all_tokens: Vec<&TokenKind> = app
.decomp_lines
.iter()
@@ -10404,11 +10419,11 @@ mod tests {
.collect();
assert!(
all_tokens.iter().any(|k| matches!(k, TokenKind::Keyword)),
- "expected at least one Keyword (void/return/etc)"
+ "expected at least one Keyword (void/return/etc)"
);
- // Cross-highlight line should be recomputable and match what the
- // decoder found for the entry VA (may be None if Stage-1 emit
- // stripped per-line addresses, but the field remains consistent).
+ // Cross-highlight line should be recomputable and match what the
+ // decoder found for the entry VA (may be None if Stage-1 emit
+ // stripped per-line addresses, but the field remains consistent).
let ln = decomp_line_for_va(&app.decomp_lines, entry);
assert_eq!(app.decomp_cross_line, ln);
}
@@ -10416,18 +10431,18 @@ mod tests {
#[test]
fn navigate_next_prev_function_wraps() {
let mut app = GhidrustApp::headless();
- app.load_binary(&fixture_path("analysis_lab.pe")).expect("load");
- // Fake up two functions if the analyzer didn't produce any yet.
+ app.load_binary(&fixture_path("analysis_lab.pe")).expect("load");
+ // Fake up two functions if the analyzer didn't produce any yet.
if app.program.as_ref().unwrap().analysis.functions.is_empty() {
let prog = app.program.as_mut().unwrap();
let base = prog.entry.unwrap_or(prog.image_base);
prog.analysis
.functions
- .push(ghidrust_core::FunctionInfo::new(base, base + 0x10, "fn_a"));
+ .push(ghidrust_core::FunctionInfo::new(base, base + 0x10, "fn_a"));
prog.analysis.functions.push(ghidrust_core::FunctionInfo::new(
base + 0x40,
base + 0x50,
- "fn_b",
+ "fn_b",
));
}
let entries: Vec<u64> = app
@@ -10444,25 +10459,25 @@ mod tests {
let first = sorted[0];
app.listing_focus_va = Some(first);
app.nav_next_function();
- // Cursor should have moved to another function entry (or wrapped).
+ // Cursor should have moved to another function entry (or wrapped).
assert!(sorted.contains(&app.listing_focus_va.unwrap()));
}
#[test]
fn program_tree_view_filter_hides_addresses() {
let mut app = GhidrustApp::headless();
- app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
- // Grab a block name & VA.
+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
+ // Grab a block name & VA.
let (block_name, block_va) = {
let p = app.program.as_ref().unwrap();
let b = p.blocks.first().unwrap();
- (b.name.clone(), b.va)
+ (b.name().clone(), b.va)
};
assert!(app.addr_in_view(block_va));
let mut set = BTreeSet::new();
- set.insert("__does_not_exist__".to_string());
+ set.insert("__does_not_exist__".to_string());
app.set_listing_view(Some(set));
- assert!(!app.addr_in_view(block_va), "filter set must hide addr");
+ assert!(!app.addr_in_view(block_va), "filter set must hide addr");
app.add_to_view(block_name.clone());
assert!(app.addr_in_view(block_va));
app.remove_from_view(&block_name);
@@ -10474,11 +10489,11 @@ mod tests {
#[test]
fn imports_exports_are_honest_empty_or_analyzer_derived() {
let mut app = GhidrustApp::headless();
- app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
let (imports, exports) = app.imports_exports();
- // Never panics; results are analyzer-driven not fabricated.
+ // Never panics; results are analyzer-driven not fabricated.
for (va, _name) in imports.iter().chain(exports.iter()) {
- // If any row exists it must be a plausible in-image VA.
+ // If any row exists it must be a plausible in-image VA.
let in_program = app
.program
.as_ref()
@@ -10488,94 +10503,94 @@ mod tests {
}
}
- // ─── rename / retype / comment / signature / type ───
+ // ─── rename / retype / comment / signature / type ───
#[test]
fn rename_persists_and_reflects_in_analysis() {
let mut app = GhidrustApp::headless();
- app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
- // Attach a synthetic function so we have a rename target.
+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
+ // Attach a synthetic function so we have a rename target.
let entry = app.program.as_ref().and_then(|p| p.entry).unwrap();
{
let prog = app.program.as_mut().unwrap();
prog.analysis.functions.push(ghidrust_core::FunctionInfo::new(
entry,
entry + 0x10,
- "FUN_original",
+ "FUN_original",
));
}
- app.rename_at(entry, "my_main").expect("rename");
+ app.rename_at(entry, "my_main").expect("rename");
let p = app.program.as_ref().unwrap();
- assert_eq!(p.edits.rename_at(entry), Some("my_main"));
- assert_eq!(p.function_at(entry).map(|f| f.name.as_str()), Some("my_main"));
+ assert_eq!(p.edits.rename_at(entry), Some("my_main"));
+ assert_eq!(p.function_at(entry).map(|f| f.name().as_str()), Some("my_main"));
assert_eq!(
p.display_function_name_at(entry).as_deref(),
- Some("my_main")
+ Some("my_main")
);
- // Empty rename clears the edit and rejects with error.
- let err = app.rename_at(entry, "");
+ // Empty rename clears the edit and rejects with error.
+ let err = app.rename_at(entry, "");
assert!(err.is_err());
}
#[test]
fn retype_and_comment_and_signature_persist() {
let mut app = GhidrustApp::headless();
- app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
let va = app.program.as_ref().and_then(|p| p.entry).unwrap();
- app.retype_at(va, "int32_t").expect("retype");
- app.set_comment_at(va, CommentKind::Eol, "eol comment").expect("comment");
- app.set_comment_at(va, CommentKind::Plate, "plate!").expect("plate");
- app.set_function_signature(va, "int foo(char *)").expect("sig");
+ app.retype_at(va, "int32_t").expect("retype");
+ app.set_comment_at(va, CommentKind::Eol, "eol comment").expect("comment");
+ app.set_comment_at(va, CommentKind::Plate, "plate!").expect("plate");
+ app.set_function_signature(va, "int foo(char *)").expect("sig");
let p = app.program.as_ref().unwrap();
- assert_eq!(p.edits.retype_at(va), Some("int32_t"));
- assert_eq!(p.edits.comment_at(va, CommentKind::Eol), Some("eol comment"));
- assert_eq!(p.edits.comment_at(va, CommentKind::Plate), Some("plate!"));
+ assert_eq!(p.edits.retype_at(va), Some("int32_t"));
+ assert_eq!(p.edits.comment_at(va, CommentKind::Eol), Some("eol comment"));
+ assert_eq!(p.edits.comment_at(va, CommentKind::Plate), Some("plate!"));
assert_eq!(
p.edits.function_signature(va).map(|s| s.signature.as_str()),
- Some("int foo(char *)")
+ Some("int foo(char *)")
);
}
#[test]
fn commit_params_and_locals_snapshot_analyzer_state() {
let mut app = GhidrustApp::headless();
- app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
let entry = app.program.as_ref().and_then(|p| p.entry).unwrap();
{
let prog = app.program.as_mut().unwrap();
let mut fi =
- ghidrust_core::FunctionInfo::new(entry, entry + 0x40, "with_params");
- fi.calling_convention = Some("windowsx64".into());
- fi.parameters = vec!["rcx".into(), "rdx".into()];
- fi.stack_locals = vec!["local_10".into(), "local_18".into()];
+ ghidrust_core::FunctionInfo::new(entry, entry + 0x40, "with_params");
+ fi.calling_convention = Some("windowsx64".into());
+ fi.parameters = vec!["rcx".into(), "rdx".into()];
+ fi.stack_locals = vec!["local_10".into(), "local_18".into()];
prog.analysis.functions.push(fi);
}
- app.commit_params_return(entry).expect("commit params");
- app.commit_locals(entry).expect("commit locals");
+ app.commit_params_return(entry).expect("commit params");
+ app.commit_locals(entry).expect("commit locals");
let sig = app.program.as_ref().unwrap().edits.function_signature(entry).unwrap();
assert_eq!(sig.parameters.len(), 2);
assert_eq!(sig.locals.len(), 2);
- assert_eq!(sig.return_type.as_deref(), Some("undefined"));
+ assert_eq!(sig.return_type.as_deref(), Some("undefined"));
}
#[test]
fn user_types_and_applied_types_persist() {
let mut app = GhidrustApp::headless();
- app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
- app.define_user_type("Widget", "struct Widget { int id; }").expect("new type");
+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
+ app.define_user_type("Widget", "struct Widget { int id; }").expect("new type");
let va = app.program.as_ref().and_then(|p| p.entry).unwrap();
- app.apply_type_at(va, "Widget").expect("apply");
+ app.apply_type_at(va, "Widget").expect("apply");
let p = app.program.as_ref().unwrap();
- assert!(p.edits.user_types.contains_key("Widget"));
- assert_eq!(p.edits.applied_type_at(va), Some("Widget"));
+ assert!(p.edits.user_types.contains_key("Widget"));
+ assert_eq!(p.edits.applied_type_at(va), Some("Widget"));
}
#[test]
fn dtm_builtins_contain_stage0_types() {
- for want in ["byte", "word", "dword", "qword", "char", "int", "int32_t", "pointer"] {
+ for want in ["byte", "word", "dword", "qword", "char", "int", "int32_t", "pointer"] {
assert!(
BUILTIN_TYPES.contains(&want),
- "expected {want} in DTM Built-In archive"
+ "expected {want} in DTM Built-In archive"
);
}
}
@@ -10583,12 +10598,12 @@ mod tests {
#[test]
fn console_severity_tracks_log_calls() {
let mut app = GhidrustApp::headless();
- // Preseeded with 1 info line.
+ // Preseeded with 1 info line.
assert_eq!(app.console.len(), 1);
assert_eq!(app.console_severity.len(), 1);
- app.log("info");
- app.log_warn("warn");
- app.log_error("boom");
+ app.log("info");
+ app.log_warn("warn");
+ app.log_error("boom");
assert_eq!(
app.console_severity.last().copied(),
Some(ConsoleSeverity::Error)
@@ -10602,31 +10617,31 @@ mod tests {
#[test]
fn scalar_and_address_hints_extract_first_literal() {
- assert!(first_scalar_hint("rax, 0x1234").unwrap().contains("0x1234"));
- assert!(first_scalar_hint("rax, 42").unwrap().contains("dec 42"));
- assert!(first_address_hint("0x140001000").unwrap().contains("0x140001000"));
- assert!(first_scalar_hint("rax, rbx").is_none());
+ assert!(first_scalar_hint("rax, 0x1234").unwrap().contains("0x1234"));
+ assert!(first_scalar_hint("rax, 42").unwrap().contains("dec 42"));
+ assert!(first_address_hint("0x140001000").unwrap().contains("0x140001000"));
+ assert!(first_scalar_hint("rax, rbx").is_none());
}
- // ─── polish — DTM editing / chooser / persistence ────
+ // ─── polish — DTM editing / chooser / persistence ────
#[test]
fn rename_and_delete_user_type_rewrites_applied_types() {
let mut app = GhidrustApp::headless();
- app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
let va = app.program.as_ref().and_then(|p| p.entry).unwrap();
- app.define_user_type("Widget", "Structure\nint id;")
- .expect("define");
- app.apply_type_at(va, "Widget").expect("apply");
+ app.define_user_type("Widget", "Structure\nint id;")
+ .expect("define");
+ app.apply_type_at(va, "Widget").expect("apply");
- // Rename user type must rewrite the applied-types decoration.
- app.rename_user_type("Widget", "Gadget").expect("rename");
+ // Rename user type must rewrite the applied-types decoration.
+ app.rename_user_type("Widget", "Gadget").expect("rename");
let p = app.program.as_ref().unwrap();
- assert!(p.edits.user_types.contains_key("Gadget"));
- assert_eq!(p.edits.applied_type_at(va), Some("Gadget"));
+ assert!(p.edits.user_types.contains_key("Gadget"));
+ assert_eq!(p.edits.applied_type_at(va), Some("Gadget"));
- // Delete user type must clear the applied decoration too.
- app.delete_user_type("Gadget").expect("delete");
+ // Delete user type must clear the applied decoration too.
+ app.delete_user_type("Gadget").expect("delete");
let p = app.program.as_ref().unwrap();
assert!(p.edits.user_types.is_empty());
assert!(p.edits.applied_type_at(va).is_none());
@@ -10635,35 +10650,35 @@ mod tests {
#[test]
fn edit_user_type_supports_rename_and_body_swap() {
let mut app = GhidrustApp::headless();
- app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
- app.define_user_type("Widget", "Structure\nint a;")
- .expect("define");
- app.edit_user_type("Widget", "WidgetV2", "Structure\nint a;\nint b;")
- .expect("edit");
+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
+ app.define_user_type("Widget", "Structure\nint a;")
+ .expect("define");
+ app.edit_user_type("Widget", "WidgetV2", "Structure\nint a;\nint b;")
+ .expect("edit");
let p = app.program.as_ref().unwrap();
- assert!(!p.edits.user_types.contains_key("Widget"));
- assert!(p.edits.user_types.contains_key("WidgetV2"));
- assert!(p.edits.user_type("WidgetV2").unwrap().contains("int b;"));
- // Editing a non-existent type must fail rather than silently create.
- assert!(app.edit_user_type("nope", "x", "y").is_err());
+ assert!(!p.edits.user_types.contains_key("Widget"));
+ assert!(p.edits.user_types.contains_key("WidgetV2"));
+ assert!(p.edits.user_type("WidgetV2").unwrap().contains("int b;"));
+ // Editing a non-existent type must fail rather than silently create.
+ assert!(app.edit_user_type("nope", "x", "y").is_err());
}
#[test]
fn new_typedef_on_and_pointer_to_register_user_types() {
let mut app = GhidrustApp::headless();
- app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
- let td = app.new_typedef_on("int32_t").expect("typedef");
- let pt = app.new_pointer_to("int32_t").expect("pointer");
+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
+ let td = app.new_typedef_on("int32_t").expect("typedef");
+ let pt = app.new_pointer_to("int32_t").expect("pointer");
let p = app.program.as_ref().unwrap();
assert!(p.edits.user_types.contains_key(&td));
assert!(p.edits.user_types.contains_key(&pt));
- assert!(pt.ends_with('*'));
+ assert!(pt.ends_with('*'));
}
#[test]
fn type_chooser_dialog_opens_with_target_va() {
let mut app = GhidrustApp::headless();
- app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
let va = app.program.as_ref().and_then(|p| p.entry).unwrap();
assert!(!app.show_type_chooser_dialog);
app.open_type_chooser(Some(va));
@@ -10674,29 +10689,29 @@ mod tests {
#[test]
fn edit_type_dialog_preloads_body() {
let mut app = GhidrustApp::headless();
- app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
- app.define_user_type("Foo", "Structure\nint x;").expect("define");
- app.open_edit_type_dialog("Foo");
+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
+ app.define_user_type("Foo", "Structure\nint x;").expect("define");
+ app.open_edit_type_dialog("Foo");
assert!(app.show_edit_type_dialog);
- assert_eq!(app.edit_type_dialog_orig_name, "Foo");
- assert_eq!(app.edit_type_dialog_name, "Foo");
- assert!(app.edit_type_dialog_body.contains("int x;"));
+ assert_eq!(app.edit_type_dialog_orig_name, "Foo");
+ assert_eq!(app.edit_type_dialog_name, "Foo");
+ assert!(app.edit_type_dialog_body.contains("int x;"));
}
#[test]
fn all_five_comment_kinds_render_edits_into_program() {
let mut app = GhidrustApp::headless();
- app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
let va = app.program.as_ref().and_then(|p| p.entry).unwrap();
for k in CommentKind::ALL {
- app.set_comment_at(va, *k, format!("k={}", k.label()))
- .expect("comment");
+ app.set_comment_at(va, *k, format!("k={}", k.label))
+ .expect("comment");
}
let p = app.program.as_ref().unwrap();
for k in CommentKind::ALL {
assert_eq!(
p.edits.comment_at(va, *k),
- Some(format!("k={}", k.label()).as_str())
+ Some(format!("k={}", k.label).as_str())
);
}
assert_eq!(p.edits.comments_at(va).len(), CommentKind::ALL.len());
@@ -10707,30 +10722,30 @@ mod tests {
use ghidrust_core::Project;
let dir = std::env::temp_dir().join(format!(
- "ghidrust_gui_edits_rt_{}",
+ "ghidrust_gui_edits_rt_{}",
std::process::id()
));
let _ = std::fs::remove_dir_all(&dir);
- let mut proj = Project::create(&dir, "GuiEditRt").expect("proj");
- let f = proj.import_file(fixture_path("tiny_x64.pe")).unwrap();
+ let mut proj = Project::create(&dir, "GuiEditRt").expect("proj");
+ let f = proj.import_file(fixture_path("tiny_x64.pe")).unwrap();
- // Session A — apply user edits then save.
+ // Session A — apply user edits then save.
let mut app = GhidrustApp::headless();
app.project = Some(proj);
app.active_file_id = Some(f.id.clone());
app.load_binary(&app.project.as_ref().unwrap().binary_path(&f))
- .expect("load");
+ .expect("load");
let va = app.program.as_ref().and_then(|p| p.entry).unwrap();
- app.rename_at(va, "session_a_main").expect("rename");
- app.set_comment_at(va, CommentKind::Plate, "plate!")
- .expect("comment");
- app.define_user_type("Widget", "Structure\nint id;")
- .expect("define");
- app.apply_type_at(va, "Widget").expect("apply");
- app.save_results().expect("save");
-
- // Session B — fresh app, same project, same file.
- let proj2 = Project::open(&dir).expect("reopen");
+ app.rename_at(va, "session_a_main").expect("rename");
+ app.set_comment_at(va, CommentKind::Plate, "plate!")
+ .expect("comment");
+ app.define_user_type("Widget", "Structure\nint id;")
+ .expect("define");
+ app.apply_type_at(va, "Widget").expect("apply");
+ app.save_results.expect("save");
+
+ // Session B — fresh app, same project, same file.
+ let proj2 = Project::open(&dir).expect("reopen");
let mut app2 = GhidrustApp::headless();
app2.project = Some(proj2);
app2.active_file_id = Some(f.id.clone());
@@ -10739,13 +10754,13 @@ mod tests {
.as_ref()
.unwrap()
.load_program_with_results(&f)
- .expect("load with results");
+ .expect("load with results");
app2.program = Some(prog2);
let p = app2.program.as_ref().unwrap();
- assert_eq!(p.edits.rename_at(va), Some("session_a_main"));
- assert_eq!(p.edits.comment_at(va, CommentKind::Plate), Some("plate!"));
- assert!(p.edits.user_types.contains_key("Widget"));
- assert_eq!(p.edits.applied_type_at(va), Some("Widget"));
+ assert_eq!(p.edits.rename_at(va), Some("session_a_main"));
+ assert_eq!(p.edits.comment_at(va, CommentKind::Plate), Some("plate!"));
+ assert!(p.edits.user_types.contains_key("Widget"));
+ assert_eq!(p.edits.applied_type_at(va), Some("Widget"));
let _ = std::fs::remove_dir_all(&dir);
}
@@ -10753,32 +10768,32 @@ mod tests {
#[test]
fn edit_events_invalidate_decompiler_cache() {
let mut app = GhidrustApp::headless();
- app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
let entry = app.program.as_ref().and_then(|p| p.entry).unwrap();
{
let prog = app.program.as_mut().unwrap();
prog.analysis
.functions
- .push(ghidrust_core::FunctionInfo::new(entry, entry + 0x20, "fn"));
+ .push(ghidrust_core::FunctionInfo::new(entry, entry + 0x20, "fn"));
}
app.refresh_decompiler_at(entry);
assert!(!app.decomp_text.is_empty());
- // A rename mutation must invalidate cache via drain_events.
- app.rename_at(entry, "renamed").expect("rename");
+ // A rename mutation must invalidate cache via drain_events.
+ app.rename_at(entry, "renamed").expect("rename");
let _ = app.drain_events();
- assert!(app.decomp_text.is_empty(), "cache must clear after rename");
+ assert!(app.decomp_text.is_empty(), "cache must clear after rename");
}
#[test]
fn goto_out_of_window_va_redisassembles_listing() {
let mut app = GhidrustApp::headless();
- // analysis_lab has richer layout; load then go to a VA outside entry window
- app.load_binary(&fixture_path("analysis_lab.pe")).expect("load");
+ // analysis_lab has richer layout; load then go to a VA outside entry window
+ app.load_binary(&fixture_path("analysis_lab.pe")).expect("load");
let entry = app.program.as_ref().and_then(|p| p.entry).unwrap();
let first_listing_va = app.listing[0].address;
assert_eq!(first_listing_va, entry);
- // Pick a program block VA that is not covered by the entry listing window
+ // Pick a program block VA that is not covered by the entry listing window
let window_end = {
let last = app.listing.last().unwrap();
last.address + u64::from(last.length).max(1)
@@ -10791,59 +10806,59 @@ mod tests {
.iter()
.map(|b| b.va)
.find(|&va| va < first_listing_va || va >= window_end)
- .expect("need a block VA outside entry listing window");
+ .expect("need a block VA outside entry listing window");
- // Confirm helper says outside
+ // Confirm helper says outside
assert!(
listing_index_at_or_before(&app.listing, outside).is_none(),
- "precondition: {outside:#x} must be outside listing [{first_listing_va:#x}..)"
+ "precondition: {outside:#x} must be outside listing [{first_listing_va:#x}.)"
);
- app.goto_address_str(&format!("{outside:#x}"))
- .expect("goto outside");
+ app.goto_address_str(&format!("{outside:#x}"))
+ .expect("goto outside");
assert_eq!(app.listing_focus_va, Some(outside));
assert!(
!app.listing.is_empty(),
- "re-disassemble must produce listing"
+ "re-disassemble must produce listing"
);
assert_eq!(
app.listing[0].address, outside,
- "listing must start at target VA after re-disassemble"
+ "listing must start at target VA after re-disassemble"
);
- // Selection points at first insn of new window
+ // Selection points at first insn of new window
assert_eq!(app.listing_selection.start, Some(0));
- // Memory search hit navigation also refreshes when needed
+ // Memory search hit navigation also refreshes when needed
if let Some(hit) = app.memory_hits.first().cloned() {
let _ = hit;
}
- app.search_memory_input = "55 48 89 e5".into();
- app.run_search_memory().expect("mem");
+ app.search_memory_input = "55 48 89 e5".into();
+ app.run_search_memory.expect("mem");
assert!(!app.memory_hits.is_empty());
let hit_va = app.memory_hits[0].va;
- // Force listing back to entry-only window
- app.goto_address_str(&format!("{entry:#x}")).expect("back to entry");
+ // Force listing back to entry-only window
+ app.goto_address_str(&format!("{entry:#x}")).expect("back to entry");
assert_eq!(app.listing[0].address, entry);
- // Navigate to memory hit (may be same or different region)
- app.goto_address_str(&format!("{hit_va:#x}"))
- .expect("goto hit");
+ // Navigate to memory hit (may be same or different region)
+ app.goto_address_str(&format!("{hit_va:#x}"))
+ .expect("goto hit");
assert!(
app.listing
.iter()
.any(|i| i.address == hit_va
|| (i.address <= hit_va && hit_va < i.address + u64::from(i.length))),
- "listing must cover hit VA {hit_va:#x} after goto; first={:#x}",
+ "listing must cover hit VA {hit_va:#x} after goto; first={:#x}",
app.listing[0].address
);
}
- // ─── tables, xrefs, equates, tags, search dialogs ────
+ // ─── tables, xrefs, equates, tags, search dialogs ────
#[test]
fn xrefs_to_and_from_return_honest_rows_on_fixture() {
let mut app = GhidrustApp::headless();
- app.load_binary(&fixture_path("analysis_lab.pe")).expect("load");
- // xrefs_from at entry decodes and never fabricates.
+ app.load_binary(&fixture_path("analysis_lab.pe")).expect("load");
+ // xrefs_from at entry decodes and never fabricates.
let entry = app.program.as_ref().and_then(|p| p.entry).unwrap();
let from = app.xrefs_from_va(entry);
for r in &from {
@@ -10851,83 +10866,83 @@ mod tests {
assert!(r.from >= entry);
}
- // Inject a fake reference so xrefs_to_va picks it up deterministically.
+ // Inject a fake reference so xrefs_to_va picks it up deterministically.
{
let prog = app.program.as_mut().unwrap();
prog.analysis.references.push(ghidrust_core::ReferenceInfo {
from: prog.image_base + 0x100,
to: entry,
- kind: "call".into(),
+ kind: "call".into(),
});
}
let to = app.xrefs_to_va(entry);
- assert!(to.iter().any(|r| r.kind == "call"));
+ assert!(to.iter().any(|r| r.kind == "call"));
assert!(to.iter().all(|r| r.to == entry));
}
#[test]
fn set_equate_and_edit_events_fan_out() {
let mut app = GhidrustApp::headless();
- app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
let va = app.program.as_ref().and_then(|p| p.entry).unwrap();
- app.set_equate(va, 1, "SW_HIDE", 0).expect("set equate");
+ app.set_equate(va, 1, "SW_HIDE", 0).expect("set equate");
let p = app.program.as_ref().unwrap();
- assert_eq!(p.edits.equate_at(va, 1).map(|e| e.name.as_str()), Some("SW_HIDE"));
+ assert_eq!(p.edits.equate_at(va, 1).map(|e| e.name().as_str()), Some("SW_HIDE"));
assert_eq!(p.edits.equate_at(va, 1).map(|e| e.value), Some(0));
- // Groups & references consistent.
+ // Groups & references consistent.
let groups = p.edits.equate_groups();
- assert!(groups.iter().any(|(n, _, _)| n == "SW_HIDE"));
- // Setting empty name clears it.
- app.set_equate(va, 1, "", 0).expect("clear");
+ assert!(groups.iter().any(|(n, _, _)| n == "SW_HIDE"));
+ // Setting empty name clears it.
+ app.set_equate(va, 1, "", 0).expect("clear");
assert!(app.program.as_ref().unwrap().edits.equate_at(va, 1).is_none());
}
#[test]
fn function_tags_add_remove_delete_via_app() {
let mut app = GhidrustApp::headless();
- app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
let entry = app.program.as_ref().and_then(|p| p.entry).unwrap();
- app.add_function_tag(entry, "MALLOC").expect("add");
- app.add_function_tag(entry, "SANITIZED").expect("add");
+ app.add_function_tag(entry, "MALLOC").expect("add");
+ app.add_function_tag(entry, "SANITIZED").expect("add");
let p = app.program.as_ref().unwrap();
- assert!(p.edits.function_has_tag(entry, "MALLOC"));
- assert!(p.edits.function_has_tag(entry, "SANITIZED"));
- assert!(p.edits.all_function_tags.contains("MALLOC"));
- app.remove_function_tag(entry, "MALLOC").expect("remove");
- assert!(!app.program.as_ref().unwrap().edits.function_has_tag(entry, "MALLOC"));
- // Delete-everywhere strips from universe.
- app.delete_tag_everywhere("SANITIZED").expect("delete");
- assert!(!app.program.as_ref().unwrap().edits.all_function_tags.contains("SANITIZED"));
+ assert!(p.edits.function_has_tag(entry, "MALLOC"));
+ assert!(p.edits.function_has_tag(entry, "SANITIZED"));
+ assert!(p.edits.all_function_tags.contains("MALLOC"));
+ app.remove_function_tag(entry, "MALLOC").expect("remove");
+ assert!(!app.program.as_ref().unwrap().edits.function_has_tag(entry, "MALLOC"));
+ // Delete-everywhere strips from universe.
+ app.delete_tag_everywhere("SANITIZED").expect("delete");
+ assert!(!app.program.as_ref().unwrap().edits.all_function_tags.contains("SANITIZED"));
}
#[test]
fn search_scalars_dialog_runs_range_over_listing() {
let mut app = GhidrustApp::headless();
- app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
- app.search_scalars_min = "0".into();
- app.search_scalars_max = "0xffff".into();
- app.run_search_scalars().expect("scalars");
- // Fixture may or may not include a scalar in this range; the runner
- // must still succeed and populate text_hits deterministically.
+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
+ app.search_scalars_min = "0".into();
+ app.search_scalars_max = "0xffff".into();
+ app.run_search_scalars.expect("scalars");
+ // Fixture may or may not include a scalar in this range; the runner
+ // must still succeed and populate text_hits deterministically.
assert!(app.show_search_results);
}
#[test]
fn search_instruction_patterns_filters_listing() {
let mut app = GhidrustApp::headless();
- app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
- // tiny_x64 has a `push rbp` prologue; filter should hit it.
- app.search_insn_mnemonic = "push".into();
+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
+ // tiny_x64 has a `push rbp` prologue; filter should hit it.
+ app.search_insn_mnemonic = "push".into();
app.search_insn_operands.clear();
- app.run_search_instruction_patterns().expect("insn");
+ app.run_search_instruction_patterns.expect("insn");
assert!(!app.text_hits.is_empty());
- assert!(app.text_hits.iter().any(|h| h.kind == "insn"));
+ assert!(app.text_hits.iter().any(|h| h.kind == "insn"));
}
#[test]
fn address_tables_hits_appear_after_analyzer_populates() {
let mut app = GhidrustApp::headless();
- app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
{
let prog = app.program.as_mut().unwrap();
prog.analysis.address_tables.push(ghidrust_core::AddressTableInfo {
@@ -10939,21 +10954,21 @@ mod tests {
}
let hits = address_table_hits(app.program.as_ref().unwrap());
assert_eq!(hits.len(), 1);
- assert!(hits[0].text.contains("3 entries"));
+ assert!(hits[0].text.contains("3 entries"));
}
#[test]
fn compute_checksums_round_trip_whole_image() {
let mut app = GhidrustApp::headless();
- app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
- app.compute_checksums(ChecksumMode::WholeImage).expect("checksum");
+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
+ app.compute_checksums(ChecksumMode::WholeImage).expect("checksum");
let r = app.checksum_last.as_ref().unwrap();
assert!(r.len > 0);
assert!(r.crc32 != 0);
assert!(r.adler32 != 0);
- // Deterministic: re-running yields the same values.
+ // Deterministic: re-running yields the same values.
let first = r.clone();
- app.compute_checksums(ChecksumMode::WholeImage).expect("checksum");
+ app.compute_checksums(ChecksumMode::WholeImage).expect("checksum");
assert_eq!(app.checksum_last.as_ref().unwrap(), &first);
}
@@ -10962,8 +10977,8 @@ mod tests {
let mut app = GhidrustApp::headless();
assert_eq!(app.bytes_pane_bpr, 16);
assert!(app.bytes_pane_va.is_none());
- app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
- // Programmatic follow — reflects listing_focus.
+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
+ // Programmatic follow — reflects listing_focus.
app.listing_focus_va = app.program.as_ref().and_then(|p| p.entry);
app.bytes_pane_va = app.listing_focus_va;
assert!(app.bytes_pane_va.is_some());
@@ -10972,21 +10987,21 @@ mod tests {
#[test]
fn parse_scalar_input_hex_and_dec_and_signed() {
let app = GhidrustApp::headless();
- assert_eq!(app.parse_scalar_input("0x1234").unwrap(), 0x1234);
- assert_eq!(app.parse_scalar_input("42").unwrap(), 42);
- assert_eq!(app.parse_scalar_input("-0x10").unwrap(), -0x10);
- assert!(app.parse_scalar_input("").is_err());
+ assert_eq!(app.parse_scalar_input("0x1234").unwrap(), 0x1234);
+ assert_eq!(app.parse_scalar_input("42").unwrap(), 42);
+ assert_eq!(app.parse_scalar_input("-0x10").unwrap(), -0x10);
+ assert!(app.parse_scalar_input("").is_err());
}
- // ── Graphs & maps ─────────────────────────────────────
+ // ── Graphs & maps ─────────────────────────────────────
- /// Function Graph derives Stage-0 blocks + edges from the
- /// currently-focused function's CFG (honest empty if the region has
- /// no recovered blocks).
+ /// Function Graph derives Stage-0 blocks + edges from the
+ /// currently-focused function's CFG (honest empty if the region has
+ /// no recovered blocks).
#[test]
fn function_graph_pane_layouts_stage0_cfg() {
let mut app = GhidrustApp::headless();
- app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
let entry = app.program.as_ref().and_then(|p| p.entry).unwrap();
app.focus_function(entry);
@@ -11001,8 +11016,8 @@ mod tests {
FunctionGraphLayout::Hierarchical,
view,
);
- // Honest-empty is acceptable, but if blocks land they must all
- // have positive rects.
+ // Honest-empty is acceptable, but if blocks land they must all
+ // have positive rects.
for b in &blocks {
assert!(b.rect.width() > 0.0);
}
@@ -11011,8 +11026,8 @@ mod tests {
}
}
- /// Function Call Graph roots at the current function with
- /// level 0; expansion levels are session-only settings.
+ /// Function Call Graph roots at the current function with
+ /// level 0; expansion levels are session-only settings.
#[test]
fn call_graph_state_settings_persist_across_frames() {
let mut app = GhidrustApp::headless();
@@ -11023,16 +11038,16 @@ mod tests {
assert_eq!(app.graph_state.call_graph_levels_in, 2);
}
- /// 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();
- app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
let n0 = app.program.as_ref().unwrap().blocks.len();
- // Add a synthetic RWX block at 0x900000.
+ // Add a synthetic RWX block at 0x900000.
app.program.as_mut().unwrap().blocks.push(
ghidrust_core::MemoryBlock {
- name: "synthetic".into(),
+ name: "synthetic".into(),
va: 0x900000,
size: 0x100,
bytes: vec![0u8; 0x100],
@@ -11042,7 +11057,7 @@ mod tests {
},
);
assert_eq!(app.program.as_ref().unwrap().blocks.len(), n0 + 1);
- // Flip its RWX (via the field, mirrors the UI checkbox mutation).
+ // Flip its RWX (via the field, mirrors the UI checkbox mutation).
let idx = app.program.as_ref().unwrap().blocks.len() - 1;
{
let b = &mut app.program.as_mut().unwrap().blocks[idx];
@@ -11053,28 +11068,28 @@ mod tests {
assert_eq!(app.program.as_ref().unwrap().blocks.len(), n0);
}
- /// 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();
- assert!(app.register_manager.values.is_empty());
- app.register_manager.selected = Some("RAX".into());
+ assert!(app.register_manager.values().is_empty());
+ app.register_manager.selected = Some("RAX".into());
app.register_manager
- .values
+ .values()
.push(register_manager::RegisterValueRow {
- register: "RAX".into(),
+ register: "RAX".into(),
start_va: 0x1000,
end_va: 0x1100,
- value: "0x2a".into(),
+ value: "0x2a".into(),
});
- assert_eq!(app.register_manager.values.len(), 1);
+ assert_eq!(app.register_manager.values().len(), 1);
}
- /// 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();
- app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
+ app.load_binary(&fixture_path("tiny_x64.pe")).expect("load");
let s = entropy::entropy_samples(app.program.as_ref().unwrap(), 256);
assert!(!s.is_empty());
for w in s.windows(2) {
@@ -11082,13 +11097,13 @@ mod tests {
}
}
- // ── Scripts ───────────────────────────────────────────
+ // ── Scripts ───────────────────────────────────────────
#[test]
fn script_manager_catalog_is_populated_from_mcp_surface() {
let app = GhidrustApp::headless();
assert!(!app.script_manager.catalog.is_empty());
- assert!(app.script_manager.catalog.iter().any(|s| s.name == "mcp.list_functions"));
+ assert!(app.script_manager.catalog.iter().any(|s| s.name() == "mcp.list_functions"));
}
#[test]
@@ -11096,7 +11111,7 @@ mod tests {
let mut app = GhidrustApp::headless();
app.text_editor.open_untitled();
assert_eq!(app.text_editor.tabs.len(), 1);
- app.text_editor.tabs[0].body.push_str("body");
+ app.text_editor.tabs[0].body.push_str("body");
app.text_editor.tabs[0].dirty = true;
app.text_editor.close_active();
assert_eq!(app.text_editor.tabs.len(), 0);
@@ -11105,41 +11120,28 @@ mod tests {
#[test]
fn mcp_repl_submit_records_prompt_and_response() {
let mut app = GhidrustApp::headless();
- app.mcp_repl.input = "mcp.list_functions".into();
+ app.mcp_repl.input = "mcp.list_functions".into();
app.mcp_repl.submit();
assert_eq!(app.mcp_repl.transcript.len(), 2);
assert!(app.mcp_repl.transcript[0].prompt);
assert!(!app.mcp_repl.transcript[1].prompt);
}
- // ── Debugger visibility ──────────────────────────────
+ // ── Debugger visibility ──────────────────────────────
#[test]
- fn debugger_panes_enumerated_in_shell_panes() {
+ fn debugger_host_enumerated_in_shell_panes() {
let panes = GhidrustApp::shell_panes();
- for expected in [
- "Debugger Targets",
- "Debugger Threads",
- "Debugger Modules",
- "Debugger Regions",
- "Debugger Registers",
- "Debugger Stack",
- "Debugger Breakpoints",
- "Debugger Memory Bytes",
- "Debugger Watches",
- "Debugger Console",
- ] {
- assert!(
- panes.contains(&expected),
- "shell_panes() missing debugger provider `{expected}`",
- );
- }
+ assert!(
+ panes.contains(&"Debugger"),
+ "shell_panes missing tabbed Debugger host; full list = {panes:?}",
+ );
}
#[test]
fn debugger_menu_is_registered_in_shell() {
let menus = GhidrustApp::shell_menus();
- assert!(menus.contains(&"Debugger"));
+ assert!(menus.contains(&"Debugger"));
}
#[test]
@@ -11153,58 +11155,64 @@ mod tests {
app.debugger.toggle_breakpoint(0x1000);
assert!(!app.debugger.has_breakpoint(0x1000));
- app.debugger.add_watch("rax");
- app.debugger.add_watch("rax"); // dedup
- app.debugger.add_watch("*(int*)rsp");
+ app.debugger.add_watch("rax");
+ app.debugger.add_watch("rax"); // dedup
+ app.debugger.add_watch("*(int*)rsp");
assert_eq!(app.debugger.watches.len(), 2);
}
- // ── Docking / layouts ────────────────────────────────
+ // ── Docking / layouts ────────────────────────────────
#[test]
fn save_and_restore_layout_round_trip() {
- // Use a fresh %APPDATA%/ghidrust equivalent to keep test hermetic.
+ // Use a fresh %APPDATA%/ghidrust equivalent to keep test hermetic.
let dir = std::env::temp_dir().join(format!(
- "ghidrust_layouts_{}",
+ "ghidrust_layouts_{}",
std::process::id()
));
let _ = std::fs::remove_dir_all(&dir);
- // Point APPDATA at our sandbox so layouts write here.
- let prev = std::env::var("APPDATA").ok();
- // Only override APPDATA when it's the layout-dir resolver we care about.
- std::env::set_var("APPDATA", &dir);
+ // Point APPDATA at our sandbox so layouts write here.
+ let prev = std::env::var("APPDATA").ok();
+ // Only override APPDATA when it's the layout-dir resolver we care about.
+ std::env::set_var("APPDATA", &dir);
struct RestoreAppdata(Option<String>);
impl Drop for RestoreAppdata {
fn drop(&mut self) {
if let Some(p) = &self.0 {
- std::env::set_var("APPDATA", p);
+ std::env::set_var("APPDATA", p);
} else {
- std::env::remove_var("APPDATA");
+ std::env::remove_var("APPDATA");
}
}
}
let _guard = RestoreAppdata(prev);
let mut app = GhidrustApp::headless();
- // Flip a few state bits so we can prove the round-trip.
+ // Flip a few state bits so we can prove the round-trip.
app.toggle_pane(PaneKind::Bookmarks, true);
app.toggle_pane(PaneKind::MemoryMap, true);
- app.debugger_open.insert(DebuggerPane::Targets, true);
+ app.debugger.host_open = true;
+ app.debugger.enabled = true;
+ app.debugger.active_tab = DebuggerPane::Targets;
app.focus_center_tab(DockTab::Decompiler);
app.show_console = false;
- app.save_layout_named("myTest").expect("save layout");
- // Flip everything back so restore has something to change.
+ app.save_layout_named("myTest").expect("save layout");
+ // Flip everything back so restore has something to change.
app.toggle_pane(PaneKind::Bookmarks, false);
app.toggle_pane(PaneKind::MemoryMap, false);
- app.debugger_open.insert(DebuggerPane::Targets, false);
+ app.debugger.host_open = false;
+ app.debugger.enabled = false;
+ app.debugger.active_tab = DebuggerPane::Stack;
app.focus_center_tab(DockTab::Overview);
app.show_console = true;
- app.restore_layout_named("myTest").expect("restore layout");
+ app.restore_layout_named("myTest").expect("restore layout");
assert!(app.is_pane_open(PaneKind::Bookmarks));
assert!(app.is_pane_open(PaneKind::MemoryMap));
- assert_eq!(app.debugger_open.get(&DebuggerPane::Targets), Some(&true));
+ assert!(app.debugger.host_open);
+ assert!(app.debugger.enabled);
+ assert_eq!(app.debugger.active_tab, DebuggerPane::Targets);
assert_eq!(app.center, CenterPane::Decompiler);
assert!(app.center_dock.find_tab(&DockTab::Decompiler).is_some());
assert!(!app.show_console);
@@ -11221,15 +11229,18 @@ mod tests {
#[test]
fn graph_debugger_configure_menu_actions_wired_not_nyi() {
- let src = include_str!("main.rs");
- // 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\""));
- // Debugger menu is registered.
- assert!(src.contains("ui.menu_button(\"Debugger\","));
- // Configure dialog + Save Tool Layout menu items are wired.
- assert!(src.contains("show_configure_dialog"));
- assert!(src.contains("show_layouts_dialog"));
+ let src = include_str!("main.rs");
+ // 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\""));
+ // Debugger menu is registered.
+ assert!(src.contains("ui.menu_button(\"Debugger\","));
+ // Launch is wired (not nyi).
+ assert!(src.contains("open_launch_ui"));
+ assert!(!src.contains("nyi(\"Debugger → Launch"));
+ // 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 d1edf48..e6bc787 100644
--- a/crates/ghidrust-gui/src/menu_actions.rs
+++ b/crates/ghidrust-gui/src/menu_actions.rs
@@ -1,9 +1,9 @@
-//! Pure helpers for CodeBrowser menu actions (Ghidra analogs).
+//! Pure helpers for menu actions.
//! Unit-tested without egui click automation.
use ghidrust_core::{Instruction, Program};
-/// Listing selection as inclusive instruction indices (Ghidra: selection in Listing).
+/// Listing selection as inclusive instruction indices.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct ListingSelection {
pub start: Option<usize>,
@@ -42,7 +42,7 @@ impl ListingSelection {
}
/// Parse VA for Navigation → Go To Address (hex with optional 0x, or decimal).
-/// Ghidra analog: Navigation → Go To… accepts hex address.
+/// : Navigation → Go To… accepts hex address.
pub fn parse_address(s: &str) -> Result<u64, String> {
let t = s.trim();
if t.is_empty() {
@@ -143,7 +143,7 @@ pub struct TextHit {
/// Search → For Scalars — every scalar literal that appears in an operand
/// within `[min, max]`.
///
-/// Ghidra `ScalarSearchPlugin` lists every scalar operand and lets the user
+/// `ScalarSearchPlugin` lists every scalar operand and lets the user
/// filter by numeric range. Ghidrust's Stage-0 decoder emits scalars as either
/// `0x...` (hex) or decimal literals inside the operand string; both are
/// picked up here.
@@ -227,7 +227,7 @@ fn format_scalar(v: i64) -> String {
/// matches `mnemonic_glob` (case-insensitive substring match) and whose
/// operands contain `operand_substr` (empty = don't filter).
///
-/// Ghidra `BytePatternPlugin` supports a richer bit-pattern language; the
+/// `BytePatternPlugin` supports a richer bit-pattern language; the
/// Stage-0 Ghidrust flavour uses the mnemonic + operand string that the
/// decoder already produced so users can find e.g. every `cmp * , 0x0` or
/// every `call ptr` without needing a full pcode search host.
@@ -383,7 +383,7 @@ pub fn listing_index_at_or_before(listing: &[Instruction], va: u64) -> Option<us
best
}
-/// Processor / language summary (Ghidra: Edit → Tool Options / language; we show Tools → Processor).
+/// Processor / language summary.
#[derive(Debug, Clone)]
pub struct ProcessorInfo {
pub language: String,
@@ -405,8 +405,8 @@ pub fn processor_info(prog: &Program) -> ProcessorInfo {
entry: prog.entry,
endian: "little".into(),
pointer_size: 8,
- notes: "Ghidrust ships a fixed x86-64 decode path (no multi-processor SLEIGH editor). \
- Analog to Ghidra language/processor display for the loaded program."
+ notes: "Ghidrust ships a fixed x86-64 decode path (no multi-processor language editor). \
+ Processor info reflects the loaded program."
.into(),
}
}
diff --git a/crates/ghidrust-gui/src/nav.rs b/crates/ghidrust-gui/src/nav.rs
index f667aef..ddeafef 100644
--- a/crates/ghidrust-gui/src/nav.rs
+++ b/crates/ghidrust-gui/src/nav.rs
@@ -1,13 +1,13 @@
-//! Ghidra-analog navigation history for Back / Forward (Alt+Left / Alt+Right).
+//! navigation history for Back / Forward (Alt+Left / Alt+Right).
//!
-//! Semantics match Ghidra `NavigationHistoryPlugin`:
+//! Semantics match ``:
//! - Cursor moves push a new location onto Back.
//! - `back()` pops from Back and pushes the current onto Forward.
//! - `forward()` inverts that.
//! - Any *new* navigation while Forward is non-empty clears Forward (branch).
//! - Bounded to `capacity` entries per stack (256 by default).
-/// One point of interest in a program (Ghidra `ProgramLocation`).
+/// One point of interest in a program.
///
/// Kept minimal — VA only. Multi-program tools will need a program id later.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
diff --git a/crates/ghidrust-gui/src/panes.rs b/crates/ghidrust-gui/src/panes.rs
index 0828aaf..eeeb991 100644
--- a/crates/ghidrust-gui/src/panes.rs
+++ b/crates/ghidrust-gui/src/panes.rs
@@ -1,7 +1,7 @@
-//! Ghidra CodeBrowser provider catalog for visible parity.
+//! provider catalog for visible.
//!
-//! 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
+//! Every provider bundled with 's default `.tool`, plus commonly-reached
+//! providers from `Window` menu, is enumerated here with the exact 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.
//!
@@ -9,13 +9,13 @@
use eframe::egui::{self, Color32, RichText, Ui};
-/// One CodeBrowser provider (window / dockable pane).
+/// One provider (window / dockable pane).
///
-/// Ordering matches the Ghidra `Window` menu (roughly alphabetical). Titles are the
-/// exact strings Ghidra uses so the Window menu is a drop-in mental map.
+/// Ordering matches the `Window` menu (roughly alphabetical). Titles are the
+/// exact strings uses so the Window menu is a drop-in mental map.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum PaneKind {
- /// Ghidrust addition (not present in Ghidra): the Grok Build agent
+ /// Ghidrust addition: the Grok Build agent
/// console. Rendered as the primary tab in the bottom dock (next to the
/// plain `Console`) so RE users can chat with an agent that already
/// speaks the full Ghidrust MCP tool surface.
@@ -51,7 +51,7 @@ pub enum PaneKind {
SymbolTable,
SymbolTree,
TextEditor,
- // Project Window providers (Ghidrust fuses Project + CodeBrowser today).
+ // Project Window providers (Ghidrust fuses Project + today).
ProjectTree,
// ── Agent Friction Closure §13 — tool panes (real backends, no stubs) ──
/// `global-metadata.dat` parser (ghidrust-il2cpp) — types / methods / images.
@@ -69,8 +69,8 @@ pub enum PaneKind {
}
impl PaneKind {
- /// Every provider Ghidrust ships (matches Ghidra's default + off-layout catalog).
- /// Order = Ghidra `Window` menu order (alphabetical within group, then special).
+ /// Every provider Ghidrust ships.
+ /// Order = `Window` menu order (alphabetical within group, then special).
pub const ALL: &'static [PaneKind] = &[
// Left dock defaults
PaneKind::ProjectTree,
@@ -83,7 +83,7 @@ impl PaneKind {
PaneKind::DecompiledView,
// Ghidrust-specific (bottom dock primary tab).
PaneKind::AgentConsole,
- // Alphabetical from here (Ghidra Window menu order)
+ // Alphabetical from here
PaneKind::Bookmarks,
PaneKind::Bytes,
PaneKind::ChecksumGenerator,
@@ -118,7 +118,7 @@ impl PaneKind {
PaneKind::AnalysisArtifacts,
];
- /// Ghidra display title (Window menu label / provider `TITLE`).
+ /// display title (Window menu label / provider `TITLE`).
pub const fn title(self) -> &'static str {
match self {
PaneKind::AgentConsole => "Grok",
@@ -171,7 +171,7 @@ impl PaneKind {
self.title()
}
- /// Ghidra plugin owner (for empty-state hint text).
+ /// plugin owner (for empty-state hint text).
pub const fn plugin(self) -> &'static str {
match self {
PaneKind::AgentConsole => "GhidrustAgentConsole",
@@ -202,7 +202,7 @@ impl PaneKind {
PaneKind::Python => "InterpreterPanelPlugin",
PaneKind::RegisterManager => "RegisterPlugin",
PaneKind::RelocationTable => "RelocationTablePlugin",
- PaneKind::ScriptManager => "GhidraScriptMgrPlugin",
+ PaneKind::ScriptManager => "ScriptMgrPlugin",
PaneKind::SymbolReferences => "SymbolTablePlugin",
PaneKind::SymbolTable => "SymbolTablePlugin",
PaneKind::SymbolTree => "SymbolTreePlugin",
@@ -303,7 +303,7 @@ impl PaneKind {
}
}
-/// Bookmark type — Ghidra ships 5 standard categories + a plugin-registered Unknown.
+/// Bookmark type — ships 5 standard categories + a plugin-registered Unknown.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BookmarkKind {
Note,
@@ -332,7 +332,7 @@ impl BookmarkKind {
}
}
- /// Ghidra-analog color for margin marker / row tint.
+ /// color for margin marker / row tint.
pub fn color(self) -> Color32 {
match self {
BookmarkKind::Note => Color32::from_rgb(0x9C, 0x27, 0xB0), // purple
@@ -344,7 +344,7 @@ impl BookmarkKind {
}
}
-/// One bookmark row (Ghidra `BookmarkPlugin` model).
+/// One bookmark row.
#[derive(Debug, Clone)]
pub struct Bookmark {
pub va: u64,
@@ -367,8 +367,8 @@ 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 . Backing analysis \
- and interactive actions land in later phases — see \
+ ui.small(RichText::new("Pane is present in the shell catalog. Backing analysis \
+ and interactive actions land in later work — see \
internal UI notes.").color(muted));
}
@@ -401,7 +401,7 @@ pub const fn backend_pending_message(kind: PaneKind) -> &'static str {
PaneKind::ProgramTree => "",
PaneKind::ProjectTree => "",
PaneKind::Python => "Backend pending — scripting host / MCP REPL lands in .",
- PaneKind::RegisterManager => "Backend pending — SLEIGH register lattice lands in .",
+ PaneKind::RegisterManager => "Backend pending — register lattice values from live/debug backends.",
PaneKind::RelocationTable => "Uses Program::sections metadata; full PE/ELF reloc parse lands in .",
PaneKind::ScriptManager => "Backend pending — script catalog lands in .",
PaneKind::SymbolReferences => "",
@@ -454,7 +454,7 @@ mod tests {
#[test]
fn ghidra_default_toolbar_providers_present() {
- // 28 default `CodeBrowser.tool` providers must all be enumerated.
+ // 28 default `.tool` providers must all be enumerated.
let names: Vec<&'static str> = PaneKind::ALL.iter().map(|k| k.title()).collect();
for expected in [
"Program Trees",
@@ -488,7 +488,7 @@ mod tests {
] {
assert!(
names.contains(&expected),
- "missing Ghidra provider `{expected}` in PaneKind::ALL"
+ "missing provider `{expected}` in PaneKind::ALL"
);
}
}
diff --git a/crates/ghidrust-gui/src/register_manager.rs b/crates/ghidrust-gui/src/register_manager.rs
index 85f375a..42c9088 100644
--- a/crates/ghidrust-gui/src/register_manager.rs
+++ b/crates/ghidrust-gui/src/register_manager.rs
@@ -1,13 +1,13 @@
//! Ghidrust GUI · Register Manager pane.
//!
-//! Ghidra `RegisterPlugin` provider: hierarchical register tree on the left,
+//! `` provider: hierarchical register tree on the left,
//! per-address-range value table on the right. The register lattice is a
-//! honest approximation of Ghidra's SLEIGH `register` spec for x86-64 —
+//! honest approximation of 's `register` spec for x86-64
//! sub-registers are grouped under their parent (e.g. `RAX` contains `EAX`,
//! `AX`, `AH`, `AL`).
//!
-//! Register values (Ghidra "context register" style) are session-only until
-//! the SLEIGH register lattice lands in the backend. Editing / clearing
+//! Register values are session-only until
+//! the 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.
//!
@@ -184,10 +184,10 @@ macro_rules! rN {
};
}
-/// The Ghidra-analog x86-64 register lattice used by the pane.
+/// The x86-64 register lattice used by the pane.
///
/// This is a hand-authored subset covering the registers listed in
-/// `Ghidra/Processors/x86/data/languages/x86-64.sinc` plus a few common
+/// `/Processors/x86/data/languages/x86-64.sinc` plus a few common
/// convenience aliases. When multi-ISA lands the pane can pick a lattice
/// off the `Program::format`.
pub const X86_64_REGISTERS: &[RegisterNode] = &[
@@ -358,7 +358,7 @@ pub fn render(
let arch = format.unwrap_or("(no program)");
ui.small(
egui::RichText::new(format!(
- "Ghidra RegisterPlugin · {arch} register lattice · session-only values (backend pending SLEIGH lattice)"
+ "Register Manager · {arch} register lattice · session-only values"
))
.color(muted),
);
diff --git a/crates/ghidrust-gui/src/scripts.rs b/crates/ghidrust-gui/src/scripts.rs
index 39dbd69..160c8f5 100644
--- a/crates/ghidrust-gui/src/scripts.rs
+++ b/crates/ghidrust-gui/src/scripts.rs
@@ -1,11 +1,10 @@
-//! Ghidrust GUI · Script Manager, Text Editor, and
+//! Ghidrust GUI ·, Text Editor, and
//! MCP REPL / interpreter panes.
//!
-//! Ghidra's `GhidraScriptMgrPlugin` (Script Manager),
-//! `TextEditorManagerPlugin` (Text Editor), and
-//! `InterpreterPanelPlugin` (Python REPL) get honest Ghidrust analogs:
+//! `` (Text Editor), and
+//! `` (Python REPL) get honest Ghidrust analogs:
//!
-//! - **Script Manager** — categorised catalog of shipped Ghidrust MCP tools
+//! **** — categorised catalog of shipped Ghidrust MCP tools
//! (see `skill/SKILL.md`). Selecting a tool shows its description; the
//! `Run` button emits a Console message so users see the parity surface
//! without a live MCP host wired up.
@@ -21,18 +20,18 @@
use eframe::egui::{self, Color32, Ui};
use std::path::PathBuf;
-/// One Ghidra-analog script entry (Ghidrust MCP tools double as the catalog).
+/// One script entry (Ghidrust MCP tools double as the catalog).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ScriptEntry {
pub name: String,
pub category: String,
pub description: String,
- /// Preferred keyboard shortcut (Ghidra "Assign Key Binding"), empty if none.
+ /// Preferred keyboard shortcut, empty if none.
pub key_binding: String,
}
/// Built-in catalog — mirrors the MCP tool surface described in
-/// `skill/SKILL.md`. Order = Ghidra Script Manager order (alphabetical
+/// `skill/SKILL.md`. Order = order (alphabetical
/// within category).
pub fn builtin_catalog() -> Vec<ScriptEntry> {
let s = |name: &str, cat: &str, desc: &str| ScriptEntry {
@@ -82,7 +81,7 @@ pub fn builtin_catalog() -> Vec<ScriptEntry> {
]
}
-/// Script Manager session state.
+/// session state.
#[derive(Debug, Clone, Default)]
pub struct ScriptManagerState {
pub catalog: Vec<ScriptEntry>,
@@ -220,7 +219,7 @@ impl MacropadReplState {
// ── Rendering ────────────────────────────────────────────────────────────────
-/// Render the Script Manager. Returns `Some(name)` if a Run was requested.
+/// Render the. Returns `Some(name)` if a Run was requested.
pub fn render_script_manager(
state: &mut ScriptManagerState,
ui: &mut Ui,
@@ -230,7 +229,7 @@ pub fn render_script_manager(
ui.heading("Script Manager");
ui.small(
egui::RichText::new(
- "Ghidra GhidraScriptMgrPlugin analog · catalog is Ghidrust's MCP tool surface (see skill/SKILL.md)",
+ "Script Manager · catalog is Ghidrust's MCP tool surface (see skill/SKILL.md)",
)
.color(muted),
);
@@ -353,7 +352,7 @@ pub fn render_text_editor(
) -> TextEditorRequest {
ui.heading("Text Editor");
ui.small(
- egui::RichText::new("Ghidra TextEditorManagerPlugin analog · in-memory tabs on top of the local filesystem").color(muted),
+ egui::RichText::new("Text Editor · in-memory tabs on top of the local filesystem").color(muted),
);
ui.separator();
@@ -442,7 +441,7 @@ pub fn render_text_editor(
pub fn render_mcp_repl(state: &mut MacropadReplState, ui: &mut Ui, muted: Color32, primary: Color32) {
ui.heading("Python (MCP REPL)");
ui.small(
- egui::RichText::new("Ghidra InterpreterPanelPlugin analog · pipes to ghidrust mcp (stub; full wire lands in P17)").color(muted),
+ egui::RichText::new("MCP REPL · pipes to ghidrust mcp (stub)").color(muted),
);
ui.separator();
diff --git a/crates/ghidrust-il2cpp/src/body.rs b/crates/ghidrust-il2cpp/src/body.rs
index 0cad365..a22c371 100644
--- a/crates/ghidrust-il2cpp/src/body.rs
+++ b/crates/ghidrust-il2cpp/src/body.rs
@@ -1,7 +1,7 @@
//! Native method-body fingerprinting for IL2CPP map enrichment.
//!
//! Classifies tiny thunks / empty returns / bool getters so agents can
-//! reject shared-stub false leads before hooking (Inspector/IDA FUNC_THUNK bar).
+//! reject shared-stub false leads before hooking.
use crate::stubs::{classify_at, follow_stub_target};
use ghidrust_core::{disassemble_range, Program};
diff --git a/crates/ghidrust-il2cpp/src/lib.rs b/crates/ghidrust-il2cpp/src/lib.rs
index 1be64a9..6d78dfa 100644
--- a/crates/ghidrust-il2cpp/src/lib.rs
+++ b/crates/ghidrust-il2cpp/src/lib.rs
@@ -1,6 +1,6 @@
//! Hand-rolled IL2CPP metadata + binary correlation for Ghidrust.
//!
-//! No Il2CppDumper / Cpp2IL / goblin at runtime — formats reimplemented in-tree.
+//! No Il2CppDumper / Cpp2IL / at runtime — formats reimplemented in-tree.
//! See `docs/IL2CPP.md` for the supported version matrix.
pub mod binary;
diff --git a/crates/ghidrust-ir/src/lib.rs b/crates/ghidrust-ir/src/lib.rs
index 1e1c810..6827ed8 100644
--- a/crates/ghidrust-ir/src/lib.rs
+++ b/crates/ghidrust-ir/src/lib.rs
@@ -1,6 +1,6 @@
//! Architecture-neutral **pcode-like IR** for the Ghidrust decompile pipeline.
//!
-//! Inspired by Ghidra’s `PcodeOp` / `Varnode` model (reference only — reimplemented
+//! Inspired by ’s `PcodeOp` / `Varnode` model (reference only — reimplemented
//! in-tree). This crate owns the type surface; SSA, structuring, and emit live
//! elsewhere.
//!
@@ -18,7 +18,7 @@ use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub struct SpaceId(pub u16);
-/// Built-in address spaces (Ghidra-like stubs).
+/// Built-in address spaces.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub enum AddrSpace {
/// Physical / image memory (RAM).
@@ -86,7 +86,7 @@ impl Varnode {
}
}
-/// Pcode-like operation codes (Ghidra `PcodeOp` inspired subset).
+/// Pcode-like operation codes.
///
/// New ops are added conservatively as lift coverage grows; unknown ISA semantics
/// stay as [`OpCode::Unimplemented`] with the mnemonic preserved in
@@ -173,25 +173,25 @@ pub enum OpCode {
/// SSA/structuring can decide whether the block terminates. Consumers
/// treat this as an opaque side-effect with no def.
Trap,
- /// `out = concat(in0, in1)` — Ghidra `PIECE`: joins two subwords into a
+ /// `out = concat(in0, in1)` — `PIECE`: joins two subwords into a
/// wider value. `in0` is the high half, `in1` is the low half, and
/// `out.size == in0.size + in1.size`.
Piece,
- /// `out = in0 >> (in1 * 8)` truncated to `out.size` — Ghidra
+ /// `out = in0 >> (in1 * 8)` truncated to `out.size`
/// `SUBPIECE`. `in1` names the byte offset from the LSB.
Subpiece,
- /// `out = in0 + in1 * <element size>` — Ghidra `PTRADD`. Semantically
+ /// `out = in0 + in1 * <element size>` — `PTRADD`. Semantically
/// identical to `IntAdd` for byte arithmetic but preserves the "array
/// index" shape so type recovery / emit can print `p[i]`.
Ptradd,
- /// `out = (T)in0` — Ghidra `CAST`. Bit-preserving reinterpretation
+ /// `out = (T)in0` — `CAST`. Bit-preserving reinterpretation
/// used when Stage-1 emit needs to insert an explicit `(uint32_t)`.
Cast,
/// ISA op not yet lifted — mnemonic preserved in [`PcodeOp::note`].
Unimplemented,
}
-/// One IR operation (Ghidra `PcodeOp` analogue).
+/// One IR operation.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PcodeOp {
pub opcode: OpCode,
@@ -380,7 +380,7 @@ mod tests {
#[test]
fn opcode_set_covers_division_trap_and_bitops() {
- // Division family, Trap for int3/hlt, and Ghidra bit-manipulation
+ // Division family, Trap for int3/hlt, and bit-manipulation
// ops (PIECE/SUBPIECE/PTRADD/CAST) that Stage-1 emit will need as
// lift coverage grows.
for op in [
diff --git a/crates/ghidrust-lift/src/lib.rs b/crates/ghidrust-lift/src/lib.rs
index d964929..2636127 100644
--- a/crates/ghidrust-lift/src/lib.rs
+++ b/crates/ghidrust-lift/src/lib.rs
@@ -2,14 +2,13 @@
//!
//! Coverage grows opcode-by-opcode. Unhandled forms fall through to
//! [`ghidrust_ir::OpCode::Unimplemented`] so Stage-0 can still print the
-//! original mnemonic. Ghidra's `x86-64.sla` semantics tables are the reference
+//! original mnemonic. 's `x86-64.sla` semantics tables are the reference
//! (read-only) but this crate is written in-tree per the dependency policy.
//!
//! # Design
//!
//! * Registers are mapped to a stable numeric id in [`AddrSpace::Register`] via
//! [`X86Reg`]. Sub-registers reuse the parent id with a smaller `Varnode.size`
-//! (Ghidra's canonical layout).
//! * Flags (`ZF`/`CF`/`SF`/`OF`/`PF`) live at reserved offsets in
//! [`AddrSpace::Register`] with size 1 so they participate in later
//! dataflow just like any other varnode.
@@ -915,7 +914,7 @@ fn lift_with_ctx(ctx: &mut LiftCtx, insn: &Instruction) -> Vec<PcodeOp> {
}
}
// 1-operand imul / mul / div / idiv (F6/F7 group).
- // Ghidra models these as writing to rax:rdx (rdx:rax) — we
+ // models these as writing to rax:rdx (rdx:rax) — we
// conservatively update rax with the low half and drop rdx so
// Stage-1 doesn't fabricate a phantom def.
"imul" | "mul" | "idiv" | "div" if parts.len() == 1 => {
@@ -966,7 +965,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 follow-up.
+ // still walk it. '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);
diff --git a/crates/ghidrust-ssa/src/lib.rs b/crates/ghidrust-ssa/src/lib.rs
index cc9fe71..4a88b56 100644
--- a/crates/ghidrust-ssa/src/lib.rs
+++ b/crates/ghidrust-ssa/src/lib.rs
@@ -1,8 +1,8 @@
//! **Ghidrust SSA layer**: CFG construction, dominators, and full Cytron-
//! style SSA rename over [`ghidrust_ir::IrSequence`].
//!
-//! Ghidra `Ghidra/Features/Decompiler` is the *reference* — implementation is
-//! hand-rolled per the workspace [DEPENDENCIES.md](../../DEPENDENCIES.md)
+//! `/Features/Decompiler` is the *reference* — implementation is
+//! hand-rolled (no third-party SSA crates at runtime)
//! policy.
//!
//! # Overview
diff --git a/crates/ghidrust-ssa/src/ssa.rs b/crates/ghidrust-ssa/src/ssa.rs
index 2eedd46..8047002 100644
--- a/crates/ghidrust-ssa/src/ssa.rs
+++ b/crates/ghidrust-ssa/src/ssa.rs
@@ -11,7 +11,7 @@
//! shape (`OpCode`, inputs, output) but wraps each varnode in
//! [`SsaOperand`] so callers can distinguish real defs from constant
//! literals. `Phi` nodes are stored on the block, not fused into the op
-//! vector, which matches Ghidra Decompiler's internal representation.
+//! vector, which matches Decompiler's internal representation.
use crate::{Cfg, ENTRY_BLOCK};
use ghidrust_ir::{AddrSpace, OpCode, Varnode};
@@ -38,7 +38,7 @@ impl SsaValue {
/// An SSA operand: a constant literal or a versioned SSA value.
///
-/// Constants (Ghidra `AddrSpace::Constant`) are **not** renamed —
+/// Constants are **not** renamed
/// they aren't storage locations. Ram/branch-target constants are also
/// carried as `Const` since they name absolute addresses, not defs.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
@@ -572,7 +572,7 @@ pub fn dead_code_eliminate(func: &mut SsaFunction) -> usize {
// writes (e.g. `xor eax, eax` before `ret`) aren't discarded. On
// x86-64 SysV / Windows the integer return register is rax (offset
// 0); we also treat rdx (offset 2) as a potential high-half return
- // to be safe. This matches Ghidra Decompiler's default liveness for
+ // to be safe. This matches Decompiler's default liveness for
// integer functions — we don't yet track floating-point returns.
for b in &func.blocks {
for op in &b.ops {
diff --git a/crates/ghidrust-structure/src/lib.rs b/crates/ghidrust-structure/src/lib.rs
index 47e71aa..3a532b5 100644
--- a/crates/ghidrust-structure/src/lib.rs
+++ b/crates/ghidrust-structure/src/lib.rs
@@ -2,7 +2,7 @@
//! of high-level [`Region`]s (`Seq`, `IfThen`, `IfThenElse`, `While`,
//! `DoWhile`, `Loop`, `Return`) suitable for structured C emission.
//!
-//! Ghidra `Ghidra/Features/Decompiler` and Cifuentes' 1994 thesis are the
+//! `/Features/Decompiler` and Cifuentes' 1994 thesis are the
//! *reference*; the code below is hand-rolled per the workspace dependency
//! policy.
//!
@@ -33,7 +33,7 @@
//! detect blocks whose terminator is a computed jump matching a known
//! `jump_va` and emit [`Region::Switch`] with per-case body regions rather
//! than dropping to a raw `Goto`. This is the wired-up path for the
-//! Ghidra-equivalent "switch analyzer + decompiler switch case rendering"
+//! equivalent "switch analyzer + decompiler switch case rendering"
//! contract.
//!
//! ## Short-circuit flattening (`switch-recovery` roadmap todo, `&&`/`||`)
@@ -158,7 +158,7 @@ pub enum Region {
}
/// One arm of a recovered `switch`. `selector` is the integer case value
-/// (matching the Ghidra `SwitchInfo::cases` shape), `body` is a full
+/// , `body` is a full
/// [`Region`] the case falls into. Terminating with `break` is Stage-1
/// emit's responsibility (via `Region::Goto` / `Region::Return`).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
diff --git a/crates/ghidrust-types/src/lib.rs b/crates/ghidrust-types/src/lib.rs
index 808df42..a54f87c 100644
--- a/crates/ghidrust-types/src/lib.rs
+++ b/crates/ghidrust-types/src/lib.rs
@@ -1,7 +1,7 @@
//! **Ghidrust type lattice + local/parameter recovery** over
//! [`ghidrust_ssa::SsaFunction`].
//!
-//! Ghidra `Ghidra/Features/Decompiler`'s `DataType` and `typeprop` pass are
+//! `/Features/Decompiler`'s `DataType` and `typeprop` pass are
//! the *reference*. Everything here is hand-rolled per the workspace
//! dependency policy — we deliberately keep the initial lattice small so
//! Stage-1 emit has enough information to name locals/params without
diff --git a/docs/IL2CPP.md b/docs/IL2CPP.md
index 2450b1b..ea21ecd 100644
--- a/docs/IL2CPP.md
+++ b/docs/IL2CPP.md
@@ -1,6 +1,6 @@
# IL2CPP + Unity inventory (Ghidrust)
-Hand-rolled support for Unity IL2CPP metadata and player-install inventory. No Il2CppDumper, Cpp2IL, or goblin at runtime — see [DEPENDENCIES.md](../DEPENDENCIES.md).
+Hand-rolled support for Unity IL2CPP metadata and player-install inventory. No Il2CppDumper, Cpp2IL, or goblin at runtime.
## Commands
diff --git a/skill/README.md b/skill/README.md
index b46b75f..a4417fe 100644
--- a/skill/README.md
+++ b/skill/README.md
@@ -2,7 +2,7 @@
## What Ghidrust is
-Ghidrust is a **Rust** reverse-engineering toolkit inspired by [Ghidra](https://github.com/NationalSecurityAgency/ghidra) — not a fork. It loads PE/ELF (and raw blobs), disassembles x86-64 (bounded by function end by default), creates/heals functions, runs Auto Analysis, decompiles to pseudo-C, parses IL2CPP metadata / touch-maps / Unity install inventory, spills large analysis artifacts, inventories PE installs, queries RTTI catalogs, and (on Windows) attaches read-only to live processes — via **CLI**, **MCP** (stdio), and an **egui** CodeBrowser-style GUI. The skill file is also **embedded** in the agent crate so Start works without a source-tree checkout.
+Ghidrust is a **Rust** reverse-engineering toolkit inspired by [](https://github.com/NationalSecurityAgency/) — not a fork. It loads PE/ELF (and raw blobs), disassembles x86-64 (bounded by function end by default), creates/heals functions, runs Auto Analysis, decompiles to pseudo-C, parses IL2CPP metadata / touch-maps / Unity install inventory, spills large analysis artifacts, inventories PE installs, queries RTTI catalogs, and (on Windows) attaches read-only to live processes — via **CLI**, **MCP** (stdio), and an **egui** -style GUI. The skill file is also **embedded** in the agent crate so Start works without a source-tree checkout.
**Aims:** a freestanding, auditable RE core; CPU-correct analysis first; optional experimental GPU bulk scan + VRAM-resident decompile; agent-friendly headless use.
diff --git a/skill/SKILL.md b/skill/SKILL.md
index 67d34cf..00bab09 100644
--- a/skill/SKILL.md
+++ b/skill/SKILL.md
@@ -1,21 +1,19 @@
---
name: ghidrust
description: >
- Use Ghidrust (Rust RE toolkit: PE/ELF/blob load, x86-64 disasm, Auto Analysis, projects,
- CLI/MCP, egui GUI, IL2CPP metadata, Unity player inventory, GPU analyzer kernels +
- multipass decompile) to reverse-engineer binaries without Ghidra. Exhaustive feature
- catalog with when-to-use guidance.
- Triggers: /ghidrust, reverse engineer, RE a PE/ELF, disassemble, RTTI, auto analysis,
- analyze binary, Ghidrust project, MCP ghidrust, strings/functions, GPU decompile,
- IL2CPP, global-metadata, unity-inventory, GameAssembly, analyzer-bench,
- rtti-gpu-bench, bulk-bench.
+ x86-64 Auto Analysis, projects, CLI/MCP, egui GUI, IL2CPP metadata, Unity player inventory,
+ GPU analyzer kernels + multipass decompile) to reverse-engineer binaries without .
+ Exhaustive feature catalog with when-to-use guidance.
+ Triggers: /ghidrust, reverse engineer, RE a PE/ELF, disassemble, decode-support, decode-query,
+ MCP ghidrust, strings/functions, GPU decompile, IL2CPP, global-metadata, unity-inventory,
+ GameAssembly, analyzer-bench, rtti-gpu-bench, bulk-bench.
metadata:
- short-description: "Ghidrust RE — CLI, MCP, IL2CPP, Unity, analyzers, GPU"
+ short-description: "Ghidrust RE — multi-arch decode, CLI, MCP, IL2CPP, Unity, analyzers, GPU"
---
# Ghidrust — agent skill
-Hand-rolled **Rust** reverse-engineering core (Ghidra-inspired labels; measurable **Ghidra-surpass** target on x86-64, Stage-0 decompile today). Prefer **CLI or MCP** for agents; GUI is for humans. **Never invent analysis** — if a fixture has no evidence, outputs are empty/honest.
+**Rust** reverse-engineering core (-inspired labels; measurable **-surpass** target on x86-64, Stage-0 decompile today). Prefer **CLI or MCP** for agents; GUI is for humans. **Never invent analysis** — if a fixture has no evidence, outputs are empty/honest.
## Paths & binaries
@@ -26,6 +24,7 @@ Hand-rolled **Rust** reverse-engineering core (Ghidra-inspired labels; measurabl
| GUI | `cargo run -p ghidrust-gui --release` |
| Fixtures | `fixtures/tiny_x64.pe`, `fixtures/analysis_lab.pe`, `fixtures/tiny_x64.elf`, `fixtures/il2cpp/*` |
| Docs | `README.md`, `docs/IL2CPP.md`, `docs/GPU_ANALYZER_MATRIX.md`, `docs/PARALLEL_RE_RESEARCH.md` |
+| Decode API | `ghidrust-decode::Engine` — `open`, `disasm`, `disasm_one`, `option`, `insn_name`, `reg_name`, `group_name`, `regs_access`; re-exported from `ghidrust-core` |
| Core API | `load_path` / `load_path_opts` / `load_blob`, `collect_strings_opts`, `run_analyzers_opts`, `Project`, `gpu_analyzers`, `bulk_scan` |
CLI always builds with `gpu` feature on deps. On Windows PowerShell: `.\target\release\ghidrust.exe …`.
@@ -37,18 +36,243 @@ cargo build -p ghidrust-gui --release
---
+
+Hand-rolled **`ghidrust-decode`** crate — Capstone-compatible `Engine` API over **23 ISAs**, implemented entirely in-tree. **No Capstone, iced-x86, or Zydis at runtime.** Program-aware disasm (`ghidrust-core::disassemble_range_ex_opts`) wraps the engine with bounded/flow/linear walks, loader-derived arch/mode, and JSON instruction records.
+
+Library entry points: `Engine::open(arch, mode)`, `disasm` / `disasm_one` / `disasm_iter`, `option(Opt::…)`, introspection helpers (`insn_name`, `reg_name`, `group_name`, `op_count`, `regs_access`, …). Legacy x86-64 helper: `decode_one`.
+
+### Decode support — `decode-support` / `server_info.decode`
+
+Run **`ghidrust decode-support [--json]`** or MCP **`decode_support`** / read **`server_info.decode`** after connect.
+
+JSON shape:
+
+| Field | Meaning |
+|-------|---------|
+| `version` | `DECODE_VERSION` (crate version) |
+| `arches[]` | `{ name, supported }` for every `Arch::ALL` entry (all `supported: true`) |
+| `options[]` | Engine option names: `syntax`, `detail`, `detail_real`, `mode`, `skipdata`, `skipdata_setup`, `mnemonic`, `unsigned`, `only_offset_branch`, `litbase` |
+| `syntax_values[]` | Allowed `--syntax` / MCP `syntax` strings |
+| `features.decode_diet` | `false` — full detail path (not diet build) |
+| `features.x86_reduce` | `false` — full x86 table (not x86 reduce build) |
+
+`server_info` also sets **`tool_surface: 5`** and lists `decode_support` / `decode_query` under `features.surface`.
+
+### CLI — `disasm`, `decode-support`, `decode-query`
+
+Add `--json` for structured stdout. Shared decode flags come from `DecodeOpts` (`crates/ghidrust-cli/src/decode_opts.rs`).
+
+#### `ghidrust disasm <path>` (alias `disassemble`)
+
+**Path modes:** PE/ELF (loader arch/mode) · raw blob when **`--arch`** is set (reads file bytes; `--addr` offset into blob).
+
+| Flag | Purpose |
+|------|---------|
+| `--addr HEX` | Start VA (default: program entry or image base) |
+| `--count N` | Max instructions (default **16**) |
+| `--skip-bad` | Skip undecodable bytes; JSON reports `decode_gaps`, `first_gap_va` |
+| `--linear` | Unbounded linear walk — **ground truth** when bounds are unknown/suspect |
+| `--flow` | Control-flow walk within function bounds (trusted ends only) |
+| `--brief` | One line per insn: `addr: mnemonic operands` (no hex); no `python -c` needed |
+| `--pretty` | Header `entry/end/n/mode/stop_reason` + brief lines + bounds warning if any |
+| `--arch NAME` | Override architecture (see catalog; aliases below) |
+| `--mode NAME\|INT` | mode bits or named mode (`64`, `thumb`, `mips32`, `le`, …) |
+| `--syntax SYNTAX` | Assembly syntax flavor (see options catalog) |
+| `--detail` | Enable structured `detail` on each instruction |
+| `--no-detail` | Force detail off |
+| `--detail-real` | Real-number detail formatting where applicable |
+| `--skipdata` | Treat unknown bytes as data (skip-data mode) |
+| `--skipdata-mnemonic S` | Mnemonic for skip-data pseudo-instructions |
+| `--skipdata-size N` | Default skip size hint |
+| `--unsigned-imm` | Print immediates unsigned |
+| `--only-offset-branch` | Branch targets as offsets only |
+| `--litbase HEX` | Literal base for architectures that use it |
+| `--mnem-override ID:MNEMONIC` | Repeatable per-instruction-id mnemonic override |
+| `--out FILE` | With `--json`: JSON file. Without: human listing text (default/`--brief`/`--pretty`). UTF-8, no BOM |
+| `--json` | Structured stdout / JSON `--out` |
+
+JSON envelope (mapped binary): `insns`, `decode_gaps`, `first_gap_va`, `stop_reason`, `mode`, `entry`, `end`, plus honesty fields when relevant (`bounds_suspect`, `bounds_warning`, `suggested_end`, `heal_hint`, `callsite_hints`). MCP `disassemble` adds `resolve`, `listing_text` (brief lines).
+
+**PowerShell-safe:** never nest `python -c "..."` in agent shell pipelines (ScriptBlock / quoting kills the job). Prefer `ghidrust disasm … --pretty` / `--brief`, or `--json --out file.json` then `Get-Content` / `ConvertFrom-Json`. Flags accept `--name` or `-name`.
+
+#### `ghidrust decode-support [--json]`
+
+No arguments. Emits engine catalog (see above).
+
+#### `ghidrust decode-query`
+
+| Flag | Purpose |
+|------|---------|
+| `--query NAME` | **Required.** One of: `insn_name`, `reg_name`, `group_name`, `insn_group`, `reg_read`, `reg_write`, `op_count`, `op_index`, `regs_access` |
+| `--arch NAME` | Architecture (default `x86`) |
+| `--mode NAME\|INT` | Mode (default `64` for x86, `little_endian` otherwise) |
+| `--id N` | Instruction / register / group id (`insn_name`, `reg_name`, `group_name`) |
+| `--index N` | Operand / group / reg index (default 0) |
+| `--bytes HEX` | Instruction bytes for insn-dependent queries |
+| `--addr HEX` | Address for decode context (default 0) |
+| `--detail` | Enable detail before decode (required for `regs_access`) |
+| `--json` | Structured stdout |
+
+Positional query name (without `--query`) is also accepted: `ghidrust decode-query insn_name --arch x86 --id 1 --json`.
+
+### MCP — `disassemble`, `decode_support`, `decode_query`
+
+Requires **`tool_surface >= 5`** (check `server_info` before assuming these tools/args exist).
+
+#### `decode_support`
+
+Arguments: `{}`. Returns same JSON as CLI `decode-support`.
+
+#### `decode_query`
+
+| Arg | Type | Purpose |
+|-----|------|---------|
+| `query` | string **required** | `insn_name` \| `reg_name` \| `group_name` \| `insn_group` \| `reg_read` \| `reg_write` \| `op_count` \| `op_index` \| `regs_access` |
+| `arch` | string | Architecture name |
+| `mode` | string \| integer | Mode name or bitfield |
+| `id` | integer | Insn/reg/group id |
+| `index` | integer | Operand/group/reg index |
+| `bytes` | string | Hex bytes for instruction-dependent queries |
+| `addr` | string | Address for decode |
+| `detail` | boolean | Enable detail (needed for `regs_access`) |
+
+#### `disassemble`
+
+| Arg | Type | Purpose |
+|-----|------|---------|
+| `path` | string **required** | PE/ELF path |
+| `addr` | string | Start VA |
+| `count` | integer | Max insns (default 16) |
+| `skip_bad` | boolean | Skip bad bytes |
+| `linear` | boolean | Unbounded linear walk |
+| `flow` | boolean | Control-flow walk within function |
+| `arch` | string | Arch override |
+| `mode` | string \| integer | Mode override |
+| `syntax` | string | `default` \| `intel` \| `att` \| `noregname` \| `masm` \| `motorola` \| `cs_reg_alias` \| `percent` \| `no_dollar` \| `no_alias_text` \| `no_alias_text_compressed` |
+| `detail` | boolean | Structured detail |
+| `detail_real` | boolean | Real-number detail |
+| `skipdata` | boolean | Skip-data mode |
+| `skipdata_mnemonic` | string | Skip-data mnemonic |
+| `skipdata_size` | integer | Skip-data size hint |
+| `unsigned_imm` | boolean | Unsigned immediates |
+| `only_offset_branch` | boolean | Offset-only branches |
+| `litbase` | string \| integer | Literal base |
+| `mnem_overrides` | array | `"ID:MNEMONIC"` strings or `{ id, mnemonic }` objects |
+
+Returns: `resolve`, `mode`, `stop_reason`, `entry`, `end`, `decode_gaps`, `first_gap_va`, `insns`.
+
+### Options catalog
+
+| Option | CLI flag | MCP field | Values / notes |
+|--------|----------|-----------|----------------|
+| **syntax** | `--syntax` | `syntax` | `default`, `intel`, `att`, `noregname`, `masm`, `motorola`, `cs_reg_alias`, `percent`, `no_dollar`, `no_alias_text`, `no_alias_text_compressed` |
+| **detail** | `--detail` / `--no-detail` | `detail` | boolean — structured operands + register access lists |
+| **detail_real** | `--detail-real` | `detail_real` | boolean |
+| **mode** | `--mode` | `mode` | Integer bitfield or named: `16`, `32`, `64`, `thumb`, `mclass`, `v8`, `mips32`, `mips64`, `ppc32`, `ppc64`, `riscv32`, `riscv64`, `riscv_c`, `le`/`little`, `be`/`big`, `bpf_classic`, `bpf_extended`, `6502`, `65c02`, … |
+| **skipdata** | `--skipdata` | `skipdata` | boolean |
+| **skipdata_setup** | `--skipdata-mnemonic`, `--skipdata-size` | `skipdata_mnemonic`, `skipdata_size` | Mnemonic + size hint (`skipdata_setup` in engine) |
+| **mnemonic** | `--mnem-override ID:MNEM` | `mnem_overrides[]` | Per-instruction-id override |
+| **unsigned** | `--unsigned-imm` | `unsigned_imm` | boolean |
+| **only_offset_branch** | `--only-offset-branch` | `only_offset_branch` | boolean |
+| **litbase** | `--litbase HEX` | `litbase` | u32 |
+
+### Architectures catalog (`Arch::ALL` — 23)
+
+All report `"supported": true` from `decode-support`. CLI/MCP `--arch` / `arch` accepts the aliases below (from `parse_arch`); other canonical names are engine-supported — use `Engine::open` in library code or extend CLI aliases if needed.
+
+| Name | CLI/MCP `--arch` aliases |
+|------|--------------------------|
+| `arm` | `arm` |
+| `arm64` | `arm64`, `aarch64` |
+| `mips` | `mips` |
+| `x86` | `x86`, `x86_64`, `x64`, `amd64` |
+| `ppc` | `ppc`, `powerpc` |
+| `sparc` | `sparc` |
+| `sysz` | `sysz`, `s390` |
+| `xcore` | *(canonical `xcore` — engine only until CLI alias added)* |
+| `m68k` | `m68k`, `68k` |
+| `tms320c64x` | *(engine only)* |
+| `m680x` | *(engine only)* |
+| `evm` | `evm` |
+| `mos65xx` | `mos65xx`, `6502` |
+| `wasm` | `wasm` |
+| `bpf` | `bpf`, `ebpf` |
+| `riscv` | `riscv`, `riscv32`, `riscv64` |
+| `sh` | *(engine only)* |
+| `tricore` | *(engine only)* |
+| `alpha` | `alpha` |
+| `hppa` | *(engine only)* |
+| `loongarch` | *(engine only)* |
+| `xtensa` | *(engine only)* |
+| `arc` | *(engine only)* |
+
+Per-arch notes: [docs/DECODE_COVERAGE.md](../docs/DECODE_COVERAGE.md).
+
+### Groups catalog
+
+
+| ID | Name | Meaning |
+|----|------|---------|
+| 0 | `Invalid` | Placeholder |
+| 1 | `Jump` | Jump group |
+| 2 | `Call` | Call group |
+| 3 | `Ret` | Return group |
+| 4 | `Int` | Interrupt |
+| 5 | `Iret` | Interrupt return |
+| 6 | `Privilege` | Privileged |
+| 7 | `BranchRelative` | PC-relative branch |
+| ≥8 | `Arch(n)` | Architecture-specific groups — resolve with `decode-query --query group_name --id N` |
+
+### Instruction JSON fields
+
+Each entry in `insns[]`:
+
+| Field | Type | When present |
+|-------|------|--------------|
+| `address` | u64 | Always |
+| `bytes` | `[u8]` | Always — raw opcode bytes |
+| `mnemonic` | string | Always |
+| `operands` | string | Always — formatted operand text |
+| `length` | u8 | Always |
+| `detail` | object | When `--detail` / `detail: true` |
+| `detail.operands[]` | array | Structured operands: `Reg`, `Imm { value, size }`, `Mem { base, index, scale, disp, segment, size }`, `Fp`, `Invalid` |
+| `detail.groups[]` | array | `GroupId` membership |
+| `detail.regs_read[]` | array | Explicit read registers |
+| `detail.regs_write[]` | array | Explicit write registers |
+| `detail.implicit_read[]` | array | Implicit reads |
+| `detail.implicit_write[]` | array | Implicit writes |
+
+Human text line (non-JSON default): `{addr:016x}: {hex bytes} {mnemonic} {operands}`.
+Brief line (`--brief` / MCP `listing_text`): `{addr:#x}: {mnemonic} {operands}`.
+
+### Decode SOPs (required)
+
+- **`tool_surface` check**: Call `server_info` first. This skill requires **`tool_surface >= 5`** for `decode_support`, `decode_query`, and extended `disassemble` decode args. If below 5 or tools missing from `tools/list` → rebuild `ghidrust`, restart MCP. (Broader Ghidrust surface still requires **`>= 3`**, prefer **`>= 4`** for bounded disasm / `get_calls_from`.)
+- **Decode mode decision tree**:
+ - Need body of **unknown / wrong / suspect** bounds? → `disasm --linear --count N` first (ground truth) → `function create --addr` to heal → then `--flow` / `decompile` on healed range.
+ - Need CFG inside a **known-good** function? → `--flow` (or default bounded).
+ - If JSON/text shows `bounds_suspect` or stop after a handful of insns with `function_end` → do **not** treat that as the full body; heal first.
+- **Bounded disasm**: Default **`Bounded`** clamps to containing function end. Trust it only when ends look honest (not prologue-only). Prefer `--linear` before decompile when unsure.
+- **Detail-first**: Pass **`--detail`** / `detail: true` when you need structured operands, **`regs_access`**, or `callsite_hints`. Without detail, rely on mnemonic/operand / listing_text strings only.
+- **Arch/mode from loader**: Omit **`--arch`/`--mode`** on PE/ELF so `arch_mode_for_program` selects from machine type. Override only for cross-arch blobs or deliberate experiments.
+- **Query helpers**: Use **`decode-query`** for `insn_name`/`reg_name`/`group_name` tables and per-instruction **`op_count`/`op_index`/`regs_access`** — do not guess ids from strings alone.
+- **Skipdata**: Enable **`--skipdata`** when linear sweeps hit inline data pools; tune **`--skipdata-mnemonic`** / **`--skipdata-size`** for readable `.byte`-style placeholders.
+
+---
+
## Agent friction SOPs (required)
-- **Version / stale MCP**: Call `server_info` first (or read `initialize.serverInfo`). This skill requires **`tool_surface >= 3`** (touch-map, body_class map, function_create, live process + artifacts). Prefer `>= 4` when using bounded disasm / `get_calls_from`. If `server_info` is missing, `tool_surface` is below that minimum, or `process_list` / `artifact_query` / `il2cpp_touch_map` / `function_create` are absent from `tools/list` → rebuild `ghidrust`, point the MCP `command` at that binary, **restart the MCP server**. Do **not** conclude live process is unsupported; do **not** invent heap-scan scripts as a substitute. CLI/GUI/MCP share one package version (`ghidrust --version`, MCP `version`, egui About).
+- **Version / stale MCP**: Call `server_info` first (or read `initialize.serverInfo`). This skill requires **`tool_surface >= 3`** (touch-map, body_class map, function_create, live process + artifacts). Prefer **`>= 4`** for bounded disasm / `get_calls_from`. Require **`>= 5`** for `decode_support`, `decode_query`, and extended `disassemble` decode flags. If `server_info` is missing, `tool_surface` is below the needed minimum, or expected tools are absent from `tools/list` → rebuild `ghidrust`, point the MCP `command` at that binary, **restart the MCP server**. Do **not** conclude live process is unsupported; do **not** invent heap-scan scripts as a substitute. CLI/GUI/MCP share one package version (`ghidrust --version`, MCP `version`, egui About).
- **Artifacts**: When envelope `entry_count` > preview or the host truncates tool text, drain via `artifact_query` / `artifact get` until `next_offset` is null. Never assume truncated MCP text is complete.
- **Program identity**: Prefer `load` with absolute `path`, or `project` + `file_id`. Facts always include `resolved_path` or honest null — resolve before analyze/decompile.
- **Inventory / tree**: Use `inventory <dir>` (PE VERSIONINFO + exe/dll) before OS `dir`/`Get-Item`. Use `tree` / `list_tree` for non-PE sidecars (existence/size only; no unpack).
-- **Seed pipeline**: Exception Directory / FSS → `function_create` (heal orphans) → tagged synthesize when still missing. Never invent managed names on synthesized ranges.
-- **Bounded disasm**: Prefer default bounded/flow disasm clamped to function body; `--linear` / `linear:true` is an escape hatch only.
+- **Seed pipeline**: Exception Directory / FSS → `function_create` (heal orphans **and** re-grow truncated stored ends) → tagged synthesize when still missing. Never invent managed names on synthesized ranges.
+- **PowerShell / agent shell**: Never recommend `python -c` with nested quotes in PS pipelines. Prefer `ghidrust disasm … --pretty` / `--brief`, or `--json --out FILE` + `ConvertFrom-Json` / MCP `disassemble` (`listing_text`, `insns[].mnemonic`/`operands`).
+- **Bounded disasm honesty**: Default bounded/flow clamps to function end. When `bounds_suspect` / short `function_end` / &lt;~8 insns then stop → `--linear` first, then `function create --addr`, then `--flow`/decompile. Never treat a 5-insn bounded result as a full function.
- **Address→function**: Always pass `addr` to `decompile` / `disassemble` / `gpu_decompile`; trust `resolved_entry` / `resolve` meta. Mid-body hits resolve to containing entry; unmapped → create/synthesize or honest `no_containing_function` (no invented 1-insn fn).
- **RTTI catalog**: Prefer `rtti_query` (`--filter`/`--exact`) before mangled `.?AV` string archaeology. Multi-vtable types report `vtable_vas[]` honestly.
- **UTF-16 xrefs**: If `search_strings` returns `utf16le`, query `get_string_xrefs` with `encoding=all` (or `utf16le`) before concluding “no refs”.
-- **Live process (Windows)**: Multi-step live work **must** use MCP (or one long-lived process) — `process_list` → `process_attach` → `process_modules` → `process_resolve` (`static_to_live`) → `process_read` → optional `process_regions` / `process_detach`. Never chain separate CLI `ghidrust process` spawns expecting the same `session_id` (sessions are in-process). Bytes ≠ types. No write/breakpoints in MVP.
+- **Live process (Windows)**: Multi-step live work **must** use MCP (or one long-lived process) — `process_list` → `process_attach` **or** `process_launch` (CREATE_SUSPENDED) → `process_modules` → `process_resolve` (`static_to_live`) → `process_read` → optional `process_resume` / `process_regions` / `process_detach`. Launch is suspended spawn + read session, **not** debug break-at-entry. Never chain separate CLI `ghidrust process` spawns expecting the same `session_id` (sessions are in-process). Bytes ≠ types. No write/breakpoints in MVP.
- **IL2CPP offline → live**: (1) `il2cpp_touch_map` / `il2cpp_meta` / `il2cpp_map` for names + method RVAs (null = unknown offline; encrypted → `next_steps` with meta-sections/touch-map). (2) Require `body_class` not `shared_stub` / `semantics_mismatch` before treating a name as a hook target. (3) `decompile` + `follow_stub` for resolve stubs with mapped slots. (4) On `runtime_unresolved` / `trampoline_or_invoker` → live attach → `process_resolve(module, rva)` → `process_read`. (5) Multi-build work: `il2cpp map --baseline PREV.json` → inspect `build_skew` (stale **map catalog**, not only stale MCP binary).
- **Skill bootstrap**: GUI project open / Start writes `.grok/skills/ghidrust/SKILL.md` (disk or embedded fallback) and shows a fail-loud checklist (mcp/skill/agents/context + hash).
- **Do not**: invent enum ordinals; treat `section_notes` as proof of hooks; read `.gdecomp` dumps as text (metrics JSON only); hook shared stubs as unique gameplay methods.
@@ -56,12 +280,24 @@ cargo build -p ghidrust-gui --release
## Decision tree
```
+Need body of unknown/wrong bounds?
+ → disasm PATH --addr HEX --count N --linear [--pretty|--brief|--json --out FILE]
+ → if bounds_suspect / truncated end → function create PATH --addr HEX
+ → then disasm --flow / decompile on healed range
+
+Need CFG inside known-good function?
+ → disasm --flow (or default bounded)
+
+Avoid:
+ → treating short bounded (e.g. 5-insn function_end) as full body
+ → PowerShell python -c nested-quote pipelines
+
Need durable workspace?
YES → project create → import → analyze [--analyzer …] [--gpu] → export
NO → load | disasm | rtti | analyze [--analyzer …] [--gpu]
-Need machine-readable?
- → --json OR ghidrust mcp
+Need machine-readable without python -c?
+ → disasm --pretty / --brief OR --json --out FILE OR MCP disassemble
→ large dumps → artifact spill + artifact_query drain
Need install layout without shell?
@@ -97,27 +333,25 @@ Need decompiled C?
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; Ghidra head-to-head uses this only
+ Kept as regression baseline; 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 (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.
+ unions/bitfields/EH still evidence-gated after bar.
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]`
-Need Ghidra ↔ Ghidrust head-to-head?
- → `ghidra-headtohead PATH [--ghidra DIR] [--captured JSON] [--out FILE] [--json]`
- → `--ghidra DIR` auto-spawns `analyzeHeadless` (locates `support/analyzeHeadless(.bat)`,
+Need ↔ Ghidrust head-to-head?
+ → `-headtohead PATH [-- DIR] [--captured JSON] [--out FILE] [--json]`
+ → `-- DIR` auto-spawns `` (locates `support/(.bat)`,
writes the embedded `DecompileAndReport.java`, parses per-function `wall_us`).
→ `--captured JSON` replays a manual capture for offline / airgapped hosts.
- → When neither is supplied, the report is methodology-only: Ghidra column left blank
+ → When neither is supplied, the report is methodology-only: column left blank
+ full runbook (dev/GHIDRA_HEADTOHEAD.md). Spawn failures surface as factual
- `ghidra spawn failed: <reason>` notes — no fabricated timings.
+ ` spawn failed: <reason>` notes — no fabricated timings.
Unity player / IL2CPP?
→ unity-inventory GAME_DIR for install layout (assemblies, plugins, metadata)
@@ -182,13 +416,15 @@ ghidrust project analyze PROJ_DIR --file ID \
### MCP (`ghidrust mcp`)
-Requires **`tool_surface >= 3`** (prefer `>= 4` for bounded disasm / `get_calls_from`; current is `4`). Check with `server_info` after connect.
+Requires **`tool_surface >= 3`** (prefer **`>= 4`** for bounded disasm / `get_calls_from`; **`>= 5`** for decode tools). Check with `server_info` after connect.
| Tool | Args | Notes |
|------|------|-------|
-| `server_info` | — | Package `version`, `tool_surface`, features, live session_model |
+| `server_info` | — | Package `version`, `tool_surface`, `decode` block, features, live session_model |
| `load` | `path` **or** `project`+`file_id` | Map + `section_notes` + `resolved_path` |
-| `disassemble` | `path`, optional `addr`, `count`, **`linear`** | Bounded by function end by default; `linear:true` escapes; JSON `stop_reason` + `decode_gaps` |
+| `decode_support` | — | Engine version, 23 arches, options, syntax values, compile features |
+| `decode_query` | `query`, optional `arch`, `mode`, `id`, `index`, `bytes`, `addr`, `detail` | Introspection queries (see decode section) |
+| `disassemble` | `path`, optional `addr`, `count`, `skip_bad`, `linear`, `flow`, `arch`, `mode`, `syntax`, `detail`, `detail_real`, `skipdata`, `skipdata_mnemonic`, `skipdata_size`, `unsigned_imm`, `only_offset_branch`, `litbase`, `mnem_overrides` | Bounded by function end by default; JSON `stop_reason` + `decode_gaps` |
| `rtti` / `rtti_query` | `path`, optional `filter`/`exact`/`match` | Catalog; multi-vtable; artifact if large |
| `artifact_get` / `artifact_query` / `artifact_list` | `id` / optional `offset`/`limit` / optional `max` | Drain or list spilled results |
| `inventory` | `path`, optional `max_depth`/`hash` | PE VERSIONINFO + exe/dll catalog |
@@ -199,7 +435,7 @@ Requires **`tool_surface >= 3`** (prefer `>= 4` for bounded disasm / `get_calls_
| `get_xrefs_to` | `path`, `addr`, optional **`skip_stubs`**, **`classify`** | RIP/tables + data ptrs; IL2CPP stubs; `to_entry` |
| `get_xrefs_from` | `path`, `addr`, optional `count` | Xrefs from VA; `from_entry` / `from_function` / `to_entry` |
| `get_calls_from` | `path`, `addr` | Callee edges inside containing function (CLI: `xrefs --calls`) |
-| `get_string_xrefs` | `path`, `filter`, optional `encoding` | UTF-16LE parity (`ascii`\|`utf16le`\|`all`) |
+| `get_string_xrefs` | `path`, `filter`, optional `encoding` | UTF-16LE / ASCII modes (`ascii`\|`utf16le`\|`all`) |
| `list_imports` / `get_import_xrefs` | `path`, optional `dll`/`name` | PE IAT |
| `function_at` / `get_function_by_address` | `path`, `addr` | Containing function + `seed_kind` |
| `read_bytes` | `path`, `addr`, optional `count` | Raw VA hex dump |
@@ -214,7 +450,7 @@ Requires **`tool_surface >= 3`** (prefer `>= 4` for bounded disasm / `get_calls_
| `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 |
-| `process_list` / `process_attach` / `process_detach` / `process_modules` / `process_read` / `process_resolve` / `process_regions` | pid / session / module / rva / max | Live Process Bridge (Windows; read-only) |
+| `process_list` / `process_attach` / `process_launch` / `process_resume` / `process_detach` / `process_modules` / `process_read` / `process_resolve` / `process_regions` | pid / image / session / module / rva / max | Live Process Bridge (Windows; read-only; launch = CREATE_SUSPENDED) |
MCP launch: `ghidrust mcp` / `target/release/ghidrust.exe mcp` (stdio; no host-specific paths).
@@ -261,7 +497,9 @@ Add `--json` for structured stdout.
| Help | `ghidrust help` |
| Version | `ghidrust version` / `--version` / `-V` `[--json]` (package + `tool_surface`) |
| Load | `ghidrust load <path\|--project DIR --file-id ID>` |
-| Disasm | `ghidrust disasm <path> [--addr HEX] [--count N] [--skip-bad] [--linear\|--flow]` (bounded by fn end by default; JSON `stop_reason`) |
+| Disasm | `ghidrust disasm <path> [--addr HEX] [--count N] [--skip-bad] [--linear\|--flow] [--brief\|--pretty] [--arch ARCH] [--mode MODE] [--syntax SYNTAX] [--detail] [--no-detail] [--detail-real] [--skipdata] [--skipdata-mnemonic S] [--skipdata-size N] [--unsigned-imm] [--only-offset-branch] [--litbase HEX] [--mnem-override ID:MNEM]… [--out FILE] [--json]` |
+| Decode support | `ghidrust decode-support [--json]` |
+| Decode query | `ghidrust decode-query --query NAME [--arch] [--mode] [--id] [--index] [--bytes HEX] [--addr HEX] [--detail] [--json]` |
| Strings | `ghidrust strings <path> [--raw] [--encoding …] [--match MODE] [--limit N] [--out FILE] [--filter SUB]` |
| Xrefs | `ghidrust xrefs <path> (--to\|--from\|--string\|--import\|--calls) [--encoding ascii\|utf16le\|all] [--skip-stubs] [--classify] [--out FILE]` |
| Bytes | `ghidrust bytes <path> --addr HEX [--count N] [--out FILE]` |
@@ -271,7 +509,7 @@ Add `--json` for structured stdout.
| Inventory | `ghidrust inventory <dir> [--max-depth N] [--hash]` |
| Tree | `ghidrust tree <path> [--max-depth N] [--ext LIST] [--name GLOB]` |
| Artifact | `ghidrust artifact get\|query\|list …` |
-| Process (Windows) | `ghidrust process list\|attach\|detach\|modules\|read\|resolve\|regions …` |
+| Process (Windows) | `ghidrust process list\|attach\|launch\|resume\|detach\|modules\|read\|resolve\|regions …` |
| IL2CPP | `ghidrust il2cpp meta\|map\|touch-map\|stubs\|icalls …` (`--baseline` / `--meta-sections`; see `docs/IL2CPP.md`) |
| Unity inventory | `ghidrust unity-inventory <game-dir>` |
| RTTI catalog | `ghidrust rtti <path> [--filter\|--name\|--exact] [--match MODE]` |
@@ -282,7 +520,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 (shared-entry, Stage-1) | `ghidrust ghidra-headtohead <path> [--ghidra DIR] [--captured JSON] [--out F]` |
+| head-to-head (shared-entry, Stage-1) | `ghidrust -headtohead <path> [-- 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]` |
@@ -294,8 +532,19 @@ Add `--json` for structured stdout.
### Recipes
```bash
+# Unknown / suspect function body (linear-first; PowerShell-safe — no python -c)
+ghidrust disasm PATH --addr 0x140001234 --count 90 --linear --pretty
+ghidrust disasm PATH --addr 0x140001234 --count 90 --linear --json --out enum.json
+ghidrust function create PATH --addr 0x140001234
+ghidrust decompile PATH --addr 0x140001234 --json --out enum_decomp.json
+# Typed-object enum pattern (generic): manager* + type_bit:u32 + out* at a FindObjects-style call;
+# walk table slots; field offsets are evidence-gated from listing/callsite_hints — do not invent names.
+
# Quick triage
ghidrust load PATH --json
+ghidrust decode-support --json
+ghidrust decode-query --query insn_name --arch x86 --id 1 --json
+ghidrust disasm PATH --addr 0x140001234 --count 32 --detail --syntax intel --pretty
ghidrust load --project PROJ --file-id ID --json
ghidrust strings PATH --encoding all --filter SomeName --match token --limit 50 --json
ghidrust xrefs PATH --string SomeName --encoding all --skip-stubs --json
@@ -318,6 +567,8 @@ ghidrust artifact get ARTIFACT_ID
# Live process (Windows; read-only)
ghidrust process list --json
ghidrust process attach PID
+ghidrust process launch PATH.exe --args "…" --cwd DIR --json
+ghidrust process resume SESSION
ghidrust process modules SESSION --json
ghidrust process resolve SESSION --module app.exe --rva 0x1234 --json
ghidrust process read SESSION --addr LIVE_VA --size 64 --json
@@ -434,7 +685,6 @@ the exact evidence (blocks / insns / ir_ops / lift ratio / GPU backend).
| **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** | `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`. |
@@ -449,7 +699,6 @@ Related GPU / matrix benches (shipped, callable, **not** part of the eval sweep)
Guardrails to respect:
-- Don't claim Hex-Rays or Ghidra C parity. Emit only what the current stage produces (Stage-0 scaffolding or Stage-0.5 IR-informed lines).
- If `gpu-decompile` exits non-zero (`equivalence_multipass = false` or `mid_pipeline_host_reads != 0`), treat the GPU output as suspect — CPU multipass is the oracle.
- Small binaries often show GPU wall-clock slower than CPU: `pcie_upload` and adapter init dominate. Always read the `device_ms` split, not the wall-clock alone, when arguing about GPU perf.
@@ -471,7 +720,6 @@ Guardrails to respect:
**Do:** exact analyzer names; `--analyzer` or `--analyzers`; `--gpu` when GPU enrich wanted; `--json` for scripts; `analyzer-bench-matrix` for strategy list; prefer `decompile --stage05` when you want the IR-informed emit; `decompile-bench` to capture wall-clock + lift-ratio numbers.
-**Don't:** invent typed/Hex-Rays C beyond the emit stage in use; claim Ghidra MCP is Ghidrust; claim Ghidra-surpass metrics without captured benches; skip empty-result honesty; conflate PCIe with on-device time; claim absence of managed types from PE strings alone when IL2CPP metadata exists (run `il2cpp meta`); invent method RVAs when the map leaves them null.
---