Skip to content

xrefs: follow A32 add/ldr branch tables into their cases - #1399

Merged
mahaloz merged 22 commits into
Noelo-Lab:mainfrom
alvistar:alvistar/kuna-arm-branch-tables
Nov 2, 2026
Merged

mahaloz merged 22 commits into
Noelo-Lab:mainfrom
alvistar:alvistar/kuna-arm-branch-tables

Conversation

@alvistar

@alvistar alvistar commented Nov 1, 2026

Copy link
Copy Markdown
Contributor

On A32, kuna xrefs stops at a switch dispatched through addls pc,pc,rN,lsl #2 or ldrls pc,[pc,rN,lsl #2] and follows only the b default after it. Every case body goes unreferenced, with its calls, strings and GOT reads.

$ kuna xrefs decompiler/crates/kuna-analysis/tests/fixtures/branchtable_arm_le32 --to on_read
# 0 references to on_read @ 0x100b8

add_dispatch makes the GOT base in r6, then cmp r5,#4; addls pc,pc,r5,lsl #2; b default; b case0 … b case4; case 2 reads on_read's slot through r6. The fixture comes with this PR, and main gives the output above. With this PR the command finds both GOT reads:

# 2 references to on_read @ 0x100b8
0x101ec	data	add_dispatch+0xf0	ldr r3,[r6,r3]
0x10338	data	ldr_dispatch+0xc4	ldr r3,[r6,r3]
  • The reference walk reads both table forms with the reader the Listing walk already uses (kuna_a32switch): the case count comes from the cmp/ls guard, the cases from the b slots or the words after the dispatch.
  • Each case is walked with the dispatch's state, so a GOT base made before the dispatch reaches every case. The dispatch files one jump per case, as Ghidra's ArmAnalyzer does; the words of an ldr table are data.
  • The predicated skip of a computed jump stays one of its flows, so PIC pool composition and no-return propagation see the instruction unchanged.
  • It needs only armframes (default inventory); --option armframes off gives the old walk back, and other architectures do not change.

Tests: verify_branchtable.rs checks each case's slot, callback, string, call and jump row, a table clamped by jumptablemax, a branch into the dispatch ahead of its guard, and armframes off. verify_predjump.rs checks that a pool word loaded before bxne r3 still forms its string after it, in A32 and Thumb. Both, and the tests/cli/arm-branch-table-case-xref.json probe, fail without the fix.

Speed (kuna strings, CPU, median of 5, main → this PR): 1.02 → 1.03 s on x86-64 musl libstdc++.so, 1.10 → 1.09 s on ARM musl libstdc++.so, 0.53 → 0.52 s on ARM musl libc.so. On an ARM shared library with 233 such tables it goes 1.13 → 1.17 s (+3.5%), because it walks the case bodies it skipped before.

🤖 Generated with Claude Code

@mahaloz

mahaloz commented Nov 1, 2026

Copy link
Copy Markdown
Contributor

[AUTOMATED] The A32 tables come out right. On 83 ldrls tables in u-boot and 120 addls tables in Ubuntu 22.04's armel libc, plus tables in a static armel glibc program, libm and libstdc++, each dispatch's jump rows equal the cmp-bounded slots/words exactly. kuna functions, decompile-all and non-ARM xref dumps are byte-identical to main. Three kinds of false rows remain on the default kuna xrefs path:

$ arm-linux-gnueabihf-gcc -nostdlib -static -no-pie -Wl,-Ttext=0xff000 -o a32repro a32repro.S
$ kuna xrefs a32repro --from 0xff01c    # a pool word after `bl __stack_chk_fail`
0xff128  jump  -  @0xff01c  andeq pc,pc,r8, lsr #0x2
0xff1a0  jump  -  @0xff01c  andeq pc,pc,r8, lsr #0x2
$ kuna xrefs a32repro --from 0xff028    # cmp r0,#3; addls pc,pc,r0,lsl #3
0xff030 0xff034 0xff038 0xff03c  jump      (cases are 0xff030 0xff038 0xff040 0xff048)
$ kuna xrefs a32repro --from 0xff060    # cmp r0,#8; bhi; add pc,pc,r0
0xff068 ... 0xff088  jump (9 rows, one onto __stack_chk_fail)

main files only each instruction's predicated skip row here, none of these.

a32repro.S
        .syntax unified
        .arch armv7-a
        .text
        .arm
        .global _start
_start: bl      guarded
        bl      slots8
        bl      unscaled
1:      b       1b

        .global guarded
        .type guarded, %function
guarded:
        push    {r4, lr}
        ldr     r4, .Lgot
        bl      __stack_chk_fail
.Lgot:  .word   0x000ff128
        .word   0x000ff1a0
        .size guarded, . - guarded

        .global slots8
        .type slots8, %function
slots8:
        cmp     r0, #3
        addls   pc, pc, r0, lsl #3
        b       9f
        mov     r0, #10
        bx      lr
        mov     r0, #11
        bx      lr
        mov     r0, #12
        bx      lr
        mov     r0, #13
        bx      lr
9:      mov     r0, #0
        bx      lr
        .size slots8, . - slots8

        .global unscaled
        .type unscaled, %function
unscaled:
        cmp     r0, #8
        bhi     9f
        add     pc, pc, r0
        nop
        mov     r1, #1
        mov     r1, #2
9:      mov     r0, r1
        bx      lr
        .size unscaled, . - unscaled

        .global __stack_chk_fail
        .type __stack_chk_fail, %function
__stack_chk_fail:
        b       __stack_chk_fail

        .p2align 8
        .global other
        .type other, %function
other:
        .rept 0x40
        mov     r0, r0
        .endr
        bx      lr
  1. Pool words read as tables (real binaries). The walk already falls through a call into the literal pool after it, and a GOT offset like 0x000ff4a8 decodes as andeq pc,pc,…, a predicated computed jump. On main that instruction filed only its skip row. Now c.flows.iter().all(|&t| Some(t) == skip) sends every predicated computed jump to the drefs reader and to branch_cases as well, and they read the next pool words as case addresses. Ubuntu 22.04's armel libc.so.6 (libc6-armel-cross 2.35) gets 8 such switches, for example kuna xrefs libc.so.6 --to 0xff4a8 → 0x87bb8 jump shm_open+0xd8 andeq pc,pc,r8, lsr #0x9. Its libstdc++.so.6 gets 3. Suggested fix: run only the A32 reader on a predicated jump, and keep the other readers on c.flows.is_empty() as on main, including the woken re-read.
  2. The index scale is not checked. fold makes Const + unknown an Indexed value whatever the shift, so lsl #3 and unshifted indexes are read as 4-byte slots. Suggested fix: require the index's INT_LEFT by 2 (or INT_MULT by 4).
  3. Minor: an ldr table word with bit 0 set (an interworking target) is filed and walked as an A32 case at an odd address. Stopping the run at the first odd word is the conservative choice.

Issues 2 and 3 already existed in the opt-in Listing walk, which shares the reader. All three are new on the default xrefs path. A sketch of all three (+19/-5 lines), re-run over the corpus above: only these false rows disappear, and every real table is unchanged.

--- a/decompiler/crates/kuna-analysis/src/listing/kuna_a32switch.rs
+++ b/decompiler/crates/kuna-analysis/src/listing/kuna_a32switch.rs
@@ fn decoded_targets
         let mut index: Option<Key> = None;
+        let mut scaled = false;
         let mut predicated = false;
