Files
rea/src/il2cpp/Il2cppBinaryFile.ts
T
JANG BYUNGKUNandmorluto 149b43ee61 fix(il2cpp): link arm64 builds whose registrations were inlined (#6989)
* fix(il2cpp): accept arm64 module arrays loaded through adrp/add pairs

A Unity 2022.3 macOS Master (LTO) arm64 build keeps no static CodeRegistration, so the module-array fallback that only decoded x86-64 RIP-relative references reported code-registration-not-found.
The registration owner now also decodes aligned adrp + add pairs in executable ranges and keeps the same exact-module-set and single-reference rules.
A minimal Mach-O fixture failed on the previous reader (47 passed / 1 failed) and passes here with four fail-closed variants (48/48 binary tests).

* fix(il2cpp): name the matched instruction form in inferred module-array limits

The inferred-array limitation always described RIP-relative LEA/MOV, which is wrong for arm64 results.
The provider now names the adrp/add pair on arm64, and the tool contract and docs cover both forms and state that a located array alone does not finish linking a Master build.
The new arm64 provider case failed before the wording change (1 passed / 1 failed) and both cases pass now.

* fix(il2cpp): accept type tables loaded without a static MetadataRegistration

A Unity 2022.3.62f3 macOS Master build inlines MetadataRegistration as well as CodeRegistration, so linking stopped at metadata-registration-not-found after the module array was found. Registration now infers the only field linking reads, the Il2CppType table, from the one run of type-shaped pointers that covers every referenced type index and whose start is loaded by the existing RIP-relative or adrp/add forms; types_field is null and the Evidence is inferred. The new arm64 and x86-64 fixtures failed on the previous reader (52 passed / 2 failed). Four run-selection variants (interior reference, run extended before the loaded address, two loaded runs, run shorter than the referenced indices) keep metadata-registration-not-found; instruction decoding and record-shape checks are not covered by these fixtures.

* test(il2cpp): pin adrp page deltas, register pairing and type-record shape

Every adrp fixture targeted its own 4 KiB page, so dropping the page delta or its sign extension, the add register check, the type-kind bound or the type-definition bound left all binary tests passing. Fixtures now reach a later and an earlier page, pair an add with a different destination or source register, break the type run with an out-of-range kind or type-definition index, and bound type-table candidates when the metadata references few type indices. Each of those five source mutations now fails 1 to 3 of 85 binary and provider tests.

* refactor(il2cpp): share Il2CppType kind decoding and document type-table bounds

The type-table fallback decoded the Il2CppType kind and class/value-type kinds separately from the type namer; both now use the Types owner. Zero and unaligned words are rejected before mapping lookup (Master sample metadata-registration search 92 to 68 ms). Docs and the limitation state that types_count is an upper bound, that a run spanning mappings or a small referenced type range can fail, and credit Cpp2IL StrippedCodeRegSupport and the data-side MetadataRegistration searches of Il2CppDumper and Cpp2IL. Master sample output is unchanged (11,031 code addresses, 37,025 type rows).

* fix(il2cpp): refuse generic instances when the type table was inferred

An inferred type table has no static MetadataRegistration, so the
genericMethodTable it would anchor cannot be located. Report
generic-methods-unsupported instead of reading from a null field.

* fix(il2cpp): fail closed when an inferred type table is not unique

Adversarial review found that the type-table fallback could pick another
type-shaped pointer table when the real one was unloaded or excluded, could
replace a static MetadataRegistration whose counts matched, and accepted a
run cut short by a mapping end. Require exactly one long-enough run in the
image, ending inside its mapping and loaded by code; skip the fallback when a
record's two counts matched; accept only assigned Il2CppTypeEnum kinds; and
look records up through the indexed file mapping so many mappings cannot
multiply the scan. Docs and limitations now describe the run length as at
least every referenced type index rather than an upper bound.

* fix(il2cpp): keep the type-table fallback cheap and its refusals exact

Review follow-ups: check that an address can lie in a mapping before the
throwing indexed lookup, so words pointing into gaps or zero-fill no longer
build an exception each (64 MiB: 74 s to under 2 s); treat a run starting at
its mapping start like one reaching its end; stop at the second long-enough
run instead of a 64-candidate capacity error; ignore ADRP/ADD pairs on
register 31; and say whether a counted MetadataRegistration was unusable or
no code-loaded run was found. Docs no longer generalize from one build or
state tool history they do not source.

* fix(il2cpp): judge type-table slots by their loaded value

The run scan read stored words, so a dyld-bound slot's placeholder could
decide whether a run qualified. Confirm each slot through readSlot and give
a run bounded by a bound or unresolved slot an unknown extent, so the
placeholder no longer changes the choice.

* docs(il2cpp): keep the failure-reason table layout

Shorten the two changed meanings so the table keeps its column widths and the
diff shows only those rows.

* docs(il2cpp): keep the reason table at its formatted width

* fix(il2cpp): read type-table record fields through the loader too

The previous change confirmed table slots through readSlot but still read
each record's kind and definition index from stored bytes. Read them with
readUInt32 and readSlot, and treat a record field the loader binds or leaves
unresolved like an unresolved slot: the run it bounds has an unknown extent.

* perf(il2cpp): share image mappings across loader-aware reads

---------

Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
2026-10-25 04:21:18 +08:00

292 lines
10 KiB
TypeScript

import type { Il2cppMethodAddress } from "../domain/il2cpp/il2cppMetadata.js";
import { Il2cppBinaryFormatFailure } from "./Il2cppBinaryFormat.js";
import { openImageSteps, readSlot, isExecutable } from "./Il2cppBinaryImage.js";
import {
findModules,
findCodeRegistration,
findMetadataRegistration,
} from "./Il2cppBinaryRegistration.js";
import { createTypeNamer } from "./Il2cppBinaryTypes.js";
import {
genericMethodLayouts,
linkGenericMethodsSteps,
type Il2cppGenericMethodLink,
} from "./Il2cppBinaryGenerics.js";
import type {
Il2cppMetadataDecoded,
Il2cppMetadataLinkFacts,
Il2cppMetadataReadOptions,
} from "./Il2cppMetadataFile.js";
/** One linked code-generation module; its name matches a metadata image. */
export interface Il2cppCodeGenModule {
readonly image: number;
readonly address: bigint;
readonly method_pointer_count: number;
readonly method_pointers: bigint;
}
type Il2cppMethodCode = bigint | "no-body" | "unknown";
export interface Il2cppBinaryLink {
readonly format: "elf" | "macho" | "pe";
readonly architecture: string;
readonly image_base: bigint;
/**
* Address of the CodeRegistration codeGenModulesCount field, or null when the
* static registration pair was unresolved and an executable byte-pattern
* candidate identified the array; instruction boundaries remain unverified.
*/
readonly code_gen_modules_field: bigint | null;
/** Address of the code-generation module pointer array. */
readonly code_gen_modules_array: bigint;
readonly code_gen_modules: readonly Il2cppCodeGenModule[];
/**
* Native code address per metadata method index; "no-body" when its module
* slot is zero, "unknown" when its owner or relocated pointer is unresolved.
*/
readonly method_addresses: Il2cppMethodAddress[];
/**
* Address of MetadataRegistration's typesCount field, or null when no static
* registration matched and an executable byte-pattern candidate identified
* the type table; types_count is then the inferred run length, at least
* every referenced type index but not an observed typesCount.
*/
readonly types_field: bigint | null;
readonly types_count: number;
/** Il2CppType table index and display name per method return, field and parameter. */
readonly return_types: Il2cppTypeReference[];
readonly field_types: Il2cppTypeReference[];
readonly parameter_types: Il2cppTypeReference[];
/** Null unless generic instances were requested. */
readonly generic_methods: Il2cppGenericMethodLink | null;
}
export type Il2cppTypeReference = {
readonly type: number;
readonly name: string | null;
};
export type Il2cppBinaryReadOptions = Pick<
Il2cppMetadataReadOptions,
"beforeText" | "onRow"
> & {
/** Also link genericMethodTable rows; unrequested paths read no generic table. */
readonly genericInstances?: boolean;
};
/**
* Link metadata methods to native code addresses without executing the image.
* A method token's row id selects its module's methodPointers slot.
*/
export function* linkIl2cppBinarySteps(
bytes: Buffer,
metadata: Il2cppMetadataDecoded,
facts: Il2cppMetadataLinkFacts,
architecture?: string,
options: Il2cppBinaryReadOptions = {},
): Generator<void, Il2cppBinaryLink> {
const version = metadata.metadata_version;
// Refuse an undecoded version before any table is read.
if (options.genericInstances === true) genericMethodLayouts(version);
yield;
const image = yield* openImageSteps(bytes, architecture);
const modules = yield* findModules(image, metadata);
const registration_ = yield* findCodeRegistration(image, modules);
const methodImage = new Int32Array(metadata.methods.length).fill(-1);
for (const [index, entry] of metadata.images.entries())
for (let offset = 0; offset < entry.type_count; offset++) {
const type = metadata.types[entry.type_start + offset]!;
if (offset % LINK_BATCH === 0) yield;
for (let method = 0; method < type.method_count; method++) {
if (method % LINK_BATCH === 0) yield;
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]!;
// No image range holds this method, so no module slot describes it.
if (owner === -1) return "unknown";
const module = modules[owner]!;
const token = facts.methodTokens[index]!;
const row = token & 0xffffff;
if (token >>> 24 !== 0x06 || row === 0 || 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`,
);
const address = readSlot(
image,
module.method_pointers + BigInt((row - 1) * 8),
);
if (address === null || address === undefined)
throw new Il2cppBinaryFormatFailure(
"invalid-method-pointer",
`module ${metadata.images[owner]!.name} method pointer ${row - 1} is not file mapped`,
);
if (address === "unknown") return "unknown";
if (address === 0n) return "no-body";
if (!isExecutable(image, address))
throw new Il2cppBinaryFormatFailure(
"invalid-method-pointer",
`method ${index} points outside unambiguous executable file data at 0x${address.toString(16)}`,
);
return address;
};
const method_addresses: Il2cppMethodAddress[] = [];
for (let index = 0; index < metadata.methods.length; index++) {
if (index % LINK_BATCH === 0) yield;
const code = methodAddress(index);
if (typeof code === "bigint" && code < image.imageBase)
throw new Il2cppBinaryFormatFailure(
"invalid-method-pointer",
"method address precedes the link image base",
);
const row: Il2cppMethodAddress =
typeof code === "bigint"
? {
state: "code",
address: `0x${code.toString(16)}`,
rva: `0x${(code - image.imageBase).toString(16)}`,
}
: { state: code, address: null, rva: null };
options.onRow?.(row);
method_addresses.push(row);
}
const registration = yield* findMetadataRegistration(
image,
metadata.types.length,
yield* referencedTypeCount(facts),
);
const typeName = createTypeNamer(
image,
metadata,
facts,
version,
options.beforeText,
);
function* reference(type: number): Generator<void, Il2cppTypeReference> {
if (type === -1) return { type, name: null };
if (type < 0 || type >= registration.count)
throw new Il2cppBinaryFormatFailure(
"invalid-type",
`type index ${type} is outside the ${registration.count} binary types`,
);
// 27.0/27.1 and 27.2 share header version 27 but place byref differently.
if (version === 27) return { type, name: null };
const address = readSlot(image, registration.types + BigInt(type * 8));
if (address === "unknown") return { type, name: null };
if (address === null)
throw new Il2cppBinaryFormatFailure(
"invalid-type",
`type ${type} has no mapped type-table slot`,
);
if (address === 0n)
throw new Il2cppBinaryFormatFailure(
"invalid-type",
`type ${type} has no Il2CppType record`,
);
return { type, name: yield* typeName(address, 0) };
}
function* column(types: Int32Array) {
const rows: Il2cppTypeReference[] = [];
for (let index = 0; index < types.length; index++) {
if (index % LINK_BATCH === 0) yield;
const row = yield* reference(types[index]!);
options.onRow?.(row);
rows.push(row);
}
return rows;
}
const return_types = yield* column(facts.returnTypes);
const field_types = yield* column(facts.fieldTypes);
const parameter_types = yield* column(facts.parameterTypes);
const generic_methods =
options.genericInstances === true
? yield* linkGenericMethodsSteps(
image,
metadata,
facts,
registration_.field,
// findMetadataRegistration reports typesCount, word 6.
registration.field === null ? null : registration.field - 48n,
options,
)
: null;
return {
format: image.container.format,
architecture: image.container.architecture,
image_base: image.imageBase,
code_gen_modules_field: registration_.field,
code_gen_modules_array: registration_.array,
code_gen_modules: modules,
method_addresses,
types_field: registration.field,
types_count: registration.count,
return_types,
field_types,
parameter_types,
generic_methods,
};
}
/** One past the highest type index any return, field or parameter references. */
function* referencedTypeCount(
facts: Il2cppMetadataLinkFacts,
): Generator<void, number> {
let count = 0;
for (const types of [
facts.returnTypes,
facts.fieldTypes,
facts.parameterTypes,
])
for (let index = 0; index < types.length; index++) {
if (index % LINK_BATCH === 0) yield;
count = Math.max(count, types[index]! + 1);
}
return count;
}
/** Rows between cooperative yields while linking. */
const LINK_BATCH = 256;
/** Synchronous linking for byte-level callers. */
export const linkIl2cppBinary = (
bytes: Buffer,
metadata: Il2cppMetadataDecoded,
facts: Il2cppMetadataLinkFacts,
architecture?: string,
options: Il2cppBinaryReadOptions = {},
): Il2cppBinaryLink => {
const steps = linkIl2cppBinarySteps(
bytes,
metadata,
facts,
architecture,
options,
);
for (;;) {
const step = steps.next();
if (step.done) return step.value;
}
};