Commit Graph

15 Commits

Author SHA1 Message Date
andeecollard 26de405194 fix(disasm): the returning-body probe follows a switch through a measured table
probes_as_returning_body ended at any unconditional jmp that was not an
immediate forward branch, so a `jmp [reg*4 + table]` switch dispatch looked
like a tail call. The imm-ref pass relies on that probe, which left one shape
of function undiscoverable: reached only as an immediate (`mov eax, offset
fn`), no prologue, packed straight after the previous function's ret, and
opening with the dispatch. The cc-boundary pass needs int3 padding and the
gap-prologue pass needs a prologue, so nothing found it.

The cost is larger than one missing function. The switch it owns is
translated nowhere, and the gap-prologue pass then starts "functions" at its
later arms (`mov eax, 1 ; ret` probes as a constant stub) and at the npad in
front of the table, which decodes the table as code. A recompiled title
calls garbage from those and carries their bytes as untranslated
instructions.

resync_jump_tables has already measured the table by the time the imm-ref
pass asks, so the probe now continues at the first arm past the dispatch,
keeping its instruction budget. A dispatch through a table the engine has not
measured is still tail-call shaped: nothing says where its arms are.

test_returning_body_switch.py pins the probe on both sides and runs
detect_all over a caller plus such a function. Against the old probe the
end-to-end test finds three false functions (two arms and the table) and not
the real one; with the fix it finds the function and none of its arms.
Found on a retail title, where two such functions owned 21 switch tables.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017QvivF8psGzR3Ws8tv21Ut
2026-09-26 09:45:45 +01:00
sp00nz 1ed528fd52 A branch into unclaimed bytes can end in a jmp, not just a ret
The conditional-branch orphan pass recovered a block only if it reached a ret.
A block that ends in an unconditional jmp was rejected, and the branch to it
was lifted as a call to a stub that pops a return address and returns.

Half-Life 2's CRT _lock helper is built exactly that way. It takes the lock in
a __try and releases it in the __finally, and its scan loop exits into two
blocks past the measured end of the body:

    005BE244  cmp  dword ptr [ebp-0x1c], -1
    005BE248  jne  0x5be2a7          <- the __finally, which calls _unlock(11)
    005BE24A  inc  edi
    005BE24B  jmp  0x5be173          <- back into the loop

Neither block was detected, so both became stubs and the __finally never ran.
Tracing every acquire and release by address made it unambiguous: every other
CRT lock balanced, and _OSFHND_LOCK was taken 15 times and released none.
Critical sections are recursive, so the owning thread kept running and only the
second thread to want the lock blocked -- which is why it presented as an AB-BA
deadlock between two locks rather than as a leak of one.

Accepting a jmp-terminated block is not enough on its own: where that jump
lands has to be addressable too, or the recovered block just ends in a call to
another stub. When the destination is inside a function -- the ordinary case,
since it is the rest of the same loop -- it is registered as an alias entry,
which is the mechanism that already exists for a tail jump into a body.

Cost is 4 function starts on Half-Life 2 (49,494 to 49,498) and three fewer
stubs. Every guest lock now balances, and a level load that previously
deadlocked two thirds of the way in runs to the same point with real locks as
it did with RECOMP_CS_MODE=single -- 15.3 MB of content against 7.8 MB before,
0 faults, 0 unresolved calls. The bypass is no longer needed to load a level.

Adds RECOMP_CS_TRACE_CRT (per-lock acquire/release order, "all" for every lock
by address) and RECOMP_CS_WATCH (guest backtrace for one lock), which are what
turned "two locks are crossed" into "this one is never released".

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BuW5WGcXFFrLAYEfvCNGs1
2026-09-05 20:20:02 -07:00
sp00nz 1a7aad3cff disasm: match the constant stub exactly, not "a ret comes soon"
Fixes a regression I introduced one commit earlier. The measurement was 19
gap-resident "mov eax, <imm32>; ret" accessors; the rule I wrote accepted any
run of eight or fewer instructions reaching a ret, which data and mid-function
fragments satisfy as well. That added 825 function starts instead of 19, and
Half-Life 2 went from loading 14.3 MB of a level without faulting to 4.8 MB and
a crash.

