From ac4f65585846fc8542234ce1366b8a251336a790 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sat, 21 Nov 2026 22:51:45 -0500 Subject: [PATCH] perf(native): pre-screen IL2CPP slots and reuse ObjC/PE indices (#13314) --- src/il2cpp/Il2cppBinaryImage.ts | 12 +- src/il2cpp/Il2cppBinaryRegistration.ts | 184 +++++++++++++++++- src/native/AppleObjcClassImportBindings.ts | 7 +- src/native/AppleObjcDispatchFacets.ts | 6 +- src/native/hardening/PeHardening.ts | 5 +- src/native/pe/PeLoadConfigParser.test.ts | 70 ++++++- src/native/pe/PeLoadConfigParser.ts | 56 ++++-- .../il2cpp/il2cppMappingOwnership.test.ts | 72 +++++++ 8 files changed, 379 insertions(+), 33 deletions(-) diff --git a/src/il2cpp/Il2cppBinaryImage.ts b/src/il2cpp/Il2cppBinaryImage.ts index 62eb8290fb..765ff99b6d 100644 --- a/src/il2cpp/Il2cppBinaryImage.ts +++ b/src/il2cpp/Il2cppBinaryImage.ts @@ -10,7 +10,6 @@ import { BinaryReader, BinaryResourceFailure, createFileMappingIndex, - mappedFileOffset, isZeroFilledSpan, type BinaryContainer, type FileMappingIndex, @@ -79,6 +78,8 @@ export interface NativeImage { readonly container: BinaryContainer; /** One image's immutable load mappings, shared by stored and loader-aware reads. */ readonly fileMappings: FileMappingIndex; + /** Indexed executable load mappings for constant/log-time code ownership checks. */ + readonly executableMappings: FileMappingIndex; readonly imageBase: bigint; /** ELF loader writes retain virtual identity; source bytes stay unchanged. */ readonly elfPointerOverlay?: ElfVirtualPointerWrites; @@ -234,6 +235,10 @@ export function* openImageSteps( container.mappings, container.zero_fills, ), + executableMappings: createFileMappingIndex( + container.executable_mappings ?? [], + [], + ), imageBase, ...(elfPointerOverlay === undefined ? {} : { elfPointerOverlay }), ...(machoPointerFixups === undefined ? {} : { machoPointerFixups }), @@ -342,10 +347,7 @@ export const hasPointerArrayCoverage = ( export const isExecutable = (image: NativeImage, address: bigint): boolean => { try { const offset = image.fileMappings.offset(address, 1); - return ( - offset === - mappedFileOffset(image.container.executable_mappings ?? [], address, 1) - ); + return offset === image.executableMappings.offset(address, 1); } catch (cause) { if (cause instanceof BinaryFormatFailure) return false; throw cause; diff --git a/src/il2cpp/Il2cppBinaryRegistration.ts b/src/il2cpp/Il2cppBinaryRegistration.ts index 444585ceff..0b22b57125 100644 --- a/src/il2cpp/Il2cppBinaryRegistration.ts +++ b/src/il2cpp/Il2cppBinaryRegistration.ts @@ -20,6 +20,75 @@ import type { Il2cppCodeGenModule } from "./Il2cppBinaryFile.js"; const TOTAL_NAME_OCCURRENCES = 65536; const SCAN_BYTES = 65536; +const hasLegacyMachoFixups = (image: NativeImage): boolean => + image.machoPointerFixups !== undefined && + image.machoPointerFixups.kind !== "none"; + +const canFastRawMapping = ( + image: NativeImage, + mapping: { + readonly address: bigint; + readonly offset: number; + readonly size: number; + }, + legacyFixups: boolean, + rawBytesLength: number, +): boolean => { + const loaded = + image.elfPointerOverlay?.hasWrites(mapping.address, mapping.size) === true; + return ( + !loaded && + !legacyFixups && + image.stored.little && + mapping.offset >= 0 && + mapping.offset + mapping.size <= rawBytesLength + ); +}; + +/** Unsigned 32-bit little-endian lane without Buffer.readUInt32LE or BigInt allocation. */ +const rawUInt32LE = (bytes: Buffer, offset: number): number => + (bytes[offset]! | + (bytes[offset + 1]! << 8) | + (bytes[offset + 2]! << 16) | + (bytes[offset + 3]! << 24)) >>> + 0; + +interface AddressLaneFilter { + readonly lo32: ReadonlySet; + readonly singleHi32: number | null; +} + +const createAddressLaneFilter = ( + addresses: Iterable, +): AddressLaneFilter => { + const lo32 = new Set(); + let singleHi32: number | null = null; + let multipleHi = false; + for (const address of addresses) { + if (address < 0n || address > 0xffffffff_ffffffffn) continue; + lo32.add(Number(address & 0xffffffffn)); + if (!multipleHi) { + const hi = Number((address >> 32n) & 0xffffffffn); + if (singleHi32 === null) singleHi32 = hi; + else if (singleHi32 !== hi) multipleHi = true; + } + } + return { lo32, singleHi32: multipleHi ? null : singleHi32 }; +}; + +const matchesAddressLane = ( + filter: AddressLaneFilter, + bytes: Buffer, + offset: number, +): boolean => { + if ( + filter.singleHi32 !== null && + rawUInt32LE(bytes, offset + 4) !== filter.singleHi32 + ) + return false; + return filter.lo32.has(rawUInt32LE(bytes, offset)); +}; + /** Index candidates by untouched bytes, retaining bounded representation space. */ const unresolvedPointerMatcher = ( image: NativeImage, @@ -214,11 +283,22 @@ export function* findModules( const unresolvedName = unresolvedPointerMatcher(image, names.keys(), (name) => (names.get(name) ?? []).map((index) => counts[index]!), ); + const rawBytes = image.stored.bytes; + const legacyFixups = hasLegacyMachoFixups(image); + const nameFilter = createAddressLaneFilter(names.keys()); for (const mapping of image.container.mappings) { const start = Number((8n - (mapping.address % 8n)) % 8n); + const fastRaw = canFastRawMapping( + image, + mapping, + legacyFixups, + rawBytes.length, + ); for (let at = start; at + 24 <= mapping.size; at += 8) { if ((at & 0xffff) < 8) yield; const offset = mapping.offset + at; + if (fastRaw && !matchesAddressLane(nameFilter, rawBytes, offset)) + continue; const address = mapping.address + BigInt(at); const raw = image.stored.word(offset, 64); const elfSlot = @@ -351,10 +431,24 @@ export function* findCodeRegistration( const expected = new Set(modules.map((module) => module.address)); const matches: { field: bigint; array: bigint }[] = []; const matchedFields = new Set(); + const rawBytes = image.stored.bytes; + const legacyFixups = hasLegacyMachoFixups(image); + const expectedCount = modules.length; for (const mapping of image.container.mappings) { const start = Number((8n - (mapping.address % 8n)) % 8n); + const fastRaw = canFastRawMapping( + image, + mapping, + legacyFixups, + rawBytes.length, + ); for (let at = start; at + 16 <= mapping.size; at += 8) { if ((at & 0xffff) < 8) yield; + if ( + fastRaw && + rawUInt32LE(rawBytes, mapping.offset + at) !== expectedCount + ) + continue; // The count owns four bytes; the following four only align its pointer. const field = mapping.address + BigInt(at); const count = readUInt32(image, field); @@ -438,10 +532,19 @@ function* findModuleArrayByCode( ): Generator { const arrays = new Set(); const unresolvedModule = unresolvedPointerMatcher(image, expected); + const rawBytes = image.stored.bytes; + const legacyFixups = hasLegacyMachoFixups(image); + const expectedFilter = createAddressLaneFilter(expected); let expectedXor = 0n; for (const candidate of expected) expectedXor ^= candidate; for (const mapping of image.container.mappings) { const start = Number((8n - (mapping.address % 8n)) % 8n); + const fastRaw = canFastRawMapping( + image, + mapping, + legacyFixups, + rawBytes.length, + ); let runStart = start; const lastPosition = new Map(); const possible = new Map(); @@ -451,7 +554,20 @@ function* findModuleArrayByCode( let duplicateValues = 0; for (let at = start; at + 8 <= mapping.size; at += 8) { if ((at & 0xffff) < 8) yield; - const raw = image.stored.word(mapping.offset + at, 64); + const offset = mapping.offset + at; + if (fastRaw && !matchesAddressLane(expectedFilter, rawBytes, offset)) { + if (possible.size !== 0) { + possible.clear(); + occurrences.clear(); + unknownPositions.clear(); + possibleXor = 0n; + duplicateValues = 0; + } + if (lastPosition.size !== 0) lastPosition.clear(); + runStart = at + 8; + continue; + } + const raw = image.stored.word(offset, 64); const address = mapping.address + BigInt(at); const elfSlot = image.elfPointerOverlay === undefined @@ -694,12 +810,28 @@ export function* findMetadataRegistration( // A record whose two counts match is static evidence even when its other // fields are unusable; code is then not asked to stand in for it. let countsMatched = false; + const rawBytes = image.stored.bytes; + const legacyFixups = hasLegacyMachoFixups(image); for (const mapping of image.container.mappings) { const start = Number((8n - (mapping.address % 8n)) % 8n); + const fastRaw = canFastRawMapping( + image, + mapping, + legacyFixups, + rawBytes.length, + ); // The fields used below end at byte 112. The full 128-byte registration // must still have loader coverage, including any declared zero-fill tail. for (let at = start; at + 112 <= mapping.size; at += 8) { if ((at & 0xffff) < 8) yield; + if (fastRaw) { + const off = mapping.offset + at; + if ( + rawUInt32LE(rawBytes, off + 80) !== typeDefinitions || + rawUInt32LE(rawBytes, off + 96) !== typeDefinitions + ) + continue; + } const address = mapping.address + BigInt(at); const fieldCount = readUInt32(image, address + 80n); if (fieldCount !== "unknown" && fieldCount !== typeDefinitions) continue; @@ -875,14 +1007,64 @@ function* findTypeTableByCode( (typeof slot === "bigint" && recordState(slot) === "unknown") ); }; + const rawBytes = image.stored.bytes; + const legacyFixups = hasLegacyMachoFixups(image); + const firstStart = spans[0]?.start ?? 0n; + const lastReach = reach.at(-1) ?? -1n; + const has12ByteSpan = spans.length > 0 && lastReach >= firstStart + 12n; + const bounded64 = + has12ByteSpan && + firstStart >= 0n && + lastReach - 12n <= 0xffffffff_ffffffffn; + const minSpanLo = bounded64 ? Number(firstStart & 0xffffffffn) : 0; + const minSpanHi = bounded64 ? Number(firstStart >> 32n) : 0; + const maxSpanRecordStart = bounded64 ? lastReach - 12n : 0n; + const maxSpanLo = bounded64 ? Number(maxSpanRecordStart & 0xffffffffn) : 0; + const maxSpanHi = bounded64 ? Number(maxSpanRecordStart >> 32n) : 0; + const isPossibleTypePointer = (offset: number): boolean => { + if (!has12ByteSpan || (rawBytes[offset]! & 7) !== 0) return false; + const lo = rawUInt32LE(rawBytes, offset); + const hi = rawUInt32LE(rawBytes, offset + 4); + if (lo === 0 && hi === 0) return false; + if (!bounded64) return true; + if (hi < minSpanHi || hi > maxSpanHi) return false; + if (hi === minSpanHi && lo < minSpanLo) return false; + if (hi === maxSpanHi && lo > maxSpanLo) return false; + return true; + }; for (const mapping of container.mappings) { const start = Number((8n - (mapping.address % 8n)) % 8n); + const fastRaw = canFastRawMapping( + image, + mapping, + legacyFixups, + rawBytes.length, + ); let runStart = -1; let startUnknown = false; let possibleLength = 0; let possibleUnknown = false; for (let at = start; at <= mapping.size; at += 8) { if ((at & 0xffff) < 8) yield; + if ( + fastRaw && + at + 8 <= mapping.size && + !isPossibleTypePointer(mapping.offset + at) + ) { + possibleLength = 0; + possibleUnknown = false; + if (runStart >= 0) { + if ((at - runStart) / 8 >= requiredTypes) { + runs.set( + mapping.address + BigInt(runStart), + startUnknown ? null : (at - runStart) / 8, + ); + if (runs.size > 1) return null; + } + runStart = -1; + } + continue; + } const address = mapping.address + BigInt(at); let endUnknown = at + 8 > mapping.size; if (!endUnknown) { diff --git a/src/native/AppleObjcClassImportBindings.ts b/src/native/AppleObjcClassImportBindings.ts index d1cb04a054..4d36660343 100644 --- a/src/native/AppleObjcClassImportBindings.ts +++ b/src/native/AppleObjcClassImportBindings.ts @@ -76,6 +76,7 @@ export const inspectObjcClassImportBindings = (input: { "Candidate address scan reached the existing max_records limit", ); + const reader = new BinaryReader(bytes, true, "macho-chained-fixup-bindings"); for (const requestedAddress of candidates) { if (examinedAddresses.has(requestedAddress)) continue; examinedAddresses.add(requestedAddress); @@ -89,11 +90,7 @@ export const inspectObjcClassImportBindings = (input: { const offset = layout.offset(parsedAddress, 8); // The loader already resolved this address to an 8-byte slot; the shared reader // repeats the range check and names the format if the slice is short. - const raw = new BinaryReader( - bytes, - true, - "macho-chained-fixup-bindings", - ).word(offset, 64); + const raw = reader.word(offset, 64); const decoded = fixups.decode(parsedAddress, raw); if (decoded.kind === "unsupported") { reasons.add(`${requestedAddress}: ${decoded.reason}`); diff --git a/src/native/AppleObjcDispatchFacets.ts b/src/native/AppleObjcDispatchFacets.ts index 391c498859..c6090e0f96 100644 --- a/src/native/AppleObjcDispatchFacets.ts +++ b/src/native/AppleObjcDispatchFacets.ts @@ -310,13 +310,13 @@ export const decodeObjcDispatchFacets = (input: { } } } - const visited = new Set(); + const visited = new Set(); const readClass = (address: bigint, meta = false) => { - if (address === 0n || visited.has(hex(address)) || !budget.admit()) return; + if (address === 0n || visited.has(address) || !budget.admit()) return; // Coverage counts admitted class objects, including recursively visited // metaclasses, in the same units as the decoded objc_classes rows. classObjectsExamined++; - visited.add(hex(address)); + visited.add(address); const { ro, name } = readLocalClass(read, address); const root = (read.u32(ro) & 2) !== 0; const superclass = resolveSuperclass(read, address, name, failures); diff --git a/src/native/hardening/PeHardening.ts b/src/native/hardening/PeHardening.ts index 7e7fa70149..c4832c786e 100644 --- a/src/native/hardening/PeHardening.ts +++ b/src/native/hardening/PeHardening.ts @@ -19,7 +19,7 @@ import { import { peSubjectArchitecture } from "../../domain/peMachine.js"; import type { PeDataDirectory } from "../../domain/peOptionalHeader.js"; import { readPeImage } from "../../domain/native/peImage.js"; -import { parsePeLoadConfig } from "../pe/PeLoadConfigParser.js"; +import { parsePeLoadConfigFromImage } from "../pe/PeLoadConfigParser.js"; const IMAGE_DLLCHARACTERISTICS_HIGH_ENTROPY_VA = 0x0020; const IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE = 0x0040; @@ -80,8 +80,9 @@ export const readPeHardening = async ( let loadConfig: PeLoadConfig | undefined; let loadConfigFailure = ""; try { - loadConfig = await parsePeLoadConfig( + loadConfig = await parsePeLoadConfigFromImage( bytes, + image, artifact, { path: artifact.path, diff --git a/src/native/pe/PeLoadConfigParser.test.ts b/src/native/pe/PeLoadConfigParser.test.ts index c2e3d7a6b0..4af879f3af 100644 --- a/src/native/pe/PeLoadConfigParser.test.ts +++ b/src/native/pe/PeLoadConfigParser.test.ts @@ -5,7 +5,12 @@ import { peLoadConfigSchema, type PeLoadConfigField, } from "../../domain/native/peLoadConfig.js"; -import { parsePeLoadConfig } from "./PeLoadConfigParser.js"; +import { + parsePeLoadConfig, + parsePeLoadConfigFromImage, +} from "./PeLoadConfigParser.js"; +import { readPeHardening } from "../hardening/PeHardening.js"; +import { readPeImage } from "../../domain/native/peImage.js"; import { PE_LOAD_CONFIG_FIXTURE, peLoadConfigImage, @@ -14,7 +19,11 @@ import { } from "./PeLoadConfig.fixture.js"; /** Element reads of every parsed image's section and mapping tables. */ -const tableReads = vi.hoisted(() => ({ count: 0, budget: Infinity })); +const tableReads = vi.hoisted(() => ({ + count: 0, + budget: Infinity, + imageReads: 0, +})); vi.mock("../../domain/native/peImage.js", async (importOriginal) => { const actual = await importOriginal(); @@ -34,6 +43,7 @@ vi.mock("../../domain/native/peImage.js", async (importOriginal) => { return { ...actual, readPeImage: (bytes: Buffer) => { + tableReads.imageReads++; const image = actual.readPeImage(bytes); return { ...image, @@ -435,3 +445,59 @@ it.each([32, 64] as const)( }); }, ); + +describe("PE load-config reuse and lazy section indexing", () => { + it("skips section and mapping index builds when TLS and load-config directories are absent", async () => { + for (const bits of [32, 64] as const) { + tableReads.count = 0; + const report = await parse({ bits, tls: false, loadConfig: false }); + expect(report).toMatchObject({ tls: null, load_config: null }); + expect(tableReads.count).toBe(0); + } + }); + + it("reuses a pre-parsed PeImage via parsePeLoadConfigFromImage and in readPeHardening", async () => { + const bytes = peLoadConfigImage({ bits: 64 }); + const artifact = { + path: "/sample.exe", + sha256: "a".repeat(64), + bytes: bytes.length, + }; + const input = inspectPeLoadConfigInputSchema.parse({ path: "/sample.exe" }); + const expected = await parsePeLoadConfig(bytes, artifact, input); + + tableReads.imageReads = 0; + const image = readPeImage(bytes); + const fromImage = await parsePeLoadConfigFromImage( + bytes, + image, + artifact, + input, + ); + expect(fromImage).toEqual(expected); + expect(tableReads.imageReads).toBe(1); + + const noDirs = peLoadConfigImage({ tls: false, loadConfig: false }); + tableReads.imageReads = 0; + tableReads.count = 0; + const noDirHardening = await readPeHardening(noDirs, { + path: "/nodirs.exe", + sha256: "a".repeat(64), + bytes: noDirs.length, + }); + expect(tableReads.imageReads).toBe(1); + expect(tableReads.count).toBe(0); + expect( + noDirHardening.rows.find((row) => row.property === "cfg_instrumented") + ?.state, + ).toBe("unknown"); + + tableReads.imageReads = 0; + const withDirHardening = await readPeHardening(bytes, artifact); + expect(tableReads.imageReads).toBe(1); + expect( + withDirHardening.rows.find((row) => row.property === "cfg_instrumented") + ?.state, + ).toBe("enabled"); + }); +}); diff --git a/src/native/pe/PeLoadConfigParser.ts b/src/native/pe/PeLoadConfigParser.ts index 56fe1472cf..e94cbb56a6 100644 --- a/src/native/pe/PeLoadConfigParser.ts +++ b/src/native/pe/PeLoadConfigParser.ts @@ -12,6 +12,7 @@ import { createFileMappingIndex, imageFileMappings, mappedFileOffset, + type FileMappingIndex, } from "../../domain/binaryContainer.js"; import { peDeclaredFileMappings, @@ -127,26 +128,32 @@ const sectionNameIndex = ( }; /** - * Read one PE TLS directory and load configuration without executing the image. - * Yields to the event loop and honors cancellation every - * `ENTRIES_PER_YIELD` callback slots. + * Read one PE TLS directory and load configuration from a parsed PE image + * without executing the image. Yields to the event loop and honors cancellation + * every `ENTRIES_PER_YIELD` callback slots. */ -export const parsePeLoadConfig = async ( +export const parsePeLoadConfigFromImage = async ( bytes: Buffer, + image: PeImage, artifact: PeLoadConfig["artifact"], input: InspectPeLoadConfigInput, signal?: AbortSignal, ): Promise => { assertArtifactReadActive(signal); - const image = readPeImage(bytes); const bits = image.bits; const base = image.image_base; - const lookup = createFileMappingIndex( - imageFileMappings(image), - image.zero_fills, - ); const pointerWidth = bits === 64 ? 8 : 4; const reader = new BinaryReader(bytes, true, "pe"); + // Build section and mapping indices only when directory 9 or 10 exists and needs them. + let mappingIndex: FileMappingIndex | undefined; + const getLookup = (): FileMappingIndex => + (mappingIndex ??= createFileMappingIndex( + imageFileMappings(image), + image.zero_fills, + )); + let cachedSectionName: ((rva: number) => string | null) | undefined; + const sectionName = (rva: number): string | null => + (cachedSectionName ??= sectionNameIndex(image.sections))(rva); const dataDirectory = (index: number): DirectorySpan | null => { const entry = image.pe_data_directories[index]; @@ -166,7 +173,7 @@ export const parsePeLoadConfig = async ( return { rva, size, - file_offset: lookup.offset(base + BigInt(rva), size), + file_offset: getLookup().offset(base + BigInt(rva), size), }; }; @@ -176,15 +183,13 @@ export const parsePeLoadConfig = async ( return delta <= 0xffffffffn ? Number(delta) : null; }; - const sectionName = sectionNameIndex(image.sections); - const locate = (va: bigint): PeLoadConfigLocated => { if (va === 0n) return { va: "0x0", rva: null, file_offset: null, section: null }; const rva = rvaOf(va); let fileOffset: number | null = null; if (rva !== null) { - fileOffset = optionalFileOffset(() => lookup.offset(va, 1)); + fileOffset = optionalFileOffset(() => getLookup().offset(va, 1)); } return { va: hex(va), @@ -202,7 +207,7 @@ export const parsePeLoadConfig = async ( locate, rvaOf, sectionName, - lookup, + lookup: { offset: (address, size) => getLookup().offset(address, size) }, templateFileOffset: (address, size) => optionalFileOffset(() => mappedFileOffset( @@ -227,7 +232,7 @@ export const parsePeLoadConfig = async ( `Load configuration Size ${String(size)} extends beyond the 32-bit RVA space`, ); try { - return lookup.offset(base + BigInt(rva), size); + return getLookup().offset(base + BigInt(rva), size); } catch (cause) { if (cause instanceof BinaryMappingFailure) throw new BinaryFormatFailure( @@ -251,6 +256,27 @@ export const parsePeLoadConfig = async ( }; }; +/** + * Read one PE TLS directory and load configuration without executing the image. + * Yields to the event loop and honors cancellation every + * `ENTRIES_PER_YIELD` callback slots. + */ +export const parsePeLoadConfig = async ( + bytes: Buffer, + artifact: PeLoadConfig["artifact"], + input: InspectPeLoadConfigInput, + signal?: AbortSignal, +): Promise => { + assertArtifactReadActive(signal); + return parsePeLoadConfigFromImage( + bytes, + readPeImage(bytes), + artifact, + input, + signal, + ); +}; + const readTls = async ({ reader, bits, diff --git a/tests/boundary/il2cpp/il2cppMappingOwnership.test.ts b/tests/boundary/il2cpp/il2cppMappingOwnership.test.ts index 5fdb0e1c9e..ad565cab18 100644 --- a/tests/boundary/il2cpp/il2cppMappingOwnership.test.ts +++ b/tests/boundary/il2cpp/il2cppMappingOwnership.test.ts @@ -1,5 +1,6 @@ import { expect, it, vi } from "vitest"; import { + isExecutable, isMapped, openImageSteps, readPointer, @@ -369,3 +370,74 @@ it("composes a UInt32 crossing a known relocation edge with unchanged source byt expect(readUInt32(image, FIXTURE_BINARY_BASE + 0x30en)).toBe(0xccdd0000); expect(readUInt32(image, FIXTURE_BINARY_BASE + 0x30cn)).toBe(1); }); + +it("reuses indexed executable mappings without rescanning container ranges", () => { + const image = open(createIl2cppBinaryFixture()); + const execMappings = image.container.executable_mappings ?? []; + const iteratorSpy = vi.spyOn(execMappings, Symbol.iterator); + try { + for (let index = 0; index < 32; index++) { + expect(isExecutable(image, FIXTURE_BINARY_BASE + 0x200n)).toBe(true); + expect(isExecutable(image, FIXTURE_BINARY_BASE + 0x400n)).toBe(true); + expect(isExecutable(image, FIXTURE_BINARY_BASE + 0x5000n)).toBe(false); + } + expect(iteratorSpy).not.toHaveBeenCalled(); + } finally { + iteratorSpy.mockRestore(); + } +}); + +it("keeps mapping verification before module-name matching and spans above 4 GiB", () => { + // Ambiguous mapping covering a duplicate module record's 8-byte name slot + // must skip that slot via readPointer rather than throwing malformed-container. + const ambiguousMacho = createIl2cppBinaryFixture(); + ambiguousMacho.copy(ambiguousMacho, 0x480, 0x400, 0x418); + ambiguousMacho.writeUInt32LE(2, 16); + ambiguousMacho.writeUInt32LE(144, 20); + const seg2 = 32 + 72; + ambiguousMacho.writeUInt32LE(0x19, seg2); + ambiguousMacho.writeUInt32LE(72, seg2 + 4); + ambiguousMacho.write("__ALIAS", seg2 + 8, "latin1"); + ambiguousMacho.writeBigUInt64LE(FIXTURE_BINARY_BASE + 0x480n, seg2 + 24); + ambiguousMacho.writeBigUInt64LE(8n, seg2 + 32); + ambiguousMacho.writeBigUInt64LE(0x10n, seg2 + 40); + ambiguousMacho.writeBigUInt64LE(8n, seg2 + 48); + ambiguousMacho.writeUInt32LE(1, seg2 + 56); + ambiguousMacho.writeUInt32LE(1, seg2 + 60); + expect(link(ambiguousMacho)).toEqual(link(createIl2cppBinaryFixture())); + + // Move module 0's name string into a second Mach-O segment in another 4 GiB + // window (0x2_0000_0000) while module 1 stays in 0x1_0000_0000, exercising + // multi-high-32-bit lane pre-screening in findModules and findTypeTableByCode. + const baseMacho = createIl2cppBinaryFixture({ + metadataRegistration: false, + adrpAdd: [[0xc20, 0x900]], + }); + const remoteBase = 0x2_0000_1000n; + const nameText = Buffer.from("Assembly-CSharp.dll\0", "utf8"); + const extraPage = Buffer.alloc(0x1000); + nameText.copy(extraPage, 0); + baseMacho.writeBigUInt64LE(remoteBase, 0x400); + baseMacho.fill(0, 0x100, 0x100 + nameText.length); + baseMacho.writeUInt32LE(2, 16); + baseMacho.writeUInt32LE(144, 20); + baseMacho.writeUInt32LE(0x19, seg2); + baseMacho.writeUInt32LE(72, seg2 + 4); + baseMacho.write("__REMOTE", seg2 + 8, "latin1"); + baseMacho.writeBigUInt64LE(remoteBase, seg2 + 24); + baseMacho.writeBigUInt64LE(BigInt(extraPage.length), seg2 + 32); + baseMacho.writeBigUInt64LE(BigInt(baseMacho.length), seg2 + 40); + baseMacho.writeBigUInt64LE(BigInt(extraPage.length), seg2 + 48); + baseMacho.writeUInt32LE(1, seg2 + 56); + baseMacho.writeUInt32LE(1, seg2 + 60); + const full = Buffer.concat([baseMacho, extraPage]); + const linked = linkIl2cppBinary(full, metadata, { + ...facts, + returnTypes: Int32Array.from(facts.returnTypes, () => 3), + }); + expect(linked.types_field).toBeNull(); + expect(linked.types_count).toBe(4); + expect(linked.code_gen_modules[0]?.address).toBe( + FIXTURE_BINARY_BASE + 0x400n, + ); +});