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.

PE function seeding — New pe_functions.rs: parse Exception Directory / .pdata RUNTIME_FUNCTION + export seeds; feed Function Start Search / create path function create — CLI ghidrust function create + MCP function_create to create/heal functions at a VA (pdata/export/FSS; may synthesize SYNTH_*) seed_kind on functions — FunctionInfo tracks origin (pdata / export / method_pointer / prologue / manual / synthesized); exposed on function-at / MCP Bounded disasm — Default listing clamps to function end; --linear / linear:true escape hatch; JSON stop_reason (+ decode_gaps with --skip-bad) Call-graph xrefs — xrefs --calls / MCP get_calls_from; xref attribution fields (from_entry / to_entry / etc.) when functions exist Resolve / containing-fn path — Stronger mid-body → entry resolution wired for the new seed/create pipeline IL2CPP touch-map — New touch_map.rs + il2cpp touch-map / il2cpp_touch_map (heap substring → name / optional RVA) IL2CPP body proof — New body.rs: body_class, shared-stub summary, prologue hash; map rejects/flags shared stubs / mismatches before hooking IL2CPP map upgrades — --meta-sections, --baseline → build_skew, richer map JSON for multi-build / encrypted-meta next_steps tool_surface → 4 — Agents require >= 3 (touch-map / body_class / function_create); prefer >= 4 for bounded disasm / get_calls_from Docs / skill — README, docs/IL2CPP.md, skill/SKILL.md (+ README) updated for the new CLI/MCP SOPs and recommended workflows CLI / MCP / tests — Large ghidrust-cli surface + cli_mcp test updates; GUI mostly adapted to FunctionInfo::new / seed plumbing

