Files
sp00nz 42e34cd394 Merge the research branch into main
Brings `research/ms-fusion-recompiler` (75 commits: the Halo bring-up of PR #5,
the MS Fusion/Ficl recompiler study, the XISO and icall-feedback work) onto a
main that has meanwhile taken the five community PRs. Both sides had been
fixing the same subsystems, so most of this is choosing between two real
implementations rather than taking one wholesale.

**x87 -- research wins the body, main keeps the state model.** Both branches
rewrote the FPU lifter. The research one is the version that was validated
against a running title: it is operand-aware (`_fcom_rhs`, `_st_expr`,
`_st_index`), so `fmul [mem]`, `fadd st(0),st(0)`, `faddp st(i)` and the
reversed fsubr/fdivr all lift correctly, and it counts pops from the mnemonic
instead of emitting zero for every form. That is kept.

From #9 we keep the *state* model, which is the better one: the compare result
lives in the shared `g_fp_cmp` rather than a per-function `_fpu_cmp` local,
because a compare and the FNSTSW that reads it routinely land in different
generated C functions -- the research branch had run into exactly this and
worked around it by declaring the local more often. Also kept from #9:
`g_fp_control_word` modelling for `_control87`, `ftst`, and the `fi*` integer
forms (fiadd/fisub/fisubr/fimul/fidiv/fidivr), which the unified handler did
not cover and which had silently regressed to comments in the merge. `fnstsw`
now takes research's in-place AH form for `ax`/`eax` *and* keeps #9's 16-bit
status word for a memory or other register destination, which research dropped
on the floor.

`frndint` maps to `rint`, not `nearbyint`: FRNDINT rounds per the control
word's RC field and signals inexact, which is what `rint` does and what
`nearbyint` explicitly suppresses.

**Registers are thread-local everywhere.** The research branch had moved the
register file to `RECOMP_TLS`; #9 and #10 added plain globals. The merge left
`g_fp_top` declared twice with different types (`RECOMP_TLS int` and
`uint32_t`), which would not have compiled. One declaration now, TLS, with the
XMM registers given the same treatment.

The storage also moves to where the rest of the register file is defined
(`xbox_memory_layout.c`); the new-game template now declares it `extern`, as
its own comment always said it should. It had been *defining* g_fp_stack and
friends only because main's runtime did not.

**Fall-through and indirect calls.** Both branches independently fixed the
fall-through-into-the-next-function bug. #7's version is stricter -- it also
requires the target be a known function and not a block the caller already owns
via CFG recovery -- so the research branch's `falls_through` is dropped rather
than left to emit the tail call a second time. For indirect calls we take #7's
snapshot-target-before-push fix *and* research's real return address, instead
of #7's placeholder zero.

**Signed compares.** Keeps main's width-aware `RECOMP_SIGNED`/`RECOMP_FLAG_WIDTH`
over research's `SXV`. SXV takes each operand's own width, so an immediate
stays 32-bit: `cmp al, 0FFh` compared -1 against 255 and `cmp ax, 8000h`
compared against +32768. Narrowing to the min of the two widths gets both
right.

**Carry.** Uses `preserve_carry or self.needs_cf`. `needs_cf` is set exactly
when the function contains adc/sbb, which is exactly when `_cf` is declared, so
this is the conservative choice and cannot miss a case #8's propagation
analysis does not reach.

**LICENSE stays byte-identical to main.** The research branch prepended an LGPL
explanation to it; that risks breaking GitHub's licence detection, and the same
explanation already lives in NOTICE and the README.

**A test was silently disabling later tests.** test_fpu_branch replaced
`lifter._fmt_mem` at module scope and never put it back, so every test that ran
after it in the same process saw a stub -- which is why the SSE suite failed
only in a full run. It restores now via a decorator. That bug pre-dates this
merge; it only became visible once there were tests after it.

pytest tools/: 140 passed. The runtime is compile-verified: 44 lifted SSE and
x87 instructions (none falling back to comments) build clean under MSVC /W3,
and the SSE semantic harness still passes.

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

115 lines
4.1 KiB
Python

