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
+197
View File
@@ -0,0 +1,197 @@
import { createHash } from "node:crypto";
import { open } from "node:fs/promises";
import { resolve } from "node:path";
import { ArtifactReaderFailure } from "../artifacts/ArtifactReader.js";
import { DyldSharedCache } from "../artifacts/DyldSharedCacheReader.js";
import { AnalysisInputError } from "../domain/analysisErrorCore.js";
import type { AnalysisError } from "../domain/analysisErrorBase.js";
import { ArtifactOperationError } from "../domain/artifactOperationError.js";
import {
DYLD_SHARED_CACHE_LIMITATIONS,
dyldSharedCacheResultSchema,
inspectDyldSharedCacheInputSchema,
type DyldSharedCacheResult,
type InspectedCacheImage,
} from "../domain/dyldSharedCache.js";
import { createEvidence, type Evidence } from "../domain/evidence.js";
import { jsonValueSchema } from "../domain/jsonValue.js";
import { err, ok, type Result } from "../domain/result.js";
import { APPLE_APPLICATION_PROVIDER } from "./InvestigationProviders.js";
const OPERATION = "inspect_dyld_shared_cache" as const;
const HASH_CHUNK_BYTES = 1024 * 1024;
const sha256File = async (
path: string,
signal?: AbortSignal,
): Promise<string> => {
const handle = await open(path, "r");
try {
const hash = createHash("sha256");
const buffer = new Uint8Array(HASH_CHUNK_BYTES);
for (;;) {
signal?.throwIfAborted();
const { bytesRead } = await handle.read(buffer, 0, buffer.length, null);
if (bytesRead === 0) break;
hash.update(buffer.subarray(0, bytesRead));
}
return hash.digest("hex");
} finally {
await handle.close();
}
};
/** Read one requested image through the cache, keeping absence explicit. */
const inspectImage = async (
cache: DyldSharedCache,
path: string,
): Promise<InspectedCacheImage> => {
const image = cache.find(path);
const base = { path, reason: null, slices: [] };
if (image === undefined)
return { ...base, status: "absent", address: null, file: null };
const address = `0x${image.address.toString(16)}`;
const read = await cache.imageFacts(path);
if (read === undefined)
return {
...base,
status: "unmapped",
address,
file: null,
reason: "The image address lies in no readable cache mapping.",
};
const { facts, file } = read;
if (facts.status === "parsed")
return {
...base,
status: "parsed",
address,
file,
slices: [...facts.slices],
};
return {
...base,
status: facts.status === "not-mach-o" ? "malformed" : facts.status,
address,
file,
reason:
facts.status === "not-mach-o"
? "The cached image is not a Mach-O image."
: facts.reason,
};
};
const failure = (cause: unknown): AnalysisError => {
if (cause instanceof ArtifactReaderFailure)
return new ArtifactOperationError(
OPERATION,
cause.reason,
undefined,
cause.message,
);
if (cause instanceof Error && "code" in cause) {
if (cause.code === "ENOENT" || cause.code === "ENOTDIR")
return new ArtifactOperationError(
OPERATION,
"path",
undefined,
"The cache file does not exist.",
);
if (cause.code === "EACCES" || cause.code === "EPERM")
return new ArtifactOperationError(
OPERATION,
"unavailable",
undefined,
"The cache file is not readable.",
);
}
if (cause instanceof Error && cause.name === "AbortError")
return new ArtifactOperationError(OPERATION, "cancelled");
return new ArtifactOperationError(OPERATION, "io");
};
/** Inspect a dyld shared cache file set selected by path. */
export const inspectDyldSharedCache = async (
rawInput: unknown,
signal?: AbortSignal,
): Promise<Result<DyldSharedCacheResult, AnalysisError>> => {
const parsed = inspectDyldSharedCacheInputSchema.safeParse(rawInput);
if (!parsed.success)
return err(new AnalysisInputError(OPERATION, { cause: parsed.error }));
const cachePath = resolve(parsed.data.cache_path);
let cache: DyldSharedCache | undefined;
try {
cache = await DyldSharedCache.open(cachePath, signal);
const inspected: InspectedCacheImage[] = [];
for (const path of parsed.data.images ?? []) {
signal?.throwIfAborted();
inspected.push(await inspectImage(cache, path));
}
const unreadable = cache.header.subcaches
.filter(({ status }) => status !== "present")
.map(({ suffix }) => suffix);
return ok(
dyldSharedCacheResultSchema.parse({
cache_path: cachePath,
main_file_sha256: await sha256File(cachePath, signal),
...cache.header,
images_total: cache.images.length,
images: cache.images.map(({ path, address }) => ({
path,
address: `0x${address.toString(16)}`,
})),
inspected_images: inspected,
coverage: {
status: unreadable.length === 0 ? "complete" : "partial",
unreadable_subcaches: unreadable,
},
limitations: [
...DYLD_SHARED_CACHE_LIMITATIONS,
...(unreadable.length === 0
? []
: [
`Subcaches ${unreadable.join(", ")} are missing or do not match the main cache UUID; images mapped there are unmapped.`,
]),
],
}),
);
} catch (cause: unknown) {
return err(failure(cause));
} finally {
await cache?.close();
}
};
/** Inspect a dyld shared cache and wrap the observation as Evidence. */
export const inspectDyldSharedCacheEvidence = async (
rawInput: unknown,
signal?: AbortSignal,
): Promise<Result<Evidence, AnalysisError>> => {
const inspected = await inspectDyldSharedCache(rawInput, signal);
if (!inspected.ok) return inspected;
const result = inspected.value;
return ok(
createEvidence(
{
path: result.cache_path,
sha256: result.main_file_sha256,
format: "file",
},
APPLE_APPLICATION_PROVIDER,
{
operation: OPERATION,
parameters: {
cache_path: result.cache_path,
images: result.inspected_images.map(({ path }) => path),
},
result: jsonValueSchema.parse(result),
rawResult: null,
confidence: "observed",
authority: "shipped-artifact",
environment: null,
limitations: result.limitations,
},
),
);
};
+138
View File
@@ -0,0 +1,138 @@
/** Synthetic dyld shared caches laid out field by field for tests. */
export interface CacheFixtureImage {
readonly path: string;
readonly bytes: Uint8Array;
/** Place the image in the `.01` subcache instead of the main file. */
readonly inSubcache?: boolean;
}
export interface CacheFixture {
readonly main: Uint8Array;
readonly subcaches: readonly {
readonly suffix: string;
readonly bytes: Uint8Array;
}[];
}
const MAIN_BASE = 0x180000000n;
const SUB_BASE = 0x190000000n;
const MODERN_HEADER = 0x228;
const LEGACY_HEADER = 0x98;
const uuid = (seed: number): Buffer =>
Buffer.from(
Array.from({ length: 16 }, (_, index) => (seed * 31 + index) & 0xff),
);
const align = (value: number): number => Math.ceil(value / 0x1000) * 0x1000;
const writeHeader = (
buffer: Buffer,
options: {
readonly headerSize: number;
readonly uuidSeed: number;
readonly architecture: string;
},
): void => {
buffer.write(`dyld_v1 ${options.architecture}`.padEnd(15, " "), 0, "latin1");
buffer.writeUInt32LE(options.headerSize, 0x10);
buffer.writeUInt32LE(1, 0x14);
uuid(options.uuidSeed).copy(buffer, 0x58);
};
const writeMapping = (
buffer: Buffer,
at: number,
address: bigint,
size: number,
): void => {
buffer.writeBigUInt64LE(address, at);
buffer.writeBigUInt64LE(BigInt(size), at + 8);
buffer.writeBigUInt64LE(0n, at + 16);
buffer.writeUInt32LE(5, at + 24);
buffer.writeUInt32LE(5, at + 28);
};
/** Build a main cache (modern or legacy header) plus an optional `.01` subcache. */
export const dyldCacheFixture = (
images: readonly CacheFixtureImage[],
options: {
readonly legacy?: boolean;
readonly architecture?: string;
readonly subcacheUuidSeed?: number;
} = {},
): CacheFixture => {
const architecture = options.architecture ?? "arm64e";
const legacy = options.legacy === true;
const headerSize = legacy ? LEGACY_HEADER : MODERN_HEADER;
const sub = images.filter(({ inSubcache }) => inSubcache === true);
const main = images.filter(({ inSubcache }) => inSubcache !== true);
const mappingTable = headerSize;
const imageTable = mappingTable + 32;
const subTable = imageTable + images.length * 32;
const pathsAt = subTable + (sub.length > 0 && !legacy ? 56 : 0);
const paths = images.map(({ path }) => Buffer.from(`${path}\0`));
let cursor = align(
pathsAt + paths.reduce((total, path) => total + path.length, 0),
);
const mainOffsets = main.map((image) => {
const offset = cursor;
cursor = align(cursor + image.bytes.length);
return offset;
});
const mainFile = Buffer.alloc(cursor);
writeHeader(mainFile, { headerSize, uuidSeed: 1, architecture });
writeMapping(mainFile, mappingTable, MAIN_BASE, mainFile.length);
if (legacy) {
mainFile.writeUInt32LE(imageTable, 0x18);
mainFile.writeUInt32LE(images.length, 0x1c);
} else {
mainFile.writeUInt32LE(1, 0xd8);
mainFile.writeBigUInt64LE(MAIN_BASE, 0xe0);
mainFile.writeBigUInt64LE(0x20000000n, 0xe8);
mainFile.writeBigUInt64LE(0x10000000n, 0xf0);
mainFile.writeUInt32LE(0x001a0600, 0x16c);
mainFile.writeUInt32LE(imageTable, 0x1c0);
mainFile.writeUInt32LE(images.length, 0x1c4);
}
let pathCursor = pathsAt;
let subCursor = MODERN_HEADER + 32;
const subOffsets = new Map<string, number>();
for (const image of sub) {
subCursor = align(subCursor);
subOffsets.set(image.path, subCursor);
subCursor += image.bytes.length;
}
images.forEach((image, index) => {
const row = imageTable + index * 32;
const mainIndex = main.indexOf(image);
const address =
mainIndex >= 0
? MAIN_BASE + BigInt(mainOffsets[mainIndex] ?? 0)
: SUB_BASE + BigInt(subOffsets.get(image.path) ?? 0);
mainFile.writeBigUInt64LE(address, row);
mainFile.writeUInt32LE(pathCursor, row + 24);
const path = paths[index] ?? Buffer.alloc(1);
path.copy(mainFile, pathCursor);
pathCursor += path.length;
if (mainIndex >= 0)
Buffer.from(image.bytes).copy(mainFile, mainOffsets[mainIndex] ?? 0);
});
if (sub.length === 0 || legacy) return { main: mainFile, subcaches: [] };
mainFile.writeUInt32LE(subTable, 0x188);
mainFile.writeUInt32LE(1, 0x18c);
uuid(2).copy(mainFile, subTable);
mainFile.writeBigUInt64LE(SUB_BASE - MAIN_BASE, subTable + 16);
mainFile.write(".01", subTable + 24, "latin1");
const subFile = Buffer.alloc(align(subCursor));
writeHeader(subFile, {
headerSize: MODERN_HEADER,
uuidSeed: options.subcacheUuidSeed ?? 2,
architecture,
});
writeMapping(subFile, MODERN_HEADER, SUB_BASE, subFile.length);
for (const image of sub)
Buffer.from(image.bytes).copy(subFile, subOffsets.get(image.path) ?? 0);
return { main: mainFile, subcaches: [{ suffix: ".01", bytes: subFile }] };
};
+462
View File
@@ -0,0 +1,462 @@
import { open, type FileHandle } from "node:fs/promises";
import type { MachoImageFacts } from "../domain/dylibResolution.js";
import type {
DyldCacheMapping,
DyldCacheSubcache,
DyldSharedCacheHeader,
} from "../domain/dyldSharedCache.js";
import { ArtifactReaderFailure } from "./ArtifactReader.js";
import { readMachoImage } from "./MachoLoadCommandReader.js";
const MAGIC_PREFIX = "dyld_v1";
/** Header fields are valid only below `mappingOffset`; real headers are under 1 KiB. */
const MAX_HEADER_BYTES = 64 * 1024;
const MAX_IMAGES = 200_000;
const MAX_MAPPINGS = 64;
const MAX_SUBCACHES = 256;
const MAX_PATH_BYTES = 4096;
const BLOCK_BYTES = 64 * 1024;
/** Byte offsets of `dyld_cache_header` fields in Apple's open-source dyld. */
const FIELD = {
mappingOffset: 0x10,
mappingCount: 0x14,
imagesOffsetOld: 0x18,
imagesCountOld: 0x1c,
uuid: 0x58,
cacheType: 0x68,
platform: 0xd8,
formatBits: 0xdc,
sharedRegionStart: 0xe0,
sharedRegionSize: 0xe8,
maxSlide: 0xf0,
osVersion: 0x16c,
altPlatform: 0x170,
altOsVersion: 0x174,
subCacheArrayOffset: 0x188,
subCacheArrayCount: 0x18c,
symbolFileUuid: 0x190,
imagesOffset: 0x1c0,
imagesCount: 0x1c4,
cacheSubType: 0x1c8,
} as const;
const hex = (value: bigint | number): string => `0x${value.toString(16)}`;
const uuidText = (bytes: Buffer): string => {
const text = bytes.toString("hex").toUpperCase();
return `${text.slice(0, 8)}-${text.slice(8, 12)}-${text.slice(12, 16)}-${text.slice(16, 20)}-${text.slice(20)}`;
};
const safeNumber = (value: bigint, label: string): number => {
if (value > BigInt(Number.MAX_SAFE_INTEGER))
throw new ArtifactReaderFailure(
"format",
`dyld cache ${label} exceeds the safe range`,
);
return Number(value);
};
/** Block-cached positional reads over one cache file. */
class CacheFile {
readonly #blocks = new Map<number, Buffer>();
private constructor(
readonly suffix: string,
readonly handle: FileHandle,
readonly size: number,
) {}
static async open(path: string, suffix: string): Promise<CacheFile> {
const handle = await open(path, "r");
try {
return new CacheFile(suffix, handle, (await handle.stat()).size);
} catch (cause: unknown) {
await handle.close();
throw cause;
}
}
async read(offset: number, length: number): Promise<Buffer> {
if (offset < 0 || offset + length > this.size)
throw new ArtifactReaderFailure(
"format",
`dyld cache read at ${hex(offset)} extends beyond ${this.suffix === "" ? "the main file" : `subcache ${this.suffix}`}`,
);
if (length > BLOCK_BYTES) {
const bytes = Buffer.alloc(length);
await this.handle.read(bytes, 0, length, offset);
return bytes;
}
const chunks: Buffer[] = [];
for (let position = offset; position < offset + length;) {
const index = Math.floor(position / BLOCK_BYTES);
let block = this.#blocks.get(index);
if (block === undefined) {
const start = index * BLOCK_BYTES;
block = Buffer.alloc(Math.min(BLOCK_BYTES, this.size - start));
await this.handle.read(block, 0, block.length, start);
this.#blocks.set(index, block);
}
const from = position - index * BLOCK_BYTES;
const take = Math.min(block.length - from, offset + length - position);
chunks.push(block.subarray(from, from + take));
position += take;
}
return chunks.length === 1
? (chunks[0] ?? Buffer.alloc(0))
: Buffer.concat(chunks);
}
async cString(offset: number): Promise<string> {
const bytes = await this.read(
offset,
Math.min(MAX_PATH_BYTES, this.size - offset),
);
const end = bytes.indexOf(0);
if (end < 0)
throw new ArtifactReaderFailure(
"format",
`dyld cache string at ${hex(offset)} is unterminated`,
);
return bytes.toString("utf8", 0, end);
}
}
interface ParsedHeader {
readonly magic: string;
readonly uuid: string;
readonly mappings: readonly {
readonly address: bigint;
readonly size: bigint;
readonly fileOffset: bigint;
readonly maxProt: number;
readonly initProt: number;
}[];
readonly header: Buffer;
readonly length: number;
}
const has = (parsed: ParsedHeader, offset: number, width: number): boolean =>
parsed.length >= offset + width;
const readHeader = async (file: CacheFile): Promise<ParsedHeader> => {
if (file.size < 0x20)
throw new ArtifactReaderFailure(
"format",
"File is too short to be a dyld shared cache",
);
const prefix = await file.read(0, 0x20);
const magic = prefix.toString("latin1", 0, 16).replace(/\0+$/u, "");
if (!magic.startsWith(MAGIC_PREFIX))
throw new ArtifactReaderFailure(
"format",
"File is not a dyld shared cache",
);
const mappingOffset = prefix.readUInt32LE(FIELD.mappingOffset);
const mappingCount = prefix.readUInt32LE(FIELD.mappingCount);
if (
mappingOffset < 0x20 ||
mappingOffset > MAX_HEADER_BYTES ||
mappingCount > MAX_MAPPINGS
)
throw new ArtifactReaderFailure(
"format",
"dyld cache header has an invalid mapping table",
);
const header = await file.read(0, mappingOffset);
const table = await file.read(mappingOffset, mappingCount * 32);
const mappings = Array.from({ length: mappingCount }, (_, index) => ({
address: table.readBigUInt64LE(index * 32),
size: table.readBigUInt64LE(index * 32 + 8),
fileOffset: table.readBigUInt64LE(index * 32 + 16),
maxProt: table.readUInt32LE(index * 32 + 24),
initProt: table.readUInt32LE(index * 32 + 28),
}));
const parsed = { magic, uuid: "", mappings, header, length: mappingOffset };
return {
...parsed,
uuid: has(parsed, FIELD.uuid, 16)
? uuidText(header.subarray(FIELD.uuid, FIELD.uuid + 16))
: "",
};
};
const PLATFORMS: Readonly<Record<number, string>> = {
1: "macos",
2: "ios",
3: "tvos",
4: "watchos",
5: "bridgeos",
6: "maccatalyst",
7: "ios-simulator",
8: "tvos-simulator",
9: "watchos-simulator",
10: "driverkit",
11: "visionos",
12: "visionos-simulator",
};
const version = (value: number): string | null =>
value === 0
? null
: `${value >>> 16}.${(value >>> 8) & 0xff}.${value & 0xff}`;
/** A main dyld shared cache file and the subcaches it names. */
export class DyldSharedCache {
readonly #byPath: ReadonlyMap<
string,
{ readonly path: string; readonly address: number }
>;
private constructor(
readonly header: DyldSharedCacheHeader,
readonly images: readonly {
readonly path: string;
readonly address: number;
}[],
private readonly files: readonly CacheFile[],
private readonly regions: readonly {
readonly file: CacheFile;
readonly address: number;
readonly size: number;
readonly fileOffset: number;
}[],
) {
this.#byPath = new Map(images.map((image) => [image.path, image]));
}
/** Open the main cache file and every subcache beside it. */
static async open(
path: string,
signal?: AbortSignal,
): Promise<DyldSharedCache> {
const main = await CacheFile.open(path, "");
const files = [main];
try {
const parsed = await readHeader(main);
const subcaches = await DyldSharedCache.#subcacheEntries(main, parsed);
const statuses: DyldCacheSubcache[] = [];
const parsedFiles = [{ file: main, parsed }];
for (const entry of subcaches) {
signal?.throwIfAborted();
let file: CacheFile;
try {
file = await CacheFile.open(`${path}${entry.suffix}`, entry.suffix);
} catch (cause: unknown) {
if (
cause instanceof Error &&
"code" in cause &&
cause.code === "ENOENT"
) {
statuses.push({ ...entry, status: "missing", observed_uuid: null });
continue;
}
throw cause;
}
files.push(file);
const subParsed = await readHeader(file);
const matches = subParsed.uuid === entry.uuid;
statuses.push({
...entry,
status: matches ? "present" : "uuid-mismatch",
observed_uuid: subParsed.uuid,
});
if (matches) parsedFiles.push({ file, parsed: subParsed });
}
const header = DyldSharedCache.#summary(parsed, parsedFiles, statuses);
const images = await DyldSharedCache.#images(main, parsed, signal);
const regions = parsedFiles.flatMap(({ file, parsed: item }) =>
item.mappings.map((mapping) => ({
file,
address: safeNumber(mapping.address, "mapping address"),
size: safeNumber(mapping.size, "mapping size"),
fileOffset: safeNumber(mapping.fileOffset, "mapping file offset"),
})),
);
return new DyldSharedCache(header, images, files, regions);
} catch (cause: unknown) {
await Promise.allSettled(files.map(({ handle }) => handle.close()));
throw cause;
}
}
static async #subcacheEntries(
main: CacheFile,
parsed: ParsedHeader,
): Promise<
{
readonly suffix: string;
readonly uuid: string;
readonly vm_offset: string;
}[]
> {
if (!has(parsed, FIELD.subCacheArrayCount, 4)) return [];
const offset = parsed.header.readUInt32LE(FIELD.subCacheArrayOffset);
const count = parsed.header.readUInt32LE(FIELD.subCacheArrayCount);
if (count === 0) return [];
if (count > MAX_SUBCACHES)
throw new ArtifactReaderFailure(
"format",
"dyld cache lists too many subcaches",
);
// Headers that include cacheSubType use entries with an explicit file suffix.
const named = has(parsed, FIELD.cacheSubType, 4);
const size = named ? 56 : 24;
const table = await main.read(offset, count * size);
return Array.from({ length: count }, (_, index) => {
const base = index * size;
const suffix = named
? table.toString("latin1", base + 24, base + 56).replace(/\0.*$/su, "")
: `.${index + 1}`;
if (!/^\.[A-Za-z0-9.]+$/u.test(suffix))
throw new ArtifactReaderFailure(
"format",
"dyld subcache has an unsafe file suffix",
);
return {
suffix,
uuid: uuidText(table.subarray(base, base + 16)),
vm_offset: hex(table.readBigUInt64LE(base + 16)),
};
});
}
static #summary(
parsed: ParsedHeader,
files: readonly {
readonly file: CacheFile;
readonly parsed: ParsedHeader;
}[],
subcaches: readonly DyldCacheSubcache[],
): DyldSharedCacheHeader {
const header = parsed.header;
const u32 = (offset: number): number | null =>
has(parsed, offset, 4) ? header.readUInt32LE(offset) : null;
const u64 = (offset: number): string | null =>
has(parsed, offset, 8) ? hex(header.readBigUInt64LE(offset)) : null;
const platform = u32(FIELD.platform);
const altPlatform = u32(FIELD.altPlatform);
const cacheType = has(parsed, FIELD.cacheType, 8)
? Number(header.readBigUInt64LE(FIELD.cacheType))
: null;
const symbols = has(parsed, FIELD.symbolFileUuid, 16)
? header.subarray(FIELD.symbolFileUuid, FIELD.symbolFileUuid + 16)
: undefined;
const mappings: DyldCacheMapping[] = files.flatMap(
({ file, parsed: item }) =>
item.mappings.map((mapping) => ({
file: file.suffix,
address: hex(mapping.address),
size: hex(mapping.size),
file_offset: hex(mapping.fileOffset),
max_protection: mapping.maxProt,
initial_protection: mapping.initProt,
})),
);
return {
magic: parsed.magic,
architecture: parsed.magic.slice(MAGIC_PREFIX.length).trim(),
uuid: parsed.uuid,
platform:
platform === null
? null
: { id: platform, name: PLATFORMS[platform] ?? null },
os_version: version(u32(FIELD.osVersion) ?? 0),
alt_platform:
altPlatform === null || altPlatform === 0
? null
: { id: altPlatform, name: PLATFORMS[altPlatform] ?? null },
alt_os_version: version(u32(FIELD.altOsVersion) ?? 0),
cache_type:
cacheType === 0
? "development"
: cacheType === 1
? "production"
: cacheType === 2
? "multi-cache"
: null,
shared_region:
u64(FIELD.sharedRegionStart) === null
? null
: {
start: u64(FIELD.sharedRegionStart) ?? "0x0",
size: u64(FIELD.sharedRegionSize) ?? "0x0",
},
max_slide: u64(FIELD.maxSlide),
mappings,
subcaches: [...subcaches],
symbols_file_uuid:
symbols === undefined || symbols.every((byte) => byte === 0)
? null
: uuidText(symbols),
};
}
static async #images(
main: CacheFile,
parsed: ParsedHeader,
signal?: AbortSignal,
): Promise<{ readonly path: string; readonly address: number }[]> {
const modern = has(parsed, FIELD.imagesCount, 4);
const offset = parsed.header.readUInt32LE(
modern ? FIELD.imagesOffset : FIELD.imagesOffsetOld,
);
const count = parsed.header.readUInt32LE(
modern ? FIELD.imagesCount : FIELD.imagesCountOld,
);
if (count > MAX_IMAGES)
throw new ArtifactReaderFailure(
"limit",
`dyld cache lists more than ${MAX_IMAGES} images`,
);
const table = await main.read(offset, count * 32);
const images: { path: string; address: number }[] = [];
for (let index = 0; index < count; index++) {
if (index % 512 === 0) signal?.throwIfAborted();
images.push({
address: safeNumber(table.readBigUInt64LE(index * 32), "image address"),
path: await main.cString(table.readUInt32LE(index * 32 + 24)),
});
}
return images;
}
/** Locate an image by its exact install path. */
find(
path: string,
): { readonly path: string; readonly address: number } | undefined {
return this.#byPath.get(path);
}
/** Parse one cached image's load commands through the cache's VM mappings. */
async imageFacts(
path: string,
): Promise<
{ readonly file: string; readonly facts: MachoImageFacts } | undefined
> {
const image = this.find(path);
if (image === undefined) return undefined;
const region = this.regions.find(
({ address, size }) =>
image.address >= address && image.address < address + size,
);
if (region === undefined) return undefined;
const base = region.fileOffset + (image.address - region.address);
const available = region.size - (image.address - region.address);
const facts = await readMachoImage(
async (offset, length) =>
region.file.read(
base + offset,
Math.max(0, Math.min(length, available - offset)),
),
available,
);
return { file: region.file.suffix, facts };
}
async close(): Promise<void> {
await Promise.allSettled(this.files.map(({ handle }) => handle.close()));
}
}
+39 -1
View File
@@ -1,7 +1,7 @@
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 { join, relative, resolve, sep } from "node:path";
import {
dylibResolutionInputSchema,
@@ -14,6 +14,7 @@ import {
} from "../domain/dylibResolution.js";
import { ArtifactReaderFailure } from "./ArtifactReader.js";
import { DirectoryArtifactReader } from "./DirectoryArtifactReader.js";
import { DyldSharedCache } from "./DyldSharedCacheReader.js";
import { hasMachoMagic, readMachoImage } from "./MachoLoadCommandReader.js";
const HASH_CHUNK_BYTES = 1024 * 1024;
@@ -80,7 +81,9 @@ export const traceDylibResolution = async (options: {
.split(sep)
.join("/");
const view = new FilesystemTreeView(root, options.signal);
let cache: DyldSharedCache | undefined;
try {
cache = await openSharedCache(parsed.data.shared_cache, options.signal);
const { roots, unclassified } =
parsed.data.roots !== undefined
? { roots: parsed.data.roots, unclassified: [] }
@@ -94,6 +97,7 @@ export const traceDylibResolution = async (options: {
...(parsed.data.architecture === undefined
? {}
: { architecture: parsed.data.architecture }),
...(cache === undefined ? {} : { sharedCache: sharedCacheView(cache) }),
...(options.signal === undefined ? {} : { signal: options.signal }),
});
const digests = new Map<string, string>();
@@ -111,6 +115,15 @@ export const traceDylibResolution = async (options: {
...trace,
root_path: options.rootPath,
target_sha256: options.targetSha256,
shared_cache:
cache === undefined || parsed.data.shared_cache === undefined
? null
: {
path: resolve(parsed.data.shared_cache),
uuid: cache.header.uuid,
architecture: cache.header.architecture,
os_version: cache.header.os_version,
},
images: trace.images.map((image) => ({
...image,
sha256: digests.get(image.path),
@@ -124,9 +137,34 @@ export const traceDylibResolution = async (options: {
{ cause },
);
throw cause;
} finally {
await cache?.close();
}
};
const openSharedCache = async (
path: string | undefined,
signal?: AbortSignal,
): Promise<DyldSharedCache | undefined> => {
if (path === undefined) return undefined;
try {
return await DyldSharedCache.open(resolve(path), signal);
} catch (cause: unknown) {
if (missing(cause))
throw new ArtifactReaderFailure(
"path",
"shared_cache does not name an existing dyld shared cache file",
{ cause },
);
throw cause;
}
};
const sharedCacheView = (cache: DyldSharedCache) => ({
architecture: cache.header.architecture,
has: (path: string): boolean => cache.find(path) !== undefined,
});
/**
* 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
+35
View File
@@ -3,6 +3,7 @@ import { Cli, z } from "incur";
import { projectAndroidApplicationEvidence } from "../application/android/AndroidApplicationService.js";
import { projectAppleApplicationEvidence } from "../application/AppleApplicationService.js";
import { inspectDyldSharedCacheEvidence } from "../application/DyldSharedCacheService.js";
import {
compareApplicationVersionsEvidenceValidated,
compareJavaScriptExportShapesEvidenceValidated,
@@ -83,6 +84,7 @@ export const registerApplicationCommands = (
workflow: compareJavaScriptExportShapesEvidenceValidated,
});
registerObligationLedgerCommand(cli, logger);
registerDyldSharedCacheCommand(cli, logger);
registerCoverageCommand(cli, logger);
registerJsonCommand({
cli,
@@ -114,6 +116,39 @@ export const registerApplicationCommands = (
});
};
/** `inspect-dyld-shared-cache <cache> [--image <install path>]...` */
const registerDyldSharedCacheCommand = (
cli: CliInstance,
logger: Logger,
): void => {
cli.command(CLI_COMMANDS.inspectDyldSharedCache, {
description:
"Inspect a dyld shared cache file set and, optionally, cached images",
args: z.object({
cachePath: z.string().describe("Main dyld shared cache file"),
}),
options: z.object({
image: z
.array(z.string())
.optional()
.describe("Install path of a cached image to inspect (repeatable)"),
}),
run: ({ args, options }) =>
logCliCommand(logger, CLI_COMMANDS.inspectDyldSharedCache, async () => {
const result = await inspectDyldSharedCacheEvidence({
cache_path: args.cachePath,
...(options.image === undefined ? {} : { images: options.image }),
});
return result.ok
? jsonValueSchema.parse(result.value)
: {
error: "Application workflow failed",
...projectAnalysisError(result.error),
};
}),
});
};
const registerObligationLedgerCommand = (
cli: CliInstance,
logger: Logger,
+9
View File
@@ -80,6 +80,12 @@ const registerDylibResolutionCommand = (
.enum(["arm64", "arm64e", "x86_64"])
.optional()
.describe("Trace only this slice of each root"),
sharedCache: z
.string()
.optional()
.describe(
"Main dyld shared cache file used to answer system install paths",
),
}),
run: ({ args, options }) =>
logCliCommand(logger, CLI_COMMANDS.traceDylibResolution, () =>
@@ -91,6 +97,9 @@ const registerDylibResolutionCommand = (
...(options.architecture === undefined
? {}
: { architecture: options.architecture }),
...(options.sharedCache === undefined
? {}
: { shared_cache: options.sharedCache }),
},
logger,
),
+1
View File
@@ -26,6 +26,7 @@ export const CLI_COMMANDS = Object.freeze({
decodeInterfaceBuilder: "decode-interface-builder",
inspectKeyedArchive: "inspect-keyed-archive",
traceDylibResolution: "trace-dylib-resolution",
inspectDyldSharedCache: "inspect-dyld-shared-cache",
inspectNativeDataType: "inspect-native-data-type",
inspectNativeLoadImage: "inspect-native-load-image",
readBytes: "read-bytes",
+26
View File
@@ -1,4 +1,8 @@
import { applicationVersionComparisonResultSchema } from "../domain/javascript/javascriptApplicationVersionComparisonSchemas.js";
import {
dyldSharedCacheResultSchema,
inspectDyldSharedCacheInputSchema,
} from "../domain/dyldSharedCache.js";
import { applicationFeatureTraceResultSchema } from "../domain/javascript/javascriptFeatureTraceSchemas.js";
import { javaScriptSemanticTraceResultSchema } from "../domain/javascript/javascriptSemanticTraceSchemas.js";
import { javaScriptExportShapeComparisonResultSchema } from "../domain/javascript/javascriptExportShapeComparisonSchemas.js";
@@ -295,6 +299,25 @@ export const APPLICATION_TOOL_CONTRACTS = [
},
],
},
{
name: "inspect_dyld_shared_cache",
...toolContractMetadata("inspect_dyld_shared_cache"),
description:
"Inspect an Apple dyld shared cache file set selected by path, such as /System/Volumes/Preboot/Cryptexes/OS/System/Library/dyld/dyld_shared_cache_arm64e or one extracted from an IPSW. Reports the cache UUID, architecture, platform and OS version, VM mappings, every subcache with UUID verification, and the complete image list. For each requested install path, it reads that image's load commands (install name, dependencies, rpaths) through the cache mappings. Pure file parsing: nothing is executed, slid, or extracted.",
kind: "application",
inputSchema: inspectDyldSharedCacheInputSchema,
outputSchema: evidenceResultOf(dyldSharedCacheResultSchema),
examples: [
{
title: "Inspect the host's arm64e shared cache and libSystem",
input: {
cache_path:
"/System/Volumes/Preboot/Cryptexes/OS/System/Library/dyld/dyld_shared_cache_arm64e",
images: ["/usr/lib/libSystem.B.dylib"],
},
},
],
},
] as const satisfies readonly ToolContract[];
/** Resolve one named application contract without relying on array position. */
@@ -325,6 +348,9 @@ export function applicationToolContract(
export function applicationToolContract(
name: "project_apple_application_graph",
): (typeof APPLICATION_TOOL_CONTRACTS)[8];
export function applicationToolContract(
name: "inspect_dyld_shared_cache",
): (typeof APPLICATION_TOOL_CONTRACTS)[9];
export function applicationToolContract(
name: (typeof APPLICATION_TOOL_CONTRACTS)[number]["name"],
): (typeof APPLICATION_TOOL_CONTRACTS)[number] {
+1
View File
@@ -248,6 +248,7 @@ export const TOOL_EFFECTS: Readonly<Record<string, ToolEffects>> = {
evaluate_reconstruction_coverage: effects(),
project_android_application_graph: evidence,
project_apple_application_graph: evidence,
inspect_dyld_shared_cache: evidence,
open_binary: effects({ mutatesSession: true, launchesProcess: true }),
close_binary: effects({
mutatesSession: true,
+1
View File
@@ -13,6 +13,7 @@ export class ArtifactOperationError extends AnalysisError {
| "inspect_asset_catalog"
| "inspect_keyed_archive"
| "trace_dylib_resolution"
| "inspect_dyld_shared_cache"
| "export_web_scripts"
| "trace_web_module_imports"
| "trace_web_source_location"
+8
View File
@@ -108,3 +108,11 @@ export const compatibleSlice = (
}
return undefined;
};
/** A cache serves processes of its CPU family: arm64e also serves arm64. */
export const cacheServes = (cache: string, process: string): boolean =>
cache === process ||
(cache.startsWith("arm64") &&
process.startsWith("arm64") &&
process !== "arm64_32") ||
(cache.startsWith("x86_64") && process.startsWith("x86_64"));
+88
View File
@@ -0,0 +1,88 @@
import { z } from "zod";
import { digestSchema } from "./digests.js";
import { machoSliceSchema } from "./dylibResolution.js";
const hexSchema = z.string().regex(/^0x[0-9a-f]+$/u);
const uuidSchema = z
.string()
.regex(/^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/u);
const platformSchema = z.object({
id: z.number().int(),
name: z.string().nullable(),
});
/** One cached image selected by its exact install path. */
export const inspectDyldSharedCacheInputSchema = z.strictObject({
cache_path: z.string().min(1),
images: z.array(z.string().min(1)).min(1).optional(),
});
const mappingSchema = z.object({
file: z.string(),
address: hexSchema,
size: hexSchema,
file_offset: hexSchema,
max_protection: z.number().int(),
initial_protection: z.number().int(),
});
const subcacheSchema = z.object({
suffix: z.string(),
uuid: uuidSchema,
vm_offset: hexSchema,
status: z.enum(["present", "missing", "uuid-mismatch"]),
observed_uuid: uuidSchema.nullable(),
});
const headerSchema = z.object({
magic: z.string(),
architecture: z.string(),
uuid: z.string(),
platform: platformSchema.nullable(),
os_version: z.string().nullable(),
alt_platform: platformSchema.nullable(),
alt_os_version: z.string().nullable(),
cache_type: z.enum(["development", "production", "multi-cache"]).nullable(),
shared_region: z.object({ start: hexSchema, size: hexSchema }).nullable(),
max_slide: hexSchema.nullable(),
mappings: z.array(mappingSchema),
subcaches: z.array(subcacheSchema),
symbols_file_uuid: uuidSchema.nullable(),
});
const inspectedImageSchema = z.object({
path: z.string(),
status: z.enum(["parsed", "malformed", "unsupported", "absent", "unmapped"]),
address: hexSchema.nullable(),
file: z.string().nullable(),
reason: z.string().nullable(),
slices: z.array(machoSliceSchema),
});
/** Header, mappings, subcaches, and the complete image list of one cache. */
export const dyldSharedCacheResultSchema = z.object({
cache_path: z.string(),
main_file_sha256: digestSchema,
...headerSchema.shape,
images_total: z.number().int().nonnegative(),
images: z.array(z.object({ path: z.string(), address: hexSchema })),
inspected_images: z.array(inspectedImageSchema),
coverage: z.object({
status: z.enum(["complete", "partial"]),
unreadable_subcaches: z.array(z.string()),
}),
limitations: z.array(z.string()),
});
export type DyldCacheMapping = z.infer<typeof mappingSchema>;
export type DyldCacheSubcache = z.infer<typeof subcacheSchema>;
export type DyldSharedCacheHeader = z.infer<typeof headerSchema>;
export type DyldSharedCacheResult = z.infer<typeof dyldSharedCacheResultSchema>;
export type InspectedCacheImage = z.infer<typeof inspectedImageSchema>;
/** Limitations that bound claims made from one cache file set. */
export const DYLD_SHARED_CACHE_LIMITATIONS = [
"The cache describes the operating system it was built for; it is evidence about this cache file set, not about another host.",
"Image headers are read through the cache's VM mappings; slide info, local symbols, and code signatures are not parsed, and images are not extracted.",
];
+71
View File
@@ -518,3 +518,74 @@ describe("dyld slice compatibility and coverage", () => {
);
});
});
describe("shared cache resolution", () => {
const cache = {
architecture: "arm64e",
has: (path: string) =>
[
"/usr/lib/libSystem.B.dylib",
"/usr/lib/swift/libswiftCore.dylib",
].includes(path),
};
it("resolves cached system paths before bundled fallbacks", async () => {
const trace = await traceDylibLoading(
memoryView({
[MAIN]: executable({
rpaths: ["/usr/lib/swift", "@executable_path/../Frameworks"],
dependencies: [
dependency("/usr/lib/libSystem.B.dylib"),
dependency("@rpath/libswiftCore.dylib"),
dependency("/usr/lib/libgone.dylib"),
],
}),
"Contents/Frameworks/libswiftCore.dylib": parsed(slice()),
}),
{ roots: [MAIN], sharedCache: cache },
);
expect(
trace.edges.map(({ install_name: name, resolution, candidates }) => [
name,
resolution,
candidates.map(({ outcome }) => outcome),
]),
).toEqual([
[
"/usr/lib/libSystem.B.dylib",
{ status: "shared-cache", image: "/usr/lib/libSystem.B.dylib" },
["shared-cache"],
],
[
"@rpath/libswiftCore.dylib",
{ status: "shared-cache", image: "/usr/lib/swift/libswiftCore.dylib" },
["shared-cache"],
],
[
"/usr/lib/libgone.dylib",
{ status: "undetermined", image: null },
["outside-target"],
],
]);
expect(trace.images.map(({ path }) => path)).toEqual([MAIN]);
expect(trace.limitations).toContainEqual(
expect.stringContaining("looked up in the supplied dyld shared cache"),
);
});
it("does not consult a cache for processes it cannot serve", async () => {
const trace = await traceDylibLoading(
memoryView({
[MAIN]: executable({
architecture: "x86_64",
dependencies: [dependency("/usr/lib/libSystem.B.dylib")],
}),
}),
{ roots: [MAIN], sharedCache: cache },
);
expect(trace.edges[0]?.candidates[0]?.outcome).toBe("outside-target");
expect(trace.limitations).toContain(
"The arm64e shared cache does not serve x86_64 processes; their system paths stay undetermined.",
);
});
});
+60 -70
View File
@@ -1,6 +1,7 @@
import { z } from "zod";
import {
cacheServes,
compatibleSlice,
directoryOf,
expandPrefix,
@@ -9,6 +10,11 @@ import {
type Expansion,
} from "./dyldPaths.js";
import { digestSchema } from "./digests.js";
import {
DYLIB_RESOLUTION_LIMITATIONS,
deriveFindings,
sharedCacheLimitations,
} from "./dylibResolutionFindings.js";
/** Normalized path below the analyzed root: no `.`/`..` or empty segments. */
const ROOT_RELATIVE_PATH =
@@ -19,6 +25,8 @@ const rootRelativePathSchema = z.string().min(1).regex(ROOT_RELATIVE_PATH);
export const dylibResolutionInputSchema = z.strictObject({
roots: z.array(rootRelativePathSchema).min(1).optional(),
architecture: z.enum(["arm64", "arm64e", "x86_64"]).optional(),
/** Main dyld shared cache file whose image list answers system install paths. */
shared_cache: z.string().min(1).optional(),
});
const dependencyCommandSchema = z.enum([
@@ -75,6 +83,12 @@ export interface DylibTreeView {
image(path: string): Promise<MachoImageFacts>;
}
/** Image list of one caller-supplied dyld shared cache. */
export interface DylibSharedCacheView {
readonly architecture: string;
has(path: string): boolean;
}
const candidateSchema = z.strictObject({
path: z.string(),
source: z.enum([
@@ -94,6 +108,7 @@ const candidateSchema = z.strictObject({
"unsupported",
"architecture-missing",
"outside-target",
"shared-cache",
"escapes-target",
"undetermined",
]),
@@ -108,7 +123,13 @@ const edgeSchema = z.strictObject({
...dependencySchema.shape,
candidates: z.array(candidateSchema),
resolution: z.strictObject({
status: z.enum(["resolved", "conditional", "unresolved", "undetermined"]),
status: z.enum([
"resolved",
"conditional",
"shared-cache",
"unresolved",
"undetermined",
]),
image: z.string().nullable(),
}),
install_name_matches: z.boolean().nullable(),
@@ -139,6 +160,14 @@ const imageSchema = z.strictObject({
export const dylibResolutionResultSchema = z.strictObject({
root_path: z.string(),
target_sha256: digestSchema,
shared_cache: z
.strictObject({
path: z.string(),
uuid: z.string(),
architecture: z.string(),
os_version: z.string().nullable(),
})
.nullable(),
roots: z.array(
z.strictObject({ image: z.string(), architecture: z.string() }),
),
@@ -155,13 +184,14 @@ export const dylibResolutionResultSchema = z.strictObject({
export type DylibResolutionResult = z.infer<typeof dylibResolutionResultSchema>;
type Candidate = z.infer<typeof candidateSchema>;
type Edge = z.infer<typeof edgeSchema>;
type Finding = z.infer<typeof findingSchema>;
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"
"root_path" | "target_sha256" | "shared_cache" | "images"
> & {
readonly images: readonly (Omit<
DylibResolutionResult["images"][number],
@@ -183,6 +213,8 @@ interface ProcessContext {
readonly loaded: Map<string, LoadedImage>;
readonly byInstallName: Map<string, string>;
readonly images: Map<string, MachoImageFacts>;
/** The supplied cache, when it serves this process's architecture. */
readonly sharedCache: DylibSharedCacheView | undefined;
}
interface CandidateTemplate {
@@ -247,7 +279,13 @@ const evaluateCandidate = async (
rpath_owner: template.rpathOwner,
};
if (template.expansion.scope === "outside")
return { ...base, outcome: "outside-target", resolved_path: null };
return context.sharedCache?.has(template.expansion.path) === true
? {
...base,
outcome: "shared-cache",
resolved_path: template.expansion.path,
}
: { ...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);
@@ -284,6 +322,8 @@ const resolution = (candidates: readonly Candidate[]): Edge["resolution"] => {
status: external ? "conditional" : "resolved",
image: candidate.resolved_path,
};
if (candidate.outcome === "shared-cache")
return { status: "shared-cache", image: candidate.resolved_path };
// dyld might load these; REA cannot decide them from the analyzed root.
if (
candidate.outcome === "outside-target" ||
@@ -318,7 +358,11 @@ const resolveDependency = async (
const candidate = await evaluateCandidate(template, context);
candidates.push(candidate);
// dyld stops at the first loadable candidate.
if (candidate.outcome === "resolved") break;
if (
candidate.outcome === "resolved" ||
candidate.outcome === "shared-cache"
)
break;
}
const resolved = resolution(candidates);
const image =
@@ -394,6 +438,7 @@ export const traceDylibLoading = async (
/** Mach-O files whose root role could not be classified because they did not parse. */
readonly unclassified?: readonly string[];
readonly architecture?: string;
readonly sharedCache?: DylibSharedCacheView;
readonly signal?: AbortSignal;
},
): Promise<DylibTrace> => {
@@ -425,6 +470,11 @@ export const traceDylibLoading = async (
loaded: new Map(),
byInstallName: new Map(),
images,
sharedCache:
request.sharedCache !== undefined &&
cacheServes(request.sharedCache.architecture, slice.architecture)
? request.sharedCache
: undefined,
},
slice,
request.signal,
@@ -461,7 +511,10 @@ export const traceDylibLoading = async (
unparsed_images: unparsed,
roots_without_architecture: withoutArchitecture,
},
limitations: DYLIB_RESOLUTION_LIMITATIONS,
limitations: [
...DYLIB_RESOLUTION_LIMITATIONS,
...sharedCacheLimitations(request.sharedCache, roots),
],
};
};
@@ -476,68 +529,5 @@ const withoutDependencies = (
code_signature_present: slice.code_signature_present,
});
const deriveFindings = (
edges: readonly Edge[],
roots: DylibTrace["roots"],
images: ReadonlyMap<string, MachoImageFacts>,
): Finding[] => {
const findings: Finding[] = [];
edges.forEach((edge, index) => {
if (edge.resolution.status === "unresolved")
findings.push({
kind: edge.weak ? "weak-load-unresolved" : "required-load-unresolved",
edge_index: index,
image: edge.loader,
basis: "derived",
explanation: edge.weak
? `No candidate for weak dependency ${edge.install_name} exists in the analyzed root; dyld continues without it.`
: `No candidate for ${edge.install_name} exists in the analyzed root; dyld would fail to launch ${edge.root} (${edge.architecture}) unless the image is supplied elsewhere.`,
});
const resolvedAt = edge.candidates.findIndex(
({ outcome }) => outcome === "resolved",
);
const earlier = edge.candidates
.slice(0, Math.max(resolvedAt, 0))
.filter(
({ source, outcome }) => source === "rpath" && outcome === "absent",
)
.map(({ path }) => path);
if (resolvedAt > 0 && earlier.length > 0)
findings.push({
kind: "earlier-rpath-candidate-absent",
edge_index: index,
image: edge.loader,
basis: "derived",
explanation: `dyld searches ${earlier.join(", ")} before ${edge.resolution.image ?? edge.install_name}. A Mach-O placed at an earlier path would load first unless code-signing library validation rejects it; library validation is not evaluated here (see inspect_signature).`,
});
});
for (const { image, architecture } of roots) {
const facts = images.get(image);
const environment =
facts?.status === "parsed"
? (facts.slices.find((slice) => slice.architecture === architecture)
?.dyld_environment ?? [])
: [];
if (environment.length > 0)
findings.push({
kind: "dyld-environment-present",
edge_index: null,
image,
basis: "derived",
explanation: `${image} (${architecture}) sets dyld environment variables through LC_DYLD_ENVIRONMENT (${environment.join(", ")}); search paths they add are not modeled.`,
});
}
return findings;
};
const DYLIB_RESOLUTION_LIMITATIONS = [
"Slices are matched by dyld's graded architectures (an x86_64h process also loads x86_64). arm64e processes that disable pointer authentication can also load arm64 slices; that fallback is not modeled.",
"Absolute install names and rpaths are outside the analyzed root and are not evaluated, including /System and /usr/lib libraries that the dyld shared cache usually provides.",
"Leaf and relative install names depend on dyld fallback paths, DYLD_* variables, and the working directory; they are undetermined.",
"Load order follows dyld's dependents-first traversal in load-command order. An image reached through several chains is resolved once per process, with the rpath stack of the first chain; a later request whose install name matches an already loaded image reuses it.",
"@loader_path uses each image's symlink-resolved path within the analyzed root.",
"Code-signing checks that can reject a found image, such as library validation and the hardened runtime, are not evaluated.",
];
const compare = (left: string, right: string): number =>
left < right ? -1 : left > right ? 1 : 0;
+95
View File
@@ -0,0 +1,95 @@
import { cacheServes } from "./dyldPaths.js";
import type {
DylibEdge as Edge,
DylibFinding as Finding,
DylibSharedCacheView,
DylibTrace,
MachoImageFacts,
} from "./dylibResolution.js";
export const deriveFindings = (
edges: readonly Edge[],
roots: DylibTrace["roots"],
images: ReadonlyMap<string, MachoImageFacts>,
): Finding[] => {
const findings: Finding[] = [];
edges.forEach((edge, index) => {
if (edge.resolution.status === "unresolved")
findings.push({
kind: edge.weak ? "weak-load-unresolved" : "required-load-unresolved",
edge_index: index,
image: edge.loader,
basis: "derived",
explanation: edge.weak
? `No candidate for weak dependency ${edge.install_name} exists in the analyzed root; dyld continues without it.`
: `No candidate for ${edge.install_name} exists in the analyzed root; dyld would fail to launch ${edge.root} (${edge.architecture}) unless the image is supplied elsewhere.`,
});
const resolvedAt = edge.candidates.findIndex(
({ outcome }) => outcome === "resolved" || outcome === "shared-cache",
);
const earlier = edge.candidates
.slice(0, Math.max(resolvedAt, 0))
.filter(
({ source, outcome }) => source === "rpath" && outcome === "absent",
)
.map(({ path }) => path);
if (resolvedAt > 0 && earlier.length > 0)
findings.push({
kind: "earlier-rpath-candidate-absent",
edge_index: index,
image: edge.loader,
basis: "derived",
explanation: `dyld searches ${earlier.join(", ")} before ${edge.resolution.image ?? edge.install_name}. A Mach-O placed at an earlier path would load first unless code-signing library validation rejects it; library validation is not evaluated here (see inspect_signature).`,
});
});
for (const { image, architecture } of roots) {
const facts = images.get(image);
const environment =
facts?.status === "parsed"
? (facts.slices.find((slice) => slice.architecture === architecture)
?.dyld_environment ?? [])
: [];
if (environment.length > 0)
findings.push({
kind: "dyld-environment-present",
edge_index: null,
image,
basis: "derived",
explanation: `${image} (${architecture}) sets dyld environment variables through LC_DYLD_ENVIRONMENT (${environment.join(", ")}); search paths they add are not modeled.`,
});
}
return findings;
};
export const DYLIB_RESOLUTION_LIMITATIONS = [
"Slices are matched by dyld's graded architectures (an x86_64h process also loads x86_64). arm64e processes that disable pointer authentication can also load arm64 slices; that fallback is not modeled.",
"Absolute install names and rpaths are outside the analyzed root and are not evaluated, including /System and /usr/lib libraries that the dyld shared cache usually provides.",
"Leaf and relative install names depend on dyld fallback paths, DYLD_* variables, and the working directory; they are undetermined.",
"Load order follows dyld's dependents-first traversal in load-command order. An image reached through several chains is resolved once per process, with the rpath stack of the first chain; a later request whose install name matches an already loaded image reuses it.",
"@loader_path uses each image's symlink-resolved path within the analyzed root.",
"Code-signing checks that can reject a found image, such as library validation and the hardened runtime, are not evaluated.",
];
export const sharedCacheLimitations = (
cache: DylibSharedCacheView | undefined,
roots: DylibTrace["roots"],
): string[] => {
if (cache === undefined) return [];
const unserved = [
...new Set(
roots
.map(({ architecture }) => architecture)
.filter(
(architecture) => !cacheServes(cache.architecture, architecture),
),
),
];
return [
"Absolute install paths were looked up in the supplied dyld shared cache; on another OS build the cache contents, and therefore these outcomes, can differ.",
...(unserved.length === 0
? []
: [
`The ${cache.architecture} shared cache does not serve ${unserved.join(", ")} processes; their system paths stay undetermined.`,
]),
];
};
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -5,5 +5,5 @@ export const PACKAGE_METADATA = {
serverSdkVersion: "2.3.1",
clientSdkVersion: "2.3.1",
coreSdkVersion: "2.3.1",
skillVersion: "28",
skillVersion: "29",
} as const;
+2
View File
@@ -7,6 +7,7 @@ import { registerCompareSourceToBundleTool } from "./registerApplicationTools/co
import { registerCompareJavaScriptExportShapesTool } from "./registerApplicationTools/compareExportShapes.js";
import { registerCoverageTools } from "./registerApplicationTools/coverage.js";
import { registerReconstructionObligationLedgerTool } from "./registerApplicationTools/obligationLedger.js";
import { registerInspectDyldSharedCacheTool } from "./registerApplicationTools/inspectDyldSharedCache.js";
import { registerProjectMobileApplicationGraphTools } from "./registerApplicationTools/projectMobileApplicationGraph.js";
import type { ApplicationToolRegistration } from "./registerApplicationTools/types.js";
@@ -25,4 +26,5 @@ export const registerApplicationTools = (
registerReconstructionObligationLedgerTool(server, options);
registerCoverageTools(server, options);
registerProjectMobileApplicationGraphTools(server, options);
registerInspectDyldSharedCacheTool(server, options);
};
@@ -0,0 +1,28 @@
import type { McpServer } from "@modelcontextprotocol/server";
import { inspectDyldSharedCacheEvidence } from "../../application/DyldSharedCacheService.js";
import { applicationToolContract } from "../../contracts/applicationToolContracts.js";
import { logToolExecution } from "../toolLogging.js";
import { toolRegistrationOptions } from "../toolRegistrationOptions.js";
import { toCallToolResult } from "../toolResult.js";
import { recordResult } from "./helpers.js";
import type { ApplicationToolRegistration } from "./types.js";
/** Register the target-free dyld shared cache inspection tool. */
export const registerInspectDyldSharedCacheTool = (
server: McpServer,
options: ApplicationToolRegistration,
): void => {
const contract = applicationToolContract("inspect_dyld_shared_cache");
server.registerTool(
contract.name,
toolRegistrationOptions(contract),
async (input: unknown, context) => {
const result = await logToolExecution(options.logger, contract.name, () =>
inspectDyldSharedCacheEvidence(input, context.mcpReq.signal),
);
if (!result.ok) return toCallToolResult(result, contract);
return recordResult(options, contract, result.value);
},
);
};