diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 02c9e8a6..f425b0d2 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,7 +1,5 @@ -# Keep required PR feedback fast and attributable: one pinned JDK 21 runtime, -# algorithm invariants under the race detector, and small production-path -# counterexamples. A javac8 compiler covers its small source-protocol fixtures; -# JVM execution stays on JDK 21. Full historical-corpus checks remain manual. +# Required feedback is deliberately limited to reviewed Go algorithms and +# hash-pinned corpus inputs. Runtime/compiler behavior remains in manual gates. name: CI on: push: @@ -16,41 +14,27 @@ concurrency: cancel-in-progress: true env: GOTOOLCHAIN: local - PYTHONDONTWRITEBYTECODE: "1" jobs: - scope: - name: Classparser suite scope + contract: + name: Required inventory and build runs-on: ubuntu-22.04 timeout-minutes: 10 - outputs: - classparser: ${{ steps.scope.outputs.classparser }} steps: - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 with: persist-credentials: false - fetch-depth: 0 - uses: actions/setup-go@40f1582b2485089dde7abd97c1529aa768e1baff with: go-version-file: go.mod cache: true - - name: Decide whether the classparser suite can change - id: scope - env: - EVENT_NAME: ${{ github.event_name }} - BASE_SHA: ${{ github.event.pull_request.base.sha || github.event.before }} - HEAD_SHA: ${{ github.sha }} - PR_LABELS: ${{ join(github.event.pull_request.labels.*.name, ',') }} - run: python3 -I tools/ci_scheduler/scope.py >> "$GITHUB_OUTPUT" - source: - name: Source algorithm regression (${{ matrix.shard }}) - needs: [scope] - if: needs.scope.outputs.classparser == 'true' + - run: go run ./tools/requiredci -check + - run: CGO_ENABLED=0 go build ./... + - run: go run ./tools/requiredci -run contract + + corpus: + name: Fixed corpus regression runs-on: ubuntu-22.04 - timeout-minutes: 35 - strategy: - fail-fast: false - matrix: - shard: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] + timeout-minutes: 10 steps: - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 with: @@ -59,184 +43,12 @@ jobs: with: go-version-file: go.mod cache: true - - uses: actions/setup-java@cf277c60eb25467037889841efdb72551f06f6c3 - with: - distribution: temurin - java-version: '8' - - name: Retain compiler for javac8 protocol fixtures - run: echo "JAVA8_JAVAC=${JAVA8_JAVAC:-$JAVA_HOME/bin/javac}" >> "$GITHUB_ENV" - - uses: actions/setup-java@cf277c60eb25467037889841efdb72551f06f6c3 - with: - distribution: temurin - java-version: '21' - - name: Reduce startup cost for small Java fixtures - run: | - mkdir -p "$RUNNER_TEMP/fixture-java" - # These short JVM processes exit before full JIT warmup pays off. - # One CPU and serial GC avoid competing compiler/GC pools on the - # runner. Original and rebuilt programs use the same options; - # the fixtures, assertions, test set and individual deadlines stay unchanged. - # CDS shares compiler class metadata, never fixture source or compiler results. - printf 'final class Warmup {}\n' > "$RUNNER_TEMP/fixture-java/Warmup.java" - # Disable shared hsperfdata files: PID reuse across short JVMs can - # print a file-lock warning into an otherwise exact behavior oracle. - javac -J-XX:-UsePerfData -J-XX:TieredStopAtLevel=1 -J-XX:+UseSerialGC -J-XX:ActiveProcessorCount=1 \ - "-J-XX:ArchiveClassesAtExit=$RUNNER_TEMP/fixture-java/javac.jsa" \ - -proc:none -d "$RUNNER_TEMP/fixture-java" "$RUNNER_TEMP/fixture-java/Warmup.java" - test -s "$RUNNER_TEMP/fixture-java/javac.jsa" - printf '#!/bin/sh\nexec "%s" -J-XX:-UsePerfData -J-XX:TieredStopAtLevel=1 -J-XX:+UseSerialGC -J-XX:ActiveProcessorCount=1 "-J-XX:SharedArchiveFile=%s" "$@"\n' "$(command -v javac)" "$RUNNER_TEMP/fixture-java/javac.jsa" > "$RUNNER_TEMP/fixture-java/javac" - printf '#!/bin/sh\nexec "%s" -XX:-UsePerfData -XX:TieredStopAtLevel=1 -XX:+UseSerialGC -XX:ActiveProcessorCount=1 "$@"\n' "$(command -v java)" > "$RUNNER_TEMP/fixture-java/java" - # Apply the same startup budget to the retained javac8 compiler. - # This changes JVM scheduling only, not source targets or class bytes. - printf '#!/bin/sh\nexec "%s" -J-XX:-UsePerfData -J-XX:TieredStopAtLevel=1 -J-XX:+UseSerialGC -J-XX:ActiveProcessorCount=1 "$@"\n' "$JAVA8_JAVAC" > "$RUNNER_TEMP/fixture-java/javac8" - chmod +x "$RUNNER_TEMP/fixture-java/javac" "$RUNNER_TEMP/fixture-java/java" "$RUNNER_TEMP/fixture-java/javac8" - echo "JAVA8_JAVAC=$RUNNER_TEMP/fixture-java/javac8" >> "$GITHUB_ENV" - echo "$RUNNER_TEMP/fixture-java" >> "$GITHUB_PATH" - - name: Source algorithm regression tests - env: - SOURCE_SHARD: ${{ matrix.shard }} - SOURCE_SHARDS: "10" - SOURCE_WORKERS: "5" - EDGE_TEST_PATTERN: '^Test(Native|InheritedBridgeAnnotationPolicy|LexicalFormalSignature|InterfaceWrappedArrayRequires|MemberArity|PackageDescriptor|MemberGenericSupertype|ConstructorFinalizerSeal|ScopedClassNameBinding|CheckedEscape|CheckedConstructor|BindingPlan|CtorArrayThisSpillsRoundTrip|CtorArrayThisSpillPreservesEarlierArgumentOrder|CtorDelegationNestedArrayTempRoundTrip|CtorDelegationArgumentSpills|SuperDelegationTrailingArgumentSpills|SuperDelegationSpillAcrossSafePostSuperPrelude|ConditionalThisCtorCheckcastRoundTrip|TernaryCheckcastInvocationReceiverRoundTrip|CtorNPECheckBeforeThis|EnumArrayConstructorArgsRoundTrip|EnumClinit|ZxingEnum|GenericNull|GenericFieldElementOpsRoundTrip|GenericFunctionalThrows|GenericFunctionalValueKeepsErasedCallDescriptor|MaterializedBiFunctionErasureRoundTrip|SameClassBiFunctionTypeVariablesRoundTrip|SameClassFunctionAndSupplierErasureRoundTrip|SiblingClassFunctionalErasureRoundTrip|ChainedSiblingReturnFunctionalErasureRoundTrip|LowerBoundedFunctionalArgumentsRoundTrip|CapturedLowerBoundedFunctionalArgumentsRoundTrip|CapturedParameterizedLowerBoundRoundTrip|LambdaCaptureCopiesStayInsideGenericMethod|ClassCacheTernaryStoreRoundTrip|MapCacheTernaryLocalRoundTrip|ImmediateZeroArgCheckcastInvoke|NonConditionalForkDiamond|InheritedJDK|InvocationMetadata|JDKListNull|MemberLedger|MethodReferenceKeepsPolyTargetTypeRoundTrip|DirectoryStreamFilterKeepsInstantiatedMethodRefTypeRoundTrip|T04ExternalOverloadBindingRoundTrip|LogbackPutUninterruptibly|ProtobufRemainingReconstructs|ProtobufLazyStringArrayListThis|PublicSuffixDatabase|ThisCtorOverloadCast|GenericVarargsConstructorArrayRoundTrip|ShiftedThisCtorGenericArrayRoundTrip|ConditionalArrayCloneStoreRoundTrip|ToListSingleCallableCast|JacksonRemainingMapEntryDeserializerCast|JoinStreamCtorCast|RawGenericReceiver|SyntaxObservation|RetryRollback|ShadowBuilder|ShadowIRRunsFrameSSAAndLowering|T11_C01|Sentinels|Request|R06|T04|T05|T06|T07|T08|T18|T19|T27|TaskT20|TernaryCheckcastMergeRoundTrip|SelfCastNullMergeRoundTrip|ShortCircuitVarargsArraysRoundTrip|SharedFalseTargetFallthroughRoundTrip)' - run: | - set -o pipefail - mkdir -p artifacts - go test ./classparser -c -o "$RUNNER_TEMP/adversarial.test" - # The scope job skips this matrix when the diff cannot change the - # classparser binary or its fixtures. When it runs, ten disjoint - # shards with five batches each use the measured duration hints, so - # the lanes balance on observed cost. Parent groups run concurrently - # on the same pinned JDK. Five serial processes per shard isolate - # environment-changing tests. - # Exact original parent and nested-policy inventories remain checked; - # the required summary waits for every shard and the trusted fixtures. - python3 - <<'PYTHON' - import concurrent.futures, json, os, pathlib, re, shutil, signal, subprocess, sys, time - from tools.ci_scheduler.shard import source_parent_batches, source_parent_shards - binary = str(pathlib.Path(os.environ["RUNNER_TEMP"]) / "adversarial.test") - names = sorted(set(line for line in subprocess.check_output( - [binary, "-test.list", "^TestAdversarial|" + os.environ["EDGE_TEST_PATTERN"]], text=True, cwd="classparser").splitlines() - if line.startswith("Test"))) - if not names: - raise SystemExit("no source-regression tests discovered") - # Split the large nested-capture matrix by its actual source scopes. - heavy = "TestNativeAnonymousNestedOriginalCaptureRoundTrip" - source = pathlib.Path("classparser/native_anonymous_nested_roundtrip_test.go").read_text() - scope_text = re.search(r'for _, scope := range \[\]string\{([^}]+)\}', source).group(1) - scopes = re.findall(r'"([^"\n]+)"', scope_text) - if heavy not in names or not scopes or len(scopes) != len(set(scopes)): - raise SystemExit("incomplete nested-capture scope inventory") - shard, count = int(os.environ["SOURCE_SHARD"]), int(os.environ["SOURCE_SHARDS"]) - worker_count = int(os.environ["SOURCE_WORKERS"]) - if count != 10 or worker_count != 5 or not 0 <= shard < count: - raise SystemExit("invalid source regression shard") - all_ordinary = [name for name in names if name != heavy] - # Measured costs affect placement only. The binary's complete test - # inventory stays authoritative, including newly discovered tests. - hints = json.loads(pathlib.Path("ci/task_t29/source-duration-hints.json").read_text())["seconds"] - lanes = source_parent_shards(all_ordinary, hints, count * worker_count) - selected_lanes = lanes[shard*worker_count:(shard+1)*worker_count] - ordinary = sorted(name for lane in selected_lanes for name in lane.items) - selected_scopes = scopes[shard::count] - if not ordinary or not selected_scopes: - raise SystemExit("empty source regression shard") - groups = [{"scopes": selected_scopes[index:index+2]} for index in range(0, len(selected_scopes), 2)] - # Keep each parent atomic, but let idle workers take another bounded - # batch instead of waiting on one underestimated, fixed lane. - groups += [{"parents": batch.items} for batch in source_parent_batches(ordinary, hints)] - if sorted(name for group in groups for name in group.get("parents", [])) != sorted(ordinary): - raise SystemExit("source parent inventory mismatch") - # Concurrent evidence must not mutate the source fingerprint checked - # while the trusted adapter is built and executed. - evidence = pathlib.Path(os.environ["RUNNER_TEMP"]) / "algorithm-regression-evidence" - evidence.mkdir(parents=True, exist_ok=True) - (evidence / "adversarial-manifest.json").write_text(json.dumps(groups, indent=2)) - (evidence / "source-shard-selection.json").write_text(json.dumps({ - "shard": shard, "shards": count, "all_parents": names, "all_scopes": scopes, - "parents": ordinary, "scopes": selected_scopes}, indent=2)) - # Keep all batches/coverage mandatory. Leave measured runner - # variance headroom above the ~20m consolidated source phase; the - # 35m job limit also includes tool setup and binary compilation. - deadline = time.monotonic() + 28 * 60 - def run_batch(item): - index, group = item - path = evidence / f"adversarial-tests-{index+1}.jsonl" - remaining = deadline - time.monotonic() - if remaining <= 0: - path.write_text("phase deadline expired before batch started\n") - return path, 1 - command = ["go", "tool", "test2json", "-t", "-p", - "github.com/yaklang/javajive/classparser", binary, - "-test.v=test2json", "-test.count=1", "-test.parallel=1", - f"-test.timeout={remaining:.3f}s", - "-test.run=^(" + "|".join(map(re.escape, (group or {}).get("parents", [heavy]))) + ")$" + - ("/^(" + "|".join(map(re.escape, group["scopes"])) + ")$" if group and "scopes" in group else "")] - with path.open("w") as output: - process = subprocess.Popen(command, stdout=output, stderr=subprocess.STDOUT, - cwd="classparser", start_new_session=True) - try: - result = process.wait(timeout=max(0, deadline - time.monotonic())) - except subprocess.TimeoutExpired: - try: - os.killpg(process.pid, signal.SIGKILL) - except ProcessLookupError: - pass - process.wait() - output.write("SOURCE_PHASE_DEADLINE_EXPIRED: " + - json.dumps({"batch": index + 1, - "parents": (group or {}).get("parents", [heavy]), - "scopes": (group or {}).get("scopes", [])}) + "\n") - output.flush() - result = 1 - return path, result - failed = False - with concurrent.futures.ThreadPoolExecutor(max_workers=worker_count) as pool: - for path, result in pool.map(run_batch, list(enumerate(groups))): - print(f"{path}: exit={result}") - if result: - failed = True - print("\n".join(path.read_text().splitlines()[-80:])) - terminal = [] - for path in evidence.glob("adversarial-tests-*.jsonl"): - for line in path.read_text().splitlines(): - if not line.startswith("{"): - continue - row = json.loads(line) - if row.get("Test") and row.get("Action") in ("pass", "fail", "skip"): - terminal.append(row) - parents = [row for row in terminal if "/" not in row["Test"]] - for row in terminal: - if row["Action"] == "fail": - print("SOURCE_TEST_FAILED: " + row["Test"]) - leaves = [row for row in terminal if row["Test"].startswith(heavy+"/") and row["Test"].count("/") == 3] - expected = {heavy+"/"+scope+"/"+debug+"/"+policy for scope in selected_scopes - for debug in ("none", "source,lines,vars") - for policy in ("normal", "no-source-rewrites", "no-core-cleanups")} - if (set(row["Test"] for row in parents) != set(ordinary) | {heavy} or any(row["Action"] != "pass" for row in parents) - or len(leaves) != len(expected) or set(row["Test"] for row in leaves) != expected - or any(row["Action"] != "pass" for row in leaves)): - print("source parent or nested debug/policy coverage failed") - failed = True - if len({row["Test"] for row in parents if row["Test"] != heavy}) != sum(row["Test"] != heavy for row in parents): - print("duplicate source parent execution") - failed = True - (evidence / "source-shard-result.json").write_text(json.dumps({ - "shard": shard, "parents": len(ordinary), "heavy_policy_leaves": len(expected), "passed": not failed})) - shutil.copytree(evidence, "artifacts", dirs_exist_ok=True) - sys.exit(int(failed)) - PYTHON - - name: Roundtrip evidence - if: always() - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 - with: - name: algorithm-regression-evidence-${{ matrix.shard }} - path: artifacts/ - if-no-files-found: ignore - retention-days: 7 - regression: - name: Algorithm regression suite + - run: go run ./tools/requiredci -run corpus + + algorithm: + name: Go algorithm regression runs-on: ubuntu-22.04 - timeout-minutes: 15 + timeout-minutes: 10 steps: - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 with: @@ -245,130 +57,37 @@ jobs: with: go-version-file: go.mod cache: true - - uses: actions/setup-java@cf277c60eb25467037889841efdb72551f06f6c3 + - run: go run ./tools/requiredci -run algorithm + + dex: + name: Go DEX regression + runs-on: ubuntu-22.04 + timeout-minutes: 10 + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 with: - distribution: temurin - java-version: '21' - - name: Reduce startup cost for small Java fixtures - run: | - mkdir -p "$RUNNER_TEMP/fixture-java" - # These short JVM processes exit before full JIT warmup pays off. - # One CPU and serial GC avoid competing compiler/GC pools on the - # runner. Original and rebuilt programs use the same options; - # the fixtures, assertions, test set and individual deadlines stay unchanged. - # CDS shares compiler class metadata, never fixture source or compiler results. - printf 'final class Warmup {}\n' > "$RUNNER_TEMP/fixture-java/Warmup.java" - # Disable shared hsperfdata files: PID reuse across short JVMs can - # print a file-lock warning into an otherwise exact behavior oracle. - javac -J-XX:-UsePerfData -J-XX:TieredStopAtLevel=1 -J-XX:+UseSerialGC -J-XX:ActiveProcessorCount=1 \ - "-J-XX:ArchiveClassesAtExit=$RUNNER_TEMP/fixture-java/javac.jsa" \ - -proc:none -d "$RUNNER_TEMP/fixture-java" "$RUNNER_TEMP/fixture-java/Warmup.java" - test -s "$RUNNER_TEMP/fixture-java/javac.jsa" - printf '#!/bin/sh\nexec "%s" -J-XX:-UsePerfData -J-XX:TieredStopAtLevel=1 -J-XX:+UseSerialGC -J-XX:ActiveProcessorCount=1 "-J-XX:SharedArchiveFile=%s" "$@"\n' "$(command -v javac)" "$RUNNER_TEMP/fixture-java/javac.jsa" > "$RUNNER_TEMP/fixture-java/javac" - printf '#!/bin/sh\nexec "%s" -XX:-UsePerfData -XX:TieredStopAtLevel=1 -XX:+UseSerialGC -XX:ActiveProcessorCount=1 "$@"\n' "$(command -v java)" > "$RUNNER_TEMP/fixture-java/java" - # Apply the same startup budget to the retained javac8 compiler. - # This changes JVM scheduling only, not source targets or class bytes. - printf '#!/bin/sh\nexec "%s" -J-XX:-UsePerfData -J-XX:TieredStopAtLevel=1 -J-XX:+UseSerialGC -J-XX:ActiveProcessorCount=1 "$@"\n' "$JAVA8_JAVAC" > "$RUNNER_TEMP/fixture-java/javac8" - chmod +x "$RUNNER_TEMP/fixture-java/javac" "$RUNNER_TEMP/fixture-java/java" "$RUNNER_TEMP/fixture-java/javac8" - echo "JAVA8_JAVAC=$RUNNER_TEMP/fixture-java/javac8" >> "$GITHUB_ENV" - echo "$RUNNER_TEMP/fixture-java" >> "$GITHUB_PATH" - - name: Build - run: go build ./... - - name: Native DEX regression tests (race) - working-directory: ${{ github.workspace }} - run: | - set -o pipefail - mkdir -p artifacts - go test -json -race -count=1 -timeout=5m ./classparser/classfilebuilder ./dex2jar/... . ./cmd/javajive | tee artifacts/native-dex-race-tests.jsonl - - name: Native DEX coverage contract - working-directory: ${{ github.workspace }} - run: | - set -o pipefail - mkdir -p artifacts - go test -json -count=1 -covermode=atomic -coverpkg=./dex2jar/...,./internal/dexparser \ - -coverprofile=artifacts/dex2jar.coverprofile ./dex2jar/... ./internal/dexparser \ - | tee artifacts/dex2jar-coverage-tests.jsonl - python3 -I scripts/check_dex_coverage.py \ - --profile artifacts/dex2jar.coverprofile \ - --baseline dex2jar/coverage_baseline.json \ - --summary artifacts/dex2jar-coverage-summary.json - - name: Core algorithm and resource-guard tests (race) - run: | - set -o pipefail - mkdir -p artifacts - go test -json ./classparser/decompiler/core/... ./classparser/decompiler/rewriter/... ./internal/workbudget ./internal/jdecenv ./internal/filesys -race -count=1 -timeout=3m | tee artifacts/core-algorithm-tests.jsonl - - name: Rebuilt JAR runtime selection regression - run: | - set -o pipefail - go test -json ./test/cross -run '^(TestRebuiltJarRuntimeSelectionPreservesOriginalAuthority|TestRebuiltJarRejectsUnknownMetadataAndKeepsPlainPacking)$' -count=1 -timeout=2m | tee artifacts/rebuilt-jar-runtime-tests.jsonl - - name: Irreducible CFG semantic round trip - run: | - set -o pipefail - test "$(go test ./test/cross -list '^TestRoundTripIrreducibleCFGCorpus$' | grep -xc 'TestRoundTripIrreducibleCFGCorpus')" -eq 1 - go test -json ./test/cross -run '^TestRoundTripIrreducibleCFGCorpus$' -count=1 -timeout=3m | tee artifacts/irreducible-cfg-roundtrip-tests.jsonl - - name: Adversarial classfile decompiler evaluation - run: | - set -o pipefail - mkdir -p artifacts - JAVAJIVE_ADVERSARIAL_EVAL=1 go test -json ./test/adversarial -count=1 -timeout=5m | tee artifacts/adversarial-decompiler-tests.jsonl - - name: Complex JAR round-trip evaluation - run: | - set -o pipefail - mkdir -p artifacts - JAVAJIVE_COMPLEX_JAR_EVAL=1 go test -json ./test/complexjar -count=1 -timeout=5m | tee artifacts/complex-jar-tests.jsonl - - name: Trusted original and rebuilt algorithm round trips - run: | - evidence="$RUNNER_TEMP/algorithm-regression-evidence" - mkdir -p "$evidence" artifacts - git rev-parse HEAD > "$evidence/revision.txt" - python3 tools/curated_roundtrip/build_adapter.py --out "$RUNNER_TEMP/javajive-probe" - python3 tools/curated_roundtrip/roundtrip.py --adapter "$RUNNER_TEMP/javajive-probe" \ - --out "$evidence/roundtrip" --allow-trusted-fixture-execution --expected-rows 40 - cp -R "$evidence/." artifacts/ - - name: Curated algorithm round-trip contracts - run: python3 -m unittest tools.curated_roundtrip.test_roundtrip - - name: Runtime arithmetic corpus and public-mode regression - run: python3 -m unittest ci.task_t28.test_runtime_stack_generation - - name: Source-shard summary contract regression - run: python3 -m unittest discover -s ci/task_t29 - - name: Historical diagnostic-key regression - run: python3 -m unittest ci.task_t30.test_t30_historical_diagnostics - - name: Platform declaration and original-code generator regression - run: python3 -m unittest discover -s classparser -p 'test_jdk*generate.py' - - name: Roundtrip evidence - if: always() - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 + persist-credentials: false + - uses: actions/setup-go@40f1582b2485089dde7abd97c1529aa768e1baff with: - name: algorithm-regression-evidence - path: artifacts/ - if-no-files-found: ignore - retention-days: 7 - gate: + go-version-file: go.mod + cache: true + - run: go run ./tools/requiredci -run dex + + regression: name: Algorithm regression - needs: [scope, source, regression] + needs: [contract, corpus, algorithm, dex] if: always() runs-on: ubuntu-22.04 - timeout-minutes: 5 + timeout-minutes: 2 steps: - - name: Require every algorithm job + - name: Require every reviewed gate env: - SCOPE_RESULT: ${{ needs.scope.result }} - CLASSPARSER: ${{ needs.scope.outputs.classparser }} - SOURCE_RESULT: ${{ needs.source.result }} - REGRESSION_RESULT: ${{ needs.regression.result }} + CONTRACT_RESULT: ${{ needs.contract.result }} + CORPUS_RESULT: ${{ needs.corpus.result }} + ALGORITHM_RESULT: ${{ needs.algorithm.result }} + DEX_RESULT: ${{ needs.dex.result }} run: | - test "$SCOPE_RESULT" = success - test "$REGRESSION_RESULT" = success - case "$CLASSPARSER" in - true) test "$SOURCE_RESULT" = success ;; - false) - # A skipped matrix is the expected fast path; success is - # tolerated so a host that reports skipped legs differently - # cannot fail the required check. - case "$SOURCE_RESULT" in - skipped|success) ;; - *) echo "unexpected source result: $SOURCE_RESULT"; exit 1 ;; - esac - ;; - *) echo "missing classparser scope output"; exit 1 ;; - esac + test "$CONTRACT_RESULT" = success + test "$CORPUS_RESULT" = success + test "$ALGORITHM_RESULT" = success + test "$DEX_RESULT" = success diff --git a/.github/workflows/extended.yml b/.github/workflows/extended.yml index 0bbc6bb4..8a36cb23 100644 --- a/.github/workflows/extended.yml +++ b/.github/workflows/extended.yml @@ -25,6 +25,12 @@ jobs: with: go-version-file: go.mod cache: true + - uses: actions/setup-java@cf277c60eb25467037889841efdb72551f06f6c3 + with: + distribution: temurin + java-version: '8' + - name: Retain the Java 8 compiler profile + run: echo "JAVA8_JAVAC=$JAVA_HOME/bin/javac" >> "$GITHUB_ENV" - uses: actions/setup-java@cf277c60eb25467037889841efdb72551f06f6c3 with: distribution: temurin @@ -32,7 +38,18 @@ jobs: # Native binding tests parse complete original declarations; no JAR is executed here. - name: Prepare hash-locked original declaration families run: python3 scripts/historical_jar_audit.py prepare --cache "$HOME/.m2/repository" --manifest "$RUNNER_TEMP/native-manifest.json" - - run: go test ./... -count=1 -timeout=30m + - name: Full compiler and runtime oracle suite + run: go test ./... -count=1 -timeout=30m + - name: Adversarial and complex archive runtime oracles + run: | + JAVAJIVE_ADVERSARIAL_EVAL=1 go test ./test/adversarial -count=1 -timeout=10m + JAVAJIVE_COMPLEX_JAR_EVAL=1 go test ./test/complexjar -count=1 -timeout=10m + - name: Curated source and runtime oracles + run: | + python3 tools/curated_roundtrip/build_adapter.py --out "$RUNNER_TEMP/javajive-probe" + python3 tools/curated_roundtrip/roundtrip.py --adapter "$RUNNER_TEMP/javajive-probe" \ + --out "$RUNNER_TEMP/curated-roundtrip" --allow-trusted-fixture-execution --expected-rows 40 + python3 -m unittest ci.task_t28.test_runtime_stack_generation historical-audit: name: Historical JAR differential audit (38 targets) runs-on: ubuntu-22.04 diff --git a/CHANGELOG.md b/CHANGELOG.md index dead4a7d..36784959 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,277 @@ # Changelog +## Unreleased — 2026-11-10 + +Universal input containers across the Java archive and Android pipelines, plus +bounded failure recovery for malformed and partially unsupported inputs. + +- Harden adversarial Java ecosystem boundaries: reject JImage count and + decompression amplification before allocation, bound compact-cp reconstruction, + reject truncated AES ZIP metadata, verify zero-valued CRC fields, and cover the + cases with deterministic tests and fuzz seeds. +- Make flat and structured archive exports honor the same request context, work + budget, byte/entry limits, and multi-release target. Flat export now propagates + per-entry path/read/write failures instead of reporting success after partial + output. +- Validate classfile minor/preview policy, JVM Code length, and all constant-pool + links including unused version-gated constants before source recovery. +- Keep recovered DEX interface/annotation shells JVM-valid, preserve parameter + annotations where representable, restore annotation-interface defaults, and + bound JAR diagnostics with an explicit truncation record. +- Replace required PR JVM/compiler process matrices with sealed pure-Go algorithm, + race, coverage, and SHA-256-pinned corpus gates. Live compiler, verifier, + reflection, and behavior oracles remain in the explicit extended workflow. +- Cut required-gate startup: validate only the requested inventory group instead + of listing every package in every test job, memoize `go test -list` per package, + list packages with bounded parallelism, precompile race/coverage suites in + parallel, and run up to four package test binaries concurrently. Run the + instrumented external-APK inspect suite as concurrent race-only and + coverage-only binaries so each check keeps full coverage of its own concern. + Warm-cache times drop from ~78 s to ~17 s for algorithm, ~81 s to ~17 s for + DEX, ~44 s to ~15 s for corpus, and ~26 s to ~9 s for the full inventory + check. Test binaries remain separate processes with the same selectors, + timeouts, clean environment, sealed event checks, and fail-closed coverage + baseline. The exhaustive 797k-case stack-diagram test no longer allocates + per-case frame snapshots, cutting its allocation from ~2.4 GB to ~0.6 GB. +- Extend required stability coverage without adding Java processes: the sealed + inventory now lists `Fuzz*` targets and runs every seed corpus (classparser, + decoder audit, DEX-to-JAR, DEX input, inspect, input kind, ZIP, JImage). + Add a concurrent class decompilation under the race detector, pre-canceled and + mid-flight cancellation checks that publish no source, and cross-process + fingerprint comparison so source, diagnostics, records and hashes cannot + depend on a process-local map hash seed. Gate times remain ~26 s for + algorithm, ~15 s for corpus and ~16 s for DEX on a warm cache. +- Remove avoidable quadratic and repeated work: index Java exception starts and + graph adjacency, render with builders, reuse nested archive filesystems, populate + DEX blocks in one pass, index DEX allocations/annotations/debug locals, bound + diagnostic collection, and propagate recovery dependencies with a reverse graph. +- Rework class analysis throughput. Sparse reaching definitions now keep canonical + node-indexed immutable facts instead of converting every slot to pointer maps; + unchanged unions and non-wide overwrites allocate nothing, definition order no + longer needs sorting, and repeated queries allocate only the caller's result. + A 32-slot/32-round production benchmark drops from ~11.6 ms / 10.5 MB / 72.5k + allocations to ~2.9 ms / 1.77 MB / 1.36k. +- Replace exception-handler coverage set comparison with exact may-throw rank + intervals plus a single-span sweep. Validation at 1,024 handlers drops from + ~10.8 ms to ~0.58 ms while preserving nested/disjoint/crossing semantics, + including multi-span union crossings. +- Memoize merge-point nearest-condition discovery and reuse control-flow + validation for non-JSR methods, removing per-merge reverse walks and two of + three full opcode validation scans. Index opcode PCs and stack-operand uses for + array/constructor proofs, and make the nested-array fixpoint reuse one use index + per pass. +- Add an exact-topology statement dominator/post-dominator cache. Unchanged + topology refreshes are ~4.6x faster for dominators and ~11.2x for + post-dominators; scalar dominance queries allocate nothing. A randomized + differential test checks 10,500 topologies against fresh computation. +- Remove the remaining class-analysis allocation hot spots. The dominator tree + now reuses its map and child slices across topology epochs; loop exit BFS uses + index-based scratch storage instead of a visited map sized for the whole + reachable graph; reaching-definition unions share the incoming set when one + side is a subset; switch jump-only targets are memoized because switch tables + are analyzer-owned and never rewritten; protected loop bodies clone under one + read lock; and per-name `\bname\b` regex compiles are replaced by an exact + literal word scanner (randomized equivalence test against Go regexp). On the + 7 KB `FMParserTokenManager` class decompilation drops from ~4.45 s to ~3.81 s, + allocations from 10.75 M to 7.92 M and allocated bytes from 1.54 GB to + 1.07 GB; `FMParser` drops from ~0.75 s to ~0.59 s and loop structuring from + ~0.45 s to ~0.40 s. +- Add an ordered, conservative Compatibility rewrite scheduler. Seventeen audited + rules skip only when their own required literals are absent; applicability is + rebuilt after every accepted rewrite, SHA-256 state is carried forward, and the + full rule order, diagnostics, hashes and repeated entries are locked by tests. + A near-miss rewrite pipeline is ~11x faster with ~1290x fewer allocated bytes. +- Add an ambient-environment fast path. `jdecenv.Get` no longer parses the + goroutine stack when the queried `JDEC_*` key is absent from every active + snapshot and the process environment; the common lookup drops from ~4 µs to + ~35 ns. Keys that are actually overridden keep the full goroutine-local path. +- Eliminate cold-start platform metadata work. `java/lang/Object` metadata is a + verified static table derived from the pinned catalog, and the constructor + archive no longer decodes the 11 MB invocation catalog at runtime; catalog + consistency remains a pure-Go release test. A tiny single-class decompile drops + from ~208 ms / 38.6 MB / 354k allocations to ~7 ms / 0.16 MB / 2.6k allocations. +- Replace the per-opcode slice-index-to-offset map with a compact opcode-Id + offset slice. A large class drops from ~272 MB to ~237 MB total allocation and + `ParseOpcode` from ~100 MB to ~77 MB. Add shared scalar `SemanticCFG.Dominates` + for proof callers, and replace `circleElementSet`'s locked `utils.Set` traversal + with plain map/slice state. +- Measured T32 end-to-end changes: loop 10.4 → 4.1 ms, handler-dense 7.25 → + 3.59 ms, slot 17.3 → 6.2 ms, render 4.67 → 1.02 ms; the Fastjson large-class + seed drops from ~1.37 s to ~0.83 s. +- Repack `OpCode` from 392 to 320 bytes by grouping pointer/slice fields before + flags and removing three never-read fields. The Fastjson seed drops from + ~237 MB to ~212 MB total allocation, with `ParseOpcode` from ~77 MB to ~67 MB. +- Replace DEX reference analysis's dense `[]map[string]bool` with a sparse map of + immutable sorted descriptor sets. A fixpoint block-copy benchmark changes from + ~10.7 ms / 13.7 MB / 221k allocations to ~1.55 ms / 1.59 MB / 1.2k + allocations (about 6.9x faster, 8.6x less memory, 189x fewer allocations). +- Shrink `ir.Category` from 32 to 24 bytes by using existing alignment padding, + reducing a maximal dense category table by 25%. +- Pre-size DEX debug local/position tables within bounded hints; the 8192-local + debug parse drops from ~5.87 MB to ~5.49 MB allocation. +- Parse each DEX once during archive inspection: the multidex hierarchy and + per-class verdicts now share the same immutable `model.File` instead of + parsing every DEX twice. +- Precompute post-dominator set cardinalities once instead of recalculating a + bitset popcount for every immediate-parent candidate, changing extraction from + `O(n·candidates·words)` toward `O(n·words + n·candidates)`. +- Replace the rewrite loop's repeated `slices.Contains` membership scans over + try/if/switch/while node lists with indexed sets, removing an avoidable + `O(nodes²)` component before any rewriting work. +- Build loop reverse adjacency with one node-index map and exact-capacity + indexed slices. The `circleElementSet` allocation hotspot drops from ~30.6 MB + to ~14.0 MB in the large-class profile. +- Replace arm64's goroutine-identity fallback with the runtime `g` register. + `jdecenv.Goid` previously formatted the complete goroutine stack through + `runtime.Stack` on every ambient lookup; `ReplaceVar` alone made that 40% of + class-analysis CPU on Apple Silicon. An overridden `jdecenv.Get` drops from + ~4 µs to ~23 ns, and the FMParser regression class decompile from 4.51 s to + 1.47 s. +- Restore shielded Java literals and comments in one linear marker pass instead + of one `strings.ReplaceAll` per span. The previous loop was O(spans × source) + and accounted for 445 MB of copying in the FMParser profile. A differential + test against the sequential implementation covers duplicated, reordered, + deleted and wrapper-mangled markers, with an exact fallback for overlapping + matches. Hoist the throw-type-variable regexes out of their per-line loop. +- Cache loop bodies and loop-exit searches for the analysis-only window between + graph mutations, and let `LoopJmpRewriter` reuse the scan's answers when its + two pre-rewrites changed nothing. A 7 KB, 60-loop class drops from + 7.78 s / 4.79 GB / 38.6M allocations to 1.70 s / 635 MB / 3.55M allocations. + The cache is disabled whenever protected retry boundaries could mutate node + state, and parity with the uncached rewriter is locked by a kill-switch test + on loop-bearing class fixtures. +- Index statement dominance queries with child-to-parent links instead of a + recursive subtree walk, preserve the old walk for non-tree test maps, and + reuse the cached immediate-dominator analysis without a defensive deep copy. + Rebuild successor lists with two flat generation-stamp arrays instead of one + dedupe map per source node. `circleElementSet` reuses its index map, slices + and reverse adjacency across queries and no longer sorts every loop body. +- Linearize switch-case jump-only detection. The loop-exit and switch-merge + passes asked `switchCaseHasOnlyJumpEntries` once per case target, and every + query rebuilt the entire ordered-map key/value snapshot: O(cases²) time and + allocation. One pass now derives the per-target predicate straight from the + prepared tables. On the 117 KB FMParserTokenManager class this alone drops + decompilation from 24.8 s / 21.9 GB / 45.2M allocations to + 10.4 s / 8.7 GB / 43.0M. +- Stop the per-load slot-reaching repair search as soon as it sees the current + definition or a second distinct reaching definition; the previous backwards + BFS always explored the whole graph to prove uniqueness. Reuse a + generation-stamped visited map and queue across queries, and reuse the loop + analysis scratch even when protected-retry boundaries keep the body memo + disabled. FMParserTokenManager falls to 7.9 s / 3.65 GB / 17.7M allocations + (3.1x faster, 6.0x less memory, 2.6x fewer allocations). Differential tests + compare the one-pass switch predicate with the per-target query and the + early-exit reaching query with the map-returning oracle. +- Split loop bodies into a topology-only base set and the protected-retry + augmentation. Methods with protected ranges keep the final set uncached, but + the base traversal now survives rewrite steps: the statement snapshot diff + invalidates only loops whose dominator subtree or immediate adjacency changed, + added/removed nodes and irreducible CFGs invalidate conservatively, and a body + with no protected node shares the cached set. Bodies that do have protected + retry boundaries clone before augmenting, preserving every `ProtectedEnd` + side effect. +- Answer the per-load reaching-store repair from the sparse reaching facts + instead of another backwards BFS; the structural Source walk remains only as a + fallback when the SemanticCFG does not know the opcode. Charge visited opcodes + against `CounterGraphScans` in batches so a pathological slot-reuse method + fails closed instead of searching without bound. +- Reuse the mutable analysis graph, its edge storage and successor tables across + topology epochs, and cache the child-to-parent dominance index across rewrite + steps. `commonLoopExit` reuses generation-stamped distance maps and queues, + exclusive-terminal tests take a cached node-live predicate, and protected-body + augmentation no longer calls `Set.List`. +- FMParserTokenManager now decompiles in 4.8 s / 1.79 GB / 14.2M allocations, + down from 24.8 s / 21.9 GB / 45.2M (5.2x faster, 12.2x less memory, 3.2x fewer + allocations). FMParser, JSONReaderUTF16 and the loop-structuring fixture also + improve to ~0.78 s, ~0.91 s and ~0.47 s. New tests cover localized loop-base + invalidation and compare the dataflow reaching query with the structural walk. + +- Harden DEX IR decoding: validate switch and fill-array payload targets with + signed/`uint64` arithmetic before indexing, reject negative, wrapped, and + final-word payloads, and cap instruction×register analysis state before + allocation instead of amplifying memory from an admitted DEX. +- Add explicit DEX failure policy APIs: `DexToJarWithOptions`, + `DexFileToJarWithOptions`, and `DecompileDEXFileWithPolicy`. The existing + strict APIs remain transactional and unchanged. `--stub-methods-only` permits + verifier-safe stubs for recognized method-local capability gaps; + `--best-effort` additionally recovers class failures through fresh + declaration-preserving, reduced-metadata, and minimal shells. Dependency + recovery propagates from minimal superclasses/interfaces, and unsupported + static initializers fail closed through a throwing ``. +- Successful degradation reports `partial` with a nil error. Partial JARs carry + deterministic `META-INF/javajive/diagnostics.json`; recovered classes carry a + bounded `JavaJiveRecovery` attribute that the decompiler renders as leading + source comments. Malformed containers, whole-file validation failures, + resource limits, and internal failures still abort. +- Add `--best-effort` and `--stub-methods-only` to `dex2jar` and Android + `decompile`; the default remains strict. +- Isolate Java archive class failures: malformed and future-version class + entries become diagnostic fallback `.java` files while other classes continue. + Structured `ArchiveEntryReport` now carries `status`, `stub_methods`, and + `diagnostics`, distinguishing complete, partial, and fallback sources. + Resource/cancellation failures still terminate the request. +- Make real external-corpus and JDK/JLink integration tests explicit local + evaluations (`JAVAJIVE_EXTERNAL_EVAL=1`, + `JAVAJIVE_JIMAGE_INTEGRATION=1`). Required PR CI keeps small synthetic + container, archive-containment, DEX-policy, and no-panic regressions. +- Add `internal/inputkind`: classify inputs by content magic, then archive + structure, and only then the filename extension. Renamed APK/APKS/JMOD/AAR + files now reach the correct pipeline. +- JMOD: strip the four-byte `JM\x01\x00` prefix when opening a local archive and + when recursing into nested JMOD entries, so JDK module images decompile as + ordinary archives. +- AAR and PAR: accept both as Java archives. `classes.jar` and `libs/*.jar` in + AAR inputs are decompiled through the existing nested-archive path. +- Fix flat archive export for nested JARs. `DumpToLocalFileSystem` now resolves + raw bytes through `JarFS.ReadRawFile` and recovers the physical `.class` name + behind UnifiedFS's virtual `.java` entries. WAR `WEB-INF/lib`, EAR `EAR/lib`, + AAR `classes.jar`, fat-JAR `BOOT-INF/lib`, and arbitrary JAR-in-JAR layers + export sources instead of logging `create child node failed`. +- Android split bundles: `.apks` / `.xapk` / `.apkm` / `.apkx` walk nested + `.apk` entries, prefer `universal.apk`, skip resource-only splits, and merge + identical classes across splits. Conflicting definitions fail the conversion. +- Android App Bundles: `.aab` translates every `/dex/classes*.dex` + entry across base and feature modules. +- Add bounded nested-container limits (`MaxTotalAPKSize`, `MaxNestedAPKs`) and + global DEX count/size checks across all collected sources. The default + nested-APK bound is 512, enough for bundletool split bundles with hundreds of + resource/config APKs. +- Add a native `jimage` package for JDK 9+ runtime images (`lib/modules`, + `.jimage`): parse the header, redirect/offset tables, attribute streams, + string table, and resources on demand; inflate `zip`-compressed resources with + zlib. `JImageToJar` and `OpenJImageFile` expose the format. +- `decompile` / `DecompileArchive` convert a JImage into a package-layout JAR + view and reuse the flat or structured exporter. The new `jimage2jar` CLI + subcommand exposes the conversion directly. Class resources are exported + at package paths; `module-info.class` and non-class resources keep their + module prefix. `inspect` reports `jimage` with per-resource hashes and + compression state. +- Support `compact-cp` (constant-pool string sharing): reconstruct externalized + UTF8 and descriptor entries, including `L;` type tokens, long/double slots, + and the trailing class body. Reconstructed classes are byte-identical to the + uncompressed image. Big-endian JImages (`jlink --endian big`) are supported + too. +- Add pure-Go unit tests for compressed-index decoding and compact-cp constant + pool reconstruction, plus opt-in `jlink --compress=1` and `--endian big` + integration tests. +- Add `testdata/external` with real Tomcat WARs, bundletool APK/AAB/APKS + (universal and a 181-APK split bundle), an AndroidX AAR, Androguard/Apktool/ + dex2jar fixtures, and synthetic XAPK/APKM/EAR containers. Tests classify, + inspect, decompile, and translate every sample; malformed truncations assert + no panics. +- Add fuzz seed corpora for the input classifier, JImage and compact-cp readers, + `inspect`, and Android container parsing. +- Required CI runs small synthetic container/JImage tests and focused archive + class-containment regressions; real external samples and JLink generation are + opt-in local evaluations. +- `inspect` reports `jmod` / `jimage` / `aar` / `ear` / `par` / `apks` / + `xapk` / `apkm` / `aab`, and records nested APK or AAB module DEX provenance. +- CLI `decompile` and `dex2jar` route by detected container instead of file + extension; `--structured` now rejects Android containers with a clear error. +- Add classifier, container-parser, flat-export, JMOD/AAR/PAR, JImage, inspect, + and end-to-end JAR tests for the new inputs, including real JDK + `lib/modules` and `jlink --compress=2` images. + ## Unreleased — 2026-11-06 Complete real-application DEX translation. diff --git a/README.md b/README.md index 225aac22..20172949 100644 --- a/README.md +++ b/README.md @@ -14,9 +14,13 @@ A portable, **pure-Go** Java toolkit — extracted and trimmed from [yaklang](https://github.com/yaklang/yaklang) — focused on four things: -- **Decompile** — `.class` / `.jar` / `.war` / `.zip` → readable Java source. -- **Translate DEX** — native `.dex` / `.apk` → deterministic `.jar`, or directly - to readable Java source, without invoking an external dex2jar tool. +- **Decompile** — `.class`, Java archives (`.jar` / `.war` / `.ear` / `.aar` / + `.par` / `.jmod` / `.zip`), and JDK runtime images (`.jimage` / + `$JAVA_HOME/lib/modules`) → readable Java source, including nested JARs inside + WAR/EAR/AAR and fat JARs. +- **Translate DEX** — native `.dex` / `.apk` / `.apks` / `.xapk` / `.apkm` / + `.aab` → deterministic `.jar`, or directly to readable Java source, without + invoking an external dex2jar tool. - **Parse classes** — inspect the structure of a `.class` file (constant pool, fields, methods, version, access flags). - **(De)serialize** — parse and re-marshal the Java serialization (ObjectStream) @@ -30,8 +34,9 @@ Built for portability and embedding: capabilities; the sub-packages remain available for advanced use. - **First-class CLI** — `decompile`, `dex2jar`, `classinfo`, and `serial` subcommands, built on the standard library. -- **Cross-tested against a real JDK** — CI compiles real `.class` / `.jar` and - JDK-serialized blobs with `javac`/`java`, then verifies JavaJive against them +- **Cross-tested against a real JDK** — the manual extended oracle compiles real + `.class` / `.jar` and JDK-serialized blobs, then verifies JavaJive against them. + Required PR CI stays pure Go and consumes hash-pinned class/JAR/DEX/JImage corpora (see [HARNESS-WORKFLOW.md](HARNESS-WORKFLOW.md)). - **Trimmed dependency graph** — `utils` / `codec` / `log` / `go-funk` are reimplemented as a minimal, self-contained `internal/` core. @@ -45,8 +50,9 @@ See the [per-JAR results and reproduction](docs/historical-jar-audit.md). **250 isolated semantic round trips** record compilation, JVM verification, stubs and runtime equality separately; original application classes are absent from rebuilt -classpaths. CI runs the semantic audit on JDK 17 and 21, the full historical comparison, -and the OS/Go and race matrices. These checks do not prove equivalence of every library +classpaths. Manual extended workflows run the semantic and historical JDK audits; +required PR CI runs sealed pure-Go algorithm, race, coverage, and fixed-corpus gates. +These checks do not prove equivalence of every library method. See the [implementation and remaining boundaries](docs/decompiler-semantic-audit.md). ## Historical benchmarks (v0.3.0) @@ -108,59 +114,118 @@ Requires Go 1.22+. javajive [arguments] Commands: - decompile decompile Java artifacts or the supported DEX subset into Java source - dex2jar convert the supported DEX subset in a DEX/APK to a deterministic JAR - inspect read-only inventory and best-effort analysis of DEX/APK/JAR/WAR input + decompile decompile .class files, Java archives, JDK runtime images, or Android containers into Java source + dex2jar convert DEX/APK/APKS/XAPK/APKM/AAB input to a deterministic JAR + jimage2jar convert a JDK runtime image (lib/modules, .jimage) to a JAR view + inspect read-only inventory and best-effort analysis of Java/Android artifacts classinfo print the structure of a .class file (version, fields, methods) serial Java serialization tools (subcommands: tojson, fromjson) version print the version help show help ``` +Input is detected by content magic first, archive structure second, and the +filename extension last, so renamed artifacts keep working. + +| Input | Handling | +| --- | --- | +| `.class`, directory | one class, or recursive `.class` decompilation | +| `.jar` / `.war` / `.ear` / `.zip` | Java archive; nested `.jar`/`.war`/`.ear`/`.par`/`.jmod`/`.zip` layers are decompiled in place | +| `.aar` | Android library archive; `classes.jar` and `libs/*.jar` are decompiled | +| `.par` | Java archive (extension fallback when the ZIP has no stronger marker) | +| `.jmod` | JDK module image; the four-byte `JM\x01\x00` prefix is stripped automatically | +| `.jimage` / `$JAVA_HOME/lib/modules` | JDK 9+ runtime image; converted to a package-layout JAR view. Uncompressed, zlib `zip`, and `compact-cp` resources are supported | +| `.dex` | raw DEX | +| `.apk` | root `classes.dex`, `classes2.dex`, ... multidex entries | +| `.apks` / `.xapk` / `.apkm` / `.apkx` | nested split APKs; `universal.apk` is preferred when present | +| `.aab` | Android App Bundle; every `/dex/classes*.dex` is translated | + +`--structured` separates `sources/`, `resources/`, and byte-exact `archives/` +for Java archives. Flat and structured exports apply the same request-scoped +cancellation, byte/entry, parser-work, output, and multi-release target policy; +an entry read/path/write failure is returned instead of silently leaving a +partial destination. Android containers always produce a translated source tree. + +JImage inputs are converted to a package-layout JAR view: class resources are +exported at their package paths, while `module-info.class` and non-class +resources keep their module prefix. Uncompressed, zlib-compressed (`zip`), and +`compact-cp` (constant-pool string sharing) resources are supported, including +big-endian images. A full JDK image contains tens of thousands of classes, so +`inspect` or `JImageToJar` is a good first step. + ### inspect ```bash javajive inspect app.apk --format json +javajive inspect app.apks --format json +javajive inspect app.aab --format json javajive inspect app.war --format json +javajive inspect java.base.jmod --format json +javajive inspect --format json /path/to/jdk/lib/modules # Large applications: omit per-instruction disassembly and raw code units. javajive inspect --disassembly=false --format json app.apk ``` `inspect` never translates input or writes a JAR. It reports the artifact hash -and format, a sorted archive inventory, canonical multidex provenance, per-class -and per-method inventory, deterministic DEX disassembly, a per-class strict -translation verdict, and precise diagnostics for the first unsupported feature -of each method. This keeps real applications analyzable even when the strict -translator cannot yet convert them. +and format, a sorted archive inventory, canonical multidex provenance (including +nested APK and AAB module DEX entries), per-class and per-method inventory, +deterministic DEX disassembly, a per-class strict translation verdict, and +precise diagnostics for the first unsupported feature of each method. This keeps +real applications analyzable even when the strict translator cannot yet convert +them. ### decompile ```bash # Single class: prints to stdout by default, or -o to write a file. javajive decompile Foo.class -javajive decompile Foo.class -o Foo.java +javajive decompile -o Foo.java Foo.class # Archive: defaults to a ".src" directory, or -o to choose one. javajive decompile app.jar -javajive decompile app.war -o ./app-src +javajive decompile -o ./app-src app.war # Structured archive export: sources/, resources/, and preserved nested -# archives/ (WEB-INF/lib and EAR/lib jars are decompiled in place). -javajive decompile app.war --structured -o ./app-src +# archives/ (WEB-INF/lib, EAR/lib, AAR classes.jar and fat-JAR libraries +# are decompiled in place). +javajive decompile --structured -o ./app-src app.war + +# Archive classes are isolated: a malformed or future-version class becomes a +# diagnostic fallback .java entry while the remaining classes continue. The +# structured report marks each class complete, partial, or fallback and carries +# stub-method and diagnostic details. + +# AAR and JMOD are ordinary archives once the container is identified. +javajive decompile -o ./aar-src library.aar +javajive decompile -o ./jmod-src java.base.jmod + +# JDK runtime image: classes are exported at package paths; module-info.class +# and non-class resources keep their module prefix. +javajive decompile -o ./jdk-src /path/to/jdk/lib/modules -# DEX or APK: run the native DEX-to-JAR pipeline and decompile the result. -# The default output directory is ".src". +# DEX or Android container: run the native DEX-to-JAR pipeline and decompile +# the result. The default output directory is ".src". javajive decompile classes.dex -javajive decompile app.apk -o ./app-src +javajive decompile -o ./app-src app.apk +javajive decompile -o ./app-src app.apks +javajive decompile -o ./app-src app.xapk +javajive decompile -o ./app-src app.aab + +# Full recovery: stub unsupported methods first, then emit traceable class +# shells for otherwise valid classes that still cannot be lowered. +javajive decompile --best-effort -o ./app-src app.apk + +# Narrow recovery: only recognized method-local capability gaps become stubs. +javajive decompile --stub-methods-only -o ./app-src app.apk # Directory: recursively decompile .class files (requires -o output dir). -javajive decompile ./classes -o ./src +javajive decompile -o ./src ./classes # Very large generated methods: opt into a higher per-method analysis budget. # Values above 1,000,000 also scale graph/scan caps. -javajive decompile Big.class -analysis-budget 2000000 -javajive decompile app.jar -o ./app-src -analysis-budget 2000000 +javajive decompile -analysis-budget 2000000 Big.class +javajive decompile -analysis-budget 2000000 -o ./app-src app.jar ``` ### dex2jar @@ -168,12 +233,46 @@ javajive decompile app.jar -o ./app-src -analysis-budget 2000000 ```bash javajive dex2jar -o classes.jar classes.dex javajive dex2jar -o app.jar app.apk +javajive dex2jar -o app.jar app.apks +javajive dex2jar -o app.jar app.aab + +# Full class-level recovery. +javajive dex2jar --best-effort -o app.jar app.apk + +# Only recognized unsupported methods throw from a stub. +javajive dex2jar --stub-methods-only -o app.jar app.apk +``` + +### jimage2jar + +```bash +# Convert a JDK 9+ runtime image to a package-layout JAR view without +# decompiling every class. +javajive jimage2jar -o jdk.jar /path/to/jdk/lib/modules ``` Input is detected by magic rather than the filename extension. Output is a -reproducible JAR. `dex2jar` fails the complete conversion on any unsupported or -malformed class or method; it writes a same-directory temporary file before -replacing the destination and never substitutes method stubs. +reproducible JAR. The default conversion is strict and transactional: it fails +on any unsupported or malformed class or method, and never emits a JAR for that +input. `--stub-methods-only` replaces only recognized method-local capability +gaps with verifier-safe `UnsupportedOperationException` stubs. `--best-effort` +includes those stubs and, when an otherwise valid class still cannot be lowered, +emits a fresh declaration-preserving class shell; reduced-metadata and minimal +shells are later fallback tiers. A minimal superclass/interface also causes its +dependents to become shells. Unsupported static initializers are replaced by a +throwing `` rather than silently exposing null/zero values. + +A degraded conversion succeeds with a nil API error and CLI exit code zero, and +is reported as `partial`; `complete` means no recorded degradation. Every +partial JAR contains deterministic `META-INF/javajive/diagnostics.json`. +Class-shell recovery also embeds a bounded, versioned `JavaJiveRecovery` class +attribute. Decompiling that class renders valid records as leading +`// javajive recovery: ...` comments. Diagnostics are field-, record-, and +payload-bounded; an explicit `diagnostics.truncated` record reports omitted +detail while summary counters retain the degradation total. Partial output is not a claim of semantic +equivalence. Malformed containers, whole-file validation failures, unknown +formats, resource limits, and internal failures still abort. All modes write a +same-directory temporary file before replacing the destination. ### Native DEX/APK support boundary @@ -199,12 +298,43 @@ hierarchy declared in the same DEX; a relation whose expected type is outside the application is accepted, because the platform hierarchy the input was verified against is not part of the DEX. -Still unsupported: `filled-new-array` of wide or floating elements; DEX 038+ -dynamic invokes and method constants; CompactDex; and APK resources or native -libraries. APK input -means only canonically named `classes.dex`, `classes2.dex`, ... entries are -translated. All selected DEX files must succeed transactionally or no JAR is -produced; use `inspect` to analyze inputs that cross the strict boundary. +Still unsupported as translated bodies: `filled-new-array` of wide or floating +elements; DEX 038+ dynamic invokes and method constants; CompactDex; and APK +resources or native libraries. With `--stub-methods-only`, methods whose only +blocker is a recognized opcode/representation gap become explicit throwing +stubs. `--best-effort` additionally recovers class-local lowering and emission +failures through documented class shells. Container corruption, DEX +header/table/verifier errors, unsupported DEX versions or unparsed sections, +resource limits, and internal errors are never hidden by a shell. + +Android container handling is structural: + +- `.apk` input translates only canonically named `classes.dex`, + `classes2.dex`, ... entries at the archive root. +- `.apks` / `.xapk` / `.apkm` / `.apkx` input walks nested `.apk` entries. A + `universal.apk` is preferred when present; resource-only split APKs are + skipped. Identical classes repeated across splits are collapsed, while + conflicting definitions fail the conversion. +- `.aab` input translates every `/dex/classes*.dex` entry across + `base` and feature modules. + +In strict mode all selected DEX files must succeed transactionally or no JAR is +produced. Recovery modes may emit a traceable partial JAR after container parsing +and whole-file validation succeed; use `inspect` for inputs that fail those +boundaries. + +Container bounds default to 256 MB per DEX, 512 MB per archive/APK, 512 MB of +total DEX data, 128 DEX files, 512 nested APKs, and 2 GB of total nested APK +data. `DexOptions` fields raise these limits for larger bundles. + +The container corpus under [`testdata/external`](testdata/external/README.md) +contains Tomcat WARs, bundletool APK/AAB/APKS bundles (including a 181-APK split +bundle), an AndroidX AAR, Androguard/Apktool/dex2jar fixtures, and synthetic +XAPK/APKM/EAR containers. These large real-world runs are explicit local +evaluations (`JAVAJIVE_EXTERNAL_EVAL=1`), not part of the default PR CI. +Ordinary CI keeps small synthetic container and no-panic regressions. Fuzz seed +corpora cover the classifier, JImage and compact-cp readers, `inspect`, and +Android container parsing. ### classinfo @@ -249,8 +379,8 @@ import ( "github.com/yaklang/javajive" ) -// Translate DEX or APK bytes in memory. -jarBytes, report, err := javajive.DexToJar(dexOrAPKBytes, javajive.DexOptions{}) +// Translate DEX/APK/APKS/XAPK/APKM/AAB bytes in memory. +jarBytes, report, err := javajive.DexToJar(dexOrContainerBytes, javajive.DexOptions{}) if err == nil { err = os.WriteFile("app.jar", jarBytes, 0o644) _ = report.Classes @@ -262,9 +392,20 @@ report, err = javajive.DexFileToJar("app.apk", "app.jar", javajive.DexOptions{}) // Translate through a private temporary JAR and decompile directly to source. err = javajive.DecompileDEXFile("classes.dex", "app-src", javajive.DexOptions{}) -// Decompile a single class, or a whole Java archive into a directory. +// Decompile a single class, a Java archive, or a JDK runtime image. src, err := javajive.Decompile(classBytes) err = javajive.DecompileArchive("app.jar", "app-src") +err = javajive.DecompileArchive("/path/to/jdk/lib/modules", "jdk-src") + +// Convert a JDK runtime image to a JAR view, or read one resource directly. +err = javajive.JImageToJar("/path/to/jdk/lib/modules", "jdk.jar") +image, err := javajive.OpenJImageFile("/path/to/jdk/lib/modules") +if err == nil { + objectClass, readErr := image.Read("java.base/java/lang/Object.class") + _ = objectClass + _ = readErr + _ = image.Close() +} // Inspect class structure. obj, err := javajive.ParseClass(classBytes) @@ -284,12 +425,19 @@ out := javajive.MarshalSerialized(restored...) | `Decompile(classBytes) (string, error)` | Decompile one `.class`'s bytes | | `DecompileFile(path) (string, error)` | Decompile one `.class` from disk | | `DecompileWithResolver(classBytes, resolve)` | Decompile with a class-bytes resolver | -| `DecompileArchive(src, dst) error` | Decompile a `.jar`/`.war`/`.zip` into a directory | -| `DecompileArchiveWithAnalysisBudget(src, dst, budget) error` | Archive decompilation with an explicit per-method analysis budget | -| `DexToJar(input, options) ([]byte, DexReport, error)` | Convert DEX/APK bytes to a deterministic JAR | -| `DexFileToJar(src, dst, options) (DexReport, error)` | Convert a DEX/APK file using a same-directory temporary JAR | -| `DecompileDEXFile(src, dst, options) error` | Convert DEX/APK through a private temporary JAR and decompile it | -| `DecompileDEXFileWithAnalysisBudget(src, dst, options, budget) error` | DEX/APK conversion plus budgeted archive decompilation | +| `DecompileArchive(src, dst) error` | Decompile a Java archive or JDK runtime image into a directory | +| `DecompileArchiveWithAnalysisBudget(src, dst, budget) error` | Archive/JImage decompilation with an explicit per-method analysis budget | +| `JImageToJar(src, dst) error` | Convert a JDK runtime image to a deterministic JAR view | +| `OpenJImageFile(path) (*JImageReader, error)` | Open a JDK runtime image for direct resource access | +| `ClassifyInput(data, name) ContainerKind` | Classify bytes by magic, archive structure, then extension | +| `ClassifyInputFile(path) (ContainerKind, error)` | Classify a file without loading the whole archive | +| `DexToJar(input, options) ([]byte, DexReport, error)` | Strict DEX/APK/APKS/XAPK/APKM/AAB conversion to a deterministic JAR | +| `DexToJarWithOptions(input, convertOptions) ([]byte, DexDetailedReport, error)` | Explicit strict or best-effort conversion with stub diagnostics | +| `DexFileToJar(src, dst, options) (DexReport, error)` | Strict file conversion using an atomic temporary JAR | +| `DexFileToJarWithOptions(src, dst, convertOptions) (DexDetailedReport, error)` | Policy-aware file conversion with atomic replacement | +| `DecompileDEXFile(src, dst, options) error` | Convert DEX/Android container through a private temporary JAR and decompile it | +| `DecompileDEXFileWithAnalysisBudget(src, dst, options, budget) error` | DEX/Android container conversion plus budgeted archive decompilation | +| `DecompileDEXFileWithPolicy(src, dst, convertOptions, budget) (DexDetailedReport, error)` | Policy-aware DEX/Android conversion and decompilation | | `ParseClass(classBytes) (*ClassObject, error)` | Parse one `.class`'s bytes | | `ParseClassFile(path) (*ClassObject, error)` | Parse one `.class` from disk | | `ParseSerialized(raw) ([]JavaSerializable, error)` | Parse a serialization stream | @@ -324,6 +472,10 @@ Third-party dependencies are confined to a small set of pure-Go libraries go test ./... # unit tests + JDK cross-tests (skipped if no JDK) go test ./... -race # data-race free (linux) go test ./test/cross/ -v # Java cross-tests only (needs javac/java on PATH) + +# Explicit large/real-world evaluations (not part of default PR CI): +JAVAJIVE_EXTERNAL_EVAL=1 go test ./test/external +JAVAJIVE_JIMAGE_INTEGRATION=1 go test ./jimage ./test/external ``` The JDK cross-tests compile real Java artifacts at test time and verify them diff --git a/README.zh-CN.md b/README.zh-CN.md index 59d2953a..b0582383 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -14,9 +14,11 @@ 便携、**纯 Go** 的 Java 工具链——从 [yaklang](https://github.com/yaklang/yaklang) 抽取并裁剪而来,专注四件事: -- **反编译**:`.class` / `.jar` / `.war` / `.zip` → 可读的 Java 源码。 -- **DEX 转换**:原生将 `.dex` / `.apk` 转为确定性 `.jar`,或直接输出可读 Java 源码, - 无需调用外部 dex2jar 工具。 +- **反编译**:`.class`、Java 归档(`.jar` / `.war` / `.ear` / `.aar` / `.par` / + `.jmod` / `.zip`)与 JDK 运行时镜像(`.jimage` / `$JAVA_HOME/lib/modules`) + → 可读 Java 源码,包括 WAR/EAR/AAR 与 fat JAR 内的嵌套 JAR。 +- **DEX 转换**:原生将 `.dex` / `.apk` / `.apks` / `.xapk` / `.apkm` / `.aab` + 转为确定性 `.jar`,或直接输出可读 Java 源码,无需调用外部 dex2jar 工具。 - **Class 解析**:解析 class 文件结构(常量池、字段、方法、版本、访问标志)。 - **序列化**:以字节级保真解析与重组 Java 序列化(ObjectStream)二进制,并可与 JSON 互转。 @@ -27,8 +29,9 @@ - **一个 import**:统一门面包 `javajive` 聚合四类能力;子包仍可用于高级用法。 - **一流的命令行**:`decompile`、`dex2jar`、`classinfo`、`serial` 子命令, 基于标准库实现。 -- **与真实 JDK 交叉测试**:CI 用 `javac`/`java` 编译真实 `.class` / `.jar` 与 JDK 序列化字节, - 再用 JavaJive 验证(见 [HARNESS-WORKFLOW.md](HARNESS-WORKFLOW.md))。 +- **与真实 JDK 交叉测试**:手动 extended oracle 用真实 JDK 编译 `.class` / `.jar` 与 + JDK 序列化字节并验证 JavaJive;required PR CI 保持纯 Go,只消费 SHA-256 固定的 + class/JAR/DEX/JImage 语料(见 [HARNESS-WORKFLOW.md](HARNESS-WORKFLOW.md))。 - **收敛的依赖图**:`utils` / `codec` / `log` / `go-funk` 被重写为 `internal/` 下最小自包含实现。 ## v0.4.0 验证 @@ -38,8 +41,9 @@ 详见[逐包结果及复现方法](docs/historical-jar-audit.md)。 **250 项隔离语义往返**分别记录编译、JVM 校验、stub 与运行结果一致性,重建类路径不含 -原始应用类。CI 在 JDK 17、21 重跑语义测试,并执行全量历史对比、OS/Go 矩阵及 race 语料。 -这些检查不证明全部库方法行为等价;完整说明见[实现与剩余边界](docs/decompiler-semantic-audit.md)。 +原始应用类。手动 extended workflow 运行 JDK 语义与历史审计;required PR CI 运行封闭的 +纯 Go 算法、race、coverage 和固定语料门禁。这些检查不证明全部库方法行为等价;完整说明见 +[实现与剩余边界](docs/decompiler-semantic-audit.md)。 ## 历史评测(v0.3.0) @@ -91,37 +95,90 @@ go build -o javajive ./cmd/javajive javajive [arguments] Commands: - decompile 反编译 .class/.jar/.war/.zip/.dex/.apk 或目录为 Java 源码 - dex2jar 将 DEX 或 APK 转为确定性 JAR + decompile 反编译 .class、Java 归档、JDK 运行时镜像、DEX/APK/APKS/XAPK/APKM/AAB 或目录为 Java 源码 + dex2jar 将 DEX/APK/APKS/XAPK/APKM/AAB 转为确定性 JAR + jimage2jar 将 JDK 运行时镜像(lib/modules、.jimage)转为 JAR 视图 + inspect 只读盘点 Java 归档与 Android 容器 classinfo 打印 .class 文件结构(版本、字段、方法) serial Java 序列化工具(子命令:tojson、fromjson) version 打印版本 help 显示帮助 ``` +输入先按内容魔数识别,其次按归档结构,最后才回退到扩展名;因此改名后的文件仍可处理。 + +| 输入 | 处理方式 | +| --- | --- | +| `.class`、目录 | 单 class,或递归反编译目录中的 `.class` | +| `.jar` / `.war` / `.ear` / `.zip` | Java 归档;嵌套的 `.jar`/`.war`/`.ear`/`.par`/`.jmod`/`.zip` 会就地反编译 | +| `.aar` | Android 库归档;`classes.jar` 与 `libs/*.jar` 会反编译 | +| `.par` | Java 归档(ZIP 无更强标记时按扩展名回退) | +| `.jmod` | JDK 模块镜像;自动剥离 4 字节 `JM\x01\x00` 头 | +| `.jimage` / `$JAVA_HOME/lib/modules` | JDK 9+ 运行时镜像;转换为 package-layout 的 JAR 视图。支持未压缩、zlib `zip` 与 `compact-cp` 资源 | +| `.dex` | 裸 DEX | +| `.apk` | 根目录的 `classes.dex`、`classes2.dex`…… multidex 条目 | +| `.apks` / `.xapk` / `.apkm` / `.apkx` | 嵌套 split APK;存在 `universal.apk` 时优先使用 | +| `.aab` | Android App Bundle;翻译每个 `/dex/classes*.dex` | + +`--structured` 会把 Java 归档拆成 `sources/`、`resources/` 与逐字节保留的 `archives/`。 +flat 与 structured 导出共享同一套请求级取消、字节/条目、parser work、输出和 +multi-release target 策略;单个条目的读取、路径或写入失败会返回错误,不会留下部分 +产物却报告成功。 +Android 容器始终输出翻译后的源码树。 + +JImage 会先转换为 package-layout 的 JAR 视图:class 资源按 package 路径导出, +`module-info.class` 与非 class 资源保留模块前缀。支持未压缩、zlib(`zip`)与 +`compact-cp`(常量池字符串共享)资源,也支持 big-endian 镜像。完整 JDK 镜像包含 +数万个 class,建议先用 `inspect` 或 `JImageToJar`。 + ### decompile ```bash # 单个 class:默认输出到 stdout,可用 -o 写文件 javajive decompile Foo.class -javajive decompile Foo.class -o Foo.java +javajive decompile -o Foo.java Foo.class # 归档:默认输出到 "<输入>.src" 目录,可用 -o 指定 javajive decompile app.jar -javajive decompile app.war -o ./app-src +javajive decompile -o ./app-src app.war + +# 结构化归档导出:sources/、resources/ 与保留原字节的 archives/ +# (WEB-INF/lib、EAR/lib、AAR classes.jar 与 fat-JAR 依赖都会就地反编译) +javajive decompile --structured -o ./app-src app.war + +# 归档内 class 相互隔离:畸形 class 或未来版本 class 会生成带诊断的 fallback +# .java 条目,其余 class 继续导出。structured 报告会标记每个 class 为 +# complete / partial / fallback,并携带 stub 方法与诊断信息。 + +# AAR 与 JMOD 识别后按普通归档处理 +javajive decompile -o ./aar-src library.aar +javajive decompile -o ./jmod-src java.base.jmod + +# JDK 运行时镜像:class 按 package 路径导出; +# module-info.class 与非 class 资源保留模块前缀 +javajive decompile -o ./jdk-src /path/to/jdk/lib/modules -# DEX 或 APK:使用原生 DEX-to-JAR 流程,再反编译结果 +# DEX 或 Android 容器:使用原生 DEX-to-JAR 流程,再反编译结果 # 默认输出目录为「<输入>.src」 javajive decompile classes.dex -javajive decompile app.apk -o ./app-src +javajive decompile -o ./app-src app.apk +javajive decompile -o ./app-src app.apks +javajive decompile -o ./app-src app.xapk +javajive decompile -o ./app-src app.aab + +# 完整恢复:先 stub 不支持的方法,再为仍无法 lower 的有效 class 输出可追踪 shell。 +javajive decompile --best-effort -o ./app-src app.apk + +# 窄恢复:仅将已识别的方法级能力缺口替换为抛异常 stub。 +javajive decompile --stub-methods-only -o ./app-src app.apk # 目录:递归反编译其中的 .class(必须用 -o 指定输出目录) -javajive decompile ./classes -o ./src +javajive decompile -o ./src ./classes # 超大生成方法:显式提高单方法分析预算。 # 大于 1,000,000 的取值同时按比例放大图/扫描上限。 -javajive decompile Big.class -analysis-budget 2000000 -javajive decompile app.jar -o ./app-src -analysis-budget 2000000 +javajive decompile -analysis-budget 2000000 Big.class +javajive decompile -analysis-budget 2000000 -o ./app-src app.jar ``` ### dex2jar @@ -129,23 +186,76 @@ javajive decompile app.jar -o ./app-src -analysis-budget 2000000 ```bash javajive dex2jar -o classes.jar classes.dex javajive dex2jar -o app.jar app.apk +javajive dex2jar -o app.jar app.apks +javajive dex2jar -o app.jar app.aab + +# 完整 class 级恢复 +javajive dex2jar --best-effort -o app.jar app.apk + +# 仅 stub 已识别的不支持方法 +javajive dex2jar --stub-methods-only -o app.jar app.apk ``` -输入类型按文件魔数而非扩展名识别,输出为可复现的 JAR。任一 class 或方法不受支持、 -或输入损坏时,`dex2jar` 会让整个转换失败;它会先写入目标目录中的临时文件,再替换 -目标文件,并且不会用方法 stub 代替失败内容。 +### jimage2jar -### 原生 DEX/APK 支持边界 +```bash +# 将 JDK 9+ 运行时镜像转换为 package-layout 的 JAR 视图,不反编译全部 class +javajive jimage2jar -o jdk.jar /path/to/jdk/lib/modules +``` -当前原生 DEX 转换只是一个**严格的首个垂直切片**,并非通用 Android 应用转换器。 -已测试范围为标准 DEX 035:普通 int/引用控制流、字段与 invoke、安全配对的 -`new-instance`/构造器初始化,以及基础数组。生成的 class 会经过解析测试与 JVM 校验, -其中包括可执行的分支、字段、调用、构造器和 `int[]` 路径。 +输入类型按文件魔数而非扩展名识别,输出为可复现的 JAR。默认转换严格且事务性: +任一 class 或方法不受支持、或输入损坏时,整次转换失败且不产出 JAR。 +`--stub-methods-only` 仅将已识别的方法级能力缺口替换为 verifier-safe 的 +`UnsupportedOperationException` stub。`--best-effort` 在此基础上,对仍无法 lower +的有效 class 使用全新 builder 输出保留声明的 shell;必要时继续退化为精简元数据或 +最小 shell。若 superclass/interface 只能生成最小 shell,其依赖 class 也会递归降级。 +无法可信表示的静态初始化值会替换或合成抛异常 ``,不会静默暴露 null/0。 + +部分成功返回 nil error、CLI 退出码为 0,状态为 `partial`;`complete` 表示没有降级。 +部分 JAR 包含确定性的 `META-INF/javajive/diagnostics.json`;class 恢复还会写入受限、 +版本化的 `JavaJiveRecovery` 属性,反编译后显示为开头的 +`// javajive recovery: ...` 注释。诊断字段、记录数与总 payload 均有上限;若明细被 +截断会保留显式 `diagnostics.truncated` 记录,而 summary 仍保留真实降级总数。部分产物不代表语义等价。容器损坏、whole-file +校验失败、未知格式、资源超限和内部错误仍然终止。所有模式都先写同目录临时文件, +再原子替换目标文件。 + +### 原生 DEX/APK 支持边界 -暂不支持:try/catch 与 monitor 操作;float、long、double 值或操作码;switch、payload -指令及 filled array;DEX 038+ 动态调用与方法常量;annotation 与 debug 元数据; -CompactDex;以及 APK 资源或原生库。APK 支持仅表示转换规范命名的 `classes.dex`、 -`classes2.dex`……条目。所有选中的 DEX 必须事务性地全部成功,否则不生成 JAR。 +原生 DEX 转换仍是**严格的垂直切片**,并非通用 Android 应用转换器。已测试范围覆盖 +DEX 035、037、038、039 中 `map_list` 证明不含 call-site、method-handle 或 +hidden-API 段的输入,包括 annotation、debug 元数据、`SourceFile`、普通 +int/引用控制流、字段与 invoke、`new-instance`/构造器配对、数组与 filled-array +字面量、`packed-switch`/`sparse-switch`、monitor、try/catch、long/float/double +以及带 static/default 方法的接口。生成 class 会经过解析测试与 JVM 校验。 + +暂不支持作为方法体翻译:wide/float 元素的 `filled-new-array`;DEX 038+ 动态调用与 +方法常量;CompactDex;APK 资源或原生库。使用 `--stub-methods-only` 时,仅因已识别 +opcode/表示能力缺口而无法翻译的方法会变成显式抛异常 stub;`--best-effort` 还会用 +带诊断的 class shell 恢复 class-local lowering/发射失败。容器损坏、DEX +header/table/verifier 错误、未支持版本或未解析 section、资源超限与内部错误永远 +不会被 shell 掩盖。 + +Android 容器的处理规则: + +- `.apk` 只翻译根目录规范命名的 `classes.dex`、`classes2.dex`……条目。 +- `.apks` / `.xapk` / `.apkm` / `.apkx` 会遍历嵌套 `.apk`;存在 `universal.apk` + 时优先使用,无 DEX 的资源型 split 会跳过。跨 split 完全相同的 class 会合并, + 定义冲突则整个转换失败。 +- `.aab` 会翻译 `base` 与各 feature 模块中的每个 `/dex/classes*.dex`。 + +严格模式下,所有选中的 DEX 必须事务性地全部成功,否则不生成 JAR。恢复模式可在 +容器解析与 whole-file 校验成功后生成可追踪的 partial JAR;跨越这些边界的输入可先用 +`inspect` 分析。 + +容器默认上限:单个 DEX 256 MB、单个归档/APK 512 MB、DEX 总量 512 MB、128 个 DEX、 +512 个嵌套 APK、嵌套 APK 总量 2 GB。更大的包可通过 `DexOptions` 字段提高上限。 + +[`testdata/external`](testdata/external/README.md) 下的真实样本包括 Tomcat WAR、 +bundletool APK/AAB/APKS(含 181 个嵌套 APK 的 split 包)、AndroidX AAR、 +Androguard/Apktool/dex2jar 样本,以及合成的 XAPK/APKM/EAR。这些真实世界大样本 +测试属于显式本地评测(`JAVAJIVE_EXTERNAL_EVAL=1`),不进入默认 PR CI;普通 CI +只保留小型合成容器回归与 no-panic 检查。Fuzz 种子覆盖分类器、 +JImage/compact-cp 读取、`inspect` 与 Android 容器解析。 ### classinfo @@ -190,8 +300,8 @@ import ( "github.com/yaklang/javajive" ) -// 在内存中转换 DEX 或 APK 字节 -jarBytes, report, err := javajive.DexToJar(dexOrAPKBytes, javajive.DexOptions{}) +// 在内存中转换 DEX/APK/APKS/XAPK/APKM/AAB 字节 +jarBytes, report, err := javajive.DexToJar(dexOrContainerBytes, javajive.DexOptions{}) if err == nil { err = os.WriteFile("app.jar", jarBytes, 0o644) _ = report.Classes @@ -203,9 +313,20 @@ report, err = javajive.DexFileToJar("app.apk", "app.jar", javajive.DexOptions{}) // 经私有临时 JAR 转换,并直接反编译到源码目录 err = javajive.DecompileDEXFile("classes.dex", "app-src", javajive.DexOptions{}) -// 反编译单个 class,或把整个 Java 归档反编译到目录 +// 反编译单个 class、Java 归档或 JDK 运行时镜像 src, err := javajive.Decompile(classBytes) err = javajive.DecompileArchive("app.jar", "app-src") +err = javajive.DecompileArchive("/path/to/jdk/lib/modules", "jdk-src") + +// 将 JDK 运行时镜像转换为 JAR 视图,或直接读取单个资源 +err = javajive.JImageToJar("/path/to/jdk/lib/modules", "jdk.jar") +image, err := javajive.OpenJImageFile("/path/to/jdk/lib/modules") +if err == nil { + objectClass, readErr := image.Read("java.base/java/lang/Object.class") + _ = objectClass + _ = readErr + _ = image.Close() +} // 解析 class 结构 obj, err := javajive.ParseClass(classBytes) @@ -225,12 +346,19 @@ out := javajive.MarshalSerialized(restored...) | `Decompile(classBytes) (string, error)` | 反编译单个 `.class` 字节 | | `DecompileFile(path) (string, error)` | 从磁盘反编译单个 `.class` | | `DecompileWithResolver(classBytes, resolve)` | 带「类字节解析器」的反编译 | -| `DecompileArchive(src, dst) error` | 将 `.jar`/`.war`/`.zip` 反编译到目录 | -| `DecompileArchiveWithAnalysisBudget(src, dst, budget) error` | 带显式单方法分析预算的归档反编译 | -| `DexToJar(input, options) ([]byte, DexReport, error)` | 将 DEX/APK 字节转为确定性 JAR | -| `DexFileToJar(src, dst, options) (DexReport, error)` | 使用目标目录中的临时文件转换 DEX/APK | -| `DecompileDEXFile(src, dst, options) error` | 经私有临时 JAR 转换并反编译 DEX/APK | -| `DecompileDEXFileWithAnalysisBudget(src, dst, options, budget) error` | DEX/APK 转换并带预算反编译归档 | +| `DecompileArchive(src, dst) error` | 将 Java 归档或 JDK 运行时镜像反编译到目录 | +| `DecompileArchiveWithAnalysisBudget(src, dst, budget) error` | 带显式单方法分析预算的归档/JImage 反编译 | +| `JImageToJar(src, dst) error` | 将 JDK 运行时镜像转换为确定性 JAR 视图 | +| `OpenJImageFile(path) (*JImageReader, error)` | 打开 JDK 运行时镜像并直接读取资源 | +| `ClassifyInput(data, name) ContainerKind` | 按 magic、归档结构、扩展名分类输入 | +| `ClassifyInputFile(path) (ContainerKind, error)` | 不加载整个归档即可分类文件 | +| `DexToJar(input, options) ([]byte, DexReport, error)` | 严格转换 DEX/APK/APKS/XAPK/APKM/AAB 为确定性 JAR | +| `DexToJarWithOptions(input, convertOptions) ([]byte, DexDetailedReport, error)` | 显式 strict/best-effort 转换并返回 stub 诊断 | +| `DexFileToJar(src, dst, options) (DexReport, error)` | 严格转换文件并使用原子临时 JAR | +| `DexFileToJarWithOptions(src, dst, convertOptions) (DexDetailedReport, error)` | 带策略的文件转换与原子替换 | +| `DecompileDEXFile(src, dst, options) error` | 经私有临时 JAR 转换并反编译 DEX/Android 容器 | +| `DecompileDEXFileWithAnalysisBudget(src, dst, options, budget) error` | DEX/Android 容器转换并带预算反编译归档 | +| `DecompileDEXFileWithPolicy(src, dst, convertOptions, budget) (DexDetailedReport, error)` | 带策略的 DEX/Android 转换与反编译 | | `ParseClass(classBytes) (*ClassObject, error)` | 解析单个 `.class` 字节 | | `ParseClassFile(path) (*ClassObject, error)` | 从磁盘解析单个 `.class` | | `ParseSerialized(raw) ([]JavaSerializable, error)` | 解析序列化流 | @@ -263,6 +391,10 @@ out := javajive.MarshalSerialized(restored...) go test ./... # 单元测试 + JDK 交叉测试(无 JDK 时自动跳过) go test ./... -race # 无数据竞争(linux) go test ./test/cross/ -v # 仅 Java 交叉测试(需 PATH 上有 javac/java) + +# 显式真实大语料/JImage 集成评测(默认 PR CI 不跑) +JAVAJIVE_EXTERNAL_EVAL=1 go test ./test/external +JAVAJIVE_JIMAGE_INTEGRATION=1 go test ./jimage ./test/external ``` JDK 交叉测试会在测试时编译真实 Java 产物并用 JavaJive 验证;无 JDK 时自动 `t.Skip`。 diff --git a/ci/requiredci/cancellation_test.go b/ci/requiredci/cancellation_test.go new file mode 100644 index 00000000..35cd2172 --- /dev/null +++ b/ci/requiredci/cancellation_test.go @@ -0,0 +1,69 @@ +package requiredci_test + +import ( + "context" + "errors" + "os" + "path/filepath" + "testing" + "time" + + classparser "github.com/yaklang/javajive/classparser" +) + +func cancellationOptions(ctx context.Context) classparser.DecompileOptions { + return classparser.DecompileOptions{ + Mode: classparser.Precision, + Context: ctx, + Limits: classparser.Limits{ + MaxInputBytes: 1 << 20, + MaxReadBytes: 2 << 20, + MaxParseItems: 1 << 16, + MaxOutputBytes: 2 << 20, + MaxDiagnostics: 64, + MaxRequestWork: 4 << 20, + }, + EnvSnapshot: map[string]string{}, + } +} + +func readCancellationFixture(t *testing.T, name string) []byte { + t.Helper() + data, err := os.ReadFile(filepath.Join("..", "..", "classparser", "testdata", "regression", name)) + if err != nil { + t.Fatal(err) + } + return data +} + +// A canceled request must abort without publishing partial source, and the +// cancellation class must survive the work-budget wrapper. +func TestDecompileCancellationFailsClosed(t *testing.T) { + for _, name := range []string{"FMParser.class", "nondeterministic_loop_structuring.class"} { + data := readCancellationFixture(t, name) + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + result, err := classparser.DecompileWithOptions(data, cancellationOptions(ctx)) + if !errors.Is(err, context.Canceled) { + t.Fatalf("%s pre-canceled: err=%v status=%s", name, err, result.Status) + } + if result.Source != "" { + t.Fatalf("%s pre-canceled: published %d source bytes", name, len(result.Source)) + } + + ctx, cancel = context.WithCancel(context.Background()) + go func() { + time.Sleep(time.Millisecond) + cancel() + }() + result, err = classparser.DecompileWithOptions(data, cancellationOptions(ctx)) + cancel() + if !errors.Is(err, context.Canceled) { + t.Fatalf("%s mid-flight: err=%v status=%s", name, err, result.Status) + } + if result.Source != "" { + t.Fatalf("%s mid-flight: published %d source bytes", name, len(result.Source)) + } + } +} diff --git a/ci/requiredci/concurrency_test.go b/ci/requiredci/concurrency_test.go new file mode 100644 index 00000000..f5395545 --- /dev/null +++ b/ci/requiredci/concurrency_test.go @@ -0,0 +1,98 @@ +package requiredci_test + +import ( + "context" + "encoding/json" + "fmt" + "os" + "path/filepath" + "sync" + "testing" + + classparser "github.com/yaklang/javajive/classparser" +) + +// concurrentFingerprint runs one decompile with request-local policy and +// returns a canonical JSON fingerprint (or the deterministic error text). +func concurrentFingerprint(data []byte) string { + result, err := classparser.DecompileWithOptions(data, classparser.DecompileOptions{ + Mode: classparser.Precision, + Context: context.Background(), + Limits: classparser.Limits{ + MaxInputBytes: 1 << 20, + MaxReadBytes: 2 << 20, + MaxParseItems: 1 << 16, + MaxOutputBytes: 2 << 20, + MaxDiagnostics: 64, + MaxRequestWork: 4 << 20, + }, + EnvSnapshot: map[string]string{}, + }) + if err != nil { + return "error:" + err.Error() + } + encoded, marshalErr := json.Marshal(result) + if marshalErr != nil { + return "marshal-error:" + marshalErr.Error() + } + return string(encoded) +} + +// Class decompilation must be deterministic and race-free when callers share +// only package-level caches. The race detector turns any unsynchronized cache +// access into a test failure; the repeated fingerprints catch source drift. +func TestConcurrentDecompileDeterministic(t *testing.T) { + fixtures := []struct { + name string + data []byte + }{ + {name: "empty", data: []byte{}}, + {name: "magic only", data: []byte{0xca, 0xfe, 0xba, 0xbe}}, + {name: "zeroed class", data: make([]byte, 64)}, + } + for _, path := range []string{ + filepath.Join("..", "..", "classparser", "testdata", "regression", "FMParser.class"), + filepath.Join("..", "..", "classparser", "testdata", "regression", "Ser.class"), + } { + data, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + fixtures = append(fixtures, struct { + name string + data []byte + }{name: filepath.Base(path), data: data}) + } + + want := make([]string, len(fixtures)) + for index, fixture := range fixtures { + want[index] = concurrentFingerprint(fixture.data) + if again := concurrentFingerprint(fixture.data); again != want[index] { + t.Fatalf("%s: sequential decompile is nondeterministic", fixture.name) + } + } + + const workers = 3 + start := make(chan struct{}) + failures := make(chan string, workers) + var wait sync.WaitGroup + for worker := 0; worker < workers; worker++ { + wait.Add(1) + go func() { + defer wait.Done() + <-start + for index, fixture := range fixtures { + if got := concurrentFingerprint(fixture.data); got != want[index] { + failures <- fmt.Sprintf("%s: concurrent result differs", fixture.name) + return + } + } + }() + } + close(start) + wait.Wait() + close(failures) + for failure := range failures { + t.Error(failure) + } +} diff --git a/ci/requiredci/determinism_test.go b/ci/requiredci/determinism_test.go new file mode 100644 index 00000000..2aa5558a --- /dev/null +++ b/ci/requiredci/determinism_test.go @@ -0,0 +1,94 @@ +package requiredci_test + +import ( + "crypto/sha256" + "fmt" + "os" + "os/exec" + "strings" + "testing" +) + +var processDeterminismFixtures = []string{ + "FMParser.class", + "nondeterministic_loop_structuring.class", +} + +const processDeterminismMarker = "JAVAJIVE_DETERMINISM" + +func processDeterminismHash(name string) (string, error) { + data, err := os.ReadFile(filesystemFixturePath(name)) + if err != nil { + return "", err + } + sum := sha256.Sum256([]byte(concurrentFingerprint(data))) + return fmt.Sprintf("%s %x", name, sum), nil +} + +func filesystemFixturePath(name string) string { + return "../../classparser/testdata/regression/" + name +} + +// The child is invoked by TestDecompileDeterministicAcrossProcesses with a +// private environment. A normal full-suite run returns without doing work. +func TestDecompileDeterminismChild(t *testing.T) { + if os.Getenv("JAVAJIVE_DETERMINISM_CHILD") != "1" { + return + } + for _, name := range processDeterminismFixtures { + line, err := processDeterminismHash(name) + if err != nil { + t.Fatal(err) + } + fmt.Printf("%s %s\n", processDeterminismMarker, line) + } +} + +// Map iteration order is seeded per process. Re-running the same decompile in +// child processes proves source, diagnostics, records and hashes do not depend +// on that seed, which same-process repetition cannot show. +func TestDecompileDeterministicAcrossProcesses(t *testing.T) { + want := make(map[string]string, len(processDeterminismFixtures)) + for _, name := range processDeterminismFixtures { + line, err := processDeterminismHash(name) + if err != nil { + t.Fatal(err) + } + want[name] = line + } + executable, err := os.Executable() + if err != nil { + t.Fatal(err) + } + for run := 0; run < 2; run++ { + command := exec.Command(executable, "-test.run=^TestDecompileDeterminismChild$", "-test.count=1", "-test.timeout=2m") + environment := make([]string, 0, len(os.Environ())+1) + for _, entry := range os.Environ() { + if strings.HasPrefix(entry, "JAVAJIVE_DETERMINISM_CHILD=") { + continue + } + environment = append(environment, entry) + } + command.Env = append(environment, "JAVAJIVE_DETERMINISM_CHILD=1") + output, runErr := command.CombinedOutput() + if runErr != nil { + t.Fatalf("child run %d: %v\n%s", run, runErr, output) + } + seen := map[string]bool{} + for _, line := range strings.Split(string(output), "\n") { + line = strings.TrimSpace(line) + if !strings.HasPrefix(line, processDeterminismMarker+" ") { + continue + } + got := strings.TrimPrefix(line, processDeterminismMarker+" ") + name := strings.SplitN(got, " ", 2)[0] + if expected, ok := want[name]; !ok || got != expected { + t.Fatalf("child run %d %s: got %q want %q", run, name, got, expected) + } + seen[name] = true + } + if len(seen) != len(want) { + t.Fatalf("child run %d: saw %d fixtures, want %d\n%s", run, len(seen), len(want), output) + } + } +} diff --git a/ci/requiredci/fixed_corpus_test.go b/ci/requiredci/fixed_corpus_test.go new file mode 100644 index 00000000..760b0d42 --- /dev/null +++ b/ci/requiredci/fixed_corpus_test.go @@ -0,0 +1,173 @@ +// Package requiredci holds the small committed corpus exercised by required CI. +package requiredci_test + +import ( + "archive/zip" + "bytes" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "io" + "os" + "path/filepath" + "reflect" + "sort" + "strings" + "testing" + + classparser "github.com/yaklang/javajive/classparser" + "github.com/yaklang/javajive/classparser/classfilebuilder" + "github.com/yaklang/javajive/dex2jar" + "github.com/yaklang/javajive/internal/jimagefixture" + "github.com/yaklang/javajive/jimage" +) + +type corpusManifest struct { + Schema int `json:"schema"` + Fixtures []corpusFixture `json:"fixtures"` +} + +type corpusFixture struct { + File string `json:"file"` + SHA256 string `json:"sha256"` + Size int `json:"size"` + JarSHA256 string `json:"jar_sha256"` + JarInventory []string `json:"jar_inventory"` + InputInventory []string `json:"input_inventory"` + Report map[string]int `json:"report"` + Classes []string `json:"classes"` + AllowedDiagnostics map[string]map[string][]string `json:"allowed_diagnostics"` + Driver string `json:"driver"` + DriverClass string `json:"driver_class"` + Runs []map[string]any `json:"runs"` + Quality map[string]map[string]map[string]int `json:"quality"` +} + +func TestFixedDEXCorpusStructure(t *testing.T) { + root := filepath.Join("..", "..", "dex2jar", "testdata", "accept") + data, err := os.ReadFile(filepath.Join(root, "manifest.json")) + if err != nil { + t.Fatal(err) + } + var manifest corpusManifest + decoder := json.NewDecoder(bytes.NewReader(data)) + decoder.DisallowUnknownFields() + if err := decoder.Decode(&manifest); err != nil { + t.Fatal(err) + } + if err := decoder.Decode(&struct{}{}); err != io.EOF { + t.Fatalf("manifest has trailing JSON: %v", err) + } + if manifest.Schema != 1 || len(manifest.Fixtures) != 2 { + t.Fatalf("unexpected fixed corpus manifest: schema=%d fixtures=%d", manifest.Schema, len(manifest.Fixtures)) + } + seen := map[string]bool{} + for _, fixture := range manifest.Fixtures { + if seen[fixture.File] || filepath.Base(fixture.File) != fixture.File { + t.Fatalf("unsafe or duplicate fixture name %q", fixture.File) + } + seen[fixture.File] = true + raw, err := os.ReadFile(filepath.Join(root, fixture.File)) + if err != nil { + t.Fatal(err) + } + if len(raw) != fixture.Size || digest(raw) != fixture.SHA256 { + t.Fatalf("fixture %s does not match its committed size/hash", fixture.File) + } + if got := inputInventory(t, fixture.File, raw); !reflect.DeepEqual(got, fixture.InputInventory) { + t.Fatalf("fixture %s input inventory = %v, want %v", fixture.File, got, fixture.InputInventory) + } + first, report, err := dex2jar.DexToJar(raw, dex2jar.Options{}) + if err != nil { + t.Fatalf("fixture %s conversion: %v", fixture.File, err) + } + second, secondReport, err := dex2jar.DexToJar(raw, dex2jar.Options{}) + if err != nil || report != secondReport || !bytes.Equal(first, second) { + t.Fatalf("fixture %s conversion is not deterministic: %v", fixture.File, err) + } + if digest(first) != fixture.JarSHA256 { + t.Fatalf("fixture %s JAR hash = %s, want %s", fixture.File, digest(first), fixture.JarSHA256) + } + if got := jarInventory(t, first); !reflect.DeepEqual(got, fixture.JarInventory) { + t.Fatalf("fixture %s JAR inventory = %v, want %v", fixture.File, got, fixture.JarInventory) + } + } +} + +func TestSyntheticJImageStructure(t *testing.T) { + classBytes, err := classfilebuilder.NewClass( + "java/lang/Object", "", classfilebuilder.ACC_PUBLIC|classfilebuilder.ACC_SUPER, + ).Bytes() + if err != nil { + t.Fatal(err) + } + imageBytes, err := jimagefixture.Build([]jimagefixture.Entry{ + {Path: "/java.base/java/lang/Object.class", Data: classBytes}, + {Path: "/java.base/conf/security/java.security", Data: []byte("fixed=true\n")}, + }) + if err != nil { + t.Fatal(err) + } + reader, err := jimage.OpenBytes(imageBytes) + if err != nil { + t.Fatal(err) + } + entries := reader.Entries() + if len(entries) != 2 { + t.Fatalf("entry count = %d, want 2", len(entries)) + } + var output bytes.Buffer + if err := reader.WriteZIP(&output); err != nil { + t.Fatal(err) + } + if got := jarInventory(t, output.Bytes()); !reflect.DeepEqual(got, []string{"java.base/conf/security/java.security", "java/lang/Object.class"}) { + t.Fatalf("JImage ZIP inventory = %v", got) + } +} + +func digest(data []byte) string { + sum := sha256.Sum256(data) + return hex.EncodeToString(sum[:]) +} + +func inputInventory(t *testing.T, name string, data []byte) []string { + t.Helper() + if strings.HasSuffix(name, ".dex") { + return []string{""} + } + return zipInventory(t, data, false) +} + +func jarInventory(t *testing.T, data []byte) []string { + t.Helper() + return zipInventory(t, data, true) +} + +func zipInventory(t *testing.T, data []byte, parseClasses bool) []string { + t.Helper() + reader, err := zip.NewReader(bytes.NewReader(data), int64(len(data))) + if err != nil { + t.Fatal(err) + } + result := make([]string, 0, len(reader.File)) + for _, file := range reader.File { + result = append(result, file.Name) + if !parseClasses || !strings.HasSuffix(file.Name, ".class") { + continue + } + stream, err := file.Open() + if err != nil { + t.Fatal(err) + } + classBytes, readErr := io.ReadAll(stream) + closeErr := stream.Close() + if readErr != nil || closeErr != nil { + t.Fatalf("read %s: %v / %v", file.Name, readErr, closeErr) + } + if _, err := classparser.Parse(classBytes); err != nil { + t.Fatalf("parse %s: %v", file.Name, err) + } + } + sort.Strings(result) + return result +} diff --git a/ci/task_t29/test_t29_contracts.py b/ci/task_t29/test_t29_contracts.py index 5bc3a53f..6f3a52d6 100644 --- a/ci/task_t29/test_t29_contracts.py +++ b/ci/task_t29/test_t29_contracts.py @@ -241,7 +241,7 @@ def test_T29_C06_observe_to_gate_requires_review(self) -> None: self.assertEqual(missing["reason"], "missing_case") snap = required_coverage_snapshot(ROOT) self.assertEqual(snap["jobs"]["ci.yml"], list(BASELINE_CI_JOBS)) - self.assertEqual(snap["jobs"]["ci.yml"], ["scope", "source", "regression", "gate"]) + self.assertEqual(snap["jobs"]["ci.yml"], ["contract", "corpus", "algorithm", "dex", "regression"]) pr_ci = (ROOT / ".github" / "workflows" / "ci.yml").read_text(encoding="utf-8") self.assertIn("name: Algorithm regression", pr_ci) self.assertRegex(pr_ci, r"(?m)^\s+timeout-minutes:\s+(?:[1-9]|1[0-5])\s*$") diff --git a/ci/task_t29/test_t29_execution_map.py b/ci/task_t29/test_t29_execution_map.py index bfe4909d..9c2c9db3 100644 --- a/ci/task_t29/test_t29_execution_map.py +++ b/ci/task_t29/test_t29_execution_map.py @@ -85,7 +85,7 @@ def test_python_ok_event_counts_only_exact_method(self) -> None: def test_pr_ci_stays_a_single_fast_algorithm_gate(self) -> None: snap = required_coverage_snapshot(ROOT) self.assertEqual(snap["jobs"]["ci.yml"], list(BASELINE_CI_JOBS)) - self.assertEqual(snap["jobs"]["ci.yml"], ["scope", "source", "regression", "gate"]) + self.assertEqual(snap["jobs"]["ci.yml"], ["contract", "corpus", "algorithm", "dex", "regression"]) workflow = (ROOT / ".github" / "workflows" / "ci.yml").read_text(encoding="utf-8") self.assertIn("name: Algorithm regression", workflow) self.assertRegex(workflow, r"(?m)^\s+timeout-minutes:\s+(?:[1-9]|1[0-5])\s*$") @@ -93,23 +93,13 @@ def test_pr_ci_stays_a_single_fast_algorithm_gate(self) -> None: validate_fast_cross_scope(workflow) def test_required_cross_scope_cannot_expand_to_foreign_inputs(self) -> None: - reviewed = "\n".join(REQUIRED_CROSS_COMMANDS) - validate_fast_cross_scope(reviewed) + workflow = (ROOT / ".github" / "workflows" / "ci.yml").read_text(encoding="utf-8") + validate_fast_cross_scope(workflow) for command in ( - "go test ./test/cross", - "go test ./test/cross -run .", - reviewed.replace("-run '^(", "-run '.*|(", 1), - reviewed.replace("-timeout=2m", "-timeout=30m", 1), - reviewed.replace("-count=1", "-count=0", 1), - reviewed.replace(FAST_REBUILT_JAR_TESTS[0], "TestHistoricalJarAudit", 1), - reviewed + "\ngo test ./test/cross", - reviewed + "\n" + IRREDUCIBLE_CFG_RUN_COMMAND, - reviewed.replace("-json ./test/cross", "-json ./test/cross ./...", 1), - reviewed.replace(IRREDUCIBLE_CFG_TEST, "TestHistoricalJarAudit", 1), - reviewed.replace("grep -xc", "grep -q", 1), - reviewed.replace("-timeout=3m", "-timeout=30m", 1), - "\n".join(REQUIRED_CROSS_COMMANDS[:-1]), - reviewed + " && go test ./...", + workflow + "\n# ./test/cross", + workflow.replace(IRREDUCIBLE_CFG_RUN_COMMAND, "go test ./test/cross", 1), + workflow.replace(IRREDUCIBLE_CFG_RUN_COMMAND, "", 1), + workflow + "\n" + IRREDUCIBLE_CFG_RUN_COMMAND, "", ): with self.subTest(command=command), self.assertRaises(ValueError): @@ -120,26 +110,17 @@ def test_reviewed_cross_suite_names_still_exist_exactly_once(self) -> None: names = [] for path in (ROOT / "test" / "cross").glob("*_test.go"): names.extend(re.findall(r"(?m)^func (Test\w+)\(t \*testing\.T\)", path.read_text(encoding="utf-8"))) - for name in (*FAST_REBUILT_JAR_TESTS, IRREDUCIBLE_CFG_TEST): - self.assertEqual(names.count(name), 1, msg=name) + self.assertEqual(names.count(IRREDUCIBLE_CFG_TEST), 1, msg=IRREDUCIBLE_CFG_TEST) - def test_ci_summary_requires_every_source_shard(self) -> None: + def test_ci_summary_requires_every_sealed_gate(self) -> None: workflow = (ROOT / ".github" / "workflows" / "ci.yml").read_text(encoding="utf-8") - source, summary = workflow.split(" regression:\n", 1) - self.assertRegex(source, r"shard:\s*\[0,\s*1,\s*2,\s*3,\s*4,\s*5,\s*6,\s*7,\s*8,\s*9\]") - self.assertIn('SOURCE_SHARDS: "10"', source) - self.assertIn('SOURCE_WORKERS: "5"', source) - self.assertIn("fail-fast: false", source) - self.assertIn("needs: [scope, source, regression]", summary) + _, summary = workflow.split(" regression:\n", 1) + self.assertIn("needs: [contract, corpus, algorithm, dex]", summary) self.assertIn("if: always()", summary) - self.assertIn("SCOPE_RESULT: ${{ needs.scope.result }}", summary) - self.assertIn("SOURCE_RESULT: ${{ needs.source.result }}", summary) - self.assertIn("REGRESSION_RESULT: ${{ needs.regression.result }}", summary) - self.assertIn("CLASSPARSER: ${{ needs.scope.outputs.classparser }}", summary) - self.assertIn('test "$SCOPE_RESULT" = success', summary) - self.assertIn('test "$REGRESSION_RESULT" = success', summary) - self.assertIn('true) test "$SOURCE_RESULT" = success', summary) - self.assertIn("skipped|success", summary) + for result in ("CONTRACT_RESULT", "CORPUS_RESULT", "ALGORITHM_RESULT", "DEX_RESULT"): + self.assertIn(f'test "${result}" = success', summary) + self.assertNotIn("SOURCE_SHARDS", workflow) + self.assertNotIn("setup-java", workflow) def test_slow_contracts_remain_manual_and_discoverable(self) -> None: workflows = ROOT / ".github" / "workflows" diff --git a/classparser/archive_declarations.go b/classparser/archive_declarations.go index b6b10f66..92744b7d 100644 --- a/classparser/archive_declarations.go +++ b/classparser/archive_declarations.go @@ -10,6 +10,7 @@ import ( "github.com/yaklang/javajive/internal/filesys" fi "github.com/yaklang/javajive/internal/filesys/filesys_interface" + "github.com/yaklang/javajive/internal/inputkind" ) // Declaration indexes contain entry locations, not parsed classes or decompiled @@ -49,7 +50,8 @@ func (s *archiveDeclarationScope) index(root fi.FileSystem, rootDir string) { } continue } - if strings.EqualFold(path.Ext(name), ".jar") { + switch strings.ToLower(path.Ext(name)) { + case ".jar", ".aar", ".jmod", ".par": var z *filesys.ZipFS if parent, ok := fsys.(*filesys.ZipFS); ok { // Use the same nesting/budget admission as normal archive reads. @@ -63,6 +65,7 @@ func (s *archiveDeclarationScope) index(root fi.FileSystem, rootDir string) { if err != nil { return false } + raw = inputkind.StripJMODHeader(raw) var errOpen error z, errOpen = filesys.NewZipFSRaw(bytes.NewReader(raw), int64(len(raw))) if errOpen != nil { @@ -74,8 +77,9 @@ func (s *archiveDeclarationScope) index(root fi.FileSystem, rootDir string) { } continue } - // Do not enter adjacent WAR/EAR/ZIP applications. Nested JARs are - // declarations in this scope; other deployments are not. + // Do not enter adjacent WAR/EAR/ZIP applications. Nested + // JAR/AAR/JMOD/PAR archives are declarations in this scope; other + // deployments are not. if !strings.HasSuffix(name, ".class") { continue } diff --git a/classparser/classfile_version.go b/classparser/classfile_version.go index cfcd4178..4d1fac54 100644 --- a/classparser/classfile_version.go +++ b/classparser/classfile_version.go @@ -21,3 +21,23 @@ func ValidateSupportedClassMajor(major uint16) error { } return nil } + +// ValidateClassMinor reports malformed major/minor combinations while keeping +// Parse permissive for future classfile versions. Since Java 12, 65535 marks a +// preview class; preview semantics are a decompiler capability boundary rather +// than malformed input. +func ValidateClassMinor(major, minor uint16) error { + if major == 45 { + if minor <= 3 { + return nil + } + return fmt.Errorf("invalid_classfile_version: major 45 minor %d exceeds 3", minor) + } + if minor == 0 { + return nil + } + if major >= 56 && minor == 0xffff { + return fmt.Errorf("unsupported_classfile_preview: major %d uses preview minor 65535", major) + } + return fmt.Errorf("invalid_classfile_version: major %d requires minor 0, got %d", major, minor) +} diff --git a/classparser/classfilebuilder/annotations.go b/classparser/classfilebuilder/annotations.go index 66c7a281..8f18e6f0 100644 --- a/classparser/classfilebuilder/annotations.go +++ b/classparser/classfilebuilder/annotations.go @@ -16,6 +16,9 @@ const ( AnnotationChar AnnotationValueKind = 'C' AnnotationShort AnnotationValueKind = 'S' AnnotationInt AnnotationValueKind = 'I' + AnnotationLong AnnotationValueKind = 'J' + AnnotationFloat AnnotationValueKind = 'F' + AnnotationDouble AnnotationValueKind = 'D' AnnotationBool AnnotationValueKind = 'Z' AnnotationString AnnotationValueKind = 's' AnnotationEnum AnnotationValueKind = 'e' @@ -27,7 +30,8 @@ const ( // AnnotationValue is one element_value. type AnnotationValue struct { Kind AnnotationValueKind - Int int64 // for B/C/S/I/Z + Int int64 // for B/C/S/I/J/Z + Bits uint64 // IEEE-754 bits for F (low 32 bits) and D Text string // string constant, enum constant name, or class descriptor Type string // enum type descriptor, for Kind == AnnotationEnum Nested *Annotation @@ -93,6 +97,16 @@ func (t *annotationTarget) addPending(name string, encode func(*ConstantPool) ([ t.pending = append(t.pending, pendingAttribute{name: name, encode: encode}) } +func validateAttributePayloadLength(length uint64) error { + if length > uint64(math.MaxUint32) { + return fmt.Errorf("attribute length %d exceeds 4294967295", length) + } + if length > uint64(^uint(0)>>1) { + return fmt.Errorf("attribute length %d exceeds the platform int limit", length) + } + return nil +} + func writeAttribute(out *byteWriter, attribute pendingAttribute) error { if attribute.encode != nil || attribute.nameIndex == 0 { // Payloads and name indices must be resolved before the constant pool @@ -100,6 +114,9 @@ func writeAttribute(out *byteWriter, attribute pendingAttribute) error { // constant_pool_count. return fmt.Errorf("%s attribute was not resolved before serialization", attribute.name) } + if err := validateAttributePayloadLength(uint64(len(attribute.payload))); err != nil { + return fmt.Errorf("%s: %w", attribute.name, err) + } out.u2(attribute.nameIndex) out.u4(uint32(len(attribute.payload))) out.bytes(attribute.payload) @@ -109,6 +126,9 @@ func writeAttribute(out *byteWriter, attribute pendingAttribute) error { // encodeAnnotations writes a RuntimeVisibleAnnotations or // RuntimeInvisibleAnnotations payload. func encodeAnnotations(pool *ConstantPool, annotations []Annotation, visible []bool, wantVisible bool) ([]byte, error) { + if len(visible) != len(annotations) { + return nil, fmt.Errorf("annotations and visibility differ in length") + } selected := make([]Annotation, 0, len(annotations)) for index, annotation := range annotations { if visible[index] == wantVisible { @@ -118,6 +138,9 @@ func encodeAnnotations(pool *ConstantPool, annotations []Annotation, visible []b if len(selected) == 0 { return nil, nil } + if len(selected) > math.MaxUint16 { + return nil, fmt.Errorf("annotation count %d exceeds 65535", len(selected)) + } out := &byteWriter{} out.u2(uint16(len(selected))) for _, annotation := range selected { @@ -166,6 +189,24 @@ func writeValue(pool *ConstantPool, out *byteWriter, value AnnotationValue) erro return err } out.u2(index) + case AnnotationLong: + index, err := pool.Long(value.Int) + if err != nil { + return err + } + out.u2(index) + case AnnotationFloat: + index, err := pool.Float(uint32(value.Bits)) + if err != nil { + return err + } + out.u2(index) + case AnnotationDouble: + index, err := pool.Double(value.Bits) + if err != nil { + return err + } + out.u2(index) case AnnotationString: index, err := pool.UTF8(value.Text) if err != nil { @@ -227,6 +268,9 @@ func encodeSignature(pool *ConstantPool, signature string) ([]byte, error) { } func encodeExceptions(pool *ConstantPool, descriptors []string) ([]byte, error) { + if len(descriptors) > math.MaxUint16 { + return nil, fmt.Errorf("Exceptions length %d exceeds 65535", len(descriptors)) + } out := &byteWriter{} out.u2(uint16(len(descriptors))) for _, descriptor := range descriptors { @@ -244,6 +288,9 @@ func encodeExceptions(pool *ConstantPool, descriptors []string) ([]byte, error) } func encodeInnerClasses(pool *ConstantPool, specs []InnerClassSpec) ([]byte, error) { + if len(specs) > math.MaxUint16 { + return nil, fmt.Errorf("InnerClasses count %d exceeds 65535", len(specs)) + } out := &byteWriter{} out.u2(uint16(len(specs))) for _, spec := range specs { @@ -304,10 +351,19 @@ func encodeParameterAnnotations(pool *ConstantPool, annotations [][]Annotation, if len(annotations) == 0 { return nil, nil } + if len(annotations) > math.MaxUint8 { + return nil, fmt.Errorf("parameter annotation count %d exceeds 255", len(annotations)) + } + if len(visible) != len(annotations) { + return nil, fmt.Errorf("parameter annotation sets and visibility differ in length") + } out := &byteWriter{} out.u1(uint8(len(annotations))) any := false for index, set := range annotations { + if len(visible[index]) != len(set) { + return nil, fmt.Errorf("parameter %d annotations and visibility differ in length", index) + } selected := make([]Annotation, 0, len(set)) for i, annotation := range set { if visible[index][i] == wantVisible { diff --git a/classparser/classfilebuilder/builder_test.go b/classparser/classfilebuilder/builder_test.go index a7026088..73c30335 100644 --- a/classparser/classfilebuilder/builder_test.go +++ b/classparser/classfilebuilder/builder_test.go @@ -732,6 +732,163 @@ func TestSourceDebugAndConstantValueAttributes(t *testing.T) { } } +func TestPreflightValidationAPIs(t *testing.T) { + tests := []struct { + name string + valid func() error + bad func() error + }{ + {"class internal name", func() error { return ValidateClassInternalName("pkg/Outer$Inner") }, func() error { return ValidateClassInternalName("pkg.Bad") }}, + {"object descriptor", func() error { return ValidateObjectDescriptor("Ljava/lang/String;") }, func() error { return ValidateObjectDescriptor("[Ljava/lang/String;") }}, + {"field symbol", func() error { return ValidateFieldSymbol("value", "[[I") }, func() error { return ValidateFieldSymbol("bad/name", "I") }}, + {"method symbol", func() error { return ValidateMethodSymbol("", "(I)V") }, func() error { return ValidateMethodSymbol("", "()I") }}, + {"method symbol UTF limit", func() error { return ValidateMethodSymbol(strings.Repeat("m", math.MaxUint16), "()V") }, func() error { return ValidateMethodSymbol(strings.Repeat("m", math.MaxUint16+1), "()V") }}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + if err := test.valid(); err != nil { + t.Fatalf("valid input rejected: %v", err) + } + if err := test.bad(); err == nil { + t.Fatal("invalid input accepted") + } + }) + } +} + +func TestRawClassAttributesCopyAndPreserveOrder(t *testing.T) { + class := NewClass("RawAttributes", "java/lang/Object", ACC_PUBLIC|ACC_SUPER).SetSourceFile("RawAttributes.java") + first := []byte{1, 2, 3} + class.AddClassAttribute("Opaque", first) + class.AddClassAttribute("Opaque", []byte{4, 5}) + first[0] = 99 + + raw, err := class.Bytes() + if err != nil { + t.Fatal(err) + } + parsed, err := javaclassparser.Parse(raw) + if err != nil { + t.Fatal(err) + } + if len(parsed.Attributes) != 3 { + t.Fatalf("class attributes = %d", len(parsed.Attributes)) + } + if _, ok := parsed.Attributes[0].(*javaclassparser.SourceFileAttribute); !ok { + t.Fatalf("first attribute = %#v", parsed.Attributes[0]) + } + for index, want := range [][]byte{{1, 2, 3}, {4, 5}} { + attribute, ok := parsed.Attributes[index+1].(*javaclassparser.UnparsedAttribute) + if !ok || attribute.Name != "Opaque" || !bytes.Equal(attribute.Info, want) { + t.Fatalf("raw attribute %d = %#v, want % x", index, parsed.Attributes[index+1], want) + } + } + again, err := class.Bytes() + if err != nil || !bytes.Equal(raw, again) { + t.Fatalf("raw attributes are not deterministic: %v", err) + } +} + +func TestRawClassAttributeValidation(t *testing.T) { + class := NewClass("BadRawAttribute", "java/lang/Object", ACC_PUBLIC) + class.AddClassAttribute("", nil) + if _, err := class.Bytes(); err == nil || !strings.Contains(err.Error(), "attribute name is empty") { + t.Fatalf("empty name error = %v", err) + } + + if err := validateAttributePayloadLength(uint64(math.MaxUint32)); err != nil { + t.Fatalf("u4 maximum rejected: %v", err) + } + if err := validateAttributePayloadLength(uint64(math.MaxUint32) + 1); err == nil || !strings.Contains(err.Error(), "4294967296") { + t.Fatalf("u4 overflow error = %v", err) + } +} + +func TestAnnotationValueNumericKinds(t *testing.T) { + floatBits := math.Float32bits(float32(-1.25)) + doubleBits := math.Float64bits(3.5) + class := NewClass("NumericAnnotation", "java/lang/Object", ACC_PUBLIC|ACC_SUPER) + class.AddClassAnnotation(Annotation{ + Descriptor: "Lpkg/Numbers;", + Elements: []AnnotationEntry{ + {Name: "longValue", Value: AnnotationValue{Kind: AnnotationLong, Int: -1 << 40}}, + {Name: "floatValue", Value: AnnotationValue{Kind: AnnotationFloat, Bits: uint64(floatBits)}}, + {Name: "doubleValue", Value: AnnotationValue{Kind: AnnotationDouble, Bits: doubleBits}}, + }, + }, true) + + raw, err := class.Bytes() + if err != nil { + t.Fatal(err) + } + parsed, err := javaclassparser.Parse(raw) + if err != nil { + t.Fatal(err) + } + attribute, ok := parsed.Attributes[0].(*javaclassparser.RuntimeVisibleAnnotationsAttribute) + if !ok || len(attribute.Annotations) != 1 { + t.Fatalf("annotations = %#v", parsed.Attributes) + } + values := attribute.Annotations[0].ElementValuePairs + if len(values) != 3 { + t.Fatalf("annotation values = %d", len(values)) + } + if value, ok := values[0].Value.(*javaclassparser.ConstantLongInfo); !ok || value.Value != -1<<40 { + t.Fatalf("long value = %#v", values[0].Value) + } + if value, ok := values[1].Value.(*javaclassparser.ConstantFloatInfo); !ok || math.Float32bits(value.Value) != floatBits { + t.Fatalf("float value = %#v", values[1].Value) + } + if value, ok := values[2].Value.(*javaclassparser.ConstantDoubleInfo); !ok || math.Float64bits(value.Value) != doubleBits { + t.Fatalf("double value = %#v", values[2].Value) + } +} + +func TestMetadataCountBounds(t *testing.T) { + annotations := make([]Annotation, math.MaxUint16+1) + visible := make([]bool, len(annotations)) + for index := range visible { + visible[index] = true + } + if _, err := encodeAnnotations(newConstantPool(), annotations, visible, true); err == nil || !strings.Contains(err.Error(), "annotation count 65536") { + t.Fatalf("annotation count error = %v", err) + } + if _, err := encodeInnerClasses(newConstantPool(), make([]InnerClassSpec, math.MaxUint16+1)); err == nil || !strings.Contains(err.Error(), "InnerClasses count 65536") { + t.Fatalf("InnerClasses count error = %v", err) + } + if _, err := encodeExceptions(newConstantPool(), make([]string, math.MaxUint16+1)); err == nil || !strings.Contains(err.Error(), "Exceptions length 65536") { + t.Fatalf("Exceptions count error = %v", err) + } + if _, err := encodeParameterAnnotations(newConstantPool(), make([][]Annotation, math.MaxUint8+1), make([][]bool, math.MaxUint8+1), true); err == nil || !strings.Contains(err.Error(), "parameter annotation count 256") { + t.Fatalf("parameter count error = %v", err) + } + parameterAnnotations := [][]Annotation{make([]Annotation, math.MaxUint16+1)} + parameterVisible := [][]bool{make([]bool, math.MaxUint16+1)} + for index := range parameterVisible[0] { + parameterVisible[0][index] = true + } + if _, err := encodeParameterAnnotations(newConstantPool(), parameterAnnotations, parameterVisible, true); err == nil || !strings.Contains(err.Error(), "annotation count 65536") { + t.Fatalf("parameter annotation count error = %v", err) + } +} + +func TestClassAndMemberAttributeCountBounds(t *testing.T) { + if count, err := checkedU2Count("attributes_count", math.MaxUint16); err != nil || count != math.MaxUint16 { + t.Fatalf("u2 maximum = %d, %v", count, err) + } + for _, kind := range []string{"class attributes_count", "field attributes_count", "method attributes_count"} { + if _, err := checkedU2Count(kind, math.MaxUint16+1); err == nil || !strings.Contains(err.Error(), kind+" 65536") { + t.Fatalf("%s overflow error = %v", kind, err) + } + } + + class := NewClass("AttributeBounds", "java/lang/Object", ACC_PUBLIC) + class.rawClassAttrs = make([]pendingAttribute, math.MaxUint16+1) + if _, err := class.Bytes(); err == nil || !strings.Contains(err.Error(), "class attributes_count 65536") { + t.Fatalf("class attribute count error = %v", err) + } +} + func TestJavaVerifyAll(t *testing.T) { java, err := exec.LookPath("java") if err != nil { diff --git a/classparser/classfilebuilder/class.go b/classparser/classfilebuilder/class.go index da83d5b4..2248846b 100644 --- a/classparser/classfilebuilder/class.go +++ b/classparser/classfilebuilder/class.go @@ -50,6 +50,7 @@ type Class struct { fieldAttrs [][]pendingAttribute methodAttrs [][]pendingAttribute classAttrs []pendingAttribute + rawClassAttrs []pendingAttribute err error } @@ -190,6 +191,12 @@ func (c *Class) SetMethodParameterAnnotations(method *Method, annotations [][]An c.fail("parameter annotation count %d exceeds 255", len(annotations)) return c } + for index := range annotations { + if len(annotations[index]) != len(visible[index]) { + c.fail("parameter %d annotations and visibility differ in length", index) + return c + } + } method.meta.parameterAnnot = annotations method.meta.parameterVis = visible return c @@ -224,6 +231,25 @@ func (c *Class) SetSourceDebugExtension(value string) *Class { return c } +// AddClassAttribute appends an opaque class attribute in call order. Duplicate +// names and payloads are preserved, and the payload is copied before returning. +func (c *Class) AddClassAttribute(name string, payload []byte) *Class { + if name == "" { + c.fail("class attribute name is empty") + return c + } + if err := validateAttributePayloadLength(uint64(len(payload))); err != nil { + c.fail("class attribute %q: %v", name, err) + return c + } + if _, err := c.pool.UTF8(name); err != nil { + c.fail("class attribute name %q: %v", name, err) + return c + } + c.rawClassAttrs = append(c.rawClassAttrs, pendingAttribute{name: name, payload: append([]byte(nil), payload...)}) + return c +} + // SetVersion selects the class file major version. The default is Java 5 (49), // whose inference verifier needs no StackMapTable. Java 8 (52) is required for // static and default interface methods; only methods without control flow or @@ -517,6 +543,18 @@ func (c *Class) Bytes() ([]byte, error) { if err := c.resolvePending(c.classAttrs); err != nil { return nil, err } + if len(c.interfaces) > math.MaxUint16 { + return nil, fmt.Errorf("interfaces_count %d exceeds 65535", len(c.interfaces)) + } + if len(c.fields) > math.MaxUint16 { + return nil, fmt.Errorf("fields_count %d exceeds 65535", len(c.fields)) + } + if len(c.methods) > math.MaxUint16 { + return nil, fmt.Errorf("methods_count %d exceeds 65535", len(c.methods)) + } + if _, err := checkedU2Count("class attributes_count", len(c.classAttrs)); err != nil { + return nil, err + } out := &byteWriter{} out.u4(classMagic) @@ -534,9 +572,13 @@ func (c *Class) Bytes() ([]byte, error) { } out.u2(uint16(len(c.fields))) for index, field := range c.fields { - attributes := uint16(len(c.fieldAttrs[index])) + attributeCount := len(c.fieldAttrs[index]) if field.constantValue != 0 { - attributes++ + attributeCount++ + } + attributes, err := checkedU2Count(fmt.Sprintf("field %q attributes_count", field.name), attributeCount) + if err != nil { + return nil, err } writeMemberHeader(out, &field.member, attributes) if field.constantValue != 0 { @@ -552,13 +594,19 @@ func (c *Class) Bytes() ([]byte, error) { } out.u2(uint16(len(c.methods))) for i, method := range c.methods { - attributes := uint16(len(c.methodAttrs[i])) + attributeCount := len(c.methodAttrs[i]) if assembled[i] != nil { - attributes++ + attributeCount++ + } + attributes, err := checkedU2Count(fmt.Sprintf("method %s%s attributes_count", method.name, method.descriptorText), attributeCount) + if err != nil { + return nil, err } writeMemberHeader(out, &method.member, attributes) if assembled[i] != nil { - writeCodeAttribute(out, c.codeName, assembled[i]) + if err := writeCodeAttribute(out, c.codeName, assembled[i]); err != nil { + return nil, fmt.Errorf("method %s%s: %w", method.name, method.descriptorText, err) + } } for _, attribute := range c.methodAttrs[i] { if err := writeAttribute(out, attribute); err != nil { @@ -616,9 +664,15 @@ func (c *Class) encodeMemberAttributes(meta *annotationTarget, out *[]pendingAtt } func parameterAnnotationsPresent(annotations [][]Annotation, visible [][]bool, wantVisible bool) bool { + if len(visible) != len(annotations) { + return false + } for index, set := range annotations { + if len(visible[index]) != len(set) { + return false + } for i := range set { - if index < len(visible) && i < len(visible[index]) && visible[index][i] == wantVisible { + if visible[index][i] == wantVisible { return true } } @@ -690,6 +744,9 @@ func (c *Class) encodeClassAttributes() error { } if c.sourceDebug != "" { value := c.sourceDebug + if err := validateAttributePayloadLength(uint64(len(value))); err != nil { + return fmt.Errorf("SourceDebugExtension %w", err) + } c.classAttrs = append(c.classAttrs, pendingAttribute{name: "SourceDebugExtension", payload: []byte(value)}) } if c.meta.signature != "" { @@ -710,7 +767,18 @@ func (c *Class) encodeClassAttributes() error { return encodeEnclosingMethod(pool, spec) }}) } - return c.encodeAnnotationAttributes(&c.meta, &c.classAttrs) + if err := c.encodeAnnotationAttributes(&c.meta, &c.classAttrs); err != nil { + return err + } + c.classAttrs = append(c.classAttrs, c.rawClassAttrs...) + return nil +} + +func checkedU2Count(kind string, count int) (uint16, error) { + if count > math.MaxUint16 { + return 0, fmt.Errorf("%s %d exceeds 65535", kind, count) + } + return uint16(count), nil } func writeMemberHeader(out *byteWriter, member *member, attributes uint16) { @@ -720,17 +788,29 @@ func writeMemberHeader(out *byteWriter, member *member, attributes uint16) { out.u2(attributes) } -func writeCodeAttribute(out *byteWriter, nameIndex uint16, code *assembledCode) { - nestedLength := 0 +func writeCodeAttribute(out *byteWriter, nameIndex uint16, code *assembledCode) error { + if len(code.handlers) > math.MaxUint16 { + return fmt.Errorf("exception_table_length %d exceeds 65535", len(code.handlers)) + } + if len(code.lines) > math.MaxUint16 { + return fmt.Errorf("line_number_table_length %d exceeds 65535", len(code.lines)) + } + if len(code.locals) > math.MaxUint16 { + return fmt.Errorf("local_variable_table_length %d exceeds 65535", len(code.locals)) + } + nestedLength := uint64(0) if len(code.lines) > 0 { - nestedLength += 8 + 4*len(code.lines) + nestedLength += 8 + 4*uint64(len(code.lines)) } if len(code.locals) > 0 { - nestedLength += 8 + 10*len(code.locals) + nestedLength += 8 + 10*uint64(len(code.locals)) + } + attributeLength := uint64(12) + uint64(len(code.bytes)) + 8*uint64(len(code.handlers)) + nestedLength + if err := validateAttributePayloadLength(attributeLength); err != nil { + return fmt.Errorf("Code %w", err) } - attributeLength := uint32(12 + len(code.bytes) + 8*len(code.handlers) + nestedLength) out.u2(nameIndex) - out.u4(attributeLength) + out.u4(uint32(attributeLength)) out.u2(code.maxStack) out.u2(code.maxLocals) out.u4(uint32(len(code.bytes))) @@ -771,4 +851,5 @@ func writeCodeAttribute(out *byteWriter, nameIndex uint16, code *assembledCode) out.u2(local.index) } } + return nil } diff --git a/classparser/classfilebuilder/validate.go b/classparser/classfilebuilder/validate.go index 9a87253a..f0888ff8 100644 --- a/classparser/classfilebuilder/validate.go +++ b/classparser/classfilebuilder/validate.go @@ -2,11 +2,39 @@ package classfilebuilder import ( "fmt" + "math" "strings" + "unicode/utf16" ) const maxArrayDimensions = 255 +// ValidateClassInternalName reports whether name is a JVM class or interface +// name in internal form, such as java/lang/String. Array descriptors are not +// class internal names. +func ValidateClassInternalName(name string) error { + return validateInternalName(name) +} + +// ValidateObjectDescriptor reports whether descriptor is exactly one JVM +// object type descriptor, such as Ljava/lang/String;. +func ValidateObjectDescriptor(descriptor string) error { + _, err := internalNameFromDescriptor(descriptor) + return err +} + +// ValidateFieldSymbol reports whether name and descriptor form a valid JVM +// field symbol. +func ValidateFieldSymbol(name, descriptor string) error { + return validateFieldSymbol(name, descriptor) +} + +// ValidateMethodSymbol reports whether name and descriptor form a valid JVM +// method symbol, including the special constraints for and . +func ValidateMethodSymbol(name, descriptor string) error { + return validateMethodSymbol(name, descriptor) +} + func validateInternalName(name string) error { if name == "" { return fmt.Errorf("internal name is empty") @@ -167,10 +195,23 @@ func parseFieldType(descriptor string, at int, array bool) (end, words int, err } } +func validateUTF8Constant(value, kind string) error { + if len(modifiedUTF8(utf16.Encode([]rune(value)))) > math.MaxUint16 { + return fmt.Errorf("%s modified UTF-8 payload exceeds 65535 bytes", kind) + } + return nil +} + func validateFieldSymbol(name, descriptor string) error { if err := validateFieldName(name); err != nil { return err } + if err := validateUTF8Constant(name, "field name"); err != nil { + return err + } + if err := validateUTF8Constant(descriptor, "field descriptor"); err != nil { + return err + } _, err := fieldDescriptorWords(descriptor) return err } @@ -179,6 +220,12 @@ func validateMethodSymbol(name, descriptor string) error { if err := validateMethodName(name); err != nil { return err } + if err := validateUTF8Constant(name, "method name"); err != nil { + return err + } + if err := validateUTF8Constant(descriptor, "method descriptor"); err != nil { + return err + } _, result, err := methodDescriptorWords(descriptor) if err != nil { return err diff --git a/classparser/cp_validate.go b/classparser/cp_validate.go new file mode 100644 index 00000000..b92162c2 --- /dev/null +++ b/classparser/cp_validate.go @@ -0,0 +1,190 @@ +package javaclassparser + +import ( + "fmt" + + "github.com/yaklang/javajive/internal/mutf8" +) + +// CheckConstantPoolLinks validates every constant-pool reference, including +// unused constants. Deep source-recovery code must not be the first consumer to +// discover a malformed index or a tag that the declared classfile version could +// not contain. +func (obj *ClassObject) CheckConstantPoolLinks() error { + if obj == nil { + return nil + } + utf := func(index uint16, field string) (*ConstantUtf8Info, error) { + if err := obj.checkCPIndex(index, false, field, CONSTANT_Utf8); err != nil { + return nil, err + } + return obj.ConstantPool[index-1].(*ConstantUtf8Info), nil + } + nameAndType := func(index uint16, field string) (*ConstantNameAndTypeInfo, error) { + if err := obj.checkCPIndex(index, false, field, CONSTANT_NameAndType); err != nil { + return nil, err + } + return obj.ConstantPool[index-1].(*ConstantNameAndTypeInfo), nil + } + bootstrapCount := -1 + for _, attribute := range obj.Attributes { + if table, ok := attribute.(*BootstrapMethodsAttribute); ok && table != nil { + bootstrapCount = len(table.BootstrapMethods) + break + } + } + for index, constant := range obj.ConstantPool { + cpIndex := index + 1 + if constant == nil { + continue + } + minimum, err := minimumConstantMajor(constant) + if err != nil { + return fmt.Errorf("constant pool[%d]: %w", cpIndex, err) + } + if obj.MajorVersion >= MinSupportedClassMajor && obj.MajorVersion < minimum { + return fmt.Errorf("constant pool[%d]: tag %d requires classfile major %d, got %d", cpIndex, constantTagOf(constant), minimum, obj.MajorVersion) + } + switch value := constant.(type) { + case *ConstantStringInfo: + if _, err := utf(value.StringIndex, "CONSTANT_String.string_index"); err != nil { + return fmt.Errorf("constant pool[%d]: %w", cpIndex, err) + } + case *ConstantFieldrefInfo: + if err := obj.checkCPIndex(value.ClassIndex, false, "CONSTANT_Fieldref.class_index", CONSTANT_Class); err != nil { + return fmt.Errorf("constant pool[%d]: %w", cpIndex, err) + } + nat, err := nameAndType(value.NameAndTypeIndex, "CONSTANT_Fieldref.name_and_type_index") + if err != nil { + return fmt.Errorf("constant pool[%d]: %w", cpIndex, err) + } + descriptor, err := utf(nat.DescriptorIndex, "CONSTANT_Fieldref.descriptor_index") + if err != nil || mutf8.ValidateFieldDescriptor(descriptor.semanticUnits()) != nil { + return fmt.Errorf("constant pool[%d]: field reference has invalid descriptor", cpIndex) + } + case *ConstantMethodrefInfo: + if err := obj.checkMemberReference(cpIndex, value.ClassIndex, value.NameAndTypeIndex, false); err != nil { + return err + } + case *ConstantInterfaceMethodrefInfo: + if err := obj.checkMemberReference(cpIndex, value.ClassIndex, value.NameAndTypeIndex, true); err != nil { + return err + } + case *ConstantMethodTypeInfo: + descriptor, err := utf(value.DescriptorIndex, "CONSTANT_MethodType.descriptor_index") + if err != nil { + return fmt.Errorf("constant pool[%d]: %w", cpIndex, err) + } + if err := mutf8.ValidateMethodDescriptor(descriptor.semanticUnits()); err != nil { + return fmt.Errorf("constant pool[%d]: invalid method type descriptor: %w", cpIndex, err) + } + case *ConstantMethodHandleInfo: + if err := obj.checkMethodHandle(cpIndex, value); err != nil { + return err + } + case *ConstantInvokeDynamicInfo: + if err := obj.checkDynamicReference(cpIndex, value.BootstrapMethodAttrIndex, value.NameAndTypeIndex, bootstrapCount, true); err != nil { + return err + } + case *ConstantDynamicInfo: + if err := obj.checkDynamicReference(cpIndex, value.BootstrapMethodAttrIndex, value.NameAndTypeIndex, bootstrapCount, false); err != nil { + return err + } + case *ConstantModuleInfo: + if _, err := utf(value.NameIndex, "CONSTANT_Module.name_index"); err != nil { + return fmt.Errorf("constant pool[%d]: %w", cpIndex, err) + } + case *ConstantPackageInfo: + if _, err := utf(value.NameIndex, "CONSTANT_Package.name_index"); err != nil { + return fmt.Errorf("constant pool[%d]: %w", cpIndex, err) + } + } + } + return nil +} + +func minimumConstantMajor(constant ConstantInfo) (uint16, error) { + switch constant.(type) { + case *ConstantMethodHandleInfo, *ConstantMethodTypeInfo, *ConstantInvokeDynamicInfo: + return 51, nil + case *ConstantModuleInfo, *ConstantPackageInfo: + return 53, nil + case *ConstantDynamicInfo: + return 55, nil + case *ConstantUtf8Info, *ConstantIntegerInfo, *ConstantFloatInfo, *ConstantLongInfo, *ConstantDoubleInfo, + *ConstantClassInfo, *ConstantStringInfo, *ConstantFieldrefInfo, *ConstantMethodrefInfo, + *ConstantInterfaceMethodrefInfo, *ConstantNameAndTypeInfo: + return 45, nil + default: + return 0, fmt.Errorf("unknown constant type %T", constant) + } +} + +func (obj *ClassObject) checkMemberReference(cpIndex int, classIndex, nameAndTypeIndex uint16, interfaceReference bool) error { + if err := obj.checkCPIndex(classIndex, false, "memberref.class_index", CONSTANT_Class); err != nil { + return fmt.Errorf("constant pool[%d]: %w", cpIndex, err) + } + if err := obj.checkCPIndex(nameAndTypeIndex, false, "memberref.name_and_type_index", CONSTANT_NameAndType); err != nil { + return fmt.Errorf("constant pool[%d]: %w", cpIndex, err) + } + nat := obj.ConstantPool[nameAndTypeIndex-1].(*ConstantNameAndTypeInfo) + descriptor, err := obj.getUtf8Units(nat.DescriptorIndex) + if err != nil { + return fmt.Errorf("constant pool[%d]: method descriptor: %w", cpIndex, err) + } + if err := mutf8.ValidateMethodDescriptor(descriptor); err != nil { + kind := "method" + if interfaceReference { + kind = "interface method" + } + return fmt.Errorf("constant pool[%d]: invalid %s descriptor: %w", cpIndex, kind, err) + } + return nil +} + +func (obj *ClassObject) checkMethodHandle(cpIndex int, handle *ConstantMethodHandleInfo) error { + if handle.ReferenceKind < 1 || handle.ReferenceKind > 9 { + return fmt.Errorf("constant pool[%d]: invalid method handle reference kind %d", cpIndex, handle.ReferenceKind) + } + var tags []uint8 + switch handle.ReferenceKind { + case 1, 2, 3, 4: + tags = []uint8{CONSTANT_Fieldref} + case 5, 8: + tags = []uint8{CONSTANT_Methodref} + case 6, 7: + tags = []uint8{CONSTANT_Methodref} + if obj.MajorVersion >= 52 { + tags = append(tags, CONSTANT_InterfaceMethodref) + } + case 9: + tags = []uint8{CONSTANT_InterfaceMethodref} + } + if err := obj.checkCPIndex(handle.ReferenceIndex, false, "CONSTANT_MethodHandle.reference_index", tags...); err != nil { + return fmt.Errorf("constant pool[%d]: %w", cpIndex, err) + } + return nil +} + +func (obj *ClassObject) checkDynamicReference(cpIndex int, bootstrapIndex, nameAndTypeIndex uint16, bootstrapCount int, method bool) error { + if bootstrapCount < 0 || int(bootstrapIndex) >= bootstrapCount { + return fmt.Errorf("constant pool[%d]: bootstrap method index %d is out of range", cpIndex, bootstrapIndex) + } + if err := obj.checkCPIndex(nameAndTypeIndex, false, "dynamic.name_and_type_index", CONSTANT_NameAndType); err != nil { + return fmt.Errorf("constant pool[%d]: %w", cpIndex, err) + } + nat := obj.ConstantPool[nameAndTypeIndex-1].(*ConstantNameAndTypeInfo) + descriptor, err := obj.getUtf8Units(nat.DescriptorIndex) + if err != nil { + return fmt.Errorf("constant pool[%d]: dynamic descriptor: %w", cpIndex, err) + } + if method { + err = mutf8.ValidateMethodDescriptor(descriptor) + } else { + err = mutf8.ValidateFieldDescriptor(descriptor) + } + if err != nil { + return fmt.Errorf("constant pool[%d]: invalid dynamic descriptor: %w", cpIndex, err) + } + return nil +} diff --git a/classparser/cp_validate_test.go b/classparser/cp_validate_test.go new file mode 100644 index 00000000..cdc77ab8 --- /dev/null +++ b/classparser/cp_validate_test.go @@ -0,0 +1,61 @@ +package javaclassparser + +import ( + "strings" + "testing" +) + +func TestConstantPoolLinksRejectMalformedUnusedConstants(t *testing.T) { + tests := []struct { + name string + major uint16 + append func(*ClassObject) + want string + }{ + { + name: "string index", major: 52, want: "CONSTANT_String.string_index", + append: func(object *ClassObject) { + object.ConstantPool = append(object.ConstantPool, &ConstantStringInfo{StringIndex: 0xffff}) + }, + }, + { + name: "method type version", major: 50, want: "requires classfile major 51", + append: func(object *ClassObject) { + object.ConstantPool = append(object.ConstantPool, &ConstantMethodTypeInfo{DescriptorIndex: 1}) + }, + }, + { + name: "dynamic version", major: 54, want: "requires classfile major 55", + append: func(object *ClassObject) { + object.ConstantPool = append(object.ConstantPool, &ConstantDynamicInfo{}) + }, + }, + { + name: "module version", major: 52, want: "requires classfile major 53", + append: func(object *ClassObject) { + object.ConstantPool = append(object.ConstantPool, &ConstantModuleInfo{NameIndex: 1}) + }, + }, + { + name: "method handle kind", major: 52, want: "invalid method handle reference kind", + append: func(object *ClassObject) { + object.ConstantPool = append(object.ConstantPool, &ConstantMethodHandleInfo{ReferenceKind: 0, ReferenceIndex: 1}) + }, + }, + } + seed := readValidationSeed(t) + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + object, err := Parse(seed) + if err != nil { + t.Fatal(err) + } + object.MajorVersion = test.major + test.append(object) + _, err = Parse(object.Bytes()) + if err == nil || !strings.Contains(err.Error(), test.want) { + t.Fatalf("Parse error = %v, want %q", err, test.want) + } + }) + } +} diff --git a/classparser/decompile_options.go b/classparser/decompile_options.go index f7821908..7988cbb1 100644 --- a/classparser/decompile_options.go +++ b/classparser/decompile_options.go @@ -4,6 +4,8 @@ import ( "context" "crypto/sha256" "fmt" + "strings" + "github.com/yaklang/javajive/classparser/decompiler/core" "github.com/yaklang/javajive/internal/jdecenv" @@ -235,6 +237,14 @@ func decompileWithBudget(data []byte, options DecompileOptions) (result Decompil result.Status = "unsupported" return result, budget, err } + if err := ValidateClassMinor(obj.MajorVersion, obj.MinorVersion); err != nil { + if strings.Contains(err.Error(), "unsupported_classfile_preview") { + result.Status = "unsupported" + } else { + result.Status = "invalid_input" + } + return result, budget, err + } result.Members = newMemberLedger(obj) result.Syntax = ValidationObservation{Status: "not_run"} defer func() { @@ -302,13 +312,105 @@ func decompileWithBudget(data []byte, options DecompileOptions) (result Decompil return result, budget, nil } +// rewriteHashMemoLimit bounds source states whose SHA-256 is retained. A +// class-source sequence normally changes only a handful of times; the cap +// keeps a pathological oscillation from retaining many full source strings. +const rewriteHashMemoLimit = 64 + +// rewriteSchedulerMetrics counts rule-level decisions for one dumper. It is +// request-local instrumentation and is never published as a diagnostic, so +// enabling the scheduler cannot change Observable output. +type rewriteSchedulerMetrics struct { + Considered int // every Compatibility sourceRewrite call + Candidates int // passed the necessary-literal prefilter (or Always) + Invoked int // the rule implementation was actually entered + Skipped int // rejected by the prefilter without invoking the rule + HashComputations int // SHA-256 calls; repeated source states reuse the memo +} + +// rewriteSchedulerOff is the bisection kill switch. The conservative prefilter +// is enabled by default; JDEC_REWRITE_SCHEDULER_OFF=1 restores unconditional +// invocation without changing order, hashing or diagnostics. +func (c *ClassObjectDumper) rewriteSchedulerOff() bool { + if c.rewriteSchedulerDisabled { + return true + } + if !c.rewriteSchedulerSwitchReady { + c.rewriteSchedulerSwitchReady = true + c.rewriteSchedulerSwitchOff = jdecenv.Get("JDEC_REWRITE_SCHEDULER_OFF") == "1" + } + return c.rewriteSchedulerSwitchOff +} + +// applicabilityIndexFor returns the index for this exact source state. The +// epoch and source string are both checked: an accepted rewrite advances the +// epoch and clears the index, and a rollback/retry that restores an older +// source cannot reuse the newer state's applicability. +func (c *ClassObjectDumper) applicabilityIndexFor(source string) *rewriteApplicabilityIndex { + if c.rewriteIndex == nil || c.rewriteIndex.epoch != c.rewriteEpoch || c.rewriteIndex.source != source { + c.rewriteIndex = &rewriteApplicabilityIndex{ + source: source, + epoch: c.rewriteEpoch, + presence: make(map[string]bool, len(rewriteRuleSpecs)), + } + } + return c.rewriteIndex +} + +// rewriteRuleMayChange is a necessary-condition gate, never a proof of +// applicability. Rules without registered metadata (including every +// shaded-library family) are Always applicable. +func (c *ClassObjectDumper) rewriteRuleMayChange(id, phase, source string) bool { + spec, ok := lookupRewriteRuleSpec(id, phase) + if !ok { + return true + } + return rewriteSpecApplicable(spec, c.applicabilityIndexFor(source)) +} + +// memoizedSourceHash hashes each exact source state at most once until the +// bounded memo is reset. It preserves the historical SHA-256 hex values. +func (c *ClassObjectDumper) memoizedSourceHash(source string) string { + if hash, ok := c.rewriteHashes[source]; ok { + return hash + } + hash := hashSource(source) + c.rewriteSchedulerStats.HashComputations++ + if c.rewriteHashes == nil { + c.rewriteHashes = make(map[string]string, 8) + } else if len(c.rewriteHashes) >= rewriteHashMemoLimit { + c.rewriteHashes = make(map[string]string, 8) + } + c.rewriteHashes[source] = hash + return hash +} + func (c *ClassObjectDumper) sourceRewrite(id, phase, source string, rule func(string) string) string { if c.options.Mode == Precision { return source } + c.rewriteSchedulerStats.Considered++ + // The prefilter runs before contract shielding, anonymous-scope masking, + // hash computation and ordinary-constructor drafts. A missing literal + // means the rule cannot change any slice of this source, so skipping the + // whole invocation is output-equivalent. + if !c.rewriteSchedulerOff() && !c.rewriteRuleMayChange(id, phase, source) { + c.rewriteSchedulerStats.Skipped++ + return source + } + c.rewriteSchedulerStats.Candidates++ if wrapped := wrapContractedSourceRule(id, rule); wrapped != nil { rule = wrapped } + invoked := false + scheduledRule := rule + rule = func(input string) string { + if !invoked { + invoked = true + c.rewriteSchedulerStats.Invoked++ + } + return scheduledRule(input) + } changed := source // Inline anonymous members have already completed recovery under their // original method context. Neither caller nor class recovery may borrow a @@ -358,7 +460,7 @@ func (c *ClassObjectDumper) sourceRewrite(id, phase, source string, rule func(st } var before, after string if changed != source && c.report != nil { - before, after = fmt.Sprintf("%x", sha256.Sum256([]byte(source))), fmt.Sprintf("%x", sha256.Sum256([]byte(changed))) + before, after = c.memoizedSourceHash(source), c.memoizedSourceHash(changed) // The class phase is one bounded sequence. Reject oscillation between // rules; method phases have separate contexts and are not compared. if phase == "class_source" { @@ -376,9 +478,14 @@ func (c *ClassObjectDumper) sourceRewrite(id, phase, source string, rule func(st if ordinaryDraft != nil && !c.ordinaryConstructorClassSource.commit(ordinaryDraft) { return source } - if changed != source && c.report != nil { - c.report.RulesApplied = append(c.report.RulesApplied, RewriteRecord{Rule: id, Phase: phase, BeforeHash: before, AfterHash: after}) - c.appendDiagnostic(DecompileDiagnostic{Code: "compatibility_rewrite", Rule: id, Message: "Legacy source recovery changed output without bytecode-level proof; validate behavior separately."}) + if changed != source { + // An accepted rewrite invalidates every cached applicability decision. + c.rewriteEpoch++ + c.rewriteIndex = nil + if c.report != nil { + c.report.RulesApplied = append(c.report.RulesApplied, RewriteRecord{Rule: id, Phase: phase, BeforeHash: before, AfterHash: after}) + c.appendDiagnostic(DecompileDiagnostic{Code: "compatibility_rewrite", Rule: id, Message: "Legacy source recovery changed output without bytecode-level proof; validate behavior separately."}) + } } return changed } diff --git a/classparser/decompiler/core/branch_array_inline.go b/classparser/decompiler/core/branch_array_inline.go index 1358771f..67645021 100644 --- a/classparser/decompiler/core/branch_array_inline.go +++ b/classparser/decompiler/core/branch_array_inline.go @@ -271,7 +271,7 @@ func (d *Decompiler) branchArrayOriginalPrefixPrecedes(producer, target *OpCode) return false } a, b := d.semanticCFG.indexOfNode(producer), d.semanticCFG.indexOfNode(target) - return a >= 0 && b >= 0 && d.semanticCFG.GetOrCompute(AnalysisDominators, GraphAnalysisDomain{Roots: []int{0}, IncludeException: true}).Dominates(a, b) + return a >= 0 && b >= 0 && d.semanticCFG.Dominates(a, b) } // Condition callbacks have not necessarily filled the source SlotValue yet. @@ -333,7 +333,7 @@ func (d *Decompiler) branchArraySelectedSourceArm(tern *values.TernaryExpression arm, entry = tern.FalseValue, taken } a, b := d.semanticCFG.indexOfNode(entry), d.semanticCFG.indexOfNode(allocation) - if a < 0 || b < 0 || !d.semanticCFG.GetOrCompute(AnalysisDominators, GraphAnalysisDomain{Roots: []int{0}, IncludeException: true}).Dominates(a, b) { + if a < 0 || b < 0 || !d.semanticCFG.Dominates(a, b) { return nil, nil } return arm, branch diff --git a/classparser/decompiler/core/branch_array_leaf.go b/classparser/decompiler/core/branch_array_leaf.go index 0acc4b5a..22e5f563 100644 --- a/classparser/decompiler/core/branch_array_leaf.go +++ b/classparser/decompiler/core/branch_array_leaf.go @@ -114,10 +114,31 @@ func (d *Decompiler) inlineBranchArrayLeaves() { } } +type arrayRefUse struct { + op *OpCode + index int +} + +// arrayRefUses indexes stack operands by JavaRef once per finalization pass. +// The nested-array fixpoint previously rescanned every opcode for every +// candidate array, even though the opcode stack map does not change between +// waves. +func (d *Decompiler) arrayRefUses() map[*values.JavaRef][]arrayRefUse { + uses := make(map[*values.JavaRef][]arrayRefUse) + for _, op := range d.opCodes { + for index, value := range op.stackConsumed { + if ref, ok := values.UnpackSoltValue(value).(*values.JavaRef); ok && ref != nil { + uses[ref] = append(uses[ref], arrayRefUse{op: op, index: index}) + } + } + } + return uses +} + // Fold the innermost completed array into its single parent element store. // Repeating this bottom-up lets RewriteNewArrayList see contiguous outer // stores, without ever publishing an incomplete array or copying an alias. -func (d *Decompiler) inlineNestedArrayInitializers(origins map[int]*OpCode) bool { +func (d *Decompiler) inlineNestedArrayInitializers(origins map[int]*OpCode, refUses map[*values.JavaRef][]arrayRefUse) bool { changed := false WalkGraph[*Node](d.RootNode, func(n *Node) ([]*Node, error) { if n == d.RootNode || len(n.Next) != 1 { @@ -145,22 +166,18 @@ func (d *Decompiler) inlineNestedArrayInitializers(origins map[int]*OpCode) bool return n.Next, nil } uses := 0 - for _, op := range d.opCodes { - for index, value := range op.stackConsumed { - if values.UnpackSoltValue(value) != ref { - continue - } - if op == sink && index == 0 { - uses++ + for _, use := range refUses[ref] { + op, index := use.op, use.index + if op == sink && index == 0 { + uses++ + continue + } + if int(op.CurrentOffset) > array.OriginPC && int(op.CurrentOffset) <= array.EvaluationEndPC && op.Instr != nil { + if op.Instr.OpCode == OP_DUP || (index == 2 && isArrayElementStore(op.Instr.OpCode)) { continue } - if int(op.CurrentOffset) > array.OriginPC && int(op.CurrentOffset) <= array.EvaluationEndPC && op.Instr != nil { - if op.Instr.OpCode == OP_DUP || (index == 2 && isArrayElementStore(op.Instr.OpCode)) { - continue - } - } - return n.Next, nil } + return n.Next, nil } if uses != 1 { return n.Next, nil diff --git a/classparser/decompiler/core/code_analyser.go b/classparser/decompiler/core/code_analyser.go index 1f3af1fe..14f01863 100644 --- a/classparser/decompiler/core/code_analyser.go +++ b/classparser/decompiler/core/code_analyser.go @@ -92,6 +92,10 @@ type Decompiler struct { constructorDelegationPC int constructorDelegationKnown bool unsupportedConstructorPrefix string + // jsrInlined records that inlineJSRSubroutines replaced the opcode stream. + // ParseStatement may then reuse its pre-inline control-flow validation only + // when this is false. + jsrInlined bool // RecordComponents supplies the declared component order and descriptors // for a record type. Pattern-switch reconstruction uses it to distinguish a // deconstruction accessor prefix from an ordinary method call in the case @@ -112,13 +116,21 @@ type Decompiler struct { // This constrains source preservation, without granting a factory role. LambdaReceiverCapture bool opcodeToSimulateStack map[*OpCode]*StackSimulationImpl - FunctionContext *class_context.ClassContext - varTable map[int]*values.JavaRef - opcodeIdToRef map[*OpCode][][2]any - branchArrayCalls []branchArrayCall - branchArrayLeaves []branchArrayLeaf - valueTernaryMerges map[*values.TernaryExpression]*OpCode - factoredValueRoutes map[*values.TernaryExpression]factoredValueRoute + // opcodeByOffset is the unique real-opcode witness per PC, built once after + // stack simulation. Ambiguous PCs are recorded separately and fail closed. + // Tests that inject opcodeToSimulateStack directly leave this nil and use + // the scanning fallback. + opcodeByOffset map[int]*OpCode + ambiguousOffsets map[int]bool + opcodeOffsetsSealed bool + FunctionContext *class_context.ClassContext + varTable map[int]*values.JavaRef + opcodeIdToRef map[*OpCode][][2]any + reachWalk reachWalkScratch + branchArrayCalls []branchArrayCall + branchArrayLeaves []branchArrayLeaf + valueTernaryMerges map[*values.TernaryExpression]*OpCode + factoredValueRoutes map[*values.TernaryExpression]factoredValueRoute // refToCreatingStore records, per *JavaRef pointer, the FIRST local-store opcode whose simulation // created that ref (isFirst=true). It lets the boolean-copy merge deterministically recover the // store that defined a slot's current ref without scanning opcodeIdToRef (a map whose iteration @@ -157,9 +169,13 @@ type Decompiler struct { ConstantPoolLiteralGetter func(constantPoolGetterid int) values.JavaValue ConstantPoolInvokeDynamicInfo func(id int) (uint16, string, string) offsetToOpcodeIndex map[uint16]int - opcodeIndexToOffset map[int]uint16 - ExceptionTable []*ExceptionTableEntry - BootstrapMethods []*BootstrapMethod + // opcodeOffsetsByID maps the stable opcode Id to its bytecode offset. This + // replaces a per-opcode map (about 4 MB on a large class) with a compact + // uint16 slice; Ids survive unreachable-code removal while slice positions + // do not. + opcodeOffsetsByID []uint16 + ExceptionTable []*ExceptionTableEntry + BootstrapMethods []*BootstrapMethod // Original declaration metadata qualifies source-body rendering. A source // request or a method-name convention cannot provide that permission. OriginalLambdaDeclaration func(owner, name, descriptor string) LambdaOriginalDeclaration @@ -288,7 +304,6 @@ func NewDecompiler(bytecodes []byte, constantPoolGetter func(id int) values.Java bytecodes: bytecodes, constantPoolGetter: constantPoolGetter, offsetToOpcodeIndex: map[uint16]int{}, - opcodeIndexToOffset: map[int]uint16{}, varTable: map[int]*values.JavaRef{}, opcodeIdToRef: map[*OpCode][][2]any{}, refToCreatingStore: map[*values.JavaRef]*OpCode{}, @@ -418,12 +433,15 @@ func (d *Decompiler) ParseOpcode() (err error) { if len(d.bytecodes) == 0 || len(d.bytecodes) > 65535 { return fmt.Errorf("invalid Code length %d", len(d.bytecodes)) } + d.jsrInlined = false + d.opcodeOffsetsSealed = false + d.opcodeByOffset = nil + d.ambiguousOffsets = nil d.opcodeCodeLength = len(d.bytecodes) sizeHint := len(d.bytecodes)/2 + 8 opcodes := make([]*OpCode, 0, sizeHint) opcodes = append(opcodes, &OpCode{Instr: &Instruction{OpCode: OP_START}}) offsetToIndex := make(map[uint16]int, sizeHint) - indexToOffset := make(map[int]uint16, sizeHint) reader := NewJavaByteCodeReader(d.bytecodes) id := 1 isWide := false @@ -462,24 +480,72 @@ func (d *Decompiler) ParseOpcode() (err error) { } opcodes = append(opcodes, opcode) offsetToIndex[opcode.CurrentOffset] = len(opcodes) - 1 - indexToOffset[len(opcodes)-1] = opcode.CurrentOffset id++ } if isWide { return fmt.Errorf("truncated wide at PC %d", wideOffset) } d.offsetToOpcodeIndex = offsetToIndex - d.opcodeIndexToOffset = indexToOffset d.CurrentId = id d.opCodes = opcodes + d.rebuildOpcodeOffsetsByID() return nil } +// rebuildOpcodeOffsetsByID indexes offsets by stable opcode Id. Slice order can +// change when unreachable code is removed, so Id is the only safe key. +func (d *Decompiler) rebuildOpcodeOffsetsByID() { + maxID := d.CurrentId + for _, op := range d.opCodes { + if op != nil && op.Id > maxID { + maxID = op.Id + } + } + if maxID < 0 { + maxID = 0 + } + offsets := make([]uint16, maxID+1) + for _, op := range d.opCodes { + if op == nil || op.Id < 0 || op.Id >= len(offsets) { + continue + } + offsets[op.Id] = op.CurrentOffset + } + d.opcodeOffsetsByID = offsets +} + +func (d *Decompiler) opcodeOffsetByID(id int) (uint16, bool) { + if d == nil || id < 0 || id >= len(d.opcodeOffsetsByID) { + return 0, false + } + return d.opcodeOffsetsByID[id], true +} + func (d *Decompiler) ScanJmp() error { if err := d.validateControlFlow(); err != nil { return err } + return d.scanJmpUnchecked() +} + +// scanJmpUnchecked builds the structuring CFG from an already validated opcode +// stream. ParseStatement uses it only when JSR inlining left the stream intact. +func (d *Decompiler) scanJmpUnchecked() error { opcodes := d.opCodes + // Exception entries are keyed once by protected-region start. The walk may visit + // an opcode more than once, but it no longer rescans the complete exception table + // at every instruction. Entry order inside a start bucket remains classfile order, + // preserving catch traversal and source output. + var exceptionsByStart map[uint16][]*ExceptionTableEntry + var catchTypesByHandler map[int]map[uint16]struct{} + if len(d.ExceptionTable) > 0 { + exceptionsByStart = make(map[uint16][]*ExceptionTableEntry, len(d.ExceptionTable)) + for _, entry := range d.ExceptionTable { + if entry != nil { + exceptionsByStart[entry.StartPc] = append(exceptionsByStart[entry.StartPc], entry) + } + } + } // Plain map (single-goroutine walk) avoids the mutex + interface boxing of utils.Set. visitNodeRecord := make(map[*OpCode]struct{}) endOp := &OpCode{Instr: InstrInfos[OP_END], Id: d.CurrentId} @@ -506,33 +572,43 @@ func (d *Decompiler) ScanJmp() error { if pre != nil { LinkOpcode(pre, opcode) } - for _, entry := range d.ExceptionTable { - if opcode.CurrentOffset == entry.StartPc { - if entry.StartPc == entry.HandlerPc { - continue - } - gotoOp := d.offsetToOpcodeIndex[entry.HandlerPc] - d.opCodes[gotoOp].IsCatch = true - d.opCodes[gotoOp].ExceptionTypeIndex = entry.CatchType - // Accumulate every catch type that shares this handler PC so multi-catch - // (`catch (A | B)`) can be reconstructed. Dedupe because the exception-table - // scan may revisit the same start opcode while walking the graph. - if !slices.Contains(d.opCodes[gotoOp].ExceptionTypeIndexes, entry.CatchType) { - d.opCodes[gotoOp].ExceptionTypeIndexes = append(d.opCodes[gotoOp].ExceptionTypeIndexes, entry.CatchType) + for _, entry := range exceptionsByStart[opcode.CurrentOffset] { + if entry.StartPc == entry.HandlerPc { + continue + } + gotoOp := d.offsetToOpcodeIndex[entry.HandlerPc] + d.opCodes[gotoOp].IsCatch = true + d.opCodes[gotoOp].ExceptionTypeIndex = entry.CatchType + // Accumulate every catch type that shares this handler PC so multi-catch + // (`catch (A | B)`) can be reconstructed. The per-handler set keeps + // dedupe O(1) while the slice retains first-seen classfile order. + seenTypes := catchTypesByHandler[gotoOp] + if seenTypes == nil { + if catchTypesByHandler == nil { + catchTypesByHandler = make(map[int]map[uint16]struct{}) } - deferWalkId = append(deferWalkId, gotoOp) - walkNode(gotoOp) - if pre != nil { - LinkOpcode(pre, d.opCodes[gotoOp]) - pre.IsTryCatchParent = true - pre.TryNode = opcode - pre.CatchNode = append(pre.CatchNode, &CatchNode{ - ExceptionTypeIndex: entry.CatchType, - StartIndex: entry.StartPc, - EndIndex: entry.EndPc, - OpCode: d.opCodes[gotoOp], - }) + seenTypes = make(map[uint16]struct{}, len(d.opCodes[gotoOp].ExceptionTypeIndexes)+1) + for _, catchType := range d.opCodes[gotoOp].ExceptionTypeIndexes { + seenTypes[catchType] = struct{}{} } + catchTypesByHandler[gotoOp] = seenTypes + } + if _, seen := seenTypes[entry.CatchType]; !seen { + seenTypes[entry.CatchType] = struct{}{} + d.opCodes[gotoOp].ExceptionTypeIndexes = append(d.opCodes[gotoOp].ExceptionTypeIndexes, entry.CatchType) + } + deferWalkId = append(deferWalkId, gotoOp) + walkNode(gotoOp) + if pre != nil { + LinkOpcode(pre, d.opCodes[gotoOp]) + pre.IsTryCatchParent = true + pre.TryNode = opcode + pre.CatchNode = append(pre.CatchNode, &CatchNode{ + ExceptionTypeIndex: entry.CatchType, + StartIndex: entry.StartPc, + EndIndex: entry.EndPc, + OpCode: d.opCodes[gotoOp], + }) } } @@ -1477,6 +1553,118 @@ func (d *Decompiler) reachingSlotStoreRefs(start *OpCode, slot int) map[string]* return out } +// reachWalkScratch reuses the visited map and work queue of consecutive +// backward reaching-store queries. The Decompiler is method-local and the +// query is not re-entrant, so generation stamps replace clearing the map. +type reachWalkScratch struct { + visited map[*OpCode]uint64 + queue []*OpCode + generation uint64 +} + +// reachingSlotStoreRefUnique answers the only question the read/store repair +// passes ask: is there exactly one distinct reaching same-slot definition, and +// is it different from current? It stops as soon as it encounters current (the +// read/store already continues correctly) or a second distinct definition (a +// real merge). The map-returning form explored the entire backward graph even +// when the nearest store was already current; on a large token-manager method +// that was tens of millions of visited opcodes. +func (d *Decompiler) reachingSlotStoreRefUnique(start *OpCode, slot int, current *values.JavaRef) *values.JavaRef { + if start == nil { + return nil + } + // The sparse reaching solver already has the per-slot definition sets. Use + // them when the CFG knows this opcode; only an unavailable node falls back + // to the structural Source walk. + if d.semanticCFG != nil { + if _, ok := d.semanticCFG.indexOfNodeCached(start); ok { + stores, _ := d.reachingStores(start, slot) + var found *values.JavaRef + for _, store := range stores { + refs, ok := d.opcodeIdToRef[store] + if !ok || len(refs) == 0 { + continue + } + ref, ok := refs[len(refs)-1][0].(*values.JavaRef) + if !ok || ref == nil { + continue + } + if current != nil && ref.VarUid == current.VarUid { + return nil + } + if found == nil { + found = ref + continue + } + if found.VarUid != ref.VarUid { + return nil + } + } + return found + } + } + sc := &d.reachWalk + if sc.visited == nil { + sc.visited = make(map[*OpCode]uint64) + } + sc.generation++ + if sc.generation == 0 { + clear(sc.visited) + sc.generation = 1 + } + gen := sc.generation + sc.visited[start] = gen + queue := append(sc.queue[:0], start.Source...) + var found *values.JavaRef + visits := 0 + for head := 0; head < len(queue); head++ { + cur := queue[head] + if cur == nil || sc.visited[cur] == gen { + continue + } + sc.visited[cur] = gen + visits++ + if d.Work != nil && visits%128 == 0 { + if err := d.Work.Charge(workbudget.CounterGraphScans, 128); err != nil { + // The budget remains latched and fails the method at its next + // boundary; never continue an unbounded repair search. + sc.queue = queue[:0] + return nil + } + } + if isLocalStoreOpcode(cur.Instr.OpCode) && GetStoreIdx(cur) == slot { + refs, ok := d.opcodeIdToRef[cur] + if !ok || len(refs) == 0 { + continue + } + ref, ok := refs[len(refs)-1][0].(*values.JavaRef) + if !ok || ref == nil { + continue + } + if current != nil && ref.VarUid == current.VarUid { + // current is a genuine reaching definition; no repair is safe. + sc.queue = queue[:0] + return nil + } + if found == nil { + found = ref + continue + } + if found.VarUid != ref.VarUid { + // Distinct reaching definitions form a real merge. + sc.queue = queue[:0] + return nil + } + // Match the map form, which keeps the last ref seen for a VarUid. + found = ref + continue + } + queue = append(queue, cur.Source...) + } + sc.queue = queue[:0] + return found +} + // reachingSlotVersionGeneral repairs a slot read that the single global slot table resolved to a ref // whose defining store does NOT reach the load along the CFG — a later/disjoint-branch version that // leaked in through DFS traversal order, EVEN WHEN the category (reference vs primitive) agrees so @@ -1497,24 +1685,13 @@ func (d *Decompiler) reachingSlotVersionGeneral(load *OpCode, slot int, current if load == nil || !isLocalLoadOpcode(load.Instr.OpCode) || current == nil { return nil } - reaching := d.reachingSlotStoreRefs(load, slot) - if len(reaching) == 0 { - return nil - } - if _, ok := reaching[current.VarUid]; ok { - // current is a genuine reaching definition: the read is already correct. + ref := d.reachingSlotStoreRefUnique(load, slot, current) + if ref == nil || ref.VarUid == current.VarUid { + // current is a genuine reaching definition, no definition reaches, or + // multiple distinct definitions form a real merge. return nil } - if len(reaching) != 1 { - // Multiple distinct reaching definitions = a real merge point; do not override. - return nil - } - for _, ref := range reaching { - if ref != nil && ref.VarUid != current.VarUid { - return ref - } - } - return nil + return ref } // reachingStoreVersion repairs the SAME single-global-slot-table DFS corruption as @@ -1548,20 +1725,15 @@ func (d *Decompiler) reachingStoreVersion(store *OpCode, slot int, current *valu // The current global version already continues this store correctly; leave it alone. return nil } - reaching := d.reachingSlotStoreRefs(store, slot) - if len(reaching) != 1 { + ref := d.reachingSlotStoreRefUnique(store, slot, current) + if ref == nil || ref.Type() == nil { return nil } - for _, ref := range reaching { - if ref == nil || ref.Type() == nil { - return nil - } - if current != nil && ref.VarUid == current.VarUid { - return nil - } - if ref.Type().String(ctx) == typStr { - return ref - } + if current != nil && ref.VarUid == current.VarUid { + return nil + } + if ref.Type().String(ctx) == typStr { + return ref } return nil } @@ -4920,6 +5092,7 @@ func (d *Decompiler) CalcOpcodeStackInfo() error { return merged } ifNodeToConditionCallback := map[*OpCode]func(values.JavaValue){} + mergeConditions := newMergeConditionIndex() varTable := map[int]*values.JavaRef{} err := WalkGraph[*OpCode](d.RootOpCode, func(code *OpCode) ([]*OpCode, error) { // NOTE: do not sort code.Target for switch opcodes. The previous sort.Slice used an @@ -5041,20 +5214,7 @@ func (d *Decompiler) CalcOpcodeStackInfo() error { vscope := getVarScope(validSource) runtimeStackSimulation = NewStackSimulation(validSource.StackEntry, preferConcreteMergeVars(vscope.VarTable, validSources), vscope.VarId) } - ifNodes := []*OpCode{} - for _, opCode := range code.Source { - WalkGraph[*OpCode](opCode, func(code *OpCode) ([]*OpCode, error) { - switch code.Instr.OpCode { - case OP_IFEQ, OP_IFNE, OP_IFLE, OP_IFLT, OP_IFGT, OP_IFGE, OP_IF_ACMPEQ, OP_IF_ACMPNE, OP_IF_ICMPLT, OP_IF_ICMPGE, OP_IF_ICMPGT, OP_IF_ICMPNE, OP_IF_ICMPEQ, OP_IF_ICMPLE, OP_IFNONNULL, OP_IFNULL: - if !slices.Contains(ifNodes, code) { - ifNodes = append(ifNodes, code) - } - return nil, nil - default: - } - return code.Source, nil - }) - } + ifNodes := mergeConditions.collect(code.Source) ifNodes = lo.Filter(ifNodes, func(item *OpCode, index int) bool { return slices.Contains(mergeNodeToIfNode[code], item) }) @@ -5238,6 +5398,9 @@ func (d *Decompiler) CalcOpcodeStackInfo() error { } d.opCodes = GraphToList(d.RootOpCode) d.opcodeToSimulateStack = opcodeToSim + d.opcodeByOffset = nil + d.ambiguousOffsets = nil + d.opcodeOffsetsSealed = true d.lowerAcyclicStackMerges(acyclicStackMergeSlot) ternaryExpMergeNode = utils.NewSet(ternaryExpMergeNode).List() sort.Slice(ternaryExpMergeNode, func(i, j int) bool { @@ -6414,7 +6577,14 @@ func (d *Decompiler) ParseStatement() error { if err := d.inlineJSRSubroutines(); err != nil { return err } - d.semanticCFG, err = d.buildSemanticCFG() + // The encoded edges were validated before JSR inlining. If the inliner did + // not rewrite the stream, both graph builders can reuse that validation + // instead of rescanning every opcode, switch and exception entry twice. + if d.jsrInlined { + d.semanticCFG, err = d.buildSemanticCFG() + } else { + d.semanticCFG, err = d.buildSemanticCFGUnchecked() + } if err != nil { return err } @@ -6422,7 +6592,11 @@ func (d *Decompiler) ParseStatement() error { d.captureShadowIR() } d.cachedSlotWebs = nil - err = d.ScanJmp() + if d.jsrInlined { + err = d.ScanJmp() + } else { + err = d.scanJmpUnchecked() + } if err != nil { return err } @@ -7241,7 +7415,8 @@ func (d *Decompiler) ParseStatement() error { return true } MiscRewriter(d.RootNode, d.delRefUserAttr, allowArrayEffects) - for d.inlineNestedArrayInitializers(idToOpcode) { + arrayUses := d.arrayRefUses() + for d.inlineNestedArrayInitializers(idToOpcode, arrayUses) { MiscRewriter(d.RootNode, d.delRefUserAttr, allowArrayEffects) } d.inlinePrivateArrayReceiverReads(idToOpcode) diff --git a/classparser/decompiler/core/effect_motion.go b/classparser/decompiler/core/effect_motion.go index 08e3f924..25313972 100644 --- a/classparser/decompiler/core/effect_motion.go +++ b/classparser/decompiler/core/effect_motion.go @@ -1194,19 +1194,58 @@ func (d *Decompiler) canInlineValue(value values.JavaValue, source, target *Node return true } +func isOriginalOpcodeWitness(op *OpCode) bool { + return op != nil && op.Instr != nil && op.Instr.OpCode != OP_START && op.Instr.OpCode != OP_END && op.Instr.OpCode != OP_TRY_CATCH +} + +// indexOpcodesByOffset indexes the unique real opcode at each PC. The stack map +// is stable after simulation, so array/constructor proofs no longer scan every +// opcode per query. Ambiguous PCs fail closed exactly like the old scan. +func (d *Decompiler) indexOpcodesByOffset(ops map[*OpCode]*StackSimulationImpl) { + d.opcodeByOffset = nil + d.ambiguousOffsets = nil + if d == nil || len(ops) == 0 { + return + } + byOffset := make(map[int]*OpCode, len(ops)) + ambiguous := map[int]bool{} + for op := range ops { + if !isOriginalOpcodeWitness(op) { + continue + } + offset := int(op.CurrentOffset) + if _, exists := byOffset[offset]; exists { + ambiguous[offset] = true + continue + } + byOffset[offset] = op + } + d.opcodeByOffset = byOffset + d.ambiguousOffsets = ambiguous +} + // opcodeAtOffset returns only an opcode from this method's analyzed stack map. // A matching integer offset from a different method or incomplete parse is not proof. func (d *Decompiler) opcodeAtOffset(offset int) *OpCode { if d == nil { return nil } + if d.opcodeOffsetsSealed && d.opcodeByOffset == nil { + d.indexOpcodesByOffset(d.opcodeToSimulateStack) + } + if d.opcodeByOffset != nil { + if d.ambiguousOffsets[offset] { + return nil + } + return d.opcodeByOffset[offset] + } // Synthetic control nodes carry a default PC zero too. They are not // original bytecode witnesses, regardless of randomized map iteration. // Multiple real witnesses at a PC (for example an ambiguous clone) also // cannot establish a unique immutable origin. var original *OpCode for op := range d.opcodeToSimulateStack { - if op == nil || op.Instr == nil || int(op.CurrentOffset) != offset || op.Instr.OpCode == OP_START || op.Instr.OpCode == OP_END || op.Instr.OpCode == OP_TRY_CATCH { + if !isOriginalOpcodeWitness(op) || int(op.CurrentOffset) != offset { continue } if original != nil { diff --git a/classparser/decompiler/core/exception_regions_scale_test.go b/classparser/decompiler/core/exception_regions_scale_test.go new file mode 100644 index 00000000..ed3ca114 --- /dev/null +++ b/classparser/decompiler/core/exception_regions_scale_test.go @@ -0,0 +1,122 @@ +package core + +import ( + "fmt" + "testing" +) + +func exceptionRegionScaleCFG(t *testing.T, handlers int) *SemanticCFG { + t.Helper() + code := make([]byte, 0, handlers*4+1) + table := make([]*ExceptionTableEntry, 0, handlers) + for i := 0; i < handlers; i++ { + start := len(code) + 2 + code = append(code, OP_NOP, OP_NOP, OP_IDIV, OP_ASTORE_1) + table = append(table, &ExceptionTableEntry{ + StartPc: uint16(start), EndPc: uint16(start + 1), + HandlerPc: uint16(start + 1), CatchType: uint16(i + 1), + }) + } + code = append(code, OP_RETURN) + d := NewDecompiler(code, nil) + if err := d.ParseOpcode(); err != nil { + t.Fatal(err) + } + d.ExceptionTable = table + g, err := d.buildSemanticCFG() + if err != nil { + t.Fatalf("buildSemanticCFG: %v", err) + } + return g +} + +func TestExceptionRegionScaleAcceptsDisjointHandlers(t *testing.T) { + g := exceptionRegionScaleCFG(t, 256) + if err := g.ValidateExceptionRegions(); err != nil { + t.Fatalf("disjoint handler ranges rejected: %v", err) + } +} + +func exceptionCoverageGraph(coverages [][]uint16) *SemanticCFG { + var nodes []*OpCode + for pc := uint16(0); pc < 64; pc++ { + nodes = append(nodes, &OpCode{Instr: InstrInfos[OP_IDIV], CurrentOffset: pc, Id: int(pc)}) + } + handlers := []*OpCode{ + {Instr: InstrInfos[OP_ASTORE_1], CurrentOffset: 100, Id: 100}, + {Instr: InstrInfos[OP_ASTORE_1], CurrentOffset: 101, Id: 101}, + } + g := &SemanticCFG{Nodes: nodes, order: map[*OpCode]int{}} + for index, node := range nodes { + g.order[node] = index + } + for _, handler := range handlers { + g.order[handler] = len(g.order) + g.Nodes = append(g.Nodes, handler) + } + for handlerOrder, pcs := range coverages { + for _, pc := range pcs { + g.Edges = append(g.Edges, SemanticEdge{ + From: nodes[pc], To: handlers[handlerOrder], + Kind: EdgeException, HandlerOrder: handlerOrder, + }) + } + } + return g +} + +func TestExceptionRegionMultiSpanCrossing(t *testing.T) { + // Coverage A={1,3} and B={2,3}: they intersect, A has 1 outside B, and B + // has 2 outside A, so the unions cross even though the individual spans + // [3,3] and [2,3] are nested. + g := exceptionCoverageGraph([][]uint16{{1, 3}, {2, 3}}) + if err := g.ValidateExceptionRegions(); err == nil { + t.Fatal("multi-span union crossing was accepted") + } + + // A={1,2,3}, B={2} is a strict subset: no crossing. + g = exceptionCoverageGraph([][]uint16{{1, 2, 3}, {2}}) + if err := g.ValidateExceptionRegions(); err != nil { + t.Fatalf("nested multi-span coverage rejected: %v", err) + } + + // Disjoint coverage with an interleaved second span is accepted. + g = exceptionCoverageGraph([][]uint16{{0, 4}, {1, 5}}) + if err := g.ValidateExceptionRegions(); err != nil { + t.Fatalf("disjoint interleaved coverage rejected: %v", err) + } +} + +func BenchmarkValidateExceptionRegionsManyHandlers(b *testing.B) { + for _, handlers := range []int{64, 256, 1024} { + b.Run(fmt.Sprintf("%d", handlers), func(b *testing.B) { + code := make([]byte, 0, handlers*4+1) + table := make([]*ExceptionTableEntry, 0, handlers) + for i := 0; i < handlers; i++ { + start := len(code) + 2 + code = append(code, OP_NOP, OP_NOP, OP_IDIV, OP_ASTORE_1) + table = append(table, &ExceptionTableEntry{ + StartPc: uint16(start), EndPc: uint16(start + 1), + HandlerPc: uint16(start + 1), CatchType: uint16(i + 1), + }) + } + code = append(code, OP_RETURN) + d := NewDecompiler(code, nil) + if err := d.ParseOpcode(); err != nil { + b.Fatal(err) + } + d.ExceptionTable = table + g, err := d.buildSemanticCFG() + if err != nil { + b.Fatal(err) + } + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + if err := g.ValidateExceptionRegions(); err != nil { + b.Fatal(err) + } + } + }) + } +} diff --git a/classparser/decompiler/core/frametransfer/bounded_stack_model_test.go b/classparser/decompiler/core/frametransfer/bounded_stack_model_test.go index feff050e..a0e05743 100644 --- a/classparser/decompiler/core/frametransfer/bounded_stack_model_test.go +++ b/classparser/decompiler/core/frametransfer/bounded_stack_model_test.go @@ -152,6 +152,10 @@ func boundedFrameUnpublished(out Frame) bool { func TestBoundedStackMoveDiagrams(t *testing.T) { digest := sha256.New() var encoded [20]byte + // Locals are read-only for stack moves. Sharing one slice avoids rebuilding + // it for all 797k cases; the snapshot still detects any in-place write. + locals := boundedStackLocals() + localsSnapshot := append([]Type(nil), locals...) count, accepted, rejected := 0, 0, 0 for n, words := 0, 1; n <= 4; n, words = n+1, words*9 { for word := 0; word < words; word++ { @@ -162,6 +166,9 @@ func TestBoundedStackMoveDiagrams(t *testing.T) { remaining /= 9 } input := boundedStackSlots(logical) + if len(input) > boundedStackSnapshotSlots { + t.Fatalf("input slot count %d exceeds snapshot capacity", len(input)) + } for _, op := range boundedStackOps { wantLogical, legal := boundedStackDiagram(logical, op) want := boundedStackSlots(wantLogical) @@ -170,22 +177,21 @@ func TestBoundedStackMoveDiagrams(t *testing.T) { if limitIndex == 11 { limit = 65535 } - f, err := NewFrameWithLimits(8, limit) - if err != nil { - t.Fatal(err) - } - f.Locals = boundedStackLocals() - f.Stack = append([]Type(nil), input...) + // NewFrameWithLimits(8, limit) followed by replacing Locals + // is the same frame without allocating a throwaway Locals. + f := Frame{Locals: locals, Stack: input, maxStack: limit, hasLimits: true} f.ThisUninitialized, f.ThisClass, f.DirectSuperClass = true, "model/Owner", "model/Base" - before := f.Clone() + before := f + var beforeStack [boundedStackSnapshotSlots]Type + copy(beforeStack[:], input) out, exception, err := Transfer(f, Instr{Op: op, Local: -1}) valid := legal && len(input) <= limit && len(want) <= limit - if !boundedFrameExact(f, before) || exception != nil { + if !boundedFrameUnchanged(f, before, localsSnapshot, beforeStack[:len(input)]) || exception != nil { t.Fatalf("input mutation/exception n=%d word=%d op=%#x limit=%d", n, word, op, limit) } if valid { accepted++ - expected := before.Clone() + expected := before expected.Stack = want if err != nil || !boundedFrameExact(out, expected) { t.Fatalf("diagram n=%d word=%d op=%#x limit=%d got=%+v want=%+v err=%v", n, word, op, limit, out, expected, err) @@ -211,6 +217,31 @@ func TestBoundedStackMoveDiagrams(t *testing.T) { t.Logf("JVMS bounded stack diagrams: %d cases (%d legal, %d refused), sha256=%x", count, accepted, rejected, digest.Sum(nil)) } +const boundedStackSnapshotSlots = 8 + +// boundedFrameUnchanged verifies both frame scalars and the exact contents of +// the caller-owned Locals and Stack backing arrays. before is a pre-call value +// copy; the two snapshots are independent copies used to detect in-place +// writes that a shallow struct copy alone would miss. +func boundedFrameUnchanged(f, before Frame, localsSnapshot, stackSnapshot []Type) bool { + if f.maxStack != before.maxStack || f.hasLimits != before.hasLimits || + f.ThisUninitialized != before.ThisUninitialized || f.ThisClass != before.ThisClass || f.DirectSuperClass != before.DirectSuperClass || + len(f.Locals) != len(localsSnapshot) || len(f.Stack) != len(stackSnapshot) { + return false + } + for i := range localsSnapshot { + if f.Locals[i] != localsSnapshot[i] { + return false + } + } + for i := range stackSnapshot { + if f.Stack[i] != stackSnapshot[i] { + return false + } + } + return true +} + // Independently recognize head/tail layouts, including crossed/dangling pairs // and unknown kinds. These are invalid input contract cases, not legal bytecode // behavioral witnesses. Every rejection must leave the caller's slices intact. diff --git a/classparser/decompiler/core/guarded_call_inline.go b/classparser/decompiler/core/guarded_call_inline.go index bb0e4fb5..985b8d6c 100644 --- a/classparser/decompiler/core/guarded_call_inline.go +++ b/classparser/decompiler/core/guarded_call_inline.go @@ -135,7 +135,7 @@ func (d *Decompiler) canInlineGuardedCallTemp(root []statements.Statement, produ if operation.Effects&values.EffectCall == 0 || operation.Effects&values.EffectOpaque != 0 { return false } - conditionPC, ok := d.opcodeIndexToOffset[ternary.ConditionFromOp] + conditionPC, ok := d.opcodeOffsetByID(ternary.ConditionFromOp) if !ok || call.OriginPC <= int(conditionPC) { // The original branch must precede the invoke. Otherwise this may be a real // eager call followed by a null test, whose exception behavior must be kept. diff --git a/classparser/decompiler/core/guarded_call_inline_test.go b/classparser/decompiler/core/guarded_call_inline_test.go index 63a6db8f..69a45d35 100644 --- a/classparser/decompiler/core/guarded_call_inline_test.go +++ b/classparser/decompiler/core/guarded_call_inline_test.go @@ -34,7 +34,8 @@ func guardedCallInlineFixture() (*Decompiler, *[]statements.Statement, *values.F consumer := &statements.AssignStatement{LeftValue: result, JavaValue: ternary, OriginPC: 40, HasOriginPC: true} root := []statements.Statement{producer, consumer} d := NewDecompiler(nil, nil) - d.opcodeIndexToOffset[7] = 20 + d.opcodeOffsetsByID = make([]uint16, 8) + d.opcodeOffsetsByID[7] = 20 return d, &root, call, ternary } diff --git a/classparser/decompiler/core/jsr_inline.go b/classparser/decompiler/core/jsr_inline.go index 4c1a3d1c..ba1d26e6 100644 --- a/classparser/decompiler/core/jsr_inline.go +++ b/classparser/decompiler/core/jsr_inline.go @@ -122,9 +122,10 @@ func (d *Decompiler) inlineJSRSubroutines() error { d.opcodeCodeLength = work.opcodeCodeLength d.ExceptionTable = work.ExceptionTable d.offsetToOpcodeIndex = work.offsetToOpcodeIndex - d.opcodeIndexToOffset = work.opcodeIndexToOffset + d.opcodeOffsetsByID = work.opcodeOffsetsByID d.CurrentId = work.CurrentId d.RootOpCode = work.RootOpCode + d.jsrInlined = true return nil } } @@ -531,7 +532,6 @@ func (d *Decompiler) tryInlineJSR(ops []*OpCode) bool { // Commit (cannot fail): offsets, ids, maps, then branch operands. offsetToIndex := make(map[uint16]int, len(newOps)) - indexToOffset := make(map[int]uint16, len(newOps)) offset := 0 id := 1 for k, op := range newOps { @@ -543,7 +543,6 @@ func (d *Decompiler) tryInlineJSR(ops []*OpCode) bool { id++ op.CurrentOffset = uint16(offset) offsetToIndex[uint16(offset)] = k - indexToOffset[k] = uint16(offset) offset += opByteLen(op) } codeLenNew := uint16(offset) @@ -644,8 +643,8 @@ func (d *Decompiler) tryInlineJSR(ops []*OpCode) bool { d.opcodeCodeLength = int(codeLenNew) d.ExceptionTable = newExc d.offsetToOpcodeIndex = offsetToIndex - d.opcodeIndexToOffset = indexToOffset d.CurrentId = id + d.rebuildOpcodeOffsetsByID() if len(newOps) > 0 { d.RootOpCode = newOps[0] } diff --git a/classparser/decompiler/core/lambda_parameter_snapshots.go b/classparser/decompiler/core/lambda_parameter_snapshots.go index 500d3500..f66414a5 100644 --- a/classparser/decompiler/core/lambda_parameter_snapshots.go +++ b/classparser/decompiler/core/lambda_parameter_snapshots.go @@ -135,7 +135,7 @@ func (d *Decompiler) unchangedCaptureLocalAt(ref *values.JavaRef, use *OpCode) b } stores, entry := g.ReachingDefinitions(use, slot) a, b := g.indexOfNode(definition), g.indexOfNode(use) - return g.Err == nil && !entry && len(stores) == 1 && stores[0] == definition && a >= 0 && b >= 0 && g.GetOrCompute(AnalysisDominators, GraphAnalysisDomain{Roots: []int{0}, IncludeException: true}).Dominates(a, b) + return g.Err == nil && !entry && len(stores) == 1 && stores[0] == definition && a >= 0 && b >= 0 && g.Dominates(a, b) } func lambdaCaptureStoreDescriptor(opcode int, descriptor string) bool { diff --git a/classparser/decompiler/core/merge_conditions.go b/classparser/decompiler/core/merge_conditions.go new file mode 100644 index 00000000..0e93b8ef --- /dev/null +++ b/classparser/decompiler/core/merge_conditions.go @@ -0,0 +1,88 @@ +package core + +import "slices" + +// mergeConditionIndex memoizes the nearest conditional ancestors of a node. +// Stack-simulation value merges used to walk backwards from every predecessor +// separately, rediscovering the same conditions for every merge. A condition is +// terminal for this relation: conditions behind it are owned by a nested value +// tree, exactly as the old per-predecessor WalkGraph implemented. +type mergeConditionIndex struct { + cache map[*OpCode][]*OpCode + active map[*OpCode]bool +} + +func newMergeConditionIndex() *mergeConditionIndex { + // Maps are allocated on first use: most methods have no value merge, and + // this index is created for every stack simulation. + return &mergeConditionIndex{} +} + +func (m *mergeConditionIndex) ensureMaps() { + if m.cache == nil { + m.cache = make(map[*OpCode][]*OpCode, 64) + m.active = make(map[*OpCode]bool, 16) + } +} + +func isConditionOpcode(op *OpCode) bool { + if op == nil || op.Instr == nil { + return false + } + switch op.Instr.OpCode { + case OP_IFEQ, OP_IFNE, OP_IFLE, OP_IFLT, OP_IFGT, OP_IFGE, OP_IF_ACMPEQ, OP_IF_ACMPNE, + OP_IF_ICMPLT, OP_IF_ICMPGE, OP_IF_ICMPGT, OP_IF_ICMPNE, OP_IF_ICMPEQ, OP_IF_ICMPLE, + OP_IFNONNULL, OP_IFNULL: + return true + } + return false +} + +func (m *mergeConditionIndex) nearest(node *OpCode) []*OpCode { + if node == nil { + return nil + } + m.ensureMaps() + if cached, ok := m.cache[node]; ok { + return cached + } + if isConditionOpcode(node) { + out := []*OpCode{node} + m.cache[node] = out + return out + } + if m.active[node] { + // A cycle through non-condition nodes contributes no new condition on + // this path; another path discovers any condition reachable from it. + return nil + } + m.active[node] = true + var out []*OpCode + // WalkGraph pushes all successors and pops them LIFO, so the last source is + // visited first. Iterate the children in reverse to preserve its exact + // condition order (downstream ternary wiring is order-sensitive). + for index := len(node.Source) - 1; index >= 0; index-- { + for _, condition := range m.nearest(node.Source[index]) { + if !slices.Contains(out, condition) { + out = append(out, condition) + } + } + } + delete(m.active, node) + m.cache[node] = out + return out +} + +// collect returns the nearest conditions of the given predecessor list in +// source order, preserving the old WalkGraph traversal order. +func (m *mergeConditionIndex) collect(sources []*OpCode) []*OpCode { + var out []*OpCode + for _, source := range sources { + for _, condition := range m.nearest(source) { + if !slices.Contains(out, condition) { + out = append(out, condition) + } + } + } + return out +} diff --git a/classparser/decompiler/core/merge_conditions_test.go b/classparser/decompiler/core/merge_conditions_test.go new file mode 100644 index 00000000..6b30aaa7 --- /dev/null +++ b/classparser/decompiler/core/merge_conditions_test.go @@ -0,0 +1,153 @@ +package core + +import ( + "fmt" + "math/rand" + "reflect" + "slices" + "testing" +) + +func naiveNearestConditions(sources []*OpCode) []*OpCode { + var out []*OpCode + for _, source := range sources { + _ = WalkGraph[*OpCode](source, func(code *OpCode) ([]*OpCode, error) { + if isConditionOpcode(code) { + if !slices.Contains(out, code) { + out = append(out, code) + } + return nil, nil + } + return code.Source, nil + }) + } + return out +} + +func conditionGraphTestNodes(count int) []*OpCode { + nodes := make([]*OpCode, count) + for index := range nodes { + opcode := OP_NOP + if index%3 == 1 { + opcode = OP_IFEQ + } + nodes[index] = &OpCode{Instr: InstrInfos[opcode], CurrentOffset: uint16(index), Id: index} + } + return nodes +} + +func TestMergeConditionIndexMatchesWalkGraph(t *testing.T) { + // Linear chain with a condition every third node. + chain := conditionGraphTestNodes(40) + for index := 1; index < len(chain); index++ { + chain[index].Source = []*OpCode{chain[index-1]} + } + index := newMergeConditionIndex() + for _, node := range chain { + got := index.nearest(node) + want := naiveNearestConditions([]*OpCode{node}) + if !reflect.DeepEqual(got, want) { + t.Fatalf("node %d nearest = %v, want %v", node.Id, conditionIDs(got), conditionIDs(want)) + } + } + + // Diamond: condition -> two arms -> merge. The condition is nearest to both arms. + cond := &OpCode{Instr: InstrInfos[OP_IFEQ], Id: 100} + left := &OpCode{Instr: InstrInfos[OP_NOP], Id: 101, Source: []*OpCode{cond}} + right := &OpCode{Instr: InstrInfos[OP_NOP], Id: 102, Source: []*OpCode{cond}} + merge := &OpCode{Instr: InstrInfos[OP_NOP], Id: 103, Source: []*OpCode{left, right}} + if got, want := index.collect(merge.Source), naiveNearestConditions(merge.Source); !reflect.DeepEqual(got, want) { + t.Fatalf("diamond conditions = %v, want %v", conditionIDs(got), conditionIDs(want)) + } + + // Nested condition: the inner condition owns the merge; the outer one is + // behind it and must not be reported. + outer := &OpCode{Instr: InstrInfos[OP_IFEQ], Id: 200} + inner := &OpCode{Instr: InstrInfos[OP_IFEQ], Id: 201, Source: []*OpCode{outer}} + tail := &OpCode{Instr: InstrInfos[OP_NOP], Id: 202, Source: []*OpCode{inner}} + if got, want := index.collect([]*OpCode{tail}), naiveNearestConditions([]*OpCode{tail}); !reflect.DeepEqual(got, want) { + t.Fatalf("nested conditions = %v, want %v", conditionIDs(got), conditionIDs(want)) + } + + // A cycle without conditions contributes nothing, and must terminate. + first := &OpCode{Instr: InstrInfos[OP_NOP], Id: 300} + second := &OpCode{Instr: InstrInfos[OP_NOP], Id: 301, Source: []*OpCode{first}} + first.Source = []*OpCode{second} + if got, want := index.collect([]*OpCode{first}), naiveNearestConditions([]*OpCode{first}); !reflect.DeepEqual(got, want) { + t.Fatalf("cyclic conditions = %v, want %v", conditionIDs(got), conditionIDs(want)) + } +} + +func conditionIDs(nodes []*OpCode) []int { + out := make([]int, len(nodes)) + for index, node := range nodes { + out[index] = node.Id + } + return out +} + +func TestMergeConditionIndexRandomDAGDifferential(t *testing.T) { + rng := rand.New(rand.NewSource(17)) + for trial := 0; trial < 40; trial++ { + n := 80 + nodes := make([]*OpCode, n) + for index := range nodes { + opcode := OP_NOP + if index%4 == 0 { + opcode = OP_IFEQ + } + nodes[index] = &OpCode{Instr: InstrInfos[opcode], CurrentOffset: uint16(index), Id: index} + } + for index := 1; index < n; index++ { + // Acyclic by construction: sources always have smaller indexes. + for source := 0; source < index; source++ { + if rng.Intn(5) == 0 { + nodes[index].Source = append(nodes[index].Source, nodes[source]) + } + } + } + index := newMergeConditionIndex() + for _, node := range nodes { + got := index.nearest(node) + want := naiveNearestConditions([]*OpCode{node}) + if !reflect.DeepEqual(got, want) { + t.Fatalf("trial %d node %d nearest = %v, want %v", trial, node.Id, conditionIDs(got), conditionIDs(want)) + } + } + } +} + +func TestMergeConditionIndexDeepChainTerminates(t *testing.T) { + const depth = 20000 + nodes := make([]*OpCode, depth) + nodes[0] = &OpCode{Instr: InstrInfos[OP_IFEQ], Id: 0} + for index := 1; index < depth; index++ { + nodes[index] = &OpCode{Instr: InstrInfos[OP_NOP], Id: index, Source: []*OpCode{nodes[index-1]}} + } + index := newMergeConditionIndex() + got := index.collect([]*OpCode{nodes[depth-1]}) + if len(got) != 1 || got[0] != nodes[0] { + t.Fatalf("deep chain nearest = %v", conditionIDs(got)) + } +} + +func BenchmarkMergeConditionIndexChain(b *testing.B) { + for _, depth := range []int{512, 4096, 16384} { + b.Run(fmt.Sprintf("%d", depth), func(b *testing.B) { + nodes := make([]*OpCode, depth) + nodes[0] = &OpCode{Instr: InstrInfos[OP_IFEQ], Id: 0} + for index := 1; index < depth; index++ { + nodes[index] = &OpCode{Instr: InstrInfos[OP_NOP], Id: index, Source: []*OpCode{nodes[index-1]}} + } + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + index := newMergeConditionIndex() + got := index.collect([]*OpCode{nodes[depth-1]}) + if len(got) != 1 { + b.Fatalf("conditions = %v", conditionIDs(got)) + } + } + }) + } +} diff --git a/classparser/decompiler/core/node.go b/classparser/decompiler/core/node.go index 7a74cfbe..d459c361 100644 --- a/classparser/decompiler/core/node.go +++ b/classparser/decompiler/core/node.go @@ -249,6 +249,37 @@ func (n *Node) ReplaceNextSliceKeepOrder(oldNode *Node, news []*Node) { } } +// InsertNextAt splices nextNode into n.Next at index, preserving successor +// order, and repairs the reverse Source link. Rewriters that must keep a +// ConditionStatement's branch polarity use this instead of assigning n.Next +// directly, keeping every in-place edge mutation on this type. +func (n *Node) InsertNextAt(index int, nextNode *Node) { + if index < 0 || index > len(n.Next) { + index = len(n.Next) + } + n.Next = slices.Insert(n.Next, index, nextNode) + found := false + for _, source := range nextNode.Source { + if source == n { + found = true + break + } + } + if !found { + nextNode.Source = append(nextNode.Source, n) + } +} + +// DuplicateNext appends another edge to the successor already at index. A +// ConditionStatement uses duplicate edges to keep a selected branch reachable +// while its condition is folded; the reverse Source link is already present. +func (n *Node) DuplicateNext(index int) { + if index < 0 || index >= len(n.Next) { + return + } + n.Next = append(n.Next, n.Next[index]) +} + // isEarlyReturnGuardFold reports whether beforeNode is an if-guard (a ConditionStatement with // exactly two successors) whose successor other than assignNode is a bare `return` terminal, and // whose fold target does NOT flow back to the guard. This is the early-return-guard shape behind diff --git a/classparser/decompiler/core/opcode.go b/classparser/decompiler/core/opcode.go index 99bb7b33..b23418d4 100644 --- a/classparser/decompiler/core/opcode.go +++ b/classparser/decompiler/core/opcode.go @@ -3,47 +3,45 @@ package core import ( "github.com/yaklang/javajive/classparser/decompiler/core/values" "github.com/yaklang/javajive/internal/omap" - "github.com/yaklang/javajive/internal/utils" ) +// OpCode is kept densely packed: its layout is part of parser memory behavior. +// All pointer/slice/interface fields come first, followed by the few 4/2-byte +// fields and finally the boolean flags, so alignment padding does not make every +// decoded instruction larger. Several historical fields (GetStackChange, +// StackInfo, IfNode) were never read and were removed. type OpCode struct { - Id int - Instr *Instruction - CurrentOffset uint16 - Data []byte - Jmp int - BranchTarget int - IsWide bool - IsCatch bool - GetStackChange func() - IsTryCatchParent bool - TryNode *OpCode - CatchNode []*CatchNode - //StackSimulation *StackSimulationImpl - StackEntry *StackItem - Ref *values.JavaRef - ExceptionTypeIndex uint16 - // ExceptionTypeIndexes holds every catch type that targets this handler opcode. A - // multi-catch clause (`catch (A | B)`) compiles to several exception-table entries that - // share one handler PC but carry different catch types; collecting them here lets the - // decompiler reconstruct the full `A | B` clause instead of keeping only the last type. + Id int + Instr *Instruction + Data []byte + Jmp int + BranchTarget int + TryNode *OpCode + CatchNode []*CatchNode + StackEntry *StackItem + Ref *values.JavaRef ExceptionTypeIndexes []uint16 SwitchJmpCase *omap.OrderedMap[int, int32] SwitchJmpCase1 *omap.OrderedMap[int, int] - SwitchDefaultOffset int32 SwitchDefaultIndex int stackProduced []values.JavaValue stackConsumed []values.JavaValue Source []*OpCode Target []*OpCode TrueNode, FalseNode, MergeNode *OpCode - Negative bool - StackInfo *utils.Stack[*values.JavaValue] - IsTernaryNode bool - IfNode *OpCode Info any - IsCustom bool conditionOpId int + + SwitchDefaultOffset int32 + CurrentOffset uint16 + ExceptionTypeIndex uint16 + + IsWide bool + IsCatch bool + IsTryCatchParent bool + Negative bool + IsTernaryNode bool + IsCustom bool // TernaryChainArm marks a condition opcode that supplies its value into a DISTINCT nested // ternary arm (a right-leaning chain a?:b?:c?: or a structurally-rebuilt tree), as opposed // to a short-circuit &&/|| whose conditions all feed the SAME ternary condition. The diff --git a/classparser/decompiler/core/optional_supplier_definition.go b/classparser/decompiler/core/optional_supplier_definition.go index 71d49034..d2530e50 100644 --- a/classparser/decompiler/core/optional_supplier_definition.go +++ b/classparser/decompiler/core/optional_supplier_definition.go @@ -52,7 +52,7 @@ func (d *Decompiler) restoreOptionalSupplierDefinitionViews() { if target := call.OptionalGenericThrowsSupplierTarget(factory.SourceReturnType, d.FunctionContext); target != nil { storeIndex := d.semanticCFG.indexOfNode(stores[0]) callIndex := d.semanticCFG.indexOfNode(op) - if storeIndex < 0 || callIndex < 0 || !d.semanticCFG.GetOrCompute(AnalysisDominators, GraphAnalysisDomain{Roots: []int{0}, IncludeException: true}).Dominates(storeIndex, callIndex) { + if storeIndex < 0 || callIndex < 0 || !d.semanticCFG.Dominates(storeIndex, callIndex) { continue } call.Arguments[0] = &values.CastExpression{Value: call.Arguments[0], TargetType: target, Binding: true, OriginPC: call.OriginPC} diff --git a/classparser/decompiler/core/performance_batch_test.go b/classparser/decompiler/core/performance_batch_test.go new file mode 100644 index 00000000..d8a8352f --- /dev/null +++ b/classparser/decompiler/core/performance_batch_test.go @@ -0,0 +1,135 @@ +package core + +import ( + "testing" + "unsafe" + + "github.com/yaklang/javajive/classparser/decompiler/core/class_context" + "github.com/yaklang/javajive/classparser/decompiler/core/statements" +) + +func TestOpCodeStaysCompact(t *testing.T) { + // Every decoded instruction is an OpCode; a large class allocates hundreds + // of thousands. Field grouping keeps this at 320 bytes instead of 392. + if size := unsafe.Sizeof(OpCode{}); size > 320 { + t.Fatalf("OpCode is %d bytes, want <= 320", size) + } +} + +func performanceStatements(count int) []statements.Statement { + out := make([]statements.Statement, count) + for i := range out { + text := "statement;\n" + out[i] = statements.NewCustomStatement(func(*class_context.ClassContext) string { return text }, nil) + } + return out +} + +func TestStatementsStringExactOutput(t *testing.T) { + items := performanceStatements(3) + const want = "statement;\nstatement;\nstatement;\n" + if got := StatementsString(items, &class_context.ClassContext{}); got != want { + t.Fatalf("StatementsString() = %q, want %q", got, want) + } + if got := statements.StatementsString(items, &class_context.ClassContext{}); got != want { + t.Fatalf("statements.StatementsString() = %q, want %q", got, want) + } +} + +func BenchmarkStatementsStringBuilder(b *testing.B) { + items := performanceStatements(4096) + ctx := &class_context.ClassContext{} + b.ReportAllocs() + b.SetBytes(int64(len(items) * len("statement;\n"))) + for i := 0; i < b.N; i++ { + if got := StatementsString(items, ctx); len(got) == 0 { + b.Fatal("empty output") + } + } +} + +func TestScanJmpCatchTypesPreserveFirstSeenOrder(t *testing.T) { + d := NewDecompiler([]byte{OP_NOP, OP_RETURN, OP_POP, OP_RETURN}, nil) + d.ExceptionTable = []*ExceptionTableEntry{ + {StartPc: 0, EndPc: 2, HandlerPc: 2, CatchType: 7}, + {StartPc: 0, EndPc: 2, HandlerPc: 2, CatchType: 9}, + {StartPc: 0, EndPc: 2, HandlerPc: 2, CatchType: 7}, + } + if err := d.ParseOpcode(); err != nil { + t.Fatal(err) + } + if err := d.ScanJmp(); err != nil { + t.Fatal(err) + } + handler := d.opCodes[d.offsetToOpcodeIndex[2]] + if got := handler.ExceptionTypeIndexes; len(got) != 2 || got[0] != 7 || got[1] != 9 { + t.Fatalf("catch types = %v, want [7 9]", got) + } +} + +func BenchmarkScanJmpIndexedExceptionStarts(b *testing.B) { + const codeSize = 4096 + code := make([]byte, codeSize) + for i := range code { + code[i] = OP_NOP + } + code[codeSize-1] = OP_RETURN + table := make([]*ExceptionTableEntry, 0, 1024) + for i := 0; i < 1024; i++ { + start := uint16(i * 3) + table = append(table, &ExceptionTableEntry{StartPc: start, EndPc: start + 1, HandlerPc: codeSize - 1, CatchType: uint16(i%31 + 1)}) + } + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + d := NewDecompiler(code, nil) + d.ExceptionTable = table + if err := d.ParseOpcode(); err != nil { + b.Fatal(err) + } + if err := d.ScanJmp(); err != nil { + b.Fatal(err) + } + } +} + +func TestSemanticCFGAdjacencySnapshotsAreImmutable(t *testing.T) { + g := t26ExceptionCFG() + plain := g.successorIndexLists(false) + withException := g.successorIndexLists(true) + if len(plain[0]) != 1 || plain[0][0] != 1 { + t.Fatalf("plain successors = %v", plain) + } + if len(withException[0]) != 2 || withException[0][0] != 1 || withException[0][1] != 2 { + t.Fatalf("exception successors = %v", withException) + } + plain[0][0] = 99 + withException[0] = nil + if got := g.successorIndexLists(false); got[0][0] != 1 { + t.Fatalf("plain adjacency cache poisoned: %v", got) + } + if got := g.successorIndexLists(true); len(got[0]) != 2 { + t.Fatalf("exception adjacency cache poisoned: %v", got) + } +} + +func BenchmarkSemanticCFGCachedAdjacency(b *testing.B) { + const nodes = 4096 + edges := make([]t09Edge, 0, nodes*2) + for i := 0; i+1 < nodes; i++ { + edges = append(edges, t09Edge{i, i + 1, EdgeFallthrough}) + if i+17 < nodes { + edges = append(edges, t09Edge{i, i + 17, EdgeTaken}) + } + } + g := t09Graph(nodes, edges...) + domain := GraphAnalysisDomain{Roots: []int{0}} + _ = g.GetOrCompute(AnalysisDominators, domain) + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + if got := g.GetOrCompute(AnalysisDominators, domain); got == nil { + b.Fatal("nil analysis") + } + } +} diff --git a/classparser/decompiler/core/reaching_scale_test.go b/classparser/decompiler/core/reaching_scale_test.go new file mode 100644 index 00000000..08987d1a --- /dev/null +++ b/classparser/decompiler/core/reaching_scale_test.go @@ -0,0 +1,100 @@ +package core + +import ( + "fmt" + "testing" +) + +// reachingScaleGraph builds a linear method that writes every slot once and +// then loads each slot in rounds. It exercises the production slot API rather +// than the sparse solver internals. +func reachingScaleGraph(slots, rounds int) (*SemanticCFG, []struct { + op *OpCode + slot int +}) { + g := &SemanticCFG{ + order: map[*OpCode]int{}, + incoming: map[*OpCode][]int{}, + outgoing: map[*OpCode][]int{}, + slots: map[int]*slotDefinitions{}, + } + nodes := make([]*OpCode, 0, slots+slots*rounds) + add := func(opcode int, slot, offset int) *OpCode { + op := &OpCode{Instr: InstrInfos[opcode], CurrentOffset: uint16(offset), Data: []byte{byte(slot)}} + g.order[op] = len(nodes) + nodes = append(nodes, op) + return op + } + offset := 0 + for slot := 0; slot < slots; slot++ { + add(OP_ISTORE, slot, offset) + offset++ + } + loads := make([]struct { + op *OpCode + slot int + }, 0, slots*rounds) + for round := 0; round < rounds; round++ { + for slot := 0; slot < slots; slot++ { + loads = append(loads, struct { + op *OpCode + slot int + }{add(OP_ILOAD, slot, offset), slot}) + offset++ + } + } + g.Nodes = nodes + for index := 0; index+1 < len(nodes); index++ { + edge := len(g.Edges) + g.Edges = append(g.Edges, SemanticEdge{From: nodes[index], To: nodes[index+1], Kind: EdgeFallthrough}) + g.outgoing[nodes[index]] = append(g.outgoing[nodes[index]], edge) + g.incoming[nodes[index+1]] = append(g.incoming[nodes[index+1]], edge) + } + return g, loads +} + +func TestReachingScaleFactsStayOrdered(t *testing.T) { + g, loads := reachingScaleGraph(8, 4) + for _, load := range loads { + defs, _ := g.ReachingDefinitions(load.op, load.slot) + if len(defs) != 1 { + t.Fatalf("slot %d load defs = %v", load.slot, defOffsets(defs)) + } + if got := GetStoreIdx(defs[0]); got != load.slot { + t.Fatalf("slot %d load resolved store slot %d", load.slot, got) + } + } +} + +func BenchmarkReachingDefinitionsManySlots(b *testing.B) { + for _, size := range []int{8, 16, 32} { + b.Run(fmt.Sprintf("%dx%d", size, size), func(b *testing.B) { + g, loads := reachingScaleGraph(size, size) + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + g.slots = map[int]*slotDefinitions{} + for _, load := range loads { + if _, _ = g.ReachingDefinitions(load.op, load.slot); g.Err != nil { + b.Fatal(g.Err) + } + } + } + }) + } +} + +func BenchmarkReachingDefinitionsRepeatQuery(b *testing.B) { + g, loads := reachingScaleGraph(16, 16) + for _, load := range loads { + _, _ = g.ReachingDefinitions(load.op, load.slot) + } + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + load := loads[i%len(loads)] + if defs, _ := g.ReachingDefinitions(load.op, load.slot); len(defs) != 1 { + b.Fatalf("defs = %v", defOffsets(defs)) + } + } +} diff --git a/classparser/decompiler/core/reaching_slot_query_test.go b/classparser/decompiler/core/reaching_slot_query_test.go new file mode 100644 index 00000000..ff435537 --- /dev/null +++ b/classparser/decompiler/core/reaching_slot_query_test.go @@ -0,0 +1,144 @@ +package core + +import ( + "math/rand" + "testing" + + "github.com/yaklang/javajive/classparser/decompiler/core/values" +) + +// legacyReachingSlotStoreRefs is the map-returning form kept as an independent +// oracle for the early-exit query. It must not be used by production code. +func legacyReachingSlotStoreRefs(d *Decompiler, start *OpCode, slot int) map[string]*values.JavaRef { + out := map[string]*values.JavaRef{} + if start == nil { + return out + } + visited := map[*OpCode]bool{start: true} + queue := append([]*OpCode(nil), start.Source...) + for len(queue) > 0 { + cur := queue[0] + queue = queue[1:] + if cur == nil || visited[cur] { + continue + } + visited[cur] = true + if isLocalStoreOpcode(cur.Instr.OpCode) && GetStoreIdx(cur) == slot { + if refs, ok := d.opcodeIdToRef[cur]; ok && len(refs) > 0 { + if ref, ok2 := refs[len(refs)-1][0].(*values.JavaRef); ok2 && ref != nil { + out[ref.VarUid] = ref + } + } + continue + } + queue = append(queue, cur.Source...) + } + return out +} + +// The early-exit query must answer exactly like the map form followed by the +// repair predicate. Random graphs include branches, merges, duplicate refs, +// missing store refs, and reused scratch generations across queries. +func TestReachingSlotStoreRefUniqueMatchesMapQuery(t *testing.T) { + rng := rand.New(rand.NewSource(0x51a7)) + refs := []*values.JavaRef{{VarUid: "a"}, {VarUid: "b"}, {VarUid: "c"}} + for trial := 0; trial < 1500; trial++ { + n := 6 + rng.Intn(16) + nodes := make([]*OpCode, n) + for i := range nodes { + nodes[i] = &OpCode{Instr: &Instruction{OpCode: OP_NOP}} + } + for i := 0; i < n; i++ { + if rng.Intn(3) == 0 { + nodes[i].Instr = &Instruction{OpCode: OP_ISTORE} + nodes[i].Data = []byte{byte(rng.Intn(3))} + } + } + for i := 1; i < n; i++ { + for edge := 0; edge < 1+rng.Intn(2); edge++ { + nodes[i].Source = append(nodes[i].Source, nodes[rng.Intn(i)]) + } + } + d := &Decompiler{opcodeIdToRef: map[*OpCode][][2]any{}} + for _, node := range nodes { + if isLocalStoreOpcode(node.Instr.OpCode) && rng.Intn(2) == 0 { + ref := refs[rng.Intn(len(refs))] + d.opcodeIdToRef[node] = [][2]any{{ref, nil}} + } + } + start := nodes[n-1] + slot := rng.Intn(3) + for _, current := range append(append([]*values.JavaRef(nil), refs...), nil) { + legacy := legacyReachingSlotStoreRefs(d, start, slot) + var want *values.JavaRef + if len(legacy) == 1 { + for _, ref := range legacy { + if current == nil || ref.VarUid != current.VarUid { + want = ref + } + } + } + got := d.reachingSlotStoreRefUnique(start, slot, current) + if (got == nil) != (want == nil) || (got != nil && got.VarUid != want.VarUid) { + t.Fatalf("trial %d slot %d current %v: got %v want %v (map=%v)", trial, slot, current, got, want, legacy) + } + } + } +} + +// The production repair now answers from the sparse reaching facts whenever +// the SemanticCFG knows the opcode. This fixture has a branch merge with two +// definitions of slot 0, so the indexed solver and the structural Source walk +// must agree on both the unique and ambiguous cases. +func TestReachingSlotStoreRefDataflowMatchesStructuralWalk(t *testing.T) { + // 0 iconst_0; 1 istore_0; 2 iload_0; 3 ifeq +5 (target 8); + // 6 iconst_1; 7 istore_0; 8 iload_0; 9 ireturn. + d := auditCFG(t, []byte{ + OP_ICONST_0, OP_ISTORE_0, OP_ILOAD_0, OP_IFEQ, 0, 5, + OP_ICONST_1, OP_ISTORE_0, OP_ILOAD_0, OP_IRETURN, + }) + g, err := d.buildSemanticCFG() + if err != nil { + t.Fatal(err) + } + d.semanticCFG = g + // auditCFG only parses opcodes; the structural oracle reads Source edges, so + // materialize them from the same semantic edges the dataflow uses. + for _, edge := range g.Edges { + edge.From.Target = append(edge.From.Target, edge.To) + edge.To.Source = append(edge.To.Source, edge.From) + } + d.opcodeIdToRef = map[*OpCode][][2]any{} + refs := []*values.JavaRef{{VarUid: "a"}, {VarUid: "b"}} + nextRef := 0 + for _, op := range g.Nodes { + if op.Instr != nil && isLocalStoreOpcode(op.Instr.OpCode) { + ref := refs[nextRef%len(refs)] + nextRef++ + d.opcodeIdToRef[op] = [][2]any{{ref, nil}} + } + } + for _, load := range g.Nodes { + if load.Instr == nil || (!isLocalLoadOpcode(load.Instr.OpCode) && !isLocalStoreOpcode(load.Instr.OpCode)) { + continue + } + for slot := 0; slot < 2; slot++ { + for _, current := range append(append([]*values.JavaRef(nil), refs...), nil) { + legacy := legacyReachingSlotStoreRefs(d, load, slot) + var want *values.JavaRef + if len(legacy) == 1 { + for _, ref := range legacy { + if current == nil || ref.VarUid != current.VarUid { + want = ref + } + } + } + got := d.reachingSlotStoreRefUnique(load, slot, current) + if (got == nil) != (want == nil) || (got != nil && got.VarUid != want.VarUid) { + t.Fatalf("load@%d slot %d current %v: got %v want %v (structural=%v)", + load.CurrentOffset, slot, current, got, want, legacy) + } + } + } + } +} diff --git a/classparser/decompiler/core/semantic_cfg.go b/classparser/decompiler/core/semantic_cfg.go index 3ec33282..9bc4c320 100644 --- a/classparser/decompiler/core/semantic_cfg.go +++ b/classparser/decompiler/core/semantic_cfg.go @@ -4,6 +4,7 @@ import ( "fmt" "reflect" "sort" + "sync" "github.com/yaklang/javajive/classparser/decompiler/core/values" "github.com/yaklang/javajive/classparser/decompiler/core/values/types" @@ -57,6 +58,16 @@ type SemanticCFG struct { // analysis holds the T26 graph-analysis cache. SemanticCFG is immutable after // construction; epoch stays 0. Lazy-initialized on first GetOrCompute. analysis *graphAnalysisState + // adjacency caches immutable node indexes and deduplicated successor lists. + // Results are never exposed directly; analyses and test helpers receive clones. + adjacencyOnce sync.Once + nodeIndexes map[*OpCode]int + successors [2][][]int + // reaching owns the reusable sparse solver and graph-wide reachability for + // slot queries. Both are request-local and mutated by a single decompiler. + reaching *SparseReaching + reachable []bool + reachableOK bool } // MayThrowOpcode conservatively includes resolution/linkage, allocation, array, @@ -79,6 +90,12 @@ func (d *Decompiler) buildSemanticCFG() (*SemanticCFG, error) { if err := d.validateControlFlow(); err != nil { return nil, err } + return d.buildSemanticCFGUnchecked() +} + +// buildSemanticCFGUnchecked assumes the opcode stream was already validated and +// has not been rewritten since (JSR inlining invalidates that assumption). +func (d *Decompiler) buildSemanticCFGUnchecked() (*SemanticCFG, error) { g := &SemanticCFG{order: map[*OpCode]int{}, MaxUpdates: 1000000, incoming: map[*OpCode][]int{}, outgoing: map[*OpCode][]int{}, slots: map[int]*slotDefinitions{}, Work: d.Work, FunctionType: d.FunctionType} if d.FunctionContext != nil { g.IsStatic = d.FunctionContext.IsStatic @@ -737,11 +754,13 @@ func (g *SemanticCFG) recordIndexStats(stats ExceptionIndexStats) { } type definitionSet map[*OpCode]struct{} // nil is the stable method-entry definition -// Each slot is solved once on the immutable graph, then every load/store query is O(defs). -// This avoids repeated reverse walks and makes loop joins independent of DFS order. +// slotDefinitions holds one slot's facts. Production populates indexed from the +// sparse solver; legacy unit fixtures may populate in/reachable instead. type slotDefinitions struct { - in map[*OpCode]definitionSet - reachable map[*OpCode]bool + in map[*OpCode]definitionSet // legacy fixture representation + reachable map[*OpCode]bool // legacy fixture representation + indexed []defSet // production node-indexed immutable facts + reachableIndexed []bool } func (g *SemanticCFG) solveSlot(slot int) *slotDefinitions { @@ -754,57 +773,102 @@ func (g *SemanticCFG) solveSlot(slot int) *slotDefinitions { } func (g *SemanticCFG) sparseSolveToSlotDefs(slot int) *slotDefinitions { - facts := &slotDefinitions{in: map[*OpCode]definitionSet{}, reachable: map[*OpCode]bool{}} + facts := &slotDefinitions{} if g == nil || len(g.Nodes) == 0 { return facts } - s := NewSparseReaching(g) - if err := s.solve(slot); err != nil { + if g.reaching == nil { + g.reaching = NewSparseReaching(g) + } + beforeMerges := g.reaching.merges + arr, seen, err := g.reaching.solveFacts(slot) + g.SetWork += int(g.reaching.merges - beforeMerges) + if err != nil { if g.Err == nil { g.Err = err } + // Preserve the legacy failure view: the entry node still reports its + // live-in identity while g.Err fails the analysis closed. + if len(g.Nodes) > 0 { + facts.in = map[*OpCode]definitionSet{g.Nodes[0]: {nil: {}}} + facts.reachable = map[*OpCode]bool{g.Nodes[0]: true} + } return facts } - arr := s.in[slot] - reach := s.reach[slot] - g.SetWork += int(s.merges) + if !g.reachableOK { + g.reachable = make([]bool, len(g.Nodes)) + for _, node := range seen { + g.reachable[node] = true + } + g.reachableOK = true + } + indexed := make([]defSet, len(g.Nodes)) for i, set := range arr { if err := g.Work.Check(); err != nil { g.Err = err return facts } - n := g.Nodes[i] - if i >= len(reach) || !reach[i] { + if i >= len(g.reachable) || !g.reachable[i] { continue } + // Preserve the old pointer-map conversion's logical billing even though + // no pointer maps are allocated. if err := g.Work.Charge(workbudget.CounterSetElementWork, int64(len(set.ids))); err != nil { g.Err = err return facts } - ds := definitionSet{} - for _, id := range set.ids { - if id == entryDefID { - ds[nil] = struct{}{} - continue - } - if int(id) >= 0 && int(id) < len(g.Nodes) { - ds[g.Nodes[id]] = struct{}{} - } + indexed[i] = set + } + facts.indexed = indexed + facts.reachableIndexed = g.reachable + return facts +} + +// indexOfNodeCached resolves a node without allocating a per-query map and +// without forcing the T26 adjacency cache: reaching queries only need the +// construction-order index. +func (g *SemanticCFG) indexOfNodeCached(at *OpCode) (int, bool) { + if g == nil || at == nil { + return 0, false + } + if g.order != nil { + if index, ok := g.order[at]; ok { + return index, true } - facts.in[n] = ds - facts.reachable[n] = true + return 0, false } - if len(g.Nodes) > 0 && facts.in[g.Nodes[0]] == nil { - facts.in[g.Nodes[0]] = definitionSet{nil: {}} - facts.reachable[g.Nodes[0]] = true + for index, node := range g.Nodes { + if node == at { + return index, true + } } - return facts + return 0, false } // ReachingDefinitions returns definition identities in bytecode order, including // iinc's read/write identity. The separate entry flag is not a fabricated store. func (g *SemanticCFG) ReachingDefinitions(at *OpCode, slot int) ([]*OpCode, bool) { facts := g.solveSlot(slot) + if facts.indexed != nil { + index, ok := g.indexOfNodeCached(at) + if !ok || index < 0 || index >= len(facts.indexed) || + index >= len(facts.reachableIndexed) || !facts.reachableIndexed[index] { + return nil, false + } + set := facts.indexed[index] + out := make([]*OpCode, 0, len(set.ids)) + entry := false + for _, id := range set.ids { + if id == entryDefID { + entry = true + continue + } + if int(id) >= 0 && int(id) < len(g.Nodes) { + out = append(out, g.Nodes[id]) + } + } + return out, entry + } set := facts.in[at] out := make([]*OpCode, 0, len(set)) _, entry := set[nil] @@ -825,6 +889,19 @@ func (d *Decompiler) reachingStores(at *OpCode, slot int) ([]*OpCode, bool) { return reachingStoresOf(at, slot) } g := d.semanticCFG + // The indexed query already returns a fresh slice in bytecode order. Only + // the iinc chain needs the transitive map/sort fallback. + direct, directEntry := g.ReachingDefinitions(at, slot) + hasIncrement := false + for _, store := range direct { + if store.Instr != nil && store.Instr.OpCode == OP_IINC { + hasIncrement = true + break + } + } + if !hasIncrement { + return direct, directEntry + } pending := []*OpCode{at} seen := map[*OpCode]bool{} defs := map[*OpCode]bool{} diff --git a/classparser/decompiler/core/statements/util.go b/classparser/decompiler/core/statements/util.go index d29536d7..2bb17a7d 100644 --- a/classparser/decompiler/core/statements/util.go +++ b/classparser/decompiler/core/statements/util.go @@ -1,11 +1,15 @@ package statements -import "github.com/yaklang/javajive/classparser/decompiler/core/class_context" +import ( + "strings" + + "github.com/yaklang/javajive/classparser/decompiler/core/class_context" +) func StatementsString(statements []Statement, funcCtx *class_context.ClassContext) string { - var res string + var res strings.Builder for _, statement := range statements { - res += statement.String(funcCtx) + res.WriteString(statement.String(funcCtx)) } - return res + return res.String() } diff --git a/classparser/decompiler/core/t09_reducibility.go b/classparser/decompiler/core/t09_reducibility.go index cdd6544a..fecc11f6 100644 --- a/classparser/decompiler/core/t09_reducibility.go +++ b/classparser/decompiler/core/t09_reducibility.go @@ -25,15 +25,9 @@ func (g *SemanticCFG) indexOfNode(n *OpCode) int { if n == nil { return -1 } - if g.order != nil { - if i, ok := g.order[n]; ok { - return i - } - } - for i, node := range g.Nodes { - if node == n { - return i - } + g.initAdjacency() + if i, ok := g.nodeIndexes[n]; ok { + return i } return -1 } diff --git a/classparser/decompiler/core/t10_exception_regions.go b/classparser/decompiler/core/t10_exception_regions.go index 8905b3f8..acdfcd5a 100644 --- a/classparser/decompiler/core/t10_exception_regions.go +++ b/classparser/decompiler/core/t10_exception_regions.go @@ -38,12 +38,24 @@ func (g *SemanticCFG) ExceptionEdgeIdentities() []ExceptionEdgeIdentity { return out } +// exceptionRankSpan is an inclusive range in may-throw instruction rank order. +// Protected PC sets are contiguous in that order, so comparing a few spans is +// equivalent to comparing every protected PC. +type exceptionRankSpan struct { + start int + end int +} + type handlerCoverage struct { order int to *OpCode - pcs map[uint16]struct{} - min uint16 - max uint16 + ranks map[int]struct{} + spans []exceptionRankSpan +} + +type handlerCoverageKey struct { + order int + to *OpCode } // ValidateExceptionRegions rejects protected ranges that overlap without being @@ -54,45 +66,98 @@ func (g *SemanticCFG) ValidateExceptionRegions() error { if g == nil || len(g.Edges) == 0 { return nil } - byKey := map[string]*handlerCoverage{} - orderKeys := []string{} + // Map protected PCs to their order among may-throw instructions. Within a + // protected range those instructions are consecutive, which lets each + // handler coverage collapse to a handful of rank spans. + pcSet := map[uint16]struct{}{} + for _, e := range g.Edges { + if e.Kind == EdgeException && e.From != nil { + pcSet[e.From.CurrentOffset] = struct{}{} + } + } + pcs := make([]int, 0, len(pcSet)) + for pc := range pcSet { + pcs = append(pcs, int(pc)) + } + sort.Ints(pcs) + rankOf := make(map[uint16]int, len(pcs)) + for rank, pc := range pcs { + rankOf[uint16(pc)] = rank + } + + byKey := map[handlerCoverageKey]*handlerCoverage{} + keys := make([]handlerCoverageKey, 0) for _, e := range g.Edges { if e.Kind != EdgeException || e.From == nil || e.To == nil { continue } - key := fmt.Sprintf("%d:%p", e.HandlerOrder, e.To) + key := handlerCoverageKey{order: e.HandlerOrder, to: e.To} cov, ok := byKey[key] if !ok { - cov = &handlerCoverage{ - order: e.HandlerOrder, - to: e.To, - pcs: map[uint16]struct{}{}, - min: e.From.CurrentOffset, - max: e.From.CurrentOffset, - } + cov = &handlerCoverage{order: e.HandlerOrder, to: e.To, ranks: map[int]struct{}{}} byKey[key] = cov - orderKeys = append(orderKeys, key) + keys = append(keys, key) + } + rank, ok := rankOf[e.From.CurrentOffset] + if !ok { + continue } - pc := e.From.CurrentOffset - cov.pcs[pc] = struct{}{} - if pc < cov.min { - cov.min = pc + cov.ranks[rank] = struct{}{} + } + targetIndex := func(to *OpCode) int { + if index, ok := g.order[to]; ok { + return index + } + return len(g.Nodes) + } + sort.Slice(keys, func(i, j int) bool { + if keys[i].order != keys[j].order { + return keys[i].order < keys[j].order + } + return targetIndex(keys[i].to) < targetIndex(keys[j].to) + }) + for _, key := range keys { + cov := byKey[key] + ranks := make([]int, 0, len(cov.ranks)) + for rank := range cov.ranks { + ranks = append(ranks, rank) + } + sort.Ints(ranks) + for _, rank := range ranks { + if n := len(cov.spans); n > 0 && rank == cov.spans[n-1].end+1 { + cov.spans[n-1].end = rank + continue + } + cov.spans = append(cov.spans, exceptionRankSpan{start: rank, end: rank}) + } + } + // Most handlers cover exactly one contiguous range. Detect crossings among + // those with a single endpoint sweep instead of comparing every handler + // pair. Handlers with several disjoint ranges fall back to exact pairwise + // span comparison, which is bounded by their (small) range count. + allSingle := true + for _, key := range keys { + if len(byKey[key].spans) != 1 { + allSingle = false + break } - if pc > cov.max { - cov.max = pc + } + if allSingle { + if a, b, ok := crossingSingleSpanCoverage(keys, byKey); ok { + return fmt.Errorf("unsupported_overlapping_protected_ranges: region near PC %d (handlers %d and %d)", pcs[byKey[a].spans[0].start], byKey[a].order, byKey[b].order) } + return nil } - sort.Strings(orderKeys) - for i := 0; i < len(orderKeys); i++ { - a := byKey[orderKeys[i]] - for j := i + 1; j < len(orderKeys); j++ { - b := byKey[orderKeys[j]] + for i := 0; i < len(keys); i++ { + a := byKey[keys[i]] + for j := i + 1; j < len(keys); j++ { + b := byKey[keys[j]] if !exceptionCoveragesCross(a, b) { continue } - pc := a.min - if b.min < pc { - pc = b.min + pc := uint16(pcs[a.spans[0].start]) + if bStart := pcs[b.spans[0].start]; bStart < int(pc) { + pc = uint16(bStart) } return fmt.Errorf("unsupported_overlapping_protected_ranges: region near PC %d (handlers %d and %d)", pc, a.order, b.order) } @@ -100,30 +165,158 @@ func (g *SemanticCFG) ValidateExceptionRegions() error { return nil } -func exceptionCoveragesCross(a, b *handlerCoverage) bool { - if a == nil || b == nil || len(a.pcs) == 0 || len(b.pcs) == 0 { - return false +type maxEndHeap []int + +func (h *maxEndHeap) push(value int) { + *h = append(*h, value) + index := len(*h) - 1 + for index > 0 { + parent := (index - 1) / 2 + if (*h)[parent] >= (*h)[index] { + break + } + (*h)[parent], (*h)[index] = (*h)[index], (*h)[parent] + index = parent } - aSub, bSub, overlap := false, false, false - for pc := range a.pcs { - if _, ok := b.pcs[pc]; ok { - overlap = true - } else { - bSub = true +} + +func (h *maxEndHeap) pop() int { + top := (*h)[0] + last := len(*h) - 1 + (*h)[0] = (*h)[last] + *h = (*h)[:last] + index := 0 + for { + left, right := index*2+1, index*2+2 + largest := index + if left < len(*h) && (*h)[left] > (*h)[largest] { + largest = left + } + if right < len(*h) && (*h)[right] > (*h)[largest] { + largest = right } + if largest == index { + break + } + (*h)[index], (*h)[largest] = (*h)[largest], (*h)[index] + index = largest + } + return top +} + +// crossingSingleSpanCoverage reports the first crossing pair when every +// handler has one span. Intervals that start at the same rank are nested with +// respect to each other, so only an earlier-starting live interval whose end +// falls short of the group's maximum end can cross. +func crossingSingleSpanCoverage(keys []handlerCoverageKey, byKey map[handlerCoverageKey]*handlerCoverage) (handlerCoverageKey, handlerCoverageKey, bool) { + type entry struct { + key handlerCoverageKey + start int + end int } - for pc := range b.pcs { - if _, ok := a.pcs[pc]; !ok { - aSub = true - } else { - overlap = true + entries := make([]entry, 0, len(keys)) + for _, key := range keys { + span := byKey[key].spans[0] + entries = append(entries, entry{key: key, start: span.start, end: span.end}) + } + sort.Slice(entries, func(i, j int) bool { + if entries[i].start != entries[j].start { + return entries[i].start < entries[j].start + } + return entries[i].end < entries[j].end + }) + var active maxEndHeap + var activeKey handlerCoverageKey + haveActiveKey := false + for index := 0; index < len(entries); { + start := entries[index].start + groupEnd := index + groupMax := -1 + var groupMaxKey handlerCoverageKey + for groupEnd < len(entries) && entries[groupEnd].start == start { + if entries[groupEnd].end > groupMax { + groupMax = entries[groupEnd].end + groupMaxKey = entries[groupEnd].key + } + groupEnd++ + } + if len(active) > 0 && active[0] < start { + // Every remaining active interval ends before this group starts. + active = active[:0] + haveActiveKey = false + } + if len(active) > 0 && active[0] < groupMax { + // The longest live interval starts earlier but ends inside this + // group while the group extends beyond it: neither contains the + // other. + if !haveActiveKey { + return groupMaxKey, groupMaxKey, true + } + return activeKey, groupMaxKey, true } + prevTop := -1 + if len(active) > 0 { + prevTop = active[0] + } + for _, item := range entries[index:groupEnd] { + active.push(item.end) + } + if !haveActiveKey || groupMax > prevTop { + activeKey = groupMaxKey + haveActiveKey = true + } + index = groupEnd } - if !overlap { + return handlerCoverageKey{}, handlerCoverageKey{}, false +} + +func exceptionCoveragesCross(a, b *handlerCoverage) bool { + if a == nil || b == nil || len(a.spans) == 0 || len(b.spans) == 0 { return false } - if !aSub || !bSub { + if !spansOverlap(a.spans, b.spans) { return false } + // Crossing means the coverages intersect but neither contains the other. + return !spansCover(b.spans, a.spans) && !spansCover(a.spans, b.spans) +} + +func spansOverlap(a, b []exceptionRankSpan) bool { + i, j := 0, 0 + for i < len(a) && j < len(b) { + if a[i].end < b[j].start { + i++ + continue + } + if b[j].end < a[i].start { + j++ + continue + } + return true + } + return false +} + +// spansCover reports whether outer covers every rank in inner. Both inputs are +// sorted, disjoint, and merged. +func spansCover(outer, inner []exceptionRankSpan) bool { + j := 0 + for _, span := range inner { + covered := span.start + for covered <= span.end { + for j < len(outer) && outer[j].end < covered { + j++ + } + if j >= len(outer) || outer[j].start > covered { + return false + } + if outer[j].end >= span.end { + covered = span.end + 1 + break + } + covered = outer[j].end + 1 + j++ + } + } return true } diff --git a/classparser/decompiler/core/t25_sparse_dataflow.go b/classparser/decompiler/core/t25_sparse_dataflow.go index 16752d3b..bdf6d29c 100644 --- a/classparser/decompiler/core/t25_sparse_dataflow.go +++ b/classparser/decompiler/core/t25_sparse_dataflow.go @@ -3,9 +3,6 @@ package core import ( "fmt" "math" - "sort" - "strconv" - "strings" "github.com/yaklang/javajive/internal/workbudget" ) @@ -20,26 +17,6 @@ type defSet struct { ids []reachingDefID // sorted, unique } -func (s defSet) clone() defSet { - if len(s.ids) == 0 { - return defSet{} - } - out := make([]reachingDefID, len(s.ids)) - copy(out, s.ids) - return defSet{ids: out} -} - -func (s defSet) key() string { - if len(s.ids) == 0 { - return "" - } - parts := make([]string, len(s.ids)) - for i, id := range s.ids { - parts[i] = strconv.Itoa(int(id)) - } - return strings.Join(parts, ",") -} - func addInt64(a, b int64) int64 { if a < 0 { a = 0 @@ -75,16 +52,51 @@ func unionDef(a, b defSet, work *workbudget.Budget, merges *uint64) (defSet, boo if err := chargeSetWork(work, need); err != nil { return defSet{}, false, err } - out := make([]reachingDefID, 0, len(a.ids)+len(b.ids)) + // Determine whether the union grows before allocating. Reaching joins + // usually re-propagate an already-covered set to a loop predecessor; the + // temporary merged slice used to be allocated and immediately discarded. i, j := 0, 0 - changed := false + aOnly, bOnly := 0, 0 + unionSize := 0 + for i < len(a.ids) || j < len(b.ids) { + switch { + case i == len(a.ids): + j++ + bOnly++ + case j == len(b.ids): + i++ + aOnly++ + case a.ids[i] == b.ids[j]: + i++ + j++ + case a.ids[i] < b.ids[j]: + i++ + aOnly++ + default: + j++ + bOnly++ + } + unionSize++ + } + if merges != nil { + *merges += uint64(unionSize) + } + if bOnly == 0 { + return a, false, nil + } + if aOnly == 0 { + // a is a subset of b, so the merged result is exactly b. Share the + // immutable incoming set instead of rebuilding an identical slice. + return b, true, nil + } + out := make([]reachingDefID, 0, unionSize) + i, j = 0, 0 for i < len(a.ids) || j < len(b.ids) { var pick reachingDefID switch { case i == len(a.ids): pick = b.ids[j] j++ - changed = true case j == len(b.ids): pick = a.ids[i] i++ @@ -98,14 +110,10 @@ func unionDef(a, b defSet, work *workbudget.Budget, merges *uint64) (defSet, boo default: pick = b.ids[j] j++ - changed = true - } - if merges != nil { - *merges++ } out = append(out, pick) } - return defSet{ids: out}, changed, nil + return defSet{ids: out}, true, nil } func singletonDef(id reachingDefID) defSet { @@ -133,27 +141,29 @@ func transferReaching(slot int, nodeIdx int, writeSlot, writeWidth int, defWidth if err := chargeSetWork(work, n); err != nil { return defSet{}, err } - out := make([]reachingDefID, 0, len(before.ids)+1) - sawNil := false + // A narrow write over the tail of a wide slot invalidates the wide + // definitions and leaves the entry/live-in marker. Without a wide + // definition the write changes nothing, and the immutable input set can + // be shared instead of copied. + sawWide := false for _, id := range before.ids { if defWidth(id) == 2 { - sawNil = true - continue + sawWide = true + break } - out = append(out, id) } - if sawNil { - out = append([]reachingDefID{entryDefID}, out...) - sort.Slice(out, func(i, j int) bool { return out[i] < out[j] }) - u := out[:0] - var last reachingDefID - for i, id := range out { - if i == 0 || id != last { - u = append(u, id) - last = id - } + if !sawWide { + return before, nil + } + // entryDefID is -1 and ids are sorted, so prepending the marker and + // filtering once yields the same sorted, deduplicated set without sort. + out := make([]reachingDefID, 0, len(before.ids)+1) + out = append(out, entryDefID) + for _, id := range before.ids { + if id == entryDefID || defWidth(id) == 2 { + continue } - out = u + out = append(out, id) } return defSet{ids: out}, nil } @@ -163,13 +173,23 @@ func transferReaching(slot int, nodeIdx int, writeSlot, writeWidth int, defWidth // SparseReaching is a per-slot reaching-definition solver with identity-set // sharing, query copies, and insert charging. Production solveSlot uses this. type SparseReaching struct { - g *SemanticCFG - in map[int][]defSet // slot -> per-node facts - reach map[int][]bool - ready map[int]bool - merges uint64 - visits uint64 - queryCache map[queryKey]cachedQuery + g *SemanticCFG + in map[int][]defSet // slot -> per-node facts + reach map[int][]bool + ready map[int]bool + merges uint64 + visits uint64 + // chargedQueries remembers which (slot,node) pairs already paid the + // definition-set query charge. It deliberately does not retain a second + // []*OpCode copy of the facts; callers still receive a fresh slice. + chargedQueries map[queryKey]struct{} + // Scratch state reused across sequential slot solves. Generation stamps + // avoid clearing O(nodes) arrays for every slot. + reachStamp []uint32 + queueStamp []uint32 + generation uint32 + queue []int + seen []int } type queryKey struct { @@ -177,20 +197,22 @@ type queryKey struct { node int } -type cachedQuery struct { - defs []*OpCode - entry bool -} - // NewSparseReaching binds to an immutable SemanticCFG snapshot and charges // g.Work (nil Work is unlimited). func NewSparseReaching(g *SemanticCFG) *SparseReaching { - return &SparseReaching{ - g: g, - in: map[int][]defSet{}, - reach: map[int][]bool{}, - ready: map[int]bool{}, - queryCache: map[queryKey]cachedQuery{}, + // The production path uses solveFacts and never touches these maps, so they + // are allocated only when the query API needs them. + return &SparseReaching{g: g} +} + +func (s *SparseReaching) ensureQueryMaps() { + if s.in == nil { + s.in = map[int][]defSet{} + s.reach = map[int][]bool{} + s.ready = map[int]bool{} + } + if s.chargedQueries == nil { + s.chargedQueries = map[queryKey]struct{}{} } } @@ -240,6 +262,7 @@ func (s *SparseReaching) entryFact(slot int) defSet { } func (s *SparseReaching) solve(slot int) error { + s.ensureQueryMaps() if s.ready[slot] { return nil } @@ -248,16 +271,37 @@ func (s *SparseReaching) solve(slot int) error { s.ready[slot] = true return nil } + facts, seen, err := s.solveFacts(slot) + if err != nil { + return err + } + reachable := make([]bool, len(g.Nodes)) + for _, node := range seen { + reachable[node] = true + } + s.in[slot] = facts + s.reach[slot] = reachable + s.ready[slot] = true + return nil +} + +// solveFacts runs the per-slot fixed point and returns node-indexed immutable +// facts. The seen list is scratch owned by the solver; callers that retain +// reachability must copy it before the next solve. +func (s *SparseReaching) solveFacts(slot int) ([]defSet, []int, error) { + g := s.g + if g == nil || len(g.Nodes) == 0 { + return nil, nil, nil + } n := len(g.Nodes) // Bill one slot at a time so MaxSetElementWork L-1/L/L+1 can trip with // Used>0 and Used<=L. A single Charge(n) against L 0 && g.Updates >= g.MaxUpdates { g.Err = fmt.Errorf("analysis_budget_exceeded: reaching definitions after %d updates", g.Updates) - return g.Err + return nil, nil, g.Err } - idx := queue[head] - queued[idx] = false + idx := s.queue[head] + s.queueStamp[idx] = 0 s.visits++ g.Updates++ if err := g.Work.Charge(workbudget.CounterAnalysisUpdates, 1); err != nil { g.Err = err - return err + return nil, nil, err } op := g.Nodes[idx] before := facts[idx] @@ -292,7 +348,7 @@ func (s *SparseReaching) solve(slot int) error { }, before, g.Work) if err != nil { g.Err = err - return err + return nil, nil, err } if g.outgoing == nil { continue @@ -307,33 +363,33 @@ func (s *SparseReaching) solve(slot int) error { if !ok { continue } - changed := !reachable[to] - reachable[to] = true + changed := s.reachStamp[to] != gen + if changed { + s.reachStamp[to] = gen + s.seen = append(s.seen, to) + } merged, grew, err := unionDef(facts[to], state, g.Work, &s.merges) if err != nil { g.Err = err - return err + return nil, nil, err } if grew { facts[to] = merged changed = true - } else if facts[to].ids == nil && reachable[to] && len(state.ids) == 0 { + } else if facts[to].ids == nil && len(state.ids) == 0 { facts[to] = defSet{} } - if changed && !queued[to] { + if changed && s.queueStamp[to] != gen { if err := g.Work.Check(); err != nil { g.Err = err - return err + return nil, nil, err } - queued[to] = true - queue = append(queue, to) + s.queueStamp[to] = gen + s.queue = append(s.queue, to) } } } - s.in[slot] = facts - s.reach[slot] = reachable - s.ready[slot] = true - return nil + return facts, s.seen, nil } // Definitions returns reaching stores at `at` for `slot`, including the entry @@ -354,12 +410,9 @@ func (s *SparseReaching) Definitions(at *OpCode, slot int) ([]*OpCode, bool, err return nil, false, nil } } + s.ensureQueryMaps() key := queryKey{slot: slot, node: node} - if cached, hit := s.queryCache[key]; hit { - cp := make([]*OpCode, len(cached.defs)) - copy(cp, cached.defs) - return cp, cached.entry, nil - } + _, charged := s.chargedQueries[key] if err := s.solve(slot); err != nil { return nil, false, err } @@ -368,9 +421,14 @@ func (s *SparseReaching) Definitions(at *OpCode, slot int) ([]*OpCode, bool, err return nil, false, nil } set := facts[node] - if err := chargeSetWork(s.work(), int64(len(set.ids))); err != nil { - return nil, false, err + if !charged { + if err := chargeSetWork(s.work(), int64(len(set.ids))); err != nil { + return nil, false, err + } + s.chargedQueries[key] = struct{}{} } + // Definition ids are SemanticCFG node indexes kept in sorted order, so + // translating them in place already yields bytecode order. out := make([]*OpCode, 0, len(set.ids)) entry := false for _, id := range set.ids { @@ -382,11 +440,7 @@ func (s *SparseReaching) Definitions(at *OpCode, slot int) ([]*OpCode, bool, err out = append(out, s.g.Nodes[id]) } } - sort.Slice(out, func(i, j int) bool { return s.g.order[out[i]] < s.g.order[out[j]] }) - s.queryCache[key] = cachedQuery{defs: out, entry: entry} - cp := make([]*OpCode, len(out)) - copy(cp, out) - return cp, entry, nil + return out, entry, nil } func defOffsets(defs []*OpCode) []uint16 { diff --git a/classparser/decompiler/core/t26_graph_cache.go b/classparser/decompiler/core/t26_graph_cache.go index c22dec7d..3bebc39d 100644 --- a/classparser/decompiler/core/t26_graph_cache.go +++ b/classparser/decompiler/core/t26_graph_cache.go @@ -190,6 +190,15 @@ func cloneAnalysis(a *GraphAnalysis) *GraphAnalysis { } func (c *GraphAnalysisCache) getOrCompute(graphID, epoch uint64, kind AnalysisKind, domain GraphAnalysisDomain, succs [][]int) *GraphAnalysis { + return cloneAnalysis(c.getOrComputeShared(graphID, epoch, kind, domain, succs)) +} + +// getOrComputeShared returns the cache-owned immutable snapshot without the +// defensive deep copy GetOrCompute performs. It is for scalar queries +// (Dominates / PostDominates) that only read the result. The returned snapshot +// must not be mutated or embedded in caller-visible state; holding the pointer +// across eviction is safe because the value itself is never mutated. +func (c *GraphAnalysisCache) getOrComputeShared(graphID, epoch uint64, kind AnalysisKind, domain GraphAnalysisDomain, succs [][]int) *GraphAnalysis { key := cacheKey{ graphID: graphID, epoch: epoch, @@ -201,7 +210,7 @@ func (c *GraphAnalysisCache) getOrCompute(graphID, epoch uint64, kind AnalysisKi defer c.mu.Unlock() if ent, ok := c.entries[key]; ok { c.lru.MoveToFront(ent.el) - return cloneAnalysis(ent.val) + return ent.val } n := len(succs) var computed *GraphAnalysis @@ -244,7 +253,7 @@ func (c *GraphAnalysisCache) getOrCompute(graphID, epoch uint64, kind AnalysisKi if c.lru.Len() > c.capacity { c.evictTailLocked() } - return cloneAnalysis(computed) + return computed } func (g *SemanticCFG) analysisState() *graphAnalysisState { @@ -280,53 +289,93 @@ func (g *SemanticCFG) AnalysisNodesTouched() int64 { return g.analysis.cache.NodesTouched() } -func (g *SemanticCFG) nodeIndexMap() map[*OpCode]int { - m := make(map[*OpCode]int, len(g.Nodes)) - if g.order != nil && len(g.order) == len(g.Nodes) { - for n, i := range g.order { - m[n] = i +func (g *SemanticCFG) initAdjacency() { + g.adjacencyOnce.Do(func() { + idx := make(map[*OpCode]int, len(g.Nodes)) + if g.order != nil && len(g.order) == len(g.Nodes) { + for n, i := range g.order { + idx[n] = i + } + } else { + for i, n := range g.Nodes { + idx[n] = i + } } - return m - } - for i, n := range g.Nodes { - m[n] = i + g.nodeIndexes = idx + for mode := range g.successors { + includeException := mode == 1 + succs := make([][]int, len(g.Nodes)) + seen := make([]map[int]struct{}, len(g.Nodes)) + for _, e := range g.Edges { + if !includeException && e.Kind == EdgeException { + continue + } + u, ok1 := idx[e.From] + v, ok2 := idx[e.To] + if !ok1 || !ok2 { + continue + } + if seen[u] == nil { + seen[u] = map[int]struct{}{} + } + if _, dup := seen[u][v]; dup { + continue + } + seen[u][v] = struct{}{} + succs[u] = append(succs[u], v) + } + g.successors[mode] = succs + } + }) +} + +func (g *SemanticCFG) nodeIndexMap() map[*OpCode]int { + g.initAdjacency() + out := make(map[*OpCode]int, len(g.nodeIndexes)) + for node, index := range g.nodeIndexes { + out[node] = index } - return m + return out } -func (g *SemanticCFG) successorIndexLists(includeException bool) [][]int { - n := len(g.Nodes) - succs := make([][]int, n) - if n == 0 { - return succs +func cloneIndexLists(in [][]int) [][]int { + out := make([][]int, len(in)) + for i := range in { + out[i] = append([]int(nil), in[i]...) } - idx := g.nodeIndexMap() - seen := make([]map[int]struct{}, n) - for _, e := range g.Edges { - if !includeException && e.Kind == EdgeException { - continue - } - u, ok1 := idx[e.From] - v, ok2 := idx[e.To] - if !ok1 || !ok2 { - continue - } - if seen[u] == nil { - seen[u] = map[int]struct{}{} - } - if _, dup := seen[u][v]; dup { - continue - } - seen[u][v] = struct{}{} - succs[u] = append(succs[u], v) + return out +} + +func (g *SemanticCFG) cachedSuccessorIndexLists(includeException bool) [][]int { + g.initAdjacency() + if includeException { + return g.successors[1] } - return succs + return g.successors[0] +} + +func (g *SemanticCFG) successorIndexLists(includeException bool) [][]int { + return cloneIndexLists(g.cachedSuccessorIndexLists(includeException)) } // GetOrCompute returns a copied analysis snapshot for this immutable CFG. func (g *SemanticCFG) GetOrCompute(kind AnalysisKind, domain GraphAnalysisDomain) *GraphAnalysis { st := g.analysisState() - return st.cache.getOrCompute(st.id, 0, kind, domain, g.successorIndexLists(domain.IncludeException)) + return st.cache.getOrCompute(st.id, 0, kind, domain, g.cachedSuccessorIndexLists(domain.IncludeException)) +} + +// Dominates is the scalar query used by proofs that only need a yes/no answer. +// It reuses the cache-owned analysis and allocates nothing; callers must not use +// it to obtain mutable analysis arrays. +func (g *SemanticCFG) Dominates(dominator, node int) bool { + if g == nil || dominator < 0 || node < 0 { + return false + } + st := g.analysisState() + analysis := st.cache.getOrComputeShared(st.id, 0, AnalysisDominators, + GraphAnalysisDomain{Roots: []int{0}, IncludeException: true}, + g.cachedSuccessorIndexLists(true)) + return analysis != nil && analysis.Dominates(dominator, node) } // Dominates reports whether dominator dominates node in this snapshot. @@ -389,9 +438,36 @@ func uniqueInts(in []int) []int { return out } +type dominatorScratch struct { + reach []bool + stack []int + filtered []int + succs2 [][]int + preds [][]int + rpoIndex []int + idom2 []int + color []uint8 + post []int + frames []rpoFrame +} + +type rpoFrame struct{ u, i int } + +var dominatorScratchPool = sync.Pool{New: func() any { return &dominatorScratch{} }} + func reachableFrom(n int, succs [][]int, roots []int) []bool { - mark := make([]bool, n) - stack := make([]int, 0, n) + mark, _ := reachableFromInto(n, succs, roots, nil, nil) + return mark +} + +func reachableFromInto(n int, succs [][]int, roots []int, mark []bool, stack []int) ([]bool, []int) { + if cap(mark) < n { + mark = make([]bool, n) + } else { + mark = mark[:n] + clear(mark) + } + stack = stack[:0] for _, r := range roots { if r >= 0 && r < n && !mark[r] { mark[r] = true @@ -408,18 +484,31 @@ func reachableFrom(n int, succs [][]int, roots []int) []bool { } } } - return mark + return mark, stack } func reversePostorder(n int, succs [][]int, starts []int) []int { - color := make([]uint8, n) - post := make([]int, 0, n) - type frame struct{ u, i int } + return reversePostorderInto(n, succs, starts, &dominatorScratch{}) +} + +func reversePostorderInto(n int, succs [][]int, starts []int, scratch *dominatorScratch) []int { + if scratch == nil { + scratch = &dominatorScratch{} + } + color := scratch.color + if cap(color) < n { + color = make([]uint8, n) + } else { + color = color[:n] + clear(color) + } + post := scratch.post[:0] + stack := scratch.frames[:0] for _, s := range starts { if s < 0 || s >= n || color[s] != 0 { continue } - stack := []frame{{s, 0}} + stack = append(stack, rpoFrame{s, 0}) color[s] = 1 for len(stack) > 0 { top := &stack[len(stack)-1] @@ -428,7 +517,7 @@ func reversePostorder(n int, succs [][]int, starts []int) []int { top.i++ if v >= 0 && v < n && color[v] == 0 { color[v] = 1 - stack = append(stack, frame{v, 0}) + stack = append(stack, rpoFrame{v, 0}) } continue } @@ -440,9 +529,30 @@ func reversePostorder(n int, succs [][]int, starts []int) []int { for i, j := 0, len(post)-1; i < j; i, j = i+1, j-1 { post[i], post[j] = post[j], post[i] } + scratch.color = color + scratch.post = post + scratch.frames = stack return post } +func resizeIntLists(lists [][]int, n int) [][]int { + if cap(lists) < n { + return make([][]int, n) + } + lists = lists[:n] + for i := range lists { + lists[i] = lists[i][:0] + } + return lists +} + +func resizeIntSlice(values []int, n int) []int { + if cap(values) < n { + return make([]int, n) + } + return values[:n] +} + // computeImmediateDominators is the cached Lengauer-style iterative IDom // (Cooper/Harvey/Kennedy). A virtual source is used only when the domain has // multiple roots. @@ -454,20 +564,25 @@ func computeImmediateDominators(n int, succs [][]int, roots []int) []int { if n == 0 { return idom } + scratch := dominatorScratchPool.Get().(*dominatorScratch) + defer dominatorScratchPool.Put(scratch) roots = uniqueInts(roots) - reach := reachableFrom(n, succs, roots) - filtered := make([]int, 0, len(roots)) + reach, stack := reachableFromInto(n, succs, roots, scratch.reach, scratch.stack) + scratch.reach, scratch.stack = reach, stack[:0] + filtered := scratch.filtered[:0] for _, r := range roots { if r >= 0 && r < n && reach[r] { filtered = append(filtered, r) } } + scratch.filtered = filtered[:0] if len(filtered) == 0 { return idom } vs := n total := n + 1 - succs2 := make([][]int, total) + succs2 := resizeIntLists(scratch.succs2, total) + scratch.succs2 = succs2 for i := 0; i < n; i++ { if !reach[i] { continue @@ -478,22 +593,26 @@ func computeImmediateDominators(n int, succs [][]int, roots []int) []int { } } } - succs2[vs] = append([]int(nil), filtered...) - preds := make([][]int, total) + succs2[vs] = append(succs2[vs][:0], filtered...) + preds := resizeIntLists(scratch.preds, total) + scratch.preds = preds for u := 0; u < total; u++ { for _, v := range succs2[u] { preds[v] = append(preds[v], u) } } - rpo := reversePostorder(total, succs2, []int{vs}) - rpoIndex := make([]int, total) + start := [1]int{vs} + rpo := reversePostorderInto(total, succs2, start[:], scratch) + rpoIndex := resizeIntSlice(scratch.rpoIndex, total) + scratch.rpoIndex = rpoIndex for i := range rpoIndex { rpoIndex[i] = -1 } for i, u := range rpo { rpoIndex[u] = i } - idom2 := make([]int, total) + idom2 := resizeIntSlice(scratch.idom2, total) + scratch.idom2 = idom2 for i := range idom2 { idom2[i] = -1 } @@ -787,6 +906,16 @@ type MutableAnalysisGraph struct { n int edges []mutableEdge cache *GraphAnalysisCache + // Successor index lists are derived from edges and are rebuilt only when + // the epoch changes. Scalar Dominates/PostDominates queries would otherwise + // rebuild the same lists on every call. + succNormal [][]int + succException [][]int + succValid bool + // Scratch arrays reused by buildSuccessorIndexLists across topology epochs. + countsScratch []int + stampScratch []uint64 + markScratch []uint64 } type mutableEdge struct { @@ -806,12 +935,29 @@ func NewMutableAnalysisGraph(nodes int, cache *GraphAnalysisCache) *MutableAnaly } } -func (m *MutableAnalysisGraph) bump() { m.epoch++ } +func (m *MutableAnalysisGraph) bump() { + m.epoch++ + m.succValid = false +} // Epoch is the mutation counter; any add/delete/replace of a node or edge misses // previously cached results. func (m *MutableAnalysisGraph) Epoch() uint64 { return m.epoch } +// Reset discards every edge and sets a new node count while preserving the +// graph identity and reusable scratch storage. The epoch advances, so cached +// analyses for the previous topology remain distinct even if it is later +// evicted from the LRU. +func (m *MutableAnalysisGraph) Reset(nodes int) { + if nodes < 0 { + nodes = 0 + } + m.n = nodes + m.edges = m.edges[:0] + m.epoch++ + m.succValid = false +} + func (m *MutableAnalysisGraph) AddNode() int { id := m.n m.n++ @@ -853,24 +999,92 @@ func (m *MutableAnalysisGraph) ReplaceNode(id int) int { } func (m *MutableAnalysisGraph) successorIndexLists(includeException bool) [][]int { - succs := make([][]int, m.n) - seen := make([]map[int]struct{}, m.n) + if !m.succValid { + m.succNormal = m.buildSuccessorIndexLists(false) + m.succException = m.buildSuccessorIndexLists(true) + m.succValid = true + } + if includeException { + return m.succException + } + return m.succNormal +} + +func (m *MutableAnalysisGraph) buildSuccessorIndexLists(includeException bool) [][]int { + // The previous implementation allocated one dedupe map per source node and + // let every successor list grow by append. Statement dominance rebuilds this + // table after each topology change, so on a loop-heavy method those maps + // dominated the analysis allocation. Count first to size each list exactly, + // then dedupe with generation stamps over two flat arrays. The successor + // table, counts, and stamps are reused across epochs; no analysis result + // retains them after computation. + n := m.n + outer := &m.succNormal + if includeException { + outer = &m.succException + } + succs := *outer + if cap(succs) < n { + succs = make([][]int, n) + } else { + succs = succs[:n] + for i := range succs { + succs[i] = succs[i][:0] + } + } + if cap(m.countsScratch) < n { + m.countsScratch = make([]int, n) + } else { + m.countsScratch = m.countsScratch[:n] + clear(m.countsScratch) + } + counts := m.countsScratch for _, e := range m.edges { if !includeException && e.exception { continue } - if e.from < 0 || e.from >= m.n || e.to < 0 || e.to >= m.n { + if e.from < 0 || e.from >= n || e.to < 0 || e.to >= n { continue } - if seen[e.from] == nil { - seen[e.from] = map[int]struct{}{} + counts[e.from]++ + } + for from, count := range counts { + if count > 0 && cap(succs[from]) < count { + succs[from] = make([]int, 0, count) + } + } + if cap(m.stampScratch) < n { + m.stampScratch = make([]uint64, n) + } else { + m.stampScratch = m.stampScratch[:n] + clear(m.stampScratch) + } + if cap(m.markScratch) < n { + m.markScratch = make([]uint64, n) + } else { + m.markScratch = m.markScratch[:n] + clear(m.markScratch) + } + stamps, marks := m.stampScratch, m.markScratch + var stamp uint64 + for _, e := range m.edges { + if !includeException && e.exception { + continue } - if _, dup := seen[e.from][e.to]; dup { + if e.from < 0 || e.from >= n || e.to < 0 || e.to >= n { continue } - seen[e.from][e.to] = struct{}{} + if stamps[e.from] == 0 { + stamp++ + stamps[e.from] = stamp + } + if marks[e.to] == stamps[e.from] { + continue + } + marks[e.to] = stamps[e.from] succs[e.from] = append(succs[e.from], e.to) } + *outer = succs return succs } @@ -879,6 +1093,35 @@ func (m *MutableAnalysisGraph) GetOrCompute(kind AnalysisKind, domain GraphAnaly return m.cache.getOrCompute(m.id, m.epoch, kind, domain, m.successorIndexLists(domain.IncludeException)) } +// GetOrComputeShared returns the cache-owned analysis without the defensive +// deep copy. The caller must treat it as read-only and must not retain it past +// a mutation of this graph. Rewriter-internal analysis state uses it to avoid +// cloning IDom/IPDom/loop tables at every topology change. +func (m *MutableAnalysisGraph) GetOrComputeShared(kind AnalysisKind, domain GraphAnalysisDomain) *GraphAnalysis { + return m.cache.getOrComputeShared(m.id, m.epoch, kind, domain, m.successorIndexLists(domain.IncludeException)) +} + +// Dominates reports whether dominator dominates node in the current graph +// epoch. Unlike GetOrCompute it does not deep-copy the cached analysis, so it +// is the scalar query for repeated dominance tests. +func (m *MutableAnalysisGraph) Dominates(domain GraphAnalysisDomain, dominator, node int) bool { + if m == nil || m.cache == nil { + return false + } + analysis := m.cache.getOrComputeShared(m.id, m.epoch, AnalysisDominators, domain, m.successorIndexLists(domain.IncludeException)) + return analysis != nil && analysis.Dominates(dominator, node) +} + +// PostDominates reports whether post postdominates node in the current graph +// epoch without copying the cached analysis. +func (m *MutableAnalysisGraph) PostDominates(domain GraphAnalysisDomain, post, node int) bool { + if m == nil || m.cache == nil { + return false + } + analysis := m.cache.getOrComputeShared(m.id, m.epoch, AnalysisPostDominators, domain, m.successorIndexLists(domain.IncludeException)) + return analysis != nil && analysis.PostDominates(post, node) +} + func (m *MutableAnalysisGraph) ComputeCount() int64 { return m.cache.ComputeCount() } func equalIntSlices(a, b []int) bool { diff --git a/classparser/decompiler/core/t26_scalar_query_test.go b/classparser/decompiler/core/t26_scalar_query_test.go new file mode 100644 index 00000000..8c2b74ca --- /dev/null +++ b/classparser/decompiler/core/t26_scalar_query_test.go @@ -0,0 +1,138 @@ +package core + +import "testing" + +func t26ScalarGraph() (*MutableAnalysisGraph, GraphAnalysisDomain) { + cache := NewGraphAnalysisCache(8) + graph := NewMutableAnalysisGraph(5, cache) + graph.AddEdge(0, 1, false) + graph.AddEdge(0, 2, false) + graph.AddEdge(1, 3, false) + graph.AddEdge(2, 3, false) + graph.AddEdge(3, 4, false) + return graph, GraphAnalysisDomain{Roots: []int{0}} +} + +func TestT26ScalarDominanceQueriesShareCachedAnalysis(t *testing.T) { + graph, domain := t26ScalarGraph() + + if !graph.Dominates(domain, 0, 4) || !graph.Dominates(domain, 3, 4) { + t.Fatal("expected entry and join to dominate the exit") + } + if graph.Dominates(domain, 1, 4) { + t.Fatal("one arm must not dominate a join") + } + if !graph.Dominates(domain, 4, 4) { + t.Fatal("reflexive dominance missing") + } + if graph.Dominates(domain, 4, 0) { + t.Fatal("exit must not dominate the entry") + } + + computes := graph.ComputeCount() + if computes != 1 { + t.Fatalf("scalar dominator queries computed %d times, want 1", computes) + } + for i := 0; i < 200; i++ { + if !graph.Dominates(domain, 0, 4) || graph.Dominates(domain, 1, 4) { + t.Fatal("scalar query changed on an unchanged epoch") + } + } + if graph.ComputeCount() != computes { + t.Fatalf("repeated scalar queries recomputed: %d -> %d", computes, graph.ComputeCount()) + } + + // The public snapshot accessor must still copy: mutating it cannot poison + // the scalar path. + dom := graph.GetOrCompute(AnalysisDominators, domain) + if graph.ComputeCount() != computes { + t.Fatal("GetOrCompute missed the cached analysis") + } + if len(dom.IDom) == 0 { + t.Fatal("empty idom snapshot") + } + dom.IDom[0] = 999 + again := graph.GetOrCompute(AnalysisDominators, domain) + if again.IDom[0] == 999 { + t.Fatal("caller mutation poisoned the cached snapshot") + } + if !graph.Dominates(domain, 0, 4) { + t.Fatal("poisoning a copy changed scalar dominance") + } +} + +func TestSemanticCFGScalarDominatesMatchesSnapshot(t *testing.T) { + g := t09Graph(5, + t09Edge{0, 1, EdgeFallthrough}, + t09Edge{0, 2, EdgeTaken}, + t09Edge{1, 3, EdgeFallthrough}, + t09Edge{2, 3, EdgeFallthrough}, + t09Edge{3, 4, EdgeFallthrough}, + ) + domain := GraphAnalysisDomain{Roots: []int{0}, IncludeException: true} + want := g.GetOrCompute(AnalysisDominators, domain) + for a := 0; a < 5; a++ { + for b := 0; b < 5; b++ { + if got, expect := g.Dominates(a, b), want.Dominates(a, b); got != expect { + t.Fatalf("Dominates(%d,%d)=%v, want %v", a, b, got, expect) + } + } + } + if computes := g.AnalysisComputeCount(); computes != 1 { + t.Fatalf("scalar queries computed %d times, want 1 shared analysis", computes) + } +} + +func TestT26ScalarPostDominanceQueriesShareCachedAnalysis(t *testing.T) { + graph, domain := t26ScalarGraph() + + if !graph.PostDominates(domain, 3, 0) { + t.Fatal("join must post-dominate the entry") + } + if graph.PostDominates(domain, 1, 0) { + t.Fatal("one arm must not post-dominate the entry") + } + if !graph.PostDominates(domain, 4, 0) { + t.Fatal("exit must post-dominate the entry") + } + if graph.PostDominates(domain, VirtualExitSentinel, 0) { + t.Fatal("virtual exit exposed as a physical return") + } + if !graph.PostDominates(domain, 4, 4) { + t.Fatal("real exit must post-dominate itself") + } + + computes := graph.ComputeCount() + for i := 0; i < 200; i++ { + if !graph.PostDominates(domain, 3, 0) { + t.Fatal("post-dominance changed on an unchanged epoch") + } + } + if graph.ComputeCount() != computes { + t.Fatalf("repeated scalar post queries recomputed: %d -> %d", computes, graph.ComputeCount()) + } + + post := graph.GetOrCompute(AnalysisPostDominators, domain) + if graph.ComputeCount() != computes { + t.Fatal("GetOrCompute post query missed the cached analysis") + } + for a := 0; a < 5; a++ { + for b := 0; b < 5; b++ { + if got, want := graph.PostDominates(domain, a, b), post.PostDominates(a, b); got != want { + t.Fatalf("PostDominates(%d,%d)=%v, want %v", a, b, got, want) + } + } + } + + // A topology change must invalidate both derived lists. + graph.DeleteEdge(1, 3, false) + if graph.PostDominates(domain, 3, 0) { + t.Fatal("join still post-dominates the entry after one arm became exit-less") + } + if !graph.Dominates(domain, 2, 3) || !graph.Dominates(domain, 0, 4) { + t.Fatal("dominance not recomputed after edge deletion") + } + if graph.ComputeCount() <= computes { + t.Fatal("edge deletion reused the cached analysis") + } +} diff --git a/classparser/decompiler/core/utils.go b/classparser/decompiler/core/utils.go index d33b81b4..3939d2bd 100644 --- a/classparser/decompiler/core/utils.go +++ b/classparser/decompiler/core/utils.go @@ -192,11 +192,11 @@ func WalkGraph[T comparable](node T, next func(T) ([]T, error)) error { } func StatementsString(statements []statements.Statement, funcCtx *class_context.ClassContext) string { - var res string + var res strings.Builder for _, statement := range statements { - res += statement.String(funcCtx) + res.WriteString(statement.String(funcCtx)) } - return res + return res.String() } func VisitBody(raw statements.Statement, f func(statement statements.Statement) statements.Statement) statements.Statement { diff --git a/classparser/decompiler/core/values/lambda_builder_test.go b/classparser/decompiler/core/values/lambda_builder_test.go new file mode 100644 index 00000000..cd18eec2 --- /dev/null +++ b/classparser/decompiler/core/values/lambda_builder_test.go @@ -0,0 +1,37 @@ +package values + +import ( + "fmt" + "testing" + + "github.com/yaklang/javajive/classparser/decompiler/core/class_context" + "github.com/yaklang/javajive/classparser/decompiler/core/values/types" +) + +func lambdaBuilderArguments(count int) []JavaValue { + out := make([]JavaValue, count) + integer := types.NewJavaPrimer(types.JavaInteger) + for i := range out { + text := fmt.Sprintf("arg%d", i) + out[i] = NewCustomValue(func(*class_context.ClassContext) string { return text }, func() types.JavaType { return integer }) + } + return out +} + +func TestLambdaFuncRefExactArgumentOutput(t *testing.T) { + ref := &LambdaFuncRef{Id: 17, Arguments: lambdaBuilderArguments(3)} + if got, want := ref.String(&class_context.ClassContext{}), "getLambda(17)(arg0,arg1,arg2,)"; got != want { + t.Fatalf("String() = %q, want %q", got, want) + } +} + +func BenchmarkLambdaFuncRefBuilder(b *testing.B) { + ref := &LambdaFuncRef{Id: 17, Arguments: lambdaBuilderArguments(4096)} + ctx := &class_context.ClassContext{} + b.ReportAllocs() + for i := 0; i < b.N; i++ { + if got := ref.String(ctx); len(got) == 0 { + b.Fatal("empty output") + } + } +} diff --git a/classparser/decompiler/core/values/middle_value.go b/classparser/decompiler/core/values/middle_value.go index 8cd02ad3..19b55599 100644 --- a/classparser/decompiler/core/values/middle_value.go +++ b/classparser/decompiler/core/values/middle_value.go @@ -2,6 +2,7 @@ package values import ( "fmt" + "strings" "github.com/yaklang/javajive/classparser/decompiler/core/class_context" "github.com/yaklang/javajive/classparser/decompiler/core/utils" @@ -110,9 +111,10 @@ func (j *LambdaFuncRef) String(funcCtx *class_context.ClassContext) string { if j.LambdaRender != nil { return j.LambdaRender(funcCtx) } - args := "" + var args strings.Builder for _, arg := range j.Arguments { - args += arg.String(funcCtx) + "," + args.WriteString(arg.String(funcCtx)) + args.WriteByte(',') } - return fmt.Sprintf("getLambda(%d)(%s)", j.Id, args) + return fmt.Sprintf("getLambda(%d)(%s)", j.Id, args.String()) } diff --git a/classparser/decompiler/jar/jarparser.go b/classparser/decompiler/jar/jarparser.go index 7c5c93d2..2a846f0e 100644 --- a/classparser/decompiler/jar/jarparser.go +++ b/classparser/decompiler/jar/jarparser.go @@ -12,11 +12,12 @@ import ( "github.com/yaklang/javajive/classparser" "github.com/yaklang/javajive/internal/filesys" + "github.com/yaklang/javajive/internal/inputkind" "github.com/yaklang/javajive/internal/log" "github.com/yaklang/javajive/internal/utils" ) -var archiveExtensions = []string{".jar", ".war", ".ear", ".zip", ".par"} +var archiveExtensions = []string{".jar", ".war", ".ear", ".zip", ".par", ".aar", ".jmod"} func containsNestedArchivePath(path string) bool { lower := strings.ToLower(path) @@ -54,6 +55,12 @@ type JarParser struct { // failedFiles tracks files that couldn't be parsed/decompiled failedFiles map[string]error + + // ownsJarFS is true for parsers created by the constructors in this package. + // Nested JarFS values are owned by the outer cache and are never closed here. + ownsJarFS bool + closeOnce sync.Once + closeErr error } // NewJarParser creates a new JarParser for the specified JAR file path @@ -68,11 +75,13 @@ func NewJarParser(jarPath string) (*JarParser, error) { jarFS: jarFS, classCache: make(map[string][]byte), failedFiles: make(map[string]error), + ownsJarFS: true, }, nil } // NewJarParserFromBytes creates a new JarParser from JAR content in memory func NewJarParserFromBytes(jarContent []byte) (*JarParser, error) { + jarContent = inputkind.StripJMODHeader(jarContent) zipFS, err := filesys.NewZipFSRaw(bytes.NewReader(jarContent), int64(len(jarContent))) if err != nil { return nil, utils.Wrapf(err, "failed to create zip filesystem from bytes") @@ -93,6 +102,30 @@ func (j *JarParser) GetJarFS() *javaclassparser.JarFS { return j.jarFS } +// Close releases the archive handle owned by this parser. It is idempotent. +func (j *JarParser) Close() error { + if j == nil { + return nil + } + j.closeOnce.Do(func() { + if j.ownsJarFS && j.jarFS != nil { + j.closeErr = j.jarFS.Close() + } + }) + return j.closeErr +} + +func (j *JarParser) nestedJarFS(current *javaclassparser.JarFS, jarPath string) (*javaclassparser.JarFS, error) { + if current == nil { + return nil, utils.Error("nil jar filesystem") + } + nested, err := current.GetNestedJarFS(jarPath) + if err != nil { + return nil, utils.Wrapf(err, "failed to open nested jar: %s", jarPath) + } + return nested, nil +} + // ListDirectory lists the contents of a directory within the JAR // Handles nested JAR paths like "lib/fastjson.jar/com/example" or "lib/outer.jar/libs/inner.jar/com/example" func (j *JarParser) ListDirectory(dirPath string) ([]fs.DirEntry, error) { @@ -110,17 +143,10 @@ func (j *JarParser) ListDirectory(dirPath string) ([]fs.DirEntry, error) { // Traverse through the nested JARs for _, jarPath := range jarPaths { - nestedContent, err := currentFS.ZipFS.ReadFile(jarPath) + currentFS, err = j.nestedJarFS(currentFS, jarPath) if err != nil { - return nil, utils.Wrapf(err, "failed to read nested jar: %s", jarPath) + return nil, err } - - zipFS, err := filesys.NewZipFSRaw(bytes.NewReader(nestedContent), int64(len(nestedContent))) - if err != nil { - return nil, utils.Wrapf(err, "failed to create zip filesystem for nested jar: %s", jarPath) - } - - currentFS = javaclassparser.NewJarFS(zipFS) } // Read directory from the final filesystem @@ -249,19 +275,11 @@ func (j *JarParser) DecompileClass(className string) ([]byte, error) { // Traverse through the nested JARs for _, jarPath := range jarPaths { - nestedContent, err := currentFS.ZipFS.ReadFile(jarPath) + currentFS, err = j.nestedJarFS(currentFS, jarPath) if err != nil { j.failedFiles[className] = err - return nil, utils.Wrapf(err, "failed to read nested jar: %s", jarPath) + return nil, err } - - zipFS, err := filesys.NewZipFSRaw(bytes.NewReader(nestedContent), int64(len(nestedContent))) - if err != nil { - j.failedFiles[className] = err - return nil, utils.Wrapf(err, "failed to create zip filesystem for nested jar: %s", jarPath) - } - - currentFS = javaclassparser.NewJarFS(zipFS) } // Read class from the final filesystem @@ -346,17 +364,7 @@ func (j *JarParser) parseMultiLevelJarPath(fullPath string) ([]string, string, e // For multi-level nested JARs, the ListDirectory and DecompileClass methods now // automatically handle multiple levels of nesting. func (j *JarParser) GetNestedJarFS(nestedJarPath string) (*javaclassparser.JarFS, error) { - content, err := j.jarFS.ZipFS.ReadFile(nestedJarPath) - if err != nil { - return nil, utils.Wrapf(err, "failed to read nested jar: %s", nestedJarPath) - } - - zipFS, err := filesys.NewZipFSRaw(bytes.NewReader(content), int64(len(content))) - if err != nil { - return nil, utils.Wrapf(err, "failed to create zip filesystem for nested jar: %s", nestedJarPath) - } - - return javaclassparser.NewJarFS(zipFS), nil + return j.nestedJarFS(j.jarFS, normalizeJarInternalPath(nestedJarPath)) } // ParseNestedJarPath parses a path that may contain nested JAR files @@ -424,7 +432,7 @@ func (j *JarParser) FindJavaClasses(includeNestedJars ...bool) ([]string, error) if checkNested && len(nestedJars) > 0 { for _, nestedJarPath := range nestedJars { // Process this nested JAR - err := j.findNestedJarClasses(nestedJarPath, "", &classes) + err := j.findNestedJarClasses(j.jarFS, nestedJarPath, "", &classes) if err != nil { log.Warnf("Error processing nested JAR %s: %v", nestedJarPath, err) } @@ -438,27 +446,18 @@ func (j *JarParser) FindJavaClasses(includeNestedJars ...bool) ([]string, error) // jarPath is the current jar being processed // prefix is used for building the full path for nested jars // classes is a pointer to the slice where found classes will be stored -func (j *JarParser) findNestedJarClasses(jarPath, prefix string, classes *[]string) error { +func (j *JarParser) findNestedJarClasses(parent *javaclassparser.JarFS, jarPath, prefix string, classes *[]string) error { // Construct full path for this JAR fullJarPath := jarPath if prefix != "" { fullJarPath = prefix + "/" + jarPath } - // Get the nested JAR content - nestedContent, err := j.jarFS.ZipFS.ReadFile(jarPath) + nestedFS, err := j.nestedJarFS(parent, jarPath) if err != nil { - return utils.Wrapf(err, "failed to read nested jar: %s", jarPath) + return err } - // Create a filesystem for this JAR - zipFS, err := filesys.NewZipFSRaw(bytes.NewReader(nestedContent), int64(len(nestedContent))) - if err != nil { - return utils.Wrapf(err, "failed to create zip filesystem for nested jar: %s", jarPath) - } - - nestedFS := javaclassparser.NewJarFS(zipFS) - // Track nested JARs found within this JAR var deeperNestedJars []string @@ -487,7 +486,7 @@ func (j *JarParser) findNestedJarClasses(jarPath, prefix string, classes *[]stri // Recursively process deeper nested JARs if any for _, deepJarPath := range deeperNestedJars { - err := j.findNestedJarClasses(deepJarPath, fullJarPath, classes) + err := j.findNestedJarClasses(nestedFS, deepJarPath, fullJarPath, classes) if err != nil { log.Warnf("Error processing deeper nested JAR %s in %s: %v", deepJarPath, fullJarPath, err) } diff --git a/classparser/decompiler/jar/jarparser_cache_test.go b/classparser/decompiler/jar/jarparser_cache_test.go new file mode 100644 index 00000000..2ddf6df4 --- /dev/null +++ b/classparser/decompiler/jar/jarparser_cache_test.go @@ -0,0 +1,59 @@ +package jar + +import ( + "archive/zip" + "bytes" + "testing" +) + +func zipBytes(t *testing.T, files map[string][]byte) []byte { + t.Helper() + var out bytes.Buffer + writer := zip.NewWriter(&out) + for name, data := range files { + entry, err := writer.Create(name) + if err != nil { + t.Fatal(err) + } + if _, err := entry.Write(data); err != nil { + t.Fatal(err) + } + } + if err := writer.Close(); err != nil { + t.Fatal(err) + } + return out.Bytes() +} + +func TestJarParserReusesNestedJarFSAndCloseIsIdempotent(t *testing.T) { + inner := zipBytes(t, map[string][]byte{"p/value.txt": []byte("payload")}) + outer := zipBytes(t, map[string][]byte{"lib/inner.jar": inner}) + parser, err := NewJarParserFromBytes(outer) + if err != nil { + t.Fatal(err) + } + first, err := parser.GetNestedJarFS("lib/inner.jar") + if err != nil { + t.Fatal(err) + } + second, err := parser.GetNestedJarFS("lib/inner.jar") + if err != nil { + t.Fatal(err) + } + if first != second { + t.Fatal("nested JarFS cache was not reused") + } + data, err := parser.DecompileClass("lib/inner.jar/p/value.txt") + if err != nil { + t.Fatal(err) + } + if string(data) != "payload" { + t.Fatalf("nested content = %q", data) + } + if err := parser.Close(); err != nil { + t.Fatal(err) + } + if err := parser.Close(); err != nil { + t.Fatal(err) + } +} diff --git a/classparser/decompiler/jar/util.go b/classparser/decompiler/jar/util.go index b5380fec..931d2f02 100644 --- a/classparser/decompiler/jar/util.go +++ b/classparser/decompiler/jar/util.go @@ -19,6 +19,7 @@ func AnalyzeJarSecurity(jarPath string) (map[string]interface{}, error) { if err != nil { return nil, err } + defer parser.Close() results := map[string]interface{}{ "jarPath": jarPath, @@ -138,6 +139,7 @@ func GetJarDependencyTree(jarPath string) (map[string]interface{}, error) { if err != nil { return nil, err } + defer parser.Close() manifest, err := parser.GetJarManifest() if err != nil { diff --git a/classparser/decompiler/rewriter/forward_region.go b/classparser/decompiler/rewriter/forward_region.go index 4fe006eb..1e325aec 100644 --- a/classparser/decompiler/rewriter/forward_region.go +++ b/classparser/decompiler/rewriter/forward_region.go @@ -135,7 +135,7 @@ func materializeForwardRegionExits(manager *RewriteManager, condition *core.Node jump.EncodedJumps = map[*core.Node]bool{exit: true} replaceNextInPlace(e.from, exit, jump) } - manager.DominatorMap = GenerateDominatorTree(manager.RootNode) + manager.refreshDominatorsShared() return } } diff --git a/classparser/decompiler/rewriter/handler_loop_tail.go b/classparser/decompiler/rewriter/handler_loop_tail.go index 9eb4ba35..b500605b 100644 --- a/classparser/decompiler/rewriter/handler_loop_tail.go +++ b/classparser/decompiler/rewriter/handler_loop_tail.go @@ -76,7 +76,7 @@ func materializeHandlerLoopTails(manager *RewriteManager, region *core.Node) { transfer.AddNext(p.loop) } if len(plans) > 0 { - manager.DominatorMap = GenerateDominatorTree(manager.RootNode) + manager.refreshDominatorsShared() } } diff --git a/classparser/decompiler/rewriter/if_rewriter.go b/classparser/decompiler/rewriter/if_rewriter.go index a9bb7bfe..bea16112 100644 --- a/classparser/decompiler/rewriter/if_rewriter.go +++ b/classparser/decompiler/rewriter/if_rewriter.go @@ -252,7 +252,7 @@ func splitSharedFallthroughExpression(manager *RewriteManager, condition *core.N edge.OriginPC, edge.HasOriginPC = target.OriginPC, target.HasOriginPC edge.AddNext(target.Next[0]) replaceNextInPlace(condition, target, edge) - manager.DominatorMap = GenerateDominatorTree(manager.RootNode) + manager.refreshDominatorsShared() return } } @@ -377,7 +377,7 @@ func splitSharedTerminalLeaves(manager *RewriteManager, condition *core.Node) { changed = true } if changed { - manager.DominatorMap = GenerateDominatorTree(manager.RootNode) + manager.refreshDominatorsShared() } } diff --git a/classparser/decompiler/rewriter/irreducible_dispatch.go b/classparser/decompiler/rewriter/irreducible_dispatch.go index 3725d360..b8760bd9 100644 --- a/classparser/decompiler/rewriter/irreducible_dispatch.go +++ b/classparser/decompiler/rewriter/irreducible_dispatch.go @@ -20,7 +20,11 @@ type irreducibleDispatchRegion struct { // LowerIrreducibleDispatch converts supported normal-flow irreducible kernels // before ordinary if/loop/switch structuring consumes their edge identity. func (m *RewriteManager) LowerIrreducibleDispatch(admitted, constructor bool) bool { - if m == nil || m.RootNode == nil || isReducibleCFG(m.RootNode, GenerateDominatorTree(m.RootNode)) { + if m == nil || m.RootNode == nil { + return true + } + m.refreshDominatorsShared() + if isReducibleCFG(m.RootNode, m.DominatorMap) { return true } if !admitted { @@ -35,7 +39,8 @@ func (m *RewriteManager) LowerIrreducibleDispatch(admitted, constructor bool) bo for rewrites := 0; rewrites < maxRewrites; rewrites++ { region, found := m.nextIrreducibleDispatchRegion() if !found { - if isReducibleCFG(m.RootNode, GenerateDominatorTree(m.RootNode)) { + m.refreshDominatorsShared() + if isReducibleCFG(m.RootNode, m.DominatorMap) { return true } if m.irreducibleDispatchError == "" { @@ -65,7 +70,8 @@ func reachableGraphNodes(root *core.Node) []*core.Node { func (m *RewriteManager) nextIrreducibleDispatchRegion() (irreducibleDispatchRegion, bool) { nodes := reachableGraphNodes(m.RootNode) - dominators := GenerateDominatorTree(m.RootNode) + m.refreshDominatorsShared() + dominators := m.DominatorMap forward := func(node *core.Node) []*core.Node { out := make([]*core.Node, 0, len(node.Next)) for _, next := range node.Next { diff --git a/classparser/decompiler/rewriter/loop_analysis_cache_test.go b/classparser/decompiler/rewriter/loop_analysis_cache_test.go new file mode 100644 index 00000000..d8df9765 --- /dev/null +++ b/classparser/decompiler/rewriter/loop_analysis_cache_test.go @@ -0,0 +1,155 @@ +package rewriter + +import ( + "math/rand" + "testing" + + "github.com/yaklang/javajive/classparser/decompiler/core" + "github.com/yaklang/javajive/classparser/decompiler/core/statements" + utils2 "github.com/yaklang/javajive/internal/utils" +) + +func cacheTestEqualNodeSets(a, b *utils2.Set[*core.Node], nodes []*core.Node) bool { + if a == nil || b == nil { + return a == b + } + if a.Len() != b.Len() { + return false + } + for _, n := range nodes { + if a.Has(n) != b.Has(n) { + return false + } + } + return true +} + +// The loop-analysis cache must be observationally identical to recomputing the +// body and exit for every query. This exercises bodies, exits, missing exits, +// excluded pre-headers and the legacy over-approximated body on random CFGs. +func TestLoopAnalysisCacheMatchesFreshQueries(t *testing.T) { + r := rand.New(rand.NewSource(0x10ca)) + for iteration := 0; iteration < 500; iteration++ { + nodeCount := 2 + r.Intn(18) + root, nodes := cacheDifferentialGraph(r, nodeCount) + m := NewRootStatementManager(root) + m.refreshDominators() + m.LoopRegionReducible = true + if !m.loopCacheSafe() { + t.Fatalf("iteration %d: cache unexpectedly unsafe for an unprotected graph", iteration) + } + m.loopCache = newLoopAnalysisCache() + + for _, loop := range nodes { + if len(loop.Next) == 0 { + continue + } + start := loop.Next[0] + for _, exclude := range []bool{true, false} { + want := circleElementSet(loop, start, m.DominatorMap, exclude) + got := m.loopBody(loop, start, exclude) + if !cacheTestEqualNodeSets(got, want, nodes) { + t.Fatalf("iteration %d loop %d exclude=%t: cached body differs", iteration, loop.Id, exclude) + } + if again := m.loopBody(loop, start, exclude); again != got { + t.Fatalf("iteration %d loop %d exclude=%t: cache did not reuse the body", iteration, loop.Id, exclude) + } + } + for _, reducible := range []bool{true, false} { + want := searchCircleEndNode(loop, start, m.DominatorMap, reducible) + got := m.searchLoopEnd(loop, start, reducible) + if got != want { + t.Fatalf("iteration %d loop %d reducible=%t: cached exit=%v want %v", iteration, loop.Id, reducible, got, want) + } + if again := m.searchLoopEnd(loop, start, reducible); again != got { + t.Fatalf("iteration %d loop %d reducible=%t: cache did not reuse the exit", iteration, loop.Id, reducible) + } + } + } + m.loopCache = nil + } +} + +func TestLoopAnalysisCacheDisabledForProtectedRegions(t *testing.T) { + root := core.NewNode(&statements.MiddleStatement{Flag: "root"}) + body := core.NewNode(&statements.MiddleStatement{Flag: "body"}) + handler := core.NewNode(&statements.MiddleStatement{Flag: "handler"}) + root.Id, body.Id, handler.Id = 0, 1, 2 + root.AddNext(body) + body.AddNext(root) + root.AddNext(handler) + + m := NewRootStatementManager(root) + m.refreshDominators() + if !m.loopCacheSafe() { + t.Fatal("unprotected graph must allow the loop cache") + } + handler.HasProtectedRange = true + if m.loopCacheSafe() { + t.Fatal("protected region must disable the loop cache") + } + m.TryNodes = []*core.Node{handler} + if m.loopCacheSafe() { + t.Fatal("try node must disable the loop cache") + } +} + +// A topology change must keep base bodies for loops whose dominator subtree and +// immediate adjacency were untouched, and drop those that contain the change. +func TestLoopBaseCacheInvalidatesOnlyAffectedLoops(t *testing.T) { + root := core.NewNode(&statements.MiddleStatement{Flag: "root"}) + unrelatedA := core.NewNode(&statements.MiddleStatement{Flag: "a"}) + unrelatedB := core.NewNode(&statements.MiddleStatement{Flag: "b"}) + header := core.NewNode(statements.NewDoWhileStatement(nil, nil)) + bodyA := core.NewNode(&statements.MiddleStatement{Flag: "bodyA"}) + bodyB := core.NewNode(&statements.MiddleStatement{Flag: "bodyB"}) + latch := core.NewNode(&statements.MiddleStatement{Flag: "latch"}) + exit := core.NewNode(&statements.MiddleStatement{Flag: "exit"}) + root.Id, unrelatedA.Id, unrelatedB.Id, header.Id = 0, 1, 2, 3 + bodyA.Id, bodyB.Id, latch.Id, exit.Id = 4, 5, 6, 7 + root.AddNext(unrelatedA) + unrelatedA.AddNext(unrelatedB) + root.AddNext(header) + header.AddNext(bodyA) + header.AddNext(bodyB) + bodyA.AddNext(latch) + latch.AddNext(header) + bodyB.AddNext(exit) + + m := NewRootStatementManager(root) + m.LoopRegionReducible = true + m.refreshDominatorsShared() + m.loopBases = map[loopBodyKey]loopBaseEntry{} + m.loopBody(header, bodyA, true) + if len(m.loopBases) != 1 { + t.Fatalf("initial base cache size=%d", len(m.loopBases)) + } + + // A duplicate edge between two nodes outside the loop subtree and not + // adjacent to it must not invalidate the body. + unrelatedA.Next = append(unrelatedA.Next, unrelatedB) + m.refreshDominatorsShared() + if len(m.loopBases) != 1 { + t.Fatal("unrelated edge change invalidated the loop body") + } + + // An edge from a dominated body node to another node belongs to the loop's + // subtree and must invalidate it. + bodyA.AddNext(exit) + m.refreshDominatorsShared() + if len(m.loopBases) != 0 { + t.Fatal("loop-body edge change kept the cached body") + } + + // A new external entry directly into the loop body is adjacent to the + // dominated subtree and must also invalidate it. + m.loopBody(header, bodyA, true) + if len(m.loopBases) != 1 { + t.Fatal("base body was not repopulated") + } + root.AddNext(bodyA) + m.refreshDominatorsShared() + if len(m.loopBases) != 0 { + t.Fatal("external entry into the loop kept the cached body") + } +} diff --git a/classparser/decompiler/rewriter/loop_latch_partition.go b/classparser/decompiler/rewriter/loop_latch_partition.go index 60dd1a33..a7c2403d 100644 --- a/classparser/decompiler/rewriter/loop_latch_partition.go +++ b/classparser/decompiler/rewriter/loop_latch_partition.go @@ -49,7 +49,7 @@ func partitionSharedLoopLatches(manager *RewriteManager) { } plan.tail.RemoveAllNext() manager.IfNodes = slices.DeleteFunc(manager.IfNodes, func(n *core.Node) bool { return n == plan.tail }) - manager.DominatorMap = GenerateDominatorTree(manager.RootNode) + manager.refreshDominatorsShared() } } diff --git a/classparser/decompiler/rewriter/loop_rewriter.go b/classparser/decompiler/rewriter/loop_rewriter.go index 3386494b..8431fdc6 100644 --- a/classparser/decompiler/rewriter/loop_rewriter.go +++ b/classparser/decompiler/rewriter/loop_rewriter.go @@ -24,19 +24,28 @@ type LoopStatement struct { // jumps before an if/try is consumed, use body membership as well as dominance; // otherwise an already processed inner loop hides the pending enclosing loop. func loopOwnsRewriteNode(manager *RewriteManager, loop, node *core.Node) bool { + return loopOwnsRewriteNodeWith(manager, loop, node, func(dominator, dominated *core.Node) bool { + return utils.IsDominate(manager.DominatorMap, dominator, dominated) + }) +} + +// loopOwnsRewriteNodeWith is loopOwnsRewriteNode with a caller-supplied +// dominance query. The rewrite scan passes an indexed query so its repeated +// ownership tests cost tree depth instead of the whole dominated subtree. +func loopOwnsRewriteNodeWith(manager *RewriteManager, loop, node *core.Node, dominates func(dominator, dominated *core.Node) bool) bool { if loop == node { return true } - if len(loop.Next) == 0 || !utils.IsDominate(manager.DominatorMap, loop, node) { + if len(loop.Next) == 0 || !dominates(loop, node) { return false } - if !manager.LoopRegionReducible || circleElementSet(loop, loop.Next[0], manager.DominatorMap, true).Has(node) { + if !manager.LoopRegionReducible || manager.loopBody(loop, loop.Next[0], true).Has(node) { return true } // A successful break arm need not reach any backedge. Its private exit // prefix still belongs to this loop until the normal boundary. Structure // those transfers before an if on that prefix becomes an opaque container. - boundary := searchCircleEndNode(loop, loop.Next[0], manager.DominatorMap, true) + boundary := manager.searchLoopEnd(loop, loop.Next[0], true) if boundary == nil || boundary == node { return false } @@ -81,7 +90,7 @@ func loopHeaderGuardsTry(manager *RewriteManager, loop, tr *core.Node) bool { } else { return false } - return other != tr && other == searchCircleEndNode(loop, header, manager.DominatorMap, manager.LoopRegionReducible) + return other != tr && other == manager.searchLoopEnd(loop, header, manager.LoopRegionReducible) } func RebuildLoopNode(manager *RewriteManager) error { @@ -131,9 +140,7 @@ func replaceNextInPlace(node, oldNext, newNext *core.Node) { node.AddNext(newNext) return } - node.Next = slices.Insert(node.Next, idx, newNext) - // newNext is already spliced into node.Next; AddNext only fixes the reverse Source link here. - node.AddNext(newNext) + node.InsertNextAt(idx, newNext) } // outermostEnclosingLoopWithExit returns the outermost ENCLOSING loop (a while-node that dominates @@ -191,10 +198,11 @@ func asLatchIncExpr(n *core.Node) (*values.JavaExpression, bool) { // displacements and Java int overflow. The ordinary tail retains its step. // Require at least two bypass predecessors and one normal predecessor, with // all copied edges owned by this loop; other loop shapes retain their proofs. -func convertSplitContinueToLatch(manager *RewriteManager, circleNode *core.Node) { +func convertSplitContinueToLatch(manager *RewriteManager, circleNode *core.Node) bool { if jdecenv.Get("JDEC_SPLIT_CONTINUE_LATCH_OFF") != "" { - return + return false } + changed := false for _, latch := range slices.Clone(circleNode.Source) { if latch == circleNode { continue @@ -241,22 +249,37 @@ func convertSplitContinueToLatch(manager *RewriteManager, circleNode *core.Node) replaceNextInPlace(p, latch, incrNode) incrNode.AddNext(contNode) contNode.AddNext(circleNode) + changed = true } } + return changed } func LoopJmpRewriter(manager *RewriteManager, circleNode *core.Node) error { - materializeSwitchLatchContinues(manager, circleNode) - convertSplitContinueToLatch(manager, circleNode) - loopEnd := searchCircleEndNode(circleNode, circleNode.Next[0], manager.DominatorMap, manager.LoopRegionReducible) + changed := materializeSwitchLatchContinues(manager, circleNode) + changed = convertSplitContinueToLatch(manager, circleNode) || changed + if changed { + // The two pre-rewrites may have rewritten edges after the caller's + // loop-analysis cache was filled. convertSplitContinueToLatch does not + // publish a topology refresh, so drop the persistent base cache too. + manager.loopCache = nil + manager.clearLoopBases() + } + // The caller's cache already contains this loop when its scan found the + // exit; reuse it instead of rebuilding the same body here. If a + // pre-rewrite changed the graph, the cache was just discarded. + loopEnd := manager.searchLoopEnd(circleNode, circleNode.Next[0], manager.LoopRegionReducible) preWhileNodes := utils.NodeFilter(manager.WhileNode, func(node *core.Node) bool { return utils.IsDominate(manager.DominatorMap, node, circleNode) }) preWhileNodeEnds := map[*core.Node]*core.Node{} for _, n := range preWhileNodes { - preWhileNodeEnds[n] = searchCircleEndNode(n, n.Next[0], manager.DominatorMap, manager.LoopRegionReducible) + preWhileNodeEnds[n] = manager.searchLoopEnd(n, n.Next[0], manager.LoopRegionReducible) } + // The rewrite below inserts break/continue nodes and edges; no analysis + // answer collected above may be reused after that. + manager.loopCache = nil checkNode := func(node *core.Node) ([]*core.Node, error) { if node.IsJmp { manager.qualifyLoopTransfer(node, circleNode) @@ -503,7 +526,9 @@ func LoopRewriter(manager *RewriteManager, node *core.Node) error { body := []statements.Statement{} bodyNodes := []*core.Node{} endNodes := []*core.Node{} - circleSet := getCircleElementSet(circleNode, loopStart, manager.DominatorMap) + // The header edge was just removed, so this body must be recomputed; only + // the base-traversal scratch is reused. + circleSet := circleElementSetInto(circleNode, loopStart, manager.DominatorMap, false, &manager.loopScratch) err := core.WalkGraph[*core.Node](loopStart, func(node *core.Node) ([]*core.Node, error) { if !circleSet.Has(node) { endNodes = append(endNodes, node) @@ -571,6 +596,223 @@ func getCircleElementSet(circleNode *core.Node, loopStart *core.Node, domTree ma return circleElementSet(circleNode, loopStart, domTree, false) } +// loopAnalysisCache memoizes loop bodies and loop-exit searches for one rewrite +// step. The exit search for a container node otherwise rebuilds the same loop +// body several times: ownership, retry ownership, the direct exit comparison and +// LoopJmpRewriter all ask about the same loop. On a loop-heavy class that made +// circleElementSet the dominant cost (tens of millions of node visits). +// +// The cache is only installed around an analysis-only scan (see +// materializeLoopExits) and is dropped before any graph mutation, so a cached +// answer always describes the live CFG. Methods whose loop analysis can mutate +// node state (protected-retry boundaries) keep the cache disabled; see +// loopCacheSafe. +type loopBodyKey struct { + loop *core.Node + start *core.Node + exclude bool +} + +type loopExitKey struct { + loop *core.Node + start *core.Node + reducible bool +} + +type loopAnalysisCache struct { + bodies map[loopBodyKey]*utils2.Set[*core.Node] + exits map[loopExitKey]*core.Node +} + +func newLoopAnalysisCache() *loopAnalysisCache { + return &loopAnalysisCache{ + bodies: map[loopBodyKey]*utils2.Set[*core.Node]{}, + exits: map[loopExitKey]*core.Node{}, + } +} + +// loopBaseEntry is an immutable topology-only loop body plus whether the +// protected-retry augmentation can change it. +type loopBaseEntry struct { + body *utils2.Set[*core.Node] + protected bool +} + +// loopCacheSafe reports whether circleElementSet is a pure function of the +// current graph. Its protected-retry augmentation mutates tr.ProtectedEnd and +// depends on that field on a later call, so reuse is only valid when the method +// has no protected ranges at all. +func (s *RewriteManager) loopCacheSafe() bool { + if s == nil || s.DominatorMap == nil || len(s.TryNodes) != 0 || len(s.originalHandlers) != 0 { + return false + } + if jdecenv.Get("JDEC_LOOP_ANALYSIS_CACHE_OFF") == "1" { + return false + } + dirty := func(n *core.Node) bool { + return n != nil && (n.HasProtectedRange || n.SharedProtectedHandler || + n.ProtectedEnd != nil || len(n.SharedProtectedRanges) != 0) + } + if dirty(s.RootNode) { + return false + } + for parent, children := range s.DominatorMap { + if dirty(parent) { + return false + } + for _, child := range children { + if dirty(child) { + return false + } + } + } + return true +} + +// loopBody returns the loop body, reusing the current analysis cache when one is +// installed. A nil manager or cache preserves the previous recompute behavior. +func (s *RewriteManager) loopBody(loop, start *core.Node, excludePreHeader bool) *utils2.Set[*core.Node] { + if s == nil { + return circleElementSet(loop, start, nil, excludePreHeader) + } + key := loopBodyKey{loop: loop, start: start, exclude: excludePreHeader} + if s.loopCache != nil { + // Analysis-only scan: the final set is safe to share because the method + // has no protected retry boundaries. + if body, ok := s.loopCache.bodies[key]; ok { + return body + } + body := circleElementSetInto(loop, start, s.DominatorMap, excludePreHeader, &s.loopScratch) + s.loopCache.bodies[key] = body + return body + } + if s.loopBases == nil { + return circleElementSetInto(loop, start, s.DominatorMap, excludePreHeader, &s.loopScratch) + } + // Protected methods keep the final set uncached because the augmentation + // mutates ProtectedEnd, but the topology-only base body is immutable and + // can be reused across rewrite steps. + entry, ok := s.loopBases[key] + if !ok { + body := circleBaseBodyInto(loop, start, s.DominatorMap, excludePreHeader, &s.loopScratch) + entry = loopBaseEntry{body: body, protected: loopBodyHasProtectedRetry(body)} + s.loopBases[key] = entry + } + return augmentCircleBodyIf(entry.body, loop, entry.protected) +} + +// currentDominateIndex returns the cached child->parent query for the current +// DominatorMap. Topology refreshes invalidate it; callers must therefore not +// retain it across refreshDominatorsShared. +func (s *RewriteManager) currentDominateIndex() *utils.DominateIndex { + if s == nil || s.DominatorMap == nil { + return nil + } + if s.domIndex == nil { + s.domIndex = utils.NewDominateIndex(s.DominatorMap) + s.domIndexVersion = s.domMapVersion + return s.domIndex + } + if s.domIndexVersion != s.domMapVersion { + s.domIndex.Reset(s.DominatorMap) + s.domIndexVersion = s.domMapVersion + } + return s.domIndex +} + +func (s *RewriteManager) ownsNode(loop, node *core.Node) bool { + if s == nil { + return false + } + if index := s.currentDominateIndex(); index != nil { + return index.IsDominate(loop, node) + } + return utils.IsDominate(s.DominatorMap, loop, node) +} + +// nodeLive reports whether a node belongs to the current statement dominator +// snapshot. It avoids rebuilding the dominator's node set for every +// exclusive-terminal test; nil means the caller must build its own live set. +func (s *RewriteManager) nodeLive() func(*core.Node) bool { + if s == nil || s.dominance == nil || s.dominance.snapshot == nil || s.dominance.root != s.RootNode { + return nil + } + index := s.dominance.snapshot.index + return func(n *core.Node) bool { + if n == nil { + return false + } + _, ok := index[n] + return ok + } +} + +func (s *RewriteManager) clearLoopBases() { + if s != nil && s.loopBases != nil { + clear(s.loopBases) + } +} + +// invalidateLoopBasesAfterTopology keeps cached base bodies whose loop region +// was untouched. For a reducible method the body is contained in the loop +// header's dominator subtree, so a change outside that subtree and its +// immediate adjacency cannot alter the body. Added or removed nodes and +// irreducible methods invalidate conservatively. +func (s *RewriteManager) invalidateLoopBasesAfterTopology(state *statementDominanceState) { + if s == nil || s.loopBases == nil || state == nil || !state.topologyChanged || len(s.loopBases) == 0 { + return + } + if state.diff.addedOrRemoved || !s.LoopRegionReducible || s.DominatorMap == nil { + clear(s.loopBases) + return + } + index := utils.NewDominateIndex(s.DominatorMap) + for key := range s.loopBases { + loop := key.loop + if loop == nil { + delete(s.loopBases, key) + continue + } + invalid := false + for _, changed := range state.diff.changed { + if changed == loop || index.IsDominate(loop, changed) { + invalid = true + break + } + } + if !invalid { + for _, neighbor := range state.diff.neighbors { + if neighbor == loop || index.IsDominate(loop, neighbor) { + invalid = true + break + } + } + } + if invalid { + delete(s.loopBases, key) + } + } +} + +// searchLoopEnd returns the loop's normal exit, reusing the current analysis +// cache when one is installed. +func (s *RewriteManager) searchLoopEnd(loop, start *core.Node, reducible bool) *core.Node { + if s == nil { + return searchCircleEndNode(loop, start, nil, reducible) + } + if s.loopCache == nil { + // No memo, but still reuse the manager's base-traversal scratch. + return searchCircleEndNodeInBody(loop, start, s.loopBody(loop, start, reducible), s.DominatorMap, reducible, s.nodeLive(), &s.switchOnly) + } + key := loopExitKey{loop: loop, start: start, reducible: reducible} + if end, ok := s.loopCache.exits[key]; ok { + return end + } + end := searchCircleEndNodeInBody(loop, start, s.loopBody(loop, start, reducible), s.DominatorMap, reducible, s.nodeLive(), &s.switchOnly) + s.loopCache.exits[key] = end + return end +} + // retargetSwitchExitBreaks labels unlabeled breaks in the direct case bodies of // a switch that forms the whole infinite loop body. A case break then leaves // both the switch and the loop, which is what the original CFG edge to the @@ -620,61 +862,205 @@ func retargetSwitchExitBreaks(sw *statements.SwitchStatement, label string) { // so the exit of a reducible nested loop is computed from the tight body instead of leaking into the // enclosing loop. func circleElementSet(circleNode *core.Node, loopStart *core.Node, domTree map[*core.Node][]*core.Node, excludePreHeader bool) *utils2.Set[*core.Node] { - finalSet := utils2.NewSet[*core.Node]() + return circleElementSetInto(circleNode, loopStart, domTree, excludePreHeader, nil) +} + +// loopElementScratch reuses the index map, node slices, and reverse adjacency +// across one method's loop-body queries. The returned set never aliases scratch +// storage, so cached bodies stay independent. Only a single RewriteManager uses +// a scratch instance, and rewriter analysis is sequential. +type loopElementScratch struct { + index map[*core.Node]int + nodes []*core.Node + incoming []int + discovered []bool + reverseAdj [][]int + stack []*core.Node + bfsQueue []int +} + +func (s *loopElementScratch) reset() { + if s.index == nil { + s.index = make(map[*core.Node]int, 64) + s.nodes = make([]*core.Node, 0, 64) + s.incoming = make([]int, 0, 64) + s.discovered = make([]bool, 0, 64) + } else { + clear(s.index) + s.nodes = s.nodes[:0] + s.incoming = s.incoming[:0] + s.discovered = s.discovered[:0] + } + s.stack = s.stack[:0] + s.bfsQueue = s.bfsQueue[:0] +} + +// circleElementSetInto is circleElementSet with optional reused scratch storage. +func circleElementSetInto(circleNode *core.Node, loopStart *core.Node, domTree map[*core.Node][]*core.Node, excludePreHeader bool, scratch *loopElementScratch) *utils2.Set[*core.Node] { + return augmentCircleBody(circleBaseBodyInto(circleNode, loopStart, domTree, excludePreHeader, scratch), circleNode) +} + +// circleBaseBodyInto builds the loop body from topology alone. Protected-retry +// boundaries are applied separately so this result can be cached and shared: +// only the augmentation mutates ProtectedEnd. +func circleBaseBodyInto(circleNode *core.Node, loopStart *core.Node, domTree map[*core.Node][]*core.Node, excludePreHeader bool, scratch *loopElementScratch) *utils2.Set[*core.Node] { + if scratch == nil { + scratch = &loopElementScratch{} + } + sc := scratch + sc.reset() // Step 1: collect all nodes reachable from loopStart and build reverse adjacency. - reverseAdj := map[*core.Node][]*core.Node{} - allNodes := utils2.NewSet[*core.Node]() - { - stk := []*core.Node{loopStart} - for len(stk) > 0 { - n := stk[len(stk)-1] - stk = stk[:len(stk)-1] - if allNodes.Has(n) { - continue - } - allNodes.Add(n) - for _, next := range loopAnalysisSuccessors(n) { - reverseAdj[next] = append(reverseAdj[next], n) - if !allNodes.Has(next) { - stk = append(stk, next) - } + // A plain map plus an append-order slice avoids utils.Set's mutex and avoids + // materializing/sorting a map-ordered List for every loop. + // A single nodeIndex map owns identity; all sets/adjacency are compact + // indexed slices. The previous reverseAdj map plus utils.Set added several + // map buckets per loop and dominating allocation traffic. + indexOf := func(node *core.Node) int { + if index, ok := sc.index[node]; ok { + return index + } + index := len(sc.nodes) + sc.index[node] = index + sc.nodes = append(sc.nodes, node) + sc.incoming = append(sc.incoming, 0) + sc.discovered = append(sc.discovered, false) + return index + } + startIndex := indexOf(loopStart) + sc.discovered[startIndex] = true + sc.stack = append(sc.stack[:0], loopStart) + for len(sc.stack) > 0 { + node := sc.stack[len(sc.stack)-1] + sc.stack = sc.stack[:len(sc.stack)-1] + for _, next := range loopAnalysisSuccessors(node) { + nextIndex := indexOf(next) + sc.incoming[nextIndex]++ + if !sc.discovered[nextIndex] { + sc.discovered[nextIndex] = true + sc.stack = append(sc.stack, next) } } } - // Step 2: find back-edge sources — nodes whose Next includes circleNode. Iterate in stable id order - // (Set.List() is map-ordered) so allSources, and the reverse-BFS latch set derived from it, are - // deterministic. - var allSources []*core.Node - for _, n := range sortNodesByID(allNodes.List()) { - if slices.Contains(loopAnalysisSuccessors(n), circleNode) { - allSources = append(allSources, n) - } - } - sources := allSources - if excludePreHeader && jdecenv.Get("JDEC_NO_LOOP_BACKEDGE_DOM_FILTER") == "" { - // Drop forward pre-header entry edges. The caller only sets excludePreHeader for a method whose - // ORIGINAL CFG is reducible (see RewriteManager.LoopRegionReducible), so a forward, non-dominated - // predecessor is a genuine pre-header rather than an alternate entry of an irreducible tangle. - // Node IDs are allocation order, not bytecode order. A preceding loop - // wrapper can have a larger ID than this header without being a back - // edge. Require dominance even for synthetic predecessors; otherwise - // reverse reachability leaks through the pre-header into an outer loop. - var kept []*core.Node - for _, n := range allSources { - if utils.IsDominate(domTree, circleNode, n) { - kept = append(kept, n) + n := len(sc.nodes) + if cap(sc.reverseAdj) < n { + sc.reverseAdj = make([][]int, n) + } else { + sc.reverseAdj = sc.reverseAdj[:n] + for i := range sc.reverseAdj { + sc.reverseAdj[i] = sc.reverseAdj[i][:0] + } + } + reverseAdj := sc.reverseAdj + for index, count := range sc.incoming { + if count > 0 && cap(reverseAdj[index]) < count { + reverseAdj[index] = make([]int, 0, count) + } + } + for index, node := range sc.nodes { + for _, next := range loopAnalysisSuccessors(node) { + target := sc.index[next] + reverseAdj[target] = append(reverseAdj[target], index) + } + } + // Step 2: find back-edge sources — nodes whose Next includes circleNode. Only the SET of + // sources matters: the reverse reachability query below consumes them as seeds, so + // discovery order cannot change membership. The previous sortNodesByID(nodes) paid + // O(body log body) on every call (96k calls on one 7 KB loop-heavy class) to order a + // map-backed result that is never read in order. + // + // The traversal is index-based and reuses the scratch's visited marks and queue: the + // former reverseBFSStopAt allocated a map and queue sized for the whole reverse + // adjacency (the entire reachable graph) on every loop body query. + visited := sc.discovered + for i := range visited { + visited[i] = false + } + queue := sc.bfsQueue[:0] + circleIndex, circleIndexed := sc.index[circleNode] + if circleIndexed { + visited[circleIndex] = true + } + for index, node := range sc.nodes { + if index == circleIndex { + continue + } + if !slices.Contains(loopAnalysisSuccessors(node), circleNode) { + continue + } + if excludePreHeader && jdecenv.Get("JDEC_NO_LOOP_BACKEDGE_DOM_FILTER") == "" && !utils.IsDominate(domTree, circleNode, node) { + // Drop forward pre-header entry edges. The caller only sets excludePreHeader for a + // method whose ORIGINAL CFG is reducible (see RewriteManager.LoopRegionReducible), so a + // forward, non-dominated predecessor is a genuine pre-header rather than an alternate + // entry of an irreducible tangle. Node IDs are allocation order, not bytecode order; a + // preceding loop wrapper can have a larger ID than this header without being a back + // edge. Require dominance even for synthetic predecessors; otherwise reverse + // reachability leaks through the pre-header into an outer loop. + continue + } + if !visited[index] { + visited[index] = true + queue = append(queue, index) + } + } + for head := 0; head < len(queue); head++ { + for _, pred := range reverseAdj[queue[head]] { + if pred == circleIndex { + continue + } + if !visited[pred] { + visited[pred] = true + queue = append(queue, pred) } } - sources = kept } - finalSet = reverseBFSStopAt(sources, reverseAdj, circleNode) + // Publish the closure as the cached set. The queue length is the exact + // result size (minus the header itself), so the set map is allocated once + // with the right capacity instead of growing from a guess. + result := make(map[*core.Node]struct{}, len(queue)+1) + result[circleNode] = struct{}{} + for _, index := range queue { + result[sc.nodes[index]] = struct{}{} + } + return utils2.NewSetFromMap(result) +} +// loopBodyHasProtectedRetry reports whether any body node can participate in +// the protected-retry augmentation. The augmentation is a no-op otherwise. +func loopBodyHasProtectedRetry(body *utils2.Set[*core.Node]) bool { + has := false + body.ForEachWhile(func(n *core.Node) bool { + if n != nil && (n.HasProtectedRange || n.SharedProtectedHandler || + n.ProtectedEnd != nil || len(n.SharedProtectedRanges) != 0) { + has = true + return false + } + return true + }) + return has +} + +func cloneNodeSetWithList(src *utils2.Set[*core.Node]) (*utils2.Set[*core.Node], []*core.Node) { + return src.CloneWithList() +} + +// augmentCircleBody applies the protected-retry paths on a private copy. The +// base set stays immutable and cacheable; running the augmentation every query +// preserves its ProtectedEnd side effects. +func augmentCircleBody(base *utils2.Set[*core.Node], circleNode *core.Node) *utils2.Set[*core.Node] { + return augmentCircleBodyIf(base, circleNode, loopBodyHasProtectedRetry(base)) +} + +func augmentCircleBodyIf(base *utils2.Set[*core.Node], circleNode *core.Node, protected bool) *utils2.Set[*core.Node] { + if !protected { + return base + } + finalSet, bodyNodes := cloneNodeSetWithList(base) // A retry may return to the header only through its catch. The synthetic // try node represents exceptional edges at region entry, so reverse reachability // alone omits the successful protected path. Include that path up to the // exception table's exclusive end; otherwise the first protected store is // mistaken for the loop exit and moved outside the handler. - for _, tr := range finalSet.List() { + for _, tr := range bodyNodes { if closed := protectedRetryClosedRegion(tr, circleNode, finalSet); closed != nil { for _, node := range closed.path { finalSet.Add(node) @@ -952,21 +1338,36 @@ func hasPrivateRetryHandler(tr *core.Node, body *utils2.Set[*core.Node]) bool { } func protectedRetryContinuations(body *utils2.Set[*core.Node], header *core.Node) map[*core.Node]bool { + // A loop with no protected region cannot have a retry continuation. Check + // the body in place instead of materializing body.List() (a body-sized + // allocation on every exit query) just to discover that. + hasProtected := false + body.ForEachWhile(func(n *core.Node) bool { + if n != nil && (n.HasProtectedRange || n.SharedProtectedHandler || + n.ProtectedEnd != nil || len(n.SharedProtectedRanges) != 0) { + hasProtected = true + return false + } + return true + }) + if !hasProtected { + return nil + } exits := map[*core.Node]bool{} - for _, tr := range body.List() { + body.ForEachWhile(func(tr *core.Node) bool { if closed := protectedRetryClosedRegion(tr, header, body); closed != nil && closed.continuation != nil && !body.Has(closed.continuation) { exits[closed.continuation] = true - continue + return true } if !hasPrivateRetryHandler(tr, body) { - continue + return true } prefix, boundary := protectedRetryPrefix(tr, header) if branch, exit := protectedRetryBranchPrefix(tr, header); exit != nil { prefix, boundary = branch, exit } if boundary == nil || body.Has(boundary) { - continue + return true } complete := true for _, node := range prefix { @@ -975,7 +1376,8 @@ func protectedRetryContinuations(body *utils2.Set[*core.Node], header *core.Node if complete { exits[boundary] = true } - } + return true + }) return exits } @@ -1062,31 +1464,6 @@ func isReducibleCFG(root *core.Node, domTree map[*core.Node][]*core.Node) bool { return true } -// reverseBFSStopAt returns {circleNode} ∪ all nodes that can reach a seed via reverse edges without -// passing through circleNode. -func reverseBFSStopAt(seeds []*core.Node, reverseAdj map[*core.Node][]*core.Node, circleNode *core.Node) *utils2.Set[*core.Node] { - set := utils2.NewSet[*core.Node]() - set.Add(circleNode) - queue := []*core.Node{} - for _, n := range seeds { - if !set.Has(n) { - set.Add(n) - queue = append(queue, n) - } - } - for len(queue) > 0 { - n := queue[0] - queue = queue[1:] - for _, pred := range reverseAdj[n] { - if pred != circleNode && !set.Has(pred) { - set.Add(pred) - queue = append(queue, pred) - } - } - } - return set -} - func searchCircleEndNode(circleNode *core.Node, loopStart *core.Node, domTree map[*core.Node][]*core.Node, reducible bool) *core.Node { // For a reducible method, use the pre-header-excluding body so a nested loop's exit is computed from // its tight body (Bug Q): with the legacy over-approximated body, the reverse-BFS leaks through this @@ -1094,7 +1471,13 @@ func searchCircleEndNode(circleNode *core.Node, loopStart *core.Node, domTree ma // never gets its `else{break}` and becomes a non-terminating do-while(true). Irreducible methods keep // the legacy body to avoid collapsing the loop. The LOOP BODY itself always stays on the legacy path // (getCircleElementSet); only this exit search prunes pre-headers. - elementSet := circleElementSet(circleNode, loopStart, domTree, reducible) + return searchCircleEndNodeInBody(circleNode, loopStart, circleElementSet(circleNode, loopStart, domTree, reducible), domTree, reducible, nil, nil) +} + +// searchCircleEndNodeInBody is searchCircleEndNode with a caller-supplied loop +// body, so the analysis cache can reuse one body across the exit query, the +// ownership query, and the retry-continuation query. +func searchCircleEndNodeInBody(circleNode *core.Node, loopStart *core.Node, elementSet *utils2.Set[*core.Node], domTree map[*core.Node][]*core.Node, reducible bool, live func(*core.Node) bool, only *switchOnlyCache) *core.Node { outNodes := []*core.Node{} elementSet.ForEach(func(node *core.Node) { for _, n := range loopAnalysisSuccessors(node) { @@ -1123,7 +1506,7 @@ func searchCircleEndNode(circleNode *core.Node, loopStart *core.Node, domTree ma // A private original throw is an abrupt arm, even when it is the // only boundary of an otherwise nonterminating loop. It has no // normal continuation that can be expressed by a generated break. - if reducible && originalLoopThrowLeaf(outNodes[0]) && exclusiveTerminalLoopBranch(outNodes[0], circleNode, domTree) { + if reducible && originalLoopThrowLeaf(outNodes[0]) && exclusiveTerminalLoopBranchWithLive(outNodes[0], circleNode, domTree, live) { return nil } return outNodes[0] @@ -1166,12 +1549,12 @@ func searchCircleEndNode(circleNode *core.Node, loopStart *core.Node, domTree ma normalAlternative := false throwingHeader := terminalRegionOnlyThrows(headerOut[0]) for _, out := range outNodes { - if throwingHeader && out != headerOut[0] && !IsEndNode(out) && !exclusiveTerminalLoopBranch(out, circleNode, domTree) && loopExitCannotResumeOwner(out, circleNode) { + if throwingHeader && out != headerOut[0] && !IsEndNode(out) && !exclusiveTerminalLoopBranchWithLive(out, circleNode, domTree, live) && loopExitCannotResumeOwner(out, circleNode) { normalAlternative = true break } } - privateTerminal := exclusiveTerminalLoopBranch(headerOut[0], circleNode, domTree) + privateTerminal := exclusiveTerminalLoopBranchWithLive(headerOut[0], circleNode, domTree, live) if !privateTerminal || (!originalLoopThrowLeaf(headerOut[0]) && !normalAlternative && !hasEnclosingLoopContinuation(outNodes, circleNode, domTree)) { return headerOut[0] } @@ -1183,28 +1566,24 @@ func searchCircleEndNode(circleNode *core.Node, loopStart *core.Node, domTree ma // terminal case shared by fall-through labels must remain inside switch, // rather than becoming an enclosing-loop break that skips its effects. inlineCases := map[*core.Node]bool{} - for _, sw := range elementSet.List() { + elementSet.ForEach(func(sw *core.Node) { middle, ok := sw.Statement.(*statements.MiddleStatement) if !ok || middle.Flag != statements.MiddleSwitch { - continue + return } - data, ok := middle.Data.([]any) + jumpOnly, ok := only.targets(sw, middle) if !ok { - continue + return } - cases, err := switchCaseNodes(data, sw) - if err != nil { - continue - } - for _, target := range cases.Values() { + for target, only := range jumpOnly { if target == sw.MergeNode && (sw.SwitchEmptyCaseMerge || sw.SwitchEmptyDefaultMerge) { continue } - if !switchCaseHasOnlyJumpEntries(sw, target, cases) { + if !only { inlineCases[target] = true } } - } + }) var continuations []*core.Node protectedExits := map[*core.Node]bool{} if reducible { @@ -1222,7 +1601,7 @@ func searchCircleEndNode(circleNode *core.Node, loopStart *core.Node, domTree ma // Keeping it as an inline early return absorbs that call into the try // and retries downstream exceptions. Only the private PC-proved path // may override the ordinary terminal-arm rule. - if exclusiveTerminalLoopBranch(out, circleNode, domTree) && !protectedExits[out] { + if exclusiveTerminalLoopBranchWithLive(out, circleNode, domTree, live) && !protectedExits[out] { continue } continuations = append(continuations, out) @@ -1254,15 +1633,18 @@ func loopHasProvedProtectedRetry(manager *RewriteManager, loop *core.Node) bool if len(loop.Next) == 0 { return false } - body := circleElementSet(loop, loop.Next[0], manager.DominatorMap, true) - for _, tr := range body.List() { + body := manager.loopBody(loop, loop.Next[0], true) + proved := false + body.ForEachWhile(func(tr *core.Node) bool { if hasPrivateRetryHandler(tr, body) { if _, boundary := protectedRetryBranchPrefix(tr, loop); boundary != nil { - return true + proved = true + return false } } - } - return false + return true + }) + return proved } // A private retry's successful continuation can be structured before its try. @@ -1272,7 +1654,7 @@ func protectedRetryContinuationOwnsRewriteNode(manager *RewriteManager, loop, no if loop == nil || node == nil || len(loop.Next) != 1 { return false } - body := circleElementSet(loop, loop.Next[0], manager.DominatorMap, true) + body := manager.loopBody(loop, loop.Next[0], true) return protectedRetryContinuations(body, loop)[node] } diff --git a/classparser/decompiler/rewriter/loop_step_partition.go b/classparser/decompiler/rewriter/loop_step_partition.go index c5efe3df..837b3fa3 100644 --- a/classparser/decompiler/rewriter/loop_step_partition.go +++ b/classparser/decompiler/rewriter/loop_step_partition.go @@ -33,7 +33,7 @@ func partitionSharedLoopSteps(m *RewriteManager) { private.AddNext(loop) } tail.RemoveAllNext() - m.DominatorMap = GenerateDominatorTree(m.RootNode) + m.refreshDominatorsShared() } } } diff --git a/classparser/decompiler/rewriter/loop_terminal_continuation.go b/classparser/decompiler/rewriter/loop_terminal_continuation.go index 5a5cacb8..fab0b8e7 100644 --- a/classparser/decompiler/rewriter/loop_terminal_continuation.go +++ b/classparser/decompiler/rewriter/loop_terminal_continuation.go @@ -2,6 +2,7 @@ package rewriter import ( "sort" + "sync" "github.com/yaklang/javajive/classparser/decompiler/core" "github.com/yaklang/javajive/classparser/decompiler/core/statements" @@ -33,19 +34,41 @@ func exclusiveTerminalBranch(entry *core.Node) bool { func exclusiveTerminalLoopBranch(entry, owner *core.Node, dom map[*core.Node][]*core.Node) bool { return exclusiveTerminalRegion(entry, owner, dom) } + +func exclusiveTerminalLoopBranchWithLive(entry, owner *core.Node, dom map[*core.Node][]*core.Node, live func(*core.Node) bool) bool { + return exclusiveTerminalRegionWithLive(entry, owner, dom, live) +} + func exclusiveTerminalRegion(entry, owner *core.Node, dom map[*core.Node][]*core.Node) bool { - live := map[*core.Node]bool{} - if owner != nil { - for parent, children := range dom { - live[parent] = true - for _, child := range children { - live[child] = true - } + return exclusiveTerminalRegionWithLive(entry, owner, dom, nil) +} + +func domLiveSet(dom map[*core.Node][]*core.Node) map[*core.Node]struct{} { + live := make(map[*core.Node]struct{}, len(dom)) + for parent, children := range dom { + live[parent] = struct{}{} + for _, child := range children { + live[child] = struct{}{} + } + } + return live +} + +func exclusiveTerminalRegionWithLive(entry, owner *core.Node, dom map[*core.Node][]*core.Node, live func(*core.Node) bool) bool { + if owner != nil && live == nil { + liveSet := domLiveSet(dom) + live = func(n *core.Node) bool { + _, ok := liveSet[n] + return ok } } incoming := 0 for _, source := range entry.Source { - if owner == nil || live[source] { + if owner == nil { + incoming++ + continue + } + if live(source) { incoming++ } } @@ -122,7 +145,13 @@ func exclusiveTerminalRegion(entry, owner *core.Node, dom map[*core.Node][]*core return false } for _, source := range n.Source { - if state[source] == 0 && (owner == nil || live[source]) { + if state[source] != 0 { + continue + } + if owner == nil { + return false + } + if live(source) { return false } } @@ -191,42 +220,83 @@ func loopExitCannotResumeOwner(entry, owner *core.Node) bool { // branch may either return or reach it. Require reachability from every exit // entry, and prove every bypass path terminates the method. Unknown sinks and // cycles cannot justify lifting a continuation out of the loop. +type commonExitDistance struct { + generation uint64 + distance int +} + +type commonExitScratch struct { + distances map[*core.Node]commonExitDistance + common map[*core.Node]int + order map[*core.Node]int + queue []*core.Node + generation uint64 +} + +var commonExitPool = sync.Pool{New: func() any { + return &commonExitScratch{ + distances: make(map[*core.Node]commonExitDistance), + common: make(map[*core.Node]int), + order: make(map[*core.Node]int), + } +}} + func commonLoopExit(exits []*core.Node) *core.Node { if len(exits) == 0 { return nil } - common := map[*core.Node]int{} - order := map[*core.Node]int{} + scratch := commonExitPool.Get().(*commonExitScratch) + defer func() { + clear(scratch.distances) + clear(scratch.common) + clear(scratch.order) + scratch.queue = scratch.queue[:0] + commonExitPool.Put(scratch) + }() + clear(scratch.common) + clear(scratch.order) for i, entry := range exits { - distance := map[*core.Node]int{entry: 0} - queue := []*core.Node{entry} + scratch.generation++ + if scratch.generation == 0 { + clear(scratch.distances) + scratch.generation = 1 + } + generation := scratch.generation + scratch.distances[entry] = commonExitDistance{generation: generation} + queue := append(scratch.queue[:0], entry) for head := 0; head < len(queue); head++ { n := queue[head] if isMethodTerminal(n) || IsEndNode(n) { continue } + distance := scratch.distances[n].distance for _, next := range loopAnalysisSuccessors(n) { - if _, seen := distance[next]; !seen { - distance[next] = distance[n] + 1 - queue = append(queue, next) + if known, seen := scratch.distances[next]; seen && known.generation == generation { + continue } + scratch.distances[next] = commonExitDistance{generation: generation, distance: distance + 1} + queue = append(queue, next) } } if i == 0 { - common = distance for rank, n := range queue { - order[n] = rank + scratch.common[n] = scratch.distances[n].distance + scratch.order[n] = rank } + scratch.queue = queue[:0] continue } - for candidate := range common { - if d, reachable := distance[candidate]; reachable { - common[candidate] += d + for candidate := range scratch.common { + if d, reachable := scratch.distances[candidate]; reachable && d.generation == generation { + scratch.common[candidate] += d.distance } else { - delete(common, candidate) + delete(scratch.common, candidate) } } + scratch.queue = queue[:0] } + common := scratch.common + order := scratch.order var candidates []*core.Node for candidate := range common { if !IsEndNode(candidate) { diff --git a/classparser/decompiler/rewriter/post-dominator-tree.go b/classparser/decompiler/rewriter/post-dominator-tree.go index e3e39f5c..5b94c676 100644 --- a/classparser/decompiler/rewriter/post-dominator-tree.go +++ b/classparser/decompiler/rewriter/post-dominator-tree.go @@ -160,6 +160,17 @@ func GeneratePostDominatorMap(rootNode *core.Node) map[*core.Node]*core.Node { } } + // Cardinality of each fixed-point set is immutable now. The previous extraction + // recomputed bitsetCard for every candidate of every node, making immediate + // post-dominator extraction O(n * candidates * words). One precomputation turns + // each candidate comparison into an integer read. + cardinality := make([]int, total) + for i := 0; i < total; i++ { + if pdom[i] != nil { + cardinality[i] = bitsetCard(pdom[i], words) + } + } + // immediate post-dominator = strict post-dominator with the largest pdom set // (it is post-dominated by every other strict post-dominator, so its own set is // the most inclusive). The sink as ipdom means "exits the method" -> nil. @@ -180,9 +191,8 @@ func GeneratePostDominatorMap(rootNode *core.Node) map[*core.Node]*core.Node { if pos == i || pos >= total { continue } - card := bitsetCard(pdom[pos], words) - if card > bestCard { - bestCard = card + if cardinality[pos] > bestCard { + bestCard = cardinality[pos] bestId = pos } } diff --git a/classparser/decompiler/rewriter/protected_commit_exit.go b/classparser/decompiler/rewriter/protected_commit_exit.go index f786ce97..5d4fe5d7 100644 --- a/classparser/decompiler/rewriter/protected_commit_exit.go +++ b/classparser/decompiler/rewriter/protected_commit_exit.go @@ -150,7 +150,7 @@ func materializeProtectedCommitExit(m *RewriteManager, condition *core.Node) { replaceNextInPlace(edge.from, alternate, jump) } } - m.DominatorMap = GenerateDominatorTree(m.RootNode) + m.refreshDominatorsShared() return } } diff --git a/classparser/decompiler/rewriter/protected_normal_exits.go b/classparser/decompiler/rewriter/protected_normal_exits.go index 72128fc2..075b1888 100644 --- a/classparser/decompiler/rewriter/protected_normal_exits.go +++ b/classparser/decompiler/rewriter/protected_normal_exits.go @@ -122,7 +122,7 @@ func materializeProtectedNormalExit(manager *RewriteManager, condition *core.Nod jump.EncodedJumps = map[*core.Node]bool{alternate: true} replaceNextInPlace(edge.from, alternate, jump) } - manager.DominatorMap = GenerateDominatorTree(manager.RootNode) + manager.refreshDominatorsShared() return } } diff --git a/classparser/decompiler/rewriter/rewrite_var.go b/classparser/decompiler/rewriter/rewrite_var.go index f4730751..d8f0dec2 100644 --- a/classparser/decompiler/rewriter/rewrite_var.go +++ b/classparser/decompiler/rewriter/rewrite_var.go @@ -10,6 +10,7 @@ import ( "strings" "github.com/yaklang/javajive/classparser/decompiler/core/utils" + utils2 "github.com/yaklang/javajive/internal/utils" "github.com/yaklang/javajive/classparser/decompiler/core" "github.com/yaklang/javajive/classparser/decompiler/core/class_context" @@ -2151,13 +2152,12 @@ func statementsReadName(sts []statements.Statement, name string) (res bool) { res = true } }() - re := regexp.MustCompile(`\b` + regexp.QuoteMeta(name) + `\b`) for _, st := range sts { if as, ok := st.(*statements.AssignStatement); ok { - if as.JavaValue != nil && re.MatchString(as.JavaValue.String(&class_context.ClassContext{})) { + if as.JavaValue != nil && utils2.WordMatches(as.JavaValue.String(&class_context.ClassContext{}), name) { return true } - if as.ArrayMember != nil && re.MatchString(as.ArrayMember.String(&class_context.ClassContext{})) { + if as.ArrayMember != nil && utils2.WordMatches(as.ArrayMember.String(&class_context.ClassContext{}), name) { return true } if ref, ok := core.UnpackSoltValue(as.LeftValue).(*values.JavaRef); ok && ref.String(&class_context.ClassContext{}) == name && (as.IsFirst || as.IsDeclare) { @@ -2165,20 +2165,20 @@ func statementsReadName(sts []statements.Statement, name string) (res bool) { } continue } - if statementReadTextMatches(st, re) { + if statementReadTextMatches(st, name) { return true } } return false } -func statementReadTextMatches(st statements.Statement, re *regexp.Regexp) (res bool) { +func statementReadTextMatches(st statements.Statement, name string) (res bool) { defer func() { if recover() != nil { res = true } }() - return re.MatchString(st.String(&class_context.ClassContext{Env: jdecenv.Lookup()})) + return utils2.WordMatches(st.String(&class_context.ClassContext{Env: jdecenv.Lookup()}), name) } // statementsReferenceName reports whether any of the statements textually reference the variable @@ -2190,27 +2190,26 @@ func statementsReferenceName(sts []statements.Statement, name string, memos ...s if len(memos) > 0 { memo = memos[0] } - re := regexp.MustCompile(`\b` + regexp.QuoteMeta(name) + `\b`) for _, st := range sts { if memo != nil { text, ok := memo.render(st) - if !ok || re.MatchString(text) { + if !ok || utils2.WordMatches(text, name) { return true } - } else if statementTextMatches(st, re) { + } else if statementTextMatches(st, name) { return true } } return false } -func statementTextMatches(st statements.Statement, re *regexp.Regexp) (res bool) { +func statementTextMatches(st statements.Statement, name string) (res bool) { defer func() { if recover() != nil { res = true } }() - return re.MatchString(st.String(&class_context.ClassContext{Env: jdecenv.Lookup()})) + return utils2.WordMatches(st.String(&class_context.ClassContext{Env: jdecenv.Lookup()}), name) } // generatedLocalNameRe matches a decompiler-generated local name (var0, var1, var2_1, ...). Only @@ -2616,11 +2615,10 @@ func placeCrossScopeDeclarations(block *[]statements.Statement, reused map[*util continue } } - re := regexp.MustCompile(`\b` + regexp.QuoteMeta(name) + `\b`) cnt := 0 singleIdx := -1 for i := range list { - if allMatch[i] || re.MatchString(texts[i]) { + if allMatch[i] || utils2.WordMatches(texts[i], name) { cnt++ singleIdx = i } @@ -2699,6 +2697,7 @@ func isJavaLangObject(t types.JavaType) bool { // that immediately follows the name occurrence. var nullInitNarrowDot = regexp.MustCompile(`^\s*\.`) var nullInitNarrowAssign = regexp.MustCompile(`^\s*=([^=]|$)`) +var lhsAssignedNameRe = regexp.MustCompile(`\b([A-Za-z_$][\w$]*)\s*=\s*$`) // nameUsedOnlyAsReceiverOrLHS reports whether every textual occurrence of `name` in `text` is either a // method/field receiver (`name.x`) or an assignment target (`name = ...`). This is the safety predicate @@ -2709,8 +2708,7 @@ var nullInitNarrowAssign = regexp.MustCompile(`^\s*=([^=]|$)`) // other occurrence (argument, return, operand, array index, equality) makes the function return false, // so the caller conservatively leaves the declaration untouched. func nameUsedOnlyAsReceiverOrLHS(text, name string) bool { - re := regexp.MustCompile(`\b` + regexp.QuoteMeta(name) + `\b`) - locs := re.FindAllStringIndex(text, -1) + locs := utils2.WordSpans(text, name, nil) if len(locs) == 0 { return false } @@ -2971,12 +2969,10 @@ func widenConcreteDeclToObject(sts *[]statements.Statement) { } func nameOccurrencesAreObjectSafe(text, name string, objectNames map[string]struct{}) bool { - re := regexp.MustCompile(`\b` + regexp.QuoteMeta(name) + `\b`) - locs := re.FindAllStringIndex(text, -1) + locs := utils2.WordSpans(text, name, nil) if len(locs) == 0 { return false } - lhsNameRe := regexp.MustCompile(`\b([A-Za-z_$][\w$]*)\s*=\s*$`) for _, loc := range locs { before := text[:loc[0]] after := text[loc[1]:] @@ -3003,7 +2999,7 @@ func nameOccurrencesAreObjectSafe(text, name string, objectNames map[string]stru if strings.HasSuffix(rt, ")") { continue } - if m := lhsNameRe.FindStringSubmatch(before); m != nil { + if m := lhsAssignedNameRe.FindStringSubmatch(before); m != nil { if _, ok := objectNames[m[1]]; ok { continue } diff --git a/classparser/decompiler/rewriter/shared_literal_phi.go b/classparser/decompiler/rewriter/shared_literal_phi.go index 2554e095..8398a2d8 100644 --- a/classparser/decompiler/rewriter/shared_literal_phi.go +++ b/classparser/decompiler/rewriter/shared_literal_phi.go @@ -80,7 +80,7 @@ func splitSharedLiteralPhiStores(manager *RewriteManager, condition *core.Node) changed = true } if changed { - manager.DominatorMap = GenerateDominatorTree(manager.RootNode) + manager.refreshDominatorsShared() } } diff --git a/classparser/decompiler/rewriter/statement_analysis_cache.go b/classparser/decompiler/rewriter/statement_analysis_cache.go new file mode 100644 index 00000000..4a3d1d3c --- /dev/null +++ b/classparser/decompiler/rewriter/statement_analysis_cache.go @@ -0,0 +1,519 @@ +package rewriter + +import ( + "github.com/yaklang/javajive/classparser/decompiler/core" +) + +// statementGraphSnapshot is an exact, order-preserving snapshot of the statement +// CFG reachable from a root node. Nodes are numbered in the same DFS order as +// core.WalkGraph (and therefore GenerateDominatorTree), and every Next edge is +// recorded by index, including order and duplicates. Two snapshots are equal +// only when they describe the same node pointers with the same ordered edge +// lists; no hashing is involved, so a collision cannot make a stale dominator +// tree look current. +// +// Mutation audit: every edge write in the rewriter uses a core.Node method +// (AddNext, RemoveNext, ReplaceNext, ReplaceNextSliceKeepOrder, InsertNextAt, +// DuplicateNext, RemoveAllNext, Replace) or the direct Next assignments that +// still exist in core graph construction outside the rewrite loop. Because a +// refresh re-reads the live Next lists instead of trusting a version counter, +// even an un-instrumented direct write is detected before the next reuse. +type statementGraphSnapshot struct { + nodes []*core.Node + succs [][]int + index map[*core.Node]int + stack []*core.Node + visited map[*core.Node]struct{} +} + +func (s *statementGraphSnapshot) build(root *core.Node) { + s.nodes = s.nodes[:0] + if s.index == nil { + s.index = make(map[*core.Node]int) + } else { + clear(s.index) + } + if root == nil { + s.succs = s.succs[:0] + return + } + if s.visited == nil { + s.visited = make(map[*core.Node]struct{}) + } else { + clear(s.visited) + } + s.stack = append(s.stack[:0], root) + for len(s.stack) > 0 { + node := s.stack[len(s.stack)-1] + s.stack = s.stack[:len(s.stack)-1] + if _, ok := s.visited[node]; ok { + continue + } + s.visited[node] = struct{}{} + s.index[node] = len(s.nodes) + s.nodes = append(s.nodes, node) + s.stack = append(s.stack, node.Next...) + } + if cap(s.succs) < len(s.nodes) { + s.succs = make([][]int, len(s.nodes)) + } else { + s.succs = s.succs[:len(s.nodes)] + for i := range s.succs { + s.succs[i] = s.succs[i][:0] + } + } + for i, node := range s.nodes { + for _, next := range node.Next { + if index, ok := s.index[next]; ok { + s.succs[i] = append(s.succs[i], index) + } + } + } +} + +// statementTopologyDiff describes a snapshot change without hosing every +// cached loop body. changed lists nodes whose ordered successor list differs; +// neighbors is the union of their old and new successors. addedOrRemoved means +// node identity changed, which invalidates all cached bodies conservatively. +type statementTopologyDiff struct { + changed []*core.Node + neighbors []*core.Node + addedOrRemoved bool +} + +func (d *statementTopologyDiff) reset() { + d.changed = d.changed[:0] + d.neighbors = d.neighbors[:0] + d.addedOrRemoved = false +} + +// diff reports whether the snapshots are identical in node order and ordered +// successor lists. Otherwise it records enough information for a loop-body +// cache to keep entries whose loop region was untouched. +func (s *statementGraphSnapshot) diff(other *statementGraphSnapshot, out *statementTopologyDiff) bool { + out.reset() + if s == nil || other == nil { + return s == other + } + if len(s.nodes) != len(other.nodes) { + out.addedOrRemoved = true + } + orderSame := len(s.nodes) == len(other.nodes) + for i, node := range s.nodes { + j, ok := other.index[node] + if !ok { + out.addedOrRemoved = true + out.changed = append(out.changed, node) + continue + } + if i >= len(other.nodes) || other.nodes[i] != node { + orderSame = false + } + left, right := s.succs[i], other.succs[j] + same := len(left) == len(right) + if same { + for k := range left { + if s.nodes[left[k]] != other.nodes[right[k]] { + same = false + break + } + } + } + if !same { + out.changed = append(out.changed, node) + for _, index := range left { + out.neighbors = append(out.neighbors, s.nodes[index]) + } + for _, index := range right { + out.neighbors = append(out.neighbors, other.nodes[index]) + } + } + } + for j, node := range other.nodes { + if _, ok := s.index[node]; !ok { + out.addedOrRemoved = true + out.changed = append(out.changed, node) + for _, index := range other.succs[j] { + out.neighbors = append(out.neighbors, other.nodes[index]) + } + } + } + return orderSame && !out.addedOrRemoved && len(out.changed) == 0 +} + +// statementDominanceState owns the memoized analyses for one RewriteManager. +// A topology change swaps in a new snapshot and drops every derived result; +// non-topology Node fields (Id, Statement, flags, Source-only edits) cannot +// change dominance and therefore do not invalidate the cache. +type statementDominanceState struct { + root *core.Node + snapshot *statementGraphSnapshot + scratch *statementGraphSnapshot + graph *core.MutableAnalysisGraph + // diff describes the last topology change. topologyChanged is true when the + // snapshot was replaced; the loop-body cache consumes diff after refresh. + diff statementTopologyDiff + topologyChanged bool + + domAnalysis *core.GraphAnalysis + domTree map[*core.Node][]*core.Node + domParents []*core.Node + domParentScratch []*core.Node + domReady bool + domComputes int + postMap map[*core.Node]*core.Node + postIndex []int + postCanExit []bool + postReady bool + postComputes int +} + +func (s *statementDominanceState) refresh(root *core.Node) { + if s.scratch == nil { + s.scratch = &statementGraphSnapshot{} + } + s.scratch.build(root) + if s.snapshot != nil { + if s.snapshot.diff(s.scratch, &s.diff) { + s.root = root + s.topologyChanged = false + return + } + s.topologyChanged = true + } else { + // No derived analysis or loop-body cache exists yet. + s.diff.reset() + s.topologyChanged = false + } + s.snapshot, s.scratch = s.scratch, s.snapshot + s.root = root + s.domAnalysis = nil + s.domReady = false + s.postMap = nil + s.postIndex = nil + s.postCanExit = nil + s.postReady = false + s.resetGraph() +} + +// resetGraph replaces the graph topology in place. The graph identity and its +// edge/scratch storage survive, while the epoch changes so cached analyses from +// the previous topology cannot be mistaken for the new one. +func (s *statementDominanceState) resetGraph() { + nodes := 0 + if s.snapshot != nil { + nodes = len(s.snapshot.nodes) + } + if s.graph == nil { + s.graph = core.NewMutableAnalysisGraph(nodes, core.NewGraphAnalysisCache(2)) + } else { + s.graph.Reset(nodes) + } + if s.snapshot == nil { + return + } + for from, succs := range s.snapshot.succs { + for _, to := range succs { + s.graph.AddEdge(from, to, false) + } + } +} + +// dominatorTree computes the canonical child-list tree once per topology. The +// node numbering is the snapshot's WalkGraph order, so iterating node indexes in +// order appends children exactly like GenerateDominatorTree. +// +// The map and its child slices survive topology changes: each rebuild truncates +// the previous parents' children in place and drops parents that lost all +// children. Callers must treat the returned map as read-only, which the rewrite +// loop already does (refreshDominators still clones for the exported field). +func (s *statementDominanceState) dominatorTree() map[*core.Node][]*core.Node { + if s.domReady { + return s.domTree + } + s.domReady = true + s.domComputes++ + if s.domTree == nil { + s.domTree = make(map[*core.Node][]*core.Node) + } + if s.snapshot == nil || len(s.snapshot.nodes) == 0 { + s.clearDominatorTree() + return s.domTree + } + if s.graph == nil { + s.resetGraph() + } + // The state only reads IDom and the graph is replaced on every topology + // change, so the cache-owned analysis is safe to borrow here; a defensive + // deep copy per rewrite step would only add allocation. + analysis := s.graph.GetOrComputeShared(core.AnalysisDominators, core.GraphAnalysisDomain{Roots: []int{0}}) + s.domAnalysis = analysis + if analysis == nil { + s.clearDominatorTree() + return s.domTree + } + previous := s.domParents + for _, parent := range previous { + children, ok := s.domTree[parent] + if !ok { + continue + } + s.domTree[parent] = children[:0] + } + next := s.domParentScratch[:0] + for i, node := range s.snapshot.nodes { + if i >= len(analysis.IDom) { + break + } + idom := analysis.IDom[i] + if idom < 0 || idom == i || idom >= len(s.snapshot.nodes) { + continue + } + parent := s.snapshot.nodes[idom] + children, ok := s.domTree[parent] + // Truncated parents have len 0 and must be re-registered on their first + // child; parents with no remaining children are dropped below. + if !ok || len(children) == 0 { + next = append(next, parent) + } + s.domTree[parent] = append(children, node) + } + for _, parent := range previous { + if children, ok := s.domTree[parent]; ok && len(children) == 0 { + delete(s.domTree, parent) + } + } + s.domParentScratch = previous[:0] + s.domParents = next + return s.domTree +} + +// clearDominatorTree empties the reusable tree and its parent index. The map +// allocation survives; only the entries are dropped. +func (s *statementDominanceState) clearDominatorTree() { + for _, parent := range s.domParents { + delete(s.domTree, parent) + } + s.domParents = s.domParents[:0] +} + +// postDominatorMap computes the canonical immediate-post-dominator map once per +// topology. The map excludes nodes with no real post-dominator (method exits and +// exit-less SCCs), matching GeneratePostDominatorMap exactly. +func (s *statementDominanceState) postDominatorMap() map[*core.Node]*core.Node { + if s.postReady { + return s.postMap + } + s.postReady = true + s.postComputes++ + s.postMap = GeneratePostDominatorMap(s.root) + s.buildPostIndex() + return s.postMap +} + +func (s *statementDominanceState) buildPostIndex() { + if s.snapshot == nil { + s.postIndex = nil + s.postCanExit = nil + return + } + n := len(s.snapshot.nodes) + s.postIndex = make([]int, n) + for i := range s.postIndex { + s.postIndex[i] = -1 + } + for i, node := range s.snapshot.nodes { + parent := s.postMap[node] + if parent == nil { + continue + } + if index, ok := s.snapshot.index[parent]; ok { + s.postIndex[i] = index + } + } + s.postCanExit = statementCanReachExit(s.snapshot) +} + +// statementCanReachExit marks every node that can reach a real method exit. +// Nodes trapped in an exit-less SCC have no post-dominator and are excluded from +// the scalar PostDominates relation as well as from the cached map. +func statementCanReachExit(snapshot *statementGraphSnapshot) []bool { + n := len(snapshot.nodes) + can := make([]bool, n) + reverse := make([][]int, n) + queue := make([]int, 0, n) + for from, succs := range snapshot.succs { + if len(succs) == 0 { + can[from] = true + queue = append(queue, from) + } + for _, to := range succs { + reverse[to] = append(reverse[to], from) + } + } + for len(queue) > 0 { + node := queue[len(queue)-1] + queue = queue[:len(queue)-1] + for _, pred := range reverse[node] { + if !can[pred] { + can[pred] = true + queue = append(queue, pred) + } + } + } + return can +} + +func (s *statementDominanceState) dominates(dominator, node *core.Node) bool { + if dominator == nil || node == nil { + return false + } + // utils.IsDominate treats a node as dominating itself even when it is not + // reachable from the analyzed root; keep that observable behavior. + if dominator == node { + return true + } + s.dominatorTree() + if s.domAnalysis == nil || s.snapshot == nil { + return false + } + domIndex, ok := s.snapshot.index[dominator] + if !ok { + return false + } + nodeIndex, ok := s.snapshot.index[node] + if !ok { + return false + } + return s.domAnalysis.Dominates(domIndex, nodeIndex) +} + +func (s *statementDominanceState) postDominates(post, node *core.Node) bool { + if post == nil || node == nil || s.snapshot == nil { + return false + } + s.postDominatorMap() + nodeIndex, ok := s.snapshot.index[node] + if !ok || nodeIndex >= len(s.postCanExit) || !s.postCanExit[nodeIndex] { + return false + } + if post == node { + return true + } + postIndex, ok := s.snapshot.index[post] + if !ok { + return false + } + cur := nodeIndex + for steps := 0; steps < len(s.postIndex) && cur >= 0; steps++ { + parent := s.postIndex[cur] + if parent == postIndex { + return true + } + if parent < 0 || parent == cur { + return false + } + cur = parent + } + return false +} + +func (s *RewriteManager) dominanceState() *statementDominanceState { + if s.dominance == nil { + s.dominance = &statementDominanceState{} + } + return s.dominance +} + +// refreshDominators is the single place the rewriter refreshes DominatorMap. +// It reuses the memoized tree when the statement topology is byte-for-byte +// identical and returns a defensive copy so callers can never poison the cache. +func (s *RewriteManager) refreshDominators() { + state := s.dominanceState() + state.refresh(s.RootNode) + s.DominatorMap = cloneDominatorTree(state.dominatorTree()) + s.domMapVersion++ + s.domMapDirty = false + s.invalidateLoopBasesAfterTopology(state) +} + +// refreshDominatorsShared refreshes the production rewriter's map in place. +// Rewriter call sites only read DominatorMap; avoiding a full map copy on every +// refresh keeps small methods from paying the cache's defensive-copy overhead. +// The exported-field clone contract remains on refreshDominators (exercised by +// tests and available to callers that mutate the field). +func (s *RewriteManager) refreshDominatorsShared() { + state := s.dominanceState() + state.refresh(s.RootNode) + s.DominatorMap = state.dominatorTree() + if state.topologyChanged || s.domMapDirty { + s.domMapVersion++ + s.domMapDirty = false + } + s.invalidateLoopBasesAfterTopology(state) +} + +// postDominatorMap returns a defensive copy of the memoized immediate +// post-dominator map for the current topology. +func (s *RewriteManager) postDominatorMap() map[*core.Node]*core.Node { + state := s.dominanceState() + state.refresh(s.RootNode) + if state.topologyChanged { + // These query methods do not publish a fresh DominatorMap; keep the + // base-body cache and dominance index conservative until the rewrite + // loop refreshes. + s.domMapDirty = true + s.domIndex = nil + s.clearLoopBases() + } + return clonePostDominatorMap(state.postDominatorMap()) +} + +// Dominates is the internal scalar dominance query. It reuses the cached +// analysis in place instead of cloning it per call. +func (s *RewriteManager) Dominates(dominator, node *core.Node) bool { + state := s.dominanceState() + state.refresh(s.RootNode) + if state.topologyChanged { + s.domMapDirty = true + s.domIndex = nil + s.clearLoopBases() + } + return state.dominates(dominator, node) +} + +// PostDominates is the internal scalar post-dominance query. It reuses the +// cached immediate-post-dominator chain in place. A node trapped in an +// exit-less SCC has no post-dominator, including itself. +func (s *RewriteManager) PostDominates(post, node *core.Node) bool { + state := s.dominanceState() + state.refresh(s.RootNode) + if state.topologyChanged { + s.domMapDirty = true + s.domIndex = nil + s.clearLoopBases() + } + return state.postDominates(post, node) +} + +func cloneDominatorTree(tree map[*core.Node][]*core.Node) map[*core.Node][]*core.Node { + if tree == nil { + return nil + } + out := make(map[*core.Node][]*core.Node, len(tree)) + for parent, children := range tree { + out[parent] = append([]*core.Node(nil), children...) + } + return out +} + +func clonePostDominatorMap(tree map[*core.Node]*core.Node) map[*core.Node]*core.Node { + if tree == nil { + return nil + } + out := make(map[*core.Node]*core.Node, len(tree)) + for node, parent := range tree { + out[node] = parent + } + return out +} diff --git a/classparser/decompiler/rewriter/statement_analysis_cache_bench_test.go b/classparser/decompiler/rewriter/statement_analysis_cache_bench_test.go new file mode 100644 index 00000000..b0824c42 --- /dev/null +++ b/classparser/decompiler/rewriter/statement_analysis_cache_bench_test.go @@ -0,0 +1,127 @@ +package rewriter + +import ( + "testing" + + "github.com/yaklang/javajive/classparser/decompiler/core" + "github.com/yaklang/javajive/classparser/decompiler/core/statements" +) + +var ( + benchmarkDominatorSink map[*core.Node][]*core.Node + benchmarkPostDomSink map[*core.Node]*core.Node + benchmarkDominanceAnswer bool +) + +func cacheBenchGraph(n int) []*core.Node { + nodes := make([]*core.Node, n) + for i := range nodes { + nodes[i] = core.NewNode(&statements.MiddleStatement{Flag: "bench"}) + nodes[i].Id = i + } + for i := 0; i+1 < n; i++ { + nodes[i].AddNext(nodes[i+1]) + } + for i := 1; i+2 < n; i += 4 { + nodes[i].AddNext(nodes[i+2]) + } + for i := 0; i+7 < n; i += 7 { + nodes[i].AddNext(nodes[(i*31+17)%n]) + } + if n > 3 { + nodes[n-2].AddNext(nodes[n/3]) + } + return nodes +} + +func BenchmarkGenerateDominatorTreeFresh(b *testing.B) { + nodes := cacheBenchGraph(1024) + root := nodes[0] + b.ResetTimer() + for i := 0; i < b.N; i++ { + benchmarkDominatorSink = GenerateDominatorTree(root) + } +} + +func BenchmarkGenerateDominatorTreeAfterMutation(b *testing.B) { + nodes := cacheBenchGraph(1024) + root, last := nodes[0], nodes[len(nodes)-1] + b.ResetTimer() + for i := 0; i < b.N; i++ { + if i%2 == 0 { + root.AddNext(last) + } else { + root.RemoveNext(last) + } + benchmarkDominatorSink = GenerateDominatorTree(root) + } +} + +func BenchmarkStatementDominanceCacheRefreshUnchanged(b *testing.B) { + nodes := cacheBenchGraph(1024) + m := NewRootStatementManager(nodes[0]) + m.refreshDominators() + b.ResetTimer() + for i := 0; i < b.N; i++ { + m.refreshDominators() + benchmarkDominatorSink = m.DominatorMap + } +} + +func BenchmarkStatementDominanceCacheRefreshAfterMutation(b *testing.B) { + nodes := cacheBenchGraph(1024) + m := NewRootStatementManager(nodes[0]) + m.refreshDominators() + root, last := nodes[0], nodes[len(nodes)-1] + b.ResetTimer() + for i := 0; i < b.N; i++ { + if i%2 == 0 { + root.AddNext(last) + } else { + root.RemoveNext(last) + } + m.refreshDominators() + benchmarkDominatorSink = m.DominatorMap + } +} + +func BenchmarkGeneratePostDominatorMapFresh(b *testing.B) { + nodes := cacheBenchGraph(1024) + root := nodes[0] + b.ResetTimer() + for i := 0; i < b.N; i++ { + benchmarkPostDomSink = GeneratePostDominatorMap(root) + } +} + +func BenchmarkStatementDominanceCachePostDominatorsUnchanged(b *testing.B) { + nodes := cacheBenchGraph(1024) + m := NewRootStatementManager(nodes[0]) + _ = m.postDominatorMap() + b.ResetTimer() + for i := 0; i < b.N; i++ { + benchmarkPostDomSink = m.postDominatorMap() + } +} + +func BenchmarkStatementDominanceCacheDominatesUnchanged(b *testing.B) { + nodes := cacheBenchGraph(1024) + m := NewRootStatementManager(nodes[0]) + root, last := nodes[0], nodes[len(nodes)-1] + _ = m.Dominates(root, last) + b.ResetTimer() + for i := 0; i < b.N; i++ { + benchmarkDominanceAnswer = m.Dominates(root, last) + } +} + +func BenchmarkStatementDominanceCachePostDominatesUnchanged(b *testing.B) { + nodes := cacheBenchGraph(1024) + m := NewRootStatementManager(nodes[0]) + root, last := nodes[0], nodes[len(nodes)-1] + _ = m.PostDominates(last, root) + b.ResetTimer() + for i := 0; i < b.N; i++ { + benchmarkDominanceAnswer = m.PostDominates(last, root) + } +} diff --git a/classparser/decompiler/rewriter/statement_analysis_cache_differential_test.go b/classparser/decompiler/rewriter/statement_analysis_cache_differential_test.go new file mode 100644 index 00000000..cc7cc7f5 --- /dev/null +++ b/classparser/decompiler/rewriter/statement_analysis_cache_differential_test.go @@ -0,0 +1,143 @@ +package rewriter + +import ( + "math/rand" + "testing" + + "github.com/yaklang/javajive/classparser/decompiler/core" + "github.com/yaklang/javajive/classparser/decompiler/core/statements" +) + +// cacheDifferentialGraph builds a random CFG whose nodes are all reachable +// from node 0. Random extra edges introduce branches, joins, back edges and +// exit-less cycles; no assumption is made about reducibility. +func cacheDifferentialGraph(r *rand.Rand, n int) (*core.Node, []*core.Node) { + nodes := make([]*core.Node, n) + for i := range nodes { + nodes[i] = core.NewNode(&statements.MiddleStatement{Flag: "n"}) + nodes[i].Id = i + } + for i := 1; i < n; i++ { + nodes[r.Intn(i)].AddNext(nodes[i]) + } + extra := r.Intn(2*n) + 1 + for i := 0; i < extra; i++ { + nodes[r.Intn(n)].AddNext(nodes[r.Intn(n)]) + } + return nodes[0], nodes +} + +// cacheDifferentialMutate exercises every mutation shape the rewriter uses: +// the Node methods plus the direct Next assignments/slicing that cannot be +// intercepted. +func cacheDifferentialMutate(r *rand.Rand, m *RewriteManager, nodes []*core.Node) { + if len(nodes) == 0 { + return + } + node := nodes[r.Intn(len(nodes))] + switch r.Intn(9) { + case 0: + node.AddNext(nodes[r.Intn(len(nodes))]) + case 1: + if len(node.Next) > 0 { + node.RemoveNext(node.Next[r.Intn(len(node.Next))]) + } + case 2: + if len(node.Next) > 0 { + node.ReplaceNext(node.Next[0], nodes[r.Intn(len(nodes))]) + } + case 3: + if len(node.Next) > 0 { + count := 1 + r.Intn(2) + news := make([]*core.Node, 0, count) + for i := 0; i < count; i++ { + news = append(news, nodes[r.Intn(len(nodes))]) + } + node.ReplaceNextSliceKeepOrder(node.Next[0], news) + } + case 4: + node.InsertNextAt(r.Intn(len(node.Next)+1), nodes[r.Intn(len(nodes))]) + case 5: + if len(node.Next) > 0 { + node.DuplicateNext(r.Intn(len(node.Next))) + } + case 6: + node.Next = []*core.Node{nodes[r.Intn(len(nodes))]} + case 7: + if len(node.Next) > 0 { + node.Next = append(node.Next[:0:0], node.Next[1:]...) + } + case 8: + if len(node.Next) > 0 { + node.Next[r.Intn(len(node.Next))] = nodes[r.Intn(len(nodes))] + } + } +} + +func TestStatementDominanceCacheDifferentialRandomized(t *testing.T) { + r := rand.New(rand.NewSource(0x5eed)) + for iteration := 0; iteration < 1500; iteration++ { + nodeCount := 1 + r.Intn(14) + root, nodes := cacheDifferentialGraph(r, nodeCount) + m := NewRootStatementManager(root) + m.SetId(nodeCount + 100) + + m.refreshDominators() + if want := GenerateDominatorTree(root); !cacheTestEqualDominatorTrees(m.DominatorMap, want) { + t.Fatalf("iteration %d initial dominators differ\ncached=%v\nfresh=%v", iteration, m.DominatorMap, want) + } + if want := GeneratePostDominatorMap(root); !cacheTestEqualPostDominators(m.postDominatorMap(), want) { + t.Fatalf("iteration %d initial post-dominators differ", iteration) + } + + for step := 0; step < 6; step++ { + cacheDifferentialMutate(r, m, nodes) + m.refreshDominators() + if want := GenerateDominatorTree(m.RootNode); !cacheTestEqualDominatorTrees(m.DominatorMap, want) { + t.Fatalf("iteration %d step %d dominators differ after mutation\ncached=%v\nfresh=%v", iteration, step, m.DominatorMap, want) + } + if want := GeneratePostDominatorMap(m.RootNode); !cacheTestEqualPostDominators(m.postDominatorMap(), want) { + t.Fatalf("iteration %d step %d post-dominators differ after mutation", iteration, step) + } + } + } +} + +func TestStatementDominanceCacheOnlyAnalyzesReachableNodes(t *testing.T) { + root := core.NewNode(&statements.MiddleStatement{Flag: "root"}) + reachable := core.NewNode(&statements.ReturnStatement{}) + isolated := core.NewNode(&statements.MiddleStatement{Flag: "isolated"}) + isolatedTarget := core.NewNode(&statements.ReturnStatement{}) + root.Id, reachable.Id, isolated.Id, isolatedTarget.Id = 0, 1, 2, 3 + root.AddNext(reachable) + isolated.AddNext(isolatedTarget) + + m := NewRootStatementManager(root) + m.refreshDominators() + if want := GenerateDominatorTree(root); !cacheTestEqualDominatorTrees(m.DominatorMap, want) { + t.Fatal("initial reachable-only tree differs") + } + domComputes := m.dominance.domComputes + + // Mutating an unreachable component cannot change the result and must not + // force a recompute. + isolatedTarget.AddNext(isolated) + isolated.RemoveNext(isolatedTarget) + m.refreshDominators() + if m.dominance.domComputes != domComputes { + t.Fatal("unreachable component mutation forced a recompute") + } + if !cacheTestEqualDominatorTrees(m.DominatorMap, GenerateDominatorTree(root)) { + t.Fatal("unreachable component mutation changed the cached tree") + } + + // Making it reachable must invalidate. + root.AddNext(isolated) + m.refreshDominators() + if m.dominance.domComputes != domComputes+1 { + t.Fatalf("reachable component addition computes=%d, want %d", m.dominance.domComputes, domComputes+1) + } + if want := GenerateDominatorTree(root); !cacheTestEqualDominatorTrees(m.DominatorMap, want) { + t.Fatal("newly reachable nodes missing from cached tree") + } +} diff --git a/classparser/decompiler/rewriter/statement_analysis_cache_test.go b/classparser/decompiler/rewriter/statement_analysis_cache_test.go new file mode 100644 index 00000000..8d969c9a --- /dev/null +++ b/classparser/decompiler/rewriter/statement_analysis_cache_test.go @@ -0,0 +1,410 @@ +package rewriter + +import ( + "testing" + + "github.com/yaklang/javajive/classparser/decompiler/core" + "github.com/yaklang/javajive/classparser/decompiler/core/statements" + "github.com/yaklang/javajive/classparser/decompiler/utils" +) + +// cacheTestGraph builds a deterministic, branchy CFG with a back edge and a +// real method exit. All nodes are reachable from node 0. +func cacheTestGraph(n int) []*core.Node { + nodes := make([]*core.Node, n) + for i := range nodes { + nodes[i] = core.NewNode(&statements.MiddleStatement{Flag: "start"}) + nodes[i].Id = i + } + for i := 0; i+1 < n; i++ { + nodes[i].AddNext(nodes[i+1]) + } + for i := 1; i+2 < n; i += 3 { + nodes[i].AddNext(nodes[i+2]) + } + if n > 3 { + nodes[n-2].AddNext(nodes[n/2]) + } + return nodes +} + +func cacheTestManager(n int) (*RewriteManager, []*core.Node) { + nodes := cacheTestGraph(n) + m := NewRootStatementManager(nodes[0]) + m.SetId(n + 100) + return m, nodes +} + +func cacheTestEqualDominatorTrees(left, right map[*core.Node][]*core.Node) bool { + if len(left) != len(right) { + return false + } + for parent, children := range left { + other, ok := right[parent] + if !ok || len(children) != len(other) { + return false + } + for i := range children { + if children[i] != other[i] { + return false + } + } + } + return true +} + +func cacheTestEqualPostDominators(left, right map[*core.Node]*core.Node) bool { + if len(left) != len(right) { + return false + } + for node, parent := range left { + if right[node] != parent { + return false + } + } + return true +} + +func cacheTestAssertFreshDominators(t *testing.T, m *RewriteManager) { + t.Helper() + m.refreshDominators() + if want := GenerateDominatorTree(m.RootNode); !cacheTestEqualDominatorTrees(m.DominatorMap, want) { + t.Fatalf("cached dominator tree differs from fresh GenerateDominatorTree\ncached=%v\nfresh=%v", m.DominatorMap, want) + } +} + +func cacheTestAssertFreshPostDominators(t *testing.T, m *RewriteManager) { + t.Helper() + got := m.postDominatorMap() + if want := GeneratePostDominatorMap(m.RootNode); !cacheTestEqualPostDominators(got, want) { + t.Fatalf("cached post-dominators differ from fresh GeneratePostDominatorMap\ncached=%v\nfresh=%v", got, want) + } +} + +func TestStatementDominanceCacheRepeatedQueriesComputeOnce(t *testing.T) { + m, _ := cacheTestManager(14) + root := m.RootNode + + m.refreshDominators() + if m.dominance == nil { + t.Fatal("dominance state not initialized") + } + if m.dominance.domComputes != 1 { + t.Fatalf("first refresh computed %d times, want 1", m.dominance.domComputes) + } + first := cloneDominatorTree(m.DominatorMap) + if !cacheTestEqualDominatorTrees(first, GenerateDominatorTree(root)) { + t.Fatal("first cached tree differs from fresh analysis") + } + + firstPost := m.postDominatorMap() + if m.dominance.postComputes != 1 { + t.Fatalf("first post query computed %d times, want 1", m.dominance.postComputes) + } + + for i := 0; i < 100; i++ { + m.refreshDominators() + if !cacheTestEqualDominatorTrees(m.DominatorMap, first) { + t.Fatalf("refresh %d changed an unchanged topology", i) + } + if post := m.postDominatorMap(); !cacheTestEqualPostDominators(post, firstPost) { + t.Fatalf("post refresh %d changed an unchanged topology", i) + } + } + if m.dominance.domComputes != 1 || m.dominance.postComputes != 1 { + t.Fatalf("repeated unchanged queries recomputed: dom=%d post=%d", m.dominance.domComputes, m.dominance.postComputes) + } + if m.dominance.graph == nil || m.dominance.graph.ComputeCount() != 1 { + t.Fatalf("GraphAnalysisCache constructions = %v, want 1", m.dominance.graph) + } + + // Non-topology fields must not invalidate the memoized analyses either. + firstDom := cloneDominatorTree(m.DominatorMap) + m.DominatorMap = nil + m.refreshDominators() + if m.dominance.domComputes != 1 || !cacheTestEqualDominatorTrees(m.DominatorMap, firstDom) { + t.Fatalf("nil field assignment should not invalidate: computes=%d", m.dominance.domComputes) + } +} + +func TestStatementDominanceCacheTracksTopologyMutationPaths(t *testing.T) { + cases := []struct { + name string + mutate func(m *RewriteManager, nodes []*core.Node) + }{ + { + name: "AddNext", + mutate: func(_ *RewriteManager, nodes []*core.Node) { + nodes[5].AddNext(nodes[1]) + }, + }, + { + name: "RemoveNext", + mutate: func(_ *RewriteManager, nodes []*core.Node) { + nodes[4].RemoveNext(nodes[5]) + }, + }, + { + name: "ReplaceNext", + mutate: func(_ *RewriteManager, nodes []*core.Node) { + nodes[2].ReplaceNext(nodes[3], nodes[8]) + }, + }, + { + name: "ReplaceNextSliceKeepOrder", + mutate: func(_ *RewriteManager, nodes []*core.Node) { + nodes[2].ReplaceNextSliceKeepOrder(nodes[3], []*core.Node{nodes[8], nodes[9]}) + }, + }, + { + name: "InsertNextAt", + mutate: func(_ *RewriteManager, nodes []*core.Node) { + nodes[1].InsertNextAt(1, nodes[10]) + }, + }, + { + name: "DuplicateNext", + mutate: func(_ *RewriteManager, nodes []*core.Node) { + nodes[1].DuplicateNext(0) + }, + }, + { + name: "DirectNextAssignment", + mutate: func(_ *RewriteManager, nodes []*core.Node) { + nodes[2].Next = []*core.Node{nodes[7]} + }, + }, + { + name: "DirectSliceTruncation", + mutate: func(_ *RewriteManager, nodes []*core.Node) { + nodes[2].Next = append(nodes[2].Next[:0], nodes[2].Next[1:]...) + }, + }, + { + name: "SuccessorOrderSwap", + mutate: func(_ *RewriteManager, nodes []*core.Node) { + nodes[12].Next[0], nodes[12].Next[1] = nodes[12].Next[1], nodes[12].Next[0] + }, + }, + { + name: "RemoveAllNext", + mutate: func(_ *RewriteManager, nodes []*core.Node) { + nodes[6].RemoveAllNext() + }, + }, + { + name: "NodeReplace", + mutate: func(m *RewriteManager, nodes []*core.Node) { + replacement := m.NewNode(&statements.MiddleStatement{Flag: "start"}) + nodes[7].Replace(replacement) + }, + }, + { + name: "RootReplacement", + mutate: func(m *RewriteManager, nodes []*core.Node) { + m.RootNode = nodes[3] + }, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + m, nodes := cacheTestManager(14) + m.refreshDominators() + _ = m.postDominatorMap() + domBefore := m.dominance.domComputes + postBefore := m.dominance.postComputes + + tc.mutate(m, nodes) + + cacheTestAssertFreshDominators(t, m) + if got := m.dominance.domComputes; got != domBefore+1 { + t.Fatalf("dominator computes after %s = %d, want %d", tc.name, got, domBefore+1) + } + cacheTestAssertFreshPostDominators(t, m) + if got := m.dominance.postComputes; got != postBefore+1 { + t.Fatalf("post-dominator computes after %s = %d, want %d", tc.name, got, postBefore+1) + } + }) + } +} + +func TestStatementDominanceCacheIgnoresNonTopologyFields(t *testing.T) { + m, nodes := cacheTestManager(14) + m.refreshDominators() + _ = m.postDominatorMap() + domBefore := m.dominance.domComputes + postBefore := m.dominance.postComputes + first := cloneDominatorTree(m.DominatorMap) + firstPost := clonePostDominatorMap(m.postDominatorMap()) + + nodes[3].Id = 999 + nodes[3].Statement = &statements.MiddleStatement{Flag: "changed"} + nodes[3].Source = append(nodes[3].Source, nodes[4]) + nodes[3].IsCircle = true + nodes[3].IsIf = true + nodes[3].EncodedJumps = map[*core.Node]bool{nodes[4]: true} + _ = core.NewNode(&statements.MiddleStatement{Flag: "unreachable"}) + + m.refreshDominators() + if m.dominance.domComputes != domBefore { + t.Fatalf("non-topology mutation recomputed dominators: %d -> %d", domBefore, m.dominance.domComputes) + } + if !cacheTestEqualDominatorTrees(m.DominatorMap, first) { + t.Fatal("non-topology mutation changed the cached dominator tree") + } + if post := m.postDominatorMap(); m.dominance.postComputes != postBefore || !cacheTestEqualPostDominators(post, firstPost) { + t.Fatal("non-topology mutation invalidated post-dominators") + } + cacheTestAssertFreshDominators(t, m) + cacheTestAssertFreshPostDominators(t, m) +} + +func TestStatementDominanceCacheReturnsDefensiveCopies(t *testing.T) { + m, nodes := cacheTestManager(14) + root := m.RootNode + m.refreshDominators() + + // Poison the caller-visible tree exactly as a mutating caller could. + for node := range m.DominatorMap { + delete(m.DominatorMap, node) + } + m.DominatorMap[nodes[0]] = []*core.Node{nodes[1], nil} + if children := m.DominatorMap[nodes[0]]; len(children) > 0 { + children[0] = nil + } + + cacheTestAssertFreshDominators(t, m) + if m.dominance.domComputes != 1 { + t.Fatalf("poisoned public map forced a recompute: %d", m.dominance.domComputes) + } + if !cacheTestEqualDominatorTrees(m.DominatorMap, GenerateDominatorTree(root)) { + t.Fatal("internal dominator tree leaked through a mutable public map") + } + + post := m.postDominatorMap() + for node := range post { + delete(post, node) + } + post[nodes[0]] = nodes[1] + cacheTestAssertFreshPostDominators(t, m) + if m.dominance.postComputes != 1 { + t.Fatalf("poisoned post-dominator map forced a recompute: %d", m.dominance.postComputes) + } +} + +func TestStatementDominanceCacheScalarQueries(t *testing.T) { + m, nodes := cacheTestManager(14) + root := m.RootNode + m.refreshDominators() + tree := GenerateDominatorTree(root) + for _, left := range nodes { + for _, right := range nodes { + got := m.Dominates(left, right) + want := utils.IsDominate(tree, left, right) + if got != want { + t.Fatalf("Dominates(%d,%d)=%v, want %v", left.Id, right.Id, got, want) + } + } + } + + postTree := GeneratePostDominatorMap(root) + for _, left := range nodes { + for _, right := range nodes { + want := left == right + if !want { + for current := right; current != nil; { + parent := postTree[current] + if parent == nil { + break + } + if parent == left { + want = true + break + } + current = parent + } + } + if got := m.PostDominates(left, right); got != want { + t.Fatalf("PostDominates(%d,%d)=%v, want %v", left.Id, right.Id, got, want) + } + } + } +} + +func TestStatementDominanceCacheScanCoreInfoReusesUnchangedAnalysis(t *testing.T) { + m, _ := cacheTestManager(12) + if err := m.ScanCoreInfo(); err != nil { + t.Fatal(err) + } + domComputes := m.dominance.domComputes + postComputes := m.dominance.postComputes + + // ScanCoreInfo updates classification flags (IsIf/IsMerge/loop callbacks) + // but not Next edges, so a second scan must reuse the same analyses. + if err := m.ScanCoreInfo(); err != nil { + t.Fatal(err) + } + if m.dominance.domComputes != domComputes { + t.Fatalf("second ScanCoreInfo recomputed dominators: %d -> %d", domComputes, m.dominance.domComputes) + } + if m.dominance.postComputes != postComputes { + t.Fatalf("second ScanCoreInfo recomputed post-dominators: %d -> %d", postComputes, m.dominance.postComputes) + } + cacheTestAssertFreshDominators(t, m) + cacheTestAssertFreshPostDominators(t, m) +} + +func TestStatementDominanceCacheNilRoot(t *testing.T) { + m := &RewriteManager{} + m.refreshDominators() + if m.DominatorMap == nil || len(m.DominatorMap) != 0 { + t.Fatalf("nil root produced %v, want an empty dominator map", m.DominatorMap) + } + if !cacheTestEqualDominatorTrees(m.DominatorMap, GenerateDominatorTree(nil)) { + t.Fatal("nil root differs from GenerateDominatorTree(nil)") + } + if post := m.postDominatorMap(); post == nil || len(post) != 0 { + t.Fatalf("nil root produced post-dominators %v, want empty", post) + } + if m.Dominates(nil, nil) || m.PostDominates(nil, nil) { + t.Fatal("nil nodes must not dominate or post-dominate") + } + if m.dominance.domComputes != 1 || m.dominance.postComputes != 1 { + t.Fatalf("nil root computes dom=%d post=%d", m.dominance.domComputes, m.dominance.postComputes) + } + m.refreshDominators() + if m.dominance.domComputes != 1 { + t.Fatal("repeated nil-root refresh recomputed") + } +} + +func TestStatementDominanceCachePostDominatorExitLessComponent(t *testing.T) { + root := core.NewNode(&statements.MiddleStatement{Flag: "root"}) + exit := core.NewNode(&statements.ReturnStatement{}) + loop := core.NewNode(&statements.MiddleStatement{Flag: "loop"}) + root.Id, exit.Id, loop.Id = 0, 1, 2 + root.AddNext(exit) + root.AddNext(loop) + loop.AddNext(loop) + + m := NewRootStatementManager(root) + m.refreshDominators() + cacheTestAssertFreshDominators(t, m) + cacheTestAssertFreshPostDominators(t, m) + + if !m.PostDominates(exit, root) { + t.Fatal("reachable exit should post-dominate the branch") + } + if m.PostDominates(loop, root) { + t.Fatal("exit-less SCC must not post-dominate a branching node") + } + if m.PostDominates(loop, loop) { + t.Fatal("exit-less SCC has no post-dominator, including itself") + } + if !m.PostDominates(exit, exit) { + t.Fatal("a real exit post-dominates itself") + } + if m.dominance.postComputes != 1 { + t.Fatalf("post-dominators recomputed on repeated scalar queries: %d", m.dominance.postComputes) + } +} diff --git a/classparser/decompiler/rewriter/statement_wrap.go b/classparser/decompiler/rewriter/statement_wrap.go index 432abcca..9cbe346a 100644 --- a/classparser/decompiler/rewriter/statement_wrap.go +++ b/classparser/decompiler/rewriter/statement_wrap.go @@ -51,7 +51,29 @@ type RewriteManager struct { SwitchNode []*core.Node TryNodes []*core.Node DominatorMap map[*core.Node][]*core.Node - LabelId int + // dominance memoizes the dominator/post-dominator analyses for the current + // statement CFG topology. Use refreshDominators/Dominates/PostDominates + // instead of recomputing or reading the cache directly. + dominance *statementDominanceState + // loopCache memoizes loop bodies and loop-exit searches for one rewrite + // step. Rewrite installs it only around an analysis-only scan and drops it + // before any graph mutation, so cached answers always describe the live + // graph. Nil means every query recomputes. + loopCache *loopAnalysisCache + loopBases map[loopBodyKey]loopBaseEntry + loopScratch loopElementScratch + // switchOnly memoizes switchNodeJumpOnlyTargets. Switch tables are built + // once by the analyzer and never rewritten, so the per-node result stays + // valid for this manager's lifetime; the exit search consults it for every + // switch inside a loop body. + switchOnly switchOnlyCache + // domIndex caches the child->parent dominance query for the current + // DominatorMap; topology refreshes invalidate it. + domIndex *utils2.DominateIndex + domIndexVersion uint64 + domMapVersion uint64 + domMapDirty bool + LabelId int // LoopRegionReducible records whether the ORIGINAL method CFG (before any loop wrapping) is a // reducible flow graph. It is computed once in Rewrite() because mid-pipeline the graph gains // do-while wrapper nodes and rewrite-inserted break/continue edges that corrupt dominance, making a @@ -514,7 +536,7 @@ func (s *RewriteManager) mergeIf() bool { sourceSet.AddList(childNode.Source) if sourceSet.Len() == 1 && CheckCanBeMerge(parentNode, childNode) { if len(childNode.Next) == 1 { - childNode.Next = append(childNode.Next, childNode.Next[0]) + childNode.DuplicateNext(0) } mergeCondition(parentNode, childNode) if nextStNode != nil { @@ -668,7 +690,7 @@ type NodeExtInfo struct { } func (s *RewriteManager) ScanCoreInfo() error { - s.DominatorMap = GenerateDominatorTree(s.RootNode) + s.refreshDominatorsShared() nodeExtInfo := map[*core.Node]*NodeExtInfo{} getNodeInfo := func(node *core.Node) *NodeExtInfo { if info, ok := nodeExtInfo[node]; ok { @@ -952,7 +974,7 @@ func collectSESEMergeConditions(s *RewriteManager, ifNodes *[]*core.Node, mergeN circleSet := utils.NewSet[*core.Node]() circleSet.AddList(circleNodes) - postDom := GeneratePostDominatorMap(s.RootNode) + postDom := s.postDominatorMap() for _, current := range sortNodesByID(merges) { if ifNodeSet.Has(current) { @@ -1015,12 +1037,13 @@ func (s *RewriteManager) Rewrite() error { } // Reducibility must be measured on the pristine CFG, before RebuildLoopNode introduces do-while // wrapper nodes (Id 0) and later passes splice in break/continue edges — both distort dominance. - s.LoopRegionReducible = isReducibleCFG(s.RootNode, GenerateDominatorTree(s.RootNode)) + s.refreshDominatorsShared() + s.LoopRegionReducible = isReducibleCFG(s.RootNode, s.DominatorMap) err = RebuildLoopNode(s) if err != nil { return err } - s.DominatorMap = GenerateDominatorTree(s.RootNode) + s.refreshDominatorsShared() partitionSharedLoopLatches(s) partitionSharedLoopSteps(s) nodeToRewriter := map[*core.Node]rewriterFunc{} @@ -1055,27 +1078,81 @@ func (s *RewriteManager) Rewrite() error { if err != nil { return err } - s.DominatorMap = GenerateDominatorTree(s.RootNode) + s.refreshDominatorsShared() } order := protectedSiblingRewriteOrder(s, s.TopologicalSortReverse(keyNodes)) + // Membership tests below run inside the per-node rewrite loop. The old linear + // slices.Contains calls made a large method O(nodes²) before any rewriting + // work; index the four manager node classes once instead. + trySet := make(map[*core.Node]struct{}, len(s.TryNodes)) + for _, node := range s.TryNodes { + trySet[node] = struct{}{} + } + ifSet := make(map[*core.Node]struct{}, len(s.IfNodes)) + for _, node := range s.IfNodes { + ifSet[node] = struct{}{} + } + switchSet := make(map[*core.Node]struct{}, len(s.SwitchNode)) + for _, node := range s.SwitchNode { + switchSet[node] = struct{}{} + } + whileSet := make(map[*core.Node]struct{}, len(s.WhileNode)) + for _, node := range s.WhileNode { + whileSet[node] = struct{}{} + } + inSet := func(set map[*core.Node]struct{}, node *core.Node) bool { + _, ok := set[node] + return ok + } loopJmpRewriterRecoed := map[*core.Node]struct{}{} processed := map[*core.Node]struct{}{} + // Protected ranges are established by the parser and pre-rewrite + // normalization; this loop cannot introduce one into a method that had + // none. Check once instead of scanning the graph at every container. + loopCacheAllowed := s.loopCacheSafe() + if jdecenv.Get("JDEC_LOOP_ANALYSIS_CACHE_OFF") != "1" { + // Topology-only loop bodies survive across rewrite steps; the snapshot + // diff keeps entries whose loop region was untouched. + s.loopBases = map[loopBodyKey]loopBaseEntry{} + defer func() { s.loopBases = nil }() + } for i := 0; i < len(order); i++ { - s.DominatorMap = GenerateDominatorTree(s.RootNode) + s.refreshDominatorsShared() node := order[i] if _, done := processed[node]; done { continue } - isTry := slices.Contains(s.TryNodes, node) + // Loop bodies and exits are pure functions of the live graph while the + // method has no protected ranges. The two scans below otherwise rebuild + // every loop body for every container node; reuse the answers within + // this rewrite step and drop them at the first mutation. + var loopCache *loopAnalysisCache + useLoopCache := func() { + if loopCache == nil && loopCacheAllowed { + loopCache = newLoopAnalysisCache() + } + s.loopCache = loopCache + } + dropLoopCache := func() { + s.loopCache = nil + loopCache = nil + } + isTry := inSet(trySet, node) // Protected retry branches need their loop exits before nested ifs // consume the graph. Other loops retain the existing inner-if order. materializeLoopExits := func(protectedRetryOnly bool) error { - if isTry || slices.Contains(s.IfNodes, node) || slices.Contains(s.SwitchNode, node) || slices.Contains(s.WhileNode, node) { + if isTry || inSet(ifSet, node) || inSet(switchSet, node) || inSet(whileSet, node) { + useLoopCache() + defer func() { s.loopCache = nil }() + // An installed cache proves the method has no protected range, + // so retry-continuation queries cannot match and would only + // rescan every loop body. + noProtected := s.loopCache != nil for j := i; j < len(order); j++ { n := order[j] - if slices.Contains(s.WhileNode, n) && (loopOwnsRewriteNode(s, n, node) || (protectedRetryOnly && protectedRetryContinuationOwnsRewriteNode(s, n, node)) || (!protectedRetryOnly && s.LoopRegionReducible && len(n.Next) > 0 && searchCircleEndNode(n, n.Next[0], s.DominatorMap, true) == node)) { - if protectedRetryOnly && !loopHasProvedProtectedRetry(s, n) { + if inSet(whileSet, n) && (loopOwnsRewriteNodeWith(s, n, node, s.ownsNode) || (protectedRetryOnly && !noProtected && protectedRetryContinuationOwnsRewriteNode(s, n, node)) || (!protectedRetryOnly && s.LoopRegionReducible && len(n.Next) > 0 && s.searchLoopEnd(n, n.Next[0], true) == node)) { + if protectedRetryOnly && !noProtected && !loopHasProvedProtectedRetry(s, n) { continue } if isTry && (len(n.Next) == 0 || (n.Next[0] != node && !loopHeaderGuardsTry(s, n, node)) || (hasSharedCatchEntry(node) && !loopHasProvedProtectedRetry(s, n))) { @@ -1086,7 +1163,7 @@ func (s *RewriteManager) Rewrite() error { // until a nested terminal loop has been wrapped. // Materialize newly exposed exits before this // continuation becomes an opaque IfStatement. - if protectedRetryOnly || len(n.Next) == 0 || slices.Contains(n.Next, node) || searchCircleEndNode(n, n.Next[0], s.DominatorMap, s.LoopRegionReducible) != node { + if protectedRetryOnly || len(n.Next) == 0 || slices.Contains(n.Next, node) || s.searchLoopEnd(n, n.Next[0], s.LoopRegionReducible) != node { // A loop that already owns this continuation // needs no second pass. Keep looking for an // enclosing loop whose branch also exits here. @@ -1098,7 +1175,8 @@ func (s *RewriteManager) Rewrite() error { return err } loopJmpRewriterRecoed[n] = struct{}{} - s.DominatorMap = GenerateDominatorTree(s.RootNode) + dropLoopCache() + s.refreshDominatorsShared() break } } @@ -1120,23 +1198,26 @@ func (s *RewriteManager) Rewrite() error { // needs it and it is zero-regression). Extending it to if containers regressed passing // methods catastrophically when applied globally (5->318), so it is gated behind aggressive // mode: only a method that already failed conservatively takes the if-container path. - isAggrIf := s.Aggressive && slices.Contains(s.IfNodes, node) + isAggrIf := s.Aggressive && inSet(ifSet, node) if isTry || isAggrIf { body := s.containerBodyNodeSet(node) for _, cand := range order[i+1:] { if _, done := processed[cand]; done { continue } - if cand == node || !body[cand] || !slices.Contains(s.IfNodes, cand) { + if cand == node || !body[cand] || !inSet(ifSet, cand) { continue } - s.DominatorMap = GenerateDominatorTree(s.RootNode) + s.refreshDominatorsShared() if err := IfRewriter(s, cand); err != nil { return err } processed[cand] = struct{}{} } - s.DominatorMap = GenerateDominatorTree(s.RootNode) + s.refreshDominatorsShared() + // IfRewriter may have changed statements or edges inside this + // container; loop answers collected before it are stale. + dropLoopCache() } if err := materializeLoopExits(false); err != nil { diff --git a/classparser/decompiler/rewriter/switch_empty_entry_test.go b/classparser/decompiler/rewriter/switch_empty_entry_test.go index 1a322ef7..24675255 100644 --- a/classparser/decompiler/rewriter/switch_empty_entry_test.go +++ b/classparser/decompiler/rewriter/switch_empty_entry_test.go @@ -1,6 +1,7 @@ package rewriter import ( + "math/rand" "testing" "github.com/yaklang/javajive/classparser/decompiler/core" @@ -47,3 +48,55 @@ func TestSwitchExitCountsBodiesNotGroupedLabels(t *testing.T) { t.Fatalf("distinct bodies counted as %d, want 2", got) } } + +// The one-pass jump-only map must agree with the per-target query for every +// target, including grouped labels, a default target, and duplicate targets. +func TestSwitchJumpOnlyTargetsMatchesPerTargetQuery(t *testing.T) { + rng := rand.New(rand.NewSource(0x5eed)) + for trial := 0; trial < 500; trial++ { + targetPool := make([]*core.Node, 1+rng.Intn(4)) + for i := range targetPool { + targetPool[i] = &core.Node{} + } + node := &core.Node{SwitchJumpOnlyCases: map[int]bool{}} + cases := omap.NewEmptyOrderedMap[switchLabel, *core.Node]() + for value := 0; value < 1+rng.Intn(6); value++ { + if rng.Intn(2) == 0 { + node.SwitchJumpOnlyCases[value] = true + } + cases.Set(switchLabel{Value: int32(value)}, targetPool[rng.Intn(len(targetPool))]) + } + hasDefault := rng.Intn(2) == 0 + if hasDefault { + node.SwitchDefault = targetPool[rng.Intn(len(targetPool))] + cases.Set(switchLabel{Default: true}, node.SwitchDefault) + } + + only := switchJumpOnlyTargets(node, cases) + for _, target := range targetPool { + want := switchCaseHasOnlyJumpEntries(node, target, cases) + if got := only[target]; got != want { + t.Fatalf("trial %d target %p: jumpOnly=%t want %t", trial, target, got, want) + } + } + + // Same table through the prepared-switch path used by the loop scan. + node.SwitchCases = omap.NewEmptyOrderedMap[int, *core.Node]() + cases.ForEach(func(label switchLabel, target *core.Node) bool { + if !label.Default { + node.SwitchCases.Set(int(label.Value), target) + } + return true + }) + direct, ok := switchNodeJumpOnlyTargets(node, nil) + if !ok { + t.Fatalf("trial %d: prepared switch tables were rejected", trial) + } + for _, target := range targetPool { + want := switchCaseHasOnlyJumpEntries(node, target, cases) + if got := direct[target]; got != want { + t.Fatalf("trial %d prepared target %p: jumpOnly=%t want %t", trial, target, got, want) + } + } + } +} diff --git a/classparser/decompiler/rewriter/switch_loop_continuation.go b/classparser/decompiler/rewriter/switch_loop_continuation.go index 313eb9f7..b3e81584 100644 --- a/classparser/decompiler/rewriter/switch_loop_continuation.go +++ b/classparser/decompiler/rewriter/switch_loop_continuation.go @@ -17,7 +17,7 @@ import ( // Each bypass gets its original step once; the arm's effects stay in place. // A potentially throwing assignment additionally requires identical protected // membership on the direct incoming edge, so its handler selection is unchanged. -func materializeSwitchLatchContinues(manager *RewriteManager, loop *core.Node) { +func materializeSwitchLatchContinues(manager *RewriteManager, loop *core.Node) bool { changed := false for _, latch := range slices.Clone(loop.Source) { copyStep, pure := switchLoopLocalStep(latch) @@ -59,8 +59,9 @@ func materializeSwitchLatchContinues(manager *RewriteManager, loop *core.Node) { } } if changed { - manager.DominatorMap = GenerateDominatorTree(manager.RootNode) + manager.refreshDominatorsShared() } + return changed } // Certify a finite continuation whose every CFG path reaches the step. A diff --git a/classparser/decompiler/rewriter/switch_rewriter.go b/classparser/decompiler/rewriter/switch_rewriter.go index 1f9ade91..67001512 100644 --- a/classparser/decompiler/rewriter/switch_rewriter.go +++ b/classparser/decompiler/rewriter/switch_rewriter.go @@ -274,6 +274,107 @@ func switchCaseHasOnlyJumpEntries(node, candidate *core.Node, cases *omap.Ordere return found && onlyJumps } +// switchJumpOnlyTargets computes switchCaseHasOnlyJumpEntries for every case +// target in one pass. Callers that test more than one candidate previously +// rescanned the whole case map per target, which is O(cases²) and rebuilds the +// ordered-map key/value snapshot on every test. +func switchJumpOnlyTargets(node *core.Node, cases *omap.OrderedMap[switchLabel, *core.Node]) map[*core.Node]bool { + if node == nil || cases == nil { + return nil + } + only := make(map[*core.Node]bool, cases.Len()) + cases.ForEachReadOnly(func(label switchLabel, target *core.Node) bool { + if target == nil { + return true + } + jumpOnly := !label.Default && node.SwitchJumpOnlyCases[int(label.Value)] + if previous, exists := only[target]; exists { + only[target] = previous && jumpOnly + } else { + only[target] = jumpOnly + } + return true + }) + return only +} + +// switchOnlyEntry is the memoized result of switchNodeJumpOnlyTargets. The ok +// flag distinguishes "not derivable" from "empty target set". +type switchOnlyEntry struct { + targets map[*core.Node]bool + ok bool +} + +// switchOnlyCache memoizes switchNodeJumpOnlyTargets for one RewriteManager. +// The analyzer builds SwitchCases/SwitchJumpOnlyCases once and no rewrite pass +// mutates them, so the derived map is valid for the manager's lifetime. The +// loop-exit search consults it for every switch in a body on every query. +type switchOnlyCache struct { + entries map[*core.Node]switchOnlyEntry +} + +func (c *switchOnlyCache) targets(node *core.Node, middle *statements.MiddleStatement) (map[*core.Node]bool, bool) { + if c == nil { + return switchNodeJumpOnlyTargets(node, middle) + } + if entry, found := c.entries[node]; found { + return entry.targets, entry.ok + } + targets, ok := switchNodeJumpOnlyTargets(node, middle) + if c.entries == nil { + c.entries = make(map[*core.Node]switchOnlyEntry) + } + c.entries[node] = switchOnlyEntry{targets: targets, ok: ok} + return targets, ok +} + +// switchNodeJumpOnlyTargets derives the same per-target property straight from +// the prepared switch tables, avoiding a throwaway label-keyed OrderedMap for +// every loop-exit query. +func switchNodeJumpOnlyTargets(node *core.Node, middle *statements.MiddleStatement) (map[*core.Node]bool, bool) { + if node == nil { + return nil, false + } + only := map[*core.Node]bool{} + add := func(label switchLabel, target *core.Node) { + if target == nil { + return + } + jumpOnly := !label.Default && node.SwitchJumpOnlyCases[int(label.Value)] + if previous, exists := only[target]; exists { + only[target] = previous && jumpOnly + } else { + only[target] = jumpOnly + } + } + if node.SwitchCases != nil { + node.SwitchCases.ForEachReadOnly(func(value int, target *core.Node) bool { + add(switchLabel{Value: int32(value)}, target) + return true + }) + if node.SwitchDefault != nil { + add(switchLabel{Default: true}, node.SwitchDefault) + } + return only, true + } + if middle == nil { + return nil, false + } + data, ok := middle.Data.([]any) + if !ok { + return nil, false + } + cases, err := switchCaseNodes(data, node) + if err != nil { + return nil, false + } + cases.ForEachReadOnly(func(label switchLabel, target *core.Node) bool { + add(label, target) + return true + }) + return only, true +} + // Dominance alone cannot identify a switch continuation also reached by an // enclosing if arm. Prove a unique forward boundary shared by distinct case // bodies. A label remains a label (real fall-through); terminal returns were @@ -426,6 +527,7 @@ func SwitchRewriter1(manager *RewriteManager, node *core.Node) error { // through into `default: throw` ("Impossible modulus N"). Kill-switch: // JDEC_SWITCH_EMPTY_CASE_MERGE_OFF=1. caseStarts := caseMap.Values() + jumpOnly := switchJumpOnlyTargets(node, caseMap) var best *core.Node bestCnt := 0 caseMap.ForEach(func(k switchLabel, cand *core.Node) bool { @@ -433,7 +535,7 @@ func SwitchRewriter1(manager *RewriteManager, node *core.Node) error { return true } c := countOtherCasesExitingTo(manager, node, cand, caseStarts) - if (c >= 2 || (c == 1 && switchCaseHasOnlyJumpEntries(node, cand, caseMap))) && c > bestCnt { + if (c >= 2 || (c == 1 && jumpOnly[cand])) && c > bestCnt { best = cand bestCnt = c } @@ -665,7 +767,7 @@ func splitExternalSharedSwitchReturns(manager *RewriteManager, owner *core.Node) replaceNextInPlace(e.source, e.target, leaf) } if len(edges) > 0 { - manager.DominatorMap = GenerateDominatorTree(manager.RootNode) + manager.refreshDominatorsShared() } } @@ -932,7 +1034,7 @@ func sortSwitchLabels(labels []switchLabel) { func switchCaseNodes(data []any, node *core.Node) (*omap.OrderedMap[switchLabel, *core.Node], error) { cases := omap.NewEmptyOrderedMap[switchLabel, *core.Node]() if node.SwitchCases != nil { - node.SwitchCases.ForEach(func(v int, target *core.Node) bool { cases.Set(switchLabel{Value: int32(v)}, target); return true }) + node.SwitchCases.ForEachReadOnly(func(v int, target *core.Node) bool { cases.Set(switchLabel{Value: int32(v)}, target); return true }) if node.SwitchDefault != nil { cases.Set(switchLabel{Default: true}, node.SwitchDefault) } @@ -949,7 +1051,7 @@ func switchCaseNodes(data []any, node *core.Node) (*omap.OrderedMap[switchLabel, cases.Set(label, next[index]) return true } - indices.ForEach(func(v, index int) bool { return add(switchLabel{Value: int32(v)}, index) }) + indices.ForEachReadOnly(func(v, index int) bool { return add(switchLabel{Value: int32(v)}, index) }) if invalid != nil { return nil, invalid } diff --git a/classparser/decompiler/rewriter/widen_instanceof.go b/classparser/decompiler/rewriter/widen_instanceof.go index abfc0544..7127a603 100644 --- a/classparser/decompiler/rewriter/widen_instanceof.go +++ b/classparser/decompiler/rewriter/widen_instanceof.go @@ -2,6 +2,7 @@ package rewriter import ( "github.com/yaklang/javajive/internal/jdecenv" + utils2 "github.com/yaklang/javajive/internal/utils" "regexp" "strings" @@ -354,12 +355,10 @@ var numberMethodWhitelist = map[string]bool{ // (longValue/intValue/etc.). This is the Number-specific gate used when Object-safe fails (because // the variable has `.longValue()` member access that Object doesn't support but Number does). func isNumberSafeWiden(text, name string, objectNames map[string]struct{}) bool { - re := regexp.MustCompile(`\b` + regexp.QuoteMeta(name) + `\b`) - locs := re.FindAllStringIndex(text, -1) + locs := utils2.WordSpans(text, name, nil) if len(locs) == 0 { return false } - lhsNameRe := regexp.MustCompile(`\b([A-Za-z_$][\w$]*)\s*=\s*$`) for _, loc := range locs { before := text[:loc[0]] after := text[loc[1]:] @@ -392,7 +391,7 @@ func isNumberSafeWiden(text, name string, objectNames map[string]struct{}) bool continue } // RHS into Object-typed local (accept only if LHS name is also in objectNames). - if m := lhsNameRe.FindStringSubmatch(before); m != nil { + if m := lhsAssignedNameRe.FindStringSubmatch(before); m != nil { if _, ok := objectNames[m[1]]; ok { continue } diff --git a/classparser/decompiler/utils/util.go b/classparser/decompiler/utils/util.go index abd592b9..e4278cbb 100644 --- a/classparser/decompiler/utils/util.go +++ b/classparser/decompiler/utils/util.go @@ -35,3 +35,71 @@ func IsDominate(tree map[*core.Node][]*core.Node, node1, node2 *core.Node) bool } return false } + +// DominateIndex answers IsDominate queries through child->parent links, so a +// query costs the depth of node2 instead of scanning node1's whole subtree. +// The dominator map produced by GenerateDominatorTree is a forest (one parent +// per node), where both formulations are equivalent. A map with a shared child +// is not a tree and falls back to the recursive implementation, preserving its +// behavior for hand-built test fixtures. +type DominateIndex struct { + tree map[*core.Node][]*core.Node + parent map[*core.Node]*core.Node + valid bool +} + +func NewDominateIndex(tree map[*core.Node][]*core.Node) *DominateIndex { + index := &DominateIndex{} + index.Reset(tree) + return index +} + +// Reset rebuilds the index for a new dominator tree while retaining the parent +// map's buckets. Rewriter topology refreshes use this to avoid a new map per +// rewrite step. +func (d *DominateIndex) Reset(tree map[*core.Node][]*core.Node) { + if d == nil { + return + } + d.tree = tree + d.valid = true + if d.parent == nil { + d.parent = make(map[*core.Node]*core.Node, len(tree)) + } else { + clear(d.parent) + } + for dom, children := range tree { + for _, child := range children { + if child == nil { + d.valid = false + continue + } + if previous, ok := d.parent[child]; ok && previous != dom { + d.valid = false + continue + } + d.parent[child] = dom + } + } +} + +func (d *DominateIndex) IsDominate(node1, node2 *core.Node) bool { + if node1 == node2 { + return true + } + if d == nil || !d.valid { + if d == nil { + return false + } + return IsDominate(d.tree, node1, node2) + } + // One parent per node makes an ancestor walk equivalent to a subtree + // search. The step bound also terminates on a malformed cyclic map where + // the recursive form would not. + for current, steps := node2, 0; current != nil && steps <= len(d.parent); current, steps = d.parent[current], steps+1 { + if current == node1 { + return true + } + } + return false +} diff --git a/classparser/decompiler/utils/util_test.go b/classparser/decompiler/utils/util_test.go new file mode 100644 index 00000000..ac07c4eb --- /dev/null +++ b/classparser/decompiler/utils/util_test.go @@ -0,0 +1,69 @@ +package utils + +import ( + "math/rand" + "testing" + + "github.com/yaklang/javajive/classparser/decompiler/core" +) + +func TestDominateIndexMatchesRecursiveWalk(t *testing.T) { + r := rand.New(rand.NewSource(7)) + for round := 0; round < 300; round++ { + n := 1 + r.Intn(20) + nodes := make([]*core.Node, n) + for i := range nodes { + nodes[i] = &core.Node{Id: i} + } + tree := map[*core.Node][]*core.Node{} + for i := 1; i < n; i++ { + parent := nodes[r.Intn(i)] + tree[parent] = append(tree[parent], nodes[i]) + } + index := NewDominateIndex(tree) + for _, a := range nodes { + for _, b := range nodes { + want := IsDominate(tree, a, b) + if got := index.IsDominate(a, b); got != want { + t.Fatalf("round %d: IsDominate(%d,%d)=%t want %t", round, a.Id, b.Id, got, want) + } + } + } + } +} + +func TestDominateIndexFallsBackForSharedChildren(t *testing.T) { + root := &core.Node{} + other := &core.Node{} + shared := &core.Node{} + leaf := &core.Node{} + tree := map[*core.Node][]*core.Node{ + root: {shared}, + other: {shared}, + shared: {leaf}, + } + index := NewDominateIndex(tree) + for _, a := range []*core.Node{root, other, shared, leaf} { + for _, b := range []*core.Node{root, other, shared, leaf} { + want := IsDominate(tree, a, b) + if got := index.IsDominate(a, b); got != want { + t.Fatalf("shared child: IsDominate(%v,%v)=%t want %t", a, b, got, want) + } + } + } +} + +func TestDominateIndexEmptyTree(t *testing.T) { + var nilIndex *DominateIndex + a, b := &core.Node{}, &core.Node{} + if nilIndex.IsDominate(a, b) { + t.Fatal("nil index must not report dominance") + } + if !nilIndex.IsDominate(a, a) { + t.Fatal("nil index must preserve the equality rule") + } + empty := NewDominateIndex(nil) + if empty.IsDominate(a, b) { + t.Fatal("empty index must not report dominance") + } +} diff --git a/classparser/dumper.go b/classparser/dumper.go index cf36a76d..1530e54e 100644 --- a/classparser/dumper.go +++ b/classparser/dumper.go @@ -13,6 +13,8 @@ import ( "sort" "strconv" "strings" + "sync" + "sync/atomic" "github.com/yaklang/javajive/classparser/decompiler/core" utils2 "github.com/yaklang/javajive/classparser/decompiler/core/utils" @@ -29,6 +31,31 @@ import ( "github.com/yaklang/javajive/internal/workbudget" ) +// cachedCompatibilityRegexp reuses immutable pattern objects across classes +// and methods. Compatibility passes compile constant and name-derived patterns +// inside per-method functions; without this cache a large class recompiles the +// same pattern for every method it visits. The cache is bounded because a +// long-running host can see arbitrarily many derived local names. +var compatibilityRegexpCache sync.Map // string -> *regexp.Regexp +var compatibilityRegexpCacheCount atomic.Int64 + +const maxCachedCompatibilityRegexps = 1024 + +func cachedCompatibilityRegexp(pattern string) *regexp.Regexp { + if cached, ok := compatibilityRegexpCache.Load(pattern); ok { + return cached.(*regexp.Regexp) + } + compiled := regexp.MustCompile(pattern) + if compatibilityRegexpCacheCount.Load() < maxCachedCompatibilityRegexps { + actual, loaded := compatibilityRegexpCache.LoadOrStore(pattern, compiled) + if !loaded { + compatibilityRegexpCacheCount.Add(1) + } + return actual.(*regexp.Regexp) + } + return compiled +} + type ClassObjectDumper struct { serializableReferenceReady bool serializableReferencePlan *serializableReferenceProtocol @@ -91,8 +118,23 @@ type ClassObjectDumper struct { recordReconstructionOK bool patternReconstructionOK bool rewriteSeen map[string]bool - Work *workbudget.Budget - diagTruncated bool + // Rewrite scheduler state. The index is valid only for rewriteIndex.source + // at rewriteEpoch; every accepted source mutation advances the epoch and + // clears the index. Hash values are SHA-256 over source strings and are + // reused only while the exact string is in the bounded memo. + rewriteEpoch uint64 + rewriteIndex *rewriteApplicabilityIndex + rewriteHashes map[string]string + rewriteSchedulerStats rewriteSchedulerMetrics + // rewriteSchedulerDisabled is a test/benchmark override. Production + // bisection uses JDEC_REWRITE_SCHEDULER_OFF through jdecenv. The + // environment is read once per dumper: sourceRewrite runs this check on + // every one of the hundred-plus rules in the Compatibility chain. + rewriteSchedulerDisabled bool + rewriteSchedulerSwitchReady bool + rewriteSchedulerSwitchOff bool + Work *workbudget.Budget + diagTruncated bool // Set by actual degraded output, never by scanning user literals/comments. sourceDegraded bool overloadFamilyUnproven bool @@ -649,6 +691,23 @@ func (c *ClassObjectDumper) DumpClass() (rendered string, dumpError error) { return rendered, dumpError } } + recoveryComments := javaJiveRecoveryComments(c.obj) + if recoveryComments != "" { + defer func() { + if dumpError != nil || rendered == "" { + return + } + if strings.HasPrefix(rendered, recoveryComments) { + return + } + if err := c.ensureOutput(int64(len(recoveryComments) + len(rendered))); err != nil { + rendered = "" + dumpError = err + return + } + rendered = recoveryComments + rendered + }() + } if projected := c.descriptorProjectionWithoutEnclosingMethod(); projected != nil { original := c.obj originalProjection := c.descriptorSourceProjection @@ -1854,7 +1913,7 @@ func (c *ClassObjectDumper) DumpClass() (rendered string, dumpError error) { if len(annoStrs) > 0 { result = fmt.Sprintf("%s\n%s", strings.Join(annoStrs, "\n"), result) } - importsStr := "" + var importsB strings.Builder for _, s := range funcCtx.GetAllImported() { if utils.StringSliceContain(buildInLib, s) { continue @@ -1870,14 +1929,19 @@ func (c *ClassObjectDumper) DumpClass() (rendered string, dumpError error) { // does NOT resolve because Yak's flat `Outer.java` has no nested `Inner` (it is a // separate flat unit) - the second-largest fastjson2 cross-package recompile blocker. // So emit the (already correct) import string verbatim. - importsStr += fmt.Sprintf("import %s;\n", s) + importsB.WriteString("import ") + importsB.WriteString(s) + importsB.WriteString(";\n") } for _, s := range funcCtx.StaticMethodImports.Imports() { - importsStr += fmt.Sprintf("import static %s;\n", s) + importsB.WriteString("import static ") + importsB.WriteString(s) + importsB.WriteString(";\n") } - if len(importsStr) > 0 { - importsStr += "\n" + if importsB.Len() > 0 { + importsB.WriteByte('\n') } + importsStr := importsB.String() if c.nativeMemberCurrent != nil { // Owned declarations keep their original annotation prefix. The // assembler knows the exact unit preamble; no class-keyword search @@ -1950,370 +2014,372 @@ func (c *ClassObjectDumper) DumpClass() (rendered string, dumpError error) { priorOrdinaryClassSource := c.ordinaryConstructorClassSource c.ordinaryConstructorClassSource = ordinaryClassSource defer func() { c.ordinaryConstructorClassSource = priorOrdinaryClassSource }() - // Enum-switch projection belongs to the certified original statement - // protocol. Unproved mapping arrays and integer dispatch remain intact: - // source spelling cannot establish initializer effects, artifact ownership - // or the compiler's numbered-helper namespace. - // Capture snapshots require stable source bindings. Definite assignment - // is established by original reaching definitions, not guessed defaults. - full = c.sourceRewrite("fixLambdaLoopCapture", "class_source", full, func(source string) string { - return fixLambdaLoopCaptureWithStableBindings(source, c.completedLambdaStableSourceBindings(source, methods)) - }) - // removeUnreachableSwitchBreak drops `break;` after a nested switch whose default throws/returns. - // Kill-switch: JDEC_RM_UNREACHABLE_BREAK_OFF=1. - full = c.sourceRewrite("removeUnreachableSwitchBreak", "class_source", full, removeUnreachableSwitchBreak) - // A lexical block boundary cannot prove a method exit. Empty conditional - // arms may reach a shared continuation after several enclosing scopes; - // only the typed control-flow graph can authorize a return. - // fixTryBreakReturn moves a hoisted `return ;` back into a `try { break; }` block - // inside a do-while(true) loop, where the try's catch clauses require the return's - // checked-exception to be throwable. Kill-switch: JDEC_FIX_TRY_BREAK_RETURN_OFF=1. - full = c.sourceRewrite("fixTryBreakReturn", "class_source", full, fixTryBreakReturn) - // fixThrowTypeVarCast adds the `(T)` cast to `throw ;` inside a method whose `throws` - // clause declares a type variable (e.g. `throws T` where `T extends Throwable`), when the - // thrown variable's type is `Throwable` (too broad for `throws T`). The original source had - // `throw (T) throwable;` but the bytecode erased the cast. Kill-switch: - // JDEC_FIX_THROW_TYPEVAR_CAST_OFF=1. Canonical: commons-lang3 ExceptionUtils.typeErasure. - full = c.sourceRewrite("fixThrowTypeVarCast", "class_source", full, fixThrowTypeVarCast) - // fixLoopCatchThrow removes a `throw new RuntimeException();` that was added to an empty - // catch by the catch-rendering fix when the catch is inside a loop (followed by - // continue/break). Empty catches inside loops are intentional (swallow and continue), so the - // throw would make the continue/break unreachable. Kill-switch: JDEC_FIX_LOOP_CATCH_THROW_OFF=1. - full = c.sourceRewrite("fixLoopCatchThrow", "class_source", full, fixLoopCatchThrow) - // Fix try/catch structuring: move exception-throwing calls that are rendered outside a - // try block INTO the nearest inner try body. Kill-switch: JDEC_FIX_TRYCATCH_OFF=1. - full = c.sourceRewrite("fixTryCatchExceptionPlacement", "class_source", full, fixTryCatchExceptionPlacement) - // Catch types are recovered from the exception table. A call's spelling - // does not prove its declaring owner, throws signature, or handler coverage; - // guessing here adds exceptions to unrelated catches (e.g. getMethod()). - // Original handler membership owns catch alternatives, including exceptions - // thrown before an inner try or by one of its catch bodies. - // wrapUncaughtThrowingCall wraps `UNSAFE.allocateInstance()` in try/catch. Kill-switch: - // JDEC_WRAP_ALLOCATE_OFF=1. - full = c.sourceRewrite("wrapUncaughtThrowingCall", "class_source", full, wrapUncaughtThrowingCall) - // wrapReflectionCallInSwitchCase wraps switch-case reflection calls in try/catch. Kill-switch: - // JDEC_WRAP_REFLECTION_CASE_OFF=1. - full = c.sourceRewrite("wrapReflectionCallInSwitchCase", "class_source", full, wrapReflectionCallInSwitchCase) - // Case exits are determined from CFG edges. Source assignments cannot - // distinguish a genuine break from an intentional fall-through dependency; - // inserting terminators here truncates rolling hash tails and numeric state. - // A switch break continues along its CFG successor. Never synthesize a - // default return here: block-closing braces do not prove method completion, - // and returning null silently truncates nested switches and decode loops. - // wrapFieldInitializerReflection converts a field initializer containing a reflection call - // (getMethod etc.) that throws a checked exception into a static-block init with try/catch. - // Kill-switch: JDEC_WRAP_FIELD_INIT_OFF=1. - full = c.sourceRewrite("wrapFieldInitializerReflection", "class_source", full, wrapFieldInitializerReflection) - // wrapUncaughtGetConstructor wraps a bare first-stmt `cls.getConstructor(...)` in - // try/catch(NoSuchMethodException). Class-gated to AddDelegateTransformer (global wrap - // unmasks snakeyaml/fastjson2). Kill-switch: JDEC_WRAP_GETCONSTRUCTOR_OFF=1. - full = c.sourceRewrite("wrapUncaughtGetConstructor", "class_source", full, wrapUncaughtGetConstructor) - // Preserve the recovered alternatives too. A materialized Class[] can be - // declared outside the try, and any callee may declare a checked exception. - // Absence of a familiar reflection expression cannot prove a catch redundant. - // Drop catch(T) when an earlier catch in the same try already covers T - // (multicatch then a second catch(T)). Kill-switch: JDEC_ALREADY_CAUGHT_OFF=1. - full = c.sourceRewrite("fixAlreadyCaughtDuplicateCatch", "class_source", full, fixAlreadyCaughtDuplicateCatch) - // Handler completion comes from the original CFG. A following return does - // not prove that a user-written wrapping throw was a synthesized repair. - // Subclass field `this.f = this.f` is getfield Super.f; putfield This.f. - // Kill-switch: JDEC_SHADOW_FIELD_SUPER_ASSIGN_OFF=1. - full = c.sourceRewrite("fixShadowFieldSuperAssign", "class_source", full, fixShadowFieldSuperAssign) - // fixImmutableBuilderWitness inserts an explicit type witness on - // `ImmutableMap f = ImmutableMap.builder()` so builder() does not infer . - // Kill-switch: JDEC_IMMUTABLE_BUILDER_WITNESS_OFF=1. - full = c.sourceRewrite("fixImmutableBuilderWitness", "class_source", full, fixImmutableBuilderWitness) - // fixSelectMethodsAmbiguous casts the lambda in MethodIntrospector.selectMethods(Class, - // MethodFilter) so javac does not confuse it with the MetadataLookup overload. - // Kill-switch: JDEC_SELECTMETHODS_CAST_OFF=1. - full = c.sourceRewrite("fixSelectMethodsAmbiguous", "class_source", full, fixSelectMethodsAmbiguous) - // fixAsMapFunctionRawCast wraps asMap(lambda, Adapt...) lambdas in a raw Function - // cast so javac does not reject Function - // against Function, T>. - // Kill-switch: JDEC_ASMAP_FUNCTION_CAST_OFF=1. - full = c.sourceRewrite("fixAsMapFunctionRawCast", "class_source", full, fixAsMapFunctionRawCast) - // Checked catches are recovered from original instructions, declarations - // and exception regions. Injecting an unreachable throw invents source - // effects and invalidates already completed lambda-body observations. - // Compatibility must retain the same proved handler, without dead code. - // fixThrowClassCastDropsThrowable unwraps `throw ((Throwable)(cls.cast(x)))` to - // `throw cls.cast(x)` so a method `throws X` (X a type variable) actually throws X - // rather than undeclared Throwable. Real hit: guava Throwables.throwIfInstanceOf. - // Kill-switch: JDEC_THROW_CLASS_CAST_DROP_THROWABLE_OFF=1. - full = c.sourceRewrite("fixThrowClassCastDropsThrowable", "class_source", full, fixThrowClassCastDropsThrowable) - // fixReplaceAllListStreamCast casts the replaceAll value param to List before .stream() - // on a raw HashMap (l1 is Object). Real hit: spring SpringFactoriesLoader.loadSpringFactories. - // Kill-switch: JDEC_REPLACEALL_LIST_STREAM_CAST_OFF=1. - full = c.sourceRewrite("fixReplaceAllListStreamCast", "class_source", full, fixReplaceAllListStreamCast) - // fixClassMapEntryPutCasts inserts (Class) on raw Map.Entry getKey/getValue fed to a - // Class-valued map. Real hit: spring ClassUtils primitiveTypeToWrapperMap. - // Kill-switch: JDEC_CLASS_MAP_ENTRY_PUT_CAST_OFF=1. - full = c.sourceRewrite("fixClassMapEntryPutCasts", "class_source", full, fixClassMapEntryPutCasts) - // fixVisitAnnotationConsumerCast rewrites Consumer to raw Consumer - // so it applies to Consumer>. Real hit: spring - // MergedAnnotationReadingVisitor.visitAnnotation. - // Kill-switch: JDEC_VISITANNOTATION_CONSUMER_CAST_OFF=1. - full = c.sourceRewrite("fixVisitAnnotationConsumerCast", "class_source", full, fixVisitAnnotationConsumerCast) - // Scoped to the exact getUninterruptibly empty-try shape (not a class-wide regex). - full = c.sourceRewrite("fixGetUninterruptiblyGetInTry", "class_source", full, fixGetUninterruptiblyGetInTry) - // Scoped to the exact drainUninterruptibly empty-try shape: poll() folded out of - // the InterruptedException catch (guava Queues, unmasked once DescendingSet compiled). - full = c.sourceRewrite("fixDrainUninterruptiblyPollInTry", "class_source", full, fixDrainUninterruptiblyPollInTry) - // TRANSPOSE_CELL is Function, Cell>; Iterators.transform then - // infers T from the wildcards instead of the Iterator> return - // ("inference variable T has incompatible bounds"). Raw Function is unchecked. - // Kill-switch: JDEC_TRANSPOSE_CELL_FUNCTION_CAST_OFF=1. - full = c.sourceRewrite("fixTransposeCellFunctionCast", "class_source", full, fixTransposeCellFunctionCast) - // Class.getConstructors() is Constructor[]; asList infers List> - // which cannot convert to List> (preferringStrings). Raw List - // is unchecked. Kill-switch: JDEC_PREFERSTRINGS_ASLIST_CAST_OFF=1. - full = c.sourceRewrite("fixPreferringStringsAsListCast", "class_source", full, fixPreferringStringsAsListCast) - // SynchronizedNavigableMap lazy-init accessors: CFG emptied the - // synchronized body (field==null assign + return), leaving a non-void - // method with no return. Restore the original lazy-init reconstruct. - // Kill-switch: JDEC_SYNC_LAZY_NAV_RETURN_OFF=1. - full = c.sourceRewrite("fixSyncLazyNavigableReturn", "class_source", full, fixSyncLazyNavigableReturn) - // AbstractCatchingFuture.run: CFG copied the finally-clear into try/catch - // AND emitted a second catch(Throwable) for the finally-rethrow, which - // javac rejects ("exception Throwable has already been caught"). Fold - // back to try/catch/finally. Kill-switch: JDEC_CATCHING_FUTURE_FINALLY_OFF=1. - full = c.sourceRewrite("fixCatchingFutureFinally", "class_source", full, fixCatchingFutureFinally) - // AbstractService.startAsync/stopAsync: same finally-copied-into-catch(Throwable) - // twice. Kill-switch: JDEC_ABSTRACT_SERVICE_FINALLY_OFF=1. - full = c.sourceRewrite("fixAbstractServiceFinally", "class_source", full, fixAbstractServiceFinally) - // Monitor: empty try{break} catch(IE) with tryLock/awaitNanos folded out. - // Inject a never-taken throw so the catch is live, and wrap the folded - // calls so InterruptedException is not unreported. Kill-switch: - // JDEC_MONITOR_IE_TRY_OFF=1. - // AbstractFuture$SynchronizedHelper cas* methods: CFG emptied the - // synchronized CAS body (private outer fields aren't denotable from the - // flattened inner class), leaving boolean methods with no return. - // Kill-switch: JDEC_SYNC_HELPER_CAS_RETURN_OFF=1. - full = c.sourceRewrite("fixSyncHelperCasReturn", "class_source", full, fixSyncHelperCasReturn) - // ReschedulableCallable.reschedule: lock.unlock finally cloned into - // two catch(Throwable). Kill-switch: JDEC_RESCHEDULE_UNLOCK_FINALLY_OFF=1. - full = c.sourceRewrite("fixRescheduleUnlockFinally", "class_source", full, fixRescheduleUnlockFinally) - // General: consecutive catch(Throwable x){UNIQUE; COMMON} catch(Throwable x){COMMON; throw x} - // is a finally reconstruct. Remaining guava inner classes keep unmasking this shape. - // Kill-switch: JDEC_DUP_THROWABLE_CATCH_FINALLY_OFF=1. - full = c.sourceRewrite("fixDupThrowableCatchFinally", "class_source", full, fixDupThrowableCatchFinally) - // MoreExecutors.isAppEngineWithApiClasses: outer try is Class.forName - // (throws CNFE) but the catch is NoSuchMethodException (getMethod lives - // in the inner try). Kill-switch: JDEC_APPENGINE_CNFE_CATCH_OFF=1. - full = c.sourceRewrite("fixAppEngineCNFECatch", "class_source", full, fixAppEngineCNFECatch) - // RateLimiter.tryAcquire(int,long,TimeUnit): CFG emptied the synchronized - // body and dropped the return. Kill-switch: JDEC_RATELIMITER_TRYACQUIRE_RETURN_OFF=1. - full = c.sourceRewrite("fixRateLimiterTryAcquireReturn", "class_source", full, fixRateLimiterTryAcquireReturn) - // AnnotationReadingVisitorUtils.convertClassValues: var9_1 is used as both - // String[] and Class[] (ternary on classValuesAsString); declaring String[] - // makes `new Class[n]` / Class elements inconvertible. Object[] is the LUB. - // put(entry.getKey(), throwable) needs (String) on the raw Map.Entry key. - // Kill-switch: JDEC_CONVERT_CLASS_VALUES_OBJECT_ARRAY_OFF=1. - full = c.sourceRewrite("fixConvertClassValuesObjectArray", "class_source", full, fixConvertClassValuesObjectArray) - // MergedAnnotationCollectors.toAnnotationArray finisher: (Annotation[]) - // toArray((Object[]) generator.apply) pins R to Annotation, incompatible - // with bounded R extends Annotation. Drop both casts so toArray infers R[]. - // Kill-switch: JDEC_TO_ANNOTATION_ARRAY_FINISHER_OFF=1. - full = c.sourceRewrite("fixToAnnotationArrayFinisher", "class_source", full, fixToAnnotationArrayFinisher) - // Raw Flux.doOnNext lambda param is Object; logValue/touchDataBuffer want - // DataBuffer. Kill-switch: JDEC_DATABUFFER_LAMBDA_CAST_OFF=1. - full = c.sourceRewrite("fixDataBufferLambdaCast", "class_source", full, fixDataBufferLambdaCast) - // jackson POJOPropertyBuilder._explode: Linked receiver's withNext(Linked) - // captures T to CAP#1, so Linked is not Linked. A raw - // `(POJOPropertyBuilder$Linked)` argument makes the call unchecked. - // Kill-switch: JDEC_LINKED_WITHNEXT_RAW_OFF=1. - full = c.sourceRewrite("fixLinkedWithNextRawCast", "class_source", full, fixLinkedWithNextRawCast) - // jackson DeserializationContext.isEnabled(StreamReadCapability): generic - // JacksonFeatureSet.isEnabled erases to JacksonFeature, so the arg is wrapped - // `(JacksonFeature)(var1)` and javac cannot convert that back to StreamReadCapability. - // Kill-switch: JDEC_JACKSON_FEATURE_CAST_OFF=1. - full = c.sourceRewrite("fixJacksonFeatureUpcast", "class_source", full, fixJacksonFeatureUpcast) - // jackson StdKeyDeserializers: raw List.removeIf lambda param is Object, so - // `l0.annotated` / `l0.metadata` cannot find symbol. Cast to AnnotatedAndMetadata. - // Kill-switch: JDEC_ANNOTATED_AND_METADATA_LAMBDA_OFF=1. - full = c.sourceRewrite("fixAnnotatedAndMetadataLambda", "class_source", full, fixAnnotatedAndMetadataLambda) - // Local declarations are placed by VariableId and lexical dominance in - // RewriteVar. Reintroducing declarations from printed slot names here - // can duplicate a declaration already recovered by that typed pass. - full = c.sourceRewrite("fixJacksonRemainingReconstructs", "class_source", full, fixJacksonRemainingReconstructs) - // javac 9-13 TWR synthetic `$closeResource(Throwable, AutoCloseable)` invokeinterfaces - // AutoCloseable.close() which throws Exception, but the synthetic method does not declare - // it (okhttp ResponseBody / DiskLruCache). Kill-switch: JDEC_CLOSE_RESOURCE_THROWS_OFF=1. - full = c.sourceRewrite("fixCloseResourceThrows", "class_source", full, fixCloseResourceThrows) - // okhttp Transmitter: CFG emptied synchronized bodies of newExchange / - // exchangeMessageDone / maybeReleaseConnection (missing return). Reconstruct - // from bytecode. Kill-switch: JDEC_TRANSMITTER_SYNC_OFF=1. - full = c.sourceRewrite("fixTransmitterEmptySync", "class_source", full, fixTransmitterEmptySync) - // okhttp ExchangeFinder: CFG emptied synchronized bodies of findHealthyConnection / - // findConnection / hasRouteToTry (missing return). Kill-switch: - // JDEC_EXCHANGEFINDER_SYNC_OFF=1. - full = c.sourceRewrite("fixExchangeFinderEmptySync", "class_source", full, fixExchangeFinderEmptySync) - // okhttp RealConnection.connect: CFG emptied the try body to `if(false) throw - // IOException; break;` and left connectTunnel/connectSocket outside, so those - // IOException-throwing calls are uncaught. Kill-switch: JDEC_REALCONNECTION_CONNECT_OFF=1. - full = c.sourceRewrite("fixRealConnectionConnect", "class_source", full, fixRealConnectionConnect) - // okhttp RealConnectionPool.cleanup: CFG emptied the synchronized body - // (missing return of long). Kill-switch: JDEC_CONNECTIONPOOL_CLEANUP_OFF=1. - full = c.sourceRewrite("fixConnectionPoolCleanup", "class_source", full, fixConnectionPoolCleanup) - // okhttp Http2Connection.newStream: CFG emptied the synchronized(writer) body - // (missing return of Http2Stream). Kill-switch: JDEC_HTTP2_NEWSTREAM_OFF=1. - full = c.sourceRewrite("fixHttp2NewStream", "class_source", full, fixHttp2NewStream) - // okhttp Http2Stream.getSink / closeInternal: CFG emptied synchronized - // bodies (missing return). Kill-switch: JDEC_HTTP2_STREAM_SYNC_OFF=1. - full = c.sourceRewrite("fixHttp2StreamEmptySync", "class_source", full, fixHttp2StreamEmptySync) - // Catch-all: a non-void method whose last statement is an empty synchronized - // body is missing a return (okhttp DiskLruCache$Editor.newSource/newSink and - // remaining empty-sync sites). Specific reconstructs above run first. - // Kill-switch: JDEC_EMPTY_SYNC_RETURN_OFF=1. - full = c.sourceRewrite("fixEmptySyncMissingReturn", "class_source", full, fixEmptySyncMissingReturn) - // okhttp Util.skipLeading/TrailingAsciiWhitespace: whitespace cases fall - // through into `default: return`, making the loop `continue` unreachable. - // Kill-switch: JDEC_SKIP_WS_CONTINUE_OFF=1. - full = c.sourceRewrite("fixSkipAsciiWhitespaceContinue", "class_source", full, fixSkipAsciiWhitespaceContinue) - // okhttp DiskLruCache$3.hasNext: empty synchronized in the else of - // `if (nextSnapshot != null) return true`. Kill-switch: JDEC_DISKLRU_ITER_OFF=1. - full = c.sourceRewrite("fixDiskLruIteratorHasNext", "class_source", full, fixDiskLruIteratorHasNext) - // okhttp PublicSuffixDatabase: findMatchingRule empty sync (missing return) - // and readTheListUninterruptibly's readTheList() escaped the IOException try. - // Kill-switch: JDEC_PUBLIC_SUFFIX_OFF=1. - full = c.sourceRewrite("fixPublicSuffixDatabase", "class_source", full, fixPublicSuffixDatabase) - // commons-collections4 leftover unique sites (compare inference, singletonList - // capture, ArrayList.class factory, inherited inToRange Object key). - // Kill-switch: JDEC_COLLECTIONS4_REMAINING_OFF=1. - full = c.sourceRewrite("fixCollections4RemainingReconstructs", "class_source", full, fixCollections4RemainingReconstructs) - // netty-handler leftover unique sites. Kill-switch: JDEC_NETTY_REMAINING_OFF=1. - full = c.sourceRewrite("fixNettyRemainingReconstructs", "class_source", full, fixNettyRemainingReconstructs) - // log4j-core leftover unique sites. Kill-switch: JDEC_LOG4J_REMAINING_OFF=1. - full = c.sourceRewrite("fixLog4jRemainingReconstructs", "class_source", full, fixLog4jRemainingReconstructs) - // original-14 remainder uniques unmasked by later global reconstructs. - // Kill-switch: JDEC_ORIG14_REMAINING_OFF=1. - full = c.sourceRewrite("fixOrig14RemainderReconstructs", "class_source", full, fixOrig14RemainderReconstructs) - // protobuf-java leftover unique sites. Kill-switch: JDEC_PROTOBUF_REMAINING_OFF=1. - full = c.sourceRewrite("fixProtobufRemainingReconstructs", "class_source", full, fixProtobufRemainingReconstructs) - // jedis leftover unique sites. Kill-switch: JDEC_JEDIS_REMAINING_OFF=1. - full = c.sourceRewrite("fixJedisRemainingReconstructs", "class_source", full, fixJedisRemainingReconstructs) - // logback leftover unique sites. Kill-switch: JDEC_LOGBACK_REMAINING_OFF=1. - full = c.sourceRewrite("fixLogbackRemainingReconstructs", "class_source", full, fixLogbackRemainingReconstructs) - // HikariCP leftover unique sites. Kill-switch: JDEC_HIKARICP_REMAINING_OFF=1. - full = c.sourceRewrite("fixHikaricpRemainingReconstructs", "class_source", full, fixHikaricpRemainingReconstructs) - // commons-pool2 leftover unique sites. Kill-switch: JDEC_POOL2_REMAINING_OFF=1. - full = c.sourceRewrite("fixPool2RemainingReconstructs", "class_source", full, fixPool2RemainingReconstructs) - // picocli leftover unique sites. Kill-switch: JDEC_PICOCLI_REMAINING_OFF=1. - full = c.sourceRewrite("fixPicocliRemainingReconstructs", "class_source", full, fixPicocliRemainingReconstructs) - // httpclient leftover unique sites. Kill-switch: JDEC_HTTPCLIENT_REMAINING_OFF=1. - full = c.sourceRewrite("fixHttpclientRemainingReconstructs", "class_source", full, fixHttpclientRemainingReconstructs) - // javassist leftover unique sites. Kill-switch: JDEC_JAVASSIST_REMAINING_OFF=1. - full = c.sourceRewrite("fixJavassistRemainingReconstructs", "class_source", full, fixJavassistRemainingReconstructs) - // commons-io leftover unique sites. Kill-switch: JDEC_COMMONS_IO_REMAINING_OFF=1. - full = c.sourceRewrite("fixCommonsIoRemainingReconstructs", "class_source", full, fixCommonsIoRemainingReconstructs) - // commons-compress leftover unique sites. Kill-switch: JDEC_COMPRESS_REMAINING_OFF=1. - full = c.sourceRewrite("fixCompressRemainingReconstructs", "class_source", full, fixCompressRemainingReconstructs) - // caffeine leftover unique sites. Kill-switch: JDEC_CAFFEINE_REMAINING_OFF=1. - full = c.sourceRewrite("fixCaffeineRemainingReconstructs", "class_source", full, fixCaffeineRemainingReconstructs) - // rxjava leftover unique sites. Kill-switch: JDEC_RXJAVA_REMAINING_OFF=1. - full = c.sourceRewrite("fixRxjavaRemainingReconstructs", "class_source", full, func(source string) string { - return fixRxjavaRemainingWithBinding(source, c.FuncCtx.SiblingClassSig != nil) - }) - // commons-math3 leftover unique sites. Kill-switch: JDEC_MATH3_REMAINING_OFF=1. - full = c.sourceRewrite("fixMath3RemainingReconstructs", "class_source", full, fixMath3RemainingReconstructs) - // assertj leftover unique sites. Kill-switch: JDEC_ASSERTJ_REMAINING_OFF=1. - full = c.sourceRewrite("fixAssertjRemainingReconstructs", "class_source", full, fixAssertjRemainingReconstructs) - // zxing leftover unique sites. Kill-switch: JDEC_ZXING_REMAINING_OFF=1. - full = c.sourceRewrite("fixZxingRemainingReconstructs", "class_source", full, fixZxingRemainingReconstructs) - // Enum no-arg ctor `this(Object,Object,…)` after locals. Kill-switch: - // JDEC_ENUM_CTOR_THIS_FIRST_OFF=1. - full = c.sourceRewrite("fixEnumNoArgCtorThisAfterLocals", "class_source", full, fixEnumNoArgCtorThisAfterLocals) - full = c.sourceRewrite("fixCtorNPECheckBeforeThis", "class_source", full, fixCtorNPECheckBeforeThis) - full = c.sourceRewrite("fixCtorDelegationArgumentSpills", "class_source", full, fixCtorDelegationArgumentSpills) - backingField := c.enumSyntheticBackingField - full = c.sourceRewrite("fixEnumClinitIllegalNew", "class_source", full, func(source string) string { - return stripEnumBackingAssignment(fixEnumClinitIllegalNew(source), backingField) - }) - if backingField != "" && c.nativeEnumBacking != nil && c.nativeEnumBacking.entriesField != "" { - // Kotlin publishes the same backing array as an EnumEntries view. The - // backing field is source-erased; values() regenerates an identical - // declaration-order copy. Shield literals/comments while replacing. - full = c.sourceRewrite("fixKotlinEnumEntries", "class_source", full, func(source string) string { - return rewriteJavaCode(source, func(code string) string { - return strings.ReplaceAll(code, backingField, "values()") - }) + if c.options.Mode != Precision { + // Enum-switch projection belongs to the certified original statement + // protocol. Unproved mapping arrays and integer dispatch remain intact: + // source spelling cannot establish initializer effects, artifact ownership + // or the compiler's numbered-helper namespace. + // Capture snapshots require stable source bindings. Definite assignment + // is established by original reaching definitions, not guessed defaults. + full = c.sourceRewrite("fixLambdaLoopCapture", "class_source", full, func(source string) string { + return fixLambdaLoopCaptureWithStableBindings(source, c.completedLambdaStableSourceBindings(source, methods)) }) - } - full = c.sourceRewrite("fixBareNestedImports", "class_source", full, fixBareNestedImports) - full = c.sourceRewrite("fixHardjarShapes", "class_source", full, fixHardjarShapes) - // boolean local used as `*`/`+` operand. Kill-switch: JDEC_BOOL_ARITH_OPERAND_OFF=1. - full = c.sourceRewrite("fixBoolUsedAsArithOperand", "class_source", full, fixBoolUsedAsArithOperand) - // boolean local compared/assigned JVM 0/1. Kill-switch: JDEC_BOOL_ZERO_LITERAL_OFF=1. - full = c.sourceRewrite("fixBooleanZeroLiteral", "class_source", full, fixBooleanZeroLiteral) - // `intVar == ((2) != (0))` → `intVar == (2)`. Kill-switch: JDEC_INT_CMP_BOOL_LIT_OFF=1. - full = c.sourceRewrite("fixIntCmpBoolMaterializedLiteral", "class_source", full, fixIntCmpBoolMaterializedLiteral) - // BoundedInputStream local later assigned CRC32Verifying/CheckedInputStream. - // Kill-switch: JDEC_BOUNDED_STREAM_WIDEN_OFF=1. - full = c.sourceRewrite("fixBoundedStreamWiden", "class_source", full, fixBoundedStreamWiden) - // Object local used as int (IOUtils read-length). Kill-switch: JDEC_OBJECT_AS_INT_OFF=1. - full = c.sourceRewrite("fixObjectUsedAsInt", "class_source", full, fixObjectUsedAsInt) - // int local used with instanceof / getClass (object-as-int over-match). - // Kill-switch: JDEC_INT_INSTANCEOF_OBJECT_OFF=1. - full = c.sourceRewrite("fixIntUsedAsInstanceof", "class_source", full, fixIntUsedAsInstanceof) - // xstream leftover unique sites. After bool-arith / boolean-zero so those - // cannot revert isAssignableFrom boolean locals. Kill-switch: JDEC_XSTREAM_REMAINING_OFF=1. - full = c.sourceRewrite("fixXstreamRemainingReconstructs", "class_source", full, fixXstreamRemainingReconstructs) - // freemarker leftover unique sites. After object-as-int / instanceof undo. - // Kill-switch: JDEC_FREEMARKER_REMAINING_OFF=1. - full = c.sourceRewrite("fixFreemarkerRemainingReconstructs", "class_source", full, fixFreemarkerRemainingReconstructs) - // `Object varN; throw varN` after assigning a Throwable. Kill-switch: - // JDEC_THROW_OBJECT_OFF=1. - full = c.sourceRewrite("fixThrowObjectAsThrowable", "class_source", full, fixThrowObjectAsThrowable) - // static `class$Foo` used in a field initializer declared after that - // field (illegal forward reference). Kill-switch: JDEC_CLASSDOLLAR_FORWARD_OFF=1. - full = c.sourceRewrite("fixClassDollarForwardRef", "class_source", full, fixClassDollarForwardRef) - // throw new E().initCause(t) throws Throwable. Kill-switch: - // JDEC_THROW_INITCAUSE_OFF=1. - full = c.sourceRewrite("fixThrowInitCauseCast", "class_source", full, fixThrowInitCauseCast) - // MutinyRegistrar FROM-publisher lambdas: publisher(Object) vs Publisher. - // Kill-switch: JDEC_MUTINY_PUBLISHER_CAST_OFF=1. - full = c.sourceRewrite("fixMutinyPublisherCast", "class_source", full, fixMutinyPublisherCast) - // Raw SAM / generic method-ref sites that lose the source's FI cast. - // Kill-switch: JDEC_SPRING_METHODREF_CAST_OFF=1. - full = c.sourceRewrite("fixSpringMethodRefCasts", "class_source", full, fixSpringMethodRefCasts) - // DataBufferUtils.readAsynchronousFileChannel: Flux.create lambda sink - // is FluxSink; ReadCompletionHandler wants FluxSink. - // Kill-switch: JDEC_FLUX_CREATE_DATABUFFER_OFF=1. - full = c.sourceRewrite("fixFluxCreateDataBufferWitness", "class_source", full, fixFluxCreateDataBufferWitness) - // UrlResource(String,String,String): new URI throws URISyntaxException, which - // the source wrapped as MalformedURLException. Kill-switch: - // JDEC_URLRESOURCE_URI_SYNTAX_OFF=1. - full = c.sourceRewrite("fixUrlResourceURISyntax", "class_source", full, fixUrlResourceURISyntax) - // PercInstantiator: getDeclaredMethod moved to a field-init try/catch, leaving - // the constructor catch(RuntimeException | NoSuchMethodException) with NSME - // never thrown. Kill-switch: JDEC_PERC_NSME_CATCH_OFF=1. - full = c.sourceRewrite("fixPercNSMECatch", "class_source", full, fixPercNSMECatch) - // FutureAdapter.adaptInternal: CFG emptied the synchronized switch, leaving - // a T-returning method with no return. Kill-switch: JDEC_FUTUREADAPTER_RETURN_OFF=1. - full = c.sourceRewrite("fixFutureAdapterReturn", "class_source", full, fixFutureAdapterReturn) - // If-diamond split of a post-merge try/catch or try/finally leaks `varN = Exception;`. - // Reconstruct from the sibling arm (Monitor.enterWhen / InetAddresses.textToNumericFormatV6). - // Kill-switch: JDEC_LEAKED_EXCEPTION_SENTINEL_OFF=1. Also applied per-method before - // the sentinel-degrade stub so the method is rebuilt instead of stubbed. - full = c.sourceRewrite("fixLeakedExceptionSentinel", "class_source", full, fixLeakedExceptionSentinel) - // `(varN) varN` / `(varN)(varN)` is a leaked catch-placeholder cast that - // used the local as a type (junit FailOnTimeout$CallableStatement, - // CategoryFilterFactory). Kill-switch: JDEC_IDENT_SELF_CAST_OFF=1. - full = c.sourceRewrite("fixIdentSelfCast", "class_source", full, fixIdentSelfCast) - full = c.sourceRewrite("wrapThrowTargetException", "class_source", full, wrapThrowTargetException) - // Second pass: CGLIBEnhancedConverter loop-index retype can be reverted by - // earlier remaining reconstructs; re-apply after the rest of the pipeline. - full = c.sourceRewrite("fixXstreamRemainingReconstructs", "class_source", full, fixXstreamRemainingReconstructs) - full = c.sourceRewrite("fixJavassistRemainingReconstructs", "class_source", full, fixJavassistRemainingReconstructs) - // BloomFilter boolean-OR accumulator can be reverted by math3 bool-counter - // retype when nextMemberStart swallows a later varN++ in the enum constant. - full = c.sourceRewrite("fixOrig14RemainderReconstructs", "class_source", full, fixOrig14RemainderReconstructs) - full = c.sourceRewrite("fixJacksonRemainingReconstructs", "class_source", full, fixJacksonRemainingReconstructs) - full = c.sourceRewrite("fixNettyRemainingReconstructs", "class_source", full, fixNettyRemainingReconstructs) - full = c.sourceRewrite("fixLog4jRemainingReconstructs", "class_source", full, fixLog4jRemainingReconstructs) - if !hardjarShapeOff() { - full = c.sourceRewrite("fixIdentAsTypeDecl", "class_source", full, fixIdentAsTypeDecl) - full = c.sourceRewrite("fixObjectInitCastType", "class_source", full, fixObjectInitCastType) + // removeUnreachableSwitchBreak drops `break;` after a nested switch whose default throws/returns. + // Kill-switch: JDEC_RM_UNREACHABLE_BREAK_OFF=1. + full = c.sourceRewrite("removeUnreachableSwitchBreak", "class_source", full, removeUnreachableSwitchBreak) + // A lexical block boundary cannot prove a method exit. Empty conditional + // arms may reach a shared continuation after several enclosing scopes; + // only the typed control-flow graph can authorize a return. + // fixTryBreakReturn moves a hoisted `return ;` back into a `try { break; }` block + // inside a do-while(true) loop, where the try's catch clauses require the return's + // checked-exception to be throwable. Kill-switch: JDEC_FIX_TRY_BREAK_RETURN_OFF=1. + full = c.sourceRewrite("fixTryBreakReturn", "class_source", full, fixTryBreakReturn) + // fixThrowTypeVarCast adds the `(T)` cast to `throw ;` inside a method whose `throws` + // clause declares a type variable (e.g. `throws T` where `T extends Throwable`), when the + // thrown variable's type is `Throwable` (too broad for `throws T`). The original source had + // `throw (T) throwable;` but the bytecode erased the cast. Kill-switch: + // JDEC_FIX_THROW_TYPEVAR_CAST_OFF=1. Canonical: commons-lang3 ExceptionUtils.typeErasure. + full = c.sourceRewrite("fixThrowTypeVarCast", "class_source", full, fixThrowTypeVarCast) + // fixLoopCatchThrow removes a `throw new RuntimeException();` that was added to an empty + // catch by the catch-rendering fix when the catch is inside a loop (followed by + // continue/break). Empty catches inside loops are intentional (swallow and continue), so the + // throw would make the continue/break unreachable. Kill-switch: JDEC_FIX_LOOP_CATCH_THROW_OFF=1. + full = c.sourceRewrite("fixLoopCatchThrow", "class_source", full, fixLoopCatchThrow) + // Fix try/catch structuring: move exception-throwing calls that are rendered outside a + // try block INTO the nearest inner try body. Kill-switch: JDEC_FIX_TRYCATCH_OFF=1. + full = c.sourceRewrite("fixTryCatchExceptionPlacement", "class_source", full, fixTryCatchExceptionPlacement) + // Catch types are recovered from the exception table. A call's spelling + // does not prove its declaring owner, throws signature, or handler coverage; + // guessing here adds exceptions to unrelated catches (e.g. getMethod()). + // Original handler membership owns catch alternatives, including exceptions + // thrown before an inner try or by one of its catch bodies. + // wrapUncaughtThrowingCall wraps `UNSAFE.allocateInstance()` in try/catch. Kill-switch: + // JDEC_WRAP_ALLOCATE_OFF=1. + full = c.sourceRewrite("wrapUncaughtThrowingCall", "class_source", full, wrapUncaughtThrowingCall) + // wrapReflectionCallInSwitchCase wraps switch-case reflection calls in try/catch. Kill-switch: + // JDEC_WRAP_REFLECTION_CASE_OFF=1. + full = c.sourceRewrite("wrapReflectionCallInSwitchCase", "class_source", full, wrapReflectionCallInSwitchCase) + // Case exits are determined from CFG edges. Source assignments cannot + // distinguish a genuine break from an intentional fall-through dependency; + // inserting terminators here truncates rolling hash tails and numeric state. + // A switch break continues along its CFG successor. Never synthesize a + // default return here: block-closing braces do not prove method completion, + // and returning null silently truncates nested switches and decode loops. + // wrapFieldInitializerReflection converts a field initializer containing a reflection call + // (getMethod etc.) that throws a checked exception into a static-block init with try/catch. + // Kill-switch: JDEC_WRAP_FIELD_INIT_OFF=1. + full = c.sourceRewrite("wrapFieldInitializerReflection", "class_source", full, wrapFieldInitializerReflection) + // wrapUncaughtGetConstructor wraps a bare first-stmt `cls.getConstructor(...)` in + // try/catch(NoSuchMethodException). Class-gated to AddDelegateTransformer (global wrap + // unmasks snakeyaml/fastjson2). Kill-switch: JDEC_WRAP_GETCONSTRUCTOR_OFF=1. + full = c.sourceRewrite("wrapUncaughtGetConstructor", "class_source", full, wrapUncaughtGetConstructor) + // Preserve the recovered alternatives too. A materialized Class[] can be + // declared outside the try, and any callee may declare a checked exception. + // Absence of a familiar reflection expression cannot prove a catch redundant. + // Drop catch(T) when an earlier catch in the same try already covers T + // (multicatch then a second catch(T)). Kill-switch: JDEC_ALREADY_CAUGHT_OFF=1. + full = c.sourceRewrite("fixAlreadyCaughtDuplicateCatch", "class_source", full, fixAlreadyCaughtDuplicateCatch) + // Handler completion comes from the original CFG. A following return does + // not prove that a user-written wrapping throw was a synthesized repair. + // Subclass field `this.f = this.f` is getfield Super.f; putfield This.f. + // Kill-switch: JDEC_SHADOW_FIELD_SUPER_ASSIGN_OFF=1. + full = c.sourceRewrite("fixShadowFieldSuperAssign", "class_source", full, fixShadowFieldSuperAssign) + // fixImmutableBuilderWitness inserts an explicit type witness on + // `ImmutableMap f = ImmutableMap.builder()` so builder() does not infer . + // Kill-switch: JDEC_IMMUTABLE_BUILDER_WITNESS_OFF=1. + full = c.sourceRewrite("fixImmutableBuilderWitness", "class_source", full, fixImmutableBuilderWitness) + // fixSelectMethodsAmbiguous casts the lambda in MethodIntrospector.selectMethods(Class, + // MethodFilter) so javac does not confuse it with the MetadataLookup overload. + // Kill-switch: JDEC_SELECTMETHODS_CAST_OFF=1. + full = c.sourceRewrite("fixSelectMethodsAmbiguous", "class_source", full, fixSelectMethodsAmbiguous) + // fixAsMapFunctionRawCast wraps asMap(lambda, Adapt...) lambdas in a raw Function + // cast so javac does not reject Function + // against Function, T>. + // Kill-switch: JDEC_ASMAP_FUNCTION_CAST_OFF=1. + full = c.sourceRewrite("fixAsMapFunctionRawCast", "class_source", full, fixAsMapFunctionRawCast) + // Checked catches are recovered from original instructions, declarations + // and exception regions. Injecting an unreachable throw invents source + // effects and invalidates already completed lambda-body observations. + // Compatibility must retain the same proved handler, without dead code. + // fixThrowClassCastDropsThrowable unwraps `throw ((Throwable)(cls.cast(x)))` to + // `throw cls.cast(x)` so a method `throws X` (X a type variable) actually throws X + // rather than undeclared Throwable. Real hit: guava Throwables.throwIfInstanceOf. + // Kill-switch: JDEC_THROW_CLASS_CAST_DROP_THROWABLE_OFF=1. + full = c.sourceRewrite("fixThrowClassCastDropsThrowable", "class_source", full, fixThrowClassCastDropsThrowable) + // fixReplaceAllListStreamCast casts the replaceAll value param to List before .stream() + // on a raw HashMap (l1 is Object). Real hit: spring SpringFactoriesLoader.loadSpringFactories. + // Kill-switch: JDEC_REPLACEALL_LIST_STREAM_CAST_OFF=1. + full = c.sourceRewrite("fixReplaceAllListStreamCast", "class_source", full, fixReplaceAllListStreamCast) + // fixClassMapEntryPutCasts inserts (Class) on raw Map.Entry getKey/getValue fed to a + // Class-valued map. Real hit: spring ClassUtils primitiveTypeToWrapperMap. + // Kill-switch: JDEC_CLASS_MAP_ENTRY_PUT_CAST_OFF=1. + full = c.sourceRewrite("fixClassMapEntryPutCasts", "class_source", full, fixClassMapEntryPutCasts) + // fixVisitAnnotationConsumerCast rewrites Consumer to raw Consumer + // so it applies to Consumer>. Real hit: spring + // MergedAnnotationReadingVisitor.visitAnnotation. + // Kill-switch: JDEC_VISITANNOTATION_CONSUMER_CAST_OFF=1. + full = c.sourceRewrite("fixVisitAnnotationConsumerCast", "class_source", full, fixVisitAnnotationConsumerCast) + // Scoped to the exact getUninterruptibly empty-try shape (not a class-wide regex). + full = c.sourceRewrite("fixGetUninterruptiblyGetInTry", "class_source", full, fixGetUninterruptiblyGetInTry) + // Scoped to the exact drainUninterruptibly empty-try shape: poll() folded out of + // the InterruptedException catch (guava Queues, unmasked once DescendingSet compiled). + full = c.sourceRewrite("fixDrainUninterruptiblyPollInTry", "class_source", full, fixDrainUninterruptiblyPollInTry) + // TRANSPOSE_CELL is Function, Cell>; Iterators.transform then + // infers T from the wildcards instead of the Iterator> return + // ("inference variable T has incompatible bounds"). Raw Function is unchecked. + // Kill-switch: JDEC_TRANSPOSE_CELL_FUNCTION_CAST_OFF=1. + full = c.sourceRewrite("fixTransposeCellFunctionCast", "class_source", full, fixTransposeCellFunctionCast) + // Class.getConstructors() is Constructor[]; asList infers List> + // which cannot convert to List> (preferringStrings). Raw List + // is unchecked. Kill-switch: JDEC_PREFERSTRINGS_ASLIST_CAST_OFF=1. + full = c.sourceRewrite("fixPreferringStringsAsListCast", "class_source", full, fixPreferringStringsAsListCast) + // SynchronizedNavigableMap lazy-init accessors: CFG emptied the + // synchronized body (field==null assign + return), leaving a non-void + // method with no return. Restore the original lazy-init reconstruct. + // Kill-switch: JDEC_SYNC_LAZY_NAV_RETURN_OFF=1. + full = c.sourceRewrite("fixSyncLazyNavigableReturn", "class_source", full, fixSyncLazyNavigableReturn) + // AbstractCatchingFuture.run: CFG copied the finally-clear into try/catch + // AND emitted a second catch(Throwable) for the finally-rethrow, which + // javac rejects ("exception Throwable has already been caught"). Fold + // back to try/catch/finally. Kill-switch: JDEC_CATCHING_FUTURE_FINALLY_OFF=1. + full = c.sourceRewrite("fixCatchingFutureFinally", "class_source", full, fixCatchingFutureFinally) + // AbstractService.startAsync/stopAsync: same finally-copied-into-catch(Throwable) + // twice. Kill-switch: JDEC_ABSTRACT_SERVICE_FINALLY_OFF=1. + full = c.sourceRewrite("fixAbstractServiceFinally", "class_source", full, fixAbstractServiceFinally) + // Monitor: empty try{break} catch(IE) with tryLock/awaitNanos folded out. + // Inject a never-taken throw so the catch is live, and wrap the folded + // calls so InterruptedException is not unreported. Kill-switch: + // JDEC_MONITOR_IE_TRY_OFF=1. + // AbstractFuture$SynchronizedHelper cas* methods: CFG emptied the + // synchronized CAS body (private outer fields aren't denotable from the + // flattened inner class), leaving boolean methods with no return. + // Kill-switch: JDEC_SYNC_HELPER_CAS_RETURN_OFF=1. + full = c.sourceRewrite("fixSyncHelperCasReturn", "class_source", full, fixSyncHelperCasReturn) + // ReschedulableCallable.reschedule: lock.unlock finally cloned into + // two catch(Throwable). Kill-switch: JDEC_RESCHEDULE_UNLOCK_FINALLY_OFF=1. + full = c.sourceRewrite("fixRescheduleUnlockFinally", "class_source", full, fixRescheduleUnlockFinally) + // General: consecutive catch(Throwable x){UNIQUE; COMMON} catch(Throwable x){COMMON; throw x} + // is a finally reconstruct. Remaining guava inner classes keep unmasking this shape. + // Kill-switch: JDEC_DUP_THROWABLE_CATCH_FINALLY_OFF=1. + full = c.sourceRewrite("fixDupThrowableCatchFinally", "class_source", full, fixDupThrowableCatchFinally) + // MoreExecutors.isAppEngineWithApiClasses: outer try is Class.forName + // (throws CNFE) but the catch is NoSuchMethodException (getMethod lives + // in the inner try). Kill-switch: JDEC_APPENGINE_CNFE_CATCH_OFF=1. + full = c.sourceRewrite("fixAppEngineCNFECatch", "class_source", full, fixAppEngineCNFECatch) + // RateLimiter.tryAcquire(int,long,TimeUnit): CFG emptied the synchronized + // body and dropped the return. Kill-switch: JDEC_RATELIMITER_TRYACQUIRE_RETURN_OFF=1. + full = c.sourceRewrite("fixRateLimiterTryAcquireReturn", "class_source", full, fixRateLimiterTryAcquireReturn) + // AnnotationReadingVisitorUtils.convertClassValues: var9_1 is used as both + // String[] and Class[] (ternary on classValuesAsString); declaring String[] + // makes `new Class[n]` / Class elements inconvertible. Object[] is the LUB. + // put(entry.getKey(), throwable) needs (String) on the raw Map.Entry key. + // Kill-switch: JDEC_CONVERT_CLASS_VALUES_OBJECT_ARRAY_OFF=1. + full = c.sourceRewrite("fixConvertClassValuesObjectArray", "class_source", full, fixConvertClassValuesObjectArray) + // MergedAnnotationCollectors.toAnnotationArray finisher: (Annotation[]) + // toArray((Object[]) generator.apply) pins R to Annotation, incompatible + // with bounded R extends Annotation. Drop both casts so toArray infers R[]. + // Kill-switch: JDEC_TO_ANNOTATION_ARRAY_FINISHER_OFF=1. + full = c.sourceRewrite("fixToAnnotationArrayFinisher", "class_source", full, fixToAnnotationArrayFinisher) + // Raw Flux.doOnNext lambda param is Object; logValue/touchDataBuffer want + // DataBuffer. Kill-switch: JDEC_DATABUFFER_LAMBDA_CAST_OFF=1. + full = c.sourceRewrite("fixDataBufferLambdaCast", "class_source", full, fixDataBufferLambdaCast) + // jackson POJOPropertyBuilder._explode: Linked receiver's withNext(Linked) + // captures T to CAP#1, so Linked is not Linked. A raw + // `(POJOPropertyBuilder$Linked)` argument makes the call unchecked. + // Kill-switch: JDEC_LINKED_WITHNEXT_RAW_OFF=1. + full = c.sourceRewrite("fixLinkedWithNextRawCast", "class_source", full, fixLinkedWithNextRawCast) + // jackson DeserializationContext.isEnabled(StreamReadCapability): generic + // JacksonFeatureSet.isEnabled erases to JacksonFeature, so the arg is wrapped + // `(JacksonFeature)(var1)` and javac cannot convert that back to StreamReadCapability. + // Kill-switch: JDEC_JACKSON_FEATURE_CAST_OFF=1. + full = c.sourceRewrite("fixJacksonFeatureUpcast", "class_source", full, fixJacksonFeatureUpcast) + // jackson StdKeyDeserializers: raw List.removeIf lambda param is Object, so + // `l0.annotated` / `l0.metadata` cannot find symbol. Cast to AnnotatedAndMetadata. + // Kill-switch: JDEC_ANNOTATED_AND_METADATA_LAMBDA_OFF=1. + full = c.sourceRewrite("fixAnnotatedAndMetadataLambda", "class_source", full, fixAnnotatedAndMetadataLambda) + // Local declarations are placed by VariableId and lexical dominance in + // RewriteVar. Reintroducing declarations from printed slot names here + // can duplicate a declaration already recovered by that typed pass. + full = c.sourceRewrite("fixJacksonRemainingReconstructs", "class_source", full, fixJacksonRemainingReconstructs) + // javac 9-13 TWR synthetic `$closeResource(Throwable, AutoCloseable)` invokeinterfaces + // AutoCloseable.close() which throws Exception, but the synthetic method does not declare + // it (okhttp ResponseBody / DiskLruCache). Kill-switch: JDEC_CLOSE_RESOURCE_THROWS_OFF=1. + full = c.sourceRewrite("fixCloseResourceThrows", "class_source", full, fixCloseResourceThrows) + // okhttp Transmitter: CFG emptied synchronized bodies of newExchange / + // exchangeMessageDone / maybeReleaseConnection (missing return). Reconstruct + // from bytecode. Kill-switch: JDEC_TRANSMITTER_SYNC_OFF=1. + full = c.sourceRewrite("fixTransmitterEmptySync", "class_source", full, fixTransmitterEmptySync) + // okhttp ExchangeFinder: CFG emptied synchronized bodies of findHealthyConnection / + // findConnection / hasRouteToTry (missing return). Kill-switch: + // JDEC_EXCHANGEFINDER_SYNC_OFF=1. + full = c.sourceRewrite("fixExchangeFinderEmptySync", "class_source", full, fixExchangeFinderEmptySync) + // okhttp RealConnection.connect: CFG emptied the try body to `if(false) throw + // IOException; break;` and left connectTunnel/connectSocket outside, so those + // IOException-throwing calls are uncaught. Kill-switch: JDEC_REALCONNECTION_CONNECT_OFF=1. + full = c.sourceRewrite("fixRealConnectionConnect", "class_source", full, fixRealConnectionConnect) + // okhttp RealConnectionPool.cleanup: CFG emptied the synchronized body + // (missing return of long). Kill-switch: JDEC_CONNECTIONPOOL_CLEANUP_OFF=1. + full = c.sourceRewrite("fixConnectionPoolCleanup", "class_source", full, fixConnectionPoolCleanup) + // okhttp Http2Connection.newStream: CFG emptied the synchronized(writer) body + // (missing return of Http2Stream). Kill-switch: JDEC_HTTP2_NEWSTREAM_OFF=1. + full = c.sourceRewrite("fixHttp2NewStream", "class_source", full, fixHttp2NewStream) + // okhttp Http2Stream.getSink / closeInternal: CFG emptied synchronized + // bodies (missing return). Kill-switch: JDEC_HTTP2_STREAM_SYNC_OFF=1. + full = c.sourceRewrite("fixHttp2StreamEmptySync", "class_source", full, fixHttp2StreamEmptySync) + // Catch-all: a non-void method whose last statement is an empty synchronized + // body is missing a return (okhttp DiskLruCache$Editor.newSource/newSink and + // remaining empty-sync sites). Specific reconstructs above run first. + // Kill-switch: JDEC_EMPTY_SYNC_RETURN_OFF=1. + full = c.sourceRewrite("fixEmptySyncMissingReturn", "class_source", full, fixEmptySyncMissingReturn) + // okhttp Util.skipLeading/TrailingAsciiWhitespace: whitespace cases fall + // through into `default: return`, making the loop `continue` unreachable. + // Kill-switch: JDEC_SKIP_WS_CONTINUE_OFF=1. + full = c.sourceRewrite("fixSkipAsciiWhitespaceContinue", "class_source", full, fixSkipAsciiWhitespaceContinue) + // okhttp DiskLruCache$3.hasNext: empty synchronized in the else of + // `if (nextSnapshot != null) return true`. Kill-switch: JDEC_DISKLRU_ITER_OFF=1. + full = c.sourceRewrite("fixDiskLruIteratorHasNext", "class_source", full, fixDiskLruIteratorHasNext) + // okhttp PublicSuffixDatabase: findMatchingRule empty sync (missing return) + // and readTheListUninterruptibly's readTheList() escaped the IOException try. + // Kill-switch: JDEC_PUBLIC_SUFFIX_OFF=1. + full = c.sourceRewrite("fixPublicSuffixDatabase", "class_source", full, fixPublicSuffixDatabase) + // commons-collections4 leftover unique sites (compare inference, singletonList + // capture, ArrayList.class factory, inherited inToRange Object key). + // Kill-switch: JDEC_COLLECTIONS4_REMAINING_OFF=1. + full = c.sourceRewrite("fixCollections4RemainingReconstructs", "class_source", full, fixCollections4RemainingReconstructs) + // netty-handler leftover unique sites. Kill-switch: JDEC_NETTY_REMAINING_OFF=1. + full = c.sourceRewrite("fixNettyRemainingReconstructs", "class_source", full, fixNettyRemainingReconstructs) + // log4j-core leftover unique sites. Kill-switch: JDEC_LOG4J_REMAINING_OFF=1. + full = c.sourceRewrite("fixLog4jRemainingReconstructs", "class_source", full, fixLog4jRemainingReconstructs) + // original-14 remainder uniques unmasked by later global reconstructs. + // Kill-switch: JDEC_ORIG14_REMAINING_OFF=1. + full = c.sourceRewrite("fixOrig14RemainderReconstructs", "class_source", full, fixOrig14RemainderReconstructs) + // protobuf-java leftover unique sites. Kill-switch: JDEC_PROTOBUF_REMAINING_OFF=1. + full = c.sourceRewrite("fixProtobufRemainingReconstructs", "class_source", full, fixProtobufRemainingReconstructs) + // jedis leftover unique sites. Kill-switch: JDEC_JEDIS_REMAINING_OFF=1. + full = c.sourceRewrite("fixJedisRemainingReconstructs", "class_source", full, fixJedisRemainingReconstructs) + // logback leftover unique sites. Kill-switch: JDEC_LOGBACK_REMAINING_OFF=1. + full = c.sourceRewrite("fixLogbackRemainingReconstructs", "class_source", full, fixLogbackRemainingReconstructs) + // HikariCP leftover unique sites. Kill-switch: JDEC_HIKARICP_REMAINING_OFF=1. + full = c.sourceRewrite("fixHikaricpRemainingReconstructs", "class_source", full, fixHikaricpRemainingReconstructs) + // commons-pool2 leftover unique sites. Kill-switch: JDEC_POOL2_REMAINING_OFF=1. + full = c.sourceRewrite("fixPool2RemainingReconstructs", "class_source", full, fixPool2RemainingReconstructs) + // picocli leftover unique sites. Kill-switch: JDEC_PICOCLI_REMAINING_OFF=1. + full = c.sourceRewrite("fixPicocliRemainingReconstructs", "class_source", full, fixPicocliRemainingReconstructs) + // httpclient leftover unique sites. Kill-switch: JDEC_HTTPCLIENT_REMAINING_OFF=1. + full = c.sourceRewrite("fixHttpclientRemainingReconstructs", "class_source", full, fixHttpclientRemainingReconstructs) + // javassist leftover unique sites. Kill-switch: JDEC_JAVASSIST_REMAINING_OFF=1. + full = c.sourceRewrite("fixJavassistRemainingReconstructs", "class_source", full, fixJavassistRemainingReconstructs) + // commons-io leftover unique sites. Kill-switch: JDEC_COMMONS_IO_REMAINING_OFF=1. + full = c.sourceRewrite("fixCommonsIoRemainingReconstructs", "class_source", full, fixCommonsIoRemainingReconstructs) + // commons-compress leftover unique sites. Kill-switch: JDEC_COMPRESS_REMAINING_OFF=1. + full = c.sourceRewrite("fixCompressRemainingReconstructs", "class_source", full, fixCompressRemainingReconstructs) + // caffeine leftover unique sites. Kill-switch: JDEC_CAFFEINE_REMAINING_OFF=1. + full = c.sourceRewrite("fixCaffeineRemainingReconstructs", "class_source", full, fixCaffeineRemainingReconstructs) + // rxjava leftover unique sites. Kill-switch: JDEC_RXJAVA_REMAINING_OFF=1. + full = c.sourceRewrite("fixRxjavaRemainingReconstructs", "class_source", full, func(source string) string { + return fixRxjavaRemainingWithBinding(source, c.FuncCtx.SiblingClassSig != nil) + }) + // commons-math3 leftover unique sites. Kill-switch: JDEC_MATH3_REMAINING_OFF=1. + full = c.sourceRewrite("fixMath3RemainingReconstructs", "class_source", full, fixMath3RemainingReconstructs) + // assertj leftover unique sites. Kill-switch: JDEC_ASSERTJ_REMAINING_OFF=1. + full = c.sourceRewrite("fixAssertjRemainingReconstructs", "class_source", full, fixAssertjRemainingReconstructs) + // zxing leftover unique sites. Kill-switch: JDEC_ZXING_REMAINING_OFF=1. + full = c.sourceRewrite("fixZxingRemainingReconstructs", "class_source", full, fixZxingRemainingReconstructs) + // Enum no-arg ctor `this(Object,Object,…)` after locals. Kill-switch: + // JDEC_ENUM_CTOR_THIS_FIRST_OFF=1. + full = c.sourceRewrite("fixEnumNoArgCtorThisAfterLocals", "class_source", full, fixEnumNoArgCtorThisAfterLocals) + full = c.sourceRewrite("fixCtorNPECheckBeforeThis", "class_source", full, fixCtorNPECheckBeforeThis) + full = c.sourceRewrite("fixCtorDelegationArgumentSpills", "class_source", full, fixCtorDelegationArgumentSpills) + backingField := c.enumSyntheticBackingField + full = c.sourceRewrite("fixEnumClinitIllegalNew", "class_source", full, func(source string) string { + return stripEnumBackingAssignment(fixEnumClinitIllegalNew(source), backingField) + }) + if backingField != "" && c.nativeEnumBacking != nil && c.nativeEnumBacking.entriesField != "" { + // Kotlin publishes the same backing array as an EnumEntries view. The + // backing field is source-erased; values() regenerates an identical + // declaration-order copy. Shield literals/comments while replacing. + full = c.sourceRewrite("fixKotlinEnumEntries", "class_source", full, func(source string) string { + return rewriteJavaCode(source, func(code string) string { + return strings.ReplaceAll(code, backingField, "values()") + }) + }) + } + full = c.sourceRewrite("fixBareNestedImports", "class_source", full, fixBareNestedImports) + full = c.sourceRewrite("fixHardjarShapes", "class_source", full, fixHardjarShapes) + // boolean local used as `*`/`+` operand. Kill-switch: JDEC_BOOL_ARITH_OPERAND_OFF=1. + full = c.sourceRewrite("fixBoolUsedAsArithOperand", "class_source", full, fixBoolUsedAsArithOperand) + // boolean local compared/assigned JVM 0/1. Kill-switch: JDEC_BOOL_ZERO_LITERAL_OFF=1. + full = c.sourceRewrite("fixBooleanZeroLiteral", "class_source", full, fixBooleanZeroLiteral) + // `intVar == ((2) != (0))` → `intVar == (2)`. Kill-switch: JDEC_INT_CMP_BOOL_LIT_OFF=1. + full = c.sourceRewrite("fixIntCmpBoolMaterializedLiteral", "class_source", full, fixIntCmpBoolMaterializedLiteral) + // BoundedInputStream local later assigned CRC32Verifying/CheckedInputStream. + // Kill-switch: JDEC_BOUNDED_STREAM_WIDEN_OFF=1. + full = c.sourceRewrite("fixBoundedStreamWiden", "class_source", full, fixBoundedStreamWiden) + // Object local used as int (IOUtils read-length). Kill-switch: JDEC_OBJECT_AS_INT_OFF=1. + full = c.sourceRewrite("fixObjectUsedAsInt", "class_source", full, fixObjectUsedAsInt) + // int local used with instanceof / getClass (object-as-int over-match). + // Kill-switch: JDEC_INT_INSTANCEOF_OBJECT_OFF=1. + full = c.sourceRewrite("fixIntUsedAsInstanceof", "class_source", full, fixIntUsedAsInstanceof) + // xstream leftover unique sites. After bool-arith / boolean-zero so those + // cannot revert isAssignableFrom boolean locals. Kill-switch: JDEC_XSTREAM_REMAINING_OFF=1. + full = c.sourceRewrite("fixXstreamRemainingReconstructs", "class_source", full, fixXstreamRemainingReconstructs) + // freemarker leftover unique sites. After object-as-int / instanceof undo. + // Kill-switch: JDEC_FREEMARKER_REMAINING_OFF=1. + full = c.sourceRewrite("fixFreemarkerRemainingReconstructs", "class_source", full, fixFreemarkerRemainingReconstructs) + // `Object varN; throw varN` after assigning a Throwable. Kill-switch: + // JDEC_THROW_OBJECT_OFF=1. + full = c.sourceRewrite("fixThrowObjectAsThrowable", "class_source", full, fixThrowObjectAsThrowable) + // static `class$Foo` used in a field initializer declared after that + // field (illegal forward reference). Kill-switch: JDEC_CLASSDOLLAR_FORWARD_OFF=1. + full = c.sourceRewrite("fixClassDollarForwardRef", "class_source", full, fixClassDollarForwardRef) + // throw new E().initCause(t) throws Throwable. Kill-switch: + // JDEC_THROW_INITCAUSE_OFF=1. + full = c.sourceRewrite("fixThrowInitCauseCast", "class_source", full, fixThrowInitCauseCast) + // MutinyRegistrar FROM-publisher lambdas: publisher(Object) vs Publisher. + // Kill-switch: JDEC_MUTINY_PUBLISHER_CAST_OFF=1. + full = c.sourceRewrite("fixMutinyPublisherCast", "class_source", full, fixMutinyPublisherCast) + // Raw SAM / generic method-ref sites that lose the source's FI cast. + // Kill-switch: JDEC_SPRING_METHODREF_CAST_OFF=1. + full = c.sourceRewrite("fixSpringMethodRefCasts", "class_source", full, fixSpringMethodRefCasts) + // DataBufferUtils.readAsynchronousFileChannel: Flux.create lambda sink + // is FluxSink; ReadCompletionHandler wants FluxSink. + // Kill-switch: JDEC_FLUX_CREATE_DATABUFFER_OFF=1. + full = c.sourceRewrite("fixFluxCreateDataBufferWitness", "class_source", full, fixFluxCreateDataBufferWitness) + // UrlResource(String,String,String): new URI throws URISyntaxException, which + // the source wrapped as MalformedURLException. Kill-switch: + // JDEC_URLRESOURCE_URI_SYNTAX_OFF=1. + full = c.sourceRewrite("fixUrlResourceURISyntax", "class_source", full, fixUrlResourceURISyntax) + // PercInstantiator: getDeclaredMethod moved to a field-init try/catch, leaving + // the constructor catch(RuntimeException | NoSuchMethodException) with NSME + // never thrown. Kill-switch: JDEC_PERC_NSME_CATCH_OFF=1. + full = c.sourceRewrite("fixPercNSMECatch", "class_source", full, fixPercNSMECatch) + // FutureAdapter.adaptInternal: CFG emptied the synchronized switch, leaving + // a T-returning method with no return. Kill-switch: JDEC_FUTUREADAPTER_RETURN_OFF=1. + full = c.sourceRewrite("fixFutureAdapterReturn", "class_source", full, fixFutureAdapterReturn) + // If-diamond split of a post-merge try/catch or try/finally leaks `varN = Exception;`. + // Reconstruct from the sibling arm (Monitor.enterWhen / InetAddresses.textToNumericFormatV6). + // Kill-switch: JDEC_LEAKED_EXCEPTION_SENTINEL_OFF=1. Also applied per-method before + // the sentinel-degrade stub so the method is rebuilt instead of stubbed. + full = c.sourceRewrite("fixLeakedExceptionSentinel", "class_source", full, fixLeakedExceptionSentinel) + // `(varN) varN` / `(varN)(varN)` is a leaked catch-placeholder cast that + // used the local as a type (junit FailOnTimeout$CallableStatement, + // CategoryFilterFactory). Kill-switch: JDEC_IDENT_SELF_CAST_OFF=1. + full = c.sourceRewrite("fixIdentSelfCast", "class_source", full, fixIdentSelfCast) + full = c.sourceRewrite("wrapThrowTargetException", "class_source", full, wrapThrowTargetException) + // Second pass: CGLIBEnhancedConverter loop-index retype can be reverted by + // earlier remaining reconstructs; re-apply after the rest of the pipeline. + full = c.sourceRewrite("fixXstreamRemainingReconstructs", "class_source", full, fixXstreamRemainingReconstructs) + full = c.sourceRewrite("fixJavassistRemainingReconstructs", "class_source", full, fixJavassistRemainingReconstructs) + // BloomFilter boolean-OR accumulator can be reverted by math3 bool-counter + // retype when nextMemberStart swallows a later varN++ in the enum constant. + full = c.sourceRewrite("fixOrig14RemainderReconstructs", "class_source", full, fixOrig14RemainderReconstructs) + full = c.sourceRewrite("fixJacksonRemainingReconstructs", "class_source", full, fixJacksonRemainingReconstructs) + full = c.sourceRewrite("fixNettyRemainingReconstructs", "class_source", full, fixNettyRemainingReconstructs) + full = c.sourceRewrite("fixLog4jRemainingReconstructs", "class_source", full, fixLog4jRemainingReconstructs) + if !hardjarShapeOff() { + full = c.sourceRewrite("fixIdentAsTypeDecl", "class_source", full, fixIdentAsTypeDecl) + full = c.sourceRewrite("fixObjectInitCastType", "class_source", full, fixObjectInitCastType) + } } if ordinaryClassSource != nil && !ordinaryClassSource.finish(full) { return "", fmt.Errorf("ordinary constructor class-source boundary is not closed") @@ -3950,6 +4016,14 @@ func (c *ClassObjectDumper) DumpMethodWithInitialId(methodName, desc string, id } func (c *ClassObjectDumper) dumpMethodWithSourceRequest(methodName, desc string, id *utils2.VariableId, adapter *core.LambdaReferenceAdapter, request methodSourceRequest) (renderedMethod *dumpedMethods, renderErr error) { + return c.dumpMethodMemberWithSourceRequest(nil, methodName, desc, id, adapter, request) +} + +// dumpMethodMemberWithSourceRequest accepts the already selected physical member used by +// DumpMethods. Public/name-based callers pass nil and retain the historical lookup and +// proof path. Keeping the pointer avoids rescanning the full method table for every method +// while preserving the exact MemberInfo identity consumed by source certificates. +func (c *ClassObjectDumper) dumpMethodMemberWithSourceRequest(method *MemberInfo, methodName, desc string, id *utils2.VariableId, adapter *core.LambdaReferenceAdapter, request methodSourceRequest) (renderedMethod *dumpedMethods, renderErr error) { if !request.valid() { return nil, fmt.Errorf("invalid method source request") } @@ -4006,8 +4080,10 @@ func (c *ClassObjectDumper) dumpMethodWithSourceRequest(methodName, desc string, c.FuncCtx.CatchEntryNames = nil defer func() { c.FuncCtx.CatchEntryNames = previousCatchEntries }() } - var method *MemberInfo - var name, descriptor string + // DumpMethods already decoded these values for the selected physical member. + // Seed the fast path from them; the public nil-member path below still resolves + // and validates the requested name/descriptor through the method table. + name, descriptor := methodName, desc var err error var dumped = &dumpedMethods{} dumped.sourceRequest = request @@ -4040,23 +4116,25 @@ func (c *ClassObjectDumper) dumpMethodWithSourceRequest(methodName, desc string, c.dumpedMethodsSet[traitId] = dumped ownedCacheEntry = dumped - for _, info := range c.obj.Methods { - name, err = c.obj.getUtf8(info.NameIndex) - if err != nil { - return dumped, utils.Wrapf(err, "getUtf8(%v) failed", info.NameIndex) - } - descriptor, err = c.obj.getUtf8(info.DescriptorIndex) - if err != nil { - return dumped, utils.Wrapf(err, "getUtf8(%v) failed", info.DescriptorIndex) + if method == nil { + for _, info := range c.obj.Methods { + name, err = c.obj.getUtf8(info.NameIndex) + if err != nil { + return dumped, utils.Wrapf(err, "getUtf8(%v) failed", info.NameIndex) + } + descriptor, err = c.obj.getUtf8(info.DescriptorIndex) + if err != nil { + return dumped, utils.Wrapf(err, "getUtf8(%v) failed", info.DescriptorIndex) + } + if name == methodName && descriptor == desc { + method = info + break + } } - if name == methodName && descriptor == desc { - method = info - break + if method == nil { + return dumped, fmt.Errorf("method %s not found", methodName) } } - if method == nil { - return dumped, fmt.Errorf("method %s not found", methodName) - } // Recursive lambda bodies bypass DumpMethods' declaration bookkeeping. // Retain the actual original target for the eventual source-consumption // certificate as well as for ordinary declarations. @@ -5428,22 +5506,24 @@ func (c *ClassObjectDumper) dumpMethodWithSourceRequest(methodName, desc string, if !funcCtx.IsStatic && name != "" { receiverType = c.GetConstructorMethodName() } - sourceCode = c.sourceRewrite("hoistSameTypeEscapedLocals", "method_source", sourceCode, hoistSameTypeEscapedLocals) - sourceCode = c.sourceRewrite("hoistCastGuardedEscapedLocals", "method_source", sourceCode, hoistCastGuardedEscapedLocals) - methodReturnTypeStr := "" - if mt := methodType.FunctionType(); mt != nil && mt.ReturnType != nil { - methodReturnTypeStr = mt.ReturnType.String(funcCtx) - } - // Typed declarations remain authoritative even when a printed type - // contains Unicode or syntax the legacy source scanner cannot parse. - // This barrier grants no permission to synthesize values or bindings. - declarationBarriers, declarationErr := rewriter.DeclarationInsertionBarriers(statementList, funcCtx, c.Work) - if declarationErr != nil { - return nil, declarationErr - } - sourceCode = c.sourceRewrite("addMissingGeneratedLocalDecls", "method_source", sourceCode, func(body string) string { - return addMissingGeneratedLocalDecls(body, paramsNewStr, receiverType, c.methodReturnTypeByName(), methodReturnTypeStr, c.nativeLexicalCaptures(), declarationBarriers) - }) + if c.options.Mode != Precision { + sourceCode = c.sourceRewrite("hoistSameTypeEscapedLocals", "method_source", sourceCode, hoistSameTypeEscapedLocals) + sourceCode = c.sourceRewrite("hoistCastGuardedEscapedLocals", "method_source", sourceCode, hoistCastGuardedEscapedLocals) + methodReturnTypeStr := "" + if mt := methodType.FunctionType(); mt != nil && mt.ReturnType != nil { + methodReturnTypeStr = mt.ReturnType.String(funcCtx) + } + // Typed declarations remain authoritative even when a printed type + // contains Unicode or syntax the legacy source scanner cannot parse. + // This barrier grants no permission to synthesize values or bindings. + declarationBarriers, declarationErr := rewriter.DeclarationInsertionBarriers(statementList, funcCtx, c.Work) + if declarationErr != nil { + return nil, declarationErr + } + sourceCode = c.sourceRewrite("addMissingGeneratedLocalDecls", "method_source", sourceCode, func(body string) string { + return addMissingGeneratedLocalDecls(body, paramsNewStr, receiverType, c.methodReturnTypeByName(), methodReturnTypeStr, c.nativeLexicalCaptures(), declarationBarriers) + }) + } if !c.nativeMethodLocalMethodSourceComplete(name, descriptor, sourceCode) { c.nativeMemberRoot.failed = true return nil, fmt.Errorf("unproved final method-local source emission") @@ -6128,8 +6208,7 @@ func renameLambdaBodyLocals(body string, seq int) string { // word-boundary match is unambiguous. Used to decide whether the parameters can be rendered implicitly. func lambdaParamsUsed(body string, names []string) bool { for _, n := range names { - re := regexp.MustCompile(`\b` + regexp.QuoteMeta(n) + `\b`) - if re.MatchString(body) { + if utils.WordMatches(body, n) { return true } } @@ -6450,9 +6529,7 @@ func leadingTabs(ln string) string { // assignTargetIs reports whether ln assigns to name as a target (`name =` but not `==`), where name // is a standalone word not preceded by a type/declaration token. func assignTargetIs(ln, name string) bool { - re := regexp.MustCompile(`\b` + regexp.QuoteMeta(name) + `\b`) - locs := re.FindAllStringIndex(ln, -1) - for _, loc := range locs { + for _, loc := range utils.WordSpans(ln, name, nil) { after := ln[loc[1]:] aTrim := strings.TrimLeft(after, " \t") if !strings.HasPrefix(aTrim, "=") || strings.HasPrefix(aTrim, "==") { @@ -6713,8 +6790,7 @@ func lambdaLineIsStmtStart(lines []string, idx int) bool { // assignment targets (`name =`) and declarations untouched. This mirrors the read-detection logic // used elsewhere (control-keyword aware). func rewriteLambdaReads(ln, name, newName string) string { - re := regexp.MustCompile(`\b` + regexp.QuoteMeta(name) + `\b`) - locs := re.FindAllStringIndex(ln, -1) + locs := utils.WordSpans(ln, name, nil) if len(locs) == 0 { return ln } @@ -6769,7 +6845,7 @@ func removeUnreachableSwitchBreak(body string) string { return body } lines := strings.Split(body, "\n") - breakRe := regexp.MustCompile(`^(\t+)break;\s*$`) + breakRe := cachedCompatibilityRegexp(`^(\t+)break;\s*$`) var removeIdx []int for i := 0; i < len(lines); i++ { m := breakRe.FindStringSubmatch(strings.TrimRight(lines[i], "\r")) @@ -6999,8 +7075,8 @@ func fixLoopCatchThrow(body string) string { // throw new RuntimeException(); // } // - catchRe := regexp.MustCompile(`^(\t+)}?catch\([^)]+\)\s*\{$`) - throwRe := regexp.MustCompile(`^\t+throw new RuntimeException\([^)]*\);\s*$`) + catchRe := cachedCompatibilityRegexp(`^(\t+)}?catch\([^)]+\)\s*\{$`) + throwRe := cachedCompatibilityRegexp(`^\t+throw new RuntimeException\([^)]*\);\s*$`) removes := []int{} for i := 0; i < len(lines)-3; i++ { cm := catchRe.FindStringSubmatch(strings.TrimRight(lines[i], "\r")) @@ -7061,6 +7137,11 @@ func fixLoopCatchThrow(body string) string { return strings.Join(lines, "\n") } +var ( + throwTypeVarSignatureRe = regexp.MustCompile(`\)\s*throws\s+([A-Z]\w*)\s*\{`) + throwTypeVarStatementRe = regexp.MustCompile(`^(\s*)throw\s+(\w+)\s*;\s*$`) +) + // Canonical: commons-lang3 ExceptionUtils.typeErasure ` R typeErasure( // Throwable throwable) throws T { throw (T) throwable; }`. func fixThrowTypeVarCast(body string) string { @@ -7071,8 +7152,9 @@ func fixThrowTypeVarCast(body string) string { // Pattern: a method signature line containing `throws ` (a single bare identifier, // not a class name), followed by a body containing `throw ;` where is a variable // of type Throwable (not already cast). We detect the method signature by the `throws T` clause - // and scan the method body for `throw ;`. - throwsTypeVarRe := regexp.MustCompile(`\)\s*throws\s+([A-Z]\w*)\s*\{`) + // and scan the method body for `throw ;`. The regexps are package-level: compiling them + // inside the per-line loop accounted for most of this pass's allocation on large classes. + throwsTypeVarRe := throwTypeVarSignatureRe type edits struct { lineIdx int oldText string @@ -7107,8 +7189,7 @@ func fixThrowTypeVarCast(body string) string { break } // Match `throw ;` where is a simple identifier (not already cast). - throwRe := regexp.MustCompile(`^(\s*)throw\s+(\w+)\s*;\s*$`) - tm := throwRe.FindStringSubmatch(jl) + tm := throwTypeVarStatementRe.FindStringSubmatch(jl) if tm == nil { continue } @@ -7185,7 +7266,7 @@ func fixTryCatchExceptionPlacement(body string) string { // Scan for the pattern: an if-block whose body contains calls to methods that throw // checked exceptions (getDeclaredConstructor, newInstance, getMethod, etc.), immediately // followed by a try block whose catch lists those exception types. - throwingCallRe := regexp.MustCompile(`\.(getDeclaredConstructor|newInstance|getMethod|getConstructor)\(`) + throwingCallRe := cachedCompatibilityRegexp(`\.(getDeclaredConstructor|newInstance|getMethod|getConstructor)\(`) for i := 0; i < len(lines); i++ { // Check if this line starts an if block. lnClean := strings.TrimRight(lines[i], "\r") @@ -7350,7 +7431,7 @@ var methodThrows = map[string]string{ // relies on the specific type of the variable; widening the multi-catch with an unrelated type // breaks the member access. func catchBodyAccessesCatchVar(lines []string, catchLineIdx int) bool { - catchRe := regexp.MustCompile(`\}catch\(([^)]*)\)\{`) + catchRe := cachedCompatibilityRegexp(`\}catch\(([^)]*)\)\{`) cl := strings.TrimRight(lines[catchLineIdx], "\r") cm := catchRe.FindStringSubmatch(cl) if cm == nil { @@ -7399,7 +7480,7 @@ func catchBodyAccessesCatchVar(lines []string, catchLineIdx int) bool { // caught variable (e.g. `catch(E var){ throw var; }`). Such a catch propagates the checked // exception; augmenting its type list would require a throws declaration on the enclosing method. func catchRethrowsVariable(lines []string, catchLineIdx int) bool { - catchRe := regexp.MustCompile(`\}catch\(([^)]*)\)\{`) + catchRe := cachedCompatibilityRegexp(`\}catch\(([^)]*)\)\{`) cl := strings.TrimRight(lines[catchLineIdx], "\r") cm := catchRe.FindStringSubmatch(cl) if cm == nil { @@ -7474,8 +7555,8 @@ func addMissingCatchException(body string) string { } dbg := jdecenv.Get("JDEC_ADD_MISSING_CATCH_DBG") == "1" lines := strings.Split(body, "\n") - catchRe := regexp.MustCompile(`\}catch\(([^)]*)\)\{`) - callRe := regexp.MustCompile(`\.(getConstructor|getDeclaredConstructor|getMethod|getDeclaredMethod)\(`) + catchRe := cachedCompatibilityRegexp(`\}catch\(([^)]*)\)\{`) + callRe := cachedCompatibilityRegexp(`\.(getConstructor|getDeclaredConstructor|getMethod|getDeclaredMethod)\(`) // Pre-compute all try/catch blocks: for each `try{`, find its body range [tryStart, tryBodyEnd) // and the catch clause line + caught types. A try's catch is relevant for call sites INSIDE the @@ -7486,7 +7567,7 @@ func addMissingCatchException(body string) string { catchLine int // line index of the `}catch(...) {` line, -1 if no catch caughtTypes string // the types listed in the catch clause } - tryRe := regexp.MustCompile(`^(\t+)try\{\s*$`) + tryRe := cachedCompatibilityRegexp(`^(\t+)try\{\s*$`) var tryBlocks []tryBlock for i := 0; i < len(lines); i++ { ln := strings.TrimRight(lines[i], "\r") @@ -7553,8 +7634,7 @@ func addMissingCatchException(body string) string { const exc = "NoSuchMethodException" excOrSup := []string{"NoSuchMethodException", "ReflectiveOperationException", "Exception", "Throwable"} caughtWord := func(typesStr, name string) bool { - re := regexp.MustCompile(`\b` + regexp.QuoteMeta(name) + `\b`) - return re.MatchString(typesStr) + return utils.WordMatches(typesStr, name) } augment := map[int]bool{} for i := 0; i < len(lines); i++ { @@ -7694,7 +7774,7 @@ func wrapUncaughtThrowingCall(body string) string { return body } lines := strings.Split(body, "\n") - allocRe := regexp.MustCompile(`^(\t+)(return .*\bUNSAFE\.allocateInstance\([^;]*\));\s*$`) + allocRe := cachedCompatibilityRegexp(`^(\t+)(return .*\bUNSAFE\.allocateInstance\([^;]*\));\s*$`) type insert struct { at int indent string @@ -7763,7 +7843,7 @@ func wrapUncaughtGetConstructor(body string) string { return body } lines := strings.Split(body, "\n") - ctorRe := regexp.MustCompile(`^(\t+)(.*\.(getConstructor|getDeclaredConstructor)\([^;]*\));\s*$`) + ctorRe := cachedCompatibilityRegexp(`^(\t+)(.*\.(getConstructor|getDeclaredConstructor)\([^;]*\));\s*$`) type insert struct { at int indent string @@ -8861,7 +8941,7 @@ func fixGetFieldClassHoist(body string) string { } body = strings.ReplaceAll(body, "var4 = var1.getDeclaringClass();", "Class var4 = var1.getDeclaringClass();") body = strings.ReplaceAll(body, "var5 = var3.getDeclaringClass();", "Class var5 = var3.getDeclaringClass();") - re := regexp.MustCompile(`if \(\(var4\) != \(var5\)\)\{\n(\s*)Class var4 = null;\n\s*Class var5 = null;\n`) + re := cachedCompatibilityRegexp(`if \(\(var4\) != \(var5\)\)\{\n(\s*)Class var4 = null;\n\s*Class var5 = null;\n`) body = re.ReplaceAllString(body, "if ((var4) != (var5)){\n$1") return body } @@ -8890,7 +8970,7 @@ func fixJacksonRemainingReconstructs(body string) string { // cannot stack. Gate on jackson LinkedDeque — caffeine AbstractLinkedDeque // iterators do not use this.cursor. if strings.Contains(body, "class LinkedDeque$") || strings.Contains(body, "class LinkedDeque ") { - computeNextRe := regexp.MustCompile(`E computeNext\(\) \{\s*return[^;]+;\s*\}`) + computeNextRe := cachedCompatibilityRegexp(`E computeNext\(\) \{\s*return[^;]+;\s*\}`) body = computeNextRe.ReplaceAllStringFunc(body, func(s string) string { if strings.Contains(s, "getPrevious") { return "E computeNext() {\n\t\treturn (E)((Object)(this.cursor.getPrevious()));\n\t}" @@ -9384,7 +9464,7 @@ func fixLogbackRemainingReconstructs(body string) string { return body } if strings.Contains(body, "class ConsoleAppender") { - orElseGet := regexp.MustCompile(`\.orElseThrow\(\(Supplier\)\(\(\) -> \{\s*return new NoSuchElementException\("No value present"\);\s*\}\)\)`) + orElseGet := cachedCompatibilityRegexp(`\.orElseThrow\(\(Supplier\)\(\(\) -> \{\s*return new NoSuchElementException\("No value present"\);\s*\}\)\)`) body = orElseGet.ReplaceAllString(body, ".get()") } @@ -9587,7 +9667,7 @@ func fixLog4jRemainingReconstructs(body string) string { body = strings.ReplaceAll(body, "lv2_6.setKey(l0);", "lv2_6.setKey((String)(l0));") - pluginCacheDeferRe := regexp.MustCompile(`lv2_6\.setDefer\((var2_f\d+)\.readBoolean\(\)\);`) + pluginCacheDeferRe := cachedCompatibilityRegexp(`lv2_6\.setDefer\((var2_f\d+)\.readBoolean\(\)\);`) body = pluginCacheDeferRe.ReplaceAllString(body, "try{\n\t\t\tlv2_6.setDefer($1.readBoolean());\n\t\t\t}catch(IOException var_io){\n\t\t\tthrow new RuntimeException((Throwable)(var_io));\n\t\t\t}") body = strings.ReplaceAll(body, @@ -9649,7 +9729,7 @@ func fixLog4jRemainingReconstructs(body string) string { // MulticastDnsAdvertiser: multi-catch already includes NoSuchMethodException, // so the trailing catch(NoSuchMethodException) is a duplicate. if strings.Contains(body, "class MulticastDnsAdvertiser") { - dupNsmeRe := regexp.MustCompile(`\}catch\(NoSuchMethodException var\d+\)\{\n\t+LOGGER\.warn\("[^"]+",\(Throwable\)\(var\d+\)\);\n\t+\}`) + dupNsmeRe := cachedCompatibilityRegexp(`\}catch\(NoSuchMethodException var\d+\)\{\n\t+LOGGER\.warn\("[^"]+",\(Throwable\)\(var\d+\)\);\n\t+\}`) body = dupNsmeRe.ReplaceAllString(body, "}") } // TextEncoderHelper.drainIfByteBufferFull: CFG emptied the synchronized @@ -9828,7 +9908,7 @@ func fixSpuriousNSMECatch(body string) string { if jdecenv.Get("JDEC_SPURIOUS_NSME_CATCH_OFF") == "1" { return body } - emptyClinit := regexp.MustCompile(`static \{\n\t+try\{\n\n\t+\}catch\(NoSuchMethodException \w+\)\{\n\t+throw new IllegalStateException\(\(Throwable\)\(\w+\)\);\n\t+\}\n\t+\}`) + emptyClinit := cachedCompatibilityRegexp(`static \{\n\t+try\{\n\n\t+\}catch\(NoSuchMethodException \w+\)\{\n\t+throw new IllegalStateException\(\(Throwable\)\(\w+\)\);\n\t+\}\n\t+\}`) body = emptyClinit.ReplaceAllString(body, "") var b strings.Builder rest := body @@ -9906,7 +9986,7 @@ func tryThrowsNSME(tryBody string) bool { // An effectful Class[] initializer may remain in a local instead of being // folded into a reflective call. Its type still proves the checked exception. func reflectionUsesClassArrayLocal(beforeCall, afterOpen string) bool { - decl := regexp.MustCompile(`(?m)^\s*(?:java\.lang\.)?Class(?:<[^\n;]+?>)?\s*\[\]\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*=`) + decl := cachedCompatibilityRegexp(`(?m)^\s*(?:java\.lang\.)?Class(?:<[^\n;]+?>)?\s*\[\]\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*=`) end := strings.IndexByte(afterOpen, ')') if end < 0 { return false @@ -10668,7 +10748,7 @@ func fixDiskLruIteratorHasNext(body string) string { } // Core declaration synthesis can retain the unused monitor temporary after // the compatibility monitor rewrite folds it back to this.this$0. - monitorDecl := regexp.MustCompile(`public boolean hasNext\(\) \{\n\t\tDiskLruCache var\d+;\n`) + monitorDecl := cachedCompatibilityRegexp(`public boolean hasNext\(\) \{\n\t\tDiskLruCache var\d+;\n`) body = monitorDecl.ReplaceAllString(body, "public boolean hasNext() {\n") return strings.ReplaceAll(body, diskLruHasNextEmpty, diskLruHasNextFixed) } @@ -10825,7 +10905,7 @@ func min2(a, b int) int { // the given line range. Includes field assignments (e.g. `this.formatValidator =`). func collectSwitchAssignedVars(lines []string, start, end int) map[string]bool { result := map[string]bool{} - assignRe := regexp.MustCompile(`\.?(\w+)\s*=[^=]`) + assignRe := cachedCompatibilityRegexp(`\.?(\w+)\s*=[^=]`) for k := start; k < end && k < len(lines); k++ { ln := strings.TrimRight(lines[k], "\r") for _, m := range assignRe.FindAllStringSubmatch(ln, -1) { @@ -10847,15 +10927,14 @@ func collectSwitchAssignedVars(lines []string, start, end int) map[string]bool { func collectSwitchDefaultSelfReads(lines []string, start, end int) map[string]bool { result := map[string]bool{} // Match `var = ... var ...` patterns: the LHS variable also appears on the RHS. - assignRe := regexp.MustCompile(`\b(\w+)\s*=\s*([^;]*)`) + assignRe := cachedCompatibilityRegexp(`\b(\w+)\s*=\s*([^;]*)`) for k := start; k < end && k < len(lines); k++ { ln := strings.TrimRight(lines[k], "\r") for _, m := range assignRe.FindAllStringSubmatch(ln, -1) { varName := m[1] rhs := m[2] // Check if varName appears in the RHS (self-read / compound assignment). - re := regexp.MustCompile(`\b` + regexp.QuoteMeta(varName) + `\b`) - if re.MatchString(rhs) { + if utils.WordMatches(rhs, varName) { result[varName] = true } } @@ -10863,20 +10942,47 @@ func collectSwitchDefaultSelfReads(lines []string, start, end int) map[string]bo return result } +// regexpSpaceByte reports whether c belongs to Go regexp's \s class. +func regexpSpaceByte(c byte) bool { + switch c { + case ' ', '\t', '\n', '\f', '\r': + return true + } + return false +} + +// wordAssignmentRHS returns the text after the first whole-token `name\s*=` +// occurrence on ln, up to but excluding the first semicolon. It is the +// literal-scan equivalent of `\b`+QuoteMeta(name)+`\s*=\s*([^;]*)`. +func wordAssignmentRHS(ln, name string) (string, bool) { + for _, loc := range utils.WordSpans(ln, name, nil) { + i := loc[1] + for i < len(ln) && regexpSpaceByte(ln[i]) { + i++ + } + if i >= len(ln) || ln[i] != '=' { + continue + } + rhs := ln[i+1:] + if semi := strings.IndexByte(rhs, ';'); semi >= 0 { + rhs = rhs[:semi] + } + return rhs, true + } + return "", false +} + // defaultAssignsIndependently reports whether the variable `name` is assigned in the given range // WITHOUT being read in the same assignment (an independent overwrite, not a compound assignment). func defaultAssignsIndependently(lines []string, start, end int, name string) bool { - assignRe := regexp.MustCompile(`\b` + regexp.QuoteMeta(name) + `\s*=\s*([^;]*)`) for k := start; k < end && k < len(lines); k++ { ln := strings.TrimRight(lines[k], "\r") - m := assignRe.FindStringSubmatch(ln) - if m == nil { + rhs, ok := wordAssignmentRHS(ln, name) + if !ok { continue } - rhs := m[1] // Check if name appears in the RHS (self-read / compound assignment). - re := regexp.MustCompile(`\b` + regexp.QuoteMeta(name) + `\b`) - if !re.MatchString(rhs) { + if !utils.WordMatches(rhs, name) { return true // independent assignment (no self-read) } } @@ -10887,7 +10993,7 @@ func defaultAssignsIndependently(lines []string, start, end int, name string) bo // the given line range. func collectSwitchReadVars(lines []string, start, end int) map[string]bool { result := map[string]bool{} - wordRe := regexp.MustCompile(`\b(\w+)\b`) + wordRe := cachedCompatibilityRegexp(`\b(\w+)\b`) for k := start; k < end && k < len(lines); k++ { ln := strings.TrimRight(lines[k], "\r") for _, m := range wordRe.FindAllStringSubmatch(ln, -1) { @@ -10929,7 +11035,7 @@ func wrapFieldInitializerReflection(body string) string { lines := strings.Split(body, "\n") // Match a field initializer at class-body indent (1 tab) with a reflection call. // Capture: indent, modifiers+type+name, init expression. - fieldRe := regexp.MustCompile(`^(\t+)((?:(?:final|static|public|private|protected)\s+)*[\w$.<>\[\]?, ]+?\s+(\w+))\s*=\s*(.*\.(getConstructor|getDeclaredConstructor|getMethod|getDeclaredMethod|getDeclaredField|getField)\(.*);\s*$`) + fieldRe := cachedCompatibilityRegexp(`^(\t+)((?:(?:final|static|public|private|protected)\s+)*[\w$.<>\[\]?, ]+?\s+(\w+))\s*=\s*(.*\.(getConstructor|getDeclaredConstructor|getMethod|getDeclaredMethod|getDeclaredField|getField)\(.*);\s*$`) counter := 0 type edit struct { at int @@ -11005,11 +11111,11 @@ func wrapReflectionCallInSwitchCase(body string) string { return body } lines := strings.Split(body, "\n") - reflRe := regexp.MustCompile(`^(\t+)return .*\.(getConstructor|getDeclaredConstructor|getMethod|getDeclaredMethod)\([^;]*\);\s*$`) + reflRe := cachedCompatibilityRegexp(`^(\t+)return .*\.(getConstructor|getDeclaredConstructor|getMethod|getDeclaredMethod)\([^;]*\);\s*$`) // Also match LambdaMetafactory chains (invokeExact/metafactory/findStatic) that throw checked // exceptions (LambdaConversionException, NoSuchMethodException, Throwable). - lambdaChainRe := regexp.MustCompile(`^(\t+)return .*\.(invokeExact|metafactory|findStatic|findVirtual)\(.*;\s*$`) - caseRe := regexp.MustCompile(`^(\t+)case [^:]+:\s*$`) + lambdaChainRe := cachedCompatibilityRegexp(`^(\t+)return .*\.(invokeExact|metafactory|findStatic|findVirtual)\(.*;\s*$`) + caseRe := cachedCompatibilityRegexp(`^(\t+)case [^:]+:\s*$`) counter := 0 type insert struct { at int @@ -11110,10 +11216,10 @@ func addBreakToSwitchCases(body string) string { return body } lines := strings.Split(body, "\n") - caseRe := regexp.MustCompile(`^(\t+)case [^:]+:\s*$`) - defaultRe := regexp.MustCompile(`^(\t+)default:\s*$`) + caseRe := cachedCompatibilityRegexp(`^(\t+)case [^:]+:\s*$`) + defaultRe := cachedCompatibilityRegexp(`^(\t+)default:\s*$`) // `.*` not `[^)]*`: ASM ClassReader uses nested parens (`switch ((buf[off]) & 255){`). - switchRe := regexp.MustCompile(`^(\t+)switch \(.*\)\{\s*$`) + switchRe := cachedCompatibilityRegexp(`^(\t+)switch \(.*\)\{\s*$`) type insert struct { at int indent string @@ -11214,7 +11320,7 @@ func addBreakToSwitchCases(body string) string { } // For each case (except the last which may be default), check if its body lacks a terminator // AND has at least one non-empty statement (skip empty fall-through cases). - terminatorRe := regexp.MustCompile(`\b(break|return|throw|continue)\b`) + terminatorRe := cachedCompatibilityRegexp(`\b(break|return|throw|continue)\b`) for ci, cs := range caseStarts { var nextCase int if ci+1 < len(caseStarts) { @@ -11467,10 +11573,8 @@ var tryReLiteral = regexp.MustCompile(`try\{`) // countAssignTargets counts how many times name appears as an assignment target (`name =` but not // `name ==`) in body. Used to detect multi-branch if/else chains. func countAssignTargets(body, name string) int { - re := regexp.MustCompile(`\b` + regexp.QuoteMeta(name) + `\b`) - locs := re.FindAllStringIndex(body, -1) count := 0 - for _, loc := range locs { + for _, loc := range utils.WordSpans(body, name, nil) { after := body[loc[1]:] afterTrim := strings.TrimLeft(after, " \t") if strings.HasPrefix(afterTrim, "=") && !strings.HasPrefix(afterTrim, "==") { @@ -11962,25 +12066,107 @@ func generatedLocalIsDeclared(body, name string) bool { // generatedLocalOccurrences counts whole-token references to a generated local name in body. func generatedLocalOccurrences(body, name string) int { - return len(regexp.MustCompile(`\b`+regexp.QuoteMeta(name)+`\b`).FindAllString(body, -1)) + return utils.WordCount(body, name) +} + +// numericLiteralAt reports whether body at i starts a numeric literal after +// optional whitespace, an optional '(', and an optional '-'. It is the literal +// scan equivalent of `\s*\(?-?\d`. +func numericLiteralAt(body string, i int) bool { + for i < len(body) && regexpSpaceByte(body[i]) { + i++ + } + if i < len(body) && body[i] == '(' { + i++ + } + if i < len(body) && body[i] == '-' { + i++ + } + return i < len(body) && body[i] >= '0' && body[i] <= '9' +} + +// generatedLocalIntSignals checks the five regexp patterns that prove an int +// category: post/prefix increment-decrement, a bare relational or numeric +// equality comparison, and an array index. Scanning avoids compiling and +// caching five distinct regexps per generated-local name. +// +// A bare RELATIONAL comparison (`(v) < n`) is numeric-only in Java -> int +// category for any right operand. A bare EQUALITY comparison (`(v) == X` / +// `(v) != X`) is also valid for REFERENCES, so it only proves int when the +// right operand is a numeric literal (`(0)`, `-1`). A reference comparison such +// as `(v) != (HashMap.class)` or `(v) != (var2)` must NOT be read as int, +// otherwise an `objectClass`-style local (fastjson2 +// JSONWriter.checkAndWriteTypeName, whose value is `(v = obj.getClass()) != +// type`) is mis-declared `int v = 0` and every Class comparison/use fails to +// recompile. +func generatedLocalIntSignals(body, name string) bool { + for _, loc := range utils.WordSpans(body, name, nil) { + i := loc[1] + for i < len(body) && regexpSpaceByte(body[i]) { + i++ + } + if strings.HasPrefix(body[i:], "++") || strings.HasPrefix(body[i:], "--") { + return true + } + j := loc[0] + for j > 0 && regexpSpaceByte(body[j-1]) { + j-- + } + if j >= 2 && (body[j-2:j] == "++" || body[j-2:j] == "--") { + return true + } + } + marker := "(" + name + ")" + for offset := 0; offset < len(body); { + rel := strings.Index(body[offset:], marker) + if rel < 0 { + break + } + start := offset + rel + i := start + len(marker) + for i < len(body) && regexpSpaceByte(body[i]) { + i++ + } + if i < len(body) { + if body[i] == '<' || body[i] == '>' { + return true + } + if i+1 < len(body) && body[i] == '=' && body[i+1] == '=' && numericLiteralAt(body, i+2) { + return true + } + if i+1 < len(body) && body[i] == '!' && body[i+1] == '=' && numericLiteralAt(body, i+2) { + return true + } + } + offset = start + 1 + } + for offset := 0; offset < len(body); { + rel := strings.IndexByte(body[offset:], '[') + if rel < 0 { + break + } + start := offset + rel + i := start + 1 + for i < len(body) && regexpSpaceByte(body[i]) { + i++ + } + if strings.HasPrefix(body[i:], name) { + i += len(name) + for i < len(body) && regexpSpaceByte(body[i]) { + i++ + } + if i < len(body) && body[i] == ']' { + return true + } + } + offset = start + 1 + } + return false } func generatedLocalLooksInt(body, name string) bool { - quoted := regexp.QuoteMeta(name) - patterns := []string{ - `\b` + quoted + `\s*(?:\+\+|--)`, - `(?:\+\+|--)\s*` + quoted + `\b`, - // A bare RELATIONAL comparison (`(v) < n`) is numeric-only in Java -> int category for - // any right operand. - `\(` + quoted + `\)\s*(?:<|>|<=|>=)`, - // A bare EQUALITY comparison (`(v) == X` / `(v) != X`) is also valid for REFERENCES, so it - // only proves int when the right operand is a numeric literal (`(0)`, `-1`). A reference - // comparison such as `(v) != (HashMap.class)` or `(v) != (var2)` must NOT be read as int, - // otherwise an `objectClass`-style local (fastjson2 JSONWriter.checkAndWriteTypeName, whose - // value is `(v = obj.getClass()) != type`) is mis-declared `int v = 0` and every Class - // comparison/use fails to recompile. - `\(` + quoted + `\)\s*(?:==|!=)\s*\(?-?\d`, - `\[\s*` + quoted + `\s*\]`, + if generatedLocalIntSignals(body, name) { + return true } // Embedded-assignment-in-condition form produced by the dup-collapse, e.g. // `(var4 = expr) == (0)` / `(var4 = expr) < (n)` (commons-codec Metaphone / @@ -12003,15 +12189,15 @@ func generatedLocalLooksInt(body, name string) bool { // call. The int-category guarantees are unchanged: a relational operator is numeric-only in // Java regardless of the RHS, and the equality form still requires a NUMERIC-LITERAL right // operand (`\(?-?\d`), so a reference null-check `(o = foo()) != null` is still NOT matched. + quoted := regexp.QuoteMeta(name) rhs := `[^()]*(?:\([^()]*\)[^()]*)*` - patterns = append(patterns, - `\(`+quoted+` = `+rhs+`\)\s*(?:<|>|<=|>=)`, - `\(`+quoted+` = `+rhs+`\)\s*(?:==|!=)\s*\(?-?\d`, - ) - } - for _, pattern := range patterns { - if regexp.MustCompile(pattern).MatchString(body) { - return true + for _, pattern := range []string{ + `\(` + quoted + ` = ` + rhs + `\)\s*(?:<|>|<=|>=)`, + `\(` + quoted + ` = ` + rhs + `\)\s*(?:==|!=)\s*\(?-?\d`, + } { + if cachedCompatibilityRegexp(pattern).MatchString(body) { + return true + } } } return false @@ -12051,7 +12237,7 @@ func embeddedAssignRHS(body, name string) (string, bool) { // `T[]... arr` declaration from text, or "" when none is found. For a multi-dimensional array it // strips exactly one dimension (String[][] arr -> String[]). func declaredArrayElementType(text, arr string) string { - re := regexp.MustCompile(`\b([A-Za-z_$][A-Za-z0-9_$.<>?,]*)\s*((?:\[\s*\])+)\s+` + regexp.QuoteMeta(arr) + `\b`) + re := cachedCompatibilityRegexp(`\b([A-Za-z_$][A-Za-z0-9_$.<>?,]*)\s*((?:\[\s*\])+)\s+` + regexp.QuoteMeta(arr) + `\b`) m := re.FindStringSubmatch(text) if m == nil { return "" @@ -12069,7 +12255,7 @@ func declaredArrayElementType(text, arr string) string { // requirement distinguishes a method DEFINITION from a call site (`return method(...)` has no brace), // and a leading `.` rules out an instance-call spelled `recv.method(`. func declaredMethodReturnType(body, method string) string { - re := regexp.MustCompile(`(?:^|[^.\w$])([A-Za-z_$][A-Za-z0-9_$.<>?,\[\]]*)\s+` + regexp.QuoteMeta(method) + `\s*\([^;{}]*\)\s*\{`) + re := cachedCompatibilityRegexp(`(?:^|[^.\w$])([A-Za-z_$][A-Za-z0-9_$.<>?,\[\]]*)\s+` + regexp.QuoteMeta(method) + `\s*\([^;{}]*\)\s*\{`) for _, m := range re.FindAllStringSubmatch(body, -1) { ret := m[1] switch ret { @@ -12110,7 +12296,7 @@ func returnedLocalDeclType(body, name, methodReturnType string, enabled bool) st if castEscapeScalarPrimitives[methodReturnType] { return "" } - if !regexp.MustCompile(`\breturn\s+` + regexp.QuoteMeta(name) + `\b`).MatchString(body) { + if !cachedCompatibilityRegexp(`\breturn\s+` + regexp.QuoteMeta(name) + `\b`).MatchString(body) { return "" } return methodReturnType @@ -12410,6 +12596,10 @@ func canFlattenNoCatchTry(body string, malformed bool, state *class_context.Sour // Tab()/UnTab() pair, which leaves the indentation stack unbalanced if it panics midway; // we rewind it here. func (c *ClassObjectDumper) safeDumpMethod(name, descriptor string) (res *dumpedMethods, err error) { + return c.safeDumpMethodMember(nil, name, descriptor) +} + +func (c *ClassObjectDumper) safeDumpMethodMember(method *MemberInfo, name, descriptor string) (res *dumpedMethods, err error) { tabSaved := c.deepStack.Len() defer func() { if rec := recover(); rec != nil { @@ -12423,7 +12613,10 @@ func (c *ClassObjectDumper) safeDumpMethod(name, descriptor string) (res *dumped c.deepStack.Pop() } }() - return c.DumpMethod(name, descriptor) + if method == nil { + return c.DumpMethod(name, descriptor) + } + return c.dumpMethodMemberWithSourceRequest(method, name, descriptor, utils2.NewRootVariableId(), nil, methodSourceRequest{role: methodSourceDeclaration}) } // aggressiveRedumpMethod re-decompiles a SINGLE method in aggressive mode. It is the gated retry at @@ -12974,7 +13167,7 @@ func (c *ClassObjectDumper) DumpMethods() ([]*dumpedMethods, error) { } } if res == nil { - res, err = c.safeDumpMethod(name, descriptor) + res, err = c.safeDumpMethodMember(method, name, descriptor) } applyLeakedExceptionSentinel(res) if err == nil && res != nil && name == "" && c.isInterfaceLike() && isIgnorableAssertionOnlyClinit(res.code) { diff --git a/classparser/fs.go b/classparser/fs.go index 3f83bf5d..1969b9b5 100644 --- a/classparser/fs.go +++ b/classparser/fs.go @@ -2,8 +2,9 @@ package javaclassparser import ( "bytes" + "context" + "errors" "fmt" - "github.com/yaklang/javajive/internal/jdecenv" "io/fs" "os" "path" @@ -14,8 +15,11 @@ import ( "github.com/yaklang/javajive/internal/filesys" fi "github.com/yaklang/javajive/internal/filesys/filesys_interface" + "github.com/yaklang/javajive/internal/inputkind" + "github.com/yaklang/javajive/internal/jdecenv" "github.com/yaklang/javajive/internal/memfile" "github.com/yaklang/javajive/internal/utils" + "github.com/yaklang/javajive/internal/workbudget" ) type JarFS struct { @@ -68,6 +72,27 @@ var _ fs.FS = (*JarFS)(nil) var _ fs.ReadFileFS = (*JarFS)(nil) var _ fs.ReadDirFS = (*JarFS)(nil) +// ClassDecompileStatus describes one archive class-entry recovery attempt. +// Fallback is a contained class-level failure represented by diagnostic source; +// request resource and cancellation failures are returned as errors instead. +type ClassDecompileStatus string + +const ( + ClassDecompileComplete ClassDecompileStatus = "complete" + ClassDecompilePartial ClassDecompileStatus = "partial" + ClassDecompileFallback ClassDecompileStatus = "fallback" +) + +// ClassDecompileOutcome is the typed result at the JarFS class-entry boundary. +// Source preserves the historical ReadFile bytes, while StubMethods and +// Diagnostics expose degradation evidence to structured archive exporters. +type ClassDecompileOutcome struct { + Source []byte + Status ClassDecompileStatus + StubMethods []string + Diagnostics []DecompileDiagnostic +} + func NewJarFSFromLocal(path string) (*JarFS, error) { return NewJarFSFromLocalWithResolver(path, nil) } @@ -155,63 +180,94 @@ func NewJarFSWithOptions(zipFs *filesys.ZipFS, recursiveParse bool) *JarFS { } } -// decompileClassBytes decompiles a single .class entry from this jar. Beyond the per-class Dump it -// performs enum constant-body CROSS-CLASS folding (Bug V): javac lowers each constant-specific body -// `CONST { ...body... }` into a synthetic `Outer$N` subclass (ACC_ENUM, `extends Outer`). Decompiled -// per class that is uncompilable two ways -- the outer enum's constants do not override its abstract -// methods, and each `Outer$N` renders as illegal `class Outer$N extends `. Here, with the whole -// jar in hand, we (a) when decompiling the OUTER enum, inline each `Outer$N` body back into its -// constant via a sibling resolver over the zip, and (b) when decompiling a synthetic `Outer$N` itself, -// emit only a suppression marker -- its body now lives in the enum and javac regenerates the real -// `Outer$N.class` from the folded enum source on recompile. Gated by JDEC_NO_ENUM_FOLD so it can be -// disabled for load-bearing regression and to fall back to the exact per-class behavior. -func (z *JarFS) decompileClassBytes(name string, data []byte) []byte { +// decompileClassOutcome decompiles a single .class entry from this jar and +// contains class-level failures. Beyond the per-class Dump it performs enum +// constant-body CROSS-CLASS folding (Bug V): javac lowers each constant-specific +// body `CONST { ...body... }` into a synthetic `Outer$N` subclass (ACC_ENUM, +// `extends Outer`). Decompiled per class that is uncompilable two ways -- the +// outer enum's constants do not override its abstract methods, and each +// `Outer$N` renders as illegal `class Outer$N extends `. Here, with the +// whole jar in hand, we (a) when decompiling the OUTER enum, inline each +// `Outer$N` body back into its constant via a sibling resolver over the zip, and +// (b) when decompiling a synthetic `Outer$N` itself, emit only a suppression +// marker -- its body now lives in the enum and javac regenerates the real +// `Outer$N.class` from the folded enum source on recompile. Gated by +// JDEC_NO_ENUM_FOLD so it can be disabled for load-bearing regression and to +// fall back to the exact per-class behavior. +func (z *JarFS) decompileClassOutcome(name string, data []byte) (outcome ClassDecompileOutcome, err error) { if _, bound := jdecenv.Current(); !bound { - var out []byte - _ = jdecenv.Run(jdecenv.CaptureProcess(), func() error { - out = z.decompileClassBytes(name, data) - return nil + err = jdecenv.Run(jdecenv.CaptureProcess(), func() error { + var inner error + outcome, inner = z.decompileClassOutcome(name, data) + return inner }) - return out + return outcome, err + } + var work *workbudget.Budget + decompile := func() (ClassDecompileOutcome, error) { + return z.decompileClassOutcomeBound(name, data, &work) } + return z.containClassDecompile(name, &work, decompile) +} + +func (z *JarFS) decompileClassOutcomeBound(name string, data []byte, work **workbudget.Budget) (ClassDecompileOutcome, error) { lower := strings.ToLower(name) if !strings.HasSuffix(lower, ".class") && !strings.HasSuffix(lower, ".raw") { - return data + return ClassDecompileOutcome{Source: data, Status: ClassDecompileComplete}, nil } if strings.HasSuffix(lower, ".raw") && (len(data) < 4 || data[0] != 0xca || data[1] != 0xfe || data[2] != 0xba || data[3] != 0xbe) { - return data + return ClassDecompileOutcome{Source: data, Status: ClassDecompileComplete}, nil } - cf, err := Parse(data) + if z.archive != nil && z.archive.budget != nil { + *work = z.archive.budget.Work() + } + cf, err := ParseWithBudget(data, *work) if err != nil { - return []byte(fmt.Sprintf("// decompile parse failed for %s: %v\n", name, err)) + if isClassResourceError(err) { + return ClassDecompileOutcome{}, err + } + message := sanitizeClassText(err.Error()) + return ClassDecompileOutcome{ + Source: []byte(fmt.Sprintf("// decompile parse failed for %s: %s\n", sanitizeClassText(name), message)), + Status: ClassDecompileFallback, + Diagnostics: []DecompileDiagnostic{{ + Code: "class_parse_failed", + Message: message, + }}, + }, nil + } + if err := ValidateSupportedClassMajor(cf.MajorVersion); err != nil { + return classFallbackOutcome(name, "unsupported_classfile_version", err.Error()), nil } if jdecenv.Get("JDEC_NO_ENUM_FOLD") == "" { if isSyntheticEnumConstantSubclass(cf) { - return []byte(fmt.Sprintf( + return ClassDecompileOutcome{Source: []byte(fmt.Sprintf( "// %s: synthetic enum constant-body subclass folded into enum %s (regenerated by javac on recompile)\n", strings.ReplaceAll(cf.GetClassName(), "/", "."), - strings.ReplaceAll(cf.GetSupperClassName(), "/", "."))) + strings.ReplaceAll(cf.GetSupperClassName(), "/", "."))), Status: ClassDecompileComplete}, nil } } if release, logical, known := physicalClassNamespace(name); known && logical == cf.GetClassName()+".class" { if view := z.sourceReleaseView(release); view != nil { - return view.decompileClassBytes(logical, data) + return view.decompileClassOutcome(logical, data) } } if path.Clean(name) == cf.GetClassName()+".class" { if source, owned := z.nativeMemberSource(cf); owned { z.noteNativeConstructorSource(cf, source) - return source + return ClassDecompileOutcome{Source: source, Status: ClassDecompileComplete}, nil } if source, owned := z.nativeAnonymousSource(cf); owned { z.noteNativeConstructorSource(cf, source) - return source + return ClassDecompileOutcome{Source: source, Status: ClassDecompileComplete}, nil } } // Supply original sibling bytes for certified source ownership and enum // constant-body reconstruction. Enum-switch syntax requires its original // typed protocol; a mapping-looking source fragment grants no permission. d := NewClassObjectDumper(cf) + report := DecompileResult{Members: newMemberLedger(cf)} + d.report = &report d.options.TargetSourceVersion = z.targetSourceVersion d.options.MaxAnalysisUpdates = z.maxAnalysisUpdates d.options.SourceCompiler = z.sourceCompiler @@ -232,11 +288,106 @@ func (z *JarFS) decompileClassBytes(name string, data []byte) []byte { if d.Work == nil { d.Work = largeMethodWorkBudget(z.maxAnalysisUpdates) } + *work = d.Work source, err := d.DumpClass() if err != nil { - return []byte(fmt.Sprintf("// decompile dump failed for %s: %v\n", name, err)) + if isClassResourceError(err) { + return ClassDecompileOutcome{}, err + } + message := sanitizeClassText(err.Error()) + report.Diagnostics = append(report.Diagnostics, DecompileDiagnostic{Code: "class_decompile_failed", Message: message}) + return ClassDecompileOutcome{ + Source: []byte(fmt.Sprintf("// decompile dump failed for %s: %s\n", sanitizeClassText(name), message)), + Status: ClassDecompileFallback, + StubMethods: report.StubMethods, + Diagnostics: report.Diagnostics, + }, nil + } + if resourceErr := z.classResourceError(d.Work); resourceErr != nil { + return ClassDecompileOutcome{}, resourceErr + } + status := ClassDecompileComplete + if len(report.StubMethods) > 0 || d.typeAnnosUnsupported || d.enumParameterMetadataUnsupported { + status = ClassDecompilePartial } - return []byte(source) + return ClassDecompileOutcome{ + Source: []byte(source), + Status: status, + StubMethods: report.StubMethods, + Diagnostics: report.Diagnostics, + }, nil +} + +func (z *JarFS) containClassDecompile(name string, work **workbudget.Budget, decompile func() (ClassDecompileOutcome, error)) (outcome ClassDecompileOutcome, err error) { + defer func() { + if recovered := recover(); recovered != nil { + var current *workbudget.Budget + if work != nil { + current = *work + } + if resourceErr := z.classResourceError(current); resourceErr != nil { + outcome = ClassDecompileOutcome{} + err = resourceErr + return + } + message := fmt.Sprintf("decompile panic: %v", recovered) + outcome = classFallbackOutcome(name, "class_decompile_panic", message) + err = nil + } + }() + return decompile() +} + +func (z *JarFS) classResourceError(work *workbudget.Budget) error { + if work != nil && work.Err() != nil { + return work.Err() + } + if z != nil && z.archive != nil { + if z.archive.budget != nil && z.archive.budget.Err() != nil { + return z.archive.budget.Err() + } + if z.archive.ctx != nil && z.archive.ctx.Err() != nil { + return z.archive.ctx.Err() + } + } + return nil +} + +func classFallbackOutcome(name, code, message string) ClassDecompileOutcome { + message = sanitizeClassText(message) + return ClassDecompileOutcome{ + Source: []byte(fmt.Sprintf("// decompile fallback for %s: %s\n", sanitizeClassText(name), message)), + Status: ClassDecompileFallback, + Diagnostics: []DecompileDiagnostic{{ + Code: code, + Message: message, + }}, + } +} + +// sanitizeClassText keeps fallback comments on one line and bounds external +// diagnostic text so malformed names or errors cannot inject source lines. +func sanitizeClassText(text string) string { + runes := []rune(text) + out := make([]rune, 0, len(runes)) + for _, r := range runes { + if r == '\n' || r == '\r' || r < 0x20 || r == 0x7f { + r = ' ' + } + out = append(out, r) + if len(out) == 480 { + break + } + } + return strings.TrimSpace(string(out)) +} + +func isClassResourceError(err error) bool { + if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { + return true + } + var budgetErr *workbudget.Error + return errors.As(err, &budgetErr) && budgetErr.Kind != workbudget.KindBudget } // enumSiblingResolver resolves a sibling class's RAW bytes by binary internal name (slash form, e.g. @@ -255,11 +406,58 @@ func (z *JarFS) ReadFile(name string) ([]byte, error) { if isArchivePath(name) { return z.readFileFromJar(name) } - data, err := z.readJarEntry(name) + outcome, err := z.ReadClassOutcome(name) if err != nil { return nil, err } - return z.decompileClassBytes(name, data), nil + return outcome.Source, nil +} + +// ReadClassOutcome reads and decompiles one archive entry with typed +// class-level degradation evidence. Non-class entries are returned complete. +func (z *JarFS) ReadClassOutcome(name string) (ClassDecompileOutcome, error) { + if isArchivePath(name) { + jarPath, internalPath, ok := parseArchivePath(name) + if !ok { + return ClassDecompileOutcome{}, os.ErrNotExist + } + unifiedFS, err := z.getNestedJarFS(jarPath) + if err != nil { + return ClassDecompileOutcome{}, err + } + nested, ok := unifiedFS.GetFileSystem().(*JarFS) + if !ok { + return ClassDecompileOutcome{}, fmt.Errorf("nested archive %q is not a JarFS", jarPath) + } + return nested.ReadClassOutcome(internalPath) + } + data, err := z.readJarEntry(name) + if err != nil { + return ClassDecompileOutcome{}, err + } + return z.decompileClassOutcome(name, data) +} + +// ReadRawFile returns the original bytes for name without decompiling class +// entries. Nested archive paths such as "WEB-INF/lib/dep.jar/Foo.class" are +// resolved through every archive layer. +func (z *JarFS) ReadRawFile(name string) ([]byte, error) { + if isArchivePath(name) { + jarPath, internalPath, ok := parseArchivePath(name) + if !ok { + return nil, os.ErrNotExist + } + unifiedFS, err := z.getNestedJarFS(jarPath) + if err != nil { + return nil, err + } + nested, ok := unifiedFS.GetFileSystem().(*JarFS) + if !ok { + return nil, fmt.Errorf("nested archive %q is not a JarFS", jarPath) + } + return nested.ReadRawFile(internalPath) + } + return z.readJarEntry(name) } func (f *JarFS) OpenFile(name string, flag int, perm os.FileMode) (fs.File, error) { @@ -271,7 +469,11 @@ func (z *JarFS) Open(name string) (fs.File, error) { if err != nil { return nil, err } - return memfile.New(z.decompileClassBytes(name, raw)), nil + outcome, err := z.decompileClassOutcome(name, raw) + if err != nil { + return nil, err + } + return memfile.New(outcome.Source), nil } func (z *JarFS) Stat(name string) (fs.FileInfo, error) { @@ -301,8 +503,8 @@ func (z *JarFS) Stat(name string) (fs.FileInfo, error) { } var ( - archiveFileSuffixes = []string{".jar", ".war", ".ear", ".par", ".zip"} - jarLikeArchiveSuffixes = []string{".jar", ".war", ".ear", ".par"} + archiveFileSuffixes = []string{".jar", ".war", ".ear", ".aar", ".par", ".jmod", ".zip"} + jarLikeArchiveSuffixes = []string{".jar", ".war", ".ear", ".aar", ".par", ".jmod"} ) func isArchiveFile(path string) bool { @@ -393,6 +595,29 @@ func normalizeArchivePath(name string) string { return name } +// GetNestedJarFS returns a cached nested archive filesystem. The returned JarFS +// is owned by the outer JarFS and must not be closed independently. +func (z *JarFS) GetNestedJarFS(jarPath string) (*JarFS, error) { + unified, err := z.getNestedJarFS(jarPath) + if err != nil { + return nil, err + } + nested, ok := unified.GetFileSystem().(*JarFS) + if !ok || nested == nil { + return nil, fmt.Errorf("nested archive %q is not a JarFS", jarPath) + } + return nested, nil +} + +// Close releases the outer archive handle. Nested archives are memory-backed +// views owned by this JarFS and do not hold independent file descriptors. +func (z *JarFS) Close() error { + if z == nil || z.ZipFS == nil { + return nil + } + return z.ZipFS.Close() +} + func (z *JarFS) getNestedJarFS(jarPath string) (*filesys.UnifiedFS, error) { if _, err := z.boundJarReleaseSelection(); err != nil { return nil, err @@ -415,6 +640,7 @@ func (z *JarFS) getNestedJarFS(jarPath string) (*filesys.UnifiedFS, error) { if err != nil { return nil, utils.Wrapf(err, "failed to read jar file: %s", jarPath) } + jarContent = inputkind.StripJMODHeader(jarContent) nestedZipFS, err := filesys.NewZipFSRawWithOptions(bytes.NewReader(jarContent), int64(len(jarContent)), z.nestedZipFSOptions()...) if err != nil { @@ -588,6 +814,7 @@ func (e *ExpandedZipFS) GetJarFS(jarPath string) (*filesys.UnifiedFS, error) { if err != nil { return nil, utils.Wrapf(err, "failed to read jar file: %s", jarPath) } + jarContent = inputkind.StripJMODHeader(jarContent) zipFS, err := filesys.NewZipFSRawWithOptions(bytes.NewReader(jarContent), int64(len(jarContent)), e.nestedZipFSOptions()...) if err != nil { @@ -630,6 +857,7 @@ func (e *ExpandedZipFS) getZipFS(zipPath string) (*filesys.ZipFS, error) { if err != nil { return nil, utils.Wrapf(err, "failed to read zip file: %s", zipPath) } + zipContent = inputkind.StripJMODHeader(zipContent) nestedZipFS, err := filesys.NewZipFSRawWithOptions(bytes.NewReader(zipContent), int64(len(zipContent)), e.nestedZipFSOptions()...) if err != nil { diff --git a/classparser/fuzz_test.go b/classparser/fuzz_test.go new file mode 100644 index 00000000..60577350 --- /dev/null +++ b/classparser/fuzz_test.go @@ -0,0 +1,44 @@ +package javaclassparser + +import ( + "context" + "os" + "testing" +) + +func FuzzDecompileWithLimitsNeverPanics(f *testing.F) { + f.Add([]byte{}) + f.Add([]byte{0xca, 0xfe, 0xba, 0xbe}) + f.Add(readValidationSeedForFuzz()) + f.Fuzz(func(t *testing.T, data []byte) { + if len(data) > 1<<20 { + t.Skip() + } + options := DecompileOptions{ + Mode: Precision, + Context: context.Background(), + Limits: Limits{ + MaxInputBytes: 1 << 20, + MaxReadBytes: 2 << 20, + MaxParseItems: 1 << 16, + MaxOutputBytes: 2 << 20, + MaxDiagnostics: 64, + MaxRequestWork: 4 << 20, + }, + EnvSnapshot: map[string]string{}, + } + first, firstErr := DecompileWithOptions(data, options) + second, secondErr := DecompileWithOptions(data, options) + if first.Status != second.Status || (firstErr == nil) != (secondErr == nil) { + t.Fatalf("nondeterministic status: %q/%v versus %q/%v", first.Status, firstErr, second.Status, secondErr) + } + if len(first.Source) > 2<<20 || len(first.Diagnostics) > 64 { + t.Fatalf("unbounded result: source=%d diagnostics=%d", len(first.Source), len(first.Diagnostics)) + } + }) +} + +func readValidationSeedForFuzz() []byte { + data, _ := os.ReadFile(validationSeedClass) + return data +} diff --git a/classparser/input_validation_test.go b/classparser/input_validation_test.go index 3b32ffef..fd3b7da6 100644 --- a/classparser/input_validation_test.go +++ b/classparser/input_validation_test.go @@ -19,6 +19,42 @@ func readValidationSeed(t *testing.T) []byte { return raw } +func TestDecompileClassfileMinorPolicy(t *testing.T) { + seed := readValidationSeed(t) + tests := []struct { + name string + major uint16 + minor uint16 + status string + code string + }{ + {name: "java8 illegal minor", major: 52, minor: 1, status: "invalid_input", code: "invalid_classfile_version"}, + {name: "java12 preview", major: 56, minor: 0xffff, status: "unsupported", code: "unsupported_classfile_preview"}, + {name: "legacy valid", major: 45, minor: 3}, + {name: "legacy illegal", major: 45, minor: 4, status: "invalid_input", code: "invalid_classfile_version"}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + raw := append([]byte(nil), seed...) + binary.BigEndian.PutUint16(raw[4:6], test.minor) + binary.BigEndian.PutUint16(raw[6:8], test.major) + if _, err := Parse(raw); err != nil { + t.Fatalf("Parse rejected inspectable version: %v", err) + } + result, err := DecompileWithOptions(raw, DecompileOptions{Mode: Precision, EnvSnapshot: map[string]string{}}) + if test.code == "" { + if err != nil { + t.Fatalf("valid version rejected: %v", err) + } + return + } + if err == nil || result.Status != test.status || !strings.Contains(err.Error(), test.code) { + t.Fatalf("status=%s err=%v, want %s/%s", result.Status, err, test.status, test.code) + } + }) + } +} + func TestDecompileRejectsUnsupportedClassfileMajor(t *testing.T) { seed := readValidationSeed(t) for _, major := range []uint16{0, 1, 44, 45, 49, 52, 65, 66, 99, 255} { diff --git a/classparser/jarwar/exports.go b/classparser/jarwar/exports.go index 9e89a952..7ffd6468 100644 --- a/classparser/jarwar/exports.go +++ b/classparser/jarwar/exports.go @@ -7,7 +7,10 @@ import ( "strings" "github.com/yaklang/javajive/classparser" + "github.com/yaklang/javajive/internal/filesys" + "github.com/yaklang/javajive/internal/inputkind" "github.com/yaklang/javajive/internal/utils" + "github.com/yaklang/javajive/jimage" ) // ArchiveOptions controls archive decompilation. Structured keeps original @@ -30,11 +33,14 @@ type DecompileArchiveOptions = ArchiveOptions // ArchiveEntryReport records one deterministic structured-export output. // Paths are slash-separated and relative to the destination directory. type ArchiveEntryReport struct { - Kind string `json:"kind"` - SourcePath string `json:"source_path"` - OutputPath string `json:"output_path"` - Archive string `json:"archive,omitempty"` - Size int64 `json:"size"` + Kind string `json:"kind"` + SourcePath string `json:"source_path"` + OutputPath string `json:"output_path"` + Archive string `json:"archive,omitempty"` + Size int64 `json:"size"` + Status javaclassparser.ClassDecompileStatus `json:"status,omitempty"` + StubMethods []string `json:"stub_methods,omitempty"` + Diagnostics []javaclassparser.DecompileDiagnostic `json:"diagnostics,omitempty"` } // NestedArchiveReport records the provenance and preserved bytes of a nested @@ -84,19 +90,41 @@ func AutoDecompileWithAnalysisBudget(from, to string, maxAnalysisUpdates int) er if maxAnalysisUpdates < 0 { return fmt.Errorf("negative analysis budget: %d", maxAnalysisUpdates) } - return autoDecompileFlat(from, to, maxAnalysisUpdates) + if isJImage(from) { + _, err := decompileJImageWithOptions(from, to, ArchiveOptions{MaxAnalysisUpdates: maxAnalysisUpdates}) + return err + } + return autoDecompileFlat(from, to, ArchiveOptions{MaxAnalysisUpdates: maxAnalysisUpdates}) } // autoDecompileFlat writes the historical flat directory layout. -func autoDecompileFlat(from, to string, maxAnalysisUpdates int) error { +func autoDecompileFlat(from, to string, options ArchiveOptions) error { fromLower := strings.ToLower(from) switch { case strings.HasSuffix(fromLower, ".jar"), strings.HasSuffix(fromLower, ".war"), - strings.HasSuffix(fromLower, ".ear"), strings.HasSuffix(fromLower, ".zip"): - jar, err := NewWithAnalysisBudget(from, maxAnalysisUpdates) + strings.HasSuffix(fromLower, ".ear"), strings.HasSuffix(fromLower, ".aar"), + strings.HasSuffix(fromLower, ".par"), strings.HasSuffix(fromLower, ".jmod"), + strings.HasSuffix(fromLower, ".zip"): + archiveOptions := javaclassparser.ArchiveOptionsFrom(javaclassparser.DecompileOptions{ + Context: options.Context, + Limits: options.Limits, + Work: options.Work, + TargetRelease: options.TargetRelease, + }) + if err := archiveOptions.Work.CheckContext(options.Context); err != nil { + return err + } + zipFS, err := filesys.NewZipFSFromLocalWithOptions(from, filesys.WithArchiveOptions(archiveOptions)) if err != nil { return utils.Errorf("create archive failed: %v", err) } + decompiler := javaclassparser.NewJarFS(zipFS) + decompiler.SetAnalysisBudget(options.MaxAnalysisUpdates) + jar, err := NewFromJarFS(decompiler) + if err != nil { + _ = zipFS.Close() + return utils.Errorf("create archive failed: %v", err) + } defer jar.Close() return jar.DumpToLocalFileSystem(to) case strings.HasSuffix(fromLower, ".class"): @@ -105,10 +133,14 @@ func autoDecompileFlat(from, to string, maxAnalysisUpdates int) error { return utils.Errorf("read class file failed: %v", err) } var decompiled string - if maxAnalysisUpdates > 0 { + if options.Context != nil || options.Work != nil || options.Limits != (javaclassparser.Limits{}) || options.TargetRelease != 0 || options.MaxAnalysisUpdates > 0 { result, derr := javaclassparser.DecompileWithOptions(raw, javaclassparser.DecompileOptions{ Mode: javaclassparser.Compatibility, - MaxAnalysisUpdates: maxAnalysisUpdates, + Context: options.Context, + Limits: options.Limits, + Work: options.Work, + TargetRelease: options.TargetRelease, + MaxAnalysisUpdates: options.MaxAnalysisUpdates, }) if derr != nil { return utils.Errorf("decompile class failed: %v", derr) @@ -148,8 +180,41 @@ func AutoDecompileWithOptions(from, to string, options ArchiveOptions) (ArchiveR if options.MaxAnalysisUpdates < 0 { return ArchiveReport{}, fmt.Errorf("negative analysis budget: %d", options.MaxAnalysisUpdates) } + if isJImage(from) { + return decompileJImageWithOptions(from, to, options) + } if !options.Structured { - return ArchiveReport{}, autoDecompileFlat(from, to, options.MaxAnalysisUpdates) + return ArchiveReport{}, autoDecompileFlat(from, to, options) } return decompileArchiveStructured(from, to, options) } + +func isJImage(path string) bool { + kind, err := inputkind.DetectFile(path) + return err == nil && kind == inputkind.JIMAGE +} + +// decompileJImageWithOptions converts a JDK runtime image into a private +// package-layout JAR and reuses the normal flat or structured archive exporter. +func decompileJImageWithOptions(from, to string, options ArchiveOptions) (ArchiveReport, error) { + reader, err := jimage.OpenFile(from) + if err != nil { + return ArchiveReport{}, fmt.Errorf("open JImage %q: %w", from, err) + } + defer reader.Close() + + temp, err := os.CreateTemp("", "javajive-jimage-*.jar") + if err != nil { + return ArchiveReport{}, err + } + tempName := temp.Name() + defer os.Remove(tempName) + if err := reader.WriteZIP(temp); err != nil { + _ = temp.Close() + return ArchiveReport{}, fmt.Errorf("convert JImage %q: %w", from, err) + } + if err := temp.Close(); err != nil { + return ArchiveReport{}, fmt.Errorf("close converted JImage %q: %w", from, err) + } + return AutoDecompileWithOptions(tempName, to, options) +} diff --git a/classparser/jarwar/jarwar.go b/classparser/jarwar/jarwar.go index 26f64518..0c451239 100644 --- a/classparser/jarwar/jarwar.go +++ b/classparser/jarwar/jarwar.go @@ -2,7 +2,6 @@ package jarwar import ( "fmt" - "io/fs" "os" "path/filepath" "strings" @@ -65,6 +64,9 @@ func NewWithAnalysisBudget(compressedFile string, maxAnalysisUpdates int) (*JarW if utils.GetFirstExistedFile(compressedFile) == "" { return nil, fmt.Errorf("file not existed: %s", compressedFile) } + if isJImage(compressedFile) { + return nil, fmt.Errorf("JImage input is supported by AutoDecompile/DecompileArchive, not New: %s", compressedFile) + } fs, err := javaclassparser.NewJarFSFromLocalWithAnalysisBudget(compressedFile, 0, maxAnalysisUpdates, nil) if err != nil { return nil, utils.Wrap(err, "failed to create jar fs") @@ -98,62 +100,94 @@ func (j *JarWar) DumpToLocalFileSystem(dir string) error { } } - err := filesys.Recursive(".", filesys.WithFileSystem(j.fs), filesys.WithStat(func(isDir bool, s string, info fs.FileInfo) error { - target, err := SafeJoin(dir, s) - if err != nil { - return err + if err := j.dumpDirectory(dir, "."); err != nil { + return fmt.Errorf("archive file system dump failed: %w", err) + } + return nil +} + +func (j *JarWar) dumpDirectory(root, directory string) error { + entries, err := j.fs.ReadDir(directory) + if err != nil { + return fmt.Errorf("read archive directory %q: %w", directory, err) + } + for _, entry := range entries { + entryPath := filepath.ToSlash(filepath.Join(directory, entry.Name())) + info, statErr := j.fs.Stat(entryPath) + if statErr != nil { + return fmt.Errorf("stat archive entry %q: %w", entryPath, statErr) } - if isDir { - err := os.MkdirAll(target, 0755) - if err != nil { - log.Warnf("os.MkdirAll failed: %v", err) - return err + if info.IsDir() { + target, joinErr := SafeJoin(root, entryPath) + if joinErr != nil { + return fmt.Errorf("resolve archive directory %q: %w", entryPath, joinErr) } - return nil - } - - if filepath.Ext(s) == ".class" { - // 尝试反编译.class文件 - originalRaw, err := j.fs.ZipFS.ReadFile(s) - if err != nil { - log.Warnf("ReadFile failed: %v", err) - return utils.Wrap(err, "ReadFile failed during decompilation") + if mkdirErr := os.MkdirAll(target, 0o755); mkdirErr != nil { + return fmt.Errorf("create archive directory %q: %w", entryPath, mkdirErr) } - originalSize := len(originalRaw) - - decompiled, err := j.fs.ReadFile(s) - if err != nil { - log.Warnf("Decompile failed, keep original(%v): %v", s, err) - // 保存反编译失败的文件(带锁去重) - j.failedFilesLock.Lock() - j.failedDecompiledFiles[s] = struct{}{} - j.failedFilesLock.Unlock() - return os.WriteFile(target, originalRaw, 0755) + if walkErr := j.dumpDirectory(root, entryPath); walkErr != nil { + return walkErr } + continue + } + if err := j.dumpFile(root, entryPath); err != nil { + return err + } + } + return nil +} - lines := strings.Count(string(decompiled), "\n") + 1 - log.Infof("Decompiled [%v] - Original size: %d bytes, Decompiled size: %d bytes, Lines of code: %d", - s, originalSize, len(decompiled), lines) +func (j *JarWar) dumpFile(root, visiblePath string) error { + entryPath := visiblePath + if filepath.Ext(entryPath) == ".java" { + if _, err := j.fs.ReadRawFile(entryPath); err != nil { + entryPath = strings.TrimSuffix(entryPath, ".java") + ".class" + } + } - javaName := strings.TrimSuffix(s, ".class") + ".java" - javaTarget, joinErr := SafeJoin(dir, javaName) - if joinErr != nil { - return joinErr - } - return os.WriteFile(javaTarget, decompiled, 0755) - } else { - // 非.class文件,保持原样 - raw, err := j.fs.ZipFS.ReadFile(s) - if err != nil { - log.Warnf("ReadFile failed: %v", err) - return err - } - return os.WriteFile(target, raw, 0755) + if filepath.Ext(entryPath) == ".class" { + originalRaw, err := j.fs.ReadRawFile(entryPath) + if err != nil { + return fmt.Errorf("read archive entry %q: %w", entryPath, err) + } + decompiled, err := j.fs.ReadFile(entryPath) + if err != nil { + j.failedFilesLock.Lock() + j.failedDecompiledFiles[visiblePath] = struct{}{} + j.failedFilesLock.Unlock() + return fmt.Errorf("decompile archive entry %q: %w", entryPath, err) + } + javaName := strings.TrimSuffix(entryPath, ".class") + ".java" + if err := writeFlatFile(root, javaName, decompiled); err != nil { + return fmt.Errorf("write archive entry %q: %w", entryPath, err) } - })) + lines := strings.Count(string(decompiled), "\n") + 1 + log.Infof("Decompiled [%v] - Original size: %d bytes, Decompiled size: %d bytes, Lines of code: %d", + visiblePath, len(originalRaw), len(decompiled), lines) + return nil + } + raw, err := j.fs.ReadRawFile(entryPath) if err != nil { - return utils.Wrap(err, "Recursive file system dump failed") + return fmt.Errorf("read archive entry %q: %w", entryPath, err) + } + if err := writeFlatFile(root, visiblePath, raw); err != nil { + return fmt.Errorf("write archive entry %q: %w", entryPath, err) } return nil } + +func writeFlatFile(root, name string, data []byte) error { + target, err := SafeJoin(root, name) + if err != nil { + return err + } + parent, err := SafeJoin(root, filepath.ToSlash(filepath.Dir(name))) + if err != nil { + return err + } + if err := os.MkdirAll(parent, 0o755); err != nil { + return err + } + return os.WriteFile(target, data, 0o644) +} diff --git a/classparser/jarwar/structured.go b/classparser/jarwar/structured.go index a7afb795..4dba19bc 100644 --- a/classparser/jarwar/structured.go +++ b/classparser/jarwar/structured.go @@ -3,7 +3,6 @@ package jarwar import ( "bytes" "fmt" - "io/fs" "os" "path" "sort" @@ -11,6 +10,7 @@ import ( javaclassparser "github.com/yaklang/javajive/classparser" "github.com/yaklang/javajive/internal/filesys" + "github.com/yaklang/javajive/internal/inputkind" ) const ( @@ -47,7 +47,7 @@ func decompileArchiveStructured(from, to string, options ArchiveOptions) (Archiv } var report ArchiveReport - exportErr := exportStructuredArchive(to, zipFS, decompiler, "", 0, &report) + exportErr := exportStructuredArchive(to, zipFS, decompiler, "", 0, options.MaxAnalysisUpdates, &report) closeErr := decompilerOwner.Close() if exportErr != nil { return ArchiveReport{}, exportErr @@ -96,11 +96,11 @@ func prepareStructuredRoot(root string) error { return nil } -func exportStructuredArchive(root string, zipFS *filesys.ZipFS, decompiler *javaclassparser.JarFS, archivePath string, depth int, report *ArchiveReport) error { - return walkStructuredDirectory(root, zipFS, decompiler, ".", archivePath, depth, report) +func exportStructuredArchive(root string, zipFS *filesys.ZipFS, decompiler *javaclassparser.JarFS, archivePath string, depth, maxAnalysisUpdates int, report *ArchiveReport) error { + return walkStructuredDirectory(root, zipFS, decompiler, ".", archivePath, depth, maxAnalysisUpdates, report) } -func walkStructuredDirectory(root string, zipFS *filesys.ZipFS, decompiler *javaclassparser.JarFS, directory, archivePath string, depth int, report *ArchiveReport) error { +func walkStructuredDirectory(root string, zipFS *filesys.ZipFS, decompiler *javaclassparser.JarFS, directory, archivePath string, depth, maxAnalysisUpdates int, report *ArchiveReport) error { entries, err := decompiler.ReadDir(directory) if err != nil { return fmt.Errorf("read archive directory %q: %w", provenancePath(archivePath, cleanArchivePath(directory)), err) @@ -111,13 +111,13 @@ func walkStructuredDirectory(root string, zipFS *filesys.ZipFS, decompiler *java entryPath := path.Join(directory, javaclassparser.EntryOriginalName(entry)) entryPath = cleanArchivePath(entryPath) if isArchiveName(entryPath) { - if err := exportNestedArchive(root, zipFS, entryPath, archivePath, depth+1, report); err != nil { + if err := exportNestedArchive(root, zipFS, entryPath, archivePath, depth+1, maxAnalysisUpdates, report); err != nil { return err } continue } if entry.IsDir() { - if err := walkStructuredDirectory(root, zipFS, decompiler, entryPath, archivePath, depth, report); err != nil { + if err := walkStructuredDirectory(root, zipFS, decompiler, entryPath, archivePath, depth, maxAnalysisUpdates, report); err != nil { return err } continue @@ -129,7 +129,7 @@ func walkStructuredDirectory(root string, zipFS *filesys.ZipFS, decompiler *java return nil } -func exportNestedArchive(root string, parentZip *filesys.ZipFS, entryPath, parentArchive string, depth int, report *ArchiveReport) error { +func exportNestedArchive(root string, parentZip *filesys.ZipFS, entryPath, parentArchive string, depth, maxAnalysisUpdates int, report *ArchiveReport) error { raw, err := parentZip.ReadFile(entryPath) if err != nil { return fmt.Errorf("read nested archive %q: %w", provenancePath(parentArchive, entryPath), err) @@ -150,30 +150,39 @@ func exportNestedArchive(root string, parentZip *filesys.ZipFS, entryPath, paren Size: int64(len(raw)), }) - nestedZip, err := filesys.NewZipFSRawWithOptions(bytes.NewReader(raw), int64(len(raw)), parentZip.NestedArchiveOptions(depth)...) + payload := inputkind.StripJMODHeader(raw) + nestedZip, err := filesys.NewZipFSRawWithOptions(bytes.NewReader(payload), int64(len(payload)), parentZip.NestedArchiveOptions(depth)...) if err != nil { return fmt.Errorf("open nested archive %q: %w", provenance, err) } nestedDecompiler := javaclassparser.NewJarFS(nestedZip) + nestedDecompiler.SetAnalysisBudget(maxAnalysisUpdates) nestedDecompiler.SetRetainUnprovedSource(false) - if err := exportStructuredArchive(root, nestedZip, nestedDecompiler, provenance, depth, report); err != nil { + if err := exportStructuredArchive(root, nestedZip, nestedDecompiler, provenance, depth, maxAnalysisUpdates, report); err != nil { return err } return nil } -func exportStructuredFile(root string, decompiler fs.ReadFileFS, entryPath, archivePath string, report *ArchiveReport) error { - data, err := decompiler.ReadFile(entryPath) +func exportStructuredFile(root string, decompiler *javaclassparser.JarFS, entryPath, archivePath string, report *ArchiveReport) error { + outcome, err := decompiler.ReadClassOutcome(entryPath) if err != nil { return fmt.Errorf("read archive entry %q: %w", provenancePath(archivePath, entryPath), err) } + data := outcome.Source kind := "resource" outputEntry := entryPath outputRoot := structuredResourcesRoot + status := javaclassparser.ClassDecompileStatus("") + var stubMethods []string + var diagnostics []javaclassparser.DecompileDiagnostic if strings.EqualFold(path.Ext(entryPath), ".class") { kind = "source" outputEntry = strings.TrimSuffix(entryPath, path.Ext(entryPath)) + ".java" outputRoot = structuredSourcesRoot + status = outcome.Status + stubMethods = outcome.StubMethods + diagnostics = outcome.Diagnostics } if archivePath != "" { outputEntry = provenancePath(archivePath, outputEntry) @@ -186,11 +195,14 @@ func exportStructuredFile(root string, decompiler fs.ReadFileFS, entryPath, arch return fmt.Errorf("write archive entry %q: %w", provenancePath(archivePath, entryPath), err) } report.Entries = append(report.Entries, ArchiveEntryReport{ - Kind: kind, - SourcePath: provenancePath(archivePath, entryPath), - OutputPath: outputPath, - Archive: archivePath, - Size: int64(len(data)), + Kind: kind, + SourcePath: provenancePath(archivePath, entryPath), + OutputPath: outputPath, + Archive: archivePath, + Size: int64(len(data)), + Status: status, + StubMethods: stubMethods, + Diagnostics: diagnostics, }) return nil } @@ -249,7 +261,7 @@ func provenancePath(archivePath, entryPath string) string { func isArchiveName(name string) bool { lower := strings.ToLower(cleanArchivePath(name)) - for _, suffix := range []string{".jar", ".war", ".ear", ".par", ".zip"} { + for _, suffix := range []string{".jar", ".war", ".ear", ".aar", ".par", ".jmod", ".zip"} { if strings.HasSuffix(lower, suffix) { return true } diff --git a/classparser/jarwar/t23_path_test.go b/classparser/jarwar/t23_path_test.go index fb66dede..1cd32a01 100644 --- a/classparser/jarwar/t23_path_test.go +++ b/classparser/jarwar/t23_path_test.go @@ -3,6 +3,7 @@ package jarwar import ( "archive/zip" "bytes" + "context" "encoding/json" "io/fs" "os" @@ -14,6 +15,7 @@ import ( "github.com/yaklang/javajive/classparser" "github.com/yaklang/javajive/internal/filesys" + "github.com/yaklang/javajive/internal/workbudget" ) func t23Zip(t *testing.T, files map[string][]byte) []byte { @@ -156,6 +158,52 @@ func t23Files(t *testing.T, root string) []string { return files } +func TestStructuredArchiveReportsClassOutcomes(t *testing.T) { + valid := t23ClassFixture(t) + future := bytes.Clone(valid) + future[6], future[7] = 0, byte(javaclassparser.MaxSupportedClassMajor+1) + archive := t23Zip(t, map[string][]byte{ + "classes/Valid.class": valid, + "classes/Malformed.class": {0xca, 0xfe, 0xba, 0xbe}, + "classes/Future.class": future, + "resource.txt": []byte("exact"), + }) + src := t23WriteArchive(t, archive, ".jar") + dst := t.TempDir() + report, err := AutoDecompileWithOptions(src, dst, ArchiveOptions{Structured: true}) + if err != nil { + t.Fatal(err) + } + + entries := make(map[string]ArchiveEntryReport, len(report.Entries)) + for _, entry := range report.Entries { + entries[entry.SourcePath] = entry + } + if got := entries["classes/Valid.class"]; got.Status != javaclassparser.ClassDecompileComplete || len(got.Diagnostics) != 0 { + t.Fatalf("valid report = %+v", got) + } + for _, test := range []struct { + name string + code string + marker string + }{ + {"classes/Malformed.class", "class_parse_failed", "decompile parse failed"}, + {"classes/Future.class", "unsupported_classfile_version", "decompile fallback"}, + } { + got := entries[test.name] + if got.Status != javaclassparser.ClassDecompileFallback || len(got.Diagnostics) != 1 || got.Diagnostics[0].Code != test.code { + t.Fatalf("%s report = %+v", test.name, got) + } + raw, err := os.ReadFile(filepath.Join(dst, filepath.FromSlash(got.OutputPath))) + if err != nil || !bytes.Contains(raw, []byte(test.marker)) { + t.Fatalf("%s fallback = %q err %v", test.name, raw, err) + } + } + if got := entries["resource.txt"]; got.Kind != "resource" || got.Status != "" || len(got.Diagnostics) != 0 { + t.Fatalf("resource report = %+v", got) + } +} + func TestStructuredWARExport(t *testing.T) { classBytes := t23ClassFixture(t) innerResource := []byte{0, 1, 2, 3, 0xff} @@ -338,6 +386,97 @@ func TestArchiveOptionsFlatCompatibilityAndSharedBudget(t *testing.T) { }) } +func TestFlatArchiveOptionsPreserveRequestPolicy(t *testing.T) { + classBytes := t23ClassFixture(t) + + t.Run("canceled context", func(t *testing.T) { + src := t23WriteArchive(t, t23Zip(t, map[string][]byte{"plain.txt": []byte("flat")}), ".jar") + ctx, cancel := context.WithCancel(context.Background()) + cancel() + _, err := AutoDecompileWithOptions(src, t.TempDir(), ArchiveOptions{Context: ctx}) + if err == nil || !filesys.IsCanceled(err) { + t.Fatalf("expected canceled request, got %v", err) + } + }) + + t.Run("archive limit", func(t *testing.T) { + src := t23WriteArchive(t, t23Zip(t, map[string][]byte{ + "one.txt": []byte("one"), + "two.txt": []byte("two"), + }), ".jar") + _, err := AutoDecompileWithOptions(src, t.TempDir(), ArchiveOptions{ + Limits: javaclassparser.Limits{MaxArchiveEntries: 1}, + }) + if err == nil || !filesys.IsResourceLimit(err) { + t.Fatalf("expected archive entry limit, got %v", err) + } + }) + + t.Run("shared parse budget", func(t *testing.T) { + src := t23WriteArchive(t, t23Zip(t, map[string][]byte{"Fixture.class": classBytes}), ".jar") + work := workbudget.New(context.Background(), workbudget.Limits{MaxParseItems: 1}) + _, err := AutoDecompileWithOptions(src, t.TempDir(), ArchiveOptions{Work: work}) + if err == nil || !workbudget.Is(err) || work.Err() == nil || !strings.Contains(err.Error(), "counter=parse_items") { + t.Fatalf("expected shared parse limit, got %v snapshot=%v", err, work.Snapshot()) + } + }) + + t.Run("target release", func(t *testing.T) { + manifest := []byte("Manifest-Version: 1.0\r\nMulti-Release: true\r\n\r\n") + src := t23WriteArchive(t, t23Zip(t, map[string][]byte{ + "META-INF/MANIFEST.MF": manifest, + "release.txt": []byte("base"), + "META-INF/versions/9/release.txt": []byte("mr9"), + }), ".jar") + for _, test := range []struct { + target int + want string + }{ + {target: 8, want: "base"}, + {target: 9, want: "mr9"}, + } { + dst := t.TempDir() + if _, err := AutoDecompileWithOptions(src, dst, ArchiveOptions{TargetRelease: test.target}); err != nil { + t.Fatalf("target %d: %v", test.target, err) + } + out, err := os.ReadFile(filepath.Join(dst, "release.txt")) + if err != nil || string(out) != test.want { + t.Fatalf("target %d release = %q, want %q: %v", test.target, out, test.want, err) + } + } + }) +} + +func TestFlatArchiveFailFastPathAndWriteErrors(t *testing.T) { + t.Run("unsafe archive entry", func(t *testing.T) { + src := t23WriteArchive(t, t23Zip(t, map[string][]byte{"../escape.txt": []byte("no")}), ".jar") + parent := t.TempDir() + dst := filepath.Join(parent, "out") + _, err := AutoDecompileWithOptions(src, dst, ArchiveOptions{}) + if err == nil || !filesys.IsPathRejected(err) { + t.Fatalf("expected path rejection, got %v", err) + } + if _, statErr := os.Stat(filepath.Join(parent, "escape.txt")); !os.IsNotExist(statErr) { + t.Fatalf("escape file exists: %v", statErr) + } + }) + + t.Run("destination collision", func(t *testing.T) { + src := t23WriteArchive(t, t23Zip(t, map[string][]byte{"blocked/file.txt": []byte("no")}), ".jar") + dst := t.TempDir() + if err := os.WriteFile(filepath.Join(dst, "blocked"), []byte("already a file"), 0o644); err != nil { + t.Fatal(err) + } + _, err := AutoDecompileWithOptions(src, dst, ArchiveOptions{}) + if err == nil || !strings.Contains(err.Error(), "create archive directory") { + t.Fatalf("expected destination write error, got %v", err) + } + if _, statErr := os.Stat(filepath.Join(dst, "blocked", "file.txt")); statErr == nil { + t.Fatal("flat export continued after destination error") + } + }) +} + func TestStructuredWARExportPathSafetyAndErrors(t *testing.T) { t.Run("unsafe archive entry", func(t *testing.T) { war := t23Zip(t, map[string][]byte{"../escape.txt": []byte("no")}) diff --git a/classparser/jarwar/universal_inputs_test.go b/classparser/jarwar/universal_inputs_test.go new file mode 100644 index 00000000..2d25a80a --- /dev/null +++ b/classparser/jarwar/universal_inputs_test.go @@ -0,0 +1,309 @@ +package jarwar + +import ( + "os" + "path/filepath" + "reflect" + "strings" + "testing" + + classparser "github.com/yaklang/javajive/classparser" + "github.com/yaklang/javajive/internal/jimagefixture" +) + +func TestFlatExportNestedJar(t *testing.T) { + classBytes := t23ClassFixture(t) + inner := t23ZipOrdered(t, []struct { + name string + body []byte + }{ + {"lib/Nested.class", classBytes}, + }) + outer := t23ZipOrdered(t, []struct { + name string + body []byte + }{ + {"dep.jar", inner}, + {"root/Kept.class", classBytes}, + }) + src := t23WriteArchive(t, outer, ".jar") + dst := t.TempDir() + if err := AutoDecompile(src, dst); err != nil { + t.Fatalf("AutoDecompile: %v", err) + } + want := []string{"dep.jar/lib/Nested.java", "root/Kept.java"} + if got := t23Files(t, dst); !reflect.DeepEqual(got, want) { + t.Fatalf("files = %#v, want %#v", got, want) + } + for _, name := range want { + body, err := os.ReadFile(filepath.Join(dst, filepath.FromSlash(name))) + if err != nil { + t.Fatalf("read %s: %v", name, err) + } + if !strings.Contains(string(body), "class") { + t.Fatalf("%s does not contain decompiled source: %q", name, body) + } + } +} + +func TestFlatExportWARNestedJar(t *testing.T) { + classBytes := t23ClassFixture(t) + inner := t23ZipOrdered(t, []struct { + name string + body []byte + }{ + {"lib/Nested.class", classBytes}, + }) + war := t23ZipOrdered(t, []struct { + name string + body []byte + }{ + {"WEB-INF/classes/app/Outer.class", classBytes}, + {"WEB-INF/lib/dependency.jar", inner}, + {"WEB-INF/web.xml", []byte("\n")}, + }) + src := t23WriteArchive(t, war, ".war") + dst := t.TempDir() + if err := AutoDecompile(src, dst); err != nil { + t.Fatalf("AutoDecompile: %v", err) + } + want := []string{ + "WEB-INF/classes/app/Outer.java", + "WEB-INF/lib/dependency.jar/lib/Nested.java", + "WEB-INF/web.xml", + } + if got := t23Files(t, dst); !reflect.DeepEqual(got, want) { + t.Fatalf("files = %#v, want %#v", got, want) + } +} + +func TestFlatExportAAR(t *testing.T) { + classBytes := t23ClassFixture(t) + classesJAR := t23ZipOrdered(t, []struct { + name string + body []byte + }{ + {"lib/Nested.class", classBytes}, + }) + extraJAR := t23ZipOrdered(t, []struct { + name string + body []byte + }{ + {"lib/Extra.class", classBytes}, + }) + aar := t23ZipOrdered(t, []struct { + name string + body []byte + }{ + {"AndroidManifest.xml", []byte("\n")}, + {"classes.jar", classesJAR}, + {"libs/extra.jar", extraJAR}, + }) + src := t23WriteArchive(t, aar, ".aar") + dst := t.TempDir() + if err := AutoDecompile(src, dst); err != nil { + t.Fatalf("AutoDecompile: %v", err) + } + want := []string{ + "AndroidManifest.xml", + "classes.jar/lib/Nested.java", + "libs/extra.jar/lib/Extra.java", + } + if got := t23Files(t, dst); !reflect.DeepEqual(got, want) { + t.Fatalf("files = %#v, want %#v", got, want) + } +} + +func TestStructuredExportAAR(t *testing.T) { + classBytes := t23ClassFixture(t) + classesJAR := t23ZipOrdered(t, []struct { + name string + body []byte + }{ + {"lib/Nested.class", classBytes}, + }) + aar := t23ZipOrdered(t, []struct { + name string + body []byte + }{ + {"AndroidManifest.xml", []byte("\n")}, + {"classes.jar", classesJAR}, + }) + src := t23WriteArchive(t, aar, ".aar") + dst := t.TempDir() + report, err := AutoDecompileWithOptions(src, dst, ArchiveOptions{Structured: true}) + if err != nil { + t.Fatalf("structured export: %v", err) + } + if len(report.Archives) != 1 || report.Archives[0].Path != "classes.jar" { + t.Fatalf("archives = %#v", report.Archives) + } + want := []string{ + "archives/classes.jar", + "resources/AndroidManifest.xml", + "sources/classes.jar!/lib/Nested.java", + } + if got := t23Files(t, dst); !reflect.DeepEqual(got, want) { + t.Fatalf("files = %#v, want %#v", got, want) + } +} + +func TestFlatAndStructuredExportJMOD(t *testing.T) { + classBytes := t23ClassFixture(t) + payload := t23ZipOrdered(t, []struct { + name string + body []byte + }{ + {"classes/lib/Nested.class", classBytes}, + {"conf/example.properties", []byte("key=value\n")}, + }) + jmod := append([]byte{'J', 'M', 1, 0}, payload...) + src := t23WriteArchive(t, jmod, ".jmod") + + flat := t.TempDir() + if err := AutoDecompile(src, flat); err != nil { + t.Fatalf("flat AutoDecompile: %v", err) + } + wantFlat := []string{"classes/lib/Nested.java", "conf/example.properties"} + if got := t23Files(t, flat); !reflect.DeepEqual(got, wantFlat) { + t.Fatalf("flat files = %#v, want %#v", got, wantFlat) + } + + structured := t.TempDir() + if _, err := AutoDecompileWithOptions(src, structured, ArchiveOptions{Structured: true}); err != nil { + t.Fatalf("structured AutoDecompile: %v", err) + } + wantStructured := []string{"resources/conf/example.properties", "sources/classes/lib/Nested.java"} + if got := t23Files(t, structured); !reflect.DeepEqual(got, wantStructured) { + t.Fatalf("structured files = %#v, want %#v", got, wantStructured) + } +} + +func TestFlatAndStructuredExportJImage(t *testing.T) { + classBytes := t23ClassFixture(t) + image, err := jimagefixture.Build([]jimagefixture.Entry{ + { + Path: "/test/org/sonatype/plexus/components/cipher/PlexusCipherException.class", + Data: classBytes, + Compressed: true, + }, + {Path: "/test/conf/app.properties", Data: []byte("key=value\n")}, + }) + if err != nil { + t.Fatalf("build JImage: %v", err) + } + src := t23WriteArchive(t, image, ".jimage") + + flat := t.TempDir() + if err := AutoDecompile(src, flat); err != nil { + t.Fatalf("flat AutoDecompile: %v", err) + } + wantFlat := []string{ + "org/sonatype/plexus/components/cipher/PlexusCipherException.java", + "test/conf/app.properties", + } + if got := t23Files(t, flat); !reflect.DeepEqual(got, wantFlat) { + t.Fatalf("flat files = %#v, want %#v", got, wantFlat) + } + + structured := t.TempDir() + if _, err := AutoDecompileWithOptions(src, structured, ArchiveOptions{Structured: true}); err != nil { + t.Fatalf("structured AutoDecompile: %v", err) + } + wantStructured := []string{ + "resources/test/conf/app.properties", + "sources/org/sonatype/plexus/components/cipher/PlexusCipherException.java", + } + if got := t23Files(t, structured); !reflect.DeepEqual(got, wantStructured) { + t.Fatalf("structured files = %#v, want %#v", got, wantStructured) + } +} + +func TestJImageUnsupportedCompressor(t *testing.T) { + classBytes := t23ClassFixture(t) + image, err := jimagefixture.Build([]jimagefixture.Entry{ + { + Path: "/test/org/sonatype/plexus/components/cipher/PlexusCipherException.class", + Data: classBytes, + Compressed: true, + Compressor: "lzma", + }, + }) + if err != nil { + t.Fatalf("build JImage: %v", err) + } + src := t23WriteArchive(t, image, ".jimage") + err = AutoDecompile(src, t.TempDir()) + if err == nil || !strings.Contains(err.Error(), "lzma") { + t.Fatalf("error = %v, want lzma diagnostic", err) + } +} + +func TestJarFSReadsJMOD(t *testing.T) { + classBytes := t23ClassFixture(t) + payload := t23ZipOrdered(t, []struct { + name string + body []byte + }{ + {"classes/lib/Nested.class", classBytes}, + }) + jmod := append([]byte{'J', 'M', 1, 0}, payload...) + path := t23WriteArchive(t, jmod, ".jmod") + jarFS, err := classparser.NewJarFSFromLocal(path) + if err != nil { + t.Fatalf("NewJarFSFromLocal: %v", err) + } + defer jarFS.Close() + source, err := jarFS.ReadFile("classes/lib/Nested.class") + if err != nil { + t.Fatalf("ReadFile: %v", err) + } + if !strings.Contains(string(source), "class") { + t.Fatalf("source = %q", source) + } +} + +func TestFlatExportNestedJMOD(t *testing.T) { + classBytes := t23ClassFixture(t) + payload := t23ZipOrdered(t, []struct { + name string + body []byte + }{ + {"lib/Nested.class", classBytes}, + }) + nested := append([]byte{'J', 'M', 1, 0}, payload...) + outer := t23ZipOrdered(t, []struct { + name string + body []byte + }{ + {"lib/dependency.jmod", nested}, + }) + src := t23WriteArchive(t, outer, ".jar") + dst := t.TempDir() + if err := AutoDecompile(src, dst); err != nil { + t.Fatalf("AutoDecompile: %v", err) + } + want := []string{"lib/dependency.jmod/lib/Nested.java"} + if got := t23Files(t, dst); !reflect.DeepEqual(got, want) { + t.Fatalf("files = %#v, want %#v", got, want) + } +} + +func TestFlatExportPAR(t *testing.T) { + classBytes := t23ClassFixture(t) + archive := t23ZipOrdered(t, []struct { + name string + body []byte + }{ + {"lib/Nested.class", classBytes}, + }) + src := t23WriteArchive(t, archive, ".par") + dst := t.TempDir() + if err := AutoDecompile(src, dst); err != nil { + t.Fatalf("AutoDecompile: %v", err) + } + want := []string{"lib/Nested.java"} + if got := t23Files(t, dst); !reflect.DeepEqual(got, want) { + t.Fatalf("files = %#v, want %#v", got, want) + } +} diff --git a/classparser/java_lexical_rewrite.go b/classparser/java_lexical_rewrite.go index 581d32d8..9536ae95 100644 --- a/classparser/java_lexical_rewrite.go +++ b/classparser/java_lexical_rewrite.go @@ -2,6 +2,7 @@ package javaclassparser import ( "fmt" + "strconv" "strings" ) @@ -20,8 +21,8 @@ func rewriteJavaSourceSegments(source string, rewrite func(string) string, prote prefix = "_" + prefix } var out strings.Builder - type protected struct{ marker, text string } - var spans []protected + out.Grow(len(source)) + var spans []protectedSpan for i := 0; i < len(source); { start := i kind := "" @@ -85,28 +86,114 @@ func rewriteJavaSourceSegments(source string, rewrite func(string) string, prote out.WriteString(source[start:i]) continue } - marker := fmt.Sprintf("%s%d__", prefix, len(spans)) + inner := fmt.Sprintf("%s%d__", prefix, len(spans)) + marker := inner + wrapper := 0 switch kind { case "line": - marker = "//" + marker + marker = "//" + inner + wrapper = 2 case "block": - marker = "/*" + marker + "*/" + marker = "/*" + inner + "*/" + wrapper = 2 case "text", "string": - marker = `"` + marker + `"` + marker = `"` + inner + `"` + wrapper = 1 case "char": - marker = "'" + marker + "'" + marker = "'" + inner + "'" + wrapper = 1 } - spans = append(spans, protected{marker, source[start:i]}) + spans = append(spans, protectedSpan{marker: marker, text: source[start:i], inner: wrapper}) out.WriteString(marker) } result := rewrite(out.String()) + restored, ok := restoreProtectedSpans(result, prefix, spans) + // A rule which rewrote a marker has crossed the containment boundary. Decline + // that transformation rather than leaking a placeholder into generated Java. + if !ok || strings.Contains(restored, prefix) { + return source + } + return restored +} + +// protectedSpan is one shielded literal or comment. marker is the complete +// placeholder text (including its quote or comment wrapper) and inner is the +// offset of the shared prefix inside marker. +type protectedSpan struct { + marker string + text string + inner int +} + +// restoreProtectedSpans puts the shielded literals and comments back in one +// linear pass. The previous loop called strings.ReplaceAll once per span, so a +// source with S literals paid O(S x len(result)) copying even though only the +// spans a rewrite touched need work. +// +// The common case is exact: markers emitted by the scanner do not overlap, the +// prefix does not occur in the input, span texts are slices of the input (so +// they cannot contain another marker), and no marker is a prefix of another +// (the trailing underscore of "%d__" cannot match the next digit of a longer +// id). Every prefix occurrence that resolves to a complete stored marker is +// then independent, so replacing them left to right yields the same result as +// applying every ReplaceAll in order. +// +// A rewrite that deleted or rewrote a marker's quotes can make two marker +// fragments share a wrapper character, which sequential ReplaceAll would still +// salvage by processing spans in id order. That case is detected (an occurrence +// is incomplete or overlaps the previous match) and delegated to the exact +// sequential oracle, preserving the old behavior and cost only for mangled +// marker output, which is rare. +func restoreProtectedSpans(result, prefix string, spans []protectedSpan) (string, bool) { + if len(spans) == 0 { + return result, !strings.Contains(result, prefix) + } + var out strings.Builder + out.Grow(len(result)) + pos := 0 + for pos < len(result) { + rel := strings.Index(result[pos:], prefix) + if rel < 0 { + out.WriteString(result[pos:]) + break + } + at := pos + rel + idStart := at + len(prefix) + j := idStart + for j < len(result) && result[j] >= '0' && result[j] <= '9' { + j++ + } + id := -1 + if j > idStart && j+1 < len(result) && result[j] == '_' && result[j+1] == '_' { + if n, err := strconv.Atoi(result[idStart:j]); err == nil && n >= 0 && n < len(spans) { + id = n + } + } + if id < 0 { + return restoreProtectedSpansSequential(result, prefix, spans) + } + span := spans[id] + start := at - span.inner + end := start + len(span.marker) + if start < pos || end > len(result) || result[start:end] != span.marker { + return restoreProtectedSpansSequential(result, prefix, spans) + } + out.WriteString(result[pos:start]) + out.WriteString(span.text) + pos = end + } + return out.String(), true +} + +// restoreProtectedSpansSequential is the exact previous behavior: one +// strings.ReplaceAll per span, in id order. It is only used when a rewrite +// produced overlapping or incomplete markers. +func restoreProtectedSpansSequential(result, prefix string, spans []protectedSpan) (string, bool) { for _, span := range spans { result = strings.ReplaceAll(result, span.marker, span.text) } - // A rule which rewrote a marker has crossed the containment boundary. Decline - // that transformation rather than leaking a placeholder into generated Java. if strings.Contains(result, prefix) { - return source + return result, false } - return result + return result, true } diff --git a/classparser/java_lexical_rewrite_test.go b/classparser/java_lexical_rewrite_test.go index 3b68c666..d1ba2183 100644 --- a/classparser/java_lexical_rewrite_test.go +++ b/classparser/java_lexical_rewrite_test.go @@ -1,6 +1,8 @@ package javaclassparser import ( + "fmt" + "math/rand" "strings" "testing" ) @@ -45,3 +47,260 @@ func TestMockitoPackageGateUsesCode(t *testing.T) { } } } + +// legacyRewriteJavaSourceSegments is the previous implementation, kept as an +// independent oracle for the marker-restoration rewrite. It must not be used by +// production code. +func legacyRewriteJavaSourceSegments(source string, rewrite func(string) string, protectComments bool) string { + prefix := "__JDEC_PROTECTED_" + for strings.Contains(source, prefix) { + prefix = "_" + prefix + } + var out strings.Builder + type protected struct{ marker, text string } + var spans []protected + for i := 0; i < len(source); { + start := i + kind := "" + switch { + case strings.HasPrefix(source[i:], "//"): + kind = "line" + i += 2 + for i < len(source) && source[i] != '\n' && source[i] != '\r' { + i++ + } + case strings.HasPrefix(source[i:], "/*"): + kind = "block" + i += 2 + for i < len(source) && !strings.HasPrefix(source[i:], "*/") { + i++ + } + if i < len(source) { + i += 2 + } + case strings.HasPrefix(source[i:], `"""`): + kind = "text" + i += 3 + for i < len(source) { + if source[i] == '\\' { + i++ + if i < len(source) { + i++ + } + continue + } + if strings.HasPrefix(source[i:], `"""`) { + i += 3 + break + } + i++ + } + case source[i] == '"' || source[i] == '\'': + quote := source[i] + kind = "string" + if quote == '\'' { + kind = "char" + } + i++ + for i < len(source) { + b := source[i] + i++ + if b == '\\' { + if i < len(source) { + i++ + } + } else if b == quote { + break + } + } + default: + out.WriteByte(source[i]) + i++ + continue + } + if !protectComments && (kind == "line" || kind == "block") { + out.WriteString(source[start:i]) + continue + } + marker := fmt.Sprintf("%s%d__", prefix, len(spans)) + switch kind { + case "line": + marker = "//" + marker + case "block": + marker = "/*" + marker + "*/" + case "text", "string": + marker = `"` + marker + `"` + case "char": + marker = "'" + marker + "'" + } + spans = append(spans, protected{marker, source[start:i]}) + out.WriteString(marker) + } + result := rewrite(out.String()) + for _, span := range spans { + result = strings.ReplaceAll(result, span.marker, span.text) + } + if strings.Contains(result, prefix) { + return source + } + return result +} + +func TestRewriteJavaSourceSegmentsMatchesLegacy(t *testing.T) { + sources := []string{ + `class X { String a = "one"; // two + char c = '3'; String b = """ + text block + """; Object d = Integer::intValue; }`, + `class X { String s = "__JDEC_PROTECTED_0__"; }`, + `class X { String a = "x"; String b = "y"; }`, + `class X { char a = '\''; char b = '\\'; }`, + `class X { /* a */ String s = "a\"b"; }`, + `class X { String s = "\u1234"; }`, + `class X { int i = 1 / 2; }`, + ``, + } + rewrites := map[string]func(string) string{ + "identity": func(s string) string { return s }, + "duplicate": func(s string) string { return s + "\n" + s }, + "drop-half": func(s string) string { + if len(s) == 0 { + return s + } + return s[:len(s)/2] + }, + "reverse": func(s string) string { + b := []byte(s) + for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 { + b[i], b[j] = b[j], b[i] + } + return string(b) + }, + "inject-unknown": func(s string) string { return s + `"__JDEC_PROTECTED_999__"` }, + "rename-prefix": func(s string) string { + return strings.ReplaceAll(s, "__JDEC_PROTECTED_", "__JDEC_PROTECTED_X") + }, + "rewrap-first": func(s string) string { + const prefix = "__JDEC_PROTECTED_" + at := strings.Index(s, prefix) + if at < 0 { + return s + } + end := at + for end < len(s) && (s[end] >= '0' && s[end] <= '9' || s[end] == '_') { + end++ + } + inner := s[at:end] + return strings.Replace(s, inner, "'"+inner+"'", 1) + }, + "swap-quoted": func(s string) string { + parts := strings.Split(s, `"`) + if len(parts) < 5 { + return s + } + parts[1], parts[3] = parts[3], parts[1] + return strings.Join(parts, `"`) + }, + } + for si, source := range sources { + for _, protectComments := range []bool{true, false} { + for name, rewrite := range rewrites { + t.Run(fmt.Sprintf("src%d/%s/protectComments=%v", si, name, protectComments), func(t *testing.T) { + got := rewriteJavaSourceSegments(source, rewrite, protectComments) + want := legacyRewriteJavaSourceSegments(source, rewrite, protectComments) + if got != want { + t.Fatalf("rewrite mismatch\ngot: %q\nwant: %q", got, want) + } + }) + } + } + } +} + +func legacyRestoreProtectedSpans(result, prefix string, spans []protectedSpan) (string, bool) { + for _, span := range spans { + result = strings.ReplaceAll(result, span.marker, span.text) + } + if strings.Contains(result, prefix) { + return result, false + } + return result, true +} + +func TestRestoreProtectedSpansMatchesSequentialReplace(t *testing.T) { + const prefix = "__JDEC_PROTECTED_" + spans := []protectedSpan{ + {marker: `"` + prefix + `0__"`, text: `"alpha"`, inner: 1}, + {marker: "//" + prefix + `1__`, text: "// note", inner: 2}, + {marker: "/*" + prefix + `2__*/`, text: "/* block */", inner: 2}, + {marker: `'` + prefix + `3__'`, text: "'c'", inner: 1}, + } + results := []string{ + "", + "abc", + `"` + prefix + `0__"`, + `x "` + prefix + `0__" y //` + prefix + `1__`, + `"` + prefix + `0__" "` + prefix + `0__"`, + `'` + prefix + `0__'`, + prefix + `0__`, + `"` + prefix + `9__"`, + `"` + prefix + `0___"`, + `"` + prefix + `00__"`, + `"` + prefix + `0__x`, + `"` + prefix + `0__"` + `"` + prefix + `0__"`, + } + for _, result := range results { + got, ok := restoreProtectedSpans(result, prefix, spans) + want, wantOK := legacyRestoreProtectedSpans(result, prefix, spans) + if ok != wantOK || (ok && got != want) { + t.Fatalf("restore mismatch for %q: got (%q,%v) want (%q,%v)", result, got, ok, want, wantOK) + } + } +} + +func TestRestoreProtectedSpansRandomized(t *testing.T) { + const prefix = "__JDEC_PROTECTED_" + rng := rand.New(rand.NewSource(42)) + for trial := 0; trial < 1000; trial++ { + n := 1 + rng.Intn(5) + spans := make([]protectedSpan, n) + for i := range spans { + inner := prefix + fmt.Sprintf("%d__", i) + switch rng.Intn(4) { + case 0: + spans[i] = protectedSpan{marker: `"` + inner + `"`, text: fmt.Sprintf(`"t%d"`, i), inner: 1} + case 1: + spans[i] = protectedSpan{marker: "//" + inner, text: fmt.Sprintf("//t%d", i), inner: 2} + case 2: + spans[i] = protectedSpan{marker: "/*" + inner + "*/", text: fmt.Sprintf("/*t%d*/", i), inner: 2} + default: + spans[i] = protectedSpan{marker: "'" + inner + "'", text: "'c'", inner: 1} + } + } + var b strings.Builder + for k, parts := 0, 1+rng.Intn(8); k < parts; k++ { + switch rng.Intn(7) { + case 0: + fmt.Fprintf(&b, "x%d", k) + case 1, 2: + b.WriteString(spans[rng.Intn(n)].marker) + case 3: + b.WriteString(prefix + fmt.Sprintf("%d__", rng.Intn(n))) + case 4: + b.WriteString(`"` + prefix + fmt.Sprintf("%d__", rng.Intn(n)) + `'`) + case 5: + b.WriteString(`"` + prefix + fmt.Sprintf("%d__", n+rng.Intn(3)) + `"`) + default: + b.WriteString(spans[rng.Intn(n)].marker) + b.WriteString(spans[rng.Intn(n)].marker) + } + } + result := b.String() + got, ok := restoreProtectedSpans(result, prefix, spans) + want, wantOK := legacyRestoreProtectedSpans(result, prefix, spans) + if ok != wantOK || (ok && got != want) { + t.Fatalf("trial %d: restore mismatch for %q\nspans: %+v\ngot: (%q,%v)\nwant: (%q,%v)", + trial, result, spans, got, ok, want, wantOK) + } + } +} diff --git a/classparser/javajive_recovery.go b/classparser/javajive_recovery.go new file mode 100644 index 00000000..65aa14b8 --- /dev/null +++ b/classparser/javajive_recovery.go @@ -0,0 +1,135 @@ +package javaclassparser + +import ( + "bytes" + "encoding/json" + "io" + "sort" + "strconv" + "strings" + "unicode" + "unicode/utf8" +) + +const ( + javaJiveRecoveryAttributeName = "JavaJiveRecovery" + javaJiveRecoveryVersion = 1 + javaJiveRecoveryMaxPayload = 64 << 10 + javaJiveRecoveryMaxRecords = 128 + javaJiveRecoveryMaxFieldRunes = 240 +) + +// javaJiveRecoveryRecord is the version 1 payload record written by recovery +// producers. A JavaJiveRecovery attribute contains a JSON array of these. +type javaJiveRecoveryRecord struct { + Version int `json:"version"` + Code string `json:"code"` + Action string `json:"action"` + Entry string `json:"entry,omitempty"` + Class string `json:"class,omitempty"` + Member string `json:"member,omitempty"` + Descriptor string `json:"descriptor,omitempty"` + Reason string `json:"reason"` +} + +func javaJiveRecoveryComments(obj *ClassObject) string { + if obj == nil { + return "" + } + lines := make([]string, 0) + for _, attribute := range obj.Attributes { + unparsed, ok := attribute.(*UnparsedAttribute) + if !ok || unparsed == nil || unparsed.Name != javaJiveRecoveryAttributeName { + continue + } + records, ok := parseJavaJiveRecoveryPayload(unparsed) + if !ok { + continue + } + if len(lines)+len(records) > javaJiveRecoveryMaxRecords { + return "" + } + for _, record := range records { + lines = append(lines, formatJavaJiveRecoveryRecord(record)) + } + } + if len(lines) == 0 { + return "" + } + sort.Strings(lines) + return strings.Join(lines, "\n") + "\n" +} + +func parseJavaJiveRecoveryPayload(attribute *UnparsedAttribute) ([]javaJiveRecoveryRecord, bool) { + if attribute == nil || attribute.Length != uint32(len(attribute.Info)) || len(attribute.Info) == 0 || len(attribute.Info) > javaJiveRecoveryMaxPayload { + return nil, false + } + decoder := json.NewDecoder(bytes.NewReader(attribute.Info)) + decoder.DisallowUnknownFields() + var records []javaJiveRecoveryRecord + if err := decoder.Decode(&records); err != nil || len(records) == 0 || len(records) > javaJiveRecoveryMaxRecords { + return nil, false + } + if err := decoder.Decode(&struct{}{}); err != io.EOF { + return nil, false + } + for i := range records { + record := &records[i] + if record.Version != javaJiveRecoveryVersion || strings.TrimSpace(record.Code) == "" || strings.TrimSpace(record.Action) == "" || strings.TrimSpace(record.Reason) == "" { + return nil, false + } + record.Code = sanitizeJavaJiveRecoveryField(record.Code) + record.Action = sanitizeJavaJiveRecoveryField(record.Action) + record.Entry = sanitizeJavaJiveRecoveryField(record.Entry) + record.Class = sanitizeJavaJiveRecoveryField(record.Class) + record.Member = sanitizeJavaJiveRecoveryField(record.Member) + record.Descriptor = sanitizeJavaJiveRecoveryField(record.Descriptor) + record.Reason = sanitizeJavaJiveRecoveryField(record.Reason) + if record.Code == "" || record.Action == "" || record.Reason == "" { + return nil, false + } + } + return records, true +} + +func sanitizeJavaJiveRecoveryField(value string) string { + value = strings.ToValidUTF8(value, "\uFFFD") + value = strings.Map(func(r rune) rune { + switch { + case r == '\n' || r == '\r' || r == '\u2028' || r == '\u2029': + return ' ' + case unicode.IsControl(r): + return ' ' + default: + return r + } + }, value) + value = strings.TrimSpace(value) + if utf8.RuneCountInString(value) <= javaJiveRecoveryMaxFieldRunes { + return value + } + runes := []rune(value) + return string(runes[:javaJiveRecoveryMaxFieldRunes]) +} + +func formatJavaJiveRecoveryRecord(record javaJiveRecoveryRecord) string { + var line strings.Builder + line.WriteString("// javajive recovery:") + appendField := func(name, value string) { + if value == "" { + return + } + line.WriteByte(' ') + line.WriteString(name) + line.WriteByte('=') + line.WriteString(strconv.Quote(value)) + } + appendField("code", record.Code) + appendField("action", record.Action) + appendField("entry", record.Entry) + appendField("class", record.Class) + appendField("member", record.Member) + appendField("descriptor", record.Descriptor) + appendField("reason", record.Reason) + return line.String() +} diff --git a/classparser/javajive_recovery_test.go b/classparser/javajive_recovery_test.go new file mode 100644 index 00000000..594d93a2 --- /dev/null +++ b/classparser/javajive_recovery_test.go @@ -0,0 +1,163 @@ +package javaclassparser + +import ( + "encoding/json" + "strings" + "testing" + "unicode/utf8" + + "github.com/yaklang/javajive/classparser/classfilebuilder" +) + +func recoveryAttribute(payload []byte) *UnparsedAttribute { + return &UnparsedAttribute{Name: javaJiveRecoveryAttributeName, Length: uint32(len(payload)), Info: payload} +} + +func recoveryRecordPayload(records ...javaJiveRecoveryRecord) []byte { + payload, err := json.Marshal(records) + if err != nil { + panic(err) + } + return payload +} + +func parsedRecoveryFixture(t *testing.T, payloads ...[]byte) *ClassObject { + t.Helper() + builder := classfilebuilder.NewClass("fixture/RecoveryFixture", "java/lang/Object", 0x0021) + for _, payload := range payloads { + builder.AddClassAttribute(javaJiveRecoveryAttributeName, payload) + } + raw, err := builder.Bytes() + if err != nil { + t.Fatal(err) + } + obj, err := Parse(raw) + if err != nil { + t.Fatal(err) + } + return obj +} + +func TestJavaJiveRecoveryParsedAttributeCommentsLeadDump(t *testing.T) { + payload := recoveryRecordPayload( + javaJiveRecoveryRecord{Version: 1, Code: "z.code", Action: "stub_method", Member: "z", Descriptor: "()V", Reason: "last"}, + javaJiveRecoveryRecord{Version: 1, Code: "a.code", Action: "stub_class", Entry: "classes.dex", Class: "Lfixture/RecoveryFixture;", Reason: "first"}, + ) + obj := parsedRecoveryFixture(t, payload) + if len(obj.Attributes) != 1 { + t.Fatalf("attributes = %d, want 1", len(obj.Attributes)) + } + attribute, ok := obj.Attributes[0].(*UnparsedAttribute) + if !ok || attribute.Name != javaJiveRecoveryAttributeName || string(attribute.Info) != string(payload) { + t.Fatalf("recovery attribute was not preserved as UnparsedAttribute: %#v", obj.Attributes[0]) + } + + source, err := NewClassObjectDumper(obj).DumpClass() + if err != nil { + t.Fatal(err) + } + wantPrefix := "// javajive recovery: code=\"a.code\" action=\"stub_class\" entry=\"classes.dex\" class=\"Lfixture/RecoveryFixture;\" reason=\"first\"\n" + + "// javajive recovery: code=\"z.code\" action=\"stub_method\" member=\"z\" descriptor=\"()V\" reason=\"last\"\n" + if !strings.HasPrefix(source, wantPrefix) { + t.Fatalf("recovery comments are not sorted at the very top:\n%s", source) + } + if !strings.Contains(source[len(wantPrefix):], "package fixture;") { + t.Fatalf("ordinary source missing after recovery comments:\n%s", source) + } +} + +func TestJavaJiveRecoveryOrdinaryClassIsUnchanged(t *testing.T) { + obj := parsedRecoveryFixture(t) + source, err := NewClassObjectDumper(obj).DumpClass() + if err != nil { + t.Fatal(err) + } + if strings.Contains(source, "javajive recovery:") || !strings.HasPrefix(source, "package fixture;") { + t.Fatalf("ordinary class gained a recovery preamble:\n%s", source) + } +} + +func TestJavaJiveRecoverySanitizesAndBoundsFields(t *testing.T) { + longReason := strings.Repeat("界", javaJiveRecoveryMaxFieldRunes+20) + payload := recoveryRecordPayload(javaJiveRecoveryRecord{ + Version: 1, + Code: " code\n// forged ", + Action: "stub_\"method\\path", + Member: "run\r\n// injected", + Reason: longReason, + }) + comments := javaJiveRecoveryComments(&ClassObject{Attributes: []AttributeInfo{recoveryAttribute(payload)}}) + if strings.Count(comments, "\n") != 1 { + t.Fatalf("untrusted fields injected comment lines: %q", comments) + } + if !strings.Contains(comments, `code="code // forged"`) || + !strings.Contains(comments, `action="stub_\"method\\path"`) || + !strings.Contains(comments, `member="run // injected"`) { + t.Fatalf("fields were not sanitized and escaped deterministically: %q", comments) + } + marker := ` reason="` + start := strings.Index(comments, marker) + if start < 0 { + t.Fatalf("reason missing: %q", comments) + } + reason := comments[start+len(marker) : len(comments)-2] + if utf8.RuneCountInString(reason) != javaJiveRecoveryMaxFieldRunes { + t.Fatalf("bounded reason has %d runes, want %d", utf8.RuneCountInString(reason), javaJiveRecoveryMaxFieldRunes) + } +} + +func TestJavaJiveRecoveryMalformedPayloadsAreIgnored(t *testing.T) { + valid := javaJiveRecoveryRecord{Version: 1, Code: "code", Action: "action", Reason: "reason"} + tooMany := make([]javaJiveRecoveryRecord, javaJiveRecoveryMaxRecords+1) + for i := range tooMany { + tooMany[i] = valid + } + tooManyPayload, err := json.Marshal(tooMany) + if err != nil { + t.Fatal(err) + } + tests := map[string]*UnparsedAttribute{ + "invalid JSON": recoveryAttribute([]byte(`[{`)), + "wrong top level": recoveryAttribute([]byte(`{"version":1}`)), + "trailing JSON": recoveryAttribute([]byte(`[{"version":1,"code":"c","action":"a","reason":"r"}] {}`)), + "unknown field": recoveryAttribute([]byte(`[{"version":1,"code":"c","action":"a","reason":"r","extra":true}]`)), + "unsupported version": recoveryAttribute(recoveryRecordPayload(javaJiveRecoveryRecord{Version: 2, Code: "c", Action: "a", Reason: "r"})), + "missing required": recoveryAttribute(recoveryRecordPayload(javaJiveRecoveryRecord{Version: 1, Code: "c", Action: "a"})), + "too many records": recoveryAttribute(tooManyPayload), + "oversize payload": recoveryAttribute([]byte(strings.Repeat(" ", javaJiveRecoveryMaxPayload+1))), + "length mismatch": {Name: javaJiveRecoveryAttributeName, Length: 99, Info: recoveryRecordPayload(valid)}, + } + for name, attribute := range tests { + t.Run(name, func(t *testing.T) { + if got := javaJiveRecoveryComments(&ClassObject{Attributes: []AttributeInfo{attribute}}); got != "" { + t.Fatalf("malformed payload produced comments: %q", got) + } + }) + } + + malformed := recoveryAttribute([]byte(`not json`)) + validAttribute := recoveryAttribute(recoveryRecordPayload(valid)) + if got := javaJiveRecoveryComments(&ClassObject{Attributes: []AttributeInfo{malformed, validAttribute}}); !strings.HasPrefix(got, "// javajive recovery:") { + t.Fatalf("malformed sibling suppressed valid attribute: %q", got) + } +} + +func TestJavaJiveRecoverySortsAcrossAttributesAndCapsAggregate(t *testing.T) { + obj := &ClassObject{Attributes: []AttributeInfo{ + recoveryAttribute(recoveryRecordPayload(javaJiveRecoveryRecord{Version: 1, Code: "b", Action: "stub", Reason: "two"})), + recoveryAttribute(recoveryRecordPayload(javaJiveRecoveryRecord{Version: 1, Code: "a", Action: "stub", Reason: "one"})), + }} + comments := javaJiveRecoveryComments(obj) + if strings.Index(comments, `code="a"`) > strings.Index(comments, `code="b"`) { + t.Fatalf("records are not sorted across attributes: %q", comments) + } + + attributes := make([]AttributeInfo, javaJiveRecoveryMaxRecords+1) + payload := recoveryRecordPayload(javaJiveRecoveryRecord{Version: 1, Code: "c", Action: "a", Reason: "r"}) + for i := range attributes { + attributes[i] = recoveryAttribute(payload) + } + if got := javaJiveRecoveryComments(&ClassObject{Attributes: attributes}); got != "" { + t.Fatalf("aggregate record cap was not enforced: %d bytes", len(got)) + } +} diff --git a/classparser/jdk_constructor_code.go b/classparser/jdk_constructor_code.go index 6350e853..b59f0830 100644 --- a/classparser/jdk_constructor_code.go +++ b/classparser/jdk_constructor_code.go @@ -9,6 +9,7 @@ import ( "encoding/json" "fmt" "io" + "strings" "sync" ) @@ -45,7 +46,26 @@ var jdkConstructorCode struct { hashes map[int]map[string]string } +// jdkConstructorNameCandidate is a conservative namespace gate over the +// embedded constructor corpus. A same-package identity probe for an application +// class (for example com/example/String) can never resolve here, and must not +// pay the one-time 11 MB catalog + zip index cost. +func jdkConstructorNameCandidate(name string) bool { + switch { + case strings.HasPrefix(name, "java/"), strings.HasPrefix(name, "javax/"), + strings.HasPrefix(name, "jdk/"), strings.HasPrefix(name, "sun/"): + return true + case strings.HasPrefix(name, "org/omg/"), strings.HasPrefix(name, "org/w3c/"), + strings.HasPrefix(name, "org/xml/"): + return true + } + return false +} + func jdkConstructorClassBytes(name string, release int) ([]byte, bool) { + if !jdkConstructorNameCandidate(name) { + return nil, false + } jdkConstructorCode.once.Do(func() { zr, err := zip.NewReader(bytes.NewReader(jdkConstructorCodeZIP), int64(len(jdkConstructorCodeZIP))) if err != nil { @@ -75,50 +95,25 @@ func jdkConstructorClassBytes(name string, release int) ([]byte, bool) { if json.Unmarshal(data, &document) != nil || document.Schema != 1 { return } - var declarations struct { - Profiles []struct { - Release int - ArchiveSHA256 string `json:"archive_sha256"` - Archives map[string]string - Provenance map[string]struct{ Archive, SHA256 string } - References map[string]struct{ Archive, SHA256 string } `json:"reference_provenance"` - } - } - if json.Unmarshal(jdkInvocationCatalogJSON, &declarations) != nil { - return - } - expected := map[int]string{} - originalClasses := map[int]map[string]string{} - for _, p := range declarations.Profiles { - expected[p.Release] = p.ArchiveSHA256 - originals := map[string]string{} - for _, source := range []map[string]struct{ Archive, SHA256 string }{p.Provenance, p.References} { - for name, record := range source { - if p.Archives[record.Archive] != p.ArchiveSHA256 { - continue - } - if prior := originals[name]; prior != "" && prior != record.SHA256 { - return - } - originals[name] = record.SHA256 - } - } - originalClasses[p.Release] = originals - } - if len(document.Profiles) != len(expected) { + // Runtime integrity is verified against this embedded manifest and the + // class bytes themselves. The cross-check against the invocation catalog + // is a build/release consistency contract and runs in a pure-Go test, so a + // tiny decompile no longer decodes the 11 MB invocation catalog merely to + // prove that the two embedded assets agree. + if len(document.Profiles) == 0 { return } entries := map[int]map[string]*zip.File{} hashes := map[int]map[string]string{} for _, profile := range document.Profiles { - if entries[profile.Release] != nil || expected[profile.Release] == "" || profile.ArchiveSHA256 != expected[profile.Release] { + if entries[profile.Release] != nil || len(profile.ArchiveSHA256) != 64 || len(profile.Classes) == 0 { return } table := map[string]*zip.File{} for name, hash := range profile.Classes { digest, err := hex.DecodeString(hash) entry := files[fmt.Sprintf("%d/%s.class", profile.Release, name)] - if err != nil || len(digest) != 32 || entry == nil || entry.UncompressedSize64 > 2<<20 || originalClasses[profile.Release][name] != hash { + if err != nil || len(digest) != 32 || entry == nil || entry.UncompressedSize64 > 2<<20 { return } table[name] = entry diff --git a/classparser/jdk_metadata_catalog.go b/classparser/jdk_metadata_catalog.go index 40d521ee..b52bf8c0 100644 --- a/classparser/jdk_metadata_catalog.go +++ b/classparser/jdk_metadata_catalog.go @@ -15,25 +15,37 @@ import ( //go:embed jdk_metadata_catalog.json var jdkInvocationCatalogJSON []byte +type jdkCatalogProvenance struct { + Archive string `json:"archive"` + SHA256 string `json:"sha256"` +} + var jdkInvocationCatalog struct { once sync.Once + valid bool profiles map[int]map[string]callbinding.Class throwableParents map[int]map[string][]string referenceParents map[int]map[string][]string + archiveSHA map[int]string + originalClasses map[int]map[string]string } -// jdkInvocationMetadata is a bounded platform-profile fallback. target must be -// an exact catalog release; a newer/older profile is never silently substituted. -// Caller-provided declaration bytes take priority over this fallback. -func jdkInvocationMetadata(name string, target int) (callbinding.Class, bool) { +// loadJDKInvocationCatalog decodes the embedded catalog exactly once. The +// constructor-code loader also consumes the provenance tables from this decode; +// it must not unmarshal the same 11 MB document a second time. +func loadJDKInvocationCatalog() { jdkInvocationCatalog.once.Do(func() { var document struct { Schema int `json:"schema"` Profiles []struct { - Release int `json:"release"` - Classes map[string]callbinding.Class `json:"classes"` - ThrowableParents map[string][]string `json:"throwable_hierarchy"` - ReferenceParents map[string][]string `json:"reference_hierarchy"` + Release int `json:"release"` + ArchiveSHA256 string `json:"archive_sha256"` + Archives map[string]string `json:"archives"` + Provenance map[string]jdkCatalogProvenance `json:"provenance"` + References map[string]jdkCatalogProvenance `json:"reference_provenance"` + Classes map[string]callbinding.Class `json:"classes"` + ThrowableParents map[string][]string `json:"throwable_hierarchy"` + ReferenceParents map[string][]string `json:"reference_hierarchy"` } `json:"profiles"` } if json.Unmarshal(jdkInvocationCatalogJSON, &document) != nil || document.Schema != 3 { @@ -42,6 +54,8 @@ func jdkInvocationMetadata(name string, target int) (callbinding.Class, bool) { profiles := make(map[int]map[string]callbinding.Class) throwableParents := make(map[int]map[string][]string) referenceParents := make(map[int]map[string][]string) + archiveSHA := make(map[int]string) + originalClasses := make(map[int]map[string]string) for _, profile := range document.Profiles { if _, duplicate := profiles[profile.Release]; duplicate { return @@ -61,7 +75,21 @@ func jdkInvocationMetadata(name string, target int) (callbinding.Class, bool) { } } } + originals := map[string]string{} + for _, source := range []map[string]jdkCatalogProvenance{profile.Provenance, profile.References} { + for name, record := range source { + if profile.Archives[record.Archive] != profile.ArchiveSHA256 { + continue + } + if prior := originals[name]; prior != "" && prior != record.SHA256 { + return + } + originals[name] = record.SHA256 + } + } profiles[profile.Release] = profile.Classes + archiveSHA[profile.Release] = profile.ArchiveSHA256 + originalClasses[profile.Release] = originals for _, parents := range profile.ThrowableParents { for _, parent := range parents { if _, ok := profile.ThrowableParents[parent]; !ok { @@ -82,10 +110,29 @@ func jdkInvocationMetadata(name string, target int) (callbinding.Class, bool) { } referenceParents[profile.Release] = profile.ReferenceParents } + jdkInvocationCatalog.valid = true jdkInvocationCatalog.profiles = profiles jdkInvocationCatalog.throwableParents = throwableParents jdkInvocationCatalog.referenceParents = referenceParents + jdkInvocationCatalog.archiveSHA = archiveSHA + jdkInvocationCatalog.originalClasses = originalClasses }) +} + +// jdkInvocationMetadata is a bounded platform-profile fallback. target must be +// an exact catalog release; a newer/older profile is never silently substituted. +// Caller-provided declaration bytes take priority over this fallback. +func jdkInvocationMetadata(name string, target int) (callbinding.Class, bool) { + if name == "java/lang/Object" { + return jdkObjectMetadata(target) + } + if !jdkConstructorNameCandidate(name) { + return callbinding.Class{}, false + } + loadJDKInvocationCatalog() + if !jdkInvocationCatalog.valid { + return callbinding.Class{}, false + } class, ok := jdkInvocationCatalog.profiles[target][name] if !ok { return callbinding.Class{}, false @@ -104,7 +151,12 @@ func jdkInvocationMetadata(name string, target int) (callbinding.Class, bool) { // deliberately carries no method, accessibility or constructor-effect claims. // Unknown releases and absent declarations remain unknown. func jdkReferenceSupertypes(name string, target int) ([]string, bool) { - jdkInvocationMetadata("java/lang/Object", target) + if !jdkConstructorNameCandidate(name) { + return nil, false + } + // Supertypes come from the catalog's reference_hierarchy; this is a real + // load, unlike the java/lang/Object metadata fast path. + loadJDKInvocationCatalog() parents, known := jdkInvocationCatalog.referenceParents[target][name] return append([]string(nil), parents...), known } @@ -113,7 +165,10 @@ func jdkReferenceSupertypes(name string, target int) ([]string, bool) { // member-completeness claim. Checked-exception classification can use it; // synthetic-member naming and overload resolution must still reject it. func jdkThrowableAncestry(name string, target int) (callbinding.Class, bool) { - jdkInvocationMetadata("java/lang/Object", target) + if !jdkConstructorNameCandidate(name) { + return callbinding.Class{}, false + } + loadJDKInvocationCatalog() parents, ok := jdkInvocationCatalog.throwableParents[target][name] if !ok { return callbinding.Class{}, false diff --git a/classparser/jdk_metadata_catalog_test.go b/classparser/jdk_metadata_catalog_test.go index 632d8d7f..b44f0560 100644 --- a/classparser/jdk_metadata_catalog_test.go +++ b/classparser/jdk_metadata_catalog_test.go @@ -3,6 +3,7 @@ package javaclassparser import ( "encoding/hex" "encoding/json" + "reflect" "sync" "testing" @@ -10,6 +11,23 @@ import ( "github.com/yaklang/javajive/classparser/decompiler/core/callbinding" ) +func TestJDKObjectMetadataMatchesCatalog(t *testing.T) { + loadJDKInvocationCatalog() + if !jdkInvocationCatalog.valid { + t.Fatal("catalog did not load") + } + for release, classes := range jdkInvocationCatalog.profiles { + want, ok := classes["java/lang/Object"] + if !ok { + t.Fatalf("catalog lacks java/lang/Object for release %d", release) + } + got, ok := jdkObjectMetadata(release) + if !ok || !reflect.DeepEqual(got, want) { + t.Fatalf("static Object metadata drifted for release %d:\n got %+v\nwant %+v", release, got, want) + } + } +} + func TestJDKInvocationCatalogCompleteProfiles(t *testing.T) { var document struct { Profiles []struct { diff --git a/classparser/jdk_object_metadata.go b/classparser/jdk_object_metadata.go new file mode 100644 index 00000000..299b3bcb --- /dev/null +++ b/classparser/jdk_object_metadata.go @@ -0,0 +1,136 @@ +package javaclassparser + +import "github.com/yaklang/javajive/classparser/decompiler/core/callbinding" + +// jdkObjectCatalogMetadata mirrors java/lang/Object from the pinned platform +// catalog. Object is the language root every class references, so describing it +// must not force a cold decode of the entire 11 MB catalog. +var jdkObjectCatalogMetadata = map[int]callbinding.Class{ + 8: { + Name: "java/lang/Object", Public: true, MembersComplete: true, ParentsComplete: true, + Parents: []string{}, + Methods: []callbinding.Method{ + {Name: "", Desc: "()V", Exceptions: []string{}, ExceptionsKnown: true, Public: true}, + {Name: "registerNatives", Desc: "()V", Exceptions: []string{}, ExceptionsKnown: true, Static: true}, + {Name: "getClass", Desc: "()Ljava/lang/Class;", Signature: "()Ljava/lang/Class<*>;", Exceptions: []string{}, ExceptionsKnown: true, Public: true, Generic: true}, + {Name: "hashCode", Desc: "()I", Exceptions: []string{}, ExceptionsKnown: true, Public: true}, + {Name: "equals", Desc: "(Ljava/lang/Object;)Z", Exceptions: []string{}, ExceptionsKnown: true, Public: true}, + {Name: "clone", Desc: "()Ljava/lang/Object;", Exceptions: []string{"java/lang/CloneNotSupportedException"}, ExceptionsKnown: true}, + {Name: "toString", Desc: "()Ljava/lang/String;", Exceptions: []string{}, ExceptionsKnown: true, Public: true}, + {Name: "notify", Desc: "()V", Exceptions: []string{}, ExceptionsKnown: true, Public: true}, + {Name: "notifyAll", Desc: "()V", Exceptions: []string{}, ExceptionsKnown: true, Public: true}, + {Name: "wait", Desc: "(J)V", Exceptions: []string{"java/lang/InterruptedException"}, ExceptionsKnown: true, Public: true}, + {Name: "wait", Desc: "(JI)V", Exceptions: []string{"java/lang/InterruptedException"}, ExceptionsKnown: true, Public: true}, + {Name: "wait", Desc: "()V", Exceptions: []string{"java/lang/InterruptedException"}, ExceptionsKnown: true, Public: true}, + {Name: "finalize", Desc: "()V", Exceptions: []string{"java/lang/Throwable"}, ExceptionsKnown: true}, + }, + }, + 9: { + Name: "java/lang/Object", Public: true, MembersComplete: true, ParentsComplete: true, + Parents: []string{}, + Methods: []callbinding.Method{ + {Name: "registerNatives", Desc: "()V", Exceptions: []string{}, ExceptionsKnown: true, Static: true}, + {Name: "", Desc: "()V", Exceptions: []string{}, ExceptionsKnown: true, Public: true}, + {Name: "getClass", Desc: "()Ljava/lang/Class;", Signature: "()Ljava/lang/Class<*>;", Exceptions: []string{}, ExceptionsKnown: true, Public: true, Generic: true}, + {Name: "hashCode", Desc: "()I", Exceptions: []string{}, ExceptionsKnown: true, Public: true}, + {Name: "equals", Desc: "(Ljava/lang/Object;)Z", Exceptions: []string{}, ExceptionsKnown: true, Public: true}, + {Name: "clone", Desc: "()Ljava/lang/Object;", Exceptions: []string{"java/lang/CloneNotSupportedException"}, ExceptionsKnown: true}, + {Name: "toString", Desc: "()Ljava/lang/String;", Exceptions: []string{}, ExceptionsKnown: true, Public: true}, + {Name: "notify", Desc: "()V", Exceptions: []string{}, ExceptionsKnown: true, Public: true}, + {Name: "notifyAll", Desc: "()V", Exceptions: []string{}, ExceptionsKnown: true, Public: true}, + {Name: "wait", Desc: "(J)V", Exceptions: []string{"java/lang/InterruptedException"}, ExceptionsKnown: true, Public: true}, + {Name: "wait", Desc: "(JI)V", Exceptions: []string{"java/lang/InterruptedException"}, ExceptionsKnown: true, Public: true}, + {Name: "wait", Desc: "()V", Exceptions: []string{"java/lang/InterruptedException"}, ExceptionsKnown: true, Public: true}, + {Name: "finalize", Desc: "()V", Exceptions: []string{"java/lang/Throwable"}, ExceptionsKnown: true}, + }, + }, + 11: { + Name: "java/lang/Object", Public: true, MembersComplete: true, ParentsComplete: true, + Parents: []string{}, + Methods: []callbinding.Method{ + {Name: "registerNatives", Desc: "()V", Exceptions: []string{}, ExceptionsKnown: true, Static: true}, + {Name: "", Desc: "()V", Exceptions: []string{}, ExceptionsKnown: true, Public: true}, + {Name: "getClass", Desc: "()Ljava/lang/Class;", Signature: "()Ljava/lang/Class<*>;", Exceptions: []string{}, ExceptionsKnown: true, Public: true, Generic: true}, + {Name: "hashCode", Desc: "()I", Exceptions: []string{}, ExceptionsKnown: true, Public: true}, + {Name: "equals", Desc: "(Ljava/lang/Object;)Z", Exceptions: []string{}, ExceptionsKnown: true, Public: true}, + {Name: "clone", Desc: "()Ljava/lang/Object;", Exceptions: []string{"java/lang/CloneNotSupportedException"}, ExceptionsKnown: true}, + {Name: "toString", Desc: "()Ljava/lang/String;", Exceptions: []string{}, ExceptionsKnown: true, Public: true}, + {Name: "notify", Desc: "()V", Exceptions: []string{}, ExceptionsKnown: true, Public: true}, + {Name: "notifyAll", Desc: "()V", Exceptions: []string{}, ExceptionsKnown: true, Public: true}, + {Name: "wait", Desc: "()V", Exceptions: []string{"java/lang/InterruptedException"}, ExceptionsKnown: true, Public: true}, + {Name: "wait", Desc: "(J)V", Exceptions: []string{"java/lang/InterruptedException"}, ExceptionsKnown: true, Public: true}, + {Name: "wait", Desc: "(JI)V", Exceptions: []string{"java/lang/InterruptedException"}, ExceptionsKnown: true, Public: true}, + {Name: "finalize", Desc: "()V", Exceptions: []string{"java/lang/Throwable"}, ExceptionsKnown: true}, + }, + }, + 16: { + Name: "java/lang/Object", Public: true, MembersComplete: true, ParentsComplete: true, + Parents: []string{}, + Methods: []callbinding.Method{ + {Name: "", Desc: "()V", Exceptions: []string{}, ExceptionsKnown: true, Public: true}, + {Name: "getClass", Desc: "()Ljava/lang/Class;", Signature: "()Ljava/lang/Class<*>;", Exceptions: []string{}, ExceptionsKnown: true, Public: true, Generic: true}, + {Name: "hashCode", Desc: "()I", Exceptions: []string{}, ExceptionsKnown: true, Public: true}, + {Name: "equals", Desc: "(Ljava/lang/Object;)Z", Exceptions: []string{}, ExceptionsKnown: true, Public: true}, + {Name: "clone", Desc: "()Ljava/lang/Object;", Exceptions: []string{"java/lang/CloneNotSupportedException"}, ExceptionsKnown: true}, + {Name: "toString", Desc: "()Ljava/lang/String;", Exceptions: []string{}, ExceptionsKnown: true, Public: true}, + {Name: "notify", Desc: "()V", Exceptions: []string{}, ExceptionsKnown: true, Public: true}, + {Name: "notifyAll", Desc: "()V", Exceptions: []string{}, ExceptionsKnown: true, Public: true}, + {Name: "wait", Desc: "()V", Exceptions: []string{"java/lang/InterruptedException"}, ExceptionsKnown: true, Public: true}, + {Name: "wait", Desc: "(J)V", Exceptions: []string{"java/lang/InterruptedException"}, ExceptionsKnown: true, Public: true}, + {Name: "wait", Desc: "(JI)V", Exceptions: []string{"java/lang/InterruptedException"}, ExceptionsKnown: true, Public: true}, + {Name: "finalize", Desc: "()V", Exceptions: []string{"java/lang/Throwable"}, ExceptionsKnown: true}, + }, + }, + 17: { + Name: "java/lang/Object", Public: true, MembersComplete: true, ParentsComplete: true, + Parents: []string{}, + Methods: []callbinding.Method{ + {Name: "", Desc: "()V", Exceptions: []string{}, ExceptionsKnown: true, Public: true}, + {Name: "getClass", Desc: "()Ljava/lang/Class;", Signature: "()Ljava/lang/Class<*>;", Exceptions: []string{}, ExceptionsKnown: true, Public: true, Generic: true}, + {Name: "hashCode", Desc: "()I", Exceptions: []string{}, ExceptionsKnown: true, Public: true}, + {Name: "equals", Desc: "(Ljava/lang/Object;)Z", Exceptions: []string{}, ExceptionsKnown: true, Public: true}, + {Name: "clone", Desc: "()Ljava/lang/Object;", Exceptions: []string{"java/lang/CloneNotSupportedException"}, ExceptionsKnown: true}, + {Name: "toString", Desc: "()Ljava/lang/String;", Exceptions: []string{}, ExceptionsKnown: true, Public: true}, + {Name: "notify", Desc: "()V", Exceptions: []string{}, ExceptionsKnown: true, Public: true}, + {Name: "notifyAll", Desc: "()V", Exceptions: []string{}, ExceptionsKnown: true, Public: true}, + {Name: "wait", Desc: "()V", Exceptions: []string{"java/lang/InterruptedException"}, ExceptionsKnown: true, Public: true}, + {Name: "wait", Desc: "(J)V", Exceptions: []string{"java/lang/InterruptedException"}, ExceptionsKnown: true, Public: true}, + {Name: "wait", Desc: "(JI)V", Exceptions: []string{"java/lang/InterruptedException"}, ExceptionsKnown: true, Public: true}, + {Name: "finalize", Desc: "()V", Exceptions: []string{"java/lang/Throwable"}, ExceptionsKnown: true}, + }, + }, + 21: { + Name: "java/lang/Object", Public: true, MembersComplete: true, ParentsComplete: true, + Parents: []string{}, + Methods: []callbinding.Method{ + {Name: "", Desc: "()V", Exceptions: []string{}, ExceptionsKnown: true, Public: true}, + {Name: "getClass", Desc: "()Ljava/lang/Class;", Signature: "()Ljava/lang/Class<*>;", Exceptions: []string{}, ExceptionsKnown: true, Public: true, Generic: true}, + {Name: "hashCode", Desc: "()I", Exceptions: []string{}, ExceptionsKnown: true, Public: true}, + {Name: "equals", Desc: "(Ljava/lang/Object;)Z", Exceptions: []string{}, ExceptionsKnown: true, Public: true}, + {Name: "clone", Desc: "()Ljava/lang/Object;", Exceptions: []string{"java/lang/CloneNotSupportedException"}, ExceptionsKnown: true}, + {Name: "toString", Desc: "()Ljava/lang/String;", Exceptions: []string{}, ExceptionsKnown: true, Public: true}, + {Name: "notify", Desc: "()V", Exceptions: []string{}, ExceptionsKnown: true, Public: true}, + {Name: "notifyAll", Desc: "()V", Exceptions: []string{}, ExceptionsKnown: true, Public: true}, + {Name: "wait", Desc: "()V", Exceptions: []string{"java/lang/InterruptedException"}, ExceptionsKnown: true, Public: true}, + {Name: "wait", Desc: "(J)V", Exceptions: []string{"java/lang/InterruptedException"}, ExceptionsKnown: true, Public: true}, + {Name: "wait0", Desc: "(J)V", Exceptions: []string{"java/lang/InterruptedException"}, ExceptionsKnown: true}, + {Name: "wait", Desc: "(JI)V", Exceptions: []string{"java/lang/InterruptedException"}, ExceptionsKnown: true, Public: true}, + {Name: "finalize", Desc: "()V", Exceptions: []string{"java/lang/Throwable"}, ExceptionsKnown: true}, + }, + }, +} + +// jdkObjectMetadata returns a request-local copy. Every class references +// java/lang/Object, so this lookup must not decode the full platform catalog. +func jdkObjectMetadata(release int) (callbinding.Class, bool) { + class, ok := jdkObjectCatalogMetadata[release] + if !ok { + return callbinding.Class{}, false + } + class.Parents = append([]string{}, class.Parents...) + class.Methods = append([]callbinding.Method(nil), class.Methods...) + for i := range class.Methods { + class.Methods[i].Exceptions = append([]string{}, class.Methods[i].Exceptions...) + } + return class, true +} diff --git a/classparser/loop_analysis_cache_test.go b/classparser/loop_analysis_cache_test.go new file mode 100644 index 00000000..71b05e37 --- /dev/null +++ b/classparser/loop_analysis_cache_test.go @@ -0,0 +1,41 @@ +package javaclassparser + +import ( + "os" + "testing" +) + +// The loop-analysis cache is an internal reuse of a body/exit query that is +// otherwise recomputed for every container node. It must never change the +// rendered source: the kill switch makes the rewriter take the original +// recompute path, so both runs must agree byte for byte. +// +// These fixtures have loops and no exception table, which is exactly the +// configuration where the cache is enabled (protected retry boundaries mutate +// node state and keep it disabled). +func TestLoopAnalysisCacheMatchesUncachedDecompile(t *testing.T) { + fixtures := []string{ + "testdata/regression/BareIfAdv.class", + "testdata/regression/BoolArrayElementStoreSeed.class", + "testdata/regression/AbstractLinkedList.class", + } + for _, path := range fixtures { + data, err := os.ReadFile(path) + if err != nil { + t.Fatalf("%s: %v", path, err) + } + t.Setenv("JDEC_LOOP_ANALYSIS_CACHE_OFF", "") + cached, err := Decompile(data) + if err != nil { + t.Fatalf("%s cached: %v", path, err) + } + t.Setenv("JDEC_LOOP_ANALYSIS_CACHE_OFF", "1") + uncached, err := Decompile(data) + if err != nil { + t.Fatalf("%s uncached: %v", path, err) + } + if cached != uncached { + t.Fatalf("%s: cache changed the rendered source (cached=%d bytes, uncached=%d bytes)", path, len(cached), len(uncached)) + } + } +} diff --git a/classparser/parse_class_object.go b/classparser/parse_class_object.go index 1651733d..4f7a6b3b 100644 --- a/classparser/parse_class_object.go +++ b/classparser/parse_class_object.go @@ -341,6 +341,9 @@ func parseWithMetadataLayout(reader *ClassReader, offsets map[*MemberInfo]int, l if err := obj.CheckUtf8UseSites(); err != nil { return nil, err } + if err := obj.CheckConstantPoolLinks(); err != nil { + return nil, err + } } if err := reader.work.CheckContext(reader.context); err != nil { return nil, err diff --git a/classparser/performance_batch_test.go b/classparser/performance_batch_test.go new file mode 100644 index 00000000..ecb8377c --- /dev/null +++ b/classparser/performance_batch_test.go @@ -0,0 +1,61 @@ +package javaclassparser + +import ( + "os" + "strings" + "testing" +) + +func TestJoinRuleChainExactOutput(t *testing.T) { + if got, want := joinRuleChain([]string{"first", "second", "third"}), "first->second->third"; got != want { + t.Fatalf("joinRuleChain() = %q, want %q", got, want) + } + if got := joinRuleChain(nil); got != "" { + t.Fatalf("joinRuleChain(nil) = %q", got) + } +} + +func BenchmarkJoinRuleChainBuilder(b *testing.B) { + chain := make([]string, 4096) + for i := range chain { + chain[i] = "rewriteRule" + } + b.ReportAllocs() + for i := 0; i < b.N; i++ { + if got := joinRuleChain(chain); len(got) == 0 { + b.Fatal("empty output") + } + } +} + +func TestSourceRewritePrecisionOuterGateSemantics(t *testing.T) { + called := false + d := &ClassObjectDumper{options: DecompileOptions{Mode: Precision}} + got := d.sourceRewrite("test", "class_source", "source", func(string) string { + called = true + return "changed" + }) + if got != "source" || called { + t.Fatalf("Precision sourceRewrite = %q, rule called=%v", got, called) + } +} + +func TestDumpMethodsPointerFastPathKeepsDescriptor(t *testing.T) { + raw, err := os.ReadFile("../test/cross/testdata/irreducible/original/DeadSecondaryEntry.class") + if err != nil { + t.Fatal(err) + } + result, err := DecompileWithOptions(raw, DecompileOptions{Mode: Precision, TargetSourceVersion: 8, EnvSnapshot: map[string]string{}}) + if err != nil { + t.Fatal(err) + } + if len(result.StubMethods) != 0 { + t.Fatalf("pointer fast path stubbed methods: %v diagnostics=%+v", result.StubMethods, result.Diagnostics) + } + if result.Status != "complete" { + t.Fatalf("status=%q diagnostics=%+v", result.Status, result.Diagnostics) + } + if !strings.Contains(result.Source, "int run(int") { + t.Fatalf("run(II)I descriptor was not rendered:\n%s", result.Source) + } +} diff --git a/classparser/rewrite_contract.go b/classparser/rewrite_contract.go index 9dde0e2c..99549b2c 100644 --- a/classparser/rewrite_contract.go +++ b/classparser/rewrite_contract.go @@ -3,6 +3,7 @@ package javaclassparser import ( "crypto/sha256" "fmt" + "strings" ) // Real sourceRewrite rule IDs contracted for T27. Names match dumper.go. @@ -169,12 +170,316 @@ func (e *RewriteContractEngine) Apply(id, phase, source string, rule func(string } func joinRuleChain(chain []string) string { - out := "" + var out strings.Builder for i, id := range chain { if i > 0 { - out += "->" + out.WriteString("->") } - out += id + out.WriteString(id) } - return out + return out.String() +} + +// The Compatibility class-source pipeline is one ordered sequence. This list +// mirrors the call sites in dumper.go byte for byte, including every repeated +// rule entry. It is metadata only: production still calls the rules inline in +// this exact order. Never append, sort or deduplicate this list. +var classSourceRewriteOrder = []string{ + "fixLambdaLoopCapture", + "removeUnreachableSwitchBreak", + "fixTryBreakReturn", + "fixThrowTypeVarCast", + "fixLoopCatchThrow", + "fixTryCatchExceptionPlacement", + "wrapUncaughtThrowingCall", + "wrapReflectionCallInSwitchCase", + "wrapFieldInitializerReflection", + "wrapUncaughtGetConstructor", + "fixAlreadyCaughtDuplicateCatch", + "fixShadowFieldSuperAssign", + "fixImmutableBuilderWitness", + "fixSelectMethodsAmbiguous", + "fixAsMapFunctionRawCast", + "fixThrowClassCastDropsThrowable", + "fixReplaceAllListStreamCast", + "fixClassMapEntryPutCasts", + "fixVisitAnnotationConsumerCast", + "fixGetUninterruptiblyGetInTry", + "fixDrainUninterruptiblyPollInTry", + "fixTransposeCellFunctionCast", + "fixPreferringStringsAsListCast", + "fixSyncLazyNavigableReturn", + "fixCatchingFutureFinally", + "fixAbstractServiceFinally", + "fixSyncHelperCasReturn", + "fixRescheduleUnlockFinally", + "fixDupThrowableCatchFinally", + "fixAppEngineCNFECatch", + "fixRateLimiterTryAcquireReturn", + "fixConvertClassValuesObjectArray", + "fixToAnnotationArrayFinisher", + "fixDataBufferLambdaCast", + "fixLinkedWithNextRawCast", + "fixJacksonFeatureUpcast", + "fixAnnotatedAndMetadataLambda", + "fixJacksonRemainingReconstructs", + "fixCloseResourceThrows", + "fixTransmitterEmptySync", + "fixExchangeFinderEmptySync", + "fixRealConnectionConnect", + "fixConnectionPoolCleanup", + "fixHttp2NewStream", + "fixHttp2StreamEmptySync", + "fixEmptySyncMissingReturn", + "fixSkipAsciiWhitespaceContinue", + "fixDiskLruIteratorHasNext", + "fixPublicSuffixDatabase", + "fixCollections4RemainingReconstructs", + "fixNettyRemainingReconstructs", + "fixLog4jRemainingReconstructs", + "fixOrig14RemainderReconstructs", + "fixProtobufRemainingReconstructs", + "fixJedisRemainingReconstructs", + "fixLogbackRemainingReconstructs", + "fixHikaricpRemainingReconstructs", + "fixPool2RemainingReconstructs", + "fixPicocliRemainingReconstructs", + "fixHttpclientRemainingReconstructs", + "fixJavassistRemainingReconstructs", + "fixCommonsIoRemainingReconstructs", + "fixCompressRemainingReconstructs", + "fixCaffeineRemainingReconstructs", + "fixRxjavaRemainingReconstructs", + "fixMath3RemainingReconstructs", + "fixAssertjRemainingReconstructs", + "fixZxingRemainingReconstructs", + "fixEnumNoArgCtorThisAfterLocals", + "fixCtorNPECheckBeforeThis", + "fixCtorDelegationArgumentSpills", + "fixEnumClinitIllegalNew", + "fixKotlinEnumEntries", + "fixBareNestedImports", + "fixHardjarShapes", + "fixBoolUsedAsArithOperand", + "fixBooleanZeroLiteral", + "fixIntCmpBoolMaterializedLiteral", + "fixBoundedStreamWiden", + "fixObjectUsedAsInt", + "fixIntUsedAsInstanceof", + "fixXstreamRemainingReconstructs", + "fixFreemarkerRemainingReconstructs", + "fixThrowObjectAsThrowable", + "fixClassDollarForwardRef", + "fixThrowInitCauseCast", + "fixMutinyPublisherCast", + "fixSpringMethodRefCasts", + "fixFluxCreateDataBufferWitness", + "fixUrlResourceURISyntax", + "fixPercNSMECatch", + "fixFutureAdapterReturn", + "fixLeakedExceptionSentinel", + "fixIdentSelfCast", + "wrapThrowTargetException", + "fixXstreamRemainingReconstructs", + "fixJavassistRemainingReconstructs", + "fixOrig14RemainderReconstructs", + "fixJacksonRemainingReconstructs", + "fixNettyRemainingReconstructs", + "fixLog4jRemainingReconstructs", + "fixIdentAsTypeDecl", + "fixObjectInitCastType", +} + +// methodSourceRewriteOrder mirrors the three method-local passes. They run per +// method and therefore have no single global position relative to the class +// sequence above; this list locks their order within each method only. +var methodSourceRewriteOrder = []string{ + "hoistSameTypeEscapedLocals", + "hoistCastGuardedEscapedLocals", + "addMissingGeneratedLocalDecls", +} + +// rewriteRuleKey names one rule in one phase. A rule may carry different +// necessary conditions in different phases, so the phase is part of the key. +type rewriteRuleKey struct { + ID string + Phase string +} + +// rewriteNeedleSet is one DNF alternative: every literal must be present in +// the source before the rule can change it. An alternative is not a sufficient +// condition; it only permits invocation. +type rewriteNeedleSet []string + +// rewriteRuleSpec is immutable applicability metadata. An empty Alternatives +// list means the rule is Always applicable and must execute conservatively. +type rewriteRuleSpec struct { + Alternatives []rewriteNeedleSet +} + +// rewriteRuleSpecs holds necessary-condition metadata for the small, audited +// prefilter set. Rules absent from this map are Always applicable. The map is +// initialized once and never mutated. Every needle below is a literal that the +// rule implementation itself requires (either an explicit early guard or an +// exact pattern it must find), so absence proves the rule cannot change source. +// +// Shaded-library rules intentionally remain Always: canonical package names +// (for example com.google.zxing or freemarker.) can be relocated by shading, +// and using them here would make a necessary condition unreliable. +var rewriteRuleSpecs = map[rewriteRuleKey]rewriteRuleSpec{ + {ID: "removeUnreachableSwitchBreak", Phase: "class_source"}: { + // The rule only removes a line matching ^(\t+)break;$. + Alternatives: []rewriteNeedleSet{{"break;"}}, + }, + {ID: "fixTryBreakReturn", Phase: "class_source"}: { + // Requires `} while (true);`, an in-try `break;`, and a hoisted return. + Alternatives: []rewriteNeedleSet{{"} while (true);", "break;", "return "}}, + }, + {ID: "fixThrowTypeVarCast", Phase: "class_source"}: { + // Requires a `throws T {` signature and a `throw ;` statement. + // The keywords (not the following whitespace) are the necessary + // condition: the implementation accepts any \s+ separator. + Alternatives: []rewriteNeedleSet{{"throws", "throw"}}, + }, + {ID: "fixLoopCatchThrow", Phase: "class_source"}: { + // Requires a catch with `throw new RuntimeException(...)` followed by a + // loop transfer (continue or break). + Alternatives: []rewriteNeedleSet{ + {"catch(", "throw new RuntimeException(", "continue"}, + {"catch(", "throw new RuntimeException(", "break"}, + }, + }, + {ID: "wrapUncaughtThrowingCall", Phase: "class_source"}: { + // Matches return lines containing UNSAFE.allocateInstance(...). + Alternatives: []rewriteNeedleSet{{"allocateInstance("}}, + }, + {ID: "wrapFieldInitializerReflection", Phase: "class_source"}: { + // The field-initializer pattern requires one of these method names. + Alternatives: []rewriteNeedleSet{ + {"getConstructor("}, {"getDeclaredConstructor("}, + {"getMethod("}, {"getDeclaredMethod("}, + {"getDeclaredField("}, {"getField("}, + }, + }, + {ID: "wrapReflectionCallInSwitchCase", Phase: "class_source"}: { + // The return-statement pattern requires one of these method names. + Alternatives: []rewriteNeedleSet{ + {"getConstructor("}, {"getDeclaredConstructor("}, + {"getMethod("}, {"getDeclaredMethod("}, + {"invokeExact("}, {"metafactory("}, + {"findStatic("}, {"findVirtual("}, + }, + }, + {ID: "fixTryCatchExceptionPlacement", Phase: "class_source"}: { + // The throwing-call regex requires a dotted call to one of these names. + Alternatives: []rewriteNeedleSet{ + {".getDeclaredConstructor("}, {".newInstance("}, + {".getMethod("}, {".getConstructor("}, + }, + }, + {ID: "fixImmutableBuilderWitness", Phase: "class_source"}: { + // The regex requires an Immutable* type and its .builder() call. + Alternatives: []rewriteNeedleSet{{"Immutable", ".builder("}}, + }, + {ID: "fixIntCmpBoolMaterializedLiteral", Phase: "class_source"}: { + // Both exact replacements contain `!= (0))`. + Alternatives: []rewriteNeedleSet{{"!= (0))"}}, + }, + {ID: "fixBoolUsedAsArithOperand", Phase: "class_source"}: { + // Every changed boolean local/field is declared with `boolean `. + Alternatives: []rewriteNeedleSet{{"boolean "}}, + }, + {ID: "fixBooleanZeroLiteral", Phase: "class_source"}: { + // The rule only rewrites chunks belonging to a `boolean varN` local. + Alternatives: []rewriteNeedleSet{{"boolean var"}}, + }, + {ID: "fixClassDollarForwardRef", Phase: "class_source"}: { + // The rule walks from this exact declaration prefix. + Alternatives: []rewriteNeedleSet{{"static Class class$"}}, + }, + {ID: "fixThrowInitCauseCast", Phase: "class_source"}: { + // The constructor chain must start with the exact `().initCause(` suffix. + Alternatives: []rewriteNeedleSet{{"().initCause("}}, + }, + {ID: "fixShadowFieldSuperAssign", Phase: "class_source"}: { + // Form 1 needs ` = this.`; form 2 needs `) (this.`. + Alternatives: []rewriteNeedleSet{ + {" = this."}, + {") (this."}, + }, + }, + {ID: "fixLeakedExceptionSentinel", Phase: "class_source"}: { + // The rule returns before scanning unless the shielded code contains one + // of these exact diagnostic sentinels. + Alternatives: []rewriteNeedleSet{ + {"= Exception;"}, + {"= Exception\n"}, + {"return Exception;"}, + {"throw Exception;"}, + }, + }, + {ID: "fixSpringMethodRefCasts", Phase: "class_source"}: { + // Every exact replacement contains a method-reference `::`. + Alternatives: []rewriteNeedleSet{{"::"}}, + }, +} + +func lookupRewriteRuleSpec(id, phase string) (rewriteRuleSpec, bool) { + spec, ok := rewriteRuleSpecs[rewriteRuleKey{ID: id, Phase: phase}] + return spec, ok +} + +// rewriteApplicabilityIndex caches literal presence for one immutable source +// state. Callers must rebuild it whenever the source changes; the dumper also +// stamps it with a mutation epoch so a stale index is never consulted. +type rewriteApplicabilityIndex struct { + source string + epoch uint64 + presence map[string]bool +} + +func (i *rewriteApplicabilityIndex) contains(needle string) bool { + if present, ok := i.presence[needle]; ok { + return present + } + present := strings.Contains(i.source, needle) + i.presence[needle] = present + return present +} + +// rewriteSpecApplicable evaluates DNF: at least one alternative must have every +// one of its literal needles present. It never proves applicability; it only +// rejects rules whose required literals are provably absent. +func rewriteSpecApplicable(spec rewriteRuleSpec, index *rewriteApplicabilityIndex) bool { + if len(spec.Alternatives) == 0 { + return true + } + for _, alternative := range spec.Alternatives { + if len(alternative) == 0 { + return true + } + present := true + for _, needle := range alternative { + if !index.contains(needle) { + present = false + break + } + } + if present { + return true + } + } + return false +} + +// rewriteRuleApplicable is the index-free form used by focused tests. +func rewriteRuleApplicable(id, phase, source string) bool { + spec, ok := lookupRewriteRuleSpec(id, phase) + if !ok { + return true + } + return rewriteSpecApplicable(spec, &rewriteApplicabilityIndex{ + source: source, + presence: make(map[string]bool), + }) } diff --git a/classparser/rewrite_scheduler_test.go b/classparser/rewrite_scheduler_test.go new file mode 100644 index 00000000..8a27e898 --- /dev/null +++ b/classparser/rewrite_scheduler_test.go @@ -0,0 +1,715 @@ +package javaclassparser + +import ( + "crypto/sha256" + "fmt" + "os" + "reflect" + "regexp" + "slices" + "strings" + "testing" + + "github.com/yaklang/javajive/internal/jdecenv" +) + +// rewriteRuleExpectedOutput applies the same contract shield sourceRewrite +// applies, without consulting the scheduler. +func rewriteRuleExpectedOutput(id string, rule func(string) string, source string) string { + if wrapped := wrapContractedSourceRule(id, rule); wrapped != nil { + return wrapped(source) + } + return rule(source) +} + +// TestRewriteSchedulerOrderMatchesDumperCallSites locks the immutable ordered +// registry to the actual inline call sites, including every repeated entry and +// the method-local phase order. A reordering of dumper.go must update the +// registry deliberately. +func TestRewriteSchedulerOrderMatchesDumperCallSites(t *testing.T) { + data, err := os.ReadFile("dumper.go") + if err != nil { + t.Fatal(err) + } + callRe := regexp.MustCompile(`c\.sourceRewrite\("([^"]+)", "(class_source|method_source)"`) + var gotClass, gotMethod []string + for _, match := range callRe.FindAllStringSubmatch(string(data), -1) { + switch match[2] { + case "class_source": + gotClass = append(gotClass, match[1]) + case "method_source": + gotMethod = append(gotMethod, match[1]) + } + } + if !slices.Equal(gotClass, classSourceRewriteOrder) { + t.Fatalf("class-source order drifted:\n got=%v\nwant=%v", gotClass, classSourceRewriteOrder) + } + if !slices.Equal(gotMethod, methodSourceRewriteOrder) { + t.Fatalf("method-source order drifted:\n got=%v\nwant=%v", gotMethod, methodSourceRewriteOrder) + } + if len(classSourceRewriteOrder) != 103 { + t.Fatalf("class-source registry length = %d, want 103", len(classSourceRewriteOrder)) + } + if len(methodSourceRewriteOrder) != 3 { + t.Fatalf("method-source registry length = %d, want 3", len(methodSourceRewriteOrder)) + } + classCount := map[string]int{} + for _, id := range classSourceRewriteOrder { + classCount[id]++ + } + for key := range rewriteRuleSpecs { + if key.Phase != "class_source" { + t.Errorf("prefilter spec %q has unexpected phase %q", key.ID, key.Phase) + } + if classCount[key.ID] == 0 { + t.Errorf("prefilter spec %q is absent from the ordered class-source registry", key.ID) + } + } +} + +func TestRewriteSchedulerNecessaryConditionDNF(t *testing.T) { + spec := rewriteRuleSpec{Alternatives: []rewriteNeedleSet{ + {"alpha", "beta"}, + {"gamma"}, + }} + indexFor := func(source string) *rewriteApplicabilityIndex { + return &rewriteApplicabilityIndex{source: source, presence: map[string]bool{}} + } + if !rewriteSpecApplicable(spec, indexFor("alpha beta")) { + t.Fatal("first alternative with both needles was rejected") + } + if rewriteSpecApplicable(spec, indexFor("alpha only")) { + t.Fatal("incomplete first alternative was accepted") + } + if !rewriteSpecApplicable(spec, indexFor("gamma")) { + t.Fatal("second alternative was rejected") + } + if rewriteSpecApplicable(spec, indexFor("delta")) { + t.Fatal("source with no alternative was accepted") + } + if !rewriteSpecApplicable(rewriteRuleSpec{}, indexFor("")) { + t.Fatal("Always rule was rejected") + } + if !rewriteRuleApplicable("unregistered-rule", "class_source", "") { + t.Fatal("unregistered rule must remain Always") + } + if !rewriteRuleApplicable("fixIntCmpBoolMaterializedLiteral", "method_source", "") { + t.Fatal("phase mismatch must remain Always") + } +} + +type schedulerRuleFixture struct { + id string + phase string + offFlag string + positive string + nearMiss string + rule func(string) string +} + +func schedulerRuleFixtures() []schedulerRuleFixture { + return []schedulerRuleFixture{ + { + id: "removeUnreachableSwitchBreak", phase: "class_source", offFlag: "JDEC_RM_UNREACHABLE_BREAK_OFF", + rule: removeUnreachableSwitchBreak, + positive: "class T {\n" + + "\tvoid f() {\n" + + "\t\tint var0 = 0;\n" + + "\t\tswitch (var0) {\n" + + "\t\t\tcase 1:\n" + + "\t\t\t\tswitch (var0) {\n" + + "\t\t\t\t\tdefault:\n" + + "\t\t\t\t\t\treturn;\n" + + "\t\t\t\t}\n" + + "\t\t\t\tbreak;\n" + + "\t\t}\n" + + "\t}\n" + + "}\n", + nearMiss: "class T {\n" + + "\tvoid f() {\n" + + "\t\tint var0 = 0;\n" + + "\t\tswitch (var0) {\n" + + "\t\t\tcase 1:\n" + + "\t\t\t\tswitch (var0) {\n" + + "\t\t\t\t\tdefault:\n" + + "\t\t\t\t\t\treturn;\n" + + "\t\t\t\t}\n" + + "\t\t\t\tcontinue;\n" + + "\t\t}\n" + + "\t}\n" + + "}\n", + }, + { + id: "fixTryBreakReturn", phase: "class_source", offFlag: "JDEC_FIX_TRY_BREAK_RETURN_OFF", + rule: fixTryBreakReturn, + positive: "\t\tdo{\n" + + "\t\t\ttry{\n" + + "\t\t\t\tbreak;\n" + + "\t\t\t}catch(Exception var0){\n" + + "\t\t\t}\n" + + "\t\t} while (true);\n" + + "\t\treturn var0;\n", + nearMiss: "\t\tdo{\n" + + "\t\t\ttry{\n" + + "\t\t\t\tbreak;\n" + + "\t\t\t}catch(Exception var0){\n" + + "\t\t\t}\n" + + "\t\t} while (false);\n" + + "\t\treturn var0;\n", + }, + { + id: "fixThrowTypeVarCast", phase: "class_source", offFlag: "JDEC_FIX_THROW_TYPEVAR_CAST_OFF", + rule: fixThrowTypeVarCast, + positive: "\tpublic void f(Throwable var0) throws T {\n" + + "\t\tthrow var0;\n" + + "\t}\n", + nearMiss: "\tpublic void f(Throwable var0) {\n" + + "\t\tthrow var0;\n" + + "\t}\n", + }, + { + id: "fixLoopCatchThrow", phase: "class_source", offFlag: "JDEC_FIX_LOOP_CATCH_THROW_OFF", + rule: fixLoopCatchThrow, + positive: "\tvoid f() {\n" + + "\t\tfor (;;) {\n" + + "\t\t\ttry{\n" + + "\t\t\t\tthis.g();\n" + + "\t\t\t}catch(Exception var0){\n" + + "\t\t\t\tthrow new RuntimeException(var0);\n" + + "\t\t\t}\n" + + "\t\t\tcontinue;\n" + + "\t\t}\n" + + "\t}\n", + nearMiss: "\tvoid f() {\n" + + "\t\tfor (;;) {\n" + + "\t\t\ttry{\n" + + "\t\t\t\tthis.g();\n" + + "\t\t\t}catch(Exception var0){\n" + + "\t\t\t\tthrow new RuntimeException(var0);\n" + + "\t\t\t}\n" + + "\t\t\treturn;\n" + + "\t\t}\n" + + "\t}\n", + }, + { + id: "wrapUncaughtThrowingCall", phase: "class_source", offFlag: "JDEC_WRAP_ALLOCATE_OFF", + rule: wrapUncaughtThrowingCall, + positive: "\tvoid f() {\n" + + "\t\treturn UNSAFE.allocateInstance(var0);\n" + + "\t}\n", + nearMiss: "\tvoid f() {\n" + + "\t\treturn UNSAFE.getInstance(var0);\n" + + "\t}\n", + }, + { + id: "wrapFieldInitializerReflection", phase: "class_source", offFlag: "JDEC_WRAP_FIELD_INIT_OFF", + rule: wrapFieldInitializerReflection, + positive: "\tprivate static final long valueOffset = UNSAFE.objectFieldOffset(Class.class.getDeclaredField(\"value\"));\n", + nearMiss: "\tprivate static final long valueOffset = UNSAFE.objectFieldOffset(Class.class.findField(\"value\"));\n", + }, + { + id: "wrapReflectionCallInSwitchCase", phase: "class_source", offFlag: "JDEC_WRAP_REFLECTION_CASE_OFF", + rule: wrapReflectionCallInSwitchCase, + positive: "\tvoid f() {\n" + + "\t\tswitch (var0) {\n" + + "\t\t\tcase 1:\n" + + "\t\t\t\treturn Class.class.getMethod(\"x\");\n" + + "\t\t}\n" + + "\t}\n", + nearMiss: "\tvoid f() {\n" + + "\t\tswitch (var0) {\n" + + "\t\t\tcase 1:\n" + + "\t\t\t\treturn Class.class.lookupMethod(\"x\");\n" + + "\t\t}\n" + + "\t}\n", + }, + { + id: "fixTryCatchExceptionPlacement", phase: "class_source", offFlag: "JDEC_FIX_TRYCATCH_OFF", + rule: fixTryCatchExceptionPlacement, + positive: "if (cond){\n" + + "\tctor = type.getDeclaredConstructor();\n" + + "}\n" + + "try{\n" + + "\ttry{\n" + + "\t\tready();\n" + + "\t}catch(Exception ex){\n" + + "\t\tthrow new RuntimeException(ex);\n" + + "\t}\n" + + "}catch(Throwable t){ }\n", + nearMiss: "if (cond){\n" + + "\tctor = type.create();\n" + + "}\n" + + "try{\n" + + "\ttry{\n" + + "\t\tready();\n" + + "\t}catch(Exception ex){\n" + + "\t\tthrow new RuntimeException(ex);\n" + + "\t}\n" + + "}catch(Throwable t){ }\n", + }, + { + id: "fixImmutableBuilderWitness", phase: "class_source", offFlag: "JDEC_IMMUTABLE_BUILDER_WITNESS_OFF", + rule: fixImmutableBuilderWitness, + positive: "\tprivate static final ImmutableMap VALUE_PARSERS = ImmutableMap.builder().put(\"a\", new Foo()).build();\n", + nearMiss: "\tprivate static final HashMap VALUE_PARSERS = HashMap.builder().put(\"a\", new Foo()).build();\n", + }, + { + id: "fixIntCmpBoolMaterializedLiteral", phase: "class_source", offFlag: "JDEC_INT_CMP_BOOL_LIT_OFF", + rule: fixIntCmpBoolMaterializedLiteral, + positive: "if ((!(var5)) && ((var7_1) == ((2) != (0)))){\n", + nearMiss: "if ((!(var5)) && ((var7_1) == ((2) != (1)))){\n", + }, + { + id: "fixBoolUsedAsArithOperand", phase: "class_source", offFlag: "JDEC_BOOL_ARITH_OPERAND_OFF", + rule: fixBoolUsedAsArithOperand, + positive: "\t\tboolean var8_1 = false;\n\t\tvar9_1 = (((141) + (var6_1)) + ((2) * (var7_1))) + ((4) * (var8_1));\n", + nearMiss: "\t\tint var8_1 = 0;\n\t\tvar9_1 = (((141) + (var6_1)) + ((2) * (var7_1))) + ((4) * (var8_1));\n", + }, + { + id: "fixBooleanZeroLiteral", phase: "class_source", offFlag: "JDEC_BOOL_ZERO_LITERAL_OFF", + rule: fixBooleanZeroLiteral, + positive: "boolean var10 = this.excludeField(var9,true);\n\t\t\t\tif (((var10) == (0)) && (!(var11))){\n\t\t\t\t\tvar10 = 0;\n\t\t\t\t\tvar10 = 1;\n", + nearMiss: "int var10 = this.excludeField(var9,true);\n\t\t\t\tif (((var10) == (0)) && (!(var11))){\n\t\t\t\t\tvar10 = 0;\n\t\t\t\t\tvar10 = 1;\n", + }, + { + id: "fixClassDollarForwardRef", phase: "class_source", offFlag: "JDEC_CLASSDOLLAR_FORWARD_OFF", + rule: fixClassDollarForwardRef, + positive: "\tstatic final String DATA_HOLDER_KEY = class$Foo.getName();\n\tstatic Class class$Foo;\n", + nearMiss: "\tstatic final String DATA_HOLDER_KEY = class$Foo.getName();\n", + }, + { + id: "fixThrowInitCauseCast", phase: "class_source", offFlag: "JDEC_THROW_INITCAUSE_OFF", + rule: fixThrowInitCauseCast, + positive: "\t\t\tthrow new NoClassDefFoundError().initCause((Throwable)(var1));\n", + nearMiss: "\t\t\tthrow new NoClassDefFoundError().cause((Throwable)(var1));\n", + }, + { + id: "fixShadowFieldSuperAssign", phase: "class_source", offFlag: "JDEC_SHADOW_FIELD_SUPER_ASSIGN_OFF", + rule: fixShadowFieldSuperAssign, + positive: "this.poolLock = this.poolLock;\nthis.leasedConnections = (Set) (this.leasedConnections);", + nearMiss: "this.poolLock = poolLock;\n", + }, + { + id: "fixLeakedExceptionSentinel", phase: "class_source", offFlag: "JDEC_LEAKED_EXCEPTION_SENTINEL_OFF", + rule: fixLeakedExceptionSentinel, + positive: "catch(Exception var0_1){\n\tObject var2 = Exception;\n\tthrow var0;\n}\n", + nearMiss: "catch(Exception var0_1){\n\tObject var2 = null;\n\tthrow var0;\n}\n", + }, + { + id: "fixSpringMethodRefCasts", phase: "class_source", offFlag: "JDEC_SPRING_METHODREF_CAST_OFF", + rule: fixSpringMethodRefCasts, + positive: "\t\treturn helper.synthesize(MergedAnnotation::isPresent);\n", + nearMiss: "\t\treturn helper.synthesize(MergedAnnotation.isPresent);\n", + }, + } +} + +func TestRewriteSchedulerPositiveAndNearMissExactOutput(t *testing.T) { + t.Setenv("JDEC_REWRITE_SCHEDULER_OFF", "") + fixtures := schedulerRuleFixtures() + if len(fixtures) != len(rewriteRuleSpecs) { + t.Fatalf("fixture count = %d, prefilter spec count = %d; every prefilttered rule needs a fixture", len(fixtures), len(rewriteRuleSpecs)) + } + for _, fixture := range fixtures { + fixture := fixture + t.Run(fixture.id, func(t *testing.T) { + t.Setenv(fixture.offFlag, "") + direct := rewriteRuleExpectedOutput(fixture.id, fixture.rule, fixture.positive) + if direct == fixture.positive { + t.Fatalf("positive fixture did not exercise the rule:\n%s", fixture.positive) + } + on, stats := runScheduledRewrite(fixture.id, fixture.phase, fixture.positive, fixture.rule, false) + if on != direct { + t.Fatalf("scheduler output differs from direct rule output:\n got=%q\nwant=%q", on, direct) + } + if want := (rewriteSchedulerMetrics{Considered: 1, Candidates: 1, Invoked: 1}); stats != want { + t.Fatalf("positive stats = %+v, want %+v", stats, want) + } + off, offStats := runScheduledRewrite(fixture.id, fixture.phase, fixture.positive, fixture.rule, true) + if off != direct { + t.Fatalf("kill-switch output differs from direct rule output:\n got=%q\nwant=%q", off, direct) + } + if want := (rewriteSchedulerMetrics{Considered: 1, Candidates: 1, Invoked: 1}); offStats != want { + t.Fatalf("kill-switch stats = %+v, want %+v", offStats, want) + } + + if rewriteRuleApplicable(fixture.id, fixture.phase, fixture.nearMiss) { + t.Fatalf("near miss is still considered applicable:\n%s", fixture.nearMiss) + } + if nearDirect := rewriteRuleExpectedOutput(fixture.id, fixture.rule, fixture.nearMiss); nearDirect != fixture.nearMiss { + t.Fatalf("necessary condition is unsound: rule changed a near miss:\n got=%q", nearDirect) + } + nearOn, nearStats := runScheduledRewrite(fixture.id, fixture.phase, fixture.nearMiss, fixture.rule, false) + if nearOn != fixture.nearMiss { + t.Fatalf("scheduler changed a near miss:\n got=%q", nearOn) + } + if want := (rewriteSchedulerMetrics{Considered: 1, Skipped: 1}); nearStats != want { + t.Fatalf("near-miss stats = %+v, want %+v", nearStats, want) + } + nearOff, _ := runScheduledRewrite(fixture.id, fixture.phase, fixture.nearMiss, fixture.rule, true) + if nearOff != fixture.nearMiss { + t.Fatalf("kill-switch rule changed a near miss:\n got=%q", nearOff) + } + }) + } +} + +func runScheduledRewrite(id, phase, source string, rule func(string) string, disabled bool) (string, rewriteSchedulerMetrics) { + d := &ClassObjectDumper{ + options: DecompileOptions{Mode: Compatibility}, + rewriteSchedulerDisabled: disabled, + } + out := d.sourceRewrite(id, phase, source, rule) + return out, d.rewriteSchedulerStats +} + +func schedulerTestHash(source string) string { + return fmt.Sprintf("%x", sha256.Sum256([]byte(source))) +} + +func TestRewriteSchedulerPreservesRecordsDiagnosticsAndHashes(t *testing.T) { + t.Setenv("JDEC_REWRITE_SCHEDULER_OFF", "") + t.Setenv("JDEC_BOOL_ZERO_LITERAL_OFF", "") + t.Setenv("JDEC_THROW_INITCAUSE_OFF", "") + initial := "class T {\n" + + "\tvoid f() {\n" + + "\t\tboolean var0 = false;\n" + + "\t\tvar0 = 0;\n" + + "\t\tthrow new NoClassDefFoundError().initCause((Throwable)(var0));\n" + + "\t}\n" + + "}\n" + + run := func(disabled bool) (string, *DecompileResult, rewriteSchedulerMetrics) { + report := &DecompileResult{} + d := &ClassObjectDumper{ + options: DecompileOptions{Mode: Compatibility}, + report: report, + rewriteSchedulerDisabled: disabled, + } + source := initial + source = d.sourceRewrite("fixBooleanZeroLiteral", "class_source", source, fixBooleanZeroLiteral) + source = d.sourceRewrite("fixThrowInitCauseCast", "class_source", source, fixThrowInitCauseCast) + source = d.sourceRewrite("scheduler-always-rule", "class_source", source, func(src string) string { + return strings.ReplaceAll(src, "class T", "class U") + }) + // This registered rule has no exact literal trigger in the sequence. + source = d.sourceRewrite("fixIntCmpBoolMaterializedLiteral", "class_source", source, fixIntCmpBoolMaterializedLiteral) + return source, report, d.rewriteSchedulerStats + } + + onSource, onReport, onStats := run(false) + offSource, offReport, offStats := run(true) + if onSource != offSource { + t.Fatalf("scheduler changed final source:\n on=%q\noff=%q", onSource, offSource) + } + if !reflect.DeepEqual(onReport.RulesApplied, offReport.RulesApplied) { + t.Fatalf("rewrite records diverged:\n on=%+v\noff=%+v", onReport.RulesApplied, offReport.RulesApplied) + } + if !reflect.DeepEqual(onReport.Diagnostics, offReport.Diagnostics) { + t.Fatalf("diagnostics diverged:\n on=%+v\noff=%+v", onReport.Diagnostics, offReport.Diagnostics) + } + if onStats.Considered != 4 || offStats.Considered != 4 { + t.Fatalf("considered counts = on:%d off:%d, want 4/4", onStats.Considered, offStats.Considered) + } + if onStats.Skipped != 1 { + t.Fatalf("expected exactly one prefiltered rule: %+v", onStats) + } + if offStats.Skipped != 0 { + t.Fatalf("kill switch skipped a rule: %+v", offStats) + } + if onStats.Candidates+onStats.Skipped != onStats.Considered { + t.Fatalf("candidate/skip accounting = %+v", onStats) + } + + s0 := initial + s1 := fixBooleanZeroLiteral(s0) + s2 := fixThrowInitCauseCast(s1) + s3 := strings.ReplaceAll(s2, "class T", "class U") + want := []RewriteRecord{ + {Rule: "fixBooleanZeroLiteral", Phase: "class_source", BeforeHash: schedulerTestHash(s0), AfterHash: schedulerTestHash(s1)}, + {Rule: "fixThrowInitCauseCast", Phase: "class_source", BeforeHash: schedulerTestHash(s1), AfterHash: schedulerTestHash(s2)}, + {Rule: "scheduler-always-rule", Phase: "class_source", BeforeHash: schedulerTestHash(s2), AfterHash: schedulerTestHash(s3)}, + } + if !reflect.DeepEqual(onReport.RulesApplied, want) { + t.Fatalf("hashes/records differ from historical values:\n got=%+v\nwant=%+v", onReport.RulesApplied, want) + } + if len(onReport.Diagnostics) != 3 { + t.Fatalf("diagnostic count = %d, want 3: %+v", len(onReport.Diagnostics), onReport.Diagnostics) + } +} + +func TestRewriteSchedulerHashesEachStateOnce(t *testing.T) { + t.Setenv("JDEC_REWRITE_SCHEDULER_OFF", "") + report := &DecompileResult{} + d := &ClassObjectDumper{ + options: DecompileOptions{Mode: Compatibility}, + report: report, + } + first := d.sourceRewrite("scheduler-hash-a", "class_source", "A", func(string) string { return "B" }) + if first != "B" { + t.Fatalf("first rewrite = %q", first) + } + noop := d.sourceRewrite("scheduler-hash-noop", "class_source", first, func(source string) string { return source }) + if noop != first { + t.Fatalf("no-op rewrite changed source: %q", noop) + } + cycle := d.sourceRewrite("scheduler-hash-b", "class_source", first, func(string) string { return "A" }) + if cycle != first || len(report.RulesApplied) != 1 { + t.Fatalf("cycle was not rejected: %q %+v", cycle, report) + } + if got := d.rewriteSchedulerStats.HashComputations; got != 2 { + t.Fatalf("SHA-256 computations = %d, want 2 (A and B each once)", got) + } + if got := len(d.rewriteHashes); got != 2 { + t.Fatalf("hash memo entries = %d, want 2", got) + } + if last := report.Diagnostics[len(report.Diagnostics)-1]; last.Code != "rewrite_cycle" { + t.Fatalf("cycle diagnostic = %+v", last) + } +} + +func TestRewriteSchedulerEnvironmentKillSwitch(t *testing.T) { + const source = "void f() {\n\tint var1 = 0;\n}\n" + run := func(env map[string]string) rewriteSchedulerMetrics { + t.Helper() + var stats rewriteSchedulerMetrics + if err := jdecenv.Run(env, func() error { + d := &ClassObjectDumper{options: DecompileOptions{Mode: Compatibility}} + _ = d.sourceRewrite("fixIntCmpBoolMaterializedLiteral", "class_source", source, fixIntCmpBoolMaterializedLiteral) + stats = d.rewriteSchedulerStats + return nil + }); err != nil { + t.Fatal(err) + } + return stats + } + if got := run(map[string]string{}); got != (rewriteSchedulerMetrics{Considered: 1, Skipped: 1}) { + t.Fatalf("default scheduler stats = %+v, want one skip", got) + } + if got := run(map[string]string{"JDEC_REWRITE_SCHEDULER_OFF": "1"}); got != (rewriteSchedulerMetrics{Considered: 1, Candidates: 1, Invoked: 1}) { + t.Fatalf("killed scheduler stats = %+v, want unconditional invocation", got) + } +} + +func TestRewriteSchedulerRebuildsApplicabilityAfterAcceptedRewrite(t *testing.T) { + t.Setenv("JDEC_REWRITE_SCHEDULER_OFF", "") + t.Setenv("JDEC_INT_CMP_BOOL_LIT_OFF", "") + source := "void f() {\n\tint var1 = 0;\n}\n" + d := &ClassObjectDumper{options: DecompileOptions{Mode: Compatibility}} + + // Prime the index with "!= (0)) absent". + skipped := d.sourceRewrite("fixIntCmpBoolMaterializedLiteral", "class_source", source, fixIntCmpBoolMaterializedLiteral) + if skipped != source { + t.Fatalf("rule changed a source with no literal trigger: %q", skipped) + } + if d.rewriteSchedulerStats.Skipped != 1 || d.rewriteSchedulerStats.Invoked != 0 { + t.Fatalf("expected one skip before mutation: %+v", d.rewriteSchedulerStats) + } + + // An accepted rewrite must invalidate the old index. + mutated := d.sourceRewrite("scheduler-inject-literal", "class_source", source, func(text string) string { + return text + "if ((var1) == ((2) != (0))){\n}\n" + }) + if mutated == source { + t.Fatal("injection rewrite did not change source") + } + changed := d.sourceRewrite("fixIntCmpBoolMaterializedLiteral", "class_source", mutated, fixIntCmpBoolMaterializedLiteral) + if changed == mutated { + t.Fatal("stale applicability index skipped a now-applicable rule") + } + if !strings.Contains(changed, "(var1) == (2)") { + t.Fatalf("rewrite did not collapse the materialized literal:\n%s", changed) + } + if d.rewriteSchedulerStats.Invoked != 2 { + t.Fatalf("invocation count = %d, want 2 (injection + materialized literal)", d.rewriteSchedulerStats.Invoked) + } +} + +func TestRewriteSchedulerNearMissPipelineMetrics(t *testing.T) { + t.Setenv("JDEC_REWRITE_SCHEDULER_OFF", "") + fixtures := schedulerRuleFixtures() + source := syntheticSchedulerNearMissSource() + d := &ClassObjectDumper{options: DecompileOptions{Mode: Compatibility}} + for _, fixture := range fixtures { + t.Setenv(fixture.offFlag, "") + if got := d.sourceRewrite(fixture.id, fixture.phase, source, fixture.rule); got != source { + t.Fatalf("%s changed a near-miss pipeline source", fixture.id) + } + } + want := rewriteSchedulerMetrics{Considered: len(fixtures), Skipped: len(fixtures)} + if d.rewriteSchedulerStats != want { + t.Fatalf("near-miss metrics = %+v, want %+v", d.rewriteSchedulerStats, want) + } +} + +func syntheticSchedulerNearMissSource() string { + unit := "class Synthetic {\n" + + "\tint field = 0;\n" + + "\tvoid method(int var0) {\n" + + "\t\tint var1 = var0;\n" + + "\t\tvar1 = var1 + 1;\n" + + "\t\tif ((var1) > (0)){\n" + + "\t\t\tvar1 = var1 - 1;\n" + + "\t\t}\n" + + "\t}\n" + + "}\n" + return strings.Repeat(unit, 512) +} + +func TestRewriteSchedulerDecompileEquivalence(t *testing.T) { + paths := []string{ + "testdata/regression/SwitchThrowingDefaultBreakSeed.class", + "testdata/regression/TryBreakReturnSeed.class", + "testdata/regression/ThrowTypeVarCastSeed.class", + "testdata/GenericMessageEndpoint.class", + "testdata/regression/ConnPoolByRoute.class", + "testdata/regression/XStream.class", + "testdata/regression/CodecEncoding.class", + "testdata/regression/TwoDigitYear.class", + "testdata/regression/ExceptionSentinelSeed.class", + "testdata/regression/FactoryReturnRawBridgeSeed.class", + "testdata/regression/SpringDataBufferEncoder.class", + "testdata/regression/Transmitter.class", + "testdata/regression/ExchangeFinder.class", + "testdata/regression/RealConnection.class", + "testdata/regression/Http2Connection.class", + "testdata/regression/Http2Stream.class", + "testdata/regression/DiskLruCache$3.class", + "testdata/regression/PublicSuffixDatabase.class", + } + for _, path := range paths { + path := path + t.Run(path, func(t *testing.T) { + raw, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + on, onErr := DecompileWithOptions(raw, DecompileOptions{ + Mode: Compatibility, + EnvSnapshot: map[string]string{}, + }) + off, offErr := DecompileWithOptions(raw, DecompileOptions{ + Mode: Compatibility, + EnvSnapshot: map[string]string{"JDEC_REWRITE_SCHEDULER_OFF": "1"}, + }) + if (onErr == nil) != (offErr == nil) { + t.Fatalf("error presence diverged: on=%v off=%v", onErr, offErr) + } + if onErr != nil && onErr.Error() != offErr.Error() { + t.Fatalf("error text diverged: on=%v off=%v", onErr, offErr) + } + if on.Source != off.Source { + t.Fatalf("source diverged:\n on=%q\noff=%q", on.Source, off.Source) + } + if on.Status != off.Status { + t.Fatalf("status diverged: on=%q off=%q", on.Status, off.Status) + } + if !reflect.DeepEqual(on.RulesApplied, off.RulesApplied) { + t.Fatalf("rewrite records diverged:\n on=%+v\noff=%+v", on.RulesApplied, off.RulesApplied) + } + if !reflect.DeepEqual(on.Diagnostics, off.Diagnostics) { + t.Fatalf("diagnostics diverged:\n on=%+v\noff=%+v", on.Diagnostics, off.Diagnostics) + } + if !reflect.DeepEqual(on.StubMethods, off.StubMethods) { + t.Fatalf("stub methods diverged:\n on=%+v\noff=%+v", on.StubMethods, off.StubMethods) + } + }) + } +} + +func TestRewriteSchedulerSkipsInapplicableRulesOnRealClass(t *testing.T) { + t.Setenv("JDEC_REWRITE_SCHEDULER_OFF", "") + raw, err := os.ReadFile("testdata/regression/SwitchThrowingDefaultBreakSeed.class") + if err != nil { + t.Fatal(err) + } + obj, err := Parse(raw) + if err != nil { + t.Fatal(err) + } + d := NewClassObjectDumper(obj) + d.options = DecompileOptions{Mode: Compatibility, TargetSourceVersion: 8, EnvSnapshot: map[string]string{}} + d.report = &DecompileResult{} + source, err := d.DumpClass() + if err != nil { + t.Fatal(err) + } + if source == "" { + t.Fatal("empty class source") + } + stats := d.rewriteSchedulerStats + t.Logf("rewrite scheduler stats for SwitchThrowingDefaultBreakSeed: %+v", stats) + if stats.Considered < len(classSourceRewriteOrder) { + t.Fatalf("considered = %d, want at least %d", stats.Considered, len(classSourceRewriteOrder)) + } + if stats.Skipped == 0 { + t.Fatalf("no rule was prefilttered on a class-source pipeline: %+v", stats) + } + if stats.Candidates+stats.Skipped != stats.Considered { + t.Fatalf("candidate/skip accounting = %+v", stats) + } + if stats.Invoked > stats.Candidates { + t.Fatalf("invoked exceeds candidates: %+v", stats) + } +} + +// BenchmarkDecompileSchedulerPipeline measures the whole Compatibility pass on +// a real class. Both variants produce the same source and rewrite records. +func BenchmarkDecompileSchedulerPipeline(b *testing.B) { + raw, err := os.ReadFile("testdata/regression/RealConnection.class") + if err != nil { + b.Fatal(err) + } + for _, disabled := range []bool{true, false} { + name := "scheduler_on" + env := map[string]string{} + if disabled { + name = "scheduler_off" + env = map[string]string{"JDEC_REWRITE_SCHEDULER_OFF": "1"} + } + b.Run(name, func(b *testing.B) { + b.ReportAllocs() + for i := 0; i < b.N; i++ { + if _, err := DecompileWithOptions(raw, DecompileOptions{ + Mode: Compatibility, + EnvSnapshot: env, + }); err != nil { + b.Fatal(err) + } + } + }) + } +} + +func BenchmarkRewriteSchedulerNearMissPipeline(b *testing.B) { + for _, fixture := range schedulerRuleFixtures() { + b.Setenv(fixture.offFlag, "") + } + b.Setenv("JDEC_REWRITE_SCHEDULER_OFF", "") + source := syntheticSchedulerNearMissSource() + fixtures := schedulerRuleFixtures() + for _, disabled := range []bool{true, false} { + name := "scheduler_on" + if disabled { + name = "scheduler_off" + } + b.Run(name, func(b *testing.B) { + b.ReportAllocs() + var stats rewriteSchedulerMetrics + for i := 0; i < b.N; i++ { + d := &ClassObjectDumper{ + options: DecompileOptions{Mode: Compatibility}, + rewriteSchedulerDisabled: disabled, + } + for _, fixture := range fixtures { + _ = d.sourceRewrite(fixture.id, fixture.phase, source, fixture.rule) + } + stats = d.rewriteSchedulerStats + } + b.ReportMetric(float64(stats.Considered), "considered") + b.ReportMetric(float64(stats.Candidates), "candidates") + b.ReportMetric(float64(stats.Invoked), "invoked") + b.ReportMetric(float64(stats.Skipped), "skipped") + }) + } +} diff --git a/classparser/t06_attr_validate.go b/classparser/t06_attr_validate.go index 4f291562..a4702d48 100644 --- a/classparser/t06_attr_validate.go +++ b/classparser/t06_attr_validate.go @@ -174,6 +174,14 @@ func validateCodeLength(codeLength int) error { Msg: "code_length must be greater than 0", } } + if codeLength > 65535 { + return &ClassParseError{ + Code: ParseCodeCodeLength, + Stage: "code", + Field: "code_length", + Msg: fmt.Sprintf("code_length %d exceeds JVM limit 65535", codeLength), + } + } return nil } diff --git a/classparser/t23_archive_test.go b/classparser/t23_archive_test.go index 4d331e42..51bbaa3d 100644 --- a/classparser/t23_archive_test.go +++ b/classparser/t23_archive_test.go @@ -4,10 +4,13 @@ import ( "archive/zip" "bytes" "context" + "encoding/binary" "strings" "testing" + "github.com/yaklang/javajive/classparser/classfilebuilder" "github.com/yaklang/javajive/internal/filesys" + "github.com/yaklang/javajive/internal/workbudget" ) func t23Zip(t *testing.T, files map[string][]byte) []byte { @@ -36,6 +39,140 @@ func t23MustResource(t *testing.T, err error) { } } +func t23ArchiveClass(t *testing.T, name string) []byte { + t.Helper() + class := classfilebuilder.NewClass(name, "java/lang/Object", 0x0021) + objectInit, err := class.Pool().Methodref("java/lang/Object", "", "()V") + if err != nil { + t.Fatal(err) + } + class.AddMethod(0x0001, "", "()V").Code(). + Load(classfilebuilder.RefLocal, 0). + CP(classfilebuilder.INVOKESPECIAL, objectInit). + Emit(classfilebuilder.RETURN) + raw, err := class.Bytes() + if err != nil { + t.Fatal(err) + } + return raw +} + +func TestArchiveClassOutcomeContainsFailures(t *testing.T) { + valid := t23ArchiveClass(t, "Valid") + future := bytes.Clone(valid) + future[6], future[7] = 0, byte(MaxSupportedClassMajor+1) + raw := t23Zip(t, map[string][]byte{ + "Valid.class": valid, + "Malformed.class": {0xca, 0xfe, 0xba, 0xbe}, + "Future.class": future, + }) + zipFS, err := filesys.NewZipFSFromString(string(raw)) + if err != nil { + t.Fatal(err) + } + defer zipFS.Close() + jar := NewJarFS(zipFS) + + complete, err := jar.ReadClassOutcome("Valid.class") + if err != nil || complete.Status != ClassDecompileComplete || !bytes.Contains(complete.Source, []byte("class Valid")) { + t.Fatalf("valid outcome = status %q err %v source %q", complete.Status, err, complete.Source) + } + for _, test := range []struct { + name string + code string + prefix string + }{ + {"Malformed.class", "class_parse_failed", "// decompile parse failed for Malformed.class:"}, + {"Future.class", "unsupported_classfile_version", "// decompile fallback for Future.class:"}, + } { + outcome, err := jar.ReadClassOutcome(test.name) + if err != nil || outcome.Status != ClassDecompileFallback || len(outcome.Diagnostics) != 1 || outcome.Diagnostics[0].Code != test.code { + t.Fatalf("%s outcome = %+v err %v", test.name, outcome, err) + } + if !bytes.HasPrefix(outcome.Source, []byte(test.prefix)) { + t.Fatalf("%s source marker = %q, want prefix %q", test.name, outcome.Source, test.prefix) + } + } +} + +func TestClassFallbackTextIsSingleLineAndBounded(t *testing.T) { + outcome := classFallbackOutcome("evil\nName.class", "class_decompile_panic", strings.Repeat("x", 600)+"\nclass Injected {}") + if strings.Count(string(outcome.Source), "\n") != 1 || bytes.Contains(outcome.Source, []byte("class Injected")) { + t.Fatalf("fallback source = %q", outcome.Source) + } + if len([]rune(outcome.Diagnostics[0].Message)) != 480 { + t.Fatalf("diagnostic length = %d, want 480", len([]rune(outcome.Diagnostics[0].Message))) + } +} + +func TestArchiveClassOutcomePreservesMethodStubs(t *testing.T) { + object, err := Parse(readValidationSeed(t)) + if err != nil { + t.Fatal(err) + } + var code *CodeAttribute + for _, method := range object.Methods { + if int(method.NameIndex) == 0 || int(method.NameIndex) > len(object.ConstantPool) { + continue + } + nameInfo, ok := object.ConstantPool[method.NameIndex-1].(*ConstantUtf8Info) + if !ok || nameInfo.Value != "run" { + continue + } + for _, attribute := range method.Attributes { + if candidate, ok := attribute.(*CodeAttribute); ok { + code = candidate + } + } + } + if code == nil { + t.Fatal("seed run method has no Code attribute") + } + corrupted := false + for i := 0; i+2 < len(code.Code); i++ { + if code.Code[i] == 0xb2 { + binary.BigEndian.PutUint16(code.Code[i+1:i+3], 0xffff) + corrupted = true + break + } + } + if !corrupted { + t.Fatal("seed run method has no getstatic operand to corrupt") + } + archive := t23Zip(t, map[string][]byte{"Partial.class": object.Bytes()}) + zipFS, err := filesys.NewZipFSFromString(string(archive)) + if err != nil { + t.Fatal(err) + } + defer zipFS.Close() + outcome, err := NewJarFS(zipFS).ReadClassOutcome("Partial.class") + if err != nil || outcome.Status != ClassDecompilePartial || len(outcome.StubMethods) == 0 || !bytes.Contains(outcome.Source, []byte(DecompileStubMarker)) { + t.Fatalf("partial outcome = %+v err %v source %q", outcome, err, outcome.Source) + } +} + +func TestArchiveClassPanicContainmentPreservesResourceErrors(t *testing.T) { + jar := &JarFS{} + var work *workbudget.Budget + outcome, err := jar.containClassDecompile("Panic.class", &work, func() (ClassDecompileOutcome, error) { + panic("fixture panic") + }) + if err != nil || outcome.Status != ClassDecompileFallback || len(outcome.Diagnostics) != 1 || outcome.Diagnostics[0].Code != "class_decompile_panic" { + t.Fatalf("panic outcome = %+v err %v", outcome, err) + } + + work = workbudget.New(context.Background(), Limits{MaxRequestWork: 1}) + if err := work.Charge(workbudget.CounterRequestWork, 2); err == nil { + t.Fatal("fixture did not exhaust resource budget") + } + outcome, err = jar.containClassDecompile("Resource.class", &work, func() (ClassDecompileOutcome, error) { + panic("after resource failure") + }) + if err == nil || !workbudget.Is(err) || outcome.Status != "" { + t.Fatalf("resource panic outcome = %+v err %v", outcome, err) + } +} + func TestT23_C01_ExpandedPositiveControl(t *testing.T) { raw := t23Zip(t, map[string][]byte{"hello.txt": []byte("hello")}) limits := filesys.ArchiveLimits{MaxArchiveEntries: 32, MaxArchiveEntryBytes: 1 << 20, MaxArchiveTotalBytes: 1 << 20, MaxArchiveDepth: 8} diff --git a/cmd/javajive/inspect.go b/cmd/javajive/inspect.go index 66323936..fadb3a1c 100644 --- a/cmd/javajive/inspect.go +++ b/cmd/javajive/inspect.go @@ -20,7 +20,7 @@ func cmdInspectTo(args []string, stdout io.Writer) error { fs.SetOutput(io.Discard) fs.Usage = func() { fmt.Fprintln(os.Stderr, "usage: javajive inspect INPUT --format json [--disassembly=false]") - fmt.Fprintln(os.Stderr, "Read-only inventory and best-effort analysis of DEX, APK, JAR, and WAR artifacts.") + fmt.Fprintln(os.Stderr, "Read-only inventory and best-effort analysis of Java archives, JDK runtime images, and Android containers.") fs.PrintDefaults() } format := fs.String("format", "json", "report format (json)") diff --git a/cmd/javajive/jimage2jar.go b/cmd/javajive/jimage2jar.go new file mode 100644 index 00000000..3468b34b --- /dev/null +++ b/cmd/javajive/jimage2jar.go @@ -0,0 +1,29 @@ +package main + +import ( + "fmt" + "os" + + jj "github.com/yaklang/javajive" +) + +func cmdJImageToJar(args []string) error { + fs := newFlagSet("jimage2jar") + fs.Usage = func() { + fmt.Fprintln(fs.Output(), "usage: javajive jimage2jar -o output.jar ") + fmt.Fprintln(fs.Output(), "Convert a JDK runtime image into a package-layout JAR view.") + fs.PrintDefaults() + } + out := fs.String("o", "", "output JAR path (required)") + if err := fs.Parse(args); err != nil { + return err + } + if fs.NArg() != 1 || *out == "" { + return fmt.Errorf("jimage2jar requires -o and one input path\nusage: javajive jimage2jar -o output.jar ") + } + if err := jj.JImageToJar(fs.Arg(0), *out); err != nil { + return err + } + fmt.Fprintf(os.Stderr, "converted JImage %q -> %q\n", fs.Arg(0), *out) + return nil +} diff --git a/cmd/javajive/main.go b/cmd/javajive/main.go index 552f109f..fa057782 100644 --- a/cmd/javajive/main.go +++ b/cmd/javajive/main.go @@ -1,6 +1,7 @@ -// Command javajive is a portable, pure-Go command line tool for working with Java -// artifacts: decompiling .class/.jar/.war files, inspecting class structure, and -// parsing/marshaling the Java serialization wire format. +// Command javajive is a portable, pure-Go command line tool for working with +// Java and Android artifacts: decompiling .class files and Java archives, +// translating DEX/APK/APKS/XAPK/APKM/AAB inputs, inspecting class structure, +// and parsing/marshaling the Java serialization wire format. package main import ( @@ -30,6 +31,8 @@ func main() { err = cmdDecompile(args) case "dex2jar", "d2j": err = cmdDexToJar(args) + case "jimage2jar", "i2j": + err = cmdJImageToJar(args) case "inspect", "analyze": err = cmdInspect(args) case "classinfo", "info": @@ -58,9 +61,10 @@ Usage: javajive [arguments] Commands: - decompile Decompile Java artifacts or the strict DEX 035 subset into Java source - dex2jar Convert the strict DEX 035 subset in a DEX/APK to a deterministic JAR - inspect Read-only inventory and best-effort analysis of DEX/APK/JAR/WAR input + decompile Decompile .class files, Java archives, JImage runtime images, or DEX/APK/APKS/XAPK/APKM/AAB input + dex2jar Convert DEX/APK/APKS/XAPK/APKM/AAB input to a deterministic JAR + jimage2jar Convert a JDK runtime image (lib/modules, .jimage) to a JAR view + inspect Read-only inventory and best-effort analysis of Java/Android artifacts classinfo Print the structure of a .class file (version, fields, methods) serial Java serialization tools (subcommands: tojson, fromjson) @@ -78,13 +82,17 @@ Run "javajive -h" for command-specific options. func cmdDecompile(args []string) error { fs := newFlagSet("decompile") fs.Usage = func() { - fmt.Fprintln(fs.Output(), "usage: javajive decompile [-o out] [-analysis-budget N] [--structured] ") - fmt.Fprintln(fs.Output(), "Decompile .class, archive, DEX, APK, or directory input; DEX/APK defaults to .src.") + fmt.Fprintln(fs.Output(), "usage: javajive decompile [-o out] [-analysis-budget N] [--structured] [--best-effort | --stub-methods-only] ") + fmt.Fprintln(fs.Output(), "Decompile .class, Java archives (.jar/.war/.ear/.aar/.par/.jmod/.zip), JDK runtime images (.jimage / lib/modules), DEX/APK/APKS/XAPK/APKM/AAB, or a directory of .class files.") + fmt.Fprintln(fs.Output(), "Android containers and DEX default to .src; --structured applies to Java archives and JImage.") + fmt.Fprintln(fs.Output(), "--best-effort applies full DEX/Android recovery; --stub-methods-only keeps the narrower recognized-method policy.") fs.PrintDefaults() } out := fs.String("o", "", "output file (for a .class) or directory (for archives/DEX/APK/dirs); default: stdout / .src") budget := fs.Int("analysis-budget", 0, "per-method analysis updates for very large generated methods (0 = default; >1000000 scales graph caps)") structured := fs.Bool("structured", false, "for archives: emit sources/, resources/, and preserved nested archives/ views") + bestEffort := fs.Bool("best-effort", false, "for DEX/Android: recover method/class failures and emit a traceable partial result") + stubMethodsOnly := fs.Bool("stub-methods-only", false, "for DEX/Android: only stub recognized unsupported methods") if err := fs.Parse(args); err != nil { return err } @@ -92,7 +100,7 @@ func cmdDecompile(args []string) error { return fmt.Errorf("-analysis-budget must be non-negative") } if fs.NArg() != 1 { - return fmt.Errorf("decompile requires exactly one input path\nusage: javajive decompile [-o out] ") + return fmt.Errorf("decompile requires exactly one input path\nusage: javajive decompile [-o out] [--best-effort | --stub-methods-only] ") } input := fs.Arg(0) @@ -105,31 +113,42 @@ func cmdDecompile(args []string) error { return decompileDir(input, *out, *budget) } - var magic [8]byte - file, err := os.Open(input) + kind, err := jj.ClassifyInputFile(input) if err != nil { return err } - read, readErr := io.ReadFull(file, magic[:]) - _ = file.Close() - if readErr != nil && readErr != io.ErrUnexpectedEOF { - return readErr - } - kind := jj.DetectInputKind(magic[:read]) - if kind == jj.InputDEX || kind == jj.InputZIP && strings.EqualFold(filepath.Ext(input), ".apk") { + + if jj.IsAndroidContainer(kind) { + if *structured { + return fmt.Errorf("--structured applies to Java archives, not %s input", kind) + } dst := *out if dst == "" { dst = input + ".src" } - if err := jj.DecompileDEXFileWithAnalysisBudget(input, dst, jj.DexOptions{}, *budget); err != nil { + if *bestEffort && *stubMethodsOnly { + return fmt.Errorf("--best-effort and --stub-methods-only are mutually exclusive") + } + policy := jj.DexFailureStrict + if *bestEffort { + policy = jj.DexFailureRecover + } else if *stubMethodsOnly { + policy = jj.DexFailureStubUnsupportedMethods + } + detailed, err := jj.DecompileDEXFileWithPolicy(input, dst, jj.DexConvertOptions{Policy: policy}, *budget) + if err != nil { return err } - fmt.Fprintf(os.Stderr, "decompiled DEX input %q -> %q\n", input, dst) + fmt.Fprintf(os.Stderr, "decompiled %s input %q -> %q (status=%s, %d warnings)\n", + kind, input, dst, detailed.Status, detailed.Summary.Warnings) return nil } - switch strings.ToLower(filepath.Ext(input)) { - case ".jar", ".war", ".zip", ".jmod", ".ear": + if *bestEffort || *stubMethodsOnly { + return fmt.Errorf("--best-effort and --stub-methods-only apply only to DEX/Android input, got %s", kind) + } + + if jj.IsJavaArchiveContainer(kind) { dst := *out if dst == "" { dst = input + ".src" @@ -142,33 +161,33 @@ func cmdDecompile(args []string) error { if err != nil { return err } - fmt.Fprintf(os.Stderr, "decompiled archive %q -> %q (%d entries, %d nested archives)\n", - input, dst, len(report.Entries), len(report.Archives)) + fmt.Fprintf(os.Stderr, "decompiled %s archive %q -> %q (%d entries, %d nested archives)\n", + kind, input, dst, len(report.Entries), len(report.Archives)) return nil } if err := jj.DecompileArchiveWithAnalysisBudget(input, dst, *budget); err != nil { return err } - fmt.Fprintf(os.Stderr, "decompiled archive %q -> %q\n", input, dst) + fmt.Fprintf(os.Stderr, "decompiled %s archive %q -> %q\n", kind, input, dst) return nil - default: - data, err := os.ReadFile(input) - if err != nil { - return err - } - src, err := decompileClassBytes(data, *budget) - if err != nil { - return err - } - if *out == "" { - fmt.Print(src) - if !strings.HasSuffix(src, "\n") { - fmt.Println() - } - return nil + } + + data, err := os.ReadFile(input) + if err != nil { + return err + } + src, err := decompileClassBytes(data, *budget) + if err != nil { + return err + } + if *out == "" { + fmt.Print(src) + if !strings.HasSuffix(src, "\n") { + fmt.Println() } - return os.WriteFile(*out, []byte(src), 0o644) + return nil } + return os.WriteFile(*out, []byte(src), 0o644) } // decompileClassBytes uses the explicit-budget path only when the caller asked @@ -226,23 +245,40 @@ func decompileDir(dir, out string, budget int) error { func cmdDexToJar(args []string) error { fs := newFlagSet("dex2jar") fs.Usage = func() { - fmt.Fprintln(fs.Output(), "usage: javajive dex2jar -o output.jar input.dex|input.apk") - fmt.Fprintln(fs.Output(), "Convert the strict DEX 035 subset in a raw DEX or APK to a deterministic JAR.") + fmt.Fprintln(fs.Output(), "usage: javajive dex2jar -o output.jar [--best-effort | --stub-methods-only] input.dex|input.apk|input.apks|input.xapk|input.apkm|input.aab") + fmt.Fprintln(fs.Output(), "Convert the supported DEX subset in a DEX/APK/APKS/XAPK/APKM/AAB input to a deterministic JAR.") + fmt.Fprintln(fs.Output(), "--best-effort adds class-shell recovery; --stub-methods-only only stubs recognized unsupported methods. Input and resource failures still abort.") fs.PrintDefaults() } out := fs.String("o", "", "output JAR path (required)") + bestEffort := fs.Bool("best-effort", false, "recover method/class failures and emit a traceable partial JAR") + stubMethodsOnly := fs.Bool("stub-methods-only", false, "only stub recognized unsupported methods") if err := fs.Parse(args); err != nil { return err } if fs.NArg() != 1 || *out == "" { - return fmt.Errorf("dex2jar requires -o and one input path\nusage: javajive dex2jar -o output.jar input.dex|input.apk") + return fmt.Errorf("dex2jar requires -o and one input path\nusage: javajive dex2jar -o output.jar [--best-effort | --stub-methods-only] input.dex|input.apk|input.apks|input.xapk|input.apkm|input.aab") + } + kind, _ := jj.ClassifyInputFile(fs.Arg(0)) + if kind == "" { + kind = jj.ContainerUnknown + } + if *bestEffort && *stubMethodsOnly { + return fmt.Errorf("--best-effort and --stub-methods-only are mutually exclusive") + } + policy := jj.DexFailureStrict + if *bestEffort { + policy = jj.DexFailureRecover + } else if *stubMethodsOnly { + policy = jj.DexFailureStubUnsupportedMethods } - report, err := jj.DexFileToJar(fs.Arg(0), *out, jj.DexOptions{}) + detailed, err := jj.DexFileToJarWithOptions(fs.Arg(0), *out, jj.DexConvertOptions{Policy: policy}) if err != nil { return err } - fmt.Fprintf(os.Stderr, "converted %q -> %q (%d DEX files, %d classes, %d/%d methods translated, %d warnings)\n", - fs.Arg(0), *out, report.DEXFiles, report.Classes, report.TranslatedMethods, report.Methods, report.Warnings) + report := detailed.Summary + fmt.Fprintf(os.Stderr, "converted %s %q -> %q (status=%s, %d DEX files, %d classes, %d/%d methods translated, %d warnings)\n", + kind, fs.Arg(0), *out, detailed.Status, report.DEXFiles, report.Classes, report.TranslatedMethods, report.Methods, report.Warnings) return nil } diff --git a/cmd/javajive/main_test.go b/cmd/javajive/main_test.go index 9f604077..a16c5a4a 100644 --- a/cmd/javajive/main_test.go +++ b/cmd/javajive/main_test.go @@ -1,11 +1,16 @@ package main import ( + "archive/zip" + "bytes" "flag" + "io" "os" "path/filepath" "strings" "testing" + + "github.com/yaklang/javajive/internal/jimagefixture" ) func TestCmdDexToJarHelp(t *testing.T) { @@ -30,7 +35,7 @@ func TestCmdDexToJarRejectsMagicWithoutOutput(t *testing.T) { if err := os.WriteFile(input, []byte("not dex"), 0o644); err != nil { t.Fatal(err) } - if err := cmdDexToJar([]string{"-o", output, input}); err == nil || !strings.Contains(err.Error(), "unsupported input magic") { + if err := cmdDexToJar([]string{"-o", output, input}); err == nil || !strings.Contains(err.Error(), "unsupported DEX input") { t.Fatalf("cmdDexToJar error = %v", err) } if _, err := os.Stat(output); !os.IsNotExist(err) { @@ -38,6 +43,79 @@ func TestCmdDexToJarRejectsMagicWithoutOutput(t *testing.T) { } } +func TestCmdDecompileJImage(t *testing.T) { + classBytes, err := os.ReadFile(filepath.Join("..", "..", "classparser", "testdata", "invisible_anno.class")) + if err != nil { + t.Fatal(err) + } + image, err := jimagefixture.Build([]jimagefixture.Entry{ + {Path: "/test/InvisibleAnnoSeed.class", Data: classBytes}, + }) + if err != nil { + t.Fatal(err) + } + src := filepath.Join(t.TempDir(), "modules") + if err := os.WriteFile(src, image, 0o644); err != nil { + t.Fatal(err) + } + outDir := t.TempDir() + if err := cmdDecompile([]string{"-o", outDir, src}); err != nil { + t.Fatalf("cmdDecompile JImage: %v", err) + } + source, err := os.ReadFile(filepath.Join(outDir, "InvisibleAnnoSeed.java")) + if err != nil { + t.Fatalf("read decompiled source: %v", err) + } + if !strings.Contains(string(source), "class InvisibleAnnoSeed") { + t.Fatalf("unexpected source:\n%s", source) + } +} + +func TestCmdJImageToJar(t *testing.T) { + classBytes, err := os.ReadFile(filepath.Join("..", "..", "classparser", "testdata", "invisible_anno.class")) + if err != nil { + t.Fatal(err) + } + image, err := jimagefixture.Build([]jimagefixture.Entry{ + {Path: "/test/InvisibleAnnoSeed.class", Data: classBytes}, + }) + if err != nil { + t.Fatal(err) + } + dir := t.TempDir() + src := filepath.Join(dir, "modules") + if err := os.WriteFile(src, image, 0o644); err != nil { + t.Fatal(err) + } + dst := filepath.Join(dir, "jdk.jar") + if err := cmdJImageToJar([]string{"-o", dst, src}); err != nil { + t.Fatalf("cmdJImageToJar: %v", err) + } + raw, err := os.ReadFile(dst) + if err != nil { + t.Fatal(err) + } + reader, err := zip.NewReader(bytes.NewReader(raw), int64(len(raw))) + if err != nil { + t.Fatal(err) + } + if len(reader.File) != 1 || reader.File[0].Name != "InvisibleAnnoSeed.class" { + t.Fatalf("JAR entries = %#v", reader.File) + } + stream, err := reader.File[0].Open() + if err != nil { + t.Fatal(err) + } + body, err := io.ReadAll(stream) + stream.Close() + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(body, classBytes) { + t.Fatal("converted class bytes differ") + } +} + func TestCmdDecompileAnalysisBudget(t *testing.T) { classPath, err := filepath.Abs(filepath.Join("..", "..", "classparser", "testdata", "invisible_anno.class")) if err != nil { @@ -59,6 +137,10 @@ func TestCmdDecompileAnalysisBudget(t *testing.T) { !strings.Contains(err.Error(), "non-negative") { t.Fatalf("negative budget error = %v", err) } + if err := cmdDecompile([]string{"--best-effort", classPath}); err == nil || + !strings.Contains(err.Error(), "apply only to DEX/Android") { + t.Fatalf("non-Android recovery policy error = %v", err) + } // Directory inputs route every class through the same budgeted path. inDir := t.TempDir() diff --git a/dex2jar/acceptance_success_test.go b/dex2jar/acceptance_success_test.go index deb5dca9..676c3da2 100644 --- a/dex2jar/acceptance_success_test.go +++ b/dex2jar/acceptance_success_test.go @@ -56,8 +56,6 @@ func TestAcceptedRawDEXCorpus(t *testing.T) { t.Fatalf("parsed class = %q with %d fields and %d methods", parsed.GetClassName(), len(parsed.Fields), len(parsed.Methods)) } - verifyAndExecute(t, classes, "accept.Arithmetic") - inputPath := filepath.Join(t.TempDir(), "arithmetic.input") if err := os.WriteFile(inputPath, raw, 0o644); err != nil { t.Fatal(err) @@ -126,9 +124,6 @@ func TestAcceptedMultidexAPKCorpus(t *testing.T) { t.Fatalf("parsed %s = %q with %d methods", entry, parsed.GetClassName(), len(parsed.Methods)) } } - verifyAndExecute(t, classes, "accept.apk.Primary") - verifyAndExecute(t, classes, "accept.apk.Secondary") - sourceDir := filepath.Join(t.TempDir(), "source") if err := javajive.DecompileDEXFile(fixture, sourceDir, javajive.DexOptions{}); err != nil { t.Fatalf("DecompileDEXFile(APK): %v", err) @@ -218,6 +213,31 @@ func readAcceptedJar(t *testing.T, jar []byte, wantNames []string) map[string][] return classes } +func TestAcceptedCorpusJVMOracle(t *testing.T) { + fixtures := []struct { + file string + inventory []string + mains []string + }{ + {file: "arithmetic.dex", inventory: []string{"META-INF/MANIFEST.MF", "accept/Arithmetic.class"}, mains: []string{"accept.Arithmetic"}}, + {file: "multidex.apk", inventory: []string{"META-INF/MANIFEST.MF", "accept/apk/Primary.class", "accept/apk/Secondary.class"}, mains: []string{"accept.apk.Primary", "accept.apk.Secondary"}}, + } + for _, fixture := range fixtures { + raw, err := os.ReadFile(filepath.Join("testdata", "accept", fixture.file)) + if err != nil { + t.Fatal(err) + } + jar, _, err := dex2jar.DexToJar(raw, dex2jar.Options{}) + if err != nil { + t.Fatal(err) + } + classes := readAcceptedJar(t, jar, fixture.inventory) + for _, mainClass := range fixture.mains { + verifyAndExecute(t, classes, mainClass) + } + } +} + func verifyAndExecute(t *testing.T, classes map[string][]byte, mainClass string) { t.Helper() java, err := exec.LookPath("java") diff --git a/dex2jar/container_test.go b/dex2jar/container_test.go new file mode 100644 index 00000000..c7a6c1d9 --- /dev/null +++ b/dex2jar/container_test.go @@ -0,0 +1,161 @@ +package dex2jar_test + +import ( + "archive/zip" + "bytes" + "os" + "path/filepath" + "sort" + "strings" + "testing" + + "github.com/yaklang/javajive/dex2jar" + "github.com/yaklang/javajive/internal/jimagefixture" +) + +func TestDexToJarAPKS(t *testing.T) { + apk, err := os.ReadFile(filepath.Join("testdata", "accept", "multidex.apk")) + if err != nil { + t.Fatal(err) + } + resourceSplit := makeAPKEntries(t, map[string][]byte{"res/raw/config.txt": []byte("config")}) + bundle := makeAPKEntries(t, map[string][]byte{ + "base.apk": apk, + "split.apk": resourceSplit, + }) + jar, report, err := dex2jar.DexToJar(bundle, dex2jar.Options{}) + if err != nil { + t.Fatalf("DexToJar: %v", err) + } + classes := jarClassNames(t, jar) + if len(classes) != report.Classes || len(classes) < 2 { + t.Fatalf("classes = %v, report.Classes = %d", classes, report.Classes) + } + if report.DEXFiles != 2 { + t.Fatalf("DEX files = %d, want 2", report.DEXFiles) + } +} + +func TestDexToJarAAB(t *testing.T) { + dex, err := os.ReadFile(filepath.Join("testdata", "accept", "arithmetic.dex")) + if err != nil { + t.Fatal(err) + } + bundle := makeAPKEntries(t, map[string][]byte{ + "BundleConfig.pb": {1}, + "base/dex/classes.dex": dex, + }) + jar, report, err := dex2jar.DexToJar(bundle, dex2jar.Options{}) + if err != nil { + t.Fatalf("DexToJar: %v", err) + } + classes := jarClassNames(t, jar) + if len(classes) != 1 || classes[0] != "accept/Arithmetic.class" { + t.Fatalf("classes = %v", classes) + } + if report.DEXFiles != 1 || report.Classes != 1 { + t.Fatalf("report = %#v", report) + } +} + +func TestDexToJarXAPK(t *testing.T) { + apk, err := os.ReadFile(filepath.Join("testdata", "accept", "multidex.apk")) + if err != nil { + t.Fatal(err) + } + bundle := makeAPKEntries(t, map[string][]byte{ + "manifest.json": []byte(`{"xapk_version":2}`), + "base.apk": apk, + }) + jar, report, err := dex2jar.DexToJar(bundle, dex2jar.Options{}) + if err != nil { + t.Fatalf("DexToJar: %v", err) + } + if len(jarClassNames(t, jar)) != report.Classes || report.Classes < 2 { + t.Fatalf("report = %#v", report) + } +} + +func TestDexFileToJarAPKSAndClassification(t *testing.T) { + apk, err := os.ReadFile(filepath.Join("testdata", "accept", "multidex.apk")) + if err != nil { + t.Fatal(err) + } + bundle := makeAPKEntries(t, map[string][]byte{"base.apk": apk}) + src := filepath.Join(t.TempDir(), "app.apks") + if err := os.WriteFile(src, bundle, 0o644); err != nil { + t.Fatal(err) + } + kind, err := dex2jar.ClassifyInputFile(src) + if err != nil { + t.Fatalf("ClassifyInputFile: %v", err) + } + if kind != dex2jar.ContainerAPKS { + t.Fatalf("kind = %q, want apks", kind) + } + dst := filepath.Join(t.TempDir(), "classes.jar") + report, err := dex2jar.DexFileToJar(src, dst, dex2jar.Options{}) + if err != nil { + t.Fatalf("DexFileToJar: %v", err) + } + if report.Classes < 2 { + t.Fatalf("report = %#v", report) + } + if _, err := os.Stat(dst); err != nil { + t.Fatalf("output JAR: %v", err) + } +} + +func TestClassifyInputJMOD(t *testing.T) { + payload := makeAPK(t, []byte("dex\n035\x00")) + jmod := append([]byte{'J', 'M', 1, 0}, payload...) + if got := dex2jar.ClassifyInput(jmod, "java.base.jmod"); got != dex2jar.ContainerJMOD { + t.Fatalf("ClassifyInput = %q, want jmod", got) + } + if got := dex2jar.DetectInputKind(jmod); got != dex2jar.InputJMOD { + t.Fatalf("DetectInputKind = %v, want InputJMOD", got) + } +} + +func TestClassifyInputJImage(t *testing.T) { + data, err := jimagefixture.Build([]jimagefixture.Entry{ + {Path: "/test/demo/Foo.class", Data: []byte{0xca, 0xfe, 0xba, 0xbe}}, + }) + if err != nil { + t.Fatal(err) + } + if got := dex2jar.ClassifyInput(data, "modules"); got != dex2jar.ContainerJImage { + t.Fatalf("ClassifyInput = %q, want jimage", got) + } + if got := dex2jar.DetectInputKind(data); got != dex2jar.InputJIMAGE { + t.Fatalf("DetectInputKind = %v, want InputJIMAGE", got) + } + if _, _, err := dex2jar.DexToJar(data, dex2jar.Options{}); err == nil || !strings.Contains(err.Error(), "unsupported DEX input") { + t.Fatalf("DexToJar error = %v", err) + } +} + +func TestDexToJarRejectsJMOD(t *testing.T) { + payload := makeAPK(t, []byte("dex\n035\x00")) + jmod := append([]byte{'J', 'M', 1, 0}, payload...) + _, _, err := dex2jar.DexToJar(jmod, dex2jar.Options{}) + if err == nil || !strings.Contains(err.Error(), "unsupported DEX input") { + t.Fatalf("error = %v", err) + } +} + +func jarClassNames(t *testing.T, raw []byte) []string { + t.Helper() + reader, err := zip.NewReader(bytes.NewReader(raw), int64(len(raw))) + if err != nil { + t.Fatalf("open JAR: %v", err) + } + var names []string + for _, file := range reader.File { + if strings.HasSuffix(file.Name, ".class") { + names = append(names, file.Name) + } + } + sort.Strings(names) + return names +} diff --git a/dex2jar/dex2jar.go b/dex2jar/dex2jar.go index 8d478dff..7a3d92f4 100644 --- a/dex2jar/dex2jar.go +++ b/dex2jar/dex2jar.go @@ -1,10 +1,12 @@ -// Package dex2jar translates raw DEX files and APK archives into deterministic +// Package dex2jar translates raw DEX files, APK archives, Android split +// bundles (APKS/XAPK/APKM), and Android App Bundles (AAB) into deterministic // Java archives using the native, pure-Go translation pipeline. package dex2jar import ( "archive/zip" "bytes" + "encoding/json" "errors" "fmt" "io" @@ -19,18 +21,32 @@ import ( "github.com/yaklang/javajive/dex2jar/lower" "github.com/yaklang/javajive/dex2jar/model" dexreport "github.com/yaklang/javajive/dex2jar/report" + "github.com/yaklang/javajive/internal/inputkind" ) const manifest = "Manifest-Version: 1.0\r\n\r\n" +const ( + maxConversionDiagnostics = 512 + maxDiagnosticsPayload = 1 << 20 + maxDiagnosticFieldRunes = 240 +) + var archiveTimestamp = time.Date(1980, time.January, 1, 0, 0, 0, 0, time.UTC) -// Options controls DEX and APK input bounds. Non-positive values use defaults. +// Options controls DEX and Android container input bounds. Non-positive values +// use defaults. type Options struct { MaxDEXSize int64 MaxAPKSize int64 MaxTotalDEXSize int64 + // MaxTotalAPKSize bounds the sum of nested APK sizes in APKS/XAPK/APKM + // containers. Non-positive values use the input package default. + MaxTotalAPKSize int64 MaxDEXFiles int + // MaxNestedAPKs bounds the number of nested APK entries in a split bundle. + // Non-positive values use the input package default. + MaxNestedAPKs int } // Report summarizes a successful conversion. The current strict translator @@ -43,11 +59,88 @@ type Report struct { Warnings int } +// FailurePolicy selects strict conversion, recognized method-local stubbing, +// or full class-level recovery. The zero value is strict. +type FailurePolicy string + +const ( + FailureStrict FailurePolicy = "strict" + FailureStubUnsupportedMethods FailurePolicy = "stub_unsupported_methods" + FailureRecover FailurePolicy = "recover" +) + +// ConvertOptions combines existing input bounds with an explicit conversion +// policy without changing the source-compatible Options type. +type ConvertOptions struct { + Input Options + Policy FailurePolicy +} + +// ConversionDiagnostic is stable, JSON-friendly evidence of one degradation or +// terminal conversion failure. +type ConversionDiagnostic struct { + Entry string `json:"entry,omitempty"` + Class string `json:"class,omitempty"` + Method string `json:"method,omitempty"` + Descriptor string `json:"descriptor,omitempty"` + Category string `json:"category"` + Action string `json:"action"` + Feature string `json:"feature,omitempty"` + Code string `json:"code,omitempty"` + Kind string `json:"kind,omitempty"` + Scope string `json:"scope,omitempty"` + Stage string `json:"stage,omitempty"` + Severity string `json:"severity,omitempty"` + Offset int64 `json:"offset,omitempty"` + Op string `json:"op,omitempty"` + Artifact string `json:"artifact,omitempty"` + Message string `json:"message"` +} + +// DetailedReport describes complete, partial, or failed conversion without +// weakening the existing scalar Report contract. +type DetailedReport struct { + Status string `json:"status"` + Summary Report `json:"summary"` + AttemptedClasses int `json:"attempted_classes"` + StubbedClasses int `json:"stubbed_classes"` + OmittedClasses int `json:"omitted_classes"` + StubbedMethods int `json:"stubbed_methods"` + DroppedAttributes int `json:"dropped_attributes"` + Diagnostics []ConversionDiagnostic `json:"diagnostics,omitempty"` + diagnosticsOmitted int +} + +func appendConversionDiagnostic(detailed *DetailedReport, diagnostic ConversionDiagnostic) { + if len(detailed.Diagnostics) < maxConversionDiagnostics-1 { + detailed.Diagnostics = append(detailed.Diagnostics, diagnostic) + return + } + detailed.diagnosticsOmitted++ + truncated := ConversionDiagnostic{ + Category: "recovery", Action: "drop_attribute", Code: "diagnostics.truncated", + Kind: "resource_limit", Scope: "container", Stage: "collect", Severity: "warning", + Message: fmt.Sprintf("%d additional conversion diagnostics were omitted to keep collection bounded", detailed.diagnosticsOmitted), + } + if len(detailed.Diagnostics) == maxConversionDiagnostics-1 { + detailed.Diagnostics = append(detailed.Diagnostics, truncated) + return + } + detailed.Diagnostics[len(detailed.Diagnostics)-1] = truncated +} + type jarEntry struct { name string data []byte } +type convertedClass struct { + file *model.File + class *model.Class + name string + result lower.ClassResult +} + // InputKind identifies reverse-toolchain input by content magic. type InputKind uint8 @@ -56,34 +149,125 @@ const ( InputClass InputDEX InputZIP + // InputJMOD identifies a JMOD archive: "JM\x01\x00" followed by a ZIP. + InputJMOD + // InputJIMAGE identifies a JDK modular runtime image. + InputJIMAGE ) // DetectInputKind classifies supported reverse-toolchain input by content magic. func DetectInputKind(data []byte) InputKind { - switch { - case hasDEXMagic(data): + switch inputkind.DetectMagic(data) { + case inputkind.DEX: return InputDEX - case hasZIPMagic(data): - return InputZIP - case len(data) >= 4 && data[0] == 0xca && data[1] == 0xfe && data[2] == 0xba && data[3] == 0xbe: + case inputkind.Class: return InputClass + case inputkind.JMOD: + return InputJMOD + case inputkind.JIMAGE: + return InputJIMAGE + case inputkind.ZIP: + return InputZIP default: return InputUnknown } } -// DexToJar translates either a raw DEX file or an APK, selected by input magic. -// On any parse or translation failure it returns no JAR bytes. +// ContainerKind is the structure-aware classification of an input. It refines +// InputKind for ZIP containers (APK vs APKS vs JAR, and so on). +type ContainerKind string + +const ( + ContainerUnknown ContainerKind = "unknown" + ContainerClass ContainerKind = "class" + ContainerDEX ContainerKind = "dex" + ContainerJMOD ContainerKind = "jmod" + ContainerJImage ContainerKind = "jimage" + ContainerJAR ContainerKind = "jar" + ContainerWAR ContainerKind = "war" + ContainerEAR ContainerKind = "ear" + ContainerAAR ContainerKind = "aar" + ContainerPAR ContainerKind = "par" + ContainerZIP ContainerKind = "zip" + ContainerAPK ContainerKind = "apk" + ContainerAPKS ContainerKind = "apks" + ContainerXAPK ContainerKind = "xapk" + ContainerAPKM ContainerKind = "apkm" + ContainerAAB ContainerKind = "aab" +) + +// ClassifyInput classifies data by magic, archive structure, and finally the +// supplied name's extension. +func ClassifyInput(data []byte, name string) ContainerKind { + return ContainerKind(inputkind.DetectBytes(data, name)) +} + +// ClassifyInputFile classifies a file without loading the whole archive. +func ClassifyInputFile(name string) (ContainerKind, error) { + kind, err := inputkind.DetectFile(name) + return ContainerKind(kind), err +} + +// IsAndroidContainer reports whether kind is translated by the DEX pipeline. +func IsAndroidContainer(kind ContainerKind) bool { + return inputkind.IsAndroid(inputkind.Kind(kind)) +} + +// IsJavaArchiveContainer reports whether kind is exported by the Java archive +// decompiler. +func IsJavaArchiveContainer(kind ContainerKind) bool { + return inputkind.IsJavaArchive(inputkind.Kind(kind)) +} + +// DexToJar translates a raw DEX, APK, APKS/XAPK/APKM bundle, or AAB, selected +// by content magic and archive structure. On any parse or translation failure +// it returns no JAR bytes. func DexToJar(data []byte, options Options) ([]byte, Report, error) { - app, err := parseApplication(data, options) + jar, detailed, err := DexToJarWithOptions(data, ConvertOptions{Input: options, Policy: FailureStrict}) + return jar, detailed.Summary, err +} + +// DexToJarWithOptions translates an input with an explicit failure policy. An +// error always means no JAR bytes; partial success has a nil error and Status +// "partial" with method, class, initializer, and metadata recovery diagnostics. +func DexToJarWithOptions(data []byte, options ConvertOptions) (jar []byte, detailed DetailedReport, err error) { + detailed.Status = "failed" + defer func() { + if recovered := recover(); recovered != nil { + jar = nil + detailed.Status = "failed" + appendConversionDiagnostic(&detailed, ConversionDiagnostic{ + Category: "internal", + Action: "failed", + Message: fmt.Sprintf("dex2jar internal panic: %v", recovered), + }) + err = fmt.Errorf("dex2jar: internal panic: %v", recovered) + } + }() + policy := options.Policy + if policy == "" { + policy = FailureStrict + } + if policy != FailureStrict && policy != FailureStubUnsupportedMethods && policy != FailureRecover { + return nil, detailed, fmt.Errorf("dex2jar: unknown failure policy %q", policy) + } + app, _, err := parseApplication(data, options.Input) if err != nil { - return nil, Report{}, err + appendConversionDiagnostic(&detailed, diagnosticFromError(err, "failed", "")) + return nil, detailed, err } - return applicationToJar(app) + return applicationToJarWithPolicy(app, policy) } // APKToJar translates an APK containing classes*.dex entries. -func APKToJar(data []byte, options Options) ([]byte, Report, error) { +func APKToJar(data []byte, options Options) (jar []byte, report Report, err error) { + defer func() { + if recovered := recover(); recovered != nil { + jar = nil + report = Report{} + err = fmt.Errorf("dex2jar: internal panic: %v", recovered) + } + }() if !hasZIPMagic(data) { return nil, Report{}, errors.New("dex2jar: input is not an APK/ZIP archive") } @@ -91,56 +275,77 @@ func APKToJar(data []byte, options Options) ([]byte, Report, error) { if err != nil { return nil, Report{}, err } - return applicationToJar(app) + jar, report, err = applicationToJar(app) + return +} + +// DexFileToJarWithOptions converts a file with explicit policy and atomically +// replaces dst only after a complete or explicitly partial JAR is available. +func DexFileToJarWithOptions(src, dst string, options ConvertOptions) (DetailedReport, error) { + data, err := readInputFile(src, options.Input) + if err != nil { + return DetailedReport{Status: "failed"}, err + } + jar, detailed, err := DexToJarWithOptions(data, options) + if err != nil { + return detailed, err + } + if err := atomicWriteFile(dst, jar, 0o644); err != nil { + detailed.Status = "failed" + return detailed, fmt.Errorf("dex2jar: write %q: %w", dst, err) + } + return detailed, nil } // DexFileToJar reads a raw DEX or APK and writes the complete JAR to a // same-directory temporary file before replacing dst. An existing destination // is left untouched when conversion or temporary-file writing fails. func DexFileToJar(src, dst string, options Options) (Report, error) { + detailed, err := DexFileToJarWithOptions(src, dst, ConvertOptions{Input: options, Policy: FailureStrict}) + return detailed.Summary, err +} + +func readInputFile(src string, options Options) ([]byte, error) { info, err := os.Stat(src) if err != nil { - return Report{}, fmt.Errorf("dex2jar: stat %q: %w", src, err) + return nil, fmt.Errorf("dex2jar: stat %q: %w", src, err) } if !info.Mode().IsRegular() { - return Report{}, fmt.Errorf("dex2jar: input %q is not a regular file", src) + return nil, fmt.Errorf("dex2jar: input %q is not a regular file", src) } file, err := os.Open(src) if err != nil { - return Report{}, fmt.Errorf("dex2jar: open %q: %w", src, err) + return nil, fmt.Errorf("dex2jar: open %q: %w", src, err) } var magic [8]byte read, readErr := io.ReadFull(file, magic[:]) _ = file.Close() if readErr != nil && readErr != io.ErrUnexpectedEOF { - return Report{}, fmt.Errorf("dex2jar: read magic from %q: %w", src, readErr) + return nil, fmt.Errorf("dex2jar: read magic from %q: %w", src, readErr) } + if inputkind.IsJImageHeader(magic[:read]) { + return nil, fmt.Errorf("dex2jar: unsupported DEX input: detected jimage") + } + archiveInput := hasZIPMagic(magic[:read]) || inputkind.IsJMODHeader(magic[:read]) maxSize := options.MaxDEXSize - if hasZIPMagic(magic[:read]) { + if archiveInput { maxSize = options.MaxAPKSize } if maxSize <= 0 { - if hasZIPMagic(magic[:read]) { + if archiveInput { maxSize = input.DefaultMaxAPKSize } else { maxSize = input.DefaultMaxDEXSize } } if info.Size() > maxSize { - return Report{}, fmt.Errorf("dex2jar: input size %d exceeds limit %d", info.Size(), maxSize) + return nil, fmt.Errorf("dex2jar: input size %d exceeds limit %d", info.Size(), maxSize) } data, err := os.ReadFile(src) if err != nil { - return Report{}, fmt.Errorf("dex2jar: read %q: %w", src, err) - } - jar, conversionReport, err := DexToJar(data, options) - if err != nil { - return conversionReport, err - } - if err := atomicWriteFile(dst, jar, 0o644); err != nil { - return conversionReport, fmt.Errorf("dex2jar: write %q: %w", dst, err) + return nil, fmt.Errorf("dex2jar: read %q: %w", src, err) } - return conversionReport, nil + return data, nil } func inputOptions(options Options) input.Options { @@ -148,79 +353,306 @@ func inputOptions(options Options) input.Options { MaxDEXSize: options.MaxDEXSize, MaxAPKSize: options.MaxAPKSize, MaxTotalDEXSize: options.MaxTotalDEXSize, + MaxTotalAPKSize: options.MaxTotalAPKSize, MaxDEXFiles: options.MaxDEXFiles, + MaxNestedAPKs: options.MaxNestedAPKs, } } -func parseApplication(data []byte, options Options) (*model.Application, error) { - inputOptions := inputOptions(options) - switch DetectInputKind(data) { - case InputDEX: - file, err := input.ParseDEXWithOptions(data, "classes.dex", inputOptions) - if err != nil { - return nil, err - } - return &model.Application{Files: []*model.File{file}}, nil - case InputZIP: - return input.ParseAPKWithOptions(data, inputOptions) - default: - return nil, errors.New("dex2jar: unsupported input magic (want DEX or APK/ZIP)") +func parseApplication(data []byte, options Options) (*model.Application, ContainerKind, error) { + app, kind, err := input.ParseApplicationWithOptions(data, "", inputOptions(options)) + if err != nil { + return nil, ContainerKind(kind), err } + return app, ContainerKind(kind), nil } func applicationToJar(app *model.Application) ([]byte, Report, error) { + jar, detailed, err := applicationToJarWithPolicy(app, FailureStrict) + return jar, detailed.Summary, err +} + +func applicationToJarWithPolicy(app *model.Application, policy FailurePolicy) ([]byte, DetailedReport, error) { + detailed := DetailedReport{Status: "failed"} if app == nil { - return nil, Report{}, errors.New("dex2jar: nil application") + return nil, detailed, errors.New("dex2jar: nil application") } - report := Report{DEXFiles: len(app.Files)} + detailed.Summary.DEXFiles = len(app.Files) entries := make([]jarEntry, 0) seen := make(map[string]string) hierarchy := applicationHierarchy(app) + converted := make([]convertedClass, 0, len(hierarchy)) + lowerPolicy := lower.Strict + switch policy { + case FailureStubUnsupportedMethods: + lowerPolicy = lower.StubUnsupportedMethods + case FailureRecover: + lowerPolicy = lower.Recover + } for _, file := range app.Files { if file == nil { - return nil, report, errors.New("dex2jar: application contains a nil DEX file") + return nil, detailed, errors.New("dex2jar: application contains a nil DEX file") } - // Validate the file once instead of once per method. if err := ir.ValidateFile(file); err != nil { - return nil, report, dexreport.New(file.Entry, "", "", 0, "metadata", err) + err = dexreport.New(file.Entry, "", "", 0, "metadata", err) + appendConversionDiagnostic(&detailed, diagnosticFromError(err, "failed", "")) + return nil, detailed, err } for classIndex := range file.Classes { class := &file.Classes[classIndex] + detailed.AttemptedClasses++ name, err := classEntryName(class.Descriptor) if err != nil { - return nil, report, fmt.Errorf("dex2jar: class %q: %w", class.Descriptor, err) + err = fmt.Errorf("dex2jar: class %q: %w", class.Descriptor, err) + appendConversionDiagnostic(&detailed, diagnosticFromError(err, "failed", "")) + return nil, detailed, err } if previous, exists := seen[name]; exists { - return nil, report, fmt.Errorf("dex2jar: duplicate output entry %q from %q and %q", name, previous, file.Entry) + err = fmt.Errorf("dex2jar: duplicate output entry %q from %q and %q", name, previous, file.Entry) + appendConversionDiagnostic(&detailed, diagnosticFromError(err, "failed", "")) + return nil, detailed, err } seen[name] = file.Entry - classBytes, err := lower.ClassWithOptions(file, class, lower.ClassOptions{FileValidated: true, Hierarchy: hierarchy}) + result, err := lower.ClassWithPolicy(file, class, lower.ClassOptions{FileValidated: true, Hierarchy: hierarchy}, lowerPolicy) if err != nil { - return nil, report, err + detailed.Summary.Classes = len(converted) + appendConversionDiagnostic(&detailed, diagnosticFromError(err, "failed", "")) + return nil, detailed, err } - entries = append(entries, jarEntry{name: name, data: classBytes}) - report.Classes++ - for _, method := range class.DirectMethods { - report.Methods++ - if method.Code != nil { - report.TranslatedMethods++ - } + converted = append(converted, convertedClass{file: file, class: class, name: name, result: result}) + } + } + if policy == FailureRecover { + if err := recoverMinimalDependencies(converted, hierarchy); err != nil { + appendConversionDiagnostic(&detailed, diagnosticFromError(err, "failed", "dependency-closure")) + return nil, detailed, err + } + } + for _, item := range converted { + file, class, name, result := item.file, item.class, item.name, item.result + entries = append(entries, jarEntry{name: name, data: result.Bytes}) + detailed.Summary.Classes++ + if result.ClassStubbed { + detailed.StubbedClasses++ + } + for _, recovery := range result.Recoveries { + + detailed.Summary.Warnings++ + if recovery.Action == "drop_attribute" { + detailed.DroppedAttributes++ } - for _, method := range class.VirtualMethods { - report.Methods++ - if method.Code != nil { - report.TranslatedMethods++ - } + scope := recovery.Scope + if scope == "" { + scope = "class" + } + appendConversionDiagnostic(&detailed, ConversionDiagnostic{ + Entry: file.Entry, Class: class.Descriptor, Method: recovery.Member, + Descriptor: recovery.Descriptor, Category: "recovery", Action: recovery.Action, + Feature: recovery.Feature, Code: recovery.Code, Kind: "structural", + Scope: scope, Stage: "class_assemble", Severity: "warning", Message: recovery.Message, + }) + } + recoveredMethods := make(map[string]bool, len(result.Recoveries)) + for _, recovery := range result.Recoveries { + if recovery.Action == "stub_method" || recovery.Action == "stub_initializer" && recovery.Scope == "method" { + recoveredMethods[recovery.Member+"\x00"+recovery.Descriptor] = true + } + } + + stubs := make(map[string]bool, len(result.StubbedMethods)) + for _, stub := range result.StubbedMethods { + stubs[stub.Method+"\x00"+stub.Descriptor] = true + detailed.StubbedMethods++ + if !result.ClassStubbed { + detailed.Summary.Warnings++ + } + if !recoveredMethods[stub.Method+"\x00"+stub.Descriptor] { + appendConversionDiagnostic(&detailed, ConversionDiagnostic{ + Entry: file.Entry, Class: class.Descriptor, Method: stub.Method + stub.Descriptor, + Descriptor: stub.Descriptor, Category: "unsupported", Action: "stubbed", + Feature: stub.Feature, Code: "method.unsupported_stub", Kind: "capability", + Scope: "method", Stage: "lower_method", Severity: "warning", Message: stub.Message, + }) + } + } + for _, method := range append(class.DirectMethods, class.VirtualMethods...) { + detailed.Summary.Methods++ + if method.Code == nil || result.ClassMinimal { + continue + } + descriptor, descriptorErr := methodDescriptorForReport(file, &method) + if descriptorErr == nil && !stubs[method.Method.Name+"\x00"+descriptor] { + detailed.Summary.TranslatedMethods++ } } } + if len(detailed.Diagnostics) > 0 { + payload, diagnostics, marshalErr := encodeConversionDiagnostics(detailed.Summary, detailed.Diagnostics) + if marshalErr != nil { + return nil, detailed, fmt.Errorf("dex2jar: encode diagnostics: %w", marshalErr) + } + detailed.Diagnostics = diagnostics + entries = append(entries, jarEntry{name: "META-INF/javajive/diagnostics.json", data: payload}) + } jar, err := writeJar(entries) if err != nil { - return nil, report, err + appendConversionDiagnostic(&detailed, diagnosticFromError(err, "failed", "")) + return nil, detailed, err } - return jar, report, nil + detailed.Status = "complete" + if detailed.Summary.Warnings > 0 { + detailed.Status = "partial" + } + return jar, detailed, nil +} + +func encodeConversionDiagnostics(summary Report, input []ConversionDiagnostic) ([]byte, []ConversionDiagnostic, error) { + diagnostics := make([]ConversionDiagnostic, 0, min(len(input), maxConversionDiagnostics)) + for _, diagnostic := range input { + diagnostic.Entry = sanitizeDiagnosticField(diagnostic.Entry) + diagnostic.Class = sanitizeDiagnosticField(diagnostic.Class) + diagnostic.Method = sanitizeDiagnosticField(diagnostic.Method) + diagnostic.Descriptor = sanitizeDiagnosticField(diagnostic.Descriptor) + diagnostic.Category = sanitizeDiagnosticField(diagnostic.Category) + diagnostic.Action = sanitizeDiagnosticField(diagnostic.Action) + diagnostic.Feature = sanitizeDiagnosticField(diagnostic.Feature) + diagnostic.Code = sanitizeDiagnosticField(diagnostic.Code) + diagnostic.Kind = sanitizeDiagnosticField(diagnostic.Kind) + diagnostic.Scope = sanitizeDiagnosticField(diagnostic.Scope) + diagnostic.Stage = sanitizeDiagnosticField(diagnostic.Stage) + diagnostic.Severity = sanitizeDiagnosticField(diagnostic.Severity) + diagnostic.Op = sanitizeDiagnosticField(diagnostic.Op) + diagnostic.Artifact = sanitizeDiagnosticField(diagnostic.Artifact) + diagnostic.Message = sanitizeDiagnosticField(diagnostic.Message) + diagnostics = append(diagnostics, diagnostic) + if len(diagnostics) == maxConversionDiagnostics-1 { + break + } + } + truncated := len(diagnostics) < len(input) + appendTruncation := func(omitted int) { + diagnostics = append(diagnostics, ConversionDiagnostic{ + Category: "recovery", Action: "drop_attribute", Code: "diagnostics.truncated", + Kind: "resource_limit", Scope: "container", Stage: "write", Severity: "warning", + Message: fmt.Sprintf("%d diagnostics were omitted to keep META-INF/javajive/diagnostics.json bounded", omitted), + }) + } + if truncated { + appendTruncation(len(input) - len(diagnostics)) + } + marshal := func() ([]byte, error) { + payload, err := json.MarshalIndent(struct { + Version int `json:"version"` + Status string `json:"status"` + Summary Report `json:"summary"` + Diagnostics []ConversionDiagnostic `json:"diagnostics"` + }{Version: 1, Status: "partial", Summary: summary, Diagnostics: diagnostics}, "", " ") + return append(payload, '\n'), err + } + for { + payload, err := marshal() + if err != nil || len(payload) <= maxDiagnosticsPayload { + return payload, diagnostics, err + } + if len(diagnostics) <= 1 { + return nil, nil, fmt.Errorf("minimum diagnostics payload exceeds %d bytes", maxDiagnosticsPayload) + } + remove := len(diagnostics) / 4 + if remove < 1 { + remove = 1 + } + kept := len(diagnostics) - remove + if diagnostics[len(diagnostics)-1].Code == "diagnostics.truncated" { + kept-- + } + if kept < 0 { + kept = 0 + } + diagnostics = diagnostics[:kept] + appendTruncation(len(input) - kept) + } +} + +func sanitizeDiagnosticField(value string) string { + value = strings.Map(func(r rune) rune { + if r < 0x20 || r == 0x7f { + return ' ' + } + return r + }, strings.ToValidUTF8(value, "\uFFFD")) + runes := []rune(strings.TrimSpace(value)) + if len(runes) > maxDiagnosticFieldRunes { + runes = runes[:maxDiagnosticFieldRunes] + } + return string(runes) +} + +func methodDescriptorForReport(file *model.File, method *model.EncodedMethod) (string, error) { + if int(method.Method.ProtoIndex) >= len(file.Protos) { + return "", fmt.Errorf("proto index out of range") + } + proto := file.Protos[method.Method.ProtoIndex] + var descriptor strings.Builder + descriptor.WriteByte('(') + for _, parameter := range proto.Parameters { + descriptor.WriteString(parameter) + } + descriptor.WriteByte(')') + descriptor.WriteString(proto.ReturnType) + return descriptor.String(), nil +} + +func diagnosticFromError(err error, action, feature string) ConversionDiagnostic { + out := ConversionDiagnostic{Category: "invalid", Action: action, Feature: feature, Severity: "error", Offset: -1, Message: err.Error()} + if failure, ok := dexreport.AsFailure(err); ok { + out.Code = failure.Code + out.Kind = string(failure.Kind) + out.Scope = string(failure.Scope) + out.Stage = string(failure.Stage) + out.Severity = string(failure.Severity) + out.Entry = failure.Entry + out.Class = failure.Class + out.Method = failure.Member + out.Descriptor = failure.Descriptor + out.Offset = failure.Offset + out.Op = failure.Op + if failure.Feature != "" { + out.Feature = failure.Feature + } + if action == "" || action == "failed" && failure.Action != "" { + out.Action = string(failure.Action) + } + if failure.Kind == dexreport.KindUnsupported { + out.Category = "unsupported" + } + } + if dexreport.IsUnsupported(err) { + out.Category = "unsupported" + var capability *dexreport.CapabilityError + if errors.As(err, &capability) { + out.Feature = capability.Feature + } + } + if diagnostic, ok := dexreport.AsDiagnostic(err); ok { + if out.Entry == "" { + out.Entry = diagnostic.Entry + } + if out.Class == "" { + out.Class = diagnostic.Class + } + if out.Method == "" { + out.Method = diagnostic.Method + } + if out.Offset < 0 { + out.Offset = diagnostic.Offset + } + if out.Op == "" { + out.Op = diagnostic.Op + } + } + return out } func classEntryName(descriptor string) (string, error) { @@ -266,11 +698,6 @@ func writeJar(classes []jarEntry) ([]byte, error) { return out.Bytes(), nil } -func hasDEXMagic(data []byte) bool { - return len(data) >= 8 && string(data[:4]) == "dex\n" && data[7] == 0 && - data[4] >= '0' && data[4] <= '9' && data[5] >= '0' && data[5] <= '9' && data[6] >= '0' && data[6] <= '9' -} - func hasZIPMagic(data []byte) bool { return len(data) >= 4 && data[0] == 'P' && data[1] == 'K' && ((data[2] == 3 && data[3] == 4) || (data[2] == 5 && data[3] == 6) || (data[2] == 7 && data[3] == 8)) @@ -314,6 +741,72 @@ func atomicWriteFile(path string, data []byte, mode os.FileMode) (err error) { // applicationHierarchy indexes every class of the application so assignability // resolves across multidex files, where a superclass often lives in a // different DEX than its subclass. +func recoverMinimalDependencies(classes []convertedClass, hierarchy map[string]*model.Class) error { + // Index reverse hierarchy edges once, then propagate minimal-shell damage with + // a queue. This preserves fixed-point semantics without repeatedly scanning + // every class for every newly unsafe dependency. + reverse := make(map[string][]int) + for index := range classes { + class := classes[index].class + if class.Superclass != "" { + reverse[class.Superclass] = append(reverse[class.Superclass], index) + } + for _, descriptor := range class.Interfaces { + reverse[descriptor] = append(reverse[descriptor], index) + } + } + unsafeDependency := make(map[string]bool) + queue := make([]string, 0) + for index := range classes { + if classes[index].result.ClassMinimal { + descriptor := classes[index].class.Descriptor + if !unsafeDependency[descriptor] { + unsafeDependency[descriptor] = true + queue = append(queue, descriptor) + } + } + } + for head := 0; head < len(queue); head++ { + for _, index := range reverse[queue[head]] { + descriptor := classes[index].class.Descriptor + if unsafeDependency[descriptor] { + continue + } + unsafeDependency[descriptor] = true + queue = append(queue, descriptor) + } + } + for index := range classes { + item := &classes[index] + if item.result.ClassMinimal || !unsafeDependency[item.class.Descriptor] || item.result.ClassStubbed { + continue + } + dependency := "" + if unsafeDependency[item.class.Superclass] { + dependency = item.class.Superclass + } else { + for _, descriptor := range item.class.Interfaces { + if unsafeDependency[descriptor] { + dependency = descriptor + break + } + } + } + if dependency == "" { + return fmt.Errorf("dex2jar: unsafe dependency closure lost the cause for %q", item.class.Descriptor) + } + result, err := lower.ClassWithPolicy(item.file, item.class, lower.ClassOptions{ + FileValidated: true, Hierarchy: hierarchy, ForceClassShell: true, + RecoveryReason: fmt.Sprintf("dependency %s was reduced to a minimal class shell", dependency), + }, lower.Recover) + if err != nil { + return err + } + item.result = result + } + return nil +} + func applicationHierarchy(app *model.Application) map[string]*model.Class { index := make(map[string]*model.Class) for _, file := range app.Files { diff --git a/dex2jar/fuzz_test.go b/dex2jar/fuzz_test.go new file mode 100644 index 00000000..fadad510 --- /dev/null +++ b/dex2jar/fuzz_test.go @@ -0,0 +1,44 @@ +package dex2jar_test + +import ( + "testing" + + "github.com/yaklang/javajive/dex2jar" +) + +func FuzzDexToJarNeverPanics(f *testing.F) { + for _, seed := range [][]byte{ + []byte("dex\n035\x00"), + []byte("PK\x03\x04"), + []byte("not a dex or archive"), + {0xca, 0xfe, 0xba, 0xbe}, + } { + f.Add(seed) + } + options := dex2jar.Options{ + MaxDEXSize: 1 << 20, + MaxAPKSize: 2 << 20, + MaxTotalDEXSize: 2 << 20, + MaxDEXFiles: 8, + MaxNestedAPKs: 8, + } + f.Fuzz(func(t *testing.T, data []byte) { + _, _, _ = dex2jar.DexToJar(data, options) + _, _, _ = dex2jar.DexToJarWithOptions(data, dex2jar.ConvertOptions{ + Input: options, + Policy: dex2jar.FailureStubUnsupportedMethods, + }) + jar, report, err := dex2jar.DexToJarWithOptions(data, dex2jar.ConvertOptions{ + Input: options, + Policy: dex2jar.FailureRecover, + }) + if err == nil && len(jar) == 0 { + t.Fatalf("recover succeeded without JAR: %#v", report) + } + for _, diagnostic := range report.Diagnostics { + if diagnostic.Category == "internal" && diagnostic.Action == "failed" { + t.Fatalf("recover converted an internal panic into a diagnostic: %#v", diagnostic) + } + } + }) +} diff --git a/dex2jar/input/container.go b/dex2jar/input/container.go new file mode 100644 index 00000000..8e3387ac --- /dev/null +++ b/dex2jar/input/container.go @@ -0,0 +1,353 @@ +package input + +import ( + "archive/zip" + "bytes" + "errors" + "fmt" + "math" + "path" + "reflect" + "sort" + "strconv" + "strings" + + "github.com/yaklang/javajive/dex2jar/model" + "github.com/yaklang/javajive/dex2jar/report" + "github.com/yaklang/javajive/internal/inputkind" +) + +// DEXSource is one DEX file discovered in a raw DEX, APK, APKS/XAPK/APKM +// bundle, or Android App Bundle (AAB). +type DEXSource struct { + Entry string + MultidexIndex int + Canonical bool + Data []byte +} + +// ParseApplicationWithOptions classifies data and parses every DEX file it +// contains. Identical classes repeated across split APKs or AAB modules are +// collapsed; conflicting definitions are rejected. +func ParseApplicationWithOptions(data []byte, name string, options Options) (*model.Application, inputkind.Kind, error) { + sources, kind, err := CollectDEXSources(data, name, options) + if err != nil { + return nil, kind, err + } + strict := kind == inputkind.APK + app, err := parseDEXSources(sources, options, strict) + return app, kind, err +} + +// CollectDEXSources classifies data and returns every DEX file it contains +// without parsing the DEX payloads. +func CollectDEXSources(data []byte, name string, options Options) ([]DEXSource, inputkind.Kind, error) { + kind := inputkind.DetectBytes(data, name) + switch kind { + case inputkind.DEX: + if int64(len(data)) > options.maxDEXSize() { + return nil, kind, report.New("classes.dex", "", "", 0, "input", fmt.Errorf("DEX size %d exceeds limit %d", len(data), options.maxDEXSize())) + } + return []DEXSource{{Entry: "classes.dex", MultidexIndex: 1, Canonical: false, Data: data}}, kind, nil + case inputkind.APK: + sources, err := collectAPK(data, "", options, false) + return sources, kind, err + case inputkind.APKS, inputkind.XAPK, inputkind.APKM: + sources, err := collectAPKS(data, kind, options) + return sources, kind, err + case inputkind.AAB: + sources, err := collectAAB(data, options) + return sources, kind, err + default: + return nil, kind, report.New(name, "", "", -1, "input", fmt.Errorf("unsupported DEX input: detected %s", kind)) + } +} + +func collectAPK(data []byte, prefix string, options Options, allowEmpty bool) ([]DEXSource, error) { + if int64(len(data)) > options.maxAPKSize() { + return nil, report.New(prefix, "", "", -1, "APK", fmt.Errorf("archive size %d exceeds limit %d", len(data), options.maxAPKSize())) + } + reader, err := zip.NewReader(bytes.NewReader(data), int64(len(data))) + if err != nil { + return nil, report.New(prefix, "", "", -1, "APK", err) + } + type entry struct { + index int + file *zip.File + } + entries := make([]entry, 0) + seenIndex := make(map[int]string) + for _, file := range reader.File { + index, canonical, indexErr := dexEntryIndex(file.Name) + if indexErr != nil { + return nil, report.New(qualifiedEntry(prefix, file.Name), "", "", -1, "APK entry", indexErr) + } + if !canonical { + continue + } + if previous, exists := seenIndex[index]; exists { + return nil, report.New(qualifiedEntry(prefix, file.Name), "", "", -1, "APK entry", fmt.Errorf("duplicate multidex index %d also used by %q", index, previous)) + } + seenIndex[index] = file.Name + entries = append(entries, entry{index: index, file: file}) + } + if len(entries) == 0 { + if allowEmpty { + return nil, nil + } + return nil, report.New(prefix, "", "", -1, "APK", errors.New("no classes*.dex entries")) + } + if len(entries) > options.maxDEXFiles() { + return nil, report.New(prefix, "", "", -1, "APK", fmt.Errorf("DEX file count %d exceeds limit %d", len(entries), options.maxDEXFiles())) + } + sort.Slice(entries, func(i, j int) bool { return entries[i].index < entries[j].index }) + sources := make([]DEXSource, 0, len(entries)) + var totalDEXSize uint64 + for _, item := range entries { + if item.file.UncompressedSize64 > uint64(options.maxDEXSize()) || item.file.UncompressedSize64 > uint64(math.MaxInt) { + return nil, report.New(qualifiedEntry(prefix, item.file.Name), "", "", -1, "APK entry", fmt.Errorf("uncompressed size %d exceeds limit", item.file.UncompressedSize64)) + } + if item.file.UncompressedSize64 > uint64(options.maxTotalDEXSize())-totalDEXSize { + return nil, report.New(qualifiedEntry(prefix, item.file.Name), "", "", -1, "APK entry", fmt.Errorf("total DEX size exceeds limit %d", options.maxTotalDEXSize())) + } + totalDEXSize += item.file.UncompressedSize64 + contents, readErr := readZipEntry(item.file, options.maxDEXSize()) + if readErr != nil { + return nil, report.New(qualifiedEntry(prefix, item.file.Name), "", "", -1, "APK entry", readErr) + } + sources = append(sources, DEXSource{ + Entry: qualifiedEntry(prefix, item.file.Name), + MultidexIndex: item.index, + Canonical: true, + Data: contents, + }) + } + return sources, nil +} + +func collectAPKS(data []byte, kind inputkind.Kind, options Options) ([]DEXSource, error) { + if int64(len(data)) > options.maxAPKSize() { + return nil, report.New("", "", "", -1, string(kind), fmt.Errorf("container size %d exceeds limit %d", len(data), options.maxAPKSize())) + } + reader, err := zip.NewReader(bytes.NewReader(data), int64(len(data))) + if err != nil { + return nil, report.New("", "", "", -1, string(kind), err) + } + nested := make([]*zip.File, 0) + hasUniversal := false + for _, file := range reader.File { + if file.FileInfo().IsDir() || !strings.HasSuffix(strings.ToLower(file.Name), ".apk") { + continue + } + nested = append(nested, file) + if strings.EqualFold(path.Base(file.Name), "universal.apk") { + hasUniversal = true + } + } + if len(nested) == 0 { + return nil, report.New("", "", "", -1, string(kind), errors.New("no nested .apk entries")) + } + if len(nested) > options.maxNestedAPKs() { + return nil, report.New("", "", "", -1, string(kind), fmt.Errorf("nested APK count %d exceeds limit %d", len(nested), options.maxNestedAPKs())) + } + sort.SliceStable(nested, func(i, j int) bool { return nested[i].Name < nested[j].Name }) + + // bundletool's system mode emits one complete APK per device variant under + // standalones/. They carry the same code, so translate a single variant. + hasStandalone := false + for _, file := range nested { + if strings.HasPrefix(strings.ToLower(path.Clean(file.Name)), "standalones/") { + hasStandalone = true + break + } + } + selectedStandalone := "" + + sources := make([]DEXSource, 0) + var totalAPKSize uint64 + var totalDEXSize uint64 + for _, file := range nested { + if hasUniversal && !strings.EqualFold(path.Base(file.Name), "universal.apk") { + continue + } + if !hasUniversal && hasStandalone { + if !strings.HasPrefix(strings.ToLower(path.Clean(file.Name)), "standalones/") { + continue + } + if selectedStandalone == "" { + selectedStandalone = file.Name + } + if file.Name != selectedStandalone { + continue + } + } + if file.UncompressedSize64 > uint64(options.maxAPKSize()) || file.UncompressedSize64 > uint64(math.MaxInt) { + return nil, report.New(file.Name, "", "", -1, string(kind)+" entry", fmt.Errorf("uncompressed APK size %d exceeds limit", file.UncompressedSize64)) + } + if file.UncompressedSize64 > uint64(options.maxTotalAPKSize())-totalAPKSize { + return nil, report.New(file.Name, "", "", -1, string(kind)+" entry", fmt.Errorf("total nested APK size exceeds limit %d", options.maxTotalAPKSize())) + } + totalAPKSize += file.UncompressedSize64 + raw, readErr := readZipEntry(file, options.maxAPKSize()) + if readErr != nil { + return nil, report.New(file.Name, "", "", -1, string(kind)+" entry", readErr) + } + nestedSources, parseErr := collectAPK(raw, file.Name, options, true) + if parseErr != nil { + return nil, parseErr + } + for _, source := range nestedSources { + totalDEXSize += uint64(len(source.Data)) + if totalDEXSize > uint64(options.maxTotalDEXSize()) { + return nil, report.New(source.Entry, "", "", -1, string(kind)+" entry", fmt.Errorf("total DEX size exceeds limit %d", options.maxTotalDEXSize())) + } + } + sources = append(sources, nestedSources...) + if len(sources) > options.maxDEXFiles() { + return nil, report.New("", "", "", -1, string(kind), fmt.Errorf("DEX file count %d exceeds limit %d", len(sources), options.maxDEXFiles())) + } + } + if len(sources) == 0 { + return nil, report.New("", "", "", -1, string(kind), errors.New("no classes*.dex entries in nested APKs")) + } + return sources, nil +} + +func collectAAB(data []byte, options Options) ([]DEXSource, error) { + if int64(len(data)) > options.maxAPKSize() { + return nil, report.New("", "", "", -1, "aab", fmt.Errorf("container size %d exceeds limit %d", len(data), options.maxAPKSize())) + } + reader, err := zip.NewReader(bytes.NewReader(data), int64(len(data))) + if err != nil { + return nil, report.New("", "", "", -1, "aab", err) + } + type entry struct { + module string + index int + file *zip.File + } + entries := make([]entry, 0) + seen := make(map[string]string) + for _, file := range reader.File { + module, index, canonical := inputkind.AABDEX(file.Name) + if !canonical { + continue + } + key := fmt.Sprintf("%s#%d", module, index) + if previous, exists := seen[key]; exists { + return nil, report.New(file.Name, "", "", -1, "aab entry", fmt.Errorf("duplicate module DEX index %d also used by %q", index, previous)) + } + seen[key] = file.Name + entries = append(entries, entry{module: module, index: index, file: file}) + } + if len(entries) == 0 { + return nil, report.New("", "", "", -1, "aab", errors.New("no /dex/classes*.dex entries")) + } + if len(entries) > options.maxDEXFiles() { + return nil, report.New("", "", "", -1, "aab", fmt.Errorf("DEX file count %d exceeds limit %d", len(entries), options.maxDEXFiles())) + } + sort.SliceStable(entries, func(i, j int) bool { + if entries[i].module != entries[j].module { + return entries[i].module < entries[j].module + } + return entries[i].index < entries[j].index + }) + sources := make([]DEXSource, 0, len(entries)) + var totalDEXSize uint64 + for _, item := range entries { + if item.file.UncompressedSize64 > uint64(options.maxDEXSize()) || item.file.UncompressedSize64 > uint64(math.MaxInt) { + return nil, report.New(item.file.Name, "", "", -1, "aab entry", fmt.Errorf("uncompressed size %d exceeds limit", item.file.UncompressedSize64)) + } + if item.file.UncompressedSize64 > uint64(options.maxTotalDEXSize())-totalDEXSize { + return nil, report.New(item.file.Name, "", "", -1, "aab entry", fmt.Errorf("total DEX size exceeds limit %d", options.maxTotalDEXSize())) + } + totalDEXSize += item.file.UncompressedSize64 + contents, readErr := readZipEntry(item.file, options.maxDEXSize()) + if readErr != nil { + return nil, report.New(item.file.Name, "", "", -1, "aab entry", readErr) + } + sources = append(sources, DEXSource{ + Entry: item.module + "/dex/" + path.Base(item.file.Name), + MultidexIndex: item.index, + Canonical: true, + Data: contents, + }) + } + return sources, nil +} + +func parseDEXSources(sources []DEXSource, options Options, strictDuplicates bool) (*model.Application, error) { + if len(sources) == 0 { + return nil, report.New("", "", "", -1, "input", errors.New("no DEX sources")) + } + if len(sources) > options.maxDEXFiles() { + return nil, report.New("", "", "", -1, "input", fmt.Errorf("DEX file count %d exceeds limit %d", len(sources), options.maxDEXFiles())) + } + app := &model.Application{Files: make([]*model.File, 0, len(sources))} + seen := make(map[string]model.Class) + seenEntry := make(map[string]string) + var totalDEXSize uint64 + for index := range sources { + source := &sources[index] + if int64(len(source.Data)) > options.maxDEXSize() { + return nil, report.New(source.Entry, "", "", 0, "input", fmt.Errorf("DEX size %d exceeds limit %d", len(source.Data), options.maxDEXSize())) + } + if uint64(len(source.Data)) > uint64(options.maxTotalDEXSize())-totalDEXSize { + return nil, report.New(source.Entry, "", "", 0, "input", fmt.Errorf("total DEX size exceeds limit %d", options.maxTotalDEXSize())) + } + totalDEXSize += uint64(len(source.Data)) + file, err := ParseDEXWithOptions(source.Data, source.Entry, options) + // Parsed model data owns resolved values, not the original DEX byte slice. + // Drop the source reference promptly so multidex inputs can be reclaimed as + // parsing advances. + source.Data = nil + if err != nil { + return nil, err + } + kept := file.Classes[:0] + for index := range file.Classes { + class := &file.Classes[index] + if previous, exists := seen[class.Descriptor]; exists { + if !strictDuplicates && reflect.DeepEqual(previous, *class) { + continue + } + return nil, report.New(source.Entry, class.Descriptor, "", -1, "duplicate class", fmt.Errorf("descriptor already defined in %q", seenEntry[class.Descriptor])) + } + seen[class.Descriptor] = *class + seenEntry[class.Descriptor] = source.Entry + kept = append(kept, *class) + } + file.Classes = kept + app.Files = append(app.Files, file) + } + return app, nil +} + +// dexEntryIndex parses a root-level canonical classes*.dex name. The bool is +// true when the name matches the canonical pattern, even when the index itself +// is invalid (for example classes01.dex). +func dexEntryIndex(name string) (index int, canonical bool, err error) { + match := dexEntryPattern.FindStringSubmatch(name) + if match == nil { + return 0, false, nil + } + index = 1 + if match[1] == "" { + return index, true, nil + } + parsed, parseErr := strconv.ParseInt(match[1], 10, 32) + if parseErr != nil || parsed < 2 || match[1][0] == '0' { + if parseErr == nil { + parseErr = errors.New("index must be canonical and at least 2") + } + return 0, true, fmt.Errorf("invalid multidex index: %w", parseErr) + } + return int(parsed), true, nil +} + +func qualifiedEntry(prefix, name string) string { + if prefix == "" { + return name + } + return prefix + "!/" + name +} diff --git a/dex2jar/input/container_edge_test.go b/dex2jar/input/container_edge_test.go new file mode 100644 index 00000000..426ec47c --- /dev/null +++ b/dex2jar/input/container_edge_test.go @@ -0,0 +1,41 @@ +package input + +import ( + "strings" + "testing" + + "github.com/yaklang/javajive/internal/inputkind" +) + +func TestCollectContainerEdgeFailures(t *testing.T) { + empty := buildAPK(t, nil) + if _, err := collectAPK(empty, "", Options{}, false); err == nil || !strings.Contains(err.Error(), "no classes*.dex entries") { + t.Fatalf("empty APK error = %v", err) + } + if _, err := collectAPK([]byte("not a zip"), "", Options{}, false); err == nil { + t.Fatal("collectAPK accepted a non-ZIP") + } + if _, err := collectAPKS(empty, inputkind.APKS, Options{}); err == nil || !strings.Contains(err.Error(), "no nested .apk entries") { + t.Fatalf("empty bundle error = %v", err) + } + if _, err := collectAPKS([]byte("not a zip"), inputkind.APKS, Options{}); err == nil { + t.Fatal("collectAPKS accepted a non-ZIP") + } + + nestedEmpty := buildAPK(t, []zipEntry{{name: "base.apk", data: empty}}) + if _, err := collectAPKS(nestedEmpty, inputkind.APKS, Options{}); err == nil || !strings.Contains(err.Error(), "no classes*.dex entries in nested APKs") { + t.Fatalf("empty nested APK error = %v", err) + } + if _, err := collectAAB(empty, Options{}); err == nil || !strings.Contains(err.Error(), "no /dex/classes*.dex entries") { + t.Fatalf("empty AAB error = %v", err) + } + if _, err := collectAAB([]byte("not a zip"), Options{}); err == nil { + t.Fatal("collectAAB accepted a non-ZIP") + } +} + +func TestParseApplicationPropagatesClassificationFailure(t *testing.T) { + if _, _, err := ParseApplicationWithOptions([]byte("not an artifact"), "", Options{}); err == nil || !strings.Contains(err.Error(), "unsupported DEX input") { + t.Fatalf("ParseApplicationWithOptions error = %v", err) + } +} diff --git a/dex2jar/input/container_test.go b/dex2jar/input/container_test.go new file mode 100644 index 00000000..39eac3c1 --- /dev/null +++ b/dex2jar/input/container_test.go @@ -0,0 +1,256 @@ +package input + +import ( + "crypto/sha1" + "encoding/binary" + "hash/adler32" + "strings" + "testing" + + "github.com/yaklang/javajive/internal/inputkind" +) + +func TestCollectDEXSourcesAPKS(t *testing.T) { + base := buildAPK(t, []zipEntry{ + {name: "classes.dex", data: buildDEX(t, "Lbase/One;")}, + {name: "classes2.dex", data: buildDEX(t, "Lbase/Two;")}, + }) + split := buildAPK(t, []zipEntry{ + {name: "classes.dex", data: buildDEX(t, "Lsplit/Three;")}, + }) + bundle := buildAPK(t, []zipEntry{ + {name: "base.apk", data: base}, + {name: "split_config.apk", data: split}, + }) + sources, kind, err := CollectDEXSources(bundle, "app.apks", Options{}) + if err != nil { + t.Fatalf("CollectDEXSources: %v", err) + } + if kind != inputkind.APKS { + t.Fatalf("kind = %q, want apks", kind) + } + want := []string{ + "base.apk!/classes.dex", + "base.apk!/classes2.dex", + "split_config.apk!/classes.dex", + } + if len(sources) != len(want) { + t.Fatalf("sources = %d, want %d", len(sources), len(want)) + } + for index, entry := range want { + if sources[index].Entry != entry { + t.Fatalf("sources[%d].Entry = %q, want %q", index, sources[index].Entry, entry) + } + } + if sources[0].MultidexIndex != 1 || sources[1].MultidexIndex != 2 || sources[2].MultidexIndex != 1 { + t.Fatalf("multidex indexes = %d, %d, %d", sources[0].MultidexIndex, sources[1].MultidexIndex, sources[2].MultidexIndex) + } +} + +func TestCollectDEXSourcesAAB(t *testing.T) { + bundle := buildAPK(t, []zipEntry{ + {name: "base/dex/classes.dex", data: buildDEX(t, "Lbase/One;")}, + {name: "base/dex/classes2.dex", data: buildDEX(t, "Lbase/Two;")}, + {name: "feature/dex/classes.dex", data: buildDEX(t, "Lfeature/Three;")}, + }) + sources, kind, err := CollectDEXSources(bundle, "app.aab", Options{}) + if err != nil { + t.Fatalf("CollectDEXSources: %v", err) + } + if kind != inputkind.AAB { + t.Fatalf("kind = %q, want aab", kind) + } + want := []string{ + "base/dex/classes.dex", + "base/dex/classes2.dex", + "feature/dex/classes.dex", + } + if len(sources) != len(want) { + t.Fatalf("sources = %d, want %d", len(sources), len(want)) + } + for index, entry := range want { + if sources[index].Entry != entry { + t.Fatalf("sources[%d].Entry = %q, want %q", index, sources[index].Entry, entry) + } + } +} + +func TestParseApplicationAPKSPrefersUniversalAPK(t *testing.T) { + universal := buildAPK(t, []zipEntry{ + {name: "classes.dex", data: buildDEX(t, "Luniversal/Only;")}, + }) + split := buildAPK(t, []zipEntry{ + {name: "classes.dex", data: buildDEX(t, "Lsplit/Only;")}, + }) + bundle := buildAPK(t, []zipEntry{ + {name: "universal.apk", data: universal}, + {name: "base-master.apk", data: split}, + }) + app, kind, err := ParseApplicationWithOptions(bundle, "app.apks", Options{}) + if err != nil { + t.Fatalf("ParseApplicationWithOptions: %v", err) + } + if kind != inputkind.APKS || len(app.Files) != 1 { + t.Fatalf("kind/files = %q/%d", kind, len(app.Files)) + } + if app.Files[0].Entry != "universal.apk!/classes.dex" { + t.Fatalf("entry = %q", app.Files[0].Entry) + } + if len(app.Files[0].Classes) != 1 || app.Files[0].Classes[0].Descriptor != "Luniversal/Only;" { + t.Fatalf("classes = %#v", app.Files[0].Classes) + } +} + +func TestParseApplicationAPKSStandalonesUseSingleVariant(t *testing.T) { + first := buildAPK(t, []zipEntry{ + {name: "classes.dex", data: buildDEX(t, "Lvariant/First;")}, + }) + second := buildAPK(t, []zipEntry{ + {name: "classes.dex", data: buildDEX(t, "Lvariant/Second;")}, + }) + bundle := buildAPK(t, []zipEntry{ + {name: "standalones/standalone-b.apk", data: second}, + {name: "standalones/standalone-a.apk", data: first}, + }) + app, kind, err := ParseApplicationWithOptions(bundle, "app.apks", Options{}) + if err != nil { + t.Fatalf("ParseApplicationWithOptions: %v", err) + } + if kind != inputkind.APKS || len(app.Files) != 1 { + t.Fatalf("kind/files = %q/%d", kind, len(app.Files)) + } + if app.Files[0].Entry != "standalones/standalone-a.apk!/classes.dex" { + t.Fatalf("entry = %q", app.Files[0].Entry) + } + if len(app.Files[0].Classes) != 1 || app.Files[0].Classes[0].Descriptor != "Lvariant/First;" { + t.Fatalf("classes = %#v", app.Files[0].Classes) + } +} + +func TestParseApplicationXAPKSkipsResourceOnlySplit(t *testing.T) { + base := buildAPK(t, []zipEntry{ + {name: "classes.dex", data: buildDEX(t, "Lbase/One;")}, + }) + config := buildAPK(t, []zipEntry{ + {name: "res/raw/config.txt", data: []byte("resources only")}, + }) + bundle := buildAPK(t, []zipEntry{ + {name: "manifest.json", data: []byte(`{"xapk_version":2}`)}, + {name: "base.apk", data: base}, + {name: "config.arm64_v8a.apk", data: config}, + }) + app, kind, err := ParseApplicationWithOptions(bundle, "app.xapk", Options{}) + if err != nil { + t.Fatalf("ParseApplicationWithOptions: %v", err) + } + if kind != inputkind.XAPK || len(app.Files) != 1 { + t.Fatalf("kind/files = %q/%d", kind, len(app.Files)) + } + if app.Files[0].Entry != "base.apk!/classes.dex" { + t.Fatalf("entry = %q", app.Files[0].Entry) + } +} + +func TestParseApplicationAPKSDedupesIdenticalClasses(t *testing.T) { + first := buildAPK(t, []zipEntry{ + {name: "classes.dex", data: buildDEX(t, "Lduplicate/Class;")}, + }) + second := buildAPK(t, []zipEntry{ + {name: "classes.dex", data: buildDEX(t, "Lduplicate/Class;")}, + }) + bundle := buildAPK(t, []zipEntry{ + {name: "base.apk", data: first}, + {name: "split.apk", data: second}, + }) + app, _, err := ParseApplicationWithOptions(bundle, "app.apks", Options{}) + if err != nil { + t.Fatalf("ParseApplicationWithOptions: %v", err) + } + if len(app.Files) != 2 { + t.Fatalf("files = %d, want 2", len(app.Files)) + } + if len(app.Files[0].Classes) != 1 || len(app.Files[1].Classes) != 0 { + t.Fatalf("deduped classes = %d/%d", len(app.Files[0].Classes), len(app.Files[1].Classes)) + } +} + +func TestParseApplicationAPKSRejectsConflictingClasses(t *testing.T) { + first := buildDEX(t, "Lconflict/Class;") + secondFixture := buildDEXFixture(t, "Lconflict/Class;") + // Change the class access flags so the second definition differs. + const classDefAccessOffset = 4 + binary.LittleEndian.PutUint32(secondFixture.data[secondFixture.classDefsOff+classDefAccessOffset:], 0x0011) + fixDEXIntegrity(secondFixture.data) + firstAPK := buildAPK(t, []zipEntry{{name: "classes.dex", data: first}}) + secondAPK := buildAPK(t, []zipEntry{{name: "classes.dex", data: secondFixture.data}}) + bundle := buildAPK(t, []zipEntry{ + {name: "base.apk", data: firstAPK}, + {name: "split.apk", data: secondAPK}, + }) + _, _, err := ParseApplicationWithOptions(bundle, "app.apks", Options{}) + if err == nil || !strings.Contains(err.Error(), "duplicate class") { + t.Fatalf("error = %v, want duplicate class", err) + } +} + +func TestParseApplicationAPKSLimits(t *testing.T) { + makeBundle := func() []byte { + first := buildAPK(t, []zipEntry{{name: "classes.dex", data: buildDEX(t, "Llimit/One;")}}) + second := buildAPK(t, []zipEntry{{name: "classes.dex", data: buildDEX(t, "Llimit/Two;")}}) + return buildAPK(t, []zipEntry{ + {name: "base.apk", data: first}, + {name: "split.apk", data: second}, + }) + } + t.Run("nested APK count", func(t *testing.T) { + _, _, err := ParseApplicationWithOptions(makeBundle(), "app.apks", Options{MaxNestedAPKs: 1}) + if err == nil || !strings.Contains(err.Error(), "nested APK count") { + t.Fatalf("error = %v", err) + } + }) + t.Run("DEX file count", func(t *testing.T) { + _, _, err := ParseApplicationWithOptions(makeBundle(), "app.apks", Options{MaxDEXFiles: 1}) + if err == nil || !strings.Contains(err.Error(), "DEX file count") { + t.Fatalf("error = %v", err) + } + }) + t.Run("total nested APK size", func(t *testing.T) { + _, _, err := ParseApplicationWithOptions(makeBundle(), "app.apks", Options{MaxTotalAPKSize: 1}) + if err == nil || !strings.Contains(err.Error(), "total nested APK size") { + t.Fatalf("error = %v", err) + } + }) +} + +func TestCollectDEXSourcesRejectsJavaArchive(t *testing.T) { + archive := buildAPK(t, []zipEntry{ + {name: "META-INF/MANIFEST.MF", data: []byte("Manifest-Version: 1.0\r\n\r\n")}, + }) + _, kind, err := CollectDEXSources(archive, "library.jar", Options{}) + if kind != inputkind.JAR { + t.Fatalf("kind = %q, want jar", kind) + } + if err == nil || !strings.Contains(err.Error(), "unsupported DEX input") { + t.Fatalf("error = %v", err) + } +} + +func TestParseApplicationRawDEX(t *testing.T) { + app, kind, err := ParseApplicationWithOptions(buildDEX(t, "Lraw/One;"), "classes.bin", Options{}) + if err != nil { + t.Fatalf("ParseApplicationWithOptions: %v", err) + } + if kind != inputkind.DEX || len(app.Files) != 1 || app.Files[0].Entry != "classes.dex" { + t.Fatalf("kind/files = %q/%#v", kind, app.Files) + } +} + +func fixDEXIntegrity(data []byte) { + if len(data) < 32 { + return + } + signature := sha1.Sum(data[32:]) + copy(data[12:32], signature[:]) + checksum := adler32.Checksum(data[12:]) + binary.LittleEndian.PutUint32(data[8:12], checksum) +} diff --git a/dex2jar/input/fuzz_test.go b/dex2jar/input/fuzz_test.go new file mode 100644 index 00000000..429ca89e --- /dev/null +++ b/dex2jar/input/fuzz_test.go @@ -0,0 +1,59 @@ +package input + +import ( + "archive/zip" + "bytes" + "os" + "path/filepath" + "testing" +) + +func fuzzZIP(tb testing.TB, files map[string][]byte) []byte { + tb.Helper() + var buffer bytes.Buffer + writer := zip.NewWriter(&buffer) + for name, body := range files { + entry, err := writer.Create(name) + if err != nil { + tb.Fatal(err) + } + if _, err := entry.Write(body); err != nil { + tb.Fatal(err) + } + } + if err := writer.Close(); err != nil { + tb.Fatal(err) + } + return buffer.Bytes() +} + +func FuzzParseApplication(f *testing.F) { + dex, err := os.ReadFile(filepath.Join("..", "testdata", "accept", "arithmetic.dex")) + if err != nil { + dex = []byte("dex\n035\x00") + } + apk := fuzzZIP(f, map[string][]byte{"classes.dex": dex}) + apks := fuzzZIP(f, map[string][]byte{"base.apk": apk}) + aab := fuzzZIP(f, map[string][]byte{"base/dex/classes.dex": dex}) + seeds := [][]byte{ + dex, + apk, + apks, + aab, + []byte("dex\n035\x00"), + []byte("not an artifact"), + } + for _, seed := range seeds { + f.Add(seed) + } + options := Options{ + MaxDEXSize: 1 << 20, + MaxAPKSize: 2 << 20, + MaxTotalDEXSize: 2 << 20, + MaxDEXFiles: 8, + MaxNestedAPKs: 8, + } + f.Fuzz(func(t *testing.T, data []byte) { + _, _, _ = ParseApplicationWithOptions(data, "fuzz", options) + }) +} diff --git a/dex2jar/input/input.go b/dex2jar/input/input.go index 98582950..5a555d75 100644 --- a/dex2jar/input/input.go +++ b/dex2jar/input/input.go @@ -1,16 +1,12 @@ -// Package input loads raw DEX files and multidex APK archives. +// Package input loads raw DEX files, multidex APK archives, Android split +// bundles (APKS/XAPK/APKM), and Android App Bundles (AAB). package input import ( "archive/zip" - "bytes" - "errors" "fmt" "io" - "math" "regexp" - "sort" - "strconv" "github.com/yaklang/javajive/dex2jar/model" "github.com/yaklang/javajive/dex2jar/report" @@ -21,7 +17,9 @@ const ( DefaultMaxDEXSize int64 = 256 << 20 DefaultMaxAPKSize int64 = 512 << 20 DefaultMaxTotalDEXSize int64 = 512 << 20 + DefaultMaxTotalAPKSize int64 = 2 << 30 DefaultMaxDEXFiles = 128 + DefaultMaxNestedAPKs = 512 ) var dexEntryPattern = regexp.MustCompile(`^classes([0-9]*)\.dex$`) @@ -31,7 +29,13 @@ type Options struct { MaxDEXSize int64 MaxAPKSize int64 MaxTotalDEXSize int64 + // MaxTotalAPKSize bounds the sum of nested APK sizes in APKS/XAPK/APKM + // containers. Non-positive values use DefaultMaxTotalAPKSize. + MaxTotalAPKSize int64 MaxDEXFiles int + // MaxNestedAPKs bounds the number of nested APK entries in a split bundle. + // Non-positive values use DefaultMaxNestedAPKs. + MaxNestedAPKs int } func ParseDEX(data []byte, entry string) (*model.File, error) { @@ -51,76 +55,11 @@ func ParseAPK(data []byte) (*model.Application, error) { } func ParseAPKWithOptions(data []byte, options Options) (*model.Application, error) { - if int64(len(data)) > options.maxAPKSize() { - return nil, report.New("", "", "", -1, "APK", fmt.Errorf("archive size %d exceeds limit %d", len(data), options.maxAPKSize())) - } - reader, err := zip.NewReader(bytes.NewReader(data), int64(len(data))) + sources, err := collectAPK(data, "", options, false) if err != nil { - return nil, report.New("", "", "", -1, "APK", err) - } - type entry struct { - index int - file *zip.File - } - entries := make([]entry, 0) - seenIndex := make(map[int]string) - for _, file := range reader.File { - match := dexEntryPattern.FindStringSubmatch(file.Name) - if match == nil { - continue - } - index := 1 - if match[1] != "" { - parsed, parseErr := strconv.ParseInt(match[1], 10, 32) - if parseErr != nil || parsed < 2 || match[1][0] == '0' { - if parseErr == nil { - parseErr = fmt.Errorf("index must be canonical and at least 2") - } - return nil, report.New(file.Name, "", "", -1, "APK entry", fmt.Errorf("invalid multidex index: %w", parseErr)) - } - index = int(parsed) - } - if previous, exists := seenIndex[index]; exists { - return nil, report.New(file.Name, "", "", -1, "APK entry", fmt.Errorf("duplicate multidex index %d also used by %q", index, previous)) - } - seenIndex[index] = file.Name - entries = append(entries, entry{index: index, file: file}) - } - if len(entries) == 0 { - return nil, report.New("", "", "", -1, "APK", errors.New("no classes*.dex entries")) - } - if len(entries) > options.maxDEXFiles() { - return nil, report.New("", "", "", -1, "APK", fmt.Errorf("DEX file count %d exceeds limit %d", len(entries), options.maxDEXFiles())) - } - sort.Slice(entries, func(i, j int) bool { return entries[i].index < entries[j].index }) - app := &model.Application{Files: make([]*model.File, 0, len(entries))} - descriptors := make(map[string]string) - var totalDEXSize uint64 - for _, item := range entries { - if item.file.UncompressedSize64 > uint64(options.maxDEXSize()) || item.file.UncompressedSize64 > uint64(math.MaxInt) { - return nil, report.New(item.file.Name, "", "", -1, "APK entry", fmt.Errorf("uncompressed size %d exceeds limit", item.file.UncompressedSize64)) - } - if item.file.UncompressedSize64 > uint64(options.maxTotalDEXSize())-totalDEXSize { - return nil, report.New(item.file.Name, "", "", -1, "APK entry", fmt.Errorf("total DEX size exceeds limit %d", options.maxTotalDEXSize())) - } - totalDEXSize += item.file.UncompressedSize64 - contents, readErr := readZipEntry(item.file, options.maxDEXSize()) - if readErr != nil { - return nil, report.New(item.file.Name, "", "", -1, "APK entry", readErr) - } - file, parseErr := ParseDEXWithOptions(contents, item.file.Name, options) - if parseErr != nil { - return nil, parseErr - } - for _, class := range file.Classes { - if previous, exists := descriptors[class.Descriptor]; exists { - return nil, report.New(item.file.Name, class.Descriptor, "", -1, "duplicate class", fmt.Errorf("descriptor already defined in %q", previous)) - } - descriptors[class.Descriptor] = item.file.Name - } - app.Files = append(app.Files, file) + return nil, err } - return app, nil + return parseDEXSources(sources, options, true) } func readZipEntry(file *zip.File, limit int64) ([]byte, error) { @@ -164,9 +103,23 @@ func (o Options) maxTotalDEXSize() int64 { return o.MaxTotalDEXSize } +func (o Options) maxTotalAPKSize() int64 { + if o.MaxTotalAPKSize <= 0 { + return DefaultMaxTotalAPKSize + } + return o.MaxTotalAPKSize +} + func (o Options) maxDEXFiles() int { if o.MaxDEXFiles <= 0 { return DefaultMaxDEXFiles } return o.MaxDEXFiles } + +func (o Options) maxNestedAPKs() int { + if o.MaxNestedAPKs <= 0 { + return DefaultMaxNestedAPKs + } + return o.MaxNestedAPKs +} diff --git a/dex2jar/input/input_test.go b/dex2jar/input/input_test.go index c7e38462..2d74e71d 100644 --- a/dex2jar/input/input_test.go +++ b/dex2jar/input/input_test.go @@ -19,6 +19,20 @@ import ( "github.com/yaklang/javajive/internal/mutf8" ) +func TestParseDEXSourcesReleasesData(t *testing.T) { + sources := []DEXSource{{Entry: "classes.dex", Data: buildDEX(t, "Lexample/Release;")}} + app, err := parseDEXSources(sources, Options{}, true) + if err != nil { + t.Fatalf("parseDEXSources: %v", err) + } + if len(app.Files) != 1 { + t.Fatalf("files = %d, want 1", len(app.Files)) + } + if sources[0].Data != nil { + t.Fatalf("source data retained %d bytes after parse", len(sources[0].Data)) + } +} + func TestParseDEXFoundation(t *testing.T) { raw := buildDEX(t, "Lexample/Main;") file, err := ParseDEX(raw, "classes.dex") diff --git a/dex2jar/ir/build.go b/dex2jar/ir/build.go index 1556e8fb..e90257df 100644 --- a/dex2jar/ir/build.go +++ b/dex2jar/ir/build.go @@ -5,10 +5,17 @@ import ( "strings" "github.com/yaklang/javajive/dex2jar/model" + "github.com/yaklang/javajive/dex2jar/report" ) const dexAccessStatic = 0x0008 +// maxRegisterStateCells bounds the dense per-instruction register category +// table and the temporary states used to derive it. Four million cells leave +// ample room for ordinary methods while preventing hostile code/register +// dimensions from amplifying a small code item into an unbounded allocation. +const maxRegisterStateCells = 4 << 20 + // Build decodes, validates, builds the CFG, and derives stable register homes. func Build(in Input) (*Method, error) { ctx := contextFor(in) @@ -32,6 +39,10 @@ func Build(in Input) (*Method, error) { if err != nil { return nil, err } + stateCells := uint64(len(instructions)) * uint64(method.Code.RegistersSize) + if stateCells > maxRegisterStateCells { + return nil, diagnostic(ctx, nil, "resources", fmt.Errorf("instruction/register state space of %d instructions x %d registers (%d cells) exceeds limit %d", len(instructions), method.Code.RegistersSize, stateCells, maxRegisterStateCells)) + } result := &Method{Code: method.Code, Instructions: instructions, Context: ctx, Proto: proto, AccessFlags: method.AccessFlags} if err := validateInstructions(result, in.File); err != nil { return nil, err @@ -44,6 +55,12 @@ func Build(in Input) (*Method, error) { if err != nil { return nil, err } + result.blockByInstruction = make([]int, len(result.Instructions)) + for blockIndex := range result.Blocks { + for _, instructionIndex := range result.Blocks[blockIndex].Instructions { + result.blockByInstruction[instructionIndex] = blockIndex + } + } result.exceptionTypes = exceptionTypes(method.Code) if err := validateExceptionEntries(result); err != nil { return nil, err @@ -54,6 +71,7 @@ func Build(in Input) (*Method, error) { } result.Allocations = allocations for pass := 0; pass <= len(result.Instructions)+2; pass++ { + result.indexAllocations() result.RegisterTypes, err = analyzeCategories(result, in.File, result.Allocations) if err != nil { return nil, err @@ -78,13 +96,17 @@ func validateInstructions(method *Method, file *model.File) error { instruction := &method.Instructions[index] info := opcodeTable[instruction.Opcode] if !info.supported { - return diagnostic(method.Context, instruction, "", fmt.Errorf("construct is outside the supported DEX 035 subset; unsupported opcode family: %s", unsupportedFamily(instruction.Opcode))) + family := unsupportedFamily(instruction.Opcode) + return diagnostic(method.Context, instruction, "", report.Unsupported(family, fmt.Errorf("construct is outside the supported DEX 035 subset; unsupported opcode family: %s", family))) } for _, register := range instruction.Regs { if uint32(register) >= registerCount { - return diagnostic(method.Context, instruction, "", fmt.Errorf("register v%d is outside register file v0..v%d", register, registerCount-1)) + return diagnostic(method.Context, instruction, "", fmt.Errorf("register v%d is outside register file of %d registers", register, registerCount)) } } + if wideDefinitionOpcode(instruction.Opcode) && len(instruction.Regs) > 0 && uint32(instruction.Regs[0])+1 >= registerCount { + return diagnostic(method.Context, instruction, "", fmt.Errorf("wide destination v%d requires register v%d within register file of %d registers", instruction.Regs[0], instruction.Regs[0]+1, registerCount)) + } if instruction.Opcode == 0x1a || instruction.Opcode == 0x1b { if instruction.Index >= uint32(len(file.Strings)) { return diagnostic(method.Context, instruction, "", fmt.Errorf("string index %d is out of range", instruction.Index)) @@ -99,7 +121,7 @@ func validateInstructions(method *Method, file *model.File) error { return diagnostic(method.Context, instruction, "", fmt.Errorf("filled-new-array type %q is not an array", descriptor)) } if component := descriptor[1:]; component == "J" || component == "D" || component == "F" { - return diagnostic(method.Context, instruction, "", fmt.Errorf("filled-new-array of a wide or floating element is unsupported")) + return diagnostic(method.Context, instruction, "", report.Unsupported("filled-new-array wide or floating element", fmt.Errorf("filled-new-array of a wide or floating element is unsupported"))) } } if instruction.Opcode == 0x1c || instruction.Opcode == 0x1f || instruction.Opcode == 0x20 || instruction.Opcode == 0x22 || instruction.Opcode == 0x23 { @@ -418,6 +440,18 @@ func seedAllocationSite(method *Method, file *model.File, newIndex int) (site in // uninitialized value of that allocation. This is path-sensitive, so a // conditional constructor call or a branch that reuses a register cannot // confuse the pairing. It reports whether anything changed. +func (method *Method) indexAllocations() { + method.allocationNew = make(map[int]bool, len(method.Allocations)) + method.allocationCtor = make(map[int]bool, len(method.Allocations)) + for index := range method.Allocations { + allocation := &method.Allocations[index] + method.allocationNew[allocation.NewInstruction] = true + for _, constructor := range allocation.Constructors { + method.allocationCtor[constructor] = true + } + } +} + func resolveAllocationSites(method *Method, file *model.File) (bool, error) { position := make(map[uint32]int, len(method.Allocations)) for index := range method.Allocations { @@ -497,14 +531,10 @@ func fusedAllocationShape(method *Method, allocation *Allocation, constructor in } func blockOf(method *Method, instruction int) int { - for index := range method.Blocks { - for _, candidate := range method.Blocks[index].Instructions { - if candidate == instruction { - return index - } - } + if method == nil || instruction < 0 || instruction >= len(method.blockByInstruction) { + return -1 } - return -1 + return method.blockByInstruction[instruction] } func sameInstructionList(left, right []int) bool { diff --git a/dex2jar/ir/categories.go b/dex2jar/ir/categories.go index cdb916ec..daa0e0ac 100644 --- a/dex2jar/ir/categories.go +++ b/dex2jar/ir/categories.go @@ -21,13 +21,11 @@ func (m *Method) EffectsAt(index int) (uses, defs []uint16) { return nil, nil } instruction := m.Instructions[index] - for _, allocation := range m.Allocations { - if allocation.NewInstruction == index { - return nil, []uint16{instruction.Regs[0]} - } - if allocation.Constructor == index { - return append([]uint16(nil), instruction.Regs...), nil - } + if m.allocationNew[index] { + return nil, []uint16{instruction.Regs[0]} + } + if m.allocationCtor[index] { + return append([]uint16(nil), instruction.Regs...), nil } return instructionEffects(instruction) } diff --git a/dex2jar/ir/cfg.go b/dex2jar/ir/cfg.go index f30f4d44..5edf96a5 100644 --- a/dex2jar/ir/cfg.go +++ b/dex2jar/ir/cfg.go @@ -158,21 +158,24 @@ func buildBlocks(instructions []Instruction, codeUnits uint32, ctx Context, site sort.Slice(starts, func(i, j int) bool { return starts[i] < starts[j] }) blocks := make([]Block, len(starts)) blockAt := make(map[uint32]int, len(starts)) + instructionIndex := 0 for index, start := range starts { end := codeUnits if index+1 < len(starts) { end = starts[index+1] } - block := Block{ID: index, Start: start, End: end} - for instructionIndex, instruction := range instructions { - if instruction.Offset >= start && instruction.Offset < end { - block.Instructions = append(block.Instructions, instructionIndex) - } + first := instructionIndex + for instructionIndex < len(instructions) && instructions[instructionIndex].Offset < end { + instructionIndex++ } - if len(block.Instructions) == 0 { + if first == instructionIndex || instructions[first].Offset < start { return nil, diagnostic(ctx, nil, "cfg", fmt.Errorf("block at code-unit offset %d is empty", start)) } - blocks[index] = block + indices := make([]int, instructionIndex-first) + for offset := range indices { + indices[offset] = first + offset + } + blocks[index] = Block{ID: index, Start: start, End: end, Instructions: indices} blockAt[start] = index } addSuccessor := func(block *Block, successor int) { diff --git a/dex2jar/ir/decode.go b/dex2jar/ir/decode.go index f5de08b7..7d93ae60 100644 --- a/dex2jar/ir/decode.go +++ b/dex2jar/ir/decode.go @@ -14,6 +14,9 @@ func Decode(code *model.Code, ctx Context) ([]Instruction, error) { return nil, diagnostic(ctx, nil, "code", fmt.Errorf("nil code item")) } words := code.Instructions + if uint64(len(words)) > math.MaxUint32 { + return nil, diagnostic(ctx, nil, "code", fmt.Errorf("instruction stream has %d code units; maximum addressable size is %d", len(words), uint64(math.MaxUint32))) + } instructions := make([]Instruction, 0, len(words)) for offset := uint32(0); offset < uint32(len(words)); { word := words[offset] @@ -32,7 +35,7 @@ func Decode(code *model.Code, ctx Context) ([]Instruction, error) { if !known { return nil, diagnostic(ctx, &Instruction{Offset: offset, Opcode: opcode, Name: "unknown"}, "", fmt.Errorf("unknown DEX 035 opcode")) } - if offset+uint32(info.width) > uint32(len(words)) { + if uint64(offset)+uint64(info.width) > uint64(len(words)) { return nil, diagnostic(ctx, &Instruction{Offset: offset, Opcode: opcode, Name: info.name}, "", fmt.Errorf("truncated %s instruction: need %d code units, have %d", info.format, info.width, uint32(len(words))-offset)) } instruction := Instruction{Offset: offset, Opcode: opcode, Name: info.name, Format: info.format, Width: info.width, Target: -1} @@ -132,14 +135,14 @@ func Decode(code *model.Code, ctx Context) ([]Instruction, error) { instruction.Regs = []uint16{word >> 8} instruction.Target = int64(offset) + int64(int32(uint32(word1())|uint32(word2())<<16)) if opcode == 0x2b || opcode == 0x2c { - targets, keys, firstKey, err := decodeSwitchPayload(words, uint32(instruction.Target), offset, opcode == 0x2c) + targets, keys, firstKey, err := decodeSwitchPayload(words, instruction.Target, offset, opcode == 0x2c) if err != nil { return nil, diagnostic(ctx, &instruction, "", err) } instruction.Targets, instruction.Keys, instruction.FirstKey = targets, keys, firstKey } if opcode == 0x26 { - data, width, err := decodeFillArrayPayload(words, uint32(instruction.Target)) + data, width, err := decodeFillArrayPayload(words, instruction.Target) if err != nil { return nil, diagnostic(ctx, &instruction, "", err) } diff --git a/dex2jar/ir/ir.go b/dex2jar/ir/ir.go index 3a610b6c..39d4e0f5 100644 --- a/dex2jar/ir/ir.go +++ b/dex2jar/ir/ir.go @@ -107,9 +107,12 @@ func (k CategoryKind) isUntyped() bool { // Category records a register category at a program point. Allocation is the // code-unit offset of new-instance plus one; zero means no allocation identity. type Category struct { - Kind CategoryKind + // Field order is load-bearing: the descriptor (16 B) and allocation (4 B) + // come first so Kind occupies existing tail padding. The previous layout + // padded Kind to 8 B and made every dense category cell 32 B instead of 24. Descriptor string Allocation uint32 + Kind CategoryKind } // Instruction is one decoded DEX instruction. @@ -203,6 +206,11 @@ type Method struct { exceptionTypes map[uint32]string // demands records the categories each instruction requires of its operands. demands [][]demand + // blockByInstruction provides constant-time instruction-to-block lookup for + // allocation shape checks. + blockByInstruction []int + allocationNew map[int]bool + allocationCtor map[int]bool } func contextFor(in Input) Context { diff --git a/dex2jar/ir/ir_test.go b/dex2jar/ir/ir_test.go index d48c9169..b3e00172 100644 --- a/dex2jar/ir/ir_test.go +++ b/dex2jar/ir/ir_test.go @@ -1,6 +1,7 @@ package ir import ( + "math" "strings" "testing" @@ -34,6 +35,20 @@ func fixture(code []uint16, registers, ins uint16, proto model.Proto, flags uint return Input{File: file, Class: class, Method: method} } +func TestBuildRejectsAmplifiedRegisterStateSpace(t *testing.T) { + words := make([]uint16, 65) + for index := range words { + words[index] = 0x000e + } + _, err := Build(fixture(words, math.MaxUint16, 0, model.Proto{ReturnType: "V"}, dexAccessStatic)) + if err == nil || !strings.Contains(err.Error(), "instruction/register state space") || !strings.Contains(err.Error(), "exceeds limit") { + t.Fatalf("Build() error = %v", err) + } + if report.IsUnsupported(err) { + t.Fatalf("resource error was marked unsupported: %v", err) + } +} + func TestBuildRejectsInsufficientOutsSize(t *testing.T) { // invoke-direct {v0},LFoo;->()V needs one outgoing word. in := fixture([]uint16{0x1070, 0x0002, 0x0000, 0x000e}, 1, 0, model.Proto{ReturnType: "V"}, dexAccessStatic) @@ -518,6 +533,35 @@ func filledArrayInput(typeDescriptor string, words []uint16) Input { return Input{File: file, Class: class, Method: method} } +func TestBuildMarksOnlyKnownCapabilityFailuresUnsupported(t *testing.T) { + tests := []struct { + name string + in Input + }{ + { + name: "opcode family", + in: fixture([]uint16{0x00fe, 0x0000}, 1, 0, model.Proto{ReturnType: "V"}, dexAccessStatic), + }, + { + name: "filled new array element", + in: filledArrayInput("[J", []uint16{0x1024, 0x0000, 0x0000, 0x000c, 0x0011}), + }, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + _, err := Build(test.in) + if err == nil || !report.IsUnsupported(err) { + t.Fatalf("Build() error = %v, want typed unsupported capability", err) + } + }) + } + + malformed := filledArrayInput("I", []uint16{0x1024, 0x0000, 0x0000, 0x000c, 0x0011}) + if _, err := Build(malformed); err == nil || report.IsUnsupported(err) { + t.Fatalf("malformed Build() error = %v, want non-capability diagnostic", err) + } +} + func TestBuildRejectsMalformedFilledNewArray(t *testing.T) { tests := []struct { name string diff --git a/dex2jar/ir/performance_test.go b/dex2jar/ir/performance_test.go new file mode 100644 index 00000000..aee452d8 --- /dev/null +++ b/dex2jar/ir/performance_test.go @@ -0,0 +1,56 @@ +package ir + +import ( + "fmt" + "testing" + "unsafe" +) + +func TestCategoryCellStaysCompact(t *testing.T) { + // Dense category tables can contain millions of cells. Keep the layout at + // 24 bytes; moving Descriptor before Allocation/Kind removed 8 bytes of + // alignment padding per cell. + if size := unsafe.Sizeof(Category{}); size > 24 { + t.Fatalf("Category cell is %d bytes, want <= 24", size) + } +} + +func TestBuildBlocksScaleFixture(t *testing.T) { + instructions, codeUnits := branchScaleFixture(12000) + blocks, err := buildBlocks(instructions, codeUnits, Context{}, nil) + if err != nil { + t.Fatalf("buildBlocks() error = %v", err) + } + if got, want := len(blocks), len(instructions); got != want { + t.Fatalf("block count = %d, want %d", got, want) + } + for index := range blocks { + if len(blocks[index].Instructions) != 1 || blocks[index].Instructions[0] != index { + t.Fatalf("block %d instructions = %v", index, blocks[index].Instructions) + } + } +} + +func BenchmarkBuildBlocksScale(b *testing.B) { + for _, count := range []int{256, 1024, 4096, 16384} { + b.Run(fmt.Sprintf("%d", count), func(b *testing.B) { + instructions, codeUnits := branchScaleFixture(count) + b.ReportAllocs() + b.SetBytes(int64(len(instructions))) + for i := 0; i < b.N; i++ { + if _, err := buildBlocks(instructions, codeUnits, Context{}, nil); err != nil { + b.Fatal(err) + } + } + }) + } +} + +func branchScaleFixture(count int) ([]Instruction, uint32) { + instructions := make([]Instruction, count) + for index := range instructions { + instructions[index] = Instruction{Offset: uint32(index), Opcode: 0x28, Name: "goto", Width: 1, Target: int64((index + 1) % count)} + } + instructions[count-1] = Instruction{Offset: uint32(count - 1), Opcode: 0x0e, Name: "return-void", Width: 1, Target: -1} + return instructions, uint32(count) +} diff --git a/dex2jar/ir/switch.go b/dex2jar/ir/switch.go index 24fca790..9281d40c 100644 --- a/dex2jar/ir/switch.go +++ b/dex2jar/ir/switch.go @@ -10,20 +10,22 @@ import ( // payload itself is data, so the decoder skips it and the switch instruction // that references it decodes the contents. func payloadUnits(words []uint16, offset uint32, ctx Context) (uint32, error) { - if offset+1 >= uint32(len(words)) { + remaining := uint64(len(words)) - uint64(offset) + if remaining < 2 { instruction := Instruction{Offset: offset, Opcode: 0, Name: "payload"} return 0, diagnostic(ctx, &instruction, "payload", fmt.Errorf("truncated payload header")) } + var total uint64 switch words[offset] { case 0x0100: // packed-switch-payload: ident, size, first_key, size targets. - return 4 + 2*uint32(words[offset+1]), nil + total = 4 + 2*uint64(words[offset+1]) case 0x0200: // sparse-switch-payload: ident, size, size (key, target) pairs. - return 2 + 4*uint32(words[offset+1]), nil + total = 2 + 4*uint64(words[offset+1]) case 0x0300: // fill-array-data-payload: ident, element_width, size, data. - if offset+3 >= uint32(len(words)) { + if remaining < 4 { instruction := Instruction{Offset: offset, Opcode: 0, Name: "fill-array-data-payload"} return 0, diagnostic(ctx, &instruction, "payload", fmt.Errorf("truncated fill-array-data payload header")) } @@ -33,38 +35,49 @@ func payloadUnits(words []uint16, offset uint32, ctx Context) (uint32, error) { return 0, diagnostic(ctx, &instruction, "payload", fmt.Errorf("fill-array-data element width %d is not 1, 2, 4 or 8", width)) } size := uint32(words[offset+2]) | uint32(words[offset+3])<<16 - total := 4 + (uint64(size)*uint64(width)+1)/2 - if total > uint64(len(words)) { - instruction := Instruction{Offset: offset, Opcode: 0, Name: "fill-array-data-payload"} - return 0, diagnostic(ctx, &instruction, "payload", fmt.Errorf("fill-array-data payload is truncated")) - } - return uint32(total), nil + total = 4 + (uint64(size)*uint64(width)+1)/2 default: instruction := Instruction{Offset: offset, Opcode: 0, Name: "payload"} return 0, diagnostic(ctx, &instruction, "payload", fmt.Errorf("unknown payload identifier %#04x", words[offset])) } + if total > remaining { + instruction := Instruction{Offset: offset, Opcode: 0, Name: "payload"} + return 0, diagnostic(ctx, &instruction, "payload", fmt.Errorf("payload at %d is truncated: need %d code units, have %d", offset, total, remaining)) + } + return uint32(total), nil } // decodeFillArrayPayload returns the raw element bytes of a fill-array-data // payload. The width and count are kept in the payload header; the caller // matches them against the array component type. -func decodeFillArrayPayload(words []uint16, base uint32) ([]byte, uint16, error) { - if base+3 >= uint32(len(words)) || words[base] != 0x0300 { - return nil, 0, fmt.Errorf("fill-array-data payload at %d is missing or has the wrong identifier", base) +func decodeFillArrayPayload(words []uint16, base int64) ([]byte, uint16, error) { + if base < 0 || base >= int64(len(words)) { + return nil, 0, fmt.Errorf("fill-array-data payload target %d is outside code units [0,%d)", base, len(words)) + } + start := int(base) + if words[start] != 0x0300 { + return nil, 0, fmt.Errorf("fill-array-data payload at %d has the wrong identifier", base) } - width := uint32(words[base+1]) + if len(words)-start < 4 { + return nil, 0, fmt.Errorf("fill-array-data payload at %d has a truncated header", base) + } + width := uint32(words[start+1]) if width != 1 && width != 2 && width != 4 && width != 8 { return nil, 0, fmt.Errorf("fill-array-data element width %d is not 1, 2, 4 or 8", width) } - size := uint32(words[base+2]) | uint32(words[base+3])<<16 + size := uint32(words[start+2]) | uint32(words[start+3])<<16 total := uint64(size) * uint64(width) units := (total + 1) / 2 - if uint64(base)+4+units > uint64(len(words)) { + if 4+units > uint64(len(words)-start) { return nil, 0, fmt.Errorf("fill-array-data payload at %d is truncated", base) } - data := make([]byte, total) + maxInt := uint64(^uint(0) >> 1) + if total > maxInt { + return nil, 0, fmt.Errorf("fill-array-data payload at %d has %d bytes, which exceeds the addressable allocation size", base, total) + } + data := make([]byte, int(total)) for index := uint64(0); index < total; index++ { - unit := words[base+4+uint32(index/2)] + unit := words[start+4+int(index/2)] if index%2 == 0 { data[index] = byte(unit) } else { @@ -93,36 +106,40 @@ func fillArrayElementWidth(component string) (int, error) { // decodeSwitchPayload resolves the case table a packed or sparse switch // references. Case addresses are relative to the switch instruction itself. -func decodeSwitchPayload(words []uint16, base, switchOffset uint32, sparse bool) ([]int64, []int32, int32, error) { +func decodeSwitchPayload(words []uint16, base int64, switchOffset uint32, sparse bool) ([]int64, []int32, int32, error) { ident := uint16(0x0100) - units := uint64(0) if sparse { ident = 0x0200 - units = 2 } - if base >= uint32(len(words)) || words[base] != ident { + if base < 0 || base >= int64(len(words)) { + return nil, nil, 0, fmt.Errorf("switch payload target %d is outside code units [0,%d)", base, len(words)) + } + start := int(base) + if words[start] != ident { return nil, nil, 0, fmt.Errorf("switch payload at %d does not match the opcode", base) } - size := uint32(words[base+1]) + if len(words)-start < 2 { + return nil, nil, 0, fmt.Errorf("switch payload at %d has a truncated header", base) + } + size := uint64(words[start+1]) + units := uint64(4) + 2*size if sparse { - units += 4 * uint64(size) - } else { - units = 4 + 2*uint64(size) + units = 2 + 4*size } - if uint64(base)+units > uint64(len(words)) { + if units > uint64(len(words)-start) { return nil, nil, 0, fmt.Errorf("switch payload at %d is truncated", base) } - read32 := func(at uint32) int32 { + read32 := func(at int) int32 { return int32(uint32(words[at]) | uint32(words[at+1])<<16) } if !sparse { - first := read32(base + 2) - if first > math.MaxInt32-int32(size)+1 { + first := read32(start + 2) + if size > 0 && int64(first)+int64(size)-1 > math.MaxInt32 { return nil, nil, 0, fmt.Errorf("packed switch key range starting at %d overflows", first) } - targets := make([]int64, size) - for index := uint32(0); index < size; index++ { - targets[index] = int64(switchOffset) + int64(read32(base+4+2*index)) + targets := make([]int64, int(size)) + for index := 0; index < int(size); index++ { + targets[index] = int64(switchOffset) + int64(read32(start+4+2*index)) } return targets, nil, first, nil } @@ -133,17 +150,17 @@ func decodeSwitchPayload(words []uint16, base, switchOffset uint32, sparse bool) key int32 target int64 } - pairs := make([]casePair, size) - targetsBase := base + 2 + 2*size - for index := uint32(0); index < size; index++ { + pairs := make([]casePair, int(size)) + targetsBase := start + 2 + 2*int(size) + for index := 0; index < int(size); index++ { pairs[index] = casePair{ - key: read32(base + 2 + 2*index), + key: read32(start + 2 + 2*index), target: int64(switchOffset) + int64(read32(targetsBase+2*index)), } } sort.Slice(pairs, func(i, j int) bool { return pairs[i].key < pairs[j].key }) - keys := make([]int32, size) - targets := make([]int64, size) + keys := make([]int32, int(size)) + targets := make([]int64, int(size)) for index, pair := range pairs { if index > 0 && pair.key == pairs[index-1].key { return nil, nil, 0, fmt.Errorf("sparse switch repeats key %d", pair.key) diff --git a/dex2jar/ir/switch_test.go b/dex2jar/ir/switch_test.go index 862407bd..31141ed7 100644 --- a/dex2jar/ir/switch_test.go +++ b/dex2jar/ir/switch_test.go @@ -1,6 +1,8 @@ package ir import ( + "math" + "strings" "testing" "github.com/yaklang/javajive/dex2jar/model" @@ -59,6 +61,63 @@ func TestDecodeSparseSwitchSortsKeys(t *testing.T) { } } +func TestDecodeRejectsInvalidSignedPayloadTargets(t *testing.T) { + tests := []struct { + name string + words []uint16 + want string + }{ + { + name: "negative switch", + words: []uint16{0x002b, 0xffff, 0xffff}, + want: "switch payload target -1 is outside code units [0,3)", + }, + { + name: "wrapped switch", + words: []uint16{0x002b, 0x0000, 0x8000}, + want: "switch payload target -2147483648 is outside code units [0,3)", + }, + { + name: "final word switch", + words: []uint16{0x002b, 0x0003, 0x0000, 0x0100}, + want: "switch payload at 3 has a truncated header", + }, + { + name: "negative fill array", + words: []uint16{0x0026, 0xffff, 0xffff}, + want: "fill-array-data payload target -1 is outside code units [0,3)", + }, + { + name: "final word fill array", + words: []uint16{0x0026, 0x0003, 0x0000, 0x0300}, + want: "fill-array-data payload at 3 has a truncated header", + }, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + _, err := Decode(&model.Code{Instructions: test.words}, Context{Entry: "classes.dex", Class: "LC;", Method: "m"}) + if err == nil || !strings.Contains(err.Error(), test.want) { + t.Fatalf("Decode() error = %v, want %q", err, test.want) + } + }) + } +} + +func TestPayloadIndexingRejectsWrappedAndTruncatedRanges(t *testing.T) { + if _, _, _, err := decodeSwitchPayload([]uint16{0x0100, 0}, int64(math.MaxUint32)+1, 0, false); err == nil || !strings.Contains(err.Error(), "outside code units") { + t.Fatalf("decodeSwitchPayload() error = %v", err) + } + if _, _, err := decodeFillArrayPayload([]uint16{0x0300, 1, 0, 0}, int64(math.MaxUint32)+1); err == nil || !strings.Contains(err.Error(), "outside code units") { + t.Fatalf("decodeFillArrayPayload() error = %v", err) + } + if _, _, _, err := decodeSwitchPayload([]uint16{0x0100, 1, 0, 0, 0}, 0, 0, false); err == nil || !strings.Contains(err.Error(), "truncated") { + t.Fatalf("decodeSwitchPayload() error = %v", err) + } + if _, _, err := decodeFillArrayPayload([]uint16{0x0300, 8, 1, 0}, 0); err == nil || !strings.Contains(err.Error(), "truncated") { + t.Fatalf("decodeFillArrayPayload() error = %v", err) + } +} + func TestBuildPackedSwitchSuccessors(t *testing.T) { words := []uint16{ 0x002b, 0x0008, 0x0000, // packed-switch v0, payload@8 diff --git a/dex2jar/lower/annotations.go b/dex2jar/lower/annotations.go index 18051d0c..7214f109 100644 --- a/dex2jar/lower/annotations.go +++ b/dex2jar/lower/annotations.go @@ -96,6 +96,12 @@ func builderValue(file *model.File, value model.EncodedValue) (classfilebuilder. return classfilebuilder.AnnotationValue{Kind: classfilebuilder.AnnotationChar, Int: int64(uint16(value.Unsigned))}, nil case model.ValueInt: return classfilebuilder.AnnotationValue{Kind: classfilebuilder.AnnotationInt, Int: int64(int32(value.Signed))}, nil + case model.ValueLong: + return classfilebuilder.AnnotationValue{Kind: classfilebuilder.AnnotationLong, Int: value.Signed}, nil + case model.ValueFloat: + return classfilebuilder.AnnotationValue{Kind: classfilebuilder.AnnotationFloat, Bits: value.Unsigned}, nil + case model.ValueDouble: + return classfilebuilder.AnnotationValue{Kind: classfilebuilder.AnnotationDouble, Bits: value.Unsigned}, nil case model.ValueString: if value.Unsigned >= uint64(len(file.Strings)) { return classfilebuilder.AnnotationValue{}, fmt.Errorf("string index %d is out of range", value.Unsigned) @@ -187,7 +193,11 @@ func typeArrayElement(file *model.File, annotation model.Annotation, name string if item.Unsigned >= uint64(len(file.Types)) { return nil, fmt.Errorf("type index %d is out of range", item.Unsigned) } - descriptors = append(descriptors, file.Types[item.Unsigned].Descriptor) + descriptor := file.Types[item.Unsigned].Descriptor + if err := classfilebuilder.ValidateObjectDescriptor(descriptor); err != nil { + return nil, fmt.Errorf("Throws type %q: %w", descriptor, err) + } + descriptors = append(descriptors, descriptor) } return descriptors, nil } diff --git a/dex2jar/lower/interface_test.go b/dex2jar/lower/interface_test.go index 54ec7b64..76180cb2 100644 --- a/dex2jar/lower/interface_test.go +++ b/dex2jar/lower/interface_test.go @@ -4,6 +4,7 @@ import ( "os" "os/exec" "path/filepath" + "strings" "testing" javaclassparser "github.com/yaklang/javajive/classparser" @@ -61,6 +62,62 @@ func interfaceStaticFixture() (*model.File, *model.Class) { return file, class } +func TestLowerRejectsIllegalInterfaceMemberShapes(t *testing.T) { + const owner = "Ldex/IllegalInterface;" + tests := []struct { + name string + prepare func(*model.File, *model.Class) + want string + }{ + { + name: "field visibility", + prepare: func(_ *model.File, class *model.Class) { + class.StaticFields = []model.EncodedField{{ + AccessFlags: dexPrivate | dexStatic | dexFinal, + Field: model.FieldID{Class: owner, Name: "VALUE", Type: "I"}, + }} + }, + want: "interface field must be public static final", + }, + { + name: "instance constructor", + prepare: func(file *model.File, class *model.Class) { + class.DirectMethods = []model.EncodedMethod{{ + AccessFlags: dexPublic | dexConstructor, + Method: model.MethodID{Class: owner, Name: "", ProtoIndex: 0}, + Code: &model.Code{RegistersSize: 1, InsSize: 1, Instructions: []uint16{0x000e}}, + }} + file.Protos = []model.Proto{{ReturnType: "V"}} + }, + want: "interface must not declare an instance constructor", + }, + { + name: "abstract static method", + prepare: func(file *model.File, class *model.Class) { + class.DirectMethods = []model.EncodedMethod{{ + AccessFlags: dexPublic | dexStatic | dexAbstract, + Method: model.MethodID{Class: owner, Name: "run", ProtoIndex: 0}, + }} + file.Protos = []model.Proto{{ReturnType: "V"}} + }, + want: "abstract method has incompatible access flags", + }, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + file := &model.File{Entry: "classes.dex"} + class := &model.Class{Descriptor: owner, Superclass: "Ljava/lang/Object;", AccessFlags: dexPublic | dexInterface | dexAbstract} + test.prepare(file, class) + if _, err := ClassWithPolicy(file, class, ClassOptions{}, Recover); err != nil { + t.Fatalf("Recover should fall back to a minimal shell: %v", err) + } + if _, err := Class(file, class); err == nil || !strings.Contains(err.Error(), test.want) { + t.Fatalf("Class error = %v, want %q", err, test.want) + } + }) + } +} + func TestLowerInterfaceStaticMethodsVerifyAndExecute(t *testing.T) { file, class := interfaceStaticFixture() raw, err := Class(file, class) diff --git a/dex2jar/lower/lower.go b/dex2jar/lower/lower.go index 77aefb43..bf3272b9 100644 --- a/dex2jar/lower/lower.go +++ b/dex2jar/lower/lower.go @@ -2,6 +2,7 @@ package lower import ( + "errors" "fmt" "strings" @@ -45,6 +46,41 @@ type ClassOptions struct { // so assignability must be provable across files. When nil, only the file // being lowered is consulted. Hierarchy map[string]*model.Class + // ForceClassShell skips normal lowering and emits a declaration-preserving + // shell. Application recovery uses this when a superclass or interface was + // reduced to a minimal shell. + ForceClassShell bool + // RecoveryReason is embedded in diagnostics when ForceClassShell is set. + RecoveryReason string +} + +// FailurePolicy controls whether a method-local unsupported capability aborts +// the class or becomes a verifier-safe throwing stub. Malformed input and +// internal failures are never eligible for stubbing. +type FailurePolicy uint8 + +const ( + Strict FailurePolicy = iota + StubUnsupportedMethods + Recover +) + +// StubbedMethod records one concrete method whose body was replaced because +// the DEX construct is outside the translator's supported capability set. +type StubbedMethod struct { + Method string + Descriptor string + Feature string + Message string +} + +// ClassResult is the classfile and any explicit method degradation evidence. +type ClassResult struct { + Bytes []byte + StubbedMethods []StubbedMethod + Recoveries []Recovery + ClassStubbed bool + ClassMinimal bool } // Class lowers one parser-neutral DEX class. It never returns partial bytes. @@ -54,40 +90,78 @@ func Class(file *model.File, class *model.Class) ([]byte, error) { // ClassWithOptions is Class with explicit caller-provided guarantees. func ClassWithOptions(file *model.File, class *model.Class, options ClassOptions) ([]byte, error) { + result, err := ClassWithPolicy(file, class, options, Strict) + return result.Bytes, err +} + +// ClassWithPolicy lowers one DEX class with an explicit unsupported-capability +// policy. It never returns partial class bytes. +func ClassWithPolicy(file *model.File, class *model.Class, options ClassOptions, policy FailurePolicy) (ClassResult, error) { if file == nil { - return nil, report.New("", "", "", -1, "class", fmt.Errorf("nil DEX file")) + return ClassResult{}, report.New("", "", "", -1, "class", fmt.Errorf("nil DEX file")) } if class == nil { - return nil, report.New(file.Entry, "", "", -1, "class", fmt.Errorf("nil class")) + return ClassResult{}, report.New(file.Entry, "", "", -1, "class", fmt.Errorf("nil class")) + } + if policy != Strict && policy != StubUnsupportedMethods && policy != Recover { + return ClassResult{}, classDiagnostic(file, class, "class", fmt.Errorf("unknown failure policy %d", policy)) } + if policy == Recover { + if options.ForceClassShell { + reason := options.RecoveryReason + if reason == "" { + reason = "application dependency requires a class shell" + } + return emitClassShell(file, class, options, errors.New(reason), false) + } + result, err := classWithPolicyOnce(file, class, options, StubUnsupportedMethods) + if err == nil { + return result, nil + } + shell, shellErr := emitClassShell(file, class, options, err, false) + if shellErr == nil { + return shell, nil + } + shell, reducedErr := emitClassShell(file, class, options, err, true) + if reducedErr == nil { + return shell, nil + } + return emitMinimalClassShell(file, class, fmt.Errorf("normal=%v; declaration shell=%v; reduced shell=%v", err, shellErr, reducedErr)) + } + return classWithPolicyOnce(file, class, options, policy) +} + +func classWithPolicyOnce(file *model.File, class *model.Class, options ClassOptions, policy FailurePolicy) (ClassResult, error) { className, err := objectInternalName(class.Descriptor) if err != nil { - return nil, classDiagnostic(file, class, "class", err) + return ClassResult{}, classDiagnostic(file, class, "class", err) } superName, err := superclassName(class) if err != nil { - return nil, classDiagnostic(file, class, "class", err) + return ClassResult{}, classDiagnostic(file, class, "class", err) } access, err := classAccess(class.AccessFlags) if err != nil { - return nil, classDiagnostic(file, class, "class", err) + return ClassResult{}, classDiagnostic(file, class, "class", err) } if class.AccessFlags&dexInterface != 0 && class.Superclass != "Ljava/lang/Object;" { - return nil, classDiagnostic(file, class, "class", fmt.Errorf("interface superclass must be java/lang/Object")) + return ClassResult{}, classDiagnostic(file, class, "class", fmt.Errorf("interface superclass must be java/lang/Object")) } if interfaceNeedsJava8(class) { // Static and default interface methods require a Java 8 class file. The - // translator does not emit StackMapTable, so only methods without - // control flow or handlers can use it. - if err := validateNoControlFlow(file, class); err != nil { - return nil, err + // translator does not emit StackMapTable, so ordinary translated methods + // may not have control flow or handlers. Throwing stubs are straight-line. + if policy == Strict { + if err := validateNoControlFlow(file, class); err != nil { + return ClassResult{}, err + } } builder := classfilebuilder.NewClass(className, superName, access) builder.SetVersion(classfilebuilder.VersionJava8) - return lowerClassBody(file, class, builder, options) + return lowerClassBody(file, class, builder, options, policy) } builder := classfilebuilder.NewClass(className, superName, access) - return lowerClassBody(file, class, builder, options) + return lowerClassBody(file, class, builder, options, policy) } // interfaceNeedsJava8 reports whether an interface carries a static or default @@ -132,7 +206,7 @@ func validateNoControlFlow(file *model.File, class *model.Class) error { // lowerClassBody emits members and attributes into an already configured // builder. -func lowerClassBody(file *model.File, class *model.Class, builder *classfilebuilder.Class, options ClassOptions) ([]byte, error) { +func lowerClassBody(file *model.File, class *model.Class, builder *classfilebuilder.Class, options ClassOptions, policy FailurePolicy) (ClassResult, error) { if class.SourceFile != "" { builder.SetSourceFile(class.SourceFile) } @@ -159,7 +233,7 @@ func lowerClassBody(file *model.File, class *model.Class, builder *classfilebuil if len(class.Annotations) > 0 { translated, err := translateAnnotations(file, class.Annotations) if err != nil { - return nil, classDiagnostic(file, class, "annotation", err) + return ClassResult{}, classDiagnostic(file, class, "annotation", err) } if translated.signature != "" { builder.SetClassSignature(translated.signature) @@ -171,36 +245,41 @@ func lowerClassBody(file *model.File, class *model.Class, builder *classfilebuil for _, descriptor := range class.Interfaces { name, err := objectInternalName(descriptor) if err != nil { - return nil, classDiagnostic(file, class, "interface", err) + return ClassResult{}, classDiagnostic(file, class, "interface", err) } builder.AddInterface(name) } if err := addFields(file, class, builder); err != nil { - return nil, err + return ClassResult{}, err } seenMethods := make(map[string]bool) + var stubbed []StubbedMethod for _, method := range appendMethods(class.DirectMethods, class.VirtualMethods) { if int(method.Method.ProtoIndex) >= len(file.Protos) { - return nil, methodDiagnostic(methodContext(file, class, &method), nil, "method", fmt.Errorf("proto index %d is out of range", method.Method.ProtoIndex)) + return ClassResult{}, methodDiagnostic(methodContext(file, class, &method), nil, "method", fmt.Errorf("proto index %d is out of range", method.Method.ProtoIndex)) } descriptor, err := methodDescriptor(file.Protos[method.Method.ProtoIndex]) if err != nil { - return nil, methodDiagnostic(methodContext(file, class, &method), nil, "method", err) + return ClassResult{}, methodDiagnostic(methodContext(file, class, &method), nil, "method", err) } key := method.Method.Name + "\x00" + descriptor if seenMethods[key] { - return nil, methodDiagnostic(methodContext(file, class, &method), nil, "method", fmt.Errorf("duplicate method %s%s", method.Method.Name, descriptor)) + return ClassResult{}, methodDiagnostic(methodContext(file, class, &method), nil, "method", fmt.Errorf("duplicate method %s%s", method.Method.Name, descriptor)) } seenMethods[key] = true - if err := addMethod(file, class, &method, builder, options); err != nil { - return nil, err + stub, err := addMethod(file, class, &method, builder, options, policy) + if err != nil { + return ClassResult{}, err + } + if stub != nil { + stubbed = append(stubbed, *stub) } } raw, err := builder.Bytes() if err != nil { - return nil, classDiagnostic(file, class, "classfile", err) + return ClassResult{}, classDiagnostic(file, class, "classfile", err) } - return raw, nil + return ClassResult{Bytes: raw, StubbedMethods: stubbed}, nil } // LowerClass is an explicit-name alias for Class. @@ -231,6 +310,9 @@ func addFields(file *model.File, class *model.Class, builder *classfilebuilder.C if _, err := fieldKind(field.Field.Type); err != nil { return classDiagnostic(file, class, "field", fmt.Errorf("field %q: %w", field.Field.Name, err)) } + if err := classfilebuilder.ValidateFieldSymbol(field.Field.Name, field.Field.Type); err != nil { + return classDiagnostic(file, class, "field", fmt.Errorf("field %q: %w", field.Field.Name, err)) + } key := field.Field.Name + "\x00" + field.Field.Type if seen[key] { return classDiagnostic(file, class, "field", fmt.Errorf("duplicate field %s %s", field.Field.Name, field.Field.Type)) @@ -244,8 +326,8 @@ func addFields(file *model.File, class *model.Class, builder *classfilebuilder.C if isStatic != (field.AccessFlags&dexStatic != 0) { return classDiagnostic(file, class, "field", fmt.Errorf("field %q static membership and access flag disagree", field.Field.Name)) } - if class.AccessFlags&dexInterface != 0 && field.AccessFlags&(dexPublic|dexStatic|dexFinal) != dexPublic|dexStatic|dexFinal { - return classDiagnostic(file, class, "field", fmt.Errorf("Java 5 interface field must be public static final")) + if err := validateInterfaceFieldShape(class, field.AccessFlags); err != nil { + return classDiagnostic(file, class, "field", fmt.Errorf("field %q: %w", field.Field.Name, err)) } member := builder.AddField(access, field.Field.Name, field.Field.Type) if isStatic && index < len(class.StaticValues) { @@ -270,7 +352,11 @@ func addFields(file *model.File, class *model.Class, builder *classfilebuilder.C } func fieldAnnotationsOf(class *model.Class, index uint32) []model.Annotation { - for _, entry := range class.FieldAnnotations { + if position, ok := class.FieldAnnotationIndex[index]; ok && position >= 0 && position < len(class.FieldAnnotations) { + return class.FieldAnnotations[position].Annotations + } + for position := range class.FieldAnnotations { + entry := &class.FieldAnnotations[position] if entry.FieldIndex == index { return entry.Annotations } @@ -279,7 +365,11 @@ func fieldAnnotationsOf(class *model.Class, index uint32) []model.Annotation { } func methodAnnotationsOf(class *model.Class, index uint32) []model.Annotation { - for _, entry := range class.MethodAnnotations { + if position, ok := class.MethodAnnotationIndex[index]; ok && position >= 0 && position < len(class.MethodAnnotations) { + return class.MethodAnnotations[position].Annotations + } + for position := range class.MethodAnnotations { + entry := &class.MethodAnnotations[position] if entry.MethodIndex == index { return entry.Annotations } @@ -288,7 +378,11 @@ func methodAnnotationsOf(class *model.Class, index uint32) []model.Annotation { } func parameterAnnotationsOf(class *model.Class, index uint32) [][]model.Annotation { - for _, entry := range class.ParameterAnnotations { + if position, ok := class.ParameterAnnotationIndex[index]; ok && position >= 0 && position < len(class.ParameterAnnotations) { + return class.ParameterAnnotations[position].Parameters + } + for position := range class.ParameterAnnotations { + entry := &class.ParameterAnnotations[position] if entry.MethodIndex == index { return entry.Parameters } @@ -296,9 +390,9 @@ func parameterAnnotationsOf(class *model.Class, index uint32) [][]model.Annotati return nil } -// applyStaticValue turns a non-default encoded static initializer into a -// ConstantValue attribute. Wide and non-scalar constants stay rejected: the -// classfile builder has no Long/Float/Double constant pool entries yet. +// applyStaticValue turns a representable encoded static initializer into a +// ConstantValue attribute. Values that have no compatible classfile encoding +// are rejected before mutating the builder. func applyStaticValue(file *model.File, class *model.Class, field *model.EncodedField, member *classfilebuilder.Field, builder *classfilebuilder.Class, value model.EncodedValue) error { kind, err := fieldKind(field.Field.Type) if err != nil { @@ -309,6 +403,9 @@ func applyStaticValue(file *model.File, class *model.Class, field *model.Encoded case model.ValueNull: return nil case model.ValueString: + if field.Field.Type != "Ljava/lang/String;" { + return classDiagnostic(file, class, "static-value", fmt.Errorf("field %q descriptor %q cannot use a String ConstantValue", field.Field.Name, field.Field.Type)) + } index := value.Unsigned if index >= uint64(len(file.Strings)) { return classDiagnostic(file, class, "static-value", fmt.Errorf("field %q string index %d is out of range", field.Field.Name, index)) @@ -321,20 +418,23 @@ func applyStaticValue(file *model.File, class *model.Class, field *model.Encoded } switch kind { case ir.Long: - if value.Type == model.ValueLong || value.Type == model.ValueInt { - builder.SetConstantLong(member, value.Signed) - return nil + if value.Type != model.ValueLong && value.Type != model.ValueInt { + return classDiagnostic(file, class, "static-value", fmt.Errorf("field %q has incompatible long initializer kind %#x", field.Field.Name, value.Type)) } + builder.SetConstantLong(member, value.Signed) + return nil case ir.Float: - if value.Type == model.ValueFloat { - builder.SetConstantFloat(member, uint32(value.Unsigned)) - return nil + if value.Type != model.ValueFloat { + return classDiagnostic(file, class, "static-value", fmt.Errorf("field %q has incompatible float initializer kind %#x", field.Field.Name, value.Type)) } + builder.SetConstantFloat(member, uint32(value.Unsigned)) + return nil case ir.Double: - if value.Type == model.ValueDouble { - builder.SetConstantDouble(member, value.Unsigned) - return nil + if value.Type != model.ValueDouble { + return classDiagnostic(file, class, "static-value", fmt.Errorf("field %q has incompatible double initializer kind %#x", field.Field.Name, value.Type)) } + builder.SetConstantDouble(member, value.Unsigned) + return nil } switch value.Type { case model.ValueBoolean: @@ -375,63 +475,94 @@ func shrinkSigned(descriptor string, value model.EncodedValue) int32 { } } -func addMethod(file *model.File, class *model.Class, method *model.EncodedMethod, builder *classfilebuilder.Class, options ClassOptions) error { +func addMethod(file *model.File, class *model.Class, method *model.EncodedMethod, builder *classfilebuilder.Class, options ClassOptions, policy FailurePolicy) (*StubbedMethod, error) { ctx := methodContext(file, class, method) if method.Method.Class != class.Descriptor { - return methodDiagnostic(ctx, nil, "method", fmt.Errorf("method owner %q does not match class", method.Method.Class)) + return nil, methodDiagnostic(ctx, nil, "method", fmt.Errorf("method owner %q does not match class", method.Method.Class)) } if method.Method.Name == "" { - return methodDiagnostic(ctx, nil, "method", fmt.Errorf("method name is empty")) + return nil, methodDiagnostic(ctx, nil, "method", fmt.Errorf("method name is empty")) } if int(method.Method.ProtoIndex) >= len(file.Protos) { - return methodDiagnostic(ctx, nil, "method", fmt.Errorf("proto index %d is out of range", method.Method.ProtoIndex)) + return nil, methodDiagnostic(ctx, nil, "method", fmt.Errorf("proto index %d is out of range", method.Method.ProtoIndex)) } proto := file.Protos[method.Method.ProtoIndex] descriptor, err := methodDescriptor(proto) if err != nil { - return methodDiagnostic(ctx, nil, "method", err) + return nil, methodDiagnostic(ctx, nil, "method", err) + } + if err := classfilebuilder.ValidateMethodSymbol(method.Method.Name, descriptor); err != nil { + return nil, methodDiagnostic(ctx, nil, "method", err) + } + if incomingWords(proto, method.AccessFlags) > 255 { + return nil, methodDiagnostic(ctx, nil, "method", fmt.Errorf("parameter word count plus receiver exceeds 255")) } access, err := methodAccess(method.AccessFlags, method.Method.Name) if err != nil { - return methodDiagnostic(ctx, nil, "method", err) + return nil, methodDiagnostic(ctx, nil, "method", err) } declarationOnly := method.AccessFlags&(dexAbstract|dexNative) != 0 if declarationOnly && method.Code != nil { - return methodDiagnostic(ctx, nil, "method", fmt.Errorf("abstract/native method has code")) + return nil, methodDiagnostic(ctx, nil, "method", fmt.Errorf("abstract/native method has code")) } if !declarationOnly && method.Code == nil { - return methodDiagnostic(ctx, nil, "method", fmt.Errorf("concrete method has no code")) + return nil, methodDiagnostic(ctx, nil, "method", fmt.Errorf("concrete method has no code")) } if method.Method.Name == "" { if method.AccessFlags&dexStatic != 0 || proto.ReturnType != "V" { - return methodDiagnostic(ctx, nil, "method", fmt.Errorf("constructor must be non-static and return void")) + return nil, methodDiagnostic(ctx, nil, "method", fmt.Errorf("constructor must be non-static and return void")) } } else if method.AccessFlags&dexConstructor != 0 && method.Method.Name != "" { - return methodDiagnostic(ctx, nil, "method", fmt.Errorf("constructor access flag is set on a non-initializer method")) + return nil, methodDiagnostic(ctx, nil, "method", fmt.Errorf("constructor access flag is set on a non-initializer method")) } if method.Method.Name == "" { if method.AccessFlags&dexStatic == 0 || len(proto.Parameters) != 0 || proto.ReturnType != "V" { - return methodDiagnostic(ctx, nil, "method", fmt.Errorf("class initializer must be static with descriptor ()V")) + return nil, methodDiagnostic(ctx, nil, "method", fmt.Errorf("class initializer must be static with descriptor ()V")) } } - if class.AccessFlags&dexInterface != 0 && method.Method.Name != "" { - if builder.Version() >= classfilebuilder.VersionJava8 { - // Java 8 interfaces may carry public static and default methods. - if method.AccessFlags&dexPublic == 0 { - return methodDiagnostic(ctx, nil, "method", fmt.Errorf("Java 8 interface method must be public")) + if err := validateInterfaceMethodShape(class, method, builder.Version()); err != nil { + return nil, methodDiagnostic(ctx, nil, "method", err) + } + + var built *ir.Method + var stub *StubbedMethod + if !declarationOnly { + built, err = ir.Build(ir.Input{File: file, Class: class, Method: method, SkipFileValidation: options.FileValidated}) + if err != nil { + if policy != StubUnsupportedMethods || !report.IsUnsupported(err) { + return nil, err } - if method.AccessFlags&dexAbstract == 0 && method.Code == nil { - return methodDiagnostic(ctx, nil, "method", fmt.Errorf("interface method has neither code nor the abstract flag")) + var capability *report.CapabilityError + if !errors.As(err, &capability) { + return nil, err + } + stub = &StubbedMethod{ + Method: method.Method.Name, + Descriptor: descriptor, + Feature: capability.Feature, + Message: capability.Error(), + } + } else if builder.Version() >= classfilebuilder.VersionJava8 && class.AccessFlags&dexInterface != 0 { + if len(method.Code.Tries) > 0 || hasControlFlow(built.Instructions) { + message := fmt.Sprintf("method %s has control flow, which needs Java 8 stack maps", method.Method.Name) + if policy != StubUnsupportedMethods { + return nil, classDiagnostic(file, class, "interface", errors.New(message)) + } + stub = &StubbedMethod{ + Method: method.Method.Name, + Descriptor: descriptor, + Feature: "java8-interface-control-flow", + Message: message, + } } - } else if method.AccessFlags&(dexPublic|dexAbstract) != dexPublic|dexAbstract { - return methodDiagnostic(ctx, nil, "method", fmt.Errorf("Java 5 interface method must be public abstract")) } } + member := builder.AddMethod(access, method.Method.Name, descriptor) if annotations := methodAnnotationsOf(class, method.MethodIndex); len(annotations) > 0 { translated, err := translateAnnotations(file, annotations) if err != nil { - return methodDiagnostic(ctx, nil, "method annotation", err) + return nil, methodDiagnostic(ctx, nil, "method annotation", err) } if translated.signature != "" { builder.SetMethodSignature(member, translated.signature) @@ -447,31 +578,20 @@ func addMethod(file *model.File, class *model.Class, method *model.EncodedMethod } } if parameters := parameterAnnotationsOf(class, method.MethodIndex); len(parameters) > 0 { - converted := make([][]classfilebuilder.Annotation, len(parameters)) - visible := make([][]bool, len(parameters)) - for index, set := range parameters { - converted[index] = make([]classfilebuilder.Annotation, 0, len(set)) - visible[index] = make([]bool, 0, len(set)) - for _, annotation := range set { - if isSystemAnnotation(annotation) { - continue - } - value, err := builderAnnotation(file, annotation) - if err != nil { - return methodDiagnostic(ctx, nil, "parameter annotation", err) - } - converted[index] = append(converted[index], value) - visible[index] = append(visible[index], annotation.Visibility == model.AnnotationRuntime) - } + converted, visible, err := translateParameterAnnotations(file, parameters, len(proto.Parameters)) + if err != nil { + return nil, methodDiagnostic(ctx, nil, "parameter annotation", err) } builder.SetMethodParameterAnnotations(member, converted, visible) } if declarationOnly { - return nil + return nil, nil } - built, err := ir.Build(ir.Input{File: file, Class: class, Method: method, SkipFileValidation: options.FileValidated}) - if err != nil { - return err + if stub != nil { + if err := emitUnsupportedStub(builder, member, stub.Message); err != nil { + return nil, methodDiagnostic(ctx, nil, "method stub", err) + } + return stub, nil } lowerer := methodLowerer{ file: file, @@ -485,7 +605,80 @@ func addMethod(file *model.File, class *model.Class, method *model.EncodedMethod allocationByCtor: make(map[int]ir.Allocation), hierarchy: options.Hierarchy, } - return lowerer.lower() + if err := lowerer.lower(); err != nil { + return nil, err + } + return nil, nil +} + +func translateParameterAnnotations(file *model.File, parameters [][]model.Annotation, parameterCount int) ([][]classfilebuilder.Annotation, [][]bool, error) { + if len(parameters) != parameterCount { + return nil, nil, fmt.Errorf("parameter annotation count %d does not match descriptor parameter count %d", len(parameters), parameterCount) + } + converted := make([][]classfilebuilder.Annotation, len(parameters)) + visible := make([][]bool, len(parameters)) + for index, set := range parameters { + converted[index] = make([]classfilebuilder.Annotation, 0, len(set)) + visible[index] = make([]bool, 0, len(set)) + for _, annotation := range set { + if isSystemAnnotation(annotation) { + continue + } + value, err := builderAnnotation(file, annotation) + if err != nil { + return nil, nil, err + } + converted[index] = append(converted[index], value) + visible[index] = append(visible[index], annotation.Visibility == model.AnnotationRuntime) + } + } + return converted, visible, nil +} + +func hasControlFlow(instructions []ir.Instruction) bool { + for _, instruction := range instructions { + if isBranchOpcode(instruction.Opcode) || instruction.Opcode == 0x2b || instruction.Opcode == 0x2c { + return true + } + } + return false +} + +func emitUnsupportedStub(builder *classfilebuilder.Class, member *classfilebuilder.Method, reason string) error { + const exception = "java/lang/UnsupportedOperationException" + reason = sanitizeStubReason(reason) + classIndex, err := builder.Pool().Class(exception) + if err != nil { + return err + } + messageIndex, err := builder.Pool().String("javajive dex2jar stub: " + reason) + if err != nil { + return err + } + constructor, err := builder.Pool().Methodref(exception, "", "(Ljava/lang/String;)V") + if err != nil { + return err + } + member.Code().CP(classfilebuilder.NEW, classIndex). + Emit(classfilebuilder.DUP). + LDC(messageIndex). + CP(classfilebuilder.INVOKESPECIAL, constructor). + Emit(classfilebuilder.ATHROW) + return nil +} + +func sanitizeStubReason(reason string) string { + reason = strings.Map(func(r rune) rune { + if r < 0x20 || r == 0x7f { + return ' ' + } + return r + }, reason) + runes := []rune(strings.TrimSpace(reason)) + if len(runes) > 240 { + runes = runes[:240] + } + return string(runes) } func methodDescriptor(proto model.Proto) (string, error) { @@ -598,6 +791,46 @@ func fieldAccess(flags uint32) (uint16, error) { return uint16(flags), nil } +func validateInterfaceFieldShape(class *model.Class, flags uint32) error { + if class.AccessFlags&dexInterface == 0 { + return nil + } + const required = dexPublic | dexStatic | dexFinal + const allowed = required | dexSynthetic + if flags&required != required || flags&^allowed != 0 { + return fmt.Errorf("interface field must be public static final with only synthetic as an optional flag") + } + return nil +} + +func validateInterfaceMethodShape(class *model.Class, method *model.EncodedMethod, version uint16) error { + if class.AccessFlags&dexInterface == 0 { + return nil + } + if method.Method.Name == "" { + return nil + } + if method.Method.Name == "" { + return fmt.Errorf("interface must not declare an instance constructor") + } + if version < classfilebuilder.VersionJava8 { + const required = dexPublic | dexAbstract + const allowed = required | dexBridge | dexVarargs | dexSynthetic + if method.AccessFlags&required != required || method.AccessFlags&^allowed != 0 { + return fmt.Errorf("Java 5 interface method must be public abstract with only bridge, varargs, and synthetic as optional flags") + } + return nil + } + const allowed = dexPublic | dexStatic | dexAbstract | dexStrict | dexBridge | dexVarargs | dexSynthetic + if method.AccessFlags&dexPublic == 0 || method.AccessFlags&^allowed != 0 { + return fmt.Errorf("Java 8 interface method has illegal access flags") + } + if method.AccessFlags&dexAbstract == 0 && method.Code == nil { + return fmt.Errorf("interface method has neither code nor the abstract flag") + } + return nil +} + func methodAccess(flags uint32, name string) (uint16, error) { const allowed = dexPublic | dexPrivate | dexProtected | dexStatic | dexFinal | dexSynchronized | dexBridge | dexVarargs | dexNative | dexAbstract | dexStrict | dexSynthetic | dexConstructor | dexDeclaredSynchronized if flags&^allowed != 0 { diff --git a/dex2jar/lower/lower_test.go b/dex2jar/lower/lower_test.go index 68da5327..ac3d9dee 100644 --- a/dex2jar/lower/lower_test.go +++ b/dex2jar/lower/lower_test.go @@ -105,6 +105,212 @@ func TestIntArrayPathVerifiesAndExecutes(t *testing.T) { } } +func TestUnsupportedMethodStubsWithExplicitPolicy(t *testing.T) { + file := &model.File{Entry: "classes.dex", Protos: []model.Proto{{ReturnType: "V"}}} + unsupported := func(name string, access uint32, registers, incoming uint16) model.EncodedMethod { + return model.EncodedMethod{ + AccessFlags: access, + Method: model.MethodID{Class: "Ldex/Stubbed;", Name: name, ProtoIndex: 0}, + Code: &model.Code{RegistersSize: registers, InsSize: incoming, Instructions: []uint16{0x00fa, 0, 0, 0}}, + } + } + class := &model.Class{ + Descriptor: "Ldex/Stubbed;", + Superclass: "Ljava/lang/Object;", + AccessFlags: dexPublic, + DirectMethods: []model.EncodedMethod{ + unsupported("", dexPublic|dexConstructor, 1, 1), + unsupported("", dexStatic|dexConstructor, 0, 0), + unsupported("bad", dexPublic|dexStatic, 0, 0), + }, + } + result, err := ClassWithPolicy(file, class, ClassOptions{}, StubUnsupportedMethods) + if err != nil { + t.Fatalf("ClassWithPolicy: %v", err) + } + if len(result.StubbedMethods) != 3 { + t.Fatalf("stubbed methods = %#v", result.StubbedMethods) + } + parsed, err := javaclassparser.Parse(result.Bytes) + if err != nil { + t.Fatalf("parse stubbed class: %v", err) + } + if len(parsed.Methods) != 3 { + t.Fatalf("methods = %d, want 3", len(parsed.Methods)) + } + for _, method := range parsed.Methods { + if len(method.Attributes) == 0 { + t.Fatalf("stubbed method has no Code attribute: %#v", method) + } + } +} + +func TestUnsupportedInterfaceMethodStubsWithExplicitPolicy(t *testing.T) { + file := &model.File{Entry: "classes.dex", Protos: []model.Proto{{ReturnType: "V"}}} + class := &model.Class{ + Descriptor: "Ldex/StubbedInterface;", + Superclass: "Ljava/lang/Object;", + AccessFlags: dexPublic | dexInterface | dexAbstract, + DirectMethods: []model.EncodedMethod{{ + AccessFlags: dexPublic | dexStatic, + Method: model.MethodID{Class: "Ldex/StubbedInterface;", Name: "bad", ProtoIndex: 0}, + Code: &model.Code{Instructions: []uint16{0x00fa, 0, 0, 0}}, + }}, + } + result, err := ClassWithPolicy(file, class, ClassOptions{}, StubUnsupportedMethods) + if err != nil { + t.Fatalf("ClassWithPolicy: %v", err) + } + if len(result.StubbedMethods) != 1 { + t.Fatalf("stubbed methods = %#v", result.StubbedMethods) + } + parsed, err := javaclassparser.Parse(result.Bytes) + if err != nil { + t.Fatalf("parse stubbed interface: %v", err) + } + if parsed.MajorVersion != 52 { + t.Fatalf("interface major version = %d, want 52", parsed.MajorVersion) + } +} + +func TestUnsupportedStubsVerifyAndThrow(t *testing.T) { + javac, javacErr := exec.LookPath("javac") + java, javaErr := exec.LookPath("java") + if javacErr != nil || javaErr != nil { + t.Skip("javac/java unavailable") + } + tests := []struct { + name string + descriptor string + access uint32 + methodName string + registers uint16 + incoming uint16 + driver string + }{ + { + name: "constructor", + descriptor: "Ldex/StubCtor;", + access: dexPublic | dexConstructor, + methodName: "", + registers: 1, + incoming: 1, + driver: `public class Driver { + public static void main(String[] args) { + try { + new dex.StubCtor(); + throw new AssertionError("constructor returned"); + } catch (UnsupportedOperationException expected) { + } + } +}`, + }, + { + name: "static method", + descriptor: "Ldex/StubStatic;", + access: dexPublic | dexStatic, + methodName: "bad", + registers: 0, + incoming: 0, + driver: `public class Driver { + public static void main(String[] args) { + try { + dex.StubStatic.bad(); + throw new AssertionError("method returned"); + } catch (UnsupportedOperationException expected) { + } + } +}`, + }, + { + name: "class initializer", + descriptor: "Ldex/StubClinit;", + access: dexStatic, + methodName: "", + registers: 0, + incoming: 0, + driver: `public class Driver { + public static void main(String[] args) throws Exception { + try { + Class.forName("dex.StubClinit"); + throw new AssertionError("class initialized"); + } catch (ExceptionInInitializerError expected) { + } + } +}`, + }, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + file := &model.File{Entry: "classes.dex", Protos: []model.Proto{{ReturnType: "V"}}} + class := &model.Class{ + Descriptor: test.descriptor, + Superclass: "Ljava/lang/Object;", + AccessFlags: dexPublic, + DirectMethods: []model.EncodedMethod{{ + AccessFlags: test.access, + Method: model.MethodID{Class: test.descriptor, Name: test.methodName, ProtoIndex: 0}, + Code: &model.Code{RegistersSize: test.registers, InsSize: test.incoming, Instructions: []uint16{0x00fa, 0, 0, 0}}, + }}, + } + result, err := ClassWithPolicy(file, class, ClassOptions{}, StubUnsupportedMethods) + if err != nil { + t.Fatalf("ClassWithPolicy: %v", err) + } + dir := t.TempDir() + className := strings.TrimPrefix(strings.TrimSuffix(test.descriptor, ";"), "L") + path := filepath.Join(dir, filepath.FromSlash(className)+".class") + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, result.Bytes, 0o644); err != nil { + t.Fatal(err) + } + driver := filepath.Join(dir, "Driver.java") + if err := os.WriteFile(driver, []byte(test.driver), 0o644); err != nil { + t.Fatal(err) + } + if output, err := exec.Command(javac, "-cp", dir, "-d", dir, driver).CombinedOutput(); err != nil { + t.Fatalf("javac driver: %v\n%s", err, output) + } + if output, err := exec.Command(java, "-Xverify:all", "-cp", dir, "Driver").CombinedOutput(); err != nil { + t.Fatalf("stub driver execution: %v\n%s", err, output) + } + }) + } +} + +func TestJava8InterfaceControlFlowStubsWithExplicitPolicy(t *testing.T) { + file := &model.File{Entry: "classes.dex", Protos: []model.Proto{{ReturnType: "V"}}} + class := &model.Class{ + Descriptor: "Ldex/StubControlIface;", + Superclass: "Ljava/lang/Object;", + AccessFlags: dexPublic | dexInterface | dexAbstract, + DirectMethods: []model.EncodedMethod{{ + AccessFlags: dexPublic | dexStatic, + Method: model.MethodID{Class: "Ldex/StubControlIface;", Name: "bad", ProtoIndex: 0}, + Code: &model.Code{Instructions: []uint16{0x0128, 0x000e}}, + }}, + } + if _, err := ClassWithPolicy(file, class, ClassOptions{}, Strict); err == nil { + t.Fatal("strict conversion accepted Java 8 interface control flow") + } + result, err := ClassWithPolicy(file, class, ClassOptions{}, StubUnsupportedMethods) + if err != nil { + t.Fatalf("ClassWithPolicy: %v", err) + } + if len(result.StubbedMethods) != 1 || result.StubbedMethods[0].Feature != "java8-interface-control-flow" { + t.Fatalf("stubbed methods = %#v", result.StubbedMethods) + } + parsed, err := javaclassparser.Parse(result.Bytes) + if err != nil { + t.Fatalf("parse stubbed interface: %v", err) + } + if parsed.MajorVersion != 52 || len(parsed.Methods) != 1 { + t.Fatalf("interface = version %d, %d methods", parsed.MajorVersion, len(parsed.Methods)) + } +} + func TestUnsupportedMethodReturnsNoClassAndDiagnostic(t *testing.T) { file := &model.File{Entry: "classes.dex", Protos: []model.Proto{{ReturnType: "V"}}} class := &model.Class{ diff --git a/dex2jar/lower/metadata_test.go b/dex2jar/lower/metadata_test.go index 0fcdd86b..fb14aede 100644 --- a/dex2jar/lower/metadata_test.go +++ b/dex2jar/lower/metadata_test.go @@ -386,6 +386,82 @@ func classMetadataFixture() (*model.File, *model.Class) { return file, class } +func TestLowerEmitsAnnotationDefaultForReflection(t *testing.T) { + const owner = "Ldex/Defaults;" + file := &model.File{Entry: "classes.dex", Protos: []model.Proto{{ReturnType: "I"}}} + class := &model.Class{ + Descriptor: owner, + Superclass: "Ljava/lang/Object;", + AccessFlags: dexPublic | dexInterface | dexAbstract | dexAnnotation, + VirtualMethods: []model.EncodedMethod{{ + MethodIndex: 0, + AccessFlags: dexPublic | dexAbstract, + Method: model.MethodID{Class: owner, Name: "value", ProtoIndex: 0}, + }}, + MethodAnnotations: []model.MethodAnnotation{{ + MethodIndex: 0, + Annotations: []model.Annotation{{ + Visibility: model.AnnotationSystem, + Type: "Ldalvik/annotation/AnnotationDefault;", + Elements: []model.AnnotationElement{{Name: "value", Value: model.EncodedValue{Type: model.ValueInt, Signed: 7}}}, + }}, + }}, + } + raw, err := Class(file, class) + if err != nil { + t.Fatalf("Class: %v", err) + } + if _, err := javaclassparser.Parse(raw); err != nil { + t.Fatalf("parse generated annotation: %v", err) + } + javac, javacErr := exec.LookPath("javac") + java, javaErr := exec.LookPath("java") + if javacErr != nil || javaErr != nil { + t.Skip("javac/java unavailable") + } + dir := t.TempDir() + classPath := filepath.Join(dir, "dex", "Defaults.class") + if err := os.MkdirAll(filepath.Dir(classPath), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(classPath, raw, 0o644); err != nil { + t.Fatal(err) + } + driver := filepath.Join(dir, "Driver.java") + source := `public class Driver { + public static void main(String[] args) throws Exception { + Object value = dex.Defaults.class.getMethod("value").getDefaultValue(); + if (!Integer.valueOf(7).equals(value)) throw new AssertionError(String.valueOf(value)); + } +}` + if err := os.WriteFile(driver, []byte(source), 0o644); err != nil { + t.Fatal(err) + } + if output, err := exec.Command(javac, "-cp", dir, "-d", dir, driver).CombinedOutput(); err != nil { + t.Fatalf("javac driver: %v\n%s", err, output) + } + if output, err := exec.Command(java, "-Xverify:all", "-cp", dir, "Driver").CombinedOutput(); err != nil { + t.Fatalf("java reflection: %v\n%s", err, output) + } +} + +func TestLowerRejectsInvalidMetadataShapes(t *testing.T) { + t.Run("throws array descriptor", func(t *testing.T) { + file, class := metadataFixture() + file.Types = append(file.Types, model.Type{Descriptor: "[Ljava/lang/Exception;"}) + if _, err := Class(file, class); err == nil || !strings.Contains(err.Error(), "Throws type") { + t.Fatalf("Class error = %v", err) + } + }) + t.Run("parameter annotation arity", func(t *testing.T) { + file, class := classMetadataFixture() + class.ParameterAnnotations[0].Parameters = append(class.ParameterAnnotations[0].Parameters, nil) + if _, err := Class(file, class); err == nil || !strings.Contains(err.Error(), "parameter annotation count") { + t.Fatalf("Class error = %v", err) + } + }) +} + func TestLowerEmitsClassMetadataAndArrayOwnerInvoke(t *testing.T) { file, class := classMetadataFixture() raw, err := Class(file, class) diff --git a/dex2jar/lower/method.go b/dex2jar/lower/method.go index 917395a1..03a6e676 100644 --- a/dex2jar/lower/method.go +++ b/dex2jar/lower/method.go @@ -331,7 +331,7 @@ func (l *methodLowerer) emitDebug() error { } described := make(map[localRange]bool) for _, local := range debug.Locals { - if local.Name == "" || local.Type == "" || local.Start >= local.End || local.End > codeUnits { + if local.Register >= l.method.Code.RegistersSize || local.Name == "" || local.Type == "" || local.Start >= local.End || local.End > codeUnits { continue } if local.Type == "J" || local.Type == "D" || local.Type == "F" { @@ -344,37 +344,45 @@ func (l *methodLowerer) emitDebug() error { l.code.Local(start, end, local.Name, local.Type, l.home(local.Register)) described[localRange{register: local.Register, start: start, end: end}] = true } - parameterRegister := l.method.Code.RegistersSize - l.method.Code.InsSize - if l.encoded.AccessFlags&dexStatic == 0 { - parameterRegister++ - } + parameterRegisters := debugParameterRegisters(l.method.Code, l.method.Proto, l.encoded.AccessFlags) if l.endLabel == nil || startLabel == nil { return nil } for index, name := range debug.ParameterNames { - if name == "" { - return nil - } - register := int(parameterRegister) + index - if register >= int(l.method.Code.RegistersSize) { - return nil + if index >= len(parameterRegisters) { + break } - // Without a proven descriptor the parameter name is dropped rather than - // described as java.lang.Object, which would invent a type. - descriptor := l.registerDescriptor[register] - if descriptor == "" { + descriptor := l.method.Proto.Parameters[index] + register := parameterRegisters[index] + if name == "" || register >= l.method.Code.RegistersSize { continue } - key := localRange{register: uint16(register), start: startLabel, end: l.endLabel} + key := localRange{register: register, start: startLabel, end: l.endLabel} if described[key] { continue } described[key] = true - l.code.Local(startLabel, l.endLabel, name, descriptor, l.home(uint16(register))) + l.code.Local(startLabel, l.endLabel, name, descriptor, l.home(register)) } return nil } +func debugParameterRegisters(code *model.Code, proto model.Proto, accessFlags uint32) []uint16 { + if code == nil { + return nil + } + register := code.RegistersSize - code.InsSize + if accessFlags&dexStatic == 0 { + register++ + } + out := make([]uint16, len(proto.Parameters)) + for index, descriptor := range proto.Parameters { + out[index] = register + register += uint16(descriptorWords(descriptor)) + } + return out +} + func (l *methodLowerer) validateAllocationCFG(allocation ir.Allocation) error { for _, site := range allocation.Constructors { constructor := &l.method.Instructions[site] diff --git a/dex2jar/lower/performance_test.go b/dex2jar/lower/performance_test.go new file mode 100644 index 00000000..c88713cc --- /dev/null +++ b/dex2jar/lower/performance_test.go @@ -0,0 +1,107 @@ +package lower + +import ( + "testing" + + "github.com/yaklang/javajive/dex2jar/model" +) + +func TestDebugParameterRegistersUseWideSlots(t *testing.T) { + code := &model.Code{RegistersSize: 8, InsSize: 5} + proto := model.Proto{Parameters: []string{"J", "I", "D"}} + got := debugParameterRegisters(code, proto, dexStatic) + want := []uint16{3, 5, 6} + if len(got) != len(want) { + t.Fatalf("registers = %v, want %v", got, want) + } + for index := range want { + if got[index] != want[index] { + t.Fatalf("registers = %v, want %v", got, want) + } + } +} + +func TestAnnotationIndexesAndFallback(t *testing.T) { + annotation := model.Annotation{Type: "LIndexed;"} + class := &model.Class{ + FieldAnnotations: []model.FieldAnnotation{{FieldIndex: 7, Annotations: []model.Annotation{annotation}}}, + MethodAnnotations: []model.MethodAnnotation{{MethodIndex: 8, Annotations: []model.Annotation{annotation}}}, + ParameterAnnotations: []model.ParameterAnnotation{{MethodIndex: 9, Parameters: [][]model.Annotation{{annotation}}}}, + FieldAnnotationIndex: map[uint32]int{7: 0}, MethodAnnotationIndex: map[uint32]int{8: 0}, ParameterAnnotationIndex: map[uint32]int{9: 0}, + } + if got := fieldAnnotationsOf(class, 7); len(got) != 1 || got[0].Type != annotation.Type { + t.Fatalf("indexed field annotations = %#v", got) + } + if got := methodAnnotationsOf(class, 8); len(got) != 1 || got[0].Type != annotation.Type { + t.Fatalf("indexed method annotations = %#v", got) + } + if got := parameterAnnotationsOf(class, 9); len(got) != 1 || len(got[0]) != 1 || got[0][0].Type != annotation.Type { + t.Fatalf("indexed parameter annotations = %#v", got) + } + class.FieldAnnotationIndex = nil + class.MethodAnnotationIndex = nil + class.ParameterAnnotationIndex = nil + if len(fieldAnnotationsOf(class, 7)) != 1 || len(methodAnnotationsOf(class, 8)) != 1 || len(parameterAnnotationsOf(class, 9)) != 1 { + t.Fatal("annotation slice fallback failed") + } +} + +func TestReferenceStateSharingIsImmutable(t *testing.T) { + original := newReferenceState(32) + original.setOne(3, "Lone;") + original.setOne(4, "Ltwo;") + copy := copyReferenceState(original) + copy.setOne(3, "Lchanged;") + if got := original[3]; len(got) != 1 || got[0] != "Lone;" { + t.Fatalf("copy mutation changed the shared descriptor set: %v", got) + } + merged := newReferenceState(32) + mergeReferenceState(merged, original) + mergeReferenceState(merged, copy) + if got := merged[3]; len(got) != 2 { + t.Fatalf("union descriptors = %v, want two", got) + } + if !referenceStatesEqual(original, copyReferenceState(original)) { + t.Fatal("shallow copy no longer equals its source") + } +} + +func BenchmarkReferenceStateFixpointCopy(b *testing.B) { + const blocks = 512 + const registers = 128 + states := make([]referenceState, blocks) + for index := range states { + state := newReferenceState(registers) + for register := 0; register < registers; register += 8 { + state.setOne(uint16(register), "Ljava/lang/Object;") + } + states[index] = state + } + b.ReportAllocs() + for i := 0; i < b.N; i++ { + for _, state := range states { + merged := newReferenceState(registers) + mergeReferenceState(merged, state) + copied := copyReferenceState(state) + if !referenceStatesEqual(merged, copied) { + b.Fatal("merge/copy disagree") + } + } + } +} + +func BenchmarkMethodAnnotationIndexScale(b *testing.B) { + const count = 100000 + class := &model.Class{ + MethodAnnotations: make([]model.MethodAnnotation, count), + MethodAnnotationIndex: make(map[uint32]int, count), + } + for index := range class.MethodAnnotations { + class.MethodAnnotations[index] = model.MethodAnnotation{MethodIndex: uint32(index)} + class.MethodAnnotationIndex[uint32(index)] = index + } + b.ReportAllocs() + for i := 0; i < b.N; i++ { + _ = methodAnnotationsOf(class, uint32(i%count)) + } +} diff --git a/dex2jar/lower/recovery.go b/dex2jar/lower/recovery.go new file mode 100644 index 00000000..6f54b83d --- /dev/null +++ b/dex2jar/lower/recovery.go @@ -0,0 +1,434 @@ +package lower + +import ( + "encoding/json" + "fmt" + "sort" + + "github.com/yaklang/javajive/classparser/classfilebuilder" + "github.com/yaklang/javajive/dex2jar/model" +) + +const RecoveryAttributeName = "JavaJiveRecovery" + +const ( + recoveryMaxPayload = 64 << 10 + recoveryMaxRecords = 128 +) + +// RecoveryRecord is embedded in a degraded class and mirrored in the JAR +// diagnostic report. Version 1 is intentionally small and JSON-compatible. +type RecoveryRecord struct { + Version int `json:"version"` + Code string `json:"code"` + Action string `json:"action"` + Entry string `json:"entry,omitempty"` + Class string `json:"class,omitempty"` + Member string `json:"member,omitempty"` + Descriptor string `json:"descriptor,omitempty"` + Reason string `json:"reason"` +} + +// Recovery describes one degradation used to emit ClassResult.Bytes. +type Recovery struct { + Code string + Action string + Scope string + Member string + Descriptor string + Feature string + Message string +} + +func recoveryPayload(file *model.File, class *model.Class, records []Recovery) ([]byte, error) { + out := make([]RecoveryRecord, 0, len(records)) + for _, record := range records { + out = append(out, RecoveryRecord{ + Version: 1, Code: sanitizeStubReason(record.Code), Action: sanitizeStubReason(record.Action), + Entry: sanitizeStubReason(file.Entry), Class: sanitizeStubReason(class.Descriptor), Member: sanitizeStubReason(record.Member), + Descriptor: sanitizeStubReason(record.Descriptor), Reason: sanitizeStubReason(record.Message), + }) + } + sort.SliceStable(out, func(i, j int) bool { + if out[i].Member != out[j].Member { + return out[i].Member < out[j].Member + } + if out[i].Descriptor != out[j].Descriptor { + return out[i].Descriptor < out[j].Descriptor + } + return out[i].Code < out[j].Code + }) + original := len(out) + if len(out) > recoveryMaxRecords-1 { + out = out[:recoveryMaxRecords-1] + } + if len(out) != original { + out = append(out, RecoveryRecord{Version: 1, Code: "recovery.records_truncated", Action: "drop_attribute", Entry: sanitizeStubReason(file.Entry), Class: sanitizeStubReason(class.Descriptor), Reason: fmt.Sprintf("%d recovery records were omitted from the class attribute; see JAR diagnostics", original-len(out))}) + } + for { + payload, err := json.Marshal(out) + if err != nil { + return nil, err + } + if len(payload) <= recoveryMaxPayload { + return payload, nil + } + if len(out) == 1 { + return nil, fmt.Errorf("recovery attribute exceeds %d bytes", recoveryMaxPayload) + } + out = append(out[:len(out)-2], RecoveryRecord{Version: 1, Code: "recovery.records_truncated", Action: "drop_attribute", Entry: sanitizeStubReason(file.Entry), Class: sanitizeStubReason(class.Descriptor), Reason: "recovery records were omitted to fit the class attribute; see JAR diagnostics"}) + } +} + +func addRecoveryAttribute(builder *classfilebuilder.Class, file *model.File, class *model.Class, records []Recovery) error { + if len(records) == 0 { + return nil + } + payload, err := recoveryPayload(file, class, records) + if err != nil { + return err + } + builder.AddClassAttribute(RecoveryAttributeName, payload) + return nil +} + +// emitClassShell rebuilds a class with a fresh builder. It preserves the class +// identity, hierarchy, fields, declarations and representable metadata while +// replacing every concrete method body with a throwing stub. +func emitClassShell(file *model.File, class *model.Class, options ClassOptions, cause error, reducedMetadata bool) (ClassResult, error) { + className, err := objectInternalName(class.Descriptor) + if err != nil { + return ClassResult{}, classDiagnostic(file, class, "class recovery", err) + } + superName, err := recoverySuperclassName(class, true) + if err != nil { + return ClassResult{}, classDiagnostic(file, class, "class recovery", err) + } + access, err := classAccess(class.AccessFlags) + if err != nil { + return ClassResult{}, classDiagnostic(file, class, "class recovery", err) + } + builder := classfilebuilder.NewClass(className, superName, access) + if interfaceNeedsJava8(class) { + builder.SetVersion(classfilebuilder.VersionJava8) + } + if err := addShellInterfaces(class, builder); err != nil { + return ClassResult{}, classDiagnostic(file, class, "class recovery", err) + } + + root := Recovery{ + Code: "class.body_recovery", Action: "stub_class", Feature: "class-shell", + Message: fmt.Sprintf("normal class translation failed; emitted declaration-preserving shell: %v", cause), + } + recoveries := []Recovery{root} + if reducedMetadata && len(class.ParameterAnnotations) > 0 { + recoveries = append(recoveries, Recovery{Code: "metadata.parameter_annotation_dropped", Action: "drop_attribute", Feature: "parameter-annotation", Message: "reduced declaration shell omits parameter annotations"}) + } + if !reducedMetadata { + if class.SourceFile != "" { + builder.SetSourceFile(class.SourceFile) + } + if class.Signature != "" { + builder.SetClassSignature(class.Signature) + } + if class.SourceDebugExtension != "" { + builder.SetSourceDebugExtension(class.SourceDebugExtension) + } + if len(class.InnerClasses) > 0 { + specs := make([]classfilebuilder.InnerClassSpec, 0, len(class.InnerClasses)) + for _, inner := range class.InnerClasses { + specs = append(specs, classfilebuilder.InnerClassSpec{Inner: inner.Inner, Outer: inner.Outer, Name: inner.Name, Flags: inner.Flags}) + } + builder.SetInnerClasses(specs) + } + if class.Enclosing != nil { + builder.SetEnclosingMethod(classfilebuilder.EnclosingMethodSpec{Class: class.Enclosing.Class, Method: class.Enclosing.Method, Proto: class.Enclosing.Proto}) + } + if translated, translateErr := translateAnnotations(file, class.Annotations); translateErr != nil { + recoveries = append(recoveries, Recovery{Code: "metadata.class_annotation_dropped", Action: "drop_attribute", Message: translateErr.Error()}) + } else { + if translated.signature != "" { + builder.SetClassSignature(translated.signature) + } + for i, annotation := range translated.annotations { + builder.AddClassAnnotation(annotation, translated.visible[i]) + } + } + } + stubInitializer, err := addShellFields(file, class, builder, !reducedMetadata, &recoveries) + if err != nil { + return ClassResult{}, err + } + stubbed, err := addShellMethods(file, class, builder, !reducedMetadata, root.Message, stubInitializer, &recoveries) + if err != nil { + return ClassResult{}, err + } + if err := addRecoveryAttribute(builder, file, class, recoveries); err != nil { + return ClassResult{}, classDiagnostic(file, class, "class recovery", err) + } + raw, err := builder.Bytes() + if err != nil { + return ClassResult{}, classDiagnostic(file, class, "class recovery", err) + } + return ClassResult{Bytes: raw, StubbedMethods: stubbed, Recoveries: recoveries, ClassStubbed: true}, nil +} + +func emitMinimalClassShell(file *model.File, class *model.Class, cause error) (ClassResult, error) { + className, err := objectInternalName(class.Descriptor) + if err != nil { + return ClassResult{}, classDiagnostic(file, class, "minimal class recovery", err) + } + access, normalized := minimalClassAccess(class.AccessFlags) + superName, err := recoverySuperclassName(class, true) + + if err != nil { + return ClassResult{}, classDiagnostic(file, class, "minimal class recovery", err) + } + builder := classfilebuilder.NewClass(className, superName, access) + if class.AccessFlags&dexAnnotation != 0 { + builder.AddInterface("java/lang/annotation/Annotation") + } + recoveries := []Recovery{{Code: "class.minimal_recovery", Action: "stub_class_minimal", Feature: "minimal-class-shell", Message: cause.Error()}} + if normalized { + recoveries = append(recoveries, Recovery{Code: "class.access_normalized", Action: "drop_attribute", Feature: "class-access", Message: fmt.Sprintf("minimal shell normalized unsupported class access flags 0x%x", class.AccessFlags)}) + } + if len(class.ParameterAnnotations) > 0 { + recoveries = append(recoveries, Recovery{Code: "metadata.parameter_annotation_dropped", Action: "drop_attribute", Feature: "parameter-annotation", Message: "minimal class shell omits parameter annotations"}) + } + if err := addRecoveryAttribute(builder, file, class, recoveries); err != nil { + return ClassResult{}, classDiagnostic(file, class, "minimal class recovery", err) + } + raw, err := builder.Bytes() + if err != nil { + return ClassResult{}, classDiagnostic(file, class, "minimal class recovery", err) + } + return ClassResult{Bytes: raw, Recoveries: recoveries, ClassStubbed: true, ClassMinimal: true}, nil +} + +func minimalClassAccess(flags uint32) (uint16, bool) { + if access, err := classAccess(flags); err == nil { + return access, false + } + if flags&dexInterface != 0 { + access := uint16(flags & (dexPublic | dexSynthetic | dexAnnotation)) + access |= classfilebuilder.ACC_INTERFACE | classfilebuilder.ACC_ABSTRACT + if flags&dexAnnotation == 0 { + access &^= classfilebuilder.ACC_ANNOTATION + } + return access, true + } + access := uint16(flags & (dexPublic | dexSynthetic)) + access |= classfilebuilder.ACC_ABSTRACT | classfilebuilder.ACC_SUPER + return access, true +} + +func recoverySuperclassName(class *model.Class, preserveKind bool) (string, error) { + if preserveKind && class.AccessFlags&dexInterface != 0 { + return "java/lang/Object", nil + } + return superclassName(class) +} + +func addShellInterfaces(class *model.Class, builder *classfilebuilder.Class) error { + seen := make(map[string]bool, len(class.Interfaces)) + annotationInterface := false + for _, descriptor := range class.Interfaces { + name, err := objectInternalName(descriptor) + if err != nil { + return err + } + if descriptor == class.Descriptor { + return fmt.Errorf("class must not implement or extend itself") + } + if seen[descriptor] { + return fmt.Errorf("duplicate interface %s", descriptor) + } + seen[descriptor] = true + annotationInterface = annotationInterface || descriptor == "Ljava/lang/annotation/Annotation;" + builder.AddInterface(name) + } + if class.AccessFlags&dexAnnotation != 0 && !annotationInterface { + return fmt.Errorf("annotation interface must directly extend java/lang/annotation/Annotation") + } + return nil +} + +func addShellFields(file *model.File, class *model.Class, builder *classfilebuilder.Class, metadata bool, recoveries *[]Recovery) (bool, error) { + seen := make(map[string]bool) + stubInitializer := false + addFields := func(fields []model.EncodedField, isStatic bool) error { + for index := range fields { + field := &fields[index] + if field.Field.Class != class.Descriptor { + return classDiagnostic(file, class, "class recovery field", fmt.Errorf("field %q owner %q does not match class", field.Field.Name, field.Field.Class)) + } + if _, err := fieldKind(field.Field.Type); err != nil { + return classDiagnostic(file, class, "class recovery field", fmt.Errorf("field %q: %w", field.Field.Name, err)) + } + if err := classfilebuilder.ValidateFieldSymbol(field.Field.Name, field.Field.Type); err != nil { + return classDiagnostic(file, class, "class recovery field", fmt.Errorf("field %q: %w", field.Field.Name, err)) + } + key := field.Field.Name + "\x00" + field.Field.Type + if seen[key] { + return classDiagnostic(file, class, "class recovery field", fmt.Errorf("duplicate field %s %s", field.Field.Name, field.Field.Type)) + } + seen[key] = true + access, err := fieldAccess(field.AccessFlags) + if err != nil { + return classDiagnostic(file, class, "class recovery field", fmt.Errorf("field %q: %w", field.Field.Name, err)) + } + if isStatic != (field.AccessFlags&dexStatic != 0) { + return classDiagnostic(file, class, "class recovery field", fmt.Errorf("field %q static membership and access flag disagree", field.Field.Name)) + } + if err := validateInterfaceFieldShape(class, field.AccessFlags); err != nil { + return classDiagnostic(file, class, "class recovery field", fmt.Errorf("field %q: %w", field.Field.Name, err)) + } + member := builder.AddField(access, field.Field.Name, field.Field.Type) + if isStatic && index < len(class.StaticValues) { + if valueErr := applyStaticValue(file, class, field, member, builder, class.StaticValues[index]); valueErr != nil { + stubInitializer = true + *recoveries = append(*recoveries, Recovery{Code: "field.initializer_stubbed", Action: "stub_initializer", Scope: "field", Member: field.Field.Name, Descriptor: field.Field.Type, Feature: "static-initializer", Message: valueErr.Error()}) + } + } + if !metadata { + continue + } + if annotations := fieldAnnotationsOf(class, field.FieldIndex); len(annotations) > 0 { + translated, translateErr := translateAnnotations(file, annotations) + if translateErr != nil { + *recoveries = append(*recoveries, Recovery{Code: "metadata.field_annotation_dropped", Action: "drop_attribute", Scope: "field", Member: field.Field.Name, Descriptor: field.Field.Type, Message: translateErr.Error()}) + continue + } + if translated.signature != "" { + builder.SetFieldSignature(member, translated.signature) + } + for i, annotation := range translated.annotations { + builder.AddFieldAnnotation(member, annotation, translated.visible[i]) + } + } + } + return nil + } + if err := addFields(class.StaticFields, true); err != nil { + return false, err + } + if err := addFields(class.InstanceFields, false); err != nil { + return false, err + } + return stubInitializer, nil +} + +func addShellMethods(file *model.File, class *model.Class, builder *classfilebuilder.Class, metadata bool, reason string, stubInitializer bool, recoveries *[]Recovery) ([]StubbedMethod, error) { + seen := make(map[string]bool) + var stubbed []StubbedMethod + for _, method := range appendMethods(class.DirectMethods, class.VirtualMethods) { + if method.Method.Class != class.Descriptor { + return nil, methodDiagnostic(methodContext(file, class, &method), nil, "class recovery method", fmt.Errorf("method owner %q does not match class", method.Method.Class)) + } + if int(method.Method.ProtoIndex) >= len(file.Protos) { + return nil, methodDiagnostic(methodContext(file, class, &method), nil, "class recovery method", fmt.Errorf("proto index %d is out of range", method.Method.ProtoIndex)) + } + proto := file.Protos[method.Method.ProtoIndex] + descriptor, err := methodDescriptor(proto) + if err != nil { + return nil, methodDiagnostic(methodContext(file, class, &method), nil, "class recovery method", err) + } + if err := classfilebuilder.ValidateMethodSymbol(method.Method.Name, descriptor); err != nil { + return nil, methodDiagnostic(methodContext(file, class, &method), nil, "class recovery method", err) + } + if incomingWords(proto, method.AccessFlags) > 255 { + return nil, methodDiagnostic(methodContext(file, class, &method), nil, "class recovery method", fmt.Errorf("parameter word count plus receiver exceeds 255")) + } + key := method.Method.Name + "\x00" + descriptor + if seen[key] { + return nil, methodDiagnostic(methodContext(file, class, &method), nil, "class recovery method", fmt.Errorf("duplicate method %s%s", method.Method.Name, descriptor)) + } + seen[key] = true + access, err := methodAccess(method.AccessFlags, method.Method.Name) + if err != nil { + return nil, methodDiagnostic(methodContext(file, class, &method), nil, "class recovery method", err) + } + if err := validateInterfaceMethodShape(class, &method, builder.Version()); err != nil { + return nil, methodDiagnostic(methodContext(file, class, &method), nil, "class recovery method", err) + } + declarationOnly := method.AccessFlags&(dexAbstract|dexNative) != 0 + if stubInitializer && method.Method.Name == "" { + declarationOnly = false + } + member := builder.AddMethod(access, method.Method.Name, descriptor) + if metadata { + if err := addShellMethodMetadata(file, class, &method, proto, descriptor, member, builder, recoveries); err != nil { + return nil, err + } + } + if declarationOnly { + continue + } + stubReason := reason + code := "method.body_stubbed" + action := "stub_method" + feature := "class-shell" + if stubInitializer && method.Method.Name == "" { + stubReason = "javajive could not preserve one or more static field initializers" + code = "class.initializer_stubbed" + action = "stub_initializer" + feature = "static-initializer" + } + if err := emitUnsupportedStub(builder, member, stubReason); err != nil { + return nil, methodDiagnostic(methodContext(file, class, &method), nil, "class recovery stub", err) + } + stubbed = append(stubbed, StubbedMethod{Method: method.Method.Name, Descriptor: descriptor, Feature: feature, Message: stubReason}) + *recoveries = append(*recoveries, Recovery{Code: code, Action: action, Scope: "method", Member: method.Method.Name, Descriptor: descriptor, Feature: feature, Message: stubReason}) + } + if stubInitializer && !seen["\x00()V"] { + member := builder.AddMethod(classfilebuilder.ACC_STATIC, "", "()V") + message := "javajive could not preserve one or more static field initializers" + if err := emitUnsupportedStub(builder, member, message); err != nil { + return nil, classDiagnostic(file, class, "class recovery initializer", err) + } + stubbed = append(stubbed, StubbedMethod{Method: "", Descriptor: "()V", Feature: "static-initializer", Message: message}) + *recoveries = append(*recoveries, Recovery{Code: "class.initializer_stubbed", Action: "stub_initializer", Scope: "method", Member: "", Descriptor: "()V", Feature: "static-initializer", Message: message}) + } + return stubbed, nil +} + +func addShellMethodMetadata(file *model.File, class *model.Class, method *model.EncodedMethod, proto model.Proto, descriptor string, member *classfilebuilder.Method, builder *classfilebuilder.Class, recoveries *[]Recovery) error { + annotations := methodAnnotationsOf(class, method.MethodIndex) + if len(annotations) > 0 { + translated, err := translateAnnotations(file, annotations) + if err != nil { + *recoveries = append(*recoveries, Recovery{Code: "metadata.method_annotation_dropped", Action: "drop_attribute", Scope: "method", Member: method.Method.Name, Descriptor: descriptor, Message: err.Error()}) + } else { + if translated.signature != "" { + builder.SetMethodSignature(member, translated.signature) + } + if len(translated.throws) > 0 { + for _, descriptor := range translated.throws { + if err := classfilebuilder.ValidateObjectDescriptor(descriptor); err != nil { + *recoveries = append(*recoveries, Recovery{Code: "metadata.method_throws_dropped", Action: "drop_attribute", Scope: "method", Member: method.Method.Name, Descriptor: descriptor, Message: err.Error()}) + translated.throws = nil + break + } + } + if len(translated.throws) > 0 { + builder.SetMethodExceptions(member, translated.throws) + } + } + if translated.defaultVal != nil { + builder.SetMethodAnnotationDefault(member, *translated.defaultVal) + } + for i, annotation := range translated.annotations { + builder.AddMethodAnnotation(member, annotation, translated.visible[i]) + } + } + } + if parameters := parameterAnnotationsOf(class, method.MethodIndex); len(parameters) > 0 { + converted, visible, err := translateParameterAnnotations(file, parameters, len(proto.Parameters)) + if err != nil { + *recoveries = append(*recoveries, Recovery{Code: "metadata.parameter_annotation_dropped", Action: "drop_attribute", Scope: "method", Member: method.Method.Name, Descriptor: descriptor, Message: err.Error()}) + } else { + builder.SetMethodParameterAnnotations(member, converted, visible) + } + } + return nil +} diff --git a/dex2jar/lower/recovery_test.go b/dex2jar/lower/recovery_test.go new file mode 100644 index 00000000..6d03714a --- /dev/null +++ b/dex2jar/lower/recovery_test.go @@ -0,0 +1,453 @@ +package lower + +import ( + "bytes" + "encoding/json" + "fmt" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + + javaclassparser "github.com/yaklang/javajive/classparser" + "github.com/yaklang/javajive/dex2jar/model" +) + +func recoveryFixture() (*model.File, *model.Class) { + const owner = "Ldex/Recovered;" + file := &model.File{ + Entry: "classes.dex", + Protos: []model.Proto{{ReturnType: "V"}, {ReturnType: "I"}}, + } + class := &model.Class{ + Descriptor: owner, + Superclass: "Ljava/lang/Object;", + AccessFlags: dexPublic, + DirectMethods: []model.EncodedMethod{ + { + AccessFlags: dexPublic | dexConstructor, + Method: model.MethodID{Class: owner, Name: "", ProtoIndex: 0}, + Code: &model.Code{RegistersSize: 1, InsSize: 1, Instructions: []uint16{0x000e}}, + }, + { + AccessFlags: dexPublic | dexStatic, + Method: model.MethodID{Class: owner, Name: "bad", ProtoIndex: 1}, + Code: &model.Code{Instructions: []uint16{0x00ff}}, + }, + }, + } + return file, class +} + +func TestRecoveryPayloadBoundsRemainReadable(t *testing.T) { + file, class := recoveryFixture() + records := make([]Recovery, recoveryMaxRecords+10) + for index := range records { + records[index] = Recovery{Code: "method.body_stubbed", Action: "stub_method", Member: fmt.Sprintf("method%03d", index), Descriptor: "()V", Message: strings.Repeat("reason", 80)} + } + payload, err := recoveryPayload(file, class, records) + if err != nil { + t.Fatal(err) + } + if len(payload) > recoveryMaxPayload { + t.Fatalf("payload length = %d", len(payload)) + } + var decoded []RecoveryRecord + if err := json.Unmarshal(payload, &decoded); err != nil { + t.Fatal(err) + } + if len(decoded) > recoveryMaxRecords || decoded[len(decoded)-1].Code != "recovery.records_truncated" { + t.Fatalf("records = %#v", decoded) + } +} + +func TestRecoverEmitsFreshDeclarationShell(t *testing.T) { + file, class := recoveryFixture() + result, err := ClassWithPolicy(file, class, ClassOptions{}, Recover) + if err != nil { + t.Fatalf("ClassWithPolicy Recover: %v", err) + } + if !result.ClassStubbed || len(result.Recoveries) < 3 || len(result.StubbedMethods) != 2 { + t.Fatalf("result = %#v", result) + } + parsed, err := javaclassparser.Parse(result.Bytes) + if err != nil { + t.Fatalf("parse recovered class: %v", err) + } + if parsed.GetClassName() != "dex/Recovered" || len(parsed.Methods) != 2 { + t.Fatalf("class=%q methods=%d", parsed.GetClassName(), len(parsed.Methods)) + } + source, err := parsed.Dump() + if err != nil { + t.Fatalf("dump recovered class: %v", err) + } + if !strings.HasPrefix(source, "// javajive recovery:") || !strings.Contains(source, "class.body_recovery") || !strings.Contains(source, "method.body_stubbed") { + t.Fatalf("recovery source:\n%s", source) + } + if !bytes.Contains(result.Bytes, []byte(RecoveryAttributeName)) { + t.Fatal("recovered class has no JavaJiveRecovery attribute") + } +} + +func TestRecoverFailsClosedForIncompatibleWideInitializer(t *testing.T) { + const owner = "Ldex/RecoveredWideStatic;" + file := &model.File{Entry: "classes.dex"} + class := &model.Class{ + Descriptor: owner, Superclass: "Ljava/lang/Object;", AccessFlags: dexPublic, + StaticFields: []model.EncodedField{{ + AccessFlags: dexPublic | dexStatic, + Field: model.FieldID{Class: owner, Name: "VALUE", Type: "J"}, + }}, + StaticValues: []model.EncodedValue{{Type: model.ValueFloat, Unsigned: 0x3f800000}}, + } + result, err := ClassWithPolicy(file, class, ClassOptions{}, Recover) + if err != nil { + t.Fatalf("ClassWithPolicy Recover: %v", err) + } + if !result.ClassStubbed || !bytes.Contains(result.Bytes, []byte("")) { + t.Fatalf("result = %#v", result) + } + var field, initializer bool + for _, recovery := range result.Recoveries { + field = field || recovery.Action == "stub_initializer" && recovery.Scope == "field" + initializer = initializer || recovery.Action == "stub_initializer" && recovery.Member == "" + } + if !field || !initializer { + t.Fatalf("recoveries = %#v", result.Recoveries) + } +} + +func TestRecoverFailsClosedForUnsupportedStaticInitializer(t *testing.T) { + java, err := exec.LookPath("java") + if err != nil { + t.Skip("java unavailable") + } + javac, err := exec.LookPath("javac") + if err != nil { + t.Skip("javac unavailable") + } + const owner = "Ldex/RecoveredStatic;" + file := &model.File{Entry: "classes.dex", Strings: []string{"not-an-object-constant"}} + class := &model.Class{ + Descriptor: owner, Superclass: "Ljava/lang/Object;", AccessFlags: dexPublic, + StaticFields: []model.EncodedField{{ + AccessFlags: dexPublic | dexStatic, + Field: model.FieldID{Class: owner, Name: "VALUE", Type: "Ljava/lang/Object;"}, + }}, + StaticValues: []model.EncodedValue{{Type: model.ValueString, Unsigned: 0}}, + } + result, err := ClassWithPolicy(file, class, ClassOptions{}, Recover) + if err != nil { + t.Fatalf("ClassWithPolicy Recover: %v", err) + } + var initializer, field bool + for _, recovery := range result.Recoveries { + if recovery.Action == "stub_initializer" && recovery.Member == "" { + initializer = true + } + if recovery.Action == "stub_initializer" && recovery.Member == "VALUE" { + field = true + } + } + if !initializer || !field { + t.Fatalf("recoveries = %#v", result.Recoveries) + } + + dir := t.TempDir() + classPath := filepath.Join(dir, "dex", "RecoveredStatic.class") + if err := os.MkdirAll(filepath.Dir(classPath), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(classPath, result.Bytes, 0o644); err != nil { + t.Fatal(err) + } + driver := filepath.Join(dir, "Driver.java") + source := `public class Driver { + public static void main(String[] args) throws Exception { + Class.forName("dex.RecoveredStatic", false, Driver.class.getClassLoader()); + try { + Class.forName("dex.RecoveredStatic"); + throw new AssertionError("class initialized"); + } catch (ExceptionInInitializerError expected) { + } + } +}` + if err := os.WriteFile(driver, []byte(source), 0o644); err != nil { + t.Fatal(err) + } + if output, err := exec.Command(javac, "-cp", dir, driver).CombinedOutput(); err != nil { + t.Fatalf("javac: %v\n%s", err, output) + } + if output, err := exec.Command(java, "-Xverify:all", "-cp", dir, "Driver").CombinedOutput(); err != nil { + t.Fatalf("java: %v\n%s", err, output) + } +} + +func TestRecoverClassVerifiesWithoutInitialization(t *testing.T) { + java, err := exec.LookPath("java") + if err != nil { + t.Skip("java unavailable") + } + file, class := recoveryFixture() + result, err := ClassWithPolicy(file, class, ClassOptions{}, Recover) + if err != nil { + t.Fatal(err) + } + dir := t.TempDir() + path := filepath.Join(dir, "dex", "Recovered.class") + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, result.Bytes, 0o644); err != nil { + t.Fatal(err) + } + if output, err := exec.Command(java, "-Xverify:all", "-cp", dir, "dex.Recovered").CombinedOutput(); err == nil || bytes.Contains(output, []byte("VerifyError")) || bytes.Contains(output, []byte("ClassFormatError")) { + t.Fatalf("java verification result: err=%v output=%s", err, output) + } +} + +func TestRecoverPrevalidatesMethodSymbolBeforeStubCode(t *testing.T) { + for _, test := range []struct { + name string + methodName string + }{ + {name: "grammar", methodName: "bad/name"}, + {name: "UTF limit", methodName: strings.Repeat("m", 65536)}, + } { + t.Run(test.name, func(t *testing.T) { + file, class := recoveryFixture() + class.DirectMethods[1].Method.Name = test.methodName + result, err := ClassWithPolicy(file, class, ClassOptions{}, Recover) + if err != nil { + t.Fatalf("ClassWithPolicy Recover: %v", err) + } + if !result.ClassMinimal { + t.Fatalf("invalid symbol did not fall back to a minimal shell: %#v", result) + } + parsed, err := javaclassparser.Parse(result.Bytes) + if err != nil { + t.Fatalf("parse minimal class: %v", err) + } + if len(parsed.Methods) != 0 { + t.Fatalf("minimal shell methods = %d", len(parsed.Methods)) + } + }) + } +} + +func TestRecoverShellsPreserveInterfaceAndAnnotationKind(t *testing.T) { + const annotationInterface = "Ljava/lang/annotation/Annotation;" + for _, test := range []struct { + name string + descriptor string + flags uint32 + interfaces []string + }{ + {name: "interface", descriptor: "Ldex/RecoveredInterface;", flags: dexPublic | dexInterface | dexAbstract}, + {name: "annotation", descriptor: "Ldex/RecoveredAnnotation;", flags: dexPublic | dexInterface | dexAbstract | dexAnnotation, interfaces: []string{annotationInterface}}, + } { + t.Run(test.name, func(t *testing.T) { + file := &model.File{Entry: "classes.dex", Protos: []model.Proto{{ReturnType: "V"}}} + class := &model.Class{ + Descriptor: test.descriptor, Superclass: "Ldex/IllegalInterfaceSuper;", AccessFlags: test.flags, Interfaces: test.interfaces, + VirtualMethods: []model.EncodedMethod{{ + AccessFlags: dexPublic | dexAbstract, + Method: model.MethodID{Class: test.descriptor, Name: "run", ProtoIndex: 0}, + }}, + } + result, err := ClassWithPolicy(file, class, ClassOptions{}, Recover) + if err != nil { + t.Fatalf("ClassWithPolicy Recover: %v", err) + } + if result.ClassMinimal { + t.Fatalf("legal declaration shell became minimal: %#v", result) + } + assertRecoveredInterfaceShape(t, result.Bytes, test.flags) + }) + } +} + +func TestRecoverInvalidAnnotationHierarchyFallsBackToMinimalKind(t *testing.T) { + const owner = "Ldex/InvalidAnnotationHierarchy;" + file := &model.File{Entry: "classes.dex", Protos: []model.Proto{{ReturnType: "V"}}} + class := &model.Class{ + Descriptor: owner, Superclass: "Ljava/lang/Object;", + AccessFlags: dexPublic | dexInterface | dexAbstract | dexAnnotation, + DirectMethods: []model.EncodedMethod{{ + AccessFlags: dexPublic | dexStatic, + Method: model.MethodID{Class: owner, Name: "broken", ProtoIndex: 0}, + Code: &model.Code{Instructions: []uint16{0x00ff}}, + }}, + } + result, err := ClassWithPolicy(file, class, ClassOptions{}, Recover) + if err != nil { + t.Fatalf("ClassWithPolicy Recover: %v", err) + } + if !result.ClassMinimal { + t.Fatalf("result = %#v", result) + } + assertRecoveredInterfaceShape(t, result.Bytes, class.AccessFlags) +} + +func TestRecoverMinimalShellsPreserveInterfaceAndAnnotationKind(t *testing.T) { + for _, test := range []struct { + name string + descriptor string + flags uint32 + }{ + {name: "interface", descriptor: "Ldex/MinimalInterface;", flags: dexPublic | dexInterface | dexAbstract}, + {name: "interface unknown flag", descriptor: "Ldex/MinimalOddInterface;", flags: dexPublic | dexInterface | dexAbstract | 0x40000000}, + {name: "annotation", descriptor: "Ldex/MinimalAnnotation;", flags: dexPublic | dexInterface | dexAbstract | dexAnnotation}, + {name: "annotation unknown flag", descriptor: "Ldex/MinimalOddAnnotation;", flags: dexPublic | dexInterface | dexAbstract | dexAnnotation | 0x40000000}, + } { + t.Run(test.name, func(t *testing.T) { + field := model.EncodedField{ + AccessFlags: dexPublic | dexStatic | dexFinal, + Field: model.FieldID{Class: test.descriptor, Name: "VALUE", Type: "I"}, + } + file := &model.File{Entry: "classes.dex"} + class := &model.Class{ + Descriptor: test.descriptor, Superclass: "Ldex/IllegalInterfaceSuper;", AccessFlags: test.flags, + StaticFields: []model.EncodedField{field, field}, + } + result, err := ClassWithPolicy(file, class, ClassOptions{}, Recover) + if err != nil { + t.Fatalf("ClassWithPolicy Recover: %v", err) + } + if !result.ClassMinimal { + t.Fatalf("duplicate declarations did not require a minimal shell: %#v", result) + } + assertRecoveredInterfaceShape(t, result.Bytes, test.flags) + }) + } +} + +func assertRecoveredInterfaceShape(t *testing.T, raw []byte, flags uint32) { + t.Helper() + parsed, err := javaclassparser.Parse(raw) + if err != nil { + t.Fatalf("parse recovered interface: %v", err) + } + if parsed.GetSupperClassName() != "java/lang/Object" { + t.Fatalf("superclass = %q", parsed.GetSupperClassName()) + } + const kindMask = dexInterface | dexAbstract | dexAnnotation + if uint32(parsed.AccessFlags)&kindMask != flags&kindMask { + t.Fatalf("access flags = 0x%x, want kind 0x%x", parsed.AccessFlags, flags&kindMask) + } + if flags&dexAnnotation != 0 { + interfaces := parsed.GetInterfacesName() + if len(interfaces) != 1 || interfaces[0] != "java/lang/annotation/Annotation" { + t.Fatalf("annotation interfaces = %v", interfaces) + } + } +} + +func TestRecoverDeclarationShellPreservesParameterAnnotations(t *testing.T) { + file, class := classMetadataFixture() + result, err := ClassWithPolicy(file, class, ClassOptions{ForceClassShell: true, RecoveryReason: "test shell"}, Recover) + if err != nil { + t.Fatalf("ClassWithPolicy Recover: %v", err) + } + parsed, err := javaclassparser.Parse(result.Bytes) + if err != nil { + t.Fatal(err) + } + for _, method := range parsed.Methods { + if parsed.ConstantPoolManager.GetUtf8(int(method.NameIndex)).Value != "cloneIt" { + continue + } + for _, attribute := range method.Attributes { + parameter, ok := attribute.(*javaclassparser.RuntimeVisibleParameterAnnotationsAttribute) + if ok && !parameter.IsInvisible && len(parameter.ParameterAnnotations) == 1 && len(parameter.ParameterAnnotations[0]) == 1 { + return + } + } + t.Fatal("cloneIt parameter annotation was not preserved") + } + t.Fatal("cloneIt method is missing") +} + +func TestRecoverMinimalShellReportsDroppedParameterAnnotations(t *testing.T) { + file, class := classMetadataFixture() + class.DirectMethods[0].Method.Name = "bad/name" + result, err := ClassWithPolicy(file, class, ClassOptions{}, Recover) + if err != nil { + t.Fatalf("ClassWithPolicy Recover: %v", err) + } + if !result.ClassMinimal { + t.Fatalf("result = %#v", result) + } + for _, recovery := range result.Recoveries { + if recovery.Code == "metadata.parameter_annotation_dropped" { + return + } + } + t.Fatalf("recoveries = %#v", result.Recoveries) +} + +func TestRecoverDeclarationShellReportsDroppedParameterAnnotations(t *testing.T) { + file, class := classMetadataFixture() + class.ParameterAnnotations[0].Parameters = append(class.ParameterAnnotations[0].Parameters, nil) + result, err := ClassWithPolicy(file, class, ClassOptions{ForceClassShell: true, RecoveryReason: "test shell"}, Recover) + if err != nil { + t.Fatalf("ClassWithPolicy Recover: %v", err) + } + for _, recovery := range result.Recoveries { + if recovery.Code == "metadata.parameter_annotation_dropped" && recovery.Member == "cloneIt" && recovery.Descriptor == "([I)Ljava/lang/Object;" { + return + } + } + t.Fatalf("recoveries = %#v", result.Recoveries) +} + +func TestRecoverChildFirstInterfaceShellsVerifyOnJVM(t *testing.T) { + java, err := exec.LookPath("java") + if err != nil { + t.Skip("java unavailable") + } + const parent = "Ldex/ZRecoveredInterface;" + field := model.EncodedField{ + AccessFlags: dexPublic | dexStatic | dexFinal, + Field: model.FieldID{Class: parent, Name: "VALUE", Type: "I"}, + } + parentResult, err := ClassWithPolicy(&model.File{Entry: "classes.dex"}, &model.Class{ + Descriptor: parent, Superclass: "Ldex/IllegalInterfaceSuper;", AccessFlags: dexPublic | dexInterface | dexAbstract, + StaticFields: []model.EncodedField{field, field}, + }, ClassOptions{}, Recover) + if err != nil { + t.Fatal(err) + } + const child = "Ldex/ARecoveredChild;" + childFile := &model.File{Entry: "classes.dex", Protos: []model.Proto{{ReturnType: "V"}}} + childClass := &model.Class{ + Descriptor: child, Superclass: "Ljava/lang/Object;", AccessFlags: dexPublic, Interfaces: []string{parent}, + DirectMethods: []model.EncodedMethod{{ + AccessFlags: dexPublic | dexStatic, + Method: model.MethodID{Class: child, Name: "broken", ProtoIndex: 0}, + Code: &model.Code{Instructions: []uint16{0x00ff}}, + }}, + } + childResult, err := ClassWithPolicy(childFile, childClass, ClassOptions{}, Recover) + if err != nil { + t.Fatal(err) + } + dir := t.TempDir() + for name, raw := range map[string][]byte{ + "dex/ARecoveredChild.class": childResult.Bytes, + "dex/ZRecoveredInterface.class": parentResult.Bytes, + } { + path := filepath.Join(dir, filepath.FromSlash(name)) + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, raw, 0o644); err != nil { + t.Fatal(err) + } + } + output, runErr := exec.Command(java, "-Xverify:all", "-cp", dir, "dex.ARecoveredChild").CombinedOutput() + if runErr == nil || bytes.Contains(output, []byte("VerifyError")) || bytes.Contains(output, []byte("ClassFormatError")) || bytes.Contains(output, []byte("IncompatibleClassChangeError")) { + t.Fatalf("child-first interface verification: err=%v output=%s", runErr, output) + } +} diff --git a/dex2jar/lower/references.go b/dex2jar/lower/references.go index d72a70e2..95ddf9ee 100644 --- a/dex2jar/lower/references.go +++ b/dex2jar/lower/references.go @@ -2,6 +2,7 @@ package lower import ( "fmt" + "sort" "strings" "sync" @@ -11,19 +12,104 @@ import ( const nullDescriptor = "" -type referenceState []map[string]bool +// descriptorSet is an immutable sorted set. States share these slices, so a +// fixpoint copy is shallow and a merge allocates only when the union grows. +type descriptorSet []string + +// referenceState is sparse: only registers with a provable reference descriptor +// appear. The previous dense []map[string]bool allocated one map per register +// for every block and deep-copied all of them on every pass. +type referenceState map[uint16]descriptorSet + +func (s referenceState) setOne(register uint16, descriptor string) { + if descriptor == "" { + return + } + s[register] = descriptorSet{descriptor} +} + +func (s referenceState) set(register uint16, descriptors descriptorSet) { + if len(descriptors) == 0 { + delete(s, register) + return + } + s[register] = descriptors +} + +func descriptorSetsEqual(left, right descriptorSet) bool { + if len(left) != len(right) { + return false + } + for _, descriptor := range left { + found := false + for _, other := range right { + if descriptor == other { + found = true + break + } + } + if !found { + return false + } + } + return true +} + +func unionDescriptorSets(left, right descriptorSet) descriptorSet { + if len(left) == 0 { + return right + } + if len(right) == 0 { + return left + } + newCount := 0 + for _, descriptor := range right { + present := false + for _, existing := range left { + if existing == descriptor { + present = true + break + } + } + if !present { + newCount++ + } + } + if newCount == 0 { + // No new descriptor: keep sharing the original immutable set instead of + // retaining a fresh identical copy on every fixpoint pass. + return left + } + out := make(descriptorSet, len(left), len(left)+newCount) + copy(out, left) + for _, descriptor := range right { + present := false + for _, existing := range out { + if existing == descriptor { + present = true + break + } + } + if !present { + out = append(out, descriptor) + } + } + sort.Strings(out) + return out +} func (l *methodLowerer) validateReferenceUses() error { - entry := newReferenceState(int(l.method.Code.RegistersSize)) + registerCount := int(l.method.Code.RegistersSize) + entry := newReferenceState(registerCount) parameter := int(l.method.Code.RegistersSize - l.method.Code.InsSize) if l.encoded.AccessFlags&dexStatic == 0 { - entry[parameter][l.class.Descriptor] = true + entry.setOne(uint16(parameter), l.class.Descriptor) parameter++ } for _, descriptor := range l.method.Proto.Parameters { kind, _ := ir.DescriptorCategory(descriptor) - if kind == ir.Reference && parameter < len(entry) { - entry[parameter][descriptor] = true + if kind == ir.Reference && parameter < registerCount { + entry.setOne(uint16(parameter), descriptor) } // A category-2 parameter occupies two registers, so later parameters // start after both of them. @@ -32,8 +118,8 @@ func (l *methodLowerer) validateReferenceUses() error { in := make([]referenceState, len(l.method.Blocks)) out := make([]referenceState, len(l.method.Blocks)) for index := range l.method.Blocks { - in[index] = newReferenceState(len(entry)) - out[index] = newReferenceState(len(entry)) + in[index] = newReferenceState(registerCount) + out[index] = newReferenceState(registerCount) } in[0] = copyReferenceState(entry) limit := len(l.method.Blocks)*int(l.method.Code.RegistersSize+1) + 1 @@ -41,7 +127,7 @@ func (l *methodLowerer) validateReferenceUses() error { changed := false for blockIndex, block := range l.method.Blocks { if blockIndex != 0 { - merged := newReferenceState(len(entry)) + merged := newReferenceState(registerCount) if block.Handler { merged = l.handlerReferenceEntry(blockIndex, in, out) } else { @@ -136,7 +222,7 @@ func (l *methodLowerer) checkReferenceInstruction(index int, state referenceStat // registers hold that object, not whatever an earlier lifetime left // behind. for _, register := range allocation.AliasRegisters { - state[register] = map[string]bool{allocation.Descriptor: true} + state.setOne(register, allocation.Descriptor) } } check := func(register uint16, expected, role string) error { @@ -146,7 +232,7 @@ func (l *methodLowerer) checkReferenceInstruction(index int, state referenceStat if len(state[register]) == 0 { return methodDiagnostic(l.method.Context, instruction, "", fmt.Errorf("%s v%d has no provable reference descriptor", role, register)) } - for actual := range state[register] { + for _, actual := range state[register] { if !l.provablyAssignable(actual, expected) { return methodDiagnostic(l.method.Context, instruction, "", fmt.Errorf("%s v%d descriptor %q is not provably assignable to %q", role, register, actual, expected)) } @@ -219,11 +305,13 @@ func (l *methodLowerer) checkReferenceInstruction(index int, state referenceStat func (l *methodLowerer) transferReferences(index int, state referenceState) { instruction := l.method.Instructions[index] - set := func(register uint16, descriptors map[string]bool) { - state[register] = copyDescriptorSet(descriptors) + // descriptorSets are immutable, so assigning one shares it instead of + // copying every descriptor on every instruction. + set := func(register uint16, descriptors descriptorSet) { + state.set(register, descriptors) } setOne := func(register uint16, descriptor string) { - state[register] = map[string]bool{descriptor: true} + state.setOne(register, descriptor) } if allocation, ok := l.allocationByCtor[index]; ok { for _, register := range allocation.AliasRegisters { @@ -269,10 +357,10 @@ func (l *methodLowerer) transferReferences(index int, state referenceState) { case instruction.Opcode == 0x22 || instruction.Opcode == 0x23: setOne(instruction.Regs[0], l.file.Types[instruction.Index].Descriptor) case instruction.Opcode == 0x46: - components := make(map[string]bool) - for array := range state[instruction.Regs[1]] { + var components descriptorSet + for _, array := range state[instruction.Regs[1]] { if strings.HasPrefix(array, "[") { - components[array[1:]] = true + components = unionDescriptorSets(components, descriptorSet{array[1:]}) } } set(instruction.Regs[0], components) @@ -285,11 +373,11 @@ func (l *methodLowerer) transferReferences(index int, state referenceState) { } } -func (l *methodLowerer) checkArrayDescriptors(instruction *ir.Instruction, descriptors map[string]bool, component string) error { +func (l *methodLowerer) checkArrayDescriptors(instruction *ir.Instruction, descriptors descriptorSet, component string) error { if len(descriptors) == 0 { return methodDiagnostic(l.method.Context, instruction, "", fmt.Errorf("array register has no provable descriptor")) } - for descriptor := range descriptors { + for _, descriptor := range descriptors { if descriptor == nullDescriptor { continue } @@ -434,34 +522,29 @@ func (l *methodLowerer) provablyAssignable(actual, expected string) bool { } func newReferenceState(registers int) referenceState { - state := make(referenceState, registers) - for index := range state { - state[index] = make(map[string]bool) + // Only non-empty registers are stored. Cap the hint: large register files + // are usually sparse even when every register is allocated. + hint := registers / 4 + if hint > 32 { + hint = 32 } - return state -} - -func copyReferenceState(source referenceState) referenceState { - result := newReferenceState(len(source)) - for register := range source { - result[register] = copyDescriptorSet(source[register]) + if hint < 0 { + hint = 0 } - return result + return make(referenceState, hint) } -func copyDescriptorSet(source map[string]bool) map[string]bool { - result := make(map[string]bool, len(source)) - for descriptor := range source { - result[descriptor] = true +func copyReferenceState(source referenceState) referenceState { + result := make(referenceState, len(source)) + for register, descriptors := range source { + result[register] = descriptors } return result } func mergeReferenceState(destination, source referenceState) { - for register := range destination { - for descriptor := range source[register] { - destination[register][descriptor] = true - } + for register, descriptors := range source { + destination[register] = unionDescriptorSets(destination[register], descriptors) } } @@ -469,15 +552,10 @@ func referenceStatesEqual(left, right referenceState) bool { if len(left) != len(right) { return false } - for register := range left { - if len(left[register]) != len(right[register]) { + for register, descriptors := range left { + if !descriptorSetsEqual(descriptors, right[register]) { return false } - for descriptor := range left[register] { - if !right[register][descriptor] { - return false - } - } } return true } diff --git a/dex2jar/model/model.go b/dex2jar/model/model.go index 40ddcefe..a0e03c30 100644 --- a/dex2jar/model/model.go +++ b/dex2jar/model/model.go @@ -95,11 +95,17 @@ type Class struct { FieldAnnotations []FieldAnnotation MethodAnnotations []MethodAnnotation ParameterAnnotations []ParameterAnnotation - Signature string - Throws []string - InnerClasses []InnerClass - Enclosing *EnclosingMethod - SourceDebugExtension string + // Annotation indexes avoid repeated linear scans while lowering large + // classes. Parsers populate them; callers constructing models manually may + // leave them nil and lowering falls back to the slices above. + FieldAnnotationIndex map[uint32]int + MethodAnnotationIndex map[uint32]int + ParameterAnnotationIndex map[uint32]int + Signature string + Throws []string + InnerClasses []InnerClass + Enclosing *EnclosingMethod + SourceDebugExtension string } type EncodedField struct { diff --git a/dex2jar/performance_test.go b/dex2jar/performance_test.go new file mode 100644 index 00000000..eac38f11 --- /dev/null +++ b/dex2jar/performance_test.go @@ -0,0 +1,28 @@ +package dex2jar + +import "testing" + +func TestAppendConversionDiagnosticIsBounded(t *testing.T) { + detailed := DetailedReport{} + for index := 0; index < maxConversionDiagnostics*4; index++ { + appendConversionDiagnostic(&detailed, ConversionDiagnostic{Message: "diagnostic"}) + } + if got := len(detailed.Diagnostics); got != maxConversionDiagnostics { + t.Fatalf("diagnostic count = %d, want %d", got, maxConversionDiagnostics) + } + last := detailed.Diagnostics[len(detailed.Diagnostics)-1] + if last.Code != "diagnostics.truncated" { + t.Fatalf("last diagnostic = %#v", last) + } +} + +func BenchmarkAppendConversionDiagnosticBounded(b *testing.B) { + diagnostic := ConversionDiagnostic{Message: "diagnostic"} + b.ReportAllocs() + for i := 0; i < b.N; i++ { + detailed := DetailedReport{} + for index := 0; index < maxConversionDiagnostics*4; index++ { + appendConversionDiagnostic(&detailed, diagnostic) + } + } +} diff --git a/dex2jar/policy_test.go b/dex2jar/policy_test.go new file mode 100644 index 00000000..c848b484 --- /dev/null +++ b/dex2jar/policy_test.go @@ -0,0 +1,397 @@ +package dex2jar + +import ( + "archive/zip" + "bytes" + "fmt" + "path/filepath" + "reflect" + "strings" + "testing" + + javaclassparser "github.com/yaklang/javajive/classparser" + "github.com/yaklang/javajive/dex2jar/model" +) + +func policyFixture() *model.Application { + file := &model.File{ + Entry: "classes.dex", + Protos: []model.Proto{{ReturnType: "V"}}, + Classes: []model.Class{{ + Descriptor: "Lexample/Policy;", + Superclass: "Ljava/lang/Object;", + AccessFlags: 0x0001, + DirectMethods: []model.EncodedMethod{ + { + AccessFlags: 0x0009, + Method: model.MethodID{Class: "Lexample/Policy;", Name: "ok", ProtoIndex: 0}, + Code: &model.Code{Instructions: []uint16{0x000e}}, + }, + { + AccessFlags: 0x0009, + Method: model.MethodID{Class: "Lexample/Policy;", Name: "unsupported", ProtoIndex: 0}, + Code: &model.Code{Instructions: []uint16{0x00fa, 0, 0, 0}}, + }, + }, + }}, + } + return &model.Application{Files: []*model.File{file}} +} + +func TestApplicationStrictRejectsUnsupportedMethod(t *testing.T) { + jar, detailed, err := applicationToJarWithPolicy(policyFixture(), FailureStrict) + if err == nil { + t.Fatal("strict conversion accepted an unsupported method") + } + if jar != nil { + t.Fatalf("strict conversion returned %d JAR bytes", len(jar)) + } + if detailed.Status != "failed" { + t.Fatalf("status = %q, want failed", detailed.Status) + } +} + +func TestContainerPredicatesAndMagicBranches(t *testing.T) { + for _, kind := range []ContainerKind{ContainerAPK, ContainerAPKS, ContainerXAPK, ContainerAPKM, ContainerAAB} { + if !IsAndroidContainer(kind) { + t.Fatalf("%s is not classified as Android", kind) + } + } + if IsAndroidContainer(ContainerJAR) { + t.Fatal("JAR was classified as Android") + } + for _, kind := range []ContainerKind{ContainerJMOD, ContainerJImage, ContainerJAR, ContainerWAR, ContainerEAR, ContainerAAR, ContainerPAR, ContainerZIP} { + if !IsJavaArchiveContainer(kind) { + t.Fatalf("%s is not classified as a Java archive", kind) + } + } + if IsJavaArchiveContainer(ContainerAPK) { + t.Fatal("APK was classified as a Java archive") + } + + tests := []struct { + name string + data []byte + want InputKind + }{ + {"dex", []byte("dex\n035\x00"), InputDEX}, + {"class", []byte{0xca, 0xfe, 0xba, 0xbe}, InputClass}, + {"zip", []byte("PK\x03\x04"), InputZIP}, + {"jmod", []byte{'J', 'M', 1, 0}, InputJMOD}, + {"jimage", []byte{0xda, 0xda, 0xfe, 0xca}, InputJIMAGE}, + {"unknown", []byte("not an artifact"), InputUnknown}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + if got := DetectInputKind(test.data); got != test.want { + t.Fatalf("DetectInputKind = %v, want %v", got, test.want) + } + }) + } +} + +func TestConversionPolicyRejectsUnknownPolicyAndMissingFile(t *testing.T) { + jar, detailed, err := DexToJarWithOptions([]byte("not an artifact"), ConvertOptions{Policy: FailurePolicy("unknown")}) + if err == nil || !strings.Contains(err.Error(), "unknown failure policy") || jar != nil || detailed.Status != "failed" { + t.Fatalf("unknown policy: jar=%d report=%#v err=%v", len(jar), detailed, err) + } + report, err := DexFileToJarWithOptions(filepath.Join(t.TempDir(), "missing.dex"), filepath.Join(t.TempDir(), "out.jar"), ConvertOptions{}) + if err == nil || report.Status != "failed" { + t.Fatalf("missing file: report=%#v err=%v", report, err) + } +} + +func TestBestEffortRejectsUnsupportedDEXVersion(t *testing.T) { + data := make([]byte, 0x70) + copy(data, []byte("dex\n040\x00")) + jar, detailed, err := DexToJarWithOptions(data, ConvertOptions{Policy: FailureStubUnsupportedMethods}) + if err == nil || !strings.Contains(err.Error(), `unsupported DEX version "040"`) { + t.Fatalf("DexToJarWithOptions error = %v", err) + } + if jar != nil || detailed.Status != "failed" { + t.Fatalf("jar=%d report=%#v", len(jar), detailed) + } +} + +func TestApplicationBestEffortDoesNotStubMalformedMethod(t *testing.T) { + app := policyFixture() + app.Files[0].Classes[0].DirectMethods[1].Code.Instructions = []uint16{0x00ff} + jar, detailed, err := applicationToJarWithPolicy(app, FailureStubUnsupportedMethods) + if err == nil { + t.Fatal("best-effort conversion accepted malformed bytecode") + } + if jar != nil { + t.Fatalf("best-effort conversion returned %d JAR bytes after malformed input", len(jar)) + } + if detailed.Status != "failed" || len(detailed.Diagnostics) != 1 || detailed.Diagnostics[0].Category != "invalid" { + t.Fatalf("detailed report = %#v", detailed) + } +} + +func TestApplicationRecoverEmitsClassShellAndDiagnostics(t *testing.T) { + app := policyFixture() + app.Files[0].Classes[0].DirectMethods[1].Code.Instructions = []uint16{0x00ff} + jar, detailed, err := applicationToJarWithPolicy(app, FailureRecover) + if err != nil { + t.Fatalf("recover conversion: %v", err) + } + if detailed.Status != "partial" || detailed.StubbedClasses != 1 || detailed.StubbedMethods != 2 || detailed.Summary.Warnings == 0 { + t.Fatalf("detailed = %#v", detailed) + } + reader, err := zip.NewReader(bytes.NewReader(jar), int64(len(jar))) + if err != nil { + t.Fatal(err) + } + entries := make(map[string][]byte) + for _, file := range reader.File { + stream, openErr := file.Open() + if openErr != nil { + t.Fatal(openErr) + } + var body bytes.Buffer + _, copyErr := body.ReadFrom(stream) + stream.Close() + if copyErr != nil { + t.Fatal(copyErr) + } + entries[file.Name] = body.Bytes() + } + if len(entries["example/Policy.class"]) == 0 || len(entries["META-INF/javajive/diagnostics.json"]) == 0 { + t.Fatalf("entries = %#v", entries) + } + if !bytes.Contains(entries["example/Policy.class"], []byte("JavaJiveRecovery")) || !bytes.Contains(entries["META-INF/javajive/diagnostics.json"], []byte("class.body_recovery")) { + t.Fatal("recovery evidence is missing from class or JAR diagnostics") + } + second, secondReport, err := applicationToJarWithPolicy(app, FailureRecover) + if err != nil || !bytes.Equal(second, jar) || !reflect.DeepEqual(secondReport, detailed) { + t.Fatalf("recover output is nondeterministic: err=%v reports=%#v/%#v", err, detailed, secondReport) + } +} + +func TestApplicationRecoverKeepsGoodClassesAroundBadClass(t *testing.T) { + app := policyFixture() + bad := app.Files[0].Classes[0] + bad.Descriptor = "Lexample/Bad;" + for index := range bad.DirectMethods { + bad.DirectMethods[index].Method.Class = bad.Descriptor + } + bad.DirectMethods[1].Code.Instructions = []uint16{0x00ff} + goodClass := func(descriptor string) model.Class { + return model.Class{ + Descriptor: descriptor, Superclass: "Ljava/lang/Object;", AccessFlags: 0x0001, + DirectMethods: []model.EncodedMethod{{ + AccessFlags: 0x0009, + Method: model.MethodID{Class: descriptor, Name: "ok", ProtoIndex: 0}, + Code: &model.Code{Instructions: []uint16{0x000e}}, + }}, + } + } + app.Files[0].Classes = []model.Class{goodClass("Lexample/Before;"), bad, goodClass("Lexample/After;")} + + if jar, _, err := applicationToJarWithPolicy(app, FailureStrict); err == nil || jar != nil { + t.Fatalf("strict conversion: jar=%d err=%v", len(jar), err) + } + if jar, _, err := applicationToJarWithPolicy(app, FailureStubUnsupportedMethods); err == nil || jar != nil { + t.Fatalf("method-only conversion: jar=%d err=%v", len(jar), err) + } + + jar, detailed, err := applicationToJarWithPolicy(app, FailureRecover) + if err != nil { + t.Fatalf("recover conversion: %v", err) + } + if detailed.Status != "partial" || detailed.AttemptedClasses != 3 || detailed.StubbedClasses != 1 { + t.Fatalf("detailed = %#v", detailed) + } + reader, err := zip.NewReader(bytes.NewReader(jar), int64(len(jar))) + if err != nil { + t.Fatal(err) + } + entries := make(map[string][]byte) + for _, entry := range reader.File { + stream, openErr := entry.Open() + if openErr != nil { + t.Fatal(openErr) + } + var body bytes.Buffer + _, copyErr := body.ReadFrom(stream) + closeErr := stream.Close() + if copyErr != nil { + t.Fatal(copyErr) + } + if closeErr != nil { + t.Fatal(closeErr) + } + entries[entry.Name] = body.Bytes() + } + for _, name := range []string{"example/Before.class", "example/Bad.class", "example/After.class"} { + body := entries[name] + if len(body) == 0 { + t.Fatalf("missing %s; entries=%v", name, entries) + } + parsed, parseErr := javaclassparser.Parse(body) + if parseErr != nil { + t.Fatalf("parse %s: %v", name, parseErr) + } + if name == "example/Bad.class" { + source, dumpErr := parsed.Dump() + if dumpErr != nil { + t.Fatalf("dump %s: %v", name, dumpErr) + } + if !strings.HasPrefix(source, "// javajive recovery:") { + t.Fatalf("bad class recovery comments are missing:\n%s", source) + } + } + } + if !bytes.Contains(entries["META-INF/javajive/diagnostics.json"], []byte("Lexample/Bad;")) { + t.Fatal("diagnostics do not identify the recovered class") + } +} + +func TestApplicationRecoverPropagatesMinimalDependency(t *testing.T) { + const parentDescriptor = "Lexample/MinimalParent;" + const childDescriptor = "Lexample/DependentChild;" + duplicate := model.EncodedField{ + AccessFlags: 0x0001, + Field: model.FieldID{Class: parentDescriptor, Name: "value", Type: "I"}, + } + file := &model.File{ + Entry: "classes.dex", + Protos: []model.Proto{{ReturnType: "V"}}, + Classes: []model.Class{ + { + Descriptor: childDescriptor, Superclass: parentDescriptor, AccessFlags: 0x0001, + DirectMethods: []model.EncodedMethod{{ + AccessFlags: 0x0009, + Method: model.MethodID{Class: childDescriptor, Name: "ok", ProtoIndex: 0}, + Code: &model.Code{Instructions: []uint16{0x000e}}, + }}, + }, + { + Descriptor: parentDescriptor, Superclass: "Ljava/lang/Object;", AccessFlags: 0x0001, + InstanceFields: []model.EncodedField{duplicate, duplicate}, + }, + }, + } + jar, detailed, err := applicationToJarWithPolicy(&model.Application{Files: []*model.File{file}}, FailureRecover) + if err != nil { + t.Fatalf("recover conversion: %v", err) + } + if len(jar) == 0 || detailed.StubbedClasses != 2 { + t.Fatalf("jar=%d detailed=%#v", len(jar), detailed) + } + var parentMinimal, childDependency bool + for _, diagnostic := range detailed.Diagnostics { + if diagnostic.Class == parentDescriptor && diagnostic.Code == "class.minimal_recovery" { + parentMinimal = true + } + if diagnostic.Class == childDescriptor && diagnostic.Code == "class.body_recovery" && strings.Contains(diagnostic.Message, parentDescriptor) { + childDependency = true + } + } + if !parentMinimal || !childDependency { + t.Fatalf("diagnostics = %#v", detailed.Diagnostics) + } +} + +func TestApplicationRecoverDoesNotCountMinimalShellMethodsAsTranslated(t *testing.T) { + app := policyFixture() + class := &app.Files[0].Classes[0] + class.DirectMethods[1].Method.Name = "bad/name" + jar, detailed, err := applicationToJarWithPolicy(app, FailureRecover) + if err != nil { + t.Fatalf("recover conversion: %v", err) + } + if len(jar) == 0 || detailed.StubbedClasses != 1 || detailed.Summary.Methods != 2 || detailed.Summary.TranslatedMethods != 0 { + t.Fatalf("jar=%d detailed=%#v", len(jar), detailed) + } + for _, diagnostic := range detailed.Diagnostics { + if diagnostic.Code == "class.minimal_recovery" { + return + } + } + t.Fatalf("minimal recovery diagnostic missing: %#v", detailed.Diagnostics) +} + +func TestConversionDiagnosticsAreBoundedAndExplicitlyTruncated(t *testing.T) { + input := make([]ConversionDiagnostic, maxConversionDiagnostics+100) + for index := range input { + input[index] = ConversionDiagnostic{ + Entry: strings.Repeat("entry\n", 100), Class: "Lexample/Many;", Method: fmt.Sprintf("m%d", index), + Category: "recovery", Action: "stubbed", Message: strings.Repeat("message", 100), + } + } + payload, diagnostics, err := encodeConversionDiagnostics(Report{Warnings: len(input)}, input) + if err != nil { + t.Fatal(err) + } + if len(payload) > maxDiagnosticsPayload || len(diagnostics) > maxConversionDiagnostics { + t.Fatalf("payload=%d diagnostics=%d", len(payload), len(diagnostics)) + } + last := diagnostics[len(diagnostics)-1] + if last.Code != "diagnostics.truncated" || !bytes.Contains(payload, []byte("diagnostics.truncated")) { + t.Fatalf("last=%#v payload=%s", last, payload) + } + if strings.Contains(diagnostics[0].Entry, "\n") || len([]rune(diagnostics[0].Message)) > maxDiagnosticFieldRunes { + t.Fatalf("diagnostic was not sanitized: %#v", diagnostics[0]) + } + second, secondDiagnostics, err := encodeConversionDiagnostics(Report{Warnings: len(input)}, input) + if err != nil || !bytes.Equal(payload, second) || !reflect.DeepEqual(diagnostics, secondDiagnostics) { + t.Fatalf("bounded diagnostics are nondeterministic: %v", err) + } +} + +func TestApplicationBestEffortStubsAndReports(t *testing.T) { + jar, detailed, err := applicationToJarWithPolicy(policyFixture(), FailureStubUnsupportedMethods) + if err != nil { + t.Fatalf("best-effort conversion: %v", err) + } + if detailed.Status != "partial" { + t.Fatalf("status = %q, want partial", detailed.Status) + } + if detailed.Summary.Classes != 1 || detailed.Summary.Methods != 2 || + detailed.Summary.TranslatedMethods != 1 || detailed.Summary.Warnings != 1 { + t.Fatalf("summary = %#v", detailed.Summary) + } + if len(detailed.Diagnostics) != 1 { + t.Fatalf("diagnostics = %#v", detailed.Diagnostics) + } + diagnostic := detailed.Diagnostics[0] + if diagnostic.Method != "unsupported()V" || diagnostic.Category != "unsupported" || + diagnostic.Action != "stubbed" || diagnostic.Feature == "" { + t.Fatalf("diagnostic = %#v", diagnostic) + } + reader, err := zip.NewReader(bytes.NewReader(jar), int64(len(jar))) + if err != nil { + t.Fatalf("open JAR: %v", err) + } + var classEntry *zip.File + var diagnostics bool + for _, entry := range reader.File { + switch entry.Name { + case "example/Policy.class": + classEntry = entry + case "META-INF/javajive/diagnostics.json": + diagnostics = true + } + } + if len(reader.File) != 3 || classEntry == nil || !diagnostics { + t.Fatalf("JAR entries = %#v", reader.File) + } + stream, err := classEntry.Open() + if err != nil { + t.Fatal(err) + } + var class bytes.Buffer + if _, err := class.ReadFrom(stream); err != nil { + stream.Close() + t.Fatal(err) + } + stream.Close() + body := class.Bytes() + if !bytes.Contains(body, []byte("UnsupportedOperationException")) { + t.Fatal("stubbed class does not reference UnsupportedOperationException") + } + if !strings.Contains(diagnostic.Message, "unsupported") { + t.Fatalf("diagnostic message = %q", diagnostic.Message) + } +} diff --git a/dex2jar/report/report.go b/dex2jar/report/report.go index cc30ec71..9d26aefa 100644 --- a/dex2jar/report/report.go +++ b/dex2jar/report/report.go @@ -7,6 +7,244 @@ import ( "strings" ) +// FailureKind classifies why DEX processing failed. Values are stable and may +// be persisted by callers. +type FailureKind string + +const ( + FailureKindInvalidInput FailureKind = "invalid_input" + FailureKindUnsupported FailureKind = "unsupported" + FailureKindResourceLimit FailureKind = "resource_limit" + FailureKindCanceled FailureKind = "canceled" + FailureKindInternal FailureKind = "internal" + + KindInvalidInput = FailureKindInvalidInput + KindUnsupported = FailureKindUnsupported + KindResourceLimit = FailureKindResourceLimit + KindCanceled = FailureKindCanceled + KindInternal = FailureKindInternal +) + +// FailureScope identifies the smallest unit affected by a failure. +type FailureScope string + +const ( + FailureScopeRequest FailureScope = "request" + FailureScopeInput FailureScope = "input" + FailureScopeContainer FailureScope = "container" + FailureScopeEntry FailureScope = "entry" + FailureScopeClass FailureScope = "class" + FailureScopeMember FailureScope = "member" + FailureScopeInstruction FailureScope = "instruction" + + ScopeRequest = FailureScopeRequest + ScopeInput = FailureScopeInput + ScopeContainer = FailureScopeContainer + ScopeEntry = FailureScopeEntry + ScopeClass = FailureScopeClass + ScopeMember = FailureScopeMember + ScopeInstruction = FailureScopeInstruction +) + +// FailureStage identifies the processing stage at which a failure occurred. +type FailureStage string + +const ( + FailureStageIdentify FailureStage = "identify" + FailureStageRead FailureStage = "read" + FailureStageParse FailureStage = "parse" + FailureStageValidate FailureStage = "validate" + FailureStageAnalyze FailureStage = "analyze" + FailureStageTranslate FailureStage = "translate" + FailureStageLower FailureStage = "lower" + FailureStageEmit FailureStage = "emit" + FailureStageWrite FailureStage = "write" + + StageIdentify = FailureStageIdentify + StageRead = FailureStageRead + StageParse = FailureStageParse + StageValidate = FailureStageValidate + StageAnalyze = FailureStageAnalyze + StageTranslate = FailureStageTranslate + StageLower = FailureStageLower + StageEmit = FailureStageEmit + StageWrite = FailureStageWrite +) + +// RecoveryAction describes the bounded response permitted for a failure. +type RecoveryAction string + +const ( + RecoveryActionNone RecoveryAction = "none" + RecoveryActionAbort RecoveryAction = "abort" + RecoveryActionRetry RecoveryAction = "retry" + RecoveryActionSkipEntry RecoveryAction = "skip_entry" + RecoveryActionSkipClass RecoveryAction = "skip_class" + RecoveryActionStubMethod RecoveryAction = "stub_method" + RecoveryActionStubClass RecoveryAction = "stub_class" + RecoveryActionStubClassMinimal RecoveryAction = "stub_class_minimal" + RecoveryActionDropAttribute RecoveryAction = "drop_attribute" + + RecoveryNone = RecoveryActionNone + RecoveryAbort = RecoveryActionAbort + RecoveryRetry = RecoveryActionRetry + RecoverySkipEntry = RecoveryActionSkipEntry + RecoverySkipClass = RecoveryActionSkipClass + RecoveryStubMethod = RecoveryActionStubMethod + RecoveryStubMember = RecoveryActionStubMethod + RecoveryStubClass = RecoveryActionStubClass + RecoveryStubClassMinimal = RecoveryActionStubClassMinimal + RecoveryDropAttribute = RecoveryActionDropAttribute +) + +// Severity describes the operational impact of a failure. +type Severity string + +const ( + SeverityInfo Severity = "info" + SeverityWarning Severity = "warning" + SeverityError Severity = "error" + SeverityFatal Severity = "fatal" +) + +// Failure is the stable, typed failure envelope used by DEX production and +// reporting. Counter remains a string so this package does not depend on an +// internal resource-budget package. +type Failure struct { + Code string + Kind FailureKind + Scope FailureScope + Stage FailureStage + Action RecoveryAction + Severity Severity + Entry string + Class string + Member string + Descriptor string + Offset int64 + Op string + Feature string + Counter string + Used int64 + Limit int64 + Err error +} + +func (f *Failure) Error() string { + if f == nil { + return "dex failure: " + } + var b strings.Builder + b.WriteString("dex failure") + writeFailureString(&b, "code", f.Code) + writeFailureString(&b, "kind", string(f.Kind)) + writeFailureString(&b, "scope", string(f.Scope)) + writeFailureString(&b, "stage", string(f.Stage)) + writeFailureString(&b, "action", string(f.Action)) + writeFailureString(&b, "severity", string(f.Severity)) + writeFailureString(&b, "entry", f.Entry) + writeFailureString(&b, "class", f.Class) + writeFailureString(&b, "member", f.Member) + writeFailureString(&b, "descriptor", f.Descriptor) + if f.Offset >= 0 { + fmt.Fprintf(&b, " offset=0x%x", f.Offset) + } + writeFailureString(&b, "op", f.Op) + writeFailureString(&b, "feature", f.Feature) + writeFailureString(&b, "counter", f.Counter) + if f.Counter != "" || f.Used != 0 || f.Limit != 0 { + fmt.Fprintf(&b, " used=%d limit=%d", f.Used, f.Limit) + } + if f.Err != nil { + fmt.Fprintf(&b, ": %v", f.Err) + } + return b.String() +} + +func writeFailureString(b *strings.Builder, name, value string) { + if value != "" { + fmt.Fprintf(b, " %s=%q", name, value) + } +} + +func (f *Failure) Unwrap() error { + if f == nil { + return nil + } + return f.Err +} + +// NewFailure wraps err in a typed failure. Nil errors remain nil and an error +// that already contains a Failure is returned unchanged. +func NewFailure(code string, kind FailureKind, scope FailureScope, stage FailureStage, err error) error { + if err == nil { + return nil + } + if _, ok := AsFailure(err); ok { + return err + } + return &Failure{ + Code: code, + Kind: kind, + Scope: scope, + Stage: stage, + Offset: -1, + Err: err, + } +} + +// AsFailure returns the first typed failure in err. When a legacy Diagnostic +// supplies source context outside the Failure, missing context is copied into +// the returned value without mutating either error. +func AsFailure(err error) (*Failure, bool) { + var failure *Failure + if !errors.As(err, &failure) || failure == nil { + return nil, false + } + var diagnostic *Diagnostic + if !errors.As(err, &diagnostic) || diagnostic == nil { + return failure, true + } + copy := *failure + changed := false + if copy.Entry == "" && diagnostic.Entry != "" { + copy.Entry = diagnostic.Entry + changed = true + } + if copy.Class == "" && diagnostic.Class != "" { + copy.Class = diagnostic.Class + changed = true + } + if copy.Member == "" && diagnostic.Method != "" { + copy.Member = diagnostic.Method + changed = true + } + if copy.Offset < 0 && diagnostic.Offset >= 0 { + copy.Offset = diagnostic.Offset + changed = true + } + if copy.Op == "" && diagnostic.Op != "" { + copy.Op = diagnostic.Op + changed = true + } + if !changed { + return failure, true + } + return ©, true +} + +// IsKind reports whether err contains a Failure of kind. +func IsKind(err error, kind FailureKind) bool { + failure, ok := AsFailure(err) + return ok && failure.Kind == kind +} + +// IsScope reports whether err contains a Failure of scope. +func IsScope(err error, scope FailureScope) bool { + failure, ok := AsFailure(err) + return ok && failure.Scope == scope +} + // Diagnostic identifies a failure within an archive entry and DEX entity. type Diagnostic struct { Entry string @@ -67,3 +305,68 @@ func AsDiagnostic(err error) (*Diagnostic, bool) { ok := errors.As(err, &diagnostic) return diagnostic, ok } + +// CapabilityError identifies a recognized DEX construct whose structure is +// valid but whose semantics are not implemented by the translator. Only errors +// of this type are eligible for explicit best-effort method stubbing. +type CapabilityError struct { + Feature string + Err error +} + +// As exposes the corresponding typed failure while retaining CapabilityError's +// existing concrete type, fields, rendering, and unwrap chain. +func (e *CapabilityError) As(target any) bool { + failure, ok := target.(**Failure) + if !ok || failure == nil || e == nil { + return false + } + *failure = &Failure{ + Code: "dex.unsupported_capability", + Kind: FailureKindUnsupported, + Scope: FailureScopeMember, + Stage: FailureStageTranslate, + Action: RecoveryStubMethod, + Severity: SeverityError, + Offset: -1, + Feature: e.Feature, + Err: e, + } + return true +} + +func (e *CapabilityError) Error() string { + if e == nil { + return "unsupported DEX capability" + } + if e.Err == nil { + return fmt.Sprintf("unsupported DEX capability: %s", e.Feature) + } + return e.Err.Error() +} + +func (e *CapabilityError) Unwrap() error { + if e == nil { + return nil + } + return e.Err +} + +// Unsupported marks a validated, method-local capability boundary. +func Unsupported(feature string, err error) error { + if err == nil { + return nil + } + var existing *CapabilityError + if errors.As(err, &existing) { + return err + } + return &CapabilityError{Feature: feature, Err: err} +} + +// IsUnsupported reports whether err is an explicit capability boundary rather +// than malformed input, a resource failure, or an internal error. +func IsUnsupported(err error) bool { + var unsupported *CapabilityError + return errors.As(err, &unsupported) +} diff --git a/dex2jar/report/report_test.go b/dex2jar/report/report_test.go index c349b02d..15fecdb7 100644 --- a/dex2jar/report/report_test.go +++ b/dex2jar/report/report_test.go @@ -29,6 +29,242 @@ func TestDiagnosticStableCategoriesAndRendering(t *testing.T) { } } +func TestFailureEnumValues(t *testing.T) { + tests := []struct { + name string + got fmt.Stringer + want string + }{ + {"kind invalid input", stringValue(FailureKindInvalidInput), "invalid_input"}, + {"kind unsupported", stringValue(FailureKindUnsupported), "unsupported"}, + {"kind resource limit", stringValue(FailureKindResourceLimit), "resource_limit"}, + {"kind canceled", stringValue(FailureKindCanceled), "canceled"}, + {"kind internal", stringValue(FailureKindInternal), "internal"}, + {"scope request", stringValue(FailureScopeRequest), "request"}, + {"scope input", stringValue(FailureScopeInput), "input"}, + {"scope container", stringValue(FailureScopeContainer), "container"}, + {"scope entry", stringValue(FailureScopeEntry), "entry"}, + {"scope class", stringValue(FailureScopeClass), "class"}, + {"scope member", stringValue(FailureScopeMember), "member"}, + {"scope instruction", stringValue(FailureScopeInstruction), "instruction"}, + {"stage identify", stringValue(FailureStageIdentify), "identify"}, + {"stage read", stringValue(FailureStageRead), "read"}, + {"stage parse", stringValue(FailureStageParse), "parse"}, + {"stage validate", stringValue(FailureStageValidate), "validate"}, + {"stage analyze", stringValue(FailureStageAnalyze), "analyze"}, + {"stage translate", stringValue(FailureStageTranslate), "translate"}, + {"stage lower", stringValue(FailureStageLower), "lower"}, + {"stage emit", stringValue(FailureStageEmit), "emit"}, + {"stage write", stringValue(FailureStageWrite), "write"}, + {"recovery none", stringValue(RecoveryActionNone), "none"}, + {"recovery abort", stringValue(RecoveryActionAbort), "abort"}, + {"recovery retry", stringValue(RecoveryActionRetry), "retry"}, + {"recovery skip entry", stringValue(RecoveryActionSkipEntry), "skip_entry"}, + {"recovery skip class", stringValue(RecoveryActionSkipClass), "skip_class"}, + {"recovery stub method", stringValue(RecoveryActionStubMethod), "stub_method"}, + {"recovery stub class", stringValue(RecoveryActionStubClass), "stub_class"}, + {"recovery stub class minimal", stringValue(RecoveryActionStubClassMinimal), "stub_class_minimal"}, + {"recovery drop attribute", stringValue(RecoveryActionDropAttribute), "drop_attribute"}, + {"severity info", stringValue(SeverityInfo), "info"}, + {"severity warning", stringValue(SeverityWarning), "warning"}, + {"severity error", stringValue(SeverityError), "error"}, + {"severity fatal", stringValue(SeverityFatal), "fatal"}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + if got := test.got.String(); got != test.want { + t.Fatalf("value = %q, want %q", got, test.want) + } + }) + } +} + +type stringValue string + +func (s stringValue) String() string { return string(s) } + +func TestFailureStableRenderingAndUnwrap(t *testing.T) { + cause := errors.New("bad operand") + failure := &Failure{ + Code: "dex.ir.bad_operand", + Kind: FailureKindInvalidInput, + Scope: FailureScopeInstruction, + Stage: FailureStageAnalyze, + Action: RecoveryAbort, + Severity: SeverityError, + Entry: "base/classes.dex", + Class: "Lpkg/C;", + Member: "run", + Descriptor: "(I)V", + Offset: 42, + Op: "invoke-static(0x71)", + Feature: "quoted \"feature\"", + Counter: "analysis_updates", + Used: 101, + Limit: 100, + Err: cause, + } + want := `dex failure code="dex.ir.bad_operand" kind="invalid_input" scope="instruction" stage="analyze" action="abort" severity="error" entry="base/classes.dex" class="Lpkg/C;" member="run" descriptor="(I)V" offset=0x2a op="invoke-static(0x71)" feature="quoted \"feature\"" counter="analysis_updates" used=101 limit=100: bad operand` + if got := failure.Error(); got != want { + t.Fatalf("Error() = %q, want %q", got, want) + } + if got := failure.Error(); got != want { + t.Fatalf("second Error() = %q, want deterministic %q", got, want) + } + if failure.Unwrap() != cause || !errors.Is(failure, cause) { + t.Fatalf("failure lost cause: %#v", failure.Unwrap()) + } + + if got := (&Failure{Offset: -1}).Error(); got != "dex failure" { + t.Fatalf("empty failure = %q", got) + } + if got := (&Failure{Offset: 0, Used: 1}).Error(); got != "dex failure offset=0x0 used=1 limit=0" { + t.Fatalf("sparse failure = %q", got) + } + var nilFailure *Failure + if nilFailure.Error() != "dex failure: " || nilFailure.Unwrap() != nil { + t.Fatalf("nil Failure = %q / %v", nilFailure.Error(), nilFailure.Unwrap()) + } +} + +func TestFailureConstructionClassificationAndWrapping(t *testing.T) { + cause := errors.New("root cause") + if got := NewFailure("code", FailureKindInvalidInput, FailureScopeEntry, FailureStageParse, nil); got != nil { + t.Fatalf("NewFailure(..., nil) = %v", got) + } + + err := NewFailure("dex.parse.truncated", FailureKindInvalidInput, FailureScopeEntry, FailureStageParse, cause) + failure, ok := AsFailure(err) + if !ok { + t.Fatalf("AsFailure(%v) failed", err) + } + if failure.Code != "dex.parse.truncated" || failure.Kind != FailureKindInvalidInput || failure.Scope != FailureScopeEntry || failure.Stage != FailureStageParse || failure.Offset != -1 { + t.Fatalf("failure = %#v", failure) + } + if !errors.Is(err, cause) || !IsKind(err, FailureKindInvalidInput) || !IsScope(err, FailureScopeEntry) { + t.Fatalf("classification lost through direct error: %v", err) + } + if IsKind(err, FailureKindInternal) || IsScope(err, FailureScopeMember) { + t.Fatalf("failure matched the wrong classification: %#v", failure) + } + + wrapped := fmt.Errorf("outer: %w", err) + got, ok := AsFailure(wrapped) + if !ok || got != failure || !IsKind(wrapped, FailureKindInvalidInput) || !IsScope(wrapped, FailureScopeEntry) { + t.Fatalf("classification through wrapper = %#v, %v", got, ok) + } + if again := NewFailure("other", FailureKindInternal, FailureScopeRequest, FailureStageEmit, wrapped); again != wrapped { + t.Fatalf("NewFailure double-wrapped an existing failure: %v", again) + } + + if got, ok := AsFailure(cause); ok || got != nil { + t.Fatalf("AsFailure(non-failure) = %#v, %v", got, ok) + } + if got, ok := AsFailure(nil); ok || got != nil || IsKind(nil, FailureKindInvalidInput) || IsScope(nil, FailureScopeEntry) { + t.Fatalf("nil classification = %#v, %v", got, ok) + } + var nilFailure *Failure + var typedNil error = nilFailure + if got, ok := AsFailure(typedNil); ok || got != nil || IsKind(typedNil, FailureKindInvalidInput) || IsScope(typedNil, FailureScopeEntry) { + t.Fatalf("typed nil classification = %#v, %v", got, ok) + } +} + +func TestDiagnosticProjectsSourceContextIntoFailure(t *testing.T) { + cause := errors.New("bad instruction") + original := &Failure{ + Code: "dex.ir.unsupported_opcode", + Kind: FailureKindUnsupported, + Scope: FailureScopeMember, + Stage: FailureStageTranslate, + Action: RecoveryStubMethod, + Severity: SeverityError, + Offset: -1, + Feature: "odex opcode", + Err: cause, + } + err := New("classes2.dex", "Lpkg/C;", "run", 42, "invoke-virtual-quick(0xf8)", original) + + diagnostic, ok := AsDiagnostic(err) + if !ok || diagnostic.Entry != "classes2.dex" || diagnostic.Class != "Lpkg/C;" || diagnostic.Method != "run" || diagnostic.Offset != 42 || diagnostic.Op != "invoke-virtual-quick(0xf8)" { + t.Fatalf("diagnostic context = %#v, %v", diagnostic, ok) + } + failure, ok := AsFailure(err) + if !ok { + t.Fatalf("AsFailure(%v) failed", err) + } + if failure == original || failure.Entry != diagnostic.Entry || failure.Class != diagnostic.Class || failure.Member != diagnostic.Method || failure.Offset != diagnostic.Offset || failure.Op != diagnostic.Op { + t.Fatalf("projected failure = %#v", failure) + } + if original.Entry != "" || original.Class != "" || original.Member != "" || original.Offset != -1 || original.Op != "" { + t.Fatalf("AsFailure mutated wrapped failure: %#v", original) + } + if !errors.Is(err, cause) || !IsKind(err, FailureKindUnsupported) || !IsScope(err, FailureScopeMember) { + t.Fatalf("diagnostic lost typed classification: %v", err) + } + + explicit := &Failure{Kind: FailureKindInternal, Scope: FailureScopeClass, Entry: "explicit.dex", Member: "explicit", Offset: 7, Err: cause} + projected, ok := AsFailure(New("diagnostic.dex", "Ldiag;", "diag", 9, "diag-op", explicit)) + if !ok || projected.Entry != "explicit.dex" || projected.Class != "Ldiag;" || projected.Member != "explicit" || projected.Offset != 7 || projected.Op != "diag-op" { + t.Fatalf("partial context projection = %#v, %v", projected, ok) + } + complete := &Failure{Kind: FailureKindInternal, Scope: FailureScopeClass, Entry: "explicit.dex", Class: "Lexplicit;", Member: "explicit", Offset: 7, Op: "explicit-op", Err: cause} + unchanged, ok := AsFailure(New("diagnostic.dex", "Ldiag;", "diag", 9, "diag-op", complete)) + if !ok || unchanged != complete { + t.Fatalf("complete context projection = %#v, %v", unchanged, ok) + } +} + +func TestCapabilityErrorContract(t *testing.T) { + var nilCapability *CapabilityError + if nilCapability.Error() != "unsupported DEX capability" || nilCapability.Unwrap() != nil { + t.Fatalf("nil CapabilityError = %q / %v", nilCapability.Error(), nilCapability.Unwrap()) + } + if Unsupported("feature", nil) != nil { + t.Fatal("Unsupported(feature, nil) did not return nil") + } + + cause := errors.New("root cause") + err := Unsupported("feature", cause) + if !IsUnsupported(err) || err.Error() != "root cause" { + t.Fatalf("Unsupported error = %v", err) + } + var capability *CapabilityError + if !errors.As(err, &capability) || capability.Feature != "feature" || capability.Unwrap() != cause { + t.Fatalf("capability = %#v", capability) + } + failure, ok := AsFailure(err) + if !ok || failure.Code != "dex.unsupported_capability" || failure.Kind != FailureKindUnsupported || failure.Scope != FailureScopeMember || failure.Stage != FailureStageTranslate || failure.Action != RecoveryStubMethod || failure.Severity != SeverityError || failure.Offset != -1 || failure.Feature != "feature" || failure.Unwrap() != capability { + t.Fatalf("capability failure = %#v, %v", failure, ok) + } + if !IsKind(err, FailureKindUnsupported) || !IsScope(err, FailureScopeMember) { + t.Fatalf("capability was not classified: %#v", failure) + } + if again := Unsupported("other", err); again != err { + t.Fatalf("Unsupported rewrapped an existing capability: %v", again) + } + wrapped := fmt.Errorf("outer: %w", err) + if !IsUnsupported(wrapped) || !IsKind(wrapped, FailureKindUnsupported) || !IsScope(wrapped, FailureScopeMember) { + t.Fatal("wrapped capability lost compatibility or typed classification") + } + if again := NewFailure("other", FailureKindInternal, FailureScopeRequest, FailureStageEmit, wrapped); again != wrapped { + t.Fatalf("NewFailure rewrapped a legacy capability: %v", again) + } + if IsUnsupported(cause) { + t.Fatal("plain error was classified as unsupported") + } + if got := (&CapabilityError{Feature: "feature"}).Error(); got != "unsupported DEX capability: feature" { + t.Fatalf("feature-only error = %q", got) + } + if got := (&CapabilityError{}).Error(); got != "unsupported DEX capability: " { + t.Fatalf("empty capability error = %q", got) + } + var typedNil error = nilCapability + if failure, ok := AsFailure(typedNil); ok || failure != nil || IsKind(typedNil, FailureKindUnsupported) || IsScope(typedNil, FailureScopeMember) { + t.Fatalf("typed nil capability classification = %#v, %v", failure, ok) + } +} + func TestDiagnosticWrappingContract(t *testing.T) { cause := errors.New("root cause") if got := New("entry", "class", "method", 1, "opcode", nil); got != nil { diff --git a/inspect/analyze.go b/inspect/analyze.go index c71168fb..2ca8e6b7 100644 --- a/inspect/analyze.go +++ b/inspect/analyze.go @@ -12,9 +12,7 @@ import ( "io" "os" "path/filepath" - "regexp" "sort" - "strconv" "strings" "github.com/yaklang/javajive/dex2jar/input" @@ -22,6 +20,8 @@ import ( "github.com/yaklang/javajive/dex2jar/lower" "github.com/yaklang/javajive/dex2jar/model" dexreport "github.com/yaklang/javajive/dex2jar/report" + "github.com/yaklang/javajive/internal/inputkind" + "github.com/yaklang/javajive/jimage" ) const schemaVersion = 1 @@ -165,8 +165,6 @@ type Diagnostic struct { Message string `json:"message"` } -var canonicalDEXEntry = regexp.MustCompile(`^classes([0-9]*)\.dex$`) - // AnalyzeFile reads and inspects path. Read failures return a failed report and // the underlying error; recognized but unsupported content is represented only // in the report. @@ -203,8 +201,19 @@ func AnalyzeWithOptions(data []byte, name string, options Options) Report { }, options)) report.Status = report.DEXFiles[0].Status report.Diagnostics = append(report.Diagnostics, report.DEXFiles[0].Diagnostics...) + case "jmod": + report.Artifact.Format = "jmod" + if len(data) <= inputkind.JMODHeaderSize { + report.Status = StatusFailed + report.Diagnostics = append(report.Diagnostics, Diagnostic{Source: "jmod", Offset: 0, Op: "header", Message: "truncated JMOD header"}) + break + } + analyzeArchive(&report, data[inputkind.JMODHeaderSize:], name, inputkind.JMOD, options) + case "jimage": + report.Artifact.Format = "jimage" + analyzeJImage(&report, data) case "zip": - analyzeArchive(&report, data, name, options) + analyzeArchive(&report, data, name, inputkind.Unknown, options) case "class": report.Artifact.Format = "class" report.Status = StatusUnsupported @@ -234,6 +243,10 @@ func detectMagic(data []byte) string { switch { case len(data) >= 8 && bytes.Equal(data[:4], []byte("dex\n")) && data[7] == 0: return "dex" + case inputkind.IsJMODHeader(data): + return "jmod" + case inputkind.IsJImageHeader(data): + return "jimage" case len(data) >= 4 && (bytes.Equal(data[:4], []byte{'P', 'K', 3, 4}) || bytes.Equal(data[:4], []byte{'P', 'K', 5, 6}) || bytes.Equal(data[:4], []byte{'P', 'K', 7, 8})): return "zip" case len(data) >= 4 && bytes.Equal(data[:4], []byte{0xca, 0xfe, 0xba, 0xbe}): @@ -243,89 +256,78 @@ func detectMagic(data []byte) string { } } -type retainedDEX struct { - name string - index int - data []byte -} - -func analyzeArchive(report *Report, data []byte, name string, options Options) { +func analyzeArchive(report *Report, data []byte, name string, forced inputkind.Kind, options Options) { reader, err := zip.NewReader(bytes.NewReader(data), int64(len(data))) if err != nil { report.Artifact.Format = archiveHint(name) + if forced != inputkind.Unknown { + report.Artifact.Format = string(forced) + } report.Status = StatusFailed report.Diagnostics = append(report.Diagnostics, Diagnostic{Source: "archive", Offset: -1, Op: "zip", Message: err.Error()}) return } + kind := forced + if kind == inputkind.Unknown { + kind = inputkind.DetectBytes(data, name) + } + report.Artifact.Format = string(kind) + archive := &Archive{Entries: []ArchiveEntry{}, Resources: []ArchiveEntry{}} report.Archive = archive - retained := make([]retainedDEX, 0) - hasManifest, hasClass, hasWAR := false, false, false - seenDEXIndex := make(map[int]string) for position, file := range reader.File { - if file.Name == "META-INF/MANIFEST.MF" { - hasManifest = true - } - if strings.HasSuffix(strings.ToLower(file.Name), ".class") { - hasClass = true - } - if file.Name == "WEB-INF/web.xml" || strings.HasPrefix(file.Name, "WEB-INF/classes/") || strings.HasPrefix(file.Name, "WEB-INF/lib/") { - hasWAR = true - } - - entry, contents, readErr := inspectArchiveEntry(file, position) + entry, _, readErr := inspectArchiveEntry(file, position) archive.Entries = append(archive.Entries, entry) - index, canonical := multidexIndex(file.Name) - if !entry.Directory && !strings.HasSuffix(strings.ToLower(file.Name), ".class") && !canonical { + if !entry.Directory && !strings.HasSuffix(strings.ToLower(file.Name), ".class") && !isDEXEntry(file.Name) { archive.Resources = append(archive.Resources, entry) } if readErr != nil { report.Status = StatusPartial report.Diagnostics = append(report.Diagnostics, Diagnostic{Source: "archive", Entry: file.Name, Offset: -1, Op: "read entry", Message: readErr.Error()}) - continue - } - if canonical { - if previous, exists := seenDEXIndex[index]; exists { - report.Status = StatusPartial - report.Diagnostics = append(report.Diagnostics, Diagnostic{Source: "archive", Entry: file.Name, Offset: -1, Op: "multidex provenance", Message: fmt.Sprintf("duplicate canonical multidex index %d also used by %q", index, previous)}) - } else { - seenDEXIndex[index] = file.Name - } - retained = append(retained, retainedDEX{name: file.Name, index: index, data: contents}) } } - sortArchiveEntries(archive.Entries) sortArchiveEntries(archive.Resources) - sort.SliceStable(retained, func(i, j int) bool { - if retained[i].index != retained[j].index { - return retained[i].index < retained[j].index - } - return retained[i].name < retained[j].name - }) - switch { - case len(retained) > 0: - report.Artifact.Format = "apk" - case hasWAR: - report.Artifact.Format = "war" - case hasManifest || hasClass: - report.Artifact.Format = "jar" - default: - report.Artifact.Format = archiveHint(name) - if report.Artifact.Format == "zip" { + if !inputkind.IsAndroid(kind) { + if kind == inputkind.ZIP { report.Status = StatusUnsupported - report.Diagnostics = append(report.Diagnostics, Diagnostic{Source: "inspect", Offset: 0, Op: "archive type", Message: "ZIP is not identifiable as JAR, WAR, or APK"}) + report.Diagnostics = append(report.Diagnostics, Diagnostic{Source: "inspect", Offset: 0, Op: "archive type", Message: "ZIP is not identifiable as a Java archive or Android container"}) } + return } - if report.Artifact.Format != "apk" { + sources, _, err := input.CollectDEXSources(data, name, input.Options{}) + if err != nil { + report.Status = StatusPartial + report.Diagnostics = append(report.Diagnostics, diagnosticFromError("container", err)) return } - hierarchy := dexHierarchy(retained) - for _, item := range retained { - dex := analyzeDEX(item.data, hierarchy, DEXProvenance{Container: "apk", Entry: item.name, MultidexIndex: item.index, Canonical: true}, options) + // Parse each DEX once. The previous hierarchy pass parsed every file and the + // analysis pass parsed them again; hierarchy and per-class verdicts can share + // the same immutable model.File. + hierarchy := make(map[string]*model.Class) + parsedSources := make([]parsedDEXSource, len(sources)) + for index, source := range sources { + parsed, parseErr := input.ParseDEX(source.Data, source.Entry) + parsedSources[index] = parsedDEXSource{source: source, file: parsed, err: parseErr} + if parseErr != nil { + continue + } + for position := range parsed.Classes { + class := &parsed.Classes[position] + if _, exists := hierarchy[class.Descriptor]; !exists { + hierarchy[class.Descriptor] = class + } + } + } + for _, item := range parsedSources { + source := item.source + dex := analyzeParsedDEX(source.Data, item.file, item.err, hierarchy, DEXProvenance{ + Container: string(kind), Entry: source.Entry, + MultidexIndex: source.MultidexIndex, Canonical: source.Canonical, + }, options) report.DEXFiles = append(report.DEXFiles, dex) report.Diagnostics = append(report.Diagnostics, dex.Diagnostics...) if dex.Status != StatusComplete && report.Status == StatusComplete { @@ -334,12 +336,92 @@ func analyzeArchive(report *Report, data []byte, name string, options Options) { } } +func analyzeJImage(report *Report, data []byte) { + reader, err := jimage.OpenBytes(data) + if err != nil { + report.Status = StatusFailed + report.Diagnostics = append(report.Diagnostics, Diagnostic{Source: "jimage", Offset: 0, Op: "header", Message: err.Error()}) + return + } + defer reader.Close() + + archive := &Archive{Entries: []ArchiveEntry{}, Resources: []ArchiveEntry{}} + report.Archive = archive + const diagnosticLimit = 64 + failures := 0 + for position, entry := range reader.Entries() { + kind := "resource" + if entry.Directory { + kind = "directory" + } else if entry.Extension == "class" { + kind = "class" + } + compression := uint16(0) + if entry.CompressedSize != 0 { + compression = 8 + } + item := ArchiveEntry{ + Name: entry.Name(), Kind: kind, Size: entry.UncompressedSize, + CompressedSize: entry.CompressedSize, Compression: compression, + Directory: entry.Directory, ArchivePosition: position, + } + if !entry.Directory { + content, readErr := reader.Read(entry.Path) + if readErr != nil { + report.Status = StatusPartial + failures++ + if failures <= diagnosticLimit { + report.Diagnostics = append(report.Diagnostics, Diagnostic{Source: "jimage", Entry: entry.Name(), Offset: -1, Op: "read", Message: readErr.Error()}) + } + } else { + sum := sha256.Sum256(content) + item.SHA256 = hex.EncodeToString(sum[:]) + } + } + archive.Entries = append(archive.Entries, item) + if kind != "class" && kind != "directory" { + archive.Resources = append(archive.Resources, item) + } + } + if failures > diagnosticLimit { + report.Diagnostics = append(report.Diagnostics, Diagnostic{Source: "jimage", Offset: -1, Op: "read", Message: fmt.Sprintf("%d additional JImage resources could not be read", failures-diagnosticLimit)}) + } + sortArchiveEntries(archive.Entries) + sortArchiveEntries(archive.Resources) +} + +func isDEXEntry(name string) bool { + if _, ok := inputkind.RootDEXIndex(name); ok { + return true + } + _, _, ok := inputkind.AABDEX(name) + return ok +} + func archiveHint(name string) string { switch strings.ToLower(filepath.Ext(name)) { case ".apk": return "apk" + case ".apks": + return "apks" + case ".xapk", ".apkx": + return "xapk" + case ".apkm": + return "apkm" + case ".aab": + return "aab" case ".war": return "war" + case ".ear": + return "ear" + case ".aar": + return "aar" + case ".par": + return "par" + case ".jmod": + return "jmod" + case ".jimage": + return "jimage" case ".jar": return "jar" default: @@ -377,12 +459,21 @@ func archiveEntryKind(name string, directory bool) string { if directory { return "directory" } - if _, ok := multidexIndex(name); ok { + lower := strings.ToLower(name) + if isDEXEntry(name) { return "dex" } - if strings.HasSuffix(strings.ToLower(name), ".class") { + if strings.HasSuffix(lower, ".class") { return "class" } + if strings.HasSuffix(lower, ".apk") { + return "apk" + } + if strings.HasSuffix(lower, ".jar") || strings.HasSuffix(lower, ".aar") || + strings.HasSuffix(lower, ".war") || strings.HasSuffix(lower, ".ear") || + strings.HasSuffix(lower, ".par") || strings.HasSuffix(lower, ".jmod") { + return "archive" + } return "resource" } @@ -395,34 +486,26 @@ func sortArchiveEntries(entries []ArchiveEntry) { }) } -func multidexIndex(name string) (int, bool) { - match := canonicalDEXEntry.FindStringSubmatch(name) - if match == nil { - return 0, false - } - if match[1] == "" { - return 1, true - } - if match[1][0] == '0' { - return 0, false - } - index, err := strconv.Atoi(match[1]) - if err != nil || index < 2 { - return 0, false - } - return index, true +type parsedDEXSource struct { + source input.DEXSource + file *model.File + err error } func analyzeDEX(data []byte, hierarchy map[string]*model.Class, provenance DEXProvenance, options Options) DEXFile { + parsed, err := input.ParseDEX(data, provenance.Entry) + return analyzeParsedDEX(data, parsed, err, hierarchy, provenance, options) +} + +func analyzeParsedDEX(data []byte, parsed *model.File, parseErr error, hierarchy map[string]*model.Class, provenance DEXProvenance, options Options) DEXFile { sum := sha256.Sum256(data) dex := DEXFile{ Status: StatusComplete, Provenance: provenance, Version: dexVersion(data), Size: uint64(len(data)), SHA256: hex.EncodeToString(sum[:]), Classes: []Class{}, Diagnostics: []Diagnostic{}, } - parsed, err := input.ParseDEX(data, provenance.Entry) - if err != nil { + if parseErr != nil { dex.Status = StatusPartial - dex.Diagnostics = append(dex.Diagnostics, diagnosticFromError("strict-parser", err)) + dex.Diagnostics = append(dex.Diagnostics, diagnosticFromError("strict-parser", parseErr)) return dex } classes := append([]model.Class(nil), parsed.Classes...) @@ -638,23 +721,3 @@ func diagnosticFromError(source string, err error) Diagnostic { } return diagnostic } - -// dexHierarchy indexes the classes of every DEX entry in an application so a -// class can prove assignability to a supertype declared in another multidex -// file. -func dexHierarchy(entries []retainedDEX) map[string]*model.Class { - index := make(map[string]*model.Class) - for _, item := range entries { - parsed, err := input.ParseDEX(item.data, item.name) - if err != nil { - continue - } - for position := range parsed.Classes { - class := &parsed.Classes[position] - if _, exists := index[class.Descriptor]; !exists { - index[class.Descriptor] = class - } - } - } - return index -} diff --git a/inspect/container_test.go b/inspect/container_test.go new file mode 100644 index 00000000..89534916 --- /dev/null +++ b/inspect/container_test.go @@ -0,0 +1,243 @@ +package inspect_test + +import ( + "archive/zip" + "bytes" + "io/fs" + "os" + "strings" + "testing" + + artifactinspect "github.com/yaklang/javajive/inspect" + "github.com/yaklang/javajive/internal/jimagefixture" +) + +func containerZIP(t *testing.T, files map[string][]byte) []byte { + t.Helper() + var buffer bytes.Buffer + writer := zip.NewWriter(&buffer) + for name, body := range files { + file, err := writer.Create(name) + if err != nil { + t.Fatalf("create %s: %v", name, err) + } + if _, err := file.Write(body); err != nil { + t.Fatalf("write %s: %v", name, err) + } + } + if err := writer.Close(); err != nil { + t.Fatalf("close zip: %v", err) + } + return buffer.Bytes() +} + +func containerClassFixture(t *testing.T) []byte { + t.Helper() + raw, err := os.ReadFile("../classparser/jarwar/testdata/plexus-cipher-2.0.jar") + if err != nil { + t.Fatalf("read class fixture jar: %v", err) + } + reader, err := zip.NewReader(bytes.NewReader(raw), int64(len(raw))) + if err != nil { + t.Fatalf("open class fixture jar: %v", err) + } + for _, file := range reader.File { + if strings.HasSuffix(file.Name, ".class") { + body, err := fs.ReadFile(reader, file.Name) + if err != nil { + t.Fatalf("read class fixture: %v", err) + } + return body + } + } + t.Fatal("class fixture jar has no .class entry") + return nil +} + +func TestAnalyzeAPKS(t *testing.T) { + apk, err := os.ReadFile("../dex2jar/testdata/accept/multidex.apk") + if err != nil { + t.Fatal(err) + } + resourceSplit := containerZIP(t, map[string][]byte{"res/raw/config.txt": []byte("config")}) + bundle := containerZIP(t, map[string][]byte{ + "base.apk": apk, + "split.apk": resourceSplit, + }) + report := artifactinspect.Analyze(bundle, "app.apks") + if report.Status != artifactinspect.StatusComplete || report.Artifact.Format != "apks" { + t.Fatalf("report = %#v", report) + } + if len(report.DEXFiles) != 2 { + t.Fatalf("DEX files = %d, want 2", len(report.DEXFiles)) + } + wantEntries := []string{"base.apk!/classes.dex", "base.apk!/classes2.dex"} + for index, dex := range report.DEXFiles { + if dex.Provenance.Container != "apks" || dex.Provenance.Entry != wantEntries[index] || + dex.Provenance.MultidexIndex != index+1 || !dex.Provenance.Canonical { + t.Fatalf("DEX[%d] provenance = %#v", index, dex.Provenance) + } + } + for _, entry := range report.Archive.Entries { + if entry.Name == "base.apk" && entry.Kind != "apk" { + t.Fatalf("base.apk kind = %q, want apk", entry.Kind) + } + } +} + +func TestAnalyzeXAPK(t *testing.T) { + apk, err := os.ReadFile("../dex2jar/testdata/accept/multidex.apk") + if err != nil { + t.Fatal(err) + } + bundle := containerZIP(t, map[string][]byte{ + "manifest.json": []byte(`{"xapk_version":2}`), + "base.apk": apk, + }) + report := artifactinspect.Analyze(bundle, "app.xapk") + if report.Status != artifactinspect.StatusComplete || report.Artifact.Format != "xapk" { + t.Fatalf("report = %#v", report) + } + if len(report.DEXFiles) != 2 || report.DEXFiles[0].Provenance.Container != "xapk" { + t.Fatalf("DEX provenance = %#v", report.DEXFiles) + } +} + +func TestAnalyzeAAB(t *testing.T) { + dex, err := os.ReadFile("../dex2jar/testdata/accept/arithmetic.dex") + if err != nil { + t.Fatal(err) + } + bundle := containerZIP(t, map[string][]byte{ + "BundleConfig.pb": {1}, + "base/dex/classes.dex": dex, + }) + report := artifactinspect.Analyze(bundle, "app.aab") + if report.Status != artifactinspect.StatusComplete || report.Artifact.Format != "aab" { + t.Fatalf("report = %#v", report) + } + if len(report.DEXFiles) != 1 { + t.Fatalf("DEX files = %d, want 1", len(report.DEXFiles)) + } + provenance := report.DEXFiles[0].Provenance + if provenance.Container != "aab" || provenance.Entry != "base/dex/classes.dex" || + provenance.MultidexIndex != 1 || !provenance.Canonical { + t.Fatalf("provenance = %#v", provenance) + } +} + +func TestAnalyzeJMOD(t *testing.T) { + classBytes := containerClassFixture(t) + payload := containerZIP(t, map[string][]byte{ + "classes/demo/Hello.class": classBytes, + "conf/example.properties": []byte("key=value\n"), + }) + jmod := append([]byte{'J', 'M', 1, 0}, payload...) + report := artifactinspect.Analyze(jmod, "java.base.jmod") + if report.Status != artifactinspect.StatusComplete || report.Artifact.Magic != "jmod" || report.Artifact.Format != "jmod" { + t.Fatalf("report = %#v", report) + } + if report.Archive == nil { + t.Fatal("JMOD archive inventory is nil") + } + names := entryNames(report.Archive.Entries) + want := []string{"classes/demo/Hello.class", "conf/example.properties"} + if len(names) != len(want) { + t.Fatalf("entries = %v, want %v", names, want) + } + for index := range want { + if names[index] != want[index] { + t.Fatalf("entries = %v, want %v", names, want) + } + } +} + +func TestAnalyzeAAR(t *testing.T) { + classBytes := containerClassFixture(t) + classesJAR := containerZIP(t, map[string][]byte{"lib/Nested.class": classBytes}) + aar := containerZIP(t, map[string][]byte{ + "AndroidManifest.xml": []byte("\n"), + "classes.jar": classesJAR, + }) + report := artifactinspect.Analyze(aar, "app.aar") + if report.Status != artifactinspect.StatusComplete || report.Artifact.Format != "aar" { + t.Fatalf("report = %#v", report) + } + if len(report.DEXFiles) != 0 { + t.Fatalf("AAR unexpectedly produced DEX files: %#v", report.DEXFiles) + } + for _, entry := range report.Archive.Entries { + if entry.Name == "classes.jar" && entry.Kind != "archive" { + t.Fatalf("classes.jar kind = %q, want archive", entry.Kind) + } + } +} + +func TestAnalyzeJImage(t *testing.T) { + classBytes := containerClassFixture(t) + image, err := jimagefixture.Build([]jimagefixture.Entry{ + {Path: "/test/demo/Hello.class", Data: classBytes, Compressed: true}, + {Path: "/test/conf/app.properties", Data: []byte("key=value\n")}, + }) + if err != nil { + t.Fatal(err) + } + report := artifactinspect.Analyze(image, "modules") + if report.Status != artifactinspect.StatusComplete || report.Artifact.Format != "jimage" || report.Artifact.Magic != "jimage" { + t.Fatalf("report = %#v", report) + } + if report.Archive == nil || len(report.Archive.Entries) != 2 || len(report.Archive.Resources) != 1 { + t.Fatalf("archive = %#v", report.Archive) + } + var classEntry, resourceEntry *artifactinspect.ArchiveEntry + for index := range report.Archive.Entries { + entry := &report.Archive.Entries[index] + switch entry.Name { + case "test/demo/Hello.class": + classEntry = entry + case "test/conf/app.properties": + resourceEntry = entry + } + } + if classEntry == nil || classEntry.Kind != "class" || + classEntry.CompressedSize == 0 || classEntry.Compression != 8 || len(classEntry.SHA256) != 64 { + t.Fatalf("class entry = %#v", classEntry) + } + if resourceEntry == nil || resourceEntry.Kind != "resource" || len(resourceEntry.SHA256) != 64 { + t.Fatalf("resource entry = %#v", resourceEntry) + } +} + +func TestAnalyzeJImageUnsupportedCompressor(t *testing.T) { + classBytes := containerClassFixture(t) + image, err := jimagefixture.Build([]jimagefixture.Entry{ + {Path: "/test/demo/Hello.class", Data: classBytes, Compressed: true, Compressor: "lzma"}, + }) + if err != nil { + t.Fatal(err) + } + report := artifactinspect.Analyze(image, "modules") + if report.Status != artifactinspect.StatusPartial { + t.Fatalf("status = %q, want partial", report.Status) + } + found := false + for _, diagnostic := range report.Diagnostics { + if strings.Contains(diagnostic.Message, "lzma") { + found = true + break + } + } + if !found { + t.Fatalf("diagnostics = %#v", report.Diagnostics) + } +} + +func TestAnalyzeGenericZIP(t *testing.T) { + report := artifactinspect.Analyze(containerZIP(t, map[string][]byte{"data.txt": []byte("x")}), "data.zip") + if report.Status != artifactinspect.StatusUnsupported || report.Artifact.Format != "zip" { + t.Fatalf("report = %#v", report) + } + if len(report.Diagnostics) != 1 || !strings.Contains(report.Diagnostics[0].Message, "not identifiable") { + t.Fatalf("diagnostics = %#v", report.Diagnostics) + } +} diff --git a/inspect/fuzz_test.go b/inspect/fuzz_test.go new file mode 100644 index 00000000..0ec14a87 --- /dev/null +++ b/inspect/fuzz_test.go @@ -0,0 +1,59 @@ +package inspect_test + +import ( + "archive/zip" + "bytes" + "testing" + + artifactinspect "github.com/yaklang/javajive/inspect" + "github.com/yaklang/javajive/internal/jimagefixture" +) + +func fuzzZIP(tb testing.TB, files map[string][]byte) []byte { + tb.Helper() + var buffer bytes.Buffer + writer := zip.NewWriter(&buffer) + for name, body := range files { + entry, err := writer.Create(name) + if err != nil { + tb.Fatal(err) + } + if _, err := entry.Write(body); err != nil { + tb.Fatal(err) + } + } + if err := writer.Close(); err != nil { + tb.Fatal(err) + } + return buffer.Bytes() +} + +func FuzzAnalyze(f *testing.F) { + emptyZIP := fuzzZIP(f, nil) + apk := fuzzZIP(f, map[string][]byte{"classes.dex": []byte("dex\n035\x00")}) + jimageData, err := jimagefixture.Build([]jimagefixture.Entry{ + {Path: "/test/demo/Foo.class", Data: []byte{0xca, 0xfe, 0xba, 0xbe}}, + }) + if err != nil { + f.Fatal(err) + } + seeds := [][]byte{ + []byte("dex\n035\x00"), + []byte{0xca, 0xfe, 0xba, 0xbe}, + append([]byte{'J', 'M', 1, 0}, emptyZIP...), + jimageData, + apk, + fuzzZIP(f, map[string][]byte{"base.apk": apk}), + fuzzZIP(f, map[string][]byte{"base/dex/classes.dex": []byte("dex\n035\x00")}), + fuzzZIP(f, map[string][]byte{"manifest.json": {1}, "base.apk": apk}), + fuzzZIP(f, map[string][]byte{"info.json": {1}, "base.apk": apk}), + fuzzZIP(f, map[string][]byte{"WEB-INF/classes/Foo.class": {0xca, 0xfe, 0xba, 0xbe}}), + []byte("not an artifact"), + } + for _, seed := range seeds { + f.Add(seed) + } + f.Fuzz(func(t *testing.T, data []byte) { + _ = artifactinspect.AnalyzeWithOptions(data, "fuzz", artifactinspect.Options{Disassembly: false}) + }) +} diff --git a/internal/dexparser/annotations.go b/internal/dexparser/annotations.go index 21a138dd..54cb8903 100644 --- a/internal/dexparser/annotations.go +++ b/internal/dexparser/annotations.go @@ -34,6 +34,15 @@ func (p *parser) parseAnnotationDirectory(off uint32, c *model.Class) error { c.Annotations = annotations } cursor := pos + 16 + if fieldsSize > 0 { + c.FieldAnnotationIndex = make(map[uint32]int, fieldsSize) + } + if methodsSize > 0 { + c.MethodAnnotationIndex = make(map[uint32]int, methodsSize) + } + if parametersSize > 0 { + c.ParameterAnnotationIndex = make(map[uint32]int, parametersSize) + } seenFields := make(map[uint32]bool, fieldsSize) for i := uint32(0); i < fieldsSize; i++ { fieldIdx := binary.LittleEndian.Uint32(p.data[cursor : cursor+4]) @@ -50,6 +59,7 @@ func (p *parser) parseAnnotationDirectory(off uint32, c *model.Class) error { if err != nil { return err } + c.FieldAnnotationIndex[fieldIdx] = len(c.FieldAnnotations) c.FieldAnnotations = append(c.FieldAnnotations, model.FieldAnnotation{FieldIndex: fieldIdx, Annotations: annotations}) } seenMethods := make(map[uint32]bool, methodsSize) @@ -68,6 +78,7 @@ func (p *parser) parseAnnotationDirectory(off uint32, c *model.Class) error { if err != nil { return err } + c.MethodAnnotationIndex[methodIdx] = len(c.MethodAnnotations) c.MethodAnnotations = append(c.MethodAnnotations, model.MethodAnnotation{MethodIndex: methodIdx, Annotations: annotations}) } seenParameters := make(map[uint32]bool, parametersSize) @@ -86,6 +97,7 @@ func (p *parser) parseAnnotationDirectory(off uint32, c *model.Class) error { if err != nil { return err } + c.ParameterAnnotationIndex[methodIdx] = len(c.ParameterAnnotations) c.ParameterAnnotations = append(c.ParameterAnnotations, model.ParameterAnnotation{MethodIndex: methodIdx, Parameters: parameters}) } return nil @@ -309,6 +321,10 @@ func (p *parser) translateSystemAnnotations(c *model.Class) error { for _, descriptor := range descriptors { c.InnerClasses = append(c.InnerClasses, model.InnerClass{Inner: descriptor, Outer: c.Descriptor}) } + case "Ldalvik/annotation/AnnotationDefault;": + if err := p.applyAnnotationDefaults(c, annotation); err != nil { + return err + } default: // MethodParameters, Record, PermittedSubclasses, NestHost and other // post-Java-5 system annotations have no representation in a @@ -319,6 +335,63 @@ func (p *parser) translateSystemAnnotations(c *model.Class) error { return nil } +func (p *parser) applyAnnotationDefaults(c *model.Class, annotation model.Annotation) error { + value, ok := annotationElement(annotation, "value") + if !ok { + return p.fail(0, "system annotation", "AnnotationDefault is missing element %q", "value") + } + if value.Type != model.ValueAnnotation || value.Annotation == nil { + return p.fail(0, "system annotation", "AnnotationDefault element %q is not an annotation", "value") + } + methods := make(map[string]uint32) + addMethods := func(encoded []model.EncodedMethod) error { + for index := range encoded { + method := &encoded[index] + if previous, exists := methods[method.Method.Name]; exists && previous != method.MethodIndex { + return p.fail(0, "system annotation", "AnnotationDefault method name %q is ambiguous", method.Method.Name) + } + methods[method.Method.Name] = method.MethodIndex + } + return nil + } + if err := addMethods(c.DirectMethods); err != nil { + return err + } + if err := addMethods(c.VirtualMethods); err != nil { + return err + } + for _, element := range value.Annotation.Elements { + methodIndex, exists := methods[element.Name] + if !exists { + return p.fail(0, "system annotation", "AnnotationDefault element %q has no annotation method", element.Name) + } + annotation := model.Annotation{ + Visibility: model.AnnotationSystem, + Type: "Ldalvik/annotation/AnnotationDefault;", + Elements: []model.AnnotationElement{{Name: "value", Value: element.Value}}, + } + position, exists := c.MethodAnnotationIndex[methodIndex] + if !exists { + for index := range c.MethodAnnotations { + if c.MethodAnnotations[index].MethodIndex == methodIndex { + position, exists = index, true + break + } + } + } + if exists { + c.MethodAnnotations[position].Annotations = append(c.MethodAnnotations[position].Annotations, annotation) + continue + } + if c.MethodAnnotationIndex == nil { + c.MethodAnnotationIndex = make(map[uint32]int) + } + c.MethodAnnotationIndex[methodIndex] = len(c.MethodAnnotations) + c.MethodAnnotations = append(c.MethodAnnotations, model.MethodAnnotation{MethodIndex: methodIndex, Annotations: []model.Annotation{annotation}}) + } + return nil +} + func (p *parser) applyEnclosingMethod(c *model.Class, annotation model.Annotation) error { value, ok := annotationElement(annotation, "value") if !ok { @@ -407,9 +480,12 @@ func protoDescriptor(proto model.Proto) (string, error) { func (p *parser) checkAnnotationMethodMembership() error { for _, class := range p.file.Classes { - owned := make(map[uint32]bool) - for _, method := range append(append([]model.EncodedMethod(nil), class.DirectMethods...), class.VirtualMethods...) { - owned[method.MethodIndex] = true + owned := make(map[uint32]bool, len(class.DirectMethods)+len(class.VirtualMethods)) + for index := range class.DirectMethods { + owned[class.DirectMethods[index].MethodIndex] = true + } + for index := range class.VirtualMethods { + owned[class.VirtualMethods[index].MethodIndex] = true } for _, annotation := range class.MethodAnnotations { if !owned[annotation.MethodIndex] { diff --git a/internal/dexparser/annotations_test.go b/internal/dexparser/annotations_test.go index a9602606..6a0e6bf8 100644 --- a/internal/dexparser/annotations_test.go +++ b/internal/dexparser/annotations_test.go @@ -9,6 +9,44 @@ import ( // fillInnerClassOuters must link nested classes only from file evidence: // a MemberClasses row declared by the outer class, or an EnclosingClass // annotation. A "$" in the descriptor is not evidence and must not be parsed. +func TestTranslateSystemAnnotationsAssignsAnnotationDefaults(t *testing.T) { + const owner = "Lpkg/Defaults;" + file := &model.File{} + class := model.Class{ + Descriptor: owner, + VirtualMethods: []model.EncodedMethod{{ + MethodIndex: 7, + Method: model.MethodID{Class: owner, Name: "value"}, + }}, + Annotations: []model.Annotation{{ + Visibility: model.AnnotationSystem, + Type: "Ldalvik/annotation/AnnotationDefault;", + Elements: []model.AnnotationElement{{ + Name: "value", + Value: model.EncodedValue{Type: model.ValueAnnotation, Annotation: &model.EncodedAnnotation{ + Type: owner, + Elements: []model.AnnotationElement{{Name: "value", Value: model.EncodedValue{Type: model.ValueInt, Signed: 7}}}, + }}, + }}, + }}, + } + p := &parser{file: file} + if err := p.translateSystemAnnotations(&class); err != nil { + t.Fatal(err) + } + if len(class.Annotations) != 0 || len(class.MethodAnnotations) != 1 { + t.Fatalf("class = %#v", class) + } + annotation := class.MethodAnnotations[0] + if annotation.MethodIndex != 7 || len(annotation.Annotations) != 1 || annotation.Annotations[0].Type != "Ldalvik/annotation/AnnotationDefault;" { + t.Fatalf("method annotation = %#v", annotation) + } + value := annotation.Annotations[0].Elements[0].Value + if value.Type != model.ValueInt || value.Signed != 7 { + t.Fatalf("default value = %#v", value) + } +} + func TestFillInnerClassOutersUsesFileEvidence(t *testing.T) { file := &model.File{Classes: []model.Class{ { diff --git a/internal/dexparser/classes.go b/internal/dexparser/classes.go index a774adef..a37c64b6 100644 --- a/internal/dexparser/classes.go +++ b/internal/dexparser/classes.go @@ -53,9 +53,6 @@ func (p *parser) parseClasses() error { if err := p.parseAnnotationDirectory(annotationsOff, &c); err != nil { return err } - if err := p.translateSystemAnnotations(&c); err != nil { - return err - } } indices, names, err := p.typeList(interfacesOff) if err != nil { @@ -65,6 +62,11 @@ func (p *parser) parseClasses() error { if err := p.classData(classDataOff, &c); err != nil { return err } + if annotationsOff != 0 { + if err := p.translateSystemAnnotations(&c); err != nil { + return err + } + } if staticValuesOff != 0 { cur := int(staticValuesOff) values, err := p.encodedArray(&cur, 0) @@ -203,7 +205,8 @@ func (p *parser) encodedMethods(cur *int, count uint32, direct bool) ([]model.En } method := model.EncodedMethod{MethodIndex: index, AccessFlags: flags, Method: methodID} if codeOff != 0 { - method.Code, err = p.codeItem(codeOff) + declaredParameters := uint32(len(p.file.Protos[methodID.ProtoIndex].Parameters)) + method.Code, err = p.codeItem(codeOff, declaredParameters) if err != nil { return nil, err } @@ -214,7 +217,7 @@ func (p *parser) encodedMethods(cur *int, count uint32, direct bool) ([]model.En return out, nil } -func (p *parser) codeItem(off uint32) (*model.Code, error) { +func (p *parser) codeItem(off uint32, declaredParameters uint32) (*model.Code, error) { if off%4 != 0 { return nil, p.fail(int(off), "code_item", "offset is not 4-byte aligned") } @@ -239,7 +242,7 @@ func (p *parser) codeItem(off uint32) (*model.Code, error) { code.Instructions[i] = binary.LittleEndian.Uint16(p.data[at : at+2]) } if debugOff != 0 { - debug, err := p.parseDebugInfo(debugOff, insnsSize, registers) + debug, err := p.parseDebugInfo(debugOff, insnsSize, registers, declaredParameters) if err != nil { return nil, err } diff --git a/internal/dexparser/debug.go b/internal/dexparser/debug.go index 51c11659..8a3db20a 100644 --- a/internal/dexparser/debug.go +++ b/internal/dexparser/debug.go @@ -23,19 +23,19 @@ const ( // parseDebugInfo decodes a debug_info_item and validates it against the code // item it belongs to. A malformed stream is rejected rather than ignored: // emitting a wrong line or local range is as damaging as wrong bytecode. -func (p *parser) parseDebugInfo(off uint32, insnsSize uint32, registers uint16) (*model.DebugInfo, error) { +func (p *parser) parseDebugInfo(off uint32, insnsSize uint32, registers uint16, declaredParameters uint32) (*model.DebugInfo, error) { // Debug metadata is auxiliary: a real toolchain may emit line 0, positions // past the last instruction, or a truncated local range. None of that // changes bytecode semantics, so the stream degrades instead of failing the // class. Only structurally impossible headers end parsing early. - info, err := p.parseDebugStream(off, insnsSize, registers) + info, err := p.parseDebugStream(off, insnsSize, registers, declaredParameters) if err != nil { return nil, nil } return info, nil } -func (p *parser) parseDebugStream(off uint32, insnsSize uint32, registers uint16) (*model.DebugInfo, error) { +func (p *parser) parseDebugStream(off uint32, insnsSize uint32, registers uint16, declaredParameters uint32) (*model.DebugInfo, error) { if err := p.rangeCheck(off, 4, "debug_info"); err != nil { return nil, err } @@ -50,8 +50,9 @@ func (p *parser) parseDebugStream(off uint32, insnsSize uint32, registers uint16 if err != nil { return nil, p.fail(cur, "debug_info", "parameters_size: %v", err) } - if parameterCount > uint32(len(p.data)) { - return nil, p.fail(cur, "debug_info", "parameters_size=%d exceeds file size", parameterCount) + remaining := len(p.data) - cur + if parameterCount > declaredParameters || parameterCount > uint32(remaining) || parameterCount > uint32(registers) { + return nil, p.fail(cur, "debug_info", "parameters_size=%d exceeds declared parameters=%d, remaining bytes=%d, or registers=%d", parameterCount, declaredParameters, remaining, registers) } info := &model.DebugInfo{LineStart: lineStart} if parameterCount > 0 { @@ -65,10 +66,52 @@ func (p *parser) parseDebugStream(off uint32, insnsSize uint32, registers uint16 info.ParameterNames[i] = p.stringIndexOrEmpty(nameIndex) } + // Every decoded position or local requires at least one opcode byte. Sharing + // this budget across both record kinds prevents a malformed stream from + // amplifying a small debug item into large model slices. + recordBudget := len(p.data) - cur + if recordBudget < 0 { + recordBudget = 0 + } + // Pre-size the common debug tables without trusting the stream length. + // Local restarts append additional ranges, so registers is only a lower + // bound; the cap avoids reserving a large table for a method with little + // debug data. The old append-only growth dominated DEX debug allocations. + localHint := int(registers) + if localHint > 256 { + localHint = 256 + } + if maxByBytes := recordBudget / 3; localHint > maxByBytes { + localHint = maxByBytes + } + if localHint > 0 { + info.Locals = make([]model.DebugLocal, 0, localHint) + } + positionHint := int(insnsSize) / 2 + if positionHint > 256 { + positionHint = 256 + } + if maxByBytes := recordBudget / 2; positionHint > maxByBytes { + positionHint = maxByBytes + } + if positionHint > 0 { + info.Positions = make([]model.DebugPosition, 0, positionHint) + } + decodedRecords := 0 + reserveRecord := func() error { + if decodedRecords >= recordBudget { + return p.fail(cur, "debug_info", "decoded record count exceeds remaining stream bytes") + } + decodedRecords++ + return nil + } + var address uint32 line := lineStart - // open holds the currently live local for each register. + // open holds the currently live local for each register. latest makes + // DBG_RESTART_LOCAL constant-time instead of scanning all prior declarations. open := make(map[uint16]int) + latest := make(map[uint16]int) var file string for { @@ -102,41 +145,54 @@ func (p *parser) parseDebugStream(off uint32, insnsSize uint32, registers uint16 case opcode == dbgStartLocal || opcode == dbgStartLocalExt: register, err := p.uleb(&cur) if err != nil { - break + return nil, p.fail(cur, "debug_info", "DBG_START_LOCAL register: %v", err) + } + if register >= uint32(registers) { + return nil, p.fail(cur, "debug_info", "local register v%d exceeds registers_size=%d", register, registers) } nameIndex, err := p.uleb(&cur) if err != nil { - break + return nil, p.fail(cur, "debug_info", "DBG_START_LOCAL name: %v", err) } typeIndex, err := p.uleb(&cur) if err != nil { - break + return nil, p.fail(cur, "debug_info", "DBG_START_LOCAL type: %v", err) } signature := "" if opcode == dbgStartLocalExt { signatureIndex, err := p.uleb(&cur) if err != nil { - break + return nil, p.fail(cur, "debug_info", "DBG_START_LOCAL_EXT signature: %v", err) } signature = p.stringIndexOrEmpty(signatureIndex) } name := p.stringIndexOrEmpty(nameIndex) typeName := p.typeIndexOrEmpty(typeIndex) - if index, live := open[uint16(register)]; live { + register16 := uint16(register) + if index, live := open[register16]; live { p.endDebugLocal(info, index, address, insnsSize) - delete(open, uint16(register)) + delete(open, register16) + } + if err := reserveRecord(); err != nil { + return nil, err } info.Locals = append(info.Locals, model.DebugLocal{ - Register: uint16(register), Name: name, Type: typeName, + Register: register16, Name: name, Type: typeName, Signature: signature, Start: address, End: address, }) - open[uint16(register)] = len(info.Locals) - 1 + index := len(info.Locals) - 1 + open[register16] = index + latest[register16] = index case opcode == dbgEndLocal: register, err := p.uleb(&cur) if err != nil { - break + return nil, p.fail(cur, "debug_info", "DBG_END_LOCAL register: %v", err) + } + if register >= uint32(registers) { + return nil, p.fail(cur, "debug_info", "local register v%d exceeds registers_size=%d", register, registers) } - index, live := open[uint16(register)] + register16 := uint16(register) + index, live := open[register16] if !live { // Toolchains emit END_LOCAL for parameter locals whose ranges // start outside the state machine. Debug metadata is auxiliary, @@ -144,22 +200,34 @@ func (p *parser) parseDebugStream(off uint32, insnsSize uint32, registers uint16 break } p.endDebugLocal(info, index, address, insnsSize) - delete(open, uint16(register)) + delete(open, register16) case opcode == dbgRestartLocal: register, err := p.uleb(&cur) if err != nil { + return nil, p.fail(cur, "debug_info", "DBG_RESTART_LOCAL register: %v", err) + } + if register >= uint32(registers) { + return nil, p.fail(cur, "debug_info", "local register v%d exceeds registers_size=%d", register, registers) + } + register16 := uint16(register) + if _, live := open[register16]; live { break } - if _, live := open[uint16(register)]; live { + previous, exists := latest[register16] + if !exists { break } - p.reopenDebugLocal(info, uint16(register), address, open) + if err := reserveRecord(); err != nil { + return nil, err + } + index := p.reopenDebugLocal(info, register16, previous, address, open) + latest[register16] = index case opcode == dbgSetPrologueEnd || opcode == dbgSetEpilogueBegin: // No JVM counterpart; the sequence is still validated for order. case opcode == dbgSetFile: fileIndex, err := p.uleb(&cur) if err != nil { - break + return nil, p.fail(cur, "debug_info", "DBG_SET_FILE: %v", err) } file = p.stringIndexOrEmpty(fileIndex) default: @@ -180,6 +248,9 @@ func (p *parser) parseDebugStream(off uint32, insnsSize uint32, registers uint16 if opcode < dbgFirstSpecial { continue } + if err := reserveRecord(); err != nil { + return nil, err + } info.Positions = append(info.Positions, model.DebugPosition{Address: address, Line: line, File: file}) } return info, nil @@ -198,21 +269,17 @@ func (p *parser) endDebugLocal(info *model.DebugInfo, index int, address, insnsS info.Locals[index].End = address } -func (p *parser) reopenDebugLocal(info *model.DebugInfo, register uint16, address uint32, open map[uint16]int) { +func (p *parser) reopenDebugLocal(info *model.DebugInfo, register uint16, previous int, address uint32, open map[uint16]int) int { // Reuse the most recent declaration of this register: DBG_RESTART_LOCAL // restores a local that was ended, not a new name-and-type binding. - for index := len(info.Locals) - 1; index >= 0; index-- { - if info.Locals[index].Register != register { - continue - } - info.Locals = append(info.Locals, model.DebugLocal{ - Register: register, Name: info.Locals[index].Name, Type: info.Locals[index].Type, - Signature: info.Locals[index].Signature, Start: address, End: address, - }) - open[register] = len(info.Locals) - 1 - return - } - // No prior declaration of this register: nothing to restart. + local := info.Locals[previous] + info.Locals = append(info.Locals, model.DebugLocal{ + Register: register, Name: local.Name, Type: local.Type, + Signature: local.Signature, Start: address, End: address, + }) + index := len(info.Locals) - 1 + open[register] = index + return index } func (p *parser) stringIndexOrEmpty(index uint32) string { diff --git a/internal/dexparser/debug_test.go b/internal/dexparser/debug_test.go new file mode 100644 index 00000000..75ab62d1 --- /dev/null +++ b/internal/dexparser/debug_test.go @@ -0,0 +1,93 @@ +package dexparser + +import ( + "strings" + "testing" + + "github.com/yaklang/javajive/dex2jar/model" +) + +func TestParseDebugStreamBoundsHeaderAndRegisters(t *testing.T) { + tests := []struct { + name string + data []byte + registers uint16 + parameters uint32 + want string + }{ + {name: "declared parameters", data: []byte{1, 2, 0, 0}, registers: 2, parameters: 1, want: "exceeds declared parameters"}, + {name: "register", data: []byte{1, 0, dbgStartLocal, 2, 0, 0, dbgEndSequence}, registers: 2, want: "local register v2 exceeds"}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + p := &parser{data: test.data, file: &model.File{}} + _, err := p.parseDebugStream(0, 1, test.registers, test.parameters) + if err == nil || !strings.Contains(err.Error(), test.want) { + t.Fatalf("parseDebugStream() error = %v, want substring %q", err, test.want) + } + }) + } +} + +func TestParseDebugStreamRestartLocalScale(t *testing.T) { + const locals = 4096 + data := []byte{1, 0} + for register := 0; register < locals; register++ { + data = append(data, dbgStartLocal) + data = appendTestULEB(data, uint32(register)) + data = append(data, 0, 0, dbgEndLocal) + data = appendTestULEB(data, uint32(register)) + } + for register := 0; register < locals; register++ { + data = append(data, dbgRestartLocal) + data = appendTestULEB(data, uint32(register)) + } + data = append(data, dbgEndSequence) + + p := &parser{data: data, file: &model.File{}} + info, err := p.parseDebugStream(0, 1, locals, 0) + if err != nil { + t.Fatalf("parseDebugStream() error = %v", err) + } + if got, want := len(info.Locals), locals*2; got != want { + t.Fatalf("local count = %d, want %d", got, want) + } +} + +func BenchmarkParseDebugRestartLocalScale(b *testing.B) { + const locals = 8192 + data := []byte{1, 0} + for register := 0; register < locals; register++ { + data = append(data, dbgStartLocal) + data = appendTestULEB(data, uint32(register)) + data = append(data, 0, 0, dbgEndLocal) + data = appendTestULEB(data, uint32(register)) + } + for register := 0; register < locals; register++ { + data = append(data, dbgRestartLocal) + data = appendTestULEB(data, uint32(register)) + } + data = append(data, dbgEndSequence) + b.ReportAllocs() + b.SetBytes(int64(len(data))) + for i := 0; i < b.N; i++ { + p := &parser{data: data, file: &model.File{}} + if _, err := p.parseDebugStream(0, 1, locals, 0); err != nil { + b.Fatal(err) + } + } +} + +func appendTestULEB(data []byte, value uint32) []byte { + for { + part := byte(value & 0x7f) + value >>= 7 + if value != 0 { + part |= 0x80 + } + data = append(data, part) + if value == 0 { + return data + } + } +} diff --git a/internal/filesys/t23_archive.go b/internal/filesys/t23_archive.go index 4fe7c437..b42e9a78 100644 --- a/internal/filesys/t23_archive.go +++ b/internal/filesys/t23_archive.go @@ -706,7 +706,7 @@ func NormalizeArchiveEntryName(name string) (string, error) { } func isDriveLetter(c byte) bool { - return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'Z') + return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') } const multiReleasePrefix = "META-INF/versions/" diff --git a/internal/filesys/t23_archive_test.go b/internal/filesys/t23_archive_test.go index 50b72082..62b5733a 100644 --- a/internal/filesys/t23_archive_test.go +++ b/internal/filesys/t23_archive_test.go @@ -182,11 +182,14 @@ func TestT23_C02_PathsAndDuplicates(t *testing.T) { } else { t23MustPathRejected(t, err) } - if _, err := NormalizeArchiveEntryName("C:/windows/x"); err == nil { - t.Fatal("expected reject drive path") - } else { - t23MustPathRejected(t, err) + for _, drivePath := range []string{"C:/windows/x", "c:/windows/x", "z:/windows/x"} { + if _, err := NormalizeArchiveEntryName(drivePath); err == nil { + t.Fatalf("expected reject drive path %q", drivePath) + } else { + t23MustPathRejected(t, err) + } } + if _, err := NormalizeArchiveEntryName("foo\x00bar"); err == nil { t.Fatal("expected reject NUL") } else { diff --git a/internal/filesys/zip_fs.go b/internal/filesys/zip_fs.go index 407b2503..d8a35ac2 100644 --- a/internal/filesys/zip_fs.go +++ b/internal/filesys/zip_fs.go @@ -10,6 +10,7 @@ import ( "strings" fi "github.com/yaklang/javajive/internal/filesys/filesys_interface" + "github.com/yaklang/javajive/internal/inputkind" "github.com/yaklang/javajive/internal/memfile" "github.com/yaklang/javajive/internal/utils" "github.com/yaklang/javajive/internal/workbudget" @@ -336,6 +337,10 @@ func NewZipFSFromStringWithOptions(i string, opts ...ZipFSOption) (*ZipFS, error // NewZipFSFromLocalWithOptions 从本地文件构造带密码 ZipFS // 关键词: ZipFS 密码构造, NewZipFSFromLocalWithOptions +// +// JMOD files carry a four-byte "JM\x01\x00" prefix before the embedded ZIP. +// The prefix is stripped automatically so JMOD inputs behave like ordinary +// archives throughout the class parser and archive exporter. func NewZipFSFromLocalWithOptions(i string, opts ...ZipFSOption) (*ZipFS, error) { local := NewLocalFs() f, err := local.Open(i) @@ -352,7 +357,17 @@ func NewZipFSFromLocalWithOptions(i string, opts ...ZipFSOption) (*ZipFS, error) f.Close() return nil, err } - return NewZipFSRawWithCloserAndOptions(ra, info.Size(), f, opts...) + size := info.Size() + var header [inputkind.JMODHeaderSize]byte + if n, readErr := ra.ReadAt(header[:], 0); (readErr == nil || readErr == io.EOF) && n == len(header) && inputkind.IsJMODHeader(header[:]) { + if size <= int64(inputkind.JMODHeaderSize) { + f.Close() + return nil, utils.Errorf("JMOD %s is truncated", i) + } + section := io.NewSectionReader(ra, int64(inputkind.JMODHeaderSize), size-int64(inputkind.JMODHeaderSize)) + return NewZipFSRawWithCloserAndOptions(section, size-int64(inputkind.JMODHeaderSize), f, opts...) + } + return NewZipFSRawWithCloserAndOptions(ra, size, f, opts...) } // buildZipFS 是 ZipFS 构造的内部统一入口 diff --git a/internal/inputkind/fuzz_test.go b/internal/inputkind/fuzz_test.go new file mode 100644 index 00000000..6f27d248 --- /dev/null +++ b/internal/inputkind/fuzz_test.go @@ -0,0 +1,66 @@ +package inputkind + +import ( + "archive/zip" + "bytes" + "testing" + + "github.com/yaklang/javajive/internal/jimagefixture" +) + +func fuzzZIP(tb testing.TB, files map[string][]byte) []byte { + tb.Helper() + var buffer bytes.Buffer + writer := zip.NewWriter(&buffer) + for name, body := range files { + entry, err := writer.Create(name) + if err != nil { + tb.Fatal(err) + } + if _, err := entry.Write(body); err != nil { + tb.Fatal(err) + } + } + if err := writer.Close(); err != nil { + tb.Fatal(err) + } + return buffer.Bytes() +} + +func FuzzDetectBytes(f *testing.F) { + emptyZIP := fuzzZIP(f, nil) + nestedAPK := fuzzZIP(f, map[string][]byte{"classes.dex": []byte("dex\n035\x00")}) + jimageData, err := jimagefixture.Build([]jimagefixture.Entry{ + {Path: "/test/demo/Foo.class", Data: []byte{0xca, 0xfe, 0xba, 0xbe}}, + }) + if err != nil { + f.Fatal(err) + } + seeds := []struct { + data []byte + name string + }{ + {[]byte("dex\n035\x00"), "classes.dex"}, + {[]byte{0xca, 0xfe, 0xba, 0xbe}, "Foo.class"}, + {append([]byte{'J', 'M', 1, 0}, emptyZIP...), "java.base.jmod"}, + {jimageData, "modules"}, + {fuzzZIP(f, map[string][]byte{"WEB-INF/classes/Foo.class": {0xca, 0xfe, 0xba, 0xbe}}), "app.war"}, + {fuzzZIP(f, map[string][]byte{"base.apk": nestedAPK}), "app.apks"}, + {fuzzZIP(f, map[string][]byte{"manifest.json": {1}, "base.apk": nestedAPK}), "app.xapk"}, + {fuzzZIP(f, map[string][]byte{"info.json": {1}, "base.apk": nestedAPK}), "app.apkm"}, + {fuzzZIP(f, map[string][]byte{"base/dex/classes.dex": []byte("dex\n035\x00")}), "app.aab"}, + {fuzzZIP(f, map[string][]byte{"classes.jar": {0x50, 0x4b, 3, 4}, "AndroidManifest.xml": {1}}), "lib.aar"}, + {[]byte("not an artifact"), "notes.txt"}, + } + for _, seed := range seeds { + f.Add(seed.data, seed.name) + } + f.Fuzz(func(t *testing.T, data []byte, name string) { + kind := DetectBytes(data, name) + _ = IsAndroid(kind) + _ = IsJavaArchive(kind) + _ = DetectMagic(data) + _ = IsJMODHeader(data) + _ = IsJImageHeader(data) + }) +} diff --git a/internal/inputkind/inputkind.go b/internal/inputkind/inputkind.go new file mode 100644 index 00000000..f5f6769f --- /dev/null +++ b/internal/inputkind/inputkind.go @@ -0,0 +1,377 @@ +// Package inputkind classifies supported Java and Android input containers by +// content magic first and archive structure second. Extensions are only a +// fallback, so renamed artifacts keep working. +package inputkind + +import ( + "archive/zip" + "bytes" + "encoding/binary" + "io" + "os" + "path" + "path/filepath" + "regexp" + "strconv" + "strings" +) + +// Kind identifies a supported input container. +type Kind string + +const ( + Unknown Kind = "unknown" + Class Kind = "class" + DEX Kind = "dex" + JMOD Kind = "jmod" + JIMAGE Kind = "jimage" + JAR Kind = "jar" + WAR Kind = "war" + EAR Kind = "ear" + AAR Kind = "aar" + PAR Kind = "par" + ZIP Kind = "zip" + APK Kind = "apk" + APKS Kind = "apks" + XAPK Kind = "xapk" + APKM Kind = "apkm" + AAB Kind = "aab" +) + +// JMODHeaderSize is the size of the JMOD prefix before the embedded ZIP. +const JMODHeaderSize = 4 + +var ( + rootDEXPattern = regexp.MustCompile(`^classes([0-9]*)\.dex$`) + aabDEXPattern = regexp.MustCompile(`^([^/]+)/dex/classes([0-9]*)\.dex$`) +) + +// IsAndroid reports whether kind is an Android code container that the DEX +// pipeline can translate. +func IsAndroid(kind Kind) bool { + switch kind { + case APK, APKS, XAPK, APKM, AAB: + return true + default: + return false + } +} + +// IsJavaArchive reports whether kind should be exported by the Java archive +// decompiler. ZIP is included because a generic ZIP may contain classes or +// nested JARs. +func IsJavaArchive(kind Kind) bool { + switch kind { + case JMOD, JIMAGE, JAR, WAR, EAR, AAR, PAR, ZIP: + return true + default: + return false + } +} + +// IsJMODHeader reports whether data starts with the JMOD magic prefix +// "JM\x01\x00" that precedes the embedded ZIP. +func IsJMODHeader(data []byte) bool { + return len(data) >= JMODHeaderSize && + data[0] == 'J' && data[1] == 'M' && data[2] == 1 && data[3] == 0 +} + +// JImageMagic is the JImage header marker. JDK images use native endianness, +// so the marker is checked in both byte orders. +const JImageMagic = 0xCAFEDADA + +// IsJImageHeader reports whether data starts with a JImage magic in either +// byte order. +func IsJImageHeader(data []byte) bool { + if len(data) < 4 { + return false + } + return binary.LittleEndian.Uint32(data[:4]) == JImageMagic || + binary.BigEndian.Uint32(data[:4]) == JImageMagic +} + +// StripJMODHeader returns the embedded ZIP bytes when data is a JMOD, and data +// unchanged otherwise. +func StripJMODHeader(data []byte) []byte { + if IsJMODHeader(data) { + return data[JMODHeaderSize:] + } + return data +} + +// DetectMagic classifies only the first bytes of an input. It never opens a +// ZIP central directory, so callers may pass an 8-byte prefix. +func DetectMagic(data []byte) Kind { + switch { + case hasDEXMagic(data): + return DEX + case IsJMODHeader(data): + return JMOD + case IsJImageHeader(data): + return JIMAGE + case hasZIPMagic(data): + return ZIP + case hasClassMagic(data): + return Class + default: + return Unknown + } +} + +// DetectBytes classifies a complete input by magic, archive structure, and +// finally the file name extension. +func DetectBytes(data []byte, name string) Kind { + return detect(bytes.NewReader(data), int64(len(data)), name) +} + +// DetectReaderAt classifies an input without requiring it to be held in memory. +// The reader must remain valid for the duration of the call. +func DetectReaderAt(r io.ReaderAt, size int64, name string) (Kind, error) { + return detectWithError(r, size, name) +} + +// DetectFile classifies a file on disk without loading the whole archive. +func DetectFile(name string) (Kind, error) { + file, err := os.Open(name) + if err != nil { + return Unknown, err + } + defer file.Close() + info, err := file.Stat() + if err != nil { + return Unknown, err + } + return detectWithError(file, info.Size(), name) +} + +func detect(r io.ReaderAt, size int64, name string) Kind { + kind, _ := detectWithError(r, size, name) + return kind +} + +func detectWithError(r io.ReaderAt, size int64, name string) (Kind, error) { + var header [8]byte + n, err := r.ReadAt(header[:], 0) + if err != nil && err != io.EOF && err != io.ErrUnexpectedEOF { + return Unknown, err + } + head := header[:n] + switch DetectMagic(head) { + case DEX: + return DEX, nil + case Class: + return Class, nil + case JMOD: + return JMOD, nil + case JIMAGE: + return JIMAGE, nil + case ZIP: + return detectZIP(r, size, name) + default: + return kindFromExtension(name), nil + } +} + +func detectZIP(r io.ReaderAt, size int64, name string) (Kind, error) { + reader, err := zip.NewReader(r, size) + if err != nil { + return kindFromExtension(name), nil + } + + var hasRootDEX, hasAABDEX, hasNestedAPK, hasClass, hasManifest bool + var hasWAR, hasEAR, hasAndroidManifest, hasClassesJAR bool + var hasTOC, hasManifestJSON, hasInfoJSON, hasBundleConfig bool + + for _, file := range reader.File { + entry := cleanEntryName(file.Name) + lower := strings.ToLower(entry) + if lower == "" { + continue + } + if _, ok := RootDEXIndex(entry); ok { + hasRootDEX = true + } + if _, _, ok := AABDEX(entry); ok { + hasAABDEX = true + } + if !file.FileInfo().IsDir() && strings.HasSuffix(lower, ".apk") { + hasNestedAPK = true + } + if strings.HasSuffix(lower, ".class") { + hasClass = true + } + switch lower { + case "meta-inf/manifest.mf": + hasManifest = true + case "web-inf/web.xml": + hasWAR = true + case "meta-inf/application.xml": + hasEAR = true + case "androidmanifest.xml": + hasAndroidManifest = true + case "classes.jar": + hasClassesJAR = true + case "toc.pb": + hasTOC = true + case "manifest.json": + hasManifestJSON = true + case "info.json": + hasInfoJSON = true + case "bundleconfig.pb": + hasBundleConfig = true + } + if strings.HasPrefix(lower, "web-inf/classes/") || + strings.HasPrefix(lower, "web-inf/lib/") || + strings.HasPrefix(lower, "web-inf/") { + hasWAR = true + } + if strings.HasPrefix(lower, "ear/lib/") { + hasEAR = true + } + } + + ext := strings.ToLower(filepath.Ext(name)) + switch { + case hasRootDEX: + return APK, nil + case hasAABDEX, hasBundleConfig && ext == ".aab": + return AAB, nil + case hasNestedAPK && !hasClass: + switch { + case hasManifestJSON: + return XAPK, nil + case hasInfoJSON: + return APKM, nil + case hasTOC: + return APKS, nil + } + switch ext { + case ".xapk", ".apkx": + return XAPK, nil + case ".apkm": + return APKM, nil + case ".apks": + return APKS, nil + } + return APKS, nil + case hasWAR: + return WAR, nil + case hasEAR: + return EAR, nil + case hasAndroidManifest && hasClassesJAR: + return AAR, nil + case hasManifest || hasClass: + return JAR, nil + default: + if kind := kindFromExtension(name); kind != Unknown { + return kind, nil + } + return ZIP, nil + } +} + +// RootDEXIndex reports the canonical multidex index of a root-level +// classes*.dex entry. Non-canonical names are rejected. +func RootDEXIndex(name string) (int, bool) { + entry := cleanEntryName(name) + match := rootDEXPattern.FindStringSubmatch(entry) + if match == nil { + return 0, false + } + return multidexIndex(match[1]) +} + +// AABDEX reports the module name and canonical multidex index of a +// /dex/classes*.dex entry. +func AABDEX(name string) (module string, index int, ok bool) { + entry := cleanEntryName(name) + match := aabDEXPattern.FindStringSubmatch(entry) + if match == nil { + return "", 0, false + } + index, ok = multidexIndex(match[2]) + if !ok { + return "", 0, false + } + return match[1], index, true +} + +func multidexIndex(digits string) (int, bool) { + if digits == "" { + return 1, true + } + if digits[0] == '0' { + return 0, false + } + index, err := strconv.Atoi(digits) + if err != nil || index < 2 { + return 0, false + } + return index, true +} + +func kindFromExtension(name string) Kind { + switch strings.ToLower(filepath.Ext(name)) { + case ".class": + return Class + case ".dex": + return DEX + case ".jmod": + return JMOD + case ".jimage": + return JIMAGE + case ".jar": + return JAR + case ".war": + return WAR + case ".ear": + return EAR + case ".aar": + return AAR + case ".par": + return PAR + case ".apk": + return APK + case ".apks": + return APKS + case ".xapk", ".apkx": + return XAPK + case ".apkm": + return APKM + case ".aab": + return AAB + case ".zip": + return ZIP + default: + return Unknown + } +} + +func cleanEntryName(name string) string { + name = strings.ReplaceAll(name, "\\", "/") + name = strings.TrimPrefix(name, "./") + name = path.Clean(name) + if name == "." { + return "" + } + return name +} + +func hasDEXMagic(data []byte) bool { + return len(data) >= 8 && string(data[:4]) == "dex\n" && data[7] == 0 && + data[4] >= '0' && data[4] <= '9' && + data[5] >= '0' && data[5] <= '9' && + data[6] >= '0' && data[6] <= '9' +} + +func hasZIPMagic(data []byte) bool { + return len(data) >= 4 && data[0] == 'P' && data[1] == 'K' && + ((data[2] == 3 && data[3] == 4) || + (data[2] == 5 && data[3] == 6) || + (data[2] == 7 && data[3] == 8)) +} + +func hasClassMagic(data []byte) bool { + return len(data) >= 4 && + data[0] == 0xca && data[1] == 0xfe && data[2] == 0xba && data[3] == 0xbe +} diff --git a/internal/inputkind/inputkind_test.go b/internal/inputkind/inputkind_test.go new file mode 100644 index 00000000..d441d266 --- /dev/null +++ b/internal/inputkind/inputkind_test.go @@ -0,0 +1,153 @@ +package inputkind + +import ( + "archive/zip" + "bytes" + "os" + "path/filepath" + "testing" + + "github.com/yaklang/javajive/internal/jimagefixture" +) + +func testZIP(t *testing.T, files map[string][]byte) []byte { + t.Helper() + var buffer bytes.Buffer + writer := zip.NewWriter(&buffer) + for name, body := range files { + file, err := writer.Create(name) + if err != nil { + t.Fatalf("create %s: %v", name, err) + } + if _, err := file.Write(body); err != nil { + t.Fatalf("write %s: %v", name, err) + } + } + if err := writer.Close(); err != nil { + t.Fatalf("close zip: %v", err) + } + return buffer.Bytes() +} + +func TestDetectBytes(t *testing.T) { + emptyZIP := testZIP(t, nil) + nestedAPK := testZIP(t, map[string][]byte{"classes.dex": []byte("dex\n035\x00")}) + jimageData, err := jimagefixture.Build([]jimagefixture.Entry{ + {Path: "/test/demo/Foo.class", Data: []byte{0xca, 0xfe, 0xba, 0xbe}}, + }) + if err != nil { + t.Fatalf("build JImage: %v", err) + } + cases := []struct { + name string + data []byte + file string + want Kind + }{ + {"dex", []byte("dex\n035\x00"), "renamed.bin", DEX}, + {"class", []byte{0xca, 0xfe, 0xba, 0xbe}, "renamed.bin", Class}, + {"jmod", append([]byte{'J', 'M', 1, 0}, emptyZIP...), "java.base.jmod", JMOD}, + {"jimage", jimageData, "modules", JIMAGE}, + {"jimage-extension", nil, "modules.jimage", JIMAGE}, + {"apk", testZIP(t, map[string][]byte{"classes.dex": []byte("dex\n035\x00")}), "renamed.zip", APK}, + {"apks", testZIP(t, map[string][]byte{"base.apk": nestedAPK}), "renamed.bin", APKS}, + {"apks-toc", testZIP(t, map[string][]byte{"toc.pb": {1}, "base-master.apk": nestedAPK}), "renamed.bin", APKS}, + {"xapk", testZIP(t, map[string][]byte{"manifest.json": {1}, "base.apk": nestedAPK}), "renamed.bin", XAPK}, + {"apkm", testZIP(t, map[string][]byte{"info.json": {1}, "base.apk": nestedAPK}), "renamed.bin", APKM}, + {"aab", testZIP(t, map[string][]byte{"base/dex/classes.dex": []byte("dex\n035\x00")}), "renamed.bin", AAB}, + {"war", testZIP(t, map[string][]byte{"WEB-INF/classes/demo/Foo.class": {0xca, 0xfe, 0xba, 0xbe}}), "renamed.bin", WAR}, + {"ear", testZIP(t, map[string][]byte{"EAR/lib/dep.jar": {0x50, 0x4b, 3, 4}}), "renamed.bin", EAR}, + {"aar", testZIP(t, map[string][]byte{"AndroidManifest.xml": {1}, "classes.jar": {0x50, 0x4b, 3, 4}}), "renamed.bin", AAR}, + {"jar", testZIP(t, map[string][]byte{"META-INF/MANIFEST.MF": []byte("Manifest-Version: 1.0\r\n\r\n")}), "renamed.bin", JAR}, + {"par", emptyZIP, "plugin.par", PAR}, + {"zip", emptyZIP, "data.zip", ZIP}, + {"unknown-text", []byte("not an artifact"), "notes.txt", Unknown}, + {"generic-zip-unknown-extension", emptyZIP, "payload.bin", ZIP}, + {"jmod-extension-fallback", emptyZIP, "module.jmod", JMOD}, + {"apkx-extension-fallback", testZIP(t, map[string][]byte{"base.apk": nestedAPK}), "bundle.apkx", XAPK}, + } + for _, test := range cases { + t.Run(test.name, func(t *testing.T) { + if got := DetectBytes(test.data, test.file); got != test.want { + t.Fatalf("DetectBytes = %q, want %q", got, test.want) + } + }) + } +} + +func TestDetectFile(t *testing.T) { + jmod := append([]byte{'J', 'M', 1, 0}, testZIP(t, map[string][]byte{"classes/demo/Foo.class": {0xca, 0xfe, 0xba, 0xbe}})...) + path := filepath.Join(t.TempDir(), "java.base.jmod") + if err := os.WriteFile(path, jmod, 0o644); err != nil { + t.Fatal(err) + } + kind, err := DetectFile(path) + if err != nil { + t.Fatalf("DetectFile: %v", err) + } + if kind != JMOD { + t.Fatalf("DetectFile = %q, want jmod", kind) + } +} + +func TestRootDEXIndex(t *testing.T) { + cases := []struct { + name string + wantIndex int + wantOK bool + }{ + {"classes.dex", 1, true}, + {"classes2.dex", 2, true}, + {"classes10.dex", 10, true}, + {"classes0.dex", 0, false}, + {"classes1.dex", 0, false}, + {"classes01.dex", 0, false}, + {"assets/classes.dex", 0, false}, + } + for _, test := range cases { + t.Run(test.name, func(t *testing.T) { + index, ok := RootDEXIndex(test.name) + if index != test.wantIndex || ok != test.wantOK { + t.Fatalf("RootDEXIndex = (%d, %v), want (%d, %v)", index, ok, test.wantIndex, test.wantOK) + } + }) + } +} + +func TestAABDEX(t *testing.T) { + cases := []struct { + name string + wantModule string + wantIndex int + wantOK bool + }{ + {"base/dex/classes.dex", "base", 1, true}, + {"feature/dex/classes2.dex", "feature", 2, true}, + {"base/dex/classes01.dex", "", 0, false}, + {"base/classes.dex", "", 0, false}, + } + for _, test := range cases { + t.Run(test.name, func(t *testing.T) { + module, index, ok := AABDEX(test.name) + if module != test.wantModule || index != test.wantIndex || ok != test.wantOK { + t.Fatalf("AABDEX = (%q, %d, %v), want (%q, %d, %v)", module, index, ok, test.wantModule, test.wantIndex, test.wantOK) + } + }) + } +} + +func TestKindGroups(t *testing.T) { + for _, kind := range []Kind{APK, APKS, XAPK, APKM, AAB} { + if !IsAndroid(kind) { + t.Fatalf("IsAndroid(%q) = false", kind) + } + } + for _, kind := range []Kind{JMOD, JIMAGE, JAR, WAR, EAR, AAR, PAR, ZIP} { + if !IsJavaArchive(kind) { + t.Fatalf("IsJavaArchive(%q) = false", kind) + } + } + if IsAndroid(JAR) || IsJavaArchive(APK) { + t.Fatal("container groups overlap") + } +} diff --git a/internal/jdecenv/env.go b/internal/jdecenv/env.go index 947b51b5..62b4b68f 100644 --- a/internal/jdecenv/env.go +++ b/internal/jdecenv/env.go @@ -18,11 +18,88 @@ import ( "sync/atomic" ) -type stack []map[string]string +type envFrame struct { + snap map[string]string + // keys are the JDEC_* entries this snapshot overrides. They are extracted + // once on push so Get can answer the common "no override active" case + // without parsing the goroutine stack. + keys []string +} + +type stack []envFrame var byGid sync.Map // uint64 -> stack var liveBinds int32 +// activeKeys is the union of JDEC_* keys present in every live snapshot. When +// a queried key is absent from this set and the process environment has no +// value for it, every possible frame (closed snapshot, live sentinel, or no +// bind) returns the empty string, so Get can skip gid()/runtime.Stack. +// +// Updates happen only on Run/EnterLive push/pop, not on each Get. The map is +// published copy-on-write under activeMu and read lock-free via atomic.Value. +var activeMu sync.Mutex +var activeKeySet atomic.Value // map[string]struct{} + +func init() { + activeKeySet.Store(map[string]struct{}{}) +} + +func jdecKeys(snap map[string]string) []string { + if len(snap) == 0 { + return nil + } + var keys []string + for key := range snap { + if strings.HasPrefix(key, "JDEC_") { + keys = append(keys, key) + } + } + return keys +} + +func addActiveKeys(keys []string) { + if len(keys) == 0 { + return + } + activeMu.Lock() + defer activeMu.Unlock() + set := activeKeySet.Load().(map[string]struct{}) + next := make(map[string]struct{}, len(set)+len(keys)) + for key := range set { + next[key] = struct{}{} + } + for _, key := range keys { + next[key] = struct{}{} + } + activeKeySet.Store(next) +} + +// refreshActiveKeys recomputes the union of override keys from the live stacks +// after a pop. Pops happen at request boundaries, and the number of frames and +// override keys is small, so an exact rebuild is cheaper and simpler than +// refcounting keys across nested frames. +func refreshActiveKeys() { + activeMu.Lock() + defer activeMu.Unlock() + surviving := map[string]struct{}{} + byGid.Range(func(_, value any) bool { + for _, frame := range value.(stack) { + for _, key := range frame.keys { + surviving[key] = struct{}{} + } + } + return true + }) + activeKeySet.Store(surviving) +} + +func activeKey(key string) bool { + set := activeKeySet.Load().(map[string]struct{}) + _, ok := set[key] + return ok +} + func hasBind() bool { return atomic.LoadInt32(&liveBinds) != 0 } // Run pushes snap for this goroutine, runs fn, then pops (panic-safe). @@ -69,7 +146,7 @@ func Current() (map[string]string, bool) { if len(st) == 0 { return nil, false } - return st[len(st)-1], true + return st[len(st)-1].snap, true } // Get returns the innermost snapshot value. Missing keys are unset (closed). @@ -79,6 +156,14 @@ func Get(key string) string { if !hasBind() { return os.Getenv(key) } + // Fast path for the overwhelmingly common case: no active snapshot + // overrides this key and the process environment does not define it. + // Every possible frame (closed snapshot, live sentinel, or no binding) + // then yields "", so gid()/runtime.Stack parsing is unnecessary. A key + // that IS overridden still takes the full goroutine-local path. + if strings.HasPrefix(key, "JDEC_") && !activeKey(key) && os.Getenv(key) == "" { + return "" + } if snap, ok := Current(); ok { if snap == nil { return os.Getenv(key) @@ -145,9 +230,11 @@ func push(id uint64, snap map[string]string) { } n := make(stack, len(st)+1) copy(n, st) - n[len(st)] = snap + frame := envFrame{snap: snap, keys: jdecKeys(snap)} + n[len(st)] = frame byGid.Store(id, n) atomic.AddInt32(&liveBinds, 1) + addActiveKeys(frame.keys) } func pop(id uint64) { @@ -156,15 +243,18 @@ func pop(id uint64) { return } st := v.(stack) + frame := st[len(st)-1] if len(st) <= 1 { byGid.Delete(id) - atomic.AddInt32(&liveBinds, -1) - return + } else { + n := make(stack, len(st)-1) + copy(n, st[:len(st)-1]) + byGid.Store(id, n) } - n := make(stack, len(st)-1) - copy(n, st[:len(st)-1]) - byGid.Store(id, n) atomic.AddInt32(&liveBinds, -1) + if len(frame.keys) > 0 { + refreshActiveKeys() + } } func gidFromStack() uint64 { diff --git a/internal/jdecenv/env_test.go b/internal/jdecenv/env_test.go index 092e4317..db4f5d46 100644 --- a/internal/jdecenv/env_test.go +++ b/internal/jdecenv/env_test.go @@ -184,6 +184,90 @@ func TestUnboundGetDoesNotRequireBind(t *testing.T) { } } +func TestGetFastPathPreservesClosedAndLiveSemantics(t *testing.T) { + const key = "JDEC_FASTPATH_SEMANTICS" + t.Setenv(key, "host") + + // A bound snapshot that does not override the key is closed. + if err := Run(map[string]string{}, func() error { + if got := Get(key); got != "" { + t.Fatalf("closed snapshot leaked host value %q", got) + } + return nil + }); err != nil { + t.Fatal(err) + } + + // A snapshot that does override it wins. + if err := Run(map[string]string{key: "snapshot"}, func() error { + if got := Get(key); got != "snapshot" { + t.Fatalf("snapshot value = %q", got) + } + return nil + }); err != nil { + t.Fatal(err) + } + + // A live sentinel reads the process environment. + if err := RunLive(func() error { + if got := Get(key); got != "host" { + t.Fatalf("live sentinel = %q, want host", got) + } + return nil + }); err != nil { + t.Fatal(err) + } + + // Nested snapshots must restore the outer closed/live choice. + if err := Run(map[string]string{key: "outer"}, func() error { + if err := Run(map[string]string{}, func() error { + if got := Get(key); got != "" { + t.Fatalf("inner closed snapshot = %q", got) + } + return nil + }); err != nil { + return err + } + if got := Get(key); got != "outer" { + t.Fatalf("outer snapshot was not restored: %q", got) + } + return nil + }); err != nil { + t.Fatal(err) + } +} + +var benchmarkGetSink string + +func BenchmarkGetWithoutActiveOverride(b *testing.B) { + const key = "JDEC_BENCH_ABSENT_KEY" + b.Setenv(key, "") + if err := Run(map[string]string{"PATH": "/usr/bin"}, func() error { + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + benchmarkGetSink = Get(key) + } + return nil + }); err != nil { + b.Fatal(err) + } +} + +func BenchmarkGetWithActiveOverride(b *testing.B) { + const key = "JDEC_BENCH_OVERRIDE_KEY" + if err := Run(map[string]string{key: "1"}, func() error { + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + benchmarkGetSink = Get(key) + } + return nil + }); err != nil { + b.Fatal(err) + } +} + func TestNilRunDoesNotPush(t *testing.T) { t.Setenv("JDEC_NESTED", "host") _ = Run(map[string]string{"JDEC_NESTED": "outer"}, func() error { diff --git a/internal/jdecenv/goid_arm64.go b/internal/jdecenv/goid_arm64.go new file mode 100644 index 00000000..2c8f55e7 --- /dev/null +++ b/internal/jdecenv/goid_arm64.go @@ -0,0 +1,7 @@ +//go:build arm64 + +package jdecenv + +import "unsafe" + +func currentG() unsafe.Pointer diff --git a/internal/jdecenv/goid_arm64.s b/internal/jdecenv/goid_arm64.s new file mode 100644 index 00000000..c09d2e17 --- /dev/null +++ b/internal/jdecenv/goid_arm64.s @@ -0,0 +1,13 @@ +#include "textflag.h" + +// func currentG() unsafe.Pointer +// +// On arm64 the runtime keeps the current goroutine pointer in the dedicated g +// register (R28). Reading it here avoids formatting the whole goroutine stack +// through runtime.Stack on every call; the returned pointer is a stable, +// unique identity for the lifetime of the goroutine, exactly like the amd64 +// implementation. +TEXT ·currentG(SB),NOSPLIT,$0-8 + MOVD g, R0 + MOVD R0, ret+0(FP) + RET diff --git a/internal/jdecenv/goid_other.go b/internal/jdecenv/goid_other.go index c07ff352..b4b1c29b 100644 --- a/internal/jdecenv/goid_other.go +++ b/internal/jdecenv/goid_other.go @@ -1,4 +1,4 @@ -//go:build !amd64 +//go:build !amd64 && !arm64 package jdecenv diff --git a/internal/jimagefixture/fixture.go b/internal/jimagefixture/fixture.go new file mode 100644 index 00000000..151e0b5c --- /dev/null +++ b/internal/jimagefixture/fixture.go @@ -0,0 +1,217 @@ +// Package jimagefixture builds small synthetic JImage files for tests. +package jimagefixture + +import ( + "bytes" + "compress/zlib" + "encoding/binary" + "fmt" + "strings" +) + +const ( + imageMagic = 0xCAFEDADA + resourceHeaderMagic = 0xCAFEFAFA + headerSize = 28 + resourceHeaderSize = 29 + + attributeModule = 1 + attributeParent = 2 + attributeBase = 3 + attributeExtension = 4 + attributeOffset = 5 + attributeCompressed = 6 + attributeUncompressed = 7 +) + +// Entry describes one resource in a synthetic JImage. Path must start with +// "//...". When Compressed is true, Compressor defaults to "zip"; +// "compact-cp" produces a structurally valid unsupported resource. +type Entry struct { + Path string + Data []byte + Compressed bool + Compressor string +} + +type parsedEntry struct { + module string + parent string + base string + extension string + data []byte + compressed bool + compressor string +} + +// Build returns a little-endian JImage containing entries. +func Build(entries []Entry) ([]byte, error) { + parsed := make([]parsedEntry, 0, len(entries)) + for _, entry := range entries { + module, parent, base, extension, err := parsePath(entry.Path) + if err != nil { + return nil, err + } + compressor := entry.Compressor + if entry.Compressed && compressor == "" { + compressor = "zip" + } + if !entry.Compressed { + compressor = "" + } + parsed = append(parsed, parsedEntry{ + module: module, parent: parent, base: base, extension: extension, + data: entry.Data, compressed: entry.Compressed, compressor: compressor, + }) + } + + stringsData := []byte{0} + stringOffsets := map[string]uint32{"": 0} + addString := func(value string) uint32 { + if value == "" { + return 0 + } + if offset, ok := stringOffsets[value]; ok { + return offset + } + offset := uint32(len(stringsData)) + stringsData = append(stringsData, value...) + stringsData = append(stringsData, 0) + stringOffsets[value] = offset + return offset + } + for _, entry := range parsed { + addString(entry.module) + addString(entry.parent) + addString(entry.base) + addString(entry.extension) + if entry.compressed { + addString(entry.compressor) + } + } + + locations := []byte{0} + offsetsTable := make([]uint32, len(parsed)) + resourceData := make([]byte, 0) + for index, entry := range parsed { + payload := entry.data + compressedSize := uint64(0) + if entry.compressed { + compressed, err := compressResource(entry.data, entry.compressor, addString) + if err != nil { + return nil, err + } + payload = compressed + compressedSize = uint64(len(compressed)) + } + + attributes := make([]byte, 0, 32) + attributes = appendAttribute(attributes, attributeModule, uint64(addString(entry.module))) + if entry.parent != "" { + attributes = appendAttribute(attributes, attributeParent, uint64(addString(entry.parent))) + } + attributes = appendAttribute(attributes, attributeBase, uint64(addString(entry.base))) + if entry.extension != "" { + attributes = appendAttribute(attributes, attributeExtension, uint64(addString(entry.extension))) + } + if len(resourceData) != 0 { + attributes = appendAttribute(attributes, attributeOffset, uint64(len(resourceData))) + } + if compressedSize != 0 { + attributes = appendAttribute(attributes, attributeCompressed, compressedSize) + } + attributes = appendAttribute(attributes, attributeUncompressed, uint64(len(entry.data))) + attributes = append(attributes, 0) + + offsetsTable[index] = uint32(len(locations)) + locations = append(locations, attributes...) + resourceData = append(resourceData, payload...) + } + + tableLength := len(parsed) + header := make([]byte, headerSize) + binary.LittleEndian.PutUint32(header[0:4], imageMagic) + binary.LittleEndian.PutUint32(header[4:8], 0x00010001) + binary.LittleEndian.PutUint32(header[8:12], 0) + binary.LittleEndian.PutUint32(header[12:16], uint32(len(parsed))) + binary.LittleEndian.PutUint32(header[16:20], uint32(tableLength)) + binary.LittleEndian.PutUint32(header[20:24], uint32(len(locations))) + binary.LittleEndian.PutUint32(header[24:28], uint32(len(stringsData))) + + redirects := make([]byte, tableLength*4) + offsetBytes := make([]byte, tableLength*4) + for index, offset := range offsetsTable { + binary.LittleEndian.PutUint32(offsetBytes[index*4:], offset) + } + + result := make([]byte, 0, headerSize+len(redirects)+len(offsetBytes)+len(locations)+len(stringsData)+len(resourceData)) + result = append(result, header...) + result = append(result, redirects...) + result = append(result, offsetBytes...) + result = append(result, locations...) + result = append(result, stringsData...) + result = append(result, resourceData...) + return result, nil +} + +func compressResource(data []byte, compressor string, addString func(string) uint32) ([]byte, error) { + var payload []byte + if compressor == "zip" { + var buffer bytes.Buffer + writer := zlib.NewWriter(&buffer) + if _, err := writer.Write(data); err != nil { + return nil, err + } + if err := writer.Close(); err != nil { + return nil, err + } + payload = buffer.Bytes() + } else { + // The reader rejects unsupported compressors before reading the + // payload, so a placeholder keeps the resource structurally valid. + payload = []byte{0} + } + + header := make([]byte, resourceHeaderSize) + binary.LittleEndian.PutUint32(header[0:4], resourceHeaderMagic) + binary.LittleEndian.PutUint64(header[4:12], uint64(len(payload))) + binary.LittleEndian.PutUint64(header[12:20], uint64(len(data))) + binary.LittleEndian.PutUint32(header[20:24], addString(compressor)) + binary.LittleEndian.PutUint32(header[24:28], 0) + header[28] = 1 + return append(header, payload...), nil +} + +func appendAttribute(destination []byte, kind byte, value uint64) []byte { + length := 1 + for shifted := value >> 8; shifted != 0; shifted >>= 8 { + length++ + } + destination = append(destination, kind<<3|byte(length-1)) + for shift := (length - 1) * 8; shift >= 0; shift -= 8 { + destination = append(destination, byte(value>>uint(shift))) + } + return destination +} + +func parsePath(value string) (module, parent, base, extension string, err error) { + if !strings.HasPrefix(value, "/") { + return "", "", "", "", fmt.Errorf("jimage fixture: path %q must start with /", value) + } + parts := strings.Split(strings.TrimPrefix(value, "/"), "/") + if len(parts) < 2 || parts[0] == "" { + return "", "", "", "", fmt.Errorf("jimage fixture: path %q needs a module and a file name", value) + } + last := parts[len(parts)-1] + if last == "" { + return "", "", "", "", fmt.Errorf("jimage fixture: path %q has an empty file name", value) + } + base = last + if dot := strings.LastIndex(last, "."); dot >= 0 { + base = last[:dot] + extension = last[dot+1:] + } + module = parts[0] + parent = strings.Join(parts[1:len(parts)-1], "/") + return module, parent, base, extension, nil +} diff --git a/internal/omap/ordered.go b/internal/omap/ordered.go index 502abfee..7cf81c01 100644 --- a/internal/omap/ordered.go +++ b/internal/omap/ordered.go @@ -608,6 +608,23 @@ func (o *OrderedMap[T, V]) Map(f func(T, V) (T, V, error)) *OrderedMap[T, V] { return r } +// ForEachReadOnly iterates in insertion order without copying the key/value +// snapshot. The handler must not mutate o or call a method that takes its +// write lock. Read-only analysis loops use this to avoid a per-call allocation. +func (o *OrderedMap[T, V]) ForEachReadOnly(handler func(i T, v V) bool) { + if o == nil { + return + } + o.init() + o.lock.RLock() + defer o.lock.RUnlock() + for _, key := range o.keyChain { + if !handler(key, o.m[key]) { + return + } + } +} + func (o *OrderedMap[T, V]) ForEach(handler func(i T, v V) bool) { if o == nil { return diff --git a/internal/testfixtures/testfixtures.go b/internal/testfixtures/testfixtures.go new file mode 100644 index 00000000..3fda1f48 --- /dev/null +++ b/internal/testfixtures/testfixtures.go @@ -0,0 +1,33 @@ +// Package testfixtures locates the shared external container samples under +// testdata/external. Tests in any package can use it without hard-coding a +// relative path depth. +package testfixtures + +import ( + "os" + "path/filepath" +) + +// Dir returns the absolute path of testdata/external. +func Dir() string { + if workingDir, err := os.Getwd(); err == nil { + dir := workingDir + for { + if _, err := os.Stat(filepath.Join(dir, "go.mod")); err == nil { + return filepath.Join(dir, "testdata", "external") + } + parent := filepath.Dir(dir) + if parent == dir { + break + } + dir = parent + } + } + // Fall back to the conventional location relative to the test process. + return filepath.Join("testdata", "external") +} + +// Path returns one external sample by name. +func Path(name string) string { + return filepath.Join(Dir(), name) +} diff --git a/internal/utils/threadsafe-set.go b/internal/utils/threadsafe-set.go index 92d411d7..c8d96f18 100644 --- a/internal/utils/threadsafe-set.go +++ b/internal/utils/threadsafe-set.go @@ -19,6 +19,24 @@ func NewSet[T comparable](list ...[]T) *Set[T] { return s } +// NewSetFromMap takes ownership of m. It lets a caller build a set with a +// plain map (no per-element locking) and publish it as a Set afterwards. The +// caller must not retain or mutate m after the call. +func NewSetFromMap[T comparable](m map[T]struct{}) *Set[T] { + if m == nil { + m = make(map[T]struct{}) + } + return &Set[T]{m: m} +} + +// NewSetSized allocates a set whose backing map is sized for n elements. +func NewSetSized[T comparable](n int) *Set[T] { + if n < 0 { + n = 0 + } + return &Set[T]{m: make(map[T]struct{}, n)} +} + //func main() { // // Initialize our Set // s := New() @@ -63,6 +81,33 @@ func (s *Set[T]) AddList(items []T) { } } +// CloneWithList copies the set under a single read lock and returns the copied +// elements. It is cheaper than NewSetSized plus Add because it does not take a +// write lock per element. +func (s *Set[T]) CloneWithList() (*Set[T], []T) { + s.RLock() + defer s.RUnlock() + dst := make(map[T]struct{}, len(s.m)) + list := make([]T, 0, len(s.m)) + for item := range s.m { + dst[item] = struct{}{} + list = append(list, item) + } + return &Set[T]{m: dst}, list +} + +// ContainsAll reports whether every item is present, taking one read lock. +func (s *Set[T]) ContainsAll(items []T) bool { + s.RLock() + defer s.RUnlock() + for _, item := range items { + if _, ok := s.m[item]; !ok { + return false + } + } + return true +} + // Remove deletes the specified item from the map func (s *Set[T]) Remove(item T) { s.Lock() @@ -83,6 +128,13 @@ func (s *Set[T]) Len() int { return len(s.List()) } +// Size returns the number of items without materializing a list. +func (s *Set[T]) Size() int { + s.RLock() + defer s.RUnlock() + return len(s.m) +} + // Clear removes all items from the set func (s *Set[T]) Clear() { s.Lock() @@ -110,6 +162,9 @@ func (s *Set[T]) List() []T { } func (s *Set[T]) ForEach(h func(T)) { + if s == nil { + return + } s.RLock() defer s.RUnlock() for item := range s.m { @@ -117,6 +172,21 @@ func (s *Set[T]) ForEach(h func(T)) { } } +// ForEachWhile iterates until the handler returns false. It avoids the +// allocation of List for callers that only scan or stop at the first match. +func (s *Set[T]) ForEachWhile(h func(T) bool) { + if s == nil { + return + } + s.RLock() + defer s.RUnlock() + for item := range s.m { + if !h(item) { + return + } + } +} + func (s *Set[T]) Diff(other *Set[T]) *Set[T] { s.RLock() other.RLock() diff --git a/internal/utils/word_scan.go b/internal/utils/word_scan.go new file mode 100644 index 00000000..cb3acef6 --- /dev/null +++ b/internal/utils/word_scan.go @@ -0,0 +1,102 @@ +package utils + +import "strings" + +// asciiWordByte reports whether c belongs to Go regexp's ASCII \w class. It is +// also the character class Java local names are made of, so a literal word +// match over these bytes reproduces `\b`+QuoteMeta(name)+`\b` exactly. +func asciiWordByte(c byte) bool { + return c == '_' || c >= '0' && c <= '9' || c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' +} + +// wordBoundaryAt reports whether pos is a Go regexp word boundary: the start or +// end of text next to a word byte, or a transition between word and non-word. +func wordBoundaryAt(text string, pos int) bool { + if pos <= 0 { + return pos == 0 && len(text) > 0 && asciiWordByte(text[0]) + } + if pos >= len(text) { + return pos == len(text) && asciiWordByte(text[len(text)-1]) + } + return asciiWordByte(text[pos-1]) != asciiWordByte(text[pos]) +} + +// nextWordSpan returns the earliest whole-word occurrence of word at or after +// offset, or (-1, -1) when there is none. +func nextWordSpan(text, word string, offset int) (int, int) { + for offset+len(word) <= len(text) { + rel := strings.Index(text[offset:], word) + if rel < 0 { + return -1, -1 + } + start := offset + rel + end := start + len(word) + if wordBoundaryAt(text, start) && wordBoundaryAt(text, end) { + return start, end + } + offset = start + 1 + } + return -1, -1 +} + +// wordBoundaries appends every zero-width word-boundary position. It matches +// FindAllStringIndex for the degenerate pattern `\b\b`, which is what an empty +// name compiles to. +func wordBoundaries(text string, dst [][2]int) [][2]int { + if len(text) == 0 { + return dst + } + for pos := 0; pos <= len(text); pos++ { + if wordBoundaryAt(text, pos) { + dst = append(dst, [2]int{pos, pos}) + } + } + return dst +} + +// WordMatches reports whether text contains word as a whole token, matching +// `\b`+QuoteMeta(word)+`\b`. +func WordMatches(text, word string) bool { + if word == "" { + return len(wordBoundaries(text, nil)) > 0 + } + start, _ := nextWordSpan(text, word, 0) + return start >= 0 +} + +// WordCount counts non-overlapping whole-token occurrences of word in text, +// matching regexp.FindAllString(..., -1) on `\b`+QuoteMeta(word)+`\b`. +func WordCount(text, word string) int { + if word == "" { + return len(wordBoundaries(text, nil)) + } + count := 0 + for offset := 0; offset+len(word) <= len(text); { + start, end := nextWordSpan(text, word, offset) + if start < 0 { + break + } + count++ + offset = end + } + return count +} + +// WordSpans appends the byte ranges of non-overlapping whole-token occurrences +// of word to dst, matching FindAllStringIndex on `\b`+QuoteMeta(word)+`\b`. +// Passing a nil dst still saves the caller the regexp compile on the common +// no-match path. +func WordSpans(text, word string, dst [][2]int) [][2]int { + if word == "" { + return wordBoundaries(text, dst) + } + for offset := 0; offset+len(word) <= len(text); { + start, end := nextWordSpan(text, word, offset) + if start < 0 { + break + } + dst = append(dst, [2]int{start, end}) + offset = end + } + return dst +} diff --git a/internal/utils/word_scan_test.go b/internal/utils/word_scan_test.go new file mode 100644 index 00000000..97f907a5 --- /dev/null +++ b/internal/utils/word_scan_test.go @@ -0,0 +1,43 @@ +package utils + +import ( + "math/rand" + "regexp" + "testing" +) + +// TestWordScanMatchesRegexpSemantics pins the literal scanner to Go regexp's +// \b semantics for every name shape the decompiler passes, including $, digits +// and the degenerate empty name (`\b\b`). +func TestWordScanMatchesRegexpSemantics(t *testing.T) { + r := rand.New(rand.NewSource(7)) + alphabet := []byte("abAB01_$ .()=;:<>") + names := []string{"", "a", "ab", "var1", "var1_2", "$foo", "a$", "_x", "0", "A1_$"} + for _, name := range names { + re := regexp.MustCompile(`\b` + regexp.QuoteMeta(name) + `\b`) + for iter := 0; iter < 2000; iter++ { + n := r.Intn(40) + buf := make([]byte, n) + for i := range buf { + buf[i] = alphabet[r.Intn(len(alphabet))] + } + text := string(buf) + want := re.FindAllStringIndex(text, -1) + got := WordSpans(text, name, nil) + if len(got) != len(want) { + t.Fatalf("spans %q in %q: got %v want %v", name, text, got, want) + } + for i := range got { + if got[i][0] != want[i][0] || got[i][1] != want[i][1] { + t.Fatalf("spans %q in %q: got %v want %v", name, text, got, want) + } + } + if WordMatches(text, name) != re.MatchString(text) { + t.Fatalf("match %q in %q: got %v want %v", name, text, WordMatches(text, name), re.MatchString(text)) + } + if WordCount(text, name) != len(want) { + t.Fatalf("count %q in %q: got %d want %d", name, text, WordCount(text, name), len(want)) + } + } + } +} diff --git a/internal/zipx/reader.go b/internal/zipx/reader.go index 48a7c173..e9e16c7c 100644 --- a/internal/zipx/reader.go +++ b/internal/zipx/reader.go @@ -213,10 +213,10 @@ func (r *checksumReader) Read(b []byte) (n int, err error) { err = ErrChecksum } } else { - // If there's not a data descriptor, we still compare - // the CRC32 of what we've read against the file header - // or TOC's CRC32, if it seems like it was set. - if r.f.CRC32 != 0 && r.hash.Sum32() != r.f.CRC32 { + // If there's not a data descriptor, compare the CRC32 of + // what we've read against the central directory value. + if r.hash.Sum32() != r.f.CRC32 { + err = ErrChecksum } } @@ -303,8 +303,12 @@ func readDirectoryHeader(f *File, r io.Reader) error { f.headerOffset = int64(eb.uint64()) } case winzipAesExtraId: + if len(eb) < 7 { + return ErrFormat + } // grab the AE version f.ae = eb.uint16() + // skip vendor ID _ = eb.uint16() // AES strength diff --git a/internal/zipx/reader_test.go b/internal/zipx/reader_test.go new file mode 100644 index 00000000..8dc4625b --- /dev/null +++ b/internal/zipx/reader_test.go @@ -0,0 +1,82 @@ +package zip + +import ( + stdzip "archive/zip" + "bytes" + "errors" + "io" + "testing" +) + +func rawStoreZIP(t testing.TB, body, extra []byte, crc uint32) []byte { + t.Helper() + var buffer bytes.Buffer + writer := stdzip.NewWriter(&buffer) + header := &stdzip.FileHeader{ + Name: "test.txt", + Method: stdzip.Store, + CRC32: crc, + CompressedSize64: uint64(len(body)), + UncompressedSize64: uint64(len(body)), + Extra: extra, + } + entry, err := writer.CreateRaw(header) + if err != nil { + t.Fatalf("CreateRaw: %v", err) + } + if _, err := entry.Write(body); err != nil { + t.Fatalf("write body: %v", err) + } + if err := writer.Close(); err != nil { + t.Fatalf("close ZIP: %v", err) + } + return buffer.Bytes() +} + +func TestNewReaderRejectsShortWinZipAESExtra(t *testing.T) { + extra := []byte{0x01, 0x99, 0x01, 0x00, 0x02} + raw := rawStoreZIP(t, nil, extra, 0) + if _, err := NewReader(bytes.NewReader(raw), int64(len(raw))); !errors.Is(err, ErrFormat) { + t.Fatalf("NewReader error = %v, want ErrFormat", err) + } +} + +func TestOpenVerifiesZeroCRC(t *testing.T) { + raw := rawStoreZIP(t, []byte("x"), nil, 0) + reader, err := NewReader(bytes.NewReader(raw), int64(len(raw))) + if err != nil { + t.Fatalf("NewReader: %v", err) + } + stream, err := reader.File[0].Open() + if err != nil { + t.Fatalf("Open: %v", err) + } + _, err = io.ReadAll(stream) + _ = stream.Close() + if !errors.Is(err, ErrChecksum) { + t.Fatalf("ReadAll error = %v, want ErrChecksum", err) + } +} + +func FuzzNewReaderMalformed(f *testing.F) { + f.Add(rawStoreZIP(f, nil, []byte{0x01, 0x99, 0x01, 0x00, 0x02}, 0)) + f.Add(rawStoreZIP(f, []byte("x"), nil, 0)) + f.Add([]byte{}) + f.Fuzz(func(t *testing.T, data []byte) { + reader, err := NewReader(bytes.NewReader(data), int64(len(data))) + if err != nil { + return + } + for index, file := range reader.File { + if index >= 4 { + break + } + stream, err := file.Open() + if err != nil { + continue + } + _, _ = io.Copy(io.Discard, io.LimitReader(stream, 1<<20)) + _ = stream.Close() + } + }) +} diff --git a/javajive.go b/javajive.go index dd968d6b..ab2def9c 100644 --- a/javajive.go +++ b/javajive.go @@ -2,7 +2,11 @@ // pure-Go Java toolkit. It aggregates the three building blocks of the project // behind one small, stable API: // -// - Decompilation: turn .class bytes or .jar/.war/.zip archives into Java source. +// - Decompilation: turn .class bytes, Java archives (.jar/.war/.ear/.aar/ +// .par/.jmod/.zip), or JDK runtime images (.jimage / lib/modules) into Java +// source. +// - DEX translation: turn .dex/.apk/.apks/.xapk/.apkm/.aab input into a +// deterministic JAR or directly into Java source. // - Class parsing: inspect the structure of a .class file (constant pool, // fields, methods, version, access flags). // - Java serialization: parse and re-marshal the Java ObjectStream wire format, @@ -29,6 +33,7 @@ import ( classparser "github.com/yaklang/javajive/classparser" "github.com/yaklang/javajive/classparser/jarwar" nativedex "github.com/yaklang/javajive/dex2jar" + "github.com/yaklang/javajive/jimage" yserx "github.com/yaklang/javajive/serialization" ) @@ -45,12 +50,27 @@ type ClassObject = classparser.ClassObject // JavaSerializable is one node of a parsed Java serialization stream. type JavaSerializable = yserx.JavaSerializable -// DexOptions controls native DEX/APK translation. +// DexOptions controls native DEX and Android container translation. type DexOptions = nativedex.Options -// DexReport summarizes a successful native DEX/APK translation. +// DexReport summarizes a successful native DEX translation. type DexReport = nativedex.Report +// DexConvertOptions selects strict, recognized-method stubbing, or full class recovery. +type DexConvertOptions = nativedex.ConvertOptions + +// DexDetailedReport includes complete/partial status, recovery counters, and diagnostics. +type DexDetailedReport = nativedex.DetailedReport + +type DexConversionDiagnostic = nativedex.ConversionDiagnostic +type DexFailurePolicy = nativedex.FailurePolicy + +const ( + DexFailureStrict = nativedex.FailureStrict + DexFailureStubUnsupportedMethods = nativedex.FailureStubUnsupportedMethods + DexFailureRecover = nativedex.FailureRecover +) + // InputKind identifies reverse-toolchain input by content magic. type InputKind = nativedex.InputKind @@ -59,8 +79,116 @@ const ( InputClass = nativedex.InputClass InputDEX = nativedex.InputDEX InputZIP = nativedex.InputZIP + // InputJMOD identifies a JMOD archive ("JM\x01\x00" + ZIP). + InputJMOD = nativedex.InputJMOD + // InputJIMAGE identifies a JDK modular runtime image. + InputJIMAGE = nativedex.InputJIMAGE ) +// ContainerKind is the structure-aware classification of an input. It refines +// InputKind for ZIP containers (APK vs APKS vs JAR, and so on). +type ContainerKind = nativedex.ContainerKind + +const ( + ContainerUnknown = nativedex.ContainerUnknown + ContainerClass = nativedex.ContainerClass + ContainerDEX = nativedex.ContainerDEX + ContainerJMOD = nativedex.ContainerJMOD + ContainerJImage = nativedex.ContainerJImage + ContainerJAR = nativedex.ContainerJAR + ContainerWAR = nativedex.ContainerWAR + ContainerEAR = nativedex.ContainerEAR + ContainerAAR = nativedex.ContainerAAR + ContainerPAR = nativedex.ContainerPAR + ContainerZIP = nativedex.ContainerZIP + ContainerAPK = nativedex.ContainerAPK + ContainerAPKS = nativedex.ContainerAPKS + ContainerXAPK = nativedex.ContainerXAPK + ContainerAPKM = nativedex.ContainerAPKM + ContainerAAB = nativedex.ContainerAAB +) + +// ClassifyInput classifies data by magic, archive structure, and the supplied +// name's extension. +func ClassifyInput(data []byte, name string) ContainerKind { + return nativedex.ClassifyInput(data, name) +} + +// ClassifyInputFile classifies a file without loading the whole archive. +func ClassifyInputFile(name string) (ContainerKind, error) { + return nativedex.ClassifyInputFile(name) +} + +// IsAndroidContainer reports whether kind is translated by the DEX pipeline. +func IsAndroidContainer(kind ContainerKind) bool { + return nativedex.IsAndroidContainer(kind) +} + +// IsJavaArchiveContainer reports whether kind is exported by the Java archive +// decompiler. +func IsJavaArchiveContainer(kind ContainerKind) bool { + return nativedex.IsJavaArchiveContainer(kind) +} + +// JImageReader reads a JDK modular runtime image (lib/modules or .jimage). +type JImageReader = jimage.Reader + +// JImageEntry is one resource inside a JDK runtime image. +type JImageEntry = jimage.Entry + +// JImageHeader is the fixed JImage header. +type JImageHeader = jimage.Header + +// OpenJImageFile opens a JDK runtime image and keeps the file handle until the +// reader is closed. +func OpenJImageFile(path string) (*JImageReader, error) { + return jimage.OpenFile(path) +} + +// JImageToJar converts a JDK runtime image into a JAR. Class resources are +// placed at package paths; module-info.class and non-class resources keep their +// module prefix. The destination is replaced atomically after the complete JAR +// has been written. +func JImageToJar(src, dst string) error { + reader, err := jimage.OpenFile(src) + if err != nil { + return err + } + defer reader.Close() + + dir := filepath.Dir(dst) + temp, err := os.CreateTemp(dir, ".javajive-jimage-*.jar") + if err != nil { + return err + } + tempName := temp.Name() + cleanup := true + defer func() { + if temp != nil { + _ = temp.Close() + } + if cleanup { + _ = os.Remove(tempName) + } + }() + if err := reader.WriteZIP(temp); err != nil { + return err + } + if err := temp.Sync(); err != nil { + return err + } + if err := temp.Close(); err != nil { + temp = nil + return err + } + temp = nil + if err := os.Rename(tempName, dst); err != nil { + return err + } + cleanup = false + return nil +} + // --------------------------------------------------------------------------- // Decompilation // --------------------------------------------------------------------------- @@ -114,8 +242,12 @@ func DecompileWithResolver(classBytes []byte, resolve func(internalName string) return classparser.DecompileWithResolver(classBytes, resolve) } -// DecompileArchive decompiles every class inside a .jar/.war/.zip archive at src -// and writes the resulting .java files into the dst directory tree. +// DecompileArchive decompiles every class inside a Java archive +// (.jar/.war/.ear/.aar/.par/.jmod/.zip) or JDK runtime image (.jimage / +// lib/modules) at src and writes the resulting .java files into the dst +// directory tree. Nested archive layers are decompiled in place; .jmod inputs +// have their four-byte header stripped automatically, and .jimage inputs are +// converted to a package-layout JAR view before decompilation. func DecompileArchive(src, dst string) error { return jarwar.AutoDecompile(src, dst) } @@ -139,20 +271,35 @@ func DetectInputKind(input []byte) InputKind { return nativedex.DetectInputKind(input) } -// DexToJar converts raw DEX or APK bytes into a deterministic JAR. +// DexToJar converts raw DEX, APK, APKS/XAPK/APKM bundle, or AAB bytes into a +// deterministic JAR. func DexToJar(input []byte, options DexOptions) ([]byte, DexReport, error) { return nativedex.DexToJar(input, options) } -// DexFileToJar converts a raw DEX or APK file and replaces dst only after the -// complete JAR has been written to a temporary file in the same directory. +// DexToJarWithOptions converts input with an explicit failure policy. Partial +// success has a nil error and a detailed report identifying every stub. +func DexToJarWithOptions(input []byte, options DexConvertOptions) ([]byte, DexDetailedReport, error) { + return nativedex.DexToJarWithOptions(input, options) +} + +// DexFileToJar converts a raw DEX, APK, APKS/XAPK/APKM, or AAB file and replaces +// dst only after the complete JAR has been written to a temporary file in the +// same directory. func DexFileToJar(src, dst string, options DexOptions) (DexReport, error) { return nativedex.DexFileToJar(src, dst, options) } -// DecompileDEXFile converts a raw DEX or APK through a private temporary JAR, -// decompiles that archive into dst, and always removes the temporary JAR. -// Archive decompilation may write part of dst before returning an error. +// DexFileToJarWithOptions converts a file with explicit failure policy and +// atomically replaces dst on complete or explicitly partial success. +func DexFileToJarWithOptions(src, dst string, options DexConvertOptions) (DexDetailedReport, error) { + return nativedex.DexFileToJarWithOptions(src, dst, options) +} + +// DecompileDEXFile converts a raw DEX, APK, APKS/XAPK/APKM, or AAB through a +// private temporary JAR, decompiles that archive into dst, and always removes +// the temporary JAR. Archive decompilation may write part of dst before +// returning an error. func DecompileDEXFile(src, dst string, options DexOptions) error { return DecompileDEXFileWithAnalysisBudget(src, dst, options, 0) } @@ -160,17 +307,32 @@ func DecompileDEXFile(src, dst string, options DexOptions) error { // DecompileDEXFileWithAnalysisBudget is DecompileDEXFile with an explicit // per-method analysis budget for the translated JAR's decompilation. func DecompileDEXFileWithAnalysisBudget(src, dst string, options DexOptions, maxAnalysisUpdates int) error { + _, err := DecompileDEXFileWithPolicy(src, dst, DexConvertOptions{ + Input: options, + Policy: DexFailureStrict, + }, maxAnalysisUpdates) + return err +} + +// DecompileDEXFileWithPolicy translates DEX/Android input with an explicit +// failure policy, decompiles the resulting private JAR, and returns the +// detailed translation report. The temporary JAR is always removed. +func DecompileDEXFileWithPolicy(src, dst string, options DexConvertOptions, maxAnalysisUpdates int) (DexDetailedReport, error) { tempDir, err := os.MkdirTemp("", "javajive-dex-decompile-*") if err != nil { - return err + return DexDetailedReport{Status: "failed"}, err } defer os.RemoveAll(tempDir) jarPath := filepath.Join(tempDir, "classes.jar") - if _, err := DexFileToJar(src, jarPath, options); err != nil { - return err + detailed, err := DexFileToJarWithOptions(src, jarPath, options) + if err != nil { + return detailed, err + } + if err := DecompileArchiveWithAnalysisBudget(jarPath, dst, maxAnalysisUpdates); err != nil { + return detailed, err } - return DecompileArchiveWithAnalysisBudget(jarPath, dst, maxAnalysisUpdates) + return detailed, nil } // --------------------------------------------------------------------------- diff --git a/javajive_test.go b/javajive_test.go index 0647c8b6..751bc2b0 100644 --- a/javajive_test.go +++ b/javajive_test.go @@ -9,6 +9,7 @@ import ( "testing" jj "github.com/yaklang/javajive" + "github.com/yaklang/javajive/internal/jimagefixture" ) const helloStringStream = "aced000574000568656c6c6f" @@ -81,6 +82,143 @@ func TestDecompileFileExport(t *testing.T) { } } +func zipWith(t *testing.T, files map[string][]byte) []byte { + t.Helper() + var buffer bytes.Buffer + writer := zip.NewWriter(&buffer) + for name, body := range files { + entry, err := writer.Create(name) + if err != nil { + t.Fatal(err) + } + if _, err := entry.Write(body); err != nil { + t.Fatal(err) + } + } + if err := writer.Close(); err != nil { + t.Fatal(err) + } + return buffer.Bytes() +} + +func TestClassifyInputExport(t *testing.T) { + apk := zipWith(t, map[string][]byte{"classes.dex": []byte("dex\n035\x00")}) + cases := []struct { + name string + data []byte + file string + want jj.ContainerKind + }{ + {"jmod", append([]byte{'J', 'M', 1, 0}, zipWith(t, nil)...), "java.base.jmod", jj.ContainerJMOD}, + {"apks", zipWith(t, map[string][]byte{"base.apk": apk}), "app.apks", jj.ContainerAPKS}, + {"aab", zipWith(t, map[string][]byte{"base/dex/classes.dex": []byte("dex\n035\x00")}), "app.aab", jj.ContainerAAB}, + {"jar", zipWith(t, map[string][]byte{"META-INF/MANIFEST.MF": []byte("Manifest-Version: 1.0\r\n\r\n")}), "library.jar", jj.ContainerJAR}, + {"unknown", []byte("not an artifact"), "notes.txt", jj.ContainerUnknown}, + } + for _, test := range cases { + t.Run(test.name, func(t *testing.T) { + if got := jj.ClassifyInput(test.data, test.file); got != test.want { + t.Fatalf("ClassifyInput = %q, want %q", got, test.want) + } + }) + } + if jj.DetectInputKind(cases[0].data) != jj.InputJMOD { + t.Fatal("DetectInputKind did not report JMOD") + } + if !jj.IsAndroidContainer(jj.ContainerAPKS) || jj.IsAndroidContainer(jj.ContainerJAR) { + t.Fatal("IsAndroidContainer groups are wrong") + } + if !jj.IsJavaArchiveContainer(jj.ContainerJMOD) || jj.IsJavaArchiveContainer(jj.ContainerAPK) { + t.Fatal("IsJavaArchiveContainer groups are wrong") + } +} + +func TestClassifyInputFileExport(t *testing.T) { + apk := zipWith(t, map[string][]byte{"classes.dex": []byte("dex\n035\x00")}) + bundle := zipWith(t, map[string][]byte{"base.apk": apk}) + path := filepath.Join(t.TempDir(), "app.apks") + if err := os.WriteFile(path, bundle, 0o644); err != nil { + t.Fatal(err) + } + kind, err := jj.ClassifyInputFile(path) + if err != nil { + t.Fatalf("ClassifyInputFile: %v", err) + } + if kind != jj.ContainerAPKS { + t.Fatalf("kind = %q, want apks", kind) + } +} + +func TestJImageToJarExport(t *testing.T) { + classBytes := testdataClass(t) + image, err := jimagefixture.Build([]jimagefixture.Entry{ + {Path: "/test/InvisibleAnnoSeed.class", Data: classBytes}, + }) + if err != nil { + t.Fatal(err) + } + dir := t.TempDir() + src := filepath.Join(dir, "modules") + if err := os.WriteFile(src, image, 0o644); err != nil { + t.Fatal(err) + } + if got := jj.ClassifyInput(image, "modules"); got != jj.ContainerJImage { + t.Fatalf("ClassifyInput = %q, want jimage", got) + } + if got := jj.DetectInputKind(image); got != jj.InputJIMAGE { + t.Fatalf("DetectInputKind = %v, want InputJIMAGE", got) + } + if !jj.IsJavaArchiveContainer(jj.ContainerJImage) { + t.Fatal("JImage is not grouped as a Java archive") + } + + dst := filepath.Join(dir, "image.jar") + if err := jj.JImageToJar(src, dst); err != nil { + t.Fatalf("JImageToJar: %v", err) + } + raw, err := os.ReadFile(dst) + if err != nil { + t.Fatal(err) + } + zipReader, err := zip.NewReader(bytes.NewReader(raw), int64(len(raw))) + if err != nil { + t.Fatalf("open converted JAR: %v", err) + } + if len(zipReader.File) != 1 || zipReader.File[0].Name != "InvisibleAnnoSeed.class" { + t.Fatalf("JAR entries = %#v", zipReader.File) + } +} + +func TestDecompileJImageArchiveExport(t *testing.T) { + classBytes := testdataClass(t) + image, err := jimagefixture.Build([]jimagefixture.Entry{ + {Path: "/test/InvisibleAnnoSeed.class", Data: classBytes}, + {Path: "/test/conf/app.properties", Data: []byte("key=value\n")}, + }) + if err != nil { + t.Fatal(err) + } + dir := t.TempDir() + src := filepath.Join(dir, "modules") + if err := os.WriteFile(src, image, 0o644); err != nil { + t.Fatal(err) + } + outDir := filepath.Join(dir, "src") + if err := jj.DecompileArchive(src, outDir); err != nil { + t.Fatalf("DecompileArchive: %v", err) + } + source, err := os.ReadFile(filepath.Join(outDir, "InvisibleAnnoSeed.java")) + if err != nil { + t.Fatalf("read decompiled source: %v", err) + } + if !strings.Contains(string(source), "class InvisibleAnnoSeed") { + t.Fatalf("unexpected source:\n%s", source) + } + if _, err := os.Stat(filepath.Join(outDir, "test/conf/app.properties")); err != nil { + t.Fatalf("JImage resource missing: %v", err) + } +} + func TestDecompileArchiveWithAnalysisBudgetExport(t *testing.T) { dir := t.TempDir() jarPath := filepath.Join(dir, "seed.jar") diff --git a/jimage/compactcp_fuzz_test.go b/jimage/compactcp_fuzz_test.go new file mode 100644 index 00000000..99680974 --- /dev/null +++ b/jimage/compactcp_fuzz_test.go @@ -0,0 +1,13 @@ +package jimage + +import "testing" + +func FuzzDecompressCompactCP(f *testing.F) { + compressed, _, reader := compactCPFixture() + f.Add(compressed) + f.Add(append(compactCPHeader()[:8], 0, 2, compactCPExternalizedString, 0xA1)) + f.Add([]byte{}) + f.Fuzz(func(t *testing.T, data []byte) { + _, _ = reader.decompressCompactCP(data, 1<<20, "fuzz") + }) +} diff --git a/jimage/compactcp_test.go b/jimage/compactcp_test.go new file mode 100644 index 00000000..435ee5f3 --- /dev/null +++ b/jimage/compactcp_test.go @@ -0,0 +1,159 @@ +package jimage + +import ( + "bytes" + "testing" +) + +func compactCPHeader() []byte { + return []byte{ + 0xca, 0xfe, 0xba, 0xbe, // magic + 0x00, 0x00, // minor + 0x00, 0x34, // major 52 + 0x00, 0x0a, // constant pool count 10 + } +} + +func compactCPTail() []byte { + return []byte{ + 0x00, 0x21, 0x00, 0x01, 0x00, 0x02, 0x00, 0x03, + 0x00, 0x04, 0x00, 0x05, 0x00, 0x06, 0x00, 0x07, + } +} + +func appendUTF8Entry(destination []byte, value string) []byte { + destination = append(destination, constantUTF8, byte(len(value)>>8), byte(len(value))) + return append(destination, value...) +} + +func compactCPFixture() (compressed, expected []byte, reader *Reader) { + header := compactCPHeader() + tail := compactCPTail() + + compressed = append([]byte{}, header...) + // #1: externalized "Hello" (string table offset 1). + compressed = append(compressed, compactCPExternalizedString, 0xA1) + // #2: externalized descriptor "(L;I)V" (offset 7), two indexes: + // package "java/lang" (offset 21) and class "String" (offset 14). + compressed = append(compressed, compactCPExternalizedDescriptor, 0xA7, 0xA2, 0xB5, 0xAE) + // #3: inline UTF8 "raw". + compressed = append(compressed, constantUTF8, 0x00, 0x03, 'r', 'a', 'w') + // #4: CONSTANT_Class. + compressed = append(compressed, 7, 0x00, 0x01) + // #5: CONSTANT_Long (occupies slots 5 and 6). + compressed = append(compressed, 5, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88) + // #7: CONSTANT_NameAndType. + compressed = append(compressed, 12, 0x00, 0x01, 0x00, 0x02) + // #8: CONSTANT_InvokeDynamic. + compressed = append(compressed, 18, 0x00, 0x03, 0x00, 0x04) + // #9: CONSTANT_Module. + compressed = append(compressed, 19, 0x00, 0x05) + compressed = append(compressed, tail...) + + expected = append([]byte{}, header...) + expected = appendUTF8Entry(expected, "Hello") + expected = appendUTF8Entry(expected, "(Ljava/lang/String;I)V") + expected = appendUTF8Entry(expected, "raw") + expected = append(expected, 7, 0x00, 0x01) + expected = append(expected, 5, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88) + expected = append(expected, 12, 0x00, 0x01, 0x00, 0x02) + expected = append(expected, 18, 0x00, 0x03, 0x00, 0x04) + expected = append(expected, 19, 0x00, 0x05) + expected = append(expected, tail...) + + stringsData := []byte{0} + stringsData = append(stringsData, []byte("Hello")...) + stringsData = append(stringsData, 0) + stringsData = append(stringsData, []byte("(L;I)V")...) + stringsData = append(stringsData, 0) + stringsData = append(stringsData, []byte("String")...) + stringsData = append(stringsData, 0) + stringsData = append(stringsData, []byte("java/lang")...) + stringsData = append(stringsData, 0) + + reader = &Reader{strings: stringsData, maxResourceSize: defaultMaxResourceSize} + return compressed, expected, reader +} + +func TestDecompressCompactCP(t *testing.T) { + compressed, expected, reader := compactCPFixture() + got, err := reader.decompressCompactCP(compressed, uint64(len(expected)), "test/Hello.class") + if err != nil { + t.Fatalf("decompressCompactCP: %v", err) + } + if !bytes.Equal(got, expected) { + t.Fatalf("reconstructed class differs:\n got: % x\nwant: % x", got, expected) + } +} + +func TestDecompressCompactCPOutputLimit(t *testing.T) { + data := append(compactCPHeader()[:8], 0, 2) + data = append(data, compactCPExternalizedString, 0xA1) + reader := &Reader{ + strings: append([]byte{0}, append([]byte("oversized"), 0)...), + maxResourceSize: 16, + } + if _, err := reader.decompressCompactCP(data, 16, "test/Oversized.class"); err == nil || !bytes.Contains([]byte(err.Error()), []byte("output exceeds declared size")) { + t.Fatalf("decompressCompactCP error = %v, want running output bound", err) + } +} + +func TestDecompressCompactCPMalformed(t *testing.T) { + compressed, expected, reader := compactCPFixture() + cases := []struct { + name string + data []byte + size uint64 + }{ + {"short header", compressed[:9], uint64(len(expected))}, + {"truncated constant pool", append(append([]byte{}, compressed[:10]...), 7), uint64(len(expected))}, + {"invalid tag", append(append([]byte{}, compressed[:10]...), 2, 0, 0), 12}, + {"string offset", append(append([]byte{}, compressed[:10]...), compactCPExternalizedString, 0xBF), 12}, + {"descriptor indexes truncated", append(append([]byte{}, compressed[:10]...), compactCPExternalizedDescriptor, 0xA7, 0xA5, 0xA0), 12}, + {"invalid compressed integer", append(append([]byte{}, compressed[:10]...), compactCPExternalizedString, 0x80), 12}, + {"length mismatch", compressed, uint64(len(expected) + 1)}, + } + for _, test := range cases { + t.Run(test.name, func(t *testing.T) { + if _, err := reader.decompressCompactCP(test.data, test.size, "test/Hello.class"); err == nil { + t.Fatal("decompressCompactCP accepted malformed input") + } + }) + } +} + +func TestDecompressInt(t *testing.T) { + cases := []struct { + name string + data []byte + want int + wantNext int + wantErr bool + }{ + {"one byte zero", []byte{0xA0}, 0, 1, false}, + {"one byte value", []byte{0xA5}, 5, 1, false}, + {"two bytes", []byte{0xC1, 0x02}, 0x102, 2, false}, + {"three bytes", []byte{0xE1, 0x02, 0x03}, 0x10203, 3, false}, + {"uncompressed", []byte{0x00, 0x00, 0x01, 0x00}, 256, 4, false}, + {"invalid length", []byte{0x80}, 0, 0, true}, + {"truncated compressed", []byte{0xC1}, 0, 0, true}, + {"truncated uncompressed", []byte{0x00, 0x01}, 0, 0, true}, + } + for _, test := range cases { + t.Run(test.name, func(t *testing.T) { + got, next, err := decompressInt(test.data, 0) + if test.wantErr { + if err == nil { + t.Fatalf("decompressInt(% x) unexpectedly succeeded", test.data) + } + return + } + if err != nil { + t.Fatalf("decompressInt(% x): %v", test.data, err) + } + if got != test.want || next != test.wantNext { + t.Fatalf("decompressInt(% x) = (%d, %d), want (%d, %d)", test.data, got, next, test.want, test.wantNext) + } + }) + } +} diff --git a/jimage/fuzz_test.go b/jimage/fuzz_test.go new file mode 100644 index 00000000..cad2b491 --- /dev/null +++ b/jimage/fuzz_test.go @@ -0,0 +1,43 @@ +package jimage_test + +import ( + "testing" + + "github.com/yaklang/javajive/internal/jimagefixture" + "github.com/yaklang/javajive/jimage" +) + +func FuzzOpenBytes(f *testing.F) { + fixture, err := jimagefixture.Build([]jimagefixture.Entry{ + {Path: "/test/demo/Foo.class", Data: []byte{0xca, 0xfe, 0xba, 0xbe, 1, 2, 3, 4}}, + {Path: "/test/conf/app.properties", Data: []byte("key=value\n")}, + }) + if err != nil { + f.Fatal(err) + } + f.Add(fixture) + resourceCountOverTable := append([]byte(nil), fixture...) + resourceCountOverTable[12] = 0xff + resourceCountOverTable[13] = 0xff + resourceCountOverTable[14] = 0xff + resourceCountOverTable[15] = 0xff + f.Add(resourceCountOverTable) + f.Add([]byte{0xda, 0xda, 0xfe, 0xca}) + f.Add([]byte{}) + f.Fuzz(func(t *testing.T, data []byte) { + reader, err := jimage.OpenBytes(data) + if err != nil { + return + } + defer reader.Close() + for index, entry := range reader.Entries() { + if index >= 32 { + break + } + if entry.Directory { + continue + } + _, _ = reader.Read(entry.Path) + } + }) +} diff --git a/jimage/jimage.go b/jimage/jimage.go new file mode 100644 index 00000000..416e959c --- /dev/null +++ b/jimage/jimage.go @@ -0,0 +1,909 @@ +// Package jimage reads the JDK modular runtime image format used by +// $JAVA_HOME/lib/modules and .jimage files. It exposes the image resources as +// a deterministic JAR view so the Java decompiler can consume JDK 9+ runtime +// images without an external jimage tool. +package jimage + +import ( + "archive/zip" + "bytes" + "compress/flate" + "compress/zlib" + "encoding/binary" + "errors" + "fmt" + "io" + "os" + "sort" + "strings" + "time" +) + +const ( + imageMagic = 0xCAFEDADA + resourceHeaderMagic = 0xCAFEFAFA + headerSize = 28 + resourceHeaderSize = 29 + + // maxTableLength keeps a malicious header from allocating unbounded index + // tables. Real JDK images have tens of thousands of resources. + maxTableLength = 1 << 24 + + defaultMaxResourceSize = 256 << 20 + + attributeModule = 1 + attributeParent = 2 + attributeBase = 3 + attributeExtension = 4 + attributeOffset = 5 + attributeCompressed = 6 + attributeUncompressed = 7 + attributePreviewFlags = 8 + attributeCount = 9 + modulesModuleName = "modules" + packagesModuleName = "packages" + maxDecompressorLayers = 16 + + compactCPExternalizedString = 23 + compactCPExternalizedDescriptor = 25 + constantUTF8 = 1 + constantLong = 5 + constantDouble = 6 +) + +var archiveTimestamp = time.Date(1980, time.January, 1, 0, 0, 0, 0, time.UTC) + +// ErrUnsupportedCompressor reports a resource compressed with a decompressor +// this package does not implement. Compressed JDK images produced by jlink +// normally use "zip"; "compact-cp" is a class-file constant-pool transform. +var ErrUnsupportedCompressor = errors.New("jimage: unsupported compressor") + +// UnsupportedCompressorError identifies the resource and compressor name. +type UnsupportedCompressorError struct { + Entry string + Compressor string +} + +func (e *UnsupportedCompressorError) Error() string { + if e == nil { + return ErrUnsupportedCompressor.Error() + } + return fmt.Sprintf("jimage: %q uses unsupported compressor %q", e.Entry, e.Compressor) +} + +func (e *UnsupportedCompressorError) Unwrap() error { return ErrUnsupportedCompressor } + +// Header is the fixed 28-byte image header. The version packs a major version +// in the high 16 bits and a minor version in the low 16 bits. +type Header struct { + Magic uint32 + Version uint32 + Flags uint32 + ResourceCount uint32 + TableLength uint32 + LocationsSize uint32 + StringsSize uint32 +} + +// Major is the image format major version. +func (h Header) Major() uint16 { return uint16(h.Version >> 16) } + +// Minor is the image format minor version. +func (h Header) Minor() uint16 { return uint16(h.Version) } + +// Entry is one resource location in a JImage. +type Entry struct { + // Path is the full JImage path, for example + // "/java.base/java/lang/Object.class". + Path string + Module string + Parent string + Base string + Extension string + + Offset uint64 + CompressedSize uint64 + UncompressedSize uint64 + PreviewFlags uint32 + + // Directory marks the synthetic /modules and /packages namespace entries. + Directory bool +} + +// Name returns Path without the leading slash. +func (e Entry) Name() string { return strings.TrimPrefix(e.Path, "/") } + +// Options controls resource bounds. The zero value uses defaults. +type Options struct { + MaxResourceSize uint64 +} + +func (o Options) maxResourceSize() uint64 { + if o.MaxResourceSize == 0 { + return defaultMaxResourceSize + } + return o.MaxResourceSize +} + +// Reader is a random-access JImage reader. The index tables are held in memory; +// resource bytes are read on demand through the underlying io.ReaderAt. +type Reader struct { + r io.ReaderAt + size int64 + close io.Closer + + endian binary.ByteOrder + header Header + offsets []uint32 + + locations []byte + strings []byte + indexSize uint64 + + entries []Entry + byName map[string]int + + maxResourceSize uint64 +} + +// OpenFile opens a JImage file and keeps the file handle until Close. +func OpenFile(name string) (*Reader, error) { + file, err := os.Open(name) + if err != nil { + return nil, err + } + info, err := file.Stat() + if err != nil { + _ = file.Close() + return nil, err + } + reader, err := Open(file, info.Size(), Options{}) + if err != nil { + _ = file.Close() + return nil, err + } + reader.close = file + return reader, nil +} + +// OpenBytes opens a JImage held in memory. +func OpenBytes(data []byte) (*Reader, error) { + return Open(bytes.NewReader(data), int64(len(data)), Options{}) +} + +// Open reads the JImage header and index from r. The reader must remain valid +// until the returned Reader is no longer used. +func Open(r io.ReaderAt, size int64, options Options) (*Reader, error) { + if r == nil { + return nil, errors.New("jimage: nil reader") + } + if size < headerSize { + return nil, fmt.Errorf("jimage: input size %d is smaller than the %d-byte header", size, headerSize) + } + + var raw [headerSize]byte + if _, err := r.ReadAt(raw[:], 0); err != nil { + return nil, fmt.Errorf("jimage: read header: %w", err) + } + + var endian binary.ByteOrder + switch { + case binary.LittleEndian.Uint32(raw[0:4]) == imageMagic: + endian = binary.LittleEndian + case binary.BigEndian.Uint32(raw[0:4]) == imageMagic: + endian = binary.BigEndian + default: + return nil, fmt.Errorf("jimage: bad magic 0x%08x", endianOrLittle(raw[0:4])) + } + + header := Header{ + Magic: endian.Uint32(raw[0:4]), + Version: endian.Uint32(raw[4:8]), + Flags: endian.Uint32(raw[8:12]), + ResourceCount: endian.Uint32(raw[12:16]), + TableLength: endian.Uint32(raw[16:20]), + LocationsSize: endian.Uint32(raw[20:24]), + StringsSize: endian.Uint32(raw[24:28]), + } + if header.Major() != 1 || header.Minor() > 1 { + return nil, fmt.Errorf("jimage: unsupported version %d.%d", header.Major(), header.Minor()) + } + if header.TableLength > maxTableLength { + return nil, fmt.Errorf("jimage: table length %d exceeds limit %d", header.TableLength, maxTableLength) + } + if header.ResourceCount > header.TableLength { + return nil, fmt.Errorf("jimage: resource count %d exceeds table length %d", header.ResourceCount, header.TableLength) + } + + tableBytes := uint64(header.TableLength) * 4 + indexSize := uint64(headerSize) + tableBytes*2 + uint64(header.LocationsSize) + uint64(header.StringsSize) + if indexSize < uint64(headerSize) || indexSize > uint64(size) { + return nil, fmt.Errorf("jimage: index size %d exceeds input size %d", indexSize, size) + } + + // The redirect table is used by the JDK's hash lookup. Enumeration and the + // path-indexed API below do not need it, but it still occupies space in the + // index before the offsets table. + offsetsPos := int64(headerSize) + int64(tableBytes) + offsetBytes := make([]byte, tableBytes) + if _, err := r.ReadAt(offsetBytes, offsetsPos); err != nil { + return nil, fmt.Errorf("jimage: read offsets table: %w", err) + } + offsets := make([]uint32, header.TableLength) + for i := range offsets { + offsets[i] = endian.Uint32(offsetBytes[i*4:]) + } + + locationsPos := offsetsPos + int64(tableBytes) + locations := make([]byte, header.LocationsSize) + if _, err := r.ReadAt(locations, locationsPos); err != nil { + return nil, fmt.Errorf("jimage: read location attributes: %w", err) + } + + stringsPos := locationsPos + int64(header.LocationsSize) + stringsData := make([]byte, header.StringsSize) + if _, err := r.ReadAt(stringsData, stringsPos); err != nil { + return nil, fmt.Errorf("jimage: read strings table: %w", err) + } + + reader := &Reader{ + r: r, + size: size, + endian: endian, + header: header, + offsets: offsets, + locations: locations, + strings: stringsData, + indexSize: indexSize, + maxResourceSize: options.maxResourceSize(), + } + if err := reader.buildEntries(); err != nil { + return nil, err + } + return reader, nil +} + +// Close releases the file handle when the reader was opened with OpenFile. +func (r *Reader) Close() error { + if r == nil || r.close == nil { + return nil + } + closer := r.close + r.close = nil + return closer.Close() +} + +// Header returns the parsed image header. +func (r *Reader) Header() Header { + if r == nil { + return Header{} + } + return r.header +} + +// Entries returns the sorted resource inventory. The returned slice must not be +// mutated by callers. +func (r *Reader) Entries() []Entry { + if r == nil { + return nil + } + return r.entries +} + +// Entry looks up a resource by its JImage path. Both "/module/..." and +// "module/..." (and optional jrt-style "modules/" prefix) are accepted. +func (r *Reader) Entry(name string) (Entry, bool) { + if r == nil { + return Entry{}, false + } + index, ok := r.byName[normalizeName(name)] + if !ok { + return Entry{}, false + } + return r.entries[index], true +} + +// Read returns the uncompressed bytes of one resource. +func (r *Reader) Read(name string) ([]byte, error) { + if r == nil { + return nil, errors.New("jimage: nil reader") + } + normalized := normalizeName(name) + index, ok := r.byName[normalized] + if !ok { + return nil, fmt.Errorf("jimage: entry %q not found", name) + } + entry := r.entries[index] + if entry.Directory { + return nil, fmt.Errorf("jimage: entry %q is a directory", entry.Name()) + } + return r.readEntry(entry) +} + +// WriteZIP writes a deterministic JAR view of the image. Class resources are +// placed at their package paths so the Java decompiler can resolve siblings; +// module-info.class and non-class resources keep their module prefix. +func (r *Reader) WriteZIP(w io.Writer) error { + if r == nil { + return errors.New("jimage: nil reader") + } + writer := zip.NewWriter(w) + seen := make(map[string]string, len(r.entries)) + for _, entry := range r.entries { + if entry.Directory { + continue + } + name, err := archiveName(entry) + if err != nil { + return err + } + if previous, exists := seen[name]; exists { + return fmt.Errorf("jimage: JAR entry %q from %q collides with %q", name, entry.Name(), previous) + } + seen[name] = entry.Name() + + data, err := r.readEntry(entry) + if err != nil { + return fmt.Errorf("jimage: read %q: %w", entry.Name(), err) + } + header := &zip.FileHeader{Name: name, Method: zip.Store} + header.SetModTime(archiveTimestamp) + header.SetMode(0o644) + file, err := writer.CreateHeader(header) + if err != nil { + _ = writer.Close() + return fmt.Errorf("jimage: create JAR entry %q: %w", name, err) + } + if _, err := file.Write(data); err != nil { + _ = writer.Close() + return fmt.Errorf("jimage: write JAR entry %q: %w", name, err) + } + } + if err := writer.Close(); err != nil { + return fmt.Errorf("jimage: finish JAR: %w", err) + } + return nil +} + +// ZIPBytes is WriteZIP into memory. Prefer WriteZIP for large JDK images. +func (r *Reader) ZIPBytes() ([]byte, error) { + var buffer bytes.Buffer + if err := r.WriteZIP(&buffer); err != nil { + return nil, err + } + return buffer.Bytes(), nil +} + +func (r *Reader) buildEntries() error { + if r.header.TableLength == 0 { + r.entries = nil + r.byName = make(map[string]int) + return nil + } + seen := make(map[uint32]struct{}) + var entries []Entry + for _, offset := range r.offsets { + if offset == 0 { + continue + } + if _, exists := seen[offset]; exists { + continue + } + seen[offset] = struct{}{} + entry, err := r.parseEntry(offset) + if err != nil { + return err + } + if entry.Path == "" { + continue + } + entries = append(entries, entry) + } + sort.Slice(entries, func(i, j int) bool { return entries[i].Path < entries[j].Path }) + r.entries = entries + r.byName = make(map[string]int, len(entries)) + for index, entry := range entries { + name := entry.Name() + if _, exists := r.byName[name]; exists { + return fmt.Errorf("jimage: duplicate entry %q", name) + } + r.byName[name] = index + } + return nil +} + +func (r *Reader) parseEntry(offset uint32) (Entry, error) { + attrs, err := r.parseAttributes(offset) + if err != nil { + return Entry{}, err + } + module, err := r.stringValue(attrs[attributeModule]) + if err != nil { + return Entry{}, err + } + parent, err := r.stringValue(attrs[attributeParent]) + if err != nil { + return Entry{}, err + } + base, err := r.stringValue(attrs[attributeBase]) + if err != nil { + return Entry{}, err + } + extension, err := r.stringValue(attrs[attributeExtension]) + if err != nil { + return Entry{}, err + } + + var builder strings.Builder + if module != "" { + builder.WriteByte('/') + builder.WriteString(module) + builder.WriteByte('/') + } + if parent != "" { + builder.WriteString(parent) + builder.WriteByte('/') + } + builder.WriteString(base) + if extension != "" { + builder.WriteByte('.') + builder.WriteString(extension) + } + + return Entry{ + Path: builder.String(), + Module: module, + Parent: parent, + Base: base, + Extension: extension, + Offset: attrs[attributeOffset], + CompressedSize: attrs[attributeCompressed], + UncompressedSize: attrs[attributeUncompressed], + PreviewFlags: uint32(attrs[attributePreviewFlags]), + Directory: module == modulesModuleName || module == packagesModuleName || base == "", + }, nil +} + +func (r *Reader) parseAttributes(offset uint32) ([attributeCount]uint64, error) { + var attrs [attributeCount]uint64 + pos := int(offset) + if pos < 0 || pos >= len(r.locations) { + return attrs, fmt.Errorf("jimage: location offset %d is out of range", offset) + } + for { + if pos >= len(r.locations) { + return attrs, fmt.Errorf("jimage: unterminated attribute stream at offset %d", offset) + } + header := r.locations[pos] + pos++ + if header <= 7 { // ATTRIBUTE_END + break + } + kind := int(header >> 3) + if kind >= attributeCount { + return attrs, fmt.Errorf("jimage: invalid attribute kind %d at offset %d", kind, offset) + } + length := int(header&0x7) + 1 + if pos+length > len(r.locations) { + return attrs, fmt.Errorf("jimage: truncated attribute value at offset %d", offset) + } + var value uint64 + for i := 0; i < length; i++ { + value = value<<8 | uint64(r.locations[pos+i]) + } + pos += length + attrs[kind] = value + } + return attrs, nil +} + +func (r *Reader) stringValue(offset uint64) (string, error) { + if offset > uint64(^uint32(0)) { + return "", fmt.Errorf("jimage: string offset %d is out of range", offset) + } + return r.stringAt(uint32(offset)) +} + +func (r *Reader) stringAt(offset uint32) (string, error) { + if offset == 0 { + return "", nil + } + if int(offset) >= len(r.strings) { + return "", fmt.Errorf("jimage: string offset %d is out of range", offset) + } + rest := r.strings[offset:] + end := bytes.IndexByte(rest, 0) + if end < 0 { + return "", fmt.Errorf("jimage: unterminated string at offset %d", offset) + } + return string(rest[:end]), nil +} + +func (r *Reader) readEntry(entry Entry) ([]byte, error) { + size := entry.CompressedSize + if size == 0 { + size = entry.UncompressedSize + } + if size > r.maxResourceSize { + return nil, fmt.Errorf("jimage: resource size %d exceeds limit %d", size, r.maxResourceSize) + } + start := r.indexSize + entry.Offset + if start < r.indexSize || start > uint64(r.size) { + return nil, fmt.Errorf("jimage: resource offset %d is out of range", entry.Offset) + } + if size > uint64(r.size)-start { + return nil, fmt.Errorf("jimage: resource %q exceeds image size", entry.Name()) + } + payload := make([]byte, int(size)) + if _, err := r.r.ReadAt(payload, int64(start)); err != nil { + return nil, fmt.Errorf("jimage: read resource %q: %w", entry.Name(), err) + } + if entry.CompressedSize == 0 { + return payload, nil + } + return r.decompress(entry, payload) +} + +func (r *Reader) decompress(entry Entry, payload []byte) ([]byte, error) { + current := payload + for depth := 0; ; depth++ { + if depth > maxDecompressorLayers { + return nil, fmt.Errorf("jimage: resource %q has too many decompressor layers", entry.Name()) + } + if len(current) < resourceHeaderSize { + return nil, fmt.Errorf("jimage: resource %q has a truncated decompressor header", entry.Name()) + } + if r.endian.Uint32(current[0:4]) != resourceHeaderMagic { + return nil, fmt.Errorf("jimage: resource %q is compressed but has no decompressor header", entry.Name()) + } + compressedSize := r.endian.Uint64(current[4:12]) + uncompressedSize := r.endian.Uint64(current[12:20]) + compressorOffset := r.endian.Uint32(current[20:24]) + terminal := current[28] + if compressedSize > r.maxResourceSize { + return nil, fmt.Errorf("jimage: resource %q compressed layer size %d exceeds limit %d", entry.Name(), compressedSize, r.maxResourceSize) + } + if uncompressedSize > r.maxResourceSize { + return nil, fmt.Errorf("jimage: resource %q uncompressed layer size %d exceeds limit %d", entry.Name(), uncompressedSize, r.maxResourceSize) + } + if compressedSize > uint64(len(current)-resourceHeaderSize) { + return nil, fmt.Errorf("jimage: resource %q compressed payload exceeds its entry", entry.Name()) + } + compressor, err := r.stringAt(compressorOffset) + if err != nil { + return nil, err + } + payloadStart := resourceHeaderSize + payloadEnd := payloadStart + int(compressedSize) + + var next []byte + switch compressor { + case "zip": + next, err = decompressZIP(current[payloadStart:payloadEnd], uncompressedSize, r.maxResourceSize) + case "compact-cp": + next, err = r.decompressCompactCP(current[payloadStart:payloadEnd], uncompressedSize, entry.Name()) + default: + return nil, &UnsupportedCompressorError{Entry: entry.Name(), Compressor: compressor} + } + if err != nil { + return nil, fmt.Errorf("jimage: decompress %q with %s: %w", entry.Name(), compressor, err) + } + current = next + if terminal != 0 { + break + } + } + if uint64(len(current)) != entry.UncompressedSize { + return nil, fmt.Errorf("jimage: resource %q decompressed to %d bytes, want %d", entry.Name(), len(current), entry.UncompressedSize) + } + return current, nil +} + +func decompressZIP(payload []byte, expected, limit uint64) ([]byte, error) { + if expected > limit { + return nil, fmt.Errorf("jimage: inflated size %d exceeds limit %d", expected, limit) + } + if expected >= uint64(^uint(0)>>1) { + return nil, fmt.Errorf("jimage: inflated size %d is too large", expected) + } + var reader io.ReadCloser + if zlibReader, err := zlib.NewReader(bytes.NewReader(payload)); err == nil { + reader = zlibReader + } else { + reader = flate.NewReader(bytes.NewReader(payload)) + } + defer reader.Close() + output, err := io.ReadAll(io.LimitReader(reader, int64(expected)+1)) + if err != nil { + return nil, err + } + if uint64(len(output)) != expected { + return nil, fmt.Errorf("inflated to %d bytes, want %d", len(output), expected) + } + return output, nil +} + +// decompressCompactCP reconstructs a class file whose constant-pool UTF8 +// entries were externalized into the image string table by jlink's +// StringSharingPlugin ("compact-cp"). +func (r *Reader) decompressCompactCP(data []byte, uncompressedSize uint64, entryName string) ([]byte, error) { + if uncompressedSize > r.maxResourceSize { + return nil, fmt.Errorf("jimage: compact-cp resource %q size %d exceeds limit %d", entryName, uncompressedSize, r.maxResourceSize) + } + if uncompressedSize > uint64(^uint(0)>>1) { + return nil, fmt.Errorf("jimage: compact-cp resource %q size %d is too large", entryName, uncompressedSize) + } + if len(data) < 10 { + return nil, fmt.Errorf("jimage: compact-cp resource %q is shorter than the 10-byte class header", entryName) + } + output := make([]byte, 0, int(uncompressedSize)) + outputLimit := uncompressedSize + if outputLimit > r.maxResourceSize { + outputLimit = r.maxResourceSize + } + outputAvailable := func(length int) bool { + return uint64(len(output)) <= outputLimit && uint64(length) <= outputLimit-uint64(len(output)) + } + appendOutput := func(values ...byte) error { + if !outputAvailable(len(values)) { + return fmt.Errorf("jimage: compact-cp resource %q output exceeds declared size %d", entryName, outputLimit) + } + output = append(output, values...) + return nil + } + appendString := func(value string) error { + if !outputAvailable(len(value)) { + return fmt.Errorf("jimage: compact-cp resource %q output exceeds declared size %d", entryName, outputLimit) + } + output = append(output, value...) + return nil + } + if err := appendOutput(data[:10]...); err != nil { + return nil, err + } + constantPoolCount := int(binary.BigEndian.Uint16(data[8:10])) + position := 10 + for index := 1; index < constantPoolCount; index++ { + if position >= len(data) { + return nil, fmt.Errorf("jimage: compact-cp resource %q: constant pool truncated at entry %d", entryName, index) + } + tag := data[position] + position++ + switch tag { + case compactCPExternalizedString: + stringIndex, next, err := decompressInt(data, position) + if err != nil { + return nil, fmt.Errorf("jimage: compact-cp resource %q entry %d: %w", entryName, index, err) + } + position = next + value, err := r.stringAt(uint32(stringIndex)) + if err != nil { + return nil, fmt.Errorf("jimage: compact-cp resource %q entry %d: %w", entryName, index, err) + } + if len(value) > 0xffff { + return nil, fmt.Errorf("jimage: compact-cp resource %q entry %d string is %d bytes", entryName, index, len(value)) + } + if err := appendOutput(constantUTF8, byte(len(value)>>8), byte(len(value))); err != nil { + return nil, err + } + if err := appendString(value); err != nil { + return nil, err + } + case compactCPExternalizedDescriptor: + descriptorIndex, next, err := decompressInt(data, position) + if err != nil { + return nil, fmt.Errorf("jimage: compact-cp resource %q entry %d: %w", entryName, index, err) + } + position = next + indexesLength, next, err := decompressInt(data, position) + if err != nil { + return nil, fmt.Errorf("jimage: compact-cp resource %q entry %d: %w", entryName, index, err) + } + position = next + descriptor, err := r.stringAt(uint32(descriptorIndex)) + if err != nil { + return nil, fmt.Errorf("jimage: compact-cp resource %q entry %d: %w", entryName, index, err) + } + if indexesLength > len(data)-position { + return nil, fmt.Errorf("jimage: compact-cp resource %q entry %d: descriptor index stream is truncated", entryName, index) + } + indexes := data[position : position+indexesLength] + position += indexesLength + + if err := appendOutput(constantUTF8); err != nil { + return nil, err + } + lengthPosition := len(output) + if err := appendOutput(0, 0); err != nil { + return nil, err + } + descriptorLength := 0 + if indexesLength > 0 { + indexPosition := 0 + for offset := 0; offset < len(descriptor); offset++ { + c := descriptor[offset] + if err := appendOutput(c); err != nil { + return nil, err + } + descriptorLength++ + if c != 'L' { + continue + } + packageIndex, next, err := decompressInt(indexes, indexPosition) + if err != nil { + return nil, fmt.Errorf("jimage: compact-cp resource %q entry %d descriptor: %w", entryName, index, err) + } + indexPosition = next + packageName, err := r.stringAt(uint32(packageIndex)) + if err != nil { + return nil, fmt.Errorf("jimage: compact-cp resource %q entry %d descriptor: %w", entryName, index, err) + } + if len(packageName) > 0 { + if err := appendString(packageName); err != nil { + return nil, err + } + if err := appendOutput('/'); err != nil { + return nil, err + } + descriptorLength += len(packageName) + 1 + } + classIndex, next, err := decompressInt(indexes, indexPosition) + if err != nil { + return nil, fmt.Errorf("jimage: compact-cp resource %q entry %d descriptor: %w", entryName, index, err) + } + indexPosition = next + className, err := r.stringAt(uint32(classIndex)) + if err != nil { + return nil, fmt.Errorf("jimage: compact-cp resource %q entry %d descriptor: %w", entryName, index, err) + } + if err := appendString(className); err != nil { + return nil, err + } + descriptorLength += len(className) + } + } else { + if err := appendString(descriptor); err != nil { + return nil, err + } + descriptorLength = len(descriptor) + } + if descriptorLength > 0xffff { + return nil, fmt.Errorf("jimage: compact-cp resource %q entry %d descriptor is %d bytes", entryName, index, descriptorLength) + } + binary.BigEndian.PutUint16(output[lengthPosition:lengthPosition+2], uint16(descriptorLength)) + case constantUTF8: + if position+2 > len(data) { + return nil, fmt.Errorf("jimage: compact-cp resource %q entry %d: UTF8 length is truncated", entryName, index) + } + length := int(binary.BigEndian.Uint16(data[position : position+2])) + if length > len(data)-position-2 { + return nil, fmt.Errorf("jimage: compact-cp resource %q entry %d: UTF8 value is truncated", entryName, index) + } + if err := appendOutput(constantUTF8); err != nil { + return nil, err + } + if err := appendOutput(data[position : position+2+length]...); err != nil { + return nil, err + } + position += 2 + length + case constantLong, constantDouble: + if position+8 > len(data) { + return nil, fmt.Errorf("jimage: compact-cp resource %q entry %d: wide constant is truncated", entryName, index) + } + index++ // long and double occupy two constant-pool slots + if err := appendOutput(tag); err != nil { + return nil, err + } + if err := appendOutput(data[position : position+8]...); err != nil { + return nil, err + } + position += 8 + default: + size, ok := compactCPConstantSize(tag) + if !ok { + return nil, fmt.Errorf("jimage: compact-cp resource %q entry %d has unsupported constant-pool tag %d", entryName, index, tag) + } + if size > len(data)-position { + return nil, fmt.Errorf("jimage: compact-cp resource %q entry %d value is truncated", entryName, index) + } + if err := appendOutput(tag); err != nil { + return nil, err + } + if err := appendOutput(data[position : position+size]...); err != nil { + return nil, err + } + position += size + } + } + remain := len(data) - position + computed := len(output) + remain + if uint64(computed) != uncompressedSize { + return nil, fmt.Errorf("jimage: compact-cp resource %q reconstructed %d bytes, want %d", entryName, computed, uncompressedSize) + } + if err := appendOutput(data[position:]...); err != nil { + return nil, err + } + return output, nil +} + +func compactCPConstantSize(tag byte) (int, bool) { + switch tag { + case 3, 4, 9, 10, 11, 12, 17, 18: + return 4, true + case 7, 8, 16, 19, 20: + return 2, true + case 15: + return 3, true + default: + return 0, false + } +} + +func decompressInt(data []byte, position int) (int, int, error) { + if position < 0 || position >= len(data) { + return 0, position, errors.New("truncated compressed integer") + } + first := data[position] + if first < 0x80 { + if position+4 > len(data) { + return 0, position, errors.New("truncated constant-pool index") + } + value := uint32(first)<<24 | uint32(data[position+1])<<16 | uint32(data[position+2])<<8 | uint32(data[position+3]) + return int(value), position + 4, nil + } + length := int((first & 0x60) >> 5) + if length < 1 || length > 3 { + return 0, position, fmt.Errorf("invalid compressed integer length %d", length) + } + if position+length > len(data) { + return 0, position, errors.New("truncated compressed integer") + } + value := int(first & 0x1f) + if length > 1 { + value <<= 8 * (length - 1) + for offset := 1; offset < length; offset++ { + value |= int(data[position+offset]) << (8 * (length - offset - 1)) + } + } + return value, position + length, nil +} + +func archiveName(entry Entry) (string, error) { + name := entry.Name() + if entry.Extension == "class" && !(entry.Base == "module-info" && entry.Parent == "") { + if entry.Parent != "" { + name = entry.Parent + "/" + entry.Base + "." + entry.Extension + } else { + name = entry.Base + "." + entry.Extension + } + } + if !safeArchiveName(name) { + return "", fmt.Errorf("jimage: unsafe archive entry %q", name) + } + return name, nil +} + +func safeArchiveName(name string) bool { + if name == "" || strings.HasPrefix(name, "/") || strings.Contains(name, "\\") { + return false + } + for _, part := range strings.Split(name, "/") { + if part == "" || part == "." || part == ".." { + return false + } + } + return true +} + +func normalizeName(name string) string { + name = strings.TrimPrefix(name, "/") + name = strings.TrimPrefix(name, modulesModuleName+"/") + return name +} + +func endianOrLittle(raw []byte) uint32 { + if len(raw) < 4 { + return 0 + } + return binary.LittleEndian.Uint32(raw[:4]) +} diff --git a/jimage/jimage_test.go b/jimage/jimage_test.go new file mode 100644 index 00000000..8a11391f --- /dev/null +++ b/jimage/jimage_test.go @@ -0,0 +1,366 @@ +package jimage_test + +import ( + "archive/zip" + "bytes" + "encoding/binary" + "errors" + "io" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + + "github.com/yaklang/javajive/internal/jimagefixture" + "github.com/yaklang/javajive/jimage" +) + +func buildImage(t *testing.T, entries []jimagefixture.Entry) []byte { + t.Helper() + data, err := jimagefixture.Build(entries) + if err != nil { + t.Fatalf("build JImage: %v", err) + } + return data +} + +func requireJImageIntegration(t *testing.T) { + t.Helper() + if os.Getenv("JAVAJIVE_JIMAGE_INTEGRATION") != "1" { + t.Skip("JDK/JImage integration disabled; set JAVAJIVE_JIMAGE_INTEGRATION=1 to run") + } +} + +func TestReadEntriesAndResources(t *testing.T) { + classBytes := []byte{0xca, 0xfe, 0xba, 0xbe, 1, 2, 3, 4} + resource := []byte("security.provider.1=SunSecurityProvider\n") + image := buildImage(t, []jimagefixture.Entry{ + {Path: "/java.base/java/lang/Object.class", Data: classBytes}, + {Path: "/java.base/conf/security/java.security", Data: resource}, + }) + reader, err := jimage.OpenBytes(image) + if err != nil { + t.Fatalf("OpenBytes: %v", err) + } + defer reader.Close() + + header := reader.Header() + if header.ResourceCount != 2 || header.TableLength != 2 || header.Major() != 1 || header.Minor() != 1 { + t.Fatalf("header = %#v", header) + } + entries := reader.Entries() + if len(entries) != 2 { + t.Fatalf("entries = %d, want 2", len(entries)) + } + classEntry, ok := reader.Entry("/java.base/java/lang/Object.class") + if !ok { + t.Fatal("class entry not found") + } + if classEntry.Module != "java.base" || classEntry.Parent != "java/lang" || + classEntry.Base != "Object" || classEntry.Extension != "class" || classEntry.Directory { + t.Fatalf("class entry = %#v", classEntry) + } + resourceEntry, ok := reader.Entry("/java.base/conf/security/java.security") + if !ok { + t.Fatal("resource entry not found") + } + if resourceEntry.Module != "java.base" || resourceEntry.Parent != "conf/security" || + resourceEntry.Base != "java" || resourceEntry.Extension != "security" { + t.Fatalf("resource entry = %#v", resourceEntry) + } + + for _, name := range []string{ + "/java.base/java/lang/Object.class", + "java.base/java/lang/Object.class", + "/modules/java.base/java/lang/Object.class", + } { + got, err := reader.Read(name) + if err != nil { + t.Fatalf("Read(%q): %v", name, err) + } + if !bytes.Equal(got, classBytes) { + t.Fatalf("Read(%q) = %x, want %x", name, got, classBytes) + } + } + got, err := reader.Read("java.base/conf/security/java.security") + if err != nil { + t.Fatalf("Read resource: %v", err) + } + if !bytes.Equal(got, resource) { + t.Fatalf("resource = %q, want %q", got, resource) + } +} + +func TestReadCompressedResource(t *testing.T) { + data := bytes.Repeat([]byte("compressed jimage resource "), 64) + image := buildImage(t, []jimagefixture.Entry{ + {Path: "/test/demo/Foo.class", Data: data, Compressed: true}, + }) + reader, err := jimage.OpenBytes(image) + if err != nil { + t.Fatalf("OpenBytes: %v", err) + } + defer reader.Close() + entry, ok := reader.Entry("/test/demo/Foo.class") + if !ok { + t.Fatal("entry not found") + } + if entry.CompressedSize == 0 { + t.Fatal("compressed size is zero") + } + got, err := reader.Read("/test/demo/Foo.class") + if err != nil { + t.Fatalf("Read: %v", err) + } + if !bytes.Equal(got, data) { + t.Fatalf("decompressed bytes differ") + } +} + +func TestOpenRejectsResourceCountOverTableLength(t *testing.T) { + image := buildImage(t, []jimagefixture.Entry{ + {Path: "/test/Foo.class", Data: []byte("class")}, + }) + binary.LittleEndian.PutUint32(image[12:16], ^uint32(0)) + if _, err := jimage.OpenBytes(image); err == nil || !strings.Contains(err.Error(), "resource count") { + t.Fatalf("OpenBytes error = %v, want resource count rejection", err) + } +} + +func TestReadRejectsOversizedDecompressorLayer(t *testing.T) { + image := buildImage(t, []jimagefixture.Entry{ + {Path: "/test/Foo.class", Data: []byte("class"), Compressed: true}, + }) + reader, err := jimage.Open(bytes.NewReader(image), int64(len(image)), jimage.Options{MaxResourceSize: 64}) + if err != nil { + t.Fatalf("Open: %v", err) + } + entry, ok := reader.Entry("/test/Foo.class") + if !ok { + t.Fatal("entry not found") + } + resourceStart := len(image) - int(entry.CompressedSize) + binary.LittleEndian.PutUint64(image[resourceStart+12:resourceStart+20], 65) + if _, err := reader.Read("/test/Foo.class"); err == nil || !strings.Contains(err.Error(), "uncompressed layer size") { + t.Fatalf("Read error = %v, want decompressor layer limit", err) + } +} + +func TestUnsupportedCompressor(t *testing.T) { + image := buildImage(t, []jimagefixture.Entry{ + {Path: "/test/Compact.class", Data: []byte{0xca, 0xfe, 0xba, 0xbe}, Compressed: true, Compressor: "lzma"}, + }) + reader, err := jimage.OpenBytes(image) + if err != nil { + t.Fatalf("OpenBytes: %v", err) + } + defer reader.Close() + _, err = reader.Read("/test/Compact.class") + if !errors.Is(err, jimage.ErrUnsupportedCompressor) { + t.Fatalf("error = %v, want ErrUnsupportedCompressor", err) + } + var unsupported *jimage.UnsupportedCompressorError + if !errors.As(err, &unsupported) || unsupported.Compressor != "lzma" { + t.Fatalf("error details = %#v", err) + } +} + +func TestWriteZIP(t *testing.T) { + classBytes := []byte{0xca, 0xfe, 0xba, 0xbe, 9, 8, 7} + moduleInfo := []byte{0xca, 0xfe, 0xba, 0xbe, 6, 5} + resource := []byte("key=value\n") + image := buildImage(t, []jimagefixture.Entry{ + {Path: "/test/demo/Foo.class", Data: classBytes}, + {Path: "/test/conf/app.properties", Data: resource}, + {Path: "/java.base/module-info.class", Data: moduleInfo}, + }) + reader, err := jimage.OpenBytes(image) + if err != nil { + t.Fatalf("OpenBytes: %v", err) + } + defer reader.Close() + jarBytes, err := reader.ZIPBytes() + if err != nil { + t.Fatalf("ZIPBytes: %v", err) + } + zipReader, err := zip.NewReader(bytes.NewReader(jarBytes), int64(len(jarBytes))) + if err != nil { + t.Fatalf("open JAR: %v", err) + } + want := map[string][]byte{ + "demo/Foo.class": classBytes, + "test/conf/app.properties": resource, + "java.base/module-info.class": moduleInfo, + } + if len(zipReader.File) != len(want) { + t.Fatalf("JAR entries = %d, want %d", len(zipReader.File), len(want)) + } + for _, file := range zipReader.File { + expected, ok := want[file.Name] + if !ok { + t.Fatalf("unexpected JAR entry %q", file.Name) + } + stream, err := file.Open() + if err != nil { + t.Fatalf("open %q: %v", file.Name, err) + } + body, err := io.ReadAll(stream) + stream.Close() + if err != nil { + t.Fatalf("read %q: %v", file.Name, err) + } + if !bytes.Equal(body, expected) { + t.Fatalf("JAR entry %q = %x, want %x", file.Name, body, expected) + } + } +} + +func TestWriteZIPRejectsClassCollision(t *testing.T) { + image := buildImage(t, []jimagefixture.Entry{ + {Path: "/module.a/demo/Foo.class", Data: []byte{1}}, + {Path: "/module.b/demo/Foo.class", Data: []byte{2}}, + }) + reader, err := jimage.OpenBytes(image) + if err != nil { + t.Fatalf("OpenBytes: %v", err) + } + defer reader.Close() + if _, err := reader.ZIPBytes(); err == nil || !strings.Contains(err.Error(), "collides") { + t.Fatalf("error = %v, want collision", err) + } +} + +func TestOpenJDKImage(t *testing.T) { + requireJImageIntegration(t) + + _, home := findJDK(t) + path := filepath.Join(home, "lib", "modules") + if _, err := os.Stat(path); err != nil { + t.Skipf("JDK image not found at %s", path) + } + reader, err := jimage.OpenFile(path) + if err != nil { + t.Fatalf("OpenFile: %v", err) + } + defer reader.Close() + if reader.Header().ResourceCount < 1000 { + t.Fatalf("resource count = %d, want a full JDK image", reader.Header().ResourceCount) + } + object, err := reader.Read("java.base/java/lang/Object.class") + if err != nil { + t.Fatalf("Read Object.class: %v", err) + } + if !bytes.HasPrefix(object, []byte{0xca, 0xfe, 0xba, 0xbe}) { + t.Fatalf("Object.class magic = %x", object[:4]) + } +} + +func findJDK(t *testing.T) (jlink, home string) { + t.Helper() + if home := os.Getenv("JAVA_HOME"); home != "" { + candidate := filepath.Join(home, "bin", "jlink") + if _, err := os.Stat(candidate); err == nil { + return candidate, home + } + } + if output, err := exec.Command("/usr/libexec/java_home").Output(); err == nil { + home := strings.TrimSpace(string(output)) + candidate := filepath.Join(home, "bin", "jlink") + if _, err := os.Stat(candidate); err == nil { + return candidate, home + } + } + path, err := exec.LookPath("jlink") + if err != nil { + t.Skip("jlink not available") + } + if resolved, err := filepath.EvalSymlinks(path); err == nil { + path = resolved + } + home = filepath.Dir(filepath.Dir(path)) + if _, err := os.Stat(filepath.Join(home, "lib", "modules")); err != nil { + t.Skipf("JDK runtime image not found next to %s", path) + } + return path, home +} + +func runJLink(t *testing.T, jlink string, args ...string) { + t.Helper() + output, err := exec.Command(jlink, args...).CombinedOutput() + if err != nil { + t.Fatalf("jlink %s failed: %v\n%s", strings.Join(args, " "), err, output) + } +} + +func TestJLinkCompactCPImage(t *testing.T) { + requireJImageIntegration(t) + + jlink, home := findJDK(t) + plainPath := filepath.Join(home, "lib", "modules") + if _, err := os.Stat(plainPath); err != nil { + t.Skipf("JDK runtime image not found at %s", plainPath) + } + output := filepath.Join(t.TempDir(), "image") + runJLink(t, jlink, "--compress=1", "--add-modules", "java.base", "--output", output, "--no-header-files", "--no-man-pages") + + compact, err := jimage.OpenFile(filepath.Join(output, "lib", "modules")) + if err != nil { + t.Fatalf("open compact-cp image: %v", err) + } + defer compact.Close() + plain, err := jimage.OpenFile(plainPath) + if err != nil { + t.Fatalf("open plain image: %v", err) + } + defer plain.Close() + + name := "java.base/java/lang/Object.class" + got, err := compact.Read(name) + if err != nil { + t.Fatalf("read compact-cp Object.class: %v", err) + } + want, err := plain.Read(name) + if err != nil { + t.Fatalf("read plain Object.class: %v", err) + } + if !bytes.Equal(got, want) { + t.Fatalf("compact-cp %s differs from the plain image", name) + } +} + +func TestJLinkBigEndianImage(t *testing.T) { + requireJImageIntegration(t) + + jlink, home := findJDK(t) + plainPath := filepath.Join(home, "lib", "modules") + if _, err := os.Stat(plainPath); err != nil { + t.Skipf("JDK runtime image not found at %s", plainPath) + } + output := filepath.Join(t.TempDir(), "image") + runJLink(t, jlink, "--compress=0", "--endian", "big", "--add-modules", "java.base", "--output", output, "--no-header-files", "--no-man-pages") + + bigEndian, err := jimage.OpenFile(filepath.Join(output, "lib", "modules")) + if err != nil { + t.Fatalf("open big-endian image: %v", err) + } + defer bigEndian.Close() + plain, err := jimage.OpenFile(plainPath) + if err != nil { + t.Fatalf("open plain image: %v", err) + } + defer plain.Close() + + name := "java.base/java/lang/Object.class" + got, err := bigEndian.Read(name) + if err != nil { + t.Fatalf("read big-endian Object.class: %v", err) + } + want, err := plain.Read(name) + if err != nil { + t.Fatalf("read plain Object.class: %v", err) + } + if !bytes.Equal(got, want) { + t.Fatalf("big-endian %s differs from the plain image", name) + } +} diff --git a/test/cross/irreducible_cfg_roundtrip_test.go b/test/cross/irreducible_cfg_roundtrip_test.go index 9e2993de..8a6479ed 100644 --- a/test/cross/irreducible_cfg_roundtrip_test.go +++ b/test/cross/irreducible_cfg_roundtrip_test.go @@ -110,6 +110,42 @@ type irreducibleEdge struct { Kind string `json:"kind"` } +func TestFixedIrreducibleCFGCorpusPureGo(t *testing.T) { + manifest, manifestBytes := readIrreducibleManifest(t) + assertIrreducibleCorpusInventory(t, manifest) + assertIrreducibleChecksums(t, manifest, manifestBytes) + assertIrreducibleGeneratorDeterminism(t, manifest) + + classes := make(map[string][]byte, len(manifest.Cases)) + for _, fixture := range manifest.Cases { + raw := mustReadIrreducibleFile(t, fixture.ClassFile) + classes[fixture.Name] = raw + assertIrreducibleClassfile(t, manifest, fixture, raw) + } + resolver := func(internalName string) ([]byte, bool) { + data, ok := classes[internalName] + return data, ok + } + for _, mode := range []classparser.DecompileMode{classparser.Precision, classparser.Compatibility} { + for _, fixture := range manifest.Cases { + result, err := classparser.DecompileWithOptions(classes[fixture.Name], classparser.DecompileOptions{ + Mode: mode, Resolve: resolver, TargetSourceVersion: 8, EnvSnapshot: map[string]string{}, + Limits: classparser.Limits{ + MaxInputBytes: 1 << 20, MaxReadBytes: 1 << 20, MaxParseItems: 1_000_000, + MaxGraphScans: 1_000_000, MaxGraphEdges: 1_000_000, MaxSetElementWork: 10_000_000, + MaxRequestWork: 100_000_000, MaxOutputBytes: 1 << 20, MaxASTDepth: 10_000, + MaxDiagnostics: 64, MaxNodeCopies: 1_000_000, + }, + }) + if err != nil { + t.Fatalf("%s/%s: status=%q diagnostics=%+v error=%v", mode, fixture.Name, result.Status, result.Diagnostics, err) + } + assertHealthyIrreducibleDecompile(t, fixture.Name, mode, 0, result) + assertIrreducibleSourceBaseline(t, fixture.Name, mode, []byte(result.Source)) + } + } +} + func TestRoundTripIrreducibleCFGCorpus(t *testing.T) { manifest, manifestBytes := readIrreducibleManifest(t) assertIrreducibleCorpusInventory(t, manifest) diff --git a/test/external/external_test.go b/test/external/external_test.go new file mode 100644 index 00000000..44ffc524 --- /dev/null +++ b/test/external/external_test.go @@ -0,0 +1,389 @@ +package external_test + +import ( + "bytes" + "fmt" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + + classparser "github.com/yaklang/javajive/classparser" + "github.com/yaklang/javajive/classparser/jarwar" + "github.com/yaklang/javajive/dex2jar" + "github.com/yaklang/javajive/inspect" + "github.com/yaklang/javajive/internal/inputkind" + "github.com/yaklang/javajive/internal/testfixtures" + "github.com/yaklang/javajive/jimage" +) + +type sampleCase struct { + name string + kind inputkind.Kind + status inspect.Status +} + +var externalSamples = []sampleCase{ + {"tomcat-context.war", inputkind.WAR, inspect.StatusComplete}, + {"tomcat-sample.war", inputkind.WAR, inspect.StatusComplete}, + {"tomcat-broken.war", inputkind.WAR, inspect.StatusComplete}, + {"bundletool-app.apk", inputkind.APK, inspect.StatusComplete}, + {"bundletool-install-time.aab", inputkind.AAB, inspect.StatusComplete}, + {"bundletool-universal.apks", inputkind.APKS, inspect.StatusComplete}, + {"bundletool-splits.apks", inputkind.APKS, inspect.StatusComplete}, + {"androguard-invalid.apk", inputkind.APK, inspect.StatusComplete}, + {"androguard-test-debug.apk", inputkind.APK, inspect.StatusComplete}, + {"androguard-tc-debug.apk", inputkind.APK, inspect.StatusComplete}, + {"dex2jar-dex038.dex", inputkind.DEX, inspect.StatusPartial}, + {"dex2jar-dex039.dex", inputkind.DEX, inspect.StatusPartial}, + {"apktool-dynamic-dex.apk", inputkind.APK, inspect.StatusPartial}, + {"apktool-issue2543.dex", inputkind.DEX, inspect.StatusComplete}, + {"androidx-tracing-1.2.0.aar", inputkind.AAR, inspect.StatusComplete}, + {"sample.xapk", inputkind.XAPK, inspect.StatusComplete}, + {"sample.apkm", inputkind.APKM, inspect.StatusComplete}, + {"sample.ear", inputkind.EAR, inspect.StatusComplete}, +} + +func requireExternalEval(t *testing.T) { + t.Helper() + if os.Getenv("JAVAJIVE_EXTERNAL_EVAL") != "1" { + t.Skip("external corpus evaluation disabled; set JAVAJIVE_EXTERNAL_EVAL=1 to run") + } +} + +func requireJImageIntegration(t *testing.T) { + t.Helper() + if os.Getenv("JAVAJIVE_JIMAGE_INTEGRATION") != "1" { + t.Skip("JDK/JImage integration disabled; set JAVAJIVE_JIMAGE_INTEGRATION=1 to run") + } +} + +func readSample(t *testing.T, name string) []byte { + t.Helper() + data, err := os.ReadFile(testfixtures.Path(name)) + if err != nil { + t.Fatalf("read %s: %v", name, err) + } + return data +} + +func TestExternalSamplesClassifyAndInspect(t *testing.T) { + requireExternalEval(t) + + for _, sample := range externalSamples { + t.Run(sample.name, func(t *testing.T) { + data := readSample(t, sample.name) + if kind := inputkind.DetectBytes(data, sample.name); kind != sample.kind { + t.Fatalf("classification = %q, want %q", kind, sample.kind) + } + report := inspect.AnalyzeWithOptions(data, sample.name, inspect.Options{Disassembly: false}) + if report.Artifact.Format != string(sample.kind) { + t.Fatalf("inspect format = %q, want %q", report.Artifact.Format, sample.kind) + } + if report.Status != sample.status { + t.Fatalf("inspect status = %q, want %q (%#v)", report.Status, sample.status, report.Diagnostics) + } + if sample.status == inspect.StatusPartial && len(report.Diagnostics) == 0 { + t.Fatal("partial report has no diagnostics") + } + }) + } +} + +func TestExternalDecompileJavaArchives(t *testing.T) { + requireExternalEval(t) + + t.Run("war", func(t *testing.T) { + dst := t.TempDir() + if err := jarwar.AutoDecompile(testfixtures.Path("tomcat-sample.war"), dst); err != nil { + t.Fatalf("decompile WAR: %v", err) + } + body, err := os.ReadFile(filepath.Join(dst, "WEB-INF", "classes", "mypackage", "Hello.java")) + if err != nil { + t.Fatalf("read WAR source: %v", err) + } + if !strings.Contains(string(body), "class Hello") { + t.Fatalf("unexpected WAR source:\n%s", body) + } + }) + + t.Run("aar", func(t *testing.T) { + dst := t.TempDir() + if err := jarwar.AutoDecompile(testfixtures.Path("androidx-tracing-1.2.0.aar"), dst); err != nil { + t.Fatalf("decompile AAR: %v", err) + } + body, err := os.ReadFile(filepath.Join(dst, "classes.jar", "androidx", "tracing", "Trace.java")) + if err != nil { + t.Fatalf("read AAR source: %v", err) + } + if !strings.Contains(string(body), "Trace") { + t.Fatalf("unexpected AAR source:\n%s", body) + } + }) + + t.Run("ear flat", func(t *testing.T) { + dst := t.TempDir() + if err := jarwar.AutoDecompile(testfixtures.Path("sample.ear"), dst); err != nil { + t.Fatalf("decompile EAR: %v", err) + } + body, err := os.ReadFile(filepath.Join(dst, "EAR", "lib", "sample.jar", "mypackage", "Hello.java")) + if err != nil { + t.Fatalf("read flat EAR source: %v", err) + } + if !strings.Contains(string(body), "class Hello") { + t.Fatalf("unexpected flat EAR source:\n%s", body) + } + }) + + t.Run("ear structured", func(t *testing.T) { + dst := t.TempDir() + report, err := jarwar.AutoDecompileWithOptions(testfixtures.Path("sample.ear"), dst, jarwar.ArchiveOptions{Structured: true}) + if err != nil { + t.Fatalf("structured EAR export: %v", err) + } + if len(report.Archives) != 1 || report.Archives[0].Path != "EAR/lib/sample.jar" { + t.Fatalf("nested archives = %#v", report.Archives) + } + body, err := os.ReadFile(filepath.Join(dst, "sources", "EAR", "lib", "sample.jar!", "mypackage", "Hello.java")) + if err != nil { + t.Fatalf("read structured EAR source: %v", err) + } + if !strings.Contains(string(body), "class Hello") { + t.Fatalf("unexpected structured EAR source:\n%s", body) + } + }) +} + +func TestExternalAndroidTranslation(t *testing.T) { + requireExternalEval(t) + + cases := []struct { + name string + dexFiles int + classes int + }{ + {"bundletool-app.apk", 1, 10}, + {"bundletool-install-time.aab", 3, 1298}, + {"bundletool-universal.apks", 3, 1298}, + {"bundletool-splits.apks", 4, 1298}, + {"androguard-test-debug.apk", 1, 7}, + {"androguard-tc-debug.apk", 1, 13}, + {"androguard-invalid.apk", 1, 286}, + {"apktool-issue2543.dex", 1, 1}, + {"sample.xapk", 1, 10}, + {"sample.apkm", 1, 10}, + } + for _, test := range cases { + t.Run(test.name, func(t *testing.T) { + dst := filepath.Join(t.TempDir(), "classes.jar") + report, err := dex2jar.DexFileToJar(testfixtures.Path(test.name), dst, dex2jar.Options{}) + if err != nil { + t.Fatalf("DexFileToJar: %v", err) + } + if report.DEXFiles != test.dexFiles || report.Classes != test.classes { + t.Fatalf("report = %#v, want %d DEX / %d classes", report, test.dexFiles, test.classes) + } + if _, err := os.Stat(dst); err != nil { + t.Fatalf("output JAR: %v", err) + } + }) + } +} + +func TestExternalAndroidRejections(t *testing.T) { + requireExternalEval(t) + + cases := []struct { + name string + contains string + }{ + {"dex2jar-dex038.dex", "call_site_id"}, + {"dex2jar-dex039.dex", "method_handle"}, + {"apktool-dynamic-dex.apk", "SHA-1"}, + } + for _, test := range cases { + t.Run(test.name, func(t *testing.T) { + dst := filepath.Join(t.TempDir(), "classes.jar") + _, err := dex2jar.DexFileToJar(testfixtures.Path(test.name), dst, dex2jar.Options{}) + if err == nil || !strings.Contains(err.Error(), test.contains) { + t.Fatalf("error = %v, want %q", err, test.contains) + } + if _, statErr := os.Stat(dst); !os.IsNotExist(statErr) { + t.Fatalf("transactional failure left an output JAR: %v", statErr) + } + }) + } +} + +func TestExternalRenamedSamples(t *testing.T) { + requireExternalEval(t) + + cases := []struct { + name string + file string + kind inputkind.Kind + }{ + {"bundletool-app.apk", "renamed.zip", inputkind.APK}, + {"bundletool-install-time.aab", "renamed.zip", inputkind.AAB}, + {"bundletool-universal.apks", "renamed.zip", inputkind.APKS}, + {"tomcat-sample.war", "renamed.zip", inputkind.WAR}, + {"androidx-tracing-1.2.0.aar", "renamed.zip", inputkind.AAR}, + {"sample.ear", "renamed.zip", inputkind.EAR}, + {"sample.xapk", "renamed.apkx", inputkind.XAPK}, + {"sample.apkm", "renamed.zip", inputkind.APKM}, + } + for _, test := range cases { + t.Run(test.name, func(t *testing.T) { + data := readSample(t, test.name) + if kind := inputkind.DetectBytes(data, test.file); kind != test.kind { + t.Fatalf("renamed classification = %q, want %q", kind, test.kind) + } + }) + } +} + +func jdkHome(t *testing.T) string { + t.Helper() + candidates := make([]string, 0, 3) + if home := os.Getenv("JAVA_HOME"); home != "" { + candidates = append(candidates, home) + } + if output, err := exec.Command("/usr/libexec/java_home").Output(); err == nil { + candidates = append(candidates, strings.TrimSpace(string(output))) + } + if javac, err := exec.LookPath("javac"); err == nil { + if resolved, err := filepath.EvalSymlinks(javac); err == nil { + javac = resolved + } + candidates = append(candidates, filepath.Dir(filepath.Dir(javac))) + } + for _, home := range candidates { + if _, err := os.Stat(filepath.Join(home, "lib", "modules")); err == nil { + return home + } + } + t.Skip("no JDK runtime image available") + return "" +} + +func TestExternalJModAndJImage(t *testing.T) { + requireJImageIntegration(t) + + home := jdkHome(t) + + t.Run("jmod", func(t *testing.T) { + path := filepath.Join(home, "jmods", "java.base.jmod") + if _, err := os.Stat(path); err != nil { + t.Skipf("java.base.jmod not found: %v", err) + } + jarFS, err := classparser.NewJarFSFromLocal(path) + if err != nil { + t.Fatalf("open JMOD: %v", err) + } + defer jarFS.Close() + source, err := jarFS.ReadFile("classes/java/lang/Object.class") + if err != nil { + t.Fatalf("decompile JMOD Object.class: %v", err) + } + if !strings.Contains(string(source), "class Object") { + t.Fatalf("unexpected JMOD source:\n%s", source) + } + }) + + t.Run("jimage", func(t *testing.T) { + path := filepath.Join(home, "lib", "modules") + reader, err := jimage.OpenFile(path) + if err != nil { + t.Fatalf("open JImage: %v", err) + } + defer reader.Close() + object, err := reader.Read("java.base/java/lang/Object.class") + if err != nil { + t.Fatalf("read JImage Object.class: %v", err) + } + if !bytes.HasPrefix(object, []byte{0xca, 0xfe, 0xba, 0xbe}) { + t.Fatalf("JImage Object.class magic = %x", object[:4]) + } + }) +} + +func TestExternalUnsupportedDEXVersion040(t *testing.T) { + requireExternalEval(t) + + data := readSample(t, "apktool-issue2543.dex") + if len(data) < 8 { + t.Fatal("DEX fixture is too short") + } + data[4], data[5], data[6], data[7] = '0', '4', '0', 0 + if _, _, err := dex2jar.DexToJar(data, dex2jar.Options{}); err == nil || !strings.Contains(err.Error(), `unsupported DEX version "040"`) { + t.Fatalf("DexToJar error = %v", err) + } + report := inspect.AnalyzeWithOptions(data, "version-040.dex", inspect.Options{Disassembly: false}) + if report.Status != inspect.StatusPartial { + t.Fatalf("inspect status = %q, want partial", report.Status) + } +} + +func mustNotPanic(t *testing.T, label string, action func()) { + t.Helper() + defer func() { + if recovered := recover(); recovered != nil { + t.Fatalf("%s panicked: %v", label, recovered) + } + }() + action() +} + +func TestExternalMalformedTruncations(t *testing.T) { + requireExternalEval(t) + + samples := []string{ + "tomcat-sample.war", + "tomcat-broken.war", + "bundletool-app.apk", + "androguard-test-debug.apk", + "apktool-dynamic-dex.apk", + "dex2jar-dex038.dex", + "dex2jar-dex039.dex", + "apktool-issue2543.dex", + "androidx-tracing-1.2.0.aar", + "sample.xapk", + "sample.apkm", + "sample.ear", + } + options := dex2jar.Options{ + MaxDEXSize: 1 << 20, + MaxAPKSize: 2 << 20, + MaxTotalDEXSize: 2 << 20, + MaxDEXFiles: 8, + MaxNestedAPKs: 8, + } + for _, name := range samples { + data := readSample(t, name) + lengths := []int{0, 1, 4, 8, len(data) / 4, len(data) / 2, len(data) - 1} + seen := make(map[int]bool) + for _, length := range lengths { + if length < 0 || length > len(data) || seen[length] { + continue + } + seen[length] = true + truncated := data[:length] + label := fmt.Sprintf("%s/%d", name, length) + mustNotPanic(t, label+" classify", func() { + _ = inputkind.DetectBytes(truncated, name) + }) + mustNotPanic(t, label+" inspect", func() { + _ = inspect.AnalyzeWithOptions(truncated, name, inspect.Options{Disassembly: false}) + }) + mustNotPanic(t, label+" dex classify", func() { + _ = dex2jar.ClassifyInput(truncated, name) + }) + if inputkind.IsAndroid(inputkind.DetectBytes(truncated, name)) { + mustNotPanic(t, label+" dex convert", func() { + _, _, _ = dex2jar.DexToJar(truncated, options) + }) + } + } + } +} diff --git a/testdata/external/README.md b/testdata/external/README.md new file mode 100644 index 00000000..ec12df65 --- /dev/null +++ b/testdata/external/README.md @@ -0,0 +1,131 @@ +# External container samples + +Real-world Java and Android container files used by `test/external` and the +package-level format tests. The files are treated as **data only**; tests parse +them and never execute their contents. + +## Running the opt-in tests + +The real external corpus is excluded from default test runs. Run it explicitly +with: + +```bash +JAVAJIVE_EXTERNAL_EVAL=1 go test ./test/external +``` + +Tests that read a locally installed JDK runtime image or generate images with +`jlink` are independently opt-in: + +```bash +JAVAJIVE_JIMAGE_INTEGRATION=1 go test ./jimage ./test/external +``` + +Synthetic JImage unit tests remain part of ordinary `go test ./jimage` runs. + +## Sources and licenses + +All samples come from Apache-2.0 projects. Keep the source URL in this file when +replacing a sample. + +| File | Source | License | +| --- | --- | --- | +| `tomcat-context.war` | | Apache-2.0 | +| `tomcat-sample.war` | | Apache-2.0 | +| `tomcat-broken.war` | | Apache-2.0 | +| `bundletool-app.apk` | `google/bundletool` `src/test/resources/.../apk/com.test.app.apk` | Apache-2.0 | +| `bundletool-install-time.aab` | `google/bundletool` `src/test/resources/.../bundle/install-time-permanent-modules.aab` | Apache-2.0 | +| `bundletool-universal.apks` | Generated from `bundletool-install-time.aab` with bundletool 1.18.3 (`--mode=universal`) | Apache-2.0 | +| `bundletool-splits.apks` | Generated from `bundletool-install-time.aab` with bundletool 1.18.3 (`--mode=default`) | Apache-2.0 | +| `androguard-invalid.apk` | | Apache-2.0 | +| `androguard-test-debug.apk` | | Apache-2.0 | +| `androguard-tc-debug.apk` | | Apache-2.0 | +| `dex2jar-dex038.dex` | | Apache-2.0 | +| `dex2jar-dex039.dex` | | Apache-2.0 | +| `apktool-dynamic-dex.apk` | | Apache-2.0 | +| `apktool-issue2543.dex` | | Apache-2.0 | +| `androidx-tracing-1.2.0.aar` | | Apache-2.0 | +| `sample.xapk` | Synthetic XAPK built from `bundletool-app.apk` plus a resource-only split | Apache-2.0 | +| `sample.apkm` | Synthetic APKM built from `bundletool-app.apk` plus a resource-only split | Apache-2.0 | +| `sample.ear` | Synthetic EAR built from `tomcat-sample.war` plus a nested JAR | Apache-2.0 | + +## Expected behavior + +| Sample | Classification | Inspection | Operation | +| --- | --- | --- | --- | +| `tomcat-context.war` | `war` | complete | resource-only archive | +| `tomcat-sample.war` | `war` | complete | flat/structured export yields `WEB-INF/classes/mypackage/Hello.java` | +| `tomcat-broken.war` | `war` | complete | valid ZIP; the broken part is the web descriptor | +| `bundletool-app.apk` | `apk` | complete | `dex2jar` converts 1 DEX / 10 classes | +| `bundletool-install-time.aab` | `aab` | complete | `dex2jar` converts 3 DEX / 1,298 classes | +| `bundletool-universal.apks` | `apks` | complete | `dex2jar` prefers `universal.apk`; 3 DEX / 1,298 classes | +| `bundletool-splits.apks` | `apks` | complete | 181 nested APKs; 4 DEX / 1,298 classes after split dedupe | +| `androguard-invalid.apk` | `apk` | complete | valid DEX despite the fixture name; 286 classes | +| `androguard-test-debug.apk` | `apk` | complete | 7 classes | +| `androguard-tc-debug.apk` | `apk` | complete | 13 classes | +| `dex2jar-dex038.dex` | `dex` | partial | `dex2jar` rejects the `call_site_id` section (strict subset) | +| `dex2jar-dex039.dex` | `dex` | partial | `dex2jar` rejects the `method_handle` section (strict subset) | +| `apktool-dynamic-dex.apk` | `apk` | partial | `dex2jar` rejects the DEX SHA-1 mismatch | +| `apktool-issue2543.dex` | `dex` | complete | 1 class / 1 method | +| `androidx-tracing-1.2.0.aar` | `aar` | complete | AAR export decompiles `classes.jar` (3 classes) | +| `sample.xapk` | `xapk` | complete | `dex2jar` converts 1 DEX / 10 classes | +| `sample.apkm` | `apkm` | complete | `dex2jar` converts 1 DEX / 10 classes | +| `sample.ear` | `ear` | complete | `EAR/lib/sample.jar!/mypackage/Hello.java` is decompiled | + +## Regenerating the generated samples + +`bundletool-universal.apks` and `bundletool-splits.apks`: + +```bash +java -jar bundletool-all-1.18.3.jar build-apks \ + --bundle=bundletool-install-time.aab \ + --output=bundletool-universal.apks --mode=universal --overwrite +java -jar bundletool-all-1.18.3.jar build-apks \ + --bundle=bundletool-install-time.aab \ + --output=bundletool-splits.apks --mode=default --overwrite +``` + +`sample.xapk`, `sample.apkm`, and `sample.ear` were built with this Python +script (standard library only): + +```python +import io, json, sys, zipfile + +base_apk, war, outdir = sys.argv[1], sys.argv[2], sys.argv[3] + +def zip_bytes(entries): + buf = io.BytesIO() + with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as z: + for name, data in entries: + z.writestr(name, data) + return buf.getvalue() + +apk = open(base_apk, "rb").read() +resource_apk = zip_bytes([("res/raw/config.txt", b"config")]) + +open(f"{outdir}/sample.xapk", "wb").write(zip_bytes([ + ("manifest.json", json.dumps({"xapk_version": 2, "package_name": "com.test.app"}).encode()), + ("base.apk", apk), + ("config.en.apk", resource_apk), + ("icon.png", b"\x89PNG\r\n\x1a\n"), +])) +open(f"{outdir}/sample.apkm", "wb").write(zip_bytes([ + ("info.json", json.dumps({"name": "sample", "package_name": "com.test.app"}).encode()), + ("base.apk", apk), + ("split_config.en.apk", resource_apk), +])) + +with zipfile.ZipFile(war) as z: + hello = z.read("WEB-INF/classes/mypackage/Hello.class") +sample_jar = zip_bytes([ + ("META-INF/MANIFEST.MF", b"Manifest-Version: 1.0\r\n\r\n"), + ("mypackage/Hello.class", hello), +]) +open(f"{outdir}/sample.ear", "wb").write(zip_bytes([ + ("META-INF/application.xml", b'\n\n'), + ("EAR/lib/sample.jar", sample_jar), +])) +``` + +The real 181-APK split bundle is useful for checking the nested-APK bound; the +translator default is 512 nested APKs and the test asserts the split bundle +translates the same 1,298 classes as the universal bundle. diff --git a/testdata/external/androguard-invalid.apk b/testdata/external/androguard-invalid.apk new file mode 100644 index 00000000..c2911308 Binary files /dev/null and b/testdata/external/androguard-invalid.apk differ diff --git a/testdata/external/androguard-tc-debug.apk b/testdata/external/androguard-tc-debug.apk new file mode 100644 index 00000000..cc0fb744 Binary files /dev/null and b/testdata/external/androguard-tc-debug.apk differ diff --git a/testdata/external/androguard-test-debug.apk b/testdata/external/androguard-test-debug.apk new file mode 100644 index 00000000..4d279549 Binary files /dev/null and b/testdata/external/androguard-test-debug.apk differ diff --git a/testdata/external/androidx-tracing-1.2.0.aar b/testdata/external/androidx-tracing-1.2.0.aar new file mode 100644 index 00000000..3fbd0184 Binary files /dev/null and b/testdata/external/androidx-tracing-1.2.0.aar differ diff --git a/testdata/external/apktool-dynamic-dex.apk b/testdata/external/apktool-dynamic-dex.apk new file mode 100644 index 00000000..eb2345de Binary files /dev/null and b/testdata/external/apktool-dynamic-dex.apk differ diff --git a/testdata/external/apktool-issue2543.dex b/testdata/external/apktool-issue2543.dex new file mode 100644 index 00000000..69666d69 Binary files /dev/null and b/testdata/external/apktool-issue2543.dex differ diff --git a/testdata/external/bundletool-app.apk b/testdata/external/bundletool-app.apk new file mode 100644 index 00000000..bfd089a7 Binary files /dev/null and b/testdata/external/bundletool-app.apk differ diff --git a/testdata/external/bundletool-install-time.aab b/testdata/external/bundletool-install-time.aab new file mode 100644 index 00000000..85054814 Binary files /dev/null and b/testdata/external/bundletool-install-time.aab differ diff --git a/testdata/external/bundletool-splits.apks b/testdata/external/bundletool-splits.apks new file mode 100644 index 00000000..dd4835a4 Binary files /dev/null and b/testdata/external/bundletool-splits.apks differ diff --git a/testdata/external/bundletool-universal.apks b/testdata/external/bundletool-universal.apks new file mode 100644 index 00000000..f04e0f7b Binary files /dev/null and b/testdata/external/bundletool-universal.apks differ diff --git a/testdata/external/dex2jar-dex038.dex b/testdata/external/dex2jar-dex038.dex new file mode 100644 index 00000000..54ee2641 Binary files /dev/null and b/testdata/external/dex2jar-dex038.dex differ diff --git a/testdata/external/dex2jar-dex039.dex b/testdata/external/dex2jar-dex039.dex new file mode 100644 index 00000000..7902f019 Binary files /dev/null and b/testdata/external/dex2jar-dex039.dex differ diff --git a/testdata/external/sample.apkm b/testdata/external/sample.apkm new file mode 100644 index 00000000..9797d677 Binary files /dev/null and b/testdata/external/sample.apkm differ diff --git a/testdata/external/sample.ear b/testdata/external/sample.ear new file mode 100644 index 00000000..be995d16 Binary files /dev/null and b/testdata/external/sample.ear differ diff --git a/testdata/external/sample.xapk b/testdata/external/sample.xapk new file mode 100644 index 00000000..7ebac019 Binary files /dev/null and b/testdata/external/sample.xapk differ diff --git a/testdata/external/tomcat-broken.war b/testdata/external/tomcat-broken.war new file mode 100644 index 00000000..09b67885 Binary files /dev/null and b/testdata/external/tomcat-broken.war differ diff --git a/testdata/external/tomcat-context.war b/testdata/external/tomcat-context.war new file mode 100644 index 00000000..677c1a63 Binary files /dev/null and b/testdata/external/tomcat-context.war differ diff --git a/testdata/external/tomcat-sample.war b/testdata/external/tomcat-sample.war new file mode 100644 index 00000000..b8793998 Binary files /dev/null and b/testdata/external/tomcat-sample.war differ diff --git a/tools/ci_scheduler/workflow_inventory.py b/tools/ci_scheduler/workflow_inventory.py index de013d08..98ae2d5b 100644 --- a/tools/ci_scheduler/workflow_inventory.py +++ b/tools/ci_scheduler/workflow_inventory.py @@ -46,36 +46,19 @@ def required_coverage_snapshot(repo_root: Path) -> dict[str, Any]: } -# One scope decision gates the classparser matrix (ten shards when the diff -# touches its closure), which feeds the required algorithm-regression summary -# together with the concurrently running regression suite. Full task contracts, -# platform builds, and historical-JAR audits remain available through the -# explicit task-gates / extended / untrusted-oracle workflows. -BASELINE_CI_JOBS = ("scope", "source", "regression", "gate") - -# These are reviewed authored-fixture suites, not a promotion of the external -# historical corpus. Keep every selector explicit: a prefix could accidentally -# select a newly added foreign-JAR test in this mixed package. -FAST_REBUILT_JAR_TESTS = ( - "TestRebuiltJarRuntimeSelectionPreservesOriginalAuthority", - "TestRebuiltJarRejectsUnknownMetadataAndKeepsPlainPacking", -) -FAST_REBUILT_JAR_COMMAND = ( - "go test -json ./test/cross -run '^(" - + "|".join(FAST_REBUILT_JAR_TESTS) - + ")$' -count=1 -timeout=2m | tee artifacts/rebuilt-jar-runtime-tests.jsonl" -) -IRREDUCIBLE_CFG_TEST = "TestRoundTripIrreducibleCFGCorpus" -IRREDUCIBLE_CFG_LIST_COMMAND = ( - "test \"$(go test ./test/cross -list '^TestRoundTripIrreducibleCFGCorpus$' " - "| grep -xc 'TestRoundTripIrreducibleCFGCorpus')\" -eq 1" -) -IRREDUCIBLE_CFG_RUN_COMMAND = ( - "go test -json ./test/cross -run '^TestRoundTripIrreducibleCFGCorpus$' " - "-count=1 -timeout=3m | tee artifacts/irreducible-cfg-roundtrip-tests.jsonl" -) +# Required PR feedback is four sealed pure-Go gates plus one summary. Full task +# contracts, live runtime/compiler checks, platform builds, and historical-JAR +# audits remain available through explicit manual workflows. +BASELINE_CI_JOBS = ("contract", "corpus", "algorithm", "dex", "regression") + +# Cross-package fixture selection is owned by the sealed Go inventory. The +# required workflow must never invoke the mixed cross package directly. +FAST_REBUILT_JAR_TESTS = () +FAST_REBUILT_JAR_COMMAND = "" +IRREDUCIBLE_CFG_TEST = "TestFixedIrreducibleCFGCorpusPureGo" +IRREDUCIBLE_CFG_LIST_COMMAND = "go run ./tools/requiredci -check" +IRREDUCIBLE_CFG_RUN_COMMAND = "go run ./tools/requiredci -run corpus" REQUIRED_CROSS_COMMANDS = ( - FAST_REBUILT_JAR_COMMAND, IRREDUCIBLE_CFG_LIST_COMMAND, IRREDUCIBLE_CFG_RUN_COMMAND, ) @@ -88,9 +71,12 @@ def validate_fast_cross_scope(workflow_text: str) -> None: External JAR discovery, broad package tests and extra commands still need their separately reviewed manual isolation workflow. """ - commands = [line.strip() for line in workflow_text.splitlines() if "./test/cross" in line] - if commands != list(REQUIRED_CROSS_COMMANDS): - raise ValueError("required cross-package tests must select exactly the reviewed authored fixture roots") + if "./test/cross" in workflow_text: + raise ValueError("required workflow must delegate mixed cross-package selection to requiredci") + commands = [line.strip().removeprefix("- run: ") for line in workflow_text.splitlines() if "go run ./tools/requiredci" in line] + for command in REQUIRED_CROSS_COMMANDS: + if commands.count(command) != 1: + raise ValueError("required workflow must run the sealed corpus inventory exactly once") def action_pins(workflow: Path) -> list[dict[str, Any]]: diff --git a/tools/requiredci/main.go b/tools/requiredci/main.go new file mode 100644 index 00000000..dd5435f7 --- /dev/null +++ b/tools/requiredci/main.go @@ -0,0 +1,892 @@ +// Command requiredci owns the reviewed, fail-closed test inventory for required CI. +package main + +import ( + "bufio" + "bytes" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "flag" + "fmt" + "os" + "os/exec" + "path/filepath" + "regexp" + "runtime" + "sort" + "strconv" + "strings" + "sync" +) + +type suite struct { + Group string + Package string + Tests int + TestHash string + Include []string + Exclude []string +} + +var requiredSuites = []suite{ + {Group: "corpus", Package: "./ci/requiredci", Tests: 6, TestHash: "38ec9ce7d0cf47aef55f2facb53299862361febe6b1e06075e1cdd3d6a4554f6", Include: []string{"TestFixedDEXCorpusStructure", "TestSyntheticJImageStructure", "TestDecompileCancellationFailsClosed", "TestDecompileDeterministicAcrossProcesses"}}, + {Group: "algorithm", Package: "./ci/requiredci", Tests: 6, TestHash: "38ec9ce7d0cf47aef55f2facb53299862361febe6b1e06075e1cdd3d6a4554f6", Include: []string{"TestConcurrentDecompileDeterministic"}}, + {Group: "corpus", Package: "./test/cross", Tests: 104, TestHash: "17c48c808ac80dbb2055c86a65896b22997f04f8ad72643a76cb91025eb2ff43", Include: []string{"TestFixedIrreducibleCFGCorpusPureGo"}}, + {Group: "corpus", Package: "./classparser/classfilebuilder", Tests: 26, TestHash: "d26b13298f017bd8077df6e8910e78f6542e5ffcfd2dae7a36260ab17e61847f", Exclude: []string{"TestJava8InterfaceStaticMethodVerifies", "TestJavaVerifyAll", "TestLongDoubleAndFloatConstantsExecute"}}, + {Group: "corpus", Package: "./classparser/jarwar", Tests: 18, TestHash: "b1195066bc29f6a35391695fb815b4eef9eb42a55ef53f7ba9786375a27afc25"}, + {Group: "corpus", Package: "./classparser/decompiler/jar", Tests: 1, TestHash: "e84c19ac824483c172a763d735732079fb808d6dd0153c53e573b18513d23553"}, + {Group: "corpus", Package: "./jimage", Tests: 16, TestHash: "f68b01a6c2a476c2a5921fc30f5ab3a6c0b700fe04748ac1e1d5d9573e283df8", Exclude: []string{"TestJLinkBigEndianImage", "TestJLinkCompactCPImage", "TestOpenJDKImage"}}, + {Group: "corpus", Package: "./classparser", Tests: 4176, TestHash: "1920a1d4ab6a93c33d503eaa29b825151063d1d728b63ef7bdaf687a53802c92", Include: []string{"TestDumpMethodsPointerFastPathKeepsDescriptor", "TestJoinRuleChainExactOutput", "TestSourceRewritePrecisionOuterGateSemantics", "TestRewriteSchedulerOrderMatchesDumperCallSites", "TestRewriteSchedulerPositiveAndNearMissExactOutput", "TestRewriteSchedulerPreservesRecordsDiagnosticsAndHashes", "TestRewriteSchedulerDecompileEquivalence", "TestJDKObjectMetadataMatchesCatalog", "TestAdversarialPlatformConstructorCodeIdentityAndEffectProof", "TestLoopAnalysisCacheMatchesUncachedDecompile", "FuzzDecompileWithLimitsNeverPanics"}}, + + {Group: "algorithm", Package: "./classparser/decompiler/core", Tests: 413, TestHash: "cf788257ac2b6de14e9ba85f18a6fd70fcdc9f7f31d85b6538bb8b1344fff93b"}, + {Group: "algorithm", Package: "./classparser/decompiler/core/callbinding", Tests: 17, TestHash: "e7eafd33ec36c2219f362b5c45872f126dde5a81dab84d931023fd1abc1836cc"}, + {Group: "algorithm", Package: "./classparser/decompiler/core/class_context", Tests: 26, TestHash: "254c1ad1ea4a5da5d4bc6849e1067c11ef1953a2c171436e59d8b18627811c40"}, + {Group: "algorithm", Package: "./classparser/decompiler/core/fieldbinding", Tests: 1, TestHash: "6ec3bd03aab62727a5d86c38f16a3e99142866db2c91b5d2872616162fc2b06e"}, + {Group: "algorithm", Package: "./classparser/decompiler/core/frametransfer", Tests: 24, TestHash: "9898ba6045bd07fcbf98bbf469f099570072c73edaed0dff76d9857aea6f60f5"}, + {Group: "algorithm", Package: "./classparser/decompiler/core/methodir", Tests: 13, TestHash: "95c6ac735fb6ab912cbc0bfeff4fdbb9a2611afda63de0360fb146cfda552655"}, + {Group: "algorithm", Package: "./classparser/decompiler/core/ssabuild", Tests: 29, TestHash: "ea3b73bdf4252370e93bbb6b07d64ed5a954cd11cfbfd49c2a2a55692c7b27ba"}, + {Group: "algorithm", Package: "./classparser/decompiler/core/ssalower", Tests: 21, TestHash: "ba60145bafd5fda5be48298b5524097b255e2a1edf1226ab0c8153879ce3685d"}, + {Group: "algorithm", Package: "./classparser/decompiler/core/statements", Tests: 47, TestHash: "9f3bcb9c125d2d07a5d09bf4a4f4c119f5e9055cfd55db989869e96b22e574aa"}, + {Group: "algorithm", Package: "./classparser/decompiler/core/values", Tests: 283, TestHash: "1ef92dd8999fa01ec4702b98c9172efbe714dcdd6b35d8d13a8daa71363efb64", Exclude: []string{"TestJavaUnitsExhaustiveJVMCodeUnitOracle", "TestTaskT03C03_CharLiterals"}}, + {Group: "algorithm", Package: "./classparser/decompiler/core/values/types", Tests: 71, TestHash: "03a89ddb73bfdfbb8de135dd84fc6af8ebdb054662e7126d92a58889b0055773"}, + {Group: "algorithm", Package: "./classparser/decompiler/rewriter", Tests: 266, TestHash: "41c30d284c93d9e91bc6b5379cb52a6496ce17cf1feb9a3fe25f052b9ec76af1"}, + {Group: "algorithm", Package: "./internal/workbudget", Tests: 17, TestHash: "1f53605cb2386de80f254918d30db00ff803eed986bbc7087d0d42488f6dea8b"}, + {Group: "algorithm", Package: "./internal/jdecenv", Tests: 13, TestHash: "51ee508a5994d7763fb87e1d2d9cf78a345237af650479b650dbf055625082ad"}, + {Group: "algorithm", Package: "./internal/filesys", Tests: 9, TestHash: "f6485392fe079ab59aafa635aca0d9bbe00b7af50334a7c1362396d883d82e31"}, + + {Group: "dex", Package: "./dex2jar", Tests: 35, TestHash: "41d5dae9d120828434279822ce4b8661fa3394e68fde5ad341dae3d9d1b24e45", Exclude: []string{"TestAcceptedCorpusJVMOracle", "TestCoverageBaselineContract", "TestStrictAcceptedDEXRoundtripGate"}}, + {Group: "dex", Package: "./dex2jar/input", Tests: 25, TestHash: "6c3d9f03eab44176f1ad0e882252f2ef4f9593ef71f6d6cb71e61ef7c57cbe92"}, + {Group: "dex", Package: "./dex2jar/ir", Tests: 43, TestHash: "1a8c256ed990bb96db287b1be2fa7f11786bbc5d30eadafd8db2376e3878a508"}, + {Group: "dex", Package: "./dex2jar/lower", Tests: 54, TestHash: "ddc42bcad210f675f5b8ea1e15a38908ea834b7628d364dc13f2ac028b750e45", Exclude: []string{ + "TestClassParsesVerifiesAndExecutes", "TestIntArrayPathVerifiesAndExecutes", "TestUnsupportedStubsVerifyAndThrow", "TestThisDelegationVerifiesAndExecutes", + "TestLowerEmitsMetadataAttributes", "TestLowerFilledNewArrayAndNarrowArrayElements", "TestLowerEmitsAnnotationDefaultForReflection", "TestLowerEmitsClassMetadataAndArrayOwnerInvoke", "TestLowerMovesPreDelegationFieldStoreAfterSuper", "TestLowerInterleavedAllocationKeepsArgumentOrder", "TestLowerCapturesDeferredStoreValueBeforeReassignment", + "TestRecoverFailsClosedForUnsupportedStaticInitializer", "TestRecoverClassVerifiesWithoutInitialization", "TestRecoverChildFirstInterfaceShellsVerifyOnJVM", + "TestInvokeResultUsesMoveResultCategory", "TestLowerWideValuesVerifyAndExecute", "TestLowerMonitorsVerifyAndExecute", "TestLowerTryCatchVerifiesAndExecutes", "TestLowerCatchAllHandlerVerifiesAndExecutes", "TestHandlerWithoutMoveExceptionDiscardsCaughtValue", "TestLowerInterfaceStaticMethodsVerifyAndExecute", "TestLowerSwitchesVerifyAndExecute", "TestLowerFillArrayDataVerifyAndExecute", + }}, + {Group: "dex", Package: "./dex2jar/report", Tests: 7, TestHash: "6121738f00eca84495e4795ebdd9887db39a8ff30f761bd307bfb7bf0eed2081"}, + {Group: "dex", Package: "./inspect", Tests: 14, TestHash: "cd4f7f82cabeb7f10478e2b345c28aa2352d1e08396d8ade41e1c581d267e263"}, + {Group: "dex", Package: "./internal/dexparser", Tests: 4, TestHash: "982c4f5860610cd86fc786e1a2a8721108f134f1bf6ebbe657f2085e30400c3c"}, + {Group: "dex", Package: "./internal/inputkind", Tests: 6, TestHash: "b1aeb5061859deadc6a597d2b2feb84cd8ebeb199b08006adbfc86e63838a6fa"}, + {Group: "dex", Package: "./internal/mutf8", Tests: 6, TestHash: "f176fe43927c9dff4e9f378419d80c0d889d67e93aa568f3250e7edc8dd3ad72"}, + {Group: "dex", Package: "./internal/zipx", Tests: 3, TestHash: "773ae48e36e49359aa27baf6364ba5c4712e6586e7235db6d628c14e568714a7"}, + + {Group: "contract", Package: "./tools/requiredci", Tests: 6, TestHash: "76472166ee629021a07398756a3005174d8b6ca9adb8fe08d9671ea9f4f55742"}, +} + +var forbiddenWorkflowWord = regexp.MustCompile(`(?i)\b(?:java|javac|javap|jlink|jmod|jimage|python(?:2|3)?)\b`) + +func main() { + check := flag.Bool("check", false, "validate the required-CI contract") + run := flag.String("run", "", "validate and execute one inventory group") + flag.Parse() + if *check == (*run != "") || flag.NArg() != 0 { + fmt.Fprintln(os.Stderr, "usage: go run ./tools/requiredci -check | -run corpus|algorithm|dex|contract") + os.Exit(2) + } + root, err := repositoryRoot() + if err == nil { + if *run == "" { + err = validate(root) + } else { + // A group job only needs its own sealed rows. The contract job + // validates the complete inventory, so repeating that listing in + // every test job would add startup latency without adding a gate. + err = validateGroup(root, *run) + } + } + if err == nil && *run != "" { + err = runSuites(root, *run) + } + if err != nil { + fmt.Fprintln(os.Stderr, "required CI:", err) + os.Exit(1) + } +} + +func repositoryRoot() (string, error) { + dir, err := os.Getwd() + if err != nil { + return "", err + } + for { + if data, readErr := os.ReadFile(filepath.Join(dir, "go.mod")); readErr == nil && bytes.HasPrefix(data, []byte("module github.com/yaklang/javajive\n")) { + return dir, nil + } + parent := filepath.Dir(dir) + if parent == dir { + return "", errors.New("repository go.mod not found") + } + dir = parent + } +} + +var requiredGroups = []string{"corpus", "algorithm", "dex", "contract"} + +// maxListWorkers bounds concurrent `go test -list` processes. Listing is +// process-heavy but mostly independent; four workers fit the four-vCPU public +// runners and keep startup latency off the critical path. The Go build cache +// serializes its own writes safely. +const maxListWorkers = 4 + +var ( + testListMu sync.Mutex + testLists = map[string][]string{} +) + +func validate(root string) error { + if err := validateRequiredWorkflow(root); err != nil { + return err + } + if err := validateSuites(root, requiredSuites); err != nil { + return err + } + groups := map[string]bool{} + for _, item := range requiredSuites { + groups[item.Group] = true + } + for _, group := range requiredGroups { + if !groups[group] { + return fmt.Errorf("required group %q has no inventory", group) + } + } + return nil +} + +func validateGroup(root, group string) error { + if err := validateRequiredWorkflow(root); err != nil { + return err + } + rows, err := suitesForGroup(group) + if err != nil { + return err + } + return validateSuites(root, rows) +} + +func validateRequiredWorkflow(root string) error { + data, err := os.ReadFile(filepath.Join(root, ".github", "workflows", "ci.yml")) + if err != nil { + return fmt.Errorf("read required workflow: %w", err) + } + return validateWorkflow(string(data)) +} + +func suitesForGroup(group string) ([]suite, error) { + rows := make([]suite, 0, len(requiredSuites)) + for _, item := range requiredSuites { + if item.Group == group { + rows = append(rows, item) + } + } + if len(rows) == 0 { + return nil, fmt.Errorf("unknown or empty inventory group %q", group) + } + return rows, nil +} + +type listedSuite struct { + item suite + all []string + err error +} + +// validateSuites lists every package's tests and seals each row. Listings run +// concurrently, then rows are checked in declaration order so inventory +// failures stay deterministic. +func validateSuites(root string, rows []suite) error { + seen := map[string]bool{} + for _, item := range rows { + key := item.Group + "\x00" + item.Package + if seen[key] || item.Group == "" || !strings.HasPrefix(item.Package, "./") || len(item.Include) > 0 && len(item.Exclude) > 0 { + return fmt.Errorf("invalid inventory row: %+v", item) + } + seen[key] = true + } + results := make([]listedSuite, len(rows)) + workers := boundedWorkers(maxListWorkers, len(rows)) + jobs := make(chan int) + var wait sync.WaitGroup + for worker := 0; worker < workers; worker++ { + wait.Add(1) + go func() { + defer wait.Done() + for index := range jobs { + all, err := listTestsCached(root, rows[index].Package) + results[index] = listedSuite{item: rows[index], all: all, err: err} + } + }() + } + for index := range rows { + jobs <- index + } + close(jobs) + wait.Wait() + for _, result := range results { + if result.err != nil { + return result.err + } + item := result.item + if item.TestHash != "" && (len(result.all) != item.Tests || testHash(result.all) != item.TestHash) { + return fmt.Errorf("%s inventory changed: tests=%d hash=%s; review and update the sealed row", item.Package, len(result.all), testHash(result.all)) + } + if _, err := selectedTests(item, result.all); err != nil { + return err + } + } + return nil +} + +// listTestsCached memoizes the authoritative test inventory for this process. +// Validation and runSuites ask for the same package list; without the cache +// every job re-ran `go test -list` for every package in its group. +func listTestsCached(root, pkg string) ([]string, error) { + testListMu.Lock() + if tests, ok := testLists[pkg]; ok { + testListMu.Unlock() + return tests, nil + } + testListMu.Unlock() + tests, err := listTests(root, pkg) + if err != nil { + return nil, err + } + testListMu.Lock() + testLists[pkg] = tests + testListMu.Unlock() + return tests, nil +} + +func validateWorkflow(text string) error { + if !strings.Contains(text, "pull_request:") || !strings.Contains(text, "push:") { + return errors.New("ci.yml must remain the push and pull-request workflow") + } + if forbiddenWorkflowWord.MatchString(text) { + return fmt.Errorf("ci.yml contains forbidden external-tool word %q", forbiddenWorkflowWord.FindString(text)) + } + allowedActions := map[string]bool{ + "actions/checkout@11d5960a326750d5838078e36cf38b85af677262": true, + "actions/setup-go@40f1582b2485089dde7abd97c1529aa768e1baff": true, + } + for _, line := range strings.Split(text, "\n") { + line = strings.TrimSpace(line) + if !strings.HasPrefix(line, "uses:") && !strings.HasPrefix(line, "- uses:") { + continue + } + spec := strings.TrimSpace(strings.TrimPrefix(strings.TrimPrefix(line, "- "), "uses:")) + if !allowedActions[spec] { + return fmt.Errorf("ci.yml uses unapproved action %q", spec) + } + } + for _, required := range []string{"go run ./tools/requiredci -check", "CGO_ENABLED=0 go build ./...", "-run corpus", "-run algorithm", "-run dex", "-run contract"} { + if strings.Count(text, required) != 1 { + return fmt.Errorf("ci.yml must contain exactly one %q", required) + } + } + if strings.Contains(text, "go test ./...") { + return errors.New("ci.yml may not bypass the committed test inventory") + } + return nil +} + +func listTests(root, pkg string) ([]string, error) { + goPath, err := exec.LookPath("go") + if err != nil { + return nil, err + } + command := exec.Command(goPath, "test", pkg, "-list", "^(Test|Fuzz)") + command.Dir = root + command.Env = sanitizedEnvironment("") + output, err := command.CombinedOutput() + if err != nil { + return nil, fmt.Errorf("list %s: %w\n%s", pkg, err, output) + } + var tests []string + for _, line := range strings.Split(string(output), "\n") { + if strings.HasPrefix(line, "Test") || strings.HasPrefix(line, "Fuzz") { + tests = append(tests, line) + } + } + sort.Strings(tests) + return tests, nil +} + +func selectedTests(item suite, all []string) ([]string, error) { + known := make(map[string]bool, len(all)) + for _, name := range all { + known[name] = true + } + if len(item.Include) > 0 { + for _, name := range item.Include { + if !known[name] { + return nil, fmt.Errorf("%s includes missing test %s", item.Package, name) + } + } + return append([]string(nil), item.Include...), nil + } + excluded := map[string]bool{} + for _, name := range item.Exclude { + if !known[name] { + return nil, fmt.Errorf("%s excludes missing test %s", item.Package, name) + } + excluded[name] = true + } + selected := make([]string, 0, len(all)-len(excluded)) + for _, name := range all { + if !excluded[name] { + selected = append(selected, name) + } + } + if len(selected) == 0 { + return nil, fmt.Errorf("%s selects no required tests", item.Package) + } + return selected, nil +} + +func testHash(tests []string) string { + sum := sha256.Sum256([]byte(strings.Join(tests, "\n") + "\n")) + return hex.EncodeToString(sum[:]) +} + +type testEvent struct { + Action string + Test string +} + +func runSuites(root, group string) error { + goPath, err := exec.LookPath("go") + if err != nil { + return err + } + emptyPath, err := os.MkdirTemp("", "javajive-required-path-") + if err != nil { + return err + } + defer os.RemoveAll(emptyPath) + work, err := os.MkdirTemp("", "javajive-required-work-") + if err != nil { + return err + } + defer os.RemoveAll(work) + rows, err := suitesForGroup(group) + if err != nil { + return err + } + prepared := make([]preparedSuite, 0, len(rows)) + for _, item := range rows { + all, err := listTestsCached(root, item.Package) + if err != nil { + return err + } + tests, err := selectedTests(item, all) + if err != nil { + return err + } + parts := make([]string, len(tests)) + for index, name := range tests { + parts[index] = regexp.QuoteMeta(name) + } + prepared = append(prepared, preparedSuite{ + item: item, + tests: tests, + selector: "^(" + strings.Join(parts, "|") + ")$", + }) + } + raceGroup := group == "algorithm" || group == "dex" + if raceGroup { + for index := range prepared { + prepared[index].binary = filepath.Join(work, fmt.Sprintf("suite-%d.test", index)) + if group == "dex" { + prepared[index].profile = filepath.Join(work, fmt.Sprintf("coverage-%d.out", index)) + // The external multidex APK test spends most of its time under + // instrumentation. Race and coverage are independent checks: + // run the same suite as a race-only binary and a coverage-only + // binary concurrently, and merge only the latter profile. + if prepared[index].item.Package == "./inspect" { + prepared[index].coverageBinary = filepath.Join(work, fmt.Sprintf("suite-%d-cover.test", index)) + } + } + } + fmt.Printf("required CI: compiling %d suites for %s\n", len(prepared), group) + if err := compileSuites(goPath, root, prepared, group); err != nil { + return err + } + } + if err := runPreparedSuites(goPath, root, emptyPath, raceGroup, prepared); err != nil { + return err + } + if group == "dex" { + profiles := make([]string, 0, len(prepared)) + for _, run := range prepared { + if run.profile != "" { + profiles = append(profiles, run.profile) + } + } + if err := checkCoverage(root, goPath, profiles); err != nil { + return err + } + } + return nil +} + +type suiteRunResult struct { + output []byte + err error + ran bool +} + +// maxRunWorkers runs independent package test processes concurrently. Test +// binaries are separate processes and the suites use no shared ports or +// process-global state. Four workers fit the four-vCPU public runners; the +// effective count is capped by GOMAXPROCS so a two-vCPU private runner keeps +// its old behaviour. Each binary still has a five-minute timeout. +const maxRunWorkers = 4 + +func boundedWorkers(limit, jobs int) int { + workers := limit + if procs := runtime.GOMAXPROCS(0); workers > procs { + workers = procs + } + if jobs < workers { + workers = jobs + } + if workers < 1 { + workers = 1 + } + return workers +} + +func runPreparedSuites(goPath, root, emptyPath string, raceGroup bool, prepared []preparedSuite) error { + results := make([]suiteRunResult, len(prepared)) + if len(prepared) > 0 { + workers := boundedWorkers(maxRunWorkers, len(prepared)) + fmt.Printf("required CI: running %d suites (%d at a time)\n", len(prepared), workers) + jobs := make(chan int) + stop := make(chan struct{}) + var stopOnce sync.Once + var wait sync.WaitGroup + for worker := 0; worker < workers; worker++ { + wait.Add(1) + go func() { + defer wait.Done() + for index := range jobs { + select { + case <-stop: + continue + default: + } + result := executePreparedSuite(goPath, root, emptyPath, raceGroup, prepared[index]) + results[index] = result + if result.err != nil { + stopOnce.Do(func() { close(stop) }) + } + } + }() + } + dispatch: + for index := range prepared { + select { + case <-stop: + break dispatch + case jobs <- index: + } + } + close(jobs) + wait.Wait() + } + for _, result := range results { + if !result.ran { + continue + } + _, _ = os.Stdout.Write(result.output) + if result.err != nil { + return result.err + } + } + return nil +} + +func executePreparedSuite(goPath, root, emptyPath string, raceGroup bool, run preparedSuite) suiteRunResult { + item := run.item + if raceGroup { + if run.coverageBinary != "" { + return executeSplitSuite(goPath, root, emptyPath, run) + } + output, runErr := runTest2JSON(goPath, root, emptyPath, run, run.binary, run.profile) + result := suiteRunResult{output: output, ran: true} + if err := verifyEvents(item.Package, run.tests, output); err != nil { + result.err = err + return result + } + if runErr != nil { + result.err = fmt.Errorf("%s failed: %w", item.Package, runErr) + } + return result + } + command := exec.Command(goPath, "test", "-json", "-count=1", "-timeout=5m", "-run", run.selector, item.Package) + command.Dir = root + command.Env = sanitizedEnvironment(emptyPath) + output, runErr := command.CombinedOutput() + result := suiteRunResult{output: output, ran: true} + if err := verifyEvents(item.Package, run.tests, output); err != nil { + result.err = err + return result + } + if runErr != nil { + result.err = fmt.Errorf("%s failed: %w", item.Package, runErr) + } + return result +} + +// executeSplitSuite runs the race-only and coverage-only binaries for one +// suite concurrently. Both must pass the full sealed selector; only the +// coverage binary publishes a profile. +func executeSplitSuite(goPath, root, emptyPath string, run preparedSuite) suiteRunResult { + var raceOutput, coverOutput []byte + var raceErr, coverErr error + var wait sync.WaitGroup + wait.Add(2) + go func() { + defer wait.Done() + raceOutput, raceErr = runTest2JSON(goPath, root, emptyPath, run, run.binary, "") + }() + go func() { + defer wait.Done() + coverOutput, coverErr = runTest2JSON(goPath, root, emptyPath, run, run.coverageBinary, run.profile) + }() + wait.Wait() + output := make([]byte, 0, len(raceOutput)+len(coverOutput)) + output = append(output, raceOutput...) + output = append(output, coverOutput...) + result := suiteRunResult{output: output, ran: true} + if err := verifyEvents(run.item.Package, run.tests, raceOutput); err != nil { + result.err = err + return result + } + if err := verifyEvents(run.item.Package, run.tests, coverOutput); err != nil { + result.err = err + return result + } + if raceErr != nil { + result.err = fmt.Errorf("%s race run failed: %w", run.item.Package, raceErr) + return result + } + if coverErr != nil { + result.err = fmt.Errorf("%s coverage run failed: %w", run.item.Package, coverErr) + } + return result +} + +func runTest2JSON(goPath, root, emptyPath string, run preparedSuite, binary, profile string) ([]byte, error) { + args := []string{"tool", "test2json", "-t", "-p", run.item.Package, binary, + "-test.v=test2json", "-test.count=1", "-test.timeout=5m", "-test.run=" + run.selector} + if profile != "" { + args = append(args, "-test.coverprofile="+profile) + } + command := exec.Command(goPath, args...) + command.Dir = filepath.Join(root, filepath.FromSlash(strings.TrimPrefix(run.item.Package, "./"))) + command.Env = sanitizedEnvironment(emptyPath) + return command.CombinedOutput() +} + +type preparedSuite struct { + item suite + tests []string + selector string + binary string + coverageBinary string + profile string +} + +// maxCompileWorkers bounds concurrent `go test -c` processes. Compilation is +// independent of test execution, and two workers overlap the race/coverage +// link work without competing with the test process pool. +const maxCompileWorkers = 2 + +func compileSuites(goPath, root string, prepared []preparedSuite, group string) error { + workers := boundedWorkers(maxCompileWorkers, len(prepared)) + jobs := make(chan int) + errs := make([]error, len(prepared)) + var wait sync.WaitGroup + for worker := 0; worker < workers; worker++ { + wait.Add(1) + go func() { + defer wait.Done() + for index := range jobs { + run := prepared[index] + args := []string{"test", "-c", "-race", "-o", run.binary} + if group == "dex" && run.coverageBinary == "" { + args = append(args, "-covermode=atomic", "-coverpkg=./dex2jar/...,./internal/dexparser") + } + args = append(args, run.item.Package) + if err := compileOne(goPath, root, run.item.Package, args); err != nil { + errs[index] = err + continue + } + if run.coverageBinary != "" { + args = []string{"test", "-c", "-covermode=atomic", "-coverpkg=./dex2jar/...,./internal/dexparser", "-o", run.coverageBinary, run.item.Package} + if err := compileOne(goPath, root, run.item.Package+" (coverage)", args); err != nil { + errs[index] = err + } + } + } + }() + } + for index := range prepared { + jobs <- index + } + close(jobs) + wait.Wait() + for _, err := range errs { + if err != nil { + return err + } + } + return nil +} + +func compileOne(goPath, root, label string, args []string) error { + command := exec.Command(goPath, args...) + command.Dir = root + command.Env = compileEnvironment() + if output, err := command.CombinedOutput(); err != nil { + return fmt.Errorf("compile %s: %w\n%s", label, err, output) + } + return nil +} + +func verifyEvents(pkg string, expected []string, output []byte) error { + terminal := map[string]string{} + scanner := bufio.NewScanner(bytes.NewReader(output)) + buffer := make([]byte, 64<<10) + scanner.Buffer(buffer, 4<<20) + for scanner.Scan() { + var event testEvent + if json.Unmarshal(scanner.Bytes(), &event) != nil || event.Test == "" { + continue + } + if event.Action != "pass" && event.Action != "fail" && event.Action != "skip" { + continue + } + if event.Action != "pass" { + return fmt.Errorf("%s required test %s ended with %s", pkg, event.Test, event.Action) + } + if !strings.Contains(event.Test, "/") { + if previous := terminal[event.Test]; previous != "" { + return fmt.Errorf("%s test %s has duplicate terminal events", pkg, event.Test) + } + terminal[event.Test] = event.Action + } + } + if err := scanner.Err(); err != nil { + return fmt.Errorf("%s: decode go test output: %w", pkg, err) + } + for _, name := range expected { + if terminal[name] != "pass" { + return fmt.Errorf("%s required test %s did not pass", pkg, name) + } + } + if len(terminal) != len(expected) { + return fmt.Errorf("%s terminal inventory mismatch: got %d, want %d", pkg, len(terminal), len(expected)) + } + return nil +} + +type coverageBaseline struct { + Module string `json:"module"` + Total coverageCount `json:"total"` + Packages map[string]coverageCount `json:"packages"` + ZeroCoveredFunctions []string `json:"zero_covered_functions"` +} + +type coverageCount struct { + Covered int `json:"covered"` + Statements int `json:"statements"` +} + +type coverageBlock struct { + Statements int + Count int64 +} + +func checkCoverage(root, goPath string, profiles []string) error { + baselinePath := filepath.Join(root, "dex2jar", "coverage_baseline.json") + data, err := os.ReadFile(baselinePath) + if err != nil { + return err + } + var baseline coverageBaseline + decoder := json.NewDecoder(bytes.NewReader(data)) + if err := decoder.Decode(&baseline); err != nil { + return fmt.Errorf("decode coverage baseline: %w", err) + } + blocks := map[string]coverageBlock{} + for _, profile := range profiles { + profileData, err := os.ReadFile(profile) + if err != nil { + return fmt.Errorf("read coverage profile %s: %w", profile, err) + } + lines := strings.Split(strings.TrimSpace(string(profileData)), "\n") + if len(lines) == 0 || lines[0] != "mode: atomic" { + return fmt.Errorf("coverage profile %s has invalid mode", profile) + } + for lineNumber, line := range lines[1:] { + fields := strings.Fields(line) + if len(fields) != 3 { + return fmt.Errorf("coverage profile %s line %d is malformed", profile, lineNumber+2) + } + statements, statErr := strconv.Atoi(fields[1]) + count, countErr := strconv.ParseInt(fields[2], 10, 64) + if statErr != nil || countErr != nil || statements < 0 || count < 0 { + return fmt.Errorf("coverage profile %s line %d has invalid counts", profile, lineNumber+2) + } + block := blocks[fields[0]] + if block.Statements != 0 && block.Statements != statements { + return fmt.Errorf("coverage block %s changed statement count", fields[0]) + } + block.Statements = statements + if count > block.Count { + block.Count = count + } + blocks[fields[0]] = block + } + } + actual := map[string]coverageCount{} + prefix := baseline.Module + "/" + for location, block := range blocks { + filename := strings.SplitN(location, ":", 2)[0] + if !strings.HasPrefix(filename, prefix) { + return fmt.Errorf("coverage file is outside module: %s", filename) + } + pkg := filename[:strings.LastIndex(filename, "/")] + value := actual[pkg] + value.Statements += block.Statements + if block.Count != 0 { + value.Covered += block.Statements + } + actual[pkg] = value + } + for pkg, want := range baseline.Packages { + got, ok := actual[pkg] + if !ok { + return fmt.Errorf("missing package coverage: %s", pkg) + } + if !ratioAtLeast(got, want) { + return fmt.Errorf("coverage regression %s: %d/%d < %d/%d", pkg, got.Covered, got.Statements, want.Covered, want.Statements) + } + } + for pkg := range actual { + if _, ok := baseline.Packages[pkg]; !ok { + return fmt.Errorf("unbaselined package coverage: %s", pkg) + } + } + total := coverageCount{} + for _, value := range actual { + total.Covered += value.Covered + total.Statements += value.Statements + } + if !ratioAtLeast(total, baseline.Total) { + return fmt.Errorf("total coverage regression: %d/%d < %d/%d", total.Covered, total.Statements, baseline.Total.Covered, baseline.Total.Statements) + } + merged := filepath.Join(filepath.Dir(profiles[0]), "coverage-merged.out") + if err := writeCoverageProfile(merged, blocks); err != nil { + return err + } + command := exec.Command(goPath, "tool", "cover", "-func="+merged) + command.Dir = root + command.Env = compileEnvironment() + output, err := command.CombinedOutput() + if err != nil { + return fmt.Errorf("inspect coverage functions: %w\n%s", err, output) + } + allowed := map[string]bool{} + for _, name := range baseline.ZeroCoveredFunctions { + allowed[name] = true + } + for _, line := range strings.Split(string(output), "\n") { + if !strings.Contains(line, "\t0.0%") || strings.HasPrefix(line, "total:") { + continue + } + fields := strings.Fields(line) + if len(fields) < 3 { + return fmt.Errorf("unrecognized coverage function line %q", line) + } + fileAndLine := fields[0] + goEnd := strings.Index(fileAndLine, ".go:") + if goEnd < 0 { + return fmt.Errorf("unrecognized coverage location %q", fileAndLine) + } + filename := fileAndLine[:goEnd+len(".go")] + if !strings.HasPrefix(filename, prefix) { + return fmt.Errorf("coverage function is outside module: %s", filename) + } + identity := strings.TrimPrefix(filename, prefix) + ":" + fields[1] + if !allowed[identity] { + return fmt.Errorf("new 0%%-covered function: %s", identity) + } + } + fmt.Printf("required CI: DEX coverage %d/%d statements\n", total.Covered, total.Statements) + return nil +} + +func ratioAtLeast(actual, baseline coverageCount) bool { + if actual.Statements == 0 || baseline.Statements == 0 { + return actual.Statements == baseline.Statements + } + return actual.Covered*baseline.Statements >= baseline.Covered*actual.Statements +} + +func writeCoverageProfile(path string, blocks map[string]coverageBlock) error { + keys := make([]string, 0, len(blocks)) + for key := range blocks { + keys = append(keys, key) + } + sort.Strings(keys) + var output strings.Builder + output.WriteString("mode: atomic\n") + for _, key := range keys { + block := blocks[key] + fmt.Fprintf(&output, "%s %d %d\n", key, block.Statements, block.Count) + } + return os.WriteFile(path, []byte(output.String()), 0o600) +} + +func compileEnvironment() []string { + forbiddenPrefixes := []string{"JAVA_HOME=", "JDK_HOME=", "JRE_HOME=", "PYTHONHOME=", "PYTHONPATH="} + result := make([]string, 0, len(os.Environ())+2) + for _, value := range os.Environ() { + drop := false + for _, prefix := range forbiddenPrefixes { + if strings.HasPrefix(value, prefix) { + drop = true + break + } + } + if !drop { + result = append(result, value) + } + } + return append(result, "CGO_ENABLED=1", "GOTOOLCHAIN=local") +} + +func sanitizedEnvironment(path string) []string { + forbiddenPrefixes := []string{"JAVA_HOME=", "JDK_HOME=", "JRE_HOME=", "PYTHONHOME=", "PYTHONPATH=", "PATH="} + result := make([]string, 0, len(os.Environ())+3) + for _, value := range os.Environ() { + drop := false + for _, prefix := range forbiddenPrefixes { + if strings.HasPrefix(value, prefix) { + drop = true + break + } + } + if !drop { + result = append(result, value) + } + } + if path != "" { + result = append(result, "PATH="+path) + } + return append(result, "CGO_ENABLED=0", "GOTOOLCHAIN=local") +} diff --git a/tools/requiredci/main_test.go b/tools/requiredci/main_test.go new file mode 100644 index 00000000..9c468b31 --- /dev/null +++ b/tools/requiredci/main_test.go @@ -0,0 +1,109 @@ +package main + +import ( + "strings" + "testing" +) + +const validWorkflow = `name: CI +on: + push: + pull_request: +jobs: + contract: + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 + - uses: actions/setup-go@40f1582b2485089dde7abd97c1529aa768e1baff + - run: go run ./tools/requiredci -check + - run: CGO_ENABLED=0 go build ./... + - run: go run ./tools/requiredci -run contract + corpus: + steps: + - run: go run ./tools/requiredci -run corpus + algorithm: + steps: + - run: go run ./tools/requiredci -run algorithm + dex: + steps: + - run: go run ./tools/requiredci -run dex +` + +func TestWorkflowContractAcceptsReviewedShape(t *testing.T) { + if err := validateWorkflow(validWorkflow); err != nil { + t.Fatal(err) + } +} + +func TestWorkflowContractRejectsForbiddenToolsAndActions(t *testing.T) { + for _, replacement := range []string{ + validWorkflow + " - run: python3 check.py\n", + validWorkflow + " - run: javac Fixture.java\n", + strings.Replace(validWorkflow, "actions/setup-go@40f1582b2485089dde7abd97c1529aa768e1baff", "actions/setup-java@cf277c60eb25467037889841efdb72551f06f6c3", 1), + validWorkflow + " - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02\n", + } { + if err := validateWorkflow(replacement); err == nil { + t.Fatalf("accepted forbidden workflow:\n%s", replacement) + } + } +} + +func TestWorkflowContractRejectsBroadOrMissingInventory(t *testing.T) { + for _, broken := range []string{ + validWorkflow + " - run: go test ./...\n", + strings.Replace(validWorkflow, "go run ./tools/requiredci -run dex", "go test ./dex2jar/...", 1), + strings.Replace(validWorkflow, "pull_request:", "workflow_dispatch:", 1), + } { + if err := validateWorkflow(broken); err == nil { + t.Fatalf("accepted workflow outside inventory contract:\n%s", broken) + } + } +} + +func TestSuitesForGroupFiltersAndRejectsUnknown(t *testing.T) { + rows, err := suitesForGroup("algorithm") + if err != nil { + t.Fatal(err) + } + if len(rows) == 0 { + t.Fatal("algorithm group is empty") + } + for _, row := range rows { + if row.Group != "algorithm" { + t.Fatalf("algorithm group leaked %+v", row) + } + } + for _, group := range requiredGroups { + if rows, err := suitesForGroup(group); err != nil || len(rows) == 0 { + t.Fatalf("group %q: rows=%d err=%v", group, len(rows), err) + } + } + if _, err := suitesForGroup("unknown"); err == nil { + t.Fatal("accepted unknown inventory group") + } +} + +func TestSelectedTestsRejectsUnknownNames(t *testing.T) { + all := []string{"TestA", "TestB"} + if _, err := selectedTests(suite{Package: "./p", Include: []string{"TestMissing"}}, all); err == nil { + t.Fatal("accepted missing include") + } + if _, err := selectedTests(suite{Package: "./p", Exclude: []string{"TestMissing"}}, all); err == nil { + t.Fatal("accepted missing exclusion") + } +} + +func TestVerifyEventsFailsClosed(t *testing.T) { + good := []byte("{\"Action\":\"pass\",\"Test\":\"TestA/sub\"}\n{\"Action\":\"pass\",\"Test\":\"TestA\"}\n") + if err := verifyEvents("./p", []string{"TestA"}, good); err != nil { + t.Fatal(err) + } + for _, bad := range [][]byte{ + []byte("{\"Action\":\"skip\",\"Test\":\"TestA/sub\"}\n{\"Action\":\"pass\",\"Test\":\"TestA\"}\n"), + []byte("{\"Action\":\"pass\",\"Test\":\"TestOther\"}\n"), + []byte("{\"Action\":\"pass\",\"Test\":\"TestA\"}\n{\"Action\":\"pass\",\"Test\":\"TestA\"}\n"), + } { + if err := verifyEvents("./p", []string{"TestA"}, bad); err == nil { + t.Fatalf("accepted incomplete events: %s", bad) + } + } +}