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:
morluto
2026-10-07 16:50:41 +08:00
committed by GitHub
parent f430c416c7
commit eab34a9d8c
36 changed files with 1165 additions and 138 deletions
+13 -2
View File
@@ -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 };
};
+5 -4
View File
@@ -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
+23 -2
View File
@@ -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 };
};
+11 -5
View File
@@ -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;
+8
View File
@@ -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
View File
@@ -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 -5
View File
@@ -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
View File
@@ -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),
@@ -9,6 +9,8 @@ import type { Result } from "../../domain/result.js";
/** Static Android inspection boundary; implementation details belong to the provider. */
export interface AndroidAnalysisPort {
/** Cancel active work and join cleanup of any retained provider resources. */
close(): Promise<void>;
execute(
target: BinaryTarget,
request: AndroidRequest,
+10 -3
View File
@@ -1,4 +1,5 @@
import { z } from "incur";
import { AnalysisError } from "../domain/analysisErrorBase.js";
import { AndroidAnalysisService } from "../application/android/AndroidAnalysisService.js";
import { createAndroidAnalysisProvider } from "../composition/android.js";
import { CLI_COMMANDS } from "../cliCommandNames.js";
@@ -15,13 +16,19 @@ export const registerAndroidCommands = (
logger: Logger,
environment: Readonly<Record<string, string | undefined>>,
): void => {
const service = new AndroidAnalysisService(
createAndroidAnalysisProvider(environment),
);
const provider = createAndroidAnalysisProvider(environment);
const service = new AndroidAnalysisService(provider);
const execute = (name: string, operation: AndroidOperation, input: unknown) =>
withCommandCancellation((signal) =>
logCliCommand(logger, name, async () => {
const result = await service.execute(operation, input, { signal });
try {
await provider.close();
} catch (cause) {
if (cause instanceof AnalysisError)
return projectAnalysisError(cause);
throw cause;
}
return result.ok ? result.value : projectAnalysisError(result.error);
}),
);
@@ -12,7 +12,7 @@ export const ANDROID_TOOL_CONTRACTS = [
name: "inspect_android_package",
...toolContractMetadata("inspect_android_package"),
description:
"Inspect a local APK's package, SDK and permission declarations, decoded manifest and class/resource counts. Does not execute the APK or verify signatures. Requires a caller-supplied JADX MCP JAR and Java; uses one worker in an isolated temporary workspace.",
"Inspect a local APK's package, SDK and permission declarations, decoded manifest and class/resource counts. Does not execute the APK or verify signatures. Requires a caller-supplied JADX MCP JAR and JDK; uses one worker in an isolated temporary workspace.",
kind: "android-provider",
inputSchema: androidInputSchemas.inspect_android_package,
outputSchema: evidenceResultOf(
@@ -41,7 +41,7 @@ export const ANDROID_TOOL_CONTRACTS = [
name: "inspect_android_class",
...toolContractMetadata("inspect_android_class"),
description:
"Inspect one exact Android class's methods, fields and inner classes. Returns display signatures and explicit unknown DEX descriptors without materializing the whole application source.",
"Inspect one exact Android class's parsed methods, fields and inner classes, including synthetic members. Returns display signatures and explicit unknown DEX descriptors without generating source. Overload indices remain consistent within the artifact and engine session.",
kind: "android-provider",
inputSchema: androidInputSchemas.inspect_android_class,
outputSchema: evidenceResultOf(androidResultSchemas.inspect_android_class),
+3 -1
View File
@@ -93,5 +93,7 @@ const addAdjacency = (
nodeId: string,
entry: AdjacencyEntry,
): void => {
adjacency.set(nodeId, [...(adjacency.get(nodeId) ?? []), entry]);
const entries = adjacency.get(nodeId);
if (entries === undefined) adjacency.set(nodeId, [entry]);
else entries.push(entry);
};
+9 -5
View File
@@ -204,16 +204,20 @@ export const traceNativeInvestigationGraph = (
let reachedDepth = 0;
let truncated = false;
let reason: string | null = null;
const adjacency = new Map<string, NativeInvestigationEdge[]>();
for (const edge of graph.edges) {
const nodeId = direction === "forward" ? edge.from : edge.to;
if (nodeId === null) continue;
const entries = adjacency.get(nodeId);
if (entries === undefined) adjacency.set(nodeId, [edge]);
else entries.push(edge);
}
while (queue.length > 0) {
const current = queue.shift();
if (current === undefined) break;
reachedDepth = Math.max(reachedDepth, current.depth);
const adjacent = graph.edges.filter((edge) =>
direction === "forward"
? edge.from === current.id
: edge.to === current.id,
);
const adjacent = adjacency.get(current.id) ?? [];
for (const edge of adjacent) {
if (selectedEdges.size + unresolved.size >= limits.max_edges) {
File diff suppressed because one or more lines are too long
+1
View File
@@ -81,6 +81,7 @@ export const run = async (
});
createShutdown({
handle: transport.handle,
closeAndroid: transport.closeAndroid,
session,
unregisterReload,
dependencies,
+8 -2
View File
@@ -7,6 +7,7 @@ import { MCP_SHUTDOWN_FAILED } from "./messages.js";
export const createShutdown = (input: {
readonly handle: StdioServerHandle;
readonly closeAndroid?: () => Promise<void>;
readonly session: BinarySession;
readonly unregisterReload: () => void;
readonly dependencies: RuntimeDependencies;
@@ -23,8 +24,13 @@ export const createShutdown = (input: {
shutdownPromise ??= (async () => {
unregisterReload();
unregisterShutdown();
await handle.close();
await session.close({ retainProviderDocuments: true });
const results = await Promise.allSettled([
handle.close(),
input.closeAndroid?.(),
session.close({ retainProviderDocuments: true }),
]);
for (const result of results)
if (result.status === "rejected") throw result.reason;
})();
return shutdownPromise;
};
+21 -5
View File
@@ -1,3 +1,5 @@
import { createAndroidAnalysisProvider } from "../composition/android.js";
import type { AndroidAnalysisPort } from "../application/android/AndroidAnalysisPort.js";
import type { StdioServerHandle } from "@modelcontextprotocol/server/stdio";
import type { BinarySession } from "../application/binary/BinarySession.js";
@@ -27,6 +29,7 @@ export const startMcpTransport = async (
| {
readonly ok: true;
readonly handle: StdioServerHandle;
readonly closeAndroid: () => Promise<void>;
}
| { readonly ok: false }
> => {
@@ -50,14 +53,27 @@ export const startMcpTransport = async (
"Optional MCP adapter could not load; its peers remain available",
);
}
const androidProviders: AndroidAnalysisPort[] = [];
const closeAndroid = async (): Promise<void> => {
const results = await Promise.allSettled(
androidProviders.map((provider) => provider.close()),
);
for (const result of results)
if (result.status === "rejected") throw result.reason;
};
let handle: StdioServerHandle;
try {
handle = dependencies.serve(
() =>
(dependencies.createServer ?? createServer)(session, session, {
() => {
// The SDK can discard a discovery probe and construct a replacement server.
const android = createAndroidAnalysisProvider(dependencies.env);
androidProviders.push(android);
return (dependencies.createServer ?? createServer)(session, session, {
logger: serverContext.logger,
...optionalProviders,
}),
androidAnalysis: android,
});
},
{
onerror: () => {
serverLogger.error(MCP_CONNECTION_LOST);
@@ -66,7 +82,7 @@ export const startMcpTransport = async (
},
);
} catch (cause: unknown) {
await session.close();
await Promise.allSettled([session.close(), closeAndroid()]);
serverLogger.error(
{
error: cause instanceof Error ? cause.message : String(cause),
@@ -76,5 +92,5 @@ export const startMcpTransport = async (
dependencies.writeStderr(`${MCP_CONNECTION_START_FAILED}\n`);
return { ok: false };
}
return { ok: true, handle };
return { ok: true, handle, closeAndroid };
};
+11
View File
@@ -254,6 +254,12 @@ export class ProviderProcessSupervisor {
};
}
/** Begin a new observation on a retained process without retaining earlier output. */
resetOutput(): void {
this.#stdout.reset();
this.#stderr.reset();
}
/** Wait for process exit up to a caller-owned bounded interval. */
async waitForExit(timeoutMs: number): Promise<boolean> {
return waitForProcessEvent(
@@ -403,6 +409,11 @@ class ProcessOutputCapture {
return this.#bytes;
}
reset(): void {
this.#chunks.length = 0;
this.#bytes = 0;
}
append(chunk: Buffer): void {
this.#bytes += chunk.byteLength;
this.#chunks.push(Buffer.from(chunk));
+18 -3
View File
@@ -159,11 +159,26 @@ export const createServer = (
recordEvidenceWithUnknown,
};
registerBinaryAnalysisTools(toolContext);
const android = options.androidAnalysis ?? createAndroidAnalysisProvider();
const previousOnclose = server.server.onclose;
server.server.onclose = () => {
previousOnclose?.();
void android.close().catch((cause: unknown) => {
logger.error(
{ error: cause instanceof Error ? cause.message : String(cause) },
"Android provider cleanup failed",
);
});
};
const closeServer = server.close.bind(server);
server.close = async () => {
const results = await Promise.allSettled([closeServer(), android.close()]);
for (const result of results)
if (result.status === "rejected") throw result.reason;
};
registerAndroidTools(
server,
new AndroidAnalysisService(
options.androidAnalysis ?? createAndroidAnalysisProvider(),
),
new AndroidAnalysisService(android),
toolLogger,
recordEvidence,
);