diff --git a/bridge/ghidra/ReaGhidraBridge.java b/bridge/ghidra/ReaGhidraBridge.java index 60792fa32..ef11ecec3 100644 --- a/bridge/ghidra/ReaGhidraBridge.java +++ b/bridge/ghidra/ReaGhidraBridge.java @@ -1581,33 +1581,35 @@ public final class ReaGhidraBridge extends HeadlessScript { } private Function resolveProcedure(String value) throws Exception { - Address address = tryParseAddress(value); - if (address != null) { - Function function = currentProgram.getFunctionManager().getFunctionAt(address); - if (function == null && address.isMemoryAddress()) { - function = currentProgram.getFunctionManager().getFunctionContaining(address); + // Explicit address syntax wins; an unprefixed identifier is first an + // exact symbol name, even when every character is a hexadecimal digit. + boolean explicitAddress = value.matches("(?i)^0x[0-9a-f]+$") || + value.matches("(?i)^(?:[a-z0-9._~-]|%[0-9a-f]{2})+:0x[0-9a-f]+$"); + if (!explicitAddress) { + List matches = new ArrayList<>(); + for (FunctionEntry entry : procedures()) { + monitor.checkCancelled(); + Function function = entry.function; + Symbol symbol = function.getSymbol(); + String qualified = symbol == null ? function.getName() : symbol.getName(true); + if (function.getName().equals(value) || qualified.equals(value)) { + matches.add(function); + } } - if (function == null) { - throw new RequestFailure("not_found", "No procedure exists at the requested address"); - } - return function; + if (matches.size() > 1) + throw new RequestFailure("ambiguous", "Ghidra procedure name is ambiguous: " + value); + if (matches.size() == 1) return matches.get(0); } - List matches = new ArrayList<>(); - for (FunctionEntry entry : procedures()) { - Function function = entry.function; - Symbol symbol = function.getSymbol(); - String qualified = symbol == null ? function.getName() : symbol.getName(true); - if (function.getName().equals(value) || qualified.equals(value)) { - matches.add(function); - } - } - if (matches.isEmpty()) { - throw new RequestFailure("not_found", "Unknown Ghidra procedure name"); - } - if (matches.size() != 1) { - throw new RequestFailure("ambiguous", "Ghidra procedure name is ambiguous"); - } - return matches.get(0); + // Retain legacy bare-hex address input only when no symbol matches. + Address address = explicitAddress ? parseReaAddress(value) : tryParseAddress(value); + if (address == null) + throw new RequestFailure("not_found", "Unknown Ghidra procedure name or address: " + value); + Function function = currentProgram.getFunctionManager().getFunctionAt(address); + if (function == null && address.isMemoryAddress()) + function = currentProgram.getFunctionManager().getFunctionContaining(address); + if (function == null) + throw new RequestFailure("not_found", "No procedure exists at the requested address: " + value); + return function; } private JsonObject nativeApiBoundary( @@ -2947,7 +2949,7 @@ public final class ReaGhidraBridge extends HeadlessScript { private Address parseReaAddress(String value) { Address address = tryParseAddress(value); if (address == null) { - throw new RequestFailure("invalid_request", "Unknown or invalid Ghidra address"); + throw new RequestFailure("invalid_request", "Unknown or invalid Ghidra address: " + value); } return address; } @@ -2956,12 +2958,12 @@ public final class ReaGhidraBridge extends HeadlessScript { try { String spaceName = null; String offset = value; - int separator = value.lastIndexOf(":0x"); + int separator = value.toLowerCase(Locale.ROOT).lastIndexOf(":0x"); if (separator >= 0) { spaceName = decodeAddressSpace(value.substring(0, separator)); offset = value.substring(separator + 3); } - else if (value.startsWith("0x")) { + else if (value.startsWith("0x") || value.startsWith("0X")) { offset = value.substring(2); } if (!offset.matches("[0-9A-Fa-f]+")) { @@ -3055,7 +3057,7 @@ public final class ReaGhidraBridge extends HeadlessScript { ); } catch (PatternSyntaxException exception) { - throw new RequestFailure("invalid_request", "Invalid regex pattern"); + throw new RequestFailure("invalid_request", "Invalid regex pattern " + expression + ": " + exception.getDescription() + " at index " + exception.getIndex()); } return value -> pattern.matcher(value).find(); } @@ -3114,7 +3116,7 @@ public final class ReaGhidraBridge extends HeadlessScript { private void requireDocument(JsonObject params) { String document = optionalString(params, "document"); if (document != null && !document.equals(currentProgram.getName())) { - throw new RequestFailure("not_found", "Unknown Ghidra Program identity"); + throw new RequestFailure("not_found", "Unknown Ghidra Program identity: " + document + "; active program: " + currentProgram.getName()); } } diff --git a/docs/installation.md b/docs/installation.md index 0c04129aa..8b37f96d8 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -411,7 +411,17 @@ home/cache/config/temp paths. REA passes `-readOnly`, `-deleteProject`, uses Ghidra's default analysis and resource settings, and loads its packaged Java bridge via `-scriptPath`; it never opens an existing user project. Linux and macOS use a current-user-only local bridge socket and descriptor. The -experimental Windows transport uses authenticated IPv4 loopback with a +project remains under the selected temporary directory. If its Unix socket +pathname would exceed the host's byte limit, REA allocates a separate mode-0700 +socket directory under `/tmp` and removes it on close, cancellation, or failure. +Diagnostics retain the actual endpoint and both owned directories. +On macOS, REA starts the inspected JVM directly using Ghidra's own LaunchSupport +configuration. Apple platform shell wrappers hide their environments from +ownership inspection, so retaining those wrappers would prevent verified +process-group cancellation during startup. +If ownership remains unverifiable, it reports the reason and retains the process +supervisor and private runtime instead of removing files beneath a live provider. +The experimental Windows transport uses authenticated IPv4 loopback with a private native-owned bearer descriptor and Job Object process ownership. Operations begin only after default auto-analysis completes. `open_binary` diff --git a/docs/native-investigation.md b/docs/native-investigation.md index 7371e1324..533c8c787 100644 --- a/docs/native-investigation.md +++ b/docs/native-investigation.md @@ -72,6 +72,14 @@ explicit limitation; architecture inventory locations remain available. Ghidra supplies three exact-object operations: +Ghidra accepts hexadecimal addresses with or without a `0x` prefix, in either +letter case, and explicit address-space coordinates such as `EXTERNAL:0x1`. +Results use canonical lowercase hexadecimal offsets. For a procedure identifier, +an explicit `0x` or address-space prefix selects an address; otherwise an exact +database symbol name takes precedence over a bare hexadecimal address. Thus a +function renamed to `dead` remains selectable by name. Use the names returned +by the inventory, including their namespaces and any platform symbol prefix. + ```bash rea inspect-native-instruction
--provider ghidra rea resolve-native-call-targets --provider ghidra diff --git a/docs/testing.md b/docs/testing.md index 52e9f42e3..d2ec27409 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -236,6 +236,15 @@ The host-native Ghidra lane also verifies native value tracing through the production CLI and a separate stdio MCP process. It compares complete dependency graphs, validates Evidence and upstream/workflow profiles, checks capability discovery, and closes the MCP session. No provider or transport is mocked. +It also validates every advertised input/output JSON Schema and the exercised +MCP outputs, probes address spelling and name/address ambiguity, and checks +direct versus targetless calls, byte-read completeness, invalid input diagnostics, +CLI/MCP parity, atomic annotation rollback, refreshed inventories, unchanged +executable bytes, and discarded edits after reopen. A deliberately long temporary +path exercises private Unix socket allocation and cleanup, including cancellation +after a real headless process launches. Malformed annotation +readback remains a separate SDK/provider integration case; success from a real +provider cannot establish rejection of a contradictory provider response. The Linux switch lane checks dense, sparse-with-holes, shared-body, nonzero, negative, and nonexact JSON integer labels plus a comparison-only control. diff --git a/scripts/lib/native-value-e2e.mjs b/scripts/lib/native-value-e2e.mjs index ac43cd8f9..10e226908 100644 --- a/scripts/lib/native-value-e2e.mjs +++ b/scripts/lib/native-value-e2e.mjs @@ -1,5 +1,8 @@ import assert from "node:assert/strict"; import { execFile } from "node:child_process"; +import { mkdir, mkdtemp, readdir, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; import { promisify } from "node:util"; import { fileURLToPath } from "node:url"; import { Client } from "@modelcontextprotocol/client"; @@ -8,6 +11,7 @@ import { StdioClientTransport } from "@modelcontextprotocol/client/stdio"; import { parseEvidence } from "../../dist/domain/evidence.js"; import { analysisProfileSchema } from "../../dist/domain/analysisProfile.js"; import { nativeValueTraceSchema } from "../../dist/domain/native/nativeValueTrace.js"; +import { verifyGhidraBoundaries } from "./real-ghidra-boundaries.mjs"; const defaultEntrypoint = fileURLToPath(new URL("../rea.mjs", import.meta.url)); const environment = () => ({ @@ -72,6 +76,33 @@ export async function verifyNativeValueE2e( procedure, globalAddress, { entrypoint = defaultEntrypoint } = {}, +) { + const workspace = await mkdtemp(join(tmpdir(), "rea-native-values-e2e-")); + const runtime = join( + workspace, + `runtime${process.platform === "darwin" ? " with spaces" : ""}-${"x".repeat(100)}`, + ); + await mkdir(runtime); + const env = { ...environment(), TMPDIR: runtime }; + try { + return await verifyNativeValueAdapters( + target, + procedure, + globalAddress, + entrypoint, + env, + ); + } finally { + await rm(workspace, { recursive: true, force: true }); + } +} + +async function verifyNativeValueAdapters( + target, + procedure, + globalAddress, + entrypoint, + env, ) { const { stdout } = await promisify(execFile)( process.execPath, @@ -90,7 +121,7 @@ export async function verifyNativeValueE2e( "5000", "--json", ], - { env: environment(), timeout: 240000, maxBuffer: 72 * 1024 * 1024 }, + { env, timeout: 240000, maxBuffer: 72 * 1024 * 1024 }, ); const evidence = parseEvidence(JSON.parse(stdout)); assert.equal(evidence.operation, "trace_native_values"); @@ -114,16 +145,17 @@ export async function verifyNativeValueE2e( const transport = new StdioClientTransport({ command: process.execPath, args: [entrypoint, "mcp"], - env: environment(), + env, stderr: "pipe", }); const client = new Client({ name: "native-values-real-e2e", version: "1" }); + let boundaries; try { await client.connect(transport); const opened = await client.callTool( { name: "open_binary", - arguments: { path: target.path, provider: "ghidra" }, + arguments: { path: target.path, provider_id: "ghidra" }, }, { timeout: 180000 }, ); @@ -168,14 +200,11 @@ export async function verifyNativeValueE2e( analyzed.structuredContent?.evidence, ); assert.equal(functionEvidence.operation, "analyze_function"); - assert.equal(functionEvidence.provider.id, "rea-workflow"); + assert.equal(functionEvidence.provider.id, "ghidra"); const functionProfile = analysisProfileSchema.parse( functionEvidence.analysis_profile, ); - assert.deepEqual( - functionProfile.parameters.upstream_analysis_profile, - upstreamProfile, - ); + assert.deepEqual(functionProfile, upstreamProfile); assert.deepEqual( functionEvidence.normalized_result, analyzed.structuredContent?.result, @@ -219,6 +248,12 @@ export async function verifyNativeValueE2e( evidence, ); } + boundaries = await verifyGhidraBoundaries(client, { + target, + procedure, + entrypoint, + env, + }); const closed = await client.callTool({ name: "close_binary", arguments: {}, @@ -229,6 +264,13 @@ export async function verifyNativeValueE2e( arguments: {}, }); assert.equal(status.structuredContent?.result?.open, false); + assert.deepEqual( + (await readdir(env.TMPDIR)).filter((name) => + name.startsWith("rea-ghidra-"), + ), + [], + "Ghidra left runtime files after close", + ); } finally { await client.close(); await transport.close(); @@ -239,6 +281,7 @@ export async function verifyNativeValueE2e( stdio_mcp: true, inline_evidence: true, direct_function_comparison: true, + boundaries, nodes: cliGraph.total_nodes, edges: cliGraph.total_edges, decompilations: cliGraph.decompilations, diff --git a/scripts/lib/real-ghidra-boundaries.mjs b/scripts/lib/real-ghidra-boundaries.mjs new file mode 100644 index 000000000..309eb1a24 --- /dev/null +++ b/scripts/lib/real-ghidra-boundaries.mjs @@ -0,0 +1,505 @@ +import assert from "node:assert/strict"; +import { execFile } from "node:child_process"; +import { createHash, randomUUID } from "node:crypto"; +import { access, readFile, readdir, stat } from "node:fs/promises"; +import { dirname, join } from "node:path"; +import { setTimeout as delay } from "node:timers/promises"; +import { promisify } from "node:util"; +import Ajv from "ajv/dist/2020.js"; +import addFormats from "ajv-formats"; +import { mcpTextValue, requireMcpResult } from "./mcp-verifier-results.mjs"; + +/** Probe real Ghidra location, annotation and error contracts through public adapters. */ +export async function verifyGhidraBoundaries( + client, + { target, procedure, entrypoint, env }, +) { + const options = { timeout: 180000 }; + const catalog = await client.listTools(); + const ajv = new Ajv({ strict: false }); + addFormats(ajv); + const validators = new Map(); + for (const tool of catalog.tools) { + for (const key of ["inputSchema", "outputSchema"]) + assert.ok( + ajv.validateSchema(tool[key]), + `${tool.name} ${key}: ${JSON.stringify(ajv.errors)}`, + ); + validators.set(tool.name, ajv.compile(tool.outputSchema)); + } + let successfulCalls = 0; + let rejectedCalls = 0; + const call = async (name, args = {}) => { + const reply = await client.callTool({ name, arguments: args }, options); + const result = requireMcpResult(reply, name); + const validate = validators.get(name); + assert.ok(validate, `${name} missing from catalog`); + assert.ok( + validate(reply.structuredContent), + `${name}: ${JSON.stringify(validate.errors)}`, + ); + assert.deepEqual(reply.structuredContent, JSON.parse(mcpTextValue(reply))); + successfulCalls++; + return result; + }; + const invalid = async (name, args, diagnostic) => { + const reply = await client.callTool({ name, arguments: args }, options); + assert.equal( + reply.isError, + true, + `${name} accepted ${JSON.stringify(args)}`, + ); + if (diagnostic !== undefined) { + const error = reply.structuredContent?.error; + assert.equal(error?.code, "invalid_request"); + assert.equal(error?.details?.operation, name); + assert.match(JSON.stringify(error.details.issues), diagnostic); + } + rejectedCalls++; + }; + const cli = async (command, value, flags = []) => { + const { stdout } = await promisify(execFile)( + process.execPath, + [ + entrypoint, + command, + target.path, + value, + "--provider", + "ghidra", + "--json", + ...flags, + ], + { env, timeout: 240000, maxBuffer: 72 * 1024 * 1024 }, + ); + return JSON.parse(stdout).normalized_result; + }; + const original = await call("analyze_function", { procedure }); + const roots = (await readdir(env.TMPDIR)).filter((name) => + name.startsWith("rea-ghidra-"), + ); + assert.equal(roots.length, 1, "Expected one owned Ghidra runtime"); + const runtimeRoot = join(env.TMPDIR, roots[0]); + const { endpoint_path: socketPath } = JSON.parse( + await readFile(join(runtimeRoot, "ownership.json"), "utf8"), + ); + const socketRoot = dirname(socketPath); + assert.ok( + Buffer.byteLength(join(runtimeRoot, "bridge.sock"), "utf8") > 107, + "Fixture must exceed Unix socket path capacity", + ); + assert.ok(Buffer.byteLength(socketPath, "utf8") <= 103); + assert.notEqual(socketRoot, runtimeRoot); + assert.equal((await stat(socketRoot)).mode & 0o777, 0o700); + const address = original.procedure.address; + const name = original.procedure.name; + const baseline = await call("inspect_native_instruction", { address }); + assert.equal(baseline.status, "decoded"); + const bytes = await call("read_bytes", { address, length: baseline.length }); + assert.equal(bytes.bytes_hex, baseline.bytes); + const largeRead = await call("read_bytes", { + address, + length: Number.MAX_SAFE_INTEGER, + }); + assert.equal(largeRead.requested_bytes, Number.MAX_SAFE_INTEGER); + assert.equal(largeRead.complete, false); + assert.ok(largeRead.returned_bytes >= baseline.length); + assert.equal(largeRead.bytes_hex.length, largeRead.returned_bytes * 2); + for (const spelling of [ + address.toUpperCase(), + address.slice(2).toUpperCase(), + `ram:${address.toUpperCase()}`, + ]) { + assert.deepEqual( + await call("inspect_native_instruction", { address: spelling }), + baseline, + ); + assert.deepEqual( + await call("read_bytes", { address: spelling, length: baseline.length }), + bytes, + ); + assert.equal(await call("address_name", { address: spelling }), name); + assert.equal( + await call("procedure_address", { procedure: spelling }), + address, + ); + assert.equal( + (await call("resolve_containing_procedure", { address: spelling })) + .procedure.address, + address, + ); + } + assert.deepEqual( + await cli("inspect-native-instruction", address.toUpperCase()), + baseline, + ); + const interior = `0x${(BigInt(address) + 1n).toString(16)}`; + assert.equal( + (await call("inspect_native_instruction", { address: interior })).status, + "not-instruction-boundary", + ); + assert.equal( + (await call("inspect_native_instruction", { address: "0x0" })).status, + "outside-memory", + ); + assert.equal( + (await call("resolve_native_call_targets", { address })).status, + "not-call", + ); + const directEdge = original.outgoing_references.find( + (edge) => edge.kind.call && !edge.kind.computed, + ); + assert.ok(directEdge, "Source fixture lacks a direct call"); + const direct = await call("resolve_native_call_targets", { + address: directEdge.source_address, + }); + assert.equal(direct.status, "direct"); + assert.ok( + direct.targets.some( + (candidate) => + candidate.address === directEdge.target_address && + candidate.status === "direct", + ), + ); + const indirectProcedure = (await call("list_procedures")).find((item) => + item.value.endsWith("rea_ghidra_inventory_indirect"), + ); + assert.ok(indirectProcedure); + const references = await call("procedure_references", { + procedure: indirectProcedure.address, + }); + assert.ok( + references.unresolved_calls.length > 0, + "Targetless calls must remain visible", + ); + for (const site of references.unresolved_calls) { + const unresolved = await call("resolve_native_call_targets", { + address: site.address, + }); + assert.equal(unresolved.status, "unresolved"); + assert.deepEqual(unresolved.targets, []); + assert.ok(unresolved.limitations.length > 0); + } + const strings = await call("list_strings"); + assert.ok(strings.length > 0); + assert.equal( + (await call("inspect_native_instruction", { address: strings[0].address })) + .status, + "data", + ); + + await invalid( + "inspect_native_instruction", + { address: "not-an-address" }, + /hexadecimal/u, + ); + await invalid( + "inspect_native_instruction", + { address: `missing:${address}` }, + /missing:0x/u, + ); + await invalid( + "address_name", + { address: `0x${(BigInt(address) + 2n ** 64n).toString(16)}` }, + /invalid Ghidra address/u, + ); + await invalid( + "procedure_address", + { procedure: "rea_missing_procedure" }, + /rea_missing_procedure/u, + ); + await invalid( + "search_procedures", + { pattern: "[", mode: "regex" }, + /Invalid regex pattern.*index/u, + ); + await invalid( + "list_procedures", + { document: "rea_missing_program" }, + /rea_missing_program.*active program/u, + ); + for (const changes of [ + {}, + { name: "" }, + { comment: null }, + { name: "entry", approve: true }, + ]) + await invalid("annotate_native_function", { + procedure: address, + ...changes, + }); + + let cliError; + try { + await cli("search", "[", ["--kind", "procedures", "--mode", "regex"]); + } catch (error) { + assert.equal(error.code, 1); + cliError = JSON.parse(error.stdout); + } + assert.equal(cliError?.code, "invalid_request"); + assert.equal(cliError?.details?.operation, "search_procedures"); + assert.match( + JSON.stringify(cliError?.details?.issues), + /Invalid regex pattern.*index/u, + ); + + // Prime both inventories before editing so stale names cannot hide in caches. + await call("list_names"); + await call("list_procedures"); + const changes = { + procedure: address, + name: "dead", + comment: "Regular\n註記", + inline_comment: "Inline\n註記", + }; + const updated = await call("annotate_native_function", changes); + assert.deepEqual(updated.annotations, { + address, + name: changes.name, + comment: changes.comment, + inline_comment: changes.inline_comment, + }); + assert.deepEqual(updated.effects, { + scope: "session-analysis-database", + source_bytes_modified: false, + persists_after_close: false, + }); + assert.equal(updated.dossier.procedure.name, changes.name); + assert.equal( + await call("procedure_address", { procedure: changes.name }), + address, + ); + assert.equal( + (await call("procedure_info", { procedure: changes.name })).entrypoint, + address, + ); + assert.equal( + (await call("read_function_instructions", { procedure: changes.name })) + .procedure.address, + address, + ); + assert.equal( + (await call("analyze_function", { procedure: changes.name })).procedure + .name, + changes.name, + ); + assert.equal(await call("address_name", { address }), changes.name); + for (const inventory of ["list_names", "list_procedures"]) + assert.ok( + (await call(inventory)).some( + (item) => item.address === address && item.value === changes.name, + ), + ); + assert.ok( + ( + await call("search_procedures", { pattern: "dead", case_sensitive: true }) + ).some((item) => item.address === address), + ); + + await invalid( + "annotate_native_function", + { + procedure: changes.name, + name: "invalid name\n", + comment: "MUST ROLL BACK", + inline_comment: "MUST ROLL BACK", + }, + /Invalid function name/u, + ); + const retained = await call("annotate_native_function", { + procedure: changes.name, + name: changes.name, + }); + assert.deepEqual(retained.annotations, updated.annotations); + const cleared = await call("annotate_native_function", { + procedure: changes.name, + comment: "", + inline_comment: "", + }); + assert.equal(cleared.annotations.comment, null); + assert.equal(cleared.annotations.inline_comment, null); + assert.equal(cleared.annotations.name, changes.name); + assert.deepEqual( + await call("read_bytes", { address, length: baseline.length }), + bytes, + ); + assert.equal( + createHash("sha256") + .update(await readFile(target.path)) + .digest("hex"), + target.sha256, + ); + const cliUpdated = await cli("annotate-native-function", name, [ + "--name", + changes.name, + "--comment", + changes.comment, + "--inline-comment", + changes.inline_comment, + ]); + assert.deepEqual(cliUpdated.annotations, updated.annotations); + assert.deepEqual(cliUpdated.effects, updated.effects); + await call("annotate_native_function", { + procedure: address, + name: "0xordinary", + }); + assert.equal( + await call("procedure_address", { procedure: "0xordinary" }), + address, + ); + assert.equal(await call("address_name", { address }), "0xordinary"); + await call("close_binary"); + await assert.rejects(access(socketRoot), { code: "ENOENT" }); + await assert.rejects(access(runtimeRoot), { code: "ENOENT" }); + await call("open_binary", { path: target.path, provider_id: "ghidra" }); + assert.equal(await call("procedure_address", { procedure: name }), address); + assert.equal(await call("address_name", { address }), name); + assert.deepEqual( + (await call("analyze_function", { procedure: address })).comments, + original.comments, + ); + assert.equal( + createHash("sha256") + .update(await readFile(target.path)) + .digest("hex"), + target.sha256, + ); + await verifyStartupCancellation(client, call, target, env, options); + return { + mocked: false, + catalog_tools: catalog.tools.length, + successful_calls: successfulCalls, + rejected_calls: rejectedCalls, + cli_mcp_parity: true, + mutation_rollback: true, + source_immutable: true, + reopen_discards_edits: true, + long_tmpdir_private_socket_cleanup: true, + real_startup_cancellation_cleanup: true, + }; +} + +async function verifyStartupCancellation(client, call, target, env, options) { + await call("close_binary"); + await call("open_binary", { path: target.path, provider_id: "ghidra" }); + // The composite provider selects the target lazily. Use a fresh search input + // so persisted immutable snapshots cannot bypass actual provider startup. + const request = { + name: "search_procedures", + arguments: { pattern: `startup-cancellation-${randomUUID()}` }, + }; + const controller = new AbortController(); + let settled = false; + let outcome; + const pending = client + .callTool(request, { ...options, signal: controller.signal }) + .then( + (reply) => { + settled = true; + outcome = reply; + return { reply }; + }, + (error) => { + settled = true; + outcome = String(error); + return { error }; + }, + ); + const deadline = Date.now() + 30000; + let launched; + try { + while (Date.now() < deadline && !settled) { + const roots = (await readdir(env.TMPDIR)).filter((name) => + name.startsWith("rea-ghidra-"), + ); + if (roots.length === 1) { + const root = join(env.TMPDIR, roots[0]); + try { + const ownership = JSON.parse( + await readFile(join(root, "ownership.json"), "utf8"), + ); + const endpointPath = ownership.endpoint_path; + // Observe the JVM inside the owned process group before the bridge + // publishes its socket. A log file can appear after analysis finishes. + const { stdout } = await promisify(execFile)("ps", [ + "-axo", + "pid=,pgid=,comm=", + ]); + const javaProcess = stdout.split("\n").find((line) => { + const fields = line.trim().split(/\s+/u); + return ( + Number(fields[1]) === ownership.process_group_id && + /(?:^|\/)java$/u.test(fields.slice(2).join(" ")) + ); + }); + if (javaProcess === undefined) { + await delay(25); + continue; + } + const javaPid = Number(javaProcess.trim().split(/\s+/u)[0]); + await assert.rejects(access(endpointPath), { code: "ENOENT" }); + process.kill(ownership.pid, 0); + launched = { + root, + socketRoot: dirname(endpointPath), + pid: ownership.pid, + javaPid, + }; + break; + } catch (error) { + if (error.code !== "ENOENT") throw error; + } + } + await delay(25); + } + assert.ok( + launched, + `No real headless process was observed before cancellation: ${JSON.stringify(outcome)}`, + ); + assert.equal( + settled, + false, + "Cancellation must interrupt pending provider work", + ); + } finally { + controller.abort(); + await pending; + } + const cleanupDeadline = Date.now() + 30000; + while (Date.now() < cleanupDeadline) { + const processGone = [launched.pid, launched.javaPid].every((pid) => { + try { + process.kill(pid, 0); + return false; + } catch (error) { + if (error.code === "ESRCH") return true; + throw error; + } + }); + try { + await access(launched.root); + } catch (error) { + if (error.code === "ENOENT" && processGone) break; + if (error.code === "ENOENT") { + await delay(25); + continue; + } + throw error; + } + await delay(25); + } + await assert.rejects(access(launched.root), { code: "ENOENT" }); + await assert.rejects(access(launched.socketRoot), { code: "ENOENT" }); + assert.throws(() => process.kill(launched.pid, 0), { code: "ESRCH" }); + assert.throws(() => process.kill(launched.javaPid, 0), { code: "ESRCH" }); + assert.equal( + (await call("binary_session")).open, + true, + "Cancellation must preserve the selected target", + ); + assert.deepEqual( + await call(request.name, request.arguments), + [], + "A cancelled startup must allow a fresh provider query", + ); +} diff --git a/scripts/verify-real-ghidra-assertions.mjs b/scripts/verify-real-ghidra-assertions.mjs index 6a143859f..610534c05 100644 --- a/scripts/verify-real-ghidra-assertions.mjs +++ b/scripts/verify-real-ghidra-assertions.mjs @@ -255,7 +255,7 @@ export async function assertSession( session.provider.version !== SUPPORTED_GHIDRA_VERSION || session.profile_digest !== expectedDigest || session.target.sha256 !== expectedTargetSha256 || - session.read_only !== true || + session.read_only !== false || session.analysis_complete !== true || session.analysis_timed_out !== false || session.capabilities.length !== GHIDRA_SESSION_CAPABILITIES.length || @@ -279,7 +279,12 @@ export function assertRuntimeCoordinates(coordinates) { } export async function assertCleanup(coordinates) { - for (const name of ["runtime_root", "endpoint_path", "project_root"]) { + for (const name of [ + "runtime_root", + "endpoint_path", + "project_root", + "socket_root", + ]) { const path = coordinates[name]; if (typeof path === "string" && (await exists(path))) throw new Error(`Ghidra cleanup left ${name}: ${path}`); diff --git a/scripts/verify-real-ghidra-dos.mjs b/scripts/verify-real-ghidra-dos.mjs index 70319fdcd..1a786992a 100644 --- a/scripts/verify-real-ghidra-dos.mjs +++ b/scripts/verify-real-ghidra-dos.mjs @@ -99,7 +99,7 @@ try { }); const target = await call("open_binary", { path: targetPath, - provider: "ghidra", + provider_id: "ghidra", }); opened = true; assert.equal(target.format, "dos-mz"); @@ -562,9 +562,8 @@ async function evidenceCall(name, arguments_) { normalized_result: result.structuredContent?.result, }); assert.equal(evidence.subject.digest.sha256, sha256); - assert.equal(evidence.provider.id, "rea-workflow"); - assert.equal(evidence.analysis_profile.provider.id, "rea-workflow"); - assertProfile(evidence.analysis_profile.parameters.upstream_analysis_profile); + assert.equal(evidence.provider.id, "ghidra"); + assertProfile(evidence.analysis_profile); return evidence; } async function cliEvidence(command, procedure, options = []) { diff --git a/scripts/verify-real-ghidra-switch.mjs b/scripts/verify-real-ghidra-switch.mjs index 1c9c03b19..f3e6f0c5c 100644 --- a/scripts/verify-real-ghidra-switch.mjs +++ b/scripts/verify-real-ghidra-switch.mjs @@ -214,7 +214,7 @@ async function verifyTarget(path, sha256, fixtures, variant) { }); const target = await call(client, "open_binary", { path, - provider: "ghidra", + provider_id: "ghidra", }); opened = true; assert.equal(target.sha256, sha256); diff --git a/src/ghidra/GhidraAnalysisProfile.ts b/src/ghidra/GhidraAnalysisProfile.ts index f112b1561..9e1f550df 100644 --- a/src/ghidra/GhidraAnalysisProfile.ts +++ b/src/ghidra/GhidraAnalysisProfile.ts @@ -42,6 +42,11 @@ export const resolveGhidraAnalysisProfile = ( annotation_policy: "atomic-function-entry-metadata-v1", load_image_observations: "source-mappings-entry-context-v2", function_body_evidence: "complete-inclusive-ranges-v1", + location_resolution: "explicit-address-exact-name-first-v2", + process_launch: + installation.platform === "darwin" + ? "inspected-jvm-launch-support-v1" + : "official-headless-script-v1", ...(dos ? { load_image_evidence: dosCom diff --git a/src/ghidra/GhidraAnnotations.test.ts b/src/ghidra/GhidraAnnotations.test.ts deleted file mode 100644 index ee7745f8b..000000000 --- a/src/ghidra/GhidraAnnotations.test.ts +++ /dev/null @@ -1,110 +0,0 @@ -import { functionDossierSchema } from "../domain/hopperValues.js"; -import { describe, expect, it } from "vitest"; -import { nativeFunctionAnnotationsInputSchema } from "../domain/native/nativeFunctionAnnotations.js"; -import { ghidraFunctionDossier } from "../domain/ghidraValues.fixture.js"; -import { - parseGhidraFunctionInput, - parseGhidraFunctionResult, -} from "./GhidraFunctionValues.js"; -import { - CAPABILITIES, - windowsP0Capabilities, -} from "./GhidraProviderCapabilities.js"; -import { HOPPER_OPERATIONS } from "../hopper/HopperProvider.js"; - -const result = () => { - const dossier = functionDossierSchema.parse(ghidraFunctionDossier()); - return { - annotations: { - address: dossier.procedure.address, - name: dossier.procedure.name, - comment: null, - inline_comment: "Finding", - }, - dossier, - effects: { - scope: "session-analysis-database", - source_bytes_modified: false, - persists_after_close: false, - }, - }; -}; - -describe("Ghidra function annotations", () => { - it("requires an explicit function and at least one change without approval flags", () => { - for (const input of [ - {}, - { procedure: "main" }, - { procedure: "", name: "entry" }, - { procedure: "main", name: "" }, - { procedure: "main", comment: null }, - { procedure: "main", name: "entry", approve: true }, - ]) - expect( - nativeFunctionAnnotationsInputSchema.safeParse(input).success, - ).toBe(false); - expect( - parseGhidraFunctionInput("annotate_native_function", { - procedure: "0x10100", - comment: "", - }), - ).toEqual({ ok: true, value: { procedure: "0x10100", comment: "" } }); - }); - - it("preserves multiline Unicode text and omitted fields", () => { - const input = { procedure: "entry", inline_comment: "Line one\n註記" }; - expect(parseGhidraFunctionInput("annotate_native_function", input)).toEqual( - { ok: true, value: input }, - ); - }); - - it("validates readback identity, exact effects and the complete Ghidra dossier", () => { - const value = result(); - expect( - parseGhidraFunctionResult("annotate_native_function", value).ok, - ).toBe(true); - for (const malformed of [ - { ...value, annotations: { ...value.annotations, name: "different" } }, - { ...value, annotations: { ...value.annotations, address: "0x9999" } }, - { ...value, effects: { ...value.effects, source_bytes_modified: true } }, - { ...value, effects: { ...value.effects, persists_after_close: true } }, - { ...value, dossier: { ...value.dossier, native_value_flow: null } }, - ]) - expect( - parseGhidraFunctionResult("annotate_native_function", malformed).ok, - ).toBe(false); - }); - - it("preserves qualified names in readback and the refreshed dossier", () => { - const value = result(); - const name = "namespace::recovered_routine"; - expect( - parseGhidraFunctionResult("annotate_native_function", { - ...value, - annotations: { ...value.annotations, name }, - dossier: { - ...value.dossier, - procedure: { ...value.dossier.procedure, name }, - }, - }).ok, - ).toBe(true); - }); - - it("declares mutation only for the admitted operation and keeps Windows and Hopper unavailable", () => { - expect( - CAPABILITIES.find((c) => c.operation === "annotate_native_function"), - ).toMatchObject({ - available: true, - effects: { mutatesArtifact: true, mayShowUi: false }, - }); - expect( - CAPABILITIES.find((c) => c.operation === "analyze_function"), - ).toMatchObject({ effects: { mutatesArtifact: false } }); - expect( - windowsP0Capabilities().find( - (c) => c.operation === "annotate_native_function", - ), - ).toMatchObject({ available: false }); - expect(HOPPER_OPERATIONS).not.toContain("annotate_native_function"); - }); -}); diff --git a/src/ghidra/GhidraClient.ts b/src/ghidra/GhidraClient.ts index 9fa280667..4930795ad 100644 --- a/src/ghidra/GhidraClient.ts +++ b/src/ghidra/GhidraClient.ts @@ -1,7 +1,6 @@ import { randomBytes, randomUUID } from "node:crypto"; import type { Socket } from "node:net"; import { tmpdir } from "node:os"; -import { join } from "node:path"; import type { JsonValue } from "../domain/jsonValue.js"; import { err, ok, type Result } from "../domain/result.js"; @@ -40,7 +39,10 @@ import { import { createGhidraTargetSnapshot } from "./GhidraTargetSnapshot.js"; import { readFile } from "node:fs/promises"; import { connectGhidraSocket } from "./GhidraSocketConnection.js"; -import type { GhidraEndpoint } from "./GhidraTransport.js"; +import { + createGhidraEndpoint, + type GhidraEndpoint, +} from "./GhidraTransport.js"; import { GhidraWire } from "./GhidraClientWire.js"; import { completeGhidraStartupHandshake } from "./GhidraClientStartup.js"; @@ -75,6 +77,8 @@ export class GhidraClient { #launch: GhidraLaunch | undefined; #process: ProviderProcessSupervisor | undefined; #runtimeRoot: PrivateRuntimeRoot | undefined; + #socketRoot: PrivateRuntimeRoot | undefined; + #endpointPath: string | undefined; #snapshotPath: string | undefined; #targetAdmission: JsonValue | undefined; #token: string | undefined; @@ -145,7 +149,13 @@ export class GhidraClient { start(signal?: AbortSignal): Promise { if (this.#closePromise !== undefined) return this.#closePromise.then(() => this.start(signal)); - if (this.#startPromise !== undefined) return this.#startPromise; + if (this.#startPromise !== undefined) { + if (this.#startupController?.signal.aborted && !signal?.aborted) + return this.#startPromise.then((result) => + result.ok ? result : this.start(signal), + ); + return this.#startPromise; + } const controller = new AbortController(); const onAbort = (): void => controller.abort(signal?.reason); if (signal?.aborted === true) onAbort(); @@ -265,12 +275,16 @@ export class GhidraClient { return err(this.#failure("cancelled", "Ghidra startup was cancelled")); if (this.#socket !== undefined || this.#runtimeRoot !== undefined) return err(this.#failure("protocol", "Ghidra client is already started")); + this.#processSnapshot = undefined; const deadline = new ProviderStartupDeadline( this.#options.startupTimeoutMs, signal, ); try { return await this.#startWithin(deadline); + } catch (cause: unknown) { + if (cause instanceof GhidraSessionError) return err(cause); + throw cause; } finally { deadline.dispose(); } @@ -291,15 +305,25 @@ export class GhidraClient { ); } if (deadline.signal.aborted) return this.#startupInterrupted(deadline); - const endpoint: GhidraEndpoint = { - transport: this.#options.transport, - path: join( + let endpoint: GhidraEndpoint; + try { + const allocated = await createGhidraEndpoint( this.#runtimeRoot.path, - this.#options.transport === "unix-socket" - ? "bridge.sock" - : "bridge-endpoint.json", - ), - }; + this.#options.transport, + this.#options.platform, + ); + endpoint = allocated.endpoint; + this.#socketRoot = allocated.socketRoot; + this.#endpointPath = endpoint.path; + } catch (cause: unknown) { + const failure = this.#failure( + "start", + "Ghidra private endpoint allocation failed", + cause, + ); + await this.#cleanup(); + return err(failure); + } try { const snapshot = await createGhidraTargetSnapshot( this.#options.targetPath, @@ -386,7 +410,7 @@ export class GhidraClient { deadline, failure: this.#failure, isClosed: () => this.#closing, - processExited: () => this.#processSnapshot?.exitCode !== undefined, + processExited: () => this.#process?.snapshot().exitCode !== undefined, startupTimeoutMs: this.#options.startupTimeoutMs, handlers: { data: this.#onSocketData, @@ -498,20 +522,28 @@ export class GhidraClient { { reason: stopped.reason }, "Ghidra process cleanup failed closed", ); - if (forceStop) - forcedStopFailure = this.#failure( - "process", - `Ghidra process cleanup after cancellation was incomplete: ${stopped.reason}`, - ); + // Keep the supervisor and private files available for a later close. + // A still-live JVM can recreate files if its runtime is removed here. + throw this.#failure( + "process", + `Ghidra process cleanup was incomplete: ${stopped.reason}`, + ); } } this.#lastDiagnostics = this.#diagnostics(); this.#process = undefined; this.#launch = undefined; const runtimeRoot = this.#runtimeRoot; + const socketRoot = this.#socketRoot; this.#runtimeRoot = undefined; + this.#socketRoot = undefined; try { - await runtimeRoot?.close(); + const removed = await Promise.allSettled([ + runtimeRoot?.close(), + socketRoot?.close(), + ]); + const failed = removed.find((result) => result.status === "rejected"); + if (failed?.status === "rejected") throw failed.reason; } catch (cause: unknown) { if (forceStop) forcedStopFailure ??= this.#failure( @@ -522,6 +554,7 @@ export class GhidraClient { else throw cause; } this.#snapshotPath = undefined; + this.#endpointPath = undefined; this.#token = undefined; this.#runId = undefined; this.#responseBuffer.reset(); @@ -604,6 +637,12 @@ export class GhidraClient { ...(this.#runtimeRoot === undefined ? {} : { runtimeRoot: this.#runtimeRoot.path }), + ...(this.#socketRoot === undefined + ? {} + : { socketRoot: this.#socketRoot.path }), + ...(this.#endpointPath === undefined + ? {} + : { endpointPath: this.#endpointPath }), ...(this.#launch === undefined ? {} : { launch: this.#launch }), ...(snapshot === undefined ? {} : { snapshot }), ...(this.#token === undefined ? {} : { token: this.#token }), diff --git a/src/ghidra/GhidraDiagnostics.ts b/src/ghidra/GhidraDiagnostics.ts index 059738ceb..444dac5d2 100644 --- a/src/ghidra/GhidraDiagnostics.ts +++ b/src/ghidra/GhidraDiagnostics.ts @@ -1,5 +1,3 @@ -import { join } from "node:path"; - import type { JsonValue } from "../domain/jsonValue.js"; import type { ProviderProcessSnapshot } from "../process/ProviderProcess.js"; import type { GhidraLaunch } from "./GhidraLauncher.js"; @@ -15,6 +13,8 @@ export interface GhidraDiagnosticsOptions { readonly profileDigest: string; readonly runId?: string; readonly runtimeRoot?: string; + readonly socketRoot?: string; + readonly endpointPath?: string; readonly launch?: GhidraLaunch; readonly snapshot?: ProviderProcessSnapshot; readonly token?: string; @@ -47,15 +47,13 @@ export const createGhidraDiagnostics = ( ...(options.runId === undefined ? {} : { run_id: options.runId }), ...(options.runtimeRoot === undefined ? {} - : { - runtime_root: options.runtimeRoot, - endpoint_path: join( - options.runtimeRoot, - options.transport === "unix-socket" - ? "bridge.sock" - : "bridge-endpoint.json", - ), - }), + : { runtime_root: options.runtimeRoot }), + ...(options.socketRoot === undefined + ? {} + : { socket_root: options.socketRoot }), + ...(options.endpointPath === undefined + ? {} + : { endpoint_path: options.endpointPath }), ...(options.launch === undefined ? {} : { diff --git a/src/ghidra/GhidraFunctionValues.ts b/src/ghidra/GhidraFunctionValues.ts index cfd1aaf69..e1636cdf6 100644 --- a/src/ghidra/GhidraFunctionValues.ts +++ b/src/ghidra/GhidraFunctionValues.ts @@ -10,7 +10,7 @@ import { } from "../domain/native/nativeInstruction.js"; import { - AnalysisInputError, + type AnalysisInputError, AnalysisOutputError, } from "../domain/analysisErrorCore.js"; import { @@ -27,8 +27,10 @@ import { import { nativeApiBoundarySchema } from "../domain/native/nativeApiBoundary.js"; import { nativeValueFlowSchema } from "../domain/native/nativeValueFlow.js"; import { err, ok, type Result } from "../domain/result.js"; +import { analysisInputErrorFromIssues } from "../domain/inputIssueProjection.js"; import { ghidraIdentifierSchema, + ghidraInputAddressSchema, ghidraCanonicalAddressSchema, ghidraFunctionClassificationSchema as classification, ghidraFunctionBodySchema as ghidraFunctionBody, @@ -73,7 +75,7 @@ const inputSchemas = { .object({ document, type: z.string().min(1).nullable().default(null), - address: ghidraCanonicalAddressSchema.nullable().default(null), + address: ghidraInputAddressSchema.nullable().default(null), }) .strict() .refine( @@ -81,10 +83,10 @@ const inputSchemas = { "Supply exactly one of type or address", ), inspect_native_instruction: z - .object({ document, address: ghidraCanonicalAddressSchema }) + .object({ document, address: ghidraInputAddressSchema }) .strict(), resolve_native_call_targets: z - .object({ document, address: ghidraCanonicalAddressSchema }) + .object({ document, address: ghidraInputAddressSchema }) .strict(), analyze_function: z.object({ procedure }).strict(), procedure_assembly: z.object(directProcedure).strict(), @@ -99,7 +101,7 @@ const inputSchemas = { direction: z.enum(["incoming", "outgoing"]).default("outgoing"), }) .strict(), - xrefs: z.object({ document, address: ghidraCanonicalAddressSchema }).strict(), + xrefs: z.object({ document, address: ghidraInputAddressSchema }).strict(), } satisfies Readonly>; /** Validate and default one function request before it crosses the socket. */ @@ -118,7 +120,11 @@ export const parseGhidraFunctionInput = ( ), ), ) - : err(new AnalysisInputError(operation, { cause: parsed.error })); + : err( + analysisInputErrorFromIssues(operation, parsed.error.issues, value, { + cause: parsed.error, + }), + ); }; const localVariable = z diff --git a/src/ghidra/GhidraInventoryValues.ts b/src/ghidra/GhidraInventoryValues.ts index 9f08c5fb3..1ed9d4809 100644 --- a/src/ghidra/GhidraInventoryValues.ts +++ b/src/ghidra/GhidraInventoryValues.ts @@ -2,7 +2,7 @@ import { z } from "zod"; import { nativeLoadImageObservationSchema } from "../domain/native/nativeLoadImage.js"; import { - AnalysisInputError, + type AnalysisInputError, AnalysisOutputError, } from "../domain/analysisErrorCore.js"; import { @@ -11,6 +11,7 @@ import { } from "../domain/hopperValues.js"; import { jsonValueSchema, type JsonValue } from "../domain/jsonValue.js"; import { err, ok, type Result } from "../domain/result.js"; +import { analysisInputErrorFromIssues } from "../domain/inputIssueProjection.js"; /** Read-only direct inventory operations admitted by the Ghidra adapter. */ export const GHIDRA_INVENTORY_OPERATIONS = [ @@ -43,7 +44,14 @@ export const isGhidraInventoryOperation = ( export const ghidraIdentifierSchema = z.string().min(1); const identifier = ghidraIdentifierSchema; const document = identifier.nullable().default(null); -const explicitAddress = identifier; +/** Caller address spelling; the bridge resolves its space and emits canonical output. */ +export const ghidraInputAddressSchema = z + .string() + .regex( + /^(?:(?:0[xX])?[0-9a-fA-F]+|(?:[A-Za-z0-9._~-]|%[0-9a-fA-F]{2})+:0[xX][0-9a-fA-F]+)$/u, + "Use hexadecimal digits, optionally prefixed with 0x, or an encoded address-space name followed by :0x and hexadecimal digits", + ); +const explicitAddress = ghidraInputAddressSchema; const filteredAddress = explicitAddress.nullable().default(null); const searchInput = { pattern: z.string().min(1), @@ -84,7 +92,11 @@ export const parseGhidraInventoryInput = ( ): Result>, AnalysisInputError> => { const parsed = inputSchemas[operation].safeParse(value); if (!parsed.success) - return err(new AnalysisInputError(operation, { cause: parsed.error })); + return err( + analysisInputErrorFromIssues(operation, parsed.error.issues, value, { + cause: parsed.error, + }), + ); return ok(parsed.data); }; diff --git a/src/ghidra/GhidraJavaLaunch.ts b/src/ghidra/GhidraJavaLaunch.ts new file mode 100644 index 000000000..6f50ddf89 --- /dev/null +++ b/src/ghidra/GhidraJavaLaunch.ts @@ -0,0 +1,88 @@ +import { dirname, join } from "node:path"; +import { execFileOutput } from "../process/ExecFileOutput.js"; + +/** Launch coordinates obtained from Ghidra's own release configuration helper. */ +export const ghidraJavaLaunch = async (options: { + readonly analyzeHeadlessPath: string; + readonly javaHome: string; + readonly homeRoot: string; + readonly tempRoot: string; + readonly arguments: readonly string[]; + readonly environment: NodeJS.ProcessEnv; + readonly signal?: AbortSignal; +}): Promise<{ + readonly command: string; + readonly arguments: readonly string[]; + readonly environment: NodeJS.ProcessEnv; +}> => { + const supportRoot = dirname(options.analyzeHeadlessPath); + const installRoot = dirname(supportRoot); + const command = join(options.javaHome, "bin", "java"); + const isolatedProperties = [ + `-Duser.home=${options.homeRoot}`, + `-Djava.io.tmpdir=${options.tempRoot}`, + ]; + const supportArguments = [ + ...isolatedProperties, + "-cp", + join(supportRoot, "LaunchSupport.jar"), + "LaunchSupport", + installRoot, + ]; + const environment = { ...options.environment }; + const configuredEnvironment = await execFileOutput( + command, + [...supportArguments, "-envvars"], + { + env: environment, + ...(options.signal === undefined ? {} : { signal: options.signal }), + }, + ); + for (const line of configuredEnvironment.stdout.split(/\r?\n/u)) { + if (line === "") continue; + const separator = line.indexOf("="); + const key = line.slice(0, separator); + if (separator < 1 || !/^[A-Za-z_][A-Za-z0-9_]*$/u.test(key)) + throw new Error( + `Invalid Ghidra LaunchSupport environment entry: ${line}`, + ); + if ((environment[key] ?? "") === "") + environment[key] = line.slice(separator + 1); + } + const configuredArguments = await execFileOutput( + command, + [...supportArguments, "-vmargs"], + { + env: environment, + ...(options.signal === undefined ? {} : { signal: options.signal }), + }, + ); + const vmArguments = configuredArguments.stdout + .split(/\r?\n/u) + .filter((line) => line !== ""); + if ( + vmArguments.some( + (argument) => !argument.startsWith("-") || argument.includes("\0"), + ) + ) + throw new Error("Invalid Ghidra LaunchSupport JVM argument"); + return { + command, + environment, + arguments: [ + ...vmArguments, + "-Xdock:name=Ghidra-Headless", + `-Xmx${environment.GHIDRA_HEADLESS_MAXMEM || environment.GHIDRA_MAXMEM || "2G"}`, + "-XX:ParallelGCThreads=2", + "-XX:CICompilerCount=2", + "-Djava.awt.headless=true", + ...isolatedProperties, + "-showversion", + "-cp", + join(installRoot, "Ghidra", "Framework", "Utility", "lib", "Utility.jar"), + "ghidra.Ghidra", + "ghidra.app.util.headless.AnalyzeHeadless", + ...options.arguments, + ], + }; +}; diff --git a/src/ghidra/GhidraLauncher.ts b/src/ghidra/GhidraLauncher.ts index 444c4b523..f030c8559 100644 --- a/src/ghidra/GhidraLauncher.ts +++ b/src/ghidra/GhidraLauncher.ts @@ -18,6 +18,7 @@ import { spawnOwnedProviderProcess, } from "../process/ProviderProcess.js"; import { ghidraJavaEnvironment } from "./GhidraInstallation.js"; +import { ghidraJavaLaunch } from "./GhidraJavaLaunch.js"; import type { GhidraTransportKind } from "./GhidraTransport.js"; import { snapshotGhidraExtensions, @@ -124,7 +125,7 @@ export class GhidraHeadlessLauncher implements GhidraLauncher { ? {} : { dosMz: this.options.dosMz }), }); - const command = ghidraHeadlessCommand({ + const scriptCommand = ghidraHeadlessCommand({ platform, analyzeHeadlessPath: this.options.analyzeHeadlessPath, arguments: headlessArguments, @@ -132,33 +133,55 @@ export class GhidraHeadlessLauncher implements GhidraLauncher { ? {} : { comSpec: this.options.comSpec }), }); + const environment = ghidraLaunchEnvironment( + paths, + this.options.javaHome, + platform, + scriptCommand.command, + ); + if (platform === "darwin" && this.options.javaHome === undefined) + throw new GhidraLaunchError( + "macOS Ghidra requires its inspected JDK home", + ); + const command = + platform === "darwin" && this.options.javaHome !== undefined + ? await ghidraJavaLaunch({ + analyzeHeadlessPath: this.options.analyzeHeadlessPath, + javaHome: this.options.javaHome, + homeRoot: paths.homeRoot, + tempRoot: paths.tempRoot, + arguments: headlessArguments, + environment, + ...(options.signal === undefined + ? {} + : { signal: options.signal }), + }) + : { ...scriptCommand, environment }; started = await spawnOwnedProviderProcess({ command: command.command, arguments: command.arguments, runId: session.runId, - // analyzeHeadless is an interpreter-driven script. Parent identity and - // the per-process run token remain the cleanup authority. - expectedCommand: null, + // macOS launches the inspected JVM directly: platform shell wrappers + // with withheld environments cannot establish run-token ownership. + expectedCommand: platform === "darwin" ? command.command : null, windowsVerbatimArguments: platform === "win32", platform, - env: ghidraLaunchEnvironment( - paths, - this.options.javaHome, - platform, - command.command, - ), + env: command.environment, ...(options.signal === undefined ? {} : { signal: options.signal }), }); await writeGhidraRuntimeFile( paths.ownershipPath, `${JSON.stringify({ run_id: session.runId, + transport: session.transport, + endpoint_path: session.endpointPath, pid: started.ownership.leaderPid, process_group_id: started.ownership.processGroupId, parent_pid: process.pid, ownership_kind: platform === "win32" ? "windows-job-object" : "posix-process-group", - launcher: this.options.analyzeHeadlessPath, + launcher: command.command, + headless_script: this.options.analyzeHeadlessPath, created_at: new Date().toISOString(), })}\n`, platform, diff --git a/src/ghidra/GhidraProviderClient.ts b/src/ghidra/GhidraProviderClient.ts index 2dad76201..1e8fa55e6 100644 --- a/src/ghidra/GhidraProviderClient.ts +++ b/src/ghidra/GhidraProviderClient.ts @@ -132,9 +132,7 @@ export const createGhidraProviderClient = (input: { platform: installation.platform, launcher: new GhidraHeadlessLauncher({ analyzeHeadlessPath: prerequisites.value.analyzeHeadlessPath, - ...(config.ghidraJavaHome === undefined - ? {} - : { javaHome: config.ghidraJavaHome }), + javaHome: prerequisites.value.javaHome, bridgeScriptPath: fileURLToPath( new URL("../../bridge/ghidra/ReaGhidraBridge.java", import.meta.url), ), @@ -266,6 +264,7 @@ export const createGhidraProviderClient = (input: { interface GhidraClientCoordinates { readonly analyzeHeadlessPath: string; + readonly javaHome: string; readonly providerVersion: string; readonly profile: AnalysisProfileCommitment; } @@ -304,6 +303,7 @@ const ghidraClientPrerequisites = ( return err(new ProviderAdapterError("ghidra", "health")); return ok({ analyzeHeadlessPath: installation.analyzeHeadlessPath, + javaHome: installation.javaHome, providerVersion: installation.providerVersion, profile, }); @@ -341,7 +341,9 @@ const projectSessionError = ( failure.remoteCode ?? "", ) ) - return new AnalysisInputError(operation, { cause: failure }); + return new AnalysisInputError(operation, { cause: failure }, [ + { path: [], reason: "invalid_value", message: failure.message }, + ]); if (failure.kind === "remote" && failure.remoteCode === "method_unavailable") return new AnalysisCapabilityUnavailableError( "ghidra", diff --git a/src/ghidra/GhidraSessionError.test.ts b/src/ghidra/GhidraSessionError.test.ts deleted file mode 100644 index f2089b192..000000000 --- a/src/ghidra/GhidraSessionError.test.ts +++ /dev/null @@ -1,81 +0,0 @@ -import { describe, expect, it } from "vitest"; - -import { bindGhidraSessionFailure } from "./GhidraSessionError.js"; - -const diagnostics = { - target_path: "/tmp/public-fixture", - target_sha256: "a".repeat(64), -}; - -describe("Ghidra session failure diagnostics", () => { - it("retains the original Error while projecting its name, message and code", () => { - const cause = Object.assign( - new TypeError("Cannot decode /tmp/public-fixture at offset 17"), - { code: "EDECODE" }, - ); - const failure = bindGhidraSessionFailure(() => diagnostics)( - "protocol", - "Request rejected", - cause, - ); - expect(failure.cause).toBe(cause); - expect(failure.kind).toBe("protocol"); - expect(failure.diagnostics).toEqual({ - ...diagnostics, - failure_cause: { - name: "TypeError", - message: cause.message, - code: "EDECODE", - }, - }); - expect(failure.diagnostics).not.toHaveProperty("stack"); - }); - - it.each([ - ["decoder rejected", { type: "string", message: "decoder rejected" }], - [null, { type: "null", value: null }], - [false, { type: "boolean", value: false }], - [42, { type: "number", value: 42 }], - [{ opaque: true }, { type: "object" }], - ])("handles a non-Error rejection (%j)", (cause, expected) => { - const failure = bindGhidraSessionFailure(() => diagnostics)( - "process", - "Shutdown rejected", - cause, - ); - expect(failure.cause).toBe(cause); - expect(failure.diagnostics.failure_cause).toEqual(expected); - }); - - it("redacts only known authentication material in projected failure fields", () => { - const token = "actual-bridge-authentication"; - const message = `Failure ${token}: http://localhost/secret?token=public-value /tmp/password-fixture`; - const cause = Object.assign(new Error(message), { code: `code-${token}` }); - const failure = bindGhidraSessionFailure( - () => diagnostics, - (value) => value.replaceAll(token, "[REDACTED]"), - )("remote", message, cause, { remoteCode: `code-${token}` }); - expect(failure.cause).toBe(cause); - expect(failure.message).toBe(message.replaceAll(token, "[REDACTED]")); - expect(failure.diagnostics).toMatchObject({ - remote_code: "code-[REDACTED]", - remote_message: failure.message, - failure_cause: { message: failure.message, code: "code-[REDACTED]" }, - }); - expect(JSON.stringify(failure.diagnostics)).not.toContain(token); - expect(JSON.stringify(failure.diagnostics)).toContain( - "token=public-value /tmp/password-fixture", - ); - }); - - it("leaves absent causes and existing timeout metadata unchanged", () => { - const failure = bindGhidraSessionFailure(() => diagnostics)( - "timeout", - "Deadline elapsed", - undefined, - { timeoutMs: 5 }, - ); - expect(failure.timeoutMs).toBe(5); - expect(failure.diagnostics).toEqual(diagnostics); - }); -}); diff --git a/src/ghidra/GhidraSessionError.ts b/src/ghidra/GhidraSessionError.ts index f8f67a73f..dda3265f6 100644 --- a/src/ghidra/GhidraSessionError.ts +++ b/src/ghidra/GhidraSessionError.ts @@ -49,13 +49,17 @@ const createGhidraSessionError = (failure: { new GhidraSessionError( failure.kind, failure.message, - failure.remoteCode === undefined - ? failure.diagnostics - : { - ...failure.diagnostics, - remote_code: failure.redact(failure.remoteCode), - remote_message: failure.message, - }, + { + ...failure.diagnostics, + failure_kind: failure.kind, + failure_message: failure.message, + ...(failure.remoteCode === undefined + ? {} + : { + remote_code: failure.redact(failure.remoteCode), + remote_message: failure.message, + }), + }, { ...(failure.cause === undefined ? {} : { cause: failure.cause }), ...(failure.timeoutMs === undefined diff --git a/src/ghidra/GhidraTransport.ts b/src/ghidra/GhidraTransport.ts index 7cb24146d..85e3a19af 100644 --- a/src/ghidra/GhidraTransport.ts +++ b/src/ghidra/GhidraTransport.ts @@ -1,4 +1,6 @@ import { access, open } from "node:fs/promises"; +import { join } from "node:path"; +import { PrivateRuntimeRoot } from "../process/PrivateRuntimeRoot.js"; import { readWindowsPrivateRuntimeFile } from "../windows/WindowsPrivateRuntime.js"; @@ -14,6 +16,37 @@ export interface GhidraEndpoint { readonly path: string; } +/** Allocate an endpoint that fits the host's Unix sockaddr without moving the project. */ +export const createGhidraEndpoint = async ( + runtimeRoot: string, + transport: GhidraTransportKind, + platform: NodeJS.Platform, +): Promise<{ + readonly endpoint: GhidraEndpoint; + readonly socketRoot?: PrivateRuntimeRoot; +}> => { + const path = join( + runtimeRoot, + transport === "unix-socket" ? "bridge.sock" : "bridge-endpoint.json", + ); + // sockaddr_un includes a terminating NUL: macOS has 104 bytes, Linux 108. + const maximumPathBytes = platform === "darwin" ? 103 : 107; + if ( + transport !== "unix-socket" || + Buffer.byteLength(path, "utf8") <= maximumPathBytes + ) + return { endpoint: { transport, path } }; + const socketRoot = await PrivateRuntimeRoot.create({ + parent: "/tmp", + prefix: "rea-ghidra-socket-", + platform, + }); + return { + endpoint: { transport, path: join(socketRoot.path, "s") }, + socketRoot, + }; +}; + /** Exact Node connection target after endpoint discovery. */ export type GhidraConnectTarget = | { readonly path: string } diff --git a/tests/boundary/mcp/ghidraEvidenceMcp.test.ts b/tests/boundary/mcp/ghidraEvidenceMcp.test.ts index 99fd3ae01..ada117a6d 100644 --- a/tests/boundary/mcp/ghidraEvidenceMcp.test.ts +++ b/tests/boundary/mcp/ghidraEvidenceMcp.test.ts @@ -1,6 +1,65 @@ import { describe, expect, it } from "vitest"; import { EnhancedTools } from "../../../src/application/EnhancedTools.js"; import { connectGhidraMcp, sessionEvidence } from "./ghidraMcpHarness.js"; +import { functionDossierSchema } from "../../../src/domain/hopperValues.js"; +import { ghidraFunctionDossier } from "../../../src/domain/ghidraValues.fixture.js"; +import { jsonValueSchema } from "../../../src/domain/jsonValue.js"; +import { ok } from "../../../src/domain/result.js"; + +it("rejects contradictory annotation readback across the provider and MCP boundaries", async () => { + const dossier = functionDossierSchema.parse(ghidraFunctionDossier()); + const annotations = { + address: dossier.procedure.address, + name: dossier.procedure.name, + comment: null, + inline_comment: "Finding", + }; + const effects = { + scope: "session-analysis-database", + source_bytes_modified: false, + persists_after_close: false, + }; + const original = { annotations, dossier, effects }; + let output = jsonValueSchema.parse(original); + const harness = await connectGhidraMcp("ghidra-malformed-annotation", () => + Promise.resolve(ok(output)), + ); + try { + const accepted = await harness.mcp.callTool({ + name: "annotate_native_function", + arguments: { + procedure: annotations.address, + inline_comment: "Finding", + }, + }); + expect(accepted.isError).not.toBe(true); + expect(accepted.structuredContent).toMatchObject({ + result: { annotations }, + }); + for (const value of [ + { ...original, annotations: { ...annotations, name: "different" } }, + { ...original, annotations: { ...annotations, address: "0x9999" } }, + { ...original, effects: { ...effects, source_bytes_modified: true } }, + { ...original, effects: { ...effects, persists_after_close: true } }, + { ...original, dossier: { ...dossier, native_value_flow: null } }, + ]) { + output = jsonValueSchema.parse(value); + const reply = await harness.mcp.callTool({ + name: "annotate_native_function", + arguments: { + procedure: annotations.address, + inline_comment: "Finding", + }, + }); + expect(reply.isError).toBe(true); + expect(reply.structuredContent).toMatchObject({ + error: { code: "unreadable_output" }, + }); + } + } finally { + await harness.close(); + } +}); describe("Ghidra MCP evidence parity", () => { it("preserves provider evidence, composed parity, and capability routing", async () => { diff --git a/tests/boundary/mcp/ghidraFailureDiagnostics.test.ts b/tests/boundary/mcp/ghidraFailureDiagnostics.test.ts index a20757f31..15bcb1320 100644 --- a/tests/boundary/mcp/ghidraFailureDiagnostics.test.ts +++ b/tests/boundary/mcp/ghidraFailureDiagnostics.test.ts @@ -49,6 +49,9 @@ it("preserves queue failure diagnostics through the provider, CLI adapter and SD details: { diagnostics: { target_path: "/tmp/public-fixture", + failure_kind: "protocol", + failure_message: + "Ghidra serial request execution rejected unexpectedly", failure_cause: { name: "TypeError", code: "EDECODE", diff --git a/tests/boundary/providers/ghidra/ghidraLauncher.test.ts b/tests/boundary/providers/ghidra/ghidraLauncher.test.ts index 6c44f4393..591a554d3 100644 --- a/tests/boundary/providers/ghidra/ghidraLauncher.test.ts +++ b/tests/boundary/providers/ghidra/ghidraLauncher.test.ts @@ -214,6 +214,9 @@ describe("Ghidra headless launcher", () => { process.platform === "win32" ? "C:\\Java\\jdk-21" : "/opt/jdk-21"; const launcher = new GhidraHeadlessLauncher({ analyzeHeadlessPath: fixturePath, + // This fixture exercises the official script route. Native macOS JVM + // launching is covered by the real Ghidra acceptance lane. + platform: process.platform === "win32" ? "win32" : "linux", javaHome, bridgeScriptPath: "/package/bridge/ReaGhidraBridge.java", });