mirror of
https://github.com/sp00nznet/xboxrecomp.git
synced 2026-12-05 01:52:57 +00:00
An IDA path for name recovery, alongside the Ghidra one
From pcrecomp's CONSOLIDATION.md, which lists "xboxrecomp has Ghidra scripts but no IDA path" as one of four things flowing this way. It is the only one of the four that was a real gap here, and the gap was never the analysis -- IDA's FLIRT and demangler recover the same kind of names Ghidra's FidDb and RTTI analyzers do. It was that nothing wrote them out in the shape merge_names.py reads. So that is all this is. One exporter, ~130 lines, writing the same functions.json and symbols.json Ghidra's post-script writes; the merge, the placeholder filter, the sanitising, the collision handling and --apply stay where they are. Rather than porting pcrecomp's four IDA scripts (436 lines), which solve problems -- NE segment numbering, call-graph triage -- that the Xbox side does not have. FLIRT and FidDb are the same idea with different coverage and neither is a superset, so running both and taking the union names more than either alone. That is the same result symbols/map_names measures for donor MAP files. Two things in the shared consumer, because the export is not the only half: - IDA's autonames are not all Ghidra's. loc_ is IDA's LAB_, and jpt_/algn_/asc_/stru_/flt_/dbl_ have no Ghidra equivalent. Without those prefixes an IDA export merges thousands of loc_1A2B3C-shaped non-names into the recompiler, and `void loc_1A2B3C(void)` reads as a recovered name when it is the address in disguise. - The function branch's source argument was a ternary with the same value in both arms. Now it honours an exporter-supplied `source`, so IDA's FLIRT flag actually reaches the fidb/library bucket. Ghidra's export has no such field and is unchanged. Not ported, and why: pcrecomp's pe/ (1,590) is for looking at a Windows binary alongside an XBE, which nothing here does yet; drm/ and assets/ solve SafeDisc and InstallShield, which the Xbox does not have; ne/ is 16-bit. classify/ (1,600) is four per-project scripts with hardcoded paths against the Half-Life SDK and DOS segment arithmetic -- there is no general tool in there for func_id to merge with. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uoundkw2h1Z9uiD1sc2oFJ
This commit is contained in:
@@ -269,7 +269,8 @@ xboxrecomp/
|
||||
│ ├── abi_analysis/ # Calling convention / param recovery
|
||||
│ ├── recomp/ # x86 -> C static recompiler
|
||||
│ ├── debug_symbols/ # Debug-build symbol recovery
|
||||
│ ├── symbols/ ghidra_naming/ # Optional symbol-name recovery
|
||||
│ ├── symbols/ ghidra_naming/ # Optional symbol-name recovery (Ghidra)
|
||||
│ ├── ida_naming/ # ... or the same thing through IDA
|
||||
│ ├── xiso/ xmv/ # Disc image and video container tools
|
||||
│ └── fusion/ # MS Ficl/Fission study tooling
|
||||
├── src/ # Runtime libraries (C, link-time)
|
||||
@@ -404,7 +405,7 @@ capstone # x86 disassembly (pip install capstone)
|
||||
pytest # test suite only (pip install pytest)
|
||||
```
|
||||
|
||||
That's it for the core pipeline — no IDA, no Ghidra, no proprietary tools. Just the standard library + Capstone. (An *optional* `tools/ghidra_naming` helper can use headless Ghidra purely to recover symbol names; it is never required to produce a working build.)
|
||||
That's it for the core pipeline — no IDA, no Ghidra, no proprietary tools. Just the standard library + Capstone. (Optional `tools/ghidra_naming` and `tools/ida_naming` helpers use headless Ghidra or IDA purely to recover symbol names; neither is ever required to produce a working build.)
|
||||
|
||||
### Running the tests
|
||||
|
||||
|
||||
@@ -1,15 +1,16 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Merge Ghidra-exported names into a clean {address: name} map for the recompiler.
|
||||
Merge exported names into a clean {address: name} map for the recompiler.
|
||||
|
||||
Reads the JSONs produced by ExportXbeNames.py:
|
||||
tools/ghidra_naming/export/functions.json
|
||||
tools/ghidra_naming/export/symbols.json
|
||||
Reads the JSONs produced by Ghidra's ExportXbeNames.py, or by IDA's
|
||||
tools/ida_naming/export_xbe_names.py, which writes the same two files:
|
||||
<export-dir>/functions.json
|
||||
<export-dir>/symbols.json
|
||||
|
||||
Produces:
|
||||
tools/ghidra_naming/ghidra_names.json -> { "0x00352560": "name", ... }
|
||||
|
||||
Only MEANINGFUL names are kept. Ghidra auto-generated placeholders are excluded:
|
||||
Only MEANINGFUL names are kept. Auto-generated placeholders are excluded:
|
||||
FUN_*, LAB_*, DAT_*, SUB_*, UNK_*, EXT_*, OFF_*, thunk_FUN_*, switchD_*,
|
||||
caseD_*, j_* (jump thunks), and entirely-numeric / empty names.
|
||||
Each kept name is sanitized to a valid C identifier (alnum + underscore, no
|
||||
@@ -64,6 +65,12 @@ PLACEHOLDER_PREFIXES = (
|
||||
"FID_", # FunctionID conflict / hash marker
|
||||
"BYTE_", "WORD_", "DWORD_", "QWORD_", "UINT_", "INT_",
|
||||
"FLOAT_", "DOUBLE_", "BOOL_", "CHAR_", "UNICODE_",
|
||||
# IDA's own, for tools/ida_naming/export_xbe_names.py. Its autonames do
|
||||
# not all overlap Ghidra's: loc_ is IDA's LAB_, and jpt_/algn_/asc_/stru_
|
||||
# have no Ghidra equivalent at all. Without these an IDA export merges
|
||||
# thousands of loc_1A2B3C-shaped non-names into the recompiler.
|
||||
"LOC_", "NULLSUB_", "JPT_", "ALGN_", "ASC_", "STRU_",
|
||||
"XMMWORD_", "YMMWORD_", "TBYTE_", "FLT_", "DBL_", "PACKREAL_",
|
||||
)
|
||||
# Exact placeholder names (no address suffix) that must be dropped.
|
||||
PLACEHOLDER_EXACT = {
|
||||
@@ -260,9 +267,12 @@ def build_map(export_dir):
|
||||
if funcs:
|
||||
for f in funcs:
|
||||
addr = norm_addr(f.get("address"))
|
||||
# IDA's exporter sets `source` to IMPORTED for a FLIRT-identified
|
||||
# library function, which is the same claim Ghidra's FidDb makes
|
||||
# through the symbol table. Ghidra's function export has no such
|
||||
# field, so it keeps the old behaviour.
|
||||
consider(addr, f.get("name"), "Function",
|
||||
f.get("namespace", ""), "ANALYSIS"
|
||||
if not f.get("is_thunk") else "ANALYSIS")
|
||||
f.get("namespace", ""), f.get("source") or "ANALYSIS")
|
||||
|
||||
# Then symbols (covers labels promoted to data/functions, RTTI, demangled).
|
||||
if syms:
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
"""merge_names must drop IDA's autonames as thoroughly as it drops Ghidra's.
|
||||
|
||||
An export that merges `loc_1A2B3C` onto a function is worse than no export:
|
||||
the recompiler happily emits `void loc_1A2B3C(void)` and the name reads as
|
||||
recovered ground truth when it is the address in disguise.
|
||||
"""
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
import tempfile
|
||||
|
||||
# No package __init__ here (the Ghidra scripts are Jython and must not be
|
||||
# importable as one), so load the module by path the way its own runner does.
|
||||
_spec = importlib.util.spec_from_file_location(
|
||||
"merge_names", os.path.join(os.path.dirname(os.path.abspath(__file__)),
|
||||
"merge_names.py"))
|
||||
merge_names = importlib.util.module_from_spec(_spec)
|
||||
_spec.loader.exec_module(merge_names)
|
||||
|
||||
|
||||
def test_placeholders_dropped():
|
||||
for name in ("FUN_00014c20", "LAB_00014c20", "DAT_00014c20",
|
||||
"loc_1A2B3C", "sub_1A2B3C", "nullsub_7", "jpt_401000",
|
||||
"algn_401000", "asc_4A1B00", "stru_4A1B00", "unk_4A1B00",
|
||||
"off_4A1B00", "flt_4A1B00", "dbl_4A1B00", "xmmword_4A1B00",
|
||||
"s_Hello_00abc123", "0x401000", "12345", ""):
|
||||
assert merge_names.is_placeholder(name), name
|
||||
|
||||
|
||||
def test_real_names_kept():
|
||||
for name in ("CPlayer__Think", "D3DDevice_SetTexture", "memcpy",
|
||||
"Locate", "LoadTexture", "j_memcpy_real"):
|
||||
assert not merge_names.is_placeholder(name), name
|
||||
|
||||
|
||||
def test_flirt_library_outranks_a_plain_symbol():
|
||||
# IDA marks FLIRT hits IMPORTED; that must win over the same address
|
||||
# carrying a duller name from the symbol table, the way Ghidra's FidDb does.
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
with open(os.path.join(d, "functions.json"), "w") as f:
|
||||
json.dump([{"address": "0x00014C20", "name": "strlen",
|
||||
"is_thunk": False, "source": "IMPORTED"}], f)
|
||||
with open(os.path.join(d, "symbols.json"), "w") as f:
|
||||
json.dump([{"address": "0x00014C20", "name": "j_strlen_wrapper",
|
||||
"type": "Label", "source": "ANALYSIS",
|
||||
"primary": True}], f)
|
||||
final, buckets, _ = merge_names.build_map(d)
|
||||
# strlen is a reserved identifier, so it carries its address -- that is
|
||||
# the collision rule doing its job, not a placeholder being dropped.
|
||||
assert final["0x00014C20"] == "strlen_00014C20"
|
||||
assert buckets == {"fidb/library": 1}
|
||||
|
||||
|
||||
def test_ida_autonames_leave_nothing_behind():
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
with open(os.path.join(d, "functions.json"), "w") as f:
|
||||
json.dump([{"address": "0x%08X" % ea, "name": nm, "is_thunk": False}
|
||||
for ea, nm in ((0x14C20, "sub_14C20"),
|
||||
(0x14C40, "loc_14C40"),
|
||||
(0x14C60, "CSound__Play"))], f)
|
||||
final, _, _ = merge_names.build_map(d)
|
||||
# Doubled underscores collapse -- sanitize's job, not the filter's.
|
||||
assert final == {"0x00014C60": "CSound_Play"}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
for fn in (test_placeholders_dropped, test_real_names_kept,
|
||||
test_flirt_library_outranks_a_plain_symbol,
|
||||
test_ida_autonames_leave_nothing_behind):
|
||||
fn()
|
||||
print("ok ", fn.__name__)
|
||||
@@ -0,0 +1,77 @@
|
||||
# IDA Naming Path (Xbox XBE)
|
||||
|
||||
The same job as `tools/ghidra_naming/`, through IDA instead: recover real
|
||||
function and symbol names from an XBE and turn them into the
|
||||
`{address: name}` map the static recompiler consumes.
|
||||
|
||||
Only the *export* differs. The merge, the placeholder filter, the C-identifier
|
||||
sanitising, the collision handling and `--apply` are
|
||||
`tools/ghidra_naming/merge_names.py`, which reads the same two JSON files
|
||||
whichever tool wrote them.
|
||||
|
||||
```
|
||||
tools/ida_naming/
|
||||
export_xbe_names.py # runs inside IDA; writes functions.json + symbols.json
|
||||
export/ # generated
|
||||
```
|
||||
|
||||
## Why you might want this rather than Ghidra
|
||||
|
||||
IDA's FLIRT signature library and Ghidra's FidDb are the same idea with
|
||||
different coverage, and neither is a superset. A CRT or SDK version one of them
|
||||
recognises and the other does not is the normal case, not the exception, so
|
||||
running both and taking the union names more functions than either alone — the
|
||||
same result `symbols/map_names` measures for donor MAP files (735 named from
|
||||
two donors versus 504 from the best single one).
|
||||
|
||||
If you only have one of the two installed, use that one. This exists so having
|
||||
IDA is not a reason to be stuck.
|
||||
|
||||
## Loading the XBE
|
||||
|
||||
IDA ships no XBE loader either. Reuse the flat image the Ghidra path already
|
||||
builds — it is a plain binary with nothing Ghidra-specific in it:
|
||||
|
||||
```
|
||||
py -3 tools/ghidra_naming/extract_for_ghidra.py /path/to/default.xbe \
|
||||
--out-dir tools/ghidra_naming/work
|
||||
```
|
||||
|
||||
Load `work/xbe_flat.bin` in IDA as **Binary file**, processor `metapc`,
|
||||
32-bit, **loading offset `0x10000`**. Because the flat image starts at the XBE
|
||||
base, IDA's addresses equal the recompiler's `functions.json` `start` values
|
||||
exactly, which is the only property that matters when the names merge back.
|
||||
|
||||
The exporter checks this and refuses to write at the wrong base. It has to:
|
||||
names at the wrong base merge onto nothing, and the failure is silent — a
|
||||
healthy-looking export count followed by "0 addresses matching".
|
||||
|
||||
## Exporting
|
||||
|
||||
From the GUI, **File > Script file...** and pick `export_xbe_names.py`, or
|
||||
headless:
|
||||
|
||||
```
|
||||
ida -A -S"tools/ida_naming/export_xbe_names.py tools/ida_naming/export --exit" \
|
||||
xbe_flat.i64
|
||||
```
|
||||
|
||||
Wait for auto-analysis to finish first (the script calls `auto_wait()`, but a
|
||||
7.6 MB image takes a while either way).
|
||||
|
||||
## Merging
|
||||
|
||||
```
|
||||
py -3 tools/ghidra_naming/merge_names.py \
|
||||
--export-dir tools/ida_naming/export \
|
||||
--out tools/ida_naming/ida_names.json
|
||||
```
|
||||
|
||||
Add `--apply` to write the names into `tools/disasm/output/functions.json` in
|
||||
place (a `.bak` is written first). Regenerate afterwards and the emitted C uses
|
||||
them.
|
||||
|
||||
To take the union of an IDA run and a Ghidra run, `--apply` both, one after
|
||||
the other. `--apply` only sets names on entries whose address matches, so the
|
||||
second pass fills in what the first left as `sub_`; whichever you run last wins
|
||||
where they disagree. The bucket counts in each report say which tool found what.
|
||||
@@ -0,0 +1,149 @@
|
||||
"""Export an Xbox XBE's recovered names from IDA, in the shape merge_names reads.
|
||||
|
||||
xboxrecomp already had a Ghidra path and no IDA one. The gap was never the
|
||||
analysis -- IDA's FLIRT and demangler recover the same kind of names Ghidra's
|
||||
FidDb and RTTI analyzers do -- it was that nothing wrote them out in the shape
|
||||
``tools/ghidra_naming/merge_names.py`` consumes. So this is that, and nothing
|
||||
else: the merge, the placeholder filter, the C-identifier sanitising, the
|
||||
collision handling and ``--apply`` are all the existing tool's job.
|
||||
|
||||
Writes two files into an output directory:
|
||||
|
||||
functions.json [{address, name, signature, calling_convention,
|
||||
param_count, is_thunk, namespace}, ...]
|
||||
symbols.json [{address, name, type, namespace, source, primary}, ...]
|
||||
|
||||
then:
|
||||
|
||||
py -3 tools/ghidra_naming/merge_names.py \
|
||||
--export-dir tools/ida_naming/export \
|
||||
--out tools/ida_naming/ida_names.json
|
||||
|
||||
Addresses are absolute Xbox VAs, which is what ``functions.json`` keys on. That
|
||||
only holds if the database is based where the XBE is: load the flat image from
|
||||
``tools/ghidra_naming/extract_for_ghidra.py`` (it is a plain binary, nothing in
|
||||
it is Ghidra-specific) as x86 32-bit at 0x00010000, or use a loader that does
|
||||
the same. The script refuses to guess and says so if the base looks wrong.
|
||||
|
||||
Run it against an open database, from the GUI (File > Script file...) or
|
||||
headless:
|
||||
|
||||
ida -A -S"tools/ida_naming/export_xbe_names.py <outdir> --exit" xbe_flat.idb
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
|
||||
import ida_auto
|
||||
import ida_bytes
|
||||
import ida_funcs
|
||||
import ida_nalt
|
||||
import ida_name
|
||||
import ida_typeinf
|
||||
import idautils
|
||||
import idc
|
||||
|
||||
XBE_BASE = 0x00010000
|
||||
|
||||
_HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
DEFAULT_OUT = os.path.join(_HERE, "export")
|
||||
|
||||
|
||||
def _hexaddr(ea):
|
||||
return "0x%08X" % ea
|
||||
|
||||
|
||||
def _signature(ea):
|
||||
"""IDA's prototype for the function, or '' when it has none."""
|
||||
try:
|
||||
tif = ida_typeinf.tinfo_t()
|
||||
if ida_nalt.get_tinfo(tif, ea):
|
||||
return str(tif)
|
||||
except Exception:
|
||||
pass
|
||||
return idc.get_type(ea) or ""
|
||||
|
||||
|
||||
def export_functions(out_dir):
|
||||
out = []
|
||||
for ea in idautils.Functions():
|
||||
f = ida_funcs.get_func(ea)
|
||||
if not f or f.start_ea != ea:
|
||||
continue
|
||||
# FUNC_LIB is FLIRT: the CRT and SDK routines IDA recognised by
|
||||
# signature. That is the same claim Ghidra's FidDb makes, and
|
||||
# merge_names ranks it above every other bucket, so say so.
|
||||
source = "IMPORTED" if (f.flags & ida_funcs.FUNC_LIB) else "ANALYSIS"
|
||||
out.append({
|
||||
"address": _hexaddr(ea),
|
||||
"name": ida_name.get_name(ea) or "",
|
||||
"signature": _signature(ea),
|
||||
"calling_convention": "",
|
||||
"param_count": -1,
|
||||
"is_thunk": bool(f.flags & ida_funcs.FUNC_THUNK),
|
||||
"namespace": "",
|
||||
"source": source,
|
||||
})
|
||||
path = os.path.join(out_dir, "functions.json")
|
||||
with open(path, "w") as fh:
|
||||
json.dump(out, fh, indent=1)
|
||||
print("Exported %d functions -> %s" % (len(out), path))
|
||||
return len(out)
|
||||
|
||||
|
||||
def export_symbols(out_dir):
|
||||
out = []
|
||||
for ea, name in idautils.Names():
|
||||
f = ida_funcs.get_func(ea)
|
||||
is_func = bool(f) and f.start_ea == ea
|
||||
flags = ida_bytes.get_flags(ea)
|
||||
out.append({
|
||||
"address": _hexaddr(ea),
|
||||
"name": name,
|
||||
"type": "Function" if is_func else "Label",
|
||||
"namespace": "",
|
||||
# A name the analyst typed beats one IDA invented, and merge_names
|
||||
# only reads this to bucket the result for the report.
|
||||
"source": ("USER_DEFINED" if ida_bytes.has_user_name(flags)
|
||||
else "ANALYSIS"),
|
||||
"primary": True,
|
||||
})
|
||||
path = os.path.join(out_dir, "symbols.json")
|
||||
with open(path, "w") as fh:
|
||||
json.dump(out, fh, indent=1)
|
||||
print("Exported %d symbols -> %s" % (len(out), path))
|
||||
return len(out)
|
||||
|
||||
|
||||
def main():
|
||||
argv = idc.ARGV[1:] if len(idc.ARGV) > 1 else []
|
||||
argv = [a for a in argv if a != "--exit"]
|
||||
out_dir = argv[0] if argv else DEFAULT_OUT
|
||||
|
||||
ida_auto.auto_wait()
|
||||
|
||||
base = ida_nalt.get_imagebase()
|
||||
if base != XBE_BASE:
|
||||
# Worth stopping for. Names at the wrong base merge onto nothing, and
|
||||
# the failure is silent: merge_names reports a healthy count and
|
||||
# "0 addresses matching functions.json".
|
||||
print("ERROR: image base is 0x%08X, expected 0x%08X." % (base, XBE_BASE))
|
||||
print(" Rebase the database (Edit > Segments > Rebase program),")
|
||||
print(" or load the flat image at 0x%08X." % XBE_BASE)
|
||||
return 1
|
||||
|
||||
if not os.path.isdir(out_dir):
|
||||
os.makedirs(out_dir)
|
||||
export_functions(out_dir)
|
||||
export_symbols(out_dir)
|
||||
print("Now run: py -3 tools/ghidra_naming/merge_names.py --export-dir %s"
|
||||
% out_dir)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
rc = main()
|
||||
# Headless runs have to close IDA themselves; a GUI run must not. Asking
|
||||
# is one word and beats guessing from the command line IDA was started
|
||||
# with, which differs between versions.
|
||||
if "--exit" in idc.ARGV:
|
||||
idc.qexit(rc)
|
||||
Reference in New Issue
Block a user