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
Open
Conversation
…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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
On Windows,
os.path.splitroot()andos.path.splitdrive()raiseUnicodeDecodeErrorfor abytespath 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 byte3.12 returned
(b'', b'', b'foo\x88'), and POSIX still does. The regression came with GH-118089 (gh-102511), which routedsplitroot()through the native helpernt._path_splitroot_ex().os.path.normpath()has the same problem viant._path_normpath(), added slightly earlier in 3.12.Both helpers declare
path: path_t(make_wide=True, ...), sopath_converter()decodes abytesargument with the filesystem encoding before the implementation runs. On Windows that encoding is UTF-8 with thesurrogatepasserror handler, notsurrogateescape, 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 inpath->objectwhensuppress_value_errorswallows aValueError, instead of clearing it, so the caller can still see what it was given. The six existing users ofsuppress_value_error(_path_exists(),_path_isdir(), …) returnFalseonpath->value_errorwithout touchingpath->object, so they are unaffected.os._path_splitroot_ex()andos._path_normpath()enablesuppress_value_errorand delegate toos.path._splitroot_fallback()/os.path._normpath_fallback()when the conversion failed. Withnonstrict=Truealready set, the embedded-null and path-length checks are skipped, so a decode failure is the onlyValueErrorthe converter can produce here.ntpathandposixpathnow 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 thetry: from nt import … except ImportError:shape introduced by gh-102511: Add C implementation ofos.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 thereplaceerror handler, which does not fail.Behaviour changes
os.path.split(),os.path.abspath()andos.path.realpath()are built on these two helpers, so they stop raising too, and now match what they already do on POSIX: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")UnicodeDecodeErrorb'foo'split(b"c:\\\xff\\bar")UnicodeDecodeError(b'c:\\\xff', b'bar')abspath(b"c:\\\xff\\..\\foo")UnicodeDecodeErrorb'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 ValueErrorfor embedded nulls (gh-106242) — and undecodable paths now land in it: non-strict returns the absolute path as-is, and the strict modes raiseOSError. That is the same treatmentrealpath(ABSTFN + b"\x00")gets today, sotest_realpath_invalid_unicode_pathsis now written in the same shape as the neighbouringtest_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_ntpathalready covered these inputs, assertingUnicodeDecodeErrorunderif sys.platform == 'win32'and the correct result underelse. 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 aFakePathcase that exercises the__fspath__()result being what gets passed to the fallback.test_realpath_invalid_unicode_pathsno longer needs to be parameterized overstrict, 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:3ontest_ntpath,test_posixpathandtest_os— no leaks, which was the point worth checking given the reference handling moved inpath_converter().Lib/ntpath.py,Lib/posixpath.pyandModules/posixmodule.ctomainand rebuilding, keeping the new tests).ntpath.splitrootraisesUnicodeDecodeErrorwhen givenbyteson Windows #122143