Phase 2: I/O intrinsics, linear resources, deterministic profile (RFC 0007)
- air: resource types file<read|write|append>, listener, stream; io_error; intrinsic registry (19 intrinsics) synced with reference/intrinsics.md; fallible intrinsics as ok/err terminators; fs prefix narrowing; linear_aggregates gating - verifier: intrinsic form, operand, result and capability-kind checks (E1001, E3201, E5002); intrinsic effects (E3101); resource linearity in the borrow walker with per-edge moves: E3002 leaks and join mismatches, E3001, E2001, E2002, E2101 for close while borrowed; resources as borrow roots - interp: deterministic world (captured console, VFS, loopback TCP, instruction clock, pinned xoshiro256 PRNG), blocked outcome, run record with stdout/stderr/files - CLI: --stdin, --vfs, --seed, --result-file, --profile (hosted: exit 3), exit code 7; runner: stdin/vfs/seed/stdout/stderr/file/blocked headers - conformance: hello, file copy and TCP echo exit programs; 37 new tests; 4000 mutants without a crash
This commit is contained in:
1 parent
571cc6e362
commit
d405d4ea50
49 files changed
+2325
-81
No files matched your search
+227
-5
@@ -11,6 +11,9 @@
|
||||
const std = @import("std");
|
||||
const air = @import("../air.zig");
|
||||
const diag = @import("../diag.zig");
|
||||
const world_mod = @import("world.zig");
|
||||
|
||||
pub const WorldOptions = world_mod.Options;
|
||||
|
||||
pub const call_depth_limit = 1024;
|
||||
|
||||
@@ -30,6 +33,8 @@ pub const Value = union(enum) {
|
||||
/// `cap<K>`: index into the host's authority table. Never observable
|
||||
/// by the program (spec 05 §10.1).
|
||||
cap: u32,
|
||||
/// Linear resource: index into the world's handle table.
|
||||
resource: u32,
|
||||
/// Value of a built-in enum such as `cap_error`.
|
||||
builtin: struct { which: air.authority.Builtin, variant: u32 },
|
||||
|
||||
@@ -64,8 +69,13 @@ pub const Outcome = union(enum) {
|
||||
limit_exceeded: struct { limit: u64, steps: u64 },
|
||||
/// The host did not start the program (spec 05 §10.2). Not a trap.
|
||||
not_instantiated: NotInstantiated,
|
||||
/// The deterministic runtime found no future event that could complete
|
||||
/// a wait (spec 11 §8). Not a trap and not an I/O error.
|
||||
blocked: Location,
|
||||
};
|
||||
|
||||
pub const Location = struct { function: []const u8, block: []const u8, inst: u32 };
|
||||
|
||||
pub const NotInstantiated = struct {
|
||||
reason: []const u8,
|
||||
parameter: []const u8,
|
||||
@@ -89,6 +99,18 @@ pub const Options = struct {
|
||||
fuel: ?u64 = null,
|
||||
/// Capability grants for the parameters of the entry function.
|
||||
grants: []const Grant = &.{},
|
||||
/// Inputs of the deterministic world (spec 11 §8).
|
||||
world: WorldOptions = .{},
|
||||
/// Receives the run's observable output.
|
||||
output: ?*Output = null,
|
||||
};
|
||||
|
||||
/// Observable output of a run in the deterministic profile.
|
||||
pub const Output = struct {
|
||||
stdout: []const u8,
|
||||
stderr: []const u8,
|
||||
/// Files written during the run, sorted by path.
|
||||
files: []const struct { []const u8, []const u8 },
|
||||
};
|
||||
|
||||
pub const Error = std.mem.Allocator.Error || error{ EntryNotFound, DuplicateGrant };
|
||||
@@ -99,7 +121,10 @@ pub fn run(arena: std.mem.Allocator, module: air.Module, entry: []const u8, opti
|
||||
const idx = module.functionIndex(entry) orelse return error.EntryNotFound;
|
||||
const f = module.functions[idx];
|
||||
for (f.params) |p| if (p.ty != .cap) return error.EntryNotFound;
|
||||
var m: Machine = .{ .arena = arena, .module = module, .fuel = options.fuel };
|
||||
var m: Machine = .{ .arena = arena, .module = module, .fuel = options.fuel, .world = try .init(arena, options.world) };
|
||||
defer if (options.output) |o| {
|
||||
o.* = m.output() catch .{ .stdout = "", .stderr = "", .files = &.{} };
|
||||
};
|
||||
|
||||
// Instantiation (spec 05 §10.2): every capability parameter gets exactly
|
||||
// one grant of its kind, and every grant names a parameter.
|
||||
@@ -129,6 +154,7 @@ pub fn run(arena: std.mem.Allocator, module: air.Module, entry: []const u8, opti
|
||||
.value => |v| .{ .returned = v },
|
||||
.trap => |t| .{ .trapped = t },
|
||||
.limit_exceeded => .{ .limit_exceeded = .{ .limit = m.fuel.?, .steps = m.steps } },
|
||||
.blocked => |l| .{ .blocked = l },
|
||||
};
|
||||
}
|
||||
|
||||
@@ -168,7 +194,7 @@ fn kindOf(e: TrapError) TrapKind {
|
||||
};
|
||||
}
|
||||
|
||||
const CallResult = union(enum) { value: Value, trap: Trap, limit_exceeded };
|
||||
const CallResult = union(enum) { value: Value, trap: Trap, limit_exceeded, blocked: Location };
|
||||
|
||||
const Machine = struct {
|
||||
arena: std.mem.Allocator,
|
||||
@@ -177,6 +203,7 @@ const Machine = struct {
|
||||
fuel: ?u64,
|
||||
/// Host authority table; capabilities index into it.
|
||||
authorities: std.ArrayList(Authority) = .empty,
|
||||
world: world_mod.World,
|
||||
/// Instructions executed so far.
|
||||
steps: u64 = 0,
|
||||
|
||||
@@ -211,6 +238,8 @@ const Machine = struct {
|
||||
} },
|
||||
.nested_trap => |t| return .{ .trap = t },
|
||||
.limit_exceeded => return .limit_exceeded,
|
||||
.blocked => return .{ .blocked = .{ .function = f.name, .block = b.name, .inst = @intCast(ii) } },
|
||||
.nested_blocked => |l| return .{ .blocked = l },
|
||||
}
|
||||
} else unreachable; // verified blocks end with a terminator
|
||||
}
|
||||
@@ -224,6 +253,8 @@ const Machine = struct {
|
||||
/// A trap raised inside a callee, already located.
|
||||
nested_trap: Trap,
|
||||
limit_exceeded,
|
||||
blocked,
|
||||
nested_blocked: Location,
|
||||
};
|
||||
|
||||
fn exec(m: *Machine, f: air.Function, vals: []Value, inst: air.Inst) std.mem.Allocator.Error!Step {
|
||||
@@ -291,6 +322,7 @@ const Machine = struct {
|
||||
},
|
||||
.trap => |t| return .{ .nested_trap = t },
|
||||
.limit_exceeded => return .limit_exceeded,
|
||||
.blocked => |l| return .{ .nested_blocked = l },
|
||||
}
|
||||
},
|
||||
.br => |t| return m.jump(f, vals, t),
|
||||
@@ -314,7 +346,8 @@ const Machine = struct {
|
||||
},
|
||||
// No narrowing form is registered yet, so verified AIR contains
|
||||
// no reachable cap.narrow (spec 05 §10.4; forms arrive with RFC 0007/0008).
|
||||
.cap_narrow => unreachable,
|
||||
.cap_narrow => |x| return m.narrow(f, vals, x),
|
||||
.intrinsic => |x| return m.intrinsic(f, vals, inst, x),
|
||||
.ret => |v| return .{ .ret = if (v) |x| vals[x] else .void },
|
||||
.trap => return .{ .trap = .explicit },
|
||||
.local_alloc, .local_store, .local_zero, .local_load, .borrow_ref, .borrow_mut, .borrow_field, .borrow_end, .load, .store, .array_splat, .borrow_index, .slice_make, .slice_len, .slice_sub, .slice_split, .slice_copy, .guard => return m.execMemory(vals, inst),
|
||||
@@ -388,6 +421,143 @@ const Machine = struct {
|
||||
};
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ authority and I/O (spec 05 §10–§11, spec 06 §6)
|
||||
|
||||
fn output(m: *Machine) !Output {
|
||||
const keys = try m.arena.dupe([]const u8, m.world.written.keys());
|
||||
std.mem.sort([]const u8, keys, {}, struct {
|
||||
fn lt(_: void, a: []const u8, b: []const u8) bool {
|
||||
return std.mem.lessThan(u8, a, b);
|
||||
}
|
||||
}.lt);
|
||||
const files = try m.arena.alloc(struct { []const u8, []const u8 }, keys.len);
|
||||
for (keys, files) |k, *out| out.* = .{ k, m.world.files.get(k).?.items };
|
||||
return .{ .stdout = m.world.stdout.items, .stderr = m.world.stderr.items, .files = files };
|
||||
}
|
||||
|
||||
/// Bytes of a `slice<u8>` value.
|
||||
fn bytesOf(m: *Machine, v: Value) ![]u8 {
|
||||
const s = v.slice;
|
||||
const items = placePtr(s.place).array[s.start..][0..s.len];
|
||||
const out = try m.arena.alloc(u8, items.len);
|
||||
for (items, out) |x, *o| o.* = @truncate(x.int.bits);
|
||||
return out;
|
||||
}
|
||||
|
||||
/// Writes `bytes` into the start of a `slice_mut<u8>` value.
|
||||
fn fillSlice(v: Value, bytes: []const u8) void {
|
||||
const s = v.slice;
|
||||
const items = placePtr(s.place).array[s.start..][0..s.len];
|
||||
for (bytes, items[0..bytes.len]) |b, *x| x.* = .{ .int = .{ .ty = .u8, .bits = b } };
|
||||
}
|
||||
|
||||
fn resourceOf(v: Value) u32 {
|
||||
return switch (v) {
|
||||
.resource => |hd| hd,
|
||||
.place => |p| p.cell.value.resource,
|
||||
else => unreachable,
|
||||
};
|
||||
}
|
||||
|
||||
fn narrow(m: *Machine, f: air.Function, vals: []Value, x: @FieldType(air.Op, "cap_narrow")) !Step {
|
||||
const a = m.authorities.items[vals[x.cap].cap];
|
||||
// Only `prefix` is registered (reference/capabilities.md).
|
||||
const path = try m.bytesOf(vals[x.args[0]]);
|
||||
const reason: ?u32 = if (!world_mod.World.validPath(path)) 0 else if (!world_mod.World.within(a.scope, path)) 1 else null;
|
||||
if (reason) |r| {
|
||||
vals[f.blocks[x.err].params[0].value] = .{ .builtin = .{ .which = .cap_error, .variant = r } };
|
||||
return .{ .jump = x.err };
|
||||
}
|
||||
try m.authorities.append(m.arena, .{ .kind = a.kind, .scope = path });
|
||||
vals[f.blocks[x.ok].params[0].value] = .{ .cap = @intCast(m.authorities.items.len - 1) };
|
||||
return .{ .jump = x.ok };
|
||||
}
|
||||
|
||||
fn intrinsic(m: *Machine, f: air.Function, vals: []Value, inst: air.Inst, x: @FieldType(air.Op, "intrinsic")) !Step {
|
||||
const name = air.authority.intrinsics[x.index].name;
|
||||
const arg = struct {
|
||||
fn at(v: []Value, xx: @FieldType(air.Op, "intrinsic"), i: usize) Value {
|
||||
return v[xx.args[i]];
|
||||
}
|
||||
}.at;
|
||||
const W = world_mod.World;
|
||||
var results: [1]Value = undefined;
|
||||
var n_results: usize = 0;
|
||||
var failure: ?world_mod.Error = null;
|
||||
const is = struct {
|
||||
fn eq(a: []const u8, b: []const u8) bool {
|
||||
return std.mem.eql(u8, a, b);
|
||||
}
|
||||
}.eq;
|
||||
if (is(name, "clock.monotonic")) {
|
||||
return bind(vals, inst.result, .{ .int = .{ .ty = .u64, .bits = m.steps } });
|
||||
} else if (is(name, "random.fill")) {
|
||||
const buf = try m.arena.alloc(u8, arg(vals, x, 1).slice.len);
|
||||
m.world.fill(buf);
|
||||
fillSlice(arg(vals, x, 1), buf);
|
||||
return .next;
|
||||
} else if (is(name, "io.stdout_write") or is(name, "io.stderr_write")) {
|
||||
try m.world.writeOut(is(name, "io.stderr_write"), try m.bytesOf(arg(vals, x, 1)));
|
||||
} else if (is(name, "io.stdin_read")) {
|
||||
const buf = try m.arena.alloc(u8, arg(vals, x, 1).slice.len);
|
||||
const n = m.world.readIn(buf);
|
||||
fillSlice(arg(vals, x, 1), buf[0..n]);
|
||||
results[0] = .{ .int = .{ .ty = .usize, .bits = n } };
|
||||
n_results = 1;
|
||||
} else if (is(name, "fs.open_read") or is(name, "fs.create") or is(name, "fs.open_append")) {
|
||||
const scope = m.authorities.items[arg(vals, x, 0).cap].scope;
|
||||
const mode: air.authority.Resource = if (is(name, "fs.open_read")) .file_read else if (is(name, "fs.create")) .file_write else .file_append;
|
||||
switch (try m.world.open(scope, try m.bytesOf(arg(vals, x, 1)), mode)) {
|
||||
.ok => |hd| {
|
||||
results[0] = .{ .resource = hd };
|
||||
n_results = 1;
|
||||
},
|
||||
.err => |e| failure = e,
|
||||
}
|
||||
} else if (is(name, "fs.read")) {
|
||||
const buf = try m.arena.alloc(u8, arg(vals, x, 1).slice.len);
|
||||
const n = m.world.fileRead(resourceOf(arg(vals, x, 0)), buf);
|
||||
fillSlice(arg(vals, x, 1), buf[0..n]);
|
||||
results[0] = .{ .int = .{ .ty = .usize, .bits = n } };
|
||||
n_results = 1;
|
||||
} else if (is(name, "fs.write_all")) {
|
||||
try m.world.fileWrite(resourceOf(arg(vals, x, 0)), try m.bytesOf(arg(vals, x, 1)));
|
||||
} else if (is(name, "fs.sync")) {
|
||||
// Durable by construction in the in-memory file system.
|
||||
} else if (is(name, "fs.close") or is(name, "net.close_stream") or is(name, "net.close_listener")) {
|
||||
m.world.close(arg(vals, x, 0).resource);
|
||||
} else if (is(name, "net.listen") or is(name, "net.connect")) {
|
||||
const addr = try m.bytesOf(arg(vals, x, 1));
|
||||
switch (if (is(name, "net.listen")) try m.world.listen(addr) else try m.world.connect(addr)) {
|
||||
.ok => |hd| {
|
||||
results[0] = .{ .resource = hd };
|
||||
n_results = 1;
|
||||
},
|
||||
.err => |e| failure = e,
|
||||
}
|
||||
} else if (is(name, "net.accept")) {
|
||||
const s = m.world.accept(resourceOf(arg(vals, x, 0))) orelse return .blocked;
|
||||
results[0] = .{ .resource = s };
|
||||
n_results = 1;
|
||||
} else if (is(name, "net.recv")) {
|
||||
const buf = try m.arena.alloc(u8, arg(vals, x, 1).slice.len);
|
||||
const n = m.world.recv(resourceOf(arg(vals, x, 0)), buf) orelse return .blocked;
|
||||
fillSlice(arg(vals, x, 1), buf[0..n]);
|
||||
results[0] = .{ .int = .{ .ty = .usize, .bits = n } };
|
||||
n_results = 1;
|
||||
} else if (is(name, "net.send_all")) {
|
||||
failure = try m.world.send(resourceOf(arg(vals, x, 0)), try m.bytesOf(arg(vals, x, 1)));
|
||||
} else unreachable; // every registered intrinsic is handled above
|
||||
_ = W;
|
||||
|
||||
if (failure) |e| {
|
||||
vals[f.blocks[x.err.?].params[0].value] = .{ .builtin = .{ .which = .io_error, .variant = @backingInt(e) } };
|
||||
return .{ .jump = x.err.? };
|
||||
}
|
||||
for (f.blocks[x.ok.?].params, results[0..n_results]) |p, r| vals[p.value] = r;
|
||||
return .{ .jump = x.ok.? };
|
||||
}
|
||||
|
||||
fn usize_(v: Value) u64 {
|
||||
return @truncate(v.int.bits);
|
||||
}
|
||||
@@ -411,6 +581,12 @@ const Machine = struct {
|
||||
.local_load => |v| return bind(vals, inst.result, try m.deepCopy(vals[v].local.value)),
|
||||
.borrow_ref, .borrow_mut => |v| return bind(vals, inst.result, switch (vals[v]) {
|
||||
.local => |c| .{ .place = .{ .cell = c, .path = &.{} } },
|
||||
// A borrowed resource: a place whose cell holds the handle.
|
||||
.resource => |hd| blk: {
|
||||
const cell = try m.arena.create(Value.Cell);
|
||||
cell.* = .{ .value = .{ .resource = hd }, .ty = .void };
|
||||
break :blk .{ .place = .{ .cell = cell, .path = &.{} } };
|
||||
},
|
||||
else => |x| x,
|
||||
}),
|
||||
.borrow_field => |x| return bind(vals, inst.result, .{ .place = try m.extend(asPlace(vals[x.borrow]), x.field) }),
|
||||
@@ -611,6 +787,7 @@ pub fn writeValue(module: air.Module, v: Value, s: *std.json.Stringify) std.Io.W
|
||||
},
|
||||
// Storage and borrows cannot be returned from `@main` (spec 08 §11.3).
|
||||
.local, .place, .slice => try s.write(null),
|
||||
.resource => try s.write(null),
|
||||
// A capability is opaque: only its kind is shown, never its identity.
|
||||
.cap => {
|
||||
try s.beginObject();
|
||||
@@ -653,8 +830,23 @@ pub fn writeValue(module: air.Module, v: Value, s: *std.json.Stringify) std.Io.W
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes bytes as a JSON string: printable ASCII as is, every other byte
|
||||
/// as `\u00XX`, so arbitrary output is valid, deterministic JSON.
|
||||
fn writeBytes(w: *std.Io.Writer, bytes: []const u8) std.Io.Writer.Error!void {
|
||||
try w.writeByte('"');
|
||||
for (bytes) |b| switch (b) {
|
||||
'"' => try w.writeAll("\\\""),
|
||||
'\\' => try w.writeAll("\\\\"),
|
||||
'\n' => try w.writeAll("\\n"),
|
||||
0x20...0x21, 0x23...0x5b, 0x5d...0x7e => try w.writeByte(b),
|
||||
else => try w.print("\\u{x:0>4}", .{b}),
|
||||
};
|
||||
try w.writeByte('"');
|
||||
}
|
||||
|
||||
/// Writes the run record for `outcome` as one JSON object (no newline).
|
||||
pub fn writeOutcome(module: air.Module, outcome: Outcome, w: *std.Io.Writer) std.Io.Writer.Error!void {
|
||||
/// `output` is added for modules that declare `capabilities` (spec 07a).
|
||||
pub fn writeOutcome(module: air.Module, outcome: Outcome, out: ?Output, w: *std.Io.Writer) std.Io.Writer.Error!void {
|
||||
var s: std.json.Stringify = .{ .writer = w };
|
||||
try s.beginObject();
|
||||
try s.objectField("status");
|
||||
@@ -677,6 +869,17 @@ pub fn writeOutcome(module: air.Module, outcome: Outcome, w: *std.Io.Writer) std
|
||||
try s.objectField("inst");
|
||||
try s.write(t.inst);
|
||||
},
|
||||
.blocked => |l| {
|
||||
try s.write("blocked");
|
||||
try s.objectField("kind");
|
||||
try s.write("no_future_event");
|
||||
try s.objectField("function");
|
||||
try s.write(l.function);
|
||||
try s.objectField("block");
|
||||
try s.write(l.block);
|
||||
try s.objectField("inst");
|
||||
try s.write(l.inst);
|
||||
},
|
||||
.not_instantiated => |n| {
|
||||
try s.write("not_instantiated");
|
||||
try s.objectField("reason");
|
||||
@@ -706,6 +909,25 @@ pub fn writeOutcome(module: air.Module, outcome: Outcome, w: *std.Io.Writer) std
|
||||
try s.write(l.steps);
|
||||
},
|
||||
}
|
||||
if (out) |o| if (module.declares("capabilities") and outcome != .not_instantiated) {
|
||||
try s.objectField("stdout");
|
||||
try s.beginWriteRaw();
|
||||
try writeBytes(w, o.stdout);
|
||||
s.endWriteRaw();
|
||||
try s.objectField("stderr");
|
||||
try s.beginWriteRaw();
|
||||
try writeBytes(w, o.stderr);
|
||||
s.endWriteRaw();
|
||||
try s.objectField("files");
|
||||
try s.beginObject();
|
||||
for (o.files) |file| {
|
||||
try s.objectField(file[0]);
|
||||
try s.beginWriteRaw();
|
||||
try writeBytes(w, file[1]);
|
||||
s.endWriteRaw();
|
||||
}
|
||||
try s.endObject();
|
||||
};
|
||||
try s.endObject();
|
||||
}
|
||||
|
||||
@@ -728,7 +950,7 @@ fn expectRunFuel(src: []const u8, expected: []const u8, fuel: ?u64) !void {
|
||||
}
|
||||
const outcome = try run(arena, report.module.?, "main", .{ .fuel = fuel });
|
||||
var out: std.Io.Writer.Allocating = .init(arena);
|
||||
try writeOutcome(report.module.?, outcome, &out.writer);
|
||||
try writeOutcome(report.module.?, outcome, null, &out.writer);
|
||||
try std.testing.expectEqualStrings(expected, out.written());
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user