Files
rea/src/ghidra/GhidraSnapshotCache.test.ts
T
242e2b0001 fix(ghidra): preserve function facet and call coverage (#3002)
* fix(ghidra): preserve observed function facet and call coverage

Declare successful query availability in the Java producer, including explicit unavailable pseudocode reasons. Carry observed static call-set coverage through the parsed provider result and Evidence without inventing facts for legacy omissions. Use Ghidra indexed comment addresses over the function body and entry, retaining cancellation checks and sparse collection.

Closes #2951

Co-authored-by: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com>

* fix(ghidra): retain unresolved call coverage in observations

Share decoded unresolved-call facts between dossiers, callee coverage and reference observations. Combine terminal and unresolved observations in one instruction traversal and retain site records only when requested. Keep missing procedure identities incomplete and validate unresolved locations at the provider boundary.

Bind snapshots to the corrected call coverage profile so older complete claims cannot replay under the new semantics. Add real public MCP callback trace/comparison regressions.

Co-authored-by: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com>

* fix(ghidra): separate reference targets from callee coverage

Reuse containing-function ownership for resolved reference identities and independently compare those identities with the actual returned callee set. Keep known interior routes out of unresolved site records while retaining partial inventory coverage.

Advance the coverage profile to v3 and reject interim v2 cache bindings. Add a real Ghidra producer regression with restored reference metadata; the previous bridge fails the known-route assertion.

Co-authored-by: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com>

* fix(ghidra): measure incoming call coverage across function bodies

Compare incoming reference source identities across the owned function body and entry with the actual returned caller set. Stream caller-only checks and reuse dossier reference observations. Combine caller/callee coverage from observed counts without reinterpreting serialized metadata, and share the body scope owner with comments and references.

Bind snapshots to function-body coverage semantics v4 and preserve the real off-entry caller regression.

Co-authored-by: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com>

* fix(ghidra): preserve whole-scope directional call coverage

Check body-and-entry call references independently of decoded instruction flow. Reuse collected dossier references and stream inventory-only coverage checks. Keep caller-only gaps distinct from incomplete outgoing coverage in offline path reconstruction, and invalidate prior snapshot profiles.

Co-authored-by: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com>

* fix(mcp): retain compact Evidence field types

Share optional diagnostics across the three tagged relationship coverage states instead of advertising duplicate branches. Preserve coverage validation while keeping compact Evidence properties within the existing reference expansion budget. Verify invalid direction cardinalities against the actual SDK-advertised schema.

Co-authored-by: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com>

---------

Co-authored-by: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com>
Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
2026-10-14 07:52:14 +08:00

366 lines
12 KiB
TypeScript

import { describe, expect, it } from "vitest";
import { createTestBinarySession } from "../../tests/fixtures/binarySession.js";
import { parseConfig } from "../config/parseConfig.js";
import type { BinaryTarget } from "../domain/binaryTargetTypes.js";
import { functionDossierSchema } from "../domain/hopperValues.js";
import { createAnalysisProfile } from "../domain/analysisProfile.js";
import { ghidraFunctionDossier } from "../domain/ghidraValues.fixture.js";
import { err, ok } from "../domain/result.js";
import { silentLogger } from "../logger.js";
import { GhidraProvider } from "./GhidraProvider.js";
import { GhidraSessionError } from "./GhidraSessionError.js";
import { GHIDRA_SESSION_CAPABILITIES } from "./GhidraSessionValues.js";
import type { RelationshipCoverage } from "../domain/relationshipCoverage.js";
const TARGET: BinaryTarget = {
path: "/tmp/ghidra-cache-fixture",
sha256: "a".repeat(64),
kind: "executable",
format: "elf",
architecture: "x86_64",
availableArchitectures: ["x86_64"],
};
// Exercise the real provider descriptors, profile, input/output projection and
// session cache; only the installed Ghidra process is replaced at its seam.
const fixture = (version = "12.1.4", coverage?: RelationshipCoverage) => {
const config = parseConfig({ GHIDRA_INSTALL_DIR: "/opt/ghidra" });
if (!config.ok) throw config.error;
const calls: string[] = [];
let name = "original";
let cancelStarted: (() => void) | undefined;
const cancellationReady = new Promise<void>((resolve) => {
cancelStarted = resolve;
});
const provider = new GhidraProvider(
config.value,
silentLogger,
{},
{
platform: "linux",
architecture: "x64",
readText: () =>
`application.version=${version}\napplication.java.min=21\n`,
executable: () => true,
probeJava: () => ({
osArch: "amd64",
osName: "Linux",
version: "21.0.11",
major: 21,
home: "/usr/lib/jvm/jdk-21",
bits: 64,
runtime: "jdk",
}),
},
(options) => ({
start: async () =>
ok({
name: "REA Ghidra bridge",
run_id: "11111111-1111-4111-8111-111111111111",
profile_digest: options.profileDigest,
provider: { id: "ghidra", version },
read_only: false,
analysis_complete: true,
analysis_timed_out: false,
capabilities: [...GHIDRA_SESSION_CAPABILITIES],
target: {
name: "fixture",
language_id: "x86:LE:64:default",
compiler_spec_id: "gcc",
image_base: "0x1000",
default_address_space: "ram",
sha256: TARGET.sha256,
},
}),
callTool: async (operation, parameters, requestOptions) => {
calls.push(operation);
if (requestOptions?.signal !== undefined) {
const signal = requestOptions.signal;
await new Promise<void>((resolve) => {
signal.addEventListener("abort", () => resolve(), { once: true });
cancelStarted?.();
});
// Active cancellation discards Ghidra's ephemeral annotations; the
// next request reimports the original artifact under the same profile.
name = "original";
return err(new GhidraSessionError("cancelled", "Cancelled"));
}
if (operation === "annotate_native_function") {
if (typeof parameters.name !== "string")
throw new Error("Expected an annotation name");
name = parameters.name;
}
const dossier = functionDossierSchema.parse(ghidraFunctionDossier());
dossier.procedure.name = name;
dossier.pseudocode = `void ${name}() {}`;
if (operation === "annotate_native_function")
return ok({
annotations: {
address: dossier.procedure.address,
name,
comment: null,
inline_comment: null,
},
dossier,
effects: {
scope: "session-analysis-database",
source_bytes_modified: false,
persists_after_close: false,
},
});
const value =
operation === "procedure_pseudo_code" ? dossier.pseudocode : dossier;
return ok(
operation === "procedure_pseudo_code" ||
operation === "analyze_function"
? {
value,
limitations: [],
...(operation === "analyze_function" && coverage !== undefined
? { relationship_coverage: coverage }
: {}),
}
: value,
);
},
close: async () => ok(null),
}),
);
return {
calls,
cancellationReady,
session: createTestBinarySession(provider),
};
};
const open = async (session: ReturnType<typeof fixture>["session"]) => {
const preview = await session.previewTarget(TARGET);
if (!preview.ok) throw preview.error;
expect((await session.openResolvedTarget(preview.value)).ok).toBe(true);
};
describe("Ghidra relationship coverage replay", () => {
it.each([
undefined,
{ status: "complete", diagnostics: ["Resolved static references only."] },
{ status: "partial", limitations: ["Instruction coverage was truncated."] },
{ status: "unknown", reason: "Relationship inventory was unavailable." },
{
status: "partial",
limitations: ["Missing callers."],
limited_directions: ["callers"],
},
] satisfies (RelationshipCoverage | undefined)[])(
"preserves relationship coverage %j through live execution, cache and snapshot replay",
async (coverage) => {
const initial = fixture("12.1.4", coverage);
await open(initial.session);
const parameters = { procedure: "0x1000" };
for (let i = 0; i < 2; i++) {
const execution = await initial.session.execute(
"analyze_function",
parameters,
);
if (!execution.ok) throw execution.error;
expect(execution.value.relationshipCoverage).toEqual(coverage);
}
expect(initial.calls).toEqual(["analyze_function"]);
const snapshot = initial.session.exportAnalysisSnapshot();
if (!snapshot.ok) throw snapshot.error;
await initial.session.close();
const replay = fixture();
expect(replay.session.importAnalysisSnapshot(snapshot.value).ok).toBe(
true,
);
await open(replay.session);
const execution = await replay.session.execute(
"analyze_function",
parameters,
);
if (!execution.ok) throw execution.error;
expect(execution.value.relationshipCoverage ?? undefined).toEqual(
coverage,
);
expect(replay.calls).toEqual([]);
await replay.session.close();
},
);
});
describe("Ghidra snapshot profile admission", () => {
it.each([
{
parameter: "instruction_references",
current: "exact-address-incoming-v1",
legacy: undefined,
},
{
parameter: "call_relationship_coverage",
current: "function-body-call-coverage-v5",
legacy: "resolved-call-reference-diagnostics-v1",
},
{
parameter: "call_relationship_coverage",
current: "function-body-call-coverage-v5",
legacy: "decoded-call-target-coverage-v2",
},
{
parameter: "call_relationship_coverage",
current: "function-body-call-coverage-v5",
legacy: "decoded-call-target-coverage-v3",
},
{
parameter: "call_relationship_coverage",
current: "function-body-call-coverage-v5",
legacy: "function-body-call-coverage-v4",
},
])(
"refuses snapshots with outdated $parameter semantics",
async ({ parameter, current, legacy: prior }) => {
const initial = fixture();
await open(initial.session);
const snapshot = initial.session.exportAnalysisSnapshot();
if (!snapshot.ok) throw snapshot.error;
await initial.session.close();
const profile = snapshot.value.binding.analysis_profile;
expect(profile.parameters[parameter]).toBe(current);
const legacy = {
...snapshot.value,
binding: {
...snapshot.value.binding,
analysis_profile: createAnalysisProfile(profile.provider, {
...Object.fromEntries(
Object.entries(profile.parameters).filter(
([key]) => key !== parameter,
),
),
...(prior === undefined ? {} : { [parameter]: prior }),
}),
},
};
const replay = fixture();
const imported = replay.session.importAnalysisSnapshot(legacy);
if (!imported.ok) throw imported.error;
expect(await replay.session.previewTarget(TARGET)).toMatchObject({
ok: false,
error: { _tag: "EvidenceIntegrityError" },
});
expect(replay.calls).toEqual([]);
await replay.session.close();
},
);
});
describe("Ghidra snapshot cache", () => {
it.each([
{ operation: "analyze_function", parameters: { procedure: "0x1000" } },
{
operation: "procedure_pseudo_code",
parameters: { procedure: "0x1000", document: "fixture" },
},
] as const)(
"replays repeated $operation calls and imported snapshots despite private project writes",
async ({ operation, parameters }) => {
const initial = fixture();
await open(initial.session);
const first = await initial.session.execute(operation, parameters);
expect(first.ok).toBe(true);
const second = await initial.session.execute(operation, parameters);
expect(second).toMatchObject({
ok: true,
value: {
limitations: expect.arrayContaining([
expect.stringContaining("local REA analysis snapshot"),
]),
},
});
expect(second.ok && second.value.result).toEqual(
first.ok && first.value.result,
);
expect(initial.calls).toEqual([operation]);
const snapshot = initial.session.exportAnalysisSnapshot();
if (!snapshot.ok) throw snapshot.error;
expect(snapshot.value.entries).toHaveLength(1);
expect(snapshot.value.binding.analysis_profile.provider.version).toBe(
"12.1.4",
);
await initial.session.close();
const replay = fixture();
expect(replay.session.importAnalysisSnapshot(snapshot.value).ok).toBe(
true,
);
await open(replay.session);
const imported = await replay.session.execute(operation, parameters);
expect(imported.ok && imported.value.result).toEqual(
first.ok && first.value.result,
);
expect(replay.calls).toEqual([]);
await replay.session.close();
const changed = fixture("12.1.5");
expect(changed.session.importAnalysisSnapshot(snapshot.value).ok).toBe(
true,
);
expect(await changed.session.previewTarget(TARGET)).toMatchObject({
ok: false,
error: { _tag: "EvidenceIntegrityError" },
});
expect(changed.calls).toEqual([]);
},
);
it("keeps annotation-dependent reads live after cancellation reimports the original artifact", async () => {
const { session, calls, cancellationReady } = fixture();
await open(session);
const parameters = { procedure: "0x1000", document: "fixture" };
expect(
await session.execute("procedure_pseudo_code", parameters),
).toMatchObject({
ok: true,
value: { result: "void original() {}" },
});
expect(
(
await session.execute("annotate_native_function", {
procedure: "0x1000",
name: "renamed",
})
).ok,
).toBe(true);
for (let index = 0; index < 2; index += 1)
expect(
await session.execute("procedure_pseudo_code", parameters),
).toMatchObject({
ok: true,
value: { result: "void renamed() {}" },
});
expect(session.exportAnalysisSnapshot().ok).toBe(false);
const controller = new AbortController();
const cancelled = session.execute(
"analyze_function",
{ procedure: "0x2000" },
{ signal: controller.signal },
);
await cancellationReady;
controller.abort();
expect(await cancelled).toMatchObject({
ok: false,
error: { _tag: "AnalysisCancelledError" },
});
for (let index = 0; index < 2; index += 1)
expect(
await session.execute("procedure_pseudo_code", parameters),
).toMatchObject({
ok: true,
value: { result: "void original() {}" },
});
expect(
calls.filter((operation) => operation === "procedure_pseudo_code"),
).toHaveLength(5);
expect(session.exportAnalysisSnapshot().ok).toBe(false);
await session.close();
});
});