Skip to content

[AUTOMATED] feat(p1): typedepth - restore upstream's DWARF type-cycle guard (294 truncated sites -> 0, type_match 458 -> 626 of 872) - #268

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

mahaloz merged 1 commit into
mainfrom
feat/typedepth

Conversation

@mahaloz

@mahaloz mahaloz commented Aug 5, 2026

Copy link
Copy Markdown
Contributor

The bug

kuna's DWARF type mapper truncates ordinary C declarations to void.
MAX_TYPE_DEPTH = 3 counts every hop of the DW_AT_type chain — the
transparent typedef/const/volatile/restrict links included — and its
comment cites Ghidra's DWARFDataTypeImporter.trackRecursion, which is not what
upstream does:

private boolean trackRecursion(long id, int delta) {
    Integer count = recursionTrackingOffsetToLoopCount.getOrDefault(id, 0);
    count = count + delta;
    switch (count) { case 3: Msg.error(...); return false; }
    recursionTrackingOffsetToLoopCount.put(id, count);
    return true;
}

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. kuna's reduction conflates "the same DIE again" with "a deep but finite
chain", and four DIEs is ordinary C:

declaration chain hops
const char *const * ptr → const → ptr → const → char 5
const size_t * ptr → const → typedef → base 4
char *const [] array → const → ptr → char 4
char *** ptr → ptr → ptr → char 4

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 new rule resolves all 294 (0 still truncated).

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: it only converts a hang into a wrong answer. The depth budget does guard
something real — DWARF type cycles, which nothing in the format forbids and a
truncated or forged .debug_info supplies — and upstream detects them rather
than approximating them.

Scope correction: half of the reported symptom was already gone

The brief listed char **authors / idx_t *pn / mbstate_t *ps (coreutils
fmt) and the C++ const-method this. All of those are already correct on
main
: #264 (cppproto) added strip_qualifiers on its cpp path, and
because cppproto is default-ON and rebuilds every subprogram's prototype (C
included) binding it by address, plain-C prototypes inherited the fix.
Account::available renders Account *this today — verified, not assumed.

What remained, and what this PR is:

  1. Stack locals — collect_fbreg_locals maps with cpp = false: no
    collapse, budget live. The 238 sites.
  2. Globals — the DW_OP_addr arm sizes the symbol from the same mapper; a
    truncated element type sizes the global at one byte, the covering
    SymbolEntry query misses, and it renders dat_<addr> or address-taken. 55
    sites.
  3. Structural depth — three pointer hops exhaust the budget even with the
    qualifiers collapsed (gzip's add_envopt(int *, char ***, char *) is
    void *** on main).
  4. The cppproto off path, which reverts all of the above.

The change

analyzers/dwarf/kuna_typedepth.rs restores upstream's guard: TypeWalk::Cycle
is the per-offset re-entry counter bracketing every recursive step, plus
MAX_NESTING = 64 as a native-stack backstop a Java port does not need.
TypeWalk::Depth is the old budget verbatim, so --option typedepth off is
byte-identical. Termination no longer rests on a bound that also has to be
small: an offset already twice on the path is refused, and a compilation unit has
finitely many offsets.

Two consequences ride along:

  • the qualifier collapse now runs for the C callers too, which is what carries
    an anonymous aggregate's typedef name onto it (position *firstpos,
    direntry_t *entries, not the shared anon_struct);
  • because a borrowed name can already be taken, intern_aggregate falls back to
    the anonymous name when the alias does not yield an aggregate. The sweep found
    this, not an argument
    : kuna registers a core type named code, zlib's
    inftrees.h really does typedef struct {...} code;, the factory refused the
    redefinition and the pointer arm's .or_else(get_type_void) degraded
    code *next to void *next. Only an aggregate with no name of its own
    falls back, so no new name is asserted for a genuinely named type.

Option + DIV decision

Gated (typedepth, on|off, default ON, DIV-63). It changes emitted C, so
it ships behind a name per the standing rule. Default-ON because every truncation
the budget produced was a concrete DWARF type replaced by void, the replacement
types come from the debug info rather than from inference, and the parity gates
are structurally untouched.

