Repository navigation
[AUTOMATED] feat(p4): rustabi — keep the rustc two-register ScalarPair return and connect it at the call - #331
Merged
Merged
Conversation
… 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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
[AUTOMATED]
What this is
The ABI link of the layout → ABI → dataflow → emission chain for Rust
Result/Optionrecovery. Its entire deliverable is that the payloadvariable exists and is connected to the call. It names nothing
ResultorOption, synthesizes no type, and does not touchp9_emit/.New option
rustabi off|auto|always(P4,coretier, defaultoff),new module
p4_calls/kuna_rustabi.rs.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
ScalarPairis 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,
buildReturnOutputbuilds thejoin-spaceconcatenation. 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
Resultis nothing else:SubvariableFlow::tryReturnPullnarrows a RETURN to the logicalwidth of the value it is tracing. rustc materializes a two-variant
discriminant as
xor %eax,%eax; setb %al, soRAXis a one-bit logicalvalue — and truncating the RETURN to it does not narrow the returned value, it
deletes the other register.
Result<u32,u32>recovers asbool prod(uint4).FuncCallSpecs::buildOutputFromTrialshandles one used outputtrial and
returns early on two or more (STUB(W4 translate-on-handle)). Acall 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
constructJoinAddresson the merged arch handle — is stale: the siblingActionReturnRecovery::build_return_outputcalls 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_pairHere 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 bytesand a pair,
Result<Box<u64>,u32>is 16 bytes and goes through memory; bothre-verified with
rustc -C opt-level=2+objdump):ScalarPair— the least-significant half is discriminant-shaped (itsknown 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=2rustc emits the branchlesssetCCformfar more often than the branchy
mov $0/mov $1one.Memory— that half traces back, through move-only ops, to the function'sown incoming pointer argument: the sret epilogue. A veto, not an action.
Scalar— otherwise; today's answer unchanged.holds_scalar_pairis whattryReturnPullconsults, and it looks throughthe reshaping the rule pool applies:
RuleConcatZextrewritesPIECE(ZEXT(V), W)asZEXT(PIECE(V, W))as soon as the payload register iswritten 32-bit (
lea 0x7(%rdi),%edx) — the overwhelmingly common rustc case —so matching only a bare
PIECEfinds nothing.Consumer —
classify_call_output_pairAt 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_pairhas nothing to read. Running ithere 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_pairis the whole list:join_dual_classoutput rule already matched ajustified, consecutive, first-in-class register pair, which is what put two
used trials here rather than one.
distinct non-overlapping registers, and the payload half has a descendant.
probe_callee_return_writesdecodes the resolveddirect callee, bounded (192 instructions), following fall-through and
resolved machine branch targets until every path reaches a
RETURN, andrecords 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
ScalarPairat the consumer means no counter-example, not the callee returnsa 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
Funcdatanow carries a per-callee write summary. Theper-function
ArchContextthe pipeline runs against carries the load image butno 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
Funcdataand would otherwise silently drop the veto on every restartedfunction — and caches it on the
Architectureso each distinct callee body isdecoded 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
Byte for byte the caller-side shape of a real
ScalarPairconsumer — two usedoutput 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 autogave that call a16-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 stagetestcase. 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 calleebody is the only thing that differs.
The gate
autoreads the loader's source-language verdict (Compiler::Rustc), recordedon the
Architectureatload fileand copied into the per-function snapshot.The XML
<binaryimage>bootstrap never reaches that line, soautois inerton the datatest corpus by construction.
alwaysdrops 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/FakeCrypt4.9 MB static-PIE rustc binary, 4189 decompiled functions, whole-binary
decompile-all,rustabioff vsauto:Corroboration, same two runs:
SUBxxuses 1848 → 3105; assigned-callstatements 2644 → 3662.
The callee veto costs nothing measurable here. The whole-binary
autooutput 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 realScalarPairproducerdoes 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 vsauto, byte-compared:autovs offtests/bug-repro/greptests/bug-repro/sorttests/bug-repro/faillogtests/bug-repro/libselinux.so.1tests/bug-repro/betaflight_STM32F405.elf(ARM)/usr/bin/ncat(OpenSSL-linked C, 7R*dynamic symbols)/usr/bin/htop(15R*dynamic symbols)The last two rows are the second reviewer's reproducer for the
is_rust_mangledleak (any symbol beginning withRwas read as Rust v0, soOpenSSL importers were classified
Compiler::Rustc). That root cause is fixedon
mainby #332; re-verified here after rebase, zero differences.3. Speed
Interleaved off/auto,
decompile-allon FakeCrypt, two separate min-of-3 runs(the second on the exact shipped build):
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-allin a sibling worktree throughout, which is exactly whatinterleaving 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 atwo-field read and the probe never runs.
Default
Shipped
off. The pair this keeps alive renders as an untyped containeruntil 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
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.jsonwas 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 onesall exercise the consumer seam, which previously had none:
build_call_output_paircalled directly on a hand-built CALL with tworegister INDIRECT creations (the happy path asserts the
join-space output,both halves becoming SUBPIECEs, and the INDIRECT creations destroyed); the
scalar_calleeshape refused; an incomplete probe vetoing nothing; acallee 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 singletrial, 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, and2 pin the callee veto —
pair_shaped_readerrenders identically in bothpasses 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
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.
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.
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_partis untouched, as specified.strip_uncomputed_return_pieceonly matches abare two-input
PIECEat the RETURN, so on theZEXT(PIECE(...))shape thepool produces it cannot inspect the halves. Widening it would be a small
independent cleanup.
🤖 Generated with Claude Code
https://claude.ai/code/session_016WUuE4zdiEqZFWLL2YEUk9