Skip to content

[AUTOMATED] feat(p4): decompile callees first and type call-site arguments from the callee's recovered prototype (protoorder) - #669

Merged
mahaloz merged 31 commits into
mainfrom
feat/protoorder
Sep 19, 2026
Merged

mahaloz merged 31 commits into
mainfrom
feat/protoorder

Conversation

@mahaloz

@mahaloz mahaloz commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

The problem

decompile-all types each function from its own evidence, so what a callee
recovered about its parameters never reaches the calls to it:

$ cat po.c
#include <stdio.h>
__attribute__((noinline)) int nextbyte(FILE *f) { return fgetc(f); }
__attribute__((noinline)) int twice(void *p)    { return nextbyte(p) + nextbyte(p); }
int main(void) { return twice(stdin); }

$ gcc -O2 -s -o po po.c && kuna decompile-all ./po
void sub_1160(FILE *a0)
...
int sub_1170(unsigned long a0)          // the FILE * one line up never arrives

The fix

  • decompile-all decompiles callees before callers (Tarjan SCCs over the call
    graph kuna xrefs publishes); output stays in address order.
  • A callee's recovered parameter types become one more vote at a caller's
    argument when position and storage agree. Nothing is locked, so no call gains
    or loses an argument. A winning vote can add a cast at the argument.
  • The vote is refused where the caller knows better: a frame address or frame
    memory, a declared or global value, another call reading the value as a
    different kind, a constant inside code, a float that the caller uses as an
    integer (or stores, or passes on outside a float register), and a pointer whose
    pointee disagrees with the caller's own loads and stores (an access outside it
    or across its members, integer bits moved through a float member, or a
    constant stored wider than a non-character pointee, which printed as one store
    per byte). A caller with too many addresses to check is refused too.
  • Narrowed and raw-image runs skip the call graph unless the option is named;
    --jobs states nothing and says so. --option protoorder lock (opt-in) also
    states the arity. The callee-first run ends with structsynth's convergence
    sweep, like an address-order run.

The tests

  • 15 tests/cli probes over 10 fixtures; compile-back round trips for floats in
    general registers and float pointees; CLI tests that keep wide constant stores
    whole, at the default and with --option ptrfromuse void, and one for the
    structsynth sweep. Each round trip and CLI test fails without its fix.
  • 60 stripped binaries: --option protoorder off is byte-identical to main, and
    no call gains or loses an argument. type_match over 444 slices: perfect
    1,026 → 1,147, 2 worse. Speed within +5% of main (worst
    libselinux, +4.1%, +2.7% on a re-run).

🤖 Generated with Claude Code

https://claude.ai/code/session_01YFCA715QE6ZBSnTn7bwabG

@mahaloz mahaloz added the full-ci Run the full cargo workspace suite on this PR before merge (internal PRs skip it by default) label Sep 17, 2026
@mahaloz

mahaloz commented Sep 17, 2026

Copy link
Copy Markdown
Contributor Author

[AUTOMATED] Review round 2 — every required change, with what it cost.

1. "Add a guard that can actually fire on stripped input." Two, both from the
callee's own body through the entry-liveness walk calleedeadarg already owns
(probe_callee_entry_dead) rather than a second disassembly matcher: a trailing
parameter the body provably never reads is trimmed, and a callee that
provably reads the register its next argument would arrive in is declined
(Decline::UnderRecovered). Trace tally, find -O2: 105 declared / 76 void-void
/ 26 under-recovered / 2 non-canonical-storage / 1 storage-underivable; 7
under-recovered on kmod -O2. Decline::Variadic is now documented, in the
source and in the spec, as a guard that cannot fire on stripped input.

Partly refuted: the forwarding thunk cannot be declined from this evidence. A
thunk never names the registers it forwards (mov 0x50(%rdi),%rax; jmp *%rax
reads rdi and nothing else), so proves_read is correctly false and
proves_dead is too — the walk declines to say anything, which is what a
one-sided claim is for. Item 2 is what answers that class, completely.

2. "Never let a park REDUCE the argument count." Structural, not a rule: the
parked pieces mark the first slot past the recovered parameters as a variable
tail, which is the one shape func_link_input treats as locked and
input-active, so the caller's own recovery still runs past the parked slots. Your
po2.c repro now renders sub_11c0(a0,1,2,3,4); the thunk is in the fixture and
pinned by both probes.

Deleted-argument count as a first-class number, twelve binaries, 44,772
arguments: 639 at 216 sites → 45 at 25 sites. Not 0, and I am not claiming
it: all 25 are enumerated in deleted-arguments.json, none is a truncation to a
parked list, and the largest group is two sites inside kmod's 700-line
sub_163c0 (the other 55 sites to that same variadic keep 405 of 418 arguments).

3. "Replace the tautological arity statistic." Gone. New instrument
docs/features/protoorder/callsite-metrics.py, validated against your differ to
0.3% on the closed-park build (639/216/32 against your 665/228/33):

closed open (shipped)
arguments deleted 639 / 216 sites 45 / 25 sites
total call arguments 44,772 → 45,263 44,772 → 46,013
string-literal arguments 4,456 → 4,224 4,456 → 4,386
groups newly over the callee's declared arity 32 2
own parameter list shrank 12 2
calls lost 6 2

4. Catalog row. Rewritten; it stated rejected arm A. docs/options.md
regenerated, both repro spellings corrected against the tree's own output, the
fixture .s header rewritten, and the OFF probe renamed
protoorder-off-loses-the-callee-type because it no longer pins a deletion.

5. Caller-side metric. Item 3. type_match is reported as the callee-side
half only, and it costs something: +158 perfect (was +165 with the closed
list) — the price of no longer overruling a caller that over-recovered.

6. Speed. Interleaved min-of-11, large call graphs included: +1.2% kmod,
+3.6% find, +2.5% ls, +2.5% fmt, +0.7% gzip
. "Unmeasurable" was wrong.

7. Spec + hunks. docs/spec/04 has a prose section naming the failure mode
and what the open tail and the two body rules do about it. Four new normalizers
in classify-hunks.py (member-reach, string-constant, negative-spelling,
global-direct): OTHER 2,125 → 890, STATEMENT 693 → 535 of ~8,400.

One thing your round did not ask about, found while checking the witness.
argclobber on alone takes fmt -O2 main's three sub_3700 sites to 2/2/2
and removes both phantom // rdx locals — that option owns the fabricated
trailing argument, not this one. With protoorder on as well it goes inert:
drop_clobber_tail_arg returns early on fc.is_input_locked() || fc.is_dotdotdot(), and an open parked list makes every parked site exactly that.
Reported, not fixed here — the fix belongs in argclobber and is the first named
next lever. The earlier "phantom locals gone" claim was argclobber's; main
declares 15 locals in both arms of this option.

Rebased onto origin/main 0d79b02. Gates: make test 675/675 PARITY OK,
make test-stages 1072/1072 PARITY OK, make test-cli 185/185,
check-spec OK lenient + strict, kuna catalog --check OK, counters --check
no drift, docs/options.md byte-fresh, make rust-test RUST_TEST_RC=0
(the first run was red on option_values_live_value_present_for_87, a manual
count site counters --check does not cover and the rebase reverted; fixed and
re-run green).

@mahaloz

mahaloz commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor Author

[AUTOMATED] Round 3 — the blocker is fixed in code, not in prose.

1. WRONG OUTPUT (blocker) — fixed. The trim had the burden of proof
backwards: a trailing recovered parameter was kept unless the body proved it
dead, so save_cwd's fabricated rdx (neither read nor provably written) was
parked and every caller had to materialise it. It is now stated only where the
body proves it reads the register (proves_input, so xor esi,esi is not a
use). save_cwd parks params=1 trimmed=2, which is its DWARF arity:

