Skip to content

[AUTOMATED] fix(p3): reconcile a renaming input with guardInput's leftover pieces (DIV-50) - #238

Merged
mahaloz merged 2 commits into
mainfrom
fix/renamerecurse-overlapping-inputs
Aug 1, 2026
Merged

mahaloz merged 2 commits into
mainfrom
fix/renamerecurse-overlapping-inputs

Conversation

@mahaloz

@mahaloz mahaloz commented Aug 1, 2026

Copy link
Copy Markdown
Contributor

The bug

gnulib's rpl_fcntl compiled at -O2 produced no body at all — one function
in each of 48 of the 267 optimized x86-64 decbench binaries (gzip,
gnutls-serv, grep, tar, findutils, diffutils, 39 coreutils):

$ kuna decompile-all results/full_run/O2/gzip/stripped/gzip --json --mode reliable
[('sub_e0f0', 57584,
  'decompile pipeline reached an un-ported seam (LOSS-131): rename_recurse: '
  'set_input_varnode (empty stack): Lowlevel { explain: "Overlapping input varnodes" }')]

$ kuna decompile .../O2/gzip/stripped/gzip --addr e0f0 --mode reliable
void sub_e0f0(void)
{
  /* WARNING: decompilation failed: ... "Overlapping input varnodes" */
}

0xe0f0 is rpl_fcntl in the unstripped build. It is -O2-only: O0 and
O2-noinline are clean.

Root-cause classification

Neither an unported guard nor a kuna-only precondition violation: an upstream
Ghidra bug kuna inherited faithfully.

I ran the pinned upstream sources side by side with the Rust port —
Heritage::renameRecurse, Funcdata::setInputVarnode, Heritage::guardInput,
Heritage::collect, SubvariableFlow::getReplaceVarnode/replaceInput are all
faithful transcriptions. So I ran the real thing:

$ ghidra_12.1/support/analyzeHeadless <proj> gz -import .../O2/gzip/stripped/gzip \
      -postScript DecompOne.java 10e0f0
=== ENTRY 0010e0f0 ok=false
=== ERRMSG: Low-level Error: Overlapping input varnodes

Ghidra 12.1 fails on the same address of the same binary with the same message.
The fix is therefore a kuna divergence (DIV-50), not a Convergence.

Why -O2

rpl_fcntl is a varargs wrapper. At -O2 gcc spills the register arguments into
a SysV va_list register-save area and reads the third argument back through an
indexed load:

e0fd: mov %rdx,0x40(%rsp)      ; stack -0x38 = the third vararg
e15d: mov 0x10(%rsp),%eax      ; gp_offset
e16a: add 0x20(%rsp),%rax      ; + reg_save_area
e16f: mov (%rax),%rdx          ; -> folds to stack -0x38 only on a later pass

Traced with instrumentation on the failing function, the sequence is:

heritage pass what happens at stack -0x38
1 W[COPY@0xe0fd/b0], R[] — the spill has no direct reader yet, so ActionDeadCode removes it (deadremoved=1)
2 the indexed load has folded to a constant stack offset: R[-0x38:4, -0x38:4], and no write in the entry block → renameRecurse invents an 8-byte input
2 (pools) SubvariableFlow::getReplaceVarnode → replaceInput narrows that input to 4 bytes
3 I[-0x38:4] ≠ range size → guardInput fills the hole (-0x34:4), write-masks both pieces, and concatenates them with a PIECE
3→4 (pools) SUBPIECE(PIECE(hi,lo),0) folds away; the PIECE dies, the two write-masked input pieces stay in the def tree and are invisible to collect
4 a fresh free 8-byte read of the range finds an empty VariableStack, asks setInputVarnode for a full-size input → collides with the leftover pieces → LowlevelError

The fix

The leftover pieces are the value the read wants, so the collision is
reconcilable. New module
decompiler/crates/kuna-decomp/src/p3_dataflow/kuna_inputtile.rs:

  1. try set_input_varnode exactly as before (the fast path, unchanged);
  2. on the overlap error, gather the input Varnodes intersecting the request. If
    any of them straddles the request boundary, or is not write-masked, give up
    and let the upstream error fire;
  3. otherwise complete the request into an end-to-end tiling — creating a fresh
    input for any hole, exactly as guardInput does — and fold it into one
    full-size input with the upstream Funcdata::combineInputVarnodes primitive
    (funcdata_varnode.cc:383), which destroys the pieces, rewrites concatenating
    PIECEs into COPYs, and repoints every other reader at a SUBPIECE of the
    new whole.

Restricting the fold to write-masked pieces is what makes the rewrite safe
mid-rename: a write-masked Varnode is never pushed onto a VariableStack
(renaming pushes only activeHeritage op outputs and the inputs it creates
itself, neither of which is write-masked) and each Heritage::rename builds a
fresh stack, so the rewrite cannot strand a renaming-stack entry.

heritage.rs changes only three call sites (the two empty-stack paths and the
INDIRECT same-time path) to route through the new helper.

No option. These functions produced no output at all, and the new code runs
only where setInputVarnode was about to raise. Per CLAUDE.md a strict bug fix
that only corrects wrong output needs no flag. It is recorded as DIV-50 in
docs/history.md because it diverges from upstream.

Judged output

gzip rpl_fcntl (--mode reliable), after:

int4 sub_e0f0(uint8 a0,unsigned long a1,unsigned int a2)
{
  ...
  v2 = (int4)a1;
  if (!v2) return fcntl(a0,0,a2);
  if (v2 == 0x406) {
    if (dat_dfeb0 < 0) { v2 = fcntl(a0,0,a2); ... }
    v2 = fcntl(a0,0x406,a2);
    if (v2 < 0) { if (*(int4 *)__errno_location() == 0x16) { ... dat_dfeb0 = -1; goto label_e2a9; } }
    dat_dfeb0 = 1;
    return v2;
  }
  if (0xc <= v2) { ... if (v4 & 0x2c5) return fcntl(a0,a1,a2); v4 &= 0x502; }
  else           { ... if (v4 & 0x514) return fcntl(a0,a1,a2); v4 &= 0xa0a; }
  ...
}

Matching the gnulib source (lib/fcntl.c): the action == 0 / action == F_DUPFD_CLOEXEC (1030) arms, the EINVAL (22) retry probe, the
have_dupfd_cloexec cache (dat_dfeb0), the fcntl(result,F_GETFD) /
fcntl(result,F_SETFD,flags|1) fix-up and its errno-preserving close, and
the bitmask-dispatched default switch. IDA's stored pane for the same address
has the same control flow.

Residual, reported honestly: the recovered body still reads the spill slot as
an undefined stack - 0x38 local (return fcntl(a0,a1,v6)), where IDA prints
fcntl(a1, a2, v13) with v13 = a3. Keeping the va_list spill alive across the
dead-code round is the other half of the story — upstream does it with
Heritage::guardLoads + handleNewLoadCopies (addrForce on boundary Varnodes
inside a LOAD-guard range), which kuna does not port (Heritage::guard
hard-wires high_ptr_possible = false and both guards are unimplemented_stubs).
That is a much larger, separately-measurable port and is deliberately out of
scope here; Ghidra cannot even be used as a reference for it, because it fails on
this function too.

Before/after over the O2 corpus

Same 267 stripped -O2 binaries, decompile-all --json --mode reliable,
76,527 functions:

before after
Overlapping input varnodes functions 48 0
binaries hitting it 48 0
total error records 56 8
total functions enumerated 76,527 76,527
functions produced before but not after — 0
functions produced after but not before — 48

The 8 residual errors are an unrelated Unable to load 512 bytes at r0x… class,
byte-identical before and after.

Blast radius, whole-binary text diff of every emitted function:

binary functions text-changed
O2/gzip/gzip 203 1 (sub_e0f0)
O2/coreutils/sort 342 1 (sub_13850)
O2/diffutils/diff 397 1 (sub_1b520)
O2/findutils/find 657 1 (sub_17dd0)
O2/coreutils/nohup 143 1 (sub_3160)

Exactly the function that used to fail, in each case. Nothing else moves.

Speed

Interleaved medians of 5, decompile-all --mode reliable:

binary before after delta
O2/gzip/gzip 4,796 ms 4,792 ms -0.08%
O2/coreutils/sort 13,477 ms 13,114 ms -2.69%
O2/findutils/find 8,362 ms 8,279 ms -0.99%

Within the +5% budget (the new code runs only on the error path).

Regression test

tests/stages/ghdec-inputtile-overlap.xml — 1 of 8 assertions passes pre-fix
(the bare-shell signature line), 8/8 post-fix.

The vendored gzip bytes do not reproduce outside the ELF loader path (the
bytechunk console decompiles them fine even pre-fix), so the testcase carries a
reduced standalone gcc -O2 -fstack-protector-strong build of the gnulib
wrapper instead — verified to raise the identical error on the pre-fix build via
both the real-binary path (kuna decompile <bin> rpl_fcntl) and the stages
harness. The reduced C source is quoted in the testcase comment.

Gates

gate result
make test PARITY OK (675/675) — no re-pin
make test-stages PARITY OK (346/346) — re-recorded, delta is purely the 8 new keys, no per-test opt-out
make rust-test green (4,410 tests, 0 failed; docs/options.md fresh)
make check-spec green
kuna catalog --check green

Docs

  • docs/spec/03-ssa-and-simplification.md §3.1 — new prose paragraph
    "Materializing an input over existing pieces".
  • docs/history.md — DIV-50 row with the corpus measurements above.
  • decompiler/crates/kuna-base/src/xml.rs — stages corpus file count 181 → 182.

Provenance: inspiration = "decbench:cases-missing pool; gnulib rpl_fcntl at -O2, 48 of 213 optimized x86-64 binaries".

🤖 Generated with Claude Code

https://claude.ai/code/session_011RXVU58TKJxb518oViChwo

mahaloz and others added 2 commits August 1, 2026 22:15
…tover pieces (DIV-50)

gnulib's `rpl_fcntl` compiled at -O2 produced no body at all in 48 of 267
optimized x86-64 binaries (gzip, gnutls-serv, grep, tar, findutils, diffutils,
39 coreutils), exactly one function per binary:

  rename_recurse: set_input_varnode (empty stack):
    Lowlevel { explain: "Overlapping input varnodes" }

Classification: this is NOT a port defect and NOT a precondition kuna alone
violates. Ghidra 12.1 headless raises the identical
`Low-level Error: Overlapping input varnodes` on the same address of the same
binary, so it is an upstream bug kuna inherited faithfully; the fix is a kuna
divergence (DIV-50), not a convergence.

Root cause, P3 dataflow. gcc -O2 spills the register arguments of a varargs
function into a va_list register-save area and reads them back through an
indexed load. The spill has no direct reader on the first stack heritage pass,
so ActionDeadCode removes it; the indexed load only folds to the constant stack
offset on a later pass. From there heritage invents an input for the
now-undefined slot, SubvariableFlow narrows it to 4 bytes, and
Heritage::guardInput tiles the 8-byte range with two write-masked 4-byte input
pieces plus a concatenating PIECE. The simplification pools then fold that PIECE
away. On the next pass a fresh free 8-byte read of the same range finds an empty
variable stack, asks setInputVarnode for a full-size input, and collides with the
leftover pieces.

The leftover pieces are exactly the value the read wants, so the collision is
reconciled instead of raised: p3_dataflow/kuna_inputtile.rs completes the request
into an end-to-end tiling (a fresh input for any hole, as guardInput does) and
folds it into one full-size input with the upstream
Funcdata::combineInputVarnodes primitive, which destroys the pieces, rewrites
concatenating PIECEs into COPYs and repoints every other reader at a SUBPIECE of
the whole. Only write-masked pieces fully contained in the request are folded -- a
write-masked Varnode is never pushed onto a VariableStack, so the rewrite cannot
strand a renaming-stack entry -- and every other overlap still raises, exactly as
upstream.

No option: the affected functions produced no output at all before, and the new
path runs only where setInputVarnode was about to raise.

Evidence
- 267-binary O2 decbench corpus, 76,527 functions: overlapping-input class
  48 -> 0 functions in 48 -> 0 binaries; total error records 56 -> 8 (the 8
  residuals are an unrelated "Unable to load 512 bytes" class, unchanged).
- 0 functions stop being produced, 48 start.
- Whole-binary text diffs on gzip, coreutils sort, diffutils diff, findutils find
  and coreutils nohup change exactly 1 function each: the one that used to fail.
- Speed, interleaved medians of 5 (`decompile-all --mode reliable`): gzip
  4,796 -> 4,792 ms (-0.08%), coreutils sort 13,477 -> 13,114 ms (-2.69%),
  findutils find 8,362 -> 8,279 ms (-0.99%).
- Gates: make test PARITY OK (675/675), make test-stages PARITY OK (346/346, the
  delta is purely the 8 new keys, no re-pin and no per-test opt-out), make
  rust-test green, make check-spec green, kuna catalog --check green.
- tests/stages/ghdec-inputtile-overlap.xml: 1 of 8 assertions passes pre-fix,
  8/8 post-fix. The bytes are a reduced standalone gcc -O2 build of the gnulib
  wrapper; the vendored gzip bytes did not reproduce outside the ELF loader path.

Known residual (out of scope, noted in the DIV row): the recovered body still
reads the spill slot as an undefined `stack - 0x38` local. Keeping the va_list
spill alive across the dead-code round needs Heritage::guardLoads /
handleNewLoadCopies (kuna hard-wires `highPtrPossible = false`), a separate and
much larger port.

Provenance: inspiration = "decbench:cases-missing pool; gnulib rpl_fcntl at -O2,
48 of 213 optimized x86-64 binaries".

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

# Conflicts:
#	docs/history.md
@mahaloz
mahaloz merged commit 36641d3 into main Aug 1, 2026
9 checks passed
@mahaloz
mahaloz deleted the fix/renamerecurse-overlapping-inputs branch August 1, 2026 22:27
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