From 1fcc9cbe3d040ce102739760cc14476ec6726bbe Mon Sep 17 00:00:00 2001 From: Linus Groh Date: Sat, 3 Oct 2026 15:16:49 +0100 Subject: [PATCH] std.Io.Threaded: Implement futexWait/futexWake for serenity Taken from the downstream patch with slight modifications: https://github.com/SerenityOS/serenity/blob/3d85104ef2ad231f31ec3de703f24306ea2aa0bf/Ports/zig/patches/0005-Extend-support-for-SerenityOS-target.patch#L19-L73 --- lib/std/Io/Threaded.zig | 47 +++++++++++++++++++++++++++++++++++++++-- 1 file changed, 45 insertions(+), 2 deletions(-) diff --git a/lib/std/Io/Threaded.zig b/lib/std/Io/Threaded.zig index c9de11eceeaf184ca958c9f927d4b844000c2e8c..dae5f07f95685e5d4e6a8b883f3a392b65d8bd54 100644 --- a/lib/std/Io/Threaded.zig +++ b/lib/std/Io/Threaded.zig @@ -1102,6 +1102,33 @@ const Thread = struct { else => unreachable, }; }, + .serenity => { + var tm: std.c.timespec = undefined; + var tm_ptr: ?*const std.c.timespec = null; + if (timeout_ns) |ns| { + tm_ptr = &tm; + tm = timestampToPosix(ns); + } + const syscall: Syscall = if (uncancelable) .{ .thread = null } else try .start(); + const rc = std.c.futex( + @constCast(ptr), + std.c.FUTEX.WAIT | std.c.FUTEX.PRIVATE_FLAG, + expect, + tm_ptr, + null, + 0, + ); + syscall.finish(); + if (is_debug) switch (posix.errno(rc)) { + .SUCCESS => {}, + .AGAIN => {}, // ptr != expect + .TIMEDOUT => {}, // timeout + .FAULT => unreachable, // ptr was invalid + .INVAL => unreachable, // ptr was misaligned + .NOMEM => {}, // OOM, treat as spurious wake + else => unreachable, + }; + }, else => @compileError("unimplemented: futexWait"), } } @@ -1167,12 +1194,12 @@ const Thread = struct { 0, // there is no timeout struct 0, // there is no timeout struct pointer ); - switch (posix.errno(rc)) { + if (is_debug) switch (posix.errno(rc)) { .SUCCESS => {}, .FAULT => {}, // it's ok if the ptr doesn't point to valid memory .INVAL => unreachable, // arguments should be correct else => unreachable, // deadlock due to operating system bug - } + }; }, .openbsd => { const rc = std.c.futex( @@ -1191,6 +1218,22 @@ const Thread = struct { @min(max_waiters, std.math.maxInt(c_int)), ); }, + .serenity => { + const rc = std.c.futex( + @constCast(ptr), + std.c.FUTEX.WAKE | std.c.FUTEX.PRIVATE_FLAG, + max_waiters, + null, + null, + 0, + ); + if (is_debug) switch (posix.errno(rc)) { + .SUCCESS => {}, + .FAULT => {}, // it's ok if the ptr doesn't point to valid memory + .INVAL => unreachable, // arguments should be correct + else => unreachable, + }; + }, else => @compileError("unimplemented: futexWake"), } } -- 2.54.0