Skip to content

[AUTOMATED] fix(p1): Cortex-M vector table need not sit in an exec section (DIV-44) - #224

Merged
mahaloz merged 1 commit into
mainfrom
fix/cortexm-vector-nonexec-section
Aug 1, 2026
Merged

mahaloz merged 1 commit into
mainfrom
fix/cortexm-vector-nonexec-section

Conversation

@mahaloz

@mahaloz mahaloz commented Aug 1, 2026

Copy link
Copy Markdown
Contributor

The bug

kuna's ARM Cortex-M vector-table oracle (entry-discovery oracle 6) looked for the
table only inside SHF_EXECINSTR sections. That is a category error: the
vector table is data the CPU reads on reset (word 0 → SP, word 1 → PC), not
code. What has to be executable is what its handler entries point at — which
the harvest already checks, and still does.

Every FreeRTOS demo image links .isr_vector at VMA 0 flagged WA, sitting at
the base of the single RWE PT_LOAD. The loader maps it executable; the section
header does not say so. The signature was otherwise a clean match — word[0] =
0x20400000 (a plausible SRAM initial SP), word[1] = 0x4429 = e_entry — but
the oracle never got to look, so:

  • no vector table was confirmed,
  • cortexm_thumb_paints never region-painted TMode=1, so the image decoded as
    A32 instead of Thumb,
  • the vector handler seeds (8 unique Thumb targets) were never harvested, so the
    recursive-descent walk had nothing to follow.

Result: 8 functions recovered out of ~146.

The fix

cortexm_vector_table now also considers sections the program headers load as
executable: allocated sections wholly contained in a PF_X PT_LOAD
(phdr_executable_sections). The program header is the loader's own answer to "is
this executable memory?", which is both more correct and stricter than simply
dropping the section-flag test.

The fix widens where we look, never what we accept:

  • every acceptance test on the table contents is untouched — SRAM-plausible
    initial SP (0x2000_0000..=0x3FFF_FFFF), word[1] == e_entry, odd (Thumb)
    handler pointers landing in mapped executable memory, the min_target /
    CORTEXM_MAX_VECTORS walk bounds;
  • SHF_EXECINSTR sections are still tried first (and the widened set is only
    collected if none of them carries the table), so an image that already matched
    matches the same section as before;
  • an object with no program headers — a relocatable .o — yields an empty
    widened set, so that path is bit-for-bit unchanged;
  • non-ELF formats never produce an ELF SegmentFlags, so PE/Mach-O are unchanged;
  • the whole oracle remains 32-bit-ARM-gated.

Why no option (strict bug fix)

Judged a strict bug fix under the CLAUDE.md rule, not a feature:

  • It does not add a heuristic — it removes an incorrect precondition on an
    already-default-on oracle. The discovery-tier passes that are gated
    (funcstart_patterns, aif, addrtable) are gated because they are heuristic
    supersets that speculatively add entries; oracle 6 is not one of those and
    ships default-on today. Gating the correct form of a default-on oracle behind
    an opt-in would leave the wrong behavior as the default.
  • The acceptance signature is unchanged and is an exact two-word match including
    word[1] == e_entry. For this to newly fire on a non-firmware binary, that
    binary would have to be a 32-bit ARM ELF whose non-executable, PF_X-loaded
    section begins with an SRAM-range word followed by exactly its own entry point —
    i.e. an actual Cortex-M vector table.
  • Measured: 0/675 datatest assertions moved, stages parity unchanged, and the
    four control binaries below are identical before and after. The other three ARM
    firmware images in the corpus carry the same non-executable .isr_vector, and
    each stays untouched for an independent reason worth stating: betaflight's and
    cleanflight's tables sit in non-executable R PT_LOADs, so the widened set
    excludes them; crazyflie's is inside the R E load and is therefore newly
    examined — and is rejected by the unchanged acceptance test (word[1] is
    0x8025239, not its e_entry 0x80041c0). The signature, not the section flag,
    is what decides.
  • Precedent: DIV-32 and DIV-33 are analysis-tier discovery changes that moved
    entry counts and shipped as no-flag bug fixes.

