Commit Graph

41 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
GTTeancum dfec4df92a Retain recognized constant and virtual-call thunks 2026-09-13 04:56:06 -04:00
GTTeancum bdc3e186ff Reject weak immediate function starts inside decoded instructions 2026-09-13 04:52:57 -04: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 3e77128c77 disasm: a whole small function in a gap counts, not only a prologue
MSVC packs runs of constant-returning accessors -- "mov eax, <address>; ret",
six bytes each -- back to back with no padding, and they are reached only
through vtables. There is no prologue to recognise because there is no frame:
the entire function is two instructions. So the gap pass, the padding pass and
the call-target pass all miss them, and the indirect call to one is skipped
rather than made.

Half-Life 2 has 3,147 of that exact shape. 19 land in an unclaimed gap and are
found by nothing else; one of those was the last unresolved indirect call in a
level load.

The gap restriction is what makes this safe rather than reckless. The same two
instructions appear 795 times *inside* larger functions as a return path, and
treating one of those as a function start would cut a function in half -- but
those are covered by the function that owns them, so they are not in a gap and
are never considered. Both cases are 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 15:36:38 -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 666ac54f47 disasm: a function can begin right after a ret, with no padding
_pass_cc_boundaries only recognises a boundary when the compiler left int3
padding to the next alignment. It usually does -- but not when the next
function already starts on the boundary, and then a clean prologue sits
immediately after the previous function's ret with nothing marking it.

Nothing else covered that. Such a function is not a call target if it is only
ever reached through a vtable, and the prologue pass looks for "push ebp; mov
ebp, esp", which an FPO function like "sub esp, 0x18" does not have.

Restricted to addresses in an unclaimed gap, which makes it safe by
construction rather than by judgement. MSVC parks out-of-line tails after a
ret too and they look identical from here -- but a tail belongs to the
function above it, so _find_function_end has already walked over it and it is
not in a gap. Half-Life 2 has 20 of these: 12 in gaps, 8 tails, and the gap
test separates them without having to tell them apart.

The one that mattered was 0x00476EB0, a material-system method reached only
through a shader's vtable. Unresolved, the indirect call was skipped rather
than made, so eax kept a stale value and the caller used it as the source of a
256-byte string copy while loading the first level's materials.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BuW5WGcXFFrLAYEfvCNGs1
2026-09-05 03:48:27 -07:00
sp00nz d5ee8ee072 disasm: accept a vcall thunk where its address is taken, too
The data-pointer pass was the wrong half. These thunks are taken by address and
passed around as values, so in Half-Life 2 both of the ones that were stalling
a boot appear only in .text, at unaligned offsets -- immediate operands, not
table entries. That is the immediate pass's territory, and it gates on the same
probes_as_returning_body a thunk can never satisfy.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BuW5WGcXFFrLAYEfvCNGs1
2026-09-05 02:58:00 -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 897735354a disasm: a tail call ends a function, same as a ret
MSVC pads to the next function with int3 after a `ret`, and equally after a
tail call, because "return f(x)" compiles to a bare `jmp f`. The CC-boundary
pass only recognised `ret`, and only scanned back three bytes -- not far
enough to have seen a `jmp rel32` even if it had accepted one.

Half-Life 2's filesystem module has this at 0x0041FB00:

    0x0041FB00  jmp 0x0041F370      tail call, 5 bytes
    0x0041FB05  int3 x11            padding to the 16-byte boundary
    0x0041FB10  mov eax, [esp+8]    a real function, reached by pointer table

With no boundary there, sub_0041FAD0 ran on to 0x0041FE40 and swallowed it. It
is not in any vtable, so the RTTI seeds did not cover it either, and the
indirect call to it had no function to resolve to: at runtime the call was
skipped rather than made, silently, and the work it does never happened.

Only instructions the sweep actually decoded at that address are considered,
so widening the scan cannot invent a misaligned one, and padding that does not
follow a terminator is still not a boundary -- guarded by a test, since
accepting it would split functions at random.

