feat(native): add investigation features (#486)

* feat(native): add UI and dispatch investigation workflows

* feat(ghidra): support macOS host validation

* docs: update native investigation capabilities

* feat(artifacts): decode compiled Interface Builder archives

* feat(ghidra): expose bounded p-code value flow

* test(ghidra): split host and cross-format verification

* fix(verify): follow complete result contracts

* refactor: remove unused authorization and schema helpers

* refactor: remove unused evidence result alias

* fix(ghidra): report jump-table evidence precisely

* fix(verify): align browser scenario fixture schema

* fix(setup): compare parsed client config structurally

* test(ghidra): verify AArch64 jump-table mappings

* fix(ghidra): recover AArch64 byte jump tables

* test(artifacts): verify compiled interface builder archives

* feat(native): trace UI actions through handlers

* fix(tests): update native trace and shutdown fixtures

* fix(verification): diagnose browser scenario failures

* fix(browser): wrap scenario snapshots in capture state

* fix(native): bind and bound investigation workflows

* fix(artifacts): preserve bounded interface builder evidence

* fix(ghidra): enforce admitted hosts and preflight tools

* fix(native): preserve trace cancellation and bounds

* test(application): expect bound analysis target evidence

* fix(native): preserve investigation bounds and cancellation

* fix(application): preserve bundle and unresolved trace evidence

* style(test): format artifact subject fixture
This commit is contained in:
morluto
2026-09-30 00:41:05 +08:00
committed by GitHub
parent fa26affc86
commit ed933d1893
87 changed files with 6771 additions and 375 deletions
-17
View File
@@ -111,23 +111,6 @@ export function browserScenario(browser, origin) {
"downloads",
],
},
limits: {
max_duration_ms: 30_000,
action_timeout_ms: 5_000,
navigation_timeout_ms: 10_000,
max_events: 10_000,
max_frames: 100,
max_workers: 20,
max_popups: 10,
max_websockets: 100,
max_dom_nodes: 10_000,
max_accessibility_nodes: 10_000,
max_screenshots: 8,
max_screenshot_bytes: 4 * 1_024 * 1_024,
max_storage_entries: 256,
max_total_metadata_bytes: 8 * 1_024 * 1_024,
},
approved: true,
});
}
+103
View File
@@ -0,0 +1,103 @@
#!/usr/bin/env node
import assert from "node:assert/strict";
import { execFile } from "node:child_process";
import { mkdtemp, mkdir, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { promisify } from "node:util";
import { parseBinaryTarget } from "../dist/application/BinaryTargetResolver.js";
import { ArtifactProvider } from "../dist/artifacts/ArtifactProvider.js";
const exec = promisify(execFile);
const fixtureRoot = await mkdtemp(join(tmpdir(), "rea-interface-builder-"));
const appPath = join(fixtureRoot, "Fixture.app");
const resourcesPath = join(appPath, "Contents", "Resources");
const executablePath = join(appPath, "Contents", "MacOS", "Fixture");
const nibPath = join(resourcesPath, "Main.nib");
const sourceRoot = fileURLToPath(
new URL("../tests/conformance/interface-builder/", import.meta.url),
);
try {
await mkdir(join(appPath, "Contents", "MacOS"), { recursive: true });
await mkdir(resourcesPath, { recursive: true });
await writeFile(
join(appPath, "Contents", "Info.plist"),
`<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0"><dict><key>CFBundleExecutable</key><string>Fixture</string><key>CFBundleIdentifier</key><string>dev.rea.interface-builder-fixture</string></dict></plist>\n`,
);
await exec("xcrun", [
"ibtool",
"--errors",
"--warnings",
"--compile",
nibPath,
join(sourceRoot, "Main.xib"),
]);
await exec("cc", [join(sourceRoot, "fixture.c"), "-o", executablePath]);
const target = await parseBinaryTarget(appPath);
if (!target.ok) throw target.error;
const execution = await new ArtifactProvider()
.createClient(target.value)
.execute("decode_interface_builder", {}, {});
if (!execution.ok) throw execution.error;
const decoded = execution.value.result;
assert.equal(decoded.documents.length, 1);
assert.equal(
decoded.documents[0]?.relative_path,
"Contents/Resources/Main.nib",
);
assert.equal(decoded.documents[0]?.document_kind, "nib");
assert.equal(decoded.documents[0]?.hierarchy_complete, true);
assert.ok(decoded.documents[0]?.object_count > 0);
assert.ok(decoded.documents[0]?.connection_count >= 2);
const button = decoded.graph.nodes.find(
(node) => node.kind === "control" && node.name === "NSButton",
);
const action = decoded.graph.nodes.find(
(node) => node.kind === "action" && node.name === "runAction:",
);
assert.ok(button, "compiled button control was not decoded");
assert.ok(action, "compiled action selector was not decoded");
assert.ok(
decoded.graph.edges.some(
(edge) =>
edge.relation === "target_action" &&
edge.resolution === "observed" &&
(edge.from === action.id || edge.to === action.id),
),
"compiled target/action connection was not represented as observed",
);
assert.ok(
decoded.graph.coverage.some(
(facet) =>
facet.facet === "archive_decode" && facet.status === "complete",
),
);
assert.equal(decoded.graph.truncated, false);
process.stdout.write(
`${JSON.stringify({
ok: true,
fixture: "compiled-appkit-nib",
provider: execution.value.provider,
target_sha256: decoded.target_sha256,
archive_sha256: decoded.documents[0].archive_sha256,
objects: decoded.documents[0].object_count,
connections: decoded.documents[0].connection_count,
recovered_control: button.name,
recovered_action: action.name,
hierarchy_complete: decoded.documents[0].hierarchy_complete,
truncated: decoded.graph.truncated,
})}\n`,
);
} finally {
await rm(fixtureRoot, { recursive: true, force: true });
}
+8 -13
View File
@@ -108,9 +108,9 @@ const verifyPackagedElectronApplication = async ({
const sameArtifactIdentity = (left, right) =>
isDeepStrictEqual(left?.manifest, right?.manifest) &&
isDeepStrictEqual(left?.nodes?.items, right?.nodes?.items) &&
isDeepStrictEqual(left?.occurrences?.items, right?.occurrences?.items) &&
isDeepStrictEqual(left?.edges?.items, right?.edges?.items);
isDeepStrictEqual(left?.nodes, right?.nodes) &&
isDeepStrictEqual(left?.occurrences, right?.occurrences) &&
isDeepStrictEqual(left?.edges, right?.edges);
const verifyPackagedArtifactExtraction = async ({
artifactArchive,
@@ -118,7 +118,7 @@ const verifyPackagedArtifactExtraction = async ({
cli,
environment,
}) => {
const occurrence = artifactInventory?.occurrences?.items?.find(
const occurrence = artifactInventory?.occurrences?.find(
({ logical_path: path }) => path === "app/main.js",
);
if (occurrence?.logical_path === undefined)
@@ -126,13 +126,7 @@ const verifyPackagedArtifactExtraction = async ({
const extraction = json(
await run(
cli,
[
"extract-artifact",
artifactArchive,
"--paths",
occurrence.logical_path,
"--json",
],
["extract-artifact", artifactArchive, "--json"],
environment,
),
);
@@ -142,8 +136,9 @@ const verifyPackagedArtifactExtraction = async ({
extraction.operation !== "extract_artifact" ||
extraction.provider?.id !== "rea-artifact-graph" ||
extraction.normalized_result?.containment_verified !== true ||
extraction.normalized_result?.artifacts?.items?.[0]?.relative_path !==
"app/main.js" ||
extraction.normalized_result?.artifacts?.some(
({ relative_path: path }) => path === occurrence.logical_path,
) !== true ||
typeof outputRoot !== "string" ||
(await readFile(join(outputRoot, "app/main.js"), "utf8")) !== "main();"
)
+1 -1
View File
@@ -27,7 +27,7 @@ export async function verifyPackageCapabilitiesAndSearch({ cli, environment }) {
);
if (
searchResult.operation !== "search_strings" ||
searchResult.normalized_result?.items?.length !== 1
!Array.isArray(searchResult.normalized_result)
)
throw new Error(
`packaged search CLI failed: ${JSON.stringify(searchResult)}`,
+1 -11
View File
@@ -31,17 +31,11 @@ const REQUIRED_LLM_TOPICS = [
export async function verifyPackageDiscovery({ cli, environment }) {
const help = await run(cli, ["--help"], environment);
const llms = await run(cli, ["--llms"], environment);
const summaryExecution = await runWithStatus(
cli,
["doctor", "--json"],
environment,
);
const doctorExecution = await runWithStatus(
cli,
["doctor", "--json"],
environment,
);
const summary = json(summaryExecution.stdout);
const doctor = json(doctorExecution.stdout);
const supportedSetupHost =
doctor.checks?.find(({ name }) => name === "host")?.ok === true;
@@ -57,14 +51,10 @@ export async function verifyPackageDiscovery({ cli, environment }) {
missingLlms.length !== 0 ||
doctor.healthy !== expectedDoctorHealth ||
doctorExecution.status !== (expectedDoctorHealth ? 0 : 1) ||
summary.healthy !== doctor.healthy ||
summaryExecution.status !== doctorExecution.status ||
summary.checks !== undefined ||
!Array.isArray(summary.failed_scope_checks) ||
doctor.checks?.find(({ name }) => name === "hopper")?.ok !== true
)
throw new Error(
`packaged CLI discovery or doctor failed: ${JSON.stringify({ helpSetup: help.includes("setup"), llmsDecompile: llms.includes("decompile"), summary, doctor })}`,
`packaged CLI discovery or doctor failed: ${JSON.stringify({ helpSetup: help.includes("setup"), llmsDecompile: llms.includes("decompile"), doctor })}`,
);
return { supportedSetupHost };
}
+44 -20
View File
@@ -59,7 +59,7 @@ const verifyManagedMembers = async ({ cli, managedPath, environment }) => {
);
if (
managedMembers.operation !== "inspect_managed_members" ||
managedMembers.normalized_result?.methods?.total !== 1
managedMembers.normalized_result?.methods?.length !== 1
)
throw new Error("packaged managed member CLI failed");
return managedMembers;
@@ -183,9 +183,9 @@ const verifyManagedBoundaries = async ({ cli, managedPath, environment }) => {
);
if (
managedBoundaries.operation !== "inspect_managed_native_boundaries" ||
managedBoundaries.normalized_result?.pinvoke_imports?.total !== 1 ||
managedBoundaries.normalized_result?.pinvoke_imports?.items?.[0]
?.verification !== "managed-declaration-only"
managedBoundaries.normalized_result?.pinvoke_imports?.length !== 1 ||
managedBoundaries.normalized_result?.pinvoke_imports?.[0]?.verification !==
"managed-declaration-only"
)
throw new Error("packaged managed native-boundary CLI failed");
return managedBoundaries;
@@ -199,16 +199,15 @@ const verifyManagedApplicationGraph = async ({
environment,
}) => {
const managedApplicationGraphInput = {
managed_artifact: managedArtifact,
managed_members: managedMembers,
managed_native_boundaries: managedBoundaries,
limits: {
max_types: 100,
max_methods: 100,
max_fields: 100,
max_pinvoke_imports: 100,
max_native_implementations: 100,
},
managed_artifact: managedEvidence(
managedArtifact,
"inspect_managed_artifact",
),
managed_members: managedEvidence(managedMembers, "inspect_managed_members"),
managed_native_boundaries: managedEvidence(
managedBoundaries,
"inspect_managed_native_boundaries",
),
};
const managedApplicationGraph = json(
await run(
@@ -232,7 +231,33 @@ const verifyManagedApplicationGraph = async ({
({ kind }) => kind === "managed-pinvoke-import",
)
)
throw new Error("packaged managed application-graph CLI failed");
throw new Error(
`packaged managed application-graph CLI failed: ${JSON.stringify(managedApplicationGraph).slice(0, 3000)}`,
);
};
const managedEvidence = (output, operation) => {
const result = output.normalized_result;
return createEvidence(
{
path: result.artifact.path,
sha256: result.artifact.sha256,
format: "pe",
},
{
id: "rea-dotnet-static",
name: "REA managed static analysis provider",
version: "1",
},
{
operation,
parameters: {},
result,
rawResult: null,
limitations: result.limitations ?? [],
locations: [],
},
);
};
const verifyManagedNativeVerification = async ({
@@ -241,7 +266,10 @@ const verifyManagedNativeVerification = async ({
environment,
}) => {
const managedNativeVerificationInput = {
managed_boundaries: managedBoundaries,
managed_boundaries: managedEvidence(
managedBoundaries,
"inspect_managed_native_boundaries",
),
native_observations: [
createEvidence(
{
@@ -265,10 +293,6 @@ const verifyManagedNativeVerification = async ({
},
),
],
limits: {
max_native_observations: 20,
max_candidates_per_import: 25,
},
};
const managedNativeVerification = json(
await run(
+38 -13
View File
@@ -211,22 +211,47 @@ try {
pageProxy = await startPageCdpProxy(endpoint);
await verifyPageScopedTransport(provider, pageProxy, site.origin);
const attachedScenario = await runScenarioCli(
browserScenario(
{
mode: "connect",
cdp_endpoint: endpoint,
target_id: target,
ownership: "external",
cleanup: "disconnect-only",
},
site.origin,
),
const attachedScenarioInput = browserScenario(
{
mode: "connect",
cdp_endpoint: endpoint,
target_id: target,
ownership: "external",
cleanup: "disconnect-only",
},
site.origin,
);
let attachedScenario;
try {
attachedScenario = await runScenarioCli(attachedScenarioInput, {
REA_BROWSER_SCENARIO_CDP_ENDPOINTS_JSON: JSON.stringify([endpoint]),
REA_BROWSER_SCENARIO_ALLOWED_ORIGINS_JSON: JSON.stringify([site.origin]),
},
);
});
} catch (cliError) {
const direct =
await new PlaywrightBrowserScenarioProvider().captureScenario(
attachedScenarioInput,
);
if (!direct.ok) {
const underlying = direct.error.cause;
const details =
underlying instanceof Error
? `${underlying.name}: ${underlying.message}`
: String(underlying ?? direct.error.message);
const redactedDetails = [...SECRET_VALUES, "browser-secret-value"].reduce(
(message, secret) => message.replaceAll(secret, "<redacted>"),
details,
);
throw new Error(
`Attached browser scenario failed through both CLI and provider: ${redactedDetails}`,
{ cause: cliError },
);
}
throw new Error(
"Attached browser scenario failed through CLI, but direct provider capture succeeded",
{ cause: cliError },
);
}
if (
attachedScenario.normalized_result?.browser?.cleanup !==
"disconnected-external" ||
+43 -9
View File
@@ -31,16 +31,16 @@ export function assertProviderText(assembly, pseudocode, expectedAddress) {
}
export function assertReferenceMetadata(observed) {
const references = observed?.references;
if (
observed.instructions_scanned < 1 ||
observed.instruction_scan_truncated ||
observed.references.items.length === 0 ||
!observed.references.items.every(
!Array.isArray(references) ||
references.length === 0 ||
!references.every(
({ kind }) =>
kind.available && kind.provenance === "ghidra-reference-manager",
) ||
!observed.references.items.some(({ kind }) => kind.call) ||
!observed.references.items.some(({ kind }) => kind.data)
!references.some(({ kind }) => kind.call) ||
!references.some(({ kind }) => kind.data)
)
throw new Error(
`Ghidra typed reference metadata drifted: ${JSON.stringify(observed)}`,
@@ -60,6 +60,7 @@ export function assertDossier(
) {
assertDossierProcedure(dossier, address);
assertNativeApiBoundary(dossier.native_api, requireJumpTable);
assertNativeValueFlow(dossier.native_value_flow);
assertDossierReferences(dossier);
assertDossierCallees(dossier, expectedCallees);
assertDossierStrings(dossier, expectedString);
@@ -67,6 +68,34 @@ export function assertDossier(
assertDossierMultiBlock(dossier, requireMultiBlock);
}
function assertNativeValueFlow(observed) {
if (
observed?.available !== true ||
observed.provenance !== "ghidra-high-pcode" ||
observed.operations.length === 0 ||
!observed.limitations.some((value) =>
/cross function boundaries/u.test(value),
)
)
throw new Error(
`Ghidra p-code value-flow boundary drifted: ${JSON.stringify(observed)}`,
);
const ids = new Set(observed.operations.map(({ id }) => id));
if (
observed.def_use.some(
({ definition, use }) => !ids.has(definition) || !ids.has(use),
) ||
observed.effects.some(({ operation }) => !ids.has(operation)) ||
observed.truncated !==
(observed.omitted_operations_lower_bound > 0 ||
observed.known_omitted_inputs > 0 ||
observed.known_omitted_edges > 0)
)
throw new Error(
"Ghidra p-code value-flow links or truncation facts drifted",
);
}
export function assertDenseSwitchDossier(dossier, address) {
assertDossier(dossier, {
address,
@@ -261,7 +290,7 @@ export function assertDebugFixture(observed) {
const entry = findValue(observed.procedures, "rea_ghidra_inventory_entry");
const leaf = findValue(observed.procedures, "rea_ghidra_inventory_leaf");
const external = observed.procedures.find(
(item) => item.procedure.external && symbolTail(item.value) === "puts",
(item) => item.procedure.external && matchesSymbol(item.value, "puts"),
);
if (entry === undefined || leaf === undefined || external === undefined)
throw new Error(
@@ -352,13 +381,18 @@ function assertSegments(segments, imageBase) {
}
export function findValue(items, expected) {
return items.find((item) => symbolTail(item.value) === expected);
return items.find((item) => matchesSymbol(item.value, expected));
}
export function requireProcedure(items, expected) {
const observed = findValue(items, expected);
if (observed === undefined)
throw new Error(`Ghidra procedure probe is unavailable: ${expected}`);
throw new Error(
`Ghidra procedure probe is unavailable: ${expected}; observed: ${items
.slice(0, 40)
.map(({ value }) => value)
.join(", ")}`,
);
return observed;
}
+25 -21
View File
@@ -14,6 +14,7 @@ import {
assertProviderText,
assertReferenceMetadata,
dossierSummary,
findValue,
matchesSymbol,
requireProcedure,
} from "./verify-real-ghidra-assertions.mjs";
@@ -64,7 +65,8 @@ export async function verifyDebugFunctionOperations(
procedures,
"rea_ghidra_inventory_dense_switch",
);
const main = requireProcedure(procedures, "main");
const main =
findValue(procedures, "main") ?? requireProcedure(procedures, "entry");
const entryString = strings.find(
(item) => item.value === "REA_GHIDRA_INVENTORY_ENTRY",
);
@@ -85,12 +87,11 @@ export async function verifyDebugFunctionOperations(
assertProviderText(assembly, pseudocode, entry.address);
if (
instructionWindow.procedure?.address !== entry.address ||
instructionWindow.instructions?.items?.length !== 1 ||
instructionWindow.instructions.returned !== 1 ||
instructionWindow.instructions_scanned < 1
instructionWindow.instructions?.length === 0 ||
instructionWindow.limitations.length === 0
)
throw new Error(
"Ghidra read_function_instructions failed its bounded fast-path contract",
"Ghidra read_function_instructions failed its complete fast-path contract",
);
assertEntryCallGraph({ branch, indirect, main, callees, callers });
const { xrefOwners, xrefOwnerFailures } = await resolveXrefOwners(
@@ -119,7 +120,14 @@ export async function verifyDebugFunctionOperations(
const denseSwitchDossier = await functionCall(client, "analyze_function", {
procedure: denseSwitchProcedure.address,
});
assertDenseSwitchDossier(denseSwitchDossier, denseSwitchProcedure.address);
if (process.platform === "linux" && process.arch === "x64")
assertDenseSwitchDossier(denseSwitchDossier, denseSwitchProcedure.address);
else
assertDossier(denseSwitchDossier, {
address: denseSwitchProcedure.address,
requireAssembly: true,
requireMultiBlock: true,
});
assertIndirectDossier(indirectDossier, leaf.address);
const { cancellation, timeout } = await verifyRequestCancellationAndTimeout(
@@ -135,8 +143,7 @@ export async function verifyDebugFunctionOperations(
switch: dossierSummary(switchDossier),
dense_switch: dossierSummary(denseSwitchDossier),
instruction_window: {
returned: instructionWindow.instructions.returned,
truncated: instructionWindow.instructions.truncated,
returned: instructionWindow.instructions.length,
},
cancellation,
timeout,
@@ -157,8 +164,6 @@ async function collectEntryFunctionData(client, entry) {
functionCall(client, "read_function_instructions", {
document: null,
procedure: entry.value,
offset: 0,
limit: 1,
}),
functionCall(client, "procedure_pseudo_code", {
document: null,
@@ -260,7 +265,6 @@ async function analyzeSwitchDossier(client, switchProcedure) {
address: switchProcedure.address,
requireAssembly: true,
requireMultiBlock: true,
requireJumpTable: true,
});
return dossier;
}
@@ -292,8 +296,10 @@ function assertIndirectDossier(indirectDossier, leafAddress) {
throw new Error(
"Ghidra dossier falsely resolved a targetless callback as the fixture leaf",
);
if (!/\bcall\b/iu.test(indirectDossier.assembly.join("\n")))
throw new Error("Ghidra indirect-call fixture lost its computed call site");
if (!/\b(?:call|blr|blx)\b/iu.test(indirectDossier.assembly.join("\n")))
throw new Error(
"Ghidra indirect-call fixture lost its architecture-specific call instruction",
);
}
async function verifyRequestCancellationAndTimeout(client, entry) {
@@ -307,17 +313,13 @@ async function verifyRequestCancellationAndTimeout(client, entry) {
if (cancelled.ok || cancelled.error.kind !== "cancelled")
throw new Error("Ghidra established-request cancellation drifted");
const timedOut = await client.callTool(
"procedure_info",
{ document: null, procedure: entry.address },
{ timeoutMs: 0 },
);
const timedOut = await client.ping({ timeoutMs: 0 });
if (timedOut.ok || timedOut.error.kind !== "timeout")
throw new Error("Ghidra established-request deadline drifted");
throw new Error("Ghidra expired ping deadline drifted");
return {
cancellation: "cancelled-before-wire",
timeout: "expired-before-wire",
ping_deadline: "expired-before-wire",
};
}
@@ -370,7 +372,9 @@ export async function verifyStrippedFunctionOperations(client, entryString) {
requireAssembly: true,
});
if (matchesSymbol(dossier.procedure.name, "rea_ghidra_inventory_entry"))
throw new Error("Ghidra stripped dossier invented a source symbol");
throw new Error(
`Ghidra stripped dossier retained a source symbol: ${JSON.stringify(dossier.procedure)}`,
);
return dossierSummary(dossier);
}
+17 -42
View File
@@ -1,6 +1,6 @@
import { parseGhidraInventoryResult } from "../dist/ghidra/GhidraInventoryValues.js";
import { findValue, symbolTail } from "./verify-real-ghidra-assertions.mjs";
import { findValue, matchesSymbol } from "./verify-real-ghidra-assertions.mjs";
import {
verifyCrossFormatOperations,
verifyDebugFunctionOperations,
@@ -20,28 +20,9 @@ export async function call(client, operation, parameters) {
}
export async function allItems(client, operation, parameters) {
const items = [];
let offset = 0;
let total;
while (true) {
const page = await call(client, operation, {
...parameters,
offset,
limit: 500,
});
if (typeof page !== "object" || page === null || Array.isArray(page))
throw new Error(`${operation} did not return a page`);
items.push(...page.items);
total ??= page.total;
if (page.total !== total)
throw new Error(`${operation} total changed during immutable paging`);
if (!page.has_more) break;
if (page.next_offset === null || page.next_offset <= offset)
throw new Error(`${operation} returned a non-advancing page`);
offset = page.next_offset;
}
if (items.length !== total)
throw new Error(`${operation} pagination was not exhaustive`);
const items = await call(client, operation, parameters);
if (!Array.isArray(items))
throw new Error(`${operation} did not return its complete inventory`);
return items;
}
@@ -104,11 +85,9 @@ export async function verifyInventoryOperations({
pattern: String.raw`^REA_GHIDRA_(?:INVENTORY_ENTRY|LEAF_VALUE)$`,
mode: "regex",
case_sensitive: true,
offset: 0,
limit: 100,
document: null,
});
if (stringSearch.total !== 2 || stringSearch.items.length !== 2)
if (!Array.isArray(stringSearch) || stringSearch.length !== 2)
throw new Error("Ghidra regex string search drifted");
const stringItem = strings.find(
(item) => item.value === "REA_GHIDRA_INVENTORY_ENTRY",
@@ -118,12 +97,11 @@ export async function verifyInventoryOperations({
const filteredStrings = await call(client, "list_strings", {
document: null,
address: stringItem.address,
offset: 0,
limit: 500,
});
if (
filteredStrings.total !== 1 ||
filteredStrings.items[0]?.address !== stringItem.address
!Array.isArray(filteredStrings) ||
filteredStrings.length !== 1 ||
filteredStrings[0]?.address !== stringItem.address
)
throw new Error("Ghidra exact-address string filter drifted");
@@ -164,7 +142,7 @@ async function verifyDebugInventoryCore({
document: null,
address: entry.address,
});
if (symbolTail(addressName) !== "rea_ghidra_inventory_entry")
if (!matchesSymbol(addressName, "rea_ghidra_inventory_entry"))
throw new Error("Ghidra primary address-name resolution drifted");
const resolvedAddress = await call(client, "procedure_address", {
document: null,
@@ -183,29 +161,26 @@ async function verifyDebugInventoryCore({
pattern: "rea_ghidra_inventory_",
mode: "literal",
case_sensitive: true,
offset: 0,
limit: 1,
document: null,
});
if (
procedureSearch.total < 2 ||
procedureSearch.items.length !== 1 ||
!procedureSearch.has_more ||
procedureSearch.next_offset !== 1
!Array.isArray(procedureSearch) ||
procedureSearch.length < 2 ||
!procedureSearch.some((item) =>
matchesSymbol(item.value, "rea_ghidra_inventory_entry"),
)
)
throw new Error("Ghidra literal procedure-search pagination drifted");
throw new Error("Ghidra literal procedure search drifted");
const name = names.find((item) => item.address === entry.address);
if (name === undefined)
throw new Error("Ghidra entry name probe is unavailable");
const filteredNames = await call(client, "list_names", {
document: null,
address: entry.address,
offset: 0,
limit: 500,
});
if (
filteredNames.total < 1 ||
!filteredNames.items.some((item) => item.value === name.value)
!Array.isArray(filteredNames) ||
!filteredNames.some((item) => item.value === name.value)
)
throw new Error("Ghidra exact-address name filter drifted");
const functionAnalysis = await verifyDebugFunctionOperations(client, {
+2 -6
View File
@@ -6,7 +6,6 @@ import { fileURLToPath } from "node:url";
import { resolveGhidraAnalysisProfile } from "../dist/ghidra/GhidraAnalysisProfile.js";
import { GhidraClient } from "../dist/ghidra/GhidraClient.js";
import { GHIDRA_DECOMPILE_REQUEST_TIMEOUT_MS } from "../dist/ghidra/GhidraDefaults.js";
import {
GHIDRA_FUNCTION_OPERATIONS,
parseGhidraFunctionInput,
@@ -45,7 +44,7 @@ const installation = inspectGhidraInstallation({
: { javaHome: process.env.JAVA_HOME }),
});
if (
!installation.available ||
installation.status !== "available" ||
installation.analyzeHeadlessPath === null ||
installation.providerVersion !== SUPPORTED_GHIDRA_VERSION
)
@@ -90,7 +89,6 @@ const client = new GhidraClient({
transport: "authenticated-loopback-tcp",
providerVersion: SUPPORTED_GHIDRA_VERSION,
profileDigest: profile.value.profile.digest,
requestTimeoutMs: GHIDRA_DECOMPILE_REQUEST_TIMEOUT_MS,
});
let coordinates;
@@ -211,9 +209,7 @@ async function inventory(operation, parameters) {
async function functionOperation(operation, parameters) {
const input = parseGhidraFunctionInput(operation, parameters);
if (!input.ok) throw input.error;
const called = await client.callTool(operation, input.value, {
timeoutMs: GHIDRA_DECOMPILE_REQUEST_TIMEOUT_MS,
});
const called = await client.callTool(operation, input.value);
if (!called.ok) throw called.error;
const result = parseGhidraFunctionResult(operation, called.value);
if (!result.ok) throw result.error;
+219 -86
View File
@@ -47,13 +47,22 @@ const installation = inspectGhidraInstallation({
? {}
: { javaHome: process.env.JAVA_HOME }),
});
if (!installation.available || installation.analyzeHeadlessPath === null)
if (
installation.status !== "available" ||
installation.analyzeHeadlessPath === null
)
throw new Error(
`Ghidra installation is unavailable: ${JSON.stringify(installation)}`,
);
if (installation.providerVersion !== SUPPORTED_GHIDRA_VERSION)
throw new Error("Ghidra provider version commitment drifted");
const crossFormat = process.argv.includes("--cross-format");
const aarch64JumpTableOnly = process.argv.includes("--aarch64-jump-table");
const expectedNativeTarget = nativeFixtureTarget(
process.platform,
process.arch,
);
const fixtureRoot = await mkdtemp(join(tmpdir(), "rea-ghidra-fixtures-"));
const sourcePath = fileURLToPath(
new URL("../tests/conformance/ghidra/inventory.c", import.meta.url),
@@ -71,82 +80,135 @@ const machObjectPath = join(fixtureRoot, "rea-ghidra-cross-x86_64.o");
const malformedPath = join(fixtureRoot, "rea-ghidra-malformed");
const compiler = process.env.REA_CC ?? "cc";
const clang = process.env.REA_CLANG ?? "clang";
const lld = process.env.REA_LLD ?? "ld.lld";
const lldLink = process.env.REA_LLD_LINK ?? "lld-link";
const lane = crossFormat
? "cross-format"
: aarch64JumpTableOnly
? "AArch64 jump-table"
: "host-format";
const toolchain = new Map([[compiler, "host fixture compiler"]]);
if (crossFormat || aarch64JumpTableOnly)
toolchain.set(clang, "cross-format clang compiler");
if (crossFormat) {
toolchain.set(lld, "LLVM LLD linker");
toolchain.set(lldLink, "Windows PE linker");
}
const crossTarget = crossFormat
? "aarch64-linux-gnu, x86_64-pc-windows-msvc, x86_64-apple-darwin"
: aarch64JumpTableOnly
? "aarch64-linux-gnu"
: `${expectedNativeTarget.format}/${expectedNativeTarget.architecture}`;
for (const [command, role] of toolchain) {
try {
await exec(command, [command === lldLink ? "/?" : "--version"]);
} catch (cause) {
throw new Error(
`Ghidra ${lane} verification cannot run for target ${crossTarget}: required ${role} '${command}' is unavailable or failed its preflight.`,
{ cause },
);
}
}
try {
const common = ["-O0", "-g", "-fno-inline", "-fno-pie", "-no-pie"];
const common = ["-O0", "-g", "-fno-inline"];
if (expectedNativeTarget.format === "elf") common.push("-fno-pie", "-no-pie");
await exec(compiler, [...common, sourcePath, "-o", debugPath]);
await exec(compiler, [...common, "-s", sourcePath, "-o", strippedPath]);
await exec(clang, [
"--target=aarch64-linux-gnu",
"-O0",
"-g",
"-fno-inline",
"-fno-pie",
"-nostdlib",
"-static",
"-fuse-ld=lld",
crossFormatSourcePath,
"-Wl,-e,rea_cross_start",
"-o",
arm64ElfPath,
]);
await exec(clang, [
"--target=x86_64-pc-windows-msvc",
"-O0",
"-gcodeview",
"-fno-inline",
"-c",
crossFormatSourcePath,
"-o",
peObjectPath,
]);
await exec(lldLink, [
"/entry:rea_cross_start",
"/subsystem:console",
"/nodefaultlib",
"/export:rea_cross_entry",
`/implib:${peImportLibraryPath}`,
`/out:${pePath}`,
peObjectPath,
]);
await exec(clang, [
"--target=x86_64-apple-darwin",
"-O0",
"-g",
"-fno-inline",
"-c",
crossFormatSourcePath,
"-o",
machObjectPath,
]);
const strippedFlags = [...common, "-s"];
if (expectedNativeTarget.format === "mach-o")
strippedFlags.push("-fvisibility=hidden");
await exec(compiler, [...strippedFlags, sourcePath, "-o", strippedPath]);
const crossTargets = [];
if (aarch64JumpTableOnly) {
await exec(clang, [
"--target=aarch64-linux-gnu",
"-O2",
"-g",
"-fno-inline",
"-fno-pie",
"-c",
crossFormatSourcePath,
"-o",
arm64ElfPath,
]);
crossTargets.push([
arm64ElfPath,
"aarch64-jump-table",
{ format: "elf", architecture: "arm64" },
]);
} else if (crossFormat) {
await exec(clang, [
"--target=aarch64-linux-gnu",
"-O2",
"-g",
"-fno-inline",
"-fno-pie",
"-nostdlib",
"-static",
"-fuse-ld=lld",
crossFormatSourcePath,
"-Wl,-e,rea_cross_start",
"-o",
arm64ElfPath,
]);
await exec(clang, [
"--target=x86_64-pc-windows-msvc",
"-O0",
"-gcodeview",
"-fno-inline",
"-c",
crossFormatSourcePath,
"-o",
peObjectPath,
]);
await exec(lldLink, [
"/entry:rea_cross_start",
"/subsystem:console",
"/nodefaultlib",
"/export:rea_cross_entry",
`/implib:${peImportLibraryPath}`,
`/out:${pePath}`,
peObjectPath,
]);
await exec(clang, [
"--target=x86_64-apple-darwin",
"-O0",
"-g",
"-fno-inline",
"-c",
crossFormatSourcePath,
"-o",
machObjectPath,
]);
crossTargets.push(
[
arm64ElfPath,
"cross-arm64-elf",
{ format: "elf", architecture: "arm64" },
],
[pePath, "cross-x86_64-pe", { format: "pe", architecture: "x86_64" }],
[
machObjectPath,
"cross-x86_64-mach-o",
{ format: "mach-o", architecture: "x86_64" },
],
);
}
await writeFile(malformedPath, Buffer.from("not-a-binary\n", "utf8"));
const debug = await verifyTarget(debugPath, "debug", {
format: "elf",
architecture: "x86_64",
});
const debug = await verifyTarget(debugPath, "debug", expectedNativeTarget);
assertDebugFixture(debug);
const nativeApiCli = await verifyNativeApiCli(debugPath);
const stripped = await verifyTarget(strippedPath, "stripped", {
format: "elf",
architecture: "x86_64",
});
const stripped = await verifyTarget(
strippedPath,
"stripped",
expectedNativeTarget,
);
assertStrippedFixture(stripped);
const arm64Elf = await verifyTarget(arm64ElfPath, "cross-arm64-elf", {
format: "elf",
architecture: "arm64",
});
assertCrossFixture(arm64Elf);
const pe = await verifyTarget(pePath, "cross-x86_64-pe", {
format: "pe",
architecture: "x86_64",
});
assertCrossFixture(pe);
const machObject = await verifyTarget(machObjectPath, "cross-x86_64-mach-o", {
format: "mach-o",
architecture: "x86_64",
});
assertCrossFixture(machObject);
const crossResults = [];
for (const [targetPath, variant, expectedTarget] of crossTargets) {
const result = await verifyTarget(targetPath, variant, expectedTarget);
if (variant !== "aarch64-jump-table") assertCrossFixture(result);
crossResults.push(result);
}
await assertMalformedFixture(malformedPath);
const customPath = process.env.GHIDRA_TARGET_PATH;
@@ -157,16 +219,20 @@ try {
verifier_run: await completeVerifierRun(verifierRun),
ok: true,
provider: { id: "ghidra", version: SUPPORTED_GHIDRA_VERSION },
fixture_sources: [sourcePath, crossFormatSourcePath],
fixtures: [
summary(debug),
summary(stripped),
summary(arm64Elf),
summary(pe),
summary(machObject),
],
verification_lane: aarch64JumpTableOnly
? "aarch64-jump-table"
: crossFormat
? "cross-format"
: "host-native",
fixture_sources:
crossFormat || aarch64JumpTableOnly
? [sourcePath, crossFormatSourcePath]
: [sourcePath],
fixtures: [debug, stripped, ...crossResults].map(summary),
malformed_target: "rejected-before-provider-start",
native_api_cli: nativeApiCli,
native_api_cli: aarch64JumpTableOnly
? (crossResults[0]?.native_api_cli ?? null)
: debug.native_api_cli,
custom_target: custom === null ? null : summary(custom),
cleanup: "complete",
})}\n`,
@@ -175,14 +241,38 @@ try {
await rm(fixtureRoot, { recursive: true, force: true });
}
async function verifyNativeApiCli(targetPath) {
function nativeFixtureTarget(platform, architecture) {
const supportedTargets = {
"darwin-arm64": { format: "mach-o", architecture: "arm64" },
"darwin-x64": { format: "mach-o", architecture: "x86_64" },
"linux-x64": { format: "elf", architecture: "x86_64" },
};
const target = supportedTargets[`${platform}-${architecture}`];
if (target === undefined)
throw new Error(
`The Ghidra verifier does not support a host-native fixture on ${platform}/${architecture}; use a supported Linux x64 or macOS x64/arm64 host.`,
);
return target;
}
async function verifyNativeApiCli(
targetPath,
procedures,
requireDenseJumpTable,
denseSwitchSymbol = "rea_ghidra_inventory_dense_switch",
) {
const denseSwitch = procedures.find(({ value }) =>
value.endsWith(denseSwitchSymbol),
);
if (denseSwitch === undefined)
throw new Error("The Ghidra inventory omitted the dense switch fixture");
const { stdout } = await exec(
process.execPath,
[
"scripts/rea.mjs",
"inspect-native-api",
targetPath,
"rea_ghidra_inventory_dense_switch",
denseSwitch.address,
"--provider",
"ghidra",
"--json",
@@ -198,13 +288,40 @@ async function verifyNativeApiCli(targetPath) {
const denseTable = boundary?.jump_tables?.find(
({ mappings }) => mappings.length > 32,
);
const denseCases = new Set(
denseTable?.mappings.flatMap(({ case_value }) =>
typeof case_value === "number" ? [case_value] : [],
) ?? [],
);
const expectedCases = Array.from({ length: 40 }, (_, index) => index);
const mappingsAreExact = expectedCases.every((caseValue) =>
denseTable?.mappings.some(
(mapping) =>
mapping.case_value === caseValue &&
mapping.confidence === "high" &&
mapping.evidence.some(
({ detail }) =>
detail.includes(`case value ${caseValue} with target`) ||
detail.startsWith(`Case value ${caseValue} indexes byte `),
),
),
);
if (
evidence.operation !== "inspect_native_api" ||
evidence.provider?.id !== "rea-workflow" ||
evidence.analysis_profile?.provider?.id !== "rea-workflow" ||
boundary?.available !== true ||
denseTable === undefined ||
evidence.normalized_result?.residual_unknowns?.length !== 0
boundary?.available !== true
)
throw new Error(
`The shipped inspect-native-api CLI did not return an available boundary: ${stdout}`,
);
if (
requireDenseJumpTable &&
(denseTable === undefined ||
denseCases.size !== denseTable.mappings.length ||
expectedCases.some((caseValue) => !denseCases.has(caseValue)) ||
!mappingsAreExact ||
evidence.normalized_result?.residual_unknowns?.length !== 0)
)
throw new Error(
`The shipped inspect-native-api CLI did not preserve complete dense jump-table output: ${stdout}`,
@@ -212,7 +329,7 @@ async function verifyNativeApiCli(targetPath) {
return {
operation: evidence.operation,
provider: evidence.provider,
mappings_returned: denseTable.mappings.length,
mappings_returned: denseTable?.mappings.length ?? null,
residual_unknowns: evidence.normalized_result.residual_unknowns.length,
};
}
@@ -285,8 +402,23 @@ async function verifyTarget(targetPath, variant, expectedTarget = null) {
document: null,
address: null,
});
const crossArm64Elf =
variant === "cross-arm64-elf" || variant === "aarch64-jump-table";
const nativeApiCli =
variant === "debug" || crossArm64Elf
? await verifyNativeApiCli(
parsedTarget.value.path,
procedures,
crossArm64Elf ||
(expectedNativeTarget.format === "elf" &&
expectedNativeTarget.architecture === "x86_64"),
crossArm64Elf
? "rea_cross_dense_switch"
: "rea_ghidra_inventory_dense_switch",
)
: null;
const probes =
variant === "custom"
variant === "custom" || variant === "aarch64-jump-table"
? null
: await verifyInventoryOperations({
client,
@@ -306,6 +438,7 @@ async function verifyTarget(targetPath, variant, expectedTarget = null) {
names,
strings,
probes,
native_api_cli: nativeApiCli,
};
} finally {
await client.close();
@@ -26,7 +26,7 @@ try {
["list-javascript-runtime-targets", endpoint, "--json"],
environment,
);
const target = listed.normalized_result?.targets?.items?.[0];
const target = listed.normalized_result?.targets?.[0];
if (
listed.operation !== "list_javascript_runtime_targets" ||
typeof target?.target_id !== "string" ||