Commit Graph

7 Commits

Author SHA1 Message Date
Diamond Lewis bb9ed2ed1f test(conformance): Run XBE and Corpus phases in Docker 2026-09-17 09:50:38 -05:00
sp00nz cc76f551bd conformance: pointer arguments and a call closure for the XBE phase
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
2026-08-28 13:36:11 -07:00
sp00nz f6d0c83d48 conformance: run a real title's own code as the oracle
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
2026-08-28 13:22:16 -07:00
sp00nz 81366d4a0c conformance: lift from a linked image, so real code works
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
2026-08-28 13:05:11 -07:00
sp00nz 4b35222564 conformance: lift whole compiled functions, not just snippets
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
2026-08-28 12:13:32 -07:00
sp00nz 81a791bafc conformance: compare x87 stack and SSE lanes, not just eax
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
2026-08-28 11:57:55 -07:00
sp00nz 3200511b73 conformance: check the lifted C against the real CPU
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
2026-08-28 11:43:55 -07:00