fix(ghidra): recover evidenced switch cases and default targets (#579)
Correlate typed labels with recovered block entries and one indirect dispatch. Preserve ambiguous and nonexact integer associations as unknown with raw diagnostics. Expose defaults separately, collect backing load metadata, and invalidate old profiles. Add independent compiler-byte CLI/MCP acceptance and actual Ghidra model controls. Assisted-by: Kogasa (gensokyo-skills:kogasa-surprise-testing) Assisted-by: Suika (gensokyo-skills:suika-scatter-gather-planning)
This commit is contained in:
@@ -1,3 +1,5 @@
|
||||
import { hasTypedSwitchEvidence } from "./verify-real-ghidra-switch-assertions.mjs";
|
||||
|
||||
import { access } from "node:fs/promises";
|
||||
|
||||
import { parseBinaryTarget } from "../dist/application/BinaryTargetResolver.js";
|
||||
@@ -107,6 +109,14 @@ export function assertDenseSwitchDossier(dossier, address) {
|
||||
);
|
||||
if (
|
||||
denseTable === undefined ||
|
||||
denseTable.default_targets.length !== 1 ||
|
||||
denseTable.default_targets[0].confidence !== "high" ||
|
||||
!hasTypedSwitchEvidence(
|
||||
denseTable.default_targets[0].evidence,
|
||||
"Typed default label",
|
||||
denseTable.default_targets[0].target_address,
|
||||
denseTable.dispatch_address,
|
||||
) ||
|
||||
denseTable.mappings.some(
|
||||
({ target_address: target, evidence }) =>
|
||||
!/^0x[0-9a-f]+$/u.test(target) ||
|
||||
@@ -146,9 +156,8 @@ function assertNativeApiBoundary(observed, requireJumpTable) {
|
||||
) &&
|
||||
mappings.length > 0 &&
|
||||
mappings.every(
|
||||
({ target_address: target, data_addresses: addresses, evidence }) =>
|
||||
({ target_address: target, evidence }) =>
|
||||
/^0x[0-9a-f]+$/u.test(target) &&
|
||||
addresses.every((address) => /^0x[0-9a-f]+$/u.test(address)) &&
|
||||
evidence.some(({ kind }) => kind === "jump-table"),
|
||||
),
|
||||
)
|
||||
|
||||
@@ -613,3 +613,37 @@ export async function verifyNativeValueTrace(client, procedures, target) {
|
||||
const global = requireProcedure(names, "rea_ghidra_inventory_global");
|
||||
return verifyNativeValueE2e(target, entry.address, global.address);
|
||||
}
|
||||
|
||||
/** Match the source default's -1 assignment in supported native compiler encodings. */
|
||||
export async function verifyDenseDefaultReturn(client, targetAddress) {
|
||||
const instruction = await functionCall(client, "inspect_native_instruction", {
|
||||
address: targetAddress,
|
||||
});
|
||||
if (
|
||||
instruction.status !== "decoded" ||
|
||||
!isDefaultMinusOneAssignment(instruction)
|
||||
)
|
||||
throw new Error(
|
||||
`Dense default target lacks the source -1 assignment (x86 register/stack MOV or AArch64 W-register MOVN): ${JSON.stringify(instruction)}`,
|
||||
);
|
||||
return {
|
||||
target_address: targetAddress,
|
||||
instruction_bytes: instruction.bytes,
|
||||
};
|
||||
}
|
||||
|
||||
function isDefaultMinusOneAssignment(instruction) {
|
||||
if (instruction.architecture.startsWith("x86:"))
|
||||
return (
|
||||
instruction.bytes === "b8ffffffff" ||
|
||||
/^c745[0-9a-f]{2}ffffffff$/u.test(instruction.bytes)
|
||||
);
|
||||
if (
|
||||
instruction.architecture.startsWith("AARCH64:") &&
|
||||
instruction.bytes.length === 8
|
||||
) {
|
||||
const word = Buffer.from(instruction.bytes, "hex").readUInt32LE();
|
||||
return (word & 0xffffffe0) === 0x12800000;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,420 @@
|
||||
import assert from "node:assert/strict";
|
||||
|
||||
/** Verify numeric/default evidence against independent compiler-byte/source oracles. */
|
||||
export function assertSwitchBoundary(boundary, fixture) {
|
||||
assert.equal(boundary.available, true);
|
||||
assert.equal(boundary.provenance, "ghidra-high-function");
|
||||
assert.ok(
|
||||
boundary.limitations.length > 0,
|
||||
"Provider observation scope must remain explicit",
|
||||
);
|
||||
if (!fixture.table) {
|
||||
assert.deepEqual(
|
||||
boundary.jump_tables,
|
||||
[],
|
||||
"Comparison-only control fabricated a jump table",
|
||||
);
|
||||
return { numeric_cases: 0, default_targets: 0, unknowns: 0 };
|
||||
}
|
||||
assert.equal(
|
||||
boundary.jump_tables.length,
|
||||
1,
|
||||
`Expected one source-owned switch: ${fixture.name}`,
|
||||
);
|
||||
const table = boundary.jump_tables[0];
|
||||
if (fixture.allow_unsigned_32_labels === true) {
|
||||
assert.equal(fixture.discriminator_size_bytes, 4);
|
||||
assert.equal(boundary.parameters.length, 1);
|
||||
assert.equal(boundary.parameters[0].data_type, "undefined4");
|
||||
assert.equal(boundary.parameters[0].size_bytes, 4);
|
||||
assert.equal(boundary.parameters[0].confidence, "low");
|
||||
}
|
||||
assert.equal(
|
||||
table.dispatch_address,
|
||||
fixture.dispatch_address,
|
||||
"Dispatch does not identify the independently byte-proven indirect jump",
|
||||
);
|
||||
const numericCount = assertCaseMappings(table, fixture);
|
||||
assert.equal(
|
||||
table.default_targets.length,
|
||||
1,
|
||||
"Default target must be separate from numeric cases/unknowns",
|
||||
);
|
||||
const defaultTarget = table.default_targets[0];
|
||||
assert.equal(
|
||||
defaultTarget.target_address,
|
||||
fixture.default_address,
|
||||
"Default does not enter the independently byte-proven default block",
|
||||
);
|
||||
assert.equal(defaultTarget.confidence, "high");
|
||||
assert.ok(
|
||||
hasTypedSwitchEvidence(
|
||||
defaultTarget.evidence,
|
||||
"Typed default label",
|
||||
defaultTarget.target_address,
|
||||
table.dispatch_address,
|
||||
),
|
||||
"Default omitted typed label/block/dispatch evidence",
|
||||
);
|
||||
assert.ok(
|
||||
table.data_sources.some(
|
||||
({ address, entry_size_bytes: size, entry_count: count }) =>
|
||||
address === fixture.table_address &&
|
||||
size === 8 &&
|
||||
count === fixture.slots.length,
|
||||
),
|
||||
"Recovered backing-table observation disagrees with independently decoded bytes",
|
||||
);
|
||||
return {
|
||||
numeric_cases: numericCount,
|
||||
default_targets: 1,
|
||||
unknowns: fixture.unsafe_integer ? table.mappings.length : 0,
|
||||
};
|
||||
}
|
||||
|
||||
function assertCaseMappings(table, fixture) {
|
||||
const explicit = fixture.slots.filter(({ explicit_case }) => explicit_case);
|
||||
const numeric = table.mappings.filter(
|
||||
({ case_value }) => typeof case_value === "number",
|
||||
);
|
||||
if (fixture.unsafe_integer) {
|
||||
assert.equal(
|
||||
numeric.length,
|
||||
0,
|
||||
"Unsafe integer labels were rounded, truncated or replaced by table indices",
|
||||
);
|
||||
assert.equal(
|
||||
table.mappings.length,
|
||||
fixture.blocks.length,
|
||||
"Unsafe labels must retain every independently byte-proven target",
|
||||
);
|
||||
assert.deepEqual(
|
||||
table.mappings.map(({ target_address }) => target_address).sort(),
|
||||
fixture.blocks.map(({ address }) => address).sort(),
|
||||
);
|
||||
for (const mapping of table.mappings) {
|
||||
assert.equal(mapping.case_value, null);
|
||||
assert.ok(
|
||||
["low", "medium"].includes(mapping.confidence),
|
||||
"Unknown numeric association must not claim high confidence",
|
||||
);
|
||||
assertUnknownTargetEvidence(
|
||||
mapping.evidence,
|
||||
mapping.target_address,
|
||||
table.dispatch_address,
|
||||
);
|
||||
}
|
||||
} else {
|
||||
assert.equal(
|
||||
table.mappings.length,
|
||||
numeric.length,
|
||||
"Complete public fixture has unresolved/misclassified numeric case rows",
|
||||
);
|
||||
const matchedValues = new Set();
|
||||
for (const mapping of numeric) {
|
||||
const expected = fixture.slots.find(
|
||||
({ value }) =>
|
||||
value === mapping.case_value ||
|
||||
(fixture.allow_unsigned_32_labels === true &&
|
||||
Number(BigInt.asUintN(32, BigInt(value))) === mapping.case_value),
|
||||
);
|
||||
assert.ok(expected, `Fabricated out-of-range case ${mapping.case_value}`);
|
||||
assert.ok(
|
||||
!matchedValues.has(expected.value),
|
||||
"Duplicate discriminator bit pattern",
|
||||
);
|
||||
matchedValues.add(expected.value);
|
||||
assert.equal(
|
||||
mapping.target_address,
|
||||
expected.target_address,
|
||||
`Wrong case→target ${fixture.name}:${mapping.case_value}`,
|
||||
);
|
||||
assert.equal(mapping.confidence, "high");
|
||||
assert.ok(
|
||||
hasTypedSwitchEvidence(
|
||||
mapping.evidence,
|
||||
`Typed case value ${mapping.case_value}`,
|
||||
mapping.target_address,
|
||||
table.dispatch_address,
|
||||
),
|
||||
"Numeric mapping omitted typed case/block/dispatch evidence",
|
||||
);
|
||||
}
|
||||
for (const { value } of explicit)
|
||||
assert.ok(
|
||||
matchedValues.has(value),
|
||||
`Omitted source case ${fixture.name}:${value}`,
|
||||
);
|
||||
}
|
||||
return numeric.length;
|
||||
}
|
||||
|
||||
/** Match typed labels to their explicitly evidenced block and unique dispatch. */
|
||||
export function hasTypedSwitchEvidence(evidence, label, target, dispatch) {
|
||||
return evidence.some(
|
||||
({ kind, source, detail }) =>
|
||||
kind === "jump-table" &&
|
||||
source === "ghidra-clang-case-token" &&
|
||||
typeof detail === "string" &&
|
||||
detail.trim().length > 0 &&
|
||||
detail.startsWith(
|
||||
`${label} belongs to the p-code block starting at recovered target ${target};`,
|
||||
) &&
|
||||
detail.includes(
|
||||
`its unique indirect dispatch predecessor is ${dispatch}.`,
|
||||
),
|
||||
);
|
||||
}
|
||||
function assertUnknownTargetEvidence(evidence, target, dispatch) {
|
||||
assert.ok(
|
||||
evidence.some(
|
||||
({ kind, source, detail }) =>
|
||||
kind === "jump-table" &&
|
||||
source === "ghidra-high-function" &&
|
||||
typeof detail === "string" &&
|
||||
detail.trim().length > 0 &&
|
||||
detail.startsWith(
|
||||
`Ghidra recovered target ${target} at dispatch ${dispatch},`,
|
||||
) &&
|
||||
detail.includes(
|
||||
"no unambiguous, exactly representable case label or default relationship",
|
||||
),
|
||||
),
|
||||
"Unknown mapping omitted recovered target/dispatch and unavailable label evidence",
|
||||
);
|
||||
}
|
||||
|
||||
/** Fault-injected guard controls only; these records are not real provider acceptance. */
|
||||
export function assertSwitchOracleControls(fixtures) {
|
||||
const fixture = fixtures.find(({ name }) => name === "holes_shared");
|
||||
assert.ok(fixture);
|
||||
const boundary = guardBoundary(fixture);
|
||||
const evidence = boundary.jump_tables[0].default_targets[0].evidence;
|
||||
assertSwitchBoundary(boundary, fixture);
|
||||
const faults = {
|
||||
consistently_wrong_dispatch: (table) => {
|
||||
const previous = table.dispatch_address;
|
||||
table.dispatch_address = "0xff";
|
||||
for (const row of [...table.mappings, ...table.default_targets])
|
||||
for (const evidence of row.evidence)
|
||||
evidence.detail = evidence.detail.replace(previous, "0xff");
|
||||
},
|
||||
wrong_numeric_evidence_source: (table) => {
|
||||
table.mappings[0].evidence[0].source = "unrelated-source";
|
||||
},
|
||||
wrong_default_evidence_source: (table) => {
|
||||
table.default_targets[0].evidence[0].source = "ghidra-high-function";
|
||||
},
|
||||
empty_default_evidence_detail: (table) => {
|
||||
table.default_targets[0].evidence[0].detail = "";
|
||||
},
|
||||
wrong_typed_dispatch: (table) => {
|
||||
table.mappings[0].evidence[0].detail =
|
||||
table.mappings[0].evidence[0].detail.replace(
|
||||
`predecessor is ${fixture.dispatch_address}.`,
|
||||
"predecessor is 0xff.",
|
||||
);
|
||||
},
|
||||
missing_default: (table) => {
|
||||
table.default_targets = [];
|
||||
},
|
||||
default_misclassified_as_unknown: (table) => {
|
||||
table.default_targets = [];
|
||||
table.mappings.push({
|
||||
case_value: null,
|
||||
target_address: fixture.default_address,
|
||||
confidence: "low",
|
||||
evidence,
|
||||
});
|
||||
},
|
||||
wrong_shared_target: (table) => {
|
||||
table.mappings.find(({ case_value }) => case_value === 3).target_address =
|
||||
fixture.blocks[0].address;
|
||||
},
|
||||
positional_label_guess: (table) => {
|
||||
table.mappings.find(({ case_value }) => case_value === 9).case_value = 99;
|
||||
},
|
||||
omitted_case: (table) => {
|
||||
table.mappings = table.mappings.filter(
|
||||
({ case_value }) => case_value !== 2,
|
||||
);
|
||||
},
|
||||
wrong_default_target: (table) => {
|
||||
table.default_targets[0].target_address = fixture.blocks[0].address;
|
||||
},
|
||||
wrong_backing_extent: (table) => {
|
||||
table.data_sources[0].entry_count--;
|
||||
},
|
||||
};
|
||||
for (const [name, inject] of Object.entries(faults)) {
|
||||
const damaged = structuredClone(boundary);
|
||||
inject(damaged.jump_tables[0]);
|
||||
assert.throws(
|
||||
() => assertSwitchBoundary(damaged, fixture),
|
||||
undefined,
|
||||
`Oracle failed to reject ${name}`,
|
||||
);
|
||||
}
|
||||
const negative = fixtures.find(({ name }) => name === "negative");
|
||||
assert.ok(negative);
|
||||
const signed = guardBoundary(negative);
|
||||
assertSwitchBoundary(signed, negative);
|
||||
signed.jump_tables[0].mappings = signed.jump_tables[0].mappings.map(
|
||||
(mapping) => ({ ...mapping, case_value: Math.abs(mapping.case_value) }),
|
||||
);
|
||||
assert.throws(
|
||||
() => assertSwitchBoundary(signed, negative),
|
||||
undefined,
|
||||
"Lost unary minus in a signed case label",
|
||||
);
|
||||
const unsignedControls = assertStrippedSignednessControls(negative);
|
||||
const comparison = fixtures.find(({ name }) => name === "comparison");
|
||||
assert.ok(comparison);
|
||||
assertSwitchBoundary({ ...boundary, jump_tables: [] }, comparison);
|
||||
assert.throws(
|
||||
() => assertSwitchBoundary(boundary, comparison),
|
||||
undefined,
|
||||
"Fabricated table for comparison-only control",
|
||||
);
|
||||
return [
|
||||
...assertUnsafeGuardControls(fixtures),
|
||||
...unsignedControls,
|
||||
...Object.keys(faults),
|
||||
"signed_label_magnitude",
|
||||
"fabricated_comparison_table",
|
||||
];
|
||||
}
|
||||
|
||||
function assertStrippedSignednessControls(fixture) {
|
||||
const strippedFixture = { ...fixture, allow_unsigned_32_labels: true };
|
||||
const signed = guardBoundary(fixture);
|
||||
const unsigned = structuredClone(signed);
|
||||
unsigned.parameters = [
|
||||
{ data_type: "undefined4", size_bytes: 4, confidence: "low" },
|
||||
];
|
||||
for (const mapping of unsigned.jump_tables[0].mappings) {
|
||||
const previous = mapping.case_value;
|
||||
mapping.case_value = Number(BigInt.asUintN(32, BigInt(previous)));
|
||||
mapping.evidence[0].detail = mapping.evidence[0].detail.replace(
|
||||
`Typed case value ${previous} `,
|
||||
`Typed case value ${mapping.case_value} `,
|
||||
);
|
||||
}
|
||||
assertSwitchBoundary(unsigned, strippedFixture);
|
||||
assert.throws(
|
||||
() => assertSwitchBoundary(unsigned, fixture),
|
||||
undefined,
|
||||
"Known signed source labels were replaced by unsigned values",
|
||||
);
|
||||
const faults = {
|
||||
stripped_signedness_promoted: (record) => {
|
||||
record.parameters[0].confidence = "high";
|
||||
},
|
||||
stripped_wrong_discriminator_width: (record) => {
|
||||
record.parameters[0].size_bytes = 8;
|
||||
},
|
||||
stripped_wrong_bit_pattern_target: (record) => {
|
||||
record.jump_tables[0].mappings[0].target_address =
|
||||
fixture.blocks[1].address;
|
||||
},
|
||||
stripped_duplicate_bit_pattern: (record) => {
|
||||
record.jump_tables[0].mappings.push(signed.jump_tables[0].mappings[0]);
|
||||
},
|
||||
};
|
||||
for (const [name, inject] of Object.entries(faults)) {
|
||||
const damaged = structuredClone(unsigned);
|
||||
inject(damaged);
|
||||
assert.throws(
|
||||
() => assertSwitchBoundary(damaged, strippedFixture),
|
||||
undefined,
|
||||
`Oracle failed to reject ${name}`,
|
||||
);
|
||||
}
|
||||
return ["known_signed_labels_must_stay_signed", ...Object.keys(faults)];
|
||||
}
|
||||
|
||||
function assertUnsafeGuardControls(fixtures) {
|
||||
const unsafe = fixtures.find(({ name }) => name === "unsafe_integer");
|
||||
assert.ok(unsafe);
|
||||
const unknown = guardBoundary(unsafe, true);
|
||||
assertSwitchBoundary(unknown, unsafe);
|
||||
for (const labels of [
|
||||
unsafe.slots.map(({ value }) => Number(BigInt(value) & 0xffffffffn)),
|
||||
unsafe.slots.map((_, index) => index),
|
||||
unsafe.slots.map(({ value }) => Number(value)),
|
||||
]) {
|
||||
const fabricated = structuredClone(unknown);
|
||||
fabricated.jump_tables[0].mappings = fabricated.jump_tables[0].mappings.map(
|
||||
(mapping, index) => ({
|
||||
...mapping,
|
||||
case_value: labels[index],
|
||||
confidence: "high",
|
||||
}),
|
||||
);
|
||||
assert.throws(
|
||||
() => assertSwitchBoundary(fabricated, unsafe),
|
||||
undefined,
|
||||
"Unsafe label rounding/truncation/index fallback accepted",
|
||||
);
|
||||
}
|
||||
return [
|
||||
"unsafe_label_signed32_truncation",
|
||||
"unsafe_label_index_fallback",
|
||||
"unsafe_label_float_rounding",
|
||||
];
|
||||
}
|
||||
function guardBoundary(fixture, unresolved = false) {
|
||||
const typedEvidence = (label, target) => [
|
||||
{
|
||||
kind: "jump-table",
|
||||
source: "ghidra-clang-case-token",
|
||||
detail: `${label} belongs to the p-code block starting at recovered target ${target}; its unique indirect dispatch predecessor is ${fixture.dispatch_address}.`,
|
||||
},
|
||||
];
|
||||
const unknownEvidence = (target) => [
|
||||
{
|
||||
kind: "jump-table",
|
||||
source: "ghidra-high-function",
|
||||
detail: `Ghidra recovered target ${target} at dispatch ${fixture.dispatch_address}, but no unambiguous, exactly representable case label or default relationship was available.`,
|
||||
},
|
||||
];
|
||||
return {
|
||||
available: true,
|
||||
provenance: "ghidra-high-function",
|
||||
limitations: ["Guard control only"],
|
||||
jump_tables: [
|
||||
{
|
||||
dispatch_address: fixture.dispatch_address,
|
||||
data_sources: [
|
||||
{
|
||||
address: fixture.table_address,
|
||||
entry_size_bytes: 8,
|
||||
entry_count: fixture.slots.length,
|
||||
},
|
||||
],
|
||||
mappings: fixture.slots.map(({ value, target_address }, index) => ({
|
||||
case_value: unresolved ? null : value,
|
||||
target_address,
|
||||
confidence: unresolved
|
||||
? index % 2 === 0
|
||||
? "medium"
|
||||
: "low"
|
||||
: "high",
|
||||
evidence: unresolved
|
||||
? unknownEvidence(target_address)
|
||||
: typedEvidence(`Typed case value ${value}`, target_address),
|
||||
})),
|
||||
default_targets: [
|
||||
{
|
||||
target_address: fixture.default_address,
|
||||
confidence: "high",
|
||||
evidence: typedEvidence(
|
||||
"Typed default label",
|
||||
fixture.default_address,
|
||||
),
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { createHash } from "node:crypto";
|
||||
import { mkdir, readFile, realpath } from "node:fs/promises";
|
||||
import { dirname, join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const EXPECTED_CHECKS = [
|
||||
"positive_decimal",
|
||||
"unsigned32_literal_not_rewritten",
|
||||
"negative_embedded_token_sign",
|
||||
"negative_hex",
|
||||
"zero",
|
||||
"magnitude_mismatch_unknown",
|
||||
"signed_encoding_is_not_magnitude",
|
||||
"symbol_label_unknown",
|
||||
"compound_label_unknown",
|
||||
"safe_positive_boundary",
|
||||
"safe_negative_boundary",
|
||||
"safe_hex_boundary",
|
||||
"unsafe_positive_unknown",
|
||||
"unsafe_negative_unknown",
|
||||
"unsigned64_unknown",
|
||||
"no_dispatch_not_attributed",
|
||||
"unique_dispatch_block_start",
|
||||
"instruction_offset_is_not_destination",
|
||||
"wrong_dispatch_not_attributed",
|
||||
"target_not_in_table_not_attributed",
|
||||
"signed_and_positive_distinct",
|
||||
"shared_destination_keeps_all_labels",
|
||||
"default_ordinary_off_is_role",
|
||||
"default_and_numeric_can_share_target",
|
||||
"unsafe64_target_preserved_unknown",
|
||||
"magnitude_mismatch_target_preserved_unknown",
|
||||
"conflicting_value_retracted",
|
||||
"conflicting_destinations_preserved_unknown",
|
||||
"api_first_dispatch_is_insufficient",
|
||||
"multiple_dispatches_rejected",
|
||||
"multiple_dispatch_target_preserved_unknown",
|
||||
"multiple_dispatch_rejected_for_other_table",
|
||||
];
|
||||
|
||||
/** Exercise actual bridge methods on detached Ghidra objects with owned process cleanup. */
|
||||
export async function verifySwitchEvidenceControls({
|
||||
installation,
|
||||
entrypoint,
|
||||
target,
|
||||
workspace,
|
||||
runId,
|
||||
}) {
|
||||
const { spawnOwnedProviderProcess, ProviderProcessSupervisor } = await import(
|
||||
"../dist/process/ProviderProcess.js"
|
||||
);
|
||||
const { cleanupOwnedProcessGroup } = await import(
|
||||
"../dist/process/ProcessOwnership.js"
|
||||
);
|
||||
const bridge = await realpath(
|
||||
join(dirname(entrypoint), "../bridge/ghidra/ReaGhidraBridge.java"),
|
||||
);
|
||||
const fixtures = fileURLToPath(
|
||||
new URL("../tests/conformance/ghidra", import.meta.url),
|
||||
);
|
||||
const project = join(workspace, "guard-project");
|
||||
await mkdir(project);
|
||||
const sourceDigest = digest(await readFile(bridge));
|
||||
const targetDigest = digest(await readFile(target));
|
||||
const launch = await spawnOwnedProviderProcess({
|
||||
command: installation.analyzeHeadlessPath,
|
||||
arguments: [
|
||||
project,
|
||||
"SwitchEvidence",
|
||||
"-import",
|
||||
target,
|
||||
"-noanalysis",
|
||||
"-readOnly",
|
||||
"-scriptPath",
|
||||
`${fixtures};${dirname(bridge)}`,
|
||||
"-postScript",
|
||||
"ReaSwitchEvidenceProbe.java",
|
||||
bridge,
|
||||
"-deleteProject",
|
||||
],
|
||||
runId,
|
||||
expectedCommand: null,
|
||||
});
|
||||
const supervisor = new ProviderProcessSupervisor({
|
||||
...launch,
|
||||
ownsProcessLifetime: true,
|
||||
cleanup: () => cleanupOwnedProcessGroup(launch.ownership),
|
||||
});
|
||||
try {
|
||||
assert.ok(
|
||||
await supervisor.waitForExit(120000),
|
||||
"Production switch guard lane exceeded its 120-second headless deadline",
|
||||
);
|
||||
const snapshot = supervisor.snapshot();
|
||||
const output = `${snapshot.stdout.text}\n${snapshot.stderr.text}`;
|
||||
assert.equal(snapshot.exitCode, 0, output);
|
||||
const reports = [
|
||||
...output.matchAll(/REA_SWITCH_EVIDENCE_PROBE_JSON (\{[^\r\n]*\})/gu),
|
||||
];
|
||||
assert.equal(
|
||||
reports.length,
|
||||
1,
|
||||
`Expected one production guard report: ${output}`,
|
||||
);
|
||||
assert.ok(output.includes("REA_SWITCH_EVIDENCE_PROBE_COMPLETE"), output);
|
||||
const report = JSON.parse(reports[0][1]);
|
||||
assertControlReport(
|
||||
report,
|
||||
bridge,
|
||||
sourceDigest,
|
||||
installation.providerVersion,
|
||||
);
|
||||
assert.equal(
|
||||
digest(await readFile(bridge)),
|
||||
sourceDigest,
|
||||
"Guard modified bridge source",
|
||||
);
|
||||
assert.equal(
|
||||
digest(await readFile(target)),
|
||||
targetDigest,
|
||||
"Guard modified imported fixture bytes",
|
||||
);
|
||||
return report;
|
||||
} finally {
|
||||
const stopped = await supervisor.stop();
|
||||
supervisor.dispose();
|
||||
assert.notEqual(stopped.status, "incomplete", JSON.stringify(stopped));
|
||||
}
|
||||
}
|
||||
|
||||
function digest(bytes) {
|
||||
return createHash("sha256").update(bytes).digest("hex");
|
||||
}
|
||||
|
||||
function assertControlReport(report, bridge, sourceDigest, version) {
|
||||
assert.ok(
|
||||
typeof report === "object" && report !== null && !Array.isArray(report),
|
||||
);
|
||||
assert.equal(report.schema_version, 1);
|
||||
assert.equal(report.status, "passed");
|
||||
assert.equal(report.ghidra_version, version);
|
||||
assert.equal(report.bridge_source_path, bridge);
|
||||
assert.equal(report.bridge_source_sha256, sourceDigest);
|
||||
assert.ok(Array.isArray(report.checks));
|
||||
assert.deepEqual(
|
||||
[...report.checks].sort(),
|
||||
[...EXPECTED_CHECKS].sort(),
|
||||
"Production guard did not execute every required case",
|
||||
);
|
||||
assert.equal(report.check_count, EXPECTED_CHECKS.length);
|
||||
assert.ok(
|
||||
typeof report.scope === "string" &&
|
||||
report.scope.includes("detached Ghidra model objects"),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,348 @@
|
||||
#!/usr/bin/env node
|
||||
import assert from "node:assert/strict";
|
||||
import { execFile } from "node:child_process";
|
||||
import { createHash } from "node:crypto";
|
||||
import {
|
||||
copyFile,
|
||||
mkdir,
|
||||
mkdtemp,
|
||||
readFile,
|
||||
readdir,
|
||||
rm,
|
||||
writeFile,
|
||||
} from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { parseArgs, promisify } from "node:util";
|
||||
import { Client } from "@modelcontextprotocol/client";
|
||||
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
|
||||
import {
|
||||
buildSwitchSource,
|
||||
switchSymbolOracle,
|
||||
assertCompiledSwitchOracle,
|
||||
} from "../tests/conformance/ghidra/switch-fixture.mjs";
|
||||
import {
|
||||
assertSwitchBoundary,
|
||||
assertSwitchOracleControls,
|
||||
} from "./verify-real-ghidra-switch-assertions.mjs";
|
||||
import { createVerifierRun, completeVerifierRun } from "./lib/verifier-run.mjs";
|
||||
import { verifySwitchEvidenceControls } from "./verify-real-ghidra-switch-controls.mjs";
|
||||
|
||||
// Narrow compiler-shape lane; no cross compiler or game artifact prerequisites.
|
||||
const { values } = parseArgs({
|
||||
options: {
|
||||
"compiler-oracle-only": { type: "boolean", default: false },
|
||||
entrypoint: { type: "string" },
|
||||
},
|
||||
});
|
||||
const compilerOnly = values["compiler-oracle-only"];
|
||||
const entrypoint =
|
||||
values.entrypoint === undefined
|
||||
? fileURLToPath(new URL("./rea.mjs", import.meta.url))
|
||||
: resolve(values.entrypoint);
|
||||
assert.ok(
|
||||
process.platform === "linux" && process.arch === "x64",
|
||||
"Ghidra switch compiler lane requires Linux x64; macOS/Windows and cross targets use their separate provider lanes.",
|
||||
);
|
||||
const exec = promisify(execFile);
|
||||
const commands = {
|
||||
gcc: process.env.REA_GCC ?? "gcc",
|
||||
clang: process.env.REA_CLANG ?? "clang",
|
||||
nm: process.env.REA_NM ?? "nm",
|
||||
objdump: process.env.REA_OBJDUMP ?? "objdump",
|
||||
strip: process.env.REA_STRIP ?? "strip",
|
||||
};
|
||||
const versions = {};
|
||||
for (const [role, command] of Object.entries(commands)) {
|
||||
try {
|
||||
const { stdout } = await exec(command, ["--version"]);
|
||||
versions[role] = stdout.split("\n")[0];
|
||||
} catch (cause) {
|
||||
throw new Error(
|
||||
`Ghidra switch compiler lane prerequisite missing: ${role} '${command}'`,
|
||||
{ cause },
|
||||
);
|
||||
}
|
||||
}
|
||||
let installation;
|
||||
if (!compilerOnly) {
|
||||
const { inspectGhidraInstallation } = await import(
|
||||
"../dist/ghidra/GhidraInstallation.js"
|
||||
);
|
||||
assert.ok(
|
||||
process.env.GHIDRA_INSTALL_DIR,
|
||||
"Ghidra switch lane prerequisite missing: GHIDRA_INSTALL_DIR (bring your own)",
|
||||
);
|
||||
installation = inspectGhidraInstallation({
|
||||
installDir: process.env.GHIDRA_INSTALL_DIR,
|
||||
...(process.env.JAVA_HOME === undefined
|
||||
? {}
|
||||
: { javaHome: process.env.JAVA_HOME }),
|
||||
});
|
||||
assert.equal(installation.status, "available", JSON.stringify(installation));
|
||||
}
|
||||
const run = createVerifierRun();
|
||||
const workspace = await mkdtemp(join(tmpdir(), "rea-switch-proof-"));
|
||||
const runtime = join(workspace, "runtime");
|
||||
await mkdir(runtime);
|
||||
const source = join(workspace, "switch.c");
|
||||
await writeFile(source, buildSwitchSource());
|
||||
const flags = ["-O2", "-g", "-fno-pie", "-no-pie"];
|
||||
const results = [];
|
||||
let productionControls = null;
|
||||
try {
|
||||
for (const compiler of ["gcc", "clang"]) {
|
||||
const original = join(workspace, `${compiler}-optimized`);
|
||||
await exec(commands[compiler], [...flags, source, "-o", original]);
|
||||
const bytes = await readFile(original);
|
||||
const { stdout: symbols } = await exec(commands.nm, ["-n", original]);
|
||||
const { stdout: disassembly } = await exec(commands.objdump, [
|
||||
"-d",
|
||||
original,
|
||||
]);
|
||||
const fixtures = assertCompiledSwitchOracle(
|
||||
bytes,
|
||||
switchSymbolOracle(symbols),
|
||||
disassembly,
|
||||
);
|
||||
const oracleFaultControls = assertSwitchOracleControls(fixtures);
|
||||
if (!compilerOnly && productionControls === null) {
|
||||
productionControls = await verifySwitchEvidenceControls({
|
||||
installation,
|
||||
entrypoint,
|
||||
target: original,
|
||||
workspace,
|
||||
runId: run.run_id,
|
||||
});
|
||||
assert.equal(
|
||||
digest(await readFile(original)),
|
||||
digest(bytes),
|
||||
"Guard changed compiler-oracled input",
|
||||
);
|
||||
}
|
||||
const stripped = join(workspace, `${compiler}-stripped`);
|
||||
await copyFile(original, stripped);
|
||||
await exec(commands.strip, ["--strip-all", stripped]);
|
||||
// Byte/physical target oracle survives removal of the names that REA could use.
|
||||
assertCompiledSwitchOracle(await readFile(stripped), fixtures, disassembly);
|
||||
for (const [variant, path] of [
|
||||
["optimized", original],
|
||||
["stripped", stripped],
|
||||
]) {
|
||||
const sha256 = digest(await readFile(path));
|
||||
const observation = compilerOnly
|
||||
? null
|
||||
: await verifyTarget(path, sha256, fixtures, variant);
|
||||
assert.equal(
|
||||
digest(await readFile(path)),
|
||||
sha256,
|
||||
"REA analysis changed original compiled fixture",
|
||||
);
|
||||
results.push({
|
||||
compiler,
|
||||
variant,
|
||||
oracle_fault_controls: oracleFaultControls,
|
||||
sha256,
|
||||
compiler_oracle: fixtures.map(
|
||||
({
|
||||
name,
|
||||
address,
|
||||
dispatch_address,
|
||||
table_address,
|
||||
slots,
|
||||
default_address,
|
||||
}) => ({
|
||||
name,
|
||||
address,
|
||||
dispatch_address,
|
||||
table_address,
|
||||
slots,
|
||||
default_address,
|
||||
}),
|
||||
),
|
||||
observation,
|
||||
});
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
try {
|
||||
assert.deepEqual(
|
||||
(await readdir(runtime)).filter((name) => name.startsWith("rea-ghidra-")),
|
||||
[],
|
||||
"Owned Ghidra runtime survived close",
|
||||
);
|
||||
} finally {
|
||||
await rm(workspace, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
const lifecycle = await completeVerifierRun(run);
|
||||
if (lifecycle.process_lineage.status === "verified")
|
||||
assert.deepEqual(lifecycle.process_lineage.descendants, []);
|
||||
process.stdout.write(
|
||||
`${JSON.stringify({ lane: "linux-x64-compiler-switch", compiler_only: compilerOnly, entrypoint, versions, compiler_flags: flags, verifier_run: lifecycle, production_controls: productionControls, results, limitations: ["Exact compiler oracle admits absolute 8-byte native x86-64 ELF tables and fails explicitly when a compiler changes lowering.", "Compiled binaries are analyzed read-only; target programs are never executed.", "Comparison-only control proves absence of a fabricated table and preservation of provider limitations, not recovery of C source.", "Detached Ghidra object controls exercise actual bridge methods through reflection; they do not claim naturally compiled ambiguous dispatches.", "CLI/MCP comparison covers switch observations, excluding process-specific Evidence IDs."], cleanup: "complete" })}\n`,
|
||||
);
|
||||
|
||||
function digest(bytes) {
|
||||
return createHash("sha256").update(bytes).digest("hex");
|
||||
}
|
||||
async function verifyTarget(path, sha256, fixtures, variant) {
|
||||
const env = {
|
||||
PATH: process.env.PATH ?? "/usr/bin:/bin",
|
||||
TMPDIR: runtime,
|
||||
REA_LOG_LEVEL: "silent",
|
||||
REA_ANALYSIS_PROVIDER: "ghidra",
|
||||
REA_PROCESS_RUN_ID: run.run_id,
|
||||
GHIDRA_INSTALL_DIR: process.env.GHIDRA_INSTALL_DIR,
|
||||
...(process.env.JAVA_HOME === undefined
|
||||
? {}
|
||||
: { JAVA_HOME: process.env.JAVA_HOME }),
|
||||
};
|
||||
const transport = new StdioClientTransport({
|
||||
command: process.execPath,
|
||||
args: [entrypoint, "mcp"],
|
||||
env,
|
||||
stderr: "pipe",
|
||||
});
|
||||
const client = new Client({ name: "rea-real-switch-proof", version: "1" });
|
||||
let opened = false;
|
||||
let stderr = "";
|
||||
const observations = [];
|
||||
try {
|
||||
await client.connect(transport);
|
||||
transport.stderr?.on("data", (chunk) => {
|
||||
stderr = (stderr + chunk.toString()).slice(-65536);
|
||||
});
|
||||
const target = await call(client, "open_binary", {
|
||||
path,
|
||||
provider: "ghidra",
|
||||
});
|
||||
opened = true;
|
||||
assert.equal(target.sha256, sha256);
|
||||
assert.equal(target.architecture, "x86_64");
|
||||
assert.equal(target.format, "elf");
|
||||
const procedures = await call(client, "list_procedures");
|
||||
for (const fixture of fixtures) {
|
||||
const observationFixture = {
|
||||
...fixture,
|
||||
allow_unsigned_32_labels:
|
||||
variant === "stripped" && fixture.name === "negative",
|
||||
};
|
||||
const procedure = procedures.find(
|
||||
({ address }) => address === fixture.address,
|
||||
);
|
||||
assert.ok(
|
||||
procedure,
|
||||
`Source-owned function at ${fixture.address} not discovered in optimized/stripped fixture`,
|
||||
);
|
||||
const observed = await toolResult(client, "inspect_native_api", {
|
||||
procedure: procedure.address,
|
||||
});
|
||||
assertWorkflowIdentity(observed.evidence, sha256);
|
||||
assert.equal(observed.result.procedure.address, procedure.address);
|
||||
const summary = assertSwitchBoundary(
|
||||
observed.result.boundary,
|
||||
observationFixture,
|
||||
);
|
||||
assert.deepEqual(
|
||||
[...observed.result.residual_unknowns].sort(),
|
||||
expectedResidualUnknowns(observed.result.boundary, fixture).sort(),
|
||||
"Residual unknowns must preserve unresolved ABI types and exactly the expected switch uncertainty",
|
||||
);
|
||||
const cli = await cliSwitchEvidence(
|
||||
entrypoint,
|
||||
path,
|
||||
procedure.address,
|
||||
env,
|
||||
);
|
||||
assertWorkflowIdentity(cli, sha256);
|
||||
assert.equal(cli.normalized_result.procedure.address, procedure.address);
|
||||
assertSwitchBoundary(cli.normalized_result.boundary, observationFixture);
|
||||
assert.deepEqual(
|
||||
cli.normalized_result.boundary.jump_tables,
|
||||
observed.result.boundary.jump_tables,
|
||||
"CLI/MCP switch mappings/defaults/data-source evidence differ",
|
||||
);
|
||||
assert.deepEqual(
|
||||
cli.normalized_result.residual_unknowns,
|
||||
observed.result.residual_unknowns,
|
||||
);
|
||||
observations.push({
|
||||
name: fixture.name,
|
||||
...summary,
|
||||
cli_mcp_equal: true,
|
||||
limitations: observed.result.boundary.limitations,
|
||||
residual_unknowns: observed.result.residual_unknowns,
|
||||
jump_tables: observed.result.boundary.jump_tables,
|
||||
});
|
||||
}
|
||||
return { observations, stderr };
|
||||
} finally {
|
||||
try {
|
||||
if (opened) await call(client, "close_binary");
|
||||
} finally {
|
||||
try {
|
||||
await client.close();
|
||||
} finally {
|
||||
await transport.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
function assertWorkflowIdentity(evidence, sha256) {
|
||||
assert.equal(evidence.subject.digest.sha256, sha256);
|
||||
assert.equal(evidence.operation, "inspect_native_api");
|
||||
assert.equal(evidence.provider.id, "rea-workflow");
|
||||
assert.equal(evidence.analysis_profile.provider.id, "rea-workflow");
|
||||
assert.equal(
|
||||
evidence.analysis_profile.parameters.upstream_analysis_profile.parameters
|
||||
.language_id,
|
||||
"auto-from-header",
|
||||
);
|
||||
}
|
||||
|
||||
function expectedResidualUnknowns(boundary, fixture) {
|
||||
const unknowns = [boundary.return_type, ...boundary.parameters]
|
||||
.filter(({ confidence }) => confidence === "low")
|
||||
.map(
|
||||
({ role, data_type: type }) =>
|
||||
`Can the inferred ${role} type ${type} be confirmed with imported metadata or an ABI probe?`,
|
||||
);
|
||||
if (fixture.unsafe_integer)
|
||||
unknowns.push(
|
||||
`Which source-level case values correspond to every target dispatched at ${boundary.jump_tables[0].dispatch_address}?`,
|
||||
);
|
||||
return [...new Set(unknowns)];
|
||||
}
|
||||
async function toolResult(client, name, arguments_ = {}) {
|
||||
const result = await client.callTool(
|
||||
{ name, arguments: arguments_ },
|
||||
{ timeout: 240000 },
|
||||
);
|
||||
assert.notEqual(result.isError, true, JSON.stringify(result));
|
||||
assert.ok(
|
||||
result.structuredContent && "result" in result.structuredContent,
|
||||
`${name} omitted structured result`,
|
||||
);
|
||||
return result.structuredContent;
|
||||
}
|
||||
async function call(client, name, arguments_ = {}) {
|
||||
return (await toolResult(client, name, arguments_)).result;
|
||||
}
|
||||
|
||||
async function cliSwitchEvidence(entrypoint, path, procedure, env) {
|
||||
const { stdout } = await exec(
|
||||
process.execPath,
|
||||
[
|
||||
entrypoint,
|
||||
"inspect-native-api",
|
||||
path,
|
||||
procedure,
|
||||
"--provider",
|
||||
"ghidra",
|
||||
"--json",
|
||||
],
|
||||
{ env, timeout: 240000, maxBuffer: 16 * 1024 * 1024 },
|
||||
);
|
||||
return JSON.parse(stdout);
|
||||
}
|
||||
@@ -33,8 +33,10 @@ import {
|
||||
verifyInventoryOperations,
|
||||
} from "./verify-real-ghidra-inventory.mjs";
|
||||
import { completeVerifierRun, createVerifierRun } from "./lib/verifier-run.mjs";
|
||||
import { hasTypedSwitchEvidence } from "./verify-real-ghidra-switch-assertions.mjs";
|
||||
|
||||
import {
|
||||
verifyDenseDefaultReturn,
|
||||
verifyNativeTypeLayout,
|
||||
verifyRelativeSwitch,
|
||||
verifyNativeValueTrace,
|
||||
@@ -308,8 +310,7 @@ function nativeFixtureTarget(platform, architecture) {
|
||||
async function verifyNativeApiCli(
|
||||
targetPath,
|
||||
procedures,
|
||||
requireDenseJumpTable,
|
||||
denseSwitchSymbol = "rea_ghidra_inventory_dense_switch",
|
||||
{ requireDenseJumpTable, denseSwitchSymbol, client },
|
||||
) {
|
||||
const denseSwitch = procedures.find(({ value }) =>
|
||||
value.endsWith(denseSwitchSymbol),
|
||||
@@ -349,11 +350,25 @@ async function verifyNativeApiCli(
|
||||
(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 `),
|
||||
),
|
||||
(hasTypedSwitchEvidence(
|
||||
mapping.evidence,
|
||||
`Typed case value ${caseValue}`,
|
||||
mapping.target_address,
|
||||
denseTable.dispatch_address,
|
||||
) ||
|
||||
mapping.evidence.some(
|
||||
({ kind, source, detail }) =>
|
||||
kind === "jump-table" &&
|
||||
typeof detail === "string" &&
|
||||
detail.trim().length > 0 &&
|
||||
((source === "ghidra-high-function" &&
|
||||
detail.includes(
|
||||
`case value ${caseValue} with target ${mapping.target_address}`,
|
||||
)) ||
|
||||
(source === "ghidra-instruction-and-memory" &&
|
||||
detail.startsWith(`Case value ${caseValue} indexes byte `) &&
|
||||
detail.includes(`reaching ${mapping.target_address}.`))),
|
||||
)),
|
||||
),
|
||||
);
|
||||
if (
|
||||
@@ -368,7 +383,20 @@ async function verifyNativeApiCli(
|
||||
if (
|
||||
requireDenseJumpTable &&
|
||||
(denseTable === undefined ||
|
||||
denseCases.size !== denseTable.mappings.length ||
|
||||
denseCases.size !== expectedCases.length ||
|
||||
denseTable.mappings.length !== expectedCases.length ||
|
||||
denseTable.default_targets.length !== 1 ||
|
||||
denseTable.default_targets[0].confidence !== "high" ||
|
||||
!hasTypedSwitchEvidence(
|
||||
denseTable.default_targets[0].evidence,
|
||||
"Typed default label",
|
||||
denseTable.default_targets[0].target_address,
|
||||
denseTable.dispatch_address,
|
||||
) ||
|
||||
denseTable.mappings.some(
|
||||
({ target_address }) =>
|
||||
target_address === denseTable.default_targets[0].target_address,
|
||||
) ||
|
||||
expectedCases.some((caseValue) => !denseCases.has(caseValue)) ||
|
||||
!mappingsAreExact ||
|
||||
evidence.normalized_result?.residual_unknowns?.length !== 0)
|
||||
@@ -376,10 +404,17 @@ async function verifyNativeApiCli(
|
||||
throw new Error(
|
||||
`The shipped inspect-native-api CLI did not preserve complete dense jump-table output: ${stdout}`,
|
||||
);
|
||||
const defaultOracle = requireDenseJumpTable
|
||||
? await verifyDenseDefaultReturn(
|
||||
client,
|
||||
denseTable.default_targets[0].target_address,
|
||||
)
|
||||
: null;
|
||||
return {
|
||||
operation: evidence.operation,
|
||||
provider: evidence.provider,
|
||||
mappings_returned: denseTable?.mappings.length ?? null,
|
||||
default_oracle: defaultOracle,
|
||||
residual_unknowns: evidence.normalized_result.residual_unknowns.length,
|
||||
};
|
||||
}
|
||||
@@ -456,16 +491,16 @@ async function verifyTarget(targetPath, variant, expectedTarget = null) {
|
||||
variant === "cross-arm64-elf" || variant === "aarch64-jump-table";
|
||||
const nativeApiCli =
|
||||
variant === "debug" || crossArm64Elf
|
||||
? await verifyNativeApiCli(
|
||||
parsedTarget.value.path,
|
||||
procedures,
|
||||
crossArm64Elf ||
|
||||
? await verifyNativeApiCli(parsedTarget.value.path, procedures, {
|
||||
requireDenseJumpTable:
|
||||
crossArm64Elf ||
|
||||
(expectedNativeTarget.format === "elf" &&
|
||||
expectedNativeTarget.architecture === "x86_64"),
|
||||
crossArm64Elf
|
||||
denseSwitchSymbol: crossArm64Elf
|
||||
? "rea_cross_dense_switch"
|
||||
: "rea_ghidra_inventory_dense_switch",
|
||||
)
|
||||
client,
|
||||
})
|
||||
: null;
|
||||
const probes = variant.startsWith("relative-")
|
||||
? await verifyRelativeSwitch(
|
||||
|
||||
Reference in New Issue
Block a user