Skip to content

[AUTOMATED] fix(p2): (NOVEL) drop ARM ISA-mode bookkeeping from emitted C - #231

Merged
mahaloz merged 2 commits into
mainfrom
fix/isamode-userop-leak
Aug 1, 2026
Merged

mahaloz merged 2 commits into
mainfrom
fix/isamode-userop-leak

Conversation

@mahaloz

@mahaloz mahaloz commented Aug 1, 2026

Copy link
Copy Markdown
Contributor

The bug

On ARM/Thumb targets kuna emitted setISAMode(1); as a real statement in the
decompiled body. setISAMode is a SLEIGH user-op that exists only to tell the
lifter which instruction set to decode; it corresponds to nothing in the source,
and ARM.cspec:307 declares the eraser for it:

<callotherfixup targetop="setISAMode">
  <pcode incidentalcopy="true"><input name="newTB"/>
    <body><![CDATA[ r0 = r0; ]]></body></pcode>
</callotherfixup>

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-accDetect
  • O0-libopencm3-sdram-main

Root cause (P2 lift/flow, not P9)

Thumb-2 bl and tbb/tbh both lower through SLEIGH SetThumbMode(1) ->
setISAMode(TB) (ARMTHUMBinstructions.sinc:1488,4916), raising a CALLOTHER.
kuna parses and registers the cspec fixup (infra/architecture.rs init_userops_and_fixups), and xref_control_flow (p2_lift/flow.rs:1203)
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 — i.e. before
jump-table recovery. generate_ops_with_jumptables then recovered the tables,
seeded each target address, and re-drained addrlist through fallthru(),
which queued the newly discovered blocks' CALLOTHERs — and nothing drained that
second batch. inject_pcode ends with injectlist.clear(), so they were
discarded 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):

  while(!addrlist.empty()) fallthru();
  if (hasInject()) injectPcode();
  do {
    while(!tablelist.empty()) { ... recoverJumpTables ... fallthru() ... }
    checkContainedCall();
    checkMultistageJumptables();
    ...
    if (hasInject()) injectPcode();          // <-- the missing call
  } while(!tablelist.empty());

kuna's port had the inner while but not the outer do/while tail.

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 only
failing 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 single while !tablelist.is_empty() into the upstream do/while, ending each round with the
if self.has_inject() { self.inject_pcode()?; } that generate_ops already
runs. inject_pcode is already re-entrant (it re-reads injectlist.len() as it
walks 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 fix
that only corrects wrong output does not. This is the latter, on four grounds:

  1. The emitted C named a function that does not exist.
  2. The processor cspec declares the user-op must be replaced by a NOP. This
    is not kuna's judgment; it is the spec's.
  3. kuna already honoured that everywhere else. In betaflight 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.elf main is the control inside a
    single function
    : its entry block's sub_80003d0(); sub_8000304(); ... calls
    (fall-thru discovered) carried no setISAMode, while the 23 calls in
    table-reached blocks all did.
  4. It restores a faithful port of upstream 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)

kuna decompile sdram.elf --addr 0x800072c --mode reliable

before (23 occurrences):

label_8000986:
  setISAMode(1);
  sub_80002c8(dat_8000a18);
  setISAMode(1);
  v2 = sub_8000260(1);
  ...
label_80009b0:
  setISAMode(1);
  sub_80002c8(dat_8000a10);
  v3 -= 0x100;
  setISAMode(1);
  sub_80006fc(v3,0);

after (0):

label_8000986:
  sub_80002c8(dat_8000a18);
  v2 = sub_8000260(1);
  ...
label_80009b0:
  sub_80002c8(dat_8000a10);
  v3 -= 0x100;
  sub_80006fc(v3,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):

    case 0:
    case 3:
      setISAMode(1);
      if (sub_8060c08(a0)) { v1 = '\x03'; goto label_8041eea; }
      break;
    ...
