Repository navigation
[AUTOMATED] feat(p1): cppproto - ingest C++ function prototypes from DWARF - #264
Merged
Merged
Conversation
…DWARF kuna's DWARF pass applied parameter names and types only to functions whose name had no `::` and no `<`. The cause is not name-vs-address binding: an out-of-line C++ member or namespace DEFINITION carries no `DW_AT_name` of its own (the name lives on the `DW_AT_specification` declaration), so the `snap.name.is_empty()` guard dropped the whole DIE - name, typed signature and `DW_OP_fbreg` stack locals - before any binding was attempted. The `static` members prove the artificial `this` DIE was never involved. Name-keyed prototype parking is a second, independent defect that only the templates expose: kuna files the demangled `maxof<int>` as `maxof`, and a qualified name lives in a nested scope the global by-name query never descends into, while the read side is already keyed by address. New `analyzers/dwarf/kuna_cppproto.rs` fuses a definition with its one-hop `DW_AT_specification` declaration, qualifies the name by its namespace/class ancestry, flattens `DW_TAG_GNU_formal_parameter_pack`, and parks the prototype by entry address. `build_datatype` gains a `cpp` flag (false reproduces the old switch byte for byte) adding the class/reference arms, collapsing transparent qualifier hops before the depth budget is charged, and naming an anonymous aggregate after its typedef; a parameter type that will not map, or maps to a zero-width opaque aggregate, degrades to `undefined<n>` instead of discarding the signature. `DW_AT_abstract_origin` is deliberately NOT followed for the subprogram link: a GCC IPA clone is also a nameless subprogram, and coreutils `fmt`'s `put_word.isra.1` has two parameters aliasing one source parameter. Gated `cppproto`, default-ON; the pass runs at load, so the facts are stashed apart and the gate applies at the analysis commit. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01McQC7imaNfzj5k5AVumSYN
mahaloz
added a commit
that referenced
this pull request
Aug 5, 2026
…on, it is a point inside one (-1030 spurious entries, 0 real lost) A kuna FunctionSymbol is an entry address with no extent: Database::add_function takes an address and find_function answers "is a function registered AT this address", never "is this address INSIDE one". Every discovery oracle's dedup is therefore an equality test, and a candidate 12 bytes into a body passes it. Three oracles do exactly that on ordinary compiler output, and --mode auto turns all three on for anything under 500 KiB by resolving to `aggressive`: eh_frame_full promotes each .gcc_except_table landing pad to a top-level function (it is designed to), aif starts one at the first undecoded byte of an unwinder-only region (routinely not an instruction boundary), and the prologue patterns match an aligned `push rbp; mov rbp,rsp` inside a larger body. On a g++ -O0 probe, probe_try_catch [0x2acf,0x2ba7) yields sub_2b0b / sub_2b1a / sub_2b8a, all three surviving stripping, and sub_2b0b decompiles with an uninitialised rbp so every local is a garbage dereference. IDA Pro 9.2 gives get_func(0x2b0b).start_ea == 0x2acf; that is the model. .eh_frame carries the missing extent: each FDE records ONE function's [pcBegin, pcBegin+pcRange). kuna_fdeinterior.rs reuses scan_eh_frame_starts's record walk and adds the one field it skips - pcRange, decoded with the CIE R encoding's format bits only, since it is a length - and the commit filters the FULLY MERGED entry set, after the deferred Listing consumers, because one producer is aif. Not every FDE describes one function: the linker gives the whole PLT a single FDE and every stub inside it is real (the first prototype deleted every import). A range is used only when no other named function start, no other FDE pcBegin, and no .plt/.plt.sec/.plt.got/.iplt/.MIPS.stubs section falls inside it. An entry AT an FDE start is never suppressed, so oracle 3's own product is preserved. Gated and default-ON (DIV-61) because the measurement leaves no judgment call. kuna functions off vs on over 72 stripped decbench x86-64 binaries, every dropped entry classified against the matching unstripped binary's FUNC symbols (address and size): 36,568 -> 35,538 entries, 1,030 dropped, 0 added, ZERO that are a real function's entry, ZERO that carry a name, all 1,030 strictly inside a real body, 52 not even an instruction boundary. C++: big_O0.stripped 599 -> 449 (25% of the list was junk), probe_O0.stripped 189 -> 162. Static glibc --mode aggressive 1,358 -> 1,087 with 0 real and 0 named lost. PE and ET_REL are inert. Whole-binary decompile-all on eight binaries: 0 functions added, 0 surviving bodies changed and 0 surviving names changed. #259 (tailcallentry) non-regression, measured on its own corpus and surface with --option tailcallentry on: all 98 ARM images, entries 57,578 -> 57,578, zero images changed - bare-metal ARM unwinds through .ARM.exidx and only 3 of 98 carry any .eh_frame FDE. The same argument covers draft PR #239. Disclosed interaction: eh_frame_full's landing-pad product is now constrained by this gate, so verify_eh_frame_full's option-on arm flips fdeinterior off to keep testing what the LSDA decode produces. Rebased onto 890096b (#264 cppproto, DIV-60) on 1cff8ec (#262 cppcallnames, DIV-59), and fully re-measured on that tree rather than carried forward, because neither is inert here. #264 recovers out-of-line C++ member and namespace definitions from DWARF, so an unstripped C++ binary now carries far more named function symbols - the input to this option's "range holds no other named function start" condition. The invariant holds against the new symbol set: big_O0 now has 447 of its 450 surviving entries named (probe_O0 161 of 163) and the filter still drops 150 with 0 real and 0 named lost, while the stripped counterparts are unchanged at 449 / 162 (verified, not assumed - no DWARF there). Both arms of every comparison are the same build, so #262's renaming and #264's MAX_TYPE_DEPTH change cancel; coreutils fmt, the binary #264 altered, was decompiled whole in both arms to keep the two unconflated (198 -> 191 entries, 0 surviving bodies changed; fmt-O2 151 -> 151). Catalog counters were DERIVED from a fresh post-rebase catalog capture, not incremented: 91 settables, 20 core / 41 transform / 30 analysis, 90 catalog rows. #264 and this PR had made an identical off-by-one edit to the same three assertions, so the merge resolution would have shipped the wrong number had it been trusted. phase_catalog.json re-captured and docs/options.md regenerated from the post-rebase build; no stages XML added, so no corpus count or stages baseline moves. Bundle: docs/features/fdeinterior/. Gates: make test 675/675 PARITY OK (no re-pin, no per-test opt-out), make test-stages 394/394 PARITY OK, make rust-test green, make check-spec OK (strict), kuna catalog --check OK. Speed: timeit -29.28% (15 samples); interleaved medians -21.68% to +0.06% (functions) and -4.22% / -4.89% (decompile-all). Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01McQC7imaNfzj5k5AVumSYN
mahaloz
added a commit
that referenced
this pull request
Aug 5, 2026
…on, it is a point inside one (-1030 spurious entries, 0 real lost) A kuna FunctionSymbol is an entry address with no extent: Database::add_function takes an address and find_function answers "is a function registered AT this address", never "is this address INSIDE one". Every discovery oracle's dedup is therefore an equality test, and a candidate 12 bytes into a body passes it. Three oracles do exactly that on ordinary compiler output, and --mode auto turns all three on for anything under 500 KiB by resolving to `aggressive`: eh_frame_full promotes each .gcc_except_table landing pad to a top-level function (it is designed to), aif starts one at the first undecoded byte of an unwinder-only region (routinely not an instruction boundary), and the prologue patterns match an aligned `push rbp; mov rbp,rsp` inside a larger body. On a g++ -O0 probe, probe_try_catch [0x2acf,0x2ba7) yields sub_2b0b / sub_2b1a / sub_2b8a, all three surviving stripping, and sub_2b0b decompiles with an uninitialised rbp so every local is a garbage dereference. IDA Pro 9.2 gives get_func(0x2b0b).start_ea == 0x2acf; that is the model. .eh_frame carries the missing extent: each FDE records ONE function's [pcBegin, pcBegin+pcRange). kuna_fdeinterior.rs reuses scan_eh_frame_starts's record walk and adds the one field it skips - pcRange, decoded with the CIE R encoding's format bits only, since it is a length - and the commit filters the FULLY MERGED entry set, after the deferred Listing consumers, because one producer is aif. Not every FDE describes one function: the linker gives the whole PLT a single FDE and every stub inside it is real (the first prototype deleted every import). A range is used only when no other named function start, no other FDE pcBegin, and no .plt/.plt.sec/.plt.got/.iplt/.MIPS.stubs section falls inside it. An entry AT an FDE start is never suppressed, so oracle 3's own product is preserved. Gated and default-ON (DIV-61) because the measurement leaves no judgment call. kuna functions off vs on over 72 stripped decbench x86-64 binaries, every dropped entry classified against the matching unstripped binary's FUNC symbols (address and size): 36,568 -> 35,538 entries, 1,030 dropped, 0 added, ZERO that are a real function's entry, ZERO that carry a name, all 1,030 strictly inside a real body, 52 not even an instruction boundary. C++: big_O0.stripped 599 -> 449 (25% of the list was junk), probe_O0.stripped 189 -> 162. Static glibc --mode aggressive 1,358 -> 1,087 with 0 real and 0 named lost. PE and ET_REL are inert. Whole-binary decompile-all on eight binaries: 0 functions added, 0 surviving bodies changed and 0 surviving names changed. #259 (tailcallentry) non-regression, measured on its own corpus and surface with --option tailcallentry on: all 98 ARM images, entries 57,578 -> 57,578, zero images changed - bare-metal ARM unwinds through .ARM.exidx and only 3 of 98 carry any .eh_frame FDE. The same argument covers draft PR #239. Disclosed interaction: eh_frame_full's landing-pad product is now constrained by this gate, so verify_eh_frame_full's option-on arm flips fdeinterior off to keep testing what the LSDA decode produces. Rebased onto 890096b (#264 cppproto, DIV-60) on 1cff8ec (#262 cppcallnames, DIV-59), and fully re-measured on that tree rather than carried forward, because neither is inert here. #264 recovers out-of-line C++ member and namespace definitions from DWARF, so an unstripped C++ binary now carries far more named function symbols - the input to this option's "range holds no other named function start" condition. The invariant holds against the new symbol set: big_O0 now has 447 of its 450 surviving entries named (probe_O0 161 of 163) and the filter still drops 150 with 0 real and 0 named lost, while the stripped counterparts are unchanged at 449 / 162 (verified, not assumed - no DWARF there). Both arms of every comparison are the same build, so #262's renaming and #264's MAX_TYPE_DEPTH change cancel; coreutils fmt, the binary #264 altered, was decompiled whole in both arms to keep the two unconflated (198 -> 191 entries, 0 surviving bodies changed; fmt-O2 151 -> 151). Catalog counters were DERIVED from a fresh post-rebase catalog capture, not incremented: 91 settables, 20 core / 41 transform / 30 analysis, 90 catalog rows. #264 and this PR had made an identical off-by-one edit to the same three assertions, so the merge resolution would have shipped the wrong number had it been trusted. phase_catalog.json re-captured and docs/options.md regenerated from the post-rebase build; no stages XML added, so no corpus count or stages baseline moves. Bundle: docs/features/fdeinterior/. Gates: make test 675/675 PARITY OK (no re-pin, no per-test opt-out), make test-stages 394/394 PARITY OK, make rust-test green, make check-spec OK (strict), kuna catalog --check OK. Speed: timeit -29.28% (15 samples); interleaved medians -21.68% to +0.06% (functions) and -4.22% / -4.89% (decompile-all). Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01McQC7imaNfzj5k5AVumSYN
mahaloz
added a commit
that referenced
this pull request
Aug 5, 2026
…on, it is a point inside one (-1030 spurious entries, 0 real lost) (#263) A kuna FunctionSymbol is an entry address with no extent: Database::add_function takes an address and find_function answers "is a function registered AT this address", never "is this address INSIDE one". Every discovery oracle's dedup is therefore an equality test, and a candidate 12 bytes into a body passes it. Three oracles do exactly that on ordinary compiler output, and --mode auto turns all three on for anything under 500 KiB by resolving to `aggressive`: eh_frame_full promotes each .gcc_except_table landing pad to a top-level function (it is designed to), aif starts one at the first undecoded byte of an unwinder-only region (routinely not an instruction boundary), and the prologue patterns match an aligned `push rbp; mov rbp,rsp` inside a larger body. On a g++ -O0 probe, probe_try_catch [0x2acf,0x2ba7) yields sub_2b0b / sub_2b1a / sub_2b8a, all three surviving stripping, and sub_2b0b decompiles with an uninitialised rbp so every local is a garbage dereference. IDA Pro 9.2 gives get_func(0x2b0b).start_ea == 0x2acf; that is the model. .eh_frame carries the missing extent: each FDE records ONE function's [pcBegin, pcBegin+pcRange). kuna_fdeinterior.rs reuses scan_eh_frame_starts's record walk and adds the one field it skips - pcRange, decoded with the CIE R encoding's format bits only, since it is a length - and the commit filters the FULLY MERGED entry set, after the deferred Listing consumers, because one producer is aif. Not every FDE describes one function: the linker gives the whole PLT a single FDE and every stub inside it is real (the first prototype deleted every import). A range is used only when no other named function start, no other FDE pcBegin, and no .plt/.plt.sec/.plt.got/.iplt/.MIPS.stubs section falls inside it. An entry AT an FDE start is never suppressed, so oracle 3's own product is preserved. Gated and default-ON (DIV-61) because the measurement leaves no judgment call. kuna functions off vs on over 72 stripped decbench x86-64 binaries, every dropped entry classified against the matching unstripped binary's FUNC symbols (address and size): 36,568 -> 35,538 entries, 1,030 dropped, 0 added, ZERO that are a real function's entry, ZERO that carry a name, all 1,030 strictly inside a real body, 52 not even an instruction boundary. C++: big_O0.stripped 599 -> 449 (25% of the list was junk), probe_O0.stripped 189 -> 162. Static glibc --mode aggressive 1,358 -> 1,087 with 0 real and 0 named lost. PE and ET_REL are inert. Whole-binary decompile-all on eight binaries: 0 functions added, 0 surviving bodies changed and 0 surviving names changed. #259 (tailcallentry) non-regression, measured on its own corpus and surface with --option tailcallentry on: all 98 ARM images, entries 57,578 -> 57,578, zero images changed - bare-metal ARM unwinds through .ARM.exidx and only 3 of 98 carry any .eh_frame FDE. The same argument covers draft PR #239. Disclosed interaction: eh_frame_full's landing-pad product is now constrained by this gate, so verify_eh_frame_full's option-on arm flips fdeinterior off to keep testing what the LSDA decode produces. Rebased onto 890096b (#264 cppproto, DIV-60) on 1cff8ec (#262 cppcallnames, DIV-59), and fully re-measured on that tree rather than carried forward, because neither is inert here. #264 recovers out-of-line C++ member and namespace definitions from DWARF, so an unstripped C++ binary now carries far more named function symbols - the input to this option's "range holds no other named function start" condition. The invariant holds against the new symbol set: big_O0 now has 447 of its 450 surviving entries named (probe_O0 161 of 163) and the filter still drops 150 with 0 real and 0 named lost, while the stripped counterparts are unchanged at 449 / 162 (verified, not assumed - no DWARF there). Both arms of every comparison are the same build, so #262's renaming and #264's MAX_TYPE_DEPTH change cancel; coreutils fmt, the binary #264 altered, was decompiled whole in both arms to keep the two unconflated (198 -> 191 entries, 0 surviving bodies changed; fmt-O2 151 -> 151). Catalog counters were DERIVED from a fresh post-rebase catalog capture, not incremented: 91 settables, 20 core / 41 transform / 30 analysis, 90 catalog rows. #264 and this PR had made an identical off-by-one edit to the same three assertions, so the merge resolution would have shipped the wrong number had it been trusted. phase_catalog.json re-captured and docs/options.md regenerated from the post-rebase build; no stages XML added, so no corpus count or stages baseline moves. Bundle: docs/features/fdeinterior/. Gates: make test 675/675 PARITY OK (no re-pin, no per-test opt-out), make test-stages 394/394 PARITY OK, make rust-test green, make check-spec OK (strict), kuna catalog --check OK. Speed: timeit -29.28% (15 samples); interleaved medians -21.68% to +0.06% (functions) and -4.22% / -4.89% (decompile-all). Claude-Session: https://claude.ai/code/session_01McQC7imaNfzj5k5AVumSYN Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
mahaloz
added a commit
that referenced
this pull request
Aug 5, 2026
…d prototype models (registry 1 -> 5 models, __thiscall resolves) (#265) kuna's `__thiscall` machinery is fully ported, wired and consumed - and was permanently dead, because nothing could ever set `hasThis`. `Architecture::build_default_proto` read exactly one cspec element, `<default_proto><prototype>`, where the C++ `parseCompilerConfig` (architecture.cc:1253/1280-1284/1297-1303) also dispatches `<prototype>`, `<resolveprototype>` and `<modelalias>`. The per-program model registry therefore held exactly ONE model: `getModel("__thiscall")` could never resolve, `option defaultprototype __thiscall` failed with "Unknown prototype model" on every target, and `ProtoModelMerged` had no live producer at all. Across the vendored corpus, 110 cspecs declare 186 `<prototype>` elements and only the 110 inside `<default_proto>` were ever decoded. The named models now register alongside the default one, decoded through the SAME body (`decode_proto_model`), so they carry identical `<pentry>` storage and `<unaffected>`/`<killedbycall>`/`<returnaddress>`/`<internal_storage>` fidelity. Added on top: the `hasthis`/`constructor` attributes with upstream's `if (name == "__thiscall") hasThis = true` override applied last (fspec.cc:2595), `ProtoModelMerged::decode`'s fold-in + finalize for `<resolveprototype>`, `createModelAlias` for `<modelalias>`, and the post-parse invariant that every language has a `__thiscall` model, cloned off the default when the spec declares none (architecture.cc:1342). Registration selects nothing. No function's model changes, so emitted C is byte-identical: 675/675 datatests unmoved, and 12 whole-binary `decompile-all` panes (73,173 lines, four compiler specs, both arms on the same rebased tree) identical on stdout and stderr. What changed is what is REACHABLE - on `x86:LE:32:default:windows` the registry now holds `__stdcall` + `__cdecl` + `__fastcall` + `__thiscall` + the merged `__fastcall/__thiscall/__stdcall`, and `option defaultprototype __thiscall` turns the MSVC member function `int4 Box::vftable_0(void) { int4 v1; // ecx ... }` (a read-before-write of ECX, not valid C) into `int4 Box::vftable_0(int4 a0)` on the real `msvc_rtti_x86.exe` fixture. Registry census over every language:compiler pair kuna ships: 294/294 bootstrap, pairs holding more than one model 0 -> 294, pairs where `getModel("__thiscall")` resolves 0 -> 294, models registered 294 -> 790. No option: registration cannot change emitted C, proven by the ablation and the sweep rather than assumed. No DIV: this is a Convergence back onto upstream's own cspec dispatch with no corpus output shift (docs/history.md). Deliberately NOT in this PR, each noted as a follow-up: honoring `<eval_current_prototype>`/`<eval_called_prototype>` (that changes which model every function on six specs is evaluated with), automatic `__thiscall` assignment from the demangler or DWARF `DW_AT_object_pointer` - the seam #264 explicitly parked on "kuna cannot register one yet" - `FuncProto::decode`'s Java-tier constructor/destructor import, `prepareThisPointer`, and `hide_thisparam`. Speed: the extra elements are parsed once per program load, so load is the metric. Interleaved `kuna functions --json` minima, n=31: +0.42% / +0.55% / +0.15% / -0.05%. `decompile-all` worst case +0.89%. Getting there required folding the return-address, default-proto and named-model readers onto ONE cspec parse - a net removal of one parse versus the pre-PR tree. Gates: make test PARITY OK 675/675 | make test-stages PARITY OK 400/400 | make rust-test green (4,463 tests, 0 failed) | make check-spec OK (strict) | kuna catalog --check OK. Claude-Session: https://claude.ai/code/session_01McQC7imaNfzj5k5AVumSYN Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
This was referenced Aug 5, 2026
mahaloz
added a commit
that referenced
this pull request
Aug 5, 2026
… guard (294 truncated sites -> 0, type_match 458 -> 626 of 872) (#268) kuna's DWARF type mapper truncated ordinary C declarations to `void`. MAX_TYPE_DEPTH = 3 counted every hop of the DW_AT_type chain, the transparent typedef/const/volatile/restrict links included, and its comment cited Ghidra's DWARFDataTypeImporter.trackRecursion -- which is not what upstream does. Upstream counts RE-ENTRIES of one DIE offset and refuses the third, so it fires only on a genuine cycle; an acyclic chain visits each offset once however long it is. The reduction conflated "the same DIE again" with "a deep but finite chain", and four DIEs is ordinary C: const char *const *, const size_t *, char *const [], char ***. Counting the truncated sites straight out of .debug_info across six -g C binaries (coreutils fmt O0/O2, grep, bzip2, zlib minigzip, gzip): 294 -- 238 DW_OP_fbreg stack locals/params, 55 CU-top-level globals, 1 prototype parameter. The restored rule resolves all 294. Raising the cap was never the fix: with no cycle detection under it, any cap is simultaneously too low for real C and unable to bound a self-referential chain, so it only converts a hang into a wrong answer. analyzers/dwarf/kuna_typedepth.rs restores upstream's per-offset re-entry counter (TypeWalk::Cycle) plus a MAX_NESTING = 64 native-stack backstop a Java port does not need; TypeWalk::Depth is the old budget verbatim, so `--option typedepth off` is byte-identical. Scope note: #264 (cppproto) had already fixed plain-C PROTOTYPES as a side effect (it is default-on and rebuilds every subprogram's prototype with the qualifier collapse, binding by address), including the C++ const-method `this`. What remained is the cpp=false callers -- stack locals and global sizing -- plus purely structural depth, where three pointer hops exhaust the budget even with the qualifiers collapsed. Two consequences ride along: the qualifier collapse now runs for the C callers too (an anonymous aggregate takes its typedef name: `position *firstpos`, not the shared `anon_struct`), and intern_aggregate falls back to the anonymous name when that borrowed name is already held by another kind of type -- kuna registers a core type named `code` and zlib's inftrees.h typedefs an anonymous struct to exactly that, which the whole-binary sweep caught degrading `code *next` to `void *next`. Gated as `typedepth` (on|off, default ON, DIV-63) through the KUNA_TYPEDEPTH env-var bridge, because the types are baked inside `load file`, upstream of every `option` command. scripts/decompile.py gains the same bridge (a one-entry load-time-gate table): its console script emits `option` lines after `load file`, so without it a before/after demo of a load-time gate renders twice identically. Gates: make test 675/675 PARITY OK, make test-stages 400/400 PARITY OK, make rust-test green, make check-spec OK (lenient + strict), kuna catalog --check OK. Speed: worst +0.35% (interleaved min-of-15, load-dominated surfaces), budget 5%. Benchmark: the decbench scored corpus is stripped, so the delta there is a structural zero (verified); on the same projects' unstripped copies decbench type_match perfects go 458 -> 626 of 872 (+168), mean 0.8438 -> 0.9083, 193 functions improved and 0 worse. Claude-Session: https://claude.ai/code/session_01McQC7imaNfzj5k5AVumSYN Co-authored-by: Claude Opus 5 (1M context) <[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.
What
kuna's DWARF pass applied parameter names and types only to functions whose name
contained no
::and no<. On a-gC++ binary that means it lost the signature ofessentially every member function. This PR is the C++ arm of that pass, behind the new
cppprotooption (default-ON).The real root cause (the handed-down hypothesis was wrong)
The brief's hypothesis was that the DIE→function binding matched on the demangled name
instead of
DW_AT_low_pc. That is a real defect, but it is not what produced the split.Reading the probe's
.debug_infosettles it:Every one is a subprogram DEFINITION with no
DW_AT_nameof its own — C++ splits adefinition from its declaration, and the name lives on the
DW_AT_specificationtarget.kuna's guard is
if snap.declaration || snap.name.is_empty() { continue; }, so the wholeDIE — name, prototype and
DW_OP_fbregstack locals — was dropped before any bindingwas attempted. The two
staticmembers prove the artificial-thisDIE was never involved.Two theories that were also in play, corrected by reading the code:
DW_TAG_namespacedescent was never the problem.snapshot_unitsnapshots every DIEin the unit and the subprogram arm iterates
dies.values()with no depth filter, so anamespace-nested subprogram was always visited. (And the definitions sit at CU top level
anyway — only the declarations are inside the namespace.) Namespace handling matters for
building the qualified name, not for discovery.
maxof<int>does carry its ownDW_AT_name, survives the guard, and still loses itsprototype, because
kuna functionsreports0x39d0 name='maxof' aliases=['maxof<int>']:the by-name park through the global scope finds nothing. Qualified names miss for a
different reason —
find_create_scope_from_symbol_namefilesAccount::depositunder anested scope
Accountthatquery_function_by_namenever descends into. The READ side isalready keyed by address, so the round trip was broken only at the write end.
What the change does
New module
analyzers/dwarf/kuna_cppproto.rs:DW_AT_specificationdeclaration (the reduction ofGhidra's
DIEAggregate) and builds the source name from the DIE's namespace/class ancestry(
DWARFName), so the installed symbol carriesAccount::deposit, not the baredepositthe declaration DIE holds.DW_TAG_GNU_formal_parameter_pack(a variadic template's expanded arguments arenot direct children).
aggregate — to an
undefined<n>at the DIE's own byte size, instead of discarding thewhole signature.
In
analyzers/dwarf/mod.rs,build_datatypegains acpp: bool; with it false the tagswitch is byte-identical to before, which is what makes the gate-off path exact. With it
true:
DW_TAG_class_typemaps like a structure and a C++ reference like a pointer (both areDWARFDataTypeImporter's own reductions), the transparent qualifier chain is collapsedbefore the depth budget is charged, and an anonymous aggregate is named after the typedef
it was reached through.
Prototypes are parked by entry address (
set_function_prototype_pieces_at), and bothprototype READ paths (
decompile_drive's own-prototype lookup andbuild_callee_proto_pieces) are widened past the global scope. Both widenings are inertbefore this arm: a by-NAME park resolves through the global scope's
queryByName, whichcannot reach a nested-scope function, so nothing outside the global scope ever carried
parked pieces.
Option decision: gated, default-ON
Gated deliberately. Three of the four defects are strict bug fixes that would need no flag,
but the change can alter plain-C output (it did — 9 functions in coreutils
fmt), and"when in doubt, gate it" applies. Turning the whole DWARF pass off is too blunt an escape
hatch for a C++-specific behaviour change.
Default-ON because it recovers ground truth the compiler recorded and both Ghidra and IDA
apply, the datatest corpus is structurally unreachable from the analysis tier (0/675
changed, no re-pin, no per-test opt-out), and the sweep shows no plain-C regression.
The producing pass runs at
load file, upstream of theoptioncommands, so the C++ factsare stashed in a separate
AnalysisOutput::cpp_dwarfand the gate is applied where they arecommitted — that is what makes the flag live, and it keeps
cppproto offbyte-identicalto the pre-change build.
Sweep — every changed function classified
decompile-alloff vs on, whole binary, every hunk read. Both arms re-captured on therebased tree (post-#262), so that PR's C++ call-site renames sit in the baseline and do
not pollute this diff — the counts are unchanged from the pre-rebase run:
regglobal_fmt_x86_64(real C, coreutilsfmt,-O2 -g)-O0-O2dwarf_globals_x86_64(small C-O0 -g)All 9 C hunks are improvements — four
void *parameters resolved to their real pointee(
char **authors,int8 *pn,uint8 *val,__mbstate_t *ps) plus one DWARF parameter name(
bool same_paragraph). No plain-C function lost information, errored, or changed arity.Three defects the sweep found that the witness could not
This is the part worth reading — the design was right on its witness and wrong three
functions later, exactly as the standing requirement predicts.
put_word.isra.1(fmt,0x23d0) is a nameless subprogram linked byDW_AT_abstract_origin, and its two formal parameters both point at the samesource parameter
Word *w(IPA-SRA split the aggregate). Chasing it producedput_word(Word *w,Word *w)and pushed the wrong callee signature intoput_line.Decision: follow
DW_AT_specificationonly. The cost is accepted and documented — aconcrete out-of-line instance (a destructor body, a
.coldpart) recovers nothing — andthe C++ payoff is untouched, because member and namespace definitions use
DW_AT_specification. This also means the "one-hop chase finds 810 functions instead of81 on leveldb" measurement does not transfer as-is: the abstract-origin half of that gain
is deliberately left on the table.
std::vector<int>::emplace_back<int>kept its expanded packargument inside a
DW_TAG_GNU_formal_parameter_pack; reading only direct children lockeda one-parameter signature and dropped the argument at every call site.
zero-width by-value parameter did not merely lose precision — it failed
std::vector<int>::_M_realloc_insertoutright ("dereferencing a null/sentinel spacepointer"), i.e. the function stopped decompiling.
Gates
make testmake test-stagesmake rust-testmake check-spec--strict)kuna catalog --checkcatalog OKCatalog counts bumped from a fresh green run, never by arithmetic: settables 89→90, tiers
(20, 41, 28)→(20, 41, 29), catalog JSON rows 88→89,
phase_catalog.jsonfixture recaptured.Speed
The DWARF walk runs identically with the gate on or off (the C++ facts are always
computed, then dropped at commit when off), so the only marginal cost is the commit.
timeitoff → oncppproto_x86_64/Account::depositregglobal_fmt_x86_64/fmt(C guard)Both inside the +5% budget, measured on the rebased tree. Single-shot medians swing hard
with machine load — an early
fmtrun reported +38.6% and did not reproduce in four re-runs— so the interleaved numbers are the trustworthy ones. Where the on side is genuinely faster
it is because a locked prototype skips output-trial recovery.
Testcase
kuna-console/tests/verify_cppproto.rs— seven two-pass assertions over the newcppproto_x86_64fixture (out-of-line member,constmember, reference parameter,staticmember, namespace function, template instantiation, class-typed pointer parameter). Each
runs the fixture twice:
option cppproto offreproduces the bug, the default reproduces thefix.
No
tests/stages/*.xml:run_default_analysesis bound to the real-ELF bootstrap and the<binaryimage>datatest path never calls it, so a stage XML cannot reach the analysis tierat all (hence no corpus-count bump and no stages-baseline re-record beyond the normal run).
Scope / seams left clean
this->balancestillprints as
*(int4 *)((int8)this + 4). The seam for the sibling PR isbuild_datatype'sstruct/class arms, structurally untouched here.
__thiscall.DW_AT_object_pointer— the attribute Ghidra'sThisCallingConventionDWARFFunctionFixupuses — is not acted on: kuna cannot register a__thiscallmodel yet (ProtoModel::decodeis a stub), and the x86-64 SysV ABI passesthisas an ordinary first parameter regardless. Noted here as the seam for that work.Bundle:
docs/features/cppproto/(analysis.md,plan.md,record.json). DIV row:DIV-60 (DIV-59 was claimed by #262 on merge; renumbered on rebase). Rebased onto
1cff8ecb, with every shared counter re-derived from a fresh build on the rebased tree —phase_catalog.jsonrecaptured,docs/options.mdregenerated (both byte-identical to thepre-rebase versions, since #262 added no option), and all four gates re-run after the
rebase. #262 touched no
tests/stages/*.xml,kuna-base/src/xml.rsordocs/baseline-stages.json, and neither does this PR.🤖 Generated with Claude Code
https://claude.ai/code/session_01McQC7imaNfzj5k5AVumSYN
Before / after —
Account::depositincppproto_x86_64Real captured kuna output on the function this feature was built for, with
option cppprotoflipped. Ported from kuna — Ghidra DWARFFunctionImporter / DIEAggregate (a definition DIE fused with its DW_AT_specification declaration), DWARFName (the namespace path), DWARFDataTypeImporter (DW_TAG_class_type mapped like a structure, a reference like a pointer).cppproto offcppproto on(default)kuna — before (
option cppproto off)kuna — after (
option cppproto on)