Skip to content

s9/printc: fix undeclared-variable invalid-C (declare locals overlapping a param register) - #131

Merged
mahaloz merged 1 commit into
mainfrom
feat/decl-undeclared-fix
Jul 5, 2026
Merged

mahaloz merged 1 commit into
mainfrom
feat/decl-undeclared-fix

Conversation

@mahaloz

@mahaloz mahaloz commented Jul 5, 2026

Copy link
Copy Markdown
Contributor

A real correctness bug surfaced by the ghidra-beats-kuna merge/copy investigation: kuna emitted an undeclared local variable (invalid C). In tar make_directory, v5 (an un-coalesced size/phi output) is used 3× but never declared — it won't compile.

Root cause

emit_local_var_decls' is_param test skipped any high with an instance whose storage is contained in a FUNCTION_PARAMETER symbol. That false-positives on a local high that merely picked up a parameter-register varnode (a merge artifact: the un-coalesced phi output). The local was skipped from the declaration prelude yet still referenced in the statements → undeclared.

Ghidra keys declarations on the Symbol category, so a no_category local is always declared even when it overlaps a parameter.

Fix

Gate the is_param skip on the high's name actually being one of the prototype's parameters. This only makes the skip stricter (never removes a declaration), so it is byte-identical on any function that was already valid C — it only adds a declaration where kuna was emitting invalid C.

Before: v5 = v1; … sub_4ecc0(v5) with no v5 declaration.
After: uint8 v5; declared.

Tests & gates

  • New regression: verify_declared_vars.rs + fixture declmerge_x86_64 (a reduction of make_directory that reproduces the exact shape; decompiles it and asserts every referenced vN local is declared). Verified it fails on main (undeclared v5) and passes with the fix.
  • make test 675/675 PARITY OK (byte-identical), make test-stages 254/254 PARITY OK, make rust-test green.

The residual self-copy / cosmetic while-vs-do-while forms in the same cluster stay deferred (see docs/decbench/ghidra-gap-analysis.md §3); this fixes only the invalid-C sub-bug.

🤖 Generated with Claude Code

https://claude.ai/code/session_018DV2MXxQAAWK7xLPBmsq9J

…lid-C undeclared variable)

emit_local_var_decls' is_param test skipped ANY high with an instance whose storage is
contained in a FUNCTION_PARAMETER symbol. That false-positives on a LOCAL high that
merely picked up a param-register varnode (a merge artifact: an un-coalesced size/phi
output, as in tar make_directory) — the local was skipped from the declaration prelude
yet still referenced in the statements, emitting an UNDECLARED variable (invalid C,
e.g.  used 3x, never declared).

Ghidra keys declarations on the Symbol category, so a no_category local is always
declared even when it overlaps a parameter. Gate the is_param skip on the high's name
actually being one of the prototype's parameters: this only makes the skip STRICTER
(never removes a declaration), so it is byte-identical on any function that was already
valid C, and declares the previously-undeclared local.

Fixes the ghidra-beats-kuna merge/copy cluster's invalid-C sub-bug (the residual
self-copy / cosmetic while-form is separate and stays deferred). Regression:
verify_declared_vars.rs + fixture declmerge_x86_64 (reproduces the exact shape; asserts
every referenced vN local is declared).

Gates: make test 675/675 PARITY OK (byte-identical), make test-stages 254/254 PARITY OK.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_018DV2MXxQAAWK7xLPBmsq9J
@mahaloz
mahaloz merged commit afd9669 into main Jul 5, 2026
@mahaloz
mahaloz deleted the feat/decl-undeclared-fix branch July 29, 2026 08:01
mahaloz added a commit that referenced this pull request Aug 2, 2026
…IV-52) (#242)

* [AUTOMATED] fix(p9): (NOVEL) one local declaration per ScopeLocal Symbol (DIV-51)

`PrintC::emitLocalVarDecls` walks HighVariables; upstream `emitScopeVarDecls`
walks the ScopeLocal *Symbol* table (printc.cc:2667/2696), which is what makes
one symbol one declaration.  When two live ranges of one mapped stack slot did
not merge, the shared-storage naming gave both the same name and P5 recovered
different types for them, so the function opened with the same identifier
declared twice at two widths:

    void applyLedFixedLayers(void)   // betaflight_STM32F405, O2-noinline
    {
      ...
      unsigned int v12; // stack - 0x24
      uint4 v12;        // stack - 0x24

That is not compilable C, and a reader cannot tell which `v12` any body
occurrence means.  Ghidra emits one `undefined4 local_24;`, IDA one `int v23;`.

The only collapse that existed, `option dedupvardecls` (DIV-7, default on),
keys on the fully rendered LINE, so two spellings of one slot both survive by
construction -- its own module doc recorded that residual as intentional.  The
composite (array/struct/union) collapse sitting beside it was already
Symbol-keyed; the scalar case was the documented gap ("primitive types are
shared by every scalar local of that type", so the type-Rc key does not
identify a symbol).

Upstream-fidelity verdict: an UNPORTED rule, not a mis-ported or deliberately
simplified one.  The scalar collapse is now Symbol-keyed too, inside that same
option: highs whose declaration representative resolves to the same containing
ScopeLocal Symbol -- base-byte containment, the query C++ `Funcdata::linkSymbol`
itself uses (funcdata_varnode.cc:1190) -- AND that render the same identifier
emit one declaration.

Requiring the identifier to match is what makes the collapse incapable of
removing the last declaration of a referenced name, i.e. the mirror-image
failure #131 fixed.  It is load-bearing: on the campaign function nine highs of
symbol 5v13 are named `v12` (all whole 4-byte covers, so naming them alike is
correct) while its partial covers carry their own names `v14`/`v15`/`v16`, and
those must all keep their declarations.  The duplicate NAME is therefore not a
naming defect -- naming per symbol is right, and the declaration layer is where
the rule was missing.

Type arbitration when the collapsing highs disagree: the Symbol's own type,
which is what C++ `emitVarDecl` declares (`sym->getType()`, printc.cc:1719) --
unless it is narrower than the widest storage the group covers, in which case
the widest member wins.  kuna's ScopeLocal ranges are sometimes narrower than
the accesses that reach them (upstream `restructure` would have grown the
symbol), and declaring a 2-byte object for a slot the body writes 4 bytes into
and passes by address would be a new defect rather than a faithful one.  A
group that already agrees keeps its recovered type, which is sharper than the
usually-`undefined<N>` symbol type.

Strict bug fix inside an existing default-on option, so no new flag; recorded
as DIV-51.  `option dedupvardecls off` still restores the per-high rendering.

Measured before/after on 14 decbench binaries / 11,874 functions (x86-64 and
ARM Cortex-M, -O0 and -O2), the first measurement of this bug's real scope:
functions emitting a duplicate local declaration 18 -> 0.  The blast radius is
exactly those 18 -- no other function changes a byte, 21 declaration lines
disappear (35,412 -> 35,391), no function loses a declared name and none gains
one.  Every survivor is at least as wide as every access it absorbed
(`undefined3`/`unsigned short`/`char` shadows of a 4-byte slot become one
`unsigned int`).  The collapse only runs where two declarations already share an
identifier, so the symbol lookups are skipped on nearly every function;
interleaved medians of `decompile-all --mode reliable`: betaflight STM32F405
(6,387 functions) 69,782 -> 69,754 ms (-0.04%), bzip2 9,926 -> 9,863 ms
(-0.63%), gzip 3,162 -> 3,211 ms (+1.55%, 9 pairs).

`verify_declared_vars` now asserts both failure modes on the `declmerge`
fixture: no name undeclared (#131) and no name declared twice.
`tests/stages/ghdec-symbol-keyed-local-decls.xml` is the end-to-end witness over
a real binary -> decompile(addr) path (4 of 6 assertions pass pre-fix, 6/6
post-fix); it uses the smallest function in the same firmware showing the same
defect, with `option dedupvardecls off` as pass 2 pinning the bug form.

This function was already tied-best on the benchmark (kuna GED 25 == ghidra 25),
so the fix moves zero benchmark points; its value is that the output stops
being invalid C.

Gates: make test PARITY OK (675/675, baseline untouched), make test-stages
PARITY OK (352/352, re-recorded -- delta is purely the 6 new keys), make
rust-test green, make check-spec OK, kuna catalog --check OK.

inspiration = "decbench:O2-noinline-betaflight-betaflight_STM32F405-applyLedFixedLayers; NOVEL pool"

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

* [AUTOMATED] renumber DIV-51 -> DIV-52 (DIV-51 taken by #241 iteboolean)

---------

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