probes_as_constant_stub decodes the two instructions and checks the operands:
a register destination, an immediate source, then a ret. That is the shape that
was counted, so the rule and the evidence now agree.

The gap restriction still does the heavy lifting either way -- the same two
instructions occur 795 times inside larger functions as a return path, and
splitting one would cut a function in half. Both directions stay pinned by
tests.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BuW5WGcXFFrLAYEfvCNGs1
2026-09-05 16:11:23 -07:00
sp00nz 025b69ef4f disasm: a function whose frame __SEH_prolog builds is still a prologue
push <frame size>
    push <scope table>
    call __SEH_prolog

There is no "push ebp; mov ebp, esp" to recognise, because the helper does
that on the caller's behalf, so none of the shapes probes_as_prologue looks
for match and such a function is invisible to every pass that asks.

Half-Life 2 has one at 0x001F572B, in a gap immediately after the previous
function's ret and reached only through a vtable -- so no static pass saw it
and no call site named it. The consequence is the one this keeps turning out
to be: an indirect call whose target is not a known function is skipped rather
than made. Here the arguments already pushed for it stayed on the stack, which
shifted the caller's frame, so its "pop ebx" restored the wrong slot. The
corrupted ebx was then passed as an array index -- holding the object's own
address -- and the fault landed three functions away in code that had nothing
to do with it.

Found with -DRECOMP_ABI_CHECK, which named the callers returning with
callee-saved registers altered. Fifteen functions, three of them the CRT's own
frame helpers behaving as designed, and the rest all downstream of two skipped
calls.

Two immediate pushes followed by a call is specific enough not to occur by
accident, and this is only ever asked about an address that already looks like
a boundary.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BuW5WGcXFFrLAYEfvCNGs1
2026-09-05 14:35:20 -07:00
sp00nz c8ab437fa5 disasm: MSVC's virtual-call thunk is a function too
mov eax, [ecx]              load the vtable from `this`
    jmp dword ptr [eax + N]     dispatch to slot N

The compiler emits these for pointers-to-virtual-member-functions and for
interface forwarding, and every pass was missing them. They only ever exist as
values in tables, so nothing in code refers to them. They end in an indirect
tail jump and never reach a ret, so probes_as_returning_body -- which the
data-pointer pass gates on -- rejected them. And they are packed back to back
with no int3 between them, so the padding boundary pass never saw them either.

Half-Life 2 has 568 and 41 were being found. Each missed one is an indirect
call the runtime cannot resolve, and an unresolved call is skipped rather than
made: two of them, 0x00583BE2 and 0x00583BFA, were being reached 22 million
times in a boot that then sat spinning with nothing to draw.

Matched shape-exactly rather than by relaxing the general prober to allow
indirect jumps. "Ends in an indirect jump" on its own is weak evidence that
data happened to disassemble; "loads a pointer from [reg] with no index or
displacement and then jumps through that same register" is not.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BuW5WGcXFFrLAYEfvCNGs1
2026-09-05 02:55:08 -07:00
sp00nz 31e120e85a disasm: a mid-instruction seed that is a prologue means the sweep drifted
The guard added with the mid-instruction rejection assumed that a seed
landing inside an already-decoded instruction is a bad seed. That holds when
the sweep is right and the seed is wrong -- Half-Life 2's 0x00202C2E, six
bytes into a nine-byte mov -- but not the other way round.

The sweep drifts whenever it decodes zero padding or a data table as
instructions and runs off the end into real code. default.xbe's XPP section
decodes 001C950600558D at 0x00069533, which swallows the `push ebp` at
0x00069538 that sub_0006A204 tail-jumps to. Rejecting that seed left the
target stubbed, and a stub returns without the callee's own `ret 8`: esp
walked off by 4 per call, the loader's object pointer slid 8 bytes out from
under the vtable its constructor had written, and its attract loop then
called through a null slot 385 million times in 25 seconds.

A prologue is the evidence that separates the two. It is the one shape that
does not occur by accident in the middle of another instruction, so when a
seed decodes as one, realign there and keep it; otherwise reject as before.
Deliberately weaker than probes_as_function_body, which would have to decide
between two overlapping decodings rather than just recognising a start.

