// SPDX-FileCopyrightText: © 2025 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! A fuzzing loop that does not need the compiler's fuzzer. //! //! Zig 0.16.0 cannot build a test executable in fuzz mode at all //! without the one line patch this project's flake applies, and even //! with it nothing populates the table of program counters, so a //! bounded `--fuzz=N` run ends with "corrupted coverage file: pcs_len //! was zero" and an unbounded one panics in the build runner's coverage //! thread. Neither is a finding. //! //! So the loop is here instead. What it has in place of coverage //! feedback is a corpus of inputs shaped like real reports and a //! generator that knows how `Smith` reads its input, which between them //! are enough to reach the interesting paths. //! //! Usage: `zig build fuzz -- [--runs N] [--seed N] [--target NAME]` const std = @import("std"); const fuzz = @import("fuzz"); const Smith = std.testing.Smith; /// The library logs a warning for every report it refuses, which is /// most of them here and is the point rather than a problem. Quieten it /// so that what the run has to say stays readable. pub const std_options: std.Options = .{ .log_level = .err }; /// The input currently being run, so that the panic handler can say /// what it was. var current_input: []const u8 = &.{}; var current_target: []const u8 = "none"; /// Most of what a fuzzer finds in Zig is a panic -- an index out of /// bounds, an overflow, an unreachable -- and a panic ends the process /// rather than coming back as an error the loop could report. Without /// this, a finding is a stack trace and no way to know which input /// produced it, which is most of the way to useless. pub const panic = std.debug.FullPanic(fuzzPanic); fn fuzzPanic(msg: []const u8, first_trace_addr: ?usize) noreturn { { var buf: [1024]u8 = undefined; const locked = std.debug.lockStderr(&buf); defer std.debug.unlockStderr(); const w = &locked.file_writer.interface; w.print("\nFAILING INPUT\n target: {s}\n bytes ({d}): ", .{ current_target, current_input.len, }) catch {}; for (current_input) |b| w.print("{x:0>2}", .{b}) catch {}; w.print("\n rerun with: zig build fuzz -- --target {s} --seed \n\n", .{ current_target, }) catch {}; w.flush() catch {}; } std.debug.defaultPanic(msg, first_trace_addr); } pub fn main(init: std.process.Init) !void { const io = init.io; var gpa_state: std.heap.DebugAllocator(.{}) = .init; defer _ = gpa_state.deinit(); const gpa = gpa_state.allocator(); var runs: usize = 10_000; var seed: u64 = 0; var only: ?[]const u8 = null; { var args: std.process.Args.Iterator = .init(init.minimal.args); defer args.deinit(); _ = args.skip(); while (args.next()) |arg| { if (std.mem.eql(u8, arg, "--runs")) { runs = try std.fmt.parseInt(usize, args.next() orelse return error.MissingValue, 10); } else if (std.mem.eql(u8, arg, "--seed")) { seed = try std.fmt.parseInt(u64, args.next() orelse return error.MissingValue, 10); } else if (std.mem.eql(u8, arg, "--target")) { only = args.next() orelse return error.MissingValue; } else { std.debug.print("unknown argument: {s}\n", .{arg}); return error.BadUsage; } } } if (seed == 0) { // A nanosecond count is 96 bits wide; the low 64 of it are as // good a seed as any. const ns: u96 = @bitCast(std.Io.Timestamp.now(io, .real).nanoseconds); seed = @truncate(ns); } var buf: [4096]u8 = undefined; var stderr = std.Io.File.stderr().writer(io, &buf); const out = &stderr.interface; try out.print("seed {d}, {d} runs per target\n", .{ seed, runs }); var prng: std.Random.DefaultPrng = .init(seed); const random = prng.random(); var failures: usize = 0; for (fuzz.targets) |target| { if (only) |name| { if (!std.mem.eql(u8, name, target.name)) continue; } var input: std.ArrayList(u8) = .empty; defer input.deinit(gpa); fuzz.accepted = 0; var run: usize = 0; while (run < runs) : (run += 1) { input.clearRetainingCapacity(); try generate(gpa, &input, target, random, run); // A fresh allocator per input, so that a leak is attributed // to the input that caused it rather than to whichever one // happened to run last. var case_state: std.heap.DebugAllocator(.{}) = .init; // Every fourth input is run with an allocation made to // fail. `checkAllAllocationFailures` already walks every // allocation of a handful of fixed inputs; this reaches the // error paths of inputs nobody thought to write down, which // is where an `errdefer` that was never needed on the happy // path goes unnoticed. The leak check underneath is the // same one, so a failed unwind still shows up as a leak. const inject = run % 4 == 3; var failing: std.testing.FailingAllocator = .init(case_state.allocator(), .{ .fail_index = if (inject) random.uintLessThan(usize, 24) else std.math.maxInt(usize), }); fuzz.backing = failing.allocator(); current_target = target.name; current_input = input.items; var smith: Smith = .{ .in = input.items }; const result = target.run(&smith); const leaked = case_state.deinit() == .leak; if (result) |_| { if (!leaked) continue; try out.print("\nLEAK in {s}\n", .{target.name}); } else |err| if (leaked) { // The error is not the finding here; failing to unwind // cleanly is. Say so, or the report blames whichever // error happened to be on the way out. try out.print("\nLEAK in {s}, unwinding {t}\n", .{ target.name, err }); } else if (err == error.OutOfMemory and inject) { // Running out of memory is the point when a failure was // induced, and unwinding left nothing behind. continue; } else { try out.print("\nFAILURE in {s}: {t}\n", .{ target.name, err }); } failures += 1; try out.print(" input ({d} bytes): ", .{input.items.len}); for (input.items) |b| try out.print("{x:0>2}", .{b}); try out.print("\n", .{}); try out.flush(); } // The acceptance count is what says the generator is feeding // this target real input rather than the empty string. try out.print("{s: <18} {d: >7} runs {d: >7} accepted\n", .{ target.name, runs, fuzz.accepted, }); if (runs > 0 and fuzz.accepted == 0) { try out.print(" ^ nothing got through: the generator and this target disagree\n", .{}); failures += 1; } try out.flush(); } try out.print("\n{d} failure(s)\n", .{failures}); try out.flush(); if (failures > 0) return error.FuzzFailure; } /// Build one input for `target`. /// /// This has to match how `Smith` reads, and getting it wrong is silent: /// a run reports millions of iterations and has been handing the target /// nothing at all. /// /// - `value` and the range readers take **eight** bytes per 64 bits, /// little-endian, and a value outside the range asked for comes /// back as that range's *minimum* rather than reduced into it. So /// random bytes make every bool false and every selector zero, and /// the leading values are written small on purpose. /// - `slice` takes **four** bytes of little-endian length and then /// that many bytes. A length longer than the target's buffer yields /// an *empty* slice, so the length is capped at `max_report`. fn generate( gpa: std.mem.Allocator, out: *std.ArrayList(u8), target: fuzz.Target, random: std.Random, run: usize, ) !void { var i: usize = 0; while (i < target.leading_values) : (i += 1) { // Small enough to land inside whatever range the target asked // for, most of the time. const v: u64 = random.uintLessThan(u64, 512); var bytes: [8]u8 = undefined; std.mem.writeInt(u64, &bytes, v, .little); try out.appendSlice(gpa, &bytes); } if (!target.takes_payload) return; // Every few runs, hand over a corpus entry unchanged, so that the // known-good shapes keep being exercised as well as mutations of // them. const seed_input = fuzz.corpus[run % fuzz.corpus.len]; var payload: [fuzz.max_report]u8 = undefined; var len: usize = undefined; if (run % 4 == 0) { len = @min(seed_input.len, payload.len); @memcpy(payload[0..len], seed_input[0..len]); } else { // A mutation of a corpus entry: its length jittered, its bytes // copied and then some of them replaced. const base = @min(seed_input.len, payload.len); const jitter = random.intRangeAtMost(i32, -4, 8); const wanted = @as(i64, @intCast(base)) + jitter; len = @intCast(std.math.clamp(wanted, 0, @as(i64, payload.len))); @memset(payload[0..len], 0); @memcpy(payload[0..@min(base, len)], seed_input[0..@min(base, len)]); const edits = random.uintLessThan(usize, 5) + 1; var e: usize = 0; while (e < edits and len > 0) : (e += 1) { payload[random.uintLessThan(usize, len)] = random.int(u8); } } var length: [4]u8 = undefined; std.mem.writeInt(u32, &length, @intCast(len), .little); try out.appendSlice(gpa, &length); try out.appendSlice(gpa, payload[0..len]); } test { // Nothing here runs under the test runner, but it still has to // compile: this file is the only thing that builds it. std.testing.refAllDecls(@This()); }