fix(android): bound fragmented JADX MCP frame memory (#937)
* perf(android): avoid repeated MCP frame copies * fix(android): bound fragmented MCP frame memory * style(android): format JADX transport changes
This commit is contained in:
@@ -32,7 +32,8 @@ export class JadxMcpTransport implements Transport {
|
||||
readonly runId = randomUUID();
|
||||
#spawned: SpawnedOwnedProviderProcess | undefined;
|
||||
#supervisor: ProviderProcessSupervisor | undefined;
|
||||
#buffer = Buffer.alloc(0);
|
||||
#frameBuffer = Buffer.alloc(0);
|
||||
#frameLength = 0;
|
||||
#bytes = 0;
|
||||
#started = false;
|
||||
#closed = false;
|
||||
@@ -61,12 +62,16 @@ export class JadxMcpTransport implements Transport {
|
||||
stdin: "pipe",
|
||||
});
|
||||
this.#spawned = spawned;
|
||||
this.#supervisor = new ProviderProcessSupervisor({
|
||||
...spawned,
|
||||
ownsProcessLifetime: true,
|
||||
cleanup:
|
||||
spawned.cleanup ?? (() => cleanupOwnedProcessGroup(spawned.ownership)),
|
||||
});
|
||||
this.#supervisor = new ProviderProcessSupervisor(
|
||||
{
|
||||
...spawned,
|
||||
ownsProcessLifetime: true,
|
||||
cleanup:
|
||||
spawned.cleanup ??
|
||||
(() => cleanupOwnedProcessGroup(spawned.ownership)),
|
||||
},
|
||||
{ captureStdout: false },
|
||||
);
|
||||
if (
|
||||
spawned.process.stdin === undefined ||
|
||||
spawned.process.stdin === null ||
|
||||
@@ -117,6 +122,8 @@ export class JadxMcpTransport implements Transport {
|
||||
|
||||
async #stop(): Promise<void> {
|
||||
this.#closed = true;
|
||||
this.#frameBuffer = Buffer.alloc(0);
|
||||
this.#frameLength = 0;
|
||||
// A cancellation may race acquisition. Join it before inspecting ownership.
|
||||
await this.#starting?.catch(() => undefined);
|
||||
const process = this.#spawned?.process;
|
||||
@@ -161,22 +168,42 @@ export class JadxMcpTransport implements Transport {
|
||||
);
|
||||
return;
|
||||
}
|
||||
this.#buffer = Buffer.concat([this.#buffer, bytes]);
|
||||
try {
|
||||
let newline: number;
|
||||
while ((newline = this.#buffer.indexOf(10)) !== -1) {
|
||||
if (newline > MAX_FRAME_BYTES)
|
||||
let offset = 0;
|
||||
while (offset < bytes.length) {
|
||||
const newline = bytes.indexOf(10, offset);
|
||||
const end = newline === -1 ? bytes.length : newline;
|
||||
const fragment = bytes.subarray(offset, end);
|
||||
const frameBytes = this.#frameLength + fragment.length;
|
||||
if (frameBytes > MAX_FRAME_BYTES)
|
||||
throw new Error(`JADX MCP frame exceeds ${MAX_FRAME_BYTES} bytes`);
|
||||
const line = this.#buffer.subarray(0, newline).toString("utf8");
|
||||
this.#buffer = this.#buffer.subarray(newline + 1);
|
||||
this.#appendFrame(fragment, frameBytes);
|
||||
if (newline === -1) return;
|
||||
const line = this.#frameBuffer
|
||||
.subarray(0, this.#frameLength)
|
||||
.toString("utf8");
|
||||
this.#frameBuffer = Buffer.alloc(0);
|
||||
this.#frameLength = 0;
|
||||
this.onmessage?.(deserializeMessage(line));
|
||||
offset = newline + 1;
|
||||
}
|
||||
if (this.#buffer.length > MAX_FRAME_BYTES)
|
||||
throw new Error(`JADX MCP frame exceeds ${MAX_FRAME_BYTES} bytes`);
|
||||
} catch (cause) {
|
||||
this.#fail(cause instanceof Error ? cause : new Error(String(cause)));
|
||||
}
|
||||
};
|
||||
#appendFrame(fragment: Buffer, frameBytes: number): void {
|
||||
if (frameBytes > this.#frameBuffer.length) {
|
||||
const capacity = Math.min(
|
||||
MAX_FRAME_BYTES,
|
||||
Math.max(frameBytes, this.#frameBuffer.length * 2, 1),
|
||||
);
|
||||
const grown = Buffer.allocUnsafe(capacity);
|
||||
this.#frameBuffer.copy(grown, 0, 0, this.#frameLength);
|
||||
this.#frameBuffer = grown;
|
||||
}
|
||||
fragment.copy(this.#frameBuffer, this.#frameLength);
|
||||
this.#frameLength = frameBytes;
|
||||
}
|
||||
#fail(error: Error): void {
|
||||
this.#failure ??= error.message;
|
||||
this.onerror?.(error);
|
||||
|
||||
@@ -99,6 +99,8 @@ export type ProviderProcessDiagnostic =
|
||||
|
||||
/** Options for process lifecycle diagnostics. */
|
||||
export interface ProviderProcessSupervisorOptions {
|
||||
/** Retain stdout for diagnostics; disable when it carries a parsed protocol. Defaults to true. */
|
||||
readonly captureStdout?: boolean;
|
||||
readonly onDiagnostic?: (event: ProviderProcessDiagnostic) => void;
|
||||
}
|
||||
|
||||
@@ -235,7 +237,8 @@ export class ProviderProcessSupervisor {
|
||||
options: ProviderProcessSupervisorOptions = {},
|
||||
) {
|
||||
this.#options = options;
|
||||
this.#attach(launch.process.stdout, "stdout");
|
||||
if (options.captureStdout !== false)
|
||||
this.#attach(launch.process.stdout, "stdout");
|
||||
this.#attach(launch.process.stderr, "stderr");
|
||||
launch.process.once("exit", this.#onExit);
|
||||
launch.process.once("close", this.#onClose);
|
||||
|
||||
@@ -70,6 +70,7 @@ it("reuses immutable engine state while keeping each Evidence observation separa
|
||||
|
||||
it("bounds output per operation across a retained session rather than accumulating earlier captures", async () => {
|
||||
const { service, apk, launches, provider } = await setup("large-manifest");
|
||||
const expectedManifest = "x".repeat(1024 * 1024);
|
||||
for (let index = 0; index < 34; index += 1) {
|
||||
const result = await service.execute("inspect_android_package", {
|
||||
path: apk,
|
||||
@@ -78,8 +79,8 @@ it("bounds output per operation across a retained session rather than accumulati
|
||||
expect(
|
||||
androidResultSchemas.inspect_android_package.parse(
|
||||
result.value.normalized_result,
|
||||
).manifest.text.length,
|
||||
).toBe(1024 * 1024);
|
||||
).manifest.text,
|
||||
).toBe(expectedManifest);
|
||||
}
|
||||
expect(launches).toHaveLength(1);
|
||||
await provider.close();
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
import { EventEmitter } from "node:events";
|
||||
import { PassThrough } from "node:stream";
|
||||
import {
|
||||
serializeMessage,
|
||||
type JSONRPCMessage,
|
||||
} from "@modelcontextprotocol/client";
|
||||
import { expect, it } from "vitest";
|
||||
import type { ProviderProcessHandle } from "../../../src/process/ProviderProcess.js";
|
||||
import {
|
||||
JadxMcpTransport,
|
||||
type JadxLauncher,
|
||||
} from "../../../src/android/JadxMcpTransport.js";
|
||||
|
||||
class FixtureProcess extends EventEmitter implements ProviderProcessHandle {
|
||||
readonly pid = 1;
|
||||
readonly stdout = new PassThrough();
|
||||
readonly stdin = new PassThrough();
|
||||
readonly stderr = new PassThrough();
|
||||
readonly exitCode = null;
|
||||
readonly signalCode = null;
|
||||
|
||||
kill(): boolean {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
it("decodes split UTF-8 and newline bytes, then routes multiple complete frames", async () => {
|
||||
const process = new FixtureProcess();
|
||||
const launcher: JadxLauncher = async ({ runId }) => ({
|
||||
process,
|
||||
ownership: {
|
||||
runId,
|
||||
leaderPid: process.pid,
|
||||
processGroupId: process.pid,
|
||||
expectedParentPid: process.pid,
|
||||
},
|
||||
cleanup: async () => {
|
||||
process.emit("exit", 0, null);
|
||||
process.emit("close", 0, null);
|
||||
process.stdout.end();
|
||||
process.stderr.end();
|
||||
process.stdin.end();
|
||||
return { cleaned: true, signaled: false };
|
||||
},
|
||||
});
|
||||
const transport = new JadxMcpTransport(
|
||||
{ command: "fixture", arguments: [] },
|
||||
launcher,
|
||||
);
|
||||
const received: JSONRPCMessage[] = [];
|
||||
transport.onmessage = (message) => received.push(message);
|
||||
|
||||
await transport.start();
|
||||
const first = {
|
||||
jsonrpc: "2.0",
|
||||
id: 1,
|
||||
result: { content: [{ type: "text", text: "snow 雪 🦊" }] },
|
||||
} satisfies JSONRPCMessage;
|
||||
const second = {
|
||||
jsonrpc: "2.0",
|
||||
id: 2,
|
||||
result: { content: [{ type: "text", text: "second" }] },
|
||||
} satisfies JSONRPCMessage;
|
||||
const third = {
|
||||
jsonrpc: "2.0",
|
||||
id: 3,
|
||||
result: { content: [{ type: "text", text: "third" }] },
|
||||
} satisfies JSONRPCMessage;
|
||||
for (const byte of Buffer.from(serializeMessage(first)))
|
||||
process.stdout.write(Buffer.from([byte]));
|
||||
process.stdout.write(
|
||||
Buffer.from(serializeMessage(second) + serializeMessage(third)),
|
||||
);
|
||||
|
||||
expect(received).toEqual([first, second, third]);
|
||||
await transport.close();
|
||||
});
|
||||
|
||||
it("accepts a complete JSON-RPC frame at the 8 MiB boundary", async () => {
|
||||
const process = new FixtureProcess();
|
||||
const launcher: JadxLauncher = async ({ runId }) => ({
|
||||
process,
|
||||
ownership: {
|
||||
runId,
|
||||
leaderPid: process.pid,
|
||||
processGroupId: process.pid,
|
||||
expectedParentPid: process.pid,
|
||||
},
|
||||
cleanup: async () => {
|
||||
process.emit("exit", 0, null);
|
||||
process.emit("close", 0, null);
|
||||
process.stdout.end();
|
||||
process.stderr.end();
|
||||
process.stdin.end();
|
||||
return { cleaned: true, signaled: false };
|
||||
},
|
||||
});
|
||||
const transport = new JadxMcpTransport(
|
||||
{ command: "fixture", arguments: [] },
|
||||
launcher,
|
||||
);
|
||||
const received: JSONRPCMessage[] = [];
|
||||
transport.onmessage = (message) => received.push(message);
|
||||
const response = {
|
||||
jsonrpc: "2.0",
|
||||
id: 1,
|
||||
result: { content: [{ type: "text", text: "" }] },
|
||||
} satisfies JSONRPCMessage;
|
||||
const emptyFrameBytes = Buffer.byteLength(serializeMessage(response)) - 1;
|
||||
const maxFrameResponse = {
|
||||
...response,
|
||||
result: {
|
||||
content: [
|
||||
{ type: "text", text: "x".repeat(8 * 1024 * 1024 - emptyFrameBytes) },
|
||||
],
|
||||
},
|
||||
} satisfies JSONRPCMessage;
|
||||
const frame = Buffer.from(serializeMessage(maxFrameResponse));
|
||||
|
||||
expect(frame.at(-1)).toBe(10);
|
||||
expect(frame.length - 1).toBe(8 * 1024 * 1024);
|
||||
await transport.start();
|
||||
process.stdout.write(frame);
|
||||
|
||||
expect(received).toEqual([maxFrameResponse]);
|
||||
await transport.close();
|
||||
});
|
||||
Reference in New Issue
Block a user