Phase 5: race detector (P5-6) and the atomic_stats reference program (P5-9b)
Dynamic data-race detector for ordinary memory: vector clocks are the task-keyed part of the weak-memory views, so happens-before follows every synchronization edge already modelled; per-cell shadows with path granularity. Enabled for every conformance run test (433, no false positive); a unit test shows an unverified racy program caught on every schedule. Reference program atomic_stats in .aji and hand-written AIR by an independent author (equivalent:, 30 schedule seeds). Author feedback: 07a clarifications; Q-025 (no array construction) logged.
This commit is contained in:
1 parent
4242132b2a
commit
0879b9497b
10 files changed
+481
-10
No files matched your search
@@ -28,4 +28,5 @@ pub const memory_test = struct {
|
||||
test {
|
||||
_ = machine;
|
||||
_ = @import("interp/weak.zig");
|
||||
_ = @import("interp/race.zig");
|
||||
}
|
||||
+133
-6
@@ -28,6 +28,7 @@ const world_mod = @import("world.zig");
|
||||
const host_mod = @import("host.zig");
|
||||
const budget = @import("../verifier/budget.zig");
|
||||
const weak = @import("weak.zig");
|
||||
const race = @import("race.zig");
|
||||
|
||||
pub const WorldOptions = world_mod.Options;
|
||||
|
||||
@@ -105,7 +106,12 @@ pub const Value = union(enum) {
|
||||
};
|
||||
|
||||
/// Frame storage. `value` is `.void` while uninitialized.
|
||||
pub const Cell = struct { value: Value, ty: air.Type };
|
||||
pub const Cell = struct {
|
||||
value: Value,
|
||||
ty: air.Type,
|
||||
/// Accesses seen by the race detector (`Options.detect_races`).
|
||||
shadow: ?*race.Shadow = null,
|
||||
};
|
||||
|
||||
/// Path of field or element indices from the cell's value.
|
||||
pub const Place = struct { cell: *Cell, path: []const u32 };
|
||||
@@ -131,6 +137,9 @@ pub const Outcome = union(enum) {
|
||||
/// 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,
|
||||
/// The race detector (`Options.detect_races`) found two unordered
|
||||
/// conflicting accesses to ordinary memory: a verifier defect (spec 04 §21).
|
||||
race_detected: struct { at: Location, other_task: u32 },
|
||||
};
|
||||
|
||||
pub const Location = struct { function: []const u8, block: []const u8, inst: u32 };
|
||||
@@ -208,6 +217,8 @@ pub const Options = struct {
|
||||
/// Exhaustive exploration: choices come from `Explore` instead of the
|
||||
/// schedule generator (spec 04 §20.5).
|
||||
explore: ?*Explore = null,
|
||||
/// Check every ordinary access for data races (spec 04 §21; a test tool).
|
||||
detect_races: bool = false,
|
||||
};
|
||||
|
||||
/// Observable output of a run in the deterministic profile.
|
||||
@@ -274,6 +285,7 @@ pub fn run(arena: std.mem.Allocator, module: air.Module, entry: []const u8, opti
|
||||
m.exec_heap.every_step = options.collect_every_step;
|
||||
m.arc_events = options.arc_events;
|
||||
m.explore = options.explore;
|
||||
m.detect_races = options.detect_races;
|
||||
m.mem.weak_reads = hasWeakReads(module);
|
||||
if (options.collect_threshold) |t| {
|
||||
m.exec_heap.floor = t;
|
||||
@@ -361,7 +373,7 @@ const Copier = struct {
|
||||
if (c.cells.get(old)) |n| return n;
|
||||
const n = try c.to.create(Value.Cell);
|
||||
try c.cells.put(c.tmp, old, n);
|
||||
n.* = .{ .value = .void, .ty = old.ty };
|
||||
n.* = .{ .value = .void, .ty = old.ty, .shadow = if (old.shadow) |sh| try sh.copy(c.to) else null };
|
||||
n.value = try c.value(old.value);
|
||||
return n;
|
||||
}
|
||||
@@ -550,6 +562,7 @@ const Machine = struct {
|
||||
/// Atomic cells and the `seq_cst` view (spec 04 §42).
|
||||
mem: weak.Memory = .{},
|
||||
explore: ?*Explore = null,
|
||||
detect_races: bool = false,
|
||||
|
||||
// ------------------------------------------------------------ tasks and the scheduler (spec 04 §36)
|
||||
|
||||
@@ -557,6 +570,7 @@ const Machine = struct {
|
||||
/// returns, traps, or the environment stops it.
|
||||
fn runProgram(m: *Machine, fn_index: u32, args: []const Value) std.mem.Allocator.Error!Outcome {
|
||||
try m.tasks.append(m.arena, .{});
|
||||
if (m.detect_races) m.tasks.items[0].views.cur = try m.tasks.items[0].views.cur.with(race.clockKey(0), 1, m.heap());
|
||||
try m.pushFrame(0, fn_index, args);
|
||||
while (true) {
|
||||
// Safe point: between instructions no Zig local holds heap values.
|
||||
@@ -634,6 +648,7 @@ const Machine = struct {
|
||||
continue;
|
||||
},
|
||||
.task_limit => return .{ .limit_exceeded = .{ .kind = "tasks", .limit = m.task_limit, .steps = m.steps } },
|
||||
.race => |other| return .{ .race_detected = .{ .at = here, .other_task = other } },
|
||||
}
|
||||
if (m.quantum_used >= m.quantum) {
|
||||
if (try m.schedule()) |o| return o;
|
||||
@@ -795,6 +810,8 @@ const Machine = struct {
|
||||
task_limit,
|
||||
/// Continue at a block; the completed instruction is a scheduling point.
|
||||
jump_yield: u32,
|
||||
/// The race detector found a racing access by this task.
|
||||
race: u32,
|
||||
};
|
||||
|
||||
fn exec(m: *Machine, f: air.Function, vals: []Value, inst: air.Inst) std.mem.Allocator.Error!Step {
|
||||
@@ -883,8 +900,10 @@ const Machine = struct {
|
||||
m.spawned = true;
|
||||
const id: u32 = @intCast(m.tasks.items.len);
|
||||
// spawn → the child's first event (spec 04 §20.3).
|
||||
const parent = m.tasks.items[m.current].views.cur;
|
||||
var parent = m.tasks.items[m.current].views.cur;
|
||||
if (m.detect_races) parent = try parent.with(race.clockKey(id), 1, m.heap());
|
||||
try m.tasks.append(m.arena, .{ .views = .{ .cur = parent, .acq = parent } });
|
||||
try m.tick();
|
||||
try m.pushFrame(id, x.callee, try m.gather(vals, x.args));
|
||||
vals[inst.result.?] = .{ .task = id };
|
||||
return m.yieldUnlessExploring();
|
||||
@@ -903,6 +922,7 @@ const Machine = struct {
|
||||
const target = &m.tasks.items[vals[v].task];
|
||||
target.cancel = true;
|
||||
target.cancel_view = try target.cancel_view.join(m.tasks.items[m.current].views.cur, m.heap());
|
||||
try m.tick();
|
||||
return .yield;
|
||||
},
|
||||
.task_cancelled => {
|
||||
@@ -1003,6 +1023,7 @@ const Machine = struct {
|
||||
fn doSend(m: *Machine, id: u32, v: Value) !void {
|
||||
const c = &m.channels.items[id];
|
||||
const view = m.tasks.items[m.current].views.cur;
|
||||
try m.tick();
|
||||
if (c.capacity > 0) {
|
||||
try c.views.append(m.heap(), view);
|
||||
return c.buf.append(m.heap(), try m.deepCopy(v));
|
||||
@@ -1026,6 +1047,26 @@ const Machine = struct {
|
||||
return o.value;
|
||||
}
|
||||
|
||||
/// Advances the current task's clock after a releasing operation, so its
|
||||
/// later accesses are not ordered before what others acquired.
|
||||
fn tick(m: *Machine) !void {
|
||||
if (!m.detect_races) return;
|
||||
const t = &m.tasks.items[m.current];
|
||||
const key = race.clockKey(m.current);
|
||||
t.views.cur = try t.views.cur.with(key, t.views.cur.get(key) + 1, m.heap());
|
||||
}
|
||||
|
||||
/// An ordinary access by the current task (spec 04 §21).
|
||||
fn raceCheck(m: *Machine, cell: *Value.Cell, path: []const u32, write: bool) !?Step {
|
||||
if (!m.detect_races) return null;
|
||||
if (cell.shadow == null) {
|
||||
cell.shadow = try m.heap().create(race.Shadow);
|
||||
cell.shadow.?.* = .{};
|
||||
}
|
||||
const other = try race.access(m.heap(), cell.shadow.?, path, write, m.current, m.tasks.items[m.current].views.cur) orelse return null;
|
||||
return .{ .race = other };
|
||||
}
|
||||
|
||||
/// The `cancelled` outcome synchronizes with the cancels (spec 04 §20.3).
|
||||
fn observeCancel(m: *Machine) !void {
|
||||
const t = &m.tasks.items[m.current];
|
||||
@@ -1107,6 +1148,7 @@ const Machine = struct {
|
||||
const id = vals[v].sender;
|
||||
const ch = &m.channels.items[id];
|
||||
ch.close_view = try ch.close_view.join(m.tasks.items[self].views.cur, m.heap());
|
||||
try m.tick();
|
||||
ch.senders -= 1;
|
||||
m.maybeRelease(id);
|
||||
return .yield;
|
||||
@@ -1283,6 +1325,7 @@ const Machine = struct {
|
||||
.mutex_unlock => |g| {
|
||||
vals[g].guard.locked = false;
|
||||
vals[g].guard.view = m.tasks.items[m.current].views.cur;
|
||||
try m.tick();
|
||||
return .yield;
|
||||
},
|
||||
else => unreachable,
|
||||
@@ -1324,6 +1367,11 @@ const Machine = struct {
|
||||
|
||||
fn execAtomic(m: *Machine, vals: []Value, inst: air.Inst) !Step {
|
||||
const gpa = m.heap();
|
||||
// A write or fence may release: later accesses get a new clock.
|
||||
defer if (m.detect_races) switch (inst.op) {
|
||||
.atomic_store, .atomic_rmw, .atomic_cmpxchg, .atomic_fence => m.tick() catch {},
|
||||
else => {},
|
||||
};
|
||||
const views = &m.tasks.items[m.current].views;
|
||||
switch (inst.op) {
|
||||
.atomic_new => |v| {
|
||||
@@ -1462,6 +1510,10 @@ const Machine = struct {
|
||||
return v;
|
||||
}
|
||||
|
||||
fn pathTo(m: *Machine, p: Value.Place, i: u64) ![]const u32 {
|
||||
return (try m.extend(p, i)).path;
|
||||
}
|
||||
|
||||
fn extend(m: *Machine, p: Value.Place, i: u64) !Value.Place {
|
||||
const path = try m.heap().alloc(u32, p.path.len + 1);
|
||||
@memcpy(path[0..p.path.len], p.path);
|
||||
@@ -1905,15 +1957,20 @@ const Machine = struct {
|
||||
return bind(vals, inst.result, .{ .local = cell });
|
||||
},
|
||||
.local_store => |x| {
|
||||
if (try m.raceCheck(vals[x.local].local, &.{}, true)) |r| return r;
|
||||
vals[x.local].local.value = try m.deepCopy(vals[x.value]);
|
||||
return .next;
|
||||
},
|
||||
.local_zero => |v| {
|
||||
const cell = vals[v].local;
|
||||
if (try m.raceCheck(cell, &.{}, true)) |r| return r;
|
||||
cell.value = try m.zeroValue(cell.ty);
|
||||
return .next;
|
||||
},
|
||||
.local_load => |v| return bind(vals, inst.result, try m.deepCopy(vals[v].local.value)),
|
||||
.local_load => |v| {
|
||||
if (try m.raceCheck(vals[v].local, &.{}, false)) |r| return r;
|
||||
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.
|
||||
@@ -1936,9 +1993,15 @@ const Machine = struct {
|
||||
}),
|
||||
.borrow_field => |x| return bind(vals, inst.result, .{ .place = try m.extend(asPlace(vals[x.borrow]), x.field) }),
|
||||
.borrow_end => return .next,
|
||||
.load => |v| return bind(vals, inst.result, try m.deepCopy(placePtr(asPlace(vals[v])).*)),
|
||||
.load => |v| {
|
||||
const p = asPlace(vals[v]);
|
||||
if (try m.raceCheck(p.cell, p.path, false)) |r| return r;
|
||||
return bind(vals, inst.result, try m.deepCopy(placePtr(p).*));
|
||||
},
|
||||
.store => |x| {
|
||||
placePtr(asPlace(vals[x.borrow])).* = try m.deepCopy(vals[x.value]);
|
||||
const p = asPlace(vals[x.borrow]);
|
||||
if (try m.raceCheck(p.cell, p.path, true)) |r| return r;
|
||||
placePtr(p).* = try m.deepCopy(vals[x.value]);
|
||||
return .next;
|
||||
},
|
||||
.array_splat => |x| {
|
||||
@@ -1986,6 +2049,10 @@ const Machine = struct {
|
||||
const dst = placePtr(d.place).array;
|
||||
const src = placePtr(s.place).array;
|
||||
// Operands never overlap (spec 08 §11.2), so a forward copy is exact.
|
||||
if (m.detect_races) for (0..s.len) |k| {
|
||||
if (try m.raceCheck(s.place.cell, try m.pathTo(s.place, s.start + k), false)) |r| return r;
|
||||
if (try m.raceCheck(d.place.cell, try m.pathTo(d.place, d.start + k), true)) |r| return r;
|
||||
};
|
||||
for (0..s.len) |k| dst[d.start + k] = try m.deepCopy(src[s.start + k]);
|
||||
return .next;
|
||||
},
|
||||
@@ -2231,6 +2298,17 @@ pub fn writeOutcome(module: air.Module, outcome: Outcome, out: ?Output, w: *std.
|
||||
try s.objectField("inst");
|
||||
try s.write(t.inst);
|
||||
},
|
||||
.race_detected => |r| {
|
||||
try s.write("race_detected");
|
||||
try s.objectField("function");
|
||||
try s.write(r.at.function);
|
||||
try s.objectField("block");
|
||||
try s.write(r.at.block);
|
||||
try s.objectField("inst");
|
||||
try s.write(r.at.inst);
|
||||
try s.objectField("other_task");
|
||||
try s.write(r.other_task);
|
||||
},
|
||||
.blocked => |l| {
|
||||
try s.write("blocked");
|
||||
try s.objectField("kind");
|
||||
@@ -2696,3 +2774,52 @@ test "moving an island costs the same for any graph size" {
|
||||
const large = try transferSteps(1000, 10) - try transferSteps(1000, 0);
|
||||
try std.testing.expectEqual(small, large);
|
||||
}
|
||||
|
||||
test "the race detector catches an unordered write the verifier would reject" {
|
||||
// Not verified on purpose: main writes the local while a mut borrow of it
|
||||
// is lent to a running task (E4101 for the verifier, spec 04 §34).
|
||||
const src =
|
||||
\\module test.race
|
||||
\\air 0
|
||||
\\lang 0.1
|
||||
\\features [ownership, tasks]
|
||||
\\
|
||||
\\fn @poke(%p: mut<u64>) -> u64
|
||||
\\effects []
|
||||
\\entry:
|
||||
\\ %one = const.u64 1
|
||||
\\ store %p, %one
|
||||
\\ ret %one
|
||||
\\
|
||||
\\fn @main() -> u64
|
||||
\\effects [task.spawn]
|
||||
\\entry:
|
||||
\\ %x = local.alloc u64
|
||||
\\ %z = const.u64 0
|
||||
\\ local.store %x, %z
|
||||
\\ %b = borrow.mut %x
|
||||
\\ %s = task.scope.begin
|
||||
\\ %t = task.spawn %s, @poke(%b)
|
||||
\\ %two = const.u64 2
|
||||
\\ local.store %x, %two
|
||||
\\ %r = task.join %t
|
||||
\\ task.scope.end %s
|
||||
\\ borrow.end %b
|
||||
\\ ret %r
|
||||
\\
|
||||
;
|
||||
var arena_state: std.heap.ArenaAllocator = .init(std.testing.allocator);
|
||||
defer arena_state.deinit();
|
||||
const arena = arena_state.allocator();
|
||||
const parsed = try @import("../air/parse.zig").parse(arena, "race.air", src);
|
||||
try std.testing.expectEqual(@as(usize, 0), parsed.diagnostics.len);
|
||||
// On every schedule the two writes are unordered: one of them is caught.
|
||||
var seed: u64 = 0;
|
||||
while (seed < 20) : (seed += 1) {
|
||||
const outcome = try run(arena, parsed.module.?, "main", .{ .detect_races = true, .quantum = 1, .schedule_seed = seed });
|
||||
try std.testing.expect(outcome == .race_detected);
|
||||
}
|
||||
// Without the detector the program just runs.
|
||||
const plain = try run(arena, parsed.module.?, "main", .{ .quantum = 1 });
|
||||
try std.testing.expect(plain == .returned);
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
//! Dynamic data-race detector for ordinary memory (spec 04 §21; P5-6).
|
||||
//!
|
||||
//! A verified safe program has no data race: the ownership, borrow and loan
|
||||
//! rules exclude it. This detector checks that claim at run time, so a race
|
||||
//! the verifier missed fails the test that runs into it. It is a test tool,
|
||||
//! enabled by `Options.detect_races`; it never changes an outcome otherwise.
|
||||
//!
|
||||
//! Happens-before is carried by the weak-memory views (weak.zig): a task's
|
||||
//! vector clock is the part of its `cur` view whose keys are tasks
|
||||
//! (`clockKey`). Views already travel along every synchronization edge of
|
||||
//! spec 04 §20.3 and every release/acquire pair, so no other plumbing is
|
||||
//! needed. Every memory cell has a shadow: per access path, the last write
|
||||
//! and the reads since, each as (task, clock). Two accesses conflict when
|
||||
//! their paths overlap (one is a prefix of the other) and one writes; they
|
||||
//! race when neither happens-before the other.
|
||||
|
||||
const std = @import("std");
|
||||
const weak = @import("weak.zig");
|
||||
|
||||
/// The view key of task `t`'s clock: above every atomic cell index.
|
||||
pub fn clockKey(t: u32) u32 {
|
||||
return 0x8000_0000 | t;
|
||||
}
|
||||
|
||||
pub const Epoch = struct { task: u32, clock: u64 };
|
||||
|
||||
pub const Shadow = struct {
|
||||
entries: std.ArrayList(Entry) = .empty,
|
||||
|
||||
pub const Entry = struct {
|
||||
path: []const u32,
|
||||
write: ?Epoch = null,
|
||||
reads: std.ArrayList(Epoch) = .empty,
|
||||
};
|
||||
|
||||
pub fn copy(s: *const Shadow, gpa: std.mem.Allocator) !*Shadow {
|
||||
const n = try gpa.create(Shadow);
|
||||
n.* = .{};
|
||||
try n.entries.ensureTotalCapacity(gpa, s.entries.items.len);
|
||||
for (s.entries.items) |e| {
|
||||
var reads: std.ArrayList(Epoch) = .empty;
|
||||
try reads.appendSlice(gpa, e.reads.items);
|
||||
n.entries.appendAssumeCapacity(.{ .path = try gpa.dupe(u32, e.path), .write = e.write, .reads = reads });
|
||||
}
|
||||
return n;
|
||||
}
|
||||
};
|
||||
|
||||
fn overlap(a: []const u32, b: []const u32) bool {
|
||||
const n = @min(a.len, b.len);
|
||||
return std.mem.eql(u32, a[0..n], b[0..n]);
|
||||
}
|
||||
|
||||
fn ordered(e: Epoch, t: u32, cur: weak.View) bool {
|
||||
return e.task == t or e.clock <= cur.get(clockKey(e.task));
|
||||
}
|
||||
|
||||
/// Checks an access by task `t` (view `cur`) and records it. Returns the
|
||||
/// task of a racing access, or null.
|
||||
pub fn access(gpa: std.mem.Allocator, shadow: *Shadow, path: []const u32, write: bool, t: u32, cur: weak.View) !?u32 {
|
||||
for (shadow.entries.items) |e| {
|
||||
if (!overlap(e.path, path)) continue;
|
||||
if (e.write) |w| if (!ordered(w, t, cur)) return w.task;
|
||||
if (write) for (e.reads.items) |r| if (!ordered(r, t, cur)) return r.task;
|
||||
}
|
||||
const now: Epoch = .{ .task = t, .clock = cur.get(clockKey(t)) };
|
||||
const entry = for (shadow.entries.items) |*e| {
|
||||
if (std.mem.eql(u32, e.path, path)) break e;
|
||||
} else blk: {
|
||||
try shadow.entries.append(gpa, .{ .path = try gpa.dupe(u32, path) });
|
||||
break :blk &shadow.entries.items[shadow.entries.items.len - 1];
|
||||
};
|
||||
if (write) {
|
||||
entry.write = now;
|
||||
entry.reads.clearRetainingCapacity();
|
||||
} else {
|
||||
for (entry.reads.items) |*r| if (r.task == t) {
|
||||
r.clock = now.clock;
|
||||
return null;
|
||||
};
|
||||
try entry.reads.append(gpa, now);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
test "unordered writes race; ordered ones do not" {
|
||||
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
|
||||
defer arena.deinit();
|
||||
const a = arena.allocator();
|
||||
var sh: Shadow = .{};
|
||||
const t0: weak.View = try (weak.View{}).with(clockKey(0), 1, a);
|
||||
const t1: weak.View = try (weak.View{}).with(clockKey(1), 1, a);
|
||||
try std.testing.expectEqual(@as(?u32, null), try access(a, &sh, &.{}, true, 0, t0));
|
||||
// Task 1 has not synchronized with task 0: a race.
|
||||
try std.testing.expectEqual(@as(?u32, 0), try access(a, &sh, &.{0}, false, 1, t1));
|
||||
// After acquiring task 0's clock it is ordered.
|
||||
const t1b = try t1.join(t0, a);
|
||||
try std.testing.expectEqual(@as(?u32, null), try access(a, &sh, &.{0}, true, 1, t1b));
|
||||
// Disjoint paths never conflict.
|
||||
var sh2: Shadow = .{};
|
||||
_ = try access(a, &sh2, &.{ 0, 1 }, true, 0, t0);
|
||||
try std.testing.expectEqual(@as(?u32, null), try access(a, &sh2, &.{ 0, 2 }, true, 1, t1));
|
||||
}
|
||||
@@ -311,6 +311,8 @@ fn run(io: std.Io, arena: std.mem.Allocator, args: []const [:0]const u8, out: *s
|
||||
.limit_exceeded => .limit_exceeded,
|
||||
.not_instantiated => .not_instantiated,
|
||||
.blocked => .blocked,
|
||||
// Only with Options.detect_races, which the CLI does not set.
|
||||
.race_detected => .trapped,
|
||||
};
|
||||
}
|
||||
return switch (report.status) {
|
||||
|
||||
Reference in new issue
Block a user