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

This commit is contained in:
morluto
2026-10-09 00:49:30 +08:00
parent 16f4609d68
commit 15f92f2988
15 changed files with 1019 additions and 95 deletions
+15 -3
View File
@@ -6,6 +6,7 @@ import { describe, expect } from "vitest";
import {
FILE_TYPE,
LC,
buildVersionCommand,
dylibCommand,
machoImage,
rpathCommand,
@@ -36,6 +37,7 @@ const fixtureApp = async (): Promise<string> => {
"<plist><dict><key>CFBundleExecutable</key><string>App</string></dict></plist>",
"Contents/MacOS/App": machoImage({
commands: [
buildVersionCommand(1),
rpathCommand("@executable_path/../Frameworks"),
dylibCommand(LC.LOAD_DYLIB, "@rpath/libcore.dylib"),
dylibCommand(LC.LOAD_WEAK_DYLIB, "@rpath/libgone.dylib"),
@@ -43,10 +45,16 @@ const fixtureApp = async (): Promise<string> => {
}),
"Contents/Frameworks/libcore.dylib": machoImage({
fileType: FILE_TYPE.dylib,
commands: [dylibCommand(LC.ID_DYLIB, "@rpath/libcore.dylib")],
commands: [
buildVersionCommand(1),
dylibCommand(LC.ID_DYLIB, "@rpath/libcore.dylib"),
],
}),
"Contents/Helpers/tool": machoImage({
commands: [dylibCommand(LC.LOAD_DYLIB, "@loader_path/libnone.dylib")],
commands: [
buildVersionCommand(1),
dylibCommand(LC.LOAD_DYLIB, "@loader_path/libnone.dylib"),
],
}),
});
return app;
@@ -153,11 +161,15 @@ describe("trace-dylib-resolution CLI", () => {
await writeFiles(directory, {
tool: machoImage({
commands: [
buildVersionCommand(1),
dylibCommand(LC.LOAD_DYLIB, "@loader_path/lib/libhelper.dylib"),
dylibCommand(LC.LOAD_DYLIB, "@loader_path/../escape.dylib"),
],
}),
"lib/libhelper.dylib": machoImage({ fileType: FILE_TYPE.dylib }),
"lib/libhelper.dylib": machoImage({
fileType: FILE_TYPE.dylib,
commands: [buildVersionCommand(1)],
}),
"unrelated.txt": "not traversed",
});
const result = await cli.run({
+14 -3
View File
@@ -9,6 +9,7 @@ import { ArtifactProvider } from "../../../src/artifacts/ArtifactProvider.js";
import {
FILE_TYPE,
LC,
buildVersionCommand,
dylibCommand,
machoImage,
rpathCommand,
@@ -55,6 +56,7 @@ it("traces dylib resolution for an opened app bundle and rejects a changed targe
executable,
machoImage({
commands: [
buildVersionCommand(1),
rpathCommand("@executable_path/../Frameworks"),
dylibCommand(LC.LOAD_DYLIB, "@rpath/libcore.dylib"),
],
@@ -62,7 +64,10 @@ it("traces dylib resolution for an opened app bundle and rejects a changed targe
);
await writeFile(
join(app, "Contents/Frameworks/libcore.dylib"),
machoImage({ fileType: FILE_TYPE.dylib }),
machoImage({
fileType: FILE_TYPE.dylib,
commands: [buildVersionCommand(1)],
}),
);
await withClient(async (client) => {
const opened = await client.callTool({
@@ -129,12 +134,18 @@ it("traces a standalone Mach-O file whose name ends in .app", async () => {
await writeFile(
join(directory, "Tool.app"),
machoImage({
commands: [dylibCommand(LC.LOAD_DYLIB, "@loader_path/libcore.dylib")],
commands: [
buildVersionCommand(1),
dylibCommand(LC.LOAD_DYLIB, "@loader_path/libcore.dylib"),
],
}),
);
await writeFile(
join(directory, "libcore.dylib"),
machoImage({ fileType: FILE_TYPE.dylib }),
machoImage({
fileType: FILE_TYPE.dylib,
commands: [buildVersionCommand(1)],
}),
);
await withClient(async (client) => {
const opened = await client.callTool({
@@ -6,6 +6,11 @@ import { describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
import { MachOSliceArtifactReader } from "../../../../src/artifacts/MachOSliceArtifactReader.js";
import {
CPU,
fatImage,
machoImage,
} from "../../../../src/artifacts/apple/MachoImage.fixture.js";
import { ok } from "../../../../src/domain/result.js";
import type { NativeCommandRunner } from "../../../../src/native/CommandRunner.js";
@@ -46,7 +51,13 @@ describe("artifact Mach-O slices", () => {
it("uses lipo metadata to read universal slice ranges", async () => {
const root = await createTestTempDirectory("rea-slices-");
const binary = join(root, "fat");
await writeFile(binary, Buffer.from("0123456789abcdef"));
const x86 = machoImage({ cpu: CPU.x86_64 });
const arm = machoImage({ cpu: CPU.arm64 });
const image = fatImage([
{ cpu: CPU.x86_64, bytes: x86 },
{ cpu: CPU.arm64, bytes: arm },
]);
await writeFile(binary, image);
const runner: NativeCommandRunner = {
run: () =>
Promise.resolve(
@@ -57,8 +68,7 @@ describe("artifact Mach-O slices", () => {
toolVersion: null,
versionReason: "fixture",
arguments: ["-detailed_info", binary],
stdout:
"architecture x86_64\n cputype 16777223\n cpusubtype 3\n offset 0\n size 8\n align 2^2\narchitecture arm64\n cputype 16777228\n cpusubtype 0\n offset 8\n size 8\n align 2^2\n",
stdout: `architecture x86_64\n cputype 16777223\n cpusubtype 3\n offset 4096\n size ${x86.length}\n align 2^12\narchitecture arm64\n cputype 16777228\n cpusubtype 0\n offset 8192\n size ${arm.length}\n align 2^12\n`,
stderr: "",
stdoutBytes: 1,
stderrBytes: 0,
@@ -76,17 +86,17 @@ describe("artifact Mach-O slices", () => {
if (secondEntry === undefined) return;
expect(secondEntry).toMatchObject({
path: "slices/arm64",
byteOffset: 8,
declaredSize: 8,
byteOffset: 8192,
declaredSize: arm.length,
});
for (const adapterKey of ["0x8:8", "1e3:8", " 8 :8"])
for (const adapterKey of ["0x2000:8", "1e3:8", " 8192 :8"])
await expect(
reader.open({ ...secondEntry, adapterKey }),
).rejects.toMatchObject({ reason: "integrity" });
const chunks: Buffer[] = [];
const stream = await reader.open(secondEntry);
for await (const chunk of stream) chunks.push(Buffer.from(chunk));
expect(Buffer.concat(chunks).toString()).toBe("89abcdef");
expect(Buffer.concat(chunks)).toEqual(Buffer.from(arm));
expect(reader.provenance()).toEqual([
expect.objectContaining({ tool: "lipo", effects: ["read"] }),
]);
@@ -95,4 +105,84 @@ describe("artifact Mach-O slices", () => {
Reflect.set(provenance[0], "tool", "forged");
expect(reader.provenance()[0]?.tool).toBe("lipo");
});
it.each([
["CPU type", "cputype 16777223"],
["CPU subtype", "cpusubtype 2"],
["alignment", "align 2^11 (2048)"],
["offset", "offset 4097"],
])(
"rejects lipo %s that disagrees with physical Mach-O facts",
async (_label, field) => {
const root = await createTestTempDirectory("rea-slices-mismatch-");
const binary = join(root, "fat");
const thin = machoImage({ cpu: CPU.arm64 });
await writeFile(binary, fatImage([{ cpu: CPU.arm64, bytes: thin }]));
const details = [
"architecture arm64",
" cputype 16777228",
" cpusubtype 0",
" offset 4096",
` size ${thin.length}`,
" align 2^12 (4096)",
];
const index = field.startsWith("cputype")
? 1
: field.startsWith("cpusubtype")
? 2
: field.startsWith("align")
? 5
: 3;
details[index] = ` ${field}`;
const reader = new MachOSliceArtifactReader(
binary,
lipoRunner(`${details.join("\n")}\n`),
);
await expect(async () => {
for await (const _entry of reader.entries()) {
// The structural comparison runs before the reader yields a slice.
}
}).rejects.toMatchObject({ reason: "integrity" });
},
);
it("does not trust lipo after a malformed structural Mach-O parse", async () => {
const root = await createTestTempDirectory("rea-slices-malformed-");
const binary = join(root, "fat");
const thin = machoImage({ cpu: CPU.arm64 });
new DataView(thin.buffer).setUint32(16, 1, true);
const image = fatImage([{ cpu: CPU.arm64, bytes: thin }]);
await writeFile(binary, image);
const reader = new MachOSliceArtifactReader(
binary,
lipoRunner(
`architecture arm64\n cputype 16777228\n cpusubtype 0\n offset 4096\n size ${thin.length}\n align 2^12 (4096)\n`,
),
);
await expect(async () => {
for await (const _entry of reader.entries()) {
// Malformed structural facts must fail before any slice is yielded.
}
}).rejects.toThrow(/structural slice index is malformed/u);
});
});
const lipoRunner = (stdout: string): NativeCommandRunner => ({
run: () =>
Promise.resolve(
ok({
tool: "lipo",
executable: "/usr/bin/lipo",
executableSha256: "1".repeat(64),
toolVersion: null,
versionReason: "fixture",
arguments: ["-detailed_info", "fixture"],
stdout,
stderr: "",
stdoutBytes: Buffer.byteLength(stdout),
stderrBytes: 0,
exitCode: 0,
signal: null,
}),
),
});