diff --git a/docs/FORMATS.md b/docs/FORMATS.md index a5a25a7..74c9e17 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -6,8 +6,10 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | Category | Format | Extensions | Read | Write | Capabilities | Test | |---|---|---|---|---|---|---| | image | png | .png .apng | yes | yes | animation: false, alpha: true, depths: 1, 2, 4, 8, 16 | `tests/image/png.luau` | +| archive | bz2 | .bz2 .tbz2 .tbz | yes | - | stream: true | `tests/archive/bz2.luau` | Codecs (layer 1, shared by formats; not loadable on their own): +- codecs/Bzip2: bzip2 decompressor (BWT + MTF + Huffman, the .bz2 stream format of bzip2 0.9.5 / 1.0.x). A codec - codecs/Deflate: DEFLATE (RFC 1951) decoder and compressor, with the zlib (RFC 1950) and gzip (RFC 1952) wrappers. - codecs/Raster: an antialiased scanline rasterizer for paths of lines, quadratic and cubic Béziers, under an affine diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index ba09f70..7fd9a81 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -26,6 +26,18 @@ local list: { Entry } = { return require("@formats/image/png") end, }, + { + name = "bz2", + category = "archive", + path = "archive/bz2", + extensions = { "bz2", "tbz2", "tbz" }, + mime = { "application/x-bzip2" }, + deps = { "core/Err", "core/Bytes", "containers/Archive", "codecs/Bzip2" }, + caps = { decode = true, encode = false, stream = true }, + load = function() + return require("@formats/archive/bz2") + end, + }, } return list diff --git a/src/Formats/archive/bz2/init.luau b/src/Formats/archive/bz2/init.luau new file mode 100644 index 0000000..7483ab0 --- /dev/null +++ b/src/Formats/archive/bz2/init.luau @@ -0,0 +1,63 @@ +--!strict +-- archive/bz2: a .bz2 file as a single-stream archive: one entry, the decompressed data (codecs/Bzip2; concatenated +-- streams are joined, as bzip2 -d does). The entry is named after the file without its .bz2 (".tbz2" -> ".tar"), +-- else "data"; the api unwraps a .tar.bz2 into the tar inside (meta.stream). Read only. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Archive = require("@formats/containers/Archive") +local Bzip2 = require("@formats/codecs/Bzip2") + +-- ------------------------------------------------------------------------------------------------ contract +local Bz2 = { + name = "bz2", + category = "archive", + extensions = { "bz2", "tbz2", "tbz" }, + mime = { "application/x-bzip2" }, + deps = { "core/Err", "core/Bytes", "containers/Archive", "codecs/Bzip2" }, + caps = { decode = true, encode = false, stream = true }, +} + +export type DecodeOptions = { + maxBytes: number?, -- refuse larger output (default 2^30) + name: string?, -- the file name (the api passes it): names the entry +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Bz2.sniff(r: Bytes.Reader): number + local h = r:peek(10) + if #h < 10 or string.sub(h, 1, 3) ~= "BZh" then + return 0 + end + local lv = string.byte(h, 4) + if lv < 0x31 or lv > 0x39 then + return 0 + end + local magic = string.sub(h, 5, 10) + if magic == "\x31\x41\x59\x26\x53\x59" or magic == "\x17\x72\x45\x38\x50\x90" then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Bz2.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local out, consumed = Bzip2.decompress(r.buf, r.base, r.limit - r.base, { maxBytes = opts and opts.maxBytes }) + if not out then + return nil, consumed + end + local a = Archive.new("bz2") + a.meta.stream = true + Archive.put(a, { + name = Archive.streamName(opts, Bz2.extensions), + size = buffer.len(out), + compressedSize = consumed - r.base, + method = "bzip2", + dir = false, + data = out, + }) + return a, nil +end + +return Bz2 diff --git a/src/Formats/codecs/Bzip2/Decode.luau b/src/Formats/codecs/Bzip2/Decode.luau new file mode 100644 index 0000000..66df42e --- /dev/null +++ b/src/Formats/codecs/Bzip2/Decode.luau @@ -0,0 +1,538 @@ +--!strict +--!native +--!optimize 2 +-- codecs/Bzip2/Decode: bzip2 stream decoder (Julian Seward's format, as documented by the bzip2 1.0.x sources and +-- Joe Tsai's "bzip2 format specification"). Written from the format description; no third-party code. +-- Per block: MSB-first bit reader on a local 32-bit bit buffer, Huffman groups (10-bit lookup + canonical fallback for +-- codes up to 20 bits), MTF + RUNA/RUNB, inverse BWT through one u32 vector (byte in the low 8 bits, next index +-- above), RLE1 undo with the block CRC (CRC-32/BZIP2, MSB first) computed on the way out; the combined stream CRC is +-- checked at the end-of-stream marker. Concatenated streams are decoded one after the other. +-- Not supported: randomised blocks (written only by bzip2 0.9.0 and older). +-- +-- Never throws: every buffer access is in range by construction; failures return nil, message, kind +-- ("truncated" | "corrupt" | "checksum" | "limit" | "unsupported"). +local band, bor, bxor, lshift, rshift = bit32.band, bit32.bor, bit32.bxor, bit32.lshift, bit32.rshift +local readu8, readu32, writeu8, writeu32 = buffer.readu8, buffer.readu32, buffer.writeu8, buffer.writeu32 +local bcreate, bcopy, bfill, blen = buffer.create, buffer.copy, buffer.fill, buffer.len + +local Decode = {} + +-- CRC-32/BZIP2 table (polynomial 0x04C11DB7, not reflected) +local CT = table.create(256, 0) +for i = 0, 255 do + local c = lshift(i, 24) + for _ = 1, 8 do + if band(c, 0x80000000) ~= 0 then + c = bxor(lshift(c, 1), 0x04C11DB7) + else + c = lshift(c, 1) + end + end + CT[i + 1] = c +end +Decode.crcTable = CT + +local MASK = table.create(33, 0) +for i = 0, 32 do + MASK[i + 1] = if i == 32 then 0xFFFFFFFF else 2 ^ i - 1 +end + +local PBITS = 10 -- primary lookup width +local PSIZE = 1024 +local MAXGROUPS = 6 +local MAXALPHA = 258 +local MAXLEN = 20 + +-- scratch tables, reused across calls (single-threaded) +local LOOK = bcreate(MAXGROUPS * PSIZE * 4) -- per group: sym * 32 + len (len <= PBITS), 0 = longer code / none +local LENS = bcreate(MAXGROUPS * MAXALPHA) +local PERM = table.create(MAXGROUPS * MAXALPHA, 0) -- per group: symbols in canonical order +local FIRST = table.create(MAXGROUPS * (MAXLEN + 1), 0) -- first code of each length +local COUNT = table.create(MAXGROUPS * (MAXLEN + 1), 0) +local OFFS = table.create(MAXGROUPS * (MAXLEN + 1), 0) -- index into PERM of the first symbol of each length +local MAXL = table.create(MAXGROUPS, 0) +local CFTAB = table.create(257, 0) +local MTF = table.create(256, 0) +local SEQ = table.create(256, 0) + +-- build group g's tables from LENS[g*MAXALPHA .. + n): false when over-subscribed +local function buildGroup(g: number, n: number): boolean + local lbase = g * MAXALPHA + local cbase = g * (MAXLEN + 1) + for l = 0, MAXLEN do + COUNT[cbase + l + 1] = 0 + end + local maxLen = 0 + for s = 0, n - 1 do + local l = readu8(LENS, lbase + s) + COUNT[cbase + l + 1] += 1 + if l > maxLen then + maxLen = l + end + end + MAXL[g + 1] = maxLen + -- canonical codes: by length, then symbol + local code, idx = 0, 0 + for l = 1, MAXLEN do + FIRST[cbase + l + 1] = code + OFFS[cbase + l + 1] = idx + local c = COUNT[cbase + l + 1] + code += c + idx += c + if code > 2 ^ l then + return false + end + code *= 2 + end + -- perm + lookup + local pbase = g * MAXALPHA + local tbase = g * PSIZE * 4 + bfill(LOOK, tbase, 0, PSIZE * 4) + local next = table.create(MAXLEN + 1, 0) + for l = 1, MAXLEN do + next[l + 1] = OFFS[cbase + l + 1] + end + for s = 0, n - 1 do + local l = readu8(LENS, lbase + s) + local k = next[l + 1] + next[l + 1] = k + 1 + PERM[pbase + k + 1] = s + if l <= PBITS then + local c = FIRST[cbase + l + 1] + (k - OFFS[cbase + l + 1]) + local shift = PBITS - l + local from = lshift(c, shift) + local entry = s * 32 + l + for j = from, from + lshift(1, shift) - 1 do + writeu32(LOOK, tbase + j * 4, entry) + end + end + end + return true +end + +local function grow(out: buffer, op: number, need: number): buffer + local nb = bcreate(math.max(blen(out) * 2, need, 65536)) + bcopy(nb, 0, out, 0, op) + return nb +end + +-- decode(b, o, e, maxBytes) -> out, n, consumedEnd | nil, message, kind +function Decode.decode(b: buffer, o: number, e: number, maxBytes: number): (buffer?, any, any) + local out = bcreate(math.min(math.max(65536, (e - o) * 4), maxBytes + 1)) + local op = 0 + local p = o -- next input byte (may run past e: zeros are fed, and the overrun is detected) + local bb, bc = 0, 0 + local tt: buffer? = nil + local ttSize = 0 + local streams = 0 + local consumedEnd = o + + while true do + -- stream header (byte aligned) + if streams > 0 then + if p + 4 > e or readu8(b, p) ~= 0x42 or readu8(b, p + 1) ~= 0x5A or readu8(b, p + 2) ~= 0x68 then + break -- trailing data after a stream is ignored, as bzip2 -d does + end + end + if p + 4 > e then + return nil, "truncated stream header", "truncated" + end + if readu8(b, p) ~= 0x42 or readu8(b, p + 1) ~= 0x5A or readu8(b, p + 2) ~= 0x68 then + return nil, "bad magic", "corrupt" + end + local level = readu8(b, p + 3) - 0x30 + if level < 1 or level > 9 then + return nil, "bad block size", "corrupt" + end + local maxBlock = level * 100000 + if ttSize < maxBlock then + tt = bcreate(maxBlock * 4) + ttSize = maxBlock + end + local T = tt :: buffer + p += 4 + bb, bc = 0, 0 + local combined = 0 + + while true do + -- 48-bit magic + 32-bit CRC + while bc <= 24 do + bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0) + p += 1 + bc += 8 + end + local m1 = band(rshift(bb, bc - 24), 0xFFFFFF) + bc -= 24 + while bc <= 24 do + bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0) + p += 1 + bc += 8 + end + local m2 = band(rshift(bb, bc - 24), 0xFFFFFF) + bc -= 24 + while bc <= 24 do + bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0) + p += 1 + bc += 8 + end + local c1 = band(rshift(bb, bc - 16), 0xFFFF) + bc -= 16 + while bc <= 24 do + bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0) + p += 1 + bc += 8 + end + local storedCrc = band(rshift(bb, bc - 16), 0xFFFF) + c1 * 65536 + bc -= 16 + if (p - o) * 8 - bc > (e - o) * 8 then + return nil, "truncated block header", "truncated" + end + if m1 == 0x177245 and m2 == 0x385090 then + if storedCrc ~= combined then + return nil, string.format("stream CRC mismatch (%08x, expected %08x)", combined, storedCrc), "checksum" + end + -- align to the byte after the stream + p -= bc // 8 + bb, bc = 0, 0 + break + end + if m1 ~= 0x314159 or m2 ~= 0x265359 then + return nil, "bad block magic", "corrupt" + end + + -- randomised bit, origPtr, symbol map + while bc <= 24 do + bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0) + p += 1 + bc += 8 + end + local rnd = band(rshift(bb, bc - 1), 1) + bc -= 1 + while bc <= 24 do + bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0) + p += 1 + bc += 8 + end + local origPtr = band(rshift(bb, bc - 24), 0xFFFFFF) + bc -= 24 + if rnd ~= 0 then + return nil, "randomised blocks (bzip2 0.9.0 and older) are not supported", "unsupported" + end + while bc <= 24 do + bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0) + p += 1 + bc += 8 + end + local used = band(rshift(bb, bc - 16), 0xFFFF) + bc -= 16 + local nInUse = 0 + for i = 0, 15 do + if band(used, lshift(1, 15 - i)) ~= 0 then + while bc <= 24 do + bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0) + p += 1 + bc += 8 + end + local bits = band(rshift(bb, bc - 16), 0xFFFF) + bc -= 16 + for j = 0, 15 do + if band(bits, lshift(1, 15 - j)) ~= 0 then + SEQ[nInUse + 1] = i * 16 + j + nInUse += 1 + end + end + end + end + if nInUse == 0 then + return nil, "no symbols in use", "corrupt" + end + local alphaSize = nInUse + 2 + + -- groups and selectors + while bc <= 24 do + bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0) + p += 1 + bc += 8 + end + local nGroups = band(rshift(bb, bc - 3), 7) + bc -= 3 + local nSelectors = band(rshift(bb, bc - 15), 0x7FFF) + bc -= 15 + if nGroups < 2 or nGroups > 6 then + return nil, "bad number of Huffman groups", "corrupt" + end + if nSelectors < 1 then + return nil, "no selectors", "corrupt" + end + local selectors = buffer.create(nSelectors) + local mtfg0, mtfg1, mtfg2, mtfg3, mtfg4, mtfg5 = 0, 1, 2, 3, 4, 5 + for i = 0, nSelectors - 1 do + local j = 0 + while true do + if bc <= 24 then + bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0) + p += 1 + bc += 8 + end + bc -= 1 + if band(rshift(bb, bc), 1) == 0 then + break + end + j += 1 + if j >= nGroups then + return nil, "bad selector", "corrupt" + end + end + -- move-to-front over the group list + local v + if j == 0 then + v = mtfg0 + elseif j == 1 then + v = mtfg1 + mtfg1 = mtfg0 + elseif j == 2 then + v = mtfg2 + mtfg2, mtfg1 = mtfg1, mtfg0 + elseif j == 3 then + v = mtfg3 + mtfg3, mtfg2, mtfg1 = mtfg2, mtfg1, mtfg0 + elseif j == 4 then + v = mtfg4 + mtfg4, mtfg3, mtfg2, mtfg1 = mtfg3, mtfg2, mtfg1, mtfg0 + else + v = mtfg5 + mtfg5, mtfg4, mtfg3, mtfg2, mtfg1 = mtfg4, mtfg3, mtfg2, mtfg1, mtfg0 + end + mtfg0 = v + writeu8(selectors, i, v) + end + if (p - o) * 8 - bc > (e - o) * 8 then + return nil, "truncated selectors", "truncated" + end + + -- code lengths (delta coded) + for g = 0, nGroups - 1 do + while bc <= 24 do + bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0) + p += 1 + bc += 8 + end + local len = band(rshift(bb, bc - 5), 31) + bc -= 5 + for s = 0, alphaSize - 1 do + while true do + if len < 1 or len > MAXLEN then + return nil, "bad code length", "corrupt" + end + if bc <= 24 then + bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0) + p += 1 + bc += 8 + end + bc -= 1 + if band(rshift(bb, bc), 1) == 0 then + break + end + bc -= 1 + if band(rshift(bb, bc), 1) == 0 then + len += 1 + else + len -= 1 + end + end + writeu8(LENS, g * MAXALPHA + s, len) + end + if not buildGroup(g, alphaSize) then + return nil, "over-subscribed Huffman code", "corrupt" + end + end + if (p - o) * 8 - bc > (e - o) * 8 then + return nil, "truncated code lengths", "truncated" + end + + -- MTF / RUNA / RUNB symbols -> T low bytes + for i = 0, 255 do + CFTAB[i + 1] = 0 + MTF[i + 1] = i + end + local eob = alphaSize - 1 + local nblock = 0 + local selIdx = 0 + local left = 0 + local g = 0 + local tbase, pbase, cbase, gmax = 0, 0, 0, 0 + local runLen, runBit = 0, 1 + while true do + if left == 0 then + if selIdx >= nSelectors then + return nil, "ran out of selectors", "corrupt" + end + g = readu8(selectors, selIdx) + selIdx += 1 + left = 50 + tbase = g * PSIZE * 4 + pbase = g * MAXALPHA + cbase = g * (MAXLEN + 1) + gmax = MAXL[g + 1] + end + left -= 1 + while bc <= 24 do + bb = bor(lshift(bb, 8), if p < e then readu8(b, p) else 0) + p += 1 + bc += 8 + end + local ent = readu32(LOOK, tbase + band(rshift(bb, bc - PBITS), PSIZE - 1) * 4) + local sym + if ent ~= 0 then + bc -= band(ent, 31) + sym = rshift(ent, 5) + else + -- a code longer than PBITS: canonical search + local v = band(rshift(bb, bc - gmax), MASK[gmax + 1]) + sym = -1 + for l = PBITS + 1, gmax do + local c = rshift(v, gmax - l) + local f = FIRST[cbase + l + 1] + local k = c - f + if k >= 0 and k < COUNT[cbase + l + 1] then + sym = PERM[pbase + OFFS[cbase + l + 1] + k + 1] + bc -= l + break + end + end + if sym < 0 then + return nil, "bad Huffman code", "corrupt" + end + end + if sym <= 1 then + -- RUNA / RUNB: bijective base-2 run length of the front symbol + runLen += runBit * (sym + 1) + runBit *= 2 + if runLen > maxBlock then + return nil, "run past the block size", "corrupt" + end + else + if runLen > 0 then + if nblock + runLen > maxBlock then + return nil, "block larger than its declared size", "corrupt" + end + local ch = SEQ[MTF[1] + 1] + CFTAB[ch + 1] += runLen + for k = nblock, nblock + runLen - 1 do + writeu32(T, k * 4, ch) + end + nblock += runLen + runLen, runBit = 0, 1 + end + if sym == eob then + break + end + local idx = sym - 1 + if idx >= nInUse then + return nil, "bad MTF index", "corrupt" + end + if nblock >= maxBlock then + return nil, "block larger than its declared size", "corrupt" + end + local v = MTF[idx + 1] + for k = idx, 1, -1 do + MTF[k + 1] = MTF[k] + end + MTF[1] = v + local ch = SEQ[v + 1] + CFTAB[ch + 1] += 1 + writeu32(T, nblock * 4, ch) + nblock += 1 + end + if (p - o) * 8 - bc > (e - o) * 8 then + return nil, "truncated block data", "truncated" + end + end + if origPtr >= nblock then + return nil, "bad BWT origin pointer", "corrupt" + end + + -- inverse BWT: T[pos] |= i << 8 at each byte's sorted position + local sum = 0 + for i = 0, 255 do + local c = CFTAB[i + 1] + CFTAB[i + 1] = sum + sum += c + end + for i = 0, nblock - 1 do + local ch = band(readu32(T, i * 4), 255) + local k = CFTAB[ch + 1] + CFTAB[ch + 1] = k + 1 + writeu32(T, k * 4, bor(readu32(T, k * 4), lshift(i, 8))) + end + + -- walk, undo RLE1, CRC + if op + nblock + 4096 > blen(out) then + out = grow(out, op, op + nblock + 4096) + end + local cap = blen(out) + local crc = 0xFFFFFFFF + local tPos = rshift(readu32(T, origPtr * 4), 8) + local last, run = -1, 0 + local i = 0 + while i < nblock do + local v = readu32(T, tPos * 4) + local ch = band(v, 255) + tPos = rshift(v, 8) + i += 1 + if run == 4 then + -- ch is a repeat count for the previous byte + if ch > 0 then + if op + ch > maxBytes then + return nil, "output larger than maxBytes", "limit" + end + if op + ch + 256 > cap then + out = grow(out, op, op + ch + nblock - i + 4096) + cap = blen(out) + end + bfill(out, op, last, ch) + op += ch + for _ = 1, ch do + crc = bxor(lshift(crc, 8), CT[bxor(rshift(crc, 24), last) + 1]) + end + end + run = 0 + last = -1 + else + if ch == last then + run += 1 + else + run = 1 + last = ch + end + if op + 256 > cap then + if op >= maxBytes then + return nil, "output larger than maxBytes", "limit" + end + out = grow(out, op, op + nblock - i + 4096) + cap = blen(out) + end + writeu8(out, op, ch) + op += 1 + crc = bxor(lshift(crc, 8), CT[bxor(rshift(crc, 24), ch) + 1]) + end + end + if op > maxBytes then + return nil, "output larger than maxBytes", "limit" + end + crc = bxor(crc, 0xFFFFFFFF) + if crc ~= storedCrc then + return nil, string.format("block CRC mismatch (%08x, expected %08x)", crc, storedCrc), "checksum" + end + combined = bxor(bor(lshift(combined, 1), rshift(combined, 31)), crc) + end + streams += 1 + consumedEnd = p + if p >= e then + break + end + end + return out, op, consumedEnd +end + +return Decode diff --git a/src/Formats/codecs/Bzip2/init.luau b/src/Formats/codecs/Bzip2/init.luau new file mode 100644 index 0000000..e492aee --- /dev/null +++ b/src/Formats/codecs/Bzip2/init.luau @@ -0,0 +1,77 @@ +--!strict +-- codecs/Bzip2: bzip2 decompressor (BWT + MTF + Huffman, the .bz2 stream format of bzip2 0.9.5 / 1.0.x). A codec +-- (layer 3): archive/bz2 and tar.bz2 build on it. Written from the format description (no third-party code). +-- Supports: block sizes 1..9, every Huffman group layout, block and stream CRCs, concatenated streams (as bzip2 -d). +-- Not supported: randomised blocks (bzip2 0.9.0 and older; Err.UNSUPPORTED), compression. +-- +-- local Bzip2 = require("@formats/codecs/Bzip2") +-- local out, consumedEnd = Bzip2.decompress(buf) -- | nil, Err +-- local out = Bzip2.decompress(buf, offset, length, { maxBytes = 2^24 }) +-- +-- Never throws: bad data and bad arguments return nil, Err (TRUNCATED / CORRUPT / CHECKSUM / LIMIT / ARG). +local Err = require("@formats/core/Err") +local Decode = require("@formats/codecs/Bzip2/Decode") + +local Bzip2 = {} + +export type Options = { + maxBytes: number?, -- refuse output larger than this (default 2^30) +} + +local KINDS = { + truncated = Err.TRUNCATED, + corrupt = Err.CORRUPT, + checksum = Err.CHECKSUM, + limit = Err.LIMIT, + unsupported = Err.UNSUPPORTED, +} + +-- decompress(buf, offset?, length?, opts?) -> buffer, consumedEnd | nil, Err +function Bzip2.decompress(buf: buffer | string, offset: number?, length: number?, opts: Options?): (buffer?, any) + local b: buffer + if type(buf) == "string" then + b = buffer.fromstring(buf) + elseif type(buf) == "buffer" then + b = buf + else + return nil, Err.new(Err.ARG, "Bzip2.decompress: expected a buffer or a string, got " .. typeof(buf)) + end + local n = buffer.len(b) + local o = offset or 0 + if type(o) ~= "number" or o < 0 or o > n or o % 1 ~= 0 then + return nil, Err.new(Err.ARG, "Bzip2.decompress: bad offset " .. tostring(offset)) + end + local l = length or (n - o) + if type(l) ~= "number" or l < 0 or l % 1 ~= 0 then + return nil, Err.new(Err.ARG, "Bzip2.decompress: bad length " .. tostring(length)) + end + l = math.min(l, n - o) + local maxBytes = if opts and opts.maxBytes ~= nil then opts.maxBytes else 2 ^ 30 + if type(maxBytes) ~= "number" or maxBytes < 0 then + return nil, Err.new(Err.ARG, "Bzip2.decompress: bad maxBytes") + end + local out, nOut, consumed = Decode.decode(b, o, o + l, maxBytes) + if not out then + return nil, Err.new(KINDS[consumed] or Err.CORRUPT, "bzip2: " .. tostring(nOut), o) + end + local res = out + if buffer.len(out) ~= nOut then + res = buffer.create(nOut) + buffer.copy(res, 0, out, 0, nOut) + end + return res, consumed +end + +-- crc(buf, offset?, length?) -> the CRC-32/BZIP2 of a range (the block CRC bzip2 stores) +function Bzip2.crc(buf: buffer, offset: number?, length: number?): number + local CT = Decode.crcTable + local o = offset or 0 + local e = o + (length or (buffer.len(buf) - o)) + local c = 0xFFFFFFFF + for i = o, e - 1 do + c = bit32.bxor(bit32.lshift(c, 8), CT[bit32.bxor(bit32.rshift(c, 24), buffer.readu8(buf, i)) + 1]) + end + return bit32.bxor(c, 0xFFFFFFFF) +end + +return Bzip2 diff --git a/tests/archive/bz2.luau b/tests/archive/bz2.luau new file mode 100644 index 0000000..506b155 --- /dev/null +++ b/tests/archive/bz2.luau @@ -0,0 +1,65 @@ +-- archive/bz2 tests: the contract, sniff, a .bz2 as a one-entry single-stream archive (entry named after the file), +-- the api path (F.load by sniff, .tar.bz2 unwrap is the api's: covered once tar exists), errors, the fuzz pass. +-- Fixtures: tools/fixtures/bzip2.py. +local T = require("@tests/T") +local Bz2 = require("@formats/archive/bz2") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local F = require("@formats") +local Fx = require("@tests/gen/bzip2") + +local t = T.suite("bz2") + +t:eq(Bz2.name, "bz2", "name") +t:eq(Bz2.category, "archive", "category") +t:check(Bz2.caps.decode and not Bz2.caps.encode, "caps") + +for _, c in Fx.cases do + t:eq(Bz2.sniff(Bytes.reader(buffer.fromstring(c.data))), 1, c.name .. ": sniff") +end +t:eq(Bz2.sniff(Bytes.reader(buffer.fromstring("BZh9hello"))), 0, "sniff: no block magic") +t:eq(Bz2.sniff(Bytes.reader(buffer.fromstring("\x1f\x8b\x08\x00"))), 0, "sniff: gzip") + +do + local c = Fx.cases[1] + for _, x in Fx.cases do + if x.name == "text/l9" then + c = x + end + end + local a, err = Bz2.decode(Bytes.reader(buffer.fromstring(c.data)), { name = "dir/notes.txt.bz2" }) + t:check(a, "decode: " .. tostring(err)) + t:check(a.kind == "archive" and a.format == "bz2" and a.meta.stream, "a single-stream archive") + local list = a:list() + t:eq(#list, 1, "one entry") + t:eq(list[1].name, "notes.txt", "entry named after the file") + t:eq(list[1].size, #Fx.corpora.text, "entry size") + t:eq(list[1].compressedSize, #c.data, "compressed size") + t:check(buffer.tostring((a:read("notes.txt"))) == Fx.corpora.text, "read") + local _, re = a:read("nope") + t:check(re and re.code == Err.ARG, "read of a missing entry") + local _, we = a:write() + t:check(we and we.code == Err.UNSUPPORTED, "read-only") + local a2 = Bz2.decode(Bytes.reader(buffer.fromstring(c.data)), { name = "x.tbz2" }) + t:eq(a2:list()[1].name, "x.tar", ".tbz2 -> .tar") + local a3 = Bz2.decode(Bytes.reader(buffer.fromstring(c.data))) + t:eq(a3:list()[1].name, "data", "no name -> data") + -- through the api + local v, ferr = F.load(c.data) + t:check(v and v.kind == "archive" and v.format == "bz2", "F.load sniffs bz2: " .. tostring(ferr)) + t:eq(F.detect(c.data), "bz2", "F.detect") + local _, de = Bz2.decode(Bytes.reader(buffer.fromstring(string.sub(c.data, 1, 100)))) + t:check(de and de.code == Err.TRUNCATED, "truncated: " .. tostring(de)) +end + +local samples = {} +for i, c in Fx.cases do + if i % 6 == 0 and #c.data < 30000 then + table.insert(samples, c.data) + end +end +t:fuzz("decode", function(b: buffer) + return Bz2.decode(Bytes.reader(b)) +end, samples, { mutations = 6, garbage = 300 }) + +t:done() diff --git a/tests/codecs/bzip2.luau b/tests/codecs/bzip2.luau new file mode 100644 index 0000000..71a872d --- /dev/null +++ b/tests/codecs/bzip2.luau @@ -0,0 +1,103 @@ +-- codecs/Bzip2 tests: every fixture stream (Python bz2 = libbzip2, block sizes 1..9, RLE1 run edges, block-boundary +-- runs, random / skewed data, concatenated streams with trailing garbage) decodes exactly; offsets / consumedEnd; +-- maxBytes; CRC mismatches are Err.CHECKSUM; truncations are Err.TRUNCATED; the fuzz no-throw pass. +-- Fixtures: tools/fixtures/bzip2.py. +local T = require("@tests/T") +local Bzip2 = require("@formats/codecs/Bzip2") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/bzip2") + +local t = T.suite("bzip2") + +t:eq(Bzip2.crc(buffer.fromstring("123456789")), 0xFC891918, "CRC-32/BZIP2 check value") + +local nbytes = 0 +for _, c in Fx.cases do + local want = Fx.corpora[c.corpus] + local out, consumed = Bzip2.decompress(c.data) + t:check(out ~= nil, c.name .. ": " .. tostring(consumed)) + t:check(buffer.tostring(out :: buffer) == want, c.name .. ": output differs") + if c.name ~= "multi/trailing" then + t:eq(consumed, #c.data, c.name .. ": consumedEnd") + end + nbytes += #want +end +t:note("%d fixture streams, %.1f MB decoded", #Fx.cases, nbytes / 1e6) + +local function case(name: string): any + for _, c in Fx.cases do + if c.name == name then + return c + end + end + error("no case " .. name) +end + +-- inside a bigger buffer, at an offset +do + local c = case("text/l9") + local big = buffer.create(#c.data + 20) + buffer.fill(big, 0, 0xAB) + buffer.writestring(big, 7, c.data) + local out, consumed = Bzip2.decompress(big, 7, #c.data + 5) + t:check(out and buffer.tostring(out) == Fx.corpora.text, "at an offset") + t:eq(consumed, 7 + #c.data, "consumedEnd at an offset") +end + +-- maxBytes +do + local c = case("zeros/l9") + local _, e = Bzip2.decompress(c.data, nil, nil, { maxBytes = 1000 }) + t:check(e and e.code == Err.LIMIT, "maxBytes: " .. tostring(e)) + local ok = Bzip2.decompress(c.data, nil, nil, { maxBytes = 250000 }) + t:check(ok ~= nil, "maxBytes = exact size") +end + +-- block CRC / stream CRC mismatches +do + local c = case("text/l9") + local b = buffer.fromstring(c.data) + -- block CRC sits at bytes 10..13 (after "BZh9" + 6 magic bytes) + buffer.writeu8(b, 11, bit32.bxor(buffer.readu8(b, 11), 0x10)) + local _, e = Bzip2.decompress(b) + t:check(e and e.code == Err.CHECKSUM, "block CRC mismatch: " .. tostring(e)) + local s = case("one/l9") + local b2 = buffer.fromstring(s.data) + local n = buffer.len(b2) + buffer.writeu8(b2, n - 2, bit32.bxor(buffer.readu8(b2, n - 2), 0x01)) + local _, e2 = Bzip2.decompress(b2) + t:check(e2 and (e2.code == Err.CHECKSUM or e2.code == Err.CORRUPT), "stream CRC mismatch: " .. tostring(e2)) +end + +-- truncation -> TRUNCATED, bad magic -> CORRUPT, bad args -> ARG +do + local c = case("text/l1") + for _, cut in { 3, 10, 40, #c.data // 2, #c.data - 3 } do + local _, e = Bzip2.decompress(string.sub(c.data, 1, cut)) + t:check(e and e.code == Err.TRUNCATED, "truncated at " .. cut .. ": " .. tostring(e)) + end + local _, e = Bzip2.decompress("BZx9abcdefgh") + t:check(e and e.code == Err.CORRUPT, "bad magic") + local _, e2 = Bzip2.decompress(5 :: any) + t:check(e2 and e2.code == Err.ARG, "non-buffer") + local _, e3 = Bzip2.decompress("BZh9", -1) + t:check(e3 and e3.code == Err.ARG, "bad offset") +end + +-- fuzz +do + local samples = {} + for i, c in Fx.cases do + if i % 4 == 0 and #c.data < 40000 then + table.insert(samples, c.data) + end + end + t:fuzz("decompress", function(b: buffer) + return Bzip2.decompress(b) + end, samples, { mutations = 12, garbage = 1000, keepHeader = 4 }) + t:fuzz("decompress (no header kept)", function(b: buffer) + return Bzip2.decompress(b) + end, samples, { mutations = 4, garbage = 200 }) +end + +t:done() diff --git a/tools/fixtures/bzip2.py b/tools/fixtures/bzip2.py new file mode 100644 index 0000000..0464a8a --- /dev/null +++ b/tools/fixtures/bzip2.py @@ -0,0 +1,61 @@ +# Bzip2 fixtures (tools/fixtures.py): deterministic corpora compressed with Python's bz2 module (libbzip2) at block +# sizes 1..9, RLE1 edge cases (runs of 1..300 bytes, runs straddling block ends), every byte value, random data, +# concatenated streams with trailing garbage; plus a 4 MB bench corpus. +# tests/gen/bzip2.luau { corpora = { [name] = bytes }, cases = { { name, corpus, data } } } +# tests/gen/bzip2_bench.luau { size, crc, data } +import bz2, os, 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 generate(ctx): + rng = ctx.rng(7) + runs = bytearray() + for n in list(range(1, 20)) + [250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 300, 1000, 5000]: + runs += bytes([n % 251]) * n + b"x" + corpora = { + "empty": b"", + "one": b"a", + "two": b"ab", + "four": b"aaaa", + "five": b"aaaaa", + "text": text_corpus(300000), + "random": rng.randbytes(60000), + "runs": bytes(runs), + "zeros": b"\0" * 250000, + "allbytes": bytes(range(256)) * 50, + "binary": bytes(rng.choice(b"\0\0\0\x01\x02\xff ABC") for _ in range(40000)), + # a run crossing the 100k block boundary at level 1 + "boundary": b"q" * 99990 + b"r" * 30 + rng.randbytes(1000), + # more than 18 Huffman group switches / many symbols in use + "skewed": bytes(rng.choice(range(256)) if rng.random() < 0.1 else 65 for _ in range(120000)), + } + cases = [] + for cname, data in corpora.items(): + for level in (1, 5, 9) if len(data) > 1000 else (9,): + cases.append(("%s/l%d" % (cname, level), cname, bz2.compress(data, level))) + for level in range(1, 10): + cases.append(("text/all-l%d" % level, "text", bz2.compress(corpora["text"], level))) + corpora["multi"] = corpora["text"][:20000] + b"" + corpora["runs"] + multi = bz2.compress(corpora["text"][:20000], 9) + bz2.compress(b"", 1) + bz2.compress(corpora["runs"], 3) + cases.append(("multi/streams", "multi", multi)) + cases.append(("multi/trailing", "multi", multi + b"garbage after the last stream")) + ctx.emit("bzip2", { + "corpora": corpora, + "cases": [{"name": n, "corpus": c, "data": d} for n, c, d in cases], + }) + bench = bytearray() + while len(bench) < 4_000_000: + bench += corpora["text"] + corpora["binary"] + rng.randbytes(20000) + bench = bytes(bench[:4_000_000]) + ctx.emit("bzip2_bench", {"size": len(bench), "crc": zlib.crc32(bench), "data": bz2.compress(bench, 9)})