//! The `deterministic` execution profile (spec 11 §8): captured console, //! in-memory file system, in-process loopback TCP, logical clock and a //! seeded PRNG. Every result is a function of the run's inputs. const std = @import("std"); const air = @import("../air.zig"); const IoError = enum(u32) { not_found, permission_denied, already_exists, invalid_input, no_space, broken_pipe, connection_refused, connection_reset, address_in_use, address_unavailable, timed_out, other, }; comptime { // Variant indices must match the built-in enum `io_error`. for (air.authority.Builtin.io_error.variants(), 0..) |name, i| { std.debug.assert(std.mem.eql(u8, @tagName(@as(IoError, @fromBackingInt(@intCast(i)))), name)); } } pub const Error = IoError; /// Result of an operation that creates a resource. pub const Opened = union(enum) { ok: u32, err: IoError }; /// An open resource. Indices are never reused within a run. pub const Handle = union(enum) { file: struct { path: []const u8, mode: air.authority.Resource, pos: usize }, listener: struct { addr: []const u8, pending: std.ArrayList(u32) = .empty }, stream: struct { peer: ?u32, inbox: std.ArrayList(u8) = .empty, read_pos: usize = 0, peer_closed: bool = false }, closed, }; pub const Options = struct { stdin: []const u8 = "", /// Initial files: path -> contents. files: []const struct { []const u8, []const u8 } = &.{}, seed: u64 = 0, }; /// xoshiro256** with SplitMix64 seeding, specified bit for bit in spec 11 §8.1. /// Implemented here rather than taken from `std.Random`, so that neither a /// toolchain upgrade nor library details can change deterministic output. pub const Prng = struct { s: [4]u64, pub fn init(seed: u64) Prng { var x = seed; var p: Prng = undefined; for (&p.s) |*w| { x +%= 0x9e3779b97f4a7c15; var z = x; z = (z ^ (z >> 30)) *% 0xbf58476d1ce4e5b9; z = (z ^ (z >> 27)) *% 0x94d049bb133111eb; w.* = z ^ (z >> 31); } return p; } pub fn next(p: *Prng) u64 { const s = &p.s; const result = std.math.rotl(u64, s[1] *% 5, 7) *% 9; const t = s[1] << 17; s[2] ^= s[0]; s[3] ^= s[1]; s[1] ^= s[2]; s[0] ^= s[3]; s[2] ^= t; s[3] = std.math.rotl(u64, s[3], 45); return result; } /// Each call consumes ceil(len / 8) outputs; bytes are taken least /// significant first; unused bytes of the last output are discarded. pub fn fill(p: *Prng, buf: []u8) void { var i: usize = 0; while (i < buf.len) { const v = p.next(); var k: u6 = 0; while (k < 8 and i < buf.len) : ({ k += 1; i += 1; }) buf[i] = @truncate(v >> (@as(u6, k) * 8)); } } }; pub const World = struct { arena: std.mem.Allocator, stdout: std.ArrayList(u8) = .empty, stderr: std.ArrayList(u8) = .empty, stdin: []const u8, stdin_pos: usize = 0, files: std.StringArrayHashMapUnmanaged(std.ArrayList(u8)) = .empty, written: std.StringArrayHashMapUnmanaged(void) = .empty, handles: std.ArrayList(Handle) = .empty, listeners: std.StringHashMapUnmanaged(u32) = .empty, prng: Prng, pub fn init(arena: std.mem.Allocator, o: Options) !World { var w: World = .{ .arena = arena, .stdin = o.stdin, .prng = .init(o.seed) }; for (o.files) |entry| { var contents: std.ArrayList(u8) = .empty; try contents.appendSlice(arena, entry[1]); try w.files.put(arena, entry[0], contents); } return w; } fn add(w: *World, h: Handle) !u32 { try w.handles.append(w.arena, h); return @intCast(w.handles.items.len - 1); } // ------------------------------------------------------------ paths /// Absolute, no empty, `.` or `..` components (reference/intrinsics.md). pub fn validPath(path: []const u8) bool { if (path.len == 0 or path[0] != '/') return false; if (path.len == 1) return true; var it = std.mem.splitScalar(u8, path[1..], '/'); while (it.next()) |part| { if (part.len == 0 or std.mem.eql(u8, part, ".") or std.mem.eql(u8, part, "..")) return false; } return true; } /// Whether `path` lies within `scope` (null scope = whole file system). pub fn within(scope: ?[]const u8, path: []const u8) bool { const s = scope orelse return true; if (std.mem.eql(u8, s, "/")) return true; if (!std.mem.startsWith(u8, path, s)) return false; return path.len == s.len or path[s.len] == '/'; } // ------------------------------------------------------------ console pub fn writeOut(w: *World, err_stream: bool, bytes: []const u8) !void { try (if (err_stream) &w.stderr else &w.stdout).appendSlice(w.arena, bytes); } pub fn readIn(w: *World, buf: []u8) usize { const n = @min(buf.len, w.stdin.len - w.stdin_pos); @memcpy(buf[0..n], w.stdin[w.stdin_pos..][0..n]); w.stdin_pos += n; return n; } // ------------------------------------------------------------ files pub fn open(w: *World, scope: ?[]const u8, path: []const u8, mode: air.authority.Resource) !Opened { if (!validPath(path)) return .{ .err = .invalid_input }; if (!within(scope, path)) return .{ .err = .permission_denied }; const owned = try w.arena.dupe(u8, path); switch (mode) { .file_read => if (!w.files.contains(owned)) return .{ .err = .not_found }, .file_write => { try w.files.put(w.arena, owned, .empty); try w.written.put(w.arena, owned, {}); }, .file_append => { if (!w.files.contains(owned)) try w.files.put(w.arena, owned, .empty); try w.written.put(w.arena, owned, {}); }, else => unreachable, } return .{ .ok = try w.add(.{ .file = .{ .path = owned, .mode = mode, .pos = 0 } }) }; } pub fn fileRead(w: *World, h: u32, buf: []u8) usize { const f = &w.handles.items[h].file; const data = w.files.get(f.path).?.items; const n = @min(buf.len, data.len -| f.pos); @memcpy(buf[0..n], data[f.pos..][0..n]); f.pos += n; return n; } pub fn fileWrite(w: *World, h: u32, bytes: []const u8) !void { const f = &w.handles.items[h].file; try w.files.getPtr(f.path).?.appendSlice(w.arena, bytes); } pub fn close(w: *World, h: u32) void { switch (w.handles.items[h]) { .stream => |s| if (s.peer) |p| switch (w.handles.items[p]) { .stream => |*ps| ps.peer_closed = true, else => {}, }, .listener => |l| _ = w.listeners.remove(l.addr), else => {}, } w.handles.items[h] = .closed; } // ------------------------------------------------------------ loopback TCP /// `host:port` with a numeric IPv4 host. pub fn validAddr(addr: []const u8) bool { const colon = std.mem.lastIndexOfScalar(u8, addr, ':') orelse return false; _ = std.fmt.parseInt(u16, addr[colon + 1 ..], 10) catch return false; var it = std.mem.splitScalar(u8, addr[0..colon], '.'); var n: usize = 0; while (it.next()) |part| : (n += 1) { _ = std.fmt.parseInt(u8, part, 10) catch return false; } return n == 4; } pub fn listen(w: *World, addr: []const u8) !Opened { if (!validAddr(addr)) return .{ .err = .invalid_input }; const owned = try w.arena.dupe(u8, addr); if (w.listeners.contains(owned)) return .{ .err = .address_in_use }; const h = try w.add(.{ .listener = .{ .addr = owned } }); try w.listeners.put(w.arena, owned, h); return .{ .ok = h }; } pub fn connect(w: *World, addr: []const u8) !Opened { if (!validAddr(addr)) return .{ .err = .invalid_input }; const l = w.listeners.get(addr) orelse return .{ .err = .connection_refused }; const client = try w.add(.{ .stream = .{ .peer = null } }); const server = try w.add(.{ .stream = .{ .peer = client } }); w.handles.items[client].stream.peer = server; try w.handles.items[l].listener.pending.append(w.arena, server); return .{ .ok = client }; } /// Null: nothing to accept, and nothing else can ever connect (the run /// has a single execution unit): the caller reports `blocked`. pub fn accept(w: *World, h: u32) ?u32 { const l = &w.handles.items[h].listener; if (l.pending.items.len == 0) return null; return l.pending.orderedRemove(0); } pub fn send(w: *World, h: u32, bytes: []const u8) !?IoError { const s = w.handles.items[h].stream; if (s.peer_closed) return .broken_pipe; const p = s.peer orelse return .broken_pipe; try w.handles.items[p].stream.inbox.appendSlice(w.arena, bytes); return null; } /// Null: no data and the peer is open; nothing else can ever send, so /// the caller reports `blocked`. pub fn recv(w: *World, h: u32, buf: []u8) ?usize { const s = &w.handles.items[h].stream; const avail = s.inbox.items.len - s.read_pos; if (avail == 0) return if (s.peer_closed) 0 else null; const n = @min(buf.len, avail); @memcpy(buf[0..n], s.inbox.items[s.read_pos..][0..n]); s.read_pos += n; return n; } // ------------------------------------------------------------ random pub fn fill(w: *World, buf: []u8) void { w.prng.fill(buf); } }; test "paths and scopes" { try std.testing.expect(World.validPath("/data/a.txt")); try std.testing.expect(!World.validPath("data/a.txt")); try std.testing.expect(!World.validPath("/data/../etc")); try std.testing.expect(!World.validPath("/data//a")); try std.testing.expect(World.within("/data", "/data/a")); try std.testing.expect(!World.within("/data", "/database")); try std.testing.expect(World.within(null, "/x")); } test "addresses" { try std.testing.expect(World.validAddr("127.0.0.1:8080")); try std.testing.expect(!World.validAddr("localhost:80")); try std.testing.expect(!World.validAddr("127.0.0.1:99999")); } test "PRNG golden vectors (spec 11 §8.1)" { var p: Prng = .init(0); // SplitMix64(0) first output, a published reference value. try std.testing.expectEqual(@as(u64, 0xe220a8397b1dcdaf), Prng.init(0).s[0]); var b1: [1]u8 = undefined; var b7: [7]u8 = undefined; var b8: [8]u8 = undefined; var b17: [17]u8 = undefined; p.fill(&b1); p.fill(&b7); p.fill(&b8); p.fill(&b17); try std.testing.expectEqualSlices(u8, &.{180}, &b1); try std.testing.expectEqualSlices(u8, &.{ 42, 69, 86, 73, 120, 31, 110 }, &b7); try std.testing.expectEqualSlices(u8, &.{ 224, 230, 51, 73, 157, 132, 95, 26 }, &b8); try std.testing.expectEqualSlices(u8, &.{ 44, 45, 45, 38, 241, 148, 165, 106, 89, 46, 132, 31, 74, 173, 165, 187, 202 }, &b17); }