$ kuna decompile-all .../O2/findutils/stripped/find --reachable-from 0x24720 --option protoorder on
    v2 = setfilecon(v4,a2);      # was setfilecon(v4)
  if (sub_24230(v8))             # was sub_24230((int *)v9,v10,v11)

regexec(v9,a1,0,0,0) renders all five arguments in grep and diffutils/diff
(the gcc "too few arguments" case is gone); find's lsetfilecon,
__fprintf_chk(…,ctime(&v7)) and error(…,sub_e8a0(0,v5)) are unchanged from
OFF. Over the twelve binaries the class falls 45 args at 25 sites → 17 at 11,
kmod 19 → 0, find 5 → 0, grep 6 → 2. Cost: 7 type_match perfect
functions (+158 → +151)
, aggregate +370.54 → +353.37, worse rows 85 → 80.

2. Spec invariant (major) — deleted. docs/spec/04:1749 now says what the
floor actually buys (truncation to the parked list, 639/216 → 0) and names the
residual: a park of a prototype the callee does not have is a register read that
can still cost an argument at another call in the same caller.

3. Residual characterisation (major) — re-stated with the split. All 11 sites
are in deleted-arguments.json. 4 name their callee (all libext2fs entry
points in the statically linked e2fsck, none with a declared prototype), 1
drops a string literal, 0 drop a nested call. Against the DWARF twin, 3 of
those 4 move TO the callee's true arity and 1 away:
ext2fs_mmp_start 3→1 (truth 1) ✓, ext2fs_u32_list_test 3→2 (2) ✓,
ext2fs_tdb_delete 4→3 (2 params / 3 slots) ✓, ext2fs_new_block2 4→3 (4) ✗.
A fifth, fmt -O2 main → sub_6030, is checkable from the disassembly and is
also a correction: the call site is mov $0x4,%edi and nothing else, so the
rsi the OFF arm renders is left over from the error() two instructions
earlier. So "deleted" is an upper bound on harm — 4 of the 11 remove a caller's
over-recovery, 1 is a real loss, 6 have no ground truth.

One more measure, since the regexec complaint was a compile error: call sites
rendering FEWER arguments than the callee's own emitted declaration takes go
1,163 off → 898 on, down in all twelve binaries and up in none — though the
round-2 policy scored 852 there, because it stated more parameters. That 46-site
regression is the counterweight to the 28 arguments the proven tail stops
deleting; underarity.py is in the feature folder.

4. Regression pin (required) — added. The fixture grows mixed → sink +
overrec, which reproduces the class in 9.2 KB: the round-2 binary renders
sink(); and overrec(v2,a1,a2), this one renders sink(a0,a1); and
overrec(v1). tests/cli/protoorder-on-keeps-a-real-argument.json fails on the
old policy. make test-cli: 186/186.

5. Inert surfaces (minor) — they say so now. decompile-project (with and
without --stream) and decompile-graph warn on stderr; docs/cli.md and
analysis.md §8 name all three surfaces instead of --stream alone.

6. 15 locals instead of 17 (minor) — dropped. You were right; record.json
already said 15 in both arms.

7. Body (minor) — rewritten. Three sections, 78 lines, repro first, the
measurement table moved to docs/features/protoorder/. The go/no-go is re-asked
with the residual priced in, and it names what a stricter rule would cost.

Two things I did not do. I did not gate the park behind an arity ceiling —
the failures are not high-arity, save_cwd had three parameters — and I did not
take the stricter form (park only where the body reads every recovered
parameter): it costs more than the 7 perfect functions the proven tail already
gave up and I have not measured it, so it is named in the proposal rather than
claimed. Your speed reading stands: two interleaved min-of-11 runs of mine
disagree by several points per slice on this box (fmt +2.5% and −0.9% against
your +1.3%), so both runs are published and the claim is "low single-digit
percent", not a cell.

