Skip to content

[AUTOMATED] feat(p4): rustabi — keep the rustc two-register ScalarPair return and connect it at the call - #331

Merged
mahaloz merged 2 commits into
mainfrom
feat/rustabi
Aug 22, 2026
Merged

mahaloz merged 2 commits into
mainfrom
feat/rustabi

Conversation

@mahaloz

@mahaloz mahaloz commented Aug 22, 2026 •

Copy link
Copy Markdown
Contributor

[AUTOMATED]

What this is

The ABI link of the layout → ABI → dataflow → emission chain for Rust
Result/Option recovery. Its entire deliverable is that the payload
variable exists and is connected to the call
. It names nothing Result or
Option, synthesizes no type, and does not touch p9_emit/.

New option rustabi off|auto|always (P4, core tier, default off),
new module p4_calls/kuna_rustabi.rs.

Revision note (adversarial review round). An earlier revision of this PR
claimed that one classification "feeds both seams". It did not — the call
seam consulted no classification at all, and would pair any call in a
rustc-detected image whose caller happened to read two return registers.
That refutation is now fixed rather than reworded: the call seam has its own
classifier and it decodes the callee. The section Two seams, two
classifications
below is the corrected account, and it states plainly what
the consumer seam can and cannot prove.

The finding this is built on — and where it differs from the brief

The brief predicted that Rust's return ABI diverges from SysV in a way no cspec
rule can express
, so kuna would be structurally unable to recover the pair.
Measured on x86-64, that is not what is happening. The storage rustc picks
for a ScalarPair is exactly what the x86-64 cspec's <join_dual_class/>
output rule already describes, and kuna already recovers it: both output
trials go active, the rule matches, buildReturnOutput builds the join-space
concatenation. Two later seams throw it away, and both are invisible to a C
corpus because a C function whose first returned register holds a one-bit
value is rare and a Rust Result is nothing else:

  1. Producer. SubvariableFlow::tryReturnPull narrows a RETURN to the logical
    width of the value it is tracing. rustc materializes a two-variant
    discriminant as xor %eax,%eax; setb %al, so RAX is a one-bit logical
    value — and truncating the RETURN to it does not narrow the returned value, it
    deletes the other register. Result<u32,u32> recovers as
    bool prod(uint4).
  2. Consumer. FuncCallSpecs::buildOutputFromTrials handles one used output
    trial and returns early on two or more (STUB(W4 translate-on-handle)). A
    call whose model asked for a register pair therefore gets no output at
    all
    ; the INDIRECT creations survive and every read of the payload register
    renders as a local nothing ever assigns. The stub's recorded blocker — no
    constructJoinAddress on the merged arch handle — is stale: the sibling
    ActionReturnRecovery::build_return_output calls it today.

So the ABI storage was never the gap on this target. The gap is that the
recovered pair does not survive to be used.

Two seams, two classifications

The seams ask the same question — is this register pair one logical value? —
but they are not looking at the same thing, so they cannot share an answer.
Saying they do would be a false claim about the evidence.

Producer — classify_return_pair

Here the concatenation's halves are values this function computed, so their
shape answers the question. Read from the observed register writes, never
from a size (size does not predict rustc's choice: Result<u32,u32> is 8 bytes
and a pair, Result<Box<u64>,u32> is 16 bytes and goes through memory; both
re-verified with rustc -C opt-level=2 + objdump):

  • ScalarPair — the least-significant half is discriminant-shaped (its
    known non-zero bits fit in a byte) and the other half carries a value the
    function put there. Asking about known bits rather than "a constant per path"
    is deliberate: at -C opt-level=2 rustc emits the branchless setCC form
    far more often than the branchy mov $0/mov $1 one.
  • Memory — that half traces back, through move-only ops, to the function's
    own incoming pointer argument: the sret epilogue. A veto, not an action.
  • Scalar — otherwise; today's answer unchanged.

holds_scalar_pair is what tryReturnPull consults, and it looks through
the reshaping the rule pool applies: RuleConcatZext rewrites
PIECE(ZEXT(V), W) as ZEXT(PIECE(V, W)) as soon as the payload register is
written 32-bit (lea 0x7(%rdi),%edx) — the overwhelmingly common rustc case —
so matching only a bare PIECE finds nothing.

Consumer — classify_call_output_pair

At a call there are no callee values in the IR at all. Both halves are
INDIRECT creations standing for "the callee may have written this", so their
shape says nothing and classify_return_pair has nothing to read. Running it
here would be reading the caller's tea leaves and calling it a classification.

What the seam has instead is three pieces of real evidence, and
classify_call_output_pair is the whole list:

  1. The prototype model — the join_dual_class output rule already matched a
    justified, consecutive, first-in-class register pair, which is what put two
    used trials here rather than one.
  2. The caller's reads — both halves are read out of the call, they are
    distinct non-overlapping registers, and the payload half has a descendant.
  3. The callee's body — probe_callee_return_writes decodes the resolved
    direct callee, bounded (192 instructions), following fall-through and
    resolved machine branch targets until every path reaches a RETURN, and
    records the processor-space writes it observes. A nested call, an unresolved
    indirect branch, an undecodable instruction, a STORE into the register space,
    or the instruction budget makes the summary incomplete, which proves
    nothing. On a complete summary that never touches the payload register, the
    caller's read is a clobber and the pair is vetoed.

Evidence 3 is one-sided: it can refute a pair, never confirm one. So
ScalarPair at the consumer means no counter-example, not the callee returns
a pair
. That positive fact is not derivable at this point in the pipeline — a
recovered prototype is never written back to the symbol table, so a caller has
no recovered callee signature to consult — and what remains after the veto is
exactly the evidence upstream Ghidra ships this branch on unguarded. The honest
reading of the consumer half is: complete the stubbed multi-trial branch, and
refuse it where the callee refutes it.
That is what the code does, what the
module header says, and what §4.2 of the spec says.

The probe is why Funcdata now carries a per-callee write summary. The
per-function ArchContext the pipeline runs against carries the load image but
no translator, so the callee's instructions cannot be read at the seam
itself; the driver takes the probe once the flow build has produced the call
specs — and again after a cross-flow restart, which hands back a fresh
Funcdata and would otherwise silently drop the veto on every restarted
function — and caches it on the Architecture so each distinct callee body is
decoded once per run rather than once per caller. Nothing is probed unless the
rule is live for the image.

The refutation, and the fixture that pins it

scalar_callee:       movq %rdi,%rax ; addq $7,%rax ; ret     # provably never writes RDX
pair_shaped_reader:  call scalar_callee
                     leaq 1(%rdx),%rcx ; leaq 100(%rdx),%rsi
                     testb $1,%al ; cmoveq %rsi,%rcx ; movq %rcx,%rax ; ret

Byte for byte the caller-side shape of a real ScalarPair consumer — two used
output trials, a byte-tested first register, a twice-read second one — over a
callee that provably never writes the second one. Nothing at the call site
separates the two. Before the fix, --option rustabi auto gave that call a
16-byte pair output; now it does not, and the function renders identically with
the option off and on. Vendored as
decompiler/crates/kuna-analysis/tests/fixtures/rust_clobber_pair_x86_64
(1800 bytes, source alongside) and as the second <bytechunk> of the stage
testcase. The control is in the same run: the same option, on the same
caller-side shape, over prod (which does write EDX), still pairs. The callee
body is the only thing that differs.

The gate

auto reads the loader's source-language verdict (Compiler::Rustc), recorded
on the Architecture at load file and copied into the per-function snapshot.
The XML <binaryimage> bootstrap never reaches that line, so auto is inert
on the datatest corpus by construction
. always drops the language test —
needed by the stage testcase, since a <bytechunk> carries no .comment.

Measurements (re-run on this revision, rebased on 728bcd7c)

1. Phantom guards on private/FakeCrypt

4.9 MB static-PIE rustc binary, 4189 decompiled functions, whole-binary
decompile-all, rustabi off vs auto:

metric off auto delta
phantom guards (guards reading a never-assigned local) 1476 / 9026 (16.4%) 1116 / 9039 (12.3%) −360, −24.4%
never-assigned locals 4805 3533 −1272, −26.5%
functions containing one 1225 983 −242, −19.8%
functions changed — — 408
... with strictly fewer phantoms — — 392
... with more phantoms — — 1
... same phantom count, other change — — 15

Corroboration, same two runs: SUBxx uses 1848 → 3105; assigned-call
statements 2644 → 3662.

The callee veto costs nothing measurable here. The whole-binary auto
output is byte-identical across three builds — the shipped one, the one
before the restart re-seed, and one with the veto ablated behind a temporary env
hatch — all md5 b764602fb53e76c4d2fd4ffa9b0a1bff. A real ScalarPair producer
does write its payload register, so the proof never applies to one. What the
veto refuses is the caller that reads a register its callee provably never sets
— zero calls on this corpus, and the whole point on the fixture above. Every
number in the table was recomputed on fresh runs of the shipped build.

The counting script is unchanged from the previous revision (reproduced in the
review thread); every number above was recomputed with it on fresh runs.

2. C collateral — exactly 0, verified

kuna decompile-all <bin> --json, off vs auto, byte-compared:

fixture functions auto vs off
tests/bug-repro/grep 449 identical
tests/bug-repro/sort 490 identical
tests/bug-repro/faillog 69 identical
tests/bug-repro/libselinux.so.1 621 identical
tests/bug-repro/betaflight_STM32F405.elf (ARM) 5797 identical
/usr/bin/ncat (OpenSSL-linked C, 7 R* dynamic symbols) — identical
/usr/bin/htop (15 R* dynamic symbols) — identical

The last two rows are the second reviewer's reproducer for the
is_rust_mangled leak (any symbol beginning with R was read as Rust v0, so
OpenSSL importers were classified Compiler::Rustc). That root cause is fixed
on main by #332; re-verified here after rebase, zero differences.

3. Speed

Interleaved off/auto, decompile-all on FakeCrypt, two separate min-of-3 runs
(the second on the exact shipped build):

run A   off 172.36 / 169.04 / 173.53      auto 170.51 / 174.30 / 169.68   -> +0.38%
run B   off 170.71 / 170.92 / 173.73      auto 172.69 / 170.75 / 169.37   -> -0.78%

Pooled, min of 6: min(off) = 169.04 s, min(auto) = 169.37 s →
+0.20% (budget 5%). The two runs disagree in sign, which is the honest
result: the cost is below this machine's measurement floor. (A second agent was
running decompile-all in a sibling worktree throughout, which is exactly what
interleaving and min-of-N are for, and is also why I am reporting the
disagreement rather than picking the flattering run — the third reviewer flagged
that the previous revision's +0.33% did not reproduce in sign either, in the
PR's favour.) On a non-Rust image the cost is structurally zero: live() is a
two-field read and the probe never runs.

Default

Shipped off. The pair this keeps alive renders as an untyped container
until the emission link of this chain lands, and flipping the default now would
change what every Rust user sees for the sake of a deliberately temporary
rendering. Recommend flipping when the enum-typing PR lands; that is a
reviewer's call.

Gates

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

=== baseline parity ===
PARITY OK
$ make test-stages
datatests: 516/516 assertions passed
exit: 0

=== baseline parity ===
PARITY OK
$ make rust-test
cd decompiler && cargo test --workspace --no-fail-fast
...
$ echo $?
0

# 320 test targets, 4762 passed, 0 failed, 38 ignored, 0 `test result: FAILED`.
# (CI skips this on a same-repo branch PR, so this run is the gate.)
$ make check-spec
check-spec OK (lenient mode)

$ python3 tools/check_spec.py --strict
check-spec OK (strict mode)
$ ./decompiler/target/release/kuna catalog --check
catalog OK: documents exactly the registered kuna options

Catalog counts were re-derived from the failing assertions after the rebase, not
copied. This revision adds no option, so no count moved;
docs/baseline-stages.json was re-recorded for the two new stage assertions
(516 keys, no existing key moved).

