Skip to content

[AUTOMATED] fix(p3): make the opcode -> TypeOp seam total (24 functions decompiled to nothing) - #227

Merged
mahaloz merged 2 commits into
mainfrom
fix/p3-opcode-mapping-total
Aug 1, 2026
Merged

mahaloz merged 2 commits into
mainfrom
fix/p3-opcode-mapping-total

Conversation

@mahaloz

@mahaloz mahaloz commented Aug 1, 2026

Copy link
Copy Markdown
Contributor

The bug: a function that decompiles to nothing

24 functions in a 20,246-function desktop-Linux sweep produced no output at
all
-- the caller got one error record and zero C. Among them: coreutils
timeout/split main, bash wait_for (+6 more), 3 tar functions, and one
each in grep, scp, sftp, sftp-server. Every one of those is a guaranteed zero in
any benchmark.

P3 carried six hand-maintained copies of the glb->inst[opc] opcode ->
TypeOp mapping, one per rule-batch file, each a partial whitelist of "the
op-codes this batch emits" with a panic! (or a silently-wrong flagless)
default arm. The copies drifted apart, so a rule that legitimately retyped an op
to an op-code its own file had not enumerated unwound the whole decompilation
(caught per-function, reported as an error record).

Seam Missing op-code(s) Symptom
ruleaction_2::op_typeop (panic!) CPUI_INT_SRIGHT RuleBitUndistribute on (V s>> c) & (W s>> c) -- 24 functions / 27 panic events
ruleaction_3::opflags_for (panic!) CPUI_FLOAT_INT2FLOAT (x86-64), CPUI_FLOAT_LESS, CPUI_FLOAT_ADD (ARM) RuleMultiCollapse collapsing a phi to a float op
ruleaction_8::resolve_typeop (panic!) everything outside its 20 listed op-codes latent
ruleaction_5/_6/_7 (silent fallback) everything outside their lists wrong/zero property bits on the retyped op

The divergence was the tell: ruleaction_3 did list INT_SRIGHT,
ruleaction_2 listed things _3 missed. Six partial copies of one total
mapping.

The fix: derive every seam from the one total table

The tree already had the total table -- p5_types/typeop.rs (type_op_info),
transcribed field-for-field from upstream typeop.cc, whose match has no
wildcard arm
(so a new op-code cannot enter the enum without the compiler
demanding its row). ruleaction_1/_4 already resolved through it; the other
six now do too, via the new seam_type_op_for:

  • total over every op-code the enum defines;
  • the one value with no upstream inst[] record -- the CPUI_MAX sentinel,
    which is not an operation -- degrades to a property-less skeleton instead of
    aborting the function (no panic! left in the seam);
  • 291 lines of duplicated whitelist deleted.

Is it a behavior change? No -- measured

For every op-code the old whitelists listed, the canonical table carries the
same opflags; only the debug display name differs, and that string is read
solely by the infra/graph.rs dev dump (funcdata_printraw already reads names
from the canonical table).

Sweep of 12 desktop/embedded ELF binaries, 15,596 functions,
decompile-all --json --mode reliable, before vs after:

Binary error records before -> after
O0 coreutils timeout 1 -> 0
O0 coreutils split 1 -> 0
O0 coreutils ls 0 -> 0
O0 bash 7 -> 0
O0 tar 3 -> 0
O0 grep 1 -> 0
O0 openssh scp / sftp / sftp-server 1 -> 0 each
O2-noinline coreutils ls 1 -> 0
O2-noinline coreutils timeout 0 -> 0
O2-noinline betaflight STM32F405 4 -> 2
TOTAL 21 -> 2
  • 19 functions recovered (all of them whitelist panics).
  • The 2 remaining are the p2_lift/jumptable.rs:1811 panic and one loader read
    (Unable to load 512 bytes) -- both owned by other PRs.
  • Zero functions that already decompiled changed their emitted text
    (per-function SHA of the emitted C compared across all 15,596).

