Skip to content

Perf/actionpool cursor - #8

Merged
mahaloz merged 2 commits into
mainfrom
perf/actionpool-cursor
Jun 22, 2026
Merged

mahaloz merged 2 commits into
mainfrom
perf/actionpool-cursor

Conversation

@mahaloz

@mahaloz mahaloz commented Jun 22, 2026

Copy link
Copy Markdown
Contributor

No description provided.

mahaloz and others added 2 commits June 22, 2026 15:01
The ActionPool op-cursor cannot be a live BTreeMap iterator (the borrow
checker forbids holding it across the mutation a rule performs), so it is
modelled as the last-visited SeqNum and the next op is re-found each step.
That re-find was a linear front-scan (iter_all().find(|(k,_)| *k > sq)),
making the per-op advance O(N) and the whole rule-application pass O(N^2)
over the optree -- repeated across thousands of fixpoint passes.

C++ pays nothing here: op_state is a PcodeOpTree::const_iterator and
++op_state is O(1). Route the two cursor helpers (next_seqnum_after /
first_op_after) through a new PcodeOpBank::first_after_seq, an O(log n)
BTreeMap::range((Excluded(sq), Unbounded)).next() seek.

Whole-binary decompile of fmt (107 funcs): ~18.8s -> ~4.0s (4.7x),
output byte-identical, 675/675 datatest PARITY OK.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_018TNi2EzjQfRizjyNpo36y2
Two faithful, parity-safe cleanups to the rule-application hot loop that
the preceding O(N^2) cursor fix exposed:

* perop: BTreeMap<OpCode,_> -> Vec<PerOp> indexed by `opc as usize`, a
  CPUI_MAX-element flat table -- exactly the C++ `vector<Rule*>
  perop[CPUI_MAX]`. Turns each of the ~16.5M per-rule dispatch lookups
  from an O(log n) tree walk into an O(1) index.

* op-cursor advance: test successor existence with first_after_seq(..)
  .is_some() instead of cloning the successor SeqNum only to discard it,
  and borrow the range bound (Bound<&SeqNum>) so first_after_seq no
  longer clones its key -- removing millions of Address/Rc<AddrSpace>
  refcount bumps per run.

Output-preserving: 675/675 datatest PARITY OK, full workspace suite
3754/3754. NOTE: neither moves the fmt whole-binary decompile measurably
(~4.0s, within run-to-run noise) -- after the O(N^2) fix these spots are
small relative to the actual rule/heritage/type work. Kept as correct,
more-faithful, strictly-fewer-op code; the next real win needs a fresh
profile of the post-fix hot path.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_018TNi2EzjQfRizjyNpo36y2
@mahaloz
mahaloz merged commit 8741bd0 into main Jun 22, 2026
mahaloz added a commit that referenced this pull request Jun 26, 2026
Union both opt-in settables atop main: dedupitetail (4109, #104) +
unrolledguard (no ElementId, #105). Resolved by UNION (no registration
dropped):
- stages.toml: 65 settables, 98 surfaces; header counts updated
- kuna_stages/tests.rs: settable_count_is_65, surface_count_is_98, 64
  trailing commas in the static catalog
- catalog_bytecompat.rs: 65 "option" rows
- xml.rs corpus count: 155 (83 datatests + 72 stage testcases)
- kuna-catalog.xml provenance: #6 source_decompiler angr=24, #7
  structure-recovery=13 (+dedupitetail), #8 opt-in-tool=12 (+unrolledguard),
  #5/#9 use_when/change_kind max bumped 65->66 (65 settables + returnpair dup)
- baseline-stages.json + assertions.md regenerated (235/235)

Gates: catalog --check OK; make test PARITY OK 675/675; make test-stages
PARITY OK 235/235; make rust-test green.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01PBrckq3YYAzBLq5k4KpWac
@mahaloz
mahaloz deleted the perf/actionpool-cursor branch July 29, 2026 08:01
mahaloz added a commit that referenced this pull request Aug 19, 2026
…delta-review findings

[AUTOMATED] The branch was RED on its own gate: `ghidra_sim_sort_grep_breadth`
(the #[ignore]d breadth test `make test-ghidra` and the CI gates job run with
`--include-ignored`) failed on tests/bug-repro/sort::sub_6370 with "NO <vardecl
symref> resolves against <localdb>".

ROOT CAUSE (a port gap, not a heuristic).  sub_6370 declares `char v1 [16]` and
`char v2 [24]`, two stack aggregates used ONLY as `memcmp(v1,v2,0x10)` — i.e.
reached exclusively through a `&sym` reference.  The whole HighVariable of such
a variable is the CONSTANT PTRSUB offset operand (one instance, const space,
is_constant=true, is_addr_tied=false), so `kuna_link_high_symbols` skips it at
the constant guard and `kuna_high_symbol_wire_id`'s re-derivation loop — which
only scans addr-tied instances — cannot see it either.  Both declarations fell
back to the varnode create index; 2 of 2, hence "wholesale".  The Symbols were
in <localdb> the whole time (v1/v2, cat -1, real ids).

`Funcdata::link_symbol_reference` copies the referenced Symbol's name, offset
and type onto that high but DROPPED its identity, where upstream
`Varnode::setSymbolReference` (varnode.cc:465) →
`HighVariable::setSymbolReference(entry->getSymbol(), off)` (variable.cc:283)
carries the Symbol itself.  The identity is now recorded
(`HighVariable::kuna_ref_symbol`, local scope only) and read by the
declaration's symref.  Deliberately a SEPARATE field from `kuna_link_symbol`:
that one feeds <high symref>, and such a high encodes class="constant", where
Java's HighConstant.decode does nothing with a mapped local symref — so nothing
is gained there, and keeping it out preserves the one-owner invariant
`ghidra_sim_faillog_high_symrefs_are_not_shared_with_params` asserts.

This also closes the pinned residual: PIN_FAILLOG_VARDECL_UNRESOLVED moves
[0,1,0] -> [0,0,0] (sub_3320's survivor was the same class).  Every declaration
in the corpus now resolves; the pin doc states ZERO is the contract.

TEST HYGIENE (a harness bug, fixed here).  The previous round's recorded
verification ran `cargo test -p kuna-ghidra --release` WITHOUT
`--include-ignored` — its log reads "ghidra_sim_sort_grep_breadth ... ignored"
— so the breadth test was never executed locally and nothing said so.
`make test-ghidra` now tees its output and fails on TWO canaries: the CI skip
canary (specs missing/unusable => every sim test skips and passes vacuously;
worktrees hit this because KUNA_SPECS/SLEIGHHOME do not reach the cargo
suites), and a breadth canary demanding the literal
"test ghidra_sim_sort_grep_breadth ... ok" line.  The breadth test itself now
asserts 0 unresolved PER TARGET (the generic "resolved > 0" gate only catches
wholesale breakage; a 20/20 -> 1/20 regression passed silently).

DELTA-REVIEW FINDINGS (batched):

 #2 HIGH `add_param_symbol` promoted ANY storage-OVERLAPPING symbol into
    parameter slot i.  Upstream `ProtoStoreSymbol::setInput` (fspec.cc:3150)
    does the opposite — it looks up BY SLOT and removes+recreates on an
    addr/size mismatch; it never promotes an unrelated local.  And this runs in
    ActionRestructureVarnode (standalone included) where
    `clear_unlocked_category_negative` only clears cat<0, so a wrong promotion
    is permanent.  Now categorizes only on an EXACT (addr,size) match; comment
    rewritten to the real mechanism and both failure modes (checkFullCommit's
    storage compare; getDatabaseParameter keying the DB slot off
    getCategoryIndex).
 #3 MED  WireSymbol::encode bypassed the 0-size-type filter added for scope
    symbols (MappedEntry.decode throws and Java discards the whole result).
    `kuna_link_high_symbols` now routes a 0-sized dtype to the HASHED shape
    (DynamicEntry.decode has no size check) and `WireSymbol::is_encodable` is
    the backstop in both the encode and the id set.
 #4 MED  <vardecl symref> was not filtered through the encodable predicate.
    Every branch of `kuna_high_symbol_wire_id` now passes
    `ScopeLocal::symbol_is_encodable` (new O(1) single-symbol form — the set
    build would run per declaration on every decompile).
 #5 MED  `kuna_apply_dynamic_recommendations` runs at the TOP of the naming
    pass, where the ported isNameUndefined guard is vacuous, and it CREATES a
    Symbol where upstream RENAMES one.  kuna fuses linkSymbols with the vN
    assignment into one walk, so there is no "after linking, before defaults"
    point to move it to; the equivalent guard is applied against the SCOPE
    instead — a hash landing on storage the walk will bind to a
    function_parameter, or to any Symbol with a defined name, is skipped.
    Also: find_varnode's `vnlist2[pos]` is a checked `.get()` (the hash is
    host-supplied), and the hardcoded budget of 8 carries the "deliberately
    not `dynamichashmax`" note.
 #6 MED  the WIRE arm of encode_high skipped the encodable_symbols guard;
    `encodable` is empty for a has_no_code() function, so class="local" +
    symref against a <localdb> never written is the HighLocal.decode
    hard-throw.  Wire arm now takes the same gate (falls to class="other").
 #7 LOW  Funcdata::clear() left kuna_wire_symbols / kuna_wire_symbol_for_high
    behind — HighVariableId-keyed maps outliving the arena that issued the ids.
 #8 LOW  declaration tokens carried `varref`; upstream emitVarDecl pushes an
    explicitly NULL Varnode, and the omission is load-bearing
    (ClangVariableToken.getHighVariable returns inst.getHigh() from inside its
    `inst != null` block and never reaches the parent-decl fallback).  Dropped;
    the create index remains the symref fallback.
 #9 LOW  slot skew: `to_pieces` compacts out params with no dtype while
    param_storage carried absolute rp.index.  Both now use the compacted basis.
 #10 LOW live rig: `len(before) >= 2` hard-failed on a one-local function (now
    >= 1, with a NOTE at 1), and the param rename target + its recorded old
    name now both come from the post-commit result.

Doc correction (reviewer-verified): checkFullCommit inspects the parameter
count, each categoryIndex and each storage — never the model name.  The C6
prose in docs/spec/00-overview.md claimed otherwise; corrected to "the storage
echo is the load-bearing half".  Spec prose also gains the &symbol identity
record, the vardecl encodable filter, and the dynRecommend placement
divergence; ghidra-integration.md's deferred list is re-cut.

Gates: make test 675/675 PARITY OK; make test-stages 484/484 PARITY OK;
make rust-test green; make check-spec OK; make test-ghidra green WITH the
breadth test proven to have run (11 sim tests, 6/6 breadth targets at
vardecl_unresolved=0).  C text byte-identical — c_lines 283/39/92 and every
other faillog pin unchanged.  No baseline re-pins, no options, no DIV rows.

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 19, 2026
…pe, switch recovery, real signatures in the GUI) (#319)

* feat(ghidra): Phase 4 — full decompileAt response encode (rename/retype, switch recovery, real signatures)

[AUTOMATED] The decompileAt response now carries the complete first-<function>
document in the upstream child order (funcdata.cc:734): <addr> + <localdb> +
<ast> + <highlist> + <jumptablelist> + <prototype>, plus <parammeasures> under
the paramid action — everything the native Ghidra GUI features consume.

Encoders (kuna-decomp, all upstream-faithful ports over PackedEncode):
- Datatype::encodeRef/encode/encodeBasic/encodeTypedef (type.cc:462-560) +
  TypeField/TypeBitField::encode; get_unsized_id/has_same_variable_base
  completed through the existing hash_size; decode_integer_format added.
  Differential-tested against the shipped decode side (encode_ref output
  re-interns to the identical Rc through decode_type).
- FuncProto::encode (fspec.cc:4625) + EffectRecord::encode + the model-diff
  effect/likelytrash lists; params travel as <localdb> cat-0 symbols (the
  upstream symbol-backed-store wire shape).
- ScopeLocal::encode (varmap.cc:462) -> Database::encode_scope +
  Symbol::encode{_header,_body} + SymbolEntry::encode (database.cc:187-2660):
  nonzero ids always, >=1 entry per mapsym, positional <parent>+<rangelist>,
  cat-0 params with slot index + exact storage.
- Funcdata::encode_high (funcdata.cc:658) + HighVariable class rules
  (variable.cc:839) + the encode-time symbol-link pass kuna_link_high_symbols
  (the ActionNameVars::linkSymbols stand-in for kuna's string-named highs;
  runs only from Funcdata::encode, standalone path untouched).
- Funcdata::encode_jump_table over the already-ported JumpTable::encode,
  emitted independently of savetree; session jumpload toggle reaches
  FlowInfo::record_jumploads per decompile.
- ParamIDAnalysis unstubbed (the justproto arm reads the real recovered
  FuncProto); <rank> always emitted; the paramid action answers a
  parammeasures-ONLY doc (ghidra_process.cc:318).

Symbol-id echo discipline (r5 §5): invented symbols carry internal
SYMBOL_ID_BASE-range ids; globals echo the REAL host DB id
(GlobalEntry/GlobalContainer::symbol_id from the getMappedSymbols record) and
symref is OMITTED when unknown — never fabricated.

Rename/retype persistence loop: the function <localdb> answer's non-param
locals decode (RemoteLocalVar) and seed the fresh Funcdata — typelocked
locals as mapped/usepoint symbol seeds, plain renames (typelock=false, the
GUI-rename shape) as ScopeLocal::nameRecommend records (the C++ mechanism:
such symbols never survive clearUnlockedCategory(-1)), applied by the
ActionNameVars port (recommended_name_for, varmap.cc:1050 arms).

Markup type-token fidelity: EmitMarkup::tag_type splits rendered declarators
into word <type> tokens + <syntax> separators, so Java's getC()
(IllegalCharCppTransformer) no longer mangles "unsigned long *" into
unsigned_long__; markup-emitter-only, standalone bytes identical.

Harness: parse_decompile_doc decode-validates the full response the way Java
would; assert_phase4_traps asserts every r5 §3 hard-throw per function; new
switch-analyzer-shape, paramid-shape, and rename-persistence echo-back tests.
Pins: mangled [57,10,24]->[0,0,0]; diff bands [0.10..0.34]->[0.02..0.15]
(measured 0.050/0.079/0.099); c_lines unchanged.

Live-verified on stock Ghidra 12.1.2 (fmt::main, the committed
integrations/ghidra/live-smoke/phase4_features.py rig): real signature,
rename/retype round-trips that persist re-decompiles and hit the RIGHT DB
variable, DecompilerSwitchAnalysisCmd rebuilding all 10 case references from
kuna's jumptablelist, HighParamID decoding.

Gates: make test 675/675 PARITY OK, make test-stages PARITY OK, make
rust-test green, make check-spec OK, make test-ghidra green. No baseline
re-pins, no new options, no ghidra-mode default changes.

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

* docs(ghidra): Phase-4 spec prose + integration-doc state

[AUTOMATED] Spec-live prose for the Phase-4 encoders in their owning
chapters: 00-overview (the full-response encode, the encode-time symbol-link
pass, symbol-id echo discipline, the paramid doc shape, the rename/retype
persistence loop), 04 (FuncProto::encode), 05 (the Datatype::encodeRef wire
marshal-out), 06 (ScopeLocal::encode + the NameRecommend port).
docs/ghidra-integration.md: the Phase-4 checklist (shipped vs deliberately
deferred) and the §9 seam-table rows (Funcdata::encode, TypeFactory
marshal-out, ParamIDAnalysis, DB-symbol-id echo).

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

* fix(ghidra): Phase-4 review round — declaration symrefs, dynamic-storage renames, conflict-safe symbol ids

[AUTOMATED] Six confirmed findings from the adversarial review of PR #319.

C1/C5 (id-contract hole): the markup's `<vardecl symref>` still emitted the
Phase-2 varnode-create-index placeholder, which can never resolve now that
every real id is SYMBOL_ID_BASE-range — Java logged "Invalid symbol reference"
per declaration per decompile and rename/retype was DEAD on declaration-line
tokens.  The symbol-link pass now runs BEFORE the markup is printed and the
declaration carries the real LocalSymbolMap id plus the representative's
varref; the create-index survives only as the fallback for a high the analysis
left symbol-less.  Making the reorder safe required the link pass to stop
mutating the analysis scope: it now emits WIRE-ONLY symbols
(`database::WireSymbol`) that are encoded into `<localdb>` and referenced by
`<high symref>`/`<vardecl symref>` but never enter the scope, so the pass
cannot perturb the printed C at any point in the sequence.  (The first
attempt DID move it — ghidra-sim's `c_lines` pin caught +1 line on faillog
sub_2620 — which is why the design changed.)

C2 (HIGH, renames reverted in front of the user): host locals whose only
SymbolEntry is a `<hash>` DynamicEntry were dropped on decode.  That is the
storage class Java writes for every `requiresDynamicStorage` variable
(unique-space representatives, `splitOutMergeGroup` products), so renaming
such a variable silently reverted on the next decompile.  Hash entries are now
kept (`RemoteEntry::hash`, `RemoteLocalVar::hash`) and applied through the
full upstream mechanism: `ScopeLocal::dynRecommend` +
`recoverNameRecommendationsForSymbols`'s hash loop
(`Funcdata::kuna_apply_dynamic_recommendations` over `DynamicHash::findVarnode`,
run at the top of the naming pass), with typelocked ones seeded as dynamic
Symbols.  Hashes use the upstream budget of 8 because Java hardcodes the same
(`DynamicHash.java:440`) and a disagreeing hash cannot round-trip.

C3: name recommendations matched only the high's NAME REPRESENTATIVE's def
address; upstream's `findVarnodeWritten` matches ANY varnode of (size,addr)
written at the usepoint, so a rename recorded at a non-representative instance
reverted.  Now matched across every instance, plus upstream's
`!sym->isNameUndefined()` guard (never paint over a resolved symbol) and a
cat-0 guard (a parameter's name comes from the prototype).

C4 (wrong-target rename): the encode-time link pass bound any unattached named
high to the smallest containing SymbolEntry with none of the naming pass's
conflict logic — so a high the naming pass deliberately routed to `vN` because
binding it was a storage CONFLICT inherited the PARAMETER's symbol id, and
renaming that variable in the GUI renamed the parameter.  The naming pass now
RECORDS its bind decisions (`HighVariable::kuna_link_symbol`) and the encode
materializes symbols only for highs left unbound — a covered-but-unbound high
gets a data-flow-HASHED wire symbol (upstream `buildDynamicSymbol`), never the
conflicting entry's id.

C6: the decoded cat-0 parameter storage and the `<prototype model=…>` were
parsed and discarded, so kuna echoed model-rederived storage and Java's
`checkFullCommit` force-committed a kuna-rederived signature over the user's on
any parameter rename.  Both now ride through
(`RemoteParam::storage`, `RemoteFunctionFacts::{model,param_storage}` →
`apply_locked_prototype_with_model` + `apply_mapped_params`), and
`add_param_symbol` categorizes an existing overlapping entry as the parameter
slot instead of skipping it.

LOWs: `encode_scope`'s defensive symbol skips now also withhold the id from
`<high symref>` (`Database::encodable_symbol_ids` — an orphan reference is the
Java hard-throw the skip exists to avoid); the harness asserts the r5 §3
0-sized-data-type trap; the live rig's two vacuous PASS criteria are real
(collateral detection commits the decoded locals first, and the param rename
asserts decoded-vs-DB storage/ordinal equality BEFORE renaming, so a forced
full commit can no longer masquerade as an in-place edit).

Tests: a unit test drives the dynamic-recommendation mechanism end to end
(hash a varnode, seed the recommendation, apply, assert the name and Symbol
land on that variable); a sim test asserts no `<high>` borrows a cat-0
parameter's symref; the harness pins unresolvable `<vardecl symref>`s
(0/1/0 — the systemic case is fixed, one group-member residue documented).
All other pins unchanged, C text byte-identical (c_lines 283/39/92).

Live-verified on stock Ghidra 12.1.2 (fmt::main): 13/13 checks PASS, including
the strengthened ones — 21 committed DB variables for collateral detection and
decoded param storage/ordinals equal to the database.

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

* docs(ghidra): Phase-4 review-round prose — wire symbols, the four persistence channels, dynRecommend

[AUTOMATED] 00-overview: the naming pass's recorded bind decision vs the
encode-time WIRE-ONLY symbols (and why the encode never re-derives a container
binding — a conflict-separated high must not inherit the parameter's id), the
four rename/retype persistence channels (mapped/dynamic × typelocked/rename-only),
and the host model + exact parameter storage echo.  06: the dynamic
(hash-keyed) recommendation list beside the address-keyed one.
ghidra-integration.md: the review-round checklist entry and the two remaining
deferred items (including the pinned single unresolved <vardecl symref>).

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

* fix(ghidra): Phase-4 round 2 — the &symbol declaration symref, and 9 delta-review findings

[AUTOMATED] The branch was RED on its own gate: `ghidra_sim_sort_grep_breadth`
(the #[ignore]d breadth test `make test-ghidra` and the CI gates job run with
`--include-ignored`) failed on tests/bug-repro/sort::sub_6370 with "NO <vardecl
symref> resolves against <localdb>".

ROOT CAUSE (a port gap, not a heuristic).  sub_6370 declares `char v1 [16]` and
`char v2 [24]`, two stack aggregates used ONLY as `memcmp(v1,v2,0x10)` — i.e.
reached exclusively through a `&sym` reference.  The whole HighVariable of such
a variable is the CONSTANT PTRSUB offset operand (one instance, const space,
is_constant=true, is_addr_tied=false), so `kuna_link_high_symbols` skips it at
the constant guard and `kuna_high_symbol_wire_id`'s re-derivation loop — which
only scans addr-tied instances — cannot see it either.  Both declarations fell
back to the varnode create index; 2 of 2, hence "wholesale".  The Symbols were
in <localdb> the whole time (v1/v2, cat -1, real ids).

`Funcdata::link_symbol_reference` copies the referenced Symbol's name, offset
and type onto that high but DROPPED its identity, where upstream
`Varnode::setSymbolReference` (varnode.cc:465) →
`HighVariable::setSymbolReference(entry->getSymbol(), off)` (variable.cc:283)
carries the Symbol itself.  The identity is now recorded
(`HighVariable::kuna_ref_symbol`, local scope only) and read by the
declaration's symref.  Deliberately a SEPARATE field from `kuna_link_symbol`:
that one feeds <high symref>, and such a high encodes class="constant", where
Java's HighConstant.decode does nothing with a mapped local symref — so nothing
is gained there, and keeping it out preserves the one-owner invariant
`ghidra_sim_faillog_high_symrefs_are_not_shared_with_params` asserts.

This also closes the pinned residual: PIN_FAILLOG_VARDECL_UNRESOLVED moves
[0,1,0] -> [0,0,0] (sub_3320's survivor was the same class).  Every declaration
in the corpus now resolves; the pin doc states ZERO is the contract.

TEST HYGIENE (a harness bug, fixed here).  The previous round's recorded
verification ran `cargo test -p kuna-ghidra --release` WITHOUT
`--include-ignored` — its log reads "ghidra_sim_sort_grep_breadth ... ignored"
— so the breadth test was never executed locally and nothing said so.
`make test-ghidra` now tees its output and fails on TWO canaries: the CI skip
canary (specs missing/unusable => every sim test skips and passes vacuously;
worktrees hit this because KUNA_SPECS/SLEIGHHOME do not reach the cargo
suites), and a breadth canary demanding the literal
"test ghidra_sim_sort_grep_breadth ... ok" line.  The breadth test itself now
asserts 0 unresolved PER TARGET (the generic "resolved > 0" gate only catches
wholesale breakage; a 20/20 -> 1/20 regression passed silently).

DELTA-REVIEW FINDINGS (batched):

 #2 HIGH `add_param_symbol` promoted ANY storage-OVERLAPPING symbol into
    parameter slot i.  Upstream `ProtoStoreSymbol::setInput` (fspec.cc:3150)
    does the opposite — it looks up BY SLOT and removes+recreates on an
    addr/size mismatch; it never promotes an unrelated local.  And this runs in
    ActionRestructureVarnode (standalone included) where
    `clear_unlocked_category_negative` only clears cat<0, so a wrong promotion
    is permanent.  Now categorizes only on an EXACT (addr,size) match; comment
    rewritten to the real mechanism and both failure modes (checkFullCommit's
    storage compare; getDatabaseParameter keying the DB slot off
    getCategoryIndex).
 #3 MED  WireSymbol::encode bypassed the 0-size-type filter added for scope
    symbols (MappedEntry.decode throws and Java discards the whole result).
    `kuna_link_high_symbols` now routes a 0-sized dtype to the HASHED shape
    (DynamicEntry.decode has no size check) and `WireSymbol::is_encodable` is
    the backstop in both the encode and the id set.
 #4 MED  <vardecl symref> was not filtered through the encodable predicate.
    Every branch of `kuna_high_symbol_wire_id` now passes
    `ScopeLocal::symbol_is_encodable` (new O(1) single-symbol form — the set
    build would run per declaration on every decompile).
 #5 MED  `kuna_apply_dynamic_recommendations` runs at the TOP of the naming
    pass, where the ported isNameUndefined guard is vacuous, and it CREATES a
    Symbol where upstream RENAMES one.  kuna fuses linkSymbols with the vN
    assignment into one walk, so there is no "after linking, before defaults"
    point to move it to; the equivalent guard is applied against the SCOPE
    instead — a hash landing on storage the walk will bind to a
    function_parameter, or to any Symbol with a defined name, is skipped.
    Also: find_varnode's `vnlist2[pos]` is a checked `.get()` (the hash is
    host-supplied), and the hardcoded budget of 8 carries the "deliberately
    not `dynamichashmax`" note.
 #6 MED  the WIRE arm of encode_high skipped the encodable_symbols guard;
    `encodable` is empty for a has_no_code() function, so class="local" +
    symref against a <localdb> never written is the HighLocal.decode
    hard-throw.  Wire arm now takes the same gate (falls to class="other").
 #7 LOW  Funcdata::clear() left kuna_wire_symbols / kuna_wire_symbol_for_high
    behind — HighVariableId-keyed maps outliving the arena that issued the ids.
 #8 LOW  declaration tokens carried `varref`; upstream emitVarDecl pushes an
    explicitly NULL Varnode, and the omission is load-bearing
    (ClangVariableToken.getHighVariable returns inst.getHigh() from inside its
    `inst != null` block and never reaches the parent-decl fallback).  Dropped;
    the create index remains the symref fallback.
 #9 LOW  slot skew: `to_pieces` compacts out params with no dtype while
    param_storage carried absolute rp.index.  Both now use the compacted basis.
 #10 LOW live rig: `len(before) >= 2` hard-failed on a one-local function (now
    >= 1, with a NOTE at 1), and the param rename target + its recorded old
    name now both come from the post-commit result.

Doc correction (reviewer-verified): checkFullCommit inspects the parameter
count, each categoryIndex and each storage — never the model name.  The C6
prose in docs/spec/00-overview.md claimed otherwise; corrected to "the storage
echo is the load-bearing half".  Spec prose also gains the &symbol identity
record, the vardecl encodable filter, and the dynRecommend placement
divergence; ghidra-integration.md's deferred list is re-cut.

Gates: make test 675/675 PARITY OK; make test-stages 484/484 PARITY OK;
make rust-test green; make check-spec OK; make test-ghidra green WITH the
breadth test proven to have run (11 sim tests, 6/6 breadth targets at
vardecl_unresolved=0).  C text byte-identical — c_lines 283/39/92 and every
other faillog pin unchanged.  No baseline re-pins, no options, no DIV rows.

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

---------

Co-authored-by: Claude Fable 5 <[email protected]>
mahaloz added a commit that referenced this pull request Sep 16, 2026
…otype costs

The adversarial review found a hunk class the sweep missed: a `main` whose
body reads an argument register PAST the third recovers it as a parameter,
and the locked three-parameter park takes that slot away -- the value is
dropped at its call site, or, when the body stores it, declared as a local
nothing assigns.

Measured over the whole decbench stripped population (775 images, 645 with a
main this pass names): 28 recover more than three parameters, 13 of those
gain a never-assigned register local. None of the extra slots is real --
openssh sftp -O2 @0x5250 and shadow login -O2 @0x3d20, the two loudest cases,
both declare `int main(int argc, char **argv)` in their unstripped twin's
DWARF -- and on coreutils true/false the same flip replaces
`return v2._0_16_ << 0x40` with `return 0`.

- new in-repo fixture elfmainextra_x86_64 (+ its .s source) whose main
  forwards r8 into a call argument and stores r9 to a global, so both losses
  show at once; pinned by tests/stages/kuna-elfmain.xml #5-#8 and
  tests/cli/elf-main-extra-register-args.json
- tests/cli/define-function-name-outranks-analysis.json covers the
  --define-function name-precedence change this PR makes
- the class is written up in docs/spec/01-program-prep.md, the option's
  phases.toml row (so docs/options.md and the catalog fixture move with it),
  the module header and docs/features/elfmain/{record.json,sweep-params/}
- three comments still describing a two-argument prototype corrected

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01MAeimyWm5oSewpeCgAwY29
mahaloz added a commit that referenced this pull request Sep 18, 2026
mahaloz added a commit that referenced this pull request Sep 18, 2026
mahaloz added a commit that referenced this pull request Sep 18, 2026
A call argument narrower than int that the caller zero-extends kept no
truncation in the printed C, so C's integer promotion handed the callee a
different value than the binary passes (f: sink(a0 * 3) for a movzx'd
16-bit product). When subvariable flow trims a call argument and every
dropped bit is known zero, the trim is recorded on the call, and emission
casts that argument to the unsigned type of its width unless promotion
already zero-extends it or the value provably fits. clang-forwarded narrow
parameters (no zero-extension evidence) stay uncast. C output only; no
option, since it restores a conversion the binary performed.

Tests: tests/stages/kuna-truncarg.xml (12 assertions; #1-#4 and #8 fail on
main, #11/#12 are clang forwarding guards). Round trip over 719 values:
main 309 wrong, this change 0 new wrong under gcc and clang.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01YFCA715QE6ZBSnTn7bwabG
mahaloz added a commit that referenced this pull request Sep 18, 2026
mahaloz added a commit that referenced this pull request Sep 18, 2026
By default a stripped function that reads one object at fixed offsets now
gets a `struct_N *` parameter and its reads print as fields;
`--option structsynth off` gives the old output back.

A synthesized field takes a sign only when every read of it agrees, so a
zero-extended narrow read stays unsigned, and a field read at one width both
as a float and as an integer is raw bytes. A sharded run (`--jobs N` on
decompile-all, decompile-graph or decompile-project) runs its workers with
structsynth off and says so on stderr, because each worker numbered its own
struct_N. The ELFMAIN elfmain-off pass pins the upstream form with structsynth
off, and PEBNAMES-X86 #6/#8 expect the FS base as fields.

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

Union #26 (union_datatype.xml) pins upstream's `res = (int4)ptr->b->bCharField;`
and opts out with `option castimplied off`. Ten stage assertions of other
options pinned a widening this option leaves out and now match the new form:
undefname #4, charbyte #1 #2 #4 #7 #8, PEBNAMES #18, ptrfromuse #10,
TIEDPHITRIM #1 #2. docs/baseline.json and docs/baseline-stages.json unchanged.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_011Q4qgBGM28rgY6CEh5pird
mahaloz added a commit that referenced this pull request Sep 23, 2026
…ending)

Union #26 (union_datatype.xml) pins upstream's `res = (int4)ptr->b->bCharField;`
and opts out with `option castimplied off`. Ten stage assertions of other
options pinned a widening this option leaves out and now match the new form:
undefname #4, charbyte #1 #2 #4 #7 #8, PEBNAMES #18, ptrfromuse #10,
TIEDPHITRIM #1 #2. docs/baseline.json and docs/baseline-stages.json unchanged.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_011Q4qgBGM28rgY6CEh5pird
mahaloz added a commit that referenced this pull request Sep 24, 2026
…WARF corpus script

Re-records docs/baseline-stages.json for the two new assertions
(castsign #7, #8); nothing else moved (1349/1349).

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_011Q4qgBGM28rgY6CEh5pird
mahaloz added a commit that referenced this pull request Oct 2, 2026
…s its zero-extension (#794)

## The problem

On a 32-bit target, a function that returns a 64-bit integer with its high word set to zero is printed as returning only its low word, typed as a signed `int`. A caller that widens the result then sign-extends it.

```sh
printf 'typedef unsigned long long u64;\nu64 ins16(unsigned a, unsigned short b) { return ((a + 1) << 16) | b; }\n' > ins16.c
clang --target=arm-linux-gnueabi -O2 -c ins16.c -o ins16.o   # orr r0,r1,r0,lsl #16; mov r1,#0; add r0,r0,#65536
kuna decompile-all ins16.o
```
```c
int ins16(int a0,unsigned int a1)
{
  return (a1 | a0 << 0x10) + 0x10000;
}
```

`ins16(0x7fff, 0)` is `0x80000000`, but through the printed prototype `(unsigned long long)ins16(0x7fff, 0)` is `0xffffffff80000000`. MIPS and PowerPC little-endian, RISC-V 32 and i386 (`xor %edx,%edx; ret`) print the same `int`, and `u64 f(int a, int b) { return (unsigned)(a + b); }` prints `int f(...) { return a1 + a0; }`.

## The fix

- Sub-variable flow no longer trims a RETURN that reads a 64-bit integer held in two output registers: a value of at most eight bytes, wider than any single integer output register of the prototype model, with its high word where the register file's byte order puts it. That covers the joins `r1:r0`, `$3:$2` and `EDX:EAX`, and SPARC's `o0_1`, a register that names both halves. With the high register zero the RETURN reads `ZEXT(lo)`, and `RuleSubvarZext` used to cut it back to the low register.
- The function now prints `unsigned long long ins16(int a0,unsigned int a1)`. A word whose C type is signed gets the cast that makes C zero-extend it: `return (unsigned int)(a1 + a0);`.
- 16-byte pairs (x86-64 `RDX:RAX`) keep the trim, because a zeroed `RDX` there is almost always `-fzero-call-used-regs` after an `int` function. Where a 32-bit function's bytes are exactly those of a zero-extended return, it now reads `unsigned long long` though the source returns a word: an i386 `int` function scrubbed that way, gcc -O0's `int f(u64 a) { return a >> 32; }`, or ChibiOS's `chEvtGetAndClearEvents`, which zeroes `r1` for `msr basepri` before returning. The value is unchanged, and `--option returnpair single` gives the word back.

What this does not fix:

- Big-endian pairs (ARM, MIPS, PowerPC, SPARC) are joined with their halves swapped on main, which #763 fixes. With this PR alone their output does not change. On a merge with #763, `ins16` round-trips on all four.
- A caller that returns the callee's low word with only the high word changed, `return zsum(a, b) | 0xff00000000ULL;`, now prints `void` in `decompile-all`, as single-function `kuna decompile` already does on main and as main does for any 64-bit callee (#808). Main's `decompile-all` printed a return, but one that sign-extends the low word.
- `u64 zx(unsigned a) { return a; }` on ARM (`mov r1,#0; bx lr`) and `long long sx(int a) { return a + 3; }` print `void` before and after (#807).

## Tests

- `tests/stages/kuna-zextpair.xml` (ARM): 5 of 6 assertions fail on main. The control passes on both.
- `kuna-cli/tests/zext_pair_returns.rs` builds ARM, MIPS and PowerPC little-endian and i386 objects. It compiles the printed C, callers included, with gcc and clang at -O0/-O2 and compares it with the source over 289 input pairs (544 wrong values on main for ARM). It also checks under `-m32` that every return is eight bytes on ARM, i386 and SPARC.
- In `passthrough_own_return.rs`, the forwarder `bl provider; mov r1,#0` now returns `unsigned long long`.
- `decompile-all` changes no function over Lua 5.3 built for nine 32-bit targets (5,015 functions, including SPARC, ARM hard-float, MIPS and PowerPC big-endian). Over 15 decbench ARM firmware and i386 PE binaries (14,181 functions) it changes 7: one 64-bit return now right (betaflight, `lsrs r0,r0,#8; movs r1,#0`), the ChibiOS function above and four of its callers (variable numbering only), and one stretch of data decoded as code. Datatests are unchanged at 675/675. CPU time (min of 21 to 31 interleaved runs, five witnesses) moves between −4.9% and +1.4%.

Fixes #769

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_01Ps66ZCFPLywq9AKHBuDXNU
mahaloz added a commit that referenced this pull request Oct 7, 2026
…as main

A slot a layout pass finds kept by the written-slot guard alone stays
guard-only for the rest of the analysis. Later passes may no longer see the
guard's INDIRECTs live while the COPY and MULTIEQUAL they left keep the slot
a local of its own, so the final check missed it: an AArch64 clang -O2 walk
over the .a fields of `struct { long a; char pad[6]; short z; } s[8]` left
`unsigned long v3[5]` below the guarded s[2].z, and the walk wrote past it.
New AArch64 stage assert #8 (gap2).

pointer_pieces bounds an index by an unsigned remainder only under
stackstoreguard; with the option off it uses the known-bits mask, as main,
so arrayextent sizes arrays as on main.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_019c7W9nMmArWipVaBuMCy39
mahaloz added a commit that referenced this pull request Oct 12, 2026
…ment (#1044)

`--max-fn-seconds` cannot stop a function that hands the addresses of many stack locals to many calls: it runs far past the budget and its memory keeps growing until it finishes or the system kills it. This 45 KB function asks for 1 second and gets 13:

```c
// big.c -- clang -O0 -fno-pic -no-pie -nostdlib -Wl,-e,big -o big big.c
struct S { int a; long b; char c[24]; };
__attribute__((noinline)) int cb(void *p) { return *(int *)p; }
__attribute__((noinline)) int reg(const char *n, void *p, int i, int (*f)(void *)) { return f(p) + i + *n; }
#define L(i) { struct S s; s.a = (i); s.b = r; r += reg("n", &s, (i), cb); }
#define L10(i) L(i##0) L(i##1) L(i##2) L(i##3) L(i##4) L(i##5) L(i##6) L(i##7) L(i##8) L(i##9)
#define L100(i) L10(i##0) L10(i##1) L10(i##2) L10(i##3) L10(i##4) L10(i##5) L10(i##6) L10(i##7) L10(i##8) L10(i##9)
int big(void) { int r = 0; L100(1) L100(2) L100(3) L100(4) L100(5) L100(6) L100(7) return r; }
```

```
$ /usr/bin/time -f '%e s, %M KB max RSS' kuna decompile-all big --functions big --json --max-fn-seconds 1
  "error": "per-function decompile budget exceeded (1 s)"
13.13 s, 2672244 KB max RSS
```

The same shape at 290 KB (5,000 locals) ignores a 10 s budget and reaches 8 GB in 36 s, which matches the growth in #1034.

- Heritage guards every stack range at every call, as upstream does, so this function gets one INDIRECT per (local, call) pair, about a million here. That placement loop had no deadline probe; it now checks the deadline before each range.
- A pass whose deadline passed during placement returns before renaming, and a pass panic after the deadline reports the budget error, not the panic text.
- A function that finishes inside its budget is unchanged: the probes only act once the deadline has passed.

After: 1.37 s, 389 MB for the example; 10.8 s and 775 MB for the 290 KB function with a 10 s budget.

Tests: `watchdog_stops_heritage_guard_placement` runs the example (checked in as `tests/hang-repro/escaped_locals`) with a 1 s budget and fails without the fix (15 s against a 10 s bound). Speed (decompile-all of gzip, kmod, grep and ls, 11 interleaved runs): +1.7% on the min-sum with flat medians. That is within noise: the new probe runs 26,518 times over all of `ls`, which is well under a millisecond.

Part of #1034

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_015sdZpNU5odw5dVyaxeSvvz
mahaloz added a commit that referenced this pull request Oct 13, 2026
…'s own instructions

A call reads its callee's pair the way the callee's own RETURN joins it, and
the two are decided in different decompiles, in any order and any run. The
proof is now a walk of the function's raw p-code, taken by the driver for the
function and every direct callee before any pipeline runs and cached per
image, and both seams read that one verdict, so --functions, --jobs, a single
kuna decompile and self- or mutual recursion all agree. A sign extension, a
zero extension, or a product whose low half an instruction of its own made,
at every RETURN; a register piece is made by whatever wrote the whole, and a
call clobbers what the model does not preserve. kuna-cli test and fixtures
pin a caller decompiled before its callee in four run modes; the trade-off
test also checks the default; sparc-callreturn #8 pins int8.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015sdZpNU5odw5dVyaxeSvvz
mahaloz added a commit that referenced this pull request Oct 14, 2026
…'s own instructions

A call reads its callee's pair the way the callee's own RETURN joins it, and
the two are decided in different decompiles, in any order and any run. The
proof is now a walk of the function's raw p-code, taken by the driver for the
function and every direct callee before any pipeline runs and cached per
image, and both seams read that one verdict, so --functions, --jobs, a single
kuna decompile and self- or mutual recursion all agree. A sign extension, a
zero extension, or a product whose low half an instruction of its own made,
at every RETURN; a register piece is made by whatever wrote the whole, and a
call clobbers what the model does not preserve. kuna-cli test and fixtures
pin a caller decompiled before its callee in four run modes; the trade-off
test also checks the default; sparc-callreturn #8 pins int8.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015sdZpNU5odw5dVyaxeSvvz
mahaloz added a commit that referenced this pull request Oct 14, 2026
…'s own instructions

A call reads its callee's pair the way the callee's own RETURN joins it, and
the two are decided in different decompiles, in any order and any run. The
proof is now a walk of the function's raw p-code, taken by the driver for the
function and every direct callee before any pipeline runs and cached per
image, and both seams read that one verdict, so --functions, --jobs, a single
kuna decompile and self- or mutual recursion all agree. A sign extension, a
zero extension, or a product whose low half an instruction of its own made,
at every RETURN; a register piece is made by whatever wrote the whole, and a
call clobbers what the model does not preserve. kuna-cli test and fixtures
pin a caller decompiled before its callee in four run modes; the trade-off
test also checks the default; sparc-callreturn #8 pins int8.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015sdZpNU5odw5dVyaxeSvvz
mahaloz added a commit that referenced this pull request Oct 17, 2026
…1137)

A 32-bit result that C computes as a signed `int` is printed under a zero extension or an unsigned operator, so the C sign-extends (or shifts in sign bits) where the binary does not:

```
$ printf '.intel_syntax noprefix\n.globl f\n.type f,@function\nf: movzx eax,word ptr [rsi]\n xor eax,0x80\n add eax,-0x80\n mov qword ptr [rdi],rax\n ret\n.size f,.-f\n' > w.s
$ as w.s -o w.o && kuna decompile-all w.o
void f(unsigned long *a0,unsigned short *a1)
{
  *a0 = (unsigned long)((*a1 ^ 0x80) - 0x80);
}
```

`*a1` promotes to `int`, so for a halfword of 0x80 the C stores 0xffffffffffffff80 where the binary stores 0x00000000ffffff80. A switch on a byte sum has the same problem one width down:

```
$ printf 'int sel(unsigned char c){switch((unsigned char)(c+1)){case 0x80:return 3;case 0x81:return 5;case 0x82:return 7;case 0x83:return 11;case 0x84:return 13;default:return 1;}}\n' > s.c
$ gcc -O0 -c s.c && kuna decompile-all s.o
  switch(a0 + '\x01') {
    case -0x80:
```

For `c = 0x7f` the C switches on 128 and takes the default; the binary takes case 0x80.

- The IR types such an expression `unsigned int` (the most ordered operand type), but C evaluates it as `int`. A reader that treats its input as unsigned (a zero extension, a logical right shift, an unsigned compare, divide or remainder) now works out the expression's C type from what the text states (literals, declared variables, casts, hidden extensions, the usual arithmetic conversions) and, when it is signed, makes it unsigned: a plain constant of a top `+`, `-`, `*`, `&`, `|` or `^` takes a `U` suffix (`*a0 = (*a1 ^ 0x80) - 0x80U;`), otherwise the expression is cast to `unsigned int`/`unsigned long`. Nothing changes when the nonzero-bit mask clears the top bit, or when the other operand of a compare, divide or remainder is already unsigned.
- A switch selector narrower than `int` whose promotion is not known to extend like its type prints cast to that type: `switch((char)(a0 + '\x01'))`.

Tests: `tests/stages/kuna-unsignedread.xml` (zero extension, shift, switch; each fails before). Two expectations moved to the suffixed form: FMTSTATIC #8 (`(uint8)(a0 * 3 + 7U)`) and the variadic round-trip tests (`(unsigned long)(k + 1U)`). Over 12 binaries (x86-64, ARM, AArch64), 136 functions change and casts go 122,619 -> 122,588. Recompiling the output for over 50,000 random functions (gcc/clang x86-64 -O0 to -Os, Thumb-2, ARM, AArch64) and running it against the originals: none newly wrong. Speed (CPU time, min of interleaved runs over gzip, kmod, grep, ls and bash): +0.55% total; a second build of main measured -0.37% in the same runs, and bash alone moves by up to 5.6% between two builds of the same source.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_018j4RDQSRU52HGQbqmeHJVe
mahaloz pushed a commit that referenced this pull request Oct 18, 2026
Windows i386 wide arguments are placed four bytes too far into the stack after an integer or hidden result pointer.

```sh
cat > sample.c <<'C'
struct wide { double real, imag; };
struct wide copy_wide(struct wide value) { return value; }
C
i686-w64-mingw32-gcc -O0 -g -shared sample.c -o sample.dll
kuna decompile sample.dll copy_wide --sleighpath specs --json
```

The argument's incorrect JSON storage is:

```json
"stack_offset": 12
```

The machine code reads it at entry ESP+8. Consequently, generated component stores use an uninitialized word and shifted fields.

- Let stack resources disable datatype alignment with `stackalign="false"`.
- Apply it to Windows i386 argument resources, preserving four-byte slots and the datatype's object alignment.
- Keep other compiler specifications unchanged and reject malformed resource annotations.

Tests check allocator/parser behavior and real PE argument offsets, then execute regenerated hidden-result and leading-integer cases with GCC and Clang at two optimization levels.


Stage-test expectation changes: MSVCBYVAL #16 now expects Take4(5,v1) (previously declined due to the wrong padding) and #8 expects the two Pair copy-constructor lines.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_018dDZ5j7DLzPHKAXC7p8wtX
mahaloz added a commit that referenced this pull request Oct 31, 2026
…phi order behind clonephiorder

The split now destroys a one-input phi from a global to itself in the
original block too, not only when its input is a COPY's output. A copy left
there was cloned as a plain COPY by the block's next split, and
ActionVarnodeProps replaced its known-zero output with 0, so the guard that
read it printed a second store: bash sh_getopt `nextchar = NULL;` (O2,
O2-noinline, /usr/bin/bash) and scp getopt_internal `BSDoptarg = NULL;
BSDoptreset = 0; place = "";`, all once in the binary on those paths.
ELFMAIN #2 (an option-off pass) accepts the -O0 local form the split now
prints.

Address-ordering a clone's global phis picks an order the binary does not
record, so it is the `clonephiorder` option (default on, P8, transform).
Over 140 corpus binaries on and off differ in 119 store runs; of the 34 the
disassembly decides, on matches 21 and off 9. kuna-retcopyclone #8/#9 pin
both arms.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_013BBaWRVoTEYHNosYwYRoSE
mahaloz pushed a commit that referenced this pull request Nov 13, 2026
…ktrap) (#1519)

AArch64 SLEIGH lifts `brk #imm` to a jump through a SoftwareBreakpoint user-op. Flow truncated that jump to a call followed by a return, so a function whose overflow or bounds check ends in a compiler trap printed as void, passed its return value to the trap, or returned a value made up from a call through it. Flow classification now replaces that jump with a no-return halt when the immediate is one a compiler emits for a trap that does not return: #1 (llvm.trap, Swift, and Darwin/Windows unreachable), #1000 (GCC), #0x5500-#0x55ff (llvm.ubsantrap), #0xc470-#0xc473 (arm64e pointer-auth failure) and #0xf003 (MSVC __fastfail).
The trap still prints as a SoftwareBreakpoint(..) statement. For __fastfail it also reads the failure code from w0, so `mov w0,#8; brk #0xf003` prints `SoftwareBreakpoint(0xf003,..,8);`. No other trap reads a register. Always on, with no option: a brk never returns to its caller. brk #0xf000, #0 and the Linux kernel's resumable immediates keep the old rendering. ptrauthtrap still removes the pointer-auth checks it matches, and a check it keeps now ends the flow. The fix lives in p2_lift/kuna_brktrap.rs and is covered by tests/stages/kuna-brktrap.xml.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_0179iMKQeLQDThvbHGNoGw8h
mahaloz added a commit that referenced this pull request Nov 14, 2026
Re-record docs/baseline-stages.json on the merged tree (kuna-repframecopy
#8 renamed, #10-#13 added); corpus count 754.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_0179iMKQeLQDThvbHGNoGw8h
mahaloz added a commit to borancar/kuna that referenced this pull request Nov 16, 2026
…code

A callee whose walk cannot settle its stack effect is taken to pop what its
reached returns pop. That was the most any reached return popped, so a
__cdecl callee whose cold path ends in a call that does not return (one the
walk cannot read) gave the next function's `ret 0x20`: the walk runs on
through the padding into it. The pop was stated on the call, the block
expanded into its arguments, and the caller lost its second parameter and
read a slot above its frame instead.

The walk now records the pop only when every reached return pops the same,
it followed every path (no indirect jump, undecodable instruction or budget
overrun), no path ran into a software interrupt (int3 padding, int 0x29),
and no fall-through entered another known function. byvalreuse_pe_i386
gains stray/nf/ng; REPFRAMECOPY Noelo-Lab#18 and Noelo-Lab#8 fail without this.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_0179iMKQeLQDThvbHGNoGw8h
mahaloz added a commit to borancar/kuna that referenced this pull request Nov 16, 2026
…nges

The callee walks were cached until `calleeargs` changed, but a walk also
ends a path at a call to a no-return name, which `noreturn_known`,
`gobounds` and `securitycheck` gate. Turning one off in a console session
left the earlier walks in place, so a by-value block stayed expanded on the
strength of a pop a fresh session no longer proves. The cache now keys on
all four.

byvalreuse_pe_i386 gains quit/qtake/exit; REPFRAMECOPY Noelo-Lab#19 and Noelo-Lab#8 fail
without this.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_0179iMKQeLQDThvbHGNoGw8h
mahaloz added a commit to borancar/kuna that referenced this pull request Nov 16, 2026
…tles every call

A block that only its callee's reached returns prove an argument block was
expanded whenever that pop could be stated, even with another call in the
function whose pop nothing proves. The solver then guesses that call's pop
(an internal __stdcall callee that calls through a pointer: nothing), every
slot after it moves by four, and the expanded call reads the block through
the return address and the caller's next parameter: `guess(r); return
take(*r) + k;` printed `sub_4012f0(a0); ... return sub_401040(*v9,...) + a0;`.

Such a block is now expanded only when the stated pops leave every call with
a pop its prototype states or its returns prove; otherwise it stays a loop,
as on main. byvalreuse_pe_i386 gains unsettled/guess; REPFRAMECOPY Noelo-Lab#21 and
Noelo-Lab#8 fail without this.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_0179iMKQeLQDThvbHGNoGw8h
sjkim1127 added a commit to sjkim1127/kuna that referenced this pull request Nov 20, 2026
With stackviews off (the default), a function that stores a frame address
into a global and reads back through it lost its frame stores whenever the
bounded local view admission was refused, so the printed C read a local that
was never written (kuna-stackviews.xml obj_global_reuse returned 0x43 in the
binary but printed reads of an uninitialised LifetimePair).

A live COPY into persistent storage, a STORE outside the stack space, or a
write_volatile whose value is a frame address now turns on the alias-checked
stackalias hold for the rest of the function's analysis. This is a strict
correctness fix and has no option.

The x86 SEH record in kuna-pebnames-x86.xml now keeps its handler and state
stores (it printed as a never-written char[12] before); Noelo-Lab#7/Noelo-Lab#8 are re-pinned
and docs/baseline-stages.json is re-recorded for the new and renamed
assertions. No datatest assertion moved (675/675).

[AUTOMATED]

Co-Authored-By: Claude Opus 5.5 <[email protected]>
mahaloz added a commit that referenced this pull request Nov 23, 2026
…default: return; at the end of a void function (#1903)

A switch prints its arms in label order, so `default:` lands first or between two cases. When that arm ends in a call that does not return, nothing stops it, and the arm printed next reads as code it falls into. gcc -O2 `switch (t) { case 0: ...; case 1: ...; case 2: ...; default: abort(); }`:

```
printf '83ff01743b83ff02741685ff742289febf1b204000e876ffffff660f1f440000b817204000c3662e0f1f840000000000b80f204000c3662e0f1f840000000000b813204000c3' | xxd -r -p > fs.bin
kuna decompile fs.bin 0x401070 --raw-image --target x86:LE:64:default:gcc --base 0x401070 --option loweredswitch linear --define-function 0x401000=abort
```

Before:

```c
  switch(a0) {
    case 0:
      return 0x40200f;
    default:
      abort(); // no-return
    case 1:
      return 0x402013;
```

After:

```c
  switch(a0) {
    case 0:
      return 0x40200f;
    case 1:
      return 0x402013;
    case 2:
      return 0x402017;
    default:
      abort(); // no-return
  }
```

- After the label sort, `default:` prints after the other arms, and an arm whose last block ends in a call with no successor prints after all of them; if there are several, each but the last gets a `break;`. Fall-through chains stay together. No option: no order it changes prints anything the program does.
- `voidtailreturn` also covers a void function that ends in a switch: the `default: return;` arm a duplicated epilogue leaves (where the source had no `default:` or `default: break;`) is not printed when the switch is the last statement. `option voidtailreturn off` keeps it.

Tests: new stage test `kuna-switcharmorder` (the no-return `default:` prints last with nothing after it; the tail switch has no `default: return;`, and has it again with `voidtailreturn off`), unit tests for the order. `kuna-native-switch-labels` #8 no longer pins `default:` first. 0/675 datatest assertions move.

On the decbench corpus 50 more functions match the source's control flow at O2 (gained 50, lost 0) and 64 more at O0 (gained 65, lost 1: a source that puts its `abort()` arm first).

Model: `anthropic/claude-opus-5-5`

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_013BBaWVABMswm9QwjnywGWU


Co-Authored-By: Claude Fable 5.2 <[email protected]>
Claude-Session: https://claude.ai/code/session_013BBaWVABMswm9QwjnywGWU
mahaloz added a commit to sjkim1127/kuna that referenced this pull request Nov 24, 2026
…y for a prologue push

`endbr64` lifts to no p-code, so prologue_push's backward walk never met an op
at the entry address in a function built with -fcf-protection (Ubuntu's gcc
default) and ran off the block start instead. gcc's `endbr64; push %rbx; ...;
call sys1` therefore still made the call a stack-argument store, giving
`sys1(0x27,a1,a2,a3,a4,a5)` and a six-parameter caller. Running off the start
of an entry block that nothing jumps back into now counts as reaching the entry.

Adds passthroughslot Noelo-Lab#8 (pid_minus).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_013BBaWTdjVzTz11WxPZmJ9b
mahaloz added a commit to phix33/kuna that referenced this pull request Nov 26, 2026
Resolves the docs/baseline-stages.json conflict by re-recording it on the merged
tree: 5,538 assertions, main's 5,536 plus this PR's two new elfv1-symbolextent
assertions (Noelo-Lab#7, Noelo-Lab#8), with Noelo-Lab#1-Noelo-Lab#3 renamed. The corpus count stays 935.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_013BBaWTdjVzTz11WxPZmJ9b
mahaloz added a commit to thotypous/kuna that referenced this pull request Nov 26, 2026
…e them in spec 09

UNSIGNEDREAD Noelo-Lab#8 checks that a shifted product is converted once, and a
CLI test checks that a four-byte unsigned product under the Go integer
model prints without conversions. The spec 09 paragraph now states the
operand, width and bound conditions the printer checks.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_013BBaWTdjVzTz11WxPZmJ9b
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