Skip to content

refactor(macho): select slices through one owner with typed refusals - #10874

Merged
morluto merged 24 commits into
mainfrom
refactor/macho-slice-selection-owner
Nov 15, 2026
Merged

morluto merged 24 commits into
mainfrom
refactor/macho-slice-selection-owner

Conversation

@morluto

@morluto morluto commented Nov 15, 2026 •

Copy link
Copy Markdown
Owner

Summary

Mach-O slice selection now has one owner, selectMachoSlice in src/native/metadata/MachoSliceSelection.ts, with an explicit request mode and a Result whose error is a tagged refusal (architecture_not_present, ambiguous_architecture, admitted_slice_mismatch) or malformed. A caller/admission mismatch is no longer thrown as a plain TypeError that looks like a format failure. Refs plan W7; stacked on #10780 (which now carries #10847 and #10850). Also carries #10875 (collapsed): FIT property and APK certificate extensions [3] lookups through uniqueKeyed; the keyed-first-match baseline is now empty. See #10875 for its design (DT spec / dtc duplicate-property rule; RFC 5280 §4.1/§4.2) and evidence (new APK test fails on the base: 1 failed | 23 passed).

Design

  • Request. { mode: "admitted", architecture, slice } reads the image target admission bound to the session: a universal image only at the admitted range, which must be declared for the architecture's CPU family; a thin image only when its header is of that family. { mode: "architecture", architecture, input? } resolves a caller's selector by CPU family and subtype (the former selectNativeImage).
  • Container. Both modes read the FAT table once through the shared readUniversalMachoImage / readUniversalMachoSlice, which already reject overlapping ranges and FAT-shaped JVM classes and check the slice header against its declaration. The admitted path previously had a second FAT reader (readFatHeaderPrefix + readFatSliceDeclarations) with different rules.
  • Refusal vs format. malformed carries the container's message; the three refusal kinds say the request and the file disagree about which slice is meant. Each consumer decides what a refusal means at its boundary.
  • Lipo records. NativeMachoInspection picks among lipo records, not FAT bytes. That choice moves into selectLipoArchitecture (MachoArchitectureSelection.ts). It takes the same two modes and returns the same refusal type. The admitted range keeps the admitted mode, and a target architecture keeps the policy ranking, or a unique lipo name when REA has no policy for it. A selector that tools would resolve to more than one record is refused.

Problem and expected behavior

  • AppleMachoSelection.selectMachoSlice threw TypeError for "architecture absent", "needs the admitted slice", "admitted slice not declared" and "does not match the requested architecture". parseMachoLayout threw TypeError for a thin image of another CPU family and for a FAT declaration that disagrees with its header. Il2cpp caught every TypeError from the layout as malformed-container, so a refused selection was reported as a damaged file.
  • selectNativeImage already returned a Result, but with a single architecture kind that did not say whether the slice was missing or ambiguous.
  • NativeMachoInspection.selectArchitecture found a policy-less architecture by available.find(({ name }) => name === …) (a keyed-first-match baseline entry). MachoArchitectureSelection matched the guard twice for name lookups in its static policy table.

Expected: one owner states which slice a request addresses, or why it addresses none, as a typed value.

