chore: merge captured main into iNES container support
This commit is contained in:
@@ -1,4 +1,11 @@
|
||||
import { access, chmod, readFile, stat } from "node:fs/promises";
|
||||
import {
|
||||
access,
|
||||
chmod,
|
||||
mkdir,
|
||||
readFile,
|
||||
stat,
|
||||
writeFile,
|
||||
} from "node:fs/promises";
|
||||
import { join, posix, win32 } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
@@ -480,6 +487,64 @@ describe("Ghidra Windows launcher", () => {
|
||||
).toThrow(/metacharacters/u);
|
||||
});
|
||||
|
||||
it.skipIf(process.platform !== "win32").each([
|
||||
{
|
||||
properties:
|
||||
"application.version=12.1.4\napplication.release.name=PUBLIC\n",
|
||||
release: "ghidra_12.1.4_PUBLIC",
|
||||
},
|
||||
{ properties: undefined, release: "renamed-install" },
|
||||
{ properties: "application.version=12.1.4\n", release: "renamed-install" },
|
||||
])(
|
||||
"prepares the release directory through the Windows runtime ($release)",
|
||||
async ({ properties, release }) => {
|
||||
const parent = await createTestTempDirectory("rea-launch-config-");
|
||||
const installRoot = join(parent, "renamed-install");
|
||||
if (properties !== undefined) {
|
||||
await mkdir(join(installRoot, "Ghidra"), { recursive: true });
|
||||
await writeFile(
|
||||
join(installRoot, "Ghidra", "application.properties"),
|
||||
properties,
|
||||
);
|
||||
}
|
||||
const runtime = await createGhidraTestRuntime(parent);
|
||||
runtimes.push(runtime);
|
||||
const spawnProcess = vi.fn(async () => {
|
||||
throw new Error("fixture stops before process creation");
|
||||
});
|
||||
const launcher = new GhidraHeadlessLauncher({
|
||||
environment: process.env,
|
||||
platform: "win32",
|
||||
analyzeHeadlessPath: join(
|
||||
installRoot,
|
||||
"support",
|
||||
"analyzeHeadless.bat",
|
||||
),
|
||||
javaHome: "C:\\Java\\jdk-21",
|
||||
bridgeScriptPath: join(parent, "ReaGhidraBridge.java"),
|
||||
spawnProcess,
|
||||
});
|
||||
const launched = await launcher.launch({
|
||||
runtimeRoot: runtime.path,
|
||||
transport: "unix-socket",
|
||||
endpointPath: join(runtime.path, "bridge.sock"),
|
||||
token: "fixture-token",
|
||||
runId: "d6fcbb66-e829-4ff6-a535-0035aec63139",
|
||||
targetPath: join(parent, "fixture.exe"),
|
||||
targetSha256: "b".repeat(64),
|
||||
providerVersion: "12.1.4",
|
||||
profileDigest: "a".repeat(64),
|
||||
});
|
||||
expect(launched.ok).toBe(false);
|
||||
expect(spawnProcess).toHaveBeenCalledOnce();
|
||||
expect(
|
||||
(
|
||||
await stat(join(runtime.path, "config", "ghidra", release))
|
||||
).isDirectory(),
|
||||
).toBe(true);
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform !== "win32")(
|
||||
"keeps authority in a private descriptor and isolates Ghidra state through the batch launcher",
|
||||
async () => {
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
import { rm } from "node:fs/promises";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { inspectAddressContext } from "../../../../src/application/AnalysisContextQueries.js";
|
||||
import { EnhancedTools } from "../../../../src/application/EnhancedTools.js";
|
||||
import { IdaSessionClient } from "../../../../src/ida/IdaSessionClient.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 session = async (cappedReferences = false) => {
|
||||
const { root, target } = await createIdaTarget("arm64");
|
||||
roots.push(root);
|
||||
const producer = new RecordingIdaMcp(target, "headless");
|
||||
if (cappedReferences) {
|
||||
const inner = producer.overrideCall;
|
||||
producer.overrideCall = (name, args) =>
|
||||
name === "xrefs_to"
|
||||
? [
|
||||
{
|
||||
xrefs: [
|
||||
{
|
||||
addr: "0x1004",
|
||||
type: "code",
|
||||
fn: { addr: "0x1000", name: "main", size: "0x20" },
|
||||
},
|
||||
],
|
||||
more: true,
|
||||
},
|
||||
]
|
||||
: inner?.(name, args);
|
||||
}
|
||||
const client = new IdaSessionClient(
|
||||
{
|
||||
command: "fixture",
|
||||
args: [],
|
||||
env: {},
|
||||
mode: "headless",
|
||||
timeoutMs: 1000,
|
||||
workspaceRoot: root,
|
||||
},
|
||||
target,
|
||||
producer,
|
||||
);
|
||||
return { client, target };
|
||||
};
|
||||
|
||||
const MAIN = {
|
||||
found: true,
|
||||
procedure: { address: "0x1000", name: "main" },
|
||||
};
|
||||
|
||||
describe("trace_feature on headless IDA", () => {
|
||||
it("attributes a reference to its containing procedure", async () => {
|
||||
const { client } = await session();
|
||||
try {
|
||||
const result = await new EnhancedTools(client).execute("trace_feature", {
|
||||
query: "a.b",
|
||||
});
|
||||
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value).toMatchObject({
|
||||
matches: [{ type: "string", address: "0x3000" }],
|
||||
references: [
|
||||
{
|
||||
target_address: "0x3000",
|
||||
source_address: "0x1004",
|
||||
containing_procedure: MAIN,
|
||||
},
|
||||
],
|
||||
truncated: false,
|
||||
residual_unknowns: [],
|
||||
});
|
||||
} finally {
|
||||
expect((await client.close()).ok).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps an upstream reference cap visible once containment makes the trace run", async () => {
|
||||
const { client } = await session(true);
|
||||
try {
|
||||
const result = await new EnhancedTools(client).execute("trace_feature", {
|
||||
query: "a.b",
|
||||
});
|
||||
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value).toMatchObject({
|
||||
references: [{ source_address: "0x1004", containing_procedure: MAIN }],
|
||||
truncated: true,
|
||||
residual_unknowns: [
|
||||
"References to 0x3000 were truncated by the provider; additional references may exist.",
|
||||
],
|
||||
});
|
||||
} finally {
|
||||
expect((await client.close()).ok).toBe(true);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("inspect_address_context on headless IDA", () => {
|
||||
it("resolves the admitted program as the document and reports the containing procedure", async () => {
|
||||
const { client, target } = await session();
|
||||
try {
|
||||
const result = await inspectAddressContext(client, {
|
||||
address: "0x1004",
|
||||
});
|
||||
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value).toMatchObject({
|
||||
address: "0x1004",
|
||||
document: target.path,
|
||||
procedure: { state: "available", value: MAIN },
|
||||
name: { state: "unavailable" },
|
||||
comment: { state: "unavailable" },
|
||||
inline_comment: { state: "unavailable" },
|
||||
bookmarks: { state: "unavailable" },
|
||||
});
|
||||
} finally {
|
||||
expect((await client.close()).ok).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it("answers the same way for an explicit admitted document", async () => {
|
||||
const { client, target } = await session();
|
||||
try {
|
||||
const implicit = await inspectAddressContext(client, {
|
||||
address: "0x1004",
|
||||
});
|
||||
const explicit = await inspectAddressContext(client, {
|
||||
address: "0x1004",
|
||||
document: target.path,
|
||||
});
|
||||
|
||||
if (!implicit.ok) throw implicit.error;
|
||||
if (!explicit.ok) throw explicit.error;
|
||||
expect(explicit.value).toEqual(implicit.value);
|
||||
} finally {
|
||||
expect((await client.close()).ok).toBe(true);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,114 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { mkdir, readdir, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { describe, expect, it, onTestFinished } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import { elf } from "../../../../src/domain/binaryTarget.fixture.js";
|
||||
import type { BinaryTarget } from "../../../../src/domain/binaryTargetTypes.js";
|
||||
import { createIdaMcpConnection } from "../../../../src/ida/IdaMcpConnection.js";
|
||||
import { IdaSessionClient } from "../../../../src/ida/IdaSessionClient.js";
|
||||
|
||||
/**
|
||||
* A headless IDA supervisor over real stdio that answers the session
|
||||
* lifecycle, but rejects the first inventory after a close so cleanup fails
|
||||
* once and must be retried through the retained connection.
|
||||
*/
|
||||
const FLAKY_INVENTORY_SUPERVISOR = `import { createInterface } from "node:readline";
|
||||
const tools = ["idb_open", "idb_list", "idb_close", "server_health", "list_funcs",
|
||||
"lookup_funcs", "find_regex", "decompile", "disasm", "callees", "xrefs_to"];
|
||||
let session;
|
||||
let inputPath;
|
||||
let closed = false;
|
||||
let inventoryFailed = false;
|
||||
const send = (message) =>
|
||||
process.stdout.write(JSON.stringify({ jsonrpc: "2.0", ...message }) + "\\n");
|
||||
const result = (value) => ({
|
||||
content: [{ type: "text", text: JSON.stringify(value) }],
|
||||
structuredContent: value,
|
||||
});
|
||||
const call = ({ name, arguments: args }) => {
|
||||
if (name === "idb_open") {
|
||||
session = args.preferred_session_id;
|
||||
inputPath = args.input_path;
|
||||
return result({ success: true, session: { session_id: session, input_path: inputPath } });
|
||||
}
|
||||
if (name === "server_health")
|
||||
return result({ status: "ok", input_path: inputPath, idb_path: inputPath + ".i64",
|
||||
module: "target.elf", imagebase: "0x1000", auto_analysis_ready: true });
|
||||
if (name === "idb_close") {
|
||||
closed = true;
|
||||
return result({ success: true, session_id: session, saved: null, owned: true, backend: "worker" });
|
||||
}
|
||||
if (name === "idb_list") {
|
||||
if (closed && !inventoryFailed) {
|
||||
inventoryFailed = true;
|
||||
return { isError: true, content: [{ type: "text", text: "inventory unavailable" }] };
|
||||
}
|
||||
return result({ sessions: closed ? [] : [{ session_id: session, input_path: inputPath,
|
||||
owned: true, backend: "worker", is_active: true }] });
|
||||
}
|
||||
return { isError: true, content: [{ type: "text", text: "unsupported " + name }] };
|
||||
};
|
||||
for await (const line of createInterface({ input: process.stdin })) {
|
||||
const request = JSON.parse(line);
|
||||
if (request.method === "initialize")
|
||||
send({ id: request.id, result: {
|
||||
protocolVersion: request.params.protocolVersion,
|
||||
capabilities: { tools: {} },
|
||||
serverInfo: { name: "flaky-inventory-ida-fixture", version: "1" },
|
||||
} });
|
||||
else if (request.method === "tools/list")
|
||||
send({ id: request.id, result: {
|
||||
tools: tools.map((name) => ({ name, inputSchema: { type: "object" } })),
|
||||
} });
|
||||
else if (request.method === "tools/call")
|
||||
send({ id: request.id, result: call(request.params) });
|
||||
}
|
||||
`;
|
||||
|
||||
describe("retained headless IDA connection in a long-lived host", () => {
|
||||
it("retries cleanup through the detached stdio connection", async () => {
|
||||
const root = await createTestTempDirectory("rea-ida-retry-");
|
||||
const supervisor = join(root, "supervisor.mjs");
|
||||
await writeFile(supervisor, FLAKY_INVENTORY_SUPERVISOR);
|
||||
const workspaceRoot = join(root, "workspaces");
|
||||
await mkdir(workspaceRoot);
|
||||
const bytes = elf(2, 1, 62);
|
||||
const targetPath = join(root, "target.elf");
|
||||
await writeFile(targetPath, bytes);
|
||||
const target: BinaryTarget = {
|
||||
path: targetPath,
|
||||
sha256: createHash("sha256").update(bytes).digest("hex"),
|
||||
kind: "executable",
|
||||
format: "elf",
|
||||
architecture: "x86_64",
|
||||
availableArchitectures: ["x86_64"],
|
||||
};
|
||||
const config = {
|
||||
command: process.execPath,
|
||||
args: [supervisor],
|
||||
env: {},
|
||||
mode: "headless" as const,
|
||||
timeoutMs: 5000,
|
||||
workspaceRoot,
|
||||
};
|
||||
const connection = createIdaMcpConnection(config, process.env);
|
||||
// Close the supervisor even when an assertion fails before cleanup does.
|
||||
onTestFinished(() => connection.close().catch(() => undefined));
|
||||
const client = new IdaSessionClient(config, target, connection);
|
||||
|
||||
expect((await client.execute("health", {})).ok).toBe(true);
|
||||
const failed = await client.close();
|
||||
expect(failed.ok).toBe(false);
|
||||
if (!failed.ok) expect(failed.error.cleanupIncomplete).toBe(true);
|
||||
expect(await readdir(workspaceRoot)).toHaveLength(1);
|
||||
|
||||
// The connection was detached when cleanup failed; it must still serve
|
||||
// the retry that confirms release and removes the private workspace.
|
||||
expect((await client.close()).ok).toBe(true);
|
||||
expect(await readdir(workspaceRoot)).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,212 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
assertFeatureTrace,
|
||||
findMappedNonFunction,
|
||||
} from "../../../../scripts/lib/ida-feature-trace.mjs";
|
||||
|
||||
const procedure = { address: "0x1000", name: "main" };
|
||||
|
||||
const containing = (found: boolean) =>
|
||||
found
|
||||
? {
|
||||
query_address: "0x1004",
|
||||
found: true,
|
||||
procedure: { address: "0x1000", name: "main" },
|
||||
}
|
||||
: {
|
||||
query_address: "0x3010",
|
||||
found: false,
|
||||
procedure: null,
|
||||
reason: "not_in_procedure",
|
||||
};
|
||||
|
||||
const trace = (
|
||||
matches: readonly { type: string; address: string }[],
|
||||
references: readonly {
|
||||
target_address: string;
|
||||
containing_procedure: unknown;
|
||||
}[],
|
||||
) => ({
|
||||
query: "main",
|
||||
search_mode: "literal",
|
||||
matches,
|
||||
references,
|
||||
truncated: false,
|
||||
residual_unknowns: [],
|
||||
});
|
||||
|
||||
const SELECTED = { type: "procedure", address: "0x1000" };
|
||||
const SUBSTRING = { type: "procedure", address: "0x2000" };
|
||||
const STRING = { type: "string", address: "0x3000" };
|
||||
|
||||
describe("the real IDA lane's feature trace assertions", () => {
|
||||
it("accepts references to every matched address, whoever contains the source", () => {
|
||||
expect(() =>
|
||||
assertFeatureTrace(
|
||||
trace(
|
||||
[SELECTED, SUBSTRING, STRING],
|
||||
[
|
||||
{
|
||||
target_address: "0x1000",
|
||||
containing_procedure: containing(true),
|
||||
},
|
||||
// A substring match such as main_helper, referenced from code.
|
||||
{
|
||||
target_address: "0x2000",
|
||||
containing_procedure: containing(true),
|
||||
},
|
||||
// A string containing the query, referenced from data outside functions.
|
||||
{
|
||||
target_address: "0x3000",
|
||||
containing_procedure: containing(false),
|
||||
},
|
||||
],
|
||||
),
|
||||
procedure,
|
||||
),
|
||||
).not.toThrow();
|
||||
});
|
||||
|
||||
it("accepts a reference to the selected procedure from data outside functions", () => {
|
||||
expect(() =>
|
||||
assertFeatureTrace(
|
||||
trace(
|
||||
[SELECTED],
|
||||
[
|
||||
{
|
||||
target_address: "0x1000",
|
||||
containing_procedure: containing(false),
|
||||
},
|
||||
],
|
||||
),
|
||||
procedure,
|
||||
),
|
||||
).not.toThrow();
|
||||
});
|
||||
|
||||
it("rejects a reference whose target is not one of the matches", () => {
|
||||
expect(() =>
|
||||
assertFeatureTrace(
|
||||
trace(
|
||||
[SELECTED],
|
||||
[
|
||||
{
|
||||
target_address: "0x9999",
|
||||
containing_procedure: containing(true),
|
||||
},
|
||||
],
|
||||
),
|
||||
procedure,
|
||||
),
|
||||
).toThrow();
|
||||
});
|
||||
|
||||
it("rejects a trace without the selected procedure's match", () => {
|
||||
expect(() => assertFeatureTrace(trace([STRING], []), procedure)).toThrow();
|
||||
});
|
||||
|
||||
it("rejects a containment answer that is neither found nor a known reason", () => {
|
||||
expect(() =>
|
||||
assertFeatureTrace(
|
||||
trace(
|
||||
[SELECTED],
|
||||
[
|
||||
{
|
||||
target_address: "0x1000",
|
||||
containing_procedure: {
|
||||
query_address: "0x1004",
|
||||
found: false,
|
||||
procedure: null,
|
||||
reason: "unknown",
|
||||
},
|
||||
},
|
||||
],
|
||||
),
|
||||
procedure,
|
||||
),
|
||||
).toThrow();
|
||||
});
|
||||
|
||||
it("rejects a trace that does not say whether it was truncated", () => {
|
||||
expect(() =>
|
||||
assertFeatureTrace(
|
||||
{ ...trace([SELECTED], []), truncated: undefined },
|
||||
procedure,
|
||||
),
|
||||
).toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe("the real IDA lane's mapped non-function probe", () => {
|
||||
const inFunction = {
|
||||
query_address: "0x1100",
|
||||
found: true,
|
||||
procedure: { address: "0x1000", name: "main" },
|
||||
};
|
||||
const data = {
|
||||
query_address: "0x3000",
|
||||
found: false,
|
||||
procedure: null,
|
||||
reason: "not_in_procedure",
|
||||
};
|
||||
const resolver =
|
||||
(answers: Readonly<Record<string, unknown>>, asked: string[] = []) =>
|
||||
async (address: string) => {
|
||||
asked.push(address);
|
||||
return answers[address];
|
||||
};
|
||||
|
||||
it("skips a string inside a function chunk and uses the next one", async () => {
|
||||
const asked: string[] = [];
|
||||
|
||||
await expect(
|
||||
findMappedNonFunction(
|
||||
[{ address: "0x1100" }, { address: "0x3000" }],
|
||||
resolver({ "0x1100": inFunction, "0x3000": data }, asked),
|
||||
),
|
||||
).resolves.toBe("0x3000");
|
||||
expect(asked, "strings are tried in order until one qualifies").toEqual([
|
||||
"0x1100",
|
||||
"0x3000",
|
||||
]);
|
||||
});
|
||||
|
||||
it("stops at the first string that qualifies", async () => {
|
||||
const asked: string[] = [];
|
||||
|
||||
await expect(
|
||||
findMappedNonFunction(
|
||||
[{ address: "0x3000" }, { address: "0x3100" }],
|
||||
resolver({ "0x3000": data, "0x3100": data }, asked),
|
||||
),
|
||||
).resolves.toBe("0x3000");
|
||||
expect(asked).toEqual(["0x3000"]);
|
||||
});
|
||||
|
||||
it("reports no qualifying string when every string is inside a function", async () => {
|
||||
await expect(
|
||||
findMappedNonFunction(
|
||||
[{ address: "0x1100" }, { address: "0x1200" }],
|
||||
resolver({ "0x1100": inFunction, "0x1200": inFunction }),
|
||||
),
|
||||
).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it("reports no qualifying string when the target has no strings", async () => {
|
||||
await expect(
|
||||
findMappedNonFunction([], resolver({})),
|
||||
).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it("rejects a listed string that resolves as unmapped, since IDA cannot list an unmapped address", async () => {
|
||||
await expect(
|
||||
findMappedNonFunction(
|
||||
[{ address: "0x4000" }, { address: "0x3000" }],
|
||||
resolver({
|
||||
"0x4000": { ...data, reason: "outside_segments" },
|
||||
"0x3000": data,
|
||||
}),
|
||||
),
|
||||
).rejects.toThrow();
|
||||
});
|
||||
});
|
||||
@@ -134,7 +134,7 @@ it("ignores unavailable members of a nested ASAR but refuses them as active entr
|
||||
const source = join(root, "bundle");
|
||||
await mkdir(source);
|
||||
const archive = join(source, "app.asar");
|
||||
await createPackageWithOptions(contents, archive, { unpack: "**/*.node" });
|
||||
await createPackageWithOptions(contents, archive, { unpack: "*.node" });
|
||||
await rm(join(`${archive}.unpacked`, "native", "addon.node"));
|
||||
|
||||
const nestedOutput = join(root, "nested-output");
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { readFile, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { describe, expect, it, onTestFinished } from "vitest";
|
||||
|
||||
import { MachOSliceArtifactReader } from "../../../../src/artifacts/MachOSliceArtifactReader.js";
|
||||
import { XcrunCommandRunner } from "../../../../src/native/CommandRunner.js";
|
||||
import { DarwinProcessOwnershipInspectionError } from "../../../../src/process/DarwinProcessRunTokenReader.js";
|
||||
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
|
||||
|
||||
/**
|
||||
* Read a 32-bit FAT table directly. The host's /bin/ls changes between macOS
|
||||
@@ -42,6 +44,56 @@ describe("Mach-O slice reader with system lipo", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it.skipIf(process.platform !== "darwin")(
|
||||
"keeps FAT slice records separate from the echoed source pathname",
|
||||
async () => {
|
||||
const directory = await createTestTempDirectory("rea-lipo-fat-path-");
|
||||
const path = join(
|
||||
directory,
|
||||
"source\narchitecture forged\n offset 123\n size 32",
|
||||
);
|
||||
const bytes = Buffer.alloc(8224);
|
||||
bytes.writeUInt32BE(0xca_fe_ba_be, 0);
|
||||
bytes.writeUInt32BE(2, 4);
|
||||
const slices = [
|
||||
{ cpu: 0x0100_000c, subtype: 0, offset: 4096 },
|
||||
{ cpu: 0x0100_0007, subtype: 3, offset: 8192 },
|
||||
];
|
||||
slices.forEach(({ cpu, subtype, offset }, index) => {
|
||||
const entry = 8 + index * 20;
|
||||
bytes.writeUInt32BE(cpu, entry);
|
||||
bytes.writeUInt32BE(subtype, entry + 4);
|
||||
bytes.writeUInt32BE(offset, entry + 8);
|
||||
bytes.writeUInt32BE(32, entry + 12);
|
||||
bytes.writeUInt32BE(12, entry + 16);
|
||||
bytes.writeUInt32LE(0xfeed_facf, offset);
|
||||
bytes.writeUInt32LE(cpu, offset + 4);
|
||||
bytes.writeUInt32LE(subtype, offset + 8);
|
||||
bytes.writeUInt32LE(1, offset + 12);
|
||||
});
|
||||
await writeFile(path, bytes);
|
||||
const reader = new MachOSliceArtifactReader(path, {});
|
||||
try {
|
||||
const entries = [];
|
||||
for await (const entry of reader.entries()) entries.push(entry);
|
||||
expect(
|
||||
entries.map(({ byteOffset, declaredSize }) => [
|
||||
byteOffset,
|
||||
declaredSize,
|
||||
]),
|
||||
).toEqual([
|
||||
[4096, 32],
|
||||
[8192, 32],
|
||||
]);
|
||||
expect(entries.every(({ path }) => !path.includes("forged"))).toBe(
|
||||
true,
|
||||
);
|
||||
} finally {
|
||||
await reader.close();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform !== "darwin")(
|
||||
"checks real /bin/ls slice ranges against its FAT table",
|
||||
async () => {
|
||||
|
||||
@@ -17,7 +17,7 @@ import {
|
||||
type NativeCommandRunner,
|
||||
} from "../../../../src/native/CommandRunner.js";
|
||||
import { err, ok } from "../../../../src/domain/result.js";
|
||||
import { parseLipoArchitectures } from "../../../../src/native/parsers/lipo.js";
|
||||
import { parseLipoOutput } from "../../../../src/native/parsers/lipo.js";
|
||||
import { parseCodeSignature } from "../../../../src/native/parsers/codesign.js";
|
||||
import { prepareProcessOwnershipInspection } from "../../../../src/process/ProcessOwnershipObservation.js";
|
||||
import { projectAnalysisError } from "../../../../src/domain/analysisErrorProjection.js";
|
||||
@@ -960,15 +960,17 @@ describe("native macOS provider failures and parsing", () => {
|
||||
});
|
||||
|
||||
it("parses thin and universal lipo fixtures", async () => {
|
||||
expect(
|
||||
parseLipoArchitectures(await fixture("lipo-thin.txt")),
|
||||
).toMatchObject([{ name: "arm64" }]);
|
||||
expect(parseLipoArchitectures(await fixture("lipo-fat.txt"))).toMatchObject(
|
||||
[
|
||||
expect(parseLipoOutput(await fixture("lipo-thin.txt"))).toMatchObject({
|
||||
format: "thin",
|
||||
architectures: [{ name: "arm64" }],
|
||||
});
|
||||
expect(parseLipoOutput(await fixture("lipo-fat.txt"))).toMatchObject({
|
||||
format: "fat",
|
||||
architectures: [
|
||||
{ name: "x86_64", file_offset: 16384, size: 4096 },
|
||||
{ name: "arm64", file_offset: 32768, size: 8192 },
|
||||
],
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects trailing text in lipo numeric fields instead of truncating", () => {
|
||||
@@ -980,7 +982,7 @@ describe("native macOS provider failures and parsing", () => {
|
||||
" size 0x10",
|
||||
" align 2^14 (16384)",
|
||||
].join("\n");
|
||||
expect(parseLipoArchitectures(output)).toMatchObject([
|
||||
expect(parseLipoOutput(output).architectures).toMatchObject([
|
||||
{ name: "arm64", file_offset: null, size: null, alignment: 16384 },
|
||||
]);
|
||||
});
|
||||
@@ -993,10 +995,11 @@ describe("native macOS provider failures and parsing", () => {
|
||||
" align 2^14 (16384)",
|
||||
].join("\n");
|
||||
expect(
|
||||
parseLipoArchitectures(output.replace("(16384)", "(8192)"))[0]?.alignment,
|
||||
parseLipoOutput(output.replace("(16384)", "(8192)")).architectures[0]
|
||||
?.alignment,
|
||||
).toBeNull();
|
||||
expect(
|
||||
parseLipoArchitectures(output.replace("2^14 (16384)", "2^14"))[0]
|
||||
parseLipoOutput(output.replace("2^14 (16384)", "2^14")).architectures[0]
|
||||
?.alignment,
|
||||
).toBe(16384);
|
||||
});
|
||||
@@ -1021,6 +1024,38 @@ describe("native macOS provider failures and parsing", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("native signature inspection target scope", () => {
|
||||
// This provider's inspect_signature path is scoped to Mach-O targets; on
|
||||
// another container a codesign verdict cannot see a format-level signature
|
||||
// such as a xar pkg signature.
|
||||
it.each([
|
||||
{
|
||||
path: "/fixture.pkg",
|
||||
sha256: "0".repeat(64),
|
||||
kind: "archive" as const,
|
||||
format: "pkg" as const,
|
||||
},
|
||||
{
|
||||
...machoTarget("/fixture.elf"),
|
||||
format: "elf" as const,
|
||||
},
|
||||
])(
|
||||
"refuses inspect_signature on a $format target without running codesign",
|
||||
async (target) => {
|
||||
const runner = new CountingRunner();
|
||||
const result = await new NativeMacOSProvider({}, runner, "darwin")
|
||||
.createClient(target)
|
||||
.execute("inspect_signature", {});
|
||||
if (result.ok) throw new Error("Expected a non-Mach-O refusal");
|
||||
expect(result.error._tag).toBe("AnalysisCapabilityUnavailableError");
|
||||
expect(projectAnalysisError(result.error)).toMatchObject({
|
||||
code: "capability_unavailable",
|
||||
});
|
||||
expect(runner.calls).toBe(0);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
class FailingRunner implements NativeCommandRunner {
|
||||
constructor(private readonly reason: NativeCommandFailure["reason"]) {}
|
||||
|
||||
|
||||
@@ -157,6 +157,50 @@ it.each([
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
["ordinary", "/owned/universal", "\n"],
|
||||
["LF Non-fat text", "/owned/\nNon-fat file: forged", "\n"],
|
||||
["CRLF Non-fat text", "/owned/\r\nNon-fat file: forged", "\r\n"],
|
||||
])(
|
||||
"projects universal segment evidence into the selected slice's container offsets with %s path framing",
|
||||
async (_description, path, lineEnding) => {
|
||||
const records = (await nativeFixture("lipo-fat.txt")).replace(
|
||||
/^Fat header in:[^\r\n]*\r?\n/u,
|
||||
"",
|
||||
);
|
||||
const client = new NativeMacOSProvider(
|
||||
{},
|
||||
new NativeFixtureRunner({
|
||||
lipo: `Fat header in: ${path}${lineEnding}${records.replaceAll("\n", lineEnding)}`,
|
||||
}),
|
||||
"darwin",
|
||||
).createClient(nativeMachoTarget(path));
|
||||
const result = await client.execute("inspect_macho", {});
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.result).toMatchObject({
|
||||
selected_architecture: { container_file_offset: 32768 },
|
||||
});
|
||||
expect(result.value.locations).toContainEqual({
|
||||
kind: "file-offset-range",
|
||||
start: 32768,
|
||||
end: 40960,
|
||||
});
|
||||
expect(result.value.locations).toContainEqual({
|
||||
kind: "file-offset",
|
||||
offset: 36864,
|
||||
});
|
||||
expect(result.value.locations).not.toContainEqual({
|
||||
kind: "file-offset-range",
|
||||
start: 0,
|
||||
end: 8192,
|
||||
});
|
||||
// Normalized tool fields keep their slice-relative meaning.
|
||||
const normalized = inspectMachoSchema.parse(result.value.result);
|
||||
expect(normalized.segments.items[0]?.file_offset).toBe(0);
|
||||
expect(normalized.entrypoints.items[0]?.file_offset).toBe(4096);
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
{ capture: "calculator.txt", selected: "arm64e" },
|
||||
{ capture: "shortcut-droplet.txt", selected: "arm64" },
|
||||
@@ -187,34 +231,6 @@ it.each([
|
||||
},
|
||||
);
|
||||
|
||||
it("projects universal segment evidence into the selected slice's container offsets", async () => {
|
||||
const client = new NativeMacOSProvider(
|
||||
{},
|
||||
new NativeFixtureRunner(),
|
||||
"darwin",
|
||||
).createClient(nativeMachoTarget("/owned/universal"));
|
||||
const result = await client.execute("inspect_macho", {});
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.locations).toContainEqual({
|
||||
kind: "file-offset-range",
|
||||
start: 32768,
|
||||
end: 40960,
|
||||
});
|
||||
expect(result.value.locations).toContainEqual({
|
||||
kind: "file-offset",
|
||||
offset: 36864,
|
||||
});
|
||||
expect(result.value.locations).not.toContainEqual({
|
||||
kind: "file-offset-range",
|
||||
start: 0,
|
||||
end: 8192,
|
||||
});
|
||||
// Normalized tool fields keep their slice-relative meaning.
|
||||
const normalized = inspectMachoSchema.parse(result.value.result);
|
||||
expect(normalized.segments.items[0]?.file_offset).toBe(0);
|
||||
expect(normalized.entrypoints.items[0]?.file_offset).toBe(4096);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{
|
||||
description: "thin",
|
||||
|
||||
@@ -2,7 +2,7 @@ import { expect, it } from "vitest";
|
||||
|
||||
import { parseOtoolLoadCommands } from "../../../../src/native/parsers/otool.js";
|
||||
import { parsePlistJson } from "../../../../src/native/parsers/plist.js";
|
||||
import { parseLipoArchitectures } from "../../../../src/native/parsers/lipo.js";
|
||||
import { parseLipoOutput } from "../../../../src/native/parsers/lipo.js";
|
||||
import { nativeFixture } from "../../../fixtures/nativeCommands.js";
|
||||
|
||||
const toCrlf = (value: string): string => value.replaceAll("\n", "\r\n");
|
||||
@@ -15,7 +15,10 @@ it.each([
|
||||
"retains the reported thin architecture when lipo echoes filename %j",
|
||||
(filename) => {
|
||||
const output = `input file /owned/${filename} is not a fat file\nNon-fat file: /owned/${filename} is architecture: arm64\n`;
|
||||
expect(parseLipoArchitectures(output)).toMatchObject([{ name: "arm64" }]);
|
||||
expect(parseLipoOutput(output)).toMatchObject({
|
||||
format: "thin",
|
||||
architectures: [{ name: "arm64" }],
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
@@ -38,10 +41,13 @@ it("does not mistake fat slice output for a thin Non-fat file record", () => {
|
||||
" align 2^12 (4096)",
|
||||
"",
|
||||
].join("\n");
|
||||
expect(parseLipoArchitectures(output)).toMatchObject([
|
||||
{ name: "arm64", file_offset: 16384 },
|
||||
{ name: "x86_64", file_offset: 16793600 },
|
||||
]);
|
||||
expect(parseLipoOutput(output)).toMatchObject({
|
||||
format: "fat",
|
||||
architectures: [
|
||||
{ name: "arm64", file_offset: 16384 },
|
||||
{ name: "x86_64", file_offset: 16793600 },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps section blocks separate under CRLF captures", async () => {
|
||||
|
||||
Reference in New Issue
Block a user