feat(ghidra): add function analysis and conformance
This commit is contained in:
@@ -0,0 +1,27 @@
|
||||
# Ghidra conformance corpus
|
||||
|
||||
These source-owned fixtures are compiled at verification time; generated
|
||||
binaries and Ghidra projects are never committed.
|
||||
|
||||
- `inventory.c` produces separate x86-64 debug and stripped ELF executables.
|
||||
It covers imports, an external `puts` function, linker thunks, source symbols,
|
||||
direct calls, a targetless callback call, two referenced strings, and a
|
||||
multi-block branch.
|
||||
- `cross-format.c` is freestanding so the verifier can produce AArch64 ELF,
|
||||
x86-64 PE, and x86-64 Mach-O targets from the same semantics. It preserves an
|
||||
exported entry, direct and indirect calls, a volatile string reference, and a
|
||||
multi-block branch across loaders.
|
||||
|
||||
`scripts/verify-real-ghidra.mjs` uses `cc`, `clang`, and `lld-link` by default;
|
||||
`REA_CC`, `REA_CLANG`, and `REA_LLD_LINK` can select alternate commands. The
|
||||
verifier requires an exact bring-your-own Ghidra 12.1.2 installation through
|
||||
`GHIDRA_INSTALL_DIR` and validates header classification before starting the
|
||||
provider.
|
||||
|
||||
Conformance compares semantic facts: provider/profile identity, function
|
||||
classification, resolved call edges, typed references, strings/xrefs, and CFG
|
||||
topology. It only requires provider pseudocode and assembly to be non-empty,
|
||||
bounded, and address-bearing; it never compares their text with Hopper. The
|
||||
callback fixture also proves that an unresolved targetless flow is not silently
|
||||
promoted to a direct callee. Every target runs in a separate owned project and
|
||||
must leave no process, socket, project, or runtime root after close.
|
||||
@@ -0,0 +1,31 @@
|
||||
typedef int (*rea_cross_callback)(int);
|
||||
|
||||
volatile int rea_cross_global = 7;
|
||||
const volatile char rea_cross_message[] = "REA_GHIDRA_CROSS_FORMAT";
|
||||
|
||||
__attribute__((noinline, used)) int rea_cross_leaf(int value) {
|
||||
return value + rea_cross_global + rea_cross_message[0] - 'R';
|
||||
}
|
||||
|
||||
__attribute__((noinline, used)) int rea_cross_branch(int value) {
|
||||
if (value > 10) {
|
||||
return rea_cross_leaf(value);
|
||||
}
|
||||
return rea_cross_leaf(-value);
|
||||
}
|
||||
|
||||
__attribute__((noinline, used)) int rea_cross_indirect(
|
||||
rea_cross_callback callback, int value) {
|
||||
return callback(value);
|
||||
}
|
||||
|
||||
__attribute__((noinline, used, visibility("default"))) int rea_cross_entry(void) {
|
||||
return rea_cross_branch(35) + rea_cross_indirect(rea_cross_leaf, 0);
|
||||
}
|
||||
|
||||
__attribute__((used, visibility("default"))) void rea_cross_start(void) {
|
||||
volatile int result = rea_cross_entry();
|
||||
(void)result;
|
||||
for (;;) {
|
||||
}
|
||||
}
|
||||
@@ -7,9 +7,22 @@ __attribute__((noinline, used)) int rea_ghidra_inventory_leaf(int value) {
|
||||
return value + rea_ghidra_inventory_global;
|
||||
}
|
||||
|
||||
__attribute__((noinline, used)) int rea_ghidra_inventory_entry(void) {
|
||||
puts("REA_GHIDRA_INVENTORY_ENTRY");
|
||||
return rea_ghidra_inventory_leaf(35);
|
||||
__attribute__((noinline, used)) int rea_ghidra_inventory_branch(int value) {
|
||||
if (value > 10) {
|
||||
return rea_ghidra_inventory_leaf(value);
|
||||
}
|
||||
return rea_ghidra_inventory_leaf(-value);
|
||||
}
|
||||
|
||||
int main(void) { return rea_ghidra_inventory_entry() == 42 ? 0 : 1; }
|
||||
__attribute__((noinline, used)) int rea_ghidra_inventory_indirect(
|
||||
int (*callback)(int), int value) {
|
||||
return callback(value);
|
||||
}
|
||||
|
||||
__attribute__((noinline, used)) int rea_ghidra_inventory_entry(void) {
|
||||
puts("REA_GHIDRA_INVENTORY_ENTRY");
|
||||
return rea_ghidra_inventory_branch(35) +
|
||||
rea_ghidra_inventory_indirect(rea_ghidra_inventory_leaf, 0);
|
||||
}
|
||||
|
||||
int main(void) { return rea_ghidra_inventory_entry() == 49 ? 0 : 1; }
|
||||
|
||||
Vendored
+22
-2
@@ -102,6 +102,9 @@ else {
|
||||
);
|
||||
continue;
|
||||
}
|
||||
if (mode === "exit_tools" && request.method !== "shutdown")
|
||||
process.exit(74);
|
||||
if (mode === "hang_tools" && request.method !== "shutdown") continue;
|
||||
const inventory = inventoryResult(request.method);
|
||||
if (inventory !== undefined) {
|
||||
socket.write(
|
||||
@@ -132,7 +135,7 @@ const sessionInfo = ({
|
||||
timedOut,
|
||||
}) => ({
|
||||
name: "REA Ghidra bridge",
|
||||
bridge_version: 2,
|
||||
bridge_version: 3,
|
||||
run_id: sessionRunId,
|
||||
profile_digest: digest,
|
||||
provider: { id: "ghidra", version },
|
||||
@@ -152,6 +155,14 @@ const sessionInfo = ({
|
||||
"resolve_containing_procedure",
|
||||
"search_procedures",
|
||||
"search_strings",
|
||||
"analyze_function",
|
||||
"procedure_assembly",
|
||||
"procedure_callees",
|
||||
"procedure_callers",
|
||||
"procedure_info",
|
||||
"procedure_pseudo_code",
|
||||
"procedure_references",
|
||||
"xrefs",
|
||||
],
|
||||
target: {
|
||||
name: "fixture",
|
||||
@@ -237,7 +248,16 @@ const inventoryResult = (method) => {
|
||||
return {
|
||||
query_address: "0x1001",
|
||||
found: true,
|
||||
procedure: { address: "0x1000", name: "fixture_main" },
|
||||
procedure: {
|
||||
address: "0x1000",
|
||||
name: "fixture_main",
|
||||
classification: {
|
||||
external: false,
|
||||
thunk: false,
|
||||
thunk_target: null,
|
||||
provenance: "ghidra-function-manager",
|
||||
},
|
||||
},
|
||||
};
|
||||
case "search_procedures":
|
||||
return page([
|
||||
|
||||
Vendored
+92
@@ -0,0 +1,92 @@
|
||||
import type { JsonValue } from "../../src/domain/jsonValue.js";
|
||||
|
||||
export const ghidraFunctionClassification = () => ({
|
||||
external: false,
|
||||
thunk: false,
|
||||
thunk_target: null,
|
||||
provenance: "ghidra-function-manager" as const,
|
||||
});
|
||||
|
||||
export const ghidraFunctionIdentity = () => ({
|
||||
address: "0x401000",
|
||||
name: "fixture_main",
|
||||
classification: ghidraFunctionClassification(),
|
||||
});
|
||||
|
||||
const ghidraReferenceKind = () => ({
|
||||
available: true as const,
|
||||
provenance: "ghidra-reference-manager" as const,
|
||||
type: "DATA",
|
||||
flow: false,
|
||||
call: false,
|
||||
jump: false,
|
||||
data: true,
|
||||
read: true,
|
||||
write: false,
|
||||
indirect: false,
|
||||
computed: false,
|
||||
conditional: false,
|
||||
terminal: false,
|
||||
primary: true,
|
||||
operand_index: 0,
|
||||
external: false,
|
||||
});
|
||||
|
||||
export const ghidraReferenceEdge = () => ({
|
||||
source_address: "0x401001",
|
||||
target_address: "0x402000",
|
||||
source_procedure: ghidraFunctionIdentity(),
|
||||
target_procedure: null,
|
||||
kind: ghidraReferenceKind(),
|
||||
});
|
||||
|
||||
export const ghidraBounded = (items: readonly JsonValue[]) => ({
|
||||
items: [...items],
|
||||
total: items.length,
|
||||
returned: items.length,
|
||||
truncated: false,
|
||||
next_offset: null,
|
||||
});
|
||||
|
||||
export const ghidraFunctionDossier = (includeAssembly = true): JsonValue => {
|
||||
const pseudocode = "int fixture_main(void) { return 42; }";
|
||||
return {
|
||||
procedure: {
|
||||
...ghidraFunctionIdentity(),
|
||||
signature: "int fixture_main(void)",
|
||||
locals: [],
|
||||
},
|
||||
pseudocode: {
|
||||
text: pseudocode,
|
||||
total_chars: [...pseudocode].length,
|
||||
returned_chars: [...pseudocode].length,
|
||||
truncated: false,
|
||||
next_offset: null,
|
||||
},
|
||||
assembly: ghidraBounded(
|
||||
includeAssembly ? ["0x401000: CALL 0x401020", "0x401005: RET"] : [],
|
||||
),
|
||||
comments: ghidraBounded([]),
|
||||
callers: ghidraBounded([]),
|
||||
callees: ghidraBounded([]),
|
||||
incoming_references: ghidraBounded([]),
|
||||
outgoing_references: ghidraBounded([ghidraReferenceEdge()]),
|
||||
referenced_strings: ghidraBounded([
|
||||
{
|
||||
address: "0x402000",
|
||||
value: "inventory fixture",
|
||||
source_address: "0x401001",
|
||||
},
|
||||
]),
|
||||
referenced_names: ghidraBounded([]),
|
||||
basic_blocks: ghidraBounded([
|
||||
{ start: "0x401000", end: "0x401006", successors: [] },
|
||||
]),
|
||||
instruction_scan: { scanned: 2, truncated: false },
|
||||
limitations: [
|
||||
"Unresolved computed or indirect flows without target addresses are not represented as reference edges.",
|
||||
"Thunk and external classifications are Ghidra FunctionManager observations; they do not resolve targetless calls.",
|
||||
"Pseudocode and assembly are Ghidra-specific representations, not original source or Hopper-equivalent text.",
|
||||
],
|
||||
};
|
||||
};
|
||||
@@ -55,6 +55,45 @@ const dossier = (
|
||||
instruction_scan: { scanned: 1, truncated: false },
|
||||
});
|
||||
|
||||
const dossierWithReference = (
|
||||
base: "0x1000" | "0x2000",
|
||||
kind: "call" | "data" | "unavailable",
|
||||
) => {
|
||||
const target = base === "0x1000" ? "0x1010" : "0x2010";
|
||||
return functionDossierSchema.parse({
|
||||
...dossier("return helper();", base),
|
||||
outgoing_references: bounded([
|
||||
{
|
||||
source_address: base,
|
||||
target_address: target,
|
||||
source_procedure: { address: base, name: "main" },
|
||||
target_procedure: { address: target, name: "helper" },
|
||||
kind:
|
||||
kind === "unavailable"
|
||||
? { available: false, reason: "provider has no kind authority" }
|
||||
: {
|
||||
available: true,
|
||||
provenance: "ghidra-reference-manager",
|
||||
type: kind === "call" ? "UNCONDITIONAL_CALL" : "READ",
|
||||
flow: kind === "call",
|
||||
call: kind === "call",
|
||||
jump: false,
|
||||
data: kind === "data",
|
||||
read: kind === "data",
|
||||
write: false,
|
||||
indirect: false,
|
||||
computed: false,
|
||||
conditional: false,
|
||||
terminal: false,
|
||||
primary: true,
|
||||
operand_index: 0,
|
||||
external: false,
|
||||
},
|
||||
},
|
||||
]),
|
||||
});
|
||||
};
|
||||
|
||||
const observe = (
|
||||
digit: string,
|
||||
value: ReturnType<typeof dossier>,
|
||||
@@ -154,6 +193,36 @@ describe("function comparison", () => {
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("compares exact reference kinds only when both providers expose them", () => {
|
||||
const left = observe("d", dossierWithReference("0x1000", "call"));
|
||||
const same = observe("e", dossierWithReference("0x2000", "call"));
|
||||
expect(
|
||||
compareFunctions(left, same, 0, 100).dimensions.find(
|
||||
({ dimension }) => dimension === "references",
|
||||
),
|
||||
).toMatchObject({ status: "unchanged" });
|
||||
|
||||
const changed = observe("f", dossierWithReference("0x2000", "data"));
|
||||
expect(
|
||||
compareFunctions(left, changed, 0, 100).dimensions.find(
|
||||
({ dimension }) => dimension === "references",
|
||||
),
|
||||
).toMatchObject({ status: "changed" });
|
||||
|
||||
const unavailable = observe(
|
||||
"1",
|
||||
dossierWithReference("0x2000", "unavailable"),
|
||||
);
|
||||
expect(
|
||||
compareFunctions(left, unavailable, 0, 100).dimensions.find(
|
||||
({ dimension }) => dimension === "references",
|
||||
),
|
||||
).toMatchObject({
|
||||
status: "unknown",
|
||||
limitations: [expect.stringContaining("did not expose reference kinds")],
|
||||
});
|
||||
});
|
||||
|
||||
it("does not promote address-derived names through equal signatures", () => {
|
||||
const autoDossier = (base: "0x1000" | "0x2000") =>
|
||||
functionDossierSchema.parse({
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
import { beforeAll, describe, expect, it } from "vitest";
|
||||
|
||||
let bridgeSource = "";
|
||||
let queueSource = "";
|
||||
|
||||
beforeAll(async () => {
|
||||
[bridgeSource, queueSource] = await Promise.all([
|
||||
readFile(
|
||||
fileURLToPath(
|
||||
new URL("../bridge/ghidra/ReaGhidraBridge.java", import.meta.url),
|
||||
),
|
||||
"utf8",
|
||||
),
|
||||
readFile(
|
||||
fileURLToPath(
|
||||
new URL("../src/ghidra/GhidraRequestQueue.ts", import.meta.url),
|
||||
),
|
||||
"utf8",
|
||||
),
|
||||
]);
|
||||
});
|
||||
|
||||
describe("Ghidra bridge truthfulness", () => {
|
||||
it("owns one persistent decompiler interface for the Program lifetime", () => {
|
||||
expect(bridgeSource).toContain("private DecompInterface decompiler;");
|
||||
expect(bridgeSource.match(/new DecompInterface\(\)/gu)).toHaveLength(1);
|
||||
expect(
|
||||
bridgeSource.match(/decompiler\.openProgram\(currentProgram\)/gu),
|
||||
).toHaveLength(1);
|
||||
expect(bridgeSource).toContain("decompiler.dispose()");
|
||||
expect(bridgeSource).toContain("DECOMPILE_TIMEOUT_SECONDS = 30");
|
||||
expect(bridgeSource).toContain(
|
||||
"decompileFunction(\n function,\n DECOMPILE_TIMEOUT_SECONDS",
|
||||
);
|
||||
});
|
||||
|
||||
it("projects references and CFG from public Ghidra models", () => {
|
||||
expect(bridgeSource).toContain("getReferenceManager().getReferencesTo");
|
||||
expect(bridgeSource).toContain(
|
||||
"getReferencesFrom(instruction.getAddress())",
|
||||
);
|
||||
expect(bridgeSource).toContain(
|
||||
"new BasicBlockModel(currentProgram, false)",
|
||||
);
|
||||
expect(bridgeSource).toContain("block.getDestinations(monitor)");
|
||||
expect(bridgeSource).toContain(
|
||||
'result.addProperty("computed", type.isComputed())',
|
||||
);
|
||||
expect(bridgeSource).toContain(
|
||||
'result.addProperty("indirect", type.isIndirect())',
|
||||
);
|
||||
expect(bridgeSource).toContain(
|
||||
'result.addProperty("external", reference.isExternalReference())',
|
||||
);
|
||||
expect(bridgeSource).toContain("reference.isEntryPointReference()");
|
||||
});
|
||||
|
||||
it("keeps function classification and targetless-flow uncertainty explicit", () => {
|
||||
expect(bridgeSource).toContain("function.isThunk()");
|
||||
expect(bridgeSource).toContain("function.isExternal()");
|
||||
expect(bridgeSource).toContain('"ghidra-function-manager"');
|
||||
expect(bridgeSource).toContain(
|
||||
"Unresolved computed or indirect flows without target addresses",
|
||||
);
|
||||
expect(bridgeSource).toContain(
|
||||
"not original source or Hopper-equivalent text",
|
||||
);
|
||||
});
|
||||
|
||||
it("serializes a bounded request queue before crossing the socket", () => {
|
||||
expect(queueSource).toContain("class GhidraRequestQueue");
|
||||
expect(queueSource).toContain("if (this.#size >= this.maximum)");
|
||||
expect(queueSource).toContain("if (this.#active) return");
|
||||
expect(queueSource).toContain(
|
||||
"remaining = entry.deadline - performance.now()",
|
||||
);
|
||||
});
|
||||
|
||||
it("does not admit mutation methods into the Java dispatch", () => {
|
||||
for (const method of [
|
||||
'case "set_comment"',
|
||||
'case "set_address_name"',
|
||||
'case "set_inline_comment"',
|
||||
'case "set_bookmark"',
|
||||
])
|
||||
expect(bridgeSource).not.toContain(method);
|
||||
});
|
||||
});
|
||||
@@ -34,6 +34,8 @@ type FixtureMode =
|
||||
| "analysis_timeout"
|
||||
| "remote_error"
|
||||
| "hang_after_start"
|
||||
| "hang_tools"
|
||||
| "exit_tools"
|
||||
| "silent"
|
||||
| "exit";
|
||||
|
||||
@@ -230,6 +232,104 @@ describe("GhidraClient", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("fails an established function request when the provider process exits", async () => {
|
||||
const client = clientFor(new FixtureLauncher("exit_tools"));
|
||||
await expect(client.start()).resolves.toMatchObject({ ok: true });
|
||||
|
||||
await expect(
|
||||
client.callTool("procedure_pseudo_code", {
|
||||
document: null,
|
||||
procedure: "fixture_main",
|
||||
}),
|
||||
).resolves.toMatchObject({ ok: false, error: { kind: "process" } });
|
||||
});
|
||||
|
||||
it("cancels an established queued operation promptly", async () => {
|
||||
const client = clientFor(new FixtureLauncher("hang_tools"), {
|
||||
requestTimeoutMs: 10_000,
|
||||
});
|
||||
await expect(client.start()).resolves.toMatchObject({ ok: true });
|
||||
const activeController = new AbortController();
|
||||
const active = client.callTool(
|
||||
"procedure_pseudo_code",
|
||||
{ document: null, procedure: "fixture_main" },
|
||||
{ signal: activeController.signal },
|
||||
);
|
||||
await wait(5);
|
||||
const queuedController = new AbortController();
|
||||
const queued = client.callTool(
|
||||
"procedure_info",
|
||||
{ document: null, procedure: "fixture_main" },
|
||||
{ signal: queuedController.signal },
|
||||
);
|
||||
queuedController.abort();
|
||||
|
||||
await expect(queued).resolves.toMatchObject({
|
||||
ok: false,
|
||||
error: { kind: "cancelled" },
|
||||
});
|
||||
activeController.abort();
|
||||
await active;
|
||||
});
|
||||
|
||||
it("counts serial queue wait against the request deadline", async () => {
|
||||
const client = clientFor(new FixtureLauncher("hang_tools"), {
|
||||
requestTimeoutMs: 10_000,
|
||||
});
|
||||
await expect(client.start()).resolves.toMatchObject({ ok: true });
|
||||
const activeController = new AbortController();
|
||||
const active = client.callTool(
|
||||
"procedure_pseudo_code",
|
||||
{ document: null, procedure: "fixture_main" },
|
||||
{ signal: activeController.signal },
|
||||
);
|
||||
await wait(5);
|
||||
|
||||
await expect(
|
||||
client.callTool(
|
||||
"procedure_info",
|
||||
{ document: null, procedure: "fixture_main" },
|
||||
{ timeoutMs: 5 },
|
||||
),
|
||||
).resolves.toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
kind: "timeout",
|
||||
timeoutMs: 5,
|
||||
message: expect.stringContaining("serial queue"),
|
||||
},
|
||||
});
|
||||
activeController.abort();
|
||||
await active;
|
||||
});
|
||||
|
||||
it("bounds the serial per-Program request queue", async () => {
|
||||
const client = clientFor(new FixtureLauncher("hang_tools"), {
|
||||
requestTimeoutMs: 10_000,
|
||||
});
|
||||
await expect(client.start()).resolves.toMatchObject({ ok: true });
|
||||
const controller = new AbortController();
|
||||
const requests = Array.from({ length: 33 }, () =>
|
||||
client.callTool(
|
||||
"procedure_pseudo_code",
|
||||
{ document: null, procedure: "fixture_main" },
|
||||
{ signal: controller.signal },
|
||||
),
|
||||
);
|
||||
const overflow = requests[32];
|
||||
if (overflow === undefined) throw new Error("Queue probe was not created");
|
||||
|
||||
await expect(overflow).resolves.toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
kind: "protocol",
|
||||
message: expect.stringContaining("32-request limit"),
|
||||
},
|
||||
});
|
||||
controller.abort();
|
||||
await Promise.all(requests.slice(0, 32));
|
||||
});
|
||||
|
||||
it("makes double close idempotent and detaches process listeners", async () => {
|
||||
const launcher = new FixtureLauncher();
|
||||
const client = clientFor(launcher);
|
||||
@@ -294,3 +394,6 @@ describe("GhidraClient", () => {
|
||||
const exited = (process_: ChildProcess | undefined): boolean =>
|
||||
process_ !== undefined &&
|
||||
(process_.exitCode !== null || process_.signalCode !== null);
|
||||
|
||||
const wait = (milliseconds: number): Promise<void> =>
|
||||
new Promise((resolve) => setTimeout(resolve, milliseconds));
|
||||
|
||||
@@ -0,0 +1,200 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import type { JsonValue } from "../src/domain/jsonValue.js";
|
||||
import {
|
||||
GHIDRA_FUNCTION_OPERATIONS,
|
||||
isGhidraFunctionOperation,
|
||||
parseGhidraFunctionInput,
|
||||
parseGhidraFunctionResult,
|
||||
type GhidraFunctionOperation,
|
||||
} from "../src/ghidra/GhidraFunctionValues.js";
|
||||
import {
|
||||
ghidraBounded,
|
||||
ghidraFunctionClassification,
|
||||
ghidraFunctionDossier,
|
||||
ghidraFunctionIdentity,
|
||||
ghidraReferenceEdge,
|
||||
} from "./fixtures/ghidraFunction.js";
|
||||
|
||||
describe("Ghidra function-analysis boundary values", () => {
|
||||
it("defaults bounded inputs and rejects undeclared or implicit addresses", () => {
|
||||
expect(
|
||||
parseGhidraFunctionInput("procedure_info", { procedure: "main" }),
|
||||
).toEqual({
|
||||
ok: true,
|
||||
value: { document: null, procedure: "main" },
|
||||
});
|
||||
expect(
|
||||
parseGhidraFunctionInput("procedure_references", { procedure: "main" }),
|
||||
).toEqual({
|
||||
ok: true,
|
||||
value: {
|
||||
document: null,
|
||||
procedure: "main",
|
||||
direction: "outgoing",
|
||||
offset: 0,
|
||||
limit: 100,
|
||||
max_instructions: 500,
|
||||
},
|
||||
});
|
||||
expect(
|
||||
parseGhidraFunctionInput("analyze_function", { procedure: "main" }),
|
||||
).toMatchObject({
|
||||
ok: true,
|
||||
value: {
|
||||
procedure: "main",
|
||||
include_assembly: false,
|
||||
limit: 100,
|
||||
max_pseudocode_chars: 20_000,
|
||||
max_instructions: 500,
|
||||
pseudocode_offset: 0,
|
||||
assembly_offset: 0,
|
||||
collection_offset: { basic_blocks: 0, outgoing_references: 0 },
|
||||
},
|
||||
});
|
||||
expect(parseGhidraFunctionInput("xrefs", {})).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "AnalysisInputError" },
|
||||
});
|
||||
expect(
|
||||
parseGhidraFunctionInput("procedure_info", {
|
||||
procedure: "main",
|
||||
extra: true,
|
||||
}),
|
||||
).toMatchObject({ ok: false, error: { _tag: "AnalysisInputError" } });
|
||||
});
|
||||
|
||||
it("keeps the admitted operation set closed", () => {
|
||||
expect(GHIDRA_FUNCTION_OPERATIONS).toHaveLength(8);
|
||||
expect(isGhidraFunctionOperation("analyze_function")).toBe(true);
|
||||
expect(isGhidraFunctionOperation("procedure_pseudo_code")).toBe(true);
|
||||
expect(isGhidraFunctionOperation("list_procedures")).toBe(false);
|
||||
expect(isGhidraFunctionOperation("set_comment")).toBe(false);
|
||||
});
|
||||
|
||||
it("parses provider-classified function facts and reference kinds", () => {
|
||||
expect(
|
||||
parseGhidraFunctionResult("procedure_info", {
|
||||
name: "fixture_main",
|
||||
entrypoint: "0x401000",
|
||||
basicblock_count: 1,
|
||||
length: 6,
|
||||
signature: "int fixture_main(void)",
|
||||
locals: [
|
||||
{
|
||||
description: "int local @ Stack[-0x4]:4",
|
||||
provenance: "ghidra-function-database",
|
||||
},
|
||||
],
|
||||
classification: ghidraFunctionClassification(),
|
||||
}),
|
||||
).toMatchObject({ ok: true });
|
||||
expect(
|
||||
parseGhidraFunctionResult("procedure_references", {
|
||||
procedure: ghidraFunctionIdentity(),
|
||||
direction: "outgoing",
|
||||
references: ghidraBounded([ghidraReferenceEdge()]),
|
||||
instructions_scanned: 2,
|
||||
instruction_scan_truncated: false,
|
||||
}),
|
||||
).toMatchObject({
|
||||
ok: true,
|
||||
value: {
|
||||
references: {
|
||||
items: [
|
||||
{
|
||||
kind: {
|
||||
available: true,
|
||||
provenance: "ghidra-reference-manager",
|
||||
data: true,
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(
|
||||
parseGhidraFunctionResult("analyze_function", ghidraFunctionDossier()),
|
||||
).toMatchObject({ ok: true });
|
||||
});
|
||||
|
||||
it.each(malformedOutputs())(
|
||||
"rejects malformed %s output",
|
||||
(_name, operation, value) => {
|
||||
expect(parseGhidraFunctionResult(operation, value)).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "AnalysisOutputError" },
|
||||
});
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
const malformedOutputs = (): Array<
|
||||
[string, GhidraFunctionOperation, JsonValue]
|
||||
> => {
|
||||
const dossier = ghidraFunctionDossier();
|
||||
if (typeof dossier !== "object" || dossier === null || Array.isArray(dossier))
|
||||
throw new TypeError("Ghidra dossier fixture is invalid");
|
||||
const edge = ghidraReferenceEdge();
|
||||
return [
|
||||
["non-canonical address", "procedure_callers", ["401000"]],
|
||||
[
|
||||
"missing classification",
|
||||
"procedure_info",
|
||||
{
|
||||
name: "main",
|
||||
entrypoint: "0x401000",
|
||||
basicblock_count: 1,
|
||||
length: 1,
|
||||
signature: null,
|
||||
locals: [],
|
||||
},
|
||||
],
|
||||
[
|
||||
"unavailable Ghidra reference kind",
|
||||
"procedure_references",
|
||||
{
|
||||
procedure: ghidraFunctionIdentity(),
|
||||
direction: "outgoing",
|
||||
references: ghidraBounded([
|
||||
{ ...edge, kind: { available: false, reason: "unknown" } },
|
||||
]),
|
||||
instructions_scanned: 1,
|
||||
instruction_scan_truncated: false,
|
||||
},
|
||||
],
|
||||
[
|
||||
"Hopper local provenance",
|
||||
"analyze_function",
|
||||
{
|
||||
...dossier,
|
||||
procedure: {
|
||||
...ghidraFunctionIdentity(),
|
||||
signature: null,
|
||||
locals: [
|
||||
{
|
||||
description: "opaque",
|
||||
provenance: "hopper-public-python-api",
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
[
|
||||
"inconsistent dossier bound",
|
||||
"analyze_function",
|
||||
{
|
||||
...dossier,
|
||||
instruction_scan: { scanned: -1, truncated: false },
|
||||
},
|
||||
],
|
||||
[
|
||||
"missing uncertainty limitations",
|
||||
"analyze_function",
|
||||
{
|
||||
...dossier,
|
||||
limitations: [],
|
||||
},
|
||||
],
|
||||
];
|
||||
};
|
||||
+150
-9
@@ -10,7 +10,7 @@ import { parseEvidence } from "../src/domain/evidence.js";
|
||||
import type { JsonValue } from "../src/domain/jsonValue.js";
|
||||
import { ok } from "../src/domain/result.js";
|
||||
import type { GhidraInstallationHost } from "../src/ghidra/GhidraInstallation.js";
|
||||
import type { GhidraInventoryOperation } from "../src/ghidra/GhidraInventoryValues.js";
|
||||
import type { GhidraOperation } from "../src/ghidra/GhidraClient.js";
|
||||
import {
|
||||
GhidraProvider,
|
||||
type GhidraProviderClientFactory,
|
||||
@@ -18,12 +18,19 @@ import {
|
||||
import { GHIDRA_SESSION_CAPABILITIES } from "../src/ghidra/GhidraSessionValues.js";
|
||||
import { silentLogger } from "../src/logger.js";
|
||||
import { createServer } from "../src/server/createServer.js";
|
||||
import {
|
||||
ghidraBounded,
|
||||
ghidraFunctionClassification,
|
||||
ghidraFunctionDossier,
|
||||
ghidraFunctionIdentity,
|
||||
ghidraReferenceEdge,
|
||||
} from "./fixtures/ghidraFunction.js";
|
||||
|
||||
const INSTALL = "/opt/ghidra_12.1.2_PUBLIC";
|
||||
|
||||
describe("Ghidra MCP and shared CLI composition", () => {
|
||||
it("preserves provider evidence, composed parity, and capability routing", async () => {
|
||||
const calls: GhidraInventoryOperation[] = [];
|
||||
const calls: GhidraOperation[] = [];
|
||||
const factory: GhidraProviderClientFactory = (options) => ({
|
||||
start: () => Promise.resolve(ok(sessionInfo(options.profileDigest))),
|
||||
callTool: (operation, input) => {
|
||||
@@ -124,6 +131,88 @@ describe("Ghidra MCP and shared CLI composition", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const pseudocode = parseEvidence(
|
||||
(
|
||||
await mcp.callTool({
|
||||
name: "procedure_pseudo_code",
|
||||
arguments: { procedure: "fixture_main" },
|
||||
})
|
||||
).structuredContent,
|
||||
);
|
||||
expect(pseudocode).toMatchObject({
|
||||
operation: "procedure_pseudo_code",
|
||||
provider: { id: "ghidra", version: "12.1.2" },
|
||||
normalized_result: expect.stringContaining("return 42"),
|
||||
limitations: expect.arrayContaining([
|
||||
expect.stringContaining("not text-equivalent to Hopper"),
|
||||
expect.stringContaining("30-second native deadline"),
|
||||
]),
|
||||
});
|
||||
|
||||
const analyzed = parseEvidence(
|
||||
(
|
||||
await mcp.callTool({
|
||||
name: "analyze_function",
|
||||
arguments: { procedure: "fixture_main", include_assembly: true },
|
||||
})
|
||||
).structuredContent,
|
||||
);
|
||||
expect(analyzed).toMatchObject({
|
||||
operation: "analyze_function",
|
||||
provider: { id: "rea-workflow", version: "1" },
|
||||
normalized_result: {
|
||||
procedure: {
|
||||
address: "0x401000",
|
||||
name: "fixture_main",
|
||||
classification: {
|
||||
external: false,
|
||||
thunk: false,
|
||||
provenance: "ghidra-function-manager",
|
||||
},
|
||||
},
|
||||
pseudocode: { truncated: false },
|
||||
outgoing_references: {
|
||||
items: [
|
||||
{
|
||||
kind: {
|
||||
available: true,
|
||||
provenance: "ghidra-reference-manager",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
limitations: expect.arrayContaining([
|
||||
expect.stringContaining("indirect flows without target addresses"),
|
||||
expect.stringContaining(
|
||||
"not original source or Hopper-equivalent text",
|
||||
),
|
||||
]),
|
||||
},
|
||||
limitations: [
|
||||
"Derived by an REA workflow from one or more provider observations.",
|
||||
],
|
||||
});
|
||||
const directAnalyzed = await new EnhancedTools(session).execute(
|
||||
"analyze_function",
|
||||
{ procedure: "fixture_main", include_assembly: true },
|
||||
);
|
||||
expect(directAnalyzed.ok).toBe(true);
|
||||
if (!directAnalyzed.ok) return;
|
||||
expect(analyzed.normalized_result).toEqual(directAnalyzed.value);
|
||||
|
||||
const batch = await mcp.callTool({
|
||||
name: "batch_decompile",
|
||||
arguments: { addresses: ["fixture_main"] },
|
||||
});
|
||||
expect(batch.isError).not.toBe(true);
|
||||
expect(batch.structuredContent).toMatchObject({
|
||||
normalized_result: {
|
||||
succeeded: 1,
|
||||
failed: 0,
|
||||
items: [{ status: "ok" }],
|
||||
},
|
||||
});
|
||||
|
||||
const unsupported = await mcp.callTool({
|
||||
name: "set_comment",
|
||||
arguments: { address: "0x401000", comment: "not allowed" },
|
||||
@@ -156,13 +245,19 @@ describe("Ghidra MCP and shared CLI composition", () => {
|
||||
}),
|
||||
expect.objectContaining({
|
||||
name: "batch_decompile",
|
||||
available: false,
|
||||
reason: "provider_missing",
|
||||
available: true,
|
||||
}),
|
||||
expect.objectContaining({
|
||||
name: "trace_feature",
|
||||
available: false,
|
||||
reason: "provider_missing",
|
||||
available: true,
|
||||
}),
|
||||
expect.objectContaining({
|
||||
name: "get_call_graph",
|
||||
available: true,
|
||||
}),
|
||||
expect.objectContaining({
|
||||
name: "find_xrefs_to_name",
|
||||
available: true,
|
||||
}),
|
||||
]),
|
||||
},
|
||||
@@ -188,7 +283,7 @@ const installationHost = (): GhidraInstallationHost => ({
|
||||
|
||||
const sessionInfo = (profileDigest: string) => ({
|
||||
name: "REA Ghidra bridge" as const,
|
||||
bridge_version: 2 as const,
|
||||
bridge_version: 3 as const,
|
||||
run_id: "11111111-1111-4111-8111-111111111111",
|
||||
profile_digest: profileDigest,
|
||||
provider: { id: "ghidra" as const, version: "12.1.2" },
|
||||
@@ -206,7 +301,7 @@ const sessionInfo = (profileDigest: string) => ({
|
||||
});
|
||||
|
||||
const resultFor = (
|
||||
operation: GhidraInventoryOperation,
|
||||
operation: GhidraOperation,
|
||||
input: Readonly<Record<string, JsonValue>>,
|
||||
): JsonValue => {
|
||||
const limit = typeof input.limit === "number" ? input.limit : 100;
|
||||
@@ -256,6 +351,23 @@ const resultFor = (
|
||||
},
|
||||
];
|
||||
case "list_names":
|
||||
return page(
|
||||
[
|
||||
{
|
||||
address: "0x401000",
|
||||
value: "fixture_main",
|
||||
value_truncated: false,
|
||||
symbol: {
|
||||
primary: true,
|
||||
dynamic: false,
|
||||
external: false,
|
||||
type: "function",
|
||||
source: "user_defined",
|
||||
},
|
||||
},
|
||||
],
|
||||
limit,
|
||||
);
|
||||
case "search_procedures":
|
||||
case "search_strings":
|
||||
return page([], limit);
|
||||
@@ -267,8 +379,37 @@ const resultFor = (
|
||||
return {
|
||||
query_address: "0x401001",
|
||||
found: true,
|
||||
procedure: { address: "0x401000", name: "fixture_main" },
|
||||
procedure: ghidraFunctionIdentity(),
|
||||
};
|
||||
case "procedure_assembly":
|
||||
return "0x401000: CALL 0x401020\n0x401005: RET";
|
||||
case "procedure_callees":
|
||||
case "procedure_callers":
|
||||
return [];
|
||||
case "procedure_info":
|
||||
return {
|
||||
name: "fixture_main",
|
||||
entrypoint: "0x401000",
|
||||
basicblock_count: 1,
|
||||
length: 6,
|
||||
signature: "int fixture_main(void)",
|
||||
locals: [],
|
||||
classification: ghidraFunctionClassification(),
|
||||
};
|
||||
case "procedure_pseudo_code":
|
||||
return "int fixture_main(void) { return 42; }";
|
||||
case "procedure_references":
|
||||
return {
|
||||
procedure: ghidraFunctionIdentity(),
|
||||
direction: input.direction ?? "outgoing",
|
||||
references: ghidraBounded([ghidraReferenceEdge()]),
|
||||
instructions_scanned: 2,
|
||||
instruction_scan_truncated: false,
|
||||
};
|
||||
case "xrefs":
|
||||
return ["0x401001"];
|
||||
case "analyze_function":
|
||||
return ghidraFunctionDossier(input.include_assembly === true);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -46,7 +46,7 @@ describe("Ghidra provider", () => {
|
||||
expect(ghidra.capabilities().map(({ operation }) => operation)).toEqual(
|
||||
GHIDRA_PROVIDER_TOOL_CONTRACTS.map(({ name }) => name),
|
||||
);
|
||||
expect(GHIDRA_PROVIDER_TOOL_CONTRACTS).toHaveLength(10);
|
||||
expect(GHIDRA_PROVIDER_TOOL_CONTRACTS).toHaveLength(18);
|
||||
expect(Object.isFrozen(ghidra.capabilities())).toBe(true);
|
||||
expect(ghidra.capabilities()).toEqual(
|
||||
expect.arrayContaining([
|
||||
@@ -64,6 +64,20 @@ describe("Ghidra provider", () => {
|
||||
timeoutMs: 10_000,
|
||||
},
|
||||
}),
|
||||
expect.objectContaining({
|
||||
operation: "analyze_function",
|
||||
pagination: "offset",
|
||||
limits: {
|
||||
maxResults: 500,
|
||||
maxPayloadBytes: 1024 * 1024,
|
||||
timeoutMs: 35_000,
|
||||
},
|
||||
limitations: expect.arrayContaining([
|
||||
expect.stringContaining(
|
||||
"unresolved targetless flows remain unknown",
|
||||
),
|
||||
]),
|
||||
}),
|
||||
]),
|
||||
);
|
||||
expect(ghidra.inspectAvailability()).toMatchObject({
|
||||
@@ -251,6 +265,45 @@ describe("Ghidra provider", () => {
|
||||
},
|
||||
);
|
||||
|
||||
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 },
|
||||
),
|
||||
),
|
||||
),
|
||||
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 }),
|
||||
},
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it("returns cancellation before profile work", async () => {
|
||||
const controller = new AbortController();
|
||||
controller.abort();
|
||||
@@ -267,7 +320,7 @@ describe("Ghidra provider", () => {
|
||||
|
||||
const sessionInfo = () => ({
|
||||
name: "REA Ghidra bridge" as const,
|
||||
bridge_version: 2 as const,
|
||||
bridge_version: 3 as const,
|
||||
run_id: "11111111-1111-4111-8111-111111111111",
|
||||
profile_digest: "a".repeat(64),
|
||||
provider: { id: "ghidra" as const, version: "12.1.2" },
|
||||
|
||||
@@ -8,6 +8,7 @@ import { parseConfig } from "../src/config.js";
|
||||
import { HopperProvider } from "../src/hopper/HopperProvider.js";
|
||||
import { GhidraProvider } from "../src/ghidra/GhidraProvider.js";
|
||||
import { GHIDRA_INVENTORY_OPERATIONS } from "../src/ghidra/GhidraInventoryValues.js";
|
||||
import { GHIDRA_FUNCTION_OPERATIONS } from "../src/ghidra/GhidraFunctionValues.js";
|
||||
import { silentLogger } from "../src/logger.js";
|
||||
|
||||
const sourceRoot = new URL("../src/", import.meta.url);
|
||||
@@ -38,7 +39,7 @@ describe("provider-neutral architecture", () => {
|
||||
expect(violations).toEqual([]);
|
||||
});
|
||||
|
||||
it("publishes only admitted immutable Ghidra inventory capabilities", () => {
|
||||
it("publishes only admitted immutable Ghidra read-only capabilities", () => {
|
||||
const config = parseConfig({});
|
||||
expect(config.ok).toBe(true);
|
||||
if (!config.ok) return;
|
||||
@@ -49,7 +50,7 @@ describe("provider-neutral architecture", () => {
|
||||
});
|
||||
const capabilities = provider.capabilities();
|
||||
expect(capabilities.map(({ operation }) => operation).sort()).toEqual(
|
||||
[...GHIDRA_INVENTORY_OPERATIONS].sort(),
|
||||
[...GHIDRA_INVENTORY_OPERATIONS, ...GHIDRA_FUNCTION_OPERATIONS].sort(),
|
||||
);
|
||||
expect(Object.isFrozen(capabilities)).toBe(true);
|
||||
for (const descriptor of capabilities) {
|
||||
|
||||
Reference in New Issue
Block a user