Files
xboxrecomp/tools/disasm/test_decode_at.py
sp00nz 0a8097e9e4 v0.7.0 "Non-Local": unwind across recompiled frames, fs: segment, kernel gaps
Control flow that leaves a function without returning from it, and the three
places the toolkit got it wrong.

Non-local jumps. A recompiled function is a real C function, so restoring the
guest esp is only half of a longjmp: the abandoned frames stay on the native
stack and control returns into them once the resume point finishes. Each guest
jmp_buf is now paired with a native one taken at the setjmp call site, the only
place a native setjmp is valid, so the frames actually unwind. The CRT's pair is
detected by the "VC20" cookie MSVC stamps into every jmp_buf.

Frameless callees inherited a dead frame: ebp is read through g_seh_ebp, but
only tail jumps and the SEH helpers ever wrote it, so one reached by an ordinary
call got whatever the last tail jump left behind. Published wherever g_ebp is.

The fs: segment prefix was dropped, putting the TIB at guest address 0 - where a
null pointer also lands. A null check written as "cmp byte [ecx], 0" read the
exception chain head's 0xFF and passed; a null store overwrote that head instead
of faulting. Segment overrides are recorded and based at XBOX_FS_BASE, leaving
page zero free for RECOMP_TRAP_NULL to trap.

Kernel exports implemented but never dispatched: RtlUnwind, XeLoadSection,
XeUnloadSection, NtSuspendThread. Each returned success without acting, which is
worse than a stub. NtSuspendThread was the costly one - a worker that parked
itself never stopped, spinning 289M kernel calls; now 9,789.

MCPX APU never started: the frame thread idles on pause_requested, which init
sets and only the test tone ever cleared, so a title enabling the APU through
SECTL/FECTL got an APU that stayed asleep.

cvtps2pi / cvttps2pi implemented; 36 sat inside one title's WMV decoder as
no-op comments.

New xbox_video library: Media Foundation FMV decode onto a D3D8 texture, plus a
window on the guest framebuffer. Orientation comes from IMF2DBuffer's pitch
sign rather than the RGB32 convention, which had the video upside down.

Diagnostics, since a recompiled title offers no debugger: tools/stackwalk.py
guest backtraces, RECOMP_WATCHDOG_SECS, RECOMP_TRACE_ARGS/DEREF, RECOMP_PEEK
and PEEK_CHAIN, RECOMP_WATCH_VA, RECOMP_PB_SCAN/PB_EXEC, RECOMP_FB_WINDOW.

Fixed: duplicate trace symbols broke the link for any title defining its own
recomp_trace_*; they now live once in the kernel.

Verified: 4639 + 211 conformance vectors 0 mismatches, 146 tests, Halo builds.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PZDe6qTWAvohfDtYXbpRyM
2026-08-31 09:36:29 -07:00

163 lines
5.9 KiB
Python

