The CPU rasteriser takes the nearest texel whatever SET_TEXTURE_FILTER
asked for, so a floor or wall seen at a slant aliases and shimmers.
RECOMP_TEX_BILINEAR=1 blends the four nearest texels of every textured
pixel. RECOMP_TEX_ANISO=8 or 16 takes up to that many bilinear taps along
the longer of the pixel's two texel gradients and implies bilinear; any
other value leaves it off. Both are off by default and read once per
process, so with neither set every title draws exactly as before.
All three sampling paths take them:
- raster_triangle (pixel-position batches): the gradients are constant over
a triangle, so the footprint is worked out once per triangle.
- the perspective path without combiners (xf_rows): the gradient is the
coordinate one pixel right and one pixel down minus the coordinate here,
so it stays perspective-correct. XfTri gains dl[3][2], the barycentric
step per pixel, to evaluate them.
- the register-combiner stages (rc_texel, rc_stage_fetch): the same
neighbour coordinates. rc_texel's existing tent blend moves into rc_tent
so the title's own tent request and the aniso taps share it.
No mip levels: a minified texture is averaged along its stretched axis
only. GPU back ends have their own filtering and are not affected.
Test: tests/nv2a_tex_filter, one process per mode (nearest, bilinear,
aniso8, aniso16) on each of the three paths, 12 CTest cases. A two-texel
ramp checks the blend; a stripe texture of three texels to a pixel checks
that anisotropic taps average where nearest and bilinear alias.
Verified: all 12 pass on Windows (MSVC, VS 18) and Linux x86-64 (gcc 15);
nv2a_raster_batch, nv2a_ffp_backend, nv2a_combiner and nv2a_vsh pass. Built
against the unchanged nv2a_pb_exec.c, the three nearest cases pass and the
nine filtered ones fail. Each path was also broken in turn to confirm that
exactly its cases fail. The default-mode output of the test is
byte-identical before and after on all three paths.
Blast radius: nv2a_pb_exec.c only. With both switches unset the nearest
texel path is unchanged; the added work is a read of two cached ints per
texel (rc_texel), per xf_rows call and per triangle, and six multiplies per
triangle for XfTri.dl. Measured on a synthetic 64x64 textured-quad loop,
that was +2.5% on the pixel-position path, +2.3% on the perspective path
and within noise on the combiner path. With a switch set, 8 and 16 taps
cost several times the nearest path.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
docs/INDEX.md stays the one index. Every page gets one navigation line under
its title that points back to it, and runtime/ gets a reference page for the
environment variables.
docs/runtime/environment-variables.md lists every RECOMP_* switch the runtime
and tools read: its default, its effect and the source file that reads it,
grouped as bring-up, kernel, pushbuffer executor, video, audio and input.
Fifty-one of them were not in the docs at all. docs/INDEX.md links it from
"Start Here".
No page is renamed, moved or rewritten, and no other index is added.
Checked: every RECOMP_* name read by getenv, env_on, apu_env_on, env_int or
xa2_env_int in src/, tools/, templates/ and include/ is on the page, and
every name on the page is in the source. All relative links in docs/ resolve
(0 broken, as at v0.16.0). The 34 existing pages change by insertion only:
68 lines added, none removed. docs/INDEX.md gains one line.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
The executor expands a triangle strip as (i, i+1, i+2) for every i, so
every odd triangle winds the opposite way to its neighbour. A strip on
hardware keeps one winding by taking the first two vertices of each odd
triangle swapped. A back end that culls from the render state's cull
registers, or lights two-sided from the winding, therefore drops or
back-lights every second triangle of every strip.
Opt-in, off by default: with RECOMP_STRIP_ALT_WINDING unset the strip order
is unchanged and no title's output moves. Both strip expansions read it
(the transform path and the screen-space indexed path).
Test: tests/nv2a_ffp_backend draws a four-vertex strip and checks the
second triangle's vertex order, run once without the switch (1 2 3) and
once with it (2 1 3). With the switch forced off in the source the second
run fails; with it working both pass.
Verified: nv2a_ffp_backend (2 tests), nv2a_pb_walk, nv2a_raster_batch,
nv2a_vsh and nv2a_combiner pass on Windows (MSVC);
nv2a_ffp_backend passes on Linux x86-64 (gcc).
Blast radius: the strip cases of the two expansion switches in
nv2a_pb_exec.c, behind the switch.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
POP32 assigned dst before adding 4 to sp, so a lifted `pop esp` left esp
at the popped value + 4. The SDM has POP ESP load esp with the value read
from the old top of stack. Spartan: Total Warrior's round-to-int helper
(push esp; push eax; fld; frndint; fistp [esp]; pop eax; pop esp)
returned with esp off by 4, which put a garbage edi into a heap free.
POP32 now reads into a temporary, bumps sp, then writes dst; every other
destination behaves as before, and -O3 code is the same size.
Tests: the new ctest tests/stack_ops runs the lifter's emitted stack
statements (push/pop esp, the round-to-int idiom, an ordinary pop,
push/pop [esp+4], leave, pushad/popad) over a fake guest stack; the old
macro fails its three pop-esp checks. docs/pipeline/04-lifting.md and
docs/technical/register-model.md show the new macro.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Review of #162 (round 2):
- The walk stops at PUT inside a method's parameters and finishes the
same method when PUT moves, as the DMA engine does. It no longer runs
on through stale ring contents, and it no longer reads the leftover
parameters as headers (D3D streams large inline arrays across kicks).
A CALL inside a CALL stops the walk instead of overwriting the return
address.
- fetch_attr checks every vertex read against guest memory, so a garbage
32-bit index drops the batch instead of reading past guest RAM. Surface
writes are refused outside guest memory and on the thread stacks, as
they already were on the image.
- 2x2 anti-aliasing: the framebuffer window takes every other row
(xbox_FramebufferWindowSetAA), and the screen-space fallback scales its
vertices like the clip rect.
- s_xf and s_bverts are allocated on first use (about 13 MB).
- Tests: PUT inside a method, nested CALL and self-jump in nv2a_pb_walk;
a garbage index, lighting below the clamp with an attenuated local
light, and the 0x0310 latch in nv2a_ffp_backend.
- Docs: the back-end advice is marked as coming from a back end not in
this tree.
The Burnout 3 run: with RECOMP_PB_EXEC=1 the DMA walk froze it at the
Crash Nav menu and in the garage, where v0.13.0 runs. A freeze report put
the main thread in KeWaitForSingleObject under D3D's fence wait: told
exactly how far the GPU has got, D3D patches a software method into the
pushbuffer and sleeps on the event the GPU's interrupt for it would set,
and this runtime does not deliver that interrupt. The walk commit alone
reproduces it. So the walk is now opt-in, RECOMP_PB_WALK=dma, and the
default is the segment scan v0.13.0 used, with 0x0310 unmodelled as
before. In the default mode Burnout 3 runs Crash Nav and loads the car,
with no faults. Under the walk, a project that mirrors its fence
(xbox_Nv2aMirrorFence) gets a 0x0310 latch whose fence bits match the
mirrored word.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
pushbuffer-executor.md covers what sits around the v0.13.0 rasteriser: the
DMA-engine walk, answering the title while it runs, fixed-function transform
and lighting, anti-aliased surfaces, index width and the back-end interface.
d3d8ltcg-device-context.md gains the semaphore hand-off for a title whose fence
wait is replaced while the executor runs, and the PGRAPH 0x400B10 wait.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Folded into the existing guides:
- 02-disassembly: four ways the detector misses or merges functions,
each with the check for it
- 04-lifting: negative-index jump tables, privileged registers
- 05-runtime: thread-local registers in recomp_manual.c, replace vs
wrap, RECOMP_ABI_CHECK needing both halves
- 06-debugging: what the ABI checker always reports, guest registers
in cdb
- kernel-replacement: pseudo-handles, the 487 the CRT heap waits for,
a 64-bit call counter
- GETTING_STARTED: /m under Git Bash
New: docs/INDEX.md, every document in one place and again by symptom,
linked from the README. CONTRIBUTORS gains an entry.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
tools/fusion/coverage_oracle.py has sat in the tree unrunnable. It grades our
function-boundary detection against Microsoft's PrecompiledSymbolTable, and
its second argument is our detection for the *donor* title -- which means you
need that title's original Xbox default.xbe to run the pipeline over. The XBE
is not in the recompiled DLL. It is inside the BC package's SVOD container,
which everyone had assumed was sealed. It is not: it is a plain XDVDFS
filesystem with SHA-1 hash blocks interleaved at a fixed stride, and the
stride is self-proving because the hashes check.
tools/fusion/svod.py reads it -- ls, extract, verify -- in the shape of
module.py. Verified by extracting default.xbe from all four shipped BC titles
and comparing sha1 against independent extractions: byte-identical on all
four (Fuzion 2,834,432 / Crimson 3,219,456 / Blinx 44,728,320 / Conker
7,774,208 bytes).
Two things in the format bite, and both are why this is more than forty lines
of seek arithmetic.
The sector base is per title. Filesystem sectors are sectors of the original
disc; the SVOD stream is a slice of it. For Fuzion and Crimson that slice is
the whole game partition and the base is the XDVDFS constant 32. For Blinx it
is 880,036 and for Conker 956,202, and assuming 32 there does not fail -- it
reads the wrong data, quietly. So derive_base() solves for it and proves the
answer: the root table must parse, it must name default.xbe, and that entry
must resolve to XBEH under the same base. Parsing alone is not enough, which
Conker demonstrates: its directory tables are packed into consecutive sectors
and bases 956,201 through 956,207 all parse into plausible entry lists.
The other is that a bad extraction still looks right. A flat contiguous copy
of the Data files -- hash blocks and all -- parses as a valid XBE and reports
the correct title, build date, base address, section names and even the
correct XDK library version, because that all lives in the first 0x1000 bytes
and the first data block is genuine. Three extractions passed a header-only
check during this work and were wrong. xbe_gate() carries the tells that do
fire: the 0x8000xxxx kernel-thunk run must be at the VA the header declares,
and the TLS zero-fill must be a few bytes rather than the ~1.9 billion a
displaced read produces.
Limits, honestly:
- The tests are arithmetic, the directory parser against a handcrafted table,
and base derivation against a synthetic image with Conker-shaped decoys.
None of them touch a package, because the repository ships none and should
not. The four sha1 comparisons are recorded in the doc; CI cannot re-run
them.
- The PIRS header at +0x379 carries a data-block offset that gets within two
sectors of the base on all four titles, but the two-sector gap on the two
enhanced-GDF-layout titles is unexplained and four samples is not a rule.
It is used as a search hint that shortens the candidate list, never as an
answer -- the gate still has to pass.
- Read-only. The hash blocks are used as a witness that the stride is right,
not validated as a tree, so this will not tell you a package is damaged.
- Measured on the four shipped BC packages only. Other SVOD content may lay
out differently; verify first, and svod.py verify is that command.
docs/technical/svod-extraction.md is a new file rather than a section in
ms-fusion-corpus.md: the corpus doc is about what the recompiler does versus
what a game is, and a container format with a per-title table and a
validation gate is a different subject. Linked from there and from the README.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01X8ULfUvyuk8K69chXaNFM9
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
RTTI gives class names, not member names, so a method's own name is not
recoverable -- but the owning class is, and "CBaseEntity__000162C2" beats
"sub_000162C2" both for reading generated code and for crash stacks.
--names emits the {address: name} format merge_names.py --apply already
consumes, so this plugs into the existing naming path rather than adding
one.
Which class owns a method appearing in several vtables is well defined,
unlike per-slot declaration: the vtables share one implementation because
they inherit it, so the declaring class is the one that is an ancestor of
every other class in the set. That needs only the hierarchy sets, no MSVC
layout modelling. On Half-Life 2 it resolves 2,528 shared methods on top
of the 8,992 already unique -- 11,520 of 12,288 (94%) -- and returns zero
ambiguous cases. The 768 with no common ancestor are multiple inheritance
and thunks shared between unrelated classes; they are omitted rather than
guessed at.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BuW5WGcXFFrLAYEfvCNGs1
A title compiled as C++ with RTTI left on describes its own class graph in
the shipping binary. MSVC stores the CompleteObjectLocator at vtable[-1],
so vtable discovery is mechanical: find the COLs, find words pointing at
one, and the method array starts 4 bytes later.
The payoff that changes pipeline output is not the names, it is the
function starts. A method only ever called virtually is invisible to both
linear sweep and call-target scanning -- nothing in the image names its
address except the vtable. --seeds emits those addresses for
tools.disasm --seed-functions, which is why this runs BEFORE disasm.
On Half-Life 2: 2,336 type descriptors, 2,932 vtables, 176,865 slots,
12,288 unique methods. 7,992 of those addresses fell in bytes the sweep
never claimed (only 10 landed inside a known function, all adjustor
thunks), taking the function count 33,140 -> 41,215 (+24%). disasm also
realigned 19 seeded addresses it had stepped over.
RTTI is uncommon: of the eight titles on hand only HL2 has a usable
graph, Crimson Skies and the dashboard carry 4 CRT type_info records with
no vtables, and the rest have none. Absence is a normal result -- the
tool reports zero and exits 0, so regen.sh scripts can run it
unconditionally. Verified against all eight.
Deliberately does not infer which ancestor declared a slot: the
BaseClassDescriptor array is a depth-first preorder, so trailing entries
are secondary inheritance branches rather than the least-derived base,
and multiple inheritance makes the question need real layout modelling.
Reuses abi_analysis's XbeFile, so it needs no analysis JSON and can run
straight after xbe_parser.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BuW5WGcXFFrLAYEfvCNGs1
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.
Add the extended swizzled/LIN formats (float, 16/32-bit pairs, 10-bit, depth, DXN/DXT3A/DXT5A/CTX1) with distinct compact values, wire them through DXGI mapping, bpp, row-pitch and swizzle classification, and implement software channel-swap conversions (BGRA->RGBA for A16B16G16R16/A32B32G32R32, A/R field swap for A2R10G10B10/X2R10G10B10).
Support float3/float4 vertex texcoords via D3DFVF_TEXCOORDSIZE* in both the fixed-function FVF path (d3d8_shaders.c) and the native-VS input-layout path (d3d8_vsh.c); add d3d8_GetCurrentFVF.
Add tests/d3d8_smoke: an offline harness that compiles the real d3d8_resources.c + d3d8_swizzle.h with device-accessor stubs, exercising to_dxgi/bpp/predicates, swizzle round-trip, and the channel-swap conversions. Fixes an L6V5U5 sign-extension bug (5-bit V/U now cleanly sign-extends into R8G8_SNORM at upload).
Widens what can be compared against a real title from 17 functions to 37, and
the widening immediately found a bug.
**Pointer arguments are supplied rather than refused.** Some arguments now
point into a scratch buffer both sides see identically, and the buffer is
compared afterwards, so a function that writes is checked on what it wrote and
not merely on what it returned. Refusing every function that dereferences an
argument was most of what kept the set tiny.
**Callees are lifted too.** Seeding only from `push ebp; mov ebp, esp` finds
the framed functions and stops there; an FPO callee has no such prologue, so
its caller was dropped for calling into the unknown -- which is most of them. A
direct call target is a function start by definition, so those are followed,
and a function is admissible only once its whole call tree is. Extending a
function's extent past its first `ret` mattered as much: stopping there
truncates anything with a block below the exit, which then looks like it jumps
outside itself.
**fnstsw did not model C2, the unordered bit.** An x87 compare against a NaN
sets C3, C2 and C0 together, and `fucompp; fnstsw ax; test ah,44h; jp` is how
this era's CRT asks "is this a NaN". Reporting "equal" answered no every time,
so every float classification in a title took the wrong branch. The lifter's
own comment had assumed non-NaN maths was enough; Crimson Skies' float
classification is the counter-example, and it found itself. RECOMP_FCMP now
returns a fourth state and fnstsw emits 0x4500 for it.
**Surviving hostile code.** Executing a title's code with arguments it never
expected cannot be made safe in-process, so the damage is bounded instead: the
native call runs below a 32 KB stack gap walked a page at a time (jumping past
leaves the guard page unhit, and the resulting fault cannot be delivered --
the process dies before any handler runs, looking exactly like the lifted code
crashing; switching to a private stack buffer fails differently, with
STATUS_BAD_STACK, because an exception whose esp is outside the thread stack
cannot be unwound), the image is restored from a pristine copy before every
run, and when something still brings the harness down the runner reads its
progress markers, quarantines the casualty and re-runs.
**Two more state divergences, both mine, both convincing as bugs first.**
`finit` resets the x87 control word to the hardware default while the model
holds 0x027F, so anything reading it -- the _control87 family -- disagreed. And
both stacks are now filled with 0xCD: a function reading an uninitialised local
otherwise saw this process's leftovers on one side and ours on the other, and a
whole title's worth of functions reported mismatches over values neither side
had been given. Poisoned, they fault on the poison and are skipped instead.
Results: Burnout 3 37 functions / 161 vectors clean, Blood Wake 39 / 44 clean,
Crimson Skies 35 / 227 with two functions still diverging -- not yet explained,
recorded as open rather than dismissed.
pytest tools/: 142 passed. 2,599 snippet vectors and 211 whole-function
vectors, 0 mismatches.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PZDe6qTWAvohfDtYXbpRyM
py -3 -m tools.conformance --xbe "path/to/default.xbe"
The corpus tests code we compiled. This tests the code a title shipped -- and
the oracle gets better again, because Xbox code is 32-bit x86 and this harness
is a 32-bit x86 process. The game's machine code is not merely liftable, it is
executable. Map the XBE where it was linked for, call one of its functions
directly, run the lifted C over the same arguments, compare.
No game files are included, and none are needed for the rest of the suite; the
phase only runs when pointed at an XBE you own.
**Choosing what is safe to call.** Executing arbitrary game code in your own
process is not automatically safe, so candidates are selected mechanically: a
`push ebp; mov ebp, esp` prologue and a plain `ret` (never `ret imm16` -- a
stdcall callee cleans a number of argument bytes we would have to guess, and
guessing wrong corrupts the caller's stack); no `call`, so nothing reaches the
kernel or an address outside the image; every memory operand either
esp/ebp-relative or an absolute address inside a mapped section, so it cannot
dereference an argument we invented; no fs: access, no string operations,
nothing privileged; and nothing that lifts to a bare comment. Both calls run
under an exception guard, and the native side is wrapped in pushad/popad so a
function that fails to restore a callee-saved register fails its comparison
rather than corrupting the harness.
On Burnout 3 that is 17 functions out of 1,671 prologue sites. Strict, but
those 17 are genuinely verifiable.
**Both sides have to start from the same state**, and getting that wrong
produced two convincing false failures before it produced any real one:
- A `void` function never writes eax, so the native side returned whatever the
caller left there while the lifted side began at zero. The call now enters
with every GPR zeroed, which needs an indirect call through a global so eax
itself can be cleared.
- Plenty of this era's maths helpers take their argument in st(0) rather than
on the call stack, and an empty x87 stack is not neutral: the hardware yields
the indefinite value where the model yields 0.0. A Burnout 3 float-to-int
helper "failed" on every vector over an input neither side had been handed.
Both sides now get the same value in st(0).
The guest register names also have to be uncovered around the inline assembly:
RECOMP_GENERATED_CODE makes `eax` mean `g_eax` in that translation unit, and
the rewrite reaches into __asm blocks too.
Results, all zero mismatches: Burnout 3 (17 functions, 29 vectors), Conker
(34 / 42), Crimson Skies (9 / 23), Blood Wake (6 / 22).
Unchanged elsewhere: pytest tools/ 142 passed; 2,583 snippet vectors and 211
whole-function vectors, 0 mismatches.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PZDe6qTWAvohfDtYXbpRyM
The corpus previously took bytes from the .obj, which meant it could only ever
hold leaf functions with no external references: in an unlinked object every
reference outside the function is still zero, waiting for the linker, and
lifting those bytes gives confident nonsense. Jump tables, float constants and
CRT helpers -- what real code is made of -- were all out of reach.
Now the corpus is linked into a DLL at a fixed base with relocations stripped,
and functions are lifted out of the linked image. The addresses are final, so a
jump table, a .rdata constant and a call to __allmul are just numbers. The
harness maps the image where it was linked for with VirtualAlloc, so a guest
address is a host address and the lifted code reads the real bytes. That is
also the shape a real XBE arrives in, so this is the pipeline a port uses
rather than a special case.
Callees are lifted too: the runner follows every direct call and tail jump out
of a corpus function and lifts what it reaches. __allmul is now lifted and
verified alongside the corpus. Anything still referenced and undefined gets a
stub that reports itself and fails the run, so a call that went nowhere cannot
pass silently.
**bt / btr / bts / btc were unhandled** and lifted to a comment, so the bit was
silently left alone. 386 instructions, so real Xbox code has them; found once
the corpus started lifting the CRT float-to-int helper, which uses btr to clear
a rounding-control bit of the x87 control word -- the _control87 shape, not an
exotic one. Snippet cases added so the unit suite covers them too.
The runner now also reports any instruction that lifted to a bare comment.
Those are invisible to the comparison -- an unhandled instruction usually
leaves the result register alone, so both sides can agree while the lift does
nothing. That report is what diagnosed the gap below, and it did it unprompted.
**Float-to-int is deliberately not in the corpus.** MSVC lowers it to __ftol2,
whose modern LIBCMT implementation branches on __isa_available and uses
`fisttp` on the fast path -- an SSE3 instruction. The Xbox is a Pentium III: no
SSE3, and its XDK CRT's __ftol is plain x87. Comparing against the host's
helper measures this machine's CPU dispatch, not the lifter, and the two sides
cannot even agree which branch to take: the native side has a CRT that ran its
startup, the lifted side reads the image's initial value. Recorded in
corpus.py with the reasoning rather than quietly dropped.
Switch statements now lift correctly through their real .rdata jump tables --
seven entries, seven gotos, verified against the compiled original.
pytest tools/: 142 passed. Conformance: 2,583 snippet vectors and 211
whole-function vectors, 0 mismatches.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PZDe6qTWAvohfDtYXbpRyM
Phase two, and ps3recomp's lift_selftest.py shape: compile a corpus of C with
the target compiler, lift the machine code back through the real
FunctionTranslator, and run the lifted C against the original over the same
arguments. Snippets test instructions someone thought to write down; this tests
what the optimiser actually emits.
It found two bugs in the first sitting, both from a single function.
**Flag state followed address order, not control flow.** FunctionTranslator
threaded the cmp/test state from one block to the next in *address* order,
which is only correct for fall-through. An optimising compiler routinely lets a
jcc consume a comparison from a block that is not its neighbour in memory --
and the block that is its neighbour often ends in an `add`, which clobbers
flags. The condition then came out as a perfectly plausible test of the wrong
thing. State now propagates along predecessor edges and only when every
predecessor agrees; a block with disagreeing predecessors, or one reached by a
back edge not yet walked, inherits nothing and falls back rather than guessing.
**js/jns evaluated the sign at 32 bits.** SF is the sign bit of the result at
the *operand's* width. `test dl, dl; jns` asks about bit 7, but the lifted
condition tested the zero-extended byte as an int32, so 0x80-0xFF looked
positive and the branch went the same way every time. Exactly the defect the
width-aware CMP_L/CMP_G fixed for the signed compares -- js/jns were missed at
the time. `cmp` has it too, since the difference must be truncated before its
sign is taken.
Both surfaced from an eight-iteration loop over `((a>>i)&1)`, which /O2 unrolls
into `test dl, 1<<i` + `je` with a final `test dl, dl` + `jns`. No phase-one
snippet produced that shape, because nobody thought to write it. Kept as
c_bittest_loop, with matching snippet cases so the unit suite catches it too.
**/arch:IA32 on purpose.** The Xbox CPU is a Pentium III -- SSE1, no SSE2.
Modern MSVC defaults to SSE2 and puts doubles in XMM, which no real Xbox binary
contains; without this the corpus would test instructions the target cannot
execute and skip the x87 paths every title actually uses. (Compiling at the
default did surface that SSE2 `movsd` is lifted as the *string* movsd and that
the scalar-double ops use float lanes. Left alone deliberately: a Pentium III
cannot execute either, so it is not a bug against this target.)
**Only leaf functions with no external references**, because an unlinked .obj
still has zero where the linker will patch and lifting that is confident
nonsense. The runner inspects each function's listing and refuses one that
references a global, an OFFSET, a .rdata literal or a call, naming the symbol
that disqualified it -- rather than trusting the corpus to stay well-behaved.
c_mul64 and c_int2dbl are skipped on exactly that basis: MSVC lowers 64-bit
multiply and float-to-int through CRT helpers. A skip is reported, not failed.
lift_function saves and restores the process-global section map. Leaving a
synthetic one installed silently changes what every later caller thinks the
address space looks like -- under pytest, the rest of the suite, which is how
it announced itself.
pytest tools/: 142 passed. Conformance: 2,283 snippet vectors and 157 function
vectors, 0 mismatches.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PZDe6qTWAvohfDtYXbpRyM
Extends the differential suite from 26 integer cases to 59, adding 21 x87 and
12 SSE cases: 2,043 vectors, all passing. It found three live bugs, every one
of which the existing string-comparison tests were happy with.
**fxch st(i) was a silent no-op.** Capstone reports fxch with BOTH operands --
(st(0), st(i)) -- and it is the only x87 form that does; fadd, fcom, fld and
fstp all arrive with the explicit register alone. The handler read operand 0,
got the implicit st(0), and emitted `fp_top() = fp_top()`. Every fxch in every
title exchanged st0 with itself and did nothing. The existing unit test could
not see it: it asserted on emitted text, and the emitted text looked plausible.
**fnstsw did not model TOP.** The status word carries TOP in bits 11-13, which
land in AH bits 3-5, and we do model TOP -- it is g_fp_top. Leaving it out made
`fnstsw ax` disagree with the hardware on every read taken while the stack was
non-empty. The `ax` form was also writing only AH; the instruction writes all
of AX.
**stc/clc/cmc were unimplemented** (found by the integer cases in the previous
commit, fixed here alongside the rest).
**What is compared.** x87 compares stack *depth* as well as values, because
most x87 bugs this project has had were pop-count bugs rather than arithmetic
bugs: a handler that forgets to pop leaks a slot, everything after reads st(i)
one off, and the first value still looks right. SSE compares all eight
registers lane by lane and bit-exactly, including -0.0 against 0.0 -- exactly
the difference a mis-implemented MINPS tie-break produces.
**Precision.** The x87 precision control is set to double (53-bit) rather than
the hardware default of extended (64-bit). Our model holds the stack as C
double, so at extended precision the hardware carries more bits than the model
can and add/sub/mul/div/sqrt would disagree in the last place for reasons that
have nothing to do with lifting. At PC=53 those five are correctly rounded on
both sides and must match bit-exactly. Only the transcendentals still diverge
-- the x87's polynomial and libm's are different implementations -- and those
three cases carry an explicit per-case tolerance rather than a blanket one, so
a genuinely wrong answer still fails. That is the whitelist pillar of
ps3recomp's methodology: name the real divergence, do not hide it.
The fp_push/fp_pop/fp_top/fp_st macros move to module-level constants in
translator.py and the harness emits those same strings. A harness with its own
copy would keep passing after the translator's changed, which is the dangerous
direction to fail in.
fxch also gets a unit test, so the regression is caught on Linux where the
conformance suite cannot run.
pytest tools/: 142 passed. py -3 -m tools.conformance: 2043 vectors, 0
mismatches.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PZDe6qTWAvohfDtYXbpRyM
The existing lifter tests compare emitted *text* against an expected string.
That catches a rewrite that changes the form and nothing else, because nothing
in the loop ever executes either side. Every bug in the v0.6.0 changelog was of
the kind that passes such a test: `repe cmpsb` reporting equal regardless of
input, `movaps` moving 4 of 16 bytes, a signed compare at the wrong width.
This is ps3recomp's methodology, which transfers almost intact -- but it gets
stronger here, and that is the point. ps3recomp has to check its PPU lifter
against a *model* of PowerPC, because the host is not a PPC; a model can be
wrong in the same places the lifter is. We target x86 and run on x86, so the
host CPU is the reference implementation. There is nothing to disagree with.
Per case, `tools/conformance` writes the snippet into an MSVC `__asm` block
bracketed by nop markers, compiles with /FAc, reads the exact bytes back out of
the listing (MSVC is the assembler -- we never hand-encode), lifts those bytes
through the real Disassembler + lift_basic_block, and runs both the native
function and the lifted C over the same inputs.
26 cases, 1,560 vectors, currently all passing. Inputs sit on the boundaries
that separate a correct implementation from a plausible one -- 0x7F/0x80/0xFF,
0x7FFF/0x8000, INT_MIN, -1 -- since a bug that evaluates an 8-bit operand at 32
bits is invisible at 5 and obvious at 0xFF.
It found one real gap: **stc/clc/cmc were unhandled** and lifted to
`/* TODO: stc */`, so the carry a following adc/sbb reads kept whatever the last
arithmetic left in it. MSVC emits these around multi-word arithmetic and the
"return a bool in CF" idiom. Now lifted, and only when something downstream
consumes CF -- which is also the only time the enclosing function declares _cf.
It also found two bugs in itself first, both of which produced confident false
reports, and both recorded in the doc because they generalise:
- Lifting per-instruction instead of per-block. The peephole that turns
cmp + jcc/setcc/cmovcc into a real condition lives at block level, so
lift_instruction reports a stale `_flags` the block pass never emits. It
claimed 22 failures in 60 on the first case; the lifter was correct.
- The .cod byte column wraps after five bytes onto a continuation line with no
address. Missing that silently dropped every instruction longer than five
bytes -- every 32-bit immediate. A dropped instruction is the exact failure
this tool exists to catch, so having it in the harness was worse than having
no harness.
The rule underneath both: if the harness does not drive the lifter exactly as
the recompiler does, it is testing a path that does not ship.
Runs under pytest too, skipped rather than failed without a 32-bit MSVC, so the
suite stays meaningful on Linux. pytest tools/: 141 passed.
x87/SSE state comparison and whole-function lifting (ps3recomp's
lift_selftest.py shape) are the natural extensions; both are noted in
docs/technical/conformance-testing.md.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PZDe6qTWAvohfDtYXbpRyM
The README had drifted from the code, and in one place contradicted the
repository's own documentation.
**Claims that were wrong, now measured:**
- "the first known static recompilation project targeting the original Xbox" --
contradicted by docs/technical/ms-fusion-recompiler.md in this same repo.
Microsoft's Ficl/Fission got there first, shipping Xbox back-compat on the
360. Reworded to "first *public*", with the pointer to our own study of
theirs.
- Kernel coverage was "115 of 366 ordinals resolved, 55 with dedicated
bridges". Counted: 152 of 371 routed, 112 with bridges.
- Every per-module line count was stale (kernel 8,298 -> 11,128; d3d 7,018 ->
8,838; apu 3,918 -> 4,168; nv2a 4,778 -> 4,892; input 212 -> 360).
- Burnout 3 was still listed as "playable ... main menu at 60fps" three
sections after a note explaining that build leaned on hand-written
scaffolding. Says so in one place now, and retires the claim until the
recompiled path earns it back.
- "handles ~95% of instructions" is not measured anywhere. Replaced with the
honest signal: an unhandled instruction lifts to a bare comment, so grep the
generated output.
- The Quick Start skipped `tools.abi_analysis` entirely -- which is exactly what
issues #1 and #2 both walked into. Now step 6, with a note on what silently
degrades if it is skipped.
- Dependencies omitted pytest; the tool list omitted five tools that exist.
**Versioning.** v0.6.0 "Credit Where Due", with a changelog back to v0.1.0
reconstructed from commit dates rather than invented -- the feature groupings
and months come from the actual commits that landed them. Per-item attribution
follows ps3recomp's convention, so a contributor can find their work by name.
Replaces the undated "Recent Changes" bullet list, which had no ordering and
no way to tell what shipped when.
**Docs.** "How The Key Pieces Work" restated register-model.md,
memory-layout.md and indirect-calls.md badly and in less detail than the real
documents (246, 303 and 386 lines respectively), and its code snippets had gone
stale -- `PUSH32(val)` has been `PUSH32(sp, val)` for a while, and the register
globals are thread-local now. Replaced with a short index.
The two NV2A sections had no document to point at, so their content moves to
docs/technical/nv2a-shaders.md rather than being dropped.
Also removes four "(NEW)" markers that have survived several releases.
README 494 -> 553 lines, of which the changelog is 120.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PZDe6qTWAvohfDtYXbpRyM
New tools/fusion/module.py (FusionModule): white-room parse of a recompiled
xefu_*/xeo3_* module -- source/title/build from version resources, exports,
PrecompiledSymbolTable (exact), and the .rdata address-map guest column. Shared
foundation for the signature-DB / coverage-oracle / HLE-worklist work.
Building it caught an error in the just-pushed corpus doc: I'd taken Crimson's
build from the emulator-layer xefu.xex path in the single-title report, not the
game module's own resource. The game modules are four DISTINCT, monotonically
increasing builds -- 20F90F (Crimson) < 20F914 (Blinx) < 20F917 (Conker) <
20F919 (FF) -- which is a cleaner finding than "two share 20F914". Also relabel
the id row "build-path id" (Crimson's 4D530851 differs from its XBE cert id).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Extends the single-title Crimson Skies teardown into a four-title corpus
(Blinx, Crimson Skies, Conker L&R, Fuzion Frenzy -- the only titles Microsoft
has shipped through this pipeline). White-room: pefile/capstone on version
resources, exports, PrecompiledSymbolTable, and the .rdata address map. No MS
code copied.
Findings a single title can't show:
- Uniform recompiler: identical 4-export ABI, byte-dense single tier, same map
delta histogram (97.6-98.0% coverage) on all four. Nothing special-cased.
- Build drift: btsdx 20F914 (Crimson, Blinx) / 20F917 (Conker) / 20F919 (FF).
The recompiled xb1krnl is byte-identical for Blinx/Crimson/FF but Conker
ships a distinct build of it -- deterministic per compiler build, not across.
- Networking is a clean symbol fingerprint: CXo/CXnIp/CXnSock present exactly
as multiplayer capability dictates (Crimson 485, Conker 615, Blinx/FF 0).
Direct triage signal -- a title with no CXnIp can't hit Halo's XNet wall.
- Engine fingerprints: Conker is C++/STL-heavy with few named D3D; Blinx/FF
lean on XGRAPHICS. Every title recompiles its own DirectSound verbatim; the
only kernel-shaped names are Rtl*Heap. Confirms the HLE line sits at the
xboxkrnl boundary on all four.
Also documents the PrecompiledSymbolTable header layout (calibrated against the
report's Crimson ground truth) so the parse is reproducible.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
The full IDA pass over xefu_c954bd37 (default.xbe -> x64, 41 MB) finished
after the teardown was written -- it had used the .pdata entry count (76)
in the meantime. IDA independently finds 105 functions for 21 MB of
.text, against 2,246 for the PPC xboxkrnlcf at a fifth the size:
same flat-arena signature, now corroborated by a second tool.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Phase 2 routing. The kernel bridge routes ordinals with one hardcoded
table, the ordinal ABI of the XDK it was written against. Titles built
with a different XDK number the same kernel functions differently, so
swapping such a title onto the shared kernel misroutes it -- Burnout 3
(XDK 5849) exited via HalReturnToFirmware during engine setup, where its
ordinal 49 is actually HalRequestSoftwareInterrupt.
Rather than refactor the three hardcoded tables (dispatch, arg-size,
data-export), this adds one translation layer. xbox_kernel_set_ordinal_remap
takes map[title_ordinal] = canonical_ordinal; xbox_kernel_bridge_init
applies it the moment it reads the ordinal, so all three lookups see the
canonical number. Identity by default -- a title that sets no remap, or
whose XDK already matches, is byte-identical. Verified: Halo still exits
3 at render_cameras.c:458, unchanged.
tools/kernel_audit/gen_ordinal_remap.py builds a title's map by matching
each function it imports to the ordinal the kernel's own table gives that
name. Halo (3911) and Crimson (5659) remap nothing -- they ARE the
canonical XDK. Burnout 3 remaps 47 and leaves 3 its parser could not name
as identity.
Result on Burnout 3, on xboxrecomp's kernel: it no longer exits during
engine setup. Ordinal 49 resolves to HalRequestSoftwareInterrupt (benign
stub), xbe_entry_point returns normally, the title enters its host loop
and begins loading crash-mode HUD textures. The specific routing blocker
is fixed.
One layer remains, and it is not routing: the init worker
PsCreateSystemThreadEx spawns runs but does not advance game state (zero
kernel calls from the worker stack region), even though xboxrecomp's
bridge_thread_main and Burnout 3's thread wrapper set the thread up
almost identically. That is a narrow threading-execution integration
difference, the next thing to chase.
This also corrects the record: Burnout 3's table is not "buggy", it is a
different XDK's correct table. xboxrecomp is ahead on kernel code, not on
the routing table, and the reunification keeps both titles' tables.
test_gen_ordinal_remap.py covers the generator; all kernel audit tests
pass.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Attempted the Phase 2 kernel swap and it produced a genuine, correcting
finding. The mechanical swap works: Burnout 3 builds and links against
xboxrecomp's kernel (repoint two add_subdirectory lines), the
0xFE000000+i*4 dispatch contract is identical, and Phase 1's SPAWN mode
drives its frame pump -- the first PsCreateSystemThreadEx spawned a real
thread and the entry returned, exactly as designed, with zero "no bridge"
warnings.
Then the game exited during engine setup: it calls kernel ordinal 49,
which is HalRequestSoftwareInterrupt in Burnout 3's XDK (5849, 2004) but
HalReturnToFirmware in the older XDKs xboxrecomp's table was built for
(Halo 3911/2001, Crimson 5659/2003). xboxrecomp routed it to
HalReturnToFirmware and ExitProcess ran.
This corrects the earlier framing in this very doc. I had called Burnout
3's table "shifted/buggy" with "50 misroutings xboxrecomp fixes". That
was backwards. Burnout 3's routing is correct for Burnout 3's XBE; the 50
differences are two XDK ordinal ABIs, not one bug. Evidence: BO3's
known-good run never calls HalReturnToFirmware; it calls ordinal 49
during engine setup where a software interrupt is what belongs; and it
boots and renders on its own table. xboxrecomp is ahead on kernel *code*
(fixes, audit tooling, Phase 1 threading), not on the routing *table*.
So Phase 2 is not a CMake edit -- it is making kernel_bridge route
ordinals from per-title data (keyed by the title's XBE import analysis)
instead of one hardcoded switch, so the same kernel serves any XDK and
every title keeps its own table.
The Phase 2 branch is reverted; Burnout 3 is back on its working kernel.
Phase 1 (committed, Halo-verified) stands. Doc updated end to end: the
one-line finding, the routing section, the plan, and the honest summary.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Phase 1 of the Burnout 3 reunification (docs/technical/burnout3-reunification.md):
the runtime swap was gated on the two kernels having made opposite threading
choices. xboxrecomp runs the first PsCreateSystemThreadEx inline and the game
drives its own loop (Halo, Crimson Skies); Burnout 3 returns from its entry after
spawning an init thread and drives the per-frame tick from the host. Neither
kernel could build the other title. This makes xboxrecomp's kernel do both,
defaulting to the existing behavior so nothing changes for current titles.
Added, all additive:
- XBOX_WORKER_STACK_* + xbox_worker_stack_alloc/free (verbatim from the fork):
a guest stack for the host's own thread to call recompiled code from, which
is how a host-tick-driven title pumps its frame tick -- the host thread's
g_esp starts at 0, so it needs a slice before it can PUSH32 into a call.
- xbox_thread_debug_handle + g_game_thread, set when the bridge spawns a
thread, so a host watchdog can sample the game thread.
- xbox_SetThreadMode(XBOX_THREAD_MODE_SPAWN): every PsCreateSystemThreadEx
becomes a real thread so the entry can return and the host drives. Default
INLINE is the historical first-call-runs-the-game behavior.
A default-model title calls none of this, so the worker region is unused address
space and the SPAWN path is never reached -- inert by construction.
Verified:
- Halo builds and runs byte-identically: same exit=3, same milestones, same
render_cameras.c:458 assert. The primitives change nothing for it.
- The allocator passes a standalone check: 16 distinct slices, exhaustion
returns -1, a freed slice is reusable, tops are 16-byte aligned with the
right stride.
- Burnout 3's exact main.c threading API (xbox_worker_stack_alloc,
xbox_thread_debug_handle, XBOX_WORKER_STACK_TOP, xbox_SetThreadMode) compiles
against xboxrecomp's headers.
- All 8 tool test suites pass.
Phase 2 is wiring this under a real kernel swap, and confirming empirically
whether Burnout 3's init thread must run concurrently (SPAWN) or INLINE suffices.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Went to do the runtime library swap (point Burnout 3 at xboxrecomp like
Halo does) and found it is gated on a real architectural divergence, not
staleness. Recording the finding and the sequenced path so the next pass
does not re-derive it.
Toolkit half: reunited and proven. Burnout 3's fork had one feature
xboxrecomp lacked, --exclude-manual, now upstreamed; xboxrecomp's tools
generate Burnout 3's code end to end (22,893/23,010, 0 failed).
Runtime half: every library diverged substantially in BOTH directions --
after the extraction each grew mechanisms its own game layer depends on.
The hard gate is threading. Burnout 3's PsCreateSystemThreadEx makes real
Win32 threads and its frame-pump drives the game tick on a worker-stack
slice; xboxrecomp runs the start routine synchronously because that is
what Halo needs. Neither kernel is a superset of the other, so a swap
breaks one title or the other. And Burnout 3's kernel is on a shifted
export table that misroutes 50 of 147 imports -- so the kernel is where
the most correctness is waiting and where the swap is hardest.
The plan sequences it: Phase 0 retire the tools fork (mostly done),
Phase 1 reconcile the two threading models behind a per-title mode (the
gate, delicate because it touches two shipping titles), Phase 2 the
kernel swap that fixes the 50 misroutings, Phase 3 the nv2a/d3d pipeline
(most coupled, decide last), Phase 4 audio/input.
The honest summary: "get Burnout 3 on the new xboxrecomp" is half true
today and the other half is design work on a path two titles depend on,
not a CMakeLists edit -- and worth doing without throwing away the
worker-stack frame-pump Burnout 3 earned the hard way.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
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>
Microsoft resolves an indirect branch with one indexed load off a table
keyed by guest address -- `jmp qword ptr [r9 + r8*8]`, no compare, no
miss path. recomp_lookup was a binary search over every translated
function: ~13 branches on every vtable call in the title.
recomp_dispatch_init() builds a flat recomp_func_t array indexed by
(va - base) from the table the generator already emits, and recomp_lookup
uses it when present. Halo 2276: 2,363,492 entries, 18.0 MB, which is the
same trade Microsoft makes at 20 MB.
Three properties make this low risk:
- recomp_lookup keeps its signature and the binary search stays in the
file. If init is never called, or calloc fails, lookup silently keeps
searching. No caller, macro or generated call site changes.
- It does NOT pre-fill manual overrides. Those cannot be enumerated
portably, so RECOMP_ICALL still consults recomp_lookup_manual first and
this only replaces the search it used to fall through to. Priority
order is therefore unchanged by construction.
- The bounds check is a single unsigned compare: a VA below the base
wraps to a huge offset and is rejected by the same test, so there is no
separate lower bound to get wrong.
test_dispatch_flat.py compiles and runs the generated C rather than
grepping it, because an off-by-one in the index or a signedness slip in
the bounds check would survive any text assertion. It checks the flat
table and the search return identical answers for 17 addresses including
below-base, one-past-last, 0xFFFFFFFF and the kernel thunk range.
Also adds docs/technical/ms-fusion-adoption-plan.md: every finding from
the Crimson Skies teardown, with status and the evidence for the ones
deliberately not being done -- block-granular entry points (fixes ~1
address here), full block-threading (cost), flag booleans (no measured
defect), an interpreter fallback (residual too small since fd71a0e),
register/flag hardware mapping (unreachable from C). Recording why
something was rejected is worth as much as doing it; it stops the
question being re-opened from scratch.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Ran the loop on Halo 2276 end to end. It works, and seeding the raw
measured set made the title crash EARLIER than before.
Round 1 measured 67 distinct indirect-branch targets, 25 unresolved, 24
of which were not known function starts. Seeding all 24 closed all 24 --
8,849 -> 8,874 functions -- and the resulting build segfaulted
(exit=139) on a read through 0xFFFFFFF3 before reaching the
render_cameras.c:458 assert it used to reach.
That failure presents as a win: distinct assert sites went 1 -> 0. Zero
asserts because execution died before the code that asserts, which is
the exact trap run.sh warns about.
The 4 offenders were the only observed targets that were not 16-aligned.
Filtering to 16-aligned restored the original milestone and exit code,
and round 2 confirmed the diagnosis independently: those same 4
addresses were still the only unresolved targets afterwards, so they are
not function starts the detector missed -- they are garbage landing
inside .text, most likely uninitialised vtable reads. The RECOMP_ICALL
range check is trying to catch that class and cannot, because the
garbage is in range.
So: adds a `seeds` subcommand that writes a filtered seed file, --align
16 by default. Measurement and action are now separate concerns. The
database still records everything, because discarding an observation is
unrecoverable, and unaligned *resolved* targets do legitimately exist
(cc_boundary, tail_jump detection finds some).
Two rounds, cumulative:
targets observed 67 -> 71 (+4: execution reached further)
resolved 42 -> 66
unresolved in the run 25 -> 5
gaps not a function start 24 -> 4 (exactly the 4 filtered out)
Also fixes a bug in the first cut of `seeds`: it filtered against the
current functions.json, which is circular. Seeds are an input to the
pass that rewrites functions.json from scratch, so an indirect-only
target is "already known" on run N+1 only because it was seeded on run
N, and dropping it un-converges the loop. It emitted 0 seeds.
Not explained: the filtered build makes 6 CreateTexture calls where
baseline made 12, with identical total [D3D] count, assert site and exit
code. 20 previously-stubbed indirect calls now do real work so the path
legitimately changed, but that is a hypothesis, not a finding.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Static analysis cannot see where a vtable call goes; running the title
can. This records the targets the title actually reaches and feeds them
back as function-detection seeds, so successive passes converge instead
of guessing once.
Local equivalent of the two feedback inputs Microsoft's recompiler
takes: VirtualDispatchTraceFiles (recorded indirect-branch target sets)
and UpdateEnlightenments:true (a persisted analysis database the
compiler rewrites every build). See ms-fusion-codegen-teardown.md.
Runtime (opt-in via RECOMP_ICALL_FEEDBACK; a default build compiles the
TU to nothing and RECOMP_ICALL_OBSERVE discards its arguments without
expanding them, so the SEEN_* constants need not exist and src/kernel
need not be on the include path):
- flat byte array indexed by guest VA, OR'd with 1=resolved /
2=unresolved from all three dispatch macros. One subtract, one
compare, one OR on the hottest path in the generated code.
- a byte array not a bitmap: a byte store needs no read-modify-write,
so concurrent recompiled threads cannot lose each other's writes,
and 8 MiB is not worth a CAS loop. Dedup is free.
- dumps plain text, one record per line, because it is written from a
possibly-crashing process and a truncated file must still parse.
Tool: tools/recomp/icall_feedback.py merge/report. The database is
written directly in the format tools/disasm --seed-functions already
accepts, so there is no conversion step and no new pipeline stage.
The database is CUMULATIVE. A target observed in an earlier run is never
dropped because a later run did not reach it -- that is what makes the
loop converge, since each pass translates more code, which lets the
title reach further, which surfaces more targets. Flags accumulate
rather than overwrite so an unresolved-then-resolved target stays
visible as both instead of being silently repaired.
Reuses the existing --seed-functions input rather than adding a stage;
complements analyze_unresolved.py rather than replacing it (seed the
measured set first, then classify what the detector still cannot place).
Verified: unsigned bounds check rejects VAs below base without wrapping
into the array, above the window, and kernel thunks at 0xFE000000+.
Compiles clean with and without the feature macro.
tools/recomp/test_icall_feedback.py covers cumulativeness, flag
accumulation, truncated dumps, and direct loadability as seeds.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Followup to the first writeup, using IDA Professional 9.1 headless
(idalib) + Hex-Rays. Still white-room: no MS code, IR, or output reused.
The finding that reframes our roadmap: Microsoft ships TWO different
recompiler architectures from one toolchain, and the one they use for a
PowerPC guest is the one we built for an x86 guest.
PPC -> x64 : 2246 real host functions, 98.67% of .text, real call/ret,
1600 RUNTIME_FUNCTIONs. Guest GPRs in a memory context
block at rbx, movbe on every access (big-endian guest),
CR0 decomposed into four separate bytes at [rbx-64..-61]
-- in the OPTIMIZED tier, not just the fallback.
x86 -> x64 : 66 "functions", one of them 832,546 bytes. The 41MB game
module is 76 RUNTIME_FUNCTIONs whose largest is 16.4MB.
One flat arena, one host frame, jmp-only control flow,
guest regs in host regs 1:1, flags free.
Our design matches the column where MS was forced into it by the guest
architecture, not the column matching our actual guest. That is a
consequence of emitting C, and it cleanly separates the bug classes that
are inherent (registers in memory, flag synthesis) from the ones that
are not (function-granular entry, load-bearing boundary detection,
single tier, no feedback loop).
Reranked next steps accordingly. The one architectural change worth
making collapses two earlier items into one: make the translation unit a
basic block and dispatch every inter-block edge through a flat table
indexed by guest VA. Fb's 119,935 entries for 488KB of guest code is the
proof that per-instruction entry density is affordable.
Also records two GPU ideas worth stealing independently of the lifter:
async PSO preloading from the persisted shader cache, and a data-driven
per-title texture-format override table.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Reverse-engineered the design of Ficl/Fission (ficompiler.exe, Phoenix
backend) from the retail Crimson Skies BC package, to compare against
our own recompiler and decide what to adopt.
No Microsoft code, IR, or output is copied or reused -- this is a
design-level writeup derived from PE inspection and disassembly of
publicly distributed retail binaries.
Findings that change what we should build:
- They map guest->host at BYTE granularity (97.6% of the code span,
2.5M entries / 20MB) and dispatch indirect branches with a single
jmp [table + guest_eip*8]. Function boundaries are never needed.
- Guest calls push the REAL guest return address, then jmp. We push a
dummy 0, which is a latent bug for __SEH_prolog and mov eax,[esp].
- Two output tiers: Pri (fused, branch-target entry points) and Fb
(one addressable block per guest instruction). For variable-width
x86 they instead use a dense map plus cold recovery stubs -- which
is the case that applies to us.
- The runtime escape hatch is ~12 helper slots / 18 kind codes, almost
entirely port I/O and preemption polling, not untranslatable opcodes.
- Their HLE line is xboxkrnl only: the game's own statically-linked
D3D8/D3DX/DirectSound/XAPI is recompiled verbatim (3106 named guest
ranges, 23% of code bytes) and graphics is emulated at register level.
- Codegen feeds back into itself: a persisted "enlightenments" DB plus
ETW traces and recorded indirect-dispatch target sets.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Complete rewrite of the D3D8 fixed-function shader pipeline:
- 4-stage multi-texture with all D3DTOP operations and D3DTA arguments
- Hardware T&L lighting (8 lights: directional/point/spot, Blinn-Phong)
- Vertex fog (linear/exp/exp2) with PS fog color blending
- Triangle fan and quad list to triangle list conversion
- 4MB ring buffer for DrawPrimitiveUP (no per-call buffer alloc)
- Multi-stage sampler binding (all 4 stages)
- NV2A stub headers for standalone toolkit builds
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
New technical deep-dive documenting the Xbox D3D8LTCG device context
structure (~16KB at 0x35D6A0) used by Criterion RenderWare games:
- Complete field map: PB ring management, render targets, transforms
- GPU read pointer trick (device+0x30 → device+0x2C) to eliminate spin loops
- D3D8LTCG stub calling convention reference (24 mid-entry functions)
- Device context initialization sequence for recompiled games
- xemu snapshot capture methodology
Applicable to any Xbox game using the D3D8LTCG statically-linked library.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
NV2A GPU:
- Upstream nv2a_pgraph_d3d11.c/h from burnout3: translates NV2A Kelvin
push buffer method calls to D3D11 rendering commands
- Upstream nv2a_pb_replay.c: push buffer capture and replay system
- Route NV2A method calls through PGRAPH translator in nv2a_core.c
- Update CMakeLists.txt to build new NV2A files
D3D8 textures:
- Add d3d8_swizzle.h: Xbox texture unswizzle (Z-order/Morton code)
for converting swizzled Xbox textures to linear D3D11 layout
- Integrate unswizzle into tex_UnlockRect upload path
- Add texture format mappings: A4R4G4B4, LIN_A4R4G4B4, A8L8, P8
Kernel:
- Add EEPROM support (ExQueryNonVolatileSetting) with NA/NTSC defaults
- Add SMBus/SMC (HalReadSMBusValue/HalWriteSMBusValue) returning
production values: version "P01", component AV pack, 40C temp
- Enhance AvSendTVEncoderOption: returns HDTV AV pack, 480p capable
- Register new ordinals in kernel_thunks.c
APU:
- Add global audio mute flag (g_audio_muted) for development testing
Documentation:
- Add docs/technical/gap-analysis.md: comprehensive comparison of xemu
vs xboxrecomp with prioritized feature gaps for Blood Wake/Wreckless
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>