diff --git a/docs/guides/managed/managed-code-analysis.md b/docs/guides/managed/managed-code-analysis.md index 0d1c451569..e3fe4a3796 100644 --- a/docs/guides/managed/managed-code-analysis.md +++ b/docs/guides/managed/managed-code-analysis.md @@ -523,10 +523,15 @@ When the selected source changes during acquisition or no longer matches its admitted digest, inspection and comparison report retryable `artifact_changed`; any completed hash retains the observed digest and byte count. Retry against a stable source. This differs from corrupted retained Evidence, which remains an -Evidence-integrity failure. Malformed selected PE input has the same input-format -classification in inspection and comparison. Its issue identifies the selected -filename and argument: `path` for inspection, or `leftPath` / `rightPath` for CLI -comparison. A failed right-side comparison retains the completed left observation. +Evidence-integrity failure. Malformed selected PE/CLI bytes are a target refusal, +not an input error, in inspection and comparison: `unsupported_target` with +`details.format` `pe-cli`, `details.format_failure` `malformed`, and +`details.path` naming the file whose bytes are at fault, so a comparison names +the malformed side by its own path. `details.field` and `details.offset` give +the reader's structure and byte offset when known. The arguments are not at +fault, so no input recovery is offered. A metadata layout or signature form +outside decoder coverage is `unsupported_target` without `format_failure`. A +failed right-side comparison retains the completed left observation. ## Member comparison diff --git a/docs/guides/native/go-binaries.md b/docs/guides/native/go-binaries.md index 432a8a055a..534dab3cd7 100644 --- a/docs/guides/native/go-binaries.md +++ b/docs/guides/native/go-binaries.md @@ -195,6 +195,16 @@ declaration, such as a different CPU subtype, is listed as unverified, and no value is offered for it. `architecture` on any other image is rejected rather than ignored. +A damaged universal file is a target refusal, not a request to correct: +overlapping slices, a slice range outside the file, or a selected slice whose +header disagrees with its FAT entry return `unsupported_target` with +`details.format` `macho`, `details.format_failure` `malformed` (`truncated` +when the selected slice ends inside its Mach-O header), and `details.path` +naming the universal file. A FAT form outside REA's coverage, such as an +alignment exponent above 52, is `unsupported_target` without +`format_failure`. The same rules apply to `inspect_rust_binary`, +`inspect_dwarf_units` and `inspect_native_initializers`. + For ELF images without a named build-info section, discovery checks each nonempty writable, non-executable load segment in program-header order. This includes sectionless PIE images with metadata in a later data segment. Named diff --git a/docs/il2cpp-metadata.md b/docs/il2cpp-metadata.md index 2fb59d32fa..d211ed6ba0 100644 --- a/docs/il2cpp-metadata.md +++ b/docs/il2cpp-metadata.md @@ -156,8 +156,8 @@ identity. Slices are selected as for the other native inspectors: a CPU family with one slice is read by its family name, and when several slices share a family the value must name one slice's subtype exactly, so `arm64` reads the `arm64` slice beside an `arm64e` one. Selection problems are invalid -`binary_architecture` requests, and a damaged FAT table is an invalid -`binary_path`. `arm64e` is not a `binary_architecture` value: when the +`binary_architecture` requests, and a damaged FAT table or slice is a +malformed target at the binary's path (see [failures](#failures)). `arm64e` is not a `binary_architecture` value: when the intended slice is the only arm64e slice among several arm64-family slices, use `lipo -info` to enumerate exact subtypes on macOS, extract the slice into a separate file, for example `lipo universal -thin arm64e -output thin-arm64e`, @@ -465,20 +465,36 @@ Il2CppType byref flag in different bits, so a rendered name could gain or lose | --------------------------------------- | ----------- | ------------------------------------------------------------------------------------------------------------ | | `unsupported-container` | unsupported | Not a 64-bit little-endian Mach-O, PE or ELF image (ELF: AArch64 or x86-64 with dynamic section). | | `unsupported-pointer-encoding` | unsupported | Mach-O chained fixups or Android packed (APS2) ELF relocations; pointers not decoded. | -| `malformed-container` | input error | The container headers are damaged. | -| `code-gen-modules-not-found` | input error | An image has no module record; often a binary from a different build. | -| `ambiguous-code-gen-module` | input error | More than one module record matches an image. | -| `code-registration-not-found` | input error | No unique module table or executable-byte array candidate was resolved. | -| `invalid-method-token` | input error | A token is outside its module's method-pointer rows, or a MethodDef row is reused within one image. | -| `invalid-method-pointer` | input error | A slot is unavailable or its nonzero address lacks unambiguous executable file coverage. | -| `metadata-registration-not-found` | input error | No single MetadataRegistration or code-loaded type-table candidate was resolved. | -| `invalid-type` | input error | A type index or `Il2CppType` record is out of range, unmapped or malformed. | +| `malformed-container` | malformed | The container headers are damaged. | +| `code-gen-modules-not-found` | conflict | An image has no module record; often a binary from a different build. | +| `ambiguous-code-gen-module` | conflict | More than one module record matches an image. | +| `code-registration-not-found` | conflict | No unique module table or executable-byte array candidate was resolved. | +| `invalid-method-token` | conflict | A token is outside its module's method-pointer rows, or a MethodDef row is reused within one image. | +| `invalid-method-pointer` | conflict | A slot is unavailable or its nonzero address lacks unambiguous executable file coverage. | +| `metadata-registration-not-found` | conflict | No single MetadataRegistration or code-loaded type-table candidate was resolved. | +| `invalid-type` | conflict | A type index or `Il2CppType` record is out of range, unmapped or malformed. | | `unsupported-type-kind` | unsupported | A valid type kind has no implemented rendering. | | `generic-methods-unsupported` | unsupported | Generic instances were requested for metadata version 24 or 39, or a build lacks either static registration. | -| `generic-method-registration-not-found` | input error | No CodeRegistration layout bounds every genericMethodTable row, or the generic tables are unreadable. | -| `ambiguous-generic-method-registration` | input error | More than one CodeRegistration layout bounds every genericMethodTable row. | +| `generic-method-registration-not-found` | conflict | No CodeRegistration layout bounds every genericMethodTable row, or the generic tables are unreadable. | +| `ambiguous-generic-method-registration` | conflict | More than one CodeRegistration layout bounds every genericMethodTable row. | -Format failures name `binary_path` and slice-selection failures name `binary_architecture`; capacity refusals remain typed resource errors whose `reported_limits` name the exceeded budget (`boundary`, the capacity reason) and its `maximum`, with `details.refusal.unit` naming the unit the budget counts (`"entries"`, `"bytes"` or `"frames"`). Failed linking preserves the metadata source identity, validated counts, selected binary path/architecture and its SHA-256 when observed, plus prior producer observations. It never publishes an incomplete native table as complete. The binary input is bounded to 1 GiB. The virtual-pointer index has the same 1 GiB estimated representation allowance ([#14175](https://github.com/morluto/rea/issues/14175) reports a real Unity 6 arm64 build that exceeds it), reserving 2 KiB per distinct virtual destination before insertion for retained Maps and finish-time lookup storage. Repeated declarations of one destination share that reservation. This conservative allocation accounting is separate from actual process RSS and the report allowance; exhaustion returns a typed `native-index-capacity` refusal before another destination is retained. +Each category says which selected file is at fault: + +- **unsupported**: an `unsupported_target` refusal whose `details.path` is + `binary_path`. The binary's form is outside coverage. +- **malformed**: an `unsupported_target` refusal with `details.format_failure` + `malformed` or `truncated`, whose `details.path` is `binary_path`. The + binary's own bytes are damaged. A damaged universal Mach-O container, + including a slice that ends inside its header or disagrees with its FAT + table entry, is reported the same way with `details.format` `macho`. +- **conflict**: both files parsed but do not agree. They may come from + different builds, either file may be damaged, or the binary's registration + layout may be outside coverage; nothing establishes which. The refusal is an + `invalid_request` with an `invalid_value` issue for each of `path` and + `binary_path` (`--binary` in the CLI) and no `inspect_input_contract` + recovery. Neither file is called malformed. + +Slice-selection failures name `binary_architecture`: an architecture the universal file does not hold, an ambiguous one, or one given for a thin file. A metadata failure found while linking names the metadata's path, not the binary's. Capacity refusals remain typed resource errors whose `reported_limits` name the exceeded budget (`boundary`, the capacity reason) and its `maximum`, with `details.refusal.unit` naming the unit the budget counts (`"entries"`, `"bytes"` or `"frames"`). Failed linking preserves the metadata source identity, validated counts, selected binary path/architecture and its SHA-256 when observed, plus prior producer observations. It never publishes an incomplete native table as complete. The binary input is bounded to 1 GiB. The virtual-pointer index has the same 1 GiB estimated representation allowance ([#14175](https://github.com/morluto/rea/issues/14175) reports a real Unity 6 arm64 build that exceeds it), reserving 2 KiB per distinct virtual destination before insertion for retained Maps and finish-time lookup storage. Repeated declarations of one destination share that reservation. This conservative allocation accounting is separate from actual process RSS and the report allowance; exhaustion returns a typed `native-index-capacity` refusal before another destination is retained. Scans yield cooperatively in bounded batches. Name-address retention and reverse-trie construction are each limited to 65,536 entries/nodes and fallback module-array candidates to 64 (`native-index-capacity`); exceeding capacity does not prove absence. Rendered type text has a 64 MiB UTF-8 cache-workspace guard, separate from the 64 MiB encoded-report admission, and 64 nested rendering frames (`native-type-text-capacity` / `type-nesting-capacity`). Genuine cycles are malformed; unsupported type kinds are explicit coverage failures. Native row/text admission runs before allocation or retention. Unused generic parameter names are read on demand from the same stable metadata snapshot. There is no cross-inspection file cache; validated immutable Evidence is reused for session views. @@ -538,8 +554,11 @@ A file whose magic is not `0xFAB11BAF` fails as an unsupported target with A version other than 24, 27, 29, 31 or 39 fails as an unsupported target with `unsupported-version`. -Damaged metadata returns an input error (`invalid_format`) whose -message names one reason: +Damaged metadata is refused as a malformed target: an `unsupported_target` +refusal whose `details.path` is the metadata file, `details.format` is +`il2cpp-metadata`, `details.format_failure` is `truncated` for +`truncated-header` and `malformed` otherwise, and `details.reason` names one +reason. The request is not at fault, so no input recovery is offered: | Reason | Meaning | | ------------------------- | ---------------------------------------------------------------------------------------------------------------- | diff --git a/src/domain/apple/machoImageSelection.ts b/src/domain/apple/machoImageSelection.ts index 9f90a067c9..47c47f6343 100644 --- a/src/domain/apple/machoImageSelection.ts +++ b/src/domain/apple/machoImageSelection.ts @@ -1,12 +1,14 @@ import { err, ok, type Result } from "../result.js"; import { BinaryReader } from "../binaryContainer.js"; +import type { ParseFailure } from "../parseFailure.js"; import { classifyFatContainerEvidence, fatSliceOverlapReason, findOverlappingFatSlices, + inspectFatSliceRange, readFatContainerHeader, readMachoHeaderPrefixFacts, - validateFatSlice, + validateFatSliceIdentity, type FatContainerHeader, type FatSliceDeclaration, type MachoHeaderPrefixFacts, @@ -14,11 +16,71 @@ import { import type { ByteSource } from "../byteSource.js"; type UniversalMachoHeader = Extract; -interface MachoImageSelectionFailure { - readonly kind: "malformed"; + +/** The ParseFailure format of a Mach-O image and its universal container. */ +export const MACHO_FORMAT = "macho"; + +/** What the container reader established about the universal file's bytes. */ +export type MachoContainerFailure = Extract< + ParseFailure, + { readonly kind: "malformed" | "truncated" | "unsupported" } +>; + +/** + * The universal file's own format failure, raised once here. `failure.kind` + * is truncated only where this reader measured bytes ending inside a + * structure, unsupported where the container reader classified the form as + * outside coverage, and malformed otherwise. `message` is the failure's detail. + */ +export interface MachoImageSelectionFailure { + readonly kind: "format"; readonly message: string; + readonly failure: MachoContainerFailure; } +const containerFailure = ( + kind: MachoContainerFailure["kind"], + detail: string, + offset?: number, +): MachoImageSelectionFailure => { + const at = offset === undefined ? {} : { offset }; + return { + kind: "format", + message: detail, + failure: + kind === "unsupported" + ? { kind, format: MACHO_FORMAT, detail, undecodedContent: false, ...at } + : { kind, format: MACHO_FORMAT, detail, ...at }, + }; +}; + +/** + * Check one selected declaration against its slice's observed header prefix. + * The table entry and the slice header are two records in the same file, so + * their disagreement breaks the container's own rule: malformed, never the + * caller's selection. + */ +const sliceFailure = ( + slice: FatSliceDeclaration, + containerSize: number, + tableEnd: number, + prefix: MachoHeaderPrefixFacts, +): MachoImageSelectionFailure | null => { + const range = inspectFatSliceRange(slice, containerSize, tableEnd); + if (range !== null) + return containerFailure(range.category, range.reason, slice.offset); + if (prefix.identity === null) + return containerFailure( + "truncated", + `FAT architecture ${slice.index} has a truncated Mach-O identity`, + slice.offset, + ); + const mismatch = validateFatSliceIdentity(slice, prefix.identity); + return mismatch === null + ? null + : containerFailure("malformed", mismatch, slice.offset); +}; + /** * Admit a complete in-memory universal image whose slices do not overlap; * FAT-shaped JVM data remains unselected. @@ -29,23 +91,21 @@ export const readUniversalMachoImage = ( const fat = readFatContainerHeader(bytes, bytes.byteLength); if (fat.state === "not-fat") return ok(null); if (fat.state !== "parsed") - return err({ - kind: "malformed", - message: - fat.state === "malformed" - ? fat.reason - : "Universal Mach-O header is truncated", - }); + return err( + fat.state === "malformed" + ? containerFailure("malformed", fat.reason) + : containerFailure("truncated", "Universal Mach-O header is truncated"), + ); const identity = classifyFatContainerEvidence(fat, bytes); if (identity.state === "malformed") - return err({ kind: "malformed", message: identity.reason }); + return err(containerFailure(identity.category, identity.reason)); if (identity.state !== "mach-o") return ok(null); // Every range is valid here; aliased declarations are a malformed container, // as the artifact reader also rules, not slices to choose between. const overlap = findOverlappingFatSlices(fat.slices); return overlap === null ? ok(fat) - : err({ kind: "malformed", message: fatSliceOverlapReason(overlap) }); + : err(containerFailure("malformed", fatSliceOverlapReason(overlap))); }; /** Validate the selected declaration against the complete embedded CPU identity. */ @@ -55,12 +115,13 @@ export const readUniversalMachoSlice = ( slice: FatSliceDeclaration, ): Result => { const image = bytes.subarray(slice.offset, slice.offset + slice.size); - const identity = readMachoHeaderPrefixFacts(image).identity; - const message = - identity === null - ? `FAT architecture ${slice.index} has a truncated Mach-O identity` - : validateFatSlice(slice, bytes.length, header.tableEnd, identity); - return message === null ? ok(image) : err({ kind: "malformed", message }); + const failure = sliceFailure( + slice, + bytes.length, + header.tableEnd, + readMachoHeaderPrefixFacts(image), + ); + return failure === null ? ok(image) : err(failure); }; const readSourceSlice = ( @@ -113,13 +174,11 @@ export const readUniversalMachoImageFromReader = async ( } } if (fat.state !== "parsed") - return err({ - kind: "malformed", - message: - fat.state === "malformed" - ? fat.reason - : "Universal Mach-O header is truncated", - }); + return err( + fat.state === "malformed" + ? containerFailure("malformed", fat.reason) + : containerFailure("truncated", "Universal Mach-O header is truncated"), + ); if (tableBytes.length < fat.tableEnd) tableBytes = await readSourceSlice(source, 0, fat.tableEnd); const sliceHeadersByOffset = new Map(); @@ -142,12 +201,12 @@ export const readUniversalMachoImageFromReader = async ( sliceHeadersByOffset, ); if (identity.state === "malformed") - return err({ kind: "malformed", message: identity.reason }); + return err(containerFailure(identity.category, identity.reason)); if (identity.state !== "mach-o") return ok(null); const overlap = findOverlappingFatSlices(fat.slices); return overlap === null ? ok({ header: fat, tableBytes: tableBytes.subarray(0, fat.tableEnd) }) - : err({ kind: "malformed", message: fatSliceOverlapReason(overlap) }); + : err(containerFailure("malformed", fatSliceOverlapReason(overlap))); }; /** Validate one FAT slice by reading only its 16-byte Mach-O header prefix. */ @@ -161,10 +220,11 @@ export const validateUniversalMachoSliceFromReader = async ( slice.offset, Math.min(16, slice.size), ); - const identity = readMachoHeaderPrefixFacts(prefix).identity; - const message = - identity === null - ? `FAT architecture ${slice.index} has a truncated Mach-O identity` - : validateFatSlice(slice, source.size, header.tableEnd, identity); - return message === null ? ok(undefined) : err({ kind: "malformed", message }); + const failure = sliceFailure( + slice, + source.size, + header.tableEnd, + readMachoHeaderPrefixFacts(prefix), + ); + return failure === null ? ok(undefined) : err(failure); }; diff --git a/src/domain/apple/machoSliceSelection.ts b/src/domain/apple/machoSliceSelection.ts index c5f5c65126..2fcaf454c6 100644 --- a/src/domain/apple/machoSliceSelection.ts +++ b/src/domain/apple/machoSliceSelection.ts @@ -3,6 +3,7 @@ import { readUniversalMachoImageFromReader, readUniversalMachoSlice, validateUniversalMachoSliceFromReader, + type MachoImageSelectionFailure, } from "./machoImageSelection.js"; import { readMachoHeaderPrefixFacts, @@ -15,7 +16,13 @@ import { type MachoSliceArchitecture, type MachoTargetSelection, } from "./machoTargetSelection.js"; -import { AnalysisInputError } from "../analysisErrorCore.js"; +import { + AnalysisInputError, + AnalysisMalformedTargetError, + AnalysisUnsupportedTargetError, +} from "../analysisErrorCore.js"; +import type { AnalysisError } from "../analysisErrorBase.js"; +import { ParseFailureError } from "../parseFailure.js"; import { err, ok, type Result } from "../result.js"; import { MACHO_ARCHITECTURE_POLICIES } from "./machoArchitectureSelection.js"; import { sha256Hex } from "../../kernel/sha256Hex.js"; @@ -43,19 +50,17 @@ export interface SelectedNativeImage { } /** - * The caller's input fields and spellings for a slice selection. Messages name - * selectors through `spelling`, and a selector without a spelling is never - * offered as a choice. + * The caller's architecture field and spellings for a slice selection. + * Messages name selectors through `spelling`, and a selector without a + * spelling is never offered as a choice. */ export interface SliceSelectionInput { - readonly pathField: string; readonly architectureField: string; readonly spelling: Readonly>>; } -/** The shared `path` and `architecture` inputs, spelled as the selector values. */ +/** The shared `architecture` input, spelled as the selector values. */ export const SHARED_SLICE_SELECTION_INPUT: SliceSelectionInput = { - pathField: "path", architectureField: "architecture", spelling: { x86: "x86", @@ -104,10 +109,42 @@ export interface MachoSliceSelectionRefusal { readonly message: string; } -/** Why no image could be selected: a refused request, or a malformed container. */ +/** + * Why no image could be selected: a refused request, or the universal + * file's own format failure. + */ export type MachoSliceSelectionFailure = | MachoSliceSelectionRefusal - | { readonly kind: "malformed"; readonly message: string }; + | MachoImageSelectionFailure; + +/** + * The public refusal for a failed architecture selection. A refused request + * is the caller's `architecture` value; a format failure belongs to the + * selected file's bytes, so it is a malformed or unsupported target at + * `path`, never an invalid `path` argument. + */ +const selectionError = ( + operation: string, + path: string, + failure: MachoSliceSelectionFailure, + input: SliceSelectionInput, +): AnalysisError => { + if (failure.kind !== "format") + return new AnalysisInputError(operation, undefined, [ + { + path: [input.architectureField], + reason: "invalid_value", + message: failure.message, + }, + ]); + const parsed = failure.failure; + const cause = new ParseFailureError(parsed); + return parsed.kind === "unsupported" + ? new AnalysisUnsupportedTargetError(operation, path, parsed.detail, { + cause, + }) + : new AnalysisMalformedTargetError(operation, path, parsed, { cause }); +}; interface FatSlice { readonly cpuType: number; @@ -425,31 +462,11 @@ export const requireSelectedNativeImageFromReader = async ( architecture: MachoSliceArchitecture | undefined, input: SliceSelectionInput = SHARED_SLICE_SELECTION_INPUT, ): Promise => { - const container = await readUniversalMachoImageFromReader(source); - if (!container.ok) { - throw new AnalysisInputError(operation, undefined, [ - { - path: [input.pathField], - reason: "invalid_format", - message: `Selected artifact ${path}: ${container.error.message}`, - }, - ]); - } const failSelection = (failure: MachoSliceSelectionFailure): never => { - throw new AnalysisInputError(operation, undefined, [ - failure.kind !== "malformed" - ? { - path: [input.architectureField], - reason: "invalid_value", - message: failure.message, - } - : { - path: [input.pathField], - reason: "invalid_format", - message: `Selected artifact ${path}: ${failure.message}`, - }, - ]); + throw selectionError(operation, path, failure, input); }; + const container = await readUniversalMachoImageFromReader(source); + if (!container.ok) return failSelection(container.error); const parsed = container.value; const steps = selectArchitectureSliceSteps( parsed?.header ?? null, @@ -493,9 +510,9 @@ export const requireSelectedNativeImageFromReader = async ( }; /** - * Select the image for one inspection, or fail with the input to correct: - * the architecture field for a missing or mismatched selection, the path field - * for a malformed universal container. + * Select the image for one inspection, or fail: the architecture field for a + * missing or mismatched selection, and a malformed, truncated or unsupported + * target at `path` for the universal file's own format failure. */ export const requireSelectedNativeImage = ( operation: string, @@ -510,14 +527,5 @@ export const requireSelectedNativeImage = ( input, }); if (selected.ok) return selected.value; - const { kind, message } = selected.error; - throw new AnalysisInputError(operation, undefined, [ - kind !== "malformed" - ? { path: [input.architectureField], reason: "invalid_value", message } - : { - path: [input.pathField], - reason: "invalid_format", - message: `Selected artifact ${path}: ${message}`, - }, - ]); + throw selectionError(operation, path, selected.error, input); }; diff --git a/src/domain/managed/managedReaderFailure.test.ts b/src/domain/managed/managedReaderFailure.test.ts new file mode 100644 index 0000000000..7e47a63c7a --- /dev/null +++ b/src/domain/managed/managedReaderFailure.test.ts @@ -0,0 +1,82 @@ +import { describe, expect, it } from "vitest"; + +import { + AnalysisMalformedTargetError, + AnalysisUnsupportedTargetError, +} from "../analysisErrorCore.js"; +import { projectAnalysisError } from "../analysisErrorProjection.js"; +import { + managedFailure, + managedInspectionTargetFailure, +} from "./managedReaderFailure.js"; + +const OPERATION = "inspect_managed_members"; +const PATH = "/fixture.dll"; + +describe("managedInspectionTargetFailure", () => { + it("refuses a broken PE/CLI rule as a malformed target with the reader's location", () => { + const failure = managedInspectionTargetFailure( + OPERATION, + PATH, + managedFailure( + "invalid-directory", + "pe.section-data", + "pe.section-data leaves the artifact byte range", + 0x2000, + ), + ); + expect(failure).toBeInstanceOf(AnalysisMalformedTargetError); + expect(projectAnalysisError(failure!)).toMatchObject({ + code: "unsupported_target", + retryable: false, + details: { + operation: OPERATION, + path: PATH, + format_failure: "malformed", + format: "pe-cli", + field: "pe.section-data", + offset: 0x2000, + reason: "pe.section-data leaves the artifact byte range", + }, + }); + expect(projectAnalysisError(failure!)).not.toHaveProperty("recovery"); + }); + + it("omits an unknown offset rather than inventing one", () => { + const failure = managedInspectionTargetFailure( + OPERATION, + PATH, + managedFailure("invalid-tables", "metadata.tables", "bad table"), + ); + expect(failure).toBeInstanceOf(AnalysisMalformedTargetError); + expect( + (failure as AnalysisMalformedTargetError).failure, + ).not.toHaveProperty("offset"); + }); + + it.each(["unsupported-metadata", "unsupported-signature"] as const)( + "keeps %s outside decoder coverage unsupported, never malformed", + (code) => { + const failure = managedInspectionTargetFailure( + OPERATION, + PATH, + managedFailure(code, "metadata.tables", "a newer layout"), + ); + expect(failure).toBeInstanceOf(AnalysisUnsupportedTargetError); + expect(failure).toMatchObject({ path: PATH, reason: "a newer layout" }); + }, + ); + + it("leaves a resource limit and foreign causes to their producers", () => { + expect( + managedInspectionTargetFailure( + OPERATION, + PATH, + managedFailure("resource-limit", "metadata.tables", "budget"), + ), + ).toBeUndefined(); + expect( + managedInspectionTargetFailure(OPERATION, PATH, new Error("io")), + ).toBeUndefined(); + }); +}); diff --git a/src/domain/managed/managedReaderFailure.ts b/src/domain/managed/managedReaderFailure.ts index 31f3ddf6a2..bc4c4c8c58 100644 --- a/src/domain/managed/managedReaderFailure.ts +++ b/src/domain/managed/managedReaderFailure.ts @@ -1,4 +1,7 @@ -import { AnalysisInputError } from "../analysisErrorCore.js"; +import { + AnalysisMalformedTargetError, + AnalysisUnsupportedTargetError, +} from "../analysisErrorCore.js"; import type { ManagedParseIssue } from "./managedArtifact.js"; /** Header facts admitted before an unsupported table layout was identified. */ @@ -33,23 +36,46 @@ export const managedMetadataFailureStatus = ( ? "partial" : "malformed"; -/** Malformed selected metadata is input failure for every inspection workflow. */ -export const managedInspectionInputFailure = ( +/** The ParseFailure format of a managed PE/CLI image and its ECMA-335 metadata. */ +export const MANAGED_PE_CLI_FORMAT = "pe-cli"; + +/** + * The selected file's refusal when a managed reader stopped on its bytes. + * The issue code is the reader's own classification: a layout or signature + * form outside decoder coverage is an unsupported target, so a newer valid + * file is never called corrupt, and every other code names a rule the bytes + * broke, a malformed target. The request that selected the file is not at + * fault either way. A resource limit names a budget only its producer knows, + * so it and any other cause return `undefined`. + */ +export const managedInspectionTargetFailure = ( operation: string, path: string, cause: unknown, - inputField: "path" | "leftPath" | "rightPath" = "path", -): AnalysisInputError | undefined => - cause instanceof ManagedReaderFailure && - managedMetadataFailureStatus(cause.issue) === "malformed" - ? new AnalysisInputError(operation, { cause }, [ - { - path: [inputField], - reason: "invalid_format", - message: `Selected artifact ${path}: ${cause.issue.detail}`, - }, - ]) - : undefined; +): + | AnalysisMalformedTargetError + | AnalysisUnsupportedTargetError + | undefined => { + if (!(cause instanceof ManagedReaderFailure)) return undefined; + const { code, scope, offset, detail } = cause.issue; + if (code === "resource-limit") return undefined; + if (code === "unsupported-metadata" || code === "unsupported-signature") + return new AnalysisUnsupportedTargetError(operation, path, detail, { + cause, + }); + return new AnalysisMalformedTargetError( + operation, + path, + { + kind: "malformed", + format: MANAGED_PE_CLI_FORMAT, + detail, + field: scope, + ...(offset === null ? {} : { offset }), + }, + { cause }, + ); +}; /** Construct a typed managed parse failure at an exact byte location. */ export const managedFailure = ( diff --git a/src/domain/native/readBinaryContainer.ts b/src/domain/native/readBinaryContainer.ts index 57a6c12d48..c529d9ed0b 100644 --- a/src/domain/native/readBinaryContainer.ts +++ b/src/domain/native/readBinaryContainer.ts @@ -67,8 +67,13 @@ export const readBinaryContainerFromReader = async ( const fatPrefix = readFatHeaderPrefix(prefix); if (fatPrefix.state === "incomplete" || fatPrefix.state === "parsed") { const fat = await readUniversalMachoImageFromReader(source); - if (!fat.ok) - throw new BinaryFormatFailure("malformed", fat.error.message); + if (!fat.ok) { + const { kind, detail, offset } = fat.error.failure; + throw new BinaryFormatFailure(kind, detail, { + format: fat.error.failure.format, + ...(offset === undefined ? {} : { offset }), + }); + } if (fat.value !== null) throw new BinaryFormatFailure( "unsupported", diff --git a/src/dotnet/ManagedStaticProvider.ts b/src/dotnet/ManagedStaticProvider.ts index 606b1151e7..c48106c38b 100644 --- a/src/dotnet/ManagedStaticProvider.ts +++ b/src/dotnet/ManagedStaticProvider.ts @@ -41,7 +41,7 @@ import { inspectManagedArtifactBytes } from "./ManagedArtifactInspector.js"; import { inspectManagedMembersBytes } from "./ManagedMemberInspector.js"; import { inspectManagedNativeBoundariesBytes } from "./ManagedNativeBoundaryInspector.js"; import { RegularFileCleanupFailure } from "../filesystem/OwnedRegularFile.js"; -import { managedInspectionInputFailure } from "../domain/managed/managedReaderFailure.js"; +import { managedInspectionTargetFailure } from "../domain/managed/managedReaderFailure.js"; import { analysisInputErrorFromIssues } from "../domain/inputIssueProjection.js"; import type { z } from "zod"; import { @@ -167,12 +167,12 @@ class ManagedStaticClient implements AnalysisClient { if (cause instanceof AnalysisError) return err(cause); if (options?.signal?.aborted === true) return err(cancelledBy(operation, options.signal)); - const inputFailure = managedInspectionInputFailure( + const targetFailure = managedInspectionTargetFailure( operation, this.target.path, cause, ); - if (inputFailure !== undefined) return err(inputFailure); + if (targetFailure !== undefined) return err(targetFailure); return err( new ProviderAdapterError(MANAGED_STATIC_PROVIDER.id, operation, { cause, diff --git a/src/il2cpp/Il2cppBinaryFormat.ts b/src/il2cpp/Il2cppBinaryFormat.ts index 570b7b834b..081d33a54c 100644 --- a/src/il2cpp/Il2cppBinaryFormat.ts +++ b/src/il2cpp/Il2cppBinaryFormat.ts @@ -15,8 +15,15 @@ export const IL2CPP_BINARY_FAILURE_REASONS = { "type-nesting-capacity", "native-type-text-capacity", ], - malformed: [ - "malformed-container", + /** The binary's own container bytes break their format's rules. */ + malformed: ["malformed-container"], + /** + * The binary's container parsed, but its registration, pointers, tokens or + * types do not agree with the metadata. The pair may come from different + * builds, either file may be damaged, or the registration layout may be + * outside coverage, so no single file is established as at fault. + */ + linkConflict: [ "code-gen-modules-not-found", "ambiguous-code-gen-module", "code-registration-not-found", @@ -50,6 +57,12 @@ const isUnsupported = (reason: Il2cppBinaryFormatReason) => reason, ); +/** Whether a link failure is a disagreement between the two files, not one file's bytes. */ +export const isIl2cppLinkConflict = (reason: Il2cppBinaryFailureReason) => + (IL2CPP_BINARY_FAILURE_REASONS.linkConflict as readonly string[]).includes( + reason, + ); + /** * A native image REA cannot link, either outside coverage or inconsistent * with the metadata. The stable `reason` names the IL2CPP rule; a capacity diff --git a/src/il2cpp/Il2cppBinaryImage.ts b/src/il2cpp/Il2cppBinaryImage.ts index 765ff99b6d..a32604324a 100644 --- a/src/il2cpp/Il2cppBinaryImage.ts +++ b/src/il2cpp/Il2cppBinaryImage.ts @@ -39,9 +39,8 @@ import { IL2CPP_BINARY_BYTES, } from "./Il2cppBinaryFormat.js"; -/** Selection failures name the binary's inputs and IL2CPP's public spellings. */ +/** Selection failures name the binary's architecture input and IL2CPP's public spellings. */ const IL2CPP_SLICE_SELECTION_INPUT: SliceSelectionInput = { - pathField: "binary_path", architectureField: "binary_architecture", spelling: Object.fromEntries( Object.entries(IL2CPP_SLICE_SELECTORS).map(([publicName, selector]) => [ @@ -53,8 +52,9 @@ const IL2CPP_SLICE_SELECTION_INPUT: SliceSelectionInput = { /** * Select the thin image of the caller's binary: IL2CPP's `binary_architecture` - * maps onto the shared slice selector here, once, and a selection failure - * names `binary_architecture` or `binary_path`. + * maps onto the shared slice selector here, once. A refused selection names + * `binary_architecture`; a universal container format failure is a target + * refusal at the binary's own path. */ export const requireIl2cppBinaryImage = ( operation: string, @@ -187,7 +187,8 @@ export function* openImageSteps( // container's architecture names no CPU family this reader decodes. if (!selected.ok) throw new Il2cppBinaryFormatFailure( - selected.error.kind === "malformed" + selected.error.kind === "format" && + selected.error.failure.kind !== "unsupported" ? "malformed-container" : "unsupported-container", selected.error.message, diff --git a/src/il2cpp/Il2cppMetadataProvider.ts b/src/il2cpp/Il2cppMetadataProvider.ts index 27e602f16c..e3d42af2c8 100644 --- a/src/il2cpp/Il2cppMetadataProvider.ts +++ b/src/il2cpp/Il2cppMetadataProvider.ts @@ -3,9 +3,11 @@ import { Il2cppBinaryFormatFailure, IL2CPP_BINARY_BYTES, IL2CPP_BINARY_FORMAT, + isIl2cppLinkConflict, } from "./Il2cppBinaryFormat.js"; import { isParseLimit, + parseFailureAnalysisError, parseLimitConstraint, } from "../domain/parseFailureAnalysisError.js"; import { Il2cppMetadataFormatFailure } from "./Il2cppMetadataFormat.js"; @@ -75,6 +77,39 @@ const inferredReferenceForm = (architecture: string) => architecture === "arm64" ? "an adjacent ADRP+ADD pair" : "RIP-relative LEA/MOV"; +/** + * Both files parsed, but the binary does not link to the metadata. They are + * two well-formed records that disagree, and nothing establishes which one + * is wrong, so neither is called malformed: the refusal lists both selecting + * fields, and the caller's partial observation keeps both files' identities. + */ +const linkConflict = ( + binaryPath: string, + metadataPath: string, + cause: Il2cppBinaryFormatFailure, +): AnalysisInputError => + new AnalysisInputError( + OPERATION, + { + cause, + conformsToInputContract: true, + remediationAction: + "Select the native binary and global-metadata.dat from the same build. If they are from the same build, either file may be damaged or the binary's registration layout may be outside coverage. Without the binary, the metadata alone can still be read.", + }, + [ + { + path: ["path"], + reason: "invalid_value", + message: `Selected metadata ${metadataPath} does not link to the selected binary: ${cause.message}`, + }, + { + path: ["binary_path"], + reason: "invalid_value", + message: `Selected binary ${binaryPath} does not link to the metadata: ${cause.message}`, + }, + ], + ); + const failureForPrimary = ( facts: ArtifactFilePrimaryFacts, path: string, @@ -103,27 +138,20 @@ const failureForPrimary = ( ), ); if ( - cause instanceof Il2cppBinaryFormatFailure || - cause instanceof Il2cppMetadataFormatFailure - ) { - const binary = cause instanceof Il2cppBinaryFormatFailure; - // Metadata names are read on demand while linking, so a metadata failure - // can surface while path still names the binary. - const target = binary ? path : metadataPath; - return cause.kind === "unsupported" - ? new AnalysisUnsupportedTargetError(OPERATION, target, cause.message, { - cause, - }) - : new AnalysisInputError(OPERATION, { cause }, [ - { - path: [binary ? field : "path"], - reason: "invalid_format", - message: binary - ? `Selected binary ${target} does not link to the metadata: ${cause.message}` - : `Selected artifact ${target} is corrupt: ${cause.message}`, - }, - ]); - } + cause instanceof Il2cppBinaryFormatFailure && + isIl2cppLinkConflict(cause.reason) + ) + return linkConflict(path, metadataPath, cause); + // Each file's own format failure names that file. Metadata names are read + // on demand while linking, so a metadata failure can surface while `path` + // here still names the binary. + const ownFormatFailure = + cause instanceof Il2cppBinaryFormatFailure + ? parseFailureAnalysisError(OPERATION, path, cause) + : cause instanceof Il2cppMetadataFormatFailure + ? parseFailureAnalysisError(OPERATION, metadataPath, cause) + : undefined; + if (ownFormatFailure !== undefined) return ownFormatFailure; const identityFailure = projectOwnedArtifactIdentityFailure( facts, OPERATION, diff --git a/src/native/AppleDispatchMetadata.ts b/src/native/AppleDispatchMetadata.ts index 72e668d0a0..b26ae3390d 100644 --- a/src/native/AppleDispatchMetadata.ts +++ b/src/native/AppleDispatchMetadata.ts @@ -12,6 +12,7 @@ import { } from "../resources/index.js"; import { malformedInput, + ParseFailureError, parseFailureFromCause, } from "../domain/parseFailure.js"; import { setImmediate as immediate } from "node:timers/promises"; @@ -91,8 +92,8 @@ export function* decodeAppleDispatchMetadataSteps( slice: admittedSlice, }); if (!selected.ok) { - if (selected.error.kind === "malformed") - throw malformedInput("macho", selected.error.message); + if (selected.error.kind === "format") + throw new ParseFailureError(selected.error.failure); // Admission bound this architecture and slice to these exact bytes, so a // refusal is an inconsistency inside REA, not the caller's selection. throw new ProviderAdapterError(IDENTITY.id, OPERATION, { diff --git a/src/native/AppleMachoSelection.fixture.ts b/src/native/AppleMachoSelection.fixture.ts index 6155475ee6..fd242ef600 100644 --- a/src/native/AppleMachoSelection.fixture.ts +++ b/src/native/AppleMachoSelection.fixture.ts @@ -1,4 +1,4 @@ -import { malformedInput } from "../domain/parseFailure.js"; +import { ParseFailureError } from "../domain/parseFailure.js"; import { parseMachoLayout, type MachoLayout, @@ -28,7 +28,7 @@ export const layoutFor = ( slice, }); if (selected.ok) return parseMachoLayout(bytes, selected.value); - if (selected.error.kind === "malformed") - throw malformedInput("macho", selected.error.message); + if (selected.error.kind === "format") + throw new ParseFailureError(selected.error.failure); throw new MachoSliceRefused(selected.error); }; diff --git a/src/native/AppleMachoSelection.test.ts b/src/native/AppleMachoSelection.test.ts index 25bcd178aa..c8616a2403 100644 --- a/src/native/AppleMachoSelection.test.ts +++ b/src/native/AppleMachoSelection.test.ts @@ -922,8 +922,9 @@ it.each([0, 129])( ? { ok: false, error: { - kind: "malformed", + kind: "format", message: "FAT header declares no architectures", + failure: { kind: "malformed", format: "macho" }, }, } : { ok: true, value: { fileOffset: 0, selection: null } }, diff --git a/src/native/metadata/MachoSliceSelection.test.ts b/src/native/metadata/MachoSliceSelection.test.ts index 5c4b3a62ab..dd3fcc8f01 100644 --- a/src/native/metadata/MachoSliceSelection.test.ts +++ b/src/native/metadata/MachoSliceSelection.test.ts @@ -6,7 +6,16 @@ import { fatSliceRange, machoImage, } from "../../artifacts/apple/MachoImage.fixture.js"; -import { selectMachoSlice } from "../../domain/apple/machoSliceSelection.js"; +import { + requireSelectedNativeImage, + requireSelectedNativeImageFromReader, + selectMachoSlice, +} from "../../domain/apple/machoSliceSelection.js"; +import { + AnalysisInputError, + AnalysisMalformedTargetError, + AnalysisUnsupportedTargetError, +} from "../../domain/analysisErrorCore.js"; const selectNativeImage = ( bytes: Buffer, @@ -196,10 +205,17 @@ describe("selectNativeImage family reads and unread slices", () => { [CPU_ARM64, 2, 0], ]); const result = selectNativeImage(file.bytes, "arm64e"); + const message = + "FAT architecture 1 CPU type/subtype disagrees with its Mach-O header"; expect(result.ok ? undefined : result.error).toEqual({ - kind: "malformed", - message: - "FAT architecture 1 CPU type/subtype disagrees with its Mach-O header", + kind: "format", + message, + failure: { + kind: "malformed", + format: "macho", + detail: message, + offset: file.offsets[1], + }, }); }); @@ -211,9 +227,44 @@ describe("selectNativeImage family reads and unread slices", () => { // Declare the second slice past the end of the file. file.bytes.writeUInt32BE(file.bytes.length, 8 + 20 + 12); const result = selectNativeImage(file.bytes, "arm64"); + const message = "FAT architecture 1 slice range extends beyond the file"; expect(result.ok ? undefined : result.error).toEqual({ - kind: "malformed", - message: "FAT architecture 1 slice range extends beyond the file", + kind: "format", + message, + failure: { kind: "malformed", format: "macho", detail: message }, + }); + }); + + it("fails as truncated when the selected slice ends inside its Mach-O identity", () => { + const file = fat([ + [CPU_ARM64, 0], + [CPU_ARM64, 2], + ]); + // The second slice keeps its Mach-O magic but declares only 8 bytes. + file.bytes.writeUInt32BE(8, 8 + 20 + 12); + const result = selectNativeImage(file.bytes, "arm64e"); + expect(result.ok ? undefined : result.error).toMatchObject({ + kind: "format", + failure: { + kind: "truncated", + format: "macho", + detail: "FAT architecture 1 has a truncated Mach-O identity", + offset: file.offsets[1], + }, + }); + }); + + it("keeps an alignment outside coverage unsupported, not malformed", () => { + const file = fat([[CPU_ARM64, 0]]); + file.bytes.writeUInt32BE(60, 8 + 16); + const result = selectNativeImage(file.bytes, "arm64"); + expect(result.ok ? undefined : result.error).toMatchObject({ + kind: "format", + failure: { + kind: "unsupported", + format: "macho", + detail: "FAT architecture 0 alignment exponent 60 is unsupported", + }, }); }); @@ -269,3 +320,88 @@ describe("selectNativeImage family reads and unread slices", () => { ); }); }); + +/** Both public selection mappers, over a buffer and over a random-access reader. */ +const MAPPERS = { + buffer: (bytes: Buffer, architecture: MachoSliceArchitecture) => + Promise.resolve().then(() => + requireSelectedNativeImage( + "inspect_go_binary", + "/a.dylib", + bytes, + architecture, + ), + ), + reader: (bytes: Buffer, architecture: MachoSliceArchitecture) => + requireSelectedNativeImageFromReader( + "inspect_go_binary", + "/a.dylib", + { + size: bytes.length, + readRange: (offset, length) => + Promise.resolve(bytes.subarray(offset, offset + length)), + }, + architecture, + ), +} as const; + +describe.each(Object.entries(MAPPERS))( + "requireSelectedNativeImage over a %s", + (_, select) => { + const refusal = (bytes: Buffer, architecture: MachoSliceArchitecture) => + select(bytes, architecture).then( + () => { + throw new Error("expected a selection refusal"); + }, + (cause: unknown) => cause, + ); + + it("refuses an unknown slice as the caller's architecture, not the file", async () => { + const { bytes } = fat([[CPU_ARM64, 0]]); + const refused = await refusal(bytes, "x86_64"); + expect(refused).toBeInstanceOf(AnalysisInputError); + expect(refused).toMatchObject({ + issues: [{ path: ["architecture"], reason: "invalid_value" }], + }); + }); + + it("refuses a truncated selected slice as a truncated target at its path", async () => { + const file = fat([ + [CPU_ARM64, 0], + [CPU_ARM64, 2], + ]); + file.bytes.writeUInt32BE(8, 8 + 20 + 12); + const refused = await refusal(file.bytes, "arm64e"); + expect(refused).toBeInstanceOf(AnalysisMalformedTargetError); + expect(refused).toMatchObject({ + path: "/a.dylib", + failure: { + kind: "truncated", + format: "macho", + offset: file.offsets[1], + }, + }); + }); + + it("refuses a slice whose header disagrees with its table entry as a malformed target", async () => { + const file = fat([ + [CPU_ARM64, 0], + [CPU_ARM64, 2, 0], + ]); + const refused = await refusal(file.bytes, "arm64e"); + expect(refused).toBeInstanceOf(AnalysisMalformedTargetError); + expect(refused).toMatchObject({ + path: "/a.dylib", + failure: { kind: "malformed", format: "macho" }, + }); + }); + + it("refuses an alignment outside coverage as an unsupported target", async () => { + const file = fat([[CPU_ARM64, 0]]); + file.bytes.writeUInt32BE(60, 8 + 16); + const refused = await refusal(file.bytes, "arm64"); + expect(refused).toBeInstanceOf(AnalysisUnsupportedTargetError); + expect(refused).toMatchObject({ path: "/a.dylib" }); + }); + }, +); diff --git a/tests/acceptance/il2cppMetadataCli.test.ts b/tests/acceptance/il2cppMetadataCli.test.ts index c71a85131f..08f856adb8 100644 --- a/tests/acceptance/il2cppMetadataCli.test.ts +++ b/tests/acceptance/il2cppMetadataCli.test.ts @@ -332,16 +332,13 @@ cliTest( }); expect(output.exitCode).toBe(1); const expected = { - code: "invalid_request", + code: "unsupported_target", details: { operation: "inspect_il2cpp_metadata", - issues: [ - { - path: ["path"], - reason: "invalid_format", - message: expect.stringContaining("record-size-mismatch"), - }, - ], + path, + format_failure: "malformed", + format: "il2cpp-metadata", + reason: expect.stringContaining("record-size-mismatch"), }, }; expect(output.json).toMatchObject(expected); @@ -501,16 +498,12 @@ cliTest( "overlap.dat", corrupt, { - code: "invalid_request", + code: "unsupported_target", details: { operation: "inspect_il2cpp_metadata", - issues: [ - { - path: ["path"], - reason: "invalid_format", - message: expect.stringContaining("section-overlap"), - }, - ], + format_failure: "malformed", + format: "il2cpp-metadata", + reason: expect.stringContaining("section-overlap"), }, }, ], @@ -540,16 +533,13 @@ cliTest( await writeFile(path, bytes); const expected = { - code: "invalid_request", + code: "unsupported_target", details: { operation: "inspect_il2cpp_metadata", - issues: [ - { - path: ["path"], - reason: "invalid_format", - message: expect.stringContaining("truncated-header"), - }, - ], + path, + format_failure: "truncated", + format: "il2cpp-metadata", + reason: expect.stringContaining("truncated-header"), partial_observation: { normalized_result: { artifact: { @@ -1083,6 +1073,110 @@ cliTest( }, ); +cliTest( + "names the input at fault in a metadata and binary pair through CLI and MCP", + async ({ cli }) => { + const root = await createTestTempDirectory("rea-il2cpp-pair-fault-"); + const { client, call } = await sharedMcp(); + const linked = createLinkedIl2cppMetadataFixture(); + const corruptMetadata = Buffer.from(linked.bytes); + corruptMetadata.writeInt32LE( + linked.section("typeDefinitions").offset + 4, + linked.header("images", "offset"), + ); + const truncatedSlice = createUniversalFixture([ + { cpu: 0x0100000c, bytes: createIl2cppBinaryFixture() }, + ]); + // The lone slice keeps its Mach-O magic but declares only 8 bytes. + truncatedSlice.writeUInt32BE(8, 8 + 12); + for (const [name, metadata, binary, expected] of [ + [ + "metadata", + corruptMetadata, + createIl2cppBinaryFixture(), + (path: string) => ({ + code: "unsupported_target", + details: { + path, + format_failure: "malformed", + format: "il2cpp-metadata", + reason: expect.stringContaining("section-overlap"), + }, + }), + ], + [ + "binary", + linked.bytes, + truncatedSlice, + (_: string, binaryPath: string) => ({ + code: "unsupported_target", + details: { + path: binaryPath, + format_failure: "truncated", + format: "macho", + }, + }), + ], + [ + "pair", + linked.bytes, + createIl2cppBinaryFixture({ codeRegistration: false }), + // Both files parse but do not agree: neither is blamed, both + // selecting fields are listed in each adapter's spelling. + (path: string, binaryPath: string, binaryField: string) => ({ + code: "invalid_request", + details: { + issues: [ + { + path: ["path"], + reason: "invalid_value", + message: expect.stringContaining(`Selected metadata ${path}`), + }, + { + path: [binaryField], + reason: "invalid_value", + message: expect.stringContaining( + `Selected binary ${binaryPath}`, + ), + }, + ], + }, + }), + ], + ] as const) { + const path = join(root, `${name}-global-metadata.dat`); + const binaryPath = join(root, `${name}-GameAssembly.dylib`); + await writeFile(path, metadata); + await writeFile(binaryPath, binary); + // Only the universal binary takes an architecture selection. + const universal = binary === truncatedSlice; + const result = await cli.run({ + arguments: [ + "inspect-il2cpp-metadata", + path, + "--binary", + binaryPath, + ...(universal ? ["--architecture", "arm64"] : []), + "--json", + ], + }); + expect(result.exitCode, name).toBe(1); + expect(result.json, name).toMatchObject( + expected(path, binaryPath, "binary"), + ); + const response = await call("inspect_il2cpp_metadata", { + path, + binary_path: binaryPath, + ...(universal ? { binary_architecture: "arm64" } : {}), + }); + expect(parseMcpToolError(response).error, name).toMatchObject( + expected(path, binaryPath, "binary_path"), + ); + } + await client.ping(); + }, +); + cliTest( "keeps a dyld-bound method slot unresolved through CLI and MCP", async ({ cli }) => { diff --git a/tests/acceptance/il2cppStructuralExtentsCli.test.ts b/tests/acceptance/il2cppStructuralExtentsCli.test.ts index f103929ebb..6247342afb 100644 --- a/tests/acceptance/il2cppStructuralExtentsCli.test.ts +++ b/tests/acceptance/il2cppStructuralExtentsCli.test.ts @@ -47,17 +47,14 @@ cliTest( arguments: ["inspect-il2cpp-metadata", path, "--json"], }); const expected = { - code: "invalid_request", + code: "unsupported_target", details: { - issues: [ - { - path: ["path"], - reason: "invalid_format", - message: expect.stringContaining( - `record-size-mismatch: section ${name}`, - ), - }, - ], + path, + format_failure: "malformed", + format: "il2cpp-metadata", + reason: expect.stringContaining( + `record-size-mismatch: section ${name}`, + ), }, }; expect(invalid.exitCode).toBe(1); diff --git a/tests/acceptance/managedCliOutput.test.ts b/tests/acceptance/managedCliOutput.test.ts index 490645dd22..6eff34d6e7 100644 --- a/tests/acceptance/managedCliOutput.test.ts +++ b/tests/acceptance/managedCliOutput.test.ts @@ -728,41 +728,6 @@ cliTest( }, ); -cliTest( - "managed CLI reports a section table past EOF as invalid input", - async ({ cli }) => { - const root = await createTestTempDirectory("rea-managed-cli-sections-"); - const path = join(root, "fixture.dll"); - const bytes = buildManagedPeFixture(); - const pe = bytes.readUInt32LE(0x3c); - const sections = pe + 24 + bytes.readUInt16LE(pe + 20); - bytes.writeUInt32LE(bytes.length + 0x1000, sections + 20); - await writeFile(path, bytes); - for (const command of [ - "inspect-managed-artifact", - "inspect-managed-members", - "inspect-managed-native-boundaries", - ]) { - const result = await cli.run({ - arguments: [command, path, "--json"], - }); - expect(result.exitCode).toBe(1); - expect(result.json).toMatchObject({ - code: "invalid_request", - details: { - issues: [ - { - path: ["path"], - reason: "invalid_format", - message: expect.stringContaining("pe.section-data"), - }, - ], - }, - }); - } - }, -); - cliTest( "managed CLI refuses non-PE executables as unsupported targets", async ({ cli }) => { diff --git a/tests/acceptance/stableArtifactParserFailureCli.test.ts b/tests/acceptance/stableArtifactParserFailureCli.test.ts index c558a08dac..188d82b765 100644 --- a/tests/acceptance/stableArtifactParserFailureCli.test.ts +++ b/tests/acceptance/stableArtifactParserFailureCli.test.ts @@ -2,6 +2,11 @@ import { createHash } from "node:crypto"; import { writeFile } from "node:fs/promises"; import { join } from "node:path"; import { expect } from "vitest"; +import { + fatImage, + machoImage, +} from "../../src/artifacts/apple/MachoImage.fixture.js"; +import { buildManagedPeFixture } from "../../src/dotnet/ManagedPe.fixture.js"; import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js"; import { cliTest } from "../support/cli/cliFixture.js"; import { peCertificateFixture } from "../../src/native/pe/PeCertificates.fixture.js"; @@ -79,6 +84,89 @@ for (const command of [ ); } +/** A managed PE whose first section's raw data starts past the end of the file. */ +const managedSectionPastEof = () => { + const bytes = buildManagedPeFixture(); + const pe = bytes.readUInt32LE(0x3c); + const sections = pe + 24 + bytes.readUInt16LE(pe + 20); + bytes.writeUInt32LE(bytes.length + 0x1000, sections + 20); + return bytes; +}; + +/** A universal Mach-O whose first declared slice runs into the second. */ +const overlappingUniversalMacho = () => { + const slice = (type: number, subtype: number) => ({ + cpu: { type, subtype }, + bytes: machoImage({ cpu: { type, subtype }, wide: true }), + }); + const bytes = Buffer.from( + fatImage([slice(0x01000007, 3), slice(0x0100000c, 0)]), + ); + const first = bytes.readUInt32BE(8 + 8); + const second = bytes.readUInt32BE(8 + 20 + 8); + bytes.writeUInt32BE(second - first + 16, 8 + 12); + return bytes; +}; + +// Format owners with their own mappers: a managed PE/CLI reader and the +// universal Mach-O container read before slice selection. The selected file's +// bytes are at fault, so each is a malformed target at that file's path. +for (const { command, bytes, format, extra = [], identity } of [ + ...[ + "inspect-managed-artifact", + "inspect-managed-members", + "inspect-managed-native-boundaries", + ].map((command) => ({ + command, + bytes: managedSectionPastEof, + format: { format: "pe-cli", field: "pe.section-data" }, + extra: [] as string[], + identity: false, + })), + ...[ + "inspect-go-binary", + "inspect-rust-binary", + "inspect-dwarf-units", + "inspect-native-initializers", + ].map((command) => ({ + command, + bytes: overlappingUniversalMacho, + format: { format: "macho", reason: "Mach-O slices 0 and 1 overlap." }, + extra: ["--architecture", "arm64"], + identity: true, + })), +]) { + cliTest( + `${command} refuses malformed ${format.format} bytes as a malformed target`, + async ({ cli }) => { + const root = await createTestTempDirectory("rea-format-owner-"); + const path = join(root, "malformed.bin"); + const written = bytes(); + await writeFile(path, written); + const result = await cli.run({ + arguments: [command, path, ...extra, "--json"], + }); + expect(result.exitCode, result.stderr).toBe(1); + expect(result.json).toMatchObject({ + code: "unsupported_target", + category: "unsupported_target", + retryable: false, + details: { + operation: command.replaceAll("-", "_"), + path, + format_failure: "malformed", + ...format, + ...(identity + ? { partial_observation: fileIdentity(path, written) } + : {}), + }, + }); + expect(result.json).not.toHaveProperty("details.issues"); + expect(result.json).not.toHaveProperty("recovery"); + }, + ); +} + /** A PE image whose first WIN_CERTIFICATE declares less than its own header. */ const shortCertificateHeader = (): Buffer => { const bytes = peCertificateFixture(); diff --git a/tests/boundary/cli/managedMemberComparisonCli.test.ts b/tests/boundary/cli/managedMemberComparisonCli.test.ts index 44161d4be4..3eff28421d 100644 --- a/tests/boundary/cli/managedMemberComparisonCli.test.ts +++ b/tests/boundary/cli/managedMemberComparisonCli.test.ts @@ -79,7 +79,7 @@ cliTest( ); cliTest( - "attributes malformed managed comparison input to its selected argument and retains completed peer Evidence", + "names the malformed managed comparison input by its path and retains completed peer Evidence", async ({ cli }) => { const directory = await createTestTempDirectory( "rea-managed-malformed-cli-", @@ -172,30 +172,34 @@ cliTest( JSON.stringify((refused.json as { remediation: unknown }).remediation), ).not.toContain("--max-snapshot-bytes"); + // The refusal names the malformed side by its own path; the arguments are + // not at fault, so no request field is listed. for (const field of ["leftPath", "rightPath"] as const) { + const side = join(directory, `${field}.dll`); + await writeFile(side, malformed); const result = await cli.run({ arguments: [ "compare-managed-members", - field === "leftPath" ? bad : good, - field === "rightPath" ? bad : good, + field === "leftPath" ? side : good, + field === "rightPath" ? side : good, "--json", ], }); expect(result.exitCode, result.stderr).toBe(1); expect(result.json).toMatchObject({ - code: "invalid_request", - category: "invalid_input", + code: "unsupported_target", + category: "unsupported_target", retryable: false, details: { - issues: [ - { - path: [field], - reason: "invalid_format", - message: `Selected artifact ${bad}: PE section count must be positive`, - }, - ], + operation: "inspect_managed_members", + path: side, + format_failure: "malformed", + format: "pe-cli", + reason: "PE section count must be positive", }, }); + expect(result.json).not.toHaveProperty("details.issues"); + expect(result.json).not.toHaveProperty("recovery"); if (field === "rightPath") expect(result.json).toMatchObject({ details: { @@ -212,16 +216,13 @@ cliTest( }); expect(inspection.exitCode, inspection.stderr).toBe(1); expect(inspection.json).toMatchObject({ - code: "invalid_request", - category: "invalid_input", + code: "unsupported_target", + category: "unsupported_target", details: { - issues: [ - { - path: ["path"], - reason: "invalid_format", - message: `Selected artifact ${bad}: PE section count must be positive`, - }, - ], + path: bad, + format_failure: "malformed", + format: "pe-cli", + reason: "PE section count must be positive", }, }); }, diff --git a/tests/boundary/il2cpp/il2cppBinaryFile.test.ts b/tests/boundary/il2cpp/il2cppBinaryFile.test.ts index 2d7f9c9d09..8b9cfcc0e2 100644 --- a/tests/boundary/il2cpp/il2cppBinaryFile.test.ts +++ b/tests/boundary/il2cpp/il2cppBinaryFile.test.ts @@ -6,7 +6,10 @@ import { readUInt32, requireIl2cppBinaryImage, } from "../../../src/il2cpp/Il2cppBinaryImage.js"; -import { AnalysisInputError } from "../../../src/domain/analysisErrorCore.js"; +import { + AnalysisInputError, + AnalysisMalformedTargetError, +} from "../../../src/domain/analysisErrorCore.js"; import type { Il2cppBinaryArchitecture } from "../../../src/domain/il2cpp/il2cppMetadata.js"; import { describe, expect, it } from "vitest"; import { findCodeRegistration } from "../../../src/il2cpp/Il2cppBinaryRegistration.js"; @@ -134,6 +137,20 @@ const selectionIssue = ( } throw new Error("expected a selection failure"); }; +/** The universal file's own format refusal, which names the binary's path. */ +const containerFailure = ( + bytes: Buffer, + architecture?: Il2cppBinaryArchitecture, +) => { + try { + link(bytes, architecture); + } catch (cause) { + if (cause instanceof AnalysisMalformedTargetError) + return { path: cause.path, ...cause.failure }; + throw cause; + } + throw new Error("expected a container failure"); +}; const addElfLoadAlias = ( bytes: Buffer, fileOffset: number, @@ -340,9 +357,11 @@ it("rejects a universal Mach-O whose slices overlap before selecting one", () => const first = universal.readUInt32BE(8 + 8); const second = universal.readUInt32BE(8 + 20 + 8); universal.writeUInt32BE(second - first + 16, 8 + 12); - expect(selectionIssue(universal, "arm64")).toMatchObject({ - path: ["binary_path"], - reason: "invalid_format", + expect(containerFailure(universal, "arm64")).toMatchObject({ + path: "/GameAssembly.dylib", + kind: "malformed", + format: "macho", + detail: "Mach-O slices 0 and 1 overlap.", }); }); @@ -1419,13 +1438,38 @@ it("refuses an ambiguous architecture instead of choosing the first FAT slice", message: expect.stringContaining("no slice was selected"), }); }); +it("refuses a selected slice that ends inside its Mach-O identity as a truncated binary", () => { + const bytes = createUniversalFixture([ + { cpu: 0x0100000c, bytes: createIl2cppBinaryFixture() }, + ]); + bytes.writeUInt32BE(8, 8 + 12); + expect(containerFailure(bytes, "arm64")).toMatchObject({ + path: "/GameAssembly.dylib", + kind: "truncated", + format: "macho", + offset: bytes.readUInt32BE(8 + 8), + }); +}); +it("refuses an architecture the universal binary does not hold as the caller's selection", () => { + const bytes = createUniversalFixture([ + { cpu: 0x0100000c, bytes: createIl2cppBinaryFixture() }, + ]); + expect(selectionIssue(bytes, "amd64")).toMatchObject({ + path: ["binary_architecture"], + reason: "invalid_value", + }); +}); it("checks the observed slice header against the caller-selected FAT architecture", () => { const bytes = createUniversalFixture([ { cpu: 0x01000007, bytes: createIl2cppBinaryFixture() }, ]); - expect(selectionIssue(bytes, "amd64")).toMatchObject({ - path: ["binary_path"], - reason: "invalid_format", + // The table and the slice header are two records of one file, so their + // disagreement is the file's malformed container, not the caller's choice. + expect(containerFailure(bytes, "amd64")).toMatchObject({ + path: "/GameAssembly.dylib", + kind: "malformed", + format: "macho", + detail: expect.stringContaining("disagrees with its Mach-O header"), }); }); it.each([1, 0x80000000])( @@ -1434,9 +1478,10 @@ it.each([1, 0x80000000])( const thin = createIl2cppBinaryFixture(); thin.writeUInt32LE(subtype, 8); const bytes = createUniversalFixture([{ cpu: 0x0100000c, bytes: thin }]); - expect(selectionIssue(bytes, "arm64")).toMatchObject({ - path: ["binary_path"], - reason: "invalid_format", + expect(containerFailure(bytes, "arm64")).toMatchObject({ + path: "/GameAssembly.dylib", + kind: "malformed", + format: "macho", }); bytes.writeUInt32BE(subtype, 12); expect(link(bytes, "arm64").method_addresses).toEqual(expectedAddresses); diff --git a/tests/boundary/il2cpp/il2cppMetadataProvider.test.ts b/tests/boundary/il2cpp/il2cppMetadataProvider.test.ts index e1a0b82750..d171145d83 100644 --- a/tests/boundary/il2cpp/il2cppMetadataProvider.test.ts +++ b/tests/boundary/il2cpp/il2cppMetadataProvider.test.ts @@ -667,16 +667,15 @@ it("retains the exact source when recognized magic has no complete version", asy if (result.ok) throw new Error("Expected truncated metadata prefix"); expect(result.error).toMatchObject({ - _tag: "AnalysisInputError", - issues: [ - { - path: ["path"], - reason: "invalid_format", - message: expect.stringMatching( - /truncated-header:.*metadata version is unknown/u, - ), - }, - ], + _tag: "AnalysisMalformedTargetError", + path, + failure: { + kind: "truncated", + format: "il2cpp-metadata", + detail: expect.stringMatching( + /truncated-header:.*metadata version is unknown/u, + ), + }, }); expect(result.error.partialObservation).toMatchObject({ operation: "observe_il2cpp_metadata_source", @@ -879,8 +878,13 @@ it.each([false, true])( expect(ordinary).toMatchObject({ ok: false, error: { - _tag: "AnalysisInputError", - issues: [{ path: ["binary_path"], reason: "invalid_format" }], + _tag: "AnalysisMalformedTargetError", + path: binary_path, + failure: { + kind: "malformed", + format: "il2cpp-binary", + detail: expect.stringMatching(/^malformed-container:/u), + }, }, }); } finally { @@ -958,9 +962,44 @@ it("retains both observed file identities and the selected architecture when nat try { const result = await provider.inspect({ path, binary_path }); if (result.ok) throw new Error("Unresolved registration accepted"); + // Both files parse; neither is called malformed. The conflict lists each + // selecting field and keeps each file's identity. + expect(result.error).toMatchObject({ + _tag: "AnalysisInputError", + conformsToInputContract: true, + issues: [ + { + path: ["path"], + reason: "invalid_value", + message: expect.stringContaining( + `Selected metadata ${path} does not link to the selected binary: code-registration-not-found:`, + ), + }, + { + path: ["binary_path"], + reason: "invalid_value", + message: expect.stringContaining( + `Selected binary ${binary_path} does not link to the metadata: code-registration-not-found:`, + ), + }, + ], + }); + expect(projectAnalysisError(result.error)).toMatchObject({ + code: "invalid_request", + retryable: false, + remediation: { + action: expect.stringContaining("from the same build"), + }, + }); + expect(projectAnalysisError(result.error)).not.toHaveProperty("recovery"); expect(result.error.partialObservation).toMatchObject({ normalized_result: { - artifact: { path }, + artifact: { + path, + sha256: createHash("sha256") + .update(createLinkedIl2cppMetadataFixture().bytes) + .digest("hex"), + }, selected_binary: { path: binary_path, identity_status: "observed", @@ -1134,16 +1173,13 @@ it("names the metadata, not the binary, when linking reads a malformed metadata const result = await provider.inspect({ path, binary_path: binaryPath }); if (result.ok) throw new Error("Expected the metadata name to be refused"); expect(result.error).toMatchObject({ - _tag: "AnalysisInputError", - issues: [ - { - path: ["path"], - reason: "invalid_format", - message: expect.stringContaining( - `Selected artifact ${path} is corrupt: invalid-string:`, - ), - }, - ], + _tag: "AnalysisMalformedTargetError", + path, + failure: { + kind: "malformed", + format: "il2cpp-metadata", + detail: expect.stringMatching(/^invalid-string:/u), + }, }); const corrected = Buffer.from(metadata); diff --git a/tests/boundary/mcp/universalSliceMcp.test.ts b/tests/boundary/mcp/universalSliceMcp.test.ts index 8efab260a0..c526088523 100644 --- a/tests/boundary/mcp/universalSliceMcp.test.ts +++ b/tests/boundary/mcp/universalSliceMcp.test.ts @@ -87,6 +87,14 @@ const issues = (response: unknown) => }) .parse(parseMcpToolError(response as never)).error; +/** A universal file's own format refusal: a target fault, no field to correct. */ +const containerRefusal = (response: unknown) => { + const { error } = parseMcpToolError(response as never); + expect(error).not.toHaveProperty("details.issues"); + expect(error).not.toHaveProperty("recovery"); + return error; +}; + sliceTest( "reads the selected Go slice of a universal Mach-O with file-relative provenance", async ({ slices: { client, session, write } }) => { @@ -249,7 +257,7 @@ sliceTest( const damaged = await write("damaged", truncated); for (const architecture of [undefined, "arm64"] as const) expect( - issues( + containerRefusal( await client.callTool({ name: "inspect_go_binary", arguments: { @@ -257,10 +265,15 @@ sliceTest( ...(architecture === undefined ? {} : { architecture }), }, }), - ).details.issues[0], + ), ).toMatchObject({ - path: ["path"], - message: expect.stringContaining(`Selected artifact ${damaged}: FAT`), + code: "unsupported_target", + details: { + path: damaged, + format_failure: "malformed", + format: "macho", + reason: "FAT architecture 0 slice range extends beyond the file", + }, }); // The FAT table and the slice header must agree before the slice is read. @@ -276,21 +289,20 @@ sliceTest( ]).bytes, ); expect( - issues( + containerRefusal( await client.callTool({ name: "inspect_go_binary", arguments: { path: disagreeing, architecture: "arm64" }, }), ), ).toMatchObject({ - code: "invalid_request", + code: "unsupported_target", details: { - issues: [ - { - path: ["path"], - message: `Selected artifact ${disagreeing}: FAT architecture 0 CPU type/subtype disagrees with its Mach-O header`, - }, - ], + path: disagreeing, + format_failure: "malformed", + format: "macho", + reason: + "FAT architecture 0 CPU type/subtype disagrees with its Mach-O header", }, }); }, @@ -408,15 +420,20 @@ sliceTest( const path = await write("overlapping", universal.bytes); for (const architecture of ["arm64", "arm64e"]) expect( - issues( + containerRefusal( await client.callTool({ name: "inspect_go_binary", arguments: { path, architecture }, }), - ).details.issues[0], + ), ).toMatchObject({ - path: ["path"], - message: `Selected artifact ${path}: Mach-O slices 0 and 1 overlap.`, + code: "unsupported_target", + details: { + path, + format_failure: "malformed", + format: "macho", + reason: "Mach-O slices 0 and 1 overlap.", + }, }); }, );