Skip to content

armgit / rea

Public Imported from GitHub
0

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

fix(ghidra): preserve load-image completion through cancellation

morluto9c56d09c0535
diff --git a/src/domain/analysisErrorBase.ts b/src/domain/analysisErrorBase.ts
index f4d599eac..4c4b0e071 100644
--- a/src/domain/analysisErrorBase.ts
+++ b/src/domain/analysisErrorBase.ts
@@ -232,11 +232,13 @@ import type { WebPageInspection } from "./browserObservationSchemas.js";
import type { WebExecution } from "./webExecution.js";
import type { WebEventListeners } from "./webEventListeners.js";
+import type { NativeLoadImagePartialObservation } from "./native/nativeLoadImage.js";
import type { NativeAotSnapshotObservation } from "./native/nativeAotSnapshotObservation.js";
import type { FileSnapshotPartialObservation } from "./fileSnapshotObservation.js";
/** Provider-neutral evidence collected before a typed analysis failure. */
export type AnalysisPartialObservation =
+ | NativeLoadImagePartialObservation
| NativeAotSnapshotObservation
| FileSnapshotPartialObservation
| PartialProcessCaptureObservation
diff --git a/src/domain/native/nativeLoadImage.ts b/src/domain/native/nativeLoadImage.ts
index a4efc2847..4927702a3 100644
--- a/src/domain/native/nativeLoadImage.ts
+++ b/src/domain/native/nativeLoadImage.ts
@@ -136,3 +136,23 @@ export type NativeLoadImageObservation = z.infer<
>;
/** One independently compared native import fact. */
export type NativeLoadImageCheck = z.infer<typeof nativeLoadImageCheckSchema>;
+
+/** Measured provider facts, or a completed comparison retained after interruption. */
+export const nativeLoadImagePartialObservationSchema = z.discriminatedUnion(
+ "stage",
+ [
+ z.strictObject({
+ kind: z.literal("native-load-image"),
+ stage: z.literal("measured"),
+ observations: nativeLoadImageObservationSchema,
+ }),
+ z.strictObject({
+ kind: z.literal("native-load-image"),
+ stage: z.literal("completed"),
+ result: nativeLoadImageSchema,
+ }),
+ ],
+);
+export type NativeLoadImagePartialObservation = z.infer<
+ typeof nativeLoadImagePartialObservationSchema
+>;
diff --git a/src/ghidra/GhidraInventoryValues.ts b/src/ghidra/GhidraInventoryValues.ts
index f4faa1a12..1d8fff19e 100644
--- a/src/ghidra/GhidraInventoryValues.ts
+++ b/src/ghidra/GhidraInventoryValues.ts
@@ -4,7 +4,10 @@ import {
validateBytePattern,
byteSearchResultSchema,
} from "../domain/native/bytePattern.js";
-import { nativeLoadImageObservationSchema } from "../domain/native/nativeLoadImage.js";
+import {
+ nativeLoadImageObservationSchema,
+ type NativeLoadImageObservation,
+} from "../domain/native/nativeLoadImage.js";
import {
type AnalysisInputError,
@@ -355,18 +358,36 @@ const resultSchemas = {
} satisfies Readonly<Record<GhidraInventoryOperation, z.ZodType>>;
/** Validate exact Java-bridge output before creating Evidence. */
-export const parseGhidraInventoryResult = (
+export function parseGhidraInventoryResult(
+ operation: "inspect_native_load_image",
+ value: JsonValue,
+): Result<NativeLoadImageObservation, AnalysisOutputError>;
+export function parseGhidraInventoryResult(
+ operation: GhidraInventoryOperation,
+ value: JsonValue,
+): Result<JsonValue, AnalysisOutputError>;
+export function parseGhidraInventoryResult(
operation: GhidraInventoryOperation,
value: JsonValue,
-): Result<JsonValue, AnalysisOutputError> => {
+): Result<JsonValue | NativeLoadImageObservation, AnalysisOutputError> {
+ if (operation === "inspect_native_load_image") {
+ const parsed = resultSchemas.inspect_native_load_image.safeParse(value);
+ return parsed.success
+ ? ok(parsed.data)
+ : err(inventoryOutputFailure(operation, parsed.error));
+ }
const parsed = resultSchemas[operation].safeParse(value);
return parsed.success
? ok(jsonValueSchema.parse(parsed.data))
- : err(
- new AnalysisOutputError(
- operation,
- "Ghidra bridge output did not match the inventory contract",
- { cause: parsed.error },
- ),
- );
-};
+ : err(inventoryOutputFailure(operation, parsed.error));
+}
+
+const inventoryOutputFailure = (
+ operation: GhidraInventoryOperation,
+ cause: unknown,
+): AnalysisOutputError =>
+ new AnalysisOutputError(
+ operation,
+ "Ghidra bridge output did not match the inventory contract",
+ { cause },
+ );
diff --git a/src/ghidra/GhidraLoadImageAttest.test.ts b/src/ghidra/GhidraLoadImageAttest.test.ts
new file mode 100644
index 000000000..bc5ba2343
--- /dev/null
+++ b/src/ghidra/GhidraLoadImageAttest.test.ts
@@ -0,0 +1,247 @@
+import {
+ nativeAotPeFixture,
+ nativeAotPeDigest,
+} from "../../tests/fixtures/nativeaotPe.js";
+import {
+ parseNativeAotPe,
+ NATIVE_AOT_MAX_REPORT_BYTES,
+} from "../domain/native/nativeAotPe.js";
+import { expect, it, vi } from "vitest";
+import type { BinaryTarget } from "../domain/binaryTargetTypes.js";
+import { err, ok } from "../domain/result.js";
+import { ProviderAdapterError } from "../domain/providerAdapterError.js";
+import {
+ nativeLoadImageSchema,
+ nativeLoadImagePartialObservationSchema,
+} from "../domain/native/nativeLoadImage.js";
+import {
+ fixtureDosLoadImage,
+ fixtureDosComLoadImage,
+} from "./GhidraLoadImage.fixture.js";
+import { fixtureRawBinaryLoadImage } from "./GhidraRawBinaryLoadImage.fixture.js";
+import { attestGhidraNativeLoadImage } from "./GhidraLoadImageAttest.js";
+import { GhidraSessionError } from "./GhidraSessionError.js";
+
+const dosFixture = (format: "dos-mz" | "dos-com") => {
+ const fixture =
+ format === "dos-mz" ? fixtureDosLoadImage() : fixtureDosComLoadImage();
+ const target: BinaryTarget = {
+ path: "/controlled/load-image",
+ sha256: fixture.sha256,
+ kind: "executable",
+ format,
+ architecture: "x86",
+ availableArchitectures: ["x86"],
+ };
+ return { ...fixture, target };
+};
+
+const fixtureFor = (format: "dos-mz" | "dos-com" | "raw-binary") =>
+ format === "raw-binary" ? fixtureRawBinaryLoadImage() : dosFixture(format);
+
+it.each(["dos-mz", "dos-com", "raw-binary"] as const)(
+ "retains completed %s verification under late cancellation",
+ async (format) => {
+ const fixture = fixtureFor(format);
+ const caller = new AbortController();
+ const reason = { caller: "snapshot result consumption" };
+ const result = await attestGhidraNativeLoadImage({
+ operation: "inspect_native_load_image",
+ target: fixture.target,
+ measured: fixture.observation,
+ client:
+ "bytes" in fixture
+ ? {
+ readTargetSnapshot: async () => {
+ caller.abort(reason);
+ return ok({ kind: "captured", bytes: fixture.bytes });
+ },
+ }
+ : {
+ hashTargetSnapshot: async () => {
+ caller.abort(reason);
+ return ok(fixture.snapshot);
+ },
+ },
+ mapSessionError: (cause) =>
+ new ProviderAdapterError("ghidra", "inspect_native_load_image", {
+ cause,
+ }),
+ signal: caller.signal,
+ });
+ if (result.ok)
+ throw new Error("Expected cancellation after snapshot completion");
+ expect(result.error).toMatchObject({
+ _tag: "AnalysisCancelledError",
+ cause: reason,
+ });
+ expect(result.error.cause).toBe(reason);
+ expect(
+ nativeLoadImagePartialObservationSchema.parse(
+ result.error.partialObservation,
+ ),
+ ).toMatchObject({
+ kind: "native-load-image",
+ stage: "completed",
+ result: { status: "verified", format, observations: fixture.observation },
+ });
+ },
+);
+
+it.each([null, "caller stopped", new Error("caller stopped")])(
+ "preserves an already-cancelled caller's reason and measured facts (%s)",
+ async (reason) => {
+ const fixture = dosFixture("dos-mz");
+ const caller = new AbortController();
+ caller.abort(reason);
+ const read = vi.fn();
+ const result = await attestGhidraNativeLoadImage({
+ operation: "inspect_native_load_image",
+ target: fixture.target,
+ measured: fixture.observation,
+ client: { readTargetSnapshot: read },
+ mapSessionError: () => {
+ throw new Error("No source failure expected");
+ },
+ signal: caller.signal,
+ });
+ if (result.ok) throw new Error("Expected cancellation");
+ expect(result.error.cause).toBe(reason);
+ expect(
+ nativeLoadImagePartialObservationSchema.parse(
+ result.error.partialObservation,
+ ),
+ ).toMatchObject({
+ kind: "native-load-image",
+ observations: fixture.observation,
+ stage: "measured",
+ });
+ expect(read).not.toHaveBeenCalled();
+ },
+);
+
+it("preserves a snapshot failure before late cancellation", async () => {
+ const fixture = dosFixture("dos-mz");
+ const caller = new AbortController();
+ const source = new GhidraSessionError("protocol", "controlled read failure");
+ const projected = new ProviderAdapterError(
+ "ghidra",
+ "inspect_native_load_image",
+ { cause: source },
+ );
+ const result = await attestGhidraNativeLoadImage({
+ operation: "inspect_native_load_image",
+ target: fixture.target,
+ measured: fixture.observation,
+ client: {
+ readTargetSnapshot: async () => {
+ caller.abort("late caller");
+ return err(source);
+ },
+ },
+ mapSessionError: () => projected,
+ signal: caller.signal,
+ });
+ expect(result).toEqual(err(projected));
+});
+
+it("keeps ordinary DOS verification valid", async () => {
+ const fixture = dosFixture("dos-mz");
+ const result = await attestGhidraNativeLoadImage({
+ operation: "inspect_native_load_image",
+ target: fixture.target,
+ measured: fixture.observation,
+ client: {
+ readTargetSnapshot: async () =>
+ ok({ kind: "captured", bytes: fixture.bytes }),
+ },
+ mapSessionError: () => {
+ throw new Error("No source failure expected");
+ },
+ });
+ if (!result.ok) throw result.error;
+ expect(nativeLoadImageSchema.parse(result.value).status).toBe("verified");
+});
+
+it("retains completed NativeAOT facts when cancellation precedes result consumption", async () => {
+ const bytes = nativeAotPeFixture();
+ const sha256 = nativeAotPeDigest(bytes);
+ const observations = {
+ ...fixtureDosLoadImage().observation,
+ image_base: "0x140000000",
+ };
+ const target: BinaryTarget = {
+ path: "/controlled/Inert.exe",
+ sha256,
+ kind: "executable",
+ format: "pe",
+ architecture: "x86_64",
+ availableArchitectures: ["x86_64"],
+ peMachine: 0x8664,
+ managed: false,
+ executableRole: "application",
+ };
+ const caller = new AbortController();
+ const reason = { caller: "already derived metadata" };
+ caller.abort(reason);
+ const result = await attestGhidraNativeLoadImage({
+ target,
+ operation: "inspect_native_load_image",
+ measured: observations,
+ client: {},
+ nativeAotResult: parseNativeAotPe(
+ bytes,
+ sha256,
+ NATIVE_AOT_MAX_REPORT_BYTES,
+ observations.image_base,
+ ),
+ mapSessionError: () => {
+ throw new Error("No source call expected");
+ },
+ signal: caller.signal,
+ });
+ if (result.ok) throw new Error("Expected late NativeAOT cancellation");
+ expect(result.error.cause).toBe(reason);
+ expect(
+ nativeLoadImagePartialObservationSchema.parse(
+ result.error.partialObservation,
+ ),
+ ).toMatchObject({
+ kind: "native-load-image",
+ stage: "completed",
+ result: { observations: { metadata_recovery: [{ method_tables: 3 }] } },
+ });
+});
+
+it("keeps invalid NativeAOT output primary across cancellation", async () => {
+ const fixture = dosFixture("dos-mz");
+ const caller = new AbortController();
+ caller.abort("late caller");
+ const result = await attestGhidraNativeLoadImage({
+ target: {
+ ...fixture.target,
+ format: "pe",
+ peMachine: 0x14c,
+ managed: false,
+ executableRole: "application",
+ },
+ operation: "inspect_native_load_image",
+ measured: fixture.observation,
+ client: {},
+ mapSessionError: () => {
+ throw new Error("No source call expected");
+ },
+ signal: caller.signal,
+ });
+ if (result.ok) throw new Error("Expected missing derivation failure");
+ expect(result.error._tag).toBe("ProviderAdapterError");
+ expect(
+ nativeLoadImagePartialObservationSchema.parse(
+ result.error.partialObservation,
+ ),
+ ).toMatchObject({
+ kind: "native-load-image",
+ stage: "measured",
+ observations: fixture.observation,
+ });
+});
diff --git a/src/ghidra/GhidraLoadImageAttest.ts b/src/ghidra/GhidraLoadImageAttest.ts
index b61cd4c3b..232d7b496 100644
--- a/src/ghidra/GhidraLoadImageAttest.ts
+++ b/src/ghidra/GhidraLoadImageAttest.ts
@@ -1,11 +1,12 @@
+import { jsonValueSchema } from "../domain/jsonValue.js";
import type { AnalysisOperation } from "../application/AnalysisProvider.js";
import { AnalysisCancelledError } from "../domain/analysisErrorCore.js";
import type { BinaryTarget } from "../domain/binaryTargetTypes.js";
import type { AnalysisError } from "../domain/analysisErrorBase.js";
-import { jsonValueSchema, type JsonValue } from "../domain/jsonValue.js";
import {
- nativeLoadImageObservationSchema,
nativeLoadImageSchema,
+ type NativeLoadImage,
+ type NativeLoadImageObservation,
} from "../domain/native/nativeLoadImage.js";
import { ProviderAdapterError } from "../domain/providerAdapterError.js";
import { err, ok, type Result } from "../domain/result.js";
@@ -18,160 +19,164 @@ import type { NativeAotPeResult } from "../domain/native/nativeAotPe.js";
import type { GhidraClient } from "./GhidraClient.js";
import type { GhidraSessionError } from "./GhidraSessionError.js";
-type LoadImageSnapshotClient = Partial<
- Pick<GhidraClient, "hashTargetSnapshot" | "readTargetSnapshot">
->;
-
type NativeLoadImageAttestationInput = {
readonly target: BinaryTarget;
readonly operation: AnalysisOperation;
- readonly measured: JsonValue;
- readonly client: LoadImageSnapshotClient;
+ readonly measured: NativeLoadImageObservation;
+ readonly client: Partial<
+ Pick<GhidraClient, "hashTargetSnapshot" | "readTargetSnapshot">
+ >;
readonly mapSessionError: (failure: GhidraSessionError) => AnalysisError;
readonly nativeAotResult?: NativeAotPeResult | undefined;
readonly signal?: AbortSignal | undefined;
};
-const isSignalAborted = (signal: AbortSignal | undefined): boolean =>
- signal?.aborted === true;
-
-/** Independently verify measured load-image observations for admitted DOS and raw-binary targets. */
+/** Consume one typed comparison, retaining completed facts after the last awaited work. */
export const attestGhidraNativeLoadImage = async (
input: NativeLoadImageAttestationInput,
-): Promise<Result<JsonValue, AnalysisError>> => {
+): Promise<Result<NativeLoadImage, AnalysisError>> => {
+ const result = await compareLoadImage(input);
+ if (!result.ok) return result;
+ return input.signal?.aborted
+ ? err(
+ new AnalysisCancelledError(input.operation, {
+ cause: input.signal.reason,
+ partialObservation: {
+ kind: "native-load-image",
+ stage: "completed",
+ result: result.value,
+ },
+ }),
+ )
+ : result;
+};
+
+const comparisonFailure = (
+ input: NativeLoadImageAttestationInput,
+ reason: string,
+ cause?: unknown,
+): AnalysisError =>
+ new ProviderAdapterError("ghidra", input.operation, {
+ diagnostics: { reason },
+ ...(cause === undefined ? {} : { cause }),
+ partialObservation: {
+ kind: "native-load-image",
+ stage: "measured",
+ observations: input.measured,
+ },
+ });
+
+const compareLoadImage = async (
+ input: NativeLoadImageAttestationInput,
+): Promise<Result<NativeLoadImage, AnalysisError>> => {
const {
target,
operation,
- measured,
+ measured: observations,
client,
mapSessionError,
nativeAotResult,
signal,
} = input;
- if (isSignalAborted(signal))
- return err(new AnalysisCancelledError(operation));
- const observations = nativeLoadImageObservationSchema.parse(measured);
- if (target.format === "pe") {
- if (nativeAotResult === undefined)
+ // These formats have no additional source work; retain already-derived PE facts.
+ if (
+ target.format === "pe" ||
+ !["dos-mz", "dos-com", "raw-binary"].includes(target.format)
+ ) {
+ if (target.format === "pe" && nativeAotResult === undefined)
return err(
- new ProviderAdapterError("ghidra", operation, {
- diagnostics: {
- reason:
- "The Ghidra provider did not produce read-only NativeAOT metadata for this admitted PE snapshot.",
- },
- }),
+ comparisonFailure(
+ input,
+ "The Ghidra provider did not produce read-only NativeAOT metadata for this admitted PE snapshot.",
+ ),
);
- if (isSignalAborted(signal))
- return err(new AnalysisCancelledError(operation));
- try {
- return ok(
- jsonValueSchema.parse(
- nativeLoadImageSchema.parse({
- status: "unsupported",
- reason:
- "Independent load-image verification currently supports DOS MZ, explicit DOS COM, and caller-supplied raw-binary targets only.",
- observations: {
+ const represented = nativeLoadImageSchema.safeParse({
+ status: "unsupported",
+ reason:
+ "Independent load-image verification currently supports DOS MZ, explicit DOS COM, and caller-supplied raw-binary targets only.",
+ observations:
+ target.format !== "pe" || nativeAotResult === undefined
+ ? observations
+ : {
...observations,
metadata_recovery: [
...(observations.metadata_recovery ?? []),
nativeAotResult.summary,
],
},
- limitations: [
- "Load-image verification is not performed for PE targets; NativeAOT metadata observations are derived separately from the exact admitted snapshot.",
- ],
- }),
- ),
- );
- } catch (cause: unknown) {
- return err(
- new ProviderAdapterError("ghidra", operation, {
- diagnostics: {
- reason:
- cause instanceof Error
- ? cause.message
- : "NativeAOT metadata could not be represented in the load-image result",
- },
- }),
- );
- }
+ limitations: [
+ target.format === "pe"
+ ? "Load-image verification is not performed for PE targets; NativeAOT metadata observations are derived separately from the exact admitted snapshot."
+ : "Other formats expose measured mappings and source identities; no format-specific verification was performed.",
+ ],
+ });
+ return represented.success
+ ? ok(represented.data)
+ : err(
+ comparisonFailure(
+ input,
+ "Load-image observations could not be represented in the result",
+ represented.error,
+ ),
+ );
}
- if (
- target.format !== "dos-mz" &&
- target.format !== "dos-com" &&
- target.format !== "raw-binary"
- ) {
- return ok(
- jsonValueSchema.parse(
- nativeLoadImageSchema.parse({
- status: "unsupported",
- reason:
- "Independent load-image verification currently supports DOS MZ, explicit DOS COM, and caller-supplied raw-binary targets only.",
+ if (signal?.aborted)
+ return err(
+ new AnalysisCancelledError(operation, {
+ cause: signal.reason,
+ partialObservation: {
+ kind: "native-load-image",
+ stage: "measured",
observations,
- limitations: [
- "Other formats expose measured mappings and source identities; no format-specific verification was performed.",
- ],
- }),
- ),
+ },
+ }),
+ );
+ const sourceFailure = (failure: GhidraSessionError): AnalysisError =>
+ mapSessionError(
+ failure.withDiagnostics({
+ ...failure.diagnostics,
+ load_image_observations: jsonValueSchema.parse(observations),
+ }),
);
- }
if (target.format === "raw-binary") {
if (client.hashTargetSnapshot === undefined)
return err(
- new ProviderAdapterError("ghidra", operation, {
- diagnostics: {
- reason:
- "The Ghidra client does not expose its immutable target snapshot identity for independent raw-binary load-image verification.",
- },
- }),
+ comparisonFailure(
+ input,
+ "The Ghidra client does not expose its immutable target snapshot identity for independent raw-binary load-image verification.",
+ ),
);
const snapshot = await client.hashTargetSnapshot(signal);
- if (!snapshot.ok) return err(mapSessionError(snapshot.error));
- if (isSignalAborted(signal))
- return err(new AnalysisCancelledError(operation));
+ if (!snapshot.ok) return err(sourceFailure(snapshot.error));
const attested = attestGhidraRawBinaryLoadImage(
snapshot.value,
target,
observations,
);
return attested.ok
- ? ok(jsonValueSchema.parse(attested.value))
- : err(
- new ProviderAdapterError("ghidra", operation, {
- diagnostics: { reason: attested.error },
- }),
- );
+ ? attested
+ : err(comparisonFailure(input, attested.error));
}
if (client.readTargetSnapshot === undefined)
return err(
- new ProviderAdapterError("ghidra", operation, {
- diagnostics: {
- reason:
- "The Ghidra client does not expose its immutable target snapshot for independent load-image verification.",
- },
- }),
+ comparisonFailure(
+ input,
+ "The Ghidra client does not expose its immutable target snapshot for independent load-image verification.",
+ ),
);
const snapshot = await client.readTargetSnapshot(undefined, signal);
- if (!snapshot.ok) return err(mapSessionError(snapshot.error));
+ if (!snapshot.ok) return err(sourceFailure(snapshot.error));
if (snapshot.value.kind !== "captured")
return err(
- new ProviderAdapterError("ghidra", operation, {
- diagnostics: {
- reason:
- "The uncapped load-image snapshot was unexpectedly not captured.",
- },
- }),
+ comparisonFailure(
+ input,
+ "The uncapped load-image snapshot was unexpectedly not captured.",
+ ),
);
const attested = (
target.format === "dos-com"
? attestGhidraDosComLoadImage
: attestGhidraDosLoadImage
- )(snapshot.value.bytes, target.sha256 ?? "", observations);
- if (!attested.ok)
- return err(
- new ProviderAdapterError("ghidra", operation, {
- diagnostics: { reason: attested.error },
- }),
- );
- return ok(jsonValueSchema.parse(attested.value));
+ )(snapshot.value.bytes, target.sha256, observations);
+ return attested.ok ? attested : err(comparisonFailure(input, attested.error));
};
diff --git a/src/ghidra/GhidraProviderClient.ts b/src/ghidra/GhidraProviderClient.ts
index a8ce78314..8a679d868 100644
--- a/src/ghidra/GhidraProviderClient.ts
+++ b/src/ghidra/GhidraProviderClient.ts
@@ -81,7 +81,6 @@ import { GhidraHeadlessLauncher } from "./GhidraLauncher.js";
import { attestGhidraNativeLoadImage } from "./GhidraLoadImageAttest.js";
import type { NativeAotPeResult } from "../domain/native/nativeAotPe.js";
import { GhidraNativeAotSnapshotOwner } from "./GhidraNativeAotSnapshotOwner.js";
-import { nativeLoadImageObservationSchema } from "../domain/native/nativeLoadImage.js";
import {
GHIDRA_PROVIDER_IDENTITY,
healthLimitations,
@@ -532,6 +531,55 @@ export const createGhidraProviderClient = (input: {
if (!parsed.ok) return parsed;
return ok(projectExecution(operation, parsed.value, called.value));
};
+ const loadImageExecution = async (raw: JsonValue, signal?: AbortSignal) => {
+ const operation = "inspect_native_load_image";
+ const measured = parseGhidraInventoryResult(operation, raw);
+ if (!measured.ok) return measured;
+ let derived: NativeAotPeResult | undefined;
+ if (target.format === "pe") {
+ if (nativeAotOwner === undefined)
+ return err(
+ new ProviderAdapterError("ghidra", operation, {
+ diagnostics: {
+ reason:
+ "The admitted PE session has no read-only NativeAOT snapshot owner.",
+ },
+ }),
+ );
+ const result = await nativeAotOwner.derive(
+ measured.value.image_base,
+ operation,
+ signal,
+ raw,
+ );
+ if (!result.ok) return result;
+ derived = result.value;
+ }
+ const attested = await attestGhidraNativeLoadImage({
+ target,
+ operation,
+ measured: measured.value,
+ client,
+ mapSessionError: (failure) =>
+ projectSessionError(
+ operation,
+ failure,
+ config.ghidraStartupTimeoutMs,
+ lostProviderHealth(),
+ ),
+ nativeAotResult: derived,
+ signal,
+ });
+ return attested.ok
+ ? ok(
+ projectExecution(
+ operation,
+ jsonValueSchema.parse(attested.value),
+ raw,
+ ),
+ )
+ : attested;
+ };
return ok<AnalysisClient>({
execute: async (operation, parameters, options) => {
if (extensionFailure !== undefined) return err(extensionFailure);
@@ -610,6 +658,8 @@ export const createGhidraProviderClient = (input: {
lostProviderHealth(),
),
);
+ if (operation === "inspect_native_load_image")
+ return loadImageExecution(called.value, options?.signal);
let normalized: JsonValue;
let observationLimitations: readonly string[] = [];
let observationLocations: readonly EvidenceLocation[] = [];
@@ -667,47 +717,6 @@ export const createGhidraProviderClient = (input: {
});
}
}
- if (operation === "inspect_native_load_image") {
- let derived: NativeAotPeResult | undefined;
- if (target.format === "pe") {
- const observations =
- nativeLoadImageObservationSchema.parse(normalized);
- if (nativeAotOwner === undefined)
- return err(
- new ProviderAdapterError("ghidra", operation, {
- diagnostics: {
- reason:
- "The admitted PE session has no read-only NativeAOT snapshot owner.",
- },
- }),
- );
- const result = await nativeAotOwner.derive(
- observations.image_base,
- operation,
- options?.signal,
- normalized,
- );
- if (!result.ok) return result;
- derived = result.value;
- }
- const attested = await attestGhidraNativeLoadImage({
- target,
- operation,
- measured: normalized,
- client,
- mapSessionError: (failure) =>
- projectSessionError(
- operation,
- failure,
- config.ghidraStartupTimeoutMs,
- lostProviderHealth(),
- ),
- nativeAotResult: derived,
- signal: options?.signal,
- });
- if (!attested.ok) return attested;
- normalized = attested.value;
- }
return ok(
projectExecution(
operation,
diff --git a/tests/boundary/mcp/ghidraFailureDiagnostics.test.ts b/tests/boundary/mcp/ghidraFailureDiagnostics.test.ts
index 5d65a1772..2e1623569 100644
--- a/tests/boundary/mcp/ghidraFailureDiagnostics.test.ts
+++ b/tests/boundary/mcp/ghidraFailureDiagnostics.test.ts
@@ -1,3 +1,6 @@
+import { nativeLoadImagePartialObservationSchema } from "../../../src/domain/native/nativeLoadImage.js";
+import { fixtureDosLoadImage } from "../../../src/ghidra/GhidraLoadImage.fixture.js";
+import { attestGhidraDosLoadImage } from "../../../src/ghidra/GhidraLoadImageValues.js";
import { nativeAotSnapshotObservationSchema } from "../../../src/domain/native/nativeAotSnapshotObservation.js";
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
@@ -97,7 +100,7 @@ it("preserves queue failure diagnostics through the provider, CLI adapter and SD
it.each(
(["cancelled", "protocol"] as const).flatMap((kind) =>
- (["file", "native-aot"] as const).map((observation) => ({
+ (["file", "native-aot", "load-image"] as const).map((observation) => ({
kind,
observation,
})),
@@ -109,7 +112,9 @@ it.each(
"rea-ghidra-snapshot-projection-",
);
const path = join(directory, "Inert.exe");
- const bytes = nativeAotPeFixture();
+ const dos = fixtureDosLoadImage();
+ const bytes =
+ observation === "load-image" ? dos.bytes : nativeAotPeFixture();
await writeFile(path, bytes);
const partialObservation =
observation === "file"
@@ -119,12 +124,26 @@ it.each(
sha256: nativeAotPeDigest(bytes),
bytes: bytes.length,
})
- : nativeAotSnapshotObservationSchema.parse({
- kind: "native-aot-snapshot",
- analysis_artifact_sha256: nativeAotPeDigest(bytes),
- image_base: "0x140000000",
- capture: { status: "captured", bytes: bytes.length },
- });
+ : observation === "native-aot"
+ ? nativeAotSnapshotObservationSchema.parse({
+ kind: "native-aot-snapshot",
+ analysis_artifact_sha256: nativeAotPeDigest(bytes),
+ image_base: "0x140000000",
+ capture: { status: "captured", bytes: bytes.length },
+ })
+ : (() => {
+ const compared = attestGhidraDosLoadImage(
+ dos.bytes,
+ dos.sha256,
+ dos.observation,
+ );
+ if (!compared.ok) throw new Error(compared.error);
+ return nativeLoadImagePartialObservationSchema.parse({
+ kind: "native-load-image",
+ stage: "completed",
+ result: compared.value,
+ });
+ })();
const cleanup = new ProviderCleanupError("ghidra", [path], {
reason: "controlled snapshot descriptor remains",
});
diff --git a/tests/boundary/providers/ghidra/ghidraClient.test.ts b/tests/boundary/providers/ghidra/ghidraClient.test.ts
index 60fc89899..b820d1597 100644
--- a/tests/boundary/providers/ghidra/ghidraClient.test.ts
+++ b/tests/boundary/providers/ghidra/ghidraClient.test.ts
@@ -1,3 +1,7 @@
+import { parseConfig } from "../../../../src/config/parseConfig.js";
+import { GhidraProvider } from "../../../../src/ghidra/GhidraProvider.js";
+import { fixtureDosLoadImage } from "../../../../src/ghidra/GhidraLoadImage.fixture.js";
+import { jsonValueSchema } from "../../../../src/domain/jsonValue.js";
import { artifactFilePrimaryFailure } from "../../../../src/artifacts/ArtifactFileOperation.js";
import { AnalysisCancelledError } from "../../../../src/domain/analysisErrorCore.js";
import { spawn, type ChildProcess } from "node:child_process";
@@ -240,6 +244,113 @@ it("keeps one shared startup despite a failed progress sink and stops reports af
expect(reports).toBe(1);
});
+it.each(["descriptor-close", "result-consumption"] as const)(
+ "preserves DOS cancellation at the actual snapshot %s boundary",
+ async (phase) => {
+ const fixture = fixtureDosLoadImage();
+ const directory = await createTestTempDirectory("rea-dos-cancel-");
+ const targetPath = join(directory, "fixture.exe");
+ await writeFile(targetPath, fixture.bytes);
+ const live = clientFor(new FixtureLauncher(), {
+ targetPath,
+ targetSha256: fixture.sha256,
+ });
+ const started = await live.start();
+ if (!started.ok) throw started.error;
+ const caller = new AbortController();
+ const reason = { caller: phase };
+ const config = parseConfig({
+ GHIDRA_INSTALL_DIR: "/controlled/ghidra_12.1.4_PUBLIC",
+ });
+ if (!config.ok) throw config.error;
+ const provider = new GhidraProvider(
+ config.value,
+ pino({ level: "silent" }),
+ {},
+ {
+ platform: "linux",
+ architecture: "x64",
+ readText: () => "application.version=12.1.4\napplication.java.min=21\n",
+ executable: () => true,
+ probeJava: () =>
+ ok({
+ osArch: "amd64",
+ osName: "Linux",
+ version: "21.0.11",
+ major: 21,
+ home: "/controlled/jdk21",
+ bits: 64,
+ runtime: "jdk",
+ }),
+ },
+ () => ({
+ start: () => live.start(),
+ callTool: async () => ok(jsonValueSchema.parse(fixture.observation)),
+ readTargetSnapshot: async (maximum, signal) => {
+ const result = await live.readTargetSnapshot(maximum, signal);
+ if (phase === "result-consumption" && result.ok) caller.abort(reason);
+ return result;
+ },
+ close: () => live.close(),
+ }),
+ );
+ const target = {
+ path: targetPath,
+ sha256: fixture.sha256,
+ kind: "executable" as const,
+ format: "dos-mz" as const,
+ architecture: "x86" as const,
+ availableArchitectures: ["x86" as const],
+ };
+ const profile = await provider.resolveAnalysisProfile(target);
+ if (!profile.ok || profile.value.profile === null)
+ throw new Error("Expected DOS profile");
+ const client = provider.createClient(target, profile.value.profile);
+ let closedOwner: OwnedFileHandle | undefined;
+ const original = OwnedFileHandle.prototype.close;
+ const close =
+ phase === "descriptor-close"
+ ? vi
+ .spyOn(OwnedFileHandle.prototype, "close")
+ .mockImplementationOnce(async function (this: OwnedFileHandle) {
+ closedOwner = this;
+ await original.call(this);
+ caller.abort(reason);
+ })
+ : undefined;
+ onTestFinished(async () => {
+ close?.mockRestore();
+ await client.close();
+ });
+ const result = await client.execute(
+ "inspect_native_load_image",
+ {},
+ { signal: caller.signal },
+ );
+ if (result.ok) throw new Error("Expected DOS cancellation");
+ expect(result.error._tag).toBe("AnalysisCancelledError");
+ expect(result.error.cause).toBe(reason);
+ if (phase === "descriptor-close") {
+ expect(closedOwner?.handle.fd).toBe(-1);
+ expect(result.error.partialObservation).toMatchObject({
+ kind: "file-snapshot-read",
+ capture: { status: "captured", bytes: fixture.bytes.length },
+ });
+ expect(result.error.diagnostics).toMatchObject({
+ load_image_observations: fixture.observation,
+ });
+ } else {
+ expect(result.error.partialObservation).toMatchObject({
+ kind: "native-load-image",
+ stage: "completed",
+ result: { status: "verified", observations: fixture.observation },
+ });
+ }
+ close?.mockRestore();
+ expect((await client.close()).ok).toBe(true);
+ },
+);
+
it("reports snapshot descriptor cleanup immediately and resolves its exact error on retry", async () => {
const client = clientFor(new FixtureLauncher());
const started = await client.start();