The gate is an env-var bridge (KUNA_TYPEDEPTH), the relocobjects /
i386_pie_plt pattern, not a commit-time gate like cppproto: cppproto selects
between two fact sets, this changes how a single fact set is built 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 the option lines after load file, so without it a
before/after demo of any load-time gate renders twice identically — which is
exactly what the first prdemo run produced.

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
make check-spec OK (lenient and --strict)
kuna catalog --check OK

Counters derived from a fresh green build, never by arithmetic: settables 92 → 93,
tiers core 20 / transform 41 / analysis 31 → 32, catalog JSON rows 91 → 92,
phase_catalog.json fixture regenerated from decomp_dbg.

Speed

The mapper runs once per binary inside load file, so LOAD is the metric.
Interleaved off/on, minimum of 15 pairs:

surface off on delta
kuna functions grep O0 (load+commit only) 693.5 ms 695.9 ms +0.35%
kuna functions zlib minigzip O0 450.8 ms 451.5 ms +0.16%
kuna decompile fmt O2 main 304.3 ms 305.0 ms +0.24%
kuna decompile-all fmt O0 1835.6 ms 1836.0 ms +0.02%
kuna decompile-all fixture 126.8 ms 126.6 ms −0.14%

Worst +0.35%, budget 5%. The guard trades an integer compare for a BTreeMap
entry per DIE hop on a walk a handful of hops deep; nothing in the decompile loop
is touched.

Sweep (decompile-all off vs on, every changed line classified)

binary changed lines classification
zlib minigzip O0 91 52 void *→concrete, 39 alias/extent/reshape
grep O0 83 30 void *→concrete, 53 anon_struct→position, dat_337e8→unibyte_mask, array notation
gzip O0 28 18 void *→concrete, 10 anon_struct→direntry_t, &crc_32_tab[…]→crc_32_tab[…]
coreutils fmt O0 2 void *authtab[10] → char *authtab[10]
coreutils fmt O2, bzip2 O0 0 —
stripped zlib minigzip (the scored corpus) 0 no .debug_* at all
cppproto_x86_64, cppsig_x86_64.so, eh_lsda_x86_64, cpp_noreturn_x86_64 0 C++ unaffected

The wrongness axis — a wrong concrete type asserted where void * was honest
— is 0 after the intern_aggregate guard (2 before it, both the code
collision). One class is noisier rather than cleaner and is reported as such: a
local now typed as a named opaque struct (z_stream_s *strm) renders its
field accesses through a cast, because kuna maps an aggregate to a named opaque
with no fields — the existing cppproto field-population seam, not a new one.

Benchmark

The decbench scored corpus is stripped, so it carries no .debug_* and this
change is a structural zero there — verified, not assumed (decompile-all off
vs on over the stripped zlib minigzip: 0 lines differ). That also re-frames the
C type_match standing (kuna 5.17% vs angr 7.29% / ida 5.55%): that gap is
measured with no debug info present, so it is an inference gap, not a
DWARF-consumption one, and no amount of DWARF fidelity addresses it.

Where debug info exists the delta is large — decbench type_match over the same
projects' unstripped compiled/ copies (zlib + bzip2 O0, 9 binaries, n=872,
scorer main @325046f, cache_version 5, DECBENCH_NO_CACHE=1):

before after
type_match perfects 458 626 (+168)
type_match mean 0.8438 0.9083
functions improved / worse — 193 / 0
zlib O0 (n=764) 401 561 (+160)
bzip2 O0 (n=108) 57 65 (+8)

gzip was started in both arms but only the off arm's evaluation finished inside
the wall-clock budget (the box was at load ~450 from sibling agents), so it is
excluded from both rather than reported one-sided.

Tests

kuna-console/tests/verify_typedepth.rs — six two-pass e2e assertions over a new
-g -O0 C fixture (typedepth_x86_64, source vendored): the const char *const *
local, three pointer hops, the anonymous-typedef alias, the code collision, the
global's extent, and termination on self-referential + mutually recursive
structs. A Rust integration test rather than stage XML because the XML
<binaryimage> bootstrap never runs the analyzer tier (precedent
verify_cppcallnames.rs #262, verify_fdeinterior.rs #263, verify_cppsig.rs
#266); the gate is set through the env var before bootstrap_from_object,
serialized by a mutex, because the mapping happens at load.

Plus six hermetic unit tests, including a forged .debug_info whose type
chain closes on itself (self-pointer, mutually pointing typedef/const,
self-referential array) asserted to terminate under both arms — the
termination proof is a test, not an argument.

Docs: docs/spec/01-program-prep.md (prose, not just an anchor), docs/history.md
DIV-63, docs/features/typedepth/{analysis,plan,record}.{md,json},
regenerated docs/options.md.


Before / after — count_authors in typedepth_x86_64

Real captured kuna output on the function this feature was built for, with option typedepth flipped. Ported from kuna — Ghidra DWARFDataTypeImporter.trackRecursion (per-DIE-offset re-entry counter).

metric typedepth off typedepth on (default)
gotos 0 0
labels 0 0
loc 12 12
switches 0 0
kuna — before (option typedepth off)
int4 count_authors(char **authors)
{
  int4 n; // stack - 0x14
  void **p; // stack - 0x10
  char *v1;
  
  n = 0;
  for (p = authors; *p; p = &p[1]) {
    v1 = *p;
    n += (int4)strlen(v1);
  }
  return n;
}
kuna — after (option typedepth on)
int4 count_authors(char **authors)
{
  int4 n; // stack - 0x14
  char **p; // stack - 0x10
  char *v1;
  
  n = 0;
  for (p = authors; *p; p = &p[1]) {
    v1 = *p;
    n += (int4)strlen(v1);
  }
  return n;
}
kuna reference (the goal, v9.2.223)
unsigned int count_authors(char **a0)
{
    unsigned int v0;  // [bp-0x14]
    char **i;  // [bp-0x10]

    i = a0;
    for (v0 = 0; *(i); i += 1)
    {
        v0 += (unsigned int)strlen(*(i));
    }
    return v0;
}

… guard (294 truncated sites -> 0, type_match 458 -> 626 of 872)

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.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01McQC7imaNfzj5k5AVumSYN
@mahaloz
mahaloz merged commit d4a3fd2 into main Aug 5, 2026
9 checks passed
@mahaloz
mahaloz deleted the feat/typedepth branch August 5, 2026 16:30
mahaloz added a commit that referenced this pull request Aug 5, 2026
… RTTI graph and its vtables, the analyzer Ghidra does not have (DIV-64)

Ghidra has NO Itanium RTTI analyzer at all: its `RttiAnalyzer` is a Microsoft-PE
analyzer and its GCC class recovery is script-tier (RecoverClassesFromRTTIScript /
RTTIGccClassRecoverer), never auto-analysis, so on a stripped g++ binary it leaves
the Shape vtable as DAT_00107a80. IDA Pro does reconstruct it. kuna had ZERO
_ZTV/_ZTI/__class_type_info/__cxxabiv1 hits anywhere in decompiler/crates: the MSVC
half of C++ RTTI recovery was ported, the Itanium half never was, and the mechanism
does not transfer.

Discovery here is EXACT rather than a byte-pattern scan. The three __cxxabiv1
typeinfo vtables live in libstdc++, so every _ZTI object's leading vptr word is an
undefined-symbol dynamic relocation naming __class_type_info / __si_class_type_info /
__vmi_class_type_info with addend 2*ptr -- the relocation's r_offset IS the typeinfo
address and its symbol IS the flavour, and .rela.dyn is a loader input that
`strip --strip-all` cannot remove. This is not a convenience: in a PIE or shared
object the typeinfo's vptr word is 0 in the file, so the MSVC pass's own discovery
heuristic ("find the vptr the most TypeDescriptors agree on") recovers nothing on a
modern dynamically linked C++ binary.

Vtables are reached FROM the typeinfo rather than guessed -- one scan for pointer
slots holding a typeinfo address, filtered by two exact ABI constraints
(offset-to-top <= 0; at least one slot into an executable section) that reject 4/4
coincidental candidates on the probe. A slot reading 0 that carries a dynamic
relocation is an imported virtual method (__cxa_pure_virtual), so the walk steps over
it instead of truncating an abstract interface's vtable.

(NOVEL) covers the two things no other decompiler showed us the answer to: naming a
SECONDARY sub-vtable for the base subobject its inheritance displacement identifies
(Widget_vtable_for_Drawable, read off the __vmi base list -- the datum the MSVC path
discards with its pmd fields), and attributing an inherited slot to the class that
DEFINES it rather than to whichever vtable the scan reached first.

Witness: stripped g++ -O0 probe, 23 of 23 virtual methods across six classes, every
name matching the unstripped `nm -C` ground truth -- including the three
`non-virtual thunk to ...` entries, recovered as Widget::vtable_for_Drawable_0/1/2.

REACHABILITY (the reason for DIV-64). A default-off option is only half a decision:
`auto` selects `aggressive` below 500 KiB, which is the default path for
decompile-all, the kuna CLI, the web front-end and the benchmark, so an option
outside AGGRESSIVE_OVERRIDES never runs for anyone. This feature was first written in
exactly that state -- measured 0 recovered names under `--mode aggressive`, 29 with
an explicit `--option`. It now joins the preset, which is the preset's own documented
contract ("every off-by-default option flipped ON except v850indirectbranch and
dwarf_lines", with the format-gated no-ops rtti/pdb/objc/macho-arm64e/sparcstructret
named as the safe class); itaniumrtti has a strictly narrower firing condition than
rtti's PE gate. `--mode reliable` stays at 0, so the shipped defaults are untouched.

That invariant turned out to be only SAMPLED by a test, never enforced, which is why
the omission was silent. modes.rs::aggressive_carries_every_default_off_option now
enforces it and immediately found four further default-off options in the same trap
(cortexmvectors, ptrentry, tailcallentry, paramcopyhoist), recorded as an explicit
UNEVALUATED list rather than silently flipped -- each changes emitted C on the
binaries it fires for and needs its own sweep and PR.

No _LOADTIME_GATE_ENV entry is needed in scripts/decompile.py, verified rather than
assumed: #268 added that table because typedepth's DWARF types are CONSUMED inside
`load file`, while itaniumrtti commits its facts at `read symbols`, which every
`option` line precedes. The rule is now documented next to the table.

This does NOT move leveldb and cannot: libleveldb.so is built -fno-rtti (18 _ZTV
symbols, zero _ZTI, zero _ZTS, zero __cxxabiv1 relocations), so the pass emits
nothing -- verified by sweep, 3,962 functions at -O0 and 919 at -O2, 0 changed. The
separable vtable-only half was measured before scoping and rejected: of 126 slots in
the 17 defined _ZTV objects, 59 are __cxa_pure_virtual, 31 are unrelocated header
words, and every one of the remaining 36 already carries a .dynsym name -- zero
recoverable-but-unnamed methods. No benchmark number is claimed.

An adversarial probe (two template instantiations, a deep namespace, an
anonymous-namespace class) found two defects the good-citizen witness could not, and
fixing them took recovery there from 7 of 14 virtual methods to 14 of 14:
Vec<int>/Vec<double> collapsing to one class under name-only demangling (the second
then loses the idempotent name race and stays sub_<addr>, silently), and every
TU-local class being undemangleable because the ABI (2.9.1) prefixes its type-name
string with `*`. Both are now in the shipped fixture.

Sweep (pre-PR default path `--mode aggressive --option itaniumrtti off` vs post-PR
`--mode aggressive`, restricted to the <500 KiB binaries the preset applies to):
plain C 14 binaries / 357 functions 0 changed; C++ 8 binaries / 364 functions,
changed only the fixture and the two probes plus ONE hunk in cppproto_x86_64 that is
strictly better (`*(unsigned long *)this = 0x402028` -> `*(code **)this =
Shape_vptr`). Above the threshold at the option level: leveldb -O0 3,962 / -O2 919
and mcount_x86_64 1,073, all 0 changed. 0 new decompile errors, and the function
ENTRY set is byte-identical everywhere -- the pass names things, it never discovers
them.

Speed (interleaved, minimum of 15 pairs; 31 for the fire row). The number that
matters is the cost where it does NOT fire, which every user pays: +0.24% on
mcount_x86_64 (896 KiB static C, 1,969 symbols), +0.26% on stripped leveldb (1,546
dynamic relocations), +0.28% on regglobal_fmt_x86_64, and -0.38%..+0.25% end-to-end
under `--mode aggressive`. Where it does fire, +0.99% (vs +2.13% pre-preset in
isolation -- same work, larger denominator). Worst no-fire +0.28%, worst overall
+0.99%, budget 5%.

A NEW option rather than a widening of the PE-only `rtti`: the two paths have
different default-ON trajectories -- the MSVC path is a byte-pattern heuristic that
will plausibly stay opt-in forever, while this one is relocation-anchored and exact
with a measured 0-change footprint on 14 plain-C binaries. DIV-64 records the preset
membership, not the option default: `--mode reliable` is byte-identical, but mode
presets are not a datatest surface, so a membership change alters default rendering
where no parity oracle can see it -- exactly why DIV-43 exists for the symmetric
removal of dwarf_lines from the same preset.

Rebased onto d4a3fd2 (#268 typedepth), which added an option and made the identical
`92 -> 93` counter edit. git auto-merged catalog_bytecompat.rs and phase_catalog.json
with no conflict, leaving every counter short by one, and kuna_phases/tests.rs
conflicted only on the comment lines. Every counter was RE-DERIVED from a fresh green
build: settables 94, tiers (20 core, 41 transform, 33 analysis), catalog JSON rows 93;
phase_catalog.json recaptured from a fresh release decomp_dbg rather than hand-edited.

Gates: make test PARITY OK (675/675, no re-pin), make test-stages PARITY OK, make
rust-test green, make check-spec OK (lenient + strict), kuna catalog --check OK.

Covered by kuna-console/tests/verify_itaniumrtti.rs (7 two-pass e2e assertions over a
new stripped hidden-visibility fixture) plus 9 hermetic unit tests and the new
modes.rs preset invariant. No stage XML: the XML <binaryimage> datatest bootstrap
never produces an AnalysisOutput and cannot reach the analyzer tier, the same reason
cppsig / cppproto / fdeinterior / cppcallnames all use Rust integration tests.

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
The measured C `type_match` delta (decbench origin/main @325046f,
DECBENCH_NO_CACHE=1, all three optimisation levels, option off vs on):
grep 33 -> 37 perfects, diffutils 24 -> 35, gzip 57 -> 62, bzip2 mean
0.2617 -> 0.2712, findutils 21 -> 23. Pooled n=2,092: perfects 143 -> 165
(+22), mean 0.2272 -> 0.2501 (+10.1%), 137 functions improved against 3
worse.

Renumbered to DIV-64 on the rebase onto #268, which claimed DIV-63.

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
… RTTI graph and its vtables, the analyzer Ghidra does not have (DIV-64) (#267)

Ghidra has NO Itanium RTTI analyzer at all: its `RttiAnalyzer` is a Microsoft-PE
analyzer and its GCC class recovery is script-tier (RecoverClassesFromRTTIScript /
RTTIGccClassRecoverer), never auto-analysis, so on a stripped g++ binary it leaves
the Shape vtable as DAT_00107a80. IDA Pro does reconstruct it. kuna had ZERO
_ZTV/_ZTI/__class_type_info/__cxxabiv1 hits anywhere in decompiler/crates: the MSVC
half of C++ RTTI recovery was ported, the Itanium half never was, and the mechanism
does not transfer.

Discovery here is EXACT rather than a byte-pattern scan. The three __cxxabiv1
typeinfo vtables live in libstdc++, so every _ZTI object's leading vptr word is an
undefined-symbol dynamic relocation naming __class_type_info / __si_class_type_info /
__vmi_class_type_info with addend 2*ptr -- the relocation's r_offset IS the typeinfo
address and its symbol IS the flavour, and .rela.dyn is a loader input that
`strip --strip-all` cannot remove. This is not a convenience: in a PIE or shared
object the typeinfo's vptr word is 0 in the file, so the MSVC pass's own discovery
heuristic ("find the vptr the most TypeDescriptors agree on") recovers nothing on a
modern dynamically linked C++ binary.

Vtables are reached FROM the typeinfo rather than guessed -- one scan for pointer
slots holding a typeinfo address, filtered by two exact ABI constraints
(offset-to-top <= 0; at least one slot into an executable section) that reject 4/4
coincidental candidates on the probe. A slot reading 0 that carries a dynamic
relocation is an imported virtual method (__cxa_pure_virtual), so the walk steps over
it instead of truncating an abstract interface's vtable.

(NOVEL) covers the two things no other decompiler showed us the answer to: naming a
SECONDARY sub-vtable for the base subobject its inheritance displacement identifies
(Widget_vtable_for_Drawable, read off the __vmi base list -- the datum the MSVC path
discards with its pmd fields), and attributing an inherited slot to the class that
DEFINES it rather than to whichever vtable the scan reached first.

Witness: stripped g++ -O0 probe, 23 of 23 virtual methods across six classes, every
name matching the unstripped `nm -C` ground truth -- including the three
`non-virtual thunk to ...` entries, recovered as Widget::vtable_for_Drawable_0/1/2.

REACHABILITY (the reason for DIV-64). A default-off option is only half a decision:
`auto` selects `aggressive` below 500 KiB, which is the default path for
decompile-all, the kuna CLI, the web front-end and the benchmark, so an option
outside AGGRESSIVE_OVERRIDES never runs for anyone. This feature was first written in
exactly that state -- measured 0 recovered names under `--mode aggressive`, 29 with
an explicit `--option`. It now joins the preset, which is the preset's own documented
contract ("every off-by-default option flipped ON except v850indirectbranch and
dwarf_lines", with the format-gated no-ops rtti/pdb/objc/macho-arm64e/sparcstructret
named as the safe class); itaniumrtti has a strictly narrower firing condition than
rtti's PE gate. `--mode reliable` stays at 0, so the shipped defaults are untouched.

That invariant turned out to be only SAMPLED by a test, never enforced, which is why
the omission was silent. modes.rs::aggressive_carries_every_default_off_option now
enforces it and immediately found four further default-off options in the same trap
(cortexmvectors, ptrentry, tailcallentry, paramcopyhoist), recorded as an explicit
UNEVALUATED list rather than silently flipped -- each changes emitted C on the
binaries it fires for and needs its own sweep and PR.

No _LOADTIME_GATE_ENV entry is needed in scripts/decompile.py, verified rather than
assumed: #268 added that table because typedepth's DWARF types are CONSUMED inside
`load file`, while itaniumrtti commits its facts at `read symbols`, which every
`option` line precedes. The rule is now documented next to the table.

This does NOT move leveldb and cannot: libleveldb.so is built -fno-rtti (18 _ZTV
symbols, zero _ZTI, zero _ZTS, zero __cxxabiv1 relocations), so the pass emits
nothing -- verified by sweep, 3,962 functions at -O0 and 919 at -O2, 0 changed. The
separable vtable-only half was measured before scoping and rejected: of 126 slots in
the 17 defined _ZTV objects, 59 are __cxa_pure_virtual, 31 are unrelocated header
words, and every one of the remaining 36 already carries a .dynsym name -- zero
recoverable-but-unnamed methods. No benchmark number is claimed.

An adversarial probe (two template instantiations, a deep namespace, an
anonymous-namespace class) found two defects the good-citizen witness could not, and
fixing them took recovery there from 7 of 14 virtual methods to 14 of 14:
Vec<int>/Vec<double> collapsing to one class under name-only demangling (the second
then loses the idempotent name race and stays sub_<addr>, silently), and every
TU-local class being undemangleable because the ABI (2.9.1) prefixes its type-name
string with `*`. Both are now in the shipped fixture.

Sweep (pre-PR default path `--mode aggressive --option itaniumrtti off` vs post-PR
`--mode aggressive`, restricted to the <500 KiB binaries the preset applies to):
plain C 14 binaries / 357 functions 0 changed; C++ 8 binaries / 364 functions,
changed only the fixture and the two probes plus ONE hunk in cppproto_x86_64 that is
strictly better (`*(unsigned long *)this = 0x402028` -> `*(code **)this =
Shape_vptr`). Above the threshold at the option level: leveldb -O0 3,962 / -O2 919
and mcount_x86_64 1,073, all 0 changed. 0 new decompile errors, and the function
ENTRY set is byte-identical everywhere -- the pass names things, it never discovers
them.

Speed (interleaved, minimum of 15 pairs; 31 for the fire row). The number that
matters is the cost where it does NOT fire, which every user pays: +0.24% on
mcount_x86_64 (896 KiB static C, 1,969 symbols), +0.26% on stripped leveldb (1,546
dynamic relocations), +0.28% on regglobal_fmt_x86_64, and -0.38%..+0.25% end-to-end
under `--mode aggressive`. Where it does fire, +0.99% (vs +2.13% pre-preset in
isolation -- same work, larger denominator). Worst no-fire +0.28%, worst overall
+0.99%, budget 5%.

A NEW option rather than a widening of the PE-only `rtti`: the two paths have
different default-ON trajectories -- the MSVC path is a byte-pattern heuristic that
will plausibly stay opt-in forever, while this one is relocation-anchored and exact
with a measured 0-change footprint on 14 plain-C binaries. DIV-64 records the preset
membership, not the option default: `--mode reliable` is byte-identical, but mode
presets are not a datatest surface, so a membership change alters default rendering
where no parity oracle can see it -- exactly why DIV-43 exists for the symmetric
removal of dwarf_lines from the same preset.

Rebased onto d4a3fd2 (#268 typedepth), which added an option and made the identical
`92 -> 93` counter edit. git auto-merged catalog_bytecompat.rs and phase_catalog.json
with no conflict, leaving every counter short by one, and kuna_phases/tests.rs
conflicted only on the comment lines. Every counter was RE-DERIVED from a fresh green
build: settables 94, tiers (20 core, 41 transform, 33 analysis), catalog JSON rows 93;
phase_catalog.json recaptured from a fresh release decomp_dbg rather than hand-edited.

Gates: make test PARITY OK (675/675, no re-pin), make test-stages PARITY OK, make
rust-test green, make check-spec OK (lenient + strict), kuna catalog --check OK.

Covered by kuna-console/tests/verify_itaniumrtti.rs (7 two-pass e2e assertions over a
new stripped hidden-visibility fixture) plus 9 hermetic unit tests and the new
modes.rs preset invariant. No stage XML: the XML <binaryimage> datatest bootstrap
never produces an AnalysisOutput and cannot reach the analyzer tier, the same reason
cppsig / cppproto / fdeinterior / cppcallnames all use Rust integration tests.


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
The measured C `type_match` delta (decbench origin/main @325046f,
DECBENCH_NO_CACHE=1, all three optimisation levels, option off vs on):
grep 33 -> 37 perfects, diffutils 24 -> 35, gzip 57 -> 62, bzip2 mean
0.2617 -> 0.2712, findutils 21 -> 23. Pooled n=2,092: perfects 143 -> 165
(+22), mean 0.2272 -> 0.2501 (+10.1%), 137 functions improved against 3
worse.

Renumbered to DIV-64 on the rebase onto #268, which claimed DIV-63.

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
…n (C type_match perfects 143 -> 165 over 2,092 functions, 137 improved / 3 worse) (DIV-65) (#269)

* [AUTOMATED] feat(p1): libcsigs - the measured libc signature extension, 27 -> 233 prototypes

kuna's built-in libc prototype table carries 27 entries. Its own header calls the
shortfall a documented LOSS: Ghidra applies parsed C headers shipped as binary
`.gdt` archives, that format is not vendored, and the table is "a faithful,
minimal stand-in". The constraint is that no header archive exists in the tree,
not licensing - so the table is small because nobody has grown it.

Every libc callee outside those 27 leaves its callers' arguments an inferred
`unsigned long`, and half of the 1587 cases where IDA scores a perfect C
`type_match` and kuna does not have an integer-typed kuna parameter where IDA has
a concrete type.

`analyzers/protos/kuna_libcsigs.rs` adds the measured remainder: 206 further
signatures, chosen by frequency rather than intuition (a PLT call-site histogram
over the 547 frozen-decbench C binaries, plus a per-callee ranking of those 1587
cases; the rule is >= 100 sites or >= 3 cases). Every signature is reduced from a
machine-readable declaration - `gcc -aux-info` over the platform headers with
_GNU_SOURCE + _FORTIFY_SOURCE=2 for the bulk, GCC's builtin types for the FORTIFY
`_chk` family, the `<stdio.h>` `__REDIRECT` for the `__isoc99_*` aliases - and a
declaration whose every slot is not width-stable across ILP32/LP64 is REJECTED
rather than approximated (`lseek`, `time`, `strtoll`, `fseeko`, `mmap`, `signal`,
`qsort`), because a wrong prototype asserts a false type where `unsigned long` was
merely uninformative.

The same principle drives the one novel rule: an entry applies only to a name the
image IMPORTS and does not itself define. zlib's `minigzip` declares
`void error(const char *msg)` where glibc's is `void error(int,int,const char*,...)`,
and typing that call `error(0,0,...)` would be strictly worse than what it
replaces. The 27-entry base table's defined-or-imported matching is untouched.

Behind `--option libcsigs on|off`, default ON; `off` renders exactly what the base
table alone renders.

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

* [AUTOMATED] docs(libcsigs): DIV-64 row and the feature record

The measured C `type_match` delta (decbench origin/main @325046f,
DECBENCH_NO_CACHE=1, all three optimisation levels, option off vs on):
grep 33 -> 37 perfects, diffutils 24 -> 35, gzip 57 -> 62, bzip2 mean
0.2617 -> 0.2712, findutils 21 -> 23. Pooled n=2,092: perfects 143 -> 165
(+22), mean 0.2272 -> 0.2501 (+10.1%), 137 functions improved against 3
worse.

Renumbered to DIV-64 on the rebase onto #268, which claimed DIV-63.

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

* [AUTOMATED] fix(libcsigs): DIV-65, counters re-derived from a capture, preset decision

Rebase onto #267 (`itaniumrtti`), which claimed DIV-64 and added an option.

DIV-64 -> DIV-65. The counters are NOT arithmetic: `catalog_bytecompat.rs`
auto-merged to 94 with no conflict, because #267 and this branch had each made
the identical 93 -> 94 edit, so the committed value was silently short by one.
Re-derived by capturing `phase_catalog.json` from a fresh release build and
COUNTING it: 95 settables, tiers (20, 41, 34), 94 JSON rows -- and
`docs/options.md` independently reports 95 option headings. The two generated
artifacts (`phase_catalog.json`, `docs/options.md`) did merge line-by-line
correctly; the trap was only in the hard-coded `.rs` counts.

Preset decision, stated rather than left implicit: `libcsigs` is deliberately NOT
in AGGRESSIVE_OVERRIDES. It ships default-ON, so #267's
`aggressive_carries_every_default_off_option` invariant is out of scope for it --
and the liveness was measured, not assumed. On dircolors (55,680 bytes, so `auto`
resolves to `aggressive`), default vs `--option libcsigs off` differs in 57/184
functions under auto, 57/184 aggressive, 58/183 reliable, 58/184 fast. Adding it
would be worse than redundant: the preset OWNS an option it lists, and every
benchmark and sweep number in this PR was produced by `--option libcsigs off` on
sub-500 KiB binaries, i.e. straight through auto -> aggressive -- membership would
silently re-enable it there and destroy the ablation hook.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
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