Skip to content

armgit / rea

Public Imported from GitHub
0

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

fix(ghidra): retain process ownership after failed launch rollback

morluto07675f78c66c
diff --git a/src/ghidra/GhidraClient.ts b/src/ghidra/GhidraClient.ts
index 71c5a9357..33c5add1b 100644
--- a/src/ghidra/GhidraClient.ts
+++ b/src/ghidra/GhidraClient.ts
@@ -25,7 +25,7 @@ import type {
import type { GhidraInventoryOperation } from "./GhidraInventoryValues.js";
import type { GhidraFunctionOperation } from "./GhidraFunctionValues.js";
import { createGhidraDiagnostics } from "./GhidraDiagnostics.js";
-import type { GhidraLaunch } from "./GhidraLauncher.js";
+import { GhidraLaunchError, type GhidraLaunch } from "./GhidraLauncher.js";
import { GhidraResponseBuffer } from "./GhidraResponseBuffer.js";
import { GhidraResponseRouter } from "./GhidraResponseRouter.js";
import { GhidraRequestQueue } from "./GhidraRequestQueue.js";
@@ -425,8 +425,18 @@ export class GhidraClient {
err(this.#failure("start", "Ghidra launcher failed", cause)),
);
if (!launched.ok) {
+ const partialLaunch =
+ launched.error instanceof GhidraLaunchError
+ ? launched.error.partialLaunch
+ : undefined;
+ if (partialLaunch !== undefined) {
+ this.#launch = partialLaunch;
+ this.#process = new ProviderProcessSupervisor(partialLaunch, {
+ onDiagnostic: (event) => this.#onProcessDiagnostic(event),
+ });
+ }
const failure = deadline.signal.aborted
- ? this.#interruptionFailure(deadline)
+ ? this.#interruptionFailure(deadline, launched.error)
: launched.error instanceof GhidraSessionError
? launched.error
: this.#failure("start", launched.error.message, launched.error);
@@ -699,10 +709,13 @@ export class GhidraClient {
return this.#startupFailure(failure);
}
- #interruptionFailure(deadline: ProviderStartupDeadline): GhidraSessionError {
+ #interruptionFailure(
+ deadline: ProviderStartupDeadline,
+ cause?: unknown,
+ ): GhidraSessionError {
return deadline.interruption === "cancelled"
- ? this.#failure("cancelled", "Ghidra startup was cancelled")
- : this.#failure("timeout", "Ghidra startup deadline elapsed", undefined, {
+ ? this.#failure("cancelled", "Ghidra startup was cancelled", cause)
+ : this.#failure("timeout", "Ghidra startup deadline elapsed", cause, {
timeoutMs: deadline.timeoutMs,
});
}
diff --git a/src/ghidra/GhidraLauncher.ts b/src/ghidra/GhidraLauncher.ts
index b31262fd6..73bf05627 100644
--- a/src/ghidra/GhidraLauncher.ts
+++ b/src/ghidra/GhidraLauncher.ts
@@ -56,9 +56,21 @@ export interface GhidraLauncher {
/** Local launch failure retained as the cause of a provider-neutral error. */
export class GhidraLaunchError extends Error {
- constructor(message: string, options?: ErrorOptions) {
- super(message, options);
+ readonly #partialLaunch: GhidraLaunch | undefined;
+
+ constructor(
+ message: string,
+ options?: ErrorOptions & { readonly partialLaunch?: GhidraLaunch },
+ ) {
+ const { partialLaunch, ...errorOptions } = options ?? {};
+ super(message, errorOptions);
this.name = "GhidraLaunchError";
+ this.#partialLaunch = partialLaunch;
+ }
+
+ /** Process ownership retained for the client to retry an incomplete rollback. */
+ get partialLaunch(): GhidraLaunch | undefined {
+ return this.#partialLaunch;
}
}
@@ -74,6 +86,8 @@ export interface GhidraHeadlessLauncherOptions {
readonly dosMz?: true;
readonly dosCom?: true;
readonly analysisExtensions?: readonly GhidraExtension[];
+ /** Spawn seam for provider-boundary lifecycle tests. */
+ readonly spawnProcess?: typeof spawnOwnedProviderProcess;
}
/** Launch Ghidra without copying scripts into or modifying its installation. */
@@ -168,7 +182,7 @@ export class GhidraHeadlessLauncher implements GhidraLauncher {
: { signal: options.signal }),
})
: { ...scriptCommand, environment };
- started = await spawnOwnedProviderProcess({
+ started = await (this.options.spawnProcess ?? spawnOwnedProviderProcess)({
command: command.command,
arguments: command.arguments,
runId: session.runId,
@@ -181,6 +195,7 @@ export class GhidraHeadlessLauncher implements GhidraLauncher {
hostEnvironment: {},
...(options.signal === undefined ? {} : { signal: options.signal }),
});
+ const partialLaunch = ownedGhidraLaunch(started, paths, platform);
await writeGhidraRuntimeFile(
paths.ownershipPath,
`${JSON.stringify({
@@ -199,33 +214,60 @@ export class GhidraHeadlessLauncher implements GhidraLauncher {
platform,
);
if (isAborted(options.signal)) {
- await cleanupStartedProcess(started, platform);
- return err(new AnalysisCancelledError("open_binary"));
+ throw new AnalysisCancelledError("open_binary");
}
- const spawned = started;
- return ok({
- ...ownedGhidraProcess(spawned, platform),
- projectRoot: paths.projectRoot,
- ghidraLogPath: paths.ghidraLogPath,
- scriptLogPath: paths.scriptLogPath,
- });
+ return ok(partialLaunch);
} catch (cause: unknown) {
- if (started !== undefined)
- await cleanupStartedProcess(started, platform).catch(
- (cause: unknown) => {
- // best-effort cleanup: started-process cleanup must not mask the launch failure.
- void cause;
- },
- );
- return isAborted(options.signal)
- ? err(new AnalysisCancelledError("open_binary"))
- : err(
- new GhidraLaunchError("Ghidra headless launch failed", { cause }),
+ const primary = isAborted(options.signal)
+ ? new AnalysisCancelledError("open_binary", { cause })
+ : new GhidraLaunchError("Ghidra headless launch failed", { cause });
+ if (started === undefined) return err(primary);
+
+ let cleanupFailure: unknown;
+ try {
+ const cleanup = await cleanupStartedProcess(started, platform);
+ if (!cleanup.cleaned)
+ cleanupFailure = new Error(
+ `Ghidra process cleanup was incomplete: ${cleanup.reason}`,
);
+ } catch (failure: unknown) {
+ cleanupFailure = failure;
+ }
+ if (cleanupFailure !== undefined) {
+ const partialLaunch = ownedGhidraLaunch(started, paths, platform);
+ const primaryMessage = isAborted(options.signal)
+ ? primary.message
+ : `Ghidra headless launch failed: ${cause instanceof Error ? cause.message : String(cause)}`;
+ return err(
+ new GhidraLaunchError(
+ `${primaryMessage}; process cleanup remains incomplete`,
+ {
+ cause: new AggregateError(
+ [primary, cleanupFailure],
+ "Ghidra launch rollback did not release its process",
+ { cause: primary },
+ ),
+ partialLaunch,
+ },
+ ),
+ );
+ }
+ return err(primary);
}
}
}
+const ownedGhidraLaunch = (
+ spawned: SpawnedOwnedProviderProcess,
+ paths: ReturnType<typeof ghidraRuntimePaths>,
+ platform: NodeJS.Platform,
+): GhidraLaunch => ({
+ ...ownedGhidraProcess(spawned, platform),
+ projectRoot: paths.projectRoot,
+ ghidraLogPath: paths.ghidraLogPath,
+ scriptLogPath: paths.scriptLogPath,
+});
+
const ownedGhidraProcess = (
spawned: SpawnedOwnedProviderProcess,
platform: NodeJS.Platform,
diff --git a/tests/boundary/providers/ghidra/ghidraClient.test.ts b/tests/boundary/providers/ghidra/ghidraClient.test.ts
index ed60ccf90..a8a7eeac8 100644
--- a/tests/boundary/providers/ghidra/ghidraClient.test.ts
+++ b/tests/boundary/providers/ghidra/ghidraClient.test.ts
@@ -1,7 +1,7 @@
import { spawn, type ChildProcess } from "node:child_process";
import { createHash } from "node:crypto";
import { readFileSync } from "node:fs";
-import { access, chmod, mkdir } from "node:fs/promises";
+import { access, chmod, mkdir, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
@@ -11,6 +11,7 @@ import type { Logger } from "pino";
import { ok } from "../../../../src/domain/result.js";
import { GhidraClient } from "../../../../src/ghidra/GhidraClient.js";
+import { GhidraHeadlessLauncher } from "../../../../src/ghidra/GhidraLauncher.js";
import type { GhidraDiagnostic } from "../../../../src/ghidra/GhidraClientTypes.js";
import type {
GhidraLaunchSession,
@@ -19,6 +20,7 @@ import type {
import type { GhidraTransportKind } from "../../../../src/ghidra/GhidraTransport.js";
import { GHIDRA_SESSION_CAPABILITIES } from "../../../../src/ghidra/GhidraSessionValues.js";
import { waitForExit as waitForChildExit } from "../../../support/process/processFixture.js";
+import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
const fixturePath = fileURLToPath(
new URL("../../../fixtures/fakeGhidra.mjs", import.meta.url),
@@ -743,3 +745,123 @@ it("preserves failed startup and retained Ghidra cleanup capabilities until a ve
expect(cleanupAttempts).toBe(3);
await expect(access(runtime)).rejects.toMatchObject({ code: "ENOENT" });
});
+
+describe.skipIf(process.platform === "win32")(
+ "Ghidra launcher rollback ownership",
+ () => {
+ it.each([
+ ["ownership manifest write failure", false, "start"],
+ ["cancellation after process creation", true, "cancelled"],
+ ] as const)(
+ "retains the original process and runtime roots after %s until cleanup succeeds",
+ async (failureMode, cancelAfterSpawn, expectedKind) => {
+ const root = await createTestTempDirectory("rea-ghidra-rollback-");
+ const java = join(root, "jdk", "bin", "java");
+ await mkdir(join(root, "jdk", "bin"), { recursive: true });
+ await writeFile(
+ java,
+ "#!/usr/bin/env node\n// LaunchSupport fixture emits no optional values.\n",
+ );
+ await chmod(java, 0o755);
+
+ const controller = new AbortController();
+ let cleanupAllowed = false;
+ let cleanupAttempts = 0;
+ let child: ChildProcess | undefined;
+ let runtimeRoot: string | undefined;
+ const headless = new GhidraHeadlessLauncher({
+ environment: process.env,
+ javaHome: join(root, "jdk"),
+ analyzeHeadlessPath: "/unused/ghidra/support/analyzeHeadless",
+ bridgeScriptPath: "/unused/rea/ReaGhidraBridge.java",
+ spawnProcess: async ({ runId }) => {
+ const spawned = spawn(
+ process.execPath,
+ ["-e", "setInterval(() => {}, 1000)"],
+ { detached: true, stdio: ["ignore", "pipe", "pipe"] },
+ );
+ child = spawned;
+ await new Promise<void>((resolve, reject) => {
+ spawned.once("spawn", () => resolve());
+ spawned.once("error", reject);
+ });
+ if (cancelAfterSpawn)
+ controller.abort(new Error("rollback cancellation fixture"));
+ const pid = spawned.pid;
+ if (pid === undefined) throw new Error("fixture child has no PID");
+ return {
+ process: spawned,
+ ownership: {
+ runId,
+ leaderPid: pid,
+ processGroupId: pid,
+ expectedParentPid: process.pid,
+ },
+ cleanup: async () => {
+ cleanupAttempts += 1;
+ if (!cleanupAllowed)
+ return {
+ cleaned: false as const,
+ reason: `${failureMode} cleanup is still unavailable`,
+ };
+ if (spawned.exitCode === null && spawned.signalCode === null)
+ spawned.kill("SIGTERM");
+ const exited = await waitForChildExit(spawned, 5_000);
+ return exited
+ ? { cleaned: true as const, signaled: true }
+ : {
+ cleaned: false as const,
+ reason: "fixture child did not exit",
+ };
+ },
+ };
+ },
+ });
+ const launcher: GhidraLauncher = {
+ async launch(session, options) {
+ runtimeRoot = session.runtimeRoot;
+ if (!cancelAfterSpawn)
+ await mkdir(join(session.runtimeRoot, "ownership.json"));
+ return headless.launch(session, options);
+ },
+ };
+ const client = clientFor(launcher);
+ onTestFinished(async () => {
+ cleanupAllowed = true;
+ await client.close();
+ });
+
+ const started = await client.start(
+ cancelAfterSpawn ? controller.signal : undefined,
+ );
+ expect(started).toMatchObject({
+ ok: false,
+ error: {
+ kind: expectedKind,
+ cleanupFailure: { cleanupIncomplete: true },
+ },
+ });
+ if (started.ok) throw new Error("expected startup rollback failure");
+ expect(started.error.message).toContain(
+ cancelAfterSpawn ? "startup was cancelled" : "headless launch failed",
+ );
+ if (!cancelAfterSpawn)
+ expect(started.error.message).toContain("ownership.json");
+ if (runtimeRoot === undefined || child === undefined)
+ throw new Error("fixture did not retain the started process owner");
+ await access(runtimeRoot);
+ expect(child.exitCode).toBeNull();
+ expect(child.signalCode).toBeNull();
+ expect(cleanupAttempts).toBe(2);
+
+ cleanupAllowed = true;
+ await expect(client.close()).resolves.toEqual(ok(null));
+ expect(cleanupAttempts).toBe(3);
+ await expect(access(runtimeRoot)).rejects.toMatchObject({
+ code: "ENOENT",
+ });
+ await expect(waitForExit(child)).resolves.toBe(true);
+ },
+ );
+ },
+);