Tests

  • p4_calls/kuna_rustabi/tests.rs — 27 unit tests (was 15). The 12 new ones
    all exercise the consumer seam, which previously had none:
    build_call_output_pair called directly on a hand-built CALL with two
    register INDIRECT creations (the happy path asserts the join-space output,
    both halves becoming SUBPIECEs, and the INDIRECT creations destroyed); the
    scalar_callee shape refused; an incomplete probe vetoing nothing; a
    callee that does write the payload still pairing; a partial (4-of-8-byte)
    write still counting; a STORE into the space defeating the proof; the gate
    failing closed at off; a dead payload half, overlapping halves, a single
    trial, a non-INDIRECT half, and an unresolved callee.
  • tests/stages/kuna-rustabi.xml — 10 assertions (was 8), now two-sided:
    3 pin the bug at the default, 5 the fix under option rustabi always, and
    2 pin the callee veto — pair_shaped_reader renders identically in both
    passes and its call keeps no output in either.
  • kuna-console/tests/verify_rustabi_pair.rs — 7 cross-crate e2e assertions
    (was 5), adding the callee-veto case on the real rustc fixture and its
    positive control.

Scoped out, honestly

  • The consumer seam cannot positively confirm a pair. Stated above, in the
    module header and in the spec, rather than papered over. Closing it needs a
    callee fact that outlives one function's decompile (a recovered-prototype
    writeback, or an analysis-tier return-register summary); that is a separate
    PR, not a rewording of this one.
  • The Memory/sret arm is a veto with no measured firing. Implemented,
    unit-tested and correct, but on every corpus run it never changed an outcome:
    kuna's own return recovery already resolves an sret function to a single
    pointer return, so no pair forms for it to veto. A negative result.
  • No type is synthesized and no name is invented. undefined16 / [u8; 16]
    is the honest rendering of a value the engine now knows the shape of but not
    the meaning of.
  • DW_TAG_variant_part is untouched, as specified.
  • One shape I did not chase: strip_uncomputed_return_piece only matches a
    bare two-input PIECE at the RETURN, so on the ZEXT(PIECE(...)) shape the
    pool produces it cannot inspect the halves. Widening it would be a small
    independent cleanup.

🤖 Generated with Claude Code

https://claude.ai/code/session_016WUuE4zdiEqZFWLL2YEUk9

mahaloz and others added 2 commits August 22, 2026 19:54
… connect it at the call

[AUTOMATED]

A rustc `Result`/`Option`/slice/fat-pointer whose layout is a `ScalarPair` comes
back in two registers - discriminant in the first, payload in the second. kuna
already RECOVERS that pair (the x86-64 cspec's `join_dual_class` output rule
matches the RAX/RDX trials and `buildReturnOutput` builds the join), and then
loses it twice:

* the producer's RETURN is narrowed by subvariable flow to the ONE-BIT logical
  width of the `xor %eax,%eax; setb %al` discriminant, which deletes the other
  register with it (`Result<u32,u32>` -> `bool prod(uint4)`);
* the consumer's CALL falls into the un-ported multi-trial branch of
  `buildOutputFromTrials` and gets NO output at all, so the payload register
  renders as a local nothing ever assigns (`int4 v3; // edx`, read twice).

`option rustabi off|auto|always` (new, default off) answers both from one
classification taken from the observed register writes rather than from a size -
size does not predict rustc's choice. A pair is recognized when the
least-significant half is discriminant-shaped (known non-zero bits fit in a
byte, which covers the branchy `mov $0/$1` tag and the branchless `setCC` alike)
and the other half carries a value the function put there; it is vetoed when the
low half traces back to the function's own incoming pointer argument, which is
the sret epilogue rather than a tag.

The stub's recorded blocker - no `constructJoinAddress` on the merged arch
handle - was stale: the sibling `build_return_output` calls it today.