Speed (median of 3, whole-binary decompile-all, budget +5%):

Binary before after delta
coreutils timeout 1362 ms 1406 ms +3.23%
grep 6946 ms 7094 ms +2.14%
openssh sftp-server 5255 ms 5110 ms -2.78%

The positives are the previously-abandoned functions now decompiling in full.

No option: this only corrects wrong output (a function that produced nothing now
produces C), and it restores upstream behavior rather than diverging from it, so
there is no DIV row either.

Durability -- the part that stops this recurring

  • p5_types/typeop/tests.rs: iterates every OpCode the enum defines and
    asserts the seam answers for all of them with real property bits equal to
    inst[], plus the CPUI_MAX degradation and the four op-codes that were
    missing. Fails if any future op-code is unanswerable.
  • ruleaction_2/ruleaction_3 each carry the same sweep over their own local
    seam function, so re-introducing a per-file whitelist fails immediately.
  • tests/stages/ghdec-opcode-seam.xml -- end-to-end bytechunk -> lo fu -> decompile -> print C on the minimized shape (a >> 3) & (b >> 3):
    • pre-fix (verified by stashing the fix and rebuilding):
      thread 'main' panicked at ruleaction_2.rs:96: ruleaction_2 op_typeop: unhandled opcode CPUI_INT_SRIGHT and an empty body -- 2 of 3 asserts FAIL;
    • post-fix: return (int4)(a1 & a0) >> 3; -- all 3 pass.

Gates

Gate Result
make test PARITY OK (675/675) -- docs/baseline.json untouched
make test-stages PARITY OK (308/308) -- stages baseline re-recorded for the new case
make rust-test green
make check-spec green
kuna catalog --check green

Spec updated in prose: docs/spec/03-ssa-and-simplification.md §3.2 now
describes the retype-an-op-mid-rule seam and why its totality is load-bearing.

Provenance: inspiration = "decbench:cases-missing pool; coreutils timeout/split main, bash, tar".

🤖 Generated with Claude Code

https://claude.ai/code/session_011RXVU58TKJxb518oViChwo

24 functions in a 20,246-function desktop-Linux sweep produced NO OUTPUT
AT ALL -- among them coreutils `timeout`/`split` `main`, bash `wait_for`,
3 tar functions and one each in grep, scp, sftp, sftp-server. The caller
got a single error record instead of C.

Root cause: P3 carried six hand-maintained copies of the
`glb->inst[opc]` opcode -> TypeOp mapping, one per rule-batch file, each
a partial whitelist of "the op-codes this batch emits" with a `panic!`
(or a silently-wrong flagless) default arm. The copies drifted, so a
rule that legitimately retyped an op to an op-code its own file had not
enumerated unwound the whole decompilation:

  * `ruleaction_2::op_typeop` had no `CPUI_INT_SRIGHT` --
    `RuleBitUndistribute` rewriting `(V s>> c) & (W s>> c)` panicked.
    24 functions / 27 panic events.
  * `ruleaction_3::opflags_for` had no `CPUI_FLOAT_INT2FLOAT` (x86-64),
    no `CPUI_FLOAT_LESS` and no `CPUI_FLOAT_ADD` (ARM/betaflight) --
    `RuleMultiCollapse` collapsing a phi to one of those panicked.
  * `ruleaction_8::resolve_typeop` panicked on anything outside its 20
    listed op-codes; `ruleaction_5`/`_6`/`_7` instead fell back to a
    skeleton with wrong (or zero) property bits.

The tree already had the total table -- `p5_types/typeop.rs`
(`type_op_info`), transcribed field-for-field from upstream `typeop.cc`,
whose `match` has no wildcard arm so the compiler enforces completeness
(`ruleaction_1`/`_4` already resolved through it). All six seams now do
the same, via the new `seam_type_op_for`: total over every op-code, and
the one value with no upstream record -- the `CPUI_MAX` sentinel, which
is not an operation -- degrades to a property-less skeleton instead of
aborting the function.

Not a behavior change for anything that already worked: for every
op-code the old whitelists listed, the canonical table carries the same
`opflags` (only the debug display name differs, and that is read only by
the `infra/graph.rs` dev dump). Measured on 12 desktop/embedded ELF
binaries / 15,596 functions with `decompile-all --mode reliable`: error
records 21 -> 2 (19 functions recovered; the 2 remaining are the
`p2_lift/jumptable.rs:1811` panic and one loader read, both owned
elsewhere) and ZERO functions that already decompiled changed their
emitted text. Speed within noise and budget: +3.23% / +2.14% / -2.78%
(median of 3, coreutils timeout / grep / sftp-server), the positives
being the previously-abandoned functions now decompiling in full.

Durability (the part that stops this recurring): `typeop/tests.rs`
iterates every `OpCode` the enum defines and asserts the seam answers
with real property bits for all of them, matching `inst[]`, plus the
sentinel degradation and the four op-codes that were missing;
`ruleaction_2`/`_3` each carry the same sweep over their own local seam.

Provenance: inspiration = "decbench:cases-missing pool; coreutils
timeout/split main, bash, tar".

Gates: test 675/675 PARITY OK, test-stages 308/308 PARITY OK, rust-test
green, check-spec green, catalog --check green. End-to-end regression:
`tests/stages/ghdec-opcode-seam.xml` decompiles the minimized
`(a >> 3) & (b >> 3)` shape from a raw byte chunk -- pre-fix it fails
with `ruleaction_2 op_typeop: unhandled opcode CPUI_INT_SRIGHT` and an
empty body, post-fix it emits `return (int4)(a1 & a0) >> 3;`.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_011RXVU58TKJxb518oViChwo
@mahaloz

mahaloz commented Aug 1, 2026

Copy link
Copy Markdown
Contributor Author

Scope note: one seam deliberately left alone

p3_dataflow/heritage.rs (typeop_skeleton) is a seventh local opcode -> TypeOp
builder with a panic! arm, and this PR does not touch it. Two reasons:

  1. It is not reachable: all 19 call sites pass one of three literal op-codes
    (CPUI_MULTIEQUAL, CPUI_SUBPIECE, CPUI_PIECE), so no drift is possible
    and it produced none of the observed failures.
  2. Migrating it would be a real behavior change rather than a bug fix: its
    MULTIEQUAL row carries only marker, while the canonical inst[] row is
    special | marker | nocollapse. Handing heritage's phis the upstream flag
    word affects is_special()/is_nocollapse() on every phi in every function
    and belongs in its own measured PR, not here.

Everything in this PR is flag-for-flag identical to what the seams already
installed for the op-codes they listed -- which is why the 675-assertion corpus
and 15,596 already-working functions are byte-identical.

…-total

# Conflicts:
#	decompiler/crates/kuna-base/src/xml.rs
#	docs/baseline-stages.json
#	tests/stages/README.md
@mahaloz
mahaloz merged commit c99f63e into main Aug 1, 2026
9 checks passed
@mahaloz
mahaloz deleted the fix/p3-opcode-mapping-total branch August 1, 2026 19:10
mahaloz added a commit that referenced this pull request Aug 1, 2026
Two P6 cover-extension steps were dropped in the merge port, and each made
kuna emit C that computes a DIFFERENT VALUE than the binary.

1. `Funcdata::build_copy_pair_range` built `Merge::checkCopyPair`'s dominance
   range from the dominant COPY's def point alone, omitting upstream's
   `range.addRefPoint(subOp, subOp->getIn(0))` (merge.cc:1121). A def-point-only
   Cover is a point, not a range, so no intervening write to the HighVariable was
   ever found inside it, `checkCopyPair` called every dominated COPY redundant,
   and `markRedundantCopies` marked load-bearing restores non-printing. At -O0 a
   guard-clause function whose `return param;` paths share one epilogue then
   returns a failed call's NULL instead of the parameter, and `for` loops lose
   their initializer. The sibling `build_single_read_cover` records the identical
   omission as LOSS-229 and had already been fixed; this is the second site.

