Repository navigation
[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
Conversation
mahaloz
force-pushed
the
feat/libcsigs
branch
2 times, most recently
from
August 5, 2026 17:24
0b83ca5 to
623b706
Compare
…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
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 finding
kuna-analysis/src/analyzers/protos/mod.rscarries 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.gdtdata-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.mdclassifies 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 Ctype_matchand 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:/usr/includewould make kuna's output depend on the build host's libc — a kuna built on musl, or on a glibc with a different_FORTIFY_SOURCEdefault, would emit different C for the same binary. It also cannot cover the three groups that have no header prototype (__stack_chk_fail, the*_chkbuiltins, 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.struct stat *stops beingvoid *) 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:
objdump -dover the 547 C binaries carrying a scored case → a PLT call-site histogram (1,930 distinct imports).type_matchcases 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:
exiterrorgettextstrncasecmp__errno_locationopenstrcasecmpstrerrorclosedcgettext__stack_chk_fail__fprintf_chkTwo measured negatives worth recording: the
err/warn/errxfamily the brief suggested does not appear in this corpus at all (warnx12 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 longwas merely uninformative.NC-line prototypesgcc -aux-infoemits over a TU including the platform headers with_GNU_SOURCE+_FORTIFY_SOURCE=2.__isoc99_{scanf,sscanf,fscanf}from the__REDIRECTat/usr/include/stdio.h:434-441, which is the header proving them ABI-identical to the names they replace.mem/str_chkfamily 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_failfrom glibcdebug/stack_chk_fail.c.man 3as a cross-check; all matched.Rejected rather than approximated.
Tyhas 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.strtollis the one that mattered — an earlier reducer classifiedlong long intas a 4-byte integer and would have shippedint 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.
readelfover all 677 binaries of the frozenO0/O2/O2-noinlinetrees found exactly one real collision outside NuttX (which implements the genuine POSIX API anyway):So an entry here applies only to a name the image imports and does not itself define. A PLT/IAT import named
erroris 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_chktakes a leadingint flagso the format sits at slot 1;__fprintf_chkaFILE *then a flag. Treating either as its namesake would shift every argument of the most frequent call in the C corpus.Gates
make testmake test-stagesmake rust-testmake check-spec--strict)kuna catalog --checkStructural: the XML
<binaryimage>datatest bootstrap never runs the analyzer tier, so it cannot reach this pass.Measured C
type_matchdeltadecbench
origin/main@325046f,DECBENCH_NO_CACHE=1, all three optimisation levels, option off vs on:coreutils(327 binaries × 2 arms ≈ 11 h on a shared box) was started and stopped;dashcarries no DWARF ground truth in the frozen tree.Classified sweep
decompile-alloff vs on, 11 stripped binaries / 5,589 functions, function count identical in every one. 1,141 changed, every one classified:unsigned longreplaced by a concrete typeWrongness, measured on two counts
abort(a0,a2,0)→abort(),openat0 → 4,reallocarray0 → 3,getopt_long4 → 5). The only 4 flagged as moving away sit in two functions (gzip-O2 sub_f900,coreutils-ls-O2ni sub_a550) that already renderfree(v43,v24[-8]),malloc(v10,v24[-8]),memcpy(…,v24[-8])andstrlen(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.Pexecute,char *→void *, where the loss is the truthful prototype:memchr/rawmemchrreally do declareconst 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-sortabort24→24 /exit5→5 /__assert_fail3→3, grep 28/7/8, openssh-scperror10→10 /exit39→39).Speed, including load
The marginal cost is building and committing up to 206 more
PrototypePiecesat 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):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.timeiton grepmain, 15 samples: 1547.61 → 1547.82 ms (+0.01%). Whole-binarydecompile-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;offrenders 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 indocs/history.md.Gate seam: the analysis COMMIT boundary (
engine.rs::analysis_pass_enabled), same ascortexmvectors/fdeinterior/cppsig, because the producing pass runs atload fileupstream of anyoptioncommand.Preset membership: deliberately NOT in
AGGRESSIVE_OVERRIDES#267's
aggressive_carries_every_default_off_optioninvariant exists becauseautoresolves toaggressiveunder 500 KiB, so a default-OFF option absent from the preset ships inert on the default path — howitaniumrttirecovered 0 of 29 until it was caught.libcsigsships ON, so it is out of that invariant's scope by construction. But I measured the liveness rather than assuming it — ondircolors(55,680 bytes, soauto→aggressive), default vs--option libcsigs off, whole-binarydecompile-all:--mode, i.e.auto)--mode aggressive--mode reliable--mode fastLive 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 offearlier on the command line is re-enabled by the preset". Every benchmark and sweep number above was produced by--option libcsigs offon sub-500 KiB binaries, i.e. straight throughauto→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.rsto 94 with no conflict, because #267 and this branch had each independently made the identical93 -> 94edit. The committed number was silently short by one. I re-derived by capturingphase_catalog.jsonfrom a fresh release build and counting it:len()of the captured catalog;"option":/"tier":/"symptoms":occurrences all agree"},\n"occurrences, asserted== n - 1docs/options.md### \option`` headings#267's observation holds:
phase_catalog.jsonanddocs/options.mdmerged line-by-line correctly and needed no fix — the trap is only in the hard-coded.rscounts.tests/stages/kuna-catalog.xmlneeded no edit either: its per-attribute assertions are ranges (use_when/change_kind10..160) or counts of attributes this option does not carry (source_decompiler: angr,change_kind: structure-recovery/opt-in-tool);make test-stagesconfirms 400/400.Tests
decompiler/crates/kuna-console/tests/verify_libcsigs.rs— 5 two-pass e2e assertions over the vendoredfauxwarefixture (the caller'sunsigned long a0→char *a0fromopen; the fdunsigned int→int4fromopen's return; the thunk's fullint 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/*.xmlcase: the XML datatest bootstrap builds its program from a<binaryimage>element and never runs the analyzer tier, so nokuna_analysispass can fire there — the same reasonverify_cppsig.rs/verify_cppproto.rs/verify_fdeinterior.rsexist.Deliberately not here
VARIADIC_SUBSTRINGS.formatstring/apply.rsmatches bycontainsover{"printf","scanf"}, so__printf_chkis already treated as a format-string callee with the format at slot 0 when it is at slot 1. Adding theerror/err/warn/syslogfamily there is a second, independent behaviour change — its own PR, its own measurement. Note this is a different bug from the sibling PR currently fixingformatstringbeing entirely inert ondecompile-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.sub_f900/sub_a550phantom trailing stack argument (pre-existing, visible on base-table names with this option off).Rebased onto
2831e352(#267itaniumrtti, itself on #268typedepth). Neither touches this path on the measured corpus:typedepthchanges DWARF type resolution anditaniumrttiis 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