libxev-sys 0.0.1-rc.2

Low-level FFI bindings to libxev (built from vendored sources via Zig).
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
const std = @import("std");
const builtin = @import("builtin");
const assert = std.debug.assert;
const linux = std.os.linux;
const posix = std.posix;
const common = @import("common.zig");
const xev_posix = @import("../posix.zig");

/// Process management, such as waiting for process exit.
pub fn Process(comptime xev: type) type {
    if (xev.dynamic) return ProcessDynamic(xev);

    return switch (xev.backend) {
        // Supported, uses pidfd
        .io_uring,
        .epoll,
        => ProcessPidFd(xev),

        .kqueue => ProcessKqueue(xev),

        .iocp => ProcessIocp(xev),

        // Unsupported
        .wasi_poll => struct {},
    };
}

/// Process implementation using pidfd (Linux).
fn ProcessPidFd(comptime xev: type) type {
    return struct {
        const Self = @This();

        /// The error that can come in the wait callback.
        pub const WaitError = xev.Sys.PollError || error{
            InvalidChild,
        };

        /// pidfd file descriptor
        fd: posix.fd_t,

        /// Create a new process watcher for the given pid.
        pub fn init(pid: posix.pid_t) !Self {
            // Note: SOCK_NONBLOCK == PIDFD_NONBLOCK but we should PR that
            // over to Zig.
            const res = linux.pidfd_open(pid, posix.SOCK.NONBLOCK);
            const fd = switch (posix.errno(res)) {
                .SUCCESS => @as(posix.fd_t, @intCast(res)),
                .INVAL => return error.InvalidArgument,
                .MFILE => return error.ProcessFdQuotaExceeded,
                .NFILE => return error.SystemFdQuotaExceeded,
                .NODEV => return error.SystemResources,
                .NOMEM => return error.SystemResources,
                else => |err| return posix.unexpectedErrno(err),
            };

            return .{
                .fd = fd,
            };
        }

        /// Clean up the process watcher.
        pub fn deinit(self: *Self) void {
            xev_posix.close(self.fd);
        }

        /// Wait for the process to exit. This will automatically call
        /// `waitpid` or equivalent and report the exit status.
        pub fn wait(
            self: Self,
            loop: *xev.Loop,
            c: *xev.Completion,
            comptime Userdata: type,
            userdata: ?*Userdata,
            comptime cb: *const fn (
                ud: ?*Userdata,
                l: *xev.Loop,
                c: *xev.Completion,
                r: WaitError!u32,
            ) xev.CallbackAction,
        ) void {
            const events: u32 = comptime switch (xev.backend) {
                .io_uring => posix.POLL.IN,
                .epoll => linux.EPOLL.IN,
                else => unreachable,
            };

            c.* = .{
                .op = .{
                    .poll = .{
                        .fd = self.fd,
                        .events = events,
                    },
                },

                .userdata = userdata,
                .callback = (struct {
                    fn callback(
                        ud: ?*anyopaque,
                        l_inner: *xev.Loop,
                        c_inner: *xev.Completion,
                        r: xev.Result,
                    ) xev.CallbackAction {
                        const arg: WaitError!u32 = arg: {
                            // If our poll failed, report that error.
                            _ = r.poll catch |err| break :arg err;

                            // We need to wait on the pidfd because it is noted as ready
                            const fd = c_inner.op.poll.fd;
                            var info: linux.siginfo_t = undefined;
                            const res = linux.waitid(.PIDFD, fd, &info, linux.W.EXITED, null);

                            break :arg switch (posix.errno(res)) {
                                .SUCCESS => @as(u32, @intCast(info.fields.common.second.sigchld.status)),
                                .CHILD => error.InvalidChild,

                                // The fd isn't ready to read, I guess?
                                .AGAIN => return .rearm,
                                else => |err| err: {
                                    std.log.warn("unexpected process wait errno={}", .{err});
                                    break :err error.Unexpected;
                                },
                            };
                        };

                        return @call(.always_inline, cb, .{
                            common.userdataValue(Userdata, ud),
                            l_inner,
                            c_inner,
                            arg,
                        });
                    }
                }).callback,
            };
            loop.add(c);
        }

        test {
            _ = ProcessTests(
                xev,
                Self,
            );
        }
    };
}

