Skip to content

[AUTOMATED] fix(p6): kuna emits the wrong value — restore the two dropped Cover extensions (DIV-47) - #228

Merged
mahaloz merged 1 commit into
mainfrom
fix/p6-lost-restore
Aug 1, 2026
Merged

mahaloz merged 1 commit into
mainfrom
fix/p6-lost-restore

Conversation

@mahaloz

@mahaloz mahaloz commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

kuna was emitting C that computes a different value than the binary. Two
independent decbench witnesses turned out to be two distinct bugs — but one family:
in both, a Cover that upstream Ghidra builds larger was built smaller by the
port, so a legality test found no conflict where one exists.

Neither ships behind an option. Per AGENTS.md a strict bug fix that only corrects
wrong output needs no flag, and a default-off flag would leave kuna miscompiling by
default. Both changes are byte-faithful restorations of upstream code, not new policy.


Root cause 1 — a dropped restore (Merge::checkCopyPair)

Funcdata::build_copy_pair_range built the dominance range from the dominant COPY's
def point alone. Upstream (merge.cc:1120-1121) builds it from two points:

  Cover range;
  range.addDefPoint(domOp->getOut());
  range.addRefPoint(subOp,subOp->getIn(0));   // <- the port dropped this line

A def-point-only Cover is a point, not a range, so range.contain(op,1) answers
"no" for every op and checkCopyPair reports every dominated COPY redundant.
markRedundantCopies then marks it non-printing and the statement disappears.

At -O0 this is routine: several return param; paths compile to
mov -N(%rbp),%rax ; jmp .Lepi, so several COPYs of one parameter land in one
HighVariable — and the reload that follows a call clobbering the same register gets
deleted. The sibling build_single_read_cover records the identical omission as
LOSS-229 and had already been fixed; this was the second site.

Witness — gnutls ocsptool port_to_service @ 0x1144a
(~/github/decbench/results/full_run/O0/gnutls/stripped/ocsptool). The binary
explicitly reloads sport at 0x114e8 (mov -0x18(%rbp),%rax) before jumping to
the epilogue; kuna dropped it.

     if (v2) // branch-flip
       v2 = *(char **)v2;
     else {
       fprintf(stderr,"Warning: getservbyport(%s) failed. ...",a0);
+      v2 = a0;
     }
   }
   return v2;

Executable proof (both bodies transcribed verbatim, gcc -O0, input "99999"
so getservbyport fails):

Warning: getservbyport(99999) failed. Using port number as service.
ref          -> "99999" (strlen 5)
Warning: getservbyport(99999) failed. Using port number as service.
kuna_after   -> "99999" (strlen 5)
Warning: getservbyport(99999) failed. Using port number as service.
kuna_before  -> NULL

Ghidra, IDA, angr, binja and phoenix are all correct here — this was kuna-specific.

The same defect also silently deleted for loop initializers (the while-do
for-form asks testTerminal for a printed op; a non-printing one yields an empty
init slot and the statement is suppressed too):

-        for (; *v3; v3 = &v3[1]) {
+        for (v3 = a0; *v3; v3 = &v3[1]) {

Root cause 2 — an over-merge (Merge::markImplied + Varnode::setFlags)

Two halves, both missing:

  • ActionMarkImplied set the implied flag directly instead of calling
    Merge::markImplied (merge.cc:1595-1605), which also marks every operand of the
    defining op coverdirty. The kuna port of Merge::mark_implied already existed and
    was simply not wired up; the comment at the call site read "the cover-dirty
    bookkeeping on inputs is merge state the printer ignores"
    .
  • MergeContext::vn_set_cover_dirty did not forward a Varnode coverdirty to the
    owning HighVariable, which upstream Varnode::setFlags does
    (varnode.cc:377-378, high->coverDirty()). Varnode::set_flags in kuna is a W7
    stub that cannot reach the high bank, so the forward has to happen at the bridge.

Why it matters: Cover::rebuild (cover.cc:477-496) walks forward through implied
consumers, transitively. An inlined expression is printed where its outermost explicit
consumer is printed, so an operand of an implied expression is live all the way to
that point — but only once its Cover is recomputed. ActionMarkImplied is
deliberately scheduled before general merging for exactly this reason. With the
invalidation missing, the speculative merges saw pre-inlining Covers, two values live
at the same printed expression looked disjoint, and they merged into one variable.

Witness A — coreutils ptx output_one_dumb_line @ 0x574f. Two
cond ? truncation_string_length : 0 selects, both reads inlined into one call
argument printed after both writes:

     if (dat_14850) // branch-flip
-      v1 = dat_14838;
+      v2 = dat_14838;
     else {
-      v1 = 0;
+      v2 = 0;
     }
-    sub_41a6((((( ... ) - v1) - (dat_14848 - dat_14840)) - v1);
+    sub_41a6((((( ... ) - v1) - (dat_14848 - dat_14840)) - v2);

Executable proof of the shape (gcc -O0, flag1=1, flag2=0, step=100):

ref          -> 889
kuna_after   -> 889
kuna_before  -> 989

Witness B — coreutils factor @ 0x2ea0 (found by the corpus sweep, and the
worst instance seen). Two independent count-leading-zeros loops were merged into one
variable, so the normalization shift folded to a literal x - x:

/* BEFORE — v1 is BOTH clz results; the shift is unconditionally 0 */
    v1 = 0x3f;
    if (a3) { for (; !(a3 >> v1); v1 = v1 + -1) { } }
    v1 = 0x3f;
    if (a1) { for (; !(a1 >> v1); v1 = v1 + -1) { } }
    v2 = ((uint4)v1 ^ 0x3f) - ((uint4)v1 ^ 0x3f);      /* always 0 */
    ...
    for (v9 = 0; v9 < v2; v9 = v9 + 1) { ... }         /* never runs */

/* AFTER — two variables, the real clz difference */
    v1 = 0x3f;
    if (a3) { for (; !(a3 >> v1); v1 = v1 + -1) { } }
    v2 = 0x3f;
    if (a1) { for (; !(a1 >> v2); v2 = v2 + -1) { } }
    v3 = ((uint4)v1 ^ 0x3f) - ((uint4)v2 ^ 0x3f);

One bug or two?

Two bugs, one family. They are in different passes with different predicates and
each fix is independently necessary — ablation on the new fixture shows fix 1 alone
leaves two_selects sharing one variable, and fix 2 alone leaves lookup_service
returning NULL. What they share is the failure mode: a Cover-extension step that
upstream performs and the port dropped, so a cover-based legality test silently
passed. That is a pattern worth grepping for elsewhere in P6.

Corpus scale

kuna decompile-all --json --mode reliable over decbench binaries under
~/github/decbench/results/full_run/*/*/stripped/, pre-fix vs post-fix, diffing
per function (vN locals canonically renumbered first so pure renumbering does not
count):

Sample (both fixes) Value
binaries compared (O0 / O2 / O2-noinline) 60
functions compared 24,145
functions whose emitted C changed 390 (1.6%)
... of those, a statement was added (a value restored) 115

(The comparison canonically renumbers vN locals first, so a pure renaming would not
count. In practice it never collapses anything here: a changed merge decision also
changes the set of locals, which shifts the canonical numbering too. So 1.56% is the
upper bound on the semantic delta, not a measure of it — most of those functions differ
by one variable being split or joined, which is exactly what this pass decides.)

Root cause 1 measured alone, on a clean 19-binary / 5,294-function O0 sample:
11 functions changed, and every single change was an added statement — a dropped
restore or a dropped for initializer. That is the pure-miscompilation count: 0.21%
of functions were silently losing a value, and nothing anywhere was removed.

Root cause 2 carries the wider blast radius because it changes merge decisions
generally. Its value-losing instances are the ones above (ptx, factor); the rest
are variables splitting or joining differently, converging on upstream's choices — the
declmerge_x86_64 fixture, for one, now coalesces its size phi exactly as Ghidra does.

Rebase note

Rebased onto origin/main after #227 (the P3 opcode -> TypeOp seam totalisation) landed, and
re-verified end to end on top of it: both witnesses still reproduce pre-fix and are still
fixed post-fix, and every gate below was re-run against that base. My root causes are
Cover construction and Cover invalidation, not op property bits, so #227 does not interact.

Gates

Gate Result
make test PARITY OK (675/675)
make test-stages PARITY OK (305/305)
make rust-test green
make check-spec green
kuna catalog --check OK

No baseline re-pin, no per-test <com>option ... off</com> opt-out — the datatest
corpus is untouched.

Speed: median of 3, decompile-all --mode reliable, before → after:
ocsptool 2.45 s → 2.45 s, ptx 2.74 s → 2.58 s, ls 11.62 s → 11.60 s. No
regression.

Regression test

New fixture decompiler/crates/kuna-analysis/tests/fixtures/covercopy_x86_64
(+ vendored source) and kuna-console/tests/verify_cover_miscompile.rs, one test per
root cause, both asserting the value-carrying statement rather than a line count
or a GED:

  • restore_of_returned_parameter_is_emitted — the vN = a0; restore must appear
    after the clobbering lookup(...) call (an identical hoist exists at the entry,
    so position, not presence, is what distinguishes the bug).
  • independent_selects_do_not_share_one_variable — the two select arms must write
    two different variables and the emit(...) argument must subtract both.

Both fail on the pre-fix tree (verified by stashing the fix and re-running); each
fails independently when only the other fix is applied.

Other changes

🤖 Generated with Claude Code

https://claude.ai/code/session_011RXVU58TKJxb518oViChwo

@mahaloz
mahaloz force-pushed the fix/p6-lost-restore branch from 44a50fb to 8698843 Compare August 1, 2026 19:13
@mahaloz mahaloz changed the title [AUTOMATED] fix(p6): kuna emits the wrong value — restore the two dropped Cover extensions (DIV-44) [AUTOMATED] fix(p6): kuna emits the wrong value — restore the two dropped Cover extensions (DIV-47) 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
mahaloz force-pushed the fix/p6-lost-restore branch from 8698843 to 9e9df4e Compare August 1, 2026 19:17
@mahaloz
mahaloz merged commit 676ae48 into main Aug 1, 2026
9 checks passed
@mahaloz
mahaloz deleted the fix/p6-lost-restore branch August 1, 2026 19:24
mahaloz added a commit that referenced this pull request Aug 1, 2026
…(DIV-48) (#232)

* [AUTOMATED] fix(p9): (NOVEL) keep the unknown pointee's size in the realtypes relabel

`realtype_unknown_base` short-circuited to `void` for EVERY size when the
residual `TYPE_UNKNOWN` base sat under a pointer modifier, so `undefined1 *`,
`undefined4 *` and `undefined8 *` all rendered `void *`.

Only the DECLARATION was relabelled.  `opLoad` / `opPtradd` keep building index
and cast expressions from the ORIGINAL pointee size, so the declaration and the
expressions disagreed about the stride:

    int4 set_acl_fd(unsigned long a0,uint a1,uint a2,void *a3)
          if ((code *)a3[1])              // byte offset 1 under GCC's
            a0 = (*(code *)a3[1])(a3,a0); // void-arithmetic extension; the
                                          // expression was built for offset 8

`gcc -std=gnu11 -fsyntax-only` on that body reports 12 "invalid use of void
expression" errors and 12 "dereferencing 'void *' pointer" warnings.  The same
short-circuit dropped the access width from stores (`*(void *)
__errno_location() = 0x16;` for a 4-byte store).

The relabel now runs a `TYPE_UNKNOWN` pointee through the SAME size table a
scalar uses -- `undefined8 *` -> `unsigned long *`, `undefined4 *` ->
`unsigned int *` -- and keeps `void` only as the fallback for residual sizes
with no natural single C type (0, 3, 5, 6, 7, 10, ...).

P5 never mis-typed anything: `--option realtypes off` already produced the
stride-consistent `xunknown8 *a3` with the same `a3[1]`.  This was purely the
P9 presentation policy, and the off path is untouched.  A genuine `TYPE_VOID`
pointee is not a residual unknown and never enters the relabel, so
`free`/`malloc`/`memcpy`/`realloc` keep their opaque `void *` (pinned by a new
unit test).

Strict bug fix inside an existing default-on option (DIV-6), so no new flag;
recorded as DIV-47.

Measured on 5 whole-binary `decompile-all --mode reliable` runs (libacl, gzip,
mydoom, mirai, coreutils fmt): `*(void *)` cast sites 737 -> 1, `void *`
occurrences 1,585 -> 198, emitted line counts byte-for-byte unchanged.  The one
residual is a 10-byte x87 `long double` pointee, where `void` is the designed
fallback.  Least-contended-run timings over 7 interleaved pairs: gzip +0.51%,
libacl +0.13%, mirai -1.48%.

Gates: make test PARITY OK (675/675, baseline untouched), make test-stages
PARITY OK (321/321), make rust-test green, make check-spec OK (strict),
kuna catalog --check OK.

inspiration = "decbench:O2-noinline-libacl-libacl.so.1.1-set_acl_fd; NOVEL pool"

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

* [AUTOMATED] renumber DIV-47 -> DIV-48 (DIV-47 taken by #228)

---------

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

The kuna-only re-run on the optimized datasets reported 411/189 (O2-noinline) and
293/114 (O2) with a return/tail-duplication transform on most functions whose
score moved. Triaged in three steps; the code is unchanged.

WHICH TRANSFORM. `taildup:` and `returndup:` render as the SAME `return-dupe`
slug (PrintC::warning_slug), so the reported correlation lumped two passes. They
separate by warning sink: returndup uses warning_header (prototype line), taildup
uses warning(addr) (statement line). Classified that way, returndup covers 86% of
wins and 66% of regressions; taildup 2-3%. The July artifacts carry 5,183
`taildup:` banners and ZERO `returndup:` — taildup never moved.

WHY IT STARTED. returndup is default-OFF; `aggressive` turns it on, and DIV-40
made `auto` (=aggressive under 500 KiB) the front-end default. The July artifacts
predate the mode system entirely. #228/DIV-47 is refuted directly: with returndup
forced on, the fire count is identical at #228 and its parent on all six probe
binaries (17/17, 52/52, 410/410, 699/699, 76/76, 35/35), and 0 with returndup off.

NO DISCRIMINATOR. An isolating A/B on the same 36641d3 build over 536 slices /
52,862 functions (validated: the 46,005 non-firing functions score identically,
and the harness reproduces a published artifact byte-for-byte) puts returndup at
+417 GED-perfect and -7,756 aggregate GED — 608 perfects created vs 191 destroyed.
Nine candidate gates were partitioned causally (split count, void vs value return,
distinct return values, return count, switch, all-returns-identical, body size,
project, opt level): every cell is net-positive. The void-return escape hatch in
returndup_is_const_ret, which explains xmalloc and do_statx, is MORE profitable
than the value case, not less.

The single net-negative cell — the split de-structures a loop (cleanflight nextArg
loses its `for` header) — was implemented as a gate and measured, not left as
theory: +2 GED-perfect / -209 GED. Not kept, and reverted here.

Also corrects docs/modes.md, which told readers `aggressive` enables an option
"known to regress aggregate GED (DIV-18)" — superseded by #137's const-return
gate — and annotates the DIV-18 row. returndup as a default now also passes the
datatest gate (675/675, PARITY OK); promoting it is left as a separate DIV.

Gates: make test PARITY OK 675/675; make test-stages PARITY OK 356/356;
make check-spec OK; kuna catalog --check OK.


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 16, 2026
[AUTOMATED] GH-180's illegal pre-add/post-add merge (the SCARRY input and
the ADD output printing as one variable, so the emitted guard tested the
post-add value) was fixed by the DIV-47 cover restorations in #228, which
never referenced the issue. This closes the loop: every witness and the
issue's whole scope table re-verified at zero on current main (including
the non-vendored decbench gzip/diff/tar binaries), the shipped fix audited
against the pinned upstream rev, and the corrected contract pinned by a
stage testcase: grep nlscan's verbatim bytes plus the minimal unsigned
add/jb growth-guard form; the SCARRY8/CARRY8 guards must keep their
PRE-add operands and the collapsed self-update-then-test rendering must
not appear.

Bookkeeping: corpus file count 204 -> 205 (kuna-base xml.rs), stages
baseline re-recorded 460 -> 468 keys, README row added. No engine code
change, no option, no DIV row.


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

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.

1 participant