feat(ghidra): add atomic function annotation edits (#709)
* feat(ghidra): edit function annotations atomically Return annotation readback and refreshed function analysis through CLI and MCP. Own each database transaction, invalidate caches and immutable snapshots, preserve executable bytes, and retain the Windows mutation boundary. Assisted-by: Nitori (gensokyo-skills:nitori-reverse-engineering) * fix(ghidra): preserve qualified function annotation identity Preserve namespaces during local name writes and match qualified readback to the refreshed dossier. Add a producer-shaped regression and verify a real namespaced C++ function through the CLI. Assisted-by: Nitori (gensokyo-skills:nitori-reverse-engineering) * test(ghidra): align verification with annotation authority Keep strict capability and profile checks while admitting the explicit session metadata operation. Verify packaged transport authority and atomic transaction commitments and preserve a read-only Windows expectation. Assisted-by: Nitori (gensokyo-skills:nitori-reverse-engineering)
This commit is contained in:
@@ -43,6 +43,7 @@ export {
|
||||
} from "./DirectAnalysisStatus.js";
|
||||
|
||||
type DirectAnalysisTool =
|
||||
| "annotate_native_function"
|
||||
| "inspect_native_load_image"
|
||||
| "read_bytes"
|
||||
| "address_to_file_offset"
|
||||
|
||||
@@ -19,6 +19,7 @@ export const registerCoreAnalysisCommands = (
|
||||
logger: Logger,
|
||||
): void => {
|
||||
registerCoreCommands(cli, logger);
|
||||
registerAnnotationCommand(cli, logger);
|
||||
cli.command(CLI_COMMANDS.inspectNativeLoadImage, {
|
||||
description:
|
||||
"Verify loaded native bytes, source mappings, relocations and entry",
|
||||
@@ -722,3 +723,51 @@ const registerSearchCommand = (cli: CliInstance, logger: Logger): void => {
|
||||
),
|
||||
});
|
||||
};
|
||||
|
||||
const registerAnnotationCommand = (cli: CliInstance, logger: Logger): void => {
|
||||
cli.command(CLI_COMMANDS.annotateNativeFunction, {
|
||||
description: "Edit function annotations and return refreshed analysis",
|
||||
args: z.object({
|
||||
path: z.string().describe("Local executable path"),
|
||||
procedure: z
|
||||
.string()
|
||||
.describe("Exact function entry address or unique name"),
|
||||
}),
|
||||
options: z.object({
|
||||
name: z.string().min(1).optional().describe("Analyst function name"),
|
||||
comment: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe("Regular entry comment; empty text clears it"),
|
||||
"inline-comment": z
|
||||
.string()
|
||||
.optional()
|
||||
.describe("Inline entry comment; empty text clears it"),
|
||||
"target-format": formatSelectionOption,
|
||||
provider: providerSelectionOption,
|
||||
}),
|
||||
run: ({ args, options }) =>
|
||||
logCliCommand(logger, CLI_COMMANDS.annotateNativeFunction, () =>
|
||||
runDirectAnalysis(
|
||||
args.path,
|
||||
"annotate_native_function",
|
||||
{
|
||||
procedure: args.procedure,
|
||||
...(options.name === undefined ? {} : { name: options.name }),
|
||||
...(options.comment === undefined
|
||||
? {}
|
||||
: { comment: options.comment }),
|
||||
...(options["inline-comment"] === undefined
|
||||
? {}
|
||||
: { inline_comment: options["inline-comment"] }),
|
||||
},
|
||||
directAnalysisOptions(
|
||||
logger,
|
||||
undefined,
|
||||
options.provider,
|
||||
options["target-format"],
|
||||
),
|
||||
),
|
||||
),
|
||||
});
|
||||
};
|
||||
|
||||
@@ -14,6 +14,7 @@ export const CLI_COMMANDS = Object.freeze({
|
||||
capabilities: "capabilities",
|
||||
providers: "providers",
|
||||
function: "function",
|
||||
annotateNativeFunction: "annotate-native-function",
|
||||
inspectNativeApi: "inspect-native-api",
|
||||
instructions: "instructions",
|
||||
search: "search",
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { z } from "zod";
|
||||
import { nativeFunctionAnnotationsInputSchema } from "../domain/nativeFunctionAnnotations.js";
|
||||
|
||||
import {
|
||||
officialOutputSchemas,
|
||||
@@ -36,6 +37,11 @@ const official = <Name extends string, Schema extends z.ZodObject>(
|
||||
|
||||
/** Bridge operations exposed without additional application composition. */
|
||||
export const OFFICIAL_TOOL_CONTRACTS = [
|
||||
official(
|
||||
"annotate_native_function",
|
||||
"Atomically update one function name and/or entry comments, read them back, and return a refreshed complete function dossier. Ghidra changes its ephemeral session analysis database only; original executable bytes remain unchanged. Empty comment text clears that comment. Edits remain available to subsequent MCP calls until close; CLI returns the updated dossier before discarding its session. Invalid edits roll back the entire operation. Windows P0 and providers without this capability are unsupported.",
|
||||
nativeFunctionAnnotationsInputSchema,
|
||||
),
|
||||
official(
|
||||
"inspect_native_load_image",
|
||||
"Verify the provider's loaded DOS MZ or explicitly selected COM image against its immutable target snapshot: complete original/modified source-byte digests, header/module file mappings and memory digests, relocations and external entry. Returns measured observations and independent checks with mismatch coordinates. COM verification includes its imposed entry register context and does not claim PSP/runtime coverage. Overlay and uninitialized coverage remain explicit; other formats return unsupported. Does not execute or modify the target.",
|
||||
|
||||
@@ -42,6 +42,11 @@ export const TOOL_EXAMPLE_OVERRIDES: Readonly<
|
||||
get_call_graph: { address: "0x1000" },
|
||||
find_xrefs_to_name: { name: "malloc" },
|
||||
analyze_function: { procedure: "main" },
|
||||
annotate_native_function: {
|
||||
procedure: "0x10100",
|
||||
name: "entry",
|
||||
comment: "Analyst observation",
|
||||
},
|
||||
analyze_swift_types: { category: "classes", pattern: "Account" },
|
||||
inspect_native_api: { procedure: "main" },
|
||||
trace_feature: { query: "license" },
|
||||
|
||||
@@ -41,6 +41,12 @@ const sessionEvidence = effects({ mutatesSession: true });
|
||||
|
||||
/** Explicit effect audit for every public tool. */
|
||||
export const TOOL_EFFECTS: Readonly<Record<string, ToolEffects>> = {
|
||||
annotate_native_function: effects({
|
||||
mutatesTarget: true,
|
||||
mutatesSession: true,
|
||||
launchesProcess: true,
|
||||
writesFilesystem: true,
|
||||
}),
|
||||
inspect_native_load_image: evidence,
|
||||
inspect_native_dispatch_metadata: evidence,
|
||||
trace_native_ui_action: evidence,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { z } from "zod";
|
||||
import { nativeFunctionAnnotationsSchema } from "../domain/nativeFunctionAnnotations.js";
|
||||
import { nativeLoadImageSchema } from "../domain/nativeLoadImage.js";
|
||||
import { nativeUiResultSchema } from "../domain/nativeUiObservation.js";
|
||||
import { nativeValueTraceSchema } from "../domain/nativeValueTrace.js";
|
||||
@@ -101,6 +102,7 @@ const addressedString = z.object({
|
||||
|
||||
/** Exact structured-content schemas shared by direct analysis providers. */
|
||||
export const officialOutputSchemas: Readonly<Record<string, z.ZodObject>> = {
|
||||
annotate_native_function: resultOf(nativeFunctionAnnotationsSchema),
|
||||
inspect_native_load_image: resultOf(nativeLoadImageSchema),
|
||||
inspect_native_data_type: resultOf(nativeDataTypeSchema),
|
||||
inspect_native_instruction: resultOf(nativeInstructionSchema),
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import { z } from "zod";
|
||||
import { functionDossierSchema } from "./hopperValues.js";
|
||||
|
||||
/** One explicit function's analyst-authored metadata changes. */
|
||||
export const nativeFunctionAnnotationsInputSchema = z
|
||||
.strictObject({
|
||||
procedure: z.string().min(1),
|
||||
name: z.string().min(1).optional(),
|
||||
comment: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe("Regular entry comment; empty text clears it"),
|
||||
inline_comment: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe("Inline entry comment; empty text clears it"),
|
||||
})
|
||||
.refine(
|
||||
(value) =>
|
||||
value.name !== undefined ||
|
||||
value.comment !== undefined ||
|
||||
value.inline_comment !== undefined,
|
||||
"Supply at least one annotation change",
|
||||
);
|
||||
|
||||
/** Readback and refreshed analysis after one atomic metadata edit. */
|
||||
export const nativeFunctionAnnotationsSchema = z
|
||||
.strictObject({
|
||||
annotations: z.strictObject({
|
||||
address: z.string().min(1),
|
||||
name: z.string().min(1),
|
||||
comment: z.string().nullable(),
|
||||
inline_comment: z.string().nullable(),
|
||||
}),
|
||||
dossier: functionDossierSchema,
|
||||
effects: z.strictObject({
|
||||
scope: z.literal("session-analysis-database"),
|
||||
source_bytes_modified: z.literal(false),
|
||||
persists_after_close: z.literal(false),
|
||||
}),
|
||||
})
|
||||
.superRefine((value, context) => {
|
||||
if (
|
||||
value.annotations.address !== value.dossier.procedure.address ||
|
||||
value.annotations.name !== value.dossier.procedure.name
|
||||
)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
message:
|
||||
"Annotation readback disagrees with refreshed function identity",
|
||||
});
|
||||
});
|
||||
File diff suppressed because one or more lines are too long
@@ -38,7 +38,8 @@ export const resolveGhidraAnalysisProfile = (
|
||||
available_architectures: [
|
||||
...(target.availableArchitectures ?? []),
|
||||
].sort(),
|
||||
import_mode: "ephemeral-read-only",
|
||||
import_mode: "ephemeral-source-immutable",
|
||||
annotation_policy: "atomic-function-entry-metadata-v1",
|
||||
load_image_observations: "source-mappings-entry-context-v2",
|
||||
function_body_evidence: "complete-inclusive-ranges-v1",
|
||||
...(dos
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
import { functionDossierSchema } from "../domain/hopperValues.js";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { nativeFunctionAnnotationsInputSchema } from "../domain/nativeFunctionAnnotations.js";
|
||||
import { ghidraFunctionDossier } from "../domain/ghidraValues.fixture.js";
|
||||
import {
|
||||
parseGhidraFunctionInput,
|
||||
parseGhidraFunctionResult,
|
||||
} from "./GhidraFunctionValues.js";
|
||||
import {
|
||||
CAPABILITIES,
|
||||
windowsP0Capabilities,
|
||||
} from "./GhidraProviderCapabilities.js";
|
||||
import { HOPPER_PROVIDER_TOOL_CONTRACTS } from "../hopper/HopperProvider.js";
|
||||
|
||||
const result = () => {
|
||||
const dossier = functionDossierSchema.parse(ghidraFunctionDossier());
|
||||
return {
|
||||
annotations: {
|
||||
address: dossier.procedure.address,
|
||||
name: dossier.procedure.name,
|
||||
comment: null,
|
||||
inline_comment: "Finding",
|
||||
},
|
||||
dossier,
|
||||
effects: {
|
||||
scope: "session-analysis-database",
|
||||
source_bytes_modified: false,
|
||||
persists_after_close: false,
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
describe("Ghidra function annotations", () => {
|
||||
it("requires an explicit function and at least one change without approval flags", () => {
|
||||
for (const input of [
|
||||
{},
|
||||
{ procedure: "main" },
|
||||
{ procedure: "", name: "entry" },
|
||||
{ procedure: "main", name: "" },
|
||||
{ procedure: "main", comment: null },
|
||||
{ procedure: "main", name: "entry", approve: true },
|
||||
])
|
||||
expect(
|
||||
nativeFunctionAnnotationsInputSchema.safeParse(input).success,
|
||||
).toBe(false);
|
||||
expect(
|
||||
parseGhidraFunctionInput("annotate_native_function", {
|
||||
procedure: "0x10100",
|
||||
comment: "",
|
||||
}),
|
||||
).toEqual({ ok: true, value: { procedure: "0x10100", comment: "" } });
|
||||
});
|
||||
|
||||
it("preserves multiline Unicode text and omitted fields", () => {
|
||||
const input = { procedure: "entry", inline_comment: "Line one\n註記" };
|
||||
expect(parseGhidraFunctionInput("annotate_native_function", input)).toEqual(
|
||||
{ ok: true, value: input },
|
||||
);
|
||||
});
|
||||
|
||||
it("validates readback identity, exact effects and the complete Ghidra dossier", () => {
|
||||
const value = result();
|
||||
expect(
|
||||
parseGhidraFunctionResult("annotate_native_function", value).ok,
|
||||
).toBe(true);
|
||||
for (const malformed of [
|
||||
{ ...value, annotations: { ...value.annotations, name: "different" } },
|
||||
{ ...value, annotations: { ...value.annotations, address: "0x9999" } },
|
||||
{ ...value, effects: { ...value.effects, source_bytes_modified: true } },
|
||||
{ ...value, effects: { ...value.effects, persists_after_close: true } },
|
||||
{ ...value, dossier: { ...value.dossier, native_value_flow: null } },
|
||||
])
|
||||
expect(
|
||||
parseGhidraFunctionResult("annotate_native_function", malformed).ok,
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("preserves qualified names in readback and the refreshed dossier", () => {
|
||||
const value = result();
|
||||
const name = "namespace::recovered_routine";
|
||||
expect(
|
||||
parseGhidraFunctionResult("annotate_native_function", {
|
||||
...value,
|
||||
annotations: { ...value.annotations, name },
|
||||
dossier: {
|
||||
...value.dossier,
|
||||
procedure: { ...value.dossier.procedure, name },
|
||||
},
|
||||
}).ok,
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("declares mutation only for the admitted operation and keeps Windows and Hopper unavailable", () => {
|
||||
expect(
|
||||
CAPABILITIES.find((c) => c.operation === "annotate_native_function"),
|
||||
).toMatchObject({
|
||||
available: true,
|
||||
effects: { mutatesArtifact: true, mayShowUi: false },
|
||||
});
|
||||
expect(
|
||||
CAPABILITIES.find((c) => c.operation === "analyze_function"),
|
||||
).toMatchObject({ effects: { mutatesArtifact: false } });
|
||||
expect(
|
||||
windowsP0Capabilities().find(
|
||||
(c) => c.operation === "annotate_native_function",
|
||||
),
|
||||
).toMatchObject({ available: false });
|
||||
expect(
|
||||
HOPPER_PROVIDER_TOOL_CONTRACTS.some(
|
||||
(c) => c.name === "annotate_native_function",
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -59,7 +59,7 @@ export type GhidraOperation =
|
||||
| GhidraInventoryOperation
|
||||
| GhidraFunctionOperation;
|
||||
|
||||
/** Owns one authenticated, private, read-only Ghidra headless session. */
|
||||
/** Owns an authenticated private Ghidra session with transport-bound mutation authority. */
|
||||
export class GhidraClient {
|
||||
readonly #options: Required<
|
||||
Pick<GhidraClientOptions, "startupTimeoutMs" | "transport" | "platform">
|
||||
@@ -406,6 +406,8 @@ export class GhidraClient {
|
||||
return err(this.#failure("protocol", "Ghidra run identity is missing"));
|
||||
const parsed = parseGhidraSessionInfo(value, {
|
||||
runId,
|
||||
expectedReadOnly:
|
||||
this.#options.transport === "authenticated-loopback-tcp",
|
||||
providerVersion: this.#options.providerVersion,
|
||||
profileDigest: this.#options.profileDigest,
|
||||
targetSha256: this.#options.targetSha256,
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
import { z } from "zod";
|
||||
import {
|
||||
nativeFunctionAnnotationsInputSchema,
|
||||
nativeFunctionAnnotationsSchema,
|
||||
} from "../domain/nativeFunctionAnnotations.js";
|
||||
import { nativeDataTypeSchema } from "../domain/nativeDataType.js";
|
||||
import {
|
||||
nativeInstructionSchema,
|
||||
@@ -27,8 +31,9 @@ import {
|
||||
ghidraProcedureIdentitySchema as procedureIdentity,
|
||||
} from "./GhidraInventoryValues.js";
|
||||
|
||||
/** Read-only function operations admitted by the Ghidra adapter. */
|
||||
/** Function analysis and annotation operations admitted by the Ghidra adapter. */
|
||||
export const GHIDRA_FUNCTION_OPERATIONS = [
|
||||
"annotate_native_function",
|
||||
"inspect_native_data_type",
|
||||
"inspect_native_instruction",
|
||||
"resolve_native_call_targets",
|
||||
@@ -59,6 +64,7 @@ const procedure = ghidraIdentifierSchema;
|
||||
const directProcedure = { document, procedure };
|
||||
|
||||
const inputSchemas = {
|
||||
annotate_native_function: nativeFunctionAnnotationsInputSchema,
|
||||
inspect_native_data_type: z
|
||||
.object({
|
||||
document,
|
||||
@@ -356,6 +362,9 @@ const ghidraFunctionInstructionWindow = functionInstructionWindowSchema
|
||||
.strict();
|
||||
|
||||
const resultSchemas = {
|
||||
annotate_native_function: nativeFunctionAnnotationsSchema.safeExtend({
|
||||
dossier: ghidraFunctionDossier,
|
||||
}),
|
||||
analyze_function: ghidraFunctionDossier,
|
||||
procedure_assembly: z.string(),
|
||||
procedure_callees: z.array(ghidraCanonicalAddressSchema),
|
||||
|
||||
@@ -209,6 +209,19 @@ describe("Ghidra provider", () => {
|
||||
});
|
||||
|
||||
describe("Ghidra platform support", () => {
|
||||
it("keeps Windows annotation mutation unavailable independently of native controls", () => {
|
||||
const ghidra = provider({ ...installationHost(), platform: "win32" });
|
||||
expect(
|
||||
ghidra
|
||||
.capabilities()
|
||||
.find(({ operation }) => operation === "annotate_native_function"),
|
||||
).toMatchObject({
|
||||
available: false,
|
||||
reason: "Windows Ghidra P0 does not admit database mutation.",
|
||||
availabilityCode: "unsupported_host",
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps Windows P0 unavailable until native isolation authority exists", () => {
|
||||
const ghidra = provider({ ...installationHost(), platform: "win32" });
|
||||
const nativeApplication = peTarget("x86_64");
|
||||
@@ -343,7 +356,8 @@ describe("Ghidra client projection", () => {
|
||||
expect(resolved.value.profile).toMatchObject({
|
||||
provider: { id: "ghidra", name: "Ghidra", version: "12.1.4" },
|
||||
parameters: {
|
||||
import_mode: "ephemeral-read-only",
|
||||
import_mode: "ephemeral-source-immutable",
|
||||
annotation_policy: "atomic-function-entry-metadata-v1",
|
||||
analyzer_preset: "ghidra-default",
|
||||
},
|
||||
});
|
||||
@@ -452,6 +466,46 @@ describe("Ghidra result projection", () => {
|
||||
},
|
||||
);
|
||||
|
||||
it("preserves the rejected name constraint and function address", async () => {
|
||||
const message =
|
||||
"Invalid function name at 0x10100: Symbol name contains invalid characters";
|
||||
const ghidra = provider(installationHost(), () => ({
|
||||
start: () => Promise.resolve(ok(sessionInfo())),
|
||||
callTool: () =>
|
||||
Promise.resolve(
|
||||
err(
|
||||
new GhidraSessionError(
|
||||
"remote",
|
||||
message,
|
||||
{},
|
||||
{ remoteCode: "invalid_function_name" },
|
||||
),
|
||||
),
|
||||
),
|
||||
close: () => Promise.resolve(),
|
||||
}));
|
||||
const resolved = await ghidra.resolveAnalysisProfile(
|
||||
executableTarget("elf", "x86_64"),
|
||||
);
|
||||
if (!resolved.ok) throw resolved.error;
|
||||
if (resolved.value.profile === null)
|
||||
throw new Error("Expected a bound profile");
|
||||
await expect(
|
||||
ghidra
|
||||
.createClient(executableTarget("elf", "x86_64"), resolved.value.profile)
|
||||
.execute("annotate_native_function", {
|
||||
procedure: "0x10100",
|
||||
name: "bad name",
|
||||
}),
|
||||
).resolves.toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
_tag: "AnalysisInputError",
|
||||
issues: [{ path: ["name"], reason: "invalid_value", message }],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("projects remote decompile cancellation as a provider-neutral interruption", async () => {
|
||||
const code = "decompile_cancelled";
|
||||
const tag = "AnalysisCancelledError";
|
||||
@@ -566,7 +620,7 @@ const sessionInfo = () => ({
|
||||
run_id: "11111111-1111-4111-8111-111111111111",
|
||||
profile_digest: "a".repeat(64),
|
||||
provider: { id: "ghidra" as const, version: "12.1.4" },
|
||||
read_only: true as const,
|
||||
read_only: false as const,
|
||||
analysis_complete: true,
|
||||
analysis_timed_out: false,
|
||||
capabilities: [...GHIDRA_SESSION_CAPABILITIES],
|
||||
|
||||
@@ -7,11 +7,13 @@ import { GHIDRA_INVENTORY_OPERATIONS } from "./GhidraInventoryValues.js";
|
||||
import { GhidraProvider } from "./GhidraProvider.js";
|
||||
|
||||
describe("Ghidra provider capabilities", () => {
|
||||
it("publishes only admitted read-only operations and resists caller mutation", () => {
|
||||
it("publishes admitted operation effects and resists caller mutation", () => {
|
||||
const config = parseConfig({});
|
||||
expect(config.ok).toBe(true);
|
||||
if (!config.ok) return;
|
||||
const provider = new GhidraProvider(config.value, silentLogger, {
|
||||
platform: "linux",
|
||||
architecture: "x64",
|
||||
readText: () => undefined,
|
||||
executable: () => false,
|
||||
probeJava: () => undefined,
|
||||
@@ -26,7 +28,7 @@ describe("Ghidra provider capabilities", () => {
|
||||
available: true,
|
||||
reason: null,
|
||||
effects: {
|
||||
mutatesArtifact: false,
|
||||
mutatesArtifact: descriptor.operation === "annotate_native_function",
|
||||
mayShowUi: false,
|
||||
mayAccessNetwork: false,
|
||||
changesPermissions: false,
|
||||
|
||||
@@ -81,7 +81,7 @@ export type GhidraProviderClientFactory = (
|
||||
) => Pick<GhidraClient, "start" | "callTool" | "close"> &
|
||||
Partial<Pick<GhidraClient, "runtimeLineage" | "readTargetSnapshot">>;
|
||||
|
||||
/** Ghidra candidate backed by an isolated read-only headless import. */
|
||||
/** Ghidra candidate backed by an isolated ephemeral headless import. */
|
||||
export class GhidraProvider implements AnalysisProviderCandidate {
|
||||
#installation: GhidraInstallationInspection | undefined;
|
||||
|
||||
@@ -475,6 +475,14 @@ const projectSessionError = (
|
||||
operation: AnalysisOperation,
|
||||
failure: GhidraSessionError,
|
||||
): AnalysisError => {
|
||||
if (
|
||||
operation === "annotate_native_function" &&
|
||||
failure.kind === "remote" &&
|
||||
failure.remoteCode === "invalid_function_name"
|
||||
)
|
||||
return new AnalysisInputError(operation, { cause: failure }, [
|
||||
{ path: ["name"], reason: "invalid_value", message: failure.message },
|
||||
]);
|
||||
if (failure.kind === "cancelled")
|
||||
return new AnalysisCancelledError(operation);
|
||||
if (failure.kind === "timeout" || failure.kind === "analysis_timeout")
|
||||
|
||||
@@ -23,7 +23,7 @@ const providerContractByName = new Map(
|
||||
).map((contract) => [contract.name, contract]),
|
||||
);
|
||||
|
||||
/** Provider-neutral read-only contracts implemented by the Ghidra adapter. */
|
||||
/** Provider-neutral contracts implemented by the Ghidra adapter. */
|
||||
export const GHIDRA_PROVIDER_TOOL_CONTRACTS = Object.freeze(
|
||||
[...GHIDRA_INVENTORY_OPERATIONS, ...GHIDRA_FUNCTION_OPERATIONS].map(
|
||||
(operation) => {
|
||||
@@ -40,7 +40,7 @@ export const GHIDRA_PROVIDER_TOOL_CONTRACTS = Object.freeze(
|
||||
/** Health limitations shared by every Ghidra-backed capability. */
|
||||
export const healthLimitations = Object.freeze([
|
||||
"The session serves operations only after Ghidra reports default auto-analysis complete; incomplete analysis does not expose partial results.",
|
||||
"The imported Program and temporary project are ephemeral, read-only to REA, and deleted on close.",
|
||||
"The imported Program and temporary project are ephemeral and deleted on close. Annotation operations edit session database metadata; original executable bytes are never written.",
|
||||
]);
|
||||
|
||||
/** Additional limitations applied to the experimental Windows x64 P0 boundary. */
|
||||
@@ -57,6 +57,12 @@ export const limitationsFor = (operation: string): readonly string[] => {
|
||||
"Default-space addresses use lowercase 0x-prefixed hexadecimal; other address spaces use <percent-encoded-space>:0x<hex>.",
|
||||
];
|
||||
switch (operation) {
|
||||
case "annotate_native_function":
|
||||
return [
|
||||
...common,
|
||||
"Names use Ghidra USER_DEFINED source. Name writes preserve the existing namespace; readback uses the fully qualified name. Regular comments map to PRE and inline comments to EOL at the exact function entry. Changes commit together after readback and refreshed analysis; failure rolls them all back.",
|
||||
"Metadata edits invalidate immutable analysis snapshots and are discarded on close. CLI returns the updated dossier before session cleanup; this is not a saved Ghidra project.",
|
||||
];
|
||||
case "inspect_native_load_image":
|
||||
return [
|
||||
...common,
|
||||
@@ -161,7 +167,7 @@ export const CAPABILITIES: readonly CapabilityDescriptor[] = Object.freeze(
|
||||
available: true,
|
||||
reason: null,
|
||||
effects: Object.freeze({
|
||||
mutatesArtifact: false,
|
||||
mutatesArtifact: operation === "annotate_native_function",
|
||||
launchesProcess: true,
|
||||
mayShowUi: false,
|
||||
mayAccessNetwork: false,
|
||||
@@ -183,6 +189,14 @@ export const windowsP0Capabilities = (): readonly CapabilityDescriptor[] => {
|
||||
...capability.limitations,
|
||||
...windowsP0Limitations,
|
||||
]);
|
||||
if (capability.effects.mutatesArtifact)
|
||||
return Object.freeze({
|
||||
...capability,
|
||||
available: false,
|
||||
reason: "Windows Ghidra P0 does not admit database mutation.",
|
||||
availabilityCode: "unsupported_host",
|
||||
limitations,
|
||||
});
|
||||
return available
|
||||
? Object.freeze({ ...capability, limitations })
|
||||
: Object.freeze({
|
||||
|
||||
@@ -21,7 +21,7 @@ const session = (
|
||||
run_id: expected.runId,
|
||||
profile_digest: expected.profileDigest,
|
||||
provider: { id: "ghidra", version: expected.providerVersion },
|
||||
read_only: true,
|
||||
read_only: false,
|
||||
analysis_complete: true,
|
||||
analysis_timed_out: false,
|
||||
capabilities: [...GHIDRA_SESSION_CAPABILITIES],
|
||||
@@ -50,3 +50,46 @@ describe("Ghidra DOS import commitment", () => {
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Ghidra mutation handshake", () => {
|
||||
it("requires the exact mutation authority and rejects duplicate capabilities", () => {
|
||||
const value = session();
|
||||
expect(
|
||||
parseGhidraSessionInfo({ ...value, read_only: true }, expected).ok,
|
||||
).toBe(false);
|
||||
expect(
|
||||
parseGhidraSessionInfo(
|
||||
{ ...value, capabilities: [...value.capabilities, "ping"] },
|
||||
expected,
|
||||
).ok,
|
||||
).toBe(false);
|
||||
expect(
|
||||
parseGhidraSessionInfo(
|
||||
{
|
||||
...value,
|
||||
capabilities: value.capabilities.filter(
|
||||
(c) => c !== "annotate_native_function",
|
||||
),
|
||||
},
|
||||
expected,
|
||||
).ok,
|
||||
).toBe(false);
|
||||
});
|
||||
it("excludes database mutation from the Windows transport handshake", () => {
|
||||
const value = session();
|
||||
const windows = {
|
||||
...value,
|
||||
read_only: true,
|
||||
capabilities: value.capabilities.filter(
|
||||
(c) => c !== "annotate_native_function",
|
||||
),
|
||||
};
|
||||
expect(
|
||||
parseGhidraSessionInfo(windows, { ...expected, expectedReadOnly: true })
|
||||
.ok,
|
||||
).toBe(true);
|
||||
expect(
|
||||
parseGhidraSessionInfo(value, { ...expected, expectedReadOnly: true }).ok,
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -26,12 +26,10 @@ const sessionInfoSchema = z
|
||||
version: z.string().min(1),
|
||||
})
|
||||
.strict(),
|
||||
read_only: z.literal(true),
|
||||
read_only: z.boolean(),
|
||||
analysis_complete: z.boolean(),
|
||||
analysis_timed_out: z.boolean(),
|
||||
capabilities: z
|
||||
.array(capabilitySchema)
|
||||
.length(GHIDRA_SESSION_CAPABILITIES.length),
|
||||
capabilities: z.array(capabilitySchema),
|
||||
target: z
|
||||
.object({
|
||||
name: z.string().min(1),
|
||||
@@ -56,14 +54,21 @@ export const parseGhidraSessionInfo = (
|
||||
readonly providerVersion: string;
|
||||
readonly profileDigest: string;
|
||||
readonly targetSha256: string;
|
||||
readonly expectedReadOnly?: boolean;
|
||||
readonly expectedLanguageId?: string;
|
||||
readonly expectedCompilerSpecId?: string;
|
||||
},
|
||||
): Result<GhidraSessionInfo, Error> => {
|
||||
const parsed = sessionInfoSchema.safeParse(value);
|
||||
const readOnly = expected.expectedReadOnly ?? false;
|
||||
const expectedCapabilities = GHIDRA_SESSION_CAPABILITIES.filter(
|
||||
(capability) => !readOnly || capability !== "annotate_native_function",
|
||||
);
|
||||
if (
|
||||
!parsed.success ||
|
||||
parsed.data.run_id !== expected.runId ||
|
||||
parsed.data.read_only !== readOnly ||
|
||||
parsed.data.capabilities.length !== expectedCapabilities.length ||
|
||||
parsed.data.provider.version !== expected.providerVersion ||
|
||||
parsed.data.profile_digest !== expected.profileDigest ||
|
||||
parsed.data.target.sha256 !== expected.targetSha256 ||
|
||||
@@ -72,9 +77,8 @@ export const parseGhidraSessionInfo = (
|
||||
(expected.expectedCompilerSpecId !== undefined &&
|
||||
parsed.data.target.compiler_spec_id !==
|
||||
expected.expectedCompilerSpecId) ||
|
||||
new Set(parsed.data.capabilities).size !==
|
||||
GHIDRA_SESSION_CAPABILITIES.length ||
|
||||
GHIDRA_SESSION_CAPABILITIES.some(
|
||||
new Set(parsed.data.capabilities).size !== expectedCapabilities.length ||
|
||||
expectedCapabilities.some(
|
||||
(capability) => !parsed.data.capabilities.includes(capability),
|
||||
) ||
|
||||
parsed.data.analysis_complete === parsed.data.analysis_timed_out
|
||||
|
||||
@@ -47,6 +47,7 @@ export const HOPPER_PROVIDER_TOOL_CONTRACTS = Object.freeze([
|
||||
...GENERATED_MCP_TOOL_CATALOG.filter(
|
||||
({ kind, name }) =>
|
||||
kind === "official-proxy" &&
|
||||
name !== "annotate_native_function" &&
|
||||
name !== "inspect_native_load_image" &&
|
||||
name !== "inspect_native_data_type" &&
|
||||
name !== "inspect_native_instruction" &&
|
||||
|
||||
@@ -134,6 +134,9 @@ const projectOfficialArguments = (
|
||||
contract: ToolContract,
|
||||
input: unknown,
|
||||
): Readonly<Record<string, JsonValue>> => {
|
||||
// Annotation omissions preserve existing values; they are not Python defaults.
|
||||
if (contract.name === "annotate_native_function")
|
||||
return jsonObjectSchema.parse(contract.inputSchema.parse(input));
|
||||
const parsed = jsonObjectSchema.parse(input);
|
||||
if (!(contract.inputSchema instanceof z.ZodObject))
|
||||
throw new TypeError(
|
||||
|
||||
Reference in New Issue
Block a user