summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--core/dump.zig6
-rw-r--r--core/replica.zig53
-rw-r--r--core/walk.zig167
3 files changed, 203 insertions, 23 deletions
diff --git a/core/dump.zig b/core/dump.zig
index 29aebce8..deb18dba 100644
--- a/core/dump.zig
+++ b/core/dump.zig
@@ -395,8 +395,9 @@ fn loadKnowing(gpa: std.mem.Allocator, opts: Options, bytes: []const u8, notes:
};
defer l.deinit();
// A load that fails leaves nothing: what it read is freed, and the
- // core with it, its fields never torn down one by one.
+ // core with it, its fields never torn down one by one; why, in `notes`.
errdefer {
+ if (notes) |n| n.appendSlice(gpa, l.notes.items) catch {};
l.rollback();
p.fs.deinit(gpa);
gpa.destroy(p);
@@ -471,8 +472,9 @@ fn loadImage(gpa: std.mem.Allocator, opts: Options, bytes: []const u8, notes: ?*
defer l.deinit();
l.blobs = r.blobs() catch null;
// A load that fails leaves nothing: what it read is freed, and the
- // core with it, its fields never torn down one by one.
+ // core with it, its fields never torn down one by one; why, in `notes`.
errdefer {
+ if (notes) |n| n.appendSlice(gpa, l.notes.items) catch {};
l.rollback();
p.fs.deinit(gpa);
gpa.destroy(p);
diff --git a/core/replica.zig b/core/replica.zig
index 57dd4eed..72662df6 100644
--- a/core/replica.zig
+++ b/core/replica.zig
@@ -524,7 +524,7 @@ pub const Replica = struct {
/// an image a frame late at worst... or reads freed pixels, which no test
/// session has.
pub fn initDump(gpa: Allocator, id: u16, view: u8, bytes: []const u8, opts: pardes.Options) !*Replica {
- return made(gpa, id, view, opts, bytes);
+ return made(gpa, id, view, opts, bytes, null);
}
/// A pair's first client's replica (Options.pair): its core made here
@@ -534,11 +534,12 @@ pub const Replica = struct {
/// join, which the welcome confirms by its digest (`confirmBoot`). Its
/// id the session's first client's.
pub fn initBoot(gpa: Allocator, opts: pardes.Options) !*Replica {
- return made(gpa, 1, null, opts, null);
+ return made(gpa, 1, null, opts, null, null);
}
- /// `initDump`'s, or with no dump `initBoot`'s.
- fn made(gpa: Allocator, id: u16, view: ?u8, opts: pardes.Options, dump: ?[]const u8) !*Replica {
+ /// `initDump`'s, or with no dump `initBoot`'s; why a dump was refused
+ /// in `why` when given (its loader's words).
+ fn made(gpa: Allocator, id: u16, view: ?u8, opts: pardes.Options, dump: ?[]const u8, why: ?*std.ArrayList(u8)) !*Replica {
const r = try gpa.create(Replica);
r.* = .{ .gpa = gpa, .id = id, .view = view orelse 0, .t = tape.memory(gpa), .guess = true };
r.t.skips_render = true;
@@ -560,7 +561,13 @@ pub const Replica = struct {
// replica's: deltas write them while a copy is held.
pardes.dump.terminal_gpa = pardes.panes.emulator_gpa;
defer pardes.dump.terminal_gpa = null;
- const c = if (dump) |bytes| try pardes.dump.load(epoch, o, bytes, null) else boot: {
+ // The loader's words, the epoch's: why a refusal is copied out.
+ var words: std.ArrayList(u8) = .empty;
+ defer words.deinit(epoch);
+ const c = if (dump) |bytes| pardes.dump.load(epoch, o, bytes, &words) catch |err| {
+ if (why) |w| w.appendSlice(gpa, words.items) catch {};
+ return err;
+ } else boot: {
// The addons the session's start finds (runtime/session.zig).
o.addons = pardes.Addon.scan();
// On no tape, as the session's start is (one recording to a
@@ -3055,8 +3062,12 @@ pub fn join(gpa: Allocator, j: *Joined, path: []const u8, session: []const u8, o
fn fromDump(gpa: Allocator, j: *Joined, o: pardes.Options, have: ?*Have, why: []u8, t0: u64, session: []const u8) ?*Replica {
var twice = false;
while (true) {
- const r = Replica.initDump(gpa, j.client, j.view, j.dump, o) catch |err| {
- _ = std.fmt.bufPrint(why, "the session's dump would not load: {t}\x00", .{err}) catch {};
+ var refused: std.ArrayList(u8) = .empty;
+ defer refused.deinit(gpa);
+ const r = Replica.made(gpa, j.client, j.view, o, j.dump, &refused) catch |err| {
+ // The loader's first words name the field it refused.
+ const first = refused.items[0..@min(400, std.mem.indexOfScalar(u8, refused.items, '\n') orelse refused.items.len)];
+ _ = std.fmt.bufPrint(why, "the session's dump would not load: {t}{s}{s}\x00", .{ err, if (first.len > 0) ": " else "", first }) catch {};
return null;
};
if (r.loaded(j.digest)) {
@@ -5096,6 +5107,34 @@ test "bytes: a kitty image shown by a file, a temporary file or shared memory is
try std.testing.expect(shm.shm_open(object, @bitCast(std.c.O{ .ACCMODE = .RDONLY }), 0) < 0);
}
+test "a join's dump whose length says more than its buffer holds is refused, the field named, never loaded" {
+ const gpa = std.testing.allocator;
+ const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host());
+ defer a.deinit();
+ // A column tag's room for one range, that range written as a dump
+ // writes its numbers, then how many it uses: one.
+ const tag = &a.core.view().col_tags[0];
+ tag.sels = try a.core.gpa.alloc(pardes.panes.Text.SelRange, 1);
+ tag.sels[0] = .{ .row = 0x1234567, .col = 0x2345678, .arow = 0x3456789, .acol = 0x456789a, .sticky = 0x56789ab };
+ tag.nsel = 1;
+ const was = Stepping.begin(&a.t, null);
+ const dumped = try pardes.dump.byteDump(a.core);
+ tape.resync(&a.t);
+ was.end();
+ defer a.core.gpa.free(dumped);
+ const range = std.mem.sliceAsBytes(&[_]i32{ 0x1234567, 0x2345678, 0x3456789, 0x456789a, 0x56789ab });
+ const at = (std.mem.indexOf(u8, dumped, range) orelse return error.NoRange) + range.len;
+ try std.testing.expectEqual(@as(u16, 1), std.mem.readInt(u16, dumped[at..][0..2], .little));
+ // As a damaged dump has it: seven, in the room for one.
+ std.mem.writeInt(u16, dumped[at..][0..2], 7, .little);
+ var j: Joined = .{ .fd = -1, .pid = 0, .client = 1, .view = 0, .gmtoff = 0, .dump = dumped };
+ var why: [600]u8 = @splat(0);
+ try std.testing.expect(fromDump(gpa, &j, .{ .cols = 80, .rows = 24 }, null, &why, 0, "") == null);
+ const words = std.mem.sliceTo(&why, 0);
+ try std.testing.expect(std.mem.startsWith(u8, words, "the session's dump would not load: BadDump: "));
+ try std.testing.expect(std.mem.indexOf(u8, words, "nsel says 7, past the 1 its buffer holds") != null);
+}
+
test "a replica joined from the session's dump replays the units after it" {
const gpa = std.testing.allocator;
const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host());
diff --git a/core/walk.zig b/core/walk.zig
index 46bfadc5..fd2970ef 100644
--- a/core/walk.zig
+++ b/core/walk.zig
@@ -185,6 +185,39 @@ pub fn lengthOf(comptime T: type, comptime name: []const u8) ?[]const u8 {
return null;
}
+/// How many `replica.len` pairs `T` has: a buffer, and the field saying how
+/// far it is written.
+fn pairs(comptime T: type) usize {
+ return if (@hasDecl(T, "replica") and @hasField(@TypeOf(T.replica), "len")) T.replica.len.len else 0;
+}
+
+/// Where `name` is among `T`'s pairs' buffers.
+fn pairAt(comptime T: type, comptime name: []const u8) ?usize {
+ inline for (0..comptime pairs(T)) |i| if (comptime std.mem.eql(u8, T.replica.len[i][0], name)) return i;
+ return null;
+}
+
+/// A length that says more than its buffer holds.
+const Past = struct { name: []const u8, says: usize, holds: usize };
+
+/// The first length of `v` past what its buffer holds, or null. A digest, a
+/// copy, a deinit and every use slice each pair's buffer as far as its length
+/// says, so a value read back (a tape, a dump, an image: bytes from another
+/// process or the disk) is held to it where it is decoded, every pair of every
+/// type at once, and refused when one says more: never walked. `held`: how
+/// many of each fixed array were read back (a dump writes one as far as its
+/// length said); null, each whole (a tape writes them whole). A slice's are
+/// its own.
+fn pastHeld(comptime T: type, v: *const T, held: ?*const [pairs(T)]usize) ?Past {
+ inline for (0..comptime pairs(T)) |i| {
+ const buffer = @field(v, T.replica.len[i][0]);
+ const holds = if (comptime @typeInfo(@TypeOf(buffer)) == .array) (if (held) |h| @min(h[i], buffer.len) else buffer.len) else buffer.len;
+ const says = lengthIn(v, T.replica.len[i][1]);
+ if (says > holds) return .{ .name = T.replica.len[i][1], .says = says, .holds = holds };
+ }
+ return null;
+}
+
/// Every name an annotation gives is a field: a rename cannot quietly put
/// a field back in the digest.
fn checkAnnotations(comptime T: type) void {
@@ -560,6 +593,7 @@ pub fn decode(comptime T: type, r: *Reader, a: std.mem.Allocator) TapeError!T {
try decodeError(F, r, &@field(out, name));
} else @field(out, name) = try decode(F, r, a);
}
+ if (pastHeld(T, &out, null) != null) return error.BadTape;
return out;
},
.@"union" => |u| {
@@ -1119,6 +1153,8 @@ pub const Loader = struct {
/// Where a field's annotation (`replica.alloc`) says its values are
/// made instead of `gpa`.
allocs: Allocators = .{},
+ /// How many elements the last array or slice read holds (`pastHeld`).
+ filled: usize = 0,
pub fn init(gpa: std.mem.Allocator, bytes: []const u8, table: []const u8) DecodeError!Self {
var l: Self = .{ .gpa = gpa, .own = gpa, .bytes = bytes, .arena = .init(gpa) };
@@ -1474,6 +1510,7 @@ pub const Loader = struct {
// them: integers and bools (an enum's numbers may not be the other's).
const bulk = if (comptime flat(E)) l.same or (comptime flatHash(E)) and s.kind == (comptime kindOf(E)) and
(s.kind == .bool or (s.bits == @bitSizeOf(E) and s.signed == (@typeInfo(E) == .int and @typeInfo(E).int.signedness == .signed))) else false;
+ defer l.filled = keep;
if (bulk) {
if (n > l.bytes.len) return error.EndOfDump;
@memcpy(std.mem.sliceAsBytes(out[0..keep]), try l.take(keep * @sizeOf(E)));
@@ -1506,13 +1543,17 @@ pub const Loader = struct {
const packed_struct = comptime @typeInfo(T).@"struct".layout == .@"packed";
const outer = l.field;
defer l.field = outer;
+ // How far each array a length cuts was read: none yet (one read in
+ // place holds what it held).
+ var held: [pairs(T)]usize = @splat(if (existing) std.math.maxInt(usize) else 0);
if (l.same) {
if (s.fields.len != names.len) return error.BadDump;
inline for (names, 0..) |field, k| {
l.field = field;
try l.oneField(T, field, s.fields[k].ty, out, packed_struct, existing);
+ if (comptime pairAt(T, field)) |i| held[i] = l.filled;
}
- return;
+ return l.heldTo(T, out, &held);
}
var found: std.StaticBitSet(@max(1, names.len)) = .empty;
var failed = false;
@@ -1527,7 +1568,9 @@ pub const Loader = struct {
found.set(at);
inline for (names, 0..) |field, i| if (i == at) {
l.field = field;
- l.oneField(T, field, f.ty, out, packed_struct, existing) catch |err| {
+ if (l.oneField(T, field, f.ty, out, packed_struct, existing)) {
+ if (comptime pairAt(T, field)) |p| held[p] = l.filled;
+ } else |err| {
if (err != error.Incompatible) return err;
const attr = comptime @typeInfo(T).@"struct".field_attrs[std.meta.fieldIndex(T, field).?];
if (comptime attr.default_value_ptr) |dp| {
@@ -1536,7 +1579,7 @@ pub const Loader = struct {
} else if (existing) {
l.noteField("its kind changed; left as it was", @typeName(T), field);
} else failed = true;
- };
+ }
};
}
// A field the writer did not have: its default (`fresh`), or
@@ -1551,6 +1594,15 @@ pub const Loader = struct {
}
};
if (failed) return error.Incompatible;
+ return l.heldTo(T, out, &held);
+ }
+
+ /// `out`'s lengths held to what their buffers hold as read (`pastHeld`):
+ /// the dump refused, the length named.
+ fn heldTo(l: *Self, comptime T: type, out: *const T, held: *const [pairs(T)]usize) DecodeError!void {
+ const past = pastHeld(T, out, held) orelse return;
+ l.note("{s}.{s} says {d}, past the {d} its buffer holds: refused", .{ @typeName(T), past.name, past.says, past.holds });
+ return error.BadDump;
}
fn oneField(l: *Self, comptime T: type, comptime field: []const u8, ty: u32, out: *T, comptime packed_struct: bool, existing: bool) DecodeError!void {
@@ -1653,15 +1705,14 @@ fn walkedField(comptime T: type, comptime field: []const u8) bool {
return false;
}
-/// A value `save` made, `gpa`'s; what was let go is said in `notes` when
-/// it is given.
+/// A value `save` made, `gpa`'s; what was let go, or why it was refused, is
+/// said in `notes` when it is given.
pub fn load(comptime T: type, gpa: std.mem.Allocator, bytes: []const u8, notes: ?*std.ArrayList(u8)) DecodeError!T {
var l = try Load(&.{T}).init(gpa, bytes);
defer l.deinit();
+ defer if (notes) |n| n.appendSlice(gpa, l.notes.items) catch {};
errdefer l.rollback();
- const v = try l.get(T);
- if (notes) |n| try n.appendSlice(gpa, l.notes.items);
- return v;
+ return l.get(T);
}
// ---- a dump as a database: the same walk, by name, into xitdb's maps ----
@@ -1914,6 +1965,8 @@ pub const Get = struct {
/// The field being read, for a note.
field: []const u8 = "",
allocs: Allocators = .{},
+ /// How many elements the last array read holds (`pastHeld`).
+ filled: usize = 0,
const Cursor = Mem.Cursor(.read_only);
pub const Error = error{ BadDump, Incompatible, OutOfMemory };
@@ -2311,21 +2364,22 @@ pub const Get = struct {
}
const got = try numbersAt(c, l.own);
defer l.own.free(got.bytes);
- _ = try convert(E, got.bytes, got.tag, out);
+ l.filled = @min(out.len, try convert(E, got.bytes, got.tag, out));
return;
}
const list = Mem.ArrayList(.read_only).init(c) catch return error.Incompatible;
try l.listInto(E, list, out);
}
- /// The list's elements into `out`, as many as fit; an element of an
- /// array of optional pointers (a session's panes) that cannot be read is
- /// left out, not the array.
+ /// The list's elements into `out`, as many as fit (`filled`); an element
+ /// of an array of optional pointers (a session's panes) that cannot be
+ /// read is left out, not the array.
fn listInto(l: *Get, comptime E: type, list: Mem.ArrayList(.read_only), out: []E) Error!void {
const droppable = comptime @typeInfo(E) == .optional and @typeInfo(@typeInfo(E).optional.child) == .pointer;
var failed = false;
var it = list.iterator() catch return error.BadDump;
var i: usize = 0;
+ defer l.filled = i;
while (it.next() catch return error.BadDump) |at| : (i += 1) {
if (i >= out.len) break;
try l.fresh(E, &out[i]);
@@ -2347,6 +2401,8 @@ pub const Get = struct {
const map = Mem.HashMap(.read_only).init(c) catch return error.Incompatible;
var found: std.StaticBitSet(@max(1, names.len)) = .empty;
var failed = false;
+ // How far each array a length cuts was read (Load's `fields`).
+ var held: [pairs(T)]usize = @splat(if (existing) std.math.maxInt(usize) else 0);
var it = map.iterator() catch return error.BadDump;
while (it.next() catch return error.BadDump) |kv_at| {
const kv = kv_at.readKeyValuePair() catch return error.BadDump;
@@ -2360,7 +2416,9 @@ pub const Get = struct {
found.set(at);
inline for (names, 0..) |field, i| if (i == at) {
l.field = field;
- l.oneField(T, field, kv.value_cursor, out, existing) catch |err| {
+ if (l.oneField(T, field, kv.value_cursor, out, existing)) {
+ if (comptime pairAt(T, field)) |p| held[p] = l.filled;
+ } else |err| {
if (err != error.Incompatible) return err;
const attr = comptime @typeInfo(T).@"struct".field_attrs[std.meta.fieldIndex(T, field).?];
if (comptime attr.default_value_ptr) |dp| {
@@ -2369,7 +2427,7 @@ pub const Get = struct {
} else if (existing) {
l.noteField("its kind changed; left as it was", @typeName(T), field);
} else failed = true;
- };
+ }
};
}
// A field the writer did not have (or held null at a null default):
@@ -2388,6 +2446,9 @@ pub const Get = struct {
};
};
if (failed) return error.Incompatible;
+ const past = pastHeld(T, out, &held) orelse return;
+ l.note("{s}.{s} says {d}, past the {d} its buffer holds: refused", .{ @typeName(T), past.name, past.says, past.holds });
+ return error.BadDump;
}
fn oneField(l: *Get, comptime T: type, comptime field: []const u8, c: Cursor, out: *T, existing: bool) Error!void {
@@ -2621,6 +2682,84 @@ test "a dump crosses builds: a field added takes its default, one removed is pas
try std.testing.expectEqual(Old.Color.blue, back.panes[0].?.color);
}
+test "a length past what its buffer holds is refused where it is read back (a tape, a dump, an image), its field named, never walked" {
+ // Text's undo (a fixed array a length cuts) and its ranges (room a
+ // length cuts): a digest, a copy and a deinit slice each that far.
+ const Ring = struct {
+ ring: [4]u8 = @splat(0),
+ ring_len: u8 = 0,
+ pub const replica = .{ .len = .{.{ "ring", "ring_len" }} };
+ };
+ const Room = struct {
+ room: []i32 = &.{},
+ room_len: u8 = 0,
+ pub const replica = .{ .len = .{.{ "room", "room_len" }} };
+ };
+ const gpa = std.testing.allocator;
+ var arena: std.heap.ArenaAllocator = .init(gpa);
+ defer arena.deinit();
+ const a = arena.allocator();
+
+ // A dump: the length is its last byte, after the ring's count and items.
+ const ring = try save(Ring, gpa, &.{ .ring = .{ 1, 2, 0, 0 }, .ring_len = 2 });
+ defer gpa.free(ring);
+ try std.testing.expectEqual(@as(u8, 2), (try load(Ring, a, ring, null)).ring_len);
+ // The notes are made where the load's values are.
+ var notes: std.ArrayList(u8) = .empty;
+ // Past the array, and within it but past the two the dump holds.
+ for ([_]u8{ 200, 5, 3 }) |says| {
+ ring[ring.len - 1] = says;
+ notes.clearRetainingCapacity();
+ try std.testing.expectError(error.BadDump, load(Ring, a, ring, &notes));
+ try std.testing.expect(std.mem.indexOf(u8, notes.items, "ring_len") != null);
+ }
+ var room = [_]i32{ 4, 5, 6 };
+ const roomy = try save(Room, gpa, &.{ .room = &room, .room_len = 2 });
+ defer gpa.free(roomy);
+ roomy[roomy.len - 1] = 3;
+ try std.testing.expectEqual(@as(u8, 3), (try load(Room, a, roomy, null)).room_len);
+ roomy[roomy.len - 1] = 4;
+ try std.testing.expectError(error.BadDump, load(Room, a, roomy, null));
+
+ // A tape: an array is taped whole, a slice as long as it is.
+ var buf: [64]u8 = undefined;
+ var w: std.Io.Writer = .fixed(&buf);
+ try encode(Ring, &.{ .ring = .{ 1, 2, 3, 4 }, .ring_len = 4 }, &w);
+ try encode(Room, &.{ .room = &room, .room_len = 3 }, &w);
+ try encode(Ring, &.{ .ring = .{ 1, 2, 3, 4 }, .ring_len = 5 }, &w);
+ try encode(Room, &.{ .room = &room, .room_len = 4 }, &w);
+ var r: Reader = .{ .bytes = w.buffered() };
+ _ = try decode(Ring, &r, a);
+ _ = try decode(Room, &r, a);
+ try std.testing.expectError(error.BadTape, decode(Ring, &r, a));
+ try std.testing.expectError(error.BadTape, decode(Room, &r, a));
+
+ // An image: written as far as the array holds, its length as it says.
+ var image: std.Io.Writer.Allocating = .init(gpa);
+ defer image.deinit();
+ var db = try Mem.init(std.Io.failing, .{ .buffer = &image, .file_id = 0 });
+ var put: Put = .{ .gpa = gpa };
+ defer put.deinit();
+ const Both = struct { ring: Ring, room: Room };
+ try db.runContext(struct {
+ put: *Put,
+ room: []i32,
+ pub fn run(ctx: @This(), cursor: *Mem.Cursor(.read_write)) !void {
+ const map = try Mem.HashMap(.read_write).init(cursor.*);
+ try ctx.put.member(map, "fits", Both, &.{ .ring = .{ .ring = .{ 1, 2, 3, 4 }, .ring_len = 4 }, .room = .{ .room = ctx.room, .room_len = 3 } });
+ try ctx.put.member(map, "ring", Ring, &.{ .ring = .{ 1, 2, 3, 4 }, .ring_len = 9 });
+ try ctx.put.member(map, "room", Room, &.{ .room = ctx.room, .room_len = 4 });
+ }
+ }{ .put = &put, .room = &room });
+ var get: Get = .init(a);
+ defer get.deinit();
+ const root = db.rootCursor().readOnly();
+ _ = try get.get(Both, (try Get.member(root, "fits")).?);
+ try std.testing.expectError(error.BadDump, get.get(Ring, (try Get.member(root, "ring")).?));
+ try std.testing.expect(std.mem.indexOf(u8, get.notes.items, "ring_len") != null);
+ try std.testing.expectError(error.BadDump, get.get(Room, (try Get.member(root, "room")).?));
+}
+
test "a dump that is not one, or is cut short, is refused" {
const gpa = std.testing.allocator;
const S = struct { a: u32, b: []const u8 };