recomp: filter feedback seeds by alignment -- measured regression

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>
This commit is contained in:
sp00nz
2026-07-23 02:02:07 -07:00
parent 19a2ec8885
commit d06af63080
3 changed files with 157 additions and 2 deletions
+56 -2
View File
@@ -303,11 +303,18 @@ recomp_icall_feedback_dump("icall.txt");
Then close the loop:
```
python -m tools.recomp.icall_feedback merge icall.txt
python -m tools.disasm --seed-functions tools/recomp/output/icall_targets.json
python -m tools.recomp.icall_feedback --db game/2276/icall_targets.json \
--functions build/disasm/functions.json merge icall.txt
python -m tools.recomp.icall_feedback --db game/2276/icall_targets.json \
seeds --out game/2276/icall_seeds.json --align 16
python -m tools.disasm ... --seed-functions game/2276/icall_seeds.json
# re-run the recompiler; repeat
```
**Seed `icall_seeds.json`, not `icall_targets.json`.** The database is the raw
cumulative measurement; the seed file is the filtered subset that is safe to hand
the detector. Do not skip the filter — see below.
Each observed target is flagged `resolved` (dispatch found a translation, so it
confirms a real function start) or `unresolved` (dispatch failed — a real gap
that was silently becoming a stub). The database is **cumulative**: a target seen
@@ -327,6 +334,53 @@ guess; this is a record of where the title actually branched. Use both — feed
measured set in as seeds first, then classify whatever the detector still cannot
place.
### Measured result, Halo build 2276
Two rounds, on a title that asserts in `render_cameras.c:458` before reaching
`main()`:
| | round 1 | round 2 (after seeding) |
|---|---|---|
| distinct targets observed | 67 | 71 (+4, execution reached further) |
| resolved | 42 | **66** |
| unresolved **in that run** | 25 | **5** |
| cumulative gaps not a known function start | 24 | **4** |
| functions detected | 8,849 | 8,869 |
20 of the 24 gaps closed. The pre-existing `[ICALL] Failed to resolve` diagnostic
had reported **3** of those 24 — it rate-limits at 16 reports because each dumps a
16-entry ring buffer, so it went silent long before the interesting targets
appeared.
### Why the alignment filter is on by default
**Seeding the raw measured set made the title crash earlier than before.** It
segfaulted (`exit=139`) on a read through `0xFFFFFFF3` before reaching the assert
it used to reach, with 6 `CreateTexture` calls instead of 12.
This is precisely the trap `run.sh` warns about: distinct assert sites went
**1 → 0**, which looks like a win and is not one. Zero asserts because execution
died before the code that asserts.
The cause was the 4 observed targets that were **not 16-aligned**. Filtering to
16-aligned restored the original milestone and exit code. Round 2 then confirmed
the diagnosis independently: those same 4 addresses were still the only
unresolved targets, so they are not function starts the detector missed — they are
garbage that happens to land inside `.text`, most likely uninitialised vtable
reads. The `RECOMP_ICALL` range check is trying to catch exactly that class and
cannot, because the garbage is in range.
Real MSVC function starts are 16-aligned. Unaligned *resolved* targets do exist
(the detector finds some via `cc_boundary` and `tail_jump`), which is why the
filter is applied when generating seeds rather than when recording observations —
the database keeps everything, because discarding a measurement is unrecoverable.
One caveat not yet explained: the filtered build still makes 6 `CreateTexture`
calls where baseline made 12, with the same total `[D3D]` call count, the same
assert site and the same exit code. 20 previously-stubbed indirect calls now do
real work, so the path legitimately changed — but "legitimately changed" is a
hypothesis, not a finding.
## Key Insight
The hardest 10% of static recompilation is indirect calls. Direct calls are mechanical translation. Memory access is solved by the mapping layer. But indirect calls require runtime dispatch with correct stack management, failure recovery, garbage detection, and per-function workarounds for corrupted vtables. Every new crash in the recompiled game is almost certainly an ICALL problem.
+58
View File
@@ -175,6 +175,54 @@ def cmd_merge(args):
return 0
def cmd_seeds(args):
"""Write a filtered seed file from the database.
Measurement and action are deliberately separate. The database records
everything the title actually branched to, because throwing away an
observation is unrecoverable. What is safe to hand the function detector is
a narrower question, and getting it wrong is expensive: a seeded address
that is not really a function start produces a bogus function whose
translation is wrong, and that is worse than the no-op stub it replaced.
The alignment filter exists because of a measured regression on Halo 2276.
Seeding all 25 observed unresolved targets made the title crash *earlier*
(segfault before the render_cameras.c:458 assert it used to reach, 6
CreateTexture calls instead of 12). 21 of them were 16-aligned, which is
what MSVC emits for a real function start; 4 were not. An unaligned
indirect target is far more likely to be a garbage vtable read that
happened to land inside .text than a function the detector missed -- the
RECOMP_ICALL range check is trying to catch exactly that class and cannot,
because the garbage is in range.
"""
db = load_db(args.db)
if not db:
print("empty or missing database: %s" % args.db, file=sys.stderr)
return 1
# Deliberately NOT filtered against the current functions.json. Seeds are an
# input to the pass that rewrites functions.json from scratch, so dropping
# "already known" targets is circular: on the next run they are only known
# *because* they were seeded, and an indirect-only target is one the detector
# cannot re-derive on its own. A seed file must be a standalone statement of
# what to seed, idempotent across runs.
kept, dropped = {}, []
for va, flags in sorted(db.items()):
if args.align and (va % args.align):
dropped.append((va, "not %d-aligned" % args.align))
continue
kept[va] = flags
save_db(args.out, kept)
print("seeds written : %s" % args.out)
print(" from database: %d targets" % len(db))
print(" kept : %d" % len(kept))
print(" dropped : %d" % len(dropped))
for va, why in dropped:
print(" 0x%08X %s" % (va, why))
return 0
def cmd_report(args):
db = load_db(args.db)
if not db:
@@ -216,6 +264,16 @@ def main(argv=None):
"recomp_icall_feedback_dump()")
m.set_defaults(func=cmd_merge)
s = sub.add_parser("seeds", help="write a filtered seed file from the database")
s.add_argument("--out", required=True, metavar="JSON",
help="seed file to write (feed to tools.disasm "
"--seed-functions)")
s.add_argument("--align", type=int, default=16, metavar="N",
help="drop targets not N-byte aligned; 0 disables. Default "
"%(default)s, which is what MSVC emits for a function "
"start. See cmd_seeds for why this defaults on.")
s.set_defaults(func=cmd_seeds)
r = sub.add_parser("report", help="summarise the database")
r.set_defaults(func=cmd_report)
+43
View File
@@ -92,6 +92,49 @@ def test_database_is_directly_loadable_as_seed_functions():
assert raw[1]["seen"] == "unresolved", raw[1]
def test_seeds_drops_unaligned_targets():
"""Measured on Halo 2276: seeding the raw observed set made the title crash
earlier than before (segfault before the render_cameras.c:458 assert it used
to reach). The 4 offenders were the only unaligned ones. Filtering to
16-aligned restored the original milestone, and the next run confirmed those
same 4 were still the only unresolved targets -- i.e. they are not function
starts, they are garbage that happens to land in .text."""
with tempfile.TemporaryDirectory() as tmp:
db = os.path.join(tmp, "targets.json")
out = os.path.join(tmp, "seeds.json")
save_db(db, {0x001B5540: 2, 0x001D99BA: 2, 0x0024B5FB: 2, 0x00130EC0: 2})
assert main(["--db", db, "seeds", "--out", out, "--align", "16"]) == 0
kept = load_db(out)
assert sorted(kept) == [0x00130EC0, 0x001B5540], [hex(v) for v in kept]
def test_seeds_align_zero_keeps_everything():
with tempfile.TemporaryDirectory() as tmp:
db = os.path.join(tmp, "targets.json")
out = os.path.join(tmp, "seeds.json")
save_db(db, {0x001B5540: 2, 0x001D99BA: 2})
assert main(["--db", db, "seeds", "--out", out, "--align", "0"]) == 0
assert len(load_db(out)) == 2
def test_seeds_are_not_filtered_against_current_functions_json():
"""Seeds are an INPUT to the pass that rewrites functions.json from scratch.
Dropping 'already known' targets is circular: next run they are only known
because they were seeded, and an indirect-only target cannot be re-derived.
A seed file must be a standalone, idempotent statement of what to seed."""
with tempfile.TemporaryDirectory() as tmp:
db = os.path.join(tmp, "targets.json")
out = os.path.join(tmp, "seeds.json")
fns = os.path.join(tmp, "functions.json")
save_db(db, {0x00130EC0: 1, 0x001B5540: 2})
with open(fns, "w") as f:
json.dump([{"start": "0x00130EC0", "end": "0x00130F00"}], f)
assert main(["--db", db, "--functions", fns,
"seeds", "--out", out]) == 0
kept = load_db(out)
assert sorted(kept) == [0x00130EC0, 0x001B5540], [hex(v) for v in kept]
def test_zero_flag_entries_are_not_recorded():
# A zero byte means "never observed"; it must not become a seed.
with tempfile.TemporaryDirectory() as tmp: