//! 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; } /// What is done with a dump once it loads: a join's is digested (the /// session's digest decides before anything draws it: replica.fromDump), /// a Restore's or an Upgrade's image is not; then each is used (`use`). const Road = enum { join, restore }; /// A core loaded used as its user would: drawn at the size it says, then /// smaller and larger (a resize each), then given keys and a wheel notch each /// way and drawn again. A load that draws and then dies at a key is the same /// fault as one that dies drawing. fn use(q: *Pardes) void { const K = pardes.Key; const steps = [_]pardes.Event{ .{ .resize = .{ .cols = 40, .rows = 12 } }, .{ .resize = .{ .cols = 200, .rows = 60 } }, .{ .key = .{ .cp = 'j' } }, .{ .key = .{ .cp = 'w' } }, .{ .key = .{ .cp = 'x' } }, .{ .key = .{ .cp = 'd' } }, .{ .key = .{ .cp = 'u' } }, .{ .key = .{ .cp = K.page_down } }, .{ .key = .{ .cp = K.page_up } }, .{ .key = .{ .cp = 'k' } }, .{ .key = .{ .cp = K.escape } }, .{ .mouse = .{ .button = .wheel_down, .kind = .press, .col = 100, .row = 30 } }, .{ .mouse = .{ .button = .wheel_up, .kind = .press, .col = 100, .row = 30 } }, }; for (0..steps.len + 1) |at| { if (at < 3 or at == steps.len) { q.sync(); _ = q.frame_arena.reset(.retain_capacity); _ = q.render(q.frame_arena.allocator()) catch {}; } if (at == steps.len) return; q.update(steps[at]); while (q.nextEffect()) |_| {} } } fn loadSeed(whole: []const u8, road: Road, 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], ¬es)) |q| { defer q.deinit(); if (road == .join) _ = pardes.tape.digestOf(q); use(q); } 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(); // A reader's walk in it: a union, a fixed array held to its length. p.panes[0].?.trail = pardes.Trail.reader(7, "/x/rank.zig", .{ .line = 3, .col = 2 }); // A view's tag out of rest in it (View.tag_state): SPC t w remembered // (a group's last leaf), then Help typed into (a scope, a field, hits). for (" tw ?hel") |c| p.update(.{ .key = .{ .cp = c, .text = &[_]u8{c} } }); try testing.expect(p.view().tag_state.kind == .help and p.view().tag_state.nhits > 0); // The byte dump a join streams, and the image a Dump keeps. const bytes = try pardes.dump.byteDump(p); defer gpa.free(bytes); const image = try pardes.dump.dumpBytes(p); defer gpa.free(image); // Seconds a road, each core used (`use`). The image's past 1779 seeds // reach xitdb's own reader (a slot's tag past its kinds: a `switch` on // it), a dependency's. // Join seed 19224: the theme read after the core a reference to a // slice the core holds, freed by hand and again by the rollback. try loadSeed(bytes, .join, 19224); // Join seed 31554: the namespace's opens_len past its 64 slots, refused, // and the rollback's teardown of the namespace read that far. try loadSeed(bytes, .join, 31554); for ([_][]const u8{ bytes, image }, [_]Road{ .join, .restore }, [_]u64{ 2048, 1024 }) |whole, road, n| { try loadSeed(whole, road, 0); for (1..n + 1) |seed| try loadSeed(whole, road, seed); } } 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()); } } // --------------------------------------------------------------------------- // (v, vi) Numbers in a file's text and in another program's answer: a // diff's hunk headers (a `.diff` drawn, the patch view, a look's target) // and a language server's rows (each kind's answer landed, stepped, drawn; // the same places typed to Look). const diff = @import("diff.zig"); const hunks = @import("hunks.zig"); const lsp = pardes.lsp; /// Around what an int of each width holds, and past it. const numbers = [_][]const u8{ "0", "1", "2", "3", "5", "65535", "2147483647", "2147483648", "3000000000", "4294967295", "4294967296", "9223372036854775807", "9223372036854775808", "18446744073709551615", "18446744073709551616", "99999999999999999999999" }; fn draw(p: *Pardes) !void { p.sync(); _ = p.frame_arena.reset(.retain_capacity); _ = try p.render(p.frame_arena.allocator()); } fn diffSeed(gpa: std.mem.Allocator, seed: u64) !void { var prng: Random.DefaultPrng = .init(seed); const r = prng.random(); var text: std.ArrayList(u8) = .empty; defer text.deinit(gpa); try text.appendSlice(gpa, "diff --git a/x.zig b/x.zig\n--- a/x.zig\n+++ b/x.zig\n"); for (0..1 + r.uintLessThan(usize, 3)) |_| { try text.print(gpa, "@@ -{s}", .{pick(r, numbers)}); if (chance(r, 0.7)) try text.print(gpa, ",{s}", .{pick(r, numbers)}); try text.print(gpa, " +{s}", .{pick(r, numbers)}); if (chance(r, 0.7)) try text.print(gpa, ",{s}", .{pick(r, numbers)}); try text.appendSlice(gpa, " @@ fn x()\n"); const lines = [_][]const u8{ " const a = 1;\n", "-const b = 2;\n", "+const b = 3;\n", "\\ No newline at end of file\n", "\n", "--- y\n", "+++ y\n", "text\n" }; for (0..r.uintLessThan(usize, 9)) |_| try text.appendSlice(gpa, pick(r, lines)); } // A `.diff` drawn. const p = try th.withFile(gpa, text.items); defer p.deinit(); const pane = p.panes[p.view().active].?; gpa.free(pane.file.?.path); pane.file.?.path = try gpa.dupe(u8, "/change.diff"); pane.file.?.syntax_dirty = true; try draw(p); // The patch view. var arena: std.heap.ArenaAllocator = .init(gpa); defer arena.deinit(); const ctx: hunks.Ctx = .{ .arena = arena.allocator() }; _ = hunks.format(&ctx, "", text.items) catch {}; // A look's target, at every row. var rows: std.ArrayList([]const u8) = .empty; defer rows.deinit(gpa); var it = std.mem.splitScalar(u8, text.items, '\n'); while (it.next()) |row| try rows.append(gpa, row); for (0..rows.items.len) |row| _ = diff.targetAt(rows.items, row, false); } test "a diff's hunk headers with numbers past any file's: drawn, formatted and looked at, never a panic" { for (seeds) |seed| for (0..4) |k| try diffSeed(testing.allocator, seed *% 31 +% k); } fn lspSeed(gpa: std.mem.Allocator, seed: u64) !void { var prng: Random.DefaultPrng = .init(seed); const r = prng.random(); const p = try th.withFile(gpa, "alpha one\n\tbeta\n\t\tgamma \xe6\x97\xa5\n\n"); defer p.deinit(); var rows: std.ArrayList(u8) = .empty; defer rows.deinit(gpa); for (0..1 + r.uintLessThan(usize, 4)) |_| { // As lsp.sourceSpanRow writes them; the file's own name. try rows.print(gpa, "/test.txt:{s}:{s}", .{ pick(r, numbers), pick(r, numbers) }); if (chance(r, 0.5)) try rows.print(gpa, "-{s}", .{pick(r, numbers)}); try rows.appendSlice(gpa, " alpha\n"); } const kinds = [_]lsp.Kind{ .definition, .declaration, .implementation, .references, .diagnostics, .document_symbols, .workspace_symbols }; const kind = pick(r, kinds); if (lsp.supports.contains(kind)) { p.lspRequest(0, kind, ""); while (p.nextEffect()) |_| {} if (p.lsp_ask.wait) |wait| p.update(.{ .lsp_resp = .{ .id = wait.id, .rows = rows.items } }); try draw(p); for ("nNjk\r") |key| { p.update(.{ .key = .{ .cp = if (key == '\r') pardes.Key.enter else key } }); try draw(p); } } // The same places typed. var look: [96]u8 = undefined; p.update(.{ .command = try std.fmt.bufPrint(&look, "Look /test.txt:{s}:{s}", .{ pick(r, numbers), pick(r, numbers) }) }); try draw(p); p.update(.{ .command = try std.fmt.bufPrint(&look, "Look /test.txt:{s}:{s}-{s}:{s}", .{ pick(r, numbers), pick(r, numbers), pick(r, numbers), pick(r, numbers) }) }); try draw(p); p.update(.{ .command = try std.fmt.bufPrint(&look, "Look /test.txt:{s}-{s}", .{ pick(r, numbers), pick(r, numbers) }) }); try draw(p); } test "a language server's rows and a typed Look with numbers past any file's: landed, stepped and drawn, never a panic" { for (seeds) |seed| for (0..4) |k| try lspSeed(testing.allocator, seed *% 31 +% k); }