Skip to content

armgit / rea

Public Imported from GitHub
0

Reverse engineer anything with agents, from app behavior down to native binaries.

Merge origin/main into feat/dylib-resolution

Kaoru0822e5c6fccc35d7
diff --cc docs/testing.md
index 024d3a1e5,e7f406c9f..8d77e8090
--- a/docs/testing.md
+++ b/docs/testing.md
@@@ -87,17 -87,14 +87,23 @@@ extension, a login item, a privileged h
signed ad hoc. It packs the app as a directory, a `ditto` ZIP, and an APFS DMG,
then checks that `inspect-artifact` plus `project-apple-application-graph`
report the same bundle anatomy for all three through the CLI, with stdio MCP
-parity. It also checks that the DMG is detached afterwards. It runs in macOS CI.
+parity. It also checks that the DMG is detached afterwards. The same app
+covers `trace-dylib-resolution`:
+
+- each resolution status and finding, with CLI/MCP parity;
+- for every traced image, dependencies, rpaths, and install names equal to
+ `otool -l`;
+- for the main executable and an XPC service, a predicted load order equal to
+ the images dyld actually loads under `DYLD_PRINT_LIBRARIES`.
+
+It runs in macOS CI.
+ Apple artifact verifiers live in `scripts/verify/apple/`, with the macOS bundle
+ builder under `scripts/fixtures/apple/` and NIB byte fixtures beside the decoder
+ in `src/artifacts/apple/`. The npm entrypoints are unchanged. Format-specific
+ Swift/XIB/asset sources and goldens retain their locations; real Apple workflows
+ resolve them from the verifier file URL and run in the macOS CI lane.
+
MCP SDK transport tests with recording providers remain integration tests.
They are useful for schema drift and failure projection but do not prove that
Hopper, Ghidra or another substituted engine works. `verify:package` proves
diff --cc scripts/verify/apple/macos-bundle.mjs
index 0f3c986cc,bc4522b73..972c8a7c4
--- a/scripts/verify/apple/macos-bundle.mjs
+++ b/scripts/verify/apple/macos-bundle.mjs
@@@ -13,8 -13,7 +13,8 @@@ import
import {
buildMacosBundleFixture,
preflightMacosBundleFixture,
- } from "./lib/macos-bundle-fixture.mjs";
- import { verifyDylibResolution } from "./lib/macos-dylib-e2e.mjs";
+ } from "../../fixtures/apple/macos-bundle.mjs";
++import { verifyDylibResolution } from "./macos-dylib-e2e.mjs";
const exec = promisify(execFile);
diff --cc scripts/verify/apple/macos-dylib-e2e.mjs
index 828da9953,000000000..eacd06e9f
mode 100644,000000..100644
--- a/scripts/verify/apple/macos-dylib-e2e.mjs
+++ b/scripts/verify/apple/macos-dylib-e2e.mjs
@@@ -1,209 -1,0 +1,209 @@@
+import assert from "node:assert/strict";
+import { execFile } from "node:child_process";
+import { realpath } from "node:fs/promises";
+import { join, relative } from "node:path";
+import { promisify } from "node:util";
+
+import {
+ artifactCliEvidence,
+ artifactMcpResult,
+ withArtifactMcp,
- } from "./artifact-e2e.mjs";
++} from "../../lib/artifact-e2e.mjs";
+
+const exec = promisify(execFile);
+
+const MAIN = "Contents/MacOS/MacFixture";
+const SERVICE = "Contents/XPCServices/Svc.xpc/Contents/MacOS/Svc";
+const CORE = "Contents/Frameworks/Core.framework/Versions/A/Core";
+const DEPENDENCY_COMMANDS = new Set([
+ "LC_LOAD_DYLIB",
+ "LC_LOAD_WEAK_DYLIB",
+ "LC_REEXPORT_DYLIB",
+ "LC_LAZY_LOAD_DYLIB",
+ "LC_LOAD_UPWARD_DYLIB",
+]);
+
+/** Dependencies, rpaths and install name of one slice as Apple's otool reports them. */
+const otoolLoadCommands = async (path, architecture) => {
+ const { stdout } = await exec(
+ "/usr/bin/xcrun",
+ ["otool", "-arch", architecture, "-l", path],
+ { maxBuffer: 64 * 1024 * 1024 },
+ );
+ const result = { dependencies: [], rpaths: [], install_name: null };
+ for (const block of stdout.split(/\nLoad command \d+\n/u)) {
+ const command = /^\s*cmd (\S+)/mu.exec(block)?.[1];
+ const name = /^\s*name (.+?) \(offset \d+\)$/mu.exec(block)?.[1];
+ if (command === "LC_RPATH")
+ result.rpaths.push(/^\s*path (.+?) \(offset \d+\)$/mu.exec(block)?.[1]);
+ else if (command === "LC_ID_DYLIB") result.install_name = name;
+ else if (DEPENDENCY_COMMANDS.has(command))
+ result.dependencies.push(`${command} ${name}`);
+ }
+ return result;
+};
+
+/** In-bundle images dyld actually loaded, in load order. */
+const loadedImages = async (app, executable) => {
+ const { stderr } = await exec(join(app, executable), [], {
+ env: { PATH: "/usr/bin:/bin", DYLD_PRINT_LIBRARIES: "1" },
+ });
+ const appRoot = await realpath(app);
+ const loaded = [];
+ for (const line of stderr.split("\n")) {
+ const path = /^dyld\[\d+\]: <[0-9A-F-]+> (.+)$/u.exec(line)?.[1];
+ if (path === undefined) continue;
+ // Shared-cache libraries are reported by path but are not files on disk.
+ const real = await realpath(path).catch(() => undefined);
+ if (real?.startsWith(`${appRoot}/`) === true)
+ loaded.push(relative(appRoot, real));
+ }
+ return loaded;
+};
+
+/** Images a process root loads according to the trace, in first-load order. */
+const predictedImages = (trace, root) => {
+ const loaded = [root];
+ for (const edge of trace.edges)
+ if (
+ edge.root === root &&
+ ["resolved", "conditional"].includes(edge.resolution.status) &&
+ !loaded.includes(edge.resolution.image)
+ )
+ loaded.push(edge.resolution.image);
+ return loaded;
+};
+
+const findEdge = (trace, root, loader, installName) => {
+ const edge = trace.edges.find(
+ (candidate) =>
+ candidate.root === root &&
+ candidate.loader === loader &&
+ candidate.install_name === installName,
+ );
+ assert.ok(edge, `missing edge ${root}: ${loader} -> ${installName}`);
+ return edge;
+};
+
+const verifyResolutionShapes = (trace) => {
+ const core = findEdge(
+ trace,
+ MAIN,
+ MAIN,
+ "@rpath/Core.framework/Versions/A/Core",
+ );
+ assert.deepEqual(
+ core.candidates.map(({ source, outcome }) => [source, outcome]),
+ [
+ ["rpath", "absent"],
+ ["rpath", "resolved"],
+ ],
+ );
+ assert.deepEqual(core.resolution, { status: "resolved", image: CORE });
+ const weak = findEdge(trace, MAIN, MAIN, "@rpath/libgone.dylib");
+ assert.equal(weak.weak, true);
+ assert.equal(weak.resolution.status, "unresolved");
+ const delayed = findEdge(trace, MAIN, MAIN, "@rpath/libdelay.dylib");
+ assert.equal(delayed.encoding, "dylib_use_command");
+ assert.equal(delayed.delayed_init, true);
+ const chain = findEdge(trace, MAIN, CORE, "@rpath/libchain.dylib");
+ assert.equal(
+ chain.resolution.image,
+ "Contents/Frameworks/Core.framework/Versions/A/Libraries/libchain.dylib",
+ "the loading image's own LC_RPATH must be searched first",
+ );
+ const service = findEdge(
+ trace,
+ SERVICE,
+ SERVICE,
+ "@rpath/Core.framework/Versions/A/Core",
+ );
+ assert.equal(service.candidates[0]?.outcome, "outside-target");
+ assert.deepEqual(service.resolution, { status: "conditional", image: CORE });
+ const system = trace.edges.filter(({ install_name: name }) =>
+ name.startsWith("/usr/lib/"),
+ );
+ assert.ok(system.length > 0);
+ assert.ok(
+ system.every(({ resolution }) => resolution.status === "undetermined"),
+ );
+ const kinds = trace.findings.map(({ kind, image }) => `${kind}:${image}`);
+ assert.ok(kinds.includes(`weak-load-unresolved:${MAIN}`));
+ assert.ok(kinds.includes(`earlier-rpath-candidate-absent:${MAIN}`));
+};
+
+const verifyParserConformance = async (app, trace) => {
+ let slices = 0;
+ for (const image of trace.images)
+ for (const slice of image.slices) {
+ const expected = await otoolLoadCommands(
+ join(app, image.path),
+ slice.architecture,
+ );
+ const edges = trace.edges.filter(
+ ({ loader, architecture, root }) =>
+ loader === image.path &&
+ architecture === slice.architecture &&
+ root ===
+ trace.edges.find(
+ (edge) =>
+ edge.loader === image.path &&
+ edge.architecture === slice.architecture,
+ )?.root,
+ );
+ assert.deepEqual(
+ {
+ dependencies: edges.map(
+ ({ command, install_name: name }) => `${command} ${name}`,
+ ),
+ rpaths: slice.rpaths,
+ install_name: slice.install_name,
+ },
+ expected,
+ `${image.path} (${slice.architecture}) differs from otool -l`,
+ );
+ slices += 1;
+ }
+ return slices;
+};
+
+/** Verify trace_dylib_resolution against otool and the real dyld on the fixture app. */
+export async function verifyDylibResolution(app) {
+ const trace = (await artifactCliEvidence("trace-dylib-resolution", app))
+ .normalized_result;
+ await withArtifactMcp(app, async (client) => {
+ assert.deepEqual(
+ await artifactMcpResult(client, "trace_dylib_resolution"),
+ trace,
+ );
+ const invalid = await client.callTool({
+ name: "trace_dylib_resolution",
+ arguments: { roots: ["../outside"] },
+ });
+ assert.equal(invalid.isError, true);
+ });
+ assert.equal(trace.coverage.status, "complete");
+ assert.deepEqual(trace.roots.map(({ image }) => image).sort(), [
+ "Contents/Frameworks/Core.framework/Versions/A/XPCServices/FwSvc.xpc/Contents/MacOS/FwSvc",
+ "Contents/Helpers/rea-tool",
+ "Contents/Library/LaunchServices/com.example.rea.helper",
+ "Contents/Library/LoginItems/Login.app/Contents/MacOS/Login",
+ MAIN,
+ "Contents/PlugIns/Ext.appex/Contents/MacOS/Ext",
+ SERVICE,
+ ]);
+ verifyResolutionShapes(trace);
+ const slices = await verifyParserConformance(app, trace);
+ for (const root of [MAIN, SERVICE])
+ assert.deepEqual(
+ await loadedImages(app, root),
+ predictedImages(trace, root),
+ `${root} load order differs from DYLD_PRINT_LIBRARIES`,
+ );
+ return {
+ roots: trace.roots.length,
+ edges: trace.edges.length,
+ otool_slices: slices,
+ dyld_runtime_roots: 2,
+ };
+}
diff --cc src/artifacts/ArtifactProvider.ts
index 2041a89e9,54d9d3826..b180dd34b
--- a/src/artifacts/ArtifactProvider.ts
+++ b/src/artifacts/ArtifactProvider.ts
@@@ -7,8 -7,7 +7,8 @@@ import
type ProviderIdentity,
type ExecutionOptions,
} from "../application/AnalysisProvider.js";
- import { inspectBundleKeyedArchive } from "./KeyedArchiveReader.js";
- import { traceDylibResolution } from "./DylibResolutionReader.js";
+ import { inspectBundleKeyedArchive } from "./apple/KeyedArchiveReader.js";
++import { traceDylibResolution } from "./apple/DylibResolutionReader.js";
import { basename, dirname } from "node:path";
import { inventoryArtifact } from "../application/ArtifactInventory.js";
import { extractArtifact } from "../application/ArtifactExtraction.js";
diff --cc src/artifacts/apple/DylibResolutionReader.ts
index 696147e02,000000000..b18c369b0
mode 100644,000000..100644
--- a/src/artifacts/apple/DylibResolutionReader.ts
+++ b/src/artifacts/apple/DylibResolutionReader.ts
@@@ -1,350 -1,0 +1,350 @@@
+import { createHash } from "node:crypto";
+import { constants } from "node:fs";
+import { lstat, open, readlink, realpath } from "node:fs/promises";
+import { join, relative, sep } from "node:path";
+
- import { resolveTreePath } from "../domain/dyldPaths.js";
++import { resolveTreePath } from "../../domain/apple/dyldPaths.js";
+import {
+ dylibResolutionInputSchema,
+ dylibResolutionResultSchema,
+ traceDylibLoading,
+ type DylibResolutionResult,
+ type DylibTreeEntry,
+ type DylibTreeView,
+ type MachoImageFacts,
- } from "../domain/dylibResolution.js";
- import { ArtifactReaderFailure } from "./ArtifactReader.js";
- import { DirectoryArtifactReader } from "./DirectoryArtifactReader.js";
++} from "../../domain/apple/dylibResolution.js";
++import { ArtifactReaderFailure } from "../ArtifactReader.js";
++import { DirectoryArtifactReader } from "../DirectoryArtifactReader.js";
+import { hasMachoMagic, readMachoImage } from "./MachoLoadCommandReader.js";
+
+const HASH_CHUNK_BYTES = 1024 * 1024;
+
+/** Device, inode, size and change times of the file whose bytes were parsed. */
+type FileIdentity = string;
+
+/** Lazily probed, symlink-preserving view of one analyzed directory. */
+class FilesystemTreeView implements DylibTreeView {
+ readonly #entries = new Map<string, Promise<DylibTreeEntry | undefined>>();
+ readonly #images = new Map<string, Promise<MachoImageFacts>>();
+ readonly #identities = new Map<string, FileIdentity>();
+
+ constructor(
+ private readonly root: string,
+ private readonly signal?: AbortSignal,
+ ) {}
+
+ entry(path: string): Promise<DylibTreeEntry | undefined> {
+ const cached = this.#entries.get(path);
+ if (cached !== undefined) return cached;
+ const pending = this.#readEntry(path);
+ this.#entries.set(path, pending);
+ return pending;
+ }
+
+ image(path: string): Promise<MachoImageFacts> {
+ const cached = this.#images.get(path);
+ if (cached !== undefined) return cached;
+ const pending = readImage(join(this.root, path), this.signal).then(
+ ({ facts, identity }) => {
+ this.#identities.set(path, identity);
+ return facts;
+ },
+ );
+ this.#images.set(path, pending);
+ return pending;
+ }
+
+ /** Identity of the file whose header bytes `image()` parsed. */
+ identity(path: string): FileIdentity | undefined {
+ return this.#identities.get(path);
+ }
+
+ async #readEntry(path: string): Promise<DylibTreeEntry | undefined> {
+ cancelled(this.signal);
+ const absolute = join(this.root, path);
+ try {
+ const metadata = await lstat(absolute);
+ if (metadata.isSymbolicLink())
+ return { kind: "symlink", target: await readlink(absolute) };
+ if (metadata.isDirectory()) return { kind: "directory" };
+ return metadata.isFile() ? { kind: "file" } : undefined;
+ } catch (cause: unknown) {
+ if (missing(cause)) return undefined;
+ throw cause;
+ }
+ }
+}
+
+/** Resolve dyld load paths for the active Mach-O or every executable in its bundle. */
+export const traceDylibResolution = async (options: {
+ readonly rootPath: string;
+ readonly targetPath: string;
+ readonly targetSha256: string;
+ readonly enumerateRoots: boolean;
+ readonly parameters: unknown;
+ readonly signal?: AbortSignal;
+}): Promise<DylibResolutionResult> => {
+ const parsed = dylibResolutionInputSchema.safeParse(options.parameters);
+ if (!parsed.success)
+ throw new ArtifactReaderFailure(
+ "path",
+ "roots must be normalized paths relative to the analyzed root",
+ );
+ const root = await realpath(options.rootPath);
+ const target = relative(root, await realpath(options.targetPath))
+ .split(sep)
+ .join("/");
+ const view = new FilesystemTreeView(root, options.signal);
+ try {
+ const { roots: requested, unclassified } =
+ parsed.data.roots !== undefined
+ ? { roots: parsed.data.roots, unclassified: [] }
+ : options.enumerateRoots
+ ? await executableRoots(root, view, options.signal)
+ : { roots: [target], unclassified: [] };
+ const roots = await requireMachoRoots(view, requested);
+ const trace = await traceDylibLoading(view, {
+ roots,
+ unclassified,
+ ...(parsed.data.architecture === undefined
+ ? {}
+ : { architecture: parsed.data.architecture }),
+ ...(options.signal === undefined ? {} : { signal: options.signal }),
+ });
+ // Each digest must describe the same file whose headers were parsed.
+ const digests = new Map<string, string>();
+ for (const { path } of trace.images)
+ digests.set(
+ path,
+ await fileSha256(join(root, path), {
+ path,
+ expected: view.identity(path),
+ ...(options.signal === undefined ? {} : { signal: options.signal }),
+ }),
+ );
+ const targetDigest =
+ digests.get(target) ??
+ (await fileSha256(join(root, target), {
+ path: target,
+ expected: undefined,
+ ...(options.signal === undefined ? {} : { signal: options.signal }),
+ }));
+ if (targetDigest !== options.targetSha256)
+ throw new ArtifactReaderFailure(
+ "integrity",
+ `Active target digest changed: expected ${options.targetSha256}, observed ${targetDigest}`,
+ );
+ return dylibResolutionResultSchema.parse({
+ ...trace,
+ root_path: options.rootPath,
+ target_sha256: options.targetSha256,
+ images: trace.images.map((image) => ({
+ ...image,
+ sha256: digests.get(image.path),
+ })),
+ });
+ } catch (cause: unknown) {
+ if (options.signal?.aborted === true)
+ throw new ArtifactReaderFailure(
+ "cancelled",
+ "Dylib resolution was cancelled",
+ { cause },
+ );
+ const denied = permissionDenied(cause);
+ if (denied !== undefined)
+ throw new ArtifactReaderFailure(
+ "unavailable",
+ `Permission denied (${denied.code}) reading ${denied.path === undefined ? "a file in the analyzed root" : relative(root, denied.path) || denied.path}`,
+ { cause },
+ );
+ throw cause;
+ }
+};
+
+/**
+ * Every Mach-O in the bundle with an executable slice is its own process root.
+ * Mach-O files that do not parse are returned separately: whether they are
+ * executables is unknown, so they make coverage partial instead of vanishing.
+ */
+const executableRoots = async (
+ root: string,
+ view: FilesystemTreeView,
+ signal?: AbortSignal,
+): Promise<{ readonly roots: string[]; readonly unclassified: string[] }> => {
+ const roots: string[] = [];
+ const unclassified: string[] = [];
+ for await (const entry of new DirectoryArtifactReader(root).entries(signal)) {
+ if (
+ entry.kind !== "file" ||
+ !(await startsWithMachoMagic(entry.adapterKey))
+ )
+ continue;
+ const facts = await view.image(entry.path);
+ if (facts.status === "malformed" || facts.status === "unsupported")
+ unclassified.push(entry.path);
+ else if (
+ facts.status === "parsed" &&
+ facts.slices.some(({ file_type: type }) => type === "execute")
+ )
+ roots.push(entry.path);
+ }
+ return {
+ roots: roots.sort(compare),
+ unclassified: unclassified.sort(compare),
+ };
+};
+
+const compare = (left: string, right: string): number =>
+ left < right ? -1 : left > right ? 1 : 0;
+
+/**
+ * Resolve each root segment by segment, as dependency candidates are, so a
+ * symlink in an intermediate directory cannot lead outside the analyzed root.
+ */
+const requireMachoRoots = async (
+ view: FilesystemTreeView,
+ roots: readonly string[],
+): Promise<string[]> => {
+ const resolved: string[] = [];
+ for (const path of roots) {
+ const lookup = await resolveTreePath(view, path);
+ if (lookup.kind === "escapes")
+ throw new ArtifactReaderFailure(
+ "path",
+ `Root ${path} resolves outside the analyzed root`,
+ );
+ if (lookup.kind !== "file")
+ throw new ArtifactReaderFailure(
+ "path",
+ `Root ${path} is not a regular file in the analyzed root`,
+ );
+ if ((await view.image(lookup.path)).status === "not-mach-o")
+ throw new ArtifactReaderFailure(
+ "format",
+ `Root ${path} is not a Mach-O image`,
+ );
+ if (!resolved.includes(lookup.path)) resolved.push(lookup.path);
+ }
+ return resolved;
+};
+
+const startsWithMachoMagic = async (path: string): Promise<boolean> => {
+ const handle = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW);
+ try {
+ const buffer = new Uint8Array(4);
+ const { bytesRead } = await handle.read(buffer, 0, 4, 0);
+ return hasMachoMagic(buffer.subarray(0, bytesRead));
+ } finally {
+ await handle.close();
+ }
+};
+
+const identityOf = (metadata: {
+ readonly dev: bigint;
+ readonly ino: bigint;
+ readonly size: bigint;
+ readonly mtimeNs: bigint;
+ readonly ctimeNs: bigint;
+}): FileIdentity =>
+ [
+ metadata.dev,
+ metadata.ino,
+ metadata.size,
+ metadata.mtimeNs,
+ metadata.ctimeNs,
+ ].join(":");
+
+const readImage = async (
+ path: string,
+ signal?: AbortSignal,
+): Promise<{
+ readonly facts: MachoImageFacts;
+ readonly identity: FileIdentity;
+}> => {
+ cancelled(signal);
+ const handle = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW);
+ try {
+ const metadata = await handle.stat({ bigint: true });
+ const size = Number(metadata.size);
+ const facts = await readMachoImage(async (offset, length) => {
+ cancelled(signal);
+ const buffer = new Uint8Array(
+ Math.max(0, Math.min(length, size - offset)),
+ );
+ const { bytesRead } = await handle.read(buffer, 0, buffer.length, offset);
+ return buffer.subarray(0, bytesRead);
+ }, size);
+ return { facts, identity: identityOf(metadata) };
+ } finally {
+ await handle.close();
+ }
+};
+
+/** Hash a file, failing if it is not the file (or the version) that was parsed. */
+const fileSha256 = async (
+ absolute: string,
+ options: {
+ readonly path: string;
+ readonly expected: FileIdentity | undefined;
+ readonly signal?: AbortSignal;
+ },
+): Promise<string> => {
+ const { signal } = options;
+ const handle = await open(
+ absolute,
+ constants.O_RDONLY | constants.O_NOFOLLOW,
+ );
+ const unchanged = async (): Promise<void> => {
+ if (
+ options.expected !== undefined &&
+ identityOf(await handle.stat({ bigint: true })) !== options.expected
+ )
+ throw new ArtifactReaderFailure(
+ "integrity",
+ `${options.path} changed while its dyld load commands were traced`,
+ );
+ };
+ try {
+ await unchanged();
+ const hash = createHash("sha256");
+ const buffer = new Uint8Array(HASH_CHUNK_BYTES);
+ for (;;) {
+ cancelled(signal);
+ const { bytesRead } = await handle.read(buffer, 0, buffer.length, null);
+ if (bytesRead === 0) break;
+ hash.update(buffer.subarray(0, bytesRead));
+ }
+ await unchanged();
+ return hash.digest("hex");
+ } finally {
+ await handle.close();
+ }
+};
+
+const cancelled = (signal?: AbortSignal): void => {
+ if (signal?.aborted === true)
+ throw new ArtifactReaderFailure(
+ "cancelled",
+ "Dylib resolution was cancelled",
+ );
+};
+
+/** Host permission denials, kept distinct from malformed or missing files. */
+const permissionDenied = (
+ cause: unknown,
+): { readonly code: string; readonly path: string | undefined } | undefined => {
+ if (!(cause instanceof Error) || !("code" in cause)) return undefined;
+ if (cause.code !== "EACCES" && cause.code !== "EPERM") return undefined;
+ return {
+ code: cause.code,
+ path:
+ "path" in cause && typeof cause.path === "string"
+ ? cause.path
+ : undefined,
+ };
+};
+
+const missing = (cause: unknown): boolean =>
+ cause instanceof Error &&
+ "code" in cause &&
+ (cause.code === "ENOENT" || cause.code === "ENOTDIR");
diff --cc src/artifacts/apple/MachoImage.fixture.ts
index 634ab4ecf,000000000..634ab4ecf
mode 100644,000000..100644
--- a/src/artifacts/apple/MachoImage.fixture.ts
+++ b/src/artifacts/apple/MachoImage.fixture.ts
diff --cc src/artifacts/apple/MachoLoadCommandReader.test.ts
index 46c4138cc,000000000..46c4138cc
mode 100644,000000..100644
--- a/src/artifacts/apple/MachoLoadCommandReader.test.ts
+++ b/src/artifacts/apple/MachoLoadCommandReader.test.ts
diff --cc src/artifacts/apple/MachoLoadCommandReader.ts
index 63801fb41,000000000..1eb4fccb7
mode 100644,000000..100644
--- a/src/artifacts/apple/MachoLoadCommandReader.ts
+++ b/src/artifacts/apple/MachoLoadCommandReader.ts
@@@ -1,422 -1,0 +1,422 @@@
+import type {
+ MachoDependency,
+ MachoImageFacts,
+ MachoSlice,
- } from "../domain/dylibResolution.js";
++} from "../../domain/apple/dylibResolution.js";
+
+/** Read `length` bytes at `offset`; shorter results mean end of file. */
+export type ReadAt = (offset: number, length: number) => Promise<Uint8Array>;
+
+/** Load commands larger than this are refused instead of buffered. */
+export const MAX_LOAD_COMMAND_BYTES = 16 * 1024 * 1024;
+/** Target opening accepts up to 128 FAT records; Java class files share the FAT magic. */
+const MAX_FAT_ARCHITECTURES = 128;
+/** CPU types of real Mach-O slices (x86, x86_64, arm, arm64, arm64_32, ppc, ppc64). */
+const KNOWN_CPU_TYPES: readonly number[] = [
+ 7, 0x01000007, 12, 0x0100000c, 0x0200000c, 18, 0x01000012,
+];
+
+const MH_MAGIC = 0xfeedface;
+const MH_MAGIC_64 = 0xfeedfacf;
+const MH_CIGAM = 0xcefaedfe;
+const MH_CIGAM_64 = 0xcffaedfe;
+const FAT_MAGIC = 0xcafebabe;
+const FAT_MAGIC_64 = 0xcafebabf;
+const FAT_CIGAM = 0xbebafeca;
+const FAT_CIGAM_64 = 0xbfbafeca;
+
+const LC_ID_DYLIB = 0xd;
+const LC_LOAD_DYLIB = 0xc;
+const LC_LOAD_WEAK_DYLIB = 0x80000018;
+const LC_REEXPORT_DYLIB = 0x8000001f;
+const LC_LAZY_LOAD_DYLIB = 0x20;
+const LC_LOAD_UPWARD_DYLIB = 0x80000023;
+const LC_RPATH = 0x8000001c;
+const LC_DYLD_ENVIRONMENT = 0x27;
+const LC_CODE_SIGNATURE = 0x1d;
+
+/** `mach-o/loader.h` `dylib_use_command`: `nameoff == 28` and this marker. */
+const DYLIB_USE_MARKER = 0x1a741800;
+const DYLIB_USE_WEAK_LINK = 0x1;
+const DYLIB_USE_REEXPORT = 0x2;
+const DYLIB_USE_UPWARD = 0x4;
+const DYLIB_USE_DELAYED_INIT = 0x8;
+
+const DEPENDENCY_COMMANDS: ReadonlyMap<number, MachoDependency["command"]> =
+ new Map([
+ [LC_LOAD_DYLIB, "LC_LOAD_DYLIB"],
+ [LC_LOAD_WEAK_DYLIB, "LC_LOAD_WEAK_DYLIB"],
+ [LC_REEXPORT_DYLIB, "LC_REEXPORT_DYLIB"],
+ [LC_LAZY_LOAD_DYLIB, "LC_LAZY_LOAD_DYLIB"],
+ [LC_LOAD_UPWARD_DYLIB, "LC_LOAD_UPWARD_DYLIB"],
+ ]);
+
+/** Malformed or unsupported structure found while decoding one image. */
+class MachoFormatIssue extends Error {
+ constructor(
+ readonly status: "malformed" | "unsupported",
+ message: string,
+ ) {
+ super(message);
+ }
+}
+
+/** Report whether the first bytes carry a Mach-O or FAT magic number. */
+export const hasMachoMagic = (head: Uint8Array): boolean => {
+ if (head.byteLength < 4) return false;
+ const magic = new DataView(
+ head.buffer,
+ head.byteOffset,
+ head.byteLength,
+ ).getUint32(0, false);
+ return [
+ MH_MAGIC,
+ MH_MAGIC_64,
+ MH_CIGAM,
+ MH_CIGAM_64,
+ FAT_MAGIC,
+ FAT_MAGIC_64,
+ FAT_CIGAM,
+ FAT_CIGAM_64,
+ ].includes(magic);
+};
+
+/** Decode every slice's dylib-loading load commands without reading code. */
+export const readMachoImage = async (
+ readAt: ReadAt,
+ size: number,
+): Promise<MachoImageFacts> => {
+ try {
+ const head = await readAt(0, Math.min(size, 8));
+ if (head.byteLength < 8) return { status: "not-mach-o" };
+ const view = viewOf(head);
+ const magic = view.getUint32(0, false);
+ if ([FAT_MAGIC, FAT_MAGIC_64, FAT_CIGAM, FAT_CIGAM_64].includes(magic)) {
+ // FAT headers are big-endian; the swapped magics store them little-endian.
+ const littleEndian = magic === FAT_CIGAM || magic === FAT_CIGAM_64;
+ const count = view.getUint32(4, littleEndian);
+ const wide = magic === FAT_MAGIC_64 || magic === FAT_CIGAM_64;
+ // A Java class file's nonzero major version reads as the count, so an
+ // empty architecture table can only be a malformed universal header.
+ if (count === 0)
+ return {
+ status: "malformed",
+ reason: "FAT header declares no architectures",
+ };
+ if (count > MAX_FAT_ARCHITECTURES || 8 + count * (wide ? 32 : 20) > size)
+ return { status: "not-mach-o" };
+ const table = viewOf(
+ await readExact(readAt, 8, count * (wide ? 32 : 20), "FAT table"),
+ );
+ // A Java class file's version fields read as a FAT count; its "table" names no CPU.
+ const cpuTypes = Array.from({ length: count }, (_, index) =>
+ table.getUint32(index * (wide ? 32 : 20), littleEndian),
+ );
+ if (!cpuTypes.some((type) => KNOWN_CPU_TYPES.includes(type)))
+ return { status: "not-mach-o" };
+ return {
+ status: "parsed",
+ slices: await readFatSlices(readAt, size, {
+ wide,
+ littleEndian,
+ count,
+ }),
+ };
+ }
+ if (magic === MH_CIGAM || magic === MH_CIGAM_64)
+ return { status: "parsed", slices: [await readSlice(readAt, 0, size)] };
+ if (magic === MH_MAGIC || magic === MH_MAGIC_64)
+ throw new MachoFormatIssue(
+ "unsupported",
+ "big-endian Mach-O images are not supported",
+ );
+ return { status: "not-mach-o" };
+ } catch (cause: unknown) {
+ if (cause instanceof MachoFormatIssue)
+ return { status: cause.status, reason: cause.message };
+ throw cause;
+ }
+};
+
+const readFatSlices = async (
+ readAt: ReadAt,
+ size: number,
+ table: {
+ readonly wide: boolean;
+ readonly littleEndian: boolean;
+ readonly count: number;
+ },
+): Promise<MachoSlice[]> => {
+ const { wide, littleEndian, count } = table;
+ const entrySize = wide ? 32 : 20;
+ const view = viewOf(
+ await readExact(readAt, 8, count * entrySize, "FAT table"),
+ );
+ const slices: MachoSlice[] = [];
+ for (let index = 0; index < count; index++) {
+ const base = index * entrySize;
+ const offset = wide
+ ? safeNumber(view.getBigUint64(base + 8, littleEndian))
+ : view.getUint32(base + 8, littleEndian);
+ const length = wide
+ ? safeNumber(view.getBigUint64(base + 16, littleEndian))
+ : view.getUint32(base + 12, littleEndian);
+ if (offset + length > size)
+ throw new MachoFormatIssue(
+ "malformed",
+ `FAT architecture ${index} extends beyond the file`,
+ );
+ slices.push(await readSlice(readAt, offset, length));
+ }
+ return slices;
+};
+
+const readSlice = async (
+ readAt: ReadAt,
+ base: number,
+ length: number,
+): Promise<MachoSlice> => {
+ const header = viewOf(await readExact(readAt, base, 28, "Mach-O header"));
+ const magic = header.getUint32(0, true);
+ if (magic === MH_MAGIC_64 || magic === MH_MAGIC) {
+ const wide = magic === MH_MAGIC_64;
+ const headerSize = wide ? 32 : 28;
+ const commandCount = header.getUint32(16, true);
+ const commandBytes = header.getUint32(20, true);
+ if (commandBytes > MAX_LOAD_COMMAND_BYTES)
+ throw new MachoFormatIssue(
+ "unsupported",
+ `load commands occupy ${commandBytes} bytes, above the ${MAX_LOAD_COMMAND_BYTES}-byte limit`,
+ );
+ if (headerSize + commandBytes > length)
+ throw new MachoFormatIssue(
+ "malformed",
+ "load commands extend beyond the Mach-O slice",
+ );
+ const commands = await readExact(
+ readAt,
+ base + headerSize,
+ commandBytes,
+ "load commands",
+ );
+ return decodeCommands(commands, {
+ wide,
+ cpuType: header.getUint32(4, true),
+ cpuSubtype: header.getUint32(8, true),
+ fileType: header.getUint32(12, true),
+ commandCount,
+ });
+ }
+ throw new MachoFormatIssue(
+ magic === swap(MH_MAGIC) || magic === swap(MH_MAGIC_64)
+ ? "unsupported"
+ : "malformed",
+ magic === swap(MH_MAGIC) || magic === swap(MH_MAGIC_64)
+ ? "big-endian Mach-O slices are not supported"
+ : `slice at offset ${base} has no Mach-O header`,
+ );
+};
+
+const decodeCommands = (
+ bytes: Uint8Array,
+ header: {
+ readonly wide: boolean;
+ readonly cpuType: number;
+ readonly cpuSubtype: number;
+ readonly fileType: number;
+ readonly commandCount: number;
+ },
+): MachoSlice => {
+ // loader.h: load commands are 8-byte aligned in 64-bit images, 4 in 32-bit.
+ const alignment = header.wide ? 8 : 4;
+ const view = viewOf(bytes);
+ const slice: MachoSlice = {
+ architecture: architectureName(header.cpuType, header.cpuSubtype),
+ file_type: fileTypeName(header.fileType),
+ install_name: null,
+ dependencies: [],
+ rpaths: [],
+ dyld_environment: [],
+ code_signature_present: false,
+ };
+ let offset = 0;
+ for (let index = 0; index < header.commandCount; index++) {
+ if (offset + 8 > bytes.byteLength)
+ throw new MachoFormatIssue(
+ "malformed",
+ `load command ${index} starts beyond sizeofcmds`,
+ );
+ const command = view.getUint32(offset, true);
+ const size = view.getUint32(offset + 4, true);
+ if (size < 8 || size % alignment !== 0 || offset + size > bytes.byteLength)
+ throw new MachoFormatIssue(
+ "malformed",
+ `load command ${index} at offset ${offset} has invalid cmdsize ${size}`,
+ );
+ const body = bytes.subarray(offset, offset + size);
+ decodeCommand(command, body, index, slice);
+ offset += size;
+ }
+ return slice;
+};
+
+const decodeCommand = (
+ command: number,
+ body: Uint8Array,
+ index: number,
+ slice: MachoSlice,
+): void => {
+ if (command === LC_ID_DYLIB) {
+ slice.install_name = commandString(body, 24, index);
+ return;
+ }
+ if (command === LC_RPATH) {
+ slice.rpaths.push(commandString(body, 12, index));
+ return;
+ }
+ if (command === LC_DYLD_ENVIRONMENT) {
+ slice.dyld_environment.push(commandString(body, 12, index));
+ return;
+ }
+ if (command === LC_CODE_SIGNATURE) {
+ // linkedit_data_command: cmd, cmdsize, dataoff, datasize.
+ if (body.byteLength < 16)
+ throw new MachoFormatIssue(
+ "malformed",
+ `load command ${index} is too short for LC_CODE_SIGNATURE`,
+ );
+ slice.code_signature_present = true;
+ return;
+ }
+ const name = DEPENDENCY_COMMANDS.get(command);
+ if (name !== undefined)
+ slice.dependencies.push(decodeDependency(name, body, index));
+};
+
+const decodeDependency = (
+ command: MachoDependency["command"],
+ body: Uint8Array,
+ index: number,
+): MachoDependency => {
+ if (body.byteLength < 24)
+ throw new MachoFormatIssue(
+ "malformed",
+ `load command ${index} is too short for a dylib command`,
+ );
+ const view = viewOf(body);
+ const nameOffset = view.getUint32(8, true);
+ const usesFlags =
+ nameOffset === 28 &&
+ body.byteLength >= 28 &&
+ view.getUint32(12, true) === DYLIB_USE_MARKER;
+ const flags = usesFlags ? view.getUint32(24, true) : 0;
+ return {
+ command,
+ encoding: usesFlags ? "dylib_use_command" : "dylib_command",
+ install_name: commandString(body, usesFlags ? 28 : 24, index),
+ weak:
+ command === "LC_LOAD_WEAK_DYLIB" || (flags & DYLIB_USE_WEAK_LINK) !== 0,
+ upward:
+ command === "LC_LOAD_UPWARD_DYLIB" || (flags & DYLIB_USE_UPWARD) !== 0,
+ reexport:
+ command === "LC_REEXPORT_DYLIB" || (flags & DYLIB_USE_REEXPORT) !== 0,
+ delayed_init: (flags & DYLIB_USE_DELAYED_INIT) !== 0,
+ current_version: version(view.getUint32(16, true)),
+ compatibility_version: version(view.getUint32(20, true)),
+ };
+};
+
+/** NUL-terminated UTF-8 string at a `lc_str` offset inside one command. */
+const commandString = (
+ body: Uint8Array,
+ minimumOffset: number,
+ index: number,
+): string => {
+ if (body.byteLength < 12)
+ throw new MachoFormatIssue(
+ "malformed",
+ `load command ${index} is too short to hold a string offset`,
+ );
+ const offset = viewOf(body).getUint32(8, true);
+ if (offset < minimumOffset || offset >= body.byteLength)
+ throw new MachoFormatIssue(
+ "malformed",
+ `load command ${index} has string offset ${offset} outside the command`,
+ );
+ const end = body.indexOf(0, offset);
+ if (end < 0)
+ throw new MachoFormatIssue(
+ "malformed",
+ `load command ${index} has an unterminated string`,
+ );
+ try {
+ return new TextDecoder("utf-8", { fatal: true }).decode(
+ body.subarray(offset, end),
+ );
+ } catch {
+ throw new MachoFormatIssue(
+ "malformed",
+ `load command ${index} has a string that is not UTF-8`,
+ );
+ }
+};
+
+const readExact = async (
+ readAt: ReadAt,
+ offset: number,
+ length: number,
+ label: string,
+): Promise<Uint8Array> => {
+ const bytes = await readAt(offset, length);
+ if (bytes.byteLength < length)
+ throw new MachoFormatIssue("malformed", `${label} is truncated`);
+ return bytes;
+};
+
+const CPU_ARCH_ABI64 = 0x01000000;
+const CPU_ARCH_ABI64_32 = 0x02000000;
+const CPU_TYPE_X86 = 7;
+const CPU_TYPE_ARM = 12;
+const CPU_SUBTYPE_MASK = 0xff000000;
+const CPU_SUBTYPE_ARM64E = 2;
+const CPU_SUBTYPE_X86_64_H = 8;
+
+const architectureName = (cpuType: number, cpuSubtype: number): string => {
+ const subtype = cpuSubtype & ~CPU_SUBTYPE_MASK;
+ if (cpuType === (CPU_TYPE_ARM | CPU_ARCH_ABI64))
+ return subtype === CPU_SUBTYPE_ARM64E ? "arm64e" : "arm64";
+ if (cpuType === (CPU_TYPE_ARM | CPU_ARCH_ABI64_32)) return "arm64_32";
+ if (cpuType === (CPU_TYPE_X86 | CPU_ARCH_ABI64))
+ return subtype === CPU_SUBTYPE_X86_64_H ? "x86_64h" : "x86_64";
+ if (cpuType === CPU_TYPE_X86) return "i386";
+ if (cpuType === CPU_TYPE_ARM) return "arm";
+ return `cpu-${cpuType.toString(16)}`;
+};
+
+const fileTypeName = (fileType: number): MachoSlice["file_type"] =>
+ fileType === 2
+ ? "execute"
+ : fileType === 6
+ ? "dylib"
+ : fileType === 8
+ ? "bundle"
+ : "other";
+
+const version = (value: number): string =>
+ `${value >>> 16}.${(value >>> 8) & 0xff}.${value & 0xff}`;
+
+const swap = (value: number): number =>
+ (((value & 0xff) << 24) |
+ ((value & 0xff00) << 8) |
+ ((value >>> 8) & 0xff00) |
+ (value >>> 24)) >>>
+ 0;
+
+const safeNumber = (value: bigint): number => {
+ if (value > BigInt(Number.MAX_SAFE_INTEGER))
+ throw new MachoFormatIssue("malformed", "FAT offset exceeds safe range");
+ return Number(value);
+};
+
+const viewOf = (bytes: Uint8Array): DataView =>
+ new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
diff --cc src/contracts/artifactToolContracts.ts
index ade9cf25b,85fb8936b..b52f115af
--- a/src/contracts/artifactToolContracts.ts
+++ b/src/contracts/artifactToolContracts.ts
@@@ -5,9 -5,8 +5,9 @@@ import { artifactOutputSchemas } from "
import { jsonValueSchema } from "../domain/jsonValue.js";
import { toolContractMetadata } from "./toolEffects.js";
import { requireOutputSchema } from "./toolOutputSchemaPrimitives.js";
- import { appleAssetCatalogInputSchema } from "../domain/appleAssetCatalog.js";
- import { dylibResolutionInputSchema } from "../domain/dylibResolution.js";
- import { keyedArchiveInputSchema } from "../domain/keyedArchive.js";
+ import { appleAssetCatalogInputSchema } from "../domain/apple/appleAssetCatalog.js";
++import { dylibResolutionInputSchema } from "../domain/apple/dylibResolution.js";
+ import { keyedArchiveInputSchema } from "../domain/apple/keyedArchive.js";
/** Exact caller boundary for deterministic artifact inventory. */
export const artifactInventoryInputSchema = z.strictObject({
integrity_policy: z.enum(["fail", "record-and-continue"]).default("fail"),
diff --cc src/contracts/toolOutputSchemaGroups.ts
index 40aedf263,eb0fb000e..55225ffee
--- a/src/contracts/toolOutputSchemaGroups.ts
+++ b/src/contracts/toolOutputSchemaGroups.ts
@@@ -30,10 -30,9 +30,10 @@@ import
} from "../domain/nativeInspection.js";
import { artifactExtractionResultSchema } from "../domain/artifactGraph.js";
import { artifactInspectionResultSchema } from "../domain/artifactInspection.js";
- import { interfaceBuilderAnalysisSchema } from "../domain/interfaceBuilderGraph.js";
- import { dylibResolutionResultSchema } from "../domain/dylibResolution.js";
- import { keyedArchiveResultSchema } from "../domain/keyedArchive.js";
- import { appleAssetCatalogResultSchema } from "../domain/appleAssetCatalog.js";
+ import { interfaceBuilderAnalysisSchema } from "../domain/apple/interfaceBuilderGraph.js";
++import { dylibResolutionResultSchema } from "../domain/apple/dylibResolution.js";
+ import { keyedArchiveResultSchema } from "../domain/apple/keyedArchive.js";
+ import { appleAssetCatalogResultSchema } from "../domain/apple/appleAssetCatalog.js";
import {
managedArtifactInspectionSchema,
managedMemberInspectionSchema,
diff --cc src/domain/apple/dyldPaths.ts
index 765bb15d1,000000000..765bb15d1
mode 100644,000000..100644
--- a/src/domain/apple/dyldPaths.ts
+++ b/src/domain/apple/dyldPaths.ts
diff --cc src/domain/apple/dylibResolution.test.ts
index d778c6ff2,000000000..d778c6ff2
mode 100644,000000..100644
--- a/src/domain/apple/dylibResolution.test.ts
+++ b/src/domain/apple/dylibResolution.test.ts
diff --cc src/domain/apple/dylibResolution.ts
index 2d1235fd1,000000000..241a50be8
mode 100644,000000..100644
--- a/src/domain/apple/dylibResolution.ts
+++ b/src/domain/apple/dylibResolution.ts
@@@ -1,514 -1,0 +1,514 @@@
+import { z } from "zod";
+
+import {
+ compatibleSlice,
+ directoryOf,
+ expandPrefix,
+ joinPath,
+ resolveTreePath,
+ type Expansion,
+} from "./dyldPaths.js";
- import { digestSchema } from "./digests.js";
++import { digestSchema } from "../digests.js";
+import {
+ DYLIB_RESOLUTION_LIMITATIONS,
+ deriveFindings,
+} from "./dylibResolutionFindings.js";
+
+/** Normalized path below the analyzed root: no `.`/`..` or empty segments. */
+const ROOT_RELATIVE_PATH =
+ /^(?!\/)(?!(?:.*\/)?\.{1,2}(?:\/|$))(?!.*\/\/)(?!.*\/$)[^\\\0]+$/u;
+const rootRelativePathSchema = z.string().min(1).regex(ROOT_RELATIVE_PATH);
+
+/** Caller selection of process roots and one CPU slice. */
+export const dylibResolutionInputSchema = z.strictObject({
+ roots: z.array(rootRelativePathSchema).min(1).optional(),
+ architecture: z.enum(["arm64", "arm64e", "x86_64"]).optional(),
+});
+
+const dependencyCommandSchema = z.enum([
+ "LC_LOAD_DYLIB",
+ "LC_LOAD_WEAK_DYLIB",
+ "LC_REEXPORT_DYLIB",
+ "LC_LAZY_LOAD_DYLIB",
+ "LC_LOAD_UPWARD_DYLIB",
+]);
+
+const dependencySchema = z.strictObject({
+ command: dependencyCommandSchema,
+ encoding: z.enum(["dylib_command", "dylib_use_command"]),
+ install_name: z.string(),
+ weak: z.boolean(),
+ upward: z.boolean(),
+ reexport: z.boolean(),
+ delayed_init: z.boolean(),
+ current_version: z.string(),
+ compatibility_version: z.string(),
+});
+
+/** Observed dylib-loading facts of one Mach-O slice. */
+export const machoSliceSchema = z.strictObject({
+ architecture: z.string().min(1),
+ file_type: z.enum(["execute", "dylib", "bundle", "other"]),
+ install_name: z.string().nullable(),
+ dependencies: z.array(dependencySchema),
+ rpaths: z.array(z.string()),
+ dyld_environment: z.array(z.string()),
+ code_signature_present: z.boolean(),
+});
+
+export type MachoDependency = z.infer<typeof dependencySchema>;
+export type MachoSlice = z.infer<typeof machoSliceSchema>;
+
+/** Header parse of one file; malformed and unsupported images keep their reason. */
+export type MachoImageFacts =
+ | { readonly status: "parsed"; readonly slices: readonly MachoSlice[] }
+ | {
+ readonly status: "malformed" | "unsupported";
+ readonly reason: string;
+ }
+ | { readonly status: "not-mach-o" };
+
+/** One observed path below the analyzed root. Symlink targets are not followed by the view. */
+export type DylibTreeEntry =
+ | { readonly kind: "file" | "directory" }
+ | { readonly kind: "symlink"; readonly target: string };
+
+/** Read-only, lazily probed view of the analyzed root. Paths are root-relative. */
+export interface DylibTreeView {
+ entry(path: string): Promise<DylibTreeEntry | undefined>;
+ image(path: string): Promise<MachoImageFacts>;
+}
+
+const candidateSchema = z.strictObject({
+ path: z.string(),
+ source: z.enum([
+ "literal",
+ "executable_path",
+ "loader_path",
+ "rpath",
+ "already-loaded",
+ ]),
+ rpath: z.string().nullable(),
+ rpath_owner: z.string().nullable(),
+ outcome: z.enum([
+ "resolved",
+ "absent",
+ "not-mach-o",
+ "malformed",
+ "unsupported",
+ "architecture-missing",
+ "outside-target",
+ "escapes-target",
+ "undetermined",
+ ]),
+ resolved_path: z.string().nullable(),
+});
+
+const edgeSchema = z.strictObject({
+ root: z.string(),
+ architecture: z.string(),
+ loader: z.string(),
+ via: z.array(z.string()),
+ ...dependencySchema.shape,
+ candidates: z.array(candidateSchema),
+ resolution: z.strictObject({
+ status: z.enum(["resolved", "conditional", "unresolved", "undetermined"]),
+ image: z.string().nullable(),
+ }),
+ install_name_matches: z.boolean().nullable(),
+ /**
+ * The loader was reached through a conditional edge, so it might not load;
+ * this edge describes what happens only if it does.
+ */
+ loader_conditional: z.boolean(),
+});
+
+const findingSchema = z.strictObject({
+ kind: z.enum([
+ "required-load-unresolved",
+ "weak-load-unresolved",
+ "lazy-load-unresolved",
+ "earlier-rpath-candidate-absent",
+ "dyld-environment-present",
+ ]),
+ edge_index: z.number().int().nonnegative().nullable(),
+ image: z.string().nullable(),
+ basis: z.literal("derived"),
+ explanation: z.string().min(1),
+});
+
+const imageSchema = z.strictObject({
+ path: z.string(),
+ sha256: digestSchema,
+ parse_status: z.enum(["parsed", "malformed", "unsupported"]),
+ reason: z.string().nullable(),
+ slices: z.array(machoSliceSchema.omit({ dependencies: true })),
+});
+
+/** Static dyld load-path resolution for every selected process root. */
+export const dylibResolutionResultSchema = z.strictObject({
+ root_path: z.string(),
+ target_sha256: digestSchema,
+ roots: z.array(
+ z.strictObject({ image: z.string(), architecture: z.string() }),
+ ),
+ images: z.array(imageSchema),
+ edges: z.array(edgeSchema),
+ findings: z.array(findingSchema),
+ coverage: z.strictObject({
+ status: z.enum(["complete", "partial"]),
+ unparsed_images: z.array(z.string()),
+ roots_without_architecture: z.array(z.string()),
+ }),
+ limitations: z.array(z.string().min(1)),
+});
+
+export type DylibResolutionResult = z.infer<typeof dylibResolutionResultSchema>;
+type Candidate = z.infer<typeof candidateSchema>;
+export type DylibEdge = z.infer<typeof edgeSchema>;
+export type DylibFinding = z.infer<typeof findingSchema>;
+type Edge = DylibEdge;
+
+/** Result before the adapter adds file digests and the analyzed root. */
+export type DylibTrace = Omit<
+ DylibResolutionResult,
+ "root_path" | "target_sha256" | "images"
+> & {
+ readonly images: readonly (Omit<
+ DylibResolutionResult["images"][number],
+ "sha256"
+ > & { readonly sha256?: never })[];
+};
+
+interface LoadedImage {
+ readonly slice: MachoSlice;
+ /** Images from the process root to this image; the rpath stack, outermost first. */
+ readonly chain: readonly string[];
+ /** Some edge on the chain was conditional: an unknown earlier candidate may load instead. */
+ readonly conditional: boolean;
+}
+
+interface ProcessContext {
+ readonly view: DylibTreeView;
+ readonly root: string;
+ readonly architecture: string;
+ readonly executable: string | null;
+ readonly loaded: Map<string, LoadedImage>;
+ readonly byInstallName: Map<string, string>;
+ readonly images: Map<string, MachoImageFacts>;
+}
+
+interface CandidateTemplate {
+ readonly expansion: Expansion;
+ readonly source: Candidate["source"];
+ readonly rpath: string | null;
+ readonly rpathOwner: string | null;
+}
+
+const candidateTemplates = (
+ dependency: MachoDependency,
+ loader: string,
+ context: ProcessContext,
+): CandidateTemplate[] => {
+ const name = dependency.install_name;
+ if (!name.startsWith("@rpath/")) {
+ const source = name.startsWith("@executable_path")
+ ? "executable_path"
+ : name.startsWith("@loader_path")
+ ? "loader_path"
+ : "literal";
+ return [
+ {
+ expansion: expandPrefix(name, {
+ ownerDirectory: directoryOf(loader),
+ executable: context.executable,
+ }),
+ source,
+ rpath: null,
+ rpathOwner: null,
+ },
+ ];
+ }
+ const rest = name.slice("@rpath/".length);
+ const owners = [...(context.loaded.get(loader)?.chain ?? [loader])].reverse();
+ return owners.flatMap((owner) =>
+ (context.loaded.get(owner)?.slice.rpaths ?? []).map((rpath) => {
+ const base = expandPrefix(rpath, {
+ ownerDirectory: directoryOf(owner),
+ executable: context.executable,
+ });
+ const expansion: Expansion = {
+ scope: base.scope,
+ path:
+ base.scope === "outside"
+ ? `${base.path.replace(/\/+$/u, "")}/${rest}`
+ : joinPath(base.path, rest),
+ };
+ return { expansion, source: "rpath" as const, rpath, rpathOwner: owner };
+ }),
+ );
+};
+
+const evaluateCandidate = async (
+ template: CandidateTemplate,
+ context: ProcessContext,
+): Promise<Candidate> => {
+ const base = {
+ path: template.expansion.path,
+ source: template.source,
+ rpath: template.rpath,
+ rpath_owner: template.rpathOwner,
+ };
+ if (template.expansion.scope === "outside")
+ return { ...base, outcome: "outside-target", resolved_path: null };
+ if (template.expansion.scope === "undetermined")
+ return { ...base, outcome: "undetermined", resolved_path: null };
+ const lookup = await resolveTreePath(context.view, template.expansion.path);
+ if (lookup.kind === "escapes")
+ return { ...base, outcome: "escapes-target", resolved_path: null };
+ if (lookup.kind !== "file")
+ return { ...base, outcome: "absent", resolved_path: null };
+ const facts = await imageFacts(context, lookup.path);
+ const outcome: Candidate["outcome"] =
+ facts.status !== "parsed"
+ ? facts.status
+ : compatibleSlice(facts.slices, context.architecture) === undefined
+ ? "architecture-missing"
+ : "resolved";
+ return { ...base, outcome, resolved_path: lookup.path };
+};
+
+const imageFacts = async (
+ context: ProcessContext,
+ path: string,
+): Promise<MachoImageFacts> => {
+ const known = context.images.get(path);
+ if (known !== undefined) return known;
+ const facts = await context.view.image(path);
+ context.images.set(path, facts);
+ return facts;
+};
+
+const resolution = (candidates: readonly Candidate[]): Edge["resolution"] => {
+ let external = false;
+ for (const candidate of candidates) {
+ if (candidate.outcome === "resolved")
+ return {
+ status: external ? "conditional" : "resolved",
+ image: candidate.resolved_path,
+ };
+ // dyld might load these; REA cannot decide them from the analyzed root.
+ if (
+ candidate.outcome === "outside-target" ||
+ candidate.outcome === "escapes-target" ||
+ candidate.outcome === "unsupported" ||
+ candidate.outcome === "undetermined"
+ )
+ external = true;
+ }
+ return { status: external ? "undetermined" : "unresolved", image: null };
+};
+
+const resolveDependency = async (
+ dependency: MachoDependency,
+ loader: string,
+ context: ProcessContext,
+): Promise<Edge> => {
+ const current = context.loaded.get(loader);
+ const chain = current?.chain ?? [loader];
+ const loaded = context.byInstallName.get(dependency.install_name);
+ const candidates: Candidate[] = [];
+ if (loaded !== undefined)
+ candidates.push({
+ path: dependency.install_name,
+ source: "already-loaded",
+ rpath: null,
+ rpath_owner: null,
+ outcome: "resolved",
+ resolved_path: loaded,
+ });
+ else
+ for (const template of candidateTemplates(dependency, loader, context)) {
+ const candidate = await evaluateCandidate(template, context);
+ candidates.push(candidate);
+ // dyld stops at the first loadable candidate.
+ if (candidate.outcome === "resolved") break;
+ }
+ const searched = resolution(candidates);
+ // Reusing an image that itself loads only conditionally is conditional too.
+ const resolved: Edge["resolution"] =
+ loaded !== undefined &&
+ context.loaded.get(loaded)?.conditional === true &&
+ searched.status === "resolved"
+ ? { ...searched, status: "conditional" }
+ : searched;
+ const image =
+ resolved.image === null ? undefined : context.images.get(resolved.image);
+ const slice =
+ image?.status === "parsed"
+ ? compatibleSlice(image.slices, context.architecture)
+ : undefined;
+ return {
+ root: context.root,
+ architecture: context.architecture,
+ loader,
+ via: [...chain],
+ ...dependency,
+ candidates,
+ resolution: resolved,
+ install_name_matches:
+ slice === undefined || slice.install_name === null
+ ? null
+ : slice.install_name === dependency.install_name,
+ loader_conditional: current?.conditional ?? false,
+ };
+};
+
+/**
+ * Follow dyld4's dependents-first order: resolve every dependency of one
+ * image, then recurse into the images it newly loaded, in load-command order.
+ */
+const traceProcess = async (
+ context: ProcessContext,
+ rootSlice: MachoSlice,
+ signal?: AbortSignal,
+): Promise<Edge[]> => {
+ const edges: Edge[] = [];
+ context.loaded.set(context.root, {
+ slice: rootSlice,
+ chain: [context.root],
+ conditional: false,
+ });
+ if (rootSlice.install_name !== null)
+ context.byInstallName.set(rootSlice.install_name, context.root);
+ const pending = [context.root];
+ while (pending.length > 0) {
+ signal?.throwIfAborted();
+ const loader = pending.pop() ?? "";
+ const current = context.loaded.get(loader);
+ if (current === undefined) continue;
+ const created: string[] = [];
+ for (const dependency of current.slice.dependencies) {
+ const edge = await resolveDependency(dependency, loader, context);
+ edges.push(edge);
+ // dyld loads LC_LAZY_LOAD_DYLIB images on first use, not at launch.
+ if (dependency.command === "LC_LAZY_LOAD_DYLIB") continue;
+ const image = edge.resolution.image;
+ if (image === null || context.loaded.has(image)) continue;
+ const facts = context.images.get(image);
+ const slice =
+ facts?.status === "parsed"
+ ? compatibleSlice(facts.slices, context.architecture)
+ : undefined;
+ if (slice === undefined) continue;
+ context.loaded.set(image, {
+ slice,
+ chain: [...current.chain, image],
+ // dyld may load an unknown earlier candidate instead of this fallback.
+ conditional:
+ current.conditional || edge.resolution.status === "conditional",
+ });
+ if (
+ slice.install_name !== null &&
+ !context.byInstallName.has(slice.install_name)
+ )
+ context.byInstallName.set(slice.install_name, image);
+ created.push(image);
+ }
+ pending.push(...created.reverse());
+ }
+ return edges;
+};
+
+/** Trace dyld load paths from each process root through the analyzed root. */
+export const traceDylibLoading = async (
+ view: DylibTreeView,
+ request: {
+ readonly roots: readonly string[];
+ /** Mach-O files whose root role could not be classified because they did not parse. */
+ readonly unclassified?: readonly string[];
+ readonly architecture?: string;
+ readonly signal?: AbortSignal;
+ },
+): Promise<DylibTrace> => {
+ const images = new Map<string, MachoImageFacts>();
+ for (const path of request.unclassified ?? [])
+ images.set(path, await view.image(path));
+ const roots: DylibTrace["roots"][number][] = [];
+ const edges: Edge[] = [];
+ const withoutArchitecture: string[] = [];
+ for (const root of request.roots) {
+ const facts = await view.image(root);
+ images.set(root, facts);
+ if (facts.status !== "parsed") continue;
+ const slices = facts.slices.filter(
+ ({ architecture }) =>
+ request.architecture === undefined ||
+ architecture === request.architecture,
+ );
+ if (slices.length === 0) withoutArchitecture.push(root);
+ for (const slice of slices) {
+ roots.push({ image: root, architecture: slice.architecture });
+ edges.push(
+ ...(await traceProcess(
+ {
+ view,
+ root,
+ architecture: slice.architecture,
+ executable: slice.file_type === "execute" ? root : null,
+ loaded: new Map(),
+ byInstallName: new Map(),
+ images,
+ },
+ slice,
+ request.signal,
+ )),
+ );
+ }
+ }
+ const reported = [...images.entries()]
+ .filter(([, facts]) => facts.status !== "not-mach-o")
+ .sort(([left], [right]) => compare(left, right));
+ const unparsed = reported
+ .filter(([, facts]) => facts.status !== "parsed")
+ .map(([path]) => path);
+ return {
+ roots,
+ images: reported.map(([path, facts]) => ({
+ path,
+ parse_status:
+ facts.status === "not-mach-o" ? "unsupported" : facts.status,
+ reason:
+ facts.status === "parsed" || facts.status === "not-mach-o"
+ ? null
+ : facts.reason,
+ slices:
+ facts.status === "parsed" ? facts.slices.map(withoutDependencies) : [],
+ })),
+ edges,
+ findings: deriveFindings(edges, roots, images),
+ coverage: {
+ status:
+ unparsed.length === 0 && withoutArchitecture.length === 0
+ ? "complete"
+ : "partial",
+ unparsed_images: unparsed,
+ roots_without_architecture: withoutArchitecture,
+ },
+ limitations: DYLIB_RESOLUTION_LIMITATIONS,
+ };
+};
+
+const withoutDependencies = (
+ slice: MachoSlice,
+): Omit<MachoSlice, "dependencies"> => ({
+ architecture: slice.architecture,
+ file_type: slice.file_type,
+ install_name: slice.install_name,
+ rpaths: slice.rpaths,
+ dyld_environment: slice.dyld_environment,
+ code_signature_present: slice.code_signature_present,
+});
+
+const compare = (left: string, right: string): number =>
+ left < right ? -1 : left > right ? 1 : 0;
diff --cc src/domain/apple/dylibResolutionFindings.ts
index 069323eb1,000000000..069323eb1
mode 100644,000000..100644
--- a/src/domain/apple/dylibResolutionFindings.ts
+++ b/src/domain/apple/dylibResolutionFindings.ts
diff --cc tests/boundary/cli/dylibResolutionCli.test.ts
index db1646023,000000000..1911d8551
mode 100644,000000..100644
--- a/tests/boundary/cli/dylibResolutionCli.test.ts
+++ b/tests/boundary/cli/dylibResolutionCli.test.ts
@@@ -1,244 -1,0 +1,244 @@@
+import { chmod, mkdir, symlink, writeFile } from "node:fs/promises";
+import { dirname, join } from "node:path";
+
+import { describe, expect } from "vitest";
+
+import {
+ FILE_TYPE,
+ LC,
+ dylibCommand,
+ machoImage,
+ rpathCommand,
- } from "../../../src/artifacts/MachoImage.fixture.js";
- import { dylibResolutionResultSchema } from "../../../src/domain/dylibResolution.js";
++} from "../../../src/artifacts/apple/MachoImage.fixture.js";
++import { dylibResolutionResultSchema } from "../../../src/domain/apple/dylibResolution.js";
+import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
+import { cliTest } from "../../support/cli/cliFixture.js";
+
+const ENVIRONMENT = { REA_LOG_LEVEL: "silent", REA_ANALYSIS_PROVIDER: "auto" };
+
+const writeFiles = async (
+ root: string,
+ files: Readonly<Record<string, string | Uint8Array>>,
+): Promise<void> => {
+ for (const [path, content] of Object.entries(files)) {
+ await mkdir(dirname(join(root, path)), { recursive: true });
+ await writeFile(join(root, path), content);
+ }
+};
+
+const fixtureApp = async (): Promise<string> => {
+ const app = join(
+ await createTestTempDirectory("rea-dylib-cli-"),
+ "Fixture.app",
+ );
+ await writeFiles(app, {
+ "Contents/Info.plist":
+ "<plist><dict><key>CFBundleExecutable</key><string>App</string></dict></plist>",
+ "Contents/MacOS/App": machoImage({
+ commands: [
+ rpathCommand("@executable_path/../Frameworks"),
+ dylibCommand(LC.LOAD_DYLIB, "@rpath/libcore.dylib"),
+ dylibCommand(LC.LOAD_WEAK_DYLIB, "@rpath/libgone.dylib"),
+ ],
+ }),
+ "Contents/Frameworks/libcore.dylib": machoImage({
+ fileType: FILE_TYPE.dylib,
+ commands: [dylibCommand(LC.ID_DYLIB, "@rpath/libcore.dylib")],
+ }),
+ "Contents/Helpers/tool": machoImage({
+ commands: [dylibCommand(LC.LOAD_DYLIB, "@loader_path/libnone.dylib")],
+ }),
+ });
+ return app;
+};
+
+const withBrokenHelper = async (app: string): Promise<void> => {
+ const broken = machoImage({ commands: [rpathCommand("x")] });
+ // cmdsize 0 makes the command table unreadable.
+ new DataView(broken.buffer).setUint32(32 + 4, 0, true);
+ await writeFiles(app, { "Contents/Helpers/broken": broken });
+};
+
+describe("trace-dylib-resolution CLI", () => {
+ cliTest("traces every executable root of an app bundle", async ({ cli }) => {
+ const app = await fixtureApp();
+ const result = await cli.run({
+ arguments: ["trace-dylib-resolution", app, "--json"],
+ environment: ENVIRONMENT,
+ });
+ expect(result.exitCode, JSON.stringify(result.json)).toBe(0);
+ const trace = dylibResolutionResultSchema.parse(
+ (result.json as { normalized_result: unknown }).normalized_result,
+ );
+ expect(trace.root_path).toBe(app);
+ expect(trace.roots.map(({ image }) => image)).toEqual([
+ "Contents/Helpers/tool",
+ "Contents/MacOS/App",
+ ]);
+ expect(
+ trace.edges.map(({ loader, install_name: name, resolution }) => [
+ loader,
+ name,
+ resolution.status,
+ resolution.image,
+ ]),
+ ).toEqual([
+ [
+ "Contents/Helpers/tool",
+ "@loader_path/libnone.dylib",
+ "unresolved",
+ null,
+ ],
+ [
+ "Contents/MacOS/App",
+ "@rpath/libcore.dylib",
+ "resolved",
+ "Contents/Frameworks/libcore.dylib",
+ ],
+ ["Contents/MacOS/App", "@rpath/libgone.dylib", "unresolved", null],
+ ]);
+ expect(trace.findings.map(({ kind }) => kind)).toEqual([
+ "required-load-unresolved",
+ "weak-load-unresolved",
+ ]);
+ expect(
+ trace.images.every(({ sha256 }) => /^[0-9a-f]{64}$/u.test(sha256)),
+ ).toBe(true);
+ });
+
+ cliTest(
+ "narrows roots and architecture, and rejects escaping roots",
+ async ({ cli }) => {
+ const app = await fixtureApp();
+ const narrowed = await cli.run({
+ arguments: [
+ "trace-dylib-resolution",
+ app,
+ "--root",
+ "Contents/MacOS/App",
+ "--architecture",
+ "arm64",
+ "--json",
+ ],
+ environment: ENVIRONMENT,
+ });
+ expect(narrowed.exitCode).toBe(0);
+ expect(
+ (narrowed.json as { normalized_result: { roots: unknown } })
+ .normalized_result.roots,
+ ).toEqual([{ image: "Contents/MacOS/App", architecture: "arm64" }]);
+ // A root below a symlinked directory that points outside the bundle.
+ const outside = await createTestTempDirectory("rea-dylib-outside-");
+ await writeFiles(outside, { Tool: machoImage({}) });
+ await symlink(outside, join(app, "Contents/Linked"));
+ for (const root of [
+ "../outside",
+ "Contents/Info.plist",
+ "Contents/Linked/Tool",
+ ]) {
+ const rejected = await cli.run({
+ arguments: ["trace-dylib-resolution", app, "--root", root, "--json"],
+ environment: ENVIRONMENT,
+ });
+ expect(rejected.exitCode).toBe(1);
+ expect(rejected.json).toMatchObject({ error: "Analysis failed" });
+ }
+ },
+ );
+
+ cliTest(
+ "resolves a standalone Mach-O against its own directory",
+ async ({ cli }) => {
+ const directory = await createTestTempDirectory("rea-dylib-standalone-");
+ await writeFiles(directory, {
+ tool: machoImage({
+ commands: [
+ dylibCommand(LC.LOAD_DYLIB, "@loader_path/lib/libhelper.dylib"),
+ dylibCommand(LC.LOAD_DYLIB, "@loader_path/../escape.dylib"),
+ ],
+ }),
+ "lib/libhelper.dylib": machoImage({ fileType: FILE_TYPE.dylib }),
+ "unrelated.txt": "not traversed",
+ });
+ const result = await cli.run({
+ arguments: [
+ "trace-dylib-resolution",
+ join(directory, "tool"),
+ "--json",
+ ],
+ environment: ENVIRONMENT,
+ });
+ expect(result.exitCode, JSON.stringify(result.json)).toBe(0);
+ const trace = dylibResolutionResultSchema.parse(
+ (result.json as { normalized_result: unknown }).normalized_result,
+ );
+ expect(trace.roots).toEqual([{ image: "tool", architecture: "arm64" }]);
+ expect(trace.edges.map(({ resolution }) => resolution)).toEqual([
+ { status: "resolved", image: "lib/libhelper.dylib" },
+ { status: "undetermined", image: null },
+ ]);
+ },
+ );
+
+ cliTest(
+ "reports unparsed Mach-O files found while enumerating roots",
+ async ({ cli }) => {
+ const app = await fixtureApp();
+ await withBrokenHelper(app);
+ const result = await cli.run({
+ arguments: ["trace-dylib-resolution", app, "--json"],
+ environment: ENVIRONMENT,
+ });
+ expect(result.exitCode, JSON.stringify(result.json)).toBe(0);
+ const trace = dylibResolutionResultSchema.parse(
+ (result.json as { normalized_result: unknown }).normalized_result,
+ );
+ expect(trace.coverage).toMatchObject({
+ status: "partial",
+ unparsed_images: ["Contents/Helpers/broken"],
+ });
+ },
+ );
+});
+
+describe.skipIf(process.getuid?.() === 0)(
+ "trace-dylib-resolution permissions",
+ () => {
+ cliTest(
+ "reports an unreadable dependency as a permission failure",
+ async ({ cli }) => {
+ const directory = await createTestTempDirectory("rea-dylib-denied-");
+ await writeFiles(directory, {
+ tool: machoImage({
+ commands: [
+ dylibCommand(LC.LOAD_DYLIB, "@loader_path/libsecret.dylib"),
+ ],
+ }),
+ "libsecret.dylib": machoImage({ fileType: FILE_TYPE.dylib }),
+ });
+ await chmod(join(directory, "libsecret.dylib"), 0o000);
+ try {
+ const result = await cli.run({
+ arguments: [
+ "trace-dylib-resolution",
+ join(directory, "tool"),
+ "--json",
+ ],
+ environment: ENVIRONMENT,
+ });
+ expect(result.exitCode).toBe(1);
+ expect(result.json).toMatchObject({
+ details: {
+ reason: "unavailable",
+ detail: expect.stringContaining(
+ "Permission denied (EACCES) reading libsecret.dylib",
+ ),
+ },
+ });
+ } finally {
+ await chmod(join(directory, "libsecret.dylib"), 0o644);
+ }
+ },
+ );
+ },
+);
diff --cc tests/boundary/mcp/dylibResolutionMcp.test.ts
index b0639047e,000000000..2a2c18f06
mode 100644,000000..100644
--- a/tests/boundary/mcp/dylibResolutionMcp.test.ts
+++ b/tests/boundary/mcp/dylibResolutionMcp.test.ts
@@@ -1,161 -1,0 +1,161 @@@
+import { mkdir, writeFile } from "node:fs/promises";
+import { join } from "node:path";
+
+import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
+import { expect, it } from "vitest";
+import { z } from "zod";
+
+import { ArtifactProvider } from "../../../src/artifacts/ArtifactProvider.js";
+import {
+ FILE_TYPE,
+ LC,
+ dylibCommand,
+ machoImage,
+ rpathCommand,
- } from "../../../src/artifacts/MachoImage.fixture.js";
- import { dylibResolutionResultSchema } from "../../../src/domain/dylibResolution.js";
++} from "../../../src/artifacts/apple/MachoImage.fixture.js";
++import { dylibResolutionResultSchema } from "../../../src/domain/apple/dylibResolution.js";
+import { createServer } from "../../../src/server/createServer.js";
+import { createTestBinarySession } from "../../fixtures/binarySession.js";
+import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
+
+const withClient = async (
+ verify: (client: Client) => Promise<void>,
+): Promise<void> => {
+ const session = createTestBinarySession(new ArtifactProvider());
+ const server = createServer(session, session);
+ const client = new Client({ name: "dylib-mcp-test", version: "1" });
+ const [clientTransport, serverTransport] =
+ InMemoryTransport.createLinkedPair();
+ try {
+ await server.connect(serverTransport);
+ await client.connect(clientTransport);
+ await verify(client);
+ } finally {
+ await client.close();
+ await server.close();
+ }
+};
+
+const structuredResult = (value: unknown): unknown =>
+ z.object({ result: z.unknown() }).parse(value).result;
+
+it("traces dylib resolution for an opened app bundle and rejects a changed target", async () => {
+ const app = join(
+ await createTestTempDirectory("rea-dylib-mcp-"),
+ "Fixture.app",
+ );
+ await mkdir(join(app, "Contents/MacOS"), { recursive: true });
+ await mkdir(join(app, "Contents/Frameworks"), { recursive: true });
+ await writeFile(
+ join(app, "Contents/Info.plist"),
+ "<plist><dict><key>CFBundleExecutable</key><string>App</string></dict></plist>",
+ );
+ const executable = join(app, "Contents/MacOS/App");
+ await writeFile(
+ executable,
+ machoImage({
+ commands: [
+ rpathCommand("@executable_path/../Frameworks"),
+ dylibCommand(LC.LOAD_DYLIB, "@rpath/libcore.dylib"),
+ ],
+ }),
+ );
+ await writeFile(
+ join(app, "Contents/Frameworks/libcore.dylib"),
+ machoImage({ fileType: FILE_TYPE.dylib }),
+ );
+ await withClient(async (client) => {
+ const opened = await client.callTool({
+ name: "open_binary",
+ arguments: { path: app },
+ });
+ expect(opened.isError, JSON.stringify(opened)).not.toBe(true);
+ const called = await client.callTool({
+ name: "trace_dylib_resolution",
+ arguments: {},
+ });
+ expect(called.isError, JSON.stringify(called.structuredContent)).not.toBe(
+ true,
+ );
+ const trace = dylibResolutionResultSchema.parse(
+ structuredResult(called.structuredContent),
+ );
+ expect(trace.edges).toEqual([
+ expect.objectContaining({
+ install_name: "@rpath/libcore.dylib",
+ resolution: {
+ status: "resolved",
+ image: "Contents/Frameworks/libcore.dylib",
+ },
+ }),
+ ]);
+ const escaping = await client.callTool({
+ name: "trace_dylib_resolution",
+ arguments: { roots: ["Contents/../../outside"] },
+ });
+ expect(escaping.isError).toBe(true);
+
+ await writeFile(executable, machoImage({}));
+ const changed = await client.callTool({
+ name: "trace_dylib_resolution",
+ arguments: {},
+ });
+ expect(changed.isError).toBe(true);
+ expect(JSON.stringify(changed.structuredContent)).toContain("integrity");
+ });
+});
+
+it("rejects targets that are not Mach-O", async () => {
+ const directory = await createTestTempDirectory("rea-dylib-mcp-plist-");
+ const path = join(directory, "Info.plist");
+ await writeFile(path, "<plist><dict/></plist>");
+ await withClient(async (client) => {
+ const opened = await client.callTool({
+ name: "open_binary",
+ arguments: { path },
+ });
+ expect(opened.isError).not.toBe(true);
+ const called = await client.callTool({
+ name: "trace_dylib_resolution",
+ arguments: {},
+ });
+ expect(called.isError).toBe(true);
+ expect(JSON.stringify(called.structuredContent)).toContain("unavailable");
+ });
+});
+
+it("traces a standalone Mach-O file whose name ends in .app", async () => {
+ const directory = await createTestTempDirectory("rea-dylib-mcp-file-");
+ await writeFile(
+ join(directory, "Tool.app"),
+ machoImage({
+ commands: [dylibCommand(LC.LOAD_DYLIB, "@loader_path/libcore.dylib")],
+ }),
+ );
+ await writeFile(
+ join(directory, "libcore.dylib"),
+ machoImage({ fileType: FILE_TYPE.dylib }),
+ );
+ await withClient(async (client) => {
+ const opened = await client.callTool({
+ name: "open_binary",
+ arguments: { path: join(directory, "Tool.app") },
+ });
+ expect(opened.isError, JSON.stringify(opened)).not.toBe(true);
+ const called = await client.callTool({
+ name: "trace_dylib_resolution",
+ arguments: {},
+ });
+ expect(called.isError, JSON.stringify(called.structuredContent)).not.toBe(
+ true,
+ );
+ const trace = dylibResolutionResultSchema.parse(
+ structuredResult(called.structuredContent),
+ );
+ expect(trace.edges).toEqual([
+ expect.objectContaining({
+ resolution: { status: "resolved", image: "libcore.dylib" },
+ }),
+ ]);
+ });
+});