Skip to content

[AUTOMATED] fix(p8): (NOVEL) print the entry component first (DIV-48) - #235

Merged
mahaloz merged 3 commits into
mainfrom
fix/finalorder-entry-first
Aug 1, 2026
Merged

mahaloz merged 3 commits into
mainfrom
fix/finalorder-entry-first

Conversation

@mahaloz

@mahaloz mahaloz commented Aug 1, 2026

Copy link
Copy Markdown
Contributor

What

Port BlockGraph::orderBlocks (upstream block.hh:437) and call it where upstream calls it —
the first line of ActionFinalStructure::apply (blockaction.cc:2192). It was an explicit
STUB.

Structuring does not always end with a single top-level component: an irreducible knot, a
multi-entry loop, or a switch whose arms could not be folded leaves the root sblocks graph
holding several siblings, and the printer walks that component list in order. kuna had never
ported the sort that puts the list in final order, so it stayed in collapse order —
whichever component the collapse happened to append first printed first. A function could
therefore open in the middle of its body and reach its real entry only after an unconditional
goto, i.e. emit its entry as unreachable dead code.

The producer of the ordering key was already ported (BlockGraph::add_block keeps a
composite's index at the minimum over its members), so only the sort was missing — this
turned out to be exactly the "the sort is missing" case, not a representation problem.

Strict bug fix restoring upstream behavior, no option (the current output is unambiguously
wrong C, and the datatest corpus does not move).

Before / after — libopencm3 sdram main (the campaign case)

Before (--mode auto, today's main): the body opens on the 'p'/'P' command handler, and
the real entry is emitted after an unconditional goto, unreachable:

void sub_800072c(void)
{
  ...
label_8000986:                       // FUNCTION ENTRY LANDS HERE
  sub_80002c8(dat_8000a18);          // the 'p'/'P' handler ("Previous ")
  v2 = sub_8000260(1);
  ...
  v3 -= 0x100;
  sub_80006fc(v3,0);
  goto label_8000792;                // unconditional, no fallthrough
  sub_80003d0();                     // REAL ENTRY, now UNREACHABLE
  sub_8000304();                     // clock_setup / console_setup / sdram_init
  sub_80003fc();
  sub_80002c8(dat_80009e8);          // "SDRAM Example.\n"
  ...
label_8000792:
  sub_80002c8(dat_80009f4);          // "CMD> "
  switch(sub_8000260(1)) { ... }

After — entry first, no leading goto, and the 'p'/'P' handler is where the switch reaches
it:

void sub_800072c(void)
{
  ...
  sub_80003d0();
  sub_8000304();
  sub_80003fc();
  sub_80002c8(dat_80009e8);
  sub_80002c8(dat_80009ec);
  sub_80006fc(0xd0000000,0);
  for (v4 = 0; v4 <= 0xff; v4 = v4 + 1) {
    *(char *)(v4 + -0x30000000) = (char)v4;
  }
  sub_80002c8(dat_80009f0);
  v3 = sub_80006fc(0xd0000000,0);
label_8000792:
  sub_80002c8(dat_80009f4);
  switch(sub_8000260(1)) { ... }

Judged against the source (.../O0/libopencm3/compiled/sdram.i:3829) end to end, not just the
first lines: the emitted body is now the source's shape — prologue, the three initializer
calls, the two banner console_puts, dump_page, the 0..255 fill loop, the second banner, the
second dump_page, then the while (1) command loop with the f/n/p/? arms and the
nested per-arm dispatch. The before and after texts are an exact permutation of each other
(identical line multiset), so nothing was added, dropped or rewritten — only the order of the
top-level pieces. Ghidra's and IDA's stored panes
($R/O0/libopencm3/decompiled/{ghidra,ida}_sdram.c) open with the same three entry calls.

What the port actually does

  • substrate/block.rs (BlockGraph::order_blocks) — upstream's key
    (FlowBlock::compareFinalOrder, block.cc:709): entry component (index == 0) first,
    RETURN-terminated components last, everything else by ascending index (the reverse-post-order
    number). Root graph only — upstream does not recurse; nested components already carry
    their schema's own order.
  • substrate/block.rs (BlockGraph::struct_last_op_with) — FlowBlock::lastOp gains its
    missing t_copy (block.hh:546) / t_goto / t_multigoto (block.hh:576/604)
    overrides, so the RETURN half of the key can resolve a structured component through the
    BlockCopy mirror into the bblocks arena. The existing single-arena struct_last_op
    entry point is unchanged for its three existing callers (all on bblocks, where every block
    is t_basic).
  • substrate/funcdata_block.rs (Funcdata::sblocks_order_blocks) — the cross-arena seam:
    a component's lastOp opcode needs the op bank, which lives in Funcdata, so the
    RETURN set is computed there and handed to the block-level sort.
  • Ties: upstream's comparator reports two RETURN-terminated components as equal (it does not
    fall through to the index compare), so std::sort leaves them in an unspecified order. The
    Rust port uses a stable sort, which reproduces libstdc++'s small-n insertion sort and is
    deterministic for every n.

Region structurer: the ordering is needed on both paths and gets it from one call site.
regionstructure (default-ON, DIV-12) and Ghidra's CollapseStructure both hand
ActionFinalStructure the same root component list; the fix sits in that action, so neither
path needs its own hook. Confirmed empirically — the campaign case reproduces identically with
--option regionstructure off, and the corpus sweep below runs the default (region-structurer)
configuration.

Downstream consumers of the component list: the only readers after
ActionFinalStructure are finalize_switch_printing / finalize_forloop_printing (per-node,
order-insensitive), mark_unstructured / mark_label_bump_up (recursive marking,
order-insensitive), next_flow_after (which should see the final order — that is what makes
fall-through-vs-goto rendering correct), and printc.rs (emit_block_graph), a plain for blk in list walk. orderBlocks runs before all of them, exactly as upstream.

Corpus sweep — defect count and blast radius

kuna decompile-all --json --mode reliable, 12 binaries / 3,434 functions, before vs after on
this branch's base. Signature ded = "an unconditional goto label_X; whose next non-blank
line is a statement at the same or deeper depth" (dead code); lab = "the body's first
statement is a label_N:".

binary funcs ded before lab before ded after lab after functions whose text changed
O0 libopencm3 sdram.elf 56 1 1 0 0 1
O0 libopencm3 usart-stdio.elf 150 2 5 0 3 5
O0 libopencm3 button.elf 31 0 0 0 0 0
O0 libopencm3 usbmidi.elf 85 0 0 0 0 0
O0 chibios ch.elf 770 0 0 0 0 0
O0 bzip2 158 2 2 0 0 2
O0 gzip 262 0 0 0 0 0
O0 diffutils diff 526 5 5 0 0 5
O0 grep 671 1 1 0 0 1
O0 zlib libz.so.1.2.13 215 1 1 0 0 1
O2 bzip2 113 5 5 0 0 5
O2 diffutils diff 397 8 9 0 0 10
TOTAL 3,434 25 29 0 3 30
  • Defect: 25 -> 0. Every instance of the reported defect in the sample is gone.
  • The 3 residual "opens with a label" are not the defect: each is the entry block carrying a
    label at its own address (sub_8005f44 opens label_8005f44:), because a back edge later in
    the function jumps to the entry. Ghidra does the same.
  • Blast radius: 30 of 3,434 functions (0.87%) change text at all — reordering emitted blocks
    is a broad change and that is the honest number. It is also a tight change: across the whole
    changed set the goto count and line count are identical before and after (1,172 gotos /
    16,123 lines both ways). Every changed function is a permutation of its own statements; nothing
    is added, removed or re-rendered. Spot-checking all 30, each moves its first statement from a
    mid-function label to real entry code (the one exception, diffutils 0x104d0, moves a
    duplicated RETURN block off the front and to the back — the RETURN-last half of the key).

Gates

gate result
make test PARITY OK (675/675) — corpus does not move, so no flag and no re-pin
make test-stages PARITY OK (324/324); the baseline delta is purely additive (the 6 new keys), no existing key dropped and no per-test opt-out
make rust-test green (corpus file count bumped 177 -> 178 in kuna-base/src/xml.rs)
make check-spec OK, lenient and --strict
kuna catalog --check OK

Speed

Interleaved runs, decompile-all --mode reliable (medians):

workload before after delta
O0 diffutils diff, 526 functions 7.38 s 7.07 s -4.2% (noise; the before set had one 9.57 s outlier)
O2 bzip2, 113 functions 15.06 s 15.18 s +0.8%

Within the +5% budget. A stable sort_by_key over the root component list is O(k log k) in the
number of residual top-level components, which is 1 for most functions (the guard
list.len() == 1 short-circuits) and a handful otherwise.

Test

tests/stages/ghdec-finalorder-entryfirst.xml — a real binary -> decompile(addr) path over a
self-contained byte chunk. The campaign's own function is ARM Thumb and needs its whole binary
to reproduce, so the carried witness is the triage's second one, diffutils lines_differ
(x86-64 -O2, 1,120 bytes), which reproduces in isolation. 4 of the 6 assertions fail
pre-fix, 6/6 post-fix
: nothing is emitted after an unconditional goto; the body does not
open with a label; the body opens with an indented statement; the entry initializer v4 = dat_26558; is the first statement; and both labels the buggy order hoisted are still present
(the fix reorders, it does not delete).

Docs

  • docs/spec/08-structuring.md §8.1 — new Final component ordering paragraph in prose:
    collapse order is not print order, what the key is, root-only, applies to both engines, and
    what goes wrong without it.
  • docs/history.md — DIV-48 (next free off origin/main).
  • docs/decbench/features.md — finalorder-entry-first marked PR in flight.
  • tests/stages/README.md — the new testcase row.

Provenance: inspiration = "decbench:O0-libopencm3-sdram-main; NOVEL pool" — kuna already
wins this pane (GED 58 vs angr 77 / ida 79 / ghidra 85) and was still emitting its entry as
dead code, which is why no other decompiler surfaced this fix.

🤖 Generated with Claude Code

https://claude.ai/code/session_011RXVU58TKJxb518oViChwo

mahaloz and others added 3 commits August 1, 2026 20:04
Port `BlockGraph::orderBlocks` (block.hh:437) and call it where upstream
does, as the first line of `ActionFinalStructure::apply` (blockaction.cc:2192).

Structuring does not always end with a single top-level component; when it
leaves several, the printer walks the root component list in order.  kuna had
never ported the sort that puts that list in final order, so the list stayed in
COLLAPSE order -- whichever component the collapse happened to append first
printed first.  A function could therefore open in the middle of its body and
reach its real entry only after an unconditional `goto`, i.e. emit the entry as
unreachable dead code.  On the campaign case (libopencm3 sdram `main`) the body
opened on the 'p'/'P' command handler and printed
`clock_setup(); console_setup(); sdram_init(); ...` after `goto label_8000792;`.

The producer of the ordering key was already ported -- `BlockGraph::add_block`
keeps a composite's `index` at the minimum over its members -- so only the sort
was missing.  It now runs with upstream's key (`FlowBlock::compareFinalOrder`,
block.cc:709): entry component (`index == 0`) first, RETURN-terminated
components last, everything else by ascending index; root graph only (upstream
does not recurse).  `FlowBlock::lastOp` gains its missing `t_copy` /
`t_goto` / `t_multigoto` overrides so the RETURN half of the key can resolve a
structured component through the `BlockCopy` mirror into `bblocks`; the sort is
stable, so the several RETURN-terminated components upstream's comparator
reports as equal keep a deterministic order rather than `std::sort`'s
unspecified one.  Both structuring engines are covered: `CollapseStructure` and
the default-on region structurer hand `ActionFinalStructure` the same root list.

Strict bug fix restoring upstream behavior -- no option (the current output is
unambiguously wrong C).

Gates: 675/675 PARITY OK, 324/324 stages PARITY OK (delta is purely the 6 new
keys -- no re-pin, no per-test opt-out), rust-test green, check-spec OK
(strict), catalog OK.

Measured over 12 decbench binaries / 3,434 functions: "unconditional goto
followed by a statement" 25 -> 0, "body opens with a label" 29 -> 3 (the 3
residual labels sit at the entry block's own address, a legitimate back-edge
target).  Blast radius 30 of 3,434 functions (0.87%) change text at all, and
the whole changed set keeps its goto count and line count exactly (1,172 gotos
/ 16,123 lines before and after) -- the statements are a permutation.  Speed,
interleaved medians of `decompile-all --mode reliable`: O0 diffutils `diff`
7.38 s -> 7.07 s, O2 `bzip2` 15.06 s -> 15.18 s (+0.8%).

inspiration = "decbench:O0-libopencm3-sdram-main; NOVEL pool"

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

# Conflicts:
#	decompiler/crates/kuna-base/src/xml.rs
#	docs/baseline-stages.json
#	tests/stages/README.md
@mahaloz
mahaloz merged commit b0752b8 into main Aug 1, 2026
9 checks passed
@mahaloz
mahaloz deleted the fix/finalorder-entry-first branch August 1, 2026 20:18
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