Change and scope

  • src/native/metadata/MachoSliceSelection.ts: selectMachoSlice(bytes, request), MachoSliceRequest, MachoSliceSelectionRefusal, MachoSliceSelectionFailure, AdmittedMachoSlice (moved here). selectNativeImage is removed; requireSelectedNativeImage calls the owner in architecture mode and maps every refusal to the architecture input, as before.
  • src/native/AppleMachoSelection.ts: the old selectMachoSlice, MachoSlice, AdmittedMachoSlice and the two TypeError CPU checks are removed. parseMachoLayout(bytes, selected) parses the image the owner selected. The 32-bit refusal no longer names the requested architecture, which the layout no longer receives.
  • Consumers:
    • AppleDispatchMetadata throws ProviderAdapterError with diagnostics.refusal set to the kind. Admission bound this architecture and range to these exact bytes, so a refusal is an inconsistency inside REA. The projection is unchanged: the old TypeError already became ProviderAdapterError.
    • MachoInitializers notes the refusal, as it notes any undecoded fixup.
    • Il2cpp maps a refusal to unsupported-container and malformed to malformed-container. Its catch (TypeError) is removed.
  • MachoArchitectureSelection.ts: selectLipoArchitecture and architectureBaseName (moved from NativeMachoInspection). Policy subtypes are looked up through a Map built from the static table, so the guard no longer matches it; it is configuration, not parsed data. selectMachoArchitecture and machoToolArchitectureName are now module-private.
  • Baselines: keyed-first-match drops MachoArchitectureSelection.ts (2) and NativeMachoInspection.ts (1); parser-plain-throw AppleMachoSelection.ts 3 → 1.
  • The unknown-magic header (Only little-endian 64-bit Mach-O metadata is supported) is now unsupportedInput("macho"), a plain ParseFailureError and not a BinaryFormatFailure or UnsupportedMachoMetadataFormatError. Dispatch therefore still projects it to ProviderAdapterError, as the boundary test does not treat an unknown header as a supported-format capability limit pins. Il2cpp now reports it as unsupported-container instead of rethrowing a raw TypeError. The parser-plain-throw entry for AppleMachoSelection.ts is removed, and the unit pin in AppleMachoSelection.test.ts now expects an unsupported ParseFailureError.
  • FIT property lookups key each node once (WeakMap of keyed views) instead of re-keying per read.

Contribution scope: not applicable (refactor inside existing boundaries).

Contract and boundary impact

  • Semantic owner and earliest changed stage: selectMachoSlice (bytes) and selectLipoArchitecture (lipo records). Consumers: AppleDispatchMetadata, MachoInitializers, Il2cppBinaryImage, NativeMachoInspection, and the Go/Rust/initializer providers through requireSelectedNativeImage.
  • Contribution scope fit and linked maintainer decision: coordinator decision for plan W7 (caller/admission mismatches are not format failures).
  • CLI and MCP/tool-catalog contract: no schema change. requireSelectedNativeImage issue paths and messages are unchanged; universalSliceMcp boundary tests pass unchanged. inspect_macho lipo refusal messages are unchanged. Admitted dispatch metadata now applies the generic FAT admission rules:
    • Repeated declarations report "Mach-O slices i and j overlap." instead of "Admitted FAT slice is declared more than once".
    • A FAT table that extends past the file is not universal, as admission already ruled. An admitted read of it is refused as admitted_slice_mismatch.
    • The "(FAT header byte order: …)" suffix is no longer appended.
  • Provider, bridge, target-format, or platform compatibility: none.
  • Evidence, artifact, provenance, or reconstruction contract: none.
  • Target selection, authority, upstream behavior, and cleanup details (if applicable): slice choice is unchanged; no ranking is added in admitted mode.
  • Generated metadata (docs/public/product-catalog.json), package, or installation impact: none.

Expected effects (check known effects; use documentation-only on its own).
Unchecked items do not establish absence; leave uncertainties visible.

  • 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:
    • MachoArchitectureSelection.test.ts (new): a policy-less name listed twice is ambiguous_architecture; an absent caller architecture (architecture_not_present) is distinct from an undeclared admitted range (admitted_slice_mismatch); an admitted range listed twice is refused.
    • AppleMachoSelection.test.ts, AppleDispatchMetadata.test.ts: assert refusal kinds and the ProviderAdapterError diagnostics instead of TypeError text.
    • MachoSliceSelection.test.ts: asserts the split kinds.
    • The shared layoutFor fixture selects, then parses, as the readers do.
  • Base reproduction or other evidence: source-derived. On the base, every refusal was a TypeError (see the removed throw new TypeError sites and Il2cpp's catch (TypeError)). The new tests use the new API, so they do not run on the base.
  • User-visible CLI/MCP output (if applicable): unchanged for inspect_macho and slice-selecting providers (boundary tests above).
  • Remaining proof gaps: no real universal binary was run through inspect_native_dispatch_metadata; synthetic fixtures only.

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 check:fast — passed (typecheck + lint), last run after rebasing onto the rebased refactor(native): select ELF sections through the keyed owner #10780.

  • npm run test:focused -- tests/boundary/filesystem/keyedFirstMatchGuard.test.ts src/native/AppleMachoSelection.test.ts src/native/MachoArchitectureSelection.test.ts src/native/NativeMachoInspection.test.ts src/native/AppleDispatchMetadata.test.ts src/native/metadata/MachoSliceSelection.test.ts src/domain/apkSignature/apkV1SignatureBlock.test.ts src/artifacts/fit/FitStructure.test.ts tests/boundary/mcp/universalSliceMcp.test.ts — 323 passed (after rebase).

  • node scripts/verify/architecture-guards.mjs --shrink-baselines — passed; baselines lowered as listed.

  • npm run test:local -- src/native/AppleMachoSelection.test.ts src/native/metadata/MachoSliceSelection.test.ts src/native/NativeMachoInspection.test.ts src/native/AppleDispatchMetadata.test.ts src/native/NativeMachoSelectedSlice.test.ts src/native/NativeMachoCommandDiagnostics.test.ts src/native/NativeMachoVtoolRefusal.test.ts src/native/NativeMachoOperand.test.ts — 260 passed.

  • npm run test:local -- src/native/MachoArchitectureSelection.test.ts — 3 passed.

  • npm run test:focused -- tests/boundary/providers/native/objcClassMetadataFallback.test.ts tests/boundary/mcp/universalSliceMcp.test.ts tests/boundary/mcp/nativeInitializersMcp.test.ts tests/boundary/il2cpp/il2cppMappingOwnership.test.ts tests/boundary/il2cpp/il2cppBinaryFile.test.ts src/native/metadata/Il2cppContainer.test.ts (plus the four src/native files above) — 471 passed.

  • npm run test:focused -- tests/boundary/providers/native/lipoFieldOwnership.test.ts tests/boundary/providers/native/nativeSelectedArchitecture.test.ts tests/boundary/providers/native/nativeProvider.test.ts tests/boundary/providers/native/objcClassMetadataFallback.test.ts tests/boundary/mcp/universalSliceMcp.test.ts — 92 passed.

  • Review follow-up (7116818):

    • npm run test:local -- src/native/AppleDispatchMetadata.test.ts src/native/AppleMachoSelection.test.ts src/artifacts/fit/FitStructure.test.ts src/domain/apkSignature/apkV1SignatureBlock.test.ts src/firmware/devicetree/DevicetreeParser.test.ts: all passed.
    • npm run test:focused -- tests/boundary/providers/native/objcClassMetadataFallback.test.ts tests/boundary/providers/native/nativeMachoUuidlessInspection.test.ts: 25 passed. The unknown header still projects to ProviderAdapterError.
    • The new repeated-subjectKeyIdentifier test fails with the guard removed from apkV1SignatureBlock.ts (1 failed | 24 passed).
    • The new FIT repeated-property test asserts the devicetree parser's existing format refusal; it is reached before propertyOf.
    • npm run check:fast: typecheck passed. Lint errors in the two test files (max-lines-per-function) were fixed by moving the new tests to the top level; npx oxlint on them now reports 0 errors.
  • After refactor(macho): name load-command codes through the shared LC table #10714 merged (fa06533, merging main; conflicts in AppleDispatchMetadata.ts, AppleMachoSelection.ts, AppleMachoSelection.test.ts, objcClassMetadataFallback.test.ts and the guard baseline resolved, then --shrink-baselines): npm run test:local over 22 Mach-O source test files, 603 passed. npm run test:focused -- tests/boundary/providers/native/objcClassMetadataFallback.test.ts tests/boundary/il2cpp/il2cppBinaryFile.test.ts tests/boundary/providers/native/nativeSelectedArchitecture.test.ts tests/boundary/providers/native/nativeProvider.test.ts tests/boundary/providers/native/lipoFieldOwnership.test.ts, 271 passed. npx oxfmt --check ., npm run check:fast, node scripts/verify/architecture-guards.mjs and briefs/local-gate.sh passed.

Compatibility, safety, and release

  • Breaking changes or migration steps: none (internal API only).
  • Real Hopper/Ghidra, browser, or OS coverage: none; macOS native tools not run.
  • Package or release metadata impact: none.
  • Security, privacy, process, or containment review: no new reads; the admitted path still reads only the admitted range.

Author readiness

Human owner:

  • 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.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-15T10:28:10.589619Z fa06533 New commits
ℹ️ 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.

…gh ParseFailure (#10760)

* refactor(parsers): report XML, web artifact and Mach-O failures through ParseFailure

* refactor(xml): type XML parse failures as malformed or unsupported only
…es (#10794)

* refactor(parsers): report apktool strings and XML plist source failures through ParseFailure

* refactor(apktool): drop the unused ParseFailureError import
…10790)

* refactor(nativeaot): read neither of repeated frozen object regions through the keyed owner

* refactor(parsers): retire every first-match section lookup (#10793)

* fix(nativeaot): report an ambiguous frozen object region as partial (#10812)
… the keyed owner (#10847)

* refactor(native): select the GOT base and dependency segments through the keyed owner

resolveGotBase selects the SHT_DYNAMIC section and the allocated .got.plt/.got sections with uniqueKeyed, so a repeat leaves the GOT base unknown instead of taking the first match; elfDependencies reads PT_LOAD segments through the same keyed program table as PT_DYNAMIC. A new keyed-first-match guard recognizes a find/findLast or filter-then-[0] whose predicate compares a key field, whatever the table is called; existing matches are baselined. The unwind fixture can declare PT_DYNAMIC headers and repeated .dynamic/.got.plt sections.

* test(native): pin the PT_DYNAMIC path and destructured keyed lookups

The keyed-first-match guard moves to scripts/verify/keyed-first-match.mjs with focused tests, and now recognizes a destructured key in any position and a destructured filter predicate. The single PT_DYNAMIC unwind test declares .dynamic as SHT_PROGBITS so only the program header supplies DT_PLTGOT, and asserts the resolved ranges.

* fix(macho): refuse repeated chained-fixup and dyld-info tables (#10850)

parseMachoLayout kept the last LC_DYLD_CHAINED_FIXUPS range and merged the rebase/bind streams of every LC_DYLD_INFO(_ONLY) command. A repeat now refuses the slice as malformed. NativeMachoInspection's chained import-name reader already declined repeated LC_DYLD_CHAINED_FIXUPS; that rule is now covered by a test.
@morluto
morluto force-pushed the refactor/keyed-elf-sections branch from d1a105e to b173b5e Compare November 15, 2026 07:46
@greptile-apps

greptile-apps Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5 Tier: plus

[Medium impact] The PR appears safe to merge; no blocking issue was found.

Summary

This PR gives Mach-O byte selection one owner and returns typed refusals separately from malformed-file failures.

  • Mach-O readers select a slice once and report why a request cannot select one.
  • Lipo-based inspection selects one record or reports an ambiguous architecture.
  • FIT readers reuse each node's keyed property view and reject duplicate properties.
  • APK signer matching refuses certificates with repeated identity fields.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  Request["Mach-O bytes and request mode"] --> Owner["selectMachoSlice"]
  Owner --> Shared["Shared FAT reader"]
  Shared --> Selected["Selected bytes, file offset, and identity"]
  Shared --> Malformed["Malformed container"]
  Owner --> Refusal["Typed selection refusal"]
  Selected --> Layout["parseMachoLayout"]
  Layout --> Consumers["Dispatch metadata, initializers, and IL2CPP"]
  Refusal --> Boundary["Consumer chooses its error meaning"]
Loading

Reviews (4) · Last reviewed commit: "Merge remote-tracking branch 'origin/mai..." · Reviewed by Greptile

Comment thread src/artifacts/fit/FitStructure.ts Resolved
@morluto
morluto force-pushed the refactor/macho-slice-selection-owner branch from b21fbba to 7c5b78b Compare November 15, 2026 07:48
…graph failure classes (#10818)

* refactor(parsers): retire the Mach-O, source-map, NDJSON and managed-graph failure classes

* refactor(plist): report property-list and keyed-archive failures through ParseFailure (#10822)

* refactor(plist): report property-list and keyed-archive failures through ParseFailure

* refactor(kuna): report Kuna document failures through ParseFailure (#10824)

* refactor(kuna): report Kuna document failures through ParseFailure

* test(kuna): pin the limit and malformed facts of Kuna document failures

* refactor(plist): report plist decode budgets through ParseFailure (#10842)

* refactor(plist): report plist decode budgets through ParseFailure

The plist preflight owner throws a ParseFailure limit (plist-decode-bytes) for its byte budget, the shared PlistNestingLimitError for nesting depth, and a malformed failure for a reference cycle, instead of a per-format PropertyListDecodeBudgetFailure whose meaning each caller re-mapped through a fail callback. The fail option, PropertyListDecodeBudgetFailure and interfaceBuilderDecodeBudgetFailure are removed; the parser-format-failure-class baseline reaches zero.

* refactor(plist): report keyed-archive allowances as typed limit failures (#10844)

keyedArchive.ts and decodeKeyedArchiveBytes throw decodeLimit parse failures (keyed-archive-bytes, -object-table-entries, -values-per-object, -reference-edges) and malformed parse failures instead of plain RangeError/TypeError. KeyedArchiveReader no longer classifies every RangeError as a limit: only a limit parse failure or a host stack/capacity limit is one. The unreachable 128-level scan nesting check is removed; projectPlistValue already refuses the archive first.
…and subjectKeyIdentifiers, and type the unknown Mach-O header as unsupported
@morluto
morluto force-pushed the refactor/macho-slice-selection-owner branch from f802354 to 7116818 Compare November 15, 2026 08:05
…seFailure and defects through invariantViolation (#10895)

* refactor(plist): report plist and NIBArchive input faults through ParseFailure and defects through invariantViolation

* fix(plist): report a cut-short NIB header or plist length record as truncated
@morluto

morluto commented Nov 15, 2026

Copy link
Copy Markdown
Owner Author

Both issues in the Greptile summary (reviewed at f802354) are fixed in 7116818:

  1. FIT lookups: keyedProperties(node) keys each node once and keeps the view in a WeakMap.
  2. Repeated subjectKeyIdentifier: a new fixture and test cover it. The test fails with the guard removed.

Details are in the resolved review threads. Greptile has not re-reviewed the new head yet.

@morluto

morluto commented Nov 15, 2026

Copy link
Copy Markdown
Owner Author

@greptileai review

7116818 addresses both findings from the last summary (reviewed at f802354); see the reply above.

@morluto
morluto changed the base branch from refactor/keyed-elf-sections to main November 15, 2026 09:03
…ommand-literals

# Conflicts:
#	scripts/verify/architecture-guard-baselines.json
…ommand-literals

# Conflicts:
#	src/ghidra/GhidraClient.ts
# Conflicts:
#	scripts/verify/architecture-guard-baselines.json
… shared owner

nativeMachoSourcePrimary mapped every non-limit ParseFailureError to
AnalysisOutputError, so a malformed or truncated selected Mach-O was
reported as unreadable tool output and an unsupported one lost its
category. It now uses parseFailureAnalysisError like the ELF, Go and
other byte-format providers: malformed and truncated bytes are an
invalid path, unsupported bytes an unsupported target, and a limit
still falls through to its producer's budget.
# Conflicts:
#	scripts/verify/architecture-guard-baselines.json
#	src/kuna/KunaDocumentError.ts
#	src/kuna/KunaProvider.ts
# Conflicts:
#	src/native/AppleDispatchMetadata.ts
#	src/native/AppleMachoSelection.test.ts
#	src/native/AppleMachoSelection.ts
#	tests/boundary/providers/native/objcClassMetadataFallback.test.ts
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area: native Native analysis and decompilation, including Ghidra, IDA, and Hopper analysis behavior

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant