Files
reverse-engineering-anything/scripts/verify-real-ghidra-checkpoints.mjs
T
morluto dc12e5768b fix(ghidra): let sessions share a checkpointed target (#14856)
* fix(ghidra): report a held checkpoint lease as retryable contention

* fix(ghidra): let sessions share a checkpointed target

Sessions restore a checkpoint into private projects without a lease. The
socket lease is held only while one session publishes, and publication is a
compare-and-set on the source that session started from, so a later save is
refused instead of overwriting another session's edits.

Addresses #14834. Stacked on #14844.

* feat(ghidra): bound the checkpoint save wait with a launch control

REA_GHIDRA_CHECKPOINT_SAVE_WAIT_MS replaces the fixed 30 s wait for another
session's checkpoint publication. Default 30000 ms, floor 50 ms (one lease
poll), maximum 600000 ms.

The value is parsed when REA starts and fixed for a session when its
checkpoint owner is constructed. It is a restart-only launch control in
the numeric limit registry, not a runtime analysis setting, so the MCP
tool catalog is unchanged.

The busy refusal names the control, the applied value, its source and the
range, and binds them as an environment limit. An invalid value is
reported by doctor and registration validation and refuses only a
checkpointed Ghidra session.

* fix(ghidra): keep checkpoint save waits and refusals accurate

- Poll again when a lease probe races the owner's release or another
  waiter's stale-socket recovery instead of failing the save with
  configuration_invalid.
- Release the publication lease even when a staging or superseded file
  removal fails, so a retained cleanup does not block other saves.
- Report an initial analysis overtaken by another session's edits as a
  superseded restore (reopen) rather than as refused edits.
- Carry the save-wait details.limit onto a busy close_binary, through
  AnalysisClientCreation, and document the close-time shape.

* fix(ghidra): report discarded checkpoint edits and end a forced close's save wait

A session whose checkpoint save was refused because another session
published first releases its edits on the next close_binary. That close
now reports it: the result carries checkpoint {status: "discarded",
reason: "superseded", directory}, alongside the snapshot receipt when
snapshot_path was given. Only the close that releases the Program reports
it, so a failed cleanup keeps the refusal and its retry reports instead.
AnalysisClient.close returns an optional EngineCloseReport that the
composite client, BinarySession close and closeWithSnapshot carry to the
close_binary contract; an ordinary close keeps result null.

A graceful close's final save did not observe a forced stop while it
waited for another session's publication lease, so a cancelled request
escalating the close could block for the whole save wait (up to ten
minutes). The escalation now aborts that wait. The abort covers only the
lease wait, the save's cancellation cutoff; once the lease is held the
bounded publication completes, so a committed save is never reported as
failed.

The busy refusal's recovery and the installation guide now state that
REA_GHIDRA_CHECKPOINT_SAVE_WAIT_MS cannot make an MCP client wait longer:
that client's request deadline is separate and unknown to REA. The
refusal keeps its environment details.limit.

* fix(ghidra): tell a contention retry to reopen once the owner saved edits

A session that waited for a checkpoint lease keeps the generation it selected,
so after the owner saves Program edits and closes, repeating the call cannot
succeed. Report that outcome as a typed superseded failure with reopen
recovery instead of a checkpoint-directory configuration error, and say so in
the busy recovery.

* fix(ghidra): report both failures when checkpoint file removal and lease release fail

retryCleanup rethrew a lease release failure before the saved removal
failure became part of the error, so callers saw only the lease. A release
failure alongside a removal failure is now reported with it: one
ProviderCleanupError names both reasons, keeps the pending files and the
retained lease as cleanup resources, and carries both causes. A lone release
failure keeps its own error.

* fix(ghidra): keep close facts and launch causes through composed failures

Completed close facts were dropped wherever a later failure was composed.
A released engine's discard report and a saved snapshot receipt are now
carried by one owner, retainCloseOutcome, which every close composition
calls on its outermost error with the outcomes it composed: the composite
client when a sibling fails after a child released its edits, the session
when file, candidate or bundle cleanup fails after the provider closed, the
process-capture close wrapper, and the Ghidra client when cleanup fails
after its JVM stopped. The report rides the failure as
partial_observation.checkpoint and is not repeated by the retry. This
replaces retainSavedAnalysisSnapshot and the close wrapper's snapshot
extractor.

Only close_binary reports edits released unsaved, so open_binary of another
target, opening app resources, reset_investigation and external mutations
now refuse with capability_unavailable while a client reports them through
the new AnalysisClient.unsavedCloseReport, instead of releasing them
silently.

A launch failure was replaced by a superseded-restore error whenever
another session had saved meanwhile. The launcher now records whether the
failure happened while restoring the checkpoint, and only that failure is
explained as superseded; any other keeps its cause, output and diagnostics.

The busy recovery now says that a repeated call can report a superseded
checkpoint when the other session's save changed it.

* fix(ghidra): deliver the discard report through GhidraProvider and keep refusals typed

GhidraProvider wraps its client in DeferredAnalysisClient, whose
AnalysisClientCreation released the client through a cleanup lease and
returned ok(null), so the real close_binary path dropped the discard
report. The lease entry now keeps the releasing close's report and hands it
to one release outcome; a failed release, a failed inspection cleanup and a
retained creation failure carry it through retainCloseOutcome. The
GhidraProvider client does the same when native AOT cleanup also fails. A
boundary test drives close_binary through GhidraProvider.

A forced close could still publish when its stop arrived while the lease
was being acquired. Acquiring the lease is now the cancellation cutoff:
publish checks the lease signal right after it and stops, and cleanup
releases the lease.

A refused save whose cleanup also failed was wrapped into a generic
adapter error, so the client missed the refusal and kept the staged file
for another impossible save. The checkpoint now keeps its typed refusal
primary and unwrapped, carrying the cleanup failure on it; the client
records the discard and reports the cleanup failure in diagnostics.

* fix(ghidra): report released edits only for refused saves and keep startup cleanup failures

A superseded initial analysis (stage restore) set the same refused-save flag
as a refused edit, so its stopped JVM became a released-unsaved report: the
session claimed discarded edits it never had, and open_binary refused the
reopen its own error asked for. The refusal now states whether it refused
edits (GhidraCheckpointSupersededError.refusesEdits, true only for a save),
and the client records a discard only from that fact. Any refusal still
discards its staged file.

The cleanup failure a checkpoint refusal carries was read at close but not
by the startup session failure factory. Ghidra lifecycle errors that carry a
cleanup failure are now recognized by one guard, isGhidraCleanupCarrier,
used by bindGhidraSessionFailure and the close error alike; the close
diagnostic is renamed carried_cleanup_failure since it covers every
carrier.
2026-11-27 12:03:37 +00:00

541 lines
18 KiB
JavaScript

