summaryrefslogtreecommitdiff
path: root/vendor/libghostty-vt/src/lib/tinyio/posix.zig
blob: 10b96210564cbeb76c4fe7975d1a2119382500dc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
//! POSIX impl of TinyIo: plain blocking syscalls cribbed from
//! std.posix and the POSIX impls of `std.Io.Threaded`.

const std = @import("std");
const builtin = @import("builtin");
const posix = std.posix;
const Io = std.Io;
const File = Io.File;
const Dir = Io.Dir;
const Threaded = std.Io.Threaded;

// 64-bit offset syscall selection, same as `std.Io.Threaded`.
const openat_sym = if (posix.lfs64_abi) posix.system.openat64 else posix.system.openat;
const fstat_sym = if (posix.lfs64_abi) posix.system.fstat64 else posix.system.fstat;
const fstatat_sym = if (posix.lfs64_abi) posix.system.fstatat64 else posix.system.fstatat;
const lseek_sym = if (posix.lfs64_abi) posix.system.lseek64 else posix.system.lseek;
const preadv_sym = if (posix.lfs64_abi) posix.system.preadv64 else posix.system.preadv;

const have_preadv = switch (builtin.os.tag) {
    .haiku => false,
    else => true,
};

pub fn randomSecure(buffer: []u8) Io.RandomSecureError!void {
    // The same sources as `std.Io.Threaded.randomSecure` minus
    // cancelation and the /dev/urandom fallback: arc4random_buf where
    // libc provides it (all the BSDs and Darwin, glibc 2.36+), otherwise
    // the getrandom syscall on Linux. Anything else has no entropy.
    if (builtin.link_libc and @TypeOf(posix.system.arc4random_buf) != void) {
        posix.system.arc4random_buf(buffer.ptr, buffer.len);
        return;
    }

    if (builtin.os.tag == .linux) {
        const linux = std.os.linux;
        var i: usize = 0;
        while (i < buffer.len) {
            const rc = linux.getrandom(buffer[i..].ptr, buffer.len - i, 0);
            switch (linux.errno(rc)) {
                .SUCCESS => i += rc,
                .INTR => continue,
                else => return error.EntropyUnavailable,
            }
        }
        return;
    }

    return error.EntropyUnavailable;
}

pub fn closeFd(fd: posix.fd_t) void {
    // Never retry close on EINTR: POSIX leaves the fd state unspecified
    // and Linux always closes it, so retrying risks closing an unrelated
    // fd opened by another thread.
    _ = posix.system.close(fd);
}

pub fn dirOpenFile(
    _: ?*anyopaque,
    dir: Dir,
    sub_path: []const u8,
    options: Dir.OpenFileOptions,
) File.OpenError!File {
    var path_buffer: [posix.PATH_MAX]u8 = undefined;
    const sub_path_posix = try Threaded.pathToPosix(sub_path, &path_buffer);

    // Nothing in the terminal locks files. Implementing this requires
    // flock fallbacks (see std.Io.Threaded); report it as unsupported.
    if (options.lock != .none) return error.FileLocksUnsupported;

    var flags: posix.O = .{
        .ACCMODE = switch (options.mode) {
            .read_only => .RDONLY,
            .write_only => .WRONLY,
            .read_write => .RDWR,
        },
        .NOFOLLOW = !options.follow_symlinks,
    };
    if (@hasField(posix.O, "CLOEXEC")) flags.CLOEXEC = true;
    if (@hasField(posix.O, "LARGEFILE")) flags.LARGEFILE = true;
    if (@hasField(posix.O, "NOCTTY")) flags.NOCTTY = !options.allow_ctty;
    if (@hasField(posix.O, "PATH")) flags.PATH = options.path_only;
    if (@hasField(posix.O, "RESOLVE_BENEATH")) flags.RESOLVE_BENEATH = options.resolve_beneath;

    const mode: posix.mode_t = 0;
    const fd: posix.fd_t = while (true) {
        const rc = openat_sym(dir.handle, sub_path_posix, flags, mode);
        switch (posix.errno(rc)) {
            .SUCCESS => break @intCast(rc),
            .INTR => continue,
            .INVAL => return error.BadPathName,
            .ACCES => return error.AccessDenied,
            .FBIG => return error.FileTooBig,
            .OVERFLOW => return error.FileTooBig,
            .ISDIR => return error.IsDir,
            .LOOP => return error.SymLinkLoop,
            .MFILE => return error.ProcessFdQuotaExceeded,
            .NAMETOOLONG => return error.NameTooLong,
            .NFILE => return error.SystemFdQuotaExceeded,
            .NODEV => return error.NoDevice,
            .NOENT => return error.FileNotFound,
            .SRCH => return error.FileNotFound,
            .NOMEM => return error.SystemResources,
            .NOSPC => return error.NoSpaceLeft,
            .NOTDIR => return error.NotDir,
            .PERM => return error.PermissionDenied,
            .EXIST => return error.PathAlreadyExists,
            .BUSY => return error.DeviceBusy,
            .OPNOTSUPP => return error.FileLocksUnsupported,
            .AGAIN => return error.WouldBlock,
            .TXTBSY => return error.FileBusy,
            .NXIO => return error.NoDevice,
            .ROFS => return error.ReadOnlyFileSystem,
            .ILSEQ => return error.BadPathName,
            else => |err| return posix.unexpectedErrno(err),
        }
    };
    errdefer closeFd(fd);

    const file: File = .{ .handle = fd, .flags = .{ .nonblocking = false } };

    if (!options.allow_directory) {
        const is_dir = is_dir: {
            const stat = fileStat(null, file) catch |err| switch (err) {
                // Directory-ness is unknown or unknowable.
                error.Streaming => break :is_dir false,
                else => |e| return e,
            };
            break :is_dir stat.kind == .directory;
        };
        if (is_dir) return error.IsDir;
    }

    return file;
}

pub fn dirClose(_: ?*anyopaque, dirs: []const Dir) void {
    for (dirs) |dir| closeFd(dir.handle);
}

pub fn fileClose(_: ?*anyopaque, files: []const File) void {
    for (files) |file| closeFd(file.handle);
}

pub fn fileStat(_: ?*anyopaque, file: File) File.StatError!File.Stat {
    if (builtin.os.tag == .linux) {
        const linux = std.os.linux;
        while (true) {
            var statx = std.mem.zeroes(linux.Statx);
            switch (linux.errno(linux.statx(
                file.handle,
                "",
                linux.AT.EMPTY_PATH,
                Threaded.linux_statx_request,
                &statx,
            ))) {
                .SUCCESS => return Threaded.statFromLinux(&statx),
                .INTR => continue,
                .NOMEM => return error.SystemResources,
                else => |err| return posix.unexpectedErrno(err),
            }
        }
    }

    while (true) {
        var stat = std.mem.zeroes(posix.Stat);
        switch (posix.errno(fstat_sym(file.handle, &stat))) {
            .SUCCESS => return Threaded.statFromPosix(&stat),
            .INTR => continue,
            .NOMEM => return error.SystemResources,
            .ACCES => return error.AccessDenied,
            else => |err| return posix.unexpectedErrno(err),
        }
    }
}

pub fn fileLength(userdata: ?*anyopaque, file: File) File.LengthError!u64 {
    const stat = try fileStat(userdata, file);
    return stat.size;
}

/// Gathers non-empty buffers into iovecs. Returns an empty slice if there
/// is nothing to read into.
fn buffersToIovecs(
    data: []const []u8,
    iovecs_buffer: *[Threaded.max_iovecs_len]posix.iovec,
) []posix.iovec {
    var i: usize = 0;
    for (data) |buf| {
        if (iovecs_buffer.len - i == 0) break;
        if (buf.len != 0) {
            iovecs_buffer[i] = .{ .base = buf.ptr, .len = buf.len };
            i += 1;
        }
    }
    return iovecs_buffer[0..i];
}

