Skip to content

[AUTOMATED] Reject invalid Thumb switch guards - #1091

Merged
mahaloz merged 29 commits into
Noelo-Lab:mainfrom
ZyphenSVC:fix/thumbswitch-guards
Oct 15, 2026
Merged

mahaloz merged 29 commits into
Noelo-Lab:mainfrom
ZyphenSVC:fix/thumbswitch-guards

Conversation

@ZyphenSVC

Copy link
Copy Markdown
Contributor

Problem

kuna can report jump-table case references for a Thumb switch whose preceding branch does not establish an upper bound on the index. This gives the Listing analysis unjustified control-flow edges and case bodies.

cp decompiler/crates/kuna-analysis/tests/fixtures/thumbswitch_le32 /tmp/kuna-bls.elf
printf '\331' | dd of=/tmp/kuna-bls.elf bs=1 seek=553 conv=notrunc status=none
decompiler/target/release/kuna xrefs /tmp/kuna-bls.elf --from 0x822a --json |
  python3 -c 'import json,sys; print(json.dumps([hex(x["to_address"]) for x in json.load(sys.stdin)["xrefs"]]))'
["0x8232", "0x8238", "0x8240", "0x8244"]

The byte edit changes the fixture’s BHI guard to BLS. After cmp index,#3, BHI default leaves indices 0–3 on the dispatch path; BLS default instead leaves indices greater than 3. The latter cannot establish a four-entry table, so these inferred references should be absent ([]).

Fix

  • Replace the check for which flags a branch reads with an evaluation of its p-code condition. BHI and BLS read the same flags but select opposite index ranges; only the former establishes the required upper bound on fall-through.
  • Retain n + 1 entries for BHI and n for BCS when the taken branch leaves the dispatch path.
  • Require the comparison to supply the relevant carry flag, reject overwritten flags or index registers and intervening control flow, and reject a guard that branches to the dispatch itself. If the bound cannot be established, leave the table unresolved.

Tests

The CLI regressions exercise all 16 narrow Thumb condition encodings and a branch to the dispatch. Before the fix, BCC, BLS, and the dispatch-target case incorrectly recover table entries. After the fix, those cases produce no inferred references, while BCS still recovers three targets and BHI four.

Both regression corpora retain baseline parity. Thumb fixture function discovery also retains byte-identical output, with median timings of 61.5 ms before and 61.1 ms after across 21 runs per version.

ZyphenSVC and others added 29 commits October 14, 2026 09:18
Assembly rendering makes fewer temporary allocations without changing the emitted text. On the million-row x86 control, separate heaptrack runs counted 2,740,005 → 1,740,001 whole-process allocation calls (36.50% fewer). Three ordinary pairs against main `939ab703` showed CPU +1.17% and flat peak RSS, so this makes no speed claim.

```sh
python3 decompiler/crates/kuna-analysis/tests/fixtures/listing_fallthrough.py x86_64 1000000 /tmp/listing.elf
/usr/bin/time -f '%U user %S system %M KiB peak' kuna decompile-all /tmp/listing.elf --mode reliable --functions _start --jobs 1 --json > /tmp/listing.json
```

- Reuse mnemonic and operand scratch storage between assembly callbacks.
- Preserve emitted text, masks, decode context and instance-local ownership.
- Leave persistent Listing storage and public APIs unchanged. The combined API in Noelo-Lab#924 already reuses its buffers; this covers standalone assembly rendering and fallback callers.

On current main `939ab703`, nine instruction-mask tests and 12 combined-decode tests pass, including buffer reuse and long/short output coverage. Spec/layout checks and the release build pass. Complete paired JSON matches. Full workspace and stage suites are deferred to fork PR CI.
)

Phi simplification makes fewer temporary allocations without increasing persistent IR storage. On the pinned eight-function Bash sample, separate heaptrack runs counted 38,615,319 → 31,997,282 whole-process allocation calls (6,618,037 fewer, 17.14%). Three ordinary pairs against main `939ab703` changed median CPU by -0.69% with identical JSON and nearly flat peak RSS; this makes no broad speed claim.

After building Kuna and its specs, run the pinned Bash sample on main and this branch. Count allocations with heaptrack separately from ordinary timing:

```bash
curl -fL 'https://huggingface.co/datasets/noelo-lab/decbench-dataset/resolve/815eb96f130b6d2ef7fa600e04669bf20139bf27/binaries/O2-noinline/bash/bash' -o /tmp/bash.bin
strip --strip-all -o /tmp/bash.stripped /tmp/bash.bin
export KUNA_SPECS="$PWD/specs"
tag=main # use tag=pr in the other checkout
args=(decompile-all /tmp/bash.stripped --jobs 1 --json --max-fn-seconds 60 --addr 0xa20e0 --addr 0x3c0d0 --addr 0xde3f0 --addr 0xad030 --addr 0x76610 --addr 0xe0610 --addr 0xb67a0 --addr 0x3e9c0)
/usr/bin/time -f '%U user %S system %M KiB peak' decompiler/target/release/kuna "${args[@]}" > "/tmp/bash8-$tag.json"
heaptrack --record-only -o "/tmp/bash8-$tag.heap" decompiler/target/release/kuna "${args[@]}" > "/tmp/bash8-$tag-heap.json"
heaptrack_print -f "/tmp/bash8-$tag.heap.zst" -n 1
```

- Keep short expanded-input, marked-output and rewrite lists in local inline-eight buffers; larger lists still spill.
- Clean successful rewrites by iterating copied IDs instead of cloning the list.

On current main `939ab703`, seven W10 tests pass, including nested phis exceeding inline capacity and failure cleanup preserving phis and clearing marks. Spec/layout checks and the release build pass. Complete paired JSON matches. Full workspace and stage suites are deferred to fork PR CI.
…o-Lab#1050)

Decoding makes fewer temporary cursor copies while preserving assembly, p-code and decode context. A varied ARM64 Listing control used 6.05% less median CPU across three fresh-process pairs against main `ccdf0844`; repeated controls had smaller, mixed changes and peak memory stayed flat. Complete JSON matched.

This existing fixture exercises the decoder:

```sh
python3 decompiler/crates/kuna-analysis/tests/fixtures/listing_fallthrough.py aarch64 200000 /tmp/listing.elf
kuna decompile-all /tmp/listing.elf --mode reliable --functions _start --jobs 1 --json
```

- Borrow parser/builder cursors for read-only walkers.
- Detach before navigation so child queries cannot move the parent's position or breadcrumbs.
- Preserve cross-build target context and caller-address semantics without changing public APIs.

On current main `939ab703`, all 227 SLEIGH unit tests and 12 combined-decode tests pass. Spec/layout checks and the release build pass. The full workspace and stage suites also pass in fork PR CI.



Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015sdZpNU5odw5dVyaxeSvvz
…d return conversion (castnarrow) (Noelo-Lab#1089)

castimplied drops a widening that lands in a destination declared with its
type, but every truncation and sign change kept its cast: kuna printed
`v1 = (unsigned int)a0;` into an `unsigned int v1` from a `long a0`,
`*a1 = (char)a0;` through a `char *a1`, `toupper((int)a0)`, and
`return (int)x;` from a function declared `int`. C performs exactly that
conversion at an assignment, a prototyped argument and a return
(C11 6.5.16.1p2, 6.5.2.2p7, 6.8.6.4p3).

The new option castnarrow (P9 cast-policy, default on) leaves out a low
SUBPIECE printed as a cast, a CPUI_CAST between integer types, and the
`(T)name` the partial-variable printer writes for the low piece of a wider
variable, when the value lands whole in a plain assignment to a local or
parameter declared with exactly that spelling, a store through a pointer
printed with that pointee, a type-locked argument of a direct call, or a
return from a function declared that type, and the operand prints as an
integer. Arithmetic and comparison operands, varargs and trial arguments,
destinations of another spelling, bool, enum, float and pointer conversions
keep their casts.

Tests: kuna-cli castnarrow_round_trip prints gcc and clang -O0/-O2 builds
with the option off and on, compiles them beside the source with gcc and
clang at -O0 and -O2, and checks every function computes the same values.
Stage assertions and CLI probes of other options that pinned a narrowing
cast into such a destination now read the new form; subright and boolbyte,
whose assertions read the cast itself, set the option off.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011ib7dvKSnoqFMNwr6Wu6dm
…-Lab#1095)

The declaration pass sorts a function's locals by name, and a plain string
sort puts every two-digit name between v1 and v2: a function with eleven
locals declared `v1, v10, v11, v2, ..., v9`. IDA declares its numbered
locals in number order.

The new option declorder (P9 naming-policy, values natural|name, default
natural) reorders the surviving declarations once their final spellings
are known. `natural` compares digit runs by numeric value and everything
else character by character, with plain string order as the tiebreak, so
the order is total and agrees with name equality. The collapses and the
repeated-name suffixes still run over the name-sorted list, so only the
order of the declaration lines changes; `name` keeps the old order.
It applies to angr-style names, the default: Ghidra-style names carry
hexadecimal offsets (`local_1c`) that a decimal comparison would scramble,
so `namestyle ghidra` keeps the string order.

Tests: tests/stages/kuna-declorder.xml decompiles an authored gcc -O0
function with eleven live locals with no option line, which pins the
shipped default (v1..v11 in order), and with the option set to name (v10
right after v1; same lines, same body). Over 8
stripped decbench binaries under --mode aggressive, 291 of 3,225 functions
change, each only in the order of its declaration lines; 0/675 datatest
assertions move.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011ib7dvKSnoqFMNwr6Wu6dm
…alls it, as far as its analysis recovers its parameters (Noelo-Lab#1084)

An ELF that keeps its symbol table names `main` from its own `.symtab`, but the
declaration comes from the body alone: the elfmainnamed_x86_64 fixture prints
`unsigned int main(int a0,struct_0 *a1)` with `score(a1->field_0x8)` for
`score(argv[1])`.

elfmain now gives such a `main` the runtime's `int main(int argc, char **argv,
char **envp)` without adding or dropping a parameter. The declaration is not
parked on the symbol; the drive locks only the `int` return and leaves the inputs
to their usual recovery. When the inputs the body reads in parameter storage are
exactly the first k of argc/argv/envp, type inference gives each its runtime type
(unlocked, so the next call does not take it as an argument; it holds through
propagation and record synthesis gives way to it) and the recovered parameter
takes its runtime name, all in the one decompile. Anything else (argv or envp read
alone, argc handed on as a whole 64-bit register, a read past the third) is
decompiled again without the declaration and prints the option-off output.
Executables only, including static-pie; DWARF still wins. The stripped path is
unchanged.

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

A signed integer converted to float and then widened to double loses its first rounding. For `value = 16777217`, these SPARC instructions return `16777216.0`, but the printed C returns `16777217.0`.

```sh
p=$(mktemp)
printf '%s' 03000080c500400085a0188281a0192281c3e00801000000 | xxd -r -p > "$p"
kuna decompile "$p" 0x10000 --raw-image --base 0x10000 \
  --target sparc:BE:32:default --mode reliable \
  --assert 'prototype 0x10000 double sub_10000(void)' \
  --assert 'data 0x20000 int value'
rm "$p"
```

Current output:

```c
return (float8)value;
```

It should retain `return (float8)(float4)value;`.

- Preserve integer conversion rounding during cast folding and subfloat lowering.
- Fold only when floating widths match or the first conversion is exact for every signed source integer; traced narrowing also requires exactness at the replacement width.
- Keep precision changes conservative for unsupported formats; no option or new floating-point exception contract is needed.

Tests cover SPARC32 widening, SPARC64 double rounding, later truncation, exact intermediates, and same-width controls. A native x86 roundtrip compares emitted C with both rounding chains using GCC/Clang at O0/O2.

Debian: 48 ELFs, 12 architectures, 10,092 successful function comparisons. Two x87 paths regain spill rounding; three retain extended precision. No new failures or identified regressions; 61 matched timeouts/existing failures excluded.

Paired CPU timing (matched dev opt0 builds): -0.15% unaffected, +6.30% affected (128 functions each).



The integer rounding is option intfloatround (default on; off restores the previous fold). The x87 80-bit format counts 64 significant bits, and SubfloatFlow checks only the precision it narrows to (a constant by its own bits).

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

A call observes a global's new value even though the assembly writes it after the call.

```sh
python3 - <<'PYCODE'
from pathlib import Path
b = bytearray(0x2008)
b[:64] = bytes.fromhex('9de3bfa021000008d1042000d127bffc4000003c01000000d107bffc95a209a02500000cd524a0002700000cd124e004400000740100000081c7e00881e80000')
for at in (0x100, 0x200): b[at:at+8] = bytes.fromhex('81c3e00801000000')
b[0x1000:0x1004] = bytes.fromhex('3f800000')
Path('/tmp/store-order.bin').write_bytes(b)
PYCODE
kuna decompile /tmp/store-order.bin 0x1000 --raw-image --base 0x1000 \
 --target sparc:BE:32:default --mode reliable \
 --define-function 0x1100=get --define-function 0x1200=finish \
 --assert 'prototype 0x1000 void caller(void)' \
 --assert 'prototype get float get(void)' --assert 'prototype finish void finish(void)' \
 --assert 'data 0x2000 float input' --assert 'data 0x3000 float result' \
 --assert 'data 0x3004 float after'
```

Current output:
```c
v1 = input;
after = v1;
result = v1 / get();
finish();
```

- Keep a memory-loaded global store's COPY when its only use is a same-location marker input.
- Keep the write after the observing call. Retaining the COPY also captures vector-load halves before overlapping writes.
- Leave ordinary/shared readers and non-LOAD inputs unchanged; the computed-value control stays ordered. This strict memory-order fix needs no option.

Fixed order: `result = v1 / get(); after = v1; finish();`.

SPARC32 stages cover call and loop markers plus a no-later-call control. GCC/Clang O0/O2 executions check an impure getter, a computed-value control and overlapping x86-64 SIMD reads.

Existing assertions remain 675/675; stages pass 2,849/2,849. Debian: 48 ELFs, 12 architectures, 10,153 functions, 15 shared decompilation failures; six load-order repairs, one storage-comment change, no other output changes. No slowdown measured: opt1 median CPU −3.22% on 48 controls and −20.15% on seven affected functions (five alternating pairs each, under load; not release throughput).



The new refusal is option globalcallstore (default on; off restores the previous propagation) and runs only at indexaliasguard global, the one level that keeps a load ahead of an intervening global store.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015sdZpNU5odw5dVyaxeSvvz
…lo-Lab#1069)

Known library calls in ELF relocatable objects lose their standard prototypes when imports have the usual `STT_NOTYPE` metadata. This wrapper consequently loses its pointer parameter and return type:

```sh
cat > /tmp/clear.c <<'C'
extern void *memset(void *, int, unsigned int);
void *clear(void *p) { return memset(p, 0, 168); }
C
clang --target=sparc-linux-gnu -O0 -fno-builtin -c /tmp/clear.c -o /tmp/clear.o
kuna decompile /tmp/clear.o clear
```

Current output:
```c
unsigned int clear(unsigned int a0)
{
  return memset(a0,0,0xa8);
}
```

Fixed output:
```c
void * clear(void *a0)
{
  return memset(a0,0,0xa8);
}
```

- Reuse the loader's proven ELF code imports for existing library signatures, including exact synthetic call-target addresses.
- Preserve linked-image matching and import/definition ambiguity checks; exclude data-only references.
- Keep existing signature options: this repairs missing authoritative prototype metadata, with no new argument-inference policy.

Generated ELF tests cover SPARC32/x86-64 pointer parameters and returns, real x86 addend −4, text-section data-address relocations and versioned name collisions. ELF loader behavior needs an object-based console test; XML stages do not reach this path.

Compiler-built controls: 12 corrected calls across six ABI variants; all 32 data-address controls unchanged. Matched development builds: median CPU +0.93% over five alternating runs (12 functions per run).

Debian linked-ELF controls: 10,133 matching successful functions from 48 executables on 12 architectures; 20 matching errors excluded, no stable output changes.



The relocatable-object evidence is governed by the existing libproto, libcsigs and libctypes options: with the three off, an object decompiles as before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015sdZpNU5odw5dVyaxeSvvz
…proof it is one wide value (bejoin evidence) (Noelo-Lab#1062)

## The problem

On big-endian 32-bit targets a 64-bit value returns with its HIGH word in the first register, but kuna joins the pair the other way by default, so the value prints with its halves swapped (the SPARC functions are Noelo-Lab#815's repro):

```sh
cat > widen.c <<'EOF2'
void ext(void);
long long widen(int x) { ext(); return x; }
unsigned long long uwiden(unsigned x) { ext(); return x; }
long long wide_mul(int a, int b) { return (long long)a * b; }
EOF2
clang --target=sparc-linux-gnu -fintegrated-as -O2 -c widen.c -o w_sparc.o
clang --target=powerpc-linux-gnu -O2 -c widen.c -o w_ppc.o
kuna decompile-all w_sparc.o --functions widen,uwiden
kuna decompile w_ppc.o wide_mul
```
```c
// Function: widen @ 0x400000
unsigned long long widen(int a0)
{
  ext();
  return CONCAT44(a0,a0 >> 0x1f);
}

// Function: uwiden @ 0x400018
long long uwiden(unsigned int a0)
{
  ext();
  return (unsigned long long)a0 << 0x20;
}

unsigned long long wide_mul(int a0,int a1)
{
  return CONCAT44(a1 * a0,(int)((unsigned long long)((long long)a1 * a0) >> 0x20));
}
```

`--option bejoin on` fixes these, but it guesses from the instructions and also turns a correct `int` over the high half of a 64-bit temporary into a wrong `long long` (Noelo-Lab#904).

## The fix

- `bejoin` takes `off|evidence|on`. The new default, `evidence`, joins a pair high word first only when the function's own instructions prove one wide value at every RETURN: a sign extension (`mr 4,3; srawi 3,3,31`), a zero extension (a literal zero beside a value the function computed or moved there), or the two halves of one product whose low half an instruction of its own made (PowerPC `mullw` beside `mulhw`, MIPS `mflo`). Loads, a register's own entry value, by-products and values anything else reads prove nothing, on any path, one ending in `exit` included (gcc -Os computes an exit argument in a branch delay slot beside `return 0`).
- The verdict is a property of the callee alone, taken from its p-code before any decompile and cached per image, so a function's RETURN and every call to it agree whatever the decompile order (`--functions`, `--jobs`, a single `kuna decompile`). A call resolved only mid-decompile (`-mlong-calls`, a constant function pointer) to a proven callee sends the caller through the pipeline again with that verdict. A caller that reads only the first register of a proven callee reads its high word.
- Bytes an `int` can share with the `long long` keep today's join, which C's truncation reads as the right `int`: `umull r1,r0`, `addc/adde` sums, `a / 641`, MIPS gcc -O0's `>> 32`, a volatile read beside `return 0`. Those `long long`s, loads of both words and returned call results still print swapped unless the return type is declared (DWARF or `--assert prototype`, which already join right).

The repro then prints `long long widen(int a0)` and `unsigned long long uwiden(unsigned int a0)` returning `a0`, and `wide_mul` as the full product.

## The tests

- `tests/stages/kuna-bejoin-evidence{,-sparc,-armeb}.xml`: each case in the default, then `bejoin off` (Noelo-Lab#815's functions, PowerPC `wide_mul`, extensions, a declared `long long`, and the `int` negatives `(int)((a+b)>>32)`, ARM `((u64)a*b)>>32`, a volatile read). The default pass fails on main.
- `bejoin_evidence_reads_a_callee_pair_alike_in_every_run` (kuna-cli): callers placed before their callees and a self-recursive function, on PowerPC, SPARC and MIPS (one MIPS image built `-mlong-calls`), taken from `decompile-all`, `--functions`, `--jobs 2` and `kuna decompile`, compiled with their callee and run against the source. `a_value_only_a_no_return_path_reads_proves_nothing` does the same for the `exit` shape in a linked MIPS image.
- The issue's shapes and Noelo-Lab#763's sources on PowerPC, SPARC, ARM big-endian and MIPS at -O0 to -Os, printed C compiled and run against the source: 374 function builds go from wrong to right and none from right to wrong; with callers placed before their callees, 66 do in each of the four run modes, again none the other way. In 698 big-endian objects of 13 projects plus SQLite and zlib, only 64-bit functions change; 8,692 generated `int` functions that call `exit`, `abort` or `longjmp` on one path (36 builds for the four targets at -O1 to -Os) do not change; little-endian output is byte-identical.
- Speed, both within noise: -0.4% (interleaved min-of-11 `decompile-all` over gzip, kmod, grep, ls and bash's `subst.o` for PowerPC, SPARC, ARM big-endian and MIPS); -2.3% on a 1.4 MB PowerPC SQLite object (min of 3). Peak memory on SQLite objects: 254 MB before and after on PowerPC, 214 MB and 216 MB on MIPS.

Part of Noelo-Lab#904

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_015sdZpNU5odw5dVyaxeSvvz
)

A type directive that kept a local's width and kind could still split the
local: the definitions the new type did not reach came back as a new vN, and
the type could spread through copies into other locals. Such a retype is now
carried like a name-only rename and locked on every instance of the printed
variable after the merge, before casts are placed; a stack slot read whole and
by halves takes it on its whole. Enumeration, bool and character types also
type the constants the variable is assigned, compared or combined with. A
pointer to a structure, union, array or function is locked before inference on
the variable's own definitions, and the merge follows the first decompile's
variables. An address-only local's stack Symbol takes the type.

A name or type the printed C does not show for the variable the directive
reached is reported refused with the reason, never applied; a name the printer
had to suffix is applied, with a detail saying what it printed. The page
announces a refused change once. A local name that is a C keyword or a type's
name is rejected. In the console, a renamed DWARF local keeps its Symbol across
decompiles.

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

gcc up to version 9 (at -O1 and above) and older MSVC expand strlen(s)
inline as `or rcx,-1; xor eax,eax; repnz scasb; not rcx`. SLEIGH lifts
the repeat prefix as a loop inside the one instruction, so kuna printed
an eight-line do/while over the string and `~v3 - 1` wherever the length
was used, where IDA prints strlen(s).

The new option strlenscan (P3, default on) matches the two blocks the
instruction lifts to once mainloop has settled them, and proves the loop
is a string length: the count enters as all ones and the head leaves
exactly when it is zero; the body steps the count down and the pointer
up by one, reads one byte, computes nothing else with side effects, and
loops exactly while that byte is not zero (checked for all 256 values,
which proves the byte searched for is zero); nothing after the loop reads
the count except through a NOT. It places `len = strlen(s)` (a typed
builtin user-op) in the body, gives every value the loop hands on its
final-iteration value (count ~(len + 1), pointer s + len + 1, the byte
zero), and removes the never-taken zero-count exit and the back edge, for
every scan of a function in one pass. The builtin keeps CALLOTHER's call
flag, since its value depends on memory: it is ordered like a call, so a
strlen stays where its scan was, ahead of a store, call or free that
follows, and is never duplicated into several readers or merged across a
join. A scan for another byte, one
whose raw count is read, one counting from another start and one stepping
backward keep their loops.

Tests: tests/stages/kuna-strlenscan.xml runs gcc 9 -O1 functions with no
option line (strlen; a length taken before a following store, before a
following call, once for an inlined strcat, once on each side of a join;
two non-length scans still loops) and with the option off (every scan a
loop). kuna-cli strlenscan_round_trip prints gcc 9
-O1/-Os x86-64 and -O1 i386 builds with the option off and on and compiles
the x86-64 ones beside the source under gcc and clang at -O0 and -O2,
checking every function computes what the source does, with buffers
whose bytes past the terminator are not zero. Over 8 stripped decbench
binaries (gcc 11) the output is byte-identical; over 29 Ubuntu 20.04
gcc 9 binaries 52 of 11,000 functions change, each gaining strlen at its
scan's own position; 0/675 datatest assertions move.

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

A local that holds a library call's result, or that is handed to one
whole, kept a vN although kuna's own libc tables type the call:
`v1 = open(a0,0); v3 = read(v1,v4,0x200);`.

The libc tables now carry glibc's declared parameter names (leading
underscores stripped, read from the headers by
docs/features/libcnames/gen_names.py) and a conventional result name
where the result is one kind of thing (fd, n, len, p, fp, pid, tp, ...),
on the prototype they park but outside innames, so the callee's
signature and name locks do not change. The new P6 option libcnames
(default off, on under --mode aggressive) prints a numbered local under
the name of its strongest evidence: a call's return value (when every
library result it holds agrees), then a whole argument whose name says
what the value is, then a role name (dest/src, s1/s2) only when every
such name agrees. A name equal to a printed type or a C or Rust keyword
is skipped; clashes take _2, _3 in call order past every printed name
and every global the program names.

The library name is a second name for the local's number: the walk
numbers every local as with the option off, records that numbering,
and only then applies the names, so vN identity is the same in every
mode. A directive reaches the local by either name and a replay records
the number; a name a rename gave stays even when it is shaped like a
number; a local whose library name a rename took prints its number; a
vacated name goes to no one; and the check that an applied directive is
visible counts a declaration under the library name for the number.

Tests: tests/stages/kuna-libcnames.xml, kuna-cli library_names (renames,
retypes by either name, mode switches, displaced names, number-shaped
renames, globals, keywords, and a compile-and-run of tp beside the
typedef tm), the wasm and browser rename and mode-switch flows, and unit
tests. Round-trip tests and seven CLI probes of other options read the
new names; the ghidra-sim differential runs its CLI side with the option
off. Over 14 stripped decbench binaries under --mode aggressive, 968 of
10,106 numbered locals print a library name in 546 of 3,297 functions,
only names changing; 0/675 datatest assertions move. Default off because
six stage assertions of other features spell a vN it names.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011ib7dvKSnoqFMNwr6Wu6dm
…oelo-Lab#1022)

The alias-only analysis emits the caller's saved XMM lanes as live stack locals even though the helper updates a separate caller-owned rectangle. The same Clang `-O0` input produces:

```c
/* before */
unsigned int v18; // stack - 0x48 | xmm6_da
/* ... */
unsigned int v33; // stack - 0xc | xmm9_dd
/* after */
Rect v1 [2]; // stack - 0x68 | xmm0_da
fixture_copy_rect(v1,&rect_source);
return v1[0].x + v1[0].y;
```

The [neutral fixture, build command, and decompile assertions](https://github.com/mgostIH/kuna/blob/fix/lifetime-private-spills/docs/features/lifetimes/README.md#reproducing-disjoint-private-spills) reproduce this output.

- Retain exact pointer-width private spills only when every summarized write is disjoint from every retained cell at the call site.
- Protect frame-derived return-target reads from stores overlapping the ABI return slot, and preserve frame provenance through flag-only scratch.
- The saved-XMM regression checks the native result and all sixteen lanes, observer controls, and generated-C round trips; focused callee tests cover unknown and partial aliases, flag publication, and return-slot cases.

Validation: `cargo test --manifest-path decompiler/Cargo.toml -p kuna-cli --test integration saved_xmm_msabi::` and `cargo test --manifest-path decompiler/Cargo.toml -p kuna-decomp --lib kuna_callee`.

Both focused checks pass (183 selected unit tests and the native/generated-C regression).
…elo-Lab#1023)

With stack views enabled, a detached frame value can keep an integer declaration while a later member operation uses it as a node pointer. The unpatched output fails C compilation:

```text
v1 = v3->sentinel;
error: invalid type argument of ‘->’ (have ‘uint8’ {aka ‘unsigned long’})
```

The patched expression is `v1 = ((Node *)v3)->sentinel;`. For a pointer-slot access it similarly changes `&v5->left` to `&((Node *)v5)->left`, casting only the member base.

The standalone repro is in `docs/features/lifetimes/README.md` (Reproducing detached member emission). The [CLI regression](https://github.com/Noelo-Lab/kuna/blob/main/decompiler/crates/kuna-cli/tests/stack_object_lifetimes.rs) validates the fix; run it with:

```sh
cargo test --manifest-path decompiler/Cargo.toml -p kuna-cli --test integration stack_object_lifetimes::tree_range_members_use_the_pointer_type_of_each_native_access
```

- The member base is cast only when its same-width declaration disagrees with the operation’s pointer type; stored snapshots and byte arithmetic keep their existing representations.
- The focused test passes 1/1. Its native and emitted-C checks cover GCC and Clang at `-O0`/`-O2`, with stack views enabled and disabled. In the same-fixture A/B probe with stack views enabled, GCC and Clang reject the refreshed baseline at both optimization levels; the candidate compiles and runs all four combinations.
…Lab#1047)

Building a Listing currently parses each instruction again to capture its assembly. Using the existing combined translator API preserves the text and p-code while reducing decoder work.

```sh
python3 decompiler/crates/kuna-analysis/tests/fixtures/listing_fallthrough.py aarch64 200000 /tmp/listing.elf
kuna decompile-all /tmp/listing.elf --mode reliable --functions _start --jobs 1 --json
```

Three fresh-process pairs against main `ccdf0844` measured median CPU reductions of 25.5% on a varied ARM64 fixture and 27.7% on repeated x86. These are decoder-heavy controls, not estimates for overall decompilation speed; complete JSON matched.

- Capture Listing assembly through the combined API added in Noelo-Lab#924.
- Preserve generic translator fallback, context/delay handling and public String/Vec fields.
- Do not render assembly after a failed lift.

On current main `939ab703`, 110 Listing tests and five serial/parallel decode checks pass, including image-read and failure regressions. Spec/layout checks and the release build pass. The full workspace and stage suites also pass in fork PR CI.
…oelo-Lab#1048)

Large Listings retain less address-index memory while keeping exact, ordered and range queries unchanged. Three fresh-process pairs against main `ccdf0844` reduced median peak RSS from 337.39 to 316.96 MiB on a generated million-row x86 control; complete JSON matched.

```sh
python3 decompiler/crates/kuna-analysis/tests/fixtures/listing_fallthrough.py x86_64 1000000 /tmp/listing.elf
/usr/bin/time -f '%U user %S system %M KiB peak' kuna decompile-all /tmp/listing.elf --mode reliable --functions _start --jobs 1 --json > /tmp/listing.json
```

- Group sorted address/row pairs into private 4 KiB address buckets.
- Restrict range iteration to relevant buckets and boundary rows.
- Preserve indexed keys when a record's address field is mutated, replacement behavior, reverse iteration and public field types.

On current main `939ab703`, all 112 Listing tests pass, including a BTreeMap range oracle and extreme/sparse bounds. Spec/layout checks and the release build pass. The full workspace and stage suites also pass in fork PR CI.
…oelo-Lab#1049)

ARM frame recovery can retain duplicate instruction payloads while rebuilding a Listing. Three fresh-process pairs against main `ccdf0844` reduced median peak RSS from 151.67 to 113.80 MiB on a scaled A32 inventory, and from 174.94 to 161.29 MiB on a firmware inventory. Complete inventory JSON matched; U-Boot's process peak stayed flat.

This existing fixture exercises the rebuild:

```sh
python3 decompiler/crates/kuna-analysis/tests/fixtures/arm_frame_retain.py /tmp/frame.elf
kuna functions /tmp/frame.elf --json --jobs 1 --mode reliable --option armframes on
```

- Share immutable 1,024-row chunks between store snapshots.
- Copy only a touched chunk before mutation, replacement or partial-tail append.
- Preserve snapshot independence and bounded capacity; the address index is still copied, and public field types stay unchanged.

On current main `939ab703`, 109 Listing tests pass, including nested clones and payload isolation. Spec/layout checks and the release build pass. ARM frame recovery remains default-off. The full workspace and stage suites also pass in fork PR CI.
…oelo-Lab#1052)

No-return analysis avoids temporary per-function instruction-reference lists and address indexes. Three fresh-process pairs against main `939ab703` reduced median peak RSS from 337.81 to 319.03 MiB on a generated million-row x86 control; complete JSON matched.

```sh
python3 decompiler/crates/kuna-analysis/tests/fixtures/listing_fallthrough.py x86_64 1000000 /tmp/listing.elf
/usr/bin/time -f '%U user %S system %M KiB peak' kuna decompile-all /tmp/listing.elf --mode reliable --functions _start --jobs 1 --json > /tmp/listing.json
```

- Borrow bounded instruction ranges for argument and reachability scans.
- Preserve conservative clobber handling, function boundaries and contiguous fall-through requirements; argument scans retain their existing handling of address gaps.
- Leave public field types unchanged.

On current main `939ab703`, 17 analyzer regressions and three console checks pass, including gaps, boundary isolation and argument clobbers. Spec/layout checks and the release build pass. Complete paired JSON matches. The full workspace and stage suites also pass in fork PR CI.
…#1056)

Region construction makes fewer temporary allocations while preserving its traversal order and dominators. On the pinned `crond` sample, separate heaptrack runs counted 5,948,267 → 5,510,184 whole-process allocation calls (438,083 fewer). Three ordinary pairs against main `939ab703` changed median CPU from 3.125 to 2.979 seconds (-4.67%), with identical JSON and nearly flat RSS.

After building Kuna and its specs, run this on main and this branch. Use heaptrack separately to count allocations:

```sh
curl -fL 'https://huggingface.co/datasets/noelo-lab/decbench-dataset/resolve/815eb96f130b6d2ef7fa600e04669bf20139bf27/binaries/O2-noinline/cronie/crond' -o /tmp/crond.bin
strip --strip-all -o /tmp/crond.stripped /tmp/crond.bin
export KUNA_SPECS="$PWD/specs"
tag=main # use tag=pr in the other checkout
/usr/bin/time -f '%U user %S system %M KiB peak' decompiler/target/release/kuna decompile-all /tmp/crond.stripped --jobs 1 --json --max-fn-seconds 60 > "/tmp/crond-$tag.json"
heaptrack --record-only -o "/tmp/crond-$tag.heap" decompiler/target/release/kuna decompile-all /tmp/crond.stripped --jobs 1 --json --max-fn-seconds 60 > "/tmp/crond-$tag-heap.json"
heaptrack_print -f "/tmp/crond-$tag.heap.zst" -n 1
```

- Reuse sorted successor scratch and borrow predecessor slices.
- Keep dominator state in graph-local reachable-node order; preserve the caller's ordered map and unrelated entries.
- Use hash tables only for lookup/membership state, preserving deterministic output ordering.

This complements Noelo-Lab#1035's structurer retry fix. On current main `939ab703`, 20 graph tests pass, including an independent path-removal dominator oracle over cyclic graphs and reversed edge order. Spec/layout checks and the release build pass. Complete paired JSON matches. Full workspace and stage suites are deferred to fork PR CI.
`kuna catalog` now reads the linked engine's static catalog in-process by default, with no
console subprocess and no specs:

```sh
mkdir -p /tmp/kuna-catalog-only && cp decompiler/target/release/kuna /tmp/kuna-catalog-only/
(cd /tmp/kuna-catalog-only && env -u KUNA_DECOMP_DBG KUNA_ROOT=/tmp/kuna-catalog-only ./kuna catalog --check)
# catalog OK: documents exactly the registered kuna options
```

Output (stdout, stderr, exit code) is byte-identical to the external console path for every
flag combination; `catalog --json` drops from two process starts to one (33 ms -> 23 ms).

- Read the linked engine's static catalog by default; no console or specs needed.
- Preserve external queries selected by `--decomp-dbg` or non-empty `KUNA_DECOMP_DBG`,
  including precedence, diagnostics and legacy flags; a set but missing `KUNA_DECOMP_DBG` is an error.
- Keep text/JSON rendering, tier filters and Markdown behavior unchanged; check the selected
  catalog against this CLI build's registrations.
- `catalog_cli` runs as its own test binary with serialized copies/spawns (it copies and runs
  `kuna`, which raced with sibling tests' forks: ETXTBSY).

Tests cover standalone installs, an unselected sibling that must not run, byte-identical
local/external output, missing overrides, flag precedence and external catalog drift.
…elo-Lab#1070)

A call after a wide return uses the old return halves instead of the registers the caller just wrote. Reading an incoming register pair can also lose a function’s pointer argument when its own prototype is unknown.

```sh
python3 - <<'PY'
from pathlib import Path
image = bytearray.fromhex('9de3bf0090100018921000194000003d01000000d03fbff8a407bf3092102000941020a8901000124000007601000000f03fbff881c7e00881e80000')
image.extend(bytes(0x208 - len(image)))
for offset in (0x100, 0x200):
    image[offset:offset+8] = bytes.fromhex('81c3e00801000000')
Path('/tmp/call-pair.bin').write_bytes(image)
PY
kuna decompile /tmp/call-pair.bin 0x1000 --raw-image --base 0x1000 \
 --target sparc:BE:32:default:default --define-function 0x1100=producer \
 --define-function 0x1200=sink \
 --assert 'prototype producer unsigned long long producer(unsigned int a,unsigned int b)' \
 --assert 'prototype 0x1000 unsigned int caller(unsigned int a,unsigned int b)'
```

Current output:
```c
v2 = producer(a,b);
v1 = (unsigned int)(v2 >> 0x20);
v3 = (unsigned int)v2;
sink(v1,v3,0xa8);
```

With this change, the call is `sink(v1,0,0xa8)`, where `v1` addresses the local frame; no `sink` prototype is required.

- Add `multiregargs` (default on) to recover separate integer argument slots when a wider register range exactly covers them, at every `calloverlap` level.
- Apply the same recovery to incoming arguments when the ABI accepts the separate slots but not the whole range. Preserve declared wide inputs and uncertain storage. Off disables both changes.

`kuna-register-pair-call-args.xml` shows the stale arguments with the option off and the corrected call by default. Tests cover overwritten halves, delay slots, declared wide parameters and both byte orders; seven Clang math wrappers with unknown owner prototypes recompile under GCC/Clang O0/O2 and retain their pointer arguments, calls and numeric results.

Debian comparison against main `4aac7a27`: 48 ELFs, 12 architectures, 10,153 functions; three SPARC32 argument-recovery changes confirmed against disassembly, with no new errors or unstable differences. Five paired CPU measurements: +0.59% on 21 unaffected functions, −19.66% on two affected Debian functions and −4.88% on seven wrappers.
…ab#1085)

Adds public, adjustable fixtures for investigating huge-function memory use:

```sh
python3 scripts/huge_function_bench.py --out /tmp/kuna-escaped \
  --shape escaped-locals --blocks 100 350 700 \
  --kuna decompiler/target/release/kuna --seconds 10 --memory-mib 512
```

- Generates escaped-stack and branch-heavy workloads.
- Records peak RSS, elapsed/CPU time, diagnostics, and reproducibility metadata.
- Documents measured memory-limit behavior and a P8 structuring slowdown.

Related to Noelo-Lab#1034. This adds investigation tooling; it does not establish a fix for the private binary.

Tests: `scripts/tests/test_huge_function_bench.py` (run by `make test-tools`) covers a failing child's exit status and stderr, the external deadline kill, and reaping the child on interrupt.
…ab#1087)

A branch-heavy function can remain in region structuring past its one-second budget. Generate a standalone repro:

```sh
python3 - <<'PYCODE'
from pathlib import Path
from struct import pack
code = b'\x89\xf8'
for i in range(1000):
    code += b'\xa9' + pack('<I', 1 << (i % 16)) + b'\x74\x0b\x69\xc0'
    code += pack('<I', 3 + 2 * (i % 61)) + b'\x05' + pack('<I', i + 1)
    code += b'\x35' + pack('<I', i + 1)
Path('/tmp/p8.bin').write_bytes(code + b'\xc3')
PYCODE
timeout 12 kuna decompile-all /tmp/p8.bin --raw-image --target x86:LE:64:default \
  --base 0x1000 --entry 0x1000 --json --max-fn-seconds 1 --option regionstructure on
echo $?
# Before: 124
```

The folding loops now check the function's time/memory budget each round. Exhaustion returns the normal per-function error and skips fallback structuring, so the batch can continue.

Tests cover an expired budget leaving a graph unfolded and a generated 1,000-branch function timing out while the next function still decompiles. The repro stops in about 1.4 seconds after the fix. Seven alternating release-build pairs preserved full JSON output: median CPU time was 4.709 → 4.787 s for sort (490 functions), and 9.309 → 9.356 s for grep (449 functions). A 15-pair synthetic-fixture repeat measured 0.267 → 0.267 s. These measurements do not establish zero overhead.

Validation: datatest and stage parity, workspace tests, tooling tests, spec checks, and Clippy passed.

Related to Noelo-Lab#1034; follow-up to the benchmark in Noelo-Lab#1085.
…#1088)

Varnode ordered-index maintenance is the largest CPU category on ordinary binaries (about 30% of self cycles on the DecBench nightly sample), and roughly 90% of created Varnodes are destroyed again soon after. A census on main `edba0094` showed that fewer than 1% of retired Varnodes are ever reached through the definition index (0.90% on dash/ssh-add/find/man2html/bzip2, 0.67% on Bash), while the location index is used by about 62–66% of them. This change keeps the location index as is and stops maintaining definition-index entries that are never needed.

Against main `edba0094`, with complete JSON identical on every measured binary (user-space instructions from hardware counters; CPU is the sum of per-binary medians over 3 fresh pairs):

| Set | Binaries | Instructions | CPU | Peak RSS (sum) |
|---|---:|---:|---:|---:|
| ordinary x86-64 (dash, ssh-add, find, man2html, bzip2) | 5 | −8.16% | | −10.2% |
| 12 costliest nightly-sample binaries (bash, ssh, u-boot, betaflight, …) | 12 | −9.06% | −8.42% | −7.9% |
| small (dpkg-divert, gzip, x0r-usb) | 3 | −7.19% | | −4.9% |

Repro on one public binary (DecBench dataset, O2-noinline):

```sh
curl -fL 'https://huggingface.co/datasets/noelo-lab/decbench-dataset/resolve/815eb96f130b6d2ef7fa600e04669bf20139bf27/binaries/O2-noinline/dash/dash' -o /tmp/dash.bin
strip --strip-all -o /tmp/dash.stripped /tmp/dash.bin
export KUNA_SPECS="$PWD/specs"
perf stat -e instructions:u decompiler/target/release/kuna decompile-all /tmp/dash.stripped --jobs 1 --json --max-fn-seconds 600 > /tmp/dash.json
```

Main: 51.59 G instructions; this branch: 48.27 G (−6.4%), same JSON.

- Free Varnodes no longer occupy the definition tree; definition-order iteration over free nodes is derived from the location index, so every consumer sees the same order as before.
- Location keys pack signed size and class ordering into one prefix; a node changing class reuses its immutable address/size snapshot, and birth keys are built directly. One cached snapshot serves both orders, which also covers Noelo-Lab#1053 (`Varnode` 336 → 264 bytes).
- Immediate teardown removes the indexed snapshot without first inserting a temporary free entry.
- Preserved: combined class masks, signed bounds, SeqNum's uniq-only equality, creation order, stable ids and error paths. `docs/spec/00-overview.md` is updated.

Checks: 127 focused tests pass (varnode units 52, funcdata_op units 49, `verify_w3_ir_varnode` 6, `verify_w3_ir_funcdata_varnode` 10, `verify_w3_ir_funcdata_op` 10), including new comparator, range, snapshot and teardown cases; test layout, `make check-spec` and diff checks pass. The branch merges cleanly onto current main; the full workspace and stage suites are left to PR CI.
…ab#1054)

Large Listings avoid retaining a separate allocation for each repeated mnemonic. Three fresh-process pairs against main `939ab703` reduced median peak RSS from 337.96 to 299.85 MiB on a generated million-row x86 control; complete JSON matched.

```sh
python3 decompiler/crates/kuna-analysis/tests/fixtures/listing_fallthrough.py x86_64 1000000 /tmp/listing.elf
/usr/bin/time -f '%U user %S system %M KiB peak' kuna decompile-all /tmp/listing.elf --mode reliable --functions _start --jobs 1 --json > /tmp/listing.json
```

- Intern immutable mnemonic text per serial store or parallel decode lane, with no global lock; empty text needs no allocation.
- Capture shared text directly from the assembly callback. Operands remain owned strings and public `Decoded` fields remain `String`.
- Public field migration: `Insn.mnemonic` and `InsnLite.mnemonic` become `Mnemonic`; constructors use `.into()`, readers use `as_str()` or deref coercion.

The Listing walk's interning capture uses Noelo-Lab#1047's combined translator path (`one_instruction_with_assembly`) when assembly is wanted.

On main `939ab703`, 111 Listing tests and 11 decoder/context/parallel console checks pass, including pool lifetime, lane isolation and the layout-aware memory-cap fixture. Spec/layout checks and the release build pass. Complete paired JSON matches. Fork CI passes both parity gates and the complete Cargo workspace suite.
…elo-Lab#1090)

## Problem

A newline between a declaration's type and declarator panics. A final newline also makes an otherwise valid declaration fail to parse.

```sh
printf 'extern int4\nexample(void);\n' > /tmp/kuna-declaration.c
printf '%s\n' 'load file integrations/web/test/fixtures/sample.elf' \
  'parse file /tmp/kuna-declaration.c' quit | \
  decompiler/target/release/decomp_dbg -s specs
```

```text
range end index 18446744073709551615 out of range for slice of length 65537
```

## Fix

- Size lexer scratch storage to the input, retaining the 65,536-byte line limit and EOF lookahead slot. In a 100,000-declaration benchmark, requested allocation volume fell 97.6% and median parse time fell 27%.
- Extract a pending token before resetting its line buffer; reject unfinished quoted tokens cleanly.
- Treat EOF after whitespace or a completed comment as the end of input.

## Tests

Adds multiline declarations, trailing whitespace/comments, buffer reuse and line-limit cases, plus 29,524 short-input/limit combinations. The multiline declaration panics without the fix; the trailing-newline case is rejected.
@mahaloz
mahaloz merged commit e0adc31 into Noelo-Lab:main Oct 15, 2026
2 checks passed
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.

5 participants