ws-arch: merge ws/arch-lzma

This commit is contained in:
4DBug committed 2026-10-31 08:38:55 -05:00
commit b549438a0c
16 files changed
+2912

No files matched your search

+4
View File
@@ -6,8 +6,11 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
| Category | Format | Extensions | Read | Write | Capabilities | Test |
|---|---|---|---|---|---|---|
| image | png | .png .apng | yes | yes | animation: false, alpha: true, depths: 1, 2, 4, 8, 16 | `tests/image/png.luau` |
| font | ttf | .ttf .otf .ttc .otc | yes | - | outlines: "truetype", "cff", collection: true, kerning: true | `tests/font/ttf.luau` |
| archive | 7z | .7z | yes | - | methods: "copy", "lzma", "lzma2", "deflate", "bcj", "delta", encrypted: false | `tests/archive/7z.luau` |
| archive | br | .br | yes | - | stream: true | `tests/archive/br.luau` |
| archive | bz2 | .bz2 .tbz2 .tbz | yes | - | stream: true | `tests/archive/bz2.luau` |
| archive | xz | .xz .txz .lzma | yes | - | stream: true, filters: "lzma2", "lzma", "delta", "x86", "powerpc", "arm", "armthumb", "sparc", "arm64" | `tests/archive/xz.luau` |
| archive | zst | .zst .tzst | yes | - | stream: true | `tests/archive/zst.luau` |
Codecs (layer 1, shared by formats; not loadable on their own):
@@ -16,6 +19,7 @@ Codecs (layer 1, shared by formats; not loadable on their own):
- codecs/Bzip2: bzip2 decompressor (BWT + MTF + Huffman, the .bz2 stream format of bzip2 0.9.5 / 1.0.x). A codec
- codecs/Cff: Compact Font Format (Adobe TN #5176) and Type 2 charstrings (TN #5177): the outlines of OpenType fonts
- codecs/Deflate: DEFLATE (RFC 1951) decoder and compressor, with the zlib (RFC 1950) and gzip (RFC 1952) wrappers.
- codecs/Lzma: LZMA and LZMA2 decoders, the .lzma ("LZMA alone") wrapper and the .xz container. A codec (layer 3):
- codecs/Raster: an antialiased scanline rasterizer for paths of lines, quadratic and cubic Béziers, under an affine
- codecs/TrueType: the sfnt font container (TrueType .ttf, OpenType .otf with CFF outlines, collections .ttc) parsed
- codecs/Zstd: Zstandard decompression (RFC 8878). A codec (layer 3): archive/zst and anything else carrying zstd
+1
View File
@@ -5,6 +5,7 @@
| `src/Formats/codecs/Deflate/` (Inflate, init), `src/Formats/core/Crc32.luau`, `src/Formats/core/Adler32.luau`, `src/Formats/core/Huffman.luau` (table builder) | deflate-luau 1.0.0 (same author), written from RFC 1950-1952 | no licence chosen yet; no third-party code: [deflate-luau-NOTICE.txt](deflate-luau-NOTICE.txt) |
| `src/Formats/image/png/` (init, Decode) | png-luau 1.0.0 (same author), written from the PNG specification | no licence chosen yet; no third-party code |
| `src/Formats/codecs/Brotli/Static.luau` (static dictionary, context lookup table, word transforms; generated by `tools/brotli_static.py`), `src/Formats/codecs/Brotli/Decode.luau` (written from RFC 7932, structure after the reference decoder) | google/brotli | MIT: [brotli-LICENSE.txt](brotli-LICENSE.txt) |
| `src/Formats/codecs/Lzma/`, `src/Formats/archive/xz/`, `src/Formats/archive/7z/` | written from the LZMA specification / LzmaSpec.cpp and 7zFormat.txt (LZMA SDK, Igor Pavlov), the xz file format specification and xz-embedded's BCJ filters (Lasse Collin) | all public domain: [lzma-xz-PUBLIC-DOMAIN.txt](lzma-xz-PUBLIC-DOMAIN.txt) |
| `tests/fixtures/pngsuite/` | PngSuite by Willem van Schaik | [PngSuite-LICENSE.txt](PngSuite-LICENSE.txt) |
Ports of third-party code (minimp3, stb_vorbis, libopus, ...) add a row here and their upstream licence text in this
+9
View File
@@ -0,0 +1,9 @@
LZMA SDK (Igor Pavlov): "LZMA SDK is placed in the public domain. Anyone is free to copy, modify, publish, use,
compile, sell, or distribute the original LZMA SDK code, either in source code form or as a compiled binary, for any
purpose, commercial or non-commercial, and by any means." (https://www.7-zip.org/sdk.html). This covers the LZMA
specification (lzma-specification.txt, LzmaSpec.cpp) and 7zFormat.txt that codecs/Lzma and archive/7z follow.
XZ Utils / xz-embedded (Lasse Collin): the xz file format specification and xz-embedded (including xz_dec_bcj.c, whose
BCJ filters codecs/Lzma/Filters follows) were released into the public domain ("This file has been put into the public
domain. You can do whatever you want with this file."); newer releases use the 0BSD licence, which imposes no
conditions either.
+36
View File
@@ -26,6 +26,30 @@ local list: { Entry } = {
return require("@formats/image/png")
end,
},
{
name = "ttf",
category = "font",
path = "font/ttf",
extensions = { "ttf", "otf", "ttc", "otc" },
mime = { "font/ttf", "font/otf", "font/collection" },
deps = { "core/Err", "core/Bytes", "codecs/TrueType" },
caps = { decode = true, encode = false, outlines = { "truetype", "cff" }, collection = true, kerning = true },
load = function()
return require("@formats/font/ttf")
end,
},
{
name = "7z",
category = "archive",
path = "archive/7z",
extensions = { "7z" },
mime = { "application/x-7z-compressed" },
deps = { "core/Err", "core/Bytes", "core/Crc32", "Types", "codecs/Lzma", "codecs/Deflate", "containers/Archive" },
caps = { decode = true, encode = false, methods = { "copy", "lzma", "lzma2", "deflate", "bcj", "delta" }, encrypted = false },
load = function()
return require("@formats/archive/7z")
end,
},
{
name = "br",
category = "archive",
@@ -50,6 +74,18 @@ local list: { Entry } = {
return require("@formats/archive/bz2")
end,
},
{
name = "xz",
category = "archive",
path = "archive/xz",
extensions = { "xz", "txz", "lzma" },
mime = { "application/x-xz", "application/x-lzma" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Lzma", "containers/Archive" },
caps = { decode = true, encode = false, stream = true, filters = { "lzma2", "lzma", "delta", "x86", "powerpc", "arm", "armthumb", "sparc", "arm64" } },
load = function()
return require("@formats/archive/xz")
end,
},
{
name = "zst",
category = "archive",
+542
View File
@@ -0,0 +1,542 @@
--!strict
-- archive/7z/Header: the 7z header parser (7zFormat.txt from the LZMA SDK / 7-Zip, Igor Pavlov, public domain):
-- streams info (pack info, folders with their coders and bind pairs, substreams), files info (names, empty streams /
-- files, anti items, times, attributes). Not --!native: a parse failure raises an Err value that parse() catches and
-- returns; any other error is a bug and propagates (the tests' fuzz pass sees it).
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Header = {}
export type Coder = { id: string, numIn: number, numOut: number, props: buffer }
export type Folder = {
coders: { Coder },
bindPairs: { { inIndex: number, outIndex: number } },
packed: { number }, -- in-stream index of each packed stream
unpackSizes: { number }, -- per out stream
crc: number?,
firstPack: number, -- index of the folder's first pack stream (0-based)
numSub: number, -- substreams (files) in the folder
}
export type Streams = {
packPos: number,
packSizes: { number },
folders: { Folder },
subSizes: { number }, -- every substream, folder by folder
subCrcs: { [number]: number }, -- 1-based substream index -> CRC
}
export type File = {
name: string,
emptyStream: boolean,
emptyFile: boolean,
anti: boolean,
mtime: number?,
attributes: number?,
}
export type Parsed = { streams: Streams?, files: { File }, encoded: Streams? }
local K = {
End = 0x00,
Header = 0x01,
ArchiveProperties = 0x02,
AdditionalStreamsInfo = 0x03,
MainStreamsInfo = 0x04,
FilesInfo = 0x05,
PackInfo = 0x06,
UnPackInfo = 0x07,
SubStreamsInfo = 0x08,
Size = 0x09,
CRC = 0x0A,
Folder = 0x0B,
CodersUnPackSize = 0x0C,
NumUnPackStream = 0x0D,
EmptyStream = 0x0E,
EmptyFile = 0x0F,
Anti = 0x10,
Name = 0x11,
MTime = 0x14,
WinAttributes = 0x15,
EncodedHeader = 0x17,
Dummy = 0x19,
}
Header.K = K
local Fail = {}
local function bad(r: Bytes.Reader, msg: string, code: string?): never
error(setmetatable({ err = Err.new(code or Err.CORRUPT, msg, r.pos) }, Fail), 0)
end
local function check(r: Bytes.Reader)
if r.err then
error(setmetatable({ err = r.err }, Fail), 0)
end
end
local function byte(r: Bytes.Reader): number
local v = r:u8()
check(r)
return v
end
-- NUMBER: the first byte's leading 1 bits count the extra (little-endian) bytes
local function number(r: Bytes.Reader): number
local first = byte(r)
local mask = 0x80
local value = 0
for i = 0, 7 do
if bit32.band(first, mask) == 0 then
local high = bit32.band(first, mask - 1)
return value + high * 2 ^ (8 * i)
end
value += byte(r) * 2 ^ (8 * i)
mask = bit32.rshift(mask, 1)
end
return value
end
-- a count bounded by the bytes left (every counted item takes at least `min` bytes)
local function count(r: Bytes.Reader, min: number?): number
local n = number(r)
if n * (min or 1) > r:remaining() + 1 then
bad(r, "count " .. n .. " is larger than the header")
end
return n
end
local function bits(r: Bytes.Reader, n: number): { boolean }
local out = table.create(n, false)
local cur, mask = 0, 0
for i = 1, n do
if mask == 0 then
cur = byte(r)
mask = 0x80
end
out[i] = bit32.band(cur, mask) ~= 0
mask = bit32.rshift(mask, 1)
end
return out
end
-- bits preceded by an "all defined" byte
local function defined(r: Bytes.Reader, n: number): { boolean }
if byte(r) ~= 0 then
return table.create(n, true)
end
return bits(r, n)
end
local function digests(r: Bytes.Reader, n: number): { [number]: number }
local def = defined(r, n)
local out = {}
for i = 1, n do
if def[i] then
out[i] = r:u32le()
end
end
check(r)
return out
end
local function packInfo(r: Bytes.Reader, s: Streams)
s.packPos = number(r)
local n = count(r)
while true do
local t = byte(r)
if t == K.End then
break
elseif t == K.Size then
for i = 1, n do
s.packSizes[i] = number(r)
end
elseif t == K.CRC then
digests(r, n)
else
bad(r, "unexpected property " .. t .. " in pack info")
end
end
if #s.packSizes ~= n then
bad(r, "missing pack sizes")
end
end
local function folder(r: Bytes.Reader): Folder
local ncoders = count(r)
if ncoders == 0 or ncoders > 64 then
bad(r, "bad coder count " .. ncoders)
end
local f: Folder = { coders = {}, bindPairs = {}, packed = {}, unpackSizes = {}, crc = nil, firstPack = 0, numSub = 1 }
local totalIn, totalOut = 0, 0
for _ = 1, ncoders do
local flags = byte(r)
if bit32.band(flags, 0x80) ~= 0 then
bad(r, "alternative coder methods", Err.UNSUPPORTED)
end
local idSize = bit32.band(flags, 0x0F)
local id = r:string(idSize)
check(r)
local nin, nout = 1, 1
if bit32.band(flags, 0x10) ~= 0 then
nin, nout = number(r), number(r)
if nin > 64 or nout > 64 then
bad(r, "bad coder stream count")
end
end
local props = buffer.create(0)
if bit32.band(flags, 0x20) ~= 0 then
local n = count(r)
props = r:bytes(n)
check(r)
end
table.insert(f.coders, { id = id, numIn = nin, numOut = nout, props = props })
totalIn += nin
totalOut += nout
end
if totalOut == 0 then
bad(r, "a folder without output")
end
for _ = 1, totalOut - 1 do
local i, o = number(r), number(r)
table.insert(f.bindPairs, { inIndex = i, outIndex = o })
end
local npacked = totalIn - (totalOut - 1)
if npacked < 1 then
bad(r, "bad bind pairs")
end
if npacked == 1 then
for i = 0, totalIn - 1 do
local bound = false
for _, bp in f.bindPairs do
if bp.inIndex == i then
bound = true
end
end
if not bound then
table.insert(f.packed, i)
break
end
end
if #f.packed ~= 1 then
bad(r, "no packed stream")
end
else
for _ = 1, npacked do
table.insert(f.packed, number(r))
end
end
return f
end
-- the folder's main out stream: the one no bind pair consumes
function Header.mainOut(f: Folder): number?
local total = 0
for _, c in f.coders do
total += c.numOut
end
for o = 0, total - 1 do
local bound = false
for _, bp in f.bindPairs do
if bp.outIndex == o then
bound = true
end
end
if not bound then
return o
end
end
return nil
end
function Header.unpackSize(f: Folder): number
local m = Header.mainOut(f)
return if m then f.unpackSizes[m + 1] or 0 else 0
end
local function unpackInfo(r: Bytes.Reader, s: Streams)
if byte(r) ~= K.Folder then
bad(r, "expected the folder list")
end
local n = count(r)
if byte(r) ~= 0 then
bad(r, "external folders", Err.UNSUPPORTED)
end
for i = 1, n do
s.folders[i] = folder(r)
end
if byte(r) ~= K.CodersUnPackSize then
bad(r, "expected the coder unpack sizes")
end
for _, f in s.folders do
local total = 0
for _, c in f.coders do
total += c.numOut
end
for k = 1, total do
f.unpackSizes[k] = number(r)
end
end
while true do
local t = byte(r)
if t == K.End then
break
elseif t == K.CRC then
local d = digests(r, n)
for i = 1, n do
s.folders[i].crc = d[i]
end
else
bad(r, "unexpected property " .. t .. " in unpack info")
end
end
end
local function subStreamsInfo(r: Bytes.Reader, s: Streams)
local t = byte(r)
if t == K.NumUnPackStream then
for _, f in s.folders do
f.numSub = count(r, 0)
end
t = byte(r)
end
local sizes = s.subSizes
if t == K.Size then
for _, f in s.folders do
if f.numSub > 0 then
local sum = 0
for _ = 1, f.numSub - 1 do
local v = number(r)
sum += v
table.insert(sizes, v)
end
local total = Header.unpackSize(f)
if sum > total then
bad(r, "substream sizes exceed the folder")
end
table.insert(sizes, total - sum)
end
end
t = byte(r)
else
for _, f in s.folders do
if f.numSub > 1 then
bad(r, "missing substream sizes")
elseif f.numSub == 1 then
table.insert(sizes, Header.unpackSize(f))
end
end
end
-- CRCs for the streams whose folder CRC does not already cover them
local unknown = 0
for _, f in s.folders do
if not (f.numSub == 1 and f.crc) then
unknown += f.numSub
end
end
while t ~= K.End do
if t == K.CRC then
local d = digests(r, unknown)
local k, si = 1, 1
for _, f in s.folders do
if f.numSub == 1 and f.crc then
s.subCrcs[si] = f.crc
si += 1
else
for _ = 1, f.numSub do
s.subCrcs[si] = d[k]
k += 1
si += 1
end
end
end
else
bad(r, "unexpected property " .. t .. " in substreams info")
end
t = byte(r)
end
end
local function streamsInfo(r: Bytes.Reader): Streams
local s: Streams = { packPos = 0, packSizes = {}, folders = {}, subSizes = {}, subCrcs = {} }
local sawSub = false
while true do
local t = byte(r)
if t == K.End then
break
elseif t == K.PackInfo then
packInfo(r, s)
elseif t == K.UnPackInfo then
unpackInfo(r, s)
elseif t == K.SubStreamsInfo then
subStreamsInfo(r, s)
sawSub = true
else
bad(r, "unexpected property " .. t .. " in streams info")
end
end
if not sawSub then
for i, f in s.folders do
f.numSub = 1
table.insert(s.subSizes, Header.unpackSize(f))
if f.crc then
s.subCrcs[i] = f.crc
end
end
end
local p = 0
for _, f in s.folders do
f.firstPack = p
p += #f.packed
end
if p > #s.packSizes then
bad(r, "folders use more pack streams than exist")
end
return s
end
local function utf16(b: buffer, o: number, n: number): string
local out = {}
local i = 0
while i + 1 < n do
local u = buffer.readu16(b, o + i)
i += 2
if u >= 0xD800 and u < 0xDC00 and i + 1 < n then
local lo = buffer.readu16(b, o + i)
if lo >= 0xDC00 and lo < 0xE000 then
u = 0x10000 + (u - 0xD800) * 1024 + (lo - 0xDC00)
i += 2
end
end
table.insert(out, utf8.char(u))
end
return table.concat(out)
end
local function filesInfo(r: Bytes.Reader): { File }
local n = count(r, 0)
if n > 1000000 then
bad(r, "too many files", Err.LIMIT)
end
local files: { File } = table.create(n)
for i = 1, n do
files[i] = { name = "", emptyStream = false, emptyFile = false, anti = false }
end
local empties = {}
while true do
local t = byte(r)
if t == K.End then
break
end
local size = number(r)
if size > r:remaining() then
bad(r, "file property past the header")
end
local pr = r:slice(size)
check(r)
if t == K.EmptyStream then
local v = bits(pr, n)
empties = {}
for i = 1, n do
files[i].emptyStream = v[i]
if v[i] then
table.insert(empties, i)
end
end
elseif t == K.EmptyFile or t == K.Anti then
local v = bits(pr, #empties)
for k, i in empties do
if t == K.EmptyFile then
files[i].emptyFile = v[k]
else
files[i].anti = v[k]
end
end
elseif t == K.Name then
if byte(pr) ~= 0 then
bad(pr, "external names", Err.UNSUPPORTED)
end
local b = pr.buf
local p = pr.pos
for i = 1, n do
local q = p
while q + 1 < pr.limit and buffer.readu16(b, q) ~= 0 do
q += 2
end
if q + 1 >= pr.limit then
bad(pr, "unterminated name")
end
files[i].name = utf16(b, p, q - p)
p = q + 2
end
elseif t == K.MTime or t == K.WinAttributes then
local def = defined(pr, n)
if byte(pr) ~= 0 then
bad(pr, "external file properties", Err.UNSUPPORTED)
end
for i = 1, n do
if def[i] then
if t == K.MTime then
local ft = pr:u64le()
files[i].mtime = math.floor(ft / 1e7 - 11644473600)
else
files[i].attributes = pr:u32le()
end
end
end
check(pr)
end
-- other properties (CTime, ATime, StartPos, Dummy, ...) are skipped
end
return files
end
local function header(r: Bytes.Reader): Parsed
local p: Parsed = { streams = nil, files = {}, encoded = nil }
while true do
local t = byte(r)
if t == K.End then
break
elseif t == K.ArchiveProperties then
while true do
local pt = byte(r)
if pt == 0 then
break
end
r:skip(number(r))
check(r)
end
elseif t == K.AdditionalStreamsInfo then
streamsInfo(r)
elseif t == K.MainStreamsInfo then
p.streams = streamsInfo(r)
elseif t == K.FilesInfo then
p.files = filesInfo(r)
else
bad(r, "unexpected property " .. t .. " in the header")
end
end
return p
end
-- parse(buf, offset, length) -> Parsed | nil, Err. An encoded header returns { encoded = streams } for the caller to
-- decode and parse again.
function Header.parse(b: buffer, o: number, n: number): (Parsed?, Err.Err?)
local r = Bytes.reader(b, o, n)
local ok, res = pcall(function(): Parsed
local t = byte(r)
if t == K.Header then
return header(r)
elseif t == K.EncodedHeader then
return { streams = nil, files = {}, encoded = streamsInfo(r) }
end
return bad(r, "bad header type " .. t)
end)
if ok then
return res, nil
end
if type(res) == "table" and getmetatable(res :: any) == Fail then
return nil, (res :: any).err
end
error(res, 0)
end
return Header
+370
View File
@@ -0,0 +1,370 @@
--!strict
-- archive/7z: 7z archives (7zFormat.txt from the LZMA SDK, Igor Pavlov, public domain), read as an Archive whose
-- entries decode lazily (a folder is decoded once on first read, then sliced). Supports: plain and encoded (compressed)
-- headers, solid and non-solid folders, coder chains of copy / LZMA / LZMA2 / Deflate with BCJ (x86, PowerPC, ARM,
-- ARM-Thumb, SPARC, ARM64) and delta filters, empty files and directories, anti items (skipped), UTF-16 names, mtimes,
-- Windows / Unix attributes, folder and file CRC-32s (verified on read).
-- Not supported (Err.UNSUPPORTED naming the method, on read of the affected entries): BZip2, PPMd, BCJ2, Deflate64,
-- Zstd and other plug-in codecs, AES encryption, multi-volume archives, external header references; writing.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Crc32 = require("@formats/core/Crc32")
local Types = require("@formats/Types")
local Lzma = require("@formats/codecs/Lzma")
local Deflate = require("@formats/codecs/Deflate")
local Archive = require("@formats/containers/Archive")
local Header = require("@formats/archive/7z/Header")
-- ------------------------------------------------------------------------------------------------ contract
local SevenZip = {
name = "7z",
category = "archive",
extensions = { "7z" },
mime = { "application/x-7z-compressed" },
deps = { "core/Err", "core/Bytes", "core/Crc32", "Types", "codecs/Lzma", "codecs/Deflate", "containers/Archive" },
caps = { decode = true, encode = false, methods = { "copy", "lzma", "lzma2", "deflate", "bcj", "delta" }, encrypted = false },
}
export type DecodeOptions = {
maxBytes: number?, -- refuse a folder (solid block) or header that decodes to more than this (default 2^30)
checkCrc: boolean?, -- verify CRC-32s on read (default true)
}
-- ------------------------------------------------------------------------------------------------ constants
local MAGIC = "7z\188\175\39\28"
-- method id -> xz filter id (BCJ / delta)
local FILTERS: { [string]: number } = {
["\3\3\1\3"] = 0x04, -- x86
["\3\3\2\5"] = 0x05, -- PowerPC
["\3\3\5\1"] = 0x07, -- ARM
["\3\3\7\1"] = 0x08, -- ARM-Thumb
["\3\3\8\5"] = 0x09, -- SPARC
["\10"] = 0x0A, -- ARM64
["\3"] = 0x03, -- delta
}
local NAMES: { [string]: string } = {
["\0"] = "copy",
["\3\1\1"] = "lzma",
["\33"] = "lzma2",
["\4\1\8"] = "deflate",
["\4\1\9"] = "deflate64",
["\4\2\2"] = "bzip2",
["\3\4\1"] = "ppmd",
["\3\3\1\27"] = "bcj2",
["\6\241\7\1"] = "aes",
["\4\247\17\1"] = "zstd",
["\4\247\17\2"] = "brotli",
["\3\3\1\3"] = "bcj",
["\3\3\2\5"] = "ppc",
["\3\3\5\1"] = "arm",
["\3\3\7\1"] = "armt",
["\3\3\8\5"] = "sparc",
["\10"] = "arm64",
["\3"] = "delta",
}
local function methodName(id: string): string
local n = NAMES[id]
if n then
return n
end
local hex = {}
for i = 1, #id do
table.insert(hex, string.format("%02x", string.byte(id, i)))
end
return "method " .. table.concat(hex)
end
-- ------------------------------------------------------------------------------------------------ sniff
function SevenZip.sniff(r: Bytes.Reader): number
return if r:peek(6) == MAGIC then 1 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
-- folder decoding: evaluate the coder graph from the main out stream; every coder here has one in and one out stream
type Ctx = { buf: buffer, base: number, limit: number, maxBytes: number }
local function packStart(ctx: Ctx, s: Header.Streams, index: number): number
local p = ctx.base + 32 + s.packPos
for i = 1, index do
p += s.packSizes[i]
end
return p
end
local function decodeFolder(ctx: Ctx, s: Header.Streams, f: Header.Folder): (buffer?, Err.Err?)
-- coder -> first in / out stream index
local inBase, outBase = {}, {}
local ni, no = 0, 0
for i, c in f.coders do
inBase[i], outBase[i] = ni, no
ni += c.numIn
no += c.numOut
end
local depth = 0
local function out(outIdx: number): (buffer?, Err.Err?)
depth += 1
if depth > 32 then
return nil, Err.new(Err.CORRUPT, "coder graph too deep")
end
local ci
for i, c in f.coders do
if outIdx >= outBase[i] and outIdx < outBase[i] + c.numOut then
ci = i
end
end
if not ci then
return nil, Err.new(Err.CORRUPT, "bad bind pair")
end
local c = f.coders[ci]
if c.numIn ~= 1 or c.numOut ~= 1 then
return nil, Err.new(Err.UNSUPPORTED, methodName(c.id) .. " (multi-stream coder)")
end
local size = f.unpackSizes[outIdx + 1] or 0
if size > ctx.maxBytes then
return nil, Err.new(Err.LIMIT, string.format("folder of %d bytes is over maxBytes", size))
end
-- the coder's input: another coder's output, or a packed stream
local inIdx = inBase[ci]
local src: buffer, so: number, sl: number
local bound = nil
for _, bp in f.bindPairs do
if bp.inIndex == inIdx then
bound = bp.outIndex
end
end
if bound then
local b, e = out(bound)
if not b then
return nil, e
end
src, so, sl = b, 0, buffer.len(b)
else
local k = table.find(f.packed, inIdx)
if not k then
return nil, Err.new(Err.CORRUPT, "unbound coder input")
end
local pi = f.firstPack + k - 1
if pi >= #s.packSizes then
return nil, Err.new(Err.CORRUPT, "missing pack stream")
end
so = packStart(ctx, s, pi)
sl = s.packSizes[pi + 1]
if so + sl > ctx.limit or so < ctx.base then
return nil, Err.new(Err.TRUNCATED, "pack stream past the end of the archive", so)
end
src = ctx.buf
end
local id = c.id
local opts = { maxBytes = ctx.maxBytes }
if id == "\0" then
if sl < size then
return nil, Err.new(Err.TRUNCATED, "short stored stream")
end
local b = buffer.create(size)
buffer.copy(b, 0, src, so, size)
return b
elseif id == "\3\1\1" then
if buffer.len(c.props) < 5 then
return nil, Err.new(Err.CORRUPT, "bad LZMA properties")
end
local b, e = Lzma.lzma(src, so, sl, c.props, size, opts)
return b, if b then nil else e
elseif id == "\33" then
local b, e = Lzma.lzma2(src, so, sl, nil, size, opts)
return b, if b then nil else e
elseif id == "\4\1\8" then
local b, e = Deflate.inflate(src, so, sl, size)
return b, if b then nil else e
elseif FILTERS[id] then
if sl ~= size then
return nil, Err.new(Err.CORRUPT, "filter size mismatch")
end
local b = buffer.create(size)
buffer.copy(b, 0, src, so, size)
local ok, e = Lzma.filter(FILTERS[id], b, 0, size, c.props)
if not ok then
return nil, e
end
return b
end
return nil, Err.new(Err.UNSUPPORTED, methodName(id) .. " is not supported")
end
local main = Header.mainOut(f)
if not main then
return nil, Err.new(Err.CORRUPT, "folder without a main output")
end
return out(main)
end
local function folderMethod(f: Header.Folder): string
local names = {}
for _, c in f.coders do
table.insert(names, methodName(c.id))
end
return table.concat(names, "+")
end
function SevenZip.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Archive?, Err.Err?)
local o = opts or {}
local maxBytes = if type(o.maxBytes) == "number" then o.maxBytes else 2 ^ 30
local checkCrc = o.checkCrc ~= false
local b, base, limit = r.buf, r.base, r.limit
if limit - base < 32 then
return nil, Err.new(Err.TRUNCATED, "truncated signature header", base)
end
if buffer.readstring(b, base, 6) ~= MAGIC then
return nil, Err.new(Err.CORRUPT, "bad 7z signature", base)
end
if buffer.readu8(b, base + 6) ~= 0 then
return nil, Err.new(Err.UNSUPPORTED, "7z major version " .. buffer.readu8(b, base + 6), base + 6)
end
if Crc32.raw(b, base + 12, 20) ~= buffer.readu32(b, base + 8) then
return nil, Err.new(Err.CHECKSUM, "start header CRC-32 mismatch", base + 8)
end
local hr = Bytes.reader(b, base + 12, 20)
local nextOff, nextSize, nextCrc = hr:u64le(), hr:u64le(), hr:u32le()
local ctx: Ctx = { buf = b, base = base, limit = limit, maxBytes = maxBytes }
local a = Archive.new("7z")
if nextSize == 0 then
return a, nil -- an empty archive
end
local ho = base + 32 + nextOff
if nextOff < 0 or ho + nextSize > limit then
return nil, Err.new(Err.TRUNCATED, "header past the end of the archive", base + 12)
end
if Crc32.raw(b, ho, nextSize) ~= nextCrc then
return nil, Err.new(Err.CHECKSUM, "header CRC-32 mismatch", ho)
end
local hbuf, hoff, hlen = b, ho, nextSize
local parsed
for _ = 1, 4 do
local p, perr = Header.parse(hbuf, hoff, hlen)
if not p then
return nil, perr
end
if not p.encoded then
parsed = p
break
end
-- an encoded header: decode folder 1 of its streams, then parse again
local es = p.encoded
local f = es.folders[1]
if not f then
return nil, Err.new(Err.CORRUPT, "encoded header without a folder")
end
local hb, herr = decodeFolder(ctx, es, f)
if not hb then
return nil, herr
end
if f.crc and Crc32.raw(hb, 0, buffer.len(hb)) ~= f.crc then
return nil, Err.new(Err.CHECKSUM, "encoded header CRC-32 mismatch")
end
hbuf, hoff, hlen = hb, 0, buffer.len(hb)
end
if not parsed then
return nil, Err.new(Err.CORRUPT, "nested encoded headers")
end
local s = parsed.streams or { packPos = 0, packSizes = {}, folders = {}, subSizes = {}, subCrcs = {} }
a.meta.folders = #s.folders
a.meta.solid = false
-- folder caches and the substream -> folder map
local cache: { [number]: buffer } = {}
local subFolder, subOffset = {}, {}
do
local si = 1
for fi, f in s.folders do
if f.numSub > 1 then
a.meta.solid = true
end
local off = 0
for _ = 1, f.numSub do
subFolder[si], subOffset[si] = fi, off
off += s.subSizes[si] or 0
si += 1
end
if off > Header.unpackSize(f) then
return nil, Err.new(Err.CORRUPT, "substreams exceed their folder")
end
end
end
local function folderData(fi: number): (buffer?, Err.Err?)
local c = cache[fi]
if c then
return c
end
local f = s.folders[fi]
local d, e = decodeFolder(ctx, s, f)
if not d then
return nil, e
end
if checkCrc and f.crc and Crc32.raw(d, 0, buffer.len(d)) ~= f.crc then
return nil, Err.new(Err.CHECKSUM, "folder CRC-32 mismatch")
end
cache[fi] = d
return d
end
local si = 0
for _, file in parsed.files do
if file.anti then
continue
end
local attr = file.attributes
local isDir = file.emptyStream and not file.emptyFile
if attr and bit32.band(attr, 0x10) ~= 0 then
isDir = true
end
local mode = if attr and bit32.band(attr, 0x8000) ~= 0 then bit32.rshift(attr, 16) else nil
local e: Archive.Entry = {
name = file.name,
size = 0,
dir = isDir,
mtime = file.mtime,
attributes = attr,
mode = mode,
}
if not file.emptyStream then
si += 1
local idx = si
local fi = subFolder[idx]
if not fi then
return nil, Err.new(Err.CORRUPT, "more files than streams")
end
local size = s.subSizes[idx]
e.size = size
e.method = folderMethod(s.folders[fi])
if s.folders[fi].numSub == 1 then
local pk = 0
for k = 1, #s.folders[fi].packed do
pk += s.packSizes[s.folders[fi].firstPack + k] or 0
end
e.compressedSize = pk
end
e.crc = s.subCrcs[idx]
e.load = function(): (buffer?, Err.Err?)
local d, derr = folderData(fi)
if not d then
return nil, derr
end
local off = subOffset[idx]
if off + size > buffer.len(d) then
return nil, Err.new(Err.CORRUPT, "substream past its folder")
end
local out = buffer.create(size)
buffer.copy(out, 0, d, off, size)
local want = s.subCrcs[idx]
if checkCrc and want and Crc32.raw(out, 0, size) ~= want then
return nil, Err.new(Err.CHECKSUM, "CRC-32 mismatch in " .. file.name)
end
return out
end
end
Archive.put(a, e)
end
return a, nil
end
return SevenZip
+101
View File
@@ -0,0 +1,101 @@
--!strict
-- archive/xz: .xz (xz file format 1.2) and .lzma ("LZMA alone") files, read as single-stream archives holding one
-- entry (the decompressed data). Built on codecs/Lzma. Supports: concatenated streams, stream padding, every block
-- layout, checks none / CRC-32 / CRC-64 (verified; SHA-256 is not verified), filters LZMA2, delta and the BCJ filters
-- x86 / PowerPC / ARM / ARM-Thumb / SPARC / ARM64. Not supported: writing, IA-64 / RISC-V filters.
-- The entry is named after the file (opts.name without .xz / .lzma; .txz -> .tar), else "data". meta.stream = true:
-- the api unwraps an inner archive (a .tar.xz loads as the tar).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Lzma = require("@formats/codecs/Lzma")
local Archive = require("@formats/containers/Archive")
-- ------------------------------------------------------------------------------------------------ contract
local Xz = {
name = "xz",
category = "archive",
extensions = { "xz", "txz", "lzma" },
mime = { "application/x-xz", "application/x-lzma" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Lzma", "containers/Archive" },
caps = { decode = true, encode = false, stream = true, filters = { "lzma2", "lzma", "delta", "x86", "powerpc", "arm", "armthumb", "sparc", "arm64" } },
}
export type DecodeOptions = {
maxBytes: number?, -- refuse output larger than this (default 2^30)
name: string?, -- the file name (the api passes it): names the entry
}
-- ------------------------------------------------------------------------------------------------ constants
local XZ_MAGIC = "\253" .. "7zXZ\0"
-- ------------------------------------------------------------------------------------------------ sniff
-- .lzma files have no magic: props byte < 225 (0x5D for every preset), a dictionary size of 2^n or 2^n + 2^(n-1),
-- a size of -1 or under 2^40, and a 0 range coder byte
local function aloneScore(r: Bytes.Reader): number
local h = r:peek(14)
if #h < 14 then
return 0
end
local d = string.byte(h, 1)
if d >= 225 or string.byte(h, 14) ~= 0 then
return 0
end
local dict = string.byte(h, 2) + string.byte(h, 3) * 256 + string.byte(h, 4) * 65536 + string.byte(h, 5) * 16777216
local okDict = false
for n = 12, 31 do
if dict == 2 ^ n or (n < 31 and dict == 2 ^ n + 2 ^ (n - 1)) then
okDict = true
break
end
end
if not okDict then
return 0
end
local s = string.sub(h, 6, 13)
if s ~= string.rep("\255", 8) and (string.byte(h, 11) ~= 0 or string.byte(h, 12) ~= 0 or string.byte(h, 13) ~= 0) then
return 0
end
return if d == 0x5D then 0.4 else 0.2
end
function Xz.sniff(r: Bytes.Reader): number
if r:peek(6) == XZ_MAGIC then
return 1
end
return aloneScore(r)
end
-- ------------------------------------------------------------------------------------------------ decode
function Xz.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Archive?, Err.Err?)
local o = opts or {}
local n = r.limit - r.base
local out, res
local method
if r:peek(6) == XZ_MAGIC then
out, res = Lzma.xz(r.buf, r.base, n, o)
method = "lzma2"
else
out, res = Lzma.alone(r.buf, r.base, n, o)
method = "lzma"
end
if not out then
return nil, res
end
local a = Archive.new("xz")
a.meta.stream = true
a.meta.container = if method == "lzma" then "lzma" else "xz"
Archive.put(a, {
name = Archive.streamName(o, Xz.extensions),
size = buffer.len(out),
compressedSize = n,
method = method,
dir = false,
data = out,
})
return a, nil
end
return Xz
+37
View File
@@ -0,0 +1,37 @@
--!strict
--!native
--!optimize 2
-- codecs/Lzma/Crc64: CRC-64/XZ (ECMA-182 polynomial, reflected: 0xC96C5795D7870F42), the xz check type 4. The 64-bit
-- value is kept as two u32 halves (hi, lo). Written from the xz file format specification. Never throws.
local band, bxor, rshift, lshift, bor = bit32.band, bit32.bxor, bit32.rshift, bit32.lshift, bit32.bor
local readu8 = buffer.readu8
local THI, TLO = table.create(256, 0), table.create(256, 0)
for n = 0, 255 do
local hi, lo = 0, n
for _ = 1, 8 do
local low = band(lo, 1)
lo = bor(rshift(lo, 1), lshift(band(hi, 1), 31))
hi = rshift(hi, 1)
if low ~= 0 then
hi = bxor(hi, 0xC96C5795)
lo = bxor(lo, 0xD7870F42)
end
end
THI[n + 1], TLO[n + 1] = hi, lo
end
local Crc64 = {}
-- of(buf, offset, length) -> hi, lo
function Crc64.of(b: buffer, o: number, n: number): (number, number)
local hi, lo = 0xFFFFFFFF, 0xFFFFFFFF
for i = o, o + n - 1 do
local idx = band(bxor(lo, readu8(b, i)), 255) + 1
lo = bxor(TLO[idx], bor(rshift(lo, 8), lshift(band(hi, 255), 24)))
hi = bxor(THI[idx], rshift(hi, 8))
end
return bxor(hi, 0xFFFFFFFF), bxor(lo, 0xFFFFFFFF)
end
return Crc64
+492
View File
@@ -0,0 +1,492 @@
--!strict
--!native
--!optimize 2
-- codecs/Lzma/Decode: the LZMA range decoder and LZ state machine, shared by raw LZMA (.lzma, 7z) and LZMA2 (xz, 7z).
-- Written from the LZMA specification and its reference decoder (LzmaSpec.cpp, Igor Pavlov, public domain); the
-- structure (probability model layout, state transitions, distance / length decoding) follows that document.
--
-- The output buffer is also the dictionary: everything decoded stays in memory, so a match may reach back to the last
-- dictionary reset (st.dictStart). A decoder state (new) carries the probabilities, the LZ state, the four rep
-- distances, a pending match remainder (st.remLen) and the range coder across calls, so LZMA2 can feed it chunk by
-- chunk. run() decodes until st.op reaches outEnd, an end marker, or an error.
--
-- Never throws: every input read is bounds-checked (a read past the end counts in `over` and fails the call as
-- "truncated"), every output write is preceded by a capacity check, and errors return nil, message.
local readu8, readu16, writeu8, writeu16 = buffer.readu8, buffer.readu16, buffer.writeu8, buffer.writeu16
local bcreate, bcopy, blen = buffer.create, buffer.copy, buffer.len
local rshift, band = bit32.rshift, bit32.band
-- probability offsets (u16 entries)
local IS_MATCH = 0 -- 12 states x 16 pos states
local IS_REP = 192
local IS_REP_G0 = 204
local IS_REP_G1 = 216
local IS_REP_G2 = 228
local IS_REP0_LONG = 240 -- 12 x 16
local POS_SLOT = 432 -- 4 x 64
local SPEC_POS = 688 -- 115
local ALIGN = 803 -- 16
local LEN = 819 -- choice, choice2, low 16 x 8, mid 16 x 8, high 256
local REP_LEN = 1333
local LITERAL = 1847 -- 0x300 << (lc + lp)
local TOP = 16777216 -- 2^24
local Decode = {}
export type State = {
out: buffer,
cap: number,
op: number, -- bytes decoded so far (the next write offset)
dictStart: number, -- the last dictionary reset: matches may not reach before it
maxBytes: number,
probs: buffer,
nprobs: number,
lc: number,
lp: number,
pb: number,
state: number,
rep0: number,
rep1: number,
rep2: number,
rep3: number,
remLen: number, -- a match cut by outEnd, finished by the next run
range: number,
code: number,
}
-- new(cap, maxBytes) -> a decoder state with an empty output buffer of capacity cap
function Decode.new(cap: number, maxBytes: number): State
local c = math.max(64, math.min(cap, maxBytes))
return {
out = bcreate(c),
cap = c,
op = 0,
dictStart = 0,
maxBytes = maxBytes,
probs = bcreate(2),
nprobs = 0,
lc = 0,
lp = 0,
pb = 0,
state = 0,
rep0 = 0,
rep1 = 0,
rep2 = 0,
rep3 = 0,
remLen = 0,
range = 0xFFFFFFFF,
code = 0,
}
end
-- setProps(st, lc, lp, pb) -> ok, message?: new literal / position parameters (resets the probabilities)
function Decode.setProps(st: State, lc: number, lp: number, pb: number): (boolean, string?)
if lc > 8 or lp > 4 or pb > 4 or lc < 0 or lp < 0 or pb < 0 then
return false, "bad lc / lp / pb"
end
st.lc, st.lp, st.pb = lc, lp, pb
local n = LITERAL + 0x300 * 2 ^ (lc + lp)
if blen(st.probs) < n * 2 then
st.probs = bcreate(n * 2)
end
st.nprobs = n
Decode.resetState(st)
return true, nil
end
-- resetState(st): probabilities to 1/2, LZ state and reps to 0
function Decode.resetState(st: State)
local p = st.probs
for i = 0, st.nprobs - 1 do
writeu16(p, i * 2, 1024)
end
st.state = 0
st.rep0, st.rep1, st.rep2, st.rep3 = 0, 0, 0, 0
st.remLen = 0
end
-- resetDict(st): matches may no longer reach before the current position
function Decode.resetDict(st: State)
st.dictStart = st.op
st.remLen = 0
end
-- rcInit(st, buf, ip, iend) -> next ip | nil, message: the 5 range coder init bytes
function Decode.rcInit(st: State, b: buffer, ip: number, iend: number): (number?, string?)
if ip + 5 > iend then
return nil, "truncated range coder init"
end
if readu8(b, ip) ~= 0 then
return nil, "bad range coder init byte"
end
st.code = readu8(b, ip + 1) * 16777216 + readu8(b, ip + 2) * 65536 + readu8(b, ip + 3) * 256 + readu8(b, ip + 4)
st.range = 0xFFFFFFFF
if st.code == st.range then
return nil, "bad range coder init"
end
return ip + 5, nil
end
-- ensure(st, need) -> ok: grow the output to hold need bytes (bounded by maxBytes)
local function ensure(st: State, need: number): boolean
if need <= st.cap then
return true
end
if need > st.maxBytes then
return false
end
local c = math.min(math.max(st.cap * 2, need, 65536), st.maxBytes)
local nb = bcreate(c)
bcopy(nb, 0, st.out, 0, st.op)
st.out = nb
st.cap = c
return true
end
Decode.ensure = ensure
-- copy(st, n, b, ip): append n stored bytes (LZMA2 uncompressed chunks); the caller checked the input range
function Decode.copy(st: State, n: number, b: buffer, ip: number): (boolean, string?)
if not ensure(st, st.op + n) then
return false, "limit: output over maxBytes"
end
bcopy(st.out, st.op, b, ip, n)
st.op += n
return true, nil
end
-- the range decoder state while run() executes (module upvalues: the helpers below are created once, so LuaJIT
-- traces stay valid across calls; run() is not re-entrant, and never yields)
local EMPTY = bcreate(2)
local probs: buffer = EMPTY
local inb: buffer = EMPTY
local range, code, ip, iend, over = 0, 0, 0, 0, 0
-- decode one bit with the probability at index i
local function bit(i: number): number
local p = i * 2
local prob = readu16(probs, p)
local bound = rshift(range, 11) * prob
local r
if code < bound then
range = bound
writeu16(probs, p, prob + rshift(2048 - prob, 5))
r = 0
else
range -= bound
code -= bound
writeu16(probs, p, prob - rshift(prob, 5))
r = 1
end
if range < TOP then
range *= 256
if ip < iend then
code = code * 256 + readu8(inb, ip)
else
code *= 256
over += 1
end
ip += 1
end
return r
end
local function tree(base: number, nbits: number): number
local m = 1
for _ = 1, nbits do
m = m * 2 + bit(base + m)
end
return m - 2 ^ nbits
end
local function reverse(base: number, nbits: number): number
local m = 1
local sym = 0
for i = 0, nbits - 1 do
local b = bit(base + m)
m = m * 2 + b
sym += b * 2 ^ i
end
return sym
end
local function direct(nbits: number): number
local res = 0
for _ = 1, nbits do
range = rshift(range, 1)
local b = 0
if code >= range then
code -= range
b = 1
end
res = res * 2 + b
if range < TOP then
range *= 256
if ip < iend then
code = code * 256 + readu8(inb, ip)
else
code *= 256
over += 1
end
ip += 1
end
end
return res
end
local function length(base: number, posState: number): number
if bit(base) == 0 then
return tree(base + 2 + posState * 8, 3)
end
if bit(base + 1) == 0 then
return 8 + tree(base + 130 + posState * 8, 3)
end
return 16 + tree(base + 258, 8)
end
-- run(st, buf, ip, iend, outEnd) -> status, ip | nil, message. status: "full" (st.op reached outEnd) or "eos" (end
-- marker). The range coder must have been initialised (rcInit).
function Decode.run(st: State, inb0: buffer, ip0: number, iend0: number, outEnd: number): (string?, any)
probs = st.probs
inb = inb0
iend = iend0
local out = st.out
local cap = st.cap
local op = st.op
local dictStart = st.dictStart
range, code = st.range, st.code
ip = ip0
over = 0
local state = st.state
local rep0, rep1, rep2, rep3 = st.rep0, st.rep1, st.rep2, st.rep3
local lc = st.lc
local lcShift = 2 ^ (8 - lc)
local lpMask = 2 ^ st.lp - 1
local pbMask = 2 ^ st.pb - 1
local lcMul = 2 ^ lc
local status: string? = nil
local msg: string? = nil
-- a pending match from the previous call
local remLen = st.remLen
if remLen > 0 then
local n = math.min(remLen, outEnd - op)
if n > 0 then
if op + n > cap then
st.op = op
if not ensure(st, op + n) then
probs, inb = EMPTY, EMPTY
return nil, "limit: output over maxBytes"
end
out, cap = st.out, st.cap
end
local src = op - rep0 - 1
for k = 0, n - 1 do
writeu8(out, op + k, readu8(out, src + k))
end
op += n
remLen -= n
end
end
while true do
if op >= outEnd then
status = "full"
break
end
if over > 0 then
msg = "truncated"
break
end
if op + 273 > cap then
st.op = op
if not ensure(st, math.min(op + 273, outEnd)) then
msg = "limit: output over maxBytes"
break
end
out, cap = st.out, st.cap
end
local pos = op - dictStart
local posState = band(pos, pbMask)
-- is match? (inlined bit)
local pidx = (IS_MATCH + state * 16 + posState) * 2
local prob = readu16(probs, pidx)
local bound = rshift(range, 11) * prob
if code < bound then
range = bound
writeu16(probs, pidx, prob + rshift(2048 - prob, 5))
if range < TOP then
range *= 256
if ip < iend then
code = code * 256 + readu8(inb, ip)
else
code *= 256
over += 1
end
ip += 1
end
-- literal
local prev = if op > dictStart then readu8(out, op - 1) else 0
local base = LITERAL + 0x300 * (band(pos, lpMask) * lcMul + prev // lcShift)
local sym = 1
if state >= 7 then
local mpos = op - rep0 - 1
local matchByte = if mpos >= dictStart then readu8(out, mpos) else 0
repeat
local matchBit = band(rshift(matchByte, 7), 1)
matchByte *= 2
local b = bit(base + (1 + matchBit) * 256 + sym)
sym = sym * 2 + b
if matchBit ~= b then
break
end
until sym >= 256
end
while sym < 256 do
local p2 = (base + sym) * 2
local pr = readu16(probs, p2)
local bd = rshift(range, 11) * pr
if code < bd then
range = bd
writeu16(probs, p2, pr + rshift(2048 - pr, 5))
sym = sym * 2
else
range -= bd
code -= bd
writeu16(probs, p2, pr - rshift(pr, 5))
sym = sym * 2 + 1
end
if range < TOP then
range *= 256
if ip < iend then
code = code * 256 + readu8(inb, ip)
else
code *= 256
over += 1
end
ip += 1
end
end
writeu8(out, op, sym - 256)
op += 1
state = if state < 4 then 0 elseif state < 10 then state - 3 else state - 6
else
range -= bound
code -= bound
writeu16(probs, pidx, prob - rshift(prob, 5))
if range < TOP then
range *= 256
if ip < iend then
code = code * 256 + readu8(inb, ip)
else
code *= 256
over += 1
end
ip += 1
end
local len
if bit(IS_REP + state) == 0 then
-- simple match
len = length(LEN, posState)
state = if state < 7 then 7 else 10
rep3, rep2, rep1 = rep2, rep1, rep0
local lenState = if len < 3 then len else 3
local slot = tree(POS_SLOT + lenState * 64, 6)
if slot < 4 then
rep0 = slot
else
local nd = slot // 2 - 1
local dist = (2 + slot % 2) * 2 ^ nd
if slot < 14 then
dist += reverse(SPEC_POS + dist - slot, nd)
else
dist += direct(nd - 4) * 16
dist += reverse(ALIGN, 4)
end
rep0 = dist
end
if rep0 == 0xFFFFFFFF then
status = "eos"
break
end
else
if bit(IS_REP_G0 + state) == 0 then
if bit(IS_REP0_LONG + state * 16 + posState) == 0 then
-- short rep: one byte at rep0
if op == dictStart or rep0 >= op - dictStart then
msg = "distance past the dictionary start"
break
end
state = if state < 7 then 9 else 11
writeu8(out, op, readu8(out, op - rep0 - 1))
op += 1
continue
end
else
local dist
if bit(IS_REP_G1 + state) == 0 then
dist = rep1
else
if bit(IS_REP_G2 + state) == 0 then
dist = rep2
else
dist = rep3
rep3 = rep2
end
rep2 = rep1
end
rep1 = rep0
rep0 = dist
end
len = length(REP_LEN, posState)
state = if state < 7 then 8 else 11
end
-- copy len + 2 bytes from rep0 + 1 back
if rep0 >= op - dictStart then
msg = "distance past the dictionary start"
break
end
local n = len + 2
local room = outEnd - op
if n > room then
remLen = n - room
n = room
end
local src = op - rep0 - 1
if rep0 + 1 >= n then
bcopy(out, op, out, src, n)
else
for k = 0, n - 1 do
writeu8(out, op + k, readu8(out, src + k))
end
end
op += n
end
end
st.op = op
st.range, st.code = range, code
st.state = state
st.rep0, st.rep1, st.rep2, st.rep3 = rep0, rep1, rep2, rep3
st.remLen = remLen
probs, inb = EMPTY, EMPTY -- do not keep the caller's buffers alive
if msg then
return nil, msg
end
if over > 0 then
return nil, "truncated"
end
return status, ip
end
-- finish(st) -> a buffer of exactly the decoded bytes
function Decode.finish(st: State): buffer
if st.cap == st.op then
return st.out
end
local b = bcreate(st.op)
bcopy(b, 0, st.out, 0, st.op)
return b
end
return Decode
+177
View File
@@ -0,0 +1,177 @@
--!strict
--!native
--!optimize 2
-- codecs/Lzma/Filters: the branch-call-jump (BCJ) and delta decoding filters of xz and 7z, run in place over a whole
-- decoded buffer range. Written from the xz file format specification and xz-embedded's xz_dec_bcj.c (Lasse Collin,
-- public domain): x86, ARM, ARM-Thumb, PowerPC, SPARC, ARM64 and delta. Not supported: IA-64, RISC-V.
-- Never throws: every access is inside [o, o + n).
local readu8, writeu8, readu32, writeu32 = buffer.readu8, buffer.writeu8, buffer.readu32, buffer.writeu32
local band, bor, bxor, rshift, lshift, byteswap = bit32.band, bit32.bor, bit32.bxor, bit32.rshift, bit32.lshift, bit32.byteswap
local TWO32 = 4294967296
local Filters = {}
local MASK_ALLOWED = { [0] = true, true, true, false, true, false, false, false }
local MASK_BITNUM = { [0] = 0, 1, 2, 2, 3, 3, 3, 3 }
local function msbyte(b: number): boolean
return b == 0 or b == 0xFF
end
-- x86(b, o, n, start): BCJ x86 decode; start = the stream position of b[o] (the filter's start offset)
function Filters.x86(b: buffer, o: number, n: number, start: number)
if n <= 4 then
return
end
local size = n - 4
local prevPos = -1
local prevMask = 0
local i = 0
while i < size do
local c = readu8(b, o + i)
if band(c, 0xFE) ~= 0xE8 then
i += 1
continue
end
local d = i - prevPos
if d > 3 then
prevMask = 0
else
prevMask = band(lshift(prevMask, d - 1), 7)
if prevMask ~= 0 then
local bb = readu8(b, o + i + 4 - MASK_BITNUM[prevMask])
if not MASK_ALLOWED[prevMask] or msbyte(bb) then
prevPos = i
prevMask = bor(lshift(prevMask, 1), 1)
i += 1
continue
end
end
end
prevPos = i
if msbyte(readu8(b, o + i + 4)) then
local src = readu32(b, o + i + 1)
local dest
while true do
dest = (src - (start + i + 5)) % TWO32
if prevMask == 0 then
break
end
local j = MASK_BITNUM[prevMask] * 8
local bb = band(rshift(dest, 24 - j), 0xFF)
if not msbyte(bb) then
break
end
src = bxor(dest, 2 ^ (32 - j) - 1)
end
dest = band(dest, 0x01FFFFFF)
if band(dest, 0x01000000) ~= 0 then
dest = bor(dest, 0xFF000000)
end
writeu32(b, o + i + 1, dest)
i += 5
else
prevMask = bor(lshift(prevMask, 1), 1)
i += 1
end
end
end
function Filters.arm(b: buffer, o: number, n: number, start: number)
local i = 0
while i + 4 <= n do
if readu8(b, o + i + 3) == 0xEB then
local addr = readu8(b, o + i) + readu8(b, o + i + 1) * 256 + readu8(b, o + i + 2) * 65536
addr = (addr * 4 - (start + i + 8)) % TWO32
addr = rshift(addr, 2)
writeu8(b, o + i, band(addr, 255))
writeu8(b, o + i + 1, band(rshift(addr, 8), 255))
writeu8(b, o + i + 2, band(rshift(addr, 16), 255))
end
i += 4
end
end
function Filters.armthumb(b: buffer, o: number, n: number, start: number)
local i = 0
while i + 4 <= n do
local b1, b3 = readu8(b, o + i + 1), readu8(b, o + i + 3)
if band(b1, 0xF8) == 0xF0 and band(b3, 0xF8) == 0xF8 then
local addr = band(b1, 7) * 524288 + readu8(b, o + i) * 2048 + band(b3, 7) * 256 + readu8(b, o + i + 2)
addr = (addr * 2 - (start + i + 4)) % TWO32
addr = rshift(addr, 1)
writeu8(b, o + i + 1, bor(0xF0, band(rshift(addr, 19), 7)))
writeu8(b, o + i, band(rshift(addr, 11), 255))
writeu8(b, o + i + 3, bor(0xF8, band(rshift(addr, 8), 7)))
writeu8(b, o + i + 2, band(addr, 255))
i += 4
else
i += 2
end
end
end
function Filters.powerpc(b: buffer, o: number, n: number, start: number)
local i = 0
while i + 4 <= n do
local instr = byteswap(readu32(b, o + i))
if band(instr, 0xFC000003) == 0x48000001 then
instr = band(instr, 0x03FFFFFC)
instr = band((instr - (start + i)) % TWO32, 0x03FFFFFC)
instr = bor(instr, 0x48000001)
writeu32(b, o + i, byteswap(instr))
end
i += 4
end
end
function Filters.sparc(b: buffer, o: number, n: number, start: number)
local i = 0
while i + 4 <= n do
local instr = byteswap(readu32(b, o + i))
local top = rshift(instr, 22)
if top == 0x100 or top == 0x1FF then
instr = (instr * 4) % TWO32
instr = (instr - (start + i)) % TWO32
instr = rshift(instr, 2)
instr = bor((0x40000000 - band(instr, 0x400000)) % TWO32, 0x40000000, band(instr, 0x3FFFFF))
writeu32(b, o + i, byteswap(instr))
end
i += 4
end
end
function Filters.arm64(b: buffer, o: number, n: number, start: number)
local i = 0
while i + 4 <= n do
local pc = (start + i) % TWO32
local instr = readu32(b, o + i)
if rshift(instr, 26) == 0x25 then
local src = instr
local p = (TWO32 - rshift(pc, 2)) % TWO32
writeu32(b, o + i, bor(0x94000000, band((src + p) % TWO32, 0x03FFFFFF)))
elseif band(instr, 0x9F000000) == 0x90000000 then
local src = bor(band(rshift(instr, 29), 3), band(rshift(instr, 3), 0x001FFFFC))
if band(src + 0x00020000, 0x001C0000) == 0 then
local p = (TWO32 - rshift(pc, 12)) % TWO32
local dest = (src + p) % TWO32
local v = band(instr, 0x9000001F)
v = bor(v, lshift(band(dest, 3), 29))
v = bor(v, lshift(band(dest, 0x0003FFFC), 3))
v = bor(v, band((TWO32 - band(dest, 0x00020000)) % TWO32, 0x00E00000))
writeu32(b, o + i, v)
end
end
i += 4
end
end
-- delta(b, o, n, dist): b[i] += b[i - dist] (1 <= dist <= 256)
function Filters.delta(b: buffer, o: number, n: number, dist: number)
for i = dist, n - 1 do
writeu8(b, o + i, band(readu8(b, o + i) + readu8(b, o + i - dist), 255))
end
end
return Filters
+601
View File
@@ -0,0 +1,601 @@
--!strict
-- codecs/Lzma: LZMA and LZMA2 decoders, the .lzma ("LZMA alone") wrapper and the .xz container. A codec (layer 3):
-- archive/xz, archive/7z (and anything else holding LZMA data) build on it. Decode only.
-- Written from the LZMA specification (LzmaSpec.cpp, Igor Pavlov, public domain) and the xz file format specification
-- 1.2 (Lasse Collin / Igor Pavlov, public domain); the BCJ filters follow xz-embedded (public domain).
--
-- local Lzma = require("@formats/codecs/Lzma")
-- local out, e = Lzma.lzma(buf, off, len, props, unpackSize?, opts?) -- raw LZMA; props = 5-byte buffer / string
-- -- or { lc, lp, pb, dictSize }
-- local out, e = Lzma.lzma2(buf, off, len, dictSize?, unpackSize?, opts?) -- raw LZMA2 chunks
-- local out, e = Lzma.alone(buf, off?, len?, opts?) -- a .lzma file (13-byte header)
-- local out, e = Lzma.xz(buf, off?, len?, opts?) -- a .xz file (all streams concatenated)
-- Lzma.filter(id, buf, off, len, props?) -- BCJ / delta decode in place (7z)
--
-- Each returns buffer, consumedEnd (the input offset just past what was decoded) | nil, Err. opts.maxBytes (default
-- 2^30) bounds the output (Err.LIMIT). xz: every stream, block, index and footer is parsed and checked; check types
-- none / CRC-32 / CRC-64 are verified, SHA-256 is skipped (not verified). xz filters: LZMA2, delta, x86, PowerPC,
-- ARM, ARM-Thumb, SPARC, ARM64; IA-64 and RISC-V are Err.UNSUPPORTED. Never throws.
local Err = require("@formats/core/Err")
local Crc32 = require("@formats/core/Crc32")
local Decode = require("@formats/codecs/Lzma/Decode")
local Filters = require("@formats/codecs/Lzma/Filters")
local Crc64 = require("@formats/codecs/Lzma/Crc64")
local readu8, readu32 = buffer.readu8, buffer.readu32
local Lzma = {}
local DEFAULT_MAX = 2 ^ 30
export type Options = {
maxBytes: number?, -- refuse output larger than this (default 2^30)
}
export type Props = { lc: number, lp: number, pb: number, dictSize: number? }
local function toBuffer(b: any): buffer?
if type(b) == "string" then
return buffer.fromstring(b)
end
if type(b) ~= "buffer" then
return nil
end
return b
end
local function range(b: buffer, off: number?, len: number?): (number?, number)
local n = buffer.len(b)
local o = off or 0
if type(o) ~= "number" or o < 0 or o > n or o % 1 ~= 0 then
return nil, 0
end
local l = len or (n - o)
if type(l) ~= "number" or l < 0 or l % 1 ~= 0 then
return nil, 0
end
if o + l > n then
l = n - o
end
return o, l
end
local function args(what: string, buf: any, offset: number?, length: number?): (buffer?, number, number, Err.Err?)
local b = toBuffer(buf)
if not b then
return nil, 0, 0, Err.new(Err.ARG, what .. ": expected a buffer or a string, got " .. typeof(buf))
end
local o, l = range(b, offset, length)
if not o then
return nil, 0, 0, Err.new(Err.ARG, what .. ": bad offset / length " .. tostring(offset) .. ", " .. tostring(length))
end
return b, o, l, nil
end
local function maxOf(opts: Options?): number
local m = opts and opts.maxBytes
return if type(m) == "number" and m >= 0 then m else DEFAULT_MAX
end
-- a decoder message -> Err
local function fail(msg: any, at: number?): Err.Err
local s = tostring(msg)
local code = Err.CORRUPT
if string.sub(s, 1, 5) == "limit" then
code = Err.LIMIT
elseif string.find(s, "truncated", 1, true) then
code = Err.TRUNCATED
end
return Err.new(code, s, at)
end
-- props byte -> lc, lp, pb | nil
local function propsByte(d: number): (number?, number, number)
if d >= 225 then
return nil, 0, 0
end
return d % 9, (d // 9) % 5, d // 45
end
Lzma.propsByte = propsByte
-- ------------------------------------------------------------------------------------------------ LZMA
-- decodeLzma(st, b, o, e, unpackSize?) -> consumedEnd | nil, Err: one raw LZMA stream into st (props set)
local function decodeLzma(st: Decode.State, b: buffer, o: number, e: number, unpackSize: number?): (number?, Err.Err?)
local ip, ierr = Decode.rcInit(st, b, o, e)
if not ip then
return nil, fail(ierr, o)
end
local target = if unpackSize then st.op + unpackSize else math.huge
if unpackSize and target > st.maxBytes then
return nil, Err.new(Err.LIMIT, string.format("output of %d bytes is over maxBytes", unpackSize))
end
if unpackSize and not Decode.ensure(st, target) then
return nil, Err.new(Err.LIMIT, "output over maxBytes")
end
local status, res = Decode.run(st, b, ip, e, target)
if not status then
return nil, fail(res, o)
end
if unpackSize and st.op ~= target then
return nil, Err.new(Err.CORRUPT, "end marker before the declared size", o)
end
return res :: number, nil
end
-- lzma(buf, offset, length, props, unpackSize?, opts?) -> buffer, consumedEnd | nil, Err
function Lzma.lzma(buf: buffer | string, offset: number?, length: number?, props: any, unpackSize: number?, opts: Options?): (buffer?, any)
local b, o, l, aerr = args("Lzma.lzma", buf, offset, length)
if not b then
return nil, aerr
end
local lc, lp, pb
if type(props) == "table" then
lc, lp, pb = props.lc, props.lp, props.pb
else
local pbuf = toBuffer(props)
if not pbuf or buffer.len(pbuf) < 1 then
return nil, Err.new(Err.ARG, "Lzma.lzma: props must be the 5-byte properties or { lc, lp, pb }")
end
lc, lp, pb = propsByte(readu8(pbuf, 0))
if not lc then
return nil, Err.new(Err.CORRUPT, "bad LZMA properties byte")
end
end
if type(lc) ~= "number" or type(lp) ~= "number" or type(pb) ~= "number" then
return nil, Err.new(Err.ARG, "Lzma.lzma: bad props")
end
if unpackSize ~= nil and (type(unpackSize) ~= "number" or unpackSize < 0 or unpackSize % 1 ~= 0) then
return nil, Err.new(Err.ARG, "Lzma.lzma: bad unpackSize")
end
local max = maxOf(opts)
local st = Decode.new(if unpackSize then unpackSize else l * 4, max)
local ok, perr = Decode.setProps(st, lc, lp, pb)
if not ok then
return nil, Err.new(Err.CORRUPT, tostring(perr))
end
local consumed, err = decodeLzma(st, b, o, o + l, unpackSize)
if not consumed then
return nil, err
end
return Decode.finish(st), consumed
end
-- alone(buf, offset?, length?, opts?) -> buffer, consumedEnd | nil, Err: a .lzma file (props, dict size, u64 size)
function Lzma.alone(buf: buffer | string, offset: number?, length: number?, opts: Options?): (buffer?, any)
local b, o, l, aerr = args("Lzma.alone", buf, offset, length)
if not b then
return nil, aerr
end
if l < 13 then
return nil, Err.new(Err.TRUNCATED, "truncated .lzma header", o)
end
local lo, hi = readu32(b, o + 5), readu32(b, o + 9)
local size: number? = nil
if not (lo == 0xFFFFFFFF and hi == 0xFFFFFFFF) then
if hi >= 2 ^ 21 then
return nil, Err.new(Err.CORRUPT, "bad .lzma size", o + 5)
end
size = hi * 4294967296 + lo
end
return Lzma.lzma(b, o + 13, l - 13, buffer.fromstring(buffer.readstring(b, o, 1)), size, opts)
end
-- ------------------------------------------------------------------------------------------------ LZMA2
-- decodeLzma2(st, b, o, e) -> consumedEnd | nil, Err: LZMA2 chunks up to the end-of-stream byte
local function decodeLzma2(st: Decode.State, b: buffer, o: number, e: number): (number?, Err.Err?)
local p = o
local needDict, needProps = true, true
while true do
if p >= e then
return nil, Err.new(Err.TRUNCATED, "truncated LZMA2 stream", p)
end
local c = readu8(b, p)
if c == 0 then
return p + 1, nil
end
if c == 1 or c == 2 then
if p + 3 > e then
return nil, Err.new(Err.TRUNCATED, "truncated LZMA2 chunk header", p)
end
local n = readu8(b, p + 1) * 256 + readu8(b, p + 2) + 1
if c == 1 then
Decode.resetDict(st)
needDict = false
elseif needDict then
return nil, Err.new(Err.CORRUPT, "LZMA2 chunk without a dictionary reset", p)
end
if p + 3 + n > e then
return nil, Err.new(Err.TRUNCATED, "truncated LZMA2 stored chunk", p)
end
local ok, cerr = Decode.copy(st, n, b, p + 3)
if not ok then
return nil, fail(cerr, p)
end
st.remLen = 0
p += 3 + n
elseif c >= 0x80 then
if p + 5 > e then
return nil, Err.new(Err.TRUNCATED, "truncated LZMA2 chunk header", p)
end
local usize = (c % 32) * 65536 + readu8(b, p + 1) * 256 + readu8(b, p + 2) + 1
local psize = readu8(b, p + 3) * 256 + readu8(b, p + 4) + 1
local mode = (c // 32) % 4
local q = p + 5
if mode == 3 then
Decode.resetDict(st)
needDict = false
elseif needDict then
return nil, Err.new(Err.CORRUPT, "LZMA2 chunk without a dictionary reset", p)
end
if mode >= 2 then
if q >= e then
return nil, Err.new(Err.TRUNCATED, "truncated LZMA2 properties", q)
end
local lc, lp, pb = propsByte(readu8(b, q))
if not lc or lc + lp > 4 then
return nil, Err.new(Err.CORRUPT, "bad LZMA2 properties", q)
end
Decode.setProps(st, lc, lp, pb)
needProps = false
q += 1
elseif needProps then
return nil, Err.new(Err.CORRUPT, "LZMA2 chunk without properties", p)
elseif mode == 1 then
Decode.resetState(st)
end
if q + psize > e then
return nil, Err.new(Err.TRUNCATED, "truncated LZMA2 chunk", q)
end
local target = st.op + usize
if target > st.maxBytes then
return nil, Err.new(Err.LIMIT, "output over maxBytes")
end
Decode.ensure(st, target)
local ip, ierr = Decode.rcInit(st, b, q, q + psize)
if not ip then
return nil, fail(ierr, q)
end
local status, res = Decode.run(st, b, ip, q + psize, target)
if not status then
return nil, fail(res, q)
end
if status ~= "full" or st.op ~= target then
return nil, Err.new(Err.CORRUPT, "LZMA2 chunk size mismatch", p)
end
p = q + psize
else
return nil, Err.new(Err.CORRUPT, "bad LZMA2 control byte " .. c, p)
end
end
end
-- lzma2(buf, offset?, length?, dictSize?, unpackSize?, opts?) -> buffer, consumedEnd | nil, Err
function Lzma.lzma2(buf: buffer | string, offset: number?, length: number?, _dictSize: number?, unpackSize: number?, opts: Options?): (buffer?, any)
local b, o, l, aerr = args("Lzma.lzma2", buf, offset, length)
if not b then
return nil, aerr
end
local max = maxOf(opts)
local st = Decode.new(if type(unpackSize) == "number" and unpackSize >= 0 then unpackSize else l * 4, max)
local consumed, err = decodeLzma2(st, b, o, o + l)
if not consumed then
return nil, err
end
if type(unpackSize) == "number" and st.op ~= unpackSize then
return nil, Err.new(Err.CORRUPT, string.format("LZMA2 output is %d bytes, expected %d", st.op, unpackSize))
end
return Decode.finish(st), consumed
end
-- ------------------------------------------------------------------------------------------------ filters
-- filter ids (xz numbering; 7z's method ids map onto these in archive/7z)
Lzma.FILTER = table.freeze({
delta = 0x03,
x86 = 0x04,
powerpc = 0x05,
ia64 = 0x06,
arm = 0x07,
armthumb = 0x08,
sparc = 0x09,
arm64 = 0x0A,
riscv = 0x0B,
lzma2 = 0x21,
})
local BCJ: { [number]: (buffer, number, number, number) -> () } = {
[0x04] = Filters.x86,
[0x05] = Filters.powerpc,
[0x07] = Filters.arm,
[0x08] = Filters.armthumb,
[0x09] = Filters.sparc,
[0x0A] = Filters.arm64,
}
-- filter(id, buf, offset, length, props?) -> true | nil, Err: decode a BCJ / delta filter in place. props: the
-- filter's property bytes (a string or buffer: BCJ start offset u32le, delta distance - 1)
function Lzma.filter(id: number, b: buffer, o: number, n: number, props: any?): (boolean?, Err.Err?)
local pb = toBuffer(props)
local plen = if pb then buffer.len(pb) else 0
if id == 0x03 then
if plen ~= 1 then
return nil, Err.new(Err.CORRUPT, "bad delta filter properties")
end
Filters.delta(b, o, n, readu8(pb :: buffer, 0) + 1)
return true
end
local f = BCJ[id]
if not f then
return nil, Err.new(Err.UNSUPPORTED, string.format("filter 0x%x is not supported", id))
end
local start = 0
if plen == 4 then
start = readu32(pb :: buffer, 0)
elseif plen ~= 0 then
return nil, Err.new(Err.CORRUPT, "bad BCJ filter properties")
end
f(b, o, n, start)
return true
end
-- ------------------------------------------------------------------------------------------------ xz
local XZ_MAGIC = "\253" .. "7zXZ\0"
local CHECK_SIZE = { [0] = 0, 4, 4, 4, 8, 8, 8, 16, 16, 16, 32, 32, 32, 64, 64, 64 }
-- vli(b, p, e) -> value, next | nil
local function vli(b: buffer, p: number, e: number): (number?, number)
local v, mul = 0, 1
for i = 0, 8 do
if p + i >= e then
return nil, p
end
local c = readu8(b, p + i)
v += (c % 128) * mul
if c < 128 then
if c == 0 and i > 0 then
return nil, p -- non-minimal encoding
end
return v, p + i + 1
end
mul *= 128
end
return nil, p
end
Lzma.vli = vli
local function crc(b: buffer, o: number, n: number): number
return Crc32.raw(b, o, n)
end
-- one xz stream at o -> next offset | nil, Err (blocks appended to st)
local function xzStream(st: Decode.State, b: buffer, o: number, e: number): (number?, Err.Err?)
if o + 12 > e then
return nil, Err.new(Err.TRUNCATED, "truncated xz stream header", o)
end
if buffer.readstring(b, o, 6) ~= XZ_MAGIC then
return nil, Err.new(Err.CORRUPT, "bad xz magic", o)
end
if readu8(b, o + 6) ~= 0 or readu8(b, o + 7) > 15 then
return nil, Err.new(Err.UNSUPPORTED, "unknown xz stream flags", o + 6)
end
if crc(b, o + 6, 2) ~= readu32(b, o + 8) then
return nil, Err.new(Err.CHECKSUM, "xz stream header CRC-32 mismatch", o + 8)
end
local check = readu8(b, o + 7)
local csize = CHECK_SIZE[check]
local p = o + 12
local records: { { number } } = {}
while true do
if p >= e then
return nil, Err.new(Err.TRUNCATED, "truncated xz block", p)
end
local hs = readu8(b, p)
if hs == 0 then
break -- the index
end
local hsize = (hs + 1) * 4
if p + hsize > e then
return nil, Err.new(Err.TRUNCATED, "truncated xz block header", p)
end
if crc(b, p, hsize - 4) ~= readu32(b, p + hsize - 4) then
return nil, Err.new(Err.CHECKSUM, "xz block header CRC-32 mismatch", p)
end
local flags = readu8(b, p + 1)
if flags % 64 >= 4 then
return nil, Err.new(Err.UNSUPPORTED, "reserved xz block flags", p + 1)
end
local nfilters = flags % 4 + 1
local q = p + 2
local he = p + hsize - 4
local csz, usz: number? = nil, nil
if flags >= 128 or (flags // 64) % 2 == 1 then
if (flags // 64) % 2 == 1 then
local v
v, q = vli(b, q, he)
if not v or v == 0 then
return nil, Err.new(Err.CORRUPT, "bad xz compressed size", q)
end
csz = v
end
if flags >= 128 then
local v
v, q = vli(b, q, he)
if not v then
return nil, Err.new(Err.CORRUPT, "bad xz uncompressed size", q)
end
usz = v
end
end
local filters: { { id: number, props: buffer } } = {}
for _ = 1, nfilters do
local id, psz
id, q = vli(b, q, he)
if not id then
return nil, Err.new(Err.CORRUPT, "bad xz filter flags", q)
end
psz, q = vli(b, q, he)
if not psz or q + psz > he then
return nil, Err.new(Err.CORRUPT, "bad xz filter properties", q)
end
local pr = buffer.create(psz)
buffer.copy(pr, 0, b, q, psz)
q += psz
table.insert(filters, { id = id, props = pr })
end
for k = q, he - 1 do
if readu8(b, k) ~= 0 then
return nil, Err.new(Err.CORRUPT, "nonzero xz block header padding", k)
end
end
local last = filters[nfilters]
if last.id ~= 0x21 or buffer.len(last.props) ~= 1 or readu8(last.props, 0) > 40 then
return nil, Err.new(Err.UNSUPPORTED, string.format("xz filter chain must end in LZMA2 (got 0x%x)", last.id), p)
end
for k = 1, nfilters - 1 do
local id = filters[k].id
if id ~= 0x03 and not BCJ[id] then
return nil, Err.new(Err.UNSUPPORTED, string.format("xz filter 0x%x is not supported", id), p)
end
end
-- data
local dstart = p + hsize
local ostart = st.op
local dend = if csz then dstart + csz else e
if dend > e then
return nil, Err.new(Err.TRUNCATED, "truncated xz block data", dstart)
end
local cend, derr = decodeLzma2(st, b, dstart, dend)
if not cend then
return nil, derr
end
if csz and cend ~= dend then
return nil, Err.new(Err.CORRUPT, "xz compressed size mismatch", dstart)
end
local un = st.op - ostart
if usz and un ~= usz then
return nil, Err.new(Err.CORRUPT, "xz uncompressed size mismatch", dstart)
end
for k = nfilters - 1, 1, -1 do
local ok, ferr = Lzma.filter(filters[k].id, st.out, ostart, un, filters[k].props)
if not ok then
return nil, ferr
end
end
local unpadded = hsize + (cend - dstart) + csize
local pe = cend
while (pe - p) % 4 ~= 0 do
if pe >= e then
return nil, Err.new(Err.TRUNCATED, "truncated xz block padding", pe)
end
if readu8(b, pe) ~= 0 then
return nil, Err.new(Err.CORRUPT, "nonzero xz block padding", pe)
end
pe += 1
end
if pe + csize > e then
return nil, Err.new(Err.TRUNCATED, "truncated xz check", pe)
end
if check == 1 then
if crc(st.out, ostart, un) ~= readu32(b, pe) then
return nil, Err.new(Err.CHECKSUM, "xz block CRC-32 mismatch", pe)
end
elseif check == 4 then
local hi, lo = Crc64.of(st.out, ostart, un)
if lo ~= readu32(b, pe) or hi ~= readu32(b, pe + 4) then
return nil, Err.new(Err.CHECKSUM, "xz block CRC-64 mismatch", pe)
end
end
table.insert(records, { unpadded, un })
p = pe + csize
end
-- index
local ip = p
local count, q = vli(b, p + 1, e)
if not count or count ~= #records then
return nil, Err.new(Err.CORRUPT, "xz index record count mismatch", p)
end
for i = 1, count do
local a, u
a, q = vli(b, q, e)
if not a then
return nil, Err.new(Err.TRUNCATED, "truncated xz index", q)
end
u, q = vli(b, q, e)
if not u then
return nil, Err.new(Err.TRUNCATED, "truncated xz index", q)
end
if a ~= records[i][1] or u ~= records[i][2] then
return nil, Err.new(Err.CORRUPT, "xz index does not match the blocks", q)
end
end
while (q - ip) % 4 ~= 0 do
if q >= e or readu8(b, q) ~= 0 then
return nil, Err.new(Err.CORRUPT, "bad xz index padding", q)
end
q += 1
end
if q + 4 > e then
return nil, Err.new(Err.TRUNCATED, "truncated xz index", q)
end
if crc(b, ip, q - ip) ~= readu32(b, q) then
return nil, Err.new(Err.CHECKSUM, "xz index CRC-32 mismatch", q)
end
q += 4
local isize = q - ip
-- footer
if q + 12 > e then
return nil, Err.new(Err.TRUNCATED, "truncated xz stream footer", q)
end
if crc(b, q + 4, 6) ~= readu32(b, q) then
return nil, Err.new(Err.CHECKSUM, "xz stream footer CRC-32 mismatch", q)
end
if (readu32(b, q + 4) + 1) * 4 ~= isize then
return nil, Err.new(Err.CORRUPT, "xz backward size mismatch", q + 4)
end
if readu8(b, q + 8) ~= 0 or readu8(b, q + 9) ~= check or buffer.readstring(b, q + 10, 2) ~= "YZ" then
return nil, Err.new(Err.CORRUPT, "bad xz stream footer", q + 8)
end
return q + 12, nil
end
-- xz(buf, offset?, length?, opts?) -> buffer, consumedEnd | nil, Err: every stream (and stream padding) in the range
function Lzma.xz(buf: buffer | string, offset: number?, length: number?, opts: Options?): (buffer?, any)
local b, o, l, aerr = args("Lzma.xz", buf, offset, length)
if not b then
return nil, aerr
end
local e = o + l
local st = Decode.new(l * 4, maxOf(opts))
local p = o
local nstreams = 0
while true do
local nxt, err = xzStream(st, b, p, e)
if not nxt then
return nil, err
end
nstreams += 1
p = nxt
-- stream padding: zero bytes in multiples of 4
local z = p
while z < e and readu8(b, z) == 0 do
z += 1
end
if z == e then
if (z - p) % 4 ~= 0 then
return nil, Err.new(Err.CORRUPT, "xz stream padding is not a multiple of 4", p)
end
p = z
break
end
if (z - p) % 4 ~= 0 then
return nil, Err.new(Err.CORRUPT, "xz stream padding is not a multiple of 4", p)
end
p = z
end
return Decode.finish(st), p
end
-- isXz(buf, offset?) -> true when the bytes start an xz stream
function Lzma.isXz(b: buffer, o: number?): boolean
local off = o or 0
return off + 6 <= buffer.len(b) and buffer.readstring(b, off, 6) == XZ_MAGIC
end
return Lzma
+115
View File
@@ -0,0 +1,115 @@
-- archive/7z tests: the contract and sniff; every archive 7-Zip wrote in tools/fixtures/7z.py (LZMA / LZMA2 / copy /
-- Deflate, solid and not, BCJ / ARM64 / ARM / PPC + SPARC / delta chains, plain and encoded headers) lists exactly the
-- source tree (names incl. UTF-16 surrogates, directories, empty files, mtimes) and reads every file back; unsupported
-- methods (BZip2, PPMd, BCJ2, AES) list but fail on read with Err.UNSUPPORTED naming the method; corrupt CRCs; F.load;
-- the fuzz no-throw pass.
local T = require("@tests/T")
local SevenZip = require("@formats/archive/7z")
local F = require("@formats")
local Bytes = require("@formats/core/Bytes")
local Err = require("@formats/core/Err")
local Fx = require("@tests/gen/7z")
local t = T.suite("7z")
t:eq(SevenZip.name, "7z", "name")
t:eq(SevenZip.category, "archive", "category")
t:check(SevenZip.caps.decode and not SevenZip.caps.encode, "caps")
local function decode(data: string, opts: any?): (any, any)
return SevenZip.decode(Bytes.reader(buffer.fromstring(data)), opts)
end
local want: { [string]: any } = {}
for _, f in Fx.files do
want[f.name] = f
end
local nfiles = 0
for _, c in Fx.cases do
t:eq(SevenZip.sniff(Bytes.reader(buffer.fromstring(c.data))), 1, c.name .. ": sniff")
local a, err = decode(c.data)
t:check(a, c.name .. ": " .. tostring(err))
local list = a:list()
if c.empty then
t:eq(#list, 0, c.name .. ": no entries")
continue
end
local seen = {}
for _, e in list do
local w = want[e.name]
t:check(w ~= nil, c.name .. ": unexpected entry " .. e.name)
seen[e.name] = true
t:eq(e.dir, w.dir, c.name .. ": " .. e.name .. ": dir")
t:eq(e.mtime, w.mtime, c.name .. ": " .. e.name .. ": mtime")
if not w.dir then
t:eq(e.size, #w.data, c.name .. ": " .. e.name .. ": size")
local b, rerr = a:read(e.name)
if c.unsupported and #w.data > 0 then
t:check(b == nil and rerr and rerr.code == Err.UNSUPPORTED and string.find(rerr.message, c.unsupported, 1, true) ~= nil,
c.name .. ": " .. e.name .. ": unsupported: " .. tostring(rerr))
else
t:check(b and buffer.tostring(b) == w.data, c.name .. ": " .. e.name .. ": data: " .. tostring(rerr))
nfiles += 1
end
end
end
for name in want do
t:check(seen[name], c.name .. ": missing " .. name)
end
end
t:note("%d archives, %d files read", #Fx.cases, nfiles)
-- corrupt data: a flipped byte in a stored file is a CRC error on read; a flipped header byte a header CRC error
do
local c
for _, x in Fx.cases do
if x.name == "copy" then
c = x
end
end
local s = c.data
local at = string.find(s, "deep\ndeep", 1, true) :: number
local bad = string.sub(s, 1, at - 1) .. "D" .. string.sub(s, at + 1)
local a = decode(bad)
t:check(a, "copy archive with a flipped data byte still lists")
local b, e = a:read("a/b/c/deep.txt")
t:check(b == nil and e and e.code == Err.CHECKSUM, "data CRC: " .. tostring(e))
local _, e2 = decode(string.sub(s, 1, #s - 3) .. "\0\0\0")
t:check(e2 and (e2.code == Err.CHECKSUM or e2.code == Err.CORRUPT), "header CRC: " .. tostring(e2))
local _, e3 = decode(string.sub(s, 1, 20))
t:check(e3 and e3.code == Err.TRUNCATED, "truncated: " .. tostring(e3))
local a4 = decode(bad, { checkCrc = false })
t:check(a4 and a4:read("a/b/c/deep.txt"), "checkCrc = false")
end
-- through the api
do
local c = Fx.cases[2]
local a, err = F.load(c.data)
t:check(a and a.format == "7z", "F.load: " .. tostring(err))
t:eq(F.detect(c.data), "7z", "F.detect")
local r = a:read("readme.txt")
t:check(r and buffer.tostring(r) == want["readme.txt"].data, "F.load read")
end
-- fuzz: decode + read every entry
do
local samples = {}
for _, c in Fx.cases do
if #c.data < 60000 then
table.insert(samples, c.data)
end
end
t:fuzz("decode", function(b: buffer)
local a = SevenZip.decode(Bytes.reader(b), { maxBytes = 2 ^ 21 })
if a then
for _, e in a:list() do
a:read(e.name)
end
end
return a
end, samples, { mutations = 12, garbage = 300 })
end
t:done()
+78
View File
@@ -0,0 +1,78 @@
-- archive/xz tests: the contract, sniffing (.xz magic, conservative .lzma), every xz / .lzma fixture of
-- tools/fixtures/lzma.py read as a one-entry archive (entry names from opts.name), F.load through the registry, errors,
-- and the fuzz no-throw pass.
local T = require("@tests/T")
local Xz = require("@formats/archive/xz")
local F = require("@formats")
local Bytes = require("@formats/core/Bytes")
local Err = require("@formats/core/Err")
local Fx = require("@tests/gen/lzma")
local t = T.suite("xz")
t:eq(Xz.name, "xz", "name")
t:eq(Xz.category, "archive", "category")
t:check(Xz.caps.decode and not Xz.caps.encode, "caps")
local function reader(s: string): Bytes.Reader
return Bytes.reader(buffer.fromstring(s))
end
local n = 0
for _, c in Fx.cases do
if c.kind == "xz" or c.kind == "alone" then
local want = Fx.corpora[c.corpus]
t:check(Xz.sniff(reader(c.data)) > 0, c.name .. ": sniff")
local a, err = Xz.decode(reader(c.data), { name = "dir/file.txt." .. (if c.kind == "xz" then "xz" else "lzma") })
t:check(a, c.name .. ": " .. tostring(err))
local list = a:list()
t:eq(#list, 1, c.name .. ": one entry")
t:eq(list[1].name, "file.txt", c.name .. ": entry name")
t:eq(list[1].size, #want, c.name .. ": size")
t:check(a.meta.stream == true, c.name .. ": meta.stream")
local b = a:read("file.txt")
t:check(b and buffer.tostring(b) == want, c.name .. ": data")
n += 1
end
end
t:note("%d xz / lzma files", n)
-- sniff: not xz
t:eq(Xz.sniff(reader("PK\3\4 hello")), 0, "zip is not xz")
t:eq(Xz.sniff(reader("")), 0, "empty")
t:eq(Xz.sniff(reader(string.rep("\0", 40))), 0, "zeros are not .lzma")
-- through the api
do
local c = Fx.cases[1]
for _, x in Fx.cases do
if x.name == "text/xz-6" then
c = x
end
end
local a, err = F.load(c.data, { name = "notes.txz" })
t:check(a and a.kind == "archive" and a.format == "xz", "F.load: " .. tostring(err))
t:eq(a:list()[1].name, "notes.tar", "txz -> tar entry name")
t:eq(F.detect(c.data), "xz", "F.detect")
local a2 = F.archive.load(c.data)
t:eq(a2:list()[1].name, "data", "unnamed entry")
local _, e2 = F.save(a2, nil, { format = "xz" })
t:check(e2 and e2.code == Err.UNSUPPORTED, "xz is read-only: " .. tostring(e2))
local _, e3 = F.load(string.sub(c.data, 1, 100), { format = "xz" })
t:check(e3 and e3.code == Err.TRUNCATED, "truncated: " .. tostring(e3))
end
-- fuzz
do
local samples = {}
for i, c in Fx.cases do
if (c.kind == "xz" or c.kind == "alone") and i % 5 == 0 and #c.data < 30000 then
table.insert(samples, c.data)
end
end
t:fuzz("decode", function(b: buffer)
return Xz.decode(Bytes.reader(b), { maxBytes = 2 ^ 20 })
end, samples, { mutations = 6, garbage = 400 })
end
t:done()
+142
View File
@@ -0,0 +1,142 @@
-- codecs/Lzma tests: every fixture (liblzma through Python's lzma module and the xz CLI: presets 0-9 and -e, lc / lp /
-- pb variants, raw LZMA1 / LZMA2, .lzma files, xz with every check type, BCJ and delta filters, multiple blocks,
-- multiple streams and stream padding) decodes to its corpus; consumed offsets; checksum / size / truncation errors;
-- maxBytes; the fuzz no-throw pass. Fixtures: tools/fixtures/lzma.py.
local T = require("@tests/T")
local Lzma = require("@formats/codecs/Lzma")
local Err = require("@formats/core/Err")
local Fx = require("@tests/gen/lzma")
local t = T.suite("lzma")
local function decode(c: any, b: buffer, opts: any?): (buffer?, any)
if c.kind == "raw" then
return Lzma.lzma(b, 0, nil, c.props, c.size, opts)
elseif c.kind == "raw2" then
return Lzma.lzma2(b, 0, nil, nil, nil, opts)
elseif c.kind == "alone" then
return Lzma.alone(b, 0, nil, opts)
end
return Lzma.xz(b, 0, nil, opts)
end
local nbytes = 0
for _, c in Fx.cases do
local want = Fx.corpora[c.corpus]
local b = buffer.fromstring(c.data)
local out, res = decode(c, b)
t:check(out ~= nil, c.name .. ": " .. tostring(res))
t:check(buffer.tostring(out :: buffer) == want, c.name .. ": output differs")
if c.kind ~= "raw" then
t:eq(res, #c.data, c.name .. ": consumed")
end
nbytes += #want
end
t:note("%d fixture streams, %.1f MB decoded", #Fx.cases, nbytes / 1e6)
-- at an offset inside a bigger buffer, with trailing bytes
do
for _, c in Fx.cases do
if c.kind == "xz" and c.name == "text/xz-6" then
local big = buffer.create(#c.data + 11)
buffer.fill(big, 0, 0xAB)
buffer.writestring(big, 3, c.data)
local out, res = Lzma.xz(big, 3, #c.data)
t:check(out and buffer.tostring(out) == Fx.corpora.text and res == 3 + #c.data, "xz at an offset")
end
end
end
-- errors
do
local xz, xzc
for _, c in Fx.cases do
if c.name == "text/xz-check-crc32" then
xz = c
elseif c.name == "text/xz-6" then
xzc = c
end
end
-- the check field: the last bytes before the index; flip a data bit near the end of the block instead
local b = buffer.fromstring(xzc.data)
local n = buffer.len(b)
-- footer magic
buffer.writeu8(b, n - 1, 0)
local _, e1 = Lzma.xz(b)
t:check(e1 and (e1.code == Err.CORRUPT or e1.code == Err.CHECKSUM), "bad footer: " .. tostring(e1))
-- the stream header CRC
local b2 = buffer.fromstring(xz.data)
buffer.writeu8(b2, 8, bit32.bxor(buffer.readu8(b2, 8), 1))
local _, e2 = Lzma.xz(b2)
t:check(e2 and e2.code == Err.CHECKSUM, "header crc: " .. tostring(e2))
-- the block check (CRC-32 / CRC-64): flip a byte of the check field (found from the index: the 4 / 8 bytes before
-- the index indicator, which follows the block padding)
for _, c in { xz, xzc } do
local b3 = buffer.fromstring(c.data)
local n3 = buffer.len(b3)
local backward = (buffer.readu32(b3, n3 - 8) + 1) * 4
local indexAt = n3 - 12 - backward
buffer.writeu8(b3, indexAt - 1, bit32.bxor(buffer.readu8(b3, indexAt - 1), 0x10))
local _, e3 = Lzma.xz(b3)
t:check(e3 and e3.code == Err.CHECKSUM, c.name .. ": block check: " .. tostring(e3))
end
-- truncations are TRUNCATED or CORRUPT, never a throw
local _, e4 = Lzma.xz(buffer.fromstring(string.sub(xzc.data, 1, #xzc.data // 2)))
t:check(e4 and e4.code == Err.TRUNCATED, "truncated xz: " .. tostring(e4))
-- maxBytes
local _, e5 = Lzma.xz(xzc.data, nil, nil, { maxBytes = 1000 })
t:check(e5 and e5.code == Err.LIMIT, "maxBytes: " .. tostring(e5))
local ok, r1, r2 = pcall(Lzma.xz, 5 :: any)
t:check(ok and r1 == nil and r2.code == Err.ARG, "a non-buffer argument returns Err.ARG")
local _, e6 = Lzma.lzma("\0\0\0\0\0", 0, nil, "\255")
t:check(e6 and e6.code == Err.CORRUPT, "bad props byte: " .. tostring(e6))
end
-- raw LZMA with the size known: decoding stops at the size even without an end marker
do
for _, c in Fx.cases do
if c.kind == "raw" and #Fx.corpora[c.corpus] > 1000 then
local want = Fx.corpora[c.corpus]
local out = Lzma.lzma(c.data, 0, nil, { lc = 3, lp = 0, pb = 2 }, nil)
if c.name == c.corpus .. "/raw-lc3-lp0-pb2" then
t:check(out and buffer.tostring(out) == want, c.name .. ": table props, end marker")
end
local part = Lzma.lzma(c.data, 0, nil, c.props, 500)
t:check(part and buffer.tostring(part) == string.sub(want, 1, 500), c.name .. ": a prefix by size")
end
end
end
-- fuzz
do
local samples = {}
for i, c in Fx.cases do
if i % 7 == 0 and #c.data > 16 and #c.data < 40000 then
table.insert(samples, c)
end
end
local xs, as, rs = {}, {}, {}
for _, c in samples do
if c.kind == "xz" then
table.insert(xs, c.data)
elseif c.kind == "alone" then
table.insert(as, c.data)
else
table.insert(rs, c.data)
end
end
t:fuzz("xz", function(b: buffer)
return Lzma.xz(b, 0, nil, { maxBytes = 1 * 2 ^ 20 })
end, xs, { mutations = 6, garbage = 300 })
t:fuzz("alone", function(b: buffer)
return Lzma.alone(b, 0, nil, { maxBytes = 1 * 2 ^ 20 })
end, as, { mutations = 6, garbage = 300 })
t:fuzz("lzma2", function(b: buffer)
return Lzma.lzma2(b, 0, nil, nil, nil, { maxBytes = 1 * 2 ^ 20 })
end, rs, { mutations = 4, garbage = 1000 })
t:fuzz("lzma", function(b: buffer)
return Lzma.lzma(b, 0, nil, "\93", nil, { maxBytes = 1 * 2 ^ 20 })
end, rs, { mutations = 2, garbage = 1000 })
end
t:done()
+102
View File
@@ -0,0 +1,102 @@
# 7z fixtures (tools/fixtures.py): a small tree (text, x86 machine code, runs, an empty file, empty and nested
# directories, UTF-16 names with accents and a surrogate pair) archived by 7-Zip 2x (nix _7zz) with many method chains:
# LZMA / LZMA2 / copy / Deflate, solid and non-solid, BCJ / ARM64 / delta filters, plain and compressed headers; plus
# archives whose methods are not supported (BZip2, PPMd, BCJ2, AES) and an empty archive.
# tests/gen/7z.luau { files = { { name, dir, data?, mtime } }, cases = { { name, data, unsupported? } } }
import os, random, subprocess, sys, tempfile
TOOL = "_7zz"
def tree(rng):
with open(os.path.realpath(sys.executable), "rb") as f:
code = f.read(60000)
base = os.path.dirname(os.__file__)
text = b""
for name in sorted(os.listdir(base)):
if name.endswith(".py"):
with open(os.path.join(base, name), "rb") as f:
text += f.read()
if len(text) > 50000:
break
return [
("readme.txt", text[:50000]),
("bin/code.bin", code),
("bin/runs.dat", b"ab" * 5000 + b"\0" * 9000 + bytes(range(256)) * 8),
("bin/random.dat", rng.randbytes(3000)),
("empty.txt", b""),
("emptydir/", None),
("a/b/c/deep.txt", b"deep\n" * 10),
("héllo wörld ☃.txt", "unicode ☃\n".encode()),
("\U0001d11e clef.txt", b"g clef\n"),
]
def generate(ctx):
rng = random.Random(77)
files = tree(rng)
mtime = 1600000000
out_files = []
cases = []
with tempfile.TemporaryDirectory() as d:
src = os.path.join(d, "src")
for name, data in files:
p = os.path.join(src, name)
if data is None:
os.makedirs(p, exist_ok=True)
os.utime(p, (mtime, mtime))
out_files.append({"name": name.rstrip("/"), "dir": True, "mtime": mtime})
else:
os.makedirs(os.path.dirname(p), exist_ok=True)
with open(p, "wb") as f:
f.write(data)
os.utime(p, (mtime + 60, mtime + 60))
out_files.append({"name": name, "dir": False, "data": data, "mtime": mtime + 60})
for sub in ("bin", "a", "a/b", "a/b/c"):
os.utime(os.path.join(src, sub), (mtime, mtime))
out_files.append({"name": sub, "dir": True, "mtime": mtime})
def make(name, args, unsupported=None):
arc = os.path.join(d, name + ".7z")
if os.path.exists(arc):
os.remove(arc)
subprocess.run(["nix", "shell", "nixpkgs#" + TOOL, "-c", "7zz", "a", "-bd", "-y", arc] + args + ["."],
cwd=src, capture_output=True, check=True)
with open(arc, "rb") as f:
c = {"name": name, "data": f.read()}
if unsupported:
c["unsupported"] = unsupported
cases.append(c)
make("lzma-nonsolid", ["-m0=LZMA", "-ms=off", "-mhc=off"])
make("lzma-solid", ["-m0=LZMA:d=1m", "-ms=on"])
make("lzma2-solid", ["-m0=LZMA2", "-ms=on"])
make("lzma2-mt-blocks", ["-m0=LZMA2:d=64k:c=20k", "-ms=on", "-mmt=4"])
make("lzma2-hc-off", ["-m0=LZMA2", "-mhc=off"])
make("copy", ["-m0=Copy", "-mhc=off"])
make("copy-hc", ["-m0=Copy"])
make("deflate", ["-m0=Deflate", "-ms=on"])
make("bcj-lzma", ["-m0=BCJ", "-m1=LZMA", "-ms=on"])
make("bcj-lzma2", ["-m0=BCJ", "-m1=LZMA2", "-ms=off"])
make("arm64-lzma2", ["-m0=ARM64", "-m1=LZMA2"])
make("arm-lzma2", ["-m0=ARM", "-m1=LZMA2"])
make("delta-lzma", ["-m0=Delta:4", "-m1=LZMA"])
make("ppc-sparc", ["-m0=PPC", "-m1=SPARC", "-m2=LZMA2"])
make("lzma-lc-lp", ["-m0=LZMA:lc=0:lp=2:pb=0", "-ms=e"])
make("auto", ["-mx=9"])
make("fast", ["-mx=1"])
make("bzip2", ["-m0=BZip2", "-mhc=off"], unsupported="bzip2")
make("ppmd", ["-m0=PPMd", "-mhc=off"], unsupported="ppmd")
make("bcj2", ["-m0=BCJ2", "-m1=LZMA", "-m2=LZMA", "-m3=LZMA", "-mb0s0:1", "-mb0s1:2", "-mb0s2:3", "-mhc=off"],
unsupported="bcj2")
make("aes", ["-m0=LZMA2", "-mhc=off", "-pSecret"], unsupported="aes")
# an empty archive
arc = os.path.join(d, "empty.7z")
empty = os.path.join(d, "emptysrc")
os.makedirs(empty)
subprocess.run(["nix", "shell", "nixpkgs#" + TOOL, "-c", "7zz", "a", "-bd", "-y", arc, "-x!*", "."],
cwd=empty, capture_output=True)
if os.path.exists(arc):
with open(arc, "rb") as f:
cases.append({"name": "empty", "data": f.read(), "empty": True})
ctx.emit("7z", {"files": out_files, "cases": cases})
+105
View File
@@ -0,0 +1,105 @@
# LZMA / LZMA2 / xz fixtures (tools/fixtures.py): deterministic corpora compressed by liblzma (Python's lzma module and
# the xz CLI): every preset and -e, lc / lp / pb variants, raw LZMA1 / LZMA2, .lzma files with and without the size
# and end marker, xz with every check type, BCJ (x86, PowerPC, ARM, ARM-Thumb, SPARC, ARM64) and delta filters,
# multi-block (--block-size), multi-stream and stream padding.
# tests/gen/lzma.luau { corpora = { [name] = bytes }, cases = { { name, kind, corpus, data, props?, dict?,
# size? } } } kind: "raw" (LZMA1), "raw2" (LZMA2), "alone", "xz"
# tests/gen/lzma_bench.luau { size, crc, xz, alone } (a ~4 MB corpus at -6)
import lzma, os, random, subprocess, sys, zlib
def text_corpus(limit):
base = os.path.dirname(os.__file__)
out = bytearray()
for name in sorted(os.listdir(base)):
if name.endswith(".py"):
with open(os.path.join(base, name), "rb") as f:
out += f.read()
if len(out) >= limit:
break
return bytes(out[:limit])
def binary_corpus(limit):
# machine code: a slice of the Python interpreter (x86-64 here; exercises the x86 BCJ filter)
with open(os.path.realpath(sys.executable), "rb") as f:
data = f.read()
if len(data) < limit:
lib = os.path.join(os.path.dirname(os.path.realpath(sys.executable)), "..", "lib")
for name in sorted(os.listdir(lib)):
p = os.path.join(lib, name)
if name.startswith("libpython") and os.path.isfile(p):
with open(p, "rb") as f:
data += f.read(limit)
break
return data[:limit]
def xz_cli(args, data):
return subprocess.run(["xz"] + args + ["-c"], input=data, capture_output=True, check=True).stdout
def generate(ctx):
rng = random.Random(7)
corpora = {
"empty": b"",
"one": b"a",
"text": text_corpus(150000),
"binary": binary_corpus(120000),
"random": rng.randbytes(20000),
"runs": b"abc" * 3000 + b"\0" * 30000 + bytes(range(256)) * 30 + b"z" * 300,
"words": b" ".join(rng.choice([b"lorem", b"ipsum", b"dolor", b"sit", b"amet", b"\xff\xfe", b"0123"]) for _ in range(20000)),
}
cases = []
def add(name, kind, corpus, data, **extra):
c = {"name": name, "kind": kind, "corpus": corpus, "data": data}
c.update(extra)
cases.append(c)
for cname, data in corpora.items():
small = cname in ("empty", "one", "random")
presets = [0, 6] if small else [0, 1, 3, 6, 9, 9 | lzma.PRESET_EXTREME]
for p in presets:
add("%s/xz-%d%s" % (cname, p & 15, "e" if p & lzma.PRESET_EXTREME else ""), "xz", cname,
lzma.compress(data, lzma.FORMAT_XZ, check=lzma.CHECK_CRC64, preset=p))
for chk, cn in ((lzma.CHECK_NONE, "none"), (lzma.CHECK_CRC32, "crc32"), (lzma.CHECK_SHA256, "sha256")):
add("%s/xz-check-%s" % (cname, cn), "xz", cname, lzma.compress(data, lzma.FORMAT_XZ, check=chk, preset=2))
# .lzma (alone): with a size (Python writes an end marker and no size; the CLI writes the same); raw streams
add("%s/alone" % cname, "alone", cname, lzma.compress(data, lzma.FORMAT_ALONE, preset=6))
for lc, lp, pb in ((3, 0, 2), (0, 2, 0), (4, 0, 4), (1, 3, 1), (0, 4, 3)):
f = [{"id": lzma.FILTER_LZMA1, "preset": 6, "lc": lc, "lp": lp, "pb": pb, "dict_size": 1 << 20}]
raw = lzma.compress(data, lzma.FORMAT_RAW, filters=f)
add("%s/raw-lc%d-lp%d-pb%d" % (cname, lc, lp, pb), "raw", cname, raw, props=bytes([(pb * 5 + lp) * 9 + lc]), size=len(data))
for lc, lp, pb in ((3, 0, 2), (0, 4, 4), (2, 2, 1)):
f = [{"id": lzma.FILTER_LZMA2, "preset": 6, "lc": lc, "lp": lp, "pb": pb}]
add("%s/raw2-lc%d-lp%d-pb%d" % (cname, lc, lp, pb), "raw2", cname, lzma.compress(data, lzma.FORMAT_RAW, filters=f))
if not small:
for fid, fname in ((lzma.FILTER_X86, "x86"), (lzma.FILTER_POWERPC, "ppc"), (lzma.FILTER_ARM, "arm"),
(lzma.FILTER_ARMTHUMB, "armthumb"), (lzma.FILTER_SPARC, "sparc")):
f = [{"id": fid}, {"id": lzma.FILTER_LZMA2, "preset": 3}]
add("%s/xz-%s" % (cname, fname), "xz", cname, lzma.compress(data, lzma.FORMAT_XZ, filters=f))
f = [{"id": lzma.FILTER_X86, "start_offset": 0x1000}, {"id": lzma.FILTER_LZMA2, "preset": 3}]
add("%s/xz-x86-start" % cname, "xz", cname, lzma.compress(data, lzma.FORMAT_XZ, filters=f))
for dist in (1, 4, 256):
f = [{"id": lzma.FILTER_DELTA, "dist": dist}, {"id": lzma.FILTER_LZMA2, "preset": 3}]
add("%s/xz-delta%d" % (cname, dist), "xz", cname, lzma.compress(data, lzma.FORMAT_XZ, filters=f))
add("%s/xz-cli-arm64" % cname, "xz", cname, xz_cli(["--arm64", "--lzma2=preset=3"], data))
add("%s/xz-cli-blocks" % cname, "xz", cname, xz_cli(["-6", "--block-size=20000"], data))
add("%s/xz-cli-x86-delta" % cname, "xz", cname, xz_cli(["--x86", "--delta=dist=2", "--lzma2=preset=1"], data))
add("%s/alone-cli" % cname, "alone", cname, xz_cli(["--format=lzma", "-3"], data))
# multi-stream + stream padding
corpora["multi"] = corpora["text"][:40000] + corpora["runs"] + b"" + corpora["one"]
multi = (lzma.compress(corpora["text"][:40000], lzma.FORMAT_XZ, preset=1) + b"\0" * 8 +
lzma.compress(corpora["runs"], lzma.FORMAT_XZ, check=lzma.CHECK_CRC32) +
lzma.compress(b"", lzma.FORMAT_XZ) + lzma.compress(b"a", lzma.FORMAT_XZ, check=lzma.CHECK_NONE) + b"\0" * 4)
add("multi/xz-streams", "xz", "multi", multi)
ctx.emit("lzma", {"corpora": corpora, "cases": cases})
# real text and machine code, little long-range repetition
bench = text_corpus(2_000_000) + binary_corpus(1_000_000)
bench = bench[:3_000_000]
ctx.emit("lzma_bench", {"size": len(bench), "crc": zlib.crc32(bench),
"xz": lzma.compress(bench, lzma.FORMAT_XZ, preset=6),
"alone": lzma.compress(bench, lzma.FORMAT_ALONE, preset=6)})