feat(ghidra): implement read-only inventory operations

This commit is contained in:
N0zoM1z0
2026-07-16 02:59:37 +09:00
committed by N0zoM1z0
parent f0e625d7ee
commit b1c07dd9c6
101 changed files with 3825 additions and 377 deletions
+15 -11
View File
@@ -46,7 +46,11 @@ export type {
} from "./toolContractTypes.js";
const document = z.string().optional().describe("The document name");
const address = z.string().describe("A Hopper address");
const address = z
.string()
.describe(
"A provider-normalized address; default memory uses 0x-prefixed hexadecimal",
);
const optionalAddress = address.optional();
const procedure = z.string().describe("The procedure name or address");
const searchPattern = z
@@ -162,7 +166,7 @@ const session = <Name extends string>(
export const OFFICIAL_TOOL_CONTRACTS = [
official(
"address_name",
"Resolve the analyzed name at a code or data address, defaulting to Hopper's current cursor. Use before following a symbol into xrefs; null means Hopper has no name at that address.",
"Resolve the primary analyzed name at a code or data address. Headless providers require an explicit address; GUI providers may default to their current cursor. Null means the provider has no primary name at that address.",
z.object({ document, address: optionalAddress }),
),
official(
@@ -202,27 +206,27 @@ export const OFFICIAL_TOOL_CONTRACTS = [
),
official(
"list_documents",
"List all Hopper documents visible to the bridge. Use before set_current_document when a provider session contains multiple documents.",
"List provider program or document identities. Hopper may expose several documents; a Ghidra headless session contains exactly its one imported Program.",
z.object({}),
),
official(
"list_names",
"Page through analyzed names as address/value pairs. Results are bounded by offset and limit; follow next_offset until has_more is false before claiming exhaustive symbol coverage.",
"Page through analyzed memory and external symbols as address/value pairs. Provider metadata distinguishes Ghidra primary, dynamic, external, type, and source facts when available; follow next_offset before claiming exhaustive coverage.",
z.object({ document, address: optionalAddress, ...pagination }),
),
official(
"list_procedures",
"Page through analyzed procedures as address/value pairs. Wait for Hopper analysis first, then follow next_offset for exhaustive coverage; use returned addresses with analyze_function or procedure_pseudo_code.",
"Page through analyzed procedures as address/value pairs after provider analysis. Ghidra metadata distinguishes thunks and external functions; follow next_offset for exhaustive coverage and use returned addresses in later function operations.",
z.object({ document, ...pagination }),
),
official(
"list_segments",
"List all segments and sections in the selected document. Hopper's public API does not expose permissions, so writable and executable are null with explicit capability metadata.",
"List segments or memory blocks using exclusive end addresses. Ghidra reports block permissions, address space, image base, initialization, and overlay facts; Hopper marks unavailable permissions explicitly.",
z.object({ document }),
),
official(
"list_strings",
"Page through analyzed strings, or filter to one address, as address/value pairs. Follow next_offset for exhaustive results and use xrefs on interesting string addresses.",
"Page through provider-defined strings, or filter to one address, as address/value pairs. Ghidra reports charset, missing-terminator status, byte length, and explicit value truncation; follow next_offset for exhaustive results.",
z.object({ document, address: optionalAddress, ...pagination }),
),
official(
@@ -237,7 +241,7 @@ export const OFFICIAL_TOOL_CONTRACTS = [
),
official(
"procedure_address",
"Resolve a procedure symbol name or hexadecimal address to its entry address. Use this to canonicalize user-supplied identifiers before xrefs, assembly, or decompilation.",
"Resolve an unambiguous procedure symbol name or provider-normalized address to its canonical entry address. External address spaces remain explicit; use the result before xrefs, assembly, or decompilation.",
z.object({ procedure, document }),
),
official(
@@ -279,17 +283,17 @@ export const OFFICIAL_TOOL_CONTRACTS = [
),
official(
"resolve_containing_procedure",
"Resolve an arbitrary address, including an xref source or interior instruction, to its Hopper-analyzed containing procedure. A negative result includes an explicit reason and is not guessed from nearby symbols.",
"Resolve an arbitrary address, including an interior instruction or exact external entry, to its provider-analyzed containing procedure. A negative result distinguishes outside segments from not in a procedure and is never guessed from nearby symbols.",
z.object({ address, document }),
),
official(
"search_procedures",
"Search analyzed procedure names using literal matching by default or regex opt-in. Regex rejects unsupported constructs, more than 10,000 static backtracking paths, candidates over 4,096 characters, and searches over 1,000,000 work units. Results are deterministic and offset-paginated.",
"Search analyzed procedure names using literal matching by default or regex opt-in. Ghidra bounds literal work and rejects regex constructs, paths, candidates, or cumulative work outside its finite budgets. Results are deterministic and offset-paginated.",
z.object(searchInput),
),
official(
"search_strings",
"Search analyzed strings using literal matching by default or regex opt-in. Regex rejects unsupported constructs, more than 10,000 static backtracking paths, candidates over 4,096 characters, and searches over 1,000,000 work units. Results are deterministic, offset-paginated, and explicitly truncated.",
"Search analyzed strings using literal matching by default or regex opt-in. Ghidra bounds literal work and rejects regex constructs, paths, candidates, or cumulative work outside its finite budgets. Results are deterministic, offset-paginated, and explicitly truncated.",
z.object(searchInput),
),
official(
+40 -4
View File
@@ -254,6 +254,10 @@ const unavailable = z.object({
available: z.literal(false),
reason: z.string(),
});
const availableMemoryPermissions = z.object({
available: z.literal(true),
source: z.literal("ghidra-memory-block"),
});
const bounded = (item: z.ZodType) =>
z.object({
items: z.array(item),
@@ -262,8 +266,36 @@ const bounded = (item: z.ZodType) =>
truncated: z.boolean(),
next_offset: z.number().int().min(0).nullable(),
});
const addressedValue = z.object({
address: z.string(),
value: z.string(),
value_truncated: z.boolean().optional(),
symbol: z
.object({
primary: z.boolean(),
dynamic: z.boolean(),
external: z.boolean(),
type: z.string(),
source: z.enum(["default", "analysis", "ai", "imported", "user_defined"]),
})
.optional(),
procedure: z
.object({
external: z.boolean(),
thunk: z.boolean(),
thunk_target: z.string().nullable(),
})
.optional(),
string: z
.object({
encoding: z.string(),
termination: z.enum(["missing", "present_or_not_required"]),
byte_length: z.number().int().min(0),
})
.optional(),
});
const pageOutput = z.object({
items: z.array(z.object({ address: z.string(), value: z.string() })),
items: z.array(addressedValue),
offset: z.number().int().min(0),
limit: z.number().int().min(1),
total: z.number().int().min(0),
@@ -286,8 +318,12 @@ const memoryRegionOutput = z.object({
readable: z.boolean().nullable(),
writable: z.boolean().nullable(),
executable: z.boolean().nullable(),
permissions: unavailable,
provenance: z.literal("hopper-public-python-api"),
permissions: z.union([unavailable, availableMemoryPermissions]),
provenance: z.enum(["hopper-public-python-api", "ghidra-memory-block"]),
address_space: z.string().optional(),
image_base: z.string().optional(),
initialized: z.boolean().optional(),
overlay: z.boolean().optional(),
});
const segmentOutput = resultOf(
z.array(memoryRegionOutput.extend({ sections: z.array(memoryRegionOutput) })),
@@ -323,7 +359,7 @@ const graphNode = z.discriminatedUnion("status", [
]);
const functionDossierOutput = resultOf(functionDossierSchema);
/** Exact structured-content schemas for the direct Hopper operations. */
/** Exact structured-content schemas shared by direct analysis providers. */
export const officialOutputSchemas: Readonly<Record<string, z.ZodObject>> = {
address_name: resultOf(nullableText),
comment: resultOf(nullableText),
+23 -3
View File
@@ -24,9 +24,29 @@ export interface AddressedPage {
readonly hasMore: boolean;
}
/** Return the non-negative byte distance between hexadecimal addresses. */
export const addressDistance = (start: string, end: string): number =>
Math.max(0, Number.parseInt(end, 16) - Number.parseInt(start, 16));
/** Return a bounded byte distance between canonical addresses in one space. */
export const addressDistance = (start: string, end: string): number => {
const left = addressCoordinate(start);
const right = addressCoordinate(end);
if (left === null || right === null || left.space !== right.space) return 0;
const distance = right.offset - left.offset;
if (distance <= 0n) return 0;
return Number(
distance > BigInt(Number.MAX_SAFE_INTEGER)
? BigInt(Number.MAX_SAFE_INTEGER)
: distance,
);
};
const addressCoordinate = (
value: string,
): { readonly space: string; readonly offset: bigint } | null => {
const separator = value.lastIndexOf(":0x");
const space = separator < 0 ? "default" : value.slice(0, separator);
const offset = separator < 0 ? value : value.slice(separator + 1);
if (!/^0x[0-9a-f]+$/u.test(offset)) return null;
return { space, offset: BigInt(offset) };
};
const procedureMapSchema = z.record(z.string(), z.string());
const addressedNamesSchema = z.array(
+34 -33
View File
@@ -21,13 +21,18 @@ import {
} from "./GhidraDefaults.js";
import type {
GhidraClientOptions,
GhidraRequestOptions,
GhidraStartResult,
} from "./GhidraClientTypes.js";
import type { GhidraInventoryOperation } from "./GhidraInventoryValues.js";
import { createGhidraDiagnostics } from "./GhidraDiagnostics.js";
import type { GhidraLaunch } from "./GhidraLauncher.js";
import { GhidraResponseBuffer } from "./GhidraResponseBuffer.js";
import { GhidraResponseRouter } from "./GhidraResponseRouter.js";
import { GhidraSessionError } from "./GhidraSessionError.js";
import {
bindGhidraSessionFailure,
GhidraSessionError,
} from "./GhidraSessionError.js";
import {
isGhidraShutdownAcknowledgement,
parseGhidraSessionInfo,
@@ -44,6 +49,7 @@ const SESSION_ROOT = "/tmp";
export type {
GhidraClientOptions,
GhidraDiagnostic,
GhidraRequestOptions,
GhidraStartResult,
} from "./GhidraClientTypes.js";
@@ -72,10 +78,14 @@ export class GhidraClient {
#startupController: AbortController | undefined;
#startPromise: Promise<GhidraStartResult> | undefined;
#closePromise: Promise<void> | undefined;
readonly #failure = bindGhidraSessionFailure(() => this.#diagnostics());
readonly #responseRouter = new GhidraResponseRouter({
pending: this.#pending,
nextId: () => this.#nextId,
remoteFailure: (message, cause) => this.#failure("remote", message, cause),
remoteFailure: (failure) =>
this.#failure("remote", failure.message, failure, {
remoteCode: failure.code,
}),
protocolFailure: (message, cause) => this.#abortProtocol(message, cause),
});
readonly #responseBuffer = new GhidraResponseBuffer({
@@ -131,10 +141,7 @@ export class GhidraClient {
/** Revalidate live bridge, provider, run, and profile metadata. */
async ping(
options: {
readonly signal?: AbortSignal;
readonly timeoutMs?: number;
} = {},
options: GhidraRequestOptions = {},
): Promise<Result<GhidraSessionInfo, GhidraSessionError>> {
const started = await this.start(options.signal);
if (!started.ok) return started;
@@ -143,6 +150,17 @@ export class GhidraClient {
return this.#parseSessionInfo(result.value);
}
/** Execute one admitted inventory operation after the exact session handshake. */
async callTool(
operation: GhidraInventoryOperation,
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);
}
/** Stop the owned process group and remove all project/runtime artifacts. */
close(): Promise<void> {
const starting = this.#startPromise;
@@ -302,7 +320,7 @@ export class GhidraClient {
async #request(
method: string,
params: JsonValue,
options: { readonly signal?: AbortSignal; readonly timeoutMs?: number },
options: GhidraRequestOptions,
): Promise<Result<JsonValue, GhidraSessionError>> {
const socket = this.#socket;
const token = this.#token;
@@ -351,9 +369,7 @@ export class GhidraClient {
return result;
}
#parseSessionInfo(
value: JsonValue,
): Result<GhidraSessionInfo, GhidraSessionError> {
#parseSessionInfo(value: JsonValue) {
const runId = this.#runId;
if (runId === undefined)
return err(this.#failure("protocol", "Ghidra run identity is missing"));
@@ -362,15 +378,14 @@ export class GhidraClient {
providerVersion: this.#options.providerVersion,
profileDigest: this.#options.profileDigest,
});
return parsed.ok
? parsed
: err(
this.#failure(
"protocol",
"Ghidra bridge handshake is invalid",
parsed.error,
),
);
if (parsed.ok) return parsed;
return err(
this.#failure(
"protocol",
"Ghidra bridge handshake is invalid",
parsed.error,
),
);
}
async #close(
@@ -496,20 +511,6 @@ export class GhidraClient {
});
}
#failure(
kind: GhidraSessionError["kind"],
message: string,
cause?: unknown,
options: { readonly timeoutMs?: number } = {},
): GhidraSessionError {
return new GhidraSessionError(kind, message, this.#diagnostics(), {
...(cause === undefined ? {} : { cause }),
...(options.timeoutMs === undefined
? {}
: { timeoutMs: options.timeoutMs }),
});
}
#diagnostics(): Readonly<Record<string, JsonValue>> {
const snapshot = this.#process?.snapshot() ?? this.#processSnapshot;
return createGhidraDiagnostics({
+6
View File
@@ -7,6 +7,12 @@ import type { GhidraSessionInfo } from "./GhidraSessionValues.js";
/** Result of opening and authenticating one headless Ghidra session. */
export type GhidraStartResult = Result<GhidraSessionInfo, GhidraSessionError>;
/** Cancellation and deadline controls shared by authenticated requests. */
export interface GhidraRequestOptions {
readonly signal?: AbortSignal;
readonly timeoutMs?: number;
}
/** Safe lifecycle telemetry for one isolated Ghidra headless process. */
export type GhidraDiagnostic =
| {
+1 -1
View File
@@ -11,4 +11,4 @@ export const GHIDRA_REQUEST_TIMEOUT_MS = 10_000;
/** 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 = 1;
export const GHIDRA_BRIDGE_VERSION = 2;
+243
View File
@@ -0,0 +1,243 @@
import { z } from "zod";
import { AnalysisInputError, AnalysisOutputError } from "../domain/errors.js";
import {
jsonObjectSchema,
jsonValueSchema,
type JsonValue,
} from "../domain/jsonValue.js";
import { err, ok, type Result } from "../domain/result.js";
/** Read-only direct operations admitted by the Ghidra v1 adapter. */
export const GHIDRA_INVENTORY_OPERATIONS = [
"address_name",
"list_documents",
"list_names",
"list_procedures",
"list_segments",
"list_strings",
"procedure_address",
"resolve_containing_procedure",
"search_procedures",
"search_strings",
] as const;
/** One direct inventory operation implemented by the packaged Java bridge. */
export type GhidraInventoryOperation =
(typeof GHIDRA_INVENTORY_OPERATIONS)[number];
const operationSet: ReadonlySet<string> = new Set(GHIDRA_INVENTORY_OPERATIONS);
/** Narrow an application operation to the Ghidra inventory surface. */
export const isGhidraInventoryOperation = (
operation: string,
): operation is GhidraInventoryOperation => operationSet.has(operation);
const boundedIdentifier = z.string().min(1).max(4096);
const document = boundedIdentifier.nullable().default(null);
const explicitAddress = boundedIdentifier;
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),
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_segments: z.object({ document }).strict(),
list_strings: z
.object({ document, address: filteredAddress, ...pagination })
.strict(),
procedure_address: z
.object({ document, procedure: boundedIdentifier })
.strict(),
resolve_containing_procedure: z
.object({ document, address: explicitAddress })
.strict(),
search_procedures: z.object(searchInput).strict(),
search_strings: z.object(searchInput).strict(),
} satisfies Readonly<Record<GhidraInventoryOperation, z.ZodType>>;
/** Validate and default one provider request before it crosses the socket. */
export const parseGhidraInventoryInput = (
operation: GhidraInventoryOperation,
value: Readonly<Record<string, JsonValue>>,
): Result<Readonly<Record<string, JsonValue>>, AnalysisInputError> => {
const parsed = inputSchemas[operation].safeParse(value);
if (!parsed.success)
return err(new AnalysisInputError(operation, { cause: parsed.error }));
return ok(jsonObjectSchema.parse(parsed.data));
};
const canonicalAddress = z
.string()
.regex(/^(?:0x[0-9a-f]+|(?:[A-Za-z0-9._~-]|%[0-9A-F]{2})+:0x[0-9a-f]+)$/u);
const valueTruncation = { value_truncated: z.boolean() };
const symbolFacts = z
.object({
primary: z.boolean(),
dynamic: z.boolean(),
external: z.boolean(),
type: z.string().min(1),
source: z.enum(["default", "analysis", "ai", "imported", "user_defined"]),
})
.strict();
const procedureFacts = z
.object({
external: z.boolean(),
thunk: z.boolean(),
thunk_target: canonicalAddress.nullable(),
})
.strict();
const stringFacts = z
.object({
encoding: z.string().min(1),
termination: z.enum(["missing", "present_or_not_required"]),
byte_length: z.number().int().min(0),
})
.strict();
const baseItem = {
address: canonicalAddress,
value: z.string(),
...valueTruncation,
};
const symbolItem = z.object({ ...baseItem, symbol: symbolFacts }).strict();
const procedureItem = z
.object({ ...baseItem, procedure: procedureFacts })
.strict();
const stringItem = z.object({ ...baseItem, string: stringFacts }).strict();
const searchItem = z.object(baseItem).strict();
const pageSchema = <Item extends z.ZodType>(item: Item, maximumLimit: number) =>
z
.object({
items: z.array(item),
offset: z.number().int().min(0),
limit: z.number().int().min(1).max(maximumLimit),
total: z.number().int().min(0),
next_offset: z.number().int().min(0).nullable(),
has_more: z.boolean(),
})
.strict()
.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),
source: z.literal("ghidra-memory-block"),
})
.strict();
const memoryRegion = z
.object({
name: z.string(),
start: canonicalAddress,
end: canonicalAddress,
readable: z.boolean(),
writable: z.boolean(),
executable: z.boolean(),
permissions: availablePermissions,
provenance: z.literal("ghidra-memory-block"),
address_space: z.string().min(1),
image_base: canonicalAddress,
initialized: z.boolean(),
overlay: z.boolean(),
})
.strict();
const segment = memoryRegion
.extend({ sections: z.array(memoryRegion) })
.strict();
const containingProcedure = z.discriminatedUnion("found", [
z
.object({
query_address: canonicalAddress,
found: z.literal(true),
procedure: z
.object({ address: canonicalAddress, name: z.string().min(1) })
.strict(),
})
.strict(),
z
.object({
query_address: canonicalAddress,
found: z.literal(false),
procedure: z.null(),
reason: z.enum(["outside_segments", "not_in_procedure"]),
})
.strict(),
]);
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_segments: z.array(segment),
list_strings: pageSchema(stringItem, 500),
procedure_address: canonicalAddress,
resolve_containing_procedure: containingProcedure,
search_procedures: pageSchema(searchItem, 100),
search_strings: pageSchema(searchItem, 100),
} satisfies Readonly<Record<GhidraInventoryOperation, z.ZodType>>;
/** Require exact, bounded Java-bridge output before creating Evidence. */
export const parseGhidraInventoryResult = (
operation: GhidraInventoryOperation,
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 inventory contract",
{ cause: parsed.error },
),
);
};
+169 -16
View File
@@ -17,17 +17,28 @@ import type { BinaryTarget } from "../domain/binaryTarget.js";
import {
AnalysisCancelledError,
AnalysisCapabilityUnavailableError,
AnalysisInputError,
type AnalysisError,
AnalysisTimeoutError,
ProviderAdapterError,
} 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 { GhidraClient } from "./GhidraClient.js";
import type { GhidraClientOptions } from "./GhidraClientTypes.js";
import {
GHIDRA_ANALYSIS_TIMEOUT_SECONDS,
GHIDRA_MAX_LINE_BYTES,
GHIDRA_REQUEST_TIMEOUT_MS,
GHIDRA_STARTUP_TIMEOUT_MS,
} from "./GhidraDefaults.js";
import {
GHIDRA_INVENTORY_OPERATIONS,
isGhidraInventoryOperation,
parseGhidraInventoryInput,
parseGhidraInventoryResult,
} from "./GhidraInventoryValues.js";
import {
ghidraInstallationDiagnostics,
inspectGhidraInstallation,
@@ -45,13 +56,123 @@ export const GHIDRA_PROVIDER_IDENTITY: ProviderIdentity = Object.freeze({
version: null,
});
/** PR07 intentionally exposes session health but no binary operation contract. */
export const GHIDRA_PROVIDER_TOOL_CONTRACTS: readonly CapabilityDescriptor[] =
Object.freeze([]);
const officialContractByName = new Map(
OFFICIAL_TOOL_CONTRACTS.map((contract) => [contract.name, contract]),
);
/** Direct 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;
}),
);
const PAGINATED_OPERATIONS: ReadonlySet<string> = new Set([
"list_names",
"list_procedures",
"list_strings",
"search_procedures",
"search_strings",
]);
const SEARCH_OPERATIONS: ReadonlySet<string> = new Set([
"search_procedures",
"search_strings",
]);
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.",
]);
const limitationsFor = (operation: string): readonly string[] => {
const common = [
...healthLimitations,
"Default-space addresses use lowercase 0x-prefixed hexadecimal; other address spaces use <percent-encoded-space>:0x<hex>.",
];
switch (operation) {
case "list_documents":
return [
...common,
"A headless Ghidra session contains exactly one imported Program, unlike Hopper's multi-document GUI session.",
];
case "list_names":
return [
...common,
"The symbol inventory includes memory and external symbols, including dynamic symbols, but excludes variable and no-address namespace records.",
];
case "list_procedures":
case "procedure_address":
return [
...common,
"External functions and local thunks are distinct; procedure metadata identifies both and preserves a thunk target when Ghidra resolves one.",
];
case "list_strings":
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 [
...common,
"Memory-block end addresses are exclusive; permissions come from Ghidra MemoryBlock flags rather than inference from section names.",
];
case "search_procedures":
case "search_strings":
return [
...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.",
];
default:
return common;
}
};
const CAPABILITIES: readonly CapabilityDescriptor[] = Object.freeze(
GHIDRA_PROVIDER_TOOL_CONTRACTS.map((contract) =>
Object.freeze({
provider: GHIDRA_PROVIDER_IDENTITY,
operation: contract.name,
inputContractVersion: 1,
outputContractVersion: 1,
available: true,
reason: null,
pagination: PAGINATED_OPERATIONS.has(contract.name)
? ("offset" as const)
: ("none" as const),
exhaustive: !PAGINATED_OPERATIONS.has(contract.name),
effects: Object.freeze({
mutatesArtifact: false,
launchesProcess: true,
mayShowUi: false,
mayAccessNetwork: false,
mayWriteFilesystem: true,
changesPermissions: false,
requiresRoot: false,
}),
limits: Object.freeze({
maxResults: PAGINATED_OPERATIONS.has(contract.name)
? SEARCH_OPERATIONS.has(contract.name)
? 100
: 500
: null,
maxPayloadBytes: GHIDRA_MAX_LINE_BYTES,
timeoutMs: GHIDRA_REQUEST_TIMEOUT_MS,
}),
limitations: Object.freeze(limitationsFor(contract.name)),
}),
),
);
const SUPPORTED_ARCHITECTURES = new Set(["x86", "x86_64", "arm", "arm64"]);
const SUPPORTED_FORMATS = new Set(["elf", "pe", "mach-o"]);
/** Production seam for exercising provider projection without a real process. */
export type GhidraProviderClientFactory = (
options: GhidraClientOptions,
) => Pick<GhidraClient, "start" | "callTool" | "close">;
/** Linux Ghidra candidate backed by an isolated read-only headless import. */
export class GhidraProvider implements AnalysisProviderCandidate {
#installation: GhidraInstallationInspection | undefined;
@@ -60,6 +181,8 @@ export class GhidraProvider implements AnalysisProviderCandidate {
private readonly config: AppConfig,
private readonly logger: Logger,
private readonly installationHost?: GhidraInstallationHost,
private readonly clientFactory: GhidraProviderClientFactory = (options) =>
new GhidraClient(options),
) {}
identity(): ProviderIdentity {
@@ -67,7 +190,7 @@ export class GhidraProvider implements AnalysisProviderCandidate {
}
capabilities(): readonly CapabilityDescriptor[] {
return GHIDRA_PROVIDER_TOOL_CONTRACTS;
return CAPABILITIES;
}
inspectAvailability(): ProviderAvailability {
@@ -152,7 +275,7 @@ export class GhidraProvider implements AnalysisProviderCandidate {
);
if (!prerequisites.ok) return unavailableClient(prerequisites.error);
const committedProfile = prerequisites.value.profile;
const client = new GhidraClient({
const client = this.clientFactory({
launcher: new GhidraHeadlessLauncher({
analyzeHeadlessPath: prerequisites.value.analyzeHeadlessPath,
...(this.config.ghidraJavaHome === undefined
@@ -168,25 +291,42 @@ export class GhidraProvider implements AnalysisProviderCandidate {
logger: this.logger.child({ layer: "ghidra-bridge" }),
});
return {
execute: async (operation, _parameters, options) => {
if (operation !== "health")
execute: async (operation, parameters, options) => {
if (operation !== "health" && !isGhidraInventoryOperation(operation))
return err(
new AnalysisCapabilityUnavailableError(
GHIDRA_PROVIDER_IDENTITY.id,
operation,
"Ghidra binary operations are not declared by this adapter release.",
"The Ghidra adapter does not declare this operation.",
),
);
const started = await client.start(options?.signal);
if (!started.ok)
return err(projectSessionError(operation, started.error));
if (operation === "health") {
const started = await client.start(options?.signal);
if (!started.ok)
return err(projectSessionError(operation, started.error));
return ok(
createAnalysisExecution(started.value, committedProfile.provider, {
analysisProfile: committedProfile,
limitations: healthLimitations,
}),
);
}
const input = parseGhidraInventoryInput(operation, parameters);
if (!input.ok) return input;
const called = await client.callTool(
operation,
input.value,
options?.signal === undefined ? {} : { signal: options.signal },
);
if (!called.ok)
return err(projectSessionError(operation, called.error));
const result = parseGhidraInventoryResult(operation, called.value);
if (!result.ok) return result;
return ok(
createAnalysisExecution(started.value, committedProfile.provider, {
createAnalysisExecution(result.value, committedProfile.provider, {
rawResult: called.value,
analysisProfile: committedProfile,
limitations: [
"The session proves completed default Ghidra auto-analysis but exposes no binary operations in this release.",
"The imported program and project are ephemeral and externally read-only.",
],
limitations: limitationsFor(operation),
}),
);
},
@@ -268,6 +408,19 @@ const projectSessionError = (
? GHIDRA_ANALYSIS_TIMEOUT_SECONDS * 1_000
: GHIDRA_STARTUP_TIMEOUT_MS),
);
if (
failure.kind === "remote" &&
["invalid_request", "not_found", "ambiguous"].includes(
failure.remoteCode ?? "",
)
)
return new AnalysisInputError(operation, { cause: failure });
if (failure.kind === "remote" && failure.remoteCode === "method_unavailable")
return new AnalysisCapabilityUnavailableError(
"ghidra",
operation,
failure.message,
);
return new ProviderAdapterError("ghidra", operation, {
cause: failure,
diagnostics: failure.diagnostics,
+3 -4
View File
@@ -3,6 +3,7 @@ import { err, type Result } from "../domain/result.js";
import type { PendingOperations } from "../process/PendingOperations.js";
import type { GhidraSessionError } from "./GhidraSessionError.js";
import { ghidraResponseResult, parseGhidraResponseLine } from "./protocol.js";
import type { GhidraRemoteError } from "./protocol.js";
/** Dependencies for correlating validated bridge responses. */
export interface GhidraResponseRouterOptions {
@@ -11,7 +12,7 @@ export interface GhidraResponseRouterOptions {
Result<JsonValue, GhidraSessionError>
>;
readonly nextId: () => number;
readonly remoteFailure: (message: string, cause: Error) => GhidraSessionError;
readonly remoteFailure: (failure: GhidraRemoteError) => GhidraSessionError;
readonly protocolFailure: (message: string, cause?: Error) => void;
}
@@ -38,9 +39,7 @@ export class GhidraResponseRouter {
const result = ghidraResponseResult(parsed.value);
this.#options.pending.settle(
parsed.value.id,
result.ok
? result
: err(this.#options.remoteFailure(result.error.message, result.error)),
result.ok ? result : err(this.#options.remoteFailure(result.error)),
);
}
}
+50
View File
@@ -13,12 +13,14 @@ export type GhidraSessionFailureKind =
/** Additional structured context for a Ghidra session failure. */
export interface GhidraSessionErrorOptions extends ErrorOptions {
readonly timeoutMs?: number;
readonly remoteCode?: string;
}
/** Provider-owned failure with bounded, token-redacted local diagnostics. */
export class GhidraSessionError extends Error {
readonly diagnostics: Readonly<Record<string, JsonValue>>;
readonly timeoutMs: number | undefined;
readonly remoteCode: string | undefined;
constructor(
readonly kind: GhidraSessionFailureKind,
@@ -30,5 +32,53 @@ export class GhidraSessionError extends Error {
this.name = "GhidraSessionError";
this.diagnostics = structuredClone(diagnostics);
this.timeoutMs = options.timeoutMs;
this.remoteCode = options.remoteCode;
}
}
/** Build a session failure while preserving bounded remote failure metadata. */
const createGhidraSessionError = (failure: {
readonly kind: GhidraSessionFailureKind;
readonly message: string;
readonly diagnostics: Readonly<Record<string, JsonValue>>;
readonly cause?: unknown;
readonly timeoutMs?: number;
readonly remoteCode?: string;
}): GhidraSessionError =>
new GhidraSessionError(
failure.kind,
failure.message,
failure.remoteCode === undefined
? failure.diagnostics
: {
...failure.diagnostics,
remote_code: failure.remoteCode,
remote_message: failure.message,
},
{
...(failure.cause === undefined ? {} : { cause: failure.cause }),
...(failure.timeoutMs === undefined
? {}
: { timeoutMs: failure.timeoutMs }),
...(failure.remoteCode === undefined
? {}
: { remoteCode: failure.remoteCode }),
},
);
/** Bind session-failure construction to a live, token-redacted diagnostic view. */
export const bindGhidraSessionFailure =
(diagnostics: () => Readonly<Record<string, JsonValue>>) =>
(
kind: GhidraSessionFailureKind,
message: string,
cause?: unknown,
options: Pick<GhidraSessionErrorOptions, "timeoutMs" | "remoteCode"> = {},
): GhidraSessionError =>
createGhidraSessionError({
kind,
message,
diagnostics: diagnostics(),
...(cause === undefined ? {} : { cause }),
...options,
});
+20 -4
View File
@@ -3,6 +3,16 @@ import { z } from "zod";
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";
/** Exact methods proved by the bridge handshake after auto-analysis. */
export const GHIDRA_SESSION_CAPABILITIES = [
"ping",
"shutdown",
...GHIDRA_INVENTORY_OPERATIONS,
] as const;
const capabilitySchema = z.enum(GHIDRA_SESSION_CAPABILITIES);
const sessionInfoSchema = z
.object({
@@ -19,12 +29,16 @@ const sessionInfoSchema = z
read_only: z.literal(true),
analysis_complete: z.boolean(),
analysis_timed_out: z.boolean(),
capabilities: z.array(z.enum(["ping", "shutdown"])).max(2),
capabilities: z
.array(capabilitySchema)
.length(GHIDRA_SESSION_CAPABILITIES.length),
target: z
.object({
name: z.string().min(1),
language_id: z.string().min(1),
compiler_spec_id: z.string().min(1),
image_base: z.string().regex(/^0x[0-9a-f]+$/u),
default_address_space: z.string().min(1),
})
.strict(),
})
@@ -48,9 +62,11 @@ export const parseGhidraSessionInfo = (
parsed.data.run_id !== expected.runId ||
parsed.data.provider.version !== expected.providerVersion ||
parsed.data.profile_digest !== expected.profileDigest ||
new Set(parsed.data.capabilities).size !== 2 ||
!parsed.data.capabilities.includes("ping") ||
!parsed.data.capabilities.includes("shutdown") ||
new Set(parsed.data.capabilities).size !==
GHIDRA_SESSION_CAPABILITIES.length ||
GHIDRA_SESSION_CAPABILITIES.some(
(capability) => !parsed.data.capabilities.includes(capability),
) ||
parsed.data.analysis_complete === parsed.data.analysis_timed_out
)
return err(new Error("Ghidra bridge handshake identity is invalid"));
+15 -3
View File
@@ -47,6 +47,17 @@ const responseSchema = z
/** Validated response emitted by REA's packaged Ghidra script. */
export type GhidraBridgeResponse = z.infer<typeof responseSchema>;
/** Expected operation failure returned by the authenticated Java bridge. */
export class GhidraRemoteError extends Error {
constructor(
readonly code: string,
message: string,
) {
super(message);
this.name = "GhidraRemoteError";
}
}
/** Parse one complete Java-bridge response without accepting extra fields. */
export const parseGhidraResponseLine = (
line: string,
@@ -67,11 +78,12 @@ export const parseGhidraResponseLine = (
/** Project one validated response into its result or remote failure. */
export const ghidraResponseResult = (
response: GhidraBridgeResponse,
): Result<JsonValue, Error> =>
): Result<JsonValue, GhidraRemoteError> =>
response.ok
? ok(response.result ?? null)
: err(
new Error(
`${response.error?.code ?? "bridge_error"}: ${response.error?.message ?? "Ghidra bridge request failed"}`,
new GhidraRemoteError(
response.error?.code ?? "bridge_error",
response.error?.message ?? "Ghidra bridge request failed",
),
);