Skip to content

gh-122143: Fix os.path.splitroot() and os.path.normpath() for undecodable bytes paths on Windows#154585

Open
gianghungtien wants to merge 1 commit into
python:mainfrom
gianghungtien:gh-122143-ntpath-undecodable-bytes
Open

gh-122143: Fix os.path.splitroot() and os.path.normpath() for undecodable bytes paths on Windows#154585
gianghungtien wants to merge 1 commit into
python:mainfrom
gianghungtien:gh-122143-ntpath-undecodable-bytes

Conversation

@gianghungtien

Copy link
Copy Markdown
Contributor

On Windows, os.path.splitroot() and os.path.splitdrive() raise UnicodeDecodeError for a bytes path that is not valid UTF-8:

>>> ntpath.splitroot(b"foo\x88")
Traceback (most recent call last):
  ...
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x88 in position 3: invalid start byte

3.12 returned (b'', b'', b'foo\x88'), and POSIX still does. The regression came with GH-118089 (gh-102511), which routed splitroot() through the native helper nt._path_splitroot_ex(). os.path.normpath() has the same problem via nt._path_normpath(), added slightly earlier in 3.12.

Both helpers declare path: path_t(make_wide=True, ...), so path_converter() decodes a bytes argument with the filesystem encoding before the implementation runs. On Windows that encoding is UTF-8 with the surrogatepass error handler, not surrogateescape, so bytes that are not valid UTF-8 simply fail to decode. Nothing about splitting or normalizing a path actually requires a decodable path — the syntax characters (\, /, :) are ASCII — which is why the pure Python implementations handle these paths fine on every other platform.

The fix

This implements the approach eryksun suggested on the issue: let the native helpers fall back to the pure Python implementation for paths they cannot convert.

  • path_converter() keeps the original object in path->object when suppress_value_error swallows a ValueError, instead of clearing it, so the caller can still see what it was given. The six existing users of suppress_value_error (_path_exists(), _path_isdir(), …) return False on path->value_error without touching path->object, so they are unaffected.
  • os._path_splitroot_ex() and os._path_normpath() enable suppress_value_error and delegate to os.path._splitroot_fallback() / os.path._normpath_fallback() when the conversion failed. With nonstrict=True already set, the embedded-null and path-length checks are skipped, so a decode failure is the only ValueError the converter can produce here.
  • ntpath and posixpath now always define the pure Python implementations and bind the accelerated versions over the top, exposing the originals under private names. This is the reverse of the try: from nt import … except ImportError: shape introduced by gh-102511: Add C implementation of os.path.splitroot() #118089; the diff is mostly re-indentation.

The alternative discussed on the issue — changing the Windows filesystem error handler to surrogateescape — is a much broader change to PEP 529 behaviour, so I left it alone.

The other route to a decode failure, sys._enablelegacywindowsfsencoding(), is unaffected: legacy mode uses mbcs with the replace error handler, which does not fail.

Behaviour changes

os.path.split(), os.path.abspath() and os.path.realpath() are built on these two helpers, so they stop raising too, and now match what they already do on POSIX:

call before after
splitroot(b"\\\\\xff\\share\\dir") UnicodeDecodeError (b'\\\\\xff\\share', b'\\', b'dir')
splitdrive(b"foo\x88") UnicodeDecodeError (b'', b'foo\x88')
normpath(b"\xff\\..\\foo") UnicodeDecodeError b'foo'
split(b"c:\\\xff\\bar") UnicodeDecodeError (b'c:\\\xff', b'bar')
abspath(b"c:\\\xff\\..\\foo") UnicodeDecodeError b'c:\\foo'

realpath() is the one case that does not simply start succeeding. It already has a branch for paths that cannot be handed to the OS — except ValueError for embedded nulls (gh-106242) — and undecodable paths now land in it: non-strict returns the absolute path as-is, and the strict modes raise OSError. That is the same treatment realpath(ABSTFN + b"\x00") gets today, so test_realpath_invalid_unicode_paths is now written in the same shape as the neighbouring test_realpath_invalid_paths.

For a path that is decodable, nothing changes: the native helper still does all the work, and the fallback is reached only on the error path.

Tests

test_ntpath already covered these inputs, asserting UnicodeDecodeError under if sys.platform == 'win32' and the correct result under else. Those five branches (test_splitroot_invalid_paths, test_splitdrive_invalid_paths, test_split_invalid_paths, test_normpath_invalid_paths, test_abspath_invalid_paths) collapse into a single platform-independent expectation, plus a FakePath case that exercises the __fspath__() result being what gets passed to the fallback. test_realpath_invalid_unicode_paths no longer needs to be parameterized over strict, since the four modes now differ.

Verified on Windows with PCbuild\build.bat -p x64 -c Debug:

  • test_ntpath, test_posixpath, test_genericpath, test_os, test_pathlib, test_glob, test_tarfile, test_import, test_zipimport, test_runpy, test_compileall, test_fileinput, test_subprocess, test_tempfile, test_unicode_file, test_unicode_file_functions — all pass.
  • -R 3:3 on test_ntpath, test_posixpath and test_os — no leaks, which was the point worth checking given the reference handling moved in path_converter().
  • All six updated tests fail against an unpatched build (checked by reverting Lib/ntpath.py, Lib/posixpath.py and Modules/posixmodule.c to main and rebuilding, keeping the new tests).

…ndecodable bytes paths on Windows

The native helpers nt._path_splitroot_ex() and nt._path_normpath() convert
the path to a wide string first, so a bytes path which cannot be decoded
with the filesystem encoding (UTF-8 with the "surrogatepass" error handler
on Windows) failed with UnicodeDecodeError.  os.path.splitroot() and
os.path.splitdrive() regressed this way in 3.13, when the native helper was
added; os.path.normpath() has behaved this way since the native helper was
added in 3.12.

Enable suppress_value_error for both helpers and delegate such paths to the
pure Python implementations, which operate on bytes directly, as they
already do on POSIX.  path_converter() now keeps the original object when it
suppresses a ValueError, so that the fallback can be given the path.

This also fixes os.path.split(), os.path.abspath() and os.path.realpath(),
which are built on top of the two helpers.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant