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>
This commit is contained in:
authored and GitHub committed 2026-11-19 19:45:26 +00:00
1 parent 2630eff751
commit 7fd50eb361
92 files changed
+4858 -535

No files matched your search

@@ -2,6 +2,7 @@ import { setImmediate } from "node:timers/promises";
import { createHash } from "node:crypto";
import { readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { zstdCompressSync } from "node:zlib";
import { afterEach, expect, it, vi } from "vitest";
import { withVerifierCleanup } from "../../../scripts/lib/verifier-cleanup.mjs";
import {
@@ -17,10 +18,12 @@ import { inspectIl2cppMetadataV108 } from "../../../src/il2cpp/Il2cppMetadataV10
import { Il2cppGhidraSeedWriter } from "../../../src/il2cpp/Il2cppGhidraSeedWriter.js";
import { Il2cppMetadataService } from "../../../src/application/il2cpp/Il2cppMetadataService.js";
import { il2cppMetadataSchema } from "../../../src/domain/il2cpp/il2cppMetadata.js";
import * as zstandard from "../../../src/domain/compression/zstandardExactFrame.js";
import {
createElfFixture,
createIl2cppBinaryFixture,
FIXTURE_GENERIC_INSTANCES,
FIXTURE_METHOD_ADDRESSES,
} from "../../fixtures/il2cpp/binary.js";
import {
createIl2cppMetadataFixture,
@@ -755,6 +758,137 @@ it("accepts cancellation between binary linking batches and keeps the metadata s
}
});
/** Add a compressed ELF64 .shstrtab outside the fixture's PT_LOAD. */
const withCompressedElfNames = (image: Buffer): Buffer => {
const names = Buffer.from("\0.shstrtab\0");
const compressionHeader = Buffer.alloc(24);
compressionHeader.writeUInt32LE(2, 0); // ELFCOMPRESS_ZSTD
compressionHeader.writeBigUInt64LE(BigInt(names.length), 8);
compressionHeader.writeBigUInt64LE(1n, 16);
const payload = Buffer.concat([compressionHeader, zstdCompressSync(names)]);
const padding = Buffer.alloc((8 - (image.length % 8)) % 8);
const tableOffset = image.length + padding.length;
const table = Buffer.alloc(128);
const namesHeader = table.subarray(64);
namesHeader.writeUInt32LE(1, 0); // ".shstrtab" offset in names
namesHeader.writeUInt32LE(3, 4); // SHT_STRTAB
namesHeader.writeBigUInt64LE(0x800n, 8); // SHF_COMPRESSED
namesHeader.writeBigUInt64LE(BigInt(tableOffset + table.length), 24);
namesHeader.writeBigUInt64LE(BigInt(payload.length), 32);
namesHeader.writeBigUInt64LE(1n, 48);
const bytes = Buffer.concat([image, padding, table, payload]);
bytes.writeBigUInt64LE(BigInt(tableOffset), 40);
bytes.writeUInt16LE(64, 58);
bytes.writeUInt16LE(2, 60);
bytes.writeUInt16LE(1, 62);
return bytes;
};
it("retains selected source evidence when cancelled decoding compressed ELF names", async () => {
const root = await createTestTempDirectory("rea-il2cpp-elf-names-cancel-");
const path = join(root, "global-metadata.dat");
const binary_path = join(root, "libil2cpp.so");
const metadata = createLinkedIl2cppMetadataFixture().bytes;
const binary = withCompressedElfNames(
createElfFixture(createIl2cppBinaryFixture()),
);
await Promise.all([
writeFile(path, metadata),
writeFile(binary_path, binary),
]);
const controller = new AbortController();
const reason = new Error("cancel while decoding ELF names");
const decode = zstandard.decodeZstandardFramesCooperative;
const checkpoint = vi
.spyOn(zstandard, "decodeZstandardFramesCooperative")
.mockImplementation((bytes, options, pause) =>
decode(bytes, options, async () => {
controller.abort(reason);
await pause();
}),
);
const provider = new Il2cppMetadataProvider();
try {
const result = await provider.inspect(
{ path, binary_path },
{ signal: controller.signal },
);
if (result.ok) throw new Error("Expected cancellation during ELF decoding");
expect(result.error).toBeInstanceOf(AnalysisCancelledError);
expect(result.error.cause).toBe(reason);
expect(result.error.partialObservation).toMatchObject({
operation: "observe_il2cpp_metadata_source",
normalized_result: {
artifact: { path },
selected_binary: {
path: binary_path,
identity_status: "observed",
bytes: binary.length,
sha256: createHash("sha256").update(binary).digest("hex"),
},
inventory_status: "not-returned-as-complete",
},
});
checkpoint.mockRestore();
const retry = await provider.inspect({ path, binary_path });
if (!retry.ok) throw retry.error;
expect(retry.value.binary?.format).toBe("elf");
expect(retry.value.method_addresses[0]?.address).toBe(
`0x${FIXTURE_METHOD_ADDRESSES[0].toString(16)}`,
);
} finally {
await provider.close();
}
});
it.each([false, true])(
"refuses unsupported generic metadata before reading an invalid ELF directory (signal=%s)",
async (withSignal) => {
const root = await createTestTempDirectory("rea-il2cpp-generic-layout-");
const path = join(root, "global-metadata.dat");
const binary_path = join(root, "libil2cpp.so");
const metadata = createLinkedIl2cppMetadataFixture({ version: 39 }).bytes;
const binary = withCompressedElfNames(
createElfFixture(createIl2cppBinaryFixture()),
);
binary.writeBigUInt64LE(BigInt(binary.length + 8), 40);
await Promise.all([
writeFile(path, metadata),
writeFile(binary_path, binary),
]);
const options = withSignal
? { signal: new AbortController().signal }
: undefined;
const provider = new Il2cppMetadataProvider();
try {
const result = await provider.inspect(
{ path, binary_path, generic_instances: true },
options,
);
expect(result).toMatchObject({
ok: false,
error: {
_tag: "AnalysisUnsupportedTargetError",
reason: expect.stringContaining(
"generic method instances are not decoded for metadata version 39",
),
},
});
const ordinary = await provider.inspect({ path, binary_path }, options);
expect(ordinary).toMatchObject({
ok: false,
error: {
_tag: "AnalysisInputError",
issues: [{ path: ["binary_path"], reason: "invalid_format" }],
},
});
} finally {
await provider.close();
}
},
);
it("refuses duplicate MethodDef tokens before publishing linked Evidence or Ghidra seeds", async () => {
const root = await createTestTempDirectory(
"rea-il2cpp-duplicate-method-token-",