Files
reverse-engineering-anything/scripts/verify-real-ghidra-swift.mjs
T
5c59bdc8a6 feat(ghidra)!: verify the bridge on Ghidra 12.2 (#12081)
* feat(ghidra)!: verify the bridge on Ghidra 12.2

Admit 12.x from minor 2 upward, with 12.2 and JDK 25 as the verified
pair. The bridge now calls the four-argument storage API added in 12.2,
so 12.1.x cannot compile it and is no longer accepted.

BREAKING CHANGE: Ghidra 12.1.x is rejected. Use Ghidra 12.2 or another
12.x build at or above minor 2, and a JDK inside that installation's
declared range (25 or newer for the verified 12.2 build).

* docs(ghidra): point remaining lanes at Ghidra 12.2

The Windows, 6502, and m68k prerequisites still named 12.1.4 and JDK 21,
which the verified-build check now rejects. The bridge compile lane names
the 12.2 jars it actually compiles against.

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

* test(ghidra): admit the JDK the verified install declares

The Java home framing probe still reported JDK 21 while the verified
installation fixture now declares a minimum of 25, so doctor admission
failed before the path framing was checked.

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

* test(ghidra): derive admitted install fixtures from the verified release

Boundary hosts and assertions still named Ghidra 12.1.4 after admission
moved to 12.2, so list_procedures evidence and completed property reads
disagreed with the install the provider actually reported.

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

* fix(ghidra): record the exact 12.2 Clang switch-recovery defect

Ghidra 12.2 stays the verified build. Sessions and decompiler results on
that exact version name upstream issue 9996 and the 12.2.1 fix commit.
Other version strings, including 12.2.1, do not carry the limitation.

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

* test(ghidra): check switch-defect facts instead of the warning sentence

The policy test keeps the structured defect record and checks that the
owning formatter delivers its id, commit, release, and scope fields.

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

* test(browser): name the Playwright launch boundary the lifecycle catalog checks

Main retitled that case with a platform placeholder. The coverage catalog
still required the old literal, so the merged full suite reported a missing
title.

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

* test(browser): point the lifecycle catalog at main's launch title

The merged suite uses main's platform-specific Playwright launch test.
The coverage catalog now names that title, and this branch keeps main's
test body so the merge stays clean.

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

* test(browser): cover the platform launch title on this branch

The lifecycle catalog names main's platform launch title. This branch
now has that quoted test too, so the check passes before and after the
merge.

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

* fix(ghidra): record the exact 12.2 masked byte-switch defect

Ghidra 12.2 leaves an AArch64 and-0xff byte-offset switch unrecovered.
Exact 12.2 sessions now cite open upstream issue 10154, and the AArch64
lane expects that jump table to stay unrecovered.

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

* test(browser): keep one platform launch environment check

The second launch test repeated the selected environment check. The
remaining test is the parameterized title, and the launcher forwards
SYSTEMROOT on win32 so that assertion holds.

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

* fix(ghidra): keep the open switch defect on admitted builds

The exact-version check cleared ghidra-10154 on every build except 12.2.
That defect stays on admitted releases until one is known to fix it.
ghidra-9996 still clears after the exact 12.2 build.

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

* style(docs): format the Ghidra testing-lane table

The AArch64 jump-table row wrapped past the formatter width and failed
static checks.

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

* test(ghidra): give the masked switch its full byte range

The unrecovered oracle now uses 256 readable table bytes, and the same
object must still recover its compare-bounded switch.

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

* docs(website): point Ghidra setup at 12.2 and JDK 25

The public setup pages still told new users to install Ghidra 12.1.4 and
JDK 21, which this release rejects. Changed setup sentences are extracted
and left untranslated so those editions use the English page.

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

* docs(website): keep catalog edits to the changed setup strings

The catalog check compares active message ids, not a full rewrite.
Restore the previous catalogs and update only the Ghidra 12.2 setup
strings, leaving their translations empty.

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

* fix(ghidra): apply the closed switch defect from the parsed patch

12.2, 12.2.0, and 12.2.0 with a suffix all precede 12.2.1, so they keep
ghidra-9996. The masked-switch table lists all 256 byte entries.

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

* fix(ghidra): share the AArch64 switch fixture compiler invocation

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: morluto <morluto@users.noreply.github.com>
2026-11-18 16:06:51 -05:00

414 lines
13 KiB
JavaScript

#!/usr/bin/env node
import { withVerifierCleanup } from "./lib/verifier-cleanup.mjs";
import assert from "node:assert/strict";
import { execFile } from "node:child_process";
import { copyFile, mkdir, readFile, readdir } from "node:fs/promises";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { promisify } from "node:util";
import { Client } from "@modelcontextprotocol/client";
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
import { inspectVerifierGhidraInstallation } from "./lib/ghidra-installation-inspection.mjs";
import { cleanupOwnedProcessGroup } from "../dist/process/ProcessOwnership.js";
import {
ProviderProcessSupervisor,
spawnOwnedProviderProcess,
} from "../dist/process/ProviderProcess.js";
import { requireMcpOperationResult } from "./lib/mcp-verifier-results.mjs";
import { createVerifierRun, completeVerifierRun } from "./lib/verifier-run.mjs";
import {
VerifierFixture,
withVerifierFixture,
} from "./lib/verifier-fixture.mjs";
const execute = promisify(execFile);
const run = createVerifierRun();
const installation = await inspectVerifierGhidraInstallation({
environment: process.env,
installDir: process.env.GHIDRA_INSTALL_DIR,
javaHome: process.env.JAVA_HOME,
});
if (process.platform !== "darwin" || installation.status !== "available")
throw new Error(
"verify:ghidra:swift requires macOS, Ghidra 12.2 with its native decompiler, and JDK 25; set GHIDRA_INSTALL_DIR and JAVA_HOME.",
);
try {
await execute("swiftc", ["--version"], { timeout: 10_000 });
} catch (cause) {
throw new Error(
"verify:ghidra:swift requires the host Swift compiler (swiftc).",
{ cause },
);
}
// Ghidra children use the workspace as TMPDIR; a plain root admits them on every host.
const rootFixture = await VerifierFixture.open({
prefix: "rea-ghidra-swift-",
private: false,
});
const root = rootFixture.path;
const client = new Client({ name: "ghidra-swift-verifier", version: "1" });
const transport = new StdioClientTransport({
command: process.execPath,
args: [fileURLToPath(new URL("./rea.mjs", import.meta.url)), "mcp"],
env: Object.fromEntries(
Object.entries(process.env).filter(([, value]) => value !== undefined),
),
stderr: "pipe",
});
const source = fileURLToPath(
new URL("../tests/conformance/swift/type-inventory.swift", import.meta.url),
);
const literalSource = fileURLToPath(
new URL("../tests/conformance/swift/string-literals.swift", import.meta.url),
);
const binary = join(root, "swift-inventory");
const literalBinary = join(root, "swift-literals");
// swiftc rejects assembly inputs, so each source is assembled to an object first.
const literalObjects = ["decoder-safeguards.S", "unresolved-string-jump.s"].map(
(name) => ({
source: fileURLToPath(
new URL(`../tests/conformance/swift/${name}`, import.meta.url),
),
object: join(root, name.replace(/\.[sS]$/u, ".o")),
}),
);
const reports = [];
let connected = false;
let verifierRun;
let literalReport;
let decoderCleaned = true;
// The root is removed only after the session, client and decoder confirm.
rootFixture.releaseAfter(async () => {
if (connected) await call("close_binary", {});
});
rootFixture.releaseAfter(() => client.close());
rootFixture.releaseAfter(() => transport.close());
rootFixture.releaseAfter(async () => {
assert.equal(decoderCleaned, true, "Owned decoder cleanup remains pending");
verifierRun = await completeVerifierRun(run);
assert.equal(verifierRun.process_lineage.status, "verified");
assert.deepEqual(verifierRun.process_lineage.descendants, []);
});
await withVerifierFixture(rootFixture, async () => {
await execute("swiftc", ["-O", "-g", source, "-o", binary], {
timeout: 60_000,
});
await mkdir(join(root, "copied"));
const copied = join(root, "copied", "swift-inventory");
await copyFile(binary, copied);
// Decoding covers AArch64 register pairs, so build that slice on any Mac host.
for (const { source: assembly, object } of literalObjects)
await execute(
"xcrun",
[
"clang",
"-target",
"arm64-apple-macosx13.0",
"-c",
assembly,
"-o",
object,
],
{ timeout: 60_000 },
);
await execute(
"swiftc",
[
"-O",
"-target",
"arm64-apple-macosx13.0",
literalSource,
...literalObjects.map(({ object }) => object),
"-o",
literalBinary,
],
{ timeout: 60_000 },
);
await verifyDecoderSafeguards();
await client.connect(transport);
connected = true;
for (const [variant, path] of [
["debug", binary],
["without-dsym", copied],
]) {
await call("open_binary", { path, provider_id: "ghidra" });
await withVerifierCleanup(async () => {
const procedures = await call("list_procedures", {});
const inventory = await call("analyze_swift_types", {});
assert(
inventory.total > 0,
"Swift procedures disappeared from the inventory",
);
assert(
inventory.categories.other.count > 0,
"Top-level Swift symbols were lost",
);
const structs = await call("analyze_swift_types", {
category: "structs",
});
assert(
structs.categories.structs.count > 0,
"Modern struct symbols were lost",
);
const metadata = await call("analyze_swift_types", {
category: "structs",
pattern: "VMa",
});
assert.equal(
metadata.total,
2,
"Pair and Scorer metadata accessors must both be classified",
);
const pair = await call("analyze_swift_types", {
category: "structs",
pattern: "Pair",
});
assert(pair.total > 0, "Literal name filtering lost Pair symbols");
const unresolved = await call("analyze_swift_types", {
category: "structs",
pattern: "swiftIndirect",
});
assert(
unresolved.unclassified.length > 0,
"Unsupported categories must remain explicit",
);
const entries = Object.values(inventory.categories).flatMap(
(category) => category.items,
);
assert.equal(
new Set(entries.map((entry) => entry.name)).size,
inventory.total,
);
assert(
!entries.some(
(entry) =>
entry.name === "entry" || entry.name === "_swift_allocObject",
),
);
for (const entry of entries)
assert(
procedures.some(
(procedure) =>
procedure.address === entry.address &&
procedure.value === entry.name,
),
);
reports.push({
variant,
total: inventory.total,
structs: structs.total,
metadata_accessors: metadata.total,
unclassified: inventory.unclassified.length,
});
}, [() => call("close_binary", {})]);
}
literalReport = await verifyStringLiterals();
});
console.log(
JSON.stringify(
{
ok: true,
provider: "ghidra",
fixtures: reports,
swift_string_literals: literalReport,
verifier_run: verifierRun,
},
null,
2,
),
);
async function call(name, arguments_) {
const response = await client.callTool(
{ name, arguments: arguments_ },
{ timeout: 180_000 },
);
if (name === "analyze_swift_types")
assert.ok(response.structuredContent, `${name} omitted structured result`);
return requireMcpOperationResult(response, name);
}
// Literal text lives only in register constants, so it must come from the decoded pairs.
async function verifyStringLiterals() {
await call("open_binary", { path: literalBinary, provider_id: "ghidra" });
return withVerifierCleanup(async () => {
const procedures = await call("list_procedures", {});
const expected = {
smallLiteral: [["SleepDisabled", "small"]],
largeLiteral: [["The power setting could not be changed.", "large"]],
unicodeLiterals: [
["café", "small"],
["Résumé of the naïve décor, written twice", "large"],
],
emptyAndControlLiterals: [
["", "small"],
["tab\there", "small"],
],
returnedLiteral: [["Holding awake", "small"]],
};
const decoded = {};
for (const [name, literals] of Object.entries(expected)) {
const procedure = procedures.find(({ value }) => value.includes(name));
assert(procedure, `${name} is missing from the procedure inventory`);
const dossier = await call("analyze_function", {
procedure: procedure.address,
detail: "complete",
});
const observed = dossier.swift_string_literals;
assert(Array.isArray(observed), `${name} recorded no Swift literals`);
assert.deepEqual(dossier.swift_string_literal_omissions, []);
assert.deepEqual(
observed.map(({ value, representation }) => [value, representation]),
literals,
);
for (const literal of observed) {
assert.deepEqual(literal.registers, ["x0", "x1"]);
assert.equal(
literal.address === null,
literal.representation === "small",
`${literal.value} storage does not match its representation`,
);
}
decoded[name] = observed.length;
}
const unresolvedJump = procedures.find(({ value }) =>
value.includes("rea_unresolved_string_jump"),
);
assert(
unresolvedJump,
"unresolved jump fixture is missing from the procedure inventory",
);
const unresolvedDossier = await call("analyze_function", {
procedure: unresolvedJump.address,
detail: "complete",
});
assert.deepEqual(unresolvedDossier.swift_string_literals, []);
assert.deepEqual(
unresolvedDossier.swift_string_literal_omissions.map(
({ reason }) => reason,
),
["unresolved_jump"],
);
decoded.unresolvedStringJump =
unresolvedDossier.swift_string_literal_omissions.length;
return decoded;
}, [() => call("close_binary", {})]);
}
// Exercise the Java producer inside an ephemeral Ghidra database. The explicit
// budget seam makes exhaustion deterministic without exposing a runtime option.
async function verifyDecoderSafeguards() {
const scripts = join(root, "decoder-scripts");
await mkdir(scripts);
const bridgeSources = fileURLToPath(
new URL("../bridge/ghidra/", import.meta.url),
);
for (const name of await readdir(bridgeSources)) {
if (name.endsWith(".java"))
await copyFile(join(bridgeSources, name), join(scripts, name));
}
await copyFile(
fileURLToPath(
new URL(
"../tests/conformance/swift/ReaSwiftDecoderRegressions.java",
import.meta.url,
),
),
join(scripts, "ReaSwiftDecoderRegressions.java"),
);
const report = join(root, "decoder-safeguards.txt");
await runDecoderProbe(scripts, report);
assert.equal(
await readFile(report, "utf8"),
"REA_SWIFT_DECODER_SAFEGUARDS_OK\n",
);
}
async function runDecoderProbe(scripts, report) {
const controller = new AbortController();
let interrupt;
const interrupted = new Promise((resolve) => {
interrupt = () => {
controller.abort(new Error("Swift decoder probe interrupted"));
resolve(false);
};
});
process.on("SIGINT", interrupt);
process.on("SIGTERM", interrupt);
let supervisor;
let launch;
try {
launch = await spawnOwnedProviderProcess({
command: installation.analyzeHeadlessPath,
arguments: [
root,
"decoder-regressions",
"-import",
literalBinary,
"-scriptPath",
scripts,
"-postScript",
"ReaSwiftDecoderRegressions.java",
report,
"-deleteProject",
"-max-cpu",
"2",
],
runId: run.run_id,
expectedCommand: null,
env: { JAVA_HOME: installation.javaHome },
signal: controller.signal,
});
decoderCleaned = false;
supervisor = new ProviderProcessSupervisor(
{
...launch,
ownsProcessLifetime: true,
cleanup: () => cleanupOwnedProcessGroup(launch.ownership),
},
{ maxDiagnosticBytes: 8 * 1024 * 1024 },
);
assert.ok(
await Promise.race([supervisor.waitForExit(120_000), interrupted]),
controller.signal.aborted
? "Swift decoder probe interrupted"
: "Swift decoder probe timed out",
);
assert.ok(
await supervisor.waitForOutputClose(1_000),
"Swift decoder probe output did not close",
);
const snapshot = supervisor.snapshot();
assert.equal(
snapshot.exitCode,
0,
`${snapshot.stdout.text}\n${snapshot.stderr.text}`,
);
assert.ok(
!snapshot.diagnosticTruncated,
"Swift decoder probe exceeded its diagnostic capacity",
);
} finally {
try {
if (supervisor !== undefined) {
const stopped = await supervisor.stop();
decoderCleaned = stopped.status === "verified-cleanup";
assert.ok(
decoderCleaned,
`Owned Ghidra cleanup incomplete; retained ${root}: ${JSON.stringify(stopped)}`,
);
} else if (launch !== undefined) {
const stopped = await cleanupOwnedProcessGroup(launch.ownership);
decoderCleaned = stopped.cleaned;
assert.ok(
decoderCleaned,
`Owned Ghidra cleanup incomplete; retained ${root}: ${JSON.stringify(stopped)}`,
);
}
} finally {
process.off("SIGINT", interrupt);
process.off("SIGTERM", interrupt);
}
}
}