Also bridges RtlCompareMemory and RtlCompareMemoryUlong (268, 269), which
their argument sizes were already written down for but which had no
implementation. Both answer "how far do these match" and are used to decide
whether a buffer needs work; returning 0 reads as "differs at the first byte",
which is the safe-looking answer and the wrong one whenever the caller is
looking for a region it can skip.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BuW5WGcXFFrLAYEfvCNGs1
2026-09-04 21:06:38 -07:00
sp00nz 5133ba00dc Merge v0.7.0 into main, and release v0.7.1
main had been sitting on v0.6.0 plus a handful of cherry-picks while the 0.7
work accumulated on a branch, so users were still getting the old direction
flag, the old cmp carry flag, the old kernel memory model and the old disasm
recovery. This merges the 50 commits and releases the result together with the
two contributed PRs.

Contributed, and credited in CONTRIBUTORS.md:

  #18, dplewis -- ReleaseMutex returned TRUE unconditionally on POSIX, so a
  thread releasing a mutex it did not own got success and NtReleaseMutant told
  the guest a still-held mutex was free.

  #17, DarthSidious666 -- D3D8 texture translation, 4,096 lines: all 66 Xbox
  formats mapped to DXGI, cube and volume textures, software channel conversion,
  and tests/d3d8_smoke to make it checkable without a D3D11 device. Also took
  hardcoded Burnout 3 strings out of the tools and the Linux paths.

Five conflicts, all where #17's de-hardcoding met the same problem the 0.7
branch had solved differently. #17 added --game-name and a config constant; the
branch read the title out of the XBE header. Both are worth keeping, so
config.banner_name() prefers an explicit --game-name, falls back to the header
title, and only then to the default -- the header is right without anyone
remembering a flag, and the override is there for anyone who asks by name.

Verified on the merged tree rather than assumed: 175 Python tests pass, the
toolkit builds clean, #17's own d3d8_smoke passes, and a project copied from
templates/new-game runs the documented pipeline start to finish and links --
which is the path that was broken in three separate places at the start of the
week.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013pS5pcx2cx9JXyKurjok17
2026-09-03 01:40:39 -07:00
Ned Heller 857c22cc6a Merge PR #17 from DarthSidious666: D3D8 texture translation
D3D8 Texture work
2026-09-03 01:29:23 -07:00
sp00nz 178d21d71d docs: fix the three things new users actually get stuck on
All three from people following the instructions and reporting where they
stopped.

recomp_types.h is now written into --gen-dir by tools.recomp. It lived only in
templates/runtime/, so a project copied from the template hit
`error C1083: Cannot open include file: 'recomp_types.h'` at build time and had
to find it by hand. It is the runtime's register model rather than anything a
project writes, and recomp_funcs.h includes it -- a quoted include searches the
including file's own directory first, so emitting it beside the generated code
is all it takes. An existing copy is never overwritten, so a project that has
edited it keeps its edits; delete it to get the current one back.

The disassembler now names the file it wants when the analysis JSON is missing.
It said only "run the XBE parser first", leaving both the filename and its
location to guess, and someone did: `--json JSON`, then `--analysis-json JSON`
to get past the same error one step later. It now prints the exact path and the
exact command that writes it, and says that the name is what auto-detection
keys on.

The README's own quick start was the wrong instructions. Step 3 ran
tools.xbe_parser with no --json, so step 4 could not find the analysis it
needs -- and the README is what people follow, since it is the front page. It
now passes --json with the name the next step looks for, notes what --text-only
excludes, and points at GETTING_STARTED as the version that explains why.

Also: the Ghidra naming pipeline was fully built and documented in
tools/ghidra_naming/README.md and mentioned in neither guide, so "any way to
port over Ghidra labels easily?" had no findable answer. GETTING_STARTED now
has it as step 4.5, before recompiling, because the recompiler emits whatever
name is on the functions.json entry -- run it after and the names reach the
generated C, the crash traces and the ABI reports.

And the CUSTOMIZE note on RECOMP_ICALL_IS_CODE is gone. It told readers to edit
the VA range for their title; the range has come from g_xbox_code_lo/hi since
the hardcoded 0x00400000 cutoff was removed.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013pS5pcx2cx9JXyKurjok17
2026-09-02 15:24:36 -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 373de05aff docs: fix the three things new users actually get stuck on
All three from people following the instructions and reporting where they
stopped.

recomp_types.h is now written into --gen-dir by tools.recomp. It lived only in
templates/runtime/, so a project copied from the template hit
`error C1083: Cannot open include file: 'recomp_types.h'` at build time and had
to find it by hand. It is the runtime's register model rather than anything a
project writes, and recomp_funcs.h includes it -- a quoted include searches the
including file's own directory first, so emitting it beside the generated code
is all it takes. An existing copy is never overwritten, so a project that has
edited it keeps its edits; delete it to get the current one back.

The disassembler now names the file it wants when the analysis JSON is missing.
It said only "run the XBE parser first", leaving both the filename and its
location to guess, and someone did: `--json JSON`, then `--analysis-json JSON`
to get past the same error one step later. It now prints the exact path and the
exact command that writes it, and says that the name is what auto-detection
keys on.

The README's own quick start was the wrong instructions. Step 3 ran
tools.xbe_parser with no --json, so step 4 could not find the analysis it
needs -- and the README is what people follow, since it is the front page. It
now passes --json with the name the next step looks for, notes what --text-only
excludes, and points at GETTING_STARTED as the version that explains why.

Also: the Ghidra naming pipeline was fully built and documented in
tools/ghidra_naming/README.md and mentioned in neither guide, so "any way to
port over Ghidra labels easily?" had no findable answer. GETTING_STARTED now
has it as step 4.5, before recompiling, because the recompiler emits whatever
name is on the functions.json entry -- run it after and the names reach the
generated C, the crash traces and the ABI reports.

And the CUSTOMIZE note on RECOMP_ICALL_IS_CODE is gone. It told readers to edit
the VA range for their title; the range has come from g_xbox_code_lo/hi since
the hardcoded 0x00400000 cutoff was removed.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013pS5pcx2cx9JXyKurjok17
2026-09-02 15:13:59 -07:00
sp00nz bdaecf3444 Reach the dashboard's own assets, and stop recommending the seed that broke it
Three fixes, all found bringing up the Xbox Dashboard against the current
toolkit.

Partition2 is C:, the system partition. On a console that is where the
dashboard and its own assets live, and the dashboard opens them by device path
as well as through Y: -- so a path under partition2 is an ordinary asset read
and belongs in the game dir, the same place Y: already goes. It was going to
the save directory, so default.xip could not be found and the dashboard
returned to firmware. Only the bare device keeps the system-data image, which
is why the new rule carries a trailing separator and is listed first. C: and
\??\C: get the same mapping, which nothing had.

The indirect-call feedback dump never fired for a title that gave up during
boot. The firmware-exit path ends in ExitProcess, which does not run atexit, so
the host's registered dump was dead code exactly where the header says it
matters most. Dump from the bridge instead.

The mid-instruction seed guard does not cover the case that actually bit here.
A seed from func_id's identified_functions.json can land at a perfectly valid
instruction boundary that is nevertheless *inside* an existing function, and it
still clamps that function's end. On the dashboard it cut __heap_init short of
its `pop esi; ret`, so the CRT heap was never initialised, every later
allocation was garbage, and nothing anywhere said so -- it took
-DRECOMP_ABI_CHECK to see it. The help text recommended that file; it now
recommends the measured icall_targets.json and says why not the other.

Also: templates/new-game/src/recomp_manual.c had a literal newline inside a
format string, so a project copied from the template did not compile.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013pS5pcx2cx9JXyKurjok17
2026-09-02 10:20:30 -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 10693121cd disasm: data-pointer aliases must cover thunks and inside-body entries
Three corrections to the pass, each found by measurement rather than by
reading it again.

The `not inside_a_function` filter was copied from _pass_imm_ref_targets,
where it is right: that pass creates function *starts* and one landing
inside a body would split it. This pass creates aliases, and
inside-a-function is precisely what an alias is for.

Requiring a `ret` was too strict in a gap. MSVC emits C++ constructor
thunks as `mov ecx, <this>; jmp <ctor>`, and a whole run of them can sit
between two detected functions. In Half-Life 2 that run follows
sub_005C0FB0: the `push .. call .. ret` thunks passed the probe and the
`jmp` ones did not, which is a distinction with no meaning -- both are
entry points named by the same table. 45 static initialisers were the
`jmp` form, so _initterm found no body for them and silently skipped
every one. The gap branch now wants an instruction boundary the sweep
already recorded plus a stream reaching a ret *or* a tail jump; padding
has no recorded boundary, and a table does not point into it anyway.

Inside a body the bytes are already known to be code, so the only
question there is whether the address is an instruction boundary rather
than the middle of one.

It also took a wrong assumption to find: sub_005C10D6 looked like the
enclosing function, but it is an alias this pass itself created. With
aliases excluded the nearest real function ends at 0x005C0FBA, well
before, which is what put the whole run in the gap branch.

HL2: 48,334 functions, 5,741 aliases.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BuW5WGcXFFrLAYEfvCNGs1
2026-09-01 14:23:39 -07:00
sp00nz d9e7aaaeeb disasm: recover functions that exist only as data-table pointers
_pass_imm_ref_targets catches an address that appears as an immediate in
code. It cannot catch one that only ever exists as a *value in a table* --
a vtable the compiler emitted into .rdata, a callback array, a dispatch
table. RTTI recovery covers vtables belonging to polymorphic classes;
nothing covered the rest.

Half-Life 2 made the cost obvious. Its boot reached module loading and
then stopped on one unresolved indirect call after another --
0x00427F80, 0x005AC780, 0x00581CC0 -- each a clean function reachable
only through a table, each found only by running the title and reading
the indirect-call feedback. 0x00427F80 is CreateInterface's InterfaceReg
list walk, so the engine could not look up a single interface. There are
4,892 of them in this binary.

These are alias entries, not candidates, and that distinction is the
whole of the change. Registering them as function starts measurably hurt:
5,305 C++ constructors became 5,260, one clobbered callee-saved register
became 13, and the generated code shrank by 70%. A start in a gap does
not truncate an already-measured body, but it does stop its neighbour
*extending* into that gap on the rebuild, and plenty of bodies
legitimately reach past their first measurement via an out-of-line tail.
That 70% was not redundancy being removed, it was real tails no longer
being reached. Aliases are materialised after every boundary is final, so
they add an entry point without moving anyone's end.

Wreckless +349 (9.8%) against HL2's +4,892 (11.5%), so the ratio is
proportionate rather than a runaway.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BuW5WGcXFFrLAYEfvCNGs1
2026-09-01 12:53:13 -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 8652c9ae78 disasm: recover out-of-line blocks reached by a conditional branch
_pass_tail_jump_targets deliberately ignores jcc, and the reason in its
docstring is sound: a jcc target past the end of its own function usually
means the body was measured short, and registering a function start there
splits it instead of extending it. Halo proved that -- +15 functions, two
inside an existing body, one function 0xA0 bytes shorter.

But the code still has to exist. When it does not, the branch is lifted
as a call to a stub that pops a return address and returns, and that is
how Half-Life 2's realloc has been broken all along. MSVC parks an
out-of-line block of realloc at 0x005B2D38 and reaches it with `jne`;
realloc was measured as ending at 0x005B2D2A because a separately-called
helper at 0x005B2D2F clamps the boundary, so the block was orphaned. That
is realloc's *common* path, so on most calls the SEH epilogue never ran:
esp came back unrestored and ebx/esi/edi were never popped. Every
CUtlMemory::Grow got a garbage buffer, so an inserted CUtlRBTree node had
links [0,0] instead of [0xFFFF,0xFFFF], m_Root self-cycled, and the tree
search span in stricmp forever.

Registering an alias instead of a candidate is what makes this safe:
aliases are built after every body is measured, so they cannot clamp
anyone's end -- exactly the damage the jcc exclusion was avoiding. Two
further guards: the target must land in a gap (inside another function is
the alias case the existing pass already handles), and must decode to a
ret, so the interior of a mis-measured body does not qualify on the
strength of one branch.

HL2: 12 orphans recovered, aliases 8 -> 20, unresolved stubs 69 -> 58.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BuW5WGcXFFrLAYEfvCNGs1
2026-09-01 10:05:40 -07:00
sp00nz 572b8aa3d8 disasm: imm-ref pass must test code sections, not the executable bit
An XBE marks .rdata and .data executable, so `section.executable` is not
a test for "is this code" -- and .rdata disassembles happily into
bound/popal/arpl. 0x00642C18 is a string table; it became a function,
emitted `POP32(esp, di)`, and failed to compile. That it failed to
compile was luck: garbage that happened to be valid C would have become a
silently wrong function.

