Files
zig/lib/std/zig/TokenSmith.zig
T
Kendall Condon 5d58306162 rework fuzz testing to be smith based
-- On the standard library side:

The `input: []const u8` parameter of functions passed to `testing.fuzz`
has changed to `smith: *testing.Smith`. `Smith` is used to generate
values from libfuzzer or input bytes generated by libfuzzer.

`Smith` contains the following base methods:
* `value` as a generic method for generating any type
* `eos` for generating end-of-stream markers. Provides the additional
  guarantee `true` will eventually by provided.
* `bytes` for filling a byte array.
* `slice` for filling part of a buffer and providing the length.

`Smith.Weight` is used for giving value ranges a higher probability of
being selected. By default, every value has a weight of zero (i.e. they
will not be selected). Weights can only apply to values that fit within
a u64. The above functions have corresponding ones that accept weights.
Additionally, the following functions are provided:
* `baselineWeights` which provides a set of weights containing every
  possible value of a type.
* `eosSimpleWeighted` for unique weights for `true` and `false`
* `valueRangeAtMost` and `valueRangeLessThan` for weighing only a range
  of values.

-- On the libfuzzer and abi side:

--- Uids

These are u32s which are used to classify requested values. This solves
the problem of a mutation causing a new value to be requested and
shifting all future values; for example:

1. An initial input contains the values 1, 2, 3 which are interpreted
as a, b, and c respectively by the test.

2. The 1 is mutated to a 4 which causes the test to request an extra
value interpreted as d. The input is now 4, 2, 3, 5 (new value) which
the test corresponds to a, d, b, c; however, b and c no longer
correspond to their original values.

Uids contain a hash component and type component. The hash component
is currently determined in `Smith` by taking a hash of the calling
`@returnAddress()` or via an argument in the corresponding `WithHash`
functions. The type component is used extensively in libfuzzer with its
hashmaps.

--- Mutations

At the start of a cycle (a run), a random number of values to mutate is
selected with less being exponentially more likely. The indexes of the
values are selected from a selected uid with a logarithmic bias to uids
with more values.

Mutations may change a single values, several consecutive values in a
uid, or several consecutive values in the uid-independent order they
were requested. They may generate random values, mutate from previous
ones, or copy from other values in the same uid from the same input or
spliced from another.

For integers, mutations from previous ones currently only generates
random values. For bytes, mutations from previous mix new random data
and previous bytes with a set number of mutations.

--- Passive Minimization

A different approach has been taken for minimizing inputs: instead of
trying a fixed set of mutations when a fresh input is found, the input
is instead simply added to the corpus and removed when it is no longer
valuable.

The quality of an input is measured based off how many unique pcs it
hit and how many values it needed from the fuzzer. It is tracked which
inputs hold the best qualities for each pc for hitting the minimum and
maximum unique pcs while needing the least values.

Once all an input's qualities have been superseded for the pcs it hit,
it is removed from the corpus.

-- Comparison to byte-based smith

A byte-based smith would be much more inefficient and complex than this
solution. It would be unable to solve the shifting problem that Uids
do. It is unable to provide values from the fuzzer past end-of-stream.
Even with feedback, it would be unable to act on dynamic weights which
have proven essential with the updated tests (e.g. to constrain values
to a range).

-- Test updates

All the standard library tests have been updated to use the new smith
interface. For `Deque`, an ad hoc allocator was written to improve
performance and remove reliance on heap allocation. `TokenSmith` has
been added to aid in testing Ast and help inform decisions on the smith
interface.
2026-02-13 22:12:19 -05:00

278 lines
10 KiB
Zig

//! Generates a list of tokens and a valid corresponding source.
//! Smithed intertoken content is a non-goal of this.
const std = @import("../std.zig");
const Smith = std.testing.Smith;
const Token = std.zig.Token;
const TokenList = std.zig.Ast.TokenList;
const TokenSmith = @This();
source_buf: [4096]u8,
source_len: u32,
tag_buf: [512]Token.Tag,
start_buf: [512]std.zig.Ast.ByteOffset,
tags_len: u16,
fn symbolLenWeights(t: *TokenSmith, min: u32, reserve: u32) [2]Smith.Weight {
@disableInstrumentation();
const space = @as(u32, t.source_buf.len - 1) - t.source_len - reserve;
std.debug.assert(space >= 15);
return .{
.rangeAtMost(u32, min, space, 1),
.rangeAtMost(u32, min, 15, space),
};
}
pub fn gen(smith: *Smith) TokenSmith {
@disableInstrumentation();
var t: TokenSmith = .{
.source_buf = undefined,
.source_len = 0,
.tag_buf = undefined,
.start_buf = undefined,
.tags_len = 0,
};
const max_lexeme_len = comptime max: {
var max: usize = 0;
for (std.meta.tags(Token.Tag)) |tag| {
max = @max(max, if (tag.lexeme()) |s| s.len else 0);
}
break :max max;
} + 1; // + space
const symbol_reserved = 15 + 4; // 4 = doc comment: "///\n"
const max_output_bytes = @max(symbol_reserved, max_lexeme_len);
while (t.tags_len + 2 < t.tag_buf.len - 1 and
t.source_len + max_output_bytes < t.source_buf.len - 1 and
!smith.eosWeightedSimple(7, 1))
{
const tag = smith.value(Token.Tag);
if (tag == .eof) continue;
t.tag_buf[t.tags_len] = tag;
t.start_buf[t.tags_len] = t.source_len;
t.tags_len += 1;
if (tag.lexeme()) |lexeme| {
@memcpy(t.source_buf[t.source_len..][0..lexeme.len], lexeme);
t.source_len += @intCast(lexeme.len);
if (tag == .invalid_periodasterisks) {
t.tag_buf[t.tags_len] = .asterisk;
t.start_buf[t.tags_len] = t.source_len - 1;
t.tags_len += 1;
}
t.source_buf[t.source_len] = '\n';
t.source_len += 1;
} else sw: switch (tag) {
.invalid => {
// While their are multiple ways invalid may be hit,
// it is unlikely the source will be inspected.
t.source_buf[t.source_len] = 0;
t.source_len += 1;
},
.identifier => {
const start = smith.valueWeighted(u8, &.{
.rangeAtMost(u8, 'a', 'z', 1),
.rangeAtMost(u8, '@', 'Z', 1), // @, A...Z
.value(u8, '_', 1),
});
t.source_buf[t.source_len] = start;
t.source_len += 1;
if (start == '@') continue :sw .string_literal;
const len_weights = t.symbolLenWeights(0, 1);
const len = smith.sliceWeighted(
t.source_buf[t.source_len..],
&len_weights,
&.{
.rangeAtMost(u8, 'a', 'z', 1),
.rangeAtMost(u8, 'A', 'Z', 1),
.rangeAtMost(u8, '0', '9', 1),
.value(u8, '_', 1),
},
);
if (Token.getKeyword(t.source_buf[t.source_len - 1 ..][0 .. len + 1]) != null) {
t.source_buf[t.source_len - 1] = '_';
}
t.source_len += len;
t.source_buf[t.source_len] = '\n';
t.source_len += 1;
},
.char_literal, .string_literal => |kind| {
const end: u8 = switch (kind) {
.char_literal => '\'',
.string_literal => '"',
else => unreachable,
};
t.source_buf[t.source_len] = end;
t.source_len += 1;
const len_weights = t.symbolLenWeights(0, 2);
const len = smith.sliceWeighted(
t.source_buf[t.source_len..],
&len_weights,
&.{
.rangeAtMost(u8, 0x20, 0x7e, 1),
.value(u8, '\\', 15),
},
);
var start_escape = false;
for (t.source_buf[t.source_len..][0..len]) |*c| {
if (!start_escape and c.* == end) c.* = ' ';
start_escape = !start_escape and c.* == '\\';
}
if (start_escape) t.source_buf[t.source_len..][len - 1] = ' ';
t.source_len += len;
t.source_buf[t.source_len] = end;
t.source_buf[t.source_len + 1] = '\n';
t.source_len += 2;
},
.multiline_string_literal_line => {
t.source_buf[t.source_len..][0..2].* = @splat('\\');
t.source_len += 2;
const len_weights = t.symbolLenWeights(0, 1);
t.source_len += smith.sliceWeighted(
t.source_buf[t.source_len..],
&len_weights,
&.{.rangeAtMost(u8, 0x20, 0x7e, 1)},
);
t.source_buf[t.source_len] = '\n';
t.source_len += 1;
},
.number_literal => {
t.source_buf[t.source_len] = smith.valueRangeAtMost(u8, '0', '9');
t.source_len += 1;
const len_weights = t.symbolLenWeights(0, 1);
const len = smith.sliceWeighted(
t.source_buf[t.source_len..],
&len_weights,
&.{
.rangeAtMost(u8, '0', '9', 8),
.rangeAtMost(u8, 'a', 'z', 1),
.rangeAtMost(u8, 'A', 'Z', 1),
.value(u8, '+', 1),
.rangeAtMost(u8, '-', '.', 1), // -, .
},
);
var no_period = false;
var not_exponent = true;
for (t.source_buf[t.source_len..][0..len], 0..) |*c, i| {
const invalid_period = no_period and c.* == '.' or i + 1 == len;
const is_exponent = c.* == '-' or c.* == '+';
const invalid_exponent = not_exponent and is_exponent;
const valid_exponent = !not_exponent and is_exponent;
if (invalid_period or invalid_exponent) c.* = '0';
no_period |= c.* == '.' or valid_exponent;
not_exponent = switch (c.*) {
'e', 'E', 'p', 'P' => false,
else => true,
};
}
t.source_len += len;
t.source_buf[t.source_len] = '\n';
t.source_len += 1;
},
.builtin => {
t.source_buf[t.source_len] = '@';
t.source_len += 1;
const len_weights = t.symbolLenWeights(1, 1);
const len = smith.sliceWeighted(
t.source_buf[t.source_len..],
&len_weights,
&.{
.rangeAtMost(u8, 'a', 'z', 1),
.rangeAtMost(u8, 'A', 'Z', 1),
.rangeAtMost(u8, '0', '9', 1),
.value(u8, '_', 1),
},
);
if (t.source_buf[t.source_len] >= '0' and t.source_buf[t.source_len] <= '9') {
t.source_buf[t.source_len] = '_';
}
t.source_len += len;
t.source_buf[t.source_len] = '\n';
t.source_len += 1;
},
.doc_comment, .container_doc_comment => |kind| {
t.source_buf[t.source_len..][0..2].* = "//".*;
t.source_buf[t.source_len..][2] = switch (kind) {
.doc_comment => '/',
.container_doc_comment => '!',
else => unreachable,
};
t.source_len += 3;
const len_weights = t.symbolLenWeights(0, 1);
const len = smith.sliceWeighted(
t.source_buf[t.source_len..],
&len_weights,
&.{
.rangeAtMost(u8, 0x20, 0x7e, 1),
.rangeAtMost(u8, 0x80, 0xff, 1),
},
);
if (kind == .doc_comment and len != 0 and t.source_buf[t.source_len] == '/') {
t.source_buf[t.source_len] = ' ';
}
t.source_len += len;
t.source_buf[t.source_len] = '\n';
t.source_len += 1;
},
else => unreachable,
}
}
t.tag_buf[t.tags_len] = .eof;
t.start_buf[t.tags_len] = t.source_len;
t.tags_len += 1;
t.source_buf[t.source_len] = 0;
return t;
}
pub fn source(t: *TokenSmith) [:0]u8 {
return t.source_buf[0..t.source_len :0];
}
/// The Slice is not backed by a MultiArrayList, so calling deinit or toMultiArrayList is illegal.
pub fn list(t: *TokenSmith) TokenList.Slice {
var slice: TokenList.Slice = .{
.ptrs = undefined,
.len = t.tags_len,
.capacity = t.tags_len,
};
comptime std.debug.assert(slice.ptrs.len == 2);
slice.ptrs[@intFromEnum(TokenList.Field.tag)] = @ptrCast(&t.tag_buf);
slice.ptrs[@intFromEnum(TokenList.Field.start)] = @ptrCast(&t.start_buf);
return slice;
}
test TokenSmith {
try std.testing.fuzz({}, checkSource, .{});
}
fn checkSource(_: void, smith: *Smith) !void {
var t: TokenSmith = .gen(smith);
try std.testing.expectEqual(Token.Tag.eof, t.tag_buf[t.tags_len - 1]);
var tokenizer: std.zig.Tokenizer = .init(t.source());
for (t.tag_buf[0..t.tags_len], t.start_buf[0..t.tags_len]) |tag, start| {
const tok = tokenizer.next();
try std.testing.expectEqual(tok.tag, tag);
try std.testing.expectEqual(tok.loc.start, start);
if (tag == .invalid) break;
}
}