pub fn fileReadPositional(
    _: ?*anyopaque,
    file: File,
    data: []const []u8,
    offset: u64,
) File.ReadPositionalError!usize {
    var iovecs_buffer: [Threaded.max_iovecs_len]posix.iovec = undefined;
    const dest = buffersToIovecs(data, &iovecs_buffer);
    if (dest.len == 0) return 0;

    while (true) {
        const rc = if (comptime have_preadv)
            preadv_sym(file.handle, dest.ptr, @intCast(dest.len), @bitCast(offset))
        else
            posix.system.pread(file.handle, dest[0].base, dest[0].len, @bitCast(offset));
        switch (posix.errno(rc)) {
            .SUCCESS => return @bitCast(rc),
            .INTR, .TIMEDOUT => continue,
            .NXIO => return error.Unseekable,
            .SPIPE => return error.Unseekable,
            .OVERFLOW => return error.Unseekable,
            .NOBUFS => return error.SystemResources,
            .NOMEM => return error.SystemResources,
            .AGAIN => return error.WouldBlock,
            .IO => return error.InputOutput,
            .ISDIR => return error.IsDir,
            .BADF => return error.NotOpenForReading,
            else => |err| return posix.unexpectedErrno(err),
        }
    }
}

pub fn fileReadStreaming(
    file: File,
    data: []const []u8,
) Io.Operation.FileReadStreaming.Error!usize {
    var iovecs_buffer: [Threaded.max_iovecs_len]posix.iovec = undefined;
    const dest = buffersToIovecs(data, &iovecs_buffer);
    if (dest.len == 0) return 0;

    while (true) {
        const rc = posix.system.readv(file.handle, dest.ptr, @intCast(dest.len));
        switch (posix.errno(rc)) {
            .SUCCESS => {
                if (rc == 0) return error.EndOfStream;
                return @intCast(rc);
            },
            .INTR, .TIMEDOUT => continue,
            .AGAIN => return error.WouldBlock,
            .IO => return error.InputOutput,
            .ISDIR => return error.IsDir,
            .NOBUFS => return error.SystemResources,
            .NOMEM => return error.SystemResources,
            .NOTCONN => return error.SocketUnconnected,
            .CONNRESET => return error.ConnectionResetByPeer,
            .BADF => return error.NotOpenForReading,
            else => |err| return posix.unexpectedErrno(err),
        }
    }
}

pub fn fileSeekBy(_: ?*anyopaque, file: File, offset: i64) File.SeekError!void {
    while (true) {
        const rc = lseek_sym(file.handle, offset, posix.SEEK.CUR);
        switch (posix.errno(rc)) {
            .SUCCESS => return,
            .INTR => continue,
            .INVAL => return error.Unseekable,
            .OVERFLOW => return error.Unseekable,
            .SPIPE => return error.Unseekable,
            .NXIO => return error.Unseekable,
            else => |err| return posix.unexpectedErrno(err),
        }
    }
}

pub fn fileSeekTo(_: ?*anyopaque, file: File, offset: u64) File.SeekError!void {
    while (true) {
        const rc = lseek_sym(file.handle, @bitCast(offset), posix.SEEK.SET);
        switch (posix.errno(rc)) {
            .SUCCESS => return,
            .INTR => continue,
            .INVAL => return error.Unseekable,
            .OVERFLOW => return error.Unseekable,
            .SPIPE => return error.Unseekable,
            .NXIO => return error.Unseekable,
            else => |err| return posix.unexpectedErrno(err),
        }
    }
}

pub fn fileRealPath(
    _: ?*anyopaque,
    file: File,
    out_buffer: []u8,
) File.RealPathError!usize {
    return realPathFd(file.handle, out_buffer);
}

