Skip to content

Commit d57287b

Browse files
committed
Fix OSError.winerror and errno/winerror converions
1 parent 79e7015 commit d57287b

15 files changed

Lines changed: 234 additions & 169 deletions

File tree

‎Cargo.lock‎

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎Cargo.toml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,7 @@ thiserror = "1.0"
8181
thread_local = "1.1.4"
8282
unicode_names2 = "1.1.0"
8383
widestring = "1.1.0"
84+
windows-sys = "0.52.0"
8485

8586
[features]
8687
default = ["threading", "stdlib", "zlib", "importlib"]

‎Lib/test/test_tempfile.py‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1418,7 +1418,6 @@ def do_create2(self, path, recurse=1, dirs=1, files=1):
14181418
with open(os.path.join(path, "test%d.txt" % i), "wb") as f:
14191419
f.write(b"Hello world!")
14201420

1421-
@unittest.expectedFailureIfWindows("TODO: RUSTPYTHON")
14221421
def test_mkdtemp_failure(self):
14231422
# Check no additional exception if mkdtemp fails
14241423
# Previously would raise AttributeError instead

‎common/Cargo.toml‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,3 +35,7 @@ volatile = "0.3"
3535

3636
[target.'cfg(windows)'.dependencies]
3737
widestring = { workspace = true }
38+
windows-sys = { workspace = true, features = [
39+
"Win32_Foundation",
40+
"Win32_Networking_WinSock",
41+
] }

‎common/src/crt_fd.rs‎

Lines changed: 3 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ pub type Offset = libc::c_longlong;
2323
#[inline]
2424
fn cvt<T, I: num_traits::PrimInt>(ret: I, f: impl FnOnce(I) -> T) -> io::Result<T> {
2525
if ret < I::zero() {
26-
Err(crate::os::errno())
26+
Err(crate::os::last_os_error())
2727
} else {
2828
Ok(f(ret))
2929
}
@@ -86,7 +86,7 @@ impl Fd {
8686
}
8787
}
8888

89-
impl io::Write for &Fd {
89+
impl io::Write for Fd {
9090
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
9191
let count = cmp::min(buf.len(), MAX_RW);
9292
cvt(
@@ -101,19 +101,7 @@ impl io::Write for &Fd {
101101
}
102102
}
103103

104-
impl io::Write for Fd {
105-
#[inline]
106-
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
107-
(&*self).write(buf)
108-
}
109-
110-
#[inline]
111-
fn flush(&mut self) -> io::Result<()> {
112-
(&*self).flush()
113-
}
114-
}
115-
116-
impl io::Read for &Fd {
104+
impl io::Read for Fd {
117105
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
118106
let count = cmp::min(buf.len(), MAX_RW);
119107
cvt(
@@ -122,10 +110,3 @@ impl io::Read for &Fd {
122110
)
123111
}
124112
}
125-
126-
impl io::Read for Fd {
127-
#[inline]
128-
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
129-
(&*self).read(buf)
130-
}
131-
}

‎common/src/os.rs‎

Lines changed: 173 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,26 +2,64 @@
22

33
use std::{io, str::Utf8Error};
44

5+
pub trait ErrorExt {
6+
fn posix_errno(&self) -> i32;
7+
}
8+
9+
impl ErrorExt for io::Error {
10+
#[cfg(not(windows))]
11+
fn posix_errno(&self) -> i32 {
12+
self.raw_os_error().unwrap_or(0)
13+
}
14+
#[cfg(windows)]
15+
fn posix_errno(&self) -> i32 {
16+
let winerror = self.raw_os_error().unwrap_or(0);
17+
winerror_to_errno(winerror)
18+
}
19+
}
20+
521
#[cfg(windows)]
6-
pub fn errno() -> io::Error {
22+
pub fn last_os_error() -> io::Error {
723
let err = io::Error::last_os_error();
824
// FIXME: probably not ideal, we need a bigger dichotomy between GetLastError and errno
925
if err.raw_os_error() == Some(0) {
1026
extern "C" {
1127
fn _get_errno(pValue: *mut i32) -> i32;
1228
}
13-
let mut e = 0;
14-
unsafe { suppress_iph!(_get_errno(&mut e)) };
15-
io::Error::from_raw_os_error(e)
29+
let mut errno = 0;
30+
unsafe { suppress_iph!(_get_errno(&mut errno)) };
31+
let errno = errno_to_winerror(errno);
32+
io::Error::from_raw_os_error(errno)
1633
} else {
1734
err
1835
}
1936
}
37+
2038
#[cfg(not(windows))]
21-
pub fn errno() -> io::Error {
39+
pub fn last_os_error() -> io::Error {
2240
io::Error::last_os_error()
2341
}
2442

43+
#[cfg(windows)]
44+
pub fn last_posix_errno() -> i32 {
45+
let err = io::Error::last_os_error();
46+
if err.raw_os_error() == Some(0) {
47+
extern "C" {
48+
fn _get_errno(pValue: *mut i32) -> i32;
49+
}
50+
let mut errno = 0;
51+
unsafe { suppress_iph!(_get_errno(&mut errno)) };
52+
errno
53+
} else {
54+
err.posix_errno()
55+
}
56+
}
57+
58+
#[cfg(not(windows))]
59+
pub fn last_posix_errno() -> i32 {
60+
last_os_error().posix_errno()
61+
}
62+
2563
#[cfg(unix)]
2664
pub fn bytes_as_osstr(b: &[u8]) -> Result<&std::ffi::OsStr, Utf8Error> {
2765
use std::os::unix::ffi::OsStrExt;
@@ -37,3 +75,133 @@ pub fn bytes_as_osstr(b: &[u8]) -> Result<&std::ffi::OsStr, Utf8Error> {
3775
pub use std::os::unix::ffi;
3876
#[cfg(target_os = "wasi")]
3977
pub use std::os::wasi::ffi;
78+
79+
#[cfg(windows)]
80+
pub fn errno_to_winerror(errno: i32) -> i32 {
81+
use libc::*;
82+
use windows_sys::Win32::Foundation::*;
83+
let winerror = match errno {
84+
ENOENT => ERROR_FILE_NOT_FOUND,
85+
E2BIG => ERROR_BAD_ENVIRONMENT,
86+
ENOEXEC => ERROR_BAD_FORMAT,
87+
EBADF => ERROR_INVALID_HANDLE,
88+
ECHILD => ERROR_WAIT_NO_CHILDREN,
89+
EAGAIN => ERROR_NO_PROC_SLOTS,
90+
ENOMEM => ERROR_NOT_ENOUGH_MEMORY,
91+
EACCES => ERROR_ACCESS_DENIED,
92+
EEXIST => ERROR_FILE_EXISTS,
93+
EXDEV => ERROR_NOT_SAME_DEVICE,
94+
ENOTDIR => ERROR_DIRECTORY,
95+
EMFILE => ERROR_TOO_MANY_OPEN_FILES,
96+
ENOSPC => ERROR_DISK_FULL,
97+
EPIPE => ERROR_BROKEN_PIPE,
98+
ENOTEMPTY => ERROR_DIR_NOT_EMPTY,
99+
EILSEQ => ERROR_NO_UNICODE_TRANSLATION,
100+
EINVAL => ERROR_INVALID_FUNCTION,
101+
_ => ERROR_INVALID_FUNCTION,
102+
};
103+
winerror as _
104+
}
105+
106+
// winerror: https://learn.microsoft.com/windows/win32/debug/system-error-codes--0-499-
107+
// errno: https://learn.microsoft.com/cpp/c-runtime-library/errno-constants?view=msvc-170
108+
#[cfg(windows)]
109+
pub fn winerror_to_errno(winerror: i32) -> i32 {
110+
use libc::*;
111+
use windows_sys::Win32::{
112+
Foundation::*,
113+
Networking::WinSock::{WSAEACCES, WSAEBADF, WSAEFAULT, WSAEINTR, WSAEINVAL, WSAEMFILE},
114+
};
115+
// Unwrap FACILITY_WIN32 HRESULT errors.
116+
// if ((winerror & 0xFFFF0000) == 0x80070000) {
117+
// winerror &= 0x0000FFFF;
118+
// }
119+
120+
// Winsock error codes (10000-11999) are errno values.
121+
if (10000..12000).contains(&winerror) {
122+
match winerror {
123+
WSAEINTR | WSAEBADF | WSAEACCES | WSAEFAULT | WSAEINVAL | WSAEMFILE => {
124+
// Winsock definitions of errno values. See WinSock2.h
125+
return winerror - 10000;
126+
}
127+
_ => return winerror as _,
128+
}
129+
}
130+
131+
#[allow(non_upper_case_globals)]
132+
match winerror as u32 {
133+
ERROR_FILE_NOT_FOUND
134+
| ERROR_PATH_NOT_FOUND
135+
| ERROR_INVALID_DRIVE
136+
| ERROR_NO_MORE_FILES
137+
| ERROR_BAD_NETPATH
138+
| ERROR_BAD_NET_NAME
139+
| ERROR_BAD_PATHNAME
140+
| ERROR_FILENAME_EXCED_RANGE => ENOENT,
141+
ERROR_BAD_ENVIRONMENT => E2BIG,
142+
ERROR_BAD_FORMAT
143+
| ERROR_INVALID_STARTING_CODESEG
144+
| ERROR_INVALID_STACKSEG
145+
| ERROR_INVALID_MODULETYPE
146+
| ERROR_INVALID_EXE_SIGNATURE
147+
| ERROR_EXE_MARKED_INVALID
148+
| ERROR_BAD_EXE_FORMAT
149+
| ERROR_ITERATED_DATA_EXCEEDS_64k
150+
| ERROR_INVALID_MINALLOCSIZE
151+
| ERROR_DYNLINK_FROM_INVALID_RING
152+
| ERROR_IOPL_NOT_ENABLED
153+
| ERROR_INVALID_SEGDPL
154+
| ERROR_AUTODATASEG_EXCEEDS_64k
155+
| ERROR_RING2SEG_MUST_BE_MOVABLE
156+
| ERROR_RELOC_CHAIN_XEEDS_SEGLIM
157+
| ERROR_INFLOOP_IN_RELOC_CHAIN => ENOEXEC,
158+
ERROR_INVALID_HANDLE | ERROR_INVALID_TARGET_HANDLE | ERROR_DIRECT_ACCESS_HANDLE => EBADF,
159+
ERROR_WAIT_NO_CHILDREN | ERROR_CHILD_NOT_COMPLETE => ECHILD,
160+
ERROR_NO_PROC_SLOTS | ERROR_MAX_THRDS_REACHED | ERROR_NESTING_NOT_ALLOWED => EAGAIN,
161+
ERROR_ARENA_TRASHED
162+
| ERROR_NOT_ENOUGH_MEMORY
163+
| ERROR_INVALID_BLOCK
164+
| ERROR_NOT_ENOUGH_QUOTA => ENOMEM,
165+
ERROR_ACCESS_DENIED
166+
| ERROR_CURRENT_DIRECTORY
167+
| ERROR_WRITE_PROTECT
168+
| ERROR_BAD_UNIT
169+
| ERROR_NOT_READY
170+
| ERROR_BAD_COMMAND
171+
| ERROR_CRC
172+
| ERROR_BAD_LENGTH
173+
| ERROR_SEEK
174+
| ERROR_NOT_DOS_DISK
175+
| ERROR_SECTOR_NOT_FOUND
176+
| ERROR_OUT_OF_PAPER
177+
| ERROR_WRITE_FAULT
178+
| ERROR_READ_FAULT
179+
| ERROR_GEN_FAILURE
180+
| ERROR_SHARING_VIOLATION
181+
| ERROR_LOCK_VIOLATION
182+
| ERROR_WRONG_DISK
183+
| ERROR_SHARING_BUFFER_EXCEEDED
184+
| ERROR_NETWORK_ACCESS_DENIED
185+
| ERROR_CANNOT_MAKE
186+
| ERROR_FAIL_I24
187+
| ERROR_DRIVE_LOCKED
188+
| ERROR_SEEK_ON_DEVICE
189+
| ERROR_NOT_LOCKED
190+
| ERROR_LOCK_FAILED
191+
| 35 => EACCES,
192+
ERROR_FILE_EXISTS | ERROR_ALREADY_EXISTS => EEXIST,
193+
ERROR_NOT_SAME_DEVICE => EXDEV,
194+
ERROR_DIRECTORY => ENOTDIR,
195+
ERROR_TOO_MANY_OPEN_FILES => EMFILE,
196+
ERROR_DISK_FULL => ENOSPC,
197+
ERROR_BROKEN_PIPE | ERROR_NO_DATA => EPIPE,
198+
ERROR_DIR_NOT_EMPTY => ENOTEMPTY,
199+
ERROR_NO_UNICODE_TRANSLATION => EILSEQ,
200+
ERROR_INVALID_FUNCTION
201+
| ERROR_INVALID_ACCESS
202+
| ERROR_INVALID_DATA
203+
| ERROR_INVALID_PARAMETER
204+
| ERROR_NEGATIVE_SEEK => EINVAL,
205+
_ => EINVAL,
206+
}
207+
}

‎stdlib/Cargo.toml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -117,7 +117,7 @@ features = [
117117
]
118118

119119
[target.'cfg(windows)'.dependencies.windows-sys]
120-
version = "0.52.0"
120+
workspace = true
121121
features = [
122122
"Win32_Networking_WinSock",
123123
"Win32_NetworkManagement_IpHelper",

‎stdlib/src/socket.rs‎

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ mod _socket {
1313
use crate::common::lock::{PyMappedRwLockReadGuard, PyRwLock, PyRwLockReadGuard};
1414
use crate::vm::{
1515
builtins::{PyBaseExceptionRef, PyListRef, PyStrRef, PyTupleRef, PyTypeRef},
16+
common::os::ErrorExt,
1617
convert::{IntoPyException, ToPyObject, TryFromBorrowedObject, TryFromObject},
1718
function::{ArgBytesLike, ArgMemoryBuffer, Either, FsPath, OptionalArg, OptionalOption},
1819
types::{DefaultConstructor, Initializer, Representable},
@@ -1018,7 +1019,7 @@ mod _socket {
10181019
let sock = self.sock()?;
10191020
let err = sock.take_error()?;
10201021
match err {
1021-
Some(e) if e.raw_os_error() == Some(libc::EISCONN) => Ok(()),
1022+
Some(e) if e.posix_errno() == libc::EISCONN => Ok(()),
10221023
Some(e) => Err(e),
10231024
// TODO: is this accurate?
10241025
None => Ok(()),
@@ -1408,7 +1409,7 @@ mod _socket {
14081409
)
14091410
};
14101411
if ret < 0 {
1411-
return Err(crate::common::os::errno().into());
1412+
return Err(crate::common::os::last_os_error().into());
14121413
}
14131414
Ok(vm.ctx.new_int(flag).into())
14141415
} else {
@@ -1429,7 +1430,7 @@ mod _socket {
14291430
)
14301431
};
14311432
if ret < 0 {
1432-
return Err(crate::common::os::errno().into());
1433+
return Err(crate::common::os::last_os_error().into());
14331434
}
14341435
buf.truncate(buflen as usize);
14351436
Ok(vm.ctx.new_bytes(buf).into())
@@ -1470,7 +1471,7 @@ mod _socket {
14701471
}
14711472
};
14721473
if ret < 0 {
1473-
Err(crate::common::os::errno().into())
1474+
Err(crate::common::os::last_os_error().into())
14741475
} else {
14751476
Ok(())
14761477
}
@@ -1694,10 +1695,7 @@ mod _socket {
16941695
fn errno(self) -> PyResult<i32> {
16951696
match self {
16961697
Self::Timeout => Ok(errcode!(EWOULDBLOCK)),
1697-
Self::Io(err) => {
1698-
// TODO: just unwrap()?
1699-
Ok(err.raw_os_error().unwrap_or(1))
1700-
}
1698+
Self::Io(err) => Ok(err.posix_errno()),
17011699
Self::Py(exc) => Err(exc),
17021700
}
17031701
}
@@ -2354,7 +2352,7 @@ mod _socket {
23542352
use windows_sys::Win32::Networking::WinSock::closesocket as close;
23552353
let ret = unsafe { close(x as _) };
23562354
if ret < 0 {
2357-
let err = crate::common::os::errno();
2355+
let err = crate::common::os::last_os_error();
23582356
if err.raw_os_error() != Some(errcode!(ECONNRESET)) {
23592357
return Err(err);
23602358
}

‎stdlib/src/ssl.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -680,7 +680,7 @@ mod _ssl {
680680
)
681681
};
682682
if ret != 1 {
683-
let errno = std::io::Error::last_os_error().raw_os_error().unwrap();
683+
let errno = crate::common::os::last_posix_errno();
684684
let err = if errno != 0 {
685685
crate::vm::stdlib::os::errno_err(vm)
686686
} else {

‎stdlib/src/termios.rs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ pub(crate) use self::termios::make_module;
44
mod termios {
55
use crate::vm::{
66
builtins::{PyBaseExceptionRef, PyBytes, PyInt, PyListRef, PyTypeRef},
7+
common::os::ErrorExt,
78
convert::ToPyObject,
89
PyObjectRef, PyResult, TryFromObject, VirtualMachine,
910
};
@@ -259,7 +260,7 @@ mod termios {
259260
vm.new_exception(
260261
error_type(vm),
261262
vec![
262-
err.raw_os_error().to_pyobject(vm),
263+
err.posix_errno().to_pyobject(vm),
263264
vm.ctx.new_str(err.to_string()).into(),
264265
],
265266
)

0 commit comments

Comments
 (0)