fix(apple): gate shared-cache answers on platform and verified subcaches

- Use a supplied cache for a process only when it serves the process's CPU
  family and one of its LC_BUILD_VERSION or LC_VERSION_MIN platforms matches
  the cache's platform or alternate platform; slices now report platforms.
  A limitation names each root the cache was not used for, and why.
- Treat an image listed in the cache but mapped in a missing or
  UUID-mismatched subcache as undetermined, list it in
  coverage.unverified_shared_cache_images, and mark coverage partial.
- Keep a cache hit conditional when an earlier candidate is undeterminable.
- Open a development cache's named subcaches beside its base name.
- Describe absolute paths as not evaluated only when no cache is supplied.
- Preflight dyld_info in verify:dyld-shared-cache.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Kaoru0822
2026-10-07 12:36:43 +00:00
co-authored by Claude Opus 5.5
parent 202661f83b
commit 305474df6c
20 changed files with 670 additions and 299 deletions
+44 -35
View File
@@ -1,5 +1,6 @@
import { open, type FileHandle } from "node:fs/promises";
import { applePlatform } from "../domain/applePlatforms.js";
import type { MachoImageFacts } from "../domain/dylibResolution.js";
import type {
DyldCacheMapping,
@@ -10,6 +11,7 @@ import { ArtifactReaderFailure } from "./ArtifactReader.js";
import { readMachoImage } from "./MachoLoadCommandReader.js";
const MAGIC_PREFIX = "dyld_v1";
const DEVELOPMENT_EXTENSION = ".development";
/** Header fields are valid only below `mappingOffset`; real headers are under 1 KiB. */
const MAX_HEADER_BYTES = 64 * 1024;
const MAX_IMAGES = 200_000;
@@ -183,21 +185,6 @@ const readHeader = async (file: CacheFile): Promise<ParsedHeader> => {
};
};
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
@@ -236,14 +223,21 @@ export class DyldSharedCache {
const files = [main];
try {
const parsed = await readHeader(main);
const subcaches = await DyldSharedCache.#subcacheEntries(main, parsed);
const { named, entries: subcaches } =
await DyldSharedCache.#subcacheEntries(main, parsed);
// With named suffixes, dyld strips a development main file's extension
// first: dyld_shared_cache_arm64e.development -> dyld_shared_cache_arm64e.01.development.
const base =
named && path.endsWith(DEVELOPMENT_EXTENSION)
? path.slice(0, -DEVELOPMENT_EXTENSION.length)
: path;
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);
file = await CacheFile.open(`${base}${entry.suffix}`, entry.suffix);
} catch (cause: unknown) {
if (
cause instanceof Error &&
@@ -285,27 +279,30 @@ export class DyldSharedCache {
static async #subcacheEntries(
main: CacheFile,
parsed: ParsedHeader,
): Promise<
{
): Promise<{
/** Entries carry explicit file suffixes (dyld_subcache_entry v2). */
readonly named: boolean;
readonly entries: {
readonly suffix: string;
readonly uuid: string;
readonly vm_offset: string;
}[]
> {
if (!has(parsed, FIELD.subCacheArrayCount, 4)) return [];
}[];
}> {
if (!has(parsed, FIELD.subCacheArrayCount, 4))
return { named: false, entries: [] };
const offset = parsed.header.readUInt32LE(FIELD.subCacheArrayOffset);
const count = parsed.header.readUInt32LE(FIELD.subCacheArrayCount);
if (count === 0) return [];
// Headers that include cacheSubType use entries with an explicit file suffix.
const named = has(parsed, FIELD.cacheSubType, 4);
if (count === 0) return { named, entries: [] };
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 entries = Array.from({ length: count }, (_, index) => {
const base = index * size;
const suffix = named
? table.toString("latin1", base + 24, base + 56).replace(/\0.*$/su, "")
@@ -321,6 +318,7 @@ export class DyldSharedCache {
vm_offset: hex(table.readBigUInt64LE(base + 16)),
};
});
return { named, entries };
}
static #summary(
@@ -359,15 +357,12 @@ export class DyldSharedCache {
magic: parsed.magic,
architecture: parsed.magic.slice(MAGIC_PREFIX.length).trim(),
uuid: parsed.uuid,
platform:
platform === null
? null
: { id: platform, name: PLATFORMS[platform] ?? null },
platform: platform === null ? null : applePlatform(platform),
os_version: version(u32(FIELD.osVersion) ?? 0),
alt_platform:
altPlatform === null || altPlatform === 0
? null
: { id: altPlatform, name: PLATFORMS[altPlatform] ?? null },
: applePlatform(altPlatform),
alt_os_version: version(u32(FIELD.altOsVersion) ?? 0),
cache_type:
cacheType === 0
@@ -430,6 +425,23 @@ export class DyldSharedCache {
return this.#byPath.get(path);
}
/**
* Whether an install path is listed and its bytes lie in a mapping of the
* main file or a subcache whose UUID matched.
*/
locate(path: string): "mapped" | "unverified" | "absent" {
const image = this.find(path);
if (image === undefined) return "absent";
return this.#region(image.address) === undefined ? "unverified" : "mapped";
}
#region(address: number) {
return this.regions.find(
(region) =>
address >= region.address && address < region.address + region.size,
);
}
/** Parse one cached image's load commands through the cache's VM mappings. */
async imageFacts(
path: string,
@@ -438,10 +450,7 @@ export class DyldSharedCache {
> {
const image = this.find(path);
if (image === undefined) return undefined;
const region = this.regions.find(
({ address, size }) =>
image.address >= address && image.address < address + size,
);
const region = this.#region(image.address);
if (region === undefined) return undefined;
const base = region.fileOffset + (image.address - region.address);
const available = region.size - (image.address - region.address);
+9 -2
View File
@@ -8,6 +8,7 @@ import {
dylibResolutionResultSchema,
traceDylibLoading,
type DylibResolutionResult,
type DylibSharedCacheView,
type DylibTreeEntry,
type DylibTreeView,
type MachoImageFacts,
@@ -167,9 +168,15 @@ const openSharedCache = async (
}
};
const sharedCacheView = (cache: DyldSharedCache) => ({
const sharedCacheView = (cache: DyldSharedCache): DylibSharedCacheView => ({
architecture: cache.header.architecture,
has: (path: string): boolean => cache.find(path) !== undefined,
platforms: [cache.header.platform, cache.header.alt_platform].filter(
(platform) => platform !== null,
),
unavailableSubcaches: cache.header.subcaches
.filter(({ status }) => status !== "present")
.map(({ suffix, status }) => `${suffix} (${status})`),
lookup: (path) => cache.locate(path),
});
/**
+13
View File
@@ -10,6 +10,7 @@ export const LC = {
RPATH: 0x8000001c,
DYLD_ENVIRONMENT: 0x27,
CODE_SIGNATURE: 0x1d,
BUILD_VERSION: 0x32,
} as const;
export const CPU = {
@@ -75,6 +76,18 @@ export const codeSignatureCommand = (): Uint8Array => {
return bytes;
};
/** `build_version_command` for a `PLATFORM_*` value, with no tools. */
export const buildVersionCommand = (platform: number): Uint8Array => {
const bytes = new Uint8Array(24);
const view = new DataView(bytes.buffer);
view.setUint32(0, LC.BUILD_VERSION, true);
view.setUint32(4, 24, true);
view.setUint32(8, platform, true);
view.setUint32(12, 0x000f0000, true);
view.setUint32(16, 0x001a0000, true);
return bytes;
};
/** A 64-bit (or 32-bit) little-endian Mach-O image made of the given commands. */
export const machoImage = (options: {
readonly cpu?: { readonly type: number; readonly subtype: number };
@@ -4,6 +4,7 @@ import {
CPU,
FILE_TYPE,
LC,
buildVersionCommand,
codeSignatureCommand,
dyldEnvironmentCommand,
dylibCommand,
@@ -40,6 +41,9 @@ describe("Mach-O load command reader", () => {
rpathCommand("/usr/lib/swift"),
dyldEnvironmentCommand("DYLD_FRAMEWORK_PATH=@executable_path"),
codeSignatureCommand(),
// A zippered image builds for macOS and Mac Catalyst.
buildVersionCommand(1),
buildVersionCommand(6),
],
});
const facts = await read(image);
@@ -54,6 +58,10 @@ describe("Mach-O load command reader", () => {
rpaths: ["@loader_path/Frameworks", "/usr/lib/swift"],
dyld_environment: ["DYLD_FRAMEWORK_PATH=@executable_path"],
code_signature_present: true,
platforms: [
{ id: 1, name: "macos" },
{ id: 6, name: "maccatalyst" },
],
});
expect(
slice?.dependencies.map(
@@ -166,6 +174,27 @@ describe("Mach-O load command reader", () => {
});
describe("Mach-O load command reader inputs", () => {
it("reads platforms from LC_VERSION_MIN_* and keeps unknown ids", async () => {
const versionMin = new Uint8Array(16);
const view = new DataView(versionMin.buffer);
view.setUint32(0, 0x25, true);
view.setUint32(4, 16, true);
const facts = await read(
machoImage({ commands: [versionMin, buildVersionCommand(99)] }),
);
expect(facts.status === "parsed" && facts.slices[0]?.platforms).toEqual([
{ id: 2, name: "ios" },
{ id: 99, name: null },
]);
const short = new Uint8Array(8);
new DataView(short.buffer).setUint32(0, LC.BUILD_VERSION, true);
new DataView(short.buffer).setUint32(4, 8, true);
expect(await read(machoImage({ commands: [short] }))).toEqual({
status: "malformed",
reason: "load command 0 is too short for a platform version",
});
});
it("names 32-bit and non-Mach-O inputs without guessing", async () => {
const i386 = await read(
machoImage({ cpu: { type: 7, subtype: 3 }, wide: false }),
+22
View File
@@ -1,3 +1,4 @@
import { applePlatform } from "../domain/applePlatforms.js";
import type {
MachoDependency,
MachoImageFacts,
@@ -34,6 +35,14 @@ const LC_LOAD_UPWARD_DYLIB = 0x80000023;
const LC_RPATH = 0x8000001c;
const LC_DYLD_ENVIRONMENT = 0x27;
const LC_CODE_SIGNATURE = 0x1d;
const LC_BUILD_VERSION = 0x32;
/** LC_VERSION_MIN_* commands imply their platform. */
const VERSION_MIN_PLATFORMS: ReadonlyMap<number, number> = new Map([
[0x24, 1],
[0x25, 2],
[0x2f, 3],
[0x30, 4],
]);
/** `mach-o/loader.h` `dylib_use_command`: `nameoff == 28` and this marker. */
const DYLIB_USE_MARKER = 0x1a741800;
@@ -238,6 +247,7 @@ const decodeCommands = (
rpaths: [],
dyld_environment: [],
code_signature_present: false,
platforms: [],
};
let offset = 0;
for (let index = 0; index < header.commandCount; index++) {
@@ -282,6 +292,18 @@ const decodeCommand = (
slice.code_signature_present = true;
return;
}
const implied = VERSION_MIN_PLATFORMS.get(command);
if (command === LC_BUILD_VERSION || implied !== undefined) {
if (body.byteLength < 12)
throw new MachoFormatIssue(
"malformed",
`load command ${index} is too short for a platform version`,
);
const id = implied ?? viewOf(body).getUint32(8, true);
if (!slice.platforms.some((platform) => platform.id === id))
slice.platforms.push(applePlatform(id));
return;
}
const name = DEPENDENCY_COMMANDS.get(command);
if (name !== undefined)
slice.dependencies.push(decodeDependency(name, body, index));