ws-arch2-unix: archive/ar (GNU / SysV long names + symbol tables, BSD #1/ names + __.SYMDEF; GNU / BSD writer) with .deb (meta.payload = data.tar.*, meta.control from control.tar.* via codecs/compress + containers/Tar), tests vs GNU ar (byte-identical), llvm-ar, bsdtar, dpkg-deb
This commit is contained in:
1 parent
a05199c34d
commit
07f70f70d5
5 files changed
+718
No files matched your search
@@ -50,6 +50,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
|
||||
| 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 | ar | .a .ar .deb .lib | yes | yes | variants: "gnu", "bsd", deb: true | `tests/archive/ar.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` |
|
||||
|
||||
@@ -554,6 +554,18 @@ local list: { Entry } = {
|
||||
return require("@formats/archive/7z")
|
||||
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 = "br",
|
||||
category = "archive",
|
||||
|
||||
@@ -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
|
||||
@@ -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()
|
||||
@@ -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})
|
||||
Reference in new issue
Block a user