Skip to content

[AUTOMATED] feat(p1): cppproto - ingest C++ function prototypes from DWARF - #264

Merged
mahaloz merged 1 commit into
mainfrom
feat/cppproto
Aug 5, 2026
Merged

mahaloz merged 1 commit into
mainfrom
feat/cppproto

Conversation

@mahaloz

@mahaloz mahaloz commented Aug 5, 2026

Copy link
Copy Markdown
Contributor

What

kuna's DWARF pass applied parameter names and types only to functions whose name
contained no :: and no <
. On a -g C++ binary that means it lost the signature of
essentially every member function. This PR is the C++ arm of that pass, behind the new
cppproto option (default-ON).

before:  int4 Account::deposit(int4 *a0,int4 a1)
after:   int4 Account::deposit(Account *this,int4 amount)
Ghidra:  int __thiscall Account::deposit(Account *this,int amount)

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_info settles it:

 <1><9a81>: DW_TAG_subprogram      <- db::inner::scaled_add
    <9a82>   DW_AT_specification: <0x9a65>
    <9a86>   DW_AT_low_pc      : 0x258a
 <1><915a>: DW_TAG_subprogram      <- Account::deposit
    <915b>   DW_AT_specification: <0x6f65>
 <1><98f1>: DW_TAG_subprogram      <- Shape::shape_count  (static, no `this`)
    <98f2>   DW_AT_specification: <0x753d>

Every one is a subprogram DEFINITION with no DW_AT_name of its own — C++ splits a
definition from its declaration, and the name lives on the DW_AT_specification target.
kuna's guard is if snap.declaration || snap.name.is_empty() { continue; }, so the whole
DIE — name, prototype and DW_OP_fbreg stack locals — was dropped before any binding
was attempted. The two static members prove the artificial-this DIE was never involved.

Two theories that were also in play, corrected by reading the code:

  • DW_TAG_namespace descent was never the problem. snapshot_unit snapshots every DIE
    in the unit and the subprogram arm iterates dies.values() with no depth filter, so a
    namespace-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.
  • Name-keyed binding is a second, independent defect — and only the templates expose it.
    maxof<int> does carry its own DW_AT_name, survives the guard, and still loses its
    prototype, because kuna functions reports 0x39d0 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_name files Account::deposit under a
    nested scope Account that query_function_by_name never descends into. The READ side is
    already 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:

  • Fuses a definition with its one-hop DW_AT_specification declaration (the reduction of
    Ghidra's DIEAggregate) and builds the source name from the DIE's namespace/class ancestry
    (DWARFName), so the installed symbol carries Account::deposit, not the bare
    deposit the declaration DIE holds.
  • Flattens DW_TAG_GNU_formal_parameter_pack (a variadic template's expanded arguments are
    not direct children).
  • Degrades a parameter type the mapper cannot build — or that maps to a zero-width opaque
    aggregate — to an undefined<n> at the DIE's own byte size, instead of discarding the
    whole signature.

In analyzers/dwarf/mod.rs, build_datatype gains a cpp: bool; with it false the tag
switch is byte-identical to before
, which is what makes the gate-off path exact. With it
true: DW_TAG_class_type maps like a structure and a C++ reference like a pointer (both are
DWARFDataTypeImporter's own reductions), the transparent qualifier chain is collapsed
before the depth budget is charged, and an anonymous aggregate is named after the typedef
it was reached through.

The qualifier fix was not in the brief and is load-bearing: MAX_TYPE_DEPTH is 3 and
counts raw DIE hops, so a const member's this (const Account *const, four DIEs) still
came out void * after the class arm was added. The same cap is why plain C
char **authors, idx_t *pn and mbstate_t *ps rendered void * in coreutils fmt.

Prototypes are parked by entry address (set_function_prototype_pieces_at), and both
prototype READ paths (decompile_drive's own-prototype lookup and
build_callee_proto_pieces) are widened past the global scope. Both widenings are inert
before this arm: a by-NAME park resolves through the global scope's queryByName, which
cannot 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 the option commands, so the C++ facts
are stashed in a separate AnalysisOutput::cpp_dwarf and the gate is applied where they are
committed — that is what makes the flag live, and it keeps cppproto off byte-identical
to the pre-change build.

Sweep — every changed function classified

decompile-all off vs on, whole binary, every hunk read. Both arms re-captured on the
rebased 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:

binary functions changed new errors arity drops
regglobal_fmt_x86_64 (real C, coreutils fmt, -O2 -g) 169 9 0 0
C++/STL probe -O0 190 83 0 0
C++/STL probe -O2 72 7 0 0
dwarf_globals_x86_64 (small C -O0 -g) 11 0 0 0

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.

  1. GCC IPA clones. put_word.isra.1 (fmt, 0x23d0) is a nameless subprogram linked by
    DW_AT_abstract_origin, and its two formal parameters both point at the same
    source parameter Word *w (IPA-SRA split the aggregate). Chasing it produced
    put_word(Word *w,Word *w) and pushed the wrong callee signature into put_line.
    Decision: follow DW_AT_specification only. The cost is accepted and documented — a
    concrete out-of-line instance (a destructor body, a .cold part) recovers nothing — and
    the C++ payoff is untouched, because member and namespace definitions use
    DW_AT_specification. This also means the "one-hop chase finds 810 functions instead of
    81 on leveldb" measurement does not transfer as-is: the abstract-origin half of that gain
    is deliberately left on the table.
  2. Variadic-template arity. std::vector<int>::emplace_back<int> kept its expanded pack
    argument inside a DW_TAG_GNU_formal_parameter_pack; reading only direct children locked
    a one-parameter signature and dropped the argument at every call site.
  3. Zero-width by-value aggregates. A class maps to a size-0 named opaque, and a
    zero-width by-value parameter did not merely lose precision — it failed
    std::vector<int>::_M_realloc_insert outright ("dereferencing a null/sentinel space
    pointer"), i.e. the function stopped decompiling.

Gates

gate result
make test PARITY OK — 675/675 (no re-pin, no per-test opt-out)
make test-stages PARITY OK — 394/394
make rust-test green
make check-spec OK (lenient and --strict)
kuna catalog --check catalog OK

Catalog 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.json fixture 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.

target timeit off → on interleaved min-of-15
cppproto_x86_64 / Account::deposit 147.4 → 149.8 ms (+1.59%) +1.72%
regglobal_fmt_x86_64 / fmt (C guard) 472.9 → 414.5 ms (−12.36%) −0.83%

Both inside the +5% budget, measured on the rebased tree. Single-shot medians swing hard
with machine load — an early fmt run 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 new
cppproto_x86_64 fixture (out-of-line member, const member, reference parameter, static
member, namespace function, template instantiation, class-typed pointer parameter). Each
runs the fixture twice: option cppproto off reproduces the bug, the default reproduces the
fix.

No tests/stages/*.xml: run_default_analyses is bound to the real-ELF bootstrap and the
<binaryimage> datatest path never calls it, so a stage XML cannot reach the analysis tier
at all (hence no corpus-count bump and no stages-baseline re-record beyond the normal run).

Scope / seams left clean

  • Struct/class fields are OUT. A class stays a named opaque, so this->balance still
    prints as *(int4 *)((int8)this + 4). The seam for the sibling PR is build_datatype's
    struct/class arms, structurally untouched here.
  • __thiscall. DW_AT_object_pointer — the attribute Ghidra's
    ThisCallingConventionDWARFFunctionFixup uses — is not acted on: kuna cannot register a
    __thiscall model yet (ProtoModel::decode is a stub), and the x86-64 SysV ABI passes
    this as 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.json recaptured, docs/options.md regenerated (both byte-identical to the
pre-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.rs or
docs/baseline-stages.json, and neither does this PR.

🤖 Generated with Claude Code

https://claude.ai/code/session_01McQC7imaNfzj5k5AVumSYN


Before / after — Account::deposit in cppproto_x86_64

Real captured kuna output on the function this feature was built for, with option cppproto flipped. 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).

metric cppproto off cppproto on (default)
gotos 0 0
labels 0 0
loc 8 8
switches 0 0
speed 147.43 ms 149.78 ms — Δ 1.59% (budget 5.0%)
kuna — before (option cppproto off)
int4 Account::deposit(int4 *a0,int4 a1)
{
  a0[1] = a0[1] + a1;
  if (a0[2] < a0[1])
    a0[1] = a0[2];
  *a0 = *a0 + 1;
  return a0[1];
}
kuna — after (option cppproto on)
int4 Account::deposit(Account *this,int4 amount)
{
  *(int4 *)((int8)this + 4) = *(int4 *)((int8)this + 4) + amount;
  if (*(int4 *)((int8)this + 8) < *(int4 *)((int8)this + 4))
    *(unsigned int *)((int8)this + 4) = *(unsigned int *)((int8)this + 8);
  *(int4 *)this = *(int4 *)this + 1;
  return *(int4 *)((int8)this + 4);
}

…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
mahaloz merged commit 890096b into main Aug 5, 2026
9 checks passed
@mahaloz
mahaloz deleted the feat/cppproto branch August 5, 2026 05:25
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]>
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]>
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