refactor: return complete tool results inline
This commit is contained in:
@@ -35,7 +35,7 @@ export const resolveGhidraAnalysisProfile = (
|
||||
const provider = { ...identity, version: installation.providerVersion };
|
||||
return Promise.resolve(
|
||||
ok({
|
||||
profile: createAnalysisProfile(provider, 1, {
|
||||
profile: createAnalysisProfile(provider, {
|
||||
target_kind: target.kind,
|
||||
target_format: target.format,
|
||||
architecture: target.architecture ?? null,
|
||||
|
||||
@@ -17,7 +17,6 @@ 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";
|
||||
@@ -138,7 +137,6 @@ export class GhidraClient {
|
||||
failure: this.#failure,
|
||||
});
|
||||
this.#requestQueue = new GhidraRequestQueue(
|
||||
GHIDRA_MAX_QUEUED_REQUESTS,
|
||||
(method, parameters, requestOptions) =>
|
||||
this.#wire.request(method, parameters, requestOptions),
|
||||
(kind, message, timeoutMs) =>
|
||||
|
||||
@@ -12,8 +12,6 @@ export const GHIDRA_REQUEST_TIMEOUT_MS = 10_000;
|
||||
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. */
|
||||
|
||||
@@ -9,7 +9,6 @@ import {
|
||||
type GhidraFunctionOperation,
|
||||
} from "./GhidraFunctionValues.js";
|
||||
import {
|
||||
ghidraBounded,
|
||||
ghidraFunctionClassification,
|
||||
ghidraFunctionDossier,
|
||||
ghidraFunctionIdentity,
|
||||
@@ -18,7 +17,7 @@ import {
|
||||
} from "../domain/hopperValues.fixture.js";
|
||||
|
||||
describe("Ghidra function-analysis boundary values", () => {
|
||||
it("defaults bounded inputs and rejects undeclared or implicit addresses", () => {
|
||||
it("defaults inputs and rejects undeclared or implicit addresses", () => {
|
||||
expect(
|
||||
parseGhidraFunctionInput("procedure_info", { procedure: "main" }),
|
||||
).toEqual({
|
||||
@@ -33,25 +32,13 @@ describe("Ghidra function-analysis boundary values", () => {
|
||||
document: null,
|
||||
procedure: "main",
|
||||
direction: "outgoing",
|
||||
offset: 0,
|
||||
limit: 100,
|
||||
max_instructions: 500,
|
||||
},
|
||||
});
|
||||
expect(
|
||||
parseGhidraFunctionInput("analyze_function", { procedure: "main" }),
|
||||
).toMatchObject({
|
||||
ok: true,
|
||||
value: {
|
||||
procedure: "main",
|
||||
include_assembly: false,
|
||||
limit: 100,
|
||||
max_pseudocode_chars: 20_000,
|
||||
max_instructions: 500,
|
||||
pseudocode_offset: 0,
|
||||
assembly_offset: 0,
|
||||
collection_offset: { basic_blocks: 0, outgoing_references: 0 },
|
||||
},
|
||||
value: { procedure: "main" },
|
||||
});
|
||||
expect(
|
||||
parseGhidraFunctionInput("read_function_instructions", {
|
||||
@@ -59,12 +46,7 @@ describe("Ghidra function-analysis boundary values", () => {
|
||||
}),
|
||||
).toEqual({
|
||||
ok: true,
|
||||
value: {
|
||||
document: null,
|
||||
procedure: "main",
|
||||
offset: 0,
|
||||
limit: 64,
|
||||
},
|
||||
value: { document: null, procedure: "main" },
|
||||
});
|
||||
expect(parseGhidraFunctionInput("xrefs", {})).toMatchObject({
|
||||
ok: false,
|
||||
@@ -93,9 +75,7 @@ describe("Ghidra function-analysis result values", () => {
|
||||
expect(
|
||||
parseGhidraFunctionResult("read_function_instructions", {
|
||||
procedure: ghidraFunctionIdentity(),
|
||||
instructions: ghidraBounded(["0x401000: push rbp"]),
|
||||
instructions_scanned: 1,
|
||||
instruction_scan_truncated: false,
|
||||
instructions: ["0x401000: push rbp"],
|
||||
limitations: ["Ghidra-specific instruction text."],
|
||||
}),
|
||||
).toMatchObject({ ok: true });
|
||||
@@ -105,9 +85,7 @@ describe("Ghidra function-analysis result values", () => {
|
||||
...ghidraFunctionIdentity(),
|
||||
address: "0X401000",
|
||||
},
|
||||
instructions: ghidraBounded(["0x401000: push rbp"]),
|
||||
instructions_scanned: 1,
|
||||
instruction_scan_truncated: false,
|
||||
instructions: ["0x401000: push rbp"],
|
||||
limitations: ["Ghidra-specific instruction text."],
|
||||
}),
|
||||
).toMatchObject({
|
||||
@@ -134,24 +112,20 @@ describe("Ghidra function-analysis result values", () => {
|
||||
parseGhidraFunctionResult("procedure_references", {
|
||||
procedure: ghidraFunctionIdentity(),
|
||||
direction: "outgoing",
|
||||
references: ghidraBounded([ghidraReferenceEdge()]),
|
||||
instructions_scanned: 2,
|
||||
instruction_scan_truncated: false,
|
||||
references: [ghidraReferenceEdge()],
|
||||
}),
|
||||
).toMatchObject({
|
||||
ok: true,
|
||||
value: {
|
||||
references: {
|
||||
items: [
|
||||
{
|
||||
kind: {
|
||||
available: true,
|
||||
provenance: "ghidra-reference-manager",
|
||||
data: true,
|
||||
},
|
||||
references: [
|
||||
{
|
||||
kind: {
|
||||
available: true,
|
||||
provenance: "ghidra-reference-manager",
|
||||
data: true,
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
expect(
|
||||
@@ -230,11 +204,9 @@ const malformedOutputs = (): Array<
|
||||
{
|
||||
procedure: ghidraFunctionIdentity(),
|
||||
direction: "outgoing",
|
||||
references: ghidraBounded([
|
||||
references: [
|
||||
{ ...edge, kind: { available: false, reason: "unknown" } },
|
||||
]),
|
||||
instructions_scanned: 1,
|
||||
instruction_scan_truncated: false,
|
||||
],
|
||||
},
|
||||
],
|
||||
[
|
||||
|
||||
@@ -10,7 +10,7 @@ import type { JsonValue } from "../domain/jsonValue.js";
|
||||
import { nativeApiBoundarySchema } from "../domain/nativeApiBoundary.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import {
|
||||
ghidraBoundedIdentifierSchema,
|
||||
ghidraIdentifierSchema,
|
||||
ghidraCanonicalAddressSchema,
|
||||
} from "./GhidraInventoryValues.js";
|
||||
|
||||
@@ -38,69 +38,22 @@ export const isGhidraFunctionOperation = (
|
||||
operation: string,
|
||||
): operation is GhidraFunctionOperation => operationSet.has(operation);
|
||||
|
||||
const document = ghidraBoundedIdentifierSchema.nullable().default(null);
|
||||
const procedure = ghidraBoundedIdentifierSchema;
|
||||
const document = ghidraIdentifierSchema.nullable().default(null);
|
||||
const procedure = ghidraIdentifierSchema;
|
||||
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(),
|
||||
analyze_function: z.object({ procedure }).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(),
|
||||
read_function_instructions: z
|
||||
.object({
|
||||
...directProcedure,
|
||||
offset: z.number().int().min(0).max(100_000).default(0),
|
||||
limit: z.number().int().min(1).max(500).default(64),
|
||||
})
|
||||
.strict(),
|
||||
read_function_instructions: 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(),
|
||||
@@ -167,45 +120,11 @@ const referenceEdge = z
|
||||
kind: referenceKind,
|
||||
})
|
||||
.strict();
|
||||
const boundedReferenceFacts = {
|
||||
items: z.array(referenceEdge),
|
||||
total: z.number().int().min(0).nullable(),
|
||||
returned: z.number().int().min(0),
|
||||
} as const;
|
||||
const boundedReferences = z
|
||||
.discriminatedUnion("truncated", [
|
||||
z.strictObject({
|
||||
...boundedReferenceFacts,
|
||||
truncated: z.literal(false),
|
||||
next_offset: z.null(),
|
||||
}),
|
||||
z.strictObject({
|
||||
...boundedReferenceFacts,
|
||||
truncated: z.literal(true),
|
||||
next_offset: z.number().int().min(0).nullable(),
|
||||
}),
|
||||
])
|
||||
.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",
|
||||
});
|
||||
});
|
||||
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(),
|
||||
references: z.array(referenceEdge),
|
||||
})
|
||||
.strict();
|
||||
const procedureInfo = z
|
||||
@@ -256,19 +175,20 @@ 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 }) => [
|
||||
...value.comments.map(({ address }) => address),
|
||||
...value.callers.map(({ address }) => address),
|
||||
...value.callees.map(({ address }) => address),
|
||||
...value.incoming_references.flatMap(referenceAddresses),
|
||||
...value.outgoing_references.flatMap(referenceAddresses),
|
||||
...value.referenced_strings.flatMap(({ address, source_address }) => [
|
||||
address,
|
||||
source_address,
|
||||
]),
|
||||
...value.basic_blocks.items.flatMap(({ start, end, successors }) => [
|
||||
...value.referenced_names.flatMap(({ address, source_address }) => [
|
||||
address,
|
||||
source_address,
|
||||
]),
|
||||
...value.basic_blocks.flatMap(({ start, end, successors }) => [
|
||||
start,
|
||||
end,
|
||||
...successors,
|
||||
@@ -285,10 +205,10 @@ const ghidraFunctionDossier = functionDossierSchema
|
||||
});
|
||||
const identities = [
|
||||
value.procedure,
|
||||
...value.callers.items,
|
||||
...value.callees.items,
|
||||
...value.incoming_references.items.flatMap(referenceProcedures),
|
||||
...value.outgoing_references.items.flatMap(referenceProcedures),
|
||||
...value.callers,
|
||||
...value.callees,
|
||||
...value.incoming_references.flatMap(referenceProcedures),
|
||||
...value.outgoing_references.flatMap(referenceProcedures),
|
||||
];
|
||||
if (
|
||||
identities.some(
|
||||
@@ -303,10 +223,9 @@ const ghidraFunctionDossier = functionDossierSchema
|
||||
value.procedure.locals.some(
|
||||
(variable) => !localVariable.safeParse(variable).success,
|
||||
) ||
|
||||
[
|
||||
...value.incoming_references.items,
|
||||
...value.outgoing_references.items,
|
||||
].some(({ kind }) => !referenceKind.safeParse(kind).success)
|
||||
[...value.incoming_references, ...value.outgoing_references].some(
|
||||
({ kind }) => !referenceKind.safeParse(kind).success,
|
||||
)
|
||||
)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
@@ -355,7 +274,7 @@ export const parseGhidraFunctionResult = (
|
||||
};
|
||||
|
||||
const referenceAddresses = (
|
||||
edge: FunctionDossier["incoming_references"]["items"][number],
|
||||
edge: FunctionDossier["incoming_references"][number],
|
||||
): readonly string[] => [
|
||||
edge.source_address,
|
||||
edge.target_address,
|
||||
@@ -364,9 +283,9 @@ const referenceAddresses = (
|
||||
];
|
||||
|
||||
const referenceProcedures = (
|
||||
edge: FunctionDossier["incoming_references"]["items"][number],
|
||||
edge: FunctionDossier["incoming_references"][number],
|
||||
): readonly NonNullable<
|
||||
FunctionDossier["incoming_references"]["items"][number]["source_procedure"]
|
||||
FunctionDossier["incoming_references"][number]["source_procedure"]
|
||||
>[] => [
|
||||
...(edge.source_procedure === null ? [] : [edge.source_procedure]),
|
||||
...(edge.target_procedure === null ? [] : [edge.target_procedure]),
|
||||
|
||||
@@ -5,15 +5,13 @@ import {
|
||||
isGhidraInventoryOperation,
|
||||
parseGhidraInventoryInput,
|
||||
parseGhidraInventoryResult,
|
||||
type GhidraInventoryOperation,
|
||||
} from "./GhidraInventoryValues.js";
|
||||
import type { JsonValue } from "../domain/jsonValue.js";
|
||||
|
||||
describe("Ghidra inventory boundary values", () => {
|
||||
it("defaults bounded provider inputs without accepting undeclared fields", () => {
|
||||
it("accepts complete inventories and searches without page controls", () => {
|
||||
expect(parseGhidraInventoryInput("list_procedures", {})).toEqual({
|
||||
ok: true,
|
||||
value: { document: null, offset: 0, limit: 100 },
|
||||
value: { document: null },
|
||||
});
|
||||
expect(
|
||||
parseGhidraInventoryInput("search_strings", { pattern: "needle" }),
|
||||
@@ -23,26 +21,15 @@ describe("Ghidra inventory boundary values", () => {
|
||||
pattern: "needle",
|
||||
mode: "literal",
|
||||
case_sensitive: false,
|
||||
offset: 0,
|
||||
limit: 100,
|
||||
document: null,
|
||||
},
|
||||
});
|
||||
expect(
|
||||
parseGhidraInventoryInput("list_procedures", { limit: 100 }),
|
||||
).toMatchObject({ ok: false, error: { _tag: "AnalysisInputError" } });
|
||||
expect(
|
||||
parseGhidraInventoryInput("list_documents", { extra: true }),
|
||||
).toMatchObject({ ok: false, error: { _tag: "AnalysisInputError" } });
|
||||
expect(parseGhidraInventoryInput("address_name", {})).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "AnalysisInputError" },
|
||||
});
|
||||
expect(
|
||||
parseGhidraInventoryInput("procedure_address", {
|
||||
procedure: "x".repeat(4097),
|
||||
}),
|
||||
).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "AnalysisInputError" },
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps the admitted operation set closed", () => {
|
||||
@@ -52,181 +39,30 @@ describe("Ghidra inventory boundary values", () => {
|
||||
expect(isGhidraInventoryOperation("set_comment")).toBe(false);
|
||||
});
|
||||
|
||||
it("parses primary, dynamic, and external symbol facts", () => {
|
||||
const items = [
|
||||
{
|
||||
address: "EXTERNAL:0x1",
|
||||
value: "libc::puts",
|
||||
value_truncated: false,
|
||||
symbol: {
|
||||
primary: true,
|
||||
dynamic: false,
|
||||
external: true,
|
||||
type: "function",
|
||||
source: "imported",
|
||||
},
|
||||
},
|
||||
{
|
||||
address: "0x401000",
|
||||
value: "LAB_00401000",
|
||||
value_truncated: false,
|
||||
symbol: {
|
||||
primary: true,
|
||||
dynamic: true,
|
||||
external: false,
|
||||
type: "label",
|
||||
source: "default",
|
||||
},
|
||||
},
|
||||
] satisfies readonly JsonValue[];
|
||||
expect(parseGhidraInventoryResult("list_names", page(items))).toEqual({
|
||||
it("returns complete typed inventory arrays", () => {
|
||||
const procedures = Array.from({ length: 700 }, (_, index) => ({
|
||||
address: `0x${(0x401000 + index).toString(16)}`,
|
||||
value: `sub_${index}`,
|
||||
procedure: { external: false, thunk: false, thunk_target: null },
|
||||
}));
|
||||
expect(parseGhidraInventoryResult("list_procedures", procedures)).toEqual({
|
||||
ok: true,
|
||||
value: page(items),
|
||||
value: procedures,
|
||||
});
|
||||
});
|
||||
|
||||
it("parses thunk, string-layout, and memory-permission observations", () => {
|
||||
it("rejects malformed inventory items", () => {
|
||||
expect(
|
||||
parseGhidraInventoryResult(
|
||||
"list_procedures",
|
||||
page([
|
||||
{
|
||||
address: "0x401020",
|
||||
value: "puts",
|
||||
value_truncated: false,
|
||||
procedure: {
|
||||
external: false,
|
||||
thunk: true,
|
||||
thunk_target: "EXTERNAL:0x1",
|
||||
},
|
||||
},
|
||||
]),
|
||||
),
|
||||
).toMatchObject({ ok: true });
|
||||
expect(
|
||||
parseGhidraInventoryResult(
|
||||
"list_strings",
|
||||
page([
|
||||
{
|
||||
address: "0x402000",
|
||||
value: "fixture",
|
||||
value_truncated: false,
|
||||
string: {
|
||||
encoding: "UTF-8",
|
||||
termination: "missing",
|
||||
byte_length: 7,
|
||||
},
|
||||
},
|
||||
]),
|
||||
),
|
||||
).toMatchObject({ ok: true });
|
||||
expect(
|
||||
parseGhidraInventoryResult("list_segments", [
|
||||
{
|
||||
name: ".text",
|
||||
start: "0x401000",
|
||||
end: "0x402000",
|
||||
readable: true,
|
||||
writable: false,
|
||||
executable: true,
|
||||
permissions: { available: true, source: "ghidra-memory-block" },
|
||||
provenance: "ghidra-memory-block",
|
||||
address_space: "ram",
|
||||
image_base: "0x400000",
|
||||
initialized: true,
|
||||
overlay: false,
|
||||
sections: [],
|
||||
},
|
||||
]),
|
||||
).toMatchObject({ ok: true });
|
||||
});
|
||||
|
||||
it.each(malformedOutputs())(
|
||||
"rejects malformed %s output",
|
||||
(_name, operation, value) => {
|
||||
expect(parseGhidraInventoryResult(operation, value)).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "AnalysisOutputError" },
|
||||
});
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
function malformedOutputs(): Array<
|
||||
[string, GhidraInventoryOperation, JsonValue]
|
||||
> {
|
||||
return [
|
||||
[
|
||||
"non-canonical address",
|
||||
"list_procedures",
|
||||
page([
|
||||
parseGhidraInventoryResult("list_procedures", [
|
||||
{
|
||||
address: "00401000",
|
||||
value: "main",
|
||||
value_truncated: false,
|
||||
procedure: {
|
||||
external: false,
|
||||
thunk: false,
|
||||
thunk_target: null,
|
||||
},
|
||||
procedure: { external: false, thunk: false, thunk_target: null },
|
||||
},
|
||||
]),
|
||||
],
|
||||
[
|
||||
"missing external metadata",
|
||||
"list_names",
|
||||
page([{ address: "0x401000", value: "main", value_truncated: false }]),
|
||||
],
|
||||
[
|
||||
"contradictory continuation",
|
||||
"search_strings",
|
||||
{
|
||||
...page([]),
|
||||
total: 1,
|
||||
has_more: false,
|
||||
next_offset: null,
|
||||
},
|
||||
],
|
||||
[
|
||||
"non-advancing continuation",
|
||||
"list_procedures",
|
||||
{
|
||||
...page([]),
|
||||
total: 1,
|
||||
has_more: true,
|
||||
next_offset: 0,
|
||||
},
|
||||
],
|
||||
[
|
||||
"items beyond exact total",
|
||||
"list_procedures",
|
||||
{ ...page([procedureItem()]), total: 0 },
|
||||
],
|
||||
["provider limit", "search_procedures", { ...page([]), limit: 101 }],
|
||||
["multiple programs", "list_documents", ["first", "second"]],
|
||||
];
|
||||
}
|
||||
|
||||
function procedureItem(): JsonValue {
|
||||
return {
|
||||
address: "0x401000",
|
||||
value: "main",
|
||||
value_truncated: false,
|
||||
procedure: {
|
||||
external: false,
|
||||
thunk: false,
|
||||
thunk_target: null,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function page(items: readonly JsonValue[]) {
|
||||
return {
|
||||
items: [...items],
|
||||
offset: 0,
|
||||
limit: 500,
|
||||
total: items.length,
|
||||
next_offset: null,
|
||||
has_more: false,
|
||||
};
|
||||
}
|
||||
).toMatchObject({ ok: false, error: { _tag: "AnalysisOutputError" } });
|
||||
expect(
|
||||
parseGhidraInventoryResult("search_strings", [{ address: "0x1000" }]),
|
||||
).toMatchObject({ ok: false, error: { _tag: "AnalysisOutputError" } });
|
||||
});
|
||||
});
|
||||
|
||||
@@ -29,38 +29,26 @@ export const isGhidraInventoryOperation = (
|
||||
operation: string,
|
||||
): operation is GhidraInventoryOperation => operationSet.has(operation);
|
||||
|
||||
export const ghidraBoundedIdentifierSchema = z.string().min(1).max(4096);
|
||||
const boundedIdentifier = ghidraBoundedIdentifierSchema;
|
||||
const document = boundedIdentifier.nullable().default(null);
|
||||
const explicitAddress = boundedIdentifier;
|
||||
export const ghidraIdentifierSchema = z.string().min(1);
|
||||
const identifier = ghidraIdentifierSchema;
|
||||
const document = identifier.nullable().default(null);
|
||||
const explicitAddress = identifier;
|
||||
const filteredAddress = explicitAddress.nullable().default(null);
|
||||
const pagination = {
|
||||
offset: z.number().int().min(0).default(0),
|
||||
limit: z.number().int().min(1).max(500).default(100),
|
||||
};
|
||||
const searchInput = {
|
||||
pattern: z.string().min(1).max(256),
|
||||
pattern: z.string().min(1),
|
||||
mode: z.enum(["literal", "regex"]).default("literal"),
|
||||
case_sensitive: z.boolean().default(false),
|
||||
offset: z.number().int().min(0).default(0),
|
||||
limit: z.number().int().min(1).max(100).default(100),
|
||||
document,
|
||||
};
|
||||
|
||||
const inputSchemas = {
|
||||
address_name: z.object({ document, address: explicitAddress }).strict(),
|
||||
list_documents: z.object({}).strict(),
|
||||
list_names: z
|
||||
.object({ document, address: filteredAddress, ...pagination })
|
||||
.strict(),
|
||||
list_procedures: z.object({ document, ...pagination }).strict(),
|
||||
list_names: z.object({ document, address: filteredAddress }).strict(),
|
||||
list_procedures: z.object({ document }).strict(),
|
||||
list_segments: z.object({ document }).strict(),
|
||||
list_strings: z
|
||||
.object({ document, address: filteredAddress, ...pagination })
|
||||
.strict(),
|
||||
procedure_address: z
|
||||
.object({ document, procedure: boundedIdentifier })
|
||||
.strict(),
|
||||
list_strings: z.object({ document, address: filteredAddress }).strict(),
|
||||
procedure_address: z.object({ document, procedure: identifier }).strict(),
|
||||
resolve_containing_procedure: z
|
||||
.object({ document, address: explicitAddress })
|
||||
.strict(),
|
||||
@@ -83,7 +71,6 @@ 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({
|
||||
primary: z.boolean(),
|
||||
@@ -113,7 +100,6 @@ const stringFacts = z
|
||||
const baseItem = {
|
||||
address: canonicalAddress,
|
||||
value: z.string(),
|
||||
...valueTruncation,
|
||||
};
|
||||
const symbolItem = z.object({ ...baseItem, symbol: symbolFacts }).strict();
|
||||
const procedureItem = z
|
||||
@@ -122,65 +108,6 @@ const procedureItem = z
|
||||
const stringItem = z.object({ ...baseItem, string: stringFacts }).strict();
|
||||
const searchItem = z.object(baseItem).strict();
|
||||
|
||||
const pageSchema = <Item extends z.ZodType>(
|
||||
item: Item,
|
||||
maximumLimit: number,
|
||||
) => {
|
||||
const pageFacts = {
|
||||
items: z.array(item),
|
||||
offset: z.number().int().min(0),
|
||||
limit: z.number().int().min(1).max(maximumLimit),
|
||||
total: z.number().int().min(0),
|
||||
} as const;
|
||||
return z
|
||||
.discriminatedUnion("has_more", [
|
||||
z.strictObject({
|
||||
...pageFacts,
|
||||
has_more: z.literal(true),
|
||||
next_offset: z.number().int().min(0),
|
||||
}),
|
||||
z.strictObject({
|
||||
...pageFacts,
|
||||
has_more: z.literal(false),
|
||||
next_offset: z.null(),
|
||||
}),
|
||||
])
|
||||
.superRefine((page, context) => {
|
||||
const next = page.offset + page.items.length;
|
||||
const hasMore = next < page.total;
|
||||
if (page.items.length > page.limit)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["items"],
|
||||
message: "page exceeds its declared limit",
|
||||
});
|
||||
if (page.items.length > 0 && next > page.total)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["total"],
|
||||
message: "page items exceed its exact total",
|
||||
});
|
||||
if (hasMore && page.items.length === 0)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["items"],
|
||||
message: "page continuation must advance its offset",
|
||||
});
|
||||
if (page.has_more !== hasMore)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["has_more"],
|
||||
message: "page continuation does not match its exact total",
|
||||
});
|
||||
if (page.next_offset !== (hasMore ? next : null))
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["next_offset"],
|
||||
message: "page continuation offset is inconsistent",
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
const availablePermissions = z
|
||||
.object({
|
||||
available: z.literal(true),
|
||||
@@ -233,14 +160,14 @@ const containingProcedure = z.discriminatedUnion("found", [
|
||||
const resultSchemas = {
|
||||
address_name: z.string().nullable(),
|
||||
list_documents: z.array(z.string().min(1)).length(1),
|
||||
list_names: pageSchema(symbolItem, 500),
|
||||
list_procedures: pageSchema(procedureItem, 500),
|
||||
list_names: z.array(symbolItem),
|
||||
list_procedures: z.array(procedureItem),
|
||||
list_segments: z.array(segment),
|
||||
list_strings: pageSchema(stringItem, 500),
|
||||
list_strings: z.array(stringItem),
|
||||
procedure_address: canonicalAddress,
|
||||
resolve_containing_procedure: containingProcedure,
|
||||
search_procedures: pageSchema(searchItem, 100),
|
||||
search_strings: pageSchema(searchItem, 100),
|
||||
search_procedures: z.array(searchItem),
|
||||
search_strings: z.array(searchItem),
|
||||
} satisfies Readonly<Record<GhidraInventoryOperation, z.ZodType>>;
|
||||
|
||||
/** Require exact, bounded Java-bridge output before creating Evidence. */
|
||||
|
||||
@@ -65,23 +65,23 @@ describe("Ghidra provider", () => {
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
operation: "list_procedures",
|
||||
pagination: "offset",
|
||||
pagination: "none",
|
||||
effects: expect.objectContaining({
|
||||
mutatesArtifact: false,
|
||||
mayShowUi: false,
|
||||
mayWriteFilesystem: true,
|
||||
}),
|
||||
limits: {
|
||||
maxResults: 500,
|
||||
maxResults: null,
|
||||
maxPayloadBytes: 1024 * 1024,
|
||||
timeoutMs: 10_000,
|
||||
},
|
||||
}),
|
||||
expect.objectContaining({
|
||||
operation: "analyze_function",
|
||||
pagination: "offset",
|
||||
pagination: "none",
|
||||
limits: {
|
||||
maxResults: 500,
|
||||
maxResults: null,
|
||||
maxPayloadBytes: 1024 * 1024,
|
||||
timeoutMs: 35_000,
|
||||
},
|
||||
@@ -235,25 +235,17 @@ describe("Ghidra client projection", () => {
|
||||
) => {
|
||||
toolCalls.push({ operation, input, options });
|
||||
return Promise.resolve(
|
||||
ok({
|
||||
items: [
|
||||
{
|
||||
address: "0x1000",
|
||||
value: "fixture_main",
|
||||
value_truncated: false,
|
||||
procedure: {
|
||||
external: false,
|
||||
thunk: false,
|
||||
thunk_target: null,
|
||||
},
|
||||
ok([
|
||||
{
|
||||
address: "0x1000",
|
||||
value: "fixture_main",
|
||||
procedure: {
|
||||
external: false,
|
||||
thunk: false,
|
||||
thunk_target: null,
|
||||
},
|
||||
],
|
||||
offset: 0,
|
||||
limit: 100,
|
||||
total: 1,
|
||||
next_offset: null,
|
||||
has_more: false,
|
||||
}),
|
||||
},
|
||||
]),
|
||||
);
|
||||
};
|
||||
const clientFactory: GhidraProviderClientFactory = (options) => {
|
||||
@@ -276,7 +268,6 @@ describe("Ghidra client projection", () => {
|
||||
if (!resolved.ok || resolved.value.profile === null) return;
|
||||
expect(resolved.value.profile).toMatchObject({
|
||||
provider: { id: "ghidra", name: "Ghidra", version: "12.1.2" },
|
||||
provider_profile_schema_version: 1,
|
||||
parameters: {
|
||||
import_mode: "ephemeral-read-only",
|
||||
analyzer_preset: "ghidra-default",
|
||||
@@ -303,7 +294,7 @@ describe("Ghidra client projection", () => {
|
||||
expect(toolCalls).toEqual([
|
||||
{
|
||||
operation: "list_procedures",
|
||||
input: { document: null, offset: 0, limit: 100 },
|
||||
input: { document: null },
|
||||
options: {},
|
||||
},
|
||||
]);
|
||||
@@ -316,13 +307,8 @@ describe("Ghidra client projection", () => {
|
||||
version: "12.1.2",
|
||||
},
|
||||
analysisProfile: resolved.value.profile,
|
||||
result: {
|
||||
items: [{ address: "0x1000", value: "fixture_main" }],
|
||||
total: 1,
|
||||
},
|
||||
rawResult: {
|
||||
items: [{ procedure: { external: false, thunk: false } }],
|
||||
},
|
||||
result: [{ address: "0x1000", value: "fixture_main" }],
|
||||
rawResult: [{ procedure: { external: false, thunk: false } }],
|
||||
},
|
||||
});
|
||||
expect(startCount).toBe(0);
|
||||
@@ -333,7 +319,7 @@ describe("Ghidra result projection", () => {
|
||||
it("rejects malformed inventory output before Evidence creation", async () => {
|
||||
const ghidra = provider(installationHost(), () => ({
|
||||
start: () => Promise.resolve(ok(sessionInfo())),
|
||||
callTool: () => Promise.resolve(ok({ items: "not-a-page" })),
|
||||
callTool: () => Promise.resolve(ok({ items: "not-an-inventory" })),
|
||||
close: () => Promise.resolve(),
|
||||
}));
|
||||
const resolved = await ghidra.resolveAnalysisProfile(
|
||||
|
||||
@@ -39,20 +39,7 @@ export const GHIDRA_PROVIDER_TOOL_CONTRACTS = Object.freeze(
|
||||
),
|
||||
);
|
||||
|
||||
const PAGINATED_OPERATIONS: ReadonlySet<string> = new Set([
|
||||
"list_names",
|
||||
"list_procedures",
|
||||
"list_strings",
|
||||
"search_procedures",
|
||||
"search_strings",
|
||||
"procedure_references",
|
||||
"read_function_instructions",
|
||||
"analyze_function",
|
||||
]);
|
||||
const SEARCH_OPERATIONS: ReadonlySet<string> = new Set([
|
||||
"search_procedures",
|
||||
"search_strings",
|
||||
]);
|
||||
const PAGINATED_OPERATIONS: ReadonlySet<string> = new Set([]);
|
||||
const DECOMPILE_OPERATIONS: ReadonlySet<string> = new Set([
|
||||
"procedure_pseudo_code",
|
||||
"analyze_function",
|
||||
@@ -98,7 +85,6 @@ export const limitationsFor = (operation: string): readonly string[] => {
|
||||
return [
|
||||
...common,
|
||||
"Only Ghidra-defined string Data is observed; charset is reported, while a non-missing terminator cannot distinguish a present terminator from a fixed or Pascal layout.",
|
||||
"Returned values are bounded to 1,024 Unicode code points and mark value_truncated instead of silently crossing the wire budget.",
|
||||
];
|
||||
case "list_segments":
|
||||
return [
|
||||
@@ -169,8 +155,6 @@ export const CAPABILITIES: readonly CapabilityDescriptor[] = Object.freeze(
|
||||
return Object.freeze({
|
||||
provider: GHIDRA_PROVIDER_IDENTITY,
|
||||
operation,
|
||||
inputContractVersion: 1,
|
||||
outputContractVersion: 1,
|
||||
available: true,
|
||||
reason: null,
|
||||
pagination: PAGINATED_OPERATIONS.has(contract.name)
|
||||
@@ -187,11 +171,7 @@ export const CAPABILITIES: readonly CapabilityDescriptor[] = Object.freeze(
|
||||
requiresRoot: false,
|
||||
}),
|
||||
limits: Object.freeze({
|
||||
maxResults: PAGINATED_OPERATIONS.has(contract.name)
|
||||
? SEARCH_OPERATIONS.has(contract.name)
|
||||
? 100
|
||||
: 500
|
||||
: null,
|
||||
maxResults: PAGINATED_OPERATIONS.has(contract.name) ? 500 : null,
|
||||
maxPayloadBytes: GHIDRA_MAX_LINE_BYTES,
|
||||
timeoutMs: DECOMPILE_OPERATIONS.has(contract.name)
|
||||
? GHIDRA_DECOMPILE_REQUEST_TIMEOUT_MS
|
||||
|
||||
@@ -31,14 +31,12 @@ interface QueuedRequest {
|
||||
readonly onAbort: (() => void) | undefined;
|
||||
}
|
||||
|
||||
/** Bounded FIFO that admits one Ghidra Program request at a time. */
|
||||
/** 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,
|
||||
) {}
|
||||
@@ -63,16 +61,6 @@ export class GhidraRequestQueue {
|
||||
),
|
||||
),
|
||||
);
|
||||
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 =
|
||||
@@ -118,7 +106,6 @@ export class GhidraRequestQueue {
|
||||
failQueued(failure: GhidraSessionError): void {
|
||||
for (const entry of this.#queue.splice(0)) {
|
||||
this.#release(entry);
|
||||
this.#size -= 1;
|
||||
entry.resolve(err(failure));
|
||||
}
|
||||
}
|
||||
@@ -130,7 +117,6 @@ export class GhidraRequestQueue {
|
||||
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
|
||||
@@ -163,7 +149,6 @@ export class GhidraRequestQueue {
|
||||
)
|
||||
.finally(() => {
|
||||
this.#active = false;
|
||||
this.#size -= 1;
|
||||
this.#drain();
|
||||
});
|
||||
}
|
||||
@@ -173,7 +158,6 @@ export class GhidraRequestQueue {
|
||||
if (index < 0) return;
|
||||
this.#queue.splice(index, 1);
|
||||
this.#release(entry);
|
||||
this.#size -= 1;
|
||||
entry.resolve(result);
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user