Skip to content

Fix Windows path handling for non-CWD directory handles - #198

Merged
lalinsky merged 4 commits into
mainfrom
fix-windows-relative-paths
Jan 14, 2026
Merged

lalinsky merged 4 commits into
mainfrom
fix-windows-relative-paths

Conversation

@lalinsky

@lalinsky lalinsky commented Jan 13, 2026 •

Copy link
Copy Markdown
Owner

Summary

  • Fixes path resolution for Windows directory handles that aren't the CWD
  • The previous implementation incorrectly used relative paths with kernel32 APIs which don't support RootDirectory
  • Now properly resolves paths using GetFinalPathNameByHandleW when needed

Changes

  • Added FDCWD sentinel constant for Windows (like POSIX AT_FDCWD)
  • Added pathToWide() function that resolves paths relative to directory handles
  • Uses kernel32 MultiByteToWideChar for UTF-8 to UTF-16 conversion
  • Updated all affected functions: openat, dirOpen, createat, renameat, dirDeleteFile, dirDeleteDir, mkdirat, fstatat, dirAccess, dirRealPathFile

Test plan

  • Compiles for Windows target with Zig 0.15
  • Test with Wine on CI

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
@coderabbitai

coderabbitai Bot commented Jan 13, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Windows filesystem path handling was centralized: a new pathToWide API produces allocator-managed wide (WCHAR) paths used across Windows file and directory operations. FDCWD replaces the previous peb-based CWD handle. Numerous Windows-specific error and buffer handling branches were updated to use the new wide-path flow; public signatures remain unchanged.

Changes

Cohort / File(s) Summary
Windows path conversion infrastructure
src/os/windows.zig
Added FDCWD, CP_UTF8, INVALID_FILE_ATTRIBUTES; externs MultiByteToWideChar, GetFileAttributesW; new PathToWideError; implemented pathToWide(allocator, dir, path) and utf8ToWide to produce allocator-managed WCHAR buffers.
Filesystem operations refactor (Windows branches)
src/os/fs.zig
Replaced prior UTF-16 prefixing/span usage with pathToWide across open/openat/createat/dirOpen/renameat/dirDeleteFile/dirDeleteDir/mkdirat/fstatat/dirRealPathFileWindows and other Windows paths; switched cwd() to return FDCWD; updated Windows API calls to use path_w.ptr and added deferred frees.
Removed legacy NT exports & simplifications
src/os/windows.zig
Removed exported NT-specific types/constants (FILE_BASIC_INFORMATION, UNICODE_STRING, OBJECT_ATTRIBUTES) and simplified RootDirectory/NT-name handling in favor of pathToWide-driven resolution.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Poem

Wide paths hum in allocator light,
CWD set true, no peb in sight.
UTF‑8 stretches to WCHAR dawn,
Errors map, buffers freed anon.
Windows files march on. 🪟

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the main change: fixing Windows path handling for non-CWD directory handles, which is the core focus of the PR.
Description check ✅ Passed The description directly addresses the changeset by explaining the root cause, the solution (GetFinalPathNameByHandleW), and listing all updated functions with specific technical details.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix-windows-relative-paths


📜 Recent review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d10cb4c and 67dc7ba.

📒 Files selected for processing (1)
  • src/os/windows.zig
🧰 Additional context used
🧠 Learnings (3)
📚 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/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/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/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, ReleaseSafe, ubuntu-latest, x86_64-freebsd, freebsd)
  • GitHub Check: test (0.15.2, Debug, ubuntu-latest, x86_64-netbsd, netbsd)
  • GitHub Check: test (0.15.2, Debug, windows-latest, native)
  • GitHub Check: test (0.15.2, ReleaseSafe, ubuntu-latest, x86_64-netbsd, netbsd)
  • GitHub Check: test (windows-latest)
🔇 Additional comments (5)
src/os/windows.zig (5)

32-35: LGTM - Clean sentinel definition.

The -100 value mirrors POSIX AT_FDCWD semantics. Doc comment clearly warns it's not a real handle.


138-142: LGTM - Standard Win32 export.

