refactor(tools): remove artificial analysis ceilings

This commit is contained in:
morluto
2026-09-29 16:29:23 +08:00
parent 36aeec9586
commit 2f08c7c932
202 changed files with 2314 additions and 3072 deletions
-8
View File
@@ -10,11 +10,6 @@ import {
type AnalysisError,
} from "../domain/errors.js";
import { err, ok, type Result } from "../domain/result.js";
import {
GHIDRA_ANALYSIS_TIMEOUT_SECONDS,
GHIDRA_MAX_CPU,
GHIDRA_MAX_HEAP,
} from "./GhidraDefaults.js";
import type { GhidraInstallationInspection } from "./GhidraInstallation.js";
/** Resolve version-bound, deterministic semantics before Ghidra imports a target. */
@@ -47,9 +42,6 @@ export const resolveGhidraAnalysisProfile = (
language_id: "auto-from-header",
compiler_spec_id: "auto-default",
analyzer_preset: "ghidra-default",
analysis_timeout_seconds: GHIDRA_ANALYSIS_TIMEOUT_SECONDS,
max_cpu: GHIDRA_MAX_CPU,
max_heap: GHIDRA_MAX_HEAP,
}),
compatibility: {
languageId: "auto",
+10 -26
View File
@@ -15,11 +15,7 @@ import {
type ProviderProcessSnapshot,
ProviderProcessSupervisor,
} from "../process/ProviderProcess.js";
import {
GHIDRA_MAX_LINE_BYTES,
GHIDRA_REQUEST_TIMEOUT_MS,
GHIDRA_STARTUP_TIMEOUT_MS,
} from "./GhidraDefaults.js";
import { GHIDRA_STARTUP_TIMEOUT_MS } from "./GhidraDefaults.js";
import type {
GhidraClientOptions,
GhidraRequestOptions,
@@ -65,10 +61,7 @@ export type GhidraOperation =
/** Owns one authenticated, private, read-only Ghidra headless session. */
export class GhidraClient {
readonly #options: Required<
Pick<
GhidraClientOptions,
"requestTimeoutMs" | "startupTimeoutMs" | "transport"
>
Pick<GhidraClientOptions, "startupTimeoutMs" | "transport">
> &
GhidraClientOptions;
readonly #logger: Logger;
@@ -105,9 +98,7 @@ export class GhidraClient {
protocolFailure: (message, cause) => this.#abortProtocol(message, cause),
});
readonly #responseBuffer = new GhidraResponseBuffer({
maxLineBytes: GHIDRA_MAX_LINE_BYTES,
onLine: (line) => this.#responseRouter.route(line),
onFailure: (message) => this.#abortProtocol(message),
});
readonly #onSocketData = (chunk: string): void =>
this.#responseBuffer.push(chunk);
@@ -122,7 +113,6 @@ export class GhidraClient {
constructor(options: GhidraClientOptions) {
this.#options = {
...options,
requestTimeoutMs: options.requestTimeoutMs ?? GHIDRA_REQUEST_TIMEOUT_MS,
startupTimeoutMs: options.startupTimeoutMs ?? GHIDRA_STARTUP_TIMEOUT_MS,
transport: options.transport ?? "unix-socket",
};
@@ -132,20 +122,13 @@ export class GhidraClient {
getToken: () => this.#token,
nextId: () => this.#nextId++,
pending: this.#pending,
requestTimeoutMs: this.#options.requestTimeoutMs,
logger: this.#logger,
failure: this.#failure,
});
this.#requestQueue = new GhidraRequestQueue(
(method, parameters, requestOptions) =>
this.#wire.request(method, parameters, requestOptions),
(kind, message, timeoutMs) =>
this.#failure(
kind,
message,
undefined,
timeoutMs === undefined ? {} : { timeoutMs },
),
(kind, message) => this.#failure(kind, message),
);
}
@@ -187,18 +170,19 @@ export class GhidraClient {
return this.#parseSessionInfo(result.value);
}
/** Execute one admitted operation through the bounded per-Program queue. */
/** Execute one admitted operation through the serial per-Program queue. */
async callTool(
operation: GhidraOperation,
parameters: Readonly<Record<string, JsonValue>>,
options: GhidraRequestOptions = {},
options: { readonly signal?: AbortSignal } = {},
): Promise<Result<JsonValue, GhidraSessionError>> {
const started = await this.start(options.signal);
if (!started.ok) return started;
return this.#requestQueue.run(operation, parameters, {
...(options.signal === undefined ? {} : { signal: options.signal }),
timeoutMs: options.timeoutMs ?? this.#options.requestTimeoutMs,
});
return this.#requestQueue.run(
operation,
parameters,
options.signal === undefined ? {} : { signal: options.signal },
);
}
/** Stop the owned process group and remove all project/runtime artifacts. */
+1 -1
View File
@@ -11,6 +11,7 @@ export type GhidraStartResult = Result<GhidraSessionInfo, GhidraSessionError>;
/** Cancellation and deadline controls shared by authenticated requests. */
export interface GhidraRequestOptions {
readonly signal?: AbortSignal;
/** Internal startup/shutdown deadline; analysis calls have no fixed deadline. */
readonly timeoutMs?: number;
}
@@ -39,7 +40,6 @@ export interface GhidraClientOptions {
readonly transport?: GhidraTransportKind;
readonly providerVersion: string;
readonly profileDigest: string;
readonly requestTimeoutMs?: number;
readonly startupTimeoutMs?: number;
readonly onDiagnostic?: (event: GhidraDiagnostic) => void;
readonly logger?: Logger;
+17 -14
View File
@@ -20,7 +20,6 @@ export interface GhidraWireOptions {
number,
Result<JsonValue, GhidraSessionError>
>;
readonly requestTimeoutMs: number;
readonly logger: Logger;
readonly failure: (
kind: GhidraSessionFailureKind,
@@ -55,28 +54,32 @@ export class GhidraWire {
this.#options.failure("cancelled", "Ghidra request was cancelled"),
);
const id = this.#options.nextId();
const timeoutMs = options.timeoutMs ?? this.#options.requestTimeoutMs;
if (timeoutMs <= 0)
if (options.timeoutMs !== undefined && options.timeoutMs <= 0)
return err(
this.#options.failure(
"timeout",
"Ghidra request deadline elapsed",
undefined,
{ timeoutMs },
{ timeoutMs: options.timeoutMs },
),
);
const timeoutMs = options.timeoutMs;
const response = this.#options.pending.wait(id, {
timeoutMs,
...(timeoutMs === undefined
? {}
: {
timeoutMs,
timeoutValue: () =>
err(
this.#options.failure(
"timeout",
"Ghidra bridge request timed out",
undefined,
{ timeoutMs },
),
),
}),
...(options.signal === undefined ? {} : { signal: options.signal }),
timeoutValue: () =>
err(
this.#options.failure(
"timeout",
"Ghidra bridge request timed out",
undefined,
{ timeoutMs },
),
),
cancelledValue: () =>
err(this.#options.failure("cancelled", "Ghidra request was cancelled")),
});
-16
View File
@@ -1,18 +1,2 @@
/** Maximum wall-clock analysis time passed to Ghidra for one imported file. */
export const GHIDRA_ANALYSIS_TIMEOUT_SECONDS = 300;
/** Maximum CPU cores made available to one headless analysis. */
export const GHIDRA_MAX_CPU = 2;
/** Explicit JVM heap ceiling for one headless provider process. */
export const GHIDRA_MAX_HEAP = "2G";
/** Absolute import, analysis, bridge, and health startup deadline. */
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;
/** Internal safety bound for one complete Java bridge process response line. */
export const GHIDRA_MAX_LINE_BYTES = 64 * 1024 * 1024;
/** Version of REA's Java bridge handshake and request protocol. */
export const GHIDRA_BRIDGE_VERSION = 7;
-10
View File
@@ -15,11 +15,6 @@ import {
type SpawnedOwnedProviderProcess,
spawnOwnedProviderProcess,
} from "../process/ProviderProcess.js";
import {
GHIDRA_ANALYSIS_TIMEOUT_SECONDS,
GHIDRA_MAX_CPU,
GHIDRA_MAX_HEAP,
} from "./GhidraDefaults.js";
import { ghidraJavaEnvironment } from "./GhidraInstallation.js";
import type { GhidraTransportKind } from "./GhidraTransport.js";
@@ -272,10 +267,6 @@ export const ghidraHeadlessArguments = (
options.targetPath,
"-readOnly",
"-deleteProject",
"-analysisTimeoutPerFile",
String(GHIDRA_ANALYSIS_TIMEOUT_SECONDS),
"-max-cpu",
String(GHIDRA_MAX_CPU),
"-log",
options.ghidraLogPath,
"-scriptlog",
@@ -323,7 +314,6 @@ const ghidraLaunchEnvironment = (
XDG_CACHE_HOME: paths.cacheRoot,
XDG_CONFIG_HOME: paths.configRoot,
XDG_DATA_HOME: paths.dataRoot,
GHIDRA_HEADLESS_MAXMEM: GHIDRA_MAX_HEAP,
GHIDRA_HEADLESS_JAVA_OPTIONS: javaOptions,
};
};
+28 -39
View File
@@ -259,9 +259,6 @@ describe("Ghidra client projection", () => {
parameters: {
import_mode: "ephemeral-read-only",
analyzer_preset: "ghidra-default",
analysis_timeout_seconds: 300,
max_cpu: 2,
max_heap: "2G",
},
});
expect(resolved.value.compatibility).toEqual({
@@ -364,44 +361,37 @@ describe("Ghidra result projection", () => {
},
);
it.each([
["decompile_timeout", "AnalysisTimeoutError", 30_000],
["decompile_cancelled", "AnalysisCancelledError", undefined],
] as const)(
"projects remote %s as a provider-neutral interruption",
async (code, tag, timeoutMs) => {
const ghidra = provider(installationHost(), () => ({
start: () => Promise.resolve(ok(sessionInfo())),
callTool: () =>
Promise.resolve(
err(
new GhidraSessionError(
"remote",
"Fixture decompiler interruption",
{ remote_code: code },
{ remoteCode: code },
),
it("projects remote decompile cancellation as a provider-neutral interruption", async () => {
const code = "decompile_cancelled";
const tag = "AnalysisCancelledError";
const ghidra = provider(installationHost(), () => ({
start: () => Promise.resolve(ok(sessionInfo())),
callTool: () =>
Promise.resolve(
err(
new GhidraSessionError(
"remote",
"Fixture decompiler interruption",
{ remote_code: code },
{ remoteCode: code },
),
),
close: () => Promise.resolve(),
}));
const resolved = await ghidra.resolveAnalysisProfile(
executableTarget("elf", "x86_64"),
);
if (!resolved.ok || resolved.value.profile === null) return;
),
close: () => Promise.resolve(),
}));
const resolved = await ghidra.resolveAnalysisProfile(
executableTarget("elf", "x86_64"),
);
if (!resolved.ok || resolved.value.profile === null) return;
const result = await ghidra
.createClient(executableTarget("elf", "x86_64"), resolved.value.profile)
.execute("procedure_pseudo_code", { procedure: "main" });
expect(result).toMatchObject({
ok: false,
error: {
_tag: tag,
...(timeoutMs === undefined ? {} : { timeoutMs }),
},
});
},
);
const result = await ghidra
.createClient(executableTarget("elf", "x86_64"), resolved.value.profile)
.execute("procedure_pseudo_code", { procedure: "main" });
expect(result).toMatchObject({
ok: false,
error: { _tag: tag },
});
});
it("returns cancellation before profile work", async () => {
const controller = new AbortController();
@@ -419,7 +409,6 @@ describe("Ghidra result projection", () => {
const sessionInfo = () => ({
name: "REA Ghidra bridge" as const,
bridge_version: 7 as const,
run_id: "11111111-1111-4111-8111-111111111111",
profile_digest: "a".repeat(64),
provider: { id: "ghidra" as const, version: "12.1.2" },
+7 -22
View File
@@ -28,12 +28,7 @@ import { err, ok, type Result } from "../domain/result.js";
import type { Logger } from "../logger.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_STARTUP_TIMEOUT_MS,
} from "./GhidraDefaults.js";
import { GHIDRA_STARTUP_TIMEOUT_MS } from "./GhidraDefaults.js";
import {
isGhidraFunctionOperation,
parseGhidraFunctionInput,
@@ -247,13 +242,11 @@ export class GhidraProvider implements AnalysisProviderCandidate {
? 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 }),
...(operation === "procedure_pseudo_code" ||
operation === "analyze_function"
? { timeoutMs: GHIDRA_DECOMPILE_REQUEST_TIMEOUT_MS }
: {}),
});
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 = isGhidraFunctionOperation(operation)
@@ -402,15 +395,7 @@ const projectSessionError = (
if (failure.kind === "timeout" || failure.kind === "analysis_timeout")
return new AnalysisTimeoutError(
operation,
failure.timeoutMs ??
(failure.kind === "analysis_timeout"
? 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,
failure.timeoutMs ?? GHIDRA_STARTUP_TIMEOUT_MS,
);
if (failure.kind === "remote" && failure.remoteCode === "decompile_cancelled")
return new AnalysisCancelledError(operation);
+3 -3
View File
@@ -36,7 +36,7 @@ export const GHIDRA_PROVIDER_TOOL_CONTRACTS = Object.freeze(
/** Health limitations shared by every Ghidra-backed capability. */
export 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 session serves operations only after Ghidra reports default auto-analysis complete; incomplete analysis does not expose partial results.",
"The imported Program and temporary project are ephemeral, read-only to REA, and deleted on close.",
]);
@@ -86,7 +86,7 @@ export const limitationsFor = (operation: string): readonly string[] => {
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.",
"Pseudocode is Ghidra decompiler output, not original source and not text-equivalent to Hopper output.",
"External functions and functions without an analyzable body return null; other decompiler failures remain explicit.",
];
case "read_function_instructions":
@@ -124,7 +124,7 @@ export const limitationsFor = (operation: string): readonly string[] => {
"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.",
"The Java bridge serializes one function request per Program and lets each decompilation run until it completes or the caller cancels.",
];
default:
return common;
+10 -52
View File
@@ -1,5 +1,3 @@
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";
@@ -15,19 +13,15 @@ export type GhidraRequestExecutor = (
) => Promise<GhidraQueuedRequestResult>;
/** Bind queue failures to the owning client's live diagnostics. */
export type GhidraQueueFailureFactory = (
kind: "cancelled" | "timeout" | "protocol",
kind: "cancelled" | "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;
}
@@ -41,26 +35,16 @@ export class GhidraRequestQueue {
private readonly failure: GhidraQueueFailureFactory,
) {}
/** Queue one request, counting queue wait against its declared deadline. */
/** Queue one request until it completes, is cancelled, or the session closes. */
run(
method: string,
parameters: JsonValue,
options: GhidraRequestOptions & { readonly timeoutMs: number },
options: GhidraRequestOptions,
): 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,
),
),
);
return new Promise((resolve) => {
let entry: QueuedRequest;
const onAbort =
@@ -71,28 +55,11 @@ export class GhidraRequestQueue {
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);
@@ -115,27 +82,19 @@ export class GhidraRequestQueue {
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) {
if (entry.signal?.aborted === true) {
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,
),
),
err(this.failure("cancelled", "Ghidra request was cancelled")),
);
this.#drain();
return;
}
this.#active = true;
void this.execute(entry.method, entry.parameters, {
...(entry.signal === undefined ? {} : { signal: entry.signal }),
timeoutMs: remaining,
})
void this.execute(
entry.method,
entry.parameters,
entry.signal === undefined ? {} : { signal: entry.signal },
)
.then(entry.resolve)
.catch(() =>
entry.resolve(
@@ -162,7 +121,6 @@ export class GhidraRequestQueue {
}
#release(entry: QueuedRequest): void {
clearTimeout(entry.timer);
if (entry.signal !== undefined && entry.onAbort !== undefined)
entry.signal.removeEventListener("abort", entry.onAbort);
}
+2 -7
View File
@@ -1,22 +1,17 @@
import { describe, expect, it } from "vitest";
import { GHIDRA_MAX_LINE_BYTES } from "./GhidraDefaults.js";
import { GhidraResponseBuffer } from "./GhidraResponseBuffer.js";
describe("Ghidra response buffer", () => {
it("accepts complete responses larger than the former 1 MiB ceiling", () => {
it("accepts complete responses larger than the former 64 MiB ceiling", () => {
const lines: string[] = [];
const failures: string[] = [];
const buffer = new GhidraResponseBuffer({
maxLineBytes: GHIDRA_MAX_LINE_BYTES,
onLine: (line) => lines.push(line),
onFailure: (message) => failures.push(message),
});
const response = `{"result":"${"x".repeat(1_100_000)}"}`;
const response = `{"result":"${"x".repeat(64 * 1024 * 1024 + 1)}"}`;
buffer.push(`${response}\n`);
expect(failures).toEqual([]);
expect(lines).toEqual([response]);
});
});
+2 -12
View File
@@ -1,11 +1,9 @@
/** Callbacks for one bounded newline-delimited Ghidra response stream. */
/** Callbacks for one newline-delimited Ghidra response stream. */
export interface GhidraResponseBufferOptions {
readonly maxLineBytes: number;
readonly onLine: (line: string) => void;
readonly onFailure: (message: string) => void;
}
/** Splits fragmented UTF-8 socket data while enforcing a byte limit per line. */
/** Splits fragmented UTF-8 socket data into response lines. */
export class GhidraResponseBuffer {
readonly #options: GhidraResponseBufferOptions;
#buffer = "";
@@ -21,18 +19,10 @@ export class GhidraResponseBuffer {
while (newline >= 0) {
const encodedLine = this.#buffer.slice(0, newline);
this.#buffer = this.#buffer.slice(newline + 1);
if (Buffer.byteLength(encodedLine) > this.#options.maxLineBytes) {
this.#options.onFailure(
"Ghidra response exceeded the maximum line size",
);
return;
}
const line = encodedLine.trim();
if (line.length > 0) this.#options.onLine(line);
newline = this.#buffer.indexOf("\n");
}
if (Buffer.byteLength(this.#buffer) > this.#options.maxLineBytes)
this.#options.onFailure("Ghidra response exceeded the maximum line size");
}
/** Drop any incomplete line when a session closes. */
-2
View File
@@ -2,7 +2,6 @@ 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";
import { GHIDRA_FUNCTION_OPERATIONS } from "./GhidraFunctionValues.js";
@@ -19,7 +18,6 @@ const capabilitySchema = z.enum(GHIDRA_SESSION_CAPABILITIES);
const sessionInfoSchema = z
.object({
name: z.literal("REA Ghidra bridge"),
bridge_version: z.literal(GHIDRA_BRIDGE_VERSION),
run_id: z.string().uuid(),
profile_digest: z.string().regex(/^[a-f0-9]{64}$/u),
provider: z