diff options
| author | Gabriel Schneider <[email protected]> | 2026-11-23 22:53:42 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-11-23 23:27:56 -0300 |
| commit | 263b7d2e24f5bdad6a6a62b4a13bc74b8be68cb3 (patch) | |
| tree | f6f288c54222bd8b525a00a08ac6a3527ff17597 /core/walk.zig | |
| parent | dde58f770995dcbc929708048a6e0f390c70f8af (diff) | |
| download | pardes-263b7d2e24f5bdad6a6a62b4a13bc74b8be68cb3.tar.gz pardes-263b7d2e24f5bdad6a6a62b4a13bc74b8be68cb3.zip | |
walk: a length past what its buffer holds is refused where a tape, a dump or an image is decoded, its field named, never walked: merge65's core-test crashed in core/fuzz.zig's own dump fuzz (`index out of bounds: index 4503599627370496, len 64` at core/Text.zig:130, `Text.deinit` slicing `ed_redo[0..ed_redo_len]`, from views.zig `freeView`): a damaged dump was loaded with a length past its buffer, and the core's own deinit panicked (a digest, a copy and every use slice the same way); the layer's new fields moved the dump's layout so the fuzz's seeds reach it now, but the fault is the decoders': each read a `replica.len` pair's length as just a number. THE RULE, ONCE, for every pair of every type (the comptime walk lists them: `T.replica.len`, what the digest's `hash`, `fieldDigests`, the dump writer and rollback.zig already go by): `pastHeld` (the first length of a value past what its buffer holds: a slice's its own length, a fixed array's how many were read back, a dump writing one only as far as its length said, else whole), called where a struct's fields are decoded: `decode` (the tape: BadTape), `Loader.fields` (the byte dump, both of its paths: `heldTo`, BadDump) and `Get.fields` (the image: BadDump), the count read kept by each reader's `elements`/`listInto` (`filled`); the refusal's words name the field (`Text.ed_redo_len says N, past the 64 its buffer holds: refused`) and reach the user: `walk.load` and dump.zig `loadKnowing`/`loadImage` hand a refusal's notes out as they hand out a load's, and replica.zig `fromDump` says them (`the session's dump would not load: BadDump: <field> says ...`; `Replica.made` copies them out of the epoch); TESTS FIRST, each failing with the check out (run: the walk test loads `ring_len = 200`, the replica test panics `index out of bounds: index 7, len 1`): walk.zig "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" (a ring a length cuts and a room a length cuts, each through `encode`/`decode`, `save`/`load` with its length byte set past the array and past what the dump held, and `Put`/`Get`), replica.zig "a join's dump whose length says more than its buffer holds is refused, the field named, never loaded" (a column tag's `nsel` set to 7 in a byte dump's bytes, `fromDump`'s words); the fuzz as merged passes on it; the user's case: a Restore, an Upgrade or a join of a damaged dump is refused in words, the session going on (it ended at the first deinit or digest)
Co-Authored-By: Claude Opus <[email protected]>
Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T
Diffstat (limited to 'core/walk.zig')
| -rw-r--r-- | core/walk.zig | 167 |
1 files changed, 153 insertions, 14 deletions
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, ¬es)); + 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 }; |
