Skip to content

[AUTOMATED] fix(p2): maxlennop - a 15-byte instruction is not an over-long one (GH-271) - #272

Merged
mahaloz merged 2 commits into
mainfrom
fix/gh271-maxlen-nop-decode
Aug 8, 2026
Merged

mahaloz merged 2 commits into
mainfrom
fix/gh271-maxlen-nop-decode

Conversation

@mahaloz

@mahaloz mahaloz commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

Closes #271.

Root cause: not the SLEIGH spec, the parser's byte window

The issue nominated the x86 NOP constructors in ia.sinc. They are fine — the spec matches the encoding. The failure is one layer down, in the ported ParserContext.

getInstructionBytes / getInstructionBits guard only the start byte of a read against MAX_INSTRUCTION_LEN (16), then pull a fixed-width run from it. So a read can legitimately extend past the end of the 16-byte buffer, because PatternBlock::isInstructionMatch walks a candidate pattern in sizeof(uintm) chunks whatever the pattern's real width is. Matching an instruction at the 15-byte x86 maximum therefore issues a 4-byte read at offset 13 — one byte past buf.

Upstream reads whatever ParserContext memory follows buf (UB) and the caller's mask discards it. The kuna port turned that same read into a hard BadData:

Execution error: Instruction byte read past buffer (C++ UB)

FlowInfo caught it, planted an artificial halt at the NOP address, and truncated the rest of the function. Instrumenting the reported repro shows the whole failure is one masked-out byte:

KUNA-OVERRUN bytes base=13 size=4 i=3      <- the only overrun in the entire decode

The three reported defects are all that one truncation: the body is dropped because flow stops, the guard looks inverted because the truncated CFG restructures a shrink-wrapped early exit into an empty if, and the 5th parameter disappears because only the dropped loop read r8.

Fix

Bytes past the buffer read as 0 — the deterministic equivalent of the garbage C++ reads, and provably irrelevant since those bytes lie outside the matcher's mask. The start-byte guard is untouched, so a genuinely over-length encoding still raises the instruction-length error (pinned by a test).

Correctness fix restoring upstream behavior, so no option (recorded under Convergences in docs/history.md, not a DIV).

Before / after on the reported repro

// before                                  // after
void sub_401000(unsigned long a0,          void sub_401000(int8 a0,uint8 *a1,unsigned int *a2,
                uint8 *a1,                                 uint8 a3,unsigned long *a4)
                unsigned long a2,          {
                uint8 a3)                    if (a3 <= *a1)
{                                              return;
  if (*a1 < a3)                              v3 = (int8 *)*a4;
    return;                                  while( true ) {
  return;                                      ... the map walk ...
}                                              if (v3 == (int8 *)(a0 + 0x38)) break;
                                               v1 = v3[4];
                                               if (a3 <= v1) {
                                                 *a4 = v3;
                                                 *a1 = v1 - *(int8 *)(a0 + 0x28);
                                                 *a2 = 0x2a;
                                                 return;
                                               }
                                             }
                                             *a4 = v3;
                                             return;
                                           }

Body recovered, guard in the jae sense, r8 back as a4.

Why no gate caught this

All 791 ELFs in the decbench corpus are gcc-built and contain zero 15-byte NOPs. The bug survived the entire decbench campaign because the corpus has no clang-built x86-64 in it.

Measured effect on real clang output

/usr/bin/FileCheck-14 (clang, 528 KB, 1,155 functions, 122 instances of the padding):

before after
functions discovered 1,155 1,155 (byte-identical)
functions whose C changes — 46 (4.0%), all grow, none shrink
emitted lines 66,420 70,243 (+5.8%)

The 46 split cleanly in two:

  • 26 functions (+1,497 lines) — straight recovery of code that was silently missing. e.g. sub_40e6e0 58 → 214 lines, regaining the entire operator new reallocation branch of a std::vector growth path.

  • 20 functions (+2,326 lines) — a pre-existing gap this fix un-masks, not a new defect. noreturn_disc's evidence tally counts a call site whose fall-through "is not a valid instruction start", and a failed decode satisfied that test — so clang's post-call alignment padding was silently voting std::__throw_length_error no-return. With the padding decoding, the tally drops below its 3-site floor and the dead code after that genuinely-non-returning libstdc++ helper reappears (whole-binary // no-return 94 → 83).

    Every one of the 20 hangs on that single callee. The real fix is that the vendored ElfFunctionsThatDoNotReturn list — which is Ghidra's own, and shares the gap — does not cover the std::__throw_* family. Diverging from vendored upstream data is its own change with its own DIV, so it is filed as [AUTOMATED] std::__throw_* family missing from the ELF no-return list: dead code after libstdc++ throw helpers #273 and deliberately not folded in here.

Speed

Interleaved min-of-5 decompile-all on gzip (gcc-built, so both panes do identical work and the output is byte-identical): 14.45s → 14.65s (+1.4%), inside the run-to-run spread — the means go the other way, 15.26s → 14.91s. The edit replaces an error-constructing bounds check with a saturating one, so it cannot cost anything on the decode path.

Gates

Gate Result
make test PARITY OK 675/675, no re-pin
make test-stages PARITY OK 405/405 (delta is purely the 5 new keys)
make rust-test green
make check-spec OK
kuna catalog --check OK (no option added)

Tests

  • tests/stages/gh271-x86-maxlen-nop.xml — 5 assertions: the NOP decodes at 0x100d, the stream realigns at 0x101c (so it consumed exactly 15 bytes), the loop and the store past the padding both survive, and the early-exit guard keeps the jae sense. 0/5 pass pre-fix (the file aborts with the decode error), 5/5 after.
  • decompiler/crates/kuna-sleigh/tests/x86_maxlen_nop_regression.rs — the 15-byte decode, and a second test pinning that 16 prefixes (opcode at offset 16) still raises the instruction-length guard. Both verified failing against the pre-fix code.

🤖 Generated with Claude Code

https://claude.ai/code/session_014ZfprhsXxBXEM1sMP1XX8d

mahaloz and others added 2 commits August 7, 2026 16:15
…-long one (GH-271)

`ParserContext::getInstructionBytes`/`getInstructionBits` guard only the
*start* byte of a read against `MAX_INSTRUCTION_LEN` (16) and then pull a
fixed-width run from it, so a read can legitimately run off the end of the
16-byte buffer: `PatternBlock::isInstructionMatch` walks a candidate pattern
in 4-byte chunks whatever the pattern's real width, so matching an
instruction AT the 15-byte x86 maximum issues a 4-byte read at offset 13.
Upstream reads whatever memory follows `buf` (UB) and the caller's mask
discards it; the port turned the same read into a hard `BadData`, so
`FlowInfo` planted an artificial halt at that address and truncated the
function.

The witness is clang's 15-byte loop-alignment NOP
`66 66 66 66 66 66 2e 0f 1f 84 00 00 00 00 00`, routine -O2 padding ahead of
a loop head: everything past it (the loop, the stores, and any parameter only
the loop read) vanished from the emitted C, and on a shrink-wrapped function
the truncated CFG restructured into an inverted empty guard.

The tail bytes are outside the matcher's mask and cannot affect the verdict,
so they now read as 0 -- the deterministic equivalent of the garbage C++
reads. The start-byte guard is untouched, so a genuinely over-length encoding
still raises the instruction-length error.

Correctness fix, no option. Measured on /usr/bin/FileCheck-14 (clang, 1,155
functions): 46 change, all grow, 66,420 -> 70,243 lines; 26 are straight
recovery of missing code, 20 un-mask a pre-existing `std::__throw_*` gap in
the vendored no-return list (filed separately). Gates: 675/675 PARITY OK,
stages PARITY OK, rust-test green, check-spec OK.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_014ZfprhsXxBXEM1sMP1XX8d
@mahaloz
mahaloz force-pushed the fix/gh271-maxlen-nop-decode branch from a5ec87c to bba3610 Compare August 7, 2026 16:27
@mahaloz
mahaloz merged commit b6ac5a6 into main Aug 8, 2026
9 checks passed
@mahaloz
mahaloz deleted the fix/gh271-maxlen-nop-decode branch August 8, 2026 07:03
mahaloz added a commit that referenced this pull request Aug 8, 2026
* [AUTOMATED] ci: scope the workspace suite to fork PRs and to main

One push to this repo fans out ~10 concurrent jobs: 2 here plus CodeQL
default setup's 8 configured languages. On 2026-08-06 that exhausted the
runner pool -- four of them (parity gates, Analyze c-cpp/python/rust) sat
98-101 minutes with runner_id 0 and zero steps recorded, were swept, and
presented PR #272 as red having executed no code at all.

Halve this workflow's share of that demand. The `cargo workspace suite`
job -- a debug build of the whole workspace plus ~4300 tests, the long
pole at 6-9 min -- no longer runs on a pull request from a branch in this
repo. Those are the automated agent PRs, where AGENTS.md already requires
`make rust-test` green locally before the commit, so the job re-derives an
answer we already have.

It still runs, unchanged, on:
  - every push to main (the safety net: the suite always runs on the merge
    commit, so nothing reaches main without it -- the answer just arrives
    at merge rather than before it),
  - a pull request from a FORK (the case nobody ran locally),
  - any PR labelled `full-ci` (the per-PR escape hatch, no workflow edit),
  - workflow_dispatch.

The parity gates are untouched and still run on every event: 2.3-3.2 min,
and they are the cheap net that catches the common regression.

docs/agents.md records that the author, not CI, is the pre-merge gate for
`make rust-test` on an internal PR.

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

* [AUTOMATED] ci: move the options.md byte-freshness fence into the parity gates

Skipping the workspace suite on internal PRs defers every assertion in it to
the push to main. One of those is worth keeping pre-merge:
kuna-decomp/tests/options_md_fresh.rs, which asserts docs/options.md is the
catalog generator's exact bytes. Forgetting to regenerate it after touching
option metadata is a routine miss -- AGENTS.md calls it out by name -- and it
is the kind of failure that should land on the PR, not on main.

`kuna catalog --check` (already in this job) proves options.md documents the
same option SET; it does not prove the bytes match. The new step does, by
diffing against `kuna catalog --markdown`. It reuses the release binary the
job already built, so it costs nothing.

Verified both directions locally: byte-identical tree passes; a one-line
append to docs/options.md fails with the ::error annotation.

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

* [AUTOMATED] ci: make the full-ci label actually trigger the suite

The escape hatch as written could not be used the way it was documented.
`pull_request` defaults to types opened/synchronize/reopened, so adding a
label fires nothing -- and re-running a finished run REPLAYS ITS ORIGINAL
PAYLOAD, so a label added after the fact is invisible to the `if:` too.
The only way to be believed was to push a commit, which is not an escape
hatch.

Add `labeled` to the trigger. The label alone now starts a run whose payload
carries it, `contains(github.event.pull_request.labels.*.name, 'full-ci')`
sees it, and the suite runs. `unlabeled` is deliberately omitted so removing
a label re-runs nothing; the cost is one extra run per label added to a PR,
which is rare here.

Comments and docs/agents.md corrected to match.

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

---------

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
mahaloz added a commit that referenced this pull request Aug 17, 2026
…V-78) (#311)

[AUTOMATED]

Every helper in libstdc++'s <bits/functexcept.h> (plus __throw_regex_error from
<bits/regex_error.h>) is declared __attribute__((__noreturn__)) and every body
ends in _GLIBCXX_THROW_OR_ABORT -- a throw, or abort() under -fno-exceptions --
so none of the 20 can return. Upstream Ghidra's ElfFunctionsThatDoNotReturn names
__cxa_throw and the terminate entry points but omits the whole family, and the
source attribute survives into no binary artifact: at the decompiler's boundary
std::__throw_length_error is an ordinary UND .dynsym import behind a PLT stub, so
nothing but the shipped list can prove the call cannot return. Flow followed the
fall-through and emitted whatever sat after the call -- clang's
`call __stack_chk_fail` unreachable-trap, the next function's entry, or the
exception-cleanup landing pad. The gap was masked until #272, when a failed
decode of clang's 15-byte alignment NOP stopped forging noreturn_disc evidence.

The 20 helpers are appended to the vendored list in place, fenced by a
`# (kuna divergence, DIV-78)` block, exactly as DIV-21's libc additions are:
tools/sync_upstream.py's vendored scope is tests/datatests/ plus
Ghidra/Processors/*/data/languages/, so Ghidra/Features/Base/data/ is never
synced and an in-place block cannot conflict. Each helper is listed twice --
the mangled .dynsym spelling the analysis-tier scan matches pre-demangle (a
trailing-* wildcard over the Itanium ZSt<len>__throw_<name> prefix, so a
signature change cannot age it out) and the demangled base name the flow-time
matcher sees. No new option: noreturn_known and noreturn_externmatch are both
default-on and both read this file.

Witnesses: FileCheck-14 (clang, 1,155 fns) 72 change, 0 grow, no-return
annotations 69 -> 102, lines 63,247 -> 63,141; apt-get (gcc, 124 fns) 6 change,
11 -> 17; clang-format-14 (242 fns) 13 change, 12 -> 16. Zero collateral on C
binaries (grep 0/449, sort 0/490, faillog 0/69, libselinux.so.1 0/502). Speed
min-of-11 68.64 s -> 66.01 s (-3.83%).

Fixes #273


Claude-Session: https://claude.ai/code/session_01VBn8vgwoHqPFnnV4ZMApfq

Co-authored-by: Claude Fable 5 <[email protected]>
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.

[AUTOMATED] 15-byte multi-prefix NOP fails SLEIGH decode: body dropped, guard inverted

1 participant