feat(native): admit raw binaries with caller-supplied architecture and entry (#1868)

* feat(native): admit raw binaries with caller-supplied architecture and entry

* fix(native): honor raw-binary preparation and entry identity

* fix(ghidra): stream raw snapshot attestation with cancellation

* fix(native): preserve and validate raw lifecycle entries

---------

Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
This commit is contained in:
Matt Van Horn
2026-10-12 00:06:29 +08:00
committed by GitHub
co-authored by morluto
parent d3e83b0899
commit 7c207c7951
57 changed files with 2453 additions and 336 deletions
@@ -12,6 +12,7 @@ import type { ProgressUpdate } from "../../../../src/application/ProgressReporte
import { ok } from "../../../../src/domain/result.js";
import { GhidraClient } from "../../../../src/ghidra/GhidraClient.js";
import { OwnedFileHandle } from "../../../../src/filesystem/OwnedFileHandle.js";
import { GHIDRA_PROCESS_DIAGNOSTIC_BYTES } from "../../../../src/ghidra/GhidraDiagnostics.js";
import { GhidraHeadlessLauncher } from "../../../../src/ghidra/GhidraLauncher.js";
import type { GhidraDiagnostic } from "../../../../src/ghidra/GhidraClientTypes.js";
@@ -122,12 +123,14 @@ const clientFor = (
readonly transport?: GhidraTransportKind;
readonly runId?: string;
readonly logger?: Logger;
readonly targetPath?: string;
readonly targetSha256?: string;
} = {},
): GhidraClient => {
const client = new GhidraClient({
launcher,
targetPath: fixturePath,
targetSha256: TARGET_SHA256,
targetPath: options.targetPath ?? fixturePath,
targetSha256: options.targetSha256 ?? TARGET_SHA256,
transport: options.transport ?? HOST_TRANSPORT,
providerVersion: PROVIDER_VERSION,
profileDigest: PROFILE_DIGEST,
@@ -223,6 +226,80 @@ it("keeps one shared startup despite a failed progress sink and stops reports af
});
describe("GhidraClient captured source snapshot", () => {
it("retains a snapshot descriptor whose close failed until session cleanup succeeds", async () => {
const client = clientFor(new FixtureLauncher());
const started = await client.start();
if (!started.ok) throw started.error;
const close = vi
.spyOn(OwnedFileHandle.prototype, "close")
.mockRejectedValueOnce(new Error("snapshot descriptor close failed"));
try {
await expect(client.hashTargetSnapshot()).resolves.toMatchObject({
ok: false,
error: { kind: "protocol" },
});
const owner = close.mock.contexts[0];
expect(owner).toBeInstanceOf(OwnedFileHandle);
const closed = await client.close();
if (!closed.ok) throw closed.error;
expect(
close.mock.contexts.filter((context) => context === owner),
).toHaveLength(2);
} finally {
close.mockRestore();
}
});
it("hashes complete private snapshots with bounded chunks and abortable reads", async () => {
const root = await createTestTempDirectory("rea-ghidra-hash-");
const source = join(root, "firmware.bin");
const bytes = Buffer.alloc(512 * 1024 + 3, 0xa5);
const sha256 = createHash("sha256").update(bytes).digest("hex");
await writeFile(source, bytes);
const client = clientFor(new FixtureLauncher(), {
targetPath: source,
targetSha256: sha256,
});
await expect(client.hashTargetSnapshot()).resolves.toMatchObject({
ok: false,
error: { kind: "protocol" },
});
const started = await client.start();
if (!started.ok) throw started.error;
// Observe the admitted private snapshot even if the original path changes.
await writeFile(source, "changed original");
const allocate = Buffer.allocUnsafe;
const allocations = vi.spyOn(Buffer, "allocUnsafe");
try {
const identity = await client.hashTargetSnapshot();
if (!identity.ok) throw identity.error;
expect(identity.value).toEqual({ sha256, bytes: bytes.length });
expect(allocations.mock.calls.length).toBeGreaterThan(1);
expect(
Math.max(...allocations.mock.calls.map(([size]) => size)),
).toBeLessThan(bytes.length);
const controller = new AbortController();
allocations.mockImplementationOnce((size) => {
controller.abort();
return allocate(size);
});
await expect(
client.hashTargetSnapshot(controller.signal),
).resolves.toMatchObject({ ok: false, error: { kind: "cancelled" } });
} finally {
allocations.mockRestore();
}
await expect(client.hashTargetSnapshot()).resolves.toMatchObject({
ok: true,
value: { sha256, bytes: bytes.length },
});
await client.close();
await expect(client.hashTargetSnapshot()).resolves.toMatchObject({
ok: false,
error: { kind: "protocol" },
});
});
it("exposes the immutable import snapshot only during the live session", async () => {
const client = clientFor(new FixtureLauncher());
await expect(client.readTargetSnapshot()).resolves.toMatchObject({
@@ -113,6 +113,39 @@ describe("Ghidra COM loader", () => {
});
});
describe("Ghidra raw-binary loader", () => {
it("loads caller-supplied architecture and entry before auto-analysis", () => {
const arguments_ = ghidraHeadlessArguments({
projectRoot: "/tmp/project",
targetPath: "/tmp/ecu.bin",
bridgeScriptPath: "/package/bridge/ReaGhidraBridge.java",
descriptorPath: "/tmp/session.json",
ghidraLogPath: "/tmp/ghidra.log",
scriptLogPath: "/tmp/script.log",
rawBinary: {
languageId: "ARM:LE:32:v7",
compilerSpecId: "default",
baseAddr: "0x8000000",
},
});
expectOptions(arguments_, [
["-loader", "BinaryLoader"],
["-loader-baseAddr", "0x8000000"],
["-processor", "ARM:LE:32:v7"],
["-cspec", "default"],
]);
const prepare = arguments_.indexOf("-preScript");
expect(arguments_[prepare + 1]).toBe(
join("/package/bridge", "ReaGhidraPrepareRaw.java"),
);
expect(arguments_[prepare + 2]).toBe("ARM:LE:32:v7");
expect(arguments_[prepare + 3]).toBe("0x8000000");
expect(prepare).toBeLessThan(arguments_.indexOf("-postScript"));
expect(arguments_).toContain("-readOnly");
expect(arguments_).toContain("-deleteProject");
});
});
describe("Ghidra headless launcher", () => {
it("forces the admitted real-mode language and loader for DOS MZ", () => {
const arguments_ = ghidraHeadlessArguments({
@@ -208,6 +241,20 @@ describe("Ghidra configured import language and seeds", () => {
).toThrow(/cannot be combined with a DOS import/u);
});
it("never combines a configured language with a raw-binary import", () => {
expect(() =>
ghidraHeadlessArguments({
...base,
languageOverride: { languageId: "x86:LE:32:default" },
rawBinary: {
languageId: "ARM:LE:32:v7",
compilerSpecId: "default",
baseAddr: "0x8000000",
},
}),
).toThrow(/cannot be combined with a raw-binary import/u);
});
it.each(["darwin", "win32"] as const)(
"applies seeds after loader preparation and before analysis scripts on %s",
(platform) => {
@@ -31,6 +31,27 @@ describe("Hopper analysis profiles", () => {
});
});
it("does not map caller-supplied raw binaries onto a Hopper loader", () => {
expect(
hopperLoaderArgsForTarget({
path: "/tmp/ecu.bin",
sha256: "a".repeat(64),
kind: "executable",
format: "raw-binary",
architecture: "arm",
availableArchitectures: ["arm"],
entryPoint: "0x8000000",
entryPointSource: "0x8000000",
}),
).toMatchObject({
ok: false,
error: {
_tag: "ProviderAdapterError",
operation: "resolve_analysis_profile",
},
});
});
it.each([
[target("elf", "x86_64"), ["-l", "ELF", "--intel-64"]],
[target("pe", "x86"), ["-l", "WinPE", "--intel-32"]],