ws-arch2-cab: codecs/compress/Lzx (CAB LZX: windows 2^15..2^21, verbatim / aligned / uncompressed blocks, delta-coded trees, R0..R2, E8 translation, 32 KB frames; written from the spec) + cab LZX folders, checked against cabextract on cabinets of a fixture LZX compressor (tools/fixtures/_lzx.py) and libmspack's samples; Deflate.mszip (generic MSZIP blocks: CK + deflate, dictionary carried across blocks; for cab and later model/x); cab bench lines

This commit is contained in:
4DBug committed 2026-10-31 15:46:28 -05:00
1 parent 825c45b03c
commit c54c8daff5
9 files changed
+990 -49

No files matched your search

+58 -17
View File
@@ -5,14 +5,17 @@
# is what cabextract extracts and lists (sizes, data CRCs, the DOS times as UTC); cabextract, gcab and 7z must extract
# our writer's cabinets to the same bytes.
# tests/gen/cab.luau { cases = { { name, data, entries = { { name, size, crc, mtime } } } }, ours = { ok, log },
# spanned = { { name, data } } }
# spanned = { { name, data } }, bad = { { name, data } } }
import calendar, importlib.util, os, re, struct, subprocess, time, zlib
_s = importlib.util.spec_from_file_location("_arch2", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_arch2.py"))
A = importlib.util.module_from_spec(_s)
_s.loader.exec_module(A)
_s = importlib.util.spec_from_file_location("_lzx", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_lzx.py"))
L = importlib.util.module_from_spec(_s)
_s.loader.exec_module(L)
INPUTS = ["tools/fixtures/_arch2.py"]
INPUTS = ["tools/fixtures/_arch2.py", "tools/fixtures/_lzx.py"]
ENV = dict(os.environ, TZ="UTC")
@@ -34,7 +37,7 @@ def dos(t):
def build(folders, reserve=None):
"""a cabinet: folders = [(typeCompress, [(name, bytes, attribs, mtime)], encode(blockdata, previous) -> payload)];
"""a cabinet: folders = [(typeCompress, [(name, bytes, attribs, mtime)], encode(stream) -> [(payload, size)])];
reserve = (header bytes, folder size, data size)"""
hres, fres, dres = reserve or (b"", 0, 0)
flags = 4 if reserve else 0
@@ -50,13 +53,7 @@ def build(folders, reserve=None):
files += struct.pack("<IIHHHH", len(data), off, fi, d, t, attr) + name + b"\0"
off += len(data)
stream += data
out = []
prev = b""
for s in range(0, len(stream), 32768):
chunk = stream[s:s + 32768]
out.append((enc(chunk, prev), len(chunk)))
prev = chunk
blocks.append(out)
blocks.append(enc(stream))
coff = head + len(folders) * (8 + fres)
dat = coff + len(files)
folder_tab = b""
@@ -73,13 +70,33 @@ def build(folders, reserve=None):
return hdr + folder_tab + files + data
def store(chunk, prev):
return chunk
def chunks(stream):
return [stream[s:s + 32768] for s in range(0, len(stream), 32768)]
def mszip_dict(chunk, prev):
c = zlib.compressobj(9, zlib.DEFLATED, -15, zdict=prev) if prev else zlib.compressobj(9, zlib.DEFLATED, -15)
return b"CK" + c.compress(chunk) + c.flush()
def store(stream):
return [(c, len(c)) for c in chunks(stream)]
def mszip_dict(stream):
out, prev = [], b""
for chunk in chunks(stream):
c = zlib.compressobj(9, zlib.DEFLATED, -15, zdict=prev) if prev else zlib.compressobj(9, zlib.DEFLATED, -15)
out.append((b"CK" + c.compress(chunk) + c.flush(), len(chunk)))
prev = chunk
return out
def lzx(wbits, e8size=0, seed=1, plan=None):
def enc(stream):
data, frames = L.compress(stream, wbits, e8size, seed, plan)
out, p = [], 0
for i, n in enumerate(frames):
out.append((data[p:p + n], min(32768, len(stream) - i * 32768)))
p += n
assert p == len(data)
return out
return enc
LIST = re.compile(r"^\s*(\d+) \| (\d\d)\.(\d\d)\.(\d{4}) (\d\d):(\d\d):(\d\d) \| (.*)$")
@@ -147,16 +164,40 @@ def generate(ctx):
open(p, "wb").write(c)
A.tool(["cabextract"], ["cabextract", "-t", p]) # checksums and data as cabextract reads them
add(("mszip with dictionary", "two folders, reserve, utf-8")[i], p)
# LZX (our fixture compressor, checked by cabextract): windows 2^15 .. 2^21, the three block types, E8
x86 = bytearray(rng.randbytes(90000))
for i in range(0, len(x86) - 5, 23):
x86[i] = 0xE8
x86 = bytes(x86) + text[:40000]
lzx_cases = [
("lzx 2^15 text", 15, 0, [(b"t.txt", text[:100000])], None),
("lzx 2^16 mixed", 16, 0, [(b"a.txt", text), (b"b.bin", rand[:30000]), (b"c.txt", text[:5000])], None),
("lzx 2^17 types", 17, 0, [(b"m.bin", big)], [(1, 40000), (2, 30001), (3, 7777), (2, 50000), (3, 4), (1, len(big) - 127782)]),
("lzx 2^21 e8", 21, 12000000, [(b"x86.exe", x86), (b"tail.txt", text[:3000])], None),
("lzx 2^18 e8 small", 18, 70000, [(b"s.bin", x86[:20000])], [(2, 20000)]),
]
for i, (label, wb, e8size, fl, plan) in enumerate(lzx_cases):
c = build([(3 | (wb << 8), [(n, d, 0x20, 1700000000) for n, d in fl], lzx(wb, e8size, 100 + i, plan))])
p = os.path.join(tmp, "lzx%d.cab" % i)
open(p, "wb").write(c)
ents = reference(p, tmp, "lzx%d" % i)
want = {n.decode(): zlib.crc32(d) for n, d in fl}
if {e["name"]: e["crc"] for e in ents} != want:
raise RuntimeError("cabextract does not extract the fixture LZX cabinet " + label)
cases.append({"name": label, "data": c, "entries": ents})
# the libmspack test cabinets
ms = os.path.join(tmp, "ms")
os.makedirs(ms)
subprocess.run(["tar", "xzf", mspack_cabs(), "-C", ms, "--wildcards", "*/test/test_files/cabd/*.cab"], check=True)
cabd = os.path.join(ms, os.listdir(ms)[0], "test", "test_files", "cabd")
for n in ("normal_2files_1folder", "normal_255c_filename", "reserve_---", "reserve_--D",
for n in ("normal_2files_1folder", "normal_2files_2folders", "normal_255c_filename", "reserve_---", "reserve_--D",
"reserve_-F-", "reserve_-FD", "reserve_H--", "reserve_H-D", "reserve_HF-", "reserve_HFD"):
add("libmspack " + n, os.path.join(cabd, n + ".cab"))
spanned = [{"name": n, "data": open(os.path.join(cabd, n + ".cab"), "rb").read()}
for n in ("multi_basic_pt1", "multi_basic_pt2", "multi_basic_pt3")]
# broken cabinets cabextract fails on (crafted bad trees, loops, short headers / strings)
bad = [{"name": n, "data": open(os.path.join(cabd, n), "rb").read()} for n in sorted(os.listdir(cabd))
if n.endswith(".cab") and (n.startswith(("partial_", "bad_", "lzx-")) or (n.startswith("cve-") and "9732" not in n))]
# our writer, extracted by the reference tools
log, ok = [], True
for opts in ("compression=mszip", "compression=none", "compression=mszip,level=1"):
@@ -174,6 +215,6 @@ def generate(ctx):
good = r.returncode == 0 and got == want
ok = ok and good
log.append("%s %s: %s" % (opts, tool, "ok" if good else "FAILED %r" % (got,)))
ctx.emit("cab", {"cases": cases, "ours": {"ok": ok, "log": "; ".join(log)}, "spanned": spanned})
ctx.emit("cab", {"cases": cases, "ours": {"ok": ok, "log": "; ".join(log)}, "spanned": spanned, "bad": bad})
finally:
A.rmtree(tmp)