"""
Self-check for fall-through into the next function.
Run: py -3 tools/recomp/test_fallthrough.py
The disassembler splits a straight-line run of code into separate functions at
any address something else targets. A function's last instruction can then be an
ordinary one (or a conditional jump) that just runs off the end into the next
function -- x86 executes that fall-through. A C function body ends instead,
silently dropping whatever the next function does.
In Burnout 3 this was an 8-byte esp leak: sub_00013F6F (one `mov`, no terminator)
fell into sub_00013F75's shared `pop ebx; ret`. Split apart, the pop and the ret
never ran, so the caller sub_000165F0 restored ebx from the wrong slot and the
title's main loop (sub_00156400 -> sub_000165F0 while flag == ebx) exited after a
single iteration. The fix emits the fall-through as an explicit tail call.
"""
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", ".."))
from tools.recomp import config # noqa: E402
from tools.recomp.translator import FunctionTranslator # noqa: E402
BASE = 0x00010000
# mov cl, [0x004A1C77] -> 8A 0D 77 1C 4A 00 (6 bytes, no control transfer)
MOV_CL = bytes.fromhex("8A0D771C4A00")
# pop ebx; ret -> 5B C3
POP_RET = bytes.fromhex("5BC3")
# ret -> C3
RET = bytes.fromhex("C3")
# jmp $ (EB FE, to self, an intra-function unconditional jump) then a pad byte
JMP_SELF = bytes.fromhex("EBFE")
def _setup(image):
# One code section, VA BASE -> file offset 0, so byte n is at VA BASE+n.
config._install(
[config.Section(".text", BASE, len(image), 0x0000, len(image), True)],
entry_point=BASE, kernel_thunk_addr=BASE, origin="fallthrough-test")
return image
def _func_db(placements):
"""placements: list of (va, size); build contiguous func_db entries."""
db = {}
for va, size in placements:
db[va] = {"start": f"0x{va:08X}", "end": va + size,
"_addr": va, "size": size}
return db
def _translate(image, db, va):
ft = FunctionTranslator(image, db)
return ft.translate_function(va, db[va])
def test_fallthrough_emits_tail_call():
# func A: one mov, no terminator, at BASE; func B: pop ebx; ret right after.
image = _setup(MOV_CL + POP_RET)
db = _func_db([(BASE, len(MOV_CL)), (BASE + len(MOV_CL), len(POP_RET))])
c = _translate(image, db, BASE)
nxt = BASE + len(MOV_CL)
assert f"sub_{nxt:08X}(); return;" in c, c
assert "fallthrough" in c, c
print("ok fallthrough_emits_tail_call")
def test_ret_terminated_gets_no_tail_call():
# A function that ends in `ret` already exits; it must not gain a tail call.
image = _setup(MOV_CL + RET)
db = _func_db([(BASE, len(MOV_CL) + len(RET))])
c = _translate(image, db, BASE)
assert "fall through" not in c, c
print("ok ret_terminated_gets_no_tail_call")
def test_pop_ret_terminated_gets_no_tail_call():
image = _setup(POP_RET)
db = _func_db([(BASE, len(POP_RET))])
c = _translate(image, db, BASE)
assert "fall through" not in c, c
print("ok pop_ret_terminated_gets_no_tail_call")
def test_unconditional_jmp_is_not_fallthrough():
# Last instruction is an unconditional jmp: control leaves, no fall-through.
image = _setup(JMP_SELF)
db = _func_db([(BASE, len(JMP_SELF))])
c = _translate(image, db, BASE)
assert "fall through" not in c, c
print("ok unconditional_jmp_is_not_fallthrough")
def test_fallthrough_target_off_section_is_skipped():
# If `end` is past the mapped code, there is nothing to tail-call: the guard
# is is_code_address(end). Place the mov at the very end of the section.
image = _setup(MOV_CL)
db = _func_db([(BASE, len(MOV_CL))]) # end == BASE+6 == section end (data)
c = _translate(image, db, BASE)
assert "fall through" not in c, c
print("ok fallthrough_target_off_section_is_skipped")
if __name__ == "__main__":
test_fallthrough_emits_tail_call()
test_ret_terminated_gets_no_tail_call()
test_pop_ret_terminated_gets_no_tail_call()
test_unconditional_jmp_is_not_fallthrough()
test_fallthrough_target_off_section_is_skipped()
print("\nall passed")