summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorGabriel Schneider <[email protected]>2026-11-23 15:41:12 -0300
committerGabriel Schneider <[email protected]>2026-11-23 16:28:34 -0300
commit18933ab34ea07f2cf755aa4e8d9bdb4dc25a67a6 (patch)
tree9c2831a2ee8fef25364283151ca6ac312dc86ecf
parentf34d3a74cc4a6b735c98ce98cef0df42bd065e67 (diff)
downloadpardes-18933ab34ea07f2cf755aa4e8d9bdb4dc25a67a6.tar.gz
pardes-18933ab34ea07f2cf755aa4e8d9bdb4dc25a67a6.zip
the boundaries fuzzes and tests, failing first: bytes from outside (garbage and mutated-valid) into the reader that takes them, a fixed seed list and seconds, an error never a panic, memory held by a capped allocator (core/fuzz.zig, in core-test): 9P frames through the engine pardes runs (`runtime.ninep.Server(pardes.ctlfs, runtime.ninep.editor)`), framed as the engine frames them so that no walk reaches `os` (the host files) or `n`, the core effects dropped, a frame drawn after each push (16 seeds x 400 frames, deep: 607 writes, 604 reads in one run); a client inputs into the session reader (`replica.parseInput`, every tag decodeClient) applied with `update` and drawn; a session units recorded by an `Authority`, cut, flipped and grown, replayed by a `Replica` (the client road); a session byte dump and image, damaged, through `dump.check` and `dump.load`; and the sites the note found by reading, each a test: a +Search pane rows style past the syntax kinds (`m 1 1 0 0 0 0 0 3:0+3=7 a.txt`), a Grep row of a file named `a:5000000000:b` (core/Query.zig), a top-down BMP (its height negative, addons/image/image.zig, addon-test), an X10 mouse report with a control byte and an SGR one with button 192 (dev/tui/tui.zig, shell-test); on main (f34d3a74cc4a), Debug, each alone: the rows test `expected .err, found .ok` (drawn: `invalid enum value` at core/File.zig:2079), the session side `integer overflow` at core/draw.zig:282 (joinNotice, a prompt caret on a band of 65535 glyphs: Layer.capacity under a client row metrics), the client side `invalid enum value` at core/tape.zig:458 (`peek`), the Grep row `integer does not fit` at core/Query.zig:1267, the BMP `integer does not fit` (image.zig `info`), the X10 report `integer overflow` at vaxis Parser.zig:792; the 9P fuzz and the dump fuzz pass on main (no panic reached)
Co-Authored-By: Claude Opus <[email protected]> Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T
-rw-r--r--addons/image/image.zig16
-rw-r--r--core/Query.zig11
-rw-r--r--core/fuzz.zig773
-rw-r--r--core/root.zig2
-rw-r--r--dev/tui/tui.zig9
5 files changed, 811 insertions, 0 deletions
diff --git a/addons/image/image.zig b/addons/image/image.zig
index f2303433..48135458 100644
--- a/addons/image/image.zig
+++ b/addons/image/image.zig
@@ -137,3 +137,19 @@ test "a job decodes a picture to its size and pixels, and one past max_dim is sc
try std.testing.expectEqual(8 + 1280 * 4, wide.len);
try std.testing.expect(Image.jobRun("not a picture", arena.allocator()) == null);
}
+
+test "a top-down BMP (its height negative in its header) opens at its size, as any picture" {
+ var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
+ defer arena.deinit();
+ // 2x2, 24 bits, biHeight -2: rows top first, each 6 bytes and 2 of padding.
+ const bmp = "BM" ++ "\x46\x00\x00\x00" ++ "\x00\x00\x00\x00" ++ "\x36\x00\x00\x00" ++
+ "\x28\x00\x00\x00" ++ "\x02\x00\x00\x00" ++ "\xfe\xff\xff\xff" ++ "\x01\x00" ++ "\x18\x00" ++
+ "\x00\x00\x00\x00" ++ "\x10\x00\x00\x00" ++ "\x13\x0b\x00\x00" ++ "\x13\x0b\x00\x00" ++ "\x00\x00\x00\x00" ++ "\x00\x00\x00\x00" ++
+ "\x00\x00\xff\x00\xff\x00\x00\x00" ++ "\xff\x00\x00\xff\xff\xff\x00\x00";
+ try std.testing.expectEqual([2]u32{ 2, 2 }, info(bmp).?);
+ const got = Image.jobRun(bmp, arena.allocator()).?;
+ try std.testing.expectEqual(8 + 2 * 2 * 4, got.len);
+ try std.testing.expectEqual(2, std.mem.readInt(u32, got[4..8], .little));
+ // Its first pixel is the top row's first: red (BGR 00 00 ff).
+ try std.testing.expectEqualSlices(u8, &.{ 0xff, 0, 0, 0xff }, got[8..12]);
+}
diff --git a/core/Query.zig b/core/Query.zig
index 2ffcfd3b..fe25d5fd 100644
--- a/core/Query.zig
+++ b/core/Query.zig
@@ -2746,3 +2746,14 @@ test "a query row's address reaches every way a look arrives: an empty look writ
try std.testing.expectEqual(tree.Status.ok, @import("ninep/harness.zig").wr(p, tree.Node.of(qp.serial, .look), line).reply.status);
try std.testing.expectEqual(@as(i32, 3), a.body.cur_row);
}
+
+test "Grep: a row whose numbers a Found cannot hold (a column past u32) is passed over, never cast" {
+ const gpa = std.testing.allocator;
+ const p = try @import("ninep/harness.zig").withFile(gpa, "x\n");
+ defer p.deinit();
+ var q: Query = .{ .owner = 0 };
+ defer q.deinit(p.gpa);
+ take(p, &q, .grep, "a:5000000000:b:3:1-4 hit\nok.txt:2:3-5 hit\nb:7:4294967297 hit\n");
+ // Taken or passed over, each: never cast (main: Query.zig:1267).
+ try std.testing.expect(q.found.items.len <= 3);
+}
diff --git a/core/fuzz.zig b/core/fuzz.zig
new file mode 100644
index 00000000..f324a48e
--- /dev/null
+++ b/core/fuzz.zig
@@ -0,0 +1,773 @@
+//! The boundaries' fuzzes: bytes the core did not make, garbage and
+//! mutated-valid, into the reader that takes them, on a fixed list of
+//! seeds and a bound of seconds. Each holds one rule: an error, never a
+//! panic, never a hang, memory bounded (`Capped`, and the testing
+//! allocator's leak check at the end). A seed that fails is a run of its
+//! own again: `-Dtest-filter` and the seed alone in `seeds`.
+const std = @import("std");
+const pardes = @import("root.zig");
+const ninep = @import("runtime").ninep;
+const th = @import("ninep/harness.zig");
+const Pardes = pardes.Pardes;
+const Random = std.Random;
+const testing = std.testing;
+
+const seeds = [_]u64{ 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597 };
+
+/// An allocator over `child` that refuses one allocation past `one` and a
+/// total past `all`, and counts what it refused: a reader that sizes an
+/// allocation by a count the outside gave shows here, not as a machine
+/// out of memory.
+const Capped = struct {
+ child: std.mem.Allocator,
+ one: usize,
+ all: usize,
+ live: usize = 0,
+ refused: usize = 0,
+
+ fn allocator(c: *Capped) std.mem.Allocator {
+ return .{ .ptr = c, .vtable = &.{ .alloc = alloc, .resize = resize, .remap = remap, .free = free } };
+ }
+ fn room(c: *Capped, more: usize) bool {
+ if (more <= c.one and c.live + more <= c.all) return true;
+ c.refused += 1;
+ return false;
+ }
+ fn alloc(ctx: *anyopaque, len: usize, a: std.mem.Alignment, ret: usize) ?[*]u8 {
+ const c: *Capped = @ptrCast(@alignCast(ctx));
+ if (!c.room(len)) return null;
+ const got = c.child.rawAlloc(len, a, ret) orelse return null;
+ c.live += len;
+ return got;
+ }
+ fn resize(ctx: *anyopaque, m: []u8, a: std.mem.Alignment, len: usize, ret: usize) bool {
+ const c: *Capped = @ptrCast(@alignCast(ctx));
+ if (len > m.len and !c.room(len - m.len)) return false;
+ if (!c.child.rawResize(m, a, len, ret)) return false;
+ c.live = c.live - m.len + len;
+ return true;
+ }
+ fn remap(ctx: *anyopaque, m: []u8, a: std.mem.Alignment, len: usize, ret: usize) ?[*]u8 {
+ const c: *Capped = @ptrCast(@alignCast(ctx));
+ if (len > m.len and !c.room(len - m.len)) return null;
+ const got = c.child.rawRemap(m, a, len, ret) orelse return null;
+ c.live = c.live - m.len + len;
+ return got;
+ }
+ fn free(ctx: *anyopaque, m: []u8, a: std.mem.Alignment, ret: usize) void {
+ const c: *Capped = @ptrCast(@alignCast(ctx));
+ c.child.rawFree(m, a, ret);
+ c.live -= m.len;
+ }
+};
+
+fn chance(r: Random, p: f32) bool {
+ return r.float(f32) < p;
+}
+
+fn pick(r: Random, xs: anytype) @TypeOf(xs[0]) {
+ return xs[r.uintLessThan(usize, xs.len)];
+}
+
+/// Random bytes with no byte that starts a shell or a prompt (`!|<>;&$` and
+/// the backquote, `:`) and no capital (a builtin's first letter): what the
+/// fuzz writes may be run (an exec file, a click, a key) and the core's
+/// effects are dropped here, but a word that does its own I/O must never be
+/// spelled by chance.
+fn tame(r: Random, out: []u8) []u8 {
+ for (out) |*b| b.* = while (true) {
+ const c = r.int(u8);
+ if (std.mem.indexOfScalar(u8, "!|<>;&$`:", c) == null and !(c >= 'A' and c <= 'Z')) break c;
+ };
+ return out;
+}
+
+// ---------------------------------------------------------------------------
+// (ii) 9P: frames through the engine pardes runs into its tree.
+
+const Engine = ninep.Server(pardes.ctlfs, ninep.editor);
+const msize = ninep.msize;
+
+/// The names a walk takes: the tree's own, and the odd ones. Never `os` (the
+/// host's files: read and WRITTEN through the tree) nor `n` (other servers).
+const odd_names = [_][]const u8{ "", ".", "..", "...", "\x00", "a\x00b", "body\x00", "/", "a/b", "\xff\xfe", "na\xc3\xafve", "0", "1", "2", "3", "4", "9", "64", "99", "-1", "4294967295", "18446744073709551616", "pty", "ctl", "status", "data", "run", "new", "event" };
+const forbidden = [_][]const u8{ "os", "n" };
+
+fn walkName(r: Random, buf: []u8) []const u8 {
+ const top = std.meta.fieldNames(pardes.ctlfs.TopFile);
+ const pane = std.meta.fieldNames(pardes.ctlfs.PaneFile);
+ return switch (r.uintLessThan(u8, 10)) {
+ 0...3 => pick(r, top),
+ 4...6 => pick(r, pane),
+ 7, 8 => pick(r, &odd_names),
+ else => tame(r, buf[0..r.uintAtMost(usize, @min(buf.len, @as(usize, if (chance(r, 0.5)) 300 else 8)))]),
+ };
+}
+
+const offsets = [_]u64{ 0, 0, 0, 1, 3, 7, 100, 4095, 4096, 65536, 1 << 31, 1 << 32, (1 << 63) - 1, 1 << 63, std.math.maxInt(u64) };
+const counts = [_]u32{ 0, 1, 7, 64, 4096, 8192, msize - 11, msize, msize + 1, 1 << 31, std.math.maxInt(u32) };
+const words = [_][]const u8{ "", "\n", "\x00", "\xff", "\xc0\x80", "\xe6\x97", "clean\n", "dirty\n", "show\n", "addr=dot\n", "dot=addr\n", "mark\n", "nomark\n", "limit=addr\n", "0\n", "1\n", "#3\n", ",\n", "/alpha/\n", "$\n", "0,$\n", "+\n", "-\n", "m 5 5 0\n", "m 99999 99999 7\n", "m -1 -1 1\n", "m a b c\n", "follow\n", "follow new\n", "lock\n", "unlock\n", "c 2 0\n", "99999999999\n", "-1\n", "\t\t\n",
+ // A pane's rows (core/locations.zig formatRows): kind, seven numbers, styles, path.
+ "m 1 0 0 0 0 0 0 5:0+5=7 a.txt\n", "c 3 0 0 0 0 0 0 3:1+2=15 y\n", "m 1 0 0 0 0 9999 9999 4:0+4=keyword.add x\n", "p 18446744073709551615 0 0 0 0 0 0 - x\n", "m 1 4294967296 1 1 1 1 1 2:0+2=string a.txt\nc 2 0 0 0 0 0 0 - b\n" };
+
+fn data(r: Random, buf: []u8) []const u8 {
+ if (chance(r, 0.5)) return pick(r, &words);
+ const n = switch (r.uintLessThan(u8, 4)) {
+ 0 => r.uintAtMost(usize, 16),
+ 1 => r.uintAtMost(usize, 512),
+ 2 => r.uintAtMost(usize, 8192),
+ else => r.uintAtMost(usize, msize - 23),
+ };
+ return tame(r, buf[0..@min(n, buf.len)]);
+}
+
+/// The fids a connection walked last: most requests are about them.
+const Fids = struct {
+ recent: [4]u32 = @splat(0),
+ at: usize = 0,
+
+ fn any(f: *const Fids, r: Random) u32 {
+ if (chance(r, 0.6)) return pick(r, &f.recent);
+ return if (chance(r, 0.9)) r.uintLessThan(u32, 12) else pick(r, &[_]u32{ 255, 256, 4096, ninep.nofid, std.math.maxInt(u32) - 1 });
+ }
+ fn fresh(f: *Fids, r: Random) u32 {
+ const n = if (chance(r, 0.9)) 1 + r.uintLessThan(u32, 11) else f.any(r);
+ f.recent[f.at % f.recent.len] = n;
+ f.at += 1;
+ return n;
+ }
+};
+
+/// A path of the tree from its root, mostly; its names in `out`.
+fn realPath(r: Random, out: *[16][]const u8) u16 {
+ const top = std.meta.fieldNames(pardes.ctlfs.TopFile);
+ const pane = std.meta.fieldNames(pardes.ctlfs.PaneFile);
+ if (chance(r, 0.4)) {
+ out[0] = pick(r, top);
+ return 1;
+ }
+ out[0] = "pane";
+ out[1] = pick(r, &[_][]const u8{ "1", "2", "3", "4", "new" });
+ if (std.mem.eql(u8, out[1], "new")) return 2;
+ if (chance(r, 0.15)) {
+ out[2] = "pty";
+ out[3] = pick(r, &[_][]const u8{ "ctl", "status", "data", "run" });
+ return 4;
+ }
+ out[2] = if (chance(r, 0.3)) pick(r, &[_][]const u8{ "rows", "body", "addr", "data", "ctl", "event", "tag" }) else pick(r, pane);
+ return 3;
+}
+
+/// One request, valid in its encoding, hostile in its values.
+fn request(r: Random, f: *Fids, names: *[16][300]u8, buf: []u8) ninep.Msg {
+ return switch (r.uintLessThan(u8, 22)) {
+ 0 => .{ .tversion = .{ .msize = pick(r, &[_]u32{ msize, msize, 0, 1, 7, 24, 4096, msize + 24, std.math.maxInt(u32) }), .version = pick(r, &[_][]const u8{ "9P2000", "9P2000", "9P2000.u", "", "9P", "\x00" }) } },
+ 1 => .{ .tattach = .{ .fid = f.any(r), .afid = if (chance(r, 0.9)) ninep.nofid else f.any(r), .uname = pick(r, &[_][]const u8{ "user", "", "\x00" }), .aname = pick(r, &[_][]const u8{ "", "pardes", "x" }) } },
+ 2 => .{ .tauth = .{ .afid = f.any(r), .uname = "u", .aname = "" } },
+ 3 => .{ .tflush = .{ .oldtag = r.int(u16) } },
+ 4...7 => walk: {
+ var m: ninep.Msg = .{ .twalk = .{ .fid = 0, .newfid = 0, .nwname = 0 } };
+ if (chance(r, 0.7)) {
+ m.twalk.nwname = realPath(r, &m.twalk.wname);
+ // One name of it odd, now and then.
+ if (chance(r, 0.15)) m.twalk.wname[r.uintLessThan(u16, m.twalk.nwname)] = walkName(r, &names[0]);
+ } else {
+ m.twalk.fid = f.any(r);
+ m.twalk.nwname = if (chance(r, 0.95)) r.uintAtMost(u16, 4) else r.uintAtMost(u16, 16);
+ for (m.twalk.wname[0..m.twalk.nwname], names[0..m.twalk.nwname]) |*w, *nb| w.* = walkName(r, nb);
+ }
+ m.twalk.newfid = f.fresh(r);
+ break :walk m;
+ },
+ 8, 9 => .{ .topen = .{ .fid = f.any(r), .mode = if (chance(r, 0.7)) pick(r, &[_]u8{ 0, 1, 2, 3, 0x10, 0x11, 0x40, 0x12 }) else r.int(u8) } },
+ 10 => .{ .tcreate = .{ .fid = f.any(r), .name = walkName(r, &names[0]), .perm = if (chance(r, 0.5)) pick(r, &[_]u32{ 0o644, 0x80000755, 0 }) else r.int(u32), .mode = r.int(u8) } },
+ 11...13 => .{ .tread = .{ .fid = f.any(r), .offset = pick(r, &offsets), .count = pick(r, &counts) } },
+ 14...17 => .{ .twrite = .{ .fid = f.any(r), .offset = pick(r, &offsets), .data = data(r, buf) } },
+ 18 => .{ .tclunk = .{ .fid = f.any(r) } },
+ 19 => .{ .tremove = .{ .fid = f.any(r) } },
+ 20 => .{ .tstat = .{ .fid = f.any(r) } },
+ else => .{ .twstat = .{ .fid = f.any(r), .stat = .{
+ .type = if (chance(r, 0.8)) 0xffff else r.int(u16),
+ .dev = if (chance(r, 0.8)) 0xffffffff else r.int(u32),
+ .qid = .{ .type = 0xff, .version = 0xffffffff, .path = if (chance(r, 0.8)) std.math.maxInt(u64) else r.int(u64) },
+ .mode = if (chance(r, 0.7)) 0xffffffff else r.int(u32),
+ .atime = 0xffffffff,
+ .mtime = if (chance(r, 0.8)) 0xffffffff else r.int(u32),
+ .length = if (chance(r, 0.5)) std.math.maxInt(u64) else pick(r, &offsets),
+ .name = if (chance(r, 0.7)) "" else walkName(r, &names[1]),
+ .uid = "",
+ .gid = "",
+ .muid = "",
+ } } },
+ };
+}
+
+/// A frame the engine will take as one: whether it may be pushed. The
+/// stream is framed here as the engine frames it (cloud9 Server.receive), so
+/// a mutation that moves a frame's length cannot glue a walk into /os.
+fn allowed(frame: []const u8) bool {
+ const got = ninep.decode(frame) catch return true; // the engine refuses it
+ switch (got.msg) {
+ .twalk => |w| for (w.wname[0..@min(w.nwname, w.wname.len)]) |name| {
+ for (forbidden) |f| if (std.mem.eql(u8, name, f)) return false;
+ },
+ .tattach => |a| for ([_][]const u8{ "", "pardes", "x" }) |ok| {
+ if (std.mem.eql(u8, a.aname, ok)) break;
+ } else return false,
+ else => {},
+ }
+ return true;
+}
+
+fn mutate(r: Random, frame: []u8, len: usize) usize {
+ switch (r.uintLessThan(u8, 6)) {
+ 0 => frame[r.uintLessThan(usize, len)] ^= @as(u8, 1) << r.int(u3),
+ 1 => frame[r.uintLessThan(usize, len)] = r.int(u8),
+ 2 => return r.uintLessThan(usize, len), // cut, its length left saying more
+ 3 => {
+ const n = @min(r.uintAtMost(usize, 64), frame.len - len);
+ r.bytes(frame[len..][0..n]);
+ return len + n; // more than it says
+ },
+ 4 => std.mem.writeInt(u32, frame[0..4], pick(r, &[_]u32{ 0, 6, 7, @intCast(len + 1), msize + 1, std.math.maxInt(u32), r.int(u32) }), .little),
+ else => frame[4] = r.int(u8), // another type
+ }
+ return len;
+}
+
+/// Serves what the engine has whole, as runtime/9p_io.zig's `onServe` does
+/// with the turn its own: the core's effects are dropped (no save, no
+/// shell, no file).
+fn serve(p: *Pardes, e: *Engine) void {
+ while (true) {
+ const req = e.next() orelse e.retry() orelse break;
+ const reply = pardes.filesystem.EditHold.retried(&p.fs, req) orelse p.serveFs(req);
+ p.fs.edit_started = false;
+ e.reply(&reply, p.fsPayload(reply));
+ if (req.op == .release) pardes.ctlfs.runClosedLines(p);
+ while (p.nextEffect()) |_| {}
+ e.wrote(e.output().len);
+ }
+ // What the pump does between requests (Core.settle), its effects dropped.
+ pardes.ctlfs.pane.flushPausedBatch(p);
+ pardes.ctlfs.ctl.fillClosedPagers(p);
+ pardes.ctlfs.runClosedLines(p);
+ while (p.nextEffect()) |_| {}
+ e.wrote(e.output().len);
+}
+
+fn connect(e: *Engine, in: []u8, out: []u8, seed: u64) void {
+ e.initIn(.{ .in = in, .out = out, .root = pardes.ctlfs.root, .seed = @truncate(seed) });
+}
+
+fn hangUp(p: *Pardes, e: *Engine) void {
+ e.hangup();
+ serve(p, e);
+}
+
+/// One seed: a connection or more, each greeted (mostly), then requests,
+/// some mutated, some garbage.
+fn ninepSeed(seed: u64, steps: usize) !void {
+ var prng: Random.DefaultPrng = .init(seed);
+ const r = prng.random();
+ var cap: Capped = .{ .child = testing.allocator, .one = 64 << 20, .all = 512 << 20 };
+ const gpa = cap.allocator();
+ const p = try th.withFile(gpa, "alpha beta\ngamma\n\tdelta \xe6\x97\xa5\n");
+ defer p.deinit();
+ p.fs.write_room = msize - 24;
+ const e = try testing.allocator.create(Engine);
+ defer testing.allocator.destroy(e);
+ e.seq = 0;
+ const in = try testing.allocator.alloc(u8, msize);
+ defer testing.allocator.free(in);
+ const out = try testing.allocator.alloc(u8, 2 * msize);
+ defer testing.allocator.free(out);
+ const buf = try testing.allocator.alloc(u8, msize + 128);
+ defer testing.allocator.free(buf);
+ const scratch = try testing.allocator.alloc(u8, msize);
+ defer testing.allocator.free(scratch);
+ var names: [16][300]u8 = undefined;
+ var fids: Fids = .{};
+
+ var c: Conn = .{ .p = p, .e = e, .buf = buf };
+ connect(e, in, out, seed);
+ var greet = true;
+ // A dirty connection's frames are mutated and garbage comes on it (the
+ // decoder's); a clean one's are whole, and go deep (the tree's).
+ var dirty = false;
+ for (0..steps) |_| {
+ if (e.protocol.dead or chance(r, 0.004)) {
+ hangUp(p, e);
+ connect(e, in, out, r.int(u64));
+ greet = true;
+ dirty = chance(r, 0.25);
+ fids = .{};
+ }
+ if (greet) {
+ greet = false;
+ try c.send(.{ .tversion = .{ .msize = msize, .version = "9P2000" } }, ninep.notag);
+ try c.send(.{ .tattach = .{ .fid = 0, .afid = ninep.nofid, .uname = "user", .aname = "" } }, c.next());
+ } else if (dirty and chance(r, 0.05)) {
+ const len = r.uintAtMost(usize, 96);
+ r.bytes(buf[0..len]); // garbage
+ try push(p, e, buf[0..len]);
+ } else if (!dirty and chance(r, 0.4)) {
+ // A file's round: walked, opened, read and written at hostile
+ // offsets and counts, clunked (or left open).
+ var w: ninep.Msg = .{ .twalk = .{ .fid = 0, .newfid = fids.fresh(r), .nwname = 0 } };
+ w.twalk.nwname = realPath(r, &w.twalk.wname);
+ const k = w.twalk.newfid;
+ try c.send(w, c.next());
+ try c.send(.{ .topen = .{ .fid = k, .mode = pick(r, &[_]u8{ 0, 1, 2, 2, 0x11, 0x12, 0x40 }) } }, c.next());
+ for (0..1 + r.uintLessThan(usize, 4)) |_| try c.send(if (chance(r, 0.6))
+ .{ .twrite = .{ .fid = k, .offset = pick(r, &offsets), .data = data(r, scratch) } }
+ else
+ .{ .tread = .{ .fid = k, .offset = pick(r, &offsets), .count = pick(r, &counts) } }, c.next());
+ if (chance(r, 0.7)) try c.send(.{ .tclunk = .{ .fid = k } }, c.next());
+ } else {
+ const msg = request(r, &fids, &names, scratch);
+ if (!dirty and (msg == .tversion or msg == .tauth)) continue;
+ const t: u16 = if (msg == .tversion) ninep.notag else if (!dirty or chance(r, 0.97)) c.next() else pick(r, &[_]u16{ 0, c.tag, ninep.notag });
+ const f = ninep.encode(msg, t, buf) catch continue;
+ const len = if (dirty and chance(r, 0.1)) mutate(r, buf, f.len) else f.len;
+ try push(p, e, buf[0..len]);
+ }
+ // Drawn, as the session draws after a request (and every client).
+ _ = p.frame_arena.reset(.retain_capacity);
+ _ = p.render(p.frame_arena.allocator()) catch {};
+ }
+ hangUp(p, e);
+ try testing.expectEqual(@as(usize, 0), cap.refused);
+}
+
+/// One connection's sending side: each request encoded whole and pushed.
+const Conn = struct {
+ p: *Pardes,
+ e: *Engine,
+ buf: []u8,
+ tag: u16 = 0,
+
+ fn next(c: *Conn) u16 {
+ c.tag +%= 1;
+ if (c.tag == ninep.notag) c.tag = 1;
+ return c.tag;
+ }
+ fn send(c: *Conn, msg: ninep.Msg, tag: u16) !void {
+ const f = ninep.encode(msg, tag, c.buf) catch return;
+ try push(c.p, c.e, f);
+ }
+};
+
+/// Pushes `bytes` a frame at a time, as the engine will frame them, each
+/// checked by `allowed`; one that is not ends the connection there.
+fn push(p: *Pardes, e: *Engine, bytes: []const u8) !void {
+ var at: usize = 0;
+ while (at < bytes.len and !e.protocol.dead) {
+ const held = e.protocol.in_len;
+ // The length the engine will read: its own first bytes, or these.
+ var head: [4]u8 = undefined;
+ const have = @min(held, 4);
+ @memcpy(head[0..have], e.protocol.in[0..have]);
+ const more = @min(4 - have, bytes.len - at);
+ @memcpy(head[have..][0..more], bytes[at..][0..more]);
+ if (have + more < 4) {
+ at += e.push(bytes[at..]);
+ break;
+ }
+ const len = std.mem.readInt(u32, &head, .little);
+ if (held >= len) break; // a whole frame the engine has not taken yet: the rest goes
+ if (len < ninep.header_len or len > msize) {
+ _ = e.push(bytes[at..]); // the engine refuses it and ends the link
+ serve(p, e);
+ break;
+ }
+ const want = len - held;
+ if (bytes.len - at < want) {
+ at += e.push(bytes[at..]);
+ break;
+ }
+ var frame: [msize]u8 = undefined;
+ @memcpy(frame[0..held], e.protocol.in[0..held]);
+ @memcpy(frame[held..len], bytes[at..][0..want]);
+ if (!allowed(frame[0..len])) {
+ hangUp(p, e);
+ break;
+ }
+ const n = e.push(bytes[at..][0..want]);
+ at += n;
+ serve(p, e);
+ if (n < want) break;
+ }
+ serve(p, e);
+}
+
+test "9P: hostile and mutated frames through the engine into the tree: a refusal, never a panic" {
+ for (seeds) |seed| try ninepSeed(seed, 400);
+}
+
+// ---------------------------------------------------------------------------
+// (iii) the wire: a client's messages into the session's reader and core;
+// the session's units into a client's.
+
+const wire = @import("wire");
+const replica = pardes.replica;
+
+/// Bytes laid out as abi/wire.zig's decoders read them.
+const Out = struct {
+ buf: []u8,
+ n: usize = 0,
+
+ fn byte(o: *Out, v: u8) void {
+ if (o.n == o.buf.len) return;
+ o.buf[o.n] = v;
+ o.n += 1;
+ }
+ fn int(o: *Out, comptime T: type, v: T) void {
+ var b: [@sizeOf(T)]u8 = undefined;
+ std.mem.writeInt(T, &b, v, .little);
+ for (b) |x| o.byte(x);
+ }
+ fn bytes(o: *Out, v: []const u8) void {
+ for (v) |x| o.byte(x);
+ }
+};
+
+fn flag(r: Random) u8 {
+ return if (chance(r, 0.97)) @intFromBool(r.boolean()) else r.int(u8);
+}
+
+fn small(r: Random) u16 {
+ return if (chance(r, 0.8)) pick(r, &[_]u16{ 0, 1, 2, 5, 23, 24, 79, 80, 81, 127, 128, 511, 512, 513, 4096, 65535 }) else r.int(u16);
+}
+
+fn real(r: Random) u32 {
+ return if (chance(r, 0.9)) @bitCast(pick(r, &[_]f32{ 0, 1, -1, 0.5, 7.5, -0.0, 1e30, -1e30, 3.4e38, 1e-40, 65535.5 })) else r.int(u32);
+}
+
+fn metrics(o: *Out, r: Random) void {
+ const some = chance(r, 0.5);
+ o.byte(if (some) 1 else flag(r));
+ if (some) for (0..4) |_| o.int(u16, if (chance(r, 0.9)) 1 + r.uintLessThan(u16, 40) else small(r));
+}
+
+fn place(o: *Out, r: Random) void {
+ const rows = small(r);
+ for ([_]u16{ small(r), small(r), small(r), small(r), small(r), rows, if (chance(r, 0.9)) r.uintAtMost(u16, rows) else small(r) }) |n| o.int(u16, n);
+}
+
+/// A key's code: letters, digits, the specials' plane, and the odd ones.
+fn codepoint(r: Random) u32 {
+ return switch (r.uintLessThan(u8, 6)) {
+ 0, 1 => pick(r, "abcdefghijklmnopqrstuvwxyz0123456789 .,-_/\t\r"),
+ 2 => pick(r, &[_]u32{ 0, 0x08, 0x1b, 0x7f, 0x0d, 0xD800, 0xDFFF, 0xFFFD, 0x10FFFF, 0x110000, 0xFFFFFFFF }),
+ 3 => 0xE000 + r.uintLessThan(u32, 0x1900),
+ 4 => 0xF0000 + r.uintLessThan(u32, 0x20000),
+ else => r.uintAtMost(u32, 0x10FFFF),
+ };
+}
+
+/// One client message: a frame (tag, length, payload) as the decoder reads
+/// it, its shape mostly whole and its values hostile.
+fn clientFrame(r: Random, out: []u8, text: []u8) []u8 {
+ const tags = std.enums.values(wire.ClientTag);
+ const tag: u8 = if (chance(r, 0.98)) @backingInt(pick(r, tags)) else r.int(u8);
+ var o: Out = .{ .buf = out };
+ o.byte(tag);
+ o.int(u32, 0);
+ switch (std.enums.fromInt(wire.ClientTag, tag) orelse .ping) {
+ .key => {
+ o.int(u32, codepoint(r));
+ const t = tame(r, text[0..if (chance(r, 0.9)) r.uintAtMost(usize, 8) else r.uintAtMost(usize, 300)]);
+ o.int(u16, @intCast(t.len));
+ o.bytes(t);
+ for (0..3) |_| o.byte(if (chance(r, 0.8)) 0 else flag(r));
+ },
+ .mouse => {
+ o.byte(if (chance(r, 0.95)) r.uintLessThan(u8, 10) else r.int(u8));
+ o.byte(if (chance(r, 0.95)) r.uintLessThan(u8, 4) else r.int(u8));
+ o.int(u16, small(r));
+ o.int(u16, small(r));
+ for (0..3) |_| o.byte(if (chance(r, 0.8)) 0 else flag(r));
+ o.int(u32, real(r));
+ // A body hit, then a tag hit.
+ for (0..2) |which| {
+ const some = chance(r, 0.4);
+ o.byte(if (some) 1 else flag(r));
+ if (!some) continue;
+ if (which == 1) {
+ o.byte(r.uintLessThan(u8, 8));
+ o.int(u16, small(r));
+ }
+ o.int(u32, if (chance(r, 0.8)) r.uintLessThan(u32, 6) else r.int(u32));
+ o.int(u16, small(r));
+ o.int(u16, small(r));
+ o.int(u32, real(r));
+ o.int(u32, real(r));
+ metrics(&o, r);
+ place(&o, r);
+ }
+ },
+ .resize => {
+ o.int(u16, if (chance(r, 0.9)) 1 + r.uintLessThan(u16, wire.max_cols) else small(r));
+ o.int(u16, if (chance(r, 0.9)) 1 + r.uintLessThan(u16, wire.max_rows) else small(r));
+ o.int(u16, small(r));
+ o.int(u16, small(r));
+ metrics(&o, r);
+ },
+ .paste => {
+ const t = tame(r, text[0..r.uintAtMost(usize, 300)]);
+ o.int(u32, @intCast(t.len));
+ o.bytes(t);
+ },
+ .command => {
+ const t = tame(r, text[0..r.uintAtMost(usize, 64)]);
+ o.int(u16, @intCast(t.len));
+ o.bytes(t);
+ },
+ .focus => o.byte(flag(r)),
+ .frontend => for (0..3) |_| o.byte(flag(r)),
+ .pointer_leave => {},
+ else => {
+ const n = r.uintAtMost(usize, 40);
+ r.bytes(text[0..n]);
+ o.bytes(text[0..n]);
+ },
+ }
+ std.mem.writeInt(u32, out[1..5], @intCast(o.n - wire.header_len), .little);
+ return out[0..o.n];
+}
+
+/// A client's input as the session's reader takes it (`Peer.take`): its
+/// head, a stamp now and then, its event's frame; mutated, or garbage.
+fn clientInput(r: Random, out: []u8, text: []u8) []u8 {
+ if (chance(r, 0.02)) {
+ const n = r.uintAtMost(usize, 64);
+ r.bytes(out[0..n]);
+ return out[0..n];
+ }
+ var o: Out = .{ .buf = out };
+ o.int(u16, r.uintLessThan(u16, 4));
+ o.int(u32, r.int(u32));
+ if (chance(r, 0.1)) {
+ o.byte(@backingInt(wire.ClientTag.stamp));
+ o.int(u32, 16);
+ o.int(i64, r.int(i64));
+ o.int(i64, r.int(i64));
+ }
+ const f = clientFrame(r, out[o.n..], text);
+ var n = o.n + f.len;
+ if (chance(r, 0.05)) n = mutate(r, out, n);
+ return out[0..n];
+}
+
+fn wireSessionSeed(seed: u64, steps: usize) !void {
+ var prng: Random.DefaultPrng = .init(seed);
+ const r = prng.random();
+ var cap: Capped = .{ .child = testing.allocator, .one = 64 << 20, .all = 512 << 20 };
+ const p = try th.withFile(cap.allocator(), "alpha beta\ngamma\n\tdelta \xe6\x97\xa5\n");
+ defer p.deinit();
+ const out = try testing.allocator.alloc(u8, 1 << 16);
+ defer testing.allocator.free(out);
+ const text = try testing.allocator.alloc(u8, 1 << 15);
+ defer testing.allocator.free(text);
+ for (0..steps) |_| {
+ const msg = clientInput(r, out, text);
+ // Every tag's decoder, as `Peer.take` and the daemon's hello read them.
+ if (msg.len > 6) if (wire.framed(msg[6..]) catch null) |f| {
+ _ = wire.decodeClient(f.tag, f.payload) catch {};
+ };
+ const in = replica.parseInput(msg) orelse continue;
+ p.update(in.event);
+ while (p.nextEffect()) |_| {}
+ _ = p.frame_arena.reset(.retain_capacity);
+ _ = p.render(p.frame_arena.allocator()) catch {};
+ }
+ try testing.expectEqual(@as(usize, 0), cap.refused);
+}
+
+test "the wire, a session's side: a client's hostile and mutated inputs are refused or applied, never a panic" {
+ for (seeds) |seed| try wireSessionSeed(seed, 300);
+}
+
+fn never(_: ?*anyopaque) bool {
+ return false;
+}
+const quiet_host: pardes.Host.VTable = .{ .watched = never };
+
+/// A session's units from its boot, of inputs a client could send (typing,
+/// a paste, sizes, focus, a pointer's motion: nothing that saves or runs).
+fn recordedUnits(gpa: std.mem.Allocator, units: *std.ArrayList([]u8)) !void {
+ const a = try replica.Authority.init(gpa, .{ .cols = 80, .rows = 24 }, .{ .vtable = &quiet_host });
+ defer a.deinit();
+ try units.append(gpa, try gpa.dupe(u8, try a.unit(0, 0)));
+ var buf: [256]u8 = undefined;
+ // Each a tag and its payload, as abi/wire.zig's decodeClient reads it.
+ const script = [_]struct { wire.ClientTag, []const u8 }{
+ .{ .key, "i\x00\x00\x00\x01\x00i\x00\x00\x00" },
+ .{ .key, "h\x00\x00\x00\x01\x00h\x00\x00\x00" },
+ .{ .paste, "\x0f\x00\x00\x00hello\nworld\n\xe6\x97\xa5" },
+ .{ .resize, "\x64\x00\x1e\x00\x0a\x00\x14\x00\x00" }, // 100x30
+ .{ .focus, "\x00" },
+ .{ .focus, "\x01" },
+ .{ .mouse, "\x07\x02\x0a\x00\x05\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" }, // motion at 10,5
+ .{ .key, "\x1b\x00\x00\x00\x00\x00\x00\x00\x00" }, // escape
+ .{ .resize, "\x3c\x00\x14\x00\x0a\x00\x14\x00\x00" }, // 60x20
+ .{ .key, "x\x00\x00\x00\x01\x00x\x00\x00\x00" },
+ };
+ for (0..3) |_| for (script) |s| {
+ var o: Out = .{ .buf = &buf };
+ o.bytes(&@as([6]u8, @splat(0)));
+ o.byte(@backingInt(s[0]));
+ o.int(u32, @intCast(s[1].len));
+ o.bytes(s[1]);
+ const in = replica.parseInput(buf[0..o.n]) orelse return error.BadScript;
+ a.apply(in.event);
+ a.seq += 1;
+ try units.append(gpa, try gpa.dupe(u8, try a.unit(0, a.seq)));
+ };
+}
+
+fn wireClientSeed(gpa: std.mem.Allocator, units: []const []const u8, seed: u64) !void {
+ var prng: Random.DefaultPrng = .init(seed);
+ const r = prng.random();
+ var cap: Capped = .{ .child = gpa, .one = 64 << 20, .all = 512 << 20 };
+ const copies = try gpa.alloc([]u8, units.len);
+ defer gpa.free(copies);
+ for (copies, units) |*c, u| c.* = try gpa.alloc(u8, u.len + 64);
+ defer for (copies) |c| gpa.free(c);
+ var lens = try gpa.alloc(usize, units.len);
+ defer gpa.free(lens);
+ for (copies, units, lens) |c, u, *n| {
+ @memcpy(c[0..u.len], u);
+ n.* = u.len;
+ // Seed 0 is the units as sent: a replica of them is the session.
+ if (seed != 0 and chance(r, 0.3)) n.* = switch (r.uintLessThan(u8, 4)) {
+ 0 => flips: {
+ for (0..1 + r.uintLessThan(usize, 4)) |_| c[r.uintLessThan(usize, u.len)] ^= @as(u8, 1) << r.int(u3);
+ break :flips u.len;
+ },
+ 1 => cut: {
+ break :cut r.uintLessThan(usize, u.len);
+ },
+ 2 => grown: {
+ r.bytes(c[u.len..][0..64]);
+ break :grown u.len + r.uintAtMost(usize, 64);
+ },
+ else => set: {
+ c[r.uintLessThan(usize, u.len)] = r.int(u8);
+ break :set u.len;
+ },
+ };
+ }
+ const rep = replica.Replica.init(cap.allocator(), 1, copies[0][0..lens[0]]) catch return;
+ defer rep.deinit();
+ for (copies[1..], lens[1..]) |c, n| rep.confirm(c[0..n]);
+ rep.settle();
+ if (seed == 0) try testing.expect(rep.diverged == null);
+ try testing.expectEqual(@as(usize, 0), cap.refused);
+}
+
+test "the wire, a client's side: a session's units cut, flipped and grown diverge the client, never a panic" {
+ const gpa = testing.allocator;
+ var units: std.ArrayList([]u8) = .empty;
+ defer {
+ for (units.items) |u| gpa.free(u);
+ units.deinit(gpa);
+ }
+ try recordedUnits(gpa, &units);
+ try wireClientSeed(gpa, units.items, 0);
+ for (seeds) |seed| for (0..8) |k| try wireClientSeed(gpa, units.items, seed *% 31 +% k);
+}
+
+// ---------------------------------------------------------------------------
+// (iv) a dump and an image read back: a join's (a client loads it before its
+// digest is checked: replica.made), a Restore's and an Upgrade's (Db.zig's
+// image, the state file's).
+
+/// `n` bytes of `b` changed as a disk or a peer could: bits flipped, a
+/// byte set, a run zeroed, cut, grown (`b` has room past `n`).
+fn damage(r: Random, b: []u8, n: usize) usize {
+ if (n == 0) return n;
+ switch (r.uintLessThan(u8, 6)) {
+ 0 => for (0..1 + r.uintLessThan(usize, 4)) |_| {
+ b[r.uintLessThan(usize, n)] ^= @as(u8, 1) << r.int(u3);
+ },
+ 1 => b[r.uintLessThan(usize, n)] = r.int(u8),
+ 2 => {
+ const at = r.uintLessThan(usize, n);
+ @memset(b[at..][0..@min(n - at, 1 + r.uintLessThan(usize, 16))], 0);
+ },
+ 3 => return r.uintLessThan(usize, n),
+ 4 => {
+ const more = @min(b.len - n, r.uintAtMost(usize, 64));
+ r.bytes(b[n..][0..more]);
+ return n + more;
+ },
+ else => {
+ const at = r.uintLessThan(usize, n);
+ @memset(b[at..][0..@min(n - at, 8)], 0xff);
+ },
+ }
+ return n;
+}
+
+fn loadSeed(whole: []const u8, seed: u64) !void {
+ var prng: Random.DefaultPrng = .init(seed);
+ const r = prng.random();
+ var cap: Capped = .{ .child = testing.allocator, .one = 64 << 20, .all = 512 << 20 };
+ const gpa = cap.allocator();
+ const b = try testing.allocator.alloc(u8, whole.len + 64);
+ defer testing.allocator.free(b);
+ @memcpy(b[0..whole.len], whole);
+ var n = whole.len;
+ if (seed != 0) for (0..1 + r.uintLessThan(usize, 3)) |_| {
+ n = damage(r, b, n);
+ };
+ var why: [256]u8 = undefined;
+ pardes.dump.check(gpa, b[0..n], &why) catch {};
+ var notes: std.ArrayList(u8) = .empty;
+ defer notes.deinit(gpa);
+ if (pardes.dump.load(gpa, .{ .cols = 80, .rows = 24 }, b[0..n], &notes)) |q| {
+ _ = q.frame_arena.reset(.retain_capacity);
+ _ = q.render(q.frame_arena.allocator()) catch {};
+ q.deinit();
+ } else |err| if (seed == 0) return err;
+ try testing.expectEqual(@as(usize, 0), cap.refused);
+}
+
+test "a dump and an image cut, flipped and grown: refused or loaded, never a panic" {
+ const gpa = testing.allocator;
+ const p = try th.withFile(gpa, "alpha beta\ngamma\n\tdelta \xe6\x97\xa5\n");
+ defer p.deinit();
+ const bytes = try pardes.dump.dumpBytes(p);
+ defer gpa.free(bytes);
+ const image = try pardes.dump.image(p, "fuzz");
+ defer gpa.free(image);
+ for ([_][]const u8{ bytes, image }) |whole| {
+ try loadSeed(whole, 0);
+ for (seeds) |seed| for (0..8) |k| try loadSeed(whole, seed *% 31 +% k);
+ }
+}
+
+test "9P: a rows style past the syntax's kinds is refused, never drawn" {
+ const p = try th.withFile(testing.allocator, "x\n");
+ defer p.deinit();
+ // A results pane: its rows' styles are what it is painted with.
+ try pardes.panes.Output.fillResults(p, 0, "/tmp", .search, "foo", try p.gpa.dupe(u8, "a.txt:1:1 foo\nb.txt:2:3 foo\n"), null);
+ const serial = for (p.panes) |slot| {
+ const pane = slot orelse continue;
+ const f = pane.file orelse continue;
+ if (f.output != null and f.location_rows.len > 0) break pane.serial;
+ } else return error.NoSearch;
+ const rows = pardes.ctlfs.Node.of(serial, .rows);
+ // 1..4 are Syn's kinds (keyword, string, number, comment); 5..15 none.
+ for ([_][]const u8{ "7", "5", "15", "4" }) |n| {
+ _ = th.call(p, .{ .tag = 1, .op = .setattr, .node = rows, .truncate = true });
+ var line: [64]u8 = undefined;
+ const text = try std.fmt.bufPrint(&line, "m 1 1 0 0 0 0 0 3:0+3={s} a.txt\n", .{n});
+ const want: pardes.ctlfs.Status = if (std.mem.eql(u8, n, "4")) .ok else .err;
+ try testing.expectEqual(want, th.wr(p, rows, text).reply.status);
+ _ = p.frame_arena.reset(.retain_capacity);
+ _ = try p.render(p.frame_arena.allocator());
+ }
+}
diff --git a/core/root.zig b/core/root.zig
index 2f3e4494..5c15d260 100644
--- a/core/root.zig
+++ b/core/root.zig
@@ -396,6 +396,7 @@ test "a compact tagline anchors at its own pane, and both shells step from the s
}
test {
+ _ = @import("fuzz.zig");
_ = @import("Addon.zig");
_ = @import("rollback.zig");
_ = @import("Core.zig");
@@ -648,6 +649,7 @@ const machine_lines = [_]struct { []const u8, usize, []const u8 }{
.{ "ninep/pty.zig", 1, "a 9P exec's shell check (tape.site(.shell))" },
.{ "ninep/screen.zig", 1, "a 9P address's text type" },
.{ "ninep/tree.zig", 1, "the daemon's registry (/sessions, tape.site(.sessions))" },
+ .{ "fuzz.zig", 1, "the 9P fuzz's engine, the session's (runtime.ninep): a test's, no step's" },
.{ "term/terminal.zig", 2, "the emulator's image files (TMPDIR) and its Io: each side's emulator, a medium's read taped (Term.media)" },
};
diff --git a/dev/tui/tui.zig b/dev/tui/tui.zig
index d1bbe140..9320e522 100644
--- a/dev/tui/tui.zig
+++ b/dev/tui/tui.zig
@@ -2917,6 +2917,15 @@ test "a mouse report at row or column 0, or before it, is the window's edge, nev
}
}
+test "an X10 mouse report with a byte below 32, and one with a button no mouse has, are no event, never a panic" {
+ // A legacy terminal's `ESC [ M` then a control byte: Alt+[, Shift+M, Enter and two keys.
+ for ([_][]const u8{ "\x1b[M\x0d\x20\x20", "\x1b[M\x20\x0d\x20", "\x1b[M\x20\x20\x1f", "\x1b[<192;1;1M", "\x1b[<195;5;5m" }) |sequence| {
+ var parser: vaxis.Parser = .{};
+ const result = try parser.parse(sequence, std.testing.allocator);
+ try std.testing.expect(result.event == null and result.n > 0);
+ }
+}
+
test "a mouse's side buttons, xterm's 8 and 9, are Back and Forward, as SDL's X1 and X2 are" {
for ([_]vaxis.Mouse.Button{ .button_8, .button_9 }, [_]pardes.Mouse.Button{ .back, .forward }) |from, to| {
const event = mouseEvent(.{ .col = 3, .row = 2, .button = from, .mods = .{}, .type = .press }).?;