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:
co-authored by
Claude Opus 5.5
parent
202661f83b
commit
305474df6c
@@ -154,13 +154,13 @@ parser coverage, such as big-endian images), `architecture-missing`,
|
||||
`outside-target`, `shared-cache`, `escapes-target`, or `undetermined`. Slices follow dyld's
|
||||
graded architectures, so an `x86_64h` process also loads `x86_64`. The edge's `resolution` is one of:
|
||||
|
||||
| Status | Meaning |
|
||||
| -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `resolved` | An image inside the analyzed root loads, and no earlier candidate was undeterminable. |
|
||||
| `conditional` | An image inside the root resolves, but an earlier candidate outside the root (for example `/usr/lib/swift`) would win if it exists on the running system. |
|
||||
| `unresolved` | Every candidate is definitively absent or unusable inside the root. |
|
||||
| `undetermined` | No candidate resolves inside the root, and some candidate lies outside it or depends on the environment. |
|
||||
| `shared-cache` | An absolute install path, or an `@rpath` candidate outside the root, was found in the dyld shared cache passed as `shared_cache` (CLI `--shared-cache`). dyld loads the cached image, so later in-root candidates are unused. |
|
||||
| Status | Meaning |
|
||||
| -------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `resolved` | An image inside the analyzed root loads, and no earlier candidate was undeterminable. |
|
||||
| `conditional` | An image inside the root, or in the supplied shared cache, resolves, but an earlier candidate that REA cannot decide (for example `/opt/vendor/lib` or `/usr/lib/swift` without a cache) would win if it exists on the running system. |
|
||||
| `unresolved` | Every candidate is definitively absent or unusable inside the root. |
|
||||
| `undetermined` | No candidate resolves inside the root, and some candidate lies outside it or depends on the environment. |
|
||||
| `shared-cache` | An absolute install path, or an `@rpath` candidate outside the root, was found in the dyld shared cache passed as `shared_cache` (CLI `--shared-cache`). dyld loads the cached image, so later in-root candidates are unused. |
|
||||
|
||||
Absolute install names such as `/usr/lib/libSystem.B.dylib` are
|
||||
`outside-target`. On macOS 11 and later most of them live in the dyld shared
|
||||
@@ -180,11 +180,22 @@ cache rather than on disk, so REA does not check them against the host.
|
||||
image. It also compares the predicted load order of two process roots with the
|
||||
images dyld actually loads (`DYLD_PRINT_LIBRARIES`).
|
||||
|
||||
With `shared_cache`, absolute candidates are looked up in that cache's image list.
|
||||
This only happens when the cache serves the process's CPU family: an arm64e
|
||||
cache serves arm64 and arm64e processes. The result's `shared_cache` names the
|
||||
cache path, UUID, architecture and OS version. Cached images are not traversed.
|
||||
Without a cache, system paths stay `undetermined`.
|
||||
With `shared_cache`, absolute candidates are looked up in that cache's image
|
||||
list. A process uses the cache only when both of these hold:
|
||||
|
||||
- the cache serves its CPU family (an arm64e cache serves arm64 and arm64e);
|
||||
- one of its `LC_BUILD_VERSION` or `LC_VERSION_MIN_*` platforms (reported per
|
||||
slice as `platforms`) matches the cache's platform or alternate platform.
|
||||
|
||||
An iOS cache extracted from an IPSW is therefore not used for a macOS
|
||||
executable. A limitation names each process root the cache was not used for,
|
||||
and why. The result's `shared_cache` names the cache path, UUID, architecture
|
||||
and OS version. Cached images are not traversed.
|
||||
|
||||
An image listed in the cache but mapped in a missing or UUID-mismatched
|
||||
subcache is `undetermined`. It is listed in
|
||||
`coverage.unverified_shared_cache_images` and makes coverage partial. Without a
|
||||
cache, system paths stay `undetermined`.
|
||||
|
||||
## dyld shared cache
|
||||
|
||||
|
||||
@@ -677,9 +677,9 @@
|
||||
"mcp_prompts": 6
|
||||
},
|
||||
"digests": {
|
||||
"tools_sha256": "be8eeb3bf69c3093848cc410221f9c5a79b7f94b9079d0fe5ca9085216383d8d",
|
||||
"tools_sha256": "696d7cd44d8b2be6a8f03c11760de2bec5fc0cd5170d2dfe697076ab025ceea7",
|
||||
"prompts_sha256": "ef2de8814390b340623c32001610aa2709d90bed51537b6e562ab3abf144ab4d",
|
||||
"combined_sha256": "8d0b94ffbc1034a7fa9f3d42da1cd3cd0b758d09602b64f872d80dfd33b9e5cb",
|
||||
"combined_sha256": "f8946c1a0c1084e431e313a8c2b3585ff0838bd8e6c0d33ac924d1cc00410e0a",
|
||||
"providers_sha256": "14d933c5926c106e8cde60a37747e9758313fbfd651485ec96733bc608476255"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"manifest_id": "ecm_8e4ae241488b49878273e743203acbee2c1c695654d66ade1ce49dde25e8c3c6",
|
||||
"manifest_id": "ecm_f3faddc5e13549c680547c8b551770be1525f2a5f2915be1c5e8a90647d208ad",
|
||||
"verifier": {
|
||||
"id": "rea-managed-conformance",
|
||||
"version": "1"
|
||||
@@ -13,7 +13,7 @@
|
||||
"skill_digests": [
|
||||
{
|
||||
"skill_id": "reverse-engineer-anything",
|
||||
"sha256": "d3a9bb7a561b5ce617dfa1d988e4567bb602364599b5763f287555c7cd997170"
|
||||
"sha256": "cd79389c3dba83ac47ef9b819c4658626567aa049a150989d973e066c61a59c4"
|
||||
}
|
||||
],
|
||||
"claims": [
|
||||
|
||||
@@ -19,6 +19,14 @@ import {
|
||||
const exec = promisify(execFile);
|
||||
|
||||
await preflightMacosBundleFixture();
|
||||
try {
|
||||
await exec("/usr/bin/xcrun", ["--find", "dyld_info"]);
|
||||
} catch (cause) {
|
||||
throw new Error(
|
||||
"dyld shared cache verification requires dyld_info from Command Line Tools (xcrun --find dyld_info failed)",
|
||||
{ cause },
|
||||
);
|
||||
}
|
||||
|
||||
/** The cache this host's dyld uses for native processes. */
|
||||
const hostCache = async () => {
|
||||
|
||||
@@ -4,7 +4,7 @@ description: Reverse engineer native, managed, Electron/JavaScript, packaged, fi
|
||||
metadata:
|
||||
version: "29"
|
||||
tool_count: 133
|
||||
catalog_digest: "8d0b94ffbc1034a7fa9f3d42da1cd3cd0b758d09602b64f872d80dfd33b9e5cb"
|
||||
catalog_digest: "f8946c1a0c1084e431e313a8c2b3585ff0838bd8e6c0d33ac924d1cc00410e0a"
|
||||
---
|
||||
|
||||
# REA
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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),
|
||||
});
|
||||
|
||||
/**
|
||||
|
||||
@@ -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 }),
|
||||
|
||||
@@ -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));
|
||||
|
||||
@@ -92,7 +92,7 @@ export const ARTIFACT_TOOL_CONTRACTS = [
|
||||
),
|
||||
artifact(
|
||||
"trace_dylib_resolution",
|
||||
"Trace how dyld would resolve each Mach-O dylib load for the active Mach-O, or for every executable in the active .app bundle (the main app, XPC services, extensions, login items, helpers). Expands @executable_path, @loader_path, and @rpath through each process's LC_RPATH stack in dependents-first load order, and reports every candidate path with its outcome, the resolved image and digest, weak, re-export, and upward flags, and derived findings such as unresolved required loads or absent earlier @rpath candidates. Pure header parsing: nothing is executed, and absolute or system paths outside the analyzed root stay undetermined. Select roots or one architecture to narrow large bundles.",
|
||||
"Trace how dyld would resolve each Mach-O dylib load for the active Mach-O, or for every executable in the active .app bundle (the main app, XPC services, extensions, login items, helpers). Expands @executable_path, @loader_path, and @rpath through each process's LC_RPATH stack in dependents-first load order, and reports every candidate path with its outcome, the resolved image and digest, weak, re-export, and upward flags, and derived findings such as unresolved required loads or absent earlier @rpath candidates. Pure header parsing: nothing is executed. Absolute or system paths outside the analyzed root stay outside-target unless shared_cache names a dyld shared cache for the process's CPU family and platform; listed images then resolve to shared-cache. Select roots or one architecture to narrow large bundles.",
|
||||
dylibResolutionInputSchema,
|
||||
),
|
||||
] as const satisfies readonly ToolContract[];
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import { z } from "zod";
|
||||
|
||||
/** `PLATFORM_*` values from Apple's `mach-o/loader.h`. */
|
||||
const APPLE_PLATFORM_NAMES: 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",
|
||||
};
|
||||
|
||||
/** A reported platform number and its `loader.h` name, when known. */
|
||||
export const applePlatformSchema = z.strictObject({
|
||||
id: z.number().int(),
|
||||
name: z.string().nullable(),
|
||||
});
|
||||
|
||||
export type ApplePlatform = z.infer<typeof applePlatformSchema>;
|
||||
|
||||
/** Name a reported platform number without discarding unknown values. */
|
||||
export const applePlatform = (id: number): ApplePlatform => ({
|
||||
id,
|
||||
name: APPLE_PLATFORM_NAMES[id] ?? null,
|
||||
});
|
||||
|
||||
/** Display one platform, falling back to its number. */
|
||||
export const applePlatformLabel = ({ id, name }: ApplePlatform): string =>
|
||||
name ?? `platform ${id}`;
|
||||
@@ -1,5 +1,6 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import { applePlatformSchema } from "./applePlatforms.js";
|
||||
import { digestSchema } from "./digests.js";
|
||||
import { machoSliceSchema } from "./dylibResolution.js";
|
||||
|
||||
@@ -7,10 +8,6 @@ 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({
|
||||
@@ -39,9 +36,9 @@ const headerSchema = z.object({
|
||||
magic: z.string(),
|
||||
architecture: z.string(),
|
||||
uuid: z.string(),
|
||||
platform: platformSchema.nullable(),
|
||||
platform: applePlatformSchema.nullable(),
|
||||
os_version: z.string().nullable(),
|
||||
alt_platform: platformSchema.nullable(),
|
||||
alt_platform: applePlatformSchema.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(),
|
||||
|
||||
@@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
traceDylibLoading,
|
||||
type DylibSharedCacheView,
|
||||
type DylibTreeEntry,
|
||||
type DylibTreeView,
|
||||
type MachoDependency,
|
||||
@@ -17,6 +18,7 @@ const slice = (overrides: Partial<MachoSlice> = {}): MachoSlice => ({
|
||||
rpaths: [],
|
||||
dyld_environment: [],
|
||||
code_signature_present: true,
|
||||
platforms: [{ id: 1, name: "macos" }],
|
||||
...overrides,
|
||||
});
|
||||
|
||||
@@ -338,6 +340,7 @@ describe("dyld resolution outcomes", () => {
|
||||
status: "partial",
|
||||
unparsed_images: ["Contents/MacOS/b/lib.dylib"],
|
||||
roots_without_architecture: [],
|
||||
unverified_shared_cache_images: [],
|
||||
});
|
||||
expect(trace.images.map(({ path }) => path)).toEqual([
|
||||
MAIN,
|
||||
@@ -512,6 +515,7 @@ describe("dyld slice compatibility and coverage", () => {
|
||||
status: "partial",
|
||||
unparsed_images: [broken],
|
||||
roots_without_architecture: [],
|
||||
unverified_shared_cache_images: [],
|
||||
});
|
||||
expect(trace.images.find(({ path }) => path === broken)?.reason).toBe(
|
||||
"load command 0 has invalid cmdsize 0",
|
||||
@@ -519,16 +523,27 @@ 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),
|
||||
};
|
||||
/** A macOS arm64e cache that lists libSystem and libswiftCore. */
|
||||
const cache = (
|
||||
overrides: Partial<DylibSharedCacheView> = {},
|
||||
): DylibSharedCacheView => ({
|
||||
architecture: "arm64e",
|
||||
platforms: [
|
||||
{ id: 1, name: "macos" },
|
||||
{ id: 6, name: "maccatalyst" },
|
||||
],
|
||||
unavailableSubcaches: [],
|
||||
lookup: (path: string) =>
|
||||
[
|
||||
"/usr/lib/libSystem.B.dylib",
|
||||
"/usr/lib/swift/libswiftCore.dylib",
|
||||
].includes(path)
|
||||
? "mapped"
|
||||
: "absent",
|
||||
...overrides,
|
||||
});
|
||||
|
||||
describe("shared cache resolution", () => {
|
||||
it("resolves cached system paths before bundled fallbacks", async () => {
|
||||
const trace = await traceDylibLoading(
|
||||
memoryView({
|
||||
@@ -542,7 +557,7 @@ describe("shared cache resolution", () => {
|
||||
}),
|
||||
"Contents/Frameworks/libswiftCore.dylib": parsed(slice()),
|
||||
}),
|
||||
{ roots: [MAIN], sharedCache: cache },
|
||||
{ roots: [MAIN], sharedCache: cache() },
|
||||
);
|
||||
expect(
|
||||
trace.edges.map(({ install_name: name, resolution, candidates }) => [
|
||||
@@ -568,24 +583,118 @@ describe("shared cache resolution", () => {
|
||||
],
|
||||
]);
|
||||
expect(trace.images.map(({ path }) => path)).toEqual([MAIN]);
|
||||
expect(trace.coverage.status).toBe("complete");
|
||||
expect(trace.limitations).toContainEqual(
|
||||
expect.stringContaining("looked up in the supplied dyld shared cache"),
|
||||
expect.stringContaining(
|
||||
"looked up only in the supplied dyld shared cache",
|
||||
),
|
||||
);
|
||||
expect(trace.limitations).not.toContainEqual(
|
||||
expect.stringContaining("are not evaluated, including /System"),
|
||||
);
|
||||
});
|
||||
|
||||
it("does not consult a cache for processes it cannot serve", async () => {
|
||||
it("keeps a cache hit conditional after an earlier undeterminable candidate", async () => {
|
||||
const trace = await traceDylibLoading(
|
||||
memoryView({
|
||||
[MAIN]: executable({
|
||||
rpaths: ["/opt/vendor/lib", "/usr/lib/swift"],
|
||||
dependencies: [dependency("@rpath/libswiftCore.dylib")],
|
||||
}),
|
||||
}),
|
||||
{ roots: [MAIN], sharedCache: cache() },
|
||||
);
|
||||
expect(trace.edges[0]?.resolution).toEqual({
|
||||
status: "conditional",
|
||||
image: "/usr/lib/swift/libswiftCore.dylib",
|
||||
});
|
||||
expect(trace.edges[0]?.candidates.map(({ outcome }) => outcome)).toEqual([
|
||||
"outside-target",
|
||||
"shared-cache",
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("shared cache applicability", () => {
|
||||
it("does not consult a cache for another CPU family or platform", async () => {
|
||||
const trace = await traceDylibLoading(
|
||||
memoryView({
|
||||
[MAIN]: executable({
|
||||
architecture: "x86_64",
|
||||
dependencies: [dependency("/usr/lib/libSystem.B.dylib")],
|
||||
}),
|
||||
"Contents/MacOS/Phone": executable({
|
||||
platforms: [{ id: 2, name: "ios" }],
|
||||
dependencies: [dependency("/usr/lib/libSystem.B.dylib")],
|
||||
}),
|
||||
"Contents/MacOS/Old": executable({
|
||||
platforms: [],
|
||||
dependencies: [dependency("/usr/lib/libSystem.B.dylib")],
|
||||
}),
|
||||
}),
|
||||
{ roots: [MAIN], sharedCache: cache },
|
||||
{
|
||||
roots: [MAIN, "Contents/MacOS/Phone", "Contents/MacOS/Old"],
|
||||
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.",
|
||||
expect(trace.edges.map(({ candidates }) => candidates[0]?.outcome)).toEqual(
|
||||
["outside-target", "outside-target", "outside-target"],
|
||||
);
|
||||
expect(trace.limitations).toEqual(
|
||||
expect.arrayContaining([
|
||||
`The supplied shared cache was not used for ${MAIN} (x86_64): the arm64e cache does not serve x86_64 processes. Its absolute paths stay outside-target.`,
|
||||
"The supplied shared cache was not used for Contents/MacOS/Phone (arm64): the cache serves macos and maccatalyst processes, not ios. Its absolute paths stay outside-target.",
|
||||
"The supplied shared cache was not used for Contents/MacOS/Old (arm64): the process records no LC_BUILD_VERSION or LC_VERSION_MIN platform. Its absolute paths stay outside-target.",
|
||||
]),
|
||||
);
|
||||
const unknownPlatform = await traceDylibLoading(
|
||||
memoryView({
|
||||
[MAIN]: executable({
|
||||
dependencies: [dependency("/usr/lib/libSystem.B.dylib")],
|
||||
}),
|
||||
}),
|
||||
{ roots: [MAIN], sharedCache: cache({ platforms: [] }) },
|
||||
);
|
||||
expect(unknownPlatform.edges[0]?.candidates[0]?.outcome).toBe(
|
||||
"outside-target",
|
||||
);
|
||||
});
|
||||
|
||||
it("leaves images in unavailable subcaches undetermined", async () => {
|
||||
const trace = await traceDylibLoading(
|
||||
memoryView({
|
||||
[MAIN]: executable({
|
||||
dependencies: [dependency("/usr/lib/libSystem.B.dylib")],
|
||||
}),
|
||||
}),
|
||||
{
|
||||
roots: [MAIN],
|
||||
sharedCache: cache({
|
||||
unavailableSubcaches: [".01 (missing)"],
|
||||
lookup: () => "unverified",
|
||||
}),
|
||||
},
|
||||
);
|
||||
expect(trace.edges[0]?.resolution).toEqual({
|
||||
status: "undetermined",
|
||||
image: null,
|
||||
});
|
||||
expect(trace.coverage).toMatchObject({
|
||||
status: "partial",
|
||||
unverified_shared_cache_images: ["/usr/lib/libSystem.B.dylib"],
|
||||
});
|
||||
expect(trace.limitations).toContainEqual(
|
||||
expect.stringContaining("Subcaches .01 (missing)"),
|
||||
);
|
||||
});
|
||||
|
||||
it("states that absolute paths are not evaluated without a cache", async () => {
|
||||
const trace = await traceDylibLoading(
|
||||
memoryView({ [MAIN]: executable({}) }),
|
||||
{ roots: [MAIN] },
|
||||
);
|
||||
expect(trace.limitations).toContainEqual(
|
||||
expect.stringContaining("Pass shared_cache"),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
+72
-201
@@ -1,7 +1,4 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import {
|
||||
cacheServes,
|
||||
compatibleSlice,
|
||||
directoryOf,
|
||||
expandPrefix,
|
||||
@@ -9,197 +6,44 @@ import {
|
||||
resolveTreePath,
|
||||
type Expansion,
|
||||
} from "./dyldPaths.js";
|
||||
import { digestSchema } from "./digests.js";
|
||||
import {
|
||||
DYLIB_RESOLUTION_LIMITATIONS,
|
||||
deriveFindings,
|
||||
cacheMismatch,
|
||||
sharedCacheLimitations,
|
||||
type UnservedRoot,
|
||||
} from "./dylibResolutionFindings.js";
|
||||
import type {
|
||||
MachoDependency,
|
||||
MachoSlice,
|
||||
MachoImageFacts,
|
||||
DylibTreeView,
|
||||
DylibSharedCacheView,
|
||||
DylibCandidate,
|
||||
DylibEdge,
|
||||
DylibTrace,
|
||||
} from "./dylibResolutionSchema.js";
|
||||
|
||||
/** Normalized path below the analyzed root: no `.`/`..` or empty segments. */
|
||||
const ROOT_RELATIVE_PATH =
|
||||
/^(?!\/)(?!(?:.*\/)?\.{1,2}(?:\/|$))(?!.*\/\/)(?!.*\/$)[^\\\0]+$/u;
|
||||
const rootRelativePathSchema = z.string().min(1).regex(ROOT_RELATIVE_PATH);
|
||||
export {
|
||||
dylibResolutionInputSchema,
|
||||
machoSliceSchema,
|
||||
dylibResolutionResultSchema,
|
||||
type MachoDependency,
|
||||
type MachoSlice,
|
||||
type MachoImageFacts,
|
||||
type DylibTreeEntry,
|
||||
type DylibTreeView,
|
||||
type DylibSharedCacheView,
|
||||
type DylibResolutionResult,
|
||||
type DylibCandidate,
|
||||
type DylibEdge,
|
||||
type DylibFinding,
|
||||
type DylibTrace,
|
||||
} from "./dylibResolutionSchema.js";
|
||||
|
||||
/** Caller selection of process roots and one CPU slice. */
|
||||
export const dylibResolutionInputSchema = z.strictObject({
|
||||
roots: z.array(rootRelativePathSchema).min(1).optional(),
|
||||
architecture: z.enum(["arm64", "arm64e", "x86_64"]).optional(),
|
||||
/** Main dyld shared cache file whose image list answers system install paths. */
|
||||
shared_cache: z.string().min(1).optional(),
|
||||
});
|
||||
|
||||
const dependencyCommandSchema = z.enum([
|
||||
"LC_LOAD_DYLIB",
|
||||
"LC_LOAD_WEAK_DYLIB",
|
||||
"LC_REEXPORT_DYLIB",
|
||||
"LC_LAZY_LOAD_DYLIB",
|
||||
"LC_LOAD_UPWARD_DYLIB",
|
||||
]);
|
||||
|
||||
const dependencySchema = z.strictObject({
|
||||
command: dependencyCommandSchema,
|
||||
encoding: z.enum(["dylib_command", "dylib_use_command"]),
|
||||
install_name: z.string(),
|
||||
weak: z.boolean(),
|
||||
upward: z.boolean(),
|
||||
reexport: z.boolean(),
|
||||
delayed_init: z.boolean(),
|
||||
current_version: z.string(),
|
||||
compatibility_version: z.string(),
|
||||
});
|
||||
|
||||
/** Observed dylib-loading facts of one Mach-O slice. */
|
||||
export const machoSliceSchema = z.strictObject({
|
||||
architecture: z.string().min(1),
|
||||
file_type: z.enum(["execute", "dylib", "bundle", "other"]),
|
||||
install_name: z.string().nullable(),
|
||||
dependencies: z.array(dependencySchema),
|
||||
rpaths: z.array(z.string()),
|
||||
dyld_environment: z.array(z.string()),
|
||||
code_signature_present: z.boolean(),
|
||||
});
|
||||
|
||||
export type MachoDependency = z.infer<typeof dependencySchema>;
|
||||
export type MachoSlice = z.infer<typeof machoSliceSchema>;
|
||||
|
||||
/** Header parse of one file; malformed and unsupported images keep their reason. */
|
||||
export type MachoImageFacts =
|
||||
| { readonly status: "parsed"; readonly slices: readonly MachoSlice[] }
|
||||
| {
|
||||
readonly status: "malformed" | "unsupported";
|
||||
readonly reason: string;
|
||||
}
|
||||
| { readonly status: "not-mach-o" };
|
||||
|
||||
/** One observed path below the analyzed root. Symlink targets are not followed by the view. */
|
||||
export type DylibTreeEntry =
|
||||
| { readonly kind: "file" | "directory" }
|
||||
| { readonly kind: "symlink"; readonly target: string };
|
||||
|
||||
/** Read-only, lazily probed view of the analyzed root. Paths are root-relative. */
|
||||
export interface DylibTreeView {
|
||||
entry(path: string): Promise<DylibTreeEntry | undefined>;
|
||||
image(path: string): Promise<MachoImageFacts>;
|
||||
}
|
||||
|
||||
/** 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([
|
||||
"literal",
|
||||
"executable_path",
|
||||
"loader_path",
|
||||
"rpath",
|
||||
"already-loaded",
|
||||
]),
|
||||
rpath: z.string().nullable(),
|
||||
rpath_owner: z.string().nullable(),
|
||||
outcome: z.enum([
|
||||
"resolved",
|
||||
"absent",
|
||||
"not-mach-o",
|
||||
"malformed",
|
||||
"unsupported",
|
||||
"architecture-missing",
|
||||
"outside-target",
|
||||
"shared-cache",
|
||||
"escapes-target",
|
||||
"undetermined",
|
||||
]),
|
||||
resolved_path: z.string().nullable(),
|
||||
});
|
||||
|
||||
const edgeSchema = z.strictObject({
|
||||
root: z.string(),
|
||||
architecture: z.string(),
|
||||
loader: z.string(),
|
||||
via: z.array(z.string()),
|
||||
...dependencySchema.shape,
|
||||
candidates: z.array(candidateSchema),
|
||||
resolution: z.strictObject({
|
||||
status: z.enum([
|
||||
"resolved",
|
||||
"conditional",
|
||||
"shared-cache",
|
||||
"unresolved",
|
||||
"undetermined",
|
||||
]),
|
||||
image: z.string().nullable(),
|
||||
}),
|
||||
install_name_matches: z.boolean().nullable(),
|
||||
});
|
||||
|
||||
const findingSchema = z.strictObject({
|
||||
kind: z.enum([
|
||||
"required-load-unresolved",
|
||||
"weak-load-unresolved",
|
||||
"lazy-load-unresolved",
|
||||
"earlier-rpath-candidate-absent",
|
||||
"dyld-environment-present",
|
||||
]),
|
||||
edge_index: z.number().int().nonnegative().nullable(),
|
||||
image: z.string().nullable(),
|
||||
basis: z.literal("derived"),
|
||||
explanation: z.string().min(1),
|
||||
});
|
||||
|
||||
const imageSchema = z.strictObject({
|
||||
path: z.string(),
|
||||
sha256: digestSchema,
|
||||
parse_status: z.enum(["parsed", "malformed", "unsupported"]),
|
||||
reason: z.string().nullable(),
|
||||
slices: z.array(machoSliceSchema.omit({ dependencies: true })),
|
||||
});
|
||||
|
||||
/** Static dyld load-path resolution for every selected process root. */
|
||||
export const dylibResolutionResultSchema = z.strictObject({
|
||||
root_path: z.string(),
|
||||
target_sha256: digestSchema,
|
||||
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() }),
|
||||
),
|
||||
images: z.array(imageSchema),
|
||||
edges: z.array(edgeSchema),
|
||||
findings: z.array(findingSchema),
|
||||
coverage: z.strictObject({
|
||||
status: z.enum(["complete", "partial"]),
|
||||
unparsed_images: z.array(z.string()),
|
||||
roots_without_architecture: z.array(z.string()),
|
||||
}),
|
||||
limitations: z.array(z.string().min(1)),
|
||||
});
|
||||
|
||||
export type DylibResolutionResult = z.infer<typeof dylibResolutionResultSchema>;
|
||||
type Candidate = z.infer<typeof candidateSchema>;
|
||||
export type DylibEdge = z.infer<typeof edgeSchema>;
|
||||
export type DylibFinding = z.infer<typeof findingSchema>;
|
||||
type Candidate = DylibCandidate;
|
||||
type Edge = DylibEdge;
|
||||
|
||||
/** Result before the adapter adds file digests and the analyzed root. */
|
||||
export type DylibTrace = Omit<
|
||||
DylibResolutionResult,
|
||||
"root_path" | "target_sha256" | "shared_cache" | "images"
|
||||
> & {
|
||||
readonly images: readonly (Omit<
|
||||
DylibResolutionResult["images"][number],
|
||||
"sha256"
|
||||
> & { readonly sha256?: never })[];
|
||||
};
|
||||
|
||||
interface LoadedImage {
|
||||
readonly slice: MachoSlice;
|
||||
/** Images from the process root to this image; the rpath stack, outermost first. */
|
||||
@@ -214,8 +58,10 @@ 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. */
|
||||
/** The supplied cache, when it serves this process's architecture and platform. */
|
||||
readonly sharedCache: DylibSharedCacheView | undefined;
|
||||
/** Cached install paths whose subcache bytes were unavailable, across processes. */
|
||||
readonly unverifiedCacheImages: Set<string>;
|
||||
}
|
||||
|
||||
interface CandidateTemplate {
|
||||
@@ -279,14 +125,22 @@ const evaluateCandidate = async (
|
||||
rpath: template.rpath,
|
||||
rpath_owner: template.rpathOwner,
|
||||
};
|
||||
if (template.expansion.scope === "outside")
|
||||
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 === "outside") {
|
||||
const cached =
|
||||
context.sharedCache?.lookup(template.expansion.path) ?? "absent";
|
||||
if (cached === "mapped")
|
||||
return {
|
||||
...base,
|
||||
outcome: "shared-cache",
|
||||
resolved_path: template.expansion.path,
|
||||
};
|
||||
// Listed in the cache, but its subcache is unavailable: dyld might load it.
|
||||
if (cached === "unverified") {
|
||||
context.unverifiedCacheImages.add(template.expansion.path);
|
||||
return { ...base, outcome: "undetermined", resolved_path: null };
|
||||
}
|
||||
return { ...base, outcome: "outside-target", resolved_path: null };
|
||||
}
|
||||
if (template.expansion.scope === "undetermined")
|
||||
return { ...base, outcome: "undetermined", resolved_path: null };
|
||||
const lookup = await resolveTreePath(context.view, template.expansion.path);
|
||||
@@ -324,7 +178,10 @@ const resolution = (candidates: readonly Candidate[]): Edge["resolution"] => {
|
||||
image: candidate.resolved_path,
|
||||
};
|
||||
if (candidate.outcome === "shared-cache")
|
||||
return { status: "shared-cache", image: candidate.resolved_path };
|
||||
return {
|
||||
status: external ? "conditional" : "shared-cache",
|
||||
image: candidate.resolved_path,
|
||||
};
|
||||
// dyld might load these; REA cannot decide them from the analyzed root.
|
||||
if (
|
||||
candidate.outcome === "outside-target" ||
|
||||
@@ -451,6 +308,8 @@ export const traceDylibLoading = async (
|
||||
const roots: DylibTrace["roots"][number][] = [];
|
||||
const edges: Edge[] = [];
|
||||
const withoutArchitecture: string[] = [];
|
||||
const unserved: UnservedRoot[] = [];
|
||||
const unverifiedCacheImages = new Set<string>();
|
||||
for (const root of request.roots) {
|
||||
const facts = await view.image(root);
|
||||
images.set(root, facts);
|
||||
@@ -463,6 +322,16 @@ export const traceDylibLoading = async (
|
||||
if (slices.length === 0) withoutArchitecture.push(root);
|
||||
for (const slice of slices) {
|
||||
roots.push({ image: root, architecture: slice.architecture });
|
||||
const mismatch =
|
||||
request.sharedCache === undefined
|
||||
? undefined
|
||||
: cacheMismatch(request.sharedCache, slice);
|
||||
if (mismatch !== undefined)
|
||||
unserved.push({
|
||||
image: root,
|
||||
architecture: slice.architecture,
|
||||
reason: mismatch,
|
||||
});
|
||||
edges.push(
|
||||
...(await traceProcess(
|
||||
{
|
||||
@@ -474,10 +343,8 @@ export const traceDylibLoading = async (
|
||||
byInstallName: new Map(),
|
||||
images,
|
||||
sharedCache:
|
||||
request.sharedCache !== undefined &&
|
||||
cacheServes(request.sharedCache.architecture, slice.architecture)
|
||||
? request.sharedCache
|
||||
: undefined,
|
||||
mismatch === undefined ? request.sharedCache : undefined,
|
||||
unverifiedCacheImages,
|
||||
},
|
||||
slice,
|
||||
request.signal,
|
||||
@@ -508,15 +375,18 @@ export const traceDylibLoading = async (
|
||||
findings: deriveFindings(edges, roots, images),
|
||||
coverage: {
|
||||
status:
|
||||
unparsed.length === 0 && withoutArchitecture.length === 0
|
||||
unparsed.length === 0 &&
|
||||
withoutArchitecture.length === 0 &&
|
||||
unverifiedCacheImages.size === 0
|
||||
? "complete"
|
||||
: "partial",
|
||||
unparsed_images: unparsed,
|
||||
roots_without_architecture: withoutArchitecture,
|
||||
unverified_shared_cache_images: [...unverifiedCacheImages].sort(compare),
|
||||
},
|
||||
limitations: [
|
||||
...DYLIB_RESOLUTION_LIMITATIONS,
|
||||
...sharedCacheLimitations(request.sharedCache, roots),
|
||||
...sharedCacheLimitations(request.sharedCache, unserved),
|
||||
],
|
||||
};
|
||||
};
|
||||
@@ -530,6 +400,7 @@ const withoutDependencies = (
|
||||
rpaths: slice.rpaths,
|
||||
dyld_environment: slice.dyld_environment,
|
||||
code_signature_present: slice.code_signature_present,
|
||||
platforms: slice.platforms,
|
||||
});
|
||||
|
||||
const compare = (left: string, right: string): number =>
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { applePlatformLabel } from "./applePlatforms.js";
|
||||
import { cacheServes } from "./dyldPaths.js";
|
||||
import type {
|
||||
DylibEdge as Edge,
|
||||
@@ -5,6 +6,7 @@ import type {
|
||||
DylibSharedCacheView,
|
||||
DylibTrace,
|
||||
MachoImageFacts,
|
||||
MachoSlice,
|
||||
} from "./dylibResolution.js";
|
||||
|
||||
export const deriveFindings = (
|
||||
@@ -81,7 +83,6 @@ const unresolvedFinding = (edge: Edge, index: number): Finding => {
|
||||
export const DYLIB_RESOLUTION_LIMITATIONS = [
|
||||
"LC_LAZY_LOAD_DYLIB dependencies are resolved but not traversed, because dyld loads them only on first use.",
|
||||
"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.",
|
||||
@@ -89,26 +90,54 @@ export const DYLIB_RESOLUTION_LIMITATIONS = [
|
||||
"Dylib compatibility versions are not compared. Apple's linker documentation describes a load-time rejection when an image's compatibility version is older than the loader requires, but dyld on macOS 26 was observed to load such an image.",
|
||||
];
|
||||
|
||||
/** A process root the supplied shared cache cannot answer for. */
|
||||
export interface UnservedRoot {
|
||||
readonly image: string;
|
||||
readonly architecture: string;
|
||||
readonly reason: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Why the cache cannot serve a process slice, or undefined when it can:
|
||||
* dyld maps only a cache built for the process's CPU family and platform.
|
||||
*/
|
||||
export const cacheMismatch = (
|
||||
cache: DylibSharedCacheView,
|
||||
slice: Pick<MachoSlice, "architecture" | "platforms">,
|
||||
): string | undefined => {
|
||||
if (!cacheServes(cache.architecture, slice.architecture))
|
||||
return `the ${cache.architecture} cache does not serve ${slice.architecture} processes`;
|
||||
if (cache.platforms.length === 0)
|
||||
return "the cache header does not record its platform";
|
||||
if (slice.platforms.length === 0)
|
||||
return "the process records no LC_BUILD_VERSION or LC_VERSION_MIN platform";
|
||||
if (
|
||||
!slice.platforms.some(({ id }) =>
|
||||
cache.platforms.some((platform) => platform.id === id),
|
||||
)
|
||||
)
|
||||
return `the cache serves ${cache.platforms.map(applePlatformLabel).join(" and ")} processes, not ${slice.platforms.map(applePlatformLabel).join(" or ")}`;
|
||||
return undefined;
|
||||
};
|
||||
|
||||
export const sharedCacheLimitations = (
|
||||
cache: DylibSharedCacheView | undefined,
|
||||
roots: DylibTrace["roots"],
|
||||
unserved: readonly UnservedRoot[],
|
||||
): string[] => {
|
||||
if (cache === undefined) return [];
|
||||
const unserved = [
|
||||
...new Set(
|
||||
roots
|
||||
.map(({ architecture }) => architecture)
|
||||
.filter(
|
||||
(architecture) => !cacheServes(cache.architecture, architecture),
|
||||
),
|
||||
),
|
||||
];
|
||||
if (cache === undefined)
|
||||
return [
|
||||
"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. Pass shared_cache to look them up in a cache.",
|
||||
];
|
||||
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
|
||||
"Absolute install names and rpaths were looked up only in the supplied dyld shared cache; paths it does not list stay outside-target because the host filesystem outside the analyzed root is not read. On another OS build the cache contents, and therefore these outcomes, can differ.",
|
||||
...unserved.map(
|
||||
({ image, architecture, reason }) =>
|
||||
`The supplied shared cache was not used for ${image} (${architecture}): ${reason}. Its absolute paths stay outside-target.`,
|
||||
),
|
||||
...(cache.unavailableSubcaches.length === 0
|
||||
? []
|
||||
: [
|
||||
`The ${cache.architecture} shared cache does not serve ${unserved.join(", ")} processes; their system paths stay undetermined.`,
|
||||
`Subcaches ${cache.unavailableSubcaches.join(", ")} of the supplied cache are unavailable; install paths listed there are undetermined and reported in coverage.unverified_shared_cache_images.`,
|
||||
]),
|
||||
];
|
||||
};
|
||||
|
||||
@@ -0,0 +1,199 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import { applePlatformSchema, type ApplePlatform } from "./applePlatforms.js";
|
||||
import { digestSchema } from "./digests.js";
|
||||
|
||||
/** Normalized path below the analyzed root: no `.`/`..` or empty segments. */
|
||||
const ROOT_RELATIVE_PATH =
|
||||
/^(?!\/)(?!(?:.*\/)?\.{1,2}(?:\/|$))(?!.*\/\/)(?!.*\/$)[^\\\0]+$/u;
|
||||
const rootRelativePathSchema = z.string().min(1).regex(ROOT_RELATIVE_PATH);
|
||||
|
||||
/** Caller selection of process roots and one CPU slice. */
|
||||
export const dylibResolutionInputSchema = z.strictObject({
|
||||
roots: z.array(rootRelativePathSchema).min(1).optional(),
|
||||
architecture: z.enum(["arm64", "arm64e", "x86_64"]).optional(),
|
||||
/** Main dyld shared cache file whose image list answers system install paths. */
|
||||
shared_cache: z.string().min(1).optional(),
|
||||
});
|
||||
|
||||
const dependencyCommandSchema = z.enum([
|
||||
"LC_LOAD_DYLIB",
|
||||
"LC_LOAD_WEAK_DYLIB",
|
||||
"LC_REEXPORT_DYLIB",
|
||||
"LC_LAZY_LOAD_DYLIB",
|
||||
"LC_LOAD_UPWARD_DYLIB",
|
||||
]);
|
||||
|
||||
const dependencySchema = z.strictObject({
|
||||
command: dependencyCommandSchema,
|
||||
encoding: z.enum(["dylib_command", "dylib_use_command"]),
|
||||
install_name: z.string(),
|
||||
weak: z.boolean(),
|
||||
upward: z.boolean(),
|
||||
reexport: z.boolean(),
|
||||
delayed_init: z.boolean(),
|
||||
current_version: z.string(),
|
||||
compatibility_version: z.string(),
|
||||
});
|
||||
|
||||
/** Observed dylib-loading facts of one Mach-O slice. */
|
||||
export const machoSliceSchema = z.strictObject({
|
||||
architecture: z.string().min(1),
|
||||
file_type: z.enum(["execute", "dylib", "bundle", "other"]),
|
||||
install_name: z.string().nullable(),
|
||||
dependencies: z.array(dependencySchema),
|
||||
rpaths: z.array(z.string()),
|
||||
dyld_environment: z.array(z.string()),
|
||||
code_signature_present: z.boolean(),
|
||||
/** LC_BUILD_VERSION or LC_VERSION_MIN_* platforms; zippered images list two. */
|
||||
platforms: z.array(applePlatformSchema),
|
||||
});
|
||||
|
||||
export type MachoDependency = z.infer<typeof dependencySchema>;
|
||||
export type MachoSlice = z.infer<typeof machoSliceSchema>;
|
||||
|
||||
/** Header parse of one file; malformed and unsupported images keep their reason. */
|
||||
export type MachoImageFacts =
|
||||
| { readonly status: "parsed"; readonly slices: readonly MachoSlice[] }
|
||||
| {
|
||||
readonly status: "malformed" | "unsupported";
|
||||
readonly reason: string;
|
||||
}
|
||||
| { readonly status: "not-mach-o" };
|
||||
|
||||
/** One observed path below the analyzed root. Symlink targets are not followed by the view. */
|
||||
export type DylibTreeEntry =
|
||||
| { readonly kind: "file" | "directory" }
|
||||
| { readonly kind: "symlink"; readonly target: string };
|
||||
|
||||
/** Read-only, lazily probed view of the analyzed root. Paths are root-relative. */
|
||||
export interface DylibTreeView {
|
||||
entry(path: string): Promise<DylibTreeEntry | undefined>;
|
||||
image(path: string): Promise<MachoImageFacts>;
|
||||
}
|
||||
|
||||
/** Image list of one caller-supplied dyld shared cache. */
|
||||
export interface DylibSharedCacheView {
|
||||
readonly architecture: string;
|
||||
/** The cache's platform and alternate platform; empty when the header predates them. */
|
||||
readonly platforms: readonly ApplePlatform[];
|
||||
/** Subcaches whose bytes are missing or do not match, such as `.03 (missing)`. */
|
||||
readonly unavailableSubcaches: readonly string[];
|
||||
/**
|
||||
* `mapped`: listed and inside a verified mapping; `unverified`: listed, but
|
||||
* the subcache holding it is unavailable; `absent`: not listed.
|
||||
*/
|
||||
lookup(path: string): "mapped" | "unverified" | "absent";
|
||||
}
|
||||
|
||||
const candidateSchema = z.strictObject({
|
||||
path: z.string(),
|
||||
source: z.enum([
|
||||
"literal",
|
||||
"executable_path",
|
||||
"loader_path",
|
||||
"rpath",
|
||||
"already-loaded",
|
||||
]),
|
||||
rpath: z.string().nullable(),
|
||||
rpath_owner: z.string().nullable(),
|
||||
outcome: z.enum([
|
||||
"resolved",
|
||||
"absent",
|
||||
"not-mach-o",
|
||||
"malformed",
|
||||
"unsupported",
|
||||
"architecture-missing",
|
||||
"outside-target",
|
||||
"shared-cache",
|
||||
"escapes-target",
|
||||
"undetermined",
|
||||
]),
|
||||
resolved_path: z.string().nullable(),
|
||||
});
|
||||
|
||||
const edgeSchema = z.strictObject({
|
||||
root: z.string(),
|
||||
architecture: z.string(),
|
||||
loader: z.string(),
|
||||
via: z.array(z.string()),
|
||||
...dependencySchema.shape,
|
||||
candidates: z.array(candidateSchema),
|
||||
resolution: z.strictObject({
|
||||
status: z.enum([
|
||||
"resolved",
|
||||
"conditional",
|
||||
"shared-cache",
|
||||
"unresolved",
|
||||
"undetermined",
|
||||
]),
|
||||
image: z.string().nullable(),
|
||||
}),
|
||||
install_name_matches: z.boolean().nullable(),
|
||||
});
|
||||
|
||||
const findingSchema = z.strictObject({
|
||||
kind: z.enum([
|
||||
"required-load-unresolved",
|
||||
"weak-load-unresolved",
|
||||
"lazy-load-unresolved",
|
||||
"earlier-rpath-candidate-absent",
|
||||
"dyld-environment-present",
|
||||
]),
|
||||
edge_index: z.number().int().nonnegative().nullable(),
|
||||
image: z.string().nullable(),
|
||||
basis: z.literal("derived"),
|
||||
explanation: z.string().min(1),
|
||||
});
|
||||
|
||||
const imageSchema = z.strictObject({
|
||||
path: z.string(),
|
||||
sha256: digestSchema,
|
||||
parse_status: z.enum(["parsed", "malformed", "unsupported"]),
|
||||
reason: z.string().nullable(),
|
||||
slices: z.array(machoSliceSchema.omit({ dependencies: true })),
|
||||
});
|
||||
|
||||
/** Static dyld load-path resolution for every selected process root. */
|
||||
export const dylibResolutionResultSchema = z.strictObject({
|
||||
root_path: z.string(),
|
||||
target_sha256: digestSchema,
|
||||
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() }),
|
||||
),
|
||||
images: z.array(imageSchema),
|
||||
edges: z.array(edgeSchema),
|
||||
findings: z.array(findingSchema),
|
||||
coverage: z.strictObject({
|
||||
status: z.enum(["complete", "partial"]),
|
||||
unparsed_images: z.array(z.string()),
|
||||
roots_without_architecture: z.array(z.string()),
|
||||
/** Install paths the supplied cache lists in subcaches that were unavailable. */
|
||||
unverified_shared_cache_images: z.array(z.string()),
|
||||
}),
|
||||
limitations: z.array(z.string().min(1)),
|
||||
});
|
||||
|
||||
export type DylibResolutionResult = z.infer<typeof dylibResolutionResultSchema>;
|
||||
export type DylibCandidate = z.infer<typeof candidateSchema>;
|
||||
export type DylibEdge = z.infer<typeof edgeSchema>;
|
||||
export type DylibFinding = z.infer<typeof findingSchema>;
|
||||
|
||||
/** Result before the adapter adds file digests and the analyzed root. */
|
||||
export type DylibTrace = Omit<
|
||||
DylibResolutionResult,
|
||||
"root_path" | "target_sha256" | "shared_cache" | "images"
|
||||
> & {
|
||||
readonly images: readonly (Omit<
|
||||
DylibResolutionResult["images"][number],
|
||||
"sha256"
|
||||
> & { readonly sha256?: never })[];
|
||||
};
|
||||
File diff suppressed because one or more lines are too long
@@ -6,6 +6,7 @@ import { describe, expect } from "vitest";
|
||||
import {
|
||||
FILE_TYPE,
|
||||
LC,
|
||||
buildVersionCommand,
|
||||
dylibCommand,
|
||||
machoImage,
|
||||
rpathCommand,
|
||||
@@ -202,15 +203,23 @@ describe("trace-dylib-resolution CLI inputs", () => {
|
||||
await writeFiles(directory, {
|
||||
tool: machoImage({
|
||||
commands: [
|
||||
buildVersionCommand(1),
|
||||
dylibCommand(LC.LOAD_DYLIB, "/usr/lib/libSystem.B.dylib"),
|
||||
dylibCommand(LC.LOAD_DYLIB, "/usr/lib/libnotcached.dylib"),
|
||||
dylibCommand(LC.LOAD_DYLIB, "/usr/lib/swift/libswiftCore.dylib"),
|
||||
],
|
||||
}),
|
||||
// The .01 subcache holding libswiftCore is not written.
|
||||
dyld_shared_cache_arm64e: dyldCacheFixture([
|
||||
{
|
||||
path: "/usr/lib/libSystem.B.dylib",
|
||||
bytes: machoImage({ fileType: FILE_TYPE.dylib }),
|
||||
},
|
||||
{
|
||||
path: "/usr/lib/swift/libswiftCore.dylib",
|
||||
bytes: machoImage({ fileType: FILE_TYPE.dylib }),
|
||||
inSubcache: true,
|
||||
},
|
||||
]).main,
|
||||
});
|
||||
const result = await cli.run({
|
||||
@@ -234,7 +243,12 @@ describe("trace-dylib-resolution CLI inputs", () => {
|
||||
expect(trace.edges.map(({ resolution }) => resolution.status)).toEqual([
|
||||
"shared-cache",
|
||||
"undetermined",
|
||||
"undetermined",
|
||||
]);
|
||||
expect(trace.coverage).toMatchObject({
|
||||
status: "partial",
|
||||
unverified_shared_cache_images: ["/usr/lib/swift/libswiftCore.dylib"],
|
||||
});
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
@@ -27,13 +27,16 @@ const dylib = (installName: string, dependencies: readonly Uint8Array[] = []) =>
|
||||
commands: [dylibCommand(LC.ID_DYLIB, installName), ...dependencies],
|
||||
});
|
||||
|
||||
const writeCache = async (fixture: CacheFixture): Promise<string> => {
|
||||
const writeCache = async (
|
||||
fixture: CacheFixture,
|
||||
name = "dyld_shared_cache_arm64e",
|
||||
): Promise<string> => {
|
||||
const directory = await createTestTempDirectory("rea-dyld-cache-");
|
||||
const path = join(directory, "dyld_shared_cache_arm64e");
|
||||
await writeFile(path, fixture.main);
|
||||
const base = join(directory, "dyld_shared_cache_arm64e");
|
||||
await writeFile(join(directory, name), fixture.main);
|
||||
for (const { suffix, bytes } of fixture.subcaches)
|
||||
await writeFile(`${path}${suffix}`, bytes);
|
||||
return path;
|
||||
await writeFile(`${base}${suffix}`, bytes);
|
||||
return join(directory, name);
|
||||
};
|
||||
|
||||
const IMAGES = [
|
||||
@@ -122,6 +125,21 @@ describe("dyld shared cache inspection", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("finds a development cache's subcaches beside its base name", async () => {
|
||||
const path = await writeCache(
|
||||
dyldCacheFixture(IMAGES),
|
||||
"dyld_shared_cache_arm64e.development",
|
||||
);
|
||||
const result = await inspectDyldSharedCache({
|
||||
cache_path: path,
|
||||
images: ["/usr/lib/swift/libswiftCore.dylib"],
|
||||
});
|
||||
expect(result.ok && result.value).toMatchObject({
|
||||
subcaches: [{ suffix: ".01", status: "present" }],
|
||||
inspected_images: [{ status: "parsed", file: ".01" }],
|
||||
});
|
||||
});
|
||||
|
||||
it("reads legacy single-file headers without later fields", async () => {
|
||||
const path = await writeCache(
|
||||
dyldCacheFixture(IMAGES.slice(0, 1), { legacy: true }),
|
||||
|
||||
Reference in New Issue
Block a user