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
17 changes: 15 additions & 2 deletions src/atomic.zig
Original file line number Diff line number Diff line change
Expand Up @@ -609,7 +609,10 @@ pub fn atomicWrite(a: Allocator, path: []const u8, data: []const u8, opts: Write
// os.fstat names no path. Record that before the cleanup calls.
const failed = failOs(a, why, err, null, null);
sys.close(fd);
// Created above with O_EXCL, so it is this call's file.
// Created above with O_EXCL, so it is this call's file. A failed
// cleanup must not replace the errno the message was built from.
const saved = sys.last_errno;
defer sys.last_errno = saved;
sys.unlinkat(fsx.cwd, tmp, 0) catch {};
return failed;
};
Expand Down Expand Up @@ -671,7 +674,13 @@ pub fn atomicWriteAt(a: Allocator, dir: sys.fd_t, name: []const u8, data: []cons
var done = false;
defer {
sys.close(fd);
if (!done) sys.unlinkat(dir, tmp, 0) catch {};
if (!done) {
// The temporary name may already be gone. That failure is not
// the call the caller is reporting.
const saved = sys.last_errno;
defer sys.last_errno = saved;
sys.unlinkat(dir, tmp, 0) catch {};
}
}
// openat applies the umask to the create, so the exact mode the
// caller names is set on the descriptor before anything is written
Expand All @@ -685,6 +694,10 @@ pub fn atomicWriteAt(a: Allocator, dir: sys.fd_t, name: []const u8, data: []cons
}

fn discard(tmp: []const u8, created: fsx.Stat) void {
// stat or unlink can fail when the temporary name was removed
// already. That failure is not the call the caller is reporting.
const saved = sys.last_errno;
defer sys.last_errno = saved;
const cur = fsx.statAt(fsx.cwd, tmp, false) catch return;
if (cur.dev == created.dev and cur.ino == created.ino) sys.unlinkat(fsx.cwd, tmp, 0) catch {};
}
Expand Down
60 changes: 60 additions & 0 deletions src/atomic_test.zig
Original file line number Diff line number Diff line change
Expand Up @@ -1756,6 +1756,27 @@ fn closedOpenat(dir: sys.fd_t, path: [*:0]const u8, flags: sys.O, mode: linux.mo
return rc;
}

/// Remove the open file, then fail the write with EIO. Cleanup's later
/// stat or unlink fails with ENOENT, a different errno.
fn ioAfterUnlink(fd: sys.fd_t, _: []const u8) usize {
var buf: [sys.path_max]u8 = undefined;
const path = fsx.realpathFd(fd, &buf) catch unreachable;
sys.unlinkat(fsx.cwd, path, 0) catch unreachable;
return err(.IO);
}

/// Open the temporary file, remove it, and close the descriptor. The
/// following fstat fails with EBADF and the cleanup unlink with ENOENT.
fn closeAndUnlink(dir: sys.fd_t, path: [*:0]const u8, flags: sys.O, mode: linux.mode_t) usize {
const rc = linux.openat(dir, path, flags, mode);
if (linux.errno(rc) != .SUCCESS) return rc;
const fd: sys.fd_t = @intCast(rc);
const un = linux.unlinkat(dir, path, 0);
sys.close(fd);
if (linux.errno(un) != .SUCCESS) return un;
return rc;
}

var stale_path: []const u8 = "";
var parent_path: []const u8 = "";
var moved_parent_path: []const u8 = "";
Expand Down Expand Up @@ -1810,6 +1831,45 @@ test "OSError messages cover write, fsync, fstat, and stale unlink failures" {
try testing.expectEqualStrings(try A.print("[Errno 21] Is a directory: '{s}'", .{tmp}), last_why);
}

test "discard keeps the errno when its stat fails" {
begin();
defer end();
const dir = tmpdir();
defer cleanup(dir);
const path = join(dir, "fresh");
// The write hook removes the temporary file, so discard's stat is ENOENT.
atomic.ops.write = ioAfterUnlink;
try testing.expectError(error.Unexpected, write(path, "new", replace));
try testing.expectEqual(linux.E.IO, sys.last_errno);
try testing.expectEqualStrings("[Errno 5] Input/output error", last_why);
}

test "fstat cleanup keeps the errno when its unlink fails" {
begin();
defer end();
const dir = tmpdir();
defer cleanup(dir);
const path = join(dir, "fresh");
// The open hook closes the descriptor and removes the file, so fstat is
// EBADF and the cleanup unlink is ENOENT.
atomic.ops.openat = closeAndUnlink;
try testing.expectError(error.InvalidArgument, write(path, "new", replace));
try testing.expectEqual(linux.E.BADF, sys.last_errno);
try testing.expectEqualStrings("[Errno 9] Bad file descriptor", last_why);
}

test "atomicWriteAt cleanup keeps the errno when its unlink fails" {
begin();
defer end();
const dir = tmpdir();
defer cleanup(dir);
atomic.ops.write = ioAfterUnlink;
const dfd = try fsx.openDir(fsx.cwd, dir, false);
defer sys.close(dfd);
try testing.expectError(error.Unexpected, atomic.atomicWriteAt(A, dfd, "at", "new", 0o644));
try testing.expectEqual(linux.E.IO, sys.last_errno);
}

test "a parent fsync failure carries no filename and keeps its errno" {
begin();
defer end();
Expand Down
19 changes: 13 additions & 6 deletions src/state.zig
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,15 @@ threadlocal var os_text_len: usize = 0;
threadlocal var os_path: [sys.path_max]u8 = undefined;
threadlocal var os_path_len: usize = 0;

/// The OSError recorded for the latest `RootLock.acquire` on this thread.
/// Null when that acquire has not failed, or failed for a reason that is
/// not an operating-system error. `text` is Python's "[Errno N] ..." line
/// without a filename. `path` is the file that call would name, or empty
/// when it names none, such as a write or a lock on an open descriptor.
///
/// Both slices refer to thread-local storage. The next `RootLock.acquire`
/// on this thread reuses that storage, so copy them before calling it
/// again.
pub fn osFailure() ?OsFailure {
if (!os_noted) return null;
return .{ .text = os_text[0..os_text_len], .path = os_path[0..os_path_len] };
Expand Down Expand Up @@ -66,10 +75,6 @@ fn notedUnder(err: Error, root: []const u8, name: []const u8) Error {
return err;
}

fn noteErrno(e: linux.E, path: ?[]const u8) void {
noteText(sys.describeErrno(e), path);
}

/// Regular, owned by `uid`, one link, mode & 0o077 == 0.
pub fn privateOk(st: fsx.Stat, uid: linux.uid_t) bool {
return st.isReg() and st.uid == uid and st.nlink == 1 and st.mode & 0o077 == 0;
Expand Down Expand Up @@ -477,8 +482,10 @@ pub const RootLock = struct {
.AGAIN, .ACCES => if (deadline_ms) |d| {
if (try pause(d)) return error.Busy;
} else {
noteErrno(linux.errno(rc), null);
return error.Unexpected;
// F_SETLKW does not treat these as contention. Return the
// mapped error so describe agrees with the snapshot:
// EAGAIN is Unexpected, EACCES is AccessDenied.
return noted(mapped(rc), null);
},
else => return noted(mapped(rc), null),
}
Expand Down
34 changes: 34 additions & 0 deletions src/state_test.zig
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,40 @@ test "acquisition errors release the descriptors and the gate" {
}
}

test "a blocking record lock records EAGAIN and EACCES" {
const root = begin();
defer end(root);
const Hooks = struct {
var code: linux.E = .AGAIN;
fn fail(_: fsx.fd_t, _: i32, _: usize) usize {
return err(code);
}
};
defer state.lock_ops.* = .{};
state.lock_ops.fcntl = Hooks.fail;
for ([_]linux.E{ .AGAIN, .ACCES }) |code| {
Hooks.code = code;
sys.last_errno = .SUCCESS;
if (RootLock.acquire(A, root, null)) |_| {
return error.TestUnexpectedResult;
} else |failed| {
const failure = state.osFailure() orelse return error.TestUnexpectedResult;
try testing.expectEqualStrings("", failure.path);
try testing.expectEqualStrings(sys.describeErrno(code), failure.text);
try testing.expectEqual(code, sys.last_errno);
// describe of the returned error must name this errno. Returning
// Unexpected for EACCES makes it print an I/O error instead.
const sys_err = sys.asError(failed) orelse return error.TestUnexpectedResult;
try testing.expectEqualStrings(failure.text, sys.describe(sys_err));
switch (code) {
.AGAIN => try testing.expectEqual(error.Unexpected, sys_err),
.ACCES => try testing.expectEqual(error.AccessDenied, sys_err),
else => unreachable,
}
}
}
}

test "a short pid write does not reuse a stale errno" {
const root = begin();
defer end(root);
Expand Down
154 changes: 153 additions & 1 deletion tests/fs_lock_parity_probe.zig
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,12 @@
//! short timeout, printing the outcome. The test holds the lock.
//! - `hold-lock PATH MS`: takes the lock with no timeout, prints
//! `held`, sleeps MS and exits, releasing the lock as it goes.
//! - `osfail`: atomicWrite failures. The last field is the full
//! `why.msg`, compared with str() of the OSError Python raises for
//! the same call.
//! - `rootlock`: RootLock.acquire failures. The last two fields are
//! osFailure text and path, or NONE when the failure was not an
//! operating-system error.
const std = @import("std");
const linux = std.os.linux;
const common = @import("zig_common");
Expand Down Expand Up @@ -175,7 +181,13 @@ fn atomicMode() void {
};
for (aw_cases) |c| {
var why: common.atomic.Why = .{};
opLine("atomicwrite", c.name, common.atomic.atomicWrite(A, c.name, c.data, c.opts, &why));
const result = common.atomic.atomicWrite(A, c.name, c.data, c.opts, &why);
if (result) |_| {
emit(&.{ "atomicwrite", hexOf(c.name), "OK", hexOf(why.msg) });
} else |e| {
const status = std.fmt.allocPrint(A, "ERR:{s}", .{errName(e)}) catch unreachable;
emit(&.{ "atomicwrite", hexOf(c.name), status, hexOf(why.msg) });
}
why.deinit(A);
}
const rc_cases = [_]struct { name: []const u8, data: []const u8 }{
Expand All @@ -199,6 +211,142 @@ fn atomicMode() void {
}
}

/// One atomicWrite, including the full failure text. `why.msg` is copied
/// into the output before it is freed.
fn writeFail(name: []const u8, path: []const u8, data: []const u8, opts: common.atomic.WriteOptions) void {
var why: common.atomic.Why = .{};
const result = common.atomic.atomicWrite(A, path, data, opts, &why);
const status = if (result) |_|
"OK"
else |e|
std.fmt.allocPrint(A, "ERR:{s}", .{@errorName(e)}) catch unreachable;
emit(&.{ "osfail", name, status, hexOf(why.msg) });
why.deinit(A);
}

/// A write that the file-size limit stops. Python's os.write names no
/// file for that OSError, and neither does atomicWrite. A flush of a
/// regular file cannot be made to fail from this process, so the write
/// is the no-filename failure the probe can raise.
fn writeTooBig() void {
var old: linux.rlimit = undefined;
if (linux.errno(linux.prlimit(0, .FSIZE, null, &old)) != .SUCCESS) {
emit(&.{ "osfail", "write-fsize", "SKIP", "" });
return;
}
const unlimited = std.math.maxInt(u64);
const room: u64 = if (old.max == unlimited) 8 else old.max;
if (room < 8) {
emit(&.{ "osfail", "write-fsize", "SKIP", "" });
return;
}
const ign: linux.Sigaction = .{ .handler = .{ .handler = linux.SIG.IGN }, .mask = linux.sigemptyset(), .flags = 0 };
var prev: linux.Sigaction = undefined;
_ = linux.sigaction(.XFSZ, &ign, &prev);
defer _ = linux.sigaction(.XFSZ, &prev, null);
const lim: linux.rlimit = .{ .cur = 8, .max = old.max };
if (linux.errno(linux.prlimit(0, .FSIZE, &lim, null)) != .SUCCESS) {
emit(&.{ "osfail", "write-fsize", "SKIP", "" });
return;
}
defer _ = linux.prlimit(0, .FSIZE, &old, null);
var payload: [64]u8 = @splat('x');
writeFail("write-fsize", "fsize-out", &payload, .{});
}

fn chmodAt(path: []const u8, mode: linux.mode_t) void {
var zb: [sys.path_max:0]u8 = undefined;
const z = sys.z(&zb, path) catch unreachable;
if (linux.errno(linux.fchmodat(fsx.cwd, z.ptr, mode)) != .SUCCESS) unreachable;
}

/// `osfail` mode: real atomicWrite failures whose text is Python's
/// OSError for the same operation. The fixture is created here, in the
/// working directory, and any directory made unwritable is restored
/// before returning so the caller can remove the tree.
fn osFailMode() void {
var zb: [sys.path_max:0]u8 = undefined;
_ = linux.mkdirat(fsx.cwd, (sys.z(&zb, "ro") catch unreachable).ptr, 0o755);
if (linux.geteuid() == 0) {
emit(&.{ "osfail", "open-ro", "SKIP", "" });
emit(&.{ "osfail", "mkdir-ro", "SKIP", "" });
} else {
chmodAt("ro", 0o555);
defer chmodAt("ro", 0o755);
// open of the temporary file, which Python names rather than the
// destination
writeFail("open-ro", "ro/new", "x\n", .{});
// mkdir of the first missing ancestor, not the leaf that was asked for
writeFail("mkdir-ro", "ro/a/b/file", "x\n", .{});
}

_ = linux.mkdirat(fsx.cwd, (sys.z(&zb, "adir") catch unreachable).ptr, 0o755);
const meta = sys.openat(fsx.cwd, "meta", .{ .ACCMODE = .WRONLY, .CREAT = true, .EXCL = true }, 0o644) catch unreachable;
sys.writeAll(meta, "m\n") catch unreachable;
sys.close(meta);
// metadata comes from a regular file, so the directory at the
// destination is reached by rename rather than refused as a source
writeFail("rename-dir", "adir", "data\n", .{ .metadata_from = "meta" });

_ = linux.symlinkat("nowhere", fsx.cwd, (sys.z(&zb, "gone") catch unreachable).ptr);
writeFail("missing-ancestor", "gone/a/b/file", "x\n", .{});
writeTooBig();
}

fn lockCase(name: []const u8, root: []const u8) void {
if (state.RootLock.acquire(A, root, 0)) |held| {
held.release();
emit(&.{ "rootlock", name, "OK", "", "" });
} else |e| {
const status = std.fmt.allocPrint(A, "ERR:{s}", .{@errorName(e)}) catch unreachable;
if (state.osFailure()) |failure| {
emit(&.{ "rootlock", name, status, hexOf(failure.text), hexOf(failure.path) });
} else {
emit(&.{ "rootlock", name, status, "NONE", "NONE" });
}
}
}

/// `rootlock` mode: RootLock.acquire failures. Text and path are the
/// osFailure snapshot; NONE means the failure was not an OS error and
/// the snapshot was cleared.
fn rootLockMode() void {
var zb: [sys.path_max:0]u8 = undefined;
const file = sys.openat(fsx.cwd, "fileroot", .{ .ACCMODE = .WRONLY, .CREAT = true, .EXCL = true }, 0o644) catch unreachable;
sys.close(file);
lockCase("file-root", "fileroot");

_ = linux.symlinkat("nowhere", fsx.cwd, (sys.z(&zb, "dangling") catch unreachable).ptr);
lockCase("dangling-root", "dangling");

_ = linux.symlinkat("nowhere", fsx.cwd, (sys.z(&zb, "gone") catch unreachable).ptr);
lockCase("ancestor", "gone/a/b");

if (linux.geteuid() == 0) {
emit(&.{ "rootlock", "gate-ro", "SKIP", "", "" });
emit(&.{ "rootlock", "sidecar-ro", "SKIP", "", "" });
} else {
_ = linux.mkdirat(fsx.cwd, (sys.z(&zb, "gate") catch unreachable).ptr, 0o755);
chmodAt("gate", 0o555);
defer chmodAt("gate", 0o755);
lockCase("gate-ro", "gate");

_ = linux.mkdirat(fsx.cwd, (sys.z(&zb, "side") catch unreachable).ptr, 0o755);
const side = sys.openat(fsx.cwd, "side/.lock", .{ .ACCMODE = .RDWR, .CREAT = true, .EXCL = true }, 0o600) catch unreachable;
sys.close(side);
chmodAt("side", 0o555);
defer chmodAt("side", 0o755);
lockCase("sidecar-ro", "side");
}

// a directory planted at the gate is refused without an OSError, and
// only after the cases above have recorded one, so a stale snapshot
// would show up here
_ = linux.mkdirat(fsx.cwd, (sys.z(&zb, "gatedir") catch unreachable).ptr, 0o755);
_ = linux.mkdirat(fsx.cwd, (sys.z(&zb, "gatedir/.lock") catch unreachable).ptr, 0o755);
lockCase("gate-dir", "gatedir");
}

/// `which` mode: whichShutil over a PATH fixture the test built around
/// the probe's working directory, plus the unset-PATH cases.
fn whichMode() void {
Expand Down Expand Up @@ -881,6 +1029,10 @@ pub fn main(init: std.process.Init.Minimal) !void {
effectsMode();
} else if (std.mem.eql(u8, mode, "atomic")) {
atomicMode();
} else if (std.mem.eql(u8, mode, "osfail")) {
osFailMode();
} else if (std.mem.eql(u8, mode, "rootlock")) {
rootLockMode();
} else if (std.mem.eql(u8, mode, "which")) {
whichMode();
} else if (std.mem.eql(u8, mode, "diag")) {
Expand Down
Loading
Loading