Skip to content

armgit / rea

Public Imported from GitHub
0

Reverse engineer anything with agents, from app behavior down to native binaries.

fix(ghidra): own operation-scoped JVM failure evidence

morluto91884c374385
diff --git a/docs/binary-diagnostics.md b/docs/binary-diagnostics.md
index b49c0ca23..e11e1a79f 100644
--- a/docs/binary-diagnostics.md
+++ b/docs/binary-diagnostics.md
@@ -160,7 +160,12 @@ launch builder. It is a configuration fact, not measured memory use or proof of
the effective JVM limit; JVM environment options may affect that limit.
When a Windows script wrapper selects the JVM, this value remains unknown.
Historical stdout and stderr remain available, but classification uses only the
-failing operation's `failure_output`. Output draining waits at most one second,
+failing operation's `failure_output`. Retained stdout and stderr share an 8 MiB
+budget, but every drained byte is scanned for `java.lang.OutOfMemoryError`:
+`failure_output.observed_oome` records the latest confirmed token's bounded line per stream from
+the failing operation, with its byte offset, even after the budget is spent. These observations own OOME detection; retained text that ends at a class-name prefix cannot confirm a complete token. `line_complete` distinguishes a known line end from an incomplete trailing context; `invalid_utf8` marks replacement-decoded context.
+Incomplete operation output without an observed OOME keeps the original failure code and explains that a memory cause cannot be ruled out. Incompleteness alone does not confirm a memory constraint or justify heap-specific advice. Token context stays within the failing operation's checkpoint; a class-name prefix in a different identifier is not OOME evidence. A trailing bare token requires an observed stream EOF to establish its boundary.
+Output draining waits at most one second,
subject to earlier cancellation or the startup deadline. `output_incomplete`
marks a snapshot taken before stream closure; cleanup ownership remains with
the session until release succeeds.
diff --git a/src/ghidra/GhidraClient.ts b/src/ghidra/GhidraClient.ts
index becbddafb..76a7fd81c 100644
--- a/src/ghidra/GhidraClient.ts
+++ b/src/ghidra/GhidraClient.ts
@@ -45,6 +45,8 @@ import type { GhidraFunctionOperation } from "./GhidraFunctionValues.js";
import {
createGhidraDiagnostics,
ghidraDiagnosticStream,
+ ghidraFailureOutput,
+ GHIDRA_JVM_OOME_MARKER,
GHIDRA_PROCESS_DIAGNOSTIC_BYTES,
} from "./GhidraDiagnostics.js";
import { GhidraLaunchError, type GhidraLaunch } from "./GhidraLauncher.js";
@@ -890,6 +892,7 @@ export class GhidraClient {
this.#launch = partialLaunch;
this.#process = new ProviderProcessSupervisor(partialLaunch, {
maxDiagnosticBytes: GHIDRA_PROCESS_DIAGNOSTIC_BYTES,
+ outputToken: GHIDRA_JVM_OOME_MARKER,
onDiagnostic: (event) => this.#onProcessDiagnostic(event),
});
this.#startupOutputCheckpoint = this.#process.checkpointOutput();
@@ -913,6 +916,7 @@ export class GhidraClient {
this.#launch = launched.value;
this.#process = new ProviderProcessSupervisor(launched.value, {
maxDiagnosticBytes: GHIDRA_PROCESS_DIAGNOSTIC_BYTES,
+ outputToken: GHIDRA_JVM_OOME_MARKER,
onDiagnostic: (event) => this.#onProcessDiagnostic(event),
});
this.#startupOutputCheckpoint = this.#process.checkpointOutput();
@@ -1268,11 +1272,7 @@ export class GhidraClient {
const failureOutput: JsonValue | undefined =
scoped === undefined
? undefined
- : {
- stdout: ghidraDiagnosticStream(scoped.snapshot.stdout, this.#token),
- stderr: ghidraDiagnosticStream(scoped.snapshot.stderr, this.#token),
- complete: scoped.complete && !this.#outputDrainIncomplete,
- };
+ : ghidraFailureOutput(scoped, this.#token, this.#outputDrainIncomplete);
return createGhidraDiagnostics({
targetPath: this.#options.targetPath,
targetSha256: this.#options.targetSha256,
@@ -1319,11 +1319,7 @@ export class GhidraClient {
output_incomplete: snapshot.outputIncomplete === true || drainIncomplete,
stdout: ghidraDiagnosticStream(snapshot.stdout, token),
stderr: ghidraDiagnosticStream(snapshot.stderr, token),
- failure_output: {
- stdout: ghidraDiagnosticStream(scoped.snapshot.stdout, token),
- stderr: ghidraDiagnosticStream(scoped.snapshot.stderr, token),
- complete: scoped.complete && !drainIncomplete,
- },
+ failure_output: ghidraFailureOutput(scoped, token, drainIncomplete),
});
}
diff --git a/src/ghidra/GhidraDiagnostics.test.ts b/src/ghidra/GhidraDiagnostics.test.ts
index be17253eb..cdf43b518 100644
--- a/src/ghidra/GhidraDiagnostics.test.ts
+++ b/src/ghidra/GhidraDiagnostics.test.ts
@@ -1,3 +1,5 @@
+import { ProcessOutputTokenScanner } from "../process/ProcessOutputTokenScanner.js";
+import { ghidraFailureOutput } from "./GhidraDiagnostics.js";
import { expect, it } from "vitest";
import { createGhidraDiagnostics } from "./GhidraDiagnostics.js";
@@ -21,3 +23,49 @@ it("does not reuse historical operation-scoped failure output without a current
expect(diagnostics.stdout).toEqual({ text: "historical OOME" });
expect(diagnostics).not.toHaveProperty("failure_output");
});
+
+it.each([false, true])(
+ "redacts credential tails only when the captured line's right edge is incomplete (open=%s)",
+ (open) => {
+ const scanner = new ProcessOutputTokenScanner("java.lang.OutOfMemoryError");
+ const prefix = Buffer.from("prior operation prefix ");
+ scanner.scan(prefix, 0);
+ const suffix = Buffer.from(
+ open
+ ? "java.lang.OutOfMemoryError: e-trans"
+ : "java.lang.OutOfMemoryError: Java heap space\n",
+ );
+ scanner.scan(suffix, prefix.length);
+ const marker = scanner.latestWithin(
+ prefix.length,
+ prefix.length + suffix.length,
+ );
+ if (marker === undefined) throw new Error("Expected confirmed class token");
+ const stream = { text: "", bytes: 0, observedBytes: suffix.length };
+ const output = ghidraFailureOutput(
+ {
+ snapshot: {
+ stdout: stream,
+ stderr: stream,
+ exitCode: null,
+ signal: null,
+ },
+ complete: false,
+ markers: [{ stream: "stderr", ...marker }],
+ },
+ "e-transport-secret",
+ false,
+ );
+ expect(output).toMatchObject({
+ observed_oome: [
+ {
+ line: open
+ ? "java.lang.OutOfMemoryError: [REDACTED]"
+ : "java.lang.OutOfMemoryError: Java heap space",
+ line_complete: !open,
+ truncated: true,
+ },
+ ],
+ });
+ },
+);
diff --git a/src/ghidra/GhidraDiagnostics.ts b/src/ghidra/GhidraDiagnostics.ts
index 3dddd737c..f03cb7fd4 100644
--- a/src/ghidra/GhidraDiagnostics.ts
+++ b/src/ghidra/GhidraDiagnostics.ts
@@ -1,12 +1,18 @@
import type { JsonValue } from "../domain/jsonValue.js";
import { redactCapturedTransportCredential } from "../process/ProviderDiagnosticRedaction.js";
-import type { ProviderProcessSnapshot } from "../process/ProviderProcess.js";
+import type {
+ ProviderProcessOutputSince,
+ ProviderProcessSnapshot,
+} from "../process/ProviderProcess.js";
import type { GhidraLaunch } from "./GhidraLauncher.js";
import type { GhidraTransportKind } from "./GhidraTransport.js";
/** Aggregate in-memory retention budget for this provider's launcher output. */
export const GHIDRA_PROCESS_DIAGNOSTIC_BYTES = 8 * 1024 * 1024;
+/** JVM error class located in all launcher output, beyond the retention budget. */
+export const GHIDRA_JVM_OOME_MARKER = "java.lang.OutOfMemoryError";
+
/** Inputs needed to project bounded diagnostics for one Ghidra runtime. */
export interface GhidraDiagnosticsOptions {
readonly targetPath: string;
@@ -98,6 +104,41 @@ export const createGhidraDiagnostics = (
};
};
+/**
+ * Operation-scoped output, plus OOME lines observed after the checkpoint even
+ * when the retention budget dropped them from the retained text.
+ */
+export const ghidraFailureOutput = (
+ scoped: ProviderProcessOutputSince,
+ token: string | undefined,
+ drainIncomplete: boolean,
+): JsonValue => ({
+ stdout: ghidraDiagnosticStream(scoped.snapshot.stdout, token),
+ stderr: ghidraDiagnosticStream(scoped.snapshot.stderr, token),
+ complete: scoped.complete && !drainIncomplete,
+ observed_oome: (scoped.markers ?? []).map((marker) => {
+ const bytes = Buffer.byteLength(marker.line, "utf8");
+ return {
+ stream: marker.stream,
+ offset: marker.offset,
+ line: redactCapturedTransportCredential(
+ {
+ text: marker.line,
+ bytes,
+ // A cut line may end in a partial credential.
+ observedBytes:
+ marker.trailingContextIncomplete === true ? bytes + 1 : bytes,
+ },
+ token,
+ "[REDACTED]",
+ ),
+ line_complete: marker.trailingContextIncomplete !== true,
+ ...(marker.truncated ? { truncated: true } : {}),
+ ...(marker.invalidUtf8 === true ? { invalid_utf8: true } : {}),
+ };
+ }),
+});
+
export const ghidraDiagnosticStream = (
stream: ProviderProcessSnapshot["stdout"],
token: string | undefined,
diff --git a/src/ghidra/GhidraProvider.behavior.test.ts b/src/ghidra/GhidraProvider.behavior.test.ts
index d03b92477..49aee30f3 100644
--- a/src/ghidra/GhidraProvider.behavior.test.ts
+++ b/src/ghidra/GhidraProvider.behavior.test.ts
@@ -1,3 +1,4 @@
+import { ProcessOutputTokenScanner } from "../process/ProcessOutputTokenScanner.js";
import { GhidraNativeAotSnapshotOwner } from "./GhidraNativeAotSnapshotOwner.js";
import { AnalysisCleanupLease } from "../artifacts/AnalysisCleanupLease.js";
import { resolvedAnalysisError } from "../domain/analysisErrorBase.js";
@@ -3360,6 +3361,23 @@ const failureOutput = (stdout = "", stderr = "") => ({
stdout: output(stdout),
stderr: output(stderr),
complete: true,
+ observed_oome: (["stdout", "stderr"] as const).flatMap((stream) => {
+ const bytes = Buffer.from(stream === "stdout" ? stdout : stderr);
+ const scanner = new ProcessOutputTokenScanner("java.lang.OutOfMemoryError");
+ scanner.scan(bytes, 0);
+ scanner.finish();
+ const observed = scanner.latestWithin(0, bytes.length);
+ return observed === undefined
+ ? []
+ : [
+ {
+ stream,
+ offset: observed.offset,
+ line: observed.line,
+ truncated: observed.truncated,
+ },
+ ];
+ }),
});
const projectFailure = async (
kind: "cancelled" | "process" | "protocol" | "remote" | "timeout",
@@ -3551,6 +3569,45 @@ describe("Ghidra OOME error projection", () => {
});
});
+describe("Ghidra OOME beyond the retention budget", () => {
+ it("projects an observed OOME line that the retained text omits", async () => {
+ const projected = await projectFailure("process", {
+ stdout: output(""),
+ stderr: output(""),
+ failure_output: {
+ ...failureOutput("", ""),
+ complete: false,
+ observed_oome: [
+ {
+ stream: "stderr",
+ offset: 9_000_000,
+ line: "ERROR Abort due to Headless analyzer error: Java heap space (HeadlessAnalyzer) java.lang.OutOfMemoryError: Java heap space",
+ },
+ ],
+ },
+ configured_jvm_max_heap: "4G",
+ });
+ expect(projected).toMatchObject({
+ code: "resource_constraint",
+ details: {
+ resource: "memory",
+ reported_limits: { configured_jvm_max_heap: "4G" },
+ },
+ });
+ expect(projected.message).toContain("Java heap space");
+ });
+
+ it("keeps the original failure when incomplete output shows no OOME", async () => {
+ const projected = await projectFailure("process", {
+ stdout: output(""),
+ stderr: output(""),
+ failure_output: { ...failureOutput("", ""), complete: false },
+ configured_jvm_max_heap: "4G",
+ });
+ expect(projected.code).toBe("execution_failure");
+ });
+});
+
it("reuses readiness only inside its active task and provider lifetime", async () => {
let probes = 0;
let version = "21.0.11";
@@ -3746,3 +3803,82 @@ it.each([
}
},
);
+
+it.each([
+ {
+ unrelated: "INFO unrelated capacity: unable to create native thread",
+ reported: "Java heap space",
+ heapAdvice: true,
+ },
+ {
+ unrelated: "INFO unrelated configuration: Java heap space",
+ reported: "Metaspace",
+ heapAdvice: false,
+ },
+])(
+ "binds Ghidra OOME detail to the reporting line instead of unrelated output ($reported)",
+ async ({ unrelated, reported, heapAdvice }) => {
+ const projected = await projectFailure("process", {
+ failure_output: failureOutput(
+ `${unrelated}\njava.lang.OutOfMemoryError: ${reported}\n`,
+ ),
+ configured_jvm_max_heap: "4G",
+ });
+ expect(projected).toMatchObject({
+ code: "resource_constraint",
+ details: { resource: "memory" },
+ });
+ expect(projected.message).toContain(reported);
+ expect(
+ projected.remediation.action.includes("GHIDRA_HEADLESS_MAXMEM"),
+ ).toBe(heapAdvice);
+ },
+);
+
+it("does not infer a complete OOME token from a budget-cut text prefix", async () => {
+ const projected = await projectFailure("process", {
+ failure_output: {
+ stdout: output("java.lang.OutOfMemoryError"),
+ stderr: output(""),
+ complete: false,
+ observed_oome: [],
+ },
+ });
+ expect(projected.code).toBe("execution_failure");
+ expect(projected.message).toContain("a memory cause cannot be ruled out");
+});
+
+it.each([false, true])(
+ "preserves valid OOME facts among malformed observations without inventing a constraint (confirmed=%s)",
+ async (confirmed) => {
+ const malformed: JsonValue[] = [
+ null,
+ {},
+ { stream: "stderr", offset: 0, line: "" },
+ { stream: "unknown", offset: 0, line: "java.lang.OutOfMemoryError" },
+ ];
+ const projected = await projectFailure("process", {
+ failure_output: {
+ complete: false,
+ observed_oome: [
+ ...malformed,
+ ...(confirmed
+ ? [
+ {
+ stream: "stderr",
+ offset: 0,
+ line: "java.lang.OutOfMemoryError: Metaspace",
+ },
+ ]
+ : []),
+ ],
+ },
+ });
+ expect(projected.code).toBe(
+ confirmed ? "resource_constraint" : "execution_failure",
+ );
+ expect(projected.message).toContain(
+ confirmed ? "Metaspace" : "a memory cause cannot be ruled out",
+ );
+ },
+);
diff --git a/src/ghidra/GhidraProviderClient.ts b/src/ghidra/GhidraProviderClient.ts
index d8c1917c8..f6e6b8f16 100644
--- a/src/ghidra/GhidraProviderClient.ts
+++ b/src/ghidra/GhidraProviderClient.ts
@@ -1,3 +1,4 @@
+import { z } from "zod";
import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js";
import { artifactFilePrimaryFailure } from "../artifacts/ArtifactFileOperation.js";
import { fileURLToPath } from "node:url";
@@ -958,32 +959,96 @@ const projectPrimarySessionError = (
failure.message,
context,
);
+ const output =
+ failure.kind === "start" ||
+ failure.kind === "process" ||
+ failure.kind === "protocol" ||
+ failure.kind === "timeout"
+ ? readGhidraFailureOutput(failure.diagnostics.failure_output)
+ : undefined;
const memoryFailure = projectObservedJvmMemoryFailure(
operation,
failure,
context,
+ output,
);
+ const uncertainty =
+ output?.complete === false
+ ? "Ghidra's output for this operation is incomplete. No OutOfMemoryError was confirmed; a memory cause cannot be ruled out."
+ : undefined;
if (memoryFailure !== undefined) return memoryFailure;
if (failure.kind === "timeout") {
const timeoutMs = failure.timeoutMs ?? startupTimeoutMs;
- return new AnalysisTimeoutError(
- operation,
- timeoutMs,
+ const guidance =
failure.message === GHIDRA_STARTUP_DEADLINE_ELAPSED
- ? { ...context, ...ghidraStartupTimeoutGuidance(timeoutMs) }
- : context,
- );
+ ? ghidraStartupTimeoutGuidance(timeoutMs)
+ : undefined;
+ return new AnalysisTimeoutError(operation, timeoutMs, {
+ ...context,
+ ...guidance,
+ ...(uncertainty === undefined
+ ? {}
+ : {
+ userMessage: `${
+ guidance?.userMessage ??
+ `Ghidra did not finish within its ${String(timeoutMs)} ms deadline.`
+ } ${uncertainty}`,
+ }),
+ });
}
const exited = exitedProviderMessage(operation, failure, health);
if (exited !== undefined)
return new ProviderAdapterError("ghidra", operation, {
...context,
- userMessage: exited,
+ userMessage:
+ uncertainty === undefined ? exited : `${exited} ${uncertainty}`,
});
- return new ProviderAdapterError("ghidra", operation, context);
+ return new ProviderAdapterError("ghidra", operation, {
+ ...context,
+ ...(uncertainty === undefined
+ ? {}
+ : {
+ userMessage: uncertainty,
+ remediationAction:
+ "Review the retained Ghidra diagnostics and capture complete launcher output before choosing resource-specific recovery.",
+ }),
+ });
+};
+
+const observedJvmFailureSchema = z.object({
+ stream: z.enum(["stdout", "stderr"]),
+ offset: z.number().int().nonnegative(),
+ line: z.string().min(1),
+});
+
+interface GhidraFailureOutputView {
+ readonly oomText: string | undefined;
+ readonly complete: boolean | undefined;
+}
+
+/** Read the scoped capture once; unavailable fields remain unconfirmed. */
+const readGhidraFailureOutput = (
+ scoped: JsonValue | undefined,
+): GhidraFailureOutputView | undefined => {
+ if (scoped === null || typeof scoped !== "object" || Array.isArray(scoped))
+ return undefined;
+ const observedLines = Array.isArray(scoped.observed_oome)
+ ? scoped.observed_oome.flatMap((observed) => {
+ const parsed = observedJvmFailureSchema.safeParse(observed);
+ return parsed.success ? [parsed.data.line] : [];
+ })
+ : [];
+ return {
+ oomText: observedLines.length === 0 ? undefined : observedLines.join("\n"),
+ complete:
+ typeof scoped.complete === "boolean" ? scoped.complete : undefined,
+ };
};
-/** Project only OOME evidence captured during the operation that failed. */
+/**
+ * Project OOME evidence captured during the operation that failed, including
+ * OOME lines the process supervisor observed beyond the retention budget.
+ */
const projectObservedJvmMemoryFailure = (
operation: AnalysisOperation,
failure: GhidraSessionError,
@@ -991,35 +1056,10 @@ const projectObservedJvmMemoryFailure = (
readonly cause: GhidraSessionError;
readonly diagnostics: Readonly<Record<string, JsonValue>>;
},
+ scoped: GhidraFailureOutputView | undefined,
): AnalysisResourceConstraintError | undefined => {
- if (
- failure.kind !== "start" &&
- failure.kind !== "process" &&
- failure.kind !== "protocol" &&
- failure.kind !== "timeout"
- )
- return undefined;
- const scoped = failure.diagnostics.failure_output;
- if (
- scoped === null ||
- typeof scoped !== "object" ||
- Array.isArray(scoped) ||
- typeof scoped.stdout !== "object" ||
- scoped.stdout === null ||
- typeof scoped.stderr !== "object" ||
- scoped.stderr === null
- )
- return undefined;
- const streamText = (value: JsonValue): string =>
- typeof value === "object" &&
- value !== null &&
- !Array.isArray(value) &&
- typeof value.text === "string"
- ? value.text
- : "";
- const output = `${streamText(scoped.stdout)}\n${streamText(scoped.stderr)}`;
- if (!/java\.lang\.OutOfMemoryError(?:\s*:|\b)/u.test(output))
- return undefined;
+ const output = scoped?.oomText;
+ if (output === undefined) return undefined;
const threadCapacity = /unable to create native thread/iu.test(output);
const heapExhaustion = /Java heap space|GC overhead limit exceeded/iu.test(
output,
diff --git a/src/process/ProcessOutputTokenScanner.test.ts b/src/process/ProcessOutputTokenScanner.test.ts
new file mode 100644
index 000000000..79bf61ec5
--- /dev/null
+++ b/src/process/ProcessOutputTokenScanner.test.ts
@@ -0,0 +1,237 @@
+import { EventEmitter } from "node:events";
+import { PassThrough } from "node:stream";
+import { afterEach, describe, expect, it } from "vitest";
+import {
+ PROCESS_OUTPUT_TOKEN_CONTEXT_BYTES,
+ ProcessOutputTokenScanner,
+} from "./ProcessOutputTokenScanner.js";
+import { ProviderProcessSupervisor } from "./ProviderProcess.js";
+
+const MARKER = "java.lang.OutOfMemoryError";
+const OOME_LINE =
+ "ERROR Abort due to Headless analyzer error: Java heap space (HeadlessAnalyzer) java.lang.OutOfMemoryError: Java heap space";
+
+const cleanups: (() => void)[] = [];
+afterEach(() => {
+ for (const cleanup of cleanups.splice(0)) cleanup();
+});
+
+const supervised = (maxDiagnosticBytes = 64) => {
+ const producer = Object.assign(new EventEmitter(), {
+ stdout: new PassThrough(),
+ stderr: new PassThrough(),
+ exitCode: null,
+ signalCode: null,
+ kill: () => false,
+ });
+ const supervisor = new ProviderProcessSupervisor(
+ { process: producer, ownsProcessLifetime: false },
+ { maxDiagnosticBytes, outputToken: MARKER },
+ );
+ cleanups.push(() => {
+ supervisor.dispose();
+ producer.stdout.destroy();
+ producer.stderr.destroy();
+ });
+ return { producer, supervisor };
+};
+
+describe("ProviderProcessSupervisor output marker", () => {
+ it("observes a marker printed after the retention budget is exhausted", () => {
+ const { producer, supervisor } = supervised();
+ const checkpoint = supervisor.checkpointOutput();
+ producer.stdout.write("x".repeat(200));
+ producer.stderr.write(`${OOME_LINE}\n\tat frame\n`);
+ const scoped = supervisor.snapshotOutputSince(checkpoint);
+ expect(scoped.complete).toBe(false);
+ expect(scoped.snapshot.stderr.text).toBe("");
+ expect(scoped.markers).toEqual([
+ {
+ stream: "stderr",
+ offset: OOME_LINE.indexOf(MARKER),
+ line: OOME_LINE,
+ truncated: false,
+ },
+ ]);
+ });
+
+ it("detects a marker and its line split across chunks", () => {
+ const { producer, supervisor } = supervised(0);
+ const checkpoint = supervisor.checkpointOutput();
+ producer.stdout.write("progress\n");
+ const text = `${OOME_LINE}\nnext\n`;
+ const split = text.indexOf(MARKER) + 7;
+ producer.stdout.write(text.slice(0, 20));
+ producer.stdout.write(text.slice(20, split));
+ producer.stdout.write(text.slice(split, split + 10));
+ producer.stdout.write(text.slice(split + 10));
+ expect(supervisor.snapshotOutputSince(checkpoint).markers).toEqual([
+ {
+ stream: "stdout",
+ offset: "progress\n".length + OOME_LINE.indexOf(MARKER),
+ line: OOME_LINE,
+ truncated: false,
+ },
+ ]);
+ });
+
+ it("does not attribute a marker from before the checkpoint", () => {
+ const { producer, supervisor } = supervised(0);
+ producer.stderr.write(`${OOME_LINE}\n`);
+ const checkpoint = supervisor.checkpointOutput();
+ producer.stderr.write("later unrelated failure\n");
+ expect(supervisor.snapshotOutputSince(checkpoint).markers).toBeUndefined();
+ });
+
+ it("forgets markers on reset and for checkpoints from another epoch", () => {
+ const { producer, supervisor } = supervised(0);
+ const stale = supervisor.checkpointOutput();
+ producer.stderr.write(`${OOME_LINE}\n`);
+ supervisor.resetOutput();
+ expect(supervisor.snapshotOutputSince(stale).markers).toBeUndefined();
+ const current = supervisor.checkpointOutput();
+ producer.stderr.write("after reset\n");
+ expect(supervisor.snapshotOutputSince(current).markers).toBeUndefined();
+ });
+
+ it("does not scan when no marker is configured", () => {
+ const producer = Object.assign(new EventEmitter(), {
+ stdout: new PassThrough(),
+ stderr: new PassThrough(),
+ exitCode: null,
+ signalCode: null,
+ kill: () => false,
+ });
+ const supervisor = new ProviderProcessSupervisor({
+ process: producer,
+ ownsProcessLifetime: false,
+ });
+ cleanups.push(() => supervisor.dispose());
+ const checkpoint = supervisor.checkpointOutput();
+ producer.stderr.write(`${OOME_LINE}\n`);
+ expect(supervisor.snapshotOutputSince(checkpoint).markers).toBeUndefined();
+ });
+});
+
+describe("ProcessOutputTokenScanner", () => {
+ it("bounds the retained line and omits a prefix it could not keep whole", () => {
+ const scanner = new ProcessOutputTokenScanner(MARKER);
+ const prefix = "p".repeat(PROCESS_OUTPUT_TOKEN_CONTEXT_BYTES * 3);
+ const suffix = `: ${"s".repeat(PROCESS_OUTPUT_TOKEN_CONTEXT_BYTES * 3)}`;
+ scanner.scan(Buffer.from(prefix.slice(0, 1000)), 0);
+ scanner.scan(Buffer.from(prefix.slice(1000)), 1000);
+ scanner.scan(Buffer.from(`${MARKER}${suffix.slice(0, 50)}`), prefix.length);
+ scanner.scan(
+ Buffer.from(`${suffix.slice(50)}\n`),
+ prefix.length + MARKER.length + 50,
+ );
+ const observed = scanner.latestWithin(0, Number.MAX_SAFE_INTEGER);
+ expect(observed).toEqual({
+ offset: prefix.length,
+ line: `${MARKER}${suffix.slice(0, PROCESS_OUTPUT_TOKEN_CONTEXT_BYTES)}`,
+ truncated: true,
+ trailingContextIncomplete: true,
+ });
+ });
+
+ it("keeps the latest of several markers", () => {
+ const scanner = new ProcessOutputTokenScanner(MARKER);
+ const text = `first ${MARKER}\nsecond ${MARKER}: Metaspace\n`;
+ scanner.scan(Buffer.from(text), 0);
+ expect(scanner.latestWithin(0, text.length)).toEqual({
+ offset: text.lastIndexOf(MARKER),
+ line: `second ${MARKER}: Metaspace`,
+ truncated: false,
+ });
+ });
+
+ it("does not re-record a marker carried in the line tail", () => {
+ const scanner = new ProcessOutputTokenScanner(MARKER);
+ scanner.scan(Buffer.from(`detail ${MARKER}`), 0);
+ scanner.scan(Buffer.from(": Java heap space"), `detail ${MARKER}`.length);
+ scanner.scan(Buffer.from("\n"), `detail ${MARKER}: Java heap space`.length);
+ expect(scanner.latestWithin(0, 100)).toEqual({
+ offset: "detail ".length,
+ line: `detail ${MARKER}: Java heap space`,
+ truncated: false,
+ });
+ });
+});
+
+it("keeps a confirmed token when a later identifier shares its literal prefix across every chunk split", () => {
+ const valid = `${OOME_LINE}\n`;
+ const invalid = `${MARKER}Custom: ordinary identifier\n`;
+ const text = Buffer.from(valid + invalid);
+ for (let split = 0; split <= text.length; split++) {
+ const scanner = new ProcessOutputTokenScanner(MARKER);
+ scanner.scan(text.subarray(0, split), 0);
+ scanner.scan(text.subarray(split), split);
+ scanner.finish();
+ expect(scanner.latestWithin(0, text.length)).toMatchObject({
+ line: OOME_LINE,
+ offset: OOME_LINE.indexOf(MARKER),
+ });
+ }
+});
+
+it("omits line context owned by an earlier operation even when the token starts at the checkpoint", () => {
+ const { producer, supervisor } = supervised(0);
+ producer.stderr.write("earlier operation: unable to create native thread; ");
+ const checkpoint = supervisor.checkpointOutput();
+ producer.stderr.write(`${MARKER}: Java heap space\n`);
+ expect(supervisor.snapshotOutputSince(checkpoint).markers).toEqual([
+ {
+ stream: "stderr",
+ offset: "earlier operation: unable to create native thread; ".length,
+ line: `${MARKER}: Java heap space`,
+ truncated: true,
+ },
+ ]);
+});
+
+it("confirms a terminal bare token only at actual stream EOF", async () => {
+ const { producer, supervisor } = supervised(0);
+ const checkpoint = supervisor.checkpointOutput();
+ producer.stderr.write(MARKER);
+ expect(supervisor.snapshotOutputSince(checkpoint).markers).toBeUndefined();
+ const ended = new Promise<void>((resolve) =>
+ producer.stderr.once("end", resolve),
+ );
+ producer.stderr.end();
+ await ended;
+ expect(supervisor.snapshotOutputSince(checkpoint).markers).toMatchObject([
+ { line: MARKER },
+ ]);
+});
+
+it("does not promote a pending token when the stream closes without EOF", () => {
+ const { producer, supervisor } = supervised(0);
+ const checkpoint = supervisor.checkpointOutput();
+ producer.stderr.write(MARKER);
+ producer.stderr.destroy();
+ producer.emit("close", 1, null);
+ expect(supervisor.snapshotOutputSince(checkpoint).markers).toBeUndefined();
+});
+
+it("excludes a token whose prefix belongs to the earlier checkpoint range", () => {
+ const { producer, supervisor } = supervised(0);
+ producer.stderr.write(MARKER.slice(0, 10));
+ const checkpoint = supervisor.checkpointOutput();
+ producer.stderr.write(`${MARKER.slice(10)}: Java heap space\n`);
+ expect(supervisor.snapshotOutputSince(checkpoint).markers).toBeUndefined();
+});
+
+it("preserves invalid UTF-8 uncertainty in bounded token context", () => {
+ const scanner = new ProcessOutputTokenScanner(MARKER);
+ const bytes = Buffer.concat([
+ Buffer.from(`${MARKER}: `),
+ Buffer.from([0xff]),
+ Buffer.from("\n"),
+ ]);
+ scanner.scan(bytes, 0);
+ expect(scanner.latestWithin(0, bytes.length)).toMatchObject({
+ offset: 0,
+ line: `${MARKER}: \ufffd`,
+ invalidUtf8: true,
+ });
+});
diff --git a/src/process/ProcessOutputTokenScanner.ts b/src/process/ProcessOutputTokenScanner.ts
new file mode 100644
index 000000000..60a31512a
--- /dev/null
+++ b/src/process/ProcessOutputTokenScanner.ts
@@ -0,0 +1,150 @@
+import { isUtf8 } from "node:buffer";
+
+/** One confirmed token with bounded context from its raw output stream. */
+export interface ProviderProcessOutputToken {
+ /** Byte offset since construction or reset of the owning supervisor. */
+ readonly offset: number;
+ readonly line: string;
+ readonly truncated: boolean;
+ readonly invalidUtf8?: true;
+ /** True when the line's right edge is cut or its end has not been observed. */
+ readonly trailingContextIncomplete?: true;
+}
+export const PROCESS_OUTPUT_TOKEN_CONTEXT_BYTES = 1024;
+const NEWLINE = 0x0a;
+const isWordByte = (byte: number): boolean =>
+ (byte >= 0x30 && byte <= 0x39) ||
+ (byte >= 0x41 && byte <= 0x5a) ||
+ (byte >= 0x61 && byte <= 0x7a) ||
+ byte === 0x5f;
+interface Match {
+ readonly offset: number;
+ readonly prefix: Buffer;
+ readonly prefixCut: boolean;
+ suffix: Buffer;
+ open: boolean;
+ suffixCut: boolean;
+}
+/** Bounded literal token capture, delimited on the right by a non-ASCII-word byte or actual EOF. */
+export class ProcessOutputTokenScanner {
+ readonly #marker: Buffer;
+ #lineTail: Buffer = Buffer.alloc(0);
+ #lineTailCut = false;
+ #latest: Match | undefined;
+ #pending: Match | undefined;
+ constructor(marker: string) {
+ if (marker.length === 0 || marker.includes("\n"))
+ throw new RangeError("Output token must be non-empty single-line text");
+ this.#marker = Buffer.from(marker, "utf8");
+ if (!isWordByte(this.#marker[this.#marker.length - 1]!))
+ throw new RangeError("Output token must end in an ASCII word byte");
+ }
+
+ scan(chunk: Buffer, start: number): void {
+ if (chunk.length === 0) return;
+ // The next byte can invalidate a pending prefix without erasing the last
+ // confirmed token from an earlier line.
+
+ if (this.#pending !== undefined) {
+ if (!isWordByte(chunk[0]!)) this.#latest = this.#pending;
+ this.#pending = undefined;
+ }
+ this.#extendOpenLine(chunk);
+ const carried = this.#lineTail.byteLength;
+ const searched =
+ carried === 0 ? chunk : Buffer.concat([this.#lineTail, chunk]);
+ // A later identifier may share the literal prefix. Search past rejected
+ // candidates to retain the latest confirmed token in this same chunk.
+ let index = searched.lastIndexOf(this.#marker);
+ while (index >= 0 && index + this.#marker.byteLength > carried) {
+ const end = index + this.#marker.byteLength;
+ if (end === searched.length)
+ this.#pending = this.#record(searched, index, start - carried);
+ else if (!isWordByte(searched[end]!)) {
+ this.#latest = this.#record(searched, index, start - carried);
+ break;
+ }
+ index = index === 0 ? -1 : searched.lastIndexOf(this.#marker, index - 1);
+ }
+ this.#retainLineTail(searched);
+ }
+ /** Only a true stream end proves the boundary of a trailing bare token. */
+ finish(): void {
+ if (this.#pending !== undefined) this.#latest = this.#pending;
+ this.#pending = undefined;
+ if (this.#latest !== undefined) this.#latest.open = false;
+ }
+ latestWithin(
+ start: number,
+ end: number,
+ ): ProviderProcessOutputToken | undefined {
+ const latest = this.#latest;
+ if (latest === undefined || latest.offset < start || latest.offset >= end)
+ return undefined;
+ // Omit a prefix crossing the checkpoint in full: neither its old cause
+ // text nor a credential fragment cut on the left belongs to this scope.
+ const prefixInRange = latest.offset - latest.prefix.length >= start;
+ const bytes = Buffer.concat([
+ ...(prefixInRange ? [latest.prefix] : []),
+ latest.suffix,
+ ]);
+ return {
+ offset: latest.offset,
+ line: bytes.toString("utf8"),
+ ...(!isUtf8(bytes) ? { invalidUtf8: true as const } : {}),
+ truncated: latest.prefixCut || latest.suffixCut || !prefixInRange,
+ ...(latest.suffixCut || latest.open
+ ? { trailingContextIncomplete: true as const }
+ : {}),
+ };
+ }
+ #record(searched: Buffer, index: number, searchedStart: number): Match {
+ const lineStart =
+ index === 0 ? 0 : searched.lastIndexOf(NEWLINE, index - 1) + 1;
+ const prefixFits =
+ index - lineStart <= PROCESS_OUTPUT_TOKEN_CONTEXT_BYTES &&
+ (lineStart > 0 || !this.#lineTailCut);
+ const lineEnd = searched.indexOf(NEWLINE, index);
+ const available = lineEnd < 0 ? searched.byteLength : lineEnd;
+ const suffixEnd = Math.min(
+ available,
+ index + this.#marker.byteLength + PROCESS_OUTPUT_TOKEN_CONTEXT_BYTES,
+ );
+ return {
+ offset: searchedStart + index,
+ prefix: prefixFits
+ ? Buffer.from(searched.subarray(lineStart, index))
+ : Buffer.alloc(0),
+ prefixCut: !prefixFits,
+ suffix: Buffer.from(searched.subarray(index, suffixEnd)),
+ open: lineEnd < 0 && suffixEnd === available,
+ suffixCut: suffixEnd < available,
+ };
+ }
+ #extendOpenLine(chunk: Buffer): void {
+ const latest = this.#latest;
+ if (latest?.open !== true) return;
+ const lineEnd = chunk.indexOf(NEWLINE);
+ const available = lineEnd < 0 ? chunk.byteLength : lineEnd;
+ const room =
+ this.#marker.byteLength +
+ PROCESS_OUTPUT_TOKEN_CONTEXT_BYTES -
+ latest.suffix.byteLength;
+ const taken = Math.min(available, Math.max(0, room));
+ if (taken > 0)
+ latest.suffix = Buffer.concat([latest.suffix, chunk.subarray(0, taken)]);
+ latest.suffixCut = taken < available;
+ latest.open = lineEnd < 0 && taken === available;
+ }
+ #retainLineTail(searched: Buffer): void {
+ const lineStart = searched.lastIndexOf(NEWLINE) + 1;
+ const limit =
+ PROCESS_OUTPUT_TOKEN_CONTEXT_BYTES + this.#marker.byteLength - 1;
+ this.#lineTailCut =
+ searched.byteLength - lineStart > limit ||
+ (lineStart === 0 && this.#lineTailCut);
+ this.#lineTail = Buffer.from(
+ searched.subarray(Math.max(lineStart, searched.byteLength - limit)),
+ );
+ }
+}
diff --git a/src/process/ProviderProcess.ts b/src/process/ProviderProcess.ts
index 948a5a197..5d8c2623a 100644
--- a/src/process/ProviderProcess.ts
+++ b/src/process/ProviderProcess.ts
@@ -4,6 +4,11 @@ import type { Readable, Writable } from "node:stream";
import { WindowsOwnedProcess } from "../windows/WindowsOwnedProcess.js";
+import {
+ ProcessOutputTokenScanner,
+ type ProviderProcessOutputToken,
+} from "./ProcessOutputTokenScanner.js";
+
import type {
OwnedProcessGroup,
ProcessOwnershipBaseline,
@@ -138,6 +143,13 @@ export interface ProviderProcessOutputCheckpoint {
export interface ProviderProcessOutputSince {
readonly snapshot: ProviderProcessSnapshot;
readonly complete: boolean;
+ /**
+ * Latest configured output marker per stream produced after the checkpoint,
+ * observed from every drained byte regardless of the retention budget.
+ */
+ readonly markers?: readonly (ProviderProcessOutputToken & {
+ readonly stream: "stdout" | "stderr";
+ })[];
}
const outputCheckpoints = new WeakMap<
@@ -177,6 +189,11 @@ export interface ProviderProcessSupervisorOptions {
readonly captureStdout?: boolean;
/** Aggregate retained stdout/stderr byte budget; overflow is drained and reported, not retained. */
readonly maxDiagnosticBytes?: number;
+ /**
+ * Single-line token ending at a non-ASCII-word byte or EOF, located before retention
+ * applies, so its latest occurrence survives an exhausted budget.
+ */
+ readonly outputToken?: string;
readonly onDiagnostic?: (event: ProviderProcessDiagnostic) => void;
}
@@ -309,12 +326,20 @@ export class ProviderProcessSupervisor {
#stdoutObservedBytes = 0;
#stderrObservedBytes = 0;
#diagnosticTruncated = false;
+ #stdoutMarker: ProcessOutputTokenScanner | undefined;
+ #stderrMarker: ProcessOutputTokenScanner | undefined;
readonly #onStdout = (chunk: Buffer | string): void => {
this.#capture("stdout", this.#stdout, chunk);
};
readonly #onStderr = (chunk: Buffer | string): void => {
this.#capture("stderr", this.#stderr, chunk);
};
+ readonly #onStdoutEnd = (): void => {
+ this.#stdoutMarker?.finish();
+ };
+ readonly #onStderrEnd = (): void => {
+ this.#stderrMarker?.finish();
+ };
readonly #onStdoutError = (cause: Error): void => {
this.#recordStreamError("stdout", cause);
};
@@ -354,6 +379,7 @@ export class ProviderProcessSupervisor {
) {
this.#options = options;
this.#maxDiagnosticBytes = options.maxDiagnosticBytes;
+ this.#resetMarkers();
if (options.captureStdout !== false)
this.#attach(launch.process.stdout, "stdout");
this.#attach(launch.process.stderr, "stderr");
@@ -449,9 +475,7 @@ export class ProviderProcessSupervisor {
this.launch.process.outputIncomplete === true;
return {
snapshot: {
- ...(incomplete || this.#diagnosticTruncated
- ? { diagnosticTruncated: true }
- : {}),
+ ...(incomplete ? { diagnosticTruncated: true } : {}),
stdout: stdout.stream,
stderr: stderr.stream,
exitCode: this.#exitObservation?.code,
@@ -461,10 +485,42 @@ export class ProviderProcessSupervisor {
: {}),
...(incomplete ? { outputIncomplete: true } : {}),
},
- complete: !incomplete && !this.#diagnosticTruncated,
+ complete: !incomplete,
+ ...this.#markersWithin(position),
};
}
+ #markersWithin(position: {
+ readonly stdout: number;
+ readonly stderr: number;
+ }): Pick<ProviderProcessOutputSince, "markers"> {
+ const stdout = this.#stdoutMarker?.latestWithin(
+ position.stdout,
+ this.#stdoutObservedBytes,
+ );
+ const stderr = this.#stderrMarker?.latestWithin(
+ position.stderr,
+ this.#stderrObservedBytes,
+ );
+ const markers = [
+ ...(stdout === undefined
+ ? []
+ : [{ stream: "stdout" as const, ...stdout }]),
+ ...(stderr === undefined
+ ? []
+ : [{ stream: "stderr" as const, ...stderr }]),
+ ];
+ return markers.length === 0 ? {} : { markers };
+ }
+
+ #resetMarkers(): void {
+ const marker = this.#options.outputToken;
+ this.#stdoutMarker =
+ marker === undefined ? undefined : new ProcessOutputTokenScanner(marker);
+ this.#stderrMarker =
+ marker === undefined ? undefined : new ProcessOutputTokenScanner(marker);
+ }
+
/** Begin a new observation on a retained process without retaining earlier output. */
resetOutput(): void {
this.#outputEpoch += 1;
@@ -473,6 +529,7 @@ export class ProviderProcessSupervisor {
this.#stdoutObservedBytes = 0;
this.#stderrObservedBytes = 0;
this.#diagnosticTruncated = false;
+ this.#resetMarkers();
}
/** Wait for process exit up to a caller-owned bounded interval. */
@@ -547,8 +604,10 @@ export class ProviderProcessSupervisor {
this.#disposed = true;
this.launch.process.stdout?.off("data", this.#onStdout);
this.launch.process.stdout?.off("error", this.#onStdoutError);
+ this.launch.process.stdout?.off("end", this.#onStdoutEnd);
this.launch.process.stderr?.off("data", this.#onStderr);
this.launch.process.stderr?.off("error", this.#onStderrError);
+ this.launch.process.stderr?.off("end", this.#onStderrEnd);
this.launch.process.off("exit", this.#onExit);
this.launch.process.off("close", this.#onClose);
this.launch.process.off("error", this.#onError);
@@ -680,9 +739,11 @@ export class ProviderProcessSupervisor {
if (name === "stdout") {
stream?.on("data", this.#onStdout);
stream?.on("error", this.#onStdoutError);
+ stream?.on("end", this.#onStdoutEnd);
} else {
stream?.on("data", this.#onStderr);
stream?.on("error", this.#onStderrError);
+ stream?.on("end", this.#onStderrEnd);
}
}
@@ -701,8 +762,13 @@ export class ProviderProcessSupervisor {
chunk: Buffer | string,
): void {
const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
- if (stream === "stdout") this.#stdoutObservedBytes += bytes.byteLength;
- else this.#stderrObservedBytes += bytes.byteLength;
+ if (stream === "stdout") {
+ this.#stdoutMarker?.scan(bytes, this.#stdoutObservedBytes);
+ this.#stdoutObservedBytes += bytes.byteLength;
+ } else {
+ this.#stderrMarker?.scan(bytes, this.#stderrObservedBytes);
+ this.#stderrObservedBytes += bytes.byteLength;
+ }
const remaining =
this.#maxDiagnosticBytes === undefined
? bytes.byteLength
@@ -782,7 +848,7 @@ class ProcessOutputCapture {
const buffer = Buffer.concat(chunks, availableEnd - availableStart);
return {
stream: this.#snapshotBuffer(buffer, Math.max(0, end - start)),
- complete: start <= this.#bytes && end <= this.#bytes,
+ complete: start === end || (start <= this.#bytes && end <= this.#bytes),
};
}
diff --git a/src/process/ProviderProcessOutput.test.ts b/src/process/ProviderProcessOutput.test.ts
index 30a7c553d..7ced2dfb1 100644
--- a/src/process/ProviderProcessOutput.test.ts
+++ b/src/process/ProviderProcessOutput.test.ts
@@ -532,3 +532,40 @@ it.each(["close", "abort"] as const)(
}
},
);
+
+it("keeps current checkpoint coverage separate from historically dropped output", () => {
+ const producer = Object.assign(new EventEmitter(), {
+ stdout: new PassThrough(),
+ stderr: new PassThrough(),
+ exitCode: null,
+ signalCode: null,
+ kill: () => false,
+ });
+ const supervisor = new ProviderProcessSupervisor(
+ { process: producer, ownsProcessLifetime: false },
+ { maxDiagnosticBytes: 0 },
+ );
+ try {
+ producer.stdout.write("earlier dropped output");
+ expect(supervisor.snapshot().diagnosticTruncated).toBe(true);
+ const checkpoint = supervisor.checkpointOutput();
+ const current = supervisor.snapshotOutputSince(checkpoint);
+ expect(current.complete).toBe(true);
+ expect(current.snapshot.diagnosticTruncated).not.toBe(true);
+ expect(current.snapshot.stdout).toEqual({
+ text: "",
+ bytes: 0,
+ observedBytes: 0,
+ });
+ producer.stderr.write("current dropped output");
+ expect(supervisor.snapshotOutputSince(checkpoint)).toMatchObject({
+ complete: false,
+ snapshot: { diagnosticTruncated: true },
+ });
+ expect(supervisor.snapshot().diagnosticTruncated).toBe(true);
+ } finally {
+ supervisor.dispose();
+ producer.stdout.destroy();
+ producer.stderr.destroy();
+ }
+});
diff --git a/tests/boundary/providers/ghidra/ghidraClient.fixture.ts b/tests/boundary/providers/ghidra/ghidraClient.fixture.ts
index dc623abbf..214e81ed0 100644
--- a/tests/boundary/providers/ghidra/ghidraClient.fixture.ts
+++ b/tests/boundary/providers/ghidra/ghidraClient.fixture.ts
@@ -34,6 +34,12 @@ type FixtureMode =
| "silent"
| "exit"
| "old_oom_then_malformed"
+ | "prefix_cut_identifier_exit_tools"
+ | "oom_exit_tools"
+ | "flood_then_oom_exit_tools"
+ | "flood_then_exit_tools"
+ | "flood_then_malformed"
+ | "flood_silent"
| "diagnostic_output";
export class GhidraFixtureLauncher implements GhidraLauncher {
diff --git a/tests/boundary/providers/ghidra/ghidraOomRetention.test.ts b/tests/boundary/providers/ghidra/ghidraOomRetention.test.ts
new file mode 100644
index 000000000..dd12d53f6
--- /dev/null
+++ b/tests/boundary/providers/ghidra/ghidraOomRetention.test.ts
@@ -0,0 +1,191 @@
+import { createHash } from "node:crypto";
+import { writeFile } from "node:fs/promises";
+import { join } from "node:path";
+import { describe, expect, it, onTestFinished } from "vitest";
+
+import { parseConfig } from "../../../../src/config/parseConfig.js";
+import { analysisErrorProjectionSchema } from "../../../../src/contracts/errorSchemas.js";
+import { projectAnalysisError } from "../../../../src/domain/analysisErrorProjection.js";
+import { elf } from "../../../../src/domain/binaryTarget.fixture.js";
+import type { BinaryTarget } from "../../../../src/domain/binaryTargetTypes.js";
+import { ok } from "../../../../src/domain/result.js";
+import { GhidraClient } from "../../../../src/ghidra/GhidraClient.js";
+import type { GhidraJavaObservation } from "../../../../src/ghidra/GhidraJavaProbe.js";
+import type {
+ GhidraLaunchSession,
+ GhidraLauncher,
+} from "../../../../src/ghidra/GhidraLauncher.js";
+import { GhidraProvider } from "../../../../src/ghidra/GhidraProvider.js";
+import { silentLogger } from "../../../../src/logger.js";
+import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
+import { GhidraFixtureLauncher } from "./ghidraClient.fixture.js";
+
+type Mode = ConstructorParameters<typeof GhidraFixtureLauncher>[0];
+
+/** Real provider, client, process capture and projection; only the JVM is simulated. */
+const failedOperation = async (
+ mode: Mode,
+ options: { readonly startupTimeoutMs?: number } = {},
+) => {
+ const fixture = new GhidraFixtureLauncher(mode);
+ const launcher: GhidraLauncher = {
+ launch: async (session: GhidraLaunchSession) => {
+ const launched = await fixture.launch(session);
+ if (!launched.ok) return launched;
+ return ok({ ...launched.value, configuredMaxHeap: "4G" });
+ },
+ };
+ const directory = await createTestTempDirectory("rea-ghidra-oome-");
+ const bytes = elf(2, 1, 62);
+ const targetPath = join(directory, "target.elf");
+ await writeFile(targetPath, bytes);
+ const target: BinaryTarget = {
+ path: targetPath,
+ sha256: createHash("sha256").update(bytes).digest("hex"),
+ kind: "executable",
+ format: "elf",
+ architecture: "x86_64",
+ availableArchitectures: ["x86_64"],
+ };
+ const config = parseConfig({
+ GHIDRA_INSTALL_DIR: "/fixture/ghidra",
+ REA_GHIDRA_STARTUP_TIMEOUT_MS: String(options.startupTimeoutMs ?? 10_000),
+ });
+ if (!config.ok) throw config.error;
+ const provider = new GhidraProvider(
+ config.value,
+ silentLogger,
+ {},
+ {
+ platform: process.platform,
+ architecture: process.arch,
+ readText: () => "application.version=12.1.4\napplication.java.min=21\n",
+ executable: () => true,
+ probeJava: () =>
+ ok<GhidraJavaObservation>({
+ osArch: process.arch === "arm64" ? "aarch64" : "amd64",
+ osName:
+ process.platform === "darwin"
+ ? "Mac OS X"
+ : process.platform === "win32"
+ ? "Windows 11"
+ : "Linux",
+ version: "21.0.12",
+ major: 21,
+ home: "/fixture/jdk",
+ bits: 64,
+ runtime: "jdk",
+ }),
+ },
+ (clientOptions) => new GhidraClient({ ...clientOptions, launcher }),
+ );
+ const profile = await provider.resolveAnalysisProfile(target);
+ if (!profile.ok) throw profile.error;
+ if (profile.value.profile === null)
+ throw new Error("Expected Ghidra profile");
+ const client = provider.createClient(target, profile.value.profile);
+ onTestFinished(async () => {
+ await client.close();
+ });
+ const result = await client.execute("list_procedures", {});
+ if (result.ok) throw new Error("Expected a Ghidra failure");
+ return analysisErrorProjectionSchema.parse(
+ JSON.parse(JSON.stringify(projectAnalysisError(result.error))),
+ );
+};
+
+const confirmedHeapExhaustion = {
+ code: "resource_constraint",
+ details: {
+ resource: "memory",
+ reported_limits: { configured_jvm_max_heap: "4G" },
+ },
+};
+
+describe.skipIf(process.platform === "win32")(
+ "Ghidra OutOfMemoryError beyond the diagnostic retention budget",
+ () => {
+ it("reports an OOME that fits in the retained output", async () => {
+ const projected = await failedOperation("oom_exit_tools");
+ expect(projected).toMatchObject(confirmedHeapExhaustion);
+ expect(projected.message).toContain("Java heap space");
+ });
+
+ it("reports an OOME printed after more than 8 MiB of earlier output", async () => {
+ const projected = await failedOperation("flood_then_oom_exit_tools");
+ expect(projected).toMatchObject(confirmedHeapExhaustion);
+ expect(projected.message).toContain("Java heap space");
+ expect(projected.remediation.action).toContain("GHIDRA_HEADLESS_MAXMEM");
+ expect(projected.details).toMatchObject({
+ diagnostics: {
+ failure_output: {
+ complete: false,
+ observed_oome: [
+ {
+ stream: "stderr",
+ line: expect.stringContaining("java.lang.OutOfMemoryError"),
+ },
+ ],
+ },
+ },
+ });
+ }, 30_000);
+
+ it.each([
+ ["process exit", "flood_then_exit_tools"],
+ ["protocol failure", "flood_then_malformed"],
+ ] as const)(
+ "keeps an unrelated %s after budget-exhausting output",
+ async (_kind, mode) => {
+ const projected = await failedOperation(mode);
+ expect(projected.code).toBe("execution_failure");
+ expect(projected.message).toContain(
+ "a memory cause cannot be ruled out",
+ );
+ expect(projected.remediation.action).not.toContain(
+ "GHIDRA_HEADLESS_MAXMEM",
+ );
+ expect(projected.details).toMatchObject({
+ diagnostics: { failure_output: { complete: false } },
+ });
+ expect(projected.details).toMatchObject({
+ diagnostics: { failure_output: { observed_oome: [] } },
+ });
+ },
+ 30_000,
+ );
+
+ it("does not mistake a budget-cut identifier prefix for an OOME", async () => {
+ const projected = await failedOperation(
+ "prefix_cut_identifier_exit_tools",
+ );
+ expect(projected.code).toBe("execution_failure");
+ expect(projected.message).toContain("a memory cause cannot be ruled out");
+ expect(projected).toMatchObject({
+ details: {
+ diagnostics: {
+ failure_output: {
+ complete: false,
+ observed_oome: [],
+ stdout: {
+ retained_bytes: 8 * 1024 * 1024,
+ bytes: 8 * 1024 * 1024 + "Custom\n".length,
+ },
+ },
+ },
+ },
+ });
+ }, 30_000);
+
+ it("keeps a startup timeout after budget-exhausting output", async () => {
+ const projected = await failedOperation("flood_silent", {
+ startupTimeoutMs: 4_000,
+ });
+ expect(projected.code).toBe("provider_timeout");
+ expect(projected.message).toContain("a memory cause cannot be ruled out");
+ expect(projected.remediation.action).not.toContain(
+ "GHIDRA_HEADLESS_MAXMEM",
+ );
+ }, 30_000);
+ },
+);
diff --git a/tests/fixtures/fakeGhidra.mjs b/tests/fixtures/fakeGhidra.mjs
index 2756040a8..870f44753 100644
--- a/tests/fixtures/fakeGhidra.mjs
+++ b/tests/fixtures/fakeGhidra.mjs
@@ -27,8 +27,46 @@ if (
process.exit(64);
}
+const OOME_LINE =
+ "ERROR Abort due to Headless analyzer error: Java heap space (HeadlessAnalyzer) java.lang.OutOfMemoryError: Java heap space\n";
+// Exceeds the 8 MiB diagnostic retention budget in many small chunks.
+const floodStdout = async () => {
+ const line = "INFO fixture analyzer progress line\n";
+ const block = line.repeat(Math.ceil((64 * 1024) / line.length));
+ for (let written = 0; written < 10.5 * 1024 * 1024;) {
+ if (!process.stdout.write(block))
+ await new Promise((resolve) => process.stdout.once("drain", resolve));
+ written += block.length;
+ }
+};
+
+// The retention boundary ends exactly at the class-name prefix of a different identifier.
+const cutIdentifierAtBudget = async () => {
+ const marker = "java.lang.OutOfMemoryError";
+ let remaining = 8 * 1024 * 1024 - marker.length;
+ const block = Buffer.alloc(64 * 1024, 0x70);
+ while (remaining > 0) {
+ const part = block.subarray(0, Math.min(remaining, block.length));
+ if (!process.stdout.write(part))
+ await new Promise((resolve) => process.stdout.once("drain", resolve));
+ remaining -= part.length;
+ }
+ await new Promise((resolve, reject) =>
+ process.stdout.write(`${marker}Custom\n`, (error) =>
+ error ? reject(error) : resolve(),
+ ),
+ );
+ process.exit(74);
+};
+
+const writeThen = (stream, text, then) =>
+ stream.write(text, () => setTimeout(then, 10));
+
if (mode === "exit") process.exit(73);
-if (mode === "silent") setInterval(() => undefined, 1_000);
+if (mode === "flood_silent") {
+ await floodStdout();
+ setInterval(() => undefined, 1_000);
+} else if (mode === "silent") setInterval(() => undefined, 1_000);
else {
await rm(endpointPath, { force: true });
const sockets = new Set();
@@ -104,6 +142,23 @@ const onSocketData = (socket, server, chunk, state) => {
}
};
+/** Tool-request failures that follow process output, as the Ghidra JVM prints them. */
+const handleOutputFailure = (socket, state) => {
+ const oome = () =>
+ writeThen(process.stderr, OOME_LINE, () => process.exit(1));
+ if (state.mode === "prefix_cut_identifier_exit_tools")
+ void cutIdentifierAtBudget();
+ else if (state.mode === "oom_exit_tools") oome();
+ else if (state.mode === "flood_then_oom_exit_tools")
+ void floodStdout().then(oome);
+ else if (state.mode === "flood_then_exit_tools")
+ void floodStdout().then(() => process.exit(74));
+ else if (state.mode === "flood_then_malformed")
+ void floodStdout().then(() => socket.write("{invalid\n"));
+ else return false;
+ return true;
+};
+
const handleRequest = (socket, server, request, state) => {
if (request.method === "ping") {
handlePing(socket, request, state);
@@ -146,6 +201,8 @@ const handleRequest = (socket, server, request, state) => {
}
if (state.mode === "exit_tools" && request.method !== "shutdown")
process.exit(74);
+ if (request.method !== "shutdown" && handleOutputFailure(socket, state))
+ return;
if (state.mode === "hang_tools" && request.method !== "shutdown") return;
const inventory =
request.method === "list_strings" && state.mode === "fragmented"