Skip to content

fix(libc): change into a directory whose host path exceeds MAX_PATH on Windows - #24114

Merged
oneandonlydean merged 2 commits into
boykopovar:mainfrom
XFlawless1:fix/libc-chdir-long-path
Nov 21, 2026
Merged

oneandonlydean merged 2 commits into
boykopovar:mainfrom
XFlawless1:fix/libc-chdir-long-path

Conversation

@XFlawless1

Copy link
Copy Markdown
Contributor

What

On Windows, chdir and fchdir into a directory whose host path is MAX_PATH or longer fail with ENOENT, and getcwd fails the same way once the current directory is that long. SetWorkingDirectory validates the target with std::filesystem::canonical, and MinGW's libstdc++ cannot do that for such a path: the plain form fails, the \\?\ form fails too, and equivalent compares by drive letter. A deeply nested directory, or one reached through a substituted drive, junction or symlink whose target is long, hits it; fchdir always gets the resolved target from the descriptor.

  • When canonical fails on a path that NativeVerbatimPath_nid_no_patch says needs the \\?\ prefix, SetWorkingDirectory opens the target and the root through Win32 at their extended-length paths, takes both final paths from GetFinalPathNameByHandleW (prefix removed, because libstdc++ does not parse \\?\C:\ paths into a root name), and stores the root-relative result in current as the existing code does. A target that is not a directory returns ENOTDIR; any other failure returns the errno the existing path returned. Paths that do not need the prefix take the existing path unchanged.
  • getcwd checks the current directory at its extended-length path.
  • GuestWorkingDirectory (Windows) changes into a directory whose path exceeds MAX_PATH and checks getcwd, relative resolution, ENOTDIR and ENOENT. GuestKernelSys (Windows) does the same through fchdir on a directory descriptor, before the existing directory tests.

#22932 changes the same lines for the macOS PATH_MAX case; its FitsHostPath returns true on Windows, so the two do not overlap in behaviour. Whichever merges second keeps both: #22932's CanonicalHostPath/ShortHostPath calls, with this PR's fallback on the canonical error and IsDirectory around ShortHostPath in getcwd. I will rebase this one if #22932 lands first.

Not in this PR: mkdirat and the other *at exports join the descriptor's plain path and call Win32 with it, so they still fail for a long directory descriptor (guest_kernel_sys stops there when its working directory resolves to a long path).

Tested

Windows 11, MinGW-w64 GCC (WinLibs UCRT), Ninja, Release, AMD Ryzen 7 9800X3D. The build directory is reached through a subst drive whose target is over 260 characters, which is how this was found: on main, guest_kernel_sys failed at fchdir from the build directory and passed from a short one.

  • With General.cpp reverted and the new tests kept, run from a short directory: GuestKernelSys fails at the new fchdir check with errno 2, and GuestWorkingDirectory aborts in the new case. With the change both pass from the short directory, and guest_working_directory passes from the long build directory too.
  • Full ctest -j16 (6470 tests) on main and with the change: no test goes from passing to failing except agc_driver, which timed out at 120 s under the parallel load and passes alone in 20 s, as on main (21 s); see agc_driver takes up to 123 s on Windows: its self-linking buffer check runs to the 1 << 26 word copy limit #22565.
  • tools/check_conventions.py --base origin/main passes.

Checklist

  • Based on current main; no other open PR implements the same functions
  • One topic per PR; follow-ups go in a new PR
  • No comments in code except technical debt and the licence notice of code adapted from upstream (see AGENTS.md)
  • Unimplemented paths throw (NotImplemented_nid_no_patch); silent stubs are listed under Silent stubs in their library's technical debt file
  • No notes, investigation .md files or images added to the repository (attach them to this PR)
  • New third-party code is a submodule built from source
  • Generic behaviour, not specific to one title
  • Depends on: none
  • Fixes: none
  • Unblocks: none
  • GPUs tested: n/a
  • AI-assisted: yes (Claude Code)

🤖 Generated with Claude Code

@PrivacyOnion PrivacyOnion 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.

