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:
co-authored by
Claude Opus 5.5
parent
a0ec3e2016
commit
ade11fa02d
@@ -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 }] };
|
||||
};
|
||||
@@ -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()));
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user