Skip to content

fix(macho)!: report Mach-O read failures as target failures and delete MachoReadIssue - #14416

Merged
morluto merged 162 commits into
mainfrom
fix/macho-target-failure-kinds
Nov 25, 2026
Merged

morluto merged 162 commits into
mainfrom
fix/macho-target-failure-kinds

Conversation

@morluto

@morluto morluto commented Nov 25, 2026 •

Copy link
Copy Markdown
Owner

Native and Mach-O step of the #14239 stack, including the sibling cases left out of #14233. The base is now main: #14247 through #14292 have merged, and origin/main is merged in. #14417 (the retired-vocabulary guard) was merged into this branch by the merge gate, so this PR also carries it and is the stack's last PR.

Root cause

MachoReadIssue was { status: "malformed" | "unsupported", reason: string }. It could not express a file cut short or a file that changed during the read, so the Mach-O readers either called those malformed or fell back to "not Mach-O". FatSliceRangeIssue.category carried the same two values into the load-command, encryption, hardening, IPS-join and Deno readers.

Structural fix

  • One Mach-O failure type. src/domain/apple/machoContainer.ts defines MachoReadFailure (TargetFailureOf<"malformed" | "truncated" | "unsupported" | "changed">), the macho format and one constructor per kind (machoFailure). FatSliceRangeIssue becomes FatSliceRangeFailure, and FatContainerIdentity reports { state: "failed", failure }.
  • Deleted: MachoReadIssue, the reader's machoIssue/machoIssueOf mappers over ParseFailureError, and the kind: "format" selection-failure tag (now "target"). The reader throws a module-private carrier and returns { status: "failed", failure } from readMachoContainer, readMachoImage, readSliceCommandTable and frameLoadCommands. MachoImageFacts and MachoEncryptionFacts carry the same failure.
  • The fix(macho)!: report a FAT header or table cut off by the file's end as truncated #14233 sibling cases:
    1. A FAT slice declared past the end of the file is truncated, with offset, field: fat_arch[N] and extent: { availableBytes, requiredBytes }.
    2. readMachoContainer reports a magic-only file shorter than 8 bytes as truncated, and a FAT header or table past the end as truncated with the FAT reader's extent, instead of "not Mach-O".
    3. A short read after the size was measured is changed: readMachoContainer's FAT re-read, the 8-byte header re-read, the hidden ARM64 row, readSliceCommandTable's header and load-command reads, and machoImageSelection's residual needs-data. Consumers that throw use readFailureError, which raises changed as an integrity read-coverage failure and every other kind as the owner's ParseFailureError.
    4. The whole-buffer readBinaryContainer FAT path labels its failure macho, not native-binary.
  • Consumers read the fact: hardening, encryption, IPS join, Deno location, Electron fuses, the dylib resolver, MachOSliceArtifactReader (changed becomes read-coverage, other failures layout-consistency), native inspection, Apple dispatch metadata and IL2CPP.

Design notes

  1. The owner measures, so the owner names the kind. Only the container and slice readers know the measured size, so they decide truncated versus changed, and consumers never reinterpret detail text.
  2. Published enums keep their shape. trace_dylib_resolution's parse_status stays parsed | malformed | unsupported: a truncated or changed image reports malformed there, with the owner's description in reason. Adding values would change an advertised schema; I left that for a separate decision.
  3. The JVM CAFEBABE rule is unchanged. A count that reads as a class-file version stays not FAT.

Tests

  • MachoLoadCommandReader.test.ts: a FAT table cut off reports truncated with { availableBytes: 20, requiredBytes: 48 }; a magic-only file is truncated; the same four bytes from a file measured at 64 bytes are changed. The existing expectations assert failure.kind, and slice-past-end and short-header cases now expect truncated.
  • Registry: readers/macho.ts adds macho-slice-past-eof (truncated, field: fat_arch[1]) for inspect_go_binary, inspect_rust_binary, inspect_native_initializers and inspect_dwarf_units, through CLI and MCP.
  • BinaryContainer.test.ts expects format: "macho" for the zero-count FAT header.

No per-command tests are removed in this PR.

Mutation checks (in-process from source): reporting a slice past the end as malformed fails all four macho-slice-past-eof registry cases; restoring the "truncated FAT table is not Mach-O" fallback fails the new container test. Both pass after revert.

Validation

  • npx vitest run src/domain/apple src/artifacts/apple src/native src/domain/native src/electron src/artifacts/deno src/il2cpp src/hopper: 3,888 passed.
  • All registry cases in-process through createCli and the MCP server pass, except the SQLite and managed cases that need dist/ or a deep-provider session.
  • Scoped tsc over every file that names the Mach-O readers, the selection, the dylib resolver and the binary container is clean apart from the pre-existing frida errors. Also clean: oxfmt, oxlint (no new warnings), architecture-guards.

Real-provider verification scope

Not run on a macOS host with dyld_info or Hopper. The affected Mach-O readers are local static parsers.

Since the merge with main

  • CI shard 8 (peResources.test.ts, expectAdapterErrorParity). The CLI recovery named the MCP tool (inspect_pe_resources) and tools/list. The cause was this branch's stale copy of src/cli/projectCliAnalysisResult.ts: the CLI spelling of the input-schema recovery (cliInputSchemaRemediation, built from renderInputSchemaRemediation at its one owner) landed in fix(cli)!: spell a target failure's recovery with CLI commands and options #14289's final squash, after this branch's last merge from it. It is not a main bug: the test passes on the merged tree, which takes that file unchanged from main. The merge resolves it, and the existing parity assertion is the regression test.
  • MACHO_FORMAT is imported from its owner, machoContainer.ts; the re-export from machoImageSelection.ts is deleted (Greptile thread).
  • ISO 9660 in the registry. readers/containers.ts adds inspect_artifact/iso9660-directory-cycle (malformed, field: extent_location) and inspect_artifact/iso9660-extent-cut-off (truncated, field: data_length). Deleted: the CLI test "reports a malformed ISO 9660 directory tree through the compiled CLI", which iso9660-directory-cycle covers through both adapters. Mutation: reporting a cut-off extent as malformed fails iso9660-extent-cut-off.
  • Short FAT re-reads (Greptile). A FAT table re-read shorter than the table, or a slice-magic re-read short of an in-file slice, now reports changed instead of not-mach-o. The length is checked before the bytes are parsed. Two new MachoLoadCommandReader.test.ts cases cover this; both fail on the previous source.
  • Tar's own carrier. The sweep of readers changed or added on main after the stack was built found one parallel vocabulary: TarStreamEnded, which had its own kind and detail. It now extends ParseFailureError and carries the gzip carrier's malformed or truncated TargetFailure (format: "gzip"). A gzip failure before the first tar block used to be renamed a malformed tar header; it is now refused with the carrier's own kind and format. Regression test in TarArtifactReader.test.ts (fails on the old rename). No other error class or reader on main carries its own target kind.

Zero-use search

grep -rnE 'AnalysisUnsupportedTargetError|AnalysisMalformedTargetError|MachoReadIssue|FatSliceRangeIssue|format_failure|reason\s*(:|===|!==)\s*["']format["']|"reason"\s*:\s*"format"|Failure\(\s*["']format["']\s*,' . over the final tree (excluding node_modules, dist, .git, docs/releases) matches only the guard's own pattern file (scripts/verify/retired-target-failure-vocabulary.mjs), its test (tests/evaluation/retiredTargetFailureVocabulary.test.ts) and two lines of the Migration section in docs/reference/target-failures.md. No other code, test, script or bridge uses any of them. node scripts/verify/architecture-guards.mjs passes across 3,123 source files.

Remaining cleanup

  • Hopper (HopperFileOffset.fatLayout, HopperMachOImage) and binaryTarget (validatedFatDeclarations, fatIdentityError) still return universal-container failures as strings (now the owner's detail). Typing them means changing their Result<_, string> callers across open-binary admission and Hopper's offset mapping; I left that for a follow-up rather than widen this PR.
  • The guard PR follows.

…conformance registry

Introduce one domain-owned TargetFailure value whose kind alone derives
the public code, category, retryability, recovery and details, for CLI
and MCP alike. Selected-file malformed and truncated refusals are the
first area on it: AnalysisMalformedTargetError is replaced by
AnalysisTargetFailureError, and ParseFailure's byte-structure variants
are TargetFailure variants rather than a parallel type.

The shared stableArtifactParserFailureCli loop is replaced by a
declarative registry (tests/support/targetFailure/readers/*.ts) and one
generated suite that runs every registered case through the CLI and MCP.

BREAKING CHANGE: selected-file malformed and truncated refusals add
details.failure_kind, and a truncated target's remediation now says to
re-acquire the complete file instead of choosing another target. Codes
are unchanged. Affected operations: every operation that refuses a
selected file's malformed or truncated bytes, including the ELF, PE,
Mach-O, DWARF, Go, Rust, BEAM, pyc, devicetree, Apple IPS, kernel
module, binary hardening, managed PE/CLI and IL2CPP readers.
#14225 refuses a non-regular dyld input as ArtifactReaderFailure("path");
dylibFileLifetime still expected "format" and fails on main's shard 9.
stableArtifact expected "format" for an impossible descriptor byte count
(now io) and an invalid chunk size (now InternalInvariantError);
directoryArtifactReaderOpen expected "format" for a non-file entry (now
path, the same change as #14238). All three fail on main.
…cated targets

Delete the ambiguous `format` reason from ArtifactReaderFailure and
ArtifactOperationError. Each container reader now raises its owner's
fact once, through malformedArtifact / truncatedArtifact, with format,
offset, field and measured extents. Short reads inside a measured extent
are read-coverage integrity failures, path-kind refusals are `path`,
foreign or recovery-requiring inputs are `unsupported`, host tool output
is `io`, and REA defects are InternalInvariantError.

The trace, NTFS journal, release exposure, web capture, native macOS and
web artifact adapters project the reader's parsed facts as
AnalysisTargetFailureError instead of invalid_request. Inventory
malformed, truncated, unsupported and cancelled reasons take their code
from the TargetFailure projection table, so a truncated container is
unsupported_target with failure_kind "truncated" on both paths.

BREAKING CHANGE: inventory_artifact, inspect_artifact, extract_artifact,
analyze_javascript_application, inspect_desktop_application,
inspect_keyed_archive, inspect_asset_catalog, inspect_nuget_nupkg,
trace_dylib_resolution, trace_web_module_imports and
trace_web_source_location report damaged container bytes as
unsupported_target (details.reason "malformed" or "truncated", with
failure_kind and format) instead of artifact_operation_failed with
reason "format", and a truncated container as unsupported_target instead
of truncated. inspect_playwright_trace, inspect_ntfs_journal,
audit_release_exposure, the web capture inspection operations and the
caller-selected import and source maps report damaged selected bytes as
unsupported_target instead of invalid_request. The `format` reason no
longer appears in details.reason.
…get failures

The SQLite engine's `format` reason is renamed to `malformed` at its
owner (SQLITE_INSPECTION_REASONS), and its refusal becomes an
AnalysisTargetFailureError at the selected path with format "sqlite".
The pwntools and EVM worker replies keep their wire reason "format",
which their workers define, and the adapters translate it once into a
malformed target failure with the profile's format (elf, elf-core,
evm-bytecode) instead of an invalid_format argument issue. SQLite joins
the target-failure conformance registry.

BREAKING CHANGE: inspect_sqlite_database, inspect_binary_layout,
inspect_recorded_crash and inspect_evm_interface report a selected
file's malformed bytes as unsupported_target with details.failure_kind
"malformed", format_failure, format and path, instead of invalid_request
with an invalid_format issue on path.
… reference page

artifact_integrity_mismatch's projection schema requires declared and
calculated digests, which a TargetFailure of kind integrity does not
carry, so the kind now projects artifact_operation_failed with category
integrity_mismatch. The model test validates every kind's projection
against analysisErrorProjectionSchema. The reference page joins the
documentation sidebar.
…odel

# Conflicts:
#	tests/boundary/filesystem/stableArtifact.test.ts
…p unsupported desktop probes local

A Bun or Node SEA short read inside a range already checked against the
measured size meant the file changed, not that it was truncated. The
carrier range reader and Bun's readExact now raise read-coverage
integrity for it, and keep 'outside the file' as the truncated case.
DesktopFileInspection records an unsupported managed-metadata probe as a
row issue again, so later file checks still run.
…ly suites

The literal-replacement scenario now reads the failure's detail instead
of an issues[] message, and a malformed reply wrapped by cleanup failure
reports category unsupported_target.
…d drop their per-command copies

The non-MZ PE imports and load-config cases (PE32/PE32+, ZZ and high-bit
signatures) and the truncated Apple IPS body move into the conformance
registry, which runs them through the CLI and MCP and now also checks
that a refusal leaves the selected file unchanged. The per-command tests
keep only their valid-image controls.
…ce registry covers

inspect_sqlite_database/not-a-database in the target-failure registry runs
the same non-SQLite bytes through the CLI and MCP, asserts the malformed
target facts and checks the selected file is unchanged.
…etry from it

Apply the owner review on #14239 to the TargetFailure model:
- remove details.format_failure; failure_kind is the only identifier;
- give integrity, conflict and io their own codes
  (target_integrity_mismatch, input_conflict, host_io_failed) and derive
  inventory malformed, truncated and unsupported codes from the same table;
- add a retry hint (none, backoff, after_change) derived from the kind,
  with io refined by its transient errno fact; retryable stays the
  unchanged-retry flag and is true exactly for backoff;
- rename the limit-cut result code and category truncated to partial;
- drop cancelled and resource from the target kinds and spell
  identifiers in American English (unrecognized);
- return a target failure a tool handler throws as a projected isError
  result instead of letting the SDK flatten it to text.

BREAKING CHANGE: details.format_failure is removed (read
details.failure_kind). The truncated result code and category are now
partial. Target integrity failures report target_integrity_mismatch,
host read failures host_io_failed and disagreeing inputs input_conflict.
Inventory operations (inventory_artifact, inspect_artifact,
extract_artifact and the other inventory callers) report truncated
container bytes as unsupported_target. Every target failure carries a
top-level retry hint.
…rget-failures

# Conflicts:
#	docs/reference/target-failures.md
#	src/domain/analysisErrorClassification.ts
#	src/resources/ArtifactOperationFailure.test.ts
#	tests/boundary/cli/artifactZstandardWindow.test.ts
…F declarations apart

PyInstaller reads inside the measured size, and .NET bundle manifest
refills, now raise read-coverage integrity on a zero-byte read instead of
truncated. A .NET bundle field and a Godot PCK directory entry that extend
past the file are truncated (with offset and extents) instead of
malformed. An absent or invalid ASAR packed offset is malformed; only a
valid range past the archive is truncated. The .NET manifest string
offset is reported in file coordinates.
The layout and recorded-crash workers raise a distinct truncated reason
when the file ends inside the ELF identification or header, and the
decoder projects it as failure_kind truncated instead of inferring it
from the message.
…as target failures

Managed readers interpret an issue code once, in managedIssueTargetFailure:
a coverage gap is an unsupported target, every other rule violation is a
malformed target, and the inventory metadata status is derived from that
same fact. managedInspectionTargetFailure now returns only
AnalysisTargetFailureError.

An IL2CPP binary that parses but does not link to its metadata is a
conflict target failure that lists both inputs and blames neither, in
place of an invalid_request with two issue entries. Metadata version 108
is an unsupported target. The CLI spells each conflict input's field by
the command's option name.

BREAKING CHANGE: inspect_managed_artifact, inspect_managed_members,
inspect_managed_native_boundaries and the managed comparison operations
report unsupported metadata or signature forms as an
AnalysisTargetFailureError (failure_kind unsupported, format pe-cli,
field, offset) instead of a bare unsupported target. inspect_il2cpp_metadata
reports a binary/metadata pair that does not link as code input_conflict
with failure_kind conflict and details.inputs, instead of invalid_request
with details.issues, and metadata version 108 with failure_kind
unsupported.
…odel

# Conflicts:
#	src/domain/analysisErrorProjection.ts
#	src/domain/parseFailure.ts
#	tests/acceptance/stableArtifactParserFailureCli.test.ts
#	tests/boundary/cli/managedMemberComparisonCli.test.ts
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

Base automatically changed from fix/target-failure-adapter-recovery to main November 25, 2026 05:19
…ure-kinds

# Conflicts:
#	docs/reference/target-failures.md
#	src/application/WebScriptExportService.ts
#	src/artifacts/apple/KeyedArchiveReader.ts
#	src/cli/projectCliAnalysisResult.ts
#	src/domain/apple/machoSliceSelection.ts
#	src/native/NativeMacOSProvider.ts
#	src/providers/offlineArtifactFailure.ts
#	src/resources/ArtifactReader.ts
#	src/resources/index.ts
#	tests/acceptance/binaryHardeningCli.test.ts
#	tests/acceptance/iso9660Cli.test.ts
#	tests/boundary/cli/desktopApplicationCli.test.ts
#	tests/boundary/mcp/analysisViewMcp.test.ts
…tecture guards (#14417)

* fix(errors)!: reject retired target-failure vocabularies in the architecture guards

The stack replaced every parallel vocabulary for why a target could not be
read with the TargetFailure model. The architecture guards now fail when
any retired carrier or spelling returns in src, tests, scripts or the
Python bridges: AnalysisUnsupportedTargetError, AnalysisMalformedTargetError,
MachoReadIssue, FatSliceRangeIssue, details.format_failure, and a "format"
failure reason in TypeScript or on a worker wire.

The ESP image decoder's own failure kind "format" becomes "malformed", and
the tests that asserted format_failure is absent are removed: the guard
covers that.

BREAKING CHANGE: no public field changes here; this completes the #14239
migration's removal of the retired reason vocabularies.

* fix(errors): reject a "format" failure-kind union and test the vocabulary guard's patterns
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

…the conformance registry

The directory-cycle CLI test is replaced by the registry case
inspect_artifact/iso9660-directory-cycle, which checks the same refusal
through CLI and MCP.
… kind at offset zero

TarStreamEnded had its own kind and detail fields beside the model. It is
now a ParseFailureError carrying the gzip carrier's malformed or truncated
TargetFailure. A carrier failure before the first tar block is refused with
that failure (format gzip) instead of being renamed a malformed tar header.
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@morluto
morluto merged commit 5b79ae5 into main Nov 25, 2026
59 checks passed
@morluto
morluto deleted the fix/macho-target-failure-kinds branch November 25, 2026 14:23
morluto added a commit that referenced this pull request Nov 25, 2026
#14281 moved dyld_info's file-type refusal onto the TargetFailure model.
The supported forms now appear in the refusal reason, and recovery comes
from the shared target-failure table, so remediation no longer says
"linked Mach-O". The test still pinned that wording and failed on main;
CI did not select it for #14281 or #14416.

It now asserts the facts the model owns: failure_kind unsupported, format
macho, field filetype, retry none, and the reason naming the linked
executables and relocatable objects dyld_info reads.
@morluto morluto added area: native Native analysis and decompilation, including Ghidra, IDA, and Hopper analysis behavior bug Something isn't working labels Nov 26, 2026
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 bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants