Skip to content

[AUTOMATED] fix(p9): (NOVEL) render unnamed spacebase refs as stack locations (DIV-46) - #226

Merged
mahaloz merged 1 commit into
mainfrom
fix/spacebase-unnamed-location
Aug 1, 2026
Merged

mahaloz merged 1 commit into
mainfrom
fix/spacebase-unnamed-location

Conversation

@mahaloz

@mahaloz mahaloz commented Aug 1, 2026

Copy link
Copy Markdown
Contributor

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 recovered
frame 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_textfile has a 64 KiB local buffer, so MSVC emits a stack-probe call and adjusts
esp by that call's non-constant result; every frame reference then stays relative to
the entry esp with a dynamic PTRADD on top, and the offsets land outside the
mapped local frame, so no Symbol can exist. Ghidra flags exactly this case with
WARNING: Unable to track spacebase fully for stack and emits its unnamed
stack-location leaf.

The old code did this deliberately — the comment said the upstream &stackNN leaf
"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_probe frame — mydoom.exe --addr 0x405af0 (decbench
O2-noinline/mydoom), 8 leaks:

// before
  v2 = -sub_4098d0();
  *(void *)&PTRSUB(ESP,8)[v2] = 0;
  *(void *)&PTRSUB(ESP,4)[v2] = 0x80;
  *(void *)&PTRSUB(ESP,0)[v2] = 3;
  *(void *)&PTRSUB(ESP,-4)[v2] = 0;
  *(void *)&PTRSUB(ESP,-8)[v2] = 3;
  *(void *)&PTRSUB(ESP,-0xc)[v2] = 0x80000000;
  *(void *)&PTRSUB(ESP,-0x10)[v2] = *(void *)&PTRSUB(ESP,0x10040)[v2];

// after
  v2 = -sub_4098d0();
  *(void *)&(&Stack00000008)[v2] = 0;
  *(void *)&(&Stack00000004)[v2] = 0x80;
  *(void *)&(&Stack00000000)[v2] = 3;
  *(void *)&(&Stackfffffffc)[v2] = 0;
  *(void *)&(&Stackfffffff8)[v2] = 3;
  *(void *)&(&Stackfffffff4)[v2] = 0x80000000;
  *(void *)&(&Stackfffffff0)[v2] = *(void *)&(&Stack00010040)[v2];

Ghidra on the same references: *(undefined4 *)(&stack0x00000008 + iVar8) = 0;

ARM Thumb — betaflight_STM32F405.elf --addr 0x8052b04 (the
annotate_raw_stack_ptr PTRSUB(sp,#0) placeholder):

// before
    v3 = (uint1)((uint4)PTRSUB(sp,0) >> 0x11) & 1;
// after
    v3 = (uint1)((uint4)&Stack00000000 >> 0x11) & 1;

Honest scope of the fix

Stack00000008 is also an undeclared identifier — exactly like Ghidra's
stack0x00000008. This change does not make these functions compile, and I am not
claiming it does. What it changes:

  • the output no longer contains PTRSUB, an internal p-code operator, or ESP/sp, a
    raw machine register — the two things that make the text unmistakably decompiler
    internals rather than source;
  • the leaf is self-describing (space + offset) and is the same convention kuna already
    uses for every other unnamed location (dat_<addr> for data, Space<hex> for the
    rest), so a consumer sees one naming scheme instead of a special case;
  • it is the upstream behavior (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, and
the 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.xml
precedent): tests/stages/ghdec-spacebase-unnamed.xml, the real mydoom scan_textfile
bytes, asserting no PTRSUB and no ESP survive and that the leaves render. It scores
0/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 new
    push_spacebase_unnamed_ir (the C++ symbol == 0 arm: & per the value modifiers,
    then the leaf) instead of op_func_ir. The address comes from spacebase_unnamed_address,
    a transcription of TypeSpacebase::getAddress (resolve_constant, size suppressed for a
    global spacebase). The leaf name comes from kuna_unnamed_location_name, factored out
    of 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.
  • Both spacebase kinds are covered: a local frame renders Stack<hex>; a global spacebase
    resolves through the same helper to dat_<addr>; a register-covered address would render
    the 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 count
    in kuna-base/src/xml.rs (174 → 175).

Corpus impact

kuna decompile-all --json --mode reliable over 12 decbench binaries
(O2-noinline), counting functions whose emitted C contains PTRSUB(:

binary before after functions
mydoom.exe (x86 PE) 4 0 161
betaflight (ARM Thumb) 109 0 6,388
cleanflight (ARM Thumb) 72 0 3,118
mirai (x86) 12 0 181
nuttx (ARM Thumb) 4 0 890
kmod 4 0 540
gzip 3 0 261
findutils find 3 0 873
grep 2 0 633
diffutils diff 2 0 516
bzip2 1 0 153
libacl chacl 1 0 45
total 217 0 13,759

Every PTRSUB( in the sweep came from this one arm.

Gates

make test         675/675 assertions passed   PARITY OK
make test-stages  311/311 assertions passed   PARITY OK   (+6 new)
make rust-test    green (291 suites ok)
make check-spec   check-spec OK
kuna catalog --check   catalog OK

docs/baseline.json untouched.

Speed

scripts.pipeline.timeit needs an option to flip and this fix has none, so the same
median-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):

case before after delta
mydoom.exe, 161 fns (median of 9) 1,553 ms 1,563 ms +0.66%
gzip, 261 fns (median of 9) 2,939 ms 2,952 ms +0.44%
cleanflight, 3,118 fns (median of 3) 24,453 ms 24,339 ms -0.47%

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" — kuna
already 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

…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
mahaloz merged commit 694ab8e into main Aug 1, 2026
9 checks passed
@mahaloz
mahaloz deleted the fix/spacebase-unnamed-location branch August 1, 2026 18:58
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]>
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