// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! A fuzz loop of this project's own. //! //! Zig 0.16.0 cannot build a test executable in fuzz mode at all: its test //! runner reports a failing input by handing what `@errorReturnTrace()` //! returned to `std.debug.writeStackTrace`, and those are two different //! types. The devshell patches that one line so the fuzzer runs, but a //! second defect in the same release leaves the table of program counters //! empty however the modules are built, so `--fuzz=N` ends with "corrupted //! coverage file: pcs_len was zero" and a plain `--fuzz` eventually panics //! in the build runner's coverage thread. Neither is a finding. //! //! So: this loop. What it has instead of coverage feedback is that the //! *targets* know the table. Uniform code points never reach the interesting //! code -- a discontiguous match needs one of nineteen particular contraction //! starters, then a non-starter of strictly lower combining class, then the //! contraction's second half, in that order -- so `tests/fuzz.zig` builds its //! strings out of the table's own material and spends its randomness on which //! contraction and which marks rather than on whether it found one. //! //! Generating input for `Smith` means knowing how it reads bytes, and //! getting that wrong is silent: //! //! * `slice(buf)` reads four bytes as a little-endian `u32` length and //! then that many bytes. A length larger than `buf.len` is not reduced //! into range -- it yields an *empty* slice. //! * `value(T)` reads eight bytes per 64 bits as a little-endian `u64` //! and, when the value falls outside the range asked for, returns that //! range's *minimum* rather than reducing modulo. //! //! Random bytes therefore make every `bool` false, every enum its first tag //! and every bounded integer its lowest value, and a run reports millions of //! iterations having tested almost nothing. `Generator` below writes values //! on purpose for that reason. //! //! Usage: `zig build fuzz -- [iterations] [--target=name] [--seed=N]`. const std = @import("std"); const Smith = std.testing.Smith; const targets = @import("targets"); /// Where a failing input is written, so that it can be fed back in. const findings_dir = "fuzz-findings"; pub fn main(init: std.process.Init.Minimal) !u8 { var gpa_state: std.heap.DebugAllocator(.{}) = .init; defer _ = gpa_state.deinit(); const gpa = gpa_state.allocator(); var threaded: std.Io.Threaded = .init(gpa, .{}); defer threaded.deinit(); const io = threaded.io(); var arena_state: std.heap.ArenaAllocator = .init(gpa); defer arena_state.deinit(); const arena = arena_state.allocator(); var iterations: usize = 100_000; var only: ?[]const u8 = null; var seed: u64 = 0; const args = try init.args.toSlice(arena); for (args[1..]) |arg| { if (std.mem.startsWith(u8, arg, "--target=")) { only = arg["--target=".len..]; } else if (std.mem.startsWith(u8, arg, "--seed=")) { seed = try std.fmt.parseInt(u64, arg["--seed=".len..], 10); } else if (std.mem.startsWith(u8, arg, "--input=")) { // Replay one saved finding and stop. const bytes = try std.Io.Dir.cwd().readFileAlloc(io, arg["--input=".len..], arena, .limited(1 << 20)); return try replay(io, bytes, only); } else { iterations = try std.fmt.parseInt(usize, arg, 10); } } // The library allocates, and a leak is as much a finding as a panic. var target_gpa: std.heap.DebugAllocator(.{}) = .init; targets.backing = target_gpa.allocator(); var stdout_buffer: [4096]u8 = undefined; var stdout = std.Io.File.stdout().writer(io, &stdout_buffer); const out = &stdout.interface; var prng: std.Random.DefaultPrng = .init(seed); var generator: Generator = .{ .random = prng.random() }; var input: std.ArrayList(u8) = .empty; defer input.deinit(gpa); var findings: usize = 0; var ran: usize = 0; for (targets.targets) |target| { if (only) |name| if (!std.mem.eql(u8, name, target.name)) continue; targets.asserted = 0; var i: usize = 0; while (i < iterations) : (i += 1) { input.clearRetainingCapacity(); try generator.generate(gpa, &input); ran += 1; var smith: Smith = .{ .in = input.items }; const outcome = target.run(&smith); // Leaks are checked per input rather than at the end, so that // the input responsible is still in hand when one turns up. const leaks = target_gpa.detectLeaks(); if (outcome) |_| { if (leaks == 0) continue; } else |_| {} findings += 1; const path = try save(io, arena, target.name, findings, input.items); if (outcome) |_| { try out.print( "{s}: leaked {d} allocation(s); input saved to '{s}'\n", .{ target.name, leaks, path }, ); } else |err| { try out.print("{s}: {t}; input saved to '{s}'\n", .{ target.name, err, path }); } try out.flush(); } try out.print("{s}: {d} inputs, {d} reached an assertion\n", .{ target.name, iterations, targets.asserted, }); try out.flush(); } try out.print("{d} inputs, {d} findings\n", .{ ran, findings }); try out.flush(); return if (findings != 0) 1 else 0; } fn replay(io: std.Io, bytes: []const u8, only: ?[]const u8) !u8 { var target_gpa: std.heap.DebugAllocator(.{}) = .init; defer _ = target_gpa.deinit(); targets.backing = target_gpa.allocator(); _ = io; var failures: usize = 0; for (targets.targets) |target| { if (only) |name| if (!std.mem.eql(u8, name, target.name)) continue; var smith: Smith = .{ .in = bytes }; target.run(&smith) catch |err| { std.debug.print("{s}: {t}\n", .{ target.name, err }); failures += 1; }; } return if (failures != 0) 1 else 0; } fn save( io: std.Io, arena: std.mem.Allocator, target: []const u8, n: usize, bytes: []const u8, ) ![]const u8 { var dir = try std.Io.Dir.cwd().createDirPathOpen(io, findings_dir, .{}); defer dir.close(io); const name = try std.fmt.allocPrint(arena, "{s}-{d}.bin", .{ target, n }); try dir.writeFile(io, .{ .sub_path = name, .data = bytes }); return std.fs.path.join(arena, &.{ findings_dir, name }); } /// Writes bytes in the shape `Smith` reads them. /// /// Values are drawn small on purpose. A `Smith` fed uniform random bytes /// answers every question with the bottom of its range, which for this /// library means the empty string, primary strength and non-ignorable /// weighting, over and over. const Generator = struct { random: std.Random, fn generate(g: *Generator, gpa: std.mem.Allocator, out: *std.ArrayList(u8)) !void { // Enough values for the greediest target: three strings of up to // `max_length` code points apiece, plus the settings. const values = 3 * (1 + targets.max_length) + 4; for (0..values) |_| try g.value(gpa, out); } fn value(g: *Generator, gpa: std.mem.Allocator, out: *std.ArrayList(u8)) !void { // Eight little-endian bytes, which is what `value` and its range // variants consume per sixty-four bits. // Both ends of the range matter and for different reasons, so the // buckets overlap on purpose. A value that falls outside what the // target asked for is not reduced into range -- it becomes the // range's minimum -- so a distribution that is too wide answers // every question with the same index, and a run says nothing while // reporting millions of iterations. `--target=…` and the // reached-an-assertion count beside each total are how that gets // noticed. const n: u64 = switch (g.random.weightedIndex(u8, &.{ 3, 4, 3, 4, 2, 1 })) { // Booleans and enum tags. A `bool` is asked for as a range of // 0..1 and `Strength` as 0..4, so anything wider than this // answers "false" and "primary" -- and a run that never turns // `backwards_secondary` on or looks past the first level is // testing a fraction of the library. 0 => g.random.uintLessThan(u64, 5), // Lengths, and indices into the small tables the structured // targets pick from. 1 => g.random.uintLessThan(u64, 16), // Indices into the larger of those tables: one non-starter per // distinct combining class is about fifty-five entries, and // without this bucket every draw for one of those lands out of // range and collapses to the first. 2 => g.random.uintLessThan(u64, 64), // ASCII and Latin-1, where the contractions and the case // differences that matter to most callers live. 3 => g.random.uintLessThan(u64, 0x0250), // Anywhere in the BMP, which is where every contraction in // DUCET is. 4 => g.random.uintLessThan(u64, 0x10000), // Anywhere at all, including the surrogates and the ideographs // that take derived weights. 5 => g.random.uintLessThan(u64, 0x110000), else => unreachable, }; var bytes: [8]u8 = undefined; std.mem.writeInt(u64, &bytes, n, .little); try out.appendSlice(gpa, &bytes); } };