| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import enum |
| 4 |
from typing import TYPE_CHECKING, NewType, NoReturn, Protocol, TypeAlias, cast |
| 5 |
|
| 6 |
if TYPE_CHECKING: |
| 7 |
import cffi |
| 8 |
|
| 9 |
CData: TypeAlias = cffi.api.FFI.CData |
| 10 |
CType: TypeAlias = cffi.api.FFI.CType |
| 11 |
|
| 12 |
from ._generated_windows_ffi import ffi |
| 13 |
|
| 14 |
################################################################ |
| 15 |
# Functions and types |
| 16 |
################################################################ |
| 17 |
|
| 18 |
if not TYPE_CHECKING: |
| 19 |
CData: TypeAlias = ffi.CData |
| 20 |
CType: TypeAlias = ffi.CType |
| 21 |
|
| 22 |
AlwaysNull: TypeAlias = CData # We currently always pass ffi.NULL here. |
| 23 |
Handle = NewType("Handle", CData) |
| 24 |
HandleArray = NewType("HandleArray", CData) |
| 25 |
|
| 26 |
|
| 27 |
class _Kernel32(Protocol): |
| 28 |
"""Statically typed version of the kernel32.dll functions we use.""" |
| 29 |
|
| 30 |
def CreateIoCompletionPort( |
| 31 |
self, |
| 32 |
FileHandle: Handle, |
| 33 |
ExistingCompletionPort: CData | AlwaysNull, |
| 34 |
CompletionKey: int, |
| 35 |
NumberOfConcurrentThreads: int, |
| 36 |
/, |
| 37 |
) -> Handle: ... |
| 38 |
|
| 39 |
def CreateEventA( |
| 40 |
self, |
| 41 |
lpEventAttributes: AlwaysNull, |
| 42 |
bManualReset: bool, |
| 43 |
bInitialState: bool, |
| 44 |
lpName: AlwaysNull, |
| 45 |
/, |
| 46 |
) -> Handle: ... |
| 47 |
|
| 48 |
def SetFileCompletionNotificationModes( |
| 49 |
self, |
| 50 |
handle: Handle, |
| 51 |
flags: CompletionModes, |
| 52 |
/, |
| 53 |
) -> int: ... |
| 54 |
|
| 55 |
def PostQueuedCompletionStatus( |
| 56 |
self, |
| 57 |
CompletionPort: Handle, |
| 58 |
dwNumberOfBytesTransferred: int, |
| 59 |
dwCompletionKey: int, |
| 60 |
lpOverlapped: CData | AlwaysNull, |
| 61 |
/, |
| 62 |
) -> bool: ... |
| 63 |
|
| 64 |
def CancelIoEx( |
| 65 |
self, |
| 66 |
hFile: Handle, |
| 67 |
lpOverlapped: CData | AlwaysNull, |
| 68 |
/, |
| 69 |
) -> bool: ... |
| 70 |
|
| 71 |
def WriteFile( |
| 72 |
self, |
| 73 |
hFile: Handle, |
| 74 |
# not sure about this type |
| 75 |
lpBuffer: CData, |
| 76 |
nNumberOfBytesToWrite: int, |
| 77 |
lpNumberOfBytesWritten: AlwaysNull, |
| 78 |
lpOverlapped: _Overlapped, |
| 79 |
/, |
| 80 |
) -> bool: ... |
| 81 |
|
| 82 |
def ReadFile( |
| 83 |
self, |
| 84 |
hFile: Handle, |
| 85 |
# not sure about this type |
| 86 |
lpBuffer: CData, |
| 87 |
nNumberOfBytesToRead: int, |
| 88 |
lpNumberOfBytesRead: AlwaysNull, |
| 89 |
lpOverlapped: _Overlapped, |
| 90 |
/, |
| 91 |
) -> bool: ... |
| 92 |
|
| 93 |
def GetQueuedCompletionStatusEx( |
| 94 |
self, |
| 95 |
CompletionPort: Handle, |
| 96 |
lpCompletionPortEntries: CData, |
| 97 |
ulCount: int, |
| 98 |
ulNumEntriesRemoved: CData, |
| 99 |
dwMilliseconds: int, |
| 100 |
fAlertable: bool | int, |
| 101 |
/, |
| 102 |
) -> CData: ... |
| 103 |
|
| 104 |
def CreateFileW( |
| 105 |
self, |
| 106 |
lpFileName: CData, |
| 107 |
dwDesiredAccess: FileFlags, |
| 108 |
dwShareMode: FileFlags, |
| 109 |
lpSecurityAttributes: AlwaysNull, |
| 110 |
dwCreationDisposition: FileFlags, |
| 111 |
dwFlagsAndAttributes: FileFlags, |
| 112 |
hTemplateFile: AlwaysNull, |
| 113 |
/, |
| 114 |
) -> Handle: ... |
| 115 |
|
| 116 |
def WaitForSingleObject(self, hHandle: Handle, dwMilliseconds: int, /) -> CData: ... |
| 117 |
|
| 118 |
def WaitForMultipleObjects( |
| 119 |
self, |
| 120 |
nCount: int, |
| 121 |
lpHandles: HandleArray, |
| 122 |
bWaitAll: bool, |
| 123 |
dwMilliseconds: int, |
| 124 |
/, |
| 125 |
) -> ErrorCodes: ... |
| 126 |
|
| 127 |
def SetEvent(self, handle: Handle, /) -> None: ... |
| 128 |
|
| 129 |
def CloseHandle(self, handle: Handle, /) -> bool: ... |
| 130 |
|
| 131 |
def DeviceIoControl( |
| 132 |
self, |
| 133 |
hDevice: Handle, |
| 134 |
dwIoControlCode: int, |
| 135 |
# this is wrong (it's not always null) |
| 136 |
lpInBuffer: AlwaysNull, |
| 137 |
nInBufferSize: int, |
| 138 |
# this is also wrong |
| 139 |
lpOutBuffer: AlwaysNull, |
| 140 |
nOutBufferSize: int, |
| 141 |
lpBytesReturned: AlwaysNull, |
| 142 |
lpOverlapped: CData, |
| 143 |
/, |
| 144 |
) -> bool: ... |
| 145 |
|
| 146 |
|
| 147 |
class _Nt(Protocol): |
| 148 |
"""Statically typed version of the dtdll.dll functions we use.""" |
| 149 |
|
| 150 |
def RtlNtStatusToDosError(self, status: int, /) -> ErrorCodes: ... |
| 151 |
|
| 152 |
|
| 153 |
class _Ws2(Protocol): |
| 154 |
"""Statically typed version of the ws2_32.dll functions we use.""" |
| 155 |
|
| 156 |
def WSAGetLastError(self) -> int: ... |
| 157 |
|
| 158 |
def WSAIoctl( |
| 159 |
self, |
| 160 |
socket: CData, |
| 161 |
dwIoControlCode: WSAIoctls, |
| 162 |
lpvInBuffer: AlwaysNull, |
| 163 |
cbInBuffer: int, |
| 164 |
lpvOutBuffer: CData, |
| 165 |
cbOutBuffer: int, |
| 166 |
lpcbBytesReturned: CData, # int* |
| 167 |
lpOverlapped: AlwaysNull, |
| 168 |
# actually LPWSAOVERLAPPED_COMPLETION_ROUTINE |
| 169 |
lpCompletionRoutine: AlwaysNull, |
| 170 |
/, |
| 171 |
) -> int: ... |
| 172 |
|
| 173 |
|
| 174 |
class _DummyStruct(Protocol): |
| 175 |
Offset: int |
| 176 |
OffsetHigh: int |
| 177 |
|
| 178 |
|
| 179 |
class _DummyUnion(Protocol): |
| 180 |
DUMMYSTRUCTNAME: _DummyStruct |
| 181 |
Pointer: object |
| 182 |
|
| 183 |
|
| 184 |
class _Overlapped(Protocol): |
| 185 |
Internal: int |
| 186 |
InternalHigh: int |
| 187 |
DUMMYUNIONNAME: _DummyUnion |
| 188 |
hEvent: Handle |
| 189 |
|
| 190 |
|
| 191 |
kernel32 = cast("_Kernel32", ffi.dlopen("kernel32.dll")) |
| 192 |
ntdll = cast("_Nt", ffi.dlopen("ntdll.dll")) |
| 193 |
ws2_32 = cast("_Ws2", ffi.dlopen("ws2_32.dll")) |
| 194 |
|
| 195 |
################################################################ |
| 196 |
# Magic numbers |
| 197 |
################################################################ |
| 198 |
|
| 199 |
# Here's a great resource for looking these up: |
| 200 |
# https://www.magnumdb.com |
| 201 |
# (Tip: check the box to see "Hex value") |
| 202 |
|
| 203 |
INVALID_HANDLE_VALUE = Handle(ffi.cast("HANDLE", -1)) |
| 204 |
|
| 205 |
|
| 206 |
class ErrorCodes(enum.IntEnum): |
| 207 |
STATUS_TIMEOUT = 0x102 |
| 208 |
WAIT_TIMEOUT = 0x102 |
| 209 |
WAIT_ABANDONED = 0x80 |
| 210 |
WAIT_OBJECT_0 = 0x00 # object is signaled |
| 211 |
WAIT_FAILED = 0xFFFFFFFF |
| 212 |
ERROR_IO_PENDING = 997 |
| 213 |
ERROR_OPERATION_ABORTED = 995 |
| 214 |
ERROR_ABANDONED_WAIT_0 = 735 |
| 215 |
ERROR_INVALID_HANDLE = 6 |
| 216 |
ERROR_INVALID_PARAMETER = 87 |
| 217 |
ERROR_NOT_FOUND = 1168 |
| 218 |
ERROR_NOT_SOCKET = 10038 |
| 219 |
|
| 220 |
|
| 221 |
class FileFlags(enum.IntFlag): |
| 222 |
GENERIC_READ = 0x80000000 |
| 223 |
SYNCHRONIZE = 0x00100000 |
| 224 |
FILE_FLAG_OVERLAPPED = 0x40000000 |
| 225 |
FILE_SHARE_READ = 1 |
| 226 |
FILE_SHARE_WRITE = 2 |
| 227 |
FILE_SHARE_DELETE = 4 |
| 228 |
CREATE_NEW = 1 |
| 229 |
CREATE_ALWAYS = 2 |
| 230 |
OPEN_EXISTING = 3 |
| 231 |
OPEN_ALWAYS = 4 |
| 232 |
TRUNCATE_EXISTING = 5 |
| 233 |
|
| 234 |
|
| 235 |
class AFDPollFlags(enum.IntFlag): |
| 236 |
# These are drawn from a combination of: |
| 237 |
# https://github.com/piscisaureus/wepoll/blob/master/src/afd.h |
| 238 |
# https://github.com/reactos/reactos/blob/master/sdk/include/reactos/drivers/afd/shared.h |
| 239 |
AFD_POLL_RECEIVE = 0x0001 |
| 240 |
AFD_POLL_RECEIVE_EXPEDITED = 0x0002 # OOB/urgent data |
| 241 |
AFD_POLL_SEND = 0x0004 |
| 242 |
AFD_POLL_DISCONNECT = 0x0008 # received EOF (FIN) |
| 243 |
AFD_POLL_ABORT = 0x0010 # received RST |
| 244 |
AFD_POLL_LOCAL_CLOSE = 0x0020 # local socket object closed |
| 245 |
AFD_POLL_CONNECT = 0x0040 # socket is successfully connected |
| 246 |
AFD_POLL_ACCEPT = 0x0080 # you can call accept on this socket |
| 247 |
AFD_POLL_CONNECT_FAIL = 0x0100 # connect() terminated unsuccessfully |
| 248 |
# See WSAEventSelect docs for more details on these four: |
| 249 |
AFD_POLL_QOS = 0x0200 |
| 250 |
AFD_POLL_GROUP_QOS = 0x0400 |
| 251 |
AFD_POLL_ROUTING_INTERFACE_CHANGE = 0x0800 |
| 252 |
AFD_POLL_EVENT_ADDRESS_LIST_CHANGE = 0x1000 |
| 253 |
|
| 254 |
|
| 255 |
class WSAIoctls(enum.IntEnum): |
| 256 |
SIO_BASE_HANDLE = 0x48000022 |
| 257 |
SIO_BSP_HANDLE_SELECT = 0x4800001C |
| 258 |
SIO_BSP_HANDLE_POLL = 0x4800001D |
| 259 |
|
| 260 |
|
| 261 |
class CompletionModes(enum.IntFlag): |
| 262 |
FILE_SKIP_COMPLETION_PORT_ON_SUCCESS = 0x1 |
| 263 |
FILE_SKIP_SET_EVENT_ON_HANDLE = 0x2 |
| 264 |
|
| 265 |
|
| 266 |
class IoControlCodes(enum.IntEnum): |
| 267 |
IOCTL_AFD_POLL = 0x00012024 |
| 268 |
|
| 269 |
|
| 270 |
################################################################ |
| 271 |
# Generic helpers |
| 272 |
################################################################ |
| 273 |
|
| 274 |
|
| 275 |
def _handle(obj: int | CData) -> Handle: |
| 276 |
# For now, represent handles as either cffi HANDLEs or as ints. If you |
| 277 |
# try to pass in a file descriptor instead, it's not going to work |
| 278 |
# out. (For that msvcrt.get_osfhandle does the trick, but I don't know if |
| 279 |
# we'll actually need that for anything...) For sockets this doesn't |
| 280 |
# matter, Python never allocates an fd. So let's wait until we actually |
| 281 |
# encounter the problem before worrying about it. |
| 282 |
if isinstance(obj, int): |
| 283 |
return Handle(ffi.cast("HANDLE", obj)) |
| 284 |
return Handle(obj) |
| 285 |
|
| 286 |
|
| 287 |
def handle_array(count: int) -> HandleArray: |
| 288 |
"""Make an array of handles.""" |
| 289 |
return HandleArray(ffi.new(f"HANDLE[{count}]")) |
| 290 |
|
| 291 |
|
| 292 |
def raise_winerror( |
| 293 |
winerror: int | None = None, |
| 294 |
*, |
| 295 |
filename: str | None = None, |
| 296 |
filename2: str | None = None, |
| 297 |
) -> NoReturn: |
| 298 |
# assert sys.platform == "win32" # TODO: make this work in MyPy |
| 299 |
# ... in the meanwhile, ffi.getwinerror() is undefined on non-Windows, necessitating the type |
| 300 |
# ignores. |
| 301 |
|
| 302 |
if winerror is None: |
| 303 |
err = ffi.getwinerror() # type: ignore[attr-defined,unused-ignore] |
| 304 |
if err is None: |
| 305 |
raise RuntimeError("No error set?") |
| 306 |
winerror, msg = err |
| 307 |
else: |
| 308 |
err = ffi.getwinerror(winerror) # type: ignore[attr-defined,unused-ignore] |
| 309 |
if err is None: |
| 310 |
raise RuntimeError("No error set?") |
| 311 |
_, msg = err |
| 312 |
# https://docs.python.org/3/library/exceptions.html#OSError |
| 313 |
raise OSError(0, msg, filename, winerror, filename2) |