From 2444e27d005a8da87a65f1dd2ac3b6c3e1079f6f Mon Sep 17 00:00:00 2001 From: Rohit Goswami Date: Fri, 20 Nov 2026 20:24:46 +0000 Subject: [PATCH 1/4] test: share the open-descriptor count The lock tests count `/proc/self/fd` with a helper in the test file. That helper now lives in one shared test file, and a failed read of the directory returns an error. --- changelog.d/+shared-fd-count.misc.md | 1 + src/root.zig | 1 + src/state_test.zig | 23 +++++++---------------- src/test_support.zig | 19 +++++++++++++++++++ 4 files changed, 28 insertions(+), 16 deletions(-) create mode 100644 changelog.d/+shared-fd-count.misc.md create mode 100644 src/test_support.zig diff --git a/changelog.d/+shared-fd-count.misc.md b/changelog.d/+shared-fd-count.misc.md new file mode 100644 index 0000000..c464bf6 --- /dev/null +++ b/changelog.d/+shared-fd-count.misc.md @@ -0,0 +1 @@ +Move the open-descriptor count into a shared test helper and return an error when reading `/proc/self/fd` fails. diff --git a/src/root.zig b/src/root.zig index 6564e4f..7840e44 100644 --- a/src/root.zig +++ b/src/root.zig @@ -26,6 +26,7 @@ pub const syslog = @import("syslog.zig"); test { @import("std").testing.refAllDecls(@This()); + _ = @import("test_support.zig"); _ = @import("atomic_test.zig"); _ = @import("state_test.zig"); _ = @import("proc_test.zig"); diff --git a/src/state_test.zig b/src/state_test.zig index ff719df..b6b51ee 100644 --- a/src/state_test.zig +++ b/src/state_test.zig @@ -8,6 +8,7 @@ const state = @import("state.zig"); const sys = @import("sys.zig"); const fsx = @import("fsx.zig"); const atomic = @import("atomic.zig"); +const test_support = @import("test_support.zig"); const testing = std.testing; const RootLock = state.RootLock; @@ -37,16 +38,6 @@ fn err(e: linux.E) usize { return @bitCast(-@as(isize, @backingInt(e))); } -fn fdCount(gpa: std.mem.Allocator) usize { - const fd = fsx.openDir(fsx.cwd, "/proc/self/fd", true) catch unreachable; - defer sys.close(fd); - var it = fsx.DirIter.init(gpa, fd) catch unreachable; - defer it.deinit(gpa); - var n: usize = 0; - while (it.next() catch null) |_| n += 1; - return n - 1; // the directory's own descriptor -} - fn waitExit(pid: isize) u32 { var status: u32 = 0; _ = linux.wait4(@intCast(pid), @ptrCast(&status), 0, null); @@ -167,7 +158,7 @@ test "acquisition errors release the descriptors and the gate" { const root = begin(); defer end(root); inline for (.{ "flock", "fcntl", "ftruncate", "write" }) |target| { - const before = fdCount(A); + const before = try test_support.fdCount(A); if (comptime std.mem.eql(u8, target, "flock")) state.lock_ops.flock = eioFlock; if (comptime std.mem.eql(u8, target, "fcntl")) state.lock_ops.fcntl = eioFcntl; if (comptime std.mem.eql(u8, target, "ftruncate")) state.lock_ops.ftruncate = eioFtruncate; @@ -177,7 +168,7 @@ test "acquisition errors release the descriptors and the gate" { return error.TestUnexpectedResult; } else |_| {} state.lock_ops.* = .{}; - try testing.expectEqual(before, fdCount(A)); + try testing.expectEqual(before, try test_support.fdCount(A)); try acquireAndRelease(root); } } @@ -211,11 +202,11 @@ test "a release error still closes both layers" { const root = begin(); defer end(root); const holder = try RootLock.acquire(A, root, 0); - const before = fdCount(A); + const before = try test_support.fdCount(A); state.lock_ops.fcntl = eioFcntl; holder.release(); state.lock_ops.* = .{}; - try testing.expectEqual(before - 2, fdCount(A)); + try testing.expectEqual(before - 2, try test_support.fdCount(A)); try acquireAndRelease(root); } @@ -342,9 +333,9 @@ test "a hard link planted while the gate is awaited stops the truncate" { try createFile(dir, ".lock", "secret"); plant_dir = dir; state.lock_ops.flock = linkThenFlock; - const before = fdCount(gpa); + const before = try test_support.fdCount(gpa); try testing.expectError(error.GateNotPrivate, RootLock.acquire(gpa, root, 0)); - try testing.expectEqual(before, fdCount(gpa)); + try testing.expectEqual(before, try test_support.fdCount(gpa)); try expectContents(gpa, dir, "alias", "secret"); state.lock_ops.* = .{}; try sys.unlinkat(dir, "alias", 0); diff --git a/src/test_support.zig b/src/test_support.zig new file mode 100644 index 0000000..1b5f4dc --- /dev/null +++ b/src/test_support.zig @@ -0,0 +1,19 @@ +//! Helpers the unit tests share. The library test root imports this file +//! the same way it imports the other test files. A release build does not. +const std = @import("std"); +const linux = std.os.linux; +const sys = @import("sys.zig"); +const fsx = @import("fsx.zig"); + +/// Open descriptors of this process, not counting the directory descriptor +/// used to read `/proc/self/fd`. Opening that directory or reading an entry +/// returns the error, so a failed read cannot look like a smaller count. +pub fn fdCount(gpa: std.mem.Allocator) (fsx.Error || std.mem.Allocator.Error)!usize { + const fd = try fsx.openDir(fsx.cwd, "/proc/self/fd", true); + defer sys.close(fd); + var it = try fsx.DirIter.init(gpa, fd); + defer it.deinit(gpa); + var n: usize = 0; + while (try it.next()) |_| n += 1; + return n - 1; // the directory's own descriptor +} From fd54a1b1f4ad734b8e51836fa2678bd1dcf9294b Mon Sep 17 00:00:00 2001 From: Rohit Goswami Date: Fri, 20 Nov 2026 20:25:07 +0000 Subject: [PATCH 2/4] test: share the forked-child wait The proc tests had their own helper that forks a child and retries an interrupted `wait4`. That wait now lives in the shared test helper, and the proc tests call it there. --- changelog.d/+shared-child-wait.misc.md | 1 + src/proc.zig | 18 ++++-------------- src/test_support.zig | 18 ++++++++++++++++++ 3 files changed, 23 insertions(+), 14 deletions(-) create mode 100644 changelog.d/+shared-child-wait.misc.md diff --git a/changelog.d/+shared-child-wait.misc.md b/changelog.d/+shared-child-wait.misc.md new file mode 100644 index 0000000..b9dacde --- /dev/null +++ b/changelog.d/+shared-child-wait.misc.md @@ -0,0 +1 @@ +Move the forked-child wait that retries an interrupted `wait4` into the shared test helper. diff --git a/src/proc.zig b/src/proc.zig index 7b9e07d..f1f52fd 100644 --- a/src/proc.zig +++ b/src/proc.zig @@ -9,6 +9,7 @@ const std = @import("std"); const linux = std.os.linux; const sys = @import("sys.zig"); const fsx = @import("fsx.zig"); +const test_support = @import("test_support.zig"); const Allocator = std.mem.Allocator; /// The child's environment block, as execve(2) takes it; `env.Builder.envp` @@ -800,17 +801,6 @@ test "run rejects an empty argv" { try std.testing.expectError(error.InvalidArgument, run(gpa, "/bin/true", &.{}, no_env, .{})); } -/// Run `body` in a forked child, which may close the descriptors the test -/// runner talks over, and expect it to exit 0. -fn expectChildPasses(comptime body: fn () u8) !void { - const pid: isize = @bitCast(linux.fork()); - if (pid < 0) return error.Unexpected; - if (pid == 0) linux.exit_group(body()); - var status: i32 = 0; - while (linux.errno(linux.wait4(@intCast(pid), &status, 0, null)) == .INTR) {} - try std.testing.expectEqual(Term{ .exited = 0 }, decode(@bitCast(status))); -} - /// 0 when `script` under /bin/sh prints `want`, 1 when it prints something /// else, 2 when it cannot be run. fn shPrints(script: []const u8, stdin: ?[]const u8, want: []const u8) u8 { @@ -897,7 +887,7 @@ test "makeExecFixture removes scratch directories after setup failures" { } test "a closed stdout at start does not send the child's stderr to its stdout" { - try expectChildPasses(struct { + try test_support.expectChildPasses(struct { fn body() u8 { sys.close(1); return shPrints("echo out; echo err >&2", null, "out\n"); @@ -906,7 +896,7 @@ test "a closed stdout at start does not send the child's stderr to its stdout" { } test "a closed stdin at start leaves the child's stdin and stderr on their files" { - try expectChildPasses(struct { + try test_support.expectChildPasses(struct { fn body() u8 { sys.close(0); const r = shPrints("readlink /proc/self/fd/0 || echo closed", null, "/dev/null\n"); @@ -917,7 +907,7 @@ test "a closed stdin at start leaves the child's stdin and stderr on their files } test "a closed stderr at start leaves the child's stderr on /dev/null" { - try expectChildPasses(struct { + try test_support.expectChildPasses(struct { fn body() u8 { sys.close(2); return shPrints("readlink /proc/self/fd/2 || echo closed", null, "/dev/null\n"); diff --git a/src/test_support.zig b/src/test_support.zig index 1b5f4dc..81cc1a7 100644 --- a/src/test_support.zig +++ b/src/test_support.zig @@ -4,6 +4,7 @@ const std = @import("std"); const linux = std.os.linux; const sys = @import("sys.zig"); const fsx = @import("fsx.zig"); +const proc = @import("proc.zig"); /// Open descriptors of this process, not counting the directory descriptor /// used to read `/proc/self/fd`. Opening that directory or reading an entry @@ -17,3 +18,20 @@ pub fn fdCount(gpa: std.mem.Allocator) (fsx.Error || std.mem.Allocator.Error)!us while (try it.next()) |_| n += 1; return n - 1; // the directory's own descriptor } + +fn childTerm(status: u32) proc.Term { + if (status & 0x7f == 0) return .{ .exited = linux.W.EXITSTATUS(status) }; + return .{ .signaled = status & 0x7f }; +} + +/// Run `body` in a forked child, which may close the descriptors the test +/// runner talks over, and expect it to exit 0. `wait4` is retried when the +/// call is interrupted. +pub fn expectChildPasses(comptime body: fn () u8) !void { + const pid: isize = @bitCast(linux.fork()); + if (pid < 0) return error.Unexpected; + if (pid == 0) linux.exit_group(body()); + var status: i32 = 0; + while (linux.errno(linux.wait4(@intCast(pid), &status, 0, null)) == .INTR) {} + try std.testing.expectEqual(proc.Term{ .exited = 0 }, childTerm(@bitCast(status))); +} From 4c2643a8945f17c0b3f54cc27ec144f657c27734 Mon Sep 17 00:00:00 2001 From: Rohit Goswami Date: Fri, 20 Nov 2026 20:25:28 +0000 Subject: [PATCH 3/4] test: report keepAboveStdio failure when no free descriptor remains `sys.keepAboveStdio` returns `error.Unexpected` when duplication fails with `EMFILE`, and the original descriptor stays open. A child lowers `RLIMIT_NOFILE`, fills the table, and restores the limit. --- .../+keep-above-stdio-emfile-test.misc.md | 1 + src/sys.zig | 71 +++++++++++++++++++ 2 files changed, 72 insertions(+) create mode 100644 changelog.d/+keep-above-stdio-emfile-test.misc.md diff --git a/changelog.d/+keep-above-stdio-emfile-test.misc.md b/changelog.d/+keep-above-stdio-emfile-test.misc.md new file mode 100644 index 0000000..8b1af94 --- /dev/null +++ b/changelog.d/+keep-above-stdio-emfile-test.misc.md @@ -0,0 +1 @@ +Add a test that `sys.keepAboveStdio` returns `error.Unexpected` and leaves the original descriptor open when duplication fails with `EMFILE`. diff --git a/src/sys.zig b/src/sys.zig index eb08161..c422eca 100644 --- a/src/sys.zig +++ b/src/sys.zig @@ -536,3 +536,74 @@ test "keepAboveStdio moves descriptors 0, 1 and 2 above 2 with close-on-exec" { _ = try call(linux.wait4, .{ @as(linux.pid_t, @intCast(pid)), &status, @as(u32, 0), @as(?*linux.rusage, null) }); try std.testing.expectEqual(@as(i32, 0), status); } + +test "keepAboveStdio reports duplication failure when the descriptor table is full" { + // A limit of 3 makes F_DUPFD with a minimum of 3 return EINVAL. The + // soft limit stays above that, and the child fills every slot it + // allows, so the failure is EMFILE. The limit is restored before + // the child exits. + const Child = struct { + fn run() u8 { + var saved: linux.rlimit = undefined; + if (linux.errno(linux.getrlimit(.NOFILE, &saved)) != .SUCCESS) return 20; + if (linux.errno(linux.fcntl(0, linux.F.GETFD, 0)) != .SUCCESS) { + const fd = openat(linux.AT.FDCWD, "/dev/null", .{}, 0) catch return 21; + if (fd != 0) { + if (linux.errno(linux.dup2(fd, 0)) != .SUCCESS) { + close(fd); + return 22; + } + close(fd); + } + } + if (saved.max < 4) return 23; + const cap = @min(saved.max, @as(linux.rlim_t, 8)); + const tightened: linux.rlimit = .{ .cur = cap, .max = saved.max }; + if (linux.errno(linux.setrlimit(.NOFILE, &tightened)) != .SUCCESS) return 24; + defer _ = linux.setrlimit(.NOFILE, &saved); + + var extras: [16]fd_t = undefined; + var n_extra: usize = 0; + defer for (extras[0..n_extra]) |fd| close(fd); + + var hit = false; + while (n_extra < extras.len) { + const fd = openat(linux.AT.FDCWD, "/dev/null", .{}, 0) catch |err| { + if (err == error.Unexpected and last_errno == .MFILE) { + hit = true; + break; + } + return 25; + }; + if (@as(linux.rlim_t, @intCast(fd)) >= cap) { + close(fd); + return 26; + } + extras[n_extra] = fd; + n_extra += 1; + } + if (!hit) return 27; + + const low: fd_t = 0; + if (keepAboveStdio(low)) |_| { + return 28; + } else |err| { + // EMFILE is not its own error. The call reports it as + // Unexpected, and last_errno keeps the kernel's value. + if (err != error.Unexpected or last_errno != .MFILE) return 29; + if (!std.mem.eql(u8, describe(err), "[Errno 24] Too many open files")) return 30; + } + // On error the original descriptor is left open. + if (linux.errno(linux.fcntl(low, linux.F.GETFD, 0)) != .SUCCESS) return 31; + + if (linux.errno(linux.setrlimit(.NOFILE, &saved)) != .SUCCESS) return 32; + var back: linux.rlimit = undefined; + if (linux.errno(linux.getrlimit(.NOFILE, &back)) != .SUCCESS) return 33; + if (back.cur != saved.cur or back.max != saved.max) return 34; + return 0; + } + }; + + const test_support = @import("test_support.zig"); + try test_support.expectChildPasses(Child.run); +} From 800af994dc3fff50823232b87c9d18e8a95022d1 Mon Sep 17 00:00:00 2001 From: Rohit Goswami Date: Fri, 20 Nov 2026 20:25:52 +0000 Subject: [PATCH 4/4] test: count descriptors around the keepAboveStdio paths in proc The test counts `/proc/self/fd` before and after each `proc` path that calls `sys.keepAboveStdio`. The later count matches the earlier one. --- .../+proc-keep-above-stdio-fd-count.misc.md | 1 + src/proc_test.zig | 52 +++++++++++++++++++ 2 files changed, 53 insertions(+) create mode 100644 changelog.d/+proc-keep-above-stdio-fd-count.misc.md diff --git a/changelog.d/+proc-keep-above-stdio-fd-count.misc.md b/changelog.d/+proc-keep-above-stdio-fd-count.misc.md new file mode 100644 index 0000000..7f14d57 --- /dev/null +++ b/changelog.d/+proc-keep-above-stdio-fd-count.misc.md @@ -0,0 +1 @@ +Add a descriptor count around the `proc` paths that call `sys.keepAboveStdio`, checking `/proc/self/fd` before and after so a leaked descriptor fails the test. diff --git a/src/proc_test.zig b/src/proc_test.zig index 3440b9f..64a9782 100644 --- a/src/proc_test.zig +++ b/src/proc_test.zig @@ -8,6 +8,7 @@ const proc = @import("proc.zig"); const sys = @import("sys.zig"); const fsx = @import("fsx.zig"); const atomic = @import("atomic.zig"); +const test_support = @import("test_support.zig"); const testing = std.testing; const limit = 64 * 1024; @@ -495,3 +496,54 @@ test "run with all standard streams closed moves shared devnull and pipes above _ = try sys.call(linux.wait4, .{ @as(linux.pid_t, @intCast(pid)), &status, @as(u32, 0), @as(?*linux.rusage, null) }); try testing.expectEqual(@as(i32, 0), status); } + +fn keepAboveStdioFdCounts() u8 { + var arena_impl = std.heap.ArenaAllocator.init(std.heap.page_allocator); + defer arena_impl.deinit(); + const a = arena_impl.allocator(); + const pages = std.heap.page_allocator; + + // Slots 0, 1 and 2 are closed, which is when childExec moves a source + // and when a newly opened descriptor can land below 3. + sys.close(0); + sys.close(1); + sys.close(2); + const baseline = test_support.fdCount(pages) catch return 9; + + const opened = sys.openat(linux.AT.FDCWD, "/dev/null", .{}, 0) catch return 10; + if (opened >= 3) return 11; + const moved = sys.keepAboveStdio(opened) catch return 12; + if (moved < 3) return 13; + // One new descriptor, the moved one. The low slot is closed, so a + // duplication that skips that close shows up as an extra entry. + const after_move = test_support.fdCount(pages) catch return 9; + if (after_move != baseline + 1) return 14; + if (linux.errno(linux.fcntl(opened, linux.F.GETFD, 0)) != .BADF) return 15; + sys.close(moved); + const after_close = test_support.fdCount(pages) catch return 9; + if (after_close != baseline) return 16; + + // proc.run opens devnull and the stdout pipe, and the child moves any + // of those that sit below 3. This process closes its copies. + const res = proc.run(a, "/bin/sh", &.{ "sh", "-c", "printf ok && printf drop >&2" }, no_env, .{}) catch return 17; + if (res.term.code() != 0 or !std.mem.eql(u8, res.stdout, "ok")) return 18; + const after_run = test_support.fdCount(pages) catch return 9; + if (after_run != baseline) return 19; + + // The exec-failure pipe's write end goes through keepAboveStdio here. + if (proc.run(a, "/no/such/zig-common-program", &.{"missing"}, no_env, .{ .exec_error = true })) |_| { + return 20; + } else |err| { + if (err != error.NotFound) return 21; + } + const after_exec = test_support.fdCount(pages) catch return 9; + if (after_exec != baseline) return 22; + return 0; +} + +test "proc keepAboveStdio paths do not leak descriptors" { + // The count runs in the child. Closing the standard streams there is + // what makes these paths move a descriptor, and the child's table is + // the one the calls change. + try test_support.expectChildPasses(keepAboveStdioFdCounts); +}