From be94de15e77fb8e14fb568b2de3aa259763fe9c4 Mon Sep 17 00:00:00 2001 From: "Jeffrey C. Ollie" Date: Fri, 18 Sep 2026 00:29:55 -0500 Subject: [PATCH] ICC: carry a colour profile from one file to another A profile says what the numbers in an image mean. This library does nothing with that --- z2d has no colour management, so there is nothing here that could apply one --- but it can stop losing it. A program converting a JPEG to a PNG should hand back a file that still says what its colours mean, and 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. `DecodeOptions.icc` is a list to append to, `EncodeOptions.icc` is bytes to carry, and `Limits.max_icc_bytes` bounds what a length field can ask for. 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. `src/icc.zig` belongs to neither codec because the thing it knows does not. JPEG has no segment large enough --- a profile can be megabytes and an `APP2` holds 65533 bytes --- so the ICC specification's own Annex B defines how to split one across several, which makes the splitting ICC's business and not JPEG's. PNG has `iCCP`, one chunk of deflated profile whatever the size. BMP is not covered, and the reason is structural rather than an omission: a `BITMAPV5HEADER` gives an *offset* to the profile rather than the profile, and writers put it after the pixel data, so reaching it means knowing where the cursor is in a stream already read past. This decoder only ever seeks forward. A profile that is not one is dropped on the way in and refused on the way out. Unlike EXIF this is passed *on* rather than read, so carrying a malformed profile through would put a malformed profile in somebody else's file. Two checks decide, both from the profile's own header: its size field must be the size it actually is, which catches a truncated profile and one reassembled from pieces that went missing, and bytes 36 to 40 must be `acsp`. Pieces have to arrive in order. libjpeg sorts them, and can, because it holds every marker in memory before looking at any; a decoder reading a stream once cannot leave a gap for a piece that has not come. No encoder writes them out of order, and one that did would have its profile dropped rather than reassembled wrongly. libjpeg and libpng agree. `tools/check_samples.py` now 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. There is a fuzz target for the reassembler, whose properties are the three that matter for something an attacker writes: it terminates, it never exceeds the budget however the pieces are numbered, and anything it hands back is a profile. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_01MdXttGjXJxdbBPZQQNyR6h --- README.md | 88 +++++++++- build.zig | 13 ++ src/bmp.zig | 8 +- src/common.zig | 27 ++++ src/icc.zig | 353 +++++++++++++++++++++++++++++++++++++++++ src/jpeg.zig | 86 ++++++++++ src/png.zig | 132 ++++++++++++++- src/root.zig | 3 + tests/fuzz.zig | 59 +++++++ tests/icc.zig | 272 +++++++++++++++++++++++++++++++ tools/check_samples.py | 49 +++++- tools/samples.zig | 57 ++++++- 12 files changed, 1133 insertions(+), 14 deletions(-) create mode 100644 src/icc.zig create mode 100644 tests/icc.zig diff --git a/README.md b/README.md index 78c9962..b90a589 100644 --- a/README.md +++ b/README.md @@ -41,7 +41,9 @@ never with `error.UnknownFormat`: the library can tell a PNG from a stray file and says so. EXIF orientation is read from JPEG and PNG, and nothing else about EXIF is -read or written. See [Orientation](#orientation). +read or written. See [Orientation](#orientation). ICC colour profiles are +carried between JPEG and PNG without being interpreted; see +[Colour profiles](#colour-profiles). The [API documentation](https://jeff.jcollie.page/z2dimg/) is generated from the doc comments, which carry most of the explanation of why each format is the @@ -690,6 +692,80 @@ 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: + +```zig +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. + +**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. + ## A standard library bug you should know about **Zig 0.16.0's inflater panics on malformed input.** Thirty-two bytes of @@ -937,6 +1013,10 @@ derivative. Digital compression and coding of continuous-tone still images: JPEG File Interchange Format (JFIF)* (ITU-T Rec. T.871 | ISO/IEC 10918-5). +- 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*. + - 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). @@ -1007,6 +1087,12 @@ 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 diff --git a/build.zig b/build.zig index b16c610..452ad46 100644 --- a/build.zig +++ b/build.zig @@ -79,6 +79,19 @@ pub fn build(b: *std.Build) void { }); test_step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = exif_mod })).step); + // The ICC tests, which are about carrying a profile from one file to + // another rather than about either codec. + const icc_mod = b.createModule(.{ + .root_source_file = b.path("tests/icc.zig"), + .target = target, + .optimize = optimize, + .imports = &.{ + .{ .name = "z2dimg", .module = mod }, + .{ .name = "z2d", .module = z2d_dep.module("z2d") }, + }, + }); + test_step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = icc_mod })).step); + // The fuzz targets: what a decoder must do with input nobody wrote. They // are ordinary tests as well as fuzz tests, so `zig build test` exercises // the same properties on the seeds checked in beside them. diff --git a/src/bmp.zig b/src/bmp.zig index 754d3ab..23b9a41 100644 --- a/src/bmp.zig +++ b/src/bmp.zig @@ -855,10 +855,12 @@ fn readDibHeader(cur: *Cursor, pixel_offset: u32, limits: Limits) DecodeError!He /// Reads a whole BMP from `r`, producing a surface the caller owns. pub fn decode(gpa: Allocator, r: *Io.Reader, opts: DecodeOptions) DecodeError!z2d.Surface { - // BMP has no metadata of this kind, and the promise is that a caller who - // asked for an orientation is given one rather than left with whatever - // the variable held before. + // BMP carries neither of these as far as this library reads it, and the + // promise is that a caller who asked is answered rather than left with + // whatever was there before. `icc` says why a `BITMAPV5HEADER`'s embedded + // profile is not read. if (opts.orientation) |out| out.* = .top_left; + if (opts.icc) |out| out.clearRetainingCapacity(); var decoder: Decoder = try .init(r, opts.limits); return decoder.decode(gpa, r, opts); } diff --git a/src/common.zig b/src/common.zig index 334b458..b97e17c 100644 --- a/src/common.zig +++ b/src/common.zig @@ -19,6 +19,7 @@ const z2d = @import("z2d"); const Format = @import("format.zig").Format; const exif = @import("exif.zig"); +const icc = @import("icc.zig"); /// How much a decoder is permitted to believe about an image before it has /// seen the pixels. @@ -58,6 +59,16 @@ pub const Limits = struct { /// bytes at all. max_input_bytes: u64 = 1 << 28, + /// The largest ICC colour profile to carry out of a file. + /// + /// A profile is metadata and is allocated on the strength of a length + /// field, which is exactly the shape of claim `Limits` exists to bound. + /// The default is what a JPEG can hold at all --- 255 segments of 65519 + /// bytes --- since a profile larger than that could not have come out of + /// one, and real profiles are a few kilobytes. A program that never asks + /// for a profile never allocates for one whatever this says. + max_icc_bytes: u64 = icc.jpeg_max, + /// Nothing is refused. For a program decoding files it produced itself, on /// a machine it is not sharing. pub const unlimited: Limits = .{ @@ -65,6 +76,7 @@ pub const Limits = struct { .max_height = std.math.maxInt(u32), .max_pixels = std.math.maxInt(u64), .max_input_bytes = std.math.maxInt(u64), + .max_icc_bytes = std.math.maxInt(u64), }; /// Refuses dimensions this budget will not pay for. @@ -152,6 +164,21 @@ pub const DecodeOptions = struct { /// /// Left null, nothing is written and nothing is parsed. orientation: ?*exif.Orientation = null, + + /// Where to put the file's ICC colour profile, if it has one. + /// + /// The bytes are appended with the same allocator the decode was given, + /// and the caller owns what is in the list afterwards. A file with no + /// profile, or with one that is not shaped like a profile, leaves it + /// untouched — so a list that started empty and ended empty means there + /// was nothing to carry. + /// + /// Left null, no profile is collected and nothing is allocated for one. + /// `Limits.max_icc_bytes` bounds what is. + /// + /// Nothing here interprets a profile; see `icc` for what that means and + /// why. + icc: ?*std.ArrayList(u8) = null, }; /// Everything a decode can fail with. diff --git a/src/icc.zig b/src/icc.zig new file mode 100644 index 0000000..9319e1a --- /dev/null +++ b/src/icc.zig @@ -0,0 +1,353 @@ +// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie +// SPDX-License-Identifier: MIT + +//! ICC colour profiles, carried through rather than understood. +//! +//! A profile says what the numbers in an image *mean* — which real colours +//! those bytes stand for, and how to get from them to some other device's +//! numbers. This library does not do any of 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, or +//! re-encoding one at a different quality, should hand back a file that still +//! says what its colours mean; a library 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. +//! +//! ## Where a profile lives +//! +//! JPEG has no chunk 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: each segment +//! begins `ICC_PROFILE\0`, then a one-based piece number and the number of +//! pieces, then that piece of the profile. That embedding belongs to ICC +//! rather than to JPEG, which is why it is described here and not in `jpeg`. +//! +//! PNG has `iCCP`, which holds a name, a compression method, and the profile +//! deflated. One chunk, whatever the size. +//! +//! BMP can carry one too, in a `BITMAPV5HEADER`, and this library does not +//! read it. 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. It is also +//! vanishingly rare. +//! +//! ## A profile that is not one is dropped +//! +//! As with EXIF: metadata is decoration, and a file with a broken profile in +//! it is still a perfectly good photograph. But unlike EXIF, this is passed +//! *on* rather than read, so a malformed profile carried through would become +//! a malformed profile in the output, which other readers would reject. So +//! anything that is not shaped like a profile is dropped rather than +//! propagated. + +const std = @import("std"); +const mem = std.mem; +const testing = std.testing; + +/// What every `APP2` segment carrying a piece of a profile begins with. +pub const jpeg_marker = "ICC_PROFILE\x00"; + +/// The most profile data one `APP2` segment can carry. +/// +/// A segment's length field counts itself, so 65535 leaves 65533 bytes behind +/// it; the marker above takes twelve of those and the two piece numbers take +/// two more. +pub const jpeg_chunk_len = 65535 - 2 - jpeg_marker.len - 2; + +/// The most pieces a profile may be split into, since the piece number is a +/// single byte and counts from one. +pub const jpeg_chunk_limit = 255; + +/// The largest profile a JPEG can carry, which is the natural ceiling on all +/// of this: 255 pieces of 65519 bytes. +pub const jpeg_max = jpeg_chunk_limit * jpeg_chunk_len; + +/// The fixed part of a profile, which every one begins with. +const header_len = 128; + +/// Whether a byte string is shaped like an ICC profile. +/// +/// Two checks, both from the profile's own header and both cheap. The first +/// four bytes are the profile's size, which must be the size it actually is — +/// that is what catches a truncated one, a profile reassembled from pieces +/// that went missing, and a chunk of something else entirely. Bytes 36 to 40 +/// are the signature `acsp`, which every profile since the first version has +/// carried and nothing else has a reason to. +/// +/// It is not a validation of the profile's contents, and is not meant to be: +/// what follows the header is a tag table describing colour transforms that +/// this library has no opinion about. +pub fn looksValid(bytes: []const u8) bool { + if (bytes.len < header_len) return false; + if (mem.readInt(u32, bytes[0..4], .big) != bytes.len) return false; + return mem.eql(u8, bytes[36..40], "acsp"); +} + +/// Collects a profile from the pieces a JPEG splits it into. +/// +/// The 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 it looks 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. +pub const Assembler = struct { + /// How many pieces the first one said there would be, or zero before any + /// have arrived. + total: u8 = 0, + /// How many have been taken. + seen: u8 = 0, + /// Set by anything that went wrong, after which nothing more is taken and + /// the result is nothing. + broken: bool = false, + + /// Offers one `APP2` payload, with the `ICC_PROFILE\0` marker already + /// matched and removed. + /// + /// Returns false when this piece was not usable, which the caller needs + /// only to decide whether to go on appending. + pub fn take( + self: *Assembler, + gpa: mem.Allocator, + out: *std.ArrayList(u8), + payload: []const u8, + limit: u64, + ) mem.Allocator.Error!bool { + if (self.broken) return false; + // The two numbers, and at least one byte of profile behind them. + if (payload.len < 3) return self.fail(out); + + const number = payload[0]; + const total = payload[1]; + if (total == 0 or number == 0 or number > total) return self.fail(out); + + if (self.seen == 0) { + self.total = total; + } else if (total != self.total) { + // The pieces disagree about how many there are. + return self.fail(out); + } + if (number != self.seen + 1) return self.fail(out); + + const piece = payload[2..]; + if (out.items.len + piece.len > limit) return self.fail(out); + try out.appendSlice(gpa, piece); + self.seen = number; + return true; + } + + /// Whether every piece arrived and what they came to is a profile. + /// + /// Called once the file's markers have been read. A profile that never + /// finished, or finished as something that is not a profile, leaves the + /// list empty. + pub fn finish(self: *Assembler, out: *std.ArrayList(u8)) void { + if (self.broken or self.seen == 0 or self.seen != self.total or + !looksValid(out.items)) + { + out.clearRetainingCapacity(); + self.broken = true; + } + } + + fn fail(self: *Assembler, out: *std.ArrayList(u8)) bool { + self.broken = true; + out.clearRetainingCapacity(); + return false; + } +}; + +/// A profile to write, split into the pieces a JPEG needs, one at a time. +/// +/// An iterator rather than a list, so that writing one allocates nothing: the +/// encoder holds the caller's profile and walks it. +pub const Pieces = struct { + profile: []const u8, + next: usize = 0, + + pub fn init(profile: []const u8) Pieces { + return .{ .profile = profile }; + } + + /// How many `APP2` segments this profile takes. + pub fn count(self: Pieces) usize { + return (self.profile.len + jpeg_chunk_len - 1) / jpeg_chunk_len; + } + + /// The next piece, and its one-based number. + pub fn take(self: *Pieces) ?struct { number: u8, bytes: []const u8 } { + if (self.next >= self.profile.len) return null; + const end = @min(self.next + jpeg_chunk_len, self.profile.len); + const bytes = self.profile[self.next..end]; + const number: u8 = @intCast(self.next / jpeg_chunk_len + 1); + self.next = end; + return .{ .number = number, .bytes = bytes }; + } +}; + +// -- tests ------------------------------------------------------------------- + +/// A profile-shaped byte string of `len` bytes: the right size in the right +/// place and the right signature, with nothing meaningful behind them. +fn fakeProfile(buf: []u8) []u8 { + @memset(buf, 0x5a); + mem.writeInt(u32, buf[0..4], @intCast(buf.len), .big); + @memcpy(buf[36..40], "acsp"); + return buf; +} + +test "what is and is not shaped like a profile" { + var buf: [400]u8 = undefined; + const good = fakeProfile(&buf); + try testing.expect(looksValid(good)); + + // Too short to hold a header. + try testing.expect(!looksValid(good[0..127])); + try testing.expect(!looksValid("")); + + // The size field disagreeing with the size, which is what catches a + // profile reassembled from pieces that went missing. + var wrong: [400]u8 = undefined; + _ = fakeProfile(&wrong); + mem.writeInt(u32, wrong[0..4], 399, .big); + try testing.expect(!looksValid(&wrong)); + + // And the signature. + var unsigned: [400]u8 = undefined; + _ = fakeProfile(&unsigned); + @memcpy(unsigned[36..40], "nope"); + try testing.expect(!looksValid(&unsigned)); +} + +test "a profile that fits in one piece" { + const gpa = testing.allocator; + var buf: [300]u8 = undefined; + const profile = fakeProfile(&buf); + + var pieces: Pieces = .init(profile); + try testing.expectEqual(@as(usize, 1), pieces.count()); + + var out: std.ArrayList(u8) = .empty; + defer out.deinit(gpa); + var asm_: Assembler = .{}; + + var payload: [2 + 300]u8 = undefined; + while (pieces.take()) |piece| { + payload[0] = piece.number; + payload[1] = 1; + @memcpy(payload[2..][0..piece.bytes.len], piece.bytes); + try testing.expect(try asm_.take(gpa, &out, payload[0 .. 2 + piece.bytes.len], jpeg_max)); + } + asm_.finish(&out); + try testing.expectEqualSlices(u8, profile, out.items); +} + +test "a profile that has to be split" { + const gpa = testing.allocator; + const size = jpeg_chunk_len * 2 + 17; + const buf = try gpa.alloc(u8, size); + defer gpa.free(buf); + const profile = fakeProfile(buf); + + var pieces: Pieces = .init(profile); + try testing.expectEqual(@as(usize, 3), pieces.count()); + + var out: std.ArrayList(u8) = .empty; + defer out.deinit(gpa); + var asm_: Assembler = .{}; + + const payload = try gpa.alloc(u8, 2 + jpeg_chunk_len); + defer gpa.free(payload); + const total: u8 = @intCast(pieces.count()); + var numbers: [3]u8 = undefined; + var at: usize = 0; + while (pieces.take()) |piece| { + numbers[at] = piece.number; + at += 1; + payload[0] = piece.number; + payload[1] = total; + @memcpy(payload[2..][0..piece.bytes.len], piece.bytes); + try testing.expect(try asm_.take(gpa, &out, payload[0 .. 2 + piece.bytes.len], jpeg_max)); + } + // Numbered from one, in order. + try testing.expectEqualSlices(u8, &.{ 1, 2, 3 }, &numbers); + asm_.finish(&out); + try testing.expectEqualSlices(u8, profile, out.items); +} + +test "pieces that do not add up leave nothing" { + const gpa = testing.allocator; + var buf: [300]u8 = undefined; + const profile = fakeProfile(&buf); + + const cases = [_]struct { note: []const u8, numbers: []const [2]u8 }{ + // A piece missing from the middle. + .{ .note = "gap", .numbers = &.{ .{ 1, 3 }, .{ 3, 3 } } }, + // Out of order, which no encoder writes and this does not reassemble. + .{ .note = "reversed", .numbers = &.{ .{ 2, 2 }, .{ 1, 2 } } }, + // The same piece twice. + .{ .note = "repeated", .numbers = &.{ .{ 1, 2 }, .{ 1, 2 } } }, + // Disagreeing about how many pieces there are. + .{ .note = "disagreement", .numbers = &.{ .{ 1, 2 }, .{ 2, 3 } } }, + // Numbered from zero. + .{ .note = "zero", .numbers = &.{.{ 0, 1 }} }, + // A piece past the end. + .{ .note = "past the end", .numbers = &.{.{ 2, 1 }} }, + // Fewer pieces than were promised. + .{ .note = "unfinished", .numbers = &.{.{ 1, 2 }} }, + }; + + for (cases) |k| { + var out: std.ArrayList(u8) = .empty; + defer out.deinit(gpa); + var asm_: Assembler = .{}; + var payload: [2 + 100]u8 = undefined; + for (k.numbers) |n| { + payload[0] = n[0]; + payload[1] = n[1]; + @memcpy(payload[2..][0..100], profile[0..100]); + _ = try asm_.take(gpa, &out, payload[0..102], jpeg_max); + } + asm_.finish(&out); + if (out.items.len != 0) { + std.debug.print("\n{s}: {d} bytes survived and should not have\n", .{ k.note, out.items.len }); + return error.ShouldHaveBeenDropped; + } + } +} + +test "a piece longer than the limit allows" { + const gpa = testing.allocator; + var out: std.ArrayList(u8) = .empty; + defer out.deinit(gpa); + var asm_: Assembler = .{}; + + var payload: [2 + 200]u8 = undefined; + payload[0] = 1; + payload[1] = 1; + @memset(payload[2..], 0); + try testing.expect(!try asm_.take(gpa, &out, &payload, 100)); + asm_.finish(&out); + try testing.expectEqual(@as(usize, 0), out.items.len); +} + +test "what was reassembled has to be a profile" { + const gpa = testing.allocator; + var out: std.ArrayList(u8) = .empty; + defer out.deinit(gpa); + var asm_: Assembler = .{}; + + // Every piece arrives and is numbered correctly, and what they come to is + // not a profile. + var payload: [2 + 200]u8 = undefined; + payload[0] = 1; + payload[1] = 1; + @memset(payload[2..], 0x11); + try testing.expect(try asm_.take(gpa, &out, &payload, jpeg_max)); + asm_.finish(&out); + try testing.expectEqual(@as(usize, 0), out.items.len); +} diff --git a/src/jpeg.zig b/src/jpeg.zig index 01ce189..2e06eeb 100644 --- a/src/jpeg.zig +++ b/src/jpeg.zig @@ -84,6 +84,7 @@ pub const huffman = @import("jpeg/huffman.zig"); pub const idct = @import("jpeg/idct.zig"); const exif = @import("exif.zig"); +const icc = @import("icc.zig"); /// The side of a block. Everything in JPEG is eight by eight. const block_size = idct.size; @@ -123,6 +124,7 @@ const Marker = struct { const dac = 0xcc; const app0 = 0xe0; const app1 = 0xe1; + const app2 = 0xe2; const app14 = 0xee; const com = 0xfe; const tem = 0x01; @@ -345,6 +347,46 @@ const Scanner = struct { return exif.readOrientation(self.r, @intCast(len)); } + /// `APP2`, which is where a piece of an ICC profile lives when a JPEG + /// carries one. + /// + /// The segment is consumed whatever it holds; an `APP2` that is not part + /// of a profile is simply not one this cares about. + fn readIcc( + self: *Scanner, + gpa: Allocator, + out: *std.ArrayList(u8), + assembler: *icc.Assembler, + limit: u64, + ) DecodeError!void { + const len = try self.segmentLen(); + if (len < icc.jpeg_marker.len) { + try self.r.discardAll(len); + return; + } + var head: [icc.jpeg_marker.len]u8 = undefined; + try self.r.readSliceAll(&head); + var left = len - icc.jpeg_marker.len; + if (!mem.eql(u8, &head, icc.jpeg_marker)) { + try self.r.discardAll(left); + return; + } + + // The rest of the segment is a piece number, a count, and profile. + // Read in bounded steps rather than in one allocation, so that a + // length field cannot ask for memory before the limit has seen it. + var payload: std.ArrayList(u8) = .empty; + defer payload.deinit(gpa); + var buf: [4096]u8 = undefined; + while (left > 0) { + const n = @min(left, buf.len); + try self.r.readSliceAll(buf[0..n]); + try payload.appendSlice(gpa, buf[0..n]); + left -= n; + } + _ = try assembler.take(gpa, out, payload.items, limit); + } + /// `SOFn`: the size of the image and the components it is made of. fn readFrameHeader(self: *Scanner, kind: FrameKind, limits: Limits) DecodeError!Frame { const len = try self.segmentLen(); @@ -1111,6 +1153,10 @@ pub fn decode(gpa: Allocator, r: *Io.Reader, opts: DecodeOptions) DecodeError!z2 // rather than saying nothing, which is the same promise `Info` makes. var found_orientation = false; if (opts.orientation) |out| out.* = .top_left; + // A profile arrives in pieces spread through the file's markers, so the + // collector lives as long as the marker loop does. + var assembler: icc.Assembler = .{}; + if (opts.icc) |out| out.clearRetainingCapacity(); var scans: usize = 0; // A scan's bit reader consumes the marker that ended it, so the marker is // handed back here rather than looked for again. @@ -1139,6 +1185,13 @@ pub fn decode(gpa: Allocator, r: *Io.Reader, opts: DecodeOptions) DecodeError!z2 state.restart_interval = try scanner.r.takeInt(u16, .big); }, Marker.app14 => adobe_transform = try scanner.readAdobe(), + Marker.app2 => { + if (opts.icc) |out| { + try scanner.readIcc(gpa, out, &assembler, opts.limits.max_icc_bytes); + } else { + try scanner.skipSegment(); + } + }, Marker.app1 => { if (opts.orientation) |out| { if (!found_orientation) { @@ -1176,6 +1229,10 @@ pub fn decode(gpa: Allocator, r: *Io.Reader, opts: DecodeOptions) DecodeError!z2 const frame = &(state.frame orelse return error.InvalidData); if (scans == 0) return error.InvalidData; + // Every marker has been seen, so a profile is either complete or is not + // one and is thrown away. + if (opts.icc) |out| assembler.finish(out); + try reconstruct(&state); const surface_type = opts.surface_type orelse pixels.naturalSurfaceType(false); @@ -1465,6 +1522,17 @@ pub const EncodeOptions = struct { /// Sequential or progressive. mode: Mode = .baseline, + /// An ICC colour profile to carry into the file, in `APP2` segments. + /// + /// Borrowed for the call and not kept. Nothing here interprets it — see + /// `icc` for what that means — but a profile that is not shaped like one + /// is refused with `error.Unsupported` rather than written, since a + /// malformed profile in the output is a file other readers reject. + /// + /// A profile larger than 255 segments of 65519 bytes cannot be written at + /// all, which is the format's limit rather than this encoder's. + icc: ?[]const u8 = null, + /// How many components to write, and what they mean. colour: Colour = .auto, @@ -1671,6 +1739,10 @@ pub fn encode( .ycbcr => false, }; // A single component has nothing to subsample against. + if (opts.icc) |profile| { + if (!icc.looksValid(profile) or profile.len > icc.jpeg_max) return error.Unsupported; + } + const chroma: Chroma = if (greyscale) .full else opts.chroma; if (!chroma.valid()) return error.Unsupported; const factors = chroma.resolve(); @@ -1791,6 +1863,20 @@ pub fn encode( try w.writeInt(u16, 1, .big); // y density try w.writeAll(&.{ 0, 0 }); // no thumbnail + // The profile, in as many `APP2` segments as it takes. Before everything + // but the JFIF header, which is where readers look for it. + if (opts.icc) |profile| { + var pieces: icc.Pieces = .init(profile); + const total = pieces.count(); + while (pieces.take()) |piece| { + try w.writeAll(&.{ 0xff, Marker.app2 }); + try w.writeInt(u16, @intCast(2 + icc.jpeg_marker.len + 2 + piece.bytes.len), .big); + try w.writeAll(icc.jpeg_marker); + try w.writeAll(&.{ piece.number, @intCast(total) }); + try w.writeAll(piece.bytes); + } + } + try writeQuantTable(w, 0, &luma_q); if (!greyscale) try writeQuantTable(w, 1, &chroma_q); diff --git a/src/png.zig b/src/png.zig index d5bf453..179a83c 100644 --- a/src/png.zig +++ b/src/png.zig @@ -73,6 +73,7 @@ const EncodeError = common.EncodeError; const Info = common.Info; const Limits = common.Limits; const exif = @import("exif.zig"); +const icc = @import("icc.zig"); const pixels = @import("pixels.zig"); const Rgba8 = pixels.Rgba8; @@ -281,6 +282,67 @@ const ChunkReader = struct { return found; } + /// Inflates an `iCCP` chunk's profile into `out`, still checking the + /// checksum. + /// + /// The chunk is a name, a compression method, and the profile deflated. + /// The name is of no use to anything here — it is a label a person chose + /// — and the compression method has only ever had one value. + fn readIcc( + self: *ChunkReader, + chunk: Chunk, + crc: *Crc32, + gpa: Allocator, + out: *std.ArrayList(u8), + limit: u64, + ) DecodeError!void { + // Bounded to the chunk before it is hashed, for the reason `readExif` + // gives: a reader reads ahead, and hashing the read-ahead would fold + // the checksum into itself. + var bound_buf: [512]u8 = undefined; + var limited = self.r.limited(.limited(chunk.len), &bound_buf); + var hash_buf: [512]u8 = undefined; + var hashed = limited.interface.hashed(crc, &hash_buf); + const source = &hashed.reader; + + inflate: { + // The name, up to 79 bytes and a terminator. + var name_len: usize = 0; + while (true) { + const b = source.takeByte() catch break :inflate; + if (b == 0) break; + name_len += 1; + if (name_len > 79) break :inflate; + } + if (name_len == 0) break :inflate; + const method = source.takeByte() catch break :inflate; + if (method != 0) break :inflate; + + const window = try gpa.alloc(u8, flate.max_window_len); + defer gpa.free(window); + var stream: flate.Decompress = .init(source, .zlib, window); + + var buf: [4096]u8 = undefined; + while (true) { + const n = stream.reader.readSliceShort(&buf) catch break :inflate; + if (n == 0) break; + if (out.items.len + n > limit) { + out.clearRetainingCapacity(); + break :inflate; + } + try out.appendSlice(gpa, buf[0..n]); + } + // A profile that is not one is dropped rather than carried into + // whatever the caller writes next. + if (!icc.looksValid(out.items)) out.clearRetainingCapacity(); + } + + // Whatever happened above, the rest of the chunk still has to be read + // for the checksum to mean anything. + _ = source.discardRemaining() catch {}; + try self.verify(crc); + } + /// Reads the four-byte checksum and compares it. fn verify(self: *ChunkReader, crc: *Crc32) DecodeError!void { const want = try self.r.takeInt(u32, .big); @@ -451,10 +513,22 @@ pub const Decoder = struct { /// What an `eXIf` chunk before the image data said, if there was one. orientation: exif.Orientation, + /// Somewhere to put the metadata that needs memory to collect. + /// + /// `init` reads every chunk before the image data, which is where an + /// `iCCP` profile is, and it is also what `probe` is built on — and + /// `probe` has no allocator and no reason to want one. So the sink is + /// optional: given one, the profile is inflated into it; given none, + /// the chunk is skipped like any other and nothing is allocated. + pub const Sink = struct { + gpa: Allocator, + icc: *std.ArrayList(u8), + }; + /// Reads the signature, `IHDR`, and every chunk up to the first `IDAT`. /// /// The `IDAT`'s length and type are consumed; its data is not. - pub fn init(r: *Io.Reader, limits: Limits) DecodeError!Decoder { + pub fn init(r: *Io.Reader, limits: Limits, sink: ?Sink) DecodeError!Decoder { const magic = try r.takeArray(signature.len); if (!mem.eql(u8, magic, signature)) return error.UnknownFormat; @@ -540,6 +614,15 @@ pub const Decoder = struct { ); continue; } + if (chunk.is("iCCP")) { + if (sink) |s| { + try chunks.readIcc(chunk, &crc, s.gpa, s.icc, limits.max_icc_bytes); + } else { + if (chunk.len > 1 << 24) return error.InvalidData; + try chunks.skip(chunk, &crc); + } + continue; + } if (chunk.is("eXIf")) { // The same TIFF block a JPEG carries in `APP1`, which is why // it is read by a module that belongs to neither codec. PNG @@ -936,7 +1019,9 @@ fn paeth(a: u8, b: u8, c: u8) u8 { /// Reads a whole PNG from `r`, producing a surface the caller owns. pub fn decode(gpa: Allocator, r: *Io.Reader, opts: DecodeOptions) DecodeError!z2d.Surface { - var decoder: Decoder = try .init(r, opts.limits); + if (opts.icc) |out| out.clearRetainingCapacity(); + const sink: ?Decoder.Sink = if (opts.icc) |out| .{ .gpa = gpa, .icc = out } else null; + var decoder: Decoder = try .init(r, opts.limits, sink); if (opts.orientation) |out| out.* = decoder.orientation; return decoder.decode(gpa, r, opts); } @@ -947,7 +1032,7 @@ pub fn decode(gpa: Allocator, r: *Io.Reader, opts: DecodeOptions) DecodeError!z2 /// image data; see `bmp.probe` for what that means for a caller who wants to /// probe and then decode. pub fn probe(r: *Io.Reader, limits: Limits) DecodeError!Info { - const decoder: Decoder = try .init(r, limits); + const decoder: Decoder = try .init(r, limits, null); return decoder.info(); } @@ -1002,6 +1087,20 @@ pub const FilterChoice = enum { pub const EncodeOptions = struct { level: Level = .default, filter: FilterChoice = .adaptive, + + /// An ICC colour profile to carry into the file, as an `iCCP` chunk. + /// + /// Borrowed for the call and not kept. Nothing here interprets it — see + /// `icc` for what that means — but a profile that is not shaped like one + /// is refused with `error.Unsupported` rather than written, since a + /// malformed profile in the output is a file other readers reject. + icc: ?[]const u8 = null, + + /// What to call the profile in the file. + /// + /// PNG requires a name of 1 to 79 bytes and does nothing with it; it is a + /// label for a person. Ignored when `icc` is null. + icc_name: []const u8 = "ICC profile", }; /// Writes `sfc` as a PNG. @@ -1055,6 +1154,33 @@ pub fn encode( ihdr[12] = @intFromEnum(Interlace.none); try writeChunk(w, "IHDR", &ihdr); + // -- iCCP ---------------------------------------------------------------- + if (opts.icc) |profile| { + if (!icc.looksValid(profile)) return error.Unsupported; + if (opts.icc_name.len == 0 or opts.icc_name.len > 79) return error.Unsupported; + // A name is Latin-1 text with no null in it, since a null is what + // ends it. + if (mem.indexOfScalar(u8, opts.icc_name, 0) != null) return error.Unsupported; + + var chunk: std.ArrayList(u8) = .empty; + defer chunk.deinit(gpa); + try chunk.appendSlice(gpa, opts.icc_name); + try chunk.append(gpa, 0); + try chunk.append(gpa, 0); // deflate, the only compression method + try chunk.ensureUnusedCapacity(gpa, 1024); + { + var out: Io.Writer.Allocating = .fromArrayList(gpa, &chunk); + defer chunk = out.toArrayList(); + const window = try gpa.alloc(u8, flate.max_window_len); + defer gpa.free(window); + var deflate = flate.Compress.init(&out.writer, window, .zlib, opts.level.options()) catch + return error.WriteFailed; + try deflate.writer.writeAll(profile); + try deflate.finish(); + } + try writeChunk(w, "iCCP", chunk.items); + } + // -- IDAT ---------------------------------------------------------------- // // The compressed image is assembled in memory and written as one chunk. diff --git a/src/root.zig b/src/root.zig index b685a38..ec7e1dd 100644 --- a/src/root.zig +++ b/src/root.zig @@ -87,6 +87,9 @@ pub const bmp = codecs.bmp; pub const png = codecs.png; /// JFIF/JPEG. pub const jpeg = codecs.jpeg; +/// ICC colour profiles, carried from one file to another without being +/// interpreted. +pub const icc = @import("icc.zig"); /// Which way up an image goes, read from the EXIF block a JPEG or a PNG can /// carry. pub const exif = @import("exif.zig"); diff --git a/tests/fuzz.zig b/tests/fuzz.zig index 509dfe3..8b502b2 100644 --- a/tests/fuzz.zig +++ b/tests/fuzz.zig @@ -426,6 +426,19 @@ const png_corpus = [_][]const u8{ /// into a wrong-looking image. /// EXIF blocks to mutate: the two byte orders, with and without the marker /// JPEG puts in front of them, and the smallest thing that is a directory. +/// Profile pieces to mutate: one whole profile in a single piece, and the +/// same one cut in two. +const icc_corpus = [_][]const u8{ + // A piece number, a count, and a profile of 128 bytes: the size field, + // then padding to the signature, then `acsp`, then the rest. + "\x01\x01" ++ "\x00\x00\x00\x80" ++ ("\x00" ** 32) ++ "acsp" ++ ("\x00" ** 88), + // The same profile as two pieces. + "\x01\x02" ++ "\x00\x00\x00\x80" ++ ("\x00" ** 32) ++ "acsp" ++ + "\x02\x02" ++ ("\x00" ** 88), + // A count of zero, which nothing may be a piece of. + "\x01\x00rubbish", +}; + const exif_corpus = [_][]const u8{ // Little-endian, orientation 6, which is the one a camera held on its side // writes and so the one that matters most. @@ -1473,6 +1486,51 @@ test "fuzz exif" { try testing.fuzz({}, fuzzExif, .{}); } +// -- ICC --------------------------------------------------------------------- + +/// Reassembling a profile from pieces is total, bounded, and never hands back +/// something that is not a profile. +/// +/// The pieces of a JPEG's profile are length-prefixed segments an attacker +/// writes, and what they claim about each other --- which piece this is, how +/// many there are --- is checked against nothing else in the file. So the +/// three properties that matter are that it always terminates, that it never +/// exceeds the caller's budget however the pieces are numbered, and that a +/// profile that came back is one, since it is about to be written into +/// somebody else's file. +fn iccProperty(input: []const u8) !void { + const limit = 4096; + var out: std.ArrayList(u8) = .empty; + defer out.deinit(backing); + var assembler: z2dimg.icc.Assembler = .{}; + + // The input cut into pieces at a length the input itself chooses, which + // is how a malformed file's segments arrive. + var at: usize = 0; + while (at < input.len) { + const take = @max(1, @as(usize, input[at]) + 1); + const end = @min(at + take, input.len); + _ = try assembler.take(backing, &out, input[at..end], limit); + at = end; + } + assembler.finish(&out); + + try testing.expect(out.items.len <= limit); + if (out.items.len != 0) { + try testing.expect(z2dimg.icc.looksValid(out.items)); + } +} + +fn fuzzIcc(_: void, smith: *Smith) !void { + var buf: [content_max]u8 = undefined; + try iccProperty(buf[0..smith.slice(&buf)]); +} + +test "fuzz icc" { + for (icc_corpus) |seed| try iccProperty(seed); + try testing.fuzz({}, fuzzIcc, .{}); +} + // -- the table --------------------------------------------------------------- /// Wraps one of the `fuzz*` functions above so that it takes raw bytes, which @@ -1488,6 +1546,7 @@ fn Driven(comptime one: fn (void, *Smith) anyerror!void) type { pub const all = [_]Target{ .{ .name = "exif", .run = Driven(fuzzExif).run, .corpus = &exif_corpus, .content_max = content_max }, + .{ .name = "icc", .run = Driven(fuzzIcc).run, .corpus = &icc_corpus, .content_max = content_max }, .{ .name = "decode", .run = Driven(fuzzDecode).run, .corpus = &mixed_corpus, .content_max = content_max, .repair = repairPng }, .{ .name = "probe", .run = Driven(fuzzProbe).run, .corpus = &mixed_corpus, .content_max = content_max, .repair = repairPng }, .{ .name = "png", .run = Driven(fuzzPng).run, .corpus = &png_corpus, .content_max = content_max, .repair = repairPng, .interesting = png_interesting }, diff --git a/tests/icc.zig b/tests/icc.zig new file mode 100644 index 0000000..c230358 --- /dev/null +++ b/tests/icc.zig @@ -0,0 +1,272 @@ +// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie +// SPDX-License-Identifier: MIT + +//! ICC profiles carried from one file to another. +//! +//! `src/icc.zig` has the unit tests for the pieces — what is shaped like a +//! profile, and how a JPEG splits one up. These are the other half: that a +//! profile put into a file comes back out of it unchanged, and that it +//! survives being moved between formats, which is the whole point of carrying +//! it at all. + +const std = @import("std"); +const Io = std.Io; +const mem = std.mem; +const testing = std.testing; +const Allocator = mem.Allocator; + +const z2d = @import("z2d"); +const z2dimg = @import("z2dimg"); + +/// A profile-shaped byte string: the right size in the right place and the +/// right signature, with a recognisable pattern behind them so that a profile +/// that came back subtly wrong is not mistaken for one that came back right. +fn fakeProfile(gpa: Allocator, len: usize) ![]u8 { + const buf = try gpa.alloc(u8, len); + for (buf, 0..) |*b, i| b.* = @truncate(i *% 97 +% 13); + mem.writeInt(u32, buf[0..4], @intCast(len), .big); + @memcpy(buf[36..40], "acsp"); + return buf; +} + +fn surface(gpa: Allocator) !z2d.Surface { + var sfc: z2d.Surface = try .init(.image_surface_rgb, gpa, 24, 16); + errdefer sfc.deinit(gpa); + for (0..16) |y| for (0..24) |x| { + sfc.putPixel(@intCast(x), @intCast(y), .{ .rgb = .{ + .r = @truncate(x * 10), + .g = @truncate(y * 15), + .b = @truncate((x + y) * 7), + } }); + }; + return sfc; +} + +fn encodeWith(gpa: Allocator, sfc: *const z2d.Surface, opts: z2dimg.EncodeOptions) ![]u8 { + var list: std.ArrayList(u8) = .empty; + errdefer list.deinit(gpa); + var w: Io.Writer.Allocating = .fromArrayList(gpa, &list); + errdefer list = w.toArrayList(); + try z2dimg.encode(gpa, sfc, &w.writer, opts); + list = w.toArrayList(); + return list.toOwnedSlice(gpa); +} + +test "a profile comes back out of the file it went into" { + const gpa = testing.allocator; + var sfc = try surface(gpa); + defer sfc.deinit(gpa); + + // Sizes either side of the 65519 bytes one APP2 segment holds, so that + // both the single-segment case and the reassembly are covered. + for ([_]usize{ 128, 300, 3000, 65519, 65520, 140_000 }) |len| { + const profile = try fakeProfile(gpa, len); + defer gpa.free(profile); + + for ([_]z2dimg.EncodeOptions{ + .{ .jpeg = .{ .icc = profile } }, + .{ .jpeg = .{ .icc = profile, .mode = .progressive } }, + .{ .png = .{ .icc = profile } }, + }) |opts| { + const bytes = try encodeWith(gpa, &sfc, opts); + defer gpa.free(bytes); + + var got: std.ArrayList(u8) = .empty; + defer got.deinit(gpa); + var r: Io.Reader = .fixed(bytes); + var back = try z2dimg.decode(gpa, &r, .{ .icc = &got }); + defer back.deinit(gpa); + + if (!mem.eql(u8, profile, got.items)) { + std.debug.print("\n{t}, {d} bytes in, {d} out\n", .{ opts, len, got.items.len }); + return error.ProfileDidNotSurvive; + } + } + } +} + +test "a profile moved from a JPEG to a PNG" { + // The reason any of this exists: a program converting between formats + // should not silently turn a wide-gamut photograph into a washed-out one. + const gpa = testing.allocator; + var sfc = try surface(gpa); + defer sfc.deinit(gpa); + + const profile = try fakeProfile(gpa, 4096); + defer gpa.free(profile); + + const jpeg = try encodeWith(gpa, &sfc, .{ .jpeg = .{ .icc = profile } }); + defer gpa.free(jpeg); + + var carried: std.ArrayList(u8) = .empty; + defer carried.deinit(gpa); + var r: Io.Reader = .fixed(jpeg); + var decoded = try z2dimg.decode(gpa, &r, .{ .icc = &carried }); + defer decoded.deinit(gpa); + try testing.expectEqualSlices(u8, profile, carried.items); + + const png = try encodeWith(gpa, &decoded, .{ .png = .{ .icc = carried.items } }); + defer gpa.free(png); + + var again: std.ArrayList(u8) = .empty; + defer again.deinit(gpa); + var r2: Io.Reader = .fixed(png); + var final = try z2dimg.decode(gpa, &r2, .{ .icc = &again }); + defer final.deinit(gpa); + try testing.expectEqualSlices(u8, profile, again.items); +} + +test "a file with no profile leaves the list alone" { + const gpa = testing.allocator; + var sfc = try surface(gpa); + defer sfc.deinit(gpa); + + for ([_]z2dimg.EncodeOptions{ .{ .jpeg = .{} }, .{ .png = .{} }, .{ .bmp = .{} } }) |opts| { + const bytes = try encodeWith(gpa, &sfc, opts); + defer gpa.free(bytes); + + // Starting with something in the list, so that "left alone" and + // "emptied" are told apart: the promise is that a caller who asked is + // answered, not that the list is never touched. + var got: std.ArrayList(u8) = .empty; + defer got.deinit(gpa); + try got.appendSlice(gpa, "stale"); + + var r: Io.Reader = .fixed(bytes); + var back = try z2dimg.decode(gpa, &r, .{ .icc = &got }); + defer back.deinit(gpa); + try testing.expectEqual(@as(usize, 0), got.items.len); + } +} + +test "a profile that is not one is refused rather than written" { + const gpa = testing.allocator; + var sfc = try surface(gpa); + defer sfc.deinit(gpa); + + const profile = try fakeProfile(gpa, 300); + defer gpa.free(profile); + + // The size field disagreeing with the size, which is the commonest way a + // profile arrives broken. + var wrong = try gpa.dupe(u8, profile); + defer gpa.free(wrong); + mem.writeInt(u32, wrong[0..4], 299, .big); + + // And something that is not a profile at all. + const nonsense = "this is not an ICC profile, it is a sentence"; + + for ([_][]const u8{ wrong, nonsense, "" }) |bad| { + try testing.expectError(error.Unsupported, encodeWith(gpa, &sfc, .{ .jpeg = .{ .icc = bad } })); + try testing.expectError(error.Unsupported, encodeWith(gpa, &sfc, .{ .png = .{ .icc = bad } })); + } +} + +test "a PNG profile name has to be one PNG allows" { + const gpa = testing.allocator; + var sfc = try surface(gpa); + defer sfc.deinit(gpa); + const profile = try fakeProfile(gpa, 300); + defer gpa.free(profile); + + const too_long = "x" ** 80; + for ([_][]const u8{ "", too_long, "has\x00a null" }) |name| { + try testing.expectError(error.Unsupported, encodeWith(gpa, &sfc, .{ + .png = .{ .icc = profile, .icc_name = name }, + })); + } + // And the boundary is where PNG puts it. + const just_right = "x" ** 79; + const bytes = try encodeWith(gpa, &sfc, .{ .png = .{ .icc = profile, .icc_name = just_right } }); + defer gpa.free(bytes); + try testing.expect(mem.indexOf(u8, bytes, "iCCP") != null); +} + +test "the limit is what bounds a profile, not the file" { + const gpa = testing.allocator; + var sfc = try surface(gpa); + defer sfc.deinit(gpa); + + const profile = try fakeProfile(gpa, 20_000); + defer gpa.free(profile); + + for ([_]z2dimg.EncodeOptions{ .{ .jpeg = .{ .icc = profile } }, .{ .png = .{ .icc = profile } } }) |opts| { + const bytes = try encodeWith(gpa, &sfc, opts); + defer gpa.free(bytes); + + // Under the limit it comes back; over it, nothing does, and the image + // still decodes — a profile too large for the caller's budget is a + // reason to drop the profile, not to refuse the photograph. + var got: std.ArrayList(u8) = .empty; + defer got.deinit(gpa); + var r: Io.Reader = .fixed(bytes); + var back = try z2dimg.decode(gpa, &r, .{ + .icc = &got, + .limits = .{ .max_icc_bytes = 1000 }, + }); + defer back.deinit(gpa); + try testing.expectEqual(@as(usize, 0), got.items.len); + try testing.expectEqual(@as(i32, 24), back.getWidth()); + + var plenty: std.ArrayList(u8) = .empty; + defer plenty.deinit(gpa); + var r2: Io.Reader = .fixed(bytes); + var back2 = try z2dimg.decode(gpa, &r2, .{ + .icc = &plenty, + .limits = .{ .max_icc_bytes = 20_000 }, + }); + defer back2.deinit(gpa); + try testing.expectEqualSlices(u8, profile, plenty.items); + } +} + +test "a caller who asks for nothing allocates nothing for it" { + const gpa = testing.allocator; + var sfc = try surface(gpa); + defer sfc.deinit(gpa); + const profile = try fakeProfile(gpa, 8000); + defer gpa.free(profile); + + // The testing allocator is the check here: a profile collected into a list + // nobody owns would be a leak, and asking for none must not collect one. + for ([_]z2dimg.EncodeOptions{ .{ .jpeg = .{ .icc = profile } }, .{ .png = .{ .icc = profile } } }) |opts| { + const bytes = try encodeWith(gpa, &sfc, opts); + defer gpa.free(bytes); + var r: Io.Reader = .fixed(bytes); + var back = try z2dimg.decode(gpa, &r, .{}); + defer back.deinit(gpa); + } +} + +test "a file truncated anywhere still decodes or fails cleanly" { + const gpa = testing.allocator; + var sfc = try surface(gpa); + defer sfc.deinit(gpa); + const profile = try fakeProfile(gpa, 3000); + defer gpa.free(profile); + + for ([_]z2dimg.EncodeOptions{ .{ .jpeg = .{ .icc = profile } }, .{ .png = .{ .icc = profile } } }) |opts| { + const bytes = try encodeWith(gpa, &sfc, opts); + defer gpa.free(bytes); + + var n: usize = 0; + while (n < bytes.len) : (n += 7) { + var got: std.ArrayList(u8) = .empty; + defer got.deinit(gpa); + var r: Io.Reader = .fixed(bytes[0..n]); + if (z2dimg.decode(gpa, &r, .{ .icc = &got })) |s| { + var back = s; + back.deinit(gpa); + } else |err| switch (err) { + error.UnknownFormat, + error.InvalidData, + error.Unsupported, + error.EndOfStream, + error.ReadFailed, + error.ImageTooLarge, + => {}, + error.OutOfMemory => |e| return e, + } + } + } +} diff --git a/tools/check_samples.py b/tools/check_samples.py index 82fc1b2..575f868 100644 --- a/tools/check_samples.py +++ b/tools/check_samples.py @@ -71,8 +71,55 @@ def main(argv): f"{base_path.stat().st_size} -> {prog_path.stat().st_size} bytes, identical" ) + profiles, profile_failures = check_profiles(directory) + print(f"\n{len(pairs) - failures} of {len(pairs)} pairs agree with libjpeg exactly") - return 1 if failures else 0 + if profiles: + print( + f"{profiles - profile_failures} of {profiles} embedded profiles " + f"come back byte for byte" + ) + return 1 if failures or profile_failures else 0 + + +def check_profiles(directory): + """Every file beside an `.icc` sidecar must hand that profile back. + + This is the other thing the Zig tests cannot do. They check that this + library reads back what this library wrote, which would agree with itself + about a mistake; Pillow reads the profile with libjpeg and libpng, which + is what everything else on the machine uses. + """ + checked = 0 + failures = 0 + for sidecar in sorted(directory.glob("*.icc")): + want = sidecar.read_bytes() + stem = sidecar.name.removesuffix(".icc") + carriers = sorted( + p for p in directory.iterdir() + if p.name.startswith(stem) and p.suffix in (".jpg", ".png") + ) + if not carriers: + print(f"FAIL {stem}: a profile with no file carrying it") + failures += 1 + continue + for path in carriers: + checked += 1 + with Image.open(path) as im: + im.load() + got = im.info.get("icc_profile") + if got is None: + print(f"FAIL {path.name}: no profile where one was written") + failures += 1 + elif got != want: + print( + f"FAIL {path.name}: profile differs, " + f"{len(want)} bytes written and {len(got)} read back" + ) + failures += 1 + else: + print(f"ok {path.name}: {len(got)} byte profile, identical") + return checked, failures if __name__ == "__main__": diff --git a/tools/samples.zig b/tools/samples.zig index 600b51e..3b07725 100644 --- a/tools/samples.zig +++ b/tools/samples.zig @@ -145,6 +145,46 @@ pub fn main(init: std.process.Init) !void { var dir = try Io.Dir.cwd().createDirPathOpen(io, args[1], .{}); defer dir.close(io); + // A profile-shaped block, in two sizes: one that fits in a single `APP2` + // segment and one that has to be split across three. What is in it is + // arbitrary --- nothing reads a profile --- but it has the header that + // makes it one, and a pattern behind that so a profile which came back + // subtly wrong is not mistaken for one that came back right. + for ([_]usize{ 3000, 140_000 }) |len| { + const profile = try gpa.alloc(u8, len); + defer gpa.free(profile); + for (profile, 0..) |*b, i| b.* = @truncate(i *% 97 +% 13); + std.mem.writeInt(u32, profile[0..4], @intCast(len), .big); + @memcpy(profile[36..40], "acsp"); + + var sfc = try pattern(gpa, .{ .name = "icc", .width = 32, .height = 24, .chroma = .half }); + defer sfc.deinit(gpa); + + var name_buf: [64]u8 = undefined; + const stem = try std.fmt.bufPrint(&name_buf, "icc-{d}", .{len}); + + // The profile itself, for the script to compare against. + try write(io, dir, try std.fmt.bufPrint(name_buf[stem.len..], "{s}.icc", .{stem}), profile); + + for ([_]z2dimg.jpeg.Mode{ .baseline, .progressive }) |mode| { + var out: Io.Writer.Allocating = .init(gpa); + defer out.deinit(); + try z2dimg.encode(gpa, &sfc, &out.writer, .{ .jpeg = .{ + .chroma = .half, + .mode = mode, + .icc = profile, + } }); + var buf: [64]u8 = undefined; + try write(io, dir, try std.fmt.bufPrint(&buf, "{s}-{t}.jpg", .{ stem, mode }), out.written()); + } + + var out: Io.Writer.Allocating = .init(gpa); + defer out.deinit(); + try z2dimg.encode(gpa, &sfc, &out.writer, .{ .png = .{ .icc = profile } }); + var buf: [64]u8 = undefined; + try write(io, dir, try std.fmt.bufPrint(&buf, "{s}.png", .{stem}), out.written()); + } + var written: usize = 0; for (cases) |case| { var sfc = try pattern(gpa, case); @@ -168,12 +208,7 @@ pub fn main(init: std.process.Init) !void { var name_buf: [64]u8 = undefined; const name = try std.fmt.bufPrint(&name_buf, "{s}-{t}.jpg", .{ case.name, mode }); - var file = try dir.createFile(io, name, .{}); - defer file.close(io); - var file_buf: [4096]u8 = undefined; - var writer = file.writer(io, &file_buf); - try writer.interface.writeAll(out.written()); - try writer.interface.flush(); + try write(io, dir, name, out.written()); written += 1; } } @@ -182,6 +217,16 @@ pub fn main(init: std.process.Init) !void { try stderr.flush(); } +/// One file into the directory. +fn write(io: Io, dir: Io.Dir, name: []const u8, bytes: []const u8) !void { + var file = try dir.createFile(io, name, .{}); + defer file.close(io); + var buf: [4096]u8 = undefined; + var writer = file.writer(io, &buf); + try writer.interface.writeAll(bytes); + try writer.interface.flush(); +} + /// Something with enough structure in it to exercise the coder: a gradient for /// the low frequencies, and a check pattern on top for the high ones. A flat /// image would leave every AC coefficient zero and every scan after the first -- knotmirror 0.0.1