merge ws/arch2-unix (cpio, ar/deb, rpm, z, iso, lz4; containers/Cpio, Iso9660; codecs UnixCompress, Xxh32, Lz4 from ws/roblox)

This commit is contained in:
4DBug committed 2026-10-31 15:22:07 -05:00
commit 242e38c4fe
36 files changed
+5171 -7

No files matched your search

+11
View File
@@ -53,24 +53,31 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
| font | pcf | .pcf | yes | - | bitmap: true | `tests/font/pcf.luau` |
| font | psf | .psf .psfu | yes | yes | bitmap: true, variants: "psf1", "psf2" | `tests/font/psf.luau` |
| font | ttf | .ttf .otf .ttc .otc | yes | - | outlines: "truetype", "cff", collection: true, kerning: true | `tests/font/ttf.luau` |
| font | type1 | .pfb .pfa .t1 | yes | - | outlines: "type1", variants: "pfb", "pfa" | **missing** |
| font | woff | .woff | yes | - | outlines: "truetype", "cff" | `tests/font/woff.luau` |
| font | woff2 | .woff2 | yes | - | outlines: "truetype", "cff", transforms: "glyf", "loca", "hmtx" | `tests/font/woff2.luau` |
| archive | 7z | .7z | yes | - | methods: "copy", "lzma", "lzma2", "deflate", "bcj", "delta", encrypted: false | `tests/archive/7z.luau` |
| archive | adf | .adf | yes | - | variants: "ofs", "ffs" | `tests/archive/adf.luau` |
| archive | applesingle | .as .applesingle .appledouble | yes | yes | forks: true, variants: "applesingle", "appledouble" | `tests/archive/applesingle.luau` |
| archive | ar | .a .ar .deb .lib | yes | yes | variants: "gnu", "bsd", deb: true | `tests/archive/ar.luau` |
| archive | arj | .arj | yes | - | methods: "store", "arj1", "arj2", "arj3", "arj4" | `tests/archive/arj.luau` |
| archive | binhex | .hqx .hcx | yes | yes | forks: true | `tests/archive/binhex.luau` |
| archive | br | .br | yes | - | stream: true | `tests/archive/br.luau` |
| archive | bz2 | .bz2 .tbz2 .tbz | yes | - | stream: true | `tests/archive/bz2.luau` |
| archive | cpio | .cpio | yes | yes | variants: "newc", "crc", "odc", "bin" | `tests/archive/cpio.luau` |
| archive | d64 | .d64 .d71 .d81 | yes | yes | variants: "d64", "d71", "d81" | `tests/archive/d64.luau` |
| archive | fat | .img .ima .vfd .flp .fat | yes | yes | variants: "fat12", "fat16", "fat32" | `tests/archive/fat.luau` |
| archive | gzip | .gz .tgz .gzip | yes | yes | stream: true | `tests/archive/gzip.luau` |
| archive | iso | .iso | yes | - | extensions: "joliet", "rockridge", "eltorito" | `tests/archive/iso.luau` |
| archive | lha | .lzh .lha .lzs | yes | yes | methods: "lh0", "lh1", "lh4", "lh5", "lh6", "lh7", "lhx", "lzs", "lz5", "lz4", "lhd" | `tests/archive/lha.luau` |
| archive | lz4 | .lz4 .tlz4 | yes | yes | stream: true, legacy: true | `tests/archive/lz4.luau` |
| archive | macbinary | .bin .macbin | yes | yes | forks: true, variants: "I", "II", "III" | `tests/archive/macbinary.luau` |
| archive | rpm | .rpm | yes | - | compressors: "gzip", "bzip2", "xz", "lzma", "zstd" | `tests/archive/rpm.luau` |
| archive | tar | .tar | yes | yes | variants: "ustar", "pax", "gnu" | `tests/archive/tar.luau` |
| archive | uu | .uu .uue .xxe .b64 | yes | yes | variants: "uu", "xx", "base64" | `tests/archive/uu.luau` |
| archive | xz | .xz .txz .lzma | yes | - | stream: true, filters: "lzma2", "lzma", "delta", "x86", "powerpc", "arm", "armthumb", "sparc", "arm64" | `tests/archive/xz.luau` |
| archive | yenc | .yenc .ync | yes | yes | multipart: true | `tests/archive/yenc.luau` |
| archive | z | .z .taz .tz | yes | yes | stream: true, bits: 9, 16 | `tests/archive/z.luau` |
| archive | zip | .zip .wsz | yes | yes | methods: "store", "deflate", zip64: true | `tests/archive/zip.luau` |
| archive | zoo | .zoo | yes | - | methods: "store", "lzw", "lzh" | `tests/archive/zoo.luau` |
| archive | zst | .zst .tzst | yes | - | stream: true | `tests/archive/zst.luau` |
@@ -120,10 +127,13 @@ Codecs (layer 3, shared by formats; not loadable on their own), by domain:
- codecs/compress/Brotli: Brotli (RFC 7932) decompression. A codec (layer 3): archive/br and font/woff2 build on it. Written
- codecs/compress/Bzip2: bzip2 decompressor (BWT + MTF + Huffman, the .bz2 stream format of bzip2 0.9.5 / 1.0.x). A codec
- codecs/compress/Deflate: DEFLATE (RFC 1951) decoder and compressor, with the zlib (RFC 1950) and gzip (RFC 1952) wrappers.
- codecs/compress/Lz4: the LZ4 block format (lz4 doc/lz4_Block_format.md): decode and a greedy hash-chain-free encoder
- codecs/compress/Lzh: the LHA family of LZSS decoders, used by archive/lha, archive/arj and archive/zoo:
- codecs/compress/Lzma: LZMA and LZMA2 decoders, the .lzma ("LZMA alone") wrapper and the .xz container. A codec (layer 3):
- codecs/compress/Lzw: LZW decoder and encoder in the two variants file formats use. A codec (layer 1): image/gif and
- codecs/compress/PackBits: the Apple PackBits run-length code (TIFF compression 32773, PSD / PSB RLE channels, IFF
- codecs/compress/UnixCompress: the LZW of Unix compress (.Z files: magic 1F 9D, a flags byte with the maximum code
- codecs/compress/Xxh32: XXH32 of a buffer range (any seed), for the LZ4 frame format's header, block and content
- codecs/compress/Zstd: Zstandard decompression (RFC 8878). A codec (layer 3): archive/zst and anything else carrying zstd
- **entropy**
- codecs/entropy/Huffman: canonical Huffman codes (RFC 1951 3.2.2 / JPEG Annex C order) for decoders and encoders.
@@ -131,6 +141,7 @@ Codecs (layer 3, shared by formats; not loadable on their own), by domain:
- **font**
- codecs/font/Bitmap: the standard Font value for bitmap fonts (BDF, PCF, PSF, Windows FON / FNT): a Types.BitmapStrike
- codecs/font/Cff: Compact Font Format (Adobe TN #5176) and Type 2 charstrings (TN #5177): the outlines of OpenType fonts
- codecs/font/GlyphNames: PostScript glyph names -> Unicode for fonts that name their glyphs (Type 1, CFF without a
- codecs/font/TrueType: the sfnt font container (TrueType .ttf, OpenType .otf with CFF outlines, collections .ttc) parsed
- **image**
- codecs/image/Blend: layer compositing on rgba8 buffers (straight alpha): source-over with the separable and non-separable
+99 -6
View File
@@ -25,7 +25,7 @@ assert(F.archive.load(out):read("notes/todo.txt"))
| Field / method | Type | Meaning |
|---|---|---|
| `kind` | `"archive"` | |
| `format` | string | `"zip"`, `"tar"`, `"7z"`, `"gzip"`, `"xz"`, `"zst"`, `"bz2"`, `"br"` |
| `format` | string | `"zip"`, `"tar"`, `"7z"`, `"gzip"`, `"xz"`, `"zst"`, `"bz2"`, `"br"`, `"cpio"`, `"ar"`, `"rpm"`, `"z"`, `"lz4"`, `"iso"` |
| `list(self)` | `{ ArchiveEntry }` | the entries in archive order (directories included) |
| `read(self, name)` | `buffer?, Err?` | a fresh copy of the entry's bytes, decompressed (lazily, on each call) |
| `add(self, name, data, opts?)` | | add or replace an entry; `data` is a buffer or a string |
@@ -43,7 +43,7 @@ assert(F.archive.load(out):read("notes/todo.txt"))
| `mtime` | number? | modification time, Unix seconds (UTC) |
| `dir` | boolean | a directory entry |
| `crc32`, `comment` | number?, string? | zip only |
| `mode`, `uid`, `gid`, `uname`, `gname`, `type`, `link` | | tar only (`mode` is the Unix permission bits, e.g. `420` = `0644`) |
| `mode`, `uid`, `gid`, `uname`, `gname`, `type`, `link` | | tar, cpio, ar, rpm, iso (`mode` is the Unix permission bits, e.g. `420` = `0644`) |
## Load
@@ -85,11 +85,12 @@ Options for loading:
| Option | Formats | Meaning |
|---|---|---|
| `unwrap` | gzip, xz, zst, bz2, br | `false`: do not open an archive inside a single-stream file (also off when `format` is given) |
| `unwrap` | gzip, xz, zst, bz2, br, z, lz4, deb | `false`: do not open an archive inside a single-stream file or a `.deb` (also off when `format` is given) |
| `name` | single-stream | the file name, used to name the entry (set for you when loading a path) |
| `verify` | zip | check each entry's CRC-32 on read (default `true`) |
| `maxEntries` | tar | refuse more entries (default 1e6) |
| `maxBytes` | bz2, br | refuse a bigger decompressed size |
| `verify` | zip, lz4, cpio | check each entry's CRC-32 on read (zip), the XXH32 checksums (lz4), the crc sums (cpio) (default `true`) |
| `maxEntries` | tar, cpio, ar, rpm, iso | refuse more entries (default 1e6) |
| `prefer` | iso | the name set: `"rockridge"`, `"joliet"` or `"iso9660"` (default: the richest present) |
| `maxBytes` | bz2, br, rpm, z, lz4 | refuse a bigger decompressed size |
A path works on hosts with a file system:
@@ -185,6 +186,92 @@ local gzipped = assert(F.save("some text", nil, { format = "gzip", name = "note.
assert(F.archive.load(gzipped, { unwrap = false }):list()[1].name == "note.txt")
```
## Unix, package and disc archives
### cpio
GNU cpio's and bsdtar's newc, crc, odc and old binary archives read; newc, crc and odc write (`variant`, default the
source's). Entries carry the Unix fields: `type` (tar letters: `"0"` file, `"5"` directory, `"2"` symlink, ...),
`mode`, `uid`, `gid`, `nlink`, `ino`, device numbers, `link`, and `hardlink` (every link of a hard-linked file reads
its data).
```luau
local cpio = assert(F.archive.load(cpioBytes))
local by = {}
for _, e in cpio:list() do
by[e.name] = e
end
assert(by["bin"].dir and by["bin/run.sh"].mode == 493) -- 493 = 0755
assert(by["run"].type == "2" and by["run"].link == "bin/run.sh") -- a symlink
local odc = assert(cpio:write({ variant = "odc" }))
assert(F.archive.load(odc).meta.source.variant == "odc")
```
### ar and .deb
Unix `ar` archives (GNU / System V long names and symbol tables, BSD `#1/` names) read and write (`variant = "gnu"`
or `"bsd"`); symbols land in `meta.symbols`. A `.deb` loads as its `data.tar.*` (any compression), with the ar
archive in `meta.outer` and the control file's fields in `meta.outer.meta.control`:
```luau
local deb = assert(F.archive.load(debBytes))
assert(deb.format == "tar" and deb.meta.container == "ar")
assert(deb:read("./usr/bin/hello"))
local control = deb.meta.outer.meta.control
assert(control.Package == "hello" and control.Version == "1.0-1")
local ar = assert(F.archive.load(debBytes, { unwrap = false })) -- the ar itself
assert(ar:list()[1].name == "debian-binary" and ar.meta.payload == "data.tar.xz")
```
### rpm
RPM packages list from their header (no decompression); the payload (gzip, bzip2, xz, lzma or zstd) is decompressed
on the first `read`. The header fields are in `meta.rpm` (`name`, `version`, `release`, `arch`, `summary`, ... and
every tag by number in `meta.rpm.tags`). Read only.
```luau
local rpm = assert(F.archive.load(rpmBytes))
assert(rpm.meta.rpm.name == "hello" and rpm.meta.rpm.version == "1.0" and rpm.meta.rpm.arch == "noarch")
assert(rpm:list()[1].name == "usr/bin/hello" and rpm:list()[1].mode == 493)
local hello = buffer.tostring(assert(rpm:read("usr/bin/hello")))
assert(string.find(hello, "echo hello", 1, true))
```
### .Z and .lz4
Unix `compress` (`.Z`, `.taz`) and LZ4 frame (`.lz4`) files are single-stream archives like gzip: a `.tar.Z` or
`.tar.lz4` loads as the tar. Both write: `.Z` byte for byte as ncompress (`maxBits` 9..16), `.lz4` as one frame of
independent blocks (`blockSize`, `blockChecksum`, `contentChecksum`, `contentSize`).
```luau
local tar = assert(F.archive.load(tarZBytes))
assert(tar.format == "tar" and tar.meta.compression == "z")
local lz = assert(F.archive.load(lz4Bytes, { name = "notes.txt.lz4" }))
assert(lz.meta.stream and lz:list()[1].name == "notes.txt")
local z = assert(F.save(tar, nil, { format = "z" })) -- a tar inside
assert(F.archive.load(z).format == "tar")
local l4 = assert(F.save("some text", nil, { format = "lz4", blockChecksum = true }))
assert(buffer.tostring(F.archive.load(l4):read("data")) == "some text")
```
### ISO images
ISO 9660 images read with Rock Ridge names, modes and symlinks when present, else Joliet's Unicode names, else the
plain ISO names (`prefer = "joliet"` / `"iso9660"` picks another set). `meta.iso` has the volume facts and
`meta.boot` an El Torito boot catalog. Read only.
```luau
local iso = assert(F.archive.load(isoBytes))
assert(iso.meta.iso.volumeId == "DOCS" and iso.meta.iso.rockRidge and iso.meta.iso.joliet)
assert(iso.meta.boot and iso.meta.boot.bootable)
local by = {}
for _, e in iso:list() do
by[e.name] = e
end
assert(by["bin"].dir and by["bin/run.sh"].mode == 493 and by["run"].link == "bin/run.sh")
assert(F.archive.load(isoBytes, { prefer = "joliet" }).meta.iso.tree == "joliet")
```
## Formats
| Format | Read | Write | Notes |
@@ -197,6 +284,12 @@ assert(F.archive.load(gzipped, { unwrap = false }):list()[1].name == "note.txt")
| zstd (`.zst`, `.tzst`) | yes | - | single stream; no dictionaries |
| bzip2 (`.bz2`, `.tbz2`) | yes | - | single stream |
| Brotli (`.br`) | yes | - | single stream; no magic number, so pass a `.br` name or `format = "br"` |
| cpio (`.cpio`) | yes | yes | newc, crc, odc, old binary (read); hard links, symlinks, devices |
| ar (`.a`, `.ar`, `.deb`) | yes | yes | GNU / BSD names, symbol tables; a `.deb` loads as its data tar |
| rpm (`.rpm`) | yes | - | gzip / bzip2 / xz / lzma / zstd payloads |
| compress (`.Z`, `.taz`) | yes | yes | single stream; 9..16-bit LZW |
| LZ4 (`.lz4`) | yes | yes | single stream; frames, legacy frames, XXH32 checks; no dictionaries |
| ISO 9660 (`.iso`) | yes | - | Joliet, Rock Ridge, El Torito, multi-extent; no UDF |
Full capability list: [FORMATS.md](../FORMATS.md).
+1
View File
@@ -41,6 +41,7 @@
| `src/Formats/codecs/compress/Lzh/` (lh1 adaptive Huffman, lh4..lh7 block decoding, lzs / lz5) | lhasa 0.6.0 (Simon Howard) | ISC: [lhasa-LICENSE.txt](lhasa-LICENSE.txt) |
| `tests/gen/lha` (read from nixpkgs#lhasa.src at fixture time, not committed) | lhasa 0.6.0 test archives | ISC (lhasa) |
| `src/Formats/codecs/font/GlyphNames.luau` (glyph name -> Unicode table, StandardEncoding) | Adobe Glyph List For New Fonts 1.7 (via fontTools) | BSD-3-Clause: [agl-LICENSE.txt](agl-LICENSE.txt) |
| `src/Formats/codecs/compress/UnixCompress.luau` (the .Z format and the encoder's ratio check / CLEAR rule, read from compress.c; the code is new) | ncompress 5.0 | public domain (The Unlicense): [ncompress-UNLICENSE.txt](ncompress-UNLICENSE.txt) |
Ports of third-party code (minimp3, stb_vorbis, libopus, ...) add a row here and their upstream licence text in this
folder (see docs/STYLE.md, "Absorbing an existing repo").
+24
View File
@@ -0,0 +1,24 @@
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <http://unlicense.org/>
+84
View File
@@ -590,6 +590,18 @@ local list: { Entry } = {
return require("@formats/font/ttf")
end,
},
{
name = "type1",
category = "font",
path = "font/type1",
extensions = { "pfb", "pfa", "t1" },
mime = { "application/x-font-type1" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Raster", "codecs/font/GlyphNames" },
caps = { decode = true, encode = false, outlines = { "type1" }, variants = { "pfb", "pfa" } },
load = function()
return require("@formats/font/type1")
end,
},
{
name = "woff",
category = "font",
@@ -650,6 +662,18 @@ local list: { Entry } = {
return require("@formats/archive/applesingle")
end,
},
{
name = "ar",
category = "archive",
path = "archive/ar",
extensions = { "a", "ar", "deb", "lib" },
mime = { "application/x-archive", "application/vnd.debian.binary-package" },
deps = { "core/Err", "core/Bytes", "codecs/compress/Deflate", "codecs/compress/Lzma", "codecs/compress/Zstd", "codecs/compress/Bzip2", "containers/Archive", "containers/Tar" },
caps = { decode = true, encode = true, variants = { "gnu", "bsd" }, deb = true },
load = function()
return require("@formats/archive/ar")
end,
},
{
name = "arj",
category = "archive",
@@ -698,6 +722,18 @@ local list: { Entry } = {
return require("@formats/archive/bz2")
end,
},
{
name = "cpio",
category = "archive",
path = "archive/cpio",
extensions = { "cpio" },
mime = { "application/x-cpio" },
deps = { "core/Err", "core/Bytes", "containers/Archive", "containers/Cpio" },
caps = { decode = true, encode = true, variants = { "newc", "crc", "odc", "bin" } },
load = function()
return require("@formats/archive/cpio")
end,
},
{
name = "d64",
category = "archive",
@@ -734,6 +770,18 @@ local list: { Entry } = {
return require("@formats/archive/gzip")
end,
},
{
name = "iso",
category = "archive",
path = "archive/iso",
extensions = { "iso" },
mime = { "application/x-iso9660-image" },
deps = { "core/Err", "core/Bytes", "containers/Archive", "containers/Iso9660" },
caps = { decode = true, encode = false, extensions = { "joliet", "rockridge", "eltorito" } },
load = function()
return require("@formats/archive/iso")
end,
},
{
name = "lha",
category = "archive",
@@ -746,6 +794,18 @@ local list: { Entry } = {
return require("@formats/archive/lha")
end,
},
{
name = "lz4",
category = "archive",
path = "archive/lz4",
extensions = { "lz4", "tlz4" },
mime = { "application/x-lz4" },
deps = { "core/Err", "core/Bytes", "codecs/compress/Lz4", "codecs/compress/Xxh32", "containers/Archive" },
caps = { decode = true, encode = true, stream = true, legacy = true },
load = function()
return require("@formats/archive/lz4")
end,
},
{
name = "macbinary",
category = "archive",
@@ -758,6 +818,18 @@ local list: { Entry } = {
return require("@formats/archive/macbinary")
end,
},
{
name = "rpm",
category = "archive",
path = "archive/rpm",
extensions = { "rpm" },
mime = { "application/x-rpm" },
deps = { "core/Err", "core/Bytes", "codecs/compress/Deflate", "codecs/compress/Lzma", "codecs/compress/Zstd", "codecs/compress/Bzip2", "containers/Archive", "containers/Cpio" },
caps = { decode = true, encode = false, compressors = { "gzip", "bzip2", "xz", "lzma", "zstd" } },
load = function()
return require("@formats/archive/rpm")
end,
},
{
name = "tar",
category = "archive",
@@ -806,6 +878,18 @@ local list: { Entry } = {
return require("@formats/archive/yenc")
end,
},
{
name = "z",
category = "archive",
path = "archive/z",
extensions = { "z", "taz", "tz" },
mime = { "application/x-compress" },
deps = { "core/Err", "core/Bytes", "codecs/compress/UnixCompress", "containers/Archive" },
caps = { decode = true, encode = true, stream = true, bits = { 9, 16 } },
load = function()
return require("@formats/archive/z")
end,
},
{
name = "zip",
category = "archive",
+410
View File
@@ -0,0 +1,410 @@
--!strict
-- archive/ar: Unix ar archives ("!<arch>\n"): System V / GNU (names ending in "/", the "//" long-name table, the "/"
-- and "/SYM64/" symbol tables) and BSD (inline "#1/<len>" names, the "__.SYMDEF" symbol table), read into the standard
-- Archive value and written (opts.variant "gnu", the default, or "bsd") from any Archive value. Symbol tables are not
-- entries: their symbols land in meta.symbols ({ name, member }). Debian packages (.deb) are ar archives: their
-- meta.payload names the data.tar.* member (the api loads a .deb as that data tar, meta.outer = this archive) and
-- meta.control holds the fields of the control file in control.tar / .gz / .xz / .zst / .bz2 / .lzma (decompressed
-- with codecs/compress/*, read with containers/Tar). Written from the ar(5) manual pages (GNU binutils, FreeBSD) and
-- deb(5) (dpkg); no code ported. Not supported: thin archives ("!<thin>"), writing symbol tables (a re-written
-- library needs ranlib), writing .deb control data (any entries write as a plain ar).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Deflate = require("@formats/codecs/compress/Deflate")
local Lzma = require("@formats/codecs/compress/Lzma")
local Zstd = require("@formats/codecs/compress/Zstd")
local Bzip2 = require("@formats/codecs/compress/Bzip2")
local Archive = require("@formats/containers/Archive")
local Tar = require("@formats/containers/Tar")
-- ------------------------------------------------------------------------------------------------ contract
local Ar = {
name = "ar",
category = "archive",
extensions = { "a", "ar", "deb", "lib" },
mime = { "application/x-archive", "application/vnd.debian.binary-package" },
deps = { "core/Err", "core/Bytes", "codecs/compress/Deflate", "codecs/compress/Lzma", "codecs/compress/Zstd", "codecs/compress/Bzip2", "containers/Archive", "containers/Tar" },
caps = { decode = true, encode = true, variants = { "gnu", "bsd" }, deb = true },
}
export type DecodeOptions = {
maxEntries: number?, -- default 1e6
maxBytes: number?, -- .deb: the largest control.tar to decompress (default 2^26)
}
export type EncodeOptions = {
variant: ("gnu" | "bsd")?, -- default: the source archive's ("bsd" for a .deb: plain names), else "gnu"
}
-- ------------------------------------------------------------------------------------------------ constants
local MAGIC = "!<arch>\n"
local HEADER = 60
-- ------------------------------------------------------------------------------------------------ sniff
function Ar.sniff(r: Bytes.Reader): number
if r:peek(8) == MAGIC then
return if r:peek(13, 68) == "debian-binary" then 1 else 0.9
end
return if r:peek(8) == "!<thin>\n" then 0.5 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
local function lazy(b: buffer, at: number, n: number): () -> (buffer?, Err.Err?)
return function(): (buffer?, Err.Err?)
local out = buffer.create(n)
buffer.copy(out, 0, b, at, n)
return out, nil
end
end
local function decimal(s: string): number?
local d = string.match(s, "^%s*(%d+)%s*$")
return if d then tonumber(d) else (if string.find(s, "^%s*$") then 0 else nil)
end
-- the System V symbol table: a big-endian count, the member offsets, then the NUL-terminated names
local function sysvSymbols(b: buffer, o: number, n: number, wide: boolean): { { name: string, offset: number } }
local out = {}
local w = if wide then 8 else 4
if n < w then
return out
end
local count = if wide then bit32.byteswap(buffer.readu32(b, o + 4)) else bit32.byteswap(buffer.readu32(b, o))
if count * w + w > n then
return out
end
local s = o + w + count * w
local e = o + n
for i = 0, count - 1 do
local off = bit32.byteswap(buffer.readu32(b, o + w + i * w + (w - 4)))
local q = s
while q < e and buffer.readu8(b, q) ~= 0 do
q += 1
end
table.insert(out, { name = buffer.readstring(b, s, q - s), offset = off })
s = q + 1
if s > e then
break
end
end
return out
end
-- the BSD __.SYMDEF table: a byte count of { name index, member offset } u32 pairs, the string table size, the strings
local function bsdSymbols(b: buffer, o: number, n: number): { { name: string, offset: number } }
local out = {}
if n < 8 then
return out
end
local rb = buffer.readu32(b, o)
if rb % 8 ~= 0 or rb + 8 > n then
return out
end
local strs = o + 8 + rb
local strn = math.min(buffer.readu32(b, o + 4 + rb), o + n - strs)
for i = 0, rb // 8 - 1 do
local sx = buffer.readu32(b, o + 4 + i * 8)
if sx < strn then
local q = strs + sx
while q < strs + strn and buffer.readu8(b, q) ~= 0 do
q += 1
end
table.insert(out, { name = buffer.readstring(b, strs + sx, q - strs - sx), offset = buffer.readu32(b, o + 8 + i * 8) })
end
end
return out
end
-- the fields of a deb control file ("Field: value", continuation lines start with a space or tab)
local function controlFields(s: string): { [string]: string }
local out: { [string]: string } = {}
local last: string? = nil
for line in string.gmatch(s, "([^\n]*)\n?") do
local c = string.sub(line, 1, 1)
if (c == " " or c == "\t") and last then
out[last] ..= "\n" .. string.sub(line, 2)
else
local k, v = string.match(line, "^([^:%s]+):%s*(.-)%s*$")
if k then
out[k], last = v :: string, k
end
end
end
return out
end
-- control.tar[.ext] -> the control file's fields, or nil
local function debControl(b: buffer, o: number, n: number, name: string, maxBytes: number): { [string]: string }?
local ext = string.match(name, "^control%.tar%.?(%w*)$")
local raw: buffer?
local opts: any = { maxBytes = maxBytes }
if ext == "" then
raw = buffer.create(n)
buffer.copy(raw :: buffer, 0, b, o, n)
elseif ext == "gz" then
raw = Deflate.gunzip(b, o, n)
elseif ext == "xz" then
raw = Lzma.xz(b, o, n, opts)
elseif ext == "lzma" then
raw = Lzma.alone(b, o, n, opts)
elseif ext == "zst" then
raw = Zstd.decompress(b, o, n, opts)
elseif ext == "bz2" then
raw = Bzip2.decompress(b, o, n, opts)
end
if not raw then
return nil
end
local list = Tar.read(raw)
for _, e in list or {} do
if (e.name == "./control" or e.name == "control") and e.type == "0" then
return controlFields(buffer.readstring(raw, e.offset, e.size))
end
end
return nil
end
local function encode(archive: any, opts: any?): (buffer?, Err.Err?)
return Ar.encode(archive, opts)
end
function Ar.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
local o: DecodeOptions = opts or {}
local maxEntries = o.maxEntries or 1e6
local b, base, e = r.buf, r.base, r.limit
if r:peek(8) == "!<thin>\n" then
return nil, Err.new(Err.UNSUPPORTED, "thin archives (members are outside the file)", base)
end
if r:peek(8) ~= MAGIC then
return nil, Err.new(Err.CORRUPT, "bad magic", base)
end
local a = Archive.new("ar", encode)
local variant = "gnu"
local longNames: string? = nil
local symbols: { { name: string, offset: number } }? = nil
local offsets: { [number]: string } = {} -- header offset (from the start) -> member name
local count = 0
local p = base + 8
while p < e do
local c = buffer.readu8(b, p)
if (c == 0 or c == 10) and not string.find(buffer.readstring(b, p, math.min(e - p, 65536)), "[^%z\n]") then
break -- trailing padding (bsdtar fills its last 10240-byte block with zeros)
end
if p + HEADER > e then
return nil, Err.new(Err.TRUNCATED, "member header past the end", p)
end
if buffer.readstring(b, p + 58, 2) ~= "`\n" then
return nil, Err.new(Err.CORRUPT, "bad member header", p + 58)
end
local rawName = buffer.readstring(b, p, 16)
local mtime = decimal(buffer.readstring(b, p + 16, 12))
local uid = decimal(buffer.readstring(b, p + 28, 6))
local gid = decimal(buffer.readstring(b, p + 34, 6))
local modeS = string.match(buffer.readstring(b, p + 40, 8), "^%s*([0-7]*)%s*$")
local size = decimal(buffer.readstring(b, p + 48, 10))
if not (mtime and uid and gid and modeS and size) then
return nil, Err.new(Err.CORRUPT, "bad member header field", p)
end
local mode = if modeS == "" then 0 else tonumber(modeS, 8) :: number
local data = p + HEADER
if data + size > e then
return nil, Err.new(Err.TRUNCATED, "member data past the end", data)
end
local nextP = data + size + size % 2
local name = string.gsub(rawName, " +$", "")
local dataSize = size
if string.sub(name, 1, 3) == "#1/" then
local n = tonumber(string.sub(name, 4))
if not n or n > size then
return nil, Err.new(Err.CORRUPT, "bad BSD name length", p)
end
name = buffer.readstring(b, data, n)
local z = string.find(name, "\0", 1, true)
if z then
name = string.sub(name, 1, z - 1)
end
data += n
dataSize -= n
variant = "bsd"
elseif name == "//" then
longNames = buffer.readstring(b, data, size)
p = nextP
continue
elseif name == "/" or name == "/SYM64/" then
symbols = sysvSymbols(b, data, size, name == "/SYM64/")
p = nextP
continue
elseif string.match(name, "^/%d+$") then
local off = tonumber(string.sub(name, 2)) :: number
if not longNames or off >= #longNames then
return nil, Err.new(Err.CORRUPT, "long name outside the name table", p)
end
local s = string.match(longNames, "^([^\n]*)", off + 1) :: string
name = string.gsub(s, "/$", "")
elseif string.sub(name, -1) == "/" then
name = string.sub(name, 1, -2)
end
if name == "__.SYMDEF" or name == "__.SYMDEF SORTED" or name == "__.SYMDEF_64" or name == "__.SYMDEF_64 SORTED" then
symbols = bsdSymbols(b, data, dataSize)
variant = "bsd"
p = nextP
continue
end
if name == "" then
return nil, Err.new(Err.CORRUPT, "empty member name", p)
end
offsets[p - base] = name
count += 1
if count > maxEntries then
return nil, Err.new(Err.LIMIT, "more than " .. maxEntries .. " entries")
end
Archive.put(a, {
name = name,
size = dataSize,
dir = false,
mtime = mtime,
uid = uid,
gid = gid,
mode = bit32.band(mode, 0xFFF),
armode = modeS,
method = "store",
load = if dataSize > 0 then lazy(b, data, dataSize) else nil,
})
p = nextP
end
if symbols then
local out = {}
for _, s in symbols do
table.insert(out, { name = s.name, member = offsets[s.offset] })
end
a.meta.symbols = out
end
a.meta.source = { format = "ar", variant = variant }
-- Debian packages
local list = a._entries
if list[1] and list[1].name == "debian-binary" then
a.meta.source.variant = "deb"
local v = a:read("debian-binary")
a.meta.debian = if v then (string.match(buffer.tostring(v), "^%s*(.-)%s*$")) else nil
for _, ent in list do
if string.match(ent.name, "^data%.tar") then
a.meta.payload = ent.name
elseif string.match(ent.name, "^control%.tar") then
local cb = a:read(ent.name)
if cb then
a.meta.control = debControl(cb, 0, buffer.len(cb), ent.name, o.maxBytes or 2 ^ 26)
end
end
end
end
return a, nil
end
-- ------------------------------------------------------------------------------------------------ encode
local function pad(s: string, n: number): string
return s .. string.rep(" ", n - #s)
end
local function header(name: string, e: any, size: number): string?
local mtime = math.floor(if type(e.mtime) == "number" then e.mtime else 0)
local uid = if type(e.uid) == "number" then e.uid else 0
local gid = if type(e.gid) == "number" then e.gid else 0
local mode: string = if type(e.armode) == "string" and string.find(e.armode, "^[0-7]+$") then e.armode
else string.format("%o", if type(e.mode) == "number" then bit32.band(e.mode, 0xFFF) else 0x1A4)
local f: { string } = { tostring(mtime), tostring(uid), tostring(gid), mode, tostring(size) }
local w = { 12, 6, 6, 8, 10 }
for i, s in f do
if #s > w[i] or string.find(s, "[^%d]") then
return nil
end
end
return pad(name, 16) .. pad(f[1], 12) .. pad(f[2], 6) .. pad(f[3], 6) .. pad(f[4], 8) .. pad(f[5], 10) .. "`\n"
end
function Ar.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err?)
local items = Archive.entries(archive)
if not items then
return nil, Err.new(Err.ARG, "expected an Archive")
end
local o: EncodeOptions = opts or {}
local src = type(archive.meta) == "table" and type(archive.meta.source) == "table" and archive.meta.source
local variant = o.variant or (if src and src.format == "ar" and (src.variant == "bsd" or src.variant == "deb") then "bsd" else "gnu")
if variant ~= "gnu" and variant ~= "bsd" then
return nil, Err.new(Err.ARG, "variant must be gnu or bsd")
end
local files = {}
for _, it in items do
local e: any = it.entry
if not e.dir and (e.type == nil or e.type == "0") then
local data, err = it.read()
if not data then
return nil, err
end
table.insert(files, { e = e, data = data })
end
end
local w = Bytes.writer(1024)
w:string(MAGIC)
-- GNU: names over 15 bytes (or holding "/" or a space) go into the "//" table
local table_: { string } = {}
local nameOf: { string } = {}
local tsize = 0
for i, f in files do
local name: string = f.e.name
if string.find(name, "\n") or name == "" then
return nil, Err.new(Err.ARG, "entry " .. i .. ": bad name for ar")
end
if variant == "gnu" then
if #name > 15 or string.find(name, "[/ ]") then
nameOf[i] = "/" .. tsize
table.insert(table_, name .. "/\n")
tsize += #name + 2
else
nameOf[i] = name .. "/"
end
end
end
if #table_ > 0 then
local t = table.concat(table_)
if #t % 2 == 1 then
t ..= "\n"
end
w:string(pad("//", 48) .. pad(tostring(#t), 10) .. "`\n" .. t)
end
for i, f in files do
local name: string = f.e.name
local size = buffer.len(f.data)
local prefix = ""
local field = nameOf[i]
if variant == "bsd" then
if #name > 16 or string.find(name, " ") then
field = "#1/" .. #name
prefix = name
else
field = name
end
end
local h = header(field, f.e, size + #prefix)
if not h then
return nil, Err.new(Err.ARG, "entry " .. name .. ": a field does not fit the ar header")
end
w:string(h)
w:string(prefix)
w:bytes(f.data)
if (size + #prefix) % 2 == 1 then
w:string("\n")
end
end
return w:finish(), nil
end
-- ------------------------------------------------------------------------------------------------ extras
-- new() -> an empty ar Archive: a:add(name, data, { mtime, mode }); a:write({ variant = "bsd" })
function Ar.new(): any
local a = Archive.new("ar", encode)
a.meta.source = { format = "ar", variant = "gnu" }
return a
end
return Ar
+172
View File
@@ -0,0 +1,172 @@
--!strict
-- archive/cpio: cpio archives (newc, crc, odc, old binary in both byte orders; see containers/Cpio) read into the
-- standard Archive value (entries read lazily: a copy of the stored bytes) and written as newc (default), crc or odc
-- from any Archive value (a tar, a zip, ...: list() + read()). Entries carry the cpio fields: type (tar letters),
-- mode (permission bits; the type is in type), uid, gid, nlink, ino, devmajor / devminor, rdevmajor / rdevminor,
-- link (symlinks), hardlink (the first link of a hard link group; every link reads the data). Tar hard links ("1")
-- written as cpio share an inode with their target. Not supported: tar-only fields (uname, gname: dropped).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Archive = require("@formats/containers/Archive")
local Cpio = require("@formats/containers/Cpio")
-- ------------------------------------------------------------------------------------------------ contract
local CpioFormat = {
name = "cpio",
category = "archive",
extensions = { "cpio" },
mime = { "application/x-cpio" },
deps = { "core/Err", "core/Bytes", "containers/Archive", "containers/Cpio" },
caps = { decode = true, encode = true, variants = { "newc", "crc", "odc", "bin" } },
}
export type DecodeOptions = {
maxEntries: number?, -- default 1e6
verify: boolean?, -- crc archives: check the data sums (default true)
}
export type EncodeOptions = {
variant: ("newc" | "crc" | "odc")?, -- default: the source archive's (old binary: newc), else "newc"
format: string?, -- "newc", "crc" or "odc" here too; any other value (the api's "cpio") means the variant default
block: number?, -- pad to a multiple of this many bytes (default 512, as GNU cpio; 1 = none)
}
-- ------------------------------------------------------------------------------------------------ sniff
function CpioFormat.sniff(r: Bytes.Reader): number
local m = r:peek(6)
if m == "070701" or m == "070702" or m == "070707" then
return 1
end
local b2 = r:peek(2)
if (b2 == "\199\113" or b2 == "\113\199") and r:remaining() >= 26 then
return 0.5
end
return 0
end
-- ------------------------------------------------------------------------------------------------ decode
local function lazy(b: buffer, at: number, n: number): () -> (buffer?, Err.Err?)
return function(): (buffer?, Err.Err?)
local out = buffer.create(n)
buffer.copy(out, 0, b, at, n)
return out, nil
end
end
local function encode(archive: any, opts: any?): (buffer?, Err.Err?)
return CpioFormat.encode(archive, opts)
end
function CpioFormat.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
local list, info = Cpio.read(r.buf, r.base, r.limit - r.base, opts)
if not list then
return nil, info
end
local a = Archive.new("cpio", encode)
for _, e in list do
local data = e.type == "0" and e.size > 0
Archive.put(a, {
name = e.name,
size = if data then e.size else 0,
dir = e.dir,
mtime = e.mtime,
mode = bit32.band(e.mode, 0xFFF),
uid = e.uid,
gid = e.gid,
type = e.type,
link = e.link,
hardlink = e.hardlink,
nlink = e.nlink,
ino = e.ino,
devmajor = e.devmajor,
devminor = e.devminor,
rdevmajor = e.rdevmajor,
rdevminor = e.rdevminor,
method = "store",
load = if data then lazy(r.buf, e.offset, e.size) else nil,
})
end
a.meta.source = { format = "cpio", variant = info.format }
return a, nil
end
-- ------------------------------------------------------------------------------------------------ encode
local function num(v: any): number?
return if type(v) == "number" then v else nil
end
function CpioFormat.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err?)
local items = Archive.entries(archive)
if not items then
return nil, Err.new(Err.ARG, "expected an Archive")
end
local index: { [string]: number } = {}
for i, it in items do
index[it.entry.name] = index[it.entry.name] or i
end
-- tar hard links ("1"): the same inode as their target, which counts the links
local links: { [number]: number } = {}
local target: { [number]: number } = {}
for i, it in items do
local e: any = it.entry
if e.type == "1" and type(e.link) == "string" and index[e.link] then
local t = index[e.link]
target[i] = t
links[t] = (links[t] or 1) + 1
end
end
local list: { Cpio.WriteEntry } = {}
for i, it in items do
local e: any = it.entry
local typ = if type(e.type) == "string" and Cpio.TYPE_MODE[e.type] then e.type elseif e.dir then "5" else "0"
local src = target[i]
local ino, nlink = num(e.ino), num(e.nlink)
if src then
typ, ino, nlink = "0", src, links[src]
elseif links[i] then
ino, nlink = i, links[i]
end
local data: buffer? = nil
if typ == "0" then
local b, err = (items[src or i] :: any).read()
if not b then
return nil, err
end
data = b
end
local mode = num(e.mode)
table.insert(list, {
name = e.name,
data = data,
type = typ,
link = if type(e.link) == "string" and typ == "2" then e.link else nil,
mode = if mode then bit32.band(mode, 0xFFF) else nil,
uid = num(e.uid),
gid = num(e.gid),
nlink = nlink,
mtime = num(e.mtime),
ino = ino,
devmajor = num(e.devmajor),
devminor = num(e.devminor),
rdevmajor = num(e.rdevmajor),
rdevminor = num(e.rdevminor),
})
end
-- opts.format may also be the api's format name ("cpio"): the variant default then
local o: any = opts or {}
local src = type(archive.meta) == "table" and type(archive.meta.source) == "table" and archive.meta.source
local own = if src and src.format == "cpio" and (src.variant == "crc" or src.variant == "odc") then src.variant else "newc"
local variant = o.variant or (if o.format == "crc" or o.format == "odc" or o.format == "newc" then o.format else own)
return Cpio.write(list, { format = variant, block = o.block })
end
-- ------------------------------------------------------------------------------------------------ extras
-- new() -> an empty cpio Archive: a:add(name, data, { mtime, mode, dir }); a:write()
function CpioFormat.new(): any
local a = Archive.new("cpio", encode)
a.meta.source = { format = "cpio" }
return a
end
return CpioFormat
+75
View File
@@ -0,0 +1,75 @@
--!strict
-- archive/iso: ISO 9660 CD / DVD images (.iso) read into the standard Archive value through containers/Iso9660:
-- plain ISO 9660 names, Joliet and Rock Ridge (names, modes, owners, times, symlinks, relocated deep directories;
-- Rock Ridge is used when present, else Joliet, else the plain names: opts.prefer picks another), multi-extent files.
-- Directories are dir entries; file data reads lazily (a copy of the extents). meta.iso holds the volume facts
-- (volumeId, systemId, publisher, blockSize, blocks, created, joliet level, rockRidge, tree) and meta.boot the El
-- Torito boot catalog (platform, bootable, media, load segment, sector count, image LBA) when there is one.
-- Not supported: writing, UDF, interleaved files (read: Err.UNSUPPORTED), zisofs-compressed files (read: the stored
-- bytes), multi-session images (the first session).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Archive = require("@formats/containers/Archive")
local Iso9660 = require("@formats/containers/Iso9660")
-- ------------------------------------------------------------------------------------------------ contract
local Iso = {
name = "iso",
category = "archive",
extensions = { "iso" },
mime = { "application/x-iso9660-image" },
deps = { "core/Err", "core/Bytes", "containers/Archive", "containers/Iso9660" },
caps = { decode = true, encode = false, extensions = { "joliet", "rockridge", "eltorito" } },
}
export type DecodeOptions = {
prefer: ("rockridge" | "joliet" | "iso9660")?, -- the name set (default: Rock Ridge, else Joliet, else plain)
maxEntries: number?, -- default 1e6
}
-- ------------------------------------------------------------------------------------------------ sniff
function Iso.sniff(r: Bytes.Reader): number
return if r:peek(5, 16 * 2048 + 1) == "CD001" then 1 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
function Iso.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
local list, info = Iso9660.read(r.buf, r.base, r.limit - r.base, opts)
if not list then
return nil, info
end
local a = Archive.new("iso")
local b, limit = r.buf, r.limit
for _, e in list do
local data = e.type == "0" and e.size > 0
Archive.put(a, {
name = e.name,
size = e.size,
dir = e.dir,
mtime = e.mtime,
type = e.type,
mode = e.mode,
uid = e.uid,
gid = e.gid,
nlink = e.nlink,
link = e.link,
rdev = e.rdev,
hidden = e.hidden,
method = if e.zisofs then "zisofs" else "store",
load = if data
then function(): (buffer?, Err.Err?)
return Iso9660.extract(b, e, limit)
end
else nil,
})
end
a.meta.boot = info.boot
info.boot = nil
a.meta.iso = info
a.meta.source = { format = "iso", tree = info.tree }
return a, nil
end
return Iso
+353
View File
@@ -0,0 +1,353 @@
--!strict
-- archive/lz4: LZ4 frame files (.lz4: lz4 doc/lz4_Frame_format.md 1.6.x) as a single-stream Archive: one entry (the
-- decompressed data), named after the file without .lz4 (.tlz4 -> .tar), else "data"; meta.stream = true, so the api
-- unwraps a .tar.lz4. Reading: concatenated frames, skippable frames (magic 0x184D2A50..5F, skipped), the legacy
-- frame (magic 0x184C2102, 8 MB blocks), independent and linked blocks, block sizes 64 KB .. 4 MB, uncompressed
-- blocks, the header checksum, block checksums and the content checksum (XXH32, codecs/compress/Xxh32: verified
-- unless opts.verify = false), the content size (checked). Writing: one frame of independent blocks
-- (codecs/compress/Lz4), with opts for the block size, block checksums, the content checksum and the content size;
-- several entries are written as a tar inside. Written from the specification; no code ported. Not supported:
-- dictionaries (frames with a dictionary ID: Err.UNSUPPORTED), writing linked blocks or legacy frames.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Lz4 = require("@formats/codecs/compress/Lz4")
local Xxh32 = require("@formats/codecs/compress/Xxh32")
local Archive = require("@formats/containers/Archive")
-- ------------------------------------------------------------------------------------------------ contract
local Lz4Format = {
name = "lz4",
category = "archive",
extensions = { "lz4", "tlz4" },
mime = { "application/x-lz4" },
deps = { "core/Err", "core/Bytes", "codecs/compress/Lz4", "codecs/compress/Xxh32", "containers/Archive" },
caps = { decode = true, encode = true, stream = true, legacy = true },
}
export type DecodeOptions = {
maxBytes: number?, -- refuse output larger than this (default 2^30)
verify: boolean?, -- check the block / content checksums (default true; the header checksum is always checked)
name: string?, -- the file name (the api passes it): names the entry
}
export type EncodeOptions = {
blockSize: number?, -- 65536, 262144, 1048576 or 4194304 (default 4 MB, as the lz4 tool)
blockChecksum: boolean?, -- default false
contentChecksum: boolean?, -- default true
contentSize: boolean?, -- store the content size (default false)
}
-- ------------------------------------------------------------------------------------------------ constants
local MAGIC = 0x184D2204
local LEGACY = 0x184C2102
local LEGACY_BLOCK = 8 * 1048576
local SIZES: { [number]: number } = { [4] = 65536, [5] = 262144, [6] = 1048576, [7] = 4194304 }
-- ------------------------------------------------------------------------------------------------ sniff
function Lz4Format.sniff(r: Bytes.Reader): number
local m = r:peek(4)
if m == "\4\34\77\24" then
return 1
elseif m == "\2\33\76\24" then
return 0.9
elseif #m == 4 and string.byte(m, 1) >= 0x50 and string.byte(m, 1) <= 0x5F and string.sub(m, 2) == "\42\77\24" then
-- a skippable frame (zstd shares the magic): an LZ4 frame after it
local h = r:peek(4, 4)
if #h == 4 then
local n = string.byte(h, 1) + string.byte(h, 2) * 256 + string.byte(h, 3) * 65536 + string.byte(h, 4) * 16777216
if r:peek(4, 8 + n) == "\4\34\77\24" then
return 1
end
end
end
return 0
end
-- ------------------------------------------------------------------------------------------------ decode
local function skippable(m: number): boolean
return m >= 0x184D2A50 and m <= 0x184D2A5F
end
type Out = { buf: buffer, n: number, max: number }
-- room for k more bytes in the output (doubling, up to max) | false
local function room(out: Out, k: number): boolean
local need = out.n + k
if need > out.max then
return false
end
if need > buffer.len(out.buf) then
local nb = buffer.create(math.min(math.max(buffer.len(out.buf) * 2, need), out.max))
buffer.copy(nb, 0, out.buf, 0, out.n)
out.buf = nb
end
return true
end
-- one LZ4 frame at p -> the input offset after it | nil, Err
local function frame(b: buffer, p: number, e: number, out: Out, verify: boolean): (number?, Err.Err?)
if p + 7 > e then
return nil, Err.new(Err.TRUNCATED, "frame header past the end", p)
end
local flg, bd = buffer.readu8(b, p + 4), buffer.readu8(b, p + 5)
if bit32.rshift(flg, 6) ~= 1 then
return nil, Err.new(Err.UNSUPPORTED, "frame version " .. bit32.rshift(flg, 6), p + 4)
end
if bit32.band(flg, 2) ~= 0 or bit32.band(bd, 0x8F) ~= 0 then
return nil, Err.new(Err.CORRUPT, "reserved descriptor bits set", p + 4)
end
local independent = bit32.band(flg, 0x20) ~= 0
local blockSum = bit32.band(flg, 0x10) ~= 0
local hasSize = bit32.band(flg, 0x08) ~= 0
local contentSum = bit32.band(flg, 0x04) ~= 0
local hasDict = bit32.band(flg, 0x01) ~= 0
local bmax = SIZES[bit32.rshift(bd, 4)]
if not bmax then
return nil, Err.new(Err.CORRUPT, "bad block maximum size", p + 5)
end
local q = p + 6
local size: number? = nil
if hasSize then
if q + 8 > e then
return nil, Err.new(Err.TRUNCATED, "frame header past the end", q)
end
size = buffer.readu32(b, q) + buffer.readu32(b, q + 4) * 4294967296
q += 8
end
if hasDict then
return nil, Err.new(Err.UNSUPPORTED, "frames with a dictionary", q)
end
if q + 1 > e then
return nil, Err.new(Err.TRUNCATED, "frame header past the end", q)
end
local hc = bit32.band(bit32.rshift(Xxh32.hash(b, p + 4, q - p - 4), 8), 255)
if hc ~= buffer.readu8(b, q) then
return nil, Err.new(Err.CHECKSUM, "frame header checksum mismatch", q)
end
q += 1
if size and out.n + size > out.max then
return nil, Err.new(Err.LIMIT, "content over " .. out.max .. " bytes", p)
end
local start = out.n
while true do
if q + 4 > e then
return nil, Err.new(Err.TRUNCATED, "block header past the end", q)
end
local bs = buffer.readu32(b, q)
q += 4
if bs == 0 then
break
end
local raw = bit32.band(bs, 0x80000000) ~= 0
local n = bit32.band(bs, 0x7FFFFFFF)
if n > bmax then
return nil, Err.new(Err.CORRUPT, "block larger than the maximum", q - 4)
end
if q + n + (if blockSum then 4 else 0) > e then
return nil, Err.new(Err.TRUNCATED, "block past the end", q)
end
if blockSum and verify and Xxh32.hash(b, q, n) ~= buffer.readu32(b, q + n) then
return nil, Err.new(Err.CHECKSUM, "block checksum mismatch", q + n)
end
if not room(out, if raw then n else bmax) and not room(out, if raw then n else math.min(bmax, out.max - out.n)) then
return nil, Err.new(Err.LIMIT, "output over " .. out.max .. " bytes", q)
end
if raw then
buffer.copy(out.buf, out.n, b, q, n)
out.n += n
else
local lim = math.min(out.n + bmax, buffer.len(out.buf))
local dEnd, msg = Lz4.decodeInto(b, q, q + n, out.buf, out.n, lim, if independent then out.n else start)
if not dEnd then
if msg and string.sub(msg, 1, 6) == "limit:" and lim < out.n + bmax then
return nil, Err.new(Err.LIMIT, "output over " .. out.max .. " bytes", q)
end
return nil, Err.from(msg, q)
end
out.n = dEnd
end
q += n + (if blockSum then 4 else 0)
end
if contentSum then
if q + 4 > e then
return nil, Err.new(Err.TRUNCATED, "content checksum past the end", q)
end
if verify and Xxh32.hash(out.buf, start, out.n - start) ~= buffer.readu32(b, q) then
return nil, Err.new(Err.CHECKSUM, "content checksum mismatch", q)
end
q += 4
end
if size and out.n - start ~= size then
return nil, Err.new(Err.CORRUPT, "content size mismatch", p + 6)
end
return q, nil
end
-- a legacy frame at p: blocks of up to 8 MB until the input ends or a magic number follows
local function legacy(b: buffer, p: number, e: number, out: Out): (number?, Err.Err?)
local q = p + 4
while q + 4 <= e do
local n = buffer.readu32(b, q)
if n == MAGIC or n == LEGACY or skippable(n) then
break
end
q += 4
if q + n > e then
return nil, Err.new(Err.TRUNCATED, "block past the end", q)
end
if not room(out, LEGACY_BLOCK) and not room(out, math.min(LEGACY_BLOCK, out.max - out.n)) then
return nil, Err.new(Err.LIMIT, "output over " .. out.max .. " bytes", q)
end
local lim = math.min(out.n + LEGACY_BLOCK, buffer.len(out.buf))
local dEnd, msg = Lz4.decodeInto(b, q, q + n, out.buf, out.n, lim)
if not dEnd then
return nil, Err.from(msg, q)
end
out.n = dEnd
q += n
end
return q, nil
end
-- decompress(buf, offset?, length?, opts?) -> the data of every frame | nil, Err
function Lz4Format.decompress(src: buffer | string, offset: number?, length: number?, opts: DecodeOptions?): (buffer?, Err.Err?)
local b, o, n, aerr = Bytes.span("Lz4.decompress", src, offset, length)
if not b then
return nil, aerr
end
local maxBytes = (opts and opts.maxBytes) or 2 ^ 30
local verify = not (opts and opts.verify == false)
local out: Out = { buf = buffer.create(math.min(math.max(n * 3, 256), maxBytes)), n = 0, max = maxBytes }
local p, e = o, o + n
local frames = 0
while p + 4 <= e do
local m = buffer.readu32(b, p)
local q, err
if m == MAGIC then
q, err = frame(b, p, e, out, verify)
frames += 1
elseif m == LEGACY then
q, err = legacy(b, p, e, out)
frames += 1
elseif skippable(m) then
if p + 8 > e then
return nil, Err.new(Err.TRUNCATED, "skippable frame past the end", p)
end
q = p + 8 + buffer.readu32(b, p + 4)
if q > e then
return nil, Err.new(Err.TRUNCATED, "skippable frame past the end", p)
end
elseif frames > 0 then
break -- trailing data after the frames (as lz4 -d, which warns)
else
return nil, Err.new(Err.CORRUPT, "bad magic", p)
end
if not q then
return nil, err
end
p = q :: number
end
if frames == 0 then
return nil, Err.new(if n < 4 then Err.TRUNCATED else Err.CORRUPT, "no LZ4 frame", o)
end
local res = buffer.create(out.n)
buffer.copy(res, 0, out.buf, 0, out.n)
return res, nil
end
local function encode(value: any, opts: any?): (buffer?, Err.Err?)
return Lz4Format.encode(value, opts)
end
function Lz4Format.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
local o: DecodeOptions = opts or {}
local n = r.limit - r.base
local out, err = Lz4Format.decompress(r.buf, r.base, n, o)
if not out then
return nil, err
end
local a = Archive.new("lz4", encode)
a.meta.stream = true
a.meta.source = { format = "lz4", legacy = r:peek(4) == "\2\33\76\24" }
local name = Archive.streamName(o, { "lz4" })
local stem, ext = string.match(name, "^(.+)%.(%w+)$")
if stem and ext and string.lower(ext) == "tlz4" then
name = stem .. ".tar"
end
Archive.put(a, { name = name, size = buffer.len(out), compressedSize = n, method = "lz4", dir = false, data = out })
return a, nil
end
-- ------------------------------------------------------------------------------------------------ encode
-- compress(data, opts?) -> one LZ4 frame | nil, Err
function Lz4Format.compress(data: buffer | string, opts: EncodeOptions?): (buffer?, Err.Err?)
local b, o, n, aerr = Bytes.span("Lz4.compress", data, nil, nil)
if not b then
return nil, aerr
end
local op: EncodeOptions = opts or {}
local bsize = op.blockSize or 4194304
local bd = nil
for k, v in SIZES do
if v == bsize then
bd = k
end
end
if not bd then
return nil, Err.new(Err.ARG, "blockSize must be 65536, 262144, 1048576 or 4194304")
end
local blockSum = op.blockChecksum == true
local contentSum = op.contentChecksum ~= false
local withSize = op.contentSize == true
local w = Bytes.writer(n + n // 200 + 64)
w:u32le(MAGIC)
local flg = 0x40 + 0x20 + (if blockSum then 0x10 else 0) + (if withSize then 0x08 else 0) + (if contentSum then 0x04 else 0)
w:u8(flg)
w:u8(bd * 16)
if withSize then
w:u32le(n % 4294967296)
w:u32le(n // 4294967296)
end
local hc = bit32.band(bit32.rshift(Xxh32.hash(w.buf, 4, w.pos - 4), 8), 255)
w:u8(hc)
local scratch = buffer.create(Lz4.bound(math.min(bsize, math.max(n, 1))))
local p = o
while p < o + n do
local k = math.min(bsize, o + n - p)
local c = Lz4.encodeInto(b, p, k, scratch, 0)
local at = w.pos
if c < k then
w:u32le(c)
local q = w:reserve(c)
buffer.copy(w.buf, q, scratch, 0, c)
w.pos = q + c
else
w:u32le(k + 0x80000000)
local q = w:reserve(k)
buffer.copy(w.buf, q, b, p, k)
w.pos = q + k
end
if blockSum then
local len = w.pos - at - 4
w:u32le(Xxh32.hash(w.buf, at + 4, len))
end
p += k
end
w:u32le(0)
if contentSum then
w:u32le(Xxh32.hash(b, o, n))
end
return w:finish(), nil
end
-- encode(value, opts?): a buffer / string, an Archive's one file, or a tar of the Archive's entries, as one frame
function Lz4Format.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
local data, err = Archive.streamData(value)
if not data then
return nil, err
end
return Lz4Format.compress(data, opts)
end
return Lz4Format
+333
View File
@@ -0,0 +1,333 @@
--!strict
-- archive/rpm: RPM packages (format v3 / v4), read into the standard Archive value. The 96-byte lead, the signature
-- header (padded to 8 bytes) and the main header are parsed (every tag into meta.rpm.tags; the common ones by name in
-- meta.rpm); the file list comes from the header (dirnames / basenames / dirindexes, or the old filenames tag, with
-- sizes / long sizes, modes, mtimes, link targets, owners) and lists without touching the payload. The payload
-- (gzip / bzip2 / xz / lzma / zstd or none, through codecs/compress/*) is decompressed on the first read and parsed
-- as a cpio archive (containers/Cpio); entry names drop the leading "./" and "/". Ghost files (%ghost) are not
-- listed (they are not in the payload). Written from the RPM file format documentation (rpm.org, the LSB package
-- format chapter); no code ported. Not supported: writing, signature / digest verification, the "stripped cpio"
-- payload of packages with files over 4 GiB (Err.UNSUPPORTED on read), delta rpms.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Deflate = require("@formats/codecs/compress/Deflate")
local Lzma = require("@formats/codecs/compress/Lzma")
local Zstd = require("@formats/codecs/compress/Zstd")
local Bzip2 = require("@formats/codecs/compress/Bzip2")
local Archive = require("@formats/containers/Archive")
local Cpio = require("@formats/containers/Cpio")
-- ------------------------------------------------------------------------------------------------ contract
local Rpm = {
name = "rpm",
category = "archive",
extensions = { "rpm" },
mime = { "application/x-rpm" },
deps = { "core/Err", "core/Bytes", "codecs/compress/Deflate", "codecs/compress/Lzma", "codecs/compress/Zstd", "codecs/compress/Bzip2", "containers/Archive", "containers/Cpio" },
caps = { decode = true, encode = false, compressors = { "gzip", "bzip2", "xz", "lzma", "zstd" } },
}
export type DecodeOptions = {
maxBytes: number?, -- the largest decompressed payload (default 2^30)
maxEntries: number?, -- default 1e6
}
-- ------------------------------------------------------------------------------------------------ constants
local LEAD_MAGIC = "\237\171\238\219"
local HEADER_MAGIC = "\142\173\232\1"
local RPMFILE_GHOST = 64
-- the tags meta.rpm names
local NAMES: { [number]: string } = {
[1000] = "name",
[1001] = "version",
[1002] = "release",
[1003] = "epoch",
[1004] = "summary",
[1005] = "description",
[1006] = "buildtime",
[1007] = "buildhost",
[1009] = "size",
[1010] = "distribution",
[1011] = "vendor",
[1014] = "license",
[1015] = "packager",
[1016] = "group",
[1020] = "url",
[1021] = "os",
[1022] = "arch",
[1044] = "sourcerpm",
[1047] = "provides",
[1049] = "requires",
[1124] = "payloadFormat",
[1125] = "payloadCompressor",
[1126] = "payloadFlags",
[5009] = "longsize",
}
-- ------------------------------------------------------------------------------------------------ sniff
function Rpm.sniff(r: Bytes.Reader): number
return if r:peek(4) == LEAD_MAGIC then 1 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
-- a header structure at p -> { [tag] = value }, end offset | nil, Err
local function header(b: buffer, p: number, e: number): (any, any)
if p + 16 > e then
return nil, Err.new(Err.TRUNCATED, "header past the end", p)
end
if buffer.readstring(b, p, 4) ~= HEADER_MAGIC then
return nil, Err.new(Err.CORRUPT, "bad header magic", p)
end
local n = bit32.byteswap(buffer.readu32(b, p + 8))
local hsize = bit32.byteswap(buffer.readu32(b, p + 12))
local index = p + 16
local store = index + n * 16
if n > 0x10000 or hsize > 0x10000000 then
return nil, Err.new(Err.LIMIT, "header too large", p)
end
if store + hsize > e then
return nil, Err.new(Err.TRUNCATED, "header data past the end", p)
end
local tags: { [number]: any } = {}
local se = store + hsize
for i = 0, n - 1 do
local q = index + i * 16
local tag = bit32.byteswap(buffer.readu32(b, q))
local typ = bit32.byteswap(buffer.readu32(b, q + 4))
local off = bit32.byteswap(buffer.readu32(b, q + 8))
local count = bit32.byteswap(buffer.readu32(b, q + 12))
local d = store + off
if off > hsize then
return nil, Err.new(Err.CORRUPT, "tag data outside the header", q)
end
local width = if typ == 2 or typ == 1 then 1 elseif typ == 3 then 2 elseif typ == 4 then 4 elseif typ == 5 then 8 else 0
if width > 0 then
if d + count * width > se then
return nil, Err.new(Err.CORRUPT, "tag data outside the header", q)
end
local v = table.create(count)
for k = 0, count - 1 do
local x = d + k * width
v[k + 1] = if width == 1 then buffer.readu8(b, x)
elseif width == 2 then bit32.bor(bit32.lshift(buffer.readu8(b, x), 8), buffer.readu8(b, x + 1))
elseif width == 4 then bit32.byteswap(buffer.readu32(b, x))
else bit32.byteswap(buffer.readu32(b, x)) * 4294967296 + bit32.byteswap(buffer.readu32(b, x + 4))
end
tags[tag] = v
elseif typ == 7 then
if d + count > se then
return nil, Err.new(Err.CORRUPT, "tag data outside the header", q)
end
tags[tag] = buffer.readstring(b, d, count)
elseif typ == 6 or typ == 8 or typ == 9 then
local v = {}
local s = d
local want = if typ == 6 then 1 else count
if want > hsize then
return nil, Err.new(Err.CORRUPT, "bad string count", q)
end
for _ = 1, want do
local z = s
while z < se and buffer.readu8(b, z) ~= 0 do
z += 1
end
if z >= se then
return nil, Err.new(Err.CORRUPT, "unterminated string", s)
end
table.insert(v, buffer.readstring(b, s, z - s))
s = z + 1
end
tags[tag] = if typ == 6 then v[1] else v
end
end
return tags, se
end
-- the file list of the header: { name, size, mode, mtime, link, user, group, flags }
local function files(tags: { [number]: any }): { any }
local names: { string } = {}
local bn, dn, di = tags[1117], tags[1118], tags[1116]
if type(bn) == "table" and type(dn) == "table" and type(di) == "table" then
for i, base in bn do
local d = dn[(di[i] or 0) + 1]
names[i] = (if type(d) == "string" then d else "") .. base
end
elseif type(tags[1027]) == "table" then
names = tags[1027]
end
local sizes = tags[5008] or tags[1028] or {}
local modes, mtimes, links = tags[1030] or {}, tags[1034] or {}, tags[1036] or {}
local users, groups, flags = tags[1039] or {}, tags[1040] or {}, tags[1037] or {}
local out = {}
for i, n in names do
table.insert(out, {
name = n,
size = sizes[i] or 0,
mode = modes[i] or 0,
mtime = mtimes[i] or 0,
link = if links[i] and links[i] ~= "" then links[i] else nil,
user = users[i],
group = groups[i],
flags = flags[i] or 0,
})
end
return out
end
local function strip(name: string): string
return (string.gsub(name, "^%.?/+", ""))
end
-- the payload: decompressed, then its cpio entries by stripped name
local function payload(b: buffer, p: number, e: number, compressor: string?, o: DecodeOptions): (any, Err.Err?)
local n = e - p
local opts: any = { maxBytes = o.maxBytes or 2 ^ 30 }
local raw: buffer?, err: any
local m = if n >= 6 then buffer.readstring(b, p, 6) else ""
if string.sub(m, 1, 2) == "\31\139" then
raw, err = Deflate.gunzip(b, p, n)
elseif m == "\253" .. "7zXZ\0" then
raw, err = Lzma.xz(b, p, n, opts)
elseif string.sub(m, 1, 3) == "BZh" then
raw, err = Bzip2.decompress(b, p, n, opts)
elseif string.sub(m, 1, 4) == "\40\181\47\253" then
raw, err = Zstd.decompress(b, p, n, opts)
elseif compressor == "lzma" then
raw, err = Lzma.alone(b, p, n, opts)
elseif string.sub(m, 1, 5) == "07070" then
raw = buffer.create(n)
buffer.copy(raw :: buffer, 0, b, p, n)
else
return nil, Err.new(Err.UNSUPPORTED, "payload compressor " .. tostring(compressor), p)
end
if not raw then
return nil, err
end
if buffer.len(raw) >= 6 and buffer.readstring(raw, 0, 6) == "07070X" then
return nil, Err.new(Err.UNSUPPORTED, "stripped cpio payload (files over 4 GiB)")
end
local list, cerr = Cpio.read(raw, 0, nil, { maxEntries = o.maxEntries })
if not list then
return nil, cerr
end
local by = {}
for _, ent in list do
by[strip(ent.name)] = ent
end
return { buf = raw, by = by }, nil
end
function Rpm.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
local o: DecodeOptions = opts or {}
local b, base, e = r.buf, r.base, r.limit
if e - base < 96 then
return nil, Err.new(Err.TRUNCATED, "lead past the end", base)
end
if buffer.readstring(b, base, 4) ~= LEAD_MAGIC then
return nil, Err.new(Err.CORRUPT, "bad lead magic", base)
end
local major, minor = buffer.readu8(b, base + 4), buffer.readu8(b, base + 5)
local kind = bit32.bor(bit32.lshift(buffer.readu8(b, base + 6), 8), buffer.readu8(b, base + 7))
local leadName = buffer.readstring(b, base + 10, 66)
leadName = string.match(leadName, "^[^%z]*") :: string
if major < 3 then
return nil, Err.new(Err.UNSUPPORTED, "rpm format version " .. major, base + 4)
end
local sig, sigEnd = header(b, base + 96, e)
if not sig then
return nil, sigEnd
end
local hp = base + (sigEnd - base + 7) // 8 * 8
local tags, hEnd = header(b, hp, e)
if not tags then
return nil, hEnd
end
local a = Archive.new("rpm")
local info: { [string]: any } = { tags = tags, signature = sig, type = if kind == 1 then "source" else "binary", lead = { major = major, minor = minor, name = leadName } }
for tag, key in NAMES do
local v = tags[tag]
if type(v) == "table" and tag ~= 1047 and tag ~= 1049 then -- numbers and i18n strings: the first value
v = v[1]
end
info[key] = v
end
a.meta.rpm = info
a.meta.source = { format = "rpm", compressor = info.payloadCompressor }
if info.payloadFormat and info.payloadFormat ~= "cpio" then
return nil, Err.new(Err.UNSUPPORTED, "payload format " .. tostring(info.payloadFormat), hEnd)
end
local cache: any = nil
local cacheErr: Err.Err? = nil
local function entry(name: string): (any, Err.Err?)
if not cache and not cacheErr then
cache, cacheErr = payload(b, hEnd, e, info.payloadCompressor, o)
end
if not cache then
return nil, cacheErr
end
local ent = cache.by[name]
if not ent then
return nil, Err.new(Err.CORRUPT, "file " .. name .. " is not in the payload")
end
return ent, nil
end
local list = files(tags)
if #list > (o.maxEntries or 1e6) then
return nil, Err.new(Err.LIMIT, "too many files")
end
for _, f in list do
if bit32.band(f.flags, RPMFILE_GHOST) ~= 0 then
continue
end
local name = strip(f.name)
local typ = Cpio.TYPE_OF[bit32.band(f.mode, 0xF000)] or "0"
local data = typ == "0" and f.size > 0
Archive.put(a, {
name = name,
size = if data then f.size else 0,
dir = typ == "5",
mtime = f.mtime,
mode = bit32.band(f.mode, 0xFFF),
type = typ,
link = if typ == "2" then f.link else nil,
uname = f.user,
gname = f.group,
method = if info.payloadCompressor then info.payloadCompressor else "store",
load = if data
then function(): (buffer?, Err.Err?)
local ent, err = entry(name)
if not ent then
return nil, err
end
local out = buffer.create(ent.size)
buffer.copy(out, 0, cache.buf, ent.offset, ent.size)
return out, nil
end
else nil,
})
end
return a, nil
end
-- ------------------------------------------------------------------------------------------------ extras
-- cpio(r, opts?) -> the decompressed payload (a cpio archive, as rpm2cpio prints it) | nil, Err
function Rpm.cpio(r: Bytes.Reader, opts: DecodeOptions?): (buffer?, Err.Err?)
local a, err = Rpm.decode(r, opts)
if not a then
return nil, err
end
local p = r.base + 96
local _, sigEnd = header(r.buf, p, r.limit)
local hp = r.base + (sigEnd - r.base + 7) // 8 * 8
local _, hEnd = header(r.buf, hp, r.limit)
local pl, perr = payload(r.buf, hEnd, r.limit, a.meta.rpm.payloadCompressor, opts or {})
if not pl then
return nil, perr
end
return pl.buf, nil
end
return Rpm
+98
View File
@@ -0,0 +1,98 @@
--!strict
-- archive/z: Unix compress files (.Z: LZW, magic 1F 9D, 9..16-bit codes, block mode) as a single-stream Archive: one
-- entry, named after the file without .Z (.taz / .tZ -> .tar), else "data"; meta.stream = true, so the api unwraps a
-- .tar.Z into the tar. Writing: an Archive with one file entry (or a buffer / string) becomes that file compressed,
-- byte for byte what ncompress writes; an Archive with several entries is written as a tar inside (a .tar.Z). The LZW is
-- codecs/compress/UnixCompress. Not supported: pack (.z, 1F 1E) and compact (1F FF) files.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local UnixCompress = require("@formats/codecs/compress/UnixCompress")
local Archive = require("@formats/containers/Archive")
-- ------------------------------------------------------------------------------------------------ contract
local Z = {
name = "z",
category = "archive",
extensions = { "z", "taz", "tz" },
mime = { "application/x-compress" },
deps = { "core/Err", "core/Bytes", "codecs/compress/UnixCompress", "containers/Archive" },
caps = { decode = true, encode = true, stream = true, bits = { 9, 16 } },
}
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
}
export type EncodeOptions = {
maxBits: number?, -- 9..16 (compress -b), default 16
}
-- ------------------------------------------------------------------------------------------------ sniff
function Z.sniff(r: Bytes.Reader): number
if r:peek(2) ~= "\31\157" then
return 0
end
local f = r:peekU8(2)
return if f >= 0 and bit32.band(f, 0x60) == 0 and bit32.band(f, 0x1F) >= 9 and bit32.band(f, 0x1F) <= 16 then 1 else 0.3
end
-- ------------------------------------------------------------------------------------------------ decode
-- the entry name: the file name without .Z; .taz / .tz name a tar
local function entryName(opts: DecodeOptions): string
local name = Archive.streamName(opts, { "z" })
local stem, ext = string.match(name, "^(.+)%.(%w+)$")
if stem and ext and (string.lower(ext) == "taz" or string.lower(ext) == "tz") then
return stem .. ".tar"
end
return name
end
local function encode(value: any, opts: any?): (buffer?, Err.Err?)
return Z.encode(value, opts)
end
function Z.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
local o: DecodeOptions = opts or {}
local n = r.limit - r.base
local out, err = UnixCompress.decompress(r.buf, r.base, n, o)
if not out then
return nil, err
end
local a = Archive.new("z", encode)
a.meta.stream = true
a.meta.source = { format = "z", maxBits = bit32.band(buffer.readu8(r.buf, r.base + 2), 0x1F), blockMode = bit32.band(buffer.readu8(r.buf, r.base + 2), 0x80) ~= 0 }
Archive.put(a, {
name = entryName(o),
size = buffer.len(out),
compressedSize = n,
method = "lzw",
dir = false,
data = out,
})
return a, nil
end
-- ------------------------------------------------------------------------------------------------ encode
function Z.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
local data, err = Archive.streamData(value)
if not data then
return nil, err
end
return UnixCompress.compress(data, 0, buffer.len(data), { maxBits = opts and opts.maxBits })
end
-- ------------------------------------------------------------------------------------------------ extras
-- new(data?, name?) -> a .Z Archive holding one entry
function Z.new(data: (buffer | string)?, name: string?): any
local a = Archive.new("z", encode)
a.meta.stream = true
a.meta.source = { format = "z" }
if data then
a:add(name or "data", data)
end
return a
end
return Z
+291
View File
@@ -0,0 +1,291 @@
--!strict
--!native
--!optimize 2
-- codecs/compress/Lz4: the LZ4 block format (lz4 doc/lz4_Block_format.md): decode and a greedy hash-chain-free encoder
-- (the reference "fast" strategy: one 4-byte hash table, 64 KB window). A codec (layer 3): model/rbxm chunk bodies,
-- and the LZ4 frame format (archive) builds on it. New code, written from the specification. Never throws.
--
-- local out, err = Lz4.decompress(src, offset?, length?, outSize?, opts?) -- a block -> buffer | nil, Err
-- local packed = Lz4.compress(src, offset?, length?) -- -> buffer (a block) | nil, Err
-- local dEnd, msg = Lz4.decodeInto(src, p, limit, dst, d, dstLimit, histStart?) -- low level (linked blocks)
-- local n = Lz4.encodeInto(src, p, n, dst, d) -- low level; dst has bound(n) room
-- Lz4.bound(n) -- worst-case block size for n bytes
--
-- decodeInto decodes one block from src[p, limit) to dst[d, dstLimit): matches may reach back to histStart (default
-- d), so a frame decoder with linked blocks keeps the previous output in front of d. It returns the output end, or
-- nil and a message ("truncated", "corrupt: ...", "limit: output ...") for the caller's Err.from.
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Lz4 = {}
export type Options = {
maxBytes: number?, -- refuse output larger than this when outSize is not given (default 2^28)
}
local readu8, writeu8, readu16, writeu16, readu32 = buffer.readu8, buffer.writeu8, buffer.readu16, buffer.writeu16, buffer.readu32
local bcopy, bcreate, blen = buffer.copy, buffer.create, buffer.len
local band, rshift = bit32.band, bit32.rshift
local MINMATCH = 4
local LASTLITERALS = 5 -- the last 5 bytes are always literals
local MFLIMIT = 12 -- the last match starts at least 12 bytes before the end
local MAX_OFFSET = 65535
local HASH_BITS = 13
local HASH_SIZE = 2 ^ HASH_BITS
-- ------------------------------------------------------------------------------------------------ decode
function Lz4.decodeInto(src: buffer, p: number, limit: number, dst: buffer, d: number, dstLimit: number, histStart: number?): (number?, string?)
local lo = histStart or d
if limit > blen(src) or dstLimit > blen(dst) or p < 0 or d < 0 or lo < 0 or lo > d then
return nil, "corrupt: bad ranges"
end
if p >= limit then
return nil, "truncated: empty block"
end
while true do
if p >= limit then
return nil, "truncated"
end
local token = readu8(src, p)
p += 1
local lit = rshift(token, 4)
if lit == 15 then
local b = 255
while b == 255 do
if p >= limit then
return nil, "truncated"
end
b = readu8(src, p)
p += 1
lit += b
end
end
if lit > 0 then
if p + lit > limit then
return nil, "truncated: literals past the end"
end
if d + lit > dstLimit then
return nil, "limit: output larger than expected"
end
bcopy(dst, d, src, p, lit)
p += lit
d += lit
end
if p >= limit then
return d, nil -- the last sequence has no match
end
if p + 2 > limit then
return nil, "truncated"
end
local off = readu16(src, p)
p += 2
if off == 0 or d - off < lo then
return nil, "corrupt: bad match offset"
end
local ml = band(token, 15)
if ml == 15 then
local b = 255
while b == 255 do
if p >= limit then
return nil, "truncated"
end
b = readu8(src, p)
p += 1
ml += b
end
end
ml += MINMATCH
if d + ml > dstLimit then
return nil, "limit: output larger than expected"
end
local s = d - off
if off >= ml then
bcopy(dst, d, dst, s, ml)
d += ml
elseif off == 1 then
buffer.fill(dst, d, readu8(dst, s), ml)
d += ml
else
-- an overlapping match repeats the off-byte pattern: copy what is already there, doubling each time
local n = ml
while n > 0 do
local c = d - s
if c > n then
c = n
end
bcopy(dst, d, dst, s, c)
d += c
n -= c
end
end
end
end
-- decompress(src, offset?, length?, outSize?, opts?) -> buffer | nil, Err: one block. With outSize the output must be
-- exactly that long (CORRUPT otherwise); without it the output grows up to opts.maxBytes.
function Lz4.decompress(src: buffer | string, offset: number?, length: number?, outSize: number?, opts: Options?): (buffer?, Err.Err?)
local b, o, l, aerr = Bytes.span("Lz4.decompress", src, offset, length)
if not b then
return nil, aerr
end
if outSize ~= nil then
if type(outSize) ~= "number" or outSize < 0 or outSize % 1 ~= 0 then
return nil, Err.new(Err.ARG, "Lz4.decompress: bad outSize")
end
local out = bcreate(outSize)
local e, msg = Lz4.decodeInto(b, o, o + l, out, 0, outSize)
if not e then
return nil, Err.from(msg, o)
end
if e ~= outSize then
return nil, Err.new(Err.CORRUPT, string.format("block decodes to %d bytes, expected %d", e, outSize), o)
end
return out, nil
end
local max = (opts and opts.maxBytes) or 2 ^ 28
local size = math.min(math.max(l * 4, 256), max)
while true do
local out = bcreate(size)
local e, msg = Lz4.decodeInto(b, o, o + l, out, 0, size)
if e then
local res = bcreate(e)
bcopy(res, 0, out, 0, e)
return res, nil
end
if not (msg and string.sub(msg, 1, 6) == "limit:") then
return nil, Err.from(msg, o)
end
if size >= max then
return nil, Err.new(Err.LIMIT, "output over " .. max .. " bytes", o)
end
size = math.min(size * 4, max)
end
end
-- ------------------------------------------------------------------------------------------------ encode
-- bound(n) -> the largest block n input bytes can produce
function Lz4.bound(n: number): number
return n + n // 255 + 16
end
-- writes a length's 255-run extension at o; returns the next offset
local function extend(dst: buffer, o: number, n: number): number
while n >= 255 do
writeu8(dst, o, 255)
o += 1
n -= 255
end
writeu8(dst, o, n)
return o + 1
end
-- hash(v) -> 1 .. HASH_SIZE: Knuth's multiplicative hash (v * 2654435761 mod 2^32, top bits), exact in doubles
local function hash(v: number): number
local vl, vh = band(v, 0xFFFF), rshift(v, 16)
local mid = (vh * 0x79B1 + vl * 0x9E37) % 65536
return ((vl * 0x79B1 + mid * 65536) % 4294967296) // (2 ^ (32 - HASH_BITS)) + 1
end
local hashTable: { number } = table.create(HASH_SIZE, -1e9)
-- encodeInto(src, p, n, dst, d) -> the block's length: src[p, p + n) compressed to dst[d ..] (room for bound(n))
function Lz4.encodeInto(src: buffer, p: number, n: number, dst: buffer, d: number): number
local op = d
local anchor = p
local iend = p + n
local ht = hashTable
for i = 1, HASH_SIZE do
ht[i] = -1e9
end
if n >= MFLIMIT + 1 then
local mflimit = iend - MFLIMIT -- a match starts before this
local matchEnd = iend - LASTLITERALS -- and ends at or before this
local ip = p
local skip = 64
while ip < mflimit do
local v = readu32(src, ip)
local h = hash(v)
local ref = ht[h]
ht[h] = ip
if ref >= p and ip - ref <= MAX_OFFSET and readu32(src, ref) == v then
-- back over equal bytes before the match (into the pending literals)
while ip > anchor and ref > p and readu8(src, ip - 1) == readu8(src, ref - 1) do
ip -= 1
ref -= 1
end
local a = ip + MINMATCH
local bpos = ref + MINMATCH
while a + 4 <= matchEnd and readu32(src, a) == readu32(src, bpos) do
a += 4
bpos += 4
end
while a < matchEnd and readu8(src, a) == readu8(src, bpos) do
a += 1
bpos += 1
end
local ml = a - ip
local lit = ip - anchor
local tok = op
op += 1
local tl = if lit >= 15 then 15 else lit
if lit >= 15 then
op = extend(dst, op, lit - 15)
end
if lit > 0 then
bcopy(dst, op, src, anchor, lit)
op += lit
end
writeu16(dst, op, ip - ref)
op += 2
local m = ml - MINMATCH
local tm = if m >= 15 then 15 else m
if m >= 15 then
op = extend(dst, op, m - 15)
end
writeu8(dst, tok, tl * 16 + tm)
ip = a
anchor = ip
skip = 64
-- index the position just before the next one (better ratio at no cost)
if ip - 2 >= p and ip - 2 < mflimit then
local w = readu32(src, ip - 2)
ht[hash(w)] = ip - 2
end
else
ip += rshift(skip, 6) -- step up over incompressible data (the reference's acceleration)
skip += 1
end
end
end
-- the last literals
local lit = iend - anchor
local tok = op
op += 1
if lit >= 15 then
op = extend(dst, op, lit - 15)
writeu8(dst, tok, 0xF0)
else
writeu8(dst, tok, lit * 16)
end
if lit > 0 then
bcopy(dst, op, src, anchor, lit)
op += lit
end
return op - d
end
-- compress(src, offset?, length?) -> buffer (one block) | nil, Err
function Lz4.compress(src: buffer | string, offset: number?, length: number?): (buffer?, Err.Err?)
local b, o, l, aerr = Bytes.span("Lz4.compress", src, offset, length)
if not b then
return nil, aerr
end
local tmp = bcreate(Lz4.bound(l))
local n = Lz4.encodeInto(b, o, l, tmp, 0)
local out = bcreate(n)
bcopy(out, 0, tmp, 0, n)
return out, nil
end
return Lz4
@@ -0,0 +1,319 @@
--!strict
--!native
--!optimize 2
-- codecs/compress/UnixCompress: the LZW of Unix compress (.Z files: magic 1F 9D, a flags byte with the maximum code
-- width 9..16 and the block mode bit), decode and encode. A codec (layer 3): archive/z builds on it. Codes are
-- LSB-first, 9 bits wide at the start; the width grows when the next free code passes 2^width - 1 (up to the
-- maximum), and in block mode code 256 clears the table. compress writes codes in groups of eight: when the width
-- changes or a CLEAR is read, the rest of the current group (counted from the previous change) is skipped. The encoder
-- reproduces ncompress 5.0 bit for bit: greedy longest match, a full table frozen until the compression ratio checked
-- every 10000 input bytes drops, then a CLEAR. Written from the ncompress sources (public domain, The Unlicense: read
-- for the format and the encoder's ratio check; licenses/ncompress-UNLICENSE.txt). Never throws.
--
-- local out, err = UnixCompress.decompress(buf, offset?, length?, { maxBytes = 2^28 }) -- a whole .Z file
-- local z = UnixCompress.compress(buf, offset?, length?, { maxBits = 16 }) -- -> a .Z file
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local UnixCompress = {}
export type DecodeOptions = { maxBytes: number? } -- refuse output larger than this (default 2^30)
export type EncodeOptions = { maxBits: number? } -- 9..16, default 16
local readu8, writeu8, readu32, writeu32 = buffer.readu8, buffer.writeu8, buffer.readu32, buffer.writeu32
local band, bor, rshift, lshift = bit32.band, bit32.bor, bit32.rshift, bit32.lshift
local bcreate, bcopy, blen = buffer.create, buffer.copy, buffer.len
local MAXCODES = 65536
local CHECK_GAP = 10000
-- decoder tables (per call state lives in locals; the tables are reused: decode never yields)
local prefix = bcreate(MAXCODES * 4) -- u32: the code an entry extends
local suffix = bcreate(MAXCODES) -- u8: its last byte
local first = bcreate(MAXCODES) -- u8: its first byte
local length = bcreate(MAXCODES * 4) -- u32: its length
-- ------------------------------------------------------------------------------------------------ decode
-- decompress(buf, offset?, length?, opts?) -> buffer | nil, Err
function UnixCompress.decompress(buf: buffer | string, offset: number?, len: number?, opts: DecodeOptions?): (buffer?, Err.Err?)
local b, o, n, aerr = Bytes.span("UnixCompress.decompress", buf, offset, len)
if not b then
return nil, aerr
end
local maxBytes = (opts and opts.maxBytes) or 2 ^ 30
if n < 3 then
return nil, Err.new(Err.TRUNCATED, "header past the end", o)
end
if readu8(b, o) ~= 0x1F or readu8(b, o + 1) ~= 0x9D then
return nil, Err.new(Err.CORRUPT, "bad magic", o)
end
local flags = readu8(b, o + 2)
local maxbits = band(flags, 0x1F)
local block = band(flags, 0x80) ~= 0
if maxbits < 9 or maxbits > 16 then
return nil, Err.new(Err.UNSUPPORTED, "maximum code width " .. maxbits, o + 2)
end
if band(flags, 0x60) ~= 0 then
return nil, Err.new(Err.UNSUPPORTED, "reserved flag bits set", o + 2)
end
local maxmax = lshift(1, maxbits)
for i = 0, 255 do
writeu32(prefix, i * 4, 0)
writeu8(suffix, i, i)
writeu8(first, i, i)
writeu32(length, i * 4, 1)
end
local cap = math.min(math.max(n * 3, 1024), maxBytes)
local out = bcreate(cap)
local op = 0
local totalBits = (n - 3) * 8
local base = o + 3
local pos = 0 -- bit position from the first code
local gbase = 0 -- where the current group sequence starts
local nbits = 9
local mask = 511
local maxcode = 511
local freeEnt = if block then 257 else 256
local prev = -1
while pos + nbits <= totalBits do
if freeEnt > maxcode then
local g = nbits * 8
pos = gbase + (pos - gbase + g - 1) // g * g
gbase = pos
nbits += 1
maxcode = if nbits == maxbits then maxmax else lshift(1, nbits) - 1
mask = lshift(1, nbits) - 1
continue
end
-- the code: up to 23 bits from three bytes
local q = base + rshift(pos, 3)
local acc = readu8(b, q)
if q + 1 < o + n then
acc = bor(acc, lshift(readu8(b, q + 1), 8))
end
if q + 2 < o + n then
acc = bor(acc, lshift(readu8(b, q + 2), 16))
end
local c = band(rshift(acc, band(pos, 7)), mask)
pos += nbits
if c == 256 and block then
local g = nbits * 8
pos = gbase + (pos - gbase + g - 1) // g * g
gbase = pos
nbits = 9
mask = 511
maxcode = 511
freeEnt = 257
prev = -1
continue
end
local l
if prev < 0 then
if c >= 256 then
return nil, Err.new(Err.CORRUPT, "first code is not a literal", base + rshift(pos, 3))
end
l = 1
elseif c < freeEnt then
l = readu32(length, c * 4)
elseif c == freeEnt then
l = readu32(length, prev * 4) + 1
else
return nil, Err.new(Err.CORRUPT, "code past the table", base + rshift(pos, 3))
end
if op + l > cap then
if op + l > maxBytes then
return nil, Err.new(Err.LIMIT, "output over " .. maxBytes .. " bytes")
end
local ncap = math.min(math.max(cap * 2, op + l), maxBytes)
local nb = bcreate(ncap)
bcopy(nb, 0, out, 0, op)
out, cap = nb, ncap
end
-- the new entry (prev + first byte of c's string) before the copy: KwKwK reads it
if prev >= 0 and freeEnt < maxmax then
local f = if c == freeEnt then readu8(first, prev) else readu8(first, c)
writeu32(prefix, freeEnt * 4, prev)
writeu8(suffix, freeEnt, f)
writeu8(first, freeEnt, readu8(first, prev))
writeu32(length, freeEnt * 4, readu32(length, prev * 4) + 1)
freeEnt += 1
elseif prev >= 0 then
if c == freeEnt then
return nil, Err.new(Err.CORRUPT, "code past the table", base + rshift(pos, 3))
end
end
local p = op + l - 1
local k = c
while p >= op do
writeu8(out, p, readu8(suffix, k))
k = readu32(prefix, k * 4)
p -= 1
end
op += l
prev = c
end
local res = bcreate(op)
bcopy(res, 0, out, 0, op)
return res, nil
end
-- ------------------------------------------------------------------------------------------------ encode
local HSIZE = 1 * 131072 -- open addressing over (prefix << 8 | byte) + 1 keys: twice the 65536 entries
local hkey = bcreate(HSIZE * 4)
local hval = bcreate(HSIZE * 4)
-- compress(buf, offset?, length?, opts?) -> a .Z file (block mode) | nil, Err
function UnixCompress.compress(buf: buffer | string, offset: number?, len: number?, opts: EncodeOptions?): (buffer?, Err.Err?)
local b, o, n, aerr = Bytes.span("UnixCompress.compress", buf, offset, len)
if not b then
return nil, aerr
end
local maxbits = (opts and opts.maxBits) or 16
if type(maxbits) ~= "number" or maxbits < 9 or maxbits > 16 or maxbits % 1 ~= 0 then
return nil, Err.new(Err.ARG, "maxBits must be 9..16")
end
-- at most 17 bits per input byte, plus group padding (< one group per width change / clear)
local cap = 3 + n * 2 + 64
local out = bcreate(cap)
writeu8(out, 0, 0x1F)
writeu8(out, 1, 0x9D)
writeu8(out, 2, bor(maxbits, 0x80))
local outbits = 24
local boff = 24
local acc, nb = 0, 0 -- pending bits not yet written (below 2^24)
local nbits = 9
local extcode = 513
local maxmax = lshift(1, maxbits)
local stcode = true
local freeEnt = 257
local ratio = 0
local checkpoint = CHECK_GAP
buffer.fill(hkey, 0, 0, HSIZE * 4)
local function put(code: number)
acc = bor(acc, lshift(code, nb))
nb += nbits
outbits += nbits
while nb >= 8 do
local q = rshift(outbits - nb, 3)
if q < cap then
writeu8(out, q, band(acc, 255))
end
acc = rshift(acc, 8)
nb -= 8
end
end
local function align()
-- round outbits up to a whole group of nbits-bit codes since boff; the skipped bits are zeros
local g = nbits * 8
local nbits2 = boff + (outbits - boff + g - 1) // g * g
if nb > 0 then
local q = rshift(outbits - nb, 3)
if q < cap then
writeu8(out, q, band(acc, 255))
end
end
acc, nb = 0, 0
outbits = nbits2
boff = nbits2
end
if n == 0 then
local res = bcreate(3)
bcopy(res, 0, out, 0, 3)
return res, nil
end
local ent = readu8(b, o)
local e = o + n
local i = o + 1
-- checks happen with a one-byte current string, right after an output (and at the start)
local function checks(consumed: number)
if freeEnt >= extcode then
if nbits < maxbits then
align()
nbits += 1
extcode = if nbits < maxbits then lshift(1, nbits) + 1 else lshift(1, nbits)
else
extcode = math.huge
stcode = false
end
end
if not stcode and consumed >= checkpoint then
checkpoint = consumed + CHECK_GAP
local outBytes = rshift(outbits, 3)
local rat
if consumed > 0x7FFFFF then
local d = rshift(outBytes, 8)
rat = if d == 0 then 0x7FFFFFFF else consumed // d
else
rat = (consumed * 256) // outBytes
end
if rat >= ratio then
ratio = rat
else
ratio = 0
buffer.fill(hkey, 0, 0, HSIZE * 4)
put(256)
align()
nbits = 9
extcode = 513
freeEnt = 257
stcode = true
end
end
end
checks(1)
while i < e do
local c = readu8(b, i)
i += 1
local key = ent * 256 + c + 1
local h = band(ent * 4099 + c * 131 + rshift(ent, 5), HSIZE - 1)
local found = -1
while true do
local k = readu32(hkey, h * 4)
if k == 0 then
break
elseif k == key then
found = readu32(hval, h * 4)
break
end
h = band(h + 1, HSIZE - 1)
end
if found >= 0 then
ent = found
else
put(ent)
if stcode then
writeu32(hkey, h * 4, key)
writeu32(hval, h * 4, freeEnt)
freeEnt += 1
end
ent = c
checks(i - o)
end
if rshift(outbits, 3) + 8 > cap then
-- grow (rare: only incompressible input passes 2 bytes per byte)
local ncap = cap * 2
local nbuf = bcreate(ncap)
bcopy(nbuf, 0, out, 0, cap)
out, cap = nbuf, ncap
end
end
put(ent)
if nb > 0 then
local q = rshift(outbits - nb, 3)
if q < cap then
writeu8(out, q, band(acc, 255))
end
end
local size = rshift(outbits + 7, 3)
local res = bcreate(size)
bcopy(res, 0, out, 0, math.min(size, cap))
return res, nil
end
-- isCompress(buf, offset?) -> true when the bytes at offset start a .Z file
function UnixCompress.isCompress(b: buffer, o: number?): boolean
local p = o or 0
return p + 3 <= blen(b) and readu8(b, p) == 0x1F and readu8(b, p + 1) == 0x9D
end
return UnixCompress
+72
View File
@@ -0,0 +1,72 @@
--!strict
--!native
--!optimize 2
-- codecs/compress/Xxh32: XXH32 of a buffer range (any seed), for the LZ4 frame format's header, block and content
-- checksums. 32 x 32 -> 32 products split one operand into 16-bit limbs so every partial product is exact in a double.
-- From the xxHash specification (Yann Collet, BSD-2); no code copied. Never throws (the range is clamped to the buffer).
--
-- local h = Xxh32.hash(buf, offset?, length?, seed?) -- a number in 0 .. 2^32 - 1
local Xxh32 = {}
local bxor, bor, lshift, rshift = bit32.bxor, bit32.bor, bit32.lshift, bit32.rshift
local readu8, readu32 = buffer.readu8, buffer.readu32
local T32 = 4294967296
local P1, P2, P3, P4, P5 = 0x9E3779B1, 0x85EBCA77, 0xC2B2AE3D, 0x27D4EB2F, 0x165667B1
-- a * b mod 2^32 (a, b below 2^32)
local function mul(a: number, b: number): number
local a0 = a % 65536
local a1 = (a - a0) / 65536
return (a0 * b + ((a1 * b) % 65536) * 65536) % T32
end
local function rotl(x: number, r: number): number
return bor(lshift(x, r), rshift(x, 32 - r))
end
local function round(acc: number, lane: number): number
return mul(rotl((acc + mul(lane, P2)) % T32, 13), P1)
end
-- hash(buf, offset?, length?, seed?) -> XXH32
function Xxh32.hash(b: buffer, offset: number?, length: number?, seed: number?): number
local n0 = buffer.len(b)
local o = math.clamp(offset or 0, 0, n0)
local n = math.clamp(length or (n0 - o), 0, n0 - o)
local s = (seed or 0) % T32
local p = o
local e = o + n
local h
if n >= 16 then
local v1 = (s + P1 + P2) % T32
local v2 = (s + P2) % T32
local v3 = s
local v4 = (s - P1) % T32
local last = e - 16
while p <= last do
v1 = round(v1, readu32(b, p))
v2 = round(v2, readu32(b, p + 4))
v3 = round(v3, readu32(b, p + 8))
v4 = round(v4, readu32(b, p + 12))
p += 16
end
h = (rotl(v1, 1) + rotl(v2, 7) + rotl(v3, 12) + rotl(v4, 18)) % T32
else
h = (s + P5) % T32
end
h = (h + n) % T32
while p + 4 <= e do
h = mul(rotl((h + mul(readu32(b, p), P3)) % T32, 17), P4)
p += 4
end
while p < e do
h = mul(rotl((h + readu8(b, p) * P5) % T32, 11), P1)
p += 1
end
h = mul(bxor(h, rshift(h, 15)), P2)
h = mul(bxor(h, rshift(h, 13)), P3)
return bxor(h, rshift(h, 16))
end
return Xxh32
+33
View File
@@ -13,6 +13,7 @@
-- (a .tar.gz loads as the tar inside). Never throws: read of a missing entry or a failed loader returns nil, Err.
local Err = require("@formats/core/Err")
local Types = require("@formats/Types")
local Tar = require("@formats/containers/Tar")
local Archive = {}
@@ -176,6 +177,38 @@ function Archive.files(value: any, name: string?): ({ { name: string, data: buff
return out, nil
end
-- streamData(value) -> what a single-stream encoder compresses: a buffer / string as it is, an Archive's one file, or
-- a tar of the Archive's entries (files, directories, symlinks with their mode / mtime) | nil, Err
function Archive.streamData(value: any): (buffer?, Err.Err?)
if type(value) == "buffer" then
return value, nil
elseif type(value) == "string" then
return buffer.fromstring(value), nil
end
local items = Archive.entries(value)
if not items then
return nil, Err.new(Err.ARG, "expected an Archive, a buffer or a string")
end
if #items == 1 and not items[1].entry.dir then
return items[1].read()
end
local list = {}
for _, it in items do
local e: any = it.entry
local data: buffer? = nil
if not e.dir and (e.type == nil or e.type == "0") then
local b, err = it.read()
if not b then
return nil, err
end
data = b
end
local typ = if type(e.type) == "string" and #e.type == 1 then e.type else nil
table.insert(list, { name = e.name, data = data, dir = e.dir, type = typ, link = e.link, mtime = e.mtime, mode = e.mode })
end
return Tar.write(list)
end
-- fromDos(stamp) -> unix seconds | nil: an MS-DOS date and time (stamp = date * 65536 + time, as LHA / ARJ / ZIP store
-- them little endian; local time without a zone, read as UTC); nil for a zero or invalid date
function Archive.fromDos(stamp: number): number?
+440
View File
@@ -0,0 +1,440 @@
--!strict
-- containers/Cpio: cpio archives, read and written. Reading: SVR4 "newc" (070701, hex fields, 4-byte alignment),
-- "crc" (070702: newc plus a byte-sum of the data, verified), POSIX.1 "odc" (070707, octal fields, no padding) and the
-- old binary format in both byte orders (magic 070707 as a little / big endian u16, 2-byte alignment), up to the
-- TRAILER!!! entry. Hard links: newc / crc store the data once, on the last link of an inode (as GNU cpio and bsdtar
-- write it); every link of the group reads that data, and the later links name the first one in `hardlink`. Symlinks
-- hold their target as data (`link`). Writing: newc (default), crc or odc, padded to opts.block bytes (default 512, as
-- GNU cpio). Written from the cpio(5) manual pages (libarchive, GNU cpio) and POSIX.1-1988 (odc); no code ported. The
-- archive formats (archive/cpio, archive/rpm's payload) build on it.
--
-- local entries, info = Cpio.read(buf, offset?, length?, opts?) -- { Entry } , { format = "newc" | ... } | nil, Err
-- local out, err = Cpio.write({ { name = "a.txt", data = buf, mode = 0o100644, mtime = 0 } }, { format = "odc" })
--
-- Never throws: bad data returns nil, Err.
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Cpio = {}
export type Entry = {
name: string,
size: number, -- data bytes (a symlink's target length; a hard link: the shared data's size)
mode: number, -- the whole st_mode (file type bits included)
type: string, -- tar type letters: "0" file, "5" directory, "2" symlink, "3" char device, "4" block device, "6" fifo, "s" socket
dir: boolean,
uid: number,
gid: number,
nlink: number,
mtime: number,
ino: number,
devmajor: number,
devminor: number,
rdevmajor: number,
rdevminor: number,
link: string?, -- symlink target
hardlink: string?, -- the first entry of this entry's hard link group (for the later links)
offset: number, -- absolute offset of the data in the buffer
check: number?, -- crc format: the stored byte sum
}
export type ReadOptions = {
maxEntries: number?, -- default 1e6
verify: boolean?, -- crc format: check the byte sums (default true)
}
export type Info = { format: string } -- "newc" | "crc" | "odc" | "bin" | "binbe"
local S_IFMT = 0xF000
local TYPES: { [number]: string } = {
[0x8000] = "0",
[0x4000] = "5",
[0xA000] = "2",
[0x2000] = "3",
[0x6000] = "4",
[0x1000] = "6",
[0xC000] = "s",
}
local MODES: { [string]: number } = {}
for m, t in TYPES do
MODES[t] = m
end
Cpio.TYPE_MODE = MODES -- type letter -> S_IFMT bits
Cpio.TYPE_OF = TYPES -- S_IFMT bits -> type letter
local TRAILER = "TRAILER!!!"
-- format(buf, offset) -> "newc" | "crc" | "odc" | "bin" | "binbe" | nil: the format of the header at offset
function Cpio.format(b: buffer, o: number): string?
local n = buffer.len(b)
if o + 6 <= n then
local m = buffer.readstring(b, o, 6)
if m == "070701" then
return "newc"
elseif m == "070702" then
return "crc"
elseif m == "070707" then
return "odc"
end
end
if o + 2 <= n then
local v = buffer.readu16(b, o)
if v == 0x71C7 then
return "bin"
elseif v == 0xC771 then
return "binbe"
end
end
return nil
end
-- a fixed-width number field: hex (newc) or octal (odc); nil when not all digits
local function num(b: buffer, o: number, n: number, base: number): number?
local s = buffer.readstring(b, o, n)
if base == 16 then
if not string.find(s, "^%x+$") then
return nil
end
elseif not string.find(s, "^[0-7]+$") then
return nil
end
return tonumber(s, base)
end
-- checksum(buf, offset, n) -> the crc format's sum of the data bytes (mod 2^32)
function Cpio.checksum(b: buffer, o: number, n: number): number
local s = 0
local i = o
local e = o + n
while i + 4 <= e do
local v = buffer.readu32(b, i)
s += bit32.band(v, 255) + bit32.band(bit32.rshift(v, 8), 255) + bit32.band(bit32.rshift(v, 16), 255) + bit32.rshift(v, 24)
i += 4
end
while i < e do
s += buffer.readu8(b, i)
i += 1
end
return s % 4294967296
end
-- one header at p -> entry fields, header end (the name's start), name size, data size | nil, Err
local function header(b: buffer, p: number, e: number, fmt: string): (any, Err.Err?)
local h: any = {}
local nameAt
if fmt == "newc" or fmt == "crc" then
if p + 110 > e then
return nil, Err.new(Err.TRUNCATED, "header past the end", p)
end
local f = {} :: { number }
for i = 1, 13 do
local v = num(b, p + 6 + (i - 1) * 8, 8, 16)
if not v then
return nil, Err.new(Err.CORRUPT, "bad header field", p + 6 + (i - 1) * 8)
end
f[i] = v
end
h.ino, h.mode, h.uid, h.gid, h.nlink, h.mtime, h.size = f[1], f[2], f[3], f[4], f[5], f[6], f[7]
h.devmajor, h.devminor, h.rdevmajor, h.rdevminor, h.namesize, h.check = f[8], f[9], f[10], f[11], f[12], f[13]
nameAt = p + 110
elseif fmt == "odc" then
if p + 76 > e then
return nil, Err.new(Err.TRUNCATED, "header past the end", p)
end
local widths = { 6, 6, 6, 6, 6, 6, 6, 11, 6, 11 }
local f = {} :: { number }
local q = p + 6
for i, w in widths do
local v = num(b, q, w, 8)
if not v then
return nil, Err.new(Err.CORRUPT, "bad header field", q)
end
f[i] = v
q += w
end
h.ino, h.mode, h.uid, h.gid, h.nlink, h.mtime, h.namesize, h.size = f[2], f[3], f[4], f[5], f[6], f[8], f[9], f[10]
h.devmajor, h.devminor = bit32.rshift(f[1], 8), bit32.band(f[1], 255)
h.rdevmajor, h.rdevminor = bit32.rshift(f[7], 8), bit32.band(f[7], 255)
nameAt = p + 76
else
if p + 26 > e then
return nil, Err.new(Err.TRUNCATED, "header past the end", p)
end
local be = fmt == "binbe"
local function u16(i: number): number
local v = buffer.readu16(b, p + i * 2)
return if be then bit32.bor(bit32.rshift(v, 8), bit32.band(bit32.lshift(v, 8), 0xFF00)) else v
end
local dev, rdev = u16(1), u16(7)
h.ino, h.mode, h.uid, h.gid, h.nlink = u16(2), u16(3), u16(4), u16(5), u16(6)
h.mtime = u16(8) * 65536 + u16(9)
h.namesize = u16(10)
h.size = u16(11) * 65536 + u16(12)
h.devmajor, h.devminor = bit32.rshift(dev, 8), bit32.band(dev, 255)
h.rdevmajor, h.rdevminor = bit32.rshift(rdev, 8), bit32.band(rdev, 255)
nameAt = p + 26
end
if h.namesize < 1 or nameAt + h.namesize > e then
return nil, Err.new(if h.namesize < 1 then Err.CORRUPT else Err.TRUNCATED, "bad name size", nameAt)
end
h.nameAt = nameAt
return h, nil
end
-- read(buf, offset?, length?, opts?) -> { Entry }, Info | nil, Err
function Cpio.read(b: buffer, offset: number?, length: number?, opts: ReadOptions?): ({ Entry }?, any)
local o = offset or 0
local e = math.min(buffer.len(b), o + (length or (buffer.len(b) - o)))
local maxEntries = (opts and opts.maxEntries) or 1e6
local verify = not (opts and opts.verify == false)
local fmt = Cpio.format(b, o)
if not fmt or o >= e then
return nil, Err.new(Err.CORRUPT, "not a cpio archive", o)
end
local align = if fmt == "newc" or fmt == "crc" then 4 elseif fmt == "odc" then 1 else 2
local out: { Entry } = {}
local groups: { [string]: { Entry } } = {}
local p = o
while true do
if p >= e then
return nil, Err.new(Err.TRUNCATED, "no TRAILER!!! entry", p)
end
if Cpio.format(b, p) ~= fmt then
return nil, Err.new(Err.CORRUPT, "bad header magic", p)
end
local h, herr = header(b, p, e, fmt)
if not h then
return nil, herr
end
local name = buffer.readstring(b, h.nameAt, h.namesize)
local z = string.find(name, "\0", 1, true)
if z then
name = string.sub(name, 1, z - 1)
end
local data = h.nameAt + h.namesize
data = o + (data - o + align - 1) // align * align
if name == TRAILER then
break
end
if data + h.size > e then
return nil, Err.new(Err.TRUNCATED, "entry " .. name .. " data past the end", data)
end
local typ = TYPES[bit32.band(h.mode, S_IFMT)] or "0"
local entry: Entry = {
name = name,
size = h.size,
mode = h.mode,
type = typ,
dir = typ == "5",
uid = h.uid,
gid = h.gid,
nlink = h.nlink,
mtime = h.mtime,
ino = h.ino,
devmajor = h.devmajor,
devminor = h.devminor,
rdevmajor = h.rdevmajor,
rdevminor = h.rdevminor,
link = if typ == "2" then buffer.readstring(b, data, h.size) else nil,
hardlink = nil,
offset = data,
check = if fmt == "crc" then h.check else nil,
}
if fmt == "crc" and verify and typ == "0" and Cpio.checksum(b, data, h.size) ~= h.check then
return nil, Err.new(Err.CHECKSUM, "entry " .. name .. ": data checksum mismatch", data)
end
if typ == "0" and h.nlink > 1 then
local key = h.devmajor .. ":" .. h.devminor .. ":" .. h.ino
local g = groups[key]
if not g then
g = {}
groups[key] = g
else
entry.hardlink = g[1].name
end
table.insert(g, entry)
end
table.insert(out, entry)
if #out > maxEntries then
return nil, Err.new(Err.LIMIT, "more than " .. maxEntries .. " entries")
end
p = data + h.size
p = o + (p - o + align - 1) // align * align
end
-- hard links: the links stored without data read the group's data (newc / crc keep it on the last link)
for _, g in groups do
local holder: Entry? = nil
for _, x in g do
if x.size > 0 then
holder = x
end
end
if holder then
for _, x in g do
if x.size == 0 then
x.size, x.offset = holder.size, holder.offset
end
end
end
end
return out, { format = fmt }
end
-- ------------------------------------------------------------------------------------------------ writing
export type WriteEntry = {
name: string,
data: buffer?, -- file data (a symlink: its target, else taken from link)
mode: number?, -- st_mode; permission bits alone get the type bits from type / dir (default 0o644 / 0o755)
type: string?, -- a type letter (see Entry.type); default "0" ("5" for dir)
dir: boolean?,
link: string?, -- symlink target
uid: number?,
gid: number?,
nlink: number?, -- default 1 (2 for directories)
mtime: number?, -- unix seconds (default 0)
ino: number?, -- default: the entry's index (1, 2, ...); hard links share one
devmajor: number?,
devminor: number?,
rdevmajor: number?,
rdevminor: number?,
}
export type WriteOptions = {
format: ("newc" | "crc" | "odc")?, -- default "newc"
block: number?, -- pad the archive to a multiple of this many bytes (default 512; 1 = no padding)
}
local function hex8(v: number): string?
if v < 0 or v % 1 ~= 0 or v >= 4294967296 then
return nil
end
return string.format("%08X", v)
end
local function oct(v: number, w: number): string?
if v < 0 or v % 1 ~= 0 or v >= 8 ^ w then
return nil
end
local s = string.format("%o", v)
return string.rep("0", w - #s) .. s
end
-- write(entries, opts?) -> buffer | nil, Err
function Cpio.write(entries: { WriteEntry }, opts: WriteOptions?): (buffer?, Err.Err?)
local fmt = (opts and opts.format) or "newc"
if fmt ~= "newc" and fmt ~= "crc" and fmt ~= "odc" then
return nil, Err.new(Err.ARG, "format must be newc, crc or odc")
end
local block = (opts and opts.block) or 512
if type(block) ~= "number" or block < 1 or block % 1 ~= 0 then
return nil, Err.new(Err.ARG, "block must be a positive integer")
end
-- newc / crc: a hard link group's data goes on its last link only
local last: { [string]: number } = {}
local prepared: { any } = table.create(#entries)
for i, e in entries do
if type(e) ~= "table" or type(e.name) ~= "string" or e.name == "" then
return nil, Err.new(Err.ARG, "entry " .. i .. ": needs a name")
end
local typ = e.type or (if e.dir then "5" else "0")
local tbits = MODES[typ]
if not tbits then
return nil, Err.new(Err.ARG, "entry " .. e.name .. ": unknown type " .. tostring(typ))
end
local mode = e.mode or (if typ == "5" then 0x1ED elseif typ == "2" then 0x1FF else 0x1A4)
if bit32.band(mode, S_IFMT) == 0 then
mode = bit32.bor(mode, tbits)
end
local data = e.data
if typ == "2" and not data then
data = buffer.fromstring(e.link or "")
elseif typ ~= "0" and typ ~= "2" then
data = nil
end
local nlink = e.nlink or (if typ == "5" then 2 else 1)
local ino = e.ino or i
local p = { e = e, mode = mode, data = data or buffer.create(0), nlink = nlink, ino = ino, typ = typ }
prepared[i] = p
if typ == "0" and nlink > 1 then
last[(e.devmajor or 0) .. ":" .. (e.devminor or 0) .. ":" .. ino] = i
end
end
local w = Bytes.writer(1024)
local function put(name: string, p: any, data: buffer): Err.Err?
local e = p.e
local namesize = #name + 1
local size = buffer.len(data)
if fmt == "odc" then
local dev = (e.devmajor or 0) * 256 + (e.devminor or 0)
local rdev = (e.rdevmajor or 0) * 256 + (e.rdevminor or 0)
local fields = {
oct(dev, 6),
oct(p.ino, 6),
oct(p.mode, 6),
oct(e.uid or 0, 6),
oct(e.gid or 0, 6),
oct(p.nlink, 6),
oct(rdev, 6),
oct(math.floor(e.mtime or 0), 11),
oct(namesize, 6),
oct(size, 11),
}
for k = 1, 10 do
if not fields[k] then
return Err.new(Err.ARG, "entry " .. name .. ": a field does not fit the odc header")
end
end
w:string("070707" .. table.concat(fields :: { string }))
w:string(name)
w:u8(0)
w:bytes(data)
else
local check = if fmt == "crc" and p.typ == "0" then Cpio.checksum(data, 0, size) else 0
local fields = {
hex8(p.ino),
hex8(p.mode),
hex8(e.uid or 0),
hex8(e.gid or 0),
hex8(p.nlink),
hex8(math.floor(e.mtime or 0)),
hex8(size),
hex8(e.devmajor or 0),
hex8(e.devminor or 0),
hex8(e.rdevmajor or 0),
hex8(e.rdevminor or 0),
hex8(namesize),
hex8(check),
}
for k = 1, 13 do
if not fields[k] then
return Err.new(Err.ARG, "entry " .. name .. ": a field does not fit the newc header")
end
end
w:string((if fmt == "crc" then "070702" else "070701") .. table.concat(fields :: { string }))
w:string(name)
w:u8(0)
w:fill(0, (4 - (110 + namesize) % 4) % 4)
w:bytes(data)
w:fill(0, (4 - size % 4) % 4)
end
return nil
end
for i, p in prepared do
local data = p.data
if fmt ~= "odc" and p.typ == "0" and p.nlink > 1 then
local e = p.e
if last[(e.devmajor or 0) .. ":" .. (e.devminor or 0) .. ":" .. p.ino] ~= i then
data = buffer.create(0)
end
end
local err = put(p.e.name, p, data)
if err then
return nil, err
end
end
local err = put(TRAILER, { e = {}, ino = 0, mode = 0, nlink = 1 }, buffer.create(0))
if err then
return nil, err
end
w:fill(0, (block - w.pos % block) % block)
return w:finish(), nil
end
return Cpio
+525
View File
@@ -0,0 +1,525 @@
--!strict
-- containers/Iso9660: ISO 9660 (ECMA-119) CD / DVD images, read. The volume descriptors from sector 16 (primary,
-- supplementary, boot record, terminator); the directory tree walked through directory records (records never cross
-- a sector; multi-extent files are joined; associated files skipped; interleaved files listed, their read is
-- Err.UNSUPPORTED). Three name sets: plain ISO 9660 (";1" versions and a lone trailing "." dropped), Joliet (UCS-2 names
-- of a supplementary descriptor with the %/@, %/C or %/E escape) and Rock Ridge (SUSP 1.12 / RRIP 1.12 in the
-- primary tree: SP, CE continuation areas, NM names, PX modes / links / ids, PN devices, TF times, SL symlinks, CL / RE
-- / PL relocated deep directories, with the rr_moved directory hidden when it ends up empty). The tree used is Rock
-- Ridge when present, else Joliet, else plain (opts.prefer overrides). El Torito: the boot record's catalog
-- (validation entry, initial / default entry) in info.boot. Written from ECMA-119, the SUSP / RRIP 1.12 and Joliet
-- specifications and El Torito 1.0; no code ported. Not supported: zisofs (ZF) compressed files (listed; read returns
-- the stored bytes), UDF, writing.
--
-- local entries, info = Iso9660.read(buf, offset?, length?, opts?) -- { Entry }, Info | nil, Err
-- local data, err = Iso9660.extract(buf, base, entry) -- the entry's bytes (a copy of its extents)
local Err = require("@formats/core/Err")
local Types = require("@formats/Types")
local Text = require("@formats/codecs/text/Text")
local Iso9660 = {}
export type Extent = { at: number, size: number } -- byte offset (from the image start) and length
export type Entry = {
name: string, -- the path, "/" separated, no leading "/"
dir: boolean,
size: number,
extents: { Extent },
mtime: number?, -- unix seconds
type: string, -- tar letters: "0" file, "5" directory, "2" symlink, "3" / "4" devices, "6" fifo, "s" socket
mode: number?, -- Rock Ridge: the permission bits
uid: number?,
gid: number?,
nlink: number?,
link: string?, -- Rock Ridge symlink target
rdev: number?, -- Rock Ridge PN: high * 2^32 + low
hidden: boolean?,
interleaved: boolean?,
zisofs: boolean?,
}
export type ReadOptions = {
prefer: ("rockridge" | "joliet" | "iso9660")?, -- the name set (default: Rock Ridge, else Joliet, else plain)
maxEntries: number?, -- default 1e6
}
local SECTOR = 2048
local S_TYPES: { [number]: string } = { [0x8000] = "0", [0x4000] = "5", [0xA000] = "2", [0x2000] = "3", [0x6000] = "4", [0x1000] = "6", [0xC000] = "s" }
-- ------------------------------------------------------------------------------------------------ fields
local function u16(b: buffer, o: number): number
return buffer.readu16(b, o)
end
local function u32(b: buffer, o: number): number
return buffer.readu32(b, o)
end
local function str(b: buffer, o: number, n: number): string
return (string.gsub(buffer.readstring(b, o, n), "[ %z]+$", ""))
end
-- a 7-byte directory record date -> unix seconds
local function recDate(b: buffer, o: number): number?
local y = buffer.readu8(b, o)
local m, d = buffer.readu8(b, o + 1), buffer.readu8(b, o + 2)
if m < 1 or m > 12 or d < 1 or d > 31 then
return nil
end
local off = buffer.readi8(b, o + 6)
return Types.Date.toUnix({ kind = "datetime", year = 1900 + y, month = m, day = d, hour = buffer.readu8(b, o + 3), minute = buffer.readu8(b, o + 4), second = buffer.readu8(b, o + 5), offset = off * 15 })
end
-- a 17-byte descriptor date ("YYYYMMDDHHMMSScc" + offset) -> unix seconds
local function longDate(b: buffer, o: number): number?
local s = buffer.readstring(b, o, 16)
local y, mo, d, h, mi, se = string.match(s, "^(%d%d%d%d)(%d%d)(%d%d)(%d%d)(%d%d)(%d%d)%d%d$")
if not y or tonumber(y) == 0 then
return nil
end
local off = buffer.readi8(b, o + 16)
return Types.Date.toUnix({ kind = "datetime", year = tonumber(y), month = tonumber(mo), day = tonumber(d), hour = tonumber(h), minute = tonumber(mi), second = tonumber(se), offset = off * 15 })
end
-- ------------------------------------------------------------------------------------------------ SUSP / Rock Ridge
type Susp = { [string]: any }
-- the SUSP entries of a system use area (following CE continuation areas) -> { { sig, at, len } }
local function suspEntries(b: buffer, base: number, limit: number, o: number, e: number, bs: number, budget: { number }): { { any } }
local out = {}
while o + 4 <= e do
local sig = buffer.readstring(b, o, 2)
local len = buffer.readu8(b, o + 2)
if len < 4 or o + len > e then
break
end
if sig == "ST" then
break
elseif sig == "CE" and len >= 28 then
local blk, off, n = u32(b, o + 4), u32(b, o + 12), u32(b, o + 20)
local at = base + blk * bs + off
budget[1] -= 1
if budget[1] < 0 or at < base or at + n > limit or n > 65536 then
break
end
-- the rest of this area first, then the continuation (it holds what did not fit)
local rest = suspEntries(b, base, limit, o + len, e, bs, budget)
for _, x in rest do
table.insert(out, x)
end
local cont = suspEntries(b, base, limit, at, at + n, bs, budget)
for _, x in cont do
table.insert(out, x)
end
return out
end
table.insert(out, { sig, o, len })
o += len
end
return out
end
-- Rock Ridge fields of a record: { name, mode, uid, gid, nlink, mtime, link, rdev, child, relocated, zisofs }
local function rockRidge(b: buffer, base: number, limit: number, o: number, e: number, bs: number): Susp
local rr: Susp = {}
local name: { string }? = nil
local slParts: { string }? = nil
local slRoot = false
local slCont = false
for _, x in suspEntries(b, base, limit, o, e, bs, { 32 }) do
local sig, at, len = x[1], x[2], x[3]
if sig == "NM" and len >= 5 then
local flags = buffer.readu8(b, at + 4)
if bit32.band(flags, 6) == 0 then
name = name or {}
table.insert(name :: { string }, buffer.readstring(b, at + 5, len - 5))
end
elseif sig == "PX" and len >= 36 then
rr.mode, rr.nlink, rr.uid, rr.gid = u32(b, at + 4), u32(b, at + 12), u32(b, at + 20), u32(b, at + 28)
elseif sig == "PN" and len >= 20 then
rr.rdev = u32(b, at + 4) * 4294967296 + u32(b, at + 12)
elseif sig == "TF" and len >= 5 then
local flags = buffer.readu8(b, at + 4)
local w = if bit32.band(flags, 0x80) ~= 0 then 17 else 7
local q = at + 5
for bit = 0, 6 do
if bit32.band(flags, bit32.lshift(1, bit)) ~= 0 then
if q + w > at + len then
break
end
if bit == 1 then
rr.mtime = if w == 17 then longDate(b, q) else recDate(b, q)
end
q += w
end
end
elseif sig == "SL" and len >= 5 then
slParts = slParts or {}
local parts = slParts :: { string }
local q = at + 5
while q + 2 <= at + len do
local cf, cl = buffer.readu8(b, q), buffer.readu8(b, q + 1)
if q + 2 + cl > at + len then
break
end
local piece = if bit32.band(cf, 2) ~= 0 then "." elseif bit32.band(cf, 4) ~= 0 then ".." else buffer.readstring(b, q + 2, cl)
if bit32.band(cf, 8) ~= 0 then
slRoot = #parts == 0
piece = ""
end
if slCont and #parts > 0 then
parts[#parts] ..= piece
elseif bit32.band(cf, 8) == 0 or #parts > 0 then
table.insert(parts, piece)
end
slCont = bit32.band(cf, 1) ~= 0
q += 2 + cl
end
elseif sig == "CL" and len >= 12 then
rr.child = u32(b, at + 4)
elseif sig == "RE" then
rr.relocated = true
elseif sig == "ZF" then
rr.zisofs = true
end
end
if name then
rr.name = table.concat(name)
end
if slParts then
rr.link = (if slRoot then "/" else "") .. table.concat(slParts, "/")
end
return rr
end
-- ------------------------------------------------------------------------------------------------ directories
type Record = {
name: string,
dir: boolean,
lba: number,
size: number,
ear: number,
flags: number,
interleave: boolean,
mtime: number?,
rr: Susp?,
}
-- the records of a directory extent (without "." and "..") | nil, Err
local function records(b: buffer, base: number, limit: number, at: number, size: number, bs: number, joliet: boolean, rrSkip: number?): ({ Record }?, Err.Err?)
if at + size > limit then
return nil, Err.new(Err.TRUNCATED, "directory past the end", at)
end
local out: { Record } = {}
local p = at
local e = at + size
while p < e do
local len = buffer.readu8(b, p)
if len == 0 then
p = at + ((p - at) // SECTOR + 1) * SECTOR -- the rest of the sector is padding
continue
end
if len < 34 or p + len > e then
return nil, Err.new(Err.CORRUPT, "bad directory record", p)
end
local nl = buffer.readu8(b, p + 32)
if 33 + nl > len then
return nil, Err.new(Err.CORRUPT, "bad name length", p + 32)
end
local raw = buffer.readstring(b, p + 33, nl)
if raw ~= "\0" and raw ~= "\1" then
local flags = buffer.readu8(b, p + 25)
local name
if joliet then
name = Text.utf16(b, p + 33, nl, true)
else
name = raw
end
name = string.gsub(name, ";%d*$", "")
if not joliet and bit32.band(flags, 2) == 0 then
name = string.gsub(name, "%.$", "")
end
local r: Record = {
name = name,
dir = bit32.band(flags, 2) ~= 0,
lba = u32(b, p + 2),
size = u32(b, p + 10),
ear = buffer.readu8(b, p + 1),
flags = flags,
interleave = buffer.readu8(b, p + 26) ~= 0 or buffer.readu8(b, p + 27) ~= 0,
mtime = recDate(b, p + 18),
rr = nil,
}
if rrSkip then
local su = p + 33 + nl + (if nl % 2 == 0 then 1 else 0) + rrSkip
r.rr = rockRidge(b, base, limit, su, p + len, bs)
end
table.insert(out, r)
end
p += len
end
return out, nil
end
-- the root record of a volume descriptor at vd -> lba, size
local function root(b: buffer, vd: number): (number, number)
return u32(b, vd + 156 + 2), u32(b, vd + 156 + 10)
end
-- Rock Ridge in use: the root's "." record starts its system use area with SP (BE EF); its skip length
local function rockRidgeSkip(b: buffer, base: number, limit: number, lba: number, bs: number): number?
local p = base + lba * bs
if p + 34 > limit then
return nil
end
local len = buffer.readu8(b, p)
local nl = buffer.readu8(b, p + 32)
local su = p + 33 + nl + (if nl % 2 == 0 then 1 else 0)
if len < 34 or su + 7 > p + len or p + len > limit then
return nil
end
if buffer.readstring(b, su, 2) == "SP" and buffer.readu8(b, su + 4) == 0xBE and buffer.readu8(b, su + 5) == 0xEF then
return buffer.readu8(b, su + 6)
end
return nil
end
-- ------------------------------------------------------------------------------------------------ El Torito
local function boot(b: buffer, base: number, limit: number, vd: number, bs: number): { [string]: any }?
if str(b, vd + 7, 32) ~= "EL TORITO SPECIFICATION" then
return nil
end
local cat = u32(b, vd + 0x47)
local p = base + cat * bs
local info: { [string]: any } = { catalog = cat }
if p + 64 > limit or buffer.readu8(b, p) ~= 1 or buffer.readu8(b, p + 30) ~= 0x55 or buffer.readu8(b, p + 31) ~= 0xAA then
return info
end
local sum = 0
for i = 0, 30, 2 do
sum += u16(b, p + i)
end
info.valid = sum % 65536 == 0
info.platform = buffer.readu8(b, p + 1)
info.id = str(b, p + 4, 24)
local d = p + 32
info.bootable = buffer.readu8(b, d) == 0x88
info.media = buffer.readu8(b, d + 1) -- 0 no emulation, 1..3 floppies, 4 hard disk
info.loadSegment = u16(b, d + 2)
info.systemType = buffer.readu8(b, d + 4)
info.sectors = u16(b, d + 6) -- 512-byte virtual sectors
info.lba = u32(b, d + 8)
return info
end
-- ------------------------------------------------------------------------------------------------ read
-- read(buf, offset?, length?, opts?) -> { Entry }, Info | nil, Err
function Iso9660.read(b: buffer, offset: number?, length: number?, opts: ReadOptions?): ({ Entry }?, any)
local base = offset or 0
local limit = math.min(buffer.len(b), base + (length or (buffer.len(b) - base)))
local o: ReadOptions = opts or {}
local maxEntries = o.maxEntries or 1e6
local pvd: number? = nil
local svd: number? = nil
local jolietLevel: number? = nil
local bootInfo = nil
local p = base + 16 * SECTOR
for _ = 1, 64 do
if p + SECTOR > limit then
return nil, Err.new(Err.TRUNCATED, "volume descriptors past the end", p)
end
if buffer.readstring(b, p + 1, 5) ~= "CD001" then
return nil, Err.new(Err.CORRUPT, "bad volume descriptor", p)
end
local t = buffer.readu8(b, p)
if t == 255 then
break
elseif t == 1 and not pvd then
pvd = p
elseif t == 2 then
local esc = buffer.readstring(b, p + 88, 3)
if esc == "%/@" or esc == "%/C" or esc == "%/E" then
svd = p
jolietLevel = if esc == "%/@" then 1 elseif esc == "%/C" then 2 else 3
end
elseif t == 0 then
bootInfo = bootInfo or { vd = p }
end
p += SECTOR
end
if not pvd then
return nil, Err.new(Err.CORRUPT, "no primary volume descriptor", base + 16 * SECTOR)
end
local pv = pvd :: number
local bs = u16(b, pv + 128)
if bs ~= 512 and bs ~= 1024 and bs ~= 2048 then
return nil, Err.new(Err.CORRUPT, "bad logical block size " .. bs, pv + 128)
end
local info: { [string]: any } = {
blockSize = bs,
blocks = u32(b, pv + 80),
systemId = str(b, pv + 8, 32),
volumeId = str(b, pv + 40, 32),
volumeSet = str(b, pv + 190, 128),
publisher = str(b, pv + 318, 128),
preparer = str(b, pv + 446, 128),
application = str(b, pv + 574, 128),
created = longDate(b, pv + 813),
modified = longDate(b, pv + 830),
joliet = jolietLevel,
}
if bootInfo then
info.boot = boot(b, base, limit, bootInfo.vd, bs)
end
local rlba, rsize = root(b, pv)
local rrSkip = rockRidgeSkip(b, base, limit, rlba, bs)
info.rockRidge = rrSkip ~= nil
local tree = o.prefer or (if rrSkip then "rockridge" elseif svd then "joliet" else "iso9660")
if tree == "joliet" and not svd then
tree = "iso9660"
elseif tree == "rockridge" and not rrSkip then
tree = "iso9660"
end
info.tree = tree
local joliet = tree == "joliet"
local useRR = if tree == "rockridge" then rrSkip else nil
if joliet then
rlba, rsize = root(b, svd :: number)
end
if tree == "joliet" then
info.volumeId = (string.gsub(Text.utf16(b, (svd :: number) + 40, 32, true), "[ %z]+$", ""))
end
local out: { Entry } = {}
local visited: { [number]: boolean } = {}
local stack = { { lba = rlba, size = rsize, path = "" } }
local relocatedDirs: { [string]: boolean } = {}
while #stack > 0 do
local d = table.remove(stack) :: any
if visited[d.lba] then
continue
end
visited[d.lba] = true
local list, err = records(b, base, limit, base + d.lba * bs, d.size, bs, joliet, useRR)
if not list then
return nil, err
end
local i = 1
local subdirs = {}
while i <= #list do
local r = list[i]
-- multi-extent: this record and the following ones of the same name
local extents: { Extent } = { { at = base + (r.lba + r.ear) * bs, size = r.size } }
local total = r.size
local last = r
while bit32.band(last.flags, 0x80) ~= 0 and i < #list and list[i + 1].name == r.name do
i += 1
last = list[i]
table.insert(extents, { at = base + (last.lba + last.ear) * bs, size = last.size })
total += last.size
end
i += 1
if bit32.band(r.flags, 4) ~= 0 then
continue -- an associated file (resource fork)
end
local rr: any = r.rr
if rr and rr.relocated then
continue -- shown where its CL placeholder is
end
local name = if rr and rr.name then rr.name else r.name
local path = d.path .. name
local isDir = r.dir
local lba: number, size: number = r.lba, r.size
if rr and rr.child then
-- a deep directory relocated by Rock Ridge: the placeholder points at it; its size is its "." record's
isDir = true
lba = rr.child
local q = base + lba * bs
size = if q + 14 <= limit then u32(b, q + 10) else 0
end
local typ = if isDir then "5" else "0"
if rr and rr.mode then
typ = S_TYPES[bit32.band(rr.mode, 0xF000)] or typ
end
local e: Entry = {
name = path,
dir = isDir,
size = if isDir or typ ~= "0" then 0 else total,
extents = if isDir or typ ~= "0" then {} else extents,
mtime = if rr and rr.mtime then rr.mtime else r.mtime,
type = typ,
mode = if rr and rr.mode then bit32.band(rr.mode, 0xFFF) else nil,
uid = rr and rr.uid,
gid = rr and rr.gid,
nlink = rr and rr.nlink,
link = if rr and typ == "2" then rr.link else nil,
rdev = rr and rr.rdev,
hidden = if bit32.band(r.flags, 1) ~= 0 then true else nil,
interleaved = if r.interleave then true else nil,
zisofs = if rr and rr.zisofs then true else nil,
}
table.insert(out, e)
if #out > maxEntries then
return nil, Err.new(Err.LIMIT, "more than " .. maxEntries .. " entries")
end
if isDir then
table.insert(subdirs, { lba = lba, size = size, path = path .. "/" })
end
end
for k = #subdirs, 1, -1 do
table.insert(stack, subdirs[k])
end
if useRR then
for _, r in list do
if r.rr and r.rr.relocated then
relocatedDirs[d.path] = true
end
end
end
end
-- rr_moved (genisoimage's home of relocated directories): hidden when nothing else is in it
if useRR then
for dirPath in relocatedDirs do
local name = string.sub(dirPath, 1, -2)
local holds = false
for _, e in out do
if string.sub(e.name, 1, #dirPath) == dirPath then
holds = true
break
end
end
if not holds then
for k, e in out do
if e.name == name then
table.remove(out, k)
break
end
end
end
end
end
-- archive order: depth-first walk order is kept; directories sorted as the image stores them
return out, info
end
-- extract(buf, entry, limit?) -> a copy of the entry's data | nil, Err
function Iso9660.extract(b: buffer, e: Entry, limit: number?): (buffer?, Err.Err?)
if e.interleaved then
return nil, Err.new(Err.UNSUPPORTED, "interleaved file " .. e.name)
end
local lim = limit or buffer.len(b)
local out = buffer.create(e.size)
local q = 0
for _, x in e.extents do
if x.at < 0 or x.at + x.size > lim then
return nil, Err.new(Err.TRUNCATED, "file " .. e.name .. " data past the end", x.at)
end
buffer.copy(out, q, b, x.at, x.size)
q += x.size
end
return out, nil
end
-- valid(buf, offset?) -> true when a volume descriptor "CD001" sits at sector 16
function Iso9660.valid(b: buffer, offset: number?): boolean
local p = (offset or 0) + 16 * SECTOR
return p + 6 <= buffer.len(b) and buffer.readstring(b, p + 1, 5) == "CD001"
end
return Iso9660
+156
View File
@@ -0,0 +1,156 @@
-- archive/ar tests: GNU ar (deterministic and with times, a library with its "/" symbol table), llvm-ar BSD (#1/ names,
-- __.SYMDEF) and bsdtar arbsd archives list the input files (names, sizes, mtimes, data CRCs) and symbols; the GNU writer
-- gives GNU ar rcSD's bytes for the same files; bsdtar and dpkg-deb archives re-encode to their own bytes; .deb packages
-- from dpkg-deb (xz / gzip / zstd / none) and older bzip2 / lzma members give meta.control and load through the api as
-- their data tar; errors; the fuzz pass. Fixtures: tools/fixtures/ar.py.
local T = require("@tests/T")
local F = require("@formats")
local Ar = require("@formats/archive/ar")
local Bytes = require("@formats/core/Bytes")
local Crc32 = require("@formats/core/Crc32")
local Err = require("@formats/core/Err")
local Fx = require("@tests/gen/ar")
local t = T.suite("ar")
t:eq(Ar.name, "ar", "name")
local function decode(s: string): (any, any)
return Ar.decode(Bytes.reader(buffer.fromstring(s)))
end
local function check(a: any, want: any, label: string)
local list = a:list()
t:eq(#list, #want, label .. ": entry count")
for i, w in want do
local e = list[i]
t:eq(e.name, w.name, label .. ": entry " .. i .. " name")
t:eq(e.size, w.size, label .. ": " .. w.name .. " size")
if w.mtime then
t:eq(e.mtime, w.mtime, label .. ": " .. w.name .. " mtime")
end
if w.crc then
local b = a:read(w.name)
t:eq(Crc32.of(b), w.crc, label .. ": " .. w.name .. " data")
end
if w.type then
t:eq(e.type, w.type, label .. ": " .. w.name .. " type")
end
end
end
local function sortedSymbols(list: { any }): string
local s = {}
for _, x in list do
table.insert(s, x.name .. "@" .. tostring(x.member))
end
table.sort(s)
return table.concat(s, ",")
end
-- 1. reading
for _, c in Fx.archives do
local a, err = decode(c.data)
t:check(a, c.name .. ": " .. tostring(err))
check(a, c.entries, c.name)
t:eq(a.meta.source.variant, c.variant, c.name .. ": variant")
t:eq(F.detect(c.data), "ar", c.name .. ": F.detect")
if c.symbols then
t:check(a.meta.symbols, c.name .. ": symbols")
t:eq(sortedSymbols(a.meta.symbols), sortedSymbols(c.symbols), c.name .. ": symbol names and members")
end
if c.roundtrip then
local out = assert(a:write())
local o = buffer.tostring(out)
t:check(string.sub(c.data, 1, #o) == o and not string.find(string.sub(c.data, #o + 1), "[^%z]"), c.name .. ": re-encode gives the same bytes (bsdtar pads with zeros)")
end
end
-- 2. writing: GNU ar rcSD's bytes; BSD names read back; any Archive to ar
do
local a = Ar.new()
for _, f in Fx.files do
a:add(f.name, f.data)
end
local out = assert(a:write())
t:check(buffer.tostring(out) == Fx.gnuD, "gnu: bytes identical to GNU ar rcSD")
local bsd = assert(a:write({ variant = "bsd" }))
local back = Ar.decode(Bytes.reader(bsd))
t:eq(back.meta.source.variant, "bsd", "bsd: variant")
t:eq(#back:list(), #Fx.files, "bsd: count")
for _, f in Fx.files do
t:eq(buffer.tostring(back:read(f.name)), f.data, "bsd: round trip " .. f.name)
end
local tar = F.format("tar").new()
tar:add("dir/", "", { dir = true })
tar:add("dir/file.txt", "in a dir", { mtime = 5 })
local conv = F.load(assert(F.save(tar, nil, { format = "ar" })))
t:eq(#conv:list(), 1, "tar -> ar: directories dropped")
t:eq(conv:list()[1].name, "dir/file.txt", "tar -> ar: path name in the long-name table")
t:eq(conv:list()[1].mtime, 5, "tar -> ar: mtime")
end
-- 3. Debian packages
for _, d in Fx.debs do
local a, err = decode(d.data)
t:check(a, d.name .. ": " .. tostring(err))
t:eq(a.meta.source.variant, "deb", d.name .. ": variant")
t:eq(a.meta.debian, "2.0", d.name .. ": debian-binary")
t:eq(a.meta.payload, d.payload, d.name .. ": payload")
t:check(a.meta.control, d.name .. ": control fields")
for k, v in d.control do
t:eq(a.meta.control[k], v, d.name .. ": control " .. k)
end
local out = assert(a:write())
t:check(buffer.tostring(out) == d.data, d.name .. ": re-encode gives the same bytes")
local data, lerr = F.load(d.data, { name = "hello.deb" })
t:check(data, d.name .. ": F.load: " .. tostring(lerr))
t:eq(data.format, "tar", d.name .. ": loads as the data tar")
t:eq(data.meta.container, "ar", d.name .. ": meta.container")
t:eq(data.meta.outer.meta.control.Package, "hello", d.name .. ": meta.outer control")
check(data, d.entries, d.name .. " data")
local outer = F.load(d.data, { unwrap = false })
t:eq(outer.format, "ar", d.name .. ": unwrap = false keeps the ar")
end
-- 4. errors
do
local _, e1 = decode("!<thin>\n")
t:check(e1 and e1.code == Err.UNSUPPORTED, "thin archive: " .. tostring(e1))
local good = Fx.archives[1].data
local b = buffer.fromstring(good)
buffer.writeu8(b, 8 + 58, 0x41)
local _, e2 = Ar.decode(Bytes.reader(b))
t:check(e2 and e2.code == Err.CORRUPT, "bad member header: " .. tostring(e2))
local _, e3 = decode(string.sub(good, 1, 100))
t:check(e3 and e3.code == Err.TRUNCATED, "truncated: " .. tostring(e3))
local _, e4 = decode("!<arch>\n" .. string.format("%-16s%-12d%-6d%-6d%-8s%-10d`\n", "/99", 0, 0, 0, "644", 0))
t:check(e4 and e4.code == Err.CORRUPT, "long name without a table: " .. tostring(e4))
local _, e5 = Ar.encode({ kind = "image" })
t:check(e5 and e5.code == Err.ARG, "encode a non-archive")
local _, e6 = decode("not an archive")
t:check(e6 and e6.code == Err.CORRUPT, "bad magic")
end
local samples = {}
for _, c in Fx.archives do
if #c.data < 8000 then
table.insert(samples, c.data)
end
end
for _, d in Fx.debs do
if #d.data < 8000 then
table.insert(samples, d.data)
end
end
t:fuzz("decode", function(b: buffer)
local a = Ar.decode(Bytes.reader(b))
if a then
for _, e in a:list() do
a:read(e.name)
end
a:write()
end
return a
end, samples, { mutations = 30, keepHeader = 8 })
t:done()
+164
View File
@@ -0,0 +1,164 @@
-- archive/cpio tests (and containers/Cpio): GNU cpio archives of one tree in newc / crc / odc / bin (and the bin one
-- byte-swapped to big endian) and bsdtar newc / odc archives list the entries os.lstat sees (names, types, modes, sizes,
-- mtimes, link counts, symlink targets, data CRCs, hard links reading the shared data); re-encoding the GNU newc / crc /
-- odc archives gives GNU's bytes; devices (rdev fields), crc sums, a .cpio.gz through the api, conversions to and from
-- tar (hard links share an inode), errors, the fuzz pass. Fixtures: tools/fixtures/cpio.py.
local T = require("@tests/T")
local F = require("@formats")
local CpioF = require("@formats/archive/cpio")
local Cpio = require("@formats/containers/Cpio")
local Bytes = require("@formats/core/Bytes")
local Crc32 = require("@formats/core/Crc32")
local Err = require("@formats/core/Err")
local Fx = require("@tests/gen/cpio")
local t = T.suite("cpio")
t:eq(CpioF.name, "cpio", "name")
local function check(a: any, want: any, label: string)
local list = a:list()
t:eq(#list, #want, label .. ": entry count")
local by = {}
for _, e in list do
by[e.name] = e
end
for _, w in want do
local e = by[w.name]
t:check(e, label .. ": has " .. w.name)
t:eq(e.type, w.type, label .. ": " .. w.name .. " type")
t:eq(e.mode, w.mode, label .. ": " .. w.name .. " mode")
t:eq(e.size, w.size, label .. ": " .. w.name .. " size")
t:eq(e.mtime, w.mtime, label .. ": " .. w.name .. " mtime")
if w.type ~= "5" then
t:eq(e.nlink, w.nlink, label .. ": " .. w.name .. " nlink")
end
t:eq(e.link, w.link, label .. ": " .. w.name .. " link")
t:eq(e.dir, w.type == "5", label .. ": " .. w.name .. " dir")
if w.crc then
local b, err = a:read(w.name)
t:check(b, label .. ": read " .. w.name .. ": " .. tostring(err))
t:eq(Crc32.of(b), w.crc, label .. ": " .. w.name .. " data")
end
end
end
-- 1. reading
for _, c in Fx.archives do
local a, err = CpioF.decode(Bytes.reader(buffer.fromstring(c.data)))
t:check(a, c.name .. ": " .. tostring(err))
do
check(a, c.entries, c.name)
t:eq(a.meta.source.variant, c.format, c.name .. ": variant")
t:eq(F.detect(c.data), "cpio", c.name .. ": F.detect")
-- hard links: the later links of the hello.txt group name the first
local hl = 0
for _, e in a:list() do
if e.hardlink then
hl += 1
end
end
t:eq(hl, 2, c.name .. ": two later hard links")
end
end
-- 2. writing: GNU's bytes back from the decoded archive (newc / crc / odc)
for _, c in Fx.archives do
if c.gnu and c.format ~= "bin" then
local a = CpioF.decode(Bytes.reader(buffer.fromstring(c.data)))
local out, err = a:write({ format = c.format })
t:check(out, c.name .. ": write: " .. tostring(err))
t:check(out and buffer.tostring(out) == c.data, c.name .. ": bytes identical to GNU cpio")
end
end
-- 3. devices, sums, the container directly
do
local list, info = Cpio.read(buffer.fromstring(Fx.devices))
t:check(list and info.format == "newc", "devices: read")
t:eq(#list, 4, "devices: entries")
t:eq(list[2].type, "3", "char device")
t:eq(list[2].rdevmajor * 256 + list[2].rdevminor, 259, "null: rdev 1:3")
t:eq(list[3].type, "4", "block device")
t:eq(list[3].rdevmajor, 8, "sda: rdev major")
t:eq(list[4].type, "s", "socket")
local _, e1 = Cpio.read(buffer.fromstring(Fx.badcrc))
t:check(e1 and e1.code == Err.CHECKSUM, "crc: bad sum: " .. tostring(e1))
t:check(Cpio.read(buffer.fromstring(Fx.badcrc), 0, nil, { verify = false }), "crc: verify = false")
-- devices survive a newc and an odc write
for _, fmt in { "newc", "odc" } do
local a = CpioF.decode(Bytes.reader(buffer.fromstring(Fx.devices)))
local back = CpioF.decode(Bytes.reader(assert(a:write({ format = fmt }))))
local d = back:list()[3]
t:check(d.type == "4" and d.rdevmajor == 8 and d.rdevminor == 0, fmt .. ": block device round trip")
end
end
-- 4. the api: .cpio.gz unwraps, Archive values, conversions
do
local a, err = F.load(Fx.gz, { name = "tree.cpio.gz" })
t:check(a and a.format == "cpio" and a.meta.compression == "gzip", "cpio.gz unwraps: " .. tostring(err))
local c = CpioF.new()
c:add("bin/", "", { dir = true })
c:add("bin/run.sh", "#!/bin/sh\n", { mode = 493, mtime = 1767225600 })
local back = F.load(assert(F.save(c)))
t:eq(back.format, "cpio", "F.save(cpio) round trip")
t:eq(back:list()[2].mode, 493, "mode round trip")
t:eq(back:list()[2].mtime, 1767225600, "mtime round trip")
t:eq(buffer.tostring(back:read("bin/run.sh")), "#!/bin/sh\n", "data round trip")
-- cpio -> tar keeps symlinks; tar -> cpio turns tar hard links into a shared inode
local gnu = CpioF.decode(Bytes.reader(buffer.fromstring(Fx.archives[1].data)))
local tar = F.load(assert(F.save(gnu, nil, { format = "tar" })))
local sym
for _, e in tar:list() do
if e.name == "sym" then
sym = e
end
end
t:check(sym and sym.type == "2" and sym.link == "hello.txt", "cpio -> tar: symlink")
local tf = F.format("tar").new()
tf:add("a.txt", "shared")
tf:add("b.txt", "")
tf._byName["b.txt"].type, tf._byName["b.txt"].link = "1", "a.txt"
local cp = F.load(assert(F.save(tf, nil, { format = "cpio" })))
t:eq(buffer.tostring(cp:read("b.txt")), "shared", "tar hard link -> cpio: data")
t:eq(cp:list()[2].hardlink, "a.txt", "tar hard link -> cpio: hardlink")
t:eq(cp:list()[1].nlink, 2, "tar hard link -> cpio: nlink")
end
-- 5. errors
do
local good = Fx.archives[1].data
local _, e1 = CpioF.decode(Bytes.reader(buffer.fromstring(string.sub(good, 1, 300))))
t:check(e1 and e1.code == Err.TRUNCATED, "truncated: " .. tostring(e1))
local b = buffer.fromstring(good)
buffer.writeu8(b, 10, string.byte("z"))
local _, e2 = CpioF.decode(Bytes.reader(b))
t:check(e2 and e2.code == Err.CORRUPT, "bad hex field: " .. tostring(e2))
local _, e3 = CpioF.encode({ kind = "image" })
t:check(e3 and e3.code == Err.ARG, "encode a non-archive")
local _, e4 = Cpio.write({ { name = "x", data = buffer.create(1), mtime = 2 ^ 40 } }, { format = "odc" })
t:check(e4 and e4.code == Err.ARG, "odc: mtime too large")
local _, e5 = CpioF.decode(Bytes.reader(buffer.fromstring("070701")))
t:check(e5 and e5.code == Err.TRUNCATED, "header past the end")
t:eq(CpioF.sniff(Bytes.reader(buffer.fromstring(string.rep("\0", 64)))), 0, "zeros are not cpio")
end
local samples = {}
for _, c in Fx.archives do
if #c.data <= 20000 then
table.insert(samples, c.data)
end
end
table.insert(samples, Fx.devices)
t:fuzz("decode", function(b: buffer)
local a = CpioF.decode(Bytes.reader(b))
if a then
for _, e in a:list() do
a:read(e.name)
end
a:write()
end
return a
end, samples, { mutations = 30, keepHeader = 0 })
t:done()
+134
View File
@@ -0,0 +1,134 @@
-- archive/iso tests (and containers/Iso9660): xorriso images (plain names, Joliet, Rock Ridge, Joliet + Rock Ridge with
-- deep directories / a 200-byte name / a long symlink target) and a genisoimage -J -R image (rr_moved relocation, CE
-- areas) list what the source tree holds (Rock Ridge: names, modes, symlink targets, mtimes, data CRCs) or what pycdlib
-- reads (plain and Joliet names, sizes, data CRCs); prefer = "joliet" on a -J -R image; an El Torito boot catalog as
-- xorriso reports it; a crafted multi-extent file reads whole; an interleaved file is UNSUPPORTED; errors; the fuzz pass.
-- Fixtures: tools/fixtures/iso.py.
local T = require("@tests/T")
local F = require("@formats")
local Iso = require("@formats/archive/iso")
local Bytes = require("@formats/core/Bytes")
local Crc32 = require("@formats/core/Crc32")
local Err = require("@formats/core/Err")
local Fx = require("@tests/gen/iso")
local t = T.suite("iso")
t:eq(Iso.name, "iso", "name")
local function dataOf(c: any): string
return if c.same then Fx.images[c.same].data else c.data
end
for _, c in Fx.images do
local a, err = Iso.decode(Bytes.reader(buffer.fromstring(dataOf(c))), { prefer = c.tree :: any })
t:check(a, c.name .. ": " .. tostring(err))
t:eq(a.meta.iso.tree, c.tree, c.name .. ": name set")
t:eq(F.detect(dataOf(c)), "iso", c.name .. ": F.detect")
local by = {}
for _, e in a:list() do
by[e.name] = e
end
t:eq(#a:list(), #c.entries, c.name .. ": entry count")
for _, w in c.entries do
local e = by[w.name]
t:check(e, c.name .. ": has " .. w.name)
t:eq(e.dir, w.dir, c.name .. ": " .. w.name .. " dir")
if w.mode then
t:eq(e.mode, w.mode, c.name .. ": " .. w.name .. " mode")
end
if w.link then
t:eq(e.type, "2", c.name .. ": " .. w.name .. " symlink")
t:eq(e.link, w.link, c.name .. ": " .. w.name .. " target")
end
if w.mtime and not w.dir then
t:eq(e.mtime, w.mtime, c.name .. ": " .. w.name .. " mtime")
end
if w.crc then
t:eq(e.size, w.size, c.name .. ": " .. w.name .. " size")
local b, rerr = a:read(w.name)
t:check(b, c.name .. ": read " .. w.name .. ": " .. tostring(rerr))
t:eq(Crc32.of(b), w.crc, c.name .. ": " .. w.name .. " data")
end
end
t:note("%-24s %-9s %3d entries", c.name, c.tree, #c.entries)
end
-- the default name set: Rock Ridge over Joliet; Joliet over plain
do
local jr = Iso.decode(Bytes.reader(buffer.fromstring(Fx.images[5].data)))
t:eq(jr.meta.iso.tree, "rockridge", "-J -R: Rock Ridge by default")
t:eq(jr.meta.iso.joliet, 3, "-J -R: Joliet level 3 seen")
t:check(jr.meta.iso.rockRidge, "-J -R: rockRidge")
local j = Iso.decode(Bytes.reader(buffer.fromstring(Fx.images[2].data)))
t:eq(j.meta.iso.tree, "joliet", "-J: Joliet by default")
local p = F.load(Fx.images[1].data)
t:eq(p.format, "iso", "F.load")
t:eq(p.meta.iso.tree, "iso9660", "plain")
t:check(p.meta.iso.blockSize == 2048 and p.meta.iso.blocks > 0, "volume facts")
-- any Archive converts: iso -> tar
local tar = F.load(assert(F.save(jr, nil, { format = "tar" })))
t:eq(buffer.tostring(tar:read("hello.txt")), "hello, iso\n", "iso -> tar")
end
-- El Torito
do
local a = Iso.decode(Bytes.reader(buffer.fromstring(Fx.boot.data)))
local bt = a.meta.boot
t:check(bt, "boot catalog")
t:eq(bt.catalog, Fx.boot.catalog, "boot: catalog LBA")
t:eq(bt.lba, Fx.boot.lba, "boot: image LBA")
t:eq(bt.sectors, Fx.boot.sectors, "boot: load size")
t:eq(bt.bootable, Fx.boot.bootable, "boot: bootable")
t:eq(bt.media, 0, "boot: no emulation")
t:check(bt.valid, "boot: validation entry checksum")
end
-- multi-extent and interleaved records
do
local a = Iso.decode(Bytes.reader(buffer.fromstring(Fx.multi.data)))
local n = 0
for _, e in a:list() do
if e.name == Fx.multi.name then
n += 1
t:eq(e.size, Fx.multi.size, "multi-extent: size")
end
end
t:eq(n, 1, "multi-extent: one entry")
t:eq(Crc32.of(a:read(Fx.multi.name)), Fx.multi.crc, "multi-extent: data")
local il = Iso.decode(Bytes.reader(buffer.fromstring(Fx.interleaved)))
local _, e = il:read("HELLO.TXT")
t:check(e and e.code == Err.UNSUPPORTED, "interleaved: " .. tostring(e))
end
-- errors
do
local good = Fx.images[1].data
local _, e1 = Iso.decode(Bytes.reader(buffer.fromstring(string.sub(good, 1, 20000))))
t:check(e1 and e1.code == Err.TRUNCATED, "short: " .. tostring(e1))
local b = buffer.fromstring(good)
buffer.writeu8(b, 16 * 2048 + 1, 0x58)
local _, e2 = Iso.decode(Bytes.reader(b))
t:check(e2 and e2.code == Err.CORRUPT, "bad descriptor: " .. tostring(e2))
local cut = Iso.decode(Bytes.reader(buffer.fromstring(string.sub(good, 1, 20 * 2048))))
t:check(cut == nil or cut, "a cut image: no throw")
t:eq(Iso.sniff(Bytes.reader(buffer.fromstring(string.rep("\0", 40000)))), 0, "zeros are not an iso")
end
-- fuzz: the volume descriptors and directories (the first 64 KB of a few images: their data lies further out)
local samples = {}
for i, c in Fx.images do
if c.data and (i == 1 or i == 3 or i == 5) then
table.insert(samples, string.sub(c.data, 1, 26 * 2048))
end
end
t:fuzz("decode", function(b: buffer)
local a = Iso.decode(Bytes.reader(b))
if a then
for _, e in a:list() do
a:read(e.name)
end
end
return a
end, samples, { mutations = 40, keepHeader = 16 * 2048 })
t:done()
+119
View File
@@ -0,0 +1,119 @@
-- archive/lz4 tests (and codecs/compress/Xxh32): frames from the lz4 tool (default, linked blocks, 64 KB blocks, block
-- checksums, content size, no content checksum, HC, legacy), concatenated and skippable frames decode to their corpora;
-- our frames (every option set) decode with `lz4 -d` (verdicts from the fixture step) and round-trip; XXH32 test
-- vectors; checksum / size / truncation errors; the api (.tar.lz4 unwrap, naming); the fuzz pass.
-- Fixtures: tools/fixtures/lz4frame.py.
local T = require("@tests/T")
local F = require("@formats")
local Lz4F = require("@formats/archive/lz4")
local Xxh32 = require("@formats/codecs/compress/Xxh32")
local Bytes = require("@formats/core/Bytes")
local Crc32 = require("@formats/core/Crc32")
local Err = require("@formats/core/Err")
local Fx = require("@tests/gen/lz4frame")
local C = require("@tests/gen/lz4frame_corpora")
local t = T.suite("lz4")
t:eq(Lz4F.name, "lz4", "name")
-- XXH32 vectors (xxHash's sanity checks)
t:eq(Xxh32.hash(buffer.fromstring("")), 0x02CC5D05, "xxh32 empty")
t:eq(Xxh32.hash(buffer.fromstring(""), 0, 0, 0x9E3779B1), 0x36B78AE7, "xxh32 empty, seed prime")
t:eq(Xxh32.hash(buffer.fromstring("a")), 0x550D7456, "xxh32 a")
t:eq(Xxh32.hash(buffer.fromstring("abc")), 0x32D153FF, "xxh32 abc")
t:eq(Xxh32.hash(buffer.fromstring("Nobody inspects the spammish repetition")), 0xE2293B2F, "xxh32 sentence")
local function want(c: any): string
if c.corpus == "short+text" then
return C.short .. C.text
end
return C[c.corpus]
end
for _, c in Fx.cases do
local out, err = Lz4F.decompress(c.data)
t:check(out, c.name .. ": " .. tostring(err))
local w = want(c)
t:eq(buffer.len(out), #w, c.name .. ": size")
t:eq(Crc32.of(out), Crc32.of(buffer.fromstring(w)), c.name .. ": data")
t:eq(F.detect(c.data), "lz4", c.name .. ": F.detect")
end
-- our frames, read by lz4 -d
t:check(#Fx.ours >= 15, "verdicts present")
for _, v in Fx.ours do
t:check(v.ok, "lz4 -d reads our " .. v.name)
end
for name, data in C do
for _, o in { {}, { blockSize = 65536, blockChecksum = true, contentSize = true }, { contentChecksum = false } } do
local z = assert(Lz4F.compress(data, o :: any))
t:eq(buffer.tostring(assert(Lz4F.decompress(z))), data, "round trip " .. name)
end
end
-- the api
do
local a = assert(F.load(Fx.cases[1].data, { name = "notes.txt.lz4" }))
t:check(a.meta.stream and a.format == "lz4", "single stream")
t:eq(a:list()[1].name, "notes.txt", "entry named after the file")
local tar = F.format("tar").new()
tar:add("a.txt", "alpha")
tar:add("b.txt", "beta")
local tl = assert(F.save(tar, nil, { format = "lz4" }))
local back = F.load(tl, { name = "x.tlz4" })
t:eq(back.format, "tar", "several entries: a .tar.lz4 that unwraps")
t:eq(back.meta.compression, "lz4", "meta.compression")
t:eq(F.load(tl, { name = "x.tlz4", unwrap = false }):list()[1].name, "x.tar", ".tlz4 -> .tar")
local s = assert(F.save("some text", nil, { format = "lz4" }))
t:eq(buffer.tostring(F.load(s):read("data")), "some text", "a string")
end
-- errors
do
local good
for _, c in Fx.cases do
if c.name == "text/BX" then
good = c.data
end
end
local function flip(at: number): buffer
local b = buffer.fromstring(good)
buffer.writeu8(b, at, bit32.bxor(buffer.readu8(b, at), 1))
return b
end
local _, e1 = Lz4F.decompress(flip(6))
t:check(e1 and e1.code == Err.CHECKSUM, "header checksum: " .. tostring(e1))
local _, e2 = Lz4F.decompress(flip(20))
t:check(e2 and e2.code == Err.CHECKSUM, "block checksum: " .. tostring(e2))
local _, e3 = Lz4F.decompress(flip(#good - 2))
t:check(e3 and e3.code == Err.CHECKSUM, "content checksum: " .. tostring(e3))
t:check(Lz4F.decompress(flip(#good - 2), nil, nil, { verify = false }), "verify = false")
local _, e4 = Lz4F.decompress(string.sub(good, 1, 1000))
t:check(e4 and e4.code == Err.TRUNCATED, "truncated: " .. tostring(e4))
local _, e5 = Lz4F.decompress(Fx.cases[1].data, nil, nil, { maxBytes = 10 })
t:check(e5 == nil or e5.code == Err.LIMIT, "maxBytes")
local big
for _, c in Fx.cases do
if c.name == "zeros/default" then
big = c.data
end
end
local _, e6 = Lz4F.decompress(big, nil, nil, { maxBytes = 1000 })
t:check(e6 and e6.code == Err.LIMIT, "maxBytes: " .. tostring(e6))
local _, e7 = Lz4F.compress("x", { blockSize = 1000 })
t:check(e7 and e7.code == Err.ARG, "bad blockSize")
local _, e8 = Lz4F.decompress("not lz4 at all")
t:check(e8 and e8.code == Err.CORRUPT, "bad magic")
end
local samples = {}
for _, c in Fx.cases do
if #c.data < 6000 then
table.insert(samples, c.data)
end
end
t:fuzz("decode", function(b: buffer)
return Lz4F.decode(Bytes.reader(b), { maxBytes = 2 ^ 22 })
end, samples, { mutations = 40, keepHeader = 4 })
t:done()
+101
View File
@@ -0,0 +1,101 @@
-- archive/rpm tests: one package from rpmbuild with each payload compressor (gzip, bzip2, xz, lzma, zstd, none) gives
-- the header fields `rpm -qp --qf` prints, its file list (names, sizes, modes, mtimes, symlink targets; %ghost files
-- skipped), the file data rpm2cpio's stream holds (CRCs, hard links), and Rpm.cpio = rpm2cpio's bytes; errors; the
-- fuzz pass. Fixtures: tools/fixtures/rpm.py.
local T = require("@tests/T")
local F = require("@formats")
local Rpm = require("@formats/archive/rpm")
local Bytes = require("@formats/core/Bytes")
local Crc32 = require("@formats/core/Crc32")
local Err = require("@formats/core/Err")
local Fx = require("@tests/gen/rpm")
local t = T.suite("rpm")
t:eq(Rpm.name, "rpm", "name")
local TYPES = { [0x8000] = "0", [0x4000] = "5", [0xA000] = "2" }
for _, c in Fx.rpms do
local a, err = Rpm.decode(Bytes.reader(buffer.fromstring(c.data)))
t:check(a, c.name .. ": " .. tostring(err))
t:eq(F.detect(c.data), "rpm", c.name .. ": F.detect")
for k, v in c.fields do
t:eq(a.meta.rpm[k], v, c.name .. ": " .. k)
end
t:eq(a.meta.rpm.type, "binary", c.name .. ": binary package")
local by = {}
for _, e in a:list() do
by[e.name] = e
end
local n = 0
for _, w in c.files do
local e = by[w.name]
if w.flags % 128 >= 64 then
t:check(e == nil, c.name .. ": ghost " .. w.name .. " not listed")
continue
end
n += 1
t:check(e, c.name .. ": has " .. w.name)
t:eq(e.type, TYPES[w.type], c.name .. ": " .. w.name .. " type")
t:eq(e.mode, w.mode, c.name .. ": " .. w.name .. " mode")
t:eq(e.mtime, w.mtime, c.name .. ": " .. w.name .. " mtime")
t:eq(e.link, w.link, c.name .. ": " .. w.name .. " link")
if w.crc then
t:eq(e.size, w.size, c.name .. ": " .. w.name .. " size")
local b, rerr = a:read(w.name)
t:check(b, c.name .. ": read " .. w.name .. ": " .. tostring(rerr))
t:eq(Crc32.of(b), w.crc, c.name .. ": " .. w.name .. " data")
end
end
t:eq(#a:list(), n, c.name .. ": entry count")
-- hard links: both read the same bytes
t:eq(buffer.tostring(a:read("usr/bin/hello")), "#!/bin/sh\necho hello\n", c.name .. ": hard link (first)")
t:eq(buffer.tostring(a:read("usr/bin/hello2")), "#!/bin/sh\necho hello\n", c.name .. ": hard link (second)")
local raw = Rpm.cpio(Bytes.reader(buffer.fromstring(c.data)))
t:check(raw and buffer.len(raw) == c.cpioSize and Crc32.of(raw) == c.cpioCrc, c.name .. ": Rpm.cpio = rpm2cpio")
t:note("%-16s %s %d files", c.name, tostring(a.meta.rpm.payloadCompressor), n)
end
-- the api: an rpm loads as itself (no payload unwrap), converts to tar
do
local c = Fx.rpms[1]
local a = assert(F.load(c.data))
t:eq(a.format, "rpm", "F.load")
local tar = F.load(assert(F.save(a, nil, { format = "tar" })))
t:eq(buffer.tostring(tar:read("usr/bin/hello")), "#!/bin/sh\necho hello\n", "rpm -> tar")
local _, e = F.save(a)
t:check(e, "rpm is read-only")
end
-- errors
do
local good = Fx.rpms[1].data
local _, e1 = Rpm.decode(Bytes.reader(buffer.fromstring(string.sub(good, 1, 50))))
t:check(e1 and e1.code == Err.TRUNCATED, "short lead: " .. tostring(e1))
local b = buffer.fromstring(good)
buffer.writeu8(b, 96, 0)
local _, e2 = Rpm.decode(Bytes.reader(b))
t:check(e2 and e2.code == Err.CORRUPT, "bad signature magic: " .. tostring(e2))
local cut = Rpm.decode(Bytes.reader(buffer.fromstring(string.sub(good, 1, #good - 200))))
t:check(cut, "a cut payload still lists")
local _, e3 = cut:read("usr/share/doc/hello/README")
t:check(e3 ~= nil, "a cut payload fails on read: " .. tostring(e3))
end
local samples = {}
for _, c in Fx.rpms do
if #c.data < 40000 then
table.insert(samples, c.data)
end
end
t:fuzz("decode", function(b: buffer)
local a = Rpm.decode(Bytes.reader(b))
if a then
for _, e in a:list() do
a:read(e.name)
end
end
return a
end, samples, { mutations = 25, keepHeader = 4 })
t:done()
+70
View File
@@ -0,0 +1,70 @@
-- archive/z tests: .Z files from ncompress load as single-stream archives (entry names from the file name, .taz -> .tar),
-- a .tar.Z unwraps to the tar through the api, writing gives ncompress's bytes (a buffer, a one-entry Archive) and a
-- tar inside for several entries, conversions, errors, the fuzz pass. Fixtures: tools/fixtures/z.py.
local T = require("@tests/T")
local F = require("@formats")
local Z = require("@formats/archive/z")
local Bytes = require("@formats/core/Bytes")
local Err = require("@formats/core/Err")
local Fx = require("@tests/gen/z")
local t = T.suite("z")
t:eq(Z.name, "z", "name")
local text = Fx.cases[3]
do
local a, err = Z.decode(Bytes.reader(buffer.fromstring(text.z)), { name = "notes.txt.Z" })
t:check(a, "decode: " .. tostring(err))
t:check(a.meta.stream, "single stream")
t:eq(a:list()[1].name, "notes.txt", "entry named after the file")
t:eq(a:list()[1].method, "lzw", "method")
t:eq(buffer.tostring(a:read("notes.txt")), text.input, "data")
t:eq(a.meta.source.maxBits, 16, "maxBits")
t:eq(Z.decode(Bytes.reader(buffer.fromstring(text.z))):list()[1].name, "data", "no name: data")
t:eq(F.detect(text.z), "z", "F.detect")
t:eq(Z.decode(Bytes.reader(buffer.fromstring(text.z)), { name = "x.taz" }):list()[1].name, "x.tar", ".taz -> .tar")
t:eq(Z.decode(Bytes.reader(buffer.fromstring(text.z)), { name = "x.tZ" }):list()[1].name, "x.tar", ".tZ -> .tar")
end
-- the api: a .tar.Z is the tar inside
do
local a, err = F.load(Fx.tarZ, { name = "src.tar.Z" })
t:check(a, "tar.Z: " .. tostring(err))
t:eq(a.format, "tar", "tar.Z unwraps")
t:eq(a.meta.compression, "z", "meta.compression")
t:eq(#a:list(), #Fx.tarNames, "tar entries")
local outer = F.load(Fx.tarZ, { name = "src.tar.Z", unwrap = false })
t:eq(outer:list()[1].name, "src.tar", "unwrap = false")
end
-- writing
do
local out = assert(F.save(text.input, nil, { format = "z" }))
t:check(buffer.tostring(out) == text.z, "a string: ncompress's bytes")
local one = Z.new(text.input, "t.txt")
t:check(buffer.tostring(assert(one:write())) == text.z, "a one-entry archive: ncompress's bytes")
local tar = F.format("tar").new()
tar:add("a.txt", "alpha")
tar:add("b.txt", "beta")
local tz = assert(F.save(tar, nil, { format = "z" }))
local back = F.load(tz)
t:eq(back.format, "tar", "several entries: a tar inside")
t:eq(buffer.tostring(back:read("b.txt")), "beta", "tar inside: data")
local b10 = assert(Z.encode(Fx.cases[6].input, { maxBits = Fx.cases[6].bits }))
t:check(buffer.tostring(b10) == Fx.cases[6].z, "maxBits option")
end
-- errors
do
local _, e1 = Z.decode(Bytes.reader(buffer.fromstring("\31\157")))
t:check(e1 and e1.code == Err.TRUNCATED, "short")
local _, e2 = Z.encode({ kind = "image" })
t:check(e2 and e2.code == Err.ARG, "encode a non-archive")
t:eq(Z.sniff(Bytes.reader(buffer.fromstring("\31\139\8"))), 0, "gzip is not .Z")
end
t:fuzz("decode", function(b: buffer)
return Z.decode(Bytes.reader(b), { maxBytes = 2 ^ 22 })
end, { text.z, Fx.tarZ }, { mutations = 40, keepHeader = 3 })
t:done()
+101
View File
@@ -0,0 +1,101 @@
-- codecs/compress/Lz4 tests: every reference block (python-lz4 fast at accelerations 1 / 4 / 16, HC 4 / 9 / 12)
-- decodes to its corpus, with and without the size; our encoder's blocks decode with the reference (fixture verdicts)
-- and round trip here; linked blocks through decodeInto's history; error codes; truncated / mutated / random blocks
-- never throw. Fixtures: tools/fixtures/lz4.py.
local T = require("@tests/T")
local Lz4 = require("@formats/codecs/compress/Lz4")
local Err = require("@formats/core/Err")
local Fx = require("@tests/gen/lz4")
local C = require("@tests/gen/lz4_corpora")
local t = T.suite("lz4")
local nbytes = 0
for _, c in Fx.cases do
local want = C[c.corpus]
local out, err = Lz4.decompress(c.data, nil, nil, #want)
t:check(out ~= nil and buffer.tostring(out) == want, c.name .. ": " .. tostring(err))
if #want > 0 then
local grown = Lz4.decompress(c.data)
t:check(grown ~= nil and buffer.tostring(grown) == want, c.name .. ": without the size")
end
nbytes += #want
end
t:note("%d reference blocks, %.1f MB decoded", #Fx.cases, nbytes / 1e6)
for _, v in Fx.ours do
t:check(v.ok, v.name .. ": the reference decodes our block")
end
for name, data in C do
local b = Lz4.compress(data) :: buffer
local back = Lz4.decompress(b, nil, nil, #data)
t:check(back ~= nil and buffer.tostring(back) == data, name .. ": round trip")
if name == "text" or name == "zeros" or name == "runs" then
t:check(buffer.len(b) < #data / 2, name .. ": compresses")
end
t:check(buffer.len(b) <= Lz4.bound(#data), name .. ": within bound")
end
-- at an offset, and linked blocks: the second block refers into the first one's output
do
local text = C.text
local a, b2 = string.sub(text, 1, 70000), string.sub(text, 70001, 140000)
local pa = Lz4.compress(a) :: buffer
-- a block of b2 that copies the first 40 bytes of b2's region from a (a match reaching back across blocks)
local big = buffer.create(buffer.len(pa) + 20)
buffer.copy(big, 9, pa)
local out = Lz4.decompress(big, 9, buffer.len(pa), #a)
t:check(out ~= nil and buffer.tostring(out) == a, "at an offset")
local hand = buffer.create(3 + 1 + 2 + 1)
-- token: 0 literals, match length 15 + ext; offset = 100 back into the previous block
buffer.writeu8(hand, 0, 0x0F)
buffer.writeu16(hand, 1, 100)
buffer.writeu8(hand, 3, 20) -- match length 4 + 15 + 20 = 39
buffer.writeu8(hand, 4, 0x10) -- the last sequence: one literal
buffer.writeu8(hand, 5, 33)
local dst = buffer.create(#a + 40)
buffer.writestring(dst, 0, a)
local e, msg = Lz4.decodeInto(hand, 0, 6, dst, #a, #a + 40, 0)
t:check(e == #a + 40, "linked block: " .. tostring(msg))
t:eq(buffer.readstring(dst, #a, 39), string.sub(a, #a - 99, #a - 61), "linked block: match from the history")
local e2, msg2 = Lz4.decodeInto(hand, 0, 6, dst, #a, #a + 40)
t:check(e2 == nil and string.find(msg2 or "", "offset") ~= nil, "without history the match is corrupt")
t:check(b2 ~= nil, "second half")
end
-- errors
do
local _, e1 = Lz4.decompress("")
t:check(e1 and e1.code == Err.TRUNCATED, "empty: " .. tostring(e1))
local _, e2 = Lz4.decompress("\x50ab")
t:check(e2 and e2.code == Err.TRUNCATED, "literals past the end: " .. tostring(e2))
local _, e3 = Lz4.decompress("\x14abcd\x09\x00\x10z")
t:check(e3 and e3.code == Err.CORRUPT, "offset before the start: " .. tostring(e3))
local _, e4 = Lz4.decompress("\x10a", nil, nil, 5)
t:check(e4 and e4.code == Err.CORRUPT, "shorter than outSize: " .. tostring(e4))
local _, e5 = Lz4.decompress("\x50abcde", nil, nil, 2)
t:check(e5 and e5.code == Err.LIMIT, "longer than outSize: " .. tostring(e5))
local _, e6 = Lz4.decompress(C.zeros and (Lz4.compress(C.zeros) :: buffer), nil, nil, nil, { maxBytes = 1000 })
t:check(e6 and e6.code == Err.LIMIT, "maxBytes: " .. tostring(e6))
local ok, r1, r2 = pcall(Lz4.decompress, 5 :: any)
t:check(ok and r1 == nil and r2.code == Err.ARG, "a non-buffer argument returns Err.ARG")
local _, e7 = Lz4.decompress("\x10a", nil, nil, -1)
t:check(e7 and e7.code == Err.ARG, "bad outSize")
end
do
local samples = {}
for i, c in Fx.cases do
if i % 4 == 0 and #c.data > 8 and #c.data < 30000 then
table.insert(samples, c.data)
end
end
t:fuzz("decompress", function(b: buffer)
return Lz4.decompress(b, nil, nil, nil, { maxBytes = 1e6 })
end, samples, { mutations = 30, garbage = 2000 })
t:fuzz("decompress (sized)", function(b: buffer)
return Lz4.decompress(b, nil, nil, 70000)
end, samples, { mutations = 30, garbage = 500, seed = 5 })
end
t:done()
+75
View File
@@ -0,0 +1,75 @@
-- codecs/compress/UnixCompress tests: ncompress 5.0 files (widths 10..16, block mode, CLEAR codes after the ratio
-- check, empty / one-byte / random inputs) decode to their inputs; compress() gives ncompress's bytes for the same input
-- and width; non-block-mode streams; errors; the fuzz pass. Fixtures: tools/fixtures/z.py.
local T = require("@tests/T")
local UnixCompress = require("@formats/codecs/compress/UnixCompress")
local Crc32 = require("@formats/core/Crc32")
local Err = require("@formats/core/Err")
local Fx = require("@tests/gen/z")
local t = T.suite("unixcompress")
for _, c in Fx.cases do
local out, err = UnixCompress.decompress(c.z)
t:check(out, c.name .. ": decompress: " .. tostring(err))
t:eq(buffer.len(out), #c.input, c.name .. ": size")
t:eq(Crc32.of(out), Crc32.of(buffer.fromstring(c.input)), c.name .. ": data")
local z, zerr = UnixCompress.compress(c.input, nil, nil, { maxBits = c.bits })
t:check(z, c.name .. ": compress: " .. tostring(zerr))
t:eq(buffer.len(z), #c.z, c.name .. ": compressed size = ncompress")
t:check(buffer.tostring(z) == c.z, c.name .. ": bytes identical to ncompress -b " .. c.bits)
t:note("%-12s %7d -> %7d bytes (-b %d)", c.name, #c.input, #c.z, c.bits)
end
-- 9-bit codes, LSB first, after a .Z header with the given flags byte
local function pack(flags: number, codes: { number }): buffer
local acc, nb, bytes = 0, 0, { 0x1F, 0x9D, flags }
for _, c in codes do
acc += c * 2 ^ nb
nb += 9
while nb >= 8 do
table.insert(bytes, acc % 256)
acc = acc // 256
nb -= 8
end
end
if nb > 0 then
table.insert(bytes, acc)
end
return T.bytes(bytes)
end
-- a non-block-mode stream (no CLEAR code; 256 is the first table entry): "ABABABA"
do
local out = UnixCompress.decompress(pack(0x10, { 65, 66, 256, 258 }))
t:eq(out and buffer.tostring(out), "ABABABA", "non-block mode")
end
-- errors
do
local _, e1 = UnixCompress.decompress("\31\157")
t:check(e1 and e1.code == Err.TRUNCATED, "short header")
local _, e2 = UnixCompress.decompress("\31\158\144")
t:check(e2 and e2.code == Err.CORRUPT, "bad magic")
local _, e3 = UnixCompress.decompress("\31\157\145")
t:check(e3 and e3.code == Err.UNSUPPORTED, "17-bit codes")
local _, e4 = UnixCompress.decompress(pack(0x90, { 65, 400 }))
t:check(e4 and e4.code == Err.CORRUPT, "a code past the table: " .. tostring(e4))
local _, e5 = UnixCompress.decompress(Fx.cases[5].z, nil, nil, { maxBytes = 1000 })
t:check(e5 and e5.code == Err.LIMIT, "maxBytes")
local _, e6 = UnixCompress.compress("x", nil, nil, { maxBits = 17 })
t:check(e6 and e6.code == Err.ARG, "maxBits 17")
end
local samples = {}
for _, c in Fx.cases do
if #c.z < 4000 and #c.z > 3 then
table.insert(samples, c.z)
end
end
table.insert(samples, string.sub(Fx.cases[#Fx.cases].z, 1, 3000))
t:fuzz("decompress", function(b: buffer)
return UnixCompress.decompress(b, nil, nil, { maxBytes = 2 ^ 22 })
end, samples, { mutations = 40, keepHeader = 3 })
t:done()
+44 -1
View File
@@ -1,7 +1,7 @@
-- Throughput (bash tools/bench.sh): codec MB/s under both runtimes. MB/s are of decompressed output, best of n runs.
-- Fixtures: tools/fixtures/deflate.py (a 6 MB corpus), tools/fixtures/png.py (1024 x 768 images), tools/fixtures/mp3.py,
-- tools/fixtures/opus.py (3 s stereo files; MB/s of f32 output, 48 kHz stereo f32 is 0.384 MB/s of real time),
-- tools/fixtures/flac.py; wav encodes / decodes a generated tone; zstd / brotli / bzip2 / lzma (*_bench corpora), fonts
-- tools/fixtures/flac.py; wav encodes / decodes a generated tone; zstd / brotli / bzip2 / lzma / lz4 (*_bench corpora), .Z (tools/fixtures/z.py), fonts
-- (glyphs per second), json / xml / yaml, jpeg / gif / tiff / qoi / tga / pnm / hdr and ImageOps.
local Deflate = require("@formats/codecs/compress/Deflate")
local Crc32 = require("@formats/core/Crc32")
@@ -236,6 +236,19 @@ do
Zstd.decompress(z19, nil, nil, { verify = false })
end)
end
do
local Lz4 = require("@formats/codecs/compress/Lz4")
local LB = require("@tests/gen/lz4_bench")
local lz = buffer.fromstring(LB.data)
local raw = assert(Lz4.decompress(lz, nil, nil, LB.size))
assert(Crc32.of(raw) == LB.crc, "lz4 bench corpus mismatch")
bench("lz4 block decompress (hc9)", 5, LB.size, function()
Lz4.decompress(lz, nil, nil, LB.size)
end)
bench("lz4 block compress", 3, LB.size, function()
Lz4.compress(raw)
end)
end
do
local Brotli = require("@formats/codecs/compress/Brotli")
local BB = require("@tests/gen/brotli_bench")
@@ -254,6 +267,36 @@ do
Bzip2.decompress(bz)
end)
end
do
local Lz4F = require("@formats/archive/lz4")
local LF = require("@tests/gen/lz4frame")
local LC = require("@tests/gen/lz4frame_corpora")
local frameData
for _, c in LF.cases do
if c.name == "text/BX" then
frameData = buffer.fromstring(c.data)
end
end
bench("lz4 frame decode (64K, xxh32)", 5, #LC.text, function()
Lz4F.decompress(frameData)
end)
local tb = buffer.fromstring(LC.text)
bench("lz4 frame encode (xxh32)", 5, #LC.text, function()
Lz4F.compress(tb)
end)
end
do
local UnixCompress = require("@formats/codecs/compress/UnixCompress")
local ZC = require("@tests/gen/z")
local zc = ZC.cases[5] -- the 700 KB corpus, -b 16
local zb, zi = buffer.fromstring(zc.z), buffer.fromstring(zc.input)
bench(".Z decompress (lzw -b16)", 5, #zc.input, function()
UnixCompress.decompress(zb)
end)
bench(".Z compress (lzw -b16)", 3, #zc.input, function()
UnixCompress.compress(zi)
end)
end
do
local Lzma = require("@formats/codecs/compress/Lzma")
local LB = require("@tests/gen/lzma_bench")
+13
View File
@@ -0,0 +1,13 @@
-- tools/fixtures/_lz4_encode.luau: run by tools/fixtures/lz4.py under the luau CLI: compresses every corpus of
-- tests/gen/lz4_corpora with codecs/compress/Lz4 and prints "<name> <hex>" lines for the reference to decompress.
local Lz4 = require("@formats/codecs/compress/Lz4")
local C = require("@tests/gen/lz4_corpora")
for name, data in C do
local b = assert(Lz4.compress(data))
local t = table.create(buffer.len(b))
for i = 0, buffer.len(b) - 1 do
t[i + 1] = string.format("%02x", buffer.readu8(b, i))
end
print(name .. " " .. table.concat(t))
end
+21
View File
@@ -0,0 +1,21 @@
-- tools/fixtures/_lz4frame_encode.luau: run by tools/fixtures/lz4frame.py under the luau CLI: writes every corpus of
-- tests/gen/lz4frame_corpora as LZ4 frames with archive/lz4 (several option sets) and prints "<name> <hex>" lines for
-- the lz4 tool to decompress.
local Lz4F = require("@formats/archive/lz4")
local C = require("@tests/gen/lz4frame_corpora")
local sets = {
default = {},
b64k = { blockSize = 65536, blockChecksum = true, contentSize = true },
nocrc = { contentChecksum = false, blockSize = 262144 },
}
for name, data in C do
for sname, o in sets do
local b = assert(Lz4F.compress(data, o :: any))
local t = table.create(buffer.len(b))
for i = 0, buffer.len(b) - 1 do
t[i + 1] = string.format("%02x", buffer.readu8(b, i))
end
print(name .. "/" .. sname .. " " .. table.concat(t))
end
end
+139
View File
@@ -0,0 +1,139 @@
# ar / deb fixtures (tools/fixtures.py): GNU ar (binutils: deterministic `rcSD`, real times `rcSU`, a library of two
# `as`-assembled objects with its "/" symbol table), llvm-ar --format=bsd (#1/ names, __.SYMDEF), bsdtar arbsd, and
# Debian packages from dpkg-deb --build (-Zxz / gzip / zstd / none) plus two built here (bzip2 and lzma members, as
# older dpkg wrote them). The expected entries are the input files; the .deb data entries come from Python's tarfile.
# tests/gen/ar.luau { files = { { name, data } }, gnuD = data (GNU ar rcSD of files), archives = { { name, data,
# variant, entries = { { name, size, mtime?, crc } }, symbols? = { { name, member } }, roundtrip? } },
# debs = { { name, data, control = { [field] = value }, payload, entries = { { name, type, size, crc? } } } } }
import bz2, gzip, io, lzma, os, shutil, subprocess, tarfile, tempfile, time, zlib
MTIME = 1700000000
def sh(pkgs, script, cwd, env=None):
argv = ["nix", "shell"] + ["nixpkgs#" + p for p in pkgs] + ["-c", "sh", "-c", script]
return subprocess.run(argv, cwd=cwd, capture_output=True, check=True, env=env).stdout
def ar_member(name, data, mtime=MTIME):
h = b"%-16s%-12d%-6d%-6d%-8s%-10d`\n" % (name, mtime, 0, 0, b"100644", len(data))
return h + data + (b"\n" if len(data) % 2 else b"")
def unpack(z, m):
if z == "xz":
return lzma.decompress(m)
if z == "gzip":
return gzip.decompress(m)
if z == "zstd":
return subprocess.run(["nix", "shell", "nixpkgs#zstd", "-c", "zstd", "-d", "-c"], input=m, capture_output=True, check=True).stdout
return m
def tar_entries(raw):
out = []
with tarfile.open(fileobj=io.BytesIO(raw)) as t:
for m in t.getmembers():
e = {"name": m.name + ("/" if m.isdir() and not m.name.endswith("/") else ""), "type": m.type.decode() if m.type != b"\0" else "0",
"size": m.size if m.isfile() else 0}
if m.isfile():
e["crc"] = zlib.crc32(t.extractfile(m).read())
out.append(e)
return out
def generate(ctx):
rng = ctx.rng(17)
files = [
("a.txt", b"hello, ar\n"),
("odd", b"x" * 7),
("empty", b""),
("exactly15chars_", b"fifteen"),
("sixteen_chars_16", b"sixteen"),
("a_very_long_member_name.txt", rng.randbytes(1001)),
("another-long-member-name.bin", b"long name two\n"),
]
tmp = tempfile.mkdtemp()
try:
names = [n for n, _ in files]
for n, d in files:
with open(os.path.join(tmp, n), "wb") as f:
f.write(d)
os.utime(os.path.join(tmp, n), (MTIME, MTIME))
q = " ".join(names)
archives = []
gnuD = sh(["binutils"], "ar rcSD out.a %s && cat out.a && rm out.a" % q, tmp)
ents = [{"name": n, "size": len(d), "crc": zlib.crc32(d)} for n, d in files]
timed = [dict(e, mtime=MTIME) for e in ents]
archives.append({"name": "gnu-D", "data": gnuD, "variant": "gnu", "entries": ents})
archives.append({"name": "gnu-U", "data": sh(["binutils"], "ar rcSU out.a %s && cat out.a && rm out.a" % q, tmp),
"variant": "gnu", "entries": timed})
# a library: two objects, with a symbol table
with open(os.path.join(tmp, "s1.s"), "w") as f:
f.write(".globl foo\nfoo:\n.data\n.globl bar\nbar: .long 1\n")
with open(os.path.join(tmp, "s2.s"), "w") as f:
f.write(".globl baz_with_a_long_symbol_name\nbaz_with_a_long_symbol_name:\n")
sh(["binutils"], "as -o one.o s1.s && as -o second_object_long_name.o s2.s", tmp)
objs = []
for n in ("one.o", "second_object_long_name.o"):
with open(os.path.join(tmp, n), "rb") as f:
d = f.read()
objs.append({"name": n, "size": len(d), "crc": zlib.crc32(d)})
syms = [{"name": "foo", "member": "one.o"}, {"name": "bar", "member": "one.o"},
{"name": "baz_with_a_long_symbol_name", "member": "second_object_long_name.o"}]
lib = "one.o second_object_long_name.o a.txt"
archives.append({"name": "gnu-lib", "data": sh(["binutils"], "ar rcsD out.a %s && cat out.a && rm out.a" % lib, tmp),
"variant": "gnu", "entries": objs + ents[:1], "symbols": syms})
archives.append({"name": "llvm-bsd", "data": sh(["llvm"], "llvm-ar rcSD --format=bsd out.a %s && cat out.a && rm out.a" % q, tmp),
"variant": "bsd", "entries": ents})
archives.append({"name": "llvm-bsd-lib", "data": sh(["llvm"], "llvm-ar rcsD --format=bsd out.a %s && cat out.a && rm out.a" % lib, tmp),
"variant": "bsd", "entries": objs + ents[:1], "symbols": syms})
archives.append({"name": "bsdtar-arbsd", "data": sh(["libarchive"], "bsdtar --format=arbsd -cf - %s" % q, tmp),
"variant": "bsd", "entries": timed, "roundtrip": True})
# Debian packages
pkg = os.path.join(tmp, "pkg")
os.makedirs(os.path.join(pkg, "DEBIAN"))
os.makedirs(os.path.join(pkg, "usr", "share", "doc", "hello"))
os.makedirs(os.path.join(pkg, "usr", "bin"))
control = ("Package: hello\nVersion: 1.0-1\nArchitecture: all\nMaintainer: Ada <[email protected]>\n"
"Depends: libc6 (>= 2.31)\nDescription: a greeting\n prints a greeting\n .\n and exits\n")
with open(os.path.join(pkg, "DEBIAN", "control"), "w") as f:
f.write(control)
with open(os.path.join(pkg, "usr", "bin", "hello"), "wb") as f:
f.write(b"#!/bin/sh\necho hello\n")
os.chmod(os.path.join(pkg, "usr", "bin", "hello"), 0o755)
with open(os.path.join(pkg, "usr", "share", "doc", "hello", "README"), "wb") as f:
f.write(rng.randbytes(2000))
fields = {"Package": "hello", "Version": "1.0-1", "Architecture": "all", "Maintainer": "Ada <[email protected]>",
"Depends": "libc6 (>= 2.31)", "Description": "a greeting\nprints a greeting\n.\nand exits"}
env = dict(os.environ, SOURCE_DATE_EPOCH=str(MTIME))
debs = []
for z, ext in (("xz", ".xz"), ("gzip", ".gz"), ("zstd", ".zst"), ("none", "")):
data = sh(["dpkg"], "dpkg-deb --root-owner-group -Z%s --build pkg out.deb >/dev/null && cat out.deb && rm out.deb" % z, tmp, env)
raw = None
p = 8
while p < len(data):
n = int(data[p + 48:p + 58])
if data[p:p + 8] == b"data.tar":
m = data[p + 60:p + 60 + n]
raw = unpack(z, m)
p += 60 + n + (n & 1)
debs.append({"name": "dpkg-" + z, "data": data, "control": fields, "payload": "data.tar" + ext, "entries": tar_entries(raw)})
# older compressors, assembled here: control.tar.bz2 + data.tar.bz2, control.tar.lzma + data.tar.lzma
def tar_of(root, prefix):
b = io.BytesIO()
with tarfile.open(fileobj=b, mode="w", format=tarfile.GNU_FORMAT) as t:
t.add(root, arcname=prefix, filter=lambda ti: setattr(ti, "mtime", MTIME) or ti)
return b.getvalue()
ctl = tar_of(os.path.join(pkg, "DEBIAN"), ".")
dat_dir = os.path.join(tmp, "datatree")
shutil.copytree(pkg, dat_dir, ignore=shutil.ignore_patterns("DEBIAN"))
dat = tar_of(dat_dir, ".")
alone = lambda b: lzma.compress(b, format=lzma.FORMAT_ALONE)
for name, comp, ext in (("py-bzip2", bz2.compress, ".bz2"), ("py-lzma", alone, ".lzma")):
data = b"!<arch>\n" + ar_member(b"debian-binary", b"2.0\n") + ar_member(b"control.tar" + ext.encode(), comp(ctl)) + \
ar_member(b"data.tar" + ext.encode(), comp(dat))
debs.append({"name": name, "data": data, "control": fields, "payload": "data.tar" + ext, "entries": tar_entries(dat)})
finally:
shutil.rmtree(tmp)
ctx.emit("ar", {"files": [{"name": n, "data": d} for n, d in files], "gnuD": gnuD, "archives": archives, "debs": debs})
+110
View File
@@ -0,0 +1,110 @@
# cpio fixtures (tools/fixtures.py): GNU cpio (nixpkgs#cpio, --reproducible) archives of one tree in newc / crc / odc /
# bin, the bin one byte-swapped into the big-endian old binary format, bsdtar (libarchive) newc / odc archives, a crafted
# newc archive with device nodes and a bad crc sum, and a .cpio.gz. The expected entries come from os.lstat of the tree.
# tests/gen/cpio.luau { archives = { { name, data, format, gnu?, entries = { { name, type, mode, size, mtime, nlink,
# link?, crc? } } } }, devices = data, badcrc = data, gz = data }
import gzip, os, shutil, stat, struct, subprocess, tempfile, zlib
TYPES = {stat.S_IFREG: "0", stat.S_IFDIR: "5", stat.S_IFLNK: "2", stat.S_IFIFO: "6", stat.S_IFCHR: "3", stat.S_IFBLK: "4"}
def run(ctx, pkg, script, cwd):
return subprocess.run(["nix", "shell", "nixpkgs#" + pkg, "-c", "sh", "-c", script], cwd=cwd, capture_output=True, check=True).stdout
def swap_bin(data):
"""the little-endian old binary archive -> the big-endian one (every u16 header field swapped)"""
out, p = bytearray(), 0
while True:
f = struct.unpack("<13H", data[p:p + 26])
ns, fs = f[10], f[11] << 16 | f[12]
name = data[p + 26:p + 26 + ns - 1]
out += struct.pack(">13H", *f)
q = p + 26 + ns + (ns & 1)
e = q + fs + (fs & 1)
out += data[p + 26:e]
p = e
if name == b"TRAILER!!!":
return bytes(out + data[p:])
def newc(name, mode, size=0, data=b"", nlink=1, rdev=(0, 0), check=0, ino=1, crc=False):
ns = len(name) + 1
h = b"070701" + b"".join(b"%08X" % v for v in (ino, mode, 0, 0, nlink, 1600000000, size, 0, 0, rdev[0], rdev[1], ns, check))
if crc:
h = b"070702" + h[6:]
b = h + name + b"\0"
b += b"\0" * (-len(b) % 4) + data + b"\0" * (-len(data) % 4)
return b
def generate(ctx):
rng = ctx.rng(11)
files = [
("hello.txt", b"hello, cpio\n"),
("empty", b""),
("dir/sub/data.bin", rng.randbytes(3000)),
("exact4", b"four"),
("odd", b"x" * 7),
("d" * 60 + "/" + "e" * 80 + "/a-name-longer-than-a-hundred-bytes.txt", b"long " * 40),
("unicodé/naïve.txt", "ünïcödé".encode()),
]
tmp = tempfile.mkdtemp()
try:
root = os.path.join(tmp, "tree")
for name, data in files:
p = os.path.join(root, name)
os.makedirs(os.path.dirname(p), exist_ok=True)
with open(p, "wb") as f:
f.write(data)
os.chmod(os.path.join(root, "odd"), 0o755)
os.makedirs(os.path.join(root, "emptydir"))
os.symlink("hello.txt", os.path.join(root, "sym"))
os.symlink("dir/sub/data.bin", os.path.join(root, "dir/sublink"))
os.link(os.path.join(root, "hello.txt"), os.path.join(root, "hard"))
os.link(os.path.join(root, "hello.txt"), os.path.join(root, "dir/hard2"))
os.mkfifo(os.path.join(root, "fifo"))
for dirpath, dirs, fs in os.walk(root):
for n in dirs + fs:
os.utime(os.path.join(dirpath, n), (1650000000, 1650000000), follow_symlinks=False)
os.utime(root, (1650000000, 1650000000))
names = sorted(subprocess.run(["find", "."], cwd=root, capture_output=True, check=True).stdout.decode().split("\n")[:-1])
names = [n[2:] if n.startswith("./") else n for n in names]
def expected():
out = []
for n in names:
st = os.lstat(os.path.join(root, n))
t = TYPES[stat.S_IFMT(st.st_mode)]
e = {"name": n, "type": t, "mode": stat.S_IMODE(st.st_mode), "mtime": int(st.st_mtime), "nlink": st.st_nlink,
"size": st.st_size if t == "0" else 0}
if t == "2":
e["link"] = os.readlink(os.path.join(root, n))
if t == "0":
with open(os.path.join(root, n), "rb") as f:
e["crc"] = zlib.crc32(f.read())
out.append(e)
return out
want = expected()
listing = "find . | LC_ALL=C sort | "
archives = []
for fmt in ("newc", "crc", "odc", "bin"):
data = run(ctx, "cpio", listing + "cpio -o -H %s --reproducible 2>/dev/null" % fmt, root)
archives.append({"name": "gnu-" + fmt, "data": data, "format": fmt, "gnu": True, "entries": want})
archives.append({"name": "gnu-binbe", "data": swap_bin(archives[3]["data"]), "format": "binbe", "entries": want})
for fmt in ("newc", "odc"):
data = run(ctx, "libarchive", listing + "sed 's|^\\./||' | bsdtar --format=%s -n -cf - -T -" % fmt, root)
archives.append({"name": "bsdtar-" + fmt, "data": data, "format": fmt, "entries": want})
gz = gzip.compress(archives[0]["data"], mtime=0)
finally:
shutil.rmtree(tmp)
devices = b"".join([
newc(b"dev", 0o040755, nlink=2, ino=1),
newc(b"dev/null", 0o020666, rdev=(1, 3), ino=2),
newc(b"dev/sda", 0o060660, rdev=(8, 0), ino=3),
newc(b"dev/sock", 0o140755, ino=4),
newc(b"TRAILER!!!", 0, ino=0),
])
badcrc = newc(b"f", 0o100644, 3, b"abc", check=1, crc=True) + newc(b"TRAILER!!!", 0, ino=0, crc=True)
ctx.emit("cpio", {"archives": archives, "devices": devices, "badcrc": badcrc, "gz": gz})
+81
View File
@@ -0,0 +1,81 @@
# Docs inputs for the archive page's Unix / package sections (tools/fixtures.py; tools/docs_check.py explains the
# inputs): a newc cpio by GNU cpio, a .deb by dpkg-deb, an .rpm by rpmbuild, a .tar.Z by ncompress, an ISO image by
# xorriso (-J -R, with an El Torito boot image) and an .lz4 by the lz4 tool, all of one small tree.
# tests/gen/docs_arch_unix.luau { files = { [name] = bytes }, vars = { cpioBytes = "tree.cpio", ... } }
import importlib.util, io, os, subprocess, tarfile, tempfile
INPUTS = ["tools/docs_check.py"]
MTIME = 1767225600 # 2026-01-01T00:00:00Z
SPEC = """Name: hello
Version: 1.0
Release: 1
Summary: a greeting
License: MIT
BuildArch: noarch
%description
prints a greeting
%install
mkdir -p %{buildroot}/usr/bin
printf '#!/bin/sh\\necho hello\\n' > %{buildroot}/usr/bin/hello
chmod 755 %{buildroot}/usr/bin/hello
%files
/usr/bin/hello
"""
def docs_check(ctx):
spec = importlib.util.spec_from_file_location("docs_check", os.path.join(ctx.root, "tools", "docs_check.py"))
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
return m
def sh(pkgs, script, cwd, env=None):
argv = ["nix", "shell"] + ["nixpkgs#" + p for p in pkgs] + ["-c", "sh", "-c", script]
return subprocess.run(argv, cwd=cwd, capture_output=True, check=True, env=env).stdout
def generate(ctx):
dc = docs_check(ctx)
files = {}
env = dict(os.environ, SOURCE_DATE_EPOCH=str(MTIME))
with tempfile.TemporaryDirectory() as d:
tree = os.path.join(d, "tree")
os.makedirs(os.path.join(tree, "bin"))
with open(os.path.join(tree, "readme.txt"), "wb") as f:
f.write(b"formats-luau unix archives\n")
with open(os.path.join(tree, "bin", "run.sh"), "wb") as f:
f.write(b"#!/bin/sh\necho hi\n")
os.chmod(os.path.join(tree, "bin", "run.sh"), 0o755)
os.symlink("bin/run.sh", os.path.join(tree, "run"))
with open(os.path.join(tree, "boot.img"), "wb") as f:
f.write(b"\xfa\xeb\xfe" + bytes(2045))
for dirpath, dirs, fs in os.walk(tree):
for n in dirs + fs:
os.utime(os.path.join(dirpath, n), (MTIME, MTIME), follow_symlinks=False)
files["tree.cpio"] = sh(["cpio", "findutils"], "find readme.txt bin run | LC_ALL=C sort | cpio -o -H newc --reproducible 2>/dev/null", tree)
files["disc.iso"] = sh(["xorriso"], "xorriso -as mkisofs -quiet -no-pad -J -R -V DOCS -b boot.img -no-emul-boot -boot-load-size 4 -o - .", tree)
b = io.BytesIO()
with tarfile.open(fileobj=b, mode="w", format=tarfile.PAX_FORMAT) as t:
for n in ("readme.txt", "bin/run.sh"):
t.add(os.path.join(tree, n), arcname=n)
files["src.tar.Z"] = subprocess.run(["nix", "shell", "nixpkgs#ncompress", "-c", "compress", "-c", "-f"], input=b.getvalue(),
capture_output=True, check=True).stdout
files["notes.txt.lz4"] = subprocess.run(["nix", "shell", "nixpkgs#lz4", "-c", "lz4", "-c"], input=b"formats-luau unix archives\n" * 8,
capture_output=True, check=True).stdout
pkg = os.path.join(d, "pkg")
os.makedirs(os.path.join(pkg, "DEBIAN"))
os.makedirs(os.path.join(pkg, "usr", "bin"))
with open(os.path.join(pkg, "DEBIAN", "control"), "w") as f:
f.write("Package: hello\nVersion: 1.0-1\nArchitecture: all\nMaintainer: Ada <[email protected]>\nDescription: a greeting\n")
with open(os.path.join(pkg, "usr", "bin", "hello"), "wb") as f:
f.write(b"#!/bin/sh\necho hello\n")
os.chmod(os.path.join(pkg, "usr", "bin", "hello"), 0o755)
files["hello.deb"] = sh(["dpkg"], "dpkg-deb --root-owner-group -Zxz --build pkg out.deb >/dev/null && cat out.deb", d, env)
with open(os.path.join(d, "hello.spec"), "w") as f:
f.write(SPEC)
sh(["rpm"], "rpmbuild --define '_topdir %s/top' --define '__os_install_post %%{nil}' --define '_build_id_links none' -bb hello.spec >/dev/null 2>&1" % d, d, env)
files["hello.rpm"] = open(os.path.join(d, "top", "RPMS", "noarch", "hello-1.0-1.noarch.rpm"), "rb").read()
dc.emit_inputs(ctx, files, {"cpioBytes": "tree.cpio", "isoBytes": "disc.iso", "tarZBytes": "src.tar.Z", "lz4Bytes": "notes.txt.lz4",
"debBytes": "hello.deb", "rpmBytes": "hello.rpm"})
+195
View File
@@ -0,0 +1,195 @@
# iso fixtures (tools/fixtures.py): ISO 9660 images of one tree built by xorriso (nixpkgs#xorriso: plain and Joliet
# with -rockridge off, then the mkisofs emulation -R, -J -R, an El Torito no-emulation boot image) and genisoimage (nixpkgs#cdrkit, -J -R: deep directories
# relocated to rr_moved, long names and symlink targets in CE continuation areas), plus a multi-extent file and an
# interleaved file crafted here by splitting / editing a directory record. Expected listings: the source tree (os.lstat)
# for Rock Ridge images, pycdlib (a second reader, run through nix python) for the plain and Joliet name sets.
# tests/gen/iso.luau { images = { { name, data (or same = the index of the image with the same data), tree, entries = { { name, dir, size?, crc?, mode?, link?, mtime? } } } },
# boot = { data, lba, sectors, catalog }, multi = { data, name, size, crc }, interleaved = data }
import json, os, shutil, stat, struct, subprocess, tempfile, zlib
MTIME = 1650000000
DUMP = r"""
import json, sys, io, zlib, pycdlib
path, kind = sys.argv[1], sys.argv[2]
iso = pycdlib.PyCdlib()
iso.open(path)
out = []
key = {"joliet": "joliet_path", "iso9660": "iso_path"}[kind]
for d, dirs, files in iso.walk(**{key: "/"}):
base = d.rstrip("/")
for n in dirs:
out.append({"name": (base + "/" + n).lstrip("/"), "dir": True})
for n in files:
p = base + "/" + n
b = io.BytesIO()
iso.get_file_from_iso_fp(b, **{key: p})
name = p.lstrip("/")
if ";" in name:
name = name[:name.rindex(";")]
if kind == "iso9660" and name.endswith("."):
name = name[:-1]
out.append({"name": name, "dir": False, "size": len(b.getvalue()), "crc": zlib.crc32(b.getvalue())})
iso.close()
sys.stdout.write(json.dumps(out))
"""
def sh(pkg, argv, cwd):
return subprocess.run(["nix", "shell", "nixpkgs#" + pkg, "-c"] + argv, cwd=cwd, capture_output=True, check=True).stdout
def tree_entries(root, skip_deep=False):
out = []
for dirpath, dirs, files in os.walk(root):
dirs.sort()
for n in sorted(dirs + files):
p = os.path.join(dirpath, n)
rel = os.path.relpath(p, root)
st = os.lstat(p)
e = {"name": rel, "dir": stat.S_ISDIR(st.st_mode), "mode": stat.S_IMODE(st.st_mode), "mtime": MTIME}
if stat.S_ISLNK(st.st_mode):
e["link"] = os.readlink(p)
elif stat.S_ISREG(st.st_mode):
with open(p, "rb") as f:
d = f.read()
e["size"], e["crc"] = len(d), zlib.crc32(d)
out.append(e)
return out
def split_record(data, name, at_bytes):
"""a multi-extent copy: the directory record of name split into two records (the first flagged 0x80)"""
img = bytearray(data)
root_lba = struct.unpack_from("<I", img, 16 * 2048 + 156 + 2)[0]
root_len = struct.unpack_from("<I", img, 16 * 2048 + 156 + 10)[0]
p, e = root_lba * 2048, root_lba * 2048 + root_len
while p < e:
ln = img[p]
if ln == 0:
p = (p // 2048 + 1) * 2048
continue
nl = img[p + 32]
if bytes(img[p + 33:p + 33 + nl]) == name:
rec = bytearray(img[p:p + ln])
size = struct.unpack_from("<I", rec, 10)[0]
lba = struct.unpack_from("<I", rec, 2)[0]
a, b2 = bytearray(rec), bytearray(rec)
struct.pack_into("<I", a, 10, at_bytes)
struct.pack_into(">I", a, 14, at_bytes)
a[25] |= 0x80
struct.pack_into("<I", b2, 2, lba + at_bytes // 2048)
struct.pack_into(">I", b2, 6, lba + at_bytes // 2048)
struct.pack_into("<I", b2, 10, size - at_bytes)
struct.pack_into(">I", b2, 14, size - at_bytes)
sector_end = (p // 2048 + 1) * 2048
used = sector_end
q = p + ln
while q < sector_end and img[q] != 0:
q += img[q]
assert q + ln <= sector_end, "no room in the directory sector"
img[p:q + ln] = a + b2 + img[p + ln:q]
return bytes(img), size
p += ln
raise Exception("record not found")
def set_interleave(data, name):
img = bytearray(data)
root_lba = struct.unpack_from("<I", img, 16 * 2048 + 156 + 2)[0]
p = root_lba * 2048
while img[p]:
nl = img[p + 32]
if bytes(img[p + 33:p + 33 + nl]) == name:
img[p + 26], img[p + 27] = 1, 1
return bytes(img)
p += img[p]
raise Exception("record not found")
def generate(ctx):
rng = ctx.rng(29)
tmp = tempfile.mkdtemp()
try:
root = os.path.join(tmp, "tree")
files = [
("hello.txt", b"hello, iso\n"),
("empty", b""),
("dir/sub/data.bin", rng.randbytes(5000)),
("big.bin", rng.randbytes(40000)),
("A File With Spaces And A Name Longer Than Sixty-Four Characters For Joliet.txt", b"long joliet\n"),
("unicodé/naïve.txt", "ünïcödé".encode()),
("run.sh", b"#!/bin/sh\necho hi\n"),
]
for n, d in files:
p = os.path.join(root, n)
os.makedirs(os.path.dirname(p), exist_ok=True)
with open(p, "wb") as f:
f.write(d)
os.chmod(os.path.join(root, "run.sh"), 0o755)
os.symlink("hello.txt", os.path.join(root, "link"))
os.makedirs(os.path.join(root, "emptydir"))
for dirpath, dirs, fs in os.walk(root):
for n in dirs + fs:
os.utime(os.path.join(dirpath, n), (MTIME, MTIME), follow_symlinks=False)
base_entries = tree_entries(root)
# a second tree with what only Rock Ridge holds: deep directories, a 200-byte name, a long symlink target
root2 = os.path.join(tmp, "tree2")
shutil.copytree(root, root2, symlinks=True)
deep = os.path.join(root2, *["d%d" % i for i in range(1, 11)])
os.makedirs(deep)
with open(os.path.join(deep, "deep.txt"), "wb") as f:
f.write(b"ten levels down\n")
with open(os.path.join(root2, "n" * 200), "wb") as f:
f.write(b"a 200-byte name\n")
os.symlink("/" + "/".join(["target-component-%02d" % i for i in range(16)]), os.path.join(root2, "longlink"))
for dirpath, dirs, fs in os.walk(root2):
for n in dirs + fs:
os.utime(os.path.join(dirpath, n), (MTIME, MTIME), follow_symlinks=False)
rr_entries = tree_entries(root2)
images = []
def dump(path, kind):
return json.loads(ctx.python(["pycdlib"], DUMP.replace("sys.argv[1], sys.argv[2]", repr(path) + ", " + repr(kind))))
def xorriso(name, args, src, tree, entries=None):
out = os.path.join(tmp, name + ".iso")
if args and args[0] == "native": # xorriso's own commands (mkisofs emulation always writes Rock Ridge)
sh("xorriso", ["xorriso", "-outdev", out, "-padding", "0"] + args[1:] + ["-map", src, "/"], tmp)
else:
sh("xorriso", ["xorriso", "-as", "mkisofs", "-quiet", "-no-pad", "-o", out] + args + [src], tmp)
if entries is None:
entries = dump(out, tree)
images.append({"name": name, "data": open(out, "rb").read(), "tree": tree, "entries": entries})
return out
plain = xorriso("xorriso-plain", ["native", "-rockridge", "off"], root, "iso9660")
xorriso("xorriso-J", ["native", "-rockridge", "off", "-joliet", "on"], root, "joliet")
xorriso("xorriso-R", ["-R"], root, "rockridge", base_entries)
xorriso("xorriso-JR", ["-J", "-R"], root2, "rockridge", rr_entries)
out = os.path.join(tmp, "geniso.iso")
sh("cdrkit", ["genisoimage", "-quiet", "-no-pad", "-J", "-R", "-o", out, root2], tmp)
images.append({"name": "genisoimage-JR", "data": open(out, "rb").read(), "tree": "rockridge", "entries": rr_entries})
# Joliet from the -J -R image too (prefer = "joliet")
images.append({"name": "genisoimage-JR-joliet", "same": len(images), "tree": "joliet", "entries": dump(out, "joliet")})
# El Torito
bootdir = os.path.join(tmp, "boot")
shutil.copytree(root, bootdir, symlinks=True)
with open(os.path.join(bootdir, "boot.img"), "wb") as f:
f.write(b"\xfa\xeb\xfe" + bytes(2045))
out = os.path.join(tmp, "boot.iso")
sh("xorriso", ["xorriso", "-as", "mkisofs", "-quiet", "-no-pad", "-R", "-o", out, "-b", "boot.img", "-c", "boot.cat", "-no-emul-boot",
"-boot-load-size", "4", bootdir], tmp)
bdata = open(out, "rb").read()
info = subprocess.run(["nix", "shell", "nixpkgs#xorriso", "-c", "xorriso", "-indev", out, "-report_el_torito", "plain"],
capture_output=True, text=True).stdout
# "El Torito boot img : 1 BIOS y none 0x0000 0x00 4 LBA"
row = [l for l in info.split("\n") if l.startswith("El Torito boot img")][0].split()
cat = [l for l in info.split("\n") if l.startswith("El Torito catalog")][0].split()
boot = {"data": bdata, "sectors": int(row[-2]), "lba": int(row[-1]), "bootable": row[7] == "y", "catalog": int(cat[4])}
multi, msize = split_record(open(plain, "rb").read(), b"BIG.BIN;1", 2048 * 8)
mcrc = zlib.crc32(dict(files)["big.bin"])
interleaved = set_interleave(open(plain, "rb").read(), b"HELLO.TXT;1")
finally:
shutil.rmtree(tmp)
ctx.emit("iso", {"images": images, "boot": boot, "multi": {"data": multi, "name": "BIG.BIN", "size": msize, "crc": mcrc},
"interleaved": interleaved})
+90
View File
@@ -0,0 +1,90 @@
# LZ4 block fixtures (tools/fixtures.py): deterministic corpora compressed by the reference (python-lz4, the lz4
# library: fast mode at several accelerations, and HC at levels 4 / 9 / 12), plus our own encoder's blocks
# (tools/fixtures/_lz4_encode.luau under the luau CLI) decompressed by the reference, as verdicts.
# tests/gen/lz4.luau { corpora = { [name] = bytes }, cases = { { name, corpus, data } }, ours = { { name, ok } } }
# tests/gen/lz4_bench.luau { size, crc, data (lz4 HC 9 block), raw }
import json, os, random, shutil, subprocess, zlib
INPUTS = ["src/Formats/codecs/compress/Lz4.luau", "tools/fixtures/_lz4_encode.luau"]
REF = r"""
import json, sys, lz4.block
req = json.load(sys.stdin)
out = {}
if req["op"] == "compress":
for name, hexdata in req["corpora"].items():
data = bytes.fromhex(hexdata)
res = {}
for acc in (1, 4, 16):
res["fast%d" % acc] = lz4.block.compress(data, mode="fast", acceleration=acc, store_size=False).hex()
for lv in (4, 9, 12):
res["hc%d" % lv] = lz4.block.compress(data, mode="high_compression", compression=lv, store_size=False).hex()
out[name] = res
else:
for name, item in req["blocks"].items():
try:
got = lz4.block.decompress(bytes.fromhex(item["data"]), uncompressed_size=item["size"])
out[name] = got.hex() == item["want"]
except Exception as e:
out[name] = False
print(json.dumps(out))
"""
def corpora(rng):
base = os.path.dirname(os.__file__)
text = bytearray()
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) >= 300000:
break
text = bytes(text[:300000])
far = rng.randbytes(9000)
return {
"empty": b"",
"one": b"a",
"twelve": b"abcabcabcabc",
"thirteen": b"abcabcabcabca",
"short": b"hello, hello, hello lz4 world\n",
"text": text[:150000],
"random": rng.randbytes(20000),
"runs": b"abc" * 4000 + b"\0" * 70000 + bytes(range(256)) * 40 + b"z" * 300,
"zeros": b"\0" * 100000,
"far": far + rng.randbytes(60000) + far,
"binary": bytes(rng.choice(b"\0\0\0\x01\x02\xff ABC") for _ in range(60000)),
"longlit": rng.randbytes(1000) + b"q" * 1000 + rng.randbytes(300),
}
def luau_cmd():
exe = shutil.which("luau")
return [exe] if exe else ["nix", "shell", "nixpkgs#luau", "-c", "luau"]
def generate(ctx):
rng = random.Random(41)
cs = corpora(rng)
ref = json.loads(ctx.python(["lz4"], REF, input=json.dumps({"op": "compress", "corpora": {k: v.hex() for k, v in cs.items()}}).encode()))
cases = []
for name, res in ref.items():
for mode, hexdata in res.items():
cases.append({"name": "%s/%s" % (name, mode), "corpus": name, "data": bytes.fromhex(hexdata)})
# our encoder's blocks, read back by the reference
ctx.emit("lz4_corpora", cs)
enc = subprocess.run(luau_cmd() + [os.path.join(ctx.root, "tools", "fixtures", "_lz4_encode.luau")], capture_output=True, check=True, cwd=ctx.root).stdout.decode()
blocks = {}
for line in enc.split("\n"):
if line.strip():
name, hexdata = line.split(" ", 1)
blocks[name] = {"data": hexdata.strip(), "size": len(cs[name]), "want": cs[name].hex()}
verdict = json.loads(ctx.python(["lz4"], REF, input=json.dumps({"op": "decompress", "blocks": blocks}).encode()))
ours = [{"name": n, "ok": bool(verdict.get(n)), "size": len(bytes.fromhex(blocks[n]["data"]))} for n in sorted(blocks)]
ctx.emit("lz4", {"cases": cases, "ours": ours})
bench = bytearray()
while len(bench) < 6_000_000:
bench += cs["text"] + bytes(rng.choice(b"\0\0\0\x01\x02\xff ABC") for _ in range(100000)) + rng.randbytes(20000)
bench = bytes(bench[:6_000_000])
code = "import sys, lz4.block; sys.stdout.buffer.write(lz4.block.compress(sys.stdin.buffer.read(), mode='high_compression', compression=9, store_size=False))"
ctx.emit("lz4_bench", {"size": len(bench), "crc": zlib.crc32(bench), "data": ctx.python(["lz4"], code, input=bench)})
+72
View File
@@ -0,0 +1,72 @@
# LZ4 frame fixtures (tools/fixtures.py): corpora compressed by the lz4 tool 1.10 (nixpkgs#lz4) with its frame options
# (default, linked blocks -BD, 64 KB blocks -B4 with and without -BD, block checksums -BX, --content-size,
# --no-frame-crc, -9, the legacy format -l), concatenated frames and a skippable frame; and our writer's frames
# (tools/fixtures/_lz4frame_encode.luau under the luau CLI) decompressed by `lz4 -d`, as verdicts.
# tests/gen/lz4frame.luau { cases = { { name, corpus, data } }, ours = { { name, ok } } }
# tests/gen/lz4frame_corpora.luau { [name] = bytes }
import os, shutil, struct, subprocess, tempfile
INPUTS = ["src/Formats/archive/lz4/init.luau", "src/Formats/codecs/compress/Lz4.luau", "src/Formats/codecs/compress/Xxh32.luau",
"tools/fixtures/_lz4frame_encode.luau"]
def lz4(args, data=None, path=None):
argv = ["nix", "shell", "nixpkgs#lz4", "-c", "lz4"] + args + ([path] if path else [])
return subprocess.run(argv, input=data, capture_output=True, check=True).stdout
def corpora(rng):
base = os.path.dirname(os.__file__)
text = bytearray()
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) >= 160000:
break
return {"empty": b"", "short": b"hello, lz4 frames\n", "text": bytes(text[:160000]), "random": rng.randbytes(20000),
"zeros": b"\0" * 300000}
def luau_cmd():
exe = shutil.which("luau")
return [exe] if exe else ["nix", "shell", "nixpkgs#luau", "-c", "luau"]
def generate(ctx):
cs = corpora(ctx.rng(43))
cases = []
tmp = tempfile.mkdtemp()
try:
for name, data in cs.items():
path = os.path.join(tmp, name)
with open(path, "wb") as f:
f.write(data)
variants = [("default", ["-c"])]
if name in ("text", "zeros", "short"):
variants += [("BD", ["-c", "-BD"]), ("B4", ["-c", "-B4"]), ("B4BD", ["-c", "-B4", "-BD"]), ("BX", ["-c", "-B4", "-BX"]),
("size", ["-c", "--content-size"]), ("nocrc", ["-c", "--no-frame-crc"]), ("hc9", ["-c", "-9", "-B4", "-BD"]),
("legacy", ["-c", "-l"])]
for vname, args in variants:
cases.append({"name": name + "/" + vname, "corpus": name, "data": lz4(args, path=path)})
finally:
shutil.rmtree(tmp)
# two frames, and a skippable frame in front
two = lz4(["-c"], data=cs["short"]) + lz4(["-c", "-B4"], data=cs["text"])
cases.append({"name": "concat", "corpus": "short+text", "data": two})
skip = struct.pack("<II", 0x184D2A53, 5) + b"skip!" + lz4(["-c"], data=cs["short"])
cases.append({"name": "skippable", "corpus": "short", "data": skip})
ctx.emit("lz4frame_corpora", cs)
enc = subprocess.run(luau_cmd() + [os.path.join(ctx.root, "tools", "fixtures", "_lz4frame_encode.luau")], capture_output=True,
check=True, cwd=ctx.root).stdout.decode()
ours = []
for line in enc.split("\n"):
if line.strip():
name, hexdata = line.split(" ", 1)
try:
got = lz4(["-d", "-c"], data=bytes.fromhex(hexdata.strip()))
ok = got == cs[name.split("/")[0]]
except subprocess.CalledProcessError:
ok = False
ours.append({"name": name, "ok": ok})
ctx.emit("lz4frame", {"cases": cases, "ours": sorted(ours, key=lambda o: o["name"])})
+101
View File
@@ -0,0 +1,101 @@
# rpm fixtures (tools/fixtures.py): one package built by rpmbuild (nixpkgs#rpm) with each payload compressor (gzip,
# bzip2, xz, lzma, zstd, none), holding files, a symlink, a hard link pair, a directory and a %ghost file. The expected
# header fields and file list come from `rpm -qp --qf`, the file data from rpm2cpio's cpio stream (parsed here).
# tests/gen/rpm.luau { rpms = { { name, data, compressor, fields = { name, version, ... }, files = { { name, size,
# mode, mtime, link?, crc? } }, cpioCrc } } }
import os, shutil, subprocess, tempfile, zlib
SPEC = r"""
Name: hello
Version: 1.0
Release: 3
Epoch: 2
Summary: a greeting
License: MIT
URL: https://example.org/hello
Group: Applications/Text
BuildArch: noarch
%description
prints a greeting
and exits
%install
mkdir -p %{buildroot}/usr/bin %{buildroot}/usr/share/doc/hello %{buildroot}/var/log
printf '#!/bin/sh\necho hello\n' > %{buildroot}/usr/bin/hello
chmod 755 %{buildroot}/usr/bin/hello
python3 -c "import random; open('%{buildroot}/usr/share/doc/hello/README', 'wb').write(random.Random(3).randbytes(20000))"
printf 'a long name' > "%{buildroot}/usr/share/doc/hello/a file name with spaces and more than one hundred characters, to pass every old limit of the cpio or tar headers.txt"
ln -s hello %{buildroot}/usr/bin/hi
ln %{buildroot}/usr/bin/hello %{buildroot}/usr/bin/hello2
touch %{buildroot}/var/log/hello.log
%files
/usr/bin/hello
/usr/bin/hello2
/usr/bin/hi
%dir /usr/share/doc/hello
/usr/share/doc/hello/README
"/usr/share/doc/hello/a file name with spaces and more than one hundred characters, to pass every old limit of the cpio or tar headers.txt"
%ghost /var/log/hello.log
"""
QF = "%{NAME}\\n%{VERSION}\\n%{RELEASE}\\n%{EPOCH}\\n%{ARCH}\\n%{OS}\\n%{LICENSE}\\n%{URL}\\n%{PAYLOADCOMPRESSOR}\\n%{PAYLOADFORMAT}\\n%{SUMMARY}\\n"
FQF = "[%{FILENAMES}\\t%{FILESIZES}\\t%{FILEMODES}\\t%{FILEMTIMES}\\t%{FILELINKTOS}\\t%{FILEFLAGS}\\n]"
def cpio_files(d):
out, ino, p = {}, {}, 0
while p < len(d):
h = d[p:p + 110]
f = [int(h[6 + 8 * i:14 + 8 * i], 16) for i in range(13)]
ns, fs = f[11], f[6]
name = d[p + 110:p + 110 + ns - 1].decode()
p = (p + 110 + ns + 3) & ~3
if name == "TRAILER!!!":
out[None] = p # the archive's end (rpm2cpio pads its output with zeros)
break
out[name[2:] if name.startswith("./") else name] = f[0]
if fs:
ino[f[0]] = d[p:p + fs]
p = (p + fs + 3) & ~3
return {n: (i if n is None else ino.get(i, b"")) for n, i in out.items()} # hard links: the data of their inode
def generate(ctx):
tmp = tempfile.mkdtemp()
rpms = []
try:
with open(os.path.join(tmp, "hello.spec"), "w") as f:
f.write(SPEC)
env = dict(os.environ, SOURCE_DATE_EPOCH="1700000000")
for comp, io in (("gzip", "w9.gzdio"), ("bzip2", "w9.bzdio"), ("xz", "w6.xzdio"), ("lzma", "w6.lzdio"), ("zstd", "w19.zstdio"), ("none", "w0.ufdio")):
top = os.path.join(tmp, "top-" + comp)
subprocess.run(["nix", "shell", "nixpkgs#rpm", "nixpkgs#python3", "-c", "rpmbuild", "--define", "_topdir " + top,
"--define", "_binary_payload " + io, "--define", "__os_install_post %{nil}",
"--define", "_build_id_links none", "--define", "use_source_date_epoch_as_buildtime 1",
"--define", "clamp_mtime_to_source_date_epoch 1", "-bb", "hello.spec"],
cwd=tmp, capture_output=True, check=True, env=env)
path = os.path.join(top, "RPMS", "noarch", "hello-1.0-3.noarch.rpm")
data = open(path, "rb").read()
q = lambda fmt: subprocess.run(["nix", "shell", "nixpkgs#rpm", "-c", "rpm", "--dbpath", os.path.join(tmp, "db"), "-qp", "--qf", fmt, path],
capture_output=True, check=True).stdout.decode()
v = q(QF).split("\n")
fields = dict(zip(["name", "version", "release", "epoch", "arch", "os", "license", "url", "payloadCompressor", "payloadFormat", "summary"], v))
fields["epoch"] = int(fields["epoch"])
if comp == "none":
del fields["payloadCompressor"] # whatever rpm stores for "no compression" is checked by the test itself
raw = subprocess.run(["nix", "shell", "nixpkgs#rpm", "-c", "rpm2cpio", path], capture_output=True, check=True).stdout
content = cpio_files(raw)
files = []
for line in q(FQF).split("\n")[:-1]:
name, size, mode, mtime, link, flags = line.split("\t")
e = {"name": name.lstrip("/"), "size": int(size), "mode": int(mode) & 0xFFF, "type": int(mode) & 0xF000,
"mtime": int(mtime), "flags": int(flags)}
if link:
e["link"] = link
if e["name"] in content and e["type"] == 0x8000:
e["crc"] = zlib.crc32(content[e["name"]])
files.append(e)
rpms.append({"name": "rpmbuild-" + comp, "data": data, "compressor": comp, "fields": fields, "files": files,
"cpioCrc": zlib.crc32(raw[:content[None]]), "cpioSize": content[None]})
finally:
shutil.rmtree(tmp)
ctx.emit("rpm", {"rpms": rpms})
+45
View File
@@ -0,0 +1,45 @@
# .Z fixtures (tools/fixtures.py): Unix compress files written by ncompress 5.0 (nixpkgs#ncompress, `compress -c -f
# -b N`) from a few inputs: empty, one byte, short text, a 700 KB word corpus with incompressible stretches (the 16-bit
# table fills, the ratio check emits CLEAR codes), random bytes, and every width 10..16; a .tar.Z for the api's unwrap.
# gzip -d reads each file too (its output must be the input: a second decoder agreeing on what ncompress wrote).
# tests/gen/z.luau { cases = { { name, input, bits, z } }, tarZ = data, tarNames = { ... } }
import io, subprocess, tarfile
def compress(data, bits):
return subprocess.run(["nix", "shell", "nixpkgs#ncompress", "-c", "compress", "-c", "-f", "-b", str(bits)], input=data,
capture_output=True, check=True).stdout
def corpus(rng, size):
words = ["".join(rng.choice("abcdefghijklmnopqrstuvwxyz") for _ in range(rng.randint(2, 9))) for _ in range(3000)]
out = bytearray()
while len(out) < size:
if rng.random() < 0.002:
out += rng.randbytes(rng.randint(500, 4000)) # incompressible stretches: the ratio drops, CLEAR follows
else:
out += (" ".join(rng.choice(words) for _ in range(12)) + ".\n").encode()
return bytes(out[:size])
def generate(ctx):
rng = ctx.rng(23)
big = corpus(rng, 700000)
inputs = [("empty", b"", 16), ("one", b"A", 16), ("text", b"TOBEORNOTTOBEORTOBEORNOT#" * 40, 16),
("random", rng.randbytes(30000), 16), ("corpus16", big, 16)]
mid = big[:120000]
for bits in range(10, 16): # (-b 9 output does not round-trip through ncompress or gzip: not a valid file)
inputs.append(("corpus-b%d" % bits, mid, bits))
cases = []
for name, data, bits in inputs:
z = compress(data, bits)
back = subprocess.run(["nix", "shell", "nixpkgs#gzip", "-c", "gzip", "-d", "-c"], input=z, capture_output=True, check=True).stdout
assert back == data, "gzip -d disagrees on " + name
cases.append({"name": name, "input": data, "bits": bits, "z": z})
b = io.BytesIO()
with tarfile.open(fileobj=b, mode="w", format=tarfile.PAX_FORMAT) as t:
for n, d in (("a.txt", b"alpha\n"), ("b/c.txt", b"gamma " * 100)):
ti = tarfile.TarInfo(n)
ti.size, ti.mtime = len(d), 1700000000
t.addfile(ti, io.BytesIO(d))
ctx.emit("z", {"cases": cases, "tarZ": compress(b.getvalue(), 16), "tarNames": ["a.txt", "b/c.txt"]})