2. `ActionMarkImplied` set the implied flag directly instead of going through
   `Merge::markImplied` (merge.cc:1595-1605), dropping the operand cover-dirtying,
   and `MergeContext::vn_set_cover_dirty` did not forward a Varnode `coverdirty`
   to the owning HighVariable the way `Varnode::setFlags` does
   (varnode.cc:377-378). `Cover::rebuild` walks forward through implied consumers,
   so an operand's live range only reaches the point where the inlined expression
   is printed once it is recomputed — and `HighIntersectTest::update_high`
   short-circuits on a high it believes is clean. Without both halves the
   speculative merges saw pre-inlining Covers and folded two values that are live
   at the same printed expression into one variable, so the emitted C read the
   later value where the binary reads the earlier one.

Both are upstream-faithful restorations, not new policy, so neither ships behind
an option: a default-off flag would leave kuna miscompiling by default.

Gates: make test PARITY OK (675/675), make test-stages PARITY OK (314/314),
make rust-test green, make check-spec green, kuna catalog --check OK. No baseline
re-pin and no per-test opt-out.

Regression: new fixture `covercopy_x86_64` (+ source) and
`kuna-console/tests/verify_cover_miscompile.rs`, one test per root cause,
asserting the VALUE-carrying statement (the `vN = a0;` restore after the
clobbering call; the two selects staying two variables and both being read by the
call argument). Each test fails on the pre-fix tree.

`verify_declared_vars`' sanity floor moves 5 -> 4: with Covers recomputed at the
right points the `make_dir_clone` size phi finally coalesces with the `strlen`
result the way upstream does, so the un-coalesced `v5` is gone. The
undeclared-variable gate itself is unchanged and still passes.

Rebased onto origin/main after #227 (the P3 opcode -> TypeOp seam totalisation)
and re-verified end to end on that base; the root causes here are Cover
construction and Cover invalidation, not op property bits. DIV-44..46 were taken
by #224/#225/#226 while this was in flight, so this claims DIV-47.

Docs: DIV-47 in docs/history.md; docs/spec/06-variables-and-merge.md gains the
prose for both cover extensions (the two-point Cover construction and the
implied-consumer walk).

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_011RXVU58TKJxb518oViChwo
mahaloz added a commit that referenced this pull request Aug 1, 2026
#228)

Two P6 cover-extension steps were dropped in the merge port, and each made
kuna emit C that computes a DIFFERENT VALUE than the binary.

1. `Funcdata::build_copy_pair_range` built `Merge::checkCopyPair`'s dominance
   range from the dominant COPY's def point alone, omitting upstream's
   `range.addRefPoint(subOp, subOp->getIn(0))` (merge.cc:1121). A def-point-only
   Cover is a point, not a range, so no intervening write to the HighVariable was
   ever found inside it, `checkCopyPair` called every dominated COPY redundant,
   and `markRedundantCopies` marked load-bearing restores non-printing. At -O0 a
   guard-clause function whose `return param;` paths share one epilogue then
   returns a failed call's NULL instead of the parameter, and `for` loops lose
   their initializer. The sibling `build_single_read_cover` records the identical
   omission as LOSS-229 and had already been fixed; this is the second site.

2. `ActionMarkImplied` set the implied flag directly instead of going through
   `Merge::markImplied` (merge.cc:1595-1605), dropping the operand cover-dirtying,
   and `MergeContext::vn_set_cover_dirty` did not forward a Varnode `coverdirty`
   to the owning HighVariable the way `Varnode::setFlags` does
   (varnode.cc:377-378). `Cover::rebuild` walks forward through implied consumers,
   so an operand's live range only reaches the point where the inlined expression
   is printed once it is recomputed — and `HighIntersectTest::update_high`
   short-circuits on a high it believes is clean. Without both halves the
   speculative merges saw pre-inlining Covers and folded two values that are live
   at the same printed expression into one variable, so the emitted C read the
   later value where the binary reads the earlier one.

