Skip to content

fix(apple): trace LC_LAZY_LOAD_DYLIB_INFO lazy dylib dependencies - #5582

Closed
kaoru0822-kitauji wants to merge 1 commit into
mainfrom
fix/dylib-lazy-load-commands
Closed

kaoru0822-kitauji wants to merge 1 commit into
mainfrom
fix/dylib-lazy-load-commands

Conversation

@kaoru0822-kitauji

@kaoru0822-kitauji kaoru0822-kitauji commented Oct 20, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Fixes #5551

trace-dylib-resolution dropped dylibs linked with -lazy_library by current Apple linkers, but still reported coverage.status: "complete". These linkers encode the dependency as LC_LAZY_LOAD_DYLIB_INFO (0x3a) rather than the legacy LC_LAZY_LOAD_DYLIB (0x20). The dependency now shows up as a lazy edge. It resolves when the dylib is present. When the dylib is absent, the result has a lazy-load-unresolved finding, which stays distinct from a launch failure.

Problem and expected behavior

LC_LAZY_LOAD_DYLIB_INFO is a linkedit_data_command that points to a __LINKEDIT blob. That blob is dyld's LazyLoadDylibLinkEdit record: loadPathOffset, flagImageOffset, flags, pointerFormat, chainStartImageOffset, symbolsCount, symbolStringArrayOffset, followed by the path and symbol strings. The format is defined in apple-oss-distributions/dyld mach_o/LazyLoadDylib.{h,cpp}. MachoLoadCommandReader skipped unrecognized commands, so it never emitted this dependency. The trace then derived complete coverage from the dependencies it did emit.

Change and scope

  • Parser (owning boundary): MachoLoadCommandReader now reads each LC_LAZY_LOAD_DYLIB_INFO payload, in load-command order, as a dependency with command: "LC_LAZY_LOAD_DYLIB_INFO" and encoding: "lazy_load_dylib_info".
    • Validation follows LazyLoadDylib::valid(): header size, path offset and termination, symbol-array bounds, and data inside the slice. It skips the flag and chain-start VM-offset checks, because they need the VM layout and do not change which dylib is named.
    • flags & 1 (dylibMayBeMissing) maps to weak.
    • Payloads over the existing 16 MiB limit are reported as unsupported.
  • Lazy flag set once in the parser: dependencies get a parsed lazy boolean, set for both lazy commands. traceProcess and the findings now use lazy instead of comparing command names.
  • Weak lazy dylibs: a missing weak lazy-info dylib gets a "continues without it" explanation, because dyld's _dyld_lazy_load halts only when the dylib is not weak.
  • Null versions: lazy-info records carry no dylib versions, so current_version and compatibility_version are now nullable and are null for this encoding.
  • Not included: native inspect_macho, which goes through otool -l, still does not list lazy-info dependencies. That is a separate parser and tool contract, left for a follow-up.

Scope: an ordinary fix within existing boundaries; no maintainer scope decision is needed.

Contract and boundary impact

  • Semantic owner and earliest changed stage: src/artifacts/apple/MachoLoadCommandReader.ts (Mach-O load-command parsing).
  • Contribution scope fit and linked maintainer decision: not applicable (bug fix inside the existing static-parsing tool).
  • CLI and MCP/tool-catalog contract: additive changes to the trace_dylib_resolution output schema:
    • a new command enum value and a new encoding enum value;
    • a new lazy boolean on each edge;
    • current_version and compatibility_version are now nullable.
  • Provider, bridge, target-format, or platform compatibility: Mach-O only; no Apple tool required.
  • Evidence, artifact, provenance, or reconstruction contract: no change.
  • Target selection, authority, upstream behavior, and cleanup details: not applicable.
  • Generated metadata, package, or installation impact: none committed.

Expected effects:

  • Read existing files or captured data.
  • Launch or attach to a process.
  • Inject instrumentation or run scripts/code.
  • Change process memory, registers, files, or configuration.
  • Contact network services.
  • Recover protected code or work around protections.
  • Documentation or usability only; no target interaction.
  • Not sure yet; investigation or maintainer guidance needed.

Evidence and regression coverage

  • Tests added or updated:
    • tests/boundary/cli/dylibResolutionCli.test.ts: a CLI test with a lazy-info executable. With the dylib present, the edge resolves and there are no findings. With it absent, the trace reports lazy-load-unresolved. Coverage stays complete in both cases.
    • src/artifacts/apple/MachoLoadCommandReader.test.ts: decoding, including weak flags and multiple symbols, plus each malformed-payload rejection.
    • The MachoImage.fixture.ts builder now lays out the payload exactly as Apple's linker did for the issue repro.
  • Base reproduction: I rebuilt the issue repro on macOS 26.7.1 arm64 with Apple clang 21.0.0 and ld-27037.1, using -mmacosx-version-min=27.0. This linker ignores lazy-load at lower deployment targets. otool -l shows LC_LAZY_LOAD_DYLIB_INFO, datasize 56, and the payload bytes match the fixture layout. With the reader change reverted, the new reader tests fail: 4 failed / 26 passed.
  • CLI output on that real binary after the fix:
    • Dylib present: edges = [LC_LOAD_DYLIB /usr/lib/libSystem.B.dylib undetermined] and [LC_LAZY_LOAD_DYLIB_INFO @rpath/libl.dylib lazy=true resolved lib/libl.dylib]; findings: []; coverage.status: "complete".
    • Dylib moved away: the lazy edge is unresolved, with lazy-load-unresolved: "No candidate for lazily loaded @rpath/libl.dylib exists in the analyzed root; dyld loads it on first use, which would fail unless the image is supplied elsewhere."
  • Remaining proof gaps:
    • I did not run the binary. Its minos is 27.0 and this host runs 26.7.
    • The weak lazy-info path is checked only with synthetic bytes; no linker-produced weak lazy-info binary was tested.
    • Native inspect_macho coverage of lazy-info is not addressed.

For evidence-bearing changes:

  • Observed, derived, and inferred claims remain distinguishable.
  • Artifact identity, source provenance, and failed attempts remain preserved.
  • Unsupported, incomplete, unavailable, or uncertain outcomes remain visible.

Validation performed

  • npm run test:focused -- tests/boundary/cli/dylibResolutionCli.test.ts tests/boundary/mcp/dylibResolutionMcp.test.ts src/artifacts/apple/MachoLoadCommandReader.test.ts src/domain/apple/dylibResolution.test.ts: 4 files, 153 tests passed.
  • npm run test:local -- src/contracts/toolOutputReferences.test.ts src/contracts/tupleSchemaParity.test.ts: 59 passed.
  • npm run check:fast: typecheck and lint passed.
  • npm run docs:check: passed.
  • node scripts/rea.mjs trace-dylib-resolution <clang-built lazy binary> --json, with the dylib present and absent: output as shown above.

Compatibility, safety, and release

  • Breaking changes or migration steps: none intended. Output enums gain values and the version fields become nullable; a strict consumer that assumed version strings would now see null for lazy-info edges.
  • Real Hopper/Ghidra, browser, or OS coverage: macOS 26.7.1 arm64 static trace of a real Apple-linker binary; no providers involved.
  • Package or release metadata impact: none.
  • Security, privacy, process, or containment review: read-only parsing with bounded reads (16 MiB payload limit, bounds-checked offsets).

Author readiness

Human owner: @kaoru0822-kitauji

  • I reviewed the final diff and relevant existing code, understand the change and its edge cases, and take responsibility for the complete PR, including AI-assisted work.
  • I checked the evidence above, confirmed it supports the current change, and recorded meaningful validation gaps.
  • I declare this PR ready for initial maintainer review.

Before merge

  • This PR addresses a concrete problem or an agreed enhancement.
  • Material scope and authority questions are resolved, and any required maintainer scope decision covers the final diff.
  • The PR has one focused outcome and the title follows type(scope): outcome.
  • Related issue is linked, or the reason for not linking one is stated above.
  • Tests cover changed observable behavior and meaningful failure paths.
  • Owning docs, contracts, and generated metadata are updated where needed.
  • User-visible CLI/MCP changes include representative output.
  • I checked the final diff for secrets, unrelated cleanup, and unsupported claims.

🤖 Generated with Claude Code

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>
@kaoru0822-kitauji kaoru0822-kitauji added bug Something isn't working track:issues Issue bug-fix track labels Oct 20, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 20, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-20T15:18:12.836628Z 1ede7a0 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@greptile-apps

greptile-apps Bot commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 3/5

[Medium impact] The change affects the bounded Apple Mach-O dylib tracing workflow and its output contract.

Add a shared payload-read budget before merging so crafted files cannot tie up the reader.

Findings

  1. P1 Security Small files force huge reads ▶
  2. P2 Universal binaries lack test coverage ▶
Fix with agent prompt
### Issue 1
src/artifacts/apple/MachoLoadCommandReader.ts:534-539
Each `LC_LAZY_LOAD_DYLIB_INFO` command can read another 16 MiB, but nothing limits the total across commands. A crafted file can contain 65,536 commands pointing to the same 16 MiB payload. That roughly 17 MiB file makes the reader allocate and read 1 TiB before finishing. Previously, these commands caused no extra reads.

Add a shared read/work budget and return `unsupported` when it is exhausted. The per-record limit alone does not bound this parser.

**How this was verified:** File-controlled commands each trigger a fresh payload allocation and file read, while the bounds checks limit only each individual read.

### Issue 2
src/artifacts/apple/MachoLoadCommandReader.test.ts:359-365
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.

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!

---

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

Summary

Adds LC_LAZY_LOAD_DYLIB_INFO dependencies to static dylib tracing.

  • Dylib traces now include dependencies from Apple's newer lazy-load records.

Review used source inspection; no runtime tests were run. GitHub status and superseding PRs could not be checked because authentication was unavailable.

Acknowledged scope and proof gaps:

  • kaoru0822-kitauji explicitly disclosed synthetic-only coverage of weak lazy-info records and the lack of a linker-produced weak lazy-info sample.
  • kaoru0822-kitauji explicitly deferred lazy-info support in inspect_macho to a follow-up.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart LR
  A[Mach-O commands] --> B[Read lazy-info payload]
  B --> C[Dependency: lazy true]
  C --> D[Resolve candidate]
  D --> E[Emit edge and findings]
  E --> F[Skip launch traversal]
Loading

Reviews (1) · Last reviewed commit: "fix(apple): trace LC_LAZY_LOAD_DYLIB_INF..." · Reviewed by Greptile

Comment on lines +534 to +539
const blob = await readExact(
readAt,
slice.sliceOffset + dataOffset,
dataSize,
`load command ${index} LC_LAZY_LOAD_DYLIB_INFO data`,
);

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.

P1 security Small files force huge reads

Each LC_LAZY_LOAD_DYLIB_INFO command can read another 16 MiB, but nothing limits the total across commands. A crafted file can contain 65,536 commands pointing to the same 16 MiB payload. That roughly 17 MiB file makes the reader allocate and read 1 TiB before finishing. Previously, these commands caused no extra reads.

Add a shared read/work budget and return unsupported when it is exhausted. The per-record limit alone does not bound this parser.

How this was verified: File-controlled commands each trigger a fresh payload allocation and file read, while the bounds checks limit only each individual read.

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

Comment:
**Small files force huge reads**

Each `LC_LAZY_LOAD_DYLIB_INFO` command can read another 16 MiB, but nothing limits the total across commands. A crafted file can contain 65,536 commands pointing to the same 16 MiB payload. That roughly 17 MiB file makes the reader allocate and read 1 TiB before finishing. Previously, these commands caused no extra reads.

Add a shared read/work budget and return `unsupported` when it is exhausted. The per-record limit alone does not bound this parser.

**How this was verified:** File-controlled commands each trigger a fresh payload allocation and file read, while the bounds checks limit only each individual read.

---

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

Comment on lines +359 to +365
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"),

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!

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 1ede7a0864

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +534 to +537
const blob = await readExact(
readAt,
slice.sliceOffset + dataOffset,
dataSize,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Cap duplicate lazy-info payload reads

When an input contains many 16-byte LC_LAZY_LOAD_DYLIB_INFO commands that point at the same payload, every command performs a fresh readAt here. The 16 MiB load-command limit still permits about one million such commands, each referring to a 16 MiB valid payload, so a roughly 32 MiB accepted Mach-O can force approximately 16 TiB of repeated file reads and allocations before tracing completes. Cache payloads by (sliceOffset, dataOffset, dataSize) or apply a cumulative payload-read budget.

AGENTS.md reference: AGENTS.md:L48-L52

Useful? React with 👍 / 👎.

morluto commented Oct 20, 2026

Copy link
Copy Markdown
Owner

Superseded by #5650 (fix(apple): read LC_LAZY_LOAD_DYLIB_INFO dependency payloads), which is now merged into main. Closing this PR — thank you for the contribution @kaoru0822-kitauji.

@morluto morluto closed this Oct 20, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working track:issues Issue bug-fix track

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] trace-dylib-resolution omits lazy dylib dependencies while reporting complete coverage

2 participants