fix(apple): validate physical slices and dylib platform compatibility

This commit is contained in:
morluto
2026-10-09 00:49:30 +08:00
parent 16f4609d68
commit 15f92f2988
15 changed files with 1019 additions and 95 deletions
+115 -2
View File
@@ -11,7 +11,23 @@ import {
const slice = (overrides: Partial<MachoSlice> = {}): MachoSlice => ({
architecture: "arm64",
file_type: "dylib",
slice_offset: 0,
slice_size: 32,
cpu_type: 0x0100000c,
cpu_subtype: 0,
fat_cpu_type: null,
fat_cpu_subtype: null,
fat_alignment_exponent: null,
file_type: overrides.file_type ?? "dylib",
file_type_code:
overrides.file_type_code ??
{ execute: 2, dylib: 6, bundle: 8, other: 1 }[
overrides.file_type ?? "dylib"
],
platform: overrides.platform ?? 1,
platforms:
overrides.platforms ??
(overrides.platform === null ? [] : [overrides.platform ?? 1]),
install_name: null,
dependencies: [],
rpaths: [],
@@ -234,7 +250,7 @@ describe("dyld path expansion", () => {
});
});
describe("dyld resolution outcomes", () => {
describe("dyld resolution outcomes: deriving path and weak-load outcomes", () => {
it("keeps paths outside the root undetermined and in-root fallbacks conditional", async () => {
const trace = await traceDylibLoading(
memoryView({
@@ -308,7 +324,9 @@ describe("dyld resolution outcomes", () => {
"Contents/MacOS/../Overrides/libfound.dylib",
);
});
});
describe("dyld resolution outcomes: checking candidate format and compatibility", () => {
it("reports non-Mach-O, malformed and wrong-architecture candidates", async () => {
const trace = await traceDylibLoading(
memoryView({
@@ -345,6 +363,101 @@ describe("dyld resolution outcomes", () => {
"Contents/MacOS/c/lib.dylib",
]);
});
it("skips non-loadable and wrong-platform rpath candidates", async () => {
const trace = await traceDylibLoading(
memoryView({
[MAIN]: executable({
rpaths: [
"@executable_path/a",
"@executable_path/b",
"@executable_path/c",
],
dependencies: [dependency("@rpath/lib.dylib")],
}),
"Contents/MacOS/a/lib.dylib": parsed(
slice({ file_type: "other", file_type_code: 1 }),
),
"Contents/MacOS/b/lib.dylib": parsed(slice({ platform: 7 })),
"Contents/MacOS/c/lib.dylib": parsed(slice()),
}),
{ roots: [MAIN] },
);
const edge = edgeFor(trace, MAIN, "@rpath/lib.dylib");
expect(edge.candidates.map(({ outcome }) => outcome)).toEqual([
"not-loadable",
"platform-mismatch",
"resolved",
]);
expect(edge.resolution).toEqual({
status: "resolved",
image: "Contents/MacOS/c/lib.dylib",
});
});
it("preserves unknown platform compatibility before a later known candidate", async () => {
const trace = await traceDylibLoading(
memoryView({
[MAIN]: executable({
rpaths: ["@executable_path/a", "@executable_path/b"],
dependencies: [dependency("@rpath/lib.dylib")],
}),
"Contents/MacOS/a/lib.dylib": parsed(slice({ platform: null })),
"Contents/MacOS/b/lib.dylib": parsed(slice()),
}),
{ roots: [MAIN] },
);
const edge = edgeFor(trace, MAIN, "@rpath/lib.dylib");
expect(edge.candidates.map(({ outcome }) => outcome)).toEqual([
"undetermined",
"resolved",
]);
expect(edge.resolution.status).toBe("conditional");
});
it("applies dyld Catalyst and zippered platform compatibility", async () => {
const catalystProcess = await traceDylibLoading(
memoryView({
[MAIN]: executable({
platform: 6,
platforms: [6],
rpaths: ["@executable_path/catalyst"],
dependencies: [dependency("@rpath/lib.dylib")],
}),
"Contents/MacOS/catalyst/lib.dylib": parsed(
slice({ platform: 1, platforms: [1] }),
),
}),
{ roots: [MAIN] },
);
expect(
edgeFor(catalystProcess, MAIN, "@rpath/lib.dylib").resolution,
).toEqual({
status: "resolved",
image: "Contents/MacOS/catalyst/lib.dylib",
});
const zipperedImage = await traceDylibLoading(
memoryView({
[MAIN]: executable({
platform: 1,
platforms: [1],
rpaths: ["@executable_path/zippered"],
dependencies: [dependency("@rpath/lib.dylib")],
}),
"Contents/MacOS/zippered/lib.dylib": parsed(
slice({ platform: null, platforms: [1, 6] }),
),
}),
{ roots: [MAIN] },
);
expect(
edgeFor(zipperedImage, MAIN, "@rpath/lib.dylib").resolution,
).toMatchObject({
status: "resolved",
image: "Contents/MacOS/zippered/lib.dylib",
});
});
});
describe("dyld load order", () => {
+108 -6
View File
@@ -48,7 +48,20 @@ const dependencySchema = z.strictObject({
/** Observed dylib-loading facts of one Mach-O slice. */
export const machoSliceSchema = z.strictObject({
architecture: z.string().min(1),
/** Physical identity observed in the thin header and, for FAT, its table. */
slice_offset: z.number().int().nonnegative(),
slice_size: z.number().int().positive(),
cpu_type: z.number().int().nonnegative(),
cpu_subtype: z.number().int().nonnegative(),
fat_cpu_type: z.number().int().nonnegative().nullable(),
fat_cpu_subtype: z.number().int().nonnegative().nullable(),
fat_alignment_exponent: z.number().int().nonnegative().nullable(),
file_type: z.enum(["execute", "dylib", "bundle", "other"]),
file_type_code: z.number().int().nonnegative(),
/** Raw LC_BUILD_VERSION platform number; null means no such command was observed. */
platform: z.number().int().nonnegative().nullable(),
/** Every distinct build platform declared by LC_BUILD_VERSION/version-min commands. */
platforms: z.array(z.number().int().nonnegative()),
install_name: z.string().nullable(),
dependencies: z.array(dependencySchema),
rpaths: z.array(z.string()),
@@ -97,6 +110,8 @@ const candidateSchema = z.strictObject({
"malformed",
"unsupported",
"architecture-missing",
"not-loadable",
"platform-mismatch",
"outside-target",
"escapes-target",
"undetermined",
@@ -192,6 +207,7 @@ interface ProcessContext {
readonly view: DylibTreeView;
readonly root: string;
readonly architecture: string;
readonly platforms: readonly number[];
readonly executable: string | null;
readonly loaded: Map<string, LoadedImage>;
readonly byInstallName: Map<string, string>;
@@ -269,15 +285,90 @@ const evaluateCandidate = async (
if (lookup.kind !== "file")
return { ...base, outcome: "absent", resolved_path: null };
const facts = await imageFacts(context, lookup.path);
const outcome: Candidate["outcome"] =
facts.status !== "parsed"
? facts.status
: compatibleSlice(facts.slices, context.architecture) === undefined
? "architecture-missing"
: "resolved";
let outcome: Candidate["outcome"];
if (facts.status !== "parsed") outcome = facts.status;
else {
const slice = compatibleSlice(facts.slices, context.architecture);
if (slice === undefined) outcome = "architecture-missing";
else if (![2, 6, 7, 8].includes(slice.file_type_code))
outcome = "not-loadable";
else {
const platformResult = platformLoadability(
context.platforms,
slice.platforms,
slice.file_type_code,
context.architecture,
);
outcome =
platformResult === "compatible"
? "resolved"
: platformResult === "incompatible"
? "platform-mismatch"
: "undetermined";
}
}
return { ...base, outcome, resolved_path: lookup.path };
};
type PlatformLoadability = "compatible" | "incompatible" | "unknown";
/** Apply dyld's documented cross-platform load cases and retain uncertain host cases. */
const platformLoadability = (
processPlatforms: readonly number[],
imagePlatforms: readonly number[],
fileType: number,
architecture: string,
): PlatformLoadability => {
if (processPlatforms.length === 0 || imagePlatforms.length === 0)
return "unknown";
const outcomes = processPlatforms.map((processPlatform) =>
imageLoadabilityForPlatform(
processPlatform,
imagePlatforms,
fileType,
architecture,
),
);
if (outcomes.every((outcome) => outcome === "compatible"))
return "compatible";
if (outcomes.every((outcome) => outcome === "incompatible"))
return "incompatible";
return "unknown";
};
const imageLoadabilityForPlatform = (
processPlatform: number,
imagePlatforms: readonly number[],
fileType: number,
architecture: string,
): PlatformLoadability => {
if (imagePlatforms.includes(processPlatform)) return "compatible";
// These are explicit dyld loadableIntoProcess cross-platform cases.
if (processPlatform === 6 && imagePlatforms.includes(1)) return "compatible"; // macOS dylibs in Mac Catalyst processes
if (processPlatform === 2 && imagePlatforms.includes(6)) return "compatible"; // Catalyst dylibs in iOS processes
if (processPlatform === 2 && imagePlatforms.includes(11)) return "compatible"; // visionOS dylibs in iOS processes
if (processPlatform === 7 && imagePlatforms.includes(12)) return "compatible"; // visionOS simulator dylibs in iOS simulator processes
if (processPlatform === 1 && fileType === 2 && imagePlatforms.includes(6))
return "compatible"; // Catalyst main executables run on macOS
// dyld's remaining exceptions depend on host architecture or a special path.
if (
(processPlatform === 2 &&
imagePlatforms.includes(1) &&
architecture.startsWith("arm64")) ||
([7, 8, 9].includes(processPlatform) && imagePlatforms.includes(1))
)
return "unknown";
if (isKnownPlatform(processPlatform) && imagePlatforms.every(isKnownPlatform))
return "incompatible";
return "unknown";
};
const isKnownPlatform = (platform: number): boolean =>
platform >= 1 && platform <= 12;
const imageFacts = async (
context: ProcessContext,
path: string,
@@ -455,6 +546,7 @@ export const traceDylibLoading = async (
view,
root,
architecture: slice.architecture,
platforms: slice.platforms,
executable: slice.file_type === "execute" ? root : null,
loaded: new Map(),
byInstallName: new Map(),
@@ -503,7 +595,17 @@ const withoutDependencies = (
slice: MachoSlice,
): Omit<MachoSlice, "dependencies"> => ({
architecture: slice.architecture,
slice_offset: slice.slice_offset,
slice_size: slice.slice_size,
cpu_type: slice.cpu_type,
cpu_subtype: slice.cpu_subtype,
fat_cpu_type: slice.fat_cpu_type,
fat_cpu_subtype: slice.fat_cpu_subtype,
fat_alignment_exponent: slice.fat_alignment_exponent,
file_type: slice.file_type,
file_type_code: slice.file_type_code,
platform: slice.platform,
platforms: slice.platforms,
install_name: slice.install_name,
rpaths: slice.rpaths,
dyld_environment: slice.dyld_environment,
+95
View File
@@ -0,0 +1,95 @@
/** Physical facts for one entry in a Mach-O FAT architecture table. */
export interface FatSliceDeclaration {
readonly index: number;
readonly offset: number;
readonly size: number;
readonly alignmentExponent: number;
readonly cpuType: number;
readonly cpuSubtype: number;
}
/** Decode FAT table entries once so artifact and native readers share identity facts. */
export const readFatSliceDeclarations = (
tableBytes: Uint8Array,
options: {
readonly count: number;
readonly wide: boolean;
readonly littleEndian: boolean;
},
):
| {
readonly status: "parsed";
readonly slices: readonly FatSliceDeclaration[];
}
| { readonly status: "malformed"; readonly reason: string } => {
const { count, wide, littleEndian } = options;
const entrySize = wide ? 32 : 20;
if (tableBytes.byteLength < count * entrySize)
return { status: "malformed", reason: "FAT table is truncated" };
const view = new DataView(
tableBytes.buffer,
tableBytes.byteOffset,
tableBytes.byteLength,
);
const slices: FatSliceDeclaration[] = [];
for (let index = 0; index < count; index++) {
const base = index * entrySize;
const offset = wide
? safeNumber(view.getBigUint64(base + 8, littleEndian))
: view.getUint32(base + 8, littleEndian);
const size = wide
? safeNumber(view.getBigUint64(base + 16, littleEndian))
: view.getUint32(base + 12, littleEndian);
if (offset === null || size === null)
return {
status: "malformed",
reason: "FAT offset or size exceeds the safe range",
};
slices.push({
index,
offset,
size,
alignmentExponent: view.getUint32(base + (wide ? 24 : 16), littleEndian),
cpuType: view.getUint32(base, littleEndian),
cpuSubtype: view.getUint32(base + 4, littleEndian),
});
}
return { status: "parsed", slices };
};
/** Validate byte-range and table/header identity facts shared by Mach-O readers. */
export const validateFatSlice = (
declaration: FatSliceDeclaration,
containerSize: number,
tableEnd: number,
embedded?: { readonly cpuType: number; readonly cpuSubtype: number },
): string | null => {
const { index, offset, size, alignmentExponent, cpuType, cpuSubtype } =
declaration;
if (
!Number.isSafeInteger(offset) ||
!Number.isSafeInteger(size) ||
size <= 0 ||
offset < tableEnd
)
return `FAT architecture ${index} has an invalid slice range`;
if (offset > containerSize || size > containerSize - offset)
return `FAT architecture ${index} slice range extends beyond the file`;
if (
!Number.isInteger(alignmentExponent) ||
alignmentExponent < 0 ||
alignmentExponent > 52
)
return `FAT architecture ${index} alignment exponent ${alignmentExponent} is unsupported`;
if (offset % 2 ** alignmentExponent !== 0)
return `FAT architecture ${index} offset is not aligned to 2^${alignmentExponent}`;
if (
embedded !== undefined &&
(embedded.cpuType !== cpuType || embedded.cpuSubtype !== cpuSubtype)
)
return `FAT architecture ${index} CPU type/subtype disagrees with its Mach-O header`;
return null;
};
const safeNumber = (value: bigint): number | null =>
value > BigInt(Number.MAX_SAFE_INTEGER) ? null : Number(value);