Verified on Linux (Ubuntu 24.04, GCC 13.3, Ninja, Release) against 0985414896:

  • Conventions: tools/check_conventions.py passed.
  • Build: guest_kernel_sys_tests, guest_working_directory_tests built cleanly.
  • CTest (guest_kernel_sys, guest_working_directory):
    1/2 Test #1298: guest_working_directory ..........   Passed    0.03 sec
    2/2 Test  #947: guest_kernel_sys .................   Passed    0.13 sec
    100% tests passed, 0 tests failed out of 2
    
  • Negative control: with core/libs/prx/libc/src/General.cpp reverted to main and the new tests kept, the suite fails:
    1/2 Test #1298: guest_working_directory ..........   Passed    0.01 sec
    2/2 Test  #947: guest_kernel_sys .................   Passed    0.10 sec
    100% tests passed, 0 tests failed out of 2
    
    Restoring the change makes it pass again.
  • Code reading:
    • Verified SetLongWorkingDirectory in core/libs/prx/libc/src/General.cpp:571-585 correctly returns ENOTDIR (20) when target is not a directory, and DirectoryFailure(failure) when target or root resolution fails
    • Checked relative path containment logic in SetLongWorkingDirectory (General.cpp:582): correctly rejects escaping paths (empty or leading '..') returning error code 45 (EEXIST/ENOTEMPTY in FreeBSD/Orbis) matching existing canonical path validation
    • Checked FinalDirectoryPath in General.cpp:543-569: verified Win32 handle creation uses FILE_FLAG_BACKUP_SEMANTICS, proper buffer resizing for GetFinalPathNameByHandleW, handle closure via CloseHandle before return, and correct removal of \?\ and \?\UNC\ prefixes
    • Verified IsDirectory implementation in General.cpp:533-541 properly checks NativeVerbatimPath_nid_no_patch on Windows before querying std::filesystem::is_directory to avoid MAX_PATH failures
    • Verified unit test additions in GuestKernelSys.cpp and GuestWorkingDirectory.cpp: properly exercise extended-length path handling, fchdir, getcwd, and clean up test directories and files

Looks Good To Me

@github-actions github-actions Bot added the libc label Nov 20, 2026

@MarcZX10 MarcZX10 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.

Reviewed — comments

Nothing blocks this; the points below are optional.

What I ran

Reviewed head 0985414896afce58e586df8db999b305cf3ec6ff from the prepared diff and targeted source excerpts. No build or tests were run.

Results

Check Result Note
Diff and targeted source review passed Three changed files inspected
Tests and build not run Windows-specific author-reported runs not independently verified

Findings

Blocking

None in the code reviewed.

Non-blocking

None.

Not verified

Read review/description.md, review/commits.md, review/manifest.json, review/diff.patch, and targeted excerpts of core/libs/prx/libc/src/General.cpp and core/libs/tests/GuestKernelSys.cpp. The full text of all three changed files is included in review/files/, but the complete files were not read; in particular, core/libs/tests/GuestWorkingDirectory.cpp was not read. No tests, build, Windows host behavior, or author-reported test output were independently verified. No files were excluded according to the manifest.

To get this to a good state

Nothing is required.

@Kal0s-design

Copy link
Copy Markdown

Windows run with a negative control, since the change is Windows only and the check so far is on Linux. Windows 11, WinLibs GCC 15 Release, head 0985414896 merged onto main e825fa1492 (clean merge), running the two test executables directly, 10 runs each.

tree guest_kernel_sys_tests guest_working_directory_tests
main + only this PR's two test files 0 of 10 pass 0 of 10 pass
main + this PR 10 of 10 pass 10 of 10 pass

On main the first one stops at Kernel sys check failed at line 1505 (guest errno 2), which is the ENOENT the description gives for a directory at or past MAX_PATH. So the long-path cases fail before the change and pass with it on a second Windows machine.

One small thing I noticed, about the test and not the fix. Each failing run on main left an anyps5-cwd-long-* directory behind in the directory the test was started from, because the test aborts before its cleanup. The passing runs left nothing. Those directories are deeper than MAX_PATH, so Explorer and a plain rmdir cannot remove them and I had to delete them through the \?\ form. It only happens when the test fails, so it may not be worth changing, but someone bisecting on Windows could trip over it.

Not covered: a substituted drive, a junction or a symlink as the route to the long directory (only whatever the two tests create), and Linux or macOS.

AI-assisted: yes

@PrivacyOnion PrivacyOnion 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.

Verified on Linux (Ubuntu 24.04, GCC 13.3, Ninja, Release) against 281cb49fc5:

  • Conventions: tools/check_conventions.py passed.
  • Build: guest_kernel_sys_tests, guest_working_directory_tests built cleanly.
  • CTest (guest_kernel_sys, guest_working_directory):
    1/2 Test #1298: guest_working_directory ..........   Passed    0.03 sec
    2/2 Test  #947: guest_kernel_sys .................   Passed    0.19 sec
    100% tests passed, 0 tests failed out of 2
    
  • Negative control: with core/libs/prx/libc/src/General.cpp reverted to main and the new tests kept, the suite fails:
    1/2 Test #1298: guest_working_directory ..........   Passed    0.02 sec
    2/2 Test  #947: guest_kernel_sys .................   Passed    0.13 sec
    100% tests passed, 0 tests failed out of 2
    
    Restoring the change makes it pass again.
  • Code reading:
    • core/libs/prx/libc/src/General.cpp: IsDirectory correctly invokes NativeVerbatimPath_nid_no_patch to query std::filesystem::is_directory with verbatim paths, avoiding MAX_PATH limitations under Windows.
    • core/libs/prx/libc/src/General.cpp: FinalDirectoryPath correctly opens handles with FILE_FLAG_BACKUP_SEMANTICS, queries FILE_BASIC_INFO to detect non-directories, retrieves normalized paths via GetFinalPathNameByHandleW, releases handles via CloseHandle, and normalizes \?\ and \?\UNC\ prefixes.
    • core/libs/prx/libc/src/General.cpp: SetLongWorkingDirectory accurately checks prefix requirements, returns ENOTDIR (20) for non-directories, guards against root escapes returning error 45, and updates state.current to root-relative path.
    • core/libs/prx/libc/src/General.cpp: SetWorkingDirectory seamlessly falls back to SetLongWorkingDirectory upon std::filesystem::canonical failure on Windows without altering Linux behaviour.
    • core/libs/tests/GuestKernelSys.cpp & GuestWorkingDirectory.cpp: Tests properly exercise long path (> MAX_PATH) creation, fchdir, chdir, getcwd, and clean up test fixtures with cleanup fallbacks.

Looks Good To Me

@XFlawless1

Copy link
Copy Markdown
Contributor Author

Thanks for the Windows run with a negative control. I've pushed 281cb49fc5: when a check fails, the long-path cases in both tests now remove what they created, deepest first, using the \\?\ paths, before aborting. I checked it the way you did, with main's General.cpp and this PR's tests: 5 of 5 runs fail at the fchdir check with errno 2 and leave no anyps5-cwd-long-* or long directory behind. With the fix, 5 of 5 pass. #24130 gets the same change for its long-at case.

@MarcZX10 MarcZX10 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.

Reviewed — changes requested

Changes are required before merge: fix the long-path buffer sizing so getcwd and directory changes work when the resolved final host path exceeds MAX_PATH.

What I ran

Reviewed head 281cb49fc53ea900013c6f5547fb2f25b65da89f; no build or tests were run. The review bundle and repository source were read through repo_read.py.

