Skip to content

[AUTOMATED] feat(p4): spillargtrial - recover call args lost to a caller-save spill - #315

Merged
mahaloz merged 1 commit into
mainfrom
fix/i275-spillargtrial
Aug 17, 2026
Merged

mahaloz merged 1 commit into
mainfrom
fix/i275-spillargtrial

Conversation

@mahaloz

@mahaloz mahaloz commented Aug 17, 2026

Copy link
Copy Markdown
Contributor

Fixes #275

Ships the remainder PR #284 scoped and left open: defect (A), GH-275's headline
symptom, behind option spillargtrial off|reload|spill (default off).

The mechanism — #284's hypothesis held, verbatim

Instrumented Funcdata::only_op_use on the filed repro. Exactly one rejection
fires, and it is the predicted one:

OOU reject: code=CPUI_STORE at 1162 vn=unique:16@d700 slot=3 opmatch_addr=116c
            store_in1=Some("unique:8@9d00") store_in2_is_vn=true

0x1162 is movapd XMMWORD PTR [rsp+0x20],xmm1; store_in2_is_vn=true says the
walked Varnode is the store's value operand. The control (packed_one_atan2_ok)
produces zero rejections, which is why one call recovers and two do not.

So: any CPUI_STORE among a trial Varnode's descendants makes only_op_use false,
check_input_trial_use calls mark_inactive — which also sets CHECKED, so the trial
is never re-scored — and the producer dies to DCE.

Why this is a floating-point bug. On x86-64 SysV no xmm register is
callee-saved, so a double that is both an argument and live across the call must be
spilled by the caller. GH-275 needs more than one atan2 for exactly that reason: with
one call the value is dead afterwards and no spill is emitted.

Two corrections to #284's file:line detail (main has moved): the STORE arm is now
substrate/funcdata_varnode.rs:2258-2265, and one thing the scoping did not
anticipate — RuleLoadVarnode::check_spacebase returns None here.
ActionActiveParam runs before ActionStackPtrFlow in the first mainloop
iteration, so the pointer is still the raw INT_ADD(RSP, #0x20); and the reload
straddles the call, which re-defines the stack pointer, so the reload's constant is not
comparable to the store's. The search therefore walks forward from the store's own base
Varnode over INDIRECT/COPY/INT_ADD/INT_SUB carrying the running offset
delta
. MULTIEQUAL is not followed (a phi's other arm may carry a different frame).

Predicate A vs B — measured, and B wins

  • spill (predicate A, weak): any caller-frame store of the walked Varnode's value.
  • reload (predicate B, strong): additionally requires a later LOAD of the same
    slot at the same width — a genuine caller-save spill/reload pair.

Oracle: 360 non-variadic libc/POSIX prototypes, scored per call site (variadic
functions deliberately excluded — a vararg site legitimately exceeds its prototype).

decbench O2 — 268 binaries, 74,668 functions, 90,787 oracle-scored call sites

arm exact SHORT SPURIOUS new spurious
off 85,633 1,457 3,697 —
reload 85,685 (+52) 1,332 (−125) 3,770 (+73) 73
spill 85,637 (+4) 1,327 (−130) 3,823 (+126) 132, and 6 previously-correct sites broken

/usr/bin — 250 ELF binaries, 48,876 functions, 68,708 oracle-scored call sites

arm exact SHORT SPURIOUS new spurious
off 64,749 1,072 2,887 —
reload 64,758 (+9) 1,036 (−36) 2,915 (+28) 37
spill 64,742 (−7) 1,026 (−46) 2,940 (+53) 65

Combined: reload exact +61, SHORT −161, SPURIOUS +101. spill exact −3 — it
buys its extra 15 short-fixes with more spurious arguments than it fixes, and is
net-negative on /usr/bin. reload is the recommended level; spill ships only as a
bisect handle
(exactly calloverlap's in/full precedent, inverted).

The decisive single witness, from a ground-truth corpus I compiled with clang -O2 so
every callee's true arity is known from source — an inlined 64-byte memcpy:

14e7: movaps XMMWORD PTR [rsp+0x30],xmm3   ; four stores that FILL the local buffer,
14ec: movaps XMMWORD PTR [rsp+0x20],xmm2   ; never read back into a register
14f1: movaps XMMWORD PTR [rsp+0x10],xmm1
14f6: movaps XMMWORD PTR [rsp],xmm0
14fa: mov    rdi,rsp
1500: call   sptr2                          ; void sptr2(void *, long) -- 2 args
off / reload:  sptr2(&v1,a0);                    // correct
spill:         sptr2(v1,v5,v9,v13,&v1,a0);       // FOUR arguments invented

reload declines all four (reload=false on each), which is precisely what the reload
requirement is for.

The false positives are real, and intrinsic

I hand-audited the 73-row reload list grouped by callee and verified the largest
categories against objdump (26 of 73 rows, 36%; 3 of the 16 distinct callees), plus
the clang witness:

  • shadow/* commonio_sort → qsort(...) 4 → 5 (25 rows). Ground truth:
    a889: mov QWORD PTR [rsp+0x8],r8   ; caller-save spill of the element count
    a88e: call qsort@plt
    a899: mov r8,QWORD PTR [rsp+0x8]   ; reload
    r8 is SysV integer argument Stage reorg #5. Wrong.
  • coreutils/tac tac_seekable → lseek(input_fd,v21,0,v13) 3 → 4. Wrong.
  • nginx (clang -O2) ngx_http_file_cache_vary → ngx_strncasecmp(v5,data,size,v3)
    3 → 4 — mov [rsp+0x10],rcx around the call, rcx being SysV argument Recover PLT/GOT import names in ELF decompilation #4.
    Wrong (source arity 3).

There is no local discriminator. The verified true positive has the identical
shape — coreutils/* rpl_fseeko (109 of the 120 fixed sites):

6469: mov DWORD PTR [rsp+0xc],edx   ; spill of whence
646d: mov QWORD PTR [rsp],rsi       ; spill of offset
6471: call fileno@plt
6476: mov edx,DWORD PTR [rsp+0xc]   ; reload
647a: mov rsi,QWORD PTR [rsp]
...
644e: jmp fseeko@plt                ; tail call: rsi/rdx ARE the arguments

fseeko() → fseeko(fp,offset,CONCAT44(dat_14,whence)). Correct. A caller-save spill
of a live value that happens to sit in an ABI argument register is structurally
indistinguishable
from a spilled argument; only the callee's own behaviour separates
them, which the trial machinery does not have here. That is the honest ceiling of this
predicate, and the reason for the default below.

Recovery — the three filed repros (clang 14 -O2, --mode reliable)

repro off (today) reload
packed_two_atan2 atan2(SUB168(v1,0)); … atan2(v3,v5) atan2(SUB168(v1,0),SUB164(v1,8)); … atan2(v3,SUB164(v1,8))
packed_copysign_atan2 atan2(); atan2(a0,SUB168(v1,8));
packed_one_atan2_ok (control) atan2(SUB168(v1,0),SUB168(v1,8)) byte-identical

packed_two_atan2 also loses its spurious unsigned int v5; // stack - 0x18 local.
Raw p-code CALL arity (decomp_dbg → print raw) confirms the fix is upstream of
printing:

off      0x116c: call fatan2(free)(XMM3_Qa)
         0x118a: call fatan2(free)(XMM0_Qa,s0xffffffffffffffe8:4)
reload   0x116c: call fatan2(free)(XMM3_Qa,XMM1_Da)
         0x118a: call fatan2(free)(XMM0_Qa,XMM1_Da)

The residual 4-byte XMM1_Da is #284's defect (B) (movaps is packed-single, so
Heritage::refinement partitions XMM1 at 4-byte boundaries and the float pentry is
minsize="4"), out of scope here. The copysign variant's first argument renders as
a0 — a stale binding, defect (C), calloverlap's territory. The two options
compose: --option calloverlap full --option spillargtrial reload gives
atan2(v6,SUB168(v1,8)), right arity and right values.

Collateral, both directions

off → reload off → spill
functions changed (decbench O2, 74,668) 424 (0.57%) 827 (1.11%)
functions changed (/usr/bin, 48,876) 1,170 (2.39%) 2,028
call sites gaining args / losing (decbench) 338 / 0 593 / 6
new decompile errors 0 0
clang corpus (11 binaries, 8,766 fns) 49 changed, 0 lost, 0 new errors —

One /usr/bin function flips error state (busybox sub_462370), and it is a
watchdog flake, not a regression: standalone it takes 11.44 s at off and 10.71 s at
reload
, straddling the 10 s per-function budget in both arms.

Speed

Interleaved A/B, arm order alternating per iteration, child CPU time
(getrusage(RUSAGE_CHILDREN)) as well as wall clock.

workload N load arm CPU Δ min CPU Δ median
coreutils/sort decompile-all 11 2.1 (quiet) reload +0.14% −0.47%
coreutils/sort decompile-all 11 2.1 spill +0.02% +0.53%

Well inside the 5% budget. An earlier run of the same benchmark under a shedding load
returned −2.93%, which is impossible for a change that can only add work — the noise
the campaign notes warn about; the quiet-box row is the one to trust.

Why default off, and why no DIV row

No DIV row: the shipped default does not change (spill_arg_trial = 0, upstream
byte-identical), so there is no divergence to record in docs/history.md. That
reasoning holds — docs/history.md's registry records default divergences, and the
new levels are opt-in.

Default off despite the favourable 61:0 exact-arity ledger, because this is a
deliberate divergence from upstream, not a port repair: only_op_use is faithful to
funcdata_varnode.cc:1891, and its blanket STORE rejection exists precisely to stop an
ordinary frame store from becoming a bogus argument. The failure mode is a spurious
trailing argument
, and no gate can see one — the datatest corpus is
prototype-declared (a locked prototype makes isInputActive false and bypasses trial
recovery entirely) and GED scores topology, not arity. With the burden of evidence on
the change and 101 hand-confirmable false positives against 161 fixes, the right shape
is a symptom-targeted opt-in: turn it on when you see a dropped argument.
Not added to AGGRESSIVE_OVERRIDES for the same reason (auto picks aggressive under
500 KiB, which would make it the de facto default).

tier = "transform", not core like its calloverlap sibling: it INSERTS a call
argument and is right on the spill/reload shape and wrong on an ordinary frame store,
which is the transform tier's definition.

Test

tests/stages/gh275-spillargtrial.xml, two-pass, built from the real clang 14 -O2
bytes
of the filed function relocated to 0x100000 (only the two call rel32 fields
and the xorpd RIP-relative displacement recomputed). Pass 1 (default off) pins the
arg-dropping shape and the spurious stack local; pass 2 (option spillargtrial reload) pins both recovered call sites.

Gates

Run on the rebased tree (origin/main = a8c12463, aifstrict), after re-deriving every
shared count from a green build of that tree and grepping each value back out.

$ make test
datatests: 675/675 assertions passed
exit: 0

=== baseline parity ===
PARITY OK

$ make test-stages
datatests: 484/484 assertions passed
exit: 0

=== baseline parity ===
PARITY OK

$ make check-spec
python3 tools/check_spec.py
check-spec OK (lenient mode)
(and tools/check_spec.py --strict -> check-spec OK (strict mode))

$ make rust-test
... 315 `test result:` lines, `0 failed` in every one
test options_md_matches_the_generator_byte_for_byte ... ok
MAKE_EXIT=0

docs/baseline.json is untouched — default-off means the corpus must not move, and
it does not. docs/baseline-stages.json re-recorded (never hand-merged) for the three
new assertions, 481 → 484.

Shared counts, all derived from this tree rather than computed (this rebase hit the
silent auto-merge twice — both sides made the identical N -> N+1 edit and git took it
one short): settables 110 -> 111, tiers (24,47,39) -> (24,48,39), the mid-table
},\n tally 109 -> 110, catalog_bytecompat.rs 110 -> 111 (x3) with
phase_catalog.json regenerated, stage corpus files 207 -> 208 (counted, not added),
and kuna-catalog.xml's opt-in-tool bucket 13 -> 14. docs/options.md regenerated
from this build; kuna catalog --check green.

Spec

docs/spec/04-calls-and-prototypes.md §4.2 (ActionActiveParam), the chapter whose
Anchors: header owns p4_calls — prose on what only_op_use decides, why the STORE
arm exists, the SysV no-callee-saved-xmm forcing function, the two timing constraints
that shape the frame-slot recognition, and an explicit statement that this is a
departure from upstream and why it is off by default.

🤖 Generated with Claude Code

https://claude.ai/code/session_01VBn8vgwoHqPFnnV4ZMApfq

[AUTOMATED]

GH-275's headline symptom, scoped as defect (A) in PR #284: on x86-64 SysV no
xmm register is callee-saved, so a floating-point value that is both an
argument and live across the call MUST be spilled by the caller - and that
spill is a second descendant of the very Varnode the input trial is scoring.
`Funcdata::only_op_use` rejects on any CPUI_STORE, `check_input_trial_use`
calls `mark_inactive` (which also sets CHECKED, so the trial is never
re-scored), and the argument's producer dies to DCE.

New settable `spillargtrial off|reload|spill`, default off.  At `reload` a
frame STORE stops rejecting only when it writes the walked Varnode's own value
into a caller-frame slot AND a later LOAD reads that slot back at the same
width; at `spill` the reload requirement is dropped.  Since ActionActiveParam
runs before ActionStackPtrFlow the frame reference is still the raw
INT_ADD(sp, #const), and the reload straddles the call that re-defines the
stack pointer, so the search walks forward from the store's own base Varnode
carrying the running offset delta rather than matching raw constants.

This is a deliberate divergence from upstream, not a port repair: the rule it
relaxes exists to stop an ordinary frame store from becoming a bogus argument.
No DIV row - the shipped default does not change.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VBn8vgwoHqPFnnV4ZMApfq
@mahaloz
mahaloz merged commit a6507e9 into main Aug 17, 2026
9 checks passed
@mahaloz
mahaloz deleted the fix/i275-spillargtrial branch August 17, 2026 02:32
mahaloz added a commit that referenced this pull request Aug 17, 2026
The branch was cut from #302 while main advanced to #316; the engine
PRs in between (spillargtrial #315, stackguard #306, snip-reads #307,
loadguardrange #308, ...) legitimately shift the ghidra-path output, so
CI's merge-ref run measured register leaks 108 vs the pinned 106. Rebase
onto origin/main and re-pin every value to the rebased tree:

  registers 106/64/60 -> 108/58/60, unique 32/2/8 -> 34/4/8,
  mangled 21/13/7 -> 21/6/7, c_lines 241/174/89 -> 243/128/89,
  diff ratios 0.643/0.898/0.811 -> 0.646/0.867/0.811 (band unchanged);
  placeholders/resolvable/traffic unchanged (49/25/17, 24/18/14,
  1477/1003).

The sub_3320 shrink (c_lines -26%, FS_OFFSET gone from its register
set, mangled 13 -> 6) is the stackguard/snip-reads work stripping the
canary sequence -- explainable, not suspicious. Determinism verified:
three consecutive runs of the pins test are measurement-identical.

Gates on the rebased tree: harness release + --include-ignored green,
make test 675/675 PARITY OK, make test-stages PARITY OK, check-spec OK,
kuna-ghidra dev-profile spot check green. The full workspace suite ran
green on this branch pre-rebase and every added commit is already-CI-
green main history, so it is covered by the branch + main CI runs.

[AUTOMATED]

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01AfGYKwUWvPYYj1Aw7tcLhC
mahaloz added a commit that referenced this pull request Aug 17, 2026
…the GUI-path quality gap (#317)

* feat(ghidra): ghidra-sim differential test harness — pin the GUI-path quality gap

Extract the decompile_at_e2e MockJava loopback into a shared module
(tests/ghidra_sim/mod.rs — AnswerSource-pluggable pump, wire builders,
session tracer, dual-<function> doc parser, a markup->C flattener that
replicates Java's getC() token cleaning (IllegalCharCppTransformer),
badness scanners, line-diff metric) and build ghidra-sim v1 on top
(tests/ghidra_sim/oracle.rs): a mock-Java answer source backed by kuna's
own analysis of real vendored ELFs — bootstrap_from_object for
bytes/labels, the real Sleigh re-encoded as wire <inst> docs for
getPcode, and a tspec GENERATED from the loaded Sleigh's
AddrSpaceManager so packed space indices agree by construction.
getMappedSymbols/getExternalRef answer EMPTY at a marked PHASE-3 SEAM.

tests/ghidra_sim_e2e.rs drives the full wire lifecycle (registerProgram
-> setAction -> decompileAt x3 -> flushNative -> repeat -> deregister)
over tests/bug-repro/faillog (sort/grep as an ignored breadth test),
asserts the response-document schema (name/entry echo, markup
opref/varref subset-of ast, 19-query legality + query-legal placement),
and PINS today's Phase-2 reality: per-function raw-register leaks
(106/64/60), Unique tokens (32/2/8), placeholders (49/25/17) of which
the loader already knows names for 24/18/14 (Phase 3 drives to 0),
getC()-mangled tokens (21/13/7, PR-C drives to 0), ghidra-vs-CLI line
diff ratios (0.64/0.90/0.81 floors), getPcode traffic 1477/1003, and
getMappedSymbols == 0 (Phase 3 flips to >=1). Pins move only with the
provider/emitter change that earns them.

[AUTOMATED]

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01AfGYKwUWvPYYj1Aw7tcLhC

* ci(ghidra): run the ghidra-sim harness in the gates job + make test-ghidra

Add a `gates`-job step running `cargo test -p kuna-ghidra --release --
--include-ignored` (with the standard specs-skip canary grep) after the
catalog checks: the workspace suite is skipped on internal PRs, and a
GUI-path regression is exactly what the ghidra-sim pins exist to catch
pre-merge. Cost: ~1-2 min of compile over the release deps `make
binaries` already built, ~2 s of test runtime. `make test-ghidra` is the
same run locally.

[AUTOMATED]

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01AfGYKwUWvPYYj1Aw7tcLhC

* docs(ghidra): live-smoke rig + testing-strategy section for the harness

integrations/ghidra/live-smoke/: a manual/dev pyghidra rig that swaps
DecompileProcessFactory.exepath to kuna_ghidra inside a real Ghidra,
decompiles the same functions with both cores, and writes a side-by-side
report with the same badness-scanner counts the in-tree harness pins
(README covers the offline-pyghidra setup and the getC()-vs-GUI-panel
rendering distinction). docs/ghidra-integration.md §11 rewritten around
the shipped harness: what it covers, how to run it, where the pins live.

[AUTOMATED]

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01AfGYKwUWvPYYj1Aw7tcLhC

* test(ghidra): harden the ghidra-sim pins per adversarial review

- Diff-ratio pins are now a BAND: ceilings [0.70,0.95,0.90] join the
  floors (a markup regression that makes the GUI text worse now fails
  instead of saturating), the vacuous `<= 1.0` assert is gone, and the
  flattened-C normalized line count is pinned per target (241/174/89) --
  the assert that actually catches a <break>-token collapse. The pin
  comment now decomposes the ratio (Phase-3 symbol gap + option-preset
  skew until setOptions is wired) so nobody chases 0 with symbol work.
- decompile_cli now routes through the SHARED per-function step
  (kuna_console::decompile_step::decompile_one, DIV-66) with the
  error-noreturn CALL_RETURN flow overrides built exactly as
  kuna_console::project does -- the previous direct drive call silently
  dropped them (latent: faillog has no error() sites, and every faillog
  pin re-measured IDENTICAL; sort/grep-class fixtures would have
  diverged from the real CLI).
- Assert strength: warnings frames pinned trim-empty on registerProgram
  and decompileAt (no substring blocklists); markup oprefs AND varrefs
  pinned non-empty per class; ast varnode refs collected from the
  <varnodes> child only (all Java's buildVarnodeRefs keys -- an op
  operand ref undeclared there must not launder the subset assert);
  the name echo compares against the sim's code_label (which consults
  label_overrides) rather than the raw program lookup.
- CI: the gates-job harness step tees its output to a log before the
  canary grep, so a FAILING pin still prints its diagnostics (the old
  command substitution aborted under bash -e before any echo).
- live-smoke docs/script: kuna_ghidra is not built by `make binaries`;
  point at `cargo build --release -p kuna-ghidra`.

Tests/CI/docs-only diff: the parity gates are untouched by construction.
`cargo test -p kuna-ghidra --release -- --include-ignored` fully green;
`make check-spec` green. No pinned value moved.

[AUTOMATED]

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01AfGYKwUWvPYYj1Aw7tcLhC

* test(ghidra): re-measure the faillog pins on main @ 813ee13 (rebase)

The branch was cut from #302 while main advanced to #316; the engine
PRs in between (spillargtrial #315, stackguard #306, snip-reads #307,
loadguardrange #308, ...) legitimately shift the ghidra-path output, so
CI's merge-ref run measured register leaks 108 vs the pinned 106. Rebase
onto origin/main and re-pin every value to the rebased tree:

  registers 106/64/60 -> 108/58/60, unique 32/2/8 -> 34/4/8,
  mangled 21/13/7 -> 21/6/7, c_lines 241/174/89 -> 243/128/89,
  diff ratios 0.643/0.898/0.811 -> 0.646/0.867/0.811 (band unchanged);
  placeholders/resolvable/traffic unchanged (49/25/17, 24/18/14,
  1477/1003).

The sub_3320 shrink (c_lines -26%, FS_OFFSET gone from its register
set, mangled 13 -> 6) is the stackguard/snip-reads work stripping the
canary sequence -- explainable, not suspicious. Determinism verified:
three consecutive runs of the pins test are measurement-identical.

Gates on the rebased tree: harness release + --include-ignored green,
make test 675/675 PARITY OK, make test-stages PARITY OK, check-spec OK,
kuna-ghidra dev-profile spot check green. The full workspace suite ran
green on this branch pre-rebase and every added commit is already-CI-
green main history, so it is covered by the branch + main CI runs.

[AUTOMATED]

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01AfGYKwUWvPYYj1Aw7tcLhC

---------

Co-authored-by: Claude Fable 5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[AUTOMATED] x86-64 packed-double setup drops atan2 call args

1 participant