oofze9541d312209
diff --git a/README.md b/README.md
index 7be6e44..2f0e2c3 100644
--- a/README.md
+++ b/README.md
@@ -16,7 +16,7 @@ It is **not** a Ghidra fork or wrapper. Analysis logic (loaders, decode, analyze
| **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 |
| **CPU-correct first** | CPU paths are the oracle; optional GPU paths must match or enrich them, not replace honesty with speed claims |
-| **Agent-ready** | Headless CLI + stdio MCP with artifact spill/drain, program identity (`path` or `project`+`file_id`), PE install inventory, RTTI catalog query, UTF-16 xref parity, live process bridge (Windows), and egui panes for every surface |
+| **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 |
| **Practical projects** | Create a workspace, import binaries, run analyzers, persist results (`analysis.bin`), reopen later |
---
@@ -181,9 +181,10 @@ 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) | Exactly one of: `--to` / `--from` / `--string` / `--import`; `--encoding ascii\|utf16le\|all`; `--skip-stubs` / `--classify` |
+| `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 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` |
+| `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` |
| `ghidrust decompile <path>` | Containing-fn resolve + Stage-1 pseudo-C | `--addr` (mid-body ok), `--follow-stub`, `--json` |
| `ghidrust gpu-decompile <path>` | GPU multipass at resolved entry; metrics JSON primary; `.gdecomp` opaque | `--addr`, `--metrics`, `--json` |
| `ghidrust rtti <path>` | RTTI catalog (filter/exact/match; multi-vtable honest) | `--filter`/`--name`/`--exact`, `--match`, `--json` |
@@ -191,9 +192,9 @@ First-class commands for the queries agents used to need ad-hoc scripts for. Sam
| `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 il2cpp meta\|map\|stubs\|icalls` | IL2CPP metadata + method map + resolve stubs + icalls | See [docs/IL2CPP.md](docs/IL2CPP.md) |
+| `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; `decode_gaps` when `--skip-bad` | `--addr HEX`, `--count N`, `--skip-bad`, `--json` |
+| `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` |
```bash
# Wide + ASCII string search (token match + limit; BOM-free --out)
@@ -207,15 +208,24 @@ ghidrust xrefs app.exe --string ResolutionWidth --skip-stubs --json
ghidrust imports app.exe --name ShellExecuteW --json
ghidrust xrefs app.exe --import ShellExecuteW --json
-# Body VA → function interval
+# Body VA → function interval (seed_kind: pdata|export|method_pointer|prologue|manual|synthesized)
ghidrust function-at app.exe --addr 0x14000d8ad --json
-# Keep listing through a decode hole
+# Create/heal a missing function (optional end; orphan resolve may synthesize SYNTH_*)
+ghidrust function create app.exe --addr 0x14000d8ad --json
+
+# Bounded disasm (default); --linear escapes function-end clamp; JSON includes stop_reason
ghidrust disasm app.exe --addr 0x14000d890 --count 40 --skip-bad
+ghidrust disasm app.exe --addr 0x14000d890 --count 40 --linear --json
+
+# Callee edges inside a function
+ghidrust xrefs app.exe --calls 0x14000d8ad --json
# Unity / IL2CPP (see docs/IL2CPP.md)
ghidrust unity-inventory /path/to/GameDir --json
+ghidrust il2cpp touch-map --meta /path/to/*_Data/il2cpp_data/Metadata/global-metadata.dat --filter Camera --json
ghidrust il2cpp meta /path/to/*_Data/il2cpp_data/Metadata/global-metadata.dat --filter Camera --json
+ghidrust il2cpp map --binary /path/to/GameAssembly.dll --meta /path/to/.../global-metadata.dat --baseline prev_map.json --json
ghidrust il2cpp stubs --binary /path/to/GameAssembly.dll --json
ghidrust decompile /path/to/GameAssembly.dll --addr 0x180012345 --follow-stub
```
@@ -280,18 +290,21 @@ ghidrust load --project ./MyProject --file-id <id> --json
ghidrust inventory /path/to/InstallRoot --max-depth 8 --json
ghidrust tree /path/to/GameDir --ext dll,dat --name "*meta*" --json
-# Listing (optional --skip-bad for undecodable holes)
+# Listing (bounded by fn end by default; --linear escapes; optional --skip-bad)
ghidrust disasm /path/to/app.exe --count 32
ghidrust disasm /path/to/app.exe --addr 0x140001000 --count 64 --skip-bad
+ghidrust disasm /path/to/app.exe --addr 0x140001000 --count 64 --linear --json
# Strings / xrefs / imports / containing function
ghidrust strings /path/to/app.exe --encoding all --filter SomeName --match token --limit 50 --json
ghidrust strings /path/to/blob.dat --raw --filter Camera --out camera.json --json
ghidrust xrefs /path/to/app.exe --string SomeName --encoding all --skip-stubs --classify --json
ghidrust xrefs /path/to/app.exe --to 0x140002010 --json
+ghidrust xrefs /path/to/app.exe --calls 0x140001000 --json
ghidrust imports /path/to/app.exe --json
ghidrust xrefs /path/to/app.exe --import CreateFileW --json
ghidrust function-at /path/to/app.exe --addr 0x140001234 --json
+ghidrust function create /path/to/app.exe --addr 0x140001234 --json
ghidrust rtti /path/to/app.exe --filter Widget --json
# Artifacts (drain large spilled dumps)
@@ -307,8 +320,9 @@ ghidrust process read <session_id> --addr 0x7ff… --size 64 --json
ghidrust process regions <session_id> --json
ghidrust process detach <session_id>
-# Unity player inventory + IL2CPP metadata / stubs / method map
+# Unity player inventory + IL2CPP touch-map / metadata / stubs / method map
ghidrust unity-inventory /path/to/GameDir --json
+ghidrust il2cpp touch-map --meta /path/to/Game_Data/il2cpp_data/Metadata/global-metadata.dat --filter Camera --json
ghidrust il2cpp meta /path/to/Game_Data/il2cpp_data/Metadata/global-metadata.dat --filter Camera --json
ghidrust il2cpp map --binary /path/to/GameAssembly.dll --meta /path/to/.../global-metadata.dat --json
ghidrust il2cpp stubs --binary /path/to/GameAssembly.dll --json
@@ -368,17 +382,18 @@ 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] [--json]` | x86-64 listing; `--skip-bad` advances one byte on decode failure |
+| `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 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) [--encoding ascii\|utf16le\|all] [--skip-stubs] [--classify] [--json]` | RIP-aware xrefs; string encoding parity |
+| `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 |
| `ghidrust imports <path> [--dll NAME] [--name NAME] [--json]` | PE import / IAT slots |
-| `ghidrust function-at <path> --addr HEX [--json]` | Containing function for a body VA |
+| `ghidrust function-at <path> --addr HEX [--json]` | Containing function for a body VA (`seed_kind`) |
+| `ghidrust function create <path> --addr HEX [--end HEX] [--json]` | Create/heal function at VA (pdata/export/FSS; may synthesize) |
| `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 il2cpp meta\|map\|stubs\|icalls …` | IL2CPP metadata / RVA map / resolve stubs / engine icalls ([docs/IL2CPP.md](docs/IL2CPP.md)) |
+| `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) |
| `ghidrust analyzers [--json]` | List Auto Analysis names |
@@ -397,7 +412,7 @@ MyProject/
`--json` and `--out FILE` write UTF-8 **without BOM**. Prefer `--out` over shell redirection when filters contain `:` (Windows path hazard). Decompile status lines go to stderr only with `--verbose` (avoids PowerShell `NativeCommandError` noise when scripting).
-Recommended early path: **strings / imports / xrefs** for orientation → **Function Start Search** + `function-at` → address tables → conventions/stack → RTTI → `decompile`. For Unity IL2CPP players: **`unity-inventory`** for install layout → **`il2cpp meta`** for managed types → stubs / map / `--follow-stub` as needed.
+Recommended early path: **strings / imports / xrefs** for orientation → Exception Directory / `.pdata` seeds + **Function Start Search** → `function create` for orphans → bounded `disasm` / `xrefs --calls` → address tables → conventions/stack → RTTI → `decompile`. For Unity IL2CPP players: **`unity-inventory`** → **`il2cpp touch-map`** (names) → **`il2cpp map`** (`body_class` / shared stubs; `--baseline` for `build_skew`) → stubs / `--follow-stub` as needed.
---
@@ -485,7 +500,7 @@ 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` | Listing + containing-fn resolve + `decode_gaps` |
+| `disassemble` | `path`, optional `addr`, `count`, `linear` | 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`) |
@@ -494,17 +509,20 @@ On Linux/macOS:
| `list_analyzers` | — | Auto Analysis option names |
| `analyze` | `path`, optional `analyzers[]`, optional `gpu` | Run analyzers (+ GPU enrich if `gpu: true`) |
| `list_strings` / `search_strings` | `path`, optional `encoding` (`ascii`\|`utf16`\|`all`), `filter`, `match` (`substr`\|`token`\|`whole`\|`glob`), `min`, `limit`, `raw` | ASCII / UTF-16LE strings; `raw:true` for non-PE/ELF blobs |
-| `get_xrefs_to` | `path`, `addr`, optional `skip_stubs`, `classify` | Xrefs **to** a VA; IL2CPP resolve-stub filter/label |
-| `get_xrefs_from` | `path`, `addr`, optional `count` | Xrefs **from** a VA |
+| `get_xrefs_to` | `path`, `addr`, optional `skip_stubs`, `classify` | Xrefs **to** a VA; IL2CPP resolve-stub filter/label; `to_entry` when known |
+| `get_xrefs_from` | `path`, `addr`, optional `count` | Xrefs **from** a VA; `from_entry` / `from_function` / `to_entry` when known |
+| `get_calls_from` | `path`, `addr` | Callee edges (`call`/`jmp`) inside the containing function |
| `get_string_xrefs` | `path`, `filter`, optional `encoding` | String xrefs with `ascii`\|`utf16le`\|`all` |
| `list_imports` | `path`, optional `dll` / `name` | PE IAT slots |
| `get_import_xrefs` | `path`, `name` | Code sites that reference an import IAT slot |
-| `function_at` / `get_function_by_address` | `path`, `addr` | Containing function for a body VA |
+| `function_at` / `get_function_by_address` | `path`, `addr` | Containing function for a body VA (`seed_kind`) |
| `read_bytes` | `path`, `addr`, optional `count` | Raw VA hex dump |
| `il2cpp_meta` | `path`, optional `filter` | Parse `global-metadata.dat` (v27/29/31); fail closed if encrypted |
-| `il2cpp_map` | `binary`, `meta`, optional `filter` | Metadata ↔ RVA map (`rva` null when unproven) |
+| `il2cpp_map` | `binary`, `meta` or `meta_sections`, optional `filter`, `baseline` | Metadata ↔ RVA + `body_class` / `shared_stubs` / `semantics_mismatch` / optional `build_skew` |
+| `il2cpp_touch_map` | `filter`, `meta` or `meta_sections`, optional `binary` | Substring touch-map over metadata heaps |
| `il2cpp_stubs` | `binary`, optional `filter`, `max` | List IL2CPP resolve stubs by icall name |
| `il2cpp_icalls` | `binary`, optional `filter` | Engine icall name↔fn tables |
+| `function_create` | `path`, `addr`, optional `end` | Create/heal a function at VA (pdata/export/FSS; may synthesize `SYNTH_*`) |
| `unity_inventory` | `path` | Unity player dir → assemblies, plugins, metadata, PE versions |
| `decompile` | `path`, optional `addr`, `count`, `stage`, `follow_stub` | Containing-fn resolve + Stage-1 expression-folded C; JSON includes `folded_temps`, `token_count`, `goto_rate`, `resolve` |
| `list_gpu_strategies` | — | Per-analyzer GPU strategy matrix |
@@ -516,7 +534,7 @@ On Linux/macOS:
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.
-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 `2` for live process + artifacts).
+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`**.
#### Analysis artifacts
@@ -545,9 +563,13 @@ Example agent-facing call shapes (conceptual):
{ "name": "get_string_xrefs", "arguments": { "path": "…/app.exe", "filter": "ResolutionWidth" } }
{ "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": "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" } }
{ "name": "il2cpp_meta", "arguments": { "path": "…/global-metadata.dat", "filter": "Camera" } }
-{ "name": "il2cpp_map", "arguments": { "binary": "…/GameAssembly.dll", "meta": "…/global-metadata.dat" } }
+{ "name": "il2cpp_map", "arguments": { "binary": "…/GameAssembly.dll", "meta": "…/global-metadata.dat", "baseline": "…/prev_map.json" } }
{ "name": "il2cpp_stubs", "arguments": { "binary": "…/GameAssembly.dll", "filter": "Camera" } }
{ "name": "decompile", "arguments": { "path": "…/GameAssembly.dll", "addr": "0x180012345", "follow_stub": true } }
{ "name": "analyze", "arguments": { "path": "…/app.exe", "analyzers": ["ASCII Strings", "Unicode Strings"], "gpu": true } }
diff --git a/crates/ghidrust-cli/src/friction.rs b/crates/ghidrust-cli/src/friction.rs
index f64375f..e1413a1 100644
--- a/crates/ghidrust-cli/src/friction.rs
+++ b/crates/ghidrust-cli/src/friction.rs
@@ -647,6 +647,8 @@ 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.
let r = resolve_function(prog, requested).map_err(|e| e.to_string())?;
let meta = resolve_result_json(&r);
if !r.ok {
diff --git a/crates/ghidrust-cli/src/main.rs b/crates/ghidrust-cli/src/main.rs
index d92edfd..66eda44 100644
--- a/crates/ghidrust-cli/src/main.rs
+++ b/crates/ghidrust-cli/src/main.rs
@@ -3,20 +3,23 @@
mod friction;
use ghidrust_core::{
- analyzer_catalog, analyze_path, artifact_get, artifact_query, collect_strings_bytes,
- collect_strings_opts, 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, 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,
+ 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,
};
use ghidrust_decomp::decompile_entry;
use ghidrust_il2cpp::{
- classify_at, correlate, filter_entries, find_resolve_stubs, follow_stub_target,
- is_resolve_stub_va, resolve_icalls_path, stub_matches_filter, to_script_json, Il2CppMetadata,
+ classify_at, compare_baseline, correlate, filter_entries, find_resolve_stubs,
+ follow_stub_target, is_resolve_stub_va, load_baseline_map, load_metadata_flexible,
+ resolve_icalls_path, stub_matches_filter, to_script_json, touch_map, Il2CppMetadata,
ResolveStub,
};
use ghidrust_unity_inventory::inventory_path;
@@ -33,8 +36,9 @@ const PACKAGE_VERSION: &str = env!("CARGO_PKG_VERSION");
/// Monotonic MCP tool-surface contract. Bump when tools are added/removed/renamed
/// or required args change in a breaking way. Skill documents a minimum.
-/// `2` = live process + artifacts + inventory / tree / rtti_query surface.
-const TOOL_SURFACE_VERSION: u32 = 2;
+/// `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;
fn package_version() -> &'static str {
PACKAGE_VERSION
@@ -52,7 +56,11 @@ fn server_info_json() -> Value {
"inventory",
"rtti_query",
"list_tree",
- "decompile_stage1"
+ "decompile_stage1",
+ "function_create",
+ "il2cpp_touch_map",
+ "bound_disasm",
+ "get_calls_from"
],
"live_process": {
"tools": [
@@ -200,6 +208,7 @@ fn main() -> ExitCode {
"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),
@@ -234,16 +243,21 @@ fn print_help() {
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] [--out FILE] [--json]\n\
+ ghidrust disasm <path> [--addr <hex>] [--count N] [--skip-bad] [--linear|--flow]\n\
+ [--out FILE] [--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\
- ghidrust xrefs <path> (--to HEX | --from HEX | --string FILTER | --import NAME)\n\
+ ghidrust xrefs <path> (--to HEX | --from HEX | --string FILTER | --import NAME | --calls HEX)\n\
[--encoding ascii|utf16le|all] [--skip-stubs] [--classify] [--out FILE] [--json]\n\
ghidrust imports <path> [--dll NAME] [--name NAME] [--json]\n\
ghidrust function-at <path> --addr HEX [--json]\n\
+ ghidrust function create <path> --addr HEX [--end HEX] [--json]\n\
ghidrust il2cpp meta <metadata.dat> [--filter SUB] [--out FILE] [--json]\n\
- ghidrust il2cpp map --binary <il2cpp> --meta <metadata.dat> [--filter SUB] [--script-json] [--out FILE] [--json]\n\
+ ghidrust il2cpp map --binary <il2cpp> --meta <metadata.dat>|--meta-sections DIR\n\
+ [--filter SUB] [--baseline PREV.json] [--baseline-strict] [--script-json]\n\
+ [--out FILE] [--json]\n\
+ ghidrust il2cpp touch-map --meta PATH|--meta-sections DIR --filter SUB [--binary PE] [--json]\n\
ghidrust il2cpp stubs --binary <il2cpp> [--filter SUB] [--max N] [--out FILE] [--json]\n\
ghidrust il2cpp icalls --binary <engine.dll> [--filter SUB] [--out FILE] [--json]\n\
ghidrust unity-inventory <game-dir> [--out FILE] [--json]\n\
@@ -643,6 +657,8 @@ fn cmd_disasm(args: &[String], json: bool) -> ExitCode {
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() {
@@ -659,6 +675,14 @@ fn cmd_disasm(args: &[String], json: bool) -> ExitCode {
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;
@@ -667,15 +691,34 @@ fn cmd_disasm(args: &[String], json: bool) -> ExitCode {
}
}
match load_path(&path) {
- Ok(prog) => {
+ Ok(mut prog) => {
let start = addr.or(prog.entry).unwrap_or(prog.image_base);
- match disassemble_range_opts(&prog, start, count, skip_bad) {
+ 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 {
@@ -690,6 +733,7 @@ fn cmd_disasm(args: &[String], json: bool) -> ExitCode {
result.first_gap_va.map(|v| format!("{v:#x}"))
);
}
+ println!("; stop_reason={:?} mode={:?}", result.stop_reason, mode);
})
}
}
@@ -894,6 +938,7 @@ fn cmd_xrefs(args: &[String], json: bool) -> ExitCode {
};
let mut to: Option<u64> = None;
let mut from: Option<u64> = None;
+ let mut calls: Option<u64> = None;
let mut string_filter: Option<String> = None;
let mut import_name: Option<String> = None;
let mut skip_stubs = false;
@@ -911,6 +956,10 @@ fn cmd_xrefs(args: &[String], json: bool) -> ExitCode {
from = parse_u64(&args[i + 1]).ok();
i += 2;
}
+ "--calls" if i + 1 < args.len() => {
+ calls = parse_u64(&args[i + 1]).ok();
+ i += 2;
+ }
"--string" if i + 1 < args.len() => {
string_filter = Some(args[i + 1].clone());
i += 2;
@@ -938,18 +987,55 @@ fn cmd_xrefs(args: &[String], json: bool) -> ExitCode {
_ => i += 1,
}
}
- let modes = [to.is_some(), from.is_some(), string_filter.is_some(), import_name.is_some()]
- .iter()
- .filter(|&&b| b)
- .count();
+ let modes = [
+ to.is_some(),
+ from.is_some(),
+ string_filter.is_some(),
+ import_name.is_some(),
+ calls.is_some(),
+ ]
+ .iter()
+ .filter(|&&b| b)
+ .count();
if modes != 1 {
eprintln!(
- "usage: ghidrust xrefs <path> (--to HEX | --from HEX | --string FILTER | --import NAME) [--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(prog) => {
+ Ok(mut prog) => {
+ if let Some(entry) = calls {
+ let _ = run_analyzers(&mut prog, &["Function Start Search"]);
+ let entry = resolve_function(&mut prog, entry)
+ .ok()
+ .and_then(|r| r.resolved_entry)
+ .unwrap_or(entry);
+ let edges = calls_callees(&prog, entry);
+ let rows: Vec<_> = edges
+ .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,
+ })
+ })
+ .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("-")
+ );
+ }
+ });
+ }
let mut refs = if let Some(t) = to {
xrefs_to(&prog, t, None)
} else if let Some(f) = from {
@@ -962,34 +1048,7 @@ fn cmd_xrefs(args: &[String], json: bool) -> ExitCode {
if skip_stubs {
refs.retain(|r| !is_resolve_stub_va(&prog, r.from));
}
- let rows: Vec<_> = refs
- .iter()
- .map(|r| {
- let stub = if classify {
- classify_at(&prog, r.from)
- } else {
- None
- };
- let kind = if stub.is_some() {
- "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}");
- }
- }
- json!({
- "from": format!("{:#x}", r.from),
- "to": format!("{:#x}", r.to),
- "kind": kind,
- "preview": preview,
- "encoding": r.encoding,
- })
- })
- .collect();
+ let rows: Vec<_> = refs.iter().map(|r| xref_row_json(r, &prog, classify)).collect();
emit_result(&rows, json, out_path.as_deref(), || {
for r in &rows {
println!(
@@ -1013,13 +1072,14 @@ 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|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),
other => {
@@ -1239,8 +1299,11 @@ fn cmd_il2cpp_meta(args: &[String], json: bool) -> ExitCode {
fn cmd_il2cpp_map(args: &[String], json: bool) -> ExitCode {
let mut binary: Option<PathBuf> = None;
let mut meta_path: Option<PathBuf> = None;
+ let mut meta_sections: Option<PathBuf> = None;
let mut filter: Option<String> = None;
let mut out_path: Option<PathBuf> = None;
+ let mut baseline_path: Option<PathBuf> = None;
+ let mut baseline_strict = false;
let mut script_json = false;
let mut i = 0;
while i < args.len() {
@@ -1253,6 +1316,10 @@ fn cmd_il2cpp_map(args: &[String], json: bool) -> ExitCode {
meta_path = Some(PathBuf::from(&args[i + 1]));
i += 2;
}
+ "--meta-sections" if i + 1 < args.len() => {
+ meta_sections = Some(PathBuf::from(&args[i + 1]));
+ i += 2;
+ }
"--filter" if i + 1 < args.len() => {
filter = Some(args[i + 1].clone());
i += 2;
@@ -1261,6 +1328,14 @@ fn cmd_il2cpp_map(args: &[String], json: bool) -> ExitCode {
out_path = Some(PathBuf::from(&args[i + 1]));
i += 2;
}
+ "--baseline" if i + 1 < args.len() => {
+ baseline_path = Some(PathBuf::from(&args[i + 1]));
+ i += 2;
+ }
+ "--baseline-strict" => {
+ baseline_strict = true;
+ i += 1;
+ }
"--script-json" => {
script_json = true;
i += 1;
@@ -1268,12 +1343,17 @@ fn cmd_il2cpp_map(args: &[String], json: bool) -> ExitCode {
_ => i += 1,
}
}
- let (Some(binary), Some(meta_path)) = (binary, meta_path) else {
+ let Some(binary) = binary else {
eprintln!(
- "usage: ghidrust il2cpp map --binary <il2cpp> --meta <metadata.dat> [--filter SUB] [--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");
+ return ExitCode::from(2);
+ }
let prog = match load_path(&binary) {
Ok(p) => p,
Err(e) => {
@@ -1281,10 +1361,20 @@ fn cmd_il2cpp_map(args: &[String], json: bool) -> ExitCode {
return ExitCode::FAILURE;
}
};
- let meta = match Il2CppMetadata::load_path(&meta_path) {
+ let meta = match load_metadata_flexible(meta_path.as_deref(), meta_sections.as_deref()) {
Ok(m) => m,
Err(e) => {
- eprintln!("error: {e}");
+ if let Some(payload) = e.to_structured_json() {
+ if json {
+ 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}");
+ }
return ExitCode::FAILURE;
}
};
@@ -1295,6 +1385,17 @@ fn cmd_il2cpp_map(args: &[String], json: bool) -> ExitCode {
map.entries
.retain(|e| e.full_name.to_ascii_lowercase().contains(&fl));
}
+ if let Some(bp) = &baseline_path {
+ match load_baseline_map(bp) {
+ Ok(prev) => {
+ map.build_skew = Some(compare_baseline(&map, &prev));
+ }
+ Err(e) => {
+ eprintln!("error loading baseline: {e}");
+ return ExitCode::FAILURE;
+ }
+ }
+ }
if script_json {
let script = to_script_json(&map);
return emit_result(&script, json, out_path.as_deref(), || {
@@ -1304,22 +1405,49 @@ fn cmd_il2cpp_map(args: &[String], json: bool) -> ExitCode {
);
});
}
- emit_result(&map, json, out_path.as_deref(), || {
+ let strict_fail = baseline_strict
+ && map
+ .build_skew
+ .as_ref()
+ .map(|s| !s.moved.is_empty())
+ .unwrap_or(false);
+ let code = emit_result(&map, json, out_path.as_deref(), || {
println!(
- "method map: {} entries, pointer_count={:?}",
+ "method map: {} entries, pointer_count={:?}, shared_stubs={}",
map.entries.len(),
- map.method_pointer_count
+ map.method_pointer_count,
+ map.shared_stubs.len()
);
for n in &map.notes {
println!(" note: {n}");
}
+ if let Some(skew) = &map.build_skew {
+ println!(
+ " build_skew: moved={} missing={} appeared={}",
+ skew.moved.len(),
+ skew.missing.len(),
+ skew.appeared.len()
+ );
+ }
for e in map.entries.iter().take(40) {
match e.rva {
- Some(rva) => println!(" {:#x} {}", rva, e.full_name),
+ Some(rva) => {
+ let bc = e
+ .body_class
+ .map(|c| format!(" [{c:?}]"))
+ .unwrap_or_default();
+ println!(" {:#x} {}{bc}", rva, 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));
+ ExitCode::FAILURE
+ } else {
+ code
+ }
}
Err(e) => {
eprintln!("error: {e}");
@@ -1328,6 +1456,96 @@ fn cmd_il2cpp_map(args: &[String], json: bool) -> ExitCode {
}
}
+fn cmd_il2cpp_touch_map(args: &[String], json: bool) -> ExitCode {
+ let mut meta_path: Option<PathBuf> = None;
+ let mut meta_sections: Option<PathBuf> = None;
+ let mut filter: Option<String> = None;
+ let mut binary: Option<PathBuf> = None;
+ let mut out_path: Option<PathBuf> = None;
+ let mut i = 0;
+ while i < args.len() {
+ match args[i].as_str() {
+ "--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 = Some(PathBuf::from(&args[i + 1]));
+ i += 2;
+ }
+ "--filter" if i + 1 < args.len() => {
+ filter = Some(args[i + 1].clone());
+ i += 2;
+ }
+ "--binary" if i + 1 < args.len() => {
+ binary = Some(PathBuf::from(&args[i + 1]));
+ i += 2;
+ }
+ "--out" if i + 1 < args.len() => {
+ out_path = Some(PathBuf::from(&args[i + 1]));
+ i += 2;
+ }
+ _ => i += 1,
+ }
+ }
+ let Some(filter) = filter else {
+ eprintln!(
+ "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");
+ return ExitCode::from(2);
+ }
+ let prog = match &binary {
+ Some(b) => match load_path(b) {
+ Ok(p) => Some(p),
+ Err(e) => {
+ eprintln!("error: {e}");
+ return ExitCode::FAILURE;
+ }
+ },
+ None => None,
+ };
+ match touch_map(
+ meta_path.as_deref(),
+ meta_sections.as_deref(),
+ &filter,
+ prog.as_ref(),
+ ) {
+ Ok(report) => emit_result(&report, json, out_path.as_deref(), || {
+ println!(
+ "touch-map filter={:?} rows={}",
+ report.filter, report.row_count
+ );
+ for r in report.rows.iter().take(40) {
+ println!(
+ " {:?} {} conf={:?} {}",
+ r.kind,
+ r.string,
+ r.confidence,
+ r.full_name.as_deref().unwrap_or("-")
+ );
+ }
+ }),
+ Err(e) => {
+ if let Some(payload) = e.to_structured_json() {
+ if json {
+ 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}");
+ }
+ ExitCode::FAILURE
+ }
+ }
+}
+
fn cmd_il2cpp_stubs(args: &[String], json: bool) -> ExitCode {
let mut binary: Option<PathBuf> = None;
let mut filter: Option<String> = None;
@@ -1484,6 +1702,70 @@ fn cmd_imports(args: &[String], json: bool) -> ExitCode {
}
}
+fn cmd_function(args: &[String], json: bool) -> ExitCode {
+ let sub = args.first().map(|s| s.as_str()).unwrap_or("");
+ match sub {
+ "create" => cmd_function_create(&args[1..], json),
+ _ => {
+ eprintln!("usage: ghidrust function create <path> --addr HEX [--end HEX] [--json]");
+ ExitCode::from(2)
+ }
+ }
+}
+
+fn cmd_function_create(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 end: Option<u64> = 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;
+ }
+ "--end" if i + 1 < args.len() => {
+ end = parse_u64(&args[i + 1]).ok();
+ i += 2;
+ }
+ _ => i += 1,
+ }
+ }
+ let Some(va) = addr else {
+ eprintln!("usage: ghidrust function create <path> --addr HEX [--end HEX] [--json]");
+ return ExitCode::from(2);
+ };
+ match load_path(&path) {
+ Ok(mut prog) => {
+ 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,
+ }));
+ } else {
+ println!(
+ "created {} [{:#x}, {:#x}) seed_kind={:?}",
+ f.name, f.entry, f.end, f.seed_kind
+ );
+ }
+ ExitCode::SUCCESS
+ }
+ Err(e) => {
+ eprintln!("error: {e}");
+ ExitCode::FAILURE
+ }
+ }
+}
+
fn cmd_function_at(args: &[String], json: bool) -> ExitCode {
let path = match path_arg(args) {
Ok(p) => p,
@@ -2851,6 +3133,35 @@ fn fmt_opt_va(v: Option<u64>) -> String {
v.map(|x| format!("{x:#x}")).unwrap_or_else(|| "-".into())
}
+fn xref_row_json(r: &ghidrust_core::XRef, prog: &Program, classify: bool) -> Value {
+ let stub = if classify {
+ classify_at(prog, r.from)
+ } else {
+ None
+ };
+ let kind = if stub.is_some() {
+ "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}");
+ }
+ }
+ 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}")),
+ })
+}
+
fn refs_json(refs: &[ghidrust_core::XRef]) -> Value {
Value::Array(
refs.iter()
@@ -2861,6 +3172,9 @@ fn refs_json(refs: &[ghidrust_core::XRef]) -> Value {
"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(),
@@ -3048,13 +3362,17 @@ fn tool_defs() -> Vec<ToolDef> {
},
ToolDef {
name: "disassemble",
- description: "Disassemble x86-64 at entry or given address",
+ 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.",
input_schema: json!({
"type": "object",
"properties": {
"path": { "type": "string" },
"addr": { "type": "string" },
- "count": { "type": "integer" }
+ "count": { "type": "integer" },
+ "linear": {
+ "type": "boolean",
+ "description": "Escape hatch: legacy unbounded linear walk (default false = bounded by function end)"
+ }
},
"required": ["path"]
}),
@@ -3190,15 +3508,31 @@ fn tool_defs() -> Vec<ToolDef> {
},
ToolDef {
name: "il2cpp_map",
- description: "Correlate metadata methods with binary RVAs when CodeRegistration validates. Unproven RVAs are null.",
+ 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" },
- "filter": { "type": "string" }
+ "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", "meta"]
+ "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.",
+ 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" }
+ },
+ "required": ["filter"]
}),
},
ToolDef {
@@ -3266,7 +3600,7 @@ fn tool_defs() -> Vec<ToolDef> {
},
ToolDef {
name: "get_xrefs_from",
- description: "Cross-references from a VA (disassemble forward)",
+ description: "Cross-references from a VA (disassemble forward); includes from_entry/from_function/to_entry when functions exist",
input_schema: json!({
"type": "object",
"properties": {
@@ -3277,6 +3611,18 @@ fn tool_defs() -> Vec<ToolDef> {
"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.",
+ input_schema: json!({
+ "type": "object",
+ "properties": {
+ "path": { "type": "string" },
+ "addr": { "type": "string", "description": "Function entry or mid-body VA" }
+ },
+ "required": ["path", "addr"]
+ }),
+ },
ToolDef {
name: "get_string_xrefs",
description: "Find strings by filter, then xrefs (encoding ascii|utf16le|all; interior LEA supported)",
@@ -3317,7 +3663,7 @@ fn tool_defs() -> Vec<ToolDef> {
},
ToolDef {
name: "function_at",
- description: "Containing function for a VA (runs Function Start Search if needed)",
+ 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": {
@@ -3329,7 +3675,7 @@ fn tool_defs() -> Vec<ToolDef> {
},
ToolDef {
name: "get_function_by_address",
- description: "Alias of function_at",
+ description: "Alias of function_at (includes seed_kind)",
input_schema: json!({
"type": "object",
"properties": {
@@ -3339,6 +3685,19 @@ fn tool_defs() -> Vec<ToolDef> {
"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.",
+ input_schema: json!({
+ "type": "object",
+ "properties": {
+ "path": { "type": "string" },
+ "addr": { "type": "string" },
+ "end": { "type": "string" }
+ },
+ "required": ["path", "addr"]
+ }),
+ },
]
}
@@ -3754,21 +4113,58 @@ fn call_tool(params: &Value) -> Result<String, String> {
.get("binary")
.and_then(|p| p.as_str())
.ok_or_else(|| "missing arguments.binary".to_string())?;
- let meta_path = args
- .get("meta")
+ let meta = args.get("meta").and_then(|p| p.as_str()).map(Path::new);
+ let meta_sections = args
+ .get("meta_sections")
.and_then(|p| p.as_str())
- .ok_or_else(|| "missing arguments.meta".to_string())?;
+ .map(Path::new);
+ if meta.is_none() && meta_sections.is_none() {
+ 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 prog = load_path(binary).map_err(|e| e.to_string())?;
- let meta = Il2CppMetadata::load_path(meta_path).map_err(|e| e.to_string())?;
+ let meta = load_metadata_flexible(meta, meta_sections).map_err(|e| {
+ e.to_structured_json()
+ .map(|v| serde_json::to_string_pretty(&v).unwrap_or_else(|_| e.to_string()))
+ .unwrap_or_else(|| e.to_string())
+ })?;
let mut map = correlate(&prog, &meta).map_err(|e| e.to_string())?;
if let Some(f) = filter {
let fl = f.to_ascii_lowercase();
map.entries
.retain(|e| e.full_name.to_ascii_lowercase().contains(&fl));
}
+ if let Some(bp) = baseline {
+ let prev = load_baseline_map(Path::new(bp)).map_err(|e| e.to_string())?;
+ map.build_skew = Some(compare_baseline(&map, &prev));
+ }
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);
+ let meta_sections = args
+ .get("meta_sections")
+ .and_then(|p| p.as_str())
+ .map(Path::new);
+ let filter = args
+ .get("filter")
+ .and_then(|f| f.as_str())
+ .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());
+ }
+ 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,
+ };
+ let report = touch_map(meta, meta_sections, filter, prog.as_ref()).map_err(|e| {
+ e.to_structured_json()
+ .map(|v| serde_json::to_string_pretty(&v).unwrap_or_else(|_| e.to_string()))
+ .unwrap_or_else(|| e.to_string())
+ })?;
+ Ok(serde_json::to_string_pretty(&report).unwrap())
+ }
"il2cpp_stubs" => {
let binary = args
.get("binary")
@@ -3869,22 +4265,7 @@ fn call_tool(params: &Value) -> Result<String, String> {
refs.retain(|r| !is_resolve_stub_va(&prog, r.from));
}
if classify {
- let rows: Vec<_> = refs
- .iter()
- .map(|r| {
- let kind = if classify_at(&prog, r.from).is_some() {
- "resolve_stub"
- } else {
- r.kind
- };
- json!({
- "from": format!("{:#x}", r.from),
- "to": format!("{:#x}", r.to),
- "kind": kind,
- "preview": r.preview,
- })
- })
- .collect();
+ let rows: Vec<_> = refs.iter().map(|r| xref_row_json(r, &prog, true)).collect();
return Ok(serde_json::to_string_pretty(&rows).unwrap());
}
Ok(serde_json::to_string_pretty(&refs_json(&refs)).unwrap())
@@ -3904,6 +4285,37 @@ fn call_tool(params: &Value) -> Result<String, String> {
let refs = xrefs_from(&prog, va, count);
Ok(serde_json::to_string_pretty(&refs_json(&refs)).unwrap())
}
+ "get_calls_from" => {
+ let path = args
+ .get("path")
+ .and_then(|p| p.as_str())
+ .ok_or_else(|| "missing arguments.path".to_string())?;
+ let addr = args
+ .get("addr")
+ .and_then(|a| a.as_str())
+ .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))?;
+ let edges = calls_callees(&prog, entry);
+ let rows: Vec<_> = edges
+ .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,
+ })
+ })
+ .collect();
+ Ok(serde_json::to_string_pretty(&json!({
+ "resolve": resolve_meta,
+ "calls": rows,
+ }))
+ .unwrap())
+ }
"get_string_xrefs" => {
let path = args
.get("path")
@@ -3971,6 +4383,7 @@ fn call_tool(params: &Value) -> Result<String, String> {
"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!({
@@ -3980,6 +4393,30 @@ fn call_tool(params: &Value) -> Result<String, String> {
.unwrap()),
}
}
+ "function_create" => {
+ let path = args
+ .get("path")
+ .and_then(|p| p.as_str())
+ .ok_or_else(|| "missing arguments.path".to_string())?;
+ let addr = args
+ .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()) {
+ Some(e) => Some(parse_u64(e)?),
+ None => None,
+ };
+ let mut prog = load_path(path).map_err(|e| e.to_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,
+ }))
+ .unwrap())
+ }
"list_analyzers" => {
let cat = analyzer_catalog();
Ok(serde_json::to_string_pretty(&cat).unwrap())
@@ -4199,16 +4636,30 @@ fn call_tool(params: &Value) -> Result<String, String> {
.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 result = disassemble_range_opts(&prog, start, count, true)
+ 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,
diff --git a/crates/ghidrust-cli/tests/cli_mcp.rs b/crates/ghidrust-cli/tests/cli_mcp.rs
index 6ae4a68..2b85c1b 100644
--- a/crates/ghidrust-cli/tests/cli_mcp.rs
+++ b/crates/ghidrust-cli/tests/cli_mcp.rs
@@ -232,14 +232,20 @@ fn mcp_server_info_and_live_tools() {
"process_read",
"artifact_query",
"inventory",
+ "il2cpp_touch_map",
+ "function_create",
] {
assert!(s.contains(tool), "missing {tool} in {s}");
}
- // tool_surface must be at least 2 (not a placeholder zero)
- assert!(
- s.contains("\"toolSurface\":2")
- || s.contains("\"tool_surface\": 2")
- || s.contains("\"tool_surface\":2"),
- "expected tool_surface >= 2 in {s}"
- );
+ // tool_surface must be at least 3 (touch-map / body_class / function_create surface)
+ let surface_ok = s.contains("\"toolSurface\":3")
+ || s.contains("\"tool_surface\": 3")
+ || s.contains("\"tool_surface\":3")
+ || s.contains("\"toolSurface\":4")
+ || s.contains("\"tool_surface\": 4")
+ || s.contains("\"tool_surface\":4")
+ || s.contains("\"toolSurface\":5")
+ || s.contains("\"tool_surface\": 5")
+ || s.contains("\"tool_surface\":5");
+ assert!(surface_ok, "expected tool_surface >= 3 in {s}");
}
diff --git a/crates/ghidrust-core/src/analyzers/aggressive.rs b/crates/ghidrust-core/src/analyzers/aggressive.rs
index 4316f46..47b1694 100644
--- a/crates/ghidrust-core/src/analyzers/aggressive.rs
+++ b/crates/ghidrust-core/src/analyzers/aggressive.rs
@@ -56,16 +56,10 @@ pub fn run(prog: &mut Program) -> Result<AnalyzerOutput> {
if end > va + 2 {
recovered.push(DiscoveredRange { start: va, end });
if prog.function_at(va).is_none() {
- prog.analysis.functions.push(FunctionInfo {
- entry: va,
- end,
- name: format!("AIF_{va:08x}"),
- calling_convention: None,
- noreturn: false,
- varargs: false,
- parameters: Vec::new(),
- stack_locals: Vec::new(),
- });
+ prog.analysis.functions.push(
+ FunctionInfo::new(va, end, format!("AIF_{va:08x}"))
+ .with_seed_kind(crate::program::FunctionSeedKind::Prologue),
+ );
}
i += (end - va) as usize;
continue;
diff --git a/crates/ghidrust-core/src/analyzers/function_start.rs b/crates/ghidrust-core/src/analyzers/function_start.rs
index 54b0774..2e4a8b4 100644
--- a/crates/ghidrust-core/src/analyzers/function_start.rs
+++ b/crates/ghidrust-core/src/analyzers/function_start.rs
@@ -1,21 +1,41 @@
-//! Function Start Search — entry, symbols, and real prologues only (no mid-body seeds).
+//! Function Start Search — PE pdata/exports first, then entry, symbols, prologues.
use super::AnalyzerOutput;
-use crate::disasm::decode_one;
use crate::error::Result;
-use crate::program::{FunctionInfo, Program};
+use crate::pe_functions::{
+ grow_function, parse_export_code_vas, parse_runtime_functions, RuntimeFunction,
+};
+use crate::program::{FunctionInfo, FunctionSeedKind, Program};
pub fn run(prog: &mut Program) -> Result<AnalyzerOutput> {
- let mut seeds: Vec<u64> = Vec::new();
+ let mut seeds: Vec<(u64, FunctionSeedKind, Option<u64>, Option<String>)> = Vec::new();
+
+ // 1) PE Exception Directory — authoritative begins/ends (mandatory PE64 pass).
+ let runtime: Vec<RuntimeFunction> = parse_runtime_functions(prog);
+ for rf in &runtime {
+ seeds.push((
+ rf.begin_va,
+ FunctionSeedKind::Pdata,
+ Some(rf.end_va),
+ None,
+ ));
+ }
+
+ // 2) PE exports that land in executable memory.
+ for (va, name) in parse_export_code_vas(prog) {
+ seeds.push((va, FunctionSeedKind::Export, None, Some(name)));
+ }
+
+ // 3) Image entry.
if let Some(e) = prog.entry {
- seeds.push(e);
+ seeds.push((e, FunctionSeedKind::Prologue, None, None));
}
- // Symbol VAs that look like code entries (not demangle-only / not mid-string)
+
+ // 4) Symbol VAs that look like code entries.
for s in &prog.analysis.symbols {
if !prog.contains_va(s.va) {
continue;
}
- // Only seed symbols that sit at executable addresses with a plausible start
if !prog
.blocks
.iter()
@@ -23,13 +43,18 @@ pub fn run(prog: &mut Program) -> Result<AnalyzerOutput> {
{
continue;
}
- if s.name.starts_with("FUN_") || s.name.starts_with("Lab") || s.name.starts_with("synth_") {
- seeds.push(s.va);
+ if s.name.starts_with("FUN_") || s.name.starts_with("Lab") || s.name.starts_with("synth_")
+ {
+ seeds.push((
+ s.va,
+ FunctionSeedKind::Prologue,
+ None,
+ Some(s.name.clone()),
+ ));
}
}
- // Prologue scan: push rbp; mov rbp, rsp — full 4-byte pattern only
- // Also: standalone function start as `sub rsp, imm` ONLY when not preceded by
- // push rbp / mov rbp (i.e. not the second instruction of a frame prologue).
+
+ // 5) Prologue scan: push rbp; mov rbp, rsp — and standalone sub rsp, imm.
for block in prog.exec_blocks() {
let b = &block.bytes;
let mut i = 0;
@@ -37,12 +62,10 @@ pub fn run(prog: &mut Program) -> Result<AnalyzerOutput> {
let at_push_rbp_mov =
b[i] == 0x55 && b[i + 1] == 0x48 && b[i + 2] == 0x89 && b[i + 3] == 0xE5;
if at_push_rbp_mov {
- seeds.push(block.va + i as u64);
+ seeds.push((block.va + i as u64, FunctionSeedKind::Prologue, None, None));
i += 4;
continue;
}
- // sub rsp, imm8 as function start: require not mid-prologue
- // (i.e. previous bytes are not `55 48 89 e5`)
if b[i] == 0x48 && b[i + 1] == 0x83 && b[i + 2] == 0xEC {
let mid_frame = i >= 4
&& b[i - 4] == 0x55
@@ -50,103 +73,103 @@ pub fn run(prog: &mut Program) -> Result<AnalyzerOutput> {
&& b[i - 2] == 0x89
&& b[i - 1] == 0xE5;
if !mid_frame {
- // Also skip if already inside a grown function range (filled later)
- seeds.push(block.va + i as u64);
+ seeds.push((block.va + i as u64, FunctionSeedKind::Prologue, None, None));
}
}
i += 1;
}
}
- seeds.sort_unstable();
- seeds.dedup();
- // Grow functions first, then drop seeds that fall inside another function's body
- let mut raw: Vec<(u64, u64, String)> = Vec::new();
- for entry in seeds {
- let end = grow_function(prog, entry);
- let name = prog
- .analysis
- .symbols
- .iter()
- .find(|s| s.va == entry)
- .map(|s| s.name.clone())
+ // Prefer pdata / export over weaker seeds at the same VA.
+ seeds.sort_by(|(a, ka, _, _), (b, kb, _, _)| {
+ a.cmp(b).then_with(|| seed_priority(ka).cmp(&seed_priority(kb)))
+ });
+ let mut merged: Vec<(u64, FunctionSeedKind, Option<u64>, Option<String>)> = Vec::new();
+ for (va, kind, pdata_end, name) in seeds {
+ if let Some(last) = merged.last_mut() {
+ if last.0 == va {
+ if seed_priority(&kind) < seed_priority(&last.1) {
+ last.1 = kind;
+ }
+ if last.2.is_none() {
+ last.2 = pdata_end;
+ }
+ if last.3.is_none() {
+ last.3 = name;
+ }
+ continue;
+ }
+ }
+ merged.push((va, kind, pdata_end, name));
+ }
+ let seeds = merged;
+
+ // Grow: end = min(pdata.end, next_seed, first_ret, int3_run>=2, decode_bail)
+ let mut raw: Vec<FunctionInfo> = Vec::new();
+ for (i, (entry, kind, pdata_end, name_opt)) in seeds.iter().enumerate() {
+ let next_seed = seeds.get(i + 1).map(|(v, _, _, _)| *v);
+ let hard = match (pdata_end, next_seed) {
+ (Some(pe), Some(ns)) => Some((*pe).min(ns)),
+ (Some(pe), None) => Some(*pe),
+ (None, Some(ns)) => Some(ns),
+ (None, None) => None,
+ };
+ let end = grow_function(prog, *entry, hard);
+ let name = name_opt
+ .clone()
+ .or_else(|| {
+ prog.analysis
+ .symbols
+ .iter()
+ .find(|s| s.va == *entry)
+ .map(|s| s.name.clone())
+ })
.unwrap_or_else(|| format!("FUN_{entry:08x}"));
- raw.push((entry, end, name));
+ raw.push(FunctionInfo::new(*entry, end, name).with_seed_kind(*kind));
}
+
// Prefer earlier starts: discard any start strictly inside a previous [entry,end)
- raw.sort_by_key(|(e, _, _)| *e);
+ raw.sort_by_key(|f| f.entry);
let mut functions = Vec::new();
- for (entry, end, name) in raw {
+ for f in raw {
let covered = functions
.iter()
- .any(|f: &FunctionInfo| entry > f.entry && entry < f.end);
+ .any(|prev: &FunctionInfo| f.entry > prev.entry && f.entry < prev.end);
if covered {
continue;
}
- functions.push(FunctionInfo {
- entry,
- end,
- name,
- calling_convention: None,
- noreturn: false,
- varargs: false,
- parameters: Vec::new(),
- stack_locals: Vec::new(),
- });
+ functions.push(f);
}
if functions.is_empty() {
if let Some(e) = prog.entry {
- functions.push(FunctionInfo {
- entry: e,
- end: grow_function(prog, e),
- name: format!("FUN_{e:08x}"),
- calling_convention: None,
- noreturn: false,
- varargs: false,
- parameters: Vec::new(),
- stack_locals: Vec::new(),
- });
+ functions.push(
+ FunctionInfo::new(e, grow_function(prog, e, None), format!("FUN_{e:08x}"))
+ .with_seed_kind(FunctionSeedKind::Prologue),
+ );
}
}
let n = functions.len();
+ let pdata_n = functions
+ .iter()
+ .filter(|f| f.seed_kind == Some(FunctionSeedKind::Pdata))
+ .count();
prog.analysis.functions = functions.clone();
Ok(AnalyzerOutput {
name: "Function Start Search".into(),
status: "ok".into(),
- message: format!("identified {n} function start(s)"),
+ message: format!("identified {n} function start(s) ({pdata_n} from PE Exception Directory)"),
functions: Some(functions),
..Default::default()
})
}
-fn grow_function(prog: &Program, entry: u64) -> u64 {
- let mut va = entry;
- let mut end = entry;
- let mut skipped = 0u32;
- // Grow generously so mid-body VAs fall inside [entry, end).
- for _ in 0..4096 {
- let Some(bytes) = prog.read_va(va, 15) else {
- break;
- };
- match decode_one(&bytes, va) {
- Ok(insn) => {
- skipped = 0;
- end = va + insn.length as u64;
- if insn.mnemonic == "ret" {
- break;
- }
- va = end;
- }
- Err(_) => {
- // Skip bad bytes to keep extent continuous across decode holes.
- skipped += 1;
- if skipped > 16 {
- break;
- }
- va = va.wrapping_add(1);
- end = end.max(va);
- }
- }
+fn seed_priority(k: &FunctionSeedKind) -> u8 {
+ match k {
+ FunctionSeedKind::Pdata => 0,
+ FunctionSeedKind::Export => 1,
+ FunctionSeedKind::MethodPointer => 2,
+ FunctionSeedKind::Prologue => 3,
+ FunctionSeedKind::Manual => 4,
+ FunctionSeedKind::Synthesized => 5,
}
- end.max(entry + 1)
}
diff --git a/crates/ghidrust-core/src/analyzers/noreturn.rs b/crates/ghidrust-core/src/analyzers/noreturn.rs
index 9f296fb..a069e97 100644
--- a/crates/ghidrust-core/src/analyzers/noreturn.rs
+++ b/crates/ghidrust-core/src/analyzers/noreturn.rs
@@ -27,16 +27,10 @@ pub fn run(prog: &mut Program) -> Result<AnalyzerOutput> {
f.noreturn = true;
marked.push(s.va);
} else {
- prog.analysis.functions.push(FunctionInfo {
- entry: s.va,
- end: s.va + 1,
- name: s.name.clone(),
- calling_convention: Some("stdcall".into()),
- noreturn: true,
- varargs: false,
- parameters: Vec::new(),
- stack_locals: Vec::new(),
- });
+ let mut fi = FunctionInfo::new(s.va, s.va + 1, s.name.clone());
+ fi.calling_convention = Some("stdcall".into());
+ fi.noreturn = true;
+ prog.analysis.functions.push(fi);
marked.push(s.va);
}
}
diff --git a/crates/ghidrust-core/src/analyzers/variadic.rs b/crates/ghidrust-core/src/analyzers/variadic.rs
index 664bc8a..24ea935 100644
--- a/crates/ghidrust-core/src/analyzers/variadic.rs
+++ b/crates/ghidrust-core/src/analyzers/variadic.rs
@@ -17,16 +17,11 @@ pub fn run(prog: &mut Program) -> Result<AnalyzerOutput> {
f.varargs = true;
entries.push(s.va);
} else {
- prog.analysis.functions.push(FunctionInfo {
- entry: s.va,
- end: s.va + 1,
- name: s.name.clone(),
- calling_convention: Some("cdecl".into()),
- noreturn: false,
- varargs: true,
- parameters: vec!["format".into()],
- stack_locals: Vec::new(),
- });
+ let mut fi = FunctionInfo::new(s.va, s.va + 1, s.name.clone());
+ fi.calling_convention = Some("cdecl".into());
+ fi.varargs = true;
+ fi.parameters = vec!["format".into()];
+ prog.analysis.functions.push(fi);
entries.push(s.va);
}
}
diff --git a/crates/ghidrust-core/src/disasm.rs b/crates/ghidrust-core/src/disasm.rs
index f9f3e50..6a6f89b 100644
--- a/crates/ghidrust-core/src/disasm.rs
+++ b/crates/ghidrust-core/src/disasm.rs
@@ -5,8 +5,33 @@
use crate::error::{Error, Result};
use crate::program::Program;
+use serde::Serialize;
+use std::collections::{HashSet, VecDeque};
pub use ghidrust_decode::{decode_one, Instruction};
+/// 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.
+ Bounded,
+ /// Follow fallthrough and branch targets; never leave `[start, bound_end)` when bound set.
+ Flow,
+ /// Legacy count-walk (no bound / int3 / seed stops).
+ Linear,
+}
+
+/// Why a disassembly pass stopped.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
+#[serde(rename_all = "snake_case")]
+pub enum DisasmStopReason {
+ Count,
+ FunctionEnd,
+ Int3,
+ NextSeed,
+ DecodeFail,
+}
+
pub fn disassemble_at(prog: &Program, va: u64) -> Result<Instruction> {
let bytes = prog
.read_va(va, 15)
@@ -19,30 +44,83 @@ pub fn disassemble_range(prog: &Program, start: u64, max_insns: usize) -> Result
}
/// Result of a continuity-aware disassembly pass.
-#[derive(Debug, Clone)]
+#[derive(Debug, Clone, Serialize)]
pub struct DisasmRangeResult {
pub insns: Vec<Instruction>,
/// Number of undecodable byte positions skipped (soft-fail holes).
pub decode_gaps: usize,
/// First gap VA when any gaps were skipped.
pub first_gap_va: Option<u64>,
+ /// Why the walk stopped.
+ pub stop_reason: DisasmStopReason,
+ /// 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")]
+ pub end: Option<u64>,
}
/// Disassemble up to `max_insns` instructions from `start`.
///
/// When `skip_bad` is true, undecodable bytes advance by one and continue
/// (listing continuity across sparse decode holes). `decode_gaps` counts skips.
+/// Delegates to [`DisasmMode::Linear`].
pub fn disassemble_range_opts(
prog: &Program,
start: u64,
max_insns: usize,
skip_bad: bool,
+) -> Result<DisasmRangeResult> {
+ disassemble_range_ex(prog, start, max_insns, skip_bad, DisasmMode::Linear, None)
+}
+
+/// True when `va` begins an int3 padding run (`≥ 2` consecutive `0xCC` bytes).
+pub fn int3_padding_at(prog: &Program, va: u64) -> bool {
+ match prog.read_va(va, 2) {
+ Some(b) if b.len() >= 2 && b[0] == 0xCC && b[1] == 0xCC => true,
+ _ => false,
+ }
+}
+
+/// Extended disassembly with mode + optional exclusive upper bound.
+pub fn disassemble_range_ex(
+ prog: &Program,
+ start: u64,
+ max_insns: usize,
+ skip_bad: bool,
+ mode: DisasmMode,
+ bound_end: Option<u64>,
+) -> 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 result = match mode {
+ DisasmMode::Linear => disasm_linear(prog, start, max_insns, skip_bad)?,
+ DisasmMode::Bounded => {
+ disasm_bounded(prog, start, max_insns, skip_bad, bound_end, self_entry)?
+ }
+ DisasmMode::Flow => disasm_flow(prog, start, max_insns, skip_bad, bound_end, self_entry)?,
+ };
+ result.entry = entry;
+ result.end = end;
+ Ok(result)
+}
+
+fn disasm_linear(
+ prog: &Program,
+ start: u64,
+ max_insns: usize,
+ skip_bad: bool,
) -> Result<DisasmRangeResult> {
let mut out = Vec::new();
let mut va = start;
let mut steps = 0usize;
let mut decode_gaps = 0usize;
let mut first_gap_va = None;
+ let mut stop_reason = DisasmStopReason::Count;
let max_steps = if skip_bad {
max_insns.saturating_mul(8).max(max_insns)
} else {
@@ -65,6 +143,85 @@ pub fn disassemble_range_opts(
va = va.wrapping_add(1);
continue;
}
+ stop_reason = DisasmStopReason::DecodeFail;
+ break;
+ }
+ }
+ }
+ if out.is_empty() {
+ return Err(Error::Decode(format!("no instructions at {start:#x}")));
+ }
+ if out.len() >= max_insns {
+ stop_reason = DisasmStopReason::Count;
+ }
+ Ok(DisasmRangeResult {
+ insns: out,
+ decode_gaps,
+ first_gap_va,
+ stop_reason,
+ entry: None,
+ end: None,
+ })
+}
+
+fn disasm_bounded(
+ prog: &Program,
+ start: u64,
+ max_insns: usize,
+ skip_bad: bool,
+ bound_end: Option<u64>,
+ self_entry: Option<u64>,
+) -> Result<DisasmRangeResult> {
+ let mut out = Vec::new();
+ let mut va = start;
+ let mut steps = 0usize;
+ let mut decode_gaps = 0usize;
+ let mut first_gap_va = None;
+ let mut stop_reason = DisasmStopReason::Count;
+ let max_steps = if skip_bad {
+ max_insns.saturating_mul(8).max(max_insns)
+ } else {
+ max_insns
+ };
+ while out.len() < max_insns && steps < max_steps {
+ if let Some(end) = bound_end {
+ if va >= end {
+ stop_reason = DisasmStopReason::FunctionEnd;
+ break;
+ }
+ }
+ if va != start && is_next_seed(prog, va, self_entry) {
+ stop_reason = DisasmStopReason::NextSeed;
+ break;
+ }
+ if int3_padding_at(prog, va) {
+ stop_reason = DisasmStopReason::Int3;
+ break;
+ }
+ steps += 1;
+ match disassemble_at(prog, 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.
+ if va >= end {
+ stop_reason = DisasmStopReason::FunctionEnd;
+ break;
+ }
+ }
+ out.push(insn);
+ va = next;
+ }
+ Err(_) => {
+ if skip_bad {
+ if first_gap_va.is_none() {
+ first_gap_va = Some(va);
+ }
+ decode_gaps += 1;
+ va = va.wrapping_add(1);
+ continue;
+ }
+ stop_reason = DisasmStopReason::DecodeFail;
break;
}
}
@@ -72,17 +229,193 @@ pub fn disassemble_range_opts(
if out.is_empty() {
return Err(Error::Decode(format!("no instructions at {start:#x}")));
}
+ if out.len() >= max_insns && stop_reason == DisasmStopReason::Count {
+ stop_reason = DisasmStopReason::Count;
+ }
Ok(DisasmRangeResult {
insns: out,
decode_gaps,
first_gap_va,
+ stop_reason,
+ entry: None,
+ end: None,
})
}
+fn disasm_flow(
+ prog: &Program,
+ start: u64,
+ max_insns: usize,
+ skip_bad: bool,
+ bound_end: Option<u64>,
+ self_entry: Option<u64>,
+) -> Result<DisasmRangeResult> {
+ let mut out = Vec::new();
+ let mut decode_gaps = 0usize;
+ let mut first_gap_va = None;
+ let mut stop_reason = DisasmStopReason::Count;
+ let mut visited = HashSet::new();
+ let mut queue = VecDeque::new();
+ queue.push_back(start);
+
+ while out.len() < max_insns {
+ let Some(va) = queue.pop_front() else {
+ break;
+ };
+ if !visited.insert(va) {
+ continue;
+ }
+ if let Some(end) = bound_end {
+ if va < start || va >= end {
+ continue;
+ }
+ }
+ if va != start && is_next_seed(prog, va, self_entry) {
+ if out.is_empty() {
+ // Should not happen for start; keep scanning other paths.
+ continue;
+ }
+ stop_reason = DisasmStopReason::NextSeed;
+ continue;
+ }
+ if int3_padding_at(prog, va) {
+ stop_reason = DisasmStopReason::Int3;
+ continue;
+ }
+ match disassemble_at(prog, va) {
+ Ok(insn) => {
+ let fallthrough = va.wrapping_add(insn.length.max(1) as u64);
+ let mnem = insn.mnemonic.clone();
+ let targets = flow_targets(&insn);
+ out.push(insn);
+
+ for t in targets {
+ if in_flow_bounds(t, start, bound_end) {
+ queue.push_back(t);
+ }
+ }
+ if !is_terminal_transfer(mnem.as_str())
+ && in_flow_bounds(fallthrough, start, bound_end)
+ {
+ queue.push_back(fallthrough);
+ }
+ }
+ Err(_) => {
+ if skip_bad {
+ if first_gap_va.is_none() {
+ first_gap_va = Some(va);
+ }
+ decode_gaps += 1;
+ let next = va.wrapping_add(1);
+ if in_flow_bounds(next, start, bound_end) {
+ queue.push_back(next);
+ }
+ continue;
+ }
+ stop_reason = DisasmStopReason::DecodeFail;
+ if out.is_empty() {
+ break;
+ }
+ }
+ }
+ }
+
+ if out.is_empty() {
+ return Err(Error::Decode(format!("no instructions at {start:#x}")));
+ }
+ if out.len() >= max_insns {
+ stop_reason = DisasmStopReason::Count;
+ } else if bound_end.is_some()
+ && queue
+ .iter()
+ .all(|&va| bound_end.map(|e| va >= e).unwrap_or(false))
+ && stop_reason == DisasmStopReason::Count
+ {
+ stop_reason = DisasmStopReason::FunctionEnd;
+ }
+ // Stable address order for deterministic listings.
+ out.sort_by_key(|i| i.address);
+ out.dedup_by_key(|i| i.address);
+ Ok(DisasmRangeResult {
+ insns: out,
+ decode_gaps,
+ first_gap_va,
+ stop_reason,
+ entry: None,
+ end: None,
+ })
+}
+
+fn in_flow_bounds(va: u64, start: u64, bound_end: Option<u64>) -> bool {
+ match bound_end {
+ Some(end) => va >= start && va < end,
+ None => true,
+ }
+}
+
+fn is_next_seed(prog: &Program, va: u64, self_entry: Option<u64>) -> bool {
+ prog.analysis
+ .functions
+ .iter()
+ .any(|f| f.entry == va && Some(f.entry) != self_entry)
+}
+
+fn is_terminal_transfer(mnem: &str) -> bool {
+ matches!(
+ mnem,
+ "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"
+ )
+}
+
+fn flow_targets(insn: &Instruction) -> Vec<u64> {
+ if !is_flow_mnemonic(&insn.mnemonic) {
+ return Vec::new();
+ }
+ // 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.
+ out.retain(|t| *t != insn.address);
+ out
+}
+
#[cfg(test)]
mod tests {
use super::*;
- use crate::program::{MemoryBlock, Program};
+ use crate::program::{FunctionInfo, MemoryBlock, Program};
#[test]
fn decode_push_rbp_mov_rbp_rsp() {
@@ -129,5 +462,83 @@ mod tests {
listing.insns
);
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
+ let mut bytes = vec![0x55, 0x48, 0x89, 0xe5, 0xc3, 0xcc, 0xcc, 0x31, 0xc0, 0xc3];
+ let base = 0x140001000u64;
+ let fn_a_entry = base;
+ let fn_a_end = base + 7; // exclusive end at int3 padding start
+ let fn_b_entry = base + 7;
+ let fn_b_end = base + bytes.len() as u64;
+
+ let mut prog = Program::new("t".into(), "PE32+");
+ prog.blocks.push(MemoryBlock {
+ name: ".text".into(),
+ va: base,
+ size: bytes.len() as u64,
+ bytes: std::mem::take(&mut bytes),
+ readable: true,
+ writable: false,
+ executable: true,
+ });
+ prog.analysis
+ .functions
+ .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"));
+
+ let listing = disassemble_range_ex(
+ &prog,
+ fn_a_entry,
+ 64,
+ false,
+ DisasmMode::Bounded,
+ Some(fn_a_end),
+ )
+ .unwrap();
+
+ assert!(
+ listing.insns.iter().all(|i| i.address < fn_b_entry),
+ "bounded listing leaked into sibling: {:?}",
+ listing.insns
+ );
+ assert!(
+ !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!(
+ matches!(
+ listing.stop_reason,
+ DisasmStopReason::FunctionEnd | DisasmStopReason::Int3 | DisasmStopReason::NextSeed
+ ),
+ "stop_reason={:?}",
+ listing.stop_reason
+ );
+ assert_eq!(listing.entry, Some(fn_a_entry));
+ assert_eq!(listing.end, Some(fn_a_end));
+ }
+
+ #[test]
+ fn int3_padding_helper() {
+ let mut prog = Program::new("t".into(), "PE32+");
+ prog.blocks.push(MemoryBlock {
+ name: ".text".into(),
+ va: 0x1000,
+ size: 4,
+ bytes: vec![0xcc, 0xcc, 0xc3, 0x90],
+ readable: true,
+ writable: false,
+ executable: true,
+ });
+ assert!(int3_padding_at(&prog, 0x1000));
+ assert!(!int3_padding_at(&prog, 0x1002));
}
}
diff --git a/crates/ghidrust-core/src/gpu_analyzers/strategies.rs b/crates/ghidrust-core/src/gpu_analyzers/strategies.rs
index 8a8944e..9ffb7e4 100644
--- a/crates/ghidrust-core/src/gpu_analyzers/strategies.rs
+++ b/crates/ghidrust-core/src/gpu_analyzers/strategies.rs
@@ -236,20 +236,12 @@ pub fn merge_seeds_into_program(
for &off in hits {
if let Some(va) = flat_to_va(map, off) {
if !prog.analysis.functions.iter().any(|f| f.entry == va) {
- prog.analysis.functions.push(FunctionInfo {
- entry: va,
- end: va,
- name: format!("FUN_{va:016x}"),
- calling_convention: if strategy == GpuStrategyClass::PrologueAbi {
- Some("unknown".into())
- } else {
- None
- },
- noreturn: false,
- varargs: false,
- parameters: Vec::new(),
- stack_locals: Vec::new(),
- });
+ let mut fi = FunctionInfo::new(va, va, format!("FUN_{va:016x}"))
+ .with_seed_kind(crate::program::FunctionSeedKind::Prologue);
+ if strategy == GpuStrategyClass::PrologueAbi {
+ fi.calling_convention = Some("unknown".into());
+ }
+ prog.analysis.functions.push(fi);
}
}
}
@@ -321,16 +313,9 @@ pub fn merge_seeds_into_program(
f.stack_locals.push(format!("spill_{va:x}"));
n += 1;
} else {
- prog.analysis.functions.push(FunctionInfo {
- entry: va,
- end: va,
- name: format!("FUN_{va:016x}"),
- calling_convention: None,
- noreturn: false,
- varargs: false,
- parameters: Vec::new(),
- stack_locals: vec![format!("frame_{va:x}")],
- });
+ let mut fi = FunctionInfo::new(va, va, format!("FUN_{va:016x}"));
+ fi.stack_locals = vec![format!("frame_{va:x}")];
+ prog.analysis.functions.push(fi);
n += 1;
}
}
@@ -364,16 +349,9 @@ pub fn merge_seeds_into_program(
});
}
"Non-Returning Functions - Discovered" => {
- prog.analysis.functions.push(FunctionInfo {
- entry: va,
- end: va,
- name: label.into(),
- calling_convention: None,
- noreturn: true,
- varargs: false,
- parameters: Vec::new(),
- stack_locals: Vec::new(),
- });
+ let mut fi = FunctionInfo::new(va, va, label);
+ fi.noreturn = true;
+ prog.analysis.functions.push(fi);
}
"PDB MSDIA" | "PDB Universal" => {
prog.analysis.pdb_symbols.push(SymbolInfo {
@@ -383,16 +361,9 @@ pub fn merge_seeds_into_program(
});
}
"Variadic Function Signature Override" => {
- prog.analysis.functions.push(FunctionInfo {
- entry: va,
- end: va,
- name: label.into(),
- calling_convention: None,
- noreturn: false,
- varargs: true,
- parameters: Vec::new(),
- stack_locals: Vec::new(),
- });
+ let mut fi = FunctionInfo::new(va, va, label);
+ fi.varargs = true;
+ prog.analysis.functions.push(fi);
}
"Windows x86 Propagate External Parameters" => {
prog.analysis.symbols.push(SymbolInfo {
diff --git a/crates/ghidrust-core/src/lib.rs b/crates/ghidrust-core/src/lib.rs
index 267036d..315767c 100644
--- a/crates/ghidrust-core/src/lib.rs
+++ b/crates/ghidrust-core/src/lib.rs
@@ -12,6 +12,7 @@ pub mod imports;
pub mod inventory;
pub mod io_util;
pub mod pe;
+pub mod pe_functions;
pub mod process;
pub mod program;
pub mod project;
@@ -47,8 +48,8 @@ pub use artifacts::{
ArtifactEnvelope, ArtifactMeta, DEFAULT_PREVIEW_LIMIT,
};
pub use disasm::{
- decode_one, disassemble_at, disassemble_range, disassemble_range_opts, DisasmRangeResult,
- Instruction,
+ decode_one, disassemble_at, disassemble_range, disassemble_range_ex, disassemble_range_opts,
+ int3_padding_at, DisasmMode, DisasmRangeResult, DisasmStopReason, Instruction,
};
pub use imports::{filter_imports, load_imports, parse_pe_imports};
pub use inventory::{
@@ -61,6 +62,10 @@ pub use process::{
process_resolve, static_to_live, ModuleInfo, ProcessInfo, ProcessSession, ReadResult,
RegionInfo, ResolveLive,
};
+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,
+};
pub use resolve::{resolve_function, resolve_result_json, ResolveResult, ResolveStatus};
pub use rtti_catalog::{
clear_rtti_cache, enrich_class, rtti_catalog, rtti_query, RttiCatalogEntry, RttiMatchMode,
@@ -75,9 +80,8 @@ pub use edits::{
pub use error::{Error, Result};
pub use program::{
AddressTableInfo, AddressTableRole, AnalysisState, CallFixupInfo, DiscoveredRange, FidMatch,
- FunctionInfo,
- ImportEntry, MediaHit, MemoryBlock, Program, ReferenceInfo, ResourceInfo, SectionInfo,
- SwitchInfo, SymbolInfo,
+ FunctionInfo, FunctionSeedKind, ImportEntry, MediaHit, MemoryBlock, Program, ReferenceInfo,
+ ResourceInfo, SectionInfo, SwitchInfo, SymbolInfo,
};
pub use project::{
AnalysisSummary, Project, ProjectFileEntry, ProjectMeta, ProjectTreeModel, ProjectTreeRow,
@@ -86,8 +90,9 @@ pub use project::{
pub use rtti::{recover_rtti, RttiClass, RttiReport};
pub use theme::{m3_tokens, ThemeMode, M3Tokens};
pub use xrefs::{
- instruction_targets, operand_addresses, rip_relative_targets, xrefs_from, xrefs_to,
- xrefs_to_import, xrefs_to_string_filter, xrefs_to_string_filter_opts, XRef,
+ calls_callees, instruction_targets, operand_addresses, rip_relative_targets, xrefs_from,
+ xrefs_to, xrefs_to_import, xrefs_to_string_filter, xrefs_to_string_filter_opts, CalleeEdge,
+ XRef,
};
use std::path::{Path, PathBuf};
diff --git a/crates/ghidrust-core/src/pe_functions.rs b/crates/ghidrust-core/src/pe_functions.rs
new file mode 100644
index 0000000..21baa64
--- /dev/null
+++ b/crates/ghidrust-core/src/pe_functions.rs
@@ -0,0 +1,556 @@
+//! PE Exception Directory (.pdata) RUNTIME_FUNCTION + export seeds + function create.
+//!
+//! Hand-rolled PE parse (no goblin). Industry-aligned function seeding for PE64.
+
+use crate::disasm::decode_one;
+use crate::program::{FunctionInfo, FunctionSeedKind, Program};
+use serde::{Deserialize, Serialize};
+
+/// UNWIND_INFO flag: unwind info chains to another RUNTIME_FUNCTION.
+const UNW_FLAG_CHAININFO: u8 = 0x4;
+
+/// One PE64 RUNTIME_FUNCTION (IMAGE_RUNTIME_FUNCTION_ENTRY), VA-resolved.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+pub struct RuntimeFunction {
+ /// BeginAddress RVA from .pdata.
+ pub begin_rva: u32,
+ /// EndAddress RVA from .pdata (exclusive).
+ pub end_rva: u32,
+ /// UnwindData RVA (UNWIND_INFO).
+ pub unwind_rva: u32,
+ pub begin_va: u64,
+ pub end_va: u64,
+ /// True when UNWIND_INFO.Flags includes UNW_FLAG_CHAININFO.
+ pub chained: bool,
+}
+
+/// Parse PE Exception Directory / .pdata into runtime function ranges.
+///
+/// Honors UNW_FLAG_CHAININFO by following the chain for classification; does not
+/// invent separate functions for embedded chain-node RUNTIME_FUNCTION records
+/// that lack a real BeginAddress (BeginAddress == 0), and skips zero-length /
+/// empty begins.
+pub fn parse_runtime_functions(prog: &Program) -> Vec<RuntimeFunction> {
+ if !prog.format.to_ascii_lowercase().starts_with("pe") {
+ return Vec::new();
+ }
+ let data = &prog.file_bytes;
+ let Some((exc_rva, exc_size)) = pe_data_directory(data, 3) else {
+ return Vec::new();
+ };
+ if exc_rva == 0 || exc_size < 12 {
+ return Vec::new();
+ }
+ let Some(mut off) = rva_to_file(data, exc_rva as u64) else {
+ return Vec::new();
+ };
+ let end_off = off + exc_size as usize;
+ let image_base = prog.image_base;
+ let mut out = Vec::new();
+ while off + 12 <= end_off.min(data.len()) {
+ let begin_rva = rdu32(data, off);
+ let end_rva = rdu32(data, off + 4);
+ let unwind_rva = rdu32(data, off + 8);
+ off += 12;
+ if begin_rva == 0 || end_rva <= begin_rva {
+ continue;
+ }
+ let chained = unwind_is_chained(data, unwind_rva);
+ // Pure chain descriptor with no real begin is already filtered (begin==0).
+ // Embedded chain nodes live inside UNWIND_INFO and are never seeded here.
+ out.push(RuntimeFunction {
+ begin_rva,
+ end_rva,
+ unwind_rva,
+ begin_va: image_base.wrapping_add(begin_rva as u64),
+ end_va: image_base.wrapping_add(end_rva as u64),
+ chained,
+ });
+ }
+ out
+}
+
+/// Convert RUNTIME_FUNCTION entries into seed FunctionInfo records (pdata ends).
+pub fn functions_from_runtime(rts: &[RuntimeFunction]) -> Vec<FunctionInfo> {
+ let mut out = Vec::new();
+ for rf in rts {
+ // Chained fragments still have a real BeginAddress in .pdata; keep them
+ // as seeds with authoritative ends (industry FSS / EH analyzer behavior).
+ out.push(
+ FunctionInfo::new(
+ rf.begin_va,
+ rf.end_va,
+ format!("FUN_{:08x}", rf.begin_va),
+ )
+ .with_seed_kind(FunctionSeedKind::Pdata),
+ );
+ }
+ out
+}
+
+/// PE export VAs that land in executable memory.
+pub fn parse_export_code_vas(prog: &Program) -> Vec<(u64, String)> {
+ if !prog.format.to_ascii_lowercase().starts_with("pe") {
+ return Vec::new();
+ }
+ let data = &prog.file_bytes;
+ let Some((exp_rva, exp_size)) = pe_data_directory(data, 0) else {
+ return Vec::new();
+ };
+ if exp_rva == 0 || exp_size < 40 {
+ return Vec::new();
+ }
+ let Some(exp_off) = rva_to_file(data, exp_rva as u64) else {
+ return Vec::new();
+ };
+ if exp_off + 40 > data.len() {
+ return Vec::new();
+ }
+ let num_functions = rdu32(data, exp_off + 20) as usize;
+ let num_names = rdu32(data, exp_off + 24) as usize;
+ let addr_rva = rdu32(data, exp_off + 28) as u64;
+ let names_rva = rdu32(data, exp_off + 32) as u64;
+ let ords_rva = rdu32(data, exp_off + 36) as u64;
+ let Some(addr_off) = rva_to_file(data, addr_rva) else {
+ return Vec::new();
+ };
+ let mut name_by_ord: Vec<Option<String>> = vec![None; num_functions];
+ if num_names > 0 {
+ if let (Some(names_off), Some(ords_off)) =
+ (rva_to_file(data, names_rva), rva_to_file(data, ords_rva))
+ {
+ for i in 0..num_names {
+ let n_off = names_off + i * 4;
+ let o_off = ords_off + i * 2;
+ if n_off + 4 > data.len() || o_off + 2 > data.len() {
+ break;
+ }
+ let name_rva = rdu32(data, n_off) as u64;
+ let ord = u16::from_le_bytes(data[o_off..o_off + 2].try_into().unwrap()) as usize;
+ if ord < name_by_ord.len() {
+ name_by_ord[ord] = read_cstr_rva(data, name_rva);
+ }
+ }
+ }
+ }
+ let mut out = Vec::new();
+ for i in 0..num_functions {
+ let a_off = addr_off + i * 4;
+ if a_off + 4 > data.len() {
+ break;
+ }
+ let func_rva = rdu32(data, a_off) as u64;
+ if func_rva == 0 {
+ continue;
+ }
+ // Forwarded exports live inside the export directory span — skip.
+ if func_rva >= exp_rva as u64 && func_rva < exp_rva as u64 + exp_size as u64 {
+ continue;
+ }
+ let va = prog.image_base.wrapping_add(func_rva);
+ if !is_executable_va(prog, va) {
+ continue;
+ }
+ let name = name_by_ord
+ .get(i)
+ .and_then(|n| n.clone())
+ .unwrap_or_else(|| format!("ord_{i}"));
+ out.push((va, name));
+ }
+ out
+}
+
+/// Create (or refresh) a function at `addr`. When `end_opt` is None, grow the body.
+pub fn create_function(prog: &mut Program, addr: u64, end_opt: Option<u64>) -> FunctionInfo {
+ create_function_with_kind(prog, addr, end_opt, FunctionSeedKind::Manual, None)
+}
+
+/// Create/heal a function with an explicit seed kind and optional name.
+pub fn create_function_with_kind(
+ prog: &mut Program,
+ addr: u64,
+ end_opt: Option<u64>,
+ kind: FunctionSeedKind,
+ name: Option<String>,
+) -> FunctionInfo {
+ if let Some(existing) = prog.function_at(addr).cloned() {
+ if let Some(end) = end_opt {
+ if let Some(f) = prog.function_at_mut(addr) {
+ if end > f.end {
+ f.end = end;
+ }
+ 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));
+ let end = end.max(addr.saturating_add(1));
+ let name = name.unwrap_or_else(|| match kind {
+ FunctionSeedKind::Synthesized => format!("SYNTH_{addr:08x}"),
+ _ => format!("FUN_{addr:08x}"),
+ });
+ let info = FunctionInfo::new(addr, end, name).with_seed_kind(kind);
+ prog.analysis.functions.push(info.clone());
+ prog.analysis.functions.sort_by_key(|f| f.entry);
+ info
+}
+
+/// Find a pdata range containing `va`, if any.
+pub fn runtime_function_containing(prog: &Program, va: u64) -> Option<RuntimeFunction> {
+ parse_runtime_functions(prog)
+ .into_iter()
+ .find(|rf| va >= rf.begin_va && va < rf.end_va)
+}
+
+/// Grow a function body from `entry` until a stop condition.
+///
+/// Stop at the earliest of: `hard_end`, first `ret`, int3 run ≥ 2, decode bail.
+pub fn grow_function(prog: &Program, entry: u64, hard_end: Option<u64>) -> u64 {
+ let mut va = entry;
+ let mut end = entry;
+ let mut skipped = 0u32;
+ for _ in 0..4096 {
+ if let Some(limit) = hard_end {
+ if va >= limit {
+ break;
+ }
+ }
+ let Some(bytes) = prog.read_va(va, 15) else {
+ break;
+ };
+ if bytes.len() >= 2 && bytes[0] == 0xCC && bytes[1] == 0xCC {
+ // int3 padding run — function ends before the pad.
+ break;
+ }
+ match decode_one(&bytes, va) {
+ Ok(insn) => {
+ skipped = 0;
+ let next = va + insn.length as u64;
+ if let Some(limit) = hard_end {
+ if next > limit {
+ end = limit;
+ break;
+ }
+ }
+ end = next;
+ if insn.mnemonic == "ret" {
+ break;
+ }
+ // Single int3 often pads after ret; a run of two is handled above.
+ va = end;
+ }
+ Err(_) => {
+ skipped += 1;
+ if skipped > 16 {
+ break;
+ }
+ va = va.wrapping_add(1);
+ if let Some(limit) = hard_end {
+ if va > limit {
+ end = limit;
+ break;
+ }
+ }
+ end = end.max(va);
+ }
+ }
+ }
+ let grown = end.max(entry + 1);
+ match hard_end {
+ Some(limit) => grown.min(limit).max(entry + 1),
+ None => grown,
+ }
+}
+
+fn is_executable_va(prog: &Program, va: u64) -> bool {
+ prog.blocks
+ .iter()
+ .any(|b| b.executable && va >= b.va && va < b.va.saturating_add(b.size))
+}
+
+fn unwind_is_chained(data: &[u8], unwind_rva: u32) -> bool {
+ if unwind_rva == 0 {
+ return false;
+ }
+ let Some(off) = rva_to_file(data, unwind_rva as u64) else {
+ return false;
+ };
+ if off >= data.len() {
+ return false;
+ }
+ let flags = (data[off] >> 3) & 0x1f;
+ if flags & UNW_FLAG_CHAININFO == 0 {
+ return false;
+ }
+ // Follow chain only to validate; do not emit the embedded RUNTIME_FUNCTION
+ // as a seed (BeginAddress there may be zero / non-primary).
+ let _ = chained_runtime_begin(data, off);
+ true
+}
+
+/// Read BeginAddress of the RUNTIME_FUNCTION embedded after unwind codes (if any).
+fn chained_runtime_begin(data: &[u8], unwind_off: usize) -> Option<u32> {
+ if unwind_off + 4 > data.len() {
+ return None;
+ }
+ let count_codes = data[unwind_off + 2] as usize;
+ // UNWIND_CODE array is CountOfCodes entries of 2 bytes, then align to even count.
+ let mut code_bytes = count_codes * 2;
+ if count_codes % 2 != 0 {
+ code_bytes += 2;
+ }
+ let chain_off = unwind_off + 4 + code_bytes;
+ if chain_off + 12 > data.len() {
+ return None;
+ }
+ Some(rdu32(data, chain_off))
+}
+
+/// Data directory index → (rva, size).
+fn pe_data_directory(data: &[u8], index: usize) -> Option<(u32, u32)> {
+ if data.len() < 0x40 || &data[0..2] != b"MZ" {
+ return None;
+ }
+ let e_lfanew = rdu32(data, 0x3C) as usize;
+ if e_lfanew + 24 > data.len() || &data[e_lfanew..e_lfanew + 4] != b"PE\0\0" {
+ return None;
+ }
+ let opt = e_lfanew + 24;
+ let magic = rdu16(data, opt)?;
+ let (data_dir, num_dd_off) = match magic {
+ 0x10b => (opt + 96, opt + 92), // PE32: NumberOfRvaAndSizes at +92
+ 0x20b => (opt + 112, opt + 108),
+ _ => return None,
+ };
+ let num_dd = rdu32(data, num_dd_off) as usize;
+ if index >= num_dd {
+ return None;
+ }
+ let off = data_dir + index * 8;
+ if off + 8 > data.len() {
+ return None;
+ }
+ Some((rdu32(data, off), rdu32(data, off + 4)))
+}
+
+fn rva_to_file(data: &[u8], rva: u64) -> Option<usize> {
+ if data.len() < 0x40 {
+ return None;
+ }
+ let e_lfanew = rdu32(data, 0x3C) as usize;
+ let coff = e_lfanew + 4;
+ let num_sections = rdu16(data, coff + 2)? as usize;
+ let opt_size = rdu16(data, coff + 16)? as usize;
+ let sec_table = coff + 20 + opt_size;
+ for i in 0..num_sections {
+ let off = sec_table + i * 40;
+ if off + 40 > data.len() {
+ break;
+ }
+ let virt_size = rdu32(data, off + 8) as u64;
+ let va_rva = rdu32(data, off + 12) as u64;
+ let raw_size = rdu32(data, off + 16) as u64;
+ let file_off = rdu32(data, off + 20) as u64;
+ let span = virt_size.max(raw_size);
+ if rva >= va_rva && rva < va_rva + span {
+ let delta = rva - va_rva;
+ if delta < raw_size {
+ return Some((file_off + delta) as usize);
+ }
+ }
+ }
+ None
+}
+
+fn read_cstr_rva(data: &[u8], rva: u64) -> Option<String> {
+ let off = rva_to_file(data, rva)?;
+ if off >= data.len() {
+ return None;
+ }
+ let end = data[off..]
+ .iter()
+ .position(|&b| b == 0)
+ .map(|p| off + p)
+ .unwrap_or(data.len());
+ if end == off {
+ return None;
+ }
+ Some(String::from_utf8_lossy(&data[off..end]).into_owned())
+}
+
+fn rdu16(data: &[u8], off: usize) -> Option<u16> {
+ if off + 2 > data.len() {
+ return None;
+ }
+ Some(u16::from_le_bytes(data[off..off + 2].try_into().unwrap()))
+}
+
+fn rdu32(data: &[u8], off: usize) -> u32 {
+ u32::from_le_bytes(data[off..off + 4].try_into().unwrap())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::program::MemoryBlock;
+
+ /// Craft a minimal PE32+ with .pdata RUNTIME_FUNCTION + UNWIND_INFO.
+ fn minimal_pe_with_pdata() -> Vec<u8> {
+ // Layout (file):
+ // 0x000 DOS+PE headers (optional + data dirs)
+ // 0x200 section table (2 sections: .text, .pdata)
+ // 0x400 .text raw: code at RVA 0x1000
+ // 0x600 .pdata raw: one RUNTIME_FUNCTION + UNWIND_INFO
+ let mut data = vec![0u8; 0x800];
+ // MZ
+ data[0] = b'M';
+ data[1] = b'Z';
+ data[0x3C..0x40].copy_from_slice(&0x80u32.to_le_bytes());
+ // PE signature at 0x80
+ data[0x80..0x84].copy_from_slice(b"PE\0\0");
+ let coff = 0x84;
+ // Machine AMD64
+ data[coff..coff + 2].copy_from_slice(&0x8664u16.to_le_bytes());
+ data[coff + 2..coff + 4].copy_from_slice(&2u16.to_le_bytes()); // sections
+ data[coff + 16..coff + 18].copy_from_slice(&0xF0u16.to_le_bytes()); // opt size
+ let opt = coff + 20; // 0x98
+ data[opt..opt + 2].copy_from_slice(&0x20bu16.to_le_bytes()); // PE32+
+ // AddressOfEntryPoint RVA
+ data[opt + 16..opt + 20].copy_from_slice(&0x1000u32.to_le_bytes());
+ // ImageBase
+ data[opt + 24..opt + 32].copy_from_slice(&0x140000000u64.to_le_bytes());
+ // NumberOfRvaAndSizes
+ data[opt + 108..opt + 112].copy_from_slice(&16u32.to_le_bytes());
+ let dd = opt + 112;
+ // Exception directory (index 3): RVA 0x2000, size 12
+ let exc = dd + 3 * 8;
+ data[exc..exc + 4].copy_from_slice(&0x2000u32.to_le_bytes());
+ data[exc + 4..exc + 8].copy_from_slice(&12u32.to_le_bytes());
+
+ let sec = opt + 0xF0; // section table
+ // .text: VA 0x1000, vsize 0x1000, raw 0x200 @ 0x400
+ write_sec(&mut data, sec, b".text\0\0\0", 0x1000, 0x1000, 0x200, 0x400, 0x6000_0020);
+ // .pdata: VA 0x2000, vsize 0x1000, raw 0x200 @ 0x600
+ write_sec(
+ &mut data,
+ sec + 40,
+ b".pdata\0\0",
+ 0x1000,
+ 0x2000,
+ 0x200,
+ 0x600,
+ 0x4000_0040,
+ );
+
+ // code: push rbp; mov rbp,rsp; xor eax,eax; pop rbp; ret; int3; int3
+ let text = &mut data[0x400..0x400 + 10];
+ text.copy_from_slice(&[0x55, 0x48, 0x89, 0xE5, 0x31, 0xC0, 0x5D, 0xC3, 0xCC, 0xCC]);
+
+ // RUNTIME_FUNCTION at .pdata: begin=0x1000 end=0x1008 unwind=0x200C
+ let pd = 0x600;
+ data[pd..pd + 4].copy_from_slice(&0x1000u32.to_le_bytes());
+ data[pd + 4..pd + 8].copy_from_slice(&0x1008u32.to_le_bytes());
+ data[pd + 8..pd + 12].copy_from_slice(&0x200Cu32.to_le_bytes());
+ // UNWIND_INFO at RVA 0x200C → file 0x60C: version=1 flags=0, prolog=4, codes=0
+ data[0x60C] = 0x01; // version 1, flags 0
+ data[0x60D] = 0x04; // SizeOfProlog
+ data[0x60E] = 0x00; // CountOfCodes
+ data[0x60F] = 0x00; // FrameRegister/Offset
+ data
+ }
+
+ fn write_sec(
+ data: &mut [u8],
+ off: usize,
+ name: &[u8; 8],
+ vsize: u32,
+ va: u32,
+ raw_size: u32,
+ file_off: u32,
+ chars: u32,
+ ) {
+ data[off..off + 8].copy_from_slice(name);
+ data[off + 8..off + 12].copy_from_slice(&vsize.to_le_bytes());
+ data[off + 12..off + 16].copy_from_slice(&va.to_le_bytes());
+ data[off + 16..off + 20].copy_from_slice(&raw_size.to_le_bytes());
+ data[off + 20..off + 24].copy_from_slice(&file_off.to_le_bytes());
+ data[off + 36..off + 40].copy_from_slice(&chars.to_le_bytes());
+ }
+
+ #[test]
+ fn parse_pdata_runtime_functions() {
+ let bytes = minimal_pe_with_pdata();
+ let prog = crate::pe::load_pe(&bytes, "pdata_test").expect("load");
+ let rts = parse_runtime_functions(&prog);
+ assert_eq!(rts.len(), 1);
+ assert_eq!(rts[0].begin_rva, 0x1000);
+ assert_eq!(rts[0].end_rva, 0x1008);
+ assert_eq!(rts[0].begin_va, 0x140001000);
+ assert_eq!(rts[0].end_va, 0x140001008);
+ assert!(!rts[0].chained);
+ let seeded = functions_from_runtime(&rts);
+ assert_eq!(seeded[0].seed_kind, Some(FunctionSeedKind::Pdata));
+ assert_eq!(seeded[0].end, 0x140001008);
+ }
+
+ #[test]
+ fn chaininfo_embedded_node_not_seeded() {
+ // Build UNWIND_INFO with CHAININFO + embedded RUNTIME_FUNCTION begin=0.
+ let mut bytes = minimal_pe_with_pdata();
+ // flags: version=1 (low 3) + CHAININFO (bit of flags << 3) → 0x01 | (0x4 << 3) = 0x21
+ bytes[0x60C] = 0x21;
+ bytes[0x60E] = 0x00; // no codes
+ // embedded RUNTIME_FUNCTION at 0x610: begin=0 → must not become a seed
+ bytes[0x610..0x614].copy_from_slice(&0u32.to_le_bytes());
+ bytes[0x614..0x618].copy_from_slice(&0x1008u32.to_le_bytes());
+ bytes[0x618..0x61C].copy_from_slice(&0x200Cu32.to_le_bytes());
+ let prog = crate::pe::load_pe(&bytes, "chain").expect("load");
+ let rts = parse_runtime_functions(&prog);
+ assert_eq!(rts.len(), 1);
+ assert!(rts[0].chained);
+ // Still only the .pdata row — not the embedded zero-begin node.
+ assert_eq!(rts[0].begin_rva, 0x1000);
+ }
+
+ #[test]
+ fn grow_stops_on_int3_run() {
+ let mut prog = Program::new("t".into(), "PE32+");
+ // Without ret: grow should stop at int3 run
+ let code = vec![0x55, 0x48, 0x89, 0xE5, 0x90, 0xCC, 0xCC, 0x90];
+ prog.blocks.push(MemoryBlock {
+ name: ".text".into(),
+ va: 0x1000,
+ size: code.len() as u64,
+ bytes: code,
+ readable: true,
+ writable: false,
+ executable: true,
+ });
+ let end = grow_function(&prog, 0x1000, None);
+ assert_eq!(end, 0x1005, "should stop before int3 int3");
+ }
+
+ #[test]
+ fn create_function_grows_when_no_end() {
+ let mut prog = Program::new("t".into(), "PE32+");
+ let code = vec![0x55, 0x48, 0x89, 0xE5, 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,
+ });
+ let f = create_function(&mut prog, 0x1000, None);
+ assert_eq!(f.entry, 0x1000);
+ assert_eq!(f.end, 0x1005); // after ret
+ assert_eq!(f.seed_kind, Some(FunctionSeedKind::Manual));
+ assert_eq!(prog.analysis.functions.len(), 1);
+ }
+}
diff --git a/crates/ghidrust-core/src/program.rs b/crates/ghidrust-core/src/program.rs
index 2ebce4d..9db370b 100644
--- a/crates/ghidrust-core/src/program.rs
+++ b/crates/ghidrust-core/src/program.rs
@@ -25,6 +25,18 @@ pub struct SectionInfo {
pub characteristics: u32,
}
+/// How a function entry was first seeded into analysis.
+#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "snake_case")]
+pub enum FunctionSeedKind {
+ Pdata,
+ Export,
+ MethodPointer,
+ Prologue,
+ Manual,
+ Synthesized,
+}
+
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct FunctionInfo {
pub entry: u64,
@@ -37,6 +49,30 @@ pub struct FunctionInfo {
pub parameters: Vec<String>,
/// Stack locals as "offset:size" or name.
pub stack_locals: Vec<String>,
+ /// Origin of this function record (`pdata`, `export`, `prologue`, …).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub seed_kind: Option<FunctionSeedKind>,
+}
+
+impl FunctionInfo {
+ pub fn new(entry: u64, end: u64, name: impl Into<String>) -> Self {
+ Self {
+ entry,
+ end,
+ name: name.into(),
+ calling_convention: None,
+ noreturn: false,
+ varargs: false,
+ parameters: Vec::new(),
+ stack_locals: Vec::new(),
+ seed_kind: None,
+ }
+ }
+
+ pub fn with_seed_kind(mut self, kind: FunctionSeedKind) -> Self {
+ self.seed_kind = Some(kind);
+ self
+ }
}
/// One PE import / IAT slot (ELF imports may be added later).
diff --git a/crates/ghidrust-core/src/resolve.rs b/crates/ghidrust-core/src/resolve.rs
index f3d1171..f8ec4cc 100644
--- a/crates/ghidrust-core/src/resolve.rs
+++ b/crates/ghidrust-core/src/resolve.rs
@@ -1,11 +1,14 @@
//! Address → Function resolution (containing-function layer).
//!
-//! Shared by CLI, MCP, GPU decompile, and GUI. Never invents a 1-insn function
-//! at a mid-body hit; returns honest `no_containing_function` instead.
+//! Shared by CLI, MCP, GPU decompile, and GUI. On executable orphans: re-run FSS
+//! once, heal from pdata when possible, otherwise synthesize `SYNTH_{addr}`.
use crate::analyzers::run_analyzers;
use crate::error::Result;
-use crate::program::{FunctionInfo, Program};
+use crate::pe_functions::{
+ create_function_with_kind, runtime_function_containing,
+};
+use crate::program::{FunctionInfo, FunctionSeedKind, Program};
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
@@ -17,6 +20,8 @@ pub enum ResolveStatus {
NoContainingFunction,
NotExecutable,
Unmapped,
+ /// Orphan executable VA healed via pdata or freshly synthesized.
+ Synthesized,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -38,6 +43,15 @@ pub struct ResolveResult {
pub candidates: Vec<ResolveCandidate>,
#[serde(skip_serializing_if = "Option::is_none")]
pub reason: Option<String>,
+ /// Present when status is `synthesized` (pdata heal or orphan synth).
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub synthesized_range: Option<SynthesizedRange>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct SynthesizedRange {
+ pub start: u64,
+ pub end: u64,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -59,10 +73,25 @@ fn fail(addr: u64, status: ResolveStatus, reason: &str) -> ResolveResult {
ambiguous: false,
candidates: vec![],
reason: Some(reason.into()),
+ synthesized_range: None,
}
}
-fn ok_from(addr: u64, f: &FunctionInfo, status: ResolveStatus, ambiguous: bool, candidates: Vec<ResolveCandidate>) -> ResolveResult {
+fn ok_from(
+ addr: u64,
+ f: &FunctionInfo,
+ status: ResolveStatus,
+ ambiguous: bool,
+ candidates: Vec<ResolveCandidate>,
+) -> ResolveResult {
+ let synthesized_range = if status == ResolveStatus::Synthesized {
+ Some(SynthesizedRange {
+ start: f.entry,
+ end: f.end,
+ })
+ } else {
+ None
+ };
ResolveResult {
ok: true,
resolve_status: status,
@@ -74,49 +103,23 @@ fn ok_from(addr: u64, f: &FunctionInfo, status: ResolveStatus, ambiguous: bool,
ambiguous,
candidates,
reason: None,
+ synthesized_range,
}
}
-/// Resolve `addr` to a function entry. Auto-runs Function Start Search once when empty.
-pub fn resolve_function(prog: &mut Program, addr: u64) -> Result<ResolveResult> {
- if !prog.contains_va(addr) {
- return Ok(fail(addr, ResolveStatus::Unmapped, "unmapped"));
- }
- let in_exec = prog
- .blocks
- .iter()
- .any(|b| b.executable && addr >= b.va && addr < b.va.saturating_add(b.size));
- if !in_exec {
- // Still allow exact function entry hits on non-exec (rare); otherwise honest.
- if prog.function_at(addr).is_none() {
- return Ok(fail(addr, ResolveStatus::NotExecutable, "not_executable"));
- }
- }
-
- if prog.analysis.functions.is_empty() {
- let _ = run_analyzers(prog, &["Function Start Search"])?;
- }
-
+fn try_resolve_covering(prog: &Program, addr: u64) -> Option<ResolveResult> {
if let Some(f) = prog.function_at(addr) {
- return Ok(ok_from(addr, f, ResolveStatus::ExactEntry, false, vec![]));
+ return Some(ok_from(addr, f, ResolveStatus::ExactEntry, false, vec![]));
}
-
let covering: Vec<&FunctionInfo> = prog
.analysis
.functions
.iter()
.filter(|f| addr >= f.entry && addr < f.end.max(f.entry.saturating_add(1)))
.collect();
-
if covering.is_empty() {
- return Ok(fail(
- addr,
- ResolveStatus::NoContainingFunction,
- "no_containing_function",
- ));
+ return None;
}
-
- // Primary = smallest containing range; tie-break greatest entry.
let primary = covering
.iter()
.copied()
@@ -125,7 +128,6 @@ pub fn resolve_function(prog: &mut Program, addr: u64) -> Result<ResolveResult>
(span, u64::MAX - f.entry)
})
.expect("non-empty");
-
let ambiguous = covering.len() > 1;
let candidates: Vec<ResolveCandidate> = covering
.iter()
@@ -135,13 +137,71 @@ pub fn resolve_function(prog: &mut Program, addr: u64) -> Result<ResolveResult>
name: f.name.clone(),
})
.collect();
-
let status = if ambiguous {
ResolveStatus::Ambiguous
} else {
ResolveStatus::Containing
};
- Ok(ok_from(addr, primary, status, ambiguous, candidates))
+ Some(ok_from(addr, primary, status, ambiguous, candidates))
+}
+
+/// Resolve `addr` to a function entry. Auto-runs Function Start Search when empty;
+/// on executable orphans, re-runs FSS once then pdata-heals or synthesizes.
+pub fn resolve_function(prog: &mut Program, addr: u64) -> Result<ResolveResult> {
+ if !prog.contains_va(addr) {
+ return Ok(fail(addr, ResolveStatus::Unmapped, "unmapped"));
+ }
+ let in_exec = prog
+ .blocks
+ .iter()
+ .any(|b| b.executable && addr >= b.va && addr < b.va.saturating_add(b.size));
+ if !in_exec {
+ if prog.function_at(addr).is_none() {
+ return Ok(fail(addr, ResolveStatus::NotExecutable, "not_executable"));
+ }
+ }
+
+ if prog.analysis.functions.is_empty() {
+ let _ = run_analyzers(prog, &["Function Start Search"])?;
+ }
+
+ if let Some(r) = try_resolve_covering(prog, addr) {
+ return Ok(r);
+ }
+
+ if !in_exec {
+ return Ok(fail(
+ addr,
+ ResolveStatus::NoContainingFunction,
+ "no_containing_function",
+ ));
+ }
+
+ // Orphan executable VA: re-run FSS/PE once, then pdata-heal or synthesize.
+ let _ = run_analyzers(prog, &["Function Start Search"])?;
+ if let Some(r) = try_resolve_covering(prog, addr) {
+ return Ok(r);
+ }
+
+ if let Some(rf) = runtime_function_containing(prog, addr) {
+ let f = create_function_with_kind(
+ prog,
+ rf.begin_va,
+ Some(rf.end_va),
+ FunctionSeedKind::Pdata,
+ Some(format!("FUN_{:08x}", rf.begin_va)),
+ );
+ return Ok(ok_from(addr, &f, ResolveStatus::Synthesized, false, vec![]));
+ }
+
+ let f = create_function_with_kind(
+ prog,
+ addr,
+ None,
+ FunctionSeedKind::Synthesized,
+ Some(format!("SYNTH_{addr:08x}")),
+ );
+ Ok(ok_from(addr, &f, ResolveStatus::Synthesized, false, vec![]))
}
/// JSON-friendly hex fields for agent responses.
@@ -161,6 +221,10 @@ pub fn resolve_result_json(r: &ResolveResult) -> serde_json::Value {
"name": c.name,
})).collect::<Vec<_>>(),
"reason": r.reason,
+ "synthesized_range": r.synthesized_range.as_ref().map(|s| serde_json::json!({
+ "start": format!("{:#x}", s.start),
+ "end": format!("{:#x}", s.end),
+ })),
})
}
@@ -180,16 +244,9 @@ mod tests {
writable: false,
executable: true,
});
- prog.analysis.functions.push(FunctionInfo {
- entry,
- end,
- name: "f".into(),
- calling_convention: None,
- noreturn: false,
- varargs: false,
- parameters: vec![],
- stack_locals: vec![],
- });
+ prog.analysis.functions.push(
+ FunctionInfo::new(entry, end, "f").with_seed_kind(FunctionSeedKind::Manual),
+ );
prog
}
@@ -212,30 +269,37 @@ mod tests {
}
#[test]
- fn no_fn_honest() {
+ fn orphan_executable_synthesizes() {
let mut prog = Program::new("t".into(), "PE32+");
+ // ret; int3; int3 so grow terminates cleanly
+ let mut bytes = vec![0x90; 0x100];
+ bytes[0x50] = 0xC3;
+ bytes[0x51] = 0xCC;
+ bytes[0x52] = 0xCC;
prog.blocks.push(MemoryBlock {
name: ".text".into(),
va: 0x1000,
size: 0x100,
- bytes: vec![0x90; 0x100],
+ bytes,
readable: true,
writable: false,
executable: true,
});
- // Non-empty functions list so we don't auto-run FSS on empty image heuristics.
- prog.analysis.functions.push(FunctionInfo {
- entry: 0x2000,
- end: 0x2100,
- name: "elsewhere".into(),
- calling_convention: None,
- noreturn: false,
- varargs: false,
- parameters: vec![],
- stack_locals: vec![],
- });
+ // Non-empty functions list so first path does not only rely on empty-FSS.
+ prog.analysis.functions.push(FunctionInfo::new(0x2000, 0x2100, "elsewhere"));
let r = resolve_function(&mut prog, 0x1050).unwrap();
- assert!(!r.ok);
- assert_eq!(r.resolve_status, ResolveStatus::NoContainingFunction);
+ assert!(r.ok);
+ assert_eq!(r.resolve_status, ResolveStatus::Synthesized);
+ assert_eq!(r.resolved_entry, Some(0x1050));
+ assert_eq!(r.function_name.as_deref(), Some("SYNTH_00001050"));
+ assert!(r.synthesized_range.is_some());
+ let syn = r.synthesized_range.unwrap();
+ assert_eq!(syn.start, 0x1050);
+ assert!(syn.end > syn.start);
+ assert!(prog.function_at(0x1050).is_some());
+ assert_eq!(
+ prog.function_at(0x1050).unwrap().seed_kind,
+ Some(FunctionSeedKind::Synthesized)
+ );
}
}
diff --git a/crates/ghidrust-core/src/xrefs.rs b/crates/ghidrust-core/src/xrefs.rs
index 0d3e9f3..111313d 100644
--- a/crates/ghidrust-core/src/xrefs.rs
+++ b/crates/ghidrust-core/src/xrefs.rs
@@ -7,7 +7,9 @@
//! 4. Decoded instructions — absolute operand hex + RIP-relative targets
//! 5. Import / IAT slots — `call/jmp [rip+disp]` landing on IAT VAs
-use crate::disasm::{decode_one, disassemble_range};
+use crate::disasm::{
+ decode_one, disassemble_range, disassemble_range_ex, DisasmMode,
+};
use crate::program::{ImportEntry, Program};
use serde::Serialize;
@@ -26,6 +28,32 @@ pub struct XRef {
/// String encoding when this xref targets a string (`ascii`, `utf16le`); omitted otherwise.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub encoding: Option<String>,
+ /// Containing function entry for `from`, when analyzed.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub from_entry: Option<u64>,
+ /// Containing function name for `from`, when analyzed.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub from_function: Option<String>,
+ /// Containing / resolved function entry for `to`, when analyzed.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub to_entry: Option<u64>,
+}
+
+/// Call/jmp edge discovered inside a function body.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
+pub struct CalleeEdge {
+ /// Call/jmp site VA.
+ pub from: u64,
+ /// Decoded target VA.
+ pub to: u64,
+ /// `call` or `jmp`.
+ pub kind: &'static str,
+ /// Resolved callee entry when `to` lands in a known function.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub to_entry: Option<u64>,
+ /// Callee function name when known.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub to_function: Option<String>,
}
/// Compute references **to** `target`.
@@ -41,13 +69,7 @@ pub fn xrefs_to(
for r in &prog.analysis.references {
if r.to == target {
- out.push(XRef {
- from: r.from,
- to: r.to,
- kind: static_kind(&r.kind),
- preview: r.kind.clone(),
- encoding: None,
- });
+ out.push(xref(r.from, r.to, static_kind(&r.kind), r.kind.clone(), None));
}
}
@@ -55,13 +77,13 @@ pub fn xrefs_to(
for (i, entry) in tbl.entries.iter().enumerate() {
if *entry == target {
let from = tbl.base + (i as u64) * 8;
- out.push(XRef {
+ out.push(xref(
from,
- to: target,
- kind: "ptr_table",
- preview: format!("[{}] {:#x}", i, target),
- encoding: None,
- });
+ target,
+ "ptr_table",
+ format!("[{}] {:#x}", i, target),
+ None,
+ ));
}
}
}
@@ -74,7 +96,7 @@ pub fn xrefs_to(
scan_exec_xrefs_to(prog, target, &mut out);
}
- finalize(&mut out);
+ finalize(prog, &mut out);
out
}
@@ -102,13 +124,7 @@ fn scan_data_pointer_refs(prog: &Program, target: u64, out: &mut Vec<XRef>) {
let val = u64::from_le_bytes(b[off..off + 8].try_into().unwrap());
if val == target {
let from = block.va + off as u64;
- out.push(XRef {
- from,
- to: target,
- kind: "ptr",
- preview: format!("dq {target:#x}"),
- encoding: None,
- });
+ out.push(xref(from, target, "ptr", format!("dq {target:#x}"), None));
found += 1;
}
off += 8;
@@ -125,17 +141,61 @@ pub fn xrefs_from(prog: &Program, source: u64, max_insns: usize) -> Vec<XRef> {
for insn in &listing {
for tgt in instruction_targets(insn) {
if prog.contains_va(tgt) {
- out.push(XRef {
- from: insn.address,
- to: tgt,
- kind: mnemonic_kind(&insn.mnemonic),
- preview: format!("{} {}", insn.mnemonic, insn.operands),
- encoding: None,
- });
+ out.push(xref(
+ insn.address,
+ tgt,
+ mnemonic_kind(&insn.mnemonic),
+ format!("{} {}", insn.mnemonic, insn.operands),
+ None,
+ ));
}
}
}
- finalize(&mut out);
+ finalize(prog, &mut out);
+ out
+}
+
+/// Scan call/jmp sites inside the function at `entry` (bounded listing).
+///
+/// Targets are resolved to containing function entries when analyzed.
+pub fn calls_callees(prog: &Program, entry: u64) -> Vec<CalleeEdge> {
+ let Some(f) = prog
+ .function_at(entry)
+ .or_else(|| prog.function_containing(entry))
+ else {
+ return Vec::new();
+ };
+ let start = f.entry;
+ let bound_end = f.end;
+ let Ok(listing) = disassemble_range_ex(
+ prog,
+ start,
+ 4096,
+ true,
+ DisasmMode::Bounded,
+ Some(bound_end),
+ ) else {
+ return Vec::new();
+ };
+ let mut out = Vec::new();
+ for insn in &listing.insns {
+ let kind = mnemonic_kind(&insn.mnemonic);
+ if kind != "call" && kind != "jmp" {
+ continue;
+ }
+ for tgt in instruction_targets(insn) {
+ let (to_entry, to_function) = resolve_target_fn(prog, tgt);
+ out.push(CalleeEdge {
+ from: insn.address,
+ to: tgt,
+ kind,
+ to_entry,
+ to_function,
+ });
+ }
+ }
+ out.sort_by_key(|e| (e.from, e.to, e.kind));
+ out.dedup_by(|a, b| a.from == b.from && a.to == b.to && a.kind == b.kind);
out
}
@@ -167,7 +227,7 @@ pub fn xrefs_to_import(prog: &Program, import_name: &str) -> Vec<XRef> {
}
out.extend(refs);
}
- finalize(&mut out);
+ finalize(prog, &mut out);
out
}
@@ -234,7 +294,7 @@ pub fn xrefs_to_string_filter_opts(
}
}
}
- finalize(&mut out);
+ finalize(prog, &mut out);
out
}
@@ -364,13 +424,13 @@ fn scan_exec_xrefs_to(prog: &Program, target: u64, out: &mut Vec<XRef>) {
match decode_one(slice, va) {
Ok(insn) => {
if instruction_targets(&insn).contains(&target) {
- out.push(XRef {
- from: insn.address,
- to: target,
- kind: mnemonic_kind(&insn.mnemonic),
- preview: format!("{} {}", insn.mnemonic, insn.operands),
- encoding: None,
- });
+ out.push(xref(
+ insn.address,
+ target,
+ mnemonic_kind(&insn.mnemonic),
+ format!("{} {}", insn.mnemonic, insn.operands),
+ None,
+ ));
}
off += insn.length.max(1) as usize;
}
@@ -387,18 +447,58 @@ fn push_listing_xrefs_to(
) {
for insn in listing {
if instruction_targets(insn).contains(&target) {
- out.push(XRef {
- from: insn.address,
- to: target,
- kind: mnemonic_kind(&insn.mnemonic),
- preview: format!("{} {}", insn.mnemonic, insn.operands),
- encoding: None,
- });
+ out.push(xref(
+ insn.address,
+ target,
+ mnemonic_kind(&insn.mnemonic),
+ format!("{} {}", insn.mnemonic, insn.operands),
+ None,
+ ));
}
}
}
-fn finalize(out: &mut Vec<XRef>) {
+fn xref(
+ from: u64,
+ to: u64,
+ kind: &'static str,
+ preview: String,
+ encoding: Option<String>,
+) -> XRef {
+ XRef {
+ from,
+ to,
+ kind,
+ preview,
+ encoding,
+ from_entry: None,
+ from_function: None,
+ to_entry: None,
+ }
+}
+
+fn resolve_target_fn(prog: &Program, va: u64) -> (Option<u64>, Option<String>) {
+ if let Some(f) = prog.function_at(va).or_else(|| prog.function_containing(va)) {
+ (Some(f.entry), Some(f.name.clone()))
+ } else {
+ (None, None)
+ }
+}
+
+fn attribute(prog: &Program, r: &mut XRef) {
+ if let Some(f) = prog.function_containing(r.from) {
+ r.from_entry = Some(f.entry);
+ r.from_function = Some(f.name.clone());
+ }
+ if let Some(f) = prog.function_at(r.to).or_else(|| prog.function_containing(r.to)) {
+ r.to_entry = Some(f.entry);
+ }
+}
+
+fn finalize(prog: &Program, out: &mut Vec<XRef>) {
+ for r in out.iter_mut() {
+ attribute(prog, r);
+ }
out.sort_by_key(|r| (r.from, r.to, r.kind));
out.dedup_by(|a, b| a.from == b.from && a.to == b.to && a.kind == b.kind);
}
@@ -621,4 +721,52 @@ mod tests {
"{refs:?}"
);
}
+
+ #[test]
+ fn xref_from_entry_populated_when_functions_exist() {
+ use crate::program::FunctionInfo;
+
+ let mut prog = Program::new("t".into(), "PE32+");
+ let caller = 0x140001000u64;
+ let callee = 0x140001100u64;
+ // call rel32 to callee, then ret
+ let next = caller + 5;
+ let disp = (callee as i64) - (next as i64);
+ let mut code = vec![0xe8];
+ code.extend_from_slice(&(disp as i32).to_le_bytes());
+ code.push(0xc3);
+ // pad to callee
+ code.resize((callee - caller) as usize, 0xcc);
+ code.extend_from_slice(&[0x31, 0xc0, 0xc3]); // xor eax,eax; ret
+ prog.blocks.push(MemoryBlock {
+ name: ".text".into(),
+ va: caller,
+ size: code.len() as u64,
+ bytes: code,
+ readable: true,
+ writable: false,
+ executable: true,
+ });
+ prog.analysis
+ .functions
+ .push(FunctionInfo::new(caller, caller + 6, "caller"));
+ prog.analysis
+ .functions
+ .push(FunctionInfo::new(callee, callee + 3, "callee"));
+
+ let refs = xrefs_from(&prog, caller, 8);
+ let call = refs
+ .iter()
+ .find(|r| r.kind == "call" && r.to == callee)
+ .expect(&format!("expected call xref, got {refs:?}"));
+ assert_eq!(call.from_entry, Some(caller));
+ assert_eq!(call.from_function.as_deref(), Some("caller"));
+ assert_eq!(call.to_entry, Some(callee));
+
+ let edges = calls_callees(&prog, caller);
+ assert!(
+ edges.iter().any(|e| e.to == callee && e.to_entry == Some(callee)),
+ "{edges:?}"
+ );
+ }
}
diff --git a/crates/ghidrust-gui/src/main.rs b/crates/ghidrust-gui/src/main.rs
index bf045ad..d60f122 100644
--- a/crates/ghidrust-gui/src/main.rs
+++ b/crates/ghidrust-gui/src/main.rs
@@ -10421,26 +10421,14 @@ mod tests {
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 {
- entry: base,
- end: base + 0x10,
- name: "fn_a".into(),
- calling_convention: None,
- noreturn: false,
- varargs: false,
- parameters: Vec::new(),
- stack_locals: Vec::new(),
- });
- prog.analysis.functions.push(ghidrust_core::FunctionInfo {
- entry: base + 0x40,
- end: base + 0x50,
- name: "fn_b".into(),
- calling_convention: None,
- noreturn: false,
- varargs: false,
- parameters: Vec::new(),
- stack_locals: Vec::new(),
- });
+ prog.analysis
+ .functions
+ .push(ghidrust_core::FunctionInfo::new(base, base + 0x10, "fn_a"));
+ prog.analysis.functions.push(ghidrust_core::FunctionInfo::new(
+ base + 0x40,
+ base + 0x50,
+ "fn_b",
+ ));
}
let entries: Vec<u64> = app
.program
@@ -10510,16 +10498,11 @@ mod tests {
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 {
+ prog.analysis.functions.push(ghidrust_core::FunctionInfo::new(
entry,
- end: entry + 0x10,
- name: "FUN_original".into(),
- calling_convention: None,
- noreturn: false,
- varargs: false,
- parameters: Vec::new(),
- stack_locals: Vec::new(),
- });
+ entry + 0x10,
+ "FUN_original",
+ ));
}
app.rename_at(entry, "my_main").expect("rename");
let p = app.program.as_ref().unwrap();
@@ -10560,16 +10543,12 @@ mod tests {
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 {
- entry,
- end: entry + 0x40,
- name: "with_params".into(),
- calling_convention: Some("windowsx64".into()),
- noreturn: false,
- varargs: false,
- parameters: vec!["rcx".into(), "rdx".into()],
- stack_locals: vec!["local_10".into(), "local_18".into()],
- });
+ 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()];
+ prog.analysis.functions.push(fi);
}
app.commit_params_return(entry).expect("commit params");
app.commit_locals(entry).expect("commit locals");
@@ -10778,16 +10757,9 @@ mod tests {
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 {
- entry,
- end: entry + 0x20,
- name: "fn".into(),
- calling_convention: None,
- noreturn: false,
- varargs: false,
- parameters: Vec::new(),
- stack_locals: Vec::new(),
- });
+ prog.analysis
+ .functions
+ .push(ghidrust_core::FunctionInfo::new(entry, entry + 0x20, "fn"));
}
app.refresh_decompiler_at(entry);
assert!(!app.decomp_text.is_empty());
diff --git a/crates/ghidrust-gui/src/menu_actions.rs b/crates/ghidrust-gui/src/menu_actions.rs
index 4aff7ad..d1edf48 100644
--- a/crates/ghidrust-gui/src/menu_actions.rs
+++ b/crates/ghidrust-gui/src/menu_actions.rs
@@ -700,16 +700,9 @@ mod tests {
use ghidrust_core::FunctionInfo;
let mut prog = load_path(fixture_path("tiny_x64.pe")).unwrap();
let entry = prog.entry.unwrap_or(prog.image_base);
- prog.analysis.functions.push(FunctionInfo {
- entry,
- end: entry + 0x40,
- name: "FUN_test".into(),
- calling_convention: None,
- noreturn: false,
- varargs: false,
- parameters: Vec::new(),
- stack_locals: Vec::new(),
- });
+ prog.analysis
+ .functions
+ .push(FunctionInfo::new(entry, entry + 0x40, "FUN_test"));
assert_eq!(decompile_entry_for_va(&prog, entry + 0x10), entry);
assert_eq!(decompile_entry_for_va(&prog, entry), entry);
}
diff --git a/crates/ghidrust-gui/src/scripts.rs b/crates/ghidrust-gui/src/scripts.rs
index 811e828..39dbd69 100644
--- a/crates/ghidrust-gui/src/scripts.rs
+++ b/crates/ghidrust-gui/src/scripts.rs
@@ -74,6 +74,7 @@ pub fn builtin_catalog() -> Vec<ScriptEntry> {
s("mcp.il2cpp_stubs", "MCP · IL2CPP", "List IL2CPP resolve stubs by icall name."),
s("mcp.unity_inventory", "MCP · Unity", "Player install inventory (assemblies, plugins, metadata)."),
s("mcp.function_at", "MCP · Functions", "Containing function for a body VA."),
+ s("mcp.function_create", "MCP · Functions", "Create/heal a function at VA (optional end)."),
s("mcp.decompile", "MCP · Decompile", "Stage-1 C; optional follow_stub for IL2CPP."),
s("mcp.get_current_address", "MCP · Cursor", "Report the currently focused Listing VA."),
s("mcp.get_current_function", "MCP · Cursor", "Report the function containing the cursor."),
diff --git a/crates/ghidrust-il2cpp/src/binary.rs b/crates/ghidrust-il2cpp/src/binary.rs
index 3d7ee11..5b428dd 100644
--- a/crates/ghidrust-il2cpp/src/binary.rs
+++ b/crates/ghidrust-il2cpp/src/binary.rs
@@ -1,12 +1,15 @@
//! CodeRegistration / MetadataRegistration correlation (PE64 P0).
+use crate::body::{
+ collapse_shared_stubs, fingerprint_body, semantics_mismatch, BodyClass, SharedStubSummary,
+};
use crate::error::{Error, Result};
use crate::metadata::Il2CppMetadata;
use ghidrust_core::Program;
-use serde::Serialize;
+use serde::{Deserialize, Serialize};
-/// One managed method with optional validated RVA.
-#[derive(Debug, Clone, Serialize)]
+/// One managed method with optional validated RVA + body proof.
+#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MethodMapEntry {
pub method_index: u32,
pub name: String,
@@ -15,15 +18,54 @@ pub struct MethodMapEntry {
pub rva: Option<u64>,
pub va: Option<u64>,
pub token: u32,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub body_class: Option<BodyClass>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub shared_target: Option<u64>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub alias_count: Option<usize>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub prologue_hash: Option<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub semantics_mismatch: Option<bool>,
}
-#[derive(Debug, Clone, Serialize)]
+#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MethodMap {
pub binary_name: String,
pub metadata_version: i32,
pub method_pointer_count: Option<u64>,
pub entries: Vec<MethodMapEntry>,
pub notes: Vec<String>,
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub shared_stubs: Vec<SharedStubSummary>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub build_skew: Option<BuildSkew>,
+}
+
+/// Diff of current map against a prior map JSON (catalog skew).
+#[derive(Debug, Clone, Serialize, Deserialize, Default)]
+pub struct BuildSkew {
+ pub moved: Vec<SkewMoved>,
+ pub missing: Vec<SkewName>,
+ pub appeared: Vec<SkewName>,
+ /// Small sample of moved rows for agents (first N).
+ pub sample: Vec<SkewMoved>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct SkewMoved {
+ pub full_name: String,
+ pub method_index: u32,
+ pub old_rva: Option<u64>,
+ pub new_rva: Option<u64>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct SkewName {
+ pub full_name: String,
+ pub method_index: u32,
+ pub rva: Option<u64>,
}
/// Correlate metadata method indices with binary method pointers when registration validates.
@@ -49,15 +91,122 @@ pub fn correlate(prog: &Program, meta: &Il2CppMetadata) -> Result<MethodMap> {
rva,
va,
token: m.token,
+ body_class: None,
+ shared_target: None,
+ alias_count: None,
+ prologue_hash: None,
+ semantics_mismatch: None,
});
}
- Ok(MethodMap {
+ let mut map = MethodMap {
binary_name: prog.name.clone(),
metadata_version: meta.header.version,
method_pointer_count: pointers.as_ref().map(|p| p.len() as u64),
entries,
notes,
- })
+ shared_stubs: Vec::new(),
+ build_skew: None,
+ };
+ enrich_bodies(prog, &mut map);
+ Ok(map)
+}
+
+/// Fingerprint each resolved RVA and emit shared_stubs aggregate.
+pub fn enrich_bodies(prog: &Program, map: &mut MethodMap) {
+ for e in &mut map.entries {
+ let Some(va) = e.va else { continue };
+ let fp = fingerprint_body(prog, va);
+ e.body_class = Some(fp.body_class);
+ e.shared_target = fp.shared_target;
+ e.prologue_hash = if fp.prologue_hash.is_empty() {
+ None
+ } else {
+ Some(fp.prologue_hash)
+ };
+ e.semantics_mismatch = Some(semantics_mismatch(&e.name, fp.body_class));
+ }
+ map.shared_stubs = collapse_shared_stubs(&mut map.entries);
+ // Recompute mismatch after shared_stub promotion.
+ for e in &mut map.entries {
+ if let Some(bc) = e.body_class {
+ e.semantics_mismatch = Some(semantics_mismatch(&e.name, bc));
+ }
+ }
+}
+
+/// Compare `current` against a prior MethodMap (by full_name, fallback method_index).
+pub fn compare_baseline(current: &MethodMap, baseline: &MethodMap) -> BuildSkew {
+ use std::collections::HashMap;
+ let mut base_by_name: HashMap<&str, &MethodMapEntry> = HashMap::new();
+ let mut base_by_idx: HashMap<u32, &MethodMapEntry> = HashMap::new();
+ for e in &baseline.entries {
+ base_by_name.insert(e.full_name.as_str(), e);
+ base_by_idx.insert(e.method_index, e);
+ }
+ let mut cur_by_name: HashMap<&str, &MethodMapEntry> = HashMap::new();
+ for e in &current.entries {
+ cur_by_name.insert(e.full_name.as_str(), e);
+ }
+
+ let mut moved = Vec::new();
+ let mut appeared = Vec::new();
+ let mut seen_base = std::collections::HashSet::new();
+
+ for e in &current.entries {
+ let prev = base_by_name
+ .get(e.full_name.as_str())
+ .copied()
+ .or_else(|| base_by_idx.get(&e.method_index).copied());
+ match prev {
+ Some(p) => {
+ seen_base.insert(p.full_name.as_str());
+ if p.rva != e.rva {
+ moved.push(SkewMoved {
+ full_name: e.full_name.clone(),
+ method_index: e.method_index,
+ old_rva: p.rva,
+ new_rva: e.rva,
+ });
+ }
+ }
+ None => {
+ appeared.push(SkewName {
+ full_name: e.full_name.clone(),
+ method_index: e.method_index,
+ rva: e.rva,
+ });
+ }
+ }
+ }
+
+ let mut missing = Vec::new();
+ for e in &baseline.entries {
+ if !cur_by_name.contains_key(e.full_name.as_str())
+ && !current.entries.iter().any(|c| c.method_index == e.method_index)
+ {
+ missing.push(SkewName {
+ full_name: e.full_name.clone(),
+ method_index: e.method_index,
+ rva: e.rva,
+ });
+ } else {
+ let _ = seen_base;
+ }
+ }
+
+ let sample: Vec<_> = moved.iter().take(16).cloned().collect();
+ BuildSkew {
+ moved,
+ missing,
+ appeared,
+ sample,
+ }
+}
+
+/// Load a prior map JSON from disk.
+pub fn load_baseline_map(path: &std::path::Path) -> Result<MethodMap> {
+ let data = std::fs::read(path).map_err(|e| Error::Io(e.to_string()))?;
+ serde_json::from_slice(&data).map_err(|e| Error::Parse(format!("baseline map: {e}")))
}
/// Scan non-exec data for a pointer array that looks like methodPointers.
@@ -172,3 +321,93 @@ pub fn load_and_correlate(
let meta = Il2CppMetadata::load_path(meta_path)?;
correlate(&prog, &meta)
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn baseline_skew_moved_and_missing() {
+ let baseline = MethodMap {
+ binary_name: "a".into(),
+ metadata_version: 31,
+ method_pointer_count: None,
+ entries: vec![
+ MethodMapEntry {
+ method_index: 0,
+ name: "get_a".into(),
+ full_name: "T::get_a".into(),
+ rva: Some(0x1000),
+ va: Some(0x140001000),
+ token: 1,
+ body_class: None,
+ shared_target: None,
+ alias_count: None,
+ prologue_hash: None,
+ semantics_mismatch: None,
+ },
+ MethodMapEntry {
+ method_index: 1,
+ name: "gone".into(),
+ full_name: "T::gone".into(),
+ rva: Some(0x2000),
+ va: None,
+ token: 2,
+ body_class: None,
+ shared_target: None,
+ alias_count: None,
+ prologue_hash: None,
+ semantics_mismatch: None,
+ },
+ ],
+ notes: vec![],
+ shared_stubs: vec![],
+ build_skew: None,
+ };
+ let current = MethodMap {
+ binary_name: "a".into(),
+ metadata_version: 31,
+ method_pointer_count: None,
+ entries: vec![
+ MethodMapEntry {
+ method_index: 0,
+ name: "get_a".into(),
+ full_name: "T::get_a".into(),
+ rva: Some(0x1100),
+ va: Some(0x140001100),
+ token: 1,
+ body_class: Some(BodyClass::Complex),
+ shared_target: None,
+ alias_count: None,
+ prologue_hash: None,
+ semantics_mismatch: None,
+ },
+ MethodMapEntry {
+ method_index: 2,
+ name: "new".into(),
+ full_name: "T::new".into(),
+ rva: Some(0x3000),
+ va: None,
+ token: 3,
+ body_class: None,
+ shared_target: None,
+ alias_count: None,
+ prologue_hash: None,
+ semantics_mismatch: None,
+ },
+ ],
+ notes: vec![],
+ shared_stubs: vec![],
+ build_skew: None,
+ };
+ let skew = compare_baseline(&current, &baseline);
+ assert_eq!(skew.moved.len(), 1);
+ assert_eq!(skew.moved[0].old_rva, Some(0x1000));
+ assert_eq!(skew.moved[0].new_rva, Some(0x1100));
+ assert_eq!(skew.missing.len(), 1);
+ assert_eq!(skew.missing[0].full_name, "T::gone");
+ assert_eq!(skew.appeared.len(), 1);
+ assert_eq!(skew.appeared[0].full_name, "T::new");
+ assert!(!skew.sample.is_empty());
+ }
+}
diff --git a/crates/ghidrust-il2cpp/src/body.rs b/crates/ghidrust-il2cpp/src/body.rs
new file mode 100644
index 0000000..0cad365
--- /dev/null
+++ b/crates/ghidrust-il2cpp/src/body.rs
@@ -0,0 +1,548 @@
+//! 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).
+
+use crate::stubs::{classify_at, follow_stub_target};
+use ghidrust_core::{disassemble_range, Program};
+use serde::{Deserialize, Serialize};
+use std::collections::HashMap;
+
+/// Shape of a native body at a method pointer VA.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum BodyClass {
+ ThinThunk,
+ SharedStub,
+ EmptyXorAlRet,
+ BoolBitTest,
+ Complex,
+ Unreadable,
+ RuntimeUnresolved,
+}
+
+/// Fingerprint of bytes/disasm at one VA.
+#[derive(Debug, Clone, Serialize)]
+pub struct BodyFingerprint {
+ pub body_class: BodyClass,
+ /// CRC16-CCITT over the first prologue bytes (FLIRT-adjacent, not a FLIRT DB).
+ pub prologue_hash: String,
+ pub shared_target: Option<u64>,
+ pub insn_count: usize,
+}
+
+/// Aggregate shared-stub summary for map JSON.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct SharedStubSummary {
+ pub target: u64,
+ pub prologue_hash: String,
+ pub alias_count: usize,
+ pub sample_names: Vec<String>,
+}
+
+const PROLOGUE_BYTES: usize = 16;
+const TINY_INSN_LIMIT: usize = 6;
+const TINY_BYTE_LIMIT: usize = 24;
+
+/// Fingerprint the native body at `va`.
+pub fn fingerprint_body(prog: &Program, va: u64) -> BodyFingerprint {
+ let Some(bytes) = prog.read_va(va, PROLOGUE_BYTES.max(32)) else {
+ return BodyFingerprint {
+ body_class: BodyClass::Unreadable,
+ prologue_hash: String::new(),
+ shared_target: None,
+ insn_count: 0,
+ };
+ };
+ if bytes.is_empty() {
+ return BodyFingerprint {
+ body_class: BodyClass::Unreadable,
+ prologue_hash: String::new(),
+ shared_target: None,
+ insn_count: 0,
+ };
+ }
+
+ let prologue_hash = format!("{:04x}", crc16_ccitt(&bytes[..bytes.len().min(PROLOGUE_BYTES)]));
+
+ // Resolve-stub with empty slot → runtime_unresolved (separate from thin thunk).
+ if let Some(stub) = classify_at(prog, va) {
+ if follow_stub_target(prog, &stub).is_none() {
+ return BodyFingerprint {
+ body_class: BodyClass::RuntimeUnresolved,
+ prologue_hash,
+ shared_target: None,
+ insn_count: 0,
+ };
+ }
+ }
+
+ if is_empty_xor_ret(&bytes) {
+ return BodyFingerprint {
+ body_class: BodyClass::EmptyXorAlRet,
+ prologue_hash,
+ shared_target: None,
+ insn_count: 2,
+ };
+ }
+
+ let listing = disassemble_range(prog, va, 16).unwrap_or_default();
+ let insn_count = listing.len();
+
+ if let Some((target, is_reg)) = thin_thunk_target(&listing) {
+ return BodyFingerprint {
+ body_class: BodyClass::ThinThunk,
+ prologue_hash,
+ shared_target: if is_reg { None } else { Some(target) },
+ insn_count,
+ };
+ }
+
+ if is_bool_bit_test(&listing) {
+ return BodyFingerprint {
+ body_class: BodyClass::BoolBitTest,
+ prologue_hash,
+ shared_target: None,
+ insn_count,
+ };
+ }
+
+ BodyFingerprint {
+ body_class: BodyClass::Complex,
+ prologue_hash,
+ shared_target: None,
+ insn_count,
+ }
+}
+
+/// True when a managed name looks like a getter/setter/predicate but the body is not.
+pub fn semantics_mismatch(name: &str, body_class: BodyClass) -> bool {
+ let leaf = name.rsplit("::").next().unwrap_or(name);
+ let leaf_l = leaf.to_ascii_lowercase();
+ let looks_accessor = leaf_l.starts_with("get_")
+ || leaf_l.starts_with("set_")
+ || leaf_l.starts_with("is")
+ || leaf_l.starts_with("has")
+ || leaf_l.starts_with("get") && leaf.len() > 3 && leaf.as_bytes().get(3).map(|c| c.is_ascii_uppercase()).unwrap_or(false);
+
+ if !looks_accessor {
+ return false;
+ }
+ matches!(
+ body_class,
+ BodyClass::EmptyXorAlRet
+ | BodyClass::ThinThunk
+ | BodyClass::SharedStub
+ | BodyClass::RuntimeUnresolved
+ | BodyClass::Unreadable
+ )
+}
+
+/// Collapse identical tiny bodies into shared_stub summaries.
+///
+/// Updates `entries` in place: when ≥2 methods share the same tiny prologue
+/// (or the same VA), promote `body_class` to `shared_stub` and set alias counts.
+pub fn collapse_shared_stubs(entries: &mut [crate::binary::MethodMapEntry]) -> Vec<SharedStubSummary> {
+ // Group by (prologue_hash) for tiny bodies, and by VA for identical pointers.
+ let mut by_hash: HashMap<String, Vec<usize>> = HashMap::new();
+ let mut by_va: HashMap<u64, Vec<usize>> = HashMap::new();
+
+ for (i, e) in entries.iter().enumerate() {
+ let Some(va) = e.va else { continue };
+ by_va.entry(va).or_default().push(i);
+ let Some(hash) = e.prologue_hash.as_ref() else { continue };
+ if hash.is_empty() {
+ continue;
+ }
+ let tiny = matches!(
+ e.body_class,
+ Some(BodyClass::ThinThunk)
+ | Some(BodyClass::EmptyXorAlRet)
+ | Some(BodyClass::BoolBitTest)
+ | Some(BodyClass::Complex)
+ ) && e
+ .body_class
+ .map(|c| {
+ // Complex only collapses when still tiny (insn heuristic stored nowhere —
+ // use shared_target / empty / thin / bool exclusively for hash groups).
+ matches!(
+ c,
+ BodyClass::ThinThunk | BodyClass::EmptyXorAlRet | BodyClass::BoolBitTest
+ )
+ })
+ .unwrap_or(false);
+ if tiny {
+ by_hash.entry(hash.clone()).or_default().push(i);
+ }
+ }
+
+ let mut summaries: Vec<SharedStubSummary> = Vec::new();
+ let mut seen_summary: HashMap<String, usize> = HashMap::new();
+
+ // Same VA → alias_count; promote tiny bodies to shared_stub when aliased.
+ for (va, idxs) in &by_va {
+ if idxs.len() < 2 {
+ // Still record alias_count=1 for consistency? Plan says when many collapse.
+ for &i in idxs {
+ entries[i].alias_count = Some(1);
+ }
+ continue;
+ }
+ let alias_count = idxs.len();
+ let hash = entries[idxs[0]]
+ .prologue_hash
+ .clone()
+ .unwrap_or_default();
+ let sample: Vec<String> = idxs
+ .iter()
+ .take(4)
+ .map(|&i| entries[i].full_name.clone())
+ .collect();
+ let promote = entries[idxs[0]].body_class.map(is_collapsible).unwrap_or(false);
+ for &i in idxs {
+ entries[i].alias_count = Some(alias_count);
+ if promote {
+ entries[i].body_class = Some(BodyClass::SharedStub);
+ entries[i].shared_target = Some(*va);
+ }
+ }
+ if promote {
+ let key = format!("va:{va:x}");
+ if let std::collections::hash_map::Entry::Vacant(slot) = seen_summary.entry(key) {
+ slot.insert(summaries.len());
+ summaries.push(SharedStubSummary {
+ target: *va,
+ prologue_hash: hash,
+ alias_count,
+ sample_names: sample,
+ });
+ }
+ }
+ }
+
+ // Same prologue hash at different VAs (identical tiny clones).
+ for (hash, idxs) in &by_hash {
+ if idxs.len() < 2 {
+ continue;
+ }
+ let distinct_vas: Vec<u64> = {
+ let mut v: Vec<u64> = idxs.iter().filter_map(|&i| entries[i].va).collect();
+ v.sort_unstable();
+ v.dedup();
+ v
+ };
+ if distinct_vas.len() < 2 {
+ continue; // already covered by same-VA group
+ }
+ let target = distinct_vas[0];
+ let alias_count = idxs.len();
+ let sample: Vec<String> = idxs
+ .iter()
+ .take(4)
+ .map(|&i| entries[i].full_name.clone())
+ .collect();
+ for &i in idxs {
+ entries[i].body_class = Some(BodyClass::SharedStub);
+ entries[i].shared_target = Some(target);
+ entries[i].alias_count = Some(alias_count.max(entries[i].alias_count.unwrap_or(0)));
+ }
+ let key = format!("hash:{hash}");
+ if let std::collections::hash_map::Entry::Vacant(slot) = seen_summary.entry(key) {
+ slot.insert(summaries.len());
+ summaries.push(SharedStubSummary {
+ target,
+ prologue_hash: hash.clone(),
+ alias_count,
+ sample_names: sample,
+ });
+ }
+ }
+
+ summaries.sort_by(|a, b| b.alias_count.cmp(&a.alias_count).then(a.target.cmp(&b.target)));
+ summaries
+}
+
+fn is_collapsible(c: BodyClass) -> bool {
+ matches!(
+ c,
+ BodyClass::ThinThunk
+ | BodyClass::EmptyXorAlRet
+ | BodyClass::BoolBitTest
+ | BodyClass::SharedStub
+ )
+}
+
+fn is_empty_xor_ret(bytes: &[u8]) -> bool {
+ // xor al,al / xor eax,eax / xor rax,rax + ret
+ // 30 c0 c3 | 31 c0 c3 | 33 c0 c3 | 48 31 c0 c3 | 48 33 c0 c3
+ // also xor edx,edx + ret (31 d2 c3) used as empty int return
+ if bytes.len() >= 3 {
+ let a = bytes[0];
+ let b = bytes[1];
+ let c = bytes[2];
+ if c == 0xc3 && matches!((a, b), (0x30, 0xc0) | (0x31, 0xc0) | (0x33, 0xc0) | (0x31, 0xd2) | (0x33, 0xd2))
+ {
+ return true;
+ }
+ }
+ if bytes.len() >= 4 && bytes[0] == 0x48 && bytes[3] == 0xc3 {
+ let b = bytes[1];
+ let c = bytes[2];
+ if matches!((b, c), (0x31, 0xc0) | (0x33, 0xc0) | (0x31, 0xd2) | (0x33, 0xd2)) {
+ return true;
+ }
+ }
+ false
+}
+
+/// Returns `(target_va, is_reg_thunk)`.
+fn thin_thunk_target(listing: &[ghidrust_core::Instruction]) -> Option<(u64, bool)> {
+ if listing.is_empty() || listing.len() > TINY_INSN_LIMIT {
+ return None;
+ }
+ // Allow optional junk (int3/nop) after a terminating jmp.
+ let mut saw_jmp = false;
+ let mut out: Option<(u64, bool)> = None;
+ for insn in listing {
+ let m = insn.mnemonic.to_ascii_lowercase();
+ if m == "int3" || m == "nop" {
+ if saw_jmp {
+ continue;
+ }
+ return None;
+ }
+ if saw_jmp {
+ return None;
+ }
+ if m == "jmp" {
+ saw_jmp = true;
+ if let Some(t) = parse_jmp_target(insn) {
+ out = Some((t, false));
+ } else {
+ let ops = insn.operands.to_ascii_lowercase();
+ if is_reg_only(&ops) {
+ out = Some((0, true));
+ } else {
+ return None;
+ }
+ }
+ continue;
+ }
+ // Strict: only pure jmp (+ trailing int3/nop).
+ return None;
+ }
+ out
+}
+
+fn parse_jmp_target(insn: &ghidrust_core::Instruction) -> Option<u64> {
+ let ops = insn.operands.trim();
+ // Absolute/rel: "0x140001234" or "140001234h"
+ if let Some(t) = parse_hex_token(ops) {
+ return Some(t);
+ }
+ // RIP-relative memory jmp [rip+disp]
+ let rip = ghidrust_core::rip_relative_targets(insn);
+ if let Some(&t) = rip.first() {
+ return Some(t);
+ }
+ None
+}
+
+fn parse_hex_token(s: &str) -> Option<u64> {
+ let t = s.trim().trim_end_matches('h');
+ let t = t.trim_start_matches("0x").trim_start_matches("0X");
+ if t.is_empty() || !t.chars().all(|c| c.is_ascii_hexdigit()) {
+ return None;
+ }
+ u64::from_str_radix(t, 16).ok()
+}
+
+fn is_reg_only(ops: &str) -> bool {
+ let o = ops.trim();
+ matches!(
+ o,
+ "rax" | "rcx" | "rdx" | "rbx" | "rsp" | "rbp" | "rsi" | "rdi"
+ | "r8" | "r9" | "r10" | "r11" | "r12" | "r13" | "r14" | "r15"
+ | "eax" | "ecx" | "edx"
+ )
+}
+
+fn is_bool_bit_test(listing: &[ghidrust_core::Instruction]) -> bool {
+ if listing.is_empty() || listing.len() > 8 {
+ return false;
+ }
+ let mut has_mem_load = false;
+ let mut has_bit = false;
+ let mut has_ret = false;
+ for insn in listing {
+ let m = insn.mnemonic.to_ascii_lowercase();
+ let ops = insn.operands.to_ascii_lowercase();
+ if m == "ret" {
+ has_ret = true;
+ }
+ if (m == "mov" || m == "movzx" || m == "movsx") && ops.contains('[') {
+ has_mem_load = true;
+ }
+ if m == "bt" || m == "test" {
+ has_bit = true;
+ }
+ if m == "and"
+ && (ops.contains(", 1")
+ || ops.contains(",1")
+ || ops.contains(", 0x1")
+ || ops.contains(",0x1"))
+ {
+ has_bit = true;
+ }
+ if m == "shr" || m == "sar" {
+ // field extract then mask — weak signal with and/test
+ has_bit = has_bit || ops.contains(", 1") || ops.contains(",1");
+ }
+ }
+ has_mem_load && has_bit && has_ret && listing.len() <= 8
+}
+
+/// CRC-16/CCITT-FALSE (poly 0x1021, init 0xFFFF).
+pub fn crc16_ccitt(data: &[u8]) -> u16 {
+ let mut crc: u16 = 0xFFFF;
+ for &b in data {
+ crc ^= (b as u16) << 8;
+ for _ in 0..8 {
+ if crc & 0x8000 != 0 {
+ crc = (crc << 1) ^ 0x1021;
+ } else {
+ crc <<= 1;
+ }
+ }
+ }
+ crc
+}
+
+/// Alias kept for call sites / tests.
+pub fn fingerprint_body_norm(prog: &Program, va: u64) -> BodyFingerprint {
+ let _ = TINY_BYTE_LIMIT;
+ fingerprint_body(prog, va)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use ghidrust_core::program::{MemoryBlock, Program};
+
+ fn prog_with_text(bytes: &[u8]) -> Program {
+ let image_base = 0x140000000u64;
+ let text_va = image_base + 0x1000;
+ let mut prog = Program::new("body".into(), "PE32+");
+ prog.image_base = image_base;
+ prog.blocks.push(MemoryBlock {
+ name: ".text".into(),
+ va: text_va,
+ size: bytes.len() as u64,
+ bytes: bytes.to_vec(),
+ readable: true,
+ writable: false,
+ executable: true,
+ });
+ prog
+ }
+
+ #[test]
+ fn xor_eax_eax_ret_empty() {
+ let prog = prog_with_text(&[0x31, 0xc0, 0xc3]);
+ let fp = fingerprint_body_norm(&prog, 0x140001000);
+ assert_eq!(fp.body_class, BodyClass::EmptyXorAlRet);
+ assert!(!fp.prologue_hash.is_empty());
+ }
+
+ #[test]
+ fn xor_al_al_ret_empty() {
+ let prog = prog_with_text(&[0x30, 0xc0, 0xc3]);
+ let fp = fingerprint_body_norm(&prog, 0x140001000);
+ assert_eq!(fp.body_class, BodyClass::EmptyXorAlRet);
+ }
+
+ #[test]
+ fn jmp_rel32_thin_thunk() {
+ // jmp +0 ; E9 00 00 00 00 → target = next+0 = va+5
+ let prog = prog_with_text(&[0xE9, 0x00, 0x00, 0x00, 0x00]);
+ let fp = fingerprint_body_norm(&prog, 0x140001000);
+ assert_eq!(fp.body_class, BodyClass::ThinThunk);
+ assert_eq!(fp.shared_target, Some(0x140001005));
+ }
+
+ #[test]
+ fn jmp_reg_thin_thunk() {
+ let prog = prog_with_text(&[0xFF, 0xE0]); // jmp rax
+ let fp = fingerprint_body_norm(&prog, 0x140001000);
+ assert_eq!(fp.body_class, BodyClass::ThinThunk);
+ assert!(fp.shared_target.is_none());
+ }
+
+ #[test]
+ fn bool_bit_test_getter() {
+ // movzx eax, byte [rcx+0x10] ; and eax, 1 ; ret
+ let bytes = [
+ 0x0F, 0xB6, 0x41, 0x10, // movzx eax, byte ptr [rcx+0x10]
+ 0x83, 0xE0, 0x01, // and eax, 1
+ 0xC3, // ret
+ ];
+ let prog = prog_with_text(&bytes);
+ let fp = fingerprint_body_norm(&prog, 0x140001000);
+ assert_eq!(fp.body_class, BodyClass::BoolBitTest, "{fp:?}");
+ }
+
+ #[test]
+ fn semantics_mismatch_getter_empty() {
+ assert!(semantics_mismatch("Foo::get_main", BodyClass::EmptyXorAlRet));
+ assert!(semantics_mismatch("isReady", BodyClass::ThinThunk));
+ assert!(semantics_mismatch("hasFlag", BodyClass::SharedStub));
+ assert!(!semantics_mismatch("Update", BodyClass::EmptyXorAlRet));
+ assert!(!semantics_mismatch("get_main", BodyClass::BoolBitTest));
+ assert!(!semantics_mismatch("get_main", BodyClass::Complex));
+ }
+
+ #[test]
+ fn unreadable_va() {
+ let prog = Program::new("empty".into(), "PE32+");
+ let fp = fingerprint_body_norm(&prog, 0x140001000);
+ assert_eq!(fp.body_class, BodyClass::Unreadable);
+ }
+
+ #[test]
+ fn collapse_shared_identical_xor() {
+ use crate::binary::MethodMapEntry;
+ let mut entries = vec![
+ MethodMapEntry {
+ method_index: 0,
+ name: "get_a".into(),
+ full_name: "T::get_a".into(),
+ rva: Some(0x1000),
+ va: Some(0x140001000),
+ token: 0,
+ body_class: Some(BodyClass::EmptyXorAlRet),
+ shared_target: None,
+ alias_count: None,
+ prologue_hash: Some("abcd".into()),
+ semantics_mismatch: Some(true),
+ },
+ MethodMapEntry {
+ method_index: 1,
+ name: "get_b".into(),
+ full_name: "T::get_b".into(),
+ rva: Some(0x1000),
+ va: Some(0x140001000),
+ token: 0,
+ body_class: Some(BodyClass::EmptyXorAlRet),
+ shared_target: None,
+ alias_count: None,
+ prologue_hash: Some("abcd".into()),
+ semantics_mismatch: Some(true),
+ },
+ ];
+ let stubs = collapse_shared_stubs(&mut entries);
+ assert_eq!(stubs.len(), 1);
+ assert_eq!(stubs[0].alias_count, 2);
+ assert_eq!(entries[0].body_class, Some(BodyClass::SharedStub));
+ assert_eq!(entries[0].alias_count, Some(2));
+ }
+}
diff --git a/crates/ghidrust-il2cpp/src/error.rs b/crates/ghidrust-il2cpp/src/error.rs
index 0ea79a6..a18203b 100644
--- a/crates/ghidrust-il2cpp/src/error.rs
+++ b/crates/ghidrust-il2cpp/src/error.rs
@@ -15,6 +15,8 @@ pub const ENCRYPTED_METADATA_NEXT_STEPS: &[&str] = &[
"Use engine PE strings + il2cpp icalls for native internal-call RVAs",
"Treat GameAssembly resolve stubs as lazy thunks, not gameplay callers (xrefs --skip-stubs)",
"Instance/type latch may require live inspection when metadata is unavailable",
+ "If you have a decrypted dump: il2cpp touch-map --meta PATH|--meta-sections DIR --filter SUB",
+ "meta-sections DIR expects global-metadata.dat (or clear metadata.dat); section dumps documented in docs/IL2CPP.md",
];
impl Error {
@@ -71,5 +73,6 @@ mod tests {
let steps = v["next_steps"].as_array().expect("next_steps");
assert!(steps.len() >= 3);
assert!(steps.iter().any(|s| s.as_str().unwrap_or("").contains("il2cpp icalls")));
+ assert!(steps.iter().any(|s| s.as_str().unwrap_or("").contains("touch-map")));
}
}
diff --git a/crates/ghidrust-il2cpp/src/lib.rs b/crates/ghidrust-il2cpp/src/lib.rs
index bda78d7..1be64a9 100644
--- a/crates/ghidrust-il2cpp/src/lib.rs
+++ b/crates/ghidrust-il2cpp/src/lib.rs
@@ -4,13 +4,20 @@
//! See `docs/IL2CPP.md` for the supported version matrix.
pub mod binary;
+pub mod body;
pub mod error;
pub mod icall;
pub mod metadata;
pub mod stubs;
+pub mod touch_map;
pub use binary::{
- correlate, load_and_correlate, to_script_json, MethodMap, MethodMapEntry, ScriptJson,
+ compare_baseline, correlate, enrich_bodies, load_and_correlate, load_baseline_map,
+ to_script_json, BuildSkew, MethodMap, MethodMapEntry, ScriptJson, SkewMoved, SkewName,
+};
+pub use body::{
+ collapse_shared_stubs, fingerprint_body, fingerprint_body_norm, semantics_mismatch, BodyClass,
+ BodyFingerprint, SharedStubSummary,
};
pub use error::{Error, Result, ENCRYPTED_METADATA_NEXT_STEPS};
pub use icall::{
@@ -18,9 +25,13 @@ pub use icall::{
ICallTableLayout,
};
pub use metadata::{
- build_synthetic, build_synthetic_v31, Il2CppMetadata, MetadataDialect, METADATA_MAGIC,
+ build_synthetic, build_synthetic_v31, load_from_meta_sections_dir, load_metadata_flexible,
+ Il2CppMetadata, MetadataDialect, METADATA_MAGIC,
};
pub use stubs::{
classify_at, find_resolve_stubs, follow_stub_target, is_resolve_stub_va, stub_matches_filter,
Il2CppKind, ResolveStub,
};
+pub use touch_map::{
+ build_touch_map, touch_map, TouchConfidence, TouchKind, TouchMapReport, TouchMapRow,
+};
diff --git a/crates/ghidrust-il2cpp/src/metadata.rs b/crates/ghidrust-il2cpp/src/metadata.rs
index be90a1f..2e37c6c 100644
--- a/crates/ghidrust-il2cpp/src/metadata.rs
+++ b/crates/ghidrust-il2cpp/src/metadata.rs
@@ -127,6 +127,27 @@ impl Il2CppMetadata {
Self::parse(&data)
}
+ /// Load from a clear metadata file path, or from a directory containing it.
+ ///
+ /// Directory candidates (first hit wins):
+ /// - `global-metadata.dat`
+ /// - `metadata.dat`
+ /// - `global-metadata.dat.decrypted`
+ /// - nested `il2cpp_data/Metadata/global-metadata.dat`
+ pub fn load_path_or_dir(path: impl AsRef<Path>) -> Result<Self> {
+ let path = path.as_ref();
+ if path.is_file() {
+ return Self::load_path(path);
+ }
+ if path.is_dir() {
+ return load_from_meta_sections_dir(path);
+ }
+ Err(Error::Io(format!(
+ "metadata path not found: {}",
+ path.display()
+ )))
+ }
+
pub fn parse(data: &[u8]) -> Result<Self> {
if data.len() < 16 {
return Err(Error::Parse("metadata too small".into()));
@@ -436,6 +457,89 @@ fn parse_images(
Ok(out)
}
+/// Resolve metadata from `--meta PATH` and/or `--meta-sections DIR`.
+///
+/// Prefer an explicit file when both are given. Fail closed on encrypted magic
+/// with [`Error::EncryptedOrObfuscated`] (see `ENCRYPTED_METADATA_NEXT_STEPS`).
+pub fn load_metadata_flexible(
+ meta: Option<&Path>,
+ meta_sections: Option<&Path>,
+) -> Result<Il2CppMetadata> {
+ if let Some(p) = meta {
+ return Il2CppMetadata::load_path_or_dir(p);
+ }
+ if let Some(dir) = meta_sections {
+ return load_from_meta_sections_dir(dir);
+ }
+ Err(Error::Parse(
+ "provide --meta PATH or --meta-sections DIR".into(),
+ ))
+}
+
+/// Load clear `global-metadata.dat` (or documented aliases) from a directory.
+///
+/// Expected layout (see `docs/IL2CPP.md`):
+/// - `DIR/global-metadata.dat` — preferred clear dump
+/// - `DIR/metadata.dat` — alternate name
+/// - `DIR/global-metadata.dat.decrypted`
+/// - `DIR/*/il2cpp_data/Metadata/global-metadata.dat` — one level of player-data nesting
+///
+/// Sectioned v39+/v106 dumps are not reassembled in P0; place a clear monolithic
+/// file in the directory. Encrypted files fail closed (do not invent RVAs).
+pub fn load_from_meta_sections_dir(dir: &Path) -> Result<Il2CppMetadata> {
+ if !dir.is_dir() {
+ return Err(Error::Io(format!(
+ "meta-sections path is not a directory: {}",
+ dir.display()
+ )));
+ }
+ let candidates = [
+ dir.join("global-metadata.dat"),
+ dir.join("metadata.dat"),
+ dir.join("global-metadata.dat.decrypted"),
+ dir.join("Metadata").join("global-metadata.dat"),
+ dir.join("il2cpp_data")
+ .join("Metadata")
+ .join("global-metadata.dat"),
+ ];
+ let mut last_err: Option<Error> = None;
+ for c in &candidates {
+ if c.is_file() {
+ match Il2CppMetadata::load_path(c) {
+ Ok(m) => return Ok(m),
+ Err(e) => {
+ // Encrypted: surface immediately (fail closed).
+ if matches!(e, Error::EncryptedOrObfuscated { .. }) {
+ return Err(e);
+ }
+ last_err = Some(e);
+ }
+ }
+ }
+ }
+ // One-level scan for *_Data/il2cpp_data/Metadata/global-metadata.dat
+ if let Ok(rd) = std::fs::read_dir(dir) {
+ for ent in rd.flatten() {
+ let p = ent.path();
+ if p.is_dir() {
+ let nested = p
+ .join("il2cpp_data")
+ .join("Metadata")
+ .join("global-metadata.dat");
+ if nested.is_file() {
+ return Il2CppMetadata::load_path(nested);
+ }
+ }
+ }
+ }
+ Err(last_err.unwrap_or_else(|| {
+ Error::Io(format!(
+ "no clear global-metadata.dat under {} (see docs/IL2CPP.md meta-sections)",
+ dir.display()
+ ))
+ }))
+}
+
/// Build a minimal valid metadata blob for tests (dialect v31 layout).
pub fn build_synthetic_v31() -> Vec<u8> {
build_synthetic(31)
diff --git a/crates/ghidrust-il2cpp/src/touch_map.rs b/crates/ghidrust-il2cpp/src/touch_map.rs
new file mode 100644
index 0000000..18ca3f8
--- /dev/null
+++ b/crates/ghidrust-il2cpp/src/touch_map.rs
@@ -0,0 +1,278 @@
+//! Substring touch-map over metadata heaps (Inspector stringLiterals bridge).
+
+use crate::binary::{correlate, MethodMap};
+use crate::error::Result;
+use crate::metadata::{load_metadata_flexible, Il2CppMetadata, MethodDef, TypeDef};
+use ghidrust_core::Program;
+use serde::Serialize;
+use std::collections::HashMap;
+use std::path::Path;
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize)]
+#[serde(rename_all = "snake_case")]
+pub enum TouchKind {
+ Method,
+ Field,
+ Type,
+ Property,
+ Other,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
+#[serde(rename_all = "snake_case")]
+pub enum TouchConfidence {
+ NameOnly,
+ RvaBound,
+}
+
+#[derive(Debug, Clone, Serialize)]
+pub struct TouchMapRow {
+ pub string: String,
+ pub kind: TouchKind,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub full_name: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub mp_index: Option<u32>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub rva: Option<u64>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub va: Option<u64>,
+ pub confidence: TouchConfidence,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub note: Option<String>,
+}
+
+#[derive(Debug, Clone, Serialize)]
+pub struct TouchMapReport {
+ pub filter: String,
+ pub row_count: usize,
+ pub rows: Vec<TouchMapRow>,
+ pub notes: Vec<String>,
+}
+
+/// Build a touch-map for `filter` against metadata (file or meta-sections dir).
+pub fn touch_map(
+ meta_path: Option<&Path>,
+ meta_sections: Option<&Path>,
+ filter: &str,
+ prog: Option<&Program>,
+) -> Result<TouchMapReport> {
+ let meta = load_metadata_flexible(meta_path, meta_sections)?;
+ let map = prog.map(|p| correlate(p, &meta)).transpose()?;
+ Ok(build_touch_map(&meta, filter, map.as_ref()))
+}
+
+pub fn build_touch_map(
+ meta: &Il2CppMetadata,
+ filter: &str,
+ map: Option<&MethodMap>,
+) -> TouchMapReport {
+ let needle = filter.to_ascii_lowercase();
+ let mut rows = Vec::new();
+ let mut notes = Vec::new();
+
+ let mut method_by_name: HashMap<&str, Vec<&MethodDef>> = HashMap::new();
+ for m in &meta.methods {
+ method_by_name.entry(m.name.as_str()).or_default().push(m);
+ }
+
+ let type_full: Vec<(String, &TypeDef)> =
+ meta.types.iter().map(|t| (t.full_name(), t)).collect();
+ let type_by_full: HashMap<&str, &TypeDef> =
+ type_full.iter().map(|(n, t)| (n.as_str(), *t)).collect();
+ let type_by_short: HashMap<&str, &TypeDef> =
+ meta.types.iter().map(|t| (t.name.as_str(), t)).collect();
+
+ let map_by_idx: HashMap<u32, &crate::binary::MethodMapEntry> = map
+ .map(|m| m.entries.iter().map(|e| (e.method_index, e)).collect())
+ .unwrap_or_default();
+
+ for (_off, s) in &meta.strings {
+ if !s.to_ascii_lowercase().contains(&needle) {
+ continue;
+ }
+ rows.push(classify_string(
+ s,
+ meta,
+ &method_by_name,
+ &type_by_full,
+ &type_by_short,
+ &map_by_idx,
+ ));
+ }
+
+ for m in meta.filter_methods(filter) {
+ let full = meta.method_full_name(m);
+ if rows
+ .iter()
+ .any(|r| r.full_name.as_deref() == Some(full.as_str()))
+ {
+ continue;
+ }
+ let (rva, va, conf, note) = match map_by_idx.get(&m.index) {
+ Some(e) if e.rva.is_some() => {
+ let note = e.body_class.map(|c| format!("body_class={}", body_class_str(c)));
+ (e.rva, e.va, TouchConfidence::RvaBound, note)
+ }
+ Some(_) => (
+ None,
+ None,
+ TouchConfidence::NameOnly,
+ Some("mapped entry without proven RVA".into()),
+ ),
+ None => (None, None, TouchConfidence::NameOnly, None),
+ };
+ rows.push(TouchMapRow {
+ string: m.name.clone(),
+ kind: TouchKind::Method,
+ full_name: Some(full),
+ mp_index: Some(m.index),
+ rva,
+ va,
+ confidence: conf,
+ note,
+ });
+ }
+
+ for t in meta.filter_types(filter) {
+ let full = t.full_name();
+ if rows.iter().any(|r| {
+ r.kind == TouchKind::Type && r.full_name.as_deref() == Some(full.as_str())
+ }) {
+ continue;
+ }
+ rows.push(TouchMapRow {
+ string: t.name.clone(),
+ kind: TouchKind::Type,
+ full_name: Some(full),
+ mp_index: None,
+ rva: None,
+ va: None,
+ confidence: TouchConfidence::NameOnly,
+ note: None,
+ });
+ }
+
+ if map.is_none() {
+ notes.push("no binary loaded; confidence is name_only only".into());
+ }
+ rows.sort_by(|a, b| a.string.cmp(&b.string).then(a.kind.cmp(&b.kind)));
+ const MAX: usize = 4096;
+ if rows.len() > MAX {
+ notes.push(format!("truncated rows from {} to {MAX}", rows.len()));
+ rows.truncate(MAX);
+ }
+
+ TouchMapReport {
+ filter: filter.to_string(),
+ row_count: rows.len(),
+ rows,
+ notes,
+ }
+}
+
+fn body_class_str(c: crate::body::BodyClass) -> &'static str {
+ match c {
+ crate::body::BodyClass::ThinThunk => "thin_thunk",
+ crate::body::BodyClass::SharedStub => "shared_stub",
+ crate::body::BodyClass::EmptyXorAlRet => "empty_xor_al_ret",
+ crate::body::BodyClass::BoolBitTest => "bool_bit_test",
+ crate::body::BodyClass::Complex => "complex",
+ crate::body::BodyClass::Unreadable => "unreadable",
+ crate::body::BodyClass::RuntimeUnresolved => "runtime_unresolved",
+ }
+}
+
+fn classify_string<'a>(
+ s: &str,
+ meta: &'a Il2CppMetadata,
+ method_by_name: &HashMap<&str, Vec<&'a MethodDef>>,
+ type_by_full: &HashMap<&str, &'a TypeDef>,
+ type_by_short: &HashMap<&str, &'a TypeDef>,
+ map_by_idx: &HashMap<u32, &crate::binary::MethodMapEntry>,
+) -> TouchMapRow {
+ if let Some(methods) = method_by_name.get(s) {
+ if let Some(m) = methods.first() {
+ let full = meta.method_full_name(m);
+ let kind = if looks_property(s) {
+ TouchKind::Property
+ } else {
+ TouchKind::Method
+ };
+ let (rva, va, conf) = match map_by_idx.get(&m.index) {
+ Some(e) if e.rva.is_some() => (e.rva, e.va, TouchConfidence::RvaBound),
+ _ => (None, None, TouchConfidence::NameOnly),
+ };
+ return TouchMapRow {
+ string: s.to_string(),
+ kind,
+ full_name: Some(full),
+ mp_index: Some(m.index),
+ rva,
+ va,
+ confidence: conf,
+ note: None,
+ };
+ }
+ }
+ if let Some(t) = type_by_full.get(s).or_else(|| type_by_short.get(s)) {
+ return TouchMapRow {
+ string: s.to_string(),
+ kind: TouchKind::Type,
+ full_name: Some(t.full_name()),
+ mp_index: None,
+ rva: None,
+ va: None,
+ confidence: TouchConfidence::NameOnly,
+ note: None,
+ };
+ }
+ let kind = if looks_field(s) {
+ TouchKind::Field
+ } else if looks_property(s) {
+ TouchKind::Property
+ } else {
+ TouchKind::Other
+ };
+ TouchMapRow {
+ string: s.to_string(),
+ kind,
+ full_name: None,
+ mp_index: None,
+ rva: None,
+ va: None,
+ confidence: TouchConfidence::NameOnly,
+ note: None,
+ }
+}
+
+fn looks_property(name: &str) -> bool {
+ let n = name.to_ascii_lowercase();
+ n.starts_with("get_") || n.starts_with("set_")
+}
+
+fn looks_field(name: &str) -> bool {
+ (name.starts_with('<') && name.contains(">k__BackingField"))
+ || name.starts_with("m_")
+ || name.starts_with('_')
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::metadata::build_synthetic_v31;
+
+ #[test]
+ fn touch_map_finds_camera() {
+ let bytes = build_synthetic_v31();
+ let meta = Il2CppMetadata::parse(&bytes).unwrap();
+ let report = build_touch_map(&meta, "Camera", None);
+ assert!(report.row_count >= 1);
+ assert!(report.rows.iter().any(|r| {
+ r.full_name
+ .as_deref()
+ .unwrap_or("")
+ .contains("Camera")
+ }));
+ }
+}
diff --git a/docs/IL2CPP.md b/docs/IL2CPP.md
index 65d8d6d..2450b1b 100644
--- a/docs/IL2CPP.md
+++ b/docs/IL2CPP.md
@@ -8,7 +8,9 @@ Hand-rolled support for Unity IL2CPP metadata and player-install inventory. No I
ghidrust strings <path> [--raw] [--match substr|token|whole|glob] [--limit N] [--out FILE]
ghidrust bytes <path> --addr HEX [--count N] [--out FILE] [--json]
ghidrust il2cpp meta <global-metadata.dat> [--filter SUB] [--json] [--out FILE]
-ghidrust il2cpp map --binary <GameAssembly.dll> --meta <metadata.dat> [--script-json]
+ghidrust il2cpp map --binary <GameAssembly.dll> --meta <metadata.dat>|--meta-sections DIR
+ [--baseline PREV.json] [--baseline-strict] [--script-json]
+ghidrust il2cpp touch-map --meta PATH|--meta-sections DIR --filter SUB [--binary PE] [--json]
ghidrust il2cpp stubs --binary <GameAssembly.dll> [--filter SUB]
ghidrust il2cpp icalls --binary <UnityPlayer.dll> [--filter SUB] [--json] [--out FILE]
ghidrust xrefs … [--skip-stubs] [--classify] [--out FILE]
@@ -17,6 +19,33 @@ ghidrust decompile … [--follow-stub] [--out FILE]
ghidrust unity-inventory <player-dir> [--json]
```
+## Meta-sections directory
+
+When a clear monolithic `global-metadata.dat` is available (or decrypted offline), pass it with `--meta`, or point `--meta-sections DIR` at a folder that contains one of:
+
+| Candidate | Notes |
+|-----------|--------|
+| `DIR/global-metadata.dat` | Preferred clear dump |
+| `DIR/metadata.dat` | Alternate filename |
+| `DIR/global-metadata.dat.decrypted` | Explicit decrypted alias |
+| `DIR/Metadata/global-metadata.dat` | Nested Metadata folder |
+| `DIR/il2cpp_data/Metadata/global-metadata.dat` | Unity player layout fragment |
+| `DIR/*_Data/il2cpp_data/Metadata/global-metadata.dat` | One-level player-data scan |
+
+Ghidrust does **not** reassemble encrypted or v39+/v106 sectioned heaps. Place a clear `0xFAB11BAF` file in the directory. Wrong magic → fail closed with `next_steps` (includes touch-map / meta-sections).
+
+## Touch-map + body proof
+
+`il2cpp touch-map` searches metadata string heaps for `--filter` and classifies rows as `method|field|type|property|other`. With `--binary`, proven method pointers upgrade confidence to `rva_bound`.
+
+`il2cpp map` fingerprints each resolved VA:
+
+- `body_class`: `thin_thunk` | `shared_stub` | `empty_xor_al_ret` | `bool_bit_test` | `complex` | `unreadable` | `runtime_unresolved`
+- `shared_stubs[]` aggregate when many names collapse to one tiny body
+- `semantics_mismatch` when `get_`/`set_`/`is*`/`has*` names disagree with stub/empty bodies
+
+`--baseline PREV.json` emits `build_skew: { moved, missing, appeared, sample }`. `--baseline-strict` exits nonzero if any RVA moved.
+
## Engine icall resolve (name‖fn tables)
Unity engine PEs often store parallel pointer arrays: one of C-string name VAs (`Namespace.Type::method` / `*_Injected`) and one of code VAs. After `Create Address Tables` (stitched runs with `DataPtrs` / `CodePtrs` roles):
@@ -50,7 +79,8 @@ Launch: `ghidrust mcp` (or `target/release/ghidrust.exe mcp` after build). Stdio
| Tool | Args | Purpose |
|------|------|---------|
| `il2cpp_meta` | `path`, optional `filter` | Parse `global-metadata.dat` → types/methods |
-| `il2cpp_map` | `binary`, `meta`, optional `filter` | Metadata ↔ RVA map (`rva` null when unproven) |
+| `il2cpp_map` | `binary`, `meta` or `meta_sections`, optional `filter`, `baseline` | Metadata ↔ RVA map + `body_class` / `shared_stubs` / optional `build_skew` |
+| `il2cpp_touch_map` | `filter`, `meta` or `meta_sections`, optional `binary` | Substring touch-map over heaps |
| `il2cpp_stubs` | `binary`, optional `filter`, `max` | Classify resolve stubs |
| `il2cpp_icalls` | `binary`, optional `filter` | Engine name‖fn icall tables |
| `read_bytes` | `path`, `addr`, optional `count` | Raw VA dump |
@@ -78,7 +108,9 @@ Magic must be `0xFAB11BAF`. Wrong magic → fail closed. CLI/MCP JSON:
"next_steps": [
"Use engine PE strings + il2cpp icalls for native internal-call RVAs",
"Treat GameAssembly resolve stubs as lazy thunks, not gameplay callers (xrefs --skip-stubs)",
- "Instance/type latch may require live inspection when metadata is unavailable"
+ "Instance/type latch may require live inspection when metadata is unavailable",
+ "If you have a decrypted dump: il2cpp touch-map --meta PATH|--meta-sections DIR --filter SUB",
+ "meta-sections DIR expects global-metadata.dat (or clear metadata.dat); section dumps documented in docs/IL2CPP.md"
]
}
```
diff --git a/skill/README.md b/skill/README.md
index fa8ccb7..b46b75f 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, runs Auto Analysis, decompiles to pseudo-C, parses IL2CPP metadata / 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 [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.
**Aims:** a freestanding, auditable RE core; CPU-correct analysis first; optional experimental GPU bulk scan + VRAM-resident decompile; agent-friendly headless use.
@@ -18,11 +18,13 @@ cargo build --workspace --release
./target/release/ghidrust help
./target/release/ghidrust load fixtures/tiny_x64.pe
./target/release/ghidrust disasm fixtures/tiny_x64.pe --count 16
+./target/release/ghidrust function create fixtures/tiny_x64.pe --addr 0x140001000 --json
./target/release/ghidrust decompile fixtures/tiny_x64.pe --addr 0x140001000 --json
./target/release/ghidrust inventory fixtures --max-depth 2 --json
./target/release/ghidrust tree fixtures --ext pe,dat --json
./target/release/ghidrust artifact list --json
./target/release/ghidrust il2cpp meta fixtures/il2cpp/meta_v31.dat --filter Camera --json
+./target/release/ghidrust il2cpp touch-map --meta fixtures/il2cpp/meta_v31.dat --filter Camera --json
./target/release/ghidrust il2cpp stubs --binary fixtures/il2cpp/il2cpp_stub_lab.pe --json
./target/release/ghidrust gpu-decompile fixtures/tiny_x64.pe --out entry.gdecomp --json
@@ -31,7 +33,7 @@ cargo run -p ghidrust-gui --release
Windows: `.\target\release\ghidrust.exe` / `.\target\release\ghidrust-gui.exe`. Friction surfaces (`inventory`, `tree`, `artifact`, `process`, `rtti --filter`) match MCP tool names in `tool_defs()` — see [`SKILL.md`](SKILL.md).
-Check build identity: `ghidrust --version` (same package version as MCP `server_info` and egui About). Live multi-step work needs MCP `tool_surface >= 2`; restart MCP after rebuild if `process_*` is missing.
+Check build identity: `ghidrust --version` (same package version as MCP `server_info` and egui About). Agents need MCP `tool_surface >= 3` (touch-map / body_class / function_create); prefer `>= 4` for bounded disasm / `get_calls_from` (current is `4`). Restart MCP after rebuild if those or `process_*` are missing.
MCP for agents (register in Cursor / Claude Desktop / other MCP clients — see root README):
diff --git a/skill/SKILL.md b/skill/SKILL.md
index 9267dde..67d34cf 100644
--- a/skill/SKILL.md
+++ b/skill/SKILL.md
@@ -39,17 +39,19 @@ cargo build -p ghidrust-gui --release
## Agent friction SOPs (required)
-- **Version / stale MCP**: Call `server_info` first (or read `initialize.serverInfo`). This skill requires **`tool_surface >= 2`** (live process + artifacts + inventory). If `server_info` is missing, `tool_surface` is below that minimum, or `process_list` / `artifact_query` / `inventory` 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` 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).
- **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).
-- **Address→function**: Always pass `addr` to `decompile` / `disassemble` / `gpu_decompile`; trust `resolved_entry` / `resolve` meta. Mid-body hits resolve to containing entry; unmapped → `no_containing_function` (no invented 1-insn fn).
+- **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.
+- **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.
-- **IL2CPP offline → live**: (1) `il2cpp_meta` / `il2cpp_map` for method RVAs (null = unknown offline). (2) `decompile` + `follow_stub` for resolve stubs with mapped slots. (3) On `runtime_unresolved` / `trampoline_or_invoker` (see `next_steps` in JSON) → live attach → `process_resolve(module, rva)` → `process_read` for class/instance bytes. `follow_stub` is **not** “get managed method body for every RVA.”
+- **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).
+- **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.
## Decision tree
@@ -119,9 +121,11 @@ Need Ghidra ↔ Ghidrust head-to-head?
Unity player / IL2CPP?
→ unity-inventory GAME_DIR for install layout (assemblies, plugins, metadata)
- → il2cpp meta …/global-metadata.dat for managed types/methods
- → il2cpp stubs / map on GameAssembly.dll; xrefs --skip-stubs; decompile --follow-stub
- → encrypted metadata (wrong magic) → report encrypted, do not invent types
+ → il2cpp touch-map --meta META|--meta-sections DIR --filter NAME (names first)
+ → il2cpp map --binary GA.dll --meta META [--baseline PREV.json] → require body_class
+ (reject shared_stub / semantics_mismatch before hooking); inspect build_skew on rebuilds
+ → il2cpp meta for managed types/methods; stubs; xrefs --skip-stubs; decompile --follow-stub
+ → encrypted metadata (wrong magic) → report encrypted + next_steps; do not invent types
→ See docs/IL2CPP.md
Large string dumps / raw non-PE files?
@@ -178,13 +182,13 @@ ghidrust project analyze PROJ_DIR --file ID \
### MCP (`ghidrust mcp`)
-Requires **`tool_surface >= 2`**. Check with `server_info` after connect.
+Requires **`tool_surface >= 3`** (prefer `>= 4` for bounded disasm / `get_calls_from`; current is `4`). Check with `server_info` after connect.
| Tool | Args | Notes |
|------|------|-------|
| `server_info` | — | Package `version`, `tool_surface`, features, live session_model |
| `load` | `path` **or** `project`+`file_id` | Map + `section_notes` + `resolved_path` |
-| `disassemble` | `path`, optional `addr`, `count` | Containing-fn resolve + `decode_gaps` |
+| `disassemble` | `path`, optional `addr`, `count`, **`linear`** | Bounded by function end by default; `linear:true` escapes; 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 |
@@ -192,16 +196,19 @@ Requires **`tool_surface >= 2`**. Check with `server_info` after connect.
| `list_analyzers` | — | Auto Analysis names |
| `analyze` | `path`, optional `analyzers[]`, **`gpu`** | CPU + optional GPU enrich |
| `list_strings` / `search_strings` | `path`, optional `encoding`, `filter`, **`match`**, `min`, **`limit`**, **`raw`** | Blob scan when `raw:true` |
-| `get_xrefs_to` | `path`, `addr`, optional **`skip_stubs`**, **`classify`** | RIP/tables + data ptrs; IL2CPP stubs |
-| `get_xrefs_from` | `path`, `addr`, optional `count` | Xrefs from VA |
+| `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`) |
| `list_imports` / `get_import_xrefs` | `path`, optional `dll`/`name` | PE IAT |
-| `function_at` / `get_function_by_address` | `path`, `addr` | Containing function |
+| `function_at` / `get_function_by_address` | `path`, `addr` | Containing function + `seed_kind` |
| `read_bytes` | `path`, `addr`, optional `count` | Raw VA hex dump |
| `il2cpp_meta` | `path`, optional `filter` | `global-metadata.dat` types/methods (v27/29/31); encrypted → `next_steps` JSON |
-| `il2cpp_map` | `binary`, `meta`, optional `filter` | Method RVA map; null when unproven |
+| `il2cpp_map` | `binary`, `meta` or `meta_sections`, optional `filter`, `baseline` | Method RVA map + `body_class` / `shared_stubs` / `semantics_mismatch` / optional `build_skew`; null RVA when unproven |
+| `il2cpp_touch_map` | `filter`, `meta` or `meta_sections`, optional `binary` | Heap substring touch-map (`name_only` \| `rva_bound`) |
| `il2cpp_stubs` | `binary`, optional `filter`, `max` | Resolve stubs (filter: name or C-string at `name_string_va`) |
| `il2cpp_icalls` | `binary`, optional `filter` | Engine name‖fn icall tables → index / RVA |
+| `function_create` | `path`, `addr`, optional `end` | Create/heal function (pdata/export/FSS; may synthesize `SYNTH_*`) |
| `unity_inventory` | `path` | Player dir + PE VERSIONINFO helpers |
| `decompile` | `path`, optional `addr`, `count`, `stage`, **`follow_stub`** | Resolve meta + Stage-1; JSON: `folded_temps`, `token_count`, `goto_rate`; `follow_stub` may be `runtime_unresolved` / `trampoline_or_invoker` with `next_steps` → live process |
| `list_gpu_strategies` | — | Strategy matrix |
@@ -221,7 +228,8 @@ Canonical detail: [`docs/IL2CPP.md`](../docs/IL2CPP.md).
|------|-----|-----|
| Player install inventory | `ghidrust unity-inventory GAME_DIR --json` | `unity_inventory` `{path}` |
| Managed types/methods | `ghidrust il2cpp meta META.dat [--filter F] --json` | `il2cpp_meta` `{path, filter?}` |
-| Metadata ↔ RVA | `ghidrust il2cpp map --binary GA.dll --meta META.dat --json` | `il2cpp_map` `{binary, meta, filter?}` |
+| Touch-map (names) | `ghidrust il2cpp touch-map --meta META\|--meta-sections DIR --filter F [--binary GA.dll] --json` | `il2cpp_touch_map` |
+| Metadata ↔ RVA + body proof | `ghidrust il2cpp map --binary GA.dll --meta META.dat\|--meta-sections DIR [--baseline PREV.json] [--baseline-strict] --json` | `il2cpp_map` `{binary, meta\|meta_sections, filter?, baseline?}` |
| Engine icall name→fn | `ghidrust il2cpp icalls --binary ENGINE.dll --filter F --json` | `il2cpp_icalls` `{binary, filter?}` |
| Resolve stubs | `ghidrust il2cpp stubs --binary GA.dll --filter F --json` | `il2cpp_stubs` `{binary, filter?, max?}` |
| Raw bytes at VA | `ghidrust bytes PATH --addr HEX --count N --json` | `read_bytes` `{path, addr, count?}` |
@@ -253,17 +261,18 @@ 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]` |
+| Disasm | `ghidrust disasm <path> [--addr HEX] [--count N] [--skip-bad] [--linear\|--flow]` (bounded by fn end by default; JSON `stop_reason`) |
| Strings | `ghidrust strings <path> [--raw] [--encoding …] [--match MODE] [--limit N] [--out FILE] [--filter SUB]` |
-| Xrefs | `ghidrust xrefs <path> (--to\|--from\|--string\|--import) [--encoding ascii\|utf16le\|all] [--skip-stubs] [--classify] [--out FILE]` |
+| 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]` |
| Imports | `ghidrust imports <path> [--dll\|--name]` |
-| Function-at | `ghidrust function-at <path> --addr HEX` |
+| Function-at | `ghidrust function-at <path> --addr HEX` (`seed_kind`) |
+| Function create | `ghidrust function create <path> --addr HEX [--end HEX]` |
| 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 …` |
-| IL2CPP | `ghidrust il2cpp meta\|map\|stubs\|icalls …` (see `docs/IL2CPP.md`) |
+| 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]` |
| List analyzers | `ghidrust analyzers` |
@@ -317,7 +326,9 @@ ghidrust process detach SESSION
# Unity / IL2CPP
ghidrust unity-inventory GAME_DIR --json
+ghidrust il2cpp touch-map --meta GAME_DIR/*_Data/il2cpp_data/Metadata/global-metadata.dat --filter Camera --json
ghidrust il2cpp meta GAME_DIR/*_Data/il2cpp_data/Metadata/global-metadata.dat --filter Camera --json
+ghidrust il2cpp map --binary GAME_DIR/GameAssembly.dll --meta GAME_DIR/*_Data/il2cpp_data/Metadata/global-metadata.dat --json
ghidrust il2cpp stubs --binary GAME_DIR/GameAssembly.dll --filter Camera --json
ghidrust il2cpp icalls --binary GAME_DIR/UnityPlayer.dll --filter Camera --json
ghidrust xrefs GAME_DIR/GameAssembly.dll --to HEX --skip-stubs --classify --json