Skip to content

std.Build.Step.Compile: fix race condition in args file creation #23997

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
21 changes: 20 additions & 1 deletion lib/std/Build/Step/Compile.zig
Original file line number Diff line number Diff line change
Expand Up @@ -1801,7 +1801,26 @@ fn getZigArgs(compile: *Compile, fuzz: bool) ![][]const u8 {
);

const args_file = "args" ++ fs.path.sep_str ++ args_hex_hash;
try b.cache_root.handle.writeFile(.{ .sub_path = args_file, .data = args });
if (b.cache_root.handle.access(args_file, .{})) |_| {
// The args file is already present from a previous run.
} else |err| switch (err) {
error.FileNotFound => {
try b.cache_root.handle.makePath("tmp");
const rand_int = std.crypto.random.int(u64);
const tmp_path = "tmp" ++ fs.path.sep_str ++ std.fmt.hex(rand_int);
try b.cache_root.handle.writeFile(.{ .sub_path = tmp_path, .data = args });
defer b.cache_root.handle.deleteFile(tmp_path) catch {
// It's fine if the temporary file can't be cleaned up.
};
b.cache_root.handle.rename(tmp_path, args_file) catch |rename_err| switch (rename_err) {
error.PathAlreadyExists => {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's worth noting that the package fetching code also handles error.AccessDenied:

error.PathAlreadyExists, error.AccessDenied => {
However, based on the documentation for RenameError, it looks like that case is only relevant for directories, not files as in this case:

zig/lib/std/posix.zig

Lines 2595 to 2597 in ef35c3d

/// On Windows, this error may be returned instead of PathAlreadyExists when
/// renaming a directory over an existing directory.
AccessDenied,
so this code doesn't handle it.

// The args file was created by another concurrent build process.
},
else => |other_err| return other_err,
};
},
else => |other_err| return other_err,
}

const resolved_args_file = try mem.concat(arena, u8, &.{
"@",
Expand Down