Skip to content

Commit fe63a40

Browse files
authored
bpo-38822: Fixed os.stat failing on inaccessible directories. (pythonGH-25527)
It would just fail if the path was inaccessible and had a trailing slash. It should fall back to the parent directory's metadata.
1 parent 2a3f489 commit fe63a40

File tree

2 files changed

+24
-2
lines changed

2 files changed

+24
-2
lines changed
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Fixed :func:`os.stat` failing on inaccessible directories with a trailing
2+
slash, rather than falling back to the parent directory's metadata. This
3+
implicitly affected :func:`os.path.exists` and :func:`os.path.isdir`.

Modules/posixmodule.c

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1851,9 +1851,28 @@ attributes_from_dir(LPCWSTR pszFile, BY_HANDLE_FILE_INFORMATION *info, ULONG *re
18511851
{
18521852
HANDLE hFindFile;
18531853
WIN32_FIND_DATAW FileData;
1854-
hFindFile = FindFirstFileW(pszFile, &FileData);
1855-
if (hFindFile == INVALID_HANDLE_VALUE)
1854+
LPCWSTR filename = pszFile;
1855+
size_t n = wcslen(pszFile);
1856+
if (n && (pszFile[n - 1] == L'\\' || pszFile[n - 1] == L'/')) {
1857+
// cannot use PyMem_Malloc here because we do not hold the GIL
1858+
filename = (LPCWSTR)malloc((n + 1) * sizeof(filename[0]));
1859+
wcsncpy_s((LPWSTR)filename, n + 1, pszFile, n);
1860+
while (--n > 0 && (filename[n] == L'\\' || filename[n] == L'/')) {
1861+
((LPWSTR)filename)[n] = L'\0';
1862+
}
1863+
if (!n || filename[n] == L':') {
1864+
// Nothing left te query
1865+
free((void *)filename);
1866+
return FALSE;
1867+
}
1868+
}
1869+
hFindFile = FindFirstFileW(filename, &FileData);
1870+
if (pszFile != filename) {
1871+
free((void *)filename);
1872+
}
1873+
if (hFindFile == INVALID_HANDLE_VALUE) {
18561874
return FALSE;
1875+
}
18571876
FindClose(hFindFile);
18581877
find_data_to_file_info(&FileData, info, reparse_tag);
18591878
return TRUE;

0 commit comments

Comments
 (0)