summaryrefslogtreecommitdiff
path: root/core
diff options
context:
space:
mode:
authorGabriel Schneider <[email protected]>2026-11-23 23:27:56 -0300
committerGabriel Schneider <[email protected]>2026-11-23 23:32:29 -0300
commit5b4f790453c636ab10a0be2686008af7a67e0afe (patch)
tree59063fba659c0f69e8b79576532e955f20d6b1f3 /core
parent263b7d2e24f5bdad6a6a62b4a13bc74b8be68cb3 (diff)
downloadpardes-5b4f790453c636ab10a0be2686008af7a67e0afe.tar.gz
pardes-5b4f790453c636ab10a0be2686008af7a67e0afe.zip
walk: every count a byte dump or an image holds is held to the bytes it came in, and the fuzz reads the byte dump a join streams as a join does: core/fuzz.zig's dump fuzz had read two IMAGES (`dump.dumpBytes` is an image too), so the byte loader a client's join runs (`walk.Load`, before the session's digest is checked) was never fuzzed; now its two wholes are `dump.byteDump` read as a join reads it (`Road.join`: loaded, digested, let go) and the image read as a Restore or an Upgrade reads it (`Road.restore`: loaded, drawn), 4096 seeds and 1024 (seconds each). EACH SITE BELOW WAS A RUN OF IT FIRST, then the fix: the join road's seed 96, `Loader.readInt` on a same-build dump `@intCast` a byte-wide word into a narrower int (`integer does not fit`): `std.math.cast`, BadDump; the table's counts sized allocations of 240 GB (an enum's names, a u32 read): `Loader.entries`, each count held to the bytes left by the least an entry takes (a type 1, a name and value 18, a field 6); seed 456, `skip` over a damaged table where a struct is its own field recursed to a stack overflow (a segfault): `max_depth` 256 (a session's types nest about twenty); seed 1835, a same-build enum read with `@fromBackingInt` (`invalid enum value`): `std.enums.fromInt` (`enumFrom`'s rule), BadDump; the restore road's seed 672, an image's list count sized a 10 TB allocation (`Get.slice`): held to the slots the image's bytes hold; and its byte values read with no bound (`readBytesObjectAlloc(.., null)`: 12 EB asked): `walk.most` (the database's length) at each of `Get`'s reads and `Db.Read.open`'s session. Then the counts the fuzz did not reach, by the same rule and a test that fails without it (`integer overflow` in `initEmpty`'s and `skip`'s `bits + 63`): a bitset's count (`Loader.bitCount`, read and passed over; `Get`'s), a slice's count and an array's or a skip's loop held to the bytes LEFT (were the whole dump's, or none: a loop of 2^64 skips); test walk.zig "a bitset's count read back is held to the bytes left, read or passed over, in a dump and an image: never a size that overflows". OPEN, not done here: the image road past seed 1024 reaches xitdb's own reader (seed 1780: `switch on corrupt value` in xitdb `HashMap.init`, a slot's tag byte past its kinds, from `Db.Read.blobs`): a dependency's, for build/patches.zig and a report; a byte dump that loads but means nothing (a live view that is none: a Restore of an old byte-dump file draws it and panics in `Core.view`); references read back as another type (no-panic-1's `typeWord` sites, not reached in 4096 seeds)
Co-Authored-By: Claude Opus <[email protected]> Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T
Diffstat (limited to 'core')
-rw-r--r--core/Db.zig2
-rw-r--r--core/fuzz.zig29
-rw-r--r--core/walk.zig105
3 files changed, 112 insertions, 24 deletions
diff --git a/core/Db.zig b/core/Db.zig
index 254eb4a7..eb8ee20c 100644
--- a/core/Db.zig
+++ b/core/Db.zig
@@ -487,7 +487,7 @@ pub const Read = struct {
r.names = if (entry.getCursor(key("names")) catch null) |c| @constCast(c.readBytesAlloc(gpa, 4096) catch &.{}) else &.{};
errdefer if (r.names.len > 0) gpa.free(r.names);
const at = (entry.getCursor(key("session")) catch return error.NotADump) orelse return error.NotADump;
- const session: []u8 = @constCast(at.readBytesAlloc(gpa, null) catch |err| return if (err == error.OutOfMemory) error.OutOfMemory else error.NotADump);
+ const session: []u8 = @constCast(at.readBytesAlloc(gpa, pardes.walk.most(at)) catch |err| return if (err == error.OutOfMemory) error.OutOfMemory else error.NotADump);
var owned: std.ArrayList(u8) = .fromOwnedSlice(session);
r.session_buf = .fromArrayList(gpa, &owned);
errdefer r.session_buf.deinit();
diff --git a/core/fuzz.zig b/core/fuzz.zig
index f324a48e..0fce6f9d 100644
--- a/core/fuzz.zig
+++ b/core/fuzz.zig
@@ -711,7 +711,12 @@ fn damage(r: Random, b: []u8, n: usize) usize {
return n;
}
-fn loadSeed(whole: []const u8, seed: u64) !void {
+/// 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 drawn.
+const Road = enum { join, restore };
+
+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 };
@@ -728,8 +733,13 @@ fn loadSeed(whole: []const u8, seed: u64) !void {
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 {};
+ switch (road) {
+ .join => _ = pardes.tape.digestOf(q),
+ .restore => {
+ _ = 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);
@@ -739,13 +749,16 @@ test "a dump and an image cut, flipped and grown: refused or loaded, never a pan
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);
+ // 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.image(p, "fuzz");
+ const image = try pardes.dump.dumpBytes(p);
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);
+ // Seconds a road. The image's past 1024 seeds reach xitdb's own reader
+ // (a slot's tag past its kinds: a `switch` on it), a dependency's.
+ for ([_][]const u8{ bytes, image }, [_]Road{ .join, .restore }, [_]u64{ 4096, 1024 }) |whole, road, n| {
+ try loadSeed(whole, road, 0);
+ for (1..n + 1) |seed| try loadSeed(whole, road, seed);
}
}
diff --git a/core/walk.zig b/core/walk.zig
index fd2970ef..02e46454 100644
--- a/core/walk.zig
+++ b/core/walk.zig
@@ -1125,6 +1125,9 @@ pub fn Load(comptime roots: []const type) type {
};
}
+/// How deep a dump's types nest, at most: a session's are about twenty.
+const max_depth = 256;
+
/// `Load`'s reader, one for every root set: it reads by the dump's own
/// table, and this build's (`table`) only says whether the two are one.
pub const Loader = struct {
@@ -1155,6 +1158,8 @@ pub const Loader = struct {
allocs: Allocators = .{},
/// How many elements the last array or slice read holds (`pastHeld`).
filled: usize = 0,
+ /// How deep `skip` is in the dump's own types.
+ depth: u16 = 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) };
@@ -1203,14 +1208,29 @@ pub const Loader = struct {
return countOf(try l.scalar(u64));
}
+ /// A bitset's count of bits, its words no more than the bytes left.
+ fn bitCount(l: *Self) DecodeError!usize {
+ const n = try l.count();
+ if (n / 64 > (l.bytes.len - l.at) / 8) return error.EndOfDump;
+ return n;
+ }
+
fn name(l: *Self) DecodeError![]const u8 {
return l.take(try l.scalar(u16));
}
+ /// The count of a table's entries of `each` bytes at least read next,
+ /// no more than the bytes left hold: a damaged one sizes nothing.
+ fn entries(l: *Self, each: usize) DecodeError!usize {
+ const n = try l.scalar(u32);
+ if (n > (l.bytes.len - l.at) / each) return error.BadDump;
+ return n;
+ }
+
fn readTable(l: *Self) DecodeError!void {
const a = l.arena.allocator();
- const n = try l.scalar(u32);
- if (n > l.bytes.len) return error.BadDump;
+ // A type is its kind's byte at least; a name its length's two.
+ const n = try l.entries(1);
l.src = try a.alloc(SrcType, n);
for (l.src) |*t| {
const k = std.enums.fromInt(Kind, (try l.take(1))[0]) orelse return error.BadDump;
@@ -1224,7 +1244,7 @@ pub const Loader = struct {
.@"enum" => {
t.signed = (try l.take(1))[0] != 0;
t.bits = try l.scalar(u16);
- const list = try a.alloc(SrcField, try l.scalar(u32));
+ const list = try a.alloc(SrcField, try l.entries(2 + 16));
for (list) |*f| f.* = .{ .name = try l.name(), .value = try l.scalar(i128) };
t.fields = list;
},
@@ -1234,9 +1254,7 @@ pub const Loader = struct {
},
.optional, .one, .slice, .prefix, .error_union => t.child = try l.scalar(u32),
.@"struct", .@"union" => {
- const nfields = try l.scalar(u32);
- if (nfields > l.bytes.len) return error.BadDump;
- const list = try a.alloc(SrcField, nfields);
+ const list = try a.alloc(SrcField, try l.entries(2 + 4));
for (list) |*f| f.* = .{ .name = try l.name(), .ty = try l.scalar(u32) };
t.fields = list;
},
@@ -1308,7 +1326,8 @@ pub const Loader = struct {
if (l.same) {
const info = @typeInfo(I).int;
const W = @Int(info.signedness, intBytes(info.bits) * 8);
- return @intCast(try l.scalar(W));
+ // A number its own width holds: a u21's byte-wide word past it is no u21.
+ return std.math.cast(I, try l.scalar(W)) orelse error.BadDump;
}
const n = intBytes(s.bits);
const raw = try l.take(n);
@@ -1359,7 +1378,9 @@ pub const Loader = struct {
.@"enum" => {
const e = @typeInfo(T).@"enum";
if (l.same) {
- out.* = @fromBackingInt(@intCast(try l.readInt(e.tag_type, s)));
+ // A number one of its names has (`enumFrom`'s rule).
+ const tag = try l.readInt(e.tag_type, s);
+ out.* = if (e.mode == .nonexhaustive) @fromBackingInt(tag) else std.enums.fromInt(T, tag) orelse return error.BadDump;
return;
}
const n = try l.readInt(i128, s);
@@ -1465,7 +1486,7 @@ pub const Loader = struct {
if (comptime @hasDecl(T, "dumpFree")) try l.customs.append(l.own, .{ .ptr = out, .gpa = l.gpa, .free = @ptrCast(&T.dumpFree) });
},
.bitset => {
- const bits = try l.count();
+ const bits = try l.bitCount();
out.* = try .initEmpty(l.gpa, bits);
const words = (bits + @bitSizeOf(usize) - 1) / @bitSizeOf(usize);
if (words > 0) @memcpy(std.mem.sliceAsBytes(out.masks[0..words]), try l.take(words * @sizeOf(usize)));
@@ -1488,7 +1509,7 @@ pub const Loader = struct {
if (try l.ref()) |again| return @as([*]E, @ptrCast(@alignCast(again.ptr)))[0 .. again.len / @max(1, @sizeOf(E))];
const n = try l.count();
if (n == 0) return &.{};
- if (n > l.bytes.len) return error.BadDump;
+ if (n > l.bytes.len - l.at) return error.EndOfDump;
const many = try l.gpa.alloc(E, n);
const at = l.made(std.mem.sliceAsBytes(many), .of(E)) catch |err| {
l.gpa.free(many);
@@ -1521,6 +1542,8 @@ pub const Loader = struct {
// cannot be read is left out, not the array.
const droppable = comptime @typeInfo(E) == .optional and @typeInfo(@typeInfo(E).optional.child) == .pointer;
var failed = false;
+ // Each element a byte at least: a damaged count starts no loop.
+ if (n > l.bytes.len - l.at) return error.EndOfDump;
for (0..try countOf(n)) |i| {
if (i >= keep) {
try l.skip(ty);
@@ -1634,6 +1657,11 @@ pub const Loader = struct {
/// The source's value of type `ty` passed over.
fn skip(l: *Self, ty: u32) DecodeError!void {
+ // The dump's table says what its types hold: a damaged one can make
+ // a struct its own field, a recursion as deep as the stack.
+ if (l.depth == max_depth) return error.BadDump;
+ l.depth += 1;
+ defer l.depth -= 1;
const s = l.src[ty];
switch (s.kind) {
.skip, .void => {},
@@ -1667,7 +1695,7 @@ pub const Loader = struct {
_ = try l.name();
},
.custom => _ = try l.take(try l.count()),
- .bitset => _ = try l.take((try l.count() + 63) / 64 * 8),
+ .bitset => _ = try l.take((try l.bitCount() + 63) / 64 * 8),
}
}
@@ -1679,6 +1707,7 @@ pub const Loader = struct {
_ = try l.take(@intCast(n * size));
return;
}
+ if (n > l.bytes.len - l.at) return error.EndOfDump;
for (0..try countOf(n)) |_| try l.skip(ty);
}
};
@@ -1774,6 +1803,12 @@ const wide_tag = "w8".*;
const custom_tag = "cu".*;
const bitset_tag = "bs".*;
+/// The most bytes a value read at the cursor `c` can be: its database's. A
+/// damaged length (an image's, cut or flipped) sizes no allocation past them.
+pub fn most(c: anytype) usize {
+ return std.math.cast(usize, c.db.core.length() catch 0) orelse std.math.maxInt(usize);
+}
+
fn typeWord(comptime T: type) u64 {
return comptime std.hash.Wyhash.hash(0, @typeName(T));
}
@@ -2195,7 +2230,7 @@ pub const Get = struct {
},
.err, .error_union => unreachable,
.custom => {
- const got = c.readBytesObjectAlloc(l.own, null) catch return error.Incompatible;
+ const got = c.readBytesObjectAlloc(l.own, most(c)) catch return error.Incompatible;
defer l.own.free(got.value);
T.dumpRead(out, l.gpa, got.value) catch |err| {
if (err == error.OutOfMemory) return error.OutOfMemory;
@@ -2205,10 +2240,11 @@ pub const Get = struct {
if (comptime @hasDecl(T, "dumpFree")) try l.customs.append(l.own, .{ .ptr = out, .gpa = l.gpa, .free = @ptrCast(&T.dumpFree) });
},
.bitset => {
- const got = c.readBytesObjectAlloc(l.own, null) catch return error.Incompatible;
+ const got = c.readBytesObjectAlloc(l.own, most(c)) catch return error.Incompatible;
defer l.own.free(got.value);
if (got.value.len < 8) return error.BadDump;
const bits = countOf(std.mem.bytesToValue(u64, got.value[0..8])) catch return error.BadDump;
+ if (bits / 64 > got.value.len / 8) return error.BadDump;
const words = (bits + @bitSizeOf(usize) - 1) / @bitSizeOf(usize);
if (got.value.len != 8 + words * @sizeOf(usize)) return error.BadDump;
out.* = try .initEmpty(l.gpa, bits);
@@ -2271,7 +2307,7 @@ pub const Get = struct {
/// The numbers' bytes at `c` and their format tag, `alloc`'s.
fn numbersAt(c: Cursor, alloc: std.mem.Allocator) Error!struct { bytes: []u8, tag: [2]u8 } {
- const got = c.readBytesObjectAlloc(alloc, null) catch |err| return if (err == error.OutOfMemory) error.OutOfMemory else error.Incompatible;
+ const got = c.readBytesObjectAlloc(alloc, most(c)) catch |err| return if (err == error.OutOfMemory) error.OutOfMemory else error.Incompatible;
const bytes: []u8 = @constCast(got.value);
const tag = got.format_tag orelse {
alloc.free(bytes);
@@ -2326,6 +2362,9 @@ pub const Get = struct {
const list = Mem.ArrayList(.read_only).init(c) catch return error.Incompatible;
const n = countOf(list.count() catch return error.BadDump) catch return error.BadDump;
if (n == 0) return &.{};
+ // No more than the image's bytes hold slots for: a damaged count
+ // sizes nothing.
+ if (n > (c.db.core.length() catch return error.BadDump) / (@bitSizeOf(xitdb.Slot) / 8)) return error.BadDump;
const many = try l.gpa.alloc(E, n);
const at = l.keep(std.mem.sliceAsBytes(many), .of(E), slot) catch |err| {
l.gpa.free(many);
@@ -2346,7 +2385,7 @@ pub const Get = struct {
if (!std.mem.eql(u8, &tag, &blob_tag) or got.value.len != 32) return null;
const texts = l.blobs orelse return error.BadDump;
const at = (texts.getCursor(std.mem.readInt(u256, got.value[0..32], .big)) catch return error.BadDump) orelse return error.BadDump;
- const text = at.readBytesAlloc(l.gpa, null) catch |err| return if (err == error.OutOfMemory) error.OutOfMemory else error.BadDump;
+ const text = at.readBytesAlloc(l.gpa, most(at)) catch |err| return if (err == error.OutOfMemory) error.OutOfMemory else error.BadDump;
const bytes: []u8 = @constCast(text);
_ = l.keep(bytes, .@"1", slot) catch |err| {
l.gpa.free(bytes);
@@ -2760,6 +2799,42 @@ test "a length past what its buffer holds is refused where it is read back (a ta
try std.testing.expectError(error.BadDump, get.get(Room, (try Get.member(root, "room")).?));
}
+test "a bitset's count read back is held to the bytes left, read or passed over, in a dump and an image: never a size that overflows" {
+ const gpa = std.testing.allocator;
+ const B = struct { bits: std.DynamicBitSetUnmanaged = .{}, after: []const u8 = "" };
+ var b: B = .{ .bits = try .initEmpty(gpa, 70), .after = "x" };
+ defer b.bits.deinit(gpa);
+ var arena: std.heap.ArenaAllocator = .init(gpa);
+ defer arena.deinit();
+ const a = arena.allocator();
+ const bytes = try save(B, gpa, &b);
+ defer gpa.free(bytes);
+ // The bits' count, two words, then the slice's reference, count and byte.
+ const at = bytes.len - (8 + 16 + 4 + 8 + 1);
+ try std.testing.expectEqual(@as(u64, 70), std.mem.readInt(u64, bytes[at..][0..8], .little));
+ std.mem.writeInt(u64, bytes[at..][0..8], std.math.maxInt(u64), .little);
+ try std.testing.expectError(error.EndOfDump, load(B, a, bytes, null));
+ // Passed over by a build without the field.
+ const Without = struct { after: []const u8 = "" };
+ try std.testing.expectError(error.EndOfDump, load(Without, a, bytes, null));
+ // An image's: the bytes a field of that name holds.
+ 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 Raw = struct { bits: []const u8 };
+ try db.runContext(struct {
+ put: *Put,
+ pub fn run(ctx: @This(), cursor: *Mem.Cursor(.read_write)) !void {
+ try ctx.put.member(try Mem.HashMap(.read_write).init(cursor.*), "b", Raw, &.{ .bits = &@as([8]u8, @splat(0xff)) });
+ }
+ }{ .put = &put });
+ var get: Get = .init(a);
+ defer get.deinit();
+ try std.testing.expectError(error.BadDump, get.get(B, (try Get.member(db.rootCursor().readOnly(), "b")).?));
+}
+
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 };