Skip to content

[AUTOMATED] feat(p5): loadguardrange - complete the LoadGuard/StoreGuard ValueSet range refinement so indexed stack arrays get real bounds (DIV-77) - #308

Merged
mahaloz merged 1 commit into
mainfrom
fix/i182-loadguard-range
Aug 16, 2026
Merged

mahaloz merged 1 commit into
mainfrom
fix/i182-loadguard-range

Conversation

@mahaloz

@mahaloz mahaloz commented Aug 16, 2026

Copy link
Copy Markdown
Contributor

Fixes #182

Root cause

For a stack array accessed through a computed index, the only bound P6 ever saw was the min_items = 3 fallback in Funcdata::gather_open: the entire upstream LoadGuard/StoreGuard range-refinement machinery was stubbed (ValueSetSolver::establishValueSets/solve returned Err, LoadGuard::establishRange/finalizeRange and Heritage::analyzeNewLoadGuards/handleNewLoadCopies were STUB(W6), and gather_open skipped the MapState::addGuard loops). Every guard kept step = 0 and the whole-space range, addGuard upstream bails on step == 0, so no real index bound could ever exist. RangeHint::attempt_join then rejected the stack-0x1c hint on diffsz(4) > highind(3) — betaflight cliServo printed int2 v5 [4] written at v5[v2] with v2 provably in [0,5], and elements 4/5 split off as never-assigned scalars that were range-checked and stored into the servo config.

What was ported (pinned upstream GHIDRA_REV)

  1. ValueSetSolver IR binding — p5_types/rangeutil.rs: establishValueSets (rangeutil.cc:2416), solve (rangeutil.cc:2524), ValueSet::setVarnode/iterate/computeTypeCode (rangeutil.cc:1503/1611/1567), the whole constraint-generation pipeline (generateConstraints/constraintsFromCBranch/constraintsFromPath/applyConstraints/generateTrue|FalseEquation/checkRelativeConstant/generateRelativeConstraint, rangeutil.cc:2066-2406), and the live-IR ValueSetEdge successor source — on top of the already-ported-and-tested CircleRange/widening/Bourdoncle-ordering machinery. Where the C++ threads a Varnode->ValueSet back-pointer plus Varnode/PcodeOp/FlowBlock mark bits, the port keeps a VarnodeId -> node map and side sets on the solver (upstream always sets the back-pointer and the mark together, and clears the marks when the solver dies, so membership is observationally identical); nothing iterates a hash container in an order-sensitive way.
  2. LoadGuard analysis — p3_dataflow/heritage.rs: LoadGuard::establishRange/finalizeRange (heritage.cc:741/788), LoadGuard::isValid, Heritage::analyzeNewLoadGuards (heritage.cc:834), handleNewLoadCopies/findAddressForces/propagateCopyAway (heritage.cc:618-730), called at the upstream point at the end of each heritage pass (heritage.cc:2753-2754).
  3. MapState::addGuard loops — p6_variables/funcdata_spacebase.rs: the gatherOpen guard iteration (varmap.cc:1241-1248) and MapState::addGuard (varmap.cc:1003), including the step == 0 bail, the LOAD/STORE-size-vs-step reconciliation, the align-size type fallback, and highind = ((max-min)+1)/step - 1 for a range-locked guard.

Documented deviations from upstream (both defensive-only, both commented at the site):

  • analyzeNewLoadGuards' C++ update loops start at the post-break iterator, which can include one already-analyzed boundary guard whose SeqNum is not in readNodes — upstream then dereferences map::find() == end() (UB). The port skips guards with no read node (the sane interpretation of the same loop).
  • Solver inputs that upstream's invariants guarantee are in the system are handled with a set-full fallback instead of a null-pointer dereference if the invariant were ever violated.
  • handleNewLoadCopies is ported in full but its work list (loadCopyOps) is only filled by guardLoads, which sits behind the still-disabled highPtrPossible seam — so its live behavior is the faithful empty-list early return (noted in the spec).

Option

