fix(reverse): reconcile cleanup ownership and mutation diagnostics (#2799)
* feat(process): add owned debugger shutdown lifecycle * feat(reverse): add local inspection commands * feat(gdb): add persistent debugger integration * feat(cutter): add Cutter bridge integration * test(reverse): enforce complete integration coverage * fix(process): preserve debugger shutdown ownership * fix(reverse): retain evidence across interrupted commands * fix(gdb): honor captured provider environment * test(process): cover debugger shutdown retries * fix(reverse): retain evidence for interrupted providers * test(process): cover debugger shutdown retries * fix(reverse): retain evidence for interrupted providers * fix(server): snapshot provider environment at creation * fix(reverse): close review gaps with complete coverage * fix(reverse): address inspection review findings * fix(gdb): bound sessions and retain cleanup ownership * fix(ci): require reverse-tools quality lane * fix(process): unref inherited debugger output pipes * fix(reverse): address remaining PR 1960 findings * fix(gdb): address remaining PR 1961 findings * fix(reverse): account for unrestricted provider execution * fix(process): retain debugger ownership until safe shutdown * fix(process): preserve replacement debugger sessions * fix(reverse): preserve admission and output provenance * fix(process): retain exited debugger until output settles * fix(mcp): bound provider admission and debugger cleanup * fix(reverse): preserve failure provenance and classify E2BIG * fix(gdb): preserve startup cleanup and detach safety * fix(process): retain debugger ownership after detach failure * fix(reverse): preserve mutation and failure provenance * fix(gdb): address debugger review findings * fix(reverse): rebind sessions after external mutation * fix(process): cap debugger output after exit * fix(gdb): protect one-shot detach verification * feat(debugger): add reverse tool coverage gate * test(debugger): cover integrated failure paths * fix(gdb): bound and preserve session observations * fix(gdb): address review regressions * style: format merged integration files * fix(reverse): preserve session and output evidence * refactor(gdb): share repeated test and partial result setup * fix(gdb): invalidate TTY proof for Python aliases * fix(reverse): retain failure output byte counts * test(process): synchronize late debugger output * fix(gdb): invalidate TTY proof for wrapped commands * fix(gdb): recognize wit command abbreviation * test(reverse): wait for cancelled descendant readiness * test(reverse): bound descendant cancellation cleanup * style(reverse): format integration tests and adapters * style: format reverse engineering integration files * test(reverse): remove duplicate environment harness * test(gdb): share session startup assertions * fix(gdb): invalidate output proof for command abbreviations * test(reverse): share composition edge case scenarios * fix(ci): recognize verification and mutation tool entries * test(rizin): cover successful fake inferior detach * test(cli): align full output failure envelope * test(cli): isolate reverse command lifecycle service * test(process): share debugger output fixture setup * fix(binary): preserve high-bit Windows signature bytes * style(binary): format Windows signature parser * test(mcp): preserve call coverage in unchanged comparison * fix(ci): include reverse tools Vitest configs in lint cache * fix(mcp): preserve target content on delivery errors * ci: align duplication ceiling with expanded suite * test(reverse): allow signal admission mutants * fix(reverse): bound retained cleanup failures to process owners * fix(test): replace drifting mutation ranges with owned selectors * fix(reverse): admit persistent commands and retain cleanup ownership * fix(cutter): recover timed-out commands from exact receipts * fix(cutter): reject unsupported bridge request kinds * fix(ci): repair client format and shared verification fixtures * fix(native): preserve debugger cleanup ownership and bridge authentication * test(native): retain diagnostics without perfect coverage requirements * chore(licenses): refresh locked dependency inventory and notices * fix(test): exclude transient command locks from mutation sandboxes * fix(gdb): admit only platforms with safe detach verification * fix(cutter): retain bounded completion receipts until acknowledgement * fix(cutter): acknowledge commands rejected before UI dispatch * test(reverse): fail cancellation checks before fixture teardown * test(gdb): clean up the retained broken-stdin fixture owner * docs(test): clarify focused provider verification scope * fix(rizin): retain close cleanup failures * fix(gdb): wait for inferior stop and bound MI buffering * fix(cutter): retain failed receipt acknowledgements * fix(rizin): return retained session identity on rebind failure * fix(gdb): preserve startup cancellation and lossy status * fix(rizin): retain launch provenance and assemble frames once * fix(cutter): recover receipts across callers and bound discovery * docs: describe debugger evidence and bridge recovery * fix(process): keep cleanup incomplete while writers remain Stopping a debugger no longer reports success when inherited output streams stay open, so BinarySession cannot reopen a binary a child is still changing. Concurrent Cutter cleanup retries share one receipt acknowledgement instead of treating a consumed receipt as failure. * fix(debuggers): recover cleanup with captured process identities * fix(analysis): retire sessions after unrestricted commands * fix(cli): preserve completed evidence after cleanup recovery * fix(cutter): bound frame collection and coalesce cleanup * fix(windows): resolve selected provider paths absolutely * fix(gdb): report decoding loss in failed startup evidence * fix(rizin): scope decoding loss to collected command frames * test(mcp): cover snapshot retirement in reverse tools CI --------- Co-authored-by: Daniel Gonçalves Araujo <47118053+dandgabr@users.noreply.github.com> Co-authored-by: REA Maintainers <noreply@github.com> Co-authored-by: OpenAI Codex <codex@users.noreply.github.com> Co-authored-by: Cursor Agent <cursoragent@cursor.com>
This commit is contained in:
co-authored by
Daniel Gonçalves Araujo
REA Maintainers
OpenAI Codex
Cursor Agent
parent
2ad2a044d4
commit
4aa51bfe19
@@ -14,6 +14,7 @@ import { ProviderCleanupError } from "../../../src/domain/providerCleanupError.j
|
||||
import { err, ok as resultOk } from "../../../src/domain/result.js";
|
||||
import { createEvidenceBundle } from "../../../src/domain/evidenceBundle.js";
|
||||
import { createEvidence } from "../../../src/domain/evidence.js";
|
||||
import { thinMach } from "../../../src/domain/binaryTarget.fixture.js";
|
||||
import { observed as ok } from "../../fixtures/analysisExecution.js";
|
||||
import {
|
||||
ControllableAnalysisClient,
|
||||
@@ -23,9 +24,16 @@ import {
|
||||
createTestBinarySession,
|
||||
} from "../../fixtures/binarySession.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { copyFile, writeFile } from "node:fs/promises";
|
||||
import { extname, join } from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
copyFile,
|
||||
link,
|
||||
mkdir,
|
||||
realpath,
|
||||
symlink,
|
||||
writeFile,
|
||||
} from "node:fs/promises";
|
||||
import { dirname, extname, join } from "node:path";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
const client = (fail = false): AnalysisClient => ({
|
||||
execute: () => Promise.resolve(fail ? err(new HopperStartError()) : ok(null)),
|
||||
@@ -165,6 +173,247 @@ describe("detached provider and target metadata", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("drains session calls and retires analysis after an admitted external mutation", async () => {
|
||||
const [target] = await createBinarySessionTargets();
|
||||
const alias = join(dirname(target), "first-alias.hop");
|
||||
await symlink(target, alias);
|
||||
const calls: string[] = [];
|
||||
const clients: { closed: number; targetSha256: string }[] = [];
|
||||
const base = createCacheProvider(calls);
|
||||
const session = createTestBinarySession({
|
||||
...base,
|
||||
createClient: (...arguments_) => {
|
||||
const client = base.createClient(...arguments_);
|
||||
const tracked = { closed: 0, targetSha256: arguments_[0].sha256 };
|
||||
clients.push(tracked);
|
||||
return {
|
||||
...client,
|
||||
close: async () => {
|
||||
tracked.closed += 1;
|
||||
return client.close();
|
||||
},
|
||||
};
|
||||
},
|
||||
});
|
||||
expect((await session.open(target)).ok).toBe(true);
|
||||
expect(session.activeTarget()?.path).toBe(target);
|
||||
const originalDigest = session.activeTarget()?.sha256;
|
||||
const started = createDeferred<void>();
|
||||
const release = createDeferred<void>();
|
||||
|
||||
const mutation = session.withAdmittedExternalMutation(
|
||||
alias,
|
||||
undefined,
|
||||
async () => {
|
||||
expect(session.activeTarget()?.path).toBe(target);
|
||||
started.resolve();
|
||||
await release.promise;
|
||||
await writeFile(alias, "changed by external provider");
|
||||
return resultOk("provider finished");
|
||||
},
|
||||
(_value, error) => error,
|
||||
);
|
||||
await started.promise;
|
||||
const queuedAnalysis = session.execute("address_name", {});
|
||||
expect(calls).toEqual([]);
|
||||
|
||||
release.resolve();
|
||||
await expect(mutation).resolves.toMatchObject({
|
||||
ok: true,
|
||||
value: { ok: true, value: "provider finished" },
|
||||
});
|
||||
expect((await queuedAnalysis).ok).toBe(false);
|
||||
expect(session.activeTarget()).toBeUndefined();
|
||||
expect(calls).toEqual([]);
|
||||
expect(clients).toHaveLength(0);
|
||||
expect((await session.open(target)).ok).toBe(true);
|
||||
expect((await session.execute("address_name", {})).ok).toBe(true);
|
||||
expect(session.activeTarget()?.sha256).not.toBe(originalDigest);
|
||||
expect(clients.at(-1)?.targetSha256).toBe(session.activeTarget()?.sha256);
|
||||
expect(calls).toEqual(["address_name"]);
|
||||
await session.close();
|
||||
});
|
||||
|
||||
it("leaves analysis unbound when a command returns before its writer finishes", async () => {
|
||||
const [target] = await createBinarySessionTargets();
|
||||
const session = createTestBinarySession(createCacheProvider([]));
|
||||
expect((await session.open(target)).ok).toBe(true);
|
||||
const originalDigest = session.activeTarget()?.sha256;
|
||||
const releaseWriter = createDeferred<void>();
|
||||
let writer: Promise<void> | undefined;
|
||||
const result = await session.withAdmittedExternalMutation(
|
||||
target,
|
||||
undefined,
|
||||
async () => {
|
||||
writer = releaseWriter.promise.then(() =>
|
||||
writeFile(target, "delayed write"),
|
||||
);
|
||||
return resultOk("command replied");
|
||||
},
|
||||
(_value, error) => error,
|
||||
);
|
||||
expect(result).toEqual(resultOk(resultOk("command replied")));
|
||||
expect(session.activeTarget()).toBeUndefined();
|
||||
releaseWriter.resolve();
|
||||
await writer;
|
||||
expect((await session.execute("address_name", {})).ok).toBe(false);
|
||||
expect((await session.open(target)).ok).toBe(true);
|
||||
expect(session.activeTarget()?.sha256).not.toBe(originalDigest);
|
||||
await session.close();
|
||||
});
|
||||
|
||||
it("retires analysis when an external mutation uses a hard link", async () => {
|
||||
const [target] = await createBinarySessionTargets();
|
||||
const alias = join(dirname(target), "hard-link-alias.hop");
|
||||
await link(target, alias);
|
||||
const session = createTestBinarySession(createCacheProvider([]));
|
||||
expect((await session.open(target)).ok).toBe(true);
|
||||
const before = session.activeTarget()?.sha256;
|
||||
|
||||
const result = await session.withAdmittedExternalMutation(
|
||||
alias,
|
||||
undefined,
|
||||
async () => {
|
||||
await writeFile(alias, "changed through hard link");
|
||||
return resultOk("changed");
|
||||
},
|
||||
(_value, error) => error,
|
||||
);
|
||||
|
||||
expect(result).toMatchObject({
|
||||
ok: true,
|
||||
value: { ok: true, value: "changed" },
|
||||
});
|
||||
expect(session.activeTarget()).toBeUndefined();
|
||||
expect((await session.open(target)).ok).toBe(true);
|
||||
expect(session.activeTarget()?.sha256).not.toBe(before);
|
||||
await session.close();
|
||||
});
|
||||
|
||||
it("preserves Evidence records while retiring the client after an external mutation", async () => {
|
||||
const [target] = await createBinarySessionTargets();
|
||||
const session = createTestBinarySession(createCacheProvider([]));
|
||||
expect((await session.open(target)).ok).toBe(true);
|
||||
expect(
|
||||
(await session.execute("address_name", { address: "0x1000" })).ok,
|
||||
).toBe(true);
|
||||
recordNetworkReachabilityUnknown(session, "medium");
|
||||
const before = session.exportEvidenceBundle();
|
||||
|
||||
const result = await session.withAdmittedExternalMutation(
|
||||
target,
|
||||
undefined,
|
||||
async () => resultOk("observed"),
|
||||
(_value, error) => error,
|
||||
);
|
||||
|
||||
expect(result.ok).toBe(true);
|
||||
expect(session.exportEvidenceBundle().records).toEqual(before.records);
|
||||
expect(session.listUnknowns()).toHaveLength(1);
|
||||
await session.close();
|
||||
});
|
||||
|
||||
it("requires explicitly reopening an app bundle after a session mutation", async () => {
|
||||
const directory = await createTestTempDirectory("rea-session-app-rebind-");
|
||||
const app = join(directory, "Fixture.app");
|
||||
const executable = join(app, "Fixture");
|
||||
await mkdir(app, { recursive: true });
|
||||
await writeFile(
|
||||
join(app, "Info.plist"),
|
||||
"<plist><dict><key>CFBundleExecutable</key><string>Fixture</string></dict></plist>",
|
||||
);
|
||||
await writeFile(executable, thinMach(0xfeedfacf, 0x0100000c));
|
||||
const session = createTestBinarySession(createCacheProvider([]));
|
||||
expect((await session.open(app)).ok).toBe(true);
|
||||
const initial = session.activeTarget();
|
||||
expect(initial?.sourcePath).toBe(await realpath(app));
|
||||
|
||||
const result = await session.withAdmittedExternalMutation(
|
||||
initial?.path ?? executable,
|
||||
undefined,
|
||||
async () => resultOk("observed"),
|
||||
(_value, error) => error,
|
||||
);
|
||||
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result).toMatchObject({
|
||||
ok: true,
|
||||
value: { ok: true, value: "observed" },
|
||||
});
|
||||
expect(session.activeTarget()).toBeUndefined();
|
||||
expect((await session.open(app)).ok).toBe(true);
|
||||
expect(session.activeTarget()).toMatchObject({
|
||||
path: await realpath(executable),
|
||||
sourcePath: await realpath(app),
|
||||
bundleInfoPlist: await realpath(join(app, "Info.plist")),
|
||||
});
|
||||
await session.close();
|
||||
});
|
||||
|
||||
it("retires an auxiliary-only session after an external mutation", async () => {
|
||||
const [target] = await createBinarySessionTargets();
|
||||
const session = createTestBinarySession(() => ({
|
||||
execute: () => Promise.resolve(ok(null)),
|
||||
close: () => Promise.resolve(resultOk(null)),
|
||||
}));
|
||||
expect((await session.open(target)).ok).toBe(true);
|
||||
|
||||
const result = await session.withAdmittedExternalMutation(
|
||||
target,
|
||||
undefined,
|
||||
async () => resultOk("observed"),
|
||||
(_value, error) => error,
|
||||
);
|
||||
|
||||
expect(result).toMatchObject({
|
||||
ok: true,
|
||||
value: { ok: true, value: "observed" },
|
||||
});
|
||||
expect(session.activeTarget()).toBeUndefined();
|
||||
await session.close();
|
||||
});
|
||||
|
||||
it("keeps an externally mutated session unbound until cleanup is retried", async () => {
|
||||
const [target] = await createBinarySessionTargets();
|
||||
const cleanupError = new ProviderCleanupError("fixture", ["provider-child"], {
|
||||
reason: "process group is still alive",
|
||||
});
|
||||
let created = 0;
|
||||
let closeAttempts = 0;
|
||||
const session = createTestBinarySession(() => {
|
||||
created += 1;
|
||||
return {
|
||||
execute: () => Promise.resolve(ok(null)),
|
||||
close: () =>
|
||||
Promise.resolve(
|
||||
++closeAttempts === 1 ? err(cleanupError) : resultOk(null),
|
||||
),
|
||||
};
|
||||
});
|
||||
expect((await session.open(target)).ok).toBe(true);
|
||||
expect(session.activeTarget()).toBeDefined();
|
||||
expect(created).toBe(1);
|
||||
|
||||
const mutation = await session.withAdmittedExternalMutation(
|
||||
target,
|
||||
undefined,
|
||||
async () => resultOk("dispatched"),
|
||||
(_value, error) => error,
|
||||
);
|
||||
|
||||
expect(closeAttempts).toBe(1);
|
||||
expect(mutation.ok).toBe(false);
|
||||
if (mutation.ok) throw new Error("Expected cleanup failure");
|
||||
expect(mutation.error).toBeInstanceOf(ProviderCleanupError);
|
||||
expect(mutation.error.cleanupIncomplete).toBe(true);
|
||||
expect(session.activeTarget()).toBeUndefined();
|
||||
expect((await session.execute("address_name", {})).ok).toBe(false);
|
||||
expect(created).toBe(1);
|
||||
expect((await session.open(target)).ok).toBe(true);
|
||||
expect(created).toBe(2);
|
||||
await session.close();
|
||||
});
|
||||
|
||||
describe("opening previewed targets", () => {
|
||||
it("rechecks the active target after another serialized transition", async () => {
|
||||
const [first, second] = await createBinarySessionTargets();
|
||||
@@ -1279,6 +1528,77 @@ describe("selector origin forwarding", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("blocks analysis rebinding until the external writer cleanup settles", async () => {
|
||||
const [target] = await createBinarySessionTargets();
|
||||
const session = createTestBinarySession(createCacheProvider([]));
|
||||
expect((await session.open(target)).ok).toBe(true);
|
||||
const failure = new ProviderCleanupError("rizin", ["writer"], {
|
||||
reason: "writer remains alive",
|
||||
});
|
||||
const result = await session.withAdmittedExternalMutation(
|
||||
target,
|
||||
undefined,
|
||||
async () => err(failure),
|
||||
(_value, error) => error,
|
||||
);
|
||||
expect(result).toEqual(resultOk(err(failure)));
|
||||
expect(session.activeTarget()).toBeUndefined();
|
||||
expect(await session.open(target)).toEqual(err(failure));
|
||||
const anotherMutation = vi.fn(async () => resultOk("unrelated command"));
|
||||
expect(
|
||||
await session.withAdmittedExternalMutation(
|
||||
target,
|
||||
undefined,
|
||||
anotherMutation,
|
||||
(_value, error) => error,
|
||||
),
|
||||
).toEqual(err(failure));
|
||||
expect(anotherMutation).not.toHaveBeenCalled();
|
||||
// Only the resource owner may acknowledge completed cleanup.
|
||||
failure.resolveCleanup();
|
||||
expect((await session.open(target)).ok).toBe(true);
|
||||
await session.close();
|
||||
});
|
||||
|
||||
it("requires explicit close before an external mutation of an active Ghidra session", async () => {
|
||||
const [target] = await createBinarySessionTargets();
|
||||
const base = createCacheProvider([]);
|
||||
const identity = { id: "ghidra", name: "Ghidra", version: "fixture" };
|
||||
const session = createTestBinarySession({
|
||||
...base,
|
||||
identity: () => identity,
|
||||
resolveAnalysisProfile: async () =>
|
||||
resultOk({
|
||||
profile: createAnalysisProfile(identity, { fixture: true }),
|
||||
}),
|
||||
capabilities: () =>
|
||||
base.capabilities().map((capability) => ({
|
||||
...capability,
|
||||
provider: identity,
|
||||
})),
|
||||
});
|
||||
expect((await session.open(target)).ok).toBe(true);
|
||||
expect(session.providerIdentity().id).toBe("ghidra");
|
||||
const mutate = vi.fn(async () => resultOk("mutated"));
|
||||
const result = await session.withAdmittedExternalMutation(
|
||||
target,
|
||||
undefined,
|
||||
mutate,
|
||||
(_value, error) => error,
|
||||
);
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
message: expect.stringContaining(
|
||||
"Close the active Ghidra session explicitly",
|
||||
),
|
||||
},
|
||||
});
|
||||
expect(mutate).not.toHaveBeenCalled();
|
||||
expect(session.activeTarget()?.path).toBe(target);
|
||||
await session.close();
|
||||
});
|
||||
|
||||
describe("reference truncation forwarding", () => {
|
||||
const referenceProvider = (
|
||||
referencesTruncated: boolean | undefined,
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { z } from "zod";
|
||||
|
||||
import { createAnalysisExecution } from "../../src/application/AnalysisProvider.js";
|
||||
import { traceCallPath } from "../../src/application/CallPathTracing.js";
|
||||
import { ok } from "../../src/domain/result.js";
|
||||
|
||||
it("attributes malformed relationship output to the originating provider operation", async () => {
|
||||
const result = await traceCallPath(
|
||||
async (operation) =>
|
||||
ok(operation === "procedure_address" ? "0x1000" : "0x1000"),
|
||||
async () =>
|
||||
ok(
|
||||
createAnalysisExecution(
|
||||
{ callees: [123] },
|
||||
{ id: "test", name: "test", version: null },
|
||||
),
|
||||
),
|
||||
{ start: "entry", direction: "forward" },
|
||||
);
|
||||
|
||||
expect(result.ok).toBe(true);
|
||||
if (result.ok) {
|
||||
const failures = z
|
||||
.object({
|
||||
failures: z.array(
|
||||
z.object({
|
||||
error: z.object({
|
||||
details: z.object({ operation: z.string() }),
|
||||
}),
|
||||
}),
|
||||
),
|
||||
})
|
||||
.parse(result.value).failures;
|
||||
expect(failures[0]?.error.details.operation).toBe("procedure_callees");
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,95 @@
|
||||
import { win32 } from "node:path";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { resolveWindowsProviderExecutable } from "../../src/composition/resolveWindowsProviderExecutable.js";
|
||||
import { createReverseEngineeringCommandPort } from "../../src/composition/reverseEngineering.js";
|
||||
|
||||
const windowsLookup = (cwd: string, files: readonly string[]) => {
|
||||
const existingFiles = new Set(
|
||||
files.map((path) => win32.normalize(path).toLowerCase()),
|
||||
);
|
||||
return {
|
||||
cwd,
|
||||
isFile: (path: string): boolean =>
|
||||
existingFiles.has(win32.normalize(path).toLowerCase()),
|
||||
};
|
||||
};
|
||||
|
||||
describe("resolveWindowsProviderExecutable", () => {
|
||||
it("resolves a bare name from quoted and relative Windows PATH entries", () => {
|
||||
const cwd = "C:\\work";
|
||||
const expected = "C:\\work\\Program Files\\REA Tools\\objdump.EXE";
|
||||
expect(
|
||||
resolveWindowsProviderExecutable(
|
||||
"objdump",
|
||||
{
|
||||
PATH: `.;".\\Program Files\\REA Tools";D:\\unused`,
|
||||
PATHEXT: ".COM;.EXE;.BAT",
|
||||
},
|
||||
windowsLookup(cwd, [expected]),
|
||||
),
|
||||
).toBe(expected);
|
||||
});
|
||||
|
||||
it("resolves a relative configured path against the caller's Windows CWD", () => {
|
||||
expect(
|
||||
resolveWindowsProviderExecutable(
|
||||
".\\tools\\objdump.exe",
|
||||
{},
|
||||
windowsLookup("D:\\analysis", []),
|
||||
),
|
||||
).toBe("D:\\analysis\\tools\\objdump.exe");
|
||||
});
|
||||
|
||||
it("resolves relative PATH hits to absolute drive paths", () => {
|
||||
const expected = "D:\\analysis\\bin\\rizin.EXE";
|
||||
expect(
|
||||
resolveWindowsProviderExecutable(
|
||||
"rizin",
|
||||
{ PATH: ".\\bin", PATHEXT: ".EXE" },
|
||||
windowsLookup("D:\\analysis", [expected]),
|
||||
),
|
||||
).toBe(expected);
|
||||
});
|
||||
|
||||
it("skips script extensions and preserves a caller-selected absolute path", () => {
|
||||
const expected = "C:\\tools\\rizin.EXE";
|
||||
const selected = "C:\\tools\\rizin.exe";
|
||||
expect(
|
||||
resolveWindowsProviderExecutable(
|
||||
"rizin",
|
||||
{ PATH: "C:\\tools", PATHEXT: ".CMD;.BAT;.EXE;.COM" },
|
||||
windowsLookup("C:\\work", ["C:\\tools\\rizin.CMD", expected]),
|
||||
),
|
||||
).toBe(expected);
|
||||
expect(
|
||||
resolveWindowsProviderExecutable(
|
||||
selected,
|
||||
{},
|
||||
windowsLookup("D:\\work", []),
|
||||
),
|
||||
).toBe(selected);
|
||||
});
|
||||
|
||||
it("keeps unresolved bare command names unchanged", () => {
|
||||
expect(
|
||||
resolveWindowsProviderExecutable(
|
||||
"missing-tool",
|
||||
{ PATH: ".\\tools", PATHEXT: ".EXE" },
|
||||
windowsLookup("C:\\work", []),
|
||||
),
|
||||
).toBe("missing-tool");
|
||||
});
|
||||
|
||||
it("passes an absolute selected command through provider composition", () => {
|
||||
const commands = createReverseEngineeringCommandPort(
|
||||
{ REA_OBJDUMP_COMMAND: "C:\\tools\\objdump.exe" },
|
||||
"win32",
|
||||
);
|
||||
expect(
|
||||
commands.objdump({ path: "artifact", operation: "file_headers" })
|
||||
.executable,
|
||||
).toBe("C:\\tools\\objdump.exe");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,564 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { TestReverseEngineeringService as ReverseEngineeringService } from "../support/reverseEngineeringService.js";
|
||||
import { createReverseEngineeringService } from "../../src/composition/reverseEngineering.js";
|
||||
import { projectAnalysisError } from "../../src/domain/analysisErrorProjection.js";
|
||||
import { REVERSE_ENGINEERING_TOOL_CONTRACTS } from "../../src/contracts/reverseEngineeringToolContracts.js";
|
||||
|
||||
describe("reverse engineering command services", () => {
|
||||
it("documents the shared combined capture limit for both command tools", () => {
|
||||
for (const contract of REVERSE_ENGINEERING_TOOL_CONTRACTS)
|
||||
expect(contract.description).toContain("shared 16 MiB combined limit");
|
||||
expect(REVERSE_ENGINEERING_TOOL_CONTRACTS[0]?.description).toContain(
|
||||
"does not follow local debug links by default",
|
||||
);
|
||||
});
|
||||
|
||||
it("uses compatible local DWARF link flags and disables debuginfod through the environment", async () => {
|
||||
const directory = await mkdtemp(join(tmpdir(), "rea-reverse-tools-"));
|
||||
const path = join(directory, "fixture.bin");
|
||||
await writeFile(path, Buffer.from([0x7f, 0x45, 0x4c, 0x46]));
|
||||
const calls: {
|
||||
command: string;
|
||||
args: readonly string[];
|
||||
env: NodeJS.ProcessEnv | undefined;
|
||||
}[] = [];
|
||||
const service = new ReverseEngineeringService({
|
||||
environment: {
|
||||
REA_OBJDUMP_COMMAND: "/tools/objdump",
|
||||
DEBUGINFOD_URLS: "https://debug.example.invalid",
|
||||
},
|
||||
run: async (command, args, options) => {
|
||||
calls.push({ command, args, env: options?.env });
|
||||
return { stdout: "DWARF output\n", stderr: "diagnostic\n" };
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
const result = await service.inspectWithObjdump({
|
||||
path,
|
||||
operation: "dwarf",
|
||||
follow_debug_links: true,
|
||||
});
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) return;
|
||||
expect(calls).toEqual([
|
||||
{
|
||||
command: "/tools/objdump",
|
||||
args: ["-W", "-WK", path],
|
||||
env: expect.objectContaining({ DEBUGINFOD_URLS: "" }),
|
||||
},
|
||||
]);
|
||||
expect(result.value.raw_result).toMatchObject({
|
||||
stdout: "DWARF output\n",
|
||||
stderr: "diagnostic\n",
|
||||
exit_code: 0,
|
||||
output_truncated: false,
|
||||
});
|
||||
expect(result.value.provider.id).toBe("gnu.objdump");
|
||||
expect(result.value.subject?.local_path).toBe(path);
|
||||
} finally {
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects non-regular artifacts without launching the provider", async () => {
|
||||
const directory = await mkdtemp(
|
||||
join(tmpdir(), "rea-reverse-special-file-"),
|
||||
);
|
||||
let invoked = false;
|
||||
const service = new ReverseEngineeringService({
|
||||
run: async () => {
|
||||
invoked = true;
|
||||
return { stdout: "", stderr: "" };
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
const result = await service.inspectWithObjdump({
|
||||
path: directory,
|
||||
operation: "file_headers",
|
||||
});
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok)
|
||||
expect(result.error.cause).toMatchObject({
|
||||
code: "EINVAL",
|
||||
message: "Artifact digest requires a regular file",
|
||||
});
|
||||
expect(invoked).toBe(false);
|
||||
} finally {
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("classifies captured spawn failures instead of reporting provider evidence", async () => {
|
||||
const directory = await mkdtemp(
|
||||
join(tmpdir(), "rea-objdump-spawn-failure-"),
|
||||
);
|
||||
const path = join(directory, "fixture.bin");
|
||||
await writeFile(path, "fixture");
|
||||
const service = new ReverseEngineeringService({
|
||||
run: async () => {
|
||||
const failure = Object.assign(new Error("not found"), {
|
||||
stdout: "",
|
||||
stderr: "",
|
||||
code: "ENOENT",
|
||||
signal: null,
|
||||
killed: false,
|
||||
});
|
||||
throw failure;
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
const result = await service.inspectWithObjdump({
|
||||
path,
|
||||
operation: "file_headers",
|
||||
});
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) {
|
||||
expect(result.error._tag).toBe("AnalysisCapabilityUnavailableError");
|
||||
expect(result.error.message).toContain("ENOENT");
|
||||
expect(result.error.message).not.toContain("stdout");
|
||||
}
|
||||
} finally {
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("marks max-buffer termination as unknown completion while retaining output", async () => {
|
||||
const directory = await mkdtemp(join(tmpdir(), "rea-objdump-max-buffer-"));
|
||||
const path = join(directory, "fixture.bin");
|
||||
await writeFile(path, "fixture");
|
||||
const service = new ReverseEngineeringService({
|
||||
run: async () => {
|
||||
throw Object.assign(new Error("max buffer exceeded"), {
|
||||
stdout: "captured partial output",
|
||||
stderr: "",
|
||||
code: "ERR_CHILD_PROCESS_STDIO_MAXBUFFER",
|
||||
signal: "SIGTERM",
|
||||
killed: true,
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
const result = await service.executeRizinCommand({
|
||||
path,
|
||||
command: "wx 00 @ 0",
|
||||
});
|
||||
expect(result.ok).toBe(true);
|
||||
if (result.ok)
|
||||
expect(result.value.raw_result).toMatchObject({
|
||||
stdout: "captured partial output",
|
||||
exit_code: null,
|
||||
output_truncated: true,
|
||||
completion_status: "unknown",
|
||||
});
|
||||
} finally {
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it("uses one selected environment snapshot for provider selection and execution", async () => {
|
||||
const directory = await mkdtemp(join(tmpdir(), "rea-provider-environment-"));
|
||||
const path = join(directory, "fixture.bin");
|
||||
await writeFile(path, Buffer.from([0x7f, 0x45, 0x4c, 0x46]));
|
||||
const selectedEnvironment = {
|
||||
REA_RIZIN_COMMAND: "/selected/rizin",
|
||||
PATH: "/selected/bin",
|
||||
SELECTED_VALUE: "captured",
|
||||
};
|
||||
const calls: { command: string; env: NodeJS.ProcessEnv | undefined }[] = [];
|
||||
const service = createReverseEngineeringService(selectedEnvironment, {
|
||||
run: async (command, _args, options) => {
|
||||
calls.push({ command, env: options?.env });
|
||||
return { stdout: "headers", stderr: "" };
|
||||
},
|
||||
});
|
||||
selectedEnvironment.REA_RIZIN_COMMAND = "/changed/rizin";
|
||||
selectedEnvironment.SELECTED_VALUE = "changed after construction";
|
||||
|
||||
try {
|
||||
const result = await service.executeRizinCommand({
|
||||
path,
|
||||
command: "iI",
|
||||
});
|
||||
expect(result.ok).toBe(true);
|
||||
expect(calls).toEqual([
|
||||
{
|
||||
command: "/selected/rizin",
|
||||
env: {
|
||||
REA_RIZIN_COMMAND: "/selected/rizin",
|
||||
PATH: "/selected/bin",
|
||||
SELECTED_VALUE: "captured",
|
||||
},
|
||||
},
|
||||
]);
|
||||
} finally {
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("marks signal-terminated provider commands as unknown completion", async () => {
|
||||
const directory = await mkdtemp(join(tmpdir(), "rea-provider-signal-exit-"));
|
||||
const path = join(directory, "fixture.bin");
|
||||
await writeFile(path, "fixture");
|
||||
let invocation = 0;
|
||||
const service = new ReverseEngineeringService({
|
||||
run: async () => {
|
||||
invocation += 1;
|
||||
if (invocation === 1)
|
||||
throw Object.assign(new Error("provider killed by signal"), {
|
||||
stdout: "partial output",
|
||||
stderr: "",
|
||||
code: null,
|
||||
signal: "SIGKILL",
|
||||
killed: true,
|
||||
});
|
||||
throw Object.assign(new Error("provider exited with status 2"), {
|
||||
stdout: "ordinary partial output",
|
||||
stderr: "ordinary diagnostic",
|
||||
code: 2,
|
||||
signal: null,
|
||||
killed: false,
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
const signaled = await service.executeRizinCommand({
|
||||
path,
|
||||
command: "wx 00 @ 0",
|
||||
});
|
||||
expect(signaled.ok).toBe(true);
|
||||
if (signaled.ok) {
|
||||
expect(signaled.value.raw_result).toMatchObject({
|
||||
stdout: "partial output",
|
||||
exit_code: null,
|
||||
signal: "SIGKILL",
|
||||
completion_status: "unknown",
|
||||
});
|
||||
expect(signaled.value.limitations.join(" ")).toContain("signal");
|
||||
}
|
||||
const ordinaryExit = await service.executeRizinCommand({
|
||||
path,
|
||||
command: "iI",
|
||||
});
|
||||
expect(ordinaryExit.ok).toBe(true);
|
||||
if (ordinaryExit.ok) {
|
||||
expect(ordinaryExit.value.raw_result).toMatchObject({
|
||||
stdout: "ordinary partial output",
|
||||
exit_code: 2,
|
||||
signal: null,
|
||||
completion_status: "complete",
|
||||
});
|
||||
expect(ordinaryExit.value.limitations.join(" ")).not.toContain(
|
||||
"terminated by signal",
|
||||
);
|
||||
expect(ordinaryExit.value.limitations).toContain(
|
||||
"Rizin commands and retained plugins may read files or access network resources outside the selected artifact; those external inputs are not bound to Evidence.",
|
||||
);
|
||||
expect(ordinaryExit.value.limitations).toHaveLength(4);
|
||||
}
|
||||
} finally {
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
describe("Rizin command service", () => {
|
||||
it("runs Rizin with user scripts suppressed while retaining plugins and preserves nonzero output", async () => {
|
||||
const directory = await mkdtemp(join(tmpdir(), "rea-rizin-"));
|
||||
const path = join(directory, "fixture.bin");
|
||||
await writeFile(path, "fixture");
|
||||
const calls: { command: string; args: readonly string[] }[] = [];
|
||||
const service = new ReverseEngineeringService({
|
||||
environment: { REA_RIZIN_COMMAND: "/tools/rizin" },
|
||||
run: async (command, args) => {
|
||||
calls.push({ command, args });
|
||||
const failure = new Error("command exited with status 2") as Error & {
|
||||
stdout: string;
|
||||
stderr: string;
|
||||
code: number;
|
||||
signal: null;
|
||||
killed: boolean;
|
||||
};
|
||||
Object.assign(failure, {
|
||||
stdout: "partial data",
|
||||
stderr: "command error",
|
||||
code: 2,
|
||||
signal: null,
|
||||
killed: false,
|
||||
});
|
||||
throw failure;
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
const result = await service.executeRizinCommand({ path, command: "iI" });
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) return;
|
||||
expect(calls).toEqual([
|
||||
{
|
||||
command: "/tools/rizin",
|
||||
args: ["-N", "-q", "-c", "iI", path],
|
||||
},
|
||||
]);
|
||||
expect(result.value.raw_result).toMatchObject({
|
||||
stdout: "partial data",
|
||||
stderr: "command error",
|
||||
exit_code: 2,
|
||||
completion_status: "complete",
|
||||
});
|
||||
expect(result.value.limitations.join(" ")).not.toContain(
|
||||
"terminated by signal",
|
||||
);
|
||||
expect(result.value.limitations).toContain(
|
||||
"Rizin commands and retained plugins may read files or access network resources outside the selected artifact; those external inputs are not bound to Evidence.",
|
||||
);
|
||||
expect(result.value.limitations).toHaveLength(4);
|
||||
expect(result.value.parameters).toMatchObject({
|
||||
command: "iI",
|
||||
provider_executable: "/tools/rizin",
|
||||
});
|
||||
expect(result.value.provider.id).toBe("rizin");
|
||||
} finally {
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects multiline Rizin command input before launching the provider", async () => {
|
||||
const directory = await mkdtemp(join(tmpdir(), "rea-rizin-input-"));
|
||||
const path = join(directory, "fixture.bin");
|
||||
await writeFile(path, "fixture");
|
||||
let invoked = false;
|
||||
const service = new ReverseEngineeringService({
|
||||
run: async () => {
|
||||
invoked = true;
|
||||
return { stdout: "", stderr: "" };
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
const result = await service.executeRizinCommand({
|
||||
path,
|
||||
command: "iI\nq",
|
||||
});
|
||||
expect(result.ok).toBe(false);
|
||||
expect(invoked).toBe(false);
|
||||
} finally {
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("preserves pre and post artifact digests when an unrestricted Rizin command changes the file", async () => {
|
||||
const directory = await mkdtemp(join(tmpdir(), "rea-rizin-mutation-"));
|
||||
const path = join(directory, "fixture.bin");
|
||||
await writeFile(path, "before");
|
||||
const service = new ReverseEngineeringService({
|
||||
run: async () => {
|
||||
await writeFile(path, "after");
|
||||
return { stdout: "changed", stderr: "" };
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
const result = await service.executeRizinCommand({
|
||||
path,
|
||||
command: "wx 00 @ 0",
|
||||
});
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) return;
|
||||
expect(result.value.subject?.digest.sha256).toBe(
|
||||
createHash("sha256").update("before").digest("hex"),
|
||||
);
|
||||
expect(result.value.raw_result).toMatchObject({
|
||||
artifact_sha256_after: createHash("sha256")
|
||||
.update("after")
|
||||
.digest("hex"),
|
||||
artifact_changed: true,
|
||||
});
|
||||
expect(result.value.limitations).toContain(
|
||||
"The provider command may have changed the artifact while analysis was running; pre-run and post-run digests are both reported.",
|
||||
);
|
||||
} finally {
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it("retains partial Evidence when a provider command times out", async () => {
|
||||
const directory = await mkdtemp(join(tmpdir(), "rea-rizin-timeout-partial-"));
|
||||
const path = join(directory, "fixture.bin");
|
||||
await writeFile(path, "before");
|
||||
const service = new ReverseEngineeringService({
|
||||
run: async () => {
|
||||
const failure = Object.assign(new Error("timeout"), {
|
||||
stdout: "captured before timeout",
|
||||
stderr: "still running",
|
||||
code: "ETIMEDOUT",
|
||||
signal: "SIGTERM",
|
||||
killed: true,
|
||||
});
|
||||
throw failure;
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
const result = await service.executeRizinCommand({
|
||||
path,
|
||||
command: "wx 00 @ 0",
|
||||
});
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) {
|
||||
expect(result.error._tag).toBe("AnalysisTimeoutError");
|
||||
expect(result.error.partialObservation).toMatchObject({
|
||||
operation: "execute_rizin_command",
|
||||
raw_result: {
|
||||
stdout: "captured before timeout",
|
||||
stderr: "still running",
|
||||
completion_status: "unknown",
|
||||
signal: "SIGTERM",
|
||||
artifact_sha256_after: expect.any(String),
|
||||
},
|
||||
});
|
||||
expect(JSON.stringify(projectAnalysisError(result.error))).toContain(
|
||||
"captured before timeout",
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("preserves raw byte counts when cancellation rejects invalid UTF-8 output", async () => {
|
||||
const directory = await mkdtemp(
|
||||
join(tmpdir(), "rea-rizin-abort-invalid-utf8-"),
|
||||
);
|
||||
const path = join(directory, "fixture.bin");
|
||||
await writeFile(path, "fixture");
|
||||
const controller = new AbortController();
|
||||
const failure = Object.assign(new Error("The operation was aborted"), {
|
||||
stdout: "�",
|
||||
stderr: "€",
|
||||
stdoutBytes: 1,
|
||||
stderrBytes: 3,
|
||||
code: "ABORT_ERR",
|
||||
signal: null,
|
||||
killed: true,
|
||||
});
|
||||
const service = new ReverseEngineeringService({
|
||||
run: async () => {
|
||||
controller.abort();
|
||||
throw failure;
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
const result = await service.executeRizinCommand(
|
||||
{ path, command: "iI" },
|
||||
{ signal: controller.signal },
|
||||
);
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) {
|
||||
expect(result.error._tag).toBe("AnalysisCancelledError");
|
||||
expect(result.error.capturedOutput).toMatchObject({
|
||||
stdout: "�",
|
||||
stderr: "€",
|
||||
stdout_bytes: 1,
|
||||
stderr_bytes: 3,
|
||||
});
|
||||
}
|
||||
} finally {
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("preserves provider facts when cancellation interrupts the post-run digest", async () => {
|
||||
const directory = await mkdtemp(join(tmpdir(), "rea-rizin-digest-cancel-"));
|
||||
const path = join(directory, "fixture.bin");
|
||||
await writeFile(path, "fixture");
|
||||
const controller = new AbortController();
|
||||
const service = new ReverseEngineeringService({
|
||||
run: async () => {
|
||||
controller.abort();
|
||||
return {
|
||||
stdout: "�",
|
||||
stderr: "�",
|
||||
stdoutInvalidUtf8: true,
|
||||
stderrInvalidUtf8: true,
|
||||
stdoutBytes: 1,
|
||||
stderrBytes: 1,
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
const result = await service.executeRizinCommand(
|
||||
{ path, command: "iI" },
|
||||
{ signal: controller.signal },
|
||||
);
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) {
|
||||
expect(result.error._tag).toBe("AnalysisCancelledError");
|
||||
expect(result.error.capturedOutput).toMatchObject({
|
||||
stdout: "�",
|
||||
stderr: "�",
|
||||
stdout_bytes: 1,
|
||||
stderr_bytes: 1,
|
||||
exit_code: 0,
|
||||
signal: null,
|
||||
});
|
||||
expect(result.error.partialObservation).toMatchObject({
|
||||
raw_result: {
|
||||
stdout: "�",
|
||||
exit_code: null,
|
||||
completion_status: "unknown",
|
||||
artifact_sha256_after: null,
|
||||
},
|
||||
limitations: expect.arrayContaining([
|
||||
expect.stringContaining("cancellation interrupted the digest"),
|
||||
]),
|
||||
});
|
||||
}
|
||||
} finally {
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("marks signal-terminated provider output incomplete", async () => {
|
||||
const directory = await mkdtemp(join(tmpdir(), "rea-rizin-signal-"));
|
||||
const path = join(directory, "fixture.bin");
|
||||
await writeFile(path, "fixture");
|
||||
const service = new ReverseEngineeringService({
|
||||
run: async () => {
|
||||
throw Object.assign(new Error("terminated"), {
|
||||
stdout: "partial",
|
||||
stderr: "",
|
||||
code: null,
|
||||
signal: "SIGSEGV",
|
||||
killed: false,
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
const result = await service.executeRizinCommand({ path, command: "iI" });
|
||||
expect(result.ok).toBe(true);
|
||||
if (result.ok)
|
||||
expect(result.value.raw_result).toMatchObject({
|
||||
signal: "SIGSEGV",
|
||||
exit_code: null,
|
||||
completion_status: "unknown",
|
||||
});
|
||||
} finally {
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,103 @@
|
||||
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { TestReverseEngineeringService } from "../support/reverseEngineeringService.js";
|
||||
|
||||
it("bounds concurrent reverse-engineering provider calls", async () => {
|
||||
const directory = await mkdtemp(join(tmpdir(), "rea-reverse-capacity-"));
|
||||
const path = join(directory, "fixture.bin");
|
||||
await writeFile(path, "fixture");
|
||||
let release!: () => void;
|
||||
const gate = new Promise<void>((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
let calls = 0;
|
||||
let mode: "success" | "failure" | "timeout" = "success";
|
||||
const service = new TestReverseEngineeringService({
|
||||
run: async () => {
|
||||
calls += 1;
|
||||
if (mode === "failure")
|
||||
throw Object.assign(new Error("provider failed"), { code: "ENOENT" });
|
||||
if (mode === "timeout")
|
||||
throw Object.assign(new Error("provider timed out"), {
|
||||
code: "ETIMEDOUT",
|
||||
});
|
||||
await gate;
|
||||
return { stdout: "", stderr: "" };
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
const active = Array.from({ length: 8 }, () =>
|
||||
service.inspectWithObjdump({ path, operation: "file_headers" }),
|
||||
);
|
||||
const preAborted = new AbortController();
|
||||
preAborted.abort();
|
||||
await expect(
|
||||
service.inspectWithObjdump(
|
||||
{ path, operation: "file_headers" },
|
||||
{ signal: preAborted.signal },
|
||||
),
|
||||
).resolves.toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "AnalysisCancelledError" },
|
||||
});
|
||||
await expect(
|
||||
service.inspectWithObjdump({ path, operation: "file_headers" }),
|
||||
).resolves.toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
_tag: "AnalysisResourceConstraintError",
|
||||
resource: "transport",
|
||||
reportedLimits: {
|
||||
max_concurrent_operations: 8,
|
||||
active_operations: 8,
|
||||
},
|
||||
},
|
||||
});
|
||||
release();
|
||||
const results = await Promise.all(active);
|
||||
expect(results.every((result) => result.ok)).toBe(true);
|
||||
expect(calls).toBe(8);
|
||||
|
||||
mode = "failure";
|
||||
const failed = await Promise.all(
|
||||
Array.from({ length: 8 }, () =>
|
||||
service.inspectWithObjdump({ path, operation: "file_headers" }),
|
||||
),
|
||||
);
|
||||
expect(failed.every((result) => !result.ok)).toBe(true);
|
||||
|
||||
mode = "timeout";
|
||||
const timedOut = await Promise.all(
|
||||
Array.from({ length: 8 }, () =>
|
||||
service.inspectWithObjdump({ path, operation: "file_headers" }),
|
||||
),
|
||||
);
|
||||
expect(timedOut.every((result) => !result.ok)).toBe(true);
|
||||
|
||||
const aborted = new AbortController();
|
||||
aborted.abort();
|
||||
const cancelled = await Promise.all(
|
||||
Array.from({ length: 8 }, () =>
|
||||
service.inspectWithObjdump(
|
||||
{ path, operation: "file_headers" },
|
||||
{ signal: aborted.signal },
|
||||
),
|
||||
),
|
||||
);
|
||||
expect(cancelled.every((result) => !result.ok)).toBe(true);
|
||||
|
||||
mode = "success";
|
||||
await expect(
|
||||
service.inspectWithObjdump({ path, operation: "file_headers" }),
|
||||
).resolves.toMatchObject({ ok: true });
|
||||
} finally {
|
||||
release();
|
||||
await service.close();
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,288 @@
|
||||
import { chmod, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { TestReverseEngineeringService as ReverseEngineeringService } from "../support/reverseEngineeringService.js";
|
||||
|
||||
type PromiseOutcome<Value> =
|
||||
| { readonly status: "fulfilled"; readonly value: Value }
|
||||
| { readonly status: "rejected"; readonly reason: unknown }
|
||||
| { readonly status: "timeout" };
|
||||
|
||||
const settleWithin = async <Value>(
|
||||
promise: Promise<Value>,
|
||||
timeoutMs: number,
|
||||
): Promise<PromiseOutcome<Value>> => {
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
try {
|
||||
return await Promise.race([
|
||||
promise.then(
|
||||
(value): PromiseOutcome<Value> => ({ status: "fulfilled", value }),
|
||||
(reason: unknown): PromiseOutcome<Value> => ({
|
||||
status: "rejected",
|
||||
reason,
|
||||
}),
|
||||
),
|
||||
new Promise<PromiseOutcome<Value>>((resolve) => {
|
||||
timer = setTimeout(() => resolve({ status: "timeout" }), timeoutMs);
|
||||
}),
|
||||
]);
|
||||
} finally {
|
||||
if (timer !== undefined) clearTimeout(timer);
|
||||
}
|
||||
};
|
||||
|
||||
const processIsRunning = (pid: number): boolean => {
|
||||
try {
|
||||
process.kill(pid, 0);
|
||||
return true;
|
||||
} catch (cause) {
|
||||
return !(
|
||||
cause instanceof Error &&
|
||||
"code" in cause &&
|
||||
cause.code === "ESRCH"
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const waitForProcessExit = async (
|
||||
pid: number,
|
||||
timeoutMs: number,
|
||||
): Promise<boolean> => {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
while (Date.now() < deadline) {
|
||||
if (!processIsRunning(pid)) return true;
|
||||
await new Promise((resolve) => setTimeout(resolve, 10));
|
||||
}
|
||||
return !processIsRunning(pid);
|
||||
};
|
||||
|
||||
const killProcessAndWait = async (
|
||||
pid: number,
|
||||
timeoutMs: number,
|
||||
): Promise<boolean> => {
|
||||
try {
|
||||
process.kill(pid, "SIGKILL");
|
||||
} catch (cause) {
|
||||
if (!(cause instanceof Error && "code" in cause && cause.code === "ESRCH"))
|
||||
throw cause;
|
||||
}
|
||||
return waitForProcessExit(pid, timeoutMs);
|
||||
};
|
||||
|
||||
type CancellationResult = Awaited<
|
||||
ReturnType<ReverseEngineeringService["executeRizinCommand"]>
|
||||
>;
|
||||
|
||||
interface CancellationProcessMarkers {
|
||||
readonly providerPid: string;
|
||||
readonly descendantPid: string;
|
||||
readonly descendantStarted: string;
|
||||
}
|
||||
|
||||
interface CancellationProcessIds {
|
||||
readonly providerPid: number;
|
||||
readonly descendantPid: number;
|
||||
}
|
||||
|
||||
const readProcessMarker = async (path: string): Promise<number | undefined> => {
|
||||
const text = await readFile(path, "utf8").catch(() => "");
|
||||
const pid = Number(text);
|
||||
return Number.isSafeInteger(pid) && pid > 0 ? pid : undefined;
|
||||
};
|
||||
|
||||
const waitForCancellationProcesses = async (
|
||||
markers: CancellationProcessMarkers,
|
||||
): Promise<CancellationProcessIds> => {
|
||||
for (let attempt = 0; attempt < 500; attempt += 1) {
|
||||
const [providerPid, descendantPid, descendantStarted] = await Promise.all([
|
||||
readProcessMarker(markers.providerPid),
|
||||
readProcessMarker(markers.descendantPid),
|
||||
readFile(markers.descendantStarted).then(
|
||||
() => true,
|
||||
() => false,
|
||||
),
|
||||
]);
|
||||
if (
|
||||
providerPid !== undefined &&
|
||||
descendantPid !== undefined &&
|
||||
descendantStarted
|
||||
)
|
||||
return { providerPid, descendantPid };
|
||||
await new Promise((resolveDelay) => setTimeout(resolveDelay, 10));
|
||||
}
|
||||
throw new Error("Rizin provider and descendant did not start in time.");
|
||||
};
|
||||
|
||||
const killCancellationProcesses = async (
|
||||
ids: CancellationProcessIds,
|
||||
): Promise<void> => {
|
||||
expect(await killProcessAndWait(ids.providerPid, 2_000)).toBe(true);
|
||||
expect(await killProcessAndWait(ids.descendantPid, 2_000)).toBe(true);
|
||||
};
|
||||
|
||||
const settleCancelledProvider = async (
|
||||
pending: Promise<CancellationResult>,
|
||||
): Promise<CancellationResult> => {
|
||||
const outcome = await settleWithin(pending, 7_000);
|
||||
if (outcome.status === "timeout")
|
||||
throw new Error("Rizin cancellation did not settle before its deadline");
|
||||
if (outcome.status === "rejected") throw outcome.reason;
|
||||
return outcome.value;
|
||||
};
|
||||
|
||||
const expectCancelledResult = (result: CancellationResult): void => {
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) return;
|
||||
expect(result.error._tag).toBe("AnalysisCancelledError");
|
||||
expect(result.error.cleanup).toBeUndefined();
|
||||
expect(result.error.capturedOutput).toMatchObject({
|
||||
stdout: "provider output before cancellation",
|
||||
stderr: "",
|
||||
truncated: false,
|
||||
exit_code: null,
|
||||
signal: "SIGKILL",
|
||||
});
|
||||
expect(result.error.cause).toBeInstanceOf(Error);
|
||||
expect(result.error.partialObservation).toMatchObject({
|
||||
raw_result: {
|
||||
stdout: "provider output before cancellation",
|
||||
completion_status: "unknown",
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const cleanupCancellationScenario = async (options: {
|
||||
readonly controller: AbortController;
|
||||
readonly pending: Promise<CancellationResult> | undefined;
|
||||
readonly service: ReverseEngineeringService;
|
||||
readonly processIds: CancellationProcessIds | undefined;
|
||||
readonly directory: string;
|
||||
}): Promise<void> => {
|
||||
options.controller.abort();
|
||||
try {
|
||||
if (options.pending !== undefined) {
|
||||
try {
|
||||
if (options.processIds !== undefined)
|
||||
await settleCancelledProvider(options.pending);
|
||||
else await settleWithin(options.pending, 10_000);
|
||||
} catch {
|
||||
// Main assertions report operation failures; continue cleanup.
|
||||
}
|
||||
}
|
||||
let cleanup = await settleWithin(options.service.close(), 7_000);
|
||||
if (cleanup.status === "timeout" && options.processIds !== undefined) {
|
||||
await killCancellationProcesses(options.processIds);
|
||||
cleanup = await settleWithin(options.service.close(), 3_000);
|
||||
}
|
||||
if (cleanup.status === "timeout")
|
||||
throw new Error("Service cleanup did not settle within its deadline.");
|
||||
if (cleanup.status === "rejected") throw cleanup.reason;
|
||||
if (options.processIds !== undefined) {
|
||||
for (const pid of [
|
||||
options.processIds.providerPid,
|
||||
options.processIds.descendantPid,
|
||||
]) {
|
||||
if (processIsRunning(pid)) await killProcessAndWait(pid, 2_000);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
await rm(options.directory, { recursive: true, force: true });
|
||||
}
|
||||
};
|
||||
|
||||
it("uses stoppable process mode for caller-selected provider commands", async () => {
|
||||
const directory = await mkdtemp(join(tmpdir(), "rea-rizin-stoppable-"));
|
||||
const path = join(directory, "fixture.bin");
|
||||
await writeFile(path, "fixture");
|
||||
let received: Record<string, unknown> | undefined;
|
||||
const service = new ReverseEngineeringService({
|
||||
run: async (_command, _args, options) => {
|
||||
received = options as Record<string, unknown>;
|
||||
return { stdout: "", stderr: "" };
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
await service.executeRizinCommand({ path, command: "iI" });
|
||||
expect(received?.stopSignal).toBe("SIGTERM");
|
||||
} finally {
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"waits for a cancelled Rizin process to exit before returning",
|
||||
async () => {
|
||||
const directory = await mkdtemp(join(tmpdir(), "rea-rizin-cancel-settle-"));
|
||||
const path = join(directory, "fixture.bin");
|
||||
const providerPidMarker = join(directory, "provider-pid");
|
||||
const descendantStartedMarker = join(directory, "descendant-started");
|
||||
const descendantPidMarker = join(directory, "descendant-pid");
|
||||
const provider = join(directory, "slow-rizin.mjs");
|
||||
const descendantScript = [
|
||||
"const fs = require('node:fs');",
|
||||
"process.on('SIGTERM', () => {});",
|
||||
"fs.writeFileSync(process.env.REA_TEST_DESCENDANT_STARTED, 'started');",
|
||||
"setInterval(() => {}, 1000);",
|
||||
].join("\n");
|
||||
await writeFile(path, "before");
|
||||
await writeFile(
|
||||
provider,
|
||||
`#!${process.execPath}
|
||||
import { spawn } from "node:child_process";
|
||||
import { writeFileSync } from "node:fs";
|
||||
writeFileSync(process.env.REA_TEST_PROVIDER_PID, String(process.pid));
|
||||
process.stdout.write("provider output before cancellation");
|
||||
const child = spawn(process.execPath, ["-e", ${JSON.stringify(descendantScript)}], { env: process.env, stdio: "ignore" });
|
||||
writeFileSync(process.env.REA_TEST_DESCENDANT_PID, String(child.pid));
|
||||
setInterval(() => {}, 1000);
|
||||
`,
|
||||
);
|
||||
await chmod(provider, 0o755);
|
||||
const controller = new AbortController();
|
||||
const service = new ReverseEngineeringService({
|
||||
environment: {
|
||||
REA_RIZIN_COMMAND: provider,
|
||||
REA_TEST_ARTIFACT: path,
|
||||
REA_TEST_PROVIDER_PID: providerPidMarker,
|
||||
REA_TEST_DESCENDANT_STARTED: descendantStartedMarker,
|
||||
REA_TEST_DESCENDANT_PID: descendantPidMarker,
|
||||
},
|
||||
});
|
||||
|
||||
let pending: ReturnType<typeof service.executeRizinCommand> | undefined;
|
||||
let processIds: CancellationProcessIds | undefined;
|
||||
try {
|
||||
pending = service.executeRizinCommand(
|
||||
{ path, command: "sleep" },
|
||||
{ signal: controller.signal },
|
||||
);
|
||||
processIds = await waitForCancellationProcesses({
|
||||
providerPid: providerPidMarker,
|
||||
descendantPid: descendantPidMarker,
|
||||
descendantStarted: descendantStartedMarker,
|
||||
});
|
||||
controller.abort();
|
||||
|
||||
expectCancelledResult(await settleCancelledProvider(pending));
|
||||
expect(await readFile(path, "utf8")).toBe("before");
|
||||
expect(await waitForProcessExit(processIds.descendantPid, 2_000)).toBe(
|
||||
true,
|
||||
);
|
||||
expect(await waitForProcessExit(processIds.providerPid, 2_000)).toBe(
|
||||
true,
|
||||
);
|
||||
} finally {
|
||||
await cleanupCancellationScenario({
|
||||
controller,
|
||||
pending,
|
||||
service,
|
||||
processIds,
|
||||
directory,
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,114 @@
|
||||
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { expect, it, vi } from "vitest";
|
||||
|
||||
import { ReverseEngineeringService } from "../../src/application/reverse/ReverseEngineeringService.js";
|
||||
import { REVERSE_ENGINEERING_TOOL_CONTRACTS } from "../../src/contracts/reverseEngineeringToolContracts.js";
|
||||
import { execFileOutput } from "../../src/process/ExecFileOutput.js";
|
||||
|
||||
type ExecFileOutputOptions = NonNullable<Parameters<typeof execFileOutput>[2]>;
|
||||
|
||||
it("documents the shared combined capture limit for both command tools", () => {
|
||||
for (const contract of REVERSE_ENGINEERING_TOOL_CONTRACTS)
|
||||
expect(contract.description).toContain("shared 16 MiB combined limit");
|
||||
});
|
||||
|
||||
it("uses provider profiles supplied through the application port", async () => {
|
||||
const directory = await mkdtemp(join(tmpdir(), "rea-reverse-port-"));
|
||||
const path = join(directory, "fixture.bin");
|
||||
await writeFile(path, Buffer.from([0x7f, 0x45, 0x4c, 0x46]));
|
||||
const run = vi.fn(
|
||||
async (
|
||||
_command: string,
|
||||
_args: readonly string[],
|
||||
_options?: ExecFileOutputOptions,
|
||||
) => ({ stdout: "injected", stderr: "" }),
|
||||
);
|
||||
const service = new ReverseEngineeringService({
|
||||
environment: { REA_OBJDUMP_COMMAND: "ambient-objdump" },
|
||||
commands: {
|
||||
objdump: () => ({
|
||||
executable: "injected-objdump",
|
||||
arguments: ["--injected", path],
|
||||
identity: {
|
||||
id: "test.objdump",
|
||||
name: "Injected objdump",
|
||||
version: null,
|
||||
},
|
||||
environmentOverrides: { INJECTED_PROFILE: "yes" },
|
||||
}),
|
||||
rizin: () => ({
|
||||
executable: "injected-rizin",
|
||||
arguments: ["--injected", path],
|
||||
identity: { id: "test.rizin", name: "Injected Rizin", version: null },
|
||||
}),
|
||||
},
|
||||
run,
|
||||
});
|
||||
|
||||
try {
|
||||
const result = await service.inspectWithObjdump({
|
||||
path,
|
||||
operation: "file_headers",
|
||||
});
|
||||
expect(result.ok).toBe(true);
|
||||
const call = run.mock.calls[0];
|
||||
expect(call?.[0]).toBe("injected-objdump");
|
||||
expect(call?.[1]).toEqual(["--injected", path]);
|
||||
expect(call?.[2]?.env?.INJECTED_PROFILE).toBe("yes");
|
||||
if (result.ok) expect(result.value.provider.id).toBe("test.objdump");
|
||||
} finally {
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("does not reintroduce ambient variables absent from the captured provider environment", async () => {
|
||||
const directory = await mkdtemp(join(tmpdir(), "rea-reverse-env-"));
|
||||
const path = join(directory, "fixture.bin");
|
||||
const variable = "REA_TEST_LATE_PROVIDER_ENV";
|
||||
const previous = process.env[variable];
|
||||
await writeFile(path, Buffer.from([0x7f, 0x45, 0x4c, 0x46]));
|
||||
process.env[variable] = "late-ambient-value";
|
||||
const run = vi.fn(
|
||||
async (
|
||||
_command: string,
|
||||
_args: readonly string[],
|
||||
_options?: ExecFileOutputOptions,
|
||||
) => ({ stdout: "captured", stderr: "" }),
|
||||
);
|
||||
const service = new ReverseEngineeringService({
|
||||
environment: { REA_OBJDUMP_COMMAND: "captured-objdump" },
|
||||
commands: {
|
||||
objdump: () => ({
|
||||
executable: "captured-objdump",
|
||||
arguments: [path],
|
||||
identity: {
|
||||
id: "test.objdump",
|
||||
name: "Captured objdump",
|
||||
version: null,
|
||||
},
|
||||
environmentOverrides: { PROFILE_VALUE: "explicit" },
|
||||
}),
|
||||
rizin: () => ({
|
||||
executable: "captured-rizin",
|
||||
arguments: [path],
|
||||
identity: { id: "test.rizin", name: "Captured Rizin", version: null },
|
||||
}),
|
||||
},
|
||||
run,
|
||||
});
|
||||
|
||||
try {
|
||||
await service.inspectWithObjdump({ path, operation: "file_headers" });
|
||||
expect(run.mock.calls[0]?.[2]?.env).toEqual({
|
||||
REA_OBJDUMP_COMMAND: "captured-objdump",
|
||||
PROFILE_VALUE: "explicit",
|
||||
});
|
||||
} finally {
|
||||
if (previous === undefined) delete process.env[variable];
|
||||
else process.env[variable] = previous;
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,31 @@
|
||||
import { rm } from "node:fs/promises";
|
||||
import { createArtifact } from "../support/reverseEngineeringCompositionFixtures.js";
|
||||
|
||||
import { expect, it, vi } from "vitest";
|
||||
|
||||
import { TestReverseEngineeringService as ReverseEngineeringService } from "../support/reverseEngineeringService.js";
|
||||
|
||||
it("rejects NUL in a Rizin command before touching the provider", async () => {
|
||||
const { directory, path } = await createArtifact();
|
||||
let invoked = false;
|
||||
const service = new ReverseEngineeringService({
|
||||
run: async () => {
|
||||
invoked = true;
|
||||
return { stdout: "", stderr: "" };
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
const result = await service.executeRizinCommand({
|
||||
path,
|
||||
command: "wx\u0000 00",
|
||||
});
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "AnalysisInputError", operation: "execute_rizin_command" },
|
||||
});
|
||||
expect(invoked).toBe(false);
|
||||
} finally {
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
Reference in New Issue
Block a user