mirror of
https://github.com/sp00nznet/xboxrecomp.git
synced 2026-12-06 02:22:30 +00:00
7071e907ea
func_id classified functions by which XDK library section they call, but
the section VAs came from config.XDK_SECTIONS -- a table of Burnout 3's
addresses, with no way for a caller to supply the real ones. The toolkit
grew out of Burnout 3, so this was right for exactly one title and
silently wrong for every other.
On Half-Life 2 all eight hardcoded ranges land inside .text. That
mislabelled 4,498 functions, including 2,697 as "game_audio" and 884 as
"game_video" in a title that has no video section at all. Worse, those
labels ran before vtable scanning, which only classifies functions not
already labelled -- so the bogus labels were also *stealing* functions
from a pass that would have got them right.
identify.py already parsed the real section table for "game-agnostic
vtable scanning"; it just did so after propagation. Parsing it once, up
front, and passing it through fixes both. config now carries only a
section NAME -> category map, which is the part that actually generalises.
Half-Life 2, before -> after:
xdk_caller 4,498 -> 730 (and now from HL2's own addresses)
vtable_scan 13,792 -> 15,397
vtable_ctor 1,584 -> 2,185
Verified no regression on Burnout 3: every previously-hardcoded range is
reproduced exactly by the derived table, so its classification is
unchanged (it also gains DOLBY -> game_audio, which the old table
omitted). With no section table the pass now classifies nothing rather
than guessing.
Also: generated C banners said "Burnout 3: Takedown" for every title.
They now read the name from the XBE certificate -- "Half Life 2 - Retail
Build", "Crimson Skies", "Wreckless - The Yakuza Missions" -- falling
back to the filename, since a cosmetic banner must never fail a build.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BuW5WGcXFFrLAYEfvCNGs1
316 lines
11 KiB
Python
316 lines
11 KiB
Python
"""
|
|
Main orchestrator for function identification.
|
|
|
|
Loads all input data, runs identification phases in order,
|
|
and produces enriched output.
|
|
"""
|
|
|
|
import json
|
|
import os
|
|
import time
|
|
from collections import defaultdict
|
|
|
|
from . import config
|
|
from .imm_scanner import scan_immediate_refs
|
|
from .rw_identifier import identify_rw_functions
|
|
from .crt_identifier import identify_crt_functions
|
|
from .stub_classifier import classify_stubs
|
|
from .vtable_scanner import scan_vtables
|
|
from .clustering import propagate_labels
|
|
from .output import write_results
|
|
|
|
|
|
def run(xbe_path, functions_path=None, strings_path=None, xrefs_path=None,
|
|
output_dir=None, verbose=False):
|
|
"""
|
|
Run the full function identification pipeline.
|
|
|
|
Args:
|
|
xbe_path: Path to the XBE file.
|
|
functions_path: Path to functions.json (or default).
|
|
strings_path: Path to strings.json (or default).
|
|
xrefs_path: Path to xrefs.json (or default).
|
|
output_dir: Output directory (or default).
|
|
verbose: Print progress info.
|
|
|
|
Returns:
|
|
dict: Summary statistics.
|
|
"""
|
|
functions_path = functions_path or config.DEFAULT_FUNCTIONS_JSON
|
|
strings_path = strings_path or config.DEFAULT_STRINGS_JSON
|
|
xrefs_path = xrefs_path or config.DEFAULT_XREFS_JSON
|
|
output_dir = output_dir or config.DEFAULT_OUTPUT_DIR
|
|
|
|
t_start = time.time()
|
|
|
|
# ── Phase 0: Load inputs ──────────────────────────────────
|
|
if verbose:
|
|
print("Phase 0: Loading inputs...")
|
|
|
|
xbe_data = _load_binary(xbe_path)
|
|
functions = _load_json(functions_path)
|
|
strings = _load_json(strings_path)
|
|
xrefs = _load_json(xrefs_path)
|
|
|
|
if verbose:
|
|
print(f" XBE: {len(xbe_data):,} bytes")
|
|
print(f" Functions: {len(functions):,}")
|
|
print(f" Strings: {len(strings):,}")
|
|
print(f" Xrefs: {len(xrefs):,}")
|
|
|
|
# ── Phase 1: Immediate operand scan + xref merge ─────────
|
|
if verbose:
|
|
print("\nPhase 1: Scanning immediate operands + merging xrefs...")
|
|
t1 = time.time()
|
|
imm_refs = scan_immediate_refs(xbe_data, functions, verbose=verbose)
|
|
|
|
# Merge data_read xrefs that target .rdata/.data into imm_refs
|
|
xref_merge_count = _merge_xref_data_reads(xrefs, functions, imm_refs, verbose)
|
|
|
|
if verbose:
|
|
print(f" Merged {xref_merge_count:,} data_read xrefs")
|
|
print(f" Total unique data addresses after merge: {len(imm_refs):,}")
|
|
print(f" Done in {time.time() - t1:.1f}s")
|
|
|
|
# ── Phase 2: RenderWare identification ────────────────────
|
|
if verbose:
|
|
print("\nPhase 2: RenderWare identification...")
|
|
t2 = time.time()
|
|
rw_results, rw_modules = identify_rw_functions(
|
|
strings, imm_refs, functions, verbose=verbose
|
|
)
|
|
if verbose:
|
|
print(f" Done in {time.time() - t2:.1f}s")
|
|
|
|
# ── Phase 3: CRT identification ──────────────────────────
|
|
if verbose:
|
|
print("\nPhase 3: CRT identification...")
|
|
t3 = time.time()
|
|
crt_results = identify_crt_functions(xbe_data, functions, verbose=verbose)
|
|
if verbose:
|
|
print(f" Done in {time.time() - t3:.1f}s")
|
|
|
|
# Remove any CRT matches that overlap with RW (RW wins)
|
|
for addr in list(crt_results.keys()):
|
|
if addr in rw_results:
|
|
del crt_results[addr]
|
|
|
|
# ── Phase 3b: Stub classification ────────────────────────
|
|
if verbose:
|
|
print("\nPhase 3b: Stub classification...")
|
|
t3b = time.time()
|
|
stub_results = classify_stubs(xbe_data, functions, verbose=verbose)
|
|
if verbose:
|
|
print(f" Done in {time.time() - t3b:.1f}s")
|
|
|
|
# Remove stubs that overlap with RW or CRT
|
|
for addr in list(stub_results.keys()):
|
|
if addr in rw_results or addr in crt_results:
|
|
del stub_results[addr]
|
|
|
|
# Section table from the XBE itself. Both label propagation and vtable
|
|
# scanning need it, and neither may use a hardcoded one -- see
|
|
# config.XDK_SECTION_CATEGORIES.
|
|
xbe_sections = _parse_xbe_sections(xbe_data)
|
|
|
|
# ── Phase 4: Label propagation ───────────────────────────
|
|
if verbose:
|
|
print("\nPhase 4: Label propagation...")
|
|
t4 = time.time()
|
|
propagated = propagate_labels(
|
|
functions, rw_results, crt_results, imm_refs, strings,
|
|
verbose=verbose, sections=xbe_sections
|
|
)
|
|
if verbose:
|
|
print(f" Done in {time.time() - t4:.1f}s")
|
|
|
|
# ── Phase 5: Vtable scanning ──────────────────────────────
|
|
if verbose:
|
|
print("\nPhase 5: Vtable scanning...")
|
|
t5 = time.time()
|
|
|
|
if verbose and xbe_sections:
|
|
code_count = sum(1 for s in xbe_sections if s.get("executable"))
|
|
data_count = len(xbe_sections) - code_count
|
|
print(f" XBE sections: {len(xbe_sections)} ({code_count} code, {data_count} data)")
|
|
|
|
vtable_results, vtables = scan_vtables(
|
|
xbe_data, functions, imm_refs, verbose=verbose,
|
|
sections=xbe_sections if xbe_sections else None
|
|
)
|
|
# Only classify functions not already labeled by earlier phases
|
|
already_labeled = set(rw_results) | set(crt_results) | set(propagated) | set(stub_results)
|
|
vtable_new = {a: v for a, v in vtable_results.items() if a not in already_labeled}
|
|
if verbose:
|
|
print(f" New classifications from vtable: {len(vtable_new)}")
|
|
print(f" Done in {time.time() - t5:.1f}s")
|
|
|
|
# Merge vtable results into propagated for output
|
|
propagated.update(vtable_new)
|
|
|
|
# Add discovered vtable thunks as new function entries
|
|
func_starts = {int(f["start"], 16) for f in functions}
|
|
thunk_count = 0
|
|
for addr, info in vtable_results.items():
|
|
if addr not in func_starts and info.get("method") == "vtable_thunk":
|
|
est_size = 32 # estimate; refined later if re-disassembled
|
|
functions.append({
|
|
"start": f"0x{addr:08X}",
|
|
"end": f"0x{addr + est_size:08X}",
|
|
"size": est_size,
|
|
"name": f"sub_{addr:08X}",
|
|
"section": ".text",
|
|
"insn_count": 8,
|
|
"type": "vtable_thunk",
|
|
"vtable_addr": f"0x{info.get('vtable_addr', 0):08X}",
|
|
"vtable_index": info.get("vtable_index", -1),
|
|
})
|
|
thunk_count += 1
|
|
if verbose and thunk_count:
|
|
print(f" Added {thunk_count} vtable thunks to function list")
|
|
|
|
# ── Phase 6: Write output ────────────────────────────────
|
|
if verbose:
|
|
print("\nPhase 6: Writing output...")
|
|
|
|
summary = write_results(
|
|
functions, rw_results, crt_results, propagated, rw_modules,
|
|
output_dir, verbose=verbose, stub_results=stub_results
|
|
)
|
|
|
|
if verbose:
|
|
print(f"\nTotal time: {time.time() - t_start:.1f}s")
|
|
print(f"Output written to: {output_dir}/")
|
|
|
|
return summary
|
|
|
|
|
|
def _merge_xref_data_reads(xrefs, functions, imm_refs, verbose):
|
|
"""
|
|
Merge data_read xrefs into the imm_refs map.
|
|
|
|
The xref database has 77K+ data_read entries (from mov [addr] style
|
|
instructions) that the imm_scanner misses. Merging these gives a
|
|
much more complete picture of data references.
|
|
|
|
Returns the count of new entries added.
|
|
"""
|
|
# Build sorted function start list for binary search
|
|
func_starts = sorted(int(f["start"], 16) for f in functions)
|
|
|
|
rdata_lo = config.RDATA_VA_START
|
|
rdata_hi = config.RDATA_VA_END
|
|
data_lo = config.DATA_VA_START
|
|
data_hi = config.DATA_VA_END
|
|
|
|
count = 0
|
|
for xref in xrefs:
|
|
if xref["type"] != "data_read":
|
|
continue
|
|
|
|
target = int(xref["to"], 16)
|
|
if not ((rdata_lo <= target < rdata_hi) or (data_lo <= target < data_hi)):
|
|
continue
|
|
|
|
source = int(xref["from"], 16)
|
|
|
|
# Find containing function
|
|
lo, hi = 0, len(func_starts) - 1
|
|
while lo <= hi:
|
|
mid = (lo + hi) // 2
|
|
if func_starts[mid] <= source:
|
|
lo = mid + 1
|
|
else:
|
|
hi = mid - 1
|
|
func_addr = func_starts[hi] if hi >= 0 else None
|
|
|
|
if func_addr is not None:
|
|
if target not in imm_refs:
|
|
imm_refs[target] = []
|
|
count += 1
|
|
if func_addr not in imm_refs[target]:
|
|
imm_refs[target].append(func_addr)
|
|
|
|
return count
|
|
|
|
|
|
def _parse_xbe_sections(xbe_data):
|
|
"""
|
|
Parse section info directly from XBE headers.
|
|
|
|
Returns list of dicts: {name, va, size, raw, executable}
|
|
Returns None if parsing fails (falls back to config).
|
|
"""
|
|
import struct
|
|
|
|
if len(xbe_data) < 0x180:
|
|
return None
|
|
|
|
# XBE header magic check
|
|
if xbe_data[:4] != b'XBEH':
|
|
return None
|
|
|
|
try:
|
|
# Section headers offset and count
|
|
sec_headers_offset = struct.unpack_from('<I', xbe_data, 0x120)[0]
|
|
num_sections = struct.unpack_from('<I', xbe_data, 0x11C)[0]
|
|
|
|
# XBE base address
|
|
base_addr = struct.unpack_from('<I', xbe_data, 0x104)[0]
|
|
|
|
# Adjust section headers offset to be relative to file start
|
|
sec_offset = sec_headers_offset - base_addr
|
|
|
|
sections = []
|
|
for i in range(num_sections):
|
|
off = sec_offset + i * 56 # Each section header is 56 bytes
|
|
if off + 56 > len(xbe_data):
|
|
break
|
|
|
|
flags = struct.unpack_from('<I', xbe_data, off + 0)[0]
|
|
va = struct.unpack_from('<I', xbe_data, off + 4)[0]
|
|
vsize = struct.unpack_from('<I', xbe_data, off + 8)[0]
|
|
raw_addr = struct.unpack_from('<I', xbe_data, off + 12)[0]
|
|
raw_size = struct.unpack_from('<I', xbe_data, off + 16)[0]
|
|
name_addr = struct.unpack_from('<I', xbe_data, off + 20)[0]
|
|
|
|
# Read section name
|
|
name_off = name_addr - base_addr
|
|
if 0 <= name_off < len(xbe_data) - 16:
|
|
name_end = xbe_data.index(b'\0', name_off) if b'\0' in xbe_data[name_off:name_off+32] else name_off+8
|
|
name = xbe_data[name_off:name_end].decode('ascii', errors='replace')
|
|
else:
|
|
name = f"sec_{i}"
|
|
|
|
executable = bool(flags & 0x4) # Section flag for executable
|
|
|
|
sections.append({
|
|
"name": name,
|
|
"va": va,
|
|
"size": vsize,
|
|
"raw": raw_addr,
|
|
"raw_size": raw_size,
|
|
"executable": executable,
|
|
})
|
|
|
|
return sections if sections else None
|
|
|
|
except Exception:
|
|
return None
|
|
|
|
|
|
def _load_binary(path):
|
|
"""Load a binary file."""
|
|
if not os.path.exists(path):
|
|
raise FileNotFoundError(f"XBE file not found: {path}")
|
|
with open(path, "rb") as f:
|
|
return f.read()
|
|
|
|
|
|
def _load_json(path):
|
|
"""Load a JSON file."""
|
|
if not os.path.exists(path):
|
|
raise FileNotFoundError(f"JSON file not found: {path}")
|
|
with open(path, "r", encoding="utf-8") as f:
|
|
return json.load(f)
|