zig

fork of https://codeberg.org/ziglang/zig
Log | Files | Refs | README | LICENSE

commit 5058beb1793aafaaf63cb5b9ef4c751fba08a62c (tree)
parent 1c35e73b614398529782f8c027366c6d8d51ac4b
Author: Andrew Kelley <andrew@ziglang.org>
Date:   Mon, 22 Jul 2024 16:45:19 -0700

implement std.testing.fuzzInput

for the -fno-fuzz case. The other case will take more work in libfuzzer.

Diffstat:
Mlib/std/io/test.zig | 2+-
Mlib/std/testing.zig | 30++++++++++++++++++++++++++++++
2 files changed, 31 insertions(+), 1 deletion(-)

diff --git a/lib/std/io/test.zig b/lib/std/io/test.zig @@ -16,7 +16,7 @@ test "write a file, read it, then delete it" { defer tmp.cleanup(); var data: [1024]u8 = undefined; - var prng = DefaultPrng.init(1234); + var prng = DefaultPrng.init(std.testing.random_seed); const random = prng.random(); random.bytes(data[0..]); const tmp_file_name = "temp_test_file.txt"; diff --git a/lib/std/testing.zig b/lib/std/testing.zig @@ -1136,3 +1136,33 @@ pub fn refAllDeclsRecursive(comptime T: type) void { _ = &@field(T, decl.name); } } + +const FuzzerSlice = extern struct { + ptr: [*]const u8, + len: usize, + + fn toSlice(s: FuzzerSlice) []const u8 { + return s.ptr[0..s.len]; + } +}; + +extern fn fuzzer_next() FuzzerSlice; + +pub const FuzzInputOptions = struct { + corpus: []const []const u8 = &.{}, +}; + +pub fn fuzzInput(options: FuzzInputOptions) []const u8 { + @disableInstrumentation(); + if (builtin.fuzz) { + return fuzzer_next().toSlice(); + } else { + if (options.corpus.len == 0) { + return ""; + } else { + var prng = std.Random.DefaultPrng.init(std.testing.random_seed); + const random = prng.random(); + return options.corpus[random.uintLessThan(usize, options.corpus.len)]; + } + } +}