authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2025-11-24 11:18:35-08:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2025-11-24 14:34:18-08:00
log3f34f5e43349214c862882a83bd951701a6c735f
tree031d1ab910775458fb6066f5379b54e2e44e1baf
parenta242292644a12b8ca0485759ba45c550265da5bd

build runner: update Mutex and Condition usage to std.Io


6 files changed, 149 insertions(+), 112 deletions(-)

lib/compiler/build_runner.zig+9-9
......@@ -494,7 +494,7 @@ pub fn main() !void {
494494
495495 .max_rss = max_rss,
496496 .max_rss_is_default = false,
497 .max_rss_mutex = .{},
497 .max_rss_mutex = .init,
498498 .skip_oom_steps = skip_oom_steps,
499499 .unit_test_timeout_ns = test_timeout_ns,
500500
......@@ -583,7 +583,7 @@ pub fn main() !void {
583583
584584 if (run.web_server) |*ws| {
585585 assert(!watch); // fatal error after CLI parsing
586 while (true) switch (ws.wait()) {
586 while (true) switch (try ws.wait()) {
587587 .rebuild => {
588588 for (run.step_stack.keys()) |step| {
589589 step.state = .precheck_done;
......@@ -652,7 +652,7 @@ const Run = struct {
652652 gpa: Allocator,
653653 max_rss: u64,
654654 max_rss_is_default: bool,
655 max_rss_mutex: std.Thread.Mutex,
655 max_rss_mutex: Io.Mutex,
656656 skip_oom_steps: bool,
657657 unit_test_timeout_ns: ?u64,
658658 watch: bool,
......@@ -1305,6 +1305,8 @@ fn workerMakeOneStep(
13051305 prog_node: std.Progress.Node,
13061306 run: *Run,
13071307) void {
1308 const io = b.graph.io;
1309
13081310 // First, check the conditions for running this step. If they are not met,
13091311 // then we return without doing the step, relying on another worker to
13101312 // queue this step up again when dependencies are met.
......@@ -1326,8 +1328,8 @@ fn workerMakeOneStep(
13261328 }
13271329
13281330 if (s.max_rss != 0) {
1329 run.max_rss_mutex.lock();
1330 defer run.max_rss_mutex.unlock();
1331 run.max_rss_mutex.lockUncancelable(io);
1332 defer run.max_rss_mutex.unlock(io);
13311333
13321334 // Avoid running steps twice.
13331335 if (s.state != .precheck_done) {
......@@ -1378,8 +1380,6 @@ fn workerMakeOneStep(
13781380 printErrorMessages(run.gpa, s, .{}, bw, ttyconf, run.error_style, run.multiline_errors) catch {};
13791381 }
13801382
1381 const io = b.graph.io;
1382
13831383 handle_result: {
13841384 if (make_result) |_| {
13851385 @atomicStore(Step.State, &s.state, .success, .seq_cst);
......@@ -1406,8 +1406,8 @@ fn workerMakeOneStep(
14061406 // If this is a step that claims resources, we must now queue up other
14071407 // steps that are waiting for resources.
14081408 if (s.max_rss != 0) {
1409 run.max_rss_mutex.lock();
1410 defer run.max_rss_mutex.unlock();
1409 run.max_rss_mutex.lockUncancelable(io);
1410 defer run.max_rss_mutex.unlock(io);
14111411
14121412 // Give the memory back to the scheduler.
14131413 run.claimed_rss -= s.max_rss;
lib/std/Build/Cache.zig+22-9
......@@ -22,7 +22,7 @@ manifest_dir: fs.Dir,
2222hash: HashHelper = .{},
2323/// This value is accessed from multiple threads, protected by mutex.
2424recent_problematic_timestamp: Io.Timestamp = .zero,
25mutex: std.Thread.Mutex = .{},
25mutex: Io.Mutex = .init,
2626
2727/// A set of strings such as the zig library directory or project source root, which
2828/// are stripped from the file paths before putting into the cache. They
......@@ -474,6 +474,7 @@ pub const Manifest = struct {
474474 /// A cache manifest file exists however it could not be parsed.
475475 InvalidFormat,
476476 OutOfMemory,
477 Canceled,
477478 };
478479
479480 /// Check the cache to see if the input exists in it. If it exists, returns `true`.
......@@ -559,12 +560,14 @@ pub const Manifest = struct {
559560 self.diagnostic = .{ .manifest_create = error.FileNotFound };
560561 return error.CacheCheckFailed;
561562 },
563 error.Canceled => return error.Canceled,
562564 else => |e| {
563565 self.diagnostic = .{ .manifest_create = e };
564566 return error.CacheCheckFailed;
565567 },
566568 }
567569 },
570 error.Canceled => return error.Canceled,
568571 else => |e| {
569572 self.diagnostic = .{ .manifest_create = e };
570573 return error.CacheCheckFailed;
......@@ -762,6 +765,7 @@ pub const Manifest = struct {
762765 // Every digest before this one has been populated successfully.
763766 return .{ .miss = .{ .file_digests_populated = idx } };
764767 },
768 error.Canceled => return error.Canceled,
765769 else => |e| {
766770 self.diagnostic = .{ .file_open = .{
767771 .file_index = idx,
......@@ -790,7 +794,7 @@ pub const Manifest = struct {
790794 .inode = actual_stat.inode,
791795 };
792796
793 if (self.isProblematicTimestamp(cache_hash_file.stat.mtime)) {
797 if (try self.isProblematicTimestamp(cache_hash_file.stat.mtime)) {
794798 // The actual file has an unreliable timestamp, force it to be hashed
795799 cache_hash_file.stat.mtime = .zero;
796800 cache_hash_file.stat.inode = 0;
......@@ -848,7 +852,9 @@ pub const Manifest = struct {
848852 }
849853 }
850854
851 fn isProblematicTimestamp(man: *Manifest, timestamp: Io.Timestamp) bool {
855 fn isProblematicTimestamp(man: *Manifest, timestamp: Io.Timestamp) error{Canceled}!bool {
856 const io = man.cache.io;
857
852858 // If the file_time is prior to the most recent problematic timestamp
853859 // then we don't need to access the filesystem.
854860 if (timestamp.nanoseconds < man.recent_problematic_timestamp.nanoseconds)
......@@ -856,8 +862,8 @@ pub const Manifest = struct {
856862
857863 // Next we will check the globally shared Cache timestamp, which is accessed
858864 // from multiple threads.
859 man.cache.mutex.lock();
860 defer man.cache.mutex.unlock();
865 try man.cache.mutex.lock(io);
866 defer man.cache.mutex.unlock(io);
861867
862868 // Save the global one to our local one to avoid locking next time.
863869 man.recent_problematic_timestamp = man.cache.recent_problematic_timestamp;
......@@ -871,11 +877,18 @@ pub const Manifest = struct {
871877 var file = man.cache.manifest_dir.createFile("timestamp", .{
872878 .read = true,
873879 .truncate = true,
874 }) catch return true;
880 }) catch |err| switch (err) {
881 error.Canceled => return error.Canceled,
882 else => return true,
883 };
875884 defer file.close();
876885
877886 // Save locally and also save globally (we still hold the global lock).
878 man.recent_problematic_timestamp = (file.stat() catch return true).mtime;
887 const stat = file.stat() catch |err| switch (err) {
888 error.Canceled => return error.Canceled,
889 else => return true,
890 };
891 man.recent_problematic_timestamp = stat.mtime;
879892 man.cache.recent_problematic_timestamp = man.recent_problematic_timestamp;
880893 }
881894
......@@ -902,7 +915,7 @@ pub const Manifest = struct {
902915 .inode = actual_stat.inode,
903916 };
904917
905 if (self.isProblematicTimestamp(ch_file.stat.mtime)) {
918 if (try self.isProblematicTimestamp(ch_file.stat.mtime)) {
906919 // The actual file has an unreliable timestamp, force it to be hashed
907920 ch_file.stat.mtime = .zero;
908921 ch_file.stat.inode = 0;
......@@ -1038,7 +1051,7 @@ pub const Manifest = struct {
10381051 .contents = null,
10391052 };
10401053
1041 if (self.isProblematicTimestamp(new_file.stat.mtime)) {
1054 if (try self.isProblematicTimestamp(new_file.stat.mtime)) {
10421055 // The actual file has an unreliable timestamp, force it to be hashed
10431056 new_file.stat.mtime = .zero;
10441057 new_file.stat.inode = 0;
lib/std/Build/Fuzz.zig+48-37
......@@ -27,11 +27,11 @@ root_prog_node: std.Progress.Node,
2727prog_node: std.Progress.Node,
2828
2929/// Protects `coverage_files`.
30coverage_mutex: std.Thread.Mutex,
30coverage_mutex: Io.Mutex,
3131coverage_files: std.AutoArrayHashMapUnmanaged(u64, CoverageMap),
3232
33queue_mutex: std.Thread.Mutex,
34queue_cond: std.Thread.Condition,
33queue_mutex: Io.Mutex,
34queue_cond: Io.Condition,
3535msg_queue: std.ArrayList(Msg),
3636
3737pub const Mode = union(enum) {
......@@ -122,8 +122,8 @@ pub fn init(
122122 .root_prog_node = root_prog_node,
123123 .prog_node = .none,
124124 .coverage_files = .empty,
125 .coverage_mutex = .{},
126 .queue_mutex = .{},
125 .coverage_mutex = .init,
126 .queue_mutex = .init,
127127 .queue_cond = .{},
128128 .msg_queue = .empty,
129129 };
......@@ -157,9 +157,7 @@ pub fn deinit(fuzz: *Fuzz) void {
157157fn rebuildTestsWorkerRun(run: *Step.Run, gpa: Allocator, ttyconf: tty.Config, parent_prog_node: std.Progress.Node) void {
158158 rebuildTestsWorkerRunFallible(run, gpa, ttyconf, parent_prog_node) catch |err| {
159159 const compile = run.producer.?;
160 log.err("step '{s}': failed to rebuild in fuzz mode: {s}", .{
161 compile.step.name, @errorName(err),
162 });
160 log.err("step '{s}': failed to rebuild in fuzz mode: {t}", .{ compile.step.name, err });
163161 };
164162}
165163
......@@ -208,9 +206,7 @@ fn fuzzWorkerRun(
208206 return;
209207 },
210208 else => {
211 log.err("step '{s}': failed to rerun '{s}' in fuzz mode: {s}", .{
212 run.step.name, test_name, @errorName(err),
213 });
209 log.err("step '{s}': failed to rerun '{s}' in fuzz mode: {t}", .{ run.step.name, test_name, err });
214210 return;
215211 },
216212 };
......@@ -269,8 +265,10 @@ pub fn sendUpdate(
269265 socket: *std.http.Server.WebSocket,
270266 prev: *Previous,
271267) !void {
272 fuzz.coverage_mutex.lock();
273 defer fuzz.coverage_mutex.unlock();
268 const io = fuzz.io;
269
270 try fuzz.coverage_mutex.lock(io);
271 defer fuzz.coverage_mutex.unlock(io);
274272
275273 const coverage_maps = fuzz.coverage_files.values();
276274 if (coverage_maps.len == 0) return;
......@@ -331,30 +329,41 @@ pub fn sendUpdate(
331329}
332330
333331fn coverageRun(fuzz: *Fuzz) void {
334 fuzz.queue_mutex.lock();
335 defer fuzz.queue_mutex.unlock();
332 coverageRunCancelable(fuzz) catch |err| switch (err) {
333 error.Canceled => return,
334 };
335}
336
337fn coverageRunCancelable(fuzz: *Fuzz) Io.Cancelable!void {
338 const io = fuzz.io;
339
340 try fuzz.queue_mutex.lock(io);
341 defer fuzz.queue_mutex.unlock(io);
336342
337343 while (true) {
338 fuzz.queue_cond.wait(&fuzz.queue_mutex);
344 try fuzz.queue_cond.wait(io, &fuzz.queue_mutex);
339345 for (fuzz.msg_queue.items) |msg| switch (msg) {
340346 .coverage => |coverage| prepareTables(fuzz, coverage.run, coverage.id) catch |err| switch (err) {
341347 error.AlreadyReported => continue,
342 else => |e| log.err("failed to prepare code coverage tables: {s}", .{@errorName(e)}),
348 error.Canceled => return,
349 else => |e| log.err("failed to prepare code coverage tables: {t}", .{e}),
343350 },
344351 .entry_point => |entry_point| addEntryPoint(fuzz, entry_point.coverage_id, entry_point.addr) catch |err| switch (err) {
345352 error.AlreadyReported => continue,
346 else => |e| log.err("failed to prepare code coverage tables: {s}", .{@errorName(e)}),
353 error.Canceled => return,
354 else => |e| log.err("failed to prepare code coverage tables: {t}", .{e}),
347355 },
348356 };
349357 fuzz.msg_queue.clearRetainingCapacity();
350358 }
351359}
352fn prepareTables(fuzz: *Fuzz, run_step: *Step.Run, coverage_id: u64) error{ OutOfMemory, AlreadyReported }!void {
360fn prepareTables(fuzz: *Fuzz, run_step: *Step.Run, coverage_id: u64) error{ OutOfMemory, AlreadyReported, Canceled }!void {
353361 assert(fuzz.mode == .forever);
354362 const ws = fuzz.mode.forever.ws;
363 const io = fuzz.io;
355364
356 fuzz.coverage_mutex.lock();
357 defer fuzz.coverage_mutex.unlock();
365 try fuzz.coverage_mutex.lock(io);
366 defer fuzz.coverage_mutex.unlock(io);
358367
359368 const gop = try fuzz.coverage_files.getOrPut(fuzz.gpa, coverage_id);
360369 if (gop.found_existing) {
......@@ -385,8 +394,8 @@ fn prepareTables(fuzz: *Fuzz, run_step: *Step.Run, coverage_id: u64) error{ OutO
385394 target.ofmt,
386395 target.cpu.arch,
387396 ) catch |err| {
388 log.err("step '{s}': failed to load debug information for '{f}': {s}", .{
389 run_step.step.name, rebuilt_exe_path, @errorName(err),
397 log.err("step '{s}': failed to load debug information for '{f}': {t}", .{
398 run_step.step.name, rebuilt_exe_path, err,
390399 });
391400 return error.AlreadyReported;
392401 };
......@@ -397,15 +406,15 @@ fn prepareTables(fuzz: *Fuzz, run_step: *Step.Run, coverage_id: u64) error{ OutO
397406 .sub_path = "v/" ++ std.fmt.hex(coverage_id),
398407 };
399408 var coverage_file = coverage_file_path.root_dir.handle.openFile(coverage_file_path.sub_path, .{}) catch |err| {
400 log.err("step '{s}': failed to load coverage file '{f}': {s}", .{
401 run_step.step.name, coverage_file_path, @errorName(err),
409 log.err("step '{s}': failed to load coverage file '{f}': {t}", .{
410 run_step.step.name, coverage_file_path, err,
402411 });
403412 return error.AlreadyReported;
404413 };
405414 defer coverage_file.close();
406415
407416 const file_size = coverage_file.getEndPos() catch |err| {
408 log.err("unable to check len of coverage file '{f}': {s}", .{ coverage_file_path, @errorName(err) });
417 log.err("unable to check len of coverage file '{f}': {t}", .{ coverage_file_path, err });
409418 return error.AlreadyReported;
410419 };
411420
......@@ -417,7 +426,7 @@ fn prepareTables(fuzz: *Fuzz, run_step: *Step.Run, coverage_id: u64) error{ OutO
417426 coverage_file.handle,
418427 0,
419428 ) catch |err| {
420 log.err("failed to map coverage file '{f}': {s}", .{ coverage_file_path, @errorName(err) });
429 log.err("failed to map coverage file '{f}': {t}", .{ coverage_file_path, err });
421430 return error.AlreadyReported;
422431 };
423432 gop.value_ptr.mapped_memory = mapped_memory;
......@@ -443,7 +452,7 @@ fn prepareTables(fuzz: *Fuzz, run_step: *Step.Run, coverage_id: u64) error{ OutO
443452 }{ .addrs = sorted_pcs.items(.pc) });
444453
445454 debug_info.resolveAddresses(fuzz.gpa, sorted_pcs.items(.pc), sorted_pcs.items(.sl)) catch |err| {
446 log.err("failed to resolve addresses to source locations: {s}", .{@errorName(err)});
455 log.err("failed to resolve addresses to source locations: {t}", .{err});
447456 return error.AlreadyReported;
448457 };
449458
......@@ -453,9 +462,11 @@ fn prepareTables(fuzz: *Fuzz, run_step: *Step.Run, coverage_id: u64) error{ OutO
453462 ws.notifyUpdate();
454463}
455464
456fn addEntryPoint(fuzz: *Fuzz, coverage_id: u64, addr: u64) error{ AlreadyReported, OutOfMemory }!void {
457 fuzz.coverage_mutex.lock();
458 defer fuzz.coverage_mutex.unlock();
465fn addEntryPoint(fuzz: *Fuzz, coverage_id: u64, addr: u64) error{ AlreadyReported, OutOfMemory, Canceled }!void {
466 const io = fuzz.io;
467
468 try fuzz.coverage_mutex.lock(io);
469 defer fuzz.coverage_mutex.unlock(io);
459470
460471 const coverage_map = fuzz.coverage_files.getPtr(coverage_id).?;
461472 const header: *const abi.SeenPcsHeader = @ptrCast(coverage_map.mapped_memory[0..@sizeOf(abi.SeenPcsHeader)]);
......@@ -518,8 +529,8 @@ pub fn waitAndPrintReport(fuzz: *Fuzz) void {
518529 .sub_path = "v/" ++ std.fmt.hex(cov.id),
519530 };
520531 var coverage_file = coverage_file_path.root_dir.handle.openFile(coverage_file_path.sub_path, .{}) catch |err| {
521 fatal("step '{s}': failed to load coverage file '{f}': {s}", .{
522 cov.run.step.name, coverage_file_path, @errorName(err),
532 fatal("step '{s}': failed to load coverage file '{f}': {t}", .{
533 cov.run.step.name, coverage_file_path, err,
523534 });
524535 };
525536 defer coverage_file.close();
......@@ -530,8 +541,8 @@ pub fn waitAndPrintReport(fuzz: *Fuzz) void {
530541
531542 var header: fuzz_abi.SeenPcsHeader = undefined;
532543 r.interface.readSliceAll(std.mem.asBytes(&header)) catch |err| {
533 fatal("step '{s}': failed to read from coverage file '{f}': {s}", .{
534 cov.run.step.name, coverage_file_path, @errorName(err),
544 fatal("step '{s}': failed to read from coverage file '{f}': {t}", .{
545 cov.run.step.name, coverage_file_path, err,
535546 });
536547 };
537548
......@@ -545,8 +556,8 @@ pub fn waitAndPrintReport(fuzz: *Fuzz) void {
545556 const chunk_count = fuzz_abi.SeenPcsHeader.seenElemsLen(header.pcs_len);
546557 for (0..chunk_count) |_| {
547558 const seen = r.interface.takeInt(usize, .little) catch |err| {
548 fatal("step '{s}': failed to read from coverage file '{f}': {s}", .{
549 cov.run.step.name, coverage_file_path, @errorName(err),
559 fatal("step '{s}': failed to read from coverage file '{f}': {t}", .{
560 cov.run.step.name, coverage_file_path, err,
550561 });
551562 };
552563 seen_count += @popCount(seen);
lib/std/Build/Step.zig+19-18
......@@ -362,7 +362,7 @@ pub fn captureChildProcess(
362362 .allocator = arena,
363363 .argv = argv,
364364 .progress_node = progress_node,
365 }) catch |err| return s.fail("failed to run {s}: {s}", .{ argv[0], @errorName(err) });
365 }) catch |err| return s.fail("failed to run {s}: {t}", .{ argv[0], err });
366366
367367 if (result.stderr.len > 0) {
368368 try s.result_error_msgs.append(arena, result.stderr);
......@@ -412,7 +412,7 @@ pub fn evalZigProcess(
412412 error.BrokenPipe => {
413413 // Process restart required.
414414 const term = zp.child.wait() catch |e| {
415 return s.fail("unable to wait for {s}: {s}", .{ argv[0], @errorName(e) });
415 return s.fail("unable to wait for {s}: {t}", .{ argv[0], e });
416416 };
417417 _ = term;
418418 s.clearZigProcess(gpa);
......@@ -428,7 +428,7 @@ pub fn evalZigProcess(
428428 if (s.result_error_msgs.items.len > 0 and result == null) {
429429 // Crash detected.
430430 const term = zp.child.wait() catch |e| {
431 return s.fail("unable to wait for {s}: {s}", .{ argv[0], @errorName(e) });
431 return s.fail("unable to wait for {s}: {t}", .{ argv[0], e });
432432 };
433433 s.result_peak_rss = zp.child.resource_usage_statistics.getMaxRss() orelse 0;
434434 s.clearZigProcess(gpa);
......@@ -453,9 +453,7 @@ pub fn evalZigProcess(
453453 child.request_resource_usage_statistics = true;
454454 child.progress_node = prog_node;
455455
456 child.spawn() catch |err| return s.fail("failed to spawn zig compiler {s}: {s}", .{
457 argv[0], @errorName(err),
458 });
456 child.spawn() catch |err| return s.fail("failed to spawn zig compiler {s}: {t}", .{ argv[0], err });
459457
460458 const zp = try gpa.create(ZigProcess);
461459 zp.* = .{
......@@ -480,7 +478,7 @@ pub fn evalZigProcess(
480478 zp.child.stdin = null;
481479
482480 const term = zp.child.wait() catch |err| {
483 return s.fail("unable to wait for {s}: {s}", .{ argv[0], @errorName(err) });
481 return s.fail("unable to wait for {s}: {t}", .{ argv[0], err });
484482 };
485483 s.result_peak_rss = zp.child.resource_usage_statistics.getMaxRss() orelse 0;
486484
......@@ -513,8 +511,8 @@ pub fn installFile(s: *Step, src_lazy_path: Build.LazyPath, dest_path: []const u
513511 const src_path = src_lazy_path.getPath3(b, s);
514512 try handleVerbose(b, null, &.{ "install", "-C", b.fmt("{f}", .{src_path}), dest_path });
515513 return Io.Dir.updateFile(src_path.root_dir.handle.adaptToNewApi(), io, src_path.sub_path, .cwd(), dest_path, .{}) catch |err| {
516 return s.fail("unable to update file from '{f}' to '{s}': {s}", .{
517 src_path, dest_path, @errorName(err),
514 return s.fail("unable to update file from '{f}' to '{s}': {t}", .{
515 src_path, dest_path, err,
518516 });
519517 };
520518}
......@@ -524,9 +522,7 @@ pub fn installDir(s: *Step, dest_path: []const u8) !std.fs.Dir.MakePathStatus {
524522 const b = s.owner;
525523 try handleVerbose(b, null, &.{ "install", "-d", dest_path });
526524 return std.fs.cwd().makePathStatus(dest_path) catch |err| {
527 return s.fail("unable to create dir '{s}': {s}", .{
528 dest_path, @errorName(err),
529 });
525 return s.fail("unable to create dir '{s}': {t}", .{ dest_path, err });
530526 };
531527}
532528
......@@ -825,22 +821,27 @@ pub fn cacheHitAndWatch(s: *Step, man: *Build.Cache.Manifest) !bool {
825821 return is_hit;
826822}
827823
828fn failWithCacheError(s: *Step, man: *const Build.Cache.Manifest, err: Build.Cache.Manifest.HitError) error{ OutOfMemory, MakeFailed } {
824fn failWithCacheError(
825 s: *Step,
826 man: *const Build.Cache.Manifest,
827 err: Build.Cache.Manifest.HitError,
828) error{ OutOfMemory, Canceled, MakeFailed } {
829829 switch (err) {
830830 error.CacheCheckFailed => switch (man.diagnostic) {
831831 .none => unreachable,
832 .manifest_create, .manifest_read, .manifest_lock => |e| return s.fail("failed to check cache: {s} {s}", .{
833 @tagName(man.diagnostic), @errorName(e),
832 .manifest_create, .manifest_read, .manifest_lock => |e| return s.fail("failed to check cache: {t} {t}", .{
833 man.diagnostic, e,
834834 }),
835835 .file_open, .file_stat, .file_read, .file_hash => |op| {
836836 const pp = man.files.keys()[op.file_index].prefixed_path;
837837 const prefix = man.cache.prefixes()[pp.prefix].path orelse "";
838 return s.fail("failed to check cache: '{s}{c}{s}' {s} {s}", .{
839 prefix, std.fs.path.sep, pp.sub_path, @tagName(man.diagnostic), @errorName(op.err),
838 return s.fail("failed to check cache: '{s}{c}{s}' {t} {t}", .{
839 prefix, std.fs.path.sep, pp.sub_path, man.diagnostic, op.err,
840840 });
841841 },
842842 },
843843 error.OutOfMemory => return error.OutOfMemory,
844 error.Canceled => return error.Canceled,
844845 error.InvalidFormat => return s.fail("failed to check cache: invalid manifest file format", .{}),
845846 }
846847}
......@@ -850,7 +851,7 @@ fn failWithCacheError(s: *Step, man: *const Build.Cache.Manifest, err: Build.Cac
850851pub fn writeManifest(s: *Step, man: *Build.Cache.Manifest) !void {
851852 if (s.test_results.isSuccess()) {
852853 man.writeManifest() catch |err| {
853 try s.addError("unable to write cache manifest: {s}", .{@errorName(err)});
854 try s.addError("unable to write cache manifest: {t}", .{err});
854855 };
855856 }
856857}
lib/std/Build/Step/Run.zig+7-6
......@@ -1830,6 +1830,7 @@ fn pollZigTest(
18301830} {
18311831 const gpa = run.step.owner.allocator;
18321832 const arena = run.step.owner.allocator;
1833 const io = run.step.owner.graph.io;
18331834
18341835 var sub_prog_node: ?std.Progress.Node = null;
18351836 defer if (sub_prog_node) |n| n.end();
......@@ -2035,8 +2036,8 @@ fn pollZigTest(
20352036
20362037 {
20372038 const fuzz = fuzz_context.?.fuzz;
2038 fuzz.queue_mutex.lock();
2039 defer fuzz.queue_mutex.unlock();
2039 fuzz.queue_mutex.lockUncancelable(io);
2040 defer fuzz.queue_mutex.unlock(io);
20402041 try fuzz.msg_queue.append(fuzz.gpa, .{ .coverage = .{
20412042 .id = coverage_id.?,
20422043 .cumulative = .{
......@@ -2046,20 +2047,20 @@ fn pollZigTest(
20462047 },
20472048 .run = run,
20482049 } });
2049 fuzz.queue_cond.signal();
2050 fuzz.queue_cond.signal(io);
20502051 }
20512052 },
20522053 .fuzz_start_addr => {
20532054 const fuzz = fuzz_context.?.fuzz;
20542055 const addr = body_r.takeInt(u64, .little) catch unreachable;
20552056 {
2056 fuzz.queue_mutex.lock();
2057 defer fuzz.queue_mutex.unlock();
2057 fuzz.queue_mutex.lockUncancelable(io);
2058 defer fuzz.queue_mutex.unlock(io);
20582059 try fuzz.msg_queue.append(fuzz.gpa, .{ .entry_point = .{
20592060 .addr = addr,
20602061 .coverage_id = coverage_id.?,
20612062 } });
2062 fuzz.queue_cond.signal();
2063 fuzz.queue_cond.signal(io);
20632064 }
20642065 },
20652066 else => {}, // ignore other messages
lib/std/Build/WebServer.zig+44-33
......@@ -19,7 +19,7 @@ step_names_trailing: []u8,
1919step_status_bits: []u8,
2020
2121fuzz: ?Fuzz,
22time_report_mutex: std.Thread.Mutex,
22time_report_mutex: Io.Mutex,
2323time_report_msgs: [][]u8,
2424time_report_update_times: []i64,
2525
......@@ -33,9 +33,9 @@ build_status: std.atomic.Value(abi.BuildStatus),
3333/// an unreasonable number of packets.
3434update_id: std.atomic.Value(u32),
3535
36runner_request_mutex: std.Thread.Mutex,
37runner_request_ready_cond: std.Thread.Condition,
38runner_request_empty_cond: std.Thread.Condition,
36runner_request_mutex: Io.Mutex,
37runner_request_ready_cond: Io.Condition,
38runner_request_empty_cond: Io.Condition,
3939runner_request: ?RunnerRequest,
4040
4141/// If a client is not explicitly notified of changes with `notifyUpdate`, it will be sent updates
......@@ -114,14 +114,14 @@ pub fn init(opts: Options) WebServer {
114114 .step_status_bits = step_status_bits,
115115
116116 .fuzz = null,
117 .time_report_mutex = .{},
117 .time_report_mutex = .init,
118118 .time_report_msgs = time_report_msgs,
119119 .time_report_update_times = time_report_update_times,
120120
121121 .build_status = .init(.idle),
122122 .update_id = .init(0),
123123
124 .runner_request_mutex = .{},
124 .runner_request_mutex = .init,
125125 .runner_request_ready_cond = .{},
126126 .runner_request_empty_cond = .{},
127127 .runner_request = null,
......@@ -296,6 +296,8 @@ fn accept(ws: *WebServer, stream: net.Stream) void {
296296}
297297
298298fn serveWebSocket(ws: *WebServer, sock: *http.Server.WebSocket) !noreturn {
299 const io = ws.graph.io;
300
299301 var prev_build_status = ws.build_status.load(.monotonic);
300302
301303 const prev_step_status_bits = try ws.gpa.alloc(u8, ws.step_status_bits.len);
......@@ -331,8 +333,8 @@ fn serveWebSocket(ws: *WebServer, sock: *http.Server.WebSocket) !noreturn {
331333 }
332334
333335 {
334 ws.time_report_mutex.lock();
335 defer ws.time_report_mutex.unlock();
336 try ws.time_report_mutex.lock(io);
337 defer ws.time_report_mutex.unlock(io);
336338 for (ws.time_report_msgs, ws.time_report_update_times) |msg, update_time| {
337339 if (update_time <= prev_time) continue;
338340 // We want to send `msg`, but shouldn't block `ws.time_report_mutex` while we do, so
......@@ -340,8 +342,8 @@ fn serveWebSocket(ws: *WebServer, sock: *http.Server.WebSocket) !noreturn {
340342 const owned_msg = try ws.gpa.dupe(u8, msg);
341343 defer ws.gpa.free(owned_msg);
342344 // Temporarily unlock, then re-lock after the message is sent.
343 ws.time_report_mutex.unlock();
344 defer ws.time_report_mutex.lock();
345 ws.time_report_mutex.unlock(io);
346 defer ws.time_report_mutex.lockUncancelable(io);
345347 try sock.writeMessage(owned_msg, .binary);
346348 }
347349 }
......@@ -382,6 +384,8 @@ fn serveWebSocket(ws: *WebServer, sock: *http.Server.WebSocket) !noreturn {
382384 }
383385}
384386fn recvWebSocketMessages(ws: *WebServer, sock: *http.Server.WebSocket) void {
387 const io = ws.graph.io;
388
385389 while (true) {
386390 const msg = sock.readSmallMessage() catch return;
387391 if (msg.opcode != .binary) continue;
......@@ -390,14 +394,16 @@ fn recvWebSocketMessages(ws: *WebServer, sock: *http.Server.WebSocket) void {
390394 switch (tag) {
391395 _ => continue,
392396 .rebuild => while (true) {
393 ws.runner_request_mutex.lock();
394 defer ws.runner_request_mutex.unlock();
397 ws.runner_request_mutex.lock(io) catch |err| switch (err) {
398 error.Canceled => return,
399 };
400 defer ws.runner_request_mutex.unlock(io);
395401 if (ws.runner_request == null) {
396402 ws.runner_request = .rebuild;
397 ws.runner_request_ready_cond.signal();
403 ws.runner_request_ready_cond.signal(io);
398404 break;
399405 }
400 ws.runner_request_empty_cond.wait(&ws.runner_request_mutex);
406 ws.runner_request_empty_cond.wait(io, &ws.runner_request_mutex) catch return;
401407 },
402408 }
403409 }
......@@ -691,14 +697,15 @@ pub fn updateTimeReportCompile(ws: *WebServer, opts: struct {
691697 trailing: []const u8,
692698}) void {
693699 const gpa = ws.gpa;
700 const io = ws.graph.io;
694701
695702 const step_idx: u32 = for (ws.all_steps, 0..) |s, i| {
696703 if (s == &opts.compile.step) break @intCast(i);
697704 } else unreachable;
698705
699706 const old_buf = old: {
700 ws.time_report_mutex.lock();
701 defer ws.time_report_mutex.unlock();
707 ws.time_report_mutex.lock(io) catch return;
708 defer ws.time_report_mutex.unlock(io);
702709 const old = ws.time_report_msgs[step_idx];
703710 ws.time_report_msgs[step_idx] = &.{};
704711 break :old old;
......@@ -720,8 +727,8 @@ pub fn updateTimeReportCompile(ws: *WebServer, opts: struct {
720727 @memcpy(buf[@sizeOf(abi.time_report.CompileResult)..], opts.trailing);
721728
722729 {
723 ws.time_report_mutex.lock();
724 defer ws.time_report_mutex.unlock();
730 ws.time_report_mutex.lock(io) catch return;
731 defer ws.time_report_mutex.unlock(io);
725732 assert(ws.time_report_msgs[step_idx].len == 0);
726733 ws.time_report_msgs[step_idx] = buf;
727734 ws.time_report_update_times[step_idx] = ws.now();
......@@ -731,14 +738,15 @@ pub fn updateTimeReportCompile(ws: *WebServer, opts: struct {
731738
732739pub fn updateTimeReportGeneric(ws: *WebServer, step: *Build.Step, ns_total: u64) void {
733740 const gpa = ws.gpa;
741 const io = ws.graph.io;
734742
735743 const step_idx: u32 = for (ws.all_steps, 0..) |s, i| {
736744 if (s == step) break @intCast(i);
737745 } else unreachable;
738746
739747 const old_buf = old: {
740 ws.time_report_mutex.lock();
741 defer ws.time_report_mutex.unlock();
748 ws.time_report_mutex.lock(io) catch return;
749 defer ws.time_report_mutex.unlock(io);
742750 const old = ws.time_report_msgs[step_idx];
743751 ws.time_report_msgs[step_idx] = &.{};
744752 break :old old;
......@@ -750,8 +758,8 @@ pub fn updateTimeReportGeneric(ws: *WebServer, step: *Build.Step, ns_total: u64)
750758 .ns_total = ns_total,
751759 };
752760 {
753 ws.time_report_mutex.lock();
754 defer ws.time_report_mutex.unlock();
761 ws.time_report_mutex.lock(io) catch return;
762 defer ws.time_report_mutex.unlock(io);
755763 assert(ws.time_report_msgs[step_idx].len == 0);
756764 ws.time_report_msgs[step_idx] = buf;
757765 ws.time_report_update_times[step_idx] = ws.now();
......@@ -766,6 +774,7 @@ pub fn updateTimeReportRunTest(
766774 ns_per_test: []const u64,
767775) void {
768776 const gpa = ws.gpa;
777 const io = ws.graph.io;
769778
770779 const step_idx: u32 = for (ws.all_steps, 0..) |s, i| {
771780 if (s == &run.step) break @intCast(i);
......@@ -782,8 +791,8 @@ pub fn updateTimeReportRunTest(
782791 break :len @sizeOf(abi.time_report.RunTestResult) + names_len + 8 * tests_len;
783792 };
784793 const old_buf = old: {
785 ws.time_report_mutex.lock();
786 defer ws.time_report_mutex.unlock();
794 ws.time_report_mutex.lock(io) catch return;
795 defer ws.time_report_mutex.unlock(io);
787796 const old = ws.time_report_msgs[step_idx];
788797 ws.time_report_msgs[step_idx] = &.{};
789798 break :old old;
......@@ -808,8 +817,8 @@ pub fn updateTimeReportRunTest(
808817 assert(offset == buf.len);
809818
810819 {
811 ws.time_report_mutex.lock();
812 defer ws.time_report_mutex.unlock();
820 ws.time_report_mutex.lock(io) catch return;
821 defer ws.time_report_mutex.unlock(io);
813822 assert(ws.time_report_msgs[step_idx].len == 0);
814823 ws.time_report_msgs[step_idx] = buf;
815824 ws.time_report_update_times[step_idx] = ws.now();
......@@ -821,8 +830,9 @@ const RunnerRequest = union(enum) {
821830 rebuild,
822831};
823832pub fn getRunnerRequest(ws: *WebServer) ?RunnerRequest {
824 ws.runner_request_mutex.lock();
825 defer ws.runner_request_mutex.unlock();
833 const io = ws.graph.io;
834 ws.runner_request_mutex.lock(io) catch return;
835 defer ws.runner_request_mutex.unlock(io);
826836 if (ws.runner_request) |req| {
827837 ws.runner_request = null;
828838 ws.runner_request_empty_cond.signal();
......@@ -830,16 +840,17 @@ pub fn getRunnerRequest(ws: *WebServer) ?RunnerRequest {
830840 }
831841 return null;
832842}
833pub fn wait(ws: *WebServer) RunnerRequest {
834 ws.runner_request_mutex.lock();
835 defer ws.runner_request_mutex.unlock();
843pub fn wait(ws: *WebServer) Io.Cancelable!RunnerRequest {
844 const io = ws.graph.io;
845 try ws.runner_request_mutex.lock(io);
846 defer ws.runner_request_mutex.unlock(io);
836847 while (true) {
837848 if (ws.runner_request) |req| {
838849 ws.runner_request = null;
839 ws.runner_request_empty_cond.signal();
850 ws.runner_request_empty_cond.signal(io);
840851 return req;
841852 }
842 ws.runner_request_ready_cond.wait(&ws.runner_request_mutex);
853 try ws.runner_request_ready_cond.wait(io, &ws.runner_request_mutex);
843854 }
844855}
845856