fix(android): support owned JADX stdio on Windows (#1276)

Support owned JADX stdio on Windows x64, preserve protocol input errors through cancellation, and verify native stdin and Android CLI/MCP lifecycle on the real Windows host.

Closes #1262
This commit is contained in:
Ysopwnable
2026-10-09 20:34:42 +08:00
committed by GitHub
parent b71a591a60
commit 636b245f1b
21 changed files with 954 additions and 49 deletions
+65 -7
View File
@@ -1,6 +1,7 @@
import { constants } from "node:fs";
import { access, realpath, stat } from "node:fs/promises";
import { isAbsolute, join } from "node:path";
import { delimiter, isAbsolute, join, resolve } from "node:path";
import { systemWindowsNativeAuthority } from "../windows/WindowsNativeLoader.js";
import { AnalysisCapabilityUnavailableError } from "../domain/analysisErrorCore.js";
import type { AndroidOperation } from "../domain/android/androidAnalysis.js";
import type { JsonValue } from "../domain/jsonValue.js";
@@ -116,7 +117,7 @@ const readJadxConfiguration = async (
): Promise<JadxConfiguration> => {
requireSupportedHost();
const jar = await resolveJar(environment);
const java = resolveJava(environment);
const java = await resolveJava(environment, signal);
await requireJavaHomeExecutable(environment.JAVA_HOME, java);
const jvmArguments = resolveJvmArguments(environment);
await inspectJavaRuntime(java, environment, signal);
@@ -169,9 +170,26 @@ const requireEngineArchive = async (
const requireSupportedHost = (): void => {
if (process.platform === "linux" || process.platform === "darwin") return;
if (process.platform === "win32" && process.arch === "x64") {
const loaded = systemWindowsNativeAuthority();
if (loaded.available && loaded.authority.inspection.protocolStdin === true)
return;
throw configurationFailure(
"runtime_missing",
loaded.available
? "The bundled Windows native artifact lacks owned protocol stdin; use a matching current Windows x64 REA package."
: loaded.reason,
{
platform: process.platform,
architecture: process.arch,
phase: "process-ownership",
owned_protocol_stdin: false,
},
);
}
throw configurationFailure(
"unsupported_host",
`Android JADX subprocess ownership is unsupported on ${process.platform}; use Linux or macOS. The metadata bridge has real-provider verification on macOS arm64.`,
`Android JADX subprocess ownership is unsupported on ${process.platform}/${process.arch}; use Linux, macOS, or Windows x64 with its bundled native controls.`,
{ platform: process.platform },
);
};
@@ -206,12 +224,52 @@ const resolveJar = async (
}
};
const resolveJava = (
const resolveJava = async (
environment: Readonly<Record<string, string | undefined>>,
): string => {
if (environment.JAVA_HOME === undefined) return "java";
signal?: AbortSignal,
): Promise<string> => {
const executable = process.platform === "win32" ? "java.exe" : "java";
if (environment.JAVA_HOME === undefined) {
if (process.platform !== "win32") return executable;
const path =
Object.entries(environment).find(
([key]) => key.toLowerCase() === "path",
)?.[1] ?? "";
for (const directory of [process.cwd(), ...path.split(delimiter)]) {
signal?.throwIfAborted();
// Windows PATH commonly quotes individual entries containing spaces.
const selected =
directory.startsWith('"') && directory.endsWith('"')
? directory.slice(1, -1)
: directory;
const candidate = resolve(selected, executable);
try {
await access(candidate, constants.R_OK | constants.X_OK);
if ((await stat(candidate)).isFile()) return await realpath(candidate);
} catch (cause: unknown) {
if (
typeof cause === "object" &&
cause !== null &&
"code" in cause &&
(cause.code === "ENOENT" || cause.code === "ENOTDIR")
)
continue;
throw configurationFailure(
"runtime_missing",
`Cannot inspect selected Java executable ${candidate}: ${errorText(cause)}`,
{ java_executable: candidate },
cause,
);
}
}
throw configurationFailure(
"runtime_missing",
"Cannot find java.exe on the selected Windows PATH. Select a full JDK with JAVA_HOME or PATH, then verify it with java --list-modules. REA does not install Java.",
{ java_executable: executable },
);
}
if (isAbsolute(environment.JAVA_HOME))
return join(environment.JAVA_HOME, "bin", "java");
return join(environment.JAVA_HOME, "bin", executable);
throw configurationFailure(
"open_options_invalid",
"JAVA_HOME must select an existing JDK by absolute path; omit it to use java on PATH.",
+14 -2
View File
@@ -5,6 +5,7 @@ import {
type Transport,
} from "@modelcontextprotocol/client";
import { randomUUID } from "node:crypto";
import { finished } from "node:stream/promises";
import type {
OwnedProviderProcessSpawnOptions,
SpawnedOwnedProviderProcess,
@@ -19,7 +20,7 @@ import { ProviderCleanupError } from "../domain/providerCleanupError.js";
const MAX_FRAME_BYTES = 8 * 1024 * 1024;
const MAX_OPERATION_BYTES = 32 * 1024 * 1024;
/** Injectable process acquisition seam; the production launcher owns a POSIX group. */
/** Injectable acquisition seam; production owns a POSIX group or Windows job. */
export type JadxLauncher = (
options: OwnedProviderProcessSpawnOptions,
) => Promise<SpawnedOwnedProviderProcess>;
@@ -139,8 +140,19 @@ export class JadxMcpTransport implements Transport {
process?.stderr?.off("data", this.#countStderr);
process?.off("error", this.#error);
process?.off("exit", this.#exit);
process?.stdin?.off("error", this.#error);
const input = process?.stdin;
// A job termination can complete an in-flight pipe write asynchronously.
// Observe its errors until the owned Writable has finished closing.
const inputClosed =
input === undefined || input === null
? undefined
: finished(input, { readable: false, cleanup: true }).catch(
() => undefined,
);
const stopped = await this.#supervisor?.stop();
input?.destroy();
await inputClosed;
input?.off("error", this.#error);
this.onclose?.();
if (stopped?.status === "incomplete")
throw new ProviderCleanupError("jadx", [this.runId], {
+1 -1
View File
@@ -352,7 +352,7 @@ const workflowAvailabilityFor = ({
: "provider_missing",
remediation:
policy.androidAnalysisAvailability?.reason ??
"Set REA_JADX_MCP_JAR to a caller-supplied jadx-headless-mcp 0.7.1 JAR and provide a full JDK on Linux or macOS.",
"Set REA_JADX_MCP_JAR to a caller-supplied jadx-headless-mcp 0.7.1 JAR and provide a full JDK on Linux, macOS, or Windows x64 with its matching bundled native controls.",
};
const browser = browserProviderAvailability(name, kind, policy);
if (browser !== null) return browser;
+1 -4
View File
@@ -151,16 +151,13 @@ export const spawnOwnedProviderProcess = async (
REA_PROCESS_RUN_ID: options.runId,
};
if (platform === "win32" && process.platform === "win32") {
if (options.stdin === "pipe")
throw new Error(
"Owned Windows provider processes do not support protocol stdin",
);
const child = new WindowsOwnedProcess(
options.command,
options.arguments,
options.cwd,
environment,
options.windowsVerbatimArguments ?? false,
options.stdin === "pipe",
);
return {
process: child,
+1 -1
View File
@@ -311,6 +311,6 @@ const missingAndroidAvailability = async (): Promise<ProviderAvailability> => ({
status: "unavailable",
code: "not_configured",
reason:
"Set REA_JADX_MCP_JAR to a caller-supplied jadx-headless-mcp 0.7.1 JAR and provide a full JDK on Linux or macOS.",
"Set REA_JADX_MCP_JAR to a caller-supplied jadx-headless-mcp 0.7.1 JAR and provide a full JDK on Linux, macOS, or Windows x64 with its matching bundled native controls.",
diagnostics: { configured: false },
});
+18 -1
View File
@@ -7,7 +7,7 @@ import {
type WindowsNativeLoadHost,
} from "./WindowsNativeLoader.js";
const fixture = () => {
const fixture = (protocolStdin?: boolean) => {
const bytes = Buffer.alloc(128);
bytes.write("MZ");
bytes.writeUInt32LE(64, 0x3c);
@@ -51,6 +51,7 @@ const fixture = () => {
privateDacl: true,
atomicJobAssignment: true,
killOnOwnerClose: true,
...(protocolStdin === undefined ? {} : { protocolStdin }),
}),
};
},
@@ -59,6 +60,22 @@ const fixture = () => {
};
describe("packaged Windows native admission", () => {
it.each([true, false])(
"preserves protocol stdin capability %s alongside existing job controls",
(protocolStdin) => {
const value = fixture(protocolStdin);
expect(loadWindowsNativeAuthority(value.host)).toMatchObject({
available: true,
authority: {
inspection: {
protocolStdin,
atomicJobAssignment: true,
killOnOwnerClose: true,
},
},
});
},
);
it("loads only after compatibility and digest checks, preserving producer identity", () => {
const value = fixture();
expect(loadWindowsNativeAuthority(value.host)).toMatchObject({
+1
View File
@@ -43,6 +43,7 @@ const inspectionSchema = z.strictObject({
privateDacl: z.literal(true),
atomicJobAssignment: z.literal(true),
killOnOwnerClose: z.literal(true),
protocolStdin: z.boolean().optional(),
});
type NativeCall = (
+62 -1
View File
@@ -1,5 +1,5 @@
import { EventEmitter } from "node:events";
import { PassThrough } from "node:stream";
import { PassThrough, Writable } from "node:stream";
import { z } from "zod";
@@ -36,6 +36,7 @@ export const quoteWindowsProcessArgument = (value: string): string => {
export class WindowsOwnedProcess extends EventEmitter {
readonly stdout = new PassThrough();
readonly stderr = new PassThrough();
readonly stdin: Writable | null;
readonly signalCode: NodeJS.Signals | null = null;
exitCode: number | null = null;
readonly pid: number;
@@ -55,9 +56,14 @@ export class WindowsOwnedProcess extends EventEmitter {
cwd: string | undefined,
environment: NodeJS.ProcessEnv,
verbatim: boolean,
protocolStdin = false,
) {
super();
this.#authority = requireWindowsNativeAuthority();
if (protocolStdin && this.#authority.inspection.protocolStdin !== true)
throw new Error(
"The bundled Windows native artifact does not support owned protocol stdin; use a matching current Windows x64 REA package.",
);
const entries = Object.entries(environment)
.filter((entry): entry is [string, string] => entry[1] !== undefined)
.map(([key, value]) => `${key}=${value}`);
@@ -75,16 +81,70 @@ export class WindowsOwnedProcess extends EventEmitter {
line,
cwd ?? "",
entries,
...(protocolStdin ? [true] : []),
]),
);
this.pid = launched.pid;
this.#handle = launched.handle;
this.stdin = protocolStdin
? new Writable({
write: (chunk: unknown, _encoding, callback) => {
void this.#writeInput(chunk).then(
() => callback(),
(cause: unknown) =>
callback(
cause instanceof Error ? cause : new Error(String(cause)),
),
);
},
final: (callback) => {
try {
this.#authority.call("process_stdin_close", [this.#handle]);
callback();
} catch (cause: unknown) {
callback(
cause instanceof Error ? cause : new Error(String(cause)),
);
}
},
destroy: (cause, callback) => {
try {
if (!this.#closed)
this.#authority.call("process_stdin_close", [this.#handle]);
callback(cause);
} catch (failure: unknown) {
callback(
failure instanceof Error ? failure : new Error(String(failure)),
);
}
},
})
: null;
this.#settled = new Promise((resolve) => {
this.#settle = resolve;
});
this.#schedule();
}
async #writeInput(chunk: unknown): Promise<void> {
const bytes = z.instanceof(Buffer).parse(chunk);
const written = z
.number()
.int()
.nonnegative()
.max(Number.MAX_SAFE_INTEGER)
.parse(
await this.#authority.call("process_stdin_write", [
this.#handle,
bytes,
]),
);
if (written !== bytes.length)
throw new Error(
"Owned Windows input write did not preserve all requested bytes",
);
}
/** Terminate the retained job, never a PID supplied by another caller. */
kill(signal?: NodeJS.Signals | number): boolean {
if (signal === 0)
@@ -184,6 +244,7 @@ export class WindowsOwnedProcess extends EventEmitter {
if (this.#timer !== undefined) clearTimeout(this.#timer);
this.#authority.call("process_close", [this.#handle]);
this.#closed = true;
this.stdin?.destroy();
this.stdout.end();
this.stderr.end();
this.#settle?.();