Both are upstream-faithful restorations, not new policy, so neither ships behind
an option: a default-off flag would leave kuna miscompiling by default.

Gates: make test PARITY OK (675/675), make test-stages PARITY OK (314/314),
make rust-test green, make check-spec green, kuna catalog --check OK. No baseline
re-pin and no per-test opt-out.

Regression: new fixture `covercopy_x86_64` (+ source) and
`kuna-console/tests/verify_cover_miscompile.rs`, one test per root cause,
asserting the VALUE-carrying statement (the `vN = a0;` restore after the
clobbering call; the two selects staying two variables and both being read by the
call argument). Each test fails on the pre-fix tree.

`verify_declared_vars`' sanity floor moves 5 -> 4: with Covers recomputed at the
right points the `make_dir_clone` size phi finally coalesces with the `strlen`
result the way upstream does, so the un-coalesced `v5` is gone. The
undeclared-variable gate itself is unchanged and still passes.

Rebased onto origin/main after #227 (the P3 opcode -> TypeOp seam totalisation)
and re-verified end to end on that base; the root causes here are Cover
construction and Cover invalidation, not op property bits. DIV-44..46 were taken
by #224/#225/#226 while this was in flight, so this claims DIV-47.

Docs: DIV-47 in docs/history.md; docs/spec/06-variables-and-merge.md gains the
prose for both cover extensions (the two-point Cover construction and the
implied-consumer walk).


Claude-Session: https://claude.ai/code/session_011RXVU58TKJxb518oViChwo

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
mahaloz added a commit that referenced this pull request Aug 1, 2026
)

`main` in coreutils comm/join/uniq produced no output at all: the decompile
pipeline panicked at `p2_lift/jumptable.rs:1811` and the whole function came back
as a warning shell. Six functions -- comm/join/uniq `main`, at -O0 and at
-O2-noinline -- every one of them the getopt_long dispatch.

The chain. `loweredswitch` (P2, default-on) rewires a comparison cascade's head
into a synthetic BRANCHIND and then sweeps the orphaned compare spine with
`removeUnreachableBlocks`. In these binaries the cascade is only half the
dispatch: the short options ('1'/'2'/'3' and the negative help/version sentinels)
go through the cascade, while the dense long-option range (0x7a, 0x80..0x83) goes
through a genuine GCC PIC relative-offset jump table (`3e ff e0  notrack jmp rax`
at comm 0x3aed, table in .rodata at 0x9800). Severing the cascade head's
out-edges strands that table's block, and the sweep destroys its ops -- including
the real BRANCHIND. The ported `blockRemoveInternal` did NOT drop the table
(`funcdata_block.rs:1369` was `// JumpTable *jt = findJumpTable(op); ... --
STUB(W4)`), so a labelless table survived in `jumpvec`. `ActionSwitchNorm` then
re-recovered its model and `JumpBasic::findDeterminingVarnodes` unwrapped
`inrefs[0]` of a `pcodeop_flags::dead` op.

Two parts, both strict bug fixes, so no option:

1. Parity + crash-proofing. `Funcdata::remove_jump_table` (C++
   `Funcdata::removeJumpTable`, `funcdata_block.cc:470`) is ported and
   `block_remove_internal` uses it via the existing `find_jump_table_index`,
   exactly as `funcdata_block.cc:272` does. `ActionSwitchNorm::apply` gains the
   liveness guard `install_switch_defaults` already had (skip a table whose
   indirect op is absent / dead / parentless), and
   `JumpBasic::find_determining_varnodes` returns `KunaResult<()>` instead of
   unwrapping, so a stale table abandons its own recovery rather than the run.

2. Quality. Part 1 alone stops the panic but leaves the real table's block
   destroyed: comm `main` then rendered a 60-line body whose switch carried only
   the cascade's cases and had silently lost 'z', --check-order, --nocheck-order,
   --output-delimiter and --total. So `kuna_install_lowered_switch` now declines
   when its rewiring would strand a block whose tail BRANCHIND already owns a
   recovered `JumpTable` (`kuna_lowered_switch_strands_table` walks reachability
   from the entry over the post-surgery successor relation, before any edit). Its
   existing guard only checked for a table at the head's own branch address, which
   never matches here -- the cascade head and the real BRANCHIND are different
   instructions. This narrows when an existing option fires, so it lives inside
   `loweredswitch` rather than behind a new flag.
   `tests/stages/ghangr-loweredswitch-mv.xml` (mv -O2, a cascade with no
   downstream table) still installs, so the decline is not over-broad.

All six functions now render identically to `--option loweredswitch off`, which
is the shape Ghidra emits (comm `main`: 97 lines, `switch(v1) { case 0x7a ...
case 0x80 ... case 0x83 ... default }`).

Corpus sweep, `kuna decompile-all --json --mode reliable` over 16 stripped
binaries (coreutils/grep/gzip/diffutils, O0 + O2-noinline), 6130 functions: error
records 6 -> 0, all six the `jumptable.rs:1811` panic. The
`ruleaction_2.rs:96`/`ruleaction_3.rs:125` opcode-whitelist family is 0 both
before and after on this base (it landed on main in #227) and is not touched
here.

Speed: no regression. Wall-clock `decompile-all` over 5 binaries, 6 reps each:
before min 35.48 s / median 35.62 s, after min 33.51 s / median 34.83 s.
`python3 -m scripts.pipeline.timeit --option loweredswitch` on comm sub_3994:
off 256.2 ms, on 228.8 ms, delta -10.69% (budget 5.0%) -> within budget.

Gates: make test PARITY OK (675/675), make test-stages PARITY OK (323/323),
make rust-test green, make check-spec OK, kuna catalog --check OK. No baseline
re-pin of docs/baseline.json. Spec prose in docs/spec/02-lift-and-flow.md (table
lifetime and the install decline); regression test
tests/stages/ghdec-stalejumptable.xml (two-pass over the real comm bytes: 0/5
assertions before, 5/5 after). The new stage XML bumps the hard-coded corpus
file count in decompiler/crates/kuna-base/src/xml.rs (177 -> 178).

inspiration = "decbench:cases-missing pool; coreutils comm/join/uniq main"


Claude-Session: https://claude.ai/code/session_011RXVU58TKJxb518oViChwo

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
mahaloz added a commit that referenced this pull request Aug 1, 2026
…timating it (#237)

The recall pool was the campaign's headline claim and it was carrying an
unverified number. Measured properly it is 7,354, not 6,540 -- the smaller
figure could not be reproduced under any rival-subset or filter variant.

Where it actually goes, and most of this contradicts what the campaign
believed:

  63    (0.9%)  genuinely recovered by the 2026-08-01 fix wave
  1,994 (27.1%) already fixed BEFORE the wave -- the stored kuna artifacts
                were 12-16 days old, so the pool was measuring staleness
  3,233 (44.0%) decbench's .text filter, never kuna's fault
  2,061 (28.0%) still missing, real kuna gap

So the wave's benchmark-visible recall gain is small and the campaign should
say so. Two corrections in the other direction: #224 recovered 256 freertos
functions decbench structurally cannot score, and both #227 and #234
under-claimed (19 -> measured 50; 6 -> measured 13).

98.3% of the live remainder is function-entry granularity on embedded ARM --
kuna emits a body for code CONTAINING the DWARF low_pc but does not start a
function AT it, median 24 bytes away. That is one gap, not two thousand.

Highest-value remaining bug: rename_recurse / "Overlapping input varnodes" on
gnulib's rpl_fcntl, hard-failing one function in 48 of 213 optimized x86-64
binaries, -O2 only.

Method notes worth keeping: matching is by address, never by name; PE targets
report ImageBase+RVA where the rival artifacts record RVAs, and uncorrected
that fabricates 181 fake gaps.
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