Files
sp00nz e54233e752 tools.split: one byte-exact .s per function, for decompilation
Asked for by someone using the recomp as a function splitter for a decomp,
which the toolkit was already most of the way to without saying so anywhere.
The analysis half -- boundaries, call graph, calling conventions, frame shapes,
recovered names -- is the same whether you go on to recompile or not, and
tools/recomp was simply the only consumer of it.

Each function gets a file: a header with its address range, size, section,
detection method and confidence, its signature from tools.abi_analysis, and its
callers; then the body, with branch targets inside the function labelled and
callees named.

The bytes are `db` and the disassembly is a comment beside them, which is the
opposite of what an N64 decomp does and deliberately so. MIPS round-trips
through an assembler because the encoding is fixed-width and unambiguous. x86
does not -- `mov eax, ecx` has two encodings, immediates have short forms, and
which one MSVC picked cannot be recovered from the mnemonic. Reassembling a
listing gives code that runs identically and does not match, and matching is
the only oracle a decomp has. Emitting the original bytes as data makes the
file byte-exact by construction and still leaves the disassembly to read.

Verified rather than asserted, and the verification found two real bugs:

  - reconstructing bytes from the instruction stream produced files longer than
    the function, because a decoded instruction can start inside a function and
    run past its end wherever data was decoded as code. 102 of 2,254 functions,
    silently. Bytes now come from the image and coverage is exact by
    construction.
  - filling only the trailing gap left three functions short, because MSVC
    parks switch tables in the middle of a function body and the disassembler
    correctly marks those as data. memcpy has two. Gaps are filled wherever
    they occur and come out as labelled data runs in place.

Xbox Dashboard .text: 2,254 of 2,254 functions byte-identical to the shipped
binary.

docs/DECOMP.md is the guide, separate from GETTING_STARTED because it is a
different job with a different endpoint -- and it is honest about what is not
solved: no object-file grouping, code only, inferred boundaries that are wrong
in data-heavy regions, and byte-identical is not build-identical.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013pS5pcx2cx9JXyKurjok17
2026-09-02 23:50:15 -07:00

112 lines
3.8 KiB
Python

"""Self-check for the function splitter.
Run: py -3 -m pytest tools/split/test_split.py
The one property that matters: the bytes that go into a .s come back out of it
unchanged. Everything else in the file is a comment for a human, but if the db
directives drift from the original encoding then a decomp built on them stops
matching the shipped binary and the whole point is gone.
"""
import os
import re
import tempfile
from .splitter import _split_hex, write_function
class _Insn:
def __init__(self, address, bytes_hex, mnemonic="nop", op_str="",
call_target=None, jump_target=None):
self.address = address
self.bytes_hex = bytes_hex
self.size = len(bytes_hex) // 2
self.mnemonic = mnemonic
self.op_str = op_str
self.call_target = call_target
self.jump_target = jump_target
class _Func:
def __init__(self, start, end, name="sub_00001000"):
self.start = start
self.end = end
self.name = name
self.section = ".text"
self.confidence = 0.9
self.detection_method = "prologue"
self.num_instructions = 0
self.called_by = []
self.calls_to = []
@property
def size(self):
return self.end - self.start
def _emitted_bytes(path):
"""Every byte the .s actually assembles to, in order."""
out = []
for line in open(path, encoding="utf-8"):
line = line.split(";", 1)[0] # strip the disassembly comment
m = re.match(r"\s*db\s+(.*)", line)
if not m:
continue
for tok in m.group(1).split(","):
tok = tok.strip()
if tok:
out.append(int(tok, 16))
return bytes(out)
def test_unbroken_hex_is_split_per_byte():
# bytes_hex arrives as one string, not whitespace-separated. Splitting on
# whitespace produced a single huge literal per instruction and every
# emitted file was wrong while looking plausible.
assert _split_hex("558bec") == ["55", "8b", "ec"]
assert _split_hex("c3") == ["c3"]
assert _split_hex("") == []
def test_emitted_bytes_match_the_original_encoding():
insns = [
_Insn(0x1000, "55", "push", "ebp"),
_Insn(0x1001, "8bec", "mov", "ebp, esp"),
_Insn(0x1003, "e857feffff", "call", "0xf5f", call_target=0xF5F),
# Longer than one db line, so the continuation path is covered too.
_Insn(0x1008, "0f1f840000000000660f1f440000", "nop", "word ptr [eax]"),
_Insn(0x1016, "c3", "ret", ""),
]
func = _Func(0x1000, 0x1017)
func.num_instructions = len(insns)
expect = bytes.fromhex("".join(i.bytes_hex for i in insns))
with tempfile.TemporaryDirectory() as tmp:
path = os.path.join(tmp, "f.s")
write_function(path, func, insns, None, lambda a: "sub_%08X" % a)
assert _emitted_bytes(path) == expect
text = open(path, encoding="utf-8").read()
# The callee is named, because "call 0xf5f" is not a lead to follow.
assert "sub_00000F5F" in text
# And the function is labelled so it can be referenced.
assert "sub_00001000:" in text
def test_branch_targets_inside_the_function_become_labels():
insns = [
_Insn(0x2000, "eb02", "jmp", "0x2004", jump_target=0x2004),
_Insn(0x2002, "6690", "xchg", "ax, ax"),
_Insn(0x2004, "c3", "ret", ""),
]
func = _Func(0x2000, 0x2005, name="sub_00002000")
func.num_instructions = len(insns)
with tempfile.TemporaryDirectory() as tmp:
path = os.path.join(tmp, "f.s")
write_function(path, func, insns, None, lambda a: "sub_%08X" % a)
text = open(path, encoding="utf-8").read()
assert ".L_00002004:" in text
# Still byte-exact with a label in the middle.
assert _emitted_bytes(path) == bytes.fromhex("eb0266 90c3".replace(" ", ""))