"""
Self-check for Engine.decode_at (sweep realignment).
Run: py -3 tools/disasm/test_decode_at.py
linear_sweep decodes each section as a single stream and resyncs only by
skipping one byte when capstone fails. Where it runs through data -- a jump
table, padding, an embedded constant -- it emerges misaligned and stays out of
phase until it happens to fall back into step. Everything downstream keys off
engine.instructions, so an address the sweep stepped over does not exist:
recursive_descent stops dead there because it only reads that dict, and
_pass_call_targets silently dropped the candidate.
On Halo 2276 that discarded 46 direct call targets -- provable function starts,
one of them 16-aligned in a 5.7 KB hole and named in its own caller's call list.
31 of the 46 come back with this.
"""
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", ".."))
from tools.disasm.engine import DisasmEngine # noqa: E402
class _Section:
def __init__(self, va, data, executable=True):
self.virtual_addr = va
self.virtual_size = len(data)
self.executable = executable
self.name = ".text"
class _Image:
"""Minimal duck-typed BinaryImage."""
def __init__(self, *sections):
self._secs = sections
self.base_address = min(s.virtual_addr for s in sections)
self.image_size = max(s.virtual_addr + s.virtual_size
for s in sections) - self.base_address
def get_section_at_va(self, va):
for s in self._secs:
if s.virtual_addr <= va < s.virtual_addr + s.virtual_size:
return s
return None
def get_section_data(self, section):
return section.data
def _engine(va, data, executable=True):
s = _Section(va, data, executable)
s.data = data
img = _Image(s)
return DisasmEngine(img), s
BASE = 0x00010000
def test_decode_at_reaches_an_address_the_sweep_stepped_over():
# 0x10000: 90 nop
# 0x10001: b9 78 56 34 12 mov ecx, 0x12345678 <- swallows 0x10002..5
# 0x10006: 33 c0 xor eax, eax <- the real target
# 0x10008: c3 ret
data = b"\x90\xb9\x78\x56\x34\x12\x33\xc0\xc3"
eng, _ = _engine(BASE, data)
# Simulate a sweep that went out of phase: pretend it only landed on 0x10001.
eng.decode_at(BASE + 1)
assert (BASE + 6) in eng.instructions, "resync should have covered 0x10006"
# Now the misalignment case: nothing decoded at all, ask for 0x10006 directly.
eng2, _ = _engine(BASE, data)
added = eng2.decode_at(BASE + 6)
assert added >= 1, added
assert (BASE + 6) in eng2.instructions
assert eng2.instructions[BASE + 6].mnemonic == "xor", \
eng2.instructions[BASE + 6].mnemonic
def test_decode_at_stops_on_resync_and_does_not_evict():
data = b"\x90\x90\x90\x33\xc0\xc3"
eng, sec = _engine(BASE, data)
eng.linear_sweep(sec)
before = dict(eng.instructions)
# Every address is already decoded here, so decoding at one adds nothing new
# and must not replace what is there -- an eviction would corrupt whichever
# function already walks that chain.
eng.decode_at(BASE + 3)
assert len(eng.instructions) == len(before)
for a, i in before.items():
assert eng.instructions[a] is i, "decode_at evicted an existing insn"
def test_decode_at_refuses_non_executable_and_out_of_range():
data = b"\x33\xc0\xc3"
s = _Section(BASE, data, executable=False)
s.data = data
eng = DisasmEngine(_Image(s))
assert eng.decode_at(BASE) == 0, "must not decode a non-executable section"
eng2, _ = _engine(BASE, data)
assert eng2.decode_at(BASE + 0x9999) == 0, "must not decode outside the section"
def test_decode_at_stops_at_a_terminator():
# ret immediately, then junk that must not be pulled in
data = b"\xc3" + b"\x00" * 32
eng, _ = _engine(BASE, data)
added = eng.decode_at(BASE)
assert added == 1, added
assert eng.instructions[BASE].is_ret
def test_probe_accepts_a_function_body_and_rejects_fill():
"""
probes_as_function_body is the corroboration _pass_call_targets requires
before manufacturing a function at a call target the sweep stepped over.
It replaced a 16-byte alignment test that dropped Wreckless's _mtinitlocks
(unaligned, packed straight after a jump table) and accepted all-zero fill.
"""
# push esi / push edi / xor eax,eax / inc eax / pop edi / pop esi / ret
body = bytes.fromhex("5657 33c0 40 5f5e c3".replace(" ", ""))
# two nops of padding put the body at an unaligned start -- the
# _mtinitlocks shape exactly
eng, _ = _engine(BASE, bytes.fromhex("9090") + body)
assert eng.probes_as_function_body(BASE + 2), "a body reaching a ret is a function start whatever its alignment"
# all-zero fill decodes forever as `add [eax], al` and never terminates
eng2, _ = _engine(BASE, bytes(4096))
assert not eng2.probes_as_function_body(BASE), "zero fill must not read as a function"
# a lone 0xff at the end of the section: undecodable, runs off the end
eng3, _ = _engine(BASE, bytes.fromhex("ff"))
assert not eng3.probes_as_function_body(BASE)
def test_probe_does_not_mutate_the_sweep():
eng, _ = _engine(BASE, bytes.fromhex("9090565733c0c3"))
before = dict(eng.instructions)
eng.probes_as_function_body(BASE + 2)
assert eng.instructions == before, "probing must not record instructions the sweep did not produce"
def test_probe_follows_a_tail_jump():
# push esi / jmp $+2 -- a tail call is a legitimate function ending
eng, _ = _engine(BASE, bytes.fromhex("56eb00c3"))
assert eng.probes_as_function_body(BASE)
def _run():
fns = [v for k, v in sorted(globals().items()) if k.startswith("test_")]
for fn in fns:
fn()
print(" ok %s" % fn.__name__)
print("%d checks passed" % len(fns))
if __name__ == "__main__":
_run()