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:
N0zoM1z0
2026-10-06 17:24:33 +08:00
committed by GitHub
parent c3bc38bf6c
commit 9bab55337a
49 changed files with 730 additions and 72 deletions
+2 -1
View File
@@ -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
+114
View File
@@ -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);
});
});
+3 -1
View File
@@ -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,
+10 -1
View File
@@ -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),
+56 -2
View File
@@ -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],
+4 -2
View File
@@ -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,
+9 -1
View File
@@ -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")
+17 -3
View File
@@ -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({
+44 -1
View File
@@ -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);
});
});
+11 -7
View File
@@ -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