fix(errors)!: align unsupported-signature status and split invalid-method-token at its producer (#14230)

* fix(managed)!: report an unsupported signature as partial metadata, not malformed

The refusal path already treats `unsupported-signature` as a valid form
outside decoder coverage, but `managedMetadataFailureStatus` still called
it malformed. One predicate, `isManagedCoverageGap`, now owns that split
for both the refusal and the inventory status.

Value retention no longer reads the inventory status: one value's
unsupported signature is still retained locally, while a budget or an
unsupported metadata layout still stops the whole read.

BREAKING CHANGE: when a managed reader stops on `unsupported-signature`,
`metadata.status` is `partial` (was `malformed`) in managed artifact,
member and native-boundary inspection, and the artifact
`classification.status` is `managed` (was `malformed`). The field names
and enum members are unchanged.

* fix(il2cpp)!: refuse a reused or non-MethodDef token as malformed metadata

`invalid-method-token` covered two facts. A MethodDef row reused within
one image, or a token that is not a nonzero MethodDef row, is in the
metadata's own records; a row past the module's method pointers is a
disagreement between two files that both parse.

The metadata reader now checks each image's tokens while reading link
facts and raises `invalid-method-definition-token`, which the provider
already refuses as a malformed target at the metadata's path. The linker
keeps `invalid-method-token` for the cross-file range check only and drops
its own duplicate scan.

BREAKING CHANGE: a duplicate or non-MethodDef method token found while
linking is `unsupported_target` with `details.path` the metadata file,
`details.format` `il2cpp-metadata`, `details.format_failure` `malformed`
and `details.reason` starting `invalid-method-definition-token:` (was an
`invalid_request` link conflict naming `path` and `binary_path` with
reason `invalid-method-token`). A token past the module's method
pointers keeps the conflict and the `invalid-method-token` reason.
This commit is contained in:
morluto authored and GitHub committed 2026-11-23 20:50:18 -05:00
1 parent 0af067d766
commit eb6c281fec
12 files changed
+239 -71

No files matched your search

+6 -2
View File
@@ -530,8 +530,12 @@ not an input error, in inspection and comparison: `unsupported_target` with
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.
outside decoder coverage is `unsupported_target` without `format_failure`.
Inventory status follows the same split: when a reader stops on such a form
(`unsupported-metadata` or `unsupported-signature`), `metadata.status` is
`partial` and an artifact's `classification.status` stays `managed`; only a
broken rule makes them `malformed`. A failed right-side comparison retains the
completed left observation.
## Member comparison
+20 -14
View File
@@ -469,7 +469,7 @@ Il2CppType byref flag in different bits, so a rendered name could gain or lose
| `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-token` | conflict | A metadata MethodDef row is past its module's method-pointer rows. |
| `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. |
@@ -494,6 +494,11 @@ Each category says which selected file is at fault:
`binary_path` (`--binary` in the CLI) and no `inspect_input_contract`
recovery. Neither file is called malformed.
A token that is not a MethodDef row, or a row reused within one image, is
the metadata's own fault, so linking refuses it as malformed metadata with
`invalid-method-definition-token` (see [failures](#failures)), not
as a conflict. Rows may repeat across images, since each image numbers its own.
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.
@@ -560,19 +565,20 @@ refusal whose `details.path` is the metadata file, `details.format` is
`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 |
| ------------------------- | ---------------------------------------------------------------------------------------------------------------- |
| `truncated-header` | The file is shorter than the header. |
| `unexpected-header-size` | `stringLiterals.offset` is not the header size: 264 bytes for version 24, 256 for 27, 29 and 31, 380 for 39. |
| `section-out-of-bounds` | A section extends beyond the file, or a non-empty section starts inside the header. |
| `section-overlap` | Two sections overlap. Zero-size sections are exempt and gaps are allowed. |
| `record-size-mismatch` | A section size does not divide into its records, or the record size differs from the one the index widths imply. |
| `type-index-width` | The record used to derive the type index width implies no 1, 2 or 4 byte width. |
| `index-out-of-range` | A serialized index or range points outside its target collection. |
| `nested-type-conflict` | A type is listed as nested in two types, in itself, or in a cycle of declaring types. |
| `declaring-type-mismatch` | A method inside a type's method range names a different type, or a method lies outside its type's range. |
| `image-range-overlap` | Two images claim the same type definitions. |
| `invalid-string` | A name index is outside the strings section, its string is unterminated, or it is not valid UTF-8. |
| Reason | Meaning |
| --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
| `truncated-header` | The file is shorter than the header. |
| `unexpected-header-size` | `stringLiterals.offset` is not the header size: 264 bytes for version 24, 256 for 27, 29 and 31, 380 for 39. |
| `section-out-of-bounds` | A section extends beyond the file, or a non-empty section starts inside the header. |
| `section-overlap` | Two sections overlap. Zero-size sections are exempt and gaps are allowed. |
| `record-size-mismatch` | A section size does not divide into its records, or the record size differs from the one the index widths imply. |
| `type-index-width` | The record used to derive the type index width implies no 1, 2 or 4 byte width. |
| `index-out-of-range` | A serialized index or range points outside its target collection. |
| `nested-type-conflict` | A type is listed as nested in two types, in itself, or in a cycle of declaring types. |
| `declaring-type-mismatch` | A method inside a type's method range names a different type, or a method lies outside its type's range. |
| `image-range-overlap` | Two images claim the same type definitions. |
| `invalid-string` | A name index is outside the strings section, its string is unterminated, or it is not valid UTF-8. |
| `invalid-method-definition-token` | Read only when linking a binary: a method an image owns has no nonzero MethodDef token, or two methods in one image share a MethodDef row. |
Record extents are checked for the decoded images, types, methods, fields,
properties, events, parameters, string literals, nested types, generic
@@ -5,9 +5,12 @@ import {
AnalysisUnsupportedTargetError,
} from "../analysisErrorCore.js";
import { projectAnalysisError } from "../analysisErrorProjection.js";
import type { ManagedParseIssue } from "./managedArtifact.js";
import {
managedFailure,
managedInspectionTargetFailure,
managedMetadataFailureStatus,
retainManagedValueFailure,
} from "./managedReaderFailure.js";
const OPERATION = "inspect_managed_members";
@@ -67,6 +70,50 @@ describe("managedInspectionTargetFailure", () => {
},
);
it.each([
["resource-limit", "partial"],
["unsupported-metadata", "partial"],
["unsupported-signature", "partial"],
["invalid-blob", "malformed"],
["invalid-tables", "malformed"],
["invalid-directory", "malformed"],
] as const)(
"reports %s as %s metadata, matching the refusal's classification",
(code, status) => {
const issue = managedFailure(code, "metadata.tables", "detail").issue;
expect(managedMetadataFailureStatus(issue)).toBe(status);
const refusal = managedInspectionTargetFailure(
OPERATION,
PATH,
managedFailure(code, "metadata.tables", "detail"),
);
// Only a broken rule is malformed in both the inventory and a refusal.
expect(refusal instanceof AnalysisMalformedTargetError).toBe(
status === "malformed",
);
},
);
it.each([
["unsupported-signature", "retained"],
["invalid-blob", "retained"],
["unsupported-metadata", "escapes"],
["resource-limit", "escapes"],
] as const)(
"keeps one value's %s local or stops the whole read: %s",
(code, outcome) => {
const issues: ManagedParseIssue[] = [];
const cause = managedFailure(code, "metadata.TypeSpec:0x1b000001", "x");
if (outcome === "retained") {
expect(retainManagedValueFailure(cause, issues)).toBe(cause);
expect(issues).toEqual([cause.issue]);
} else {
expect(() => retainManagedValueFailure(cause, issues)).toThrow(cause);
expect(issues).toEqual([]);
}
},
);
it("leaves a resource limit and foreign causes to their producers", () => {
expect(
managedInspectionTargetFailure(
+22 -5
View File
@@ -28,11 +28,23 @@ export class ManagedReaderFailure extends Error {
/** Refuse a heap-dependent row whose shared stream issue is reported by layout inventory. */
export class ManagedHeapAmbiguityFailure extends ManagedReaderFailure {}
/** A resource or unsupported layout leaves metadata unknown, not malformed. */
/**
* Whether a reader stopped on a valid construct REA does not implement: a
* metadata layout or signature form outside decoder coverage. Every other
* code except `resource-limit` names a rule the bytes broke.
*/
export const isManagedCoverageGap = (code: ManagedParseIssue["code"]) =>
code === "unsupported-metadata" || code === "unsupported-signature";
/**
* Metadata status after a reader stopped. A budget or a construct outside
* coverage leaves metadata unknown (`partial`); only a broken rule makes it
* `malformed`.
*/
export const managedMetadataFailureStatus = (
issue: ManagedParseIssue,
): "partial" | "malformed" =>
issue.code === "resource-limit" || issue.code === "unsupported-metadata"
issue.code === "resource-limit" || isManagedCoverageGap(issue.code)
? "partial"
: "malformed";
@@ -59,7 +71,7 @@ export const managedInspectionTargetFailure = (
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")
if (isManagedCoverageGap(code))
return new AnalysisUnsupportedTargetError(operation, path, detail, {
cause,
});
@@ -86,14 +98,19 @@ export const managedFailure = (
): ManagedReaderFailure =>
new ManagedReaderFailure({ code, scope, offset, detail });
/** Retain a local malformed fact; capacity and unexpected failures still escape. */
/**
* Retain one value's malformed or unsupported fact so independent values can
* still be read. A budget or an unsupported metadata layout stops the whole
* read, and unexpected failures still escape.
*/
export const retainManagedValueFailure = (
cause: unknown,
issues: ManagedParseIssue[],
): ManagedReaderFailure => {
if (
!(cause instanceof ManagedReaderFailure) ||
managedMetadataFailureStatus(cause.issue) === "partial"
cause.issue.code === "resource-limit" ||
cause.issue.code === "unsupported-metadata"
)
throw cause;
if (!(cause instanceof ManagedHeapAmbiguityFailure)) issues.push(cause.issue);
+3 -2
View File
@@ -29,6 +29,7 @@ import {
import { readTypeMemberListFacts } from "../domain/managed/managedTypeMemberLists.js";
import {
ManagedReaderFailure,
isManagedCoverageGap,
managedMetadataFailureStatus,
type ManagedMetadataHeaderFacts,
} from "../domain/managed/managedReaderFailure.js";
@@ -360,11 +361,11 @@ const partialMetadataResult = ({
attributes: [],
coverage: { state: "partial", issues: [issue] },
limitations: [
issue.code === "unsupported-metadata"
isManagedCoverageGap(issue.code)
? issue.detail
: issue.code === "resource-limit"
? "CLI metadata inspection stopped at its representation budget; omitted facts are unknown."
: "CLI metadata could not be read because the PE/CLI structure is malformed or unsupported.",
: "CLI metadata could not be read because the PE/CLI structure is malformed.",
],
});
+3 -20
View File
@@ -148,25 +148,6 @@ function* linkImageSteps(
methodImage[type.method_start + method] = index;
}
}
const methodByImageAndRow = metadata.images.map(
() => new Map<number, number>(),
);
for (let index = 0; index < methodImage.length; index++) {
if (index % LINK_BATCH === 0) yield;
const owner = methodImage[index]!;
if (owner === -1) continue;
const token = facts.methodTokens[index]!;
const row = token & 0xffffff;
if (token >>> 24 !== 0x06 || row === 0) continue;
const methodsByRow = methodByImageAndRow[owner]!;
const earlier = methodsByRow.get(row);
if (earlier !== undefined)
throw new Il2cppBinaryFormatFailure(
"invalid-method-token",
`methods ${earlier} and ${index} in image ${metadata.images[owner]!.name} share MethodDef token 0x${token.toString(16)}`,
);
methodsByRow.set(row, index);
}
yield;
const methodAddress = (index: number): Il2cppMethodCode => {
const owner = methodImage[index]!;
@@ -175,7 +156,9 @@ function* linkImageSteps(
const module = modules[owner]!;
const token = facts.methodTokens[index]!;
const row = token & 0xffffff;
if (token >>> 24 !== 0x06 || row === 0 || row > module.method_pointer_count)
// The metadata reader admitted every owned token as a nonzero MethodDef
// row unique within its image; only the binary's row count is left.
if (row > module.method_pointer_count)
throw new Il2cppBinaryFormatFailure(
"invalid-method-token",
`method ${index} token 0x${token.toString(16)} is outside module ${metadata.images[owner]!.name}'s ${module.method_pointer_count} method pointers`,
+42
View File
@@ -655,6 +655,46 @@ function* checkMethodOwners(
}
}
/**
* Native linking reads each image's methods by MethodDef row, so every method
* an image owns must carry a nonzero MethodDef token that no other method in
* that image uses. The images and tokens are both this file's own records, so
* a violation makes the metadata malformed whichever binary is selected.
* Reuse across images is allowed: each image numbers its own rows.
*/
function* checkMethodTokens(
images: Il2cppMetadataDecoded["images"],
types: Il2cppMetadataDecoded["types"],
methodTokens: Uint32Array,
) {
let work = 0;
for (const image of images) {
const methodByRow = new Map<number, number>();
for (let offset = 0; offset < image.type_count; offset++) {
const type = types[image.type_start + offset]!;
if (work++ % 256 === 0) yield;
for (let index = 0; index < type.method_count; index++) {
if (work++ % 256 === 0) yield;
const method = type.method_start + index;
const token = methodTokens[method]!;
const row = token & 0xffffff;
if (token >>> 24 !== 0x06 || row === 0)
throw new Il2cppMetadataFormatFailure(
"invalid-method-definition-token",
`method ${method} in image ${image.name} has token 0x${token.toString(16)}, which is not a MethodDef row`,
);
const earlier = methodByRow.get(row);
if (earlier !== undefined)
throw new Il2cppMetadataFormatFailure(
"invalid-method-definition-token",
`methods ${earlier} and ${method} in image ${image.name} share MethodDef token 0x${token.toString(16)}`,
);
methodByRow.set(row, method);
}
}
}
}
/** Each type belongs to at most one image. */
function* checkImageRanges(images: Il2cppMetadataDecoded["images"]) {
const ranges: { start: number; end: number; index: number }[] = [];
@@ -918,6 +958,8 @@ function* readMetadataCoreSteps(
const { types, memberRanges } = yield* readTypes(tables);
const { methods, parameterRanges } = yield* readMethods(tables);
yield* checkMethodOwners(types, methods);
if (tables.linkFacts !== undefined)
yield* checkMethodTokens(images, types, tables.linkFacts.methodTokens);
const members = yield* readIl2cppMembers(tables, {
...memberRanges,
parameters: parameterRanges,
+1
View File
@@ -14,6 +14,7 @@ export const IL2CPP_METADATA_FAILURE_REASONS = {
"declaring-type-mismatch",
"image-range-overlap",
"invalid-string",
"invalid-method-definition-token",
],
} as const;
export type Il2cppMetadataFailureReason =
+55 -16
View File
@@ -1089,6 +1089,41 @@ cliTest(
]);
// The lone slice keeps its Mach-O magic but declares only 8 bytes.
truncatedSlice.writeUInt32BE(8, 8 + 12);
// Methods 0 and 1 share an image; a version 31 token is at offset 24.
const tokenPair = createLinkedIl2cppMetadataFixture({ version: 31 });
const tokenAt = (method: number) =>
tokenPair.record("methods", method) + 24;
const duplicateToken = Buffer.from(tokenPair.bytes);
duplicateToken.writeUInt32LE(
duplicateToken.readUInt32LE(tokenAt(0)),
tokenAt(1),
);
// A valid MethodDef row past the binary module's 3 method pointers.
const tokenBeyondModule = Buffer.from(tokenPair.bytes);
tokenBeyondModule.writeUInt32LE(0x06000004, tokenAt(0));
const pairConflict =
(reason: string) =>
(path: string, binaryPath: string, binaryField: string) => ({
code: "invalid_request",
details: {
issues: [
{
path: ["path"],
reason: "invalid_value",
message: expect.stringContaining(
`Selected metadata ${path} does not link to the selected binary: ${reason}:`,
),
},
{
path: [binaryField],
reason: "invalid_value",
message: expect.stringContaining(
`Selected binary ${binaryPath} does not link to the metadata: ${reason}:`,
),
},
],
},
});
for (const [name, metadata, binary, expected] of [
[
"metadata",
@@ -1123,26 +1158,30 @@ cliTest(
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",
pairConflict("code-registration-not-found"),
],
[
// The reused row is the metadata's own fault, whatever the binary.
"duplicate-token",
duplicateToken,
createIl2cppBinaryFixture(),
(path: string) => ({
code: "unsupported_target",
details: {
issues: [
{
path: ["path"],
reason: "invalid_value",
message: expect.stringContaining(`Selected metadata ${path}`),
},
{
path: [binaryField],
reason: "invalid_value",
message: expect.stringContaining(
`Selected binary ${binaryPath}`,
),
},
],
path,
format_failure: "malformed",
format: "il2cpp-metadata",
reason: expect.stringMatching(/^invalid-method-definition-token:/u),
},
}),
],
[
// A well-formed row only this binary's module cannot hold.
"token-beyond-module",
tokenBeyondModule,
createIl2cppBinaryFixture(),
pairConflict("invalid-method-token"),
],
] as const) {
const path = join(root, `${name}-global-metadata.dat`);
const binaryPath = join(root, `${name}-GameAssembly.dylib`);
@@ -244,13 +244,15 @@ it("still rejects distinct MetadataRegistration fields", () => {
).toEqual({ reason: "metadata-registration-not-found", kind: "malformed" });
});
it("rejects reused MethodDef tokens within an image but preserves cross-image reuse and folded addresses", () => {
const duplicateTokens = Uint32Array.from(facts.methodTokens);
duplicateTokens[1] = duplicateTokens[0]!;
it("rejects a MethodDef row past the module's method pointers but preserves cross-image reuse and folded addresses", () => {
// A valid MethodDef row the binary's 3-slot module does not hold: the
// metadata admits it, so only the pair disagrees.
const beyondModule = Uint32Array.from(facts.methodTokens);
beyondModule[0] = 0x06000004;
expect(() =>
linkIl2cppBinary(createIl2cppBinaryFixture(), metadata, {
...facts,
methodTokens: duplicateTokens,
methodTokens: beyondModule,
}),
).toThrow(
expect.objectContaining({
@@ -14,6 +14,7 @@ import {
} from "../../fixtures/il2cpp/readers.js";
import {
createIl2cppMetadataFixture,
createLinkedIl2cppMetadataFixture,
FIXTURE_IMAGES,
fixtureImages,
FIXTURE_METHODS,
@@ -208,6 +209,28 @@ describe("rejected IL2CPP global-metadata", () => {
},
);
it.each([
["a MethodDef row reused within one image", (first: number) => first],
["a token outside the MethodDef table", () => 0x0a000002],
["MethodDef row zero", () => 0x06000000],
])("refuses %s as malformed metadata before native linking", (_, token) => {
const fixture = createLinkedIl2cppMetadataFixture({ version: 31 });
const bytes = Buffer.from(fixture.bytes);
// Methods 0 and 1 belong to the same image; the token is at offset 24.
const first = bytes.readUInt32LE(fixture.record("methods", 0) + 24);
bytes.writeUInt32LE(token(first), fixture.record("methods", 1) + 24);
// The public inventory does not read tokens, so it is unaffected.
expect(readIl2cppMetadata(bytes).methods).toHaveLength(
readIl2cppMetadata(fixture.bytes).methods.length,
);
const rejected = failure(bytes, readIl2cppMetadataForLinking);
expect(rejected).toMatchObject({
reason: "invalid-method-definition-token",
kind: "malformed",
failure: { format: "il2cpp-metadata" },
});
});
it("uses the same truncated-prefix classification before native linking", () => {
const bytes = Buffer.alloc(7);
bytes.writeUInt32LE(0xfab11baf, 0);
@@ -8,7 +8,6 @@ import { withVerifierCleanup } from "../../../scripts/lib/verifier-cleanup.mjs";
import {
AnalysisCancelledError,
AnalysisCapabilityUnavailableError,
AnalysisInputError,
AnalysisResourceConstraintError,
AnalysisUnsupportedTargetError,
} from "../../../src/domain/analysisErrorCore.js";
@@ -918,16 +917,20 @@ it("refuses duplicate MethodDef tokens before publishing linked Evidence or Ghid
{ path, binary_path: binaryPath, detail: "complete" },
{ path: duplicateSeeds },
);
expect(refused.ok).toBe(false);
if (refused.ok)
throw new Error("Duplicate MethodDef identity was accepted");
if (!(refused.error instanceof AnalysisInputError))
throw new Error("Duplicate MethodDef identity was not an input refusal");
expect(refused.error.issues[0]?.message).toContain("invalid-method-token");
expect(refused.error.issues[0]?.message).toContain("share MethodDef token");
expect(refused.error.partialObservation).toMatchObject({
normalized_result: { artifact: { path } },
// The reused row is in the metadata's own records, so the metadata alone
// is malformed; the binary is not named.
expect(projectAnalysisError(refused.error)).toMatchObject({
code: "unsupported_target",
details: {
path,
format: "il2cpp-metadata",
format_failure: "malformed",
reason: expect.stringMatching(/^invalid-method-definition-token:/u),
},
});
expect(projectAnalysisError(refused.error)).not.toHaveProperty("recovery");
await expect(readFile(duplicateSeeds)).rejects.toMatchObject({
code: "ENOENT",
});