feat(ghidra): configurable import language and analysis seeds (#1667)

* feat(ghidra): configurable import language and analysis seeds

REA_GHIDRA_LANGUAGE_ID and REA_GHIDRA_COMPILER_SPEC_ID set the import
language when the header cannot identify the compiler (for example,
Borland C++ PE images).

REA_GHIDRA_SEED_FILE seeds functions, code and labels before
auto-analysis, for code reached only through computed jumps or data.

Both are validated before launch, recorded in the analysis profile and
verified in the bridge handshake.

* fix(ghidra): parse language XML and preserve seed ordering

* test(ghidra): use explicit platform paths for seed launch checks

* fix(javascript): retain cleanup failure reason in error causes

---------

Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
This commit is contained in:
sqmagellan
2026-10-11 09:57:38 +08:00
committed by GitHub
co-authored by morluto
parent c1efa6467d
commit af88184eee
27 changed files with 1827 additions and 20 deletions
+11
View File
@@ -4,6 +4,10 @@ import { isAbsolute } from "node:path";
import { ConfigurationError } from "../domain/configurationErrors.js";
import { err, ok, type Result } from "../domain/result.js";
import { analysisProviderSelectorSchema } from "../contracts/providerSelection.js";
import {
ghidraCompilerSpecIdSchema,
ghidraLanguageIdSchema,
} from "./ghidraLanguageOverride.js";
import { ghidraStartupTimeoutSchema } from "./ghidraStartupTimeout.js";
import { mcpInputSchemaProfileSchema } from "./mcpInputSchemaProfile.js";
import { mcpResponseBudgetSchema } from "./mcpResponseBudget.js";
@@ -33,6 +37,13 @@ const environmentSchema = z.object({
.refine(isAbsolute, "REA_GHIDRA_NATIVEAOT_JAR must be absolute")
.optional(),
REA_GHIDRA_STARTUP_TIMEOUT_MS: ghidraStartupTimeoutSchema,
REA_GHIDRA_LANGUAGE_ID: ghidraLanguageIdSchema.optional(),
REA_GHIDRA_COMPILER_SPEC_ID: ghidraCompilerSpecIdSchema.optional(),
REA_GHIDRA_SEED_FILE: z
.string()
.min(1)
.refine(isAbsolute, "REA_GHIDRA_SEED_FILE must be absolute")
.optional(),
REA_ILSPY_CMD_PATH: z
.string()
.min(1)
+28
View File
@@ -0,0 +1,28 @@
import { z } from "zod";
/**
* Explicit Ghidra import language for targets whose header cannot identify the
* producing compiler, such as Borland-built PE images.
*/
export interface GhidraLanguageOverride {
/** Ghidra language ID: `processor:endian:size:variant`. */
readonly languageId: string;
/** Ghidra compiler-spec ID; absent selects the language's default spec. */
readonly compilerSpecId?: string;
}
// Ghidra language IDs are four colon-separated fields; variants may contain
// spaces ("x86:LE:16:Real Mode") but never leading or trailing whitespace.
export const ghidraLanguageIdSchema = z
.string()
.regex(
/^[A-Za-z0-9_.+-]+:(?:LE|BE):[1-9]\d*:[A-Za-z0-9_.+-](?:[A-Za-z0-9_.+ -]*[A-Za-z0-9_.+-])?$/u,
"must be a Ghidra language ID such as x86:LE:32:default",
);
export const ghidraCompilerSpecIdSchema = z
.string()
.regex(
/^[A-Za-z0-9_.+-]+$/u,
"must be a Ghidra compiler-spec ID such as default or borlandcpp",
);
+29 -1
View File
@@ -2,7 +2,7 @@ import { accessSync, constants } from "node:fs";
import { join } from "node:path";
import { ConfigurationError } from "../domain/configurationErrors.js";
import { ok, type Result } from "../domain/result.js";
import { err, ok, type Result } from "../domain/result.js";
import { parseEnvironment } from "./environment.js";
import { homeDirectoryFromEnvironment } from "./homeDirectory.js";
import { parseStringArray, parseLoaderArgs } from "./parsers.js";
@@ -46,6 +46,21 @@ export const parseConfig = (
"REA_REFERENCE_SECRET_PATTERNS_JSON",
);
if (!secretPatterns.ok) return secretPatterns;
// Ghidra's analyzeHeadless accepts -cspec only together with -processor.
if (
env.REA_GHIDRA_COMPILER_SPEC_ID !== undefined &&
env.REA_GHIDRA_LANGUAGE_ID === undefined
)
return err(
new ConfigurationError("Invalid REA environment configuration", {
settings: [
{
setting: "REA_GHIDRA_COMPILER_SPEC_ID",
constraint: "requires REA_GHIDRA_LANGUAGE_ID",
},
],
}),
);
return ok({
...(env.REA_MCP_MAX_RESPONSE_BYTES === undefined
? {}
@@ -60,6 +75,19 @@ export const parseConfig = (
ghidraInstallDir: env.GHIDRA_INSTALL_DIR,
ghidraJavaHome: env.JAVA_HOME,
ghidraStartupTimeoutMs: env.REA_GHIDRA_STARTUP_TIMEOUT_MS,
...(env.REA_GHIDRA_LANGUAGE_ID === undefined
? {}
: {
ghidraLanguageOverride: {
languageId: env.REA_GHIDRA_LANGUAGE_ID,
...(env.REA_GHIDRA_COMPILER_SPEC_ID === undefined
? {}
: { compilerSpecId: env.REA_GHIDRA_COMPILER_SPEC_ID }),
},
}),
...(env.REA_GHIDRA_SEED_FILE === undefined
? {}
: { ghidraSeedFile: env.REA_GHIDRA_SEED_FILE }),
...(env.REA_GHIDRA_NATIVEAOT_JAR === undefined
? {}
: { ghidraNativeAotJar: env.REA_GHIDRA_NATIVEAOT_JAR }),
+3
View File
@@ -2,6 +2,7 @@ import type { LogLevel } from "../logger.js";
import type { ReferenceSourcePolicy } from "../domain/referenceSourcePolicy.js";
import type { AnalysisProviderSelector } from "../contracts/providerSelection.js";
import type { GhidraLanguageOverride } from "./ghidraLanguageOverride.js";
import type { McpInputSchemaProfile } from "./mcpInputSchemaProfile.js";
export interface AppConfig {
@@ -12,6 +13,8 @@ export interface AppConfig {
readonly ghidraInstallDir: string | undefined;
readonly ghidraJavaHome: string | undefined;
readonly ghidraStartupTimeoutMs: number;
readonly ghidraLanguageOverride?: GhidraLanguageOverride;
readonly ghidraSeedFile?: string;
readonly ghidraNativeAotJar?: string;
readonly ilspyCmdPath: string | undefined;
readonly hopperLauncherPath: string;
+46 -2
View File
@@ -3,6 +3,7 @@ import type {
ProviderIdentity,
} from "../application/AnalysisProvider.js";
import { createAnalysisProfile } from "../domain/analysisProfile.js";
import type { GhidraLanguageOverride } from "../config/ghidraLanguageOverride.js";
import type { BinaryTarget } from "../domain/binaryTargetTypes.js";
import {
AnalysisCancelledError,
@@ -23,6 +24,7 @@ export const resolveGhidraAnalysisProfile = (
identity: ProviderIdentity,
installation: GhidraInstallationInspection,
signal?: AbortSignal,
languageOverride?: GhidraLanguageOverride,
): Promise<Result<AnalysisProfileResolution, AnalysisError>> => {
if (signal?.aborted === true)
return Promise.resolve(err(new AnalysisCancelledError("open_binary")));
@@ -47,6 +49,17 @@ export const resolveGhidraAnalysisProfile = (
const dosMz = target.format === "dos-mz";
const dosCom = target.format === "dos-com";
const dos = dosMz || dosCom;
// DOS imports already force an admitted loader, language, and context.
if (dos && languageOverride !== undefined)
return Promise.resolve(
err(
new AnalysisUnsupportedTargetError(
"resolve_analysis_profile",
target.path,
"REA_GHIDRA_LANGUAGE_ID cannot override the admitted DOS real-mode import.",
),
),
);
return Promise.resolve(
ok({
profile: createAnalysisProfile(provider, {
@@ -89,8 +102,17 @@ export const resolveGhidraAnalysisProfile = (
: dosCom
? "BinaryLoader"
: "auto-from-header",
language_id: dos ? "x86:LE:16:Real Mode" : "auto-from-header",
compiler_spec_id: dos ? "default" : "auto-default",
language_id: dos
? "x86:LE:16:Real Mode"
: (languageOverride?.languageId ?? "auto-from-header"),
compiler_spec_id: dos
? "default"
: languageOverride === undefined
? "auto-default"
: (languageOverride.compilerSpecId ?? "language-default"),
...(languageOverride === undefined
? {}
: { language_selection: "configured-v1" }),
...(dos
? {
load_segment: "0x1000",
@@ -115,3 +137,25 @@ export const resolveGhidraAnalysisProfile = (
}),
);
};
/** Read the import-language commitment back from a resolved profile. */
export const ghidraProfileLanguageOverride = (
parameters: Readonly<Record<string, unknown>>,
): GhidraLanguageOverride | undefined => {
if (parameters.language_selection !== "configured-v1") return undefined;
const languageId = parameters.language_id;
const compilerSpecId = parameters.compiler_spec_id;
if (typeof languageId !== "string" || typeof compilerSpecId !== "string")
return undefined;
return compilerSpecId === "language-default"
? { languageId }
: { languageId, compilerSpecId };
};
/** Whether a committed profile and the active configuration select the same language. */
export const sameGhidraLanguageOverride = (
left: GhidraLanguageOverride | undefined,
right: GhidraLanguageOverride | undefined,
): boolean =>
left?.languageId === right?.languageId &&
left?.compilerSpecId === right?.compilerSpecId;
+258
View File
@@ -0,0 +1,258 @@
import { createHash } from "node:crypto";
import {
mkdtemp,
readFile,
realpath,
rm,
symlink,
writeFile,
} from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { parseConfig } from "../config/parseConfig.js";
import type { BinaryTarget } from "../domain/binaryTargetTypes.js";
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
import { silentLogger } from "../logger.js";
import {
ghidraSeedFailure,
ghidraSeedLimitations,
parseGhidraSeeds,
resolveGhidraAnalysisSeeds,
snapshotGhidraAnalysisSeeds,
type GhidraSeedCommitment,
type GhidraSeedReport,
} from "./GhidraAnalysisSeeds.js";
import type { GhidraInstallationHost } from "./GhidraInstallation.js";
import { GhidraProvider } from "./GhidraProvider.js";
const directories: string[] = [];
afterEach(async () => {
for (const directory of directories.splice(0))
await rm(directory, { recursive: true, force: true });
});
const workspace = async () => {
const directory = await mkdtemp(join(tmpdir(), "rea-ghidra-seeds-"));
directories.push(directory);
return directory;
};
const SEEDS = [
"# comment and blank lines are ignored",
"",
"0x401000\tfunction\tentry",
"0x00401046\tfunction",
"0x40A1C4\tcode\r",
"0x402200\tlabel\tExample::render",
"",
].join("\n");
const CANONICAL =
"0x401000\tfunction\tentry\n0x401046\tfunction\n0x40a1c4\tcode\n0x402200\tlabel\tExample::render\n";
describe("Ghidra seed parsing", () => {
it("accepts the documented line forms", () => {
const parsed = parseGhidraSeeds(SEEDS);
if (!parsed.ok) throw parsed.error;
expect(parsed.value.map((entry) => entry.kind)).toEqual([
"function",
"function",
"code",
"label",
]);
});
it.each([
["401000\tfunction", "line 1: address must be 0x-prefixed hex"],
["0x401000\tdata", "line 1: kind must be function, code or label"],
["0x401000", "line 1: expected address<TAB>kind[<TAB>name]"],
["0x401000\tlabel", "line 1: a label seed requires a name"],
[
"0x401000\tcode\tname",
"line 1: a code seed takes no name; add a label seed",
],
[
"0x401000\tfunction\ttwo words",
"line 1: name must be 1..2000 characters without whitespace",
],
[
"0x401000\tcode\n0x0401000\tcode",
"line 2: duplicate code seed at 0x0401000",
],
])("rejects %j", (text, constraint) => {
const parsed = parseGhidraSeeds(text);
if (parsed.ok) throw new Error("Expected a seed error");
expect(parsed.error.settings).toEqual([
{ setting: "REA_GHIDRA_SEED_FILE", constraint },
]);
});
});
describe("Ghidra seed commitment", () => {
it("digests the canonical form and snapshots exactly that", async () => {
const directory = await workspace();
const path = join(directory, "seeds.tsv");
await writeFile(path, SEEDS);
const resolved = await resolveGhidraAnalysisSeeds(path);
if (!resolved.ok) throw resolved.error;
const commitment = resolved.value;
if (commitment === undefined) throw new Error("Expected a commitment");
expect(commitment).toMatchObject({
format: "rea-ghidra-seeds-v1",
configured_path: path,
sha256: createHash("sha256").update(CANONICAL).digest("hex"),
entries: { function: 2, code: 1, label: 1 },
});
const runtime = await workspace();
const snapshot = await snapshotGhidraAnalysisSeeds(commitment, runtime);
expect(await readFile(snapshot, "utf8")).toBe(CANONICAL);
});
it("is absent when no seed file is configured", async () => {
const resolved = await resolveGhidraAnalysisSeeds(undefined);
expect(resolved.ok && resolved.value).toBeUndefined();
});
it("refuses a seed file that changed after the profile was committed", async () => {
const directory = await workspace();
const path = join(directory, "seeds.tsv");
await writeFile(path, SEEDS);
const resolved = await resolveGhidraAnalysisSeeds(path);
if (!resolved.ok || resolved.value === undefined)
throw new Error("Expected a commitment");
await writeFile(path, `${SEEDS}0x401100\tcode\n`);
await expect(
snapshotGhidraAnalysisSeeds(resolved.value, await workspace()),
).rejects.toThrow(/changed after the analysis profile was committed/u);
});
it("commits the resolved path behind a configured symbolic link", async () => {
const directory = await workspace();
const path = join(directory, "seeds.tsv");
await writeFile(path, SEEDS);
const link = join(directory, "link.tsv");
await symlink(path, link);
const resolved = await resolveGhidraAnalysisSeeds(link);
if (!resolved.ok || resolved.value === undefined)
throw new Error("Expected a commitment");
expect(resolved.value.path).toBe(await realpath(path));
});
it("reports an unreadable seed file as a provider error", async () => {
const resolved = await resolveGhidraAnalysisSeeds(
join(await workspace(), "absent.tsv"),
);
if (resolved.ok) throw new Error("Expected an error");
expect(projectAnalysisError(resolved.error)).toMatchObject({
details: { diagnostics: { setting: "REA_GHIDRA_SEED_FILE" } },
});
});
});
describe("Ghidra seed session verification", () => {
const commitment: GhidraSeedCommitment = {
format: "rea-ghidra-seeds-v1",
path: "/seeds.tsv",
configured_path: "/seeds.tsv",
sha256: "b".repeat(64),
entries: { function: 2, code: 1, label: 1 },
};
const report: GhidraSeedReport = {
format: "rea-ghidra-seeds-v1",
sha256: "b".repeat(64),
entries: 4,
function_created: 1,
function_existing: 0,
function_failed: 1,
code_decoded: 1,
code_failed: 0,
label_applied: 1,
label_failed: 0,
unmapped: 0,
};
it("accepts exactly the committed seeds and reports their outcome", () => {
expect(ghidraSeedFailure(commitment, report, "xrefs")).toBeUndefined();
expect(ghidraSeedFailure(undefined, undefined, "xrefs")).toBeUndefined();
expect(ghidraSeedLimitations(commitment, report)).toEqual([
expect.stringContaining("caller assertions, not Ghidra discoveries"),
expect.stringContaining(
"1 functions created, 0 already present, 1 failed",
),
]);
expect(ghidraSeedLimitations(undefined)).toEqual([]);
});
it.each([
["a missing report", commitment, undefined],
["an uncommitted report", undefined, report],
["a different digest", commitment, { ...report, sha256: "c".repeat(64) }],
["a different count", commitment, { ...report, entries: 3 }],
])("fails closed on %s", (_label, committed, reported) => {
expect(ghidraSeedFailure(committed, reported, "xrefs")).toBeDefined();
});
});
describe("Ghidra seed profile", () => {
const host: GhidraInstallationHost = {
platform: "linux",
architecture: "x64",
readText: () => "application.version=12.1.4\n",
executable: () => true,
probeJava: () => ({
version: "21.0.11",
major: 21,
home: "/jdk-21",
bits: 64,
runtime: "jdk",
}),
};
const pe: BinaryTarget = {
path: "/fixture.exe",
sha256: "a".repeat(64),
kind: "executable",
format: "pe",
architecture: "x86",
availableArchitectures: ["x86"],
executableRole: "application",
managed: false,
};
it("commits the seed digest and counts into the analysis profile", async () => {
const path = join(await workspace(), "seeds.tsv");
await writeFile(path, SEEDS);
const parsed = parseConfig({
GHIDRA_INSTALL_DIR: "/ghidra",
REA_GHIDRA_SEED_FILE: path,
});
if (!parsed.ok) throw parsed.error;
const ghidra = new GhidraProvider(parsed.value, silentLogger, {}, host);
const resolved = await ghidra.resolveAnalysisProfile(pe);
if (!resolved.ok) throw resolved.error;
expect(resolved.value.profile?.parameters.analysis_seeds).toMatchObject({
format: "rea-ghidra-seeds-v1",
entries: { function: 2, code: 1, label: 1 },
});
});
it("refuses a malformed seed file before launching Ghidra", async () => {
const path = join(await workspace(), "seeds.tsv");
await writeFile(path, "0x401000\tdata\n");
const parsed = parseConfig({
GHIDRA_INSTALL_DIR: "/ghidra",
REA_GHIDRA_SEED_FILE: path,
});
if (!parsed.ok) throw parsed.error;
const ghidra = new GhidraProvider(parsed.value, silentLogger, {}, host);
const resolved = await ghidra.resolveAnalysisProfile(pe);
if (resolved.ok) throw new Error("Expected a configuration error");
expect(projectAnalysisError(resolved.error)).toMatchObject({
code: "configuration_invalid",
details: { settings: [{ setting: "REA_GHIDRA_SEED_FILE" }] },
});
});
it("requires an absolute seed path", () => {
const parsed = parseConfig({ REA_GHIDRA_SEED_FILE: "seeds.tsv" });
expect(parsed.ok).toBe(false);
});
});
+286
View File
@@ -0,0 +1,286 @@
import { createHash } from "node:crypto";
import { constants } from "node:fs";
import { mkdir, open, realpath, writeFile } from "node:fs/promises";
import { isAbsolute, join } from "node:path";
import { z } from "zod";
import type { AnalysisOperation } from "../application/AnalysisProvider.js";
import { ConfigurationError } from "../domain/configurationErrors.js";
import { ProviderAdapterError } from "../domain/providerAdapterError.js";
import { err, ok, type Result } from "../domain/result.js";
/** Seed file format admitted by this adapter. */
export const GHIDRA_SEED_FORMAT = "rea-ghidra-seeds-v1";
export const GHIDRA_SEED_SCRIPT = "ReaGhidraApplySeeds.java";
export const MAX_GHIDRA_SEED_BYTES = 32 * 1024 * 1024;
export const MAX_GHIDRA_SEED_ENTRIES = 1_000_000;
const MAX_SEED_NAME_LENGTH = 2000;
const digest = z.string().regex(/^[a-f0-9]{64}$/u);
const count = z.number().int().nonnegative();
/** Caller-declared seeds committed into the analysis profile before import. */
export const ghidraSeedCommitmentSchema = z.strictObject({
format: z.literal(GHIDRA_SEED_FORMAT),
path: z.string().refine(isAbsolute, "Seed path must be absolute"),
configured_path: z.string().refine(isAbsolute, "Seed path must be absolute"),
sha256: digest,
entries: z.strictObject({ function: count, code: count, label: count }),
});
export type GhidraSeedCommitment = z.infer<typeof ghidraSeedCommitmentSchema>;
/** What the pre-analysis script applied, as reported by the bridge handshake. */
export const ghidraSeedReportSchema = z.strictObject({
format: z.literal(GHIDRA_SEED_FORMAT),
sha256: digest,
entries: count,
function_created: count,
function_existing: count,
function_failed: count,
code_decoded: count,
code_failed: count,
label_applied: count,
label_failed: count,
unmapped: count,
});
export type GhidraSeedReport = z.infer<typeof ghidraSeedReportSchema>;
type SeedKind = "function" | "code" | "label";
interface SeedEntry {
readonly address: bigint;
readonly kind: SeedKind;
readonly name?: string;
}
const seedLineError = (line: number, constraint: string) =>
new ConfigurationError("Invalid REA environment configuration", {
settings: [
{
setting: "REA_GHIDRA_SEED_FILE",
constraint: `line ${line}: ${constraint}`,
},
],
});
/**
* Parse `address<TAB>kind[<TAB>name]` lines. Blank lines and `#` comments are
* ignored. Addresses are hexadecimal offsets in the default address space.
*/
export const parseGhidraSeeds = (
text: string,
): Result<readonly SeedEntry[], ConfigurationError> => {
const entries: SeedEntry[] = [];
const seen = new Set<string>();
const lines = text.split("\n");
for (const [index, raw] of lines.entries()) {
const line = raw.endsWith("\r") ? raw.slice(0, -1) : raw;
if (line.trim() === "" || line.startsWith("#")) continue;
const number = index + 1;
const fields = line.split("\t");
if (fields.length < 2 || fields.length > 3)
return err(seedLineError(number, "expected address<TAB>kind[<TAB>name]"));
const [address, kind, name] = fields;
if (address === undefined || !/^0x[0-9a-fA-F]{1,16}$/u.test(address))
return err(seedLineError(number, "address must be 0x-prefixed hex"));
if (kind !== "function" && kind !== "code" && kind !== "label")
return err(seedLineError(number, "kind must be function, code or label"));
if (
name !== undefined &&
(name.length === 0 ||
name.length > MAX_SEED_NAME_LENGTH ||
/[\s\0]/u.test(name))
)
return err(
seedLineError(
number,
`name must be 1..${MAX_SEED_NAME_LENGTH} characters without whitespace`,
),
);
if (kind === "label" && name === undefined)
return err(seedLineError(number, "a label seed requires a name"));
if (kind === "code" && name !== undefined)
return err(
seedLineError(number, "a code seed takes no name; add a label seed"),
);
const value = BigInt(address);
const key = `${value.toString(16)}:${kind}`;
if (seen.has(key))
return err(seedLineError(number, `duplicate ${kind} seed at ${address}`));
seen.add(key);
entries.push({
address: value,
kind,
...(name === undefined ? {} : { name }),
});
if (entries.length > MAX_GHIDRA_SEED_ENTRIES)
return err(
seedLineError(
number,
`more than ${MAX_GHIDRA_SEED_ENTRIES} seed entries`,
),
);
}
return ok(entries);
};
/** Canonical script input: lowercase addresses, fixed field order, LF endings. */
const normalizedSeeds = (entries: readonly SeedEntry[]): string =>
entries
.map(
(entry) =>
`0x${entry.address.toString(16)}\t${entry.kind}${entry.name === undefined ? "" : `\t${entry.name}`}\n`,
)
.join("");
/** Read a bounded regular file through one handle without following links. */
const readSeedFile = async (path: string): Promise<Buffer> => {
const file = await open(
path,
constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK,
);
try {
const stat = await file.stat();
if (!stat.isFile() || stat.size > MAX_GHIDRA_SEED_BYTES)
throw new Error(
`Ghidra seed file must be a regular file of at most ${MAX_GHIDRA_SEED_BYTES} bytes: ${path}`,
);
const bytes = Buffer.alloc(stat.size);
let offset = 0;
while (offset < bytes.length) {
const read = await file.read(
bytes,
offset,
bytes.length - offset,
offset,
);
if (read.bytesRead === 0)
throw new Error(`Incomplete Ghidra seed file read: ${path}`);
offset += read.bytesRead;
}
return bytes;
} finally {
await file.close();
}
};
const sha256 = (bytes: Buffer | string): string =>
createHash("sha256").update(bytes).digest("hex");
const decodeSeeds = (bytes: Buffer) => {
const text = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
return parseGhidraSeeds(text);
};
/** Resolve the configured seed file into an immutable profile commitment. */
export const resolveGhidraAnalysisSeeds = async (
configured: string | undefined,
): Promise<
Result<
GhidraSeedCommitment | undefined,
ConfigurationError | ProviderAdapterError
>
> => {
if (configured === undefined) return ok(undefined);
let bytes: Buffer;
let path: string;
try {
path = await realpath(configured);
bytes = await readSeedFile(path);
} catch (cause: unknown) {
return err(
new ProviderAdapterError("ghidra", "resolve_analysis_profile", {
cause,
diagnostics: {
setting: "REA_GHIDRA_SEED_FILE",
path: configured,
reason: cause instanceof Error ? cause.message : String(cause),
},
}),
);
}
let parsed: ReturnType<typeof decodeSeeds>;
try {
parsed = decodeSeeds(bytes);
} catch {
return err(seedLineError(0, "file is not valid UTF-8"));
}
if (!parsed.ok) return parsed;
const normalized = normalizedSeeds(parsed.value);
const tally = { function: 0, code: 0, label: 0 };
for (const entry of parsed.value) tally[entry.kind] += 1;
return ok({
format: GHIDRA_SEED_FORMAT,
path,
configured_path: configured,
sha256: sha256(normalized),
entries: tally,
});
};
/** Re-read the committed seeds and write the canonical copy the script applies. */
export const snapshotGhidraAnalysisSeeds = async (
commitment: GhidraSeedCommitment,
runtimeRoot: string,
): Promise<string> => {
ghidraSeedCommitmentSchema.parse(commitment);
if ((await realpath(commitment.configured_path)) !== commitment.path)
throw new Error(
"Ghidra seed file resolved path differs from explicit configuration",
);
const parsed = decodeSeeds(await readSeedFile(commitment.path));
if (!parsed.ok) throw parsed.error;
const normalized = normalizedSeeds(parsed.value);
if (sha256(normalized) !== commitment.sha256)
throw new Error(
`Ghidra seed file changed after the analysis profile was committed: ${commitment.path}`,
);
const directory = join(runtimeRoot, "seeds");
await mkdir(directory, { mode: 0o700 });
const path = join(directory, "seeds.tsv");
await writeFile(path, normalized, { flag: "wx", mode: 0o600 });
return path;
};
const totalEntries = (commitment: GhidraSeedCommitment): number =>
commitment.entries.function +
commitment.entries.code +
commitment.entries.label;
/** Fail closed when the session did not apply exactly the committed seeds. */
export const ghidraSeedFailure = (
commitment: GhidraSeedCommitment | undefined,
report: GhidraSeedReport | undefined,
operation: AnalysisOperation,
): ProviderAdapterError | undefined => {
if (commitment === undefined && report === undefined) return undefined;
const reason =
commitment === undefined
? "The Ghidra session reported analysis seeds that the profile did not commit."
: report === undefined
? "The Ghidra session did not report the committed analysis seeds."
: report.sha256 !== commitment.sha256 ||
report.entries !== totalEntries(commitment)
? "The Ghidra session applied analysis seeds that differ from the committed profile."
: undefined;
return reason === undefined
? undefined
: new ProviderAdapterError("ghidra", operation, {
diagnostics: { reason },
});
};
/** Session limitations that keep seeded facts distinct from Ghidra discoveries. */
export const ghidraSeedLimitations = (
commitment: GhidraSeedCommitment | undefined,
report?: GhidraSeedReport,
): readonly string[] =>
commitment === undefined
? []
: [
`Ghidra analysis was seeded before auto-analysis from ${commitment.path} (sha256 ${commitment.sha256}: ${commitment.entries.function} function, ${commitment.entries.code} code, ${commitment.entries.label} label entries). Seeded functions, code and names are caller assertions, not Ghidra discoveries.`,
...(report === undefined
? []
: [
`Seed outcome: ${report.function_created} functions created, ${report.function_existing} already present, ${report.function_failed} failed; ${report.code_decoded} code seeds decoded, ${report.code_failed} failed; ${report.label_applied} labels applied, ${report.label_failed} failed; ${report.unmapped} seeds outside initialized memory.`,
]),
];
+118
View File
@@ -0,0 +1,118 @@
import { readdir, readFile } from "node:fs/promises";
import { join } from "node:path";
import { DOMParser, onWarningStopParsing } from "@xmldom/xmldom";
import type { GhidraLanguageOverride } from "../config/ghidraLanguageOverride.js";
import { ConfigurationError } from "../domain/configurationErrors.js";
/** One language definition and the compiler specs it declares. */
export interface GhidraLanguageDefinition {
readonly id: string;
readonly compilerSpecIds: readonly string[];
}
// Language definitions are small XML files; refuse anything implausibly large.
const MAX_LDEFS_BYTES = 4 * 1024 * 1024;
// Processor modules ship under Processors; installed extensions may add more.
const LANGUAGE_ROOTS = ["Ghidra/Processors", "Ghidra/Extensions"] as const;
/** Parse the `<language>` elements of one `.ldefs` document. */
export const parseGhidraLanguageDefinitions = (
text: string,
): readonly GhidraLanguageDefinition[] => {
const definitions: GhidraLanguageDefinition[] = [];
const document = new DOMParser({
onError: onWarningStopParsing,
}).parseFromString(text, "application/xml");
const root = document.documentElement;
if (root?.tagName !== "language_definitions")
throw new SyntaxError("Expected Ghidra language_definitions XML root");
for (const language of Array.from(root.getElementsByTagName("language"))) {
if (language.parentNode !== root) continue;
const id = language.getAttribute("id");
if (id === null) continue;
const compilerSpecIds: string[] = [];
for (const compiler of Array.from(
language.getElementsByTagName("compiler"),
)) {
if (compiler.parentNode !== language) continue;
const compilerId = compiler.getAttribute("id");
if (compilerId !== null) compilerSpecIds.push(compilerId);
}
definitions.push({ id, compilerSpecIds });
}
return definitions;
};
const languageDirectories = async (installDir: string): Promise<string[]> => {
const directories: string[] = [];
for (const root of LANGUAGE_ROOTS) {
let modules: string[];
try {
modules = await readdir(join(installDir, root));
} catch {
continue;
}
for (const module of modules.sort())
directories.push(join(installDir, root, module, "data", "languages"));
}
return directories;
};
/** Read every language definition shipped by one Ghidra installation. */
export const readGhidraLanguageCatalog = async (
installDir: string,
): Promise<readonly GhidraLanguageDefinition[]> => {
const definitions: GhidraLanguageDefinition[] = [];
for (const directory of await languageDirectories(installDir)) {
let entries: string[];
try {
entries = await readdir(directory);
} catch {
continue;
}
for (const entry of entries.sort()) {
if (!entry.endsWith(".ldefs")) continue;
const bytes = await readFile(join(directory, entry));
if (bytes.length > MAX_LDEFS_BYTES) continue;
definitions.push(
...parseGhidraLanguageDefinitions(bytes.toString("utf8")),
);
}
}
return definitions;
};
/**
* Check a configured import language against the installation before launch,
* so an unknown ID fails as configuration instead of as a failed import.
*/
export const admitGhidraLanguageOverride = (
override: GhidraLanguageOverride,
catalog: readonly GhidraLanguageDefinition[],
providerVersion: string,
): ConfigurationError | null => {
const language = catalog.find((value) => value.id === override.languageId);
if (language === undefined)
return new ConfigurationError("Invalid REA environment configuration", {
settings: [
{
setting: "REA_GHIDRA_LANGUAGE_ID",
constraint: `is not a language defined by Ghidra ${providerVersion}`,
},
],
});
if (
override.compilerSpecId !== undefined &&
!language.compilerSpecIds.includes(override.compilerSpecId)
)
return new ConfigurationError("Invalid REA environment configuration", {
settings: [
{
setting: "REA_GHIDRA_COMPILER_SPEC_ID",
constraint: `must be one of the selected language's compiler specs: ${language.compilerSpecIds.join(", ")}`,
},
],
});
return null;
};
+320
View File
@@ -0,0 +1,320 @@
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { parseConfig } from "../config/parseConfig.js";
import type { BinaryTarget } from "../domain/binaryTargetTypes.js";
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
import { silentLogger } from "../logger.js";
import {
ghidraProfileLanguageOverride,
sameGhidraLanguageOverride,
} from "./GhidraAnalysisProfile.js";
import type { GhidraInstallationHost } from "./GhidraInstallation.js";
import {
admitGhidraLanguageOverride,
parseGhidraLanguageDefinitions,
readGhidraLanguageCatalog,
} from "./GhidraLanguageCatalog.js";
import { GhidraProvider } from "./GhidraProvider.js";
// Abbreviated from Ghidra 12.1.4 Processors/x86/data/languages/x86.ldefs.
const X86_LDEFS = `<?xml version="1.0" encoding="UTF-8"?>
<language_definitions>
<language processor="x86"
endian="little"
size="32"
variant="default"
id="x86:LE:32:default">
<description>Intel/AMD 32-bit x86</description>
<compiler name="Visual Studio" spec="x86win.cspec" id="windows"/>
<compiler name="gcc" spec="x86gcc.cspec" id="gcc"/>
<compiler name="Borland C++" spec="x86borland.cspec" id="borlandcpp"/>
</language>
<language processor="x86" endian="little" size="16" variant="Real Mode"
id="x86:LE:16:Real Mode">
<compiler name="default" spec="x86-16.cspec" id="default"/>
</language>
</language_definitions>
`;
// Fake installation inspection; the language catalog is a real directory.
const host: GhidraInstallationHost = {
platform: "linux",
architecture: "x64",
readText: () => "application.version=12.1.4\n",
executable: () => true,
probeJava: () => ({
version: "21.0.11",
major: 21,
home: "/jdk-21",
bits: 64,
runtime: "jdk",
}),
};
const pe: BinaryTarget = {
path: "/fixture.exe",
sha256: "a".repeat(64),
kind: "executable",
format: "pe",
architecture: "x86",
availableArchitectures: ["x86"],
executableRole: "application",
managed: false,
};
let installDir = "";
beforeAll(async () => {
installDir = await mkdtemp(join(tmpdir(), "rea-ghidra-languages-"));
const languages = join(installDir, "Ghidra/Processors/x86/data/languages");
await mkdir(languages, { recursive: true });
await writeFile(join(languages, "x86.ldefs"), X86_LDEFS);
});
afterAll(async () => {
await rm(installDir, { recursive: true, force: true });
});
const provider = (environment: Record<string, string>) => {
const parsed = parseConfig({
GHIDRA_INSTALL_DIR: installDir,
...environment,
});
if (!parsed.ok) throw parsed.error;
return new GhidraProvider(parsed.value, silentLogger, {}, host);
};
describe("Ghidra language override configuration", () => {
it("accepts a language with an optional compiler spec", () => {
const parsed = parseConfig({
REA_GHIDRA_LANGUAGE_ID: "x86:LE:32:default",
REA_GHIDRA_COMPILER_SPEC_ID: "borlandcpp",
});
if (!parsed.ok) throw parsed.error;
expect(parsed.value.ghidraLanguageOverride).toEqual({
languageId: "x86:LE:32:default",
compilerSpecId: "borlandcpp",
});
const languageOnly = parseConfig({
REA_GHIDRA_LANGUAGE_ID: "x86:LE:16:Real Mode",
});
if (!languageOnly.ok) throw languageOnly.error;
expect(languageOnly.value.ghidraLanguageOverride).toEqual({
languageId: "x86:LE:16:Real Mode",
});
});
it("requires a language for a compiler spec, as analyzeHeadless does", () => {
const parsed = parseConfig({ REA_GHIDRA_COMPILER_SPEC_ID: "borlandcpp" });
if (parsed.ok) throw new Error("Expected a configuration error");
expect(projectAnalysisError(parsed.error)).toMatchObject({
code: "configuration_invalid",
details: {
settings: [
{
setting: "REA_GHIDRA_COMPILER_SPEC_ID",
constraint: "requires REA_GHIDRA_LANGUAGE_ID",
},
],
},
});
});
it.each([
["REA_GHIDRA_LANGUAGE_ID", "x86 LE 32"],
["REA_GHIDRA_LANGUAGE_ID", "x86:LE:32: default"],
["REA_GHIDRA_LANGUAGE_ID", "x86:XE:32:default"],
["REA_GHIDRA_COMPILER_SPEC_ID", "borland cpp"],
])("rejects malformed %s %j without echoing it", (setting, value) => {
const parsed = parseConfig({
REA_GHIDRA_LANGUAGE_ID: "x86:LE:32:default",
[setting]: value,
});
if (parsed.ok) throw new Error("Expected a configuration error");
const projected = projectAnalysisError(parsed.error);
expect(projected).toMatchObject({
code: "configuration_invalid",
details: { settings: [{ setting, constraint: expect.any(String) }] },
});
expect(JSON.stringify(projected)).not.toContain(value);
});
});
describe("Ghidra language catalog", () => {
it("reads quoted and escaped XML attributes without admitting comments or CDATA", () => {
const catalog = parseGhidraLanguageDefinitions(`<language_definitions>
<!-- <language id="removed"><compiler id="removed"/></language> -->
<language id='x86:LE:32:default'>
<description><![CDATA[<compiler id="not-a-compiler"/>]]></description>
<!-- <compiler id="removed"/> -->
<compiler id='borland&#99;pp' name='Borland &amp; C++'/>
</language>
</language_definitions>`);
expect(catalog).toEqual([
{ id: "x86:LE:32:default", compilerSpecIds: ["borlandcpp"] },
]);
expect(
admitGhidraLanguageOverride(
{ languageId: "x86:LE:32:default", compilerSpecId: "removed" },
catalog,
"12.1.4",
),
).not.toBeNull();
});
it.each([
'<language_definitions><language id="x86:LE:32:default"></language_definitions>',
"<language_definitions><language id=x86:LE:32:default/></language_definitions>",
'<other><language id="x86:LE:32:default"/></other>',
])("rejects malformed language-definition documents", (text) => {
expect(() => parseGhidraLanguageDefinitions(text)).toThrow();
});
it("parses language IDs and their compiler specs", async () => {
expect(parseGhidraLanguageDefinitions(X86_LDEFS)).toEqual([
{
id: "x86:LE:32:default",
compilerSpecIds: ["windows", "gcc", "borlandcpp"],
},
{ id: "x86:LE:16:Real Mode", compilerSpecIds: ["default"] },
]);
expect(await readGhidraLanguageCatalog(installDir)).toHaveLength(2);
expect(await readGhidraLanguageCatalog(join(installDir, "absent"))).toEqual(
[],
);
});
it("admits only languages and compiler specs the installation defines", () => {
const catalog = parseGhidraLanguageDefinitions(X86_LDEFS);
expect(
admitGhidraLanguageOverride(
{ languageId: "x86:LE:32:default", compilerSpecId: "borlandcpp" },
catalog,
"12.1.4",
),
).toBeNull();
const language = admitGhidraLanguageOverride(
{ languageId: "x86:LE:31:default" },
catalog,
"12.1.4",
);
expect(language?.settings).toEqual([
{
setting: "REA_GHIDRA_LANGUAGE_ID",
constraint: "is not a language defined by Ghidra 12.1.4",
},
]);
const spec = admitGhidraLanguageOverride(
{ languageId: "x86:LE:32:default", compilerSpecId: "golang" },
catalog,
"12.1.4",
);
expect(spec?.settings).toEqual([
{
setting: "REA_GHIDRA_COMPILER_SPEC_ID",
constraint:
"must be one of the selected language's compiler specs: windows, gcc, borlandcpp",
},
]);
});
});
describe("Ghidra language override profile", () => {
it("returns a provider failure for a malformed installed language definition", async () => {
const path = join(
installDir,
"Ghidra/Processors/x86/data/languages/broken.ldefs",
);
await writeFile(
path,
"<language_definitions><language></language_definitions>",
);
try {
const resolved = await provider({
REA_GHIDRA_LANGUAGE_ID: "x86:LE:32:default",
}).resolveAnalysisProfile(pe);
if (resolved.ok) throw new Error("Expected a language catalog failure");
expect(resolved.error).toMatchObject({
providerId: "ghidra",
operation: "resolve_analysis_profile",
});
} finally {
await rm(path);
}
});
it("commits the configured language and compiler spec", async () => {
const resolved = await provider({
REA_GHIDRA_LANGUAGE_ID: "x86:LE:32:default",
REA_GHIDRA_COMPILER_SPEC_ID: "borlandcpp",
}).resolveAnalysisProfile(pe);
if (!resolved.ok) throw resolved.error;
const parameters = resolved.value.profile?.parameters ?? {};
expect(parameters).toMatchObject({
loader: "auto-from-header",
language_id: "x86:LE:32:default",
compiler_spec_id: "borlandcpp",
language_selection: "configured-v1",
});
expect(ghidraProfileLanguageOverride(parameters)).toEqual({
languageId: "x86:LE:32:default",
compilerSpecId: "borlandcpp",
});
});
it("records the language default when no compiler spec is configured", async () => {
const resolved = await provider({
REA_GHIDRA_LANGUAGE_ID: "x86:LE:32:default",
}).resolveAnalysisProfile(pe);
if (!resolved.ok) throw resolved.error;
const parameters = resolved.value.profile?.parameters ?? {};
expect(parameters.compiler_spec_id).toBe("language-default");
expect(ghidraProfileLanguageOverride(parameters)).toEqual({
languageId: "x86:LE:32:default",
});
});
it("keeps header auto-detection and a distinct digest without an override", async () => {
const automatic = await provider({}).resolveAnalysisProfile(pe);
const configured = await provider({
REA_GHIDRA_LANGUAGE_ID: "x86:LE:32:default",
REA_GHIDRA_COMPILER_SPEC_ID: "borlandcpp",
}).resolveAnalysisProfile(pe);
if (!automatic.ok) throw automatic.error;
if (!configured.ok) throw configured.error;
const parameters = automatic.value.profile?.parameters ?? {};
expect(parameters).toMatchObject({
language_id: "auto-from-header",
compiler_spec_id: "auto-default",
});
expect(parameters).not.toHaveProperty("language_selection");
expect(ghidraProfileLanguageOverride(parameters)).toBeUndefined();
expect(automatic.value.profile?.digest).not.toBe(
configured.value.profile?.digest,
);
});
it("refuses an undefined compiler spec before launching Ghidra", async () => {
const resolved = await provider({
REA_GHIDRA_LANGUAGE_ID: "x86:LE:32:default",
REA_GHIDRA_COMPILER_SPEC_ID: "golang",
}).resolveAnalysisProfile(pe);
if (resolved.ok) throw new Error("Expected a configuration error");
expect(projectAnalysisError(resolved.error)).toMatchObject({
code: "configuration_invalid",
details: {
settings: [{ setting: "REA_GHIDRA_COMPILER_SPEC_ID" }],
},
});
});
it("compares committed and configured selections exactly", () => {
expect(sameGhidraLanguageOverride(undefined, undefined)).toBe(true);
expect(
sameGhidraLanguageOverride(
{ languageId: "x86:LE:32:default" },
{ languageId: "x86:LE:32:default", compilerSpecId: "borlandcpp" },
),
).toBe(false);
});
});
+49 -1
View File
@@ -1,3 +1,9 @@
import {
GHIDRA_SEED_SCRIPT,
snapshotGhidraAnalysisSeeds,
type GhidraSeedCommitment,
} from "./GhidraAnalysisSeeds.js";
import type { GhidraLanguageOverride } from "../config/ghidraLanguageOverride.js";
import { snapshotEnvironment } from "../process/snapshotEnvironment.js";
import { mkdir } from "node:fs/promises";
import { basename, dirname, join, posix, win32 } from "node:path";
@@ -85,6 +91,10 @@ export interface GhidraHeadlessLauncherOptions {
/** Select the admitted 16-bit real-mode MZ import instead of auto-detection. */
readonly dosMz?: true;
readonly dosCom?: true;
/** Explicit import language committed by the analysis profile. */
readonly languageOverride?: GhidraLanguageOverride;
/** Caller seeds committed by the analysis profile, applied before analysis. */
readonly analysisSeeds?: GhidraSeedCommitment;
readonly analysisExtensions?: readonly GhidraExtension[];
/** Spawn seam for provider-boundary lifecycle tests. */
readonly spawnProcess?: typeof spawnOwnedProviderProcess;
@@ -111,6 +121,13 @@ export class GhidraHeadlessLauncher implements GhidraLauncher {
let started: SpawnedOwnedProviderProcess | undefined;
try {
await createGhidraRuntimeDirectories(paths, platform);
const seedPath =
this.options.analysisSeeds === undefined
? undefined
: await snapshotGhidraAnalysisSeeds(
this.options.analysisSeeds,
session.runtimeRoot,
);
const extensions = await snapshotGhidraExtensions(
this.options.analysisExtensions ?? [],
session.runtimeRoot,
@@ -147,6 +164,10 @@ export class GhidraHeadlessLauncher implements GhidraLauncher {
...(this.options.dosMz === undefined
? {}
: { dosMz: this.options.dosMz }),
...(this.options.languageOverride === undefined
? {}
: { languageOverride: this.options.languageOverride }),
...(seedPath === undefined ? {} : { seedPath }),
});
const scriptCommand = ghidraHeadlessCommand({
environment: this.options.environment,
@@ -368,6 +389,9 @@ export interface GhidraHeadlessArgumentOptions {
readonly scriptLogPath: string;
readonly dosMz?: true;
readonly dosCom?: true;
readonly languageOverride?: GhidraLanguageOverride;
/** Canonical seed snapshot passed to the pre-analysis seed script. */
readonly seedPath?: string;
}
/** Build the complete read-only headless invocation in deterministic order. */
@@ -379,6 +403,14 @@ export const ghidraHeadlessArguments = (
const scriptPath =
(options.platform ?? process.platform) === "win32" ? win32 : posix;
const bridgeDirectory = scriptPath.dirname(options.bridgeScriptPath);
const override = options.languageOverride;
if (
override !== undefined &&
(options.dosMz === true || options.dosCom === true)
)
throw new Error(
"A Ghidra language override cannot be combined with a DOS import.",
);
return [
options.projectRoot,
"rea-project",
@@ -404,7 +436,15 @@ export const ghidraHeadlessArguments = (
"-cspec",
"default",
]
: []),
: override !== undefined
? [
"-processor",
override.languageId,
...(override.compilerSpecId === undefined
? []
: ["-cspec", override.compilerSpecId]),
]
: []),
"-readOnly",
"-deleteProject",
"-log",
@@ -419,6 +459,14 @@ export const ghidraHeadlessArguments = (
scriptPath.join(bridgeDirectory, "ReaGhidraPrepareCom.java"),
]
: []),
// Seeds follow any loader preparation and precede default auto-analysis.
...(options.seedPath === undefined
? []
: [
"-preScript",
scriptPath.join(bridgeDirectory, GHIDRA_SEED_SCRIPT),
options.seedPath,
]),
...((options.platform ?? process.platform) === "win32"
? []
: [
+152
View File
@@ -1,3 +1,4 @@
import type { GhidraSeedReport } from "./GhidraAnalysisSeeds.js";
import { createHash } from "node:crypto";
import { execFile } from "node:child_process";
// Fake-backed provider coverage; real Ghidra verification lives in
@@ -1010,3 +1011,154 @@ it("projects Ghidra startup failure and its incomplete cleanup together", async
},
});
});
describe("Ghidra analysis seeds and configured language", () => {
const seedSession = async (
report: (sha256: string) => GhidraSeedReport | undefined,
) => {
const directory = await mkdtemp(join(tmpdir(), "rea-provider-seeds-"));
const seeds = join(directory, "seeds.tsv");
await writeFile(seeds, "0x401000\tfunction\tentry\n0x401010\tcode\n");
const config = parseConfig({
GHIDRA_INSTALL_DIR: INSTALL,
REA_GHIDRA_SEED_FILE: seeds,
});
if (!config.ok) throw config.error;
const counts = { starts: 0, calls: 0, closes: 0 };
const ghidra = new GhidraProvider(
config.value,
silentLogger,
{},
installationHost(),
() => ({
start: () => {
counts.starts++;
const seedReport = report(
createHash("sha256")
.update("0x401000\tfunction\tentry\n0x401010\tcode\n")
.digest("hex"),
);
return Promise.resolve(
ok({
...sessionInfo(),
...(seedReport === undefined
? {}
: { analysis_seeds: seedReport }),
}),
);
},
callTool: () => {
counts.calls++;
return Promise.resolve(ok(null));
},
close: () => {
counts.closes++;
return Promise.resolve(ok(null));
},
}),
);
const target = executableTarget("elf", "x86_64");
const resolved = await ghidra.resolveAnalysisProfile(target);
if (!resolved.ok || resolved.value.profile === null)
throw new Error("expected seed profile");
return {
directory,
counts,
client: ghidra.createClient(target, resolved.value.profile),
};
};
const applied = (sha256: string): GhidraSeedReport => ({
format: "rea-ghidra-seeds-v1",
sha256,
entries: 2,
function_created: 1,
function_existing: 0,
function_failed: 0,
code_decoded: 0,
code_failed: 1,
label_applied: 0,
label_failed: 0,
unmapped: 0,
});
it("reports the verified seed outcome as a session limitation", async () => {
const { directory, client } = await seedSession(applied);
try {
const health = await client.execute("health", {});
if (!health.ok) throw health.error;
expect(health.value.limitations).toEqual(
expect.arrayContaining([
expect.stringContaining("caller assertions, not Ghidra discoveries"),
expect.stringContaining(
"1 functions created, 0 already present, 0 failed; 0 code seeds decoded, 1 failed",
),
]),
);
} finally {
await rm(directory, { recursive: true, force: true });
}
});
it.each([
["no seed report", () => undefined],
[
"a report for other seeds",
(sha256: string): GhidraSeedReport => ({
...applied(sha256),
sha256: "0".repeat(64),
}),
],
])("fails closed on %s before any analysis call", async (_label, report) => {
const { directory, counts, client } = await seedSession(report);
try {
const failed = await client.execute("list_procedures", {});
expect(failed.ok).toBe(false);
if (!failed.ok) expect(failed.error._tag).toBe("ProviderAdapterError");
expect(counts).toEqual({ starts: 1, calls: 0, closes: 1 });
} finally {
await rm(directory, { recursive: true, force: true });
}
});
it("refuses a profile resolved without the configured seeds or language", async () => {
const plain = parseConfig({ GHIDRA_INSTALL_DIR: INSTALL });
if (!plain.ok) throw plain.error;
const target = executableTarget("elf", "x86_64");
const resolved = await new GhidraProvider(
plain.value,
silentLogger,
{},
installationHost(),
).resolveAnalysisProfile(target);
if (!resolved.ok || resolved.value.profile === null)
throw new Error("expected profile");
for (const environment of [
{ REA_GHIDRA_SEED_FILE: "/seeds.tsv" },
{ REA_GHIDRA_LANGUAGE_ID: "x86:LE:32:default" },
]) {
const configured = parseConfig({
GHIDRA_INSTALL_DIR: INSTALL,
...environment,
});
if (!configured.ok) throw configured.error;
let starts = 0;
const client = new GhidraProvider(
configured.value,
silentLogger,
{},
installationHost(),
() => ({
start: () => {
starts++;
return Promise.resolve(ok(sessionInfo()));
},
callTool: () => Promise.resolve(ok(null)),
close: () => Promise.resolve(ok(null)),
}),
).createClient(target, resolved.value.profile);
const failed = await client.execute("health", {});
expect(failed.ok).toBe(false);
expect(starts).toBe(0);
}
});
});
+44 -3
View File
@@ -20,7 +20,8 @@ import {
jsonValueSchema,
type JsonValue,
} from "../domain/jsonValue.js";
import { ok } from "../domain/result.js";
import { err, ok } from "../domain/result.js";
import { ProviderAdapterError } from "../domain/providerAdapterError.js";
import type { Logger } from "pino";
import { GhidraClient } from "./GhidraClient.js";
import {
@@ -30,6 +31,12 @@ import {
type GhidraInstallationInspection,
} from "./GhidraInstallation.js";
import { resolveGhidraAnalysisProfile } from "./GhidraAnalysisProfile.js";
import { AnalysisCancelledError } from "../domain/analysisErrorCore.js";
import { resolveGhidraAnalysisSeeds } from "./GhidraAnalysisSeeds.js";
import {
admitGhidraLanguageOverride,
readGhidraLanguageCatalog,
} from "./GhidraLanguageCatalog.js";
import { ghidraMipsUnsupportedReason } from "./GhidraMipsProfile.js";
import { resolveGhidraExtensions } from "./extensions/GhidraExtensions.js";
import {
@@ -184,8 +191,32 @@ export class GhidraProvider implements AnalysisProviderCandidate {
GHIDRA_PROVIDER_IDENTITY,
installation,
options?.signal,
this.config.ghidraLanguageOverride,
);
if (!resolved.ok || resolved.value.profile === null) return resolved;
const override = this.config.ghidraLanguageOverride;
if (override !== undefined && installation.status === "available") {
let catalog: Awaited<ReturnType<typeof readGhidraLanguageCatalog>>;
try {
catalog = await readGhidraLanguageCatalog(installation.installDir);
} catch (cause: unknown) {
return err(
new ProviderAdapterError("ghidra", "resolve_analysis_profile", {
cause,
diagnostics: {
reason:
"Could not read the installed Ghidra language definitions.",
},
}),
);
}
const refused = admitGhidraLanguageOverride(
override,
catalog,
installation.providerVersion,
);
if (refused !== null) return err(refused);
}
const extensions = await resolveGhidraExtensions(
this.config,
target,
@@ -193,12 +224,22 @@ export class GhidraProvider implements AnalysisProviderCandidate {
options?.signal,
);
if (!extensions.ok) return extensions;
if (extensions.value.length === 0) return resolved;
if (options?.signal?.aborted === true)
return err(new AnalysisCancelledError("open_binary"));
const seeds = await resolveGhidraAnalysisSeeds(this.config.ghidraSeedFile);
if (!seeds.ok) return seeds;
if (extensions.value.length === 0 && seeds.value === undefined)
return resolved;
return ok({
...resolved.value,
profile: createAnalysisProfile(resolved.value.profile.provider, {
...resolved.value.profile.parameters,
analysis_extensions: jsonValueSchema.parse(extensions.value),
...(extensions.value.length === 0
? {}
: { analysis_extensions: jsonValueSchema.parse(extensions.value) }),
...(seeds.value === undefined
? {}
: { analysis_seeds: jsonValueSchema.parse(seeds.value) }),
}),
});
}
+68 -10
View File
@@ -9,6 +9,15 @@ import {
} from "../application/AnalysisProvider.js";
import type { AppConfig } from "../config/types.js";
import type { JsonValue } from "../domain/jsonValue.js";
import {
ghidraSeedCommitmentSchema,
ghidraSeedFailure,
ghidraSeedLimitations,
} from "./GhidraAnalysisSeeds.js";
import {
ghidraProfileLanguageOverride,
sameGhidraLanguageOverride,
} from "./GhidraAnalysisProfile.js";
import type { AnalysisProfileCommitment } from "../domain/analysisProfile.js";
import type { BinaryTarget } from "../domain/binaryTargetTypes.js";
import {
@@ -105,6 +114,36 @@ export const createGhidraProviderClient = (input: {
}),
);
const extensions = extensionProfile.data;
const seedProfile = ghidraSeedCommitmentSchema
.optional()
.safeParse(committedProfile.parameters.analysis_seeds);
if (
!seedProfile.success ||
(config.ghidraSeedFile === undefined) !== (seedProfile.data === undefined)
)
return unavailableClient(
new ProviderAdapterError("ghidra", "open_binary", {
diagnostics: {
reason:
"Resolve REA_GHIDRA_SEED_FILE into an analysis profile before opening the session.",
},
}),
);
const seeds = seedProfile.data;
const languageOverride = ghidraProfileLanguageOverride(
committedProfile.parameters,
);
if (
!sameGhidraLanguageOverride(languageOverride, config.ghidraLanguageOverride)
)
return unavailableClient(
new ProviderAdapterError("ghidra", "open_binary", {
diagnostics: {
reason:
"The committed analysis profile and REA_GHIDRA_LANGUAGE_ID/REA_GHIDRA_COMPILER_SPEC_ID differ; reopen the target to resolve a new profile.",
},
}),
);
const invalidProfile = validateGhidraExtensionProfile(
extensions,
config,
@@ -118,6 +157,8 @@ export const createGhidraProviderClient = (input: {
}),
);
let extensionFailure: AnalysisError | undefined;
// Replaced by the reported outcome once the session handshake is checked.
const seedLimitations: string[] = [...ghidraSeedLimitations(seeds)];
const targetLimitations = [
...(target.format === "dos-mz"
? [
@@ -149,6 +190,8 @@ export const createGhidraProviderClient = (input: {
),
...(target.format === "dos-mz" ? { dosMz: true } : {}),
...(target.format === "dos-com" ? { dosCom: true } : {}),
...(languageOverride === undefined ? {} : { languageOverride }),
...(seeds === undefined ? {} : { analysisSeeds: seeds }),
platform: installation.platform,
...(extensions.length === 0 ? {} : { analysisExtensions: extensions }),
}),
@@ -168,7 +211,14 @@ export const createGhidraProviderClient = (input: {
expectedLanguageId: "x86:LE:16:Real Mode",
expectedCompilerSpecId: "default",
}
: {}),
: languageOverride === undefined
? {}
: {
expectedLanguageId: languageOverride.languageId,
...(languageOverride.compilerSpecId === undefined
? {}
: { expectedCompilerSpecId: languageOverride.compilerSpecId }),
}),
...(context === undefined ? {} : { runId: context.runId }),
logger: logger.child({ layer: "ghidra-bridge" }),
});
@@ -176,11 +226,18 @@ export const createGhidraProviderClient = (input: {
operation: AnalysisOperation,
info: GhidraSessionInfo,
): Promise<AnalysisError | undefined> => {
extensionFailure = ghidraExtensionFailure(
extensions,
info.analysis_extensions ?? [],
operation,
);
extensionFailure =
ghidraExtensionFailure(
extensions,
info.analysis_extensions ?? [],
operation,
) ?? ghidraSeedFailure(seeds, info.analysis_seeds, operation);
if (extensionFailure === undefined && info.analysis_seeds !== undefined)
seedLimitations.splice(
0,
seedLimitations.length,
...ghidraSeedLimitations(seeds, info.analysis_seeds),
);
if (extensionFailure === undefined) return undefined;
const closed = await client.close();
return closed.ok
@@ -194,10 +251,11 @@ export const createGhidraProviderClient = (input: {
const releaseLimitation = unverifiedGhidraBuildLimitation(
prerequisites.value.providerVersion,
);
const sessionLimitations = [
const sessionLimitations = (): readonly string[] => [
...providerLimitations,
...targetLimitations,
...ghidraExtensionLimitations(extensions),
...seedLimitations,
...(releaseLimitation === undefined ? [] : [releaseLimitation]),
];
return {
@@ -230,7 +288,7 @@ export const createGhidraProviderClient = (input: {
return ok(
createAnalysisExecution(started.value, committedProfile.provider, {
analysisProfile: committedProfile,
limitations: [...healthLimitations, ...sessionLimitations],
limitations: [...healthLimitations, ...sessionLimitations()],
}),
);
}
@@ -238,7 +296,7 @@ export const createGhidraProviderClient = (input: {
? parseGhidraFunctionInput(operation, parameters)
: parseGhidraInventoryInput(operation, parameters);
if (!input.ok) return input;
if (extensions.length > 0) {
if (extensions.length > 0 || seeds !== undefined) {
const started = await client.start(options?.signal);
if (!started.ok)
return err(
@@ -299,7 +357,7 @@ export const createGhidraProviderClient = (input: {
limitations: [
...limitationsFor(operation),
...observationLimitations,
...sessionLimitations,
...sessionLimitations(),
],
}),
);
+2
View File
@@ -1,3 +1,4 @@
import { ghidraSeedReportSchema } from "./GhidraAnalysisSeeds.js";
import { z } from "zod";
import type { JsonValue } from "../domain/jsonValue.js";
@@ -40,6 +41,7 @@ const sessionInfoSchema = z
analysis_complete: z.boolean(),
analysis_timed_out: z.boolean(),
analysis_extensions: z.array(ghidraExtensionResultSchema).optional(),
analysis_seeds: ghidraSeedReportSchema.optional(),
capabilities: z.array(capabilitySchema),
target: z
.object({
@@ -702,7 +702,10 @@ export class JavaScriptAnalysisWorker {
},
{
operation: OPERATION,
...(original === undefined ? {} : { cause: original }),
cause: new Error(
reason,
original === undefined ? undefined : { cause: original },
),
},
);
}