#!/usr/bin/env node
import { sha256File } from "./lib/verifier-file-sha256.mjs";
import { createVerifierCommands } from "./lib/verify-commands.mjs";
import { createVerifierMcpOwner } from "./lib/verifier-mcp-owner.mjs";
import assert from "node:assert/strict";
import {
copyFile,
mkdir,
readFile,
readdir,
writeFile,
} from "node:fs/promises";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { Client } from "@modelcontextprotocol/client";
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
import {
requireMcpOperationResult,
requireMcpToolError,
} from "./lib/mcp-verifier-results.mjs";
import {
requireCheckpointCliRefusal,
assertCheckpointRefusalPreservesManifest,
} from "./lib/ghidra-checkpoint-refusal.mjs";
import {
createVerifierRun,
completeVerifierRun,
assertVerifierCleanupComplete,
} from "./lib/verifier-run.mjs";
import { VerifierFixture } from "./lib/verifier-fixture.mjs";
import { completeEvidenceClient } from "./lib/complete-evidence.mjs";
if (process.platform === "win32")
throw new Error(
"Owned Ghidra checkpoints currently support Linux/macOS only.",
);
const run = createVerifierRun();
// Ghidra children use the root as HOME and TMPDIR; a plain root admits them on every host.
const workspace = await VerifierFixture.open({
prefix: "rea-ghidra-checkpoints-",
private: false,
});
const root = workspace.path;
const runtime = join(root, "runtime"),
checkpointDirectory = join(root, "checkpoints");
const entrypoint = fileURLToPath(new URL("./rea.mjs", import.meta.url));
const sourcePath = join(root, "fixture.c"),
target = join(root, "checkpoint-fixture");
const env = {
...process.env,
HOME: root,
XDG_CONFIG_HOME: join(root, "config"),
XDG_CACHE_HOME: join(root, "cache"),
XDG_DATA_HOME: join(root, "data"),
TMPDIR: runtime,
JDK_JAVA_OPTIONS: `-Duser.home=${root}`,
REA_ANALYSIS_PROVIDER: "ghidra",
REA_GHIDRA_CHECKPOINT_DIR: checkpointDirectory,
};
for (const name of [
"REA_GHIDRA_PROJECT_PATH",
"REA_GHIDRA_PROGRAM_NAME",
"REA_GHIDRA_SEED_FILE",
"REA_GHIDRA_NATIVEAOT_JAR",
"REA_GHIDRA_LANGUAGE_ID",
"REA_GHIDRA_COMPILER_SPEC_ID",
"REA_GHIDRA_DISABLED_ANALYZERS",
])
delete env[name];
const compilerCommands = await createVerifierCommands();
const report = {
verifier: "ghidra-owned-checkpoints",
phases: [],
target: null,
};
async function phase(name, operation) {
const start = performance.now();
try {
const facts = await operation();
report.phases.push({
name,
status: "verified",
elapsed_ms: Math.round(performance.now() - start),
...facts,
});
} catch (cause) {
report.phases.push({
name,
status: "failed",
elapsed_ms: Math.round(performance.now() - start),
});
throw cause;
}
}
async function cli(procedure, flags = [], path = target) {
try {
const { stdout } = await compilerCommands.exec(
process.execPath,
[
entrypoint,
"decompile",
"--detail",
"complete",
path,
procedure,
"--provider",
"ghidra",
"--json",
...flags,
],
{ env, timeout: 240000, maxBuffer: 16 * 1024 * 1024 },
);
return JSON.parse(stdout);
} catch (cause) {
// The checkpoint refusal helper reads the execFile-shaped stdout and stderr.
if (cause instanceof Error && cause.snapshot?.stdout?.text !== undefined) {
cause.stdout = cause.snapshot.stdout.text;
cause.stderr = cause.snapshot.stderr.text;
}
throw cause;
}
}
async function connect(environment = {}) {
const owner = createVerifierMcpOwner();
const client = completeEvidenceClient(
new Client({
name: "rea-ghidra-checkpoint-verifier",
version: "1",
}),
);
const transport = new StdioClientTransport({
command: process.execPath,
args: [entrypoint, "mcp"],
env: { ...env, ...environment },
stderr: "pipe",
});
transport.stderr?.on("data", () => {});
compilerCommands.adopt(owner, "checkpoint MCP connection");
await owner.open(client, transport);
const raw = (name, args = {}) =>
client.callTool({ name, arguments: args }, { timeout: 240000 });
return {
raw,
call: async (name, args = {}) =>
requireMcpOperationResult(await raw(name, args), name),
close: () => owner.close(),
};
}
let manifestPath;
const manifest = async () => JSON.parse(await readFile(manifestPath, "utf8"));
try {
await mkdir(runtime);
await writeFile(
sourcePath,
`typedef struct CheckpointRecord { int value; int flag; } CheckpointRecord;
__attribute__((noinline)) int rea_checkpoint_leaf(CheckpointRecord *record) { return record->value * 7 + record->flag; }
int main(void) { CheckpointRecord record = { 3, 11 }; return rea_checkpoint_leaf(&record); }
`,
);
// The name and type checks read the fixture's DWARF. A linked Mach-O keeps
// DWARF only in its objects or a dSYM beside it, and REA imports an
// immutable copy of the selected file alone, so on macOS the target is the
// object itself, which carries its DWARF.
await compilerCommands.exec(
"cc",
[
"-O0",
"-g",
"-gdwarf-4",
"-fno-inline",
...(process.platform === "darwin" ? ["-c"] : []),
sourcePath,
"-o",
target,
],
{ timeout: 120_000, maxBuffer: 16 * 1024 * 1024 },
);
const targetDigest = await sha256File(target);
report.target = {
sha256: targetDigest,
source: `self-built C struct/function ${process.platform === "darwin" ? "object" : "executable"} fixture; never executed`,
host: process.platform,
architecture: process.arch,
};
let original, initialManifest;
const snapshotPath = join(root, "analysis-snapshot.json");
await phase(
"a cold MCP session keeps its live Program across initial save and repeated open",
async () => {
const cold = await connect({
REA_GHIDRA_CHECKPOINT_DIR: join(root, "cold-session-checkpoints"),
});
try {
await cold.call("open_binary", { path: target, provider_id: "ghidra" });
await cold.call("procedure_pseudo_code", {
detail: "complete",
procedure: "rea_checkpoint_leaf",
});
const id = (await cold.call("binary_session")).analysis_run.run_id;
await cold.call("annotate_native_function", {
procedure: "rea_checkpoint_leaf",
comment: "cold-session unsaved comment",
});
await cold.call("open_binary", { path: target, provider_id: "ghidra" });
assert.equal(
(await cold.call("binary_session")).analysis_run.run_id,
id,
);
const current = await cold.call("procedure_pseudo_code", {
detail: "complete",
procedure: "rea_checkpoint_leaf",
});
assert.match(JSON.stringify(current), /cold-session unsaved comment/);
await cold.call("close_binary");
return { same_live_run: true, unsaved_metadata_retained: true };
} finally {
await cold.close();
}
},
);
await phase("first analysis creates a checkpoint", async () => {
original = await cli("rea_checkpoint_leaf", ["--snapshot", snapshotPath]);
assert.match(JSON.stringify(original.normalized_result), /value/);
const keys = await readdir(checkpointDirectory);
assert.equal(keys.length, 1);
manifestPath = join(checkpointDirectory, keys[0], "current.json");
initialManifest = await manifest();
assert.equal(initialManifest.target_sha256, targetDigest);
assert.deepEqual(
original.analysis_profile.parameters.owned_checkpoint.state,
{ kind: "initial-analysis" },
);
return {
provider_version: original.provider.version,
response_bytes: Buffer.byteLength(JSON.stringify(original)),
};
});
await phase(
"the first checkpoint publication preserves initial immutable snapshot identity",
async () => {
const cached = await cli("rea_checkpoint_leaf", [
"--snapshot",
snapshotPath,
]);
assert.deepEqual(cached, original);
assert.deepEqual(await manifest(), initialManifest);
return {};
},
);
await phase(
"fresh CLI restores the Program and does not rewrite it",
async () => {
const restored = await cli("rea_checkpoint_leaf");
assert.deepEqual(restored.normalized_result, original.normalized_result);
assert.equal(
restored.analysis_profile.digest,
original.analysis_profile.digest,
);
assert.ok(
restored.limitations.some((value) =>
value.includes(initialManifest.source.sha256),
),
);
assert.deepEqual(await manifest(), initialManifest);
return {
checkpoint_sha256: initialManifest.source.sha256,
response_bytes: Buffer.byteLength(JSON.stringify(restored)),
};
},
);
await phase(
"another path with identical target bytes reuses the same Program",
async () => {
const alias = join(root, "renamed-target");
await copyFile(target, alias);
const restored = await cli("rea_checkpoint_leaf", [], alias);
assert.deepEqual(restored.normalized_result, original.normalized_result);
assert.equal(restored.caller_input_path, alias);
assert.deepEqual(await manifest(), initialManifest);
return {};
},
);
await phase(
"MCP preserves a live run, shares the target with a second session, and refuses its later save",
async () => {
const active = await connect();
try {
await active.call("open_binary", {
path: target,
provider_id: "ghidra",
});
await active.call("procedure_pseudo_code", {
detail: "complete",
procedure: "rea_checkpoint_leaf",
});
const id = (await active.call("binary_session")).analysis_run.run_id;
const other = await connect();
try {
await other.call("open_binary", {
path: target,
provider_id: "ghidra",
});
// Both sessions restore the same generation into private
// projects and answer queries while the other is live.
const shared = await other.call("procedure_pseudo_code", {
detail: "complete",
procedure: "rea_checkpoint_leaf",
});
assert.match(JSON.stringify(shared), /value/);
await other.call("annotate_native_function", {
procedure: "rea_checkpoint_leaf",
comment: "REA checkpoint comment from the later session",
});
await active.call("open_binary", {
path: target,
provider_id: "ghidra",
});
assert.equal(
(await active.call("binary_session")).analysis_run.run_id,
id,
);
await active.call("annotate_native_function", {
procedure: "rea_checkpoint_leaf",
name: "rea_checkpoint_retained",
comment: "REA checkpoint first comment",
});
await active.call("close_binary");
const published = await manifest();
assert.notDeepEqual(published, initialManifest);
// The later session started from the superseded generation: its
// save is refused rather than overwriting the first session's.
const refused = requireMcpToolError(await other.raw("close_binary"));
assert.equal(refused.code, "cleanup_incomplete");
assert.deepEqual(refused.recovery, {
kind: "retry_cleanup",
operation: "close_binary",
});
assert.match(refused.remediation.action, /edits were not saved/);
assert.deepEqual(await manifest(), published);
// The refusal is permanent, so the next close discards and releases.
await other.call("close_binary");
assert.deepEqual(await manifest(), published);
} finally {
await other.close();
}
return {
same_live_run: true,
concurrent_session_answered: true,
later_save_refused: true,
};
} finally {
await active.close();
}
},
);
await phase("new MCP restores edits and remains editable", async () => {
const resumed = await connect();
try {
await resumed.call("open_binary", {
path: target,
provider_id: "ghidra",
});
const analysis = await resumed.call("analyze_function", {
procedure: "rea_checkpoint_retained",
detail: "complete",
});
assert.equal(analysis.procedure.name, "rea_checkpoint_retained");
assert.match(JSON.stringify(analysis), /REA checkpoint first comment/);
assert.match(analysis.pseudocode, /value/);
await resumed.call("annotate_native_function", {
procedure: "rea_checkpoint_retained",
comment: "REA checkpoint second comment",
});
await resumed.call("close_binary");
return { structure_field_preserved: true };
} finally {
await resumed.close();
}
});
await phase("CLI sees the second MCP edit", async () => {
const result = await cli("rea_checkpoint_retained");
assert.match(
JSON.stringify(result.normalized_result),
/REA checkpoint second comment/,
);
return {};
});
await phase(
"an older immutable REA snapshot refuses the changed checkpoint",
async () => {
const refusal = await requireCheckpointCliRefusal(
() => cli("rea_checkpoint_leaf", ["--snapshot", snapshotPath]),
"evidence_integrity_mismatch",
);
assert.ok(refusal.details.binding_mismatch.profile_digest);
return {};
},
);
await phase(
"an edited live Program switches to identical bytes at another path",
async () => {
const active = await connect();
const alias = join(root, "live-alias");
await copyFile(target, alias);
try {
await active.call("open_binary", {
path: target,
provider_id: "ghidra",
});
await active.call("annotate_native_function", {
procedure: "rea_checkpoint_retained",
comment: "REA checkpoint second comment; saved during alias switch",
});
await active.call("open_binary", {
path: alias,
provider_id: "ghidra",
});
const result = await active.call("procedure_pseudo_code", {
detail: "complete",
procedure: "rea_checkpoint_retained",
});
assert.match(JSON.stringify(result), /saved during alias switch/);
await active.call("close_binary");
return { alias_switch_preserved_edits: true };
} finally {
await active.close();
}
},
);
const current = await manifest(),
bytes = await readFile(manifestPath);
await phase(
"target/profile mismatch is refused without replacing the saved state",
async () => {
const attemptedBytes = Buffer.from(
JSON.stringify({ ...current, target_sha256: "0".repeat(64) }),
);
try {
await writeFile(manifestPath, attemptedBytes);
await assertCheckpointRefusalPreservesManifest(
() => cli("rea_checkpoint_retained"),
manifestPath,
attemptedBytes,
);
} finally {
await writeFile(manifestPath, bytes);
}
return {};
},
);
await phase(
"malformed manifest is refused without a fresh import",
async () => {
const attemptedBytes = Buffer.from("{");
try {
await writeFile(manifestPath, attemptedBytes);
await assertCheckpointRefusalPreservesManifest(
() => cli("rea_checkpoint_retained"),
manifestPath,
attemptedBytes,
);
} finally {
await writeFile(manifestPath, bytes);
}
return {};
},
);
await phase(
"corrupt packed data is refused and explicit restoration recovers",
async () => {
const packed = join(
checkpointDirectory,
(await readdir(checkpointDirectory))[0],
current.source.file,
),
backup = join(root, "good.gzf");
await copyFile(packed, backup);
try {
await writeFile(packed, "corrupted packed data");
await requireCheckpointCliRefusal(
() => cli("rea_checkpoint_retained"),
"configuration_invalid",
);
} finally {
await copyFile(backup, packed);
}
const result = await cli("rea_checkpoint_retained");
assert.match(
JSON.stringify(result.normalized_result),
/REA checkpoint second comment/,
);
return {};
},
);
assert.equal(await sha256File(target), targetDigest);
assert.deepEqual(await readdir(runtime), []);
const checkpointFiles = await readdir(
join(checkpointDirectory, (await readdir(checkpointDirectory))[0]),
);
assert.equal(
checkpointFiles.length,
2,
"Only the current manifest and packed Program should remain",
);
report.status = "verified";
} catch (cause) {
report.status = "failed";
report.error = cause instanceof Error ? cause.stack : String(cause);
if (typeof cause?.stdout === "string")
report.failure_stdout = cause.stdout.slice(-12000);
if (typeof cause?.stderr === "string")
report.failure_stderr = cause.stderr.slice(-4000);
process.exitCode = 1;
} finally {
let cleanupVerified = false;
try {
await workspace.closeEarly([() => compilerCommands.close()]);
report.run = await completeVerifierRun(run);
assertVerifierCleanupComplete(report.run.process_lineage);
cleanupVerified = true;
} catch (cause) {
report.cleanup_error = String(cause);
report.retained_workspace = root;
process.exitCode = 1;
}
if (cleanupVerified && report.status === "verified") {
try {
await workspace.release();
} catch (cause) {
report.cleanup_error = String(cause);
report.retained_workspace = root;
process.exitCode = 1;
}
} else if (report.retained_workspace === undefined) {
report.retained_workspace = root;
}
process.stdout.write(JSON.stringify(report, null, 2) + "\n");
}