label_8041e00:
    setISAMode(1);
    if (sub_806220c(a0)) {
      if (4 <= (uint4)*(uint1 *)(a0 + 0x14) - 6) // branch-flip
        v1 = '\b';
      else {
        setISAMode(1);
        switch(*(uint1 *)(a0 + 0x14)) {
          case 6: v1 = '\t'; break;
          ...
          case 9: v1 = '\f';
        }
      }

after (0) — and the inner tbb switch now folds its default: in, which is
exactly the ghidra shape the triage record flagged as a suspected knock-on:

    case 0:
    case 3:
      if (sub_8060c08(a0)) { v1 = '\x03'; goto label_8041eea; }
      break;
    ...
label_8041e00:
    if (sub_806220c(a0)) {
      switch(*(void *)(a0 + 0x14)) {
        case 6: v1 = '\t'; break;
        case 7: v1 = '\n'; break;
        case 8: v1 = '\v'; break;
        case 9: v1 = '\f'; break;
        default: v1 = '\b';
      }

Corpus-wide size

Every ARM binary in the decbench corpus (98 targets — the stripped/ trees of
O0, O2 and O2-noinline), kuna decompile-all --json --mode reliable:

before after
functions enumerated 56,535 56,535
functions containing setISAMode 1,499 0
setISAMode statements emitted 21,955 0

Worst single binary: betaflight O2-noinline — 185 of 6,388 functions, 3,733
statements.

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) and 6388 -> 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, so
PRs #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 pcodeop name in the vendored
specs 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 prints
them too — that is the correct rendering for unimplemented semantics.
Cross-checking the emitted C against the set of declared callotherfixup
targetops across all vendored cspecs (ARM/MIPS setISAMode, plus the SPARC
register-window, JVM and tricore ops), exactly one leaked:

declared callotherfixup targetops present in emitted C:
  setISAMode: 21955

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 setISAMode lines factored out:

  • O2-noinline/libopencm3/lcd-dma.elf: 228 functions, 10 with another change,
    22,579 -> 22,552 non-setISAMode lines. Every change is a dead uint4 v1; // lr
    declaration disappearing (the CALLOTHER's input had been keeping lr live).
  • O2-noinline/betaflight: 6,388 functions, 107 with another change,
    146,936 -> 146,389 lines. Same dead-lr shrink plus expression propagation
    into indirect-call targets that the CALLOTHER had been blocking
    (v2 = **(uint4 **)(a1+0x10); (*(code *)(v2 & ...))(...) becomes one
    expression).

Gates

gate result
make test PARITY OK (675/675) — docs/baseline.json untouched
make test-stages PARITY OK (309/309)
make rust-test green
make check-spec green
kuna catalog --check green

docs/baseline-stages.json gains only the four new assertion keys (305 -> 309);
docs/baseline.json is 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, on
an otherwise-idle box:

binary before after delta
betaflight O2-noinline (6,388 fns) 76.37 s 73.65 s -3.56%
libopencm3 lcd-dma O2-noinline 40.34 s 41.26 s +2.28%
libopencm3 adc-dac-printf O0 14.79 s 15.08 s +2.00%
crazyflie cf2 O2 39.12 s 38.49 s -1.61%

Whole-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 real binary -> load function -> decompile -> print C path (the wrapper architecture is cleared and the file is
loaded 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-dev container with
arm-linux-gnueabihf-gcc -mthumb -Os -static -nostdlib -e _start): dispatch
compiles to tbb [pc,r0] with eight table-reachable case blocks, four of them
holding a pair of bls — the decbench shape, minimised.

Verified both ways: with the fix reverted the testcase fails on
ISAMODE #1 with eight setISAMode(1); statements, and the three
flow-integrity assertions (#2 the four table-reachable tail-call arms, #3 the
table-reachable f0 call sites, #4 case 7: still reached) pass in both
states, 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

mahaloz and others added 2 commits August 1, 2026 19:14
…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
@mahaloz
mahaloz merged commit 1e7b04c into main Aug 1, 2026
9 checks passed
@mahaloz
mahaloz deleted the fix/isamode-userop-leak branch August 1, 2026 19:44
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