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
+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);