summaryrefslogtreecommitdiff
path: root/src/host/memory.zig
diff options
context:
space:
mode:
Diffstat (limited to 'src/host/memory.zig')
-rw-r--r--src/host/memory.zig558
1 files changed, 116 insertions, 442 deletions
diff --git a/src/host/memory.zig b/src/host/memory.zig
index 044fc3b..2749ea1 100644
--- a/src/host/memory.zig
+++ b/src/host/memory.zig
@@ -1,13 +1,12 @@
//! Sketch memory by lifetime.
//!
-//! `StateFile`: one `MAP_SHARED` file holding the live state, plus a header
-//! describing the layout, so the state outlives restarts,
-//! a probe can read it from another process, and a reload with a changed
-//! layout can carry the old values over field by field.
+//! `State`: process memory in the layout the sketch declares; a reload
+//! with a changed layout carries the old values over field by field. It
+//! outlives the process in the sessions database (Sessions.zig), whose
+//! stretches keep its layout in the header format below.
//!
-//! `StoreFile`: a heap in a file, mapped at the same address in every run,
-//! so what it holds may point into it: the sketch's `Store` and everything
-//! allocated for it outlive restarts.
+//! `OldState`: a state file from before the database held the present,
+//! read once to import it.
//!
//! `Session`: this process's memory, kept across reloads.
const std = @import("std");
@@ -18,7 +17,7 @@ const field_value = @import("fields.zig");
pub const page = std.heap.page_size_min;
pub const header_len = 64 * 1024;
-/// One slot, the live state: snapshots are marks in the sessions database.
+/// A layout header, and an old file's one slot, the live state.
pub const file_magic = "SKETCH03".*;
/// Before sessions: slot 0 live and 1..7 snapshots (`old_slot_count`), which
/// the host imports as marks and then drops (`dropSnapshots`).
@@ -291,167 +290,93 @@ fn remapEnum(from: Layout.Leaf, old: []const u8, to: Layout.Leaf, new: []u8) boo
return true;
}
-pub const StateFile = struct {
- fd: posix.fd_t,
- map: []align(page) u8,
- /// 1, or `old_slot_count` in a file from before sessions.
- slots: usize = 1,
- /// Layout of the bytes in the file, owned by `arena`.
- layout: Layout,
+/// Live State: page aligned, in the running sketch's layout; `header` is
+/// that layout as `layoutOf` reads it back, for the sessions' stretches.
+pub const State = struct {
+ bytes: []align(page) u8 = &.{},
+ layout: Layout = .{},
+ header: []const u8 = "",
+ /// Owns `layout` and `header`.
arena: std.heap.ArenaAllocator,
- /// Opens or creates `path`. A new (empty) file has no layout and no used
- /// slots: the first `adopt` fills it. A file that is not a state file
- /// this host can read is refused, never truncated: it may be someone's
- /// work, written by another build.
- pub fn open(gpa: std.mem.Allocator, path: []const u8) !StateFile {
- const fd = try posix.openat(posix.AT.FDCWD, path, .{ .ACCMODE = .RDWR, .CREAT = true }, 0o600);
- errdefer _ = posix.system.close(fd);
- var self: StateFile = .{ .fd = fd, .map = &.{}, .layout = .{}, .arena = .init(gpa) };
- errdefer self.arena.deinit();
- const len = try fileSize(fd);
- if (len > 0) {
- if (len < header_len) return error.NotAStateFile;
- self.map = try mapFile(fd, @intCast(len), .{ .READ = true, .WRITE = true });
- errdefer posix.munmap(self.map);
- try self.check();
- self.layout = try readLayout(self.arena.allocator(), self.map) orelse .{};
- return self;
- }
- try self.resize(0);
- self.header().* = .{ .size = 0, .alignment = 1, .hash = 0, .stride = 0, .used = 0, .field_count = 0, .strings_len = 0 };
- return self;
+ pub fn init(gpa: std.mem.Allocator) State {
+ return .{ .arena = .init(gpa) };
}
- pub fn close(self: *StateFile) void {
- if (self.map.len != 0) posix.munmap(self.map);
- _ = posix.system.close(self.fd);
+ pub fn deinit(self: *State, gpa: std.mem.Allocator) void {
+ gpa.free(self.bytes);
self.arena.deinit();
}
- pub fn header(self: *StateFile) *Header {
- return @ptrCast(self.map.ptr);
- }
-
- /// The header and the layout after it, as `readLayout` reads them back.
- pub fn layoutBytes(self: *StateFile) []const u8 {
- const h = self.header();
- return self.map[0 .. @sizeOf(Header) + @as(usize, h.field_count) * @sizeOf(StoredField) + h.strings_len];
+ pub fn live(self: *State) []align(page) u8 {
+ return self.bytes[0..self.layout.size];
}
- pub fn slot(self: *StateFile, index: usize) []align(page) u8 {
- std.debug.assert(index < self.slots);
- const h = self.header();
- const start = header_len + index * h.stride;
- return @alignCast(self.map[start..][0..h.size]);
+ /// Makes State hold `new`'s layout: a new allocation of its defaults
+ /// (`defaults`), then every leaf `migrate` keeps of the old State. Null
+ /// when the layout is unchanged, or there was none.
+ pub fn adopt(self: *State, gpa: std.mem.Allocator, new: abi.Layout, defaults: *const fn (abi.Memory, [*]u8) callconv(.c) void) !?Migration {
+ const first = self.bytes.len == 0;
+ if (!first and self.layout.hash == new.hash and self.layout.size == new.size) return null;
+ var arena: std.heap.ArenaAllocator = .init(gpa);
+ errdefer arena.deinit();
+ const layout = try Layout.copy(arena.allocator(), new);
+ const region = try arena.allocator().alignedAlloc(u8, .of(Header), header_len);
+ @memset(region, 0);
+ const h: *Header = @ptrCast(region.ptr);
+ h.* = .{ .size = new.size, .alignment = new.alignment, .hash = new.hash, .stride = std.mem.alignForward(usize, @max(new.size, 1), page), .used = 1, .field_count = 0, .strings_len = 0 };
+ try writeLayout(region, layout);
+ const bytes = try gpa.alignedAlloc(u8, .fromByteUnits(page), @max(new.size, 1));
+ @memset(bytes, 0);
+ defaults(.state, bytes.ptr);
+ const m = if (first) null else migrate(self.layout, self.live(), layout, bytes);
+ self.deinit(gpa);
+ self.* = .{ .bytes = bytes, .layout = layout, .header = region[0 .. @sizeOf(Header) + @as(usize, h.field_count) * @sizeOf(StoredField) + h.strings_len], .arena = arena };
+ return m;
}
+};
- pub fn used(self: *StateFile, index: usize) bool {
- return self.header().used & (@as(u32, 1) << @intCast(index)) != 0;
- }
-
- pub fn markUsed(self: *StateFile, index: usize, value: bool) void {
- const bit = @as(u32, 1) << @intCast(index);
- if (value) self.header().used |= bit else self.header().used &= ~bit;
- }
-
- pub const Adoption = union(enum) {
- unchanged,
- created,
- migrated: Migration,
- };
-
- /// Makes the file hold `new`'s layout. Used slots are migrated: `defaults`
- /// writes the new default values, then unchanged fields are copied over.
- pub fn adopt(self: *StateFile, gpa: std.mem.Allocator, new: abi.Layout, defaults: *const fn (abi.Memory, [*]u8) callconv(.c) void) !Adoption {
- if (self.layout.hash == new.hash and self.layout.size == new.size and self.header().used & 1 != 0) {
- // Same type, older header: describe it again, bytes untouched.
- if (std.mem.eql(u8, &self.header().magic, &file_magic_v1)) {
- var kept = self.arena;
- defer kept.deinit();
- self.arena = .init(gpa);
- self.layout = try Layout.copy(self.arena.allocator(), new);
- try writeLayout(self.map[0..header_len], self.layout);
- self.header().magic = file_magic_v2;
- }
- return .unchanged;
- }
- const had_state = self.header().used & 1 != 0;
-
- // Keep the old bytes and layout while the file is rebuilt.
- var old_arena: std.heap.ArenaAllocator = .init(gpa);
- defer old_arena.deinit();
- const old_layout = self.layout;
- var old_slots: [old_slot_count]?[]u8 = @splat(null);
- for (old_slots[0..self.slots], 0..) |*copy, i| {
- if (self.used(i)) copy.* = try old_arena.allocator().dupe(u8, self.slot(i));
- }
- const old_used = self.header().used;
- // `old_layout` points into `self.arena`: move it aside before resetting.
- var kept = self.arena;
- defer kept.deinit();
- self.arena = .init(gpa);
-
- self.layout = try Layout.copy(self.arena.allocator(), new);
- const stride = std.mem.alignForward(usize, @max(new.size, 1), page);
- try self.resize(stride);
- const h = self.header();
- h.* = .{ .magic = if (self.slots == 1) file_magic else file_magic_v2, .size = new.size, .alignment = new.alignment, .hash = new.hash, .stride = stride, .used = old_used, .field_count = 0, .strings_len = 0 };
- try writeLayout(self.map[0..header_len], self.layout);
+/// A state file from before the sessions database held the present: a
+/// layout header, then one slot (`file_magic`), or eight (`file_magic_v2`,
+/// `file_magic_v1`), the first live State and the others snapshots. Mapped
+/// read-only: imported once, never changed.
+pub const OldState = struct {
+ map: []align(page) const u8,
+ slots: usize,
- var total: Migration = .{};
- for (old_slots, 0..) |maybe_old, i| {
- const old = maybe_old orelse continue;
- const bytes = self.slot(i);
- @memset(bytes, 0);
- defaults(.state, bytes.ptr);
- const m = migrate(old_layout, old, self.layout, bytes);
- total.kept += m.kept;
- if (i == 0) total.reset = m.reset;
- }
- if (!had_state) {
- self.markUsed(0, false);
- return .created;
- }
- return .{ .migrated = total };
+ /// error.FileNotFound when `path` is missing or empty; a file that is
+ /// no state file this host reads is refused.
+ pub fn open(path: []const u8) !OldState {
+ const map = mapReadOnly(path);
+ if (map.len == 0) return error.FileNotFound;
+ errdefer posix.munmap(map);
+ if (map.len < header_len) return error.NotAStateFile;
+ const h: *const Header = @ptrCast(map.ptr);
+ const slots: usize = if (std.mem.eql(u8, &h.magic, &file_magic)) 1 else if (std.mem.eql(u8, &h.magic, &file_magic_v2) or std.mem.eql(u8, &h.magic, &file_magic_v1)) old_slot_count else return error.NotAStateFile;
+ if (map.len < header_len + slots * h.stride or h.size > h.stride) return error.CorruptStateFile;
+ return .{ .map = map, .slots = slots };
}
- /// Makes a file from before sessions one of a single slot, its
- /// snapshots (imported as marks by now) dropped.
- pub fn dropSnapshots(self: *StateFile) !void {
- if (self.slots == 1) return;
- const stride = self.header().stride;
- self.slots = 1;
- try self.resize(stride);
- self.header().magic = file_magic;
- self.header().used &= 1;
+ pub fn close(self: OldState) void {
+ posix.munmap(self.map);
}
- fn check(self: *StateFile) !void {
- const h = self.header();
- if (std.mem.eql(u8, &h.magic, &file_magic)) {
- self.slots = 1;
- } else if (std.mem.eql(u8, &h.magic, &file_magic_v2) or std.mem.eql(u8, &h.magic, &file_magic_v1)) {
- self.slots = old_slot_count;
- } else return error.NotAStateFile;
- if (self.map.len < header_len + self.slots * h.stride or h.size > h.stride) return error.CorruptStateFile;
+ /// The header and layout, as `restore` and `layoutOf` take them.
+ pub fn layoutBytes(self: OldState) []const u8 {
+ return self.map[0..header_len];
}
- fn resize(self: *StateFile, stride: usize) !void {
- const len = header_len + self.slots * stride;
- if (self.map.len != 0) posix.munmap(self.map);
- self.map = &.{};
- switch (posix.errno(posix.system.ftruncate(self.fd, @intCast(len)))) {
- .SUCCESS => {},
- else => |err| return posix.unexpectedErrno(err),
- }
- self.map = try mapFile(self.fd, len, .{ .READ = true, .WRITE = true });
+ /// Slot `i`'s State, null when the slot is unused.
+ pub fn slot(self: OldState, i: usize) ?[]const u8 {
+ const h: *const Header = @ptrCast(self.map.ptr);
+ if (h.used & (@as(u32, 1) << @intCast(i)) == 0) return null;
+ return self.map[header_len + i * h.stride ..][0..h.size];
}
};
/// Fills `live` (laid out as `to`) from `image`, state kept in another
-/// layout, described by `layout_bytes` (a header as `StateFile.layoutBytes`
-/// gives it): `defaults`, then every leaf `migrate` keeps. Returns the
+/// layout, described by `layout_bytes` (a header as `State.header` holds
+/// it): `defaults`, then every leaf `migrate` keeps. Returns the
/// image's layout, `arena`'s.
pub fn restore(arena: std.mem.Allocator, layout_bytes: []const u8, image: []const u8, to: Layout, live: []u8, defaults: *const fn (abi.Memory, [*]u8) callconv(.c) void) !Layout {
const from = try layoutOf(arena, layout_bytes);
@@ -462,7 +387,7 @@ pub fn restore(arena: std.mem.Allocator, layout_bytes: []const u8, image: []cons
return from;
}
-/// The layout in a header as `StateFile.layoutBytes` gives it, `arena`'s.
+/// The layout in a header as `State.header` holds it, `arena`'s.
pub fn layoutOf(arena: std.mem.Allocator, layout_bytes: []const u8) !Layout {
if (layout_bytes.len < @sizeOf(Header) or layout_bytes.len > header_len) return error.CorruptKeyframe;
const region = try arena.alignedAlloc(u8, .of(Header), header_len);
@@ -515,14 +440,14 @@ fn writeLayout(region: []u8, layout: Layout) !void {
h.strings_len = @intCast(strings);
}
-/// The layout stored in a state or store file's header, or null if it has
-/// none. Reads both formats, by magic: a v1 header (`file_magic_v1`,
-/// `store_layout_magic_v1`) has no element leaves, so its arrays are whole
-/// leaves only, which migrate while their type is unchanged.
+/// The layout stored in a state file's header, or null if it has none.
+/// Reads both formats, by magic: a v1 header (`file_magic_v1`) has no
+/// element leaves, so its arrays are whole leaves only, which migrate while
+/// their type is unchanged.
pub fn readLayout(arena: std.mem.Allocator, map: []const u8) !?Layout {
const h: *const Header = @ptrCast(@alignCast(map.ptr));
if (h.hash == 0 and h.field_count == 0) return null;
- const v1 = std.mem.eql(u8, &h.magic, &file_magic_v1) or std.mem.eql(u8, &h.magic, &store_layout_magic_v1);
+ const v1 = std.mem.eql(u8, &h.magic, &file_magic_v1);
const stride: usize = if (v1) @sizeOf(StoredFieldV1) else @sizeOf(StoredField);
const strings_start = @sizeOf(Header) + @as(usize, h.field_count) * stride;
if (strings_start + h.strings_len > header_len or map.len < header_len) return error.CorruptHeader;
@@ -560,10 +485,6 @@ pub fn readLayout(arena: std.mem.Allocator, map: []const u8) !?Layout {
return .{ .size = h.size, .alignment = h.alignment, .hash = h.hash, .fields = leaves };
}
-pub fn mapFile(fd: posix.fd_t, len: usize, prot: posix.PROT) ![]align(page) u8 {
- return posix.mmap(null, len, prot, .{ .TYPE = .SHARED }, fd, 0);
-}
-
pub fn fileSize(fd: posix.fd_t) !u64 {
var stat: linux.Statx = undefined;
switch (linux.errno(linux.statx(fd, "", linux.AT.EMPTY_PATH, .{ .SIZE = true }, &stat))) {
@@ -582,208 +503,6 @@ pub fn mapReadOnly(path: []const u8) []align(page) const u8 {
return posix.mmap(null, @intCast(len), .{ .READ = true }, .{ .TYPE = .SHARED }, fd, 0) catch &.{};
}
-/// Where every store is mapped, in every process: far from where Linux puts
-/// executables (0x55...) and mappings (0x7f...).
-pub const store_base: usize = 0x2000_0000_0000;
-/// The most a store can grow to. Only reserved: pages exist as they are used.
-pub const store_reserve: usize = 64 << 30;
-/// The allocator's record (`Meta`); unchanged by the layout format.
-pub const store_magic = "SKSTORE1".*;
-/// The store's layout header, like `file_magic` and `file_magic_v1`.
-pub const store_layout_magic = "SKSTORE2".*;
-pub const store_layout_magic_v1 = "SKSTORE1".*;
-/// The layout region is a state file header; the allocator's own record
-/// follows, then the heap.
-const meta_offset = header_len;
-const heap_offset = 2 * header_len;
-
-/// A heap in a file, with the sketch's `Store` at its root. Mapped at
-/// `store_base` in every run, so pointers it holds into itself stay valid
-/// across restarts. Not crash-safe: a crash in the middle of an allocation
-/// can leave it inconsistent (`--fresh` starts over).
-///
-/// Blocks come in power-of-two sizes, each class with a free list threaded
-/// through the free blocks, so growing a list by doubling reuses what it
-/// frees. The file grows by mapping more of it in place: nothing moves.
-pub const StoreFile = struct {
- fd: posix.fd_t,
- /// Bytes of the file mapped at `store_base`.
- len: usize,
- /// The root's layout, owned by `arena`.
- layout: Layout,
- arena: std.heap.ArenaAllocator,
-
- const Meta = extern struct {
- magic: [8]u8 = store_magic,
- base: u64 = store_base,
- /// Offset of the first byte never handed out.
- top: u64 = heap_offset,
- /// Offset of the sketch's Store, or 0 before the first adopt.
- root: u64 = 0,
- /// Offsets of the first free block of each size class (2^i bytes), 0
- /// when none; a free block's first 8 bytes hold the next one's.
- free: [64]u64 = @splat(0),
- };
-
- pub fn open(gpa: std.mem.Allocator, path: []const u8, fresh: bool) !StoreFile {
- const fd = try posix.openat(posix.AT.FDCWD, path, .{ .ACCMODE = .RDWR, .CREAT = true }, 0o600);
- errdefer _ = posix.system.close(fd);
- // The same file mapped by two processes would be two heaps writing
- // over each other.
- if (linux.errno(linux.flock(fd, posix.LOCK.EX | posix.LOCK.NB)) != .SUCCESS) return error.StoreInUse;
- const reserved = posix.mmap(@ptrFromInt(store_base), store_reserve, .{}, .{ .TYPE = .PRIVATE, .ANONYMOUS = true, .NORESERVE = true, .FIXED_NOREPLACE = true }, -1, 0) catch return error.StoreAddressTaken;
- // Old kernels treat FIXED_NOREPLACE as a hint.
- if (@intFromPtr(reserved.ptr) != store_base) {
- posix.munmap(reserved);
- return error.StoreAddressTaken;
- }
- errdefer posix.munmap(reserved);
- var self: StoreFile = .{ .fd = fd, .len = 0, .layout = .{}, .arena = .init(gpa) };
- errdefer self.arena.deinit();
- const size: usize = @intCast(try fileSize(fd));
- if (!fresh and size > 0) {
- // Checked before mapping, which may lengthen the file: a file
- // that is not a store is refused untouched, never wiped.
- var m: Meta = undefined;
- const read = linux.pread(fd, std.mem.asBytes(&m), @sizeOf(Meta), meta_offset);
- if (size < heap_offset or read != @sizeOf(Meta) or !std.mem.eql(u8, &m.magic, &store_magic) or m.base != store_base or m.top > size) return error.NotAStoreFile;
- try self.grow(size);
- self.layout = try readLayout(self.arena.allocator(), self.region()) orelse .{};
- return self;
- }
- try self.wipe();
- return self;
- }
-
- pub fn close(self: *StoreFile) void {
- posix.munmap(@as([*]align(page) u8, @ptrFromInt(store_base))[0..store_reserve]);
- _ = posix.system.close(self.fd);
- self.arena.deinit();
- }
-
- /// Empties the store: no root, nothing allocated.
- fn wipe(self: *StoreFile) !void {
- // Mapped pages past the new end would fault: map the reserve back.
- if (self.len > heap_offset) {
- _ = try posix.mmap(@ptrFromInt(store_base + heap_offset), self.len - heap_offset, .{}, .{ .TYPE = .PRIVATE, .ANONYMOUS = true, .NORESERVE = true, .FIXED = true }, -1, 0);
- self.len = heap_offset;
- }
- try truncate(self.fd, heap_offset);
- try self.grow(heap_offset);
- @memset(self.region(), 0);
- self.header().* = .{ .magic = store_layout_magic, .size = 0, .alignment = 1, .hash = 0, .stride = 0, .used = 0, .field_count = 0, .strings_len = 0 };
- self.meta().* = .{};
- self.layout = .{};
- }
-
- /// Maps the file up to `need` bytes, growing it when it is shorter.
- fn grow(self: *StoreFile, need: usize) !void {
- if (need <= self.len) return;
- const len = std.mem.alignForward(usize, @max(need, self.len * 2, 1 << 20), page);
- if (len > store_reserve) return error.StoreFull;
- if (try fileSize(self.fd) < len) try truncate(self.fd, len);
- _ = try posix.mmap(@ptrFromInt(store_base + self.len), len - self.len, .{ .READ = true, .WRITE = true }, .{ .TYPE = .SHARED, .FIXED = true }, self.fd, self.len);
- self.len = len;
- }
-
- fn region(_: *StoreFile) []u8 {
- return @as([*]u8, @ptrFromInt(store_base))[0..header_len];
- }
- fn header(_: *StoreFile) *Header {
- return @ptrFromInt(store_base);
- }
- fn meta(_: *StoreFile) *Meta {
- return @ptrFromInt(store_base + meta_offset);
- }
-
- /// The sketch's Store.
- pub fn root(self: *StoreFile) [*]u8 {
- const offset = self.meta().root;
- return @ptrFromInt(store_base + if (offset == 0) heap_offset else offset);
- }
-
- pub const Adoption = StateFile.Adoption;
-
- /// Makes the root hold `new`'s layout: the new defaults, then every field
- /// whose path and type are unchanged, copied over. Pointer fields keep
- /// pointing where they did, since the store never moves.
- pub fn adopt(self: *StoreFile, gpa: std.mem.Allocator, new: abi.Layout, defaults: *const fn (abi.Memory, [*]u8) callconv(.c) void) !Adoption {
- const m = self.meta();
- if (m.root != 0 and self.layout.hash == new.hash and self.layout.size == new.size) return .unchanged;
- const a = self.allocator();
- const alignment: std.mem.Alignment = .fromByteUnits(@max(new.alignment, 1));
- const fresh = a.rawAlloc(@max(new.size, 1), alignment, @returnAddress()) orelse return error.StoreFull;
- @memset(fresh[0..@max(new.size, 1)], 0);
- defaults(.store, fresh);
-
- var kept = self.arena;
- defer kept.deinit();
- self.arena = .init(gpa);
- const old_layout = self.layout;
- self.layout = try Layout.copy(self.arena.allocator(), new);
- var result: Adoption = .created;
- if (m.root != 0) {
- const old: [*]u8 = @ptrFromInt(store_base + m.root);
- result = .{ .migrated = migrate(old_layout, old[0..old_layout.size], self.layout, fresh[0..new.size]) };
- a.rawFree(old[0..@max(old_layout.size, 1)], .fromByteUnits(@max(old_layout.alignment, 1)), @returnAddress());
- }
- self.header().* = .{ .magic = store_layout_magic, .size = new.size, .alignment = new.alignment, .hash = new.hash, .stride = 0, .used = 1, .field_count = 0, .strings_len = 0 };
- try writeLayout(self.region(), self.layout);
- m.root = @intFromPtr(fresh) - store_base;
- return result;
- }
-
- pub fn allocator(self: *StoreFile) std.mem.Allocator {
- return .{ .ptr = self, .vtable = &.{ .alloc = alloc, .resize = resize, .remap = remap, .free = free } };
- }
-
- fn class(len: usize, alignment: std.mem.Alignment) u6 {
- return @intCast(std.math.log2_int_ceil(usize, @max(len, alignment.toByteUnits(), 16)));
- }
-
- fn alloc(ctx: *anyopaque, len: usize, alignment: std.mem.Alignment, _: usize) ?[*]u8 {
- const self: *StoreFile = @ptrCast(@alignCast(ctx));
- const m = self.meta();
- const c = class(len, alignment);
- const size = @as(usize, 1) << c;
- if (m.free[c] != 0) {
- const block: [*]u8 = @ptrFromInt(store_base + m.free[c]);
- if (alignment.check(@intFromPtr(block))) {
- m.free[c] = @as(*const u64, @ptrCast(@alignCast(block))).*;
- return block;
- }
- }
- const offset = std.mem.alignForward(usize, m.top, @max(@min(size, page), alignment.toByteUnits()));
- self.grow(offset + size) catch return null;
- m.top = offset + size;
- return @ptrFromInt(store_base + offset);
- }
-
- /// In place within the block's size class.
- fn resize(_: *anyopaque, memory: []u8, alignment: std.mem.Alignment, new_len: usize, _: usize) bool {
- return class(memory.len, alignment) == class(new_len, alignment);
- }
-
- fn remap(ctx: *anyopaque, memory: []u8, alignment: std.mem.Alignment, new_len: usize, ret: usize) ?[*]u8 {
- return if (resize(ctx, memory, alignment, new_len, ret)) memory.ptr else null;
- }
-
- fn free(ctx: *anyopaque, memory: []u8, alignment: std.mem.Alignment, _: usize) void {
- const self: *StoreFile = @ptrCast(@alignCast(ctx));
- const m = self.meta();
- const c = class(memory.len, alignment);
- @as(*u64, @ptrCast(@alignCast(memory.ptr))).* = m.free[c];
- m.free[c] = @intFromPtr(memory.ptr) - store_base;
- }
-};
-
-fn truncate(fd: posix.fd_t, len: usize) !void {
- switch (posix.errno(posix.system.ftruncate(fd, @intCast(len)))) {
- .SUCCESS => {},
- else => |err| return posix.unexpectedErrno(err),
- }
-}
-
/// Session memory: survives reloads while its layout hash is unchanged.
/// Everything allocated from `heap` is released with it.
pub const Session = struct {
@@ -921,7 +640,7 @@ test "migration keeps unchanged fields and defaults the rest" {
try std.testing.expectEqual(@as(usize, 1), m.reset);
}
-test "state file migrates live state, and a reopen reads the layout back" {
+test "State migrates to a changed layout, and keeps itself when it is unchanged" {
const V1 = extern struct { score: u32 = 0, name: [4]u8 = "none".* };
const V2 = extern struct { level: u16 = 1, score: u32 = 0 };
const D = struct {
@@ -932,65 +651,20 @@ test "state file migrates live state, and a reopen reads the layout back" {
@as(*V2, @ptrCast(@alignCast(p))).* = .{};
}
};
- var tmp = std.testing.tmpDir(.{});
- defer tmp.cleanup();
- var buf: [std.fs.max_path_bytes]u8 = undefined;
- const path = try std.mem.print(&buf, ".zig-cache/tmp/{s}/test.state", .{&tmp.sub_path});
const gpa = std.testing.allocator;
- {
- var file = try StateFile.open(gpa, path);
- defer file.close();
- try std.testing.expectEqual(StateFile.Adoption.created, try file.adopt(gpa, abi.layout.of(V1, .state), D.v1));
- file.markUsed(0, true);
- @as(*V1, @ptrCast(file.slot(0).ptr)).score = 99;
- }
- var file = try StateFile.open(gpa, path);
- defer file.close();
- try std.testing.expectEqual(abi.layout.hash(V1), file.layout.hash);
- const adoption = try file.adopt(gpa, abi.layout.of(V2, .state), D.v2);
- try std.testing.expectEqual(@as(usize, 1), adoption.migrated.reset);
- try std.testing.expectEqual(V2{ .level = 1, .score = 99 }, @as(*V2, @ptrCast(file.slot(0).ptr)).*);
-}
-
-test "a store keeps its root and what it points to across a reopen, and migrates by field" {
- const V1 = struct { list: std.ArrayList(u32) = .empty, count: u32 = 0 };
- const V2 = struct { added: u8 = 7, list: std.ArrayList(u32) = .empty };
- const D = struct {
- fn v1(_: abi.Memory, p: [*]u8) callconv(.c) void {
- @as(*V1, @ptrCast(@alignCast(p))).* = .{};
- }
- fn v2(_: abi.Memory, p: [*]u8) callconv(.c) void {
- @as(*V2, @ptrCast(@alignCast(p))).* = .{};
- }
- };
- var tmp = std.testing.tmpDir(.{});
- defer tmp.cleanup();
- var buf: [std.fs.max_path_bytes]u8 = undefined;
- const path = try std.mem.print(&buf, ".zig-cache/tmp/{s}/test.store", .{&tmp.sub_path});
- const gpa = std.testing.allocator;
- {
- var store = try StoreFile.open(gpa, path, false);
- defer store.close();
- try std.testing.expectEqual(StoreFile.Adoption.created, try store.adopt(gpa, abi.layout.of(V1, .store), D.v1));
- const v: *V1 = @ptrCast(@alignCast(store.root()));
- for (0..10_000) |i| try v.list.append(store.allocator(), @intCast(i));
- v.count = 3;
- try std.testing.expectError(error.StoreInUse, StoreFile.open(gpa, path, false));
- }
- {
- var store = try StoreFile.open(gpa, path, false);
- defer store.close();
- try std.testing.expectEqual(StoreFile.Adoption.unchanged, try store.adopt(gpa, abi.layout.of(V1, .store), D.v1));
- const adoption = try store.adopt(gpa, abi.layout.of(V2, .store), D.v2);
- try std.testing.expectEqual(@as(usize, 1), adoption.migrated.reset);
- const v: *V2 = @ptrCast(@alignCast(store.root()));
- try std.testing.expectEqual(@as(u8, 7), v.added);
- try std.testing.expectEqual(@as(u32, 9999), v.list.items[9999]);
- v.list.deinit(store.allocator());
- }
- var store = try StoreFile.open(gpa, path, true);
- defer store.close();
- try std.testing.expectEqual(StoreFile.Adoption.created, try store.adopt(gpa, abi.layout.of(V2, .store), D.v2));
+ var state: State = .init(gpa);
+ defer state.deinit(gpa);
+ try std.testing.expectEqual(@as(?Migration, null), try state.adopt(gpa, abi.layout.of(V1, .state), D.v1));
+ @as(*V1, @ptrCast(state.live().ptr)).score = 99;
+ try std.testing.expectEqual(@as(?Migration, null), try state.adopt(gpa, abi.layout.of(V1, .state), D.v1));
+ try std.testing.expectEqual(@as(u32, 99), @as(*V1, @ptrCast(state.live().ptr)).score);
+ const m = (try state.adopt(gpa, abi.layout.of(V2, .state), D.v2)).?;
+ try std.testing.expectEqual(@as(usize, 1), m.reset);
+ try std.testing.expectEqual(V2{ .level = 1, .score = 99 }, @as(*V2, @ptrCast(@alignCast(state.live().ptr))).*);
+ // The header reads back as the layout.
+ var arena: std.heap.ArenaAllocator = .init(gpa);
+ defer arena.deinit();
+ try std.testing.expectEqual(abi.layout.hash(V2), (try layoutOf(arena.allocator(), state.header)).hash);
}
test "arrays migrate element by element: fields, enums by name, shrink and growth" {
@@ -1105,14 +779,15 @@ test "a file that is not a state file is refused, untouched" {
defer std.testing.allocator.free(text);
@memset(text, 'x');
try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = path, .data = text });
- try std.testing.expectError(error.NotAStateFile, StateFile.open(std.testing.allocator, path));
+ try std.testing.expectError(error.NotAStateFile, OldState.open(path));
const after = try std.Io.Dir.cwd().readFileAlloc(io, path, std.testing.allocator, .unlimited);
defer std.testing.allocator.free(after);
try std.testing.expectEqualSlices(u8, text, after);
}
+ try std.testing.expectError(error.FileNotFound, OldState.open(try testPath(&buf, tmp, "none.state")));
}
-test "a state file from before element leaves (drat-meout's) keeps every value" {
+test "a state file from before element leaves (drat-meout's) imports with every value" {
const gpa = std.testing.allocator;
const io = std.testing.io;
var tmp = std.testing.tmpDir(.{});
@@ -1132,30 +807,29 @@ test "a state file from before element leaves (drat-meout's) keeps every value"
const h: *const Header = @ptrCast(@alignCast(original.ptr));
const live = original[header_len..][0..h.size];
- // The layout the game had when it wrote the file, as a sketch would
- // describe it: unchanged, so nothing migrates and the header is
- // rewritten in the new format.
- const same = try asSketchLayout(a, old, &.{});
- {
- var file = try StateFile.open(gpa, path);
- defer file.close();
- try std.testing.expectEqual(StateFile.Adoption.unchanged, try file.adopt(gpa, same, NoDefaults.f));
- try std.testing.expectEqualStrings(&file_magic_v2, &file.header().magic);
- }
- var file = try StateFile.open(gpa, path);
+ const file = try OldState.open(path);
defer file.close();
- try std.testing.expectEqual(old.fields.len, file.layout.fields.len);
- try std.testing.expectEqualSlices(u8, live, file.slot(0));
-
- // A changed layout (one field gone, one new): every other leaf keeps
- // its value, the songs included (an unchanged array type, so whole).
- const changed = try asSketchLayout(a, old, "scene");
- _ = try file.adopt(gpa, changed, NoDefaults.f);
- for (old.fields) |leaf| {
- if (std.mem.eql(u8, leaf.path, "scene")) continue;
- try std.testing.expectEqualSlices(u8, leaf.bytes(live), leaf.bytes(file.slot(0)));
+ try std.testing.expectEqual(@as(usize, old_slot_count), file.slots);
+ // Into the layout the game had when it wrote the file, as a sketch would
+ // describe it: every byte; then into a changed one (one field gone, one
+ // new): every other leaf keeps its value, the songs included (an
+ // unchanged array type, so whole).
+ for ([_][]const u8{ "", "scene" }) |drop| {
+ var state: State = .init(gpa);
+ defer state.deinit(gpa);
+ _ = try state.adopt(gpa, try asSketchLayout(a, old, drop), NoDefaults.f);
+ @memset(state.live(), 0);
+ _ = try restore(a, file.layoutBytes(), file.slot(0).?, state.layout, state.live(), NoDefaults.f);
+ if (drop.len == 0) try std.testing.expectEqualSlices(u8, live, state.live());
+ for (old.fields) |leaf| {
+ if (drop.len > 0 and std.mem.eql(u8, leaf.path, drop)) continue;
+ try std.testing.expectEqualSlices(u8, leaf.bytes(live), leaf.bytes(state.live()));
+ }
}
- try std.testing.expectEqual(@as(u8, 0), file.slot(0)[h.size]);
+ // The file is as it was.
+ const after = try tmp.dir.readFileAlloc(io, "game.state", gpa, .unlimited);
+ defer gpa.free(after);
+ try std.testing.expectEqualSlices(u8, original, after);
}
const NoDefaults = struct {