Commit 618398b7d3

Evan Haas <evan@lagerdata.com>
2022-04-07 08:48:30
std.fs: prevent possible integer overflow in Dir.makePath
The call to `makeDir` for the top-level component of `sub_path` can return `error.FileNotFound` if the directory represented by `self` has been deleted. Fixes #11397
1 parent d66c61a
Changed files (2)
lib
lib/std/fs/test.zig
@@ -610,6 +610,16 @@ test "makePath, put some files in it, deleteTree" {
     }
 }
 
+test "makePath in a directory that no longer exists" {
+    if (builtin.os.tag == .windows) return error.SkipZigTest; // Windows returns FileBusy if attempting to remove an open dir
+
+    var tmp = tmpDir(.{});
+    defer tmp.cleanup();
+    try tmp.parent_dir.deleteTree(&tmp.sub_path);
+
+    try testing.expectError(error.FileNotFound, tmp.dir.makePath("sub-path"));
+}
+
 test "writev, readv" {
     var tmp = tmpDir(.{});
     defer tmp.cleanup();
lib/std/fs.zig
@@ -1308,9 +1308,9 @@ pub const Dir = struct {
                     if (end_index == sub_path.len) return;
                 },
                 error.FileNotFound => {
-                    if (end_index == 0) return err;
                     // march end_index backward until next path component
                     while (true) {
+                        if (end_index == 0) return err;
                         end_index -= 1;
                         if (path.isSep(sub_path[end_index])) break;
                     }