Skip to content

re-implement Windows ReadDir on top of GetFileInformationByHandleEx - #164529

Open
RalfJung wants to merge 2 commits into
rust-lang:mainfrom
RalfJung:windows-read-dir
Open

RalfJung wants to merge 2 commits into
rust-lang:mainfrom
RalfJung:windows-read-dir

Conversation

@RalfJung

@RalfJung RalfJung commented Oct 18, 2026 •

Copy link
Copy Markdown
Member

View all comments

The current implementation based on FindFirstFileExW fundamentally relies on knowing the path to the directory, so implementing Dir::read_dir (iterating a directory based on a Dir handle) is not possible. remove_dir_all already uses a completely different implementation based on GetFileInformationByHandleEx that can work with a directory handle. This PR adjusts fs::read_dir to also use an implementation based on GetFileInformationByHandleEx.

The directory entry buffer is currently 1 KiB large, as that's what we are using for remove_dir_all. That is fairly small; it means we have to do a new syscall around every 9 entries. For comparison, the glibc implementation uses a buffer of 32 KiB by default.

try-job: test-x86_64-msvc*

@rustbot rustbot added O-windows Operating system: Windows S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. T-libs Relevant to the library team, which will review and decide on the PR/issue. labels Oct 18, 2026
Comment on lines 1064 to 1065
impl From<c::WIN32_FIND_DATAW> for FileAttr {
fn from(wfd: c::WIN32_FIND_DATAW) -> Self {

@RalfJung RalfJung Oct 18, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

FWIW this conversion from WIN32_FIND_DATAW is still used by fs::metadata. File::metadata uses yet another conversion, from BY_HANDLE_FILE_INFORMATION. And DirEntry::metadata now uses FILE_ID_BOTH_DIR_INFO.

No idea if it makes sense to consolidate that, but I'd say that would be a job for a different PR.

View changes since the review

@RalfJung

Copy link
Copy Markdown
Member Author

I don't have a Windows machine so this is only build-tested so far...
@bors try

@rust-bors

This comment has been minimized.

rust-bors Bot pushed a commit that referenced this pull request Oct 18, 2026
re-implement Windows ReadDir on top of GetFileInformationByHandleEx

try-job: test-x86_64-msvc*
@rust-log-analyzer

This comment has been minimized.

@rust-bors

This comment was marked as resolved.

@RalfJung

Copy link
Copy Markdown
Member Author

@bors try

@rust-bors

This comment has been minimized.

rust-bors Bot pushed a commit that referenced this pull request Oct 18, 2026
re-implement Windows ReadDir on top of GetFileInformationByHandleEx

try-job: test-x86_64-msvc*
@rust-bors

rust-bors Bot commented Oct 18, 2026

Copy link
Copy Markdown
Contributor

☀️ Try build successful (CI)
Build commit: c9ad66c (c9ad66c5d99336ce105e9b2591e1c8f87d9ecf22)
Base parent: 15c1044 (15c10447a46529b68e38c7f138aeb95240e4d7d6)

@RalfJung

Copy link
Copy Markdown
Member Author

@bors try

rust-bors Bot pushed a commit that referenced this pull request Oct 19, 2026
re-implement Windows ReadDir on top of GetFileInformationByHandleEx

try-job: test-x86_64-msvc*
@rust-bors

This comment has been minimized.

// `read_dir` on a non-directory should fail, but Windows `Dir::open` suceeds.
// So we have to specifically check for this.
return Err(io::const_error!(io::ErrorKind::NotADirectory, "path is not a directory"));
}

@RalfJung RalfJung Oct 19, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Would it maybe be better to call buf.fill() already here? Would that "naturall" throw an error for non-directories, or would we still need a dedicated check then?
Currently we delay that until the first next() call. That matches what glibc does.

View changes since the review

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I think what you currently have is fine for now. Ideally we would be using Dir to limit it to opening a directory but, as I said, I'm uncomfortable tying this to a new unstable feature.

@RalfJung RalfJung Oct 20, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

I think Dir::open (open dir with just a path) will happily open files on Windows, so using Dir would not help.

Dir::open_dir (open dir relative to Dir handle) ensures that it has a directory, but that requires us to already have a Dir to begin with.

(Yeah I find that naming quite confusing... but it's what got approved in the ACP so I guess other people like it.)

@RalfJung
RalfJung marked this pull request as ready for review October 19, 2026 06:09
@rustbot rustbot added the S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. label Oct 19, 2026
@rustbot rustbot removed the S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. label Oct 19, 2026
@rustbot

rustbot commented Oct 19, 2026

Copy link
Copy Markdown
Collaborator

r? @Mark-Simulacrum

rustbot has assigned @Mark-Simulacrum.
They will have a look at your PR within the next two weeks and either review your PR or reassign to another reviewer.

Use r? to explicitly pick a reviewer

Why was this reviewer chosen?

The reviewer was selected based on:

  • Owners of files modified in this PR: @ChrisDenton, libs
  • @ChrisDenton, libs expanded to 13 candidates
  • Random selection from JohnTitor, Mark-Simulacrum

@RalfJung

Copy link
Copy Markdown
Member Author

r? @ChrisDenton

@rustbot

rustbot commented Oct 19, 2026

Copy link
Copy Markdown
Collaborator

ChrisDenton is currently at their maximum review capacity.
They may take a while to respond.

@rust-log-analyzer

This comment has been minimized.

@rust-bors

rust-bors Bot commented Oct 19, 2026

Copy link
Copy Markdown
Contributor

☀️ Try build successful (CI)
Build commit: 60c0f2e (60c0f2e84cba1dcbd8c1f6b32d9cfae5fc6af11b)
Base parent: b6eeb93 (b6eeb93c992027a03e1fd120b6652546396b142c)

@ChrisDenton

Copy link
Copy Markdown
Member

While I think this is the right long-term direction I admit I am concerned about re-implementing an important and long-stable function on top of an experimental and only partially implemented new feature. This would make std::fs::read_dir sensitive to any changes or problems with Dir.

@RalfJung

Copy link
Copy Markdown
Member Author

Note that the only thing we do with Dir is Dir::open, which is a fairly "traditional" method (it uses CreateFileW, not NtCreateFile). I can inline that CreateFileW call if you prefer.

This is on the critical path for rust-lang/miri#4982 so I'd like to find some way to make progress here. Happy to take suggestions for the best way to do that.

@RalfJung

Copy link
Copy Markdown
Member Author

Also, CreateFileW + GetFileInformationByHandleEx has been used in remove_dir_all on Windows for a long time now. So I'd say that combination is pretty battle-tested at this point.

Rather than using Dir::open I can also use File::open to get the handle. That's what remove_dir_all does. It just seemed kind of hacky.

@RalfJung

Copy link
Copy Markdown
Member Author

I have reused the code from remove_dir_all now for opening the directory, so this no longer has any interaction with fs::Dir.

@bors try

@rust-bors

This comment has been minimized.

rust-bors Bot pushed a commit that referenced this pull request Oct 20, 2026
re-implement Windows ReadDir on top of GetFileInformationByHandleEx

try-job: test-x86_64-msvc*
@rust-bors

rust-bors Bot commented Oct 20, 2026

Copy link
Copy Markdown
Contributor

☀️ Try build successful (CI)
Build commit: 54d7313 (54d7313ab1a96805f76681b87b2d85369a5652f3)
Base parent: 39b126b (39b126b8e227197c688fed9f9962658bdd89a761)

Comment thread library/std/src/fs/tests.rs Resolved
Comment thread library/std/src/sys/fs/windows.rs Resolved
@RalfJung
RalfJung force-pushed the windows-read-dir branch 3 times, most recently from 97c18f3 to 9de1464 Compare October 21, 2026 10:23
@rustbot

This comment has been minimized.

@RalfJung

Copy link
Copy Markdown
Member Author

@bors try

rust-bors Bot pushed a commit that referenced this pull request Oct 21, 2026
re-implement Windows ReadDir on top of GetFileInformationByHandleEx

try-job: test-x86_64-msvc*
@rust-bors

This comment has been minimized.

options.read(true);
// FIXME: use race-free handle-based approach instead.
Dir::open(&self.root, &options)
dir_handle.open_dir(Path::new(""), &options)

@RalfJung RalfJung Oct 21, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Now that we have an underlying handle, we can also implement this method properly. :)

(This is only used by the unstable ReadDir::dir.)

View changes since the review

@rust-bors

rust-bors Bot commented Oct 21, 2026

Copy link
Copy Markdown
Contributor

☀️ Try build successful (CI)
Build commit: 7369f4e (7369f4e2cf33f04741ad8ca17a291ead9e7b1bba)
Base parent: 1731fae (1731faea0da5b4ebf881d8e53f98066c17a74711)

@rust-bors

This comment has been minimized.

@rustbot

rustbot commented Oct 23, 2026

Copy link
Copy Markdown
Collaborator

This PR was rebased onto a different main commit. Here's a range-diff highlighting what actually changed.

Rebasing is a normal part of keeping PRs up to date, so no action is needed—this note is just to help reviewers.

@RalfJung

RalfJung commented Nov 15, 2026 •

Copy link
Copy Markdown
Member Author

@ChrisDenton I have removed all uses of fs::Dir from stable code.

I agree this is still a big change. OTOH, if my understanding is correct, it is a change that we have to do at some point if we ever want to have Dir::read_dir on Windows. (Well, we could have entirely separate read-dir logic for fs::read_dir vs `Dir::read_dir. But that does not sound great to me.) Is there any benefit to waiting? At some point we're going to have to take the risk and see what happens. If there are problems, we'll revert.

If you think there is a way we can avoid this change, or a better way to stage it, I am all ears.

@mehmettoplu-rs

Copy link
Copy Markdown
Contributor

I tested this PR on a real Windows machine (Windows 11 25H2, build 26200.9711): I built dd36e1b and its merge-base 0cefa27 with the same config and compared the output of a small test program on both.

  • Correctness: 32 of 35 cases give identical output (names, file types, metadata, errors) on NTFS. \\wsl$, a subst drive and a UNC path are identical too, and on FAT32 and exFAT the only differences are the same error code change as below. This includes a directory of 1000 files with 255-character names, where the 1 KiB buffer holds one entry per call and is refilled for every entry. No crashes or hangs.
  • Concurrent changes: while another thread created, renamed and deleted files in the directory being read, no entry was lost, duplicated or corrupted.
  • Behavior change: the remaining 3 cases show one difference. When the last path component does not exist (or is a broken symlink/junction), read_dir now returns OS error 2 (ERROR_FILE_NOT_FOUND) instead of 3 (ERROR_PATH_NOT_FOUND). kind() is still NotFound, and the new code is consistent with fs::metadata and fs::canonicalize on the same paths, but the message users see changes from "The system cannot find the path specified" to "The system cannot find the file specified".
  • Performance: with the 1 KiB buffer, large directories are 2-3x slower than before (100k files: 2.3x, WinSxS: 3.3x). With a 4 KiB buffer the speed matches the old implementation everywhere except WinSxS, and 16 KiB was the fastest in most cases (0.85-1.00x of the old time outside WinSxS). WinSxS stays somewhat slower even with 16 KiB (about 1.2x). I don't know the exact reason; one possible cause is that FileIdBothDirectoryInfo also returns 8.3 short names, which the old FindFirstFileExW(FindExInfoBasic) call did not query.

Test programs, scripts and the exact commands: https://gist.github.com/mehmettoplu-rs/0695b793986404e20dfdd71c0d222408

I used an LLM (Claude) to help write the test programs and scripts and to run them. I decided what to test and reviewed the code, the results and the conclusions myself.

If the PR changes (for example the buffer size), I can run these tests again.

Environment and method
  • Windows 11 Pro 25H2, build 26200.9711. AMD Ryzen 5 3600X, 8 GB RAM, NVMe SSD (NTFS). A USB stick formatted as FAT32 and as exFAT. WSL 2 (Ubuntu). Developer Mode on (needed for symlinks). The test directories were excluded from Defender.
  • All toolchains are x86_64-pc-windows-msvc, built locally with the library profile:
    • base: 0cefa27fe3d (merge-base)
    • PR: dd36e1badff
    • for the buffer comparison only: dd36e1badff with DirBuff::BUFFER_SIZE set to 4, 16 and 64 KiB
    • as a sanity check, nightly 5f4effd57 (2026-11-13) gave the same output as base in all 35 cases.
  • ./x test library/std --no-doc on the PR: 946 passed, 0 failed.
  • The test program reads a directory with read_dir and prints one sorted line per entry: name, path(), file_type() (including is_symlink_dir/is_symlink_file), len, attributes, readonly, creation and last write time, and the windows_by_handle fields. It also compares DirEntry::metadata() with fs::symlink_metadata(entry.path()). Errors are printed as kind() and raw_os_error(), and it records whether the error came from read_dir itself or from the first next(). The windows_by_handle fields are None with both implementations.
  • Test directory, created by a script: normal/empty/10 MiB files, read-only/hidden/system attributes, file and directory symlinks, a junction, broken links, a hard link, a 5 GiB sparse file, names with Turkish letters, emoji, CJK, 255 characters, a trailing dot or space and a lone surrogate, a case-sensitive directory, 1000 short and 1000 long names, a path longer than 260 characters, and symlinks created from inside WSL. Also C:\, System32, WinSxS, WindowsApps, \\wsl$\Ubuntu\etc and \\wsl$\Ubuntu\usr\bin.
  • Each case was run as base, then PR, then base again. If the two base runs differed, the case was marked unstable instead of counted as a difference: NTFS can refresh stale metadata in the directory index between two runs. After a warm-up round, the final round had 35 cases and 0 unstable. Last access times were not compared.
  • Differences between DirEntry::metadata() and symlink_metadata() (directory sizes, stale index data for hard-linked files in WinSxS) appear identically with base and PR.
  • Concurrency: one thread creates, renames and deletes up to 200 files while another thread repeatedly reads the directory, which also has 1000 files that are never touched, and the test checks that each of those appears exactly once per pass. 3 runs of 10 s each with base, PR and PR with 16 KiB, about 28 million entries in total: no violations, no errors. Calling remove_dir_all on the directory while a ReadDir is open succeeds with all three; the iterator then returns the entries it has already buffered and ends without an error.
  • Performance: hyperfine 2.0, test program in a mode that only iterates (no metadata calls), 5 warm-up runs, 20-50 runs, median.
Error codes

OS error codes from raw_os_error(). kind() is NotFound in every case.

Path read_dir base read_dir PR metadata / symlink_metadata / canonicalize (base and PR)
rdtest\missing\a\b\c 3 3 3
rdtest\file.txt\sub 3 3 3
rdtest\missing 3 2 2
rdtest\broken_linkdir 3 2 2
rdtest\broken_junc 3 2 2
Performance

Median time of base, and time of each variant relative to base (above 1 = slower).

Directory base PR (1 KiB) 4 KiB 16 KiB 64 KiB
100,000 short names 60.3 ms 2.29x 1.02x 0.89x 0.91x
C:\Windows\WinSxS (28,282 entries) 52.5 ms 3.33x 1.66x 1.18x 1.54x
C:\Windows\System32 (5,092 entries) 11.8 ms 1.43x 1.00x 0.94x 0.86x
1000 short names 7.9 ms 1.07x 0.98x 1.00x 0.98x
1000 names of 255 characters 10.6 ms 1.43x 0.95x 0.85x 0.93x

I measured three rounds. The ratios varied between them (for example 16 KiB on WinSxS: 1.18x to 1.64x), but the overall pattern was the same. On WinSxS and the 100,000-file directory, 64 KiB was slower than 16 KiB in all three rounds, which I can't explain. DirBuff is also used by remove_dir_all, so changing BUFFER_SIZE affects it too.

Not tested
  • Dev Drive (ReFS)
  • mounted ISO (CDFS/UDF)
  • OneDrive placeholders
  • a real network share (only \\localhost)
  • test suites of crates such as walkdir, ignore, tempfile

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

O-windows Operating system: Windows S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. T-libs Relevant to the library team, which will review and decide on the PR/issue.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants