From 3dc80be5ba5a8c6554dd1e4bd485ed9ca1483e04 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 08:32:11 -0500 Subject: [PATCH] ws-arch: codecs/Lzma: LZMA / LZMA2 decoders, .lzma (alone), the xz container (checks none / CRC-32 / CRC-64, BCJ x86 / PPC / ARM / ARMT / SPARC / ARM64 + delta filters, multi-block / multi-stream); tests against liblzma --- src/Formats/codecs/Lzma/Crc64.luau | 37 ++ src/Formats/codecs/Lzma/Decode.luau | 492 ++++++++++++++++++++++ src/Formats/codecs/Lzma/Filters.luau | 177 ++++++++ src/Formats/codecs/Lzma/init.luau | 601 +++++++++++++++++++++++++++ tests/codecs/lzma.luau | 142 +++++++ tools/fixtures/lzma.py | 105 +++++ 6 files changed, 1554 insertions(+) create mode 100644 src/Formats/codecs/Lzma/Crc64.luau create mode 100644 src/Formats/codecs/Lzma/Decode.luau create mode 100644 src/Formats/codecs/Lzma/Filters.luau create mode 100644 src/Formats/codecs/Lzma/init.luau create mode 100644 tests/codecs/lzma.luau create mode 100644 tools/fixtures/lzma.py diff --git a/src/Formats/codecs/Lzma/Crc64.luau b/src/Formats/codecs/Lzma/Crc64.luau new file mode 100644 index 0000000..19f682f --- /dev/null +++ b/src/Formats/codecs/Lzma/Crc64.luau @@ -0,0 +1,37 @@ +--!strict +--!native +--!optimize 2 +-- codecs/Lzma/Crc64: CRC-64/XZ (ECMA-182 polynomial, reflected: 0xC96C5795D7870F42), the xz check type 4. The 64-bit +-- value is kept as two u32 halves (hi, lo). Written from the xz file format specification. Never throws. +local band, bxor, rshift, lshift, bor = bit32.band, bit32.bxor, bit32.rshift, bit32.lshift, bit32.bor +local readu8 = buffer.readu8 + +local THI, TLO = table.create(256, 0), table.create(256, 0) +for n = 0, 255 do + local hi, lo = 0, n + for _ = 1, 8 do + local low = band(lo, 1) + lo = bor(rshift(lo, 1), lshift(band(hi, 1), 31)) + hi = rshift(hi, 1) + if low ~= 0 then + hi = bxor(hi, 0xC96C5795) + lo = bxor(lo, 0xD7870F42) + end + end + THI[n + 1], TLO[n + 1] = hi, lo +end + +local Crc64 = {} + +-- of(buf, offset, length) -> hi, lo +function Crc64.of(b: buffer, o: number, n: number): (number, number) + local hi, lo = 0xFFFFFFFF, 0xFFFFFFFF + for i = o, o + n - 1 do + local idx = band(bxor(lo, readu8(b, i)), 255) + 1 + lo = bxor(TLO[idx], bor(rshift(lo, 8), lshift(band(hi, 255), 24))) + hi = bxor(THI[idx], rshift(hi, 8)) + end + return bxor(hi, 0xFFFFFFFF), bxor(lo, 0xFFFFFFFF) +end + +return Crc64 diff --git a/src/Formats/codecs/Lzma/Decode.luau b/src/Formats/codecs/Lzma/Decode.luau new file mode 100644 index 0000000..51be654 --- /dev/null +++ b/src/Formats/codecs/Lzma/Decode.luau @@ -0,0 +1,492 @@ +--!strict +--!native +--!optimize 2 +-- codecs/Lzma/Decode: the LZMA range decoder and LZ state machine, shared by raw LZMA (.lzma, 7z) and LZMA2 (xz, 7z). +-- Written from the LZMA specification and its reference decoder (LzmaSpec.cpp, Igor Pavlov, public domain); the +-- structure (probability model layout, state transitions, distance / length decoding) follows that document. +-- +-- The output buffer is also the dictionary: everything decoded stays in memory, so a match may reach back to the last +-- dictionary reset (st.dictStart). A decoder state (new) carries the probabilities, the LZ state, the four rep +-- distances, a pending match remainder (st.remLen) and the range coder across calls, so LZMA2 can feed it chunk by +-- chunk. run() decodes until st.op reaches outEnd, an end marker, or an error. +-- +-- Never throws: every input read is bounds-checked (a read past the end counts in `over` and fails the call as +-- "truncated"), every output write is preceded by a capacity check, and errors return nil, message. +local readu8, readu16, writeu8, writeu16 = buffer.readu8, buffer.readu16, buffer.writeu8, buffer.writeu16 +local bcreate, bcopy, blen = buffer.create, buffer.copy, buffer.len +local rshift, band = bit32.rshift, bit32.band + +-- probability offsets (u16 entries) +local IS_MATCH = 0 -- 12 states x 16 pos states +local IS_REP = 192 +local IS_REP_G0 = 204 +local IS_REP_G1 = 216 +local IS_REP_G2 = 228 +local IS_REP0_LONG = 240 -- 12 x 16 +local POS_SLOT = 432 -- 4 x 64 +local SPEC_POS = 688 -- 115 +local ALIGN = 803 -- 16 +local LEN = 819 -- choice, choice2, low 16 x 8, mid 16 x 8, high 256 +local REP_LEN = 1333 +local LITERAL = 1847 -- 0x300 << (lc + lp) + +local TOP = 16777216 -- 2^24 + +local Decode = {} + +export type State = { + out: buffer, + cap: number, + op: number, -- bytes decoded so far (the next write offset) + dictStart: number, -- the last dictionary reset: matches may not reach before it + maxBytes: number, + probs: buffer, + nprobs: number, + lc: number, + lp: number, + pb: number, + state: number, + rep0: number, + rep1: number, + rep2: number, + rep3: number, + remLen: number, -- a match cut by outEnd, finished by the next run + range: number, + code: number, +} + +-- new(cap, maxBytes) -> a decoder state with an empty output buffer of capacity cap +function Decode.new(cap: number, maxBytes: number): State + local c = math.max(64, math.min(cap, maxBytes)) + return { + out = bcreate(c), + cap = c, + op = 0, + dictStart = 0, + maxBytes = maxBytes, + probs = bcreate(2), + nprobs = 0, + lc = 0, + lp = 0, + pb = 0, + state = 0, + rep0 = 0, + rep1 = 0, + rep2 = 0, + rep3 = 0, + remLen = 0, + range = 0xFFFFFFFF, + code = 0, + } +end + +-- setProps(st, lc, lp, pb) -> ok, message?: new literal / position parameters (resets the probabilities) +function Decode.setProps(st: State, lc: number, lp: number, pb: number): (boolean, string?) + if lc > 8 or lp > 4 or pb > 4 or lc < 0 or lp < 0 or pb < 0 then + return false, "bad lc / lp / pb" + end + st.lc, st.lp, st.pb = lc, lp, pb + local n = LITERAL + 0x300 * 2 ^ (lc + lp) + if blen(st.probs) < n * 2 then + st.probs = bcreate(n * 2) + end + st.nprobs = n + Decode.resetState(st) + return true, nil +end + +-- resetState(st): probabilities to 1/2, LZ state and reps to 0 +function Decode.resetState(st: State) + local p = st.probs + for i = 0, st.nprobs - 1 do + writeu16(p, i * 2, 1024) + end + st.state = 0 + st.rep0, st.rep1, st.rep2, st.rep3 = 0, 0, 0, 0 + st.remLen = 0 +end + +-- resetDict(st): matches may no longer reach before the current position +function Decode.resetDict(st: State) + st.dictStart = st.op + st.remLen = 0 +end + +-- rcInit(st, buf, ip, iend) -> next ip | nil, message: the 5 range coder init bytes +function Decode.rcInit(st: State, b: buffer, ip: number, iend: number): (number?, string?) + if ip + 5 > iend then + return nil, "truncated range coder init" + end + if readu8(b, ip) ~= 0 then + return nil, "bad range coder init byte" + end + st.code = readu8(b, ip + 1) * 16777216 + readu8(b, ip + 2) * 65536 + readu8(b, ip + 3) * 256 + readu8(b, ip + 4) + st.range = 0xFFFFFFFF + if st.code == st.range then + return nil, "bad range coder init" + end + return ip + 5, nil +end + +-- ensure(st, need) -> ok: grow the output to hold need bytes (bounded by maxBytes) +local function ensure(st: State, need: number): boolean + if need <= st.cap then + return true + end + if need > st.maxBytes then + return false + end + local c = math.min(math.max(st.cap * 2, need, 65536), st.maxBytes) + local nb = bcreate(c) + bcopy(nb, 0, st.out, 0, st.op) + st.out = nb + st.cap = c + return true +end +Decode.ensure = ensure + +-- copy(st, n, b, ip): append n stored bytes (LZMA2 uncompressed chunks); the caller checked the input range +function Decode.copy(st: State, n: number, b: buffer, ip: number): (boolean, string?) + if not ensure(st, st.op + n) then + return false, "limit: output over maxBytes" + end + bcopy(st.out, st.op, b, ip, n) + st.op += n + return true, nil +end + +-- the range decoder state while run() executes (module upvalues: the helpers below are created once, so LuaJIT +-- traces stay valid across calls; run() is not re-entrant, and never yields) +local EMPTY = bcreate(2) +local probs: buffer = EMPTY +local inb: buffer = EMPTY +local range, code, ip, iend, over = 0, 0, 0, 0, 0 + +-- decode one bit with the probability at index i +local function bit(i: number): number + local p = i * 2 + local prob = readu16(probs, p) + local bound = rshift(range, 11) * prob + local r + if code < bound then + range = bound + writeu16(probs, p, prob + rshift(2048 - prob, 5)) + r = 0 + else + range -= bound + code -= bound + writeu16(probs, p, prob - rshift(prob, 5)) + r = 1 + end + if range < TOP then + range *= 256 + if ip < iend then + code = code * 256 + readu8(inb, ip) + else + code *= 256 + over += 1 + end + ip += 1 + end + return r +end + +local function tree(base: number, nbits: number): number + local m = 1 + for _ = 1, nbits do + m = m * 2 + bit(base + m) + end + return m - 2 ^ nbits +end + +local function reverse(base: number, nbits: number): number + local m = 1 + local sym = 0 + for i = 0, nbits - 1 do + local b = bit(base + m) + m = m * 2 + b + sym += b * 2 ^ i + end + return sym +end + +local function direct(nbits: number): number + local res = 0 + for _ = 1, nbits do + range = rshift(range, 1) + local b = 0 + if code >= range then + code -= range + b = 1 + end + res = res * 2 + b + if range < TOP then + range *= 256 + if ip < iend then + code = code * 256 + readu8(inb, ip) + else + code *= 256 + over += 1 + end + ip += 1 + end + end + return res +end + +local function length(base: number, posState: number): number + if bit(base) == 0 then + return tree(base + 2 + posState * 8, 3) + end + if bit(base + 1) == 0 then + return 8 + tree(base + 130 + posState * 8, 3) + end + return 16 + tree(base + 258, 8) +end + +-- run(st, buf, ip, iend, outEnd) -> status, ip | nil, message. status: "full" (st.op reached outEnd) or "eos" (end +-- marker). The range coder must have been initialised (rcInit). +function Decode.run(st: State, inb0: buffer, ip0: number, iend0: number, outEnd: number): (string?, any) + probs = st.probs + inb = inb0 + iend = iend0 + local out = st.out + local cap = st.cap + local op = st.op + local dictStart = st.dictStart + range, code = st.range, st.code + ip = ip0 + over = 0 + local state = st.state + local rep0, rep1, rep2, rep3 = st.rep0, st.rep1, st.rep2, st.rep3 + local lc = st.lc + local lcShift = 2 ^ (8 - lc) + local lpMask = 2 ^ st.lp - 1 + local pbMask = 2 ^ st.pb - 1 + local lcMul = 2 ^ lc + + local status: string? = nil + local msg: string? = nil + + -- a pending match from the previous call + local remLen = st.remLen + if remLen > 0 then + local n = math.min(remLen, outEnd - op) + if n > 0 then + if op + n > cap then + st.op = op + if not ensure(st, op + n) then + probs, inb = EMPTY, EMPTY + return nil, "limit: output over maxBytes" + end + out, cap = st.out, st.cap + end + local src = op - rep0 - 1 + for k = 0, n - 1 do + writeu8(out, op + k, readu8(out, src + k)) + end + op += n + remLen -= n + end + end + + while true do + if op >= outEnd then + status = "full" + break + end + if over > 0 then + msg = "truncated" + break + end + if op + 273 > cap then + st.op = op + if not ensure(st, math.min(op + 273, outEnd)) then + msg = "limit: output over maxBytes" + break + end + out, cap = st.out, st.cap + end + local pos = op - dictStart + local posState = band(pos, pbMask) + -- is match? (inlined bit) + local pidx = (IS_MATCH + state * 16 + posState) * 2 + local prob = readu16(probs, pidx) + local bound = rshift(range, 11) * prob + if code < bound then + range = bound + writeu16(probs, pidx, prob + rshift(2048 - prob, 5)) + if range < TOP then + range *= 256 + if ip < iend then + code = code * 256 + readu8(inb, ip) + else + code *= 256 + over += 1 + end + ip += 1 + end + -- literal + local prev = if op > dictStart then readu8(out, op - 1) else 0 + local base = LITERAL + 0x300 * (band(pos, lpMask) * lcMul + prev // lcShift) + local sym = 1 + if state >= 7 then + local mpos = op - rep0 - 1 + local matchByte = if mpos >= dictStart then readu8(out, mpos) else 0 + repeat + local matchBit = band(rshift(matchByte, 7), 1) + matchByte *= 2 + local b = bit(base + (1 + matchBit) * 256 + sym) + sym = sym * 2 + b + if matchBit ~= b then + break + end + until sym >= 256 + end + while sym < 256 do + local p2 = (base + sym) * 2 + local pr = readu16(probs, p2) + local bd = rshift(range, 11) * pr + if code < bd then + range = bd + writeu16(probs, p2, pr + rshift(2048 - pr, 5)) + sym = sym * 2 + else + range -= bd + code -= bd + writeu16(probs, p2, pr - rshift(pr, 5)) + sym = sym * 2 + 1 + end + if range < TOP then + range *= 256 + if ip < iend then + code = code * 256 + readu8(inb, ip) + else + code *= 256 + over += 1 + end + ip += 1 + end + end + writeu8(out, op, sym - 256) + op += 1 + state = if state < 4 then 0 elseif state < 10 then state - 3 else state - 6 + else + range -= bound + code -= bound + writeu16(probs, pidx, prob - rshift(prob, 5)) + if range < TOP then + range *= 256 + if ip < iend then + code = code * 256 + readu8(inb, ip) + else + code *= 256 + over += 1 + end + ip += 1 + end + local len + if bit(IS_REP + state) == 0 then + -- simple match + len = length(LEN, posState) + state = if state < 7 then 7 else 10 + rep3, rep2, rep1 = rep2, rep1, rep0 + local lenState = if len < 3 then len else 3 + local slot = tree(POS_SLOT + lenState * 64, 6) + if slot < 4 then + rep0 = slot + else + local nd = slot // 2 - 1 + local dist = (2 + slot % 2) * 2 ^ nd + if slot < 14 then + dist += reverse(SPEC_POS + dist - slot, nd) + else + dist += direct(nd - 4) * 16 + dist += reverse(ALIGN, 4) + end + rep0 = dist + end + if rep0 == 0xFFFFFFFF then + status = "eos" + break + end + else + if bit(IS_REP_G0 + state) == 0 then + if bit(IS_REP0_LONG + state * 16 + posState) == 0 then + -- short rep: one byte at rep0 + if op == dictStart or rep0 >= op - dictStart then + msg = "distance past the dictionary start" + break + end + state = if state < 7 then 9 else 11 + writeu8(out, op, readu8(out, op - rep0 - 1)) + op += 1 + continue + end + else + local dist + if bit(IS_REP_G1 + state) == 0 then + dist = rep1 + else + if bit(IS_REP_G2 + state) == 0 then + dist = rep2 + else + dist = rep3 + rep3 = rep2 + end + rep2 = rep1 + end + rep1 = rep0 + rep0 = dist + end + len = length(REP_LEN, posState) + state = if state < 7 then 8 else 11 + end + -- copy len + 2 bytes from rep0 + 1 back + if rep0 >= op - dictStart then + msg = "distance past the dictionary start" + break + end + local n = len + 2 + local room = outEnd - op + if n > room then + remLen = n - room + n = room + end + local src = op - rep0 - 1 + if rep0 + 1 >= n then + bcopy(out, op, out, src, n) + else + for k = 0, n - 1 do + writeu8(out, op + k, readu8(out, src + k)) + end + end + op += n + end + end + st.op = op + st.range, st.code = range, code + st.state = state + st.rep0, st.rep1, st.rep2, st.rep3 = rep0, rep1, rep2, rep3 + st.remLen = remLen + probs, inb = EMPTY, EMPTY -- do not keep the caller's buffers alive + if msg then + return nil, msg + end + if over > 0 then + return nil, "truncated" + end + return status, ip +end + +-- finish(st) -> a buffer of exactly the decoded bytes +function Decode.finish(st: State): buffer + if st.cap == st.op then + return st.out + end + local b = bcreate(st.op) + bcopy(b, 0, st.out, 0, st.op) + return b +end + +return Decode diff --git a/src/Formats/codecs/Lzma/Filters.luau b/src/Formats/codecs/Lzma/Filters.luau new file mode 100644 index 0000000..60a5d59 --- /dev/null +++ b/src/Formats/codecs/Lzma/Filters.luau @@ -0,0 +1,177 @@ +--!strict +--!native +--!optimize 2 +-- codecs/Lzma/Filters: the branch-call-jump (BCJ) and delta decoding filters of xz and 7z, run in place over a whole +-- decoded buffer range. Written from the xz file format specification and xz-embedded's xz_dec_bcj.c (Lasse Collin, +-- public domain): x86, ARM, ARM-Thumb, PowerPC, SPARC, ARM64 and delta. Not supported: IA-64, RISC-V. +-- Never throws: every access is inside [o, o + n). +local readu8, writeu8, readu32, writeu32 = buffer.readu8, buffer.writeu8, buffer.readu32, buffer.writeu32 +local band, bor, bxor, rshift, lshift, byteswap = bit32.band, bit32.bor, bit32.bxor, bit32.rshift, bit32.lshift, bit32.byteswap + +local TWO32 = 4294967296 + +local Filters = {} + +local MASK_ALLOWED = { [0] = true, true, true, false, true, false, false, false } +local MASK_BITNUM = { [0] = 0, 1, 2, 2, 3, 3, 3, 3 } + +local function msbyte(b: number): boolean + return b == 0 or b == 0xFF +end + +-- x86(b, o, n, start): BCJ x86 decode; start = the stream position of b[o] (the filter's start offset) +function Filters.x86(b: buffer, o: number, n: number, start: number) + if n <= 4 then + return + end + local size = n - 4 + local prevPos = -1 + local prevMask = 0 + local i = 0 + while i < size do + local c = readu8(b, o + i) + if band(c, 0xFE) ~= 0xE8 then + i += 1 + continue + end + local d = i - prevPos + if d > 3 then + prevMask = 0 + else + prevMask = band(lshift(prevMask, d - 1), 7) + if prevMask ~= 0 then + local bb = readu8(b, o + i + 4 - MASK_BITNUM[prevMask]) + if not MASK_ALLOWED[prevMask] or msbyte(bb) then + prevPos = i + prevMask = bor(lshift(prevMask, 1), 1) + i += 1 + continue + end + end + end + prevPos = i + if msbyte(readu8(b, o + i + 4)) then + local src = readu32(b, o + i + 1) + local dest + while true do + dest = (src - (start + i + 5)) % TWO32 + if prevMask == 0 then + break + end + local j = MASK_BITNUM[prevMask] * 8 + local bb = band(rshift(dest, 24 - j), 0xFF) + if not msbyte(bb) then + break + end + src = bxor(dest, 2 ^ (32 - j) - 1) + end + dest = band(dest, 0x01FFFFFF) + if band(dest, 0x01000000) ~= 0 then + dest = bor(dest, 0xFF000000) + end + writeu32(b, o + i + 1, dest) + i += 5 + else + prevMask = bor(lshift(prevMask, 1), 1) + i += 1 + end + end +end + +function Filters.arm(b: buffer, o: number, n: number, start: number) + local i = 0 + while i + 4 <= n do + if readu8(b, o + i + 3) == 0xEB then + local addr = readu8(b, o + i) + readu8(b, o + i + 1) * 256 + readu8(b, o + i + 2) * 65536 + addr = (addr * 4 - (start + i + 8)) % TWO32 + addr = rshift(addr, 2) + writeu8(b, o + i, band(addr, 255)) + writeu8(b, o + i + 1, band(rshift(addr, 8), 255)) + writeu8(b, o + i + 2, band(rshift(addr, 16), 255)) + end + i += 4 + end +end + +function Filters.armthumb(b: buffer, o: number, n: number, start: number) + local i = 0 + while i + 4 <= n do + local b1, b3 = readu8(b, o + i + 1), readu8(b, o + i + 3) + if band(b1, 0xF8) == 0xF0 and band(b3, 0xF8) == 0xF8 then + local addr = band(b1, 7) * 524288 + readu8(b, o + i) * 2048 + band(b3, 7) * 256 + readu8(b, o + i + 2) + addr = (addr * 2 - (start + i + 4)) % TWO32 + addr = rshift(addr, 1) + writeu8(b, o + i + 1, bor(0xF0, band(rshift(addr, 19), 7))) + writeu8(b, o + i, band(rshift(addr, 11), 255)) + writeu8(b, o + i + 3, bor(0xF8, band(rshift(addr, 8), 7))) + writeu8(b, o + i + 2, band(addr, 255)) + i += 4 + else + i += 2 + end + end +end + +function Filters.powerpc(b: buffer, o: number, n: number, start: number) + local i = 0 + while i + 4 <= n do + local instr = byteswap(readu32(b, o + i)) + if band(instr, 0xFC000003) == 0x48000001 then + instr = band(instr, 0x03FFFFFC) + instr = band((instr - (start + i)) % TWO32, 0x03FFFFFC) + instr = bor(instr, 0x48000001) + writeu32(b, o + i, byteswap(instr)) + end + i += 4 + end +end + +function Filters.sparc(b: buffer, o: number, n: number, start: number) + local i = 0 + while i + 4 <= n do + local instr = byteswap(readu32(b, o + i)) + local top = rshift(instr, 22) + if top == 0x100 or top == 0x1FF then + instr = (instr * 4) % TWO32 + instr = (instr - (start + i)) % TWO32 + instr = rshift(instr, 2) + instr = bor((0x40000000 - band(instr, 0x400000)) % TWO32, 0x40000000, band(instr, 0x3FFFFF)) + writeu32(b, o + i, byteswap(instr)) + end + i += 4 + end +end + +function Filters.arm64(b: buffer, o: number, n: number, start: number) + local i = 0 + while i + 4 <= n do + local pc = (start + i) % TWO32 + local instr = readu32(b, o + i) + if rshift(instr, 26) == 0x25 then + local src = instr + local p = (TWO32 - rshift(pc, 2)) % TWO32 + writeu32(b, o + i, bor(0x94000000, band((src + p) % TWO32, 0x03FFFFFF))) + elseif band(instr, 0x9F000000) == 0x90000000 then + local src = bor(band(rshift(instr, 29), 3), band(rshift(instr, 3), 0x001FFFFC)) + if band(src + 0x00020000, 0x001C0000) == 0 then + local p = (TWO32 - rshift(pc, 12)) % TWO32 + local dest = (src + p) % TWO32 + local v = band(instr, 0x9000001F) + v = bor(v, lshift(band(dest, 3), 29)) + v = bor(v, lshift(band(dest, 0x0003FFFC), 3)) + v = bor(v, band((TWO32 - band(dest, 0x00020000)) % TWO32, 0x00E00000)) + writeu32(b, o + i, v) + end + end + i += 4 + end +end + +-- delta(b, o, n, dist): b[i] += b[i - dist] (1 <= dist <= 256) +function Filters.delta(b: buffer, o: number, n: number, dist: number) + for i = dist, n - 1 do + writeu8(b, o + i, band(readu8(b, o + i) + readu8(b, o + i - dist), 255)) + end +end + +return Filters diff --git a/src/Formats/codecs/Lzma/init.luau b/src/Formats/codecs/Lzma/init.luau new file mode 100644 index 0000000..f6f2825 --- /dev/null +++ b/src/Formats/codecs/Lzma/init.luau @@ -0,0 +1,601 @@ +--!strict +-- codecs/Lzma: LZMA and LZMA2 decoders, the .lzma ("LZMA alone") wrapper and the .xz container. A codec (layer 3): +-- archive/xz, archive/7z (and anything else holding LZMA data) build on it. Decode only. +-- Written from the LZMA specification (LzmaSpec.cpp, Igor Pavlov, public domain) and the xz file format specification +-- 1.2 (Lasse Collin / Igor Pavlov, public domain); the BCJ filters follow xz-embedded (public domain). +-- +-- local Lzma = require("@formats/codecs/Lzma") +-- local out, e = Lzma.lzma(buf, off, len, props, unpackSize?, opts?) -- raw LZMA; props = 5-byte buffer / string +-- -- or { lc, lp, pb, dictSize } +-- local out, e = Lzma.lzma2(buf, off, len, dictSize?, unpackSize?, opts?) -- raw LZMA2 chunks +-- local out, e = Lzma.alone(buf, off?, len?, opts?) -- a .lzma file (13-byte header) +-- local out, e = Lzma.xz(buf, off?, len?, opts?) -- a .xz file (all streams concatenated) +-- Lzma.filter(id, buf, off, len, props?) -- BCJ / delta decode in place (7z) +-- +-- Each returns buffer, consumedEnd (the input offset just past what was decoded) | nil, Err. opts.maxBytes (default +-- 2^30) bounds the output (Err.LIMIT). xz: every stream, block, index and footer is parsed and checked; check types +-- none / CRC-32 / CRC-64 are verified, SHA-256 is skipped (not verified). xz filters: LZMA2, delta, x86, PowerPC, +-- ARM, ARM-Thumb, SPARC, ARM64; IA-64 and RISC-V are Err.UNSUPPORTED. Never throws. +local Err = require("@formats/core/Err") +local Crc32 = require("@formats/core/Crc32") +local Decode = require("@formats/codecs/Lzma/Decode") +local Filters = require("@formats/codecs/Lzma/Filters") +local Crc64 = require("@formats/codecs/Lzma/Crc64") + +local readu8, readu32 = buffer.readu8, buffer.readu32 + +local Lzma = {} + +local DEFAULT_MAX = 2 ^ 30 + +export type Options = { + maxBytes: number?, -- refuse output larger than this (default 2^30) +} +export type Props = { lc: number, lp: number, pb: number, dictSize: number? } + +local function toBuffer(b: any): buffer? + if type(b) == "string" then + return buffer.fromstring(b) + end + if type(b) ~= "buffer" then + return nil + end + return b +end + +local function range(b: buffer, off: number?, len: number?): (number?, number) + local n = buffer.len(b) + local o = off or 0 + if type(o) ~= "number" or o < 0 or o > n or o % 1 ~= 0 then + return nil, 0 + end + local l = len or (n - o) + if type(l) ~= "number" or l < 0 or l % 1 ~= 0 then + return nil, 0 + end + if o + l > n then + l = n - o + end + return o, l +end + +local function args(what: string, buf: any, offset: number?, length: number?): (buffer?, number, number, Err.Err?) + local b = toBuffer(buf) + if not b then + return nil, 0, 0, Err.new(Err.ARG, what .. ": expected a buffer or a string, got " .. typeof(buf)) + end + local o, l = range(b, offset, length) + if not o then + return nil, 0, 0, Err.new(Err.ARG, what .. ": bad offset / length " .. tostring(offset) .. ", " .. tostring(length)) + end + return b, o, l, nil +end + +local function maxOf(opts: Options?): number + local m = opts and opts.maxBytes + return if type(m) == "number" and m >= 0 then m else DEFAULT_MAX +end + +-- a decoder message -> Err +local function fail(msg: any, at: number?): Err.Err + local s = tostring(msg) + local code = Err.CORRUPT + if string.sub(s, 1, 5) == "limit" then + code = Err.LIMIT + elseif string.find(s, "truncated", 1, true) then + code = Err.TRUNCATED + end + return Err.new(code, s, at) +end + +-- props byte -> lc, lp, pb | nil +local function propsByte(d: number): (number?, number, number) + if d >= 225 then + return nil, 0, 0 + end + return d % 9, (d // 9) % 5, d // 45 +end +Lzma.propsByte = propsByte + +-- ------------------------------------------------------------------------------------------------ LZMA +-- decodeLzma(st, b, o, e, unpackSize?) -> consumedEnd | nil, Err: one raw LZMA stream into st (props set) +local function decodeLzma(st: Decode.State, b: buffer, o: number, e: number, unpackSize: number?): (number?, Err.Err?) + local ip, ierr = Decode.rcInit(st, b, o, e) + if not ip then + return nil, fail(ierr, o) + end + local target = if unpackSize then st.op + unpackSize else math.huge + if unpackSize and target > st.maxBytes then + return nil, Err.new(Err.LIMIT, string.format("output of %d bytes is over maxBytes", unpackSize)) + end + if unpackSize and not Decode.ensure(st, target) then + return nil, Err.new(Err.LIMIT, "output over maxBytes") + end + local status, res = Decode.run(st, b, ip, e, target) + if not status then + return nil, fail(res, o) + end + if unpackSize and st.op ~= target then + return nil, Err.new(Err.CORRUPT, "end marker before the declared size", o) + end + return res :: number, nil +end + +-- lzma(buf, offset, length, props, unpackSize?, opts?) -> buffer, consumedEnd | nil, Err +function Lzma.lzma(buf: buffer | string, offset: number?, length: number?, props: any, unpackSize: number?, opts: Options?): (buffer?, any) + local b, o, l, aerr = args("Lzma.lzma", buf, offset, length) + if not b then + return nil, aerr + end + local lc, lp, pb + if type(props) == "table" then + lc, lp, pb = props.lc, props.lp, props.pb + else + local pbuf = toBuffer(props) + if not pbuf or buffer.len(pbuf) < 1 then + return nil, Err.new(Err.ARG, "Lzma.lzma: props must be the 5-byte properties or { lc, lp, pb }") + end + lc, lp, pb = propsByte(readu8(pbuf, 0)) + if not lc then + return nil, Err.new(Err.CORRUPT, "bad LZMA properties byte") + end + end + if type(lc) ~= "number" or type(lp) ~= "number" or type(pb) ~= "number" then + return nil, Err.new(Err.ARG, "Lzma.lzma: bad props") + end + if unpackSize ~= nil and (type(unpackSize) ~= "number" or unpackSize < 0 or unpackSize % 1 ~= 0) then + return nil, Err.new(Err.ARG, "Lzma.lzma: bad unpackSize") + end + local max = maxOf(opts) + local st = Decode.new(if unpackSize then unpackSize else l * 4, max) + local ok, perr = Decode.setProps(st, lc, lp, pb) + if not ok then + return nil, Err.new(Err.CORRUPT, tostring(perr)) + end + local consumed, err = decodeLzma(st, b, o, o + l, unpackSize) + if not consumed then + return nil, err + end + return Decode.finish(st), consumed +end + +-- alone(buf, offset?, length?, opts?) -> buffer, consumedEnd | nil, Err: a .lzma file (props, dict size, u64 size) +function Lzma.alone(buf: buffer | string, offset: number?, length: number?, opts: Options?): (buffer?, any) + local b, o, l, aerr = args("Lzma.alone", buf, offset, length) + if not b then + return nil, aerr + end + if l < 13 then + return nil, Err.new(Err.TRUNCATED, "truncated .lzma header", o) + end + local lo, hi = readu32(b, o + 5), readu32(b, o + 9) + local size: number? = nil + if not (lo == 0xFFFFFFFF and hi == 0xFFFFFFFF) then + if hi >= 2 ^ 21 then + return nil, Err.new(Err.CORRUPT, "bad .lzma size", o + 5) + end + size = hi * 4294967296 + lo + end + return Lzma.lzma(b, o + 13, l - 13, buffer.fromstring(buffer.readstring(b, o, 1)), size, opts) +end + +-- ------------------------------------------------------------------------------------------------ LZMA2 +-- decodeLzma2(st, b, o, e) -> consumedEnd | nil, Err: LZMA2 chunks up to the end-of-stream byte +local function decodeLzma2(st: Decode.State, b: buffer, o: number, e: number): (number?, Err.Err?) + local p = o + local needDict, needProps = true, true + while true do + if p >= e then + return nil, Err.new(Err.TRUNCATED, "truncated LZMA2 stream", p) + end + local c = readu8(b, p) + if c == 0 then + return p + 1, nil + end + if c == 1 or c == 2 then + if p + 3 > e then + return nil, Err.new(Err.TRUNCATED, "truncated LZMA2 chunk header", p) + end + local n = readu8(b, p + 1) * 256 + readu8(b, p + 2) + 1 + if c == 1 then + Decode.resetDict(st) + needDict = false + elseif needDict then + return nil, Err.new(Err.CORRUPT, "LZMA2 chunk without a dictionary reset", p) + end + if p + 3 + n > e then + return nil, Err.new(Err.TRUNCATED, "truncated LZMA2 stored chunk", p) + end + local ok, cerr = Decode.copy(st, n, b, p + 3) + if not ok then + return nil, fail(cerr, p) + end + st.remLen = 0 + p += 3 + n + elseif c >= 0x80 then + if p + 5 > e then + return nil, Err.new(Err.TRUNCATED, "truncated LZMA2 chunk header", p) + end + local usize = (c % 32) * 65536 + readu8(b, p + 1) * 256 + readu8(b, p + 2) + 1 + local psize = readu8(b, p + 3) * 256 + readu8(b, p + 4) + 1 + local mode = (c // 32) % 4 + local q = p + 5 + if mode == 3 then + Decode.resetDict(st) + needDict = false + elseif needDict then + return nil, Err.new(Err.CORRUPT, "LZMA2 chunk without a dictionary reset", p) + end + if mode >= 2 then + if q >= e then + return nil, Err.new(Err.TRUNCATED, "truncated LZMA2 properties", q) + end + local lc, lp, pb = propsByte(readu8(b, q)) + if not lc or lc + lp > 4 then + return nil, Err.new(Err.CORRUPT, "bad LZMA2 properties", q) + end + Decode.setProps(st, lc, lp, pb) + needProps = false + q += 1 + elseif needProps then + return nil, Err.new(Err.CORRUPT, "LZMA2 chunk without properties", p) + elseif mode == 1 then + Decode.resetState(st) + end + if q + psize > e then + return nil, Err.new(Err.TRUNCATED, "truncated LZMA2 chunk", q) + end + local target = st.op + usize + if target > st.maxBytes then + return nil, Err.new(Err.LIMIT, "output over maxBytes") + end + Decode.ensure(st, target) + local ip, ierr = Decode.rcInit(st, b, q, q + psize) + if not ip then + return nil, fail(ierr, q) + end + local status, res = Decode.run(st, b, ip, q + psize, target) + if not status then + return nil, fail(res, q) + end + if status ~= "full" or st.op ~= target then + return nil, Err.new(Err.CORRUPT, "LZMA2 chunk size mismatch", p) + end + p = q + psize + else + return nil, Err.new(Err.CORRUPT, "bad LZMA2 control byte " .. c, p) + end + end +end + +-- lzma2(buf, offset?, length?, dictSize?, unpackSize?, opts?) -> buffer, consumedEnd | nil, Err +function Lzma.lzma2(buf: buffer | string, offset: number?, length: number?, _dictSize: number?, unpackSize: number?, opts: Options?): (buffer?, any) + local b, o, l, aerr = args("Lzma.lzma2", buf, offset, length) + if not b then + return nil, aerr + end + local max = maxOf(opts) + local st = Decode.new(if type(unpackSize) == "number" and unpackSize >= 0 then unpackSize else l * 4, max) + local consumed, err = decodeLzma2(st, b, o, o + l) + if not consumed then + return nil, err + end + if type(unpackSize) == "number" and st.op ~= unpackSize then + return nil, Err.new(Err.CORRUPT, string.format("LZMA2 output is %d bytes, expected %d", st.op, unpackSize)) + end + return Decode.finish(st), consumed +end + +-- ------------------------------------------------------------------------------------------------ filters +-- filter ids (xz numbering; 7z's method ids map onto these in archive/7z) +Lzma.FILTER = table.freeze({ + delta = 0x03, + x86 = 0x04, + powerpc = 0x05, + ia64 = 0x06, + arm = 0x07, + armthumb = 0x08, + sparc = 0x09, + arm64 = 0x0A, + riscv = 0x0B, + lzma2 = 0x21, +}) +local BCJ: { [number]: (buffer, number, number, number) -> () } = { + [0x04] = Filters.x86, + [0x05] = Filters.powerpc, + [0x07] = Filters.arm, + [0x08] = Filters.armthumb, + [0x09] = Filters.sparc, + [0x0A] = Filters.arm64, +} + +-- filter(id, buf, offset, length, props?) -> true | nil, Err: decode a BCJ / delta filter in place. props: the +-- filter's property bytes (a string or buffer: BCJ start offset u32le, delta distance - 1) +function Lzma.filter(id: number, b: buffer, o: number, n: number, props: any?): (boolean?, Err.Err?) + local pb = toBuffer(props) + local plen = if pb then buffer.len(pb) else 0 + if id == 0x03 then + if plen ~= 1 then + return nil, Err.new(Err.CORRUPT, "bad delta filter properties") + end + Filters.delta(b, o, n, readu8(pb :: buffer, 0) + 1) + return true + end + local f = BCJ[id] + if not f then + return nil, Err.new(Err.UNSUPPORTED, string.format("filter 0x%x is not supported", id)) + end + local start = 0 + if plen == 4 then + start = readu32(pb :: buffer, 0) + elseif plen ~= 0 then + return nil, Err.new(Err.CORRUPT, "bad BCJ filter properties") + end + f(b, o, n, start) + return true +end + +-- ------------------------------------------------------------------------------------------------ xz +local XZ_MAGIC = "\253" .. "7zXZ\0" +local CHECK_SIZE = { [0] = 0, 4, 4, 4, 8, 8, 8, 16, 16, 16, 32, 32, 32, 64, 64, 64 } + +-- vli(b, p, e) -> value, next | nil +local function vli(b: buffer, p: number, e: number): (number?, number) + local v, mul = 0, 1 + for i = 0, 8 do + if p + i >= e then + return nil, p + end + local c = readu8(b, p + i) + v += (c % 128) * mul + if c < 128 then + if c == 0 and i > 0 then + return nil, p -- non-minimal encoding + end + return v, p + i + 1 + end + mul *= 128 + end + return nil, p +end +Lzma.vli = vli + +local function crc(b: buffer, o: number, n: number): number + return Crc32.raw(b, o, n) +end + +-- one xz stream at o -> next offset | nil, Err (blocks appended to st) +local function xzStream(st: Decode.State, b: buffer, o: number, e: number): (number?, Err.Err?) + if o + 12 > e then + return nil, Err.new(Err.TRUNCATED, "truncated xz stream header", o) + end + if buffer.readstring(b, o, 6) ~= XZ_MAGIC then + return nil, Err.new(Err.CORRUPT, "bad xz magic", o) + end + if readu8(b, o + 6) ~= 0 or readu8(b, o + 7) > 15 then + return nil, Err.new(Err.UNSUPPORTED, "unknown xz stream flags", o + 6) + end + if crc(b, o + 6, 2) ~= readu32(b, o + 8) then + return nil, Err.new(Err.CHECKSUM, "xz stream header CRC-32 mismatch", o + 8) + end + local check = readu8(b, o + 7) + local csize = CHECK_SIZE[check] + local p = o + 12 + local records: { { number } } = {} + while true do + if p >= e then + return nil, Err.new(Err.TRUNCATED, "truncated xz block", p) + end + local hs = readu8(b, p) + if hs == 0 then + break -- the index + end + local hsize = (hs + 1) * 4 + if p + hsize > e then + return nil, Err.new(Err.TRUNCATED, "truncated xz block header", p) + end + if crc(b, p, hsize - 4) ~= readu32(b, p + hsize - 4) then + return nil, Err.new(Err.CHECKSUM, "xz block header CRC-32 mismatch", p) + end + local flags = readu8(b, p + 1) + if flags % 64 >= 4 then + return nil, Err.new(Err.UNSUPPORTED, "reserved xz block flags", p + 1) + end + local nfilters = flags % 4 + 1 + local q = p + 2 + local he = p + hsize - 4 + local csz, usz: number? = nil, nil + if flags >= 128 or (flags // 64) % 2 == 1 then + if (flags // 64) % 2 == 1 then + local v + v, q = vli(b, q, he) + if not v or v == 0 then + return nil, Err.new(Err.CORRUPT, "bad xz compressed size", q) + end + csz = v + end + if flags >= 128 then + local v + v, q = vli(b, q, he) + if not v then + return nil, Err.new(Err.CORRUPT, "bad xz uncompressed size", q) + end + usz = v + end + end + local filters: { { id: number, props: buffer } } = {} + for _ = 1, nfilters do + local id, psz + id, q = vli(b, q, he) + if not id then + return nil, Err.new(Err.CORRUPT, "bad xz filter flags", q) + end + psz, q = vli(b, q, he) + if not psz or q + psz > he then + return nil, Err.new(Err.CORRUPT, "bad xz filter properties", q) + end + local pr = buffer.create(psz) + buffer.copy(pr, 0, b, q, psz) + q += psz + table.insert(filters, { id = id, props = pr }) + end + for k = q, he - 1 do + if readu8(b, k) ~= 0 then + return nil, Err.new(Err.CORRUPT, "nonzero xz block header padding", k) + end + end + local last = filters[nfilters] + if last.id ~= 0x21 or buffer.len(last.props) ~= 1 or readu8(last.props, 0) > 40 then + return nil, Err.new(Err.UNSUPPORTED, string.format("xz filter chain must end in LZMA2 (got 0x%x)", last.id), p) + end + for k = 1, nfilters - 1 do + local id = filters[k].id + if id ~= 0x03 and not BCJ[id] then + return nil, Err.new(Err.UNSUPPORTED, string.format("xz filter 0x%x is not supported", id), p) + end + end + -- data + local dstart = p + hsize + local ostart = st.op + local dend = if csz then dstart + csz else e + if dend > e then + return nil, Err.new(Err.TRUNCATED, "truncated xz block data", dstart) + end + local cend, derr = decodeLzma2(st, b, dstart, dend) + if not cend then + return nil, derr + end + if csz and cend ~= dend then + return nil, Err.new(Err.CORRUPT, "xz compressed size mismatch", dstart) + end + local un = st.op - ostart + if usz and un ~= usz then + return nil, Err.new(Err.CORRUPT, "xz uncompressed size mismatch", dstart) + end + for k = nfilters - 1, 1, -1 do + local ok, ferr = Lzma.filter(filters[k].id, st.out, ostart, un, filters[k].props) + if not ok then + return nil, ferr + end + end + local unpadded = hsize + (cend - dstart) + csize + local pe = cend + while (pe - p) % 4 ~= 0 do + if pe >= e then + return nil, Err.new(Err.TRUNCATED, "truncated xz block padding", pe) + end + if readu8(b, pe) ~= 0 then + return nil, Err.new(Err.CORRUPT, "nonzero xz block padding", pe) + end + pe += 1 + end + if pe + csize > e then + return nil, Err.new(Err.TRUNCATED, "truncated xz check", pe) + end + if check == 1 then + if crc(st.out, ostart, un) ~= readu32(b, pe) then + return nil, Err.new(Err.CHECKSUM, "xz block CRC-32 mismatch", pe) + end + elseif check == 4 then + local hi, lo = Crc64.of(st.out, ostart, un) + if lo ~= readu32(b, pe) or hi ~= readu32(b, pe + 4) then + return nil, Err.new(Err.CHECKSUM, "xz block CRC-64 mismatch", pe) + end + end + table.insert(records, { unpadded, un }) + p = pe + csize + end + -- index + local ip = p + local count, q = vli(b, p + 1, e) + if not count or count ~= #records then + return nil, Err.new(Err.CORRUPT, "xz index record count mismatch", p) + end + for i = 1, count do + local a, u + a, q = vli(b, q, e) + if not a then + return nil, Err.new(Err.TRUNCATED, "truncated xz index", q) + end + u, q = vli(b, q, e) + if not u then + return nil, Err.new(Err.TRUNCATED, "truncated xz index", q) + end + if a ~= records[i][1] or u ~= records[i][2] then + return nil, Err.new(Err.CORRUPT, "xz index does not match the blocks", q) + end + end + while (q - ip) % 4 ~= 0 do + if q >= e or readu8(b, q) ~= 0 then + return nil, Err.new(Err.CORRUPT, "bad xz index padding", q) + end + q += 1 + end + if q + 4 > e then + return nil, Err.new(Err.TRUNCATED, "truncated xz index", q) + end + if crc(b, ip, q - ip) ~= readu32(b, q) then + return nil, Err.new(Err.CHECKSUM, "xz index CRC-32 mismatch", q) + end + q += 4 + local isize = q - ip + -- footer + if q + 12 > e then + return nil, Err.new(Err.TRUNCATED, "truncated xz stream footer", q) + end + if crc(b, q + 4, 6) ~= readu32(b, q) then + return nil, Err.new(Err.CHECKSUM, "xz stream footer CRC-32 mismatch", q) + end + if (readu32(b, q + 4) + 1) * 4 ~= isize then + return nil, Err.new(Err.CORRUPT, "xz backward size mismatch", q + 4) + end + if readu8(b, q + 8) ~= 0 or readu8(b, q + 9) ~= check or buffer.readstring(b, q + 10, 2) ~= "YZ" then + return nil, Err.new(Err.CORRUPT, "bad xz stream footer", q + 8) + end + return q + 12, nil +end + +-- xz(buf, offset?, length?, opts?) -> buffer, consumedEnd | nil, Err: every stream (and stream padding) in the range +function Lzma.xz(buf: buffer | string, offset: number?, length: number?, opts: Options?): (buffer?, any) + local b, o, l, aerr = args("Lzma.xz", buf, offset, length) + if not b then + return nil, aerr + end + local e = o + l + local st = Decode.new(l * 4, maxOf(opts)) + local p = o + local nstreams = 0 + while true do + local nxt, err = xzStream(st, b, p, e) + if not nxt then + return nil, err + end + nstreams += 1 + p = nxt + -- stream padding: zero bytes in multiples of 4 + local z = p + while z < e and readu8(b, z) == 0 do + z += 1 + end + if z == e then + if (z - p) % 4 ~= 0 then + return nil, Err.new(Err.CORRUPT, "xz stream padding is not a multiple of 4", p) + end + p = z + break + end + if (z - p) % 4 ~= 0 then + return nil, Err.new(Err.CORRUPT, "xz stream padding is not a multiple of 4", p) + end + p = z + end + return Decode.finish(st), p +end + +-- isXz(buf, offset?) -> true when the bytes start an xz stream +function Lzma.isXz(b: buffer, o: number?): boolean + local off = o or 0 + return off + 6 <= buffer.len(b) and buffer.readstring(b, off, 6) == XZ_MAGIC +end + +return Lzma diff --git a/tests/codecs/lzma.luau b/tests/codecs/lzma.luau new file mode 100644 index 0000000..669b265 --- /dev/null +++ b/tests/codecs/lzma.luau @@ -0,0 +1,142 @@ +-- codecs/Lzma tests: every fixture (liblzma through Python's lzma module and the xz CLI: presets 0-9 and -e, lc / lp / +-- pb variants, raw LZMA1 / LZMA2, .lzma files, xz with every check type, BCJ and delta filters, multiple blocks, +-- multiple streams and stream padding) decodes to its corpus; consumed offsets; checksum / size / truncation errors; +-- maxBytes; the fuzz no-throw pass. Fixtures: tools/fixtures/lzma.py. +local T = require("@tests/T") +local Lzma = require("@formats/codecs/Lzma") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/lzma") + +local t = T.suite("lzma") + +local function decode(c: any, b: buffer, opts: any?): (buffer?, any) + if c.kind == "raw" then + return Lzma.lzma(b, 0, nil, c.props, c.size, opts) + elseif c.kind == "raw2" then + return Lzma.lzma2(b, 0, nil, nil, nil, opts) + elseif c.kind == "alone" then + return Lzma.alone(b, 0, nil, opts) + end + return Lzma.xz(b, 0, nil, opts) +end + +local nbytes = 0 +for _, c in Fx.cases do + local want = Fx.corpora[c.corpus] + local b = buffer.fromstring(c.data) + local out, res = decode(c, b) + t:check(out ~= nil, c.name .. ": " .. tostring(res)) + t:check(buffer.tostring(out :: buffer) == want, c.name .. ": output differs") + if c.kind ~= "raw" then + t:eq(res, #c.data, c.name .. ": consumed") + end + nbytes += #want +end +t:note("%d fixture streams, %.1f MB decoded", #Fx.cases, nbytes / 1e6) + +-- at an offset inside a bigger buffer, with trailing bytes +do + for _, c in Fx.cases do + if c.kind == "xz" and c.name == "text/xz-6" then + local big = buffer.create(#c.data + 11) + buffer.fill(big, 0, 0xAB) + buffer.writestring(big, 3, c.data) + local out, res = Lzma.xz(big, 3, #c.data) + t:check(out and buffer.tostring(out) == Fx.corpora.text and res == 3 + #c.data, "xz at an offset") + end + end +end + +-- errors +do + local xz, xzc + for _, c in Fx.cases do + if c.name == "text/xz-check-crc32" then + xz = c + elseif c.name == "text/xz-6" then + xzc = c + end + end + -- the check field: the last bytes before the index; flip a data bit near the end of the block instead + local b = buffer.fromstring(xzc.data) + local n = buffer.len(b) + -- footer magic + buffer.writeu8(b, n - 1, 0) + local _, e1 = Lzma.xz(b) + t:check(e1 and (e1.code == Err.CORRUPT or e1.code == Err.CHECKSUM), "bad footer: " .. tostring(e1)) + -- the stream header CRC + local b2 = buffer.fromstring(xz.data) + buffer.writeu8(b2, 8, bit32.bxor(buffer.readu8(b2, 8), 1)) + local _, e2 = Lzma.xz(b2) + t:check(e2 and e2.code == Err.CHECKSUM, "header crc: " .. tostring(e2)) + -- the block check (CRC-32 / CRC-64): flip a byte of the check field (found from the index: the 4 / 8 bytes before + -- the index indicator, which follows the block padding) + for _, c in { xz, xzc } do + local b3 = buffer.fromstring(c.data) + local n3 = buffer.len(b3) + local backward = (buffer.readu32(b3, n3 - 8) + 1) * 4 + local indexAt = n3 - 12 - backward + buffer.writeu8(b3, indexAt - 1, bit32.bxor(buffer.readu8(b3, indexAt - 1), 0x10)) + local _, e3 = Lzma.xz(b3) + t:check(e3 and e3.code == Err.CHECKSUM, c.name .. ": block check: " .. tostring(e3)) + end + -- truncations are TRUNCATED or CORRUPT, never a throw + local _, e4 = Lzma.xz(buffer.fromstring(string.sub(xzc.data, 1, #xzc.data // 2))) + t:check(e4 and e4.code == Err.TRUNCATED, "truncated xz: " .. tostring(e4)) + -- maxBytes + local _, e5 = Lzma.xz(xzc.data, nil, nil, { maxBytes = 1000 }) + t:check(e5 and e5.code == Err.LIMIT, "maxBytes: " .. tostring(e5)) + local ok, r1, r2 = pcall(Lzma.xz, 5 :: any) + t:check(ok and r1 == nil and r2.code == Err.ARG, "a non-buffer argument returns Err.ARG") + local _, e6 = Lzma.lzma("\0\0\0\0\0", 0, nil, "\255") + t:check(e6 and e6.code == Err.CORRUPT, "bad props byte: " .. tostring(e6)) +end + +-- raw LZMA with the size known: decoding stops at the size even without an end marker +do + for _, c in Fx.cases do + if c.kind == "raw" and #Fx.corpora[c.corpus] > 1000 then + local want = Fx.corpora[c.corpus] + local out = Lzma.lzma(c.data, 0, nil, { lc = 3, lp = 0, pb = 2 }, nil) + if c.name == c.corpus .. "/raw-lc3-lp0-pb2" then + t:check(out and buffer.tostring(out) == want, c.name .. ": table props, end marker") + end + local part = Lzma.lzma(c.data, 0, nil, c.props, 500) + t:check(part and buffer.tostring(part) == string.sub(want, 1, 500), c.name .. ": a prefix by size") + end + end +end + +-- fuzz +do + local samples = {} + for i, c in Fx.cases do + if i % 7 == 0 and #c.data > 16 and #c.data < 40000 then + table.insert(samples, c) + end + end + local xs, as, rs = {}, {}, {} + for _, c in samples do + if c.kind == "xz" then + table.insert(xs, c.data) + elseif c.kind == "alone" then + table.insert(as, c.data) + else + table.insert(rs, c.data) + end + end + t:fuzz("xz", function(b: buffer) + return Lzma.xz(b, 0, nil, { maxBytes = 1 * 2 ^ 20 }) + end, xs, { mutations = 6, garbage = 300 }) + t:fuzz("alone", function(b: buffer) + return Lzma.alone(b, 0, nil, { maxBytes = 1 * 2 ^ 20 }) + end, as, { mutations = 6, garbage = 300 }) + t:fuzz("lzma2", function(b: buffer) + return Lzma.lzma2(b, 0, nil, nil, nil, { maxBytes = 1 * 2 ^ 20 }) + end, rs, { mutations = 4, garbage = 1000 }) + t:fuzz("lzma", function(b: buffer) + return Lzma.lzma(b, 0, nil, "\93", nil, { maxBytes = 1 * 2 ^ 20 }) + end, rs, { mutations = 2, garbage = 1000 }) +end + +t:done() diff --git a/tools/fixtures/lzma.py b/tools/fixtures/lzma.py new file mode 100644 index 0000000..09be77f --- /dev/null +++ b/tools/fixtures/lzma.py @@ -0,0 +1,105 @@ +# LZMA / LZMA2 / xz fixtures (tools/fixtures.py): deterministic corpora compressed by liblzma (Python's lzma module and +# the xz CLI): every preset and -e, lc / lp / pb variants, raw LZMA1 / LZMA2, .lzma files with and without the size +# and end marker, xz with every check type, BCJ (x86, PowerPC, ARM, ARM-Thumb, SPARC, ARM64) and delta filters, +# multi-block (--block-size), multi-stream and stream padding. +# tests/gen/lzma.luau { corpora = { [name] = bytes }, cases = { { name, kind, corpus, data, props?, dict?, +# size? } } } kind: "raw" (LZMA1), "raw2" (LZMA2), "alone", "xz" +# tests/gen/lzma_bench.luau { size, crc, xz, alone } (a ~4 MB corpus at -6) +import lzma, os, random, subprocess, sys, zlib + + +def text_corpus(limit): + base = os.path.dirname(os.__file__) + out = bytearray() + for name in sorted(os.listdir(base)): + if name.endswith(".py"): + with open(os.path.join(base, name), "rb") as f: + out += f.read() + if len(out) >= limit: + break + return bytes(out[:limit]) + + +def binary_corpus(limit): + # machine code: a slice of the Python interpreter (x86-64 here; exercises the x86 BCJ filter) + with open(os.path.realpath(sys.executable), "rb") as f: + data = f.read() + if len(data) < limit: + lib = os.path.join(os.path.dirname(os.path.realpath(sys.executable)), "..", "lib") + for name in sorted(os.listdir(lib)): + p = os.path.join(lib, name) + if name.startswith("libpython") and os.path.isfile(p): + with open(p, "rb") as f: + data += f.read(limit) + break + return data[:limit] + + +def xz_cli(args, data): + return subprocess.run(["xz"] + args + ["-c"], input=data, capture_output=True, check=True).stdout + + +def generate(ctx): + rng = random.Random(7) + corpora = { + "empty": b"", + "one": b"a", + "text": text_corpus(150000), + "binary": binary_corpus(120000), + "random": rng.randbytes(20000), + "runs": b"abc" * 3000 + b"\0" * 30000 + bytes(range(256)) * 30 + b"z" * 300, + "words": b" ".join(rng.choice([b"lorem", b"ipsum", b"dolor", b"sit", b"amet", b"\xff\xfe", b"0123"]) for _ in range(20000)), + } + cases = [] + + def add(name, kind, corpus, data, **extra): + c = {"name": name, "kind": kind, "corpus": corpus, "data": data} + c.update(extra) + cases.append(c) + + for cname, data in corpora.items(): + small = cname in ("empty", "one", "random") + presets = [0, 6] if small else [0, 1, 3, 6, 9, 9 | lzma.PRESET_EXTREME] + for p in presets: + add("%s/xz-%d%s" % (cname, p & 15, "e" if p & lzma.PRESET_EXTREME else ""), "xz", cname, + lzma.compress(data, lzma.FORMAT_XZ, check=lzma.CHECK_CRC64, preset=p)) + for chk, cn in ((lzma.CHECK_NONE, "none"), (lzma.CHECK_CRC32, "crc32"), (lzma.CHECK_SHA256, "sha256")): + add("%s/xz-check-%s" % (cname, cn), "xz", cname, lzma.compress(data, lzma.FORMAT_XZ, check=chk, preset=2)) + # .lzma (alone): with a size (Python writes an end marker and no size; the CLI writes the same); raw streams + add("%s/alone" % cname, "alone", cname, lzma.compress(data, lzma.FORMAT_ALONE, preset=6)) + for lc, lp, pb in ((3, 0, 2), (0, 2, 0), (4, 0, 4), (1, 3, 1), (0, 4, 3)): + f = [{"id": lzma.FILTER_LZMA1, "preset": 6, "lc": lc, "lp": lp, "pb": pb, "dict_size": 1 << 20}] + raw = lzma.compress(data, lzma.FORMAT_RAW, filters=f) + add("%s/raw-lc%d-lp%d-pb%d" % (cname, lc, lp, pb), "raw", cname, raw, props=bytes([(pb * 5 + lp) * 9 + lc]), size=len(data)) + for lc, lp, pb in ((3, 0, 2), (0, 4, 4), (2, 2, 1)): + f = [{"id": lzma.FILTER_LZMA2, "preset": 6, "lc": lc, "lp": lp, "pb": pb}] + add("%s/raw2-lc%d-lp%d-pb%d" % (cname, lc, lp, pb), "raw2", cname, lzma.compress(data, lzma.FORMAT_RAW, filters=f)) + if not small: + for fid, fname in ((lzma.FILTER_X86, "x86"), (lzma.FILTER_POWERPC, "ppc"), (lzma.FILTER_ARM, "arm"), + (lzma.FILTER_ARMTHUMB, "armthumb"), (lzma.FILTER_SPARC, "sparc")): + f = [{"id": fid}, {"id": lzma.FILTER_LZMA2, "preset": 3}] + add("%s/xz-%s" % (cname, fname), "xz", cname, lzma.compress(data, lzma.FORMAT_XZ, filters=f)) + f = [{"id": lzma.FILTER_X86, "start_offset": 0x1000}, {"id": lzma.FILTER_LZMA2, "preset": 3}] + add("%s/xz-x86-start" % cname, "xz", cname, lzma.compress(data, lzma.FORMAT_XZ, filters=f)) + for dist in (1, 4, 256): + f = [{"id": lzma.FILTER_DELTA, "dist": dist}, {"id": lzma.FILTER_LZMA2, "preset": 3}] + add("%s/xz-delta%d" % (cname, dist), "xz", cname, lzma.compress(data, lzma.FORMAT_XZ, filters=f)) + add("%s/xz-cli-arm64" % cname, "xz", cname, xz_cli(["--arm64", "--lzma2=preset=3"], data)) + add("%s/xz-cli-blocks" % cname, "xz", cname, xz_cli(["-6", "--block-size=20000"], data)) + add("%s/xz-cli-x86-delta" % cname, "xz", cname, xz_cli(["--x86", "--delta=dist=2", "--lzma2=preset=1"], data)) + add("%s/alone-cli" % cname, "alone", cname, xz_cli(["--format=lzma", "-3"], data)) + # multi-stream + stream padding + corpora["multi"] = corpora["text"][:40000] + corpora["runs"] + b"" + corpora["one"] + multi = (lzma.compress(corpora["text"][:40000], lzma.FORMAT_XZ, preset=1) + b"\0" * 8 + + lzma.compress(corpora["runs"], lzma.FORMAT_XZ, check=lzma.CHECK_CRC32) + + lzma.compress(b"", lzma.FORMAT_XZ) + lzma.compress(b"a", lzma.FORMAT_XZ, check=lzma.CHECK_NONE) + b"\0" * 4) + add("multi/xz-streams", "xz", "multi", multi) + + ctx.emit("lzma", {"corpora": corpora, "cases": cases}) + + # real text and machine code, little long-range repetition + bench = text_corpus(2_000_000) + binary_corpus(1_000_000) + bench = bench[:3_000_000] + ctx.emit("lzma_bench", {"size": len(bench), "crc": zlib.crc32(bench), + "xz": lzma.compress(bench, lzma.FORMAT_XZ, preset=6), + "alone": lzma.compress(bench, lzma.FORMAT_ALONE, preset=6)})