-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathfuzz.zig
372 lines (323 loc) · 12.5 KB
/
fuzz.zig
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
const builtin = @import("builtin");
const pkmn = @import("pkmn");
const std = @import("std");
pub const pkmn_options = pkmn.Options{ .internal = true };
const Frame = struct {
log: []u8 = &.{},
state: []u8,
result: pkmn.Result = pkmn.Result.Default,
c1: pkmn.Choice = .{},
c2: pkmn.Choice = .{},
extra: []u8,
};
var gen: u8 = 0;
var last: ?u64 = null;
var initial: []u8 = &.{};
var buf: ?std.ArrayList(u8) = null;
var frames: ?std.ArrayList(Frame) = null;
const transitions = true; // DEBUG
const showdown = pkmn.options.showdown;
const chance = pkmn.options.chance;
const endian = builtin.cpu.arch.endian();
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer std.debug.assert(gpa.deinit() == .ok);
const allocator = gpa.allocator();
const args = try std.process.argsAlloc(allocator);
defer std.process.argsFree(allocator, args);
if (args.len != 1 and (args.len < 3 or args.len > 5)) usageAndExit(args[0]);
if (args.len > 1) {
gen = std.fmt.parseUnsigned(u8, args[1], 10) catch
errorAndExit("gen", args[1], args[0]);
if (gen < 1 or gen > 9) errorAndExit("gen", args[1], args[0]);
const end = args[2].len - 1;
const mod: usize = switch (args[2][end]) {
's' => 1,
'm' => std.time.s_per_min,
'h' => std.time.s_per_hour,
'd' => std.time.s_per_day,
else => errorAndExit("duration", args[2], args[0]),
};
const duration = mod * (std.fmt.parseUnsigned(usize, args[2][0..end], 10) catch
errorAndExit("duration", args[2], args[0])) * std.time.ns_per_s;
const seed = if (args.len > 3) std.fmt.parseUnsigned(u64, args[3], 0) catch
errorAndExit("seed", args[3], args[0]) else seed: {
const Random = if (@hasDecl(std, "Random")) std.Random else std.rand;
var secret: [Random.DefaultCsprng.secret_seed_length]u8 = undefined;
std.crypto.random.bytes(&secret);
var csprng = Random.DefaultCsprng.init(secret);
const random = csprng.random();
break :seed random.int(usize);
};
try fuzz(allocator, seed, duration);
} else {
const stdin = std.io.getStdIn();
var reader = std.io.bufferedReader(stdin.reader());
var r = reader.reader();
if (try r.readByte() != @intFromBool(showdown)) {
const err = std.io.getStdErr().writer();
err.print("Cannot process frame from -Dshowdown={}\n", .{!showdown}) catch {};
usageAndExit(args[0]);
}
gen = try r.readByte();
if (gen < 1 or gen > 9) errorAndExit("gen", gen, args[0]);
const size = try r.readInt(i16, endian);
if (size != -1 and size != 0) errorAndExit("log size", size, args[0]);
_ = try r.readInt(i32, endian);
_ = try switch (gen) {
1 => r.readStruct(pkmn.gen1.Battle(pkmn.gen1.PRNG)),
else => unreachable,
};
if (size != 0) _ = try r.readByte();
const durations = try switch (gen) {
1 => r.readStruct(pkmn.gen1.chance.Durations),
else => unreachable,
};
var battle = try switch (gen) {
1 => r.readStruct(pkmn.gen1.Battle(pkmn.gen1.PRNG)),
else => unreachable,
};
_ = try r.readStruct(pkmn.Result);
const c1 = try r.readStruct(pkmn.Choice);
const c2 = try r.readStruct(pkmn.Choice);
switch (gen) {
1 => {
var chance_ = if (chance) pkmn.gen1.Chance(pkmn.Rational(u128)){
.probability = .{},
.durations = durations,
} else pkmn.gen1.chance.NULL;
const options = pkmn.battle.options(
pkmn.protocol.NULL,
&chance_,
pkmn.gen1.calc.NULL,
);
const result = update(&battle, c1, c2, &options, allocator);
std.debug.assert(!showdown or result.type != .Error);
},
else => unreachable,
}
}
}
pub fn fuzz(allocator: std.mem.Allocator, seed: u64, duration: usize) !void {
std.debug.assert(gen >= 1 and gen <= 9);
const save = pkmn.options.log and builtin.mode == .Debug;
var random = pkmn.PSRNG.init(seed);
var elapsed = try std.time.Timer.start();
while (elapsed.read() < duration) {
last = random.src.seed;
const cleric = showdown;
var battle = switch (gen) {
1 => pkmn.gen1.helpers.Battle.random(&random, .{
.cleric = cleric,
.block = false,
.durations = true,
}),
else => unreachable,
};
const max = switch (gen) {
1 => pkmn.gen1.MAX_LOGS,
else => unreachable,
};
var log: ?pkmn.protocol.Log(std.ArrayList(u8).Writer) = null;
if (save) {
if (frames != null) deinit(allocator);
initial = try allocator.dupe(u8, std.mem.toBytes(battle)[0..]);
frames = std.ArrayList(Frame).init(allocator);
buf = std.ArrayList(u8).init(allocator);
log = pkmn.protocol.Log(std.ArrayList(u8).Writer){ .writer = buf.?.writer() };
}
std.debug.assert(!showdown or battle.side(.P1).get(1).hp > 0);
std.debug.assert(!showdown or battle.side(.P2).get(1).hp > 0);
switch (gen) {
1 => {
var chance_ = if (chance) chance: {
var durations = pkmn.gen1.chance.Durations{};
// Pokémon which start the battle sleeping must seen prior .started or
// .continuing observations which would have set their counter >= 1
if (!cleric) {
inline for (.{ .P1, .P2 }) |player| {
var d = durations.get(player);
for (battle.side(player).pokemon, 0..) |p, i| {
if (pkmn.gen1.Status.is(p.status, .SLP)) {
d.sleeps = pkmn.Array(6, u3).set(d.sleeps, i, 1);
}
}
}
}
break :chance pkmn.gen1.Chance(pkmn.Rational(u128)){
.probability = .{},
.durations = durations,
};
} else pkmn.gen1.chance.NULL;
const options = pkmn.battle.options(
if (save) log.? else pkmn.protocol.NULL,
&chance_,
pkmn.gen1.calc.NULL,
);
try run(&battle, &random, save, max, allocator, options);
},
else => unreachable,
}
}
if (frames != null) deinit(allocator);
}
fn run(
battle: anytype,
random: *pkmn.PSRNG,
save: bool,
max: usize,
allocator: std.mem.Allocator,
options: anytype,
) !void {
var choices: [pkmn.CHOICES_SIZE]pkmn.Choice = undefined;
var c1 = pkmn.Choice{};
var c2 = pkmn.Choice{};
var p1 = pkmn.PSRNG.init(random.newSeed());
var p2 = pkmn.PSRNG.init(random.newSeed());
var result = update(battle, c1, c2, &options, allocator);
while (result.type == .None) : (result = update(battle, c1, c2, &options, allocator)) {
var n = battle.choices(.P1, result.p1, &choices);
if (n == 0) break;
c1 = choices[p1.range(u8, 0, n)];
n = battle.choices(.P2, result.p2, &choices);
if (n == 0) break;
c2 = choices[p2.range(u8, 0, n)];
if (save) {
std.debug.assert(buf.?.items.len <= max);
try frames.?.append(.{
.result = result,
.c1 = c1,
.c2 = c2,
.state = try allocator.dupe(u8, std.mem.toBytes(battle.*)[0..]),
.log = try buf.?.toOwnedSlice(),
.extra = if (chance)
try allocator.dupe(u8, std.mem.toBytes(options.chance.durations)[0..])
else
&.{},
});
}
}
std.debug.assert(!showdown or result.type != .Error);
}
pub fn update(
battle: anytype,
c1: pkmn.Choice,
c2: pkmn.Choice,
options: anytype,
allocator: std.mem.Allocator,
) pkmn.Result {
if (!chance) return battle.update(c1, c2, options) catch unreachable;
const writer = std.io.null_writer;
// const writer = std.io.getStdErr().writer();
return switch (gen) {
1 => pkmn.gen1.calc.update(battle, c1, c2, options, allocator, writer, transitions),
else => unreachable,
} catch unreachable;
}
fn errorAndExit(msg: []const u8, arg: anytype, cmd: []const u8) noreturn {
const err = std.io.getStdErr().writer();
err.print("Invalid {s}: {any}\n", .{ msg, arg }) catch {};
usageAndExit(cmd);
}
fn usageAndExit(cmd: []const u8) noreturn {
const err = std.io.getStdErr().writer();
err.print("Usage: {s} <GEN> <DURATION> <SEED?>\n", .{cmd}) catch {};
std.process.exit(1);
}
fn deinit(allocator: std.mem.Allocator) void {
std.debug.assert(initial.len > 0);
allocator.free(initial);
for (frames.?.items) |frame| {
allocator.free(frame.state);
allocator.free(frame.log);
allocator.free(frame.extra);
}
frames.?.deinit();
std.debug.assert(buf != null);
buf.?.deinit();
}
fn dump(seed: u64) !void {
const out = std.io.getStdOut();
var bw = std.io.bufferedWriter(out.writer());
var w = bw.writer();
if (out.isTty() or builtin.mode != .Debug) {
try w.print("0x{X}\n", .{seed});
} else {
try w.writeInt(u64, seed, endian);
try display(&w, false);
}
try bw.flush();
// Write the last state information to the logs/ directory if it
// exists so that it can easily be turned into a regression testcase
var n: [1024]u8 = undefined;
const ext = if (showdown) "showdown" else "pkmn";
const name = try std.fmt.bufPrint(&n, "logs/0x{X}.{s}.bin", .{ seed, ext });
const dir = std.fs.cwd();
const file = dir.createFile(name, .{}) catch return;
defer file.close();
try display(&file.writer(), true);
var p: [1024]u8 = undefined;
const path = try dir.realpath(name, &p);
dir.deleteFile("logs/dump.bin") catch {};
dir.symLink(path, "logs/dump.bin", .{}) catch return;
}
fn display(w: anytype, final: bool) !void {
try w.writeByte(@intFromBool(showdown));
try w.writeByte(gen);
try w.writeInt(i16, -1, endian);
try w.writeInt(i32, if (final) switch (gen) {
1 => @as(i32, @intCast(@sizeOf(pkmn.gen1.chance.Durations))),
else => unreachable,
} else @as(i32, 0), endian);
try w.writeAll(initial);
if (frames) |fs| {
if (final) {
if (fs.items.len == 0) return;
const f = fs.items[fs.items.len - 1];
try w.writeByte(0);
try w.writeAll(f.extra);
try w.writeAll(f.state);
try w.writeStruct(f.result);
try w.writeStruct(f.c1);
try w.writeStruct(f.c2);
} else {
for (fs.items) |f| {
try w.writeAll(f.log);
try w.writeAll(f.state);
try w.writeStruct(f.result);
try w.writeStruct(f.c1);
try w.writeStruct(f.c2);
}
}
}
if (buf) |b| try w.writeAll(b.items);
}
pub const panic = Panic.call;
pub const Panic = struct {
pub fn call(msg: []const u8, ert: ?*std.builtin.StackTrace, ra: ?usize) noreturn {
if (last) |seed| dump(seed) catch unreachable;
if (@hasDecl(std.builtin, "Panic")) {
std.debug.FormattedPanic.call(msg, ert, ra);
} else {
std.builtin.default_panic(msg, ert, ra);
}
}
pub fn sentinelMismatch(expected: anytype, _: @TypeOf(expected)) noreturn {
call("sentinel mismatch", null, null);
}
pub fn unwrapError(_: ?*std.builtin.StackTrace, _: anyerror) noreturn {
call("attempt to unwrap error", null, null);
}
pub fn outOfBounds(_: usize, _: usize) noreturn {
call("index out of bounds", null, null);
}
pub fn startGreaterThanEnd(_: usize, _: usize) noreturn {
call("start index is larger than end index", null, null);
}
pub fn inactiveUnionField(active: anytype, _: @TypeOf(active)) noreturn {
call("access of inactive union field", null, null);
}
pub const messages = if (@hasDecl(std.builtin, "Panic"))
std.debug.FormattedPanic.messages
else {};
};