Gates on the rebased tree: make test 675/675 PARITY OK · make test-stages
1072/1072 PARITY OK · make check-spec OK lenient + strict · make test-cli
186/186 · kuna catalog --check OK · counters --check no drift ·
docs/options.md byte-fresh · two protoorder on runs sha256-identical ·
--jobs 4 --option protoorder on rc=2 · make rust-test RUST_TEST_RC=0 (415 test binaries ok, 0 FAILED).

🤖 Generated with Claude Code

https://claude.ai/code/session_01MAeimyWm5oSewpeCgAwY29

@mahaloz

mahaloz commented Sep 17, 2026

Copy link
Copy Markdown
Contributor Author

[AUTOMATED] Round 4 — every required change, and one refutation.

1. The register-file-saturating variadic — closed in code, option (b).
New decline register-file-full: a recovered list whose last parameter is in a
register and whose next slot is not. That is exactly the boundary where
under_recovered goes blind, so the rule is stated as "the walk has no witness
here" rather than as a variadic test, and it is asked of the model in both
directions (a convention that passes everything on the stack never trips it).
Your mirai witness:

[protoorder] decline sub_85c0 @0x85c0 register-file-full
  sub_85c0("[main] Attempting to connect to CNC\n");
void sub_2640(void)

Your 25-line repro is in the bundle (docs/features/protoorder/register-save-repro.md),
with the caveat that on a _FORTIFY_SOURCE toolchain it recovers 14 parameters
and lands on the rule you already have. The in-repo form is vfmt/vfmtcaller
in the fixture — the prologue by hand, save area read back at a dynamic index —
and a fourth probe, tests/cli/protoorder-declines-a-register-saturating-callee.json.
I built the counterfactual to check the probe is not vacuous: without the rule
the site renders vfmt((unsigned char *)0x402004,a1,a2,a3,a4,a5) and
vfmtcaller becomes a six-parameter function.

Cost: 46 perfect on the campaign typesweep (+151 → +105) and 25 on
firmware (+38 → +13). The rule is the second most common decline over the corpus
(1,943 against 7,611 parks) and the most common on AAPCS.

2 and 3. Re-measured, and the metric's blindness is where the number is.
Corpus is 22 binaries / 14,142 functions, never pooled, with the
fabricated-parameter counter (variables[] rows with kind == "arg") beside
type_match. You were right that type_match.py:1053-1098 sizes everything on
ground_truth_vars; that is now stated in the PR body's go/no-go paragraph, in
proposal.md, in analysis.md §5 and in record.json.

20 x86-64 userland 2 ARM Cortex-M
call arguments gained / deleted +818 at 418 / 28 at 21 +2,371 at 1,834 / 881 at 518
never-assigned arguments 281 → 374 470 → 997
functions gaining an arg row 155 (2.1%) 630 (9.6%)
over-arity groups new / fixed 5 / 158 730 / 148
under-arity sites 1,819 → 1,464 3,795 → 4,839

x86-64 userland is a win by every column, mirai included (its allphantom
goes 7 → 6). ARM Cortex-M is a loss by every column, and the firmware
type_match sweep still says +13 perfect — which is your point, in one pair of
numbers, and it is now the PR body's headline caveat.

I did not fix the ARM case, and the PR says so. The mechanism is not the
acceptance policy: betaflight's sub_800c1ec is parked with one parameter,
the correct list, byte-identical to the OFF arm, and its caller still renders
sub_800c1ec(a0,a3). The open tail makes the spec variadic, and
characterize_as_input_param then sends a variadic spec straight to the model,
so every argument register is a candidate at that site again. I built and
measured the obvious fix — close the tail where the entry walk decoded the whole
callee body — and it is a null result: 785 functions gain arg rows either way
and 19 more arguments are deleted, because the callees that fabricate are the
ones that call something. Reverted, and recorded in the spec as a rejected arm.

4. argclobber is in the PR body, with the lines: neither 1/2/3,
argclobber on 2/2/2, protoorder on 2/2/3, both 2/2/3.