fn reapProcess(pid: posix.pid_t) void {
    var status: c_int = undefined;
    while (true) switch (posix.errno(posix.system.waitpid(pid, &status, 0))) {
        .SUCCESS => return,
        .INTR => continue,
        .CHILD => return,
        else => unreachable,
    };
}

fn ProcessKqueue(comptime xev: type) type {
    return struct {
        const Self = @This();

        /// The error that can come in the wait callback.
        pub const WaitError = xev.Sys.ProcError;

        /// The pid to watch.
        pid: posix.pid_t,

        /// Create a new process watcher for the given pid.
        pub fn init(pid: posix.pid_t) !Self {
            return .{
                .pid = pid,
            };
        }

        /// Does nothing for Kqueue.
        pub fn deinit(self: *Self) void {
            _ = self;
        }

        /// Wait for the process to exit. This will automatically call
        /// `waitpid` or equivalent and report the exit status.
        pub fn wait(
            self: Self,
            loop: *xev.Loop,
            c: *xev.Completion,
            comptime Userdata: type,
            userdata: ?*Userdata,
            comptime cb: *const fn (
                ud: ?*Userdata,
                l: *xev.Loop,
                c: *xev.Completion,
                r: WaitError!u32,
            ) xev.CallbackAction,
        ) void {
            c.* = .{
                .op = .{
                    .proc = .{
                        .pid = self.pid,
                        .flags = xev.Sys.NOTE_EXIT_FLAGS,
                    },
                },

                .userdata = userdata,
                .callback = (struct {
                    fn callback(
                        ud: ?*anyopaque,
                        l_inner: *xev.Loop,
                        c_inner: *xev.Completion,
                        r: xev.Result,
                    ) xev.CallbackAction {
                        // Reap the process. We do this because our xev.Process
                        // docs note that this is the equivalent of calling
                        // `wait` on a process. The Linux side (pidfd) does this
                        // automatically since the `waitid` syscall is used.
                        if (r.proc) |_| {
                            reapProcess(c_inner.op.proc.pid);
                        } else |_| {}

                        return @call(.always_inline, cb, .{
                            common.userdataValue(Userdata, ud),
                            l_inner,
                            c_inner,
                            if (r.proc) |v| v else |err| err,
                        });
                    }
                }).callback,
            };
            loop.add(c);
        }

        test {
            _ = ProcessTests(
                xev,
                Self,
            );
        }
    };
}

const windows = @import("../windows.zig");
fn ProcessIocp(comptime xev: type) type {
    return struct {
        const Self = @This();

        pub const WaitError = xev.Sys.JobObjectError;

        job: windows.HANDLE,
        process: windows.HANDLE,

        pub fn init(process: posix.pid_t) !Self {
            const current_process = windows.kernel32.GetCurrentProcess();

            // Duplicate the process handle so we don't rely on the caller keeping it alive
            var dup_process: windows.HANDLE = undefined;
            const dup_result = windows.kernel32.DuplicateHandle(
                current_process,
                process,
                current_process,
                &dup_process,
                0,
                windows.FALSE,
                windows.DUPLICATE_SAME_ACCESS,
            );
            if (dup_result == .FALSE) return windows.unexpectedError(windows.kernel32.GetLastError());

            const job = try windows.exp.CreateJobObject(null, null);
            errdefer _ = windows.CloseHandle(job);

            try windows.exp.AssignProcessToJobObject(job, dup_process);

            return .{
                .job = job,
                .process = dup_process,
            };
        }

        pub fn deinit(self: *Self) void {
            _ = windows.CloseHandle(self.job);
            _ = windows.CloseHandle(self.process);
        }

        pub fn wait(
            self: Self,
            loop: *xev.Loop,
            c: *xev.Completion,
            comptime Userdata: type,
            userdata: ?*Userdata,
            comptime cb: *const fn (
                ud: ?*Userdata,
                l: *xev.Loop,
                c: *xev.Completion,
                r: WaitError!u32,
            ) xev.CallbackAction,
        ) void {
            c.* = .{
                .op = .{
                    .job_object = .{
                        .job = self.job,
                        .userdata = self.process,
                    },
                },
                .userdata = userdata,
                .callback = (struct {
                    fn callback(
                        ud: ?*anyopaque,
                        l_inner: *xev.Loop,
                        c_inner: *xev.Completion,
                        r: xev.Result,
                    ) xev.CallbackAction {
                        if (r.job_object) |result| {
                            switch (result) {
                                .associated => {
                                    // There was a period of time between when the job object was created
                                    // and when it was associated with the completion port. We may have
                                    // missed a notification, so check if it's still alive.

                                    var exit_code: windows.DWORD = undefined;
                                    const process: windows.HANDLE = @ptrCast(c_inner.op.job_object.userdata);
                                    const has_code = windows.kernel32.GetExitCodeProcess(process, &exit_code) != .FALSE;
                                    if (!has_code) std.log.warn("unable to get exit code for process={}", .{windows.kernel32.GetLastError()});
                                    if (exit_code == windows.exp.STILL_ACTIVE) return .rearm;

                                    return @call(.always_inline, cb, .{
                                        common.userdataValue(Userdata, ud),
                                        l_inner,
                                        c_inner,
                                        exit_code,
                                    });
                                },
                                .message => |message| {
                                    const result_inner = switch (message.type) {
                                        .JOB_OBJECT_MSG_EXIT_PROCESS,
                                        .JOB_OBJECT_MSG_ABNORMAL_EXIT_PROCESS,
                                        => b: {
                                            const process: windows.HANDLE = @ptrCast(c_inner.op.job_object.userdata);
                                            const pid = windows.exp.k32.GetProcessId(process);
                                            if (pid == 0) break :b WaitError.Unexpected;
                                            if (message.value != pid) return .rearm;

                                            var exit_code: windows.DWORD = undefined;
                                            const has_code = windows.kernel32.GetExitCodeProcess(process, &exit_code) != .FALSE;
                                            if (!has_code) std.log.warn("unable to get exit code for process={}", .{windows.kernel32.GetLastError()});
                                            break :b if (has_code) exit_code else WaitError.Unexpected;
                                        },
                                        else => return .rearm,
                                    };

                                    return @call(.always_inline, cb, .{ common.userdataValue(Userdata, ud), l_inner, c_inner, result_inner });
                                },
                            }
                        } else |err| {
                            return @call(.always_inline, cb, .{
                                common.userdataValue(Userdata, ud),
                                l_inner,
                                c_inner,
                                err,
                            });
                        }
                    }
                }).callback,
            };
            loop.add(c);
        }

        test {
            _ = ProcessTests(
                xev,
                Self,
            );
        }
    };
}

fn ProcessDynamic(comptime dynamic: type) type {
    return struct {
        const Self = @This();

        backend: Union,

        pub const Union = dynamic.Union(&.{"Process"});
        pub const WaitError = dynamic.ErrorSet(&.{ "Process", "WaitError" });

        pub fn init(fd: posix.pid_t) !Self {
            return .{ .backend = switch (dynamic.backend) {
                inline else => |tag| backend: {
                    const api = (comptime dynamic.superset(tag)).Api();
                    break :backend @unionInit(
                        Union,
                        @tagName(tag),
                        try api.Process.init(fd),
                    );
                },
            } };
        }

        pub fn deinit(self: *Self) void {
            switch (dynamic.backend) {
                inline else => |tag| @field(
                    self.backend,
                    @tagName(tag),
                ).deinit(),
            }
        }

        pub fn wait(
            self: Self,
            loop: *dynamic.Loop,
            c: *dynamic.Completion,
            comptime Userdata: type,
            userdata: ?*Userdata,
            comptime cb: *const fn (
                ud: ?*Userdata,
                l: *dynamic.Loop,
                c: *dynamic.Completion,
                r: WaitError!u32,
            ) dynamic.CallbackAction,
        ) void {
            switch (dynamic.backend) {
                inline else => |tag| {
                    c.ensureTag(tag);

                    const api = (comptime dynamic.superset(tag)).Api();
                    const api_cb = (struct {
                        fn callback(
                            ud_inner: ?*Userdata,
                            l_inner: *api.Loop,
                            c_inner: *api.Completion,
                            r_inner: api.Process.WaitError!u32,
                        ) dynamic.CallbackAction {
                            return cb(
                                ud_inner,
                                @fieldParentPtr("backend", @as(
                                    *dynamic.Loop.Union,
                                    @fieldParentPtr(@tagName(tag), l_inner),
                                )),
                                @fieldParentPtr("value", @as(
                                    *dynamic.Completion.Union,
                                    @fieldParentPtr(@tagName(tag), c_inner),
                                )),
                                r_inner,
                            );
                        }
                    }).callback;

                    @field(
                        self.backend,
                        @tagName(tag),
                    ).wait(
                        &@field(loop.backend, @tagName(tag)),
                        &@field(c.value, @tagName(tag)),
                        Userdata,
                        userdata,
                        api_cb,
                    );
                },
            }
        }

        test {
            _ = ProcessTests(
                dynamic,
                Self,
            );
        }
    };
}

