feat(artifacts): trace Mach-O dylib resolution in bundles
Add trace_dylib_resolution (CLI trace-dylib-resolution) to the artifact family. For the active Mach-O, or every executable in the active .app (the main app, XPC services, extensions, login items, helpers), it reports which file each dylib load reaches and how. A pure TypeScript reader decodes FAT and Mach-O load commands: LC_LOAD/WEAK/REEXPORT/LAZY/UPWARD_DYLIB, including the newer dylib_use_command encoding with weak, re-export, upward and delayed-init flags, plus LC_ID_DYLIB, LC_RPATH, LC_DYLD_ENVIRONMENT and code-signature presence. Malformed tables are reported with the failing command instead of being guessed. Resolution follows dyld: - @executable_path comes from each process root; - @loader_path comes from the loading image, or from the owner of the LC_RPATH entry being expanded; - @rpath searches the loader's rpaths first, then up the load chain; - dependencies load dependents-first in load-command order, once per process, and a matching install name reuses an already loaded image; - symlinks are followed inside the analyzed root, and escapes stop. Every candidate path is reported with its outcome. Each edge resolves to resolved, conditional (an outside-root candidate such as /usr/lib/swift precedes), unresolved, or undetermined. Absolute and shared-cache system paths are never checked against the host. Derived findings cover unresolved required or weak loads, absent earlier @rpath candidates (with library validation left unknown), and LC_DYLD_ENVIRONMENT. verify:macos-bundle now also: - checks every traced image against otool -l; - asserts each resolution status on a clang-built fixture that adds a missing Overrides rpath, an absolute rpath, and a delay-init library; - compares the predicted load order of two process roots with what dyld loads under DYLD_PRINT_LIBRARIES. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
55249704c5
commit
11b7f918c2
@@ -12,6 +12,7 @@ export class ArtifactOperationError extends AnalysisError {
|
||||
| "decode_interface_builder"
|
||||
| "inspect_asset_catalog"
|
||||
| "inspect_keyed_archive"
|
||||
| "trace_dylib_resolution"
|
||||
| "export_web_scripts"
|
||||
| "trace_web_module_imports"
|
||||
| "trace_web_source_location"
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
import type { DylibTreeEntry, DylibTreeView } from "./dylibResolution.js";
|
||||
|
||||
const MAX_SYMLINK_HOPS = 32;
|
||||
|
||||
export type PathLookup =
|
||||
| { readonly kind: "file"; readonly path: string }
|
||||
| { readonly kind: "absent" | "escapes" | "not-file" };
|
||||
|
||||
/**
|
||||
* Resolve a root-relative path one segment at a time, as `open` would:
|
||||
* symlinks are followed inside the root, `..` applies to the real parent,
|
||||
* and any escape above the root or through an absolute link stops.
|
||||
*/
|
||||
export const resolveTreePath = async (
|
||||
view: DylibTreeView,
|
||||
input: string,
|
||||
): Promise<PathLookup> => {
|
||||
const pending = segmentsOf(input);
|
||||
const resolved: string[] = [];
|
||||
let last: DylibTreeEntry | undefined;
|
||||
let hops = 0;
|
||||
while (pending.length > 0) {
|
||||
const segment = pending.shift() ?? "";
|
||||
if (segment === "..") {
|
||||
if (resolved.length === 0) return { kind: "escapes" };
|
||||
resolved.pop();
|
||||
last = { kind: "directory" };
|
||||
continue;
|
||||
}
|
||||
const path = [...resolved, segment].join("/");
|
||||
const entry = await view.entry(path);
|
||||
if (entry === undefined) return { kind: "absent" };
|
||||
if (entry.kind === "symlink") {
|
||||
hops += 1;
|
||||
if (hops > MAX_SYMLINK_HOPS) return { kind: "absent" };
|
||||
if (entry.target.startsWith("/")) return { kind: "escapes" };
|
||||
pending.unshift(...segmentsOf(entry.target));
|
||||
continue;
|
||||
}
|
||||
if (entry.kind === "file" && pending.length > 0) return { kind: "absent" };
|
||||
resolved.push(segment);
|
||||
last = entry;
|
||||
}
|
||||
return last?.kind === "file"
|
||||
? { kind: "file", path: resolved.join("/") }
|
||||
: { kind: "not-file" };
|
||||
};
|
||||
|
||||
const segmentsOf = (path: string): string[] =>
|
||||
path.split("/").filter((segment) => segment !== "" && segment !== ".");
|
||||
|
||||
export const directoryOf = (path: string): string => {
|
||||
const index = path.lastIndexOf("/");
|
||||
return index < 0 ? "" : path.slice(0, index);
|
||||
};
|
||||
|
||||
export const joinPath = (directory: string, rest: string): string =>
|
||||
directory === "" ? rest : rest === "" ? directory : `${directory}/${rest}`;
|
||||
|
||||
export type Expansion =
|
||||
| { readonly scope: "target"; readonly path: string }
|
||||
| { readonly scope: "outside"; readonly path: string }
|
||||
| { readonly scope: "undetermined"; readonly path: string };
|
||||
|
||||
/** Expand one dyld path prefix relative to its owning image. */
|
||||
export const expandPrefix = (
|
||||
raw: string,
|
||||
context: {
|
||||
readonly ownerDirectory: string;
|
||||
readonly executable: string | null;
|
||||
},
|
||||
): Expansion => {
|
||||
const variable = /^@(executable_path|loader_path)(?:\/(.*))?$/u.exec(raw);
|
||||
if (variable !== null) {
|
||||
const rest = variable[2] ?? "";
|
||||
if (variable[1] === "loader_path")
|
||||
return { scope: "target", path: joinPath(context.ownerDirectory, rest) };
|
||||
return context.executable === null
|
||||
? { scope: "undetermined", path: raw }
|
||||
: {
|
||||
scope: "target",
|
||||
path: joinPath(directoryOf(context.executable), rest),
|
||||
};
|
||||
}
|
||||
if (raw.startsWith("/")) return { scope: "outside", path: raw };
|
||||
return { scope: "undetermined", path: raw };
|
||||
};
|
||||
@@ -0,0 +1,440 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
traceDylibLoading,
|
||||
type DylibTreeEntry,
|
||||
type DylibTreeView,
|
||||
type MachoDependency,
|
||||
type MachoImageFacts,
|
||||
type MachoSlice,
|
||||
} from "./dylibResolution.js";
|
||||
|
||||
const slice = (overrides: Partial<MachoSlice> = {}): MachoSlice => ({
|
||||
architecture: "arm64",
|
||||
file_type: "dylib",
|
||||
install_name: null,
|
||||
dependencies: [],
|
||||
rpaths: [],
|
||||
dyld_environment: [],
|
||||
code_signature_present: true,
|
||||
...overrides,
|
||||
});
|
||||
|
||||
const dependency = (
|
||||
installName: string,
|
||||
overrides: Partial<MachoDependency> = {},
|
||||
): MachoDependency => ({
|
||||
command: "LC_LOAD_DYLIB",
|
||||
encoding: "dylib_command",
|
||||
install_name: installName,
|
||||
weak: false,
|
||||
upward: false,
|
||||
reexport: false,
|
||||
delayed_init: false,
|
||||
current_version: "1.0.0",
|
||||
compatibility_version: "1.0.0",
|
||||
...overrides,
|
||||
});
|
||||
|
||||
const parsed = (...slices: MachoSlice[]): MachoImageFacts => ({
|
||||
status: "parsed",
|
||||
slices,
|
||||
});
|
||||
|
||||
const executable = (overrides: Partial<MachoSlice> = {}): MachoImageFacts =>
|
||||
parsed(slice({ file_type: "execute", ...overrides }));
|
||||
|
||||
/** In-memory tree: files are images (or "data"), symlinks map to targets. */
|
||||
const memoryView = (
|
||||
files: Readonly<Record<string, MachoImageFacts | "data">>,
|
||||
symlinks: Readonly<Record<string, string>> = {},
|
||||
): DylibTreeView => {
|
||||
const entries = new Map<string, DylibTreeEntry>();
|
||||
const addParents = (path: string): void => {
|
||||
const segments = path.split("/");
|
||||
for (let length = 1; length < segments.length; length++)
|
||||
entries.set(segments.slice(0, length).join("/"), { kind: "directory" });
|
||||
};
|
||||
for (const path of Object.keys(files)) {
|
||||
addParents(path);
|
||||
entries.set(path, { kind: "file" });
|
||||
}
|
||||
for (const [path, target] of Object.entries(symlinks)) {
|
||||
addParents(path);
|
||||
entries.set(path, { kind: "symlink", target });
|
||||
}
|
||||
return {
|
||||
entry: (path) => Promise.resolve(entries.get(path)),
|
||||
image: (path) => {
|
||||
const facts = files[path];
|
||||
return Promise.resolve(
|
||||
facts === undefined || facts === "data"
|
||||
? { status: "not-mach-o" as const }
|
||||
: facts,
|
||||
);
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
const MAIN = "Contents/MacOS/App";
|
||||
|
||||
const edgeFor = (
|
||||
trace: Awaited<ReturnType<typeof traceDylibLoading>>,
|
||||
loader: string,
|
||||
installName: string,
|
||||
) => {
|
||||
const edge = trace.edges.find(
|
||||
(candidate) =>
|
||||
candidate.loader === loader && candidate.install_name === installName,
|
||||
);
|
||||
if (edge === undefined)
|
||||
throw new Error(`missing ${loader} -> ${installName}`);
|
||||
return edge;
|
||||
};
|
||||
|
||||
describe("dyld path expansion", () => {
|
||||
it("searches the loading image's rpaths before its loaders'", async () => {
|
||||
const core = "Contents/Frameworks/Core.framework/Versions/A/Core";
|
||||
const trace = await traceDylibLoading(
|
||||
memoryView({
|
||||
[MAIN]: executable({
|
||||
rpaths: ["@executable_path/../Frameworks"],
|
||||
dependencies: [dependency("@rpath/Core.framework/Versions/A/Core")],
|
||||
}),
|
||||
[core]: parsed(
|
||||
slice({
|
||||
rpaths: ["@loader_path/Libraries"],
|
||||
dependencies: [dependency("@rpath/libchain.dylib")],
|
||||
}),
|
||||
),
|
||||
"Contents/Frameworks/libchain.dylib": parsed(slice()),
|
||||
"Contents/Frameworks/Core.framework/Versions/A/Libraries/libchain.dylib":
|
||||
parsed(slice()),
|
||||
}),
|
||||
{ roots: [MAIN] },
|
||||
);
|
||||
const chain = edgeFor(trace, core, "@rpath/libchain.dylib");
|
||||
expect(chain.via).toEqual([MAIN, core]);
|
||||
expect(chain.candidates).toEqual([
|
||||
expect.objectContaining({
|
||||
source: "rpath",
|
||||
rpath: "@loader_path/Libraries",
|
||||
rpath_owner: core,
|
||||
outcome: "resolved",
|
||||
}),
|
||||
]);
|
||||
expect(chain.resolution).toEqual({
|
||||
status: "resolved",
|
||||
image:
|
||||
"Contents/Frameworks/Core.framework/Versions/A/Libraries/libchain.dylib",
|
||||
});
|
||||
});
|
||||
|
||||
it("expands @loader_path in an rpath relative to the image that owns it", async () => {
|
||||
const plugin = "Contents/PlugIns/Tool.bundle/Contents/MacOS/Tool";
|
||||
const trace = await traceDylibLoading(
|
||||
memoryView({
|
||||
[MAIN]: executable({
|
||||
rpaths: ["@loader_path/../Shared"],
|
||||
dependencies: [
|
||||
dependency(
|
||||
`@executable_path/../PlugIns/Tool.bundle/Contents/MacOS/Tool`,
|
||||
),
|
||||
],
|
||||
}),
|
||||
[plugin]: parsed(
|
||||
slice({
|
||||
file_type: "bundle",
|
||||
dependencies: [dependency("@rpath/libshared.dylib")],
|
||||
}),
|
||||
),
|
||||
"Contents/Shared/libshared.dylib": parsed(slice()),
|
||||
}),
|
||||
{ roots: [MAIN] },
|
||||
);
|
||||
expect(edgeFor(trace, plugin, "@rpath/libshared.dylib").candidates).toEqual(
|
||||
[
|
||||
expect.objectContaining({
|
||||
path: "Contents/MacOS/../Shared/libshared.dylib",
|
||||
rpath_owner: MAIN,
|
||||
outcome: "resolved",
|
||||
resolved_path: "Contents/Shared/libshared.dylib",
|
||||
}),
|
||||
],
|
||||
);
|
||||
});
|
||||
|
||||
it("gives each executable root its own @executable_path", async () => {
|
||||
const service = "Contents/XPCServices/Fetch.xpc/Contents/MacOS/Fetch";
|
||||
const trace = await traceDylibLoading(
|
||||
memoryView({
|
||||
[MAIN]: executable({
|
||||
dependencies: [dependency("@executable_path/libhere.dylib")],
|
||||
}),
|
||||
[service]: executable({
|
||||
dependencies: [dependency("@executable_path/libhere.dylib")],
|
||||
}),
|
||||
"Contents/MacOS/libhere.dylib": parsed(slice()),
|
||||
}),
|
||||
{ roots: [MAIN, service] },
|
||||
);
|
||||
expect(
|
||||
edgeFor(trace, MAIN, "@executable_path/libhere.dylib").resolution.status,
|
||||
).toBe("resolved");
|
||||
expect(
|
||||
edgeFor(trace, service, "@executable_path/libhere.dylib"),
|
||||
).toMatchObject({
|
||||
candidates: [
|
||||
{
|
||||
path: "Contents/XPCServices/Fetch.xpc/Contents/MacOS/libhere.dylib",
|
||||
outcome: "absent",
|
||||
},
|
||||
],
|
||||
resolution: { status: "unresolved", image: null },
|
||||
});
|
||||
});
|
||||
|
||||
it("follows Versions/Current inside the root and stops at escaping links", async () => {
|
||||
const trace = await traceDylibLoading(
|
||||
memoryView(
|
||||
{
|
||||
[MAIN]: executable({
|
||||
rpaths: ["@executable_path/../Frameworks"],
|
||||
dependencies: [
|
||||
dependency("@rpath/Core.framework/Core"),
|
||||
dependency("@rpath/Escape.framework/Escape"),
|
||||
dependency("@executable_path/../../../outside.dylib"),
|
||||
],
|
||||
}),
|
||||
"Contents/Frameworks/Core.framework/Versions/A/Core": parsed(slice()),
|
||||
},
|
||||
{
|
||||
"Contents/Frameworks/Core.framework/Versions/Current": "A",
|
||||
"Contents/Frameworks/Core.framework/Core": "Versions/Current/Core",
|
||||
"Contents/Frameworks/Escape.framework":
|
||||
"/Library/Frameworks/Escape.framework",
|
||||
},
|
||||
),
|
||||
{ roots: [MAIN] },
|
||||
);
|
||||
expect(
|
||||
edgeFor(trace, MAIN, "@rpath/Core.framework/Core").resolution,
|
||||
).toEqual({
|
||||
status: "resolved",
|
||||
image: "Contents/Frameworks/Core.framework/Versions/A/Core",
|
||||
});
|
||||
for (const name of [
|
||||
"@rpath/Escape.framework/Escape",
|
||||
"@executable_path/../../../outside.dylib",
|
||||
])
|
||||
expect(edgeFor(trace, MAIN, name)).toMatchObject({
|
||||
candidates: [{ outcome: "escapes-target" }],
|
||||
resolution: { status: "undetermined", image: null },
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("dyld resolution outcomes", () => {
|
||||
it("keeps paths outside the root undetermined and in-root fallbacks conditional", async () => {
|
||||
const trace = await traceDylibLoading(
|
||||
memoryView({
|
||||
[MAIN]: executable({
|
||||
rpaths: ["/usr/lib/swift", "@executable_path/../Frameworks"],
|
||||
dependencies: [
|
||||
dependency("/usr/lib/libSystem.B.dylib"),
|
||||
dependency("@rpath/libswiftCore.dylib"),
|
||||
dependency("libleaf.dylib"),
|
||||
],
|
||||
}),
|
||||
"Contents/Frameworks/libswiftCore.dylib": parsed(slice()),
|
||||
}),
|
||||
{ roots: [MAIN] },
|
||||
);
|
||||
expect(edgeFor(trace, MAIN, "/usr/lib/libSystem.B.dylib")).toMatchObject({
|
||||
candidates: [
|
||||
{ outcome: "outside-target", path: "/usr/lib/libSystem.B.dylib" },
|
||||
],
|
||||
resolution: { status: "undetermined", image: null },
|
||||
});
|
||||
expect(edgeFor(trace, MAIN, "@rpath/libswiftCore.dylib")).toMatchObject({
|
||||
candidates: [
|
||||
{
|
||||
outcome: "outside-target",
|
||||
path: "/usr/lib/swift/libswiftCore.dylib",
|
||||
},
|
||||
{ outcome: "resolved" },
|
||||
],
|
||||
resolution: {
|
||||
status: "conditional",
|
||||
image: "Contents/Frameworks/libswiftCore.dylib",
|
||||
},
|
||||
});
|
||||
expect(edgeFor(trace, MAIN, "libleaf.dylib").resolution.status).toBe(
|
||||
"undetermined",
|
||||
);
|
||||
});
|
||||
|
||||
it("derives unresolved and earlier-candidate findings separately for weak loads", async () => {
|
||||
const trace = await traceDylibLoading(
|
||||
memoryView({
|
||||
[MAIN]: executable({
|
||||
rpaths: [
|
||||
"@executable_path/../Overrides",
|
||||
"@executable_path/../Frameworks",
|
||||
],
|
||||
dependencies: [
|
||||
dependency("@rpath/libfound.dylib"),
|
||||
dependency("@rpath/libgone.dylib", {
|
||||
command: "LC_LOAD_WEAK_DYLIB",
|
||||
weak: true,
|
||||
}),
|
||||
dependency("@rpath/libmissing.dylib"),
|
||||
],
|
||||
dyld_environment: ["DYLD_LIBRARY_PATH=/tmp"],
|
||||
}),
|
||||
"Contents/Frameworks/libfound.dylib": parsed(slice()),
|
||||
}),
|
||||
{ roots: [MAIN] },
|
||||
);
|
||||
expect(
|
||||
trace.findings.map(({ kind, edge_index: index }) => [kind, index]),
|
||||
).toEqual([
|
||||
["earlier-rpath-candidate-absent", 0],
|
||||
["weak-load-unresolved", 1],
|
||||
["required-load-unresolved", 2],
|
||||
["dyld-environment-present", null],
|
||||
]);
|
||||
expect(trace.findings[0]?.explanation).toContain(
|
||||
"Contents/MacOS/../Overrides/libfound.dylib",
|
||||
);
|
||||
});
|
||||
|
||||
it("reports non-Mach-O, malformed and wrong-architecture candidates", async () => {
|
||||
const trace = await traceDylibLoading(
|
||||
memoryView({
|
||||
[MAIN]: executable({
|
||||
rpaths: [
|
||||
"@executable_path/a",
|
||||
"@executable_path/b",
|
||||
"@executable_path/c",
|
||||
],
|
||||
dependencies: [dependency("@rpath/lib.dylib")],
|
||||
}),
|
||||
"Contents/MacOS/a/lib.dylib": "data",
|
||||
"Contents/MacOS/b/lib.dylib": {
|
||||
status: "malformed",
|
||||
reason: "load command 0 has invalid cmdsize 0",
|
||||
},
|
||||
"Contents/MacOS/c/lib.dylib": parsed(slice({ architecture: "x86_64" })),
|
||||
}),
|
||||
{ roots: [MAIN] },
|
||||
);
|
||||
expect(
|
||||
edgeFor(trace, MAIN, "@rpath/lib.dylib").candidates.map(
|
||||
({ outcome }) => outcome,
|
||||
),
|
||||
).toEqual(["not-mach-o", "malformed", "architecture-missing"]);
|
||||
expect(trace.coverage).toEqual({
|
||||
status: "partial",
|
||||
unparsed_images: ["Contents/MacOS/b/lib.dylib"],
|
||||
roots_without_architecture: [],
|
||||
});
|
||||
expect(trace.images.map(({ path }) => path)).toEqual([
|
||||
MAIN,
|
||||
"Contents/MacOS/b/lib.dylib",
|
||||
"Contents/MacOS/c/lib.dylib",
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("dyld load order", () => {
|
||||
it("loads each image once per process and reuses matching install names", async () => {
|
||||
const a = "Contents/Frameworks/libA.dylib";
|
||||
const b = "Contents/Frameworks/libB.dylib";
|
||||
const trace = await traceDylibLoading(
|
||||
memoryView({
|
||||
[MAIN]: executable({
|
||||
rpaths: ["@executable_path/../Frameworks"],
|
||||
dependencies: [
|
||||
dependency("@rpath/libA.dylib"),
|
||||
dependency("@rpath/libB.dylib"),
|
||||
],
|
||||
}),
|
||||
[a]: parsed(
|
||||
slice({
|
||||
install_name: "@rpath/libA.dylib",
|
||||
dependencies: [
|
||||
dependency("@rpath/libB.dylib"),
|
||||
dependency("@rpath/libA.dylib"),
|
||||
],
|
||||
}),
|
||||
),
|
||||
[b]: parsed(
|
||||
slice({
|
||||
install_name: "@rpath/libB.dylib",
|
||||
dependencies: [dependency("@rpath/libA.dylib")],
|
||||
}),
|
||||
),
|
||||
}),
|
||||
{ roots: [MAIN] },
|
||||
);
|
||||
expect(
|
||||
trace.edges.map(
|
||||
({ loader, install_name: name }) =>
|
||||
`${loader.split("/").at(-1)}>${name}`,
|
||||
),
|
||||
).toEqual([
|
||||
"App>@rpath/libA.dylib",
|
||||
"App>@rpath/libB.dylib",
|
||||
"libA.dylib>@rpath/libB.dylib",
|
||||
"libA.dylib>@rpath/libA.dylib",
|
||||
"libB.dylib>@rpath/libA.dylib",
|
||||
]);
|
||||
expect(edgeFor(trace, b, "@rpath/libA.dylib").candidates).toEqual([
|
||||
expect.objectContaining({ source: "already-loaded", resolved_path: a }),
|
||||
]);
|
||||
expect(edgeFor(trace, a, "@rpath/libA.dylib").install_name_matches).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
it("leaves @executable_path undetermined for a library root and filters architectures", async () => {
|
||||
const library = "Contents/Frameworks/libroot.dylib";
|
||||
const trace = await traceDylibLoading(
|
||||
memoryView({
|
||||
[library]: parsed(
|
||||
slice({ dependencies: [dependency("@executable_path/x.dylib")] }),
|
||||
),
|
||||
[MAIN]: executable(),
|
||||
}),
|
||||
{ roots: [library, MAIN], architecture: "x86_64" },
|
||||
);
|
||||
expect(trace.roots).toEqual([]);
|
||||
expect(trace.coverage.roots_without_architecture).toEqual([library, MAIN]);
|
||||
const arm = await traceDylibLoading(
|
||||
memoryView({
|
||||
[library]: parsed(
|
||||
slice({ dependencies: [dependency("@executable_path/x.dylib")] }),
|
||||
),
|
||||
}),
|
||||
{ roots: [library] },
|
||||
);
|
||||
expect(arm.edges[0]?.candidates).toEqual([
|
||||
expect.objectContaining({
|
||||
source: "executable_path",
|
||||
outcome: "undetermined",
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
it("stops when cancelled", async () => {
|
||||
const controller = new AbortController();
|
||||
controller.abort();
|
||||
await expect(
|
||||
traceDylibLoading(memoryView({ [MAIN]: executable() }), {
|
||||
roots: [MAIN],
|
||||
signal: controller.signal,
|
||||
}),
|
||||
).rejects.toThrow();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,542 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import {
|
||||
directoryOf,
|
||||
expandPrefix,
|
||||
joinPath,
|
||||
resolveTreePath,
|
||||
type Expansion,
|
||||
} from "./dyldPaths.js";
|
||||
import { digestSchema } from "./digests.js";
|
||||
|
||||
/** Normalized path below the analyzed root: no `.`/`..` or empty segments. */
|
||||
const ROOT_RELATIVE_PATH =
|
||||
/^(?!\/)(?!(?:.*\/)?\.{1,2}(?:\/|$))(?!.*\/\/)(?!.*\/$)[^\\\0]+$/u;
|
||||
const rootRelativePathSchema = z.string().min(1).regex(ROOT_RELATIVE_PATH);
|
||||
|
||||
/** Caller selection of process roots and one CPU slice. */
|
||||
export const dylibResolutionInputSchema = z.strictObject({
|
||||
roots: z.array(rootRelativePathSchema).min(1).optional(),
|
||||
architecture: z.enum(["arm64", "arm64e", "x86_64"]).optional(),
|
||||
});
|
||||
|
||||
const dependencyCommandSchema = z.enum([
|
||||
"LC_LOAD_DYLIB",
|
||||
"LC_LOAD_WEAK_DYLIB",
|
||||
"LC_REEXPORT_DYLIB",
|
||||
"LC_LAZY_LOAD_DYLIB",
|
||||
"LC_LOAD_UPWARD_DYLIB",
|
||||
]);
|
||||
|
||||
const dependencySchema = z.strictObject({
|
||||
command: dependencyCommandSchema,
|
||||
encoding: z.enum(["dylib_command", "dylib_use_command"]),
|
||||
install_name: z.string(),
|
||||
weak: z.boolean(),
|
||||
upward: z.boolean(),
|
||||
reexport: z.boolean(),
|
||||
delayed_init: z.boolean(),
|
||||
current_version: z.string(),
|
||||
compatibility_version: z.string(),
|
||||
});
|
||||
|
||||
/** Observed dylib-loading facts of one Mach-O slice. */
|
||||
export const machoSliceSchema = z.strictObject({
|
||||
architecture: z.string().min(1),
|
||||
file_type: z.enum(["execute", "dylib", "bundle", "other"]),
|
||||
install_name: z.string().nullable(),
|
||||
dependencies: z.array(dependencySchema),
|
||||
rpaths: z.array(z.string()),
|
||||
dyld_environment: z.array(z.string()),
|
||||
code_signature_present: z.boolean(),
|
||||
});
|
||||
|
||||
export type MachoDependency = z.infer<typeof dependencySchema>;
|
||||
export type MachoSlice = z.infer<typeof machoSliceSchema>;
|
||||
|
||||
/** Header parse of one file; malformed and unsupported images keep their reason. */
|
||||
export type MachoImageFacts =
|
||||
| { readonly status: "parsed"; readonly slices: readonly MachoSlice[] }
|
||||
| {
|
||||
readonly status: "malformed" | "unsupported";
|
||||
readonly reason: string;
|
||||
}
|
||||
| { readonly status: "not-mach-o" };
|
||||
|
||||
/** One observed path below the analyzed root. Symlink targets are not followed by the view. */
|
||||
export type DylibTreeEntry =
|
||||
| { readonly kind: "file" | "directory" }
|
||||
| { readonly kind: "symlink"; readonly target: string };
|
||||
|
||||
/** Read-only, lazily probed view of the analyzed root. Paths are root-relative. */
|
||||
export interface DylibTreeView {
|
||||
entry(path: string): Promise<DylibTreeEntry | undefined>;
|
||||
image(path: string): Promise<MachoImageFacts>;
|
||||
}
|
||||
|
||||
const candidateSchema = z.strictObject({
|
||||
path: z.string(),
|
||||
source: z.enum([
|
||||
"literal",
|
||||
"executable_path",
|
||||
"loader_path",
|
||||
"rpath",
|
||||
"already-loaded",
|
||||
]),
|
||||
rpath: z.string().nullable(),
|
||||
rpath_owner: z.string().nullable(),
|
||||
outcome: z.enum([
|
||||
"resolved",
|
||||
"absent",
|
||||
"not-mach-o",
|
||||
"malformed",
|
||||
"architecture-missing",
|
||||
"outside-target",
|
||||
"escapes-target",
|
||||
"undetermined",
|
||||
]),
|
||||
resolved_path: z.string().nullable(),
|
||||
});
|
||||
|
||||
const edgeSchema = z.strictObject({
|
||||
root: z.string(),
|
||||
architecture: z.string(),
|
||||
loader: z.string(),
|
||||
via: z.array(z.string()),
|
||||
...dependencySchema.shape,
|
||||
candidates: z.array(candidateSchema),
|
||||
resolution: z.strictObject({
|
||||
status: z.enum(["resolved", "conditional", "unresolved", "undetermined"]),
|
||||
image: z.string().nullable(),
|
||||
}),
|
||||
install_name_matches: z.boolean().nullable(),
|
||||
});
|
||||
|
||||
const findingSchema = z.strictObject({
|
||||
kind: z.enum([
|
||||
"required-load-unresolved",
|
||||
"weak-load-unresolved",
|
||||
"earlier-rpath-candidate-absent",
|
||||
"dyld-environment-present",
|
||||
]),
|
||||
edge_index: z.number().int().nonnegative().nullable(),
|
||||
image: z.string().nullable(),
|
||||
basis: z.literal("derived"),
|
||||
explanation: z.string().min(1),
|
||||
});
|
||||
|
||||
const imageSchema = z.strictObject({
|
||||
path: z.string(),
|
||||
sha256: digestSchema,
|
||||
parse_status: z.enum(["parsed", "malformed", "unsupported"]),
|
||||
reason: z.string().nullable(),
|
||||
slices: z.array(machoSliceSchema.omit({ dependencies: true })),
|
||||
});
|
||||
|
||||
/** Static dyld load-path resolution for every selected process root. */
|
||||
export const dylibResolutionResultSchema = z.strictObject({
|
||||
root_path: z.string(),
|
||||
target_sha256: digestSchema,
|
||||
roots: z.array(
|
||||
z.strictObject({ image: z.string(), architecture: z.string() }),
|
||||
),
|
||||
images: z.array(imageSchema),
|
||||
edges: z.array(edgeSchema),
|
||||
findings: z.array(findingSchema),
|
||||
coverage: z.strictObject({
|
||||
status: z.enum(["complete", "partial"]),
|
||||
unparsed_images: z.array(z.string()),
|
||||
roots_without_architecture: z.array(z.string()),
|
||||
}),
|
||||
limitations: z.array(z.string().min(1)),
|
||||
});
|
||||
|
||||
export type DylibResolutionResult = z.infer<typeof dylibResolutionResultSchema>;
|
||||
type Candidate = z.infer<typeof candidateSchema>;
|
||||
type Edge = z.infer<typeof edgeSchema>;
|
||||
type Finding = z.infer<typeof findingSchema>;
|
||||
|
||||
/** Result before the adapter adds file digests and the analyzed root. */
|
||||
export type DylibTrace = Omit<
|
||||
DylibResolutionResult,
|
||||
"root_path" | "target_sha256" | "images"
|
||||
> & {
|
||||
readonly images: readonly (Omit<
|
||||
DylibResolutionResult["images"][number],
|
||||
"sha256"
|
||||
> & { readonly sha256?: never })[];
|
||||
};
|
||||
|
||||
interface LoadedImage {
|
||||
readonly slice: MachoSlice;
|
||||
/** Images from the process root to this image; the rpath stack, outermost first. */
|
||||
readonly chain: readonly string[];
|
||||
}
|
||||
|
||||
interface ProcessContext {
|
||||
readonly view: DylibTreeView;
|
||||
readonly root: string;
|
||||
readonly architecture: string;
|
||||
readonly executable: string | null;
|
||||
readonly loaded: Map<string, LoadedImage>;
|
||||
readonly byInstallName: Map<string, string>;
|
||||
readonly images: Map<string, MachoImageFacts>;
|
||||
}
|
||||
|
||||
interface CandidateTemplate {
|
||||
readonly expansion: Expansion;
|
||||
readonly source: Candidate["source"];
|
||||
readonly rpath: string | null;
|
||||
readonly rpathOwner: string | null;
|
||||
}
|
||||
|
||||
const candidateTemplates = (
|
||||
dependency: MachoDependency,
|
||||
loader: string,
|
||||
context: ProcessContext,
|
||||
): CandidateTemplate[] => {
|
||||
const name = dependency.install_name;
|
||||
if (!name.startsWith("@rpath/")) {
|
||||
const source = name.startsWith("@executable_path")
|
||||
? "executable_path"
|
||||
: name.startsWith("@loader_path")
|
||||
? "loader_path"
|
||||
: "literal";
|
||||
return [
|
||||
{
|
||||
expansion: expandPrefix(name, {
|
||||
ownerDirectory: directoryOf(loader),
|
||||
executable: context.executable,
|
||||
}),
|
||||
source,
|
||||
rpath: null,
|
||||
rpathOwner: null,
|
||||
},
|
||||
];
|
||||
}
|
||||
const rest = name.slice("@rpath/".length);
|
||||
const owners = [...(context.loaded.get(loader)?.chain ?? [loader])].reverse();
|
||||
return owners.flatMap((owner) =>
|
||||
(context.loaded.get(owner)?.slice.rpaths ?? []).map((rpath) => {
|
||||
const base = expandPrefix(rpath, {
|
||||
ownerDirectory: directoryOf(owner),
|
||||
executable: context.executable,
|
||||
});
|
||||
const expansion: Expansion = {
|
||||
scope: base.scope,
|
||||
path:
|
||||
base.scope === "outside"
|
||||
? `${base.path.replace(/\/+$/u, "")}/${rest}`
|
||||
: joinPath(base.path, rest),
|
||||
};
|
||||
return { expansion, source: "rpath" as const, rpath, rpathOwner: owner };
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
const evaluateCandidate = async (
|
||||
template: CandidateTemplate,
|
||||
context: ProcessContext,
|
||||
): Promise<Candidate> => {
|
||||
const base = {
|
||||
path: template.expansion.path,
|
||||
source: template.source,
|
||||
rpath: template.rpath,
|
||||
rpath_owner: template.rpathOwner,
|
||||
};
|
||||
if (template.expansion.scope === "outside")
|
||||
return { ...base, outcome: "outside-target", resolved_path: null };
|
||||
if (template.expansion.scope === "undetermined")
|
||||
return { ...base, outcome: "undetermined", resolved_path: null };
|
||||
const lookup = await resolveTreePath(context.view, template.expansion.path);
|
||||
if (lookup.kind === "escapes")
|
||||
return { ...base, outcome: "escapes-target", resolved_path: null };
|
||||
if (lookup.kind !== "file")
|
||||
return { ...base, outcome: "absent", resolved_path: null };
|
||||
const facts = await imageFacts(context, lookup.path);
|
||||
const outcome: Candidate["outcome"] =
|
||||
facts.status === "not-mach-o"
|
||||
? "not-mach-o"
|
||||
: facts.status !== "parsed"
|
||||
? "malformed"
|
||||
: facts.slices.some(
|
||||
({ architecture }) => architecture === context.architecture,
|
||||
)
|
||||
? "resolved"
|
||||
: "architecture-missing";
|
||||
return { ...base, outcome, resolved_path: lookup.path };
|
||||
};
|
||||
|
||||
const imageFacts = async (
|
||||
context: ProcessContext,
|
||||
path: string,
|
||||
): Promise<MachoImageFacts> => {
|
||||
const known = context.images.get(path);
|
||||
if (known !== undefined) return known;
|
||||
const facts = await context.view.image(path);
|
||||
context.images.set(path, facts);
|
||||
return facts;
|
||||
};
|
||||
|
||||
const resolution = (candidates: readonly Candidate[]): Edge["resolution"] => {
|
||||
let external = false;
|
||||
for (const candidate of candidates) {
|
||||
if (candidate.outcome === "resolved")
|
||||
return {
|
||||
status: external ? "conditional" : "resolved",
|
||||
image: candidate.resolved_path,
|
||||
};
|
||||
if (
|
||||
candidate.outcome === "outside-target" ||
|
||||
candidate.outcome === "escapes-target" ||
|
||||
candidate.outcome === "undetermined"
|
||||
)
|
||||
external = true;
|
||||
}
|
||||
return { status: external ? "undetermined" : "unresolved", image: null };
|
||||
};
|
||||
|
||||
const resolveDependency = async (
|
||||
dependency: MachoDependency,
|
||||
loader: string,
|
||||
context: ProcessContext,
|
||||
): Promise<Edge> => {
|
||||
const chain = context.loaded.get(loader)?.chain ?? [loader];
|
||||
const loaded = context.byInstallName.get(dependency.install_name);
|
||||
const candidates: Candidate[] = [];
|
||||
if (loaded !== undefined)
|
||||
candidates.push({
|
||||
path: dependency.install_name,
|
||||
source: "already-loaded",
|
||||
rpath: null,
|
||||
rpath_owner: null,
|
||||
outcome: "resolved",
|
||||
resolved_path: loaded,
|
||||
});
|
||||
else
|
||||
for (const template of candidateTemplates(dependency, loader, context)) {
|
||||
const candidate = await evaluateCandidate(template, context);
|
||||
candidates.push(candidate);
|
||||
// dyld stops at the first loadable candidate.
|
||||
if (candidate.outcome === "resolved") break;
|
||||
}
|
||||
const resolved = resolution(candidates);
|
||||
const image =
|
||||
resolved.image === null ? undefined : context.images.get(resolved.image);
|
||||
const slice =
|
||||
image?.status === "parsed"
|
||||
? image.slices.find(
|
||||
({ architecture }) => architecture === context.architecture,
|
||||
)
|
||||
: undefined;
|
||||
return {
|
||||
root: context.root,
|
||||
architecture: context.architecture,
|
||||
loader,
|
||||
via: [...chain],
|
||||
...dependency,
|
||||
candidates,
|
||||
resolution: resolved,
|
||||
install_name_matches:
|
||||
slice === undefined || slice.install_name === null
|
||||
? null
|
||||
: slice.install_name === dependency.install_name,
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* Follow dyld4's dependents-first order: resolve every dependency of one
|
||||
* image, then recurse into the images it newly loaded, in load-command order.
|
||||
*/
|
||||
const traceProcess = async (
|
||||
context: ProcessContext,
|
||||
rootSlice: MachoSlice,
|
||||
signal?: AbortSignal,
|
||||
): Promise<Edge[]> => {
|
||||
const edges: Edge[] = [];
|
||||
context.loaded.set(context.root, { slice: rootSlice, chain: [context.root] });
|
||||
if (rootSlice.install_name !== null)
|
||||
context.byInstallName.set(rootSlice.install_name, context.root);
|
||||
const pending = [context.root];
|
||||
while (pending.length > 0) {
|
||||
signal?.throwIfAborted();
|
||||
const loader = pending.pop() ?? "";
|
||||
const current = context.loaded.get(loader);
|
||||
if (current === undefined) continue;
|
||||
const created: string[] = [];
|
||||
for (const dependency of current.slice.dependencies) {
|
||||
const edge = await resolveDependency(dependency, loader, context);
|
||||
edges.push(edge);
|
||||
const image = edge.resolution.image;
|
||||
if (image === null || context.loaded.has(image)) continue;
|
||||
const facts = context.images.get(image);
|
||||
const slice =
|
||||
facts?.status === "parsed"
|
||||
? facts.slices.find(
|
||||
({ architecture }) => architecture === context.architecture,
|
||||
)
|
||||
: undefined;
|
||||
if (slice === undefined) continue;
|
||||
context.loaded.set(image, { slice, chain: [...current.chain, image] });
|
||||
if (
|
||||
slice.install_name !== null &&
|
||||
!context.byInstallName.has(slice.install_name)
|
||||
)
|
||||
context.byInstallName.set(slice.install_name, image);
|
||||
created.push(image);
|
||||
}
|
||||
pending.push(...created.reverse());
|
||||
}
|
||||
return edges;
|
||||
};
|
||||
|
||||
/** Trace dyld load paths from each process root through the analyzed root. */
|
||||
export const traceDylibLoading = async (
|
||||
view: DylibTreeView,
|
||||
request: {
|
||||
readonly roots: readonly string[];
|
||||
readonly architecture?: string;
|
||||
readonly signal?: AbortSignal;
|
||||
},
|
||||
): Promise<DylibTrace> => {
|
||||
const images = new Map<string, MachoImageFacts>();
|
||||
const roots: DylibTrace["roots"][number][] = [];
|
||||
const edges: Edge[] = [];
|
||||
const withoutArchitecture: string[] = [];
|
||||
for (const root of request.roots) {
|
||||
const facts = await view.image(root);
|
||||
images.set(root, facts);
|
||||
if (facts.status !== "parsed") continue;
|
||||
const slices = facts.slices.filter(
|
||||
({ architecture }) =>
|
||||
request.architecture === undefined ||
|
||||
architecture === request.architecture,
|
||||
);
|
||||
if (slices.length === 0) withoutArchitecture.push(root);
|
||||
for (const slice of slices) {
|
||||
roots.push({ image: root, architecture: slice.architecture });
|
||||
edges.push(
|
||||
...(await traceProcess(
|
||||
{
|
||||
view,
|
||||
root,
|
||||
architecture: slice.architecture,
|
||||
executable: slice.file_type === "execute" ? root : null,
|
||||
loaded: new Map(),
|
||||
byInstallName: new Map(),
|
||||
images,
|
||||
},
|
||||
slice,
|
||||
request.signal,
|
||||
)),
|
||||
);
|
||||
}
|
||||
}
|
||||
const reported = [...images.entries()]
|
||||
.filter(([, facts]) => facts.status !== "not-mach-o")
|
||||
.sort(([left], [right]) => compare(left, right));
|
||||
const unparsed = reported
|
||||
.filter(([, facts]) => facts.status !== "parsed")
|
||||
.map(([path]) => path);
|
||||
return {
|
||||
roots,
|
||||
images: reported.map(([path, facts]) => ({
|
||||
path,
|
||||
parse_status:
|
||||
facts.status === "not-mach-o" ? "unsupported" : facts.status,
|
||||
reason:
|
||||
facts.status === "parsed" || facts.status === "not-mach-o"
|
||||
? null
|
||||
: facts.reason,
|
||||
slices:
|
||||
facts.status === "parsed" ? facts.slices.map(withoutDependencies) : [],
|
||||
})),
|
||||
edges,
|
||||
findings: deriveFindings(edges, roots, images),
|
||||
coverage: {
|
||||
status:
|
||||
unparsed.length === 0 && withoutArchitecture.length === 0
|
||||
? "complete"
|
||||
: "partial",
|
||||
unparsed_images: unparsed,
|
||||
roots_without_architecture: withoutArchitecture,
|
||||
},
|
||||
limitations: DYLIB_RESOLUTION_LIMITATIONS,
|
||||
};
|
||||
};
|
||||
|
||||
const withoutDependencies = (
|
||||
slice: MachoSlice,
|
||||
): Omit<MachoSlice, "dependencies"> => ({
|
||||
architecture: slice.architecture,
|
||||
file_type: slice.file_type,
|
||||
install_name: slice.install_name,
|
||||
rpaths: slice.rpaths,
|
||||
dyld_environment: slice.dyld_environment,
|
||||
code_signature_present: slice.code_signature_present,
|
||||
});
|
||||
|
||||
const deriveFindings = (
|
||||
edges: readonly Edge[],
|
||||
roots: DylibTrace["roots"],
|
||||
images: ReadonlyMap<string, MachoImageFacts>,
|
||||
): Finding[] => {
|
||||
const findings: Finding[] = [];
|
||||
edges.forEach((edge, index) => {
|
||||
if (edge.resolution.status === "unresolved")
|
||||
findings.push({
|
||||
kind: edge.weak ? "weak-load-unresolved" : "required-load-unresolved",
|
||||
edge_index: index,
|
||||
image: edge.loader,
|
||||
basis: "derived",
|
||||
explanation: edge.weak
|
||||
? `No candidate for weak dependency ${edge.install_name} exists in the analyzed root; dyld continues without it.`
|
||||
: `No candidate for ${edge.install_name} exists in the analyzed root; dyld would fail to launch ${edge.root} (${edge.architecture}) unless the image is supplied elsewhere.`,
|
||||
});
|
||||
const resolvedAt = edge.candidates.findIndex(
|
||||
({ outcome }) => outcome === "resolved",
|
||||
);
|
||||
const earlier = edge.candidates
|
||||
.slice(0, Math.max(resolvedAt, 0))
|
||||
.filter(
|
||||
({ source, outcome }) => source === "rpath" && outcome === "absent",
|
||||
)
|
||||
.map(({ path }) => path);
|
||||
if (resolvedAt > 0 && earlier.length > 0)
|
||||
findings.push({
|
||||
kind: "earlier-rpath-candidate-absent",
|
||||
edge_index: index,
|
||||
image: edge.loader,
|
||||
basis: "derived",
|
||||
explanation: `dyld searches ${earlier.join(", ")} before ${edge.resolution.image ?? edge.install_name}. A Mach-O placed at an earlier path would load first unless code-signing library validation rejects it; library validation is not evaluated here (see inspect_signature).`,
|
||||
});
|
||||
});
|
||||
for (const { image, architecture } of roots) {
|
||||
const facts = images.get(image);
|
||||
const environment =
|
||||
facts?.status === "parsed"
|
||||
? (facts.slices.find((slice) => slice.architecture === architecture)
|
||||
?.dyld_environment ?? [])
|
||||
: [];
|
||||
if (environment.length > 0)
|
||||
findings.push({
|
||||
kind: "dyld-environment-present",
|
||||
edge_index: null,
|
||||
image,
|
||||
basis: "derived",
|
||||
explanation: `${image} (${architecture}) sets dyld environment variables through LC_DYLD_ENVIRONMENT (${environment.join(", ")}); search paths they add are not modeled.`,
|
||||
});
|
||||
}
|
||||
return findings;
|
||||
};
|
||||
|
||||
const DYLIB_RESOLUTION_LIMITATIONS = [
|
||||
"Absolute install names and rpaths are outside the analyzed root and are not evaluated, including /System and /usr/lib libraries that the dyld shared cache usually provides.",
|
||||
"Leaf and relative install names depend on dyld fallback paths, DYLD_* variables, and the working directory; they are undetermined.",
|
||||
"Load order follows dyld's dependents-first traversal in load-command order. An image reached through several chains is resolved once per process, with the rpath stack of the first chain; a later request whose install name matches an already loaded image reuses it.",
|
||||
"@loader_path uses each image's symlink-resolved path within the analyzed root.",
|
||||
"Code-signing checks that can reject a found image, such as library validation and the hardened runtime, are not evaluated.",
|
||||
];
|
||||
|
||||
const compare = (left: string, right: string): number =>
|
||||
left < right ? -1 : left > right ? 1 : 0;
|
||||
Reference in New Issue
Block a user