Skip to content

[AUTOMATED] fix(driver): dallparity - one decompile step, and formatstring becomes an opt-in on both surfaces (DIV-66) - #270

Merged
mahaloz merged 1 commit into
mainfrom
fix/dallparity
Aug 5, 2026
Merged

mahaloz merged 1 commit into
mainfrom
fix/dallparity

Conversation

@mahaloz

@mahaloz mahaloz commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Two defects, one root, and the second only became visible once the first was fixed.

(a) kuna decompile and kuna decompile-all did not produce the same C 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.

(b) Honouring the option exposed that it misses the speed budget by an order of
magnitude
, so formatstring leaves the aggressive preset and becomes a per-run opt-in on
every 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.

$ kuna decompile      O0/zlib/stripped/minigzip --addr 0x14c9 --option formatstring on
void error(char *a0)                       # correct
$ kuna decompile-all  O0/zlib/stripped/minigzip --addr 0x14c9 --option formatstring on
void error(unsigned long a0)               # BEFORE: the option was a silent no-op
void error(char *a0)                       # AFTER

IDA Pro 9.2 renders void error(const char *a1) here.

Mechanism (verified, not assumed)

IfcDecompile wrapped decompile_func_full_with_override_dyn in Ghidra's
FormatStringAnalyzer half-B loop — decompile, walk the CALL ops, read the constant format
string at each printf/scanf-family call's format-argument slot, install the derived
per-call-site PrototypePieces override, decompile a second time — and enabled
readonlypropagate for the duration. project::decompile_targets called the drive directly
and did neither.

The scoped readonlypropagate flip is the larger of the two effects, and was not in the
original 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:

-  *(unsigned int *)(dat_14001c5c + 0x204) = 0x200;   // decompile-all
+  v1 = dat_10003af8;                                 // decompile
-  sub_140053aa(a1,dat_140013fc,6);
+  sub_140053aa(a1,"1.2.0",6);

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 M vs kuna decompile-all --addr X --mode M,
normalizing only the function name.

# Class Stronger side Verdict
1 format-string varargs typing loop never runs on the whole-binary surface decompile fixed
2 the loop's scoped readonlypropagate never applies (dominant; ARM literal pools) decompile fixed
3 funcstart_patterns on + aif on injected for non-x86-64 decompile-all intentional, documented (DIV-20); discovery-tier
4 per-function watchdog (--max-fn-seconds) decompile (unbudgeted) intentional driver policy (spec §0.2)
5 flow-extent bound (fd.get_size() vs unbounded) — equivalent; 0 residual
6 function naming under --addr — 0 name differences
7 console-seeded facts (map addr, parse line extern, map hash, override …) decompile unreachable from either CLI
8 print raw / --regions — output-format surface

Classes 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 on forced on
both 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 to aggressive):
reliable and fast were already 0/14 each, which is itself the proof that this one feature
was the whole divergence. Worst-hit: ARM CMSIS_DAP.axf at 8 of 14.

The fix

One shared per-function step, kuna-console/src/decompile_step.rs (decompile_one), holding
the drive call, the format-string loop and the scoped readonlypropagate flip. Both
IfcDecompile and decompile_targets go through it, each passing only the facts it has via
one DecompileSeed. The shared pipeline is the single source of truth, not a second copy of
the 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 formatstring is now an opt-in

The shipped default is free — measured, not assumed

Default vs an explicit --option formatstring off (both disable the loop), interleaved,
minimum of 13 pairs:

case off (ms) default (ms) delta
crontab-O0 1,626.9 1,625.1 -0.11%
psktool-O0 330.1 330.6 +0.16%
gzip-O0 2,700.0 2,699.5 -0.02%
minigzip-O0 4,947.7 4,955.6 +0.16%
CMSIS_DAP.axf ARM 2,503.1 2,503.7 +0.02%
tar-O0 (1570 fns, large) 24,228.9 24,238.1 +0.04%
b2sum-O0 5,302.8 5,303.6 +0.02%

Worst +0.16%, including the large tar (1,570 functions, 24 s). And the default's
output is byte-identical to explicit-off over 15,990 functions / 33 cases, 0
differences
— which, combined with the pre-rebase measurement that the formatstring off
arm 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

case off (ms) --option formatstring on (ms) delta
crontab-O0 1,632.1 2,863.7 +75.46%
psktool-O0 331.5 505.7 +52.54%
gzip-O0 2,713.6 3,884.1 +43.13%
tar-O0 (1570 fns, large) 24,352.2 28,067.0 +15.25%
CMSIS_DAP.axf ARM 2,513.9 2,653.6 +5.56%
b2sum-O0 5,433.7 5,633.7 +3.68%
minigzip-O0 4,986.9 5,081.2 +1.89%

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. So formatstring
is removed from AGGRESSIVE_OVERRIDES and entered in modes.rs's EXCLUDED_ON_PURPOSE with
its reason, alongside v850indirectbranch and dwarf_lines. That list is enforced: the
aggressive_carries_every_default_off_option invariant makes an unlisted default-off option a
build failure. Its shipped option default was already off — only the preset made it
effectively on, and (before this PR) only on the one surface that ran the loop. So this also
stops kuna decompile being charged for a feature decompile-all never 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:

binary functions re-decompiled with the skip redundant overrides dropped
crontab 160 25 24 12
psktool 57 5 3 9
gzip 248 25 25 8

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 + upstream readonly on is 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 formatstring option and is the precondition for ever
putting it back in the preset — recorded as follow-up 1.

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 — 4,535 passed / 0 failed / 37 ignored
make check-spec OK (lenient and strict)
kuna catalog --check catalog OK

Shared counters, re-derived from the built artifact

Rebased onto b96cc531 (#269). This PR adds no option, so 95 is main's number carried through
unchanged — but read off the build rather than reasoned about, because this queue has
auto-merged the identical off-by-one three times:

source count
live kuna catalog --json 95
catalog_bytecompat.rs 95
kuna_phases/tests.rs 95
phase_catalog.json 95
docs/options.md (### sections) 95
docs/options.md vs a fresh kuna catalog --markdown byte-identical

Classified sweep

Shipped default: no change (0 differences over 15,990 functions, above).

Under the opt-in, the same 33-case / 15,990-function
decompile-all sweep changes 1,824 bodies with 0 entries
added 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 a
read-only load constant-folding — dat_<hex> collapsing to a resolved global or a string
literal — 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_version 5,
DECBENCH_NO_CACHE=1), both arms re-decompiled and re-scored against the same source CFGs:

project metric n perfect mean improved regressed
zlib ged 774 315 -> 315 6.2132 -> 6.2132 0 0
zlib type_match 764 62 -> 65 0.3478 -> 0.3498 3 6
cronie ged 199 73 -> 73 9.8844 -> 7.8241 4 0
cronie type_match 184 11 -> 13 0.3315 -> 0.3633 14 0
sysvinit ged 195 70 -> 70 7.0359 -> 7.0359 0 0
sysvinit type_match 185 7 -> 10 0.3657 -> 0.3822 12 4

type_match perfects 80 → 88 of 1,133 (29 improved, 10 regressed);
GED 4 improved / 0 regressed of 1,168.
The type_match regressions are the
formatstring feature's own known cost — a %c argument typed uint1 where the C variadic
promotion makes the parameter an int, and a format-derived width narrowing a recovered
uLong — which kuna decompile has always produced.

Option / DIV decision

Driver-tier: no new --option, no phases.toml row, no catalog counters — the change is
inside kuna-console's driver seam plus one preset entry, and formatstring is already the
switch. 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/stages file is an XML <binaryimage> whose
bootstrap never produces an AnalysisOutput, so an analysis-tier option cannot be reached
from there. Gated instead by verify_decompile_all_parity.rs — three assertions over the four
vendored fmt_<arch> fixtures (including the ARM literal-pool case): the two-pass shape on
the 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 name is not a divergence: both surfaces fail identically at
load file, in a different crate. Not folded in.

strip_bracket_groups (kuna-analysis/src/analyzers/demangle/mod.rs) deletes every balanced
(...) group, so leveldb::(anonymous namespace)::HandleDumpCommand reduces to
leveldb::::HandleDumpCommand; Database::find_create_scope_from_symbol_name splits on
every :: and attach_scope rejects the empty component, aborting load file for the
entire binary. 8 such symbols in leveldbutil; reproduces on libleveldb.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 — and
anonymous 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 no
demangled 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.rs
  • decompiler/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.

…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 mahaloz changed the title [AUTOMATED] fix(driver): dallparity - one decompile step, so decompile-all stops being the weaker surface (DIV-64) [AUTOMATED] fix(driver): dallparity - one decompile step, and formatstring becomes an opt-in on both surfaces (DIV-66) Aug 5, 2026
@mahaloz
mahaloz merged commit 2755028 into main Aug 5, 2026
9 checks passed
@mahaloz
mahaloz deleted the fix/dallparity branch August 5, 2026 19:13
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
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