Files
reverse-engineering-anything/src/android/JadxJavaProbe.ts
T
morluto df1e647266 refactor(desktop): let build-computer and agentenv cleanup errors read their owner's release (#10855)
* refactor(errors): read cleanup completion from dependencies instead of pushing it to dependents

AnalysisError.cleanupIncomplete becomes a getter over the error's own unresolved state and its bound dependencies. The WeakRef dependents graph and resolveCleanup's push propagation are removed, and subclasses mark their initial state through markCleanupIncomplete instead of overriding a public mutable field.

* fix(errors): settle bound dependencies before binding more

A composite whose dependencies had released but whose status was never read
stayed incomplete when a later dependency was bound.

* refactor(errors): let errors read a lease group's release instead of resolving them (#10759)

AnalysisCleanupLeaseGroup no longer calls resolveCleanup() on its error.
The error holds the group as a release claim and reads cleanupReleased when
asked, so completion follows the lease owner without a push.

* chore(verify): count resolveCleanup and bindCleanupDependencies calls so they only shrink (#10763)

* refactor(errors): let errors read a lease group's release instead of resolving them

AnalysisCleanupLeaseGroup no longer calls resolveCleanup() on its error.
The error holds the group as a release claim and reads cleanupReleased when
asked, so completion follows the lease owner without a push.

* chore(verify): count resolveCleanup and bindCleanupDependencies calls so they only shrink

* refactor(process): let worker cleanup errors read their root epoch's release

OwnedWorkerRuntime's root epoch is now an AnalysisCleanupReleaseClaim. Errors bound to it read its release when asked instead of the epoch pushing resolveCleanup() through weak references, and a runtime without a retained root binds an already-released owner. Removes the OwnedWorkerCleanupFailure structural type and four resolveCleanup() pushes; the counted baseline shrinks accordingly.

* refactor(pcap): let pcap cleanup errors read command and snapshot release (#10792)

Retained pcap commands, retained snapshot failures and snapshot completion descriptors now own their release and errors read it: commands and snapshot failures implement AnalysisCleanupReleaseClaim, and a failed completion-descriptor close is retried through an AnalysisCleanupLease bound to its error. Removes four resolveCleanup() pushes; the counted baseline shrinks accordingly.

* refactor(process): let Darwin helper cleanup errors read their owner's release

Darwin helper cache and run-token reader root cleanup now record an AnalysisCleanupRelease that every failure reports; a successful retry confirms it. Replaces the first-failure anchor that later failures depended on and the resolveCleanup() push. Removes two resolveCleanup() and two bindCleanupDependencies() calls; both counted baselines shrink.

* refactor(ghidra): let Ghidra cleanup errors read the client's and checkpoint's release

GhidraClient and GhidraCheckpoint bind each cleanup failure to an AnalysisCleanupRelease and confirm it when a later close or retry releases everything, instead of keeping a set of failures and pushing resolveCleanup() to each. Removes two resolveCleanup() calls; the counted baseline shrinks.

* refactor(process): let debugger session cleanup errors read a confirmed stop

OwnedDebuggerSessionRegistry binds each retained gdb or rizin cleanup failure to the session's AnalysisCleanupRelease and confirms it when a stop is confirmed, keeping the latest failure for retry reporting, instead of pushing resolveCleanup() to a set of failures. Removes one resolveCleanup() call; the counted baseline shrinks.

* refactor(process): drop the debugger registry's unused closeOperation option

Returning the latest retained failure removed the last reader of closeOperation; remove the option and the values gdb and rizin supplied.

* refactor(server): let environment shutdown errors read a successful close

serveEnvironment binds each shutdown failure to an AnalysisCleanupRelease that a later successful close confirms, instead of pushing resolveCleanup() to a set of failures. The state-file retry test now also requires the earlier report to read the release. Removes one resolveCleanup() call; the counted baseline shrinks.

* refactor(desktop): release retained screen-judge cleanup through its lease

Each retained judge or screenshot cleanup owner is wrapped in an AnalysisCleanupLease bound to its failure; close() releases the lease, which records the release the failure reads, instead of closing the owner and pushing resolveCleanup(). Removes one resolveCleanup() call; the counted baseline shrinks.

* refactor(ida): let IDA close failures read the session's later close

IdaSessionClient's close failure binds an owner that is both its resource owner and its release claim, read from the client's closed state, instead of keeping weak references and pushing resolveCleanup() after a successful retry. Removes one resolveCleanup() call; the counted baseline shrinks.

* refactor(javascript): let source-map codec cleanup errors read a later close (#10814)

* refactor(javascript): let source-map codec cleanup errors read a later close

OwnedCodec binds each close failure to an AnalysisCleanupRelease that a later successful close confirms, replacing the first-failure anchor that later failures depended on and the resolveCleanup() push. Removes one resolveCleanup() and one bindCleanupDependencies() call; both counted baselines shrink.

* refactor(cutter): let pending Cutter command errors read the completion receipt (#10815)

* refactor(cutter): let pending Cutter command errors read the completion receipt

Each pending Cutter command keeps an AnalysisCleanupRelease bound to its timeout failure; the producer's terminal completion receipt confirms it instead of pushing resolveCleanup(). Removes one resolveCleanup() call; the counted baseline shrinks.

* refactor(application): let provider candidate cleanup errors read the candidate's close (#10817)

* refactor(application): let provider candidate cleanup errors read the candidate's close

AnalysisProviderRegistry keeps one AnalysisCleanupRelease per candidate whose resource close is unconfirmed; failures bind to it and a later confirmed close confirms it, instead of pushing resolveCleanup() to a set of failures. Removes one resolveCleanup() call; the counted baseline shrinks.

* fix(errors): bind a cleanup release claim to an error at most once

AnalysisError kept release claims in an array, so a provider whose retried close returned the same error bound the same claim again on every retry and each cleanupIncomplete read scanned the duplicates. Keep the claims in a set.

* refactor(application): let reverse-tool cleanup errors read a verified stop (#10819)

* refactor(application): let reverse-tool cleanup errors read a verified stop

Each retained provider process group in ReverseEngineeringService keeps an AnalysisCleanupRelease; its command and retry failures bind to it and a later verified stop confirms it, instead of collecting failures and pushing resolveCleanup(). Removes one resolveCleanup() call; the counted baseline shrinks.

* refactor(sqlite): let SQLite worker and root cleanup errors read their release (#10821)

Each retained SQLite snapshot cleanup records an AnalysisCleanupRelease for its worker and for its runtime root; the resource failures bind to them and a verified stop or root removal confirms them, instead of pushing resolveCleanup(). Composite failures keep reading those resource failures. Removes two resolveCleanup() calls; the counted baseline shrinks.

* refactor(android): let JADX cleanup errors read their retained cleanup's release

Each retained JADX cleanup records an AnalysisCleanupRelease for the admission failure's descriptor owners and one for the whole retained cleanup. The admission failure and every error the cleanup reports bind to them, and a confirmed close confirms them, instead of pushing resolveCleanup() through WeakRefs to reported errors. Removes two resolveCleanup() calls; the counted baseline shrinks.

* refactor(application): let session close failures read the client's later close

A retained session cleanup records an AnalysisCleanupRelease; unowned cleanup failures the client's close reported bind to it and the successful close confirms it, instead of the session collecting them and pushing resolveCleanup(). Failures that already follow their own owner keep reading it. Adds a regression for an unowned close failure. Removes one resolveCleanup() call; the counted baseline shrinks.

* refactor(desktop): let build-computer and agentenv cleanup errors read their owner's release

Build-computer teardown, retained task readers, remote reader folders and agentenv solve sandboxes each record an AnalysisCleanupRelease that their bound failures read; a verified teardown or stop confirms it instead of pushing resolveCleanup() through WeakRef sets. Long-run job failures read whether every job they name has confirmed its stop, so a failure naming two jobs no longer reads complete when only one stops (regression added). WeakRef sets kept only where late facts (completion receipts, reader views) are still retained as diagnostics. Removes six resolveCleanup() calls; the counted baseline shrinks.

* refactor(kuna): let source-map and Kuna cache cleanup errors read their owner's release (#10856)

* refactor(browser): let late source-map fetch errors read their response's release

A pending source-map fetch and a response cancellation each record an AnalysisCleanupRelease that their cancellation or deadline failure reads; releasing the late response or the reader lock confirms it instead of pushing resolveCleanup(). Removes two resolveCleanup() calls; the counted baseline shrinks.

* refactor(kuna): let project-cache cleanup errors read each owner's release

Each retained Kuna resource owner (process, staging, hash descriptor, retired file) records a release that the errors reporting it read; an error completes once every owner it reports confirms, and retirement that moves staging to a retained file forwards the staging owner's release to the file's. Replaces the WeakRef report list, its pruning and the resolveCleanup() push. Removes one resolveCleanup() call; the counted baseline shrinks.

* refactor(process): forbid resolveCleanup() pushes; native markers read their supervisor's release (#10857)

* refactor(providers): let an attributed client failure read its source's completed cleanup

Re-attributing a failure whose source cleanup already completed now binds a claim reading that source's release instead of pushing resolveCleanup() onto the new error; a pending source is still bound as a dependency. Resources stay as history, as before. Removes one resolveCleanup() call; the counted baseline shrinks.

* refactor(process): let native command markers read their supervisor's release

ProviderProcessSupervisor records an AnalysisCleanupRelease that a stop proving the process ended confirms. Native command and LLDB resolver cleanup markers bind to their supervisor's release, so a verified stop by either owner completes them, instead of each owner pushing resolveCleanup() onto the markers it tracks. Removes the last two resolveCleanup() calls outside the error base; the counted baseline is empty.

* chore(verify): forbid resolveCleanup() pushes outside the error base

Every production owner now confirms a release its errors read, so the counted baseline is empty. The guard becomes an outright ban with no baseline entry.

* test(native): complete native command and LLDB markers through a direct supervisor stop

* refactor(errors): complete an error's cleanup from its owner's record and every dependency (#10892)

* refactor(errors): complete an error's cleanup from its owner's record and every dependency

* refactor(errors): complete test errors through an owner release and delete resolveCleanup() (#10898)

* refactor(android): compose JADX and Apktool cleanup failures through one shared owner (#10900)

* refactor(android): compose JADX and Apktool cleanup failures through one shared owner

* refactor(application): compose service cleanup failures through the shared owner (#10902)
2026-11-15 20:06:47 +08:00

419 lines
15 KiB
TypeScript

import type { ProcessInspectionFailure } from "../process/ProcessInspectionCleanup.js";
import { classifyLaunchFailureCode } from "../process/launchFailure.js";
import { randomUUID } from "node:crypto";
import type { RetainedResourceScope } from "../application/AnalysisProvider.js";
import {
AnalysisError,
type AnalysisCapturedOutput,
} from "../domain/analysisErrorBase.js";
import {
AnalysisCapabilityUnavailableError,
AnalysisTimeoutError,
cancelledBy,
carriedReason,
} from "../domain/analysisErrorCore.js";
import { ProviderAdapterError } from "../domain/providerAdapterError.js";
import { analysisErrorWithCleanupDependencies } from "../domain/analysisErrorCleanup.js";
import {
InternalInvariantError,
invariantViolation,
} from "../domain/internalInvariant.js";
import { jsonValueSchema, type JsonValue } from "../domain/jsonValue.js";
import { err, ok, type Result } from "../domain/result.js";
import {
prepareOwnedCommand,
runOwnedCommand,
OwnedCommandFailure,
} from "../process/OwnedCommand.js";
import type { ProviderProcessSnapshot } from "../process/ProviderProcess.js";
import { DarwinProcessOwnershipInspectionError } from "../process/DarwinProcessRunTokenReader.js";
import {
retainOwnedCommandCleanup,
processInspectionCancellationError,
processInspectionFailure,
bindProcessInspectionCancellations,
} from "../providers/OwnedCommandCleanup.js";
import { analysisClientFailureForOperation } from "../providers/AnalysisClientFailure.js";
import { jadxOperationTimeoutGuidance } from "./JadxOperationTimeout.js";
const JAVA_MODULE_LISTING_TIMEOUT_MS = 10_000;
const JAVA_MODULE_LISTING_MAX_OUTPUT_BYTES = 1024 * 1024;
export interface JadxJavaProbeOptions {
readonly resourceOwner: RetainedResourceScope;
readonly signal?: AbortSignal | undefined;
readonly operation?: string;
/** The Android operation owns this deadline; the probe also has its own bound. */
readonly operationDeadline?: {
readonly signal: AbortSignal;
readonly timeoutMs: number;
};
readonly launcher?: NonNullable<
Parameters<typeof runOwnedCommand>[2]
>["launcher"];
readonly timeoutMs?: number;
}
export interface JadxJavaProbeRefusal {
/** Actual preparation record; retained without changing timeout or fallback policy. */
readonly inspectionFailure?: ProcessInspectionFailure;
readonly code:
| "runtime_missing"
| "runtime_unavailable"
| "version_unresolved"
| "unsupported_version";
readonly message: string;
readonly diagnostics: Readonly<Record<string, JsonValue>>;
readonly kind: "java_probe" | "java_runtime";
}
interface JavaModules {
readonly compiler: true;
readonly major: number;
}
const refusal = (
code: JadxJavaProbeRefusal["code"],
message: string,
diagnostics: JadxJavaProbeRefusal["diagnostics"],
kind: JadxJavaProbeRefusal["kind"],
): Result<never, JadxJavaProbeRefusal> =>
err({ code, message, diagnostics, kind });
const capturedOutput = (
snapshot: ProviderProcessSnapshot,
): AnalysisCapturedOutput => ({
stdout: snapshot.stdout.text,
stderr: snapshot.stderr.text,
stdout_bytes: snapshot.stdout.observedBytes,
stderr_bytes: snapshot.stderr.observedBytes,
truncated:
snapshot.diagnosticTruncated === true || snapshot.outputIncomplete === true,
exit_code: snapshot.exitCode ?? null,
signal: snapshot.signal ?? null,
});
const projectRefusal = (
failure: JadxJavaProbeRefusal,
operation: string,
cause: unknown,
output?: AnalysisCapturedOutput,
) => {
const { stdout: _stdout, stderr: _stderr, ...facts } = failure.diagnostics;
return new AnalysisCapabilityUnavailableError(
"jadx",
operation,
failure.message,
{
cause,
userMessage: failure.message,
diagnostics: {
...facts,
failure_kind: failure.kind,
failure_code: failure.code,
},
...(output === undefined ? {} : { capturedOutput: output }),
},
);
};
/** Interpret one complete module listing before joining final cleanup. */
export const inspectJadxJava = async (
java: string,
environment: Readonly<Record<string, string | undefined>>,
options: JadxJavaProbeOptions,
): Promise<Result<JavaModules, JadxJavaProbeRefusal>> => {
const operation = options.operation ?? "inspect_jadx_configuration";
try {
return await options.resourceOwner.run(async () => {
let observed: Result<JavaModules, JadxJavaProbeRefusal> | undefined;
try {
await prepareOwnedCommand(options.signal);
await runOwnedCommand(
{
command: java,
arguments: ["--list-modules"],
runId: randomUUID(),
expectedCommand: null,
hostEnvironment: environment,
sweepTokenOwnedProcesses: true,
},
{
timeoutMs: options.timeoutMs ?? JAVA_MODULE_LISTING_TIMEOUT_MS,
diagnosticBytes: JAVA_MODULE_LISTING_MAX_OUTPUT_BYTES,
acceptNonZeroExit: true,
observeCompleted: (snapshot) => {
observed = parseJavaModules(java, snapshot);
},
},
{
signal: options.signal,
...(options.launcher === undefined
? {}
: { launcher: options.launcher }),
},
);
// runOwnedCommand observes every completed run before it resolves.
if (observed === undefined)
throw invariantViolation(
"Java probe completed without an observation",
);
return observed;
} catch (cause: unknown) {
const command =
cause instanceof OwnedCommandFailure ? cause : undefined;
const preparation = processInspectionFailure(cause);
const output =
command?.snapshot == null
? preparation instanceof DarwinProcessOwnershipInspectionError
? preparation.capturedOutput
: undefined
: capturedOutput(command.snapshot);
const inspectionCancellation =
command === undefined || command.preparationFailure !== undefined
? processInspectionCancellationError(cause, operation)
: undefined;
const cleanups = retainOwnedCommandCleanup(
cause,
options.resourceOwner,
"jadx",
operation,
);
let primary: AnalysisError;
if (observed !== undefined && !observed.ok) {
if (cleanups.length === 0) return observed;
primary = projectRefusal(observed.error, operation, cause, output);
} else if (
command?.reason === "cancelled" &&
command.cancellation !== undefined
) {
const reason = command.cancellation.reason;
const errorOptions = {
...(output === undefined ? {} : { capturedOutput: output }),
...(observed?.ok === true
? {
diagnostics: {
java_module_observation: {
compiler: observed.value.compiler,
major: observed.value.major,
},
},
}
: {}),
};
primary =
options.operationDeadline?.signal.aborted === true &&
reason === options.operationDeadline.signal.reason
? new AnalysisTimeoutError(
operation,
options.operationDeadline.timeoutMs,
{
...errorOptions,
cause: reason,
...jadxOperationTimeoutGuidance(
options.operationDeadline.timeoutMs,
),
},
)
: (inspectionCancellation ??
cancelledBy(operation, carriedReason(reason), errorOptions));
} else if (inspectionCancellation !== undefined) {
primary = inspectionCancellation;
} else if (
observed?.ok === true &&
command?.cleanupOwner !== undefined
) {
primary = new ProviderAdapterError("jadx", operation, {
cause,
...(output === undefined ? {} : { capturedOutput: output }),
diagnostics: {
stage: "cleanup",
java_module_observation: {
compiler: observed.value.compiler,
major: observed.value.major,
},
},
});
} else if (preparation !== undefined && command?.reason !== "timeout") {
primary = new ProviderAdapterError("jadx", operation, {
cause,
...(output === undefined ? {} : { capturedOutput: output }),
diagnostics: {
stage: "ownership_preparation",
...(!(
preparation instanceof DarwinProcessOwnershipInspectionError
) || preparation.compilerOutcome === undefined
? {}
: {
compiler_outcome: jsonValueSchema.parse(
preparation.compilerOutcome,
),
}),
},
});
} else if (cause instanceof AnalysisError) {
primary = cause;
} else if (cause instanceof InternalInvariantError) {
// A REA defect says nothing about the selected Java runtime.
primary = new ProviderAdapterError("jadx", operation, {
cause,
...(output === undefined ? {} : { capturedOutput: output }),
});
} else {
const failure = commandProbeRefusal(
java,
command,
cause,
options.timeoutMs ?? JAVA_MODULE_LISTING_TIMEOUT_MS,
);
if (preparation !== undefined)
Object.defineProperty(failure, "inspectionFailure", {
value: preparation,
});
if (cleanups.length === 0) return err(failure);
primary = projectRefusal(failure, operation, cause, output);
}
for (const cleanup of cleanups)
primary = analysisErrorWithCleanupDependencies(
primary,
cleanup,
operation,
);
throw bindProcessInspectionCancellations(cause, primary, operation);
}
});
} catch (cause: unknown) {
if (cause instanceof AnalysisError) throw cause;
throw analysisClientFailureForOperation(cause, "jadx", operation);
}
};
const commandProbeRefusal = (
java: string,
command:
| Pick<OwnedCommandFailure, "snapshot" | "reason" | "processError">
| undefined,
cause: unknown,
timeoutMs: number,
): JadxJavaProbeRefusal => {
const output =
command?.snapshot == null ? undefined : capturedOutput(command.snapshot);
const processError =
command?.processError ?? (cause instanceof Error ? cause : undefined);
const systemCode =
processError === undefined ? undefined : Reflect.get(processError, "code");
const missing = classifyLaunchFailureCode(systemCode)?.kind === "missing";
const limited = command?.reason === "output-limit";
const timedOut = command?.reason === "timeout";
return {
code: missing
? "runtime_missing"
: limited || timedOut
? "version_unresolved"
: "runtime_unavailable",
kind: missing ? "java_runtime" : "java_probe",
message: limited
? `The selected Java launcher ${java} exceeded the ${String(JAVA_MODULE_LISTING_MAX_OUTPUT_BYTES)}-byte module-listing output budget. This release has no runtime override. REA retained partial output but could not establish compiler or version availability. Inspect the selected launcher for verbose or unbounded output; java --list-modules should return a concise module listing. REA_JADX_OPERATION_TIMEOUT_MS does not raise this probe.`
: timedOut
? `The selected Java launcher ${java} did not finish the module-listing probe within ${String(timeoutMs)} ms. This release has no runtime override. Inspect its startup responsiveness and verify it with java --list-modules. REA_JADX_OPERATION_TIMEOUT_MS does not raise this probe.`
: `Cannot inspect selected Java runtime ${java}: ${missing ? `spawn java ${String(systemCode)}` : cause instanceof Error ? cause.message : cause === undefined ? `exit ${String(output?.exit_code ?? "unknown")}${output?.signal == null ? "" : ` (${output.signal})`}` : String(cause)}. Review the selected launcher and retained diagnostics.`,
diagnostics: {
java_executable: java,
phase: "module-inspection",
exit_code: output?.exit_code ?? null,
process_error_code: typeof systemCode === "string" ? systemCode : null,
signal: output?.signal ?? null,
killed: null,
stdout: output?.stdout ?? "",
stderr: output?.stderr ?? "",
output_truncated: output?.truncated ?? true,
...(limited
? {
failure: "output_limit",
output_limit_bytes: JAVA_MODULE_LISTING_MAX_OUTPUT_BYTES,
}
: {}),
...(timedOut
? { failure: "probe_terminated", deadline_ms: timeoutMs }
: {}),
},
};
};
const parseJavaModules = (
java: string,
snapshot: ProviderProcessSnapshot,
): Result<JavaModules, JadxJavaProbeRefusal> => {
if (snapshot.exitCode !== 0 || snapshot.signal !== null)
return err(
commandProbeRefusal(
java,
{ reason: "process", snapshot, processError: undefined },
undefined,
JAVA_MODULE_LISTING_TIMEOUT_MS,
),
);
const stdout = snapshot.stdout.text;
const stderr = snapshot.stderr.text;
const compiler = /^jdk\.compiler(?:@|$)/mu.test(stdout);
if (!compiler)
return refusal(
"runtime_missing",
`Selected Java runtime ${java} does not provide jdk.compiler. Select a full JDK including jdk.compiler via JAVA_HOME or PATH; verify it with java --list-modules. A JRE cannot compile REA's source bridge.`,
{
java_executable: java,
phase: "module-inspection",
jdk_compiler: false,
stdout,
stderr,
output_truncated: false,
},
"java_runtime",
);
const major = /^java\.base@(\d+)(?:[.+_-]|$)/mu.exec(stdout)?.[1];
if (major === undefined)
return refusal(
"version_unresolved",
`The selected Java launcher ${java} did not report a parseable java.base version in its module listing. Inspect the launcher output and verify it with java --list-modules.`,
{
java_executable: java,
phase: "module-inspection",
jdk_compiler: true,
java_major: null,
stdout,
stderr,
output_truncated: false,
},
"java_probe",
);
const majorNumber = Number(major);
if (!Number.isSafeInteger(majorNumber) || majorNumber <= 0)
return refusal(
"version_unresolved",
`The selected Java launcher ${java} reported an invalid java.base major version. Review the retained module listing.`,
{
java_executable: java,
phase: "module-inspection",
jdk_compiler: true,
java_major: null,
unparsed_java_major: major,
stdout,
stderr,
output_truncated: false,
},
"java_probe",
);
if (majorNumber < 17)
return refusal(
"unsupported_version",
`Selected Java runtime ${java} must be JDK 17 or newer and include jdk.compiler; verify it with java --list-modules.`,
{
java_executable: java,
phase: "module-inspection",
jdk_compiler: true,
java_major: major ?? null,
stdout,
stderr,
output_truncated: false,
},
"java_runtime",
);
return ok({ compiler: true, major: majorNumber });
};