Files
reverse-engineering-anything/scripts/verify-real-ghidra-switch-controls.mjs
T
f25a0a0599 refactor(verify): run Ghidra verifier commands through the supervised owner (2 of 2) (#12717)
* refactor(verify): run Ghidra verifier commands through the supervised owner (2 of 2)

Route the remaining Ghidra verifier compiler and CLI launches through
createVerifierCommands, close that owner before lineage observation, and
assert the raw arm64 alignment refusal from its structured error.

* fix(verify): stop detached Ghidra verifier commands on interrupt

SIGINT and SIGTERM abort the command owner and the scripts wait for its
cleanup, so a compiler started in its own process group cannot outlive
the verifier.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* fix(verify): stop Ghidra verifier analysis when interrupted

Pass the verifier interruption signal into MCP and Ghidra waits, and stop
waiting for calls that cannot observe it, so SIGINT does not continue the
analysis before cleanup.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* fix(verify): stop the switch evidence probe when the verifier is interrupted

Pass the verifier interruption signal into the detached Ghidra control
probe and end its wait so supervisor.stop() runs before a later SIGKILL.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* fix(verify): observe work already started when a verifier interrupt wins

untilInterrupted now settles the caller's promise after the signal has
already aborted, so a connection started just before the check cannot
reject with nobody listening.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* refactor(verify): share verifier interrupt handling and keep it through release

Move the SIGINT/SIGTERM abort wiring into bindVerifierCommandInterruption.
Handlers stay installed until after fixture release, and untilInterrupted
still observes a promise that was already started.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* fix(verify): keep diagnostic workspaces and stop fixture builds on interrupt

Check the interruption signal after finalization and before the fixture
root is removed. MIPS and RISC-V fixture compilers and readers now run
through the verifier command owner, so SIGTERM aborts them instead of
waiting out their execFile deadline.

Co-authored-by: morluto <morluto@users.noreply.github.com>

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: morluto <morluto@users.noreply.github.com>
2026-11-19 23:29:09 -05:00

180 lines
5.5 KiB
JavaScript

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,
signal,
}) {
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));
if (signal?.aborted) throw signal.reason;
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,
...(signal === undefined ? {} : { signal }),
});
const supervisor = new ProviderProcessSupervisor({
...launch,
ownsProcessLifetime: true,
cleanup: () => cleanupOwnedProcessGroup(launch.ownership),
});
try {
assert.ok(
await waitForExitOrSignal(supervisor, signal),
"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));
}
}
// The caller may suppress SIGINT and SIGTERM. Stop this wait when that signal
// aborts so `finally` can reach supervisor.stop() before a later SIGKILL.
const waitForExitOrSignal = (supervisor, signal) =>
new Promise((resolve, reject) => {
if (signal?.aborted) {
reject(signal.reason);
return;
}
const onAbort = () => reject(signal.reason);
signal?.addEventListener("abort", onAbort, { once: true });
supervisor.waitForExit(120000).then(
(exited) => {
signal?.removeEventListener("abort", onAbort);
resolve(exited);
},
(cause) => {
signal?.removeEventListener("abort", onAbort);
reject(cause);
},
);
});
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"),
);
}