- Zig 96%
- Python 3%
- Nix <1%
- Shell <1%
z2dimg #
Image files in and out of z2d surfaces,
for Zig 0.17. It reads and writes through a *std.Io.Reader and a
*std.Io.Writer you supply and performs no I/O of its own — and because the
decoders therefore make no system calls at all, one can be run in a forked
process that seccomp has reduced to four of them on Linux, or that Capsicum has
cut off from everything but its reply pipe on FreeBSD.
It builds on a fork of z2d, the same revision zig-svg uses. The fork is upstream with additions and nothing taken away, so its surfaces are z2d's, and a program using both libraries has one z2d rather than two.
const z2dimg = @import("z2dimg");
var buf: [4096]u8 = undefined;
var file_reader = file.reader(io, &buf);
var surface = try z2dimg.decode(gpa, &file_reader.interface, .{});
defer surface.deinit(gpa);
and back out again:
try z2dimg.encode(gpa, &surface, &file_writer.interface, .{ .png = .{} });
The tag of the options is the format, so there is no separate format argument to contradict them.
Each format has a page of its own in doc/, covering what it reads,
what it writes, and the decisions behind both.
| Format | Reads | Writes | Animation | Alpha | EXIF orientation | ICC profile | Not implemented |
|---|---|---|---|---|---|---|---|
| BMP | every header, depth and encoding, including embedded JPEG and PNG | 24- and 32-bit | — | read, write | — | no | OS/2 Huffman and 24-bit RLE compression; V5 embedded profiles; writing indexed, 16-bit, RLE or embedded JPEG/PNG |
| PNG | every color type, bit depth and interlacing, and APNG | 8-bit, with or without alpha, and APNG | read, write | read, write | read, write | read, write | writing 16-bit, paletted or interlaced files; 16-bit precision (read samples are scaled to 8 bits) |
| JPEG | baseline, extended and progressive, 8-bit; grayscale, YCbCr, CMYK and YCCK | baseline and progressive | — | — | read, write | read, write | arithmetic coding, lossless, hierarchical and 12-bit; writing CMYK or YCCK |
| GIF | still and animated, interlaced | still and animated | read, write | on or off only | — | no | reducing colors (more than 256 is refused) |
| TGA (Truevision) | every image type | true color, 24- or 32-bit, optionally run-length encoded | — | read, write | — | — | writing color-mapped or grayscale |
| XBM (X BitMap) | yes | yes, by thresholding | — | — | — | — | — |
| XPM (X PixMap) | up to four characters a pixel | yes | — | on or off only | — | — | more than four characters a pixel; reducing colors |
| PBM, PGM, PPM, PAM (Netpbm) | all seven layouts | all seven, plain or raw | — | PAM only | — | — | 16-bit precision (samples are scaled to 8 bits) |
| PCX (ZSoft PC Paintbrush) | every shape | every shape but monochrome | — | read, write (four-plane shape) | — | — | writing monochrome; reducing colors |
| ICO, CUR (Windows icons) | both entry shapes | several images, as DIBs or PNGs | — | read, write | — | no | profiles in PNG entries |
| WebP | lossless and lossy, still and animated | lossless, still | read | read, write | read | read | writing lossy or animated files, EXIF or ICC; the predictor transform when writing |
In the metadata columns, no means the format can carry it and this library does not read it, and — means the format has nowhere to put it. Animation covers reading and writing frames for every animated format, and a still image reads as an animation of one frame.
A format that is recognised but has no codec fails with error.Unsupported,
never with error.UnknownFormat: the library can tell a PNG from a stray file
and says so.
Camera raw formats (CR2, CR3, NEF and DNG) are not read yet; PLAN.md is the plan for them.
EXIF orientation is read from JPEG, PNG and WebP, and written to JPEG and PNG; nothing else about EXIF is read or written. See Orientation. ICC colour profiles are carried between JPEG and PNG without being interpreted, and read out of a WebP; see Colour profiles.
The API documentation is generated from the doc comments, which carry most of the explanation of why each format is the shape it is.
Where this lives #
The repository lives in three places that carry the same history. The Forgejo instance at https://git.jcollie.dev/jeff/z2dimg is the web-visible one:
$ git clone https://git.jcollie.dev/jeff/z2dimg.git
it is mirrored on Tangled at https://tangled.org/jcollie.dev/z2dimg, and it is also on the Radicle network, where the repository's identifier is
rad:z3DUKtY1MbjoYCPVf9VFuhmmf2Gh4
and rad clone rad:z3DUKtY1MbjoYCPVf9VFuhmmf2Gh4 fetches it from any node that
seeds it. Any of the three is the whole project.
Adding it to a project #
$ zig fetch --save git+https://git.jcollie.dev/jeff/z2dimg.git
const z2dimg_dep = b.dependency("z2dimg", .{ .target = target, .optimize = optimize });
exe.root_module.addImport("z2dimg", z2dimg_dep.module("z2dimg"));
z2d comes with it, pinned in build.zig.zon, and the surfaces this library
hands back are ordinary z2d surfaces — draw on them, composite them, hand them
to a Context.
Sans-I/O #
Nothing here opens, closes, reads or writes a file, and nothing here takes an
Io. A decoder is handed a *std.Io.Reader and an encoder a
*std.Io.Writer, and where those get their bytes is the calling program's
business: a file, a socket, a slice already in memory, a decompressor, a test
fixture.
That buys three things. The library is indifferent to which Io
implementation the program chose — threads, fibers, io_uring — because it never
performs I/O to need one. It is testable without a filesystem: every test in it
runs against Io.Reader.fixed over a byte slice, which is why they are fast
and why the fuzz loop gets through a few million inputs a minute per target. And the
decoders are pure, which is the part that matters most: a decoder here is a
function from bytes to pixels that makes no system call of any kind. That is
what makes the sandbox below possible, and cheap.
The one obligation it puts on a caller is that the reader's buffer must be at
least z2dimg.min_buffer_len bytes — eight — so that the format signature can
be examined without being consumed. A reader with a smaller one is an error
rather than a panic.
Limits #
A header is a handful of bytes an attacker wrote, and one of the numbers in it is how much memory to allocate. Being sans-I/O makes that worse rather than better: there is no file on disk whose size bounds the claim, only a stream that may be arbitrarily long or may be a pipe that never ends. So the bound comes from the calling program, which is the only party that knows what it is willing to spend.
var surface = try z2dimg.decode(gpa, reader, .{
.limits = .{ .max_width = 4096, .max_height = 4096, .max_pixels = 1 << 22 },
});
The defaults are sized for a program showing images to a person: nothing a
camera or a screenshot produces is refused, and a malicious file cannot ask for
a terabyte. max_pixels is the one that matters, because width and height can
each be modest while their product is not, and it is the product that gets
allocated. Something decoding avatars off the network should lower all three a
long way; Limits.unlimited exists for a batch converter with a machine to
itself.
probe is the cheap half of this: it reads the header, says how large the
image is and what it will decode to, and stops.
const info = try z2dimg.probe(reader, .{});
if (info.pixelCount() > budget) return error.TooBig;
It consumes the header, since a *Io.Reader cannot be rewound. To probe and
then decode the same stream, use a codec's two-step decoder — bmp.Decoder,
whose init reads the headers and whose decode goes on from there.
Premultiplied alpha #
Worth knowing about, because it is silent when it goes wrong.
Every image format stores straight alpha: a half-transparent red is
(255, 0, 0, 128), the colour at full strength alongside the coverage that
applies to it. z2d's compositor wants premultiplied alpha, where the same
pixel is (128, 0, 0, 128). Handing a straight-alpha value to z2d does not
fail; it composites wrongly, and the symptom is a halo of too-bright colour
around anything semi-transparent.
So the conversion happens exactly once, in z2dimg.pixels, and no codec in
this library writes to a surface buffer directly. pixels.Rgba8 is the
straight-alpha value codecs speak, and it is deliberately not one of z2d's
pixel types: keeping them distinct is what stops the two being mixed up by the
type system staying quiet. The multiplication itself is delegated to z2d, so
this library's rounding is z2d's rounding by construction.
One consequence is worth stating plainly: a decode-then-encode round trip is not byte-exact for an image with alpha. Premultiplying and demultiplying are truncating divisions, so a channel comes back within two of where it started, and at very low alpha the straight-alpha value it is reconstructed into can differ wildly — at an alpha of 2 a straight channel carries barely one bit of real information. Opaque images round-trip exactly.
Orientation #
A camera turned on its side records the picture the way the sensor saw it and writes down which way the camera was held. Ignore that and the photograph is displayed sideways, so this library reads it — and reads nothing else about EXIF, and writes none of it.
const info = try z2dimg.probe(&reader, .{});
if (info.orientation.swapsDimensions()) {
// What is on screen is `info.height` by `info.width`.
}
probe answers from the header alone. For a caller who has already decided to
decode, DecodeOptions takes somewhere to put the answer, because a sans-I/O
decoder is handed a stream it cannot rewind and asking twice would mean
buffering the whole image. EncodeOptions takes one to write, so that the tag
survives a conversion:
WebP is the exception to the first sentence. Its EXIF chunk goes after
the image data, so probe — which stops at the first image chunk, and is
cheap because it does — cannot reach it and reports .top_left for every
WebP. Only DecodeOptions.orientation gets the real answer there, and only
then does the decoder walk past the picture to look. Read is all: this library
writes the simple lossless WebP, which has nowhere to put an EXIF chunk.
var orientation: z2dimg.exif.Orientation = undefined;
var surface = try z2dimg.decode(gpa, &reader, .{ .orientation = &orientation });
try z2dimg.encode(gpa, &surface, writer, .{ .png = .{ .orientation = orientation } });
Writing is the same one tag and nothing else — twenty-six bytes, as a JPEG
APP1 segment or a PNG eXIf chunk. Every other tag a camera wrote is lost by
a decode here, and building a block that carried only orientation while
claiming to be the original's metadata would be worse than saying so. Null
writes no tag at all, which differs from .top_left only in whether the file
carries one; both say the same thing to a viewer.
The surface is always the image as stored, and writing the tag does not
rotate anything either: an encoder asked for .right_top writes .right_top
and makes no claim about the pixels beside it, so a caller who has already
turned the image the right way up wants .top_left or nothing. The orientation
is a correction to apply, not a description of what was done. Orientation.transform() gives that
correction as something to do rather than a tag to look up — a mirror and a
rotation, in that order — since every caller otherwise works the same table out
for itself. Nothing here rotates anything: which of the caller's own coordinate
systems the correction belongs in is not this library's business.
A file with no EXIF reports .top_left, the identity, which is deliberately
indistinguishable from a file that says .top_left itself. The question a
caller has is how to display the image and the answer is the same either way.
Where it comes from, and where it lives in this tree #
EXIF is a TIFF file with no image in it, carried inside some other file's
metadata. JPEG puts it in an APP1 segment behind the marker Exif\0\0; PNG
Third Edition puts the same block in an eXIf chunk. So src/exif.zig belongs
to neither codec: it is handed a block and knows nothing about markers or
chunks, which is also what would make it liftable into a library of its own if
it ever grew past reading one tag.
It reads the block in a single forward pass. A TIFF is a structure of offsets
and reading one usually means seeking about inside it, but a sans-I/O decoder
has neither a reader it may seek nor a reason to buffer a block that may be
megabytes of thumbnail. An offset that points backwards is not followed — a
real file's IFD0 follows its header immediately — and the cost is that a
deliberately shuffled block reports nothing rather than being chased around.
A malformed block is not an error. Every structural problem answers "no
orientation", never a failure. Metadata is decoration: a camera that wrote a
broken APP1 fifteen years ago still wrote a perfectly good photograph, and
refusing to decode it would serve nobody. Only the underlying stream failing
propagates.
tools/check_samples.py holds the writing to libjpeg and libpng the same way
it holds the colour profiles: all eight orientations into a baseline JPEG, a
progressive JPEG and a PNG, and Pillow reads all twenty-four back as written.
The fixtures in tests/exif_fixtures.zig are eighteen files Pillow wrote — all
eight orientations in both formats, and one of each with no EXIF at all — with
what Pillow reads back out of its own output recorded beside each, so the
expected value is libjpeg and libpng's answer rather than a restatement of this
library's. There is a fuzz target as well, since metadata is the part of a file
that no decoder validates and every decoder walks past.
Colour profiles #
An ICC profile says what the numbers in an image mean — which real colours those bytes stand for. This library does nothing with that. z2d has no colour management, so there is nothing here that could apply a profile, and pretending otherwise would be worse than saying so.
What it can do is not lose it. A program converting a JPEG to a PNG should hand back a file that still says what its colours mean; one that silently dropped the profile would turn a wide-gamut photograph into a washed-out one the first time it passed through. So the profile comes out as bytes and goes back in as bytes, unread:
var profile: std.ArrayList(u8) = .empty;
defer profile.deinit(gpa);
var surface = try z2dimg.decode(gpa, &reader, .{ .icc = &profile });
defer surface.deinit(gpa);
try z2dimg.encode(gpa, &surface, writer, .{ .png = .{ .icc = profile.items } });
The bytes are appended with the allocator the decode was given and the caller owns them. A file with no profile leaves the list empty, so a list that started empty and ended empty means there was nothing to carry.
Where a profile lives, and what it costs #
JPEG has no segment large enough. A profile is commonly a few kilobytes and can
be megabytes, and an APP2 segment holds at most 65533 bytes — so the ICC
specification's own Annex B defines how to split one across several, each
beginning ICC_PROFILE\0 and then a one-based piece number and a count. That
embedding belongs to ICC rather than to JPEG, which is why src/icc.zig
belongs to neither codec. PNG has iCCP, which is a name, a compression
method, and the profile deflated, in one chunk whatever the size. WebP has
ICCP, which is the simplest of the three: the profile as it is, in one
chunk, with nothing wrapped around it — and it is read only, since this
library writes the simple lossless form of WebP and that shape has no
VP8X to declare a profile beside.
WebP is read but not written, for the reason above: the simple lossless
file this library writes has nowhere to put a profile, and writing the
extended form to carry one would mean declaring a VP8X and everything that
implies about the rest of the file.
BMP is not covered. A BITMAPV5HEADER can carry one, but the header gives
an offset to the profile rather than the profile itself and writers put it
after the pixel data, so reaching it means knowing where the cursor is in a
stream that has already been read past — which a decoder that only ever seeks
forward cannot do. Asking a BMP for a profile leaves the list empty.
A profile is memory allocated on the strength of a length field, which is
exactly the shape of claim Limits exists to bound, so max_icc_bytes bounds
it. The default is what a JPEG can hold at all, 255 pieces of 65519 bytes,
since a larger profile could not have come out of one. A profile over the
budget is dropped and the image still decodes: a profile too large is a reason
to lose the profile, not the photograph. A caller who asks for no profile
allocates nothing for one.
A profile that is not one is dropped #
As with EXIF, a broken block is not a reason to refuse a good photograph. But
unlike EXIF this is passed on rather than read, so carrying a malformed
profile through would put a malformed profile in the output for other readers
to reject. Two checks decide, both from the profile's own header: the first
four bytes are its size and must be the size it actually is — which is what
catches a truncated profile and one reassembled from pieces that went missing —
and bytes 36 to 40 are the signature acsp. Anything else is dropped on the
way in and refused with error.Unsupported on the way out.
Pieces have to arrive in order. The specification numbers them and does not promise an order, and libjpeg sorts them — but it can, because it holds every marker in memory before looking at any of them. A decoder reading a stream once cannot leave a gap for a piece that has not come yet, and no encoder writes them out of order; one that did would have its profile dropped rather than reassembled wrongly.
tools/check_samples.py holds this to libjpeg and libpng: it writes a 3KB
profile and a 140KB one — the second split across three APP2 segments — into
a baseline JPEG, a progressive JPEG and a PNG, and Pillow reads all six back
byte for byte.
Sandboxing #
Image decoders are where memory-safety bugs live. They parse attacker-chosen
binary structures, do arithmetic on lengths that came out of those structures,
and are reached by every program that displays a picture from anywhere. Zig's
bounds and overflow checks catch a great deal of that in a safe build and none
of it in ReleaseFast, and neither build catches a logic error that reads the
wrong part of a buffer it is entitled to read.
So the decoder can be run somewhere it can do no harm even if it is wrong:
var image = try z2dimg.sandbox.decode(gpa, reader, .{});
defer image.deinit();
// image.surface is an ordinary z2d.Surface.
This follows glycin, GNOME's image
loading library, which runs each format's loader as a separate sandboxed
process and passes the pixels back through shared memory. The mechanism here is
much smaller — one fork, one seccomp filter, one memfd — because the
decoders it is protecting are already pure. glycin has to permit its loaders a
good deal, because they are ordinary programs that open files. A sans-I/O
decoder needs nothing permitted at all.
parent child
------ -----
read the input into memory
memfd_create + ftruncate
mmap MAP_SHARED ─────────────────▶ inherited across fork()
pipe2
fork() ──────────────────────────▶ prctl(PR_SET_NO_NEW_PRIVS)
seccomp(SET_MODE_FILTER)
── nothing further is permitted ──
decode, allocating from the mapping
write(pipe, reply)
exit_group(0)
waitpid ◀────────────────────────
read the reply, validate it
munmap the unused tail
wrap the pixels as a z2d.Surface
Under the default strict profile the filter permits four system calls:
write, exit_group, exit and rt_sigreturn. Not openat, not socket,
not execve, not mmap — the memory was reserved before the filter went on,
and the child allocates out of the shared mapping with a
FixedBufferAllocator, so the surface it decodes into is already in memory the
parent can see and there is nothing to copy back. The input is copied in before
the fork rather than streamed, because a child that could still read its input
would need a descriptor an attacker might redirect, and would introduce a
deadlock between two processes each writing to a pipe the other is not
draining.
Animations in the sandbox #
sandbox.decodeAnimation streams frames out of the forked process one at a
time, which is what keeps a thousand-frame animation inside a one-frame
budget: the child resets its allocator between frames, so what has to fit in
the shared mapping is the largest frame and the decoder's working memory
rather than the sum of every frame.
That costs the one property the still-image path leans on — that the child is dead before the parent looks at the pixels. Here it is alive between frames, waiting to be told it may write the next one over the last. Every shape check survives, so a malicious reply still cannot make the parent read outside the mapping; what is given up is that a frame's contents may change while the parent is looking at them, which is a torn picture and not a memory-safety failure. The module has always said that a subverted decoder's pixels are the attacker's anyway.
The child does not composite. It is run with compositing off and hands
back un-composited frames; the canvas is built in the parent, out of frames
whose shape has already been checked. Less runs inside the sandbox and less is
trusted from it — a child that lies about a frame can make the canvas wrong,
but it cannot make the compositing go wrong, because the compositing is not
its. The canvas size the child claims is checked against the caller's Limits
before the parent allocates anything on the strength of it.
A caller that stops reading half way leaves the child blocked for ever waiting
for an acknowledgement, so deinit kills it rather than waiting for it.
Closing the pipes would also do it, but only if the child co-operates, and
that is the one process here that might not.
There is a fifth call in one place, and it is confined. A decoder handing its
result back a frame at a time has to wait for the parent between frames, and
waiting means read — so the streaming profile permits it, and permits it
on one descriptor only. That is possible because a descriptor is an
integer rather than a pointer, which is the one kind of argument a seccomp
filter can compare; the child moves the pipe onto a fixed number with dup2
before the filter goes on, so that the number the filter tests can be a
constant. A read on any other descriptor kills the process exactly as
openat would, which src/sandbox.zig asserts directly by running two
children that differ only in the integer they name.
What the child is stripped of before the filter goes on. A forked child
keeps everything the parent had, because CLOEXEC means nothing to a process
that never execs — so four things are taken away first, all of them free in
syscall surface because all of them happen before there is a filter to stop
them.
Its inherited descriptors are closed. This is the one that was a real
hole: a decoder cannot open a socket under any profile here, but write is
a call it has, and a subverted one could put attacker-controlled bytes into a
connection the parent already had. The pipes are moved to fixed numbers,
everything above them is closed with close_range, and the strict profiles
then permit write on the reply descriptor and no other. The two halves make
each other worth having: closing takes away what could be written to, and the
filter takes away the ability to name anything else.
Processor time, through RLIMIT_CPU — a decoder stuck in a loop is killed
by the kernel, so the parent needs no clock of its own, and time spent waiting
on a pipe does not count towards it. Core dumps, through RLIMIT_CORE, so
a crash cannot write the shared mapping out to disk. And dumpability,
through PR_SET_DUMPABLE, which stops another process of the same user
attaching with ptrace to read that mapping.
What it protects against: a decoder subverted into doing something other
than decoding. Reading a file, opening a socket, running a program, attaching
to another process — each dies at the attempt, as error.SandboxViolation. And
a decoder that crashes: a segmentation fault in the child is
error.DecoderCrashed in the parent, not a dead program.
What it does not do is make the pixels trustworthy. A subverted decoder can still write what it likes into the shared mapping, because writing there is its job. What the parent validates is the shape of the reply — that the buffer is inside the mapping, correctly aligned, and exactly the length the stated dimensions require — so a malicious reply cannot make the parent read out of bounds. The contents of a valid-looking buffer are the attacker's if the decoder was theirs.
It costs a fork and a waitpid per image, plus the page faults for the
pixels: tens of microseconds against a decode measured in milliseconds for
anything but a tiny image. It runs on 64-bit Linux and 64-bit FreeBSD, and
elsewhere sandbox.decode returns error.SandboxUnavailable rather than
quietly decoding unsandboxed — a security feature that turns itself off is
worse than one that was never there.
Out-parameters come back too. DecodeOptions.orientation and
DecodeOptions.icc point into the caller's memory, which the child only has a
copy-on-write copy of, so nothing it writes there would ever arrive. The
orientation travels in the reply instead, and the child collects the profile
into the shared mapping, where the parent checks its place like it checks the
pixels' and copies it into the caller's list with the caller's allocator.
On FreeBSD #
The same design, with Capsicum
in place of seccomp. Capsicum is not a system call filter. It takes away
every global namespace at once when a process calls cap_enter, so that no
path can be opened, no address reached and no other process signalled, and
it limits each descriptor the process still holds to the rights it was given.
The child arrives at cap_enter holding exactly this:
| descriptor | rights |
|---|---|
| the reply pipe | CAP_WRITE |
| the acknowledgement pipe, when streaming | CAP_READ |
standard input, output and error, under strict |
none |
— everything else having been closed with closefrom, exactly as on Linux.
Capsicum's own answer to a forbidden call is an error, which would leave a
subverted decoder looking like one that failed quietly. PROC_TRAPCAP_CTL
turns that error into a SIGTRAP, so a refused call ends the child and the
parent reports error.SandboxViolation, the same as for SIGSYS on Linux.
PROC_TRACE_CTL stands in for PR_SET_DUMPABLE, though a process may turn
its own tracing back on, which the seccomp filter leaves no way to do. That
would help only another process of the same user that is already waiting to
attach, and such a process could attach to the parent instead. The rlimits
are the same ones.
The profiles map onto two behaviours. strict and streaming strip the
standard streams and make refusal fatal, so a panic dies trying to print
itself, as it does under the strict filter. permissive leaves the streams
alone and does not trap, so a panic prints its message, fails quietly to open
the debug information for a trace, and aborts as error.DecoderCrashed.
What it does not refuse that seccomp does. Capsicum permits fork, which
names nothing global; the new process is in capability mode too, so it is
contained, but it is a way to spend resources. The child sets RLIMIT_NPROC
to zero, which refuses fork to any user but root. A program decoding as
root has only capability mode between a subverted decoder and a fork bomb.
Capsicum also permits the long tail of calls that touch only the process
itself, such as getpid, mmap of anonymous memory and sigaction. None of
them reaches anything outside.
Deciding not to isolate #
Some programs should not use a child process. macOS and Windows have no sandbox this library can use: macOS's is deprecated, and Windows' needs a second executable to launch, which a library has no business shipping. And a program may already be inside a sandbox. A renderer running in a locked-down child of its own, such as zig-svg's, that meets a PNG embedded in the document it is drawing gains nothing from forking again, and the filter it is under would refuse the fork anyway.
var image = try z2dimg.sandbox.decode(gpa, reader, .{ .isolation = .none });
defer image.deinit();
Isolation.none runs the same code in this process, behind the same Image
and AnimationStream, with the same limits and the same errors. The one
exception is LimitsUnbounded, which is about reserving a mapping, and there
is no mapping without a child. So a program can make the choice in one place
and keep one code path after it. Isolation.best is .process where the
sandbox exists and .none where it does not. It is not the default: it
decodes unsandboxed on some platforms, and a caller who accepts that should
have to write it down.
The plain z2dimg.decode and z2dimg.encode are unsandboxed as well, and
remain the way in for a caller who never wanted a sandbox. sandbox.decode
with .none is for a program that wants one where it can have one and needs
to say so where it cannot. Encoding is never sandboxed. The encoder's input
is a surface the program built itself, not bytes from somewhere else.
Testing #
$ zig build test # unit tests, round trips, and the fuzz corpus
$ zig build check # compile the tools nothing else builds
$ zig build fuzz-run # the fuzz loop, a minute a target
$ cd corpus && zig build run # the wuffs image corpus, fetched on demand
$ nix build .#checks.x86_64-linux.freebsd -L # build and test on FreeBSD, in a VM
Every BMP fixture is assembled in the test rather than read from a file. A
checked-in .bmp is a wall of hex that says nothing about which of its fields
is under test, where infoHeader(.{ .bpp = 16, .compression = bitfields })
says exactly that.
The PNG and JPEG fixtures work the other way round, and are the stronger test. Twenty-six files are generated by tools/mkpng.py, a small Python encoder
with explicit control over every choice the format offers, and each is opened
with Pillow and compared against its expected pixels before being written
into tests/png_fixtures.zig. A fixture Pillow disagrees with never reaches
the repository. That matters because a round-trip test only proves an encoder
and a decoder agree with each other, which they will even if both are wrong the
same way; these prove the decoder agrees with an implementation that has never
seen this code. The encoder was checked in the same direction, by hand — every
surface format it can write, read back by Pillow.
The JPEG encoder was checked the same way: every option it offers, written out
and read back by Pillow, which agreed with this library's own decoding of the
same bytes to within 2 counts — and reported the alpha-only case as mode L,
which is the part that would have been easy to get subtly wrong.
The fifteen JPEG fixtures are the same idea inverted: Pillow encodes each one with the options its note names — baseline and progressive, 4:4:4, 4:2:2 and 4:2:0, greyscale, restart markers, optimised Huffman tables, dimensions that do not divide by the MCU size — and then decodes its own output, and those pixels are what the test expects. The comparison has a tolerance because it must: JPEG defines IDCT accuracy requirements rather than an exact transform, so two conforming decoders are entitled to differ. Measured across all fifteen, the worst single channel is 3 and the worst mean over an image is 0.14, and the bounds are set just above that — tight enough that anything actually wrong moves them by tens.
The animation tests in tests/anim.zig are assembled rather than checked in:
each GIF is built from named pieces, so a test says which field it is about
instead of holding a wall of hex. The LZW payloads are the one part that
cannot be written by hand, and they were generated by a small encoder and
cross-checked against wuffs' own artificial-gif files, whose one-pixel
payload is byte for byte the one here.
The later formats are fixtured the same way, each against whichever
implementation is the reference for it: ImageMagick for XBM, XPM, GIF and TGA,
and netpbm's own tools for PBM, PGM, PPM and PAM, through
tools/gen_netpbm_fixtures.py. The rule is the same every time — the expected
pixels are read out of the other implementation's output, never out of this
one's — and it has paid for itself at least once already. The GIF decoder
round-tripped its own output perfectly while disagreeing with every other
implementation in the world about when the LZW code width grows, and nothing
but a real file from another encoder was ever going to say so.
The fuzz targets in tests/fuzz.zig assert properties rather than examples:
that a decode terminates, allocates within its limits and leaks nothing; that
anything it accepts survives being written out and read again; and that probe
and decode never disagree about how large an image is, since a caller is
invited to trust the cheap answer before paying for the expensive one. The
sandbox's tests fork a child, lock it down, and check that an ordinary
forbidden call kills it and an ordinary permitted write does not: the claim
the whole sandbox rests on, made directly. The forbidden call is getpid
under seccomp and opening /dev/null under Capsicum, which allows getpid.
Those tests run on Linux under zig build test, and the FreeBSD half runs on
FreeBSD itself:
$ nix build .#checks.x86_64-linux.freebsd -L
That boots a stock FreeBSD 14.5 cloud image under KVM, with no network, and
builds and tests the library there with ziglang.org's own FreeBSD build of the
same Zig, as an unprivileged user. It is zig build test run natively rather
than test executables cross-compiled from Linux, so it also catches a
build.zig or an @import that works only on the machine it was written on.
Everything the guest needs arrives on the cloud-init seed disc: a script as the
user-data, the Zig tarball, this source, and the Zig package cache for
--system. The verdict comes back on the serial console, and the check passes
only on a line the guest prints after Zig itself has succeeded, so a guest that
hangs, runs out of memory or never runs the script fails it.
nix/freebsd/default.nix has the detail. The tests pass there apart from the
claims that belong to seccomp alone, which skip.
Having no network is what lets it be an ordinary derivation in the Nix sandbox;
it needs only the kvm system feature, which Nix advertises wherever
/dev/kvm exists. It is part of nix flake check on x86_64-linux, and the
Forgejo workflow runs it on a runner that can boot a guest.
The unsandboxed path was checked by hand for -Dtarget=x86_64-windows, under
64-bit wine.
zig build fuzz --fuzz is what those targets were written for, and on Zig
0.17 it runs with coverage feedback, because the test binary is compiled with
LLVM; the self-hosted backend Debug otherwise uses emits no coverage
instrumentation. zig build fuzz --fuzz -Dfuzz-filter=png narrows it to one
target. zig build fuzz-run is a second loop over the same targets with no
coverage feedback but a corpus of real files to mutate, and a mode that fails
allocations on purpose. For an image format the corpus is doing most of the
work anyway: a BMP is two bytes of signature, a fourteen-byte file header and a
length-tagged DIB header, and random bytes get past none of that.
The wuffs corpus #
corpus/ is a second project, with its own build.zig, that checks these
decoders against Google wuffs' test images.
$ cd corpus
$ zig build run # fetches wuffs the first time, then checks it
$ zig build run -- -v # and says what every case is for
None of it is checked in. wuffs is a sixteen megabyte dependency pinned by
commit hash and marked lazy, so nothing is downloaded until that run step
is actually asked for, and nothing that merely builds this library has to know
the corpus exists. That is also why it is a separate package rather than
another test module: keeping it out of the library's own manifest keeps it out
of everything generated from that manifest. The library comes to it by path,
from the checkout it sits inside, so the two are always the same code.
It is a different kind of test from everything in tests/. Those fixtures are
generated — a script writes an image, another implementation reads it back,
and what that implementation reports becomes the expectation — which proves
this library agrees with Pillow, ImageMagick and netpbm about files those
tools wrote. It cannot prove anything about a file none of them would ever
write, and those are the files that break decoders. Half of wuffs' corpus is
exactly that: hand-built corner cases, each with a paragraph of commentary
saying which ambiguity in the format it pins down.
Four kinds of claim are made, in increasing order of what they are worth:
- against NIE. wuffs ships
hippopotamus.nie, its own uncompressed format — a sixteen byte header and then raw BGRA — holding the exact pixels of a 36×28 image that is also present as a BMP, two PNGs and a PPM. Pillow confirms all four hold precisely those pixels, so anything but an exact match is this library's fault. - agreement between encodings. Several lossless encodings of one image
must decode to identical pixels. This needs no external truth at all,
which is the point:
bricks-noditheras a BMP, a PNG, a TGA and a GIF runs four separate decoders here over one picture, and any one of them being wrong shows up as a disagreement. It is the cheapest strong test in the project, and it is what finally gave TGA and GIF an exact check rather than a tolerance. - agreement on the alpha alone. This exists for one file and earns its
place: a lossy WebP's colour is lossy and its transparency is not, because
VP8 is opaque and the alpha travels beside the frame as a lossless image.
So
hippopotamus.masked-with-muybridge.lossy.webpis held against the PNG of the same picture on the alpha channel — 1008 pixels, many of them partly transparent, every one exact — in a file where nothing else can be checked at all. - accepted or refused. For the corner cases, where the claim is only that a file is decoded or rejected rather than crashing or hanging.
Nothing compares a lossy encoding against ground truth. A JPEG of the
hippopotamus differs from the NIE by up to 29 counts a channel and a GIF of it
by up to 21, and neither number says anything about this decoder: both are the
encoder's loss, and quantising to 256 colours and then reproducing that
palette exactly is a correct GIF decode that differs from the original. A
tolerance wide enough to admit that is wide enough to admit a real bug. The
lossy WebPs are here on the same terms: what holds that decoder to the bit is
dwebp, in zig-vp8's own tests, where the comparison is against another
decoder reading the same file rather than against the picture encoded.
It found three, immediately. A JPEG decoder that multiplied max_pixels by
four and so panicked on every JPEG in existence when handed
Limits.unlimited; a GIF frame of zero area refused as malformed when it
should draw nothing; and a GIF refused over an invalid LZW code that sat after
a frame the decoder had already filled. The first is the worst of the three —
a crash, in a library whose whole argument is that decoders are where
memory-safety bugs live — and no amount of fuzzing was going to find it,
because the fuzzer always passes bounded limits.
The ways decoders get broken #
tests/hardening.zig is a test per class of vulnerability that has actually
been found in a real image decoder, organised by attack rather than by format
— because the same mistake turns up in each format's decoder wearing different
clothes, and a suite arranged by format hides that.
| what it pins | where it has gone wrong |
|---|---|
| a truncated file's output does not depend on what was in memory | CVE-2008-0420, a BMP decoder leaking the process's memory into the image; CVE-2013-6629, libjpeg emitting uninitialised bytes |
| a run-length run longer than its row is clipped, not written | the libnsbmp heap overflow; CVE-2013-3663 |
| a run-length delta jumping past the image saturates | the same class, the other escape |
| run-length data that never ends still terminates | decoders that looped on it |
| run-length encoding at a depth it cannot describe is refused | what Ladybird added after incompatible pairs reached its pixel decoders |
| a palette index past the end of the palette is a colour, not a read | the libpng png_do_quantize over-read |
tRNS describing more entries than the palette has |
several libpng bugs indexing one chunk by another's length |
| image data that decompresses to less than a row | CVE-2014-0333, an IDAT loop that never ended |
| a colour profile chunk claiming more than it holds | the png_handle_iCCP failures |
| dimensions whose product overflows | CVE-2018-20330, a miscomputed buffer size |
| a scan naming a Huffman table never defined | the libjpeg null-pointer crashes |
| twelve-bit samples | CVE-2023-2804, reachable only at that precision |
Most of these cannot go wrong here the way they went wrong in C. A slice index is bounds-checked, so what was disclosure is a panic — but a panic in a decoder is a crash in whatever opened the file, so the standard these tests hold to is that a malformed file is refused, not that it fails safely.
Every one of them passed the first time they were run, which is the expected
outcome and also a reason to distrust them: a test that has never failed may be
testing nothing. So the clamp that keeps a run-length run inside its row was
deliberately removed to check — the test panics with index out of bounds: index 4, len 4, which is precisely the heap overflow, caught by the bounds
check and by the test.
The fuzz targets cover the same ground continuously and far more widely; these exist because a fuzzer finds what it finds, and a named case that is checked on every build says which specific mistakes were considered.
Building #
The Zig dependency is fetched by Zig; everything else comes from Nix.
$ nix develop
$ zig build test
nix build builds the package the other way, with zon2nix turning
build.zig.zon into a Nix expression so that the build itself needs no
network. Adding, removing or updating a dependency is the whole of
regenerating that file:
$ nix develop -c zon2nix --17 --nix=build.zig.zon.nix build.zig.zon
Licence #
MIT, and the project follows REUSE: reuse lint
passes, every file carries its own SPDX-FileCopyrightText and
SPDX-License-Identifier, and the ones that cannot are covered by
REUSE.toml. z2d itself is MPL-2.0 and is a dependency rather than a
derivative.
References cited #
- Microsoft Corporation. [MS-WMF]: Windows Metafile Format. https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-wmf/4813e7fd-52d0-4f42-965f-228c8b7488d2
- Microsoft Corporation. Bitmap Storage. Win32 API documentation, Microsoft Learn. https://learn.microsoft.com/en-us/windows/win32/gdi/bitmap-storage
- Microsoft Corporation. BITMAPV5HEADER structure (wingdi.h). Win32 API documentation, Microsoft Learn. https://learn.microsoft.com/en-us/windows/win32/api/wingdi/ns-wingdi-bitmapv5header
- BMP file format. Wikipedia. https://en.wikipedia.org/wiki/BMP_file_format
- World Wide Web Consortium (W3C). Portable Network Graphics (PNG) Specification (Third Edition) (W3C Recommendation). https://www.w3.org/TR/png-3/
- Deutsch, L. P., & Gailly, J.-L. (1996, May). ZLIB Compressed Data Format Specification version 3.3 (RFC 1950). Internet Engineering Task Force. https://www.rfc-editor.org/info/rfc1950
- Deutsch, L. P. (1996, May). DEFLATE Compressed Data Format Specification version 1.3 (RFC 1951). Internet Engineering Task Force. https://www.rfc-editor.org/info/rfc1951
- Boutell, T. (1997, March). PNG (Portable Network Graphics) Specification Version 1.0 (RFC 2083). Internet Engineering Task Force. https://www.rfc-editor.org/info/rfc2083
- Seccomp BPF (SEcure COMPuting with filters). The Linux Kernel documentation. https://www.kernel.org/doc/html/latest/userspace-api/seccomp_filter.html
- Kerrisk, M. seccomp(2). Linux man-pages. https://man7.org/linux/man-pages/man2/seccomp.2.html
- Kerrisk, M. memfd_create(2). Linux man-pages. https://man7.org/linux/man-pages/man2/memfd_create.2.html
- Kerrisk, M. prctl(2). Linux man-pages. https://man7.org/linux/man-pages/man2/prctl.2.html
- Watson, R. N. M., Anderson, J., Laurie, B., & Kennaway, K. (2010, August). Capsicum: Practical Capabilities for UNIX. In Proceedings of the 19th USENIX Security Symposium (pp. 29–46). USENIX Association. https://www.usenix.org/legacy/event/sec10/tech/full_papers/Watson.pdf
- The FreeBSD Project. capsicum(4). FreeBSD Manual Pages. https://man.freebsd.org/cgi/man.cgi?query=capsicum&sektion=4
- The FreeBSD Project. cap_enter(2). FreeBSD Manual Pages. https://man.freebsd.org/cgi/man.cgi?query=cap_enter&sektion=2
- The FreeBSD Project. cap_rights_limit(2). FreeBSD Manual Pages. https://man.freebsd.org/cgi/man.cgi?query=cap_rights_limit&sektion=2
- The FreeBSD Project. procctl(2). FreeBSD Manual Pages. https://man.freebsd.org/cgi/man.cgi?query=procctl&sektion=2
- The FreeBSD Project. closefrom(2). FreeBSD Manual Pages. https://man.freebsd.org/cgi/man.cgi?query=closefrom&sektion=2
- The FreeBSD Project. nuageinit(7). FreeBSD Manual Pages, 2026. https://man.freebsd.org/cgi/man.cgi?query=nuageinit&sektion=7
- McCanne, S., & Jacobson, V. (1993, January). The BSD Packet Filter: A New Architecture for User-level Packet Capture. In Proceedings of the USENIX Winter 1993 Conference (pp. 259–269). USENIX Association. https://www.tcpdump.org/papers/bpf-usenix93.pdf
- Herold, S. glycin. GNOME. https://gitlab.gnome.org/GNOME/glycin
- International Telecommunication Union. (1992, September). Information technology — Digital compression and coding of continuous-tone still images — Requirements and guidelines (ITU-T Rec. T.81 | ISO/IEC 10918-1). https://www.w3.org/Graphics/JPEG/itu-t81.pdf
- International Telecommunication Union. (1994, November). Information technology — Digital compression and coding of continuous-tone still images: Compliance testing (ITU-T Rec. T.83 | ISO/IEC 10918-2). https://www.itu.int/rec/T-REC-T.83
- International Telecommunication Union. (2011, May). Information technology — Digital compression and coding of continuous-tone still images: JPEG File Interchange Format (JFIF) (ITU-T Rec. T.871 | ISO/IEC 10918-5). https://www.itu.int/rec/T-REC-T.871
- International Color Consortium. (2010, December). Specification ICC.1:2010 (Profile version 4.3.0.0): Image technology colour management — Architecture, profile format, and data structure. https://www.color.org/specification/ICC1v43_2010-12.pdf
- Camera & Imaging Products Association. (2023, May). Exchangeable image file format for digital still cameras: Exif Version 3.0 (CIPA DC-008-Translation- 2023 | JEITA CP-3451F). https://www.cipa.jp/std/documents/download_e.html?DC-008-Translation-2023-E
- Adobe Developers Association. (1992, June). TIFF Revision 6.0. https://web.archive.org/web/20230315131931/https://www.adobe.io/content/dam/udp/en/open/standards/tiff/TIFF6.pdf
- Arnaud Le Hors. (1996, May). XPM Manual: The X PixMap Format (Version 3.4i). https://www.x.org/docs/XPM/xpm.pdf
- X.Org Foundation. rgb.txt, the X colour name database. https://gitlab.freedesktop.org/xorg/app/rgb/-/raw/master/rgb.txt
- CompuServe Incorporated. (1987, June). GIF: Graphics Interchange Format — A standard defining a mechanism for the storage and transmission of raster-based graphics information (Version 87a). https://www.w3.org/Graphics/GIF/spec-gif87.txt
- CompuServe Incorporated. (1990, July). Graphics Interchange Format (Version 89a). https://www.w3.org/Graphics/GIF/spec-gif89a.txt
- Welch, T. A. (1984, June). A Technique for High-Performance Data Compression. Computer, 17(6), 8–19. https://doi.org/10.1109/MC.1984.1659158
- Truevision, Inc. (1991, January). Truevision TGA File Format Specification (Version 2.0). https://web.archive.org/web/20230326043748/http://www.dca.fee.unicamp.br/~martino/disciplinas/ea978/tgaffs.pdf
- ImageMagick Studio LLC. ImageMagick. https://imagemagick.org/
- Tao, N., et al. Wuffs: Wrangling Untrusted File Formats Safely
(commit
f31d952). Google. https://github.com/google/wuffs - Tao, N. (2021, November). Naïve Image Formats: NIE, NII, NIA. Wuffs. https://github.com/google/wuffs/blob/main/doc/spec/nie-spec.md
- Poskanzer, J., et al. pbm — Netpbm bi-level image format. Netpbm. https://netpbm.sourceforge.net/doc/pbm.html
- Poskanzer, J., et al. pgm — Netpbm grayscale image format. Netpbm. https://netpbm.sourceforge.net/doc/pgm.html
- Poskanzer, J., et al. ppm — Netpbm color image format. Netpbm. https://netpbm.sourceforge.net/doc/ppm.html
- Poskanzer, J., et al. pam — Netpbm arbitrary image format. Netpbm. https://netpbm.sourceforge.net/doc/pam.html
- Poskanzer, J., et al. Netpbm (Version 11.15.3). https://netpbm.sourceforge.net/
- ZSoft Corporation. (1991, July). ZSoft PCX File Format Technical Reference Manual (Revision 5). https://www.fileformat.info/format/pcx/spec/a10e75307b3a4cc49c3bbe6db4c41fa2/view.htm
- Hornick, J. (1995, September 29). Icons. Microsoft Developer Network, Microsoft Corporation. https://learn.microsoft.com/en-us/previous-versions/ms997538(v=msdn.10)
- Google. WebP Container Specification. Google Developers. https://developers.google.com/speed/webp/docs/riff_container
- Google. WebP Lossless Bitstream Specification. Google Developers. https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification
- Google. libwebp. https://chromium.googlesource.com/webm/libwebp
- Ollie, J. C. zig-riff. https://git.jcollie.dev/jeff/zig-riff
- Ollie, J. C. zig-vp8. https://git.jcollie.dev/jeff/zig-vp8
- libjpeg-turbo. https://libjpeg-turbo.org/
- Clark, J. A., et al. Pillow. https://python-pillow.github.io/
- Marchesi, C. z2d (Version 0.12.2-pre, commit
6c4f0ca). https://github.com/vancluever/z2d
The first three are the format. [MS-WMF] is the only freely published document
that defines BitmapFileHeader, BitmapInfoHeader, BitmapV4Header and the
Compression enumeration normatively rather than describing them, and is
what the header parsing implements; the GDI pages supply the row-padding rule,
the meaning of a negative height, and the LCS_sRGB constant this library
stamps into the V4 headers it writes.
Wikipedia is fourth because it is the most complete public account of the BMP
family as it exists rather than as Microsoft documents it — the table of header
lengths that identify each version, the OS/2 variants at 16 and 64 bytes, and
the fact that OS/2 gave compression values 3 and 4 to a Huffman encoding and a
24-bit run-length encoding where Windows has BI_BITFIELDS and BI_JPEG.
Refusing those two rather than guessing at them is the whole of what reading it
changed.
The W3C specification is PNG as it now stands, and is what the codec here
implements: the chunk layout, the five colour types and the depths each allows,
the five filters and the exact tie-breaking of the Paeth predictor, the Adam7
tables, and the rule that the case of a chunk type's first letter says whether
an unrecognised chunk may be skipped. RFC 2083 is the same format as it was
first published and is kept because a good deal of writing about PNG still
cites it. The two compression RFCs are the layer underneath: 1951 is the
deflate bitstream, 1950 the zlib wrapper around it with the Adler-32 that a
truncated IDAT run fails — std.compress.flate implements both, and this
library only has to know which container to ask for.
The next four are the sandbox. The kernel's own document is the one that says a
filter cannot dereference a pointer argument — which is why this is built
around a decoder that needs no files rather than a filter that polices which
files it opens — and why PR_SET_NO_NEW_PRIVS has to come first. seccomp(2)
supplies the detail that x86-64's x32 ABI shares an architecture token with
ordinary x86-64 and sets bit 30 of every call number, which is why the filter
refuses that range explicitly rather than by accident. McCanne and Jacobson
define the machine a seccomp filter is a program for, down to the rule that a
jump is counted from the instruction after it, which is the arithmetic in
src/sandbox/seccomp.zig and what its tests check.
T.81 is JPEG, and is the authority for the marker structure, the zig-zag order, canonical Huffman coding, progressive mode's spectral selection and successive approximation — Annex G, and Figure G.7 in particular, which is the refinement scan that interleaves correction bits with runs of zeroes — restart intervals, and Annex K, which supplies both the example tables that almost every encoder uses unchanged and, in K.2, the procedure for building a table from an image's own statistics. T.83 is why the JPEG tests compare with a tolerance at all: it specifies accuracy requirements for the inverse DCT rather than an exact transform, deliberately, so that the fast factorisations would stay conforming. T.871 is what T.81 leaves out — JPEG codes components and says nothing about what they mean, and JFIF is the convention that three of them are YCbCr, with the coefficients this decoder converts by.
Four things in the JPEG codec come from reading libjpeg rather than any
specification: that Adobe's APP14 marker is the only thing that says how four
components are to be read, and that Adobe writes CMYK inverted; that the
default chroma upsampling is a triangle filter; the buffering a refinement
scan's correction bits need, which T.81 describes as a data flow and libjpeg
solves as a program; and the ten-scan script this encoder writes progressive
files with, which is jpeg_simple_progression and is what the format settled
on rather than anything the specification prescribes. Pillow is the referee for every
fixture in the test suite, in both directions.
The ICC specification is cited for two things, neither of which is colour: the
sixteen bytes of profile header this library checks before carrying one — the
size field and the acsp signature — and Annex B, which defines how a profile
too large for one JPEG segment is split across several. Everything else in it
describes transforms this library has no opinion about.
Exif and TIFF 6.0 are the two halves of the metadata this library reads. TIFF
is the container — the byte order mark, the magic 42, an image file directory
of twelve-byte entries each naming a tag, a type, a count and either a value or
where to find it — and Exif is what the tags mean, of which this reads exactly
one: Orientation, tag 0x0112, which is a SHORT and therefore sits inside
its own entry rather than at an offset, which is the whole reason a
forward-only pass can read it. The W3C PNG specification above is the third
piece, since it is what defines the eXIf chunk that carries the same block in
a PNG and says it holds the block without the Exif\0\0 marker a JPEG puts in
front of it.
The XPM manual is the format, and the only place several of its awkward
details are written down: that a colour string may carry a value for each of
five display kinds, that a value may contain spaces and is ended only by the
next key, and that the characters spelling a pixel include the leading spaces
a parser would otherwise skip. rgb.txt is the colour names it refers to,
taken from X.Org rather than from a web palette — the two agree on most names
and disagree on gray, which is #BEBEBE to X and #808080 to CSS.
The two GIF specifications are the format, and 89a is what this library writes: 87a is cited alongside it because both signatures are read and the difference between them is exactly the blocks 89a added — the graphic control extension this library reads a transparent index out of, and the application and comment extensions it skips. Neither document states the one rule that matters most in practice, which is when the LZW code width grows; Welch's paper is where the algorithm is described, and The one thing about GIF's LZW says what the two sides of it disagree about.
The Truevision specification is TGA, and is cited for the parts a file cannot tell you itself: that there is no signature, what the eighteen header bytes mean, which of the image types are defined, and that the attribute bits field in the image descriptor says how many of the alpha byte's bits are real — which is the field almost no writer fills in, and the reason this library has to guess.
ImageMagick is the reference the XBM, XPM, GIF and TGA fixtures are checked against, in both directions.
wuffs is cited twice over. Its test corpus is what corpus/ checks these
decoders against, and the commentary beside each of its hand-built files —
which decoding policies exist for a GIF frame that falls outside its screen,
and which real decoder picked each one — is documentation of the formats that
exists nowhere else. The NIE specification is the second: a sixteen byte
header and raw BGRA, which is the whole format, and which is why wuffs can
ship exact pixels beside an image without shipping a decoder to read them
with.
The four Netpbm format pages are the specification, such as it is: there is no
standards body behind these and the man pages are the normative text. They are
cited for the three things that are not guessable — that a maxval above 255
means two bytes a sample in most significant byte first order, that exactly one
whitespace character separates a raw header from its samples, and that in PBM
alone a set bit means black. The PAM page is cited separately for the rule this
library follows about DEPTH and TUPLTYPE: the depth is normative and the
tuple type is a name for it, which is why a TUPLTYPE this library has never
heard of is read anyway.
Netpbm itself, the implementation, is the reference the test fixtures are generated from, for the reason the Netpbm section gives.
The PCX technical reference is the format, and is cited for the two things a
file cannot tell you itself: that bits_per_pixel counts bits per plane,
so that the depth is its product with the plane count and the seven
combinations are seven different memory layouts; and that the 256-colour
palette lives after the image data behind a 0x0C marker, because the
128-byte header was fixed before anyone needed one. It is also where the
version numbers are enumerated, including the version 3 that means "no
palette" and so means the default EGA colours.
The icon documentation is cited for the two things that make an ICO more than
a directory of bitmaps: that an entry's DIB declares twice the height it has,
the second half being the AND mask, and that the entry carries no
BITMAPFILEHEADER because the directory already holds what it would have
said. It does not document the convention that a 32-bit entry's top byte is
alpha, which is the one thing about the format that most needs documenting and
is known only from what every icon and every reader actually does.
The two WebP specifications are cited for opposite reasons. The lossless one
is complete and is what the decoder was written from, down to the
hundred-and-twenty-entry distance table, which is taken from it verbatim
rather than transcribed because the order is not derivable and one wrong entry
would corrupt only the files that happened to use that code. The container one
is cited with libwebp because it is not sufficient on its own: its prose
numbers the VP8X flag bits in the opposite order from the values every
implementation uses, so the constants come from the source and the
specification supplies everything else. The container document is also where
the ALPH chunk is defined — the filtering rules, the header byte, and the
fact that the compressed form is a headerless lossless image with the values
in its green channel.
The lossy bitstream is not cited here because it is not read here: RFC 6386 is zig-vp8's reference and is cited in that project, which is the whole point of it being a separate project.
glycin is the design the sandbox follows, and reading it is the quickest way to
see what the sans-I/O core buys: the same idea, with a great deal less that has
to be permitted. z2d is the library on the other side of the bridge, and its
premultiplied pixel formats are the reason src/pixels.zig exists at all.