Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
fix(apple): read LC_LAZY_LOAD_DYLIB_INFO dependency payloads
Parse the linkedit install name for lazy-load info commands, resolve those
edges without traversing them, and stop inspect-macho from treating an otool
dependency list as exhaustive when that payload is omitted.

Fixes #5551
Fixes #5649

Co-authored-by: morluto <morluto@users.noreply.github.com>
  • Loading branch information
cursoragent and morluto committed Oct 20, 2026
commit f9482b64e759aa4b4c6e08c76795b3099410b157
12 changes: 8 additions & 4 deletions docs/apple-application-analysis.md
Original file line number Diff line number Diff line change
Expand Up @@ -180,8 +180,10 @@ rea trace-dylib-resolution MyApp.app --root Contents/MacOS/MyApp --architecture

Load commands are parsed in TypeScript from Mach-O and FAT headers, including
the `dylib_use_command` encoding newer linkers emit for flags such as delayed
initialization. Nothing is executed and no Apple tool is required, so the tool
also works off macOS.
initialization, and `LC_LAZY_LOAD_DYLIB_INFO` (`0x3a`). That command stores its
install name in a linkedit payload rather than in the load command itself.
Nothing is executed and no Apple tool is required, so the tool also works off
macOS.

Resolution follows dyld:

Expand Down Expand Up @@ -222,8 +224,10 @@ cache rather than on disk, so REA does not check them against the host.
`findings` are derived, not observed:

- `required-load-unresolved`, `weak-load-unresolved`, and `lazy-load-unresolved`.
`LC_LAZY_LOAD_DYLIB` dependencies are resolved but not traversed, because dyld
loads them on first use; an unresolved one is not a launch failure.
`LC_LAZY_LOAD_DYLIB` and `LC_LAZY_LOAD_DYLIB_INFO` dependencies are resolved
but not traversed, because dyld loads them on first use; an unresolved one is
not a launch failure. `LC_LAZY_LOAD_DYLIB_INFO` has no compatibility version,
so those fields are null. Its may-be-missing flag is reported as `weak`.
- `earlier-rpath-candidate-absent`: a compatible Mach-O placed at an earlier
modeled search path could take precedence, subject to unmodeled search inputs
and code-signing library validation. These findings do not establish which
Expand Down
6 changes: 5 additions & 1 deletion scripts/verify/apple/macos-dylib-e2e.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -140,8 +140,12 @@ const verifyParserConformance = async (app, trace) => {
join(app, image.path),
slice.architecture,
);
// otool -l prints LC_LAZY_LOAD_DYLIB_INFO without its linkedit install
// name, so this comparison cannot expect that edge. The structural
// reader tests own the payload.
const edges = trace.edges.filter(
({ loader, architecture, root }) =>
({ loader, architecture, root, command }) =>
command !== "LC_LAZY_LOAD_DYLIB_INFO" &&
loader === image.path &&
architecture === slice.architecture &&
root ===
Expand Down
81 changes: 81 additions & 0 deletions src/artifacts/apple/MachoImage.fixture.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,87 @@ export const machoImage = (options: {
return bytes;
};

/**
* Little-endian `LC_LAZY_LOAD_DYLIB_INFO` (0x3a) payload.
* The 24-byte header is load-path offset, flag image offset, flags,
* pointer format, chain-start image offset, symbol count, and the
* symbol-offset array offset. Strings are NUL-terminated and the payload
* is padded to 8 bytes, matching a one-symbol `@rpath/libl.dylib` payload
* of 56 bytes.
*/
export const lazyLoadDylibInfoPayload = (options: {
readonly path: string;
readonly symbols?: readonly string[];
readonly flags?: number;
}): Uint8Array => {
const symbols = options.symbols ?? [];
const headerSize = 24;
const pathBytes = encoder.encode(options.path);
const symbolBytes = symbols.map((symbol) => encoder.encode(symbol));
const symbolArrayOffset = headerSize;
const pathOffset = symbolArrayOffset + symbols.length * 4;
let cursor = pathOffset + pathBytes.length + 1;
const symbolOffsets = symbolBytes.map((bytes) => {
const offset = cursor;
cursor += bytes.length + 1;
return offset;
});
const payload = new Uint8Array(Math.ceil(cursor / 8) * 8);
const view = new DataView(payload.buffer);
view.setUint32(0, pathOffset, true);
view.setUint16(8, options.flags ?? 0, true);
view.setUint32(16, symbols.length, true);
view.setUint32(20, symbolArrayOffset, true);
symbolOffsets.forEach((offset, index) =>
view.setUint32(symbolArrayOffset + index * 4, offset, true),
);
payload.set(pathBytes, pathOffset);
symbolBytes.forEach((bytes, index) => {
const offset = symbolOffsets[index];
if (offset !== undefined) payload.set(bytes, offset);
});
return payload;
};

/**
* Place one `LC_LAZY_LOAD_DYLIB_INFO` command among the other commands and
* append its payload after the image. `dataoff` is relative to this slice.
*/
export const machoImageWithLazyLoadDylibInfo = (options: {
readonly path: string;
readonly symbols?: readonly string[];
readonly flags?: number;
readonly cpu?: { readonly type: number; readonly subtype: number };
readonly fileType?: number;
readonly wide?: boolean;
readonly commandsBefore?: readonly Uint8Array[];
readonly commandsAfter?: readonly Uint8Array[];
}): Uint8Array => {
const payload = lazyLoadDylibInfoPayload(options);
const command = new Uint8Array(16);
const commandView = new DataView(command.buffer);
commandView.setUint32(0, 0x3a, true);
commandView.setUint32(4, command.length, true);
const wide = options.wide ?? true;
const commandsBefore = options.commandsBefore ?? [];
const image = machoImage({
...(options.cpu === undefined ? {} : { cpu: options.cpu }),
...(options.fileType === undefined ? {} : { fileType: options.fileType }),
wide,
commands: [...commandsBefore, command, ...(options.commandsAfter ?? [])],
});
const out = new Uint8Array(image.length + payload.length);
out.set(image);
out.set(payload, image.length);
const headerSize = wide ? 32 : 28;
const commandAt =
headerSize + commandsBefore.reduce((total, item) => total + item.length, 0);
const view = new DataView(out.buffer);
view.setUint32(commandAt + 8, image.length, true);
view.setUint32(commandAt + 12, payload.length, true);
return out;
};

/** Thin Mach-O with one unknown command, for width and command-size regressions. */
export const machoImageWithUnknownCommand = (
wide: boolean,
Expand Down
176 changes: 175 additions & 1 deletion src/artifacts/apple/MachoLoadCommandReader.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { createHash } from "node:crypto";
import { mkdir, writeFile } from "node:fs/promises";
import { mkdir, rename, writeFile } from "node:fs/promises";
import { join } from "node:path";

import { describe, expect, it } from "vitest";
Expand All @@ -14,7 +14,9 @@ import {
dylibCommand,
dylibUseCommand,
fatImage,
lazyLoadDylibInfoPayload,
machoImage,
machoImageWithLazyLoadDylibInfo,
readerOf,
rpathCommand,
versionMinCommand,
Expand Down Expand Up @@ -353,6 +355,178 @@ describe("Mach-O load command reader: decodes thin-image load commands", () => {
});
});

describe("LC_LAZY_LOAD_DYLIB_INFO payload", () => {
it("reads install names from the linkedit payload in load-command order", async () => {
const payload = lazyLoadDylibInfoPayload({
path: "@rpath/libl.dylib",
symbols: ["_lf"],
});
expect(payload).toHaveLength(56);
const image = machoImageWithLazyLoadDylibInfo({
path: "@rpath/libl.dylib",
symbols: ["_lf"],
commandsBefore: [
dylibCommand(LC.LOAD_DYLIB, "/usr/lib/libSystem.B.dylib"),
],
commandsAfter: [dylibCommand(LC.LOAD_DYLIB, "@rpath/libafter.dylib")],
});
const facts = await read(image);
if (facts.status !== "parsed")
throw new Error(
facts.status === "not-mach-o" ? facts.status : facts.reason,
);
expect(
facts.slices[0]?.dependencies.map(
({ command, install_name: name, encoding, weak, current_version }) => ({
command,
name,
encoding,
weak,
current_version,
}),
),
).toEqual([
{
command: "LC_LOAD_DYLIB",
name: "/usr/lib/libSystem.B.dylib",
encoding: "dylib_command",
weak: false,
current_version: "1.0.0",
},
{
command: "LC_LAZY_LOAD_DYLIB_INFO",
name: "@rpath/libl.dylib",
encoding: "lazy_load_dylib_info",
weak: false,
current_version: null,
},
{
command: "LC_LOAD_DYLIB",
name: "@rpath/libafter.dylib",
encoding: "dylib_command",
weak: false,
current_version: "1.0.0",
},
]);
const weak = await read(
machoImageWithLazyLoadDylibInfo({
path: "@rpath/libl.dylib",
flags: 0x1,
}),
);
if (weak.status !== "parsed")
throw new Error(weak.status === "not-mach-o" ? weak.status : weak.reason);
expect(weak.slices[0]?.dependencies[0]).toMatchObject({ weak: true });
const universal = await read(
fatImage([
{
cpu: CPU.arm64,
bytes: machoImageWithLazyLoadDylibInfo({
path: "@rpath/libl.dylib",
symbols: ["_lf"],
}),
},
]),
);
if (universal.status !== "parsed")
throw new Error(
universal.status === "not-mach-o" ? universal.status : universal.reason,
);
expect(universal.slices[0]?.dependencies[0]?.install_name).toBe(
"@rpath/libl.dylib",
);
});

it("rejects a lazy-info payload that is truncated, mis-pointed, or has unknown flags", async () => {
const outside = machoImageWithLazyLoadDylibInfo({
path: "@rpath/libl.dylib",
});
const view = new DataView(outside.buffer);
const commandAt = 32;
view.setUint32(commandAt + 8, outside.length, true);
expect((await read(outside)).status).toBe("malformed");

const badPayload = lazyLoadDylibInfoPayload({
path: "@rpath/libl.dylib",
});
const badPath = machoImageWithLazyLoadDylibInfo({
path: "@rpath/libl.dylib",
});
const payloadAt = badPath.length - badPayload.length;
new DataView(badPath.buffer).setUint32(payloadAt, badPath.length, true);
expect(await read(badPath)).toMatchObject({
status: "malformed",
reason: expect.stringContaining("load path"),
});

const unknownFlags = machoImageWithLazyLoadDylibInfo({
path: "@rpath/libl.dylib",
flags: 0x2,
});
expect(await read(unknownFlags)).toMatchObject({
status: "unsupported",
reason: expect.stringContaining("unrecognized bits"),
});
});
});

describe("LC_LAZY_LOAD_DYLIB_INFO resolution", () => {
it("reports the lazy edge and does not treat an absent image as a launch failure", async () => {
const root = await createTestTempDirectory("rea-lazy-info-");
const executablePath = "lazy";
const dylibPath = "lib/libl.dylib";
const executable = machoImageWithLazyLoadDylibInfo({
path: "@rpath/libl.dylib",
symbols: ["_lf"],
commandsBefore: [
buildVersionCommand(1),
rpathCommand("@executable_path/lib"),
dylibCommand(LC.LOAD_DYLIB, "/usr/lib/libSystem.B.dylib"),
],
});
const dylib = machoImage({
fileType: FILE_TYPE.dylib,
commands: [
buildVersionCommand(1),
dylibCommand(LC.ID_DYLIB, "@rpath/libl.dylib"),
dylibCommand(LC.LOAD_DYLIB, "@rpath/libdeep.dylib"),
],
});
await mkdir(join(root, "lib"));
await writeFile(join(root, executablePath), executable);
await writeFile(join(root, dylibPath), dylib);
const trace = () =>
traceDylibResolution({
rootPath: root,
targetPath: join(root, executablePath),
targetSha256: createHash("sha256").update(executable).digest("hex"),
enumerateRoots: false,
parameters: { roots: [executablePath] },
});
const present = await trace();
expect(present.coverage.status).toBe("complete");
expect(present.edges.map(({ install_name: name }) => name)).toEqual([
"/usr/lib/libSystem.B.dylib",
"@rpath/libl.dylib",
]);
expect(present.edges[1]).toMatchObject({
command: "LC_LAZY_LOAD_DYLIB_INFO",
encoding: "lazy_load_dylib_info",
current_version: null,
compatibility_version: null,
resolution: { status: "resolved", image: dylibPath },
});
expect(present.findings).toEqual([]);
await rename(join(root, dylibPath), `${join(root, dylibPath)}.moved`);
const absent = await trace();
expect(absent.coverage.status).toBe("complete");
expect(absent.findings.map(({ kind }) => kind)).toEqual([
"lazy-load-unresolved",
]);
expect(absent.edges[1]?.resolution.status).toBe("unresolved");
});
});

describe("Mach-O load command reader: reads and validates universal binary slices", () => {
it("reads every slice of FAT and FAT_64 containers in either byte order", async () => {
for (const [wide, littleEndian] of [
Expand Down
Loading
Loading