Repository navigation
[AUTOMATED] feat(p5): loadguardrange - complete the LoadGuard/StoreGuard ValueSet range refinement so indexed stack arrays get real bounds (DIV-77) - #308
Merged
Conversation
… 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
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]>
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.
Fixes #182
Root cause
For a stack array accessed through a computed index, the only bound P6 ever saw was the
min_items = 3fallback inFuncdata::gather_open: the entire upstream LoadGuard/StoreGuard range-refinement machinery was stubbed (ValueSetSolver::establishValueSets/solvereturnedErr,LoadGuard::establishRange/finalizeRangeandHeritage::analyzeNewLoadGuards/handleNewLoadCopieswereSTUB(W6), andgather_openskipped theMapState::addGuardloops). Every guard keptstep = 0and the whole-space range,addGuardupstream bails onstep == 0, so no real index bound could ever exist.RangeHint::attempt_jointhen rejected thestack-0x1chint ondiffsz(4) > highind(3)— betaflightcliServoprintedint2 v5 [4]written atv5[v2]withv2provably 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)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-IRValueSetEdgesuccessor source — on top of the already-ported-and-testedCircleRange/widening/Bourdoncle-ordering machinery. Where the C++ threads aVarnode->ValueSetback-pointer plus Varnode/PcodeOp/FlowBlock mark bits, the port keeps aVarnodeId -> nodemap 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.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).p6_variables/funcdata_spacebase.rs: thegatherOpenguard iteration (varmap.cc:1241-1248) andMapState::addGuard(varmap.cc:1003), including thestep == 0bail, the LOAD/STORE-size-vs-step reconciliation, the align-size type fallback, andhighind = ((max-min)+1)/step - 1for a range-locked guard.Documented deviations from upstream (both defensive-only, both commented at the site):
analyzeNewLoadGuards' C++ update loops start at the post-breakiterator, which can include one already-analyzed boundary guard whose SeqNum is not inreadNodes— upstream then dereferencesmap::find() == end()(UB). The port skips guards with no read node (the sane interpretation of the same loop).handleNewLoadCopiesis ported in full but its work list (loadCopyOps) is only filled byguardLoads, which sits behind the still-disabledhighPtrPossibleseam — 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).offreproduces the pre-port output byte-identically (verified on the witness:--option loadguardrange offoutput is byte-identical to main's).tier = core, fullphases.tomlrow with symptoms/use_when,kuna catalog --checkgreen,docs/options.mdregenerated.Witness (before / after)
kuna decompile-all tests/bug-repro/betaflight_STM32F405.elf --addr 0x801b4a4(cliServo):Before (=
option loadguardrange off):After (default):
[8]rather than[6]because the open range fills to the next mapped local — the sameshort local_24 [8]stock Ghidra prints for this function; every access is in bounds and no tail scalar splits off. Thedecompile-project.cand.asmartifacts carry the same fix (; stack: v7 @ [stack-0x24] (int2[8])).Second witness (
diff3main@ 0x2a20, not vendored in-repo — decbenchresults/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 inmapping[]'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 astep, andaddGuardbails 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:Every one of the 18 changes is one of three shapes, all upstream-faithful:
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]withacStack28[8]), sortsub_8d304 scalars→char *[4](the"coreutils"/"sha224sum"string table), libselinuxsub_1c650→char *[3], grepsub_1ed40two 8-byte slots→long [2].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), betaflightsub_802a338(int2 [29]open-fill →[2]+[2]; Ghidra also splits this region into small pieces, no giant array).Mergeuntied-call intersection now tests the real range), so a deadunsigned long vN; vN = vN;pair (grepsub_1d410/sub_1d4b0/sub_1eca0, sortsub_12ca0, libselinuxsub_22240, betaflightsub_8052428,sub_8046d48) and two dead 16-byte shadow buffers (grepsub_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 realcliServobytes (ARM Cortex-M Thumb, callees stubbedbx lr), two passes: default asserts the single in-boundsint2 v7 [8]withv7[4]/v7[5]element reads;option loadguardrange offpins the[4]cap + split-off never-assignedv8/v9and the uninitialized config store. Corpus count bumped to 207 (kuna-base/src/xml.rs),docs/baseline-stages.jsonre-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)
phase_catalog.jsonfixture /docs/options.md: 108 settables (regenerated, not merged)kuna_phases/tests.rs: settables 108, tiers (core, transform, analysis) = (24, 47, 37),},\n107, live readers 34 (suppressed 74)catalog_bytecompat.rs: 108 x3Spec
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 (WidenerNoneestablish,WidenerFullfinalize), range locking, and cross-references chapters 05/06.docs/spec/06-variables-and-merge.md: thegather_openbullet gains theaddGuardhint source and the real-highindjoin behavior.make check-specgreen.Gates (rebased tree)
make test: 675/675, PARITY OK (the default-ON flip changes 0 datatest assertions)make test-stages: 481/481, PARITY OKmake rust-test: greenmake check-spec: greenkuna catalog --check: OKSpeed
Interleaved on/off (same rebased binary, the only delta being
--option loadguardrange off), wall-clock minimum:grep(whole binary, 449 fns)betaflight_STM32F405.elf(whole binary, 5,797 fns)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