fix(android)!: preserve JVM settings and reuse metadata sessions (#908)
* perf(graph): avoid repeated traversal edge scans and copies * fix(android)!: preserve JVM settings and reuse metadata sessions Read class metadata without generating application source, retain immutable serialized APK sessions, and join owned cleanup on cancellation and shutdown. BREAKING CHANGE: Android analysis now requires a full JDK 17 or newer with its compiler module for the packaged Java source bridge.
This commit is contained in:
@@ -2,7 +2,10 @@ import { constants, createReadStream } from "node:fs";
|
||||
import { chmod, copyFile } from "node:fs/promises";
|
||||
import { createHash } from "node:crypto";
|
||||
import { join } from "node:path";
|
||||
import { AnalysisInputError } from "../domain/analysisErrorCore.js";
|
||||
import {
|
||||
AnalysisInputError,
|
||||
AnalysisCapabilityUnavailableError,
|
||||
} from "../domain/analysisErrorCore.js";
|
||||
import type { AndroidOperation } from "../domain/android/androidAnalysis.js";
|
||||
|
||||
/** Stream a local file digest without retaining the APK or JAR in memory. */
|
||||
@@ -37,10 +40,18 @@ export const snapshotAndroidTarget = async (
|
||||
/** Fingerprint the actual immutable engine bytes executed for this observation. */
|
||||
export const snapshotAndroidEngine = async (
|
||||
source: string,
|
||||
sha256: string,
|
||||
root: string,
|
||||
operation: AndroidOperation,
|
||||
): Promise<{ path: string; sha256: string }> => {
|
||||
const path = join(root, "engine.jar");
|
||||
await copyFile(source, path, constants.COPYFILE_EXCL);
|
||||
await chmod(path, 0o400);
|
||||
return { path, sha256: await hashAndroidFile(path) };
|
||||
if ((await hashAndroidFile(path)) !== sha256)
|
||||
throw new AnalysisCapabilityUnavailableError(
|
||||
"jadx",
|
||||
operation,
|
||||
"REA_JADX_MCP_JAR bytes changed during admission; retry with a stable engine file.",
|
||||
);
|
||||
return { path, sha256 };
|
||||
};
|
||||
|
||||
@@ -137,19 +137,20 @@ const searchClasses = async (
|
||||
engine: Engine,
|
||||
): Promise<JsonValue> => {
|
||||
const classes: string[] = [];
|
||||
const pageSize = 4096;
|
||||
let total: number | undefined;
|
||||
do {
|
||||
const page = jadxClassPageSchema.parse(
|
||||
await tools.json("list_classes", {
|
||||
offset: classes.length,
|
||||
limit: 200,
|
||||
limit: pageSize,
|
||||
}),
|
||||
);
|
||||
if (
|
||||
(total !== undefined && total !== page.total) ||
|
||||
page.offset !== classes.length ||
|
||||
page.limit !== 200 ||
|
||||
page.items.length > 200
|
||||
page.limit !== pageSize ||
|
||||
page.items.length > pageSize
|
||||
)
|
||||
throw new AnalysisOutputError(
|
||||
request.operation,
|
||||
@@ -307,7 +308,7 @@ const traceReferences = async (
|
||||
throw new AnalysisCapabilityUnavailableError(
|
||||
"jadx",
|
||||
request.operation,
|
||||
`JADX ${JADX_RELEASE.version} references select the first same-name method; ${summary.full_name}.${methodName} has ${candidates.length} overloads. No unambiguous reference result is available.`,
|
||||
`References require a unique method name; ${summary.full_name}.${methodName} has ${candidates.length} overloads. No unambiguous reference result is available.`,
|
||||
);
|
||||
const expectedTarget =
|
||||
methodName === undefined
|
||||
|
||||
@@ -9,6 +9,7 @@ import { JADX_JAR_CONFIGURATION_REMEDIATION } from "./JadxRelease.js";
|
||||
export interface JadxConfiguration {
|
||||
readonly jar: string;
|
||||
readonly java: string;
|
||||
readonly jvmArguments: readonly string[];
|
||||
}
|
||||
|
||||
/** Admit explicit local tooling without installing or changing host configuration. */
|
||||
@@ -20,7 +21,7 @@ export const resolveJadxConfiguration = async (
|
||||
new AnalysisCapabilityUnavailableError("jadx", operation, reason);
|
||||
if (process.platform !== "linux" && process.platform !== "darwin")
|
||||
throw unavailable(
|
||||
`Android JADX subprocess ownership is unsupported on ${process.platform}; use Linux or macOS. Only Linux has real-provider verification.`,
|
||||
`Android JADX subprocess ownership is unsupported on ${process.platform}; use Linux or macOS. The metadata bridge has real-provider verification on macOS arm64.`,
|
||||
);
|
||||
const jar = environment.REA_JADX_MCP_JAR;
|
||||
if (environment.JAVA_HOME !== undefined && !isAbsolute(environment.JAVA_HOME))
|
||||
@@ -55,5 +56,25 @@ export const resolveJadxConfiguration = async (
|
||||
);
|
||||
}
|
||||
}
|
||||
return { jar: await realpath(jar), java };
|
||||
const jvmArguments: string[] = [];
|
||||
for (const [name, prefix, suffix] of [
|
||||
["REA_JADX_HEAP_MIB", "-Xmx", "m"],
|
||||
["REA_JADX_ACTIVE_PROCESSOR_COUNT", "-XX:ActiveProcessorCount=", ""],
|
||||
] as const) {
|
||||
const value = environment[name];
|
||||
if (value === undefined) continue;
|
||||
if (!/^[1-9]\d*$/u.test(value) || !Number.isSafeInteger(Number(value)))
|
||||
throw unavailable(
|
||||
`${name} must be a positive safe integer; received ${value}.`,
|
||||
);
|
||||
if (
|
||||
name === "REA_JADX_ACTIVE_PROCESSOR_COUNT" &&
|
||||
Number(value) > 2_147_483_647
|
||||
)
|
||||
throw unavailable(
|
||||
`${name} exceeds the JVM's signed 32-bit processor-count range.`,
|
||||
);
|
||||
jvmArguments.push(`${prefix}${value}${suffix}`);
|
||||
}
|
||||
return { jar: await realpath(jar), java, jvmArguments };
|
||||
};
|
||||
|
||||
@@ -17,7 +17,7 @@ import { cleanupOwnedProcessGroup } from "../process/ProcessOwnership.js";
|
||||
import { ProviderCleanupError } from "../domain/providerCleanupError.js";
|
||||
|
||||
const MAX_FRAME_BYTES = 8 * 1024 * 1024;
|
||||
const MAX_SESSION_BYTES = 32 * 1024 * 1024;
|
||||
const MAX_OPERATION_BYTES = 32 * 1024 * 1024;
|
||||
|
||||
/** Injectable process acquisition seam; the production launcher owns a POSIX group. */
|
||||
export type JadxLauncher = (
|
||||
@@ -109,6 +109,12 @@ export class JadxMcpTransport implements Transport {
|
||||
return this.#failure;
|
||||
}
|
||||
|
||||
/** Scope both the byte budget and diagnostic retention to the next serialized request. */
|
||||
beginOperation(): void {
|
||||
this.#bytes = 0;
|
||||
this.#supervisor?.resetOutput();
|
||||
}
|
||||
|
||||
async #stop(): Promise<void> {
|
||||
this.#closed = true;
|
||||
// A cancellation may race acquisition. Join it before inspecting ownership.
|
||||
@@ -136,10 +142,10 @@ export class JadxMcpTransport implements Transport {
|
||||
};
|
||||
readonly #countStderr = (chunk: Buffer | string): void => {
|
||||
this.#bytes += Buffer.byteLength(chunk);
|
||||
if (this.#bytes > MAX_SESSION_BYTES)
|
||||
if (this.#bytes > MAX_OPERATION_BYTES)
|
||||
this.#fail(
|
||||
new Error(
|
||||
`JADX session output exceeds ${MAX_SESSION_BYTES} bytes; no complete result is available`,
|
||||
`JADX operation output exceeds ${MAX_OPERATION_BYTES} bytes; no complete result is available`,
|
||||
),
|
||||
);
|
||||
};
|
||||
@@ -147,10 +153,10 @@ export class JadxMcpTransport implements Transport {
|
||||
if (this.#closed) return;
|
||||
const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
||||
this.#bytes += bytes.length;
|
||||
if (this.#bytes > MAX_SESSION_BYTES) {
|
||||
if (this.#bytes > MAX_OPERATION_BYTES) {
|
||||
this.#fail(
|
||||
new Error(
|
||||
`JADX session output exceeds ${MAX_SESSION_BYTES} bytes; no complete result is available`,
|
||||
`JADX operation output exceeds ${MAX_OPERATION_BYTES} bytes; no complete result is available`,
|
||||
),
|
||||
);
|
||||
return;
|
||||
|
||||
@@ -4,6 +4,14 @@ import { jsonValueSchema } from "../domain/jsonValue.js";
|
||||
import type { AndroidOperation } from "../domain/android/androidAnalysis.js";
|
||||
|
||||
const count = z.number().int().nonnegative();
|
||||
/** Values observed inside the exact JVM producing the analysis. */
|
||||
export const jadxRuntimeSchema = z.object({
|
||||
engine_reported_version: z.string().min(1),
|
||||
max_heap_bytes: z.number().int().positive().safe(),
|
||||
available_processors: z.number().int().positive(),
|
||||
java_version: z.string().min(1),
|
||||
metadata_scope: z.literal("parsed_members"),
|
||||
});
|
||||
export const jadxLoadSchema = z.object({
|
||||
state: z.literal("LOADED"),
|
||||
apk_path: z.string(),
|
||||
|
||||
+157
-41
@@ -1,4 +1,7 @@
|
||||
import { z } from "zod";
|
||||
import { chmod, copyFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import type { AndroidAnalysisPort } from "../application/android/AndroidAnalysisPort.js";
|
||||
import type { ExecutionOptions } from "../application/AnalysisProvider.js";
|
||||
import { AnalysisError } from "../domain/analysisErrorBase.js";
|
||||
@@ -6,24 +9,29 @@ import {
|
||||
AnalysisCancelledError,
|
||||
AnalysisCapabilityUnavailableError,
|
||||
AnalysisOutputError,
|
||||
AnalysisInputError,
|
||||
AnalysisTimeoutError,
|
||||
} from "../domain/analysisErrorCore.js";
|
||||
import { ProviderAdapterError } from "../domain/providerAdapterError.js";
|
||||
import { ProviderCleanupError } from "../domain/providerCleanupError.js";
|
||||
import type { AndroidRequest } from "../domain/android/androidAnalysis.js";
|
||||
import type { BinaryTarget } from "../domain/binaryTarget.js";
|
||||
import { err, ok } from "../domain/result.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import { PrivateRuntimeRoot } from "../process/PrivateRuntimeRoot.js";
|
||||
import {
|
||||
snapshotAndroidEngine,
|
||||
hashAndroidFile,
|
||||
snapshotAndroidTarget,
|
||||
} from "./AndroidTargetSnapshot.js";
|
||||
import { resolveJadxConfiguration } from "./JadxConfiguration.js";
|
||||
import type { JadxLauncher } from "./JadxMcpTransport.js";
|
||||
import { JADX_HEAP_XMX_ARGUMENT } from "./JadxRelease.js";
|
||||
|
||||
import { JadxSession } from "./JadxSession.js";
|
||||
|
||||
const OPERATION_TIMEOUT_MS = 120_000;
|
||||
const BRIDGE_SOURCE = fileURLToPath(
|
||||
new URL("../../bridge/android/ReaJadxBridge.java", import.meta.url),
|
||||
);
|
||||
type Outcome = Awaited<ReturnType<AndroidAnalysisPort["execute"]>>;
|
||||
|
||||
const waitForTurn = (
|
||||
@@ -74,11 +82,11 @@ const executionError = (context: {
|
||||
});
|
||||
};
|
||||
|
||||
const cleanup = async (
|
||||
const cleanup = async <Value>(
|
||||
session: JadxSession | undefined,
|
||||
root: PrivateRuntimeRoot | undefined,
|
||||
previous: Outcome,
|
||||
): Promise<Outcome> => {
|
||||
previous: Result<Value, AnalysisError>,
|
||||
): Promise<Result<Value, AnalysisError>> => {
|
||||
const diagnostics = {
|
||||
previous_error: previous.ok
|
||||
? null
|
||||
@@ -125,10 +133,23 @@ const cleanup = async (
|
||||
return previous;
|
||||
};
|
||||
|
||||
/** One queued engine per REA instance, with a fresh owned workspace for every request. */
|
||||
interface RetainedSession {
|
||||
readonly key: string;
|
||||
readonly root: PrivateRuntimeRoot;
|
||||
readonly session: JadxSession;
|
||||
readonly snapshot: string;
|
||||
readonly jarHash: string;
|
||||
readonly bridgeHash: string;
|
||||
}
|
||||
|
||||
/** One serialized, immutable APK session per REA instance, retired on idle or shutdown. */
|
||||
export class JadxProvider implements AndroidAnalysisPort {
|
||||
#tail: Promise<void> = Promise.resolve();
|
||||
#cleanupFailure: AnalysisError | undefined;
|
||||
#retained: RetainedSession | undefined;
|
||||
#idle: NodeJS.Timeout | undefined;
|
||||
readonly #shutdown = new AbortController();
|
||||
#closePromise: Promise<void> | undefined;
|
||||
constructor(
|
||||
readonly environment: Readonly<
|
||||
Record<string, string | undefined>
|
||||
@@ -142,30 +163,69 @@ export class JadxProvider implements AndroidAnalysisPort {
|
||||
request: AndroidRequest,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Outcome> {
|
||||
if (this.#shutdown.signal.aborted)
|
||||
return err(new AnalysisCancelledError(request.operation));
|
||||
const signal =
|
||||
options?.signal === undefined
|
||||
? this.#shutdown.signal
|
||||
: AbortSignal.any([options.signal, this.#shutdown.signal]);
|
||||
const predecessor = this.#tail;
|
||||
let release: () => void = () => {};
|
||||
this.#tail = new Promise<void>((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
try {
|
||||
await waitForTurn(predecessor, request, options?.signal);
|
||||
await waitForTurn(predecessor, request, signal);
|
||||
} catch {
|
||||
void predecessor.then(release);
|
||||
return err(new AnalysisCancelledError(request.operation));
|
||||
}
|
||||
try {
|
||||
if (options?.signal?.aborted === true)
|
||||
if (signal.aborted)
|
||||
return err(new AnalysisCancelledError(request.operation));
|
||||
if (this.#cleanupFailure !== undefined) return err(this.#cleanupFailure);
|
||||
const outcome = await this.#execute(target, request, options);
|
||||
clearTimeout(this.#idle);
|
||||
const outcome = await this.#execute(target, request, { signal });
|
||||
if (!outcome.ok && outcome.error.cleanupIncomplete)
|
||||
this.#cleanupFailure = outcome.error;
|
||||
if (outcome.ok) this.#scheduleIdle();
|
||||
return outcome;
|
||||
} finally {
|
||||
release();
|
||||
}
|
||||
}
|
||||
|
||||
/** Cancel queued/active operations and join the owned engine and workspace cleanup. */
|
||||
close(): Promise<void> {
|
||||
this.#shutdown.abort();
|
||||
clearTimeout(this.#idle);
|
||||
this.#closePromise ??= this.#tail.then(() => this.#retire());
|
||||
return this.#closePromise;
|
||||
}
|
||||
|
||||
async #retire(): Promise<void> {
|
||||
if (this.#cleanupFailure !== undefined) throw this.#cleanupFailure;
|
||||
const retained = this.#retained;
|
||||
this.#retained = undefined;
|
||||
const result = await cleanup(
|
||||
retained?.session,
|
||||
retained?.root,
|
||||
ok(undefined),
|
||||
);
|
||||
if (!result.ok) {
|
||||
this.#cleanupFailure = result.error;
|
||||
throw result.error;
|
||||
}
|
||||
}
|
||||
|
||||
#scheduleIdle(): void {
|
||||
this.#idle = setTimeout(() => {
|
||||
const retirement = this.#tail.then(() => this.#retire());
|
||||
this.#tail = retirement.catch(() => undefined);
|
||||
}, 60_000);
|
||||
this.#idle.unref();
|
||||
}
|
||||
|
||||
async #execute(
|
||||
target: BinaryTarget,
|
||||
request: AndroidRequest,
|
||||
@@ -191,47 +251,99 @@ export class JadxProvider implements AndroidAnalysisPort {
|
||||
request.operation,
|
||||
);
|
||||
signal.throwIfAborted();
|
||||
root = await PrivateRuntimeRoot.create({ prefix: "rea-android-" });
|
||||
const engine = await snapshotAndroidEngine(configuration.jar, root.path);
|
||||
const snapshot = await snapshotAndroidTarget(
|
||||
target.path,
|
||||
target.sha256,
|
||||
root.path,
|
||||
request.operation,
|
||||
);
|
||||
signal.throwIfAborted();
|
||||
session = new JadxSession(
|
||||
{
|
||||
command: configuration.java,
|
||||
arguments: [
|
||||
JADX_HEAP_XMX_ARGUMENT,
|
||||
"-XX:ActiveProcessorCount=1",
|
||||
"-jar",
|
||||
engine.path,
|
||||
"--threads",
|
||||
"1",
|
||||
"--max-source-bytes",
|
||||
"1048576",
|
||||
"--decompile-timeout-ms",
|
||||
"90000",
|
||||
],
|
||||
cwd: root.path,
|
||||
hostEnvironment: this.environment,
|
||||
env: {
|
||||
_JAVA_OPTIONS: `${JADX_HEAP_XMX_ARGUMENT} -XX:ActiveProcessorCount=1`,
|
||||
const jarHash = await hashAndroidFile(configuration.jar);
|
||||
const bridgeHash = await hashAndroidFile(BRIDGE_SOURCE);
|
||||
if ((await hashAndroidFile(target.path)) !== target.sha256)
|
||||
throw new AnalysisInputError(request.operation, undefined, [
|
||||
{
|
||||
path: ["path"],
|
||||
reason: "invalid_value",
|
||||
message:
|
||||
"APK bytes changed after admission; retry against a stable file.",
|
||||
},
|
||||
},
|
||||
this.launcher,
|
||||
);
|
||||
]);
|
||||
const key = JSON.stringify({
|
||||
path: target.path,
|
||||
sha256: target.sha256,
|
||||
jar: configuration.jar,
|
||||
jarHash,
|
||||
bridgeHash,
|
||||
java: configuration.java,
|
||||
arguments: configuration.jvmArguments,
|
||||
options: [
|
||||
this.environment.JAVA_TOOL_OPTIONS,
|
||||
this.environment._JAVA_OPTIONS,
|
||||
this.environment.JDK_JAVA_OPTIONS,
|
||||
this.environment.PATH,
|
||||
this.environment.JAVA_HOME,
|
||||
],
|
||||
});
|
||||
if (this.#retained !== undefined && this.#retained.key !== key)
|
||||
await this.#retire();
|
||||
let retained = this.#retained;
|
||||
if (retained === undefined) {
|
||||
root = await PrivateRuntimeRoot.create({ prefix: "rea-android-" });
|
||||
const engine = await snapshotAndroidEngine(
|
||||
configuration.jar,
|
||||
jarHash,
|
||||
root.path,
|
||||
request.operation,
|
||||
);
|
||||
const snapshot = await snapshotAndroidTarget(
|
||||
target.path,
|
||||
target.sha256,
|
||||
root.path,
|
||||
request.operation,
|
||||
);
|
||||
const bridge = join(root.path, "ReaJadxBridge.java");
|
||||
await copyFile(BRIDGE_SOURCE, bridge);
|
||||
await chmod(bridge, 0o400);
|
||||
if ((await hashAndroidFile(bridge)) !== bridgeHash)
|
||||
throw new AnalysisCapabilityUnavailableError(
|
||||
"jadx",
|
||||
request.operation,
|
||||
"REA Android bridge bytes changed during admission; retry with a stable installation.",
|
||||
);
|
||||
signal.throwIfAborted();
|
||||
session = new JadxSession(
|
||||
{
|
||||
command: configuration.java,
|
||||
arguments: [
|
||||
...configuration.jvmArguments,
|
||||
"--class-path",
|
||||
engine.path,
|
||||
bridge,
|
||||
],
|
||||
cwd: root.path,
|
||||
hostEnvironment: this.environment,
|
||||
},
|
||||
this.launcher,
|
||||
);
|
||||
retained = {
|
||||
key,
|
||||
root,
|
||||
session,
|
||||
snapshot,
|
||||
jarHash: engine.sha256,
|
||||
bridgeHash,
|
||||
};
|
||||
}
|
||||
root = retained.root;
|
||||
session = retained.session;
|
||||
const { snapshot } = retained;
|
||||
outcome = ok(
|
||||
await session.execute({
|
||||
request,
|
||||
target,
|
||||
snapshot,
|
||||
jarHash: engine.sha256,
|
||||
jarHash: retained.jarHash,
|
||||
bridgeHash: retained.bridgeHash,
|
||||
signal,
|
||||
}),
|
||||
);
|
||||
signal.throwIfAborted();
|
||||
this.#retained = retained;
|
||||
return outcome;
|
||||
} catch (cause) {
|
||||
outcome = err(
|
||||
executionError({
|
||||
@@ -243,6 +355,10 @@ export class JadxProvider implements AndroidAnalysisPort {
|
||||
}),
|
||||
);
|
||||
}
|
||||
// An existing session also needs retirement when admission fails before selection.
|
||||
root ??= this.#retained?.root;
|
||||
session ??= this.#retained?.session;
|
||||
this.#retained = undefined;
|
||||
return cleanup(session, root, outcome);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,11 +6,11 @@ export const JADX_RELEASE = Object.freeze({
|
||||
url: "https://github.com/1013503897/jadx-headless-mcp/releases/download/v0.7.1/jadx-headless-mcp-0.7.1-all.jar",
|
||||
});
|
||||
|
||||
/** JVM heap ceiling applied to every owned JADX worker process. */
|
||||
export const JADX_HEAP_LIMIT_MIB = 512;
|
||||
|
||||
/** JVM `-Xmx` argument matching {@link JADX_HEAP_LIMIT_MIB}. */
|
||||
export const JADX_HEAP_XMX_ARGUMENT = `-Xmx${JADX_HEAP_LIMIT_MIB}m`;
|
||||
/** Identity of REA's metadata bridge, distinct from the producing engine. */
|
||||
export const JADX_BRIDGE_IDENTITY = Object.freeze({
|
||||
name: "rea-jadx-bridge",
|
||||
version: "1",
|
||||
});
|
||||
|
||||
/** Remediation when `REA_JADX_MCP_JAR` is missing or not an absolute path. */
|
||||
export const JADX_JAR_CONFIGURATION_REMEDIATION = `Set REA_JADX_MCP_JAR to the absolute path of a caller-supplied jadx-headless-mcp ${JADX_RELEASE.version} JAR. REA does not download or install it.`;
|
||||
@@ -26,5 +26,6 @@ export const JADX_PROVIDER_IDENTITY = Object.freeze({
|
||||
export const JADX_LIMITATIONS = [
|
||||
"Static decompiler observations do not establish runtime behavior; the APK is never executed.",
|
||||
"Method signatures use provider display types; exact DEX descriptors and instruction offsets are unavailable. Overload indices are local to this engine and artifact.",
|
||||
"Class inventories use parsed metadata before code generation, including synthetic members that may be omitted from decompiled source. Source positions remain unknown.",
|
||||
"Manifest summary fields are extracted by the upstream engine; decoded XML is retained for verification. APK signatures, split APKs, native libraries and Android runtime capture are not verified by this provider.",
|
||||
] as const;
|
||||
|
||||
+42
-17
@@ -16,11 +16,12 @@ import { analyzeJadxRequest, type JadxToolPort } from "./JadxAnalysis.js";
|
||||
import { JadxMcpTransport, type JadxLauncher } from "./JadxMcpTransport.js";
|
||||
import {
|
||||
jadxLoadSchema,
|
||||
jadxRuntimeSchema,
|
||||
parseJadxEnvelope,
|
||||
parseJadxJson,
|
||||
} from "./JadxProtocol.js";
|
||||
import {
|
||||
JADX_HEAP_LIMIT_MIB,
|
||||
JADX_BRIDGE_IDENTITY,
|
||||
JADX_RELEASE,
|
||||
JADX_PROVIDER_IDENTITY,
|
||||
JADX_LIMITATIONS,
|
||||
@@ -30,7 +31,7 @@ import {
|
||||
export class JadxSession {
|
||||
readonly transport: JadxMcpTransport;
|
||||
readonly #client = new Client({ name: "rea-android-adapter", version: "1" });
|
||||
readonly #raw: JsonValue[] = [];
|
||||
#loaded: ReturnType<typeof jadxLoadSchema.parse> | undefined;
|
||||
|
||||
constructor(
|
||||
options: Omit<OwnedProviderProcessSpawnOptions, "runId" | "stdin">,
|
||||
@@ -45,6 +46,7 @@ export class JadxSession {
|
||||
readonly target: BinaryTarget;
|
||||
readonly snapshot: string;
|
||||
readonly jarHash: string;
|
||||
readonly bridgeHash: string;
|
||||
readonly signal: AbortSignal;
|
||||
}): Promise<AnalysisExecution> {
|
||||
const { request, target, snapshot, jarHash, signal } = context;
|
||||
@@ -54,42 +56,64 @@ export class JadxSession {
|
||||
signal.addEventListener("abort", abort, { once: true });
|
||||
try {
|
||||
signal.throwIfAborted();
|
||||
await this.#client.connect(this.transport, { timeout: 30_000 });
|
||||
this.transport.beginOperation();
|
||||
const raw: JsonValue[] = [];
|
||||
if (this.#loaded === undefined)
|
||||
await this.#client.connect(this.transport, { timeout: 30_000 });
|
||||
const server = this.#client.getServerVersion();
|
||||
if (
|
||||
server?.name !== "jadx-headless-mcp" ||
|
||||
server.version !== JADX_RELEASE.version
|
||||
server?.name !== JADX_BRIDGE_IDENTITY.name ||
|
||||
server.version !== JADX_BRIDGE_IDENTITY.version
|
||||
)
|
||||
throw new AnalysisCapabilityUnavailableError(
|
||||
"jadx",
|
||||
request.operation,
|
||||
`Expected jadx-headless-mcp ${JADX_RELEASE.version}; server reported ${server?.name ?? "unknown"} ${server?.version ?? "unknown"}.`,
|
||||
`Expected ${JADX_BRIDGE_IDENTITY.name} ${JADX_BRIDGE_IDENTITY.version}; server reported ${server?.name ?? "unknown"} ${server?.version ?? "unknown"}.`,
|
||||
);
|
||||
const tools = this.#tools(request, target, signal);
|
||||
const loaded = jadxLoadSchema.parse(
|
||||
await tools.json("load_apk", {
|
||||
path: snapshot,
|
||||
threads: 1,
|
||||
resources: "full",
|
||||
}),
|
||||
const tools = this.#tools(request, target, signal, raw);
|
||||
const runtime = jadxRuntimeSchema.parse(
|
||||
await tools.json("rea_jvm_status", {}),
|
||||
);
|
||||
if (runtime.engine_reported_version !== JADX_RELEASE.version)
|
||||
throw new AnalysisCapabilityUnavailableError(
|
||||
"jadx",
|
||||
request.operation,
|
||||
`Expected engine ${JADX_RELEASE.version}; JAR reported ${runtime.engine_reported_version}.`,
|
||||
);
|
||||
const loaded =
|
||||
this.#loaded ??
|
||||
jadxLoadSchema.parse(
|
||||
await tools.json("load_apk", {
|
||||
path: snapshot,
|
||||
threads: 1,
|
||||
resources: "full",
|
||||
}),
|
||||
);
|
||||
if (loaded.apk_path !== snapshot)
|
||||
throw new AnalysisOutputError(
|
||||
request.operation,
|
||||
"JADX loaded a different APK path than the admitted snapshot",
|
||||
);
|
||||
this.#loaded = loaded;
|
||||
const engine = {
|
||||
name: "jadx-headless-mcp",
|
||||
version: JADX_RELEASE.version,
|
||||
version: runtime.engine_reported_version,
|
||||
artifact_sha256: jarHash,
|
||||
source_revision:
|
||||
jarHash === JADX_RELEASE.sha256 ? JADX_RELEASE.revision : null,
|
||||
worker_count: 1,
|
||||
heap_limit_mib: JADX_HEAP_LIMIT_MIB,
|
||||
heap_limit_mib:
|
||||
Math.floor(runtime.max_heap_bytes / (1024 * 1024)) || null,
|
||||
} as const;
|
||||
const result = await analyzeJadxRequest(tools, request, loaded, engine);
|
||||
return createAnalysisExecution(result, JADX_PROVIDER_IDENTITY, {
|
||||
rawResult: { server, jar_sha256: jarHash, calls: this.#raw },
|
||||
rawResult: {
|
||||
server,
|
||||
bridge_sha256: context.bridgeHash,
|
||||
jar_sha256: jarHash,
|
||||
loaded,
|
||||
calls: raw,
|
||||
},
|
||||
subject: target,
|
||||
limitations: JADX_LIMITATIONS,
|
||||
locations:
|
||||
@@ -115,6 +139,7 @@ export class JadxSession {
|
||||
request: AndroidRequest,
|
||||
target: BinaryTarget,
|
||||
signal: AbortSignal,
|
||||
raw: JsonValue[],
|
||||
): JadxToolPort {
|
||||
const call = async (
|
||||
name: string,
|
||||
@@ -126,7 +151,7 @@ export class JadxSession {
|
||||
{ timeout: 120_000, signal },
|
||||
);
|
||||
const envelope = parseJadxEnvelope(response, request.operation);
|
||||
this.#raw.push({
|
||||
raw.push({
|
||||
operation: name,
|
||||
input,
|
||||
response: jsonValueSchema.parse(response),
|
||||
|
||||
Reference in New Issue
Block a user