The caller's section list is the real answer, and dropping that parameter
when this pass was restructured to run once is what let data through.

Effect on Half-Life 2: 2,425 promotions -> 1,166, all in code sections,
and unresolved call stubs fall from 1,531 back to 69 -- the bogus
functions were dragging in their own garbage call targets.

Third time this format's executable bit has misled something here, after
resync_jump_tables (fixed by requiring a table's entries to stay in its
own section) and the fault handler's stack scan.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BuW5WGcXFFrLAYEfvCNGs1
2026-09-01 09:29:42 -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
DarthSidious666 d12e466e8d runtime+tools: derive layout/imports/version from the XBE instead of hardcoding Burnout 3
Title-agnostic refactor across the runtime and tooling:

- kernel: read thunk-table ordinals from the mapped XBE table, keeping the
  static list only as a no-XBE fallback; add xbox_kernel_set_version() for
  per-title XDK version reporting; drop Burnout 3-specific version/hardware
  values and code/key paths from the comments.
- nv2a: generic EnumWindows lookup for a "- Static Recompilation" window and
  a menu-name table, replacing the Burnout 3 window-class/title strings.
- platform: GetWindowTextA/EnumWindows/WNDENUMPROC stubs backing the generic
  window search.
- tools: func_id/disasm/recomp derive .text/.rdata/.data and XDK section
  layouts from the XBE under analysis (configure_from_xbe), retaining the
  old layout as reference fallback.
- docs: README + kernel-replacement notes updated for the neutral paths.
2026-08-29 11:42:55 +01:00
sp00nz 842ee254e8 d3d: implement D3D8Surface; disasm: hash tool source into the cache key
- d3d8_resources.c / d3d8_internal.h: D3D8Surface was declared but never built,
  so tex_GetSurfaceLevel and dev_GetBackBuffer both returned E_NOTIMPL. Halo
  checks those during rasterizer init and gives up (BootToDash) before its main
  loop. A surface is a view onto a texture level (or a back buffer): it borrows
  the parent's ID3D11Texture2D and system memory and owns neither. GetSurfaceLevel
  now hands one back.

- cache.py: the analysis cache keyed on the XBE and options but not on the
  disassembler's own source, so editing a detection pass returned the previous
  run's functions.json and read as "the change did nothing" -- the same silent
  wrong answer the option fingerprint guards against. Fold the tool's *.py into
  the key.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-23 11:08:47 -07:00
sp00nz 392f8580bc disasm: require alignment before manufacturing a call-target decode
Ran the new toolkit on Steel Battalion LOC (retail default.xbe and the
debug brainbox2.xbe) and the call-target realignment from fd71a0e
generalised much harder than on Halo -- +75 and +103 functions against
Halo's +34. Then checked whether they were real:

  new functions on the debug build: 103
    16-aligned  61
     4-aligned  68
    unaligned   35

35 of 103 not even 4-aligned is the same signature as the garbage
indirect targets from d06af63: a call operand decoded out of data
produces a plausible in-section address that is almost never aligned.

decode_at manufactures an instruction where the sweep had none, which is
creating evidence rather than reading it, so it should demand
corroboration. Targets that already decoded are untouched whatever their
alignment -- that is pre-existing behaviour and not this pass's business.

                      before   ungated   16-aligned gate
  SB retail            7,199    7,274    7,240   (+41, 33 rejected)
  SB debug            14,094   14,197   14,155   (+61, 42 rejected)
  Halo 2276            8,869    8,903    8,901   (+32,  2 rejected)

Cost on Halo is 2 of the 46 unresolved stubs it used to recover, 31 ->
29. Both are 0x2530xx, past the last detected function, so they are
plausibly garbage as well. Trading 2 doubtful recoveries for 75 rejected
bogus functions across two other binaries is the right side of that.

Threshold lives in config.CALL_TARGET_REALIGN_ALIGNMENT; set to 1 to
disable. This is the third independent measurement to land on 16-byte
alignment as the discriminator between a real MSVC function start and a
misdecoded call operand.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-23 02:31:13 -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 19a2ec8885 recomp: make the feedback loop usable on a real per-title project
Wiring it to Halo found two things that only show up outside this repo.

