Skip to content

armgit / rea

Public Imported from GitHub
0

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

fix(ghidra): retry retained language catalog closes before admission (#6210)

Kaoru0822292fd532c9e6
diff --git a/src/ghidra/GhidraLanguageCatalog.ts b/src/ghidra/GhidraLanguageCatalog.ts
index 1cd939af2..d6f28e21d 100644
--- a/src/ghidra/GhidraLanguageCatalog.ts
+++ b/src/ghidra/GhidraLanguageCatalog.ts
@@ -1,12 +1,13 @@
-import { open, readdir } from "node:fs/promises";
-import type { FileHandle } from "node:fs/promises";
+import { readdir } from "node:fs/promises";
import { join } from "node:path";
import { parseXmlDocument } from "../domain/xmlDocument.js";
import { decodeXmlPlistText } from "../domain/propertyListXmlText.js";
+import type { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js";
+import { withArtifactRegularFile } from "../artifacts/ArtifactFileOperation.js";
import type { GhidraLanguageOverride } from "../config/ghidraLanguageOverride.js";
import { ConfigurationError } from "../domain/configurationErrors.js";
-import { OwnedFileHandle } from "../filesystem/OwnedFileHandle.js";
+import { RegularFileOperationCancelled } from "../filesystem/RegularFile.js";
import { readBoundedFileBytes } from "../process/BoundedFileBytes.js";
/** One language definition and the compiler specs it declares. */
@@ -20,62 +21,6 @@ const MAX_LDEFS_BYTES = 4 * 1024 * 1024;
// Processor modules ship under Processors; installed extensions may add more.
const LANGUAGE_ROOTS = ["Ghidra/Processors", "Ghidra/Extensions"] as const;
-interface RetainedLanguageFile {
- readonly path: string;
- readonly owner: OwnedFileHandle<FileHandle>;
-}
-
-/** Language definition handles whose close is unconfirmed but retryable. */
-const pendingLanguageFileCleanup = new Set<RetainedLanguageFile>();
-
-/**
- * Cleanup of one or more language definition handles is unconfirmed. Any
- * read failure that preceded it is kept as the primary failure.
- */
-export class GhidraLanguageCatalogCleanupError extends Error {
- constructor(
- readonly paths: readonly string[],
- readonly causes: readonly unknown[],
- readonly readFailure?: unknown,
- ) {
- super(
- `Language definition cleanup is unconfirmed: ${paths.join(", ")}`,
- readFailure === undefined ? undefined : { cause: readFailure },
- );
- }
-}
-
-/** Close one owner; retain it only while a later close can still succeed. */
-const closeLanguageFile = async (
- file: RetainedLanguageFile,
-): Promise<unknown> => {
- try {
- await file.owner.close();
- pendingLanguageFileCleanup.delete(file);
- return undefined;
- } catch (cause: unknown) {
- // Descriptor invalidation does not prove that this owner confirmed close.
- // Keep even sticky failures in the lifecycle scope so later reads surface
- // the unresolved cleanup instead of silently abandoning ownership.
- pendingLanguageFileCleanup.add(file);
- return cause;
- }
-};
-
-/** Retry every retained owner before reporting the failures together. */
-const retryLanguageFileCleanup = async (): Promise<void> => {
- const failed: { readonly path: string; readonly cause: unknown }[] = [];
- for (const file of pendingLanguageFileCleanup) {
- const cause = await closeLanguageFile(file);
- if (cause !== undefined) failed.push({ path: file.path, cause });
- }
- if (failed.length > 0)
- throw new GhidraLanguageCatalogCleanupError(
- failed.map(({ path }) => path),
- failed.map(({ cause }) => cause),
- );
-};
-
/** Parse the `<language>` elements of one `.ldefs` document. */
export const parseGhidraLanguageDefinitions = (
text: string,
@@ -122,61 +67,66 @@ const languageDirectories = async (installDir: string): Promise<string[]> => {
return directories;
};
-/** Read at most the catalog limit; undefined marks an oversized file. */
-const readLanguageDefinitionFile = async (
+/**
+ * Parse one definition before its final close; an oversized file declares
+ * nothing. The caller's scope owns a descriptor whose close is unconfirmed.
+ */
+const readLanguageDefinitionFile = (
path: string,
-): Promise<Buffer | undefined> => {
- await retryLanguageFileCleanup();
- const file = { path, owner: new OwnedFileHandle(await open(path, "r")) };
- let read:
- | { readonly ok: true; readonly bytes: Buffer | undefined }
- | { readonly ok: false; readonly cause: unknown };
- try {
- read = {
- ok: true,
- bytes: await readBoundedFileBytes(file.owner.handle, MAX_LDEFS_BYTES),
- };
- } catch (cause: unknown) {
- read = { ok: false, cause };
- }
- const cleanup = await closeLanguageFile(file);
- if (cleanup !== undefined)
- throw new GhidraLanguageCatalogCleanupError(
- [path],
- [cleanup],
- read.ok ? undefined : read.cause,
- );
- if (!read.ok) throw read.cause;
- return read.bytes;
-};
-
-/** Read every language definition shipped by one Ghidra installation. */
-export const readGhidraLanguageCatalog = async (
- installDir: string,
-): Promise<readonly GhidraLanguageDefinition[]> => {
- // Surface retained cleanup even when this catalog has no definitions to read.
- await retryLanguageFileCleanup();
- const definitions: GhidraLanguageDefinition[] = [];
- for (const directory of await languageDirectories(installDir)) {
- let entries: string[];
- try {
- entries = await readdir(directory);
- } catch {
- continue;
- }
- for (const entry of entries.sort()) {
- if (!entry.endsWith(".ldefs")) continue;
- const bytes = await readLanguageDefinitionFile(join(directory, entry));
- if (bytes === undefined) continue;
+ resources: ArtifactResourceScope,
+ signal: AbortSignal | undefined,
+): Promise<readonly GhidraLanguageDefinition[]> =>
+ withArtifactRegularFile(
+ path,
+ resources,
+ signal,
+ async (file) => {
+ const bytes = await readBoundedFileBytes(file, MAX_LDEFS_BYTES, {
+ signal,
+ cancellationFailure: (reason) =>
+ new RegularFileOperationCancelled(reason),
+ });
// The XML byte owner validates encoding and declaration before syntax
// parsing; a literal U+FFFD cannot diagnose invalid source bytes.
- definitions.push(
- ...parseGhidraLanguageDefinitions(decodeXmlPlistText(bytes)),
- );
+ return bytes === undefined
+ ? []
+ : parseGhidraLanguageDefinitions(decodeXmlPlistText(bytes));
+ },
+ "follow",
+ );
+
+/**
+ * Read every language definition shipped by one Ghidra installation. Admission
+ * first retries cleanup the scope retains, so an unconfirmed close blocks reads
+ * only until that exact owner releases.
+ */
+export const readGhidraLanguageCatalog = (
+ installDir: string,
+ resources: ArtifactResourceScope,
+ signal?: AbortSignal,
+): Promise<readonly GhidraLanguageDefinition[]> =>
+ resources.run(async () => {
+ const definitions: GhidraLanguageDefinition[] = [];
+ for (const directory of await languageDirectories(installDir)) {
+ let entries: string[];
+ try {
+ entries = await readdir(directory);
+ } catch {
+ continue;
+ }
+ for (const entry of entries.sort()) {
+ if (!entry.endsWith(".ldefs")) continue;
+ definitions.push(
+ ...(await readLanguageDefinitionFile(
+ join(directory, entry),
+ resources,
+ signal,
+ )),
+ );
+ }
}
- }
- return definitions;
-};
+ return definitions;
+ });
/**
* Check a configured import language against the installation before launch,
diff --git a/src/ghidra/GhidraLanguageOverride.test.ts b/src/ghidra/GhidraLanguageOverride.test.ts
index 6a07445d2..bb9b071f4 100644
--- a/src/ghidra/GhidraLanguageOverride.test.ts
+++ b/src/ghidra/GhidraLanguageOverride.test.ts
@@ -18,6 +18,7 @@ import {
readGhidraLanguageCatalog,
} from "./GhidraLanguageCatalog.js";
import { GhidraProvider } from "./GhidraProvider.js";
+import { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js";
// Abbreviated from Ghidra 12.1.4 Processors/x86/data/languages/x86.ldefs.
const X86_LDEFS = `<?xml version="1.0" encoding="UTF-8"?>
@@ -197,10 +198,15 @@ describe("Ghidra language catalog", () => {
},
{ id: "x86:LE:16:Real Mode", compilerSpecIds: ["default"] },
]);
- expect(await readGhidraLanguageCatalog(installDir)).toHaveLength(2);
- expect(await readGhidraLanguageCatalog(join(installDir, "absent"))).toEqual(
- [],
- );
+ expect(
+ await readGhidraLanguageCatalog(installDir, new ArtifactResourceScope()),
+ ).toHaveLength(2);
+ expect(
+ await readGhidraLanguageCatalog(
+ join(installDir, "absent"),
+ new ArtifactResourceScope(),
+ ),
+ ).toEqual([]);
});
it("reads a UTF-8 signed definition beside an unsigned sibling", async () => {
@@ -219,7 +225,9 @@ describe("Ghidra language catalog", () => {
]),
);
await writeFile(join(module("x86"), "x86.ldefs"), X86_LDEFS);
- expect(await readGhidraLanguageCatalog(root)).toEqual([
+ expect(
+ await readGhidraLanguageCatalog(root, new ArtifactResourceScope()),
+ ).toEqual([
{ id: "probe:LE:32:default", compilerSpecIds: [] },
...parseGhidraLanguageDefinitions(X86_LDEFS),
]);
diff --git a/src/ghidra/GhidraProvider.ts b/src/ghidra/GhidraProvider.ts
index 89b4d363c..181b66def 100644
--- a/src/ghidra/GhidraProvider.ts
+++ b/src/ghidra/GhidraProvider.ts
@@ -40,7 +40,6 @@ import {
} from "../domain/jsonValue.js";
import { err, ok, type Result } from "../domain/result.js";
import { AnalysisError } from "../domain/analysisErrorBase.js";
-import { ProviderAdapterError } from "../domain/providerAdapterError.js";
import { ProviderCleanupError } from "../domain/providerCleanupError.js";
import type { Logger } from "pino";
import { GhidraClient } from "./GhidraClient.js";
@@ -55,9 +54,9 @@ import { AnalysisCancelledError } from "../domain/analysisErrorCore.js";
import { resolveGhidraAnalysisSeeds } from "./GhidraAnalysisSeeds.js";
import {
admitGhidraLanguageOverride,
- GhidraLanguageCatalogCleanupError,
readGhidraLanguageCatalog,
} from "./GhidraLanguageCatalog.js";
+import { ghidraFileFailure } from "./GhidraFileArtifacts.js";
import {
ghidraProcessorUnsupportedReason,
isGhidraPspTarget,
@@ -397,31 +396,15 @@ export class GhidraProvider implements AnalysisProviderCandidate {
if (override !== undefined && installation.status === "available") {
let catalog: Awaited<ReturnType<typeof readGhidraLanguageCatalog>>;
try {
- catalog = await readGhidraLanguageCatalog(installation.installDir);
+ catalog = await readGhidraLanguageCatalog(
+ installation.installDir,
+ this.#inspectionResources,
+ options?.signal,
+ );
} catch (cause: unknown) {
- if (cause instanceof GhidraLanguageCatalogCleanupError)
- return err(
- new ProviderCleanupError(
- "ghidra",
- cause.paths,
- {
- reason: cause.message,
- paths: [...cause.paths],
- close_failures: cause.causes.map(providerFailureText),
- ...(cause.readFailure === undefined
- ? {}
- : { read_failure: providerFailureText(cause.readFailure) }),
- },
- { operation: "resolve_analysis_profile", cause },
- ),
- );
return err(
- new ProviderAdapterError("ghidra", "resolve_analysis_profile", {
- cause,
- diagnostics: {
- reason:
- "Could not read the installed Ghidra language definitions.",
- },
+ ghidraFileFailure(cause, "resolve_analysis_profile", {
+ setting: "REA_GHIDRA_LANGUAGE_ID",
}),
);
}
diff --git a/tests/boundary/filesystem/ghidraLanguageCatalogBound.test.ts b/tests/boundary/filesystem/ghidraLanguageCatalogBound.test.ts
index 8555c1dbd..d44c475fe 100644
--- a/tests/boundary/filesystem/ghidraLanguageCatalogBound.test.ts
+++ b/tests/boundary/filesystem/ghidraLanguageCatalogBound.test.ts
@@ -1,7 +1,9 @@
-import { mkdir, writeFile } from "node:fs/promises";
+import { execFileSync } from "node:child_process";
+import { mkdir, symlink, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { afterEach, expect, it, vi } from "vitest";
+import { ArtifactResourceScope } from "../../../src/artifacts/ArtifactResourceScope.js";
import { readGhidraLanguageCatalog } from "../../../src/ghidra/GhidraLanguageCatalog.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
@@ -61,9 +63,9 @@ it("skips an oversized definition without buffering it beyond the catalog limit"
'<language_definitions><language id="x86:LE:32:default"/></language_definitions>',
);
- expect(await readGhidraLanguageCatalog(root)).toEqual([
- { id: "x86:LE:32:default", compilerSpecIds: [] },
- ]);
+ expect(
+ await readGhidraLanguageCatalog(root, new ArtifactResourceScope()),
+ ).toEqual([{ id: "x86:LE:32:default", compilerSpecIds: [] }]);
expect(readBytes.value).toBeGreaterThan(0);
expect(readBytes.value).toBeLessThanOrEqual(LIMIT + 1);
});
@@ -80,7 +82,37 @@ it("keeps a definition at exactly the catalog limit", async () => {
Buffer.concat([document, Buffer.alloc(LIMIT - document.length, 0x20)]),
);
- expect(await readGhidraLanguageCatalog(root)).toEqual([
- { id: "edge:LE:32:default", compilerSpecIds: [] },
- ]);
+ expect(
+ await readGhidraLanguageCatalog(root, new ArtifactResourceScope()),
+ ).toEqual([{ id: "edge:LE:32:default", compilerSpecIds: [] }]);
});
+
+it("follows a symlinked definition file", async () => {
+ const root = await createTestTempDirectory("rea-ghidra-ldefs-symlink-");
+ const languages = join(root, "Ghidra/Processors/link/data/languages");
+ await mkdir(languages, { recursive: true });
+ const source = join(root, "source.xml");
+ await writeFile(
+ source,
+ '<language_definitions><language id="link:LE:32:default"/></language_definitions>',
+ );
+ await symlink(source, join(languages, "link.ldefs"));
+ expect(
+ await readGhidraLanguageCatalog(root, new ArtifactResourceScope()),
+ ).toEqual([{ id: "link:LE:32:default", compilerSpecIds: [] }]);
+});
+
+it.skipIf(process.platform === "win32")(
+ "refuses a non-regular definition without waiting for a writer",
+ async () => {
+ const root = await createTestTempDirectory("rea-ghidra-ldefs-fifo-");
+ const languages = join(root, "Ghidra/Processors/pipe/data/languages");
+ await mkdir(languages, { recursive: true });
+ execFileSync("mkfifo", [join(languages, "pipe.ldefs")]);
+ const resources = new ArtifactResourceScope();
+ await expect(
+ readGhidraLanguageCatalog(root, resources),
+ ).rejects.toMatchObject({ code: "ENOTFILE" });
+ expect(resources.hasPending).toBe(false);
+ },
+);
diff --git a/tests/boundary/filesystem/ghidraLanguageCatalogCleanup.test.ts b/tests/boundary/filesystem/ghidraLanguageCatalogCleanup.test.ts
index c00983765..03617837b 100644
--- a/tests/boundary/filesystem/ghidraLanguageCatalogCleanup.test.ts
+++ b/tests/boundary/filesystem/ghidraLanguageCatalogCleanup.test.ts
@@ -3,9 +3,11 @@ import { basename, join } from "node:path";
import { afterEach, expect, it, vi } from "vitest";
import {
- GhidraLanguageCatalogCleanupError,
- readGhidraLanguageCatalog,
-} from "../../../src/ghidra/GhidraLanguageCatalog.js";
+ ArtifactResourceRetryFailure,
+ ArtifactResourceScope,
+} from "../../../src/artifacts/ArtifactResourceScope.js";
+import { ArtifactReaderFailure } from "../../../src/artifacts/ArtifactReader.js";
+import { readGhidraLanguageCatalog } from "../../../src/ghidra/GhidraLanguageCatalog.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
interface FileControl {
@@ -16,6 +18,7 @@ interface FileControl {
readFails: boolean;
invalidated: boolean;
closeCalls: number;
+ opens: number;
}
// Per-file failure controls, keyed by definition file name, and a barrier
@@ -45,6 +48,7 @@ vi.mock("node:fs/promises", async (importOriginal) => {
const real = await actual.open(...args);
const control = controls.get(basename(String(args[0])));
if (control === undefined) return real;
+ control.opens += 1;
let released = false;
const release = async () => {
if (released) return;
@@ -55,6 +59,8 @@ vi.mock("node:fs/promises", async (importOriginal) => {
get fd() {
return control.invalidated ? -1 : real.fd;
},
+ stat: (...statArgs: Parameters<typeof real.stat>) =>
+ real.stat(...statArgs),
read: (...readArgs: Parameters<typeof real.read>) =>
control.readFails
? Promise.reject(new Error("definition read failed"))
@@ -77,8 +83,6 @@ vi.mock("node:fs/promises", async (importOriginal) => {
};
});
-let preserveUnconfirmedOwner = false;
-
const control = (name: string, overrides: Partial<FileControl> = {}) => {
const value: FileControl = {
closeFails: false,
@@ -87,6 +91,7 @@ const control = (name: string, overrides: Partial<FileControl> = {}) => {
readFails: false,
invalidated: false,
closeCalls: 0,
+ opens: 0,
...overrides,
};
controls.set(name, value);
@@ -104,31 +109,77 @@ const installation = async (name: string): Promise<string> => {
return root;
};
-// Let every retained owner close, then drain them through a healthy read.
+const scopes: ArtifactResourceScope[] = [];
+const scope = (): ArtifactResourceScope => {
+ const value = new ArtifactResourceScope();
+ scopes.push(value);
+ return value;
+};
+
+// Let every retained owner close through its own scope, except an invalidated
+// descriptor whose close can never be confirmed.
afterEach(async () => {
- if (preserveUnconfirmedOwner) {
- preserveUnconfirmedOwner = false;
- controls.clear();
- return;
- }
- for (const value of controls.values()) value.closeFails = false;
- await readGhidraLanguageCatalog(await installation("drain"));
+ for (const value of controls.values())
+ if (!value.invalidateOnFailure) value.closeFails = false;
+ await Promise.allSettled(scopes.map((value) => value.close()));
+ scopes.length = 0;
controls.clear();
});
-it("retries a retained close before the next read", async () => {
+it("retries the retained close in the caller scope before the next read", async () => {
+ const resources = scope();
const retained = control("flaky.ldefs", { closeFails: true });
- await expect(
- readGhidraLanguageCatalog(await installation("flaky")),
- ).rejects.toMatchObject({ paths: [expect.stringContaining("flaky.ldefs")] });
+ const failure = await readGhidraLanguageCatalog(
+ await installation("flaky"),
+ resources,
+ ).catch((cause: unknown) => cause);
+ expect(failure).toBeInstanceOf(ArtifactReaderFailure);
+ expect(failure).toMatchObject({
+ cleanup: { resources: [expect.stringContaining("flaky.ldefs")] },
+ });
+ expect(resources.hasPending).toBe(true);
retained.closeFails = false;
- expect(await readGhidraLanguageCatalog(await installation("x86"))).toEqual([
- { id: "x86:LE:32:default", compilerSpecIds: [] },
- ]);
+ expect(
+ await readGhidraLanguageCatalog(await installation("x86"), resources),
+ ).toEqual([{ id: "x86:LE:32:default", compilerSpecIds: [] }]);
+ expect(retained.closeCalls).toBe(2);
+ expect(resources.hasPending).toBe(false);
+});
+
+it("refuses new reads without opening definitions while the retry still fails", async () => {
+ const resources = scope();
+ const retained = control("stuck.ldefs", { closeFails: true });
+ await expect(
+ readGhidraLanguageCatalog(await installation("stuck"), resources),
+ ).rejects.toBeInstanceOf(ArtifactReaderFailure);
+ const next = control("next.ldefs");
+ const refused = await readGhidraLanguageCatalog(
+ await installation("next"),
+ resources,
+ ).catch((cause: unknown) => cause);
+ expect(refused).toBeInstanceOf(ArtifactResourceRetryFailure);
+ expect(refused).toMatchObject({
+ cleanup: { resources: [expect.stringContaining("stuck.ldefs")] },
+ });
expect(retained.closeCalls).toBe(2);
+ expect(next.opens).toBe(0);
+ expect(resources.hasPending).toBe(true);
+});
+
+it("keeps one scope's retained close out of another scope", async () => {
+ control("isolated.ldefs", { closeFails: true });
+ const failed = scope();
+ await expect(
+ readGhidraLanguageCatalog(await installation("isolated"), failed),
+ ).rejects.toBeInstanceOf(ArtifactReaderFailure);
+ expect(
+ await readGhidraLanguageCatalog(await installation("x86"), scope()),
+ ).toEqual([{ id: "x86:LE:32:default", compilerSpecIds: [] }]);
+ expect(failed.hasPending).toBe(true);
});
it("attempts every retained close and reports the remaining failures together", async () => {
+ const resources = scope();
const first = control("first.ldefs", {
closeFails: true,
synchronizedClose: true,
@@ -138,66 +189,72 @@ it("attempts every retained close and reports the remaining failures together",
synchronizedClose: true,
});
barrier.state.expected = 2;
- // Concurrent resolutions can each retain an owner.
+ // Concurrent resolutions can each retain an owner in the same scope.
const roots = [await installation("first"), await installation("second")];
const results = await Promise.allSettled(
- roots.map((root) => readGhidraLanguageCatalog(root)),
+ roots.map((root) => readGhidraLanguageCatalog(root, resources)),
);
expect(results.map(({ status }) => status)).toEqual(["rejected", "rejected"]);
second.closeFails = false;
const failure = await readGhidraLanguageCatalog(
await installation("x86"),
+ resources,
).catch((cause: unknown) => cause);
- expect(failure).toBeInstanceOf(GhidraLanguageCatalogCleanupError);
+ expect(failure).toBeInstanceOf(ArtifactResourceRetryFailure);
expect(failure).toMatchObject({
- paths: [expect.stringContaining("first.ldefs")],
+ cleanup: { resources: [expect.stringContaining("first.ldefs")] },
});
expect(second.closeCalls).toBe(2);
expect(first.closeCalls).toBe(2);
});
-it("keeps the read failure when the close also fails", async () => {
+it("keeps the read failure primary when the close also fails", async () => {
control("damaged.ldefs", { readFails: true, closeFails: true });
const failure = await readGhidraLanguageCatalog(
await installation("damaged"),
+ scope(),
).catch((cause: unknown) => cause);
- expect(failure).toBeInstanceOf(GhidraLanguageCatalogCleanupError);
+ expect(failure).toBeInstanceOf(ArtifactReaderFailure);
expect(failure).toMatchObject({
- readFailure: expect.objectContaining({ message: "definition read failed" }),
+ message: "definition read failed",
+ cleanup: { resources: [expect.stringContaining("damaged.ldefs")] },
});
});
it("reports retained cleanup for a catalog without definitions", async () => {
+ const resources = scope();
control("pending.ldefs", { closeFails: true });
await expect(
- readGhidraLanguageCatalog(await installation("pending")),
- ).rejects.toBeInstanceOf(GhidraLanguageCatalogCleanupError);
+ readGhidraLanguageCatalog(await installation("pending"), resources),
+ ).rejects.toBeInstanceOf(ArtifactReaderFailure);
const empty = await createTestTempDirectory("rea-ghidra-ldefs-empty-");
- await expect(readGhidraLanguageCatalog(empty)).rejects.toMatchObject({
- paths: [expect.stringContaining("pending.ldefs")],
+ await expect(
+ readGhidraLanguageCatalog(empty, resources),
+ ).rejects.toMatchObject({
+ cleanup: { resources: [expect.stringContaining("pending.ldefs")] },
});
});
it("retains an invalidated descriptor owner and keeps later reads blocked", async () => {
+ const resources = scope();
const broken = control("broken.ldefs", {
closeFails: true,
invalidateOnFailure: true,
});
- const first = await readGhidraLanguageCatalog(
- await installation("broken"),
- ).catch((cause: unknown) => cause);
- expect(first).toBeInstanceOf(GhidraLanguageCatalogCleanupError);
- expect(first).toMatchObject({
- paths: [expect.stringContaining("broken.ldefs")],
+ await expect(
+ readGhidraLanguageCatalog(await installation("broken"), resources),
+ ).rejects.toMatchObject({
+ cleanup: { resources: [expect.stringContaining("broken.ldefs")] },
});
-
const later = await readGhidraLanguageCatalog(
await installation("x86"),
+ resources,
).catch((cause: unknown) => cause);
- expect(later).toBeInstanceOf(GhidraLanguageCatalogCleanupError);
+ expect(later).toBeInstanceOf(ArtifactResourceRetryFailure);
expect(later).toMatchObject({
- paths: [expect.stringContaining("broken.ldefs")],
+ cleanup: { resources: [expect.stringContaining("broken.ldefs")] },
});
+ // The owner refuses to re-close an invalidated descriptor it never confirmed.
expect(broken.closeCalls).toBe(1);
- preserveUnconfirmedOwner = true;
+ expect(resources.hasPending).toBe(true);
});
diff --git a/tests/boundary/filesystem/ghidraLanguageCatalogEncoding.test.ts b/tests/boundary/filesystem/ghidraLanguageCatalogEncoding.test.ts
index 647e5c226..2b7e5153a 100644
--- a/tests/boundary/filesystem/ghidraLanguageCatalogEncoding.test.ts
+++ b/tests/boundary/filesystem/ghidraLanguageCatalogEncoding.test.ts
@@ -1,6 +1,7 @@
import { mkdir, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect, it } from "vitest";
+import { ArtifactResourceScope } from "../../../src/artifacts/ArtifactResourceScope.js";
import { readGhidraLanguageCatalog } from "../../../src/ghidra/GhidraLanguageCatalog.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
@@ -57,11 +58,13 @@ it.each([
await mkdir(directory, { recursive: true });
await writeFile(join(directory, "toy.ldefs"), bytes);
if (expectedError === null)
- expect(await readGhidraLanguageCatalog(root)).toEqual([
- { id: "toy:LE:32:default", compilerSpecIds: ["default"] },
- ]);
+ expect(
+ await readGhidraLanguageCatalog(root, new ArtifactResourceScope()),
+ ).toEqual([{ id: "toy:LE:32:default", compilerSpecIds: ["default"] }]);
else
- await expect(readGhidraLanguageCatalog(root)).rejects.toMatchObject({
+ await expect(
+ readGhidraLanguageCatalog(root, new ArtifactResourceScope()),
+ ).rejects.toMatchObject({
reason: expectedError,
});
},
diff --git a/tests/boundary/filesystem/ghidraLanguageCatalogRecovery.test.ts b/tests/boundary/filesystem/ghidraLanguageCatalogRecovery.test.ts
new file mode 100644
index 000000000..632832d42
--- /dev/null
+++ b/tests/boundary/filesystem/ghidraLanguageCatalogRecovery.test.ts
@@ -0,0 +1,262 @@
+import { mkdir, writeFile } from "node:fs/promises";
+import { join } from "node:path";
+import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
+import { afterEach, expect, it, onTestFinished, vi } from "vitest";
+import { AnalysisProviderRegistry } from "../../../src/application/binary/AnalysisProviderRegistry.js";
+import { composeBinarySession } from "../../../src/application/binary/BinarySessionComposition.js";
+import { parseConfig } from "../../../src/config/parseConfig.js";
+import type { BinaryTarget } from "../../../src/domain/binaryTargetTypes.js";
+import { ghidraProfileInstallationHost } from "../../../src/ghidra/GhidraInstallation.fixture.js";
+import { GhidraProvider } from "../../../src/ghidra/GhidraProvider.js";
+import { silentLogger } from "../../../src/logger.js";
+import { createServer } from "../../../src/server/createServer.js";
+import { createDeferred } from "../../fixtures/binarySession.js";
+import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
+import { nativeAotPeFixture } from "../../fixtures/nativeaotPe.js";
+import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
+
+// Fault only the installed x86 language definition; its real descriptor stays
+// open while close is refused, and closes for real once the fault clears.
+const fault = vi.hoisted(() => ({
+ enabled: false,
+ deny: false,
+ opens: 0,
+ closes: 0,
+ onClose: undefined as (() => Promise<void>) | undefined,
+}));
+vi.mock("node:fs/promises", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("node:fs/promises")>();
+ return {
+ ...actual,
+ open: async (...args: Parameters<typeof actual.open>) => {
+ const handle = await actual.open(...args);
+ if (fault.enabled && String(args[0]).endsWith("/x86.ldefs")) {
+ fault.opens++;
+ const close = handle.close.bind(handle);
+ handle.close = async () => {
+ fault.closes++;
+ await fault.onClose?.();
+ if (fault.deny)
+ throw Object.assign(new Error("injected close EIO"), {
+ code: "EIO",
+ });
+ return close();
+ };
+ }
+ return handle;
+ },
+ };
+});
+
+afterEach(() => {
+ Object.assign(fault, {
+ enabled: false,
+ deny: false,
+ opens: 0,
+ closes: 0,
+ onClose: undefined,
+ });
+});
+
+const fixture = async () => {
+ const root = await createTestTempDirectory("rea-ghidra-catalog-close-");
+ const languages = join(root, "Ghidra/Processors/x86/data/languages");
+ const path = join(root, "fixture.exe");
+ await mkdir(languages, { recursive: true });
+ await writeFile(
+ join(languages, "x86.ldefs"),
+ '<language_definitions><language id="x86:LE:64:default"><compiler id="windows"/></language></language_definitions>',
+ );
+ await writeFile(path, nativeAotPeFixture());
+ const config = parseConfig({
+ GHIDRA_INSTALL_DIR: root,
+ REA_GHIDRA_LANGUAGE_ID: "x86:LE:64:default",
+ });
+ if (!config.ok) throw config.error;
+ const provider = new GhidraProvider(
+ config.value,
+ silentLogger,
+ {},
+ ghidraProfileInstallationHost,
+ () => {
+ throw new Error("unexpected engine startup");
+ },
+ );
+ const registry = new AnalysisProviderRegistry([provider]);
+ onTestFinished(async () => {
+ fault.deny = false;
+ fault.onClose = undefined;
+ await registry.closeOwnedResources();
+ });
+ const target: BinaryTarget = {
+ path,
+ sha256: "a".repeat(64),
+ kind: "executable",
+ format: "pe",
+ architecture: "x86_64",
+ availableArchitectures: ["x86_64"],
+ executableRole: "application",
+ managed: false,
+ };
+ return {
+ definition: join(languages, "x86.ldefs"),
+ path,
+ provider,
+ registry,
+ target,
+ };
+};
+
+it("retries the retained catalog close on later MCP admission and reopens the same registry", async () => {
+ const { definition, path, provider, registry } = await fixture();
+ const session = composeBinarySession(registry);
+ const server = createServer(
+ { kind: "session", session },
+ {
+ logger: silentLogger,
+ },
+ );
+ const client = new Client({ name: "catalog-close-recovery", version: "1" });
+ const [clientTransport, serverTransport] =
+ InMemoryTransport.createLinkedPair();
+ const call = (name: "open_binary" | "close_binary") =>
+ client.callTool({
+ name,
+ arguments: name === "open_binary" ? { path, provider_id: "ghidra" } : {},
+ });
+ try {
+ await server.connect(serverTransport);
+ await client.connect(clientTransport);
+ expect((await call("open_binary")).isError).not.toBe(true);
+ expect((await call("close_binary")).isError).not.toBe(true);
+
+ fault.enabled = true;
+ fault.deny = true;
+ const failed = parseMcpToolError(await call("open_binary"));
+ expect(failed.error).toMatchObject({
+ code: "cleanup_incomplete",
+ details: { cleanup: "incomplete", resources: [definition] },
+ });
+ expect(provider.hasPendingOwnedResources()).toBe(true);
+ expect(registry.hasPendingOwnedResources()).toBe(true);
+ expect({ opens: fault.opens, closes: fault.closes }).toEqual({
+ opens: 1,
+ closes: 1,
+ });
+
+ // While the exact owner still refuses close, admission retries it and stays
+ // fail-closed without reading the catalog again.
+ const refused = parseMcpToolError(await call("open_binary"));
+ expect(refused.error).toMatchObject({
+ code: "cleanup_incomplete",
+ details: { cleanup: "incomplete", resources: [definition] },
+ });
+ expect({ opens: fault.opens, closes: fault.closes }).toEqual({
+ opens: 1,
+ closes: 2,
+ });
+ expect(registry.hasPendingOwnedResources()).toBe(true);
+
+ fault.deny = false;
+ expect((await call("open_binary")).isError).not.toBe(true);
+ // The retained owner released once, then a fresh catalog read closed cleanly.
+ expect({ opens: fault.opens, closes: fault.closes }).toEqual({
+ opens: 2,
+ closes: 4,
+ });
+ expect(provider.hasPendingOwnedResources()).toBe(false);
+ expect((await call("close_binary")).isError).not.toBe(true);
+ expect(registry.hasPendingOwnedResources()).toBe(false);
+ } finally {
+ await client.close();
+ await server.close();
+ await session.close();
+ }
+});
+
+it.each(["released", "still failing"] as const)(
+ "finishes the catalog cleanup retry when admission is cancelled during it (%s)",
+ async (outcome) => {
+ const { definition, registry, target } = await fixture();
+ fault.enabled = true;
+ fault.deny = true;
+ const first = await registry.select(target, "ghidra");
+ if (first.ok) throw new Error("Expected incomplete catalog cleanup");
+ expect(first.error.cleanupIncomplete).toBe(true);
+ expect(first.error.cleanupResources).toEqual([definition]);
+
+ const entered = createDeferred<undefined>();
+ const release = createDeferred<undefined>();
+ fault.onClose = async () => {
+ entered.resolve(undefined);
+ await release.promise;
+ };
+ const controller = new AbortController();
+ const reason = { caller: "cancel during catalog cleanup retry" };
+ let settled = false;
+ const admission = registry
+ .select(target, "ghidra", { signal: controller.signal })
+ .finally(() => {
+ settled = true;
+ });
+ await entered.promise;
+ controller.abort(reason);
+ await Promise.resolve();
+ // Cancellation never abandons the in-flight close of the retained owner.
+ expect(settled).toBe(false);
+ if (outcome === "released") fault.deny = false;
+ fault.onClose = undefined;
+ release.resolve(undefined);
+ const cancelled = await admission;
+ if (cancelled.ok) throw new Error("Expected cancelled admission");
+ expect(fault.closes).toBe(2);
+ expect(fault.opens).toBe(1);
+
+ if (outcome === "released") {
+ expect(cancelled.error).toMatchObject({
+ _tag: "AnalysisCancelledError",
+ cause: reason,
+ cleanupIncomplete: false,
+ });
+ expect(first.error.cleanupIncomplete).toBe(false);
+ expect(registry.hasPendingOwnedResources()).toBe(false);
+ } else {
+ expect(cancelled.error.cleanupIncomplete).toBe(true);
+ expect(cancelled.error.cleanupResources).toEqual([definition]);
+ expect(first.error.cleanupIncomplete).toBe(true);
+ expect(registry.hasPendingOwnedResources()).toBe(true);
+ fault.deny = false;
+ }
+ const recovered = await registry.select(target, "ghidra");
+ expect(recovered.ok).toBe(true);
+ expect(first.error.cleanupIncomplete).toBe(false);
+ expect(registry.hasPendingOwnedResources()).toBe(false);
+ },
+);
+
+it("keeps the caller's reason and the catalog owner when cancellation lands during the final close", async () => {
+ const { definition, provider, target } = await fixture();
+ const controller = new AbortController();
+ const reason = { caller: "cancel during final catalog close" };
+ fault.enabled = true;
+ fault.deny = true;
+ fault.onClose = async () => {
+ controller.abort(reason);
+ };
+ const resolved = await provider.resolveAnalysisProfile(target, {
+ signal: controller.signal,
+ });
+ if (resolved.ok) throw new Error("Expected cancelled catalog read");
+ expect(resolved.error).toMatchObject({
+ _tag: "AnalysisCancelledError",
+ cleanupIncomplete: true,
+ cleanupResources: [definition],
+ });
+ expect(JSON.stringify(resolved.error.cause)).toContain(reason.caller);
+ expect(provider.hasPendingOwnedResources()).toBe(true);
+ fault.deny = false;
+ fault.onClose = undefined;
+ expect((await provider.closeOwnedResources()).ok).toBe(true);
+ expect(resolved.error.cleanupIncomplete).toBe(false);
+ expect(provider.hasPendingOwnedResources()).toBe(false);
+});