fn ProcessTests(
    comptime xev: type,
    comptime Impl: type,
) type {
    return struct {
        const argv_0: []const []const u8 = switch (builtin.os.tag) {
            .windows => &.{ "cmd.exe", "/C", "exit 0" },
            else => &.{ "sh", "-c", "exit 0" },
        };

        const argv_42: []const []const u8 = switch (builtin.os.tag) {
            .windows => &.{ "cmd.exe", "/C", "exit 42" },
            else => &.{ "sh", "-c", "exit 42" },
        };

        test "process wait" {
            const testing = std.testing;
            const io = testing.io;

            const child = try std.process.spawn(io, .{ .argv = argv_0 });

            var loop = try xev.Loop.init(.{});
            defer loop.deinit();

            var p = try Impl.init(child.id.?);
            defer p.deinit();

            // Wait
            var code: ?u32 = null;
            var c_wait: xev.Completion = .{};
            p.wait(&loop, &c_wait, ?u32, &code, (struct {
                fn callback(
                    ud: ?*?u32,
                    _: *xev.Loop,
                    _: *xev.Completion,
                    r: Impl.WaitError!u32,
                ) xev.CallbackAction {
                    ud.?.* = r catch unreachable;
                    return .disarm;
                }
            }).callback);

            // Wait for wake
            try loop.run(.until_done);
            try testing.expectEqual(@as(u32, 0), code.?);
        }

        test "process wait with non-zero exit code" {
            if (builtin.os.tag == .freebsd) return error.SkipZigTest;
            const testing = std.testing;
            const io = testing.io;

            const child = try std.process.spawn(io, .{ .argv = argv_42 });

            var loop = try xev.Loop.init(.{});
            defer loop.deinit();

            var p = try Impl.init(child.id.?);
            defer p.deinit();

            // Wait
            var code: ?u32 = null;
            var c_wait: xev.Completion = .{};
            p.wait(&loop, &c_wait, ?u32, &code, (struct {
                fn callback(
                    ud: ?*?u32,
                    _: *xev.Loop,
                    _: *xev.Completion,
                    r: Impl.WaitError!u32,
                ) xev.CallbackAction {
                    ud.?.* = r catch unreachable;
                    return .disarm;
                }
            }).callback);

            // Wait for wake
            try loop.run(.until_done);
            try testing.expectEqual(@as(u32, 42), code.?);
        }

        test "process wait on a process that already exited" {
            const testing = std.testing;
            const io = testing.io;

            var child = try std.process.spawn(io, .{ .argv = argv_0 });

            var loop = try xev.Loop.init(.{});
            defer loop.deinit();

            var p = try Impl.init(child.id.?);
            defer p.deinit();

            _ = try child.wait(io);

            // Wait
            var code: ?u32 = null;
            var c_wait: xev.Completion = .{};
            p.wait(&loop, &c_wait, ?u32, &code, (struct {
                fn callback(
                    ud: ?*?u32,
                    _: *xev.Loop,
                    _: *xev.Completion,
                    r: Impl.WaitError!u32,
                ) xev.CallbackAction {
                    ud.?.* = r catch 0;
                    return .disarm;
                }
            }).callback);

            // Wait for wake
            try loop.run(.until_done);
            try testing.expectEqual(@as(u32, 0), code.?);
        }
    };
}