@@
-                let Some(index) = index else { return TableRead::default() };
+                let Some(index) = index.filter(|_| scaled) else { return TableRead::default() };
@@
                 let targets = if words {
-                    super::kuna_switchtable::targets(base, from, self.pool, exec, Some(read), read)
+                    let mut words = super::kuna_switchtable::targets(base, from, self.pool, exec, Some(read), read);
+                    words.truncate(words.iter().position(|&t| t & 1 != 0).unwrap_or(words.len()));
+                    if words.len() < MIN_ENTRIES { Vec::new() } else { words }
                 } else {
@@
                     .find_map(|vn| key_of(vn, data).filter(|k| matches!(k, Key::Reg(..))));
+                let by = op.ins.get(1).filter(|vn| is_constant(vn)).map(|vn| vn.offset);
+                scaled = matches!((op.opcode, by), (OpCode::CPUI_INT_LEFT, Some(2)) | (OpCode::CPUI_INT_MULT, Some(4)));
--- a/decompiler/crates/kuna-analysis/src/listing/xrefs.rs
+++ b/decompiler/crates/kuna-analysis/src/listing/xrefs.rs
@@ woken re-read
-                if read.cases.is_empty() && read.stated.is_none() && read.gap.is_none() {
+                let predicated = a32_tables.is_some() && is_predicated(translate, &code_space, vma);
+                if read.cases.is_empty() && read.stated.is_none() && read.gap.is_none() && !predicated {
@@ per-instruction table read
+                    let unpredicated = c.flows.is_empty();
                     for &(base, kind) in &drefs {
-                        if kind == XrefKind::Data && stated.is_none() && a32.gap.is_none() {
+                        if unpredicated && kind == XrefKind::Data && stated.is_none() && a32.gap.is_none() {
@@
-                    if cases.is_empty() && stated.is_none() && a32.gap.is_none() {
+                    if unpredicated && cases.is_empty() && stated.is_none() && a32.gap.is_none() {
@@
+/// Whether the instruction at `vma` is predicated: its p-code holds a `CBRANCH`.
+fn is_predicated(translate: &dyn Translate, code_space: &Rc<AddrSpace>, vma: u64) -> bool {
+    let mut cap = FullCapture::default();
+    decode(translate, vma, code_space, &mut cap).is_some()
+        && cap.ops().iter().any(|op| op.opcode == OpCode::CPUI_CBRANCH)
+}

These fixes want test cases: a pool word after a call in predjump_arm_le32, and an lsl #3 table. The docs/spec/01 sentence "the other table readers run on it as on any computed jump" would then become "on an unpredicated one".

@alvistar

alvistar commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks, all three reproduce here with your a32repro.S, and your sketch fixes them. Pushed as one commit per fix:

  • cd27f590 the data-reference and branch-register readers run only on an unpredicated computed jump, at the first read and at the woken re-read.
  • 643a701f the A32 reader takes a dispatch only when its index is INT_LEFT by 2 or INT_MULT by 4.
  • 1553c597 an ldr table ends before its first word with bit 0 set.

Instead of another change to predjump_arm_le32 (it would move every address again), the tests use a new fixture, a32tablefp_arm_le32, built from your a32repro.S plus an ldrls table whose third word is odd. verify_branchtable.rs checks that the pool word after bl __stack_chk_fail, the lsl #3 dispatch and the unscaled add pc,pc,r0 file no jump rows and no switch record, and that the odd-word table gives only its first two cases. Each test fails without its fix. The spec sentence now says the other readers run only on an unpredicated jump, and it describes the scale and odd-word rules.

kuna strings CPU, median of 5, main → this PR: 1.00 → 1.01 s on x86-64 musl libstdc++.so, 1.05 → 1.06 s on ARM musl libstdc++.so, 0.52 → 0.53 s on ARM musl libc.so, 1.12 → 1.16 s on the ARM library with 233 tables.

Edited: rebased on main to resolve a conflict with #1412; SHAs updated.

alvistar and others added 17 commits November 2, 2026 08:53
The reference walk stopped at a guarded `addls pc,pc,rN,lsl Noelo-Lab#2` or
`ldrls pc,[pc,rN,lsl Noelo-Lab#2]` and walked only `b default`, so every case
body went unreferenced, and it filed a jump from the dispatch to the
next instruction. It now reads both forms with the reader the Listing
walk already uses under `armframes` (`kuna_a32switch`), walks each case
as the dispatcher's own code with the dispatch's state, so a GOT base
made before the dispatch reaches every case, and files one jump row per
case. The predicated skip is a fall-through, not a reference. The words
of an `ldr` table stay data with no pointer row, as in Ghidra's ARM
switch recovery.

Fixture `branchtable_arm_le32` (GCC 14.2, the dispatch in `asm goto`
because GCC 14 compresses ARM-state tables) with e2e tests in
`verify_branchtable.rs`, a gap record and a promoted CLI probe.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The three default-option tests each bootstrapped the fixture and rebuilt
the whole reference index. They now share one index through a OnceLock,
and `build` takes the options a test needs set before analysis.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The A32 read recorded the number of cases it read as the count the
switch states, so a table clamped by `jumptablemax` looked complete and
was never marked truncated. `A32Tables::targets` now returns the guard's
count beside the cases, as the Thumb `tbb` reader does, and a stated
count stops the other readers from trying the dispatch.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The table read had dropped the reference walk's row from a predicated
computed jump to the next instruction and widened the read's gate to
"every flow is that skip", for every architecture and whatever
`armframes` said. `Classified::skip_falls_through` now moves that skip
into the fall-through, and both the Listing and the reference walks
apply it only where they read A32 tables (`armframes` on an ARM image),
so the two walks agree and both gates are again "no static flow".
With `armframes off`, and on every other architecture, the walk is the
one before A32 tables: the skip row is back and no table is read.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`A32Tables` built a second `PoolImage` of the file beside the one the
reference walk already holds. It now borrows the caller's image; the
Listing walk builds one only where `kuna_a32switch::applies` holds, and
the reference walk's `sections_are_runtime` check goes, since its image
exists only for runtime sections.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`A32Tables::targets` decoded the dispatch again, and the guard check
decoded it a third time when the dispatch was predicated. The reference
walk now passes its own p-code and length to `decoded_targets`, and
`guard_cases` takes a predicated dispatch's p-code instead of a flag;
the Listing walk, which keeps no p-code, decodes once in `targets`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
When the walk decoded an `addls pc`/`ldrls pc` dispatch before the `cmp`
that falls into it (a branch into the dispatch, or breadth-first order),
the A32 read found no guard, nothing queued the dispatch for a second
read, and the retry loop consulted only the register-chain and Thumb
readers. `guard_cases` now reports the address its read stopped at, the
A32 read queues the dispatch there, and the retry loop tries the A32
reader first, as the first read does.

Fixture: `early_dispatch` branches into its own dispatch ahead of the
guard (fixture rebuilt; the other functions' code is unchanged, its data
moved, and the test constants follow).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The two inline comments the A32 table read added go; what they said,
why the A32 read comes first and that the predicated skip is the
fall-through, is in `descend`'s header.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The `armframes` summary said the inventory value needs `listing` and
`funcstart_patterns`, and that enabled recovery follows A32 tables,
which read as if table following needed both. The code reads tables
under `armframes` alone, and should: `funcstart_patterns` is off by
default, so sharing frame recovery's gate would turn table following
off by default. The summary, the spec and the gap record now say so,
and say where the predicated skip is a fall-through, that the switch
record states the guard's count, and that a dispatch reached before
its guard is read again.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The reference walk turned the skip of every predicated computed jump on an
ARM image into its fall-through, so PIC pool composition took `bxne r3` as
an instruction that ran and fell through: a pool word in flight was dropped
on the path where the jump did not run, and the string that `add rN,pc,r2`
forms after it lost its row (A32 and Thumb `it ne`).

The walk now keeps classify's shape and only recognises the skip through
`Classified::predicated_skip`: the skip files no row, and a dispatch whose
only flow is that skip is still read as an A32 table.

New fixture `predjump_arm_le32` (top-level asm) with the e2e test
`verify_predjump`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The Listing walk took the skip of a predicated computed jump as its
fall-through wherever A32 tables are read, so the same instruction had two
shapes: flows=[], fall_through=next in the Listing, flows=[next] and no
fall-through for the AIF gap decoder, the decode memo, pdecode and
coldentry. No-return propagation reads the Listing, so a function that
leaves through `bxne r0` or `bl abort` was no longer proved no-return and
its callers' C changed by default.

No walk converts the skip any more. `classify` keeps it as a flow on every
architecture and under every option, and `Classified::predicated_skip` is
the one place that recognises it: a computed jump whose only flow is its
skip is read as an A32 table. `skip_falls_through` is gone. The spec,
the armframes summary and the gap record say so.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A guarded A32 dispatch whose table read gave no case (a run shorter than
two entries, `b caseN` slots past the section end, or `jumptablemax`
below two) still returned its guard's count. A stated count stops the
other table readers, so they no longer ran on that dispatch, and the
switch record claimed a table with no case read.

No case read now means no stated count, as before the count was stated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Pins the rows of an `ldr pc,[pc,r0,lsl Noelo-Lab#2]` table with no range check
placed right after a literal-pool word: the dispatch files only the row
of its PC-relative operand and no switch record, as before A32 tables
were read. The guard read stops at the undecoded pool word, but no table
reader can read this form without a case count.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
picpool now reads Thumb literal copies only in images with .got, .got.plt
or .dynamic, so the GOT-less predjump fixture lost its Thumb pool string.
A one-word .got holding pool_msg makes it a GOT image again; every code
and rodata address moves up 0x20 for the extra program header.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The walk falls through a call into the literal pool after it, and a GOT
offset such as 0x000ff128 decodes as `andeq pc,pc,...`. The data-reference
and branch-register readers then took the next pool words as its cases.
They now run only on an unpredicated computed jump, at the first read and
at the re-read once the guard is decoded.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`fold` makes `Const + unknown` an indexed value whatever the shift, so an
`addls pc,pc,r0,lsl Noelo-Lab#3` dispatch and an unscaled `add pc,pc,r0` were read
as tables of 4-byte slots. The index must now be `INT_LEFT` by 2 or
`INT_MULT` by 4.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A table word with bit 0 set is an interworking target, not an A32 case,
and was walked at an odd address. The run now ends before it; a run left
shorter than two entries gives no table.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alvistar
alvistar force-pushed the alvistar/kuna-arm-branch-tables branch from a9a70db to 1553c59 Compare November 2, 2026 08:13
mahaloz and others added 5 commits November 2, 2026 08:41
Reconcile exact same-address generic leaves with unique qualified DWARF facts under cppproto. Preserve conflicting identities, existing symbols and unspellable C++ paths.

Add C++/Rust namespace, returned-address and raw-identifier regressions, native execution proofs and a complete changed-function review. Original 675 assertions remain unchanged; all four checks and the six-case speed budget pass.
…space

[AUTOMATED] Preserve qualified DWARF function identities
…S object files (Noelo-Lab#1435)

A PowerPC or MIPS object file (.o) now decompiles with its calls and globals resolved;
before, a `bl`/`jal` still branched to itself or to 0 and data addresses read 0.

PowerPC 32/64: REL24, PLTREL24 (the -fPIC .got2 addend is not part of the target),
LOCAL24PC, ADDR24, the 14-bit branches, the ADDR16*/REL16*/TOC16 halves, and REL32/REL64/
UADDR* words. ELFv1 function symbols, and calls to static functions made against .opd plus
the descriptor's offset, land on the descriptor's code. The TOC base is .toc + 0x8000, or
where the linker's .got would go when the object has no .toc.

MIPS (kuna_mipsreloc.rs): R_MIPS_26, PC16, o32 HI16/LO16 pairing, N64 chained entries,
GPREL16/32 and the GOT forms, resolved against a synthetic GOT and a _gp laid out before the
small data the way the linker does.

Checked against GNU ld linking the same objects at kuna's section addresses. Linked images
and other architectures are unchanged. Part of Noelo-Lab#904.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_0179iMKMUBscgGJBW9XHH5hJ
…allers (Noelo-Lab#1436)

In MIPS PIC code every call to an exported function goes through the GOT, so `bejoin
callers` found no callers and 64-bit returns kept their halves swapped. A `jalr $25` now
counts as a call to the function its GOT entry names, when `$25` came from
`lw $25,%call16(f)(base)` or from a %got page load that `addiu $25,..,%lo(f)` completes.
The load must be the nearest write of `$25` within 8 instructions, with no branch between
and no branch landing between. `base` must hold the GOT pointer the prologue computes from
`$t9` (`$gp`, or clang's saved register), and only reloads from a stack slot the function
saved it to may write it again.

An `lwl`/`lwr` pair into `$3` after a call is a write, not a read. That read had falsely
proven SQLite's `int sqlite3PagerWrite`, `int sqlite3VdbeMemFinalize` and
`void vdbeMemClearExternAndSetNull` 64-bit. Over 216 gcc/clang MIPS PIC images every newly
proven function returns 8 bytes. Non-MIPS and little-endian output is unchanged.

Part of Noelo-Lab#904.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_0179iMKMUBscgGJBW9XHH5hJ
@mahaloz
mahaloz merged commit c5fcb03 into Noelo-Lab:main Nov 2, 2026
2 checks passed
mahaloz added a commit that referenced this pull request Nov 2, 2026
#1399 inserted is_predicated between decode's doc comment and fn decode, so rustdoc gave
decode no description and is_predicated began with decode's text. Comment move only.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_0179iMKMUBscgGJBW9XHH5hJ
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.

2 participants