fix(javascript): integrate current main stability fixes
Include the merged Hopper reconnect-listener readiness fix so local and CI validation use the same current main recovery boundary. Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com> Co-authored-by: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com>
This commit is contained in:
co-authored by
factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>
Kaoru0822
commit
b60248c462
@@ -86,6 +86,40 @@ it("accepts a full JDK and canonicalizes the selected JAR", async () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("admits engine classes past repeated ZIP resource filenames", async () => {
|
||||
const root = await createTestTempDirectory("rea-jadx-duplicate-resource-");
|
||||
const jar = join(root, "engine.jar");
|
||||
const javaHome = await createFakeJdk(root);
|
||||
await writeOrderedZip(jar, [
|
||||
"META-INF/LICENSE.txt",
|
||||
"META-INF/LICENCE.txt",
|
||||
"com/atxx/jhmcp/JadxSession.class",
|
||||
"com/atxx/jhmcp/SessionHolder.class",
|
||||
"jadx/api/JadxDecompiler.class",
|
||||
"com/google/gson/Gson.class",
|
||||
"io/modelcontextprotocol/kotlin/sdk/server/Server.class",
|
||||
]);
|
||||
const bytes = await readFile(jar);
|
||||
const original = Buffer.from("META-INF/LICENCE.txt");
|
||||
let renamed = 0;
|
||||
for (
|
||||
let offset = bytes.indexOf(original);
|
||||
offset >= 0;
|
||||
offset = bytes.indexOf(original, offset + original.length)
|
||||
) {
|
||||
bytes.write("META-INF/LICENSE.txt", offset);
|
||||
renamed++;
|
||||
}
|
||||
expect(renamed).toBe(2);
|
||||
await writeFile(jar, bytes);
|
||||
await expect(
|
||||
resolveConfiguration(
|
||||
{ REA_JADX_MCP_JAR: jar, JAVA_HOME: javaHome },
|
||||
"inspect_android_package",
|
||||
),
|
||||
).resolves.toMatchObject({ jar: await realpath(jar) });
|
||||
});
|
||||
|
||||
it("configures heap and visible processors independently without forcing either", async () => {
|
||||
const root = await createTestTempDirectory("rea-jadx-config-");
|
||||
const jar = join(root, "engine.jar");
|
||||
|
||||
@@ -1,4 +1,12 @@
|
||||
import { access, readFile, writeFile } from "node:fs/promises";
|
||||
import {
|
||||
access,
|
||||
lstat,
|
||||
mkdir,
|
||||
readFile,
|
||||
realpath,
|
||||
symlink,
|
||||
writeFile,
|
||||
} from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { expect } from "vitest";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
@@ -78,6 +86,54 @@ const groups = [
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
cliTest(
|
||||
"uninstall purge retains unrelated data behind a managed-root symlink",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-uninstall-root-link-");
|
||||
const home = join(root, "home");
|
||||
const unrelated = join(root, "unrelated-application");
|
||||
await mkdir(home);
|
||||
for (const name of ["cache", "state"]) {
|
||||
await mkdir(join(unrelated, name), { recursive: true });
|
||||
await writeFile(join(unrelated, name, "keep.txt"), `unrelated ${name}`);
|
||||
}
|
||||
const managedRoot = join(home, ".rea");
|
||||
await symlink(
|
||||
unrelated,
|
||||
managedRoot,
|
||||
process.platform === "win32" ? "junction" : "dir",
|
||||
);
|
||||
|
||||
const result = await cli.run({
|
||||
arguments: ["uninstall", "--purge-data", "--json"],
|
||||
cwd: home,
|
||||
environment: {
|
||||
HOME: home,
|
||||
USERPROFILE: home,
|
||||
XDG_CONFIG_HOME: join(root, "xdg-config"),
|
||||
XDG_CACHE_HOME: join(root, "xdg-cache"),
|
||||
},
|
||||
timeoutMs: 20_000,
|
||||
});
|
||||
|
||||
expect(result.exitCode, result.stderr).toBe(0);
|
||||
expect.soft(result.json).toMatchObject({
|
||||
status: "complete",
|
||||
items: expect.arrayContaining([
|
||||
expect.objectContaining({ name: "cache", status: "retained" }),
|
||||
expect.objectContaining({ name: "state", status: "retained" }),
|
||||
]),
|
||||
});
|
||||
expect((await lstat(managedRoot)).isSymbolicLink()).toBe(true);
|
||||
expect(await realpath(managedRoot)).toBe(await realpath(unrelated));
|
||||
for (const name of ["cache", "state"])
|
||||
await expect
|
||||
.soft(readFile(join(unrelated, name, "keep.txt"), "utf8"))
|
||||
.resolves.toBe(`unrelated ${name}`);
|
||||
},
|
||||
);
|
||||
|
||||
for (const group of groups) {
|
||||
cliTest(
|
||||
`${group.name} lifecycle follows the selected roots`,
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { expect } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
|
||||
cliTest(
|
||||
"rejects a headerless image until architecture and entry are supplied",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-raw-cli-");
|
||||
const path = join(root, "ecu.bin");
|
||||
await writeFile(path, Buffer.from("1eff2fe1", "hex"));
|
||||
const before = await cli.run({
|
||||
arguments: ["inspect", path, "--json"],
|
||||
environment: {
|
||||
HOME: root,
|
||||
XDG_CONFIG_HOME: root,
|
||||
XDG_CACHE_HOME: root,
|
||||
},
|
||||
});
|
||||
expect(before.exitCode).not.toBe(0);
|
||||
expect(JSON.stringify(before.json)).not.toContain("raw-binary");
|
||||
const missing = await cli.run({
|
||||
arguments: ["inspect", path, "--target-format", "raw-binary", "--json"],
|
||||
environment: {
|
||||
HOME: root,
|
||||
XDG_CONFIG_HOME: root,
|
||||
XDG_CACHE_HOME: root,
|
||||
},
|
||||
});
|
||||
expect(missing.exitCode).toBe(1);
|
||||
expect(missing.json).toMatchObject({
|
||||
code: "target_unavailable",
|
||||
details: { reason: expect.stringContaining("architecture") },
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"rejects an unaligned AArch64 entry before provider startup",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-raw-cli-alignment-");
|
||||
const path = join(root, "image.bin");
|
||||
await writeFile(path, Buffer.from("c0035fd6", "hex"));
|
||||
const result = await cli.run({
|
||||
arguments: [
|
||||
"inspect",
|
||||
path,
|
||||
"--target-format",
|
||||
"raw-binary",
|
||||
"--architecture",
|
||||
"arm64",
|
||||
"--entry-point",
|
||||
"0x8000001",
|
||||
"--provider",
|
||||
"ghidra",
|
||||
"--json",
|
||||
],
|
||||
environment: { HOME: root, XDG_CONFIG_HOME: root, XDG_CACHE_HOME: root },
|
||||
});
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.json).toMatchObject({
|
||||
code: "target_unavailable",
|
||||
details: { reason: expect.stringContaining("must be 4-byte aligned") },
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"stops Hopper from claiming a caller-supplied raw-binary image",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-raw-cli-hopper-");
|
||||
const path = join(root, "ecu.bin");
|
||||
await writeFile(path, Buffer.from("1eff2fe1", "hex"));
|
||||
const result = await cli.run({
|
||||
arguments: [
|
||||
"inspect",
|
||||
path,
|
||||
"--target-format",
|
||||
"raw-binary",
|
||||
"--architecture",
|
||||
"arm",
|
||||
"--entry-point",
|
||||
"0x8000000",
|
||||
"--provider",
|
||||
"hopper",
|
||||
"--json",
|
||||
],
|
||||
environment: {
|
||||
HOME: root,
|
||||
XDG_CONFIG_HOME: root,
|
||||
XDG_CACHE_HOME: root,
|
||||
},
|
||||
});
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(JSON.stringify(result.json)).toMatch(/Hopper|ghidra|Ghidra|hopper/i);
|
||||
expect(JSON.stringify(result.json)).not.toMatch(
|
||||
/unsupported binary format/i,
|
||||
);
|
||||
},
|
||||
);
|
||||
@@ -77,7 +77,7 @@ it("binds ZIP opens to the emitted entry metadata", async () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects duplicate ZIP names before replacing an emitted entry", async () => {
|
||||
it("retains duplicate ZIP members without replacing their source identities", async () => {
|
||||
const root = await createTestTempDirectory("rea-zip-duplicate-identity-");
|
||||
const path = join(root, "duplicates.zip");
|
||||
const writer = new ZipWriter(new Uint8ArrayWriter());
|
||||
@@ -106,11 +106,20 @@ it("rejects duplicate ZIP names before replacing an emitted entry", async () =>
|
||||
const iterator = reader.entries()[Symbol.asyncIterator]();
|
||||
const first = await iterator.next();
|
||||
if (first.done) throw new Error("Expected the first ZIP member");
|
||||
await expect(iterator.next()).rejects.toMatchObject({ reason: "path" });
|
||||
const stream = await reader.open({ ...first.value });
|
||||
const chunks: Buffer[] = [];
|
||||
for await (const chunk of stream) chunks.push(Buffer.from(chunk));
|
||||
expect(Buffer.concat(chunks).toString()).toBe("first bytes\n");
|
||||
const second = await iterator.next();
|
||||
if (second.done) throw new Error("Expected the second ZIP member");
|
||||
expect(first.value.path).toBe(second.value.path);
|
||||
expect(first.value.adapterKey).not.toBe(second.value.adapterKey);
|
||||
expect((await iterator.next()).done).toBe(true);
|
||||
for (const [entry, expected] of [
|
||||
[first.value, "first bytes\n"],
|
||||
[second.value, "later bytes\n"],
|
||||
] as const) {
|
||||
const chunks: Buffer[] = [];
|
||||
for await (const chunk of await reader.open({ ...entry }))
|
||||
chunks.push(Buffer.from(chunk));
|
||||
expect(Buffer.concat(chunks).toString()).toBe(expected);
|
||||
}
|
||||
} finally {
|
||||
await reader.close();
|
||||
}
|
||||
|
||||
@@ -1341,6 +1341,146 @@ describe("Codex configuration comments", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("managed data purge root validation", () => {
|
||||
it.each(["existing", "dangling"] as const)(
|
||||
"retains cache and state when the managed-root symlink is %s",
|
||||
async (targetState) => {
|
||||
const root = await createTestTempDirectory("rea-uninstall-data-root-");
|
||||
roots.push(root);
|
||||
const home = join(root, "home");
|
||||
const outside = join(root, "unrelated-application");
|
||||
await mkdir(home);
|
||||
if (targetState === "existing")
|
||||
for (const name of ["cache", "state"]) {
|
||||
await mkdir(join(outside, name), { recursive: true });
|
||||
await writeFile(join(outside, name, "keep.txt"), "unrelated data");
|
||||
}
|
||||
const managedRoot = join(home, ".rea");
|
||||
await symlink(
|
||||
outside,
|
||||
managedRoot,
|
||||
process.platform === "win32" ? "junction" : "dir",
|
||||
);
|
||||
|
||||
const result = await runUninstall(
|
||||
true,
|
||||
systemUninstallHost(home, undefined, {}),
|
||||
);
|
||||
|
||||
expect(result.status).toBe("complete");
|
||||
expect((await lstat(managedRoot)).isSymbolicLink()).toBe(true);
|
||||
for (const name of ["cache", "state"])
|
||||
expect(result.items).toContainEqual(
|
||||
expect.objectContaining({ name, status: "retained" }),
|
||||
);
|
||||
if (targetState === "existing")
|
||||
for (const name of ["cache", "state"])
|
||||
expect(await readFile(join(outside, name, "keep.txt"), "utf8")).toBe(
|
||||
"unrelated data",
|
||||
);
|
||||
else
|
||||
await expect(lstat(outside)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
},
|
||||
);
|
||||
|
||||
it("retains a managed data root that is not a directory", async () => {
|
||||
const home = await createTestTempDirectory("rea-uninstall-data-file-");
|
||||
roots.push(home);
|
||||
const managedRoot = join(home, ".rea");
|
||||
await writeFile(managedRoot, "unrelated file");
|
||||
|
||||
const result = await runUninstall(
|
||||
true,
|
||||
systemUninstallHost(home, undefined, {}),
|
||||
);
|
||||
|
||||
expect(result.status).toBe("complete");
|
||||
for (const name of ["cache", "state"])
|
||||
expect(result.items).toContainEqual(
|
||||
expect.objectContaining({ name, status: "retained" }),
|
||||
);
|
||||
expect(await readFile(managedRoot, "utf8")).toBe("unrelated file");
|
||||
});
|
||||
|
||||
it("purges ordinary managed data through a legitimate home directory link", async () => {
|
||||
const root = await createTestTempDirectory("rea-uninstall-home-link-");
|
||||
roots.push(root);
|
||||
const home = join(root, "actual-home");
|
||||
const linkedHome = join(root, "linked-home");
|
||||
const managedRoot = join(home, ".rea");
|
||||
for (const name of ["cache", "state"]) {
|
||||
await mkdir(join(managedRoot, name), { recursive: true });
|
||||
await writeFile(join(managedRoot, name, "data.txt"), "managed data");
|
||||
}
|
||||
await writeFile(join(managedRoot, "keep.txt"), "other data");
|
||||
await symlink(
|
||||
home,
|
||||
linkedHome,
|
||||
process.platform === "win32" ? "junction" : "dir",
|
||||
);
|
||||
|
||||
const result = await runUninstall(
|
||||
true,
|
||||
systemUninstallHost(linkedHome, undefined, {}),
|
||||
);
|
||||
|
||||
expect(result.status).toBe("complete");
|
||||
for (const name of ["cache", "state"]) {
|
||||
expect(result.items).toContainEqual(
|
||||
expect.objectContaining({ name, status: "removed" }),
|
||||
);
|
||||
await expect(lstat(join(managedRoot, name))).rejects.toMatchObject({
|
||||
code: "ENOENT",
|
||||
});
|
||||
}
|
||||
expect((await lstat(linkedHome)).isSymbolicLink()).toBe(true);
|
||||
expect(await readFile(join(managedRoot, "keep.txt"), "utf8")).toBe(
|
||||
"other data",
|
||||
);
|
||||
});
|
||||
|
||||
it("reports root inspection failure without removing managed data", async () => {
|
||||
const home = await createTestTempDirectory("rea-uninstall-data-denied-");
|
||||
roots.push(home);
|
||||
const managedRoot = join(home, ".rea");
|
||||
for (const name of ["cache", "state"]) {
|
||||
await mkdir(join(managedRoot, name), { recursive: true });
|
||||
await writeFile(join(managedRoot, name, "keep.txt"), "managed data");
|
||||
}
|
||||
const remove = vi.fn(testFileSystem.remove);
|
||||
const result = await runUninstall(
|
||||
true,
|
||||
systemUninstallHost(
|
||||
home,
|
||||
{
|
||||
...testFileSystem,
|
||||
stat: (path) =>
|
||||
path === managedRoot
|
||||
? Promise.reject(
|
||||
Object.assign(new Error("root inspection denied"), {
|
||||
code: "EACCES",
|
||||
}),
|
||||
)
|
||||
: lstat(path),
|
||||
remove,
|
||||
},
|
||||
{},
|
||||
),
|
||||
);
|
||||
|
||||
expect(result.status).toBe("failed");
|
||||
expect(remove).not.toHaveBeenCalled();
|
||||
for (const name of ["cache", "state"]) {
|
||||
expect(result.items).toContainEqual(
|
||||
expect.objectContaining({ name, status: "failed" }),
|
||||
);
|
||||
expect(await readFile(join(managedRoot, name, "keep.txt"), "utf8")).toBe(
|
||||
"managed data",
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("client configuration filesystem removal", () => {
|
||||
it("uninstalls only owned entries and refuses purge symlinks", async () => {
|
||||
const home = await createTestTempDirectory("rea-uninstall-");
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { readFile, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { parseBinaryTarget } from "../../../src/application/BinaryTargetResolver.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
describe("raw-binary admission", () => {
|
||||
it("requires explicit architecture and entry even with a misleading suffix", async () => {
|
||||
const directory = await createTestTempDirectory("rea-raw-target-");
|
||||
const path = join(directory, "fixture.js");
|
||||
const bytes = Buffer.from("1eff2fe1", "hex");
|
||||
await writeFile(path, bytes);
|
||||
const target = await parseBinaryTarget(path, {
|
||||
cwd: directory,
|
||||
hostArchitecture: "arm64",
|
||||
formatHint: "raw-binary",
|
||||
architecture: "arm",
|
||||
entryPoint: "0x08000000",
|
||||
});
|
||||
expect(target).toMatchObject({
|
||||
ok: true,
|
||||
value: {
|
||||
path,
|
||||
format: "raw-binary",
|
||||
kind: "executable",
|
||||
architecture: "arm",
|
||||
availableArchitectures: ["arm"],
|
||||
entryPoint: "0x8000000",
|
||||
entryPointSource: "0x08000000",
|
||||
sha256: createHash("sha256").update(bytes).digest("hex"),
|
||||
},
|
||||
});
|
||||
expect(await readFile(path)).toEqual(bytes);
|
||||
const detected = await parseBinaryTarget(path);
|
||||
expect(detected.ok && detected.value.format).not.toBe("raw-binary");
|
||||
});
|
||||
it("rejects raw-binary without architecture and entry", async () => {
|
||||
const directory = await createTestTempDirectory("rea-raw-missing-");
|
||||
const path = join(directory, "fixture.bin");
|
||||
await writeFile(path, Buffer.from("c3", "hex"));
|
||||
expect(
|
||||
await parseBinaryTarget(path, {
|
||||
cwd: directory,
|
||||
hostArchitecture: "x64",
|
||||
formatHint: "raw-binary",
|
||||
}),
|
||||
).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
_tag: "BinaryTargetError",
|
||||
reason: expect.stringContaining("architecture"),
|
||||
},
|
||||
});
|
||||
});
|
||||
it("rejects architecture without format=raw-binary", async () => {
|
||||
const directory = await createTestTempDirectory("rea-raw-unpaired-");
|
||||
const path = join(directory, "fixture.bin");
|
||||
await writeFile(path, Buffer.from("c3", "hex"));
|
||||
expect(
|
||||
await parseBinaryTarget(path, {
|
||||
cwd: directory,
|
||||
hostArchitecture: "x64",
|
||||
architecture: "arm",
|
||||
entryPoint: "0x8000000",
|
||||
}),
|
||||
).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
_tag: "BinaryTargetError",
|
||||
reason: expect.stringContaining("format=raw-binary"),
|
||||
},
|
||||
});
|
||||
});
|
||||
it("rejects an empty image", async () => {
|
||||
const directory = await createTestTempDirectory("rea-raw-empty-");
|
||||
const path = join(directory, "fixture.bin");
|
||||
await writeFile(path, Buffer.alloc(0));
|
||||
expect(
|
||||
await parseBinaryTarget(path, {
|
||||
cwd: directory,
|
||||
hostArchitecture: "x64",
|
||||
formatHint: "raw-binary",
|
||||
architecture: "x86",
|
||||
entryPoint: "0x1000",
|
||||
}),
|
||||
).toMatchObject({ ok: false, error: { _tag: "BinaryTargetError" } });
|
||||
});
|
||||
it("rejects a contradictory target kind", async () => {
|
||||
const directory = await createTestTempDirectory("rea-raw-kind-");
|
||||
const path = join(directory, "fixture.bin");
|
||||
await writeFile(path, Buffer.from("c3", "hex"));
|
||||
expect(
|
||||
await parseBinaryTarget(path, {
|
||||
cwd: directory,
|
||||
hostArchitecture: "x64",
|
||||
targetKind: "database",
|
||||
formatHint: "raw-binary",
|
||||
architecture: "x86",
|
||||
entryPoint: "0x1000",
|
||||
}),
|
||||
).toMatchObject({ ok: false, error: { _tag: "BinaryTargetError" } });
|
||||
});
|
||||
});
|
||||
@@ -415,8 +415,11 @@ it("exposes the target-free static JavaScript application workflow", async () =>
|
||||
);
|
||||
|
||||
expect(analyzed.isError).not.toBe(true);
|
||||
expect(progress[0]).toBe(0);
|
||||
expect(progress.at(-1)).toBe(1);
|
||||
expect(progress[0]).toBe(1);
|
||||
expect(progress.at(-1)).toBeGreaterThan(1);
|
||||
progress.forEach((value, index) => {
|
||||
expect(value).toBeGreaterThan(progress[index - 1] ?? 0);
|
||||
});
|
||||
const projected = z
|
||||
.object({
|
||||
evidence_id: z.string(),
|
||||
|
||||
@@ -44,7 +44,7 @@ describe("enhanced MCP tools", () => {
|
||||
error: {
|
||||
category: "execution_failure",
|
||||
message:
|
||||
"Analysis returned an unreadable result. Retry once; if it continues, run `rea doctor`.",
|
||||
"Analysis returned an unreadable result. Run `rea doctor` and review the reported details; repeating the unchanged request is not expected to succeed.",
|
||||
},
|
||||
},
|
||||
],
|
||||
|
||||
@@ -96,11 +96,11 @@ describe("enhanced MCP tools", () => {
|
||||
category: "execution_failure",
|
||||
details: { operation: "decompile", reason: "failed" },
|
||||
message:
|
||||
"Analysis returned an unreadable result. Retry once; if it continues, run `rea doctor`.",
|
||||
"Analysis returned an unreadable result. Run `rea doctor` and review the reported details; repeating the unchanged request is not expected to succeed.",
|
||||
retryable: false,
|
||||
remediation: {
|
||||
action:
|
||||
"Analysis returned an unreadable result. Retry once; if it continues, run `rea doctor`.",
|
||||
"Analysis returned an unreadable result. Run `rea doctor` and review the reported details; repeating the unchanged request is not expected to succeed.",
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import { setTimeout as delay } from "node:timers/promises";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import type { AnalysisOperationPort } from "../../../src/application/AnalysisProvider.js";
|
||||
@@ -8,29 +9,52 @@ import { createServer } from "../../../src/server/createServer.js";
|
||||
import { observed } from "../../fixtures/analysisExecution.js";
|
||||
|
||||
describe("ordinary MCP progress and cancellation", () => {
|
||||
it("emits bounded progress for a normal tool request", async () => {
|
||||
it("advances MCP progress when provider waiting does not advance completed work", async () => {
|
||||
const analysis: AnalysisOperationPort = {
|
||||
execute: () => Promise.resolve(observed("0x1000")),
|
||||
execute: async (_operation, _parameters, options) => {
|
||||
for (const message of ["import pending", "analysis pending"]) {
|
||||
await delay(120);
|
||||
await options?.progress?.report({
|
||||
phase: "ghidra_startup",
|
||||
completed: 0,
|
||||
total: null,
|
||||
message,
|
||||
});
|
||||
}
|
||||
return observed("0x1000");
|
||||
},
|
||||
};
|
||||
const server = createServer({ kind: "fixed", analysis });
|
||||
const client = new Client({ name: "progress-test", version: "1" });
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
const progress: number[] = [];
|
||||
const progress: {
|
||||
progress: number;
|
||||
total?: number | undefined;
|
||||
message?: string | undefined;
|
||||
}[] = [];
|
||||
try {
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
const result = await client.callTool(
|
||||
{ name: "current_address", arguments: {} },
|
||||
{ onprogress: (update) => progress.push(update.progress) },
|
||||
{ onprogress: (update) => progress.push(update) },
|
||||
);
|
||||
|
||||
expect(result.isError).not.toBe(true);
|
||||
expect(progress[0]).toBe(0);
|
||||
expect(progress.at(-1)).toBe(1);
|
||||
progress.forEach((value, index) => {
|
||||
expect(value).toBeGreaterThanOrEqual(progress[index - 1] ?? 0);
|
||||
expect(value).toBeLessThanOrEqual(1);
|
||||
expect(progress[0]?.progress).toBe(1);
|
||||
expect(progress.map((update) => update.message)).toEqual(
|
||||
expect.arrayContaining([
|
||||
"ghidra_startup: import pending",
|
||||
"ghidra_startup: analysis pending",
|
||||
]),
|
||||
);
|
||||
expect(progress.at(-1)?.message).toContain("completed");
|
||||
progress.forEach((update, index) => {
|
||||
expect(update.progress).toBeGreaterThan(
|
||||
progress[index - 1]?.progress ?? 0,
|
||||
);
|
||||
expect(update.total).toBeUndefined();
|
||||
});
|
||||
} finally {
|
||||
await Promise.allSettled([client.close(), server.close()]);
|
||||
|
||||
@@ -0,0 +1,219 @@
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import { Ajv2020 } from "ajv/dist/2020.js";
|
||||
import { expect, it, onTestFinished } from "vitest";
|
||||
import { z } from "zod";
|
||||
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import { toolContract } from "../../../src/contracts/toolContracts.js";
|
||||
import type { AnalysisProvider } from "../../../src/application/AnalysisProvider.js";
|
||||
import { createAnalysisProfile } from "../../../src/domain/analysisProfile.js";
|
||||
import { ok } from "../../../src/domain/result.js";
|
||||
import { observed } from "../../fixtures/analysisExecution.js";
|
||||
import {
|
||||
createCacheProvider,
|
||||
createTestBinarySession,
|
||||
} from "../../fixtures/binarySession.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { silentLogger } from "../../../src/logger.js";
|
||||
import type { CallToolResult } from "@modelcontextprotocol/server";
|
||||
|
||||
const connect = async (
|
||||
provider: AnalysisProvider = createCacheProvider([]),
|
||||
) => {
|
||||
const session = createTestBinarySession(provider);
|
||||
const server = createServer(
|
||||
{ kind: "session", session },
|
||||
{ logger: silentLogger },
|
||||
);
|
||||
const client = new Client({ name: "raw-binary-mcp", version: "1" });
|
||||
onTestFinished(async () => {
|
||||
await client.close();
|
||||
await server.close();
|
||||
await session.close();
|
||||
});
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
return { client, session };
|
||||
};
|
||||
|
||||
const structured = (result: CallToolResult): Record<string, unknown> => {
|
||||
if (
|
||||
typeof result.structuredContent !== "object" ||
|
||||
result.structuredContent === null
|
||||
)
|
||||
throw new Error("missing structured result");
|
||||
return z.record(z.string(), z.unknown()).parse(result.structuredContent);
|
||||
};
|
||||
|
||||
it("opens a headerless image when architecture and entry are supplied", async () => {
|
||||
const root = await createTestTempDirectory("rea-raw-mcp-");
|
||||
const path = join(root, "ecu.bin");
|
||||
await writeFile(path, Buffer.from("1eff2fe1", "hex"));
|
||||
const { client } = await connect();
|
||||
const opened = await client.callTool({
|
||||
name: "open_binary",
|
||||
arguments: {
|
||||
path,
|
||||
format: "raw-binary",
|
||||
architecture: "arm",
|
||||
entry_point: "0x08000000",
|
||||
},
|
||||
});
|
||||
expect(opened.isError).not.toBe(true);
|
||||
expect(structured(opened).result).toMatchObject({
|
||||
path,
|
||||
format: "raw-binary",
|
||||
kind: "executable",
|
||||
architecture: "arm",
|
||||
entry_point: "0x8000000",
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects an unaligned AArch64 entry before selecting or starting a provider", async () => {
|
||||
const root = await createTestTempDirectory("rea-raw-mcp-alignment-");
|
||||
const path = join(root, "image.bin");
|
||||
await writeFile(path, Buffer.from("c0035fd6", "hex"));
|
||||
const { client, session } = await connect({
|
||||
...createCacheProvider([]),
|
||||
resolveAnalysisProfile: () => {
|
||||
throw new Error("unaligned input must not select a provider");
|
||||
},
|
||||
createClient: () => {
|
||||
throw new Error("unaligned input must not launch a provider");
|
||||
},
|
||||
});
|
||||
const opened = await client.callTool({
|
||||
name: "open_binary",
|
||||
arguments: {
|
||||
path,
|
||||
format: "raw-binary",
|
||||
architecture: "arm64",
|
||||
entry_point: "0x8000001",
|
||||
},
|
||||
});
|
||||
expect(opened.isError).toBe(true);
|
||||
expect(JSON.stringify(opened.content)).toContain("must be 4-byte aligned");
|
||||
expect(session.activeTarget()).toBeUndefined();
|
||||
});
|
||||
|
||||
it("rejects raw-binary open requests that omit architecture", async () => {
|
||||
const root = await createTestTempDirectory("rea-raw-mcp-missing-");
|
||||
const path = join(root, "ecu.bin");
|
||||
await writeFile(path, Buffer.from("1eff2fe1", "hex"));
|
||||
const { client } = await connect();
|
||||
const opened = await client.callTool({
|
||||
name: "open_binary",
|
||||
arguments: { path, format: "raw-binary" },
|
||||
});
|
||||
expect(opened.isError).toBe(true);
|
||||
});
|
||||
|
||||
it("reuses a canonical raw entry and replaces the session when the entry changes", async () => {
|
||||
const root = await createTestTempDirectory("rea-raw-mcp-reopen-");
|
||||
const path = join(root, "ecu.bin");
|
||||
await writeFile(path, Buffer.from("1eff2fe1", "hex"));
|
||||
const fixture = createCacheProvider([]);
|
||||
const resolved: string[] = [];
|
||||
const created: string[] = [];
|
||||
const closed: string[] = [];
|
||||
const { client, session } = await connect({
|
||||
...fixture,
|
||||
resolveAnalysisProfile: (target) => {
|
||||
if (target.format !== "raw-binary")
|
||||
throw new Error("expected raw binary");
|
||||
resolved.push(target.entryPoint);
|
||||
return Promise.resolve(
|
||||
ok({
|
||||
profile: createAnalysisProfile(
|
||||
{ ...fixture.identity(), version: "1" },
|
||||
{
|
||||
entry_point: target.entryPoint,
|
||||
},
|
||||
),
|
||||
}),
|
||||
);
|
||||
},
|
||||
createClient: (target) => {
|
||||
if (target.format !== "raw-binary")
|
||||
throw new Error("expected raw binary");
|
||||
created.push(target.entryPoint);
|
||||
return {
|
||||
execute: (operation) => {
|
||||
if (operation !== "health" && operation !== "address_name")
|
||||
throw new Error(`unexpected fixture operation: ${operation}`);
|
||||
return Promise.resolve(observed(target.entryPoint));
|
||||
},
|
||||
close: () => {
|
||||
closed.push(target.entryPoint);
|
||||
return Promise.resolve(ok(null));
|
||||
},
|
||||
};
|
||||
},
|
||||
});
|
||||
const tools = (await client.listTools()).tools;
|
||||
const validateLifecycle = (
|
||||
name: "open_binary" | "binary_session",
|
||||
response: CallToolResult,
|
||||
) => {
|
||||
const tool = tools.find((candidate) => candidate.name === name);
|
||||
if (tool?.outputSchema === undefined)
|
||||
throw new Error(`missing ${name} output schema`);
|
||||
const schema = z.record(z.string(), z.unknown()).parse(tool.outputSchema);
|
||||
const validate = new Ajv2020({
|
||||
strict: false,
|
||||
validateFormats: false,
|
||||
}).compile(schema);
|
||||
expect(
|
||||
validate(response.structuredContent),
|
||||
JSON.stringify(validate.errors),
|
||||
).toBe(true);
|
||||
const parsed = toolContract(name).outputSchema.parse(
|
||||
response.structuredContent,
|
||||
);
|
||||
const target = z.record(z.string(), z.unknown()).parse(parsed.result);
|
||||
const { entry_point: _entry, ...missingEntry } = target;
|
||||
expect(validate({ ...structured(response), result: missingEntry })).toBe(
|
||||
false,
|
||||
);
|
||||
return target;
|
||||
};
|
||||
for (const entryPoint of ["0x08000000", "0x8000000", "0x09000000"]) {
|
||||
const opened = await client.callTool({
|
||||
name: "open_binary",
|
||||
arguments: {
|
||||
path,
|
||||
format: "raw-binary",
|
||||
architecture: "arm",
|
||||
entry_point: entryPoint,
|
||||
},
|
||||
});
|
||||
expect(opened.isError, JSON.stringify(opened)).not.toBe(true);
|
||||
const canonical = `0x${BigInt(entryPoint).toString(16)}`;
|
||||
expect(validateLifecycle("open_binary", opened).entry_point).toBe(
|
||||
canonical,
|
||||
);
|
||||
const status = await client.callTool({
|
||||
name: "binary_session",
|
||||
arguments: {},
|
||||
});
|
||||
expect(status.isError, JSON.stringify(status)).not.toBe(true);
|
||||
expect(validateLifecycle("binary_session", status).entry_point).toBe(
|
||||
canonical,
|
||||
);
|
||||
const result = await client.callTool({
|
||||
name: "address_name",
|
||||
arguments: { address: entryPoint },
|
||||
});
|
||||
expect(result.isError, JSON.stringify(result)).not.toBe(true);
|
||||
expect(structured(result).normalized_result).toBe(canonical);
|
||||
}
|
||||
expect(session.analysisProfile()?.parameters.entry_point).toBe("0x9000000");
|
||||
expect(resolved).toEqual(["0x8000000", "0x9000000"]);
|
||||
expect(created).toEqual(["0x8000000", "0x9000000"]);
|
||||
expect(closed).toEqual(["0x8000000"]);
|
||||
});
|
||||
@@ -8,9 +8,11 @@ import { fileURLToPath } from "node:url";
|
||||
import { afterEach, describe, expect, it, onTestFinished, vi } from "vitest";
|
||||
import pino from "pino";
|
||||
import type { Logger } from "pino";
|
||||
import type { ProgressUpdate } from "../../../../src/application/ProgressReporter.js";
|
||||
|
||||
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";
|
||||
@@ -121,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,
|
||||
@@ -146,7 +150,156 @@ afterEach(async () => {
|
||||
await Promise.all(clients.splice(0).map((client) => client.close()));
|
||||
});
|
||||
|
||||
it("reports unknown startup work and stops notifications when cancellation releases the process", async () => {
|
||||
vi.useFakeTimers({ toFake: ["setInterval", "clearInterval"] });
|
||||
const launcher = new FixtureLauncher("silent");
|
||||
const client = clientFor(launcher, { startupTimeoutMs: 30_000 });
|
||||
const controller = new AbortController();
|
||||
const updates: ProgressUpdate[] = [];
|
||||
const started = client.start(controller.signal, {
|
||||
report: async (update) => {
|
||||
updates.push(update);
|
||||
controller.abort();
|
||||
},
|
||||
});
|
||||
const child = await launcher.started;
|
||||
await vi.advanceTimersByTimeAsync(10_000);
|
||||
expect(await started).toMatchObject({
|
||||
ok: false,
|
||||
error: { kind: "cancelled" },
|
||||
});
|
||||
expect(updates).toEqual([
|
||||
expect.objectContaining({
|
||||
phase: "ghidra_startup",
|
||||
completed: 0,
|
||||
total: null,
|
||||
message: expect.stringContaining("Waiting for Ghidra startup"),
|
||||
}),
|
||||
]);
|
||||
await client.close();
|
||||
await expect(waitForChildExit(child, 5_000)).resolves.toBe(true);
|
||||
await expect(access(launcher.runtimeRoots[0] ?? "")).rejects.toMatchObject({
|
||||
code: "ENOENT",
|
||||
});
|
||||
await vi.advanceTimersByTimeAsync(30_000);
|
||||
expect(updates).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("keeps one shared startup despite a failed progress sink and stops reports after readiness", async () => {
|
||||
vi.useFakeTimers({ toFake: ["setInterval", "clearInterval"] });
|
||||
const launcher = new FixtureLauncher();
|
||||
let releaseLaunch: (() => void) | undefined;
|
||||
let markLaunchPending: (() => void) | undefined;
|
||||
const launchPending = new Promise<void>((resolve) => {
|
||||
markLaunchPending = resolve;
|
||||
});
|
||||
const launchGate = new Promise<void>((resolve) => {
|
||||
releaseLaunch = resolve;
|
||||
});
|
||||
const client = clientFor(
|
||||
{
|
||||
async launch(session) {
|
||||
markLaunchPending?.();
|
||||
await launchGate;
|
||||
return launcher.launch(session);
|
||||
},
|
||||
},
|
||||
{ startupTimeoutMs: 30_000 },
|
||||
);
|
||||
let reports = 0;
|
||||
const started = client.start(undefined, {
|
||||
report: async () => {
|
||||
reports += 1;
|
||||
throw new Error("notification unavailable");
|
||||
},
|
||||
});
|
||||
const concurrent = client.start();
|
||||
await launchPending;
|
||||
await vi.advanceTimersByTimeAsync(10_000);
|
||||
expect(reports).toBe(1);
|
||||
releaseLaunch?.();
|
||||
await expect(started).resolves.toMatchObject({ ok: true });
|
||||
await expect(concurrent).resolves.toMatchObject({ ok: true });
|
||||
expect(launcher.processes).toHaveLength(1);
|
||||
await vi.advanceTimersByTimeAsync(30_000);
|
||||
expect(reports).toBe(1);
|
||||
});
|
||||
|
||||
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"]],
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
import { rm } from "node:fs/promises";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { EnhancedTools } from "../../../../src/application/EnhancedTools.js";
|
||||
import { IdaSessionClient } from "../../../../src/ida/IdaSessionClient.js";
|
||||
import type { JsonValue } from "../../../../src/domain/jsonValue.js";
|
||||
import { createIdaTarget, RecordingIdaMcp } from "../../../fixtures/idaMcp.js";
|
||||
|
||||
const roots: string[] = [];
|
||||
afterEach(async () => {
|
||||
for (const root of roots.splice(0))
|
||||
await rm(root, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
const entry = { addr: "0x1000", name: "main", size: "0x20" };
|
||||
|
||||
/** Headless session where `main` resolves, its external callee 0x2000 is not a function, and `nosuch` is unknown. */
|
||||
const session = async () => {
|
||||
const { root, target } = await createIdaTarget();
|
||||
roots.push(root);
|
||||
const producer = new RecordingIdaMcp(target, "headless");
|
||||
producer.overrideCall = (name, args): JsonValue | undefined => {
|
||||
if (name !== "lookup_funcs") return undefined;
|
||||
const queries = args.queries;
|
||||
const query = Array.isArray(queries) ? String(queries[0]) : "";
|
||||
if (query === "main" || query === "0x1000")
|
||||
return [{ query, fn: entry, error: null }];
|
||||
return [
|
||||
{
|
||||
query,
|
||||
fn: null,
|
||||
error: query === "nosuch" ? "Not found" : "Not a function",
|
||||
},
|
||||
];
|
||||
};
|
||||
const client = new IdaSessionClient(
|
||||
{
|
||||
command: "fixture",
|
||||
args: [],
|
||||
env: {},
|
||||
mode: "headless",
|
||||
timeoutMs: 1000,
|
||||
workspaceRoot: root,
|
||||
},
|
||||
target,
|
||||
producer,
|
||||
);
|
||||
return { client, tools: new EnhancedTools(client) };
|
||||
};
|
||||
|
||||
describe("provider-derived selectors in IDA composed workflows", () => {
|
||||
it("records an external callee IDA cannot resolve as a producer fault in the call graph", async () => {
|
||||
const { client, tools } = await session();
|
||||
try {
|
||||
const result = await tools.execute("get_call_graph", { address: "main" });
|
||||
|
||||
if (!result.ok) throw result.error;
|
||||
expect(
|
||||
result.value,
|
||||
"the resolved root stays ok and only the derived node carries the producer fault",
|
||||
).toMatchObject({
|
||||
"0": [{ address: "0x1000", status: "ok" }],
|
||||
"1": [
|
||||
{
|
||||
address: "0x2000",
|
||||
status: "error",
|
||||
error: { code: "unreadable_output" },
|
||||
},
|
||||
],
|
||||
});
|
||||
} finally {
|
||||
expect((await client.close()).ok).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it("records the same node as a producer fault in the call path", async () => {
|
||||
const { client, tools } = await session();
|
||||
try {
|
||||
const result = await tools.execute("trace_call_path", { start: "main" });
|
||||
|
||||
if (!result.ok) throw result.error;
|
||||
expect(
|
||||
result.value,
|
||||
"the failure belongs to the derived address and is not blamed on the caller",
|
||||
).toMatchObject({
|
||||
failures: [{ address: "0x2000", error: { code: "unreadable_output" } }],
|
||||
});
|
||||
} finally {
|
||||
expect((await client.close()).ok).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps the caller's own unknown selector an invalid request in each workflow", async () => {
|
||||
const { client, tools } = await session();
|
||||
try {
|
||||
const graph = await tools.execute("get_call_graph", {
|
||||
address: "nosuch",
|
||||
});
|
||||
const trace = await tools.execute("trace_call_path", { start: "nosuch" });
|
||||
const batch = await tools.execute("batch_decompile", {
|
||||
addresses: ["nosuch"],
|
||||
});
|
||||
|
||||
if (graph.ok || trace.ok) throw new Error("expected invalid requests");
|
||||
expect(graph.error._tag, "graph start is caller input").toBe(
|
||||
"AnalysisInputError",
|
||||
);
|
||||
expect(trace.error._tag, "trace start is caller input").toBe(
|
||||
"AnalysisInputError",
|
||||
);
|
||||
if (!batch.ok) throw batch.error;
|
||||
expect(
|
||||
batch.value,
|
||||
"the unresolved batch item and its fallback retry are both caller input",
|
||||
).toMatchObject({
|
||||
items: [
|
||||
{
|
||||
address: "nosuch",
|
||||
procedure: {
|
||||
status: "unknown",
|
||||
error: { code: "invalid_request" },
|
||||
},
|
||||
status: "error",
|
||||
error: { code: "invalid_request" },
|
||||
},
|
||||
],
|
||||
});
|
||||
} finally {
|
||||
expect((await client.close()).ok).toBe(true);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1114,3 +1114,41 @@ describe("no replacement start", () => {
|
||||
expect(session.status()).toMatchObject({ open: false });
|
||||
});
|
||||
});
|
||||
|
||||
describe("selector origin forwarding", () => {
|
||||
it("forwards the per-call selector origin to the provider client on both execution paths", async () => {
|
||||
const [first] = await createBinarySessionTargets();
|
||||
const seen: unknown[] = [];
|
||||
const session = createTestBinarySession(() => ({
|
||||
execute: (_operation, _parameters, options) => {
|
||||
seen.push(options?.selectorOrigin);
|
||||
return Promise.resolve(ok(null));
|
||||
},
|
||||
close: () => Promise.resolve(resultOk(null)),
|
||||
}));
|
||||
expect((await session.open(first)).ok, "the target opens").toBe(true);
|
||||
seen.length = 0;
|
||||
|
||||
await session.execute(
|
||||
"address_name",
|
||||
{ address: "0x1000" },
|
||||
{ selectorOrigin: "provider" },
|
||||
);
|
||||
await session.withAdmittedAnalysis(
|
||||
"binary_overview",
|
||||
undefined,
|
||||
(analysis) =>
|
||||
analysis.execute(
|
||||
"address_name",
|
||||
{ address: "0x2000" },
|
||||
{ selectorOrigin: "provider" },
|
||||
),
|
||||
);
|
||||
await session.execute("address_name", { address: "0x3000" });
|
||||
|
||||
expect(
|
||||
seen,
|
||||
"direct and admitted calls forward the origin; an unmarked call carries none",
|
||||
).toEqual(["provider", "provider", undefined]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,11 +1,16 @@
|
||||
import com.atxx.jhmcp.*;
|
||||
import com.android.tools.smali.smali.Smali;
|
||||
import com.android.tools.smali.smali.SmaliOptions;
|
||||
import com.google.gson.*;
|
||||
import io.modelcontextprotocol.kotlin.sdk.types.CallToolResult;
|
||||
import io.modelcontextprotocol.kotlin.sdk.types.TextContent;
|
||||
import jadx.api.*;
|
||||
import jadx.core.dex.nodes.*;
|
||||
import java.lang.reflect.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import java.util.zip.*;
|
||||
import kotlin.coroutines.EmptyCoroutineContext;
|
||||
import kotlinx.coroutines.BuildersKt;
|
||||
|
||||
@@ -37,6 +42,86 @@ public class ReaJadxMetadataRegression {
|
||||
return value;
|
||||
}
|
||||
|
||||
private static Path initializerFixture(String sources, String output) throws Exception {
|
||||
Path directory = Path.of(output);
|
||||
SmaliOptions options = new SmaliOptions();
|
||||
options.apiLevel = 28;
|
||||
options.jobs = 1;
|
||||
options.outputDexFile = directory.resolve("initializers.dex").toString();
|
||||
require(Smali.assemble(options, List.of(
|
||||
Path.of(sources, "InitializationPolicy.smali").toString(),
|
||||
Path.of(sources, "MixedInitialization.smali").toString())), "Initializer fixture assembly failed");
|
||||
Path apk = directory.resolve("initializers.apk");
|
||||
try (ZipOutputStream zip = new ZipOutputStream(Files.newOutputStream(apk))) {
|
||||
zip.putNextEntry(new ZipEntry("classes.dex"));
|
||||
Files.copy(Path.of(options.outputDexFile), zip);
|
||||
zip.closeEntry();
|
||||
}
|
||||
return apk;
|
||||
}
|
||||
|
||||
private static JsonObject methodArguments(String className, String methodName) {
|
||||
JsonObject value = arguments(className);
|
||||
value.addProperty("method_name", methodName);
|
||||
value.addProperty("overload_index", 0);
|
||||
return value;
|
||||
}
|
||||
|
||||
private static void verifyInitializers(SessionHolder holder, SessionConfig config,
|
||||
Constructor<?> constructor, Method handle, Path apk) throws Exception {
|
||||
BuildersKt.runBlocking(EmptyCoroutineContext.INSTANCE,
|
||||
(scope, continuation) -> holder.unload(continuation));
|
||||
BuildersKt.runBlocking(EmptyCoroutineContext.INSTANCE,
|
||||
(scope, continuation) -> holder.load(apk.toString(), config, continuation));
|
||||
Object bridge = constructor.newInstance(holder);
|
||||
String[] classNames = { "fixture.InitializationPolicy", "fixture.MixedInitialization" };
|
||||
String[][] witnesses = {
|
||||
{ "declared-policy", "->singletonList", "->POLICY:Ljava/util/List;" },
|
||||
{ "field-value", "->LABEL:Ljava/lang/String;", "->touch()V" }
|
||||
};
|
||||
for (int index = 0; index < classNames.length; index++) {
|
||||
JsonObject summary = call(handle, bridge, "get_class_summary", arguments(classNames[index]));
|
||||
JsonObject input = methodArguments(classNames[index], "<clinit>");
|
||||
JsonObject body = call(handle, bridge, "get_method_body", input);
|
||||
String text = body.get("body").getAsString();
|
||||
for (String witness : witnesses[index]) require(text.contains(witness), "Missing initializer instruction: " + witness);
|
||||
require(body.get("mode").getAsString().equals("smali"), "Static initializer must preserve DEX instructions");
|
||||
require(body.get("fell_back").getAsBoolean(), "Disassembly fallback was not reported");
|
||||
require(body.getAsJsonArray("markers").contains(new JsonPrimitive("static_initializer_disassembly")),
|
||||
"Static initializer representation reason was not reported");
|
||||
require(text.contains(".method static constructor <clinit>()V") && text.contains(".end method"),
|
||||
"Initializer method boundaries missing");
|
||||
require(body.get("overload_index").getAsInt() == 0 && body.get("overload_count").getAsInt() == 1,
|
||||
"Initializer identity changed");
|
||||
require(body.equals(call(handle, bridge, "get_method_body", input)), "Repeated initializer body changed");
|
||||
require(summary.equals(call(handle, bridge, "get_class_summary", arguments(classNames[index]))),
|
||||
"Frozen initializer metadata changed after source generation");
|
||||
}
|
||||
for (String name : List.of("missing", "originalNative")) {
|
||||
JsonObject body = call(handle, bridge, "get_method_body", methodArguments(classNames[0], name));
|
||||
String text = body.get("body").getAsString();
|
||||
require(body.get("mode").getAsString().equals("java") && !text.contains("{") && !text.contains(".method"),
|
||||
"Executable body was fabricated for " + name + ": " + text);
|
||||
}
|
||||
JsonObject ordinary = call(handle, bridge, "get_method_body", methodArguments(classNames[1], "touch"));
|
||||
require(ordinary.get("mode").getAsString().equals("java") && ordinary.get("body").getAsString().contains("COUNT"),
|
||||
"Ordinary executable method no longer produces Java");
|
||||
|
||||
SessionConfig bounded = new SessionConfig(96, 0, 90000L, 1, List.of(), List.of(), 64, ResourceMode.FULL);
|
||||
BuildersKt.runBlocking(EmptyCoroutineContext.INSTANCE,
|
||||
(scope, continuation) -> holder.unload(continuation));
|
||||
BuildersKt.runBlocking(EmptyCoroutineContext.INSTANCE,
|
||||
(scope, continuation) -> holder.load(apk.toString(), bounded, continuation));
|
||||
JsonObject partial = call(handle, constructor.newInstance(holder), "get_method_body",
|
||||
methodArguments(classNames[0], "<clinit>"));
|
||||
require(partial.get("mode").getAsString().equals("smali")
|
||||
&& partial.get("body").getAsString().contains("[truncated: exceeds 96 bytes, total "),
|
||||
"Static initializer ignored the source byte limit or omitted its truncation marker");
|
||||
String prefix = partial.get("body").getAsString().split("\n\n\\.\\.\\. \\[truncated:", 2)[0];
|
||||
require(prefix.getBytes(StandardCharsets.UTF_8).length <= 96, "Initializer text exceeded its byte limit");
|
||||
System.out.println("INITIALIZER_REGRESSION_PASS folded=2 bounded=true");
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
SessionConfig config = new SessionConfig(1048576, 0, 90000L, 1, List.of(), List.of(), 64, ResourceMode.FULL);
|
||||
SessionHolder holder = new SessionHolder(config);
|
||||
@@ -89,6 +174,7 @@ public class ReaJadxMetadataRegression {
|
||||
"Frozen summary changed after code generation");
|
||||
require(apiSummary.equals(call(handle, bridge, "get_class_summary", apiArgs)), "Unrelated frozen summary changed");
|
||||
System.out.println("METADATA_REGRESSION_PASS classes=" + states.size() + " overloads=" + signatures.size());
|
||||
verifyInitializers(holder, config, constructor, handle, initializerFixture(args[1], args[2]));
|
||||
} finally {
|
||||
BuildersKt.runBlocking(EmptyCoroutineContext.INSTANCE,
|
||||
(scope, continuation) -> holder.unload(continuation));
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
.class public abstract Lfixture/InitializationPolicy;
|
||||
.super Ljava/lang/Object;
|
||||
|
||||
.field public static final POLICY:Ljava/util/List;
|
||||
|
||||
.method static constructor <clinit>()V
|
||||
.registers 1
|
||||
const-string v0, "declared-policy"
|
||||
invoke-static {v0}, Ljava/util/Collections;->singletonList(Ljava/lang/Object;)Ljava/util/List;
|
||||
move-result-object v0
|
||||
sput-object v0, Lfixture/InitializationPolicy;->POLICY:Ljava/util/List;
|
||||
return-void
|
||||
.end method
|
||||
|
||||
.method public constructor <init>()V
|
||||
.registers 1
|
||||
invoke-direct {p0}, Ljava/lang/Object;-><init>()V
|
||||
return-void
|
||||
.end method
|
||||
|
||||
.method public abstract missing()V
|
||||
.end method
|
||||
|
||||
.method public native originalNative()V
|
||||
.end method
|
||||
@@ -0,0 +1,21 @@
|
||||
.class public Lfixture/MixedInitialization;
|
||||
.super Ljava/lang/Object;
|
||||
|
||||
.field public static final LABEL:Ljava/lang/String;
|
||||
.field public static COUNT:I
|
||||
|
||||
.method static constructor <clinit>()V
|
||||
.registers 1
|
||||
const-string v0, "field-value"
|
||||
sput-object v0, Lfixture/MixedInitialization;->LABEL:Ljava/lang/String;
|
||||
invoke-static {}, Lfixture/MixedInitialization;->touch()V
|
||||
return-void
|
||||
.end method
|
||||
|
||||
.method public static touch()V
|
||||
.registers 1
|
||||
sget v0, Lfixture/MixedInitialization;->COUNT:I
|
||||
add-int/lit8 v0, v0, 0x1
|
||||
sput v0, Lfixture/MixedInitialization;->COUNT:I
|
||||
return-void
|
||||
.end method
|
||||
+17
-6
@@ -45,11 +45,21 @@ def probe(path, socket_path, mode):
|
||||
assert time.monotonic() < deadline, failures
|
||||
time.sleep(0.005)
|
||||
|
||||
def connect():
|
||||
client = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||
client.settimeout(2)
|
||||
client.connect(socket_path)
|
||||
return client, client.makefile("rwb")
|
||||
def connect(wait_until_listening=False):
|
||||
deadline = time.monotonic() + 2 if wait_until_listening else None
|
||||
while True:
|
||||
client = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||
client.settimeout(2)
|
||||
try:
|
||||
client.connect(socket_path)
|
||||
except OSError as error:
|
||||
client.close()
|
||||
if (not isinstance(error, ConnectionRefusedError)
|
||||
or deadline is None or time.monotonic() >= deadline):
|
||||
raise
|
||||
time.sleep(0.005)
|
||||
else:
|
||||
return client, client.makefile("rwb")
|
||||
|
||||
def send(file, method, token="owned-token", params=None):
|
||||
file.write((json.dumps({"id": 1, "method": method, "token": token, "params": params or {}}) + "\n").encode())
|
||||
@@ -63,7 +73,8 @@ def probe(path, socket_path, mode):
|
||||
if "event" not in value:
|
||||
return value
|
||||
|
||||
client, file = connect()
|
||||
# bind() creates the socket path before listen() makes it connectable.
|
||||
client, file = connect(wait_until_listening=True)
|
||||
send(file, "health", "foreign-token" if mode == "unauthorized" else "owned-token")
|
||||
if mode == "lost-reply":
|
||||
assert entered.wait(2)
|
||||
|
||||
Reference in New Issue
Block a user