Phase 2: heap, regions and allocation budgets (RFC 0008)

- air: own<T>, own_array<T>, region, alloc_error; own.new/array/take/
  free, region.create/new/array/reset/destroy; mem.alloc budget form;
  linear contents of owners gated by linear_aggregates
- verifier: allocation types and capability kind (E1001, E3201),
  mem.alloc effect (E3101), ok/err counts; borrow-typed block params
  checked in the CFG stage with the region-allocation exception; linear
  owners and regions (E3002, E3001, E2001, E2002, E2101); region
  allocations as disjoint exclusive children of the shared region
  borrow; E2104 when reset/destroy would invalidate a live reference
- interp: live-byte budgets charged along the narrowing chain, shared by
  copies, mandatory in the deterministic profile; heap cells; regions
  return quota only on reset/destroy
- conformance: 25 heap/region tests including a 64 KiB region file copy;
  4000 mutants without a crash
This commit is contained in:
dev committed 2026-10-04 14:26:34 +03:00
1 parent b8d4ab4d4c
commit 7f4ce71d44
38 files changed
+1341 -48

No files matched your search

+179 -6
View File
@@ -12,6 +12,7 @@ const std = @import("std");
const air = @import("../air.zig");
const diag = @import("../diag.zig");
const world_mod = @import("world.zig");
const budget = @import("../verifier/budget.zig");
pub const WorldOptions = world_mod.Options;
@@ -35,6 +36,10 @@ pub const Value = union(enum) {
cap: u32,
/// Linear resource: index into the world's handle table.
resource: u32,
/// `own<T>` / `own_array<T>`: the heap cell.
own: *Cell,
/// `region`: index into the machine's region table.
region: u32,
/// Value of a built-in enum such as `cap_error`.
builtin: struct { which: air.authority.Builtin, variant: u32 },
@@ -92,7 +97,18 @@ pub const Grant = struct {
};
/// An authority object held by the host: copies of a capability share it.
pub const Authority = struct { kind: u16, scope: ?[]const u8 };
/// For `mem.alloc`: `limit` (null = unlimited), `used` live bytes and the
/// `parent` it was narrowed from; charges walk the chain (spec 03 §18.1).
pub const Authority = struct {
kind: u16,
scope: ?[]const u8,
limit: ?u64 = null,
used: u64 = 0,
parent: ?u32 = null,
};
/// A region: its authority and the bytes charged by its current generation.
pub const Region = struct { authority: u32, used: u64 };
pub const Options = struct {
/// Maximum number of instructions to execute (spec 11 §7.1); null means unlimited.
@@ -139,8 +155,15 @@ pub fn run(arena: std.mem.Allocator, module: air.Module, entry: []const u8, opti
if (std.mem.eql(u8, g.parameter, pname)) break g;
} else return .{ .not_instantiated = .{ .reason = "missing_capability", .parameter = pname, .kind = kind } };
if (!std.mem.eql(u8, g.kind, kind)) return .{ .not_instantiated = .{ .reason = "kind_mismatch", .parameter = pname, .kind = kind, .granted = g.kind } };
if (!air.authority.validScope(p.ty.cap, g.scope)) return .{ .not_instantiated = .{ .reason = "invalid_scope", .parameter = pname, .kind = kind, .scope = g.scope } };
try m.authorities.append(arena, .{ .kind = p.ty.cap, .scope = g.scope });
// The deterministic profile requires an explicit allocation budget (spec 03 §18.2).
const is_alloc = air.authority.kinds[p.ty.cap].scope == .byte_budget;
if (!air.authority.validScope(p.ty.cap, g.scope) or (is_alloc and g.scope == null))
return .{ .not_instantiated = .{ .reason = "invalid_scope", .parameter = pname, .kind = kind, .scope = g.scope } };
try m.authorities.append(arena, .{
.kind = p.ty.cap,
.scope = g.scope,
.limit = if (is_alloc) std.fmt.parseInt(u64, g.scope.?, 10) catch unreachable else null,
});
arg.* = .{ .cap = @intCast(m.authorities.items.len - 1) };
}
for (options.grants) |g| {
@@ -204,6 +227,8 @@ const Machine = struct {
/// Host authority table; capabilities index into it.
authorities: std.ArrayList(Authority) = .empty,
world: world_mod.World,
owners: std.AutoHashMapUnmanaged(*Value.Cell, OwnInfo) = .empty,
regions: std.ArrayList(Region) = .empty,
/// Instructions executed so far.
steps: u64 = 0,
@@ -347,6 +372,7 @@ 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 => |x| return m.narrow(f, vals, x),
.own_new, .own_array, .own_take, .own_free, .region_create, .region_new, .region_array, .region_reset, .region_destroy => return m.execAlloc(f, vals, {}, inst),
.intrinsic => |x| return m.intrinsic(f, vals, inst, x),
.ret => |v| return .{ .ret = if (v) |x| vals[x] else .void },
.trap => return .{ .trap = .explicit },
@@ -460,8 +486,20 @@ const Machine = struct {
}
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 parent = vals[x.cap].cap;
const a = m.authorities.items[parent];
if (std.mem.eql(u8, x.form, "budget")) {
// A child budget; nothing is reserved (spec 03 §18.3).
const n = usize_(vals[x.args[0]]);
if (a.limit) |lim| if (n > lim) {
vals[f.blocks[x.err].params[0].value] = .{ .builtin = .{ .which = .cap_error, .variant = 1 } };
return .{ .jump = x.err };
};
try m.authorities.append(m.arena, .{ .kind = a.kind, .scope = null, .limit = n, .parent = parent });
vals[f.blocks[x.ok].params[0].value] = .{ .cap = @intCast(m.authorities.items.len - 1) };
return .{ .jump = x.ok };
}
// `prefix` (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| {
@@ -473,6 +511,131 @@ const Machine = struct {
return .{ .jump = x.ok };
}
// ------------------------------------------------------------ heap and regions (spec 03 §18–§20)
/// Charges `bytes` to authority `a` and all its ancestors, or fails
/// without charging anything if any limit would be exceeded.
fn charge(m: *Machine, a: u32, bytes: ?u64) bool {
const b = bytes orelse return false; // size overflow
var x: ?u32 = a;
while (x) |i| : (x = m.authorities.items[i].parent) {
const auth = m.authorities.items[i];
if (auth.limit) |lim| if (auth.used > lim or b > lim - auth.used) return false;
}
x = a;
while (x) |i| : (x = m.authorities.items[i].parent) m.authorities.items[i].used += b;
return true;
}
fn uncharge(m: *Machine, a: u32, bytes: u64) void {
var x: ?u32 = a;
while (x) |i| : (x = m.authorities.items[i].parent) m.authorities.items[i].used -= bytes;
}
fn arrayBytes(m: *Machine, element: Value, n: u64) ?u64 {
const each = m.valueBytes(element) orelse return null;
return std.math.mul(u64, n, each) catch null;
}
/// Accounted size (spec 08 §7.1) of the type of a runtime value; equal
/// to `budget.accountedSize` of the value's static type.
fn valueBytes(m: *Machine, v: Value) ?u64 {
return switch (v) {
.int => |x| x.ty.bits() / 8,
.boolean => 1,
.aggregate => |a| budget.accountedSize(m.module, .{ .named = a.decl }, 0),
.array => |items| std.math.mul(u64, items.len, m.valueBytes(items[0]) orelse return null) catch null,
.builtin => |b| budget.accountedSize(m.module, .{ .builtin = b.which }, 0),
.cap => 8,
else => unreachable, // only value types are allocated (spec 03 §19.2)
};
}
fn allocFailed(f: air.Function, vals: []Value, err: u32) Step {
vals[f.blocks[err].params[0].value] = .{ .builtin = .{ .which = .alloc_error, .variant = 0 } };
return .{ .jump = err };
}
/// Owner cells remember their charge and authority for `own.free`.
const OwnInfo = struct { authority: u32, bytes: u64 };
fn execAlloc(m: *Machine, f: air.Function, vals: []Value, types_of: anytype, inst: air.Inst) !Step {
_ = types_of;
switch (inst.op) {
.own_new => |x| {
const v = vals[x.value];
const bytes = m.valueBytes(vals[x.value]);
const a = vals[x.cap].cap;
if (!m.charge(a, bytes)) return allocFailed(f, vals, x.err);
const cell = try m.arena.create(Value.Cell);
cell.* = .{ .value = try m.deepCopy(v), .ty = .void };
try m.owners.put(m.arena, cell, .{ .authority = a, .bytes = bytes.? });
vals[f.blocks[x.ok].params[0].value] = .{ .own = cell };
return .{ .jump = x.ok };
},
.own_array => |x| {
const n = usize_(vals[x.n]);
const a = vals[x.cap].cap;
const bytes = m.arrayBytes(vals[x.value], n);
if (!m.charge(a, bytes)) return allocFailed(f, vals, x.err);
const items = try m.arena.alloc(Value, n);
for (items) |*it| it.* = try m.deepCopy(vals[x.value]);
const cell = try m.arena.create(Value.Cell);
cell.* = .{ .value = .{ .array = items }, .ty = .void };
try m.owners.put(m.arena, cell, .{ .authority = a, .bytes = bytes.? });
vals[f.blocks[x.ok].params[0].value] = .{ .own = cell };
return .{ .jump = x.ok };
},
.own_take => |v| {
const cell = vals[v].own;
const info = m.owners.fetchRemove(cell).?.value;
m.uncharge(info.authority, info.bytes);
return bind(vals, inst.result, cell.value);
},
.own_free => |v| {
const info = m.owners.fetchRemove(vals[v].own).?.value;
m.uncharge(info.authority, info.bytes);
return .next;
},
.region_create => |x| {
try m.regions.append(m.arena, .{ .authority = vals[x.cap].cap, .used = 0 });
vals[f.blocks[x.ok].params[0].value] = .{ .region = @intCast(m.regions.items.len - 1) };
return .{ .jump = x.ok };
},
.region_new, .region_array => {
const rb, const value, const n: ?u64 = switch (inst.op) {
.region_new => |x| .{ x.region, x.value, null },
.region_array => |x| .{ x.region, x.value, usize_(vals[x.n]) },
else => unreachable,
};
const t = air.allocTargets(inst.op).?;
const r = placePtr(asPlace(vals[rb])).region;
const region = &m.regions.items[r];
const bytes = if (n) |count| m.arrayBytes(vals[value], count) else m.valueBytes(vals[value]);
if (!m.charge(region.authority, bytes)) return allocFailed(f, vals, t.err);
region.used += bytes.?;
const cell = try m.arena.create(Value.Cell);
if (n) |count| {
const items = try m.arena.alloc(Value, count);
for (items) |*it| it.* = try m.deepCopy(vals[value]);
cell.* = .{ .value = .{ .array = items }, .ty = .void };
vals[f.blocks[t.ok].params[0].value] = .{ .slice = .{ .place = .{ .cell = cell, .path = &.{} }, .start = 0, .len = count } };
} else {
cell.* = .{ .value = try m.deepCopy(vals[value]), .ty = .void };
vals[f.blocks[t.ok].params[0].value] = .{ .place = .{ .cell = cell, .path = &.{} } };
}
return .{ .jump = t.ok };
},
.region_reset, .region_destroy => |v| {
const region = &m.regions.items[vals[v].region];
m.uncharge(region.authority, region.used);
region.used = 0;
return .next;
},
else => unreachable,
}
}
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 {
@@ -582,6 +745,16 @@ const Machine = struct {
.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.
// Owners: the heap cell itself; arrays are borrowed as slices.
.own => |cell| switch (cell.value) {
.array => |items| .{ .slice = .{ .place = .{ .cell = cell, .path = &.{} }, .start = 0, .len = items.len } },
else => .{ .place = .{ .cell = cell, .path = &.{} } },
},
.region => |r| blk: {
const cell = try m.arena.create(Value.Cell);
cell.* = .{ .value = .{ .region = r }, .ty = .void };
break :blk .{ .place = .{ .cell = cell, .path = &.{} } };
},
.resource => |hd| blk: {
const cell = try m.arena.create(Value.Cell);
cell.* = .{ .value = .{ .resource = hd }, .ty = .void };
@@ -787,7 +960,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),
.resource, .own, .region => try s.write(null),
// A capability is opaque: only its kind is shown, never its identity.
.cap => {
try s.beginObject();