Repository navigation
[AUTOMATED] fix(p8): (NOVEL) print the entry component first (DIV-48) - #235
Merged
Merged
Conversation
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What
Port
BlockGraph::orderBlocks(upstreamblock.hh:437) and call it where upstream calls it —the first line of
ActionFinalStructure::apply(blockaction.cc:2192). It was an explicitSTUB.
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
sblocksgraphholding 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_blockkeeps acomposite's
indexat the minimum over its members), so only the sort was missing — thisturned 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 —
libopencm3sdrammain(the campaign case)Before (
--mode auto, today'smain): the body opens on the'p'/'P'command handler, andthe real entry is emitted after an unconditional
goto, unreachable:After — entry first, no leading
goto, and the'p'/'P'handler is where the switch reachesit:
Judged against the source (
.../O0/libopencm3/compiled/sdram.i:3829) end to end, not just thefirst 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, thesecond
dump_page, then thewhile (1)command loop with thef/n/p/?arms and thenested 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-ordernumber). 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::lastOpgains itsmissing
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
BlockCopymirror into thebblocksarena. The existing single-arenastruct_last_opentry point is unchanged for its three existing callers (all on
bblocks, where every blockis
t_basic).substrate/funcdata_block.rs (Funcdata::sblocks_order_blocks)— the cross-arena seam:a component's
lastOpopcode needs the op bank, which lives inFuncdata, so theRETURN set is computed there and handed to the block-level sort.
fall through to the index compare), so
std::sortleaves them in an unspecified order. TheRust port uses a stable sort, which reproduces libstdc++'s small-
ninsertion sort and isdeterministic 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'sCollapseStructureboth handActionFinalStructurethe same root component list; the fix sits in that action, so neitherpath 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
ActionFinalStructurearefinalize_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 makesfall-through-vs-
gotorendering correct), andprintc.rs (emit_block_graph), a plainfor blk in listwalk.orderBlocksruns 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 onthis branch's base. Signature ded = "an unconditional
goto label_X;whose next non-blankline is a statement at the same or deeper depth" (dead code); lab = "the body's first
statement is a
label_N:".label at its own address (
sub_8005f44openslabel_8005f44:), because a back edge later inthe function jumps to the entry. Ghidra does the same.
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 aduplicated RETURN block off the front and to the back — the RETURN-last half of the key).
Gates
make testmake test-stagesmake rust-testkuna-base/src/xml.rs)make check-spec--strictkuna catalog --checkSpeed
Interleaved runs,
decompile-all --mode reliable(medians):diff, 526 functionsbzip2, 113 functionsWithin the +5% budget. A stable
sort_by_keyover the root component list is O(k log k) in thenumber of residual top-level components, which is 1 for most functions (the guard
list.len() == 1short-circuits) and a handful otherwise.Test
tests/stages/ghdec-finalorder-entryfirst.xml— a realbinary -> decompile(addr)path over aself-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 failpre-fix, 6/6 post-fix: nothing is emitted after an unconditional
goto; the body does notopen 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 offorigin/main).docs/decbench/features.md—finalorder-entry-firstmarked PR in flight.tests/stages/README.md— the new testcase row.Provenance:
inspiration = "decbench:O0-libopencm3-sdram-main; NOVEL pool"— kuna alreadywins 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