loadguardrange (on|off), default ON — restores stock upstream Ghidra behavior (DIV-77). off reproduces the pre-port output byte-identically (verified on the witness: --option loadguardrange off output is byte-identical to main's). tier = core, full phases.toml row with symptoms/use_when, kuna catalog --check green, docs/options.md regenerated.

Witness (before / after)

kuna decompile-all tests/bug-repro/betaflight_STM32F405.elf --addr 0x801b4a4 (cliServo):

Before (= option loadguardrange off):

int2 v7 [4]; // stack - 0x24    <<< declared 4 elements; real array is 6
int2 v8; // stack - 0x1c        <<< element 4, never assigned
int2 v9; // stack - 0x1a        <<< element 5, never assigned
...
v7[v3] = cli_atoi(a1);          // under if (5 < v3) return;  -> writes v7[4], v7[5]
... (((-100 <= v8 && (v8 <= 100)) && (v9 <= 0x11))) ...
*(char *)(v2 + 10) = (char)v8;  // uninitialized read stored into config

After (default):

int2 v7 [8]; // stack - 0x24    <<< ONE array covering all six elements
...
v7[v3] = cli_atoi(a1);          // in bounds
... (((-100 <= v7[4] && (v7[4] <= 100)) && (v7[5] <= 0x11))) ...
*(char *)(v2 + 10) = (char)v7[4];

[8] rather than [6] because the open range fills to the next mapped local — the same short local_24 [8] stock Ghidra prints for this function; every access is in bounds and no tail scalar splits off. The decompile-project .c and .asm artifacts carry the same fix (; stack: v7 @ [stack-0x24] (int2[8])).

Second witness (diff3 main @ 0x2a20, not vendored in-repo — decbench results/full_run/O2/diffutils/stripped/diff3): unchanged, and that is the faithful outcome — its index bound is data-dependent (rev_mapping[mapping[i]]: the bound lives in mapping[]'s contents, not in any branch), so upstream's solver cannot derive it either (the loaded index is a full-range value set, the guard never acquires a step, and addGuard bails the same way in stock Ghidra).

Whole-binary collateral audit

decompile-all --json, base (main at the shared merge-base) vs fixed, all functions diffed and every change reviewed:

binary functions changed
grep 449 5
sort 490 2
faillog 69 0
libselinux.so.1 502 3
betaflight_STM32F405.elf 5797 8

Every one of the 18 changes is one of three shapes, all upstream-faithful:

  1. Arrays gaining their real index bound (the fix): betaflight cliServo [4]→[8], sub_80170bc [4]→[5], sub_801dcd8 [4]+4 scalars→[9], sub_806c7e4 [4]+5 scalars→[9], sub_8025944 [8]+flag byte→[16] (verified identical shape to stock Ghidra: char acStack28 [16] with acStack28[8]), sort sub_8d30 4 scalars→char *[4] (the "coreutils"/"sha224sum" string table), libselinux sub_1c650 →char *[3], grep sub_1ed40 two 8-byte slots→long [2].
  2. Over-wide open-filled arrays narrowing to the guard's real range: libselinux get_default_type (char [264] → the scalar + *(char *)((long)&vN + len + 7) rendering — verified verbatim the same shape stock Ghidra prints for this function, char local_148 + *(char *)((long)&local_150 + sVar4 + 7); the pre-fix [264] was the divergence), betaflight sub_802a338 (int2 [29] open-fill → [2]+[2]; Ghidra also splits this region into small pieces, no giant array).
  3. Dead copy-shadow elimination: the narrowed store-guard ranges stop forcing unrelated stack copies live across an indexed STORE (Merge untied-call intersection now tests the real range), so a dead unsigned long vN; vN = vN; pair (grep sub_1d410/sub_1d4b0/sub_1eca0, sort sub_12ca0, libselinux sub_22240, betaflight sub_8052428, sub_8046d48) and two dead 16-byte shadow buffers (grep sub_12650) disappear.

Adjudication for the two non-obvious cases was done against stock Ghidra headless on the same binaries (outputs in the PR discussion above); both match Ghidra exactly.

Post-rebase re-check on the final base (off-vs-on with the one rebased binary, so the flag is the only variable): betaflight changes exactly the same 8 functions; grep changes 2 (sub_12650, sub_1ed40, same shapes) — the three dead-vN = vN; copy-shadow cases were independently cleaned up on main by GH-181's snipReads fix (#307), so the flag no longer touches them.

Stage test

tests/stages/gh182-loadguardrange.xml — the real cliServo bytes (ARM Cortex-M Thumb, callees stubbed bx lr), two passes: default asserts the single in-bounds int2 v7 [8] with v7[4]/v7[5] element reads; option loadguardrange off pins the [4] cap + split-off never-assigned v8/v9 and the uninitialized config store. Corpus count bumped to 207 (kuna-base/src/xml.rs), docs/baseline-stages.json re-recorded (481 keys; vs origin/main the diff is exactly the 8 new LOADGUARDRANGE keys), README row added.

Catalog counters (all re-derived from the rebased green build)

  • live catalog / phase_catalog.json fixture / docs/options.md: 108 settables (regenerated, not merged)
  • kuna_phases/tests.rs: settables 108, tiers (core, transform, analysis) = (24, 47, 37), },\n 107, live readers 34 (suppressed 74)
  • catalog_bytecompat.rs: 108 x3
  • No new scheduled Action: the refinement runs inside the existing heritage pass, exactly as upstream — the action-tree oracle, leaf counts, and pass-adjacency allowlist are untouched.

Spec

  • docs/spec/05-types.md: the "over-wide alias guards ... never a wrong range" claim (this issue's counterexample) replaced with the live-solver description + the under-sized-range failure mode it fixes.
  • docs/spec/03-ssa-and-simplification.md: the LOAD/STORE-guard section now describes the live two-stage solve (WidenerNone establish, WidenerFull finalize), range locking, and cross-references chapters 05/06.
  • docs/spec/06-variables-and-merge.md: the gather_open bullet gains the addGuard hint source and the real-highind join behavior.
  • make check-spec green.

Gates (rebased tree)

  • make test: 675/675, PARITY OK (the default-ON flip changes 0 datatest assertions)
  • make test-stages: 481/481, PARITY OK
  • make rust-test: green
  • make check-spec: green
  • kuna catalog --check: OK

Speed

Interleaved on/off (same rebased binary, the only delta being --option loadguardrange off), wall-clock minimum:

binary runs min ON min OFF delta
grep (whole binary, 449 fns) min-of-11 13.610 s 13.621 s -0.08% (below the noise floor)
betaflight_STM32F405.elf (whole binary, 5,797 fns) min-of-3 59.212 s 58.670 s +0.92%

The solver only runs where indexed-stack guards exist, and each system is tiny (the guard pointer's def-slice); grep is indistinguishable, and the guard-rich 5,797-function firmware pays under 1%. (betaflight is min-of-3 rather than min-of-11 to bound total measurement time; the three interleaved pairs sit within 1.6% of each other.)

🤖 Generated with Claude Code

https://claude.ai/code/session_01VBn8vgwoHqPFnnV4ZMApfq

… range refinement (DIV-77)

Fixes #182: a stack array written through a computed index was capped at
the min_items = 3 fallback, splitting every element past index 3 into a
separate never-assigned scalar and printing out-of-bounds subscripts
(betaflight cliServo: int2 v5[4] written at v5[v2] with v2 in [0,5]).

Three ports, all from the pinned upstream GHIDRA_REV:
- ValueSetSolver IR binding (p5_types/rangeutil.rs): establishValueSets,
  solve, ValueSet::setVarnode/iterate/computeTypeCode, the constraint
  generation pipeline (generateConstraints/constraintsFromCBranch/
  constraintsFromPath/applyConstraints/generateTrue|FalseEquation/
  checkRelativeConstant/generateRelativeConstraint) and the live-IR
  ValueSetEdge successor source, on top of the already-ported
  CircleRange/widening/Bourdoncle machinery (rangeutil.cc:1503-2585).
- LoadGuard analysis (p3_dataflow/heritage.rs): LoadGuard::establishRange/
  finalizeRange/isValid, Heritage::analyzeNewLoadGuards/
  handleNewLoadCopies/findAddressForces/propagateCopyAway
  (heritage.cc:618-900), called at the end of each heritage pass
  (heritage.cc:2753-2754).
- MapState::addGuard loops (p6_variables/funcdata_spacebase.rs): the
  gatherOpen LOAD/STORE guard iteration (varmap.cc:1241-1248) and
  MapState::addGuard (varmap.cc:1003) supplying the real index bound
  highind = ((max-min)+1)/step - 1 to RangeHint::attempt_join.

Shipped behind new option `loadguardrange`, DEFAULT-ON (restores stock
upstream Ghidra behavior, DIV-77; 0/675 datatest ablation, stages
481/481). `option loadguardrange off` reproduces the pre-port output
byte-identically. Two-pass stage gate tests/stages/gh182-loadguardrange.xml
(corpus 207, baseline re-recorded); catalog at 108 settables with every
counter re-derived from the built artifact; spec chapters 03/05/06
updated (the "never a wrong range" claim replaced with the live
refinement). Speed: grep min-of-11 -0.08% (noise), betaflight
whole-binary min-of-3 +0.92%.

[AUTOMATED]

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VBn8vgwoHqPFnnV4ZMApfq
@mahaloz
mahaloz merged commit 40c829e into main Aug 16, 2026
9 checks passed
@mahaloz
mahaloz deleted the fix/i182-loadguard-range branch August 16, 2026 20:46
mahaloz added a commit that referenced this pull request Aug 17, 2026
The branch was cut from #302 while main advanced to #316; the engine
PRs in between (spillargtrial #315, stackguard #306, snip-reads #307,
loadguardrange #308, ...) legitimately shift the ghidra-path output, so
CI's merge-ref run measured register leaks 108 vs the pinned 106. Rebase
onto origin/main and re-pin every value to the rebased tree:

  registers 106/64/60 -> 108/58/60, unique 32/2/8 -> 34/4/8,
  mangled 21/13/7 -> 21/6/7, c_lines 241/174/89 -> 243/128/89,
  diff ratios 0.643/0.898/0.811 -> 0.646/0.867/0.811 (band unchanged);
  placeholders/resolvable/traffic unchanged (49/25/17, 24/18/14,
  1477/1003).

The sub_3320 shrink (c_lines -26%, FS_OFFSET gone from its register
set, mangled 13 -> 6) is the stackguard/snip-reads work stripping the
canary sequence -- explainable, not suspicious. Determinism verified:
three consecutive runs of the pins test are measurement-identical.

Gates on the rebased tree: harness release + --include-ignored green,
make test 675/675 PARITY OK, make test-stages PARITY OK, check-spec OK,
kuna-ghidra dev-profile spot check green. The full workspace suite ran
green on this branch pre-rebase and every added commit is already-CI-
green main history, so it is covered by the branch + main CI runs.

[AUTOMATED]

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01AfGYKwUWvPYYj1Aw7tcLhC
mahaloz added a commit that referenced this pull request Aug 17, 2026
…the GUI-path quality gap (#317)

* feat(ghidra): ghidra-sim differential test harness — pin the GUI-path quality gap

Extract the decompile_at_e2e MockJava loopback into a shared module
(tests/ghidra_sim/mod.rs — AnswerSource-pluggable pump, wire builders,
session tracer, dual-<function> doc parser, a markup->C flattener that
replicates Java's getC() token cleaning (IllegalCharCppTransformer),
badness scanners, line-diff metric) and build ghidra-sim v1 on top
(tests/ghidra_sim/oracle.rs): a mock-Java answer source backed by kuna's
own analysis of real vendored ELFs — bootstrap_from_object for
bytes/labels, the real Sleigh re-encoded as wire <inst> docs for
getPcode, and a tspec GENERATED from the loaded Sleigh's
AddrSpaceManager so packed space indices agree by construction.
getMappedSymbols/getExternalRef answer EMPTY at a marked PHASE-3 SEAM.

tests/ghidra_sim_e2e.rs drives the full wire lifecycle (registerProgram
-> setAction -> decompileAt x3 -> flushNative -> repeat -> deregister)
over tests/bug-repro/faillog (sort/grep as an ignored breadth test),
asserts the response-document schema (name/entry echo, markup
opref/varref subset-of ast, 19-query legality + query-legal placement),
and PINS today's Phase-2 reality: per-function raw-register leaks
(106/64/60), Unique tokens (32/2/8), placeholders (49/25/17) of which
the loader already knows names for 24/18/14 (Phase 3 drives to 0),
getC()-mangled tokens (21/13/7, PR-C drives to 0), ghidra-vs-CLI line
diff ratios (0.64/0.90/0.81 floors), getPcode traffic 1477/1003, and
getMappedSymbols == 0 (Phase 3 flips to >=1). Pins move only with the
provider/emitter change that earns them.

[AUTOMATED]

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01AfGYKwUWvPYYj1Aw7tcLhC

* ci(ghidra): run the ghidra-sim harness in the gates job + make test-ghidra

Add a `gates`-job step running `cargo test -p kuna-ghidra --release --
--include-ignored` (with the standard specs-skip canary grep) after the
catalog checks: the workspace suite is skipped on internal PRs, and a
GUI-path regression is exactly what the ghidra-sim pins exist to catch
pre-merge. Cost: ~1-2 min of compile over the release deps `make
binaries` already built, ~2 s of test runtime. `make test-ghidra` is the
same run locally.

[AUTOMATED]

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01AfGYKwUWvPYYj1Aw7tcLhC

* docs(ghidra): live-smoke rig + testing-strategy section for the harness

integrations/ghidra/live-smoke/: a manual/dev pyghidra rig that swaps
DecompileProcessFactory.exepath to kuna_ghidra inside a real Ghidra,
decompiles the same functions with both cores, and writes a side-by-side
report with the same badness-scanner counts the in-tree harness pins
(README covers the offline-pyghidra setup and the getC()-vs-GUI-panel
rendering distinction). docs/ghidra-integration.md §11 rewritten around
the shipped harness: what it covers, how to run it, where the pins live.

[AUTOMATED]

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01AfGYKwUWvPYYj1Aw7tcLhC

* test(ghidra): harden the ghidra-sim pins per adversarial review

- Diff-ratio pins are now a BAND: ceilings [0.70,0.95,0.90] join the
  floors (a markup regression that makes the GUI text worse now fails
  instead of saturating), the vacuous `<= 1.0` assert is gone, and the
  flattened-C normalized line count is pinned per target (241/174/89) --
  the assert that actually catches a <break>-token collapse. The pin
  comment now decomposes the ratio (Phase-3 symbol gap + option-preset
  skew until setOptions is wired) so nobody chases 0 with symbol work.
- decompile_cli now routes through the SHARED per-function step
  (kuna_console::decompile_step::decompile_one, DIV-66) with the
  error-noreturn CALL_RETURN flow overrides built exactly as
  kuna_console::project does -- the previous direct drive call silently
  dropped them (latent: faillog has no error() sites, and every faillog
  pin re-measured IDENTICAL; sort/grep-class fixtures would have
  diverged from the real CLI).
- Assert strength: warnings frames pinned trim-empty on registerProgram
  and decompileAt (no substring blocklists); markup oprefs AND varrefs
  pinned non-empty per class; ast varnode refs collected from the
  <varnodes> child only (all Java's buildVarnodeRefs keys -- an op
  operand ref undeclared there must not launder the subset assert);
  the name echo compares against the sim's code_label (which consults
  label_overrides) rather than the raw program lookup.
- CI: the gates-job harness step tees its output to a log before the
  canary grep, so a FAILING pin still prints its diagnostics (the old
  command substitution aborted under bash -e before any echo).
- live-smoke docs/script: kuna_ghidra is not built by `make binaries`;
  point at `cargo build --release -p kuna-ghidra`.

Tests/CI/docs-only diff: the parity gates are untouched by construction.
`cargo test -p kuna-ghidra --release -- --include-ignored` fully green;
`make check-spec` green. No pinned value moved.

[AUTOMATED]

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01AfGYKwUWvPYYj1Aw7tcLhC

* test(ghidra): re-measure the faillog pins on main @ 813ee13 (rebase)

The branch was cut from #302 while main advanced to #316; the engine
PRs in between (spillargtrial #315, stackguard #306, snip-reads #307,
loadguardrange #308, ...) legitimately shift the ghidra-path output, so
CI's merge-ref run measured register leaks 108 vs the pinned 106. Rebase
onto origin/main and re-pin every value to the rebased tree:

  registers 106/64/60 -> 108/58/60, unique 32/2/8 -> 34/4/8,
  mangled 21/13/7 -> 21/6/7, c_lines 241/174/89 -> 243/128/89,
  diff ratios 0.643/0.898/0.811 -> 0.646/0.867/0.811 (band unchanged);
  placeholders/resolvable/traffic unchanged (49/25/17, 24/18/14,
  1477/1003).

The sub_3320 shrink (c_lines -26%, FS_OFFSET gone from its register
set, mangled 13 -> 6) is the stackguard/snip-reads work stripping the
canary sequence -- explainable, not suspicious. Determinism verified:
three consecutive runs of the pins test are measurement-identical.

Gates on the rebased tree: harness release + --include-ignored green,
make test 675/675 PARITY OK, make test-stages PARITY OK, check-spec OK,
kuna-ghidra dev-profile spot check green. The full workspace suite ran
green on this branch pre-rebase and every added commit is already-CI-
green main history, so it is covered by the branch + main CI runs.

[AUTOMATED]

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01AfGYKwUWvPYYj1Aw7tcLhC

---------

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.

Undersized open stack array: indexed store renders out of bounds; tail elements split off

1 participant