Files
rosetta/src/Formats/codecs/Lzma/init.luau
T

568 lines
19 KiB
Luau

--!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 Bytes = require("@formats/core/Bytes")
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 toBuffer = Bytes.toBuffer
local args = Bytes.span
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, nil
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, nil
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