Repository navigation
[AUTOMATED] fix(p2): (NOVEL) drop ARM ISA-mode bookkeeping from emitted C - #231
Merged
Merged
Conversation
…ed C On ARM/Thumb targets kuna emitted `setISAMode(1);` as a real statement -- a SLEIGH user-op that exists only to tell the lifter which instruction set to decode, naming a function that does not exist. It appeared only inside blocks reachable through a recovered jump table; ghidra and ida emit nothing there, and kuna itself emitted nothing for the same instruction when the block was reached by ordinary fall-thru. Root cause is in P2 lift/flow, not P9. Thumb-2 `bl` and `tbb`/`tbh` lower through SLEIGH `SetThumbMode(1)` -> `setISAMode(TB)`, raising a CALLOTHER; `ARM.cspec:307` declares the `<callotherfixup>` that erases it, and `xref_control_flow` queues every injected-userop CALLOTHER onto `injectlist` the moment the instruction is decoded. But the drain ran exactly once, at the end of `generate_ops` -- before jump-table recovery. `generate_ops_with_jumptables` then seeded each table target and re-drained `addrlist` through `fallthru()`, queueing the newly discovered blocks' CALLOTHERs, and nothing drained that second batch; `inject_pcode` clears `injectlist` on exit, so they were discarded and the raw CALLOTHER survived to P9. Upstream Ghidra drains the inject list on every round of the outer jump-table loop (flow.cc:819); the port had the inner `while` but not the outer `do/while` tail. Restoring it is the whole fix -- `inject_pcode` was already re-entrant. Fixed at the drain rather than suppressed at P9: a printer suppression would hide the statement while leaving an un-injected CALLOTHER in the IR for every other consumer, including `early_jump_table_fail`, whose only failing arm is the uninjected-CALLOTHER classification. Strict bug fix, no option: the processor cspec -- not kuna -- declares the user-op must be replaced by a NOP, kuna already honoured that for every fall-thru-discovered block (in betaflight, 4,091 functions make a call and only 168 leaked; in libopencm3 `sdram.elf` `main` the entry block's calls were clean while its 23 table-reached ones were not), and the emitted C named a nonexistent function. No DIV row: the registry records divergences from upstream defaults and this removes one. Measured over every ARM binary in the decbench corpus (98 targets, `decompile-all --json --mode reliable`): `setISAMode` statements 21,955 -> 0 across 1,499 -> 0 functions, with functions enumerated unchanged at 56,535 (betaflight 5797 -> 5797 / 6388 -> 6388), so discovery and the Thumb paint are untouched. Cross-checking the emitted C against every declared `<callotherfixup>` targetop in the vendored cspecs finds exactly one leaker, so this closes the class; the ~8,800 other user-op call sites (`DataMemoryBarrier`, the `coprocessor_*` family) have no declared eraser and ghidra prints them too. Downstream change is small and all shrinkage: betaflight 107 of 6,388 functions gain a dead-`lr` declaration removal or an expression propagation the CALLOTHER had blocked, 146,936 -> 146,389 non-`setISAMode` lines. Speed within budget (median of 3, interleaved): betaflight -3.56%, lcd-dma +2.28%, adc-dac-printf +2.00%, cf2 -1.61%; the two 98-binary corpus sweeps 978.3 s -> 961.9 s (-1.68%). Gates: test 675/675 PARITY OK (docs/baseline.json untouched), test-stages 309/309 PARITY OK, rust-test green, check-spec green, catalog --check green. Regression coverage: tests/stages/ghdec-isamode-inject.xml over a real `load file -> load function -> decompile -> print C` path on a new 1,304-byte linked ARM Thumb fixture (arm_thumb_switch_le32, source vendored, built in the kuna-dev container) whose `dispatch` is a `tbb [pc,r0]` with eight table-reachable case blocks. With the fix reverted it fails on eight `setISAMode(1);`; its three flow-integrity assertions pass in both states, so a "fix" that dropped table flow instead of injecting into it could not sneak through. inspiration = "decbench:O2-noinline-betaflight-betaflight_STM32F405-accDetect + O0-libopencm3-sdram-main; NOVEL pool" Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_011RXVU58TKJxb518oViChwo
# Conflicts: # decompiler/crates/kuna-base/src/xml.rs # docs/baseline-stages.json # tests/stages/README.md
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
On ARM/Thumb targets kuna emitted
setISAMode(1);as a real statement in thedecompiled body.
setISAModeis a SLEIGH user-op that exists only to tell thelifter which instruction set to decode; it corresponds to nothing in the source,
and
ARM.cspec:307declares the eraser for it:ghidra and ida emit nothing there, and kuna itself emitted nothing for the
same instruction when the block was reached by ordinary fall-thru. The leak was
confined to code reachable only through a recovered jump table.
Found by two independent decbench triage records, both NOVEL pool (kuna already
ties or beats every rival on these functions and still emitted this):
O2-noinline-betaflight-betaflight_STM32F405-accDetectO0-libopencm3-sdram-mainRoot cause (P2 lift/flow, not P9)
Thumb-2
blandtbb/tbhboth lower through SLEIGHSetThumbMode(1)->setISAMode(TB)(ARMTHUMBinstructions.sinc:1488,4916), raising a CALLOTHER.kuna parses and registers the cspec fixup (
infra/architecture.rs init_userops_and_fixups), andxref_control_flow(p2_lift/flow.rs:1203)queues every injected-userop CALLOTHER onto
injectlistthe moment theinstruction is decoded.
But the drain ran exactly once, at the end of
generate_ops— i.e. beforejump-table recovery.
generate_ops_with_jumptablesthen recovered the tables,seeded each target address, and re-drained
addrlistthroughfallthru(),which queued the newly discovered blocks' CALLOTHERs — and nothing drained that
second batch.
inject_pcodeends withinjectlist.clear(), so they werediscarded and the raw CALLOTHER survived all the way to P9.
Upstream Ghidra drains the inject list on every round of the outer
jump-table loop (
decompiler/cpp/flow.cc:819):kuna's port had the inner
whilebut not the outerdo/whiletail.Which layer, and why. Fixed in P2, at the drain. Suppressing the op in P9
would hide it in the printed C while leaving an un-injected CALLOTHER in the IR
for every other consumer — including
early_jump_table_fail, whose onlyfailing arm is literally the uninjected-CALLOTHER classification. Removing it
where upstream removes it is both cleaner and less code (one restructured
loop).
The fix
decompiler/crates/kuna-decomp/src/p2_lift/flow.rs (FlowInfo::generate_ops_with_jumptables): turn the singlewhile !tablelist.is_empty()into the upstreamdo/while, ending each round with theif self.has_inject() { self.inject_pcode()?; }thatgenerate_opsalreadyruns.
inject_pcodeis already re-entrant (it re-readsinjectlist.len()as itwalks and clears at the end), so no other change was needed.
Classification: strict bug fix, no option
Per
CLAUDE.md, a feature is a judgment call and needs a flag; a strict bug fixthat only corrects wrong output does not. This is the latter, on four grounds:
is not kuna's judgment; it is the spec's.
O2-noinline,4,091 functions make at least one call and only 168 of them leaked; the
behaviour was internally inconsistent, keyed on nothing but which discovery
round happened to find the block.
sdram.elfmainis the control inside asingle function: its entry block's
sub_80003d0(); sub_8000304(); ...calls(fall-thru discovered) carried no
setISAMode, while the 23 calls intable-reached blocks all did.
generateOps.An option here would be an option to keep a known-wrong rendering, and nobody
would set it. No DIV row either: the DIV registry records divergences from
upstream defaults, and this removes one rather than adding one (same treatment
as
ghdec-whiledo-complex, the other porting-divergence correctness fix).Reproduction, before/after
O0-libopencm3-sdram-main(sdram.elf,main@0x800072c)before (23 occurrences):
after (0):
Everything else in the function is byte-identical (the separate entry-ordering
defect that record also describes is untouched — different phase, not this PR).
O2-noinline-betaflight-...-accDetect(accDetect@0x8041de4)before (10 occurrences):
after (0) — and the inner
tbbswitch now folds itsdefault:in, which isexactly the ghidra shape the triage record flagged as a suspected knock-on:
Corpus-wide size
Every ARM binary in the decbench corpus (98 targets — the
stripped/trees ofO0,O2andO2-noinline),kuna decompile-all --json --mode reliable:setISAModesetISAModestatements emittedWorst single binary: betaflight
O2-noinline— 185 of 6,388 functions, 3,733statements.
Discovery / Thumb-decode control (the regression this must not cause).
Function counts are identical on every one of the 98 binaries, including
betaflight
5797 -> 5797(O0/O2) and6388 -> 6388(O2-noinline).Thumb decoding is untouched: the fix only drains an already-queued injection
list; it does not touch
visited, the TMode paint, or discovery seeding, soPRs #168/#173/#175 are unaffected.
Is there a family of these?
Yes for call-shaped user-op identifiers — and no for leaks. Scanning the
same corpus for identifiers that match a
define pcodeopname in the vendoredspecs finds ~8,800 more call sites (
DataMemoryBarrier,isCurrentModePrivileged,the
coprocessor_*family, …). Those user-ops have no declared<callotherfixup>, so nothing is supposed to erase them and ghidra printsthem too — that is the correct rendering for unimplemented semantics.
Cross-checking the emitted C against the set of declared
callotherfixuptargetops across all vendored cspecs (ARM/MIPS
setISAMode, plus the SPARCregister-window, JVM and tricore ops), exactly one leaked:
So the class is closed by this one fix, and this PR still ships one decision.
Downstream output change
Removing a side-effecting CALLOTHER unblocks a little simplification, all of it
shrinkage. Full emitted-C diff with the
setISAModelines factored out:O2-noinline/libopencm3/lcd-dma.elf: 228 functions, 10 with another change,22,579 -> 22,552 non-
setISAModelines. Every change is a deaduint4 v1; // lrdeclaration disappearing (the CALLOTHER's input had been keeping
lrlive).O2-noinline/betaflight: 6,388 functions, 107 with another change,146,936 -> 146,389 lines. Same dead-
lrshrink plus expression propagationinto indirect-call targets that the CALLOTHER had been blocking
(
v2 = **(uint4 **)(a1+0x10); (*(code *)(v2 & ...))(...)becomes oneexpression).
Gates
make testdocs/baseline.jsonuntouchedmake test-stagesmake rust-testmake check-speckuna catalog --checkdocs/baseline-stages.jsongains only the four new assertion keys (305 -> 309);docs/baseline.jsonis not re-pinned.Speed
Within the +5% budget; if anything slightly faster, because the injected NOP
lets dead-code elimination retire varnodes the CALLOTHER had been keeping live.
Interleaved before/after
decompile-all --json --mode reliable, median of 3, onan otherwise-idle box:
O2-noinline(6,388 fns)lcd-dmaO2-noinlineadc-dac-printfO0cf2O2Whole-corpus wall clock for the two 98-binary sweeps above: 978.3 s -> 961.9 s
(-1.68%).
Regression coverage
tests/stages/ghdec-isamode-inject.xml— a realbinary -> load function -> decompile -> print Cpath (the wrapper architecture is cleared and the file isloaded through the object bootstrap, same shape as
ghdec-fast-funcdisc.xml).New fixture
decompiler/crates/kuna-analysis/tests/fixtures/arm_thumb_switch_le32(1,304 bytes, source vendored alongside, built in the
kuna-devcontainer witharm-linux-gnueabihf-gcc -mthumb -Os -static -nostdlib -e _start):dispatchcompiles to
tbb [pc,r0]with eight table-reachable case blocks, four of themholding a pair of
bls — the decbench shape, minimised.Verified both ways: with the fix reverted the testcase fails on
ISAMODE #1with eightsetISAMode(1);statements, and the threeflow-integrity assertions (#2 the four table-reachable tail-call arms, #3 the
table-reachable
f0call sites, #4case 7:still reached) pass in bothstates, so a fix that dropped table flow instead of injecting into it would not
sneak through.
Provenance
inspiration = "decbench:O2-noinline-betaflight-betaflight_STM32F405-accDetect + O0-libopencm3-sdram-main; NOVEL pool"🤖 Generated with Claude Code
https://claude.ai/code/session_011RXVU58TKJxb518oViChwo