Debian Codegraph @

pypy/module/_io/interp_win32consoleio.py

raw symbols SCIP
1 import sys
2 import os
3
4
5 from pypy.interpreter.error import OperationError, oefmt
6 from pypy.interpreter.typedef import (
7 TypeDef, generic_new_descr, GetSetProperty)
8 from pypy.interpreter.gateway import WrappedDefault, interp2app, unwrap_spec
9 from pypy.module._io.interp_iobase import (W_RawIOBase, convert_size,
10 DEFAULT_BUFFER_SIZE)
11 from pypy.module.time.interp_time import time_sleep
12 from pypy.interpreter.unicodehelper import (str_decode_utf_16,
13 utf8_encode_utf_16)
14 from pypy.module._codecs.interp_codecs import CodecState
15 from rpython.rtyper.lltypesystem import lltype, rffi
16 from rpython.rlib._os_support import utf8_traits
17 from rpython.rlib import rwin32
18 from rpython.rlib.rstring import StringBuilder
19 from rpython.rlib.rwin32file import make_win32_traits
20 from rpython.rlib.buffer import ByteBuffer
21 from rpython.rlib.rarithmetic import intmask
22 from rpython.rlib.rposix import getfullpathname
23
24 # SMALLBUF determines how many utf-8 characters will be
25 # buffered within the stream, in order to support reads
26 # of less than one character
27 SMALLBUF = 4
28 # BUFMAX determines how many bytes can be read in one go.
29 # BUFSIZ is compiler/platform dependant and defined in stdio.h,
30 # but the actual values don't matter all that much
31 BUFMAX = (32*1024*1024)
32 BUFSIZ = 512
33
34 def err_closed(space):
35 return oefmt(space.w_ValueError,
36 "I/O operation on closed file")
37
38 def err_mode(space, state):
39 # TODO sort out the state
40 return oefmt(space.w_ValueError,
41 "I/O operation on closed file")
42
43 def read_console_wide(space, handle, maxlen):
44 """
45 Make a blocking call to ReadConsoleW, returns wchar-encoded bytes
46 """
47 err = 0
48 sig = 0
49 # Windows uses a 16-bit wchar_t, we mimic that with bytes
50 buf = ByteBuffer((maxlen + 2) * 2)
51 addr = buf.get_raw_address()
52 off = 0 # offset from the beginning of buf, in wchar
53 # readlen is in 16 bits, readlen_b is in 8-bit bytes
54 readlen = readlen_b = 0
55 bufsize = BUFSIZ
56 with lltype.scoped_alloc(rwin32.LPDWORD.TO, 1) as n:
57 while readlen_b < maxlen:
58 neg_one = rffi.cast(rwin32.DWORD, -1)
59 n[0] = neg_one
60 length = min(maxlen - off, bufsize)
61 rwin32.SetLastError_saved(0)
62 res = rwin32.ReadConsoleW(handle,
63 rffi.cast(rwin32.LPWSTR, rffi.ptradd(addr, readlen_b)),
64 length, n, rffi.cast(rwin32.LPVOID, 0))
65 nread = intmask(n[0])
66 err = rwin32.GetLastError_saved()
67 if not res:
68 break
69
70 if nread == -1 and err == rwin32.ERROR_OPERATION_ABORTED:
71 break
72
73
74 if nread == 0:
75 if err != rwin32.ERROR_OPERATION_ABORTED:
76 break
77 err = 0
78 # This will only catch CTRL-C on the main thread
79 time_sleep(space, space.newfloat(0.1))
80 continue
81 readlen += nread
82 readlen_b = 2 * readlen
83
84 # We didn't manage to read the whole buffer
85 # don't try again as it will just block
86 if nread < length:
87 break
88
89 if buf.getitem(readlen_b - 2) == '\n':
90 # We read a new line
91 break
92
93 # If the buffer ends with a high surrogate, take an extra character.
94 if (readlen_b + 1) >= maxlen:
95 with lltype.scoped_alloc(rwin32.LPWORD.TO, 1) as char_type:
96 ptr = rffi.cast(rffi.CWCHARP, rffi.ptradd(addr, + 1))
97 rwin32.GetStringTypeW(rwin32.CT_CTYPE3, ptr, 1, char_type)
98 if intmask(char_type[0]) == intmask(rwin32.C3_HIGHSURROGATE):
99 readlen_b += 2
100 break
101 if err:
102 raise OperationError(space.w_WindowsError, space.newint(err))
103 if readlen_b <=0 or buf.getitem(0) == '\x1a':
104 return ''
105 else:
106 return buf.getslice(0, 1, readlen_b)
107
108
109 def _get_console_type(handle):
110 mode = lltype.malloc(rwin32.LPDWORD.TO,0,flavor='raw')
111 peek_count = lltype.malloc(rwin32.LPDWORD.TO,0,flavor='raw')
112 try:
113 if handle == rwin32.INVALID_HANDLE_VALUE:
114 return '\0'
115
116 if not rwin32.GetConsoleMode(handle, mode):
117 return '\0'
118
119 # Peek at the handle to see whether it is an input or output handle
120 if rwin32.GetNumberOfConsoleInputEvents(handle, peek_count):
121 return 'r'
122 return 'w'
123 finally:
124 lltype.free(mode, flavor='raw')
125 lltype.free(peek_count, flavor='raw')
126
127 def _pyio_get_console_type(space, w_path_or_fd):
128
129 # XXX 2021-01-10 Disable WinConsoleIO (again) it is flaky. Some interaction
130 # with pytest in running numpy's tests makes the handle invalid.
131 # TODO: refactor the w_path_or_fd handling to be more like interp_posix
132 # and use the path_or_fd() unwrap_spec all through the _io module
133 # Then this will recieve a already-processed Path object
134 # Another alternative to this whole mess would be to adapt the ctypes-based
135 # https://pypi.org/project/win_unicode_console/ which also implements PEP 528
136
137 enable_winconsoleio = os.environ.get("PYPY_ENABLE_WINCONSOLEIO")
138 if not enable_winconsoleio:
139 return '\0'
140
141 if space.isinstance_w(w_path_or_fd, space.w_int):
142 fd = space.int_w(w_path_or_fd)
143 try:
144 handle = rwin32.get_osfhandle(fd)
145 except OSError:
146 return '\0'
147 return _get_console_type(handle)
148
149 encoded = space.fsencode_w(w_path_or_fd)
150 if not encoded:
151 return '\0'
152
153 m = '\0'
154
155 # In CPython the _wcsicmp function is used to perform case insensitive comparison
156 dlower = encoded.lower()
157 if len(dlower) >=4:
158 if dlower[:4] == '\\\\.\\' or dlower[:4] == '\\\\?\\':
159 dlower = dlower[4:]
160 if dlower[:4] == '//./' or dlower[:4] == '//?/':
161 dlower = dlower[4:]
162 elif dlower[:3] == 'c:\\':
163 dlower = dlower[3:]
164 if dlower == 'conin$':
165 m = 'r'
166 elif dlower == 'conout$':
167 m = 'w'
168 elif dlower == 'con':
169 m = 'x'
170 if m != '\0':
171 return m
172
173 # Handle things like 'c:\users\user\appdata\local\temp\usession\CONOUT$
174 dlower = getfullpathname(encoded).lower()
175 if dlower[:4] == '\\\\.\\' or dlower[:4] == '\\\\?\\':
176 dlower = dlower[4:]
177 if dlower == 'conin$':
178 m = 'r'
179 elif dlower == 'conout$':
180 m = 'w'
181 elif dlower == 'con':
182 m = 'x'
183 return m
184
185
186 class W_WinConsoleIO(W_RawIOBase):
187 def __init__(self, space):
188 W_RawIOBase.__init__(self, space)
189 self.handle = rwin32.INVALID_HANDLE_VALUE
190 self.fd = -1
191 self.created = 0
192 self.readable = False
193 self.writable = False
194 self.closehandle = False
195 self.blksize = 0
196 self.buf = ''
197
198 def _dealloc_warn_w(self, space, w_source):
199 buf = self.buf
200 if buf:
201 lltype.free(buf, flavor='raw')
202
203 def _getbuffer(self, length):
204 """ Get up to length wchar from self.buf
205 """
206
207 wlen = self._buflen()
208 if wlen > length:
209 wlen = length
210 blen = wlen * 2
211 if blen <= 0:
212 return ''
213 ret = self.buf[:blen]
214 self.buf = self.buf[blen:]
215 # trim out any leading '\x00'
216 while self.buf and self.buf[0] == '\x00':
217 self.buf == self.buf[2:]
218 return ret
219
220 def _buflen(self):
221 """ get length of self.buf in wchar
222 """
223 wlen = len(self.buf) // 2
224 for i in range(0, wlen * 2, 2):
225 if self.buf[i] != '\x00':
226 return i // 2
227 return wlen
228
229 @unwrap_spec(mode='text', closefd=int)
230 def descr_init(self, space, w_nameobj, mode='r', closefd=True, w_opener=None):
231 name = rffi.cast(rffi.CWCHARP, 0)
232 self.fd = -1
233 self.handle = rwin32.INVALID_HANDLE_VALUE
234 self.readable = False
235 self.writable = False
236 self.blksize = 0
237 rwa = False
238 console_type = '\0'
239 self.buf = ''
240
241 if space.isinstance_w(w_nameobj, space.w_int):
242 self.fd = space.int_w(w_nameobj)
243 if self.fd < 0:
244 raise oefmt(space.w_ValueError,
245 "negative file descriptor")
246
247 # make the flow analysis happy,otherwise it thinks w_path
248 # is undefined later
249 w_path = w_nameobj
250 if self.fd < 0:
251 from pypy.module.posix.interp_posix import fspath
252 w_path = fspath(space, w_nameobj)
253 console_type = _pyio_get_console_type(space, w_path)
254 if not console_type:
255 raise oefmt(space.w_ValueError,
256 "Invalid console type")
257 if console_type == '\0':
258 raise oefmt(space.w_ValueError,
259 "Cannot open non-console file")
260 self.mode = 'u'
261 for char in mode:
262 if char in "+ax":
263 # OK do nothing
264 pass
265 elif char == "b":
266 self.mode = 'b'
267 elif char == "r":
268 if rwa:
269 raise oefmt(space.w_ValueError,
270 "invalid mode: %s", mode)
271 rwa = True
272 self.readable = True
273 if console_type == "x":
274 console_type = "r"
275 elif char == "w":
276 if rwa:
277 raise oefmt(space.w_ValueError,
278 "invalid mode: %s", mode)
279 rwa = True
280 self.writable = True
281 if console_type == 'x':
282 console_type = 'w'
283 else:
284 raise oefmt(space.w_ValueError,
285 "invalid mode: %s", mode)
286 if not rwa:
287 raise oefmt(space.w_ValueError,
288 "Must have exactly one of read or write mode")
289
290 if self.fd >= 0:
291 self.handle = rwin32.get_osfhandle(self.fd)
292 self.closehandle = False
293 else:
294 access = rwin32.GENERIC_READ
295 self.closehandle = True
296 if not closefd:
297 raise oefmt(space.w_ValueError,
298 "Cannot use closefd=False with a file name")
299 if self.writable:
300 access = rwin32.GENERIC_WRITE
301
302 traits = utf8_traits
303 win32traits = make_win32_traits(traits)
304
305 pathlen = space.len_w(w_path)
306 name = rffi.utf82wcharp(space.utf8_w(w_path), pathlen)
307 try:
308 self.handle = win32traits.CreateFile(name,
309 rwin32.ALL_READ_WRITE, rwin32.SHARE_READ_WRITE,
310 rffi.NULL, win32traits.OPEN_EXISTING,
311 0, rffi.cast(rwin32.HANDLE, 0))
312 if self.handle == rwin32.INVALID_HANDLE_VALUE:
313 self.handle = win32traits.CreateFile(name,
314 access,
315 rwin32.SHARE_READ_WRITE,
316 rffi.NULL, win32traits.OPEN_EXISTING,
317 0, rffi.cast(rwin32.HANDLE, 0))
318 finally:
319 lltype.free(name, flavor='raw')
320
321 if self.handle == rwin32.INVALID_HANDLE_VALUE:
322 raise WindowsError(rwin32.GetLastError_saved(),
323 "Failed to open handle")
324
325 if console_type == '\0':
326 console_type = _get_console_type(self.handle)
327
328 if console_type == '\0':
329 raise oefmt(space.w_ValueError,
330 "Cannot open non-console file")
331
332 if self.writable and console_type != 'w':
333 raise oefmt(space.w_ValueError,
334 "Cannot open input buffer for writing")
335
336 if self.readable and console_type != 'r':
337 raise oefmt(space.w_ValueError,
338 "Cannot open output buffer for reading")
339
340 self.blksize = DEFAULT_BUFFER_SIZE
341
342 def readable_w(self, space):
343 if self.handle == rwin32.INVALID_HANDLE_VALUE:
344 raise err_closed(space)
345 return space.newbool(self.readable)
346
347 def writable_w(self, space):
348 if self.handle == rwin32.INVALID_HANDLE_VALUE:
349 raise err_closed(space)
350 return space.newbool(self.writable)
351
352 def isatty_w(self, space):
353 if self.handle == rwin32.INVALID_HANDLE_VALUE:
354 raise err_closed(space)
355 return space.newbool(True)
356
357 def repr_w(self, space):
358 typename = space.type(self).name
359 try:
360 w_name = space.getattr(self, space.newtext("name"))
361 except OperationError as e:
362 if not e.match(space, space.w_Exception):
363 raise
364 return space.newtext("<%s>" % (typename,))
365 else:
366 name_repr = space.text_w(space.repr(w_name))
367 return space.newtext("<%s name=%s>" % (typename, name_repr))
368
369 def fileno_w(self, space):
370 traits = utf8_traits
371 win32traits = make_win32_traits(traits)
372 if self.fd < 0 and self.handle != rwin32.INVALID_HANDLE_VALUE:
373 if self.writable:
374 self.fd = rwin32.open_osfhandle(rffi.cast(rffi.INTP, self.handle), win32traits._O_WRONLY | win32traits._O_BINARY)
375 else:
376 self.fd = rwin32.open_osfhandle(rffi.cast(rffi.INTP, self.handle), win32traits._O_RDONLY | win32traits._O_BINARY)
377 if self.fd < 0:
378 raise err_mode(space, "fileno")
379 return space.newint(self.fd)
380
381 def readinto_w(self, space, w_buffer):
382 # Read wchar, convert to utf8, and put it into w_buffer.
383 # We buffer left-over characters into self.buf
384 rwbuffer = space.writebuf_w(w_buffer)
385 length = rwbuffer.getlength()
386 oldmode = self.mode
387 self.mode = 'u'
388 utf8, ulen = self.read(space, length)
389 i = 0
390 self.mode = oldmode
391 while utf8[i] != '\x00' and i < len(utf8):
392 rwbuffer[i] = utf8[i]
393 i += 1
394 return space.newint(i)
395
396
397 def read(self, space, length):
398 """ read from the console up to `length` utf-16 chars
399 If mode is 'u', return `length` codepoints. If mode is `b`,
400 return `length` bytes.`
401 """
402
403 if self.handle == rwin32.INVALID_HANDLE_VALUE:
404 raise err_closed(space)
405
406 if not self.readable:
407 raise err_mode(space, "reading")
408
409 if length <= 0:
410 return '', 0
411
412 if length > BUFMAX:
413 raise oefmt(space.w_ValueError,
414 "cannot read more than %d bytes", BUFMAX)
415
416 # first copy any remaining buffered utf16 data
417 builder = StringBuilder(length)
418 wbuf = self._getbuffer(length * 2)
419 w_wbuf = space.newbytes(wbuf)
420
421 state = space.fromcache(CodecState)
422 errh = state.decode_error_handler
423 outlen = 0
424 if len(wbuf) > 0:
425 utf8, lgt, pos = str_decode_utf_16(space, wbuf, w_wbuf, 'strict', final=True, errorhandler=errh)
426 if self.mode == 'u':
427 length -= lgt
428 outlen += lgt
429 else:
430 length -= len(utf8)
431 outlen += len(utf8)
432 builder.append(utf8)
433
434 if length > 0:
435 wbuf = read_console_wide(space, self.handle, length)
436 utf8, lgt, pos = str_decode_utf_16(space, wbuf, w_wbuf, 'strict', final=True, errorhandler=errh)
437 if 1 or self.mode == 'u':
438 length -= lgt
439 outlen += lgt
440 else:
441 length -= len(utf8)
442 outlen += len(utf8)
443 builder.append(utf8)
444
445 res = builder.build()
446 return res, outlen
447
448 def read_w(self, space, w_size=None):
449 size = convert_size(space, w_size)
450 if self.handle == rwin32.INVALID_HANDLE_VALUE:
451 raise err_closed(space)
452 if not self.readable:
453 raise err_mode(space,"reading")
454
455 if size < 0:
456 return self.readall_w(space)
457
458 if size > BUFMAX:
459 raise oefmt(space.w_ValueError,
460 "Cannot read more than %d bytes",
461 BUFMAX)
462
463 # If self.mode is 'u', we want to return a unicode
464 buf, length = self.read(space, size)
465 if 1 or self.mode == 'u':
466 return space.newtext(buf, length)
467 else:
468 return space.newbytes(buf)
469
470 def readall_w(self, space):
471 if self.handle == rwin32.INVALID_HANDLE_VALUE:
472 raise err_closed(space)
473
474 # Read the wstr 16-bit data from the console as 8-byte bytes
475 result = StringBuilder()
476 while True:
477 wbuf = read_console_wide(space, self.handle, BUFSIZ)
478 if len(wbuf) == 0:
479 break
480 result.append(wbuf)
481
482 wbuf = result.build()
483 state = space.fromcache(CodecState)
484 errh = state.decode_error_handler
485 w_wbuf = space.newbytes(wbuf)
486 utf8, lgt, pos = str_decode_utf_16(space, wbuf, w_wbuf, 'strict', final=True, errorhandler=errh)
487
488 return space.newtext(utf8, lgt)
489
490 def write_w(self, space, w_data):
491 if self.handle == rwin32.INVALID_HANDLE_VALUE:
492 raise err_closed(space)
493
494 if not self.writable:
495 raise err_mode(space,"writing")
496
497 if space.isinstance_w(w_data, space.w_text):
498 utf8 = space.utf8_w(w_data)
499 else:
500 utf8 = space.bytes_w(w_data)
501 if not len(utf8):
502 return space.newint(0)
503
504 # TODO: break up the encoding into chunks to save memory
505 state = space.fromcache(CodecState)
506 errh = state.encode_error_handler
507 utf16 = utf8_encode_utf_16(space, utf8, w_data, 'strict', errh, allow_surrogates=False)
508 wlen = len(utf16) // 2
509
510 with lltype.scoped_alloc(rwin32.LPDWORD.TO, 1) as n:
511 with rffi.scoped_nonmovingbuffer(utf16) as dataptr:
512 # skip BOM, start at 1
513 offset = 1
514 while offset < wlen:
515 res = rwin32.WriteConsoleW(self.handle,
516 rffi.cast(rwin32.LPVOID, rffi.ptradd(dataptr, offset * 2)),
517 wlen - offset, n , rffi.cast(rwin32.LPVOID, 0))
518 if not res:
519 err = rwin32.GetLastError_saved()
520 raise OperationError(space.w_WindowsError, space.newint(err))
521 nwrote = intmask(n[0])
522 offset += nwrote
523 return space.newint(len(utf8))
524
525 def get_blksize(self,space):
526 return space.newint(self.blksize)
527
528
529 W_WinConsoleIO.typedef = TypeDef(
530 '_io.WinConsoleIO', W_RawIOBase.typedef,
531 __new__ = generic_new_descr(W_WinConsoleIO),
532 __init__ = interp2app(W_WinConsoleIO.descr_init),
533 __repr__ = interp2app(W_WinConsoleIO.repr_w),
534
535 readable = interp2app(W_WinConsoleIO.readable_w),
536 writable = interp2app(W_WinConsoleIO.writable_w),
537 isatty = interp2app(W_WinConsoleIO.isatty_w),
538 read = interp2app(W_WinConsoleIO.read_w),
539 readall = interp2app(W_WinConsoleIO.readall_w),
540 readinto = interp2app(W_WinConsoleIO.readinto_w),
541 fileno = interp2app(W_WinConsoleIO.fileno_w),
542 write = interp2app(W_WinConsoleIO.write_w),
543 _blksize = GetSetProperty(W_WinConsoleIO.get_blksize),
544 )