Something went wrong. Try again.
Brotli (RFC 7932) compression and decompression for Zig 0.17, with sans-I/O streaming cores and std.Io adapters.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! A mutation fuzzer over the test vectors.//!//! Random bytes are rejected within the first few bits of a header, so rather//! than ask the fuzzer to invent a stream, each input picks one of the vectors//! and then a series of edits to it: a byte overwritten, a bit flipped, a//! stretch cut out. That keeps enough of the structure for the edits to land//! in prefix codes, context maps and commands, which is where a decompressor//! goes wrong. The stream is fed in pieces whose sizes the fuzzer also//! chooses, so that every edit is also tried across a call boundary.//!//! A finding is a crash or a leak. Errors are the expected outcome.//!//! zig build test --fuzz # until interrupted//! zig build test --fuzz=1M # a bounded run//!//! Without `--fuzz` the test runs the corpus below once: every vector,//! unedited.
const std = @import("std");const brotli = @import("brotli");const synth = @import("synth.zig");const vectors = @import("vectors.zig").vectors;
/// The vectors and synthetic streams small enough to mutate quickly. Those/// that decode to megabytes spend each iteration copying bytes rather than/// reading headers.const seeds = blk: { @setEvalBranchQuota(100_000); var list: []const []const u8 = &.{}; for (vectors) |v| { if (v.compressed.len <= 16 << 10 and v.length <= max_output) list = list ++ .{v.compressed}; } for (synth.cases) |c| { var length: usize = 0; for (c.output) |p| length += switch (p) { .text => |t| t.len, .repeat => |r| r.count * r.pattern.len, }; if (length <= max_output) list = list ++ .{c.compressed}; } break :blk list;};
/// One corpus entry per seed: `Smith.index` reads a little-endian `u64`,/// and an input with nothing after it makes no edits.const corpus = blk: { var entries: [seeds.len][]const u8 = undefined; for (&entries, 0..) |*e, i| { var b: [8]u8 = undefined; std.mem.writeInt(u64, &b, i, .little); const copy = b; e.* = © } break :blk entries;};
const Edit = enum { byte, flip, cut, duplicate };
/// More output than this from one stream is a stream the fuzzer has made/// repetitive, not a finding; stop there.const max_output = 256 << 10;
fn fuzzOne(_: void, smith: *std.testing.Smith) anyerror!void { const gpa = std.testing.allocator; var data: std.ArrayList(u8) = .empty; defer data.deinit(gpa); try data.appendSlice(gpa, seeds[smith.index(seeds.len)]);
var edits: usize = 0; while (data.items.len > 0 and !smith.eosWeightedSimple(1, 3) and edits < 16) : (edits += 1) { const at = smith.index(data.items.len); switch (smith.value(Edit)) { .byte => data.items[at] = smith.value(u8), .flip => data.items[at] ^= @as(u8, 1) << smith.value(u3), .cut => { const n = @min(data.items.len - at, 1 + smith.index(16)); data.replaceRangeAssumeCapacity(at, n, &.{}); }, .duplicate => { const n = @min(data.items.len - at, 1 + smith.index(16)); const copy = try gpa.dupe(u8, data.items[at..][0..n]); defer gpa.free(copy); try data.insertSlice(gpa, at, copy); }, } }
const in_step = 1 + smith.index(64); const out_step = 1 + smith.index(4096); try exercise(gpa, data.items, in_step, out_step);}
fn exercise(gpa: std.mem.Allocator, input: []const u8, in_step: usize, out_step: usize) !void { var d: brotli.Decompressor = .init(gpa, .{}); defer d.deinit(); var out: [4096]u8 = undefined; var in = input; var total: usize = 0; while (total < max_output) { const r = d.decompress(in[0..@min(in.len, in_step)], out[0..out_step]) catch return; in = in[r.read..]; total += r.written; switch (r.status) { .done => return, .need_input => if (in.len == 0) return, .need_output => {}, } }}
test "fuzz the decompressor" { try std.testing.fuzz({}, fuzzOne, .{ .corpus = &corpus });}
/// Most inputs the round-trip fuzzer builds are much smaller than this.const max_round_trip = 4 << 10;
/// Builds an input with the structure compressors look for, compresses it/// with options, pieces and flushes the fuzzer chooses, and checks that it/// decompresses to what went in. A finding here is a crash, a leak, or a/// stream that does not round-trip.fn roundTripOne(_: void, smith: *std.testing.Smith) anyerror!void { const gpa = std.testing.allocator; var data: std.ArrayList(u8) = .empty; defer data.deinit(gpa);
// Runs, repeats of what is already there (so, copies), and fresh bytes. while (!smith.eosWeightedSimple(3, 1) and data.items.len < max_round_trip) { const n = 1 + smith.index(300); switch (smith.index(3)) { 0 => try data.appendNTimes(gpa, smith.value(u8), n), 1 => if (data.items.len > 0) { const from = smith.index(data.items.len); for (0..n) |k| try data.append(gpa, data.items[from + k % (data.items.len - from)]); }, else => { const at = data.items.len; try data.resize(gpa, at + n); smith.bytes(data.items[at..]); }, } }
const options: brotli.Compressor.Options = .{ .quality = smith.valueRangeAtMost(u4, 0, brotli.Compressor.max_quality), .window_bits = smith.valueRangeAtMost(u5, 10, 24), }; const in_step = 1 + smith.index(1 << 12); const out_step = 1 + smith.index(1 << 12); const flush_every = smith.index(1 << 14);
var c: brotli.Compressor = .init(gpa, options); defer c.deinit(); var out: std.ArrayList(u8) = .empty; defer out.deinit(gpa); var pos: usize = 0; var next_flush = if (flush_every == 0) data.items.len else flush_every; while (true) { const end = @min(data.items.len, pos + in_step, next_flush); const op: brotli.Compressor.Operation = if (end == data.items.len) .finish else if (end == next_flush) .flush else .process; try out.ensureUnusedCapacity(gpa, out_step); const r = try c.compress(data.items[pos..end], out.unusedCapacitySlice()[0..out_step], op); pos += r.read; out.items.len += r.written; switch (r.status) { .need_output => {}, .done => break, .need_input => if (op == .flush) { next_flush = @min(data.items.len, pos + flush_every); }, } }
const back = try brotli.decompressAlloc(gpa, out.items, data.items.len); defer gpa.free(back); try std.testing.expectEqualSlices(u8, data.items, back);}
test "fuzz the compressor with round trips" { try std.testing.fuzz({}, roundTripOne, .{});}