Merge branch 'feat/dylib-resolution' into feat/dyld-shared-cache
Carry conditional-load propagation, parsed-image digest binding, and segment-wise root resolution into the shared-cache trace. Also: - Make cache compatibility directional: an arm64e cache serves arm64 processes and an x86_64h cache serves x86_64 ones, not the reverse. - Require the complete 24-byte LC_BUILD_VERSION with its declared tool records, and the 16-byte LC_VERSION_MIN_* command, before recording a platform. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -3,6 +3,7 @@ import { constants } from "node:fs";
|
||||
import { lstat, open, readlink, realpath } from "node:fs/promises";
|
||||
import { join, relative, resolve, sep } from "node:path";
|
||||
|
||||
import { resolveTreePath } from "../domain/dyldPaths.js";
|
||||
import {
|
||||
dylibResolutionInputSchema,
|
||||
dylibResolutionResultSchema,
|
||||
@@ -20,10 +21,14 @@ import { hasMachoMagic, readMachoImage } from "./MachoLoadCommandReader.js";
|
||||
|
||||
const HASH_CHUNK_BYTES = 1024 * 1024;
|
||||
|
||||
/** Device, inode, size and change times of the file whose bytes were parsed. */
|
||||
type FileIdentity = string;
|
||||
|
||||
/** Lazily probed, symlink-preserving view of one analyzed directory. */
|
||||
class FilesystemTreeView implements DylibTreeView {
|
||||
readonly #entries = new Map<string, Promise<DylibTreeEntry | undefined>>();
|
||||
readonly #images = new Map<string, Promise<MachoImageFacts>>();
|
||||
readonly #identities = new Map<string, FileIdentity>();
|
||||
|
||||
constructor(
|
||||
private readonly root: string,
|
||||
@@ -41,11 +46,21 @@ class FilesystemTreeView implements DylibTreeView {
|
||||
image(path: string): Promise<MachoImageFacts> {
|
||||
const cached = this.#images.get(path);
|
||||
if (cached !== undefined) return cached;
|
||||
const pending = readImage(join(this.root, path), this.signal);
|
||||
const pending = readImage(join(this.root, path), this.signal).then(
|
||||
({ facts, identity }) => {
|
||||
this.#identities.set(path, identity);
|
||||
return facts;
|
||||
},
|
||||
);
|
||||
this.#images.set(path, pending);
|
||||
return pending;
|
||||
}
|
||||
|
||||
/** Identity of the file whose header bytes `image()` parsed. */
|
||||
identity(path: string): FileIdentity | undefined {
|
||||
return this.#identities.get(path);
|
||||
}
|
||||
|
||||
async #readEntry(path: string): Promise<DylibTreeEntry | undefined> {
|
||||
cancelled(this.signal);
|
||||
const absolute = join(this.root, path);
|
||||
@@ -85,13 +100,13 @@ export const traceDylibResolution = async (options: {
|
||||
let cache: DyldSharedCache | undefined;
|
||||
try {
|
||||
cache = await openSharedCache(parsed.data.shared_cache, options.signal);
|
||||
const { roots, unclassified } =
|
||||
const { roots: requested, unclassified } =
|
||||
parsed.data.roots !== undefined
|
||||
? { roots: parsed.data.roots, unclassified: [] }
|
||||
: options.enumerateRoots
|
||||
? await executableRoots(root, view, options.signal)
|
||||
: { roots: [target], unclassified: [] };
|
||||
await requireMachoRoots(view, roots);
|
||||
const roots = await requireMachoRoots(view, requested);
|
||||
const trace = await traceDylibLoading(view, {
|
||||
roots,
|
||||
unclassified,
|
||||
@@ -101,12 +116,24 @@ export const traceDylibResolution = async (options: {
|
||||
...(cache === undefined ? {} : { sharedCache: sharedCacheView(cache) }),
|
||||
...(options.signal === undefined ? {} : { signal: options.signal }),
|
||||
});
|
||||
// Each digest must describe the same file whose headers were parsed.
|
||||
const digests = new Map<string, string>();
|
||||
for (const { path } of trace.images)
|
||||
digests.set(path, await fileSha256(join(root, path), options.signal));
|
||||
digests.set(
|
||||
path,
|
||||
await fileSha256(join(root, path), {
|
||||
path,
|
||||
expected: view.identity(path),
|
||||
...(options.signal === undefined ? {} : { signal: options.signal }),
|
||||
}),
|
||||
);
|
||||
const targetDigest =
|
||||
digests.get(target) ??
|
||||
(await fileSha256(join(root, target), options.signal));
|
||||
(await fileSha256(join(root, target), {
|
||||
path: target,
|
||||
expected: undefined,
|
||||
...(options.signal === undefined ? {} : { signal: options.signal }),
|
||||
}));
|
||||
if (targetDigest !== options.targetSha256)
|
||||
throw new ArtifactReaderFailure(
|
||||
"integrity",
|
||||
@@ -215,23 +242,35 @@ const executableRoots = async (
|
||||
const compare = (left: string, right: string): number =>
|
||||
left < right ? -1 : left > right ? 1 : 0;
|
||||
|
||||
/**
|
||||
* Resolve each root segment by segment, as dependency candidates are, so a
|
||||
* symlink in an intermediate directory cannot lead outside the analyzed root.
|
||||
*/
|
||||
const requireMachoRoots = async (
|
||||
view: FilesystemTreeView,
|
||||
roots: readonly string[],
|
||||
): Promise<void> => {
|
||||
): Promise<string[]> => {
|
||||
const resolved: string[] = [];
|
||||
for (const path of roots) {
|
||||
const entry = await view.entry(path);
|
||||
if (entry?.kind !== "file")
|
||||
const lookup = await resolveTreePath(view, path);
|
||||
if (lookup.kind === "escapes")
|
||||
throw new ArtifactReaderFailure(
|
||||
"path",
|
||||
`Root ${path} resolves outside the analyzed root`,
|
||||
);
|
||||
if (lookup.kind !== "file")
|
||||
throw new ArtifactReaderFailure(
|
||||
"path",
|
||||
`Root ${path} is not a regular file in the analyzed root`,
|
||||
);
|
||||
if ((await view.image(path)).status === "not-mach-o")
|
||||
if ((await view.image(lookup.path)).status === "not-mach-o")
|
||||
throw new ArtifactReaderFailure(
|
||||
"format",
|
||||
`Root ${path} is not a Mach-O image`,
|
||||
);
|
||||
if (!resolved.includes(lookup.path)) resolved.push(lookup.path);
|
||||
}
|
||||
return resolved;
|
||||
};
|
||||
|
||||
const startsWithMachoMagic = async (path: string): Promise<boolean> => {
|
||||
@@ -245,15 +284,34 @@ const startsWithMachoMagic = async (path: string): Promise<boolean> => {
|
||||
}
|
||||
};
|
||||
|
||||
const identityOf = (metadata: {
|
||||
readonly dev: bigint;
|
||||
readonly ino: bigint;
|
||||
readonly size: bigint;
|
||||
readonly mtimeNs: bigint;
|
||||
readonly ctimeNs: bigint;
|
||||
}): FileIdentity =>
|
||||
[
|
||||
metadata.dev,
|
||||
metadata.ino,
|
||||
metadata.size,
|
||||
metadata.mtimeNs,
|
||||
metadata.ctimeNs,
|
||||
].join(":");
|
||||
|
||||
const readImage = async (
|
||||
path: string,
|
||||
signal?: AbortSignal,
|
||||
): Promise<MachoImageFacts> => {
|
||||
): Promise<{
|
||||
readonly facts: MachoImageFacts;
|
||||
readonly identity: FileIdentity;
|
||||
}> => {
|
||||
cancelled(signal);
|
||||
const handle = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW);
|
||||
try {
|
||||
const { size } = await handle.stat();
|
||||
return await readMachoImage(async (offset, length) => {
|
||||
const metadata = await handle.stat({ bigint: true });
|
||||
const size = Number(metadata.size);
|
||||
const facts = await readMachoImage(async (offset, length) => {
|
||||
cancelled(signal);
|
||||
const buffer = new Uint8Array(
|
||||
Math.max(0, Math.min(length, size - offset)),
|
||||
@@ -261,17 +319,38 @@ const readImage = async (
|
||||
const { bytesRead } = await handle.read(buffer, 0, buffer.length, offset);
|
||||
return buffer.subarray(0, bytesRead);
|
||||
}, size);
|
||||
return { facts, identity: identityOf(metadata) };
|
||||
} finally {
|
||||
await handle.close();
|
||||
}
|
||||
};
|
||||
|
||||
/** Hash a file, failing if it is not the file (or the version) that was parsed. */
|
||||
const fileSha256 = async (
|
||||
path: string,
|
||||
signal?: AbortSignal,
|
||||
absolute: string,
|
||||
options: {
|
||||
readonly path: string;
|
||||
readonly expected: FileIdentity | undefined;
|
||||
readonly signal?: AbortSignal;
|
||||
},
|
||||
): Promise<string> => {
|
||||
const handle = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW);
|
||||
const { signal } = options;
|
||||
const handle = await open(
|
||||
absolute,
|
||||
constants.O_RDONLY | constants.O_NOFOLLOW,
|
||||
);
|
||||
const unchanged = async (): Promise<void> => {
|
||||
if (
|
||||
options.expected !== undefined &&
|
||||
identityOf(await handle.stat({ bigint: true })) !== options.expected
|
||||
)
|
||||
throw new ArtifactReaderFailure(
|
||||
"integrity",
|
||||
`${options.path} changed while its dyld load commands were traced`,
|
||||
);
|
||||
};
|
||||
try {
|
||||
await unchanged();
|
||||
const hash = createHash("sha256");
|
||||
const buffer = new Uint8Array(HASH_CHUNK_BYTES);
|
||||
for (;;) {
|
||||
@@ -280,6 +359,7 @@ const fileSha256 = async (
|
||||
if (bytesRead === 0) break;
|
||||
hash.update(buffer.subarray(0, bytesRead));
|
||||
}
|
||||
await unchanged();
|
||||
return hash.digest("hex");
|
||||
} finally {
|
||||
await handle.close();
|
||||
|
||||
@@ -186,13 +186,16 @@ describe("Mach-O load command reader inputs", () => {
|
||||
{ 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",
|
||||
});
|
||||
// A 16-byte LC_BUILD_VERSION, and one that declares a tool it lacks.
|
||||
const truncated = buildVersionCommand(1).slice(0, 16);
|
||||
new DataView(truncated.buffer).setUint32(4, 16, true);
|
||||
const missingTool = buildVersionCommand(1);
|
||||
new DataView(missingTool.buffer).setUint32(20, 1, true);
|
||||
for (const command of [truncated, missingTool])
|
||||
expect(await read(machoImage({ commands: [command] }))).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 () => {
|
||||
@@ -240,9 +243,10 @@ describe("Mach-O load command reader failures", () => {
|
||||
});
|
||||
|
||||
it("requires 8-byte command alignment in 64-bit images", async () => {
|
||||
// A command the reader does not decode; only its size is checked.
|
||||
const command = new Uint8Array(12);
|
||||
const view = new DataView(command.buffer);
|
||||
view.setUint32(0, LC.CODE_SIGNATURE, true);
|
||||
view.setUint32(0, 0x7f000001, true);
|
||||
view.setUint32(4, 12, true);
|
||||
expect(await read(machoImage({ commands: [command] }))).toMatchObject({
|
||||
status: "malformed",
|
||||
@@ -286,6 +290,11 @@ describe("Mach-O load command reader failures", () => {
|
||||
status: "malformed",
|
||||
reason: "load command 0 is too short to hold a string offset",
|
||||
});
|
||||
view.setUint32(0, LC.CODE_SIGNATURE, true);
|
||||
expect(await read(machoImage({ commands: [short] }))).toMatchObject({
|
||||
status: "malformed",
|
||||
reason: "load command 0 is too short for LC_CODE_SIGNATURE",
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects strings that are unterminated, misplaced or not UTF-8", async () => {
|
||||
|
||||
@@ -289,12 +289,26 @@ const decodeCommand = (
|
||||
return;
|
||||
}
|
||||
if (command === LC_CODE_SIGNATURE) {
|
||||
// linkedit_data_command: cmd, cmdsize, dataoff, datasize.
|
||||
if (body.byteLength < 16)
|
||||
throw new MachoFormatIssue(
|
||||
"malformed",
|
||||
`load command ${index} is too short for LC_CODE_SIGNATURE`,
|
||||
);
|
||||
slice.code_signature_present = true;
|
||||
return;
|
||||
}
|
||||
const implied = VERSION_MIN_PLATFORMS.get(command);
|
||||
if (command === LC_BUILD_VERSION || implied !== undefined) {
|
||||
if (body.byteLength < 12)
|
||||
// version_min_command is 16 bytes; build_version_command is 24 bytes
|
||||
// followed by ntools 8-byte build_tool_version records.
|
||||
const required =
|
||||
implied !== undefined
|
||||
? 16
|
||||
: body.byteLength < 24
|
||||
? 24
|
||||
: 24 + viewOf(body).getUint32(20, true) * 8;
|
||||
if (body.byteLength < required)
|
||||
throw new MachoFormatIssue(
|
||||
"malformed",
|
||||
`load command ${index} is too short for a platform version`,
|
||||
|
||||
Reference in New Issue
Block a user