Repository navigation
[AUTOMATED] feat(p1): typedepth - restore upstream's DWARF type-cycle guard (294 truncated sites -> 0, type_match 458 -> 626 of 872) - #268
Merged
Conversation
… 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
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
This was referenced Aug 5, 2026
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]>
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.
The bug
kuna's DWARF type mapper truncates ordinary C declarations to
void.MAX_TYPE_DEPTH = 3counts every hop of theDW_AT_typechain — thetransparent
typedef/const/volatile/restrictlinks included — and itscomment cites Ghidra's
DWARFDataTypeImporter.trackRecursion, which is not whatupstream 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. kuna's reduction conflates "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_infoacross six-gCbinaries (coreutils
fmtO0/O2, grep, bzip2, zlibminigzip, gzip): 294 —238
DW_OP_fbregstack locals/params, 55 CU-top-level globals, 1 prototypeparameter. 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_infosupplies — and upstream detects them ratherthan approximating them.
Scope correction: half of the reported symptom was already gone
The brief listed
char **authors/idx_t *pn/mbstate_t *ps(coreutilsfmt) and the C++const-methodthis. All of those are already correct onmain: #264 (cppproto) addedstrip_qualifierson itscpppath, andbecause
cppprotois default-ON and rebuilds every subprogram's prototype (Cincluded) binding it by address, plain-C prototypes inherited the fix.
Account::availablerendersAccount *thistoday — verified, not assumed.What remained, and what this PR is:
collect_fbreg_localsmaps withcpp = false: nocollapse, budget live. The 238 sites.
DW_OP_addrarm sizes the symbol from the same mapper; atruncated element type sizes the global at one byte, the covering
SymbolEntryquery misses, and it rendersdat_<addr>or address-taken. 55sites.
qualifiers collapsed (gzip's
add_envopt(int *, char ***, char *)isvoid ***onmain).cppproto offpath, which reverts all of the above.The change
analyzers/dwarf/kuna_typedepth.rsrestores upstream's guard:TypeWalk::Cycleis the per-offset re-entry counter bracketing every recursive step, plus
MAX_NESTING = 64as a native-stack backstop a Java port does not need.TypeWalk::Depthis the old budget verbatim, so--option typedepth offisbyte-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:
an anonymous aggregate's typedef name onto it (
position *firstpos,direntry_t *entries, not the sharedanon_struct);intern_aggregatefalls back tothe 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'sinftrees.hreally doestypedef struct {...} code;, the factory refused theredefinition and the pointer arm's
.or_else(get_type_void)degradedcode *nexttovoid *next. Only an aggregate with no name of its ownfalls 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, soit 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 replacementtypes 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), therelocobjects/i386_pie_pltpattern, not a commit-time gate likecppproto:cppprotoselectsbetween two fact sets, this changes how a single fact set is built inside
load file, upstream of everyoptioncommand.scripts/decompile.pygains the same bridge (a one-entry load-time-gate table):its console script emits the
optionlines afterload file, so without it abefore/after demo of any load-time gate renders twice identically — which is
exactly what the first
prdemorun produced.Gates
make testmake test-stagesmake rust-testmake check-spec--strict)kuna catalog --checkCounters 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.jsonfixture regenerated fromdecomp_dbg.Speed
The mapper runs once per binary inside
load file, so LOAD is the metric.Interleaved off/on, minimum of 15 pairs:
kuna functionsgrep O0 (load+commit only)kuna functionszlibminigzipO0kuna decompilefmtO2mainkuna decompile-allfmtO0kuna decompile-allfixtureWorst +0.35%, budget 5%. The guard trades an integer compare for a
BTreeMapentry per DIE hop on a walk a handful of hops deep; nothing in the decompile loop
is touched.
Sweep (
decompile-alloff vs on, every changed line classified)minigzipO0void *→concrete, 39 alias/extent/reshapevoid *→concrete, 53anon_struct→position,dat_337e8→unibyte_mask, array notationvoid *→concrete, 10anon_struct→direntry_t,&crc_32_tab[…]→crc_32_tab[…]fmtO0void *authtab[10]→char *authtab[10]fmtO2, bzip2 O0minigzip(the scored corpus).debug_*at allcppproto_x86_64,cppsig_x86_64.so,eh_lsda_x86_64,cpp_noreturn_x86_64The wrongness axis — a wrong concrete type asserted where
void *was honest— is 0 after the
intern_aggregateguard (2 before it, both thecodecollision). 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 itsfield accesses through a cast, because kuna maps an aggregate to a named opaque
with no fields — the existing
cppprotofield-population seam, not a new one.Benchmark
The decbench scored corpus is
stripped, so it carries no.debug_*and thischange is a structural zero there — verified, not assumed (
decompile-alloffvs on over the stripped zlib
minigzip: 0 lines differ). That also re-frames theC
type_matchstanding (kuna 5.17% vs angr 7.29% / ida 5.55%): that gap ismeasured 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_matchover the sameprojects' unstripped
compiled/copies (zlib + bzip2 O0, 9 binaries, n=872,scorer
main@325046f,cache_version5,DECBENCH_NO_CACHE=1):type_matchperfectstype_matchmeangzip 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 -O0C fixture (typedepth_x86_64, source vendored): theconst char *const *local, three pointer hops, the anonymous-typedef alias, the
codecollision, theglobal'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 (precedentverify_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_infowhose typechain 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.mdDIV-63,
docs/features/typedepth/{analysis,plan,record}.{md,json},regenerated
docs/options.md.Before / after —
count_authorsintypedepth_x86_64Real captured kuna output on the function this feature was built for, with
option typedepthflipped. Ported from kuna — Ghidra DWARFDataTypeImporter.trackRecursion (per-DIE-offset re-entry counter).typedepth offtypedepth on(default)kuna — before (
option typedepth off)kuna — after (
option typedepth on)kuna reference (the goal, v9.2.223)