perf(ghidra): fuse project snapshot I/O, parallelize language catalog, drop double validation, and add callTool progress heartbeats (#13310)

This commit is contained in:
morluto authored and GitHub committed 2026-11-22 08:46:18 +00:00
1 parent 2f171faa9f
commit 5b3ef76e4d
14 files changed
+847 -91

No files matched your search

+49 -18
View File
@@ -11,7 +11,10 @@ import { z } from "zod";
import type { Stats } from "node:fs";
import type { FileHandle } from "node:fs/promises";
import type { Socket } from "node:net";
import type { ProgressReporter } from "../ports/ProgressReporter.js";
import type {
ProgressReporter,
ProgressUpdate,
} from "../ports/ProgressReporter.js";
import {
AnalysisCancelledError,
@@ -311,7 +314,17 @@ export class GhidraClient {
progress?: ProgressReporter,
): Promise<GhidraStartResult> {
if (progress !== undefined)
return this.#reportStartupWait(this.start(signal), signal, progress);
return this.#withProgressHeartbeat(this.start(signal), {
intervalMs: 10_000,
signal,
progress,
createUpdate: (elapsedSeconds) => ({
phase: "ghidra_startup",
completed: 0,
total: null,
message: `Waiting for Ghidra startup (${String(elapsedSeconds)}s elapsed); import, auto-analysis and bridge readiness may still be pending`,
}),
});
if (signal?.aborted === true)
return Promise.resolve(err(this.#startupWaitCancellation(signal)));
if (this.#closePromise !== undefined)
@@ -384,11 +397,16 @@ export class GhidraClient {
return this.start(signal);
}
async #reportStartupWait(
started: Promise<GhidraStartResult>,
signal: AbortSignal | undefined,
progress: ProgressReporter,
): Promise<GhidraStartResult> {
async #withProgressHeartbeat<Value>(
pending: Promise<Value>,
options: {
readonly intervalMs: number;
readonly signal: AbortSignal | undefined;
readonly progress: ProgressReporter;
readonly createUpdate: (elapsedSeconds: number) => ProgressUpdate;
},
): Promise<Value> {
const { intervalMs, signal, progress, createUpdate } = options;
const startedAt = performance.now();
let active = true;
let reporting = false;
@@ -398,21 +416,18 @@ export class GhidraClient {
void Promise.resolve()
.then(() => {
if (!active || signal?.aborted) return;
return progress.report({
phase: "ghidra_startup",
completed: 0,
total: null,
message: `Waiting for Ghidra startup (${String(Math.floor((performance.now() - startedAt) / 1000))}s elapsed); import, auto-analysis and bridge readiness may still be pending`,
});
return progress.report(
createUpdate(Math.floor((performance.now() - startedAt) / 1000)),
);
})
// Notification failure does not release the owned startup process.
// Notification failure does not release or alter the owned Ghidra work.
.catch(() => {})
.finally(() => {
reporting = false;
});
}, 10_000);
}, intervalMs);
try {
return await started;
return await pending;
} finally {
active = false;
clearInterval(timer);
@@ -454,7 +469,10 @@ export class GhidraClient {
callToolIfReady(
operation: GhidraOperation,
parameters: Readonly<Record<string, JsonValue>>,
options: { readonly signal?: AbortSignal } = {},
options: {
readonly signal?: AbortSignal;
readonly progress?: ProgressReporter;
} = {},
): Promise<Result<JsonValue, GhidraSessionError> | undefined> {
if (!this.isReady()) return Promise.resolve(undefined);
return this.#callTool(operation, parameters, options);
@@ -479,6 +497,7 @@ export class GhidraClient {
parameters: Readonly<Record<string, JsonValue>>,
options: {
readonly signal?: AbortSignal;
readonly progress?: ProgressReporter;
readonly decompileTimeoutSeconds?: number | null;
readonly decompileMaxPayloadMiB?: number | null;
readonly valueFlowLimits?: NativeValueFlowLimits;
@@ -491,7 +510,7 @@ export class GhidraClient {
typeof parameters.pattern === "string"
? parameters.pattern
: undefined;
return this.#enqueue(
const pending = this.#enqueue(
operation,
pattern !== undefined
? {
@@ -512,6 +531,18 @@ export class GhidraClient {
: { decompileMaxPayloadMiB: options.decompileMaxPayloadMiB }),
},
);
if (options.progress === undefined) return pending;
return this.#withProgressHeartbeat(pending, {
intervalMs: 5_000,
signal: options.signal,
progress: options.progress,
createUpdate: (elapsedSeconds) => ({
phase: "ghidra_operation",
completed: 0,
total: null,
message: `Waiting for Ghidra ${operation} (${String(elapsedSeconds)}s elapsed); bridge analysis may still be pending`,
}),
});
}
/** Read the private immutable source for format parsers that require captured bytes. */
+80 -1
View File
@@ -1,4 +1,6 @@
import { GhidraAdmissionError } from "./GhidraAdmissionError.js";
import type { Hash } from "node:crypto";
import { constants } from "node:fs";
import { open } from "node:fs/promises";
import {
type ArtifactResourceScope,
@@ -20,7 +22,10 @@ import {
AnalysisArtifactChangedError,
AnalysisResourceConstraintError,
} from "../domain/analysisErrorCore.js";
import { RegularFileChangedError } from "../filesystem/RegularFile.js";
import {
RegularFileChangedError,
sameRegularFileState,
} from "../filesystem/RegularFile.js";
import { ProviderAdapterError } from "../domain/providerAdapterError.js";
import { ProviderCleanupError } from "../domain/providerCleanupError.js";
import { analysisErrorWithCleanupDependencies } from "../domain/analysisErrorCleanup.js";
@@ -58,6 +63,80 @@ export const writeGhidraProfileArtifact = async (
);
};
const STREAM_COPY_BUFFER_BYTES = 256 * 1024;
/** Single-pass regular-file copy with optional SHA-256 streaming and descriptor ownership. */
export const copyGhidraRegularFile = async (
sourcePath: string,
destinationPath: string,
resources: ArtifactResourceScope,
options: {
readonly signal?: AbortSignal | undefined;
readonly buffer?: Buffer | undefined;
readonly hash?: Hash | undefined;
readonly onOpenedSource?: ((initialSize: number) => void) | undefined;
} = {},
): Promise<void> => {
const { signal, hash, onOpenedSource } = options;
const scratch =
options.buffer ?? Buffer.allocUnsafe(STREAM_COPY_BUFFER_BYTES);
await withArtifactRegularFile(
sourcePath,
resources,
signal,
async ({ handle: srcHandle, initial }) => {
onOpenedSource?.(initial.size);
assertArtifactReadActive(signal);
const destHandle = await open(
destinationPath,
constants.O_CREAT |
constants.O_EXCL |
constants.O_WRONLY |
(constants.O_NOFOLLOW ?? 0),
0o600,
);
await withArtifactFileHandle(
destinationPath,
destHandle,
resources,
signal,
async (dest) => {
for (let offset = 0; offset < initial.size;) {
assertArtifactReadActive(signal);
const { bytesRead } = await srcHandle.read(
scratch,
0,
Math.min(scratch.length, initial.size - offset),
offset,
);
if (bytesRead === 0) throw new RegularFileChangedError(sourcePath);
hash?.update(scratch.subarray(0, bytesRead));
for (let written = 0; written < bytesRead;) {
assertArtifactReadActive(signal);
const { bytesWritten } = await dest.write(
scratch,
written,
bytesRead - written,
offset + written,
);
if (bytesWritten === 0)
throw new Error(
`Short write copying artifact to ${destinationPath}`,
);
written += bytesWritten;
}
offset += bytesRead;
}
assertArtifactReadActive(signal);
if (!sameRegularFileState(initial, await srcHandle.stat()))
throw new RegularFileChangedError(sourcePath);
},
);
},
"reject",
);
};
/** Ghidra's typed meaning for one physical file failure, else the failure. */
const ghidraPhysicalFailure = (
primary: unknown,
+4 -6
View File
@@ -36,11 +36,7 @@ import {
swiftLargeStringLiteralOmissionSchema,
} from "../domain/native/swiftStringLiteral.js";
import { functionBodyEntryAgrees } from "../domain/native/functionBody.js";
import {
jsonObjectSchema,
jsonValueSchema,
type JsonValue,
} from "../domain/jsonValue.js";
import { jsonObjectSchema, type JsonValue } from "../domain/jsonValue.js";
import type { EvidenceLocation } from "../domain/evidence.js";
import {
relationshipCoverageSchema,
@@ -425,7 +421,9 @@ export const parseGhidraFunctionResult = (
const parsed = resultSchemas[operation].safeParse(observation.value);
return parsed.success
? ok({
value: jsonValueSchema.parse(parsed.data),
// `observation.value` comes from an admitted JsonValue and `resultSchemas[operation]`
// outputs fresh plain objects/arrays whose fields are all JSON-safe.
value: parsed.data as JsonValue,
limitations: observation.limitations,
...(observation.cache_policy === undefined
? {}
+4 -2
View File
@@ -32,7 +32,7 @@ import {
functionBodyEntryAgrees,
} from "../domain/native/functionBody.js";
import { procedureIdentitySchema } from "../domain/native/procedureInfo.js";
import { jsonValueSchema, type JsonValue } from "../domain/jsonValue.js";
import type { JsonValue } from "../domain/jsonValue.js";
import { err, ok, type Result } from "../domain/result.js";
import { analysisInputErrorFromIssues } from "../domain/inputIssueProjection.js";
@@ -400,7 +400,9 @@ export function parseGhidraInventoryResult(
const parsed = resultSchemas[operation].safeParse(value);
return parsed.success
? ok({
value: jsonValueSchema.parse(parsed.data),
// `value` was already admitted as JsonValue and `resultSchemas[operation]`
// outputs fresh plain objects/arrays whose fields are all JSON-safe.
value: parsed.data as JsonValue,
// The overview omits detailed segment permissions, sections and provenance.
// Load-image observations above undergo separate local attestation.
...(operation === "read_binary_inventory_summary"
+123 -26
View File
@@ -4,7 +4,11 @@ import { parseXmlDocument } from "../domain/xmlDocument.js";
import { decodeXmlPlistText } from "../domain/propertyListXmlText.js";
import {
ArtifactFileFailureGroup,
ArtifactReaderFailure,
type ArtifactResourceScope,
artifactPrimaryCleanupLeases,
assertArtifactReadActive,
withArtifactRegularFile,
} from "../resources/index.js";
import type { GhidraLanguageOverride } from "../config/ghidraLanguageOverride.js";
@@ -22,6 +26,7 @@ export interface GhidraLanguageDefinition {
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;
const CATALOG_CONCURRENCY = 8;
/** Parse the `<language>` elements of one `.ldefs` document. */
export const parseGhidraLanguageDefinitions = (
@@ -99,6 +104,108 @@ const readLanguageDefinitionFile = (
"follow",
);
const mergeCatalogFailures = (
failures: readonly { readonly index: number; readonly cause: unknown }[],
): unknown => {
const ordered = [...failures].sort((left, right) => left.index - right.index);
const primary = ordered[0]!.cause;
const siblingCleanups = ordered
.slice(1)
.flatMap(({ cause }) =>
cause instanceof ArtifactReaderFailure && cause.cleanup !== undefined
? [cause]
: [],
);
if (siblingCleanups.length === 0) return primary;
const primaryLeases = artifactPrimaryCleanupLeases(primary);
const siblingLeases = siblingCleanups.map(artifactPrimaryCleanupLeases);
const cleanupLeases =
primaryLeases === undefined || siblingLeases.includes(undefined)
? undefined
: [
...new Set([
...primaryLeases,
...siblingLeases.flatMap((leases) => leases ?? []),
]),
];
return new ArtifactFileFailureGroup(
primary,
{
reason: siblingCleanups.map(({ cleanup }) => cleanup!.reason).join("; "),
resources: [
...new Set(
siblingCleanups.flatMap(({ cleanup }) => cleanup!.resources),
),
],
},
cleanupLeases,
);
};
const runBoundedWorkers = async (
count: number,
concurrency: number,
work: (index: number) => Promise<void>,
): Promise<void> => {
if (count === 0) return;
let nextIndex = 0;
let stopped = false;
const failures: Array<{ readonly index: number; readonly cause: unknown }> =
[];
await Promise.all(
Array.from({ length: Math.min(concurrency, count) }, async () => {
while (!stopped) {
const index = nextIndex++;
if (index >= count) return;
try {
await work(index);
} catch (cause: unknown) {
stopped = true;
failures.push({ index, cause });
return;
}
}
}),
);
if (failures.length > 0) throw mergeCatalogFailures(failures);
};
const discoverLanguageDefinitionFiles = async (
directories: readonly string[],
signal: AbortSignal | undefined,
): Promise<string[]> => {
const slots: string[][] = Array.from(
{ length: directories.length },
() => [],
);
await runBoundedWorkers(
directories.length,
CATALOG_CONCURRENCY,
async (index) => {
assertArtifactReadActive(signal);
const directory = directories[index]!;
let entries: string[];
try {
entries = await readdir(directory);
} catch (cause: unknown) {
// A module may contain no language directory; inability to read one is not absence.
if (
cause instanceof Error &&
"code" in cause &&
(cause.code === "ENOENT" || cause.code === "ENOTDIR")
)
return;
throw cause;
}
const ldefs: string[] = [];
for (const entry of entries.sort())
if (entry.endsWith(".ldefs")) ldefs.push(join(directory, entry));
slots[index] = ldefs;
},
);
return slots.flat();
};
/**
* Read every language definition shipped by one Ghidra installation. Admission
* first retries cleanup the scope retains, so an unconfirmed close blocks reads
@@ -110,33 +217,23 @@ export const readGhidraLanguageCatalog = (
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 (cause: unknown) {
// A module may contain no language directory; inability to read one is not absence.
if (
cause instanceof Error &&
"code" in cause &&
(cause.code === "ENOENT" || cause.code === "ENOTDIR")
)
continue;
throw cause;
}
for (const entry of entries.sort()) {
if (!entry.endsWith(".ldefs")) continue;
definitions.push(
...(await readLanguageDefinitionFile(
join(directory, entry),
resources,
signal,
)),
const directories = await languageDirectories(installDir);
const files = await discoverLanguageDefinitionFiles(directories, signal);
const results: Array<readonly GhidraLanguageDefinition[]> = new Array(
files.length,
);
await runBoundedWorkers(
files.length,
CATALOG_CONCURRENCY,
async (index) => {
results[index] = await readLanguageDefinitionFile(
files[index]!,
resources,
signal,
);
}
}
return definitions;
},
);
return results.flat();
});
/**
+73
View File
@@ -509,3 +509,76 @@ it
}
},
);
describe("Ghidra concurrent language catalog", () => {
it("preserves sorted module and entry order across >8 modules with missing language dirs", async () => {
const root = await createTestTempDirectory("rea-ghidra-catalog-many-");
const expectedIds: string[] = [];
for (let index = 24; index >= 0; index -= 1) {
const module = `M_${String(index).padStart(2, "0")}`;
const modDir = join(root, "Ghidra/Processors", module);
if (index % 5 === 0) {
await mkdir(modDir, { recursive: true });
continue;
}
const languages = join(modDir, "data/languages");
await mkdir(languages, { recursive: true });
for (const part of ["b", "a"]) {
const id = `${module}_${part}:LE:32:default`;
await writeFile(
join(languages, `${part}.ldefs`),
`<language_definitions><language id="${id}"><compiler id="default"/></language></language_definitions>`,
);
}
}
for (let index = 0; index < 25; index += 1) {
if (index % 5 === 0) continue;
const module = `M_${String(index).padStart(2, "0")}`;
expectedIds.push(
`${module}_a:LE:32:default`,
`${module}_b:LE:32:default`,
);
}
const resources = new ArtifactResourceScope();
try {
const catalog = await readGhidraLanguageCatalog(root, resources);
expect(catalog.map(({ id }) => id)).toEqual(expectedIds);
} finally {
await resources.close();
}
});
it.skipIf(process.platform === "win32" || process.getuid?.() === 0)(
"rethrows the lowest-index directory failure when multiple concurrent directories fail",
async () => {
const root = await createTestTempDirectory("rea-ghidra-catalog-order-");
const dirs: string[] = [];
for (let index = 0; index < 12; index += 1) {
const languages = join(
root,
"Ghidra/Processors",
`P_${String(index).padStart(2, "0")}`,
"data/languages",
);
await mkdir(languages, { recursive: true });
await writeFile(
join(languages, "arch.ldefs"),
`<language_definitions><language id="P${index}:LE:32:default"/></language_definitions>`,
);
dirs.push(languages);
}
await chmod(dirs[2]!, 0);
await chmod(dirs[9]!, 0);
const resources = new ArtifactResourceScope();
try {
await expect(
readGhidraLanguageCatalog(root, resources),
).rejects.toMatchObject({ code: "EACCES", path: dirs[2] });
} finally {
await chmod(dirs[2]!, 0o755);
await chmod(dirs[9]!, 0o755);
await resources.close();
}
},
);
});
+27 -13
View File
@@ -3,11 +3,15 @@ import {
processInspectionFailure,
retainProcessInspectionCleanup,
} from "../providers/OwnedCommandCleanup.js";
import { classifyProviderFailure } from "../providers/classifyProviderFailure.js";
import { createHash } from "node:crypto";
import { HOST_PLATFORM } from "../platform/HostPlatform.js";
import { GhidraAdmissionError } from "./GhidraAdmissionError.js";
import {
copyGhidraRegularFile,
ghidraFileDialect,
} from "./GhidraFileArtifacts.js";
import { copyExistingGhidraProject } from "./GhidraProjectSnapshot.js";
import { hashGhidraPackedProgram } from "./GhidraCheckpoint.js";
import { constants as fsConstants } from "node:fs";
import type { ArtifactResourceScope } from "../resources/index.js";
import { GHIDRA_BRIDGE_SOURCES } from "./GhidraBridgeSources.js";
import {
@@ -17,7 +21,7 @@ import {
import type { GhidraLanguageOverride } from "../config/ghidraLanguageOverride.js";
import type { GhidraRiscvCallingConvention } from "./GhidraRiscvProfile.js";
import { snapshotEnvironment } from "../process/snapshotEnvironment.js";
import { copyFile, mkdir, realpath } from "node:fs/promises";
import { mkdir, realpath } from "node:fs/promises";
import { basename, dirname, join, posix, win32 } from "node:path";
import { writeGhidraRuntimeFile } from "./GhidraRuntimeFile.js";
@@ -347,18 +351,27 @@ export class GhidraHeadlessLauncher implements GhidraLauncher {
let packedProgramPath: string | undefined;
if (session.packedProgram !== undefined) {
packedProgramPath = join(session.runtimeRoot, "restored-program.gzf");
await copyFile(
session.packedProgram.path,
packedProgramPath,
fsConstants.COPYFILE_EXCL,
);
if (
(await hashGhidraPackedProgram(
const packedHash = createHash("sha256");
try {
await copyGhidraRegularFile(
session.packedProgram.path,
packedProgramPath,
options.resourceScope,
options.signal,
)) !== session.packedProgram.sha256
)
{
signal: options.signal,
hash: packedHash,
},
);
} catch (cause: unknown) {
if (cause instanceof AnalysisError) throw cause;
throw classifyProviderFailure(
cause,
ghidraFileDialect("open_binary", {
path: session.packedProgram.path,
}),
);
}
if (packedHash.digest("hex") !== session.packedProgram.sha256)
throw new GhidraLaunchError(
"Ghidra checkpoint changed before its private import; reopen the target.",
);
@@ -1096,6 +1109,7 @@ export const ghidraHeadlessArguments = (
options.disabledAnalyzers.join(","),
]),
...(existing !== undefined ||
options.packedProgramPath !== undefined ||
(options.platform ?? HOST_PLATFORM.platform) === "win32"
? []
: [
+81 -22
View File
@@ -1,6 +1,9 @@
import { AnalysisError } from "../domain/analysisErrorBase.js";
import { classifyProviderFailure } from "../providers/classifyProviderFailure.js";
import { ghidraFileDialect } from "./GhidraFileArtifacts.js";
import {
copyGhidraRegularFile,
ghidraFileDialect,
} from "./GhidraFileArtifacts.js";
import { HOST_PLATFORM } from "../platform/HostPlatform.js";
import type { BinaryTarget } from "../domain/binaryTargetTypes.js";
import { createHash } from "node:crypto";
@@ -240,6 +243,65 @@ const pathsOverlap = (first: string, second: string): boolean => {
return contains(first, second) || contains(second, first);
};
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. */
export const copyExistingGhidraProject = async (
sourcePath: string,
@@ -277,6 +339,24 @@ 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;
}
await visitProject(
source,
projectName,
@@ -293,26 +373,5 @@ export const copyExistingGhidraProject = async (
},
signal,
);
if (expectedSha256 !== undefined) {
if (resources === undefined)
throw selectionFailure(
"Existing project verification requires an owned resource scope.",
);
if (
(await fingerprintGhidraProject(
destinationRoot,
projectName,
resources,
signal,
)) !== 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,
);
}
});
};
+45 -1
View File
@@ -23,7 +23,10 @@ import {
AnalysisCleanupLease,
AnalysisCleanupLeaseGroup,
} from "./AnalysisCleanupLease.js";
import type { AnalysisError } from "../domain/analysisErrorBase.js";
import type {
AnalysisCleanupObservation,
AnalysisError,
} from "../domain/analysisErrorBase.js";
import type { ArtifactLimitBoundary } from "../domain/artifactOperationError.js";
import { ParseFailureError, type LimitRef } from "../domain/parseFailure.js";
import { errorMessage } from "../kernel/errorMessage.js";
@@ -102,6 +105,35 @@ export class ArtifactFileCleanupFailure<
}
}
/** A primary file failure with unresolved cleanup from sibling operations. */
export class ArtifactFileFailureGroup extends ArtifactReaderFailure {
constructor(
readonly primary: unknown,
readonly siblingCleanup: AnalysisCleanupObservation,
leases: readonly AnalysisCleanupLease[] | undefined,
) {
const report = ArtifactReaderFailure.withCleanup(
primary,
siblingCleanup,
undefined,
leases,
);
super(
report.reason,
report.message,
{
...report.primaryFacts(),
cause: primary,
cleanup: report.cleanup,
cleanupLeases: report.cleanupLeases,
partialObservation: report.partialObservation,
cancellation: report.cancellation,
},
report.details,
);
}
}
/** Errnos raised while the caller-selected artifact path is being resolved. */
export type ArtifactSelectedPathErrno =
| "ENOENT"
@@ -133,6 +165,16 @@ export const mapArtifactFileFailure = (
cause: unknown,
classify: (cause: unknown) => unknown,
): unknown => {
if (cause instanceof ArtifactFileFailureGroup) {
const primary = mapArtifactFileFailure(cause.primary, classify);
return Object.is(primary, cause.primary)
? cause
: new ArtifactFileFailureGroup(
primary,
cause.siblingCleanup,
cause.cleanupLeases,
);
}
if (!(cause instanceof ArtifactFileCleanupFailure)) return classify(cause);
const physical = cause.fileCleanupFailure;
if (physical.outcome.kind !== "failed") return cause;
@@ -160,6 +202,8 @@ export interface ArtifactFilePrimaryFacts {
export const artifactFilePrimaryFacts = (
cause: unknown,
): ArtifactFilePrimaryFacts => {
if (cause instanceof ArtifactFileFailureGroup)
return artifactFilePrimaryFacts(cause.primary);
while (cause instanceof ArtifactFileCleanupFailure) {
const physical = cause.fileCleanupFailure;
if (physical.outcome.kind !== "failed") break;
+1
View File
@@ -29,6 +29,7 @@ export { translateArtifactFailure } from "./ArtifactOperationFailure.js";
export {
ArtifactFileCancelled,
ArtifactFileCleanupFailure,
ArtifactFileFailureGroup,
artifactFileCancellationCause,
artifactFileCompletion,
artifactFilePrimaryFacts,
@@ -7,6 +7,9 @@ import {
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";
@@ -16,6 +19,7 @@ interface FileControl {
synchronizedClose: boolean;
invalidateOnFailure: boolean;
readFails: boolean;
openDenied: boolean;
invalidated: boolean;
closeCalls: number;
opens: number;
@@ -25,13 +29,20 @@ interface FileControl {
// that releases synchronized closes only after all of them are pending.
const { controls, barrier } = vi.hoisted(() => {
const state = { expected: 0, arrived: 0, release: () => {} };
const gate = new Promise<void>((resolve) => {
let gate = new Promise<void>((resolve) => {
state.release = resolve;
});
return {
controls: new Map<string, FileControl>(),
barrier: {
state,
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();
@@ -45,8 +56,17 @@ vi.mock("node:fs/promises", async (importOriginal) => {
return {
...actual,
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);
const control = controls.get(basename(String(args[0])));
if (control === undefined) return real;
control.opens += 1;
let released = false;
@@ -89,6 +109,7 @@ const control = (name: string, overrides: Partial<FileControl> = {}) => {
synchronizedClose: false,
invalidateOnFailure: false,
readFails: false,
openDenied: false,
invalidated: false,
closeCalls: 0,
opens: 0,
@@ -258,3 +279,98 @@ it("retains an invalidated descriptor owner and keeps later reads blocked", asyn
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;
expect(
await readGhidraLanguageCatalog(await installation("x86"), resources),
).toEqual([{ id: "x86:LE:32:default", compilerSpecIds: [] }]);
expect(first.closeCalls).toBe(2);
expect(second.closeCalls).toBe(2);
expect(resources.hasPending).toBe(false);
expect(await readGhidraLanguageCatalog(root, resources)).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);
});
@@ -2734,3 +2734,70 @@ describe("GhidraClient reply ceiling", () => {
});
});
});
describe("GhidraClient operation progress heartbeats", () => {
it("skips progress reports on fast calls and emits 5s heartbeats until completion or abort", async () => {
const fastClient = clientFor(new FixtureLauncher());
await expect(fastClient.start()).resolves.toMatchObject({ ok: true });
const fastUpdates: ProgressUpdate[] = [];
await expect(
fastClient.callTool(
"list_strings",
{},
{
progress: {
report: async (update) => {
fastUpdates.push(update);
},
},
},
),
).resolves.toMatchObject({ ok: true });
expect(fastUpdates).toEqual([]);
const launcher = new FixtureLauncher("hang_tools");
const client = clientFor(launcher);
await expect(client.start()).resolves.toMatchObject({ ok: true });
vi.useFakeTimers({ toFake: ["setInterval", "clearInterval"] });
const controller = new AbortController();
const updates: ProgressUpdate[] = [];
const pending = client.callTool(
"analyze_function",
{ procedure: "0x1000" },
{
signal: controller.signal,
progress: {
report: async (update) => {
updates.push(update);
throw new Error("notification sink unavailable");
},
},
},
);
await vi.advanceTimersByTimeAsync(4_999);
expect(updates).toEqual([]);
await vi.advanceTimersByTimeAsync(1);
expect(updates).toEqual([
expect.objectContaining({
phase: "ghidra_operation",
completed: 0,
total: null,
message: expect.stringContaining("Waiting for Ghidra analyze_function"),
}),
]);
await vi.advanceTimersByTimeAsync(5_000);
expect(updates).toHaveLength(2);
controller.abort("caller stopped");
await expect(pending).resolves.toMatchObject({
ok: false,
error: { kind: "cancelled" },
});
await vi.advanceTimersByTimeAsync(15_000);
expect(updates).toHaveLength(2);
});
});
@@ -1,3 +1,4 @@
import { createHash } from "node:crypto";
import { createTestArtifactResourceScope } from "../../../fixtures/artifactResourceScope.js";
import {
access,
@@ -1359,3 +1360,102 @@ describe("Ghidra GameCube DOL section file", () => {
},
);
});
describe("Ghidra checkpoint restore", () => {
it("skips auto-analysis and the no-return repair when restoring a packed checkpoint", () => {
const arguments_ = ghidraHeadlessArguments({
platform: "linux",
projectRoot: "/tmp/project",
targetPath: "/tmp/target",
packedProgramPath: "/tmp/runtime/restored-program.gzf",
bridgeScriptPath: "/package/bridge/ReaGhidraBridge.java",
descriptorPath: "/tmp/session.json",
ghidraLogPath: "/tmp/ghidra.log",
scriptLogPath: "/tmp/script.log",
});
expect(arguments_).toContain("-noanalysis");
expect(arguments_).toContain("-import");
expect(arguments_).toContain("/tmp/runtime/restored-program.gzf");
expect(arguments_).not.toContain(
"/package/bridge/ReaGhidraNoReturnFix.java",
);
expect(arguments_).toContain("/package/bridge/ReaGhidraBridge.java");
});
it.skipIf(process.platform === "win32")(
"copies and verifies packed checkpoints in one pass and rejects tampered bytes before spawn",
async () => {
const parent = await createTestTempDirectory("rea-packed-restore-");
const runtime = await createGhidraTestRuntime(parent);
runtimes.push(runtime);
const javaHome = await createFakeJavaHome(parent);
const packedSource = join(parent, "program.gzf");
const packedBytes = Buffer.alloc(300 * 1024, 0x47);
packedBytes[packedBytes.length - 1] = 0x5a;
await writeFile(packedSource, packedBytes);
const sha256 = createHash("sha256").update(packedBytes).digest("hex");
const spawned: OwnedProviderProcessSpawnOptions[] = [];
const launcher = new GhidraHeadlessLauncher({
environment: process.env,
analyzeHeadlessPath: fixturePath,
platform: "linux",
configurationDirectoryName: "ghidra_12.1.4_PUBLIC",
javaHome,
bridgeScriptPath: "/package/bridge/ReaGhidraBridge.java",
spawnProcess: async (options) => {
spawned.push(options);
return fakeSpawnedProcess(options.runId);
},
});
const launched = await launcher.launch(
{
runtimeRoot: runtime.path,
transport: "unix-socket",
endpointPath: join(runtime.path, "bridge.sock"),
token: "secret-token",
runId: "d6fcbb66-e829-4ff6-a535-0035aec63139",
targetPath: "/tmp/target",
targetSha256: "b".repeat(64),
providerVersion: "12.1.4",
profileDigest: "a".repeat(64),
packedProgram: { path: packedSource, sha256 },
},
{ resourceScope: createTestArtifactResourceScope() },
);
if (!launched.ok) throw launched.error;
try {
const restored = join(runtime.path, "restored-program.gzf");
expect((await readFile(restored)).equals(packedBytes)).toBe(true);
expect((await stat(restored)).mode & 0o777).toBe(0o600);
expect(spawned[0]?.arguments).toContain("-noanalysis");
expect(spawned[0]?.arguments).not.toContain(
"/package/bridge/ReaGhidraNoReturnFix.java",
);
} finally {
await launched.value.cleanup?.();
}
const tamperedRuntime = await createGhidraTestRuntime(parent);
runtimes.push(tamperedRuntime);
packedBytes[0] = (packedBytes[0] ?? 0) ^ 0xff;
await writeFile(packedSource, packedBytes);
const tampered = await launcher.launch(
{
runtimeRoot: tamperedRuntime.path,
transport: "unix-socket",
endpointPath: join(tamperedRuntime.path, "bridge.sock"),
token: "secret-token",
runId: "d6fcbb66-e829-4ff6-a535-0035aec63139",
targetPath: "/tmp/target",
targetSha256: "b".repeat(64),
providerVersion: "12.1.4",
profileDigest: "a".repeat(64),
packedProgram: { path: packedSource, sha256 },
},
{ resourceScope: createTestArtifactResourceScope() },
);
expect(tampered.ok).toBe(false);
expect(spawned).toHaveLength(1);
},
);
});
@@ -292,3 +292,78 @@ it.skipIf(process.platform === "win32")(
).rejects.toMatchObject({ _tag: "ConfigurationError" });
},
);
it("copies multi-chunk and empty files in one pass matching fingerprint parity and file modes", async () => {
const { source, destination } = await fixture();
const large = Buffer.alloc(256 * 1024 + 17, 0x41);
large[0] = 0x5a;
large[256 * 1024] = 0x7e;
await writeFile(join(source, "selected.rep", "data"), large);
await writeFile(join(source, "selected.rep", "empty"), Buffer.alloc(0));
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 readFile(join(destination, "selected.rep", "data"))).equals(large),
).toBe(true);
expect(
await readFile(join(destination, "selected.rep", "empty")),
).toHaveLength(0);
expect(
await fingerprintGhidraProject(destination, "selected", resources),
).toBe(commitment.sha256);
if (process.platform !== "win32") {
expect(
(await stat(join(destination, "selected.rep", "data"))).mode & 0o777,
).toBe(0o600);
expect(
(await stat(join(destination, "selected.rep", "empty"))).mode & 0o777,
).toBe(0o600);
expect((await stat(join(destination, "selected.rep"))).mode & 0o777).toBe(
0o700,
);
}
});
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) => {
const { source, destination } = await fixture();
const commitment = await resolveGhidraProject(
{ path: join(source, "selected.gpr"), programName: "target.elf" },
{ path: "/tmp/target.elf" },
resources,
);
const controller = new AbortController();
controller.abort(reason);
await expect(
copyExistingGhidraProject(source, destination, {
projectName: "selected",
expectedSha256: commitment.sha256,
resources,
signal: controller.signal,
}),
).rejects.toMatchObject({ _tag: "AnalysisCancelledError", cause: reason });
expect(await readdir(destination)).toEqual([]);
},
);