mirror of
https://github.com/morluto/rea.git
synced 2026-11-23 23:15:58 +00:00
468 lines
16 KiB
TypeScript
468 lines
16 KiB
TypeScript
import { mkdir, writeFile } from "node:fs/promises";
|
|
import { basename, join } from "node:path";
|
|
import { afterEach, expect, it, vi } from "vitest";
|
|
|
|
import {
|
|
ArtifactResourceRetryFailure,
|
|
ArtifactResourceScope,
|
|
} from "../../../src/resources/ArtifactResourceScope.js";
|
|
import { ArtifactReaderFailure } from "../../../src/resources/ArtifactReader.js";
|
|
import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js";
|
|
import { ghidraFileDialect } from "../../../src/ghidra/GhidraFileArtifacts.js";
|
|
import { classifyProviderFailure } from "../../../src/providers/classifyProviderFailure.js";
|
|
import { readGhidraLanguageCatalog } from "../../../src/ghidra/GhidraLanguageCatalog.js";
|
|
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
|
import { phaseArrival, phaseGate } from "../../support/lifecycleHarness.js";
|
|
|
|
interface FileControl {
|
|
closeFails: boolean;
|
|
/** Hold close() until every synchronized handle has reached it. */
|
|
synchronizedClose: boolean;
|
|
invalidateOnFailure: boolean;
|
|
readFails: boolean;
|
|
openDenied: boolean;
|
|
invalidated: boolean;
|
|
closeCalls: number;
|
|
opens: number;
|
|
}
|
|
|
|
// Per-file failure controls, keyed by definition file name, and a barrier
|
|
// that releases synchronized closes only after all of them are pending.
|
|
const { controls, directoryControls, barrier } = vi.hoisted(() => {
|
|
const state = { expected: 0, arrived: 0, release: () => {} };
|
|
let gate = new Promise<void>((resolve) => {
|
|
state.release = resolve;
|
|
});
|
|
return {
|
|
controls: new Map<string, FileControl>(),
|
|
directoryControls: new Map<
|
|
string,
|
|
(entries: readonly string[]) => Promise<void>
|
|
>(),
|
|
barrier: {
|
|
reset: (expected: number) => {
|
|
state.expected = expected;
|
|
state.arrived = 0;
|
|
gate = new Promise<void>((resolve) => {
|
|
state.release = resolve;
|
|
});
|
|
},
|
|
arrive: async () => {
|
|
state.arrived += 1;
|
|
if (state.arrived >= state.expected) state.release();
|
|
await gate;
|
|
},
|
|
},
|
|
};
|
|
});
|
|
vi.mock("node:fs/promises", async (importOriginal) => {
|
|
const actual = await importOriginal<typeof import("node:fs/promises")>();
|
|
return {
|
|
...actual,
|
|
readdir: async (path: Parameters<typeof actual.readdir>[0]) => {
|
|
const entries = await actual.readdir(path);
|
|
await directoryControls.get(String(path))?.(entries);
|
|
return entries;
|
|
},
|
|
open: async (...args: Parameters<typeof actual.open>) => {
|
|
const path = String(args[0]);
|
|
const control = controls.get(basename(path));
|
|
if (control?.openDenied) {
|
|
// Guarantee the other worker has reached its real descriptor close.
|
|
await barrier.arrive();
|
|
throw Object.assign(new Error("definition open denied"), {
|
|
code: "EACCES",
|
|
path,
|
|
});
|
|
}
|
|
const real = await actual.open(...args);
|
|
if (control === undefined) return real;
|
|
control.opens += 1;
|
|
let released = false;
|
|
const release = async () => {
|
|
if (released) return;
|
|
released = true;
|
|
await real.close();
|
|
};
|
|
return {
|
|
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"))
|
|
: real.read(...readArgs),
|
|
close: async () => {
|
|
control.closeCalls += 1;
|
|
if (control.synchronizedClose && control.closeCalls === 1)
|
|
await barrier.arrive();
|
|
if (control.closeFails) {
|
|
if (control.invalidateOnFailure) {
|
|
await release();
|
|
control.invalidated = true;
|
|
}
|
|
throw new Error(`definition close failed: ${String(args[0])}`);
|
|
}
|
|
await release();
|
|
},
|
|
};
|
|
},
|
|
};
|
|
});
|
|
|
|
const control = (name: string, overrides: Partial<FileControl> = {}) => {
|
|
const value: FileControl = {
|
|
closeFails: false,
|
|
synchronizedClose: false,
|
|
invalidateOnFailure: false,
|
|
readFails: false,
|
|
openDenied: false,
|
|
invalidated: false,
|
|
closeCalls: 0,
|
|
opens: 0,
|
|
...overrides,
|
|
};
|
|
controls.set(name, value);
|
|
return value;
|
|
};
|
|
|
|
const installation = async (name: string): Promise<string> => {
|
|
const root = await createTestTempDirectory("rea-ghidra-ldefs-cleanup-");
|
|
const languages = join(root, "Ghidra/Processors", name, "data/languages");
|
|
await mkdir(languages, { recursive: true });
|
|
await writeFile(
|
|
join(languages, `${name}.ldefs`),
|
|
`<language_definitions><language id="${name}:LE:32:default"/></language_definitions>`,
|
|
);
|
|
return root;
|
|
};
|
|
|
|
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 () => {
|
|
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();
|
|
directoryControls.clear();
|
|
});
|
|
|
|
it.for(["installation roots", "module directories"] as const)(
|
|
"reports cancellation while completing an empty scan of %s",
|
|
async (stage) => {
|
|
const root = await createTestTempDirectory("rea-ghidra-ldefs-empty-");
|
|
const directory = join(
|
|
root,
|
|
stage === "installation roots"
|
|
? "Ghidra/Extensions"
|
|
: "Ghidra/Processors/x86/data/languages",
|
|
);
|
|
await mkdir(directory, { recursive: true });
|
|
const gate = phaseGate<readonly string[]>();
|
|
directoryControls.set(directory, (entries) => gate.hold(entries));
|
|
const resources = scope();
|
|
const controller = new AbortController();
|
|
const reason = { stage, cancelled: true };
|
|
const reading = readGhidraLanguageCatalog(
|
|
root,
|
|
resources,
|
|
controller.signal,
|
|
);
|
|
try {
|
|
expect(await gate.reached(reading, stage)).toEqual([]);
|
|
controller.abort(reason);
|
|
gate.release();
|
|
const failure = await reading.catch((cause: unknown) => cause);
|
|
if (!(failure instanceof ArtifactReaderFailure))
|
|
throw new Error("Expected typed artifact cancellation", {
|
|
cause: failure,
|
|
});
|
|
expect(failure.reason).toBe("cancelled");
|
|
expect(failure.cause).toBe(reason);
|
|
} finally {
|
|
gate.release();
|
|
await reading.catch(() => undefined);
|
|
}
|
|
expect(await readGhidraLanguageCatalog(root, resources)).toEqual({
|
|
definitions: [],
|
|
oversizedFiles: [],
|
|
});
|
|
},
|
|
);
|
|
|
|
it("refuses an already cancelled catalog before reading the installation", async () => {
|
|
const root = await createTestTempDirectory("rea-ghidra-ldefs-cancelled-");
|
|
const processors = join(root, "Ghidra/Processors");
|
|
await mkdir(processors, { recursive: true });
|
|
const visited: string[] = [];
|
|
directoryControls.set(processors, async () => {
|
|
visited.push(processors);
|
|
});
|
|
const reason = { source: "caller" };
|
|
await expect(
|
|
readGhidraLanguageCatalog(root, scope(), AbortSignal.abort(reason)),
|
|
).rejects.toMatchObject({ reason: "cancelled", cause: reason });
|
|
expect(visited).toEqual([]);
|
|
});
|
|
|
|
it("reports the lowest selected directory failure after another directory fails first", async () => {
|
|
const root = await createTestTempDirectory("rea-ghidra-ldefs-selection-");
|
|
const earlier = join(root, "Ghidra/Processors/a/data/languages");
|
|
const later = join(root, "Ghidra/Processors/b/data/languages");
|
|
const held = phaseGate();
|
|
const laterFailed = phaseArrival();
|
|
const makeFailure = (path: string) =>
|
|
Object.assign(new Error("directory read denied"), { code: "EACCES", path });
|
|
await Promise.all(
|
|
[earlier, later].map((directory) => mkdir(directory, { recursive: true })),
|
|
);
|
|
const primary = makeFailure(earlier);
|
|
directoryControls.set(earlier, () => held.hold());
|
|
directoryControls.set(later, async () => {
|
|
laterFailed.arrive();
|
|
throw makeFailure(later);
|
|
});
|
|
const reading = readGhidraLanguageCatalog(root, scope());
|
|
try {
|
|
await held.reached(reading, "earlier directory is still pending");
|
|
await laterFailed.reached(reading, "later directory refused first");
|
|
held.reject(primary);
|
|
await expect(reading).rejects.toBe(primary);
|
|
} finally {
|
|
held.release();
|
|
await reading.catch(() => undefined);
|
|
}
|
|
});
|
|
|
|
it("blocks nonempty and empty reads until the caller scope releases the same descriptor", async () => {
|
|
const resources = scope();
|
|
const retained = control("flaky.ldefs", { closeFails: true });
|
|
const owner = { resources: [expect.stringContaining("flaky.ldefs")] };
|
|
const failure = await readGhidraLanguageCatalog(
|
|
await installation("flaky"),
|
|
resources,
|
|
).catch((cause: unknown) => cause);
|
|
expect(failure).toBeInstanceOf(ArtifactReaderFailure);
|
|
expect(failure).toMatchObject({ cleanup: owner });
|
|
expect(resources.hasPending).toBe(true);
|
|
|
|
const next = control("x86.ldefs");
|
|
const nextRoot = await installation("x86");
|
|
const refused = await readGhidraLanguageCatalog(nextRoot, resources).catch(
|
|
(cause: unknown) => cause,
|
|
);
|
|
expect(refused).toBeInstanceOf(ArtifactResourceRetryFailure);
|
|
expect(refused).toMatchObject({ cleanup: owner });
|
|
expect(retained.closeCalls).toBe(2);
|
|
expect(next.opens).toBe(0);
|
|
|
|
const empty = await createTestTempDirectory("rea-ghidra-ldefs-empty-");
|
|
await expect(
|
|
readGhidraLanguageCatalog(empty, resources),
|
|
).rejects.toMatchObject({ cleanup: owner });
|
|
expect(retained.closeCalls).toBe(3);
|
|
expect(resources.hasPending).toBe(true);
|
|
|
|
retained.closeFails = false;
|
|
const catalog = await readGhidraLanguageCatalog(nextRoot, resources);
|
|
expect(catalog.definitions).toEqual([
|
|
{ id: "x86:LE:32:default", compilerSpecIds: [] },
|
|
]);
|
|
expect(retained.closeCalls).toBe(4);
|
|
expect(next.opens).toBe(1);
|
|
expect(resources.hasPending).toBe(false);
|
|
});
|
|
|
|
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);
|
|
const catalog = await readGhidraLanguageCatalog(
|
|
await installation("x86"),
|
|
scope(),
|
|
);
|
|
expect(catalog.definitions).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,
|
|
});
|
|
const second = control("second.ldefs", {
|
|
closeFails: true,
|
|
synchronizedClose: true,
|
|
});
|
|
barrier.reset(2);
|
|
// 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, 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(ArtifactResourceRetryFailure);
|
|
expect(failure).toMatchObject({
|
|
cleanup: { resources: [expect.stringContaining("first.ldefs")] },
|
|
});
|
|
expect(second.closeCalls).toBe(2);
|
|
expect(first.closeCalls).toBe(2);
|
|
});
|
|
|
|
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(ArtifactReaderFailure);
|
|
expect(failure).toMatchObject({
|
|
message: "definition read failed",
|
|
cleanup: { resources: [expect.stringContaining("damaged.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,
|
|
});
|
|
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(ArtifactResourceRetryFailure);
|
|
expect(later).toMatchObject({
|
|
cleanup: { resources: [expect.stringContaining("broken.ldefs")] },
|
|
});
|
|
// The owner refuses to re-close an invalidated descriptor it never confirmed.
|
|
expect(broken.closeCalls).toBe(1);
|
|
expect(resources.hasPending).toBe(true);
|
|
});
|
|
|
|
it("merges sibling cleanup observations and leases across concurrent definition failures", async () => {
|
|
const resources = scope();
|
|
const root = await createTestTempDirectory("rea-ghidra-ldefs-multi-");
|
|
for (let index = 0; index < 10; index += 1) {
|
|
const name = `mod_${String(index).padStart(2, "0")}`;
|
|
const languages = join(root, "Ghidra/Processors", name, "data/languages");
|
|
await mkdir(languages, { recursive: true });
|
|
await writeFile(
|
|
join(languages, `${name}.ldefs`),
|
|
`<language_definitions><language id="${name}:LE:32:default"/></language_definitions>`,
|
|
);
|
|
}
|
|
const first = control("mod_01.ldefs", {
|
|
closeFails: true,
|
|
synchronizedClose: true,
|
|
});
|
|
const second = control("mod_03.ldefs", {
|
|
closeFails: true,
|
|
synchronizedClose: true,
|
|
});
|
|
barrier.reset(2);
|
|
|
|
const failure = await readGhidraLanguageCatalog(root, resources).catch(
|
|
(cause: unknown) => cause,
|
|
);
|
|
expect(failure).toBeInstanceOf(ArtifactReaderFailure);
|
|
expect(failure).toMatchObject({
|
|
cleanup: {
|
|
resources: [
|
|
expect.stringContaining("mod_01.ldefs"),
|
|
expect.stringContaining("mod_03.ldefs"),
|
|
],
|
|
},
|
|
});
|
|
if (failure instanceof ArtifactReaderFailure)
|
|
expect(failure.cleanupLeases).toHaveLength(2);
|
|
expect(resources.hasPending).toBe(true);
|
|
|
|
first.closeFails = false;
|
|
second.closeFails = false;
|
|
const recovered = await readGhidraLanguageCatalog(
|
|
await installation("x86"),
|
|
resources,
|
|
);
|
|
expect(recovered.definitions).toEqual([
|
|
{ id: "x86:LE:32:default", compilerSpecIds: [] },
|
|
]);
|
|
expect(first.closeCalls).toBe(2);
|
|
expect(second.closeCalls).toBe(2);
|
|
expect(resources.hasPending).toBe(false);
|
|
const catalog = await readGhidraLanguageCatalog(root, resources);
|
|
expect(catalog.definitions).toHaveLength(10);
|
|
});
|
|
|
|
it("reports the denied definition as primary while owning a sibling close retry", async () => {
|
|
const resources = scope();
|
|
const root = await installation("denied");
|
|
const siblingDirectory = join(root, "Ghidra/Processors/stuck/data/languages");
|
|
await mkdir(siblingDirectory, { recursive: true });
|
|
await writeFile(
|
|
join(siblingDirectory, "stuck.ldefs"),
|
|
"<language_definitions/>",
|
|
);
|
|
control("denied.ldefs", { openDenied: true });
|
|
const stuck = control("stuck.ldefs", {
|
|
closeFails: true,
|
|
synchronizedClose: true,
|
|
});
|
|
barrier.reset(2);
|
|
|
|
const cause = await readGhidraLanguageCatalog(root, resources).catch(
|
|
(cause: unknown) => cause,
|
|
);
|
|
const failure = classifyProviderFailure(
|
|
cause,
|
|
ghidraFileDialect("resolve_analysis_profile"),
|
|
);
|
|
expect(projectAnalysisError(failure)).toMatchObject({
|
|
code: "cleanup_incomplete",
|
|
details: {
|
|
resources: [join(siblingDirectory, "stuck.ldefs")],
|
|
diagnostics: {
|
|
primary_error: {
|
|
code: "access_denied",
|
|
details: {
|
|
path: join(
|
|
root,
|
|
"Ghidra/Processors/denied/data/languages/denied.ldefs",
|
|
),
|
|
},
|
|
},
|
|
},
|
|
},
|
|
});
|
|
stuck.closeFails = false;
|
|
await resources.close();
|
|
expect(stuck.closeCalls).toBe(2);
|
|
expect(failure.cleanupIncomplete).toBe(false);
|
|
});
|