feat(apple): inspect dyld shared caches and resolve system paths

macOS 11 and later ship system libraries only inside the dyld shared
cache. trace_dylib_resolution therefore left every /usr/lib and /System
load undetermined, and REA had no way to see what a cache contains.

inspect_dyld_shared_cache (CLI inspect-dyld-shared-cache) reads a cache
file set selected by path, without an open target. Its pure TypeScript
reader parses modern and legacy dyld_cache_header layouts and reports:
- UUID, architecture, platform, OS version, Mac Catalyst alternate,
  cache type, shared region, max slide;
- every VM mapping;
- each subcache by file suffix, checked by UUID. A missing or
  mismatched subcache makes coverage partial;
- the complete image list.
For each requested install path it reads that image's load commands
through the cache mappings with the existing Mach-O reader.

trace_dylib_resolution accepts an optional shared_cache. Absolute
candidates found in a cache that serves the process's CPU family resolve
with the new outcome and status `shared-cache`. That status also takes
precedence over later in-bundle fallbacks such as a back-deployed
libswiftCore. The result names the cache UUID and OS version it used.

verify:dyld-shared-cache checks every image in the host cache (3,649 on
macOS 26.6), with dependencies and their re-export, weak, upward and
delay-init attributes, against `dyld_info -all_dyld_cache
-linked_dylibs`. It also checks CLI/MCP parity, and that each
shared-cache edge in the fixture trace is a library dyld actually loads.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Kaoru0822
2026-10-07 11:43:15 +00:00
co-authored by Claude Opus 5.5
parent a0ec3e2016
commit ade11fa02d
39 changed files with 1911 additions and 176 deletions
@@ -10,6 +10,7 @@ import {
machoImage,
rpathCommand,
} from "../../../src/artifacts/MachoImage.fixture.js";
import { dyldCacheFixture } from "../../../src/artifacts/DyldSharedCache.fixture.js";
import { dylibResolutionResultSchema } from "../../../src/domain/dylibResolution.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { cliTest } from "../../support/cli/cliFixture.js";
@@ -137,7 +138,9 @@ describe("trace-dylib-resolution CLI", () => {
}
},
);
});
describe("trace-dylib-resolution CLI inputs", () => {
cliTest(
"resolves a standalone Mach-O against its own directory",
async ({ cli }) => {
@@ -191,4 +194,47 @@ describe("trace-dylib-resolution CLI", () => {
});
},
);
cliTest(
"answers system install paths from a supplied shared cache",
async ({ cli }) => {
const directory = await createTestTempDirectory("rea-dylib-cache-");
await writeFiles(directory, {
tool: machoImage({
commands: [
dylibCommand(LC.LOAD_DYLIB, "/usr/lib/libSystem.B.dylib"),
dylibCommand(LC.LOAD_DYLIB, "/usr/lib/libnotcached.dylib"),
],
}),
dyld_shared_cache_arm64e: dyldCacheFixture([
{
path: "/usr/lib/libSystem.B.dylib",
bytes: machoImage({ fileType: FILE_TYPE.dylib }),
},
]).main,
});
const result = await cli.run({
arguments: [
"trace-dylib-resolution",
join(directory, "tool"),
"--shared-cache",
join(directory, "dyld_shared_cache_arm64e"),
"--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.shared_cache).toMatchObject({
architecture: "arm64e",
os_version: "26.6.0",
});
expect(trace.edges.map(({ resolution }) => resolution.status)).toEqual([
"shared-cache",
"undetermined",
]);
},
);
});
+1 -1
View File
@@ -175,7 +175,7 @@ describe("canonical product catalog", () => {
expect(
catalog.providers.find(({ id }) => id === APPLE_APPLICATION_PROVIDER.id)
?.capabilities,
).toEqual(["project_apple_application_graph"]);
).toEqual(["inspect_dyld_shared_cache", "project_apple_application_graph"]);
expect(
catalog.providers.find(({ id }) => id === MANAGED_WORKFLOW_PROVIDER.id)
?.capabilities,
@@ -0,0 +1,170 @@
import { rm, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import {
dyldCacheFixture,
type CacheFixture,
} from "../../../src/artifacts/DyldSharedCache.fixture.js";
import {
FILE_TYPE,
LC,
dylibCommand,
dylibUseCommand,
machoImage,
} from "../../../src/artifacts/MachoImage.fixture.js";
import {
inspectDyldSharedCache,
inspectDyldSharedCacheEvidence,
} from "../../../src/application/DyldSharedCacheService.js";
import { dyldSharedCacheResultSchema } from "../../../src/domain/dyldSharedCache.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
const dylib = (installName: string, dependencies: readonly Uint8Array[] = []) =>
machoImage({
fileType: FILE_TYPE.dylib,
commands: [dylibCommand(LC.ID_DYLIB, installName), ...dependencies],
});
const writeCache = async (fixture: CacheFixture): Promise<string> => {
const directory = await createTestTempDirectory("rea-dyld-cache-");
const path = join(directory, "dyld_shared_cache_arm64e");
await writeFile(path, fixture.main);
for (const { suffix, bytes } of fixture.subcaches)
await writeFile(`${path}${suffix}`, bytes);
return path;
};
const IMAGES = [
{
path: "/usr/lib/libSystem.B.dylib",
bytes: dylib("/usr/lib/libSystem.B.dylib", [
dylibCommand(LC.REEXPORT_DYLIB, "/usr/lib/system/libcache.dylib"),
]),
},
{
path: "/usr/lib/swift/libswiftCore.dylib",
bytes: dylib("/usr/lib/swift/libswiftCore.dylib", [
dylibUseCommand(LC.LOAD_DYLIB, "/usr/lib/libSystem.B.dylib", 0x4 | 0x8),
]),
inSubcache: true,
},
];
describe("dyld shared cache inspection", () => {
it("reads the header, subcaches, image list and cached load commands", async () => {
const path = await writeCache(dyldCacheFixture(IMAGES));
const result = await inspectDyldSharedCache({
cache_path: path,
images: ["/usr/lib/swift/libswiftCore.dylib", "/usr/lib/missing.dylib"],
});
expect(result.ok).toBe(true);
if (!result.ok) return;
const cache = dyldSharedCacheResultSchema.parse(result.value);
expect(cache).toMatchObject({
architecture: "arm64e",
platform: { id: 1, name: "macos" },
os_version: "26.6.0",
shared_region: { start: "0x180000000", size: "0x20000000" },
images_total: 2,
coverage: { status: "complete", unreadable_subcaches: [] },
});
expect(cache.subcaches).toEqual([
expect.objectContaining({
suffix: ".01",
status: "present",
vm_offset: "0x10000000",
}),
]);
expect(cache.images.map(({ path: image }) => image)).toEqual(
IMAGES.map(({ path: image }) => image),
);
const [swift, missing] = cache.inspected_images;
expect(swift).toMatchObject({ status: "parsed", file: ".01" });
expect(swift?.slices[0]?.dependencies).toEqual([
expect.objectContaining({
install_name: "/usr/lib/libSystem.B.dylib",
encoding: "dylib_use_command",
upward: true,
delayed_init: true,
}),
]);
expect(missing).toEqual({
path: "/usr/lib/missing.dylib",
status: "absent",
address: null,
file: null,
reason: null,
slices: [],
});
});
it("reports missing and mismatched subcaches as partial coverage", async () => {
const mismatched = await writeCache(
dyldCacheFixture(IMAGES, { subcacheUuidSeed: 9 }),
);
const result = await inspectDyldSharedCache({
cache_path: mismatched,
images: ["/usr/lib/swift/libswiftCore.dylib"],
});
expect(result.ok && result.value).toMatchObject({
subcaches: [{ suffix: ".01", status: "uuid-mismatch" }],
inspected_images: [{ status: "unmapped" }],
coverage: { status: "partial", unreadable_subcaches: [".01"] },
});
const missing = await writeCache(dyldCacheFixture(IMAGES));
await rm(`${missing}.01`);
const without = await inspectDyldSharedCache({ cache_path: missing });
expect(without.ok && without.value.subcaches[0]).toMatchObject({
status: "missing",
observed_uuid: null,
});
});
it("reads legacy single-file headers without later fields", async () => {
const path = await writeCache(
dyldCacheFixture(IMAGES.slice(0, 1), { legacy: true }),
);
const result = await inspectDyldSharedCache({
cache_path: path,
images: ["/usr/lib/libSystem.B.dylib"],
});
expect(result.ok && result.value).toMatchObject({
platform: null,
os_version: null,
subcaches: [],
images_total: 1,
inspected_images: [{ status: "parsed" }],
});
});
it("separates malformed input, missing files and non-cache files", async () => {
expect(await inspectDyldSharedCache({ images: [] })).toMatchObject({
ok: false,
error: { _tag: "AnalysisInputError" },
});
const directory = await createTestTempDirectory("rea-dyld-cache-bad-");
expect(
await inspectDyldSharedCache({ cache_path: join(directory, "absent") }),
).toMatchObject({ ok: false, error: { reason: "path" } });
const notCache = join(directory, "not-a-cache");
await writeFile(notCache, Buffer.alloc(64, 0x41));
expect(
await inspectDyldSharedCache({ cache_path: notCache }),
).toMatchObject({
ok: false,
error: { reason: "format" },
});
});
it("wraps the observation as Evidence about the main cache file", async () => {
const path = await writeCache(dyldCacheFixture(IMAGES));
const evidence = await inspectDyldSharedCacheEvidence({ cache_path: path });
expect(evidence.ok && evidence.value).toMatchObject({
operation: "inspect_dyld_shared_cache",
subject: { local_path: path, format: "file" },
confidence: "observed",
});
});
});
@@ -0,0 +1,75 @@
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { afterEach, expect, it } from "vitest";
import { z } from "zod";
import { dyldCacheFixture } from "../../../src/artifacts/DyldSharedCache.fixture.js";
import {
FILE_TYPE,
LC,
dylibCommand,
machoImage,
} from "../../../src/artifacts/MachoImage.fixture.js";
import { dyldSharedCacheResultSchema } from "../../../src/domain/dyldSharedCache.js";
import { createServer } from "../../../src/server/createServer.js";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
const resources: Array<{ close(): Promise<unknown> }> = [];
afterEach(async () => {
for (const resource of resources.splice(0)) await resource.close();
});
it("inspects a dyld shared cache through MCP without a target", async () => {
const session = createTestBinarySession(() => {
throw new Error("shared cache inspection must not launch a provider");
});
const server = createServer(session, session);
const client = new Client({ name: "dyld-shared-cache-test", version: "1" });
resources.push(client, server, session);
const [a, b] = InMemoryTransport.createLinkedPair();
await server.connect(b);
await client.connect(a);
const directory = await createTestTempDirectory("rea-dyld-cache-mcp-");
const path = join(directory, "dyld_shared_cache_arm64e");
const fixture = dyldCacheFixture([
{
path: "/usr/lib/libSystem.B.dylib",
bytes: machoImage({
fileType: FILE_TYPE.dylib,
commands: [dylibCommand(LC.ID_DYLIB, "/usr/lib/libSystem.B.dylib")],
}),
},
]);
await writeFile(path, fixture.main);
const tools = await client.listTools();
expect(tools.tools.map(({ name }) => name)).toContain(
"inspect_dyld_shared_cache",
);
const called = await client.callTool({
name: "inspect_dyld_shared_cache",
arguments: { cache_path: path, images: ["/usr/lib/libSystem.B.dylib"] },
});
expect(called.isError, JSON.stringify(called.structuredContent)).not.toBe(
true,
);
const result = dyldSharedCacheResultSchema.parse(
z.object({ result: z.unknown() }).parse(called.structuredContent).result,
);
expect(result).toMatchObject({
architecture: "arm64e",
images_total: 1,
inspected_images: [
{ path: "/usr/lib/libSystem.B.dylib", status: "parsed" },
],
});
const missing = await client.callTool({
name: "inspect_dyld_shared_cache",
arguments: { cache_path: join(directory, "absent") },
});
expect(missing.isError).toBe(true);
});