fix(ghidra): expose terminal-call boundary assumptions

Preserve observed terminal-call sites and callee flags across function views, raw bridge responses, Evidence, and snapshot replay. Version analysis profiles so older unqualified results cannot be reused.

Qualify Ghidra function extents without changing external no-return flags or claiming recovery of excluded code.

Validation: 76 focused tests, check:fast, docs:check, formatting, and the full Ghidra 12.1.4 host lane pass. Real CLI and all five stdio MCP function views retain the terminal-call evidence; returning puts calls remain unflagged. The reported stripped Rust ELF and Windows host remain unverified.

Fixes #1658
This commit is contained in:
morluto
2026-10-11 09:08:01 +08:00
parent 4733fc810a
commit 69a8b3a954
16 changed files with 457 additions and 55 deletions
@@ -36,7 +36,7 @@ const functionWorkflow = <Name extends FunctionWorkflowName>(
export const FUNCTION_WORKFLOW_TOOL_CONTRACTS = [
functionWorkflow(
"analyze_function",
"Build a dossier for one native function identified by symbol or provider-returned address. Returns identity with complete inclusive body ranges or explicit unknown, provider-specific pseudocode and assembly, comments, calls, references, referenced strings/names, local CFG blocks, and available native API boundary observations.",
"Build a dossier for one native function identified by symbol or provider-returned address. Returns identity with complete inclusive analyzed body ranges or explicit unknown, provider-specific pseudocode and assembly, comments, calls, references, referenced strings/names, local CFG blocks, and available native API boundary observations. Ghidra terminal-call assumptions that may cut the analyzed body are reported in limitations with available callee identities.",
),
functionWorkflow(
"inspect_native_api",
+4 -4
View File
@@ -144,7 +144,7 @@ export const OFFICIAL_TOOL_CONTRACTS = [
),
official(
"procedure_assembly",
"Return assembly for one analyzed procedure identified by symbol or hexadecimal address. Use when pseudocode loses calling-convention or instruction-level detail; output is currently returned as one unpaginated string.",
"Return assembly for one analyzed procedure identified by symbol or hexadecimal address. Use when pseudocode loses calling-convention or instruction-level detail; output is currently returned as one unpaginated string. Ghidra terminal-call assumptions that may cut the analyzed body are reported in Evidence limitations.",
z.object({ procedure, document }),
),
official(
@@ -159,12 +159,12 @@ export const OFFICIAL_TOOL_CONTRACTS = [
),
official(
"procedure_info",
"Return provider metadata for one procedure identified by symbol or address: entrypoint, signature, locals, size, block count, and complete inclusive body ranges when observed. Hopper locals preserve observed names and signed stack displacements; source types remain unknown. Body byte count and enclosing span remain distinct; unavailable extent is explicit.",
"Return provider metadata for one procedure identified by symbol or address: entrypoint, signature, locals, size, block count, and complete inclusive body ranges when observed. Extents reflect the provider's analyzed body; Ghidra terminal-call assumptions that may cut it are reported in Evidence limitations. Hopper locals preserve observed names and signed stack displacements; source types remain unknown. Body byte count and enclosing span remain distinct; unavailable extent is explicit.",
z.object({ procedure, document }),
),
official(
"read_function_instructions",
"Return every raw instruction for one analyzed procedure. Instruction text is provider-specific.",
"Return every raw instruction for one analyzed procedure. Instruction text and body extent are provider-specific. Ghidra terminal-call assumptions that may cut the analyzed body are reported in limitations.",
functionInstructionInputSchema,
),
...HOPPER_MEMORY_TOOL_DEFINITIONS.map(({ name, description, inputSchema }) =>
@@ -181,7 +181,7 @@ export const OFFICIAL_TOOL_CONTRACTS = [
),
official(
"procedure_pseudo_code",
"Decompile one analyzed procedure by symbol name or provider-normalized address. Returns provider-specific pseudocode, never original source or cross-provider text equivalence, and may return null; request procedure_assembly when instruction precision matters.",
"Decompile one analyzed procedure by symbol name or provider-normalized address. Returns provider-specific pseudocode, never original source or cross-provider text equivalence, and may return null; request procedure_assembly when instruction precision matters. Ghidra no-return assumptions may cut the analyzed body; Evidence limitations report observed terminal calls and available callee identities.",
z.object({ procedure, document }),
),
official(
+1
View File
@@ -70,6 +70,7 @@ export const resolveGhidraAnalysisProfile = (
string_inventory_evidence: "defined-data-coverage-v1",
location_resolution: "explicit-address-exact-entry-symbol-first-v3",
instruction_flow_evidence: "decoded-return-pcode-v1",
function_boundary_observations: "ghidra-terminal-call-limitations-v1",
process_launch:
installation.platform === "win32"
? "official-headless-script-v1"
+66 -18
View File
@@ -20,7 +20,55 @@ import {
ghidraReferenceEdge,
} from "../domain/ghidraValues.fixture.js";
const observationOperations: ReadonlySet<GhidraFunctionOperation> = new Set([
"analyze_function",
"procedure_assembly",
"procedure_info",
"procedure_pseudo_code",
"read_function_instructions",
]);
// Existing assertions focus on the value schema; this helper builds the current
// bridge envelope and returns its normalized value for those assertions.
const parseFunctionValueFixture = (
operation: GhidraFunctionOperation,
value: JsonValue,
) => {
const wireValue = observationOperations.has(operation)
? { value, limitations: [] }
: value;
const parsed = parseGhidraFunctionResult(operation, wireValue);
return parsed.ok ? { ok: true as const, value: parsed.value.value } : parsed;
};
describe("Ghidra function-analysis result values", () => {
it.each([...observationOperations])(
"requires the function-observation limitations envelope for %s",
(operation) => {
expect(parseGhidraFunctionResult(operation, null)).toMatchObject({
ok: false,
error: { _tag: "AnalysisOutputError" },
});
},
);
it("preserves a named function-observation limitation", () => {
expect(
parseGhidraFunctionResult("procedure_pseudo_code", "void f() {}"),
).toMatchObject({ ok: false, error: { _tag: "AnalysisOutputError" } });
const limitation =
"Ghidra marks a call to external __tls_get_addr terminal; return behavior is not independently verified.";
expect(
parseGhidraFunctionResult("procedure_pseudo_code", {
value: "void f() {}",
limitations: [limitation],
}),
).toEqual({
ok: true,
value: { value: "void f() {}", limitations: [limitation] },
});
});
it.each(["reference_kinds_available", "unresolved_calls"])(
"rejects omitted %s instead of inventing complete reference observations",
(field) => {
@@ -35,10 +83,10 @@ describe("Ghidra function-analysis result values", () => {
Object.entries(output).filter(([key]) => key !== field),
);
expect(
parseGhidraFunctionResult("procedure_references", output),
parseFunctionValueFixture("procedure_references", output),
).toMatchObject({ ok: true });
expect(
parseGhidraFunctionResult("procedure_references", incomplete),
parseFunctionValueFixture("procedure_references", incomplete),
).toMatchObject({ ok: false, error: { _tag: "AnalysisOutputError" } });
},
);
@@ -80,7 +128,7 @@ describe("Ghidra function-analysis result values", () => {
);
expect(
parseGhidraFunctionResult(
parseFunctionValueFixture(
"analyze_function",
jsonValueSchema.parse({
...dossier,
@@ -103,7 +151,7 @@ describe("Ghidra function-analysis result values", () => {
if (typeof flow !== "object" || flow === null || Array.isArray(flow))
throw new TypeError("Ghidra p-code fixture is invalid");
expect(
parseGhidraFunctionResult("analyze_function", {
parseFunctionValueFixture("analyze_function", {
...dossier,
native_value_flow: {
...flow,
@@ -159,7 +207,7 @@ describe("Ghidra compact reference provenance", () => {
};
for (const reference of [complete, legacy, unknown]) {
const expected = output([reference]);
const parsed = parseGhidraFunctionResult(operation, expected);
const parsed = parseFunctionValueFixture(operation, expected);
if (!parsed.ok) throw parsed.error;
expect(parsed.value).toEqual(expected);
}
@@ -179,7 +227,7 @@ describe("Ghidra compact reference provenance", () => {
["source", false],
] as const) {
expect(
parseGhidraFunctionResult(
parseFunctionValueFixture(
operation,
output([{ ...compactReference(), [field]: value }]),
),
@@ -215,7 +263,7 @@ describe("Ghidra jump-table mapping contract", () => {
],
},
];
const parsed = parseGhidraFunctionResult("analyze_function", {
const parsed = parseFunctionValueFixture("analyze_function", {
...dossier,
native_api: {
...boundary,
@@ -255,7 +303,7 @@ describe("Ghidra jump-table mapping contract", () => {
throw new TypeError("Ghidra jump-table fixture is unavailable");
const { default_targets: omittedDefaults, ...withoutDefaults } = table;
expect(omittedDefaults).toHaveLength(1);
const parsed = parseGhidraFunctionResult("analyze_function", {
const parsed = parseFunctionValueFixture("analyze_function", {
...dossier,
native_api: {
...boundary,
@@ -288,7 +336,7 @@ describe("Ghidra jump-table mapping contract", () => {
{ target_address: "0x401020", confidence: "high", evidence: [] },
]) {
expect(
parseGhidraFunctionResult("analyze_function", {
parseFunctionValueFixture("analyze_function", {
...dossier,
native_api: {
...boundary,
@@ -304,7 +352,7 @@ describe("Ghidra function-analysis malformed results", () => {
it.each(malformedOutputs())(
"rejects malformed %s output",
(_name, operation, value) => {
expect(parseGhidraFunctionResult(operation, value)).toMatchObject({
expect(parseFunctionValueFixture(operation, value)).toMatchObject({
ok: false,
error: { _tag: "AnalysisOutputError" },
});
@@ -438,7 +486,7 @@ describe("complete Ghidra function body range evidence", () => {
body: body(),
});
it("preserves inclusive disjoint ranges and distinguishes owned bytes from enclosing span", () => {
expect(parseGhidraFunctionResult("procedure_info", info())).toMatchObject({
expect(parseFunctionValueFixture("procedure_info", info())).toMatchObject({
ok: true,
value: { body: body(), length: 5 },
});
@@ -446,7 +494,7 @@ describe("complete Ghidra function body range evidence", () => {
it("rejects omitted body evidence instead of accepting a length as complete coverage", () => {
const { body: omitted, ...withoutBody } = info();
expect(omitted.total_bytes).toBe(5);
expect(parseGhidraFunctionResult("procedure_info", withoutBody).ok).toBe(
expect(parseFunctionValueFixture("procedure_info", withoutBody).ok).toBe(
false,
);
});
@@ -460,14 +508,14 @@ describe("complete Ghidra function body range evidence", () => {
contains_entry: false,
};
expect(
parseGhidraFunctionResult("procedure_info", {
parseFunctionValueFixture("procedure_info", {
...info(),
body: empty,
length: 0,
}).ok,
).toBe(false);
expect(
parseGhidraFunctionResult("procedure_info", {
parseFunctionValueFixture("procedure_info", {
...info(),
classification: { ...ghidraFunctionClassification(), external: true },
body: empty,
@@ -480,7 +528,7 @@ describe("complete Ghidra function body range evidence", () => {
const { body: omitted, ...identity } = ghidraFunctionIdentity();
expect(omitted.total_bytes).toBe(6);
expect(
parseGhidraFunctionResult("analyze_function", {
parseFunctionValueFixture("analyze_function", {
...dossier,
callers: [identity],
}).ok,
@@ -488,10 +536,10 @@ describe("complete Ghidra function body range evidence", () => {
});
it("requires body length and Ghidra-specific body provenance", () => {
expect(
parseGhidraFunctionResult("procedure_info", { ...info(), length: 18 }).ok,
parseFunctionValueFixture("procedure_info", { ...info(), length: 18 }).ok,
).toBe(false);
expect(
parseGhidraFunctionResult("procedure_info", {
parseFunctionValueFixture("procedure_info", {
...info(),
body: { ...body(), provenance: "unreviewed" },
}).ok,
@@ -511,7 +559,7 @@ describe("complete Ghidra function body range evidence", () => {
{ ranges: [{ start: "0x401002", end: "0x401000" }] },
])("rejects contradictory complete body facts %j", (change) => {
expect(
parseGhidraFunctionResult("procedure_info", {
parseFunctionValueFixture("procedure_info", {
...info(),
body: { ...body(), ...change },
}).ok,
+43 -3
View File
@@ -387,14 +387,54 @@ const resultSchemas = {
xrefs: z.array(ghidraCanonicalAddressSchema),
} satisfies Readonly<Record<GhidraFunctionOperation, z.ZodType>>;
const functionBoundaryObservationOperations: ReadonlySet<GhidraFunctionOperation> =
new Set([
"analyze_function",
"procedure_assembly",
"procedure_info",
"procedure_pseudo_code",
"read_function_instructions",
]);
const functionObservationEnvelope = z.strictObject({
value: z.unknown(),
limitations: z.array(z.string()),
});
export interface ParsedGhidraFunctionResult {
readonly value: JsonValue;
readonly limitations: readonly string[];
}
/** Require exact, bounded Java-bridge function output before creating Evidence. */
export const parseGhidraFunctionResult = (
operation: GhidraFunctionOperation,
value: JsonValue,
): Result<JsonValue, AnalysisOutputError> => {
const parsed = resultSchemas[operation].safeParse(value);
): Result<ParsedGhidraFunctionResult, AnalysisOutputError> => {
let observation: {
readonly value: unknown;
readonly limitations: readonly string[];
};
if (functionBoundaryObservationOperations.has(operation)) {
const envelope = functionObservationEnvelope.safeParse(value);
if (!envelope.success)
return err(
new AnalysisOutputError(
operation,
"Ghidra bridge omitted the function observation envelope",
{ cause: envelope.error },
),
);
observation = envelope.data;
} else {
observation = { value, limitations: [] };
}
const parsed = resultSchemas[operation].safeParse(observation.value);
return parsed.success
? ok(jsonValueSchema.parse(parsed.data))
? ok({
value: jsonValueSchema.parse(parsed.data),
limitations: observation.limitations,
})
: err(
new AnalysisOutputError(
operation,
@@ -562,6 +562,31 @@ describe("Ghidra result projection", () => {
});
});
it("projects terminal-call facts from the function bridge into execution limitations", async () => {
const limitation =
"Ghidra Listing reports a terminal call at 0x401020 to 0x7f001000 __tls_get_addr (external=true, thunk=false, hasNoReturn=true); fallthrough is excluded by Ghidra's flow model. This records Ghidra's FunctionManager flag, not an independent verification that the callee cannot return.";
const ghidra = provider(installationHost(), () => ({
start: () => Promise.resolve(ok(sessionInfo())),
callTool: () =>
Promise.resolve(
ok({ value: "void main() {}", limitations: [limitation] }),
),
close: () => Promise.resolve(ok(null)),
}));
const client = await createElfClient(ghidra);
const execution = await client.execute("procedure_pseudo_code", {
procedure: "main",
});
if (!execution.ok) throw execution.error;
expect(execution.value.result).toBe("void main() {}");
expect(execution.value.limitations).toContain(limitation);
expect(execution.value.rawResult).toEqual({
value: "void main() {}",
limitations: [limitation],
});
await client.close();
});
it.each([
["invalid_request", "AnalysisInputError"],
["not_found", "AnalysisInputError"],
+19 -7
View File
@@ -8,6 +8,7 @@ import {
type AnalysisOperation,
} from "../application/AnalysisProvider.js";
import type { AppConfig } from "../config/types.js";
import type { JsonValue } from "../domain/jsonValue.js";
import type { AnalysisProfileCommitment } from "../domain/analysisProfile.js";
import type { BinaryTarget } from "../domain/binaryTargetTypes.js";
import {
@@ -263,16 +264,23 @@ export const createGhidraProviderClient = (input: {
config.ghidraStartupTimeoutMs,
),
);
const result = isGhidraFunctionOperation(operation)
? parseGhidraFunctionResult(operation, called.value)
: parseGhidraInventoryResult(operation, called.value);
if (!result.ok) return result;
let normalized = result.value;
let normalized: JsonValue;
let observationLimitations: readonly string[] = [];
if (isGhidraFunctionOperation(operation)) {
const result = parseGhidraFunctionResult(operation, called.value);
if (!result.ok) return result;
normalized = result.value.value;
observationLimitations = result.value.limitations;
} else {
const result = parseGhidraInventoryResult(operation, called.value);
if (!result.ok) return result;
normalized = result.value;
}
if (operation === "inspect_native_load_image") {
const attested = await attestGhidraNativeLoadImage(
target,
operation,
result.value,
normalized,
client,
(failure) =>
projectSessionError(
@@ -288,7 +296,11 @@ export const createGhidraProviderClient = (input: {
createAnalysisExecution(normalized, committedProfile.provider, {
rawResult: called.value,
analysisProfile: committedProfile,
limitations: [...limitationsFor(operation), ...sessionLimitations],
limitations: [
...limitationsFor(operation),
...observationLimitations,
...sessionLimitations,
],
}),
);
},
+6 -1
View File
@@ -104,8 +104,13 @@ const fixture = (version = "12.1.4") => {
persists_after_close: false,
},
});
const value =
operation === "procedure_pseudo_code" ? dossier.pseudocode : dossier;
return ok(
operation === "procedure_pseudo_code" ? dossier.pseudocode : dossier,
operation === "procedure_pseudo_code" ||
operation === "analyze_function"
? { value, limitations: [] }
: value,
);
},
close: async () => ok(null),