5. use_when rewritten — shipped numbers, both directions of harm, the
fabricated-parameter symptom, and "prefer argclobber where the complaint is a
trailing register argument". docs/options.md regenerated;
tests/fixtures/phase_catalog.json re-recorded with it.

6. The string row was a cast artifact, as you said. callsite-metrics.py
now matches a string literal anywhere in the argument text instead of testing
for a " prefix, and the column reverses: 7,737 → 7,786 on x86-64 and
1,925 → 1,985 on ARM, i.e. the option adds string arguments in both. And
underarity.py no longer hard-codes a path (neither does invariants.py, which
had the same shape).

On the info item: agreed, and the proposal already trades the 2/2/2 witness
away explicitly — the third site's extra argument is what the open tail costs,
and argclobber is the option that owns it.

Gates, all re-run on this tree: make test PARITY OK 675/675, make test-stages
PARITY OK, make check-spec lenient + strict, make test-cli 187/187,
kuna catalog --check OK, counters --check no drift, docs/options.md
byte-fresh, make rust-test RUST_TEST_RC=0 (415 test binaries ok, 0 FAILED,
lane started 21:03:13Z on 974f5501 — the last commit outside docs/). The
first round-4 lane came back rc=2 on catalog_bytecompat, because moving the
phases.toml prose moves tests/fixtures/phase_catalog.json; it is re-recorded.
Speed re-measured on a quiet box after the suite: +2.1% / +4.3% / +6.3% on
fmt / ls / kmod, in range with the two earlier runs — the new rule adds no model
call and declines 1,943 parks, so it cannot be a new cost.

Still a [PROPOSAL]. Do not merge.

@mahaloz
mahaloz marked this pull request as ready for review September 17, 2026 23:15
@mahaloz mahaloz changed the title [PROPOSAL][AUTOMATED] protoorder: decompile callees first so a recovered prototype reaches its callers [AUTOMATED] feat(p4): decompile callees first and type call-site arguments from the callee's recovered prototype (protoorder) Sep 17, 2026
@mahaloz

mahaloz commented Sep 17, 2026

Copy link
Copy Markdown
Contributor Author

Round 5 replaces the design the first four rounds measured, because that design could not
pass the bar: type_match went up while call-site arity went down, and type_match is
structurally blind to a fabricated parameter.

What changed. The option is now protoorder off|types|lock, default types, and
the default states only TYPES. Nothing is written to the symbol table, so no call spec is
input-locked and ActionFuncLink runs the caller's own argument recovery at every call
exactly as it does with the option off. The callee's recovered parameter types (and a
non-void return) go on Architecture::kuna_protoorder_types, are copied onto each caller's
Funcdata by seed_protoorder_types (the bridge calleedeadarg/rustabi already take),
and reach the call site through the recovered arm of TypeOpCall::getInputLocal as a VOTE
in Varnode::getLocalType's type_order fold. Slot i matches only when position AND
storage agree with FuncCallSpecs::final_input_storage. A declared prototype still answers
first.

The arity counters, 22 binaries / 14,142 functions:

20 x86-64 userland 2 ARM Cortex-M
total call arguments 71,672 -> 71,672 33,145 -> 33,145
arguments added / deleted 0 / 0 0 / 0
functions gaining a variables[] arg row 0 0
groups newly over the callee's declared arity 0 0
never-assigned arguments 180 -> 177 394 -> 385

invariants.py: 0 calls lost, 0 gained, goto delta 0, return delta 0.
classify-hunks.py: own_signature_arity_delta empty, 0 call-arity hunks.

And it scores better than the locking design did: 444-slice type_match perfect
959 -> 1089 (+130) against the locking design's +105 on the same corpus, 1,093 improved
/ 42 worsened, 2 off perfect. The reason is that the register-file decline lock needs to
avoid fabricating parameters costs 46 perfect functions, and types does not need it.
Speed is +0.4% / +1.1% / +0.3% (interleaved min-of-15) rather than +2.1% / +4.3% / +6.3%,
because types never bumps Database::kuna_generation and so invalidates no snapshot.

The three review points from earlier rounds:

  • The argclobber composition regression is gone for the default:
    --option argclobber on alone gives fmt's three sub_3700 sites 2/2/2 with
    unsigned long a1; with protoorder types as well it is 2/2/2 and char *a1.
    lock still disables argclobber at a stated site (a locked+variadic spec), reported.
  • The ARM Cortex-M population is no longer a loss column: every counter is zero or down.
  • Three bugs in the round-4 differ are fixed (it counted (char)(...) casts and
    SUB84/builtin_strncpy as calls and split inside string literals); without them a pure
    type change reports 6 deleted arguments on betaflight.

The 42 worse type_match rows were all read. The loss class is one-directional: the fold
refuses a LESS specific vote, not a worse one, so a callee that over-typed a parameter
restates it -- grep -O0 memchr_kwset's char * becomes unsigned long *. 1,225 gain.

lock keeps the whole round-4 acceptance policy and all of its evidence, opt-in.

@mahaloz
mahaloz force-pushed the feat/protoorder branch 3 times, most recently from 9527491 to 0560fcf Compare September 18, 2026 18:48
@mahaloz
mahaloz force-pushed the feat/protoorder branch 6 times, most recently from fd698ad to 56e61ac Compare September 19, 2026 17:28
mahaloz and others added 9 commits September 19, 2026 20:09
…call-site arguments from the callee's recovered prototype

Squash of the protoorder branch (rounds 1-11) before rebasing onto main d96e340.
Round 11: a pointer vote is refused where the caller's loads and stores
disagree with a float or composite pointee (an access or address outside it,
across or inside members, a step of other than one element, a pointer member's
own pointee, sibling loads of the same field, integer bits moved through a
float member); a float type never lands on a caller parameter in a register the
convention would not give a float; a NaN constant never takes a float vote.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01YFCA715QE6ZBSnTn7bwabG
…e caller stores a wider constant through

A vote whose pointee is a non-character integer, bool or pointer is refused
when the caller stores a constant wider than it through the pointer at a fixed
place or a record stride: SplitDatatype printed such stores one per element
(gzip ".tar", betaflight 1.0f; bzip2 and tar with ptrfromuse on). Taken from
the ptrfromuse-on evaluation (cde5761), without its default flip. Fixture
protoorder_narrowvote_x86_64, CLI test a_byte_pointee_vote_keeps_the_callers_wide_stores
(default and ptrfromuse void), probe protoorder-types-keeps-a-wide-store-whole.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01YFCA715QE6ZBSnTn7bwabG
mahaloz and others added 18 commits September 19, 2026 20:09
…wide constant store, and when the walk runs out

The narrow primitive pointee rule let a vote through when the access walk gave
up (more than 511 derived addresses) and when a constant was stored at a stride
of its own width; both printed each eight-byte store as eight byte stores.
Fixture protoorder_widefill_x86_64 carries both shapes.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01YFCA715QE6ZBSnTn7bwabG
…s convergence sweep

decompile-all's callee-first path decompiled each target with decompile_entry
and never reached the batch's converge_synthesized_structs (#675), so under the
protoorder default a function kept a structure a later, larger one had
superseded (tests/cli/structsynth-sweep-mints-no-third-name failed). The sweep
now runs at the end of the callee-first path, in plan order with each target's
own park decision; not under lock, where a parked prototype is declared.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01YFCA715QE6ZBSnTn7bwabG
@mahaloz
mahaloz merged commit 3433e05 into main Sep 19, 2026
9 checks passed
@mahaloz
mahaloz deleted the feat/protoorder branch September 19, 2026 23:11
mahaloz added a commit that referenced this pull request Sep 19, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

full-ci Run the full cargo workspace suite on this PR before merge (internal PRs skip it by default)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants