Commit 5058beb179

Andrew Kelley <andrew@ziglang.org>
2024-07-23 01:45:19
implement std.testing.fuzzInput
for the -fno-fuzz case. The other case will take more work in libfuzzer.
1 parent 1c35e73
Changed files (2)
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";
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)];
+        }
+    }
+}