Skip to content

Commit e832656

Browse files
committed
implement nt path conversion for windows
1 parent 87aa052 commit e832656

File tree

5 files changed

+208
-22
lines changed

5 files changed

+208
-22
lines changed

lib/std/fs.zig

Lines changed: 0 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1285,15 +1285,6 @@ pub const Dir = struct {
12851285
.SecurityDescriptor = null,
12861286
.SecurityQualityOfService = null,
12871287
};
1288-
if (sub_path_w[0] == '.' and sub_path_w[1] == 0) {
1289-
// Windows does not recognize this, but it does work with empty string.
1290-
nt_name.Length = 0;
1291-
}
1292-
if (sub_path_w[0] == '.' and sub_path_w[1] == '.' and sub_path_w[2] == 0) {
1293-
// If you're looking to contribute to zig and fix this, see here for an example of how to
1294-
// implement this: https://git.midipix.org/ntapi/tree/src/fs/ntapi_tt_open_physical_parent_directory.c
1295-
@panic("TODO opening '..' with a relative directory handle is not yet implemented on Windows");
1296-
}
12971288
const open_reparse_point: w.DWORD = if (no_follow) w.FILE_OPEN_REPARSE_POINT else 0x0;
12981289
var io: w.IO_STATUS_BLOCK = undefined;
12991290
const rc = w.ntdll.NtCreateFile(

lib/std/fs/test.zig

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -79,8 +79,17 @@ test "openDirAbsolute" {
7979
break :blk try fs.realpathAlloc(&arena.allocator, relative_path);
8080
};
8181

82-
var dir = try fs.openDirAbsolute(base_path, .{});
83-
defer dir.close();
82+
{
83+
var dir = try fs.openDirAbsolute(base_path, .{});
84+
defer dir.close();
85+
}
86+
87+
for ([_][]const u8{ ".", ".." }) |sub_path| {
88+
const dir_path = try fs.path.join(&arena.allocator, &[_][]const u8{ base_path, sub_path });
89+
defer arena.allocator.free(dir_path);
90+
var dir = try fs.openDirAbsolute(dir_path, .{});
91+
defer dir.close();
92+
}
8493
}
8594

