diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 56bb792..0e1dc00 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -94,6 +94,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", "lzx", "quantum" | `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` | @@ -165,7 +166,9 @@ 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/Quantum: the Quantum decoder (David Stafford's LZ77 with an adaptive arithmetic coder) as Microsoft - 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 - codecs/compress/Zstd: Zstandard decompression (RFC 8878). A codec (layer 3): archive/zst and anything else carrying zstd diff --git a/docs/guide/archive.md b/docs/guide/archive.md index 4eeceed..c25a1c0 100644 --- a/docs/guide/archive.md +++ b/docs/guide/archive.md @@ -329,6 +329,23 @@ local fat = assert(F.archive.load(floppyBytes)) assert(fat.meta.fat == 12 and fat.meta.label == "DOCS" and fat:read("src/main.c")) local floppy = assert(F.save(adf, nil, { format = "fat", size = 720 })) -- copy the ADF's files to a FAT floppy assert(F.archive.load(floppy):read("s/readme")) +## Microsoft Cabinet + +Cabinet files (`.cab`) read with stored, MSZIP, LZX and Quantum folders; each data block's checksum is checked when +a file of its folder is read. Entries carry the MS-DOS `attributes` (`readonly`, `executable`), `utf8` (the name flag) +and `folder`; DOS times are local times without a zone, read as UTC. Files continued from or into another cabinet of +a set read as `UNSUPPORTED`. Writing makes one folder, MSZIP (default, `level`) or stored (`compression = "none"`): + +```luau +local cab = assert(F.archive.load(cabBytes)) +assert(cab.format == "cab" and cab.meta.folders[1].method == "mszip") +local by = {} +for _, e in cab:list() do + by[e.name] = e +end +assert(by["bin/tool.dll"].size == 16384 and by["readme.txt"].mtime == 1767225600) +local out = assert(F.save(cab, nil, { format = "cab", compression = "none" })) +assert(F.archive.load(out):list()[1].method == "store") ``` ## Formats @@ -360,6 +377,7 @@ assert(F.archive.load(floppy):read("s/readme")) | C64 disks (`.d64`, `.d71`, `.d81`) | yes | yes | PETSCII names; no GEOS VLIR | | Amiga disks (`.adf`) | yes | - | OFS / FFS; no long-name (DOS\\6 / 7) volumes | | FAT images (`.img`, `.ima`) | yes | yes | FAT12 / 16 / 32, VFAT names, MBR partitions; writes FAT12 floppies | +| Cabinet (`.cab`) | yes | yes | stored / MSZIP / LZX / Quantum (read), stored / MSZIP (write); no spanned files | Full capability list: [FORMATS.md](../FORMATS.md). diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index a2d583a..27fdc62 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -1082,6 +1082,18 @@ local list: { Entry } = { return require("@formats/archive/bz2") end, }, + { + name = "cab", + category = "archive", + path = "archive/cab", + extensions = { "cab" }, + mime = { "application/vnd.ms-cab-compressed" }, + deps = { "core/Err", "core/Bytes", "codecs/compress/Deflate", "codecs/compress/Lzx", "codecs/compress/Quantum", "containers/Archive" }, + caps = { decode = true, encode = true, methods = { "store", "mszip", "lzx", "quantum" } }, + load = function() + return require("@formats/archive/cab") + end, + }, { name = "cpio", category = "archive", diff --git a/src/Formats/archive/cab/Sum.luau b/src/Formats/archive/cab/Sum.luau new file mode 100644 index 0000000..c57c2c3 --- /dev/null +++ b/src/Formats/archive/cab/Sum.luau @@ -0,0 +1,42 @@ +--!strict +--!native +--!optimize 2 +-- archive/cab/Sum: the cabinet data block checksum (the XOR of the data's little-endian 32-bit words, the last 1..3 +-- bytes packed most significant first, then the block's cbData / cbUncomp word). Written from the CAB format +-- description ([MS-CAB] 2.4, CFDATA.csum). + +local readu8, readu32, blen = buffer.readu8, buffer.readu32, buffer.len +local bxor, bor, lshift = bit32.bxor, bit32.bor, bit32.lshift + +local Sum = {} + +-- of(buf, off, len, seed) -> the checksum of buf[off, off + len) continuing from seed (0 for a new sum) +function Sum.of(buf: buffer, off: number, len: number, seed: number): number + if off < 0 or len <= 0 or off + len > blen(buf) then + return seed + end + local s = seed + local p = off + local stop = off + len - len % 4 + while p < stop do + s = bxor(s, readu32(buf, p)) + p += 4 + end + local rem = len % 4 + local tail = 0 + if rem == 3 then + tail = bor(lshift(readu8(buf, p), 16), lshift(readu8(buf, p + 1), 8), readu8(buf, p + 2)) + elseif rem == 2 then + tail = bor(lshift(readu8(buf, p), 8), readu8(buf, p + 1)) + elseif rem == 1 then + tail = readu8(buf, p) + end + return bxor(s, tail) +end + +-- block(buf, dataAt, cbData, cbUncomp) -> the csum field of a CFDATA block with these sizes over buf[dataAt, +cbData) +function Sum.block(buf: buffer, dataAt: number, cbData: number, cbUncomp: number): number + return bxor(Sum.of(buf, dataAt, cbData, 0), cbData + cbUncomp * 65536) +end + +return Sum diff --git a/src/Formats/archive/cab/init.luau b/src/Formats/archive/cab/init.luau new file mode 100644 index 0000000..fa9f621 --- /dev/null +++ b/src/Formats/archive/cab/init.luau @@ -0,0 +1,427 @@ +--!strict +-- archive/cab: Microsoft Cabinet files (MSCF 1.3) read into an Archive: the header with its reserve areas and +-- cabinet set fields, folders (CFFOLDER) compressed with none, MSZIP (each CFDATA block "CK" + raw deflate whose +-- dictionary carries over from the block before), LZX (codecs/compress/Lzx, windows 2^15..2^21) or Quantum +-- (codecs/compress/Quantum, windows 2^10..2^21), the files (CFFILE) with their MS-DOS attributes, DOS times (local +-- time without a zone, read as UTC) and the UTF-8 name flag; every data block's checksum is verified (Err.CHECKSUM) +-- when a file of its folder is read. A folder is decompressed once per read and kept for the next file of the same +-- folder. Writes one folder, stored or MSZIP (independent 32 KB deflate blocks), from any Archive. Written from the +-- Microsoft Cabinet format specification ([MS-CAB]). Not supported: files continued from / to another cabinet of a +-- set (Err.UNSUPPORTED for those entries, and for the first folder of a cabinet continued from a previous one), +-- signed / self-extracting stubs before the header. + +-- ------------------------------------------------------------------------------------------------ requires +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 Quantum = require("@formats/codecs/compress/Quantum") +local Archive = require("@formats/containers/Archive") +local Sum = require("@formats/archive/cab/Sum") + +-- ------------------------------------------------------------------------------------------------ contract +local Cab = { + name = "cab", + category = "archive", + extensions = { "cab" }, + mime = { "application/vnd.ms-cab-compressed" }, + deps = { "core/Err", "core/Bytes", "codecs/compress/Deflate", "codecs/compress/Lzx", "codecs/compress/Quantum", "containers/Archive" }, + caps = { decode = true, encode = true, methods = { "store", "mszip", "lzx", "quantum" } }, +} + +export type DecodeOptions = { + maxBytes: number?, -- refuse a folder that decompresses to more than this (default 2^30) + maxEntries: number?, -- default 65535 + verify: boolean?, -- check the data block checksums (default true) +} +export type EncodeOptions = { + compression: ("mszip" | "none")?, -- default "mszip" + level: number?, -- deflate level 0..9 (default 6) + setId: number?, -- the cabinet set id (default 0) +} + +-- ------------------------------------------------------------------------------------------------ constants +local FLAG_PREV, FLAG_NEXT, FLAG_RESERVE = 0x0001, 0x0002, 0x0004 +local ATTR_UTF8 = 0x80 +local METHOD = { [0] = "store", "mszip", "quantum", "lzx" } +local BLOCK = 32768 + +-- ------------------------------------------------------------------------------------------------ sniff +function Cab.sniff(r: Bytes.Reader): number + if r:peek(8) == "MSCF\0\0\0\0" then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +type Folder = { + dataAt: number, -- offset of the first CFDATA (relative to the reader) + blocks: number, + type: number, -- typeCompress + index: number, +} +type Block = { at: number, len: number, size: number } + +-- the CFDATA blocks of a folder (checksums checked), their total output and whether the folder runs into the next +-- cabinet (a block with cbUncomp 0) +local function blocks(r: Bytes.Reader, f: Folder, dataReserve: number, verify: boolean, maxBytes: number): ({ Block }?, any, boolean?) + local list: { Block } = {} + local p = f.dataAt + local total = 0 + for i = 1, f.blocks do + local h = r:sub(p, 8) + local csum, cbData, cbUncomp = h:u32le(), h:u16le(), h:u16le() + if h.err then + return nil, Err.new(Err.TRUNCATED, "data block header past the end", r.base + p) + end + local at = p + 8 + dataReserve + if at + cbData > r:size() then + return nil, Err.new(Err.TRUNCATED, "data block past the end", r.base + p) + end + if cbUncomp == 0 then + return list, total, true + end + if verify and csum ~= 0 and Sum.block(r.buf, r.base + at, cbData, cbUncomp) ~= csum then + return nil, Err.new(Err.CHECKSUM, "data block " .. i .. " checksum mismatch", r.base + p) + end + total += cbUncomp + if total > maxBytes then + return nil, Err.new(Err.LIMIT, "folder larger than maxBytes") + end + table.insert(list, { at = r.base + at, len = cbData, size = cbUncomp }) + p = at + cbData + end + return list, total, false +end + +-- the decompressed data of a folder's blocks +local function inflateFolder(buf: buffer, list: { Block }, total: number, typ: number): (buffer?, Err.Err?) + local method = bit32.band(typ, 15) + local out = buffer.create(total) + if method == 0 then + local o = 0 + for _, b in list do + if b.len ~= b.size then + return nil, Err.new(Err.CORRUPT, "stored block with different sizes", b.at) + end + buffer.copy(out, o, buf, b.at, b.len) + o += b.len + 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 + buffer.copy(src, o, buf, b.at, b.len) + o += b.len + end + local res, err = Lzx.decode(src, 0, n, total, bits) + if not res then + return nil, Err.from(err) + end + return res, nil + elseif method == 2 then + local res, err = Quantum.decode(buf, list, total, bit32.band(bit32.rshift(typ, 8), 31)) + if not res then + return nil, Err.from(err) + end + return res, nil + end + return nil, Err.new(Err.UNSUPPORTED, "compression type " .. method) +end + +local function encode(archive: any, opts: any?): (buffer?, Err.Err?) + return Cab.encode(archive, opts) +end + +function Cab.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local o: DecodeOptions = opts or {} + local maxBytes = o.maxBytes or 2 ^ 30 + local maxEntries = o.maxEntries or 65535 + local verify = o.verify ~= false + if not r:match("MSCF") then + return nil, Err.new(Err.CORRUPT, "no MSCF signature", r.base) + end + r:skip(4) + local cbCabinet = r:u32le() + r:skip(4) + local coffFiles = r:u32le() + r:skip(4) + local minor, major = r:u8(), r:u8() + local cFolders, cFiles, flags = r:u16le(), r:u16le(), r:u16le() + local setId, iCabinet = r:u16le(), r:u16le() + local headerReserve, folderReserve, dataReserve = 0, 0, 0 + if bit32.band(flags, FLAG_RESERVE) ~= 0 then + headerReserve, folderReserve, dataReserve = r:u16le(), r:u8(), r:u8() + end + local a = Archive.new("cab", encode) + local meta: any = a.meta + if headerReserve > 0 then + meta.reserve = r:bytes(headerReserve) + end + if bit32.band(flags, FLAG_PREV) ~= 0 then + meta.prevCabinet, meta.prevDisk = r:cstring(256), r:cstring(256) + end + if bit32.band(flags, FLAG_NEXT) ~= 0 then + meta.nextCabinet, meta.nextDisk = r:cstring(256), r:cstring(256) + end + if r.err then + return nil, r.err + end + if major ~= 1 then + return nil, Err.new(Err.UNSUPPORTED, "cabinet version " .. major .. "." .. minor) + end + meta.setId, meta.cabinet = setId, iCabinet + meta.source = { + format = "cab", + version = major .. "." .. minor, + size = cbCabinet, + flags = flags, + reserve = { header = headerReserve, folder = folderReserve, data = dataReserve }, + } + -- folders + local folders: { Folder } = {} + local methods = {} + for i = 1, cFolders do + local dataAt, nblocks, typ = r:u32le(), r:u16le(), r:u16le() + r:skip(folderReserve) + if r.err then + return nil, r.err + end + folders[i] = { dataAt = dataAt, blocks = nblocks, type = typ, index = i } + local m = METHOD[bit32.band(typ, 15)] + methods[i] = { + method = m or ("type " .. bit32.band(typ, 15)), + window = if m == "lzx" or m == "quantum" then bit32.band(bit32.rshift(typ, 8), 31) else nil, + level = if m == "quantum" then bit32.band(bit32.rshift(typ, 4), 15) else nil, + blocks = nblocks, + } + 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 + -- the folder cache: the last decompressed folder + local cachedIndex, cachedData, cachedRuns = 0, nil :: buffer?, false + local function folderData(f: Folder): (buffer?, Err.Err?, boolean?) + if cachedIndex == f.index then + return cachedData, nil, cachedRuns + end + local list, total, runs = blocks(r, f, dataReserve, verify, maxBytes) + if not list then + return nil, total, false + end + local data, err = inflateFolder(r.buf, list, total, f.type) + if not data then + return nil, err, false + end + cachedIndex, cachedData, cachedRuns = f.index, data, runs == true + return data, nil, runs + end + -- files + local fr = r:sub(coffFiles) + for _ = 1, cFiles do + local size, offset, iFolder = fr:u32le(), fr:u32le(), fr:u16le() + local date, time, attribs = fr:u16le(), fr:u16le(), fr:u16le() + local raw = fr:cstring(65536) + if fr.err then + return nil, fr.err + end + local name = string.gsub(raw, "\\", "/") + local spanned: string? = nil + local folder: Folder? + if iFolder == 0xFFFD or iFolder == 0xFFFF then + spanned = "a file continued from the previous cabinet" + folder = folders[1] + elseif iFolder == 0xFFFE then + spanned = "a file continued in the next cabinet" + folder = folders[#folders] + else + folder = folders[iFolder + 1] + if iFolder == 0 and bit32.band(flags, FLAG_PREV) ~= 0 then + spanned = "a folder continued from the previous cabinet" + end + end + if not folder then + return nil, Err.new(Err.CORRUPT, "file " .. name .. " in a missing folder " .. iFolder) + end + local fo = folder :: Folder + if size > maxBytes then + return nil, Err.new(Err.LIMIT, name .. ": larger than maxBytes") + end + local e: any = { + name = name, + size = size, + method = METHOD[bit32.band(fo.type, 15)] or "unknown", + mtime = Archive.fromDos(date * 65536 + time), + dir = false, + attributes = bit32.band(attribs, 0xFF7F), + utf8 = bit32.band(attribs, ATTR_UTF8) ~= 0, + folder = fo.index, + offset = offset, + readonly = bit32.band(attribs, 0x01) ~= 0, + executable = bit32.band(attribs, 0x40) ~= 0, + } + if spanned then + e.spanned = true + end + if size > 0 or spanned then + e.load = function(): (buffer?, Err.Err?) + if spanned then + return nil, Err.new(Err.UNSUPPORTED, spanned :: string) + end + local data, err, runs = folderData(fo) + if not data then + return nil, err + end + if offset + size > buffer.len(data) then + if runs then + return nil, Err.new(Err.UNSUPPORTED, "a file continued in the next cabinet") + end + return nil, Err.new(Err.CORRUPT, "file past the end of its folder") + end + local out = buffer.create(size) + buffer.copy(out, 0, data, offset, size) + return out, nil + end + end + Archive.put(a, e) + end + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- encode(archive, opts?) -> a cabinet with one folder holding every file (directories are implied by the names) +function Cab.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: EncodeOptions = opts or {} + local compression = o.compression or "mszip" + if compression ~= "mszip" and compression ~= "none" then + return nil, Err.new(Err.ARG, "compression must be \"mszip\" or \"none\"") + end + local level = o.level or 6 + if type(level) ~= "number" or level < 0 or level > 9 or level % 1 ~= 0 then + return nil, Err.new(Err.ARG, "level must be 0..9") + end + local files, ferr = Archive.files(archive) + 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 + local total = 0 + for _, f in files do + total += buffer.len(f.data) + end + if total > 0x7FFF8000 then + return nil, Err.new(Err.ARG, "more than 2 GB of data") + end + -- the folder data, in 32 KB blocks + local folder = buffer.create(total) + local p = 0 + for _, f in files do + buffer.copy(folder, p, f.data, 0, buffer.len(f.data)) + p += buffer.len(f.data) + end + local data = Bytes.writer(total // 2 + 64) + local nblocks = 0 + local s = 0 + while s < total do + local n = math.min(BLOCK, total - s) + local chunk = buffer.create(n) + buffer.copy(chunk, 0, folder, s, n) + local payload: buffer + if compression == "mszip" then + local z, zerr = Deflate.compress(chunk, { level = level }) + if not z then + return nil, zerr + end + payload = buffer.create(buffer.len(z) + 2) + buffer.writeu16(payload, 0, 0x4B43) + buffer.copy(payload, 2, z, 0, buffer.len(z)) + else + payload = chunk + end + local len = buffer.len(payload) + data:u32le(Sum.block(payload, 0, len, n)) + data:u16le(len) + data:u16le(n) + data:bytes(payload) + nblocks += 1 + s += n + end + local blob = data:finish() + -- names and the file table + local table_ = Bytes.writer(64 + #files * 32) + local offset = 0 + for _, f in files do + local e: any = f.entry + local name = string.gsub(f.name, "/", "\\") + local attribs = if type(e.attributes) == "number" then bit32.band(e.attributes, 0x7F) else 0x20 + if string.find(name, "[\128-\255]") then + attribs = bit32.bor(attribs, ATTR_UTF8) + end + local stamp = Archive.toDos(e.mtime) + table_:u32le(buffer.len(f.data)) + table_:u32le(offset) + table_:u16le(0) + table_:u16le(stamp // 65536) + table_:u16le(stamp % 65536) + table_:u16le(attribs) + table_:cstring(name) + offset += buffer.len(f.data) + end + local fileTable = table_:finish() + local nfolders = 1 + local coffFiles = 36 + 8 * nfolders + local dataAt = coffFiles + buffer.len(fileTable) + local size = dataAt + buffer.len(blob) + local w = Bytes.writer(size) + w:string("MSCF") + w:u32le(0) + w:u32le(size) + w:u32le(0) + w:u32le(coffFiles) + w:u32le(0) + w:u8(3) + w:u8(1) + w:u16le(nfolders) + w:u16le(#files) + w:u16le(0) + w:u16le(o.setId or 0) + w:u16le(0) + 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 +end + +-- ------------------------------------------------------------------------------------------------ extras +-- new() -> an empty cab Archive: a:add(name, data, { mtime }); a:write({ compression = "none" | "mszip" }) +function Cab.new(): any + local a = Archive.new("cab", encode) + a.meta.source = { format = "cab" } + return a +end + +return Cab diff --git a/src/Formats/codecs/compress/Deflate/Inflate.luau b/src/Formats/codecs/compress/Deflate/Inflate.luau index 456464f..5927590 100644 --- a/src/Formats/codecs/compress/Deflate/Inflate.luau +++ b/src/Formats/codecs/compress/Deflate/Inflate.luau @@ -64,10 +64,19 @@ end -- Inflate src[start, endpos) into a buffer. cap: initial output capacity; exact: true = the output must fit in -- cap bytes (an error otherwise), false = grow as needed. prefix (with exact): stop at cap instead of failing and -- return what was inflated so far (at most cap bytes; Deflate.peek, for sniffing). +-- dict: a preset dictionary (the data before the stream, e.g. MSZIP's previous block): out starts with a copy of it, +-- distances may reach into it, and outLen includes it (cap does not). -- Returns out, outLen, consumedEnd (the input offset just past the final block) or nil, message. -function Inflate.raw(src: buffer, start: number, endpos: number, cap: number, exact: boolean, prefix: boolean?): (buffer?, any, number?) - local out = bcreate(cap) +function Inflate.raw(src: buffer, start: number, endpos: number, cap: number, exact: boolean, prefix: boolean?, dict: buffer?): (buffer?, any, number?) local op = 0 + if dict then + op = blen(dict) + cap += op + end + local out = bcreate(cap) + if dict then + bcopy(out, 0, dict, 0, op) + end local pos = start local bitbuf, bitcnt, over = 0, 0, 0 local lt, dt = bcreate(LITCAP * 4), bcreate(DISTCAP * 4) :: buffer diff --git a/src/Formats/codecs/compress/Deflate/init.luau b/src/Formats/codecs/compress/Deflate/init.luau index fd25c71..46ea9fe 100644 --- a/src/Formats/codecs/compress/Deflate/init.luau +++ b/src/Formats/codecs/compress/Deflate/init.luau @@ -6,6 +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 +-- 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 @@ -43,7 +45,9 @@ end -- inflate(buf, offset?, length?, expectedSize?) -> buffer, consumedEnd | nil, Err. Raw deflate. -- expectedSize: the exact uncompressed size when known (a zip entry): the output is allocated once, and a stream -- that inflates to a different size is an error. consumedEnd is the input offset just past the final block. -function Deflate.inflate(buf: buffer | string, offset: number?, length: number?, expectedSize: number?): (buffer?, any) +-- dict: a preset dictionary (up to 32 KB of data before the stream, as MSZIP's previous block): back references may +-- reach into it; the result holds only the new bytes. +function Deflate.inflate(buf: buffer | string, offset: number?, length: number?, expectedSize: number?, dict: buffer?): (buffer?, any) local b, o, l, aerr = args("Deflate.inflate", buf, offset, length) if not b then return nil, aerr @@ -58,10 +62,20 @@ function Deflate.inflate(buf: buffer | string, offset: number?, length: number?, else cap = math.max(1024, l * 4) end - local out, n, consumed = Inflate.raw(b, o, o + l, cap :: number, exact) + if dict ~= nil and type(dict) ~= "buffer" then + return nil, Err.new(Err.ARG, "Deflate.inflate: dict must be a buffer") + end + local out, n, consumed = Inflate.raw(b, o, o + l, cap :: number, exact, false, dict) if not out then return nil, inflateErr(tostring(n), o) end + if dict then + local d = buffer.len(dict) + n -= d + local res = buffer.create(n) + buffer.copy(res, 0, out, d, n) + out = res + end if exact and n ~= expectedSize then return nil, Err.new(Err.CORRUPT, string.format("inflate: output is %d bytes, expected %d", n, expectedSize :: number)) end @@ -295,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/src/Formats/codecs/compress/Quantum.luau b/src/Formats/codecs/compress/Quantum.luau new file mode 100644 index 0000000..ec833ce --- /dev/null +++ b/src/Formats/codecs/compress/Quantum.luau @@ -0,0 +1,251 @@ +--!strict +--!native +--!optimize 2 +-- codecs/compress/Quantum: the Quantum decoder (David Stafford's LZ77 with an adaptive arithmetic coder) as Microsoft +-- Cabinet folders use it: windows of 2^10 .. 2^21 bytes; a 16-bit arithmetic decoder (H / L / C registers with +-- underflow handling) over a most-significant-bit-first byte stream; eight adaptive frequency models (the +-- 7-symbol selector, four 64-symbol literal models, the offset models for matches of 3, 4 and 5..259 bytes and the +-- 27-symbol length model) whose cumulative frequencies grow by 8 per symbol and are rescaled above 3800 (halved, and +-- every 50th time rebuilt from the frequencies and re-sorted); position and length footers read as raw bits from the +-- same stream. Each CFDATA block is one frame (at most 32768 output bytes) that restarts the arithmetic coder; the +-- models and the window persist across the frames of a folder. Written from the public descriptions of the format +-- (the Quantum notes by Matthew Russotto and the cabinet documentation); no code from libmspack. +-- +-- local out, err = Quantum.decode(src, blocks, outSize, windowBits) -- buffer | nil, message +-- +-- blocks = { { at, len, size } }: each block's compressed bytes src[at, at + len) and its output size; outSize is +-- their total. Never throws: bad or truncated data returns nil, message. + +local band, bor, bxor, lshift, rshift = bit32.band, bit32.bor, bit32.bxor, bit32.lshift, bit32.rshift +local readu8, writeu8 = buffer.readu8, buffer.writeu8 +local bcreate, bcopy, blen = buffer.create, buffer.copy, buffer.len +local floor = math.floor + +local Quantum = {} + +-- position slots (offset - 1 = base + footer) and length slots (length - 5 = base + footer) +local PBASE = table.create(42, 0) +local PEXTRA = table.create(42, 0) +do + local b = 0 + for i = 0, 41 do + local e = if i < 4 then 0 else i // 2 - 1 + PEXTRA[i + 1] = e + PBASE[i + 1] = b + b += lshift(1, e) + end +end +local LEXTRA = { 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0 } +local LBASE = table.create(27, 0) +do + local b = 0 + for i = 1, 27 do + LBASE[i] = b + b += lshift(1, LEXTRA[i]) + end +end + +-- ------------------------------------------------------------------------------------------------ models +-- an adaptive model: symbols sym[1..n] in their current order, cumulative frequencies cum[1..n + 1] (cum[n + 1] = 0) +type Model = { n: number, sym: { number }, cum: { number }, shifts: number } + +local function model(first: number, n: number): Model + local sym = table.create(n, 0) + local cum = table.create(n + 1, 0) + for i = 1, n do + sym[i] = first + i - 1 + cum[i] = n - i + 1 + end + cum[n + 1] = 0 + return { n = n, sym = sym, cum = cum, shifts = 4 } +end + +local function rescale(m: Model) + local n, sym, cum = m.n, m.sym, m.cum + m.shifts -= 1 + if m.shifts > 0 then + for i = n, 1, -1 do + local c = rshift(cum[i], 1) + if c <= cum[i + 1] then + c = cum[i + 1] + 1 + end + cum[i] = c + end + return + end + m.shifts = 50 + -- cumulative -> halved frequencies (rounded up: no symbol drops to zero) + for i = 1, n do + cum[i] = rshift(cum[i] - cum[i + 1] + 1, 1) + end + -- sort by frequency, decreasing (a selection-style exchange sort: its order of equal frequencies is the format's) + for i = 1, n - 1 do + for j = i + 1, n do + if cum[i] < cum[j] then + cum[i], cum[j] = cum[j], cum[i] + sym[i], sym[j] = sym[j], sym[i] + end + end + end + for i = n, 1, -1 do + cum[i] += cum[i + 1] + end +end + +-- ------------------------------------------------------------------------------------------------ decode +-- the coder and bit reader of one frame +type Coder = { src: buffer, pos: number, stop: number, acc: number, cnt: number, over: number, H: number, L: number, C: number, bad: boolean } + +local function bit(c: Coder): number + if c.cnt == 0 then + local p = c.pos + if p < c.stop then + c.acc = readu8(c.src, p) + c.pos = p + 1 + else + c.acc = 0 + c.over += 1 + end + c.cnt = 8 + end + c.cnt -= 1 + return band(rshift(c.acc, c.cnt), 1) +end + +-- raw(c, n) -> the next n (0..19) bits, most significant first +local function raw(c: Coder, n: number): number + local v = 0 + for _ = 1, n do + v = v * 2 + bit(c) + end + return v +end + +local function symbol(c: Coder, m: Model): number + local cum = m.cum + local H, L, C = c.H, c.L, c.C + local range = H - L + 1 + local total = cum[1] + if range <= 0 or C < L or C > H then + -- only corrupt registers get here (the decoder keeps L <= C <= H) + c.bad = true + return 0 + end + local f = band(floor(((C - L + 1) * total - 1) / range), 0xFFFF) + local n = m.n + local i = 2 + while i <= n and cum[i] > f do + i += 1 + end + -- the symbol is sym[i - 1]: its interval is [cum[i], cum[i - 1]) + local s = m.sym[i - 1] + H = L + floor(cum[i - 1] * range / total) - 1 + L = L + floor(cum[i] * range / total) + for k = 1, i - 1 do + cum[k] += 8 + end + if cum[1] > 3800 then + rescale(m) + end + while true do + if band(bxor(L, H), 0x8000) ~= 0 then + if band(L, 0x4000) ~= 0 and band(H, 0x4000) == 0 then + -- underflow: L and H straddle the middle + C = bxor(C, 0x4000) + L = band(L, 0x3FFF) + H = bor(H, 0x4000) + else + break + end + end + L = band(lshift(L, 1), 0xFFFF) + H = bor(band(lshift(H, 1), 0xFFFF), 1) + C = bor(band(lshift(C, 1), 0xFFFF), bit(c)) + end + c.H, c.L, c.C = H, L, C + return s +end + +function Quantum.decode(src: buffer, blocks: { { at: number, len: number, size: number } }, outSize: number, windowBits: number): (buffer?, string?) + if type(windowBits) ~= "number" or windowBits < 10 or windowBits > 21 or windowBits % 1 ~= 0 then + return nil, "unsupported: Quantum window 2^" .. tostring(windowBits) + end + if outSize < 0 or outSize % 1 ~= 0 then + return nil, "bad output size" + end + local total = 0 + for _, b in blocks do + if b.at < 0 or b.len < 0 or b.at + b.len > blen(src) or b.size < 0 then + return nil, "bad block range" + end + total += b.size + end + if total ~= outSize then + return nil, "block sizes do not add up to the output size" + end + local window = lshift(1, windowBits) + local slots = windowBits * 2 + local selector = model(0, 7) + local lit = { model(0, 64), model(64, 64), model(128, 64), model(192, 64) } + local m3 = model(0, math.min(slots, 24)) + local m4 = model(0, math.min(slots, 36)) + local m5 = model(0, slots) + local mlen = model(0, 27) + local out = bcreate(outSize) + local op = 0 + for _, b in blocks do + local frameEnd = op + b.size + local c: Coder = { src = src, pos = b.at, stop = b.at + b.len, acc = 0, cnt = 0, over = 0, H = 0xFFFF, L = 0, C = 0, bad = false } + c.C = raw(c, 16) + while op < frameEnd do + local sel = symbol(c, selector) + if c.bad then + return nil, "bad arithmetic code" + end + if sel < 4 then + writeu8(out, op, symbol(c, lit[sel + 1])) + op += 1 + else + local len, slot + if sel == 4 then + len = 3 + slot = symbol(c, m3) + elseif sel == 5 then + len = 4 + slot = symbol(c, m4) + elseif sel == 6 then + local ls = symbol(c, mlen) + len = LBASE[ls + 1] + raw(c, LEXTRA[ls + 1]) + 5 + slot = symbol(c, m5) + else + return nil, "bad selector" + end + local dist = PBASE[slot + 1] + raw(c, PEXTRA[slot + 1]) + 1 + if dist > op or dist > window then + return nil, "match offset before the start of the data" + end + if op + len > frameEnd then + return nil, "match past the end of its 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 + if c.bad then + return nil, "bad arithmetic code" + end + if c.over > 4 then + return nil, "truncated frame" + end + end + end + return out, nil +end + +return Quantum diff --git a/tests/archive/cab.luau b/tests/archive/cab.luau new file mode 100644 index 0000000..a8fe737 --- /dev/null +++ b/tests/archive/cab.luau @@ -0,0 +1,166 @@ +-- archive/cab tests: cabinets by gcab (stored / MSZIP), lcab, a builder of MSZIP blocks that use the previous block as +-- 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, 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); Quantum +-- (codecs/compress/Quantum) the same way (windows 2^10 .. 2^21, model rescaling); 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") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Deflate = require("@formats/codecs/compress/Deflate") +local E = require("@tests/archive/_entries") +local Fx = require("@tests/gen/cab") + +local t = T.suite("cab") +t:eq(Cab.name, "cab", "name") + +local function load(s: string, opts: any?): (any, Err.Err?) + return Cab.decode(Bytes.reader(buffer.fromstring(s)), opts) +end + +local samples = {} +local methods = {} +for _, c in Fx.cases do + local a, err = load(c.data) + t:check(a, c.name .. ": " .. tostring(err)) + if a then + E.check(t, a, c.entries, c.name) + for _, e in a:list() do + methods[e.method] = true + end + end + 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 and methods.lzx and methods.quantum, "covers store, mszip, lzx and quantum") + +-- attributes, UTF-8 names, reserve areas (the builder's two-folder cabinet) +local two = assert(load(Fx.cases[5].data)) +local naive = two._byName["na\u{ef}ve \u{2603}.txt"] +t:check(naive and naive.utf8 and naive.attributes == 0x20, "utf-8 name and attributes") +t:eq(two.meta.source.reserve.data, 3, "data reserve") +t:eq(buffer.tostring(two.meta.reserve), "HEADER-RESERVE", "header reserve") +t:eq(#two.meta.folders, 2, "two folders") +t:check(assert(load(Fx.cases[4].data))._byName["b.bin"].readonly, "read-only attribute") + +-- our writer +t:check(Fx.ours.ok, "reference tools extract our cabinets: " .. Fx.ours.log) +E.roundTrip(t, Cab, nil, "round trip mszip") +E.roundTrip(t, Cab, { compression = "none" }, "round trip store") +local big = Cab.new() +big:add("dir/big.bin", E.content(200000, 3), { mtime = 1700000000 }) +big:add("x.txt", "x") +local bigData = assert(big:write()) +local back = assert(Cab.decode(Bytes.reader(bigData))) +t:eq(buffer.tostring(assert(back:read("dir/big.bin"))), buffer.tostring(E.content(200000, 3)), "200 KB through 7 blocks") +t:eq(back:list()[1].mtime, 1700000000, "mtime") +t:eq(select(2, Cab.encode(big, { compression = "lzx" :: any })).code, Err.ARG, "bad compression") + +-- spanned cabinets: files continued from / to another cabinet are UNSUPPORTED, the others read +for _, c in Fx.spanned do + local a, err = load(c.data) + t:check(a, c.name .. ": " .. tostring(err)) + if a then + local unsupported = 0 + for _, e in a:list() do + local b, rerr = a:read(e.name) + if not b then + t:eq(rerr.code, Err.UNSUPPORTED, c.name .. ": " .. e.name) + unsupported += 1 + end + end + t:check(unsupported > 0, c.name .. ": has spanned files") + end +end + +-- 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") + +-- Quantum directly +local Quantum = require("@formats/codecs/compress/Quantum") +t:check(not Quantum.decode(buffer.create(10), {}, 0, 9), "Quantum window 2^9 unsupported") +t:check(not Quantum.decode(buffer.create(10), { { at = 0, len = 10, size = 5 } }, 6, 16), "Quantum sizes must add up") +t:check(not Quantum.decode(buffer.create(10), { { at = 4, len = 10, size = 5 } }, 5, 16), "Quantum 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"))) +t:eq(buffer.tostring(plain), dictText .. dictText, "inflate with an unused dictionary") + +-- errors +local data = Fx.cases[2].data -- gcab -z +local function code(s: string): string? + local a, e = load(s) + if not a then + return e and e.code + end + for _, en in a:list() do + local b, rerr = a:read(en.name) + if not b then + return rerr and rerr.code + end + end + return nil +end +t:eq(code(data), nil, "intact") +t:eq(code("MSCF\0\0\0\0" .. string.rep("\0", 10)), Err.TRUNCATED, "short header") +t:eq(code("PK\3\4xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"), Err.CORRUPT, "not a cabinet") +t:eq(code(string.sub(data, 1, #data - 100)), Err.TRUNCATED, "cut") +local mid = #data - 200 +local flipped = string.sub(data, 1, mid - 1) .. string.char(bit32.bxor(string.byte(data, mid), 0x08)) .. string.sub(data, mid + 1) +t:eq(code(flipped), Err.CHECKSUM, "flipped data byte") +local a2 = assert(load(flipped, { verify = false })) +local failed = 0 +for _, e in a2:list() do + if not a2:read(e.name) then + failed += 1 + end +end +t:note("flipped byte without verify: %d entries fail", failed) + +t:fuzz("decode", function(b: buffer) + local r = Cab.decode(Bytes.reader(b)) + if r then + for _, e in r:list() do + r:read(e.name) + end + end + local r2 = Cab.decode(Bytes.reader(b), { verify = false }) + if r2 then + for _, e in r2:list() do + r2:read(e.name) + end + end + return r +end, samples, { mutations = 6 }) +t:done() diff --git a/tools/bench.luau b/tools/bench.luau index 673d055..e410067 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") @@ -1190,6 +1190,32 @@ do end end end +-- ws-arch2 cabinets: LZX (codecs/compress/Lzx), Quantum (codecs/compress/Quantum) 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", "quantum", "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 -- Draco (codecs/model/Draco): the Stanford bunny (35k points, 69k faces, Edgebreaker valence, normals) and a UV -- sphere with seams; MB/s of decoded output (u32 indices + f32 attributes per point), plus triangles per second. 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/_quantum.py b/tools/fixtures/_quantum.py new file mode 100644 index 0000000..3f9ee2c --- /dev/null +++ b/tools/fixtures/_quantum.py @@ -0,0 +1,183 @@ +# A small Quantum compressor for the cab fixtures (tools/fixtures/cab.py): no tool in nixpkgs writes Quantum +# 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 format description (as codecs/compress/Quantum): +# the same adaptive models, a 16-bit arithmetic encoder with underflow bits (Witten / Neal / Cleary style), position / +# length footers as raw bits placed where the decoder (16 code bits ahead) reads them, one frame per 32 KB block. +FRAME = 32768 +PEXTRA = [0 if i < 4 else i // 2 - 1 for i in range(42)] +PBASE = [] +_b = 0 +for _e in PEXTRA: + PBASE.append(_b) + _b += 1 << _e +LEXTRA = [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0] +LBASE = [] +_b = 0 +for _e in LEXTRA: + LBASE.append(_b) + _b += 1 << _e + + +class Model: + def __init__(self, first, n): + self.n = n + self.sym = [first + i for i in range(n)] + self.cum = [n - i for i in range(n)] + [0] + self.shifts = 4 + + def update(self, i): + """after coding sym[i] (0-based)""" + for k in range(i + 1): + self.cum[k] += 8 + if self.cum[0] > 3800: + self.rescale() + + def rescale(self): + n, cum, sym = self.n, self.cum, self.sym + self.shifts -= 1 + if self.shifts: + for i in range(n - 1, -1, -1): + cum[i] >>= 1 + if cum[i] <= cum[i + 1]: + cum[i] = cum[i + 1] + 1 + return + self.shifts = 50 + for i in range(n): + cum[i] = (cum[i] - cum[i + 1] + 1) >> 1 + for i in range(n - 1): + for j in range(i + 1, n): + if cum[i] < cum[j]: + cum[i], cum[j] = cum[j], cum[i] + sym[i], sym[j] = sym[j], sym[i] + for i in range(n - 1, -1, -1): + cum[i] += cum[i + 1] + + +class Encoder: + """one frame: code bits (by shift position) and raw bit runs to insert at code positions""" + + def __init__(self): + self.H, self.L = 0xFFFF, 0 + self.code = [] + self.pending = 0 + self.shifts = 0 + self.raws = [] # (code position, value, nbits) + + def emit(self, b): + self.code.append(b) + self.code.extend([1 - b] * self.pending) + self.pending = 0 + + def encode(self, m, s): + i = m.sym.index(s) + rng = self.H - self.L + 1 + tot = m.cum[0] + self.H = self.L + (m.cum[i] * rng) // tot - 1 + self.L = self.L + (m.cum[i + 1] * rng) // tot + m.update(i) + while True: + if (self.L ^ self.H) & 0x8000 == 0: + self.emit(self.H >> 15) + elif (self.L & 0x4000) and not (self.H & 0x4000): + self.pending += 1 + self.L &= 0x3FFF + self.H |= 0x4000 + else: + break + self.L = (self.L << 1) & 0xFFFF + self.H = ((self.H << 1) & 0xFFFF) | 1 + self.shifts += 1 + + def raw(self, v, n): + if n: + self.raws.append((16 + self.shifts, v, n)) + + def finish(self): + """the frame's bytes: flushed code with the raw runs merged in, zero padded""" + self.pending += 1 + self.emit(0 if self.L < 0x4000 else 1) + need = 16 + self.shifts + code = self.code + [0] * max(0, need - len(self.code)) + bits = [] + p = 0 + for at, v, n in self.raws: + bits.extend(code[p:at]) + p = at + bits.extend((v >> (n - 1 - k)) & 1 for k in range(n)) + bits.extend(code[p:]) + bits.extend([0] * (-len(bits) % 8 + 16)) # byte padding and 2 zero bytes: the decoder's lookahead stays inside + return bytes(int("".join(map(str, bits[i:i + 8])), 2) for i in range(0, len(bits), 8)) + + +def slot_of(off1): + s = 0 + while s + 1 < len(PBASE) and PBASE[s + 1] <= off1: + s += 1 + return s + + +def compress(data, wbits=16, maxchain=24): + """data -> [frame bytes] (one per 32 KB block)""" + window = 1 << wbits + slots = wbits * 2 + sel = Model(0, 7) + lit = [Model(0, 64), Model(64, 64), Model(128, 64), Model(192, 64)] + m3, m4, m5, mlen = Model(0, min(slots, 24)), Model(0, min(slots, 36)), Model(0, slots), Model(0, 27) + lim3, lim4 = PBASE[m3.n - 1] + (1 << PEXTRA[m3.n - 1]), PBASE[m4.n - 1] + (1 << PEXTRA[m4.n - 1]) + limw = min(window, PBASE[slots - 1] + (1 << PEXTRA[slots - 1])) + head, prev = {}, {} + frames = [] + p = 0 + + def insert(q): + if q + 3 <= len(data): + k = data[q:q + 3] + prev[q] = head.get(k) + head[k] = q + while p < len(data): + end = min(len(data), p + FRAME) + enc = Encoder() + while p < end: + limit = min(259, end - p) + best, boff = 0, 0 + if limit >= 3: + q = head.get(data[p:p + 3]) + chain = 0 + while q is not None and chain < maxchain and p - q <= limw: + l = 0 + while l < limit and data[q + l] == data[p + l]: + l += 1 + o = p - q + ok = l >= 5 or (l == 4 and o <= lim4) or (l == 3 and o <= lim3) + if ok and l > best: + best, boff = l, o + q = prev.get(q) + chain += 1 + if best >= 3: + o1 = boff - 1 + s = slot_of(o1) + if best == 3: + enc.encode(sel, 4) + enc.encode(m3, s) + elif best == 4: + enc.encode(sel, 5) + enc.encode(m4, s) + else: + l5 = best - 5 + ls = max(i for i in range(27) if LBASE[i] <= l5) + enc.encode(sel, 6) + enc.encode(mlen, ls) + enc.raw(l5 - LBASE[ls], LEXTRA[ls]) + enc.encode(m5, s) + enc.raw(o1 - PBASE[s], PEXTRA[s]) + for k in range(best): + insert(p + k) + p += best + else: + b = data[p] + enc.encode(sel, b >> 6) + enc.encode(lit[b >> 6], b) + insert(p) + p += 1 + frames.append(enc.finish()) + return frames diff --git a/tools/fixtures/cab.py b/tools/fixtures/cab.py new file mode 100644 index 0000000..2a3ae87 --- /dev/null +++ b/tools/fixtures/cab.py @@ -0,0 +1,247 @@ +# Cabinet fixtures (tools/fixtures.py): cabinets by gcab (stored and MSZIP folders, paths), lcab (stored), our own +# minimal cabinet builder below (MSZIP blocks deflated with the previous block as the zlib dictionary, several +# folders, reserve areas, attributes, UTF-8 names; LZX and Quantum folders from the fixture compressors _lzx.py / +# _quantum.py, since no packaged tool writes them), the libmspack test cabinets read from the nix store (test data, +# not committed: normal / reserve / multi-part / mszip_lzx_qtm samples and the broken ones), and our writer's output. +# The reference data is what cabextract extracts and lists (sizes, data CRCs, the DOS times as UTC); every fixture +# LZX / Quantum cabinet must extract with cabextract to the original bytes, and 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 } }, 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) +_s = importlib.util.spec_from_file_location("_quantum", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_quantum.py")) +Q = importlib.util.module_from_spec(_s) +_s.loader.exec_module(Q) + +INPUTS = ["tools/fixtures/_arch2.py", "tools/fixtures/_lzx.py", "tools/fixtures/_quantum.py"] +ENV = dict(os.environ, TZ="UTC") + + +def checksum(data, seed=0): + """the CFDATA checksum ([MS-CAB] 2.4)""" + s = seed + n = len(data) - len(data) % 4 + for i in range(0, n, 4): + s ^= struct.unpack_from(" [(payload, size)])]; + reserve = (header bytes, folder size, data size)""" + hres, fres, dres = reserve or (b"", 0, 0) + flags = 4 if reserve else 0 + head = 36 + (4 + len(hres) if reserve else 0) + nfiles = sum(len(f[1]) for f in folders) + files = b"" + blocks = [] + for fi, (typ, fl, enc) in enumerate(folders): + off = 0 + stream = b"" + for name, data, attr, mt in fl: + d, t = dos(mt) + files += struct.pack(" mtime) and extraction (name -> size, crc)""" + listing = A.tool(["cabextract"], ["cabextract", "-l", path]).decode("utf-8", "replace") + times = {} + for line in listing.splitlines(): + m = LIST.match(line) + if m: + d, mo, y, h, mi, s = (int(x) for x in m.group(2, 3, 4, 5, 6, 7)) + times[m.group(8).replace("\\", "/")] = calendar.timegm((y, mo, d, h, mi, s)) + out = os.path.join(tmp, "x-" + tag) + os.makedirs(out) + subprocess.run(["nix", "shell", "nixpkgs#cabextract", "-c", "cabextract", "-q", "-d", out, path], check=True, + capture_output=True, env=ENV) + ents = [] + for n, c in sorted(A.read_tree(out).items()): + e = {"name": n, "size": os.path.getsize(os.path.join(out, n)), "crc": c} + if n in times: + e["mtime"] = times[n] + ents.append(e) + return ents + + +def mspack_cabs(): + """the libmspack source's test cabinets (nix store path of its tarball, unpacked into a temporary directory)""" + src = subprocess.run(["nix", "build", "--no-link", "--print-out-paths", "nixpkgs#libmspack.src"], check=True, + capture_output=True).stdout.decode().strip() + return src + + +def generate(ctx): + rng = ctx.rng(47) + tmp = A.tmpdir() + try: + work = os.path.join(tmp, "w") + text = b"the quick brown fox jumps over the lazy dog\n" * 3000 + rand = rng.randbytes(70000) + A.tree(A.FILES + [("dir/sub/text.txt", text), ("dir/rand.bin", rand), + ("dir/runs.bin", b"\0" * 50000 + b"\xff" * 30000)], work) + names = [n for n, _ in A.FILES] + ["dir/sub/text.txt", "dir/rand.bin", "dir/runs.bin"] + cases = [] + + def add(name, path): + cases.append({"name": name, "data": open(path, "rb").read(), "entries": reference(path, tmp, str(len(cases)))}) + + for z in ("", "-z"): + arc = os.path.join(tmp, "gcab%s.cab" % z) + A.tool(["gcab"], ["gcab", "-c"] + ([z] if z else []) + [arc] + names, cwd=work) + add("gcab " + (z or "store"), arc) + arc = os.path.join(tmp, "lcab.cab") + A.tool(["lcab"], ["lcab", "-r", "dir", "hello.txt", arc], cwd=work) + add("lcab", arc) + # our builder: MSZIP with the dictionary, two folders (stored + MSZIP), reserve areas, attributes, UTF-8 + big = text + rand[:20000] + text[:50000] + cab1 = build([(1, [(b"a\\text.txt", big, 0x20, 1700000000), (b"b.bin", rand, 0x01, 1600000000)], mszip_dict)]) + cab2 = build([(0, [(b"stored.txt", b"stored data " * 5000, 0x20, 1700000000)], store), + (1, [("naïve ☃.txt".encode(), text, 0x80 | 0x20, 1700000002), (b"empty", b"", 0x20, 1700000000)], mszip_dict)], + reserve=(b"HEADER-RESERVE", 6, 3)) + for i, c in enumerate((cab1, cab2)): + p = os.path.join(tmp, "built%d.cab" % i) + open(p, "wb").write(c) + A.tool(["cabextract"], ["cabextract", "-t", p]) # checksums and data as cabextract reads them + add(("mszip with dictionary", "two folders, reserve, utf-8")[i], p) + # LZX (our fixture compressor, checked by cabextract): windows 2^15 .. 2^21, the three block types, E8 + x86 = bytearray(rng.randbytes(90000)) + for i in range(0, len(x86) - 5, 23): + x86[i] = 0xE8 + x86 = bytes(x86) + text[:40000] + lzx_cases = [ + ("lzx 2^15 text", 15, 0, [(b"t.txt", text[:100000])], None), + ("lzx 2^16 mixed", 16, 0, [(b"a.txt", text), (b"b.bin", rand[:30000]), (b"c.txt", text[:5000])], None), + ("lzx 2^17 types", 17, 0, [(b"m.bin", big)], [(1, 40000), (2, 30001), (3, 7777), (2, 50000), (3, 4), (1, len(big) - 127782)]), + ("lzx 2^21 e8", 21, 12000000, [(b"x86.exe", x86), (b"tail.txt", text[:3000])], None), + ("lzx 2^18 e8 small", 18, 70000, [(b"s.bin", x86[:20000])], [(2, 20000)]), + ] + for i, (label, wb, e8size, fl, plan) in enumerate(lzx_cases): + c = build([(3 | (wb << 8), [(n, d, 0x20, 1700000000) for n, d in fl], lzx(wb, e8size, 100 + i, plan))]) + p = os.path.join(tmp, "lzx%d.cab" % i) + open(p, "wb").write(c) + ents = reference(p, tmp, "lzx%d" % i) + want = {n.decode(): zlib.crc32(d) for n, d in fl} + if {e["name"]: e["crc"] for e in ents} != want: + raise RuntimeError("cabextract does not extract the fixture LZX cabinet " + label) + cases.append({"name": label, "data": c, "entries": ents}) + # Quantum (our fixture compressor, checked by cabextract): windows 2^10 .. 2^21, model rescaling and re-sorting + quantum_cases = [ + ("quantum 2^10 text", 10, [(b"q.txt", text[:20000])]), + ("quantum 2^16 mixed", 16, [(b"a.txt", text[:60000]), (b"b.bin", rand[:20000]), (b"c.bin", x86[:30000])]), + ("quantum 2^21 big", 21, [(b"big.bin", big)]), + ] + for i, (label, wb, fl) in enumerate(quantum_cases): + c = build([(2 | (4 << 4) | (wb << 8), [(n, d, 0x20, 1700000000) for n, d in fl], quantum(wb))]) + p = os.path.join(tmp, "qtm%d.cab" % i) + open(p, "wb").write(c) + ents = reference(p, tmp, "qtm%d" % i) + want = {n.decode(): zlib.crc32(d) for n, d in fl} + if {e["name"]: e["crc"] for e in ents} != want: + raise RuntimeError("cabextract does not extract the fixture Quantum cabinet " + label) + cases.append({"name": label, "data": c, "entries": ents}) + # the libmspack test cabinets + ms = os.path.join(tmp, "ms") + os.makedirs(ms) + subprocess.run(["tar", "xzf", mspack_cabs(), "-C", ms, "--wildcards", "*/test/test_files/cabd/*.cab"], check=True) + cabd = os.path.join(ms, os.listdir(ms)[0], "test", "test_files", "cabd") + for n in ("normal_2files_1folder", "normal_2files_2folders", "normal_255c_filename", "reserve_---", "reserve_--D", + "reserve_-F-", "reserve_-FD", "reserve_H--", "reserve_H-D", "reserve_HF-", "reserve_HFD", "mszip_lzx_qtm"): + add("libmspack " + n, os.path.join(cabd, n + ".cab")) + spanned = [{"name": n, "data": open(os.path.join(cabd, n + ".cab"), "rb").read()} + for n in ("multi_basic_pt1", "multi_basic_pt2", "multi_basic_pt3")] + # broken cabinets cabextract fails on (crafted bad trees, loops, short headers / strings) + bad = [{"name": n, "data": open(os.path.join(cabd, n), "rb").read()} for n in sorted(os.listdir(cabd)) + if n.endswith(".cab") and (n.startswith(("partial_", "bad_", "lzx-")) or (n.startswith("cve-") and "9732" not in n))] + # our writer, extracted by the reference tools + log, ok = [], True + for opts in ("compression=mszip", "compression=none", "compression=mszip,level=1"): + data = A.ours(ctx, "cab", opts) + p = os.path.join(tmp, "ours.cab") + open(p, "wb").write(data) + for tool, argv in (("cabextract", ["cabextract", "-q", "-d", "{o}", p]), ("gcab", ["gcab", "-x", "-C", "{o}", p]), + ("p7zip", ["7z", "x", "-o{o}", p])): + out = os.path.join(tmp, "o-%s-%d" % (tool, len(log))) + os.makedirs(out) + r = subprocess.run(["nix", "shell", "nixpkgs#" + tool, "-c"] + [a.replace("{o}", out) for a in argv], + capture_output=True, env=ENV) + got = A.read_tree(out) + want = {n: zlib.crc32(d) for n, d in A.FILES} + good = r.returncode == 0 and got == want + ok = ok and good + log.append("%s %s: %s" % (opts, tool, "ok" if good else "FAILED %r" % (got,))) + ctx.emit("cab", {"cases": cases, "ours": {"ok": ok, "log": "; ".join(log)}, "spanned": spanned, "bad": bad}) + finally: + A.rmtree(tmp) diff --git a/tools/fixtures/docs_arch_cab.py b/tools/fixtures/docs_arch_cab.py new file mode 100644 index 0000000..79ca4b0 --- /dev/null +++ b/tools/fixtures/docs_arch_cab.py @@ -0,0 +1,30 @@ +# Docs inputs for the archive page's Cabinet section (tools/fixtures.py; tools/docs_check.py explains the inputs): an +# MSZIP cabinet of a small tree by gcab. +# tests/gen/docs_arch_cab.luau { files = { [name] = bytes }, vars = { cabBytes = "setup.cab" } } +import importlib.util, os, subprocess, tempfile + +INPUTS = ["tools/docs_check.py"] + +MTIME = 1767225600 # 2026-01-01T00:00:00Z + + +def docs_check(ctx): + spec = importlib.util.spec_from_file_location("docs_check", os.path.join(ctx.root, "tools", "docs_check.py")) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + + +def generate(ctx): + dc = docs_check(ctx) + files = {} + with tempfile.TemporaryDirectory() as d: + os.makedirs(os.path.join(d, "bin")) + for n, data in (("readme.txt", b"formats-luau cabinet\n" * 20), ("bin/tool.dll", bytes(range(256)) * 64)): + with open(os.path.join(d, n), "wb") as f: + f.write(data) + os.utime(os.path.join(d, n), (MTIME, MTIME)) + subprocess.run(["nix", "shell", "nixpkgs#gcab", "-c", "gcab", "-c", "-z", "setup.cab", "readme.txt", "bin/tool.dll"], + cwd=d, check=True, capture_output=True, env=dict(os.environ, TZ="UTC")) + files["setup.cab"] = open(os.path.join(d, "setup.cab"), "rb").read() + dc.emit_inputs(ctx, files, {"cabBytes": "setup.cab"})