// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! A fuzzing loop of our own, beside Zig's. //! //! The targets in `tests/fuzz.zig` are written for Zig's fuzzer, and for //! searching, `zig build fuzz --fuzz` is the thing to run: it has coverage //! feedback and this does not. This is the other half -- a loop bounded by a //! count of inputs rather than by coverage or a clock, which is what CI wants, //! where an open-ended search is the wrong shape. //! //! What it has in place of coverage is a corpus of inputs that are already //! valid -- real expressions, real documents, real stylesheets -- which for a //! parser is most of the way there: the interesting inputs are the ones that //! are nearly right, and those are what mutating a valid input produces. //! //! zig build fuzz-run # until interrupted //! zig build fuzz-run -- --iterations 500000 //! zig build fuzz-run -- --seconds 600 --target xpath const std = @import("std"); const Io = std.Io; const targets_mod = @import("fuzz_targets"); const usage = \\usage: ztree-fuzz [options] \\ \\Mutates the seed corpus of each fuzz target and reports anything that \\does not merely return or fail. \\ \\options: \\ --iterations N stop after N inputs (default: unbounded) \\ --seconds N stop after N seconds \\ --target NAME only the target whose name is NAME \\ --seed N start from this random seed rather than the clock \\ -h, --help show this message \\ ; /// The largest input the mutator will build. Long enough for a real /// stylesheet, short enough that a failure is readable. const max_input = 64 * 1024; pub fn main(init: std.process.Init) !void { const io = init.io; const arena = init.arena.allocator(); var stdout_buffer: [16 * 1024]u8 = undefined; var stdout: Io.File.Writer = .init(.stdout(), io, &stdout_buffer); const out = &stdout.interface; var iterations: ?usize = null; var seconds: ?u64 = null; var only: ?[]const u8 = null; // The clock comes from the `Io`, which is where 0.16 keeps it. var seed: u64 = @bitCast(@as(i64, Io.Timestamp.now(io, .real).toMilliseconds())); const args = try init.minimal.args.toSlice(arena); var i: usize = @min(1, args.len); while (i < args.len) : (i += 1) { const arg = args[i]; if (std.mem.eql(u8, arg, "-h") or std.mem.eql(u8, arg, "--help")) { try out.writeAll(usage); try out.flush(); return; } else if (std.mem.eql(u8, arg, "--iterations")) { i += 1; iterations = try std.fmt.parseInt(usize, args[i], 10); } else if (std.mem.eql(u8, arg, "--seconds")) { i += 1; seconds = try std.fmt.parseInt(u64, args[i], 10); } else if (std.mem.eql(u8, arg, "--target")) { i += 1; only = args[i]; } else if (std.mem.eql(u8, arg, "--seed")) { i += 1; seed = try std.fmt.parseInt(u64, args[i], 10); } else { try out.print("unknown option {s}\n", .{arg}); try out.flush(); std.process.exit(2); } } var debug_allocator: std.heap.DebugAllocator(.{}) = .init; defer _ = debug_allocator.deinit(); const gpa = debug_allocator.allocator(); // The targets cannot name `std.testing.allocator`, which does not exist // outside a test build, so they take one from here instead -- and this one // reports a leak, which is a finding as much as a crash is. targets_mod.backing = gpa; var prng: std.Random.DefaultPrng = .init(seed); const random = prng.random(); var buffer: [max_input]u8 = undefined; // `awake` rather than `real`: a run bounded by `--seconds` must not end // early because the system clock was adjusted under it. const start = Io.Timestamp.now(io, .awake); try out.print("seed {d}\n", .{seed}); try out.flush(); var count: usize = 0; var failures: usize = 0; while (true) { if (iterations) |limit| { if (count >= limit) break; } if (seconds) |limit| { const elapsed = start.durationTo(Io.Timestamp.now(io, .awake)); if (elapsed.toSeconds() >= limit) break; } for (targets_mod.targets) |target| { if (only) |name| { if (!std.mem.eql(u8, name, target.name)) continue; } const input = mutate(random, target.seeds, &buffer); count += 1; target.run(input) catch |err| { failures += 1; try out.print( "\n{s}: {t}\ninput ({d} bytes):\n{s}\n", .{ target.name, err, input.len, input }, ); try out.flush(); }; } // Progress often enough to show the loop is alive, rarely enough not // to be what the run spends its time on. A whole line rather than a // carriage return, because most of these runs are read out of a CI log // rather than watched. if (count % 500_000 < targets_mod.targets.len) { try out.print("{d} inputs, {d} failures\n", .{ count, failures }); try out.flush(); } } try out.print("{d} inputs, {d} failures\n", .{ count, failures }); try out.flush(); if (failures != 0) std.process.exit(1); } /// Builds one input by taking a seed and damaging it. /// /// The mutations are the ones that matter for a text format: cut a piece out, /// paste a piece of another seed in, flip a byte, repeat a run. What makes /// this work without coverage feedback is that every seed is already something /// the parser accepts, so a small change lands near the boundary rather than /// in the vast space of inputs that are rejected on the first byte. fn mutate(random: std.Random, seeds: []const []const u8, buffer: []u8) []const u8 { const base = seeds[random.uintLessThan(usize, seeds.len)]; const len = @min(base.len, buffer.len); @memcpy(buffer[0..len], base[0..len]); var out = buffer[0..len]; // Between one and four edits, so that a single flip is common and a // thorough scramble is not. const edits = 1 + random.uintLessThan(usize, 4); for (0..edits) |_| { switch (random.uintLessThan(u8, 6)) { // Flip a byte. 0 => if (out.len != 0) { out[random.uintLessThan(usize, out.len)] = random.int(u8); }, // Replace a byte with one from the format's own alphabet, which is // far more likely to reach a new branch than a random byte. 1 => if (out.len != 0) { const interesting = "<>&/\"'=?![]{}:;*|.,()@$-#%0123456789 \t\n\\"; out[random.uintLessThan(usize, out.len)] = interesting[random.uintLessThan(usize, interesting.len)]; }, // Cut a run out. 2 => if (out.len > 1) { const at = random.uintLessThan(usize, out.len); const take = 1 + random.uintLessThan(usize, @min(16, out.len - at)); std.mem.copyForwards(u8, out[at..], out[at + take ..]); out = out[0 .. out.len - take]; }, // Splice in a piece of another seed. 3 => { const other = seeds[random.uintLessThan(usize, seeds.len)]; if (other.len == 0) continue; const take = 1 + random.uintLessThan(usize, @min(64, other.len)); const from = random.uintLessThan(usize, other.len - take + 1); const at = if (out.len == 0) 0 else random.uintLessThan(usize, out.len); if (out.len + take > buffer.len) continue; std.mem.copyBackwards(u8, buffer[at + take .. out.len + take], out[at..]); @memcpy(buffer[at..][0..take], other[from..][0..take]); out = buffer[0 .. out.len + take]; }, // Repeat a run, which is how nesting gets deep enough to matter. 4 => if (out.len != 0) { const at = random.uintLessThan(usize, out.len); const take = 1 + random.uintLessThan(usize, @min(32, out.len - at)); const times = 1 + random.uintLessThan(usize, 8); var written = out.len; for (0..times) |_| { if (written + take > buffer.len) break; @memcpy(buffer[written..][0..take], out[at..][0..take]); written += take; } out = buffer[0..written]; }, // Truncate. 5 => if (out.len != 0) { out = out[0..random.uintLessThan(usize, out.len)]; }, else => unreachable, } } return out; } const testing = std.testing; test "a mutation stays inside the buffer" { var prng: std.Random.DefaultPrng = .init(1); const random = prng.random(); // Deliberately small, so that every growing mutation runs into the end of // it and has to refuse rather than overrun. var buffer: [64]u8 = undefined; const long: [60]u8 = @splat('x'); const seeds = [_][]const u8{ "", "", "a[1]/b[2]//c", &long }; for (0..20_000) |_| { const out = mutate(random, &seeds, &buffer); try testing.expect(out.len <= buffer.len); } }