bpo-38030: Fix os.stat failures on block devices on Windows (GH-15681)
(cherry picked from commit 772ec0fad57412daa53d16d7019b6b2fe6e94942)
Co-authored-by: Steve Dower <steve.dower@python.org>
diff --git a/Modules/posixmodule.c b/Modules/posixmodule.c
index b9e8c0d..771c561 100644
--- a/Modules/posixmodule.c
+++ b/Modules/posixmodule.c
@@ -1793,13 +1793,13 @@
case ERROR_INVALID_PARAMETER:
case ERROR_INVALID_FUNCTION:
case ERROR_NOT_SUPPORTED:
- retval = -1;
+ /* Volumes and physical disks are block devices, e.g.
+ \\.\C: and \\.\PhysicalDrive0. */
+ memset(result, 0, sizeof(*result));
+ result->st_mode = 0x6000; /* S_IFBLK */
goto cleanup;
}
- /* Volumes and physical disks are block devices, e.g.
- \\.\C: and \\.\PhysicalDrive0. */
- memset(result, 0, sizeof(*result));
- result->st_mode = 0x6000; /* S_IFBLK */
+ retval = -1;
goto cleanup;
}
}
@@ -1826,7 +1826,14 @@
cleanup:
if (hFile != INVALID_HANDLE_VALUE) {
- CloseHandle(hFile);
+ /* Preserve last error if we are failing */
+ error = retval ? GetLastError() : 0;
+ if (!CloseHandle(hFile)) {
+ retval = -1;
+ } else if (retval) {
+ /* Restore last error */
+ SetLastError(error);
+ }
}
return retval;