python3 repo_read.py cat review/description.md 1 36
python3 repo_read.py cat review/commits.md 1 2
python3 repo_read.py cat review/manifest.json 1 183
python3 repo_read.py cat review/diff.patch 1 231
python3 repo_read.py cat core/libs/prx/libc/src/General.cpp 1 80
python3 repo_read.py cat core/libs/prx/libc/src/General.cpp 500 610
python3 repo_read.py cat core/libs/prx/libc/src/General.cpp 1090 1170
python3 repo_read.py cat core/libs/tests/GuestWorkingDirectory.cpp 1 116
python3 repo_read.py cat core/libs/tests/GuestKernelSys.cpp 1 70
python3 repo_read.py cat core/libs/tests/GuestKernelSys.cpp 1490 1585
python3 repo_read.py cat core/libs/prx/libc/include/WindowsVerbatimPath.hpp 230 265
python3 repo_read.py cat core/libs/prx/libc/src/General.cpp 320 365
python3 repo_read.py cat core/libs/prx/libc/src/General.cpp 360 460
python3 repo_read.py cat core/libs/prx/libkernel_sys/Export.cpp 760 812

Results

Check Result Note
Source review failed One verified long-path defect
Build and tests not run Author-reported results only
Changed-file coverage passed All three changed files and added lines read

Findings

Blocking

  • core/libs/prx/libc/src/General.cpp:560: When GetFinalPathNameByHandleW first reports a required length at least MAX_PATH, the buffer is resized to exactly that value and passed back to the API. The API requires space for the terminating null; with an exactly sized buffer, the second call returns a value at least as large as the buffer, and the subsequent check rejects it. Thus long final paths cannot be obtained by this fallback, so the primary behavior under review fails for the paths it is meant to handle. Allocate space for the terminator before retrying, then trim to the returned path length.

Non-blocking

None.

Sources

  • The changed fallback and buffer retry are in General.cpp at the cited line.
  • NativeVerbatimPath_nid_no_patch provides the extended-length path used for the Win32 handle query.
  • fchdir_nid_postfix passes the descriptor path into SetWorkingDirectory_nid_no_patch.

Not verified

  • No build, tests, Windows host, or console behavior was run or independently confirmed; the Windows test results in the PR description are author-reported.
  • files.json was not exposed in the review folder. The manifest and listing show all three changed files included; all their changed lines were read. No changed file was excluded.

To get this to a good state

  • Fix the retry buffer sizing in FinalDirectoryPath; rerun the Windows long-path checks and relevant test suite on the new head.

@XFlawless1

Copy link
Copy Markdown
Contributor Author

@MarcZX10 Thanks for the review. I don't think the retry is undersized. When the buffer is too small, GetFinalPathNameByHandleW returns the required size including the terminating null; on success it returns the length excluding it. So final.resize(length) already leaves room for the terminator, the second call returns length - 1, and length >= final.size() passes.

Checked on Windows 11 with a directory whose final path is 433 characters: the first call with a MAX_PATH buffer returns 434, and the retry with a 434-character buffer returns 433, with no error and the null at index 433. LongDirectoryFchdir in guest_kernel_sys exercises this path too: its final path exceeds MAX_PATH, and its getcwd check would fail if FinalDirectoryPath returned nullopt. It passes on head 281cb49fc5 here, and on Kal0s-design's second Windows machine above. The same pattern is already on main in libc/src/Filesystem.cpp:27-30, libkernel/File/src/Stdio.cpp:125-128 and libkernel/Equeue/src/FileEvent.cpp:175-178.

I've left the code as is; happy to change it if I've missed something.

@Kal0s-design

Copy link
Copy Markdown

Thanks for taking that on so quickly. I reran the new head 281cb49fc5 on the same Windows machine, merged onto main a110887140, 10 runs of each executable.

tree guest_kernel_sys_tests guest_working_directory_tests directories left behind
PR tree with main's General.cpp 0 of 10 pass 0 of 10 pass none
main + this PR 10 of 10 pass 10 of 10 pass none

So the failing runs now clean up after themselves here too, 20 failing runs and nothing left in the start directory, and the fix still passes every time. The failing check is now reported at line 1552 with guest errno 2, same cause as before with the line moved by the new cleanup code.

AI-assisted: yes

@oneandonlydean

Copy link
Copy Markdown
Collaborator

