Visitar URL original
Result of os.path.realpath("") is incorrect if cwd is on letter-less drive (\\?\-prefixed) · Issue #94696 · python/cpython · GitHub
The Wayback Machine - https://web.archive.org/web/20250415073242/https://github.com/python/cpython/issues/94696
Skip to content

Result of os.path.realpath("") is incorrect if cwd is on letter-less drive (\\?\-prefixed) #94696

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
grv87 opened this issue Jul 8, 2022 · 3 comments
Labels
OS-windows stdlib Python modules in the Lib dir type-bug An unexpected behavior, bug, or error

Comments

@grv87
Copy link

grv87 commented Jul 8, 2022

Bug report

  1. Create volume, dir on it, don't assign a drive letter
  2. In Python:
>>> import os
>>> os.chdir("\\\\?\\Volume{<uuid>}\\<dir>")
>>> os.path.realpath("")
'\\\\?\\Volume{<uuid>}\\<dir>\\.'

The dot is invalid in \\?\-prefixed path.
Dots (. and ..) are normalized by Windows API (at least on NTFS). But \\?\ paths bypass normalization and so may not contain dots. See, for example, here.
All later WinAPI calls with this path fail.

As a simple test, dir \\?\Volume{<uuid>}\dir\. doesn't work whereas dir \\?\Volume{<uuid>}\dir works.

P.S. os.path.realpath(".") gives the same invalid result

Your environment

CPython 3.10.0
Windows 10

Context
The problem arises from pip.
sys.path contains empty string (meaning current dir I presume).
And legacy installation method resolves sys.path relatively to cwd.

Investigation
Here:

path = join(cwd, path)

os.path.join still adds slash even if the second argument is empty. And if the path is ended with slash, dot is added somewhere below.

I fixed it to:

path = cwd if path == "." or path == "" else join(cwd, path)
@grv87 grv87 added the type-bug An unexpected behavior, bug, or error label Jul 8, 2022
@eryksun eryksun added OS-windows stdlib Python modules in the Lib dir labels Jul 10, 2022
@eryksun
Copy link
Contributor

eryksun commented Jul 10, 2022

This is not a supported use case. The Windows API doesn't support setting the working directory to be a device path (i.e. prefixed by "\\.\" or "\\?\"), even though WinAPI SetCurrentDirectoryW() doesn't outright fail. Only a path on a DOS drive or UNC share is supported, according to the API documentation:

Each process has a single current directory made up of two parts:

  • A disk designator that is either a drive letter followed by a colon, or a server name and share name (\\servername\sharename)
  • A directory on the disk designator

Here are a couple of examples that show undefined behavior. These examples use ctypes to ensure that the demonstrated behavior is not due to Python.

  1. GetCurrentDirectoryW() strips a trailing slash if it's not preceded by a colon.
    >>> kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)
    >>> buf = (ctypes.c_wchar * 260)()
    >>> kernel32.SetCurrentDirectoryW('\\\\?\\Volume{f3a6addf-0000-0000-0000-500600000000}\\')
    1
    >>> kernel32.GetCurrentDirectoryW(260, buf)
    48
    >>> buf.value
    '\\\\?\\Volume{f3a6addf-0000-0000-0000-500600000000}'

    >>> # The above path refers to the volume device, not the filesystem root directory.  
    >>> # To get the correct behavior, use a device name that ends with a colon 
    >>> # (e.g. "Z:" or "spam:").

    >>> kernel32.DefineDosDeviceW(0, 'spam:', r'\\?\Volume{f3a6addf-0000-0000-0000-500600000000}')
    1
    >>> kernel32.SetCurrentDirectoryW('\\\\?\\spam:\\')
    1
    >>> kernel32.GetCurrentDirectoryW(260, buf)
    10
    >>> buf.value
    '\\\\?\\spam:\\'
  1. The drive concept is not generalized to device paths. In this case, resolving a rooted path that lacks a drive (e.g. "\spam") ends up failing or otherwise misbehaving. The API ends up resolving the relative path against the unrelated NT path "\??\UNC", which is undefined behavior and can lead to absurd results.
    >>> kernel32.SetCurrentDirectoryW('\\\\?\\C:\\')
    1
    >>> kernel32.GetCurrentDirectoryW(260, buf) 
    7
    >>> buf.value
    '\\\\?\\C:\\'
    >>> kernel32.SetCurrentDirectoryW('\\')
    0
    >>> ctypes.get_last_error()
    123

    >>> kernel32.SetCurrentDirectoryW('\\\\?\\C:\\')
    1
    >>> kernel32.SetCurrentDirectoryW(r'\localhost\C$')
    1
    >>> kernel32.GetCurrentDirectoryW(260, buf)
    14
    >>> buf.value
    '\\\\localhost\\C$'

A script is just asking for problems if it sets a device path as the working directory. There's no practical benefit. In particular, using a "\\?\" extended device path does not allow the working directory to be a long path. The static buffer that's used for the current directory is hard limited to MAX_PATH (including a trailing backslash and terminating null) unless long-path support is enabled in Windows 10+.

Note that a volume device is not required to have a DOS drive-letter name to be used in a DOS path. It can be accessed seamlessly from a mounted directory in a DOS path (e.g. "C:\Mount\SpamVolume") as long as the mount point is registered as the canonical DOS name (e.g. via "mountvol.exe" or SetVolumeMountPointW()) by a system administrator.

realpath() design

The current implementation starts by calling normpath(). This isn't strictly correct for an extended device path (i.e. prefix "\\?\"). It's harmless for now because normpath() is designed to ignore device paths (i.e. prefixes "\\.\" and "\\?\"), but that's an old design flaw that should be fixed.

realpath() should start with path = os.fspath(path) and set up the path syntax variables. If the path isn't extended, call abspath() to superficially resolve the path via GetFullPathNameW().

        had_prefix = path.startswith(prefix)
        if not had_prefix:
            path = abspath(path)

This is the minimum to implement for any path for which nt._getfinalpathname() fails, i.e. a path that's either inaccessible via CreateFileW() or incompatible with GetFinalPathNameByHandleW() w/ VOLUME_NAME_DOS. Python's nt._getfinalpathname() does not support VOLUME_NAME_GUID paths.

@grv87
Copy link
Author

grv87 commented Jul 19, 2022

This is not a supported use case

This means that pip should be significantly rewritten.
Pip somewhere in the installation process resolves TEMP to the real path (which gets \\?\ prefix) and works with this path instead of the path set in TEMP (which has a drive letter).

Note that I use hundreds of apps and tools, and Python, pip and Modelio are the only ones with issues.

Should I report this as the final answer to pip?

@grv87
Copy link
Author

grv87 commented Jul 19, 2022

even though WinAPI SetCurrentDirectoryW() doesn't outright fail

IIRC, in legacy installation method pip starts new Python process (i.e. CreateProcessW) in specified dir. So, GetCurrentDirectoryW/SetCurrentDirectoryW tests may be not relevant.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
OS-windows stdlib Python modules in the Lib dir type-bug An unexpected behavior, bug, or error
Projects
None yet
Development

No branches or pull requests

2 participants