Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/+keep-above-stdio-emfile-test.misc.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Add a test that `sys.keepAboveStdio` returns `error.Unexpected` and leaves the original descriptor open when duplication fails with `EMFILE`.
1 change: 1 addition & 0 deletions changelog.d/+proc-keep-above-stdio-fd-count.misc.md
Original file line number Diff line number Diff line change
@@ -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.
1 change: 1 addition & 0 deletions changelog.d/+shared-child-wait.misc.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Move the forked-child wait that retries an interrupted `wait4` into the shared test helper.
1 change: 1 addition & 0 deletions changelog.d/+shared-fd-count.misc.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Move the open-descriptor count into a shared test helper and return an error when reading `/proc/self/fd` fails.
18 changes: 4 additions & 14 deletions src/proc.zig
Original file line number Diff line number Diff line change
Expand Up @@ -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`
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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");
Expand All @@ -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");
Expand All @@ -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");
Expand Down
52 changes: 52 additions & 0 deletions src/proc_test.zig
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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);
}
1 change: 1 addition & 0 deletions src/root.zig
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand Down
23 changes: 7 additions & 16 deletions src/state_test.zig
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -173,7 +164,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;
Expand All @@ -186,7 +177,7 @@ test "acquisition errors release the descriptors and the gate" {
try testing.expectEqualStrings("", failure.path);
try testing.expectEqualStrings("[Errno 5] Input/output error", failure.text);
state.lock_ops.* = .{};
try testing.expectEqual(before, fdCount(A));
try testing.expectEqual(before, try test_support.fdCount(A));
try acquireAndRelease(root);
}
}
Expand Down Expand Up @@ -287,11 +278,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);
}

Expand Down Expand Up @@ -420,9 +411,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);
Expand Down
71 changes: 71 additions & 0 deletions src/sys.zig
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
37 changes: 37 additions & 0 deletions src/test_support.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
//! 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");
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
/// 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
}

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)));
}
Loading