Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
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
fix(apple): trace LC_LAZY_LOAD_DYLIB_INFO lazy dylib dependencies
Apple's linker encodes -lazy_library as LC_LAZY_LOAD_DYLIB_INFO (0x3a), a
linkedit_data_command whose __LINKEDIT payload is dyld's
LazyLoadDylibLinkEdit record. The Mach-O load-command reader ignored the
command, so trace-dylib-resolution dropped the dependency while reporting
complete coverage.

Decode the record at the owning parser, validating it as dyld's
LazyLoadDylib::valid() does for the fields that name the dylib, and
normalize lazy semantics once as a dependency 'lazy' flag that the trace and
findings consume instead of matching command names. Lazy-info records carry
no dylib versions, so those fields are null for them.

Fixes #5551

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
  • Loading branch information
kaoru0822-kitauji and claude committed Oct 20, 2026
commit 1ede7a08647b485cdffe9918fdae278830bedcb8
9 changes: 6 additions & 3 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 the `LC_LAZY_LOAD_DYLIB_INFO` records they emit for
`-lazy_library`. Lazy-info records carry no dylib versions, so their
`current_version` and `compatibility_version` are null. Nothing is executed and
no Apple tool is required, so the tool also works off macOS.

Resolution follows dyld:

Expand Down Expand Up @@ -222,7 +224,8 @@ 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
Lazy dependencies (`lazy: true`, from `LC_LAZY_LOAD_DYLIB` or
`LC_LAZY_LOAD_DYLIB_INFO`) are resolved but not traversed, because dyld
loads them on first use; an unresolved one is not a launch failure.
- `earlier-rpath-candidate-absent`: a compatible Mach-O placed at an earlier
modeled search path could take precedence, subject to unmodeled search inputs
Expand Down
69 changes: 67 additions & 2 deletions src/artifacts/apple/MachoImage.fixture.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ export const LC = {
REEXPORT_DYLIB: 0x8000001f,
LAZY_LOAD_DYLIB: 0x20,
LOAD_UPWARD_DYLIB: 0x80000023,
LAZY_LOAD_DYLIB_INFO: 0x3a,
RPATH: 0x8000001c,
DYLD_ENVIRONMENT: 0x27,
CODE_SIGNATURE: 0x1d,
Expand Down Expand Up @@ -102,18 +103,71 @@ export const versionMinCommand = (command: number): Uint8Array => {
return bytes;
};

/**
* dyld's `LazyLoadDylibLinkEdit` payload as Apple's linker lays it out: the
* 24-byte header, the symbol offset array, the path and the symbol names.
*/
export const lazyLoadDylibInfo = (
path: string,
options: {
readonly flags?: number;
readonly symbols?: readonly string[];
} = {},
): Uint8Array => {
const symbols = (options.symbols ?? ["_lf"]).map((name) =>
encoder.encode(name),
);
const name = encoder.encode(path);
const pathOffset = 24 + symbols.length * 4;
let end = pathOffset + name.length + 1;
const symbolOffsets = symbols.map((symbol) => {
const offset = end;
end += symbol.length + 1;
return offset;
});
const bytes = new Uint8Array(Math.ceil(end / 8) * 8);
const view = new DataView(bytes.buffer);
view.setUint32(0, pathOffset, true);
view.setUint32(4, 0x8008, true);
view.setUint16(8, options.flags ?? 0, true);
view.setUint16(10, 6, true);
view.setUint32(12, 0x8000, true);
view.setUint32(16, symbols.length, true);
view.setUint32(20, 24, true);
symbolOffsets.forEach((offset, index) => {
view.setUint32(24 + index * 4, offset, true);
bytes.set(symbols[index] ?? new Uint8Array(), offset);
});
bytes.set(name, pathOffset);
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[];
/** `linkedit_data_command`s appended to `commands`, with data placed after them. */
readonly linkedit?: readonly {
readonly command: number;
readonly data: Uint8Array;
}[];
readonly wide?: boolean;
}): Uint8Array => {
const wide = options.wide ?? true;
const commands = options.commands ?? [];
const linkedit = options.linkedit ?? [];
const commands = [
...(options.commands ?? []),
...linkedit.map(() => new Uint8Array(16)),
];
const headerSize = wide ? 32 : 28;
const commandBytes = commands.reduce((total, item) => total + item.length, 0);
const bytes = new Uint8Array(headerSize + commandBytes + 16);
const dataStart = headerSize + commandBytes + 16;
const dataBytes = linkedit.reduce(
(total, item) => total + item.data.length,
0,
);
const bytes = new Uint8Array(dataStart + dataBytes);
const view = new DataView(bytes.buffer);
const cpu = options.cpu ?? CPU.arm64;
view.setUint32(0, wide ? 0xfeedfacf : 0xfeedface, true);
Expand All @@ -127,6 +181,17 @@ export const machoImage = (options: {
bytes.set(command, offset);
offset += command.length;
}
let dataOffset = dataStart;
let commandOffset = headerSize + commandBytes - linkedit.length * 16;
for (const { command, data } of linkedit) {
view.setUint32(commandOffset, command, true);
view.setUint32(commandOffset + 4, 16, true);
view.setUint32(commandOffset + 8, dataOffset, true);
view.setUint32(commandOffset + 12, data.length, true);
bytes.set(data, dataOffset);
commandOffset += 16;
dataOffset += data.length;
}
return bytes;
};

Expand Down
93 changes: 93 additions & 0 deletions src/artifacts/apple/MachoLoadCommandReader.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import {
dylibCommand,
dylibUseCommand,
fatImage,
lazyLoadDylibInfo,
machoImage,
readerOf,
rpathCommand,
Expand Down Expand Up @@ -353,6 +354,98 @@ describe("Mach-O load command reader: decodes thin-image load commands", () => {
});
});

describe("Mach-O load command reader: decodes LC_LAZY_LOAD_DYLIB_INFO", () => {
it("decodes LC_LAZY_LOAD_DYLIB_INFO records in load-command order", async () => {
const facts = await read(
machoImage({
commands: [dylibCommand(LC.LOAD_DYLIB, "/usr/lib/libSystem.B.dylib")],
linkedit: [
{
command: LC.LAZY_LOAD_DYLIB_INFO,
data: lazyLoadDylibInfo("@rpath/libl.dylib"),
Comment on lines +359 to +365

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Universal binaries lack test coverage

The new lazy-info tests cover only thin images. This is the reader's new path for fetching dependency data outside the load commands, and it depends on adding sliceOffset to dataOffset. The existing FAT tests use only in-command strings, so they would not catch reading a lazy payload from the wrong place.

Add a FAT fixture with lazy-info payloads in nonzero-offset slices and assert their decoded paths.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/artifacts/apple/MachoLoadCommandReader.test.ts
Line: 359-365

Comment:
**Universal binaries lack test coverage**

The new lazy-info tests cover only thin images. This is the reader's new path for fetching dependency data outside the load commands, and it depends on adding `sliceOffset` to `dataOffset`. The existing FAT tests use only in-command strings, so they would not catch reading a lazy payload from the wrong place.

Add a FAT fixture with lazy-info payloads in nonzero-offset slices and assert their decoded paths.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

},
{
command: LC.LAZY_LOAD_DYLIB_INFO,
data: lazyLoadDylibInfo("@rpath/libmaybe.dylib", {
flags: 0x1,
symbols: ["_a", "_b"],
}),
},
],
}),
);
if (facts.status !== "parsed") throw new Error(facts.status);
expect(facts.slices[0]?.dependencies.slice(1)).toEqual([
{
command: "LC_LAZY_LOAD_DYLIB_INFO",
encoding: "lazy_load_dylib_info",
install_name: "@rpath/libl.dylib",
weak: false,
upward: false,
reexport: false,
delayed_init: false,
lazy: true,
current_version: null,
compatibility_version: null,
},
expect.objectContaining({
install_name: "@rpath/libmaybe.dylib",
weak: true,
lazy: true,
}),
]);
});

it("rejects LC_LAZY_LOAD_DYLIB_INFO data that dyld would reject", async () => {
const withData = (data: Uint8Array) =>
read(
machoImage({
linkedit: [{ command: LC.LAZY_LOAD_DYLIB_INFO, data }],
}),
);
const valid = lazyLoadDylibInfo("@rpath/libl.dylib");
const patched = (offset: number, value: number) => {
const bytes = valid.slice();
new DataView(bytes.buffer).setUint32(offset, value, true);
return bytes;
};
await expect(withData(valid.subarray(0, 20))).resolves.toEqual({
status: "malformed",
reason:
"load command 0 LC_LAZY_LOAD_DYLIB_INFO data is too short for its header",
});
await expect(withData(patched(0, valid.length))).resolves.toMatchObject({
status: "malformed",
reason: expect.stringContaining("path offset"),
});
await expect(withData(patched(16, 1000))).resolves.toMatchObject({
status: "malformed",
reason: expect.stringContaining("symbol table exceeds its data"),
});
await expect(
withData(patched(24, valid.length + 1)),
).resolves.toMatchObject({
status: "malformed",
reason: expect.stringContaining("symbol 0 is outside its data"),
});
const unterminated = valid.slice();
unterminated.fill(0x41, 28);
await expect(withData(unterminated)).resolves.toMatchObject({
status: "malformed",
reason: "load command 0 has an unterminated string",
});
const beyond = machoImage({
linkedit: [{ command: LC.LAZY_LOAD_DYLIB_INFO, data: valid }],
});
await expect(
readMachoImage(readerOf(beyond), beyond.length - 1),
).resolves.toMatchObject({
status: "malformed",
reason: expect.stringContaining("data extends beyond the Mach-O slice"),
});
});
});

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