From 8fc565be35fc0dbb350d488880350cc4f879b6b8 Mon Sep 17 00:00:00 2001 From: Austin Schuh Date: Sat, 21 Nov 2026 22:14:51 -0800 Subject: [PATCH 1/5] test(windows): skip the symlink case of the cached venv test without symlinks `test_replaces_dangling_package_link_before_creating_child_link` needs to create symlinks, so it fails on Windows without the privilege to create them. Skip it there. The junction case still runs. --- .../cached_venv_dangling_symlink_test.py | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/tests/bootstrap_impls/cached_venv_dangling_symlink_test.py b/tests/bootstrap_impls/cached_venv_dangling_symlink_test.py index 363736d0a0..35f9c54bad 100644 --- a/tests/bootstrap_impls/cached_venv_dangling_symlink_test.py +++ b/tests/bootstrap_impls/cached_venv_dangling_symlink_test.py @@ -41,7 +41,17 @@ def _load_bootstrap() -> dict: return bootstrap +def _can_create_symlinks() -> bool: + with tempfile.TemporaryDirectory() as temp: + try: + os.symlink(temp, os.path.join(temp, "link"), target_is_directory=True) + except OSError: + return False + return True + + class CachedVenvDanglingSymlinkTest(unittest.TestCase): + @unittest.skipUnless(_can_create_symlinks(), "can't create symlinks") def test_replaces_dangling_package_link_before_creating_child_link(self) -> None: self._test_replaces_dangling_package_link(symlinks_supported=True) From 04ccc96f528ce178272166b8302e7762ab59c673 Mon Sep 17 00:00:00 2001 From: Austin Schuh Date: Sat, 21 Nov 2026 22:14:58 -0800 Subject: [PATCH 2/5] fix(windows): support long runfiles paths without LongPathsEnabled Without `LongPathsEnabled`, which is off by default, Windows paths of 260 characters or more fail unless they have the `\\?\` prefix. The bootstrap skipped the prefix on any Windows 10 1607 or later, so long runfiles paths broke binaries that can't create symlinks: * The fallback for when symlinks can't be created opens the runfiles files to hard link or copy them, which fails with `WinError 3`. * `os.path.exists()` is False for a long `Lib` path, so the runtime venv silently had no `site-packages`. * The check of `RUNFILES_DIR` failed, so it was cleared, and the site init then used `C:\` as the runfiles root and put every directory in `C:\` on `sys.path`. Add the prefix to paths that are long enough to need it, on any Windows version, and use it in the fallback, the venv setup and the runfiles root checks. Short paths are unchanged. This also fixes a `NameError` in the stage 2 copy of the helper, which never defined `unicode_prefix`. Share the bootstrap loader of `cached_venv_dangling_symlink_test` with a new test for long paths. --- news/windows-long-paths.fixed.md | 5 ++ python/private/python_bootstrap_template.txt | 50 ++++++++------- python/private/site_init_template.py | 14 ++-- python/private/stage2_bootstrap_template.py | 34 ++++------ python/private/zipapp/zip_main_template.py | 19 +++--- tests/bootstrap_impls/BUILD.bazel | 18 +++++- .../bootstrap_template_loader.py | 38 +++++++++++ .../cached_venv_dangling_symlink_test.py | 35 +--------- .../windows_long_paths_test.py | 64 +++++++++++++++++++ 9 files changed, 186 insertions(+), 91 deletions(-) create mode 100644 news/windows-long-paths.fixed.md create mode 100644 tests/bootstrap_impls/bootstrap_template_loader.py create mode 100644 tests/bootstrap_impls/windows_long_paths_test.py diff --git a/news/windows-long-paths.fixed.md b/news/windows-long-paths.fixed.md new file mode 100644 index 0000000000..960e328d09 --- /dev/null +++ b/news/windows-long-paths.fixed.md @@ -0,0 +1,5 @@ +(binaries/tests) (Windows) {obj}`py_binary` and {obj}`py_test` work with +runfiles paths of 260 characters or more when `LongPathsEnabled` is off, which +is the default. Before, the venv created at runtime without the privilege to +create symlinks could be missing files, and the runfiles directory wasn't found, +so imports failed. diff --git a/python/private/python_bootstrap_template.txt b/python/private/python_bootstrap_template.txt index 72bf62ddad..300a29a2c5 100644 --- a/python/private/python_bootstrap_template.txt +++ b/python/private/python_bootstrap_template.txt @@ -129,6 +129,10 @@ _symlinks_supported = not ( # symlinks can't be created needs to clean up. _WINDOWS_FALLBACK_MIN_BUILD = 17763 +# Windows paths at least this long need the \\?\ prefix. It's 248 rather than +# 260 (MAX_PATH) because that's the limit for creating directories. +_MAX_PATH_WITHOUT_PREFIX = 248 + # Windows APIs can be picky about slashes depending on the context, # so convert to backslashes to avoid any issues. if IS_WINDOWS: @@ -152,10 +156,11 @@ if IS_WINDOWS: if PYTHON_BINARY_ACTUAL and not has_windows_executable_extension(PYTHON_BINARY_ACTUAL): PYTHON_BINARY_ACTUAL = PYTHON_BINARY_ACTUAL + ".exe" -def get_windows_path_with_unc_prefix(path): +def get_windows_path_with_unc_prefix(path, always=False): """Adds UNC prefix after getting a normalized absolute Windows path. - No-op for non-Windows platforms or if running under python2. + No-op for non-Windows platforms or if running under python2. Unless `always` + is set, the prefix is only added to paths that are too long without it. """ path = path.strip() @@ -164,33 +169,25 @@ def get_windows_path_with_unc_prefix(path): if not IS_WINDOWS or sys.version_info[0] < 3: return path - # Starting in Windows 10, version 1607(OS build 14393), MAX_PATH limitations have been - # removed from common Win32 file and directory functions. - # Related doc: https://docs.microsoft.com/en-us/windows/win32/fileio/maximum-file-path-limitation?tabs=cmd#enable-long-paths-in-windows-10-version-1607-and-later - import platform - win32_version = None - # Windows 2022 with Python 3.12.8 gives flakey errors, so try a couple times. - for _ in range(3): - try: - win32_version = platform.win32_ver()[1] - break - except (ValueError, KeyError): - pass - if win32_version and win32_version >= '10.0.14393': - return path - # import sysconfig only now to maintain python 2.6 compatibility import sysconfig if sysconfig.get_platform() == 'mingw': return path - # Lets start the unicode fun unicode_prefix = '\\\\?\\' if path.startswith(unicode_prefix): return path # abspath returns a normalized absolute path - return unicode_prefix + abspath(path) + path = abspath(path) + # Long paths only work without the prefix if LongPathsEnabled is set, which + # is off by default. Only add the prefix when it's needed, so that short + # paths, e.g. __file__, are unchanged. + if not always and len(path) < _MAX_PATH_WITHOUT_PREFIX: + return path + if path.startswith('\\\\'): + return unicode_prefix + 'UNC\\' + path[2:] + return unicode_prefix + path def search_path(name): """Finds a file in a given search path.""" @@ -268,7 +265,8 @@ def find_runfiles_root(main_rel_path): runfiles_dir = runfiles_manifest_file[:-9] # Be defensive: the runfiles dir should contain our main entry point. If # it doesn't, then it must not be our runfiles directory. - if runfiles_dir and os.path.exists(join(runfiles_dir, main_rel_path)): + if runfiles_dir and os.path.exists( + get_windows_path_with_unc_prefix(join(runfiles_dir, main_rel_path))): return runfiles_dir # Clear RUNFILES_DIR & RUNFILES_MANIFEST_FILE since the runfiles dir was @@ -356,13 +354,16 @@ def _symlink_tree(link_from, link_to): # Ensure the source is an absolute path to simplify symlinking link_to_root = abspath(link_to) link_from_root = abspath(link_from) + # Walk with the \\?\ prefix, or os.walk() skips directories with long paths. + link_to_root = get_windows_path_with_unc_prefix(link_to_root, always=True) # This is non-optimal because it recreates the entire # venv site-packages tree (as opposed to finding a highest-common # directory to symlink). But its easy and understandable. for root, dirs, files in os.walk(link_to_root): rel_path = os.path.relpath(root, link_to_root) - link_from_dir = join(link_from_root, rel_path) + link_from_dir = get_windows_path_with_unc_prefix( + join(link_from_root, rel_path)) if not os.path.exists(link_from_dir): os.makedirs(link_from_dir) @@ -416,6 +417,8 @@ print(site.getsitepackages(["{venv_src}"])[-1]) venv_lib = join(venv, LIB_DIR_NAME) runfiles_venv_lib = join(runfiles_venv, LIB_DIR_NAME) + runfiles_venv_lib = get_windows_path_with_unc_prefix(runfiles_venv_lib) + venv_bin = join(venv, BIN_DIR_NAME) try: os.mkdir(venv_bin) @@ -435,7 +438,8 @@ print(site.getsitepackages(["{venv_src}"])[-1]) target = join(python_home, f) _symlink_exist_ok(from_=venv_path, to=target) - runfiles_venv_bin = join(runfiles_venv, BIN_DIR_NAME) + runfiles_venv_bin = get_windows_path_with_unc_prefix( + join(runfiles_venv, BIN_DIR_NAME)) # The runfiles bin directory may not exist if it's empty, e.g. # supports_build_time_venv=False and the interpreter is resolved at # runtime. @@ -631,6 +635,8 @@ def _run_execv(python_program, argv, env): def _symlink_exist_ok(*, from_, to): """Creates a symlink, or on Windows, a hard link, junction or copy if that's not possible.""" global _symlinks_supported + from_ = get_windows_path_with_unc_prefix(from_) + to = get_windows_path_with_unc_prefix(to) # On Windows, symlinks have to be told whether they're # pointing to a file or directory. Python is supposed to auto-detect # this, but in practice, this doesn't reliably happen. diff --git a/python/private/site_init_template.py b/python/private/site_init_template.py index 81891bbd52..a8facd298b 100644 --- a/python/private/site_init_template.py +++ b/python/private/site_init_template.py @@ -68,10 +68,16 @@ def _find_runfiles_root(): # Be defensive: the runfiles dir should contain ourselves. If it doesn't, # then it must not be our runfiles directory. - if runfiles_dir and os.path.exists( - os.path.join(runfiles_dir, _SELF_RUNFILES_RELATIVE_PATH) - ): - return runfiles_dir + if runfiles_dir: + self_path = os.path.abspath( + os.path.join(runfiles_dir, _SELF_RUNFILES_RELATIVE_PATH) + ) + # Without the \\?\ prefix, exists() is False for paths that are too + # long, unless LongPathsEnabled is set. + if os.name == "nt" and not self_path.startswith("\\\\"): + self_path = "\\\\?\\" + self_path + if os.path.exists(self_path): + return runfiles_dir num_dirs_to_runfiles_root = _SELF_RUNFILES_RELATIVE_PATH.count("/") + 1 runfiles_root = os.path.dirname(__file__) diff --git a/python/private/stage2_bootstrap_template.py b/python/private/stage2_bootstrap_template.py index 1094b36704..7a9f0cc57b 100644 --- a/python/private/stage2_bootstrap_template.py +++ b/python/private/stage2_bootstrap_template.py @@ -114,34 +114,26 @@ def get_windows_path_with_unc_prefix(path): if not IS_WINDOWS or sys.version_info[0] < 3: return path - # Starting in Windows 10, version 1607(OS build 14393), MAX_PATH limitations have been - # removed from common Win32 file and directory functions. - # Related doc: https://docs.microsoft.com/en-us/windows/win32/fileio/maximum-file-path-limitation?tabs=cmd#enable-long-paths-in-windows-10-version-1607-and-later - import platform - - win32_version = None - # Windows 2022 with Python 3.12.8 gives flakey errors, so try a couple times. - for _ in range(3): - try: - win32_version = platform.win32_ver()[1] - break - except (ValueError, KeyError): - pass - if win32_version and win32_version >= "10.0.14393": - return path - # import sysconfig only now to maintain python 2.6 compatibility import sysconfig if sysconfig.get_platform() == "mingw": return path - # Lets start the unicode fun - if path.startswith(unicode_prefix): # noqa: F821 + unicode_prefix = "\\\\?\\" + if path.startswith(unicode_prefix): return path # os.path.abspath returns a normalized absolute path - return unicode_prefix + os.path.abspath(path) # noqa: F821 + path = os.path.abspath(path) + # Long paths only work without the prefix if LongPathsEnabled is set, which + # is off by default. Only add the prefix when it's needed, so that short + # paths, e.g. __file__, are unchanged. 248 is the limit for directories. + if len(path) < 248: + return path + if path.startswith("\\\\"): + return unicode_prefix + "UNC\\" + path[2:] + return unicode_prefix + path def print_verbose(*args, mapping=None, values=None): @@ -196,7 +188,9 @@ def find_runfiles_root(main_rel_path): runfiles_dir = runfiles_manifest_file[:-9] # Be defensive: the runfiles dir should contain our main entry point. If # it doesn't, then it must not be our runfiles directory. - if runfiles_dir and os.path.exists(os.path.join(runfiles_dir, main_rel_path)): + if runfiles_dir and os.path.exists( + get_windows_path_with_unc_prefix(os.path.join(runfiles_dir, main_rel_path)) + ): return runfiles_dir # Clear RUNFILES_DIR & RUNFILES_MANIFEST_FILE since the runfiles dir was diff --git a/python/private/zipapp/zip_main_template.py b/python/private/zipapp/zip_main_template.py index 7c965fc1f5..0b3a092faa 100644 --- a/python/private/zipapp/zip_main_template.py +++ b/python/private/zipapp/zip_main_template.py @@ -104,27 +104,26 @@ def get_windows_path_with_unc_prefix(path): if not IS_WINDOWS or sys.version_info[0] < 3: return path - # Starting in Windows 10, version 1607(OS build 14393), MAX_PATH limitations have been - # removed from common Win32 file and directory functions. - # Related doc: https://docs.microsoft.com/en-us/windows/win32/fileio/maximum-file-path-limitation?tabs=cmd#enable-long-paths-in-windows-10-version-1607-and-later - import platform - - if platform.win32_ver()[1] >= "10.0.14393": - return path - # import sysconfig only now to maintain python 2.6 compatibility import sysconfig if sysconfig.get_platform() == "mingw": return path - # Lets start the unicode fun unicode_prefix = "\\\\?\\" if path.startswith(unicode_prefix): return path # os.path.abspath returns a normalized absolute path - return unicode_prefix + os.path.abspath(path) + path = os.path.abspath(path) + # Long paths only work without the prefix if LongPathsEnabled is set, which + # is off by default. Only add the prefix when it's needed, so that short + # paths, e.g. __file__, are unchanged. 248 is the limit for directories. + if len(path) < 248: + return path + if path.startswith("\\\\"): + return unicode_prefix + "UNC\\" + path[2:] + return unicode_prefix + path def search_path(name): diff --git a/tests/bootstrap_impls/BUILD.bazel b/tests/bootstrap_impls/BUILD.bazel index f2cd3a14c4..50b81ccfee 100644 --- a/tests/bootstrap_impls/BUILD.bazel +++ b/tests/bootstrap_impls/BUILD.bazel @@ -13,6 +13,7 @@ # limitations under the License. load("@rules_pkg//pkg:tar.bzl", "pkg_tar") load("@rules_shell//shell:sh_test.bzl", "sh_test") +load("//python:py_library.bzl", "py_library") load("//python:py_test.bzl", "py_test") load("//python:pytest_test.bzl", "pytest_test") load("//tests/support:py_reconfig.bzl", "py_reconfig_binary", "py_reconfig_test") @@ -149,12 +150,25 @@ pytest_test( ], ) +py_library( + name = "bootstrap_template_loader", + srcs = ["bootstrap_template_loader.py"], + data = ["//python/private:python_bootstrap_template.txt"], + deps = ["//python/runfiles"], +) + py_test( name = "cached_venv_replaces_dangling_package_symlink_test", srcs = ["cached_venv_dangling_symlink_test.py"], - data = ["//python/private:python_bootstrap_template.txt"], main = "cached_venv_dangling_symlink_test.py", - deps = ["//python/runfiles"], + deps = [":bootstrap_template_loader"], +) + +py_test( + name = "windows_long_paths_test", + srcs = ["windows_long_paths_test.py"], + target_compatible_with = ["@platforms//os:windows"], + deps = [":bootstrap_template_loader"], ) py_reconfig_test( diff --git a/tests/bootstrap_impls/bootstrap_template_loader.py b/tests/bootstrap_impls/bootstrap_template_loader.py new file mode 100644 index 0000000000..739641c956 --- /dev/null +++ b/tests/bootstrap_impls/bootstrap_template_loader.py @@ -0,0 +1,38 @@ +"""Loads python_bootstrap_template.txt as a module, for testing its functions.""" + +from __future__ import annotations + +import pathlib +import sys + +from python.runfiles import runfiles + + +def load_bootstrap() -> dict: + r = runfiles.Create() + if r: + template_path = r.Rlocation( + "rules_python/python/private/python_bootstrap_template.txt" + ) + assert template_path is not None + template = pathlib.Path(template_path) + else: + template = ( + pathlib.Path(__file__).resolve().parents[2] + / "python/private/python_bootstrap_template.txt" + ) + source = template.read_text(encoding="utf-8") + for placeholder, value in [ + ("%shebang%", "#!/usr/bin/env python3"), + ("%stage2_bootstrap%", "unused.py"), + ("%runtime_venv_symlinks%", ""), + ]: + source = source.replace(placeholder, value) + + bootstrap = {"__name__": "bootstrap_test"} + saved_path = sys.path[:] + try: + exec(compile(source, str(template), "exec"), bootstrap) + finally: + sys.path[:] = saved_path + return bootstrap diff --git a/tests/bootstrap_impls/cached_venv_dangling_symlink_test.py b/tests/bootstrap_impls/cached_venv_dangling_symlink_test.py index 35f9c54bad..2b2c4e6ccd 100644 --- a/tests/bootstrap_impls/cached_venv_dangling_symlink_test.py +++ b/tests/bootstrap_impls/cached_venv_dangling_symlink_test.py @@ -4,41 +4,10 @@ import os import pathlib -import sys import tempfile import unittest -from python.runfiles import runfiles - - -def _load_bootstrap() -> dict: - r = runfiles.Create() - if r: - template_path = r.Rlocation( - "rules_python/python/private/python_bootstrap_template.txt" - ) - assert template_path is not None - template = pathlib.Path(template_path) - else: - template = ( - pathlib.Path(__file__).resolve().parents[2] - / "python/private/python_bootstrap_template.txt" - ) - source = template.read_text(encoding="utf-8") - for placeholder, value in [ - ("%shebang%", "#!/usr/bin/env python3"), - ("%stage2_bootstrap%", "unused.py"), - ("%runtime_venv_symlinks%", ""), - ]: - source = source.replace(placeholder, value) - - bootstrap = {"__name__": "bootstrap_test"} - saved_path = sys.path[:] - try: - exec(compile(source, str(template), "exec"), bootstrap) - finally: - sys.path[:] = saved_path - return bootstrap +from tests.bootstrap_impls.bootstrap_template_loader import load_bootstrap def _can_create_symlinks() -> bool: @@ -82,7 +51,7 @@ def test_dangling_junction_is_detected_and_removed(self) -> None: self.assertFalse(os.path.lexists(junction)) def _test_replaces_dangling_package_link(self, *, symlinks_supported) -> None: - bootstrap = _load_bootstrap() + bootstrap = load_bootstrap() # False uses the fallback for when symlinks can't be created, which # creates a junction for a directory. bootstrap["_symlinks_supported"] = symlinks_supported diff --git a/tests/bootstrap_impls/windows_long_paths_test.py b/tests/bootstrap_impls/windows_long_paths_test.py new file mode 100644 index 0000000000..b936c157e3 --- /dev/null +++ b/tests/bootstrap_impls/windows_long_paths_test.py @@ -0,0 +1,64 @@ +"""Tests the bootstrap with Windows paths that need the \\?\\ prefix.""" + +from __future__ import annotations + +import os +import shutil +import tempfile +import unittest + +from tests.bootstrap_impls.bootstrap_template_loader import load_bootstrap + +_PREFIX = "\\\\?\\" +# Over 260 characters, the limit without the prefix or LongPathsEnabled. +_LONG_REL_PATH = os.path.join(*["d" * 50] * 6) + + +@unittest.skipUnless(os.name == "nt", "Windows only") +class WindowsLongPathsTest(unittest.TestCase): + def setUp(self) -> None: + self.bootstrap = load_bootstrap() + # Use the fallback for when symlinks can't be created. + self.bootstrap["_symlinks_supported"] = False + self.temp = tempfile.mkdtemp() + self.addCleanup(shutil.rmtree, _PREFIX + self.temp) + + def _write_long_file(self, root: str) -> str: + path = os.path.join(root, _LONG_REL_PATH, "file.txt") + os.makedirs(_PREFIX + os.path.dirname(path)) + with open(_PREFIX + path, "w") as f: + f.write("hello") + return path + + def test_prefix_is_only_added_to_long_paths(self) -> None: + add_prefix = self.bootstrap["get_windows_path_with_unc_prefix"] + self.assertEqual(add_prefix("C:\\short"), "C:\\short") + long_path = "C:\\" + "a" * 300 + self.assertEqual(add_prefix(long_path), _PREFIX + long_path) + self.assertEqual( + add_prefix("\\\\server\\share\\" + "a" * 300), + _PREFIX + "UNC\\server\\share\\" + "a" * 300, + ) + + def test_fallback_links_a_long_path(self) -> None: + target = self._write_long_file(self.temp) + link = os.path.join(self.temp, "link.txt") + + self.bootstrap["_symlink_exist_ok"](from_=link, to=target) + + with open(link) as f: + self.assertEqual(f.read(), "hello") + + def test_symlink_tree_includes_long_paths(self) -> None: + src = os.path.join(self.temp, "src") + self._write_long_file(src) + dest = os.path.join(self.temp, "dest") + + self.bootstrap["_symlink_tree"](link_from=dest, link_to=src) + + with open(_PREFIX + os.path.join(dest, _LONG_REL_PATH, "file.txt")) as f: + self.assertEqual(f.read(), "hello") + + +if __name__ == "__main__": + unittest.main() From 262d42afa810eeef2f7dd05b4fd8f41324b28839 Mon Sep 17 00:00:00 2001 From: Austin Schuh Date: Sun, 22 Nov 2026 11:50:38 -0800 Subject: [PATCH 3/5] fix(windows): skip the long-path prefix where it isn't needed * Remove the prefix from junction targets. `CreateJunction()` adds its own, so a long directory got a broken junction. * Don't add the prefix when `LongPathsEnabled` is set, so long paths, e.g. `__file__`, keep working with `..` and forward slashes there. Read the setting with `winreg`, not `ctypes`: `LongPathsEnabled` doesn't apply to loading DLLs, so `import ctypes` fails when Python is under a long path, as in runfiles. * Only pass the prefix to `_symlink_exist_ok()` for long paths, so short symlink targets stay unchanged. * Use the existing helper in the site init's runfiles root check, which also handles UNC paths, and test every copy of the helper. --- python/private/python_bootstrap_template.txt | 49 ++++++++-- python/private/site_init_template.py | 68 +++++++------- python/private/stage2_bootstrap_template.py | 28 +++++- python/private/zipapp/zip_main_template.py | 35 +++++++- tests/bootstrap_impls/BUILD.bazel | 7 +- .../bootstrap_template_loader.py | 51 ++++++++--- .../windows_long_paths_test.py | 89 ++++++++++++++++--- 7 files changed, 249 insertions(+), 78 deletions(-) diff --git a/python/private/python_bootstrap_template.txt b/python/private/python_bootstrap_template.txt index 300a29a2c5..9ff22cae44 100644 --- a/python/private/python_bootstrap_template.txt +++ b/python/private/python_bootstrap_template.txt @@ -180,15 +180,43 @@ def get_windows_path_with_unc_prefix(path, always=False): # abspath returns a normalized absolute path path = abspath(path) - # Long paths only work without the prefix if LongPathsEnabled is set, which - # is off by default. Only add the prefix when it's needed, so that short - # paths, e.g. __file__, are unchanged. + # Only add the prefix when it's needed, so that other paths, e.g. __file__, + # are unchanged: the prefix turns off normalization, e.g. of "..". if not always and len(path) < _MAX_PATH_WITHOUT_PREFIX: return path + if _long_paths_enabled(): + return path if path.startswith('\\\\'): return unicode_prefix + 'UNC\\' + path[2:] return unicode_prefix + path +def strip_windows_unc_prefix(path): + """Removes the prefix that get_windows_path_with_unc_prefix() adds.""" + if path.startswith('\\\\?\\UNC\\'): + return '\\\\' + path[8:] + if path.startswith('\\\\?\\'): + return path[4:] + return path + +_long_paths_enabled_result = None + +def _long_paths_enabled(): + """Returns whether LongPathsEnabled is set, which is off by default.""" + global _long_paths_enabled_result + if _long_paths_enabled_result is None: + # Read the registry instead of calling RtlAreLongPathsEnabled() through + # ctypes. ctypes needs to load _ctypes.pyd, and LongPathsEnabled doesn't + # apply to loading DLLs, so the import fails when Python itself is under + # a long path, e.g. in runfiles. winreg is built in, so it always works. + # python.exe opts in to long paths, so the registry value is enough. + try: + import winreg + with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"SYSTEM\CurrentControlSet\Control\FileSystem") as key: + _long_paths_enabled_result = bool(winreg.QueryValueEx(key, "LongPathsEnabled")[0]) + except (ImportError, OSError): + _long_paths_enabled_result = False + return _long_paths_enabled_result + def search_path(name): """Finds a file in a given search path.""" search_path = os.getenv('PATH', os.defpath).split(os.pathsep) @@ -354,14 +382,15 @@ def _symlink_tree(link_from, link_to): # Ensure the source is an absolute path to simplify symlinking link_to_root = abspath(link_to) link_from_root = abspath(link_from) - # Walk with the \\?\ prefix, or os.walk() skips directories with long paths. - link_to_root = get_windows_path_with_unc_prefix(link_to_root, always=True) + # Walk with the \\?\ prefix, or os.walk() skips directories with long + # paths, but only pass the prefix on for the paths that need it. + walk_root = get_windows_path_with_unc_prefix(link_to_root, always=True) # This is non-optimal because it recreates the entire # venv site-packages tree (as opposed to finding a highest-common # directory to symlink). But its easy and understandable. - for root, dirs, files in os.walk(link_to_root): - rel_path = os.path.relpath(root, link_to_root) + for root, dirs, files in os.walk(walk_root): + rel_path = os.path.relpath(root, walk_root) link_from_dir = get_windows_path_with_unc_prefix( join(link_from_root, rel_path)) @@ -369,7 +398,7 @@ def _symlink_tree(link_from, link_to): os.makedirs(link_from_dir) for name in files: - link_to = join(root, name) + link_to = join(link_to_root, rel_path, name) link_from = join(link_from_dir, name) _symlink_exist_ok(from_=link_from, to=link_to) @@ -685,7 +714,9 @@ def _link_dir_windows(from_, to): import _winapi try: # Junctions don't need any privileges, but need an absolute target. - _winapi.CreateJunction(to, from_) + # CreateJunction() adds its own prefix to the target, and the target + # doesn't have the MAX_PATH limit, so remove ours. + _winapi.CreateJunction(strip_windows_unc_prefix(to), from_) # Another process sharing RULES_PYTHON_EXTRACT_ROOT created it first. except FileExistsError: return diff --git a/python/private/site_init_template.py b/python/private/site_init_template.py index 376a8f15e8..368ebc14e5 100644 --- a/python/private/site_init_template.py +++ b/python/private/site_init_template.py @@ -60,41 +60,6 @@ def _print_verbose(*args, mapping=None, values=None): _print_verbose("interpreter_actual_path:", _INTERPRETER_ACTUAL_PATH) -def _find_runfiles_root(): - # Give preference to the environment variables - runfiles_dir = os.environ.get("RUNFILES_DIR", None) - if not runfiles_dir: - runfiles_manifest_file = os.environ.get("RUNFILES_MANIFEST_FILE", "") - if runfiles_manifest_file.endswith( - ".runfiles_manifest" - ) or runfiles_manifest_file.endswith(".runfiles/MANIFEST"): - runfiles_dir = runfiles_manifest_file[:-9] - - # Be defensive: the runfiles dir should contain ourselves. If it doesn't, - # then it must not be our runfiles directory. - if runfiles_dir: - self_path = os.path.abspath( - os.path.join(runfiles_dir, _SELF_RUNFILES_RELATIVE_PATH) - ) - # Without the \\?\ prefix, exists() is False for paths that are too - # long, unless LongPathsEnabled is set. - if os.name == "nt" and not self_path.startswith("\\\\"): - self_path = "\\\\?\\" + self_path - if os.path.exists(self_path): - return runfiles_dir - - num_dirs_to_runfiles_root = _SELF_RUNFILES_RELATIVE_PATH.count("/") + 1 - runfiles_root = os.path.dirname(__file__) - for _ in range(num_dirs_to_runfiles_root): - runfiles_root = os.path.dirname(runfiles_root) - return runfiles_root - - -_RUNFILES_ROOT = _find_runfiles_root() - -_print_verbose("runfiles_root:", _RUNFILES_ROOT) - - def _is_windows(): return os.name == "nt" @@ -124,6 +89,39 @@ def _get_windows_path_with_unc_prefix(path): return extended_path_prefix + path +def _find_runfiles_root(): + # Give preference to the environment variables + runfiles_dir = os.environ.get("RUNFILES_DIR", None) + if not runfiles_dir: + runfiles_manifest_file = os.environ.get("RUNFILES_MANIFEST_FILE", "") + if runfiles_manifest_file.endswith( + ".runfiles_manifest" + ) or runfiles_manifest_file.endswith(".runfiles/MANIFEST"): + runfiles_dir = runfiles_manifest_file[:-9] + + # Be defensive: the runfiles dir should contain ourselves. If it doesn't, + # then it must not be our runfiles directory. + # Without the \\?\ prefix, exists() is False for paths that are too long, + # unless LongPathsEnabled is set. + if runfiles_dir and os.path.exists( + _get_windows_path_with_unc_prefix( + os.path.join(runfiles_dir, _SELF_RUNFILES_RELATIVE_PATH) + ) + ): + return runfiles_dir + + num_dirs_to_runfiles_root = _SELF_RUNFILES_RELATIVE_PATH.count("/") + 1 + runfiles_root = os.path.dirname(__file__) + for _ in range(num_dirs_to_runfiles_root): + runfiles_root = os.path.dirname(runfiles_root) + return runfiles_root + + +_RUNFILES_ROOT = _find_runfiles_root() + +_print_verbose("runfiles_root:", _RUNFILES_ROOT) + + def _install_windows_extension_finder(): """Use extended-length paths when loading long Windows extension paths.""" if not _is_windows() or sys.version_info[0] < 3: diff --git a/python/private/stage2_bootstrap_template.py b/python/private/stage2_bootstrap_template.py index 0a180660c8..ae389f4058 100644 --- a/python/private/stage2_bootstrap_template.py +++ b/python/private/stage2_bootstrap_template.py @@ -159,16 +159,36 @@ def get_windows_path_with_unc_prefix(path): # os.path.abspath returns a normalized absolute path path = os.path.abspath(path) - # Long paths only work without the prefix if LongPathsEnabled is set, which - # is off by default. Only add the prefix when it's needed, so that short - # paths, e.g. __file__, are unchanged. 248 is the limit for directories. - if len(path) < 248: + # Only add the prefix when it's needed, so that other paths, e.g. __file__, + # are unchanged: the prefix turns off normalization, e.g. of "..". 248 is + # the limit for directories. + if len(path) < 248 or _long_paths_enabled(): return path if path.startswith("\\\\"): return unicode_prefix + "UNC\\" + path[2:] return unicode_prefix + path +@cache +def _long_paths_enabled(): + """Returns whether LongPathsEnabled is set, which is off by default.""" + # Read the registry instead of calling RtlAreLongPathsEnabled() through + # ctypes. ctypes needs to load _ctypes.pyd, and LongPathsEnabled doesn't + # apply to loading DLLs, so the import fails when Python itself is under + # a long path, e.g. in runfiles. winreg is built in, so it always works. + # python.exe opts in to long paths, so the registry value is enough. + try: + import winreg + + with winreg.OpenKey( + winreg.HKEY_LOCAL_MACHINE, + r"SYSTEM\CurrentControlSet\Control\FileSystem", + ) as key: + return bool(winreg.QueryValueEx(key, "LongPathsEnabled")[0]) + except (ImportError, OSError): + return False + + def print_verbose(*args, mapping=None, values=None): if not IS_VERBOSE: return diff --git a/python/private/zipapp/zip_main_template.py b/python/private/zipapp/zip_main_template.py index 0b3a092faa..b0bca55c3f 100644 --- a/python/private/zipapp/zip_main_template.py +++ b/python/private/zipapp/zip_main_template.py @@ -116,16 +116,43 @@ def get_windows_path_with_unc_prefix(path): # os.path.abspath returns a normalized absolute path path = os.path.abspath(path) - # Long paths only work without the prefix if LongPathsEnabled is set, which - # is off by default. Only add the prefix when it's needed, so that short - # paths, e.g. __file__, are unchanged. 248 is the limit for directories. - if len(path) < 248: + # Only add the prefix when it's needed, so that other paths, e.g. __file__, + # are unchanged: the prefix turns off normalization, e.g. of "..". 248 is + # the limit for directories. + if len(path) < 248 or _long_paths_enabled(): return path if path.startswith("\\\\"): return unicode_prefix + "UNC\\" + path[2:] return unicode_prefix + path +_long_paths_enabled_result = None + + +def _long_paths_enabled(): + """Returns whether LongPathsEnabled is set, which is off by default.""" + global _long_paths_enabled_result + if _long_paths_enabled_result is None: + # Read the registry instead of calling RtlAreLongPathsEnabled() through + # ctypes. ctypes needs to load _ctypes.pyd, and LongPathsEnabled doesn't + # apply to loading DLLs, so the import fails when Python itself is under + # a long path, e.g. in runfiles. winreg is built in, so it always works. + # python.exe opts in to long paths, so the registry value is enough. + try: + import winreg + + with winreg.OpenKey( + winreg.HKEY_LOCAL_MACHINE, + r"SYSTEM\CurrentControlSet\Control\FileSystem", + ) as key: + _long_paths_enabled_result = bool( + winreg.QueryValueEx(key, "LongPathsEnabled")[0] + ) + except (ImportError, OSError): + _long_paths_enabled_result = False + return _long_paths_enabled_result + + def search_path(name): """Finds a file in a given search path.""" search_path = os.getenv("PATH", os.defpath).split(os.pathsep) diff --git a/tests/bootstrap_impls/BUILD.bazel b/tests/bootstrap_impls/BUILD.bazel index 50b81ccfee..4dc5acbead 100644 --- a/tests/bootstrap_impls/BUILD.bazel +++ b/tests/bootstrap_impls/BUILD.bazel @@ -153,7 +153,12 @@ pytest_test( py_library( name = "bootstrap_template_loader", srcs = ["bootstrap_template_loader.py"], - data = ["//python/private:python_bootstrap_template.txt"], + data = [ + "//python/private:python_bootstrap_template.txt", + "//python/private:site_init_template", + "//python/private:stage2_bootstrap_template", + "//python/private/zipapp:zip_main_template", + ], deps = ["//python/runfiles"], ) diff --git a/tests/bootstrap_impls/bootstrap_template_loader.py b/tests/bootstrap_impls/bootstrap_template_loader.py index 739641c956..100d00a411 100644 --- a/tests/bootstrap_impls/bootstrap_template_loader.py +++ b/tests/bootstrap_impls/bootstrap_template_loader.py @@ -1,26 +1,27 @@ -"""Loads python_bootstrap_template.txt as a module, for testing its functions.""" +"""Loads the bootstrap templates as modules, for testing their functions.""" from __future__ import annotations +import ast +import functools +import os import pathlib import sys from python.runfiles import runfiles -def load_bootstrap() -> dict: +def _template_path(rel_path: str) -> pathlib.Path: r = runfiles.Create() if r: - template_path = r.Rlocation( - "rules_python/python/private/python_bootstrap_template.txt" - ) - assert template_path is not None - template = pathlib.Path(template_path) - else: - template = ( - pathlib.Path(__file__).resolve().parents[2] - / "python/private/python_bootstrap_template.txt" - ) + path = r.Rlocation("rules_python/" + rel_path) + assert path is not None + return pathlib.Path(path) + return pathlib.Path(__file__).resolve().parents[2] / rel_path + + +def load_bootstrap() -> dict: + template = _template_path("python/private/python_bootstrap_template.txt") source = template.read_text(encoding="utf-8") for placeholder, value in [ ("%shebang%", "#!/usr/bin/env python3"), @@ -36,3 +37,29 @@ def load_bootstrap() -> dict: finally: sys.path[:] = saved_path return bootstrap + + +def load_functions(rel_path: str, names: list[str]) -> dict: + """Loads some functions of a template without running the rest of it. + + Returns: + The globals of the functions, so that tests can replace the + functions that they call. + """ + template = _template_path(rel_path) + tree = ast.parse(template.read_text(encoding="utf-8")) + functions = [ + node + for node in tree.body + if isinstance(node, ast.FunctionDef) and node.name in names + ] + assert len(functions) == len(names), f"not all of {names} are in {rel_path}" + module = { + "__name__": "template_test", + "cache": functools.cache, + "os": os, + "sys": sys, + "IS_WINDOWS": os.name == "nt", + } + exec(compile(ast.Module(body=functions, type_ignores=[]), str(template), "exec"), module) + return module diff --git a/tests/bootstrap_impls/windows_long_paths_test.py b/tests/bootstrap_impls/windows_long_paths_test.py index b936c157e3..e19b5760c3 100644 --- a/tests/bootstrap_impls/windows_long_paths_test.py +++ b/tests/bootstrap_impls/windows_long_paths_test.py @@ -6,16 +6,67 @@ import shutil import tempfile import unittest +from unittest import mock -from tests.bootstrap_impls.bootstrap_template_loader import load_bootstrap +from tests.bootstrap_impls.bootstrap_template_loader import ( + load_bootstrap, + load_functions, +) _PREFIX = "\\\\?\\" # Over 260 characters, the limit without the prefix or LongPathsEnabled. _LONG_REL_PATH = os.path.join(*["d" * 50] * 6) +_HELPER = "get_windows_path_with_unc_prefix" @unittest.skipUnless(os.name == "nt", "Windows only") -class WindowsLongPathsTest(unittest.TestCase): +class PrefixHelperTest(unittest.TestCase): + def _copies(self) -> dict: + """Returns the globals of each copy of the helper.""" + names = [_HELPER, "_long_paths_enabled"] + return { + "stage 1": load_bootstrap(), + "stage 2": load_functions( + "python/private/stage2_bootstrap_template.py", names + ), + "zipapp": load_functions( + "python/private/zipapp/zip_main_template.py", names + ), + } + + def test_prefix_is_only_added_when_needed(self) -> None: + long_path = "C:\\" + "a" * 300 + unc_path = "\\\\server\\share\\" + "a" * 300 + for name, module in self._copies().items(): + add_prefix = module[_HELPER] + with self.subTest(name, long_paths_enabled=False): + module["_long_paths_enabled"] = lambda: False + self.assertEqual(add_prefix("C:\\short"), "C:\\short") + self.assertEqual(add_prefix(long_path), _PREFIX + long_path) + self.assertEqual( + add_prefix(unc_path), _PREFIX + "UNC\\" + unc_path[2:] + ) + self.assertEqual(add_prefix(_PREFIX + "C:\\x"), _PREFIX + "C:\\x") + with self.subTest(name, long_paths_enabled=True): + module["_long_paths_enabled"] = lambda: True + self.assertEqual(add_prefix(long_path), long_path) + + def test_site_init_converts_unc_paths(self) -> None: + module = load_functions( + "python/private/site_init_template.py", + ["_is_windows", "_get_windows_path_with_unc_prefix"], + ) + add_prefix = module["_get_windows_path_with_unc_prefix"] + self.assertEqual(add_prefix("C:\\x"), _PREFIX + "C:\\x") + self.assertEqual( + add_prefix("\\\\server\\share\\x"), _PREFIX + "UNC\\server\\share\\x" + ) + + +@unittest.skipUnless(os.name == "nt", "Windows only") +class LinkFallbackTest(unittest.TestCase): + """Uses the real LongPathsEnabled setting, so it passes either way.""" + def setUp(self) -> None: self.bootstrap = load_bootstrap() # Use the fallback for when symlinks can't be created. @@ -30,17 +81,7 @@ def _write_long_file(self, root: str) -> str: f.write("hello") return path - def test_prefix_is_only_added_to_long_paths(self) -> None: - add_prefix = self.bootstrap["get_windows_path_with_unc_prefix"] - self.assertEqual(add_prefix("C:\\short"), "C:\\short") - long_path = "C:\\" + "a" * 300 - self.assertEqual(add_prefix(long_path), _PREFIX + long_path) - self.assertEqual( - add_prefix("\\\\server\\share\\" + "a" * 300), - _PREFIX + "UNC\\server\\share\\" + "a" * 300, - ) - - def test_fallback_links_a_long_path(self) -> None: + def test_links_a_long_file(self) -> None: target = self._write_long_file(self.temp) link = os.path.join(self.temp, "link.txt") @@ -49,6 +90,14 @@ def test_fallback_links_a_long_path(self) -> None: with open(link) as f: self.assertEqual(f.read(), "hello") + def test_links_a_long_directory(self) -> None: + target = os.path.dirname(self._write_long_file(self.temp)) + link = os.path.join(self.temp, "link") + + self.bootstrap["_symlink_exist_ok"](from_=link, to=target) + + self.assertEqual(os.listdir(link), ["file.txt"]) + def test_symlink_tree_includes_long_paths(self) -> None: src = os.path.join(self.temp, "src") self._write_long_file(src) @@ -59,6 +108,20 @@ def test_symlink_tree_includes_long_paths(self) -> None: with open(_PREFIX + os.path.join(dest, _LONG_REL_PATH, "file.txt")) as f: self.assertEqual(f.read(), "hello") + def test_symlink_tree_keeps_short_targets_unprefixed(self) -> None: + self.bootstrap["_symlinks_supported"] = True + src = os.path.join(self.temp, "src") + os.makedirs(os.path.join(src, "pkg")) + target = os.path.join(src, "pkg", "mod.py") + open(target, "w").close() + + with mock.patch("os.symlink") as symlink: + self.bootstrap["_symlink_tree"]( + link_from=os.path.join(self.temp, "dest"), link_to=src + ) + + self.assertEqual(symlink.call_args.args[0], target) + if __name__ == "__main__": unittest.main() From 947659eed8c0a675cd20c5f25c802b345a1dbab5 Mon Sep 17 00:00:00 2001 From: Austin Schuh Date: Mon, 23 Nov 2026 23:14:48 -0800 Subject: [PATCH 4/5] style: format the long path tests --- tests/bootstrap_impls/bootstrap_template_loader.py | 5 ++++- tests/bootstrap_impls/windows_long_paths_test.py | 4 +--- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/tests/bootstrap_impls/bootstrap_template_loader.py b/tests/bootstrap_impls/bootstrap_template_loader.py index 100d00a411..cc301723ad 100644 --- a/tests/bootstrap_impls/bootstrap_template_loader.py +++ b/tests/bootstrap_impls/bootstrap_template_loader.py @@ -61,5 +61,8 @@ def load_functions(rel_path: str, names: list[str]) -> dict: "sys": sys, "IS_WINDOWS": os.name == "nt", } - exec(compile(ast.Module(body=functions, type_ignores=[]), str(template), "exec"), module) + exec( + compile(ast.Module(body=functions, type_ignores=[]), str(template), "exec"), + module, + ) return module diff --git a/tests/bootstrap_impls/windows_long_paths_test.py b/tests/bootstrap_impls/windows_long_paths_test.py index e19b5760c3..8003fe558c 100644 --- a/tests/bootstrap_impls/windows_long_paths_test.py +++ b/tests/bootstrap_impls/windows_long_paths_test.py @@ -43,9 +43,7 @@ def test_prefix_is_only_added_when_needed(self) -> None: module["_long_paths_enabled"] = lambda: False self.assertEqual(add_prefix("C:\\short"), "C:\\short") self.assertEqual(add_prefix(long_path), _PREFIX + long_path) - self.assertEqual( - add_prefix(unc_path), _PREFIX + "UNC\\" + unc_path[2:] - ) + self.assertEqual(add_prefix(unc_path), _PREFIX + "UNC\\" + unc_path[2:]) self.assertEqual(add_prefix(_PREFIX + "C:\\x"), _PREFIX + "C:\\x") with self.subTest(name, long_paths_enabled=True): module["_long_paths_enabled"] = lambda: True From 79e6738c1f7039c4094e6646f1a104db00e5d2e5 Mon Sep 17 00:00:00 2001 From: Austin Schuh Date: Mon, 23 Nov 2026 23:24:11 -0800 Subject: [PATCH 5/5] fix: type the functions list for pyrefly --- tests/bootstrap_impls/bootstrap_template_loader.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/bootstrap_impls/bootstrap_template_loader.py b/tests/bootstrap_impls/bootstrap_template_loader.py index cc301723ad..04d3b567a6 100644 --- a/tests/bootstrap_impls/bootstrap_template_loader.py +++ b/tests/bootstrap_impls/bootstrap_template_loader.py @@ -48,7 +48,7 @@ def load_functions(rel_path: str, names: list[str]) -> dict: """ template = _template_path(rel_path) tree = ast.parse(template.read_text(encoding="utf-8")) - functions = [ + functions: list[ast.stmt] = [ node for node in tree.body if isinstance(node, ast.FunctionDef) and node.name in names