fn realPathFd(fd: posix.fd_t, out_buffer: []u8) File.RealPathError!usize {
    switch (builtin.os.tag) {
        .dragonfly, .driverkit, .ios, .maccatalyst, .macos, .tvos, .visionos, .watchos => {
            var sufficient_buffer: [posix.PATH_MAX]u8 = undefined;
            @memset(&sufficient_buffer, 0);
            while (true) {
                switch (posix.errno(posix.system.fcntl(fd, posix.F.GETPATH, &sufficient_buffer))) {
                    .SUCCESS => break,
                    .INTR => continue,
                    .ACCES => return error.AccessDenied,
                    .BADF => return error.FileNotFound,
                    .NOENT => return error.FileNotFound,
                    .NOMEM => return error.SystemResources,
                    .NOSPC => return error.NameTooLong,
                    .RANGE => return error.NameTooLong,
                    else => |err| return posix.unexpectedErrno(err),
                }
            }
            const n = std.mem.indexOfScalar(u8, &sufficient_buffer, 0) orelse sufficient_buffer.len;
            if (n > out_buffer.len) return error.NameTooLong;
            @memcpy(out_buffer[0..n], sufficient_buffer[0..n]);
            return n;
        },

        .linux, .serenity, .illumos => {
            var procfs_buf: ["/proc/self/path/-2147483648\x00".len]u8 = undefined;
            const template = if (builtin.os.tag == .illumos) "/proc/self/path/{d}" else "/proc/self/fd/{d}";
            const proc_path = std.fmt.bufPrintSentinel(&procfs_buf, template, .{fd}, 0) catch unreachable;
            while (true) {
                const rc = posix.system.readlink(proc_path, out_buffer.ptr, out_buffer.len);
                switch (posix.errno(rc)) {
                    .SUCCESS => return @bitCast(rc),
                    .INTR => continue,
                    .ACCES => return error.AccessDenied,
                    .IO => return error.FileSystem,
                    .LOOP => return error.SymLinkLoop,
                    .NAMETOOLONG => return error.NameTooLong,
                    .NOENT => return error.FileNotFound,
                    .NOMEM => return error.SystemResources,
                    .NOTDIR => return error.NotDir,
                    else => |err| return posix.unexpectedErrno(err),
                }
            }
        },

        .freebsd => {
            var k_file: std.c.kinfo_file = undefined;
            k_file.structsize = std.c.KINFO_FILE_SIZE;
            while (true) {
                switch (posix.errno(std.c.fcntl(fd, std.c.F.KINFO, @intFromPtr(&k_file)))) {
                    .SUCCESS => break,
                    .INTR => continue,
                    .BADF => return error.FileNotFound,
                    else => |err| return posix.unexpectedErrno(err),
                }
            }
            const len = std.mem.findScalar(u8, &k_file.path, 0) orelse k_file.path.len;
            if (len == 0) return error.NameTooLong;
            @memcpy(out_buffer[0..len], k_file.path[0..len]);
            return len;
        },

        else => return error.OperationUnsupported,
    }
}

pub fn dirRealPathFile(
    _: ?*anyopaque,
    dir: Dir,
    sub_path: []const u8,
    out_buffer: []u8,
) Dir.RealPathFileError!usize {
    var path_buffer: [posix.PATH_MAX]u8 = undefined;
    const sub_path_posix = try Threaded.pathToPosix(sub_path, &path_buffer);

    if (builtin.link_libc and dir.handle == posix.AT.FDCWD) {
        if (out_buffer.len < posix.PATH_MAX) return error.NameTooLong;
        while (true) {
            if (std.c.realpath(sub_path_posix, out_buffer.ptr)) |redundant_pointer| {
                std.debug.assert(redundant_pointer == out_buffer.ptr);
                return std.mem.indexOfScalar(u8, out_buffer, 0) orelse out_buffer.len;
            }
            switch (@as(posix.E, @enumFromInt(std.c._errno().*))) {
                .INTR => continue,
                .ACCES => return error.AccessDenied,
                .NOENT => return error.FileNotFound,
                .OPNOTSUPP => return error.OperationUnsupported,
                .NOTDIR => return error.NotDir,
                .NAMETOOLONG => return error.NameTooLong,
                .LOOP => return error.SymLinkLoop,
                .IO => return error.InputOutput,
                else => |err| return posix.unexpectedErrno(err),
            }
        }
    }

    // Fallback: open the path and resolve the fd. Used for non-cwd
    // directory handles (which the terminal itself never passes) and
    // non-libc builds.
    var flags: posix.O = .{};
    if (@hasField(posix.O, "NONBLOCK")) flags.NONBLOCK = true;
    if (@hasField(posix.O, "CLOEXEC")) flags.CLOEXEC = true;
    if (@hasField(posix.O, "PATH")) flags.PATH = true;

    const mode: posix.mode_t = 0;
    const fd: posix.fd_t = while (true) {
        const rc = openat_sym(dir.handle, sub_path_posix, flags, mode);
        switch (posix.errno(rc)) {
            .SUCCESS => break @intCast(rc),
            .INTR => continue,
            .INVAL => return error.BadPathName,
            .ACCES => return error.AccessDenied,
            .LOOP => return error.SymLinkLoop,
            .NAMETOOLONG => return error.NameTooLong,
            .NOENT => return error.FileNotFound,
            .NOMEM => return error.SystemResources,
            .NOTDIR => return error.NotDir,
            .ILSEQ => return error.BadPathName,
            else => |err| return posix.unexpectedErrno(err),
        }
    };
    defer closeFd(fd);

    return realPathFd(fd, out_buffer);
}

pub fn dirDeleteFile(
    _: ?*anyopaque,
    dir: Dir,
    sub_path: []const u8,
) Dir.DeleteFileError!void {
    var path_buffer: [posix.PATH_MAX]u8 = undefined;
    const sub_path_posix = try Threaded.pathToPosix(sub_path, &path_buffer);

    while (true) {
        switch (posix.errno(posix.system.unlinkat(dir.handle, sub_path_posix, 0))) {
            .SUCCESS => return,
            .INTR => continue,
            // Some systems return EPERM when trying to delete a directory;
            // stat to disambiguate from a real permission error.
            .PERM => switch (builtin.os.tag) {
                .driverkit, .ios, .maccatalyst, .macos, .tvos, .visionos, .watchos, .freebsd, .netbsd, .dragonfly, .openbsd, .illumos => {
                    var st = std.mem.zeroes(posix.Stat);
                    while (true) {
                        switch (posix.errno(fstatat_sym(
                            dir.handle,
                            sub_path_posix,
                            &st,
                            posix.AT.SYMLINK_NOFOLLOW,
                        ))) {
                            .SUCCESS => break,
                            .INTR => continue,
                            else => return error.PermissionDenied,
                        }
                    }
                    const is_dir = st.mode & posix.S.IFMT == posix.S.IFDIR;
                    return if (is_dir) error.IsDir else error.PermissionDenied;
                },
                else => return error.PermissionDenied,
            },
            .ACCES => return error.AccessDenied,
            .BUSY => return error.FileBusy,
            .IO => return error.FileSystem,
            .ISDIR => return error.IsDir,
            .LOOP => return error.SymLinkLoop,
            .NAMETOOLONG => return error.NameTooLong,
            .NOENT => return error.FileNotFound,
            .NOTDIR => return error.NotDir,
            .NOMEM => return error.SystemResources,
            .ROFS => return error.ReadOnlyFileSystem,
            .ILSEQ => return error.BadPathName,
            else => |err| return posix.unexpectedErrno(err),
        }
    }
}

pub fn futexWaitInner(ptr: *const u32, expected: u32, timeout_ns: ?u64) void {
    @branchHint(.cold);

    if (builtin.single_threaded) unreachable; // nobody would ever wake us

    switch (builtin.os.tag) {
        .linux => {
            const linux = std.os.linux;
            var ts_buffer: linux.timespec = undefined;
            const ts: ?*linux.timespec = if (timeout_ns) |ns| ts: {
                ts_buffer = .{
                    .sec = @intCast(ns / std.time.ns_per_s),
                    .nsec = @intCast(ns % std.time.ns_per_s),
                };
                break :ts &ts_buffer;
            } else null;
            const rc = linux.futex_4arg(ptr, .{ .cmd = .WAIT, .private = true }, expected, ts);
            switch (linux.errno(rc)) {
                .SUCCESS => {}, // notified by wake
                .INTR => {}, // caller's responsibility to retry
                .AGAIN => {}, // ptr.* != expected
                .INVAL => {}, // possibly timeout overflow
                .TIMEDOUT => {},
                else => {}, // spurious wakeup; caller retries
            }
        },

        .driverkit, .ios, .maccatalyst, .macos, .tvos, .visionos, .watchos => {
            const c = std.c;
            const flags: c.UL = .{
                .op = .COMPARE_AND_WAIT,
                .NO_ERRNO = true,
            };
            const us: u32 = us: {
                const ns = timeout_ns orelse break :us 0; // 0 means infinite
                const us = std.math.lossyCast(u32, ns / std.time.ns_per_us);
                break :us if (us == 0) 1 else us;
            };
            const status = c.__ulock_wait(flags, ptr, expected, us);
            if (status >= 0) return;
            switch (@as(c.E, @enumFromInt(-status))) {
                .INTR => {}, // spurious wake
                .FAULT => {}, // futex address paged out; caller retries
                .TIMEDOUT => {},
                else => {}, // spurious wakeup; caller retries
            }
        },

        .freebsd => {
            const flags = @intFromEnum(std.c.UMTX_OP.WAIT_UINT_PRIVATE);
            var tm_size: usize = 0;
            var tm: std.c._umtx_time = undefined;
            var tm_ptr: ?*const std.c._umtx_time = null;
            if (timeout_ns) |ns| {
                tm_ptr = &tm;
                tm_size = @sizeOf(@TypeOf(tm));
                tm.flags = 0; // relative time
                tm.clockid = .MONOTONIC;
                tm.timeout = .{
                    .sec = @intCast(ns / std.time.ns_per_s),
                    .nsec = @intCast(ns % std.time.ns_per_s),
                };
            }
            _ = std.c._umtx_op(
                @intFromPtr(ptr),
                flags,
                @as(c_ulong, expected),
                tm_size,
                @intFromPtr(tm_ptr),
            );
        },

        else => {
            // Portable fallback: futex waits may wake spuriously, so a
            // bounded sleep is a valid (if inefficient) implementation.
            // Contention is not expected in libghostty-vt's threading
            // model, so this is effectively never reached.
            if (@atomicLoad(u32, ptr, .seq_cst) != expected) return;
            const ns = @min(timeout_ns orelse std.time.ns_per_ms, std.time.ns_per_ms);
            const ts: posix.timespec = .{
                .sec = 0,
                .nsec = @intCast(ns),
            };
            _ = posix.system.nanosleep(&ts, null);
        },
    }
}

pub fn futexWake(userdata: ?*anyopaque, ptr: *const u32, max_waiters: u32) void {
    @branchHint(.cold);
    _ = userdata;

    if (builtin.single_threaded) return; // nothing to wake up

    switch (builtin.os.tag) {
        .linux => {
            const linux = std.os.linux;
            _ = linux.futex_3arg(
                ptr,
                .{ .cmd = .WAKE, .private = true },
                @min(max_waiters, std.math.maxInt(i32)),
            );
        },

        .driverkit, .ios, .maccatalyst, .macos, .tvos, .visionos, .watchos => {
            const c = std.c;
            const flags: c.UL = .{
                .op = .COMPARE_AND_WAIT,
                .NO_ERRNO = true,
                .WAKE_ALL = max_waiters > 1,
            };
            while (true) {
                const status = c.__ulock_wake(flags, ptr, 0);
                if (status >= 0) return;
                switch (@as(c.E, @enumFromInt(-status))) {
                    .INTR, .CANCELED => continue, // spurious wake
                    else => return,
                }
            }
        },

        .freebsd => {
            _ = std.c._umtx_op(
                @intFromPtr(ptr),
                @intFromEnum(std.c.UMTX_OP.WAKE_PRIVATE),
                @min(max_waiters, std.math.maxInt(c_ulong)),
                0,
                0,
            );
        },

        // Portable fallback waiters poll with a timeout; nothing to do.
        else => {},
    }
}