Repository navigation
Fix Windows path handling for non-CWD directory handles - #198
Conversation
The previous implementation used std.os.windows.sliceToPrefixedFileW which returns relative paths for simple cases, expecting NtCreateFile's RootDirectory to resolve them. However, the code was using kernel32 APIs (CreateFileW, etc.) which don't support RootDirectory, so relative paths were resolved against CWD instead of the provided directory handle. This change: - Adds FDCWD sentinel constant for Windows (like POSIX AT_FDCWD) - Introduces pathToWide() that properly resolves paths relative to dir handles using GetFinalPathNameByHandleW - Updates all affected functions to use the new path resolution - Uses kernel32 MultiByteToWideChar for UTF-8 to UTF-16 conversion
📝 WalkthroughWalkthroughWindows filesystem path handling was centralized: a new Changes
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 3✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing touches🧪 Generate unit tests (beta)
📜 Recent review detailsConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro 📒 Files selected for processing (1)
🧰 Additional context used🧠 Learnings (3)📚 Learning: 2026-01-07T13:15:48.677ZApplied to files:
📚 Learning: 2026-01-10T13:55:00.163ZApplied to files:
📚 Learning: 2026-01-10T14:08:37.019ZApplied to files:
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
🔇 Additional comments (5)
✏️ Tip: You can disable this entire section by setting Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (2)
src/os/windows.zig (1)
836-869: Error discrimination could be better.
MultiByteToWideCharreturns 0 for various reasons: invalid UTF-8 sequences, insufficient buffer (shouldn't happen in second call), etc. Mapping all failures toNameTooLongis misleading. Consider callingGetLastError()to distinguishERROR_INSUFFICIENT_BUFFERfromERROR_NO_UNICODE_TRANSLATION(invalid UTF-8).That said, if the error set is intentionally minimal for simplicity, this works.
src/os/fs.zig (1)
2122-2156: The NtQueryAttributesFile call still relies on peb() for non-absolute paths.This is actually correct: since
pathToWidewithFDCWDreturns a relative path (just UTF-16 conversion), you still needRootDirectoryset to the CWD handle forNtQueryAttributesFile. And whendir != FDCWD,pathToWidereturns an absolute\\?\path, soPathIsRelativeWreturns false andRootDirectoryis null.The logic holds, but it's subtle. A brief comment explaining this would help future readers.
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
src/os/fs.zigsrc/os/windows.zig
🧰 Additional context used
🧠 Learnings (4)
📓 Common learnings
Learnt from: lalinsky
Repo: lalinsky/zio PR: 179
File: src/os/windows.zig:424-424
Timestamp: 2026-01-07T13:15:48.677Z
Learning: In `src/os/windows.zig`, WSABUF must be re-exported from `std.os.windows.ws2_32.WSABUF` rather than defined locally because it needs to satisfy `std.Io.Reader` compatibility requirements.
📚 Learning: 2026-01-07T13:15:48.677Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 179
File: src/os/windows.zig:424-424
Timestamp: 2026-01-07T13:15:48.677Z
Learning: In `src/os/windows.zig`, WSABUF must be re-exported from `std.os.windows.ws2_32.WSABUF` rather than defined locally because it needs to satisfy `std.Io.Reader` compatibility requirements.
Applied to files:
src/os/fs.zigsrc/os/windows.zig
📚 Learning: 2026-01-10T13:55:00.163Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 184
File: src/runtime/blocking_task.zig:117-146
Timestamp: 2026-01-10T13:55:00.163Z
Learning: In Zig files, do not reference libxev for async I/O. The project uses a custom event loop implementation under src/ev/ and a callback-based async I/O loop similar to libuv/libxev. Reviewers should ensure code relies on the src/ev event loop and that there are no libxev usage patterns; prefer the central event loop in src/ev/ for all asynchronous operations.
Applied to files:
src/os/fs.zigsrc/os/windows.zig
📚 Learning: 2026-01-10T14:08:37.019Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 184
File: src/stdio.zig:117-129
Timestamp: 2026-01-10T14:08:37.019Z
Learning: In Zig files implementing swap-like semantics (e.g., old = swap(new); defer swap(old)), ensure the return value is an opaque restoration token rather than a direct reflection of internal state. Rely on the contract to perform increment/decrement logic internally (e.g., shield_count) and not expose internal state through the token. This makes behavior predictable, supports refactoring, and avoids leaking internal state across calls. Apply this pattern broadly to Zig code that uses a paired-swap or restoration-token mechanism.
Applied to files:
src/os/fs.zigsrc/os/windows.zig
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (5)
- GitHub Check: test (0.15.2, Debug, windows-latest, native)
- GitHub Check: test (0.15.2, ReleaseSafe, windows-latest, native)
- GitHub Check: test (0.15.2, ReleaseSafe, ubuntu-latest, x86_64-netbsd, netbsd)
- GitHub Check: test (0.15.2, Debug, ubuntu-latest, x86_64-netbsd, netbsd)
- GitHub Check: test (windows-latest)
🔇 Additional comments (12)
src/os/windows.zig (2)
35-38: LGTM on the FDCWD sentinel.Using -100 mirrors POSIX AT_FDCWD and won't collide with valid Windows handles. Clean approach.
336-346: LGTM on the MultiByteToWideChar declaration.Standard kernel32 import, signature looks correct.
src/os/fs.zig (10)
15-21: LGTM on the cwd() change.Returning the sentinel
FDCWDinstead of the actual handle meanspathToWidecan detect it and do the right thing. Nice.
508-544: LGTM on openat Windows path handling.Clean pattern: allocate with
pathToWide, defer free, use.ptr. Error handling looks complete.
569-599: LGTM on dirOpen Windows path handling.Same solid pattern as openat.
628-672: LGTM on createat Windows path handling.Consistent with the other functions.
956-981: LGTM on renameat Windows path handling.Both source and destination paths handled correctly with separate allocations and defers.
999-1027: LGTM on dirDeleteFile Windows path handling.Same pattern, works as expected.
1030-1059: LGTM on dirDeleteDir Windows path handling.Consistent.
1062-1092: LGTM on mkdirat Windows path handling.No issues.
1414-1441: LGTM on fstatat Windows path handling.Clean implementation.
2473-2498: LGTM on dirRealPathFileWindows.Consistent with the rest.
Use PathIsRelativeW to detect absolute paths and return them directly without joining with the directory handle path.
…indows Simplifies the access check by using the kernel32 API instead of ntdll, consistent with other file operations in the codebase.
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Fix all issues with AI agents
In @src/os/windows.zig:
- Around line 838-849: The code incorrectly maps any MultiByteToWideChar failure
to error.NameTooLong; instead when MultiByteToWideChar returns 0 detect the
failure by calling GetLastError() and return a more accurate error (e.g., a new
error like error.InvalidEncoding or propagate the Windows error) rather than
NameTooLong; also apply the same GetLastError-based handling for the subsequent
MultiByteToWideChar call that performs the conversion so invalid UTF-8 or flag
errors are reported correctly; update references to MultiByteToWideChar failures
and replace the NameTooLong return with logic that inspects GetLastError() and
maps it to the appropriate Zig error value.
🧹 Nitpick comments (1)
src/os/fs.zig (1)
2126-2134: Inconsistent pointer usage and questionable special-casing.Two things here:
Line 2132 uses
path_wdirectly while every other call site usespath_w.ptr. While Zig's coercion makes both work, the inconsistency is confusing for readers.The early returns for "." and ".." (lines 2126-2127) bypass all validation. Is this intentional? If the directory handle is invalid, this would still return success. If this is a workaround for something, a comment explaining why would help.
Fix for consistency
- if (w.GetFileAttributesW(path_w) != w.INVALID_FILE_ATTRIBUTES) { + if (w.GetFileAttributesW(path_w.ptr) != w.INVALID_FILE_ATTRIBUTES) { return; }
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
src/os/fs.zigsrc/os/windows.zig
🧰 Additional context used
🧠 Learnings (4)
📓 Common learnings
Learnt from: lalinsky
Repo: lalinsky/zio PR: 179
File: src/os/windows.zig:424-424
Timestamp: 2026-01-07T13:15:48.677Z
Learning: In `src/os/windows.zig`, WSABUF must be re-exported from `std.os.windows.ws2_32.WSABUF` rather than defined locally because it needs to satisfy `std.Io.Reader` compatibility requirements.
Learnt from: CR
Repo: lalinsky/zio PR: 0
File: CLAUDE.md:0-0
Timestamp: 2026-01-08T21:08:29.443Z
Learning: Use `zig env` to get the path to the Zig standard library when needed for reference checks
📚 Learning: 2026-01-07T13:15:48.677Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 179
File: src/os/windows.zig:424-424
Timestamp: 2026-01-07T13:15:48.677Z
Learning: In `src/os/windows.zig`, WSABUF must be re-exported from `std.os.windows.ws2_32.WSABUF` rather than defined locally because it needs to satisfy `std.Io.Reader` compatibility requirements.
Applied to files:
src/os/fs.zigsrc/os/windows.zig
📚 Learning: 2026-01-10T13:55:00.163Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 184
File: src/runtime/blocking_task.zig:117-146
Timestamp: 2026-01-10T13:55:00.163Z
Learning: In Zig files, do not reference libxev for async I/O. The project uses a custom event loop implementation under src/ev/ and a callback-based async I/O loop similar to libuv/libxev. Reviewers should ensure code relies on the src/ev event loop and that there are no libxev usage patterns; prefer the central event loop in src/ev/ for all asynchronous operations.
Applied to files:
src/os/fs.zigsrc/os/windows.zig
📚 Learning: 2026-01-10T14:08:37.019Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 184
File: src/stdio.zig:117-129
Timestamp: 2026-01-10T14:08:37.019Z
Learning: In Zig files implementing swap-like semantics (e.g., old = swap(new); defer swap(old)), ensure the return value is an opaque restoration token rather than a direct reflection of internal state. Rely on the contract to perform increment/decrement logic internally (e.g., shield_count) and not expose internal state through the token. This makes behavior predictable, supports refactoring, and avoids leaking internal state across calls. Apply this pattern broadly to Zig code that uses a paired-swap or restoration-token mechanism.
Applied to files:
src/os/fs.zigsrc/os/windows.zig
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
- GitHub Check: test (0.15.2, ReleaseSafe, windows-latest, native)
- GitHub Check: test (0.15.2, Debug, ubuntu-latest, x86_64-netbsd, netbsd)
- GitHub Check: test (0.15.2, ReleaseSafe, ubuntu-latest, x86_64-netbsd, netbsd)
- GitHub Check: test (0.15.2, ReleaseSafe, macos-15-intel, native)
- GitHub Check: test (0.15.2, Debug, windows-latest, native)
- GitHub Check: test (windows-latest)
🔇 Additional comments (12)
src/os/windows.zig (4)
32-35: FDCWD sentinel looks correct.Using -100 matches the POSIX AT_FDCWD convention. The bit manipulation to create the pointer handle is appropriate for a sentinel value that will be explicitly checked before use.
138-142: GetFileAttributesW declaration is correct.The extern signature matches kernel32 and
INVALID_FILE_ATTRIBUTES = 0xFFFFFFFFis the documented return value for failure.
333-343: MultiByteToWideChar declaration looks good.CP_UTF8 = 65001 and the function signature are correct per Windows documentation.
819-829: Path joining logic is solid.The join operation correctly handles the
\\?\prefix fromGetFinalPathNameByHandleWoutput, adds the separator, and null-terminates viaallocSentinel. Memory ownership is clear with the caller responsible for freeing.src/os/fs.zig (8)
15-21: cwd() returning FDCWD sentinel is the right approach.This gives Windows the same semantics as POSIX
AT_FDCWD- kernel32 APIs will resolve relative paths against CWD when this sentinel is detected bypathToWide.
508-543: openat Windows path handling looks correct.The
pathToWide+defer free+ use.ptrpattern is properly applied. Error mapping fromGetLastErrorcovers the common cases.
569-599: dirOpen Windows implementation follows the established pattern.Correctly uses
FILE_FLAG_BACKUP_SEMANTICSfor directory handles.
628-672: createat Windows implementation is consistent.Handles
exclusive,truncate, andreadflags appropriately with the correctCREATE_*disposition mappings.
956-980: renameat handles both paths correctly.Both source and destination paths are resolved via
pathToWidewith proper cleanup.
999-1014: dirDeleteFile, dirDeleteDir, mkdirat all follow the same clean pattern.Consistent application of
pathToWideacross file operations.Also applies to: 1030-1046, 1062-1079
1414-1441: fstatat Windows implementation correctly opens with minimal access.Using
0fordwDesiredAccesswithFILE_FLAG_BACKUP_SEMANTICSis the right way to query attributes without needing read permission.
2459-2484: dirRealPathFileWindows follows the pattern correctly.Uses
.ptrconsistently and properly delegates todirRealPathWindowsfor the actual path resolution.
GetFinalPathNameByHandleW returning 0 indicates failure, not that the name is too long. Check GetLastError() to map the actual error. Similarly, MultiByteToWideChar can fail for various reasons (invalid UTF-8, etc.), not just buffer size issues.
Summary
RootDirectoryGetFinalPathNameByHandleWwhen neededChanges
FDCWDsentinel constant for Windows (like POSIXAT_FDCWD)pathToWide()function that resolves paths relative to directory handlesMultiByteToWideCharfor UTF-8 to UTF-16 conversionopenat,dirOpen,createat,renameat,dirDeleteFile,dirDeleteDir,mkdirat,fstatat,dirAccess,dirRealPathFileTest plan