feat(ghidra): add function analysis and conformance

This commit is contained in:
N0zoM1z0
2026-07-16 04:17:08 +09:00
committed by N0zoM1z0
parent a45de27d9e
commit d8321defd7
131 changed files with 4224 additions and 301 deletions
+2 -2
View File
@@ -7,12 +7,12 @@ export const enhancedInputSchemas = {
get_objc_protocols: z.object({}),
batch_decompile: z.object({
addresses: z
.array(z.string().describe("A Hopper address"))
.array(z.string().describe("A provider-normalized procedure address"))
.max(20)
.default([]),
}),
get_call_graph: z.object({
address: z.string().describe("A Hopper address"),
address: z.string().describe("A provider-normalized procedure address"),
direction: z.enum(["forward", "backward"]).default("forward"),
depth: z.number().int().min(1).max(5).default(2),
}),
+7 -7
View File
@@ -251,12 +251,12 @@ export const OFFICIAL_TOOL_CONTRACTS = [
),
official(
"procedure_callees",
"Return Hopper's analyzed direct callees for one procedure identified by symbol or address. Indirect calls may be absent; use analyze_function and xrefs to corroborate the call path.",
"Return the provider's resolved direct callees for one procedure identified by symbol or address. Unresolved indirect calls may be absent; use analyze_function and typed references to preserve available edge uncertainty.",
z.object({ procedure, document }),
),
official(
"procedure_callers",
"Return Hopper's analyzed direct callers for one procedure identified by symbol or address. Results reflect completed static analysis and may omit indirect references.",
"Return the provider's resolved direct callers for one procedure identified by symbol or address. Results reflect completed static analysis and may omit unresolved indirect references.",
z.object({ procedure, document }),
),
official(
@@ -266,7 +266,7 @@ export const OFFICIAL_TOOL_CONTRACTS = [
),
official(
"procedure_references",
"Return a bounded set of raw incoming or outgoing reference edges for one procedure. Endpoint procedures are resolved only when Hopper reports containment; reference kinds remain explicitly unavailable.",
"Return a bounded set of raw incoming or outgoing reference edges for one procedure. Endpoint procedures are resolved only from provider containment; Ghidra preserves observed reference kinds while providers without kind authority mark them unavailable.",
z.object({
procedure,
direction: z.enum(["incoming", "outgoing"]).default("outgoing"),
@@ -278,7 +278,7 @@ export const OFFICIAL_TOOL_CONTRACTS = [
),
official(
"procedure_pseudo_code",
"Decompile one analyzed procedure by symbol name or hexadecimal address. Returns Hopper pseudocode, not original source, 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.",
z.object({ procedure, document }),
),
official(
@@ -365,7 +365,7 @@ export const ENHANCED_TOOL_CONTRACTS = [
),
enhanced(
"get_call_graph",
"Traverse Hopper's caller or callee relationships from one symbol or address for at most five levels. Every node has an ok/error status and failures use safe typed projections; indirect calls may be missing and results are not a whole-program CFG.",
"Traverse the bound provider's caller or callee relationships from one symbol or address for at most five levels. Every node has an ok/error status and failures use safe typed projections; unresolved indirect calls may be missing and results are not a whole-program CFG.",
enhancedInputSchemas.get_call_graph,
),
enhanced(
@@ -375,7 +375,7 @@ export const ENHANCED_TOOL_CONTRACTS = [
),
enhanced(
"find_xrefs_to_name",
"Resolve an exact name through Hopper's exhaustively paged name inventory and return a resolved or unresolved result. Unresolved names use the stable name_not_found reason; xrefs remain untyped.",
"Resolve an exact name through the bound provider's exhaustively paged name inventory and return a resolved or unresolved result. Unresolved names use the stable name_not_found reason; this compact xref workflow returns address-only projections.",
enhancedInputSchemas.find_xrefs_to_name,
),
enhanced(
@@ -385,7 +385,7 @@ export const ENHANCED_TOOL_CONTRACTS = [
),
enhanced(
"analyze_function",
"Preferred bounded analysis for one procedure symbol or address. Returns identity, pseudocode, optional assembly, comments, calls, incoming references, and blocks; unsupported outgoing references and CFG edges carry explicit unavailable metadata.",
"Preferred bounded analysis for one procedure symbol or address. Returns identity, provider-specific pseudocode, optional assembly, comments, calls, typed-or-explicitly-unavailable references, referenced strings/names, and local CFG blocks with exact truncation metadata.",
enhancedInputSchemas.analyze_function,
),
enhanced(
+11 -7
View File
@@ -6,7 +6,13 @@ import {
} from "../domain/processCapture.js";
import { evidenceBundleSchema } from "../domain/evidenceBundle.js";
import { residualUnknownSchema } from "../domain/residualUnknown.js";
import { functionDossierSchema } from "../domain/hopperValues.js";
import {
functionDossierSchema,
localVariableSchema,
procedureClassificationSchema,
procedureIdentitySchema,
referenceKindSchema,
} from "../domain/hopperValues.js";
import {
demangleSwiftSchema,
inspectMachoSchema,
@@ -232,11 +238,8 @@ const sessionProvider = z.object({
const nullableText = z.string().nullable();
const addressList = z.array(z.string());
const addressedEntry = z.object({ address: z.string(), name: z.string() });
const procedureIdentity = z.object({ address: z.string(), name: z.string() });
const localVariable = z.object({
description: z.string(),
provenance: z.literal("hopper-public-python-api"),
});
const procedureIdentity = procedureIdentitySchema;
const localVariable = localVariableSchema;
const containingProcedureResolution = z.discriminatedUnion("found", [
z.object({
query_address: z.string(),
@@ -336,6 +339,7 @@ const procedureInfoOutput = resultOf(
length: z.number().min(0),
signature: nullableText,
locals: z.array(localVariable),
classification: procedureClassificationSchema.nullable().default(null),
}),
);
const symbolDiscoveryOutput = (property: "classes" | "protocols") =>
@@ -391,7 +395,7 @@ export const officialOutputSchemas: Readonly<Record<string, z.ZodObject>> = {
target_address: z.string(),
source_procedure: procedureIdentity.nullable(),
target_procedure: procedureIdentity.nullable(),
kind: unavailable,
kind: referenceKindSchema,
}),
),
instructions_scanned: z.number().int().min(0),
+17 -2
View File
@@ -13,6 +13,7 @@ import {
isAutoName,
normalizeCfg,
project,
referenceKindProjection,
referenceProjection,
sorted,
stringAndNameProjection,
@@ -359,16 +360,30 @@ const compareReferences = (
rightCount: rightProjection.length,
textDelta: null,
limitations: [
"Reference endpoints differ; exact reference kinds remain unavailable.",
"Reference endpoints differ independently of provider reference-kind metadata.",
],
});
const leftKinds = referenceKindProjection(left);
const rightKinds = referenceKindProjection(right);
if (leftKinds !== null && rightKinds !== null)
return compareValues(
"references",
leftKinds,
rightKinds,
links,
true,
true,
providersDiffer,
);
return unresolvedDimension(
"references",
"unknown",
links,
leftProjection.length,
rightProjection.length,
["Reference kinds are unavailable in the current dossier contract."],
[
"At least one provider did not expose reference kinds, so equal endpoints do not prove equal edge semantics.",
],
);
};
@@ -83,6 +83,49 @@ export const referenceProjection = (snapshot: FunctionSnapshot) =>
})),
]);
export const referenceKindProjection = (
snapshot: FunctionSnapshot,
): readonly unknown[] | null => {
const edges = [
...snapshot.collections.incoming_references.items.map((edge) => ({
direction: "in",
edge,
})),
...snapshot.collections.outgoing_references.items.map((edge) => ({
direction: "out",
edge,
})),
];
if (edges.some(({ edge }) => !edge.kind.available)) return null;
return sorted(
edges.map(({ direction, edge }) => {
if (!edge.kind.available)
throw new TypeError(
"Reference-kind availability changed during projection",
);
return {
direction,
source: edge.source_procedure?.name ?? null,
target: edge.target_procedure?.name ?? null,
type: edge.kind.type,
flow: edge.kind.flow,
call: edge.kind.call,
jump: edge.kind.jump,
data: edge.kind.data,
read: edge.kind.read,
write: edge.kind.write,
indirect: edge.kind.indirect,
computed: edge.kind.computed,
conditional: edge.kind.conditional,
terminal: edge.kind.terminal,
primary: edge.kind.primary,
operand_index: edge.kind.operand_index,
external: edge.kind.external,
};
}),
);
};
export const commentProjection = (
snapshot: FunctionSnapshot,
): readonly unknown[] | null => {
+6 -1
View File
@@ -95,7 +95,12 @@ export const parseFunctionEvidence = (input: unknown): FunctionSnapshot => {
collections,
instructionScan: first.dossier.instruction_scan,
limitations: [
...new Set(pages.flatMap(({ evidence }) => evidence.limitations)),
...new Set(
pages.flatMap(({ evidence, dossier }) => [
...evidence.limitations,
...dossier.limitations,
]),
),
].sort((left, right) => left.localeCompare(right)),
};
};
+45 -7
View File
@@ -86,16 +86,28 @@ const addressedPageSchema = z
});
}
});
const unavailableSchema = z
const unavailableAnalysisFactSchema = z
.object({ available: z.literal(false), reason: z.string() })
.strict();
const procedureIdentitySchema = z
.object({ address: z.string(), name: z.string() })
export const procedureClassificationSchema = z
.object({
external: z.boolean(),
thunk: z.boolean(),
thunk_target: z.string().nullable(),
provenance: z.string().min(1),
})
.strict();
const localVariableSchema = z
export const procedureIdentitySchema = z
.object({
address: z.string(),
name: z.string(),
classification: procedureClassificationSchema.nullable().default(null),
})
.strict();
export const localVariableSchema = z
.object({
description: z.string(),
provenance: z.literal("hopper-public-python-api"),
provenance: z.string().min(1),
})
.strict();
const boundedSchema = <T extends z.ZodType>(item: T) =>
@@ -131,13 +143,37 @@ const boundedSchema = <T extends z.ZodType>(item: T) =>
});
}
});
const availableReferenceKindSchema = z
.object({
available: z.literal(true),
provenance: z.string().min(1),
type: z.string(),
flow: z.boolean(),
call: z.boolean(),
jump: z.boolean(),
data: z.boolean(),
read: z.boolean(),
write: z.boolean(),
indirect: z.boolean(),
computed: z.boolean(),
conditional: z.boolean(),
terminal: z.boolean(),
primary: z.boolean(),
operand_index: z.number().int(),
external: z.boolean(),
})
.strict();
export const referenceKindSchema = z.discriminatedUnion("available", [
unavailableAnalysisFactSchema,
availableReferenceKindSchema,
]);
const referenceEdgeSchema = z
.object({
source_address: z.string(),
target_address: z.string(),
source_procedure: procedureIdentitySchema.nullable(),
target_procedure: procedureIdentitySchema.nullable(),
kind: unavailableSchema,
kind: referenceKindSchema,
})
.strict();
export const functionDossierSchema = z
@@ -146,6 +182,7 @@ export const functionDossierSchema = z
.object({
address: z.string(),
name: z.string(),
classification: procedureClassificationSchema.nullable().default(null),
signature: z.string().nullable(),
locals: z.array(localVariableSchema),
})
@@ -226,13 +263,14 @@ export const functionDossierSchema = z
instruction_scan: z
.object({ scanned: z.number().int().min(0), truncated: z.boolean() })
.strict(),
limitations: z.array(z.string()).default([]),
})
.strict();
/** Strict analyzed-function dossier shared by provider and comparison boundaries. */
export type FunctionDossier = z.infer<typeof functionDossierSchema>;
/** Strictly parse a complete Hopper function dossier at the provider boundary. */
/** Strictly parse a complete provider-neutral function dossier. */
export const parseFunctionDossier = (
value: JsonValue,
): Result<JsonValue, AnalysisOutputError> => {
+30 -3
View File
@@ -16,6 +16,7 @@ import {
} from "../process/ProviderProcess.js";
import {
GHIDRA_MAX_LINE_BYTES,
GHIDRA_MAX_QUEUED_REQUESTS,
GHIDRA_REQUEST_TIMEOUT_MS,
GHIDRA_STARTUP_TIMEOUT_MS,
} from "./GhidraDefaults.js";
@@ -25,10 +26,12 @@ import type {
GhidraStartResult,
} from "./GhidraClientTypes.js";
import type { GhidraInventoryOperation } from "./GhidraInventoryValues.js";
import type { GhidraFunctionOperation } from "./GhidraFunctionValues.js";
import { createGhidraDiagnostics } from "./GhidraDiagnostics.js";
import type { GhidraLaunch } from "./GhidraLauncher.js";
import { GhidraResponseBuffer } from "./GhidraResponseBuffer.js";
import { GhidraResponseRouter } from "./GhidraResponseRouter.js";
import { GhidraRequestQueue } from "./GhidraRequestQueue.js";
import {
bindGhidraSessionFailure,
GhidraSessionError,
@@ -53,6 +56,11 @@ export type {
GhidraStartResult,
} from "./GhidraClientTypes.js";
/** Closed Java-bridge operation union callable after the exact handshake. */
export type GhidraOperation =
| GhidraInventoryOperation
| GhidraFunctionOperation;
/** Owns one authenticated, private, read-only Ghidra headless session. */
export class GhidraClient {
readonly #options: Required<
@@ -79,6 +87,7 @@ export class GhidraClient {
#startPromise: Promise<GhidraStartResult> | undefined;
#closePromise: Promise<void> | undefined;
readonly #failure = bindGhidraSessionFailure(() => this.#diagnostics());
readonly #requestQueue: GhidraRequestQueue;
readonly #responseRouter = new GhidraResponseRouter({
pending: this.#pending,
nextId: () => this.#nextId,
@@ -110,6 +119,18 @@ export class GhidraClient {
requestTimeoutMs: options.requestTimeoutMs ?? GHIDRA_REQUEST_TIMEOUT_MS,
startupTimeoutMs: options.startupTimeoutMs ?? GHIDRA_STARTUP_TIMEOUT_MS,
};
this.#requestQueue = new GhidraRequestQueue(
GHIDRA_MAX_QUEUED_REQUESTS,
(method, parameters, requestOptions) =>
this.#request(method, parameters, requestOptions),
(kind, message, timeoutMs) =>
this.#failure(
kind,
message,
undefined,
timeoutMs === undefined ? {} : { timeoutMs },
),
);
}
/** Launch Ghidra once and require its exact post-analysis handshake. */
@@ -150,15 +171,18 @@ export class GhidraClient {
return this.#parseSessionInfo(result.value);
}
/** Execute one admitted inventory operation after the exact session handshake. */
/** Execute one admitted operation through the bounded per-Program queue. */
async callTool(
operation: GhidraInventoryOperation,
operation: GhidraOperation,
parameters: Readonly<Record<string, JsonValue>>,
options: GhidraRequestOptions = {},
): Promise<Result<JsonValue, GhidraSessionError>> {
const started = await this.start(options.signal);
if (!started.ok) return started;
return this.#request(operation, parameters, options);
return this.#requestQueue.run(operation, parameters, {
...(options.signal === undefined ? {} : { signal: options.signal }),
timeoutMs: options.timeoutMs ?? this.#options.requestTimeoutMs,
});
}
/** Stop the owned process group and remove all project/runtime artifacts. */
@@ -406,6 +430,9 @@ export class GhidraClient {
async #cleanup(): Promise<void> {
this.#closing = true;
try {
this.#requestQueue.failQueued(
this.#failure("process", "Ghidra session closed"),
);
const socket = this.#socket;
if (socket !== undefined && !socket.destroyed) {
const shutdown = await this.#request(
+7 -1
View File
@@ -8,7 +8,13 @@ export const GHIDRA_MAX_HEAP = "2G";
export const GHIDRA_STARTUP_TIMEOUT_MS = 330_000;
/** Default bounded wait for one established bridge request. */
export const GHIDRA_REQUEST_TIMEOUT_MS = 10_000;
/** Per-function ceiling passed to Ghidra's native decompiler process. */
export const GHIDRA_DECOMPILE_TIMEOUT_SECONDS = 30;
/** Socket deadline leaves bounded time to project a native decompiler timeout. */
export const GHIDRA_DECOMPILE_REQUEST_TIMEOUT_MS = 35_000;
/** Maximum active plus queued calls for one serial headless Program. */
export const GHIDRA_MAX_QUEUED_REQUESTS = 32;
/** Maximum encoded response line accepted from the Java bridge. */
export const GHIDRA_MAX_LINE_BYTES = 1024 * 1024;
/** Version of REA's Java bridge handshake and request protocol. */
export const GHIDRA_BRIDGE_VERSION = 2;
export const GHIDRA_BRIDGE_VERSION = 3;
+329
View File
@@ -0,0 +1,329 @@
import { z } from "zod";
import { AnalysisInputError, AnalysisOutputError } from "../domain/errors.js";
import {
functionDossierSchema,
type FunctionDossier,
} from "../domain/hopperValues.js";
import {
jsonObjectSchema,
jsonValueSchema,
type JsonValue,
} from "../domain/jsonValue.js";
import { err, ok, type Result } from "../domain/result.js";
import {
ghidraBoundedIdentifierSchema,
ghidraCanonicalAddressSchema,
} from "./GhidraInventoryValues.js";
/** Read-only function operations admitted by the Ghidra adapter. */
export const GHIDRA_FUNCTION_OPERATIONS = [
"analyze_function",
"procedure_assembly",
"procedure_callees",
"procedure_callers",
"procedure_info",
"procedure_pseudo_code",
"procedure_references",
"xrefs",
] as const;
/** One function-analysis operation implemented by the packaged Java bridge. */
export type GhidraFunctionOperation =
(typeof GHIDRA_FUNCTION_OPERATIONS)[number];
const operationSet: ReadonlySet<string> = new Set(GHIDRA_FUNCTION_OPERATIONS);
/** Narrow an application operation to the Ghidra function-analysis surface. */
export const isGhidraFunctionOperation = (
operation: string,
): operation is GhidraFunctionOperation => operationSet.has(operation);
const document = ghidraBoundedIdentifierSchema.nullable().default(null);
const procedure = ghidraBoundedIdentifierSchema;
const directProcedure = { document, procedure };
const collectionOffsets = z
.object({
comments: z.number().int().min(0).default(0),
callers: z.number().int().min(0).default(0),
callees: z.number().int().min(0).default(0),
incoming_references: z.number().int().min(0).default(0),
outgoing_references: z.number().int().min(0).default(0),
referenced_strings: z.number().int().min(0).default(0),
referenced_names: z.number().int().min(0).default(0),
basic_blocks: z.number().int().min(0).default(0),
})
.strict()
.default({
comments: 0,
callers: 0,
callees: 0,
incoming_references: 0,
outgoing_references: 0,
referenced_strings: 0,
referenced_names: 0,
basic_blocks: 0,
});
const inputSchemas = {
analyze_function: z
.object({
procedure,
include_assembly: z.boolean().default(false),
limit: z.number().int().min(1).max(500).default(100),
max_pseudocode_chars: z
.number()
.int()
.min(1)
.max(100_000)
.default(20_000),
max_instructions: z.number().int().min(1).max(5_000).default(500),
pseudocode_offset: z.number().int().min(0).default(0),
assembly_offset: z.number().int().min(0).default(0),
collection_offset: collectionOffsets,
})
.strict(),
procedure_assembly: z.object(directProcedure).strict(),
procedure_callees: z.object(directProcedure).strict(),
procedure_callers: z.object(directProcedure).strict(),
procedure_info: z.object(directProcedure).strict(),
procedure_pseudo_code: z.object(directProcedure).strict(),
procedure_references: z
.object({
...directProcedure,
direction: z.enum(["incoming", "outgoing"]).default("outgoing"),
offset: z.number().int().min(0).default(0),
limit: z.number().int().min(1).max(500).default(100),
max_instructions: z.number().int().min(1).max(5_000).default(500),
})
.strict(),
xrefs: z.object({ document, address: ghidraCanonicalAddressSchema }).strict(),
} satisfies Readonly<Record<GhidraFunctionOperation, z.ZodType>>;
/** Validate and default one function request before it crosses the socket. */
export const parseGhidraFunctionInput = (
operation: GhidraFunctionOperation,
value: Readonly<Record<string, JsonValue>>,
): Result<Readonly<Record<string, JsonValue>>, AnalysisInputError> => {
const parsed = inputSchemas[operation].safeParse(value);
return parsed.success
? ok(jsonObjectSchema.parse(parsed.data))
: err(new AnalysisInputError(operation, { cause: parsed.error }));
};
const classification = z
.object({
external: z.boolean(),
thunk: z.boolean(),
thunk_target: ghidraCanonicalAddressSchema.nullable(),
provenance: z.literal("ghidra-function-manager"),
})
.strict();
const procedureIdentity = z
.object({
address: ghidraCanonicalAddressSchema,
name: z.string().min(1),
classification,
})
.strict();
const localVariable = z
.object({
description: z.string(),
provenance: z.literal("ghidra-function-database"),
})
.strict();
const referenceKind = z
.object({
available: z.literal(true),
provenance: z.literal("ghidra-reference-manager"),
type: z.string().min(1),
flow: z.boolean(),
call: z.boolean(),
jump: z.boolean(),
data: z.boolean(),
read: z.boolean(),
write: z.boolean(),
indirect: z.boolean(),
computed: z.boolean(),
conditional: z.boolean(),
terminal: z.boolean(),
primary: z.boolean(),
operand_index: z.number().int(),
external: z.boolean(),
})
.strict();
const referenceEdge = z
.object({
source_address: ghidraCanonicalAddressSchema,
target_address: ghidraCanonicalAddressSchema,
source_procedure: procedureIdentity.nullable(),
target_procedure: procedureIdentity.nullable(),
kind: referenceKind,
})
.strict();
const boundedReferences = z
.object({
items: z.array(referenceEdge),
total: z.number().int().min(0).nullable(),
returned: z.number().int().min(0),
truncated: z.boolean(),
next_offset: z.number().int().min(0).nullable(),
})
.strict()
.superRefine((value, context) => {
if (value.returned !== value.items.length)
context.addIssue({
code: "custom",
path: ["returned"],
message: "returned must equal the number of reference items",
});
if (value.total !== null && value.total < value.returned)
context.addIssue({
code: "custom",
path: ["total"],
message: "total cannot be smaller than returned",
});
if (value.next_offset !== null && !value.truncated)
context.addIssue({
code: "custom",
path: ["next_offset"],
message: "a continuation requires truncated output",
});
});
const procedureReferences = z
.object({
procedure: procedureIdentity,
direction: z.enum(["incoming", "outgoing"]),
references: boundedReferences,
instructions_scanned: z.number().int().min(0),
instruction_scan_truncated: z.boolean(),
})
.strict();
const procedureInfo = z
.object({
name: z.string().min(1),
entrypoint: ghidraCanonicalAddressSchema,
basicblock_count: z.number().int().min(0),
length: z.number().int().min(0),
signature: z.string().nullable(),
locals: z.array(localVariable),
classification,
})
.strict();
const ghidraFunctionDossier = functionDossierSchema.superRefine(
(value, context) => {
const addresses = [
value.procedure.address,
...value.comments.items.map(({ address }) => address),
...value.callers.items.map(({ address }) => address),
...value.callees.items.map(({ address }) => address),
...value.incoming_references.items.flatMap(referenceAddresses),
...value.outgoing_references.items.flatMap(referenceAddresses),
...value.referenced_strings.items.flatMap(
({ address, source_address }) => [address, source_address],
),
...value.referenced_names.items.flatMap(({ address, source_address }) => [
address,
source_address,
]),
...value.basic_blocks.items.flatMap(({ start, end, successors }) => [
start,
end,
...successors,
]),
];
if (
addresses.some(
(address) => !ghidraCanonicalAddressSchema.safeParse(address).success,
)
)
context.addIssue({
code: "custom",
message: "Ghidra dossier contains a non-canonical address",
});
const identities = [
value.procedure,
...value.callers.items,
...value.callees.items,
...value.incoming_references.items.flatMap(referenceProcedures),
...value.outgoing_references.items.flatMap(referenceProcedures),
];
if (
identities.some(
({ classification: facts }) => !classification.safeParse(facts).success,
)
)
context.addIssue({
code: "custom",
message: "Ghidra dossier omitted function classification",
});
if (
value.procedure.locals.some(
(variable) => !localVariable.safeParse(variable).success,
) ||
[
...value.incoming_references.items,
...value.outgoing_references.items,
].some(({ kind }) => !referenceKind.safeParse(kind).success)
)
context.addIssue({
code: "custom",
message: "Ghidra dossier contains invalid provenance",
});
if (
!value.limitations.some((item) => /indirect|computed/u.test(item)) ||
!value.limitations.some((item) => /provider|Ghidra|Hopper/u.test(item))
)
context.addIssue({
code: "custom",
message: "Ghidra dossier omitted required uncertainty limitations",
});
},
);
const resultSchemas = {
analyze_function: ghidraFunctionDossier,
procedure_assembly: z.string(),
procedure_callees: z.array(ghidraCanonicalAddressSchema),
procedure_callers: z.array(ghidraCanonicalAddressSchema),
procedure_info: procedureInfo,
procedure_pseudo_code: z.string().nullable(),
procedure_references: procedureReferences,
xrefs: z.array(ghidraCanonicalAddressSchema),
} satisfies Readonly<Record<GhidraFunctionOperation, z.ZodType>>;
/** 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);
return parsed.success
? ok(jsonValueSchema.parse(parsed.data))
: err(
new AnalysisOutputError(
operation,
"Ghidra bridge output did not match the function-analysis contract",
{ cause: parsed.error },
),
);
};
const referenceAddresses = (
edge: FunctionDossier["incoming_references"]["items"][number],
): readonly string[] => [
edge.source_address,
edge.target_address,
...(edge.source_procedure === null ? [] : [edge.source_procedure.address]),
...(edge.target_procedure === null ? [] : [edge.target_procedure.address]),
];
const referenceProcedures = (
edge: FunctionDossier["incoming_references"]["items"][number],
): readonly NonNullable<
FunctionDossier["incoming_references"]["items"][number]["source_procedure"]
>[] => [
...(edge.source_procedure === null ? [] : [edge.source_procedure]),
...(edge.target_procedure === null ? [] : [edge.target_procedure]),
];
+12 -3
View File
@@ -33,7 +33,8 @@ export const isGhidraInventoryOperation = (
operation: string,
): operation is GhidraInventoryOperation => operationSet.has(operation);
const boundedIdentifier = z.string().min(1).max(4096);
export const ghidraBoundedIdentifierSchema = z.string().min(1).max(4096);
const boundedIdentifier = ghidraBoundedIdentifierSchema;
const document = boundedIdentifier.nullable().default(null);
const explicitAddress = boundedIdentifier;
const filteredAddress = explicitAddress.nullable().default(null);
@@ -82,9 +83,10 @@ export const parseGhidraInventoryInput = (
return ok(jsonObjectSchema.parse(parsed.data));
};
const canonicalAddress = z
export const ghidraCanonicalAddressSchema = z
.string()
.regex(/^(?:0x[0-9a-f]+|(?:[A-Za-z0-9._~-]|%[0-9A-F]{2})+:0x[0-9a-f]+)$/u);
const canonicalAddress = ghidraCanonicalAddressSchema;
const valueTruncation = { value_truncated: z.boolean() };
const symbolFacts = z
.object({
@@ -102,6 +104,9 @@ const procedureFacts = z
thunk_target: canonicalAddress.nullable(),
})
.strict();
const functionClassification = procedureFacts
.extend({ provenance: z.literal("ghidra-function-manager") })
.strict();
const stringFacts = z
.object({
encoding: z.string().min(1),
@@ -198,7 +203,11 @@ const containingProcedure = z.discriminatedUnion("found", [
query_address: canonicalAddress,
found: z.literal(true),
procedure: z
.object({ address: canonicalAddress, name: z.string().min(1) })
.object({
address: canonicalAddress,
name: z.string().min(1),
classification: functionClassification,
})
.strict(),
})
.strict(),
+99 -19
View File
@@ -24,15 +24,26 @@ import {
} from "../domain/errors.js";
import { err, ok, type Result } from "../domain/result.js";
import type { Logger } from "../logger.js";
import { OFFICIAL_TOOL_CONTRACTS } from "../contracts/toolContracts.js";
import {
ENHANCED_TOOL_CONTRACTS,
OFFICIAL_TOOL_CONTRACTS,
} from "../contracts/toolContracts.js";
import { GhidraClient } from "./GhidraClient.js";
import type { GhidraClientOptions } from "./GhidraClientTypes.js";
import {
GHIDRA_ANALYSIS_TIMEOUT_SECONDS,
GHIDRA_DECOMPILE_REQUEST_TIMEOUT_MS,
GHIDRA_DECOMPILE_TIMEOUT_SECONDS,
GHIDRA_MAX_LINE_BYTES,
GHIDRA_REQUEST_TIMEOUT_MS,
GHIDRA_STARTUP_TIMEOUT_MS,
} from "./GhidraDefaults.js";
import {
GHIDRA_FUNCTION_OPERATIONS,
isGhidraFunctionOperation,
parseGhidraFunctionInput,
parseGhidraFunctionResult,
} from "./GhidraFunctionValues.js";
import {
GHIDRA_INVENTORY_OPERATIONS,
isGhidraInventoryOperation,
@@ -56,18 +67,25 @@ export const GHIDRA_PROVIDER_IDENTITY: ProviderIdentity = Object.freeze({
version: null,
});
const officialContractByName = new Map(
OFFICIAL_TOOL_CONTRACTS.map((contract) => [contract.name, contract]),
const providerContractByName = new Map(
[...OFFICIAL_TOOL_CONTRACTS, ...ENHANCED_TOOL_CONTRACTS].map((contract) => [
contract.name,
contract,
]),
);
/** Direct read-only contracts implemented by the Ghidra adapter. */
/** Provider-neutral read-only contracts implemented by the Ghidra adapter. */
export const GHIDRA_PROVIDER_TOOL_CONTRACTS = Object.freeze(
GHIDRA_INVENTORY_OPERATIONS.map((operation) => {
const contract = officialContractByName.get(operation);
if (contract === undefined)
throw new TypeError(`Missing official contract for ${operation}`);
return contract;
}),
[...GHIDRA_INVENTORY_OPERATIONS, ...GHIDRA_FUNCTION_OPERATIONS].map(
(operation) => {
const contract = providerContractByName.get(operation);
if (contract === undefined)
throw new TypeError(
`Missing provider-neutral contract for ${operation}`,
);
return contract;
},
),
);
const PAGINATED_OPERATIONS: ReadonlySet<string> = new Set([
@@ -76,11 +94,17 @@ const PAGINATED_OPERATIONS: ReadonlySet<string> = new Set([
"list_strings",
"search_procedures",
"search_strings",
"procedure_references",
"analyze_function",
]);
const SEARCH_OPERATIONS: ReadonlySet<string> = new Set([
"search_procedures",
"search_strings",
]);
const DECOMPILE_OPERATIONS: ReadonlySet<string> = new Set([
"procedure_pseudo_code",
"analyze_function",
]);
const healthLimitations = Object.freeze([
"The session serves operations only after default Ghidra auto-analysis completes; an analysis timeout fails the open instead of exposing partial results.",
"The imported Program and temporary project are ephemeral, read-only to REA, and deleted on close.",
@@ -125,6 +149,44 @@ const limitationsFor = (operation: string): readonly string[] => {
...common,
"Literal search enforces 1,000,000 cumulative work units; regex mode also accepts only a conservative finite Java-regex subset with 10,000 static paths and 4,096 UTF-16 code units per candidate.",
];
case "procedure_pseudo_code":
return [
...common,
"Pseudocode is Ghidra decompiler output, not original source and not text-equivalent to Hopper output; each decompile has a 30-second native deadline.",
"External functions and functions without an analyzable body return null; other decompiler failures remain explicit.",
];
case "procedure_assembly":
return [
...common,
"Assembly is Ghidra Listing text and fails rather than silently truncating when the 100,000-instruction or 1 MiB wire bound is exceeded.",
];
case "procedure_callers":
case "procedure_callees":
return [
...common,
"Only resolved Ghidra call references are returned; unresolved computed or indirect calls remain unknown, while function classifications distinguish thunks and externals.",
];
case "xrefs":
return [
...common,
"The direct address list projects exact Ghidra references to one address but does not expose their kinds; procedure_references and analyze_function preserve available kind metadata.",
"Synthetic Ghidra entry-point references without actionable memory sources are omitted.",
];
case "procedure_references":
return [
...common,
"Reference kinds are direct Ghidra ReferenceManager observations; unresolved computed flows without a target are absent and remain unknown.",
"Synthetic Ghidra entry-point references without actionable memory sources are omitted.",
"Instruction scans stop at max_instructions; a truncated scan reports an unknown total and no false continuation.",
];
case "analyze_function":
return [
...common,
"The dossier combines Ghidra FunctionManager, Listing, ReferenceManager, BasicBlockModel, and decompiler observations; provider-specific pseudocode and assembly are not cross-provider text invariants.",
"Resolved reference metadata identifies computed, indirect, external, call, jump, and data edges; unresolved targetless flows remain unknown, and function classifications distinguish thunks and externals.",
"Synthetic Ghidra entry-point references without actionable memory sources are omitted.",
"The Java bridge serializes one function request per Program through a bounded 32-request queue and applies a 30-second native decompilation deadline.",
];
default:
return common;
}
@@ -158,7 +220,9 @@ const CAPABILITIES: readonly CapabilityDescriptor[] = Object.freeze(
: 500
: null,
maxPayloadBytes: GHIDRA_MAX_LINE_BYTES,
timeoutMs: GHIDRA_REQUEST_TIMEOUT_MS,
timeoutMs: DECOMPILE_OPERATIONS.has(contract.name)
? GHIDRA_DECOMPILE_REQUEST_TIMEOUT_MS
: GHIDRA_REQUEST_TIMEOUT_MS,
}),
limitations: Object.freeze(limitationsFor(contract.name)),
}),
@@ -292,7 +356,11 @@ export class GhidraProvider implements AnalysisProviderCandidate {
});
return {
execute: async (operation, parameters, options) => {
if (operation !== "health" && !isGhidraInventoryOperation(operation))
if (
operation !== "health" &&
!isGhidraInventoryOperation(operation) &&
!isGhidraFunctionOperation(operation)
)
return err(
new AnalysisCapabilityUnavailableError(
GHIDRA_PROVIDER_IDENTITY.id,
@@ -311,16 +379,21 @@ export class GhidraProvider implements AnalysisProviderCandidate {
}),
);
}
const input = parseGhidraInventoryInput(operation, parameters);
const input = isGhidraFunctionOperation(operation)
? parseGhidraFunctionInput(operation, parameters)
: parseGhidraInventoryInput(operation, parameters);
if (!input.ok) return input;
const called = await client.callTool(
operation,
input.value,
options?.signal === undefined ? {} : { signal: options.signal },
);
const called = await client.callTool(operation, input.value, {
...(options?.signal === undefined ? {} : { signal: options.signal }),
...(DECOMPILE_OPERATIONS.has(operation)
? { timeoutMs: GHIDRA_DECOMPILE_REQUEST_TIMEOUT_MS }
: {}),
});
if (!called.ok)
return err(projectSessionError(operation, called.error));
const result = parseGhidraInventoryResult(operation, called.value);
const result = isGhidraFunctionOperation(operation)
? parseGhidraFunctionResult(operation, called.value)
: parseGhidraInventoryResult(operation, called.value);
if (!result.ok) return result;
return ok(
createAnalysisExecution(result.value, committedProfile.provider, {
@@ -408,6 +481,13 @@ const projectSessionError = (
? GHIDRA_ANALYSIS_TIMEOUT_SECONDS * 1_000
: GHIDRA_STARTUP_TIMEOUT_MS),
);
if (failure.kind === "remote" && failure.remoteCode === "decompile_timeout")
return new AnalysisTimeoutError(
operation,
GHIDRA_DECOMPILE_TIMEOUT_SECONDS * 1_000,
);
if (failure.kind === "remote" && failure.remoteCode === "decompile_cancelled")
return new AnalysisCancelledError(operation);
if (
failure.kind === "remote" &&
["invalid_request", "not_found", "ambiguous"].includes(
+185
View File
@@ -0,0 +1,185 @@
import { performance } from "node:perf_hooks";
import type { JsonValue } from "../domain/jsonValue.js";
import { err, type Result } from "../domain/result.js";
import type { GhidraRequestOptions } from "./GhidraClientTypes.js";
import type { GhidraSessionError } from "./GhidraSessionError.js";
/** Result settled by one queued Ghidra Program request. */
export type GhidraQueuedRequestResult = Result<JsonValue, GhidraSessionError>;
/** Socket execution seam used after a request reaches the queue head. */
export type GhidraRequestExecutor = (
method: string,
parameters: JsonValue,
options: GhidraRequestOptions,
) => Promise<GhidraQueuedRequestResult>;
/** Bind queue failures to the owning client's live diagnostics. */
export type GhidraQueueFailureFactory = (
kind: "cancelled" | "timeout" | "protocol",
message: string,
timeoutMs?: number,
) => GhidraSessionError;
interface QueuedRequest {
readonly method: string;
readonly parameters: JsonValue;
readonly signal: AbortSignal | undefined;
readonly timeoutMs: number;
readonly deadline: number;
readonly resolve: (result: GhidraQueuedRequestResult) => void;
readonly timer: NodeJS.Timeout;
readonly onAbort: (() => void) | undefined;
}
/** Bounded FIFO that admits one Ghidra Program request at a time. */
export class GhidraRequestQueue {
readonly #queue: QueuedRequest[] = [];
#active = false;
#size = 0;
constructor(
private readonly maximum: number,
private readonly execute: GhidraRequestExecutor,
private readonly failure: GhidraQueueFailureFactory,
) {}
/** Queue one request, counting queue wait against its declared deadline. */
run(
method: string,
parameters: JsonValue,
options: GhidraRequestOptions & { readonly timeoutMs: number },
): Promise<GhidraQueuedRequestResult> {
if (options.signal?.aborted === true)
return Promise.resolve(
err(this.failure("cancelled", "Ghidra request was cancelled")),
);
if (options.timeoutMs <= 0)
return Promise.resolve(
err(
this.failure(
"timeout",
"Ghidra request deadline elapsed",
options.timeoutMs,
),
),
);
if (this.#size >= this.maximum)
return Promise.resolve(
err(
this.failure(
"protocol",
`Ghidra serial request queue reached its ${String(this.maximum)}-request limit`,
),
),
);
this.#size += 1;
return new Promise((resolve) => {
let entry: QueuedRequest;
const onAbort =
options.signal === undefined
? undefined
: () =>
this.#rejectQueued(
entry,
err(this.failure("cancelled", "Ghidra request was cancelled")),
);
const timer = setTimeout(
() =>
this.#rejectQueued(
entry,
err(
this.failure(
"timeout",
"Ghidra request deadline elapsed in the serial queue",
options.timeoutMs,
),
),
),
options.timeoutMs,
);
entry = {
method,
parameters,
signal: options.signal,
timeoutMs: options.timeoutMs,
deadline: performance.now() + options.timeoutMs,
resolve,
timer,
onAbort,
};
this.#queue.push(entry);
if (onAbort !== undefined)
options.signal?.addEventListener("abort", onAbort, { once: true });
this.#drain();
});
}
/** Fail requests that have not crossed the socket during session cleanup. */
failQueued(failure: GhidraSessionError): void {
for (const entry of this.#queue.splice(0)) {
this.#release(entry);
this.#size -= 1;
entry.resolve(err(failure));
}
}
#drain(): void {
if (this.#active) return;
const entry = this.#queue.shift();
if (entry === undefined) return;
this.#release(entry);
const remaining = entry.deadline - performance.now();
if (entry.signal?.aborted === true || remaining <= 0) {
this.#size -= 1;
entry.resolve(
err(
entry.signal?.aborted === true
? this.failure("cancelled", "Ghidra request was cancelled")
: this.failure(
"timeout",
"Ghidra request deadline elapsed in the serial queue",
entry.timeoutMs,
),
),
);
this.#drain();
return;
}
this.#active = true;
void this.execute(entry.method, entry.parameters, {
...(entry.signal === undefined ? {} : { signal: entry.signal }),
timeoutMs: remaining,
})
.then(entry.resolve)
.catch(() =>
entry.resolve(
err(
this.failure(
"protocol",
"Ghidra serial request execution rejected unexpectedly",
),
),
),
)
.finally(() => {
this.#active = false;
this.#size -= 1;
this.#drain();
});
}
#rejectQueued(entry: QueuedRequest, result: GhidraQueuedRequestResult): void {
const index = this.#queue.indexOf(entry);
if (index < 0) return;
this.#queue.splice(index, 1);
this.#release(entry);
this.#size -= 1;
entry.resolve(result);
}
#release(entry: QueuedRequest): void {
clearTimeout(entry.timer);
if (entry.signal !== undefined && entry.onAbort !== undefined)
entry.signal.removeEventListener("abort", entry.onAbort);
}
}
+2
View File
@@ -4,12 +4,14 @@ import type { JsonValue } from "../domain/jsonValue.js";
import { err, ok, type Result } from "../domain/result.js";
import { GHIDRA_BRIDGE_VERSION } from "./GhidraDefaults.js";
import { GHIDRA_INVENTORY_OPERATIONS } from "./GhidraInventoryValues.js";
import { GHIDRA_FUNCTION_OPERATIONS } from "./GhidraFunctionValues.js";
/** Exact methods proved by the bridge handshake after auto-analysis. */
export const GHIDRA_SESSION_CAPABILITIES = [
"ping",
"shutdown",
...GHIDRA_INVENTORY_OPERATIONS,
...GHIDRA_FUNCTION_OPERATIONS,
] as const;
const capabilitySchema = z.enum(GHIDRA_SESSION_CAPABILITIES);