--seed-functions is now repeatable. Halo already uses it for a
hand-maintained list carrying the entry points nothing in .text calls
(the PsCreateSystemThreadEx shim, real_math_initialize's tail-jump
target) with comments explaining why each is there. The feedback
database is machine-generated and rewritten every merge, so merging one
into the other would either destroy the hand-written file or make the
generated one un-regenerable. They stay separate files and the detector
unions them.

icall_feedback.py takes --functions. It hardcoded this repo's
tools/disasm/output/functions.json, but a per-title project keeps its own
(Halo: build/disasm/functions.json). Cross-referencing against the wrong
title's database silently reports every observed target as a gap, which
is the most misleading possible output for a tool whose entire job is
telling you which targets are gaps.

First real measurement, Halo build 2276, one early-boot run that asserts
in render_cameras.c:458 before reaching main():

  67 distinct indirect-branch targets observed
  25 ever-unresolved
  24 of those 25 are NOT known function starts

The pre-existing diagnostic reported 3 of those 24. It rate-limits at 16
reports because each one dumps a 16-entry ring buffer, so it went silent
long before the interesting targets appeared. 21 of the 24 gaps were
invisible.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-23 01:34:32 -07:00
sp00nz 18a6bf7a56 disasm: do not end a function at its own branch target
_find_function_end stored forward branch targets in max_addr, which is the
function's *exclusive* end. The coverage test then asked
`addr + size >= max_addr`, which is satisfied while sitting exactly on the
target -- so the walk stopped at the first instruction the function was
required to contain.

MSVC emits the triggering shape constantly: a conditional branch forward, a
body, an unconditional `jmp` backwards, and the branch target parked out of
line after it. Halo's get_edge_vertex (0x00107EC0) ended at 0x00107FB8,
which is its own tail. The tail was then lifted as a separate function and
the `jne` to it became a tail call that returned without running the
epilogue, leaking the 28-byte frame (push ebp / sub esp,0xc / push
ebx,esi,edi) on every call. Three calls in, the caller's saved esi/edi/ebx
came back as garbage.

Track branch targets in their own max_target and require the walk to decode
strictly past it. Landing on a target is not coverage.

Halo: get_edge_vertex 248 -> 402 bytes, and unresolved call targets
(addresses called but with no detected function) drop 1989 -> 175.

tools/disasm/test_function_end.py covers the out-of-line tail, a plain
function still ending at its first ret, and next_func still bounding the walk.
2026-07-20 04:01:05 -07:00
sp00nz 1610f4f70f recomp/disasm: detect SEH helpers per-title, and stop truncating functions
Two boundary bugs found while getting Halo's main thread to run.

__SEH_prolog establishes the *caller's* frame pointer, so the lifter has to
know which function it is - it emits an "ebp = g_seh_ebp" readback after the
call. The address was hardcoded to one game's CRT (0x00244784), so on every
other title no readback was emitted, ebp kept whatever stale value it had, and
the first ebp-relative local access dereferenced it. In Halo that was a fault
at 0xFFFFFFFC: ebp was 0 and the function's first act was [ebp-4].

Both helpers are compiler boilerplate with distinctive bodies, so
detect_seh_helpers() now finds them by signature (fs:[0] access plus
lea ebp,[esp+0x10] for the prolog; fs:[0] store plus leave/push ecx/ret for
the epilog), bounded by size so an unrelated function touching fs:[0] cannot
match. --seh-prolog/--seh-epilog override if detection ever fails. Halo:
__SEH_prolog 0x001DD5C8, __SEH_epilog 0x001DD601.

Separately, _find_function_end() extended a function's bounds for forward
*conditional* jumps but not unconditional ones. A body ending in
"jmp <forward>" - the tail of an if/else, or a jump over an interleaved block
- hit the terminator check with max_addr still short of the target, so the
function was cut off mid-body. Everything past the cut looked like unrelated
code and the function's own jump targets became calls to empty stubs, which
executed as no-ops. Now uses is_branch (conditional and unconditional);
`upper` is already clamped to the next known function start, so an in-bounds
target is internal rather than a tail call.

