From c54c8daff5f93e0448d18524c1b2603fd1991f7f Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 15:46:28 -0500 Subject: [PATCH] ws-arch2-cab: codecs/compress/Lzx (CAB LZX: windows 2^15..2^21, verbatim / aligned / uncompressed blocks, delta-coded trees, R0..R2, E8 translation, 32 KB frames; written from the spec) + cab LZX folders, checked against cabextract on cabinets of a fixture LZX compressor (tools/fixtures/_lzx.py) and libmspack's samples; Deflate.mszip (generic MSZIP blocks: CK + deflate, dictionary carried across blocks; for cab and later model/x); cab bench lines --- docs/FORMATS.md | 3 +- src/Formats/Registry.luau | 4 +- src/Formats/archive/cab/init.luau | 56 ++- src/Formats/codecs/compress/Deflate/init.luau | 37 +- src/Formats/codecs/compress/Lzx.luau | 449 ++++++++++++++++++ tests/archive/cab.luau | 36 +- tools/bench.luau | 28 +- tools/fixtures/_lzx.py | 351 ++++++++++++++ tools/fixtures/cab.py | 75 ++- 9 files changed, 990 insertions(+), 49 deletions(-) create mode 100644 src/Formats/codecs/compress/Lzx.luau create mode 100644 tools/fixtures/_lzx.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index a89ec21..dd393f3 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -70,7 +70,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | archive | binhex | .hqx .hcx | yes | yes | forks: true | `tests/archive/binhex.luau` | | archive | br | .br | yes | - | stream: true | `tests/archive/br.luau` | | archive | bz2 | .bz2 .tbz2 .tbz | yes | - | stream: true | `tests/archive/bz2.luau` | -| archive | cab | .cab | yes | yes | methods: "store", "mszip" | `tests/archive/cab.luau` | +| archive | cab | .cab | yes | yes | methods: "store", "mszip", "lzx" | `tests/archive/cab.luau` | | archive | cpio | .cpio | yes | yes | variants: "newc", "crc", "odc", "bin" | `tests/archive/cpio.luau` | | archive | d64 | .d64 .d71 .d81 | yes | yes | variants: "d64", "d71", "d81" | `tests/archive/d64.luau` | | archive | fat | .img .ima .vfd .flp .fat | yes | yes | variants: "fat12", "fat16", "fat32" | `tests/archive/fat.luau` | @@ -140,6 +140,7 @@ Codecs (layer 3, shared by formats; not loadable on their own), by domain: - codecs/compress/Lzh: the LHA family of LZSS decoders, used by archive/lha, archive/arj and archive/zoo: - codecs/compress/Lzma: LZMA and LZMA2 decoders, the .lzma ("LZMA alone") wrapper and the .xz container. A codec (layer 3): - codecs/compress/Lzw: LZW decoder and encoder in the two variants file formats use. A codec (layer 1): image/gif and + - codecs/compress/Lzx: the LZX decoder as Microsoft Cabinet folders use it: windows of 2^15 .. 2^21 bytes, - codecs/compress/PackBits: the Apple PackBits run-length code (TIFF compression 32773, PSD / PSB RLE channels, IFF - codecs/compress/UnixCompress: the LZW of Unix compress (.Z files: magic 1F 9D, a flags byte with the maximum code - codecs/compress/Xxh32: XXH32 of a buffer range (any seed), for the LZ4 frame format's header, block and content diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 6e81c47..ccac4a7 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -800,8 +800,8 @@ local list: { Entry } = { path = "archive/cab", extensions = { "cab" }, mime = { "application/vnd.ms-cab-compressed" }, - deps = { "core/Err", "core/Bytes", "codecs/compress/Deflate", "containers/Archive" }, - caps = { decode = true, encode = true, methods = { "store", "mszip" } }, + deps = { "core/Err", "core/Bytes", "codecs/compress/Deflate", "codecs/compress/Lzx", "containers/Archive" }, + caps = { decode = true, encode = true, methods = { "store", "mszip", "lzx" } }, load = function() return require("@formats/archive/cab") end, diff --git a/src/Formats/archive/cab/init.luau b/src/Formats/archive/cab/init.luau index cb30c8e..62d29d1 100644 --- a/src/Formats/archive/cab/init.luau +++ b/src/Formats/archive/cab/init.luau @@ -14,6 +14,7 @@ local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Deflate = require("@formats/codecs/compress/Deflate") +local Lzx = require("@formats/codecs/compress/Lzx") local Archive = require("@formats/containers/Archive") local Sum = require("@formats/archive/cab/Sum") @@ -23,8 +24,8 @@ local Cab = { category = "archive", extensions = { "cab" }, mime = { "application/vnd.ms-cab-compressed" }, - deps = { "core/Err", "core/Bytes", "codecs/compress/Deflate", "containers/Archive" }, - caps = { decode = true, encode = true, methods = { "store", "mszip" } }, + deps = { "core/Err", "core/Bytes", "codecs/compress/Deflate", "codecs/compress/Lzx", "containers/Archive" }, + caps = { decode = true, encode = true, methods = { "store", "mszip", "lzx" } }, } export type DecodeOptions = { @@ -108,25 +109,28 @@ local function inflateFolder(buf: buffer, list: { Block }, total: number, typ: n end return out, nil elseif method == 1 then + local spans: { { offset: number, length: number, size: number } } = {} + for _, b in list do + table.insert(spans, { offset = b.at, length = b.len, size = b.size }) + end + return Deflate.mszip(buf, spans) + elseif method == 3 then + local bits = bit32.band(bit32.rshift(typ, 8), 31) + local n = 0 + for _, b in list do + n += b.len + end + local src = buffer.create(n) local o = 0 for _, b in list do - if b.len < 2 or buffer.readu16(buf, b.at) ~= 0x4B43 then - return nil, Err.new(Err.CORRUPT, "MSZIP block without its CK signature", b.at) - end - local dict: buffer? = nil - if o > 0 then - local d = math.min(o, BLOCK) - dict = buffer.create(d) - buffer.copy(dict :: buffer, 0, out, o - d, d) - end - local part, err = Deflate.inflate(buf, b.at + 2, b.len - 2, b.size, dict) - if not part then - return nil, err - end - buffer.copy(out, o, part, 0, b.size) - o += b.size + buffer.copy(src, o, buf, b.at, b.len) + o += b.len end - return out, nil + local res, err = Lzx.decode(src, 0, n, total, bits) + if not res then + return nil, Err.from(err) + end + return res, nil end return nil, Err.new(Err.UNSUPPORTED, "compression type " .. method) end @@ -199,6 +203,9 @@ function Cab.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) } end meta.folders = methods + if cFiles == 0 or cFolders == 0 then + return nil, Err.new(Err.CORRUPT, "a cabinet without files or folders") + end if cFiles > maxEntries then return nil, Err.new(Err.LIMIT, "more than maxEntries files") end @@ -307,6 +314,9 @@ function Cab.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err?) if not files then return nil, ferr end + if #files == 0 then + return nil, Err.new(Err.ARG, "a cabinet needs at least one file") + end if #files > 65535 then return nil, Err.new(Err.ARG, "more than 65535 files") end @@ -373,7 +383,7 @@ function Cab.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err?) offset += buffer.len(f.data) end local fileTable = table_:finish() - local nfolders = if #files > 0 then 1 else 0 + local nfolders = 1 local coffFiles = 36 + 8 * nfolders local dataAt = coffFiles + buffer.len(fileTable) local size = dataAt + buffer.len(blob) @@ -391,11 +401,9 @@ function Cab.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err?) w:u16le(0) w:u16le(o.setId or 0) w:u16le(0) - if nfolders == 1 then - w:u32le(dataAt) - w:u16le(nblocks) - w:u16le(if compression == "mszip" then 1 else 0) - end + w:u32le(dataAt) + w:u16le(nblocks) + w:u16le(if compression == "mszip" then 1 else 0) w:bytes(fileTable) w:bytes(blob) return w:finish(), nil diff --git a/src/Formats/codecs/compress/Deflate/init.luau b/src/Formats/codecs/compress/Deflate/init.luau index b4c5319..46ea9fe 100644 --- a/src/Formats/codecs/compress/Deflate/init.luau +++ b/src/Formats/codecs/compress/Deflate/init.luau @@ -6,7 +6,8 @@ -- local Deflate = require("@formats/codecs/compress/Deflate") -- local out, err = Deflate.inflate(buf) -- raw deflate -> buffer, consumedEnd | nil, Err -- local out, err = Deflate.inflate(buf, off, len, size) -- a range, with the exact output size if known --- local out, err = Deflate.inflate(buf, off, len, size, dict) -- with a preset dictionary (MSZIP blocks) +-- local out, err = Deflate.inflate(buf, off, len, size, dict) -- with a preset dictionary +-- local out, err = Deflate.mszip(buf, { { offset, length, size }, ... }) -- MSZIP blocks ("CK" + deflate, chained) -- local out, err = Deflate.zlib(buf) -- checks the Adler-32 -- local out, err = Deflate.gunzip(buf) -- checks CRC-32 + ISIZE, concatenates members -- local z = Deflate.compress(buf, { level = 6 }) -- raw deflate; also zlibCompress / gzip @@ -308,6 +309,40 @@ function Deflate.gzip(buf: buffer | string, opts: CompressOptions?): (buffer?, E return out, nil end +-- mszip(buf, blocks) -> buffer | nil, Err: MSZIP data (Microsoft's blocked deflate, as in CAB folders and DirectX .x +-- files): blocks = { { offset, length, size } }, each buf[offset, offset + length) = "CK" + a raw deflate stream that +-- inflates to exactly size bytes using the previous block's output (up to 32 KB) as its dictionary. Returns the +-- blocks' output concatenated. +function Deflate.mszip(buf: buffer, blocks: { { offset: number, length: number, size: number } }): (buffer?, Err.Err?) + local total = 0 + for _, b in blocks do + if b.offset < 0 or b.length < 0 or b.offset + b.length > buffer.len(buf) or b.size < 0 then + return nil, Err.new(Err.ARG, "Deflate.mszip: block out of range") + end + total += b.size + end + local out = buffer.create(total) + local o = 0 + for _, b in blocks do + if b.length < 2 or buffer.readu16(buf, b.offset) ~= 0x4B43 then + return nil, Err.new(Err.CORRUPT, "mszip: block without its CK signature", b.offset) + end + local dict: buffer? = nil + if o > 0 then + local d = math.min(o, 32768) + dict = buffer.create(d) + buffer.copy(dict :: buffer, 0, out, o - d, d) + end + local part, err = Deflate.inflate(buf, b.offset + 2, b.length - 2, b.size, dict) + if not part then + return nil, err + end + buffer.copy(out, o, part, 0, b.size) + o += b.size + end + return out, nil +end + -- crc32 / adler32 (kept from deflate-luau's API; the same as core/Crc32.of / core/Adler32.of) Deflate.crc32 = function(buf: buffer | string, offset: number?, length: number?, crc: number?): number local b = toBuffer(buf) or buffer.create(0) diff --git a/src/Formats/codecs/compress/Lzx.luau b/src/Formats/codecs/compress/Lzx.luau new file mode 100644 index 0000000..35a57fc --- /dev/null +++ b/src/Formats/codecs/compress/Lzx.luau @@ -0,0 +1,449 @@ +--!strict +--!native +--!optimize 2 +-- codecs/compress/Lzx: the LZX decoder as Microsoft Cabinet folders use it: windows of 2^15 .. 2^21 bytes, +-- verbatim, aligned offset and uncompressed blocks (block sizes of 24 bits, blocks spanning frames), the main and +-- length trees sent as deltas of the previous block's code lengths through a 20-symbol pre-tree (runs 17 / 18 / 19), +-- the three repeated offsets R0..R2, the Intel E8 call translation header (applied to the first 32768 frames, on the +-- output only), and the stream cut into frames of 32768 output bytes, each 16-bit aligned at its end; trees, offsets +-- and the window persist across the frames (the CFDATA blocks) of a folder. Written from the specification +-- (Microsoft's LZX data format documentation in the Cabinet SDK and the LZX sections of [MS-PATCH]); no code from +-- libmspack. Not supported: LZX DELTA reference data and reset intervals (CHM / WIM variants). +-- +-- local out, err = Lzx.decode(src, offset, length, outSize, windowBits) -- buffer | nil, message +-- +-- src[offset, offset + length) is the folder's compressed data (the CFDATA payloads concatenated), outSize its exact +-- uncompressed size. Never throws: bad or truncated data returns nil, message. +local Huffman = require("@formats/codecs/entropy/Huffman") + +local band, bor, lshift, rshift = bit32.band, bit32.bor, bit32.lshift, bit32.rshift +local readu8, readu16, readu32, readi32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readi32 +local writeu8, writei32 = buffer.writeu8, buffer.writei32 +local bcreate, bcopy, blen = buffer.create, buffer.copy, buffer.len + +local Lzx = {} + +local FRAME = 32768 +local MAINP, LENP, ALIGNP, PREP = 10, 8, 7, 6 +local MAXMAIN = 256 + 8 * 50 +local NLEN = 249 +local SAFETY = 64 -- pre-tree runs may run past the end of a tree: room for them (as the format's reference decoder) + +-- position slots: footer bits and base of each formatted offset slot +local EXTRA = table.create(51, 0) +local BASE = table.create(51, 0) +do + local b = 0 + for i = 0, 50 do + local e = if i < 4 then 0 else math.min(i // 2 - 1, 17) + EXTRA[i + 1] = e + BASE[i + 1] = b + b += lshift(1, e) + end +end +local SLOTS: { [number]: number } = { [15] = 30, [16] = 32, [17] = 34, [18] = 36, [19] = 38, [20] = 42, [21] = 50 } + +-- ------------------------------------------------------------------------------------------------ bit reader +-- 16-bit little-endian words read most significant bit first; bb holds cnt bits left aligned (cnt <= 32). Past the +-- end, zero words are read and over counts their bits. +type State = { src: buffer, pos: number, stop: number, bb: number, cnt: number, over: number } + +local function refill(s: State) + while s.cnt <= 16 do + local p = s.pos + local w = 0 + if p + 2 <= s.stop then + w = readu16(s.src, p) + s.pos = p + 2 + elseif p < s.stop then + w = readu8(s.src, p) + s.pos = p + 1 + s.over += 8 + else + s.over += 16 + end + s.bb = bor(s.bb, lshift(w, 16 - s.cnt)) + s.cnt += 16 + end +end + +-- bits(s, n) -> the next n (1..17) bits +local function bits(s: State, n: number): number + if s.cnt < n then + refill(s) + end + local v = rshift(s.bb, 32 - n) + s.bb = lshift(s.bb, n) + s.cnt -= n + return v +end + +-- sym(s, tab, P, S) -> the next symbol of an MSB Huffman table, -1 for an invalid code +local function sym(s: State, tab: buffer, P: number, S: number): number + if s.cnt < 16 then + refill(s) + end + local e = readu32(tab, rshift(s.bb, 32 - P) * 4) + local l = band(e, 31) + if l == 0 then + if e == 0 then + return -1 + end + e = readu32(tab, (rshift(e, 5) + band(rshift(s.bb, 32 - P - S), lshift(1, S) - 1)) * 4) + l = band(e, 31) + if l == 0 then + return -1 + end + end + s.bb = lshift(s.bb, l) + s.cnt -= l + return rshift(e, 5) +end + +-- readLens: the code lengths lens[first, last) as deltas of their previous values, through a fresh pre-tree +local function readLens(s: State, lens: buffer, first: number, last: number, pre: buffer, preLens: buffer): boolean + for i = 0, 19 do + writeu8(preLens, i, bits(s, 4)) + end + local S = Huffman.buildMsb(preLens, 0, 20, pre, PREP) + if S < 0 then + return false + end + local cap = blen(lens) + local x = first + while x < last do + local z = sym(s, pre, PREP, S) + if z < 0 then + return false + end + if z == 17 or z == 18 then + local run = if z == 17 then bits(s, 4) + 4 else bits(s, 5) + 20 + for _ = 1, run do + if x < cap then + writeu8(lens, x, 0) + end + x += 1 + end + elseif z == 19 then + local run = bits(s, 1) + 4 + local d = sym(s, pre, PREP, S) + if d < 0 or d > 16 then + return false + end + local v = (readu8(lens, x) - d + 17) % 17 + for _ = 1, run do + if x < cap then + writeu8(lens, x, v) + end + x += 1 + end + else + writeu8(lens, x, (readu8(lens, x) - z + 17) % 17) + x += 1 + end + end + return true +end + +-- ------------------------------------------------------------------------------------------------ decode +-- E8 translation of the decoded output, frame by frame (absolute call targets back to relative) +local function translate(out: buffer, n: number, size: number) + local base = 0 + local frame = 0 + while base < n and frame < 32768 do + local fs = math.min(FRAME, n - base) + if fs > 10 then + local i = base + local stop = base + fs - 10 + while i < stop do + if readu8(out, i) == 0xE8 then + local abs = readi32(out, i + 1) + if abs >= -i and abs < size then + writei32(out, i + 1, if abs >= 0 then abs - i else abs + size) + end + i += 5 + else + i += 1 + end + end + end + base += fs + frame += 1 + end +end + +function Lzx.decode(src: buffer, offset: number, length: number, outSize: number, windowBits: number): (buffer?, string?) + local nslots = SLOTS[windowBits] + if not nslots then + return nil, "unsupported: LZX window 2^" .. tostring(windowBits) + end + if offset < 0 or length < 0 or offset + length > blen(src) or outSize < 0 or outSize % 1 ~= 0 then + return nil, "bad arguments" + end + local windowSize = lshift(1, windowBits) + local mainN = 256 + 8 * nslots + local out = bcreate(outSize) + local mainLens, lenLens, alignLens, preLens = bcreate(MAXMAIN + SAFETY), bcreate(NLEN + SAFETY), bcreate(8), bcreate(20) + local mainTab = bcreate(Huffman.capacity(MAXMAIN, MAINP, 16) * 4) + local lenTab = bcreate(Huffman.capacity(NLEN, LENP, 16) * 4) + local alignTab = bcreate(Huffman.capacity(8, ALIGNP, 16) * 4) + local preTab = bcreate(Huffman.capacity(20, PREP, 16) * 4) + local s: State = { src = src, pos = offset, stop = offset + length, bb = 0, cnt = 0, over = 0 } + local R0: number, R1: number, R2: number = 1, 1, 1 + local intel = 0 + local started = false + local btype, bremain, bsize = 0, 0, 0 + local mainS, lenS, alignS = 0, 0, 0 + local op = 0 + while op < outSize do + local frameEnd = math.min(op + FRAME, outSize) + while op < frameEnd do + if bremain == 0 then + -- a new block + if btype == 3 and band(bsize, 1) == 1 then + s.pos += 1 + end + if not started then + started = true + if bits(s, 1) == 1 then + local hi = bits(s, 16) + intel = hi * 65536 + bits(s, 16) + end + end + btype = bits(s, 3) + local hi = bits(s, 16) + bsize = hi * 256 + bits(s, 8) + bremain = bsize + if s.over > s.cnt then + return nil, "truncated input" + end + if bsize == 0 then + return nil, "empty block" + end + if btype == 2 then + for i = 0, 7 do + writeu8(alignLens, i, bits(s, 3)) + end + alignS = Huffman.buildMsb(alignLens, 0, 8, alignTab, ALIGNP) + if alignS < 0 then + return nil, "bad aligned offset tree" + end + end + if btype == 1 or btype == 2 then + if not readLens(s, mainLens, 0, 256, preTab, preLens) or not readLens(s, mainLens, 256, mainN, preTab, preLens) then + return nil, "bad main tree" + end + mainS = Huffman.buildMsb(mainLens, 0, mainN, mainTab, MAINP) + if mainS < 0 then + return nil, "bad main tree" + end + if not readLens(s, lenLens, 0, NLEN, preTab, preLens) then + return nil, "bad length tree" + end + lenS = Huffman.buildMsb(lenLens, 0, NLEN, lenTab, LENP) + if lenS < 0 then + return nil, "bad length tree" + end + elseif btype == 3 then + -- 1..16 bits of padding to a 16-bit boundary, then R0..R2 and the bytes + local k = s.cnt % 16 + if k == 0 then + k = 16 + end + local p = s.pos - (s.cnt - k) // 8 + s.bb, s.cnt = 0, 0 + if s.over > 0 or p + 12 > s.stop then + return nil, "truncated uncompressed block" + end + R0 = readu32(src, p) + R1 = readu32(src, p + 4) + R2 = readu32(src, p + 8) + s.pos = p + 12 + else + return nil, "bad block type " .. btype + end + if s.over > s.cnt then + return nil, "truncated input" + end + end + local runEnd = op + math.min(bremain, frameEnd - op) + if btype == 3 then + local n = runEnd - op + local p = s.pos + if p + n > s.stop then + return nil, "truncated uncompressed block" + end + bcopy(out, op, src, p, n) + s.pos = p + n + op += n + bremain -= n + else + local bb, cnt, pos, over = s.bb, s.cnt, s.pos, s.over + local stop = s.stop + local aligned = btype == 2 + local start = op + while op < runEnd do + -- refill to at least 17 bits + while cnt <= 16 do + local w = 0 + if pos + 2 <= stop then + w = readu16(src, pos) + pos += 2 + elseif pos < stop then + w = readu8(src, pos) + pos += 1 + over += 8 + else + over += 16 + end + bb = bor(bb, lshift(w, 16 - cnt)) + cnt += 16 + end + local e = readu32(mainTab, rshift(bb, 32 - MAINP) * 4) + local l = band(e, 31) + if l == 0 then + if e == 0 then + return nil, "bad main code" + end + e = readu32(mainTab, (rshift(e, 5) + band(rshift(bb, 32 - MAINP - mainS), lshift(1, mainS) - 1)) * 4) + l = band(e, 31) + if l == 0 then + return nil, "bad main code" + end + end + bb = lshift(bb, l) + cnt -= l + local m = rshift(e, 5) + if m < 256 then + writeu8(out, op, m) + op += 1 + else + m -= 256 + local len = band(m, 7) + if len == 7 then + while cnt <= 16 do + local w = 0 + if pos + 2 <= stop then + w = readu16(src, pos) + pos += 2 + else + over += 16 + end + bb = bor(bb, lshift(w, 16 - cnt)) + cnt += 16 + end + local le = readu32(lenTab, rshift(bb, 32 - LENP) * 4) + local ll = band(le, 31) + if ll == 0 then + if le == 0 then + return nil, "bad length code" + end + le = readu32(lenTab, (rshift(le, 5) + band(rshift(bb, 32 - LENP - lenS), lshift(1, lenS) - 1)) * 4) + ll = band(le, 31) + if ll == 0 then + return nil, "bad length code" + end + end + bb = lshift(bb, ll) + cnt -= ll + len += rshift(le, 5) + end + len += 2 + local slot = rshift(m, 3) + local dist: number + if slot == 0 then + dist = R0 + elseif slot == 1 then + dist = R1 + R1 = R0 + R0 = dist + elseif slot == 2 then + dist = R2 + R2 = R0 + R0 = dist + else + local ex = EXTRA[slot + 1] + dist = BASE[slot + 1] - 2 + if ex > 0 then + while cnt <= 16 do + local w = 0 + if pos + 2 <= stop then + w = readu16(src, pos) + pos += 2 + else + over += 16 + end + bb = bor(bb, lshift(w, 16 - cnt)) + cnt += 16 + end + if aligned and ex >= 3 then + if ex > 3 then + dist += lshift(rshift(bb, 35 - ex), 3) + bb = lshift(bb, ex - 3) + cnt -= ex - 3 + while cnt <= 16 do + local w = 0 + if pos + 2 <= stop then + w = readu16(src, pos) + pos += 2 + else + over += 16 + end + bb = bor(bb, lshift(w, 16 - cnt)) + cnt += 16 + end + end + local ae = readu32(alignTab, rshift(bb, 32 - ALIGNP) * 4) + local al = band(ae, 31) + if al == 0 then + return nil, "bad aligned offset code" + end + bb = lshift(bb, al) + cnt -= al + dist += rshift(ae, 5) + else + dist += rshift(bb, 32 - ex) + bb = lshift(bb, ex) + cnt -= ex + end + end + R2 = R1 + R1 = R0 + R0 = dist + end + if dist < 1 or dist > op or dist > windowSize then + return nil, "match offset before the start of the data" + end + if op + len > runEnd then + return nil, "match past the end of its block or frame" + end + local from = op - dist + if dist >= len then + bcopy(out, op, out, from, len) + else + for k = 0, len - 1 do + writeu8(out, op + k, readu8(out, from + k)) + end + end + op += len + end + end + s.bb, s.cnt, s.pos, s.over = bb, cnt, pos, over + bremain -= op - start + end + end + -- the end of a frame: realign to 16 bits + local k = s.cnt % 16 + s.bb = lshift(s.bb, k) + s.cnt -= k + if s.over > s.cnt then + return nil, "truncated input" + end + end + if intel ~= 0 then + translate(out, outSize, intel) + end + return out, nil +end + +return Lzx diff --git a/tests/archive/cab.luau b/tests/archive/cab.luau index e818db3..ea61679 100644 --- a/tests/archive/cab.luau +++ b/tests/archive/cab.luau @@ -2,7 +2,9 @@ -- their dictionary (several folders, reserve areas, attributes, UTF-8 names) and libmspack's test cabinets give the -- files cabextract extracts (names, sizes, data CRCs, DOS times read as UTC); cabextract / gcab / 7z extract our -- writer's output (fixture step) and it round-trips; spanned files are UNSUPPORTED; checksum, truncation and --- signature errors; Deflate's preset dictionary; the fuzz pass. Fixtures: tools/fixtures/cab.py. +-- signature errors, libmspack's broken cabinets; LZX (codecs/compress/Lzx) from a fixture compressor whose cabinets +-- cabextract extracts (windows 2^15 .. 2^21, verbatim / aligned / uncompressed blocks, E8); Deflate's preset +-- dictionary; the fuzz pass. Fixtures: tools/fixtures/cab.py. local T = require("@tests/T") local F = require("@formats") local Cab = require("@formats/archive/cab") @@ -33,7 +35,7 @@ for _, c in Fx.cases do t:eq(F.detect(c.data), "cab", c.name .. ": detect") table.insert(samples, string.sub(c.data, 1, 4000)) end -t:check(methods.store and methods.mszip, "covers store and mszip") +t:check(methods.store and methods.mszip and methods.lzx, "covers store, mszip and lzx") -- attributes, UTF-8 names, reserve areas (the builder's two-folder cabinet) local two = assert(load(Fx.cases[5].data)) @@ -74,7 +76,35 @@ for _, c in Fx.spanned do end end --- Deflate's preset dictionary +-- libmspack's broken cabinets (cabextract fails on every one): an error (never a throw), not a full read +for _, c in Fx.bad do + local a = load(c.data) + local ok = a ~= nil + if a then + for _, e in a:list() do + if not a:read(e.name) then + ok = false + end + end + end + -- a 263-byte file name: over the format's 256-byte limit, which libmspack enforces and we do not + t:check(not ok or c.name == "cve-2017-11423-fname-overread.cab", c.name .. ": fails") + table.insert(samples, c.data) +end + +-- LZX directly +local Lzx = require("@formats/codecs/compress/Lzx") +t:check(not Lzx.decode(buffer.create(10), 0, 10, 100, 14), "LZX window 2^14 unsupported") +t:check(not Lzx.decode(buffer.create(10), 0, 10, 100, 16), "LZX of zeros") +t:check(not Lzx.decode(buffer.create(10), 4, 10, 100, 16), "LZX range past the end") + +-- Deflate's preset dictionary and MSZIP blocks +local block1 = assert(Deflate.compress(string.rep("ab", 50))) +local mszip = buffer.create(buffer.len(block1) + 2) +buffer.writestring(mszip, 0, "CK") +buffer.copy(mszip, 2, block1) +t:eq(buffer.tostring(assert(Deflate.mszip(mszip, { { offset = 0, length = buffer.len(mszip), size = 100 } }))), string.rep("ab", 50), "Deflate.mszip") +t:eq(select(2, Deflate.mszip(mszip, { { offset = 1, length = 4, size = 100 } })).code, Err.CORRUPT, "Deflate.mszip without CK") local dictText = string.rep("abcdefgh", 100) local z = assert(Deflate.compress(dictText .. dictText)) local plain = assert(Deflate.inflate(z, nil, nil, 1600, buffer.fromstring("unused prefix"))) diff --git a/tools/bench.luau b/tools/bench.luau index ffdaeba..ac29517 100644 --- a/tools/bench.luau +++ b/tools/bench.luau @@ -2,7 +2,7 @@ -- Fixtures: tools/fixtures/deflate.py (a 6 MB corpus), tools/fixtures/png.py (1024 x 768 images), tools/fixtures/mp3.py, -- tools/fixtures/opus.py (3 s stereo files; MB/s of f32 output, 48 kHz stereo f32 is 0.384 MB/s of real time), -- tools/fixtures/flac.py; wav encodes / decodes a generated tone; zstd / brotli / bzip2 / lzma / lz4 (*_bench corpora), .Z (tools/fixtures/z.py), fonts --- (glyphs per second), json / xml / yaml, jpeg / gif / tiff / qoi / tga / pnm / hdr and ImageOps. +-- (glyphs per second), cab (LZX / MSZIP / Quantum), json / xml / yaml, jpeg / gif / tiff / qoi / tga / pnm / hdr and ImageOps. local Deflate = require("@formats/codecs/compress/Deflate") local Crc32 = require("@formats/core/Crc32") local Bytes = require("@formats/core/Bytes") @@ -1177,6 +1177,32 @@ do end end end +-- ws-arch2 cabinets: LZX (codecs/compress/Lzx) and MSZIP folders of tools/fixtures/cab.py (MB/s of output; each run +-- decodes the cabinet again, so the folder cache does not count) +do + local Cab = require("@formats/archive/cab") + local CF = require("@tests/gen/cab") + for _, kind in { "lzx", "mszip" } do + local datas, total = {}, 0 + for _, c in CF.cases do + local a = Cab.decode(Bytes.reader(buffer.fromstring(c.data))) :: any + if a and a.meta.folders[1].method == kind and #c.data > 20000 then + table.insert(datas, buffer.fromstring(c.data)) + for _, e in a:list() do + total += e.size + end + end + end + bench("cab " .. kind .. " (" .. #datas .. " cabinets)", 5, total, function() + for _, d in datas do + local a = Cab.decode(Bytes.reader(d)) :: any + for _, e in a:list() do + a:read(e.name) + end + end + end) + end +end do -- NBT / voxels (ws-voxel): a chunk-like NBT tree (24 sections with packed long arrays, 4000 entity-like compounds) -- through codecs/text/Nbt (binary and SNBT), 1M packed 5-bit indices, a 64^3 Sponge schematic and Qubicle file diff --git a/tools/fixtures/_lzx.py b/tools/fixtures/_lzx.py new file mode 100644 index 0000000..8c07c87 --- /dev/null +++ b/tools/fixtures/_lzx.py @@ -0,0 +1,351 @@ +# A small LZX compressor for the cab fixtures (tools/fixtures/cab.py): no tool in nixpkgs writes LZX cabinets, so the +# fixtures make them here and cabextract (the reference) must extract them to the original bytes before our decoder +# is compared with its output. Written from the LZX format description (as codecs/compress/Lzx): verbatim, aligned +# offset and uncompressed blocks of chosen sizes (spanning frames), delta-coded trees with pre-tree runs, repeated +# offsets, the E8 translation, 32 KB frames aligned to 16 bits. Hash-chain matching; not tuned for ratio or speed. +import heapq, random, struct + +FRAME = 32768 +SLOTS = {15: 30, 16: 32, 17: 34, 18: 36, 19: 38, 20: 42, 21: 50} +EXTRA = [0 if i < 4 else min(i // 2 - 1, 17) for i in range(51)] +BASE = [] +_b = 0 +for _e in EXTRA: + BASE.append(_b) + _b += 1 << _e + + +def slot_of(fo): + s = 0 + while s + 1 < len(BASE) and BASE[s + 1] <= fo: + s += 1 + return s + + +def lengths(freqs, maxlen): + """length-limited Huffman code lengths (halving the frequencies until the code fits); every tree complete""" + f = list(freqs) + used = [i for i, x in enumerate(f) if x > 0] + while len(used) < 2: # a complete code needs two symbols + i = next(i for i in range(len(f)) if f[i] == 0) + f[i] = 1 + used.append(i) + while True: + heap = [(f[i], i, (i,)) for i in used] + heapq.heapify(heap) + depth = {i: 0 for i in used} + k = len(f) + while len(heap) > 1: + a = heapq.heappop(heap) + b = heapq.heappop(heap) + for s in a[2] + b[2]: + depth[s] += 1 + heapq.heappush(heap, (a[0] + b[0], k, a[2] + b[2])) + k += 1 + if max(depth.values()) <= maxlen: + out = [0] * len(f) + for s, d in depth.items(): + out[s] = d + return out + f = [(x + 1) // 2 if x else 0 for x in f] + + +def codes(lens): + """canonical codes (MSB first)""" + out = [0] * len(lens) + code = 0 + for l in range(1, 17): + for s, x in enumerate(lens): + if x == l: + out[s] = code + code += 1 + code <<= 1 + return out + + +class Bits: + def __init__(self): + self.out = bytearray() + self.acc = 0 + self.n = 0 + + def put(self, v, n): + for i in range(n - 1, -1, -1): + self.acc = (self.acc << 1) | ((v >> i) & 1) + self.n += 1 + if self.n == 16: + self.out += struct.pack("= 2: + for o in r: # repeated offsets first + if o <= p: + l = 0 + while l < limit and data[p + l] == data[p + l - o]: + l += 1 + if l > best: + best, boff = l, o + if limit >= 3: + q = head.get(data[p:p + 3]) + chain = 0 + while q is not None and chain < maxchain and p - q <= window - 3: + l = 0 + while l < limit and data[q + l] == data[p + l]: + l += 1 + if l > best + 1: + best, boff = l, p - q + q = prev.get(q) + chain += 1 + if best >= 3 or (best == 2 and boff in r): + out.append((best, boff)) + if boff == r[0]: + pass + elif boff == r[1]: + r[0], r[1] = r[1], r[0] + elif boff == r[2]: + r[0], r[2] = r[2], r[0] + else: + r = [boff, r[0], r[1]] + for k in range(best): + insert(p + k) + p += best + else: + out.append(data[p]) + insert(p) + p += 1 + return out, r + + +class Tree: + """code lengths persisting across blocks (the deltas' base)""" + + def __init__(self, n): + self.lens = [0] * n + + +def pretree_items(prev, new, rng, runs): + """the pre-tree symbols ((sym, extra bits, nbits) or (19, ...)) that turn prev into new""" + items = [] + x = 0 + n = len(new) + while x < n: + if runs and new[x] == 0: + r = 0 + while x + r < n and new[x + r] == 0: + r += 1 + if r >= 20: + r = min(r, 51) + items.append((18, r - 20, 5, None)) + x += r + continue + if r >= 4: + r = min(r, 19) + items.append((17, r - 4, 4, None)) + x += r + continue + if runs: + r = 0 + while x + r < n and new[x + r] == new[x]: + r += 1 + if r >= 4: + r = min(r, 5) + items.append((19, r - 4, 1, (prev[x] - new[x]) % 17)) + x += r + continue + items.append(((prev[x] - new[x]) % 17, 0, 0, None)) + x += 1 + return items + + +def write_tree(bits, tree, first, last, new, rng): + items = pretree_items(tree.lens[first:last], new, rng, runs=rng.random() < 0.9) + freq = [0] * 20 + for s, _, _, d in items: + freq[s] += 1 + if d is not None: + freq[d] += 1 + pl = lengths(freq, 15) + pc = codes(pl) + for l in pl: + bits.put(l, 4) + for s, ex, nb, d in items: + bits.put(pc[s], pl[s]) + if nb: + bits.put(ex, nb) + if d is not None: + bits.put(pc[d], pl[d]) + tree.lens[first:last] = new + + +def compress(data, wbits=16, e8size=0, seed=1, plan=None): + """data -> (LZX stream bytes, [compressed bytes per 32 KB frame]); plan: [(block type 1..3, size)] (default: + random sizes and types)""" + rng = random.Random(seed) + window = 1 << wbits + nslots = SLOTS[wbits] + src = e8(data, e8size) if e8size else bytes(data) + if plan is None: + plan = [] + left = len(src) + while left > 0: + n = min(left, rng.choice([5000, 20000, 32768, 45000, 70000, 100000])) + plan.append((rng.choice([1, 1, 2, 2, 3]) if n > 100 else 1, n)) + left -= n + bits = Bits() + frames = [] + frame_start = 0 + main = Tree(256 + 8 * nslots) + length = Tree(249) + reps = [1, 1, 1] + pos = 0 + first = True + + def frame_end_check(p): + nonlocal frame_start + if p % FRAME == 0 or p == len(src): + bits.align() + frames.append(len(bits.out) - frame_start) + frame_start = len(bits.out) + + for btype, size in plan: + if first: + if e8size: + bits.put(1, 1) + bits.put(e8size >> 16, 16) + bits.put(e8size & 0xFFFF, 16) + else: + bits.put(0, 1) + first = False + bits.put(btype, 3) + bits.put(size >> 8, 16) + bits.put(size & 0xFF, 8) + end = pos + size + if btype == 3: + if bits.aligned(): + bits.put(0, 16) + bits.align() + for r in reps: + bits.out += struct.pack("= 3: + foot = o + 2 - BASE[slot] + if btype == 2 and EXTRA[slot] >= 3: + af[foot & 7] += 1 + syms.append((m, ls, slot, foot)) + assert r == newreps + reps = newreps + if btype == 2: + al = lengths(af, 7) + for x in al: + bits.put(x, 3) + ac = codes(al) + ml = lengths(mf, 16) + ll = lengths(lf, 16) if any(lf) or rng.random() < 0.5 else [0] * 249 + write_tree(bits, main, 0, 256, ml[:256], rng) + write_tree(bits, main, 256, len(ml), ml[256:], rng) + write_tree(bits, length, 0, 249, ll, rng) + mc, lc = codes(ml), codes(ll) + for t, s in zip(toks, syms): + m = s[0] + bits.put(mc[m], ml[m]) + if m < 256: + pos += 1 + else: + _, ls, slot, foot = s + if ls is not None: + bits.put(lc[ls], ll[ls]) + if slot >= 3: + ex = EXTRA[slot] + if btype == 2 and ex >= 3: + if ex > 3: + bits.put(foot >> 3, ex - 3) + bits.put(ac[foot & 7], al[foot & 7]) + elif ex: + bits.put(foot, ex) + pos += t[0] + frame_end_check(pos) + return bytes(bits.out), frames diff --git a/tools/fixtures/cab.py b/tools/fixtures/cab.py index cf86ebe..8011a18 100644 --- a/tools/fixtures/cab.py +++ b/tools/fixtures/cab.py @@ -5,14 +5,17 @@ # is what cabextract extracts and lists (sizes, data CRCs, the DOS times as UTC); cabextract, gcab and 7z must extract # our writer's cabinets to the same bytes. # tests/gen/cab.luau { cases = { { name, data, entries = { { name, size, crc, mtime } } } }, ours = { ok, log }, -# spanned = { { name, data } } } +# spanned = { { name, data } }, bad = { { name, data } } } import calendar, importlib.util, os, re, struct, subprocess, time, zlib _s = importlib.util.spec_from_file_location("_arch2", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_arch2.py")) A = importlib.util.module_from_spec(_s) _s.loader.exec_module(A) +_s = importlib.util.spec_from_file_location("_lzx", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_lzx.py")) +L = importlib.util.module_from_spec(_s) +_s.loader.exec_module(L) -INPUTS = ["tools/fixtures/_arch2.py"] +INPUTS = ["tools/fixtures/_arch2.py", "tools/fixtures/_lzx.py"] ENV = dict(os.environ, TZ="UTC") @@ -34,7 +37,7 @@ def dos(t): def build(folders, reserve=None): - """a cabinet: folders = [(typeCompress, [(name, bytes, attribs, mtime)], encode(blockdata, previous) -> payload)]; + """a cabinet: folders = [(typeCompress, [(name, bytes, attribs, mtime)], encode(stream) -> [(payload, size)])]; reserve = (header bytes, folder size, data size)""" hres, fres, dres = reserve or (b"", 0, 0) flags = 4 if reserve else 0 @@ -50,13 +53,7 @@ def build(folders, reserve=None): files += struct.pack("