Repository navigation
[AUTOMATED] fix(p9): (NOVEL) render unnamed spacebase refs as stack locations (DIV-46) - #226
Merged
Merged
Conversation
…ocations
A `PTRSUB(spacebase, off)` whose offset P6 bound no Symbol to fell out of the
SPACEBASE arm of `PrintC::op_ptrsub_ir` into the *functional* render, putting
an internal p-code operator and a raw machine register into the emitted C:
*(void *)&PTRSUB(ESP,8)[v2] = 0; // x86, MSVC _chkstk frame
v3 = (uint1)((uint4)PTRSUB(sp,0) >> 0x11) & 1; // ARM Thumb
Neither `PTRSUB` nor `ESP`/`sp` is declared anywhere in the function. The arm
now takes the upstream `PrintC::pushUnnamedLocation` leaf it had been
declining (the old comment argued the leaf "would expose an offset the kuna
namerec layer has not yet resolved to a name" -- but the fallback exposed that
offset *and* the register *and* an undeclared operator), naming the storage in
kuna's existing unnamed-location convention: `&Stack00000008`. Same shape as
Ghidra's `&stack0x00000008` for the identical references, and like Ghidra's it
is an undeclared, extern-like leaf -- what changes is that it names a location
instead of leaking decompiler internals.
The trigger is a frame whose spacebase cannot be tracked to a constant (an
`alloca`/`_chkstk` stack probe): every reference stays relative to the entry
stack pointer with a dynamic PTRADD on top, and the offsets land outside the
mapped local frame, so no Symbol exists to bind. Ghidra flags the same case
with "WARNING: Unable to track spacebase fully for stack".
Ungated (strict correctness fix, DIV-46): the previous output is never
defensible. The symbol-bound path is byte-identical, both spacebase kinds are
covered (a global spacebase resolves through the same `dat_<addr>` naming), and
`kuna_unnamed_location_name` is now shared with the Varnode leaf rather than
duplicated.
Provenance: decbench:O2-noinline-mydoom-mydoom-scan_textfile; NOVEL pool (kuna
already scored best of all decompilers on this function and the output was
still not C, so no other decompiler surfaced this fix).
Gates: make test 675/675 PARITY OK; make test-stages 311/311 PARITY OK;
make rust-test green; make check-spec OK; kuna catalog --check OK.
Corpus: 217 of 13,759 functions across 12 decbench binaries emitted `PTRSUB(`
before, 0 after. Speed (interleaved medians, decompile-all --mode reliable):
mydoom +0.66%, gzip +0.44%, cleanflight -0.47%.
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
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 3, 2026
…st, adversarially refuted (#247) Round 2 of the decbench improvement loop. Nine investigation tracks, one agent each, every finding re-derived on today's build before it was allowed to count, then handed to a second agent briefed to refute it. Tracks: the three un-shipped round-1 items (rodata-phantom-store, paramcopyhoist, the $$undef placeholder leak), three NOVEL wart clusters ((code *) casts, CONCAT/SUBPIECE soup, raw registers), fresh angr- and ida-pool cases, and an audit of options registered but absent from `kuna catalog`. Outcome: 8 live candidates, 1 confirmed already-fixed (the PTRSUB spacebase render, PR #226 — all 267 corpus instances now print a stack location). The refuters earned their keep again: they overturned the filed diagnosis on three of eight while leaving the symptom standing, and two of them rebuilt kuna with the proposed fix to prove the mechanism was not a no-op. Round 1's filed-mechanism record is now 2-for-5; treat every "root cause" line in these records as a starting point to disprove, not a conclusion. Two findings are much larger than the cases that surfaced them: - RuleSubRight::apply_op is a stub, so every nonzero-offset SUBPIECE prints as a raw `SUBnn` p-code operator: 5,919 occurrences in 2,394 functions (3.1%) against ghidra's 18 in 13 (0.017%) — a 329x ratio, and `SUBnn` is an undeclared identifier, so those panes are not C. - The funcptr_align seam is stubbed, so every ARM/Thumb indirect call emits an invented ISA-mode bit-clear and loses the function-pointer type: 4,027 sites in 2,496 functions across 9 ARM projects, plus every AARCH64, MIPS, Loongarch and 8051 cspec that carries <funcptr>. Claude-Session: https://claude.ai/code/session_017dPFaKJanfLSf7mWGhkzkL Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
This was referenced Aug 3, 2026
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.
The bug
A
PTRSUB(spacebase, off)is a reference into the stack (or global) frame. P6(
link_symbol_reference) binds a Symbol to the offset constant when the recoveredframe layout has one, and P9's SPACEBASE arm then renders
&local_10/&myval.b.When P6 bound nothing, the arm gave up and fell into the functional render, so an
internal p-code operator and a raw machine register went straight into the emitted C.
The trigger is a frame whose spacebase cannot be tracked to a constant. mydoom's
scan_textfilehas a 64 KiB local buffer, so MSVC emits a stack-probe call and adjustsespby that call's non-constant result; every frame reference then stays relative tothe entry
espwith a dynamicPTRADDon top, and the offsets land outside themapped local frame, so no Symbol can exist. Ghidra flags exactly this case with
WARNING: Unable to track spacebase fully for stackand emits its unnamedstack-location leaf.
The old code did this deliberately — the comment said the upstream
&stackNNleaf"would expose an offset the kuna namerec layer has not yet resolved to a name". That
reasoning does not survive contact with its own output: the fallback exposed the offset
and the register and an undeclared operator.
Reproductions (before → after)
x86, MSVC
_alloca_probeframe —mydoom.exe --addr 0x405af0(decbenchO2-noinline/mydoom), 8 leaks:Ghidra on the same references:
*(undefined4 *)(&stack0x00000008 + iVar8) = 0;ARM Thumb —
betaflight_STM32F405.elf --addr 0x8052b04(theannotate_raw_stack_ptrPTRSUB(sp,#0)placeholder):Honest scope of the fix
Stack00000008is also an undeclared identifier — exactly like Ghidra'sstack0x00000008. This change does not make these functions compile, and I am notclaiming it does. What it changes:
PTRSUB, an internal p-code operator, orESP/sp, araw machine register — the two things that make the text unmistakably decompiler
internals rather than source;
uses for every other unnamed location (
dat_<addr>for data,Space<hex>for therest), so a consumer sees one naming scheme instead of a special case;
PrintC::pushUnnamedLocation) for the identical input.I chose not to declare it. The offset is, by construction, one the frame recovery
explicitly failed to resolve to a variable, and the references reach it through an
untracked dynamic pointer; declaring a local would assert a frame layout that does not
exist. So it stays an intentional extern-like leaf, and that is now written down in the
spec (
docs/spec/09-emission.md§9.2, "Leaves with no Symbol") rather than left implicit.Gated or not
Ungated, recorded as DIV-46. CLAUDE.md's tiebreak is "when in doubt, gate it", and I
am not in doubt about this direction: no consumer wants
PTRSUB(ESP,8)in a C body, andthe replacement is what upstream does for the same input. Both baselines are unmoved, so
there is nothing an option could protect. (DIV-44 went to #224 and DIV-45 is claimed by
open PR #225 while this was in flight, hence 46.)
Because it is ungated the stage testcase is single-pass (the
ghdec-whiledo-complex.xmlprecedent):
tests/stages/ghdec-spacebase-unnamed.xml, the real mydoomscan_textfilebytes, asserting no
PTRSUBand noESPsurvive and that the leaves render. It scores0/6 against a pre-fix build, 6/6 after.
What changed
p9_emit/printc.rs— the SPACEBASE arm's symbol-less branch now calls the newpush_spacebase_unnamed_ir(the C++symbol == 0arm:&per the value modifiers,then the leaf) instead of
op_func_ir. The address comes fromspacebase_unnamed_address,a transcription of
TypeSpacebase::getAddress(resolve_constant, size suppressed for aglobal spacebase). The leaf name comes from
kuna_unnamed_location_name, factored outof the existing unnamed-location tail rather than duplicated — the tail's kuna-specific
global-resolution loop stays where it was, since it is Varnode-specific.
Stack<hex>; a global spacebaseresolves through the same helper to
dat_<addr>; a register-covered address would renderthe register name. The symbol-bound path is untouched.
docs/spec/09-emission.md(prose),docs/history.md(DIV-46),tests/stages/README.md,docs/baseline-stages.json(re-recorded, +6 keys), and the hard-coded corpus file countin
kuna-base/src/xml.rs(174 → 175).Corpus impact
kuna decompile-all --json --mode reliableover 12 decbench binaries(
O2-noinline), counting functions whose emitted C containsPTRSUB(:finddiffchaclEvery
PTRSUB(in the sweep came from this one arm.Gates
docs/baseline.jsonuntouched.Speed
scripts.pipeline.timeitneeds an option to flip and this fix has none, so the samemedian-of-N methodology was applied to a pre-fix and post-fix binary, interleaved so
machine-load drift hits both arms equally (
decompile-all --json --mode reliable):Within noise, well inside the +5% budget — the new path is two lookups replacing a
function-render call, on a branch that only fires for an unresolvable reference.
Provenance
inspiration = "decbench:O2-noinline-mydoom-mydoom-scan_textfile; NOVEL pool"— kunaalready scores best-of-all-decompilers on this function and the output was still not C,
so no other decompiler surfaced this fix.
🤖 Generated with Claude Code
https://claude.ai/code/session_011RXVU58TKJxb518oViChwo