That one had wide effects on Halo beyond the thread routine:

  unresolved stubs   3,871 -> 1,993
  generated C        860,311 -> 1,002,878 lines
  symbol attribution 49.76% -> 50.41% (2,067 -> 2,147 direct)

Self-checks: tools/recomp/test_seh_detect.py.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-20 00:24:13 -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 5eb23c3477 disasm: key the cache on seeds and sections, not just the XBE
The cache checked the XBE hash, the analysis JSON hash and --text-only, but not
--seed-functions or --extra-sections. Both change what gets disassembled, so
re-running with a different seed set returned the previous run's results and
looked exactly like the seeds had had no effect. A stale cache that reports a
plausible wrong answer is worse than a slow one; you only find out by knowing
to pass --force.

Cost an hour here: an iterative seeding loop reported "converged, 0 new
targets" for two rounds running, which was the cache handing back round 1 both
times. Real convergence took 17 rounds and went from 5,230 dangling stubs to
54.

Now fingerprints every input that affects the output. Seed order does not
matter; adding a single seed invalidates.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-16 23:18:05 -07:00
sp00nz 6d3936b08c disasm: don't disassemble data sections just because they're marked executable
Xbox linkers mark nearly every section executable, .data included, so
get_code_sections' `s.executable` test swept data in as code. Runs of zero-fill
decode as `add [eax], al` and the lifter emits C for them; one phantom in
Burnout 3's .data referenced a nonexistent `cr7` register and broke the build.
On Burnout 3 that was 33 phantom functions across .data/.rdata.

Excluded by name instead, limited to the conventional PE data sections. XDK
library sections are deliberately NOT excluded even where the name suggests
data (DSOUND_RD, D3D_RD, XON_RD) -- the linker maps class those as CODE and
they are exactly what we want disassembled. --extra-sections still overrides
this for a title that really does hide code in .data.

Burnout 3: 22,901 -> 22,868 functions, the 33 lost ones all phantoms; every
real code section unchanged.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-16 20:53:55 -07:00
sp00nz 21488f4d3d Fix the getting-started pipeline: every documented step was broken
Both open issues (#1, #2) are people bouncing off the same wall. All four
documented steps failed on a stock Windows console; reproduced each one.

- tools/xbe_parser was the only tool package without __init__.py/__main__.py,
  so `py -3 -m tools.xbe_parser` could never run (issue #2, verbatim).
- disasm auto-detect hardcoded `burnout3_analysis.json` in two copies. Now
  globs `*_analysis.json` from one helper, so per-game names work (issue #1).
- GETTING_STARTED step 2 never passed --json, so the file step 3 requires was
  never produced.
- A U+2192 arrow in recomp's argparse description and in xbe_parser's
  --extract-sections output crashed cp1252 consoles, i.e. `recomp --help` was
  a traceback on default Windows terminals.

Also adds the MIT LICENSE file. README has claimed MIT since the initial
release but no license text existed, which legally left the repo
all-rights-reserved and blocked contribution.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-16 11:20:48 -07:00
sp00nz 2269c62b6b Add --seed-functions to disasm for iterative pipeline
Allows feeding discovered function addresses (from vtable scanner)
back into the disassembler as seed candidates. Enables a two-pass
pipeline: disasm → func_id (discover thunks) → disasm+seeds → recomp.

Seed addresses are added as high-confidence candidates (0.95) before
the regular detection passes, so they properly split functions at
thunk boundaries.

Usage: py -3 -m tools.disasm game.xbe --text-only \
         --seed-functions tools/func_id/output/identified_functions.json

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-26 23:51:30 -07:00
sp00nz e633c961e6 Add --extra-sections flag to disasm for non-executable code sections
Some XBE sections contain executable code but are marked non-executable
in the section headers (e.g., XIPS in the Xbox Dashboard). The Xbox
kernel doesn't enforce page protection, so sections can contain code
regardless of their executable flag.

New --extra-sections flag:
  py -3 -m tools.disasm game.xbe --text-only --extra-sections XIPS

This adds named sections to the disassembly target list even if they
lack the executable flag. Allows lifting code from any section.

Also removed XIPS from the recomp skip list (dashboard config) since
XIPS contains the XAP text parser, not just data.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-26 14:49:13 -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