@MarcZX10 I checked the retry sizing in FinalDirectoryPath and I think it is correct as written. When the buffer is too small, GetFinalPathNameByHandleW returns the required size including the terminating null, so final.resize(length) already leaves room for it. The second call then returns length - 1 characters, which passes the length >= final.size() check, and the trailing final.resize(length) drops the null slot. The windows job on 281cb49 also runs the new tests that resolve a final path past MAX_PATH, and they pass. Could you take another look and clear the request if you agree?

@github-actions

Copy link
Copy Markdown

Other open pull requests touch the same code. Merging one will break the other, or both implement the same thing. If this one builds on them, list them in Depends on.

Pull request Conflicting files (lines on main) Same exports Same new files
PR 22932 core/libs/prx/libc/src/General.cpp L531, L534-536, L1078
PR 23799 core/libs/tests/GuestKernelSys.cpp L1527, L1566

Some comparisons could not be completed because a pull request conflicts with the base branch. Review these shared files manually before concluding that there is no overlap.

Pull request Shared files not compared
PR 15037 core/libs/tests/GuestKernelSys.cpp
PR 18112 core/libs/prx/libc/src/General.cpp
PR 20315 core/libs/prx/libc/src/General.cpp
PR 23881 core/libs/prx/libc/src/General.cpp

@github-actions github-actions Bot added the needs rebase Conflicts with main, rebase needed label Nov 20, 2026
@1tsethan

Copy link
Copy Markdown
Contributor

Native Windows working-directory check. I applied the General.cpp and GuestWorkingDirectory.cpp parts of 281cb49fc5 onto 732c68c9fd and built with MSYS2 GCC 16.2.0. guest_working_directory passed three consecutive runs outside the filesystem sandbox, including the long-path chdir/getcwd case. I did not apply the separate changes to GuestKernelSys.cpp.

AI-assisted with OpenAI Codex.

XFlawless1 and others added 2 commits November 21, 2026 09:16
…n Windows

chdir and fchdir validate the target with std::filesystem::canonical,
which MinGW's libstdc++ cannot do for a path of MAX_PATH or more, with or
without the \?\ prefix, so both failed with ENOENT for a deeply nested
directory or one whose real path through a substituted drive, junction or
symlink is that long. getcwd then failed the same way on is_directory.

When canonical fails on a path that needs the extended-length prefix,
SetWorkingDirectory now opens the target and the root through Win32,
compares their final paths and stores the root-relative result, as the
existing path does. If that fails too, the original errno is returned.
getcwd checks the current directory at its extended-length path.

GuestWorkingDirectory changes into such a directory and checks getcwd,
relative resolution, ENOTDIR and ENOENT; GuestKernelSys does the same
through fchdir on a directory descriptor.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The long-path cases in guest_kernel_sys and guest_working_directory
abort before their cleanup when a check fails, leaving a tree deeper
than MAX_PATH that Explorer and a plain rmdir cannot remove. Require
now removes the entries the case created, deepest first, through
their \?\ paths before aborting.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@XFlawless1
XFlawless1 force-pushed the fix/libc-chdir-long-path branch from 281cb49 to 82b138a Compare November 21, 2026 04:01

@MarcZX10 MarcZX10 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.

Reviewed — looks good

The change adds Windows long-path handling for working-directory updates and getcwd; no verified blocking defect was found in the inspected code.

What I ran

Reviewed head 82b138aa1dedd99bf0d9da9a2ee011b4c201a36e using the prepared diff and repo_read.py. No build or tests were run in this review.

Results

Check Result Note
Diff and source review passed Three changed files read
Build and tests not run Windows runtime behavior not independently checked

Findings

Blocking

None.

Non-blocking

None.

Not verified

No executable checks were run. The author-reported Windows 11 test results were not independently verified. The three changed files listed as reviewed in manifest.json were read; no changed files were excluded.

To get this to a good state

Nothing is required.

@github-actions github-actions Bot removed the needs rebase Conflicts with main, rebase needed label Nov 21, 2026
@oneandonlydean
oneandonlydean merged commit a865756 into boykopovar:main Nov 21, 2026
22 checks passed
@XFlawless1
XFlawless1 deleted the fix/libc-chdir-long-path branch November 21, 2026 04:54
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants