Repository navigation
[AUTOMATED] fix(driver): dallparity - one decompile step, and formatstring becomes an opt-in on both surfaces (DIV-66) - #270
Merged
Merged
Conversation
…tring becomes an opt-in on both surfaces (DIV-66) Two defects, one root; the second only became visible once the first was fixed. (a) `kuna decompile-all` and the console `decompile` command did not decompile the same way for the same binary, address and mode -- and the whole-binary one was the weaker. That is the surface decbench, the browser front-end, `decompile-project` and every agent-facing workflow use, so every benchmark number kuna has reported was measured on it. `IfcDecompile` wrapped the engine drive in Ghidra's `FormatStringAnalyzer` half-B loop (decompile -> read the constant format string at each printf/scanf-family call's format-argument slot -> install the derived per-call-site prototype override -> decompile again) and enabled `readonlypropagate` for its duration; `project::decompile_targets` called the drive directly and did neither, so `--option formatstring on` was a silent no-op there. The scoped `readonlypropagate` flip is the larger of the two effects: it constant-folds every read-only load, so on ARM Cortex-M, where a global address arrives through a PC-relative literal pool, it rewrites most of a function body rather than just its printf call sites. Fixed by making the shared pipeline the single source of truth rather than copying the loop into a second place: a new `kuna-console/src/decompile_step.rs (decompile_one)` holds the drive call, the format-string loop and the scoped flip, and both `IfcDecompile` and `decompile_targets` go through it, each passing only the facts it has via one `DecompileSeed`. Discovered call-site overrides are returned rather than stashed globally -- persisting them across functions would make a whole-binary run order-dependent and would itself be a new divergence. (b) Honouring the option exposed what it costs: a caller whose call sites yield an override is decompiled twice, measured at +43% to +75% on a printf-heavy whole binary -- an order of magnitude over the 5% budget. Attribution puts 100% of it in the second decompile (the read-only propagation is free), and the naive redundant-override skip was built, instrumented and rejected: it moved crontab's re-decompiled-function count 25 -> 24 while changing emitted C on 12 of 15,990 functions. Standing requirement 4 therefore applies: `formatstring` is removed from `AGGRESSIVE_OVERRIDES` and entered in `modes.rs`'s enforced `EXCLUDED_ON_PURPOSE` list with its reason. It was already default-off as an option; only the preset made it effectively on, and only on the one surface that ran the loop. The shipped default's emitted C is unchanged (0 differences over 15,990 functions) and its speed is unchanged (worst +0.16%), while both surfaces now deliver the same C when the option is given. Driver-tier: no new `--option`, no `phases.toml` row, no catalog counters. 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 25, 2026
…ymbolnamerepair backstops the rest (DIV-88) (#335) kuna could not load an unstripped C++ binary that uses an anonymous namespace -- at all, by any command. `Database::find_create_scope_from_symbol_name` nests one Scope per `::` component and `attach_scope` rejects an EMPTY one. The symbol table is installed inside `load file`, so that `LowlevelError` escapes `bootstrap_from_object` rather than costing one symbol: `decompile-all`, `functions` and `decompile-project` all answered `could not build an architecture for <binary>: Non-global scope has empty name` and emitted nothing. The empty component came from the name-only reduction. Itanium renders `_GLOBAL__N_...` as `(anonymous namespace)`, `strip_bracket_groups` deletes every balanced bracket group, and `leveldb::(anonymous namespace)::HandleDumpCommand` therefore reduced to `leveldb::::HandleDumpCommand`. An anonymous namespace is the ordinary way C++ gives a definition internal linkage, so this was most unstripped C++, not an exotic input. Diagnosed during the #270 leveldb work and recorded there as out of scope; this closes it. Two independent parts: 1. No flag (a strict fix). `name_anonymous_namespaces` rewrites both spellings -- Itanium `(anonymous namespace)` and MSVC `` `anonymous namespace' `` -- to the identifier `anonymous_namespace` BEFORE the bracket strip, matching what `sanitize_class_name` already gives the same construct. The identifier spelling is forced, not cosmetic: `load function` splits its argument on whitespace, so a name with a space is unaddressable from the CLI, the console and every stage XML; and a scope name reaches emitted C unsanitized, where `(` opens a parameter list. `demangle_raw` keeps the faithful c++filt text, unrewritten. 2. `symbolnamerepair` (on|off, default on). A name can be degenerate with no demangler involved, and symbol-name bytes are attacker-controlled data that no header check validates -- a hostile binary buys a total denial of analysis for a few `.strtab` bytes, which matters given the reporting binary was malware. Only the empty component is treated as degenerate. Loader-tier, so the gate is the `KUNA_SYMBOLNAMEREPAIR` env bridge (the `relocrebase` pattern), exported by both CLI surfaces; off restores the hard error, which is what someone investigating a binary's symbol table itself wants. Collateral on the Itanium/ELF world is zero and structurally so: on a binary with no `::`-qualified and no mangled symbol neither path executes. `decompile-all --json` is byte-identical on 8 real binaries, four of them C++. The one deliberate output change on a binary that already loaded is the MSVC arm (`` `anonymous namespace'::Bar::foo `` -> `anonymous_namespace::Bar::foo`); the old spelling is not valid C, so it only ever corrects wrong output. Witnesses that go from zero output to full output: the reporting `native_payload.dll` (MinGW PE32+, 1184 `_GLOBAL__N_` symbols) now exports 4061 of 4064 functions in 92.3 s; `libleveldb.so.1.23.0` 3751 functions / 273 `anonymous_namespace::` names; `leveldbutil` 58 / 7. Speed: interleaved min-of-9 `decompile-all --json` on grep, +0.75%, inside the box's measured noise floor (a null A/B of the same binary against itself spreads 0.91 s over 9 reps). Tests: `tests/stages/kuna-symbolnamerepair.xml` (6 assertions over the new `anon_namespace_x86_64` fixture, pinning all three anonymous-namespace shapes, the call-site rendering, and a min=0 max=0 guard that no `::::` survives) plus `kuna-console/tests/verify_symbolnamerepair.rs` (two-pass: the anonymous-namespace fixture loads with the backstop forced OFF, proving the two parts are independent; `hostile_scope_x86_64` -- a 4.7 KB ELF whose `.symtab` names a function `a::::b`, built reproducibly from checked-in assembly -- loads on and restores the exact error off), four demangle unit tests and the gate's own env-token test. Claude-Session: https://claude.ai/code/session_011FPeR8e2Bhv3Hm8gux8RXb Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
mahaloz
added a commit
to phix33/kuna
that referenced
this pull request
Aug 27, 2026
…e verdict (DIV-89) Review amendments to the broken-pipe fix. The core of it is right and verified: every stdout print site in kuna-cli now renders into a string and goes through the fallible boundary, and across 24 command invocations the output is byte-identical to the parent commit in stdout, stderr AND exit code. Three things needed correcting before it lands. 1. A broken pipe was collapsing every exit code to 0, which converts a false red into a false green. `kuna test` against a REGRESSED baseline exited 0 once its reader closed, and `kuna decompile` lost both the exit 1 and the `error: ...` line of the DIV-45 failure contract. The write failed because nobody was reading, which is orthogonal to whether the work succeeded, and stderr is still open -- so `error_status(err)` becomes `status_after(err, status)`: BrokenPipe keeps the verdict the command reached, anything else still reports and forces 1. decompile.rs reports and returns its failure whether or not stdout survived, emitting first so the stdout-then-stderr order is unchanged. 2. `kuna specs` had been switched from `.status()` to `.output()`, which turned a streaming passthrough into a captured one: a 148-spec run went silent for 17.2s and then printed all 1004 stderr lines ahead of all 149 stdout lines -- detaching 615 warnings that carry no filename from the `Compiling <spec>:` line that was their only attribution. It now streams the child's stdout through the same boundary with stderr left inherited, so the interleaving matches the old passthrough (time-to-first-line 17.2s -> 0.01s) and `kuna specs | head` still exits quietly. Past a write failure the reads continue to EOF so slacomp finishes its .sla files instead of dying on EPIPE. 3. The repo requires a DIV row and owning-spec prose for a driver-tier behavior change (cf. DIV-66 Noelo-Lab#270, DIV-68 Noelo-Lab#277): adds DIV-89, the stdout-boundary section in docs/spec/00-overview.md beside the DIV-45 arm it qualifies, and reconciles the docs/cli.md paragraph with the exit-code contract 60 lines below it. Tests: broken_pipe.rs gains the immediate-close case pinning that a REGRESSED parity run still exits 1 (exit 0 before this commit, 1 after), plus unit coverage of status_after; both file headers added. The two tests already here fail on main with exit 101, so the suite is a real regression net in both directions. All four gates green: make test PARITY OK, make test-stages PARITY OK, make check-spec OK (strict too), make rust-test green. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01GgH79MoS51D7LX3J5WpoRd
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.
Summary
Two defects, one root, and the second only became visible once the first was fixed.
(a)
kuna decompileandkuna decompile-alldid not produce the same C for the samebinary, address and mode — and the whole-binary one was the weaker. That is the surface
decbench, the browser front-end,
decompile-projectand every agent-facing workflow use, soevery benchmark number kuna has reported was measured on it.
(b) Honouring the option exposed that it misses the speed budget by an order of
magnitude, so
formatstringleaves theaggressivepreset and becomes a per-run opt-in onevery surface — standing requirement 4's prescribed outcome. The shipped default's
emitted C is unchanged and its speed is unchanged (worst +0.16%); the capability is one
flag away, and now actually works on both surfaces.
IDA Pro 9.2 renders
void error(const char *a1)here.Mechanism (verified, not assumed)
IfcDecompilewrappeddecompile_func_full_with_override_dynin Ghidra'sFormatStringAnalyzerhalf-B loop — decompile, walk theCALLops, read the constant formatstring at each printf/scanf-family call's format-argument slot, install the derived
per-call-site
PrototypePiecesoverride, decompile a second time — and enabledreadonlypropagatefor the duration.project::decompile_targetscalled the drive directlyand did neither.
The scoped
readonlypropagateflip is the larger of the two effects, and was not in theoriginal report. It constant-folds every read-only load, not just the format constant. On
ARM Cortex-M, where a global address arrives through a literal pool, it rewrites most of a
function body:
Full enumeration of divergence classes
182
(binary, mode, address)records over 13 binaries (C and C++, stripped and unstripped,O0 and O2, x86-64 executable + shared library + ARM Cortex-M firmware) ×
auto/reliable/fast,kuna decompile --addr X --mode Mvskuna decompile-all --addr X --mode M,normalizing only the function name.
decompilereadonlypropagatenever applies (dominant; ARM literal pools)decompilefuncstart_patterns on+aif oninjected for non-x86-64decompile-all--max-fn-seconds)decompile(unbudgeted)fd.get_size()vs unbounded)--addrmap addr,parse line extern,map hash,override …)decompileprint raw/--regionsClasses 1–2 are one root cause. 3–4 are deliberate whole-binary policy, left alone. 5–8 are
not divergences — and the 0/182 residual confirms it.
13 of 182 divergent before, 0 after. Re-run with
--option formatstring onforced onboth surfaces — the load-bearing case now that the preset no longer sets it — also
0 of 182. The pre-fix divergence was confined to
auto(which resolved toaggressive):reliableandfastwere already 0/14 each, which is itself the proof that this one featurewas the whole divergence. Worst-hit: ARM
CMSIS_DAP.axfat 8 of 14.The fix
One shared per-function step,
kuna-console/src/decompile_step.rs (decompile_one), holdingthe drive call, the format-string loop and the scoped
readonlypropagateflip. BothIfcDecompileanddecompile_targetsgo through it, each passing only the facts it has viaone
DecompileSeed. The shared pipeline is the single source of truth, not a second copy ofthe loop — the divergence existed because there were two call sites, so the fix leaves one.
Discovered call-site overrides are returned, not stashed globally: the console persists
them for a later re-decompile of the same function; the whole-binary loop drops them, because
persisting them across functions would make a whole-binary run order-dependent and would
itself be a new divergence.
Speed, and why
formatstringis now an opt-inThe shipped default is free — measured, not assumed
Default vs an explicit
--option formatstring off(both disable the loop), interleaved,minimum of 13 pairs:
Worst +0.16%, including the large
tar(1,570 functions, 24 s). And the default'soutput is byte-identical to explicit-off over 15,990 functions / 33 cases, 0
differences — which, combined with the pre-rebase measurement that the
formatstring offarm is byte-identical to the genuine pre-fix binary over the same 15,990 functions
(0 differences), means this PR changes no default output at all.
The opt-in price is why it left the preset
--option formatstring on(ms)Worst +75.46% against a 5% budget — an order of magnitude over. Standing
requirement 4: over
KUNA_PIPELINE_SPEED_BUDGET_PCT⇒ default-OFF opt-in. Soformatstringis removed from
AGGRESSIVE_OVERRIDESand entered inmodes.rs'sEXCLUDED_ON_PURPOSEwithits reason, alongside
v850indirectbranchanddwarf_lines. That list is enforced: theaggressive_carries_every_default_off_optioninvariant makes an unlisted default-off option abuild failure. Its shipped option default was already
off— only the preset made iteffectively on, and (before this PR) only on the one surface that ran the loop. So this also
stops
kuna decompilebeing charged for a featuredecompile-allnever delivered.The optimization was implemented, measured, and rejected
Declining an override whose format-derived types already equal the call's argument types, so
the caller need not be decompiled twice. Instrumented:
It buys ~nothing — the redundant overrides sit in the same functions as real ones, so the
caller re-decompiles anyway — and it changed emitted C on 12 of 15,990 functions, breaking
the parity this PR exists for. Reverted.
The instrumented rates also explain the magnitude: only 15% / 5% / 10% of functions
re-decompile on crontab / psktool / gzip. They simply carry most of the decompile time,
because a printf-heavy function is a big function. A third timing arm confirms where the cost
sits:
formatstring off+ upstreamreadonly onis free (crontab +1.15%, psktool −0.14%,gzip +0.08%), so 100% of the cost is the second decompile, not the read-only propagation.
Making that cheap is real work on the
formatstringoption and is the precondition for everputting it back in the preset — recorded as follow-up 1.
Gates
make testmake test-stagesmake rust-testmake check-speckuna catalog --checkShared counters, re-derived from the built artifact
Rebased onto
b96cc531(#269). This PR adds no option, so 95 is main's number carried throughunchanged — but read off the build rather than reasoned about, because this queue has
auto-merged the identical off-by-one three times:
kuna catalog --jsoncatalog_bytecompat.rskuna_phases/tests.rsphase_catalog.jsondocs/options.md(###sections)docs/options.mdvs a freshkuna catalog --markdownClassified sweep
Shipped default: no change (0 differences over 15,990 functions, above).
Under the opt-in, the same 33-case / 15,990-function
decompile-allsweep changes 1,824 bodies with 0 entriesadded or removed; hunk classes {'signature': 112, 'body-only': 469, 'dat-count-change': 1278, 'sig:ulong->charp': 23, 'shorter': 447, 'longer': 74, 'new-string-literal': 398}. Every hunk is one of exactly two intended
kinds: an
unsigned long→char *at a printf/scanf call (the varargs typing), or aread-only load constant-folding —
dat_<hex>collapsing to a resolved global or a stringliteral — which dominates on ARM. Largest: O0/crazyflie/stripped/cf2.elf [auto] (1523), O0/crazyflie/stripped/CMSIS_DAP.axf [auto] (177), O0/cronie/stripped/crontab [auto] (23), O0/bzip2/stripped/bzip2 [auto] (22), O0/gzip/stripped/gzip [auto] (19), O0/sysvinit/stripped/init [auto] (8), O0/zlib/stripped/minigzip [auto] (7), O0/zlib/stripped/minigzip [aggressive] (7).
Benchmark delta
0 by default. Opted in — decbench
origin/main@325046f(cache_version5,DECBENCH_NO_CACHE=1), both arms re-decompiled and re-scored against the same source CFGs:gedtype_matchgedtype_matchgedtype_matchtype_matchperfects 80 → 88 of 1,133 (29 improved, 10 regressed);GED 4 improved / 0 regressed of 1,168. The
type_matchregressions are theformatstringfeature's own known cost — a%cargument typeduint1where the C variadicpromotion makes the parameter an
int, and a format-derived width narrowing a recovereduLong— whichkuna decompilehas always produced.Option / DIV decision
Driver-tier: no new
--option, nophases.tomlrow, no catalog counters — the change isinside
kuna-console's driver seam plus one preset entry, andformatstringis already theswitch. DIV row +
docs/spec/touch + Rust integration tests, the shape PR #262 established.DIV-66 (63 → #268, 64 → #267, 65 → #269 while this was in flight; max re-checked on the
rebased tree).
No stage XML: every
tests/datatests/tests/stagesfile is an XML<binaryimage>whosebootstrap never produces an
AnalysisOutput, so an analysis-tier option cannot be reachedfrom there. Gated instead by
verify_decompile_all_parity.rs— three assertions over the fourvendored
fmt_<arch>fixtures (including the ARM literal-pool case): the two-pass shape onthe whole-binary surface, plus byte-identical output between the two surfaces in both option
states.
Second finding — separate root cause, its own PR
Non-global scope has empty nameis not a divergence: both surfaces fail identically atload file, in a different crate. Not folded in.strip_bracket_groups(kuna-analysis/src/analyzers/demangle/mod.rs) deletes every balanced(...)group, soleveldb::(anonymous namespace)::HandleDumpCommandreduces toleveldb::::HandleDumpCommand;Database::find_create_scope_from_symbol_namesplits onevery
::andattach_scoperejects the empty component, abortingload filefor theentire binary. 8 such symbols in
leveldbutil; reproduces onlibleveldb.so.1.23.0.Pre-existing (the loader-tier demangler predates #262–#266), invisible because decbench scores
the stripped binaries.
A sibling agent hit the same demangler weakness from the other side: an anonymous
namespace's typeinfo name is
*-prefixed per Itanium ABI §2.9.1 and was undemangleable — andanonymous namespaces are how most C++ spells a concrete implementation. Whoever takes this
should fix the shared root (how the demangler represents an anonymous namespace) rather than
either symptom. Two candidate directions: spell the group instead of deleting it (Ghidra
renders
(anonymous namespace)), and/or make the scope splitter skip empty components so nodemangled string can ever abort a load again.
Files
decompiler/crates/kuna-console/src/decompile_step.rs(new — the shared step)decompiler/crates/kuna-console/src/{ifacedecomp,project,lib}.rs,decompiler/crates/kuna-cli/src/decompile_all.rsdecompiler/crates/kuna-decomp/src/p0_knowledge/modes.rs(preset + enforced exclusion list)decompiler/crates/kuna-console/tests/verify_decompile_all_parity.rs(new)docs/history.md(DIV-66),docs/spec/00-overview.md,docs/spec/01-program-prep.md,docs/modes.md,docs/features/dallparity/{analysis,plan,record.json}Do not merge without review.