Measured on a 4.9 MB static-PIE rustc binary (4194 functions), auto vs off:
phantom guards 1476/9026 -> 1116/9039 (-24.4%), never-assigned locals 4805 ->
3533 (-26.5%), 409 functions change of which 392 have strictly fewer phantoms
and 1 has one more. Zero functions change on grep/sort/faillog/libselinux.so.1
and the betaflight ARM fixture, because `auto` reads the loader's
source-language verdict and the XML datatest bootstrap never sets it.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_016WUuE4zdiEqZFWLL2YEUk9
…the callee

[AUTOMATED]

An adversarial review refuted this PR's central claim. The prose said one
classification "feeds both seams"; the code never asked `classify_return_pair`
anything at the call. `build_call_output_pair` checked only `live(data)`,
`finalvn.len() == 2`, and that both halves were register INDIRECT creations, so
every call in a rustc-detected image whose caller happened to read two return
registers was paired, with no evidence about the callee. None of the 15 unit
tests exercised it and the stage test pinned only the happy path.

The reproducer is a rustc image with two `global_asm!` functions:

    scalar_callee:       movq %rdi,%rax ; addq $7,%rax ; ret   # never writes RDX
    pair_shaped_reader:  call scalar_callee ; lea 1(%rdx),%rcx
                         lea 100(%rdx),%rsi ; testb $1,%al
                         cmoveq %rsi,%rcx ; movq %rcx,%rax ; ret

Byte for byte the caller-side shape of a real `ScalarPair` consumer, over a
callee that provably never writes the second return register. `--option rustabi
auto` gave that call a 16-byte pair output.

The two seams do not see the same thing, so they cannot share an answer. At a
call there are no callee values in the IR at all - both halves are INDIRECT
creations - so the halves' shape says nothing and `classify_return_pair` has
nothing to read. `classify_call_output_pair` is a separate predicate over the
three pieces of evidence a call site actually has: the model rule that matched,
the caller's reads (distinct non-overlapping registers, payload half read), and
`probe_callee_return_writes` - a bounded decode of the resolved direct callee
that follows fall-through and resolved machine branches to every RETURN and
records the processor-space writes it observes. A nested call, an unresolved
indirect branch, an undecodable instruction, a STORE into the space, or the
instruction budget makes the summary incomplete, which proves nothing. On a
complete summary that never touches the payload register the caller's read is a
clobber and the pair is refused.

That check is one-sided: it can refute a pair, never confirm one. `ScalarPair`
at the consumer means "no counter-example", not "the callee returns a pair" -
the positive fact is not derivable there, because a recovered prototype is never
written back to the symbol table. The module header, the option prose and
docs/spec/04 §4.2 now say exactly that instead of the false shared-verdict
claim.

The per-function `ArchContext` carries the load image but no translator, so the
probe is taken by the driver once flow has produced the call specs (and again
after a cross-flow restart, which hands back a fresh `Funcdata`), cached on the
`Architecture` so each distinct callee body is decoded once per run.

Measured, FakeCrypt (4189 functions), rebased on 728bcd7: the veto changes
nothing - the whole-binary `auto` output is byte-identical across the shipped
build, the pre-re-seed build and an ablated build - so the headline is
unchanged: phantom guards 1476/9026 -> 1116/9039, never-assigned
locals 4805 -> 3533, 408 functions changed (392 fewer phantoms, 1 more). A real
ScalarPair producer does write its payload register; what the veto refuses is a
caller reading a register its callee provably never sets.

Tests: 27 unit tests (was 15), the 12 new ones all on the consumer seam, which
had none - including `build_call_output_pair` called directly on a hand-built
CALL, the `scalar_callee` shape refused, and an incomplete probe vetoing
nothing. The stage testcase is now two-sided (10 assertions, 2 pinning the
veto), and the cross-crate e2e adds the negative plus its positive control.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_016WUuE4zdiEqZFWLL2YEUk9
@mahaloz
mahaloz merged commit 244be85 into main Aug 22, 2026
9 checks passed
@mahaloz
mahaloz deleted the feat/rustabi branch August 22, 2026 21:38
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.

1 participant