Recognises what MSVC emits at -O2 for this XDK: push ebp with either
mov ebp, esp or the lea ebp, [esp-N] form the XPP code uses; a leading
push esi/edi/ebx; sub esp, N; and the two-byte hot-patch nop.

Half-Life 2 is unchanged by this -- 48,335 functions either way, 0x00202C2E
still rejected, and sub_00202BB9 keeps its full 406 bytes.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BuW5WGcXFFrLAYEfvCNGs1
2026-09-02 15:17:33 -07:00
sp00nz b010c42891 recomp: don't rewind an icall's failure path over saved registers
RECOMP_ICALL_SAFE restores g_esp on a failed lookup so a failed stdcall
does not leak its arguments. _fixup_icall_esp_save chose that save point by
walking backwards from the call absorbing every PUSH32 it met, which cannot
tell an argument from the function saving a register.

HL2's sub_005A1700 saves ebx and esi mid-body and then makes an indirect
call taking its arguments in ecx/edx only:

    push ebx
    mov  ebx, [esp+0x14]
    push esi
    lea  edx, [esp+0x14]
    mov  ecx, ebx
    call eax

Both pushes were absorbed, so a null target rewound g_esp over them and the
epilogue popped esi/ebx/edi from 8 bytes too high -- edi landed on the
return address and a float landed in the caller's esi. Three frames up a
CUtlRBTree method received a this of 0x41976D79.

Separate the cases by push and pop counts. A register popped at least as
often as it is pushed is restored on every path out, so a push of it is a
save and the argument run ends there; the comparison is >= and not ==
because a function with several epilogues pops once per return path.
A register pushed more often than popped has a push nobody restores -- an
argument -- and the run still absorbs it, which keeps sub_00135265 working:
it saves edi in the prologue and pushes it again as an argument.

Where the two remain ambiguous, stopping early is the safer error. It
under-rewinds, which the esp invariant reports as "epilogue never ran",
rather than leaving a caller silently holding a wrong register.

Two supporting changes ride along, both from tracking the same corruption:

- disasm: reject an RTTI seed that lands inside an already-decoded
  instruction. Accepting one manufactures a mid-instruction boundary, and
  the bogus function then clamps the end of the real one it sits in, which
  loses that function its epilogue. HL2 has two such slots out of 12,288;
  0x00202C2E, six bytes into a 9-byte mov, cut sub_00202BB9 short and every
  one of its 250 callers got back unrestored callee-saved registers. The
  check runs before the realign test because an earlier seed's decode_at
  can already have laid a chain through the address.

- ABI check: report the signed esp delta and the recent indirect-call
  targets. The esp invariant is one-sided by necessity -- a callee may
  legitimately pop its own arguments -- so it cannot see a frame returning
  too high, which is what this bug did. The delta plus a trace ending in
  00000000 named the failure path directly.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BuW5WGcXFFrLAYEfvCNGs1
2026-09-01 20:10:46 -07:00
sp00nz f2d3940883 disasm: follow intra-function jumps when probing a candidate
probes_as_returning_body stopped at any unconditional jmp, on the theory
that a jmp is tail-call shaped and tail calls are _pass_tail_jump_targets
business. That is true of a jmp that leaves the function and false of the
ones MSVC emits constantly to skip an else-branch.

It cost Half-Life 2 its CreateInterface list walk. 0x00427F80 is a clean
90-byte function -- walk the InterfaceReg list at 0x009342E0, compare
each name with an inlined strcmp, follow [edi+8] -- containing exactly
one jmp, forward, over four instructions. Rejected on that basis, it
became an unresolved indirect call at the precise moment the engine
started looking up interfaces.

Now a forward jump that stays inside the probed window is ordinary
control flow and the probe continues; a backward jump, or one that leaves
the window, still ends it.

HL2: 42,403 -> 42,612 functions, imm_ref_target 1,166 -> 1,375.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BuW5WGcXFFrLAYEfvCNGs1
2026-09-01 11:40:17 -07:00
sp00nz d89b8af48f disasm: recover functions whose address is only ever taken
_pass_indirect_call_slots promotes an immediate stored into a slot that
something calls through by name. That is strong evidence and it misses
the ordinary C++ case completely: a function pointer written into an
object field and later invoked as `call dword ptr [reg]` has no fixed
slot to match against.

Half-Life 2's CUtlRBTree constructor is exactly that -- `mov dword ptr
[esi], 1D0F8h` installs the comparator and the tree calls it through
`this`. Both of that tree's comparators sat in a 42-byte hole between two
detected functions, so neither existed. Every tree search called an
address the recompiler could not resolve, got 0 back, and descended into
a node that was never there. That is where the title's static
initialisation stopped.

The evidence is weak -- an address that merely appears as an immediate --
so the filter carries the weight, and the *gap* does most of the work:
the target must land in executable bytes no function already covers, and
must reach a ret without first hitting an unconditional jmp. Requiring a
ret rejects data that happens to disassemble; stopping at a jmp stays out
of tail-call territory, which _pass_tail_jump_targets already covers with
better evidence; conditional branches are allowed, because real functions
have them. Landing in a gap is what keeps a wrong guess from truncating a
real function, which would be worse than missing one.

Cost matters here: the same address is taken over and over, so this
collects distinct targets before probing and probes each once, capped.
Per-instruction probing did not finish. Collect is 0.3s and probe 8s on
2.99M instructions.

HL2 41,225 -> 43,650 functions (+5.9%), wreckless +148 (+4.2%).

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BuW5WGcXFFrLAYEfvCNGs1
2026-09-01 08:55:06 -07:00
sp00nz da8168ff28 disasm: treat MSVC's embedded switch tables as data
`jmp dword ptr [reg*4 + disp]` dispatches through a table of code
pointers that MSVC parks inline, inside the function body. linear_sweep
has no way to know, so it decoded the pointers as instructions and came
out the far side out of phase -- every byte after the table belonged to
an instruction that did not exist, until the stream happened to resync.

That routinely ate the function's own epilogue, so the `pop esi / pop
edi` balancing the prologue was never lifted and *every caller silently
lost those registers*. Half-Life 2 hits it in the CRT: memcpy and memmove
both carry a tail-copy table, and the C++ static-initialiser driver walks
its constructor array with esi as the cursor and edi as the limit. Both
came back clobbered from its own callees, so the loop stopped after 8% of
the list and Source had no registered interfaces to hand
CreateInterface. 219 tables in that one binary.

Three parts:
  - record the table address of every indexed indirect jump, measure the
    table (entries must point inside the table's own section -- XBEs mark
    .rdata and .data executable, so "points at executable" alone would
    let an array of data pointers pass), drop the instructions the sweep
    hallucinated over it, and decode_at() past the end;
  - extend function bounds by the table's entries. The case bodies are
    jump targets like any other, just held in memory rather than encoded
    in the instruction, and without them the function ended on its own
    dispatch;
  - step over the table when the boundary walk lands on it, since there
    are deliberately no instructions there now.

memcpy went from ending at its first switch to covering all 664 bytes
through the epilogue.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BuW5WGcXFFrLAYEfvCNGs1
2026-09-01 05:45:32 -07:00
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
sp00nz 7fb6d75d31 disasm: measured recursive_descent realignment, and rejected it
recursive_descent only reads engine.instructions, so it dead-ends at the
same out-of-phase holes decode_at fixes for call targets. Calling
decode_at there looked like the same one-line win with wider reach.

Measured on Halo 2276 before keeping it:

  reachable instructions   640,343 -> 640,481  (+138, 0.02%)
  total functions            8,903 -> 8,903    (no change)
  tail_jump_target             129 -> 128      (-1)

Noise, in exchange for a real increase in the chance of following a bad
decode deeper into a hole. Reverted.

It is small because descent starts from function heads the sweep already
decoded and stops at ret/jmp, so it seldom walks into a hole at all --
_pass_call_targets already catches the cases that matter. The number and
the reasoning are recorded at the call site and in the adoption plan so
the idea is not re-attempted blind.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-23 02:19:49 -07:00
sp00nz fd71a0e77c disasm: decode direct call targets the linear sweep stepped over
Tier 1 was going to be block-granular entry points. Checked the premise
against the data first and it does not hold for this codebase:

  46/46 unresolved direct-call stubs are in gaps BETWEEN detected
         functions, not mid-function. All 16-aligned.
  24/25 unresolved indirect targets are likewise gaps. Exactly one was
         mid-function, and it was at offset +0 of a known function.

So block entry points would have fixed about one address. The dominant
failure mode is not entering a function partway through, it is whole
functions never being found. Root cause, in _pass_call_targets:

    if target in self.engine.instructions:   # <- silently drops otherwise

linear_sweep decodes each section as ONE stream and resyncs only by
skipping a byte when capstone fails. Wherever it runs through data -- a
jump table, padding, an embedded constant -- it emerges out of phase and
stays that way 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 cannot rescue it either: it only
reads that dict (`insn = self.instructions.get(addr); if insn is None:
break`), it never decodes, so it dead-ends at the same hole.

The result is that the strongest evidence a function start can have -- a
direct call to it -- was being thrown away because a weaker pass had
gone out of phase upstream. Halo's 0x00017AB0 is named in its own
caller's call list, is 16-aligned, sits in a 5.7 KB hole between two
detected functions, and became `g_esp += 4`.

Adds Engine.decode_at(addr): decode a stream starting exactly there,
stopping as soon as it lands on an already-decoded address, so it
rewrites only the out-of-phase run rather than the section. Overlapping
decodes are kept, not evicted -- on x86 two valid streams really can
share bytes, and callers walk forward by end_address from a known start,
so each follows its own chain. Evicting would corrupt whichever function
was already using the old one.

Measured on Halo 2276:
  realigned call targets            34
  functions                     8,869 -> 8,903
  call_target detections        2,331 -> 2,366
  reachable instructions      637,451 -> 640,343
  of the 46 stubs, now real functions   0 -> 31

The 15 that remain are almost all unaligned, the same signature as the
garbage indirect targets from the feedback loop -- independent
confirmation that unaligned targets are misdecoded call operands rather
than functions.

Block entry points are not dead, just not first: revisit when a title
actually shows mid-function indirect targets.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-23 02:10:50 -07:00
sp00nz f5a7bf5bdd disasm: record address-taken immediates as xrefs
The xref database only tracked CS_OP_MEM operands, so it saw memory reads
(mov reg, [addr]) but never address-taken immediates (push offset str,
mov reg, offset table). String literals and static tables are referenced
almost exclusively the second way, so they were effectively invisible: on
Steel Battalion: Line of Contact the database reached 5 of 1,174 strings
and attributed them to 8 functions.

Adds Instruction.imm_ref and a DATA_IMM xref type. Same title now reaches
261 of 1,174 strings across 60 functions, within ~5% of what a raw
byte-scan of the executable sections finds.

Immediates are only recorded when they land inside the image's VA range,
and never for calls or branches, where the immediate is the branch target
and is already resolved as call_target/jump_target. DATA_IMM is a new type
rather than more DATA_READ entries, so existing consumers are unaffected:
call, jump, cond_jump, data_read and kernel_call counts are unchanged, and
func_id classification output is byte-identical before and after.

func_id/imm_scanner.py already scanned for this, but it is driven by
hardcoded per-title config constants and so cannot serve an arbitrary
binary; doing it in the engine means every consumer gets it for free.

Adds tools/disasm/test_imm_refs.py (synthetic bytes, no game files),
covering push/mov immediates, the memory-operand case, out-of-range
constants, and call/jump targets.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-19 23:20:59 -07:00
sp00nz ef5ad3a734 Initial release: Xbox static recompilation toolkit
Complete toolchain for statically recompiling original Xbox (2001-2005) games
into native Windows executables. Includes:

- XBE parser, x86 disassembler, function identifier, and x86-to-C lifter
- 6-step pipeline documentation (parse, disassemble, identify, lift, runtime, debug)
- 8 technical deep dives (register model, memory layout, ICALLs, D3D, kernel, SEH, etc.)
- 3 Xbox format references (XBE, kernel exports, disc images)
- Runtime templates (recomp_types.h, xbox_memory.h, kernel_stubs.h)
- Candidate game analysis for future recompilation targets

Proven on Burnout 3: Takedown — 22,097 functions lifted from machine code to C.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 02:27:26 -08:00