8695
test "readLinkAbsolute" {

lib/std/mem.zig

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1829,6 +1829,49 @@ test "replace" {
18291829
testing.expect(eql(u8, output[0..], "Favor reading over writing ."));
18301830
}
18311831

1832+
/// Replace all occurences of `needle` with `replacement`.
1833+
pub fn replaceScalar(comptime T: type, slice: []T, needle: T, replacement: T) void {
1834+
for (slice) |e, i| {
1835+
if (e == needle) {
1836+
slice[i] = replacement;
1837+
}
1838+
}
1839+
}
1840+
1841+
/// Collapse consecutive duplicate elements into one entry.
1842+
pub fn collapseRepeats(comptime T: type, slice: []T, elem: T) usize {
1843+
if (slice.len == 0) return 0;
1844+
var write_idx: usize = 1;
1845+
var read_idx: usize = 1;
1846+
while (read_idx < slice.len) : (read_idx += 1) {
1847+
if (slice[read_idx - 1] != elem or slice[read_idx] != elem) {
1848+
slice[write_idx] = slice[read_idx];
1849+
write_idx += 1;
1850+
}
1851+
}
1852+
return write_idx;
1853+
}
1854+
1855+
fn testCollapseRepeats(str: []const u8, elem: u8, expected: []const u8) !void {
1856+
const mutable = try std.testing.allocator.dupe(u8, str);
1857+
defer std.testing.allocator.free(mutable);
1858+
const actual = mutable[0..collapseRepeats(u8, mutable, elem)];
1859+
testing.expect(std.mem.eql(u8, actual, expected));
1860+
}
1861+
test "collapseRepeats" {
1862+
try testCollapseRepeats("", '/', "");
1863+
try testCollapseRepeats("a", '/', "a");
1864+
try testCollapseRepeats("/", '/', "/");
1865+
try testCollapseRepeats("//", '/', "/");
1866+
try testCollapseRepeats("/a", '/', "/a");
1867+
try testCollapseRepeats("//a", '/', "/a");
1868+
try testCollapseRepeats("a/", '/', "a/");
1869+
try testCollapseRepeats("a//", '/', "a/");
1870+
try testCollapseRepeats("a/a", '/', "a/a");
1871+
try testCollapseRepeats("a//a", '/', "a/a");
1872+
try testCollapseRepeats("//a///a////", '/', "/a/a/");
1873+
}
1874+
18321875
/// Calculate the size needed in an output buffer to perform a replacement.
18331876
pub fn replacementSize(comptime T: type, input: []const T, needle: []const T, replacement: []const T) usize {
18341877
var i: usize = 0;

lib/std/os/windows.zig

Lines changed: 84 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1528,6 +1528,81 @@ pub const PathSpace = struct {
15281528
}
15291529
};
15301530

1531+
/// The error type for `removeDotDirsSanitized`
1532+
pub const RemoveDotDirsError = error{TooManyParentDirs};
1533+
1534+
/// Removes '.' and '..' path components from a "sanitized relative path".
1535+
/// A "sanitized path" is one where:
1536+
/// 1) all forward slashes have been replaced with back slashes
1537+
/// 2) all repeating back slashes have been collapsed
1538+
/// 3) the path is a relative one (does not start with a back slash)
1539+
pub fn removeDotDirsSanitized(comptime T: type, path: []T) RemoveDotDirsError!usize {
1540+
std.debug.assert(path.len == 0 or path[0] != '\\');
1541+
1542+
var write_idx: usize = 0;
1543+
var read_idx: usize = 0;
1544+
while (read_idx < path.len) {
1545+
if (path[read_idx] == '.') {
1546+
if (read_idx + 1 == path.len)
1547+
return write_idx;
1548+
1549+
const after_dot = path[read_idx + 1];
1550+
if (after_dot == '\\') {
1551+
read_idx += 2;
1552+
continue;
1553+
}
1554+
if (after_dot == '.' and (read_idx + 2 == path.len or path[read_idx + 2] == '\\')) {
1555+
if (write_idx == 0) return error.TooManyParentDirs;
1556+
std.debug.assert(write_idx >= 2);
1557+
write_idx -= 1;
1558+
while (true) {
1559+
write_idx -= 1;
1560+
if (write_idx == 0) break;
1561+
if (path[write_idx] == '\\') {
1562+
write_idx += 1;
1563+
break;
1564+
}
1565+
}
1566+
if (read_idx + 2 == path.len)
1567+
return write_idx;
1568+
read_idx += 3;
1569+
continue;
1570+
}
1571+
}
1572+
1573+
// skip to the next path separator
1574+
while (true) : (read_idx += 1) {
1575+
if (read_idx == path.len)
1576+
return write_idx;
1577+
path[write_idx] = path[read_idx];
1578+
write_idx += 1;
1579+
if (path[read_idx] == '\\')
1580+
break;
1581+
}
1582+
read_idx += 1;
1583+
}
1584+
return write_idx;
1585+
}
1586+
1587+
/// Normalizes a Windows path with the following steps:
1588+
/// 1) convert all forward slashes to back slashes
1589+
/// 2) collapse duplicate back slashes
1590+
/// 3) remove '.' and '..' directory parts
1591+
/// Returns the length of the new path.
1592+
pub fn normalizePath(comptime T: type, path: []T) RemoveDotDirsError!usize {
1593+
mem.replaceScalar(T, path, '/', '\\');
1594+
const new_len = mem.collapseRepeats(T, path, '\\');
1595+
1596+
const prefix_len: usize = init: {
1597+
if (new_len >= 1 and path[0] == '\\') break :init 1;
1598+
if (new_len >= 2 and path[1] == ':')
1599+
break :init if (new_len >= 3 and path[2] == '\\') @as(usize, 3) else @as(usize, 2);
1600+
break :init 0;
1601+
};
1602+
1603+
return prefix_len + try removeDotDirsSanitized(T, path[prefix_len..new_len]);
1604+
}
1605+
15311606
/// Same as `sliceToPrefixedFileW` but accepts a pointer
15321607
/// to a null-terminated path.
15331608
pub fn cStrToPrefixedFileW(s: [*:0]const u8) !PathSpace {
@@ -1554,17 +1629,9 @@ pub fn sliceToPrefixedFileW(s: []const u8) !PathSpace {
15541629
};
15551630
path_space.len = start_index + try std.unicode.utf8ToUtf16Le(path_space.data[start_index..], s);
15561631
if (path_space.len > path_space.data.len) return error.NameTooLong;
1557-
// > File I/O functions in the Windows API convert "/" to "\" as part of
1558-
// > converting the name to an NT-style name, except when using the "\\?\"
1559-
// > prefix as detailed in the following sections.
1560-
// from https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file#maximum-path-length-limitation
1561-
// Because we want the larger maximum path length for absolute paths, we
1562-
// convert forward slashes to backward slashes here.
1563-
for (path_space.data[0..path_space.len]) |*elem| {
1564-
if (elem.* == '/') {
1565-
elem.* = '\\';
1566-
}
1567-
}
1632+
path_space.len = start_index + (normalizePath(u16, path_space.data[start_index..path_space.len]) catch |err| switch (err) {
1633+
error.TooManyParentDirs => return error.BadPathName,
1634+
});
15681635
path_space.data[path_space.len] = 0;
15691636
return path_space;
15701637
}
@@ -1637,3 +1704,9 @@ pub fn unexpectedStatus(status: NTSTATUS) std.os.UnexpectedError {
16371704
}
16381705
return error.Unexpected;
16391706
}
1707+
1708+
test "" {
1709+
if (builtin.os.tag == .windows) {
1710+
_ = @import("windows/test.zig");
1711+
}
1712+
}

lib/std/os/windows/test.zig

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
// SPDX-License-Identifier: MIT
2+
// Copyright (c) 2015-2020 Zig Contributors
3+
// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4+
// The MIT license requires this copyright notice to be included in all copies
5+
// and substantial portions of the software.
6+
const std = @import("../../std.zig");
7+
const builtin = @import("builtin");
8+
const windows = std.os.windows;
9+
const mem = std.mem;
10+
const testing = std.testing;
11+
const expect = testing.expect;
12+
13+
fn testRemoveDotDirs(str: []const u8, expected: []const u8) !void {
14+
const mutable = try testing.allocator.dupe(u8, str);
15+
defer testing.allocator.free(mutable);
16+
const actual = mutable[0..try windows.removeDotDirsSanitized(u8, mutable)];
17+
testing.expect(mem.eql(u8, actual, expected));
18+
}
19+
fn testRemoveDotDirsError(err: anyerror, str: []const u8) !void {
20+
const mutable = try testing.allocator.dupe(u8, str);
21+
defer testing.allocator.free(mutable);
22+
testing.expectError(err, windows.removeDotDirsSanitized(u8, mutable));
23+
}
24+
test "removeDotDirs" {
25+
try testRemoveDotDirs("", "");
26+
try testRemoveDotDirs(".", "");
27+
try testRemoveDotDirs(".\\", "");
28+
try testRemoveDotDirs(".\\.", "");
29+
try testRemoveDotDirs(".\\.\\", "");
30+
try testRemoveDotDirs(".\\.\\.", "");
31+
32+
try testRemoveDotDirs("a", "a");
33+
try testRemoveDotDirs("a\\", "a\\");
34+
try testRemoveDotDirs("a\\b", "a\\b");
35+
try testRemoveDotDirs("a\\.", "a\\");
36+
try testRemoveDotDirs("a\\b\\.", "a\\b\\");
37+
try testRemoveDotDirs("a\\.\\b", "a\\b");
38+
39+
try testRemoveDotDirs(".a", ".a");
40+
try testRemoveDotDirs(".a\\", ".a\\");
41+
try testRemoveDotDirs(".a\\.b", ".a\\.b");
42+
try testRemoveDotDirs(".a\\.", ".a\\");
43+
try testRemoveDotDirs(".a\\.\\.", ".a\\");
44+
try testRemoveDotDirs(".a\\.\\.\\.b", ".a\\.b");
45+
try testRemoveDotDirs(".a\\.\\.\\.b\\", ".a\\.b\\");
46+
47+
try testRemoveDotDirsError(error.TooManyParentDirs, "..");
48+
try testRemoveDotDirsError(error.TooManyParentDirs, "..\\");
49+
try testRemoveDotDirsError(error.TooManyParentDirs, ".\\..\\");
50+
try testRemoveDotDirsError(error.TooManyParentDirs, ".\\.\\..\\");
51+
52+
try testRemoveDotDirs("a\\..", "");
53+
try testRemoveDotDirs("a\\..\\", "");
54+
try testRemoveDotDirs("a\\..\\.", "");
55+
try testRemoveDotDirs("a\\..\\.\\", "");
56+
try testRemoveDotDirs("a\\..\\.\\.", "");
57+
try testRemoveDotDirsError(error.TooManyParentDirs, "a\\..\\.\\.\\..");
58+
59+
try testRemoveDotDirs("a\\..\\.\\.\\b", "b");
60+
try testRemoveDotDirs("a\\..\\.\\.\\b\\", "b\\");
61+
try testRemoveDotDirs("a\\..\\.\\.\\b\\.", "b\\");
62+
try testRemoveDotDirs("a\\..\\.\\.\\b\\.\\", "b\\");
63+
try testRemoveDotDirs("a\\..\\.\\.\\b\\.\\..", "");
64+
try testRemoveDotDirs("a\\..\\.\\.\\b\\.\\..\\", "");
65+
try testRemoveDotDirs("a\\..\\.\\.\\b\\.\\..\\.", "");
66+
try testRemoveDotDirsError(error.TooManyParentDirs, "a\\..\\.\\.\\b\\.\\..\\.\\..");
67+
68+
try testRemoveDotDirs("a\\b\\..\\", "a\\");
69+
try testRemoveDotDirs("a\\b\\..\\c", "a\\c");
70+
}

0 commit comments

Comments
 (0)