Skip to content

[AUTOMATED] feat(p1): cppsig - apply the demangled C++ signature (leveldb type_match 9 -> 35 of 525, +26 with 0 lost) - #266

Merged
mahaloz merged 2 commits into
mainfrom
feat/cppsig
Aug 5, 2026
Merged

mahaloz merged 2 commits into
mainfrom
feat/cppsig

Conversation

@mahaloz

@mahaloz mahaloz commented Aug 5, 2026

Copy link
Copy Markdown
Contributor

kuna applied no demangled C++ signature. The demangler reduces a mangled symbol to its qualified NAME only — a hard requirement of kuna's ::-scope splitter, which nests on every :: and would otherwise build junk scopes out of a signature tail — and demangle_raw, the full c++filt form, had shipped with no production caller since the demangler landed. Its own header recorded the gap: "It does NOT apply the demangled signature (parameter / return types) … a deferred follow-up."

The cost is a stripped C++ shared library, where the exported .dynsym mangled name is the only signature source that survives. On stripped google/leveldb -O0, functions whose first parameter is a NAMED pointer type, across 527 functions:

ghidra ida binja angr kuna
188 150 60 0 0

37 of ghidra's 42 outright wins are .dynsym-exported; on the 112 non-exported this-shaped functions ghidra gets 1. So the lever is the demangler, not type inference — which the plain-C control corpus confirms, kuna's type recovery there being ordinary rather than weak.

// before                                      // after (shipped default)
void leveldb::Cache::~Cache(unsigned long a0)  void leveldb::Cache::~Cache(Cache *this)
unsigned long ...::NumEntries(int8 *a0)        unsigned long ...::NumEntries(TableBuilder *this)

The whole problem is the implicit object parameter

Itanium mangles a static member function exactly like a non-static one, and like a namespaced free function: leveldb::Status::OK(), leveldb::TableBuilder::WriteBlock(…) and leveldb::NewMemEnv(Env*) share one _ZN…E shape. Guessing wrong does not cost precision — it shifts every following parameter, which is binja's bug in the other direction (it applies the declared parameters and OMITS this).

Both tiers were measured on 1329 mangled .dynsym symbols with DWARF ground truth (915 really take this) before either was written:

rule precision recall
ctor/dtor only 1.0000 0.5650
proven — ctor/dtor + cv-qualified (shipped default) 1.0000 0.7093
inferred — + class evidence 0.9278 1.0000
any nested name (naive) 0.6942 1.0000

For calibration, Ghidra 12.1's own this decision on the same binary runs at precision 0.85 (34 right / 6 wrong of 40 applications). Upstream resolves the ambiguity in DemangledFunction.isThisCall by comparing the mangled parameter count against the count its analysis recovered — information kuna does not have at the analysis tier, which is why the split above is the substitute.

proven is what the mangling entails: constructors (C1/C2/C3), destructors (D0/D1/D2), cv-/ref-qualified members (_ZNK), unqualified globals, and the MSVC forms — which state the access specifier, static and the calling convention outright. inferred decides the rest from class evidence mined out of the binary's own symbols (a scope owning a ctor/dtor/cv-member or a _ZTV/_ZTI/_ZTS symbol is a class). In inferred both directions need positive evidence: a scope with no witness at all is DECLINED, not assumed to be a namespace — that refinement takes recall 0.9978 → 1.0000 at unchanged precision.

Measured benchmark delta

decbench leveldb O0, n=525 scored functions, scored with decbench origin/main @325046f (PR #60 — the C++ type_match artifact fixes), cache_version 5, DECBENCH_NO_CACHE=1. The off arm reproduces the pre-PR tree exactly, so it is a real control.

type_match perfects
ghidra 44
kuna cppsig inferred 38
ida 35
kuna cppsig proven (shipped default) 35
binja 11
kuna cppsig off (baseline) 9
angr 8

9 → 35 at the default: +26, and ZERO lost. Mean 0.1277 → 0.1784 (proven) / 0.1920 (inferred); 28 / 44 functions improved and 0 worse in either mode. kuna moves from last place to second, tied with ida at the default and 6 short of ghidra.

The 26 newly perfect functions are exactly the set decbench's own improvement miner nominated: ~Cache ~Comparator ~DB ~Env ~EnvWrapper ~FileLock ~FilterPolicy ~Handler ~Logger ~RandomAccessFile ~Rep ~SequentialFile ~Snapshot ~Table ~TableBuilder ~WritableFile ~WriteBatch + ApproximateSize Env FileSize Iterator NumEntries Options Rep TableBuilder WriteBatch. inferred adds ChangeOptions NewErrorIterator NewMemEnv.

Note on the target: the brief's "7 → ~33 = parity with ghidra" sizing was computed on the pre-#60 scorer and is stale. Against the corrected scorer the baseline is 9 and parity is 44; this lands at 35, a large win that is honestly short of ghidra by 6. C++ references are rendered as pointers, which is what the fixed ground truth now expects.

The return type is deliberately not applied

Itanium encodes a return type only for a template function, so upstream's resolveReturnType returns null and ApplyFunctionSignatureCmd keeps whatever the analysis recovered — which is why ghidra still prints undefined8 leveldb::TableBuilder::NumEntries(TableBuilder *this). kuna expresses that as a PrototypePieces with no outtype, read by FuncProto::seed_locked_from_pieces as "lock the INPUT half only". Inventing void would DELETE every recovered return value.

Complementary to cppproto (#264), with a stated precedence

DWARF is ground truth and wins on an unstripped binary; the mangled symbol is what survives strip. The commit applies cppsig first so the DWARF prototype overwrites it wherever both reach a function — asserted in verify_cppsig::dwarf_wins_over_the_demangled_signature, whose witness is the parameter NAME (amount), which only DWARF carries.

Gates

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

Structural, not lucky: the XML <binaryimage> datatest bootstrap never runs the analyzer tier, so neither corpus can reach this pass.

Sweep — every changed function classified

decompile-all off vs on, both arms on this tree.

Plain C is untouched on every axis — 11 binaries / 1,351 functions, 0 changed in either mode (coreutils fmt -O2 -g, fmt_x86_64, dwarf_globals, fauxware, static mcount_x86_64 at 1,073 functions, stripped_dynamic, switchtab, noreturn_propagate, fmt_aarch64, fmt_arm, and the Rust-mangled rust_hello). That is structural: a C symbol is not C++-mangled, so the pass emits nothing.

C++ binary functions changed proven changed inferred new errors
leveldb -O0 stripped 3962 257 503 0
leveldb -O2 stripped 919 43 93 0
cppsig_x86_64.so 14 3 6 0
cppproto_x86_64 (-g) 25 3 3 0
cpp_mangled_x86_64 12 0 0 0
cpp_noreturn_x86_64 16 0 0 0
eh_lsda_x86_64 21 1 1 0

The wrongness axis, measured rather than argued

Raw arity change is not the harm signal — an arity decrease is often kuna over-recovering, with the demangled list right. The signal is a NEW read-before-write of an argument register (int8 *v1; // rsi): the symptom of a locked parameter list shorter than the ABI uses. Over leveldb -O0 stripped, 3,962 functions:

mode changed with a new arg-register read-before-write
proven (default) 257 2 (0.05% of the binary)
inferred 503 29

Both remaining proven cases are one mechanism, the SysV hidden return pointer: a function returning a class by value takes an sret pointer in slot 0, which the mangling does not mention, so the declared this binds to it.

/* leveldb::Status TableBuilder::status() const */
- unsigned long leveldb::TableBuilder::status(unsigned long a0,int8 *a1)
+ TableBuilder * leveldb::TableBuilder::status(TableBuilder *this)   /* rsi read-before-write */

Ghidra gets these wrong too, and worse: its parameter-count heuristic sees 3 recovered vs 1 mangled, concludes "not a thiscall", and emits Handler * leveldb::WriteBatch::Iterate(Handler *param_1) — this dropped entirely and slot 0 mis-typed. Closing it properly needs the recovered parameter count, i.e. a decompile pass; recorded as a follow-up.

Three defects the sweep found that the witness could not

  1. outtype: None crashed the CALLER-side rebuild. Handled at Funcdata::apply_locked_prototype instead of FuncProto::seed_locked_from_pieces, it left ActionDefaultParams — which reconstructs a callee's prototype to type a call's arguments — hitting assign_map's expect("outtype null"), killing every main that called such a function.
  2. cpp_demangle drops a parameter on explicit function-template specializations: _ZNSt4pairI…EC1IRS1_S4_Lb1EEEOT_OT0_ is a two-parameter forwarding constructor rendered with ONE. Those are now refused outright — which also sidesteps the module's known maxof<int>/maxof<double> collision, and alone cut the measured harm from 8 functions to 2.
  3. Overloaded operators put unbalanced brackets into the demangled text and are the densest source of static/free false positives. Refused.

Speed

The pass walks the symbol table once at load and demangles each C++ name, so load is the metric. Interleaved off/on, minimum of 13 pairs (the box runs concurrent agents):

case off proven inferred
functions leveldb-O0 stripped (load only) 183.1 ms 183.8 (+0.35%) 184.0 (+0.48%)
functions regglobal_fmt_x86_64 (plain C) 175.3 ms 175.2 (−0.08%) 175.2 (−0.07%)
decompile leveldb ~Cache 894.0 ms 897.0 (+0.34%) 894.4 (+0.04%)
decompile-all cppproto_x86_64 127.8 ms 128.2 (+0.36%) 127.7 (−0.08%)
decompile-all cppsig_x86_64.so (n=31) 107.9 ms 108.1 (+0.19%) 108.0 (+0.10%)

Worst delta +0.48%, budget 5%. An n=13 run of that last 108 ms case reported +4.01% and did not reproduce at n=31. off still pays the demangle (the facts are computed then dropped at the commit), so the C rows are flat because a C binary has no mangled symbol to walk.

Option / DIV

cppsig, values off|proven|inferred, default proven, tier analysis, change_kind analysis-enablement. It changes emitted C on C++ binaries by default, so it takes DIV-62. Catalog counts derived from a fresh green build, never by arithmetic: settables 91 → 92, tiers (20, 41, 30) → (20, 41, 31), catalog rows 90 → 91, phase_catalog.json recaptured.

Tests

decompiler/crates/kuna-console/tests/verify_cppsig.rs — 7 two-pass e2e assertions over a new strip --strip-allped cppsig_x86_64.so fixture (no DWARF, no .symtab), including the DWARF-precedence check and one that pins inferred's known static-member cost so it cannot drift silently. Plus 19 hermetic parser / this-decision unit tests.

No stage XML: the XML datatest bootstrap builds its program from a <binaryimage> element and never produces an AnalysisOutput, so no kuna_analysis pass can fire there — the same reason verify_cppproto / verify_cppcallnames / verify_fdeinterior exist.

Two verify_cppproto baseline arms now set cppsig off explicitly: with the sibling recovery at its default the "gate off = the bug" baseline stopped reproducing, because a const member and an unqualified global are both PROVEN shapes.

Deliberately not in this PR

  • Automatic __thiscall selection. [AUTOMATED] feat(p4): cspecprotos - register the compiler spec's named prototype models (registry 1 -> 5 models, __thiscall resolves) #265 registered the model on all 294 language:compiler pairs and listed assigning it as a follow-up; it still is. PrototypePieces carries no model back-pointer (the C++ field was dropped precisely because kuna had no registry) and ArchContext exposes only defaultfp. Not needed for the win either: every ABI in the corpus passes this as ordinary argument 0. The one that does not — 32-bit MSVC __thiscall, this in ECX — is REFUSED rather than mis-placed.
  • Struct/class fields. A class stays a named opaque. Measured: nobody recovers this->field on a stripped binary; all five decompilers emit *(long *)this + 0x1d0.

Before / after — sig::Account::~Account in cppsig_x86_64.so

Real captured kuna output on the function this feature was built for, with option cppsig flipped. Ported from kuna — Ghidra DemangledFunction.applyTo / GnuDemanglerAnalyzer "Apply Function Signatures"; the string-parsing shape is GnuDemanglerParser, which likewise consumes the c++filt text rather than an AST.

metric cppsig off cppsig on (default)
gotos 0 0
labels 0 0
loc 5 5
switches 0 0
kuna — before (option cppsig off)
void sig::Account::~Account(unsigned int *a0)
{
  *dat_3fe0 = *a0;
  return;
}
kuna — after (option cppsig on)
void sig::Account::~Account(Account *this)
{
  *dat_3fe0 = *(unsigned int *)this;
  return;
}

mahaloz and others added 2 commits August 5, 2026 08:07
…eldb type_match 9 -> 35 of 525, +26 with 0 lost)

kuna applied no demangled C++ signature at all. The demangler reduces a mangled
symbol to its qualified NAME only - a hard requirement of the `::`-scope
splitter - and `demangle_raw`, the full c++filt form, had shipped with NO
production caller since the demangler landed, its own header recording the
signature application as "a deferred follow-up".

The cost is a STRIPPED C++ shared library, where the exported `.dynsym` mangled
name is the only signature source left. On stripped google/leveldb -O0,
functions whose first parameter is a named pointer ran ghidra 188 / ida 150 /
binja 60 / angr 0 / kuna 0 across 527 functions.

New `analyzers/demangle/kuna_cppsig.rs` parses the demangled STRING, the same
shape as upstream's GnuDemanglerParser, and parks a prototype by entry address.
A C++ reference maps to a pointer; a by-value aggregate, array, function pointer
or overloaded operator refuses the whole signature. The return type is
deliberately NOT applied - Itanium encodes one only for a template function, so
upstream returns null and keeps what the analysis recovered; kuna expresses that
as `outtype: None`, read as "lock the INPUT half only".

Three-valued because Itanium mangles a static member function exactly like a
non-static one: `proven` (the default) applies only what the mangling entails
and measures precision 1.0000 / recall 0.7093 on 1329 symbols with DWARF ground
truth; `inferred` decides the rest from class evidence at precision 0.9278 /
recall 1.0000. Ghidra 12.1's own `this` decision on the same binary is 0.85.

Benchmark, decbench leveldb O0 (n=525) with the fixed scorer (decbench
origin/main @325046f, PR #60): type_match perfects 9 -> 35 at the default
(+26, zero lost), 38 under `inferred`. Rivals on the same scorer: ghidra 44,
ida 35, binja 11, angr 8 - kuna moves from last to second.

Plain C is untouched: 11 binaries / 1,351 functions, 0 changed.

Gated `cppsig`, default `proven` (DIV-62); the pass runs at load, so both
certainty tiers are stashed apart and the mode applies at the analysis commit.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01McQC7imaNfzj5k5AVumSYN
…d + plan.md

The standing requirement is a docs/features/<slug>/ bundle of analysis.md,
plan.md and record.json; only record.json was written. Content is the
measured material from the PR body: the leveldb type_match standing, the
precision/recall table behind the three-valued `this` rule, the three
defects the whole-binary sweep found, and the refusals.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01McQC7imaNfzj5k5AVumSYN
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