Skip to content

docs: build-plan for the infeasible-at-tier / non-ELF / huge-subsystem analyzers - #13

Merged
mahaloz merged 1 commit into
mainfrom
docs-infeasible-buildplan
Jun 23, 2026
Merged

mahaloz merged 1 commit into
mainfrom
docs-infeasible-buildplan

Conversation

@mahaloz

@mahaloz mahaloz commented Jun 23, 2026

Copy link
Copy Markdown
Contributor

Adds docs/analysis-port-buildplan.md: a concrete, dependency-ordered build-plan (not an implementation) for the Ghidra analyzers the analysis-port effort declared infeasible at kuna's current analysis tier, non-ELF / out-of-scope, or a huge subsystem. The feasible ELF analyzer set is already done (Increments 1–17; completeness sweep is Increment 15). This is the "Feasible + Docker-unblock" scope-B deliverable: for the harder analyzers, produce a plan, not code.

For each item the doc gives (a) what the Ghidra analyzer does, (b) the precise reason it is not feasible on kuna's pre-decompile, object-bytes-only tier (cites the missing subsystem + the AnalysisCtx/AnalysisOutput contract), (c) a concrete plan — what to build first, the real kuna engine seams it hooks (Sleigh::one_instruction, s2_lift/flow.rs, ObjectLoadImage, pass.rs fact kinds, the commit_analysis_output seam), S/M/L/XL effort, and ordering — and (d) a verdict (build-now-if-scope-expands / defer / never-for-an-ELF-decompiler).

Groups covered:

  1. Infeasible-at-tier (AggressiveInstructionFinderAnalyzer +ARM, FindNoReturnFunctionsAnalyzer flow heuristic, the operand/reference markup family). The most valuable part is the shared prerequisite they all need: a sketch of a kuna post-disassembly Listing tier — a recursive-descent disassembler over loadimage bytes producing an instruction/xref/function model, reusing the existing SLEIGH decoder + the S2 flow-classification logic, with new fact kinds, gated default-off and bound to the real-ELF path so the XML datatest parity is structurally untouched.
  2. Non-ELF loaders — PE/COFF and Mach-O: loader effort sizing, which ported passes each unlocks, and the container additions (mingw-w64 / osxcross) for in-env fixtures if that scope is taken.
  3. Huge ELF subsystems — Go pclntab name recovery (Golang{String,Symbol}Analyzer) and FID fingerprinting (FidAnalyzer), each with its required subsystem plan.
  4. Cosmetic / low-payoff — the _INIT_<i>/_FINI_<i> array-element naming (handled separately) and the $d data-run markup, referenced briefly.

It ends with a prioritized scope-B sequence.

Headline recommendation: build the post-disassembly Listing tier first — it is the single highest-leverage item, unlocking three analyzers at once (FindNoReturn, the sound substitute for AIF, and a prerequisite for FID). Then Go pclntab (highest standalone value, independent of the Listing tier), then FindNoReturn, then PE/COFF (if Windows scope is taken), then FID. Decline AIF itself and the operand/reference markup family as producing passes.

Docs-only: no engine code changed, so the make/make test/make rust-test/make test-stages gates were not run. Adds a one-line discoverability pointer to the new doc from missing-analyses.md (near the roadmap table) and analysis-port-log.md (near "Remaining work").

🤖 Generated with Claude Code

https://claude.ai/code/session_01FvRnfTgYKoZvS2TEvdYpWb

…m analyzers

Add docs/analysis-port-buildplan.md: a concrete, sequenced build-plan (not an
implementation) for the Ghidra analyzers that the analysis-port effort declared
infeasible-at-tier, non-ELF, or huge-subsystem. For each item: what the analyzer
does, the precise reason it is not feasible on kuna's pre-decompile object-bytes
tier, a concrete plan (what to build first, real kuna engine seams, S/M/L/XL
effort, dependency order), and a verdict.

Groups: (1) infeasible-at-tier (AIF +ARM, FindNoReturn flow heuristic, the
operand/reference markup family) — designs the shared prerequisite, a kuna
post-disassembly Listing tier reusing the SLEIGH decoder + S2 flow classification,
default-off and bound to the real-ELF path so the XML datatest parity is untouched;
(2) non-ELF PE/COFF + Mach-O loaders (+mingw-w64/osxcross fixtures); (3) huge ELF
subsystems (Go pclntab name recovery, FID fingerprinting); (4) cosmetic items.
Ends with the scope-B priority: Listing tier first (unlocks three analyzers at
once), then Go pclntab, then FindNoReturn, then PE, then FID.

Docs-only: no engine code changed, so the make/test gates were not run. Adds a
discoverability pointer to the new doc from missing-analyses.md (roadmap table)
and analysis-port-log.md (Remaining work).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01FvRnfTgYKoZvS2TEvdYpWb
@mahaloz
mahaloz merged commit 9bcf9ec into main Jun 23, 2026
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]>
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
mahaloz deleted the docs-infeasible-buildplan branch July 29, 2026 08:01
mahaloz added a commit that referenced this pull request Sep 19, 2026
… every target the vararg rule admits

A closed format prototype also changes how P4 scores the argument trials of
the calls around it. On AArch64 and ARM32 firmware that added more wrong
arguments to neighbouring calls than it removed (an x8 of 0 ahead of the real
arguments; iproute2 ip's parse_rtattr losing its len), while on x86 every such
change removed a phantom. static now resolves at load on x86 only; full still
resolves on every target VarargAbi admits. Stage passes 24-26 pin AArch64
default == off and full typed; #13/#19/#23/#28 pin ARM the same way.

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

A closed format prototype also changes how P4 scores the argument trials of
the calls around it. On AArch64 and ARM32 firmware that added more wrong
arguments to neighbouring calls than it removed (an x8 of 0 ahead of the real
arguments; iproute2 ip's parse_rtattr losing its len), while on x86 every such
change removed a phantom. static now resolves at load on x86 only; full still
resolves on every target VarargAbi admits. Stage passes 24-26 pin AArch64
default == off and full typed; #13/#19/#23/#28 pin ARM the same way.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01YFCA715QE6ZBSnTn7bwabG
mahaloz added a commit that referenced this pull request Sep 27, 2026
…ages baseline +20 elemptr keys only (1430)

tiedphitrim #13/#14 and structsynth-locals #2 read a 4-byte field through an
inferred int8 * and pinned upstream's widened form (int4)v[1]; with elemptr on
the load stays 4 bytes, *(int4 *)&v[1]. Keys unchanged.

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

A pointer stored to a global and kept in its own variable made every load of
the global after the store read the register: `gi = q; x = q[2]; *pp = p;
return gi[1] + x;` printed `return v2 + v1[1];`, which is wrong when `pp`
points at `gi`. RulePropagateCopy now leaves such a load reading the global
when a STORE, or a call with no INDIRECT on the global, lies between the store
and the load, and does not move a register copy of that load past a later
store; Merge and checkImpliedCover keep that copy as its own variable. A join
that still reads the global's value from before a store that became a COPY
after heritage counts as an earlier value read after the store, so yylex's
-O2 store keeps upstream's handling.

The fixture gains g_reload, g_write, g_before, g_diff and g_twice, called
with the stored-through pointer aimed at the global; the round trip and stage
assertions #9-#13 cover them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Ps66ZCFPLywq9AKHBuDXNU
mahaloz added a commit that referenced this pull request Oct 1, 2026
…ading the global

A pointer stored to a global and kept in its own variable made every load of
the global after the store read the register: `gi = q; x = q[2]; *pp = p;
return gi[1] + x;` printed `return v2 + v1[1];`, which is wrong when `pp`
points at `gi`. RulePropagateCopy now leaves such a load reading the global
when a STORE, or a call with no INDIRECT on the global, lies between the store
and the load, and does not move a register copy of that load past a later
store; Merge and checkImpliedCover keep that copy as its own variable. A join
that still reads the global's value from before a store that became a COPY
after heritage counts as an earlier value read after the store, so yylex's
-O2 store keeps upstream's handling.

The fixture gains g_reload, g_write, g_before, g_diff and g_twice, called
with the stored-through pointer aimed at the global; the round trip and stage
assertions #9-#13 cover them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Ps66ZCFPLywq9AKHBuDXNU
mahaloz added a commit that referenced this pull request Oct 1, 2026
…ading the global

A pointer stored to a global and kept in its own variable made every load of
the global after the store read the register: `gi = q; x = q[2]; *pp = p;
return gi[1] + x;` printed `return v2 + v1[1];`, which is wrong when `pp`
points at `gi`. RulePropagateCopy now leaves such a load reading the global
when a STORE, or a call with no INDIRECT on the global, lies between the store
and the load, and does not move a register copy of that load past a later
store; Merge and checkImpliedCover keep that copy as its own variable. A join
that still reads the global's value from before a store that became a COPY
after heritage counts as an earlier value read after the store, so yylex's
-O2 store keeps upstream's handling.

The fixture gains g_reload, g_write, g_before, g_diff and g_twice, called
with the stored-through pointer aimed at the global; the round trip and stage
assertions #9-#13 cover them.

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

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_0179iMKQeLQDThvbHGNoGw8h
mahaloz added a commit that referenced this pull request Nov 18, 2026
Two of the push-run readings for the frame a declared call leaves misread
GCC/MinGW code, found on held-out builds:
- The `mov [esp],x` local test took a push for a mov when the push landed
  on the stack pointer the declared call left after a raise (GCC's
  `call [Sleep]; add esp,12; push; push; push; push; call [f]` around a
  padded call): the run stopped at the third push and f was guessed to pop
  12 bytes too few. The simplifier has already removed such a push's
  stack-pointer write, so the store's instruction bytes say whether it is a
  push; only a mov ends the run.
- The entry-value test counted ECX's entry value written with MinGW's fixed
  frame `mov [esp],ebx` as an argument push, so a __cdecl callee was
  guessed to pop it and the function gained a phantom parameter. Only a
  pushed entry value counts now.
The fixture gains land_push and acc_entry; stage asserts #12 and #13
fail without this change.

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

A pop only the callee's RET constant states no longer settles a function in
which a direct call's callee pops above its return address and the caller
then removes more right after the call: Delphi's nested-routine frame link
(push ebp; push x; call f; pop ecx to a ret 4) and GCC before 4.7's hidden
return pointer (ret 4, then add esp,4). With every pop exact, the solve gave
such a call only the slots its callee pops and dropped the caller-removed
one (vcall_pe_i386 start: sub_4010d0(0x40301c) for (0x40301c,0x403018);
Delphi crackmes lost the frame link at every nested call). Those functions
keep main's guessed solve. The caller's cleanup is recorded on the call spec
at flow time, only where the callee pops above its return address.
CALLEEPURGE Noelo-Lab#13 pins it; the stages baseline gains that assertion.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_013BBaWTdjVzTz11WxPZmJ9b
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant