mirror of
https://github.com/morluto/rea.git
synced 2026-11-29 09:56:23 +00:00
* feat(artifacts): decode UnityFS LZMA blocks Unity's default AssetBundle compression (type 1) left members as hash_status unavailable. Decode 5-byte Unity LZMA streams with the existing lzma-purejs dependency so inventory can hash and extract them. * fix(compression): read Unity LZMA dictionary via BinaryReader Architecture guards forbid raw Buffer numeric reads outside binaryContainer; match the UEFI LZMA path. * style(compression): format UnityFS LZMA helper * fix(compression): make UnityFS LZMA cancelable and end-marker safe Accept optional LZMA end markers without trailing junk, decode off-thread so timer aborts land, return one expected-sized buffer, and mark xinzexi unverified. * fix(compression): await Unity LZMA worker exit and transfer alone buffer Await worker.terminate() before settling abort/reply paths, and allocate the synthesized alone header with allocUnsafeSlow so the worker receives it without a second encoded-stream copy. * chore: retrigger CI after Greptile worker-exit follow-up * test(compression): clarify Unity LZMA cancellation case title Retriggers Actions after the worker-exit follow-up push did not receive a GitHub Actions check suite. * fix(unityfs): keep the directory for over-budget LZMA blocks and decode spec-valid streams UnityFS writers emit one LZMA block for a whole data stream, so the per-block decode budget refused the whole inventory of any LZMA bundle above 64 MiB, where before this change the directory was retained. An over-budget block now keeps the directory and only members inside it report an unavailable read naming the budget, for LZ4 and LZMA alike. The LZMA decoder window is bounded by the declared output instead of the declared dictionary, so a large dictionary on a small block decodes and no longer allocates a dictionary-sized window. Properties follow the LZMA specification (lc 0-8, lp 0-4, pb 0-4) rather than the LZMA2 lc + lp limit. Worker error events and exits without a reply stay runtime failures instead of being reported as a malformed block. Tests decode a liblzma-produced stream as a known answer, settle only after the worker exits on completion and cancellation, and share one encoder. * fix(artifacts): report Unity LZMA size mismatch as malformed Overflow past the bundle's declared length is a format error, not a decoder budget exhaustion. Declarations above maximumBytes still fail closed as a resource limit before decode starts. * fix(unityfs): name the encoded or decoded bound that refused a block A block refused by its encoded size reported its decoded size against the decoded budget. The block now records which bound refused it, and the member read names that bound, its declared size and the budget. --------- Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
262 lines
8.6 KiB
TypeScript
262 lines
8.6 KiB
TypeScript
/** Synthetic UnityFS (AssetBundle) builders for reader tests. */
|
|
import { lz4LiteralBlock } from "./lz4LiteralBlock.js";
|
|
|
|
import { createRequire } from "node:module";
|
|
|
|
export interface UnityFsMember {
|
|
readonly path: string;
|
|
readonly data: string | Buffer;
|
|
readonly flags?: number;
|
|
readonly offset?: number;
|
|
readonly size?: number;
|
|
}
|
|
|
|
interface UnityFsOptions {
|
|
readonly formatVersion?: number;
|
|
readonly playerVersion?: string;
|
|
readonly engineVersion?: string;
|
|
readonly flags?: number;
|
|
readonly blocksInfoAtEnd?: boolean;
|
|
readonly blocksInfoCompression?: number;
|
|
readonly blockCompression?: number;
|
|
readonly blockSize?: number;
|
|
readonly declaredNodeCount?: number;
|
|
readonly declaredBlockCount?: number;
|
|
readonly encodeBlock?: (data: Buffer) => Buffer;
|
|
}
|
|
|
|
const utf8 = (value: string): Buffer => Buffer.from(value, "utf8");
|
|
const cstring = (value: string): Buffer =>
|
|
Buffer.concat([utf8(value), Buffer.alloc(1)]);
|
|
|
|
const align16 = (value: number): number => (value + 15) & ~15;
|
|
|
|
/** UnityFS LZMA: five property bytes plus the raw stream, no Alone size field. */
|
|
/** Literal and position bits, when a case needs other than Unity's 3/0/2. */
|
|
export interface UnityLzmaBits {
|
|
readonly lc: number;
|
|
readonly lp: number;
|
|
readonly pb: number;
|
|
}
|
|
|
|
const unityLzmaBlock = (
|
|
data: Buffer,
|
|
options?: { readonly endMarker?: boolean; readonly bits?: UnityLzmaBits },
|
|
): Buffer => {
|
|
const require = createRequire(import.meta.url);
|
|
const lzma = require("lzma-purejs") as {
|
|
compressFile(
|
|
input:
|
|
| Buffer
|
|
| {
|
|
readByte(): number;
|
|
read?(buffer: number[], offset: number, length: number): number;
|
|
eof?(): boolean;
|
|
},
|
|
output?: undefined,
|
|
props?: UnityLzmaBits,
|
|
): Buffer | Uint8Array;
|
|
};
|
|
if (!options?.endMarker) {
|
|
const alone = Buffer.from(
|
|
lzma.compressFile(data, undefined, options?.bits),
|
|
);
|
|
return Buffer.concat([alone.subarray(0, 5), alone.subarray(13)]);
|
|
}
|
|
let position = 0;
|
|
const alone = Buffer.from(
|
|
lzma.compressFile({
|
|
readByte() {
|
|
return position < data.length ? data[position++]! : -1;
|
|
},
|
|
read(buffer: number[], offset: number, length: number) {
|
|
let count = 0;
|
|
while (count < length && position < data.length)
|
|
buffer[offset + count++] = data[position++]!;
|
|
return count;
|
|
},
|
|
eof() {
|
|
return position >= data.length;
|
|
},
|
|
}),
|
|
);
|
|
return Buffer.concat([alone.subarray(0, 5), alone.subarray(13)]);
|
|
};
|
|
|
|
/** UnityFS LZMA as Unity writes it: properties, raw stream, no end marker. */
|
|
export const encodeUnityLzma = (data: Buffer, bits?: UnityLzmaBits): Buffer =>
|
|
unityLzmaBlock(data, bits === undefined ? undefined : { bits });
|
|
|
|
/** UnityFS LZMA with an optional end marker still present after the payload. */
|
|
export const encodeUnityLzmaWithEndMarker = (data: Buffer): Buffer =>
|
|
unityLzmaBlock(data, { endMarker: true });
|
|
|
|
/**
|
|
* A UnityFS LZMA block from an independent encoder, liblzma (CPython 3.14
|
|
* `lzma`, FORMAT_RAW LZMA1, lc=3 lp=0 pb=2, 8 MiB dictionary, as UnityPy's
|
|
* `compress_lzma` writes it). liblzma ends a raw LZMA1 stream with an end
|
|
* marker. Decodes to {@link LIBLZMA_UNITY_PLAIN}.
|
|
*/
|
|
export const LIBLZMA_UNITY_BLOCK = Buffer.from(
|
|
"5d00008000002a9b8927786125f45d29c1db00ce05ec45d1a7618bab7542fa5d08205ad3f3151c6ad851cc22bb450623f515d99384334022fef9b8a2bd3e5ccd3b92d043e47220b880870116c6c164fde1407273cbe86828b33a5798daae3c2481da8839682318ad949d020baf84fffd62e000",
|
|
"hex",
|
|
);
|
|
export const LIBLZMA_UNITY_PLAIN = Buffer.concat([
|
|
Buffer.from("UnityFS lzma known-answer payload ".repeat(20)),
|
|
Buffer.from(Array.from({ length: 64 }, (_, index) => index)),
|
|
]);
|
|
|
|
const maybeCompress = (data: Buffer, compression: number): Buffer => {
|
|
if (compression === 1) return unityLzmaBlock(data);
|
|
if (compression === 2 || compression === 3) return lz4LiteralBlock(data);
|
|
return data;
|
|
};
|
|
|
|
interface BlockRecord {
|
|
readonly uncompressedSize: number;
|
|
readonly compressedSize: number;
|
|
readonly flags: number;
|
|
}
|
|
|
|
/** Chunk the virtual stream into blocks the way a producer would. */
|
|
const chunkIntoBlocks = (
|
|
stream: Buffer,
|
|
blockSize: number,
|
|
compression: number,
|
|
encodeBlock?: (data: Buffer) => Buffer,
|
|
): { records: BlockRecord[]; payload: Buffer[] } => {
|
|
const records: BlockRecord[] = [];
|
|
const payload: Buffer[] = [];
|
|
for (
|
|
let offset = 0;
|
|
offset < stream.length || (stream.length === 0 && offset === 0);
|
|
) {
|
|
const uncompressed = stream.subarray(offset, offset + blockSize);
|
|
if (uncompressed.length === 0 && stream.length !== 0) break;
|
|
const compressed =
|
|
encodeBlock?.(uncompressed) ?? maybeCompress(uncompressed, compression);
|
|
records.push({
|
|
uncompressedSize: uncompressed.length,
|
|
compressedSize: compressed.length,
|
|
flags: compression,
|
|
});
|
|
payload.push(compressed);
|
|
offset += blockSize;
|
|
if (stream.length === 0) break;
|
|
}
|
|
return { records, payload };
|
|
};
|
|
|
|
const buildTable = (
|
|
members: readonly UnityFsMember[],
|
|
contents: readonly Buffer[],
|
|
blockRecords: readonly BlockRecord[],
|
|
options: UnityFsOptions,
|
|
): Buffer => {
|
|
let offsets = 0;
|
|
const nodeRecords = members.map((member, index) => {
|
|
const record = {
|
|
offset: member.offset ?? offsets,
|
|
size: member.size ?? contents[index]?.length ?? 0,
|
|
flags: member.flags ?? 0,
|
|
path: member.path,
|
|
};
|
|
offsets += record.size;
|
|
return record;
|
|
});
|
|
const parts: Buffer[] = [Buffer.alloc(16), Buffer.alloc(4)];
|
|
parts[1]!.writeUInt32BE(options.declaredBlockCount ?? blockRecords.length, 0);
|
|
for (const record of blockRecords) {
|
|
const row = Buffer.alloc(10);
|
|
row.writeUInt32BE(record.uncompressedSize, 0);
|
|
row.writeUInt32BE(record.compressedSize, 4);
|
|
row.writeUInt16BE(record.flags, 8);
|
|
parts.push(row);
|
|
}
|
|
const countRow = Buffer.alloc(4);
|
|
countRow.writeUInt32BE(options.declaredNodeCount ?? nodeRecords.length, 0);
|
|
parts.push(countRow);
|
|
for (const record of nodeRecords) {
|
|
const row = Buffer.alloc(20);
|
|
row.writeBigUInt64BE(BigInt(record.offset), 0);
|
|
row.writeBigUInt64BE(BigInt(record.size), 8);
|
|
row.writeUInt32BE(record.flags, 16);
|
|
parts.push(row, cstring(record.path));
|
|
}
|
|
return Buffer.concat(parts);
|
|
};
|
|
|
|
export const buildUnityFs = (
|
|
members: readonly UnityFsMember[],
|
|
options: UnityFsOptions = {},
|
|
): Buffer => {
|
|
const formatVersion = options.formatVersion ?? 8;
|
|
const playerVersion = options.playerVersion ?? "5.x.x";
|
|
const engineVersion = options.engineVersion ?? "2021.3.32f1c1";
|
|
const blockCompression = options.blockCompression ?? 3;
|
|
const blocksInfoCompression = options.blocksInfoCompression ?? 3;
|
|
const blockSize = options.blockSize ?? 131072;
|
|
const blocksInfoAtEnd = options.blocksInfoAtEnd ?? false;
|
|
const flags =
|
|
options.flags ??
|
|
blocksInfoCompression |
|
|
(blocksInfoAtEnd ? 0x80 : 0) |
|
|
(formatVersion >= 7 ? 0x200 : 0) |
|
|
0x40;
|
|
|
|
const contents = members.map(({ data }) =>
|
|
typeof data === "string" ? utf8(data) : data,
|
|
);
|
|
const { records: blockRecords, payload: compressedBlocks } = chunkIntoBlocks(
|
|
Buffer.concat(contents),
|
|
blockSize,
|
|
blockCompression,
|
|
options.encodeBlock,
|
|
);
|
|
const table = buildTable(members, contents, blockRecords, options);
|
|
const compressedTable = maybeCompress(table, blocksInfoCompression);
|
|
|
|
const headerPrefix = Buffer.concat([
|
|
Buffer.from("UnityFS\0", "latin1"),
|
|
Buffer.alloc(4),
|
|
]);
|
|
headerPrefix.writeUInt32BE(formatVersion, 8);
|
|
const headerStrings = Buffer.concat([
|
|
cstring(playerVersion),
|
|
cstring(engineVersion),
|
|
]);
|
|
let position = headerPrefix.length + headerStrings.length + 20;
|
|
if (formatVersion >= 7) position = align16(position);
|
|
|
|
const dataArea = Buffer.concat(compressedBlocks);
|
|
let dataStart: number;
|
|
let blocksInfoOffset: number;
|
|
if (blocksInfoAtEnd) {
|
|
dataStart = position;
|
|
blocksInfoOffset = position + dataArea.length;
|
|
} else {
|
|
blocksInfoOffset = position;
|
|
dataStart =
|
|
(flags & 0x200) !== 0
|
|
? align16(position + compressedTable.length)
|
|
: position + compressedTable.length;
|
|
}
|
|
const totalSize = Math.max(
|
|
dataStart + dataArea.length,
|
|
blocksInfoAtEnd ? blocksInfoOffset + compressedTable.length : 0,
|
|
dataStart,
|
|
);
|
|
|
|
const file = Buffer.alloc(totalSize);
|
|
headerPrefix.copy(file, 0);
|
|
headerStrings.copy(file, headerPrefix.length);
|
|
const fixed = headerPrefix.length + headerStrings.length;
|
|
file.writeBigUInt64BE(BigInt(totalSize), fixed);
|
|
file.writeUInt32BE(compressedTable.length, fixed + 8);
|
|
file.writeUInt32BE(table.length, fixed + 12);
|
|
file.writeUInt32BE(flags, fixed + 16);
|
|
compressedTable.copy(file, blocksInfoOffset);
|
|
dataArea.copy(file, dataStart);
|
|
return file;
|
|
};
|