Repository navigation
[AUTOMATED] fix(p6): kuna emits the wrong value — restore the two dropped Cover extensions (DIV-47) - #228
Merged
Conversation
mahaloz
force-pushed
the
fix/p6-lost-restore
branch
from
August 1, 2026 19:13
44a50fb to
8698843
Compare
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
force-pushed
the
fix/p6-lost-restore
branch
from
August 1, 2026 19:17
8698843 to
9e9df4e
Compare
mahaloz
added a commit
that referenced
this pull request
Aug 1, 2026
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]>
This was referenced Aug 1, 2026
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]>
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.
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
Coverthat upstream Ghidra builds larger was built smaller by theport, so a legality test found no conflict where one exists.
Neither ships behind an option. Per
AGENTS.mda strict bug fix that only correctswrong 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_rangebuilt the dominance range from the dominant COPY'sdef point alone. Upstream (
merge.cc:1120-1121) builds it from two points:A def-point-only
Coveris a point, not a range, sorange.contain(op,1)answers"no" for every op and
checkCopyPairreports every dominated COPY redundant.markRedundantCopiesthen marks it non-printing and the statement disappears.At
-O0this is routine: severalreturn param;paths compile tomov -N(%rbp),%rax ; jmp .Lepi, so several COPYs of one parameter land in oneHighVariable — and the reload that follows a call clobbering the same register gets
deleted. The sibling
build_single_read_coverrecords the identical omission asLOSS-229 and had already been fixed; this was the second site.
Witness —
gnutlsocsptoolport_to_service@0x1144a(
~/github/decbench/results/full_run/O0/gnutls/stripped/ocsptool). The binaryexplicitly reloads
sportat0x114e8(mov -0x18(%rbp),%rax) before jumping tothe 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
getservbyportfails):Ghidra, IDA, angr, binja and phoenix are all correct here — this was kuna-specific.
The same defect also silently deleted
forloop initializers (the while-dofor-form asks
testTerminalfor a printed op; a non-printing one yields an emptyinit slot and the statement is suppressed too):
Root cause 2 — an over-merge (
Merge::markImplied+Varnode::setFlags)Two halves, both missing:
ActionMarkImpliedset the implied flag directly instead of callingMerge::markImplied(merge.cc:1595-1605), which also marks every operand of thedefining op
coverdirty. The kuna port ofMerge::mark_impliedalready existed andwas 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_dirtydid not forward a Varnodecoverdirtyto theowning HighVariable, which upstream
Varnode::setFlagsdoes(
varnode.cc:377-378,high->coverDirty()).Varnode::set_flagsin kuna is a W7stub 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 impliedconsumers, 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.
ActionMarkImpliedisdeliberately 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 —
coreutilsptxoutput_one_dumb_line@0x574f. Twocond ? truncation_string_length : 0selects, both reads inlined into one callargument printed after both writes:
Executable proof of the shape (
gcc -O0,flag1=1, flag2=0, step=100):Witness B —
coreutilsfactor@0x2ea0(found by the corpus sweep, and theworst instance seen). Two independent count-leading-zeros loops were merged into one
variable, so the normalization shift folded to a literal
x - x: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_selectssharing one variable, and fix 2 alone leaveslookup_servicereturning 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 reliableover decbench binaries under~/github/decbench/results/full_run/*/*/stripped/, pre-fix vs post-fix, diffingper function (
vNlocals canonically renumbered first so pure renumbering does notcount):
O0/O2/O2-noinline)(The comparison canonically renumbers
vNlocals first, so a pure renaming would notcount. 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
O0sample:11 functions changed, and every single change was an added statement — a dropped
restore or a dropped
forinitializer. 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 restare variables splitting or joining differently, converging on upstream's choices — the
declmerge_x86_64fixture, for one, now coalesces its size phi exactly as Ghidra does.Rebase note
Rebased onto
origin/mainafter #227 (the P3 opcode -> TypeOp seam totalisation) landed, andre-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
make testmake test-stagesmake rust-testmake check-speckuna catalog --checkNo baseline re-pin, no per-test
<com>option ... off</com>opt-out — the datatestcorpus is untouched.
Speed: median of 3,
decompile-all --mode reliable, before → after:ocsptool2.45 s → 2.45 s,ptx2.74 s → 2.58 s,ls11.62 s → 11.60 s. Noregression.
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 perroot cause, both asserting the value-carrying statement rather than a line count
or a GED:
restore_of_returned_parameter_is_emitted— thevN = a0;restore must appearafter 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 writetwo 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
verify_declared_vars' sanity floor moves 5 → 4. Its primary assertion (noundeclared local / invalid C) is unchanged and still passes; with Covers recomputed
at the right points the
make_dir_clonesize phi finally coalesces with thestrlenresult the way upstream does, so the un-coalescedv5the fixture wasbuilt around no longer exists. Output is semantically identical.
DIV-47indocs/history.md(44–46 were taken by [AUTOMATED] fix(p1): Cortex-M vector table need not sit in an exec section (DIV-44) #224/[AUTOMATED] fix(driver): surface pipeline panics instead of reporting success (DIV-45) #225/[AUTOMATED] fix(p9): (NOVEL) render unnamed spacebase refs as stack locations (DIV-46) #226 while this was in flight).docs/spec/06-variables-and-merge.mdgains prose for both cover extensions: thetwo-point Cover construction and the implied-consumer forward walk.
structural symptom;
O0-coreutils-ptx-output_one_dumb_line.mdhad explicitlyconcluded the merge was "cover-legal", which this PR refutes.
🤖 Generated with Claude Code
https://claude.ai/code/session_011RXVU58TKJxb518oViChwo