Recorded as DIV-44 in docs/history.md.

Measured

kuna functions on the decbench full_run corpus (--mode aggressive for the
firmware images, whose auto resolution differs by size):

binary before after
freertos O0 RTOSDemo.out 8 146
freertos O2 RTOSDemo.out 8 118
freertos O2-noinline RTOSDemo.out 9 147
coreutils O0 ls (x86-64 control) 617 617
betaflight STM32F405 (working-ARM control) 5,798 5,798
crazyflie cf2.elf 2,790 2,790
cleanflight DALRCF405 2,840 2,840

The three freertos function sets are byte-identical to the control experiment
that hand-flipped .isr_vector's sh_flags from 0x3 (WA) to 0x6 (AX) on a
scratch copy of each ELF and ran the pre-fix binary — i.e. the fix recovers
exactly what the flag gate was costing, and nothing else. That control experiment
had already been scored against decbench's ground truth as 5 → 107 of 107 measured
functions covered (O0), 1 → 57 of 57 (O2), 1 → 97 of 101 (O2-noinline); those
coverage figures carry over unchanged because the function sets are identical.

Spot check of the newly recovered code (freertos O0) — real Thumb bodies, not A32
garbage:

void sub_1b04(void)          // prvIdleTask
{
  do {
    sub_1b94();              // prvCheckTasksWaitingTermination
  } while( true );
}

Speed

The change is confined to entry discovery, which runs a bounded number of times per
load (Listing::build is called ≤ 4 times, not per function), so the whole-binary
cost is unmeasurable. This box is shared with other agents running heavy decompiles,
so the discovery-path numbers are 7 interleaved before/after runs; both binaries
were built in this worktree from the same toolchain, differing only by the diff.

measurement (betaflight STM32F405) before after delta
decompile-all, whole binary, single run 81.10 s 78.49 s −3.2 %
functions --mode aggressive, 7 interleaved, min 4.905 s 4.889 s −0.3 %
functions --mode aggressive, 7 interleaved, median 5.044 s 5.176 s +2.6 %

Inside the +5 % budget, and betaflight's whole-binary decompile-all output is
md5-identical before and after (d061a4b37a7cb31df9c243169aa51953).

freertos O0 decompile-all goes 0.19 s → 1.46 s, but that is 8 → 146 functions
actually decompiled: 0.024 s → 0.010 s per function.

On betaflight the widened set is never even consulted for the table (its
.isr_vector sits at 0x20000000 in a read-only R load, so it is excluded); what
the fix costs there is one pass over 7 program headers and 16 section headers,
against the 507 KiB .text copy executable_sections already does on the same call.

Tests

Three new Rust tests in kuna-analysis (analyzers::entry::tests), driven by a
hand-assembled little-endian ELF32 ARM firmware image (build_cortexm_elf32, no
external toolchain) that reproduces the freertos shape exactly:

  • cortexm_vector_table_in_nonexec_section — asserts the bug shape first
    (.isr_vector is not an SHF_EXECINSTR section, so the old candidate set could
    not see it) and then the fixed shape: it is in a PF_X PT_LOAD, the
    table is detected, cortexm_vector_entries harvests the reset + handler seeds,
    collect_entries carries them, and cortexm_thumb_paints emits the whole-image
    TMode=1 region paint.
  • cortexm_vector_table_requires_executable_load — the same WA section in an
    RW (non-PF_X) load, and an image with no program headers at all, are both
    still invisible. This is what proves the fix is program-header containment and
    not "ignore the section flags".
  • cortexm_vector_table_exec_section_unchanged — an AX .isr_vector (the shape
    that already worked) still matches through executable_sections, with the same
    seeds, and contributes nothing to the widened delta set.

An XML stage testcase is not a fit here (the corpus has no ARM firmware image and
this is an analysis-tier discovery fact, not an emitted-C assertion) — same
treatment as the other analysis-tier discovery work.

Gates

All run in this worktree against the final commit:

  • make test — PARITY OK, 675/675 assertions
  • make test-stages — PARITY OK, 305/305 assertions
  • make rust-test — green (whole workspace, --no-fail-fast, exit 0)
  • make check-spec — green
  • kuna catalog --check — catalog OK (no option added, so no catalog counts move)

docs/baseline.json was not re-pinned; nothing needed it.

🤖 Generated with Claude Code

https://claude.ai/code/session_011RXVU58TKJxb518oViChwo

…ction (DIV-44)

The Cortex-M vector-table oracle (entry-discovery oracle 6) looked for
the table only inside `SHF_EXECINSTR` sections. That is a category
error: the vector table is DATA the CPU reads on reset (word 0 -> SP,
word 1 -> PC), not code. What has to be executable is what its handler
entries POINT AT -- which the harvest already checks, and still does.

Every FreeRTOS demo image links `.isr_vector` at VMA 0 flagged `WA`, at
the base of the single `RWE` PT_LOAD. The loader maps it executable;
the section header does not say so. The signature was otherwise a clean
match (word[0] = 0x20400000, a plausible SRAM initial SP; word[1] =
0x4429 = e_entry), but the oracle never got to look -- so no table was
confirmed, `cortexm_thumb_paints` never region-painted TMode=1 (the
image decoded as A32), and the 8 unique Thumb handler seeds were never
harvested, leaving the recursive-descent walk nothing to follow.

`cortexm_vector_table` now also considers sections the PROGRAM HEADERS
load as executable: allocated sections wholly contained in a PF_X
PT_LOAD (`phdr_executable_sections`). The program header is the
loader's own answer to "is this executable memory?", which is stricter
and more correct than dropping the section-flag test. The fix widens
WHERE we look, never WHAT we accept: every acceptance test on the table
contents is untouched, SHF_EXECINSTR sections are still tried first (so
an image that already matched matches the same section), and an object
with no program headers -- a relocatable .o -- yields an empty widened
set.

Strict bug fix, no option: this removes an incorrect precondition on an
already-default-on oracle rather than adding a heuristic, and the
unchanged two-word signature (including word[1] == e_entry) is what
still decides. Recorded as DIV-44.

Measured (`kuna functions`, decbench full_run):

  freertos O0  RTOSDemo.out    8 -> 146
  freertos O2  RTOSDemo.out    8 -> 118
  freertos O2-noinline         9 -> 147
  coreutils O0 ls (x86-64)   617 -> 617
  betaflight STM32F405      5798 -> 5798
  crazyflie  cf2.elf        2790 -> 2790
  cleanflight DALRCF405     2840 -> 2840

The three freertos function sets are byte-identical to the control
experiment that hand-flipped `.isr_vector`'s sh_flags from 0x3 (WA) to
0x6 (AX) on a scratch copy and ran the pre-fix binary -- the fix
recovers exactly what the flag gate was costing, and nothing else.
betaflight's whole-binary `decompile-all` output is md5-identical
before and after; 81.10 s -> 78.49 s, and the discovery path over 7
interleaved runs is 4.905 s -> 4.889 s (min), inside the +5% budget.

Regression coverage: three Rust tests in kuna-analysis driven by a
hand-assembled ELF32 ARM firmware image -- the bug shape (`WA`
`.isr_vector` invisible to `executable_sections`) now resolves, an `RW`
load and a program-header-less image stay invisible (proving the test
is PF_X containment, not "ignore the flags"), and an `AX` `.isr_vector`
still matches unchanged.

