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
+35
View File
@@ -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}`;
+3 -6
View File
@@ -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(),
+125 -16
View File
@@ -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
View File
@@ -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 =>
+44 -15
View File
@@ -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.`,
]),
];
};
+199
View File
@@ -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 })[];
};