Correct signature and constant value for file attribute queries.


333-343: LGTM - Correct Win32 codepage API binding.

CP_UTF8 value and MultiByteToWideChar signature match the Windows SDK.


785-837: LGTM - Past review concerns addressed.

The absolute path check via PathIsRelativeW on line 790 fixes the path-joining issue with absolute inputs. Error handling now properly consults GetLastError() instead of blindly returning NameTooLong.

Memory ownership is correct: path_wide is either returned directly (caller owns) or freed via defer when building the joined path. The defensive check on line 819-820 for buffer size changing between calls is a reasonable safeguard against TOCTOU edge cases.


841-881: LGTM - Error handling properly implemented.

Past review concern about MultiByteToWideChar error mapping is addressed - now checks GetLastError() and distinguishes between buffer issues and other failures.

Good catch on line 873 freeing the allocation before returning an error from the second conversion call.

✏️ Tip: You can disable this entire section by setting review_details to false in your review settings.


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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (2)
src/os/windows.zig (1)

836-869: Error discrimination could be better.

MultiByteToWideChar returns 0 for various reasons: invalid UTF-8 sequences, insufficient buffer (shouldn't happen in second call), etc. Mapping all failures to NameTooLong is misleading. Consider calling GetLastError() to distinguish ERROR_INSUFFICIENT_BUFFER from ERROR_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 pathToWide with FDCWD returns a relative path (just UTF-16 conversion), you still need RootDirectory set to the CWD handle for NtQueryAttributesFile. And when dir != FDCWD, pathToWide returns an absolute \\?\ path, so PathIsRelativeW returns false and RootDirectory is 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

📥 Commits

Reviewing files that changed from the base of the PR and between 8869223 and 788fb66.

📒 Files selected for processing (2)
  • src/os/fs.zig
  • src/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.zig
  • src/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.zig
  • src/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.zig
  • src/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 FDCWD instead of the actual handle means pathToWide can 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.

Comment thread src/os/windows.zig Resolved
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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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:

  1. Line 2132 uses path_w directly while every other call site uses path_w.ptr. While Zig's coercion makes both work, the inconsistency is confusing for readers.

  2. 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

📥 Commits

Reviewing files that changed from the base of the PR and between 788fb66 and d10cb4c.

📒 Files selected for processing (2)
  • src/os/fs.zig
  • src/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.zig
  • src/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.zig
  • src/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.zig
  • src/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 = 0xFFFFFFFF is 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 from GetFinalPathNameByHandleW output, adds the separator, and null-terminates via allocSentinel. 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 by pathToWide.


508-543: openat Windows path handling looks correct.

The pathToWide + defer free + use .ptr pattern is properly applied. Error mapping from GetLastError covers the common cases.


569-599: dirOpen Windows implementation follows the established pattern.

Correctly uses FILE_FLAG_BACKUP_SEMANTICS for directory handles.


628-672: createat Windows implementation is consistent.

Handles exclusive, truncate, and read flags appropriately with the correct CREATE_* disposition mappings.


956-980: renameat handles both paths correctly.

Both source and destination paths are resolved via pathToWide with proper cleanup.


999-1014: dirDeleteFile, dirDeleteDir, mkdirat all follow the same clean pattern.

Consistent application of pathToWide across file operations.

Also applies to: 1030-1046, 1062-1079


1414-1441: fstatat Windows implementation correctly opens with minimal access.

Using 0 for dwDesiredAccess with FILE_FLAG_BACKUP_SEMANTICS is the right way to query attributes without needing read permission.


2459-2484: dirRealPathFileWindows follows the pattern correctly.

Uses .ptr consistently and properly delegates to dirRealPathWindows for the actual path resolution.

Comment thread src/os/windows.zig Resolved
Comment thread src/os/windows.zig Resolved
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.
@lalinsky
lalinsky merged commit 7050ec1 into main Jan 14, 2026
@lalinsky
lalinsky deleted the fix-windows-relative-paths branch January 14, 2026 17:02
@coderabbitai coderabbitai Bot mentioned this pull request May 11, 2026
1 task done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant