Merge origin/main into feat/dylib-resolution
Follow #952's Apple ownership: the Mach-O load-command reader, dylib resolution adapter and fixture move to src/artifacts/apple/, the resolver, dyld path semantics and findings to src/domain/apple/, and the dylib lane helper to scripts/verify/apple/. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,43 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { collectInterfaceBuilderResourceKeys } from "./AppleAssetCatalogAnalysis.js";
|
||||
|
||||
describe("Apple asset catalog application workflow", () => {
|
||||
it("joins only explicit resource-key fields with archive provenance", () => {
|
||||
expect(
|
||||
collectInterfaceBuilderResourceKeys([
|
||||
{
|
||||
id: "ib:Main.nib:object:2",
|
||||
kind: "resource",
|
||||
name: "Decorative image",
|
||||
attributes: {
|
||||
imageName: "Toolbar",
|
||||
title: "not-an-asset-key",
|
||||
image: 42,
|
||||
},
|
||||
evidence: [
|
||||
{
|
||||
artifact_path: "Contents/Resources/Main.nib",
|
||||
artifact_sha256: "d".repeat(64),
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "ib:Main.nib:object:3",
|
||||
kind: "control",
|
||||
name: "Toolbar",
|
||||
attributes: { title: "not-an-asset-key" },
|
||||
evidence: [],
|
||||
},
|
||||
]),
|
||||
).toEqual([
|
||||
{
|
||||
sourceNodeId: "ib:Main.nib:object:2",
|
||||
sourcePath: "Contents/Resources/Main.nib",
|
||||
sourceArchiveSha256: "d".repeat(64),
|
||||
field: "imageName",
|
||||
key: "Toolbar",
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,267 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { lstat } from "node:fs/promises";
|
||||
import { DirectoryArtifactReader } from "../DirectoryArtifactReader.js";
|
||||
import { ArtifactReaderFailure } from "../ArtifactReader.js";
|
||||
import { analyzeInterfaceBuilderBundle } from "./InterfaceBuilderAnalysis.js";
|
||||
import {
|
||||
appleAssetCatalogInputSchema,
|
||||
parseAppleAssetCatalogRecords,
|
||||
projectAppleAssetCatalogPage,
|
||||
} from "../../domain/apple/appleAssetCatalog.js";
|
||||
import { execFileOutput } from "../../process/ExecFileOutput.js";
|
||||
|
||||
const ASSETUTIL = "/usr/bin/assetutil";
|
||||
const MAX_CATALOG_BYTES = 64 * 1024 * 1024;
|
||||
const MAX_TOTAL_METADATA_BYTES = 64 * 1024 * 1024;
|
||||
const RESOURCE_KEY_FIELDS = new Set([
|
||||
"image",
|
||||
"imageName",
|
||||
"image_name",
|
||||
"resourceName",
|
||||
"resource_name",
|
||||
"assetName",
|
||||
"asset_name",
|
||||
"UIImageName",
|
||||
"NSImageName",
|
||||
]);
|
||||
|
||||
/** Inspect compiled asset catalog metadata without extracting rendition bytes. */
|
||||
export const analyzeAppleAssetCatalogs = async (input: {
|
||||
readonly bundlePath: string;
|
||||
readonly targetSha256: string;
|
||||
readonly page?: unknown;
|
||||
readonly signal?: AbortSignal;
|
||||
readonly runAssetUtil?: (
|
||||
path: string,
|
||||
signal?: AbortSignal,
|
||||
) => Promise<string>;
|
||||
}) => {
|
||||
if (process.platform !== "darwin" && input.runAssetUtil === undefined)
|
||||
throw new ArtifactReaderFailure(
|
||||
"unavailable",
|
||||
"Apple asset catalog inspection requires macOS assetutil",
|
||||
);
|
||||
const page = appleAssetCatalogInputSchema.parse(input.page ?? {});
|
||||
const reader = new DirectoryArtifactReader(input.bundlePath);
|
||||
const catalogs: {
|
||||
path: string;
|
||||
sha256: string;
|
||||
records: ReturnType<typeof parseAppleAssetCatalogRecords>;
|
||||
}[] = [];
|
||||
let totalMetadataBytes = 0;
|
||||
try {
|
||||
for await (const entry of reader.entries(input.signal)) {
|
||||
if (entry.kind !== "file" || !entry.path.endsWith("Assets.car")) continue;
|
||||
const inspected = await inspectAssetCatalogEntry({
|
||||
reader,
|
||||
entry,
|
||||
runAssetUtil: input.runAssetUtil ?? runAssetUtil,
|
||||
...(input.signal === undefined ? {} : { signal: input.signal }),
|
||||
});
|
||||
totalMetadataBytes += inspected.metadataBytes;
|
||||
if (totalMetadataBytes > MAX_TOTAL_METADATA_BYTES)
|
||||
throw new ArtifactReaderFailure(
|
||||
"limit",
|
||||
`Combined asset catalog metadata exceeds ${MAX_TOTAL_METADATA_BYTES} bytes`,
|
||||
);
|
||||
catalogs.push(inspected.catalog);
|
||||
}
|
||||
} finally {
|
||||
await reader.close();
|
||||
}
|
||||
if (catalogs.length === 0)
|
||||
throw new ArtifactReaderFailure(
|
||||
"unavailable",
|
||||
"No compiled Assets.car catalogs were found in the app bundle",
|
||||
);
|
||||
const interfaceBuilder = await analyzeInterfaceBuilderBundle({
|
||||
bundlePath: input.bundlePath,
|
||||
targetSha256: input.targetSha256,
|
||||
...(input.signal === undefined ? {} : { signal: input.signal }),
|
||||
});
|
||||
const resourceReferences = collectInterfaceBuilderResourceKeys(
|
||||
interfaceBuilder.graph.nodes,
|
||||
);
|
||||
const result = projectAppleAssetCatalogPage({
|
||||
targetSha256: input.targetSha256,
|
||||
catalogs,
|
||||
offset: page.offset,
|
||||
limit: page.limit,
|
||||
resourceReferences,
|
||||
});
|
||||
return {
|
||||
...result,
|
||||
limitations: [
|
||||
...result.limitations,
|
||||
"Exact resource-key joins use only recognized image or asset key fields on decoded Interface Builder resource objects; other archive resource references are not inferred.",
|
||||
...(interfaceBuilder.graph.truncated
|
||||
? [
|
||||
"Interface Builder resource-key joins may be incomplete because the decoded UI graph was truncated.",
|
||||
]
|
||||
: []),
|
||||
],
|
||||
};
|
||||
};
|
||||
|
||||
const inspectAssetCatalogEntry = async (input: {
|
||||
readonly reader: DirectoryArtifactReader;
|
||||
readonly entry: import("../ArtifactReader.js").ArtifactEntry;
|
||||
readonly runAssetUtil: (
|
||||
path: string,
|
||||
signal?: AbortSignal,
|
||||
) => Promise<string>;
|
||||
readonly signal?: AbortSignal;
|
||||
}) => {
|
||||
const { entry, reader, signal } = input;
|
||||
const sha256 = await digestBounded(reader, entry, signal);
|
||||
const before = await lstat(entry.adapterKey);
|
||||
if (
|
||||
entry.sourceIdentity === undefined ||
|
||||
before.dev !== entry.sourceIdentity.device ||
|
||||
before.ino !== entry.sourceIdentity.inode
|
||||
)
|
||||
throw new ArtifactReaderFailure(
|
||||
"integrity",
|
||||
`Asset catalog changed before inspection: ${entry.path}`,
|
||||
);
|
||||
const output = await input.runAssetUtil(entry.adapterKey, signal);
|
||||
const after = await lstat(entry.adapterKey);
|
||||
if (
|
||||
before.dev !== after.dev ||
|
||||
before.ino !== after.ino ||
|
||||
before.size !== after.size ||
|
||||
(await digestBounded(reader, entry, signal)) !== sha256
|
||||
)
|
||||
throw new ArtifactReaderFailure(
|
||||
"integrity",
|
||||
`Asset catalog changed during inspection: ${entry.path}`,
|
||||
);
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(output);
|
||||
} catch (cause: unknown) {
|
||||
throw new ArtifactReaderFailure(
|
||||
"format",
|
||||
`assetutil returned invalid JSON for ${entry.path}`,
|
||||
{ cause },
|
||||
);
|
||||
}
|
||||
try {
|
||||
return {
|
||||
catalog: {
|
||||
path: entry.path,
|
||||
sha256,
|
||||
records: parseAppleAssetCatalogRecords(parsed),
|
||||
},
|
||||
metadataBytes: Buffer.byteLength(output, "utf8"),
|
||||
};
|
||||
} catch (cause: unknown) {
|
||||
throw new ArtifactReaderFailure(
|
||||
"format",
|
||||
`assetutil returned an unsupported record for ${entry.path}`,
|
||||
{ cause },
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
/** Return only explicit image or asset fields from decoded resource objects. */
|
||||
export const collectInterfaceBuilderResourceKeys = (
|
||||
nodes: readonly {
|
||||
readonly id: string;
|
||||
readonly kind: string;
|
||||
readonly name?: string;
|
||||
readonly attributes: Readonly<Record<string, unknown>>;
|
||||
readonly evidence: readonly {
|
||||
readonly artifact_path: string | null;
|
||||
readonly artifact_sha256: string | null;
|
||||
}[];
|
||||
}[],
|
||||
) =>
|
||||
nodes.flatMap((node) => {
|
||||
const source = node.evidence.find(
|
||||
(item) => item.artifact_path !== null && item.artifact_sha256 !== null,
|
||||
);
|
||||
const sourcePath = source?.artifact_path;
|
||||
const sourceArchiveSha256 = source?.artifact_sha256;
|
||||
if (sourcePath == null || sourceArchiveSha256 == null) return [];
|
||||
return Object.entries(node.attributes).flatMap(([field, value]) =>
|
||||
RESOURCE_KEY_FIELDS.has(field) &&
|
||||
typeof value === "string" &&
|
||||
value.length > 0
|
||||
? [
|
||||
{
|
||||
sourceNodeId: node.id,
|
||||
sourcePath,
|
||||
sourceArchiveSha256,
|
||||
field,
|
||||
key: value,
|
||||
},
|
||||
]
|
||||
: [],
|
||||
);
|
||||
});
|
||||
|
||||
const runAssetUtil = async (
|
||||
path: string,
|
||||
signal?: AbortSignal,
|
||||
): Promise<string> => {
|
||||
try {
|
||||
return (
|
||||
await execFileOutput(ASSETUTIL, ["--info", path], {
|
||||
timeout: 60_000,
|
||||
maxBuffer: MAX_CATALOG_BYTES,
|
||||
...(signal === undefined ? {} : { signal }),
|
||||
})
|
||||
).stdout;
|
||||
} catch (cause: unknown) {
|
||||
if (signal?.aborted === true)
|
||||
throw new ArtifactReaderFailure(
|
||||
"cancelled",
|
||||
"Asset catalog inspection cancelled",
|
||||
);
|
||||
const code =
|
||||
typeof cause === "object" && cause !== null && "code" in cause
|
||||
? cause.code
|
||||
: undefined;
|
||||
throw new ArtifactReaderFailure(
|
||||
code === "ENOENT"
|
||||
? "unavailable"
|
||||
: code === "ETIMEDOUT" || code === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER"
|
||||
? "limit"
|
||||
: "io",
|
||||
`assetutil failed${code === undefined ? "" : ` (${String(code)})`}`,
|
||||
{ cause },
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const digestBounded = async (
|
||||
reader: DirectoryArtifactReader,
|
||||
entry: import("../ArtifactReader.js").ArtifactEntry,
|
||||
signal?: AbortSignal,
|
||||
): Promise<string> => {
|
||||
if (entry.declaredSize === null || entry.declaredSize > MAX_CATALOG_BYTES)
|
||||
throw new ArtifactReaderFailure(
|
||||
"limit",
|
||||
`Asset catalog exceeds ${MAX_CATALOG_BYTES} bytes: ${entry.path}`,
|
||||
);
|
||||
const stream = await reader.open(entry, signal);
|
||||
const hash = createHash("sha256");
|
||||
let length = 0;
|
||||
for await (const chunk of stream) {
|
||||
if (signal?.aborted === true)
|
||||
throw new ArtifactReaderFailure(
|
||||
"cancelled",
|
||||
"Asset catalog inspection cancelled",
|
||||
);
|
||||
const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
||||
length += bytes.length;
|
||||
if (length > MAX_CATALOG_BYTES)
|
||||
throw new ArtifactReaderFailure(
|
||||
"limit",
|
||||
`Asset catalog exceeds byte limit: ${entry.path}`,
|
||||
);
|
||||
hash.update(bytes);
|
||||
}
|
||||
return hash.digest("hex");
|
||||
};
|
||||
@@ -0,0 +1,350 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { constants } from "node:fs";
|
||||
import { lstat, open, readlink, realpath } from "node:fs/promises";
|
||||
import { join, relative, sep } from "node:path";
|
||||
|
||||
import { resolveTreePath } from "../../domain/apple/dyldPaths.js";
|
||||
import {
|
||||
dylibResolutionInputSchema,
|
||||
dylibResolutionResultSchema,
|
||||
traceDylibLoading,
|
||||
type DylibResolutionResult,
|
||||
type DylibTreeEntry,
|
||||
type DylibTreeView,
|
||||
type MachoImageFacts,
|
||||
} from "../../domain/apple/dylibResolution.js";
|
||||
import { ArtifactReaderFailure } from "../ArtifactReader.js";
|
||||
import { DirectoryArtifactReader } from "../DirectoryArtifactReader.js";
|
||||
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,
|
||||
private readonly signal?: AbortSignal,
|
||||
) {}
|
||||
|
||||
entry(path: string): Promise<DylibTreeEntry | undefined> {
|
||||
const cached = this.#entries.get(path);
|
||||
if (cached !== undefined) return cached;
|
||||
const pending = this.#readEntry(path);
|
||||
this.#entries.set(path, pending);
|
||||
return pending;
|
||||
}
|
||||
|
||||
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).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);
|
||||
try {
|
||||
const metadata = await lstat(absolute);
|
||||
if (metadata.isSymbolicLink())
|
||||
return { kind: "symlink", target: await readlink(absolute) };
|
||||
if (metadata.isDirectory()) return { kind: "directory" };
|
||||
return metadata.isFile() ? { kind: "file" } : undefined;
|
||||
} catch (cause: unknown) {
|
||||
if (missing(cause)) return undefined;
|
||||
throw cause;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Resolve dyld load paths for the active Mach-O or every executable in its bundle. */
|
||||
export const traceDylibResolution = async (options: {
|
||||
readonly rootPath: string;
|
||||
readonly targetPath: string;
|
||||
readonly targetSha256: string;
|
||||
readonly enumerateRoots: boolean;
|
||||
readonly parameters: unknown;
|
||||
readonly signal?: AbortSignal;
|
||||
}): Promise<DylibResolutionResult> => {
|
||||
const parsed = dylibResolutionInputSchema.safeParse(options.parameters);
|
||||
if (!parsed.success)
|
||||
throw new ArtifactReaderFailure(
|
||||
"path",
|
||||
"roots must be normalized paths relative to the analyzed root",
|
||||
);
|
||||
const root = await realpath(options.rootPath);
|
||||
const target = relative(root, await realpath(options.targetPath))
|
||||
.split(sep)
|
||||
.join("/");
|
||||
const view = new FilesystemTreeView(root, options.signal);
|
||||
try {
|
||||
const { roots: requested, unclassified } =
|
||||
parsed.data.roots !== undefined
|
||||
? { roots: parsed.data.roots, unclassified: [] }
|
||||
: options.enumerateRoots
|
||||
? await executableRoots(root, view, options.signal)
|
||||
: { roots: [target], unclassified: [] };
|
||||
const roots = await requireMachoRoots(view, requested);
|
||||
const trace = await traceDylibLoading(view, {
|
||||
roots,
|
||||
unclassified,
|
||||
...(parsed.data.architecture === undefined
|
||||
? {}
|
||||
: { architecture: parsed.data.architecture }),
|
||||
...(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), {
|
||||
path,
|
||||
expected: view.identity(path),
|
||||
...(options.signal === undefined ? {} : { signal: options.signal }),
|
||||
}),
|
||||
);
|
||||
const targetDigest =
|
||||
digests.get(target) ??
|
||||
(await fileSha256(join(root, target), {
|
||||
path: target,
|
||||
expected: undefined,
|
||||
...(options.signal === undefined ? {} : { signal: options.signal }),
|
||||
}));
|
||||
if (targetDigest !== options.targetSha256)
|
||||
throw new ArtifactReaderFailure(
|
||||
"integrity",
|
||||
`Active target digest changed: expected ${options.targetSha256}, observed ${targetDigest}`,
|
||||
);
|
||||
return dylibResolutionResultSchema.parse({
|
||||
...trace,
|
||||
root_path: options.rootPath,
|
||||
target_sha256: options.targetSha256,
|
||||
images: trace.images.map((image) => ({
|
||||
...image,
|
||||
sha256: digests.get(image.path),
|
||||
})),
|
||||
});
|
||||
} catch (cause: unknown) {
|
||||
if (options.signal?.aborted === true)
|
||||
throw new ArtifactReaderFailure(
|
||||
"cancelled",
|
||||
"Dylib resolution was cancelled",
|
||||
{ cause },
|
||||
);
|
||||
const denied = permissionDenied(cause);
|
||||
if (denied !== undefined)
|
||||
throw new ArtifactReaderFailure(
|
||||
"unavailable",
|
||||
`Permission denied (${denied.code}) reading ${denied.path === undefined ? "a file in the analyzed root" : relative(root, denied.path) || denied.path}`,
|
||||
{ cause },
|
||||
);
|
||||
throw cause;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Every Mach-O in the bundle with an executable slice is its own process root.
|
||||
* Mach-O files that do not parse are returned separately: whether they are
|
||||
* executables is unknown, so they make coverage partial instead of vanishing.
|
||||
*/
|
||||
const executableRoots = async (
|
||||
root: string,
|
||||
view: FilesystemTreeView,
|
||||
signal?: AbortSignal,
|
||||
): Promise<{ readonly roots: string[]; readonly unclassified: string[] }> => {
|
||||
const roots: string[] = [];
|
||||
const unclassified: string[] = [];
|
||||
for await (const entry of new DirectoryArtifactReader(root).entries(signal)) {
|
||||
if (
|
||||
entry.kind !== "file" ||
|
||||
!(await startsWithMachoMagic(entry.adapterKey))
|
||||
)
|
||||
continue;
|
||||
const facts = await view.image(entry.path);
|
||||
if (facts.status === "malformed" || facts.status === "unsupported")
|
||||
unclassified.push(entry.path);
|
||||
else if (
|
||||
facts.status === "parsed" &&
|
||||
facts.slices.some(({ file_type: type }) => type === "execute")
|
||||
)
|
||||
roots.push(entry.path);
|
||||
}
|
||||
return {
|
||||
roots: roots.sort(compare),
|
||||
unclassified: unclassified.sort(compare),
|
||||
};
|
||||
};
|
||||
|
||||
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<string[]> => {
|
||||
const resolved: string[] = [];
|
||||
for (const path of roots) {
|
||||
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(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> => {
|
||||
const handle = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW);
|
||||
try {
|
||||
const buffer = new Uint8Array(4);
|
||||
const { bytesRead } = await handle.read(buffer, 0, 4, 0);
|
||||
return hasMachoMagic(buffer.subarray(0, bytesRead));
|
||||
} finally {
|
||||
await handle.close();
|
||||
}
|
||||
};
|
||||
|
||||
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<{
|
||||
readonly facts: MachoImageFacts;
|
||||
readonly identity: FileIdentity;
|
||||
}> => {
|
||||
cancelled(signal);
|
||||
const handle = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW);
|
||||
try {
|
||||
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)),
|
||||
);
|
||||
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 (
|
||||
absolute: string,
|
||||
options: {
|
||||
readonly path: string;
|
||||
readonly expected: FileIdentity | undefined;
|
||||
readonly signal?: AbortSignal;
|
||||
},
|
||||
): Promise<string> => {
|
||||
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 (;;) {
|
||||
cancelled(signal);
|
||||
const { bytesRead } = await handle.read(buffer, 0, buffer.length, null);
|
||||
if (bytesRead === 0) break;
|
||||
hash.update(buffer.subarray(0, bytesRead));
|
||||
}
|
||||
await unchanged();
|
||||
return hash.digest("hex");
|
||||
} finally {
|
||||
await handle.close();
|
||||
}
|
||||
};
|
||||
|
||||
const cancelled = (signal?: AbortSignal): void => {
|
||||
if (signal?.aborted === true)
|
||||
throw new ArtifactReaderFailure(
|
||||
"cancelled",
|
||||
"Dylib resolution was cancelled",
|
||||
);
|
||||
};
|
||||
|
||||
/** Host permission denials, kept distinct from malformed or missing files. */
|
||||
const permissionDenied = (
|
||||
cause: unknown,
|
||||
): { readonly code: string; readonly path: string | undefined } | undefined => {
|
||||
if (!(cause instanceof Error) || !("code" in cause)) return undefined;
|
||||
if (cause.code !== "EACCES" && cause.code !== "EPERM") return undefined;
|
||||
return {
|
||||
code: cause.code,
|
||||
path:
|
||||
"path" in cause && typeof cause.path === "string"
|
||||
? cause.path
|
||||
: undefined,
|
||||
};
|
||||
};
|
||||
|
||||
const missing = (cause: unknown): boolean =>
|
||||
cause instanceof Error &&
|
||||
"code" in cause &&
|
||||
(cause.code === "ENOENT" || cause.code === "ENOTDIR");
|
||||
@@ -0,0 +1,410 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { parseBinary } from "plist";
|
||||
|
||||
import { DirectoryArtifactReader } from "../DirectoryArtifactReader.js";
|
||||
import { projectPlistValue } from "../../domain/apple/plistValue.js";
|
||||
import {
|
||||
omittedPrototypeKeysLimitation,
|
||||
parseXmlPropertyList,
|
||||
} from "../../domain/propertyListKeys.js";
|
||||
import { decodeNibArchive, type NibArchiveDocument } from "./NibArchive.js";
|
||||
import type { ArtifactEntry } from "../ArtifactReader.js";
|
||||
import {
|
||||
buildInterfaceBuilderAnalysis,
|
||||
interfaceBuilderLimitsSchema,
|
||||
type InterfaceBuilderDocumentInput,
|
||||
} from "../../domain/apple/interfaceBuilderGraph.js";
|
||||
import {
|
||||
mergeNibHierarchies,
|
||||
projectNibViewHierarchy,
|
||||
type NibHierarchyNode,
|
||||
} from "./NibViewHierarchy.js";
|
||||
import { jsonValueSchema, type JsonValue } from "../../domain/jsonValue.js";
|
||||
|
||||
const MAX_DOCUMENT_BYTES = 64 * 1024 * 1024;
|
||||
|
||||
/** Decode compiled Interface Builder archives from a local app bundle. */
|
||||
export const analyzeInterfaceBuilderBundle = async (input: {
|
||||
readonly bundlePath: string;
|
||||
readonly targetSha256: string;
|
||||
readonly limits?: unknown;
|
||||
readonly signal?: AbortSignal;
|
||||
}) => {
|
||||
const limits = interfaceBuilderLimitsSchema.parse(input.limits ?? {});
|
||||
const reader = new DirectoryArtifactReader(input.bundlePath);
|
||||
const documents: InterfaceBuilderDocumentInput[] = [];
|
||||
const invalid: string[] = [];
|
||||
const incompleteHierarchies = new Map<string, number>();
|
||||
const prototypeKeyOmissions = new Map<string, number>();
|
||||
let omitted = 0;
|
||||
let attempted = 0;
|
||||
try {
|
||||
for await (const entry of reader.entries(input.signal)) {
|
||||
if (entry.kind !== "file" || !isInterfaceBuilderArchive(entry.path))
|
||||
continue;
|
||||
if (attempted >= limits.max_documents) {
|
||||
omitted += 1;
|
||||
continue;
|
||||
}
|
||||
attempted += 1;
|
||||
try {
|
||||
const bytes = await readEntry(reader, entry, input.signal);
|
||||
const nib =
|
||||
bytes.subarray(0, 10).toString("ascii") === "NIBArchive"
|
||||
? projectNibArchive(decodeNibArchive(bytes))
|
||||
: null;
|
||||
const { value: raw, omittedPrototypeKeys } =
|
||||
nib === null
|
||||
? decodePlist(bytes)
|
||||
: { value: nib.raw, omittedPrototypeKeys: 0 };
|
||||
if (nib !== null && nib.omitted > 0)
|
||||
incompleteHierarchies.set(entry.path, nib.omitted);
|
||||
if (omittedPrototypeKeys > 0)
|
||||
prototypeKeyOmissions.set(entry.path, omittedPrototypeKeys);
|
||||
const documentHash = createHash("sha256").update(bytes).digest("hex");
|
||||
documents.push({
|
||||
relativePath: entry.path,
|
||||
archiveSha256: documentHash,
|
||||
documentKind: entry.path.includes(".storyboardc/")
|
||||
? "storyboard_scene"
|
||||
: "nib",
|
||||
raw,
|
||||
});
|
||||
} catch (cause: unknown) {
|
||||
if (input.signal?.aborted === true) throw cause;
|
||||
invalid.push(
|
||||
`${entry.path}: ${cause instanceof Error ? cause.message : "archive decode failed"}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
await reader.close();
|
||||
}
|
||||
const result = buildInterfaceBuilderAnalysis({
|
||||
targetSha256: input.targetSha256,
|
||||
toolVersion: "rea-interface-builder/1",
|
||||
documents,
|
||||
limits,
|
||||
});
|
||||
return finalizeHierarchyCoverage(result, {
|
||||
incompleteHierarchies,
|
||||
prototypeKeyOmissions,
|
||||
invalid,
|
||||
attempted,
|
||||
omitted,
|
||||
});
|
||||
};
|
||||
|
||||
const finalizeHierarchyCoverage = (
|
||||
result: ReturnType<typeof buildInterfaceBuilderAnalysis>,
|
||||
counts: {
|
||||
incompleteHierarchies: ReadonlyMap<string, number>;
|
||||
prototypeKeyOmissions: ReadonlyMap<string, number>;
|
||||
invalid: readonly string[];
|
||||
attempted: number;
|
||||
omitted: number;
|
||||
},
|
||||
) => {
|
||||
const { incompleteHierarchies, prototypeKeyOmissions, invalid } = counts;
|
||||
const archiveDecodePartial =
|
||||
invalid.length > 0 || prototypeKeyOmissions.size > 0;
|
||||
return {
|
||||
...result,
|
||||
documents: result.documents.map((document) => ({
|
||||
...document,
|
||||
hierarchy_complete:
|
||||
document.hierarchy_complete &&
|
||||
!incompleteHierarchies.has(document.relative_path),
|
||||
})),
|
||||
graph: {
|
||||
...result.graph,
|
||||
coverage: [
|
||||
...result.graph.coverage.map((facet) => {
|
||||
const omitted = incompleteHierarchies.get(
|
||||
facet.facet.replace(/^hierarchy:/u, ""),
|
||||
);
|
||||
return facet.facet.startsWith("hierarchy:") && omitted !== undefined
|
||||
? {
|
||||
...facet,
|
||||
status: "partial" as const,
|
||||
reason: "serialized_view_hierarchy_incomplete",
|
||||
omitted: facet.omitted + omitted,
|
||||
}
|
||||
: facet;
|
||||
}),
|
||||
{
|
||||
facet: "archive_decode",
|
||||
status: archiveDecodePartial
|
||||
? ("partial" as const)
|
||||
: ("complete" as const),
|
||||
reason:
|
||||
invalid.length > 0
|
||||
? "one_or_more_archives_invalid"
|
||||
: prototypeKeyOmissions.size > 0
|
||||
? "dictionary_entries_omitted"
|
||||
: null,
|
||||
examined: counts.attempted,
|
||||
omitted: counts.omitted,
|
||||
},
|
||||
],
|
||||
truncated:
|
||||
result.graph.truncated ||
|
||||
counts.omitted > 0 ||
|
||||
archiveDecodePartial ||
|
||||
incompleteHierarchies.size > 0,
|
||||
},
|
||||
limitations: [
|
||||
...result.limitations,
|
||||
"Compiled Interface Builder archives are private serialized object graphs. The decoder reports only recognized keyed-archive objects and connections; unrecognized object classes and fields remain unknown.",
|
||||
...(incompleteHierarchies.size === 0
|
||||
? []
|
||||
: [
|
||||
"Some serialized hierarchy links could not be projected within the bounded hierarchy; their parentage remains unknown.",
|
||||
]),
|
||||
...(invalid.length === 0
|
||||
? []
|
||||
: [
|
||||
`Some Interface Builder archives could not be decoded: ${invalid.slice(0, 16).join("; ")}`,
|
||||
]),
|
||||
...[...prototypeKeyOmissions].map(
|
||||
([path, count]) => `${path}: ${omittedPrototypeKeysLimitation(count)}`,
|
||||
),
|
||||
],
|
||||
};
|
||||
};
|
||||
|
||||
/** Project decoded NIB records into the same bounded graph input as ibtool. */
|
||||
const projectNibArchive = (archive: NibArchiveDocument) => {
|
||||
const byId = new Map(archive.objects.map((object) => [object.id, object]));
|
||||
const dereference = (value: JsonValue | undefined): JsonValue | undefined => {
|
||||
if (typeof value !== "object" || value === null || Array.isArray(value))
|
||||
return value;
|
||||
const ref = value.$nib_object_ref;
|
||||
if (typeof ref !== "number") return value;
|
||||
const target = byId.get(ref);
|
||||
if (target === undefined) return undefined;
|
||||
if (target.class_name.replace(/\0+$/u, "") === "NSString") {
|
||||
const data = target.values["NS.bytes"];
|
||||
if (typeof data === "object" && data !== null && !Array.isArray(data)) {
|
||||
const encoded = data.$nib_data_base64;
|
||||
if (typeof encoded === "string")
|
||||
return Buffer.from(encoded, "base64").toString("utf8");
|
||||
}
|
||||
}
|
||||
return { objectID: String(ref) };
|
||||
};
|
||||
const referencedString = (value: JsonValue | undefined): string | null => {
|
||||
if (typeof value !== "object" || value === null || Array.isArray(value))
|
||||
return null;
|
||||
const ref = value.$nib_object_ref;
|
||||
if (typeof ref !== "number") return null;
|
||||
const target = byId.get(ref);
|
||||
const data = target?.values["NS.bytes"];
|
||||
if (target?.class_name.replace(/\0+$/u, "") !== "NSString") return null;
|
||||
if (typeof data !== "object" || data === null || Array.isArray(data))
|
||||
return null;
|
||||
const encoded = data.$nib_data_base64;
|
||||
return typeof encoded === "string"
|
||||
? Buffer.from(encoded, "base64").toString("utf8")
|
||||
: null;
|
||||
};
|
||||
const runtimeClass = (objectId: number): string | null => {
|
||||
const object = byId.get(objectId);
|
||||
if (object === undefined) return null;
|
||||
const storedClass = object.class_name.replace(/\0+$/u, "");
|
||||
if (storedClass === "NSClassSwapper")
|
||||
return referencedString(object.values.NSClassName) ?? storedClass;
|
||||
return storedClass === "UIClassSwapper"
|
||||
? (referencedString(object.values.UIClassName) ?? storedClass)
|
||||
: storedClass;
|
||||
};
|
||||
const objects = Object.fromEntries(
|
||||
archive.objects
|
||||
.filter((object) => {
|
||||
const name = runtimeClass(object.id) ?? "";
|
||||
return !/^(?:NSObject|NSIBObjectData|NSString|NSMutableString|NSNumber|NSArray|NSMutableArray|NSSet|NSMutableSet|NSDictionary|NSMutableDictionary|NSApplication|NSNib.*Connector|UIRuntime\w*Connection)$/u.test(
|
||||
name,
|
||||
);
|
||||
})
|
||||
.map((object) => {
|
||||
const className =
|
||||
runtimeClass(object.id) ?? object.class_name.replace(/\0+$/u, "");
|
||||
const strings = Object.entries(object.values).flatMap(
|
||||
([key, value]) => {
|
||||
const resolved = dereference(value);
|
||||
return typeof resolved === "string" ? [[key, resolved]] : [];
|
||||
},
|
||||
);
|
||||
const name =
|
||||
strings.find(([key]) =>
|
||||
/(?:title|label|identifier|accessibility|name|contents)/iu.test(
|
||||
key ?? "",
|
||||
),
|
||||
)?.[1] ?? className;
|
||||
return [
|
||||
String(object.id),
|
||||
{
|
||||
customClass: className,
|
||||
label: name,
|
||||
objectID: String(object.id),
|
||||
nibValues: Object.fromEntries(
|
||||
Object.entries(object.values).map(([key, value]) => [
|
||||
key,
|
||||
dereference(value) ?? null,
|
||||
]),
|
||||
),
|
||||
},
|
||||
];
|
||||
}),
|
||||
);
|
||||
const connections: Record<string, JsonValue[]> = {};
|
||||
const hierarchy: NibHierarchyNode[] = [];
|
||||
const reference = (value: JsonValue | undefined): number | null => {
|
||||
if (typeof value !== "object" || value === null || Array.isArray(value))
|
||||
return null;
|
||||
return typeof value.$nib_object_ref === "number"
|
||||
? value.$nib_object_ref
|
||||
: null;
|
||||
};
|
||||
for (const object of archive.objects) {
|
||||
const className = object.class_name.replace(/\0+$/u, "");
|
||||
// AppKit connectors use NS-prefixed keys; UIKit's runtime outlet and
|
||||
// event connections use UI-prefixed keys with the same roles.
|
||||
const uiKit = /^UIRuntime\w*Connection$/u.test(className);
|
||||
if (!uiKit && !className.includes("Connector")) continue;
|
||||
const values = object.values;
|
||||
const source = reference(uiKit ? values.UISource : values.NSSource);
|
||||
if (source === null) continue;
|
||||
const destination = reference(
|
||||
uiKit ? values.UIDestination : values.NSDestination,
|
||||
);
|
||||
const label = referencedString(uiKit ? values.UILabel : values.NSLabel);
|
||||
const type = className.includes("Outlet")
|
||||
? "outlet"
|
||||
: className.includes("Control") || className.includes("Event")
|
||||
? "action"
|
||||
: className;
|
||||
const eventMask = values.UIEventMask;
|
||||
// The source is the outlet owner or the sending control; the destination
|
||||
// is the outlet value or the action target, and a nil target is the
|
||||
// first responder.
|
||||
(connections[String(source)] ??= []).push({
|
||||
type,
|
||||
"destination-id": destination === null ? null : String(destination),
|
||||
label,
|
||||
source_id: String(source),
|
||||
archive_object_id: String(object.id),
|
||||
...(typeof eventMask === "number" ? { ui_event_mask: eventMask } : {}),
|
||||
});
|
||||
}
|
||||
let hierarchyOmitted = 0;
|
||||
const hierarchyFor = (
|
||||
objectId: number,
|
||||
seen: Set<number>,
|
||||
depth: number,
|
||||
): NibHierarchyNode | null => {
|
||||
if (depth > 32 || seen.has(objectId)) {
|
||||
hierarchyOmitted += 1;
|
||||
return null;
|
||||
}
|
||||
const object = byId.get(objectId);
|
||||
if (object === undefined) {
|
||||
hierarchyOmitted += 1;
|
||||
return null;
|
||||
}
|
||||
const nextSeen = new Set(seen).add(objectId);
|
||||
const children: NibHierarchyNode[] = [];
|
||||
for (const [key, value] of Object.entries(object.values)) {
|
||||
if (!/(?:subviews|contentview|childviewcontrollers|view)$/iu.test(key))
|
||||
continue;
|
||||
const direct = reference(value);
|
||||
if (direct === null) continue;
|
||||
const target = byId.get(direct);
|
||||
if (target === undefined) {
|
||||
hierarchyOmitted += 1;
|
||||
continue;
|
||||
}
|
||||
if (/array|set/iu.test(target.class_name)) {
|
||||
for (const candidate of Object.values(target.values)) {
|
||||
const child = reference(candidate);
|
||||
const nested =
|
||||
child === null ? null : hierarchyFor(child, nextSeen, depth + 1);
|
||||
if (nested !== null) children.push(nested);
|
||||
}
|
||||
} else {
|
||||
const nested = hierarchyFor(direct, nextSeen, depth + 1);
|
||||
if (nested !== null) children.push(nested);
|
||||
}
|
||||
}
|
||||
return { objectID: String(objectId), children };
|
||||
};
|
||||
const ibData = archive.objects.find(
|
||||
({ class_name }) => class_name.replace(/\0+$/u, "") === "NSIBObjectData",
|
||||
);
|
||||
const rootId = reference(ibData?.values.NSRoot);
|
||||
const hierarchyRoots = rootId === null ? [] : [rootId];
|
||||
for (const hierarchyRoot of hierarchyRoots) {
|
||||
const root = hierarchyFor(hierarchyRoot, new Set(), 0);
|
||||
if (root !== null) hierarchy.push(root);
|
||||
}
|
||||
const viewHierarchy = projectNibViewHierarchy(
|
||||
archive.objects,
|
||||
new Set(Object.keys(objects).map(Number)),
|
||||
);
|
||||
const merged = mergeNibHierarchies(hierarchy, viewHierarchy.hierarchy ?? []);
|
||||
return {
|
||||
omitted: viewHierarchy.omitted + hierarchyOmitted + merged.omitted,
|
||||
raw: jsonValueSchema.parse({
|
||||
"com.apple.ibtool.document.objects": objects,
|
||||
"com.apple.ibtool.document.connections": connections,
|
||||
"com.apple.ibtool.document.hierarchy": merged.hierarchy,
|
||||
"com.apple.ibtool.document.classes": Object.fromEntries(
|
||||
archive.classes.map((name) => [name.replace(/\0+$/u, ""), {}]),
|
||||
),
|
||||
}),
|
||||
};
|
||||
};
|
||||
|
||||
const isInterfaceBuilderArchive = (path: string): boolean => {
|
||||
const lower = path.toLowerCase();
|
||||
return lower.endsWith(".nib") || lower.endsWith("/objects.nib");
|
||||
};
|
||||
|
||||
const readEntry = async (
|
||||
reader: DirectoryArtifactReader,
|
||||
entry: ArtifactEntry,
|
||||
signal?: AbortSignal,
|
||||
): Promise<Buffer> => {
|
||||
if (entry.declaredSize !== null && entry.declaredSize > MAX_DOCUMENT_BYTES)
|
||||
throw new RangeError(
|
||||
"archive exceeds the 64 MiB per-document decode limit",
|
||||
);
|
||||
const stream = await reader.open(entry, signal);
|
||||
const chunks: Buffer[] = [];
|
||||
let length = 0;
|
||||
for await (const chunk of stream) {
|
||||
const bytes = Buffer.isBuffer(chunk)
|
||||
? chunk
|
||||
: Buffer.from(chunk as Uint8Array);
|
||||
length += bytes.length;
|
||||
if (length > MAX_DOCUMENT_BYTES) {
|
||||
stream.destroy();
|
||||
throw new RangeError(
|
||||
"archive exceeded the 64 MiB per-document decode limit",
|
||||
);
|
||||
}
|
||||
chunks.push(bytes);
|
||||
}
|
||||
return Buffer.concat(chunks, length);
|
||||
};
|
||||
|
||||
/** Project decoded plist data and dates while retaining omitted-key coverage. */
|
||||
const decodePlist = (
|
||||
bytes: Buffer,
|
||||
): { readonly value: JsonValue; readonly omittedPrototypeKeys: number } => {
|
||||
const { value, omittedPrototypeKeys } =
|
||||
bytes.subarray(0, 8).toString("ascii") === "bplist00"
|
||||
? { value: parseBinary(bytes), omittedPrototypeKeys: 0 }
|
||||
: parseXmlPropertyList(bytes.toString("utf8"));
|
||||
return { value: projectPlistValue(value).value, omittedPrototypeKeys };
|
||||
};
|
||||
@@ -0,0 +1,130 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { build, buildBinary } from "plist";
|
||||
import { decodeKeyedArchiveBytes } from "./KeyedArchiveReader.js";
|
||||
|
||||
const archive = {
|
||||
$archiver: "NSKeyedArchiver",
|
||||
$version: 100000,
|
||||
$objects: [
|
||||
"$null",
|
||||
{
|
||||
$class: { UID: 4 },
|
||||
child: { UID: 2 },
|
||||
shared: { UID: 2 },
|
||||
self: { UID: 1 },
|
||||
conditional: { UID: 0 },
|
||||
broken: { UID: 90 },
|
||||
},
|
||||
{ "NS.objects": [{ UID: 1 }, { UID: 3 }] },
|
||||
"value",
|
||||
{ $classname: "UnknownModel", $classes: ["UnknownModel", "NSObject"] },
|
||||
],
|
||||
$top: { root: { UID: 1 }, other: { UID: 2 } },
|
||||
};
|
||||
describe("inert keyed archive decoding", () => {
|
||||
it("preserves CF$UID, malformed references and original pagination identities", () => {
|
||||
const bytes = Buffer.from(
|
||||
build({
|
||||
...archive,
|
||||
$objects: [
|
||||
"$null",
|
||||
{ bad: { CF$UID: -1 }, valid: { CF$UID: 2 }, broken: { CF$UID: 90 } },
|
||||
"value",
|
||||
],
|
||||
}),
|
||||
);
|
||||
const graph = decodeKeyedArchiveBytes(bytes, {
|
||||
root: "root",
|
||||
offset: 1,
|
||||
limit: 1,
|
||||
});
|
||||
expect(graph.roots).toEqual({ root: { UID: 1 } });
|
||||
expect(graph.objects.map(({ id }) => id)).toEqual([1]);
|
||||
expect(graph.next_offset).toBe(2);
|
||||
expect(graph.references).toContainEqual(
|
||||
expect.objectContaining({ source: 1, target: 90, status: "unresolved" }),
|
||||
);
|
||||
expect(graph.references).toContainEqual(
|
||||
expect.objectContaining({ source: 1, target: null, status: "malformed" }),
|
||||
);
|
||||
expect(graph.references).toContainEqual(
|
||||
expect.objectContaining({ source: 1, target: 2, status: "resolved" }),
|
||||
);
|
||||
});
|
||||
it.each([
|
||||
["binary", { UID: 1 }],
|
||||
["XML", { CF$UID: 1 }],
|
||||
] as const)(
|
||||
"resolves a %s root encoded under a UID-named key",
|
||||
(format, reference) => {
|
||||
const named = {
|
||||
...archive,
|
||||
$objects: ["$null", "payload"],
|
||||
$top: { UID: reference, CF$UID: reference },
|
||||
};
|
||||
const graph = decodeKeyedArchiveBytes(
|
||||
Buffer.from(format === "binary" ? buildBinary(named) : build(named)),
|
||||
{ offset: 0, limit: 2 },
|
||||
);
|
||||
expect(
|
||||
graph.references.map(({ source, path, target, status }) => ({
|
||||
source,
|
||||
path,
|
||||
target,
|
||||
status,
|
||||
})),
|
||||
).toEqual([
|
||||
{ source: null, path: ["CF$UID"], target: 1, status: "resolved" },
|
||||
{ source: null, path: ["UID"], target: 1, status: "resolved" },
|
||||
]);
|
||||
const selected = decodeKeyedArchiveBytes(
|
||||
Buffer.from(format === "binary" ? buildBinary(named) : build(named)),
|
||||
{ root: "UID", offset: 0, limit: 2 },
|
||||
);
|
||||
expect(selected.references).toEqual([
|
||||
expect.objectContaining({ path: ["UID"], target: 1 }),
|
||||
]);
|
||||
},
|
||||
);
|
||||
it("reports an XML archive dictionary keyed __proto__ as omitted", () => {
|
||||
const xml = build({ ...archive, $objects: ["$null", "value"] }).replace(
|
||||
"<key>$top</key>",
|
||||
"<key>__proto__</key><string>x</string><key>$top</key>",
|
||||
);
|
||||
const graph = decodeKeyedArchiveBytes(Buffer.from(xml), {
|
||||
offset: 0,
|
||||
limit: 2,
|
||||
});
|
||||
expect(graph.objects.map(({ value }) => value)).toEqual(["$null", "value"]);
|
||||
expect(graph.limitations).toContain(
|
||||
"1 dictionary entry keyed __proto__ was omitted because REA results cannot represent that key.",
|
||||
);
|
||||
});
|
||||
it("rejects missing roots, malformed plist, and non-keyed archives", () => {
|
||||
expect(() =>
|
||||
decodeKeyedArchiveBytes(Buffer.from("bplist00bad"), {
|
||||
offset: 0,
|
||||
limit: 1,
|
||||
}),
|
||||
).toThrow();
|
||||
expect(() =>
|
||||
decodeKeyedArchiveBytes(Buffer.from(build({ ...archive, $top: {} })), {
|
||||
offset: 0,
|
||||
limit: 1,
|
||||
}),
|
||||
).toThrow("roots");
|
||||
expect(() =>
|
||||
decodeKeyedArchiveBytes(Buffer.from(build({ plain: true })), {
|
||||
offset: 0,
|
||||
limit: 1,
|
||||
}),
|
||||
).toThrow("NSKeyedArchiver");
|
||||
expect(() =>
|
||||
decodeKeyedArchiveBytes(Buffer.from(buildBinary(archive)), {
|
||||
root: "missing",
|
||||
offset: 0,
|
||||
limit: 1,
|
||||
}),
|
||||
).toThrow("does not exist");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,149 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { TextDecoder } from "node:util";
|
||||
import { parseBinary } from "plist";
|
||||
import { z } from "zod";
|
||||
import type { JsonValue } from "../../domain/jsonValue.js";
|
||||
import { projectPlistValue } from "../../domain/apple/plistValue.js";
|
||||
import {
|
||||
omittedPrototypeKeysLimitation,
|
||||
parseXmlPropertyList,
|
||||
} from "../../domain/propertyListKeys.js";
|
||||
import {
|
||||
keyedArchiveInputSchema,
|
||||
keyedArchiveResultSchema,
|
||||
projectKeyedArchive,
|
||||
} from "../../domain/apple/keyedArchive.js";
|
||||
import { DirectoryArtifactReader } from "../DirectoryArtifactReader.js";
|
||||
import { ArtifactReaderFailure } from "../ArtifactReader.js";
|
||||
|
||||
const MAX_BYTES = 64 * 1024 * 1024;
|
||||
|
||||
/** Parse inert plist bytes, preserving data and dates with explicit typed values. */
|
||||
export const decodeKeyedArchiveBytes = (
|
||||
bytes: Buffer,
|
||||
selection: { root?: string | undefined; offset: number; limit: number },
|
||||
) => {
|
||||
if (bytes.length > MAX_BYTES)
|
||||
throw new RangeError("Keyed archive exceeds 64 MiB");
|
||||
const binary = bytes.subarray(0, 8).toString("ascii") === "bplist00";
|
||||
const parsed = binary
|
||||
? { value: parseBinary(bytes), omittedPrototypeKeys: 0 }
|
||||
: parseXmlPropertyList(decodeXmlPlistText(bytes));
|
||||
const graph = projectKeyedArchive(normalizePlist(parsed.value), selection);
|
||||
return {
|
||||
archive_format: binary ? ("binary-plist" as const) : ("xml-plist" as const),
|
||||
...graph,
|
||||
limitations: [
|
||||
...graph.limitations,
|
||||
...(parsed.omittedPrototypeKeys === 0
|
||||
? []
|
||||
: [omittedPrototypeKeysLimitation(parsed.omittedPrototypeKeys)]),
|
||||
],
|
||||
};
|
||||
};
|
||||
|
||||
const decodeXmlPlistText = (bytes: Buffer): string => {
|
||||
const encoding =
|
||||
bytes[0] === 0xff && bytes[1] === 0xfe
|
||||
? "utf-16le"
|
||||
: bytes[0] === 0xfe && bytes[1] === 0xff
|
||||
? "utf-16be"
|
||||
: "utf-8";
|
||||
const text = new TextDecoder(encoding, { fatal: true }).decode(bytes);
|
||||
const declared = /^<\?xml\s[^?]*\bencoding\s*=\s*["']([^"']+)["']/u
|
||||
.exec(text)?.[1]
|
||||
?.toLowerCase();
|
||||
if (
|
||||
declared !== undefined &&
|
||||
((encoding !== "utf-8" && declared !== encoding && declared !== "utf-16") ||
|
||||
(encoding === "utf-8" && declared.startsWith("utf-16")))
|
||||
)
|
||||
throw new TypeError("XML encoding declaration disagrees with its bytes");
|
||||
return text;
|
||||
};
|
||||
|
||||
const normalizePlist = (value: unknown): JsonValue => {
|
||||
const projected = projectPlistValue(value);
|
||||
if (projected.unknownRealCount > 0)
|
||||
throw new RangeError("Keyed archive contains a non-finite real");
|
||||
return projected.value;
|
||||
};
|
||||
|
||||
/** Read exactly one regular, contained bundle entry without following symlinks. */
|
||||
export const inspectBundleKeyedArchive = async (input: {
|
||||
bundlePath: string;
|
||||
targetSha256: string;
|
||||
parameters: unknown;
|
||||
signal?: AbortSignal;
|
||||
}) => {
|
||||
const selected = keyedArchiveInputSchema.parse(input.parameters);
|
||||
if (
|
||||
selected.path.startsWith("/") ||
|
||||
selected.path
|
||||
.split("/")
|
||||
.some((part) => part === ".." || part === "." || part.length === 0)
|
||||
)
|
||||
throw new ArtifactReaderFailure(
|
||||
"path",
|
||||
"Archive path must be a canonical relative bundle path",
|
||||
);
|
||||
const reader = new DirectoryArtifactReader(input.bundlePath);
|
||||
try {
|
||||
for await (const entry of reader.entries(input.signal)) {
|
||||
if (entry.path !== selected.path) continue;
|
||||
if (entry.kind !== "file")
|
||||
throw new ArtifactReaderFailure(
|
||||
"path",
|
||||
"Archive must be a regular file, not a symlink or directory",
|
||||
);
|
||||
if ((entry.declaredSize ?? 0) > MAX_BYTES)
|
||||
throw new ArtifactReaderFailure(
|
||||
"limit",
|
||||
"Keyed archive exceeds 64 MiB",
|
||||
);
|
||||
const stream = await reader.open(entry, input.signal);
|
||||
const chunks: Buffer[] = [];
|
||||
let size = 0;
|
||||
for await (const chunk of stream) {
|
||||
if (input.signal?.aborted) {
|
||||
stream.destroy();
|
||||
throw new ArtifactReaderFailure(
|
||||
"cancelled",
|
||||
"Archive inspection cancelled",
|
||||
);
|
||||
}
|
||||
const bytes = z.instanceof(Buffer).parse(chunk);
|
||||
size += bytes.length;
|
||||
if (size > MAX_BYTES) {
|
||||
stream.destroy();
|
||||
throw new ArtifactReaderFailure(
|
||||
"limit",
|
||||
"Keyed archive exceeds 64 MiB",
|
||||
);
|
||||
}
|
||||
chunks.push(bytes);
|
||||
}
|
||||
const bytes = Buffer.concat(chunks, size);
|
||||
try {
|
||||
return keyedArchiveResultSchema.parse({
|
||||
target_sha256: input.targetSha256,
|
||||
archive_path: entry.path,
|
||||
archive_sha256: createHash("sha256").update(bytes).digest("hex"),
|
||||
...decodeKeyedArchiveBytes(bytes, selected),
|
||||
});
|
||||
} catch (cause) {
|
||||
throw new ArtifactReaderFailure(
|
||||
cause instanceof RangeError ? "limit" : "format",
|
||||
"Cannot decode selected Foundation keyed archive",
|
||||
{ cause },
|
||||
);
|
||||
}
|
||||
}
|
||||
throw new ArtifactReaderFailure(
|
||||
"path",
|
||||
`Archive not found in bundle: ${selected.path}`,
|
||||
);
|
||||
} finally {
|
||||
await reader.close();
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,152 @@
|
||||
/** Little-endian Mach-O images and FAT containers built field by field for tests. */
|
||||
|
||||
export const LC = {
|
||||
LOAD_DYLIB: 0xc,
|
||||
ID_DYLIB: 0xd,
|
||||
LOAD_WEAK_DYLIB: 0x80000018,
|
||||
REEXPORT_DYLIB: 0x8000001f,
|
||||
LAZY_LOAD_DYLIB: 0x20,
|
||||
LOAD_UPWARD_DYLIB: 0x80000023,
|
||||
RPATH: 0x8000001c,
|
||||
DYLD_ENVIRONMENT: 0x27,
|
||||
CODE_SIGNATURE: 0x1d,
|
||||
} as const;
|
||||
|
||||
export const CPU = {
|
||||
arm64: { type: 0x0100000c, subtype: 0 },
|
||||
arm64e: { type: 0x0100000c, subtype: 0x80000002 },
|
||||
x86_64: { type: 0x01000007, subtype: 3 },
|
||||
} as const;
|
||||
|
||||
export const FILE_TYPE = { execute: 2, dylib: 6, bundle: 8 } as const;
|
||||
|
||||
const encoder = new TextEncoder();
|
||||
|
||||
/** One load command with a NUL-terminated string at `nameOffset`, padded to 8 bytes. */
|
||||
const commandWithString = (
|
||||
command: number,
|
||||
fields: readonly number[],
|
||||
text: string,
|
||||
): Uint8Array => {
|
||||
const nameOffset = 8 + fields.length * 4 + 4;
|
||||
const name = encoder.encode(text);
|
||||
const size = Math.ceil((nameOffset + name.length + 1) / 8) * 8;
|
||||
const bytes = new Uint8Array(size);
|
||||
const view = new DataView(bytes.buffer);
|
||||
view.setUint32(0, command, true);
|
||||
view.setUint32(4, size, true);
|
||||
view.setUint32(8, nameOffset, true);
|
||||
fields.forEach((value, index) => view.setUint32(12 + index * 4, value, true));
|
||||
bytes.set(name, nameOffset);
|
||||
return bytes;
|
||||
};
|
||||
|
||||
/** Classic `dylib_command`: timestamp, current and compatibility versions. */
|
||||
export const dylibCommand = (
|
||||
command: number,
|
||||
name: string,
|
||||
versions: { readonly current?: number; readonly compatibility?: number } = {},
|
||||
): Uint8Array =>
|
||||
commandWithString(
|
||||
command,
|
||||
[2, versions.current ?? 0x10000, versions.compatibility ?? 0x10000],
|
||||
name,
|
||||
);
|
||||
|
||||
/** `dylib_use_command`: marker, versions and `DYLIB_USE_*` flags. */
|
||||
export const dylibUseCommand = (
|
||||
command: number,
|
||||
name: string,
|
||||
flags: number,
|
||||
): Uint8Array =>
|
||||
commandWithString(command, [0x1a741800, 0x10000, 0x10000, flags], name);
|
||||
|
||||
export const rpathCommand = (path: string): Uint8Array =>
|
||||
commandWithString(LC.RPATH, [], path);
|
||||
|
||||
export const dyldEnvironmentCommand = (value: string): Uint8Array =>
|
||||
commandWithString(LC.DYLD_ENVIRONMENT, [], value);
|
||||
|
||||
export const codeSignatureCommand = (): Uint8Array => {
|
||||
const bytes = new Uint8Array(16);
|
||||
const view = new DataView(bytes.buffer);
|
||||
view.setUint32(0, LC.CODE_SIGNATURE, true);
|
||||
view.setUint32(4, 16, 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 };
|
||||
readonly fileType?: number;
|
||||
readonly commands?: readonly Uint8Array[];
|
||||
readonly wide?: boolean;
|
||||
}): Uint8Array => {
|
||||
const wide = options.wide ?? true;
|
||||
const commands = options.commands ?? [];
|
||||
const headerSize = wide ? 32 : 28;
|
||||
const commandBytes = commands.reduce((total, item) => total + item.length, 0);
|
||||
const bytes = new Uint8Array(headerSize + commandBytes + 16);
|
||||
const view = new DataView(bytes.buffer);
|
||||
const cpu = options.cpu ?? CPU.arm64;
|
||||
view.setUint32(0, wide ? 0xfeedfacf : 0xfeedface, true);
|
||||
view.setUint32(4, cpu.type, true);
|
||||
view.setUint32(8, cpu.subtype, true);
|
||||
view.setUint32(12, options.fileType ?? FILE_TYPE.execute, true);
|
||||
view.setUint32(16, commands.length, true);
|
||||
view.setUint32(20, commandBytes, true);
|
||||
let offset = headerSize;
|
||||
for (const command of commands) {
|
||||
bytes.set(command, offset);
|
||||
offset += command.length;
|
||||
}
|
||||
return bytes;
|
||||
};
|
||||
|
||||
/**
|
||||
* A FAT container whose slices start on 4 KiB boundaries. Headers are
|
||||
* big-endian unless `littleEndian` selects the swapped FAT_CIGAM magics.
|
||||
*/
|
||||
export const fatImage = (
|
||||
slices: readonly {
|
||||
readonly cpu: { readonly type: number; readonly subtype: number };
|
||||
readonly bytes: Uint8Array;
|
||||
}[],
|
||||
wide = false,
|
||||
littleEndian = false,
|
||||
): Uint8Array => {
|
||||
const entrySize = wide ? 32 : 20;
|
||||
const offsets: number[] = [];
|
||||
let end = 4096;
|
||||
for (const slice of slices) {
|
||||
offsets.push(end);
|
||||
end += Math.ceil(slice.bytes.length / 4096) * 4096;
|
||||
}
|
||||
const bytes = new Uint8Array(end);
|
||||
const view = new DataView(bytes.buffer);
|
||||
view.setUint32(0, wide ? 0xcafebabf : 0xcafebabe, littleEndian);
|
||||
view.setUint32(4, slices.length, littleEndian);
|
||||
slices.forEach((slice, index) => {
|
||||
const base = 8 + index * entrySize;
|
||||
const offset = offsets[index] ?? 0;
|
||||
view.setUint32(base, slice.cpu.type, littleEndian);
|
||||
view.setUint32(base + 4, slice.cpu.subtype, littleEndian);
|
||||
if (wide) {
|
||||
view.setBigUint64(base + 8, BigInt(offset), littleEndian);
|
||||
view.setBigUint64(base + 16, BigInt(slice.bytes.length), littleEndian);
|
||||
view.setUint32(base + 24, 12, littleEndian);
|
||||
} else {
|
||||
view.setUint32(base + 8, offset, littleEndian);
|
||||
view.setUint32(base + 12, slice.bytes.length, littleEndian);
|
||||
view.setUint32(base + 16, 12, littleEndian);
|
||||
}
|
||||
bytes.set(slice.bytes, offset);
|
||||
});
|
||||
return bytes;
|
||||
};
|
||||
|
||||
/** In-memory `ReadAt` over one buffer. */
|
||||
export const readerOf =
|
||||
(bytes: Uint8Array) =>
|
||||
(offset: number, length: number): Promise<Uint8Array> =>
|
||||
Promise.resolve(bytes.subarray(offset, offset + length));
|
||||
@@ -0,0 +1,316 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
CPU,
|
||||
FILE_TYPE,
|
||||
LC,
|
||||
codeSignatureCommand,
|
||||
dyldEnvironmentCommand,
|
||||
dylibCommand,
|
||||
dylibUseCommand,
|
||||
fatImage,
|
||||
machoImage,
|
||||
readerOf,
|
||||
rpathCommand,
|
||||
} from "./MachoImage.fixture.js";
|
||||
import {
|
||||
MAX_LOAD_COMMAND_BYTES,
|
||||
hasMachoMagic,
|
||||
readMachoImage,
|
||||
} from "./MachoLoadCommandReader.js";
|
||||
|
||||
const read = (bytes: Uint8Array) =>
|
||||
readMachoImage(readerOf(bytes), bytes.length);
|
||||
|
||||
describe("Mach-O load command reader", () => {
|
||||
it("decodes dylib loading commands of a thin image", async () => {
|
||||
const image = machoImage({
|
||||
fileType: FILE_TYPE.dylib,
|
||||
commands: [
|
||||
dylibCommand(LC.ID_DYLIB, "@rpath/Core.framework/Core"),
|
||||
dylibCommand(LC.LOAD_DYLIB, "/usr/lib/libSystem.B.dylib", {
|
||||
current: 0x050f0400,
|
||||
compatibility: 0x10000,
|
||||
}),
|
||||
dylibCommand(LC.LOAD_WEAK_DYLIB, "@rpath/libweak.dylib"),
|
||||
dylibCommand(LC.REEXPORT_DYLIB, "@loader_path/libre.dylib"),
|
||||
dylibCommand(LC.LOAD_UPWARD_DYLIB, "@rpath/libup.dylib"),
|
||||
dylibCommand(LC.LAZY_LOAD_DYLIB, "@rpath/liblazy.dylib"),
|
||||
rpathCommand("@loader_path/Frameworks"),
|
||||
rpathCommand("/usr/lib/swift"),
|
||||
dyldEnvironmentCommand("DYLD_FRAMEWORK_PATH=@executable_path"),
|
||||
codeSignatureCommand(),
|
||||
],
|
||||
});
|
||||
const facts = await read(image);
|
||||
expect(facts.status).toBe("parsed");
|
||||
if (facts.status !== "parsed") return;
|
||||
expect(facts.slices).toHaveLength(1);
|
||||
const [slice] = facts.slices;
|
||||
expect(slice).toMatchObject({
|
||||
architecture: "arm64",
|
||||
file_type: "dylib",
|
||||
install_name: "@rpath/Core.framework/Core",
|
||||
rpaths: ["@loader_path/Frameworks", "/usr/lib/swift"],
|
||||
dyld_environment: ["DYLD_FRAMEWORK_PATH=@executable_path"],
|
||||
code_signature_present: true,
|
||||
});
|
||||
expect(
|
||||
slice?.dependencies.map(
|
||||
({ command, install_name: name, weak, reexport, upward }) => [
|
||||
command,
|
||||
name,
|
||||
weak,
|
||||
reexport,
|
||||
upward,
|
||||
],
|
||||
),
|
||||
).toEqual([
|
||||
["LC_LOAD_DYLIB", "/usr/lib/libSystem.B.dylib", false, false, false],
|
||||
["LC_LOAD_WEAK_DYLIB", "@rpath/libweak.dylib", true, false, false],
|
||||
["LC_REEXPORT_DYLIB", "@loader_path/libre.dylib", false, true, false],
|
||||
["LC_LOAD_UPWARD_DYLIB", "@rpath/libup.dylib", false, false, true],
|
||||
["LC_LAZY_LOAD_DYLIB", "@rpath/liblazy.dylib", false, false, false],
|
||||
]);
|
||||
expect(slice?.dependencies[0]).toMatchObject({
|
||||
encoding: "dylib_command",
|
||||
current_version: "1295.4.0",
|
||||
compatibility_version: "1.0.0",
|
||||
});
|
||||
});
|
||||
|
||||
it("decodes dylib_use_command flags", async () => {
|
||||
const facts = await read(
|
||||
machoImage({
|
||||
commands: [
|
||||
dylibUseCommand(LC.LOAD_DYLIB, "@rpath/libdelay.dylib", 0x8),
|
||||
dylibUseCommand(LC.LOAD_DYLIB, "@rpath/libweakup.dylib", 0x1 | 0x4),
|
||||
dylibUseCommand(LC.LOAD_DYLIB, "@rpath/libre.dylib", 0x2),
|
||||
],
|
||||
}),
|
||||
);
|
||||
if (facts.status !== "parsed") throw new Error(facts.status);
|
||||
expect(
|
||||
facts.slices[0]?.dependencies.map(
|
||||
({ encoding, weak, upward, reexport, delayed_init: delayed }) => ({
|
||||
encoding,
|
||||
weak,
|
||||
upward,
|
||||
reexport,
|
||||
delayed,
|
||||
}),
|
||||
),
|
||||
).toEqual([
|
||||
{
|
||||
encoding: "dylib_use_command",
|
||||
weak: false,
|
||||
upward: false,
|
||||
reexport: false,
|
||||
delayed: true,
|
||||
},
|
||||
{
|
||||
encoding: "dylib_use_command",
|
||||
weak: true,
|
||||
upward: true,
|
||||
reexport: false,
|
||||
delayed: false,
|
||||
},
|
||||
{
|
||||
encoding: "dylib_use_command",
|
||||
weak: false,
|
||||
upward: false,
|
||||
reexport: true,
|
||||
delayed: false,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("reads every slice of FAT and FAT_64 containers in either byte order", async () => {
|
||||
for (const [wide, littleEndian] of [
|
||||
[false, false],
|
||||
[true, false],
|
||||
[false, true],
|
||||
[true, true],
|
||||
] as const) {
|
||||
const facts = await read(
|
||||
fatImage(
|
||||
[
|
||||
{
|
||||
cpu: CPU.arm64e,
|
||||
bytes: machoImage({
|
||||
cpu: CPU.arm64e,
|
||||
commands: [rpathCommand("@executable_path/a")],
|
||||
}),
|
||||
},
|
||||
{
|
||||
cpu: CPU.x86_64,
|
||||
bytes: machoImage({
|
||||
cpu: CPU.x86_64,
|
||||
commands: [rpathCommand("@executable_path/b")],
|
||||
}),
|
||||
},
|
||||
],
|
||||
wide,
|
||||
littleEndian,
|
||||
),
|
||||
);
|
||||
if (facts.status !== "parsed") throw new Error(facts.status);
|
||||
expect(
|
||||
facts.slices.map(({ architecture, rpaths }) => [architecture, rpaths]),
|
||||
).toEqual([
|
||||
["arm64e", ["@executable_path/a"]],
|
||||
["x86_64", ["@executable_path/b"]],
|
||||
]);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("Mach-O load command reader inputs", () => {
|
||||
it("names 32-bit and non-Mach-O inputs without guessing", async () => {
|
||||
const i386 = await read(
|
||||
machoImage({ cpu: { type: 7, subtype: 3 }, wide: false }),
|
||||
);
|
||||
expect(i386.status === "parsed" && i386.slices[0]?.architecture).toBe(
|
||||
"i386",
|
||||
);
|
||||
// A Java class file shares the FAT magic; its version is not a slice count.
|
||||
const javaClass = Uint8Array.from([0xca, 0xfe, 0xba, 0xbe, 0, 0, 0, 0x34]);
|
||||
expect(hasMachoMagic(javaClass)).toBe(true);
|
||||
expect(await read(javaClass)).toEqual({ status: "not-mach-o" });
|
||||
expect(await read(new TextEncoder().encode("#!/bin/sh\n"))).toEqual({
|
||||
status: "not-mach-o",
|
||||
});
|
||||
expect(await read(Uint8Array.from([0xcf, 0xfa]))).toEqual({
|
||||
status: "not-mach-o",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("Mach-O load command reader failures", () => {
|
||||
const withCommandSize = (size: number): Uint8Array => {
|
||||
const image = machoImage({ commands: [rpathCommand("@loader_path")] });
|
||||
new DataView(image.buffer).setUint32(32 + 4, size, true);
|
||||
return image;
|
||||
};
|
||||
|
||||
it("reports malformed command tables with the failing command", async () => {
|
||||
expect(await read(withCommandSize(0))).toMatchObject({
|
||||
status: "malformed",
|
||||
reason: expect.stringContaining("load command 0"),
|
||||
});
|
||||
expect(await read(withCommandSize(4096))).toMatchObject({
|
||||
status: "malformed",
|
||||
reason: expect.stringContaining("invalid cmdsize"),
|
||||
});
|
||||
const extraCommand = machoImage({ commands: [rpathCommand("x")] });
|
||||
new DataView(extraCommand.buffer).setUint32(16, 2, true);
|
||||
expect(await read(extraCommand)).toMatchObject({
|
||||
status: "malformed",
|
||||
reason: "load command 1 starts beyond sizeofcmds",
|
||||
});
|
||||
});
|
||||
|
||||
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, 0x7f000001, true);
|
||||
view.setUint32(4, 12, true);
|
||||
expect(await read(machoImage({ commands: [command] }))).toMatchObject({
|
||||
status: "malformed",
|
||||
reason: expect.stringContaining("invalid cmdsize 12"),
|
||||
});
|
||||
expect(
|
||||
await read(
|
||||
machoImage({
|
||||
cpu: { type: 7, subtype: 3 },
|
||||
wide: false,
|
||||
commands: [command],
|
||||
}),
|
||||
),
|
||||
).toMatchObject({ status: "parsed" });
|
||||
});
|
||||
|
||||
it("accepts FAT tables up to 128 records that name a Mach-O CPU", async () => {
|
||||
const slices = Array.from({ length: 24 }, () => ({
|
||||
cpu: CPU.arm64,
|
||||
bytes: machoImage({}),
|
||||
}));
|
||||
const facts = await read(fatImage(slices));
|
||||
expect(facts.status === "parsed" && facts.slices).toHaveLength(24);
|
||||
// An empty table is not a Java class file, whose major version is nonzero.
|
||||
for (const magic of [
|
||||
[0xca, 0xfe, 0xba, 0xbe],
|
||||
[0xbf, 0xba, 0xfe, 0xca],
|
||||
])
|
||||
expect(await read(Uint8Array.from([...magic, 0, 0, 0, 0]))).toEqual({
|
||||
status: "malformed",
|
||||
reason: "FAT header declares no architectures",
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects string commands too short to hold their string offset", async () => {
|
||||
const short = new Uint8Array(8);
|
||||
const view = new DataView(short.buffer);
|
||||
view.setUint32(0, LC.RPATH, true);
|
||||
view.setUint32(4, 8, true);
|
||||
expect(await read(machoImage({ commands: [short] }))).toMatchObject({
|
||||
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 () => {
|
||||
const unterminated = rpathCommand("abcd");
|
||||
unterminated.fill(0x41, 12);
|
||||
expect(await read(machoImage({ commands: [unterminated] }))).toMatchObject({
|
||||
status: "malformed",
|
||||
reason: expect.stringContaining("unterminated"),
|
||||
});
|
||||
const misplaced = rpathCommand("abcd");
|
||||
new DataView(misplaced.buffer).setUint32(8, 4, true);
|
||||
expect(await read(machoImage({ commands: [misplaced] }))).toMatchObject({
|
||||
status: "malformed",
|
||||
reason: expect.stringContaining("string offset 4"),
|
||||
});
|
||||
const invalid = rpathCommand("ab");
|
||||
invalid[12] = 0xff;
|
||||
expect(await read(machoImage({ commands: [invalid] }))).toMatchObject({
|
||||
status: "malformed",
|
||||
reason: expect.stringContaining("not UTF-8"),
|
||||
});
|
||||
});
|
||||
|
||||
it("refuses truncated, oversized, big-endian and out-of-range images", async () => {
|
||||
const image = machoImage({ commands: [rpathCommand("@loader_path")] });
|
||||
expect(await read(image.subarray(0, 20))).toMatchObject({
|
||||
status: "malformed",
|
||||
reason: "Mach-O header is truncated",
|
||||
});
|
||||
const oversized = machoImage({});
|
||||
new DataView(oversized.buffer).setUint32(
|
||||
20,
|
||||
MAX_LOAD_COMMAND_BYTES + 8,
|
||||
true,
|
||||
);
|
||||
expect(await read(oversized)).toMatchObject({ status: "unsupported" });
|
||||
const beyond = machoImage({ commands: [rpathCommand("x")] });
|
||||
new DataView(beyond.buffer).setUint32(20, beyond.length, true);
|
||||
expect(await read(beyond)).toMatchObject({
|
||||
status: "malformed",
|
||||
reason: "load commands extend beyond the Mach-O slice",
|
||||
});
|
||||
const bigEndian = Uint8Array.from([0xfe, 0xed, 0xfa, 0xcf, 0, 0, 0, 0]);
|
||||
expect(await read(bigEndian)).toMatchObject({ status: "unsupported" });
|
||||
const fat = fatImage([{ cpu: CPU.arm64, bytes: machoImage({}) }]);
|
||||
expect(await read(fat.subarray(0, 4100))).toMatchObject({
|
||||
status: "malformed",
|
||||
reason: "FAT architecture 0 extends beyond the file",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,422 @@
|
||||
import type {
|
||||
MachoDependency,
|
||||
MachoImageFacts,
|
||||
MachoSlice,
|
||||
} from "../../domain/apple/dylibResolution.js";
|
||||
|
||||
/** Read `length` bytes at `offset`; shorter results mean end of file. */
|
||||
export type ReadAt = (offset: number, length: number) => Promise<Uint8Array>;
|
||||
|
||||
/** Load commands larger than this are refused instead of buffered. */
|
||||
export const MAX_LOAD_COMMAND_BYTES = 16 * 1024 * 1024;
|
||||
/** Target opening accepts up to 128 FAT records; Java class files share the FAT magic. */
|
||||
const MAX_FAT_ARCHITECTURES = 128;
|
||||
/** CPU types of real Mach-O slices (x86, x86_64, arm, arm64, arm64_32, ppc, ppc64). */
|
||||
const KNOWN_CPU_TYPES: readonly number[] = [
|
||||
7, 0x01000007, 12, 0x0100000c, 0x0200000c, 18, 0x01000012,
|
||||
];
|
||||
|
||||
const MH_MAGIC = 0xfeedface;
|
||||
const MH_MAGIC_64 = 0xfeedfacf;
|
||||
const MH_CIGAM = 0xcefaedfe;
|
||||
const MH_CIGAM_64 = 0xcffaedfe;
|
||||
const FAT_MAGIC = 0xcafebabe;
|
||||
const FAT_MAGIC_64 = 0xcafebabf;
|
||||
const FAT_CIGAM = 0xbebafeca;
|
||||
const FAT_CIGAM_64 = 0xbfbafeca;
|
||||
|
||||
const LC_ID_DYLIB = 0xd;
|
||||
const LC_LOAD_DYLIB = 0xc;
|
||||
const LC_LOAD_WEAK_DYLIB = 0x80000018;
|
||||
const LC_REEXPORT_DYLIB = 0x8000001f;
|
||||
const LC_LAZY_LOAD_DYLIB = 0x20;
|
||||
const LC_LOAD_UPWARD_DYLIB = 0x80000023;
|
||||
const LC_RPATH = 0x8000001c;
|
||||
const LC_DYLD_ENVIRONMENT = 0x27;
|
||||
const LC_CODE_SIGNATURE = 0x1d;
|
||||
|
||||
/** `mach-o/loader.h` `dylib_use_command`: `nameoff == 28` and this marker. */
|
||||
const DYLIB_USE_MARKER = 0x1a741800;
|
||||
const DYLIB_USE_WEAK_LINK = 0x1;
|
||||
const DYLIB_USE_REEXPORT = 0x2;
|
||||
const DYLIB_USE_UPWARD = 0x4;
|
||||
const DYLIB_USE_DELAYED_INIT = 0x8;
|
||||
|
||||
const DEPENDENCY_COMMANDS: ReadonlyMap<number, MachoDependency["command"]> =
|
||||
new Map([
|
||||
[LC_LOAD_DYLIB, "LC_LOAD_DYLIB"],
|
||||
[LC_LOAD_WEAK_DYLIB, "LC_LOAD_WEAK_DYLIB"],
|
||||
[LC_REEXPORT_DYLIB, "LC_REEXPORT_DYLIB"],
|
||||
[LC_LAZY_LOAD_DYLIB, "LC_LAZY_LOAD_DYLIB"],
|
||||
[LC_LOAD_UPWARD_DYLIB, "LC_LOAD_UPWARD_DYLIB"],
|
||||
]);
|
||||
|
||||
/** Malformed or unsupported structure found while decoding one image. */
|
||||
class MachoFormatIssue extends Error {
|
||||
constructor(
|
||||
readonly status: "malformed" | "unsupported",
|
||||
message: string,
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
/** Report whether the first bytes carry a Mach-O or FAT magic number. */
|
||||
export const hasMachoMagic = (head: Uint8Array): boolean => {
|
||||
if (head.byteLength < 4) return false;
|
||||
const magic = new DataView(
|
||||
head.buffer,
|
||||
head.byteOffset,
|
||||
head.byteLength,
|
||||
).getUint32(0, false);
|
||||
return [
|
||||
MH_MAGIC,
|
||||
MH_MAGIC_64,
|
||||
MH_CIGAM,
|
||||
MH_CIGAM_64,
|
||||
FAT_MAGIC,
|
||||
FAT_MAGIC_64,
|
||||
FAT_CIGAM,
|
||||
FAT_CIGAM_64,
|
||||
].includes(magic);
|
||||
};
|
||||
|
||||
/** Decode every slice's dylib-loading load commands without reading code. */
|
||||
export const readMachoImage = async (
|
||||
readAt: ReadAt,
|
||||
size: number,
|
||||
): Promise<MachoImageFacts> => {
|
||||
try {
|
||||
const head = await readAt(0, Math.min(size, 8));
|
||||
if (head.byteLength < 8) return { status: "not-mach-o" };
|
||||
const view = viewOf(head);
|
||||
const magic = view.getUint32(0, false);
|
||||
if ([FAT_MAGIC, FAT_MAGIC_64, FAT_CIGAM, FAT_CIGAM_64].includes(magic)) {
|
||||
// FAT headers are big-endian; the swapped magics store them little-endian.
|
||||
const littleEndian = magic === FAT_CIGAM || magic === FAT_CIGAM_64;
|
||||
const count = view.getUint32(4, littleEndian);
|
||||
const wide = magic === FAT_MAGIC_64 || magic === FAT_CIGAM_64;
|
||||
// A Java class file's nonzero major version reads as the count, so an
|
||||
// empty architecture table can only be a malformed universal header.
|
||||
if (count === 0)
|
||||
return {
|
||||
status: "malformed",
|
||||
reason: "FAT header declares no architectures",
|
||||
};
|
||||
if (count > MAX_FAT_ARCHITECTURES || 8 + count * (wide ? 32 : 20) > size)
|
||||
return { status: "not-mach-o" };
|
||||
const table = viewOf(
|
||||
await readExact(readAt, 8, count * (wide ? 32 : 20), "FAT table"),
|
||||
);
|
||||
// A Java class file's version fields read as a FAT count; its "table" names no CPU.
|
||||
const cpuTypes = Array.from({ length: count }, (_, index) =>
|
||||
table.getUint32(index * (wide ? 32 : 20), littleEndian),
|
||||
);
|
||||
if (!cpuTypes.some((type) => KNOWN_CPU_TYPES.includes(type)))
|
||||
return { status: "not-mach-o" };
|
||||
return {
|
||||
status: "parsed",
|
||||
slices: await readFatSlices(readAt, size, {
|
||||
wide,
|
||||
littleEndian,
|
||||
count,
|
||||
}),
|
||||
};
|
||||
}
|
||||
if (magic === MH_CIGAM || magic === MH_CIGAM_64)
|
||||
return { status: "parsed", slices: [await readSlice(readAt, 0, size)] };
|
||||
if (magic === MH_MAGIC || magic === MH_MAGIC_64)
|
||||
throw new MachoFormatIssue(
|
||||
"unsupported",
|
||||
"big-endian Mach-O images are not supported",
|
||||
);
|
||||
return { status: "not-mach-o" };
|
||||
} catch (cause: unknown) {
|
||||
if (cause instanceof MachoFormatIssue)
|
||||
return { status: cause.status, reason: cause.message };
|
||||
throw cause;
|
||||
}
|
||||
};
|
||||
|
||||
const readFatSlices = async (
|
||||
readAt: ReadAt,
|
||||
size: number,
|
||||
table: {
|
||||
readonly wide: boolean;
|
||||
readonly littleEndian: boolean;
|
||||
readonly count: number;
|
||||
},
|
||||
): Promise<MachoSlice[]> => {
|
||||
const { wide, littleEndian, count } = table;
|
||||
const entrySize = wide ? 32 : 20;
|
||||
const view = viewOf(
|
||||
await readExact(readAt, 8, count * entrySize, "FAT table"),
|
||||
);
|
||||
const slices: MachoSlice[] = [];
|
||||
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 length = wide
|
||||
? safeNumber(view.getBigUint64(base + 16, littleEndian))
|
||||
: view.getUint32(base + 12, littleEndian);
|
||||
if (offset + length > size)
|
||||
throw new MachoFormatIssue(
|
||||
"malformed",
|
||||
`FAT architecture ${index} extends beyond the file`,
|
||||
);
|
||||
slices.push(await readSlice(readAt, offset, length));
|
||||
}
|
||||
return slices;
|
||||
};
|
||||
|
||||
const readSlice = async (
|
||||
readAt: ReadAt,
|
||||
base: number,
|
||||
length: number,
|
||||
): Promise<MachoSlice> => {
|
||||
const header = viewOf(await readExact(readAt, base, 28, "Mach-O header"));
|
||||
const magic = header.getUint32(0, true);
|
||||
if (magic === MH_MAGIC_64 || magic === MH_MAGIC) {
|
||||
const wide = magic === MH_MAGIC_64;
|
||||
const headerSize = wide ? 32 : 28;
|
||||
const commandCount = header.getUint32(16, true);
|
||||
const commandBytes = header.getUint32(20, true);
|
||||
if (commandBytes > MAX_LOAD_COMMAND_BYTES)
|
||||
throw new MachoFormatIssue(
|
||||
"unsupported",
|
||||
`load commands occupy ${commandBytes} bytes, above the ${MAX_LOAD_COMMAND_BYTES}-byte limit`,
|
||||
);
|
||||
if (headerSize + commandBytes > length)
|
||||
throw new MachoFormatIssue(
|
||||
"malformed",
|
||||
"load commands extend beyond the Mach-O slice",
|
||||
);
|
||||
const commands = await readExact(
|
||||
readAt,
|
||||
base + headerSize,
|
||||
commandBytes,
|
||||
"load commands",
|
||||
);
|
||||
return decodeCommands(commands, {
|
||||
wide,
|
||||
cpuType: header.getUint32(4, true),
|
||||
cpuSubtype: header.getUint32(8, true),
|
||||
fileType: header.getUint32(12, true),
|
||||
commandCount,
|
||||
});
|
||||
}
|
||||
throw new MachoFormatIssue(
|
||||
magic === swap(MH_MAGIC) || magic === swap(MH_MAGIC_64)
|
||||
? "unsupported"
|
||||
: "malformed",
|
||||
magic === swap(MH_MAGIC) || magic === swap(MH_MAGIC_64)
|
||||
? "big-endian Mach-O slices are not supported"
|
||||
: `slice at offset ${base} has no Mach-O header`,
|
||||
);
|
||||
};
|
||||
|
||||
const decodeCommands = (
|
||||
bytes: Uint8Array,
|
||||
header: {
|
||||
readonly wide: boolean;
|
||||
readonly cpuType: number;
|
||||
readonly cpuSubtype: number;
|
||||
readonly fileType: number;
|
||||
readonly commandCount: number;
|
||||
},
|
||||
): MachoSlice => {
|
||||
// loader.h: load commands are 8-byte aligned in 64-bit images, 4 in 32-bit.
|
||||
const alignment = header.wide ? 8 : 4;
|
||||
const view = viewOf(bytes);
|
||||
const slice: MachoSlice = {
|
||||
architecture: architectureName(header.cpuType, header.cpuSubtype),
|
||||
file_type: fileTypeName(header.fileType),
|
||||
install_name: null,
|
||||
dependencies: [],
|
||||
rpaths: [],
|
||||
dyld_environment: [],
|
||||
code_signature_present: false,
|
||||
};
|
||||
let offset = 0;
|
||||
for (let index = 0; index < header.commandCount; index++) {
|
||||
if (offset + 8 > bytes.byteLength)
|
||||
throw new MachoFormatIssue(
|
||||
"malformed",
|
||||
`load command ${index} starts beyond sizeofcmds`,
|
||||
);
|
||||
const command = view.getUint32(offset, true);
|
||||
const size = view.getUint32(offset + 4, true);
|
||||
if (size < 8 || size % alignment !== 0 || offset + size > bytes.byteLength)
|
||||
throw new MachoFormatIssue(
|
||||
"malformed",
|
||||
`load command ${index} at offset ${offset} has invalid cmdsize ${size}`,
|
||||
);
|
||||
const body = bytes.subarray(offset, offset + size);
|
||||
decodeCommand(command, body, index, slice);
|
||||
offset += size;
|
||||
}
|
||||
return slice;
|
||||
};
|
||||
|
||||
const decodeCommand = (
|
||||
command: number,
|
||||
body: Uint8Array,
|
||||
index: number,
|
||||
slice: MachoSlice,
|
||||
): void => {
|
||||
if (command === LC_ID_DYLIB) {
|
||||
slice.install_name = commandString(body, 24, index);
|
||||
return;
|
||||
}
|
||||
if (command === LC_RPATH) {
|
||||
slice.rpaths.push(commandString(body, 12, index));
|
||||
return;
|
||||
}
|
||||
if (command === LC_DYLD_ENVIRONMENT) {
|
||||
slice.dyld_environment.push(commandString(body, 12, index));
|
||||
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 name = DEPENDENCY_COMMANDS.get(command);
|
||||
if (name !== undefined)
|
||||
slice.dependencies.push(decodeDependency(name, body, index));
|
||||
};
|
||||
|
||||
const decodeDependency = (
|
||||
command: MachoDependency["command"],
|
||||
body: Uint8Array,
|
||||
index: number,
|
||||
): MachoDependency => {
|
||||
if (body.byteLength < 24)
|
||||
throw new MachoFormatIssue(
|
||||
"malformed",
|
||||
`load command ${index} is too short for a dylib command`,
|
||||
);
|
||||
const view = viewOf(body);
|
||||
const nameOffset = view.getUint32(8, true);
|
||||
const usesFlags =
|
||||
nameOffset === 28 &&
|
||||
body.byteLength >= 28 &&
|
||||
view.getUint32(12, true) === DYLIB_USE_MARKER;
|
||||
const flags = usesFlags ? view.getUint32(24, true) : 0;
|
||||
return {
|
||||
command,
|
||||
encoding: usesFlags ? "dylib_use_command" : "dylib_command",
|
||||
install_name: commandString(body, usesFlags ? 28 : 24, index),
|
||||
weak:
|
||||
command === "LC_LOAD_WEAK_DYLIB" || (flags & DYLIB_USE_WEAK_LINK) !== 0,
|
||||
upward:
|
||||
command === "LC_LOAD_UPWARD_DYLIB" || (flags & DYLIB_USE_UPWARD) !== 0,
|
||||
reexport:
|
||||
command === "LC_REEXPORT_DYLIB" || (flags & DYLIB_USE_REEXPORT) !== 0,
|
||||
delayed_init: (flags & DYLIB_USE_DELAYED_INIT) !== 0,
|
||||
current_version: version(view.getUint32(16, true)),
|
||||
compatibility_version: version(view.getUint32(20, true)),
|
||||
};
|
||||
};
|
||||
|
||||
/** NUL-terminated UTF-8 string at a `lc_str` offset inside one command. */
|
||||
const commandString = (
|
||||
body: Uint8Array,
|
||||
minimumOffset: number,
|
||||
index: number,
|
||||
): string => {
|
||||
if (body.byteLength < 12)
|
||||
throw new MachoFormatIssue(
|
||||
"malformed",
|
||||
`load command ${index} is too short to hold a string offset`,
|
||||
);
|
||||
const offset = viewOf(body).getUint32(8, true);
|
||||
if (offset < minimumOffset || offset >= body.byteLength)
|
||||
throw new MachoFormatIssue(
|
||||
"malformed",
|
||||
`load command ${index} has string offset ${offset} outside the command`,
|
||||
);
|
||||
const end = body.indexOf(0, offset);
|
||||
if (end < 0)
|
||||
throw new MachoFormatIssue(
|
||||
"malformed",
|
||||
`load command ${index} has an unterminated string`,
|
||||
);
|
||||
try {
|
||||
return new TextDecoder("utf-8", { fatal: true }).decode(
|
||||
body.subarray(offset, end),
|
||||
);
|
||||
} catch {
|
||||
throw new MachoFormatIssue(
|
||||
"malformed",
|
||||
`load command ${index} has a string that is not UTF-8`,
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const readExact = async (
|
||||
readAt: ReadAt,
|
||||
offset: number,
|
||||
length: number,
|
||||
label: string,
|
||||
): Promise<Uint8Array> => {
|
||||
const bytes = await readAt(offset, length);
|
||||
if (bytes.byteLength < length)
|
||||
throw new MachoFormatIssue("malformed", `${label} is truncated`);
|
||||
return bytes;
|
||||
};
|
||||
|
||||
const CPU_ARCH_ABI64 = 0x01000000;
|
||||
const CPU_ARCH_ABI64_32 = 0x02000000;
|
||||
const CPU_TYPE_X86 = 7;
|
||||
const CPU_TYPE_ARM = 12;
|
||||
const CPU_SUBTYPE_MASK = 0xff000000;
|
||||
const CPU_SUBTYPE_ARM64E = 2;
|
||||
const CPU_SUBTYPE_X86_64_H = 8;
|
||||
|
||||
const architectureName = (cpuType: number, cpuSubtype: number): string => {
|
||||
const subtype = cpuSubtype & ~CPU_SUBTYPE_MASK;
|
||||
if (cpuType === (CPU_TYPE_ARM | CPU_ARCH_ABI64))
|
||||
return subtype === CPU_SUBTYPE_ARM64E ? "arm64e" : "arm64";
|
||||
if (cpuType === (CPU_TYPE_ARM | CPU_ARCH_ABI64_32)) return "arm64_32";
|
||||
if (cpuType === (CPU_TYPE_X86 | CPU_ARCH_ABI64))
|
||||
return subtype === CPU_SUBTYPE_X86_64_H ? "x86_64h" : "x86_64";
|
||||
if (cpuType === CPU_TYPE_X86) return "i386";
|
||||
if (cpuType === CPU_TYPE_ARM) return "arm";
|
||||
return `cpu-${cpuType.toString(16)}`;
|
||||
};
|
||||
|
||||
const fileTypeName = (fileType: number): MachoSlice["file_type"] =>
|
||||
fileType === 2
|
||||
? "execute"
|
||||
: fileType === 6
|
||||
? "dylib"
|
||||
: fileType === 8
|
||||
? "bundle"
|
||||
: "other";
|
||||
|
||||
const version = (value: number): string =>
|
||||
`${value >>> 16}.${(value >>> 8) & 0xff}.${value & 0xff}`;
|
||||
|
||||
const swap = (value: number): number =>
|
||||
(((value & 0xff) << 24) |
|
||||
((value & 0xff00) << 8) |
|
||||
((value >>> 8) & 0xff00) |
|
||||
(value >>> 24)) >>>
|
||||
0;
|
||||
|
||||
const safeNumber = (value: bigint): number => {
|
||||
if (value > BigInt(Number.MAX_SAFE_INTEGER))
|
||||
throw new MachoFormatIssue("malformed", "FAT offset exceeds safe range");
|
||||
return Number(value);
|
||||
};
|
||||
|
||||
const viewOf = (bytes: Uint8Array): DataView =>
|
||||
new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
||||
@@ -0,0 +1,94 @@
|
||||
/** Encode a minimal NIBArchive object table for decoder and projection tests. */
|
||||
export const encodeNibArchiveFixture = (input: {
|
||||
readonly classes: readonly string[];
|
||||
readonly objects: readonly {
|
||||
readonly classIndex: number;
|
||||
readonly values: Readonly<
|
||||
Record<string, number | string | boolean | null | { ref: number }>
|
||||
>;
|
||||
}[];
|
||||
}): Buffer => {
|
||||
const keys = [
|
||||
...new Set(input.objects.flatMap(({ values }) => Object.keys(values))),
|
||||
];
|
||||
const keyIndex = new Map(keys.map((key, index) => [key, index]));
|
||||
const valueRecords = input.objects.flatMap(({ values }) =>
|
||||
Object.entries(values).map(([key, value]) =>
|
||||
Buffer.concat([varint(keyIndex.get(key) ?? 0), encodeValue(value)]),
|
||||
),
|
||||
);
|
||||
let valueStart = 0;
|
||||
const records = input.objects.map(({ classIndex, values }) => {
|
||||
const count = Object.keys(values).length;
|
||||
const result = Buffer.concat([
|
||||
varint(classIndex),
|
||||
varint(valueStart),
|
||||
varint(count),
|
||||
]);
|
||||
valueStart += count;
|
||||
return result;
|
||||
});
|
||||
const objects = Buffer.concat(records);
|
||||
const encodedKeys = Buffer.concat(
|
||||
keys.map((key) =>
|
||||
Buffer.concat([varint(Buffer.byteLength(key)), Buffer.from(key)]),
|
||||
),
|
||||
);
|
||||
const values = Buffer.concat(valueRecords);
|
||||
const classes = Buffer.concat(
|
||||
input.classes.map((name) => {
|
||||
const bytes = Buffer.from(name);
|
||||
return Buffer.concat([varint(bytes.length), varint(0), bytes]);
|
||||
}),
|
||||
);
|
||||
const objectsOffset = 50;
|
||||
const keysOffset = objectsOffset + objects.length;
|
||||
const valuesOffset = keysOffset + encodedKeys.length;
|
||||
const classesOffset = valuesOffset + values.length;
|
||||
const header = Buffer.alloc(50);
|
||||
header.write("NIBArchive", 0, "ascii");
|
||||
header.writeUInt32LE(1, 10);
|
||||
header.writeUInt32LE(10, 14);
|
||||
header.writeUInt32LE(input.objects.length, 18);
|
||||
header.writeUInt32LE(objectsOffset, 22);
|
||||
header.writeUInt32LE(keys.length, 26);
|
||||
header.writeUInt32LE(keysOffset, 30);
|
||||
header.writeUInt32LE(valueStart, 34);
|
||||
header.writeUInt32LE(valuesOffset, 38);
|
||||
header.writeUInt32LE(input.classes.length, 42);
|
||||
header.writeUInt32LE(classesOffset, 46);
|
||||
return Buffer.concat([header, objects, encodedKeys, values, classes]);
|
||||
};
|
||||
|
||||
const varint = (value: number): Buffer => {
|
||||
const bytes: number[] = [];
|
||||
let remaining = value;
|
||||
do {
|
||||
let byte = remaining & 0x7f;
|
||||
remaining >>>= 7;
|
||||
if (remaining === 0) byte |= 0x80;
|
||||
bytes.push(byte);
|
||||
} while (remaining > 0);
|
||||
return Buffer.from(bytes);
|
||||
};
|
||||
|
||||
const encodeValue = (
|
||||
value: number | string | boolean | null | { ref: number },
|
||||
): Buffer => {
|
||||
if (typeof value === "boolean") return Buffer.from([value ? 4 : 5]);
|
||||
if (value === null) return Buffer.from([9]);
|
||||
if (typeof value === "number") {
|
||||
const bytes = Buffer.alloc(5);
|
||||
bytes[0] = 2;
|
||||
bytes.writeInt32LE(value, 1);
|
||||
return bytes;
|
||||
}
|
||||
if (typeof value === "object") {
|
||||
const bytes = Buffer.alloc(5);
|
||||
bytes[0] = 10;
|
||||
bytes.writeUInt32LE(value.ref, 1);
|
||||
return bytes;
|
||||
}
|
||||
const data = Buffer.from(value);
|
||||
return Buffer.concat([Buffer.from([8]), varint(data.length), data]);
|
||||
};
|
||||
@@ -0,0 +1,48 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { decodeNibArchive } from "./NibArchive.js";
|
||||
import { encodeNibArchiveFixture as encodeArchive } from "./NibArchive.fixture.js";
|
||||
|
||||
describe("NIBArchive decoder", () => {
|
||||
it("decodes bounded object, key, class, and reference tables", () => {
|
||||
const archive = encodeArchive({
|
||||
classes: ["NSView\0", "NSString\0"],
|
||||
objects: [
|
||||
{ classIndex: 0, values: { child: { ref: 1 }, enabled: true } },
|
||||
{ classIndex: 1, values: { text: "Button" } },
|
||||
],
|
||||
});
|
||||
const decoded = decodeNibArchive(archive);
|
||||
|
||||
expect(decoded.objects).toEqual([
|
||||
{
|
||||
id: 0,
|
||||
class_name: "NSView",
|
||||
values: { child: { $nib_object_ref: 1 }, enabled: true },
|
||||
},
|
||||
{
|
||||
id: 1,
|
||||
class_name: "NSString",
|
||||
values: { text: { $nib_data_base64: "QnV0dG9u" } },
|
||||
},
|
||||
]);
|
||||
expect(decoded.coder_version).toBe(10);
|
||||
});
|
||||
|
||||
it("rejects malformed references and unsupported format versions", () => {
|
||||
const valid = encodeArchive({
|
||||
classes: ["NSObject"],
|
||||
objects: [{ classIndex: 0, values: {} }],
|
||||
});
|
||||
const invalidVersion = Buffer.from(valid);
|
||||
invalidVersion.writeUInt32LE(2, 10);
|
||||
expect(() => decodeNibArchive(invalidVersion)).toThrow(/Unsupported/u);
|
||||
const invalidReference = encodeArchive({
|
||||
classes: ["NSObject"],
|
||||
objects: [{ classIndex: 0, values: { child: { ref: 4 } } }],
|
||||
});
|
||||
expect(() => decodeNibArchive(invalidReference)).toThrow(
|
||||
/object reference/u,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,430 @@
|
||||
import type { JsonValue } from "../../domain/jsonValue.js";
|
||||
import { TextDecoder } from "node:util";
|
||||
|
||||
const MAGIC = Buffer.from("NIBArchive", "ascii");
|
||||
const MAX_RECORDS = 1_000_000;
|
||||
|
||||
interface NibObjectRecord {
|
||||
readonly class_index: number;
|
||||
readonly value_start: number;
|
||||
readonly value_count: number;
|
||||
}
|
||||
|
||||
interface NibValueRecord {
|
||||
readonly key_index: number;
|
||||
readonly value: JsonValue;
|
||||
}
|
||||
|
||||
/** Parsed NIBArchive payload with the original object indices preserved. */
|
||||
export interface NibArchiveDocument {
|
||||
readonly format_version: number;
|
||||
readonly coder_version: number;
|
||||
readonly object_count: number;
|
||||
readonly connection_object_count: number;
|
||||
readonly objects: readonly {
|
||||
readonly id: number;
|
||||
readonly class_name: string;
|
||||
readonly values: Readonly<Record<string, JsonValue>>;
|
||||
}[];
|
||||
readonly classes: readonly string[];
|
||||
readonly limitations: readonly string[];
|
||||
}
|
||||
|
||||
/** Decode Apple's length-prefixed NIBArchive representation without loading UI classes. */
|
||||
export const decodeNibArchive = (bytes: Buffer): NibArchiveDocument => {
|
||||
if (bytes.length < 50 || !bytes.subarray(0, MAGIC.length).equals(MAGIC))
|
||||
throw new TypeError("NIBArchive magic or header is invalid");
|
||||
|
||||
const formatVersion = readU32(bytes, 10);
|
||||
const coderVersion = readU32(bytes, 14);
|
||||
if (formatVersion !== 1)
|
||||
throw new TypeError(
|
||||
`Unsupported NIBArchive format version ${formatVersion}`,
|
||||
);
|
||||
|
||||
const objectCount = readCount(bytes, 18, "object");
|
||||
const objectsOffset = readOffset(bytes, 22, bytes.length, "object");
|
||||
const keyCount = readCount(bytes, 26, "key");
|
||||
const keysOffset = readOffset(bytes, 30, bytes.length, "key");
|
||||
const valueCount = readCount(bytes, 34, "value");
|
||||
const valuesOffset = readOffset(bytes, 38, bytes.length, "value");
|
||||
const classCount = readCount(bytes, 42, "class");
|
||||
const classesOffset = readOffset(bytes, 46, bytes.length, "class");
|
||||
|
||||
assertOrderedOffsets(bytes.length, [
|
||||
objectsOffset,
|
||||
keysOffset,
|
||||
valuesOffset,
|
||||
classesOffset,
|
||||
]);
|
||||
const objectRecords = parseObjects(
|
||||
bytes,
|
||||
objectsOffset,
|
||||
keysOffset,
|
||||
objectCount,
|
||||
valueCount,
|
||||
classCount,
|
||||
);
|
||||
const keys = parseStrings(bytes, keysOffset, valuesOffset, keyCount, "key");
|
||||
const classes = parseClasses(bytes, classesOffset, bytes.length, classCount);
|
||||
const neededValues = valueIndexes(objectRecords, valueCount);
|
||||
const values = parseValues(
|
||||
bytes,
|
||||
valuesOffset,
|
||||
classesOffset,
|
||||
valueCount,
|
||||
keyCount,
|
||||
neededValues,
|
||||
);
|
||||
for (const { value } of values.values()) {
|
||||
if (
|
||||
typeof value === "object" &&
|
||||
value !== null &&
|
||||
!Array.isArray(value) &&
|
||||
typeof value.$nib_object_ref === "number" &&
|
||||
value.$nib_object_ref >= objectCount
|
||||
)
|
||||
throw new TypeError(
|
||||
"NIBArchive object reference is outside the object table",
|
||||
);
|
||||
}
|
||||
const objects = objectRecords.flatMap((object, id) => {
|
||||
const className = classes[object.class_index];
|
||||
if (className === undefined) return [];
|
||||
const fields: Record<string, JsonValue> = {};
|
||||
for (
|
||||
let index = object.value_start;
|
||||
index < object.value_start + object.value_count;
|
||||
index += 1
|
||||
) {
|
||||
const value = values.get(index);
|
||||
if (value === undefined) continue;
|
||||
const key = keys[value.key_index];
|
||||
if (key !== undefined) fields[key] = value.value;
|
||||
}
|
||||
return [{ id, class_name: className, values: fields }];
|
||||
});
|
||||
let connectionObjectCount = 0;
|
||||
for (const object of objects)
|
||||
if (
|
||||
/(?:Outlet|Connection|Segue|ActionConnection)/iu.test(object.class_name)
|
||||
)
|
||||
connectionObjectCount += 1;
|
||||
|
||||
return {
|
||||
format_version: formatVersion,
|
||||
coder_version: coderVersion,
|
||||
object_count: objectCount,
|
||||
connection_object_count: connectionObjectCount,
|
||||
objects,
|
||||
classes,
|
||||
limitations: [
|
||||
"NIBArchive class extensions and unsupported value encodings are retained as unavailable fields.",
|
||||
"NIBArchive object relationships are decoded from serialized references; runtime object creation and execution are not performed.",
|
||||
],
|
||||
};
|
||||
};
|
||||
|
||||
const parseObjects = (
|
||||
bytes: Buffer,
|
||||
start: number,
|
||||
end: number,
|
||||
count: number,
|
||||
valueCount: number,
|
||||
classCount: number,
|
||||
): NibObjectRecord[] => {
|
||||
const cursor = { offset: start };
|
||||
const output: NibObjectRecord[] = [];
|
||||
for (let index = 0; index < count; index += 1) {
|
||||
const classIndex = readVarint(bytes, cursor, end);
|
||||
const valueStart = readVarint(bytes, cursor, end);
|
||||
const countForObject = readVarint(bytes, cursor, end);
|
||||
if (
|
||||
classIndex >= classCount ||
|
||||
valueStart > valueCount ||
|
||||
countForObject > valueCount - valueStart
|
||||
)
|
||||
throw new TypeError(
|
||||
`NIBArchive object ${index} references an invalid table range`,
|
||||
);
|
||||
output.push({
|
||||
class_index: classIndex,
|
||||
value_start: valueStart,
|
||||
value_count: countForObject,
|
||||
});
|
||||
}
|
||||
if (cursor.offset > end)
|
||||
throw new TypeError("NIBArchive object table overlaps the next table");
|
||||
return output;
|
||||
};
|
||||
|
||||
const parseStrings = (
|
||||
bytes: Buffer,
|
||||
start: number,
|
||||
end: number,
|
||||
count: number,
|
||||
label: string,
|
||||
): string[] => {
|
||||
const cursor = { offset: start };
|
||||
const output: string[] = [];
|
||||
for (let index = 0; index < count; index += 1) {
|
||||
const length = readVarint(bytes, cursor, end);
|
||||
const next = checkedEnd(cursor.offset, length, end, `${label} ${index}`);
|
||||
const value = decodeUtf8(bytes, cursor.offset, next, `${label} ${index}`);
|
||||
cursor.offset = next;
|
||||
output.push(value);
|
||||
}
|
||||
return output;
|
||||
};
|
||||
|
||||
const parseClasses = (
|
||||
bytes: Buffer,
|
||||
start: number,
|
||||
end: number,
|
||||
count: number,
|
||||
): string[] => {
|
||||
const cursor = { offset: start };
|
||||
const output: string[] = [];
|
||||
for (let index = 0; index < count; index += 1) {
|
||||
const length = readVarint(bytes, cursor, end);
|
||||
const extraCount = readVarint(bytes, cursor, end);
|
||||
if (extraCount > 16)
|
||||
throw new TypeError(
|
||||
`NIBArchive class ${index} has too many extension values`,
|
||||
);
|
||||
ensureRange(
|
||||
cursor.offset,
|
||||
extraCount * 4,
|
||||
end,
|
||||
`class ${index} extensions`,
|
||||
);
|
||||
cursor.offset += extraCount * 4;
|
||||
const next = checkedEnd(cursor.offset, length, end, `class ${index}`);
|
||||
const name = decodeUtf8(
|
||||
bytes,
|
||||
cursor.offset,
|
||||
next,
|
||||
`class ${index}`,
|
||||
).replace(/\0+$/u, "");
|
||||
cursor.offset = next;
|
||||
output.push(name);
|
||||
}
|
||||
return output;
|
||||
};
|
||||
|
||||
const parseValues = (
|
||||
bytes: Buffer,
|
||||
start: number,
|
||||
end: number,
|
||||
count: number,
|
||||
keyCount: number,
|
||||
needed: ReadonlySet<number>,
|
||||
): Map<number, NibValueRecord> => {
|
||||
const cursor = { offset: start };
|
||||
const output = new Map<number, NibValueRecord>();
|
||||
for (let index = 0; index < count; index += 1) {
|
||||
const keyIndex = readVarint(bytes, cursor, end);
|
||||
if (keyIndex >= keyCount)
|
||||
throw new TypeError(
|
||||
`NIBArchive value ${index} references an invalid key`,
|
||||
);
|
||||
ensureRange(cursor.offset, 1, end, `value ${index} type`);
|
||||
const type = bytes[cursor.offset++] ?? -1;
|
||||
const value = readValue(bytes, cursor, end, type, index);
|
||||
if (needed.has(index)) output.set(index, { key_index: keyIndex, value });
|
||||
}
|
||||
if (cursor.offset > end)
|
||||
throw new TypeError("NIBArchive value table overlaps the next table");
|
||||
return output;
|
||||
};
|
||||
|
||||
const readValue = (
|
||||
bytes: Buffer,
|
||||
cursor: { offset: number },
|
||||
end: number,
|
||||
type: number,
|
||||
index: number,
|
||||
): JsonValue => {
|
||||
switch (type) {
|
||||
case 0:
|
||||
ensureRange(cursor.offset, 1, end, `value ${index}`);
|
||||
return bytes.readInt8(cursor.offset++);
|
||||
case 1:
|
||||
ensureRange(cursor.offset, 2, end, `value ${index}`);
|
||||
{
|
||||
const value = bytes.readInt16LE(cursor.offset);
|
||||
cursor.offset += 2;
|
||||
return value;
|
||||
}
|
||||
case 2:
|
||||
ensureRange(cursor.offset, 4, end, `value ${index}`);
|
||||
{
|
||||
const value = bytes.readInt32LE(cursor.offset);
|
||||
cursor.offset += 4;
|
||||
return value;
|
||||
}
|
||||
case 3:
|
||||
ensureRange(cursor.offset, 8, end, `value ${index}`);
|
||||
{
|
||||
const value = bytes.readBigInt64LE(cursor.offset);
|
||||
cursor.offset += 8;
|
||||
return value <= BigInt(Number.MAX_SAFE_INTEGER) &&
|
||||
value >= BigInt(Number.MIN_SAFE_INTEGER)
|
||||
? Number(value)
|
||||
: value.toString();
|
||||
}
|
||||
case 4:
|
||||
return true;
|
||||
case 5:
|
||||
return false;
|
||||
case 6:
|
||||
ensureRange(cursor.offset, 4, end, `value ${index}`);
|
||||
{
|
||||
const value = bytes.readFloatLE(cursor.offset);
|
||||
cursor.offset += 4;
|
||||
return Number.isFinite(value) ? value : null;
|
||||
}
|
||||
case 7:
|
||||
ensureRange(cursor.offset, 8, end, `value ${index}`);
|
||||
{
|
||||
const value = bytes.readDoubleLE(cursor.offset);
|
||||
cursor.offset += 8;
|
||||
return Number.isFinite(value) ? value : null;
|
||||
}
|
||||
case 8: {
|
||||
const length = readVarint(bytes, cursor, end);
|
||||
const next = checkedEnd(
|
||||
cursor.offset,
|
||||
length,
|
||||
end,
|
||||
`value ${index} data`,
|
||||
);
|
||||
const encoded = bytes.subarray(cursor.offset, next).toString("base64");
|
||||
cursor.offset = next;
|
||||
return { $nib_data_base64: encoded };
|
||||
}
|
||||
case 9:
|
||||
return null;
|
||||
case 10:
|
||||
ensureRange(cursor.offset, 4, end, `value ${index} reference`);
|
||||
{
|
||||
const objectIndex = bytes.readUInt32LE(cursor.offset);
|
||||
cursor.offset += 4;
|
||||
return { $nib_object_ref: objectIndex };
|
||||
}
|
||||
default:
|
||||
throw new TypeError(
|
||||
`NIBArchive value ${index} has unsupported type ${type}`,
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const valueIndexes = (
|
||||
objects: readonly NibObjectRecord[],
|
||||
total: number,
|
||||
): ReadonlySet<number> => {
|
||||
const indexes = new Set<number>();
|
||||
for (const object of objects)
|
||||
for (
|
||||
let index = object.value_start;
|
||||
index < object.value_start + object.value_count;
|
||||
index += 1
|
||||
)
|
||||
indexes.add(index);
|
||||
if (indexes.size > total)
|
||||
throw new TypeError(
|
||||
"NIBArchive object value ranges exceed the value table",
|
||||
);
|
||||
return indexes;
|
||||
};
|
||||
|
||||
const readCount = (bytes: Buffer, offset: number, label: string): number => {
|
||||
const count = readU32(bytes, offset);
|
||||
if (count > MAX_RECORDS)
|
||||
throw new TypeError(`NIBArchive ${label} count exceeds the decoder bound`);
|
||||
return count;
|
||||
};
|
||||
|
||||
const readOffset = (
|
||||
bytes: Buffer,
|
||||
offset: number,
|
||||
fileLength: number,
|
||||
label: string,
|
||||
): number => {
|
||||
const value = readU32(bytes, offset);
|
||||
if (value < 50 || value > fileLength)
|
||||
throw new TypeError(`NIBArchive ${label} table offset is invalid`);
|
||||
return value;
|
||||
};
|
||||
|
||||
const readU32 = (bytes: Buffer, offset: number): number => {
|
||||
ensureRange(offset, 4, bytes.length, "header");
|
||||
return bytes.readUInt32LE(offset);
|
||||
};
|
||||
|
||||
const decodeUtf8 = (
|
||||
bytes: Buffer,
|
||||
start: number,
|
||||
end: number,
|
||||
label: string,
|
||||
): string => {
|
||||
try {
|
||||
return new TextDecoder("utf-8", { fatal: true }).decode(
|
||||
bytes.subarray(start, end),
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
throw new TypeError(`NIBArchive ${label} is not valid UTF-8`, {
|
||||
cause,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const readVarint = (
|
||||
bytes: Buffer,
|
||||
cursor: { offset: number },
|
||||
end: number,
|
||||
): number => {
|
||||
let value = 0;
|
||||
let shift = 0;
|
||||
for (let index = 0; index < 5; index += 1) {
|
||||
ensureRange(cursor.offset, 1, end, "variable integer");
|
||||
const byte = bytes[cursor.offset++] ?? 0;
|
||||
value += (byte & 0x7f) * 2 ** shift;
|
||||
if ((byte & 0x80) !== 0) {
|
||||
if (value > 0x7fff_ffff)
|
||||
throw new TypeError("NIBArchive variable integer is out of range");
|
||||
return value;
|
||||
}
|
||||
shift += 7;
|
||||
}
|
||||
throw new TypeError("NIBArchive variable integer is too long");
|
||||
};
|
||||
|
||||
const checkedEnd = (
|
||||
start: number,
|
||||
length: number,
|
||||
limit: number,
|
||||
label: string,
|
||||
): number => {
|
||||
if (!Number.isSafeInteger(length) || length < 0 || start + length > limit)
|
||||
throw new TypeError(`NIBArchive ${label} exceeds its table`);
|
||||
return start + length;
|
||||
};
|
||||
|
||||
const ensureRange = (
|
||||
start: number,
|
||||
length: number,
|
||||
limit: number,
|
||||
label: string,
|
||||
): void => {
|
||||
checkedEnd(start, length, limit, label);
|
||||
};
|
||||
|
||||
const assertOrderedOffsets = (length: number, offsets: readonly number[]) => {
|
||||
let previous = 50;
|
||||
for (const offset of offsets) {
|
||||
if (offset < previous || offset > length)
|
||||
throw new TypeError("NIBArchive table offsets are out of order");
|
||||
previous = offset;
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,189 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
mergeNibHierarchies,
|
||||
projectNibViewHierarchy,
|
||||
} from "./NibViewHierarchy.js";
|
||||
|
||||
const object = (id: number, parent?: number) => ({
|
||||
id,
|
||||
class_name: "NSView",
|
||||
values:
|
||||
parent === undefined ? {} : { NSSuperview: { $nib_object_ref: parent } },
|
||||
});
|
||||
|
||||
describe("serialized NIB view hierarchy bounds", () => {
|
||||
it("leaves archives without superview links to the legacy projection", () => {
|
||||
expect(projectNibViewHierarchy([object(0)], new Set([0]))).toEqual({
|
||||
hierarchy: null,
|
||||
omitted: 0,
|
||||
});
|
||||
});
|
||||
|
||||
it("uses the serialized parent direction and retains all sibling links", () => {
|
||||
expect(
|
||||
projectNibViewHierarchy(
|
||||
[object(0), object(1, 0), object(2, 0)],
|
||||
new Set([0, 1, 2]),
|
||||
),
|
||||
).toEqual({
|
||||
hierarchy: [
|
||||
{
|
||||
objectID: "0",
|
||||
children: [
|
||||
{ objectID: "1", children: [] },
|
||||
{ objectID: "2", children: [] },
|
||||
],
|
||||
},
|
||||
],
|
||||
omitted: 0,
|
||||
});
|
||||
});
|
||||
|
||||
it("reports missing parents without inventing parentage", () => {
|
||||
expect(projectNibViewHierarchy([object(0, 99)], new Set([0]))).toEqual({
|
||||
hierarchy: [],
|
||||
omitted: 1,
|
||||
});
|
||||
});
|
||||
|
||||
it("reports a missing encoded window content view as incomplete", () => {
|
||||
expect(
|
||||
projectNibViewHierarchy(
|
||||
[
|
||||
{
|
||||
id: 0,
|
||||
class_name: "NSWindowTemplate",
|
||||
values: { NSWindowView: { $nib_object_ref: 99 } },
|
||||
},
|
||||
],
|
||||
new Set([0]),
|
||||
),
|
||||
).toEqual({ hierarchy: [{ objectID: "0", children: [] }], omitted: 1 });
|
||||
});
|
||||
|
||||
it("marks unsupported serialized parent values as incomplete", () => {
|
||||
expect(
|
||||
projectNibViewHierarchy(
|
||||
[{ id: 0, class_name: "NSView", values: { NSSuperview: "unknown" } }],
|
||||
new Set([0]),
|
||||
),
|
||||
).toEqual({ hierarchy: null, omitted: 1 });
|
||||
});
|
||||
|
||||
it("reports cyclic and self-referential parentage as incomplete", () => {
|
||||
expect(
|
||||
projectNibViewHierarchy(
|
||||
[object(0, 1), object(1, 0), object(2, 2)],
|
||||
new Set([0, 1, 2]),
|
||||
),
|
||||
).toEqual({
|
||||
hierarchy: [],
|
||||
omitted: 3,
|
||||
});
|
||||
});
|
||||
|
||||
it("does not project children whose parent was not retained", () => {
|
||||
expect(
|
||||
projectNibViewHierarchy([object(0), object(1, 0)], new Set([1])),
|
||||
).toEqual({
|
||||
hierarchy: [],
|
||||
omitted: 1,
|
||||
});
|
||||
});
|
||||
|
||||
it("reports nodes beyond the depth bound instead of claiming complete coverage", () => {
|
||||
const objects = Array.from({ length: 132 }, (_, id) =>
|
||||
object(id, id === 0 ? undefined : id - 1),
|
||||
);
|
||||
expect(
|
||||
projectNibViewHierarchy(objects, new Set(objects.map(({ id }) => id)))
|
||||
.omitted,
|
||||
).toBe(3);
|
||||
});
|
||||
|
||||
it("reports nodes beyond the record bound", () => {
|
||||
const objects = Array.from({ length: 20_002 }, (_, id) =>
|
||||
object(id, id === 0 ? undefined : 0),
|
||||
);
|
||||
expect(
|
||||
projectNibViewHierarchy(objects, new Set(objects.map(({ id }) => id)))
|
||||
.omitted,
|
||||
).toBe(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe("legacy NIB hierarchy preservation", () => {
|
||||
it("keeps encoded window parents while merging shared views only once", () => {
|
||||
const legacy = [
|
||||
{
|
||||
objectID: "window",
|
||||
children: [
|
||||
{ objectID: "view", children: [{ objectID: "first", children: [] }] },
|
||||
],
|
||||
},
|
||||
];
|
||||
const recovered = [
|
||||
{
|
||||
objectID: "view",
|
||||
children: [
|
||||
{ objectID: "first", children: [] },
|
||||
{ objectID: "second", children: [] },
|
||||
],
|
||||
},
|
||||
];
|
||||
expect(mergeNibHierarchies(legacy, recovered).hierarchy).toEqual([
|
||||
{
|
||||
objectID: "window",
|
||||
children: [
|
||||
{
|
||||
objectID: "view",
|
||||
children: [
|
||||
{ objectID: "first", children: [] },
|
||||
{ objectID: "second", children: [] },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
]);
|
||||
});
|
||||
it("moves an existing root under its encoded parent without duplicate visits", () => {
|
||||
expect(
|
||||
mergeNibHierarchies(
|
||||
[{ objectID: "child", children: [] }],
|
||||
[
|
||||
{
|
||||
objectID: "parent",
|
||||
children: [{ objectID: "child", children: [] }],
|
||||
},
|
||||
],
|
||||
),
|
||||
).toEqual({
|
||||
hierarchy: [
|
||||
{ objectID: "parent", children: [{ objectID: "child", children: [] }] },
|
||||
],
|
||||
omitted: 0,
|
||||
});
|
||||
});
|
||||
it("reports conflicting encoded parents rather than dropping a link silently", () => {
|
||||
const legacy = [
|
||||
{ objectID: "first", children: [{ objectID: "child", children: [] }] },
|
||||
];
|
||||
const recovered = [
|
||||
{ objectID: "second", children: [{ objectID: "child", children: [] }] },
|
||||
];
|
||||
expect(mergeNibHierarchies(legacy, recovered).omitted).toBe(1);
|
||||
});
|
||||
it("does not introduce a cycle when moving an existing root", () => {
|
||||
const legacy = [
|
||||
{ objectID: "child", children: [{ objectID: "parent", children: [] }] },
|
||||
];
|
||||
const recovered = [
|
||||
{ objectID: "parent", children: [{ objectID: "child", children: [] }] },
|
||||
];
|
||||
expect(mergeNibHierarchies(legacy, recovered)).toEqual({
|
||||
hierarchy: legacy,
|
||||
omitted: 1,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,176 @@
|
||||
import type { NibArchiveDocument } from "./NibArchive.js";
|
||||
import type { JsonValue } from "../../domain/jsonValue.js";
|
||||
|
||||
export type NibHierarchyNode = {
|
||||
objectID: string;
|
||||
children: NibHierarchyNode[];
|
||||
};
|
||||
|
||||
/** Project encoded view parents; archive owners are not inferred view parents. */
|
||||
export const projectNibViewHierarchy = (
|
||||
objects: NibArchiveDocument["objects"],
|
||||
retainedIds: ReadonlySet<number>,
|
||||
) => {
|
||||
const { parents, involved, invalid } = collectNibParents(
|
||||
objects,
|
||||
retainedIds,
|
||||
);
|
||||
if (parents.size === 0) return { hierarchy: null, omitted: invalid };
|
||||
const children = new Map<number, number[]>();
|
||||
for (const [child, parent] of parents) {
|
||||
if (!retainedIds.has(parent) || !retainedIds.has(child)) continue;
|
||||
const siblings = children.get(parent) ?? [];
|
||||
siblings.push(child);
|
||||
children.set(parent, siblings);
|
||||
}
|
||||
const roots: NibHierarchyNode[] = [];
|
||||
const pending: { id: number; depth: number; output: NibHierarchyNode[] }[] =
|
||||
[];
|
||||
for (const id of involved)
|
||||
if (!parents.has(id)) pending.push({ id, depth: 0, output: roots });
|
||||
const visited = new Set<number>();
|
||||
while (pending.length > 0) {
|
||||
const item = pending.pop();
|
||||
if (item === undefined) break;
|
||||
if (visited.has(item.id) || item.depth > 128 || visited.size >= 20_000)
|
||||
continue;
|
||||
visited.add(item.id);
|
||||
const node: NibHierarchyNode = { objectID: String(item.id), children: [] };
|
||||
item.output.push(node);
|
||||
for (const child of [...(children.get(item.id) ?? [])].reverse())
|
||||
pending.push({ id: child, depth: item.depth + 1, output: node.children });
|
||||
}
|
||||
return {
|
||||
hierarchy: roots,
|
||||
omitted: involved.size - visited.size + invalid,
|
||||
};
|
||||
};
|
||||
|
||||
/** Add encoded parent links once; conflicting legacy parents remain unknown. */
|
||||
export const mergeNibHierarchies = (
|
||||
legacy: NibHierarchyNode[],
|
||||
recovered: NibHierarchyNode[],
|
||||
) => {
|
||||
const existing = new Map<string, NibHierarchyNode>();
|
||||
const owners = new Map<string, NibHierarchyNode[]>();
|
||||
const parents = new Map<string, string>();
|
||||
const pending = legacy.map((node) => ({
|
||||
node,
|
||||
output: legacy,
|
||||
parent: null as string | null,
|
||||
}));
|
||||
while (pending.length > 0) {
|
||||
const entry = pending.pop();
|
||||
if (entry === undefined || existing.has(entry.node.objectID)) continue;
|
||||
existing.set(entry.node.objectID, entry.node);
|
||||
owners.set(entry.node.objectID, entry.output);
|
||||
if (entry.parent !== null) parents.set(entry.node.objectID, entry.parent);
|
||||
pending.push(
|
||||
...entry.node.children.map((node) => ({
|
||||
node,
|
||||
output: entry.node.children,
|
||||
parent: entry.node.objectID,
|
||||
})),
|
||||
);
|
||||
}
|
||||
let omitted = 0;
|
||||
const additions = recovered.map((node) => ({
|
||||
node,
|
||||
output: legacy,
|
||||
parent: null as string | null,
|
||||
}));
|
||||
while (additions.length > 0) {
|
||||
const entry = additions.pop();
|
||||
if (entry === undefined) break;
|
||||
let target = existing.get(entry.node.objectID);
|
||||
if (target === undefined) {
|
||||
target = { objectID: entry.node.objectID, children: [] };
|
||||
existing.set(target.objectID, target);
|
||||
entry.output.push(target);
|
||||
owners.set(target.objectID, entry.output);
|
||||
if (entry.parent !== null) parents.set(target.objectID, entry.parent);
|
||||
} else if (
|
||||
entry.parent !== null &&
|
||||
owners.get(target.objectID) !== entry.output
|
||||
) {
|
||||
const owner = owners.get(target.objectID);
|
||||
if (
|
||||
owner !== legacy ||
|
||||
wouldCycle(target.objectID, entry.parent, parents)
|
||||
) {
|
||||
omitted += 1;
|
||||
} else {
|
||||
owner.splice(owner.indexOf(target), 1);
|
||||
entry.output.push(target);
|
||||
owners.set(target.objectID, entry.output);
|
||||
parents.set(target.objectID, entry.parent);
|
||||
}
|
||||
}
|
||||
for (const node of [...entry.node.children].reverse())
|
||||
additions.push({
|
||||
node,
|
||||
output: target.children,
|
||||
parent: target.objectID,
|
||||
});
|
||||
}
|
||||
return { hierarchy: legacy, omitted };
|
||||
};
|
||||
|
||||
const wouldCycle = (
|
||||
child: string,
|
||||
parent: string,
|
||||
parents: ReadonlyMap<string, string>,
|
||||
): boolean => {
|
||||
const seen = new Set<string>();
|
||||
let current: string | undefined = parent;
|
||||
while (current !== undefined && !seen.has(current)) {
|
||||
if (current === child) return true;
|
||||
seen.add(current);
|
||||
current = parents.get(current);
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
const reference = (value: JsonValue | undefined): number | null => {
|
||||
if (typeof value !== "object" || value === null || Array.isArray(value))
|
||||
return null;
|
||||
return typeof value.$nib_object_ref === "number"
|
||||
? value.$nib_object_ref
|
||||
: null;
|
||||
};
|
||||
|
||||
const collectNibParents = (
|
||||
objects: NibArchiveDocument["objects"],
|
||||
retainedIds: ReadonlySet<number>,
|
||||
) => {
|
||||
const parents = new Map<number, number>();
|
||||
const involved = new Set<number>();
|
||||
let invalid = 0;
|
||||
for (const object of objects) {
|
||||
if (!retainedIds.has(object.id)) continue;
|
||||
const child = reference(object.values.NSWindowView);
|
||||
if (
|
||||
object.class_name.replace(/\0+$/u, "") === "NSWindowTemplate" &&
|
||||
invalidReference(object.values.NSWindowView)
|
||||
)
|
||||
invalid += 1;
|
||||
if (
|
||||
object.class_name.replace(/\0+$/u, "") === "NSWindowTemplate" &&
|
||||
child !== null
|
||||
) {
|
||||
parents.set(child, object.id);
|
||||
involved.add(object.id);
|
||||
involved.add(child);
|
||||
}
|
||||
const parent = reference(object.values.NSSuperview);
|
||||
if (invalidReference(object.values.NSSuperview)) invalid += 1;
|
||||
if (parent === null) continue;
|
||||
parents.set(object.id, parent);
|
||||
involved.add(object.id);
|
||||
if (retainedIds.has(parent)) involved.add(parent);
|
||||
}
|
||||
return { parents, involved, invalid };
|
||||
};
|
||||
|
||||
const invalidReference = (value: JsonValue | undefined): boolean =>
|
||||
value !== undefined && value !== null && reference(value) === null;
|
||||
Reference in New Issue
Block a user