Skip to content

[AUTOMATED] fix(p2): drop a jump table when its BRANCHIND is swept - #234

Merged
mahaloz merged 2 commits into
mainfrom
fix/stale-jumptable-removal
Aug 1, 2026
Merged

mahaloz merged 2 commits into
mainfrom
fix/stale-jumptable-removal

Conversation

@mahaloz

@mahaloz mahaloz commented Aug 1, 2026

Copy link
Copy Markdown
Contributor

The bug

main in coreutils comm, join and uniq produced no output at all: the
decompile pipeline panicked at p2_lift/jumptable.rs:1811 and the whole function
came back as a warning shell. Six functions, at -O0 and at -O2-noinline,
every one of them the getopt_long dispatch.

$ kuna decompile .../O0/coreutils/stripped/comm --addr 0x3994 --mode reliable
/* WARNING: decompilation failed: ... (LOSS-131): called `Option::unwrap()` on a `None` value */
error: decompilation failed for sub_3994 ...
thread 'main' panicked at crates/kuna-decomp/src/p2_lift/jumptable.rs:1811:76
exit=1

The chain

loweredswitch (P2, default-on) rewires a comparison cascade's head into a
synthetic BRANCHIND and then sweeps the orphaned compare spine with
removeUnreachableBlocks. In these binaries the cascade is only half the
dispatch: the short options ('1'/'2'/'3' plus the negative help/version
sentinels) go through the cascade, while the dense long-option range
(0x7a, 0x80..0x83) goes through a genuine GCC PIC relative-offset jump table
(3e ff e0 notrack jmp rax at comm 0x3aed, table in .rodata at 0x9800).

Severing the cascade head's out-edges strands that table's block, and the sweep
destroys its ops - including the real BRANCHIND. The ported
blockRemoveInternal did not drop the table:

// funcdata_block.rs:1369, before
// JumpTable *jt = findJumpTable(op); if (jt) removeJumpTable(jt); -- STUB(W4)

so a labelless table survived in jumpvec. ActionSwitchNorm re-recovered its
model and JumpBasic::findDeterminingVarnodes unwrapped inrefs[0] of a
pcodeop_flags::dead op.

The fix - two parts, both strict bug fixes (no new option)

1. Parity + crash-proofing. Funcdata::remove_jump_table (C++
Funcdata::removeJumpTable, funcdata_block.cc:470) is ported and
block_remove_internal uses it through the existing find_jump_table_index,
exactly as funcdata_block.cc:272 does. ActionSwitchNorm::apply gains the
liveness guard install_switch_defaults already had (skip a table whose indirect
op is absent / dead / parentless), and JumpBasic::find_determining_varnodes
returns KunaResult<()> instead of unwrapping, so a stale table abandons its own
recovery rather than the run.

2. Quality - and yes, part 2 was needed. Part 1 alone stops the panic but
leaves the real table's block destroyed. comm main then rendered a 60-line
body whose switch carried only the cascade's cases and had silently lost -z,
--check-order, --nocheck-order, --output-delimiter and --total - strictly
worse than --option loweredswitch off. So kuna_install_lowered_switch now
declines when its rewiring would strand a block whose tail BRANCHIND
already owns a recovered JumpTable
(kuna_lowered_switch_strands_table walks reachability from the entry over the
post-surgery successor relation, before any edit). The pre-existing guard only
checked for a table at the head's own branch address, which never matches here -
the cascade head and the real BRANCHIND are different instructions. This
narrows when an existing option fires, so it lives inside loweredswitch
rather than behind a new flag; tests/stages/ghangr-loweredswitch-mv.xml
(mv -O2, a cascade with no downstream table) still installs.

Before / after - comm main (0x3994, --mode reliable)

Before (9 lines, exit 1):

void sub_3994(void)
{
  /* WARNING: decompilation failed: decompile pipeline reached an un-ported seam
     (LOSS-131): called `Option::unwrap()` on a `None` value */
}
error: decompilation failed for sub_3994 in .../O0/coreutils/stripped/comm
thread 'main' panicked at crates/kuna-decomp/src/p2_lift/jumptable.rs:1811:76

With part 1 only (60 lines - no panic, but the real switch is gone; note the
default arm goes straight to usage(1) and 0x7a/0x80..0x83 have vanished):

  while( true ) {
    v1 = getopt_long(a0,a1,0x97c1,0xcae0,0);
    if (v1 == -1) break;
    switch(v1) {
      default:
        sub_2a20(1); // no-return, return-dupe
      case 0x31: dat_d111 = 0; break;
      case 0x32: dat_d112 = 0; break;
      case 0x33: dat_d113 = 0; break;
      case -0x83: sub_6ecc(stdout,...); exit(0); // no-return
      case -0x82: sub_2a20(0); // no-return
    }
  }

After (97 lines - identical to --option loweredswitch off, and the same
shape Ghidra emits):

  if (v1 <= 0x83) {
    if (0x7a <= v1) {
      switch(v1) {
        case 0x7a:
          dat_d010 = 0;
          break;
        default:
          goto label_3c29;
        case 0x80:
          dat_d118 = 1;
          break;
        case 0x81:
          dat_d118 = 2;
          break;
        case 0x82:
          if ((dat_d120) && (v1 = strcmp(dat_d018,optarg), v1))
            error(1,0,gettext("multiple output delimiters specified"));
          dat_d018 = optarg;
          if (*optarg) // branch-flip
            dat_d120 = strlen(optarg);
          else {
            dat_d120 = 1;
          }
          break;
        case 0x83:
          dat_d117 = 1;
      }
      goto label_3c33;
    }
    ...

All six functions (comm/join/uniq main, -O0 and -O2-noinline) are now
byte-identical to their --option loweredswitch off rendering. Checked against
the source (comm.c cases '1','2','3','z', CHECK_ORDER_OPTION,
NOCHECK_ORDER_OPTION, OUTPUT_DELIMITER_OPTION, TOTAL_OPTION) and against
the stored ghidra/ida panes - uniq main's recovered case set (0x30..0x39,
0x44, 0x66, 0x69, 0x73, 0x75, 0x77, 0x7a, 0x80) matches Ghidra's
exactly, and join main matches Ghidra's 13 cases.

Corpus sweep

kuna decompile-all --json --mode reliable over 16 stripped binaries
(coreutils/grep/gzip/diffutils, O0 + O2-noinline), 6130 functions:

panic site before after
p2_lift/jumptable.rs:1811 (this PR) 6 0
ruleaction_2.rs:96 / ruleaction_3.rs:125 (opcode whitelist, other PR) 0 0
total error records 6 0

The opcode-whitelist family already landed on main in #227, so it reads 0 on
both sides of this branch. On the pre-#227 base the same sweep read 11 (6 + 5).
(before/after measured on 676ae487; the after sweep re-run after rebasing
onto 1e7b04cd is also 0/6130, and all six functions still render identically to
their --option loweredswitch off reference there.)

Speed

No regression. Wall-clock decompile-all over 5 binaries, 6 reps each:
before min 35.48 s / median 35.62 s, after min 33.51 s / median 34.83 s.

python3 -m scripts.pipeline.timeit --option loweredswitch on comm sub_3994:
off=256.2 ms on=228.8 ms delta=-10.69% (budget 5.0%) -> within budget.

Gates

  • make test -> PARITY OK (675/675) (no docs/baseline.json re-pin)
  • make test-stages -> PARITY OK (323/323)
  • make rust-test -> green
  • make check-spec -> OK
  • kuna catalog --check -> OK

Docs + test

  • Spec prose in docs/spec/02-lift-and-flow.md: a Table lifetime paragraph
    in the switch-recovery section and the install decline in the
    lowered-cascade section.
  • tests/stages/ghdec-stalejumptable.xml: two-pass over the real comm bytes
    (pass 1 = default pipeline, pass 2 = option loweredswitch off as the
    reference). 0/5 assertions before the fix, 5/5 after.

Merge note: the new stage XML bumps the hard-coded corpus file count in
decompiler/crates/kuna-base/src/xml.rs (177 -> 178 on this base, which
already includes #231's ghdec-isamode-inject.xml). PR #232 bumps the same
constant; on merge resolve to base + all merged testcases, not to either
side.

inspiration = "decbench:cases-missing pool; coreutils comm/join/uniq main"

🤖 Generated with Claude Code

https://claude.ai/code/session_011RXVU58TKJxb518oViChwo

mahaloz and others added 2 commits August 1, 2026 19:58
`main` in coreutils comm/join/uniq produced no output at all: the decompile
pipeline panicked at `p2_lift/jumptable.rs:1811` and the whole function came back
as a warning shell. Six functions -- comm/join/uniq `main`, at -O0 and at
-O2-noinline -- every one of them the getopt_long dispatch.

The chain. `loweredswitch` (P2, default-on) rewires a comparison cascade's head
into a synthetic BRANCHIND and then sweeps the orphaned compare spine with
`removeUnreachableBlocks`. In these binaries the cascade is only half the
dispatch: the short options ('1'/'2'/'3' and the negative help/version sentinels)
go through the cascade, while the dense long-option range (0x7a, 0x80..0x83) goes
through a genuine GCC PIC relative-offset jump table (`3e ff e0  notrack jmp rax`
at comm 0x3aed, table in .rodata at 0x9800). Severing the cascade head's
out-edges strands that table's block, and the sweep destroys its ops -- including
the real BRANCHIND. The ported `blockRemoveInternal` did NOT drop the table
(`funcdata_block.rs:1369` was `// JumpTable *jt = findJumpTable(op); ... --
STUB(W4)`), so a labelless table survived in `jumpvec`. `ActionSwitchNorm` then
re-recovered its model and `JumpBasic::findDeterminingVarnodes` unwrapped
`inrefs[0]` of a `pcodeop_flags::dead` op.

Two parts, both strict bug fixes, so no option:

1. Parity + crash-proofing. `Funcdata::remove_jump_table` (C++
   `Funcdata::removeJumpTable`, `funcdata_block.cc:470`) is ported and
   `block_remove_internal` uses it via the existing `find_jump_table_index`,
   exactly as `funcdata_block.cc:272` does. `ActionSwitchNorm::apply` gains the
   liveness guard `install_switch_defaults` already had (skip a table whose
   indirect op is absent / dead / parentless), and
   `JumpBasic::find_determining_varnodes` returns `KunaResult<()>` instead of
   unwrapping, so a stale table abandons its own recovery rather than the run.

2. Quality. Part 1 alone stops the panic but leaves the real table's block
   destroyed: comm `main` then rendered a 60-line body whose switch carried only
   the cascade's cases and had silently lost 'z', --check-order, --nocheck-order,
   --output-delimiter and --total. So `kuna_install_lowered_switch` now declines
   when its rewiring would strand a block whose tail BRANCHIND already owns a
   recovered `JumpTable` (`kuna_lowered_switch_strands_table` walks reachability
   from the entry over the post-surgery successor relation, before any edit). Its
   existing guard only checked for a table at the head's own branch address, which
   never matches here -- the cascade head and the real BRANCHIND are different
   instructions. This narrows when an existing option fires, so it lives inside
   `loweredswitch` rather than behind a new flag.
   `tests/stages/ghangr-loweredswitch-mv.xml` (mv -O2, a cascade with no
   downstream table) still installs, so the decline is not over-broad.

All six functions now render identically to `--option loweredswitch off`, which
is the shape Ghidra emits (comm `main`: 97 lines, `switch(v1) { case 0x7a ...
case 0x80 ... case 0x83 ... default }`).

Corpus sweep, `kuna decompile-all --json --mode reliable` over 16 stripped
binaries (coreutils/grep/gzip/diffutils, O0 + O2-noinline), 6130 functions: error
records 6 -> 0, all six the `jumptable.rs:1811` panic. The
`ruleaction_2.rs:96`/`ruleaction_3.rs:125` opcode-whitelist family is 0 both
before and after on this base (it landed on main in #227) and is not touched
here.

Speed: no regression. Wall-clock `decompile-all` over 5 binaries, 6 reps each:
before min 35.48 s / median 35.62 s, after min 33.51 s / median 34.83 s.
`python3 -m scripts.pipeline.timeit --option loweredswitch` on comm sub_3994:
off 256.2 ms, on 228.8 ms, delta -10.69% (budget 5.0%) -> within budget.

Gates: make test PARITY OK (675/675), make test-stages PARITY OK (323/323),
make rust-test green, make check-spec OK, kuna catalog --check OK. No baseline
re-pin of docs/baseline.json. Spec prose in docs/spec/02-lift-and-flow.md (table
lifetime and the install decline); regression test
tests/stages/ghdec-stalejumptable.xml (two-pass over the real comm bytes: 0/5
assertions before, 5/5 after). The new stage XML bumps the hard-coded corpus
file count in decompiler/crates/kuna-base/src/xml.rs (177 -> 178).

inspiration = "decbench:cases-missing pool; coreutils comm/join/uniq main"

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_011RXVU58TKJxb518oViChwo
…emoval

# Conflicts:
#	decompiler/crates/kuna-base/src/xml.rs
#	docs/baseline-stages.json
#	tests/stages/README.md
@mahaloz
mahaloz merged commit 51135b5 into main Aug 1, 2026
9 checks passed
@mahaloz
mahaloz deleted the fix/stale-jumptable-removal branch August 1, 2026 20:08
mahaloz added a commit that referenced this pull request Aug 1, 2026
…timating it (#237)

The recall pool was the campaign's headline claim and it was carrying an
unverified number. Measured properly it is 7,354, not 6,540 -- the smaller
figure could not be reproduced under any rival-subset or filter variant.

Where it actually goes, and most of this contradicts what the campaign
believed:

  63    (0.9%)  genuinely recovered by the 2026-08-01 fix wave
  1,994 (27.1%) already fixed BEFORE the wave -- the stored kuna artifacts
                were 12-16 days old, so the pool was measuring staleness
  3,233 (44.0%) decbench's .text filter, never kuna's fault
  2,061 (28.0%) still missing, real kuna gap

So the wave's benchmark-visible recall gain is small and the campaign should
say so. Two corrections in the other direction: #224 recovered 256 freertos
functions decbench structurally cannot score, and both #227 and #234
under-claimed (19 -> measured 50; 6 -> measured 13).

98.3% of the live remainder is function-entry granularity on embedded ARM --
kuna emits a body for code CONTAINING the DWARF low_pc but does not start a
function AT it, median 24 bytes away. That is one gap, not two thousand.

Highest-value remaining bug: rename_recurse / "Overlapping input varnodes" on
gnulib's rpl_fcntl, hard-failing one function in 48 of 213 optimized x86-64
binaries, -O2 only.

Method notes worth keeping: matching is by address, never by name; PE targets
report ImageBase+RVA where the rival artifacts record RVAs, and uncorrected
that fabricates 181 fake gaps.
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