Phase 2: unsafe operations and trusted boundaries (RFC 0009)
- air: string literals (trusted line only), trusted obligation on functions, assume, borrow.index.unchecked - verifier: unsafe stage (E6001 outside_boundary / trusted_declares_unsafe); effect stage leaves unsafe to it, so trusted functions discharge it; assume establishes bounds facts - interp: T0009 for detected unsafe precondition violations - aji check --report unsafe: trusted functions with obligations, unsafe functions, unsafe operations with their boundary - feature unsafe published and supported; 10 conformance tests; 3000 mutants without a crash
This commit is contained in:
1 parent
c510a37cf9
commit
008654999e
24 files changed
+422
-18
No files matched your search
@@ -37,10 +37,11 @@ pub const registry = [_]Feature{
|
||||
.{ .name = "resources", .depends = &.{ "capabilities", "effects", "ownership" }, .status = .published, .phase = 2 },
|
||||
.{ .name = "sync", .depends = &.{"ownership"}, .status = .reserved, .phase = 3 },
|
||||
.{ .name = "tasks", .depends = &.{"ownership"}, .status = .reserved, .phase = 3 },
|
||||
.{ .name = "unsafe", .depends = &.{ "arrays", "effects", "ownership" }, .status = .published, .phase = 2 },
|
||||
};
|
||||
|
||||
/// Features implemented by this toolchain, sorted.
|
||||
pub const supported = [_][]const u8{ "arrays", "capabilities", "effects", "heap", "ownership", "regions", "resources" };
|
||||
pub const supported = [_][]const u8{ "arrays", "capabilities", "effects", "heap", "ownership", "regions", "resources", "unsafe" };
|
||||
|
||||
pub const Reason = enum {
|
||||
unknown_feature,
|
||||
@@ -118,6 +119,7 @@ const test_registry = [_]Feature{
|
||||
.{ .name = "regions", .depends = &.{"ownership"}, .status = .published, .phase = 1 },
|
||||
.{ .name = "islands", .depends = &.{ "ownership", "regions" }, .status = .published, .phase = 4 },
|
||||
.{ .name = "tasks", .depends = &.{"ownership"}, .status = .reserved, .phase = 3 },
|
||||
.{ .name = "unsafe", .depends = &.{ "arrays", "effects", "ownership" }, .status = .published, .phase = 2 },
|
||||
};
|
||||
|
||||
fn expectProblems(declared: []const []const u8, sup: []const []const u8, want: []const Reason) !void {
|
||||
|
||||
+6
-2
@@ -221,7 +221,7 @@ pub const Op = union(enum) {
|
||||
store: struct { borrow: ValueId, value: ValueId },
|
||||
// Feature `arrays`.
|
||||
array_splat: struct { ty: Type, value: ValueId },
|
||||
borrow_index: struct { borrow: ValueId, index: ValueId, proven: bool },
|
||||
borrow_index: struct { borrow: ValueId, index: ValueId, proven: bool, unchecked: bool = false },
|
||||
slice_make: ValueId,
|
||||
slice_len: ValueId,
|
||||
slice_sub: struct { slice: ValueId, start: ValueId, len: ValueId },
|
||||
@@ -229,6 +229,8 @@ pub const Op = union(enum) {
|
||||
slice_split: struct { slice: ValueId, at: ValueId },
|
||||
slice_copy: struct { dst: ValueId, src: ValueId },
|
||||
guard: ValueId,
|
||||
// Feature `unsafe` (spec 13 §6).
|
||||
assume: ValueId,
|
||||
|
||||
@"const": struct { ty: Type, bits: u128 },
|
||||
copy: ValueId,
|
||||
@@ -302,6 +304,8 @@ pub const Function = struct {
|
||||
ret: Type,
|
||||
/// Index into `params` of the `from` parameter of a borrow return.
|
||||
ret_from: ?u32 = null,
|
||||
/// Proof obligation of a `trusted` boundary (feature `unsafe`).
|
||||
trusted: ?[]const u8 = null,
|
||||
effects: []const []const u8,
|
||||
blocks: []const Block,
|
||||
values: []const ValueInfo,
|
||||
@@ -427,7 +431,7 @@ pub fn forEachUse(op: Op, ctx: anytype, comptime f: fn (@TypeOf(ctx), ValueId) v
|
||||
f(ctx, x.local);
|
||||
f(ctx, x.value);
|
||||
},
|
||||
.local_zero, .local_load, .borrow_ref, .borrow_mut, .borrow_end, .load, .slice_make, .slice_len, .guard => |v| f(ctx, v),
|
||||
.local_zero, .local_load, .borrow_ref, .borrow_mut, .borrow_end, .load, .slice_make, .slice_len, .guard, .assume => |v| f(ctx, v),
|
||||
.borrow_field => |x| f(ctx, x.borrow),
|
||||
.store => |x| {
|
||||
f(ctx, x.borrow);
|
||||
|
||||
+50
-2
@@ -60,6 +60,8 @@ const Tag = enum {
|
||||
global,
|
||||
/// Raw numeric text, including an optional leading `-` and any `.`.
|
||||
number,
|
||||
/// `"…"`; text excludes the quotes, escapes not yet decoded.
|
||||
string,
|
||||
invalid,
|
||||
eof,
|
||||
};
|
||||
@@ -145,6 +147,18 @@ fn tokenize(arena: Allocator, src: []const u8) Allocator.Error![]const Token {
|
||||
else => .r_brace,
|
||||
};
|
||||
},
|
||||
'"' => {
|
||||
i += 1;
|
||||
while (i < src.len and src[i] != '"' and src[i] != '\n') : (i += 1) {
|
||||
if (src[i] == '\\' and i + 1 < src.len) i += 1;
|
||||
}
|
||||
if (i < src.len and src[i] == '"') {
|
||||
i += 1;
|
||||
try tokens.append(arena, .{ .tag = .string, .text = src[start + 1 .. i - 1], .span = span });
|
||||
continue;
|
||||
}
|
||||
tag = .invalid;
|
||||
},
|
||||
'%', '@' => {
|
||||
i += 1;
|
||||
while (i < src.len and isNameChar(src[i])) i += 1;
|
||||
@@ -643,6 +657,16 @@ const Parser = struct {
|
||||
const effects_tok = try p.expectWord("effects");
|
||||
const effects = try p.parsePathList();
|
||||
_ = try p.expect(.nl, "end of line");
|
||||
var trusted: ?[]const u8 = null;
|
||||
p.skipNewlines();
|
||||
if (p.atWord("trusted")) {
|
||||
const tok = p.next();
|
||||
try p.requireFeature("unsafe", tok.span, "trusted");
|
||||
const str = try p.expect(.string, "obligation string");
|
||||
trusted = unescapeString(p.arena, str.text) catch return p.fail(str, "string with escapes \\\", \\\\ or \\n");
|
||||
if (trusted.?.len == 0) return p.fail(str, "non-empty obligation string");
|
||||
_ = try p.expect(.nl, "end of line");
|
||||
}
|
||||
// Effect names are checked against the registry when the module
|
||||
// declares `effects` (spec 05 §9.1).
|
||||
if (p.declares("effects")) for (effects) |e| {
|
||||
@@ -671,6 +695,7 @@ const Parser = struct {
|
||||
.params = params.items,
|
||||
.ret = ret,
|
||||
.ret_from = ret_from,
|
||||
.trusted = trusted,
|
||||
.effects = effects,
|
||||
.blocks = blocks.items,
|
||||
.values = p.values.items,
|
||||
@@ -1046,6 +1071,8 @@ const Parser = struct {
|
||||
@"array.splat",
|
||||
@"borrow.index",
|
||||
@"borrow.index.proven",
|
||||
@"borrow.index.unchecked",
|
||||
assume,
|
||||
@"slice.make",
|
||||
@"slice.len",
|
||||
@"slice.sub",
|
||||
@@ -1056,6 +1083,7 @@ const Parser = struct {
|
||||
const name = std.meta.stringToEnum(Name, op_tok.text) orelse return null;
|
||||
const feature: []const u8 = switch (name) {
|
||||
.@"local.alloc", .@"local.store", .@"local.zero", .@"local.load", .@"borrow.ref", .@"borrow.mut", .@"borrow.field", .@"borrow.end", .load, .store => "ownership",
|
||||
.@"borrow.index.unchecked", .assume => "unsafe",
|
||||
else => "arrays",
|
||||
};
|
||||
try p.requireFeature(feature, op_tok.span, op_tok.text);
|
||||
@@ -1090,10 +1118,11 @@ const Parser = struct {
|
||||
const ty = try p.parseType();
|
||||
break :blk .{ .array_splat = .{ .ty = ty, .value = try p.useValue() } };
|
||||
},
|
||||
.@"borrow.index", .@"borrow.index.proven" => blk: {
|
||||
.@"borrow.index", .@"borrow.index.proven", .@"borrow.index.unchecked" => blk: {
|
||||
const b, const i = try p.twoOperands();
|
||||
break :blk .{ .borrow_index = .{ .borrow = b, .index = i, .proven = name == .@"borrow.index.proven" } };
|
||||
break :blk .{ .borrow_index = .{ .borrow = b, .index = i, .proven = name == .@"borrow.index.proven", .unchecked = name == .@"borrow.index.unchecked" } };
|
||||
},
|
||||
.assume => .{ .assume = try p.useValue() },
|
||||
.@"slice.make" => .{ .slice_make = try p.useValue() },
|
||||
.@"slice.len" => .{ .slice_len = try p.useValue() },
|
||||
.@"slice.sub" => blk: {
|
||||
@@ -1217,6 +1246,25 @@ pub fn literalBits(text: []const u8, ty: air.IntType) ?u128 {
|
||||
return if (n == 128) raw else raw & ((@as(u128, 1) << @intCast(n)) - 1);
|
||||
}
|
||||
|
||||
fn unescapeString(arena: Allocator, s: []const u8) ![]const u8 {
|
||||
var out: std.ArrayList(u8) = .empty;
|
||||
var i: usize = 0;
|
||||
while (i < s.len) : (i += 1) {
|
||||
if (s[i] != '\\') {
|
||||
try out.append(arena, s[i]);
|
||||
continue;
|
||||
}
|
||||
i += 1;
|
||||
try out.append(arena, switch (s[i]) {
|
||||
'"' => '"',
|
||||
'\\' => '\\',
|
||||
'n' => '\n',
|
||||
else => return error.BadEscape,
|
||||
});
|
||||
}
|
||||
return out.items;
|
||||
}
|
||||
|
||||
fn parseScalarType(text: []const u8) ?air.Type {
|
||||
if (eql(text, "bool")) return .bool;
|
||||
if (std.meta.stringToEnum(air.IntType, text)) |it| return .{ .int = it };
|
||||
|
||||
+12
-1
@@ -51,6 +51,16 @@ pub fn print(m: air.Module, w: *Writer) Writer.Error!void {
|
||||
try w.writeAll("\neffects [");
|
||||
try list(w, f.effects);
|
||||
try w.writeAll("]\n");
|
||||
if (f.trusted) |t| {
|
||||
try w.writeAll("trusted \"");
|
||||
for (t) |ch| switch (ch) {
|
||||
'"' => try w.writeAll("\\\""),
|
||||
'\\' => try w.writeAll("\\\\"),
|
||||
'\n' => try w.writeAll("\\n"),
|
||||
else => try w.writeByte(ch),
|
||||
};
|
||||
try w.writeAll("\"\n");
|
||||
}
|
||||
for (f.blocks) |b| {
|
||||
try w.writeAll(b.name);
|
||||
if (b.params.len != 0) {
|
||||
@@ -276,7 +286,8 @@ fn printOp(m: air.Module, f: air.Function, op: air.Op, w: *Writer) Writer.Error!
|
||||
try w.writeByte(' ');
|
||||
try value(f, x.value, w);
|
||||
},
|
||||
.borrow_index => |x| try two(f, w, if (x.proven) "borrow.index.proven" else "borrow.index", x.borrow, x.index),
|
||||
.borrow_index => |x| try two(f, w, if (x.unchecked) "borrow.index.unchecked" else if (x.proven) "borrow.index.proven" else "borrow.index", x.borrow, x.index),
|
||||
.assume => |v| try one(f, w, "assume", v),
|
||||
.slice_make => |v| try one(f, w, "slice.make", v),
|
||||
.slice_len => |v| try one(f, w, "slice.len", v),
|
||||
.slice_sub => |x| {
|
||||
|
||||
+2
-1
@@ -60,7 +60,7 @@ pub const registry = [_]Code{
|
||||
.{ .id = "E5002", .kind = "air.invalid_cfg", .meaning = "Invalid block/terminator structure" },
|
||||
.{ .id = "E5101", .kind = "verifier.resource_limit", .meaning = "Deterministic verifier resource limit exceeded" },
|
||||
// E6xxx — Unsafe/ABI
|
||||
.{ .id = "E6001", .kind = "unsafe.required", .meaning = "Operation requires explicit unsafe boundary" },
|
||||
.{ .id = "E6001", .kind = "unsafe.required", .meaning = "Operation requires explicit unsafe boundary; field `reason`: `outside_boundary`, `trusted_declares_unsafe`" },
|
||||
.{ .id = "E6101", .kind = "abi.unaligned_reference", .meaning = "Normal reference requested from insufficiently aligned storage" },
|
||||
// T0xxx — Runtime traps (reported in trap records, not by the verifier)
|
||||
.{ .id = "T0001", .kind = "trap.explicit", .meaning = "`trap` instruction executed" },
|
||||
@@ -71,6 +71,7 @@ pub const registry = [_]Code{
|
||||
.{ .id = "T0006", .kind = "trap.cast_out_of_range", .meaning = "Checked cast value not representable in target type" },
|
||||
.{ .id = "T0007", .kind = "trap.call_depth", .meaning = "Call depth limit (1 024 frames) exceeded" },
|
||||
.{ .id = "T0008", .kind = "trap.out_of_bounds", .meaning = "Runtime bounds check failed" },
|
||||
.{ .id = "T0009", .kind = "trap.unsafe_precondition", .meaning = "Unsafe precondition violated (detected)" },
|
||||
};
|
||||
|
||||
pub fn lookup(id: []const u8) ?*const Code {
|
||||
|
||||
@@ -190,6 +190,7 @@ const TrapKind = enum {
|
||||
cast_out_of_range,
|
||||
call_depth,
|
||||
out_of_bounds,
|
||||
unsafe_precondition,
|
||||
|
||||
fn code(k: TrapKind) *const diag.Code {
|
||||
return switch (k) {
|
||||
@@ -201,6 +202,7 @@ const TrapKind = enum {
|
||||
.cast_out_of_range => diag.lookup("T0006").?,
|
||||
.call_depth => diag.lookup("T0007").?,
|
||||
.out_of_bounds => diag.lookup("T0008").?,
|
||||
.unsafe_precondition => diag.lookup("T0009").?,
|
||||
};
|
||||
}
|
||||
};
|
||||
@@ -376,7 +378,7 @@ const Machine = struct {
|
||||
.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),
|
||||
.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, .assume => return m.execMemory(vals, inst),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -782,7 +784,9 @@ const Machine = struct {
|
||||
};
|
||||
// `.proven` was verified in bounds; the check is kept as a
|
||||
// defensive assertion that can never fire on verified AIR.
|
||||
if (i >= len) return .{ .trap = .out_of_bounds };
|
||||
// The reference interpreter detects violated unsafe
|
||||
// preconditions (spec 13 §6.1).
|
||||
if (i >= len) return .{ .trap = if (x.unchecked) .unsafe_precondition else .out_of_bounds };
|
||||
return bind(vals, inst.result, .{ .place = try m.extend(place, start + i) });
|
||||
},
|
||||
.slice_make => |v| {
|
||||
@@ -816,6 +820,7 @@ const Machine = struct {
|
||||
return .next;
|
||||
},
|
||||
.guard => |v| return if (vals[v].boolean) .next else .{ .trap = .assert },
|
||||
.assume => |v| return if (vals[v].boolean) .next else .{ .trap = .unsafe_precondition },
|
||||
else => unreachable,
|
||||
}
|
||||
}
|
||||
|
||||
+10
-1
@@ -17,7 +17,9 @@ const usage =
|
||||
\\usage: aji <command> [args]
|
||||
\\
|
||||
\\commands:
|
||||
\\ check <file.air> parse and verify a text AIR module
|
||||
\\ check [--report unsafe] <file.air>
|
||||
\\ parse and verify a text AIR module; the unsafe report
|
||||
\\ lists trusted boundaries and unsafe operations
|
||||
\\ run [--fuel N] [--grant P=KIND[:SCOPE]]... <file.air>
|
||||
\\ verify, then run @main and print the run record;
|
||||
\\ --fuel stops after N executed instructions;
|
||||
@@ -87,6 +89,12 @@ fn run(io: std.Io, arena: std.mem.Allocator, args: []const [:0]const u8, out: *s
|
||||
var files: std.ArrayList(struct { []const u8, []const u8 }) = .empty;
|
||||
var result_file: ?[]const u8 = null;
|
||||
var rest = args[2..];
|
||||
var unsafe_report = false;
|
||||
if (std.mem.eql(u8, cmd, "check") and rest.len == 3 and std.mem.eql(u8, rest[0], "--report")) {
|
||||
if (!std.mem.eql(u8, rest[1], "unsafe")) return usageError("--report takes unsafe");
|
||||
unsafe_report = true;
|
||||
rest = rest[2..];
|
||||
}
|
||||
while (std.mem.eql(u8, cmd, "run") and rest.len >= 3) {
|
||||
const flag = rest[0];
|
||||
const value = rest[1];
|
||||
@@ -125,6 +133,7 @@ fn run(io: std.Io, arena: std.mem.Allocator, args: []const [:0]const u8, out: *s
|
||||
try d.writeJson(out);
|
||||
try out.writeByte('\n');
|
||||
}
|
||||
if (unsafe_report) if (report.module) |module| try aji.verifier.unsafe_.writeReport(module, out);
|
||||
if (report.status == .accepted and std.mem.eql(u8, cmd, "run")) {
|
||||
const module = report.module.?;
|
||||
var output: aji.interp.Output = undefined;
|
||||
|
||||
+3
-1
@@ -17,6 +17,7 @@ pub const cfg = @import("verifier/cfg.zig");
|
||||
pub const ssa = @import("verifier/ssa.zig");
|
||||
pub const types = @import("verifier/types.zig");
|
||||
pub const effects = @import("verifier/effects.zig");
|
||||
pub const unsafe_ = @import("verifier/unsafe.zig");
|
||||
pub const init = @import("verifier/init.zig");
|
||||
pub const borrow = @import("verifier/borrow.zig");
|
||||
pub const bounds = @import("verifier/bounds.zig");
|
||||
@@ -61,7 +62,7 @@ pub const Context = struct {
|
||||
/// stage, or an empty slice if the module verifies.
|
||||
pub fn verify(arena: std.mem.Allocator, file: []const u8, module: air.Module) std.mem.Allocator.Error![]const diag.Diagnostic {
|
||||
var c: Context = .{ .arena = arena, .file = file, .module = module };
|
||||
const stages = .{ budget.check, cfg.check, ssa.check, types.check, effects.check, init.check, borrow.check, bounds.check };
|
||||
const stages = .{ budget.check, cfg.check, ssa.check, types.check, effects.check, unsafe_.check, init.check, borrow.check, bounds.check };
|
||||
inline for (stages) |stage| {
|
||||
try stage(&c);
|
||||
if (c.diags.items.len != 0) {
|
||||
@@ -86,6 +87,7 @@ test {
|
||||
_ = ssa;
|
||||
_ = types;
|
||||
_ = effects;
|
||||
_ = unsafe_;
|
||||
_ = init;
|
||||
_ = borrow;
|
||||
_ = bounds;
|
||||
|
||||
+11
-3
@@ -49,6 +49,14 @@ fn factFrom(f: air.Function, cond: air.ValueId, truth: bool) ?Fact {
|
||||
};
|
||||
}
|
||||
|
||||
/// `guard` (checked) and `assume` (unsafe) both establish their condition.
|
||||
fn assertion(op: air.Op) ?air.ValueId {
|
||||
return switch (op) {
|
||||
.guard, .assume => |v| v,
|
||||
else => null,
|
||||
};
|
||||
}
|
||||
|
||||
fn constUsize(f: air.Function, v: air.ValueId) ?u128 {
|
||||
const inst = defOf(f, v) orelse return null;
|
||||
if (inst.op != .@"const") return null;
|
||||
@@ -69,8 +77,8 @@ fn checkFunction(c: *Context, f: air.Function, types: []const air.Type) !void {
|
||||
while (true) {
|
||||
if (d != 0 and preds[d].len == 1) if (edgeFact(f, preds[d][0], d)) |fact| try facts.append(c.arena, fact);
|
||||
// Guards anywhere in a strict dominator have executed before b.
|
||||
if (d != b) for (f.blocks[d].insts) |inst| if (inst.op == .guard) {
|
||||
if (factFrom(f, inst.op.guard, true)) |fact| try facts.append(c.arena, fact);
|
||||
if (d != b) for (f.blocks[d].insts) |inst| if (assertion(inst.op)) |cond| {
|
||||
if (factFrom(f, cond, true)) |fact| try facts.append(c.arena, fact);
|
||||
};
|
||||
if (d == 0) break;
|
||||
d = dom.idom[d];
|
||||
@@ -78,7 +86,7 @@ fn checkFunction(c: *Context, f: air.Function, types: []const air.Type) !void {
|
||||
|
||||
for (f.blocks[b].insts, 0..) |inst, ii| {
|
||||
switch (inst.op) {
|
||||
.guard => |g| if (factFrom(f, g, true)) |fact| try facts.append(c.arena, fact),
|
||||
.guard, .assume => |g| if (factFrom(f, g, true)) |fact| try facts.append(c.arena, fact),
|
||||
.borrow_index => |x| if (x.proven and !proven(f, types, facts.items, x.borrow, x.index)) {
|
||||
try c.report("E2103", inst.span, "element access not proven in bounds", &.{
|
||||
.{ .name = "function", .value = .{ .str = f.name } },
|
||||
|
||||
@@ -18,7 +18,9 @@ pub fn check(c: *Context) !void {
|
||||
for (f.blocks) |b| for (b.insts) |inst| switch (inst.op) {
|
||||
.call => |x| {
|
||||
const callee = m.functions[x.callee];
|
||||
for (callee.effects) |e| if (!contains(f.effects, e)) {
|
||||
// `unsafe` is checked by the unsafe stage, which knows about
|
||||
// `trusted` boundaries (spec 13 §6.4).
|
||||
for (callee.effects) |e| if (!std.mem.eql(u8, e, "unsafe") and !contains(f.effects, e)) {
|
||||
try c.report("E3101", inst.span, "callee effect not declared by the caller", &.{
|
||||
.{ .name = "function", .value = .{ .str = f.name } },
|
||||
.{ .name = "callee", .value = .{ .str = callee.name } },
|
||||
|
||||
@@ -487,7 +487,7 @@ fn checkInst(fc: *FnCtx, inst: air.Inst) !void {
|
||||
const s = fc.typeOf(x.src);
|
||||
if (!s.isSlice() or !s.inner().?.eql(d.inner().?)) return fc.kindError(span, x.src, try std.fmt.allocPrint(fc.c.arena, "slice<{s}> or slice_mut<{s}>", .{ try fc.c.typeName(d.inner().?), try fc.c.typeName(d.inner().?) }));
|
||||
},
|
||||
.guard => |v| try fc.expectValue(span, v, .bool),
|
||||
.guard, .assume => |v| try fc.expectValue(span, v, .bool),
|
||||
.arith => |x| {
|
||||
try fc.expectValue(span, x.a, .{ .int = x.ty });
|
||||
try fc.expectValue(span, x.b, .{ .int = x.ty });
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
//! Unsafe boundaries (spec 13 §6.4). Reports E6001.
|
||||
//!
|
||||
//! An unsafe operation, or a call to a function declaring the effect
|
||||
//! `unsafe`, is allowed only in a function that declares `unsafe` itself or
|
||||
//! is `trusted`. A `trusted` function is the boundary and must not declare
|
||||
//! `unsafe`.
|
||||
|
||||
const std = @import("std");
|
||||
const air = @import("../air.zig");
|
||||
const verifier = @import("../verifier.zig");
|
||||
|
||||
const Context = verifier.Context;
|
||||
|
||||
pub fn declaresUnsafe(f: air.Function) bool {
|
||||
for (f.effects) |e| if (std.mem.eql(u8, e, "unsafe")) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
/// Description of the unsafe operation `op`, or null if it is safe.
|
||||
pub fn unsafeOp(m: air.Module, op: air.Op) ?[]const u8 {
|
||||
return switch (op) {
|
||||
.assume => "assume",
|
||||
.borrow_index => |x| if (x.unchecked) "borrow.index.unchecked" else null,
|
||||
.call => |x| if (declaresUnsafe(m.functions[x.callee])) "call of an unsafe function" else null,
|
||||
else => null,
|
||||
};
|
||||
}
|
||||
|
||||
pub fn check(c: *Context) !void {
|
||||
const m = c.module;
|
||||
for (m.functions) |f| {
|
||||
const is_unsafe = declaresUnsafe(f);
|
||||
if (f.trusted != null and is_unsafe) {
|
||||
try c.report("E6001", f.span, "a trusted boundary must not declare the effect unsafe", &.{
|
||||
.{ .name = "reason", .value = .{ .str = "trusted_declares_unsafe" } },
|
||||
.{ .name = "function", .value = .{ .str = f.name } },
|
||||
});
|
||||
}
|
||||
if (is_unsafe or f.trusted != null) continue;
|
||||
for (f.blocks) |b| for (b.insts) |inst| if (unsafeOp(m, inst.op)) |what| {
|
||||
try c.report("E6001", inst.span, "unsafe operation outside an unsafe or trusted function", &.{
|
||||
.{ .name = "reason", .value = .{ .str = "outside_boundary" } },
|
||||
.{ .name = "function", .value = .{ .str = f.name } },
|
||||
.{ .name = "op", .value = .{ .str = what } },
|
||||
});
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/// The unsafe report (spec 13 §7): one JSON object per line, source order.
|
||||
pub fn writeReport(m: air.Module, w: *std.Io.Writer) std.Io.Writer.Error!void {
|
||||
for (m.functions) |f| {
|
||||
var s: std.json.Stringify = .{ .writer = w };
|
||||
if (f.trusted) |t| {
|
||||
try s.write(.{ .report = "unsafe", .kind = "trusted_function", .function = f.name, .obligation = t });
|
||||
try w.writeByte('\n');
|
||||
} else if (declaresUnsafe(f)) {
|
||||
try s.write(.{ .report = "unsafe", .kind = "unsafe_function", .function = f.name });
|
||||
try w.writeByte('\n');
|
||||
}
|
||||
for (f.blocks) |b| for (b.insts, 0..) |inst, ii| if (unsafeOp(m, inst.op)) |what| {
|
||||
var so: std.json.Stringify = .{ .writer = w };
|
||||
try so.write(.{
|
||||
.report = "unsafe",
|
||||
.kind = "operation",
|
||||
.function = f.name,
|
||||
.block = b.name,
|
||||
.inst = ii,
|
||||
.op = what,
|
||||
.boundary = if (f.trusted != null) f.name else null,
|
||||
});
|
||||
try w.writeByte('\n');
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const h = "module t\nair 0\nlang 0.1\nfeatures [arrays, effects, ownership, unsafe]\n";
|
||||
const get = "\neffects []\ntrusted \"callers pass %i < len\"\nentry:\n %e = borrow.index.unchecked %s, %i\n %v = load %e\n borrow.end %e\n ret %v\n";
|
||||
|
||||
test "trusted boundary" {
|
||||
try verifier.expectCodes(h ++ "fn @get(%s: slice<u8>, %i: usize) -> u8" ++ get, &.{});
|
||||
try verifier.expectCodes(h ++ "fn @get(%s: slice<u8>, %i: usize) -> u8\neffects []\nentry:\n %e = borrow.index.unchecked %s, %i\n %v = load %e\n borrow.end %e\n ret %v\n", &.{"E6001"});
|
||||
const raw = "fn @raw() -> void\neffects [unsafe]\nentry:\n ret\n";
|
||||
try verifier.expectCodes(h ++ "fn @f() -> void\neffects []\nentry:\n call @raw()\n ret\n" ++ raw, &.{"E6001"});
|
||||
try verifier.expectCodes(h ++ "fn @f() -> void\neffects [unsafe]\nentry:\n call @raw()\n ret\n" ++ raw, &.{});
|
||||
try verifier.expectCodes(h ++ "fn @f() -> void\neffects []\ntrusted \"raw is fine here\"\nentry:\n call @raw()\n ret\n" ++ raw, &.{});
|
||||
try verifier.expectCodes(h ++ "fn @f() -> void\neffects [unsafe]\ntrusted \"x\"\nentry:\n ret\n", &.{"E6001"});
|
||||
}
|
||||
|
||||
test writeReport {
|
||||
var arena_state: std.heap.ArenaAllocator = .init(std.testing.allocator);
|
||||
defer arena_state.deinit();
|
||||
const r = try air.parse.parse(arena_state.allocator(), "t.air", h ++ "fn @get(%s: slice<u8>, %i: usize) -> u8" ++ get);
|
||||
var buf: [1024]u8 = undefined;
|
||||
var w: std.Io.Writer = .fixed(&buf);
|
||||
try writeReport(r.module.?, &w);
|
||||
try std.testing.expectEqualStrings(
|
||||
\\{"report":"unsafe","kind":"trusted_function","function":"get","obligation":"callers pass %i < len"}
|
||||
\\{"report":"unsafe","kind":"operation","function":"get","block":"entry","inst":0,"op":"borrow.index.unchecked","boundary":"get"}
|
||||
\\
|
||||
, w.buffered());
|
||||
}
|
||||
Reference in new issue
Block a user