Files
rea/src/il2cpp/Il2cppBinaryImage.ts
T
morluto 7fd50eb361 fix(zstd): share exact-frame Zstandard decoding across ELF and OTA (#12416)
* fix(zstd): share exact-frame Zstandard decoding across ELF and OTA

Walk RFC 8878 frames once so ELF sections, Android OTA REPLACE_ZSTD, and GPU payloads reject truncated headers, blocks, checksums, and trailing bytes on every supported Node runtime. Bound that walk with the runtime zstd.max_frames setting.

* fix(zstd): keep frame output tight and report GPU frame-cap refusals

Copy each Node 22 frame off its decoder chunk before the next frame is decoded. Map a GPU zstd.max_frames refusal through the resource-limit contract instead of a provider failure.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* fix(zstd): keep frame-cap refusals and bad seeds out of malformed results

Project zstd.max_frames through one resource-limit helper for ELF notes, DWARF, GPU, and artifact reads. An invalid REA_ZSTD_MAX_FRAMES seed stays a configuration failure, and frame-header tests cover content size, window, dictionary id, and RLE blocks.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* fix(zstd): yield GPU frame decoding so cancellation can land

The frame-by-frame fallback awaits a caller pause before each data frame. GPU yields and checks the read signal there, so a many-frame payload does not finish before a disconnect is observed.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* fix(zstd): advertise the frame cap and keep strict GPU decode cancellable

List every operation that enforces zstd.max_frames, including GPU, DWARF, and ELF notes. The strict sequence uses the async decoder and checks the caller signal again after it returns, and a single output buffer is not copied a second time.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* fix(zstd): refresh analysis-setting schemas and GPU frame-cap projection

Regenerate the advertised input summaries for inspect_analysis_settings and update_analysis_settings. GPU inventory now throws the projected zstd.max_frames resource limit from payload decode and #retainFailure, so the adjustable setting survives the public failure.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* style(gpu): format the frame-cap projection throw

oxfmt keeps the zstd.max_frames throw in #retainFailure on one line so CI format:check matches the local formatter.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* fix(zstd): yield after the last frame-by-frame GPU decode

The fallback returned success in the same turn as the final synchronous frame, so a queued abort was still invisible to the caller's signal check. Pause once more before that success, matching the strict sequence.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* fix(zstd): yield ELF, OTA, and DWARF frame decoding on the caller signal

The synchronous frame loop ignored abort signals owned by inspect_elf_notes, inspect_dwarf_units, and Android OTA partition reads. Those callers now use the cooperative decoder and yield before Zstandard work, and 32-frame cancellations cover each path.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* fix(zstd): observe cancellation during structural parsing

* fix(zstd): project section-name frame caps at the ELF directory boundary

readElfDirectoryFromBuffer now requires the caller's operation and throws the adjustable zstd.max_frames resource limit. Hardening, unwind, and the other directory consumers keep that typed refusal instead of an adapter or I/O error.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* fix(zstd): preserve optional ELF evidence when frames are capped

* fix(zip): validate Zstandard members through frame completion (#12461)

fix(zip): require complete Zstandard member frames

* fix(elf): yield hardening section name decoding

* fix(elf): yield section names for unwind and export reads

* fix(zstd): yield ELF directory reads that already own a cancellation signal

Hardening, unwind, initializers, exports, kernel modules, debug link, and Android JNI now read section names through the cooperative directory when their caller has a signal. Readers with no signal stay synchronous.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* fix(elf): share one initializer directory and retain its snapshot

* fix(android): reuse the admitted JNI ELF directory

* fix(elf): retain optional debug candidate evidence through cooperative decoding

* fix(zstd): yield ELF section names for Go, Rust, and IL2CPP

These inspections already own an abort signal. Their ELF directory read now uses the cooperative container decoder so a queued cancellation can land during a many-frame section-name table.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* fix(elf): recognize compressed kernel modules before ELF decoding

The cooperative module reader decoded the bytes as ELF before the container check, so gzip, xz, and zstd modules became malformed images. The compression check now returns the unsupported-container report first.

Co-authored-by: morluto <morluto@users.noreply.github.com>

* refactor(elf): classify each container once before reading it

* fix(il2cpp): preserve admission order during cooperative linking

* fix(elf): reuse section-name decoding in debug-link comparison (#12472)

* style(elf): format updated section-reader test calls

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: morluto <morluto@users.noreply.github.com>
2026-11-19 19:45:26 +00:00

396 lines
12 KiB
TypeScript

import { parseFailureFromCause } from "../domain/parseFailure.js";
import { binaryMetadataArchitecture } from "../domain/binaryMetadataArchitecture.js";
import {
IL2CPP_SLICE_SELECTORS,
type Il2cppBinaryArchitecture,
} from "../domain/il2cpp/il2cppMetadata.js";
import {
BinaryFormatFailure,
BinaryMappingFailure,
BinaryResourceFailure,
createFileMappingIndex,
mappedFileOffset,
isZeroFilledSpan,
type BinaryContainer,
type FileMappingIndex,
} from "../domain/binaryContainer.js";
import {
readBinaryContainer,
readBinaryContainerCooperative,
} from "../domain/native/readBinaryContainer.js";
import {
requireSelectedNativeImage,
type SelectedNativeImage,
type SliceSelectionInput,
selectMachoSlice,
} from "../domain/apple/machoSliceSelection.js";
import {
parsePointerFixupsSteps,
type PointerFixups,
} from "../domain/apple/appleMachoFixups.js";
import { parseMachoLayout } from "../domain/apple/appleMachoSelection.js";
import {
readElfPointerValuesSteps,
ElfPointerRelocationFailure,
type ElfVirtualPointerWrites,
} from "../domain/native/elfPointerRelocations.js";
import {
Il2cppBinaryFormatFailure,
IL2CPP_BINARY_BYTES,
} from "./Il2cppBinaryFormat.js";
/** Selection failures name the binary's inputs 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]) => [
selector,
publicName,
]),
),
};
/**
* 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`.
*/
export const requireIl2cppBinaryImage = (
operation: string,
path: string,
bytes: Buffer,
architecture: Il2cppBinaryArchitecture | undefined,
): SelectedNativeImage =>
requireSelectedNativeImage(
operation,
path,
bytes,
architecture === undefined
? undefined
: IL2CPP_SLICE_SELECTORS[architecture],
IL2CPP_SLICE_SELECTION_INPUT,
);
export interface NativeImage {
readonly bytes: Buffer;
readonly container: BinaryContainer;
/** One image's immutable load mappings, shared by stored and loader-aware reads. */
readonly fileMappings: FileMappingIndex;
readonly imageBase: bigint;
/** ELF loader writes retain virtual identity; source bytes stay unchanged. */
readonly elfPointerOverlay?: ElfVirtualPointerWrites;
/** Mach-O loader fixups shared by every native pointer consumer. */
readonly machoPointerFixups?: PointerFixups;
}
const OPERATION = "inspect_il2cpp_metadata";
const rejectContainer = (cause: unknown): never => {
if (cause instanceof BinaryResourceFailure)
throw new Il2cppBinaryFormatFailure(
"native-index-capacity",
cause.message,
cause.failure.limit.maximum,
"bytes",
);
if (cause instanceof BinaryFormatFailure)
throw new Il2cppBinaryFormatFailure(
cause.kind === "unsupported"
? "unsupported-container"
: "malformed-container",
cause.message,
);
throw cause;
};
const readContainer = (image: Buffer): BinaryContainer => {
try {
return readBinaryContainer(image, OPERATION);
} catch (cause) {
return rejectContainer(cause);
}
};
export const readIl2cppBinaryContainerCooperative = async (
image: Buffer,
pause: () => Promise<void>,
): Promise<BinaryContainer> => {
try {
return await readBinaryContainerCooperative(image, OPERATION, pause);
} catch (cause) {
return rejectContainer(cause);
}
};
/** Open one thin image; a universal Mach-O slice is selected before this. */
export function* openImageSteps(
image: Buffer,
preparedContainer?: BinaryContainer,
): Generator<void, NativeImage> {
const container = preparedContainer ?? readContainer(image);
if (container.bits !== 64 || container.byte_order !== "little")
throw new Il2cppBinaryFormatFailure(
"unsupported-container",
`only 64-bit little-endian images are supported, not ${container.bits}-bit ${container.byte_order}-endian`,
);
let elfPointerOverlay: ElfVirtualPointerWrites | undefined;
try {
if (container.format === "elf")
elfPointerOverlay = yield* readElfPointerValuesSteps(
image,
{
bits: 64,
little: true,
machine: container.elf.machine,
dynamicSegments: container.elf.dynamicSegments,
mappings: container.mappings,
zeroFills: container.zero_fills,
},
IL2CPP_BINARY_BYTES,
{ symbolResolution: "image-definitions" },
);
} catch (cause) {
if (cause instanceof ElfPointerRelocationFailure) {
if (cause.failure.kind === "limit" && cause.unit !== undefined)
throw new Il2cppBinaryFormatFailure(
"native-index-capacity",
cause.message,
cause.failure.limit.maximum,
cause.unit,
);
if (cause.reason !== "native-index-capacity")
throw new Il2cppBinaryFormatFailure(cause.reason, cause.message);
}
if (cause instanceof BinaryFormatFailure)
throw new Il2cppBinaryFormatFailure("malformed-container", cause.message);
throw cause;
}
if (container.format === "macho" && container.macho_chained_fixups === true)
throw new Il2cppBinaryFormatFailure(
"unsupported-pointer-encoding",
"Mach-O chained fixups are not decoded",
);
let machoPointerFixups: PointerFixups | undefined;
if (container.format === "macho") {
const selected = selectMachoSlice(image, {
mode: "admitted",
architecture:
binaryMetadataArchitecture(container.architecture) ??
container.architecture,
slice: undefined,
});
// The image is the thin slice already selected; a refusal means the
// container's architecture names no CPU family this reader decodes.
if (!selected.ok)
throw new Il2cppBinaryFormatFailure(
selected.error.kind === "malformed"
? "malformed-container"
: "unsupported-container",
selected.error.message,
);
try {
const layout = parseMachoLayout(image, selected.value);
machoPointerFixups = yield* parsePointerFixupsSteps(
image,
layout.fixups,
layout.segments,
layout.baseAddress,
);
} catch (cause) {
const failure = parseFailureFromCause(cause);
if (failure !== undefined)
throw new Il2cppBinaryFormatFailure(
failure.kind === "unsupported"
? "unsupported-container"
: "malformed-container",
failure.message,
);
throw cause;
}
}
if (container.format === "pe" && container.image_base === undefined)
throw new Il2cppBinaryFormatFailure(
"malformed-container",
"PE image base was not observed",
);
const imageBase =
container.image_base ??
container.mappings.find((mapping) => mapping.offset === 0)?.address ??
container.mappings.reduce<bigint | undefined>(
(lowest, mapping) =>
lowest === undefined || mapping.address < lowest
? mapping.address
: lowest,
undefined,
) ??
0n;
return {
bytes: image,
container,
fileMappings: createFileMappingIndex(
container.mappings,
container.zero_fills,
),
imageBase,
...(elfPointerOverlay === undefined ? {} : { elfPointerOverlay }),
...(machoPointerFixups === undefined ? {} : { machoPointerFixups }),
};
}
/** Stored bytes only; loader interpretation belongs to readSlot. */
const readStoredWord = (image: NativeImage, address: bigint): bigint | null => {
try {
const offset = image.fileMappings.offset(address, 8);
return image.bytes.readBigUInt64LE(offset);
} catch (cause) {
if (cause instanceof BinaryFormatFailure) return null;
throw cause;
}
};
/** A UInt32 field owns four bytes; reading a pointer would also require unrelated padding. */
export const readUInt32 = (
image: NativeImage,
address: bigint,
): number | "unknown" | null => {
if (image.machoPointerFixups?.hasUnresolvedLegacyBytes(address, 4) === true)
return "unknown";
try {
if (image.elfPointerOverlay?.hasWrites(address, 4) === true) {
const value = image.elfPointerOverlay.unsignedAt(address, 4);
return value === undefined ? "unknown" : Number(value);
}
return image.bytes.readUInt32LE(image.fileMappings.offset(address, 4));
} catch (cause) {
if (cause instanceof BinaryFormatFailure) return null;
throw cause;
}
};
/** Exact lowercase hexadecimal form of an address in reports and issues. */
export const hexAddress = (value: bigint) => `0x${value.toString(16)}`;
export const isMapped = (image: NativeImage, address: bigint, size: number) => {
try {
image.fileMappings.offset(address, size);
return true;
} catch (cause) {
if (cause instanceof BinaryFormatFailure) return false;
throw cause;
}
};
// An array of slots that all lack a body can sit wholly in zero-fill (.bss):
// an iOS-only assembly in an Android build has its pointers there.
export const isZeroFilled = (
image: NativeImage,
address: bigint,
size: number,
) =>
isZeroFilledSpan(
image.container.mappings,
image.container.zero_fills,
address,
size,
);
/** Admit readable slots across loader ranges without walking every pointer.
* Each chunk uses the format owner's alias checks; a gap or split slot is refused.
*/
export const hasPointerArrayCoverage = (
image: NativeImage,
address: bigint,
count: number,
): boolean => {
const end = address + BigInt(count) * 8n;
let cursor = address;
while (cursor < end) {
let fileEnd = cursor;
for (const range of image.container.mappings)
if (
range.address <= cursor &&
range.address + BigInt(range.size) > fileEnd
)
fileEnd = range.address + BigInt(range.size);
let coveredEnd = fileEnd;
if (fileEnd === cursor)
for (const range of image.container.zero_fills)
if (range.address <= cursor && range.address + range.size > coveredEnd)
coveredEnd = range.address + range.size;
const stop = coveredEnd < end ? coveredEnd : end;
const size = Number(((stop - cursor) / 8n) * 8n);
if (size <= 0) return false;
try {
if (fileEnd === cursor) {
if (!isZeroFilled(image, cursor, size)) return false;
} else {
image.fileMappings.offset(cursor, size);
}
} catch (cause) {
if (cause instanceof BinaryFormatFailure) return false;
throw cause;
}
cursor += BigInt(size);
}
return true;
};
/** Both executable coverage and the unique full loader mapping must agree. */
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)
);
} catch (cause) {
if (cause instanceof BinaryFormatFailure) return false;
throw cause;
}
};
export const readSlot = (
image: NativeImage,
address: bigint,
): bigint | "unknown" | null => {
try {
if (image.elfPointerOverlay !== undefined) {
const value = image.elfPointerOverlay.unsignedAt(address, 8);
if (value !== undefined) return value;
if (image.elfPointerOverlay.hasWrites(address, 8)) return "unknown";
}
// A successful indexed read already excludes zero-fill aliases. Only a
// non-file-backed slot needs the zero-fill ownership walk.
let raw = readStoredWord(image, address);
if (raw === null && isZeroFilled(image, address, 8)) raw = 0n;
if (raw === null) return null;
if (image.machoPointerFixups !== undefined) {
const resolution = image.machoPointerFixups.decode(address, raw);
if (resolution.kind === "bind" || resolution.kind === "unknown")
return "unknown";
if (resolution.kind === "unsupported")
throw new Il2cppBinaryFormatFailure(
"unsupported-pointer-encoding",
resolution.reason,
);
return resolution.target;
}
return raw;
} catch (cause) {
if (cause instanceof BinaryMappingFailure) return null;
if (cause instanceof BinaryFormatFailure)
throw new Il2cppBinaryFormatFailure("malformed-container", cause.message);
throw cause;
}
};
/** Require an observed resolved pointer; unknown and unmapped slots stay null. */
export const readPointer = (
image: NativeImage,
address: bigint,
): bigint | null => {
const value = readSlot(image, address);
return typeof value === "bigint" ? value : null;
};