Gates: test 675/675 PARITY OK, test-stages 305/305 PARITY OK,
rust-test green, check-spec green, catalog --check green. No baseline
re-pin.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_011RXVU58TKJxb518oViChwo
@mahaloz
mahaloz merged commit 43f0d38 into main Aug 1, 2026
9 checks passed
@mahaloz
mahaloz deleted the fix/cortexm-vector-nonexec-section branch August 1, 2026 18:39
mahaloz added a commit that referenced this pull request Aug 1, 2026
Two P6 cover-extension steps were dropped in the merge port, and each made
kuna emit C that computes a DIFFERENT VALUE than the binary.

1. `Funcdata::build_copy_pair_range` built `Merge::checkCopyPair`'s dominance
   range from the dominant COPY's def point alone, omitting upstream's
   `range.addRefPoint(subOp, subOp->getIn(0))` (merge.cc:1121). A def-point-only
   Cover is a point, not a range, so no intervening write to the HighVariable was
   ever found inside it, `checkCopyPair` called every dominated COPY redundant,
   and `markRedundantCopies` marked load-bearing restores non-printing. At -O0 a
   guard-clause function whose `return param;` paths share one epilogue then
   returns a failed call's NULL instead of the parameter, and `for` loops lose
   their initializer. The sibling `build_single_read_cover` records the identical
   omission as LOSS-229 and had already been fixed; this is the second site.

2. `ActionMarkImplied` set the implied flag directly instead of going through
   `Merge::markImplied` (merge.cc:1595-1605), dropping the operand cover-dirtying,
   and `MergeContext::vn_set_cover_dirty` did not forward a Varnode `coverdirty`
   to the owning HighVariable the way `Varnode::setFlags` does
   (varnode.cc:377-378). `Cover::rebuild` walks forward through implied consumers,
   so an operand's live range only reaches the point where the inlined expression
   is printed once it is recomputed — and `HighIntersectTest::update_high`
   short-circuits on a high it believes is clean. Without both halves the
   speculative merges saw pre-inlining Covers and folded two values that are live
   at the same printed expression into one variable, so the emitted C read the
   later value where the binary reads the earlier one.

Both are upstream-faithful restorations, not new policy, so neither ships behind
an option: a default-off flag would leave kuna miscompiling by default.

Gates: make test PARITY OK (675/675), make test-stages PARITY OK (314/314),
make rust-test green, make check-spec green, kuna catalog --check OK. No baseline
re-pin and no per-test opt-out.

Regression: new fixture `covercopy_x86_64` (+ source) and
`kuna-console/tests/verify_cover_miscompile.rs`, one test per root cause,
asserting the VALUE-carrying statement (the `vN = a0;` restore after the
clobbering call; the two selects staying two variables and both being read by the
call argument). Each test fails on the pre-fix tree.

`verify_declared_vars`' sanity floor moves 5 -> 4: with Covers recomputed at the
right points the `make_dir_clone` size phi finally coalesces with the `strlen`
result the way upstream does, so the un-coalesced `v5` is gone. The
undeclared-variable gate itself is unchanged and still passes.

Rebased onto origin/main after #227 (the P3 opcode -> TypeOp seam totalisation)
and re-verified end to end on that base; the root causes here are Cover
construction and Cover invalidation, not op property bits. DIV-44..46 were taken
by #224/#225/#226 while this was in flight, so this claims DIV-47.

Docs: DIV-47 in docs/history.md; docs/spec/06-variables-and-merge.md gains the
prose for both cover extensions (the two-point Cover construction and the
implied-consumer walk).

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_011RXVU58TKJxb518oViChwo
mahaloz added a commit that referenced this pull request Aug 1, 2026
#228)

Two P6 cover-extension steps were dropped in the merge port, and each made
kuna emit C that computes a DIFFERENT VALUE than the binary.

1. `Funcdata::build_copy_pair_range` built `Merge::checkCopyPair`'s dominance
   range from the dominant COPY's def point alone, omitting upstream's
   `range.addRefPoint(subOp, subOp->getIn(0))` (merge.cc:1121). A def-point-only
   Cover is a point, not a range, so no intervening write to the HighVariable was
   ever found inside it, `checkCopyPair` called every dominated COPY redundant,
   and `markRedundantCopies` marked load-bearing restores non-printing. At -O0 a
   guard-clause function whose `return param;` paths share one epilogue then
   returns a failed call's NULL instead of the parameter, and `for` loops lose
   their initializer. The sibling `build_single_read_cover` records the identical
   omission as LOSS-229 and had already been fixed; this is the second site.

