Skip to content

[AUTOMATED] feat(p1): libcsigs - the measured libc signature extension (C type_match perfects 143 -> 165 over 2,092 functions, 137 improved / 3 worse) (DIV-65) - #269

Merged
mahaloz merged 3 commits into
mainfrom
feat/libcsigs
Aug 5, 2026

Conversation

@mahaloz

@mahaloz mahaloz commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

The finding

kuna-analysis/src/analyzers/protos/mod.rs carries a 27-entry libc prototype table. Its own header calls the shortfall a documented LOSS and says why: Ghidra applies parsed C headers shipped as binary .gdt data-type archives, that format is not vendored into the kuna tree, and the table is "a faithful, minimal stand-in".

I checked whether the constraint was deliberate. It is not a constraint on size. These are standard C library declarations, not licensed data; docs/missing-ghidra-analyses.md classifies the whole item as a dependency/data substitution of the same kind as BFD → object. The table is small because nobody had grown it.

The cost is that every libc callee outside those 27 leaves its callers' arguments an inferred unsigned long. Of the 1,587 cases where IDA scores a perfect C type_match and kuna does not, 568 (35.8%) sit in a function that calls a libc name the table did not know, against 395 (24.9%) that call one it did.

Mechanism, and why not the alternatives

The brief offered three shapes; this is (a) extend the hand-written table, and the reasoning is in docs/features/libcsigs/plan.md:

  • (b) generate at build time is rejected on purpose. Making the build read /usr/include would make kuna's output depend on the build host's libc — a kuna built on musl, or on a glibc with a different _FORTIFY_SOURCE default, would emit different C for the same binary. It also cannot cover the three groups that have no header prototype (__stack_chk_fail, the *_chk builtins, the __isoc99_* redirects) — ~45,000 corpus call sites between them. Headers are used here as an offline source of truth for a checked-in table, which keeps (b)'s rigour without (b)'s build coupling.
  • A real header-derived type database (struct/enum layouts travelling with a signature, so struct stat * stops being void *) is a genuinely larger piece of work and stays a separate item.

Which names — measured, not guessed

Two independent rankings over the frozen, read-only decbench C corpus:

  1. objdump -d over the 547 C binaries carrying a scored case → a PLT call-site histogram (1,930 distinct imports).
  2. Each of the 1,587 IDA-perfect/kuna-imperfect type_match cases mapped into its containing function block → a per-callee ranking of what would actually move the metric.

Rule: ≥ 100 corpus call sites or ≥ 3 such cases, plus a named-witness set. 206 entries, headed by:

cases sites bins name cases sites bins name
119 5,456 469 exit 42 5,587 217 error
91 8,311 121 gettext 38 310 86 strncasecmp
87 24,084 456 __errno_location 35 1,384 276 open
63 2,093 165 strcasecmp 31 6,276 220 strerror
55 5,112 327 close 30 14,664 201 dcgettext
50 29,055 466 __stack_chk_fail — 12,824 292 __fprintf_chk

Two measured negatives worth recording: the err/warn/errx family the brief suggested does not appear in this corpus at all (warnx 12 sites, the rest 0) — error(3) is what GNU userland calls. They are in the table because they are free and correct, not because they were measured.

Which signature — machine-derived, never from memory

A wrong prototype is worse than a missing one: it asserts a false type where unsigned long was merely uninformative.

  • 193 entries reduced by a fixed rule from the 1,520 NC-line prototypes gcc -aux-info emits over a TU including the platform headers with _GNU_SOURCE + _FORTIFY_SOURCE=2.
  • __isoc99_{scanf,sscanf,fscanf} from the __REDIRECT at /usr/include/stdio.h:434-441, which is the header proving them ABI-identical to the names they replace.
  • The FORTIFY mem/str _chk family has no header prototype (they are GCC builtins) — checked against GCC's own builtin table with nine compiling _Static_assert(__builtin_types_compatible_p(…)).
  • __stack_chk_fail from glibc debug/stack_chk_fail.c.
  • 16 signatures re-read by hand against man 3 as a cross-check; all matched.

Rejected rather than approximated. Ty has no spelling for a slot whose width is not stable across ILP32/LP64, so a declaration containing one is dropped: lseek (746 sites, __off_t), signal (574, function pointer), time (399), qsort (323), strtoll (247, long long), fseeko, mmap, poll, iconv, connect, pthread_once. strtoll is the one that mattered — an earlier reducer classified long long int as a 4-byte integer and would have shipped int strtoll(...). The width rule caught it, not review.

The wrongness axis: imports only

A 27-entry table can match defined-or-imported by luck. A 206-entry one cannot. readelf over all 677 binaries of the frozen O0/O2/O2-noinline trees found exactly one real collision outside NuttX (which implements the genuine POSIX API anyway):

zlib/minigzip:  void error(const char *msg);          /* shndx 16, never UND */
glibc:          void error(int, int, const char *, ...);

So an entry here applies only to a name the image imports and does not itself define. A PLT/IAT import named error is definitively the platform's; a defined one is the program's own function sharing a spelling. This is also Ghidra's model (archives apply to external functions), and it makes a statically linked image inert. The 27-entry base table's matching is untouched.

The FORTIFY entry points are modelled as the distinct functions they are, not aliases: __printf_chk takes a leading int flag so the format sits at slot 1; __fprintf_chk a FILE * then a flag. Treating either as its namesake would shift every argument of the most frequent call in the C corpus.

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 catalog OK

Structural: the XML <binaryimage> datatest bootstrap never runs the analyzer tier, so it cannot reach this pass.

Measured C type_match delta

decbench origin/main @325046f, DECBENCH_NO_CACHE=1, all three optimisation levels, option off vs on:

project n perfects off → on mean off → on improved / worse
grep 247 33 → 37 0.3105 → 0.3243 9 / 2
diffutils 420 24 → 35 0.2522 → 0.2987 40 / 0
gzip 368 57 → 62 0.3740 → 0.4007 35 / 1
bzip2 267 8 → 8 0.2617 → 0.2712 8 / 0
findutils 790 21 → 23 0.1079 → 0.1237 45 / 0
pooled 2,092 143 → 165 (+22, +15.4%) 0.2272 → 0.2501 (+10.1%) 137 / 3

coreutils (327 binaries × 2 arms ≈ 11 h on a shared box) was started and stopped; dash carries no DWARF ground truth in the frozen tree.

Classified sweep

decompile-all off vs on, 11 stripped binaries / 5,589 functions, function count identical in every one. 1,141 changed, every one classified:

n % what
471 41.3% the import's own thunk gains its signature
281 24.6% a cast removed because the callee's return is now typed
120 10.5% unsigned long replaced by a concrete type
116 10.2% variable renumbering / decl churn only
74 6.5% the function's own signature retyped
74 6.5% a call's arity restored to the declared signature
5 0.4% structuring churn
-void sub_6c53(unsigned long a0)              +void sub_6c53(char *a0)
   v1 = fputs_unlocked(a0,stdout);              v1 = fputs_unlocked(a0,stdout);
-  dat_33798 = *(unsigned int *)__errno_location();
+  dat_33798 = *__errno_location();

Wrongness, measured on two counts

  • Argument-count drift. 75 call sites had their arity restored to the declared signature (abort(a0,a2,0) → abort(), openat 0 → 4, reallocarray 0 → 3, getopt_long 4 → 5). The only 4 flagged as moving away sit in two functions (gzip-O2 sub_f900, coreutils-ls-O2ni sub_a550) that already render free(v43,v24[-8]), malloc(v10,v24[-8]), memcpy(…,v24[-8]) and strlen(v10,v4) — base-table names with one parameter — with this option OFF. A pre-existing frame-recovery defect in those functions, recorded as a follow-up.
  • Parameter specificity. 296 slots gained it, 2 lost it. Both losses are grep-O2ni Pexecute, char * → void *, where the loss is the truthful prototype: memchr/rawmemchr really do declare const void *.

Statically linked nuttx: 0 of 924 functions changed — the imports-only guard doing exactly its job. No-return annotations identical on every C binary (coreutils-sort abort 24→24 / exit 5→5 / __assert_fail 3→3, grep 28/7/8, openssh-scp error 10→10 / exit 39→39).

Speed, including load

The marginal cost is building and committing up to 206 more PrototypePieces at load, so load is the metric. Interleaved off/on, min and median of 21 pairs (kuna functions = load + the whole analysis pass list + commit, no body decompiled):

binary min median
coreutils-dircolors 293.6 → 289.4 ms (−1.45%) 321.6 → 320.7 (−0.28%)
openssh-scp 836.5 → 835.4 (−0.12%) 851.9 → 846.0 (−0.69%)
nuttx (static) 1423.4 → 1432.2 (+0.62%) 1465.9 → 1452.2 (−0.93%)
grep 849.9 → 695.4 (−18.18%) 1012.6 → 1014.9 (+0.23%)

The grep minimum is noise in both directions (an earlier 15-pair run of the same case reported +13.99%); the medians are the honest read. scripts.pipeline.timeit on grep main, 15 samples: 1547.61 → 1547.82 ms (+0.01%). Whole-binary decompile-all, interleaved min/median of 13: dircolors −0.29% / −0.22%, zlib minigzip +0.16% / +0.26%.

Worst stable delta +0.62%, budget 5%.

Option / DIV decision

Gated, default ON — --option libcsigs on|off. It changes emitted C in every dynamically linked C binary, and which signatures to assert is a judgment call rather than a mechanical bug fix, so "when in doubt, gate it" applies; off renders exactly what the 27-entry base table alone renders, which is the ablation hook the campaign needs. Default-ON is earned: 0/675 datatest assertions move (structurally — the datatest path cannot reach the analyzer tier), the speed budget is met with room, and the sweep shows 296 specificity gains against 2 losses. DIV-65 in docs/history.md.

Gate seam: the analysis COMMIT boundary (engine.rs::analysis_pass_enabled), same as cortexmvectors / fdeinterior / cppsig, because the producing pass runs at load file upstream of any option command.

Preset membership: deliberately NOT in AGGRESSIVE_OVERRIDES

#267's aggressive_carries_every_default_off_option invariant exists because auto resolves to aggressive under 500 KiB, so a default-OFF option absent from the preset ships inert on the default path — how itaniumrtti recovered 0 of 29 until it was caught. libcsigs ships ON, so it is out of that invariant's scope by construction. But I measured the liveness rather than assuming it — on dircolors (55,680 bytes, so auto → aggressive), default vs --option libcsigs off, whole-binary decompile-all:

mode functions differing cast-removal witness
(no --mode, i.e. auto) 57 of 184 yes
--mode aggressive 57 of 184 yes
--mode reliable 58 of 183 yes
--mode fast 58 of 184 yes

Live on every mode; no preset can silence it, since none turns anything off except fast's three discovery gates.

Adding ("libcsigs", "on") would be worse than redundant. AGGRESSIVE_OVERRIDES' own doc records that the preset owns an option it lists — "a user --option returndup off earlier on the command line is re-enabled by the preset". Every benchmark and sweep number above was produced by --option libcsigs off on sub-500 KiB binaries, i.e. straight through auto → aggressive. Preset membership would silently re-enable it there and destroy the ablation hook that is half the reason the flag exists. So no second DIV row for preset membership is needed; DIV-65 covers the default-ON decision alone.

Counters — derived from a capture, not from arithmetic

The rebase onto #267 auto-merged catalog_bytecompat.rs to 94 with no conflict, because #267 and this branch had each independently made the identical 93 -> 94 edit. The committed number was silently short by one. I re-derived by capturing phase_catalog.json from a fresh release build and counting it:

counter value how
settables 94 → 95 len() of the captured catalog; "option": / "tier": / "symptoms": occurrences all agree
tiers (core, transform, analysis) (20, 41, 33) → (20, 41, 34) tallied per row
catalog JSON rows 93 → 94 "},\n" occurrences, asserted == n - 1
docs/options.md 95 independent cross-check: ### \option`` headings

#267's observation holds: phase_catalog.json and docs/options.md merged line-by-line correctly and needed no fix — the trap is only in the hard-coded .rs counts. tests/stages/kuna-catalog.xml needed no edit either: its per-attribute assertions are ranges (use_when / change_kind 10..160) or counts of attributes this option does not carry (source_decompiler: angr, change_kind: structure-recovery / opt-in-tool); make test-stages confirms 400/400.

Tests

decompiler/crates/kuna-console/tests/verify_libcsigs.rs — 5 two-pass e2e assertions over the vendored fauxware fixture (the caller's unsigned long a0 → char *a0 from open; the fd unsigned int → int4 from open's return; the thunk's full int open(char *, int, ...) including the variadic tail; void exit(int4); and a function the table does not touch being byte-identical). Plus 5 hermetic table-invariant unit tests, including the FORTIFY argument slots and the imports-only rule.

No tests/stages/*.xml case: the XML datatest bootstrap builds its program from a <binaryimage> element and never runs the analyzer tier, so no kuna_analysis pass can fire there — the same reason verify_cppsig.rs / verify_cppproto.rs / verify_fdeinterior.rs exist.

Deliberately not here

  1. VARIADIC_SUBSTRINGS. formatstring/apply.rs matches by contains over {"printf","scanf"}, so __printf_chk is already treated as a format-string callee with the format at slot 0 when it is at slot 1. Adding the error/err/warn/syslog family there is a second, independent behaviour change — its own PR, its own measurement. Note this is a different bug from the sibling PR currently fixing formatstring being entirely inert on decompile-all (the override/re-decompile loop living only in the console path): that one is about the pass never running, this one about the pass mis-locating the format argument when it does. They should not be conflated.
  2. The sub_f900 / sub_a550 phantom trailing stack argument (pre-existing, visible on base-table names with this option off).
  3. A real header-derived type database carrying struct/enum layouts.

Rebased onto 2831e352 (#267 itaniumrtti, itself on #268 typedepth). Neither touches this path on the measured corpus: typedepth changes DWARF type resolution and itaniumrtti is ELF-with-Itanium-RTTI and default-off, while every benchmark and sweep binary here is stripped C. The A/B was re-run post-rebase on 5 of the 11 sweep binaries with an identical changed-function set (grep-O2ni 182 both before and after; nuttx still 0 changed).

Bundle: docs/features/libcsigs/ (analysis.md, plan.md, record.json).

🤖 Generated with Claude Code

https://claude.ai/code/session_01McQC7imaNfzj5k5AVumSYN

@mahaloz
mahaloz force-pushed the feat/libcsigs branch 2 times, most recently from 0b83ca5 to 623b706 Compare August 5, 2026 17:24
mahaloz and others added 3 commits August 5, 2026 17:30
…n, 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
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
…, 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
@mahaloz mahaloz changed the title [AUTOMATED] feat(p1): libcsigs - the measured libc signature extension (C type_match perfects 143 -> 165 over 2,092 functions, 137 improved / 3 worse) [AUTOMATED] feat(p1): libcsigs - the measured libc signature extension (C type_match perfects 143 -> 165 over 2,092 functions, 137 improved / 3 worse) (DIV-65) Aug 5, 2026
@mahaloz
mahaloz merged commit b96cc53 into main Aug 5, 2026
9 checks passed
@mahaloz
mahaloz deleted the feat/libcsigs branch August 5, 2026 17:47
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