refactor(ghidra): require an owned committed project copy (#13363)

This commit is contained in:
morluto authored and GitHub committed 2026-11-22 09:38:42 +00:00
1 parent 7c8493d41d
commit fb6e0dc6e8
5 files changed
+195 -280

No files matched your search

+2 -2
View File
@@ -223,8 +223,8 @@ const ghidraLaunchCommandOutput = (
export interface GhidraExistingProject {
/** Directory holding the selected .gpr marker and .rep data directory. */
readonly projectPath: string;
readonly projectName?: string;
readonly sha256?: string;
readonly projectName: string;
readonly sha256: string;
/** Imported program name selected with -process. */
readonly programName: string;
}
+41 -93
View File
@@ -7,7 +7,7 @@ import {
import { HOST_PLATFORM } from "../platform/HostPlatform.js";
import type { BinaryTarget } from "../domain/binaryTargetTypes.js";
import { createHash } from "node:crypto";
import { cp, lstat, mkdir, readdir, realpath } from "node:fs/promises";
import { lstat, mkdir, readdir, realpath } from "node:fs/promises";
import {
basename,
dirname,
@@ -245,81 +245,23 @@ const pathsOverlap = (first: string, second: string): boolean => {
const COPY_BUFFER_BYTES = 256 * 1024;
const copyProjectWithScope = async (
source: string,
destinationRoot: string,
projectName: string,
resources: ArtifactResourceScope,
options: {
readonly sourcePath: string;
readonly expectedSha256: string | undefined;
readonly signal: AbortSignal | undefined;
},
): Promise<void> => {
const { sourcePath, expectedSha256, signal } = options;
const hash = expectedSha256 === undefined ? undefined : createHash("sha256");
const buffer = Buffer.allocUnsafe(COPY_BUFFER_BYTES);
await visitProject(
source,
projectName,
async (path, directory) => {
if (hash !== undefined)
hash.update(
JSON.stringify([
path.split(sep).join("/"),
directory ? "directory" : "file",
]) + "\n",
);
const destination = join(destinationRoot, path);
if (directory) {
await mkdir(destination, { mode: 0o700 });
assertArtifactReadActive(signal);
return;
}
await copyGhidraRegularFile(join(source, path), destination, resources, {
signal,
buffer,
...(hash === undefined
? {}
: {
hash,
onOpenedSource: (initialSize) => {
hash.update(`${String(initialSize)}\n`);
},
}),
});
assertArtifactReadActive(signal);
},
signal,
);
if (hash !== undefined && hash.digest("hex") !== expectedSha256)
// A digest mismatch shows only that the project differs from its
// committed profile, not when it changed relative to this copy.
throw new AnalysisArtifactChangedError(
"open_binary",
sourcePath,
GHIDRA_PROJECT_PROFILE_MISMATCH,
);
};
/** Never open the caller project itself. Copy only the selected pair, then revalidate its committed content. */
/** Copy the selected pair through owned descriptors and match its committed content. */
export const copyExistingGhidraProject = async (
sourcePath: string,
destinationRoot: string,
options: {
{
signal,
projectName,
expectedSha256,
resources,
}: {
readonly signal?: AbortSignal | undefined;
readonly projectName?: string | undefined;
readonly expectedSha256?: string | undefined;
readonly resources?: ArtifactResourceScope | undefined;
} = {},
readonly projectName: string;
readonly expectedSha256: string;
readonly resources: ArtifactResourceScope;
},
): Promise<void> => {
return projectFileOperation(sourcePath, "open_binary", async () => {
const {
signal,
projectName = "rea-project",
expectedSha256,
resources,
} = options;
assertArtifactReadActive(signal);
const source = await realpath(sourcePath).catch(absentProjectEntry);
const runtime =
@@ -339,39 +281,45 @@ export const copyExistingGhidraProject = async (
`Existing Ghidra project directory does not exist: ${sourcePath}`,
);
await validateProject(source, projectName);
if (expectedSha256 !== undefined && resources === undefined)
throw selectionFailure(
"Existing project verification requires an owned resource scope.",
);
if (resources !== undefined) {
await copyProjectWithScope(
source,
destinationRoot,
projectName,
resources,
{
sourcePath,
expectedSha256,
signal,
},
);
return;
}
const hash = createHash("sha256");
const buffer = Buffer.allocUnsafe(COPY_BUFFER_BYTES);
await visitProject(
source,
projectName,
async (path, directory) => {
hash.update(
JSON.stringify([
path.split(sep).join("/"),
directory ? "directory" : "file",
]) + "\n",
);
const destination = join(destinationRoot, path);
if (directory) await mkdir(destination, { mode: 0o700 });
else
await cp(join(source, path), destination, {
dereference: true,
errorOnExist: true,
force: false,
});
await copyGhidraRegularFile(
join(source, path),
destination,
resources,
{
signal,
buffer,
hash,
onOpenedSource: (initialSize) => {
hash.update(`${String(initialSize)}\n`);
},
},
);
assertArtifactReadActive(signal);
},
signal,
);
if (hash.digest("hex") !== expectedSha256)
// A digest mismatch shows only that the project differs from its
// committed profile, not when it changed relative to this copy.
throw new AnalysisArtifactChangedError(
"open_binary",
sourcePath,
GHIDRA_PROJECT_PROFILE_MISMATCH,
);
});
};
@@ -15,6 +15,7 @@ import { join, posix, win32 } from "node:path";
import { fileURLToPath } from "node:url";
import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";
import { fingerprintGhidraProject } from "../../../../src/ghidra/GhidraProjectSnapshot.js";
import { z } from "zod";
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
@@ -717,17 +718,13 @@ describe("Ghidra existing project", () => {
descriptorPath: "/tmp/session.json",
ghidraLogPath: "/tmp/ghidra.log",
scriptLogPath: "/tmp/script.log",
existingProject: { projectName: "rea-project", programName: "game.exe" },
};
it("opens a pre-imported program without importing or deleting the project", () => {
const arguments_ = ghidraHeadlessArguments({
...base,
existingProject: { programName: "game.exe" },
});
// The project location and name stay explicit; nothing is imported.
expect(arguments_.slice(0, 2)).toEqual(["/tmp/project", "rea-project"]);
expect(arguments_).not.toContain("-import");
expect(arguments_).not.toContain("-deleteProject");
expect(arguments_).toEqual([
"/tmp/project",
"rea-project",
@@ -782,7 +779,6 @@ describe("Ghidra existing project", () => {
expect(() =>
ghidraHeadlessArguments({
...base,
existingProject: { programName: "game.exe" },
...conflict,
}),
).toThrow(
@@ -801,7 +797,6 @@ describe("Ghidra existing project", () => {
"bridge",
"ReaGhidraBridge.java",
),
existingProject: { programName: "game.exe" },
}),
).toThrow(
expect.objectContaining({
@@ -815,7 +810,7 @@ describe("Ghidra existing project", () => {
expect(() =>
ghidraHeadlessArguments({
...base,
existingProject: { programName: " " },
existingProject: { projectName: "rea-project", programName: " " },
}),
).toThrow(
expect.objectContaining({
@@ -856,7 +851,15 @@ const launchExistingProject = async (
runtimeRoot: string,
parent: string,
projectPath: string,
spawned: OwnedProviderProcessSpawnOptions[],
{
spawned,
commitment = "a".repeat(64),
observeSpawn,
}: {
spawned: OwnedProviderProcessSpawnOptions[];
commitment?: string;
observeSpawn?: () => Promise<void>;
},
) => {
const javaHome = await createFakeJavaHome(parent);
const launcher = new GhidraHeadlessLauncher({
@@ -866,9 +869,15 @@ const launchExistingProject = async (
configurationDirectoryName: "ghidra_12.1.4_PUBLIC",
javaHome,
bridgeScriptPath: "/package/bridge/ReaGhidraBridge.java",
existingProject: { projectPath, programName: "game.exe" },
existingProject: {
projectPath,
projectName: "rea-project",
programName: "game.exe",
sha256: commitment,
},
spawnProcess: async (options) => {
spawned.push(options);
await observeSpawn?.();
return fakeSpawnedProcess(options.runId);
},
});
@@ -905,12 +914,32 @@ describe("Ghidra existing project launcher", () => {
join(sourceProject, "rea-project.rep", "marker"),
"recursive",
);
const commitment = await fingerprintGhidraProject(
sourceProject,
"rea-project",
createTestArtifactResourceScope(),
);
const spawned: OwnedProviderProcessSpawnOptions[] = [];
const launched = await launchExistingProject(
runtime.path,
parent,
sourceProject,
spawned,
{
spawned,
commitment,
observeSpawn: async () => {
const copiedProject = join(runtime.path, "project");
expect(
await readFile(join(copiedProject, "rea-project.gpr"), "utf8"),
).toBe("pre-imported");
expect(
await readFile(
join(copiedProject, "rea-project.rep", "marker"),
"utf8",
),
).toBe("recursive");
},
},
);
if (!launched.ok) throw launched.error;
try {
@@ -920,19 +949,6 @@ describe("Ghidra existing project launcher", () => {
expectOptions(spawned[0]?.arguments ?? [], [["-process", "game.exe"]]);
expect(spawned[0]?.arguments).toContain("-noanalysis");
expect(spawned[0]?.arguments).toContain("-readOnly");
// Copy-first: the owned runtime holds the copy before Ghidra starts.
expect(
await readFile(join(runtime.path, "project", "rea-project.gpr"), {
encoding: "utf8",
}),
).toBe("pre-imported");
expect(
await readFile(
join(runtime.path, "project", "rea-project.rep", "marker"),
{ encoding: "utf8" },
),
).toBe("recursive");
// The caller's original project files stay untouched.
expect(await readFile(projectMarker, { encoding: "utf8" })).toBe(
"pre-imported",
);
@@ -954,7 +970,7 @@ describe("Ghidra existing project launcher", () => {
runtime.path,
parent,
join(parent, "absent-project"),
spawned,
{ spawned },
);
if (launched.ok) throw new Error("launch unexpectedly succeeded");
// The launcher wraps the copy failure; the reason stays on the cause.
@@ -963,74 +979,18 @@ describe("Ghidra existing project launcher", () => {
},
);
it.skipIf(process.platform === "win32")(
"rejects a project without the fixed rea-project name before copying",
async () => {
it.skipIf(process.platform === "win32").each([".", "project"])(
"rejects a source at %s relative to the runtime root before copying",
async (relativeSource) => {
const parent = await createTestTempDirectory("rea-launcher-test-");
const runtime = await createGhidraTestRuntime(parent);
runtimes.push(runtime);
// The headless open selects the project by the fixed name; a caller
// directory holding any other project file must fail with its reason
// instead of spawning into an opaque Ghidra error.
const sourceProject = join(parent, "user-project");
await mkdir(sourceProject, { recursive: true });
await writeFile(join(sourceProject, "other-project.grez"), "mislabeled");
const spawned: OwnedProviderProcessSpawnOptions[] = [];
const launched = await launchExistingProject(
runtime.path,
parent,
sourceProject,
spawned,
);
if (launched.ok) throw new Error("launch unexpectedly succeeded");
expect(String(launched.error.cause)).toMatch(/rea-project\.gpr/u);
expect(spawned).toHaveLength(0);
// Nothing from the rejected project was copied into the owned runtime.
await expect(
access(join(runtime.path, "project")),
).resolves.toBeUndefined();
expect(await readdir(join(runtime.path, "project"))).toEqual([]);
},
);
it.skipIf(process.platform === "win32")(
"rejects a project path that overlaps the runtime before copying",
async () => {
const parent = await createTestTempDirectory("rea-launcher-test-");
const runtime = await createGhidraTestRuntime(parent);
runtimes.push(runtime);
// Copying the runtime into itself would recurse without bound, so the
// launcher must refuse the overlap before touching the file system.
const spawned: OwnedProviderProcessSpawnOptions[] = [];
const launched = await launchExistingProject(
runtime.path,
parent,
runtime.path,
spawned,
);
if (launched.ok) throw new Error("launch unexpectedly succeeded");
expect(String(launched.error.cause)).toMatch(
/overlaps the REA runtime directory/u,
);
expect(spawned).toHaveLength(0);
expect(await readdir(join(runtime.path, "project"))).toEqual([]);
},
);
it.skipIf(process.platform === "win32")(
"rejects a project path inside the runtime before copying",
async () => {
const parent = await createTestTempDirectory("rea-launcher-test-");
const runtime = await createGhidraTestRuntime(parent);
runtimes.push(runtime);
// A caller-supplied path inside the owned runtime (here the project
// root itself) is equally an overlap and must fail before Ghidra runs.
const spawned: OwnedProviderProcessSpawnOptions[] = [];
const launched = await launchExistingProject(
runtime.path,
parent,
join(runtime.path, "project"),
spawned,
join(runtime.path, relativeSource),
{ spawned },
);
if (launched.ok) throw new Error("launch unexpectedly succeeded");
expect(String(launched.error.cause)).toMatch(
@@ -1065,7 +1025,7 @@ describe("Ghidra existing project symlink overlap", () => {
runtime.path,
parent,
alias,
spawned,
{ spawned },
);
if (launched.ok) throw new Error("launch unexpectedly succeeded");
expect(String(launched.error.cause)).toMatch(
@@ -1079,7 +1039,7 @@ describe("Ghidra existing project symlink overlap", () => {
describe("Ghidra expanded project admission", () => {
it.each([
{ label: "archive only", marker: false, data: false },
{ label: "archive plus unrelated project", marker: false, data: false },
{ label: "marker without data", marker: true, data: false },
{ label: "data without marker", marker: false, data: true },
])("rejects $label before starting Ghidra", async ({ marker, data }) => {
@@ -1089,6 +1049,8 @@ describe("Ghidra expanded project admission", () => {
const sourceProject = join(parent, "user-project");
await mkdir(sourceProject);
await writeFile(join(sourceProject, "rea-project.grez"), "saved archive");
await writeFile(join(sourceProject, "other-project.gpr"), "other marker");
await mkdir(join(sourceProject, "other-project.rep"));
if (marker)
await writeFile(join(sourceProject, "rea-project.gpr"), "marker");
if (data) await mkdir(join(sourceProject, "rea-project.rep"));
@@ -1097,7 +1059,7 @@ describe("Ghidra expanded project admission", () => {
runtime.path,
parent,
sourceProject,
spawned,
{ spawned },
);
if (launched.ok) throw new Error("launch unexpectedly succeeded");
expect(String(launched.error.cause)).toMatch(
@@ -41,45 +41,10 @@ const fixture = async ({ sharedParent = false } = {}) => {
return { source, destination };
};
it("copies only the selected project beside the caller's project and its unrelated entries", async () => {
const { source, destination } = await fixture({ sharedParent: true });
const unrelated = join(source, "unrelated.gpr");
if (process.platform === "win32")
await writeFile(unrelated, "unrelated marker");
else await symlink("unrelated-missing-project", unrelated);
const commitment = await resolveGhidraProject(
{ path: join(source, "selected.gpr"), programName: "target.elf" },
{ path: "/tmp/target.elf" },
resources,
);
await copyExistingGhidraProject(source, destination, {
projectName: "selected",
expectedSha256: commitment.sha256,
resources,
});
expect((await readdir(destination)).sort()).toEqual([
"selected.gpr",
"selected.rep",
]);
expect(await readFile(join(destination, "selected.gpr"), "utf8")).toBe(
"marker",
);
expect(
await readFile(join(destination, "selected.rep", "data"), "utf8"),
).toBe("original program");
expect(await fingerprintGhidraProject(source, "selected", resources)).toBe(
commitment.sha256,
);
if (process.platform === "win32")
expect(await readFile(unrelated, "utf8")).toBe("unrelated marker");
else expect(await readlink(unrelated)).toBe("unrelated-missing-project");
});
it("rejects a copy whose last block differs from the committed project", async () => {
const { source, destination } = await fixture();
const data = join(source, "selected.rep", "data");
const contents = Buffer.alloc(64 * 1024 + 1, 0x61);
const contents = Buffer.alloc(256 * 1024 + 1, 0x61);
await writeFile(data, contents);
const original = await fingerprintGhidraProject(
source,
@@ -277,24 +242,32 @@ it.skipIf(process.platform === "win32")(
"keeps missing entries and symbolic links classified as invalid selections",
async () => {
const { source, destination } = await fixture();
const expectedSha256 = await fingerprintGhidraProject(
source,
"selected",
resources,
);
const selection = { projectName: "selected", expectedSha256, resources };
await rm(join(source, "selected.gpr"));
await expect(
copyExistingGhidraProject(source, destination, {
projectName: "selected",
}),
copyExistingGhidraProject(source, destination, selection),
).rejects.toMatchObject({ _tag: "ConfigurationError" });
expect(await readdir(destination)).toEqual([]);
await writeFile(join(source, "other.gpr"), "marker");
await symlink("other.gpr", join(source, "selected.gpr"));
await expect(
copyExistingGhidraProject(source, destination, {
projectName: "selected",
}),
copyExistingGhidraProject(source, destination, selection),
).rejects.toMatchObject({ _tag: "ConfigurationError" });
expect(await readdir(destination)).toEqual([]);
},
);
it("copies multi-chunk and empty files in one pass matching fingerprint parity and file modes", async () => {
const { source, destination } = await fixture();
it("copies only the committed project with exact multi-chunk, empty and private files", async () => {
const { source, destination } = await fixture({ sharedParent: true });
const unrelated = join(source, "unrelated.gpr");
if (process.platform === "win32")
await writeFile(unrelated, "unrelated marker");
else await symlink("unrelated-missing-project", unrelated);
const large = Buffer.alloc(256 * 1024 + 17, 0x41);
large[0] = 0x5a;
large[256 * 1024] = 0x7e;
@@ -312,6 +285,19 @@ it("copies multi-chunk and empty files in one pass matching fingerprint parity a
resources,
});
expect((await readdir(destination)).sort()).toEqual([
"selected.gpr",
"selected.rep",
]);
expect(await readFile(join(destination, "selected.gpr"), "utf8")).toBe(
"marker",
);
expect(
(await readFile(join(source, "selected.rep", "data"))).equals(large),
).toBe(true);
if (process.platform === "win32")
expect(await readFile(unrelated, "utf8")).toBe("unrelated marker");
else expect(await readlink(unrelated)).toBe("unrelated-missing-project");
expect(
(await readFile(join(destination, "selected.rep", "data"))).equals(large),
).toBe(true);
@@ -334,17 +320,6 @@ it("copies multi-chunk and empty files in one pass matching fingerprint parity a
}
});
it("refuses expectedSha256 without a resource scope before copying any files", async () => {
const { source, destination } = await fixture();
await expect(
copyExistingGhidraProject(source, destination, {
projectName: "selected",
expectedSha256: "a".repeat(64),
}),
).rejects.toMatchObject({ _tag: "ConfigurationError" });
expect(await readdir(destination)).toEqual([]);
});
it.each([null, "stop-copy"])(
"preserves copy cancellation reason %j without leaving partial verification",
async (reason) => {
@@ -1,56 +1,86 @@
import { mkdir, writeFile } from "node:fs/promises";
import { mkdir, realpath, writeFile, type FileHandle } from "node:fs/promises";
import { join } from "node:path";
import { setImmediate } from "node:timers/promises";
import { expect, it, vi } from "vitest";
import { ArtifactFileCancelled } from "../../src/resources/ArtifactFileOperation.js";
import { ArtifactResourceScope } from "../../src/resources/ArtifactResourceScope.js";
import { AnalysisCancelledError } from "../../src/domain/analysisErrorCore.js";
import { resolveGhidraProject } from "../../src/ghidra/GhidraProjectSnapshot.js";
import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js";
import { phaseGate } from "../support/lifecycleHarness.js";
const fault = vi.hoisted(() => ({ reason: undefined as unknown }));
vi.mock(
"../../src/resources/ArtifactFileOperation.js",
async (importOriginal) => {
const original =
await importOriginal<
typeof import("../../src/resources/ArtifactFileOperation.js")
>();
return {
...original,
withArtifactRegularFile: async () => {
throw new ArtifactFileCancelled({
reason: fault.reason,
outcome: { kind: "completed", value: undefined },
});
},
};
},
);
const projectFileClose = vi.hoisted(() => ({
path: "",
hold: undefined as ((handle: FileHandle) => Promise<void>) | undefined,
}));
it.each([null, "cancel file read", { source: "caller" }])(
"preserves an owned file-read cancellation through project profile resolution: %j",
vi.mock("node:fs/promises", async (importOriginal) => {
const original = await importOriginal<typeof import("node:fs/promises")>();
return {
...original,
open: async (...args: Parameters<typeof original.open>) => {
const handle = await original.open(...args);
const hold =
args[0] === projectFileClose.path ? projectFileClose.hold : undefined;
if (hold === undefined) return handle;
const close = handle.close.bind(handle);
handle.close = async () => {
await hold(handle);
await close();
};
return handle;
},
};
});
it.each([null, { source: "caller" }])(
"preserves cancellation reason %j while closing the final project file",
async (reason) => {
const root = await createTestTempDirectory("rea-ghidra-read-cancel-");
await mkdir(join(root, "selected.rep"));
await writeFile(join(root, "selected.gpr"), "marker");
const root = await realpath(
await createTestTempDirectory("rea-ghidra-read-cancel-"),
);
const marker = join(root, "selected.gpr");
const data = join(root, "selected.rep");
const lastFile = join(data, "last");
await mkdir(data);
await writeFile(marker, "marker");
await writeFile(lastFile, "project data");
const resources = new ArtifactResourceScope();
fault.reason = reason;
const gate = phaseGate<FileHandle>();
const controller = new AbortController();
projectFileClose.path = lastFile;
projectFileClose.hold = gate.hold;
const pending = resolveGhidraProject(
{ path: marker },
{ path: join(root, "target") },
resources,
controller.signal,
);
try {
let failure: unknown;
try {
await resolveGhidraProject(
{ path: join(root, "selected.gpr") },
{ path: join(root, "target") },
resources,
);
} catch (cause) {
failure = cause;
}
expect(failure).toBeInstanceOf(AnalysisCancelledError);
if (!(failure instanceof AnalysisCancelledError))
throw new Error("Expected cancellation");
expect(failure.cause).toBe(reason);
const handle = await gate.reached(pending, "final project file close");
expect(handle.fd).toBeGreaterThanOrEqual(0);
controller.abort(reason);
expect(
await Promise.race([
pending.then(
() => "settled",
() => "settled",
),
setImmediate("held"),
]),
).toBe("held");
gate.release();
await expect(pending).rejects.toBeInstanceOf(AnalysisCancelledError);
await expect(pending).rejects.toMatchObject({
operation: "resolve_analysis_profile",
cause: reason,
});
expect(handle.fd).toBe(-1);
} finally {
gate.release();
await pending.catch(() => undefined);
projectFileClose.hold = undefined;
await resources.close();
}
},