2. `ActionMarkImplied` set the implied flag directly instead of going through
   `Merge::markImplied` (merge.cc:1595-1605), dropping the operand cover-dirtying,
   and `MergeContext::vn_set_cover_dirty` did not forward a Varnode `coverdirty`
   to the owning HighVariable the way `Varnode::setFlags` does
   (varnode.cc:377-378). `Cover::rebuild` walks forward through implied consumers,
   so an operand's live range only reaches the point where the inlined expression
   is printed once it is recomputed — and `HighIntersectTest::update_high`
   short-circuits on a high it believes is clean. Without both halves the
   speculative merges saw pre-inlining Covers and folded two values that are live
   at the same printed expression into one variable, so the emitted C read the
   later value where the binary reads the earlier one.

Both are upstream-faithful restorations, not new policy, so neither ships behind
an option: a default-off flag would leave kuna miscompiling by default.

Gates: make test PARITY OK (675/675), make test-stages PARITY OK (314/314),
make rust-test green, make check-spec green, kuna catalog --check OK. No baseline
re-pin and no per-test opt-out.

Regression: new fixture `covercopy_x86_64` (+ source) and
`kuna-console/tests/verify_cover_miscompile.rs`, one test per root cause,
asserting the VALUE-carrying statement (the `vN = a0;` restore after the
clobbering call; the two selects staying two variables and both being read by the
call argument). Each test fails on the pre-fix tree.

`verify_declared_vars`' sanity floor moves 5 -> 4: with Covers recomputed at the
right points the `make_dir_clone` size phi finally coalesces with the `strlen`
result the way upstream does, so the un-coalesced `v5` is gone. The
undeclared-variable gate itself is unchanged and still passes.

Rebased onto origin/main after #227 (the P3 opcode -> TypeOp seam totalisation)
and re-verified end to end on that base; the root causes here are Cover
construction and Cover invalidation, not op property bits. DIV-44..46 were taken
by #224/#225/#226 while this was in flight, so this claims DIV-47.

Docs: DIV-47 in docs/history.md; docs/spec/06-variables-and-merge.md gains the
prose for both cover extensions (the two-point Cover construction and the
implied-consumer walk).


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

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

The recall pool was the campaign's headline claim and it was carrying an
unverified number. Measured properly it is 7,354, not 6,540 -- the smaller
figure could not be reproduced under any rival-subset or filter variant.

Where it actually goes, and most of this contradicts what the campaign
believed:

  63    (0.9%)  genuinely recovered by the 2026-08-01 fix wave
  1,994 (27.1%) already fixed BEFORE the wave -- the stored kuna artifacts
                were 12-16 days old, so the pool was measuring staleness
  3,233 (44.0%) decbench's .text filter, never kuna's fault
  2,061 (28.0%) still missing, real kuna gap

So the wave's benchmark-visible recall gain is small and the campaign should
say so. Two corrections in the other direction: #224 recovered 256 freertos
functions decbench structurally cannot score, and both #227 and #234
under-claimed (19 -> measured 50; 6 -> measured 13).

98.3% of the live remainder is function-entry granularity on embedded ARM --
kuna emits a body for code CONTAINING the DWARF low_pc but does not start a
function AT it, median 24 bytes away. That is one gap, not two thousand.

Highest-value remaining bug: rename_recurse / "Overlapping input varnodes" on
gnulib's rpl_fcntl, hard-failing one function in 48 of 213 optimized x86-64
binaries, -O2 only.

Method notes worth keeping: matching is by address, never by name; PE targets
report ImageBase+RVA where the rival artifacts record RVAs, and uncorrected
that fabricates 181 fake gaps.
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