Skip to content

feat: harden SSA/CFG structuring, DEX SSA web splitting, and R8 recovery (v0.9.0) - #35

Merged
VillanCh merged 4 commits into
mainfrom
feat/p0-ssa-cfg-dex-r8-hardening
Nov 21, 2026
Merged

VillanCh merged 4 commits into
mainfrom
feat/p0-ssa-cfg-dex-r8-hardening

Conversation

@VillanCh

@VillanCh VillanCh commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

Summary

This PR resolves P0 and P1 algorithmic bottlenecks across SSA type lattice merging, core dataflow, multi-exit CFG/constructor/loop structuring, DEX→JAR SSA web splitting & lowering, and R8/Android --best-effort recovery, backed by pure-Go adversarial regression suites and real-world Android corpus benchmarks.

Phase 1 (P0): SSA Type Lattice, Dominance, Polymorphic-Zero DEX Lowering & Best-Effort Recovery

  1. SSA Type Lattice & Core Dataflow (classparser/decompiler/core)

    • frametransfer/frame.go: Fixed JVMS §4.10.1.2 joinRefClass array LUB convergence across multi-dimensional arrays and array interfaces (Cloneable, Serializable, Object[], Object).
    • ssalower/plan.go: Added compatibleExceptionSpillType for exception-handler local phi lattice compatibility.
    • dataflow.go & code_analyser.go: Added reachingPhiConvergentSameOrSuperStore, singleUseStoreReachesOtherLoad, and super() anchor preservation for deferred irreducible constructor CFG (JDEC_CTOR_POST_SUPER_DISPATCH_OFF).
    • values/java_value.go & values/expression.go: Resolved IsThisAlias so parent invokespecial calls render as super.m(...).
  2. CFG, Dominance & Loop/Constructor Structuring (classparser/decompiler/utils, rewriter)

    • utils/util.go: Replaced chain traversal in DominateIndex with O(1) Euler-tour entry/exit interval checks.
    • rewriter/irreducible_dispatch.go: Added postDelegationConstructorAnchor for post-super(...) irreducible dispatch.
    • rewriter/loop_form_normalize.go: Extended NormalizeLoopForms (doWhileWithConstPrefixAsWhile, isSimpleLoopUpdate, extractDoWhileGuard, gated by JDEC_LOOP_NORM_EXT_OFF).
  3. DEX IR & JVM Lowering (dex2jar, internal/dexparser)

    • Direct Read-Only Parameter Mapping & Polymorphic const/4 0 Solver: Eliminates redundant prologue copies and materializes polymorphic 0 across Int/Float/Reference.
    • DEX Fidelity: iinc emission for add-int/lit16 and lit8, float[] (FASTORE) in filled-new-array, F/J/D debug LVT entries, and hiddenapi_class_data (0xf000) parsing.
  4. End-to-End R8 / Android --best-effort Recovery (cmd/javajive, javajive.go, classparser)

    • Threaded RetainUnprovedSource cleanly without relaxing strict Precision mode invariants.

Phase 2 (P1 — Next Level): SSA Def-Use Web Splitting, Nested Multi-Exit Forward Regions & Constructor/R8 Edge Recovery

  1. DEX SSA Def-Use Live-Range Web Splitting & Pre-super() Direct Deferred Stores (dex2jar/lower/webs.go, dex2jar/lower/method.go)

    • assignWebs: Forward reaching-definitions dataflow worklist over DEX CFG blocks (handling entry-block b == 0 loop back-edges and protected-instruction exception handler edges) + Union-Find Def-Use web clustering. Splits overloaded Dalvik vN registers into disjoint JVM local slots, directly uses incoming parameter slots even when overwritten later in another web, deduplicates LVT entries per (slot, start, end), and guards giant methods (Instructions * defs > 100000) to stay well under t25 sparse dataflow budgets (JDEC_DEX_WEBSPLIT_OFF).
    • canDirectDeferredStore: Elides temporary synthetic locals on pre-super() field stores when receiver/value registers remain unmodified before delegation (JDEC_DEX_DIRECT_DEFERRED_OFF).
    • classparser/decompiler/core/values/java_value.go: Added nil/typed-nil *JavaRef safety guards in (*JavaRef).String, (*SlotValue).Type, and (*SlotValue).String.
    • Tightened arithmetic.dex deterministic quality baseline & maximum in dex2jar/testdata/accept/manifest.json (lines: 45 -> 38, tokens: 94 -> 79, synthetic_vars: 28 -> 14).
  2. Nested Multi-Exit Acyclic Forward Region Structuring (classparser/decompiler/rewriter/)

    • Extended statementWrap.forwardRegions from map[*core.Node]*forwardRegion to ordered []*forwardRegion stacks across forward_region.go, try_rewriter.go, try_if_collection_boundary.go, protected_commit_exit.go, and protected_normal_exits.go.
    • Implemented findCommonForwardJoin (non-mutating via rollbackPending), iterative materializeForwardRegionExits, closedForwardRegionWithSiblingExits (linearizing parallel sibling joins like Material BottomSheetBehavior / AppBarLayout$BaseBehavior), and sequential innermost-to-outermost finishForwardRegion wrapping (JDEC_NESTED_FORWARD_REGION_OFF).
  3. Constructor Prefix Algebraic Folding & RetainUnprovedSource Boundary Recovery (classparser/constructor_retain_prefix.go, constructor_source_boundary.go, dumper.go)

    • Under explicit RetainUnprovedSource (--best-effort), folds pre-delegation Kotlin default-parameter bitmask if branches into TernaryExpression, resolves pre-super parameter mutations via tryFoldEscapingParamIntoDelegate, omits redundant super(), or preserves effect-safe prefix statements before/after delegation or via single-arg carrier helper (JDEC_CTOR_RETAIN_PREFIX_OFF). Strictly rejected when RetainUnprovedSource == false.
  4. Checked-Exception Escape Decoupling & R8 Exception Sentinel Recovery (classparser/checked_escape.go, leaked_exception_sentinel.go)

    • Allows checkedEscapeInheritedNames under RetainUnprovedSource to collect known ancestor names across incomplete external Android/SDK hierarchies.
    • Added rewriteLeakedSuppressedClose and stripDeadExceptionSentinelLocals to reconstruct R8's <Type> varX = Exception; primary.addSuppressed(varX); res.close(); try-with-resources close pattern.
  5. Pure-Go Adversarial Tests

    • classparser/decompiler/rewriter/forward_region_nested_test.go
    • dex2jar/adversarial_p1_websplit_test.go
    • classparser/adversarial_p1_next_level_test.go
    • Updated sealed test inventory in tools/requiredci/main.go.

Review Fix: Fail-Closed Loop Constant-Prefix Hoisting Proof (loop_form_normalize.go)

  • Addressed review feedback on doWhileWithConstPrefixAsWhile (classparser/decompiler/rewriter/loop_form_normalize.go): previously it did not inspect the loop condition for writes (x++ < 1 && i++ < 2) and missed ++/--/compound/embedded writes in the body or opaque/aliased statements.
  • Replaced varAssignedInStatements with statementsMayWriteOrOpaqueLocal + valueMayWriteOrOpaqueLocal + localConflictsInStatements (via shared fail-closed statementTreeCheckFailClosed over all Statement kinds and values.InspectAccess / values.InspectValue), proving both guard.Condition, normalized cond, body, remaining, and prevAssign (gated on makeForLoop != nil) are free of writes, opaque leaves, and scope/spelling collisions before hoisting.
  • Added 3 verification layers:
    • Small-step AST behavioral interpreter evalLoopIntStatements + TestNormalizeLoopFormsConstPrefixBehavioralEquivalenceAndWriteGuards in classparser/decompiler/rewriter/loop_form_normalize_test.go (9 subtests proving iteration-count / result preservation).
    • Bytecode reproduction & regression test TestAdversarialLoopConstPrefixRejectsCondAndBodyMutationBytecode in classparser/adversarial_p0_roundtrip_test.go (pure Go, included in requiredci -run corpus).
    • Full-JDK oracle round-trip test TestAdversarialLoopConstPrefixPerIterationResetRoundTrip in classparser/adversarial_loop_const_prefix_roundtrip_test.go.

Empirical Benchmark Results (./cmd/javajive)

Target Metric Baseline (before PR) Phase 1 (P0) Phase 2 (P1)
arithmetic.dex (strict accept) Lines / Tokens / varN 48 / — / — 45 / 94 / 28 38 / 79 / 14 (-50% varN)
bundletool-app.apk Lines / varN / super call 87 / 13 / missing 60 / 2 / super.onCreate(var1) 60 / 2 / intact
androguard-tc-debug.apk Lines / varN 666 / 897 615 / 747 512 (-23.1%) / 565 (-37.0%)
bundletool-install-time.aab (1,298 classes, --best-effort) Class-level failures 67 0 0
bundletool-install-time.aab Method-level stubs — 266 31 (-88.3%)
bundletool-install-time.aab Synthetic varN 158,294 152,292 133,001 (-25,293)
requiredci -run dex Statement coverage 4,893 / 5,777 5,114 / 5,975 5,618 / 6,557 (85.7%)

Verification

  • go vet ./...
  • CGO_ENABLED=0 go build ./... & CGO_ENABLED=0 go build -tags javajive_full_jdk ./...
  • go run ./tools/requiredci -check
  • go run ./tools/requiredci -run contract
  • go run ./tools/requiredci -run corpus
  • go run ./tools/requiredci -run algorithm (with -race)
  • go run ./tools/requiredci -run dex (with -race + coverage threshold)
  • JAVAJIVE_EXTERNAL_EVAL=1 go test -v -count=1 ./test/external

…, and R8 recovery

- classparser/decompiler/core:
  - Fix JVMS 4.10.1.2 reference-array LUB convergence in joinRefClass (frametransfer/frame.go)
  - Support compatible exception-handler local phi spill types (ssalower/plan.go)
  - Add reaching-phi convergent store slot splitting and live-across-branch single-use store guards (dataflow.go, code_analyser.go)
  - Resolve IsThisAlias super.m() invocations cleanly (values/java_value.go, values/expression.go)
  - Preserve explicit super() anchor when deferred irreducible constructor CFG exists (code_analyser.go)
- classparser/decompiler/utils & rewriter:
  - Upgrade DominateIndex ancestor queries to O(1) Euler-tour intervals (utils/util.go)
  - Enable post-super() constructor irreducible dispatch via postDelegationConstructorAnchor (rewriter/irreducible_dispatch.go)
  - Extend NormalizeLoopForms with const-prefix and inverted guard normalization (rewriter/loop_form_normalize.go)
- dex2jar & internal/dexparser:
  - Map read-only incoming DEX parameters (including `this`) directly to JVM parameter slots (lower/method.go)
  - Add PolyZeroAllocation / demandState constraint solver and companion-slot lowering for zero constants shared across Int/Float/Reference (ir/*, lower/method.go)
  - Emit JVM IINC for add-int/lit16 and lit8, enable float[] (FASTORE) in filled-new-array, preserve F/J/D LVT debug entries, and accept hiddenapi_class_data (0xf000) in DEX parser
  - Refresh pinned JAR hashes and improved decompile baselines in dex2jar/testdata/accept/manifest.json
- R8 / Android --best-effort recovery & cross-platform contracts:
  - Propagate RetainUnprovedSource (--best-effort / --retain-unproved) end-to-end across cmd/javajive, javajive.go, classparser/jarwar, dumper.go, static_owner.go, and static_import.go
  - Keep strict mode unchanged while retaining bytecode-named static targets (including R8 inherited static calls and static-import collisions), non-javac enums, and enclosing-scope fallbacks under analysis/recover mode
  - Normalize LF attributes (.gitattributes) and add Windows NTFS junction fallback in t23_path_test.go so requiredci runs cleanly on Windows & Linux
- Add pure-Go adversarial regression suites covering all fixed SSA, CFG, DEX, and R8 cases and update tools/requiredci/main.go inventory
…t forward regions, and constructor prefix folding
@VillanCh VillanCh changed the title feat: harden SSA/CFG structuring, DEX polymorphic-zero/param lowering, and R8 recovery feat: harden SSA/CFG structuring, DEX SSA web splitting, and R8 recovery (v0.9.0) Nov 21, 2026
@VillanCh
VillanCh merged commit f918203 into main Nov 21, 2026
5 checks passed
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