winconsoleio.c 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179
  1. /*
  2. An implementation of Windows console I/O
  3. Classes defined here: _WindowsConsoleIO
  4. Written by Steve Dower
  5. */
  6. #define PY_SSIZE_T_CLEAN
  7. #include "Python.h"
  8. #include "pycore_fileutils.h" // _Py_BEGIN_SUPPRESS_IPH
  9. #include "pycore_object.h" // _PyObject_GC_UNTRACK()
  10. #ifdef HAVE_WINDOWS_CONSOLE_IO
  11. #include "structmember.h" // PyMemberDef
  12. #ifdef HAVE_SYS_TYPES_H
  13. #include <sys/types.h>
  14. #endif
  15. #ifdef HAVE_SYS_STAT_H
  16. #include <sys/stat.h>
  17. #endif
  18. #include <stddef.h> /* For offsetof */
  19. #ifndef WIN32_LEAN_AND_MEAN
  20. #define WIN32_LEAN_AND_MEAN
  21. #endif
  22. #include <windows.h>
  23. #include <fcntl.h>
  24. #include "_iomodule.h"
  25. /* BUFSIZ determines how many characters can be typed at the console
  26. before it starts blocking. */
  27. #if BUFSIZ < (16*1024)
  28. #define SMALLCHUNK (2*1024)
  29. #elif (BUFSIZ >= (2 << 25))
  30. #error "unreasonable BUFSIZ > 64 MiB defined"
  31. #else
  32. #define SMALLCHUNK BUFSIZ
  33. #endif
  34. /* BUFMAX determines how many bytes can be read in one go. */
  35. #define BUFMAX (32*1024*1024)
  36. /* SMALLBUF determines how many utf-8 characters will be
  37. buffered within the stream, in order to support reads
  38. of less than one character */
  39. #define SMALLBUF 4
  40. char _get_console_type(HANDLE handle) {
  41. DWORD mode, peek_count;
  42. if (handle == INVALID_HANDLE_VALUE)
  43. return '\0';
  44. if (!GetConsoleMode(handle, &mode))
  45. return '\0';
  46. /* Peek at the handle to see whether it is an input or output handle */
  47. if (GetNumberOfConsoleInputEvents(handle, &peek_count))
  48. return 'r';
  49. return 'w';
  50. }
  51. char _PyIO_get_console_type(PyObject *path_or_fd) {
  52. int fd = PyLong_AsLong(path_or_fd);
  53. PyErr_Clear();
  54. if (fd >= 0) {
  55. HANDLE handle = _Py_get_osfhandle_noraise(fd);
  56. if (handle == INVALID_HANDLE_VALUE)
  57. return '\0';
  58. return _get_console_type(handle);
  59. }
  60. PyObject *decoded;
  61. wchar_t *decoded_wstr;
  62. if (!PyUnicode_FSDecoder(path_or_fd, &decoded)) {
  63. PyErr_Clear();
  64. return '\0';
  65. }
  66. decoded_wstr = PyUnicode_AsWideCharString(decoded, NULL);
  67. Py_CLEAR(decoded);
  68. if (!decoded_wstr) {
  69. PyErr_Clear();
  70. return '\0';
  71. }
  72. char m = '\0';
  73. if (!_wcsicmp(decoded_wstr, L"CONIN$")) {
  74. m = 'r';
  75. } else if (!_wcsicmp(decoded_wstr, L"CONOUT$")) {
  76. m = 'w';
  77. } else if (!_wcsicmp(decoded_wstr, L"CON")) {
  78. m = 'x';
  79. }
  80. if (m) {
  81. PyMem_Free(decoded_wstr);
  82. return m;
  83. }
  84. DWORD length;
  85. wchar_t name_buf[MAX_PATH], *pname_buf = name_buf;
  86. length = GetFullPathNameW(decoded_wstr, MAX_PATH, pname_buf, NULL);
  87. if (length > MAX_PATH) {
  88. pname_buf = PyMem_New(wchar_t, length);
  89. if (pname_buf)
  90. length = GetFullPathNameW(decoded_wstr, length, pname_buf, NULL);
  91. else
  92. length = 0;
  93. }
  94. PyMem_Free(decoded_wstr);
  95. if (length) {
  96. wchar_t *name = pname_buf;
  97. if (length >= 4 && name[3] == L'\\' &&
  98. (name[2] == L'.' || name[2] == L'?') &&
  99. name[1] == L'\\' && name[0] == L'\\') {
  100. name += 4;
  101. }
  102. if (!_wcsicmp(name, L"CONIN$")) {
  103. m = 'r';
  104. } else if (!_wcsicmp(name, L"CONOUT$")) {
  105. m = 'w';
  106. } else if (!_wcsicmp(name, L"CON")) {
  107. m = 'x';
  108. }
  109. }
  110. if (pname_buf != name_buf)
  111. PyMem_Free(pname_buf);
  112. return m;
  113. }
  114. static DWORD
  115. _find_last_utf8_boundary(const char *buf, DWORD len)
  116. {
  117. /* This function never returns 0, returns the original len instead */
  118. DWORD count = 1;
  119. if (len == 0 || (buf[len - 1] & 0x80) == 0) {
  120. return len;
  121. }
  122. for (;; count++) {
  123. if (count > 3 || count >= len) {
  124. return len;
  125. }
  126. if ((buf[len - count] & 0xc0) != 0x80) {
  127. return len - count;
  128. }
  129. }
  130. }
  131. /*[clinic input]
  132. module _io
  133. class _io._WindowsConsoleIO "winconsoleio *" "clinic_state()->PyWindowsConsoleIO_Type"
  134. [clinic start generated code]*/
  135. /*[clinic end generated code: output=da39a3ee5e6b4b0d input=05526e723011ab36]*/
  136. typedef struct {
  137. PyObject_HEAD
  138. int fd;
  139. unsigned int created : 1;
  140. unsigned int readable : 1;
  141. unsigned int writable : 1;
  142. unsigned int closefd : 1;
  143. char finalizing;
  144. unsigned int blksize;
  145. PyObject *weakreflist;
  146. PyObject *dict;
  147. char buf[SMALLBUF];
  148. wchar_t wbuf;
  149. } winconsoleio;
  150. int
  151. _PyWindowsConsoleIO_closed(PyObject *self)
  152. {
  153. return ((winconsoleio *)self)->fd == -1;
  154. }
  155. /* Returns 0 on success, -1 with exception set on failure. */
  156. static int
  157. internal_close(winconsoleio *self)
  158. {
  159. if (self->fd != -1) {
  160. if (self->closefd) {
  161. _Py_BEGIN_SUPPRESS_IPH
  162. close(self->fd);
  163. _Py_END_SUPPRESS_IPH
  164. }
  165. self->fd = -1;
  166. }
  167. return 0;
  168. }
  169. /*[clinic input]
  170. _io._WindowsConsoleIO.close
  171. cls: defining_class
  172. /
  173. Close the console object.
  174. A closed console object cannot be used for further I/O operations.
  175. close() may be called more than once without error.
  176. [clinic start generated code]*/
  177. static PyObject *
  178. _io__WindowsConsoleIO_close_impl(winconsoleio *self, PyTypeObject *cls)
  179. /*[clinic end generated code: output=e50c1808c063e1e2 input=161001bd2a649a4b]*/
  180. {
  181. PyObject *res;
  182. PyObject *exc;
  183. int rc;
  184. _PyIO_State *state = get_io_state_by_cls(cls);
  185. res = PyObject_CallMethodOneArg((PyObject*)state->PyRawIOBase_Type,
  186. &_Py_ID(close), (PyObject*)self);
  187. if (!self->closefd) {
  188. self->fd = -1;
  189. return res;
  190. }
  191. if (res == NULL) {
  192. exc = PyErr_GetRaisedException();
  193. }
  194. rc = internal_close(self);
  195. if (res == NULL) {
  196. _PyErr_ChainExceptions1(exc);
  197. }
  198. if (rc < 0) {
  199. Py_CLEAR(res);
  200. }
  201. return res;
  202. }
  203. static PyObject *
  204. winconsoleio_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
  205. {
  206. winconsoleio *self;
  207. assert(type != NULL && type->tp_alloc != NULL);
  208. self = (winconsoleio *) type->tp_alloc(type, 0);
  209. if (self != NULL) {
  210. self->fd = -1;
  211. self->created = 0;
  212. self->readable = 0;
  213. self->writable = 0;
  214. self->closefd = 0;
  215. self->blksize = 0;
  216. self->weakreflist = NULL;
  217. }
  218. return (PyObject *) self;
  219. }
  220. /*[clinic input]
  221. _io._WindowsConsoleIO.__init__
  222. file as nameobj: object
  223. mode: str = "r"
  224. closefd: bool = True
  225. opener: object = None
  226. Open a console buffer by file descriptor.
  227. The mode can be 'rb' (default), or 'wb' for reading or writing bytes. All
  228. other mode characters will be ignored. Mode 'b' will be assumed if it is
  229. omitted. The *opener* parameter is always ignored.
  230. [clinic start generated code]*/
  231. static int
  232. _io__WindowsConsoleIO___init___impl(winconsoleio *self, PyObject *nameobj,
  233. const char *mode, int closefd,
  234. PyObject *opener)
  235. /*[clinic end generated code: output=3fd9cbcdd8d95429 input=7a3eed6bbe998fd9]*/
  236. {
  237. const char *s;
  238. wchar_t *name = NULL;
  239. char console_type = '\0';
  240. int ret = 0;
  241. int rwa = 0;
  242. int fd = -1;
  243. int fd_is_own = 0;
  244. HANDLE handle = NULL;
  245. #ifndef NDEBUG
  246. _PyIO_State *state = find_io_state_by_def(Py_TYPE(self));
  247. assert(PyObject_TypeCheck(self, state->PyWindowsConsoleIO_Type));
  248. #endif
  249. if (self->fd >= 0) {
  250. if (self->closefd) {
  251. /* Have to close the existing file first. */
  252. if (internal_close(self) < 0)
  253. return -1;
  254. }
  255. else
  256. self->fd = -1;
  257. }
  258. fd = _PyLong_AsInt(nameobj);
  259. if (fd < 0) {
  260. if (!PyErr_Occurred()) {
  261. PyErr_SetString(PyExc_ValueError,
  262. "negative file descriptor");
  263. return -1;
  264. }
  265. PyErr_Clear();
  266. }
  267. self->fd = fd;
  268. if (fd < 0) {
  269. PyObject *decodedname;
  270. int d = PyUnicode_FSDecoder(nameobj, (void*)&decodedname);
  271. if (!d)
  272. return -1;
  273. name = PyUnicode_AsWideCharString(decodedname, NULL);
  274. console_type = _PyIO_get_console_type(decodedname);
  275. Py_CLEAR(decodedname);
  276. if (name == NULL)
  277. return -1;
  278. }
  279. s = mode;
  280. while (*s) {
  281. switch (*s++) {
  282. case '+':
  283. case 'a':
  284. case 'b':
  285. case 'x':
  286. break;
  287. case 'r':
  288. if (rwa)
  289. goto bad_mode;
  290. rwa = 1;
  291. self->readable = 1;
  292. if (console_type == 'x')
  293. console_type = 'r';
  294. break;
  295. case 'w':
  296. if (rwa)
  297. goto bad_mode;
  298. rwa = 1;
  299. self->writable = 1;
  300. if (console_type == 'x')
  301. console_type = 'w';
  302. break;
  303. default:
  304. PyErr_Format(PyExc_ValueError,
  305. "invalid mode: %.200s", mode);
  306. goto error;
  307. }
  308. }
  309. if (!rwa)
  310. goto bad_mode;
  311. if (fd >= 0) {
  312. handle = _Py_get_osfhandle_noraise(fd);
  313. self->closefd = 0;
  314. } else {
  315. DWORD access = GENERIC_READ;
  316. self->closefd = 1;
  317. if (!closefd) {
  318. PyErr_SetString(PyExc_ValueError,
  319. "Cannot use closefd=False with file name");
  320. goto error;
  321. }
  322. if (self->writable)
  323. access = GENERIC_WRITE;
  324. Py_BEGIN_ALLOW_THREADS
  325. /* Attempt to open for read/write initially, then fall back
  326. on the specific access. This is required for modern names
  327. CONIN$ and CONOUT$, which allow reading/writing state as
  328. well as reading/writing content. */
  329. handle = CreateFileW(name, GENERIC_READ | GENERIC_WRITE,
  330. FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
  331. if (handle == INVALID_HANDLE_VALUE)
  332. handle = CreateFileW(name, access,
  333. FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
  334. Py_END_ALLOW_THREADS
  335. if (handle == INVALID_HANDLE_VALUE) {
  336. PyErr_SetExcFromWindowsErrWithFilenameObject(PyExc_OSError, GetLastError(), nameobj);
  337. goto error;
  338. }
  339. if (self->writable)
  340. self->fd = _Py_open_osfhandle_noraise(handle, _O_WRONLY | _O_BINARY);
  341. else
  342. self->fd = _Py_open_osfhandle_noraise(handle, _O_RDONLY | _O_BINARY);
  343. if (self->fd < 0) {
  344. PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, nameobj);
  345. CloseHandle(handle);
  346. goto error;
  347. }
  348. }
  349. if (console_type == '\0')
  350. console_type = _get_console_type(handle);
  351. if (self->writable && console_type != 'w') {
  352. PyErr_SetString(PyExc_ValueError,
  353. "Cannot open console input buffer for writing");
  354. goto error;
  355. }
  356. if (self->readable && console_type != 'r') {
  357. PyErr_SetString(PyExc_ValueError,
  358. "Cannot open console output buffer for reading");
  359. goto error;
  360. }
  361. self->blksize = DEFAULT_BUFFER_SIZE;
  362. memset(self->buf, 0, 4);
  363. if (PyObject_SetAttr((PyObject *)self, &_Py_ID(name), nameobj) < 0)
  364. goto error;
  365. goto done;
  366. bad_mode:
  367. PyErr_SetString(PyExc_ValueError,
  368. "Must have exactly one of read or write mode");
  369. error:
  370. ret = -1;
  371. internal_close(self);
  372. done:
  373. if (name)
  374. PyMem_Free(name);
  375. return ret;
  376. }
  377. static int
  378. winconsoleio_traverse(winconsoleio *self, visitproc visit, void *arg)
  379. {
  380. Py_VISIT(Py_TYPE(self));
  381. Py_VISIT(self->dict);
  382. return 0;
  383. }
  384. static int
  385. winconsoleio_clear(winconsoleio *self)
  386. {
  387. Py_CLEAR(self->dict);
  388. return 0;
  389. }
  390. static void
  391. winconsoleio_dealloc(winconsoleio *self)
  392. {
  393. PyTypeObject *tp = Py_TYPE(self);
  394. self->finalizing = 1;
  395. if (_PyIOBase_finalize((PyObject *) self) < 0)
  396. return;
  397. _PyObject_GC_UNTRACK(self);
  398. if (self->weakreflist != NULL)
  399. PyObject_ClearWeakRefs((PyObject *) self);
  400. Py_CLEAR(self->dict);
  401. tp->tp_free((PyObject *)self);
  402. Py_DECREF(tp);
  403. }
  404. static PyObject *
  405. err_closed(void)
  406. {
  407. PyErr_SetString(PyExc_ValueError, "I/O operation on closed file");
  408. return NULL;
  409. }
  410. static PyObject *
  411. err_mode(_PyIO_State *state, const char *action)
  412. {
  413. return PyErr_Format(state->unsupported_operation,
  414. "Console buffer does not support %s", action);
  415. }
  416. /*[clinic input]
  417. _io._WindowsConsoleIO.fileno
  418. Return the underlying file descriptor (an integer).
  419. [clinic start generated code]*/
  420. static PyObject *
  421. _io__WindowsConsoleIO_fileno_impl(winconsoleio *self)
  422. /*[clinic end generated code: output=006fa74ce3b5cfbf input=845c47ebbc3a2f67]*/
  423. {
  424. if (self->fd < 0)
  425. return err_closed();
  426. return PyLong_FromLong(self->fd);
  427. }
  428. /*[clinic input]
  429. _io._WindowsConsoleIO.readable
  430. True if console is an input buffer.
  431. [clinic start generated code]*/
  432. static PyObject *
  433. _io__WindowsConsoleIO_readable_impl(winconsoleio *self)
  434. /*[clinic end generated code: output=daf9cef2743becf0 input=6be9defb5302daae]*/
  435. {
  436. if (self->fd == -1)
  437. return err_closed();
  438. return PyBool_FromLong((long) self->readable);
  439. }
  440. /*[clinic input]
  441. _io._WindowsConsoleIO.writable
  442. True if console is an output buffer.
  443. [clinic start generated code]*/
  444. static PyObject *
  445. _io__WindowsConsoleIO_writable_impl(winconsoleio *self)
  446. /*[clinic end generated code: output=e0a2ad7eae5abf67 input=cefbd8abc24df6a0]*/
  447. {
  448. if (self->fd == -1)
  449. return err_closed();
  450. return PyBool_FromLong((long) self->writable);
  451. }
  452. static DWORD
  453. _buflen(winconsoleio *self)
  454. {
  455. for (DWORD i = 0; i < SMALLBUF; ++i) {
  456. if (!self->buf[i])
  457. return i;
  458. }
  459. return SMALLBUF;
  460. }
  461. static DWORD
  462. _copyfrombuf(winconsoleio *self, char *buf, DWORD len)
  463. {
  464. DWORD n = 0;
  465. while (self->buf[0] && len--) {
  466. buf[n++] = self->buf[0];
  467. for (int i = 1; i < SMALLBUF; ++i)
  468. self->buf[i - 1] = self->buf[i];
  469. self->buf[SMALLBUF - 1] = 0;
  470. }
  471. return n;
  472. }
  473. static wchar_t *
  474. read_console_w(HANDLE handle, DWORD maxlen, DWORD *readlen) {
  475. int err = 0, sig = 0;
  476. wchar_t *buf = (wchar_t*)PyMem_Malloc(maxlen * sizeof(wchar_t));
  477. if (!buf)
  478. goto error;
  479. *readlen = 0;
  480. //DebugBreak();
  481. Py_BEGIN_ALLOW_THREADS
  482. DWORD off = 0;
  483. while (off < maxlen) {
  484. DWORD n = (DWORD)-1;
  485. DWORD len = min(maxlen - off, BUFSIZ);
  486. SetLastError(0);
  487. BOOL res = ReadConsoleW(handle, &buf[off], len, &n, NULL);
  488. if (!res) {
  489. err = GetLastError();
  490. break;
  491. }
  492. if (n == (DWORD)-1 && (err = GetLastError()) == ERROR_OPERATION_ABORTED) {
  493. break;
  494. }
  495. if (n == 0) {
  496. err = GetLastError();
  497. if (err != ERROR_OPERATION_ABORTED)
  498. break;
  499. err = 0;
  500. HANDLE hInterruptEvent = _PyOS_SigintEvent();
  501. if (WaitForSingleObjectEx(hInterruptEvent, 100, FALSE)
  502. == WAIT_OBJECT_0) {
  503. ResetEvent(hInterruptEvent);
  504. Py_BLOCK_THREADS
  505. sig = PyErr_CheckSignals();
  506. Py_UNBLOCK_THREADS
  507. if (sig < 0)
  508. break;
  509. }
  510. }
  511. *readlen += n;
  512. /* If we didn't read a full buffer that time, don't try
  513. again or we will block a second time. */
  514. if (n < len)
  515. break;
  516. /* If the buffer ended with a newline, break out */
  517. if (buf[*readlen - 1] == '\n')
  518. break;
  519. /* If the buffer ends with a high surrogate, expand the
  520. buffer and read an extra character. */
  521. WORD char_type;
  522. if (off + BUFSIZ >= maxlen &&
  523. GetStringTypeW(CT_CTYPE3, &buf[*readlen - 1], 1, &char_type) &&
  524. char_type == C3_HIGHSURROGATE) {
  525. wchar_t *newbuf;
  526. maxlen += 1;
  527. Py_BLOCK_THREADS
  528. newbuf = (wchar_t*)PyMem_Realloc(buf, maxlen * sizeof(wchar_t));
  529. Py_UNBLOCK_THREADS
  530. if (!newbuf) {
  531. sig = -1;
  532. break;
  533. }
  534. buf = newbuf;
  535. /* Only advance by n and not BUFSIZ in this case */
  536. off += n;
  537. continue;
  538. }
  539. off += BUFSIZ;
  540. }
  541. Py_END_ALLOW_THREADS
  542. if (sig)
  543. goto error;
  544. if (err) {
  545. PyErr_SetFromWindowsErr(err);
  546. goto error;
  547. }
  548. if (*readlen > 0 && buf[0] == L'\x1a') {
  549. PyMem_Free(buf);
  550. buf = (wchar_t *)PyMem_Malloc(sizeof(wchar_t));
  551. if (!buf)
  552. goto error;
  553. buf[0] = L'\0';
  554. *readlen = 0;
  555. }
  556. return buf;
  557. error:
  558. if (buf)
  559. PyMem_Free(buf);
  560. return NULL;
  561. }
  562. static Py_ssize_t
  563. readinto(_PyIO_State *state, winconsoleio *self, char *buf, Py_ssize_t len)
  564. {
  565. if (self->fd == -1) {
  566. err_closed();
  567. return -1;
  568. }
  569. if (!self->readable) {
  570. err_mode(state, "reading");
  571. return -1;
  572. }
  573. if (len == 0)
  574. return 0;
  575. if (len > BUFMAX) {
  576. PyErr_Format(PyExc_ValueError, "cannot read more than %d bytes", BUFMAX);
  577. return -1;
  578. }
  579. HANDLE handle = _Py_get_osfhandle(self->fd);
  580. if (handle == INVALID_HANDLE_VALUE)
  581. return -1;
  582. /* Each character may take up to 4 bytes in the final buffer.
  583. This is highly conservative, but necessary to avoid
  584. failure for any given Unicode input (e.g. \U0010ffff).
  585. If the caller requests fewer than 4 bytes, we buffer one
  586. character.
  587. */
  588. DWORD wlen = (DWORD)(len / 4);
  589. if (wlen == 0) {
  590. wlen = 1;
  591. }
  592. DWORD read_len = _copyfrombuf(self, buf, (DWORD)len);
  593. if (read_len) {
  594. buf = &buf[read_len];
  595. len -= read_len;
  596. wlen -= 1;
  597. }
  598. if (len == read_len || wlen == 0)
  599. return read_len;
  600. DWORD n;
  601. wchar_t *wbuf = read_console_w(handle, wlen, &n);
  602. if (wbuf == NULL)
  603. return -1;
  604. if (n == 0) {
  605. PyMem_Free(wbuf);
  606. return read_len;
  607. }
  608. int err = 0;
  609. DWORD u8n = 0;
  610. Py_BEGIN_ALLOW_THREADS
  611. if (len < 4) {
  612. if (WideCharToMultiByte(CP_UTF8, 0, wbuf, n,
  613. self->buf, sizeof(self->buf) / sizeof(self->buf[0]),
  614. NULL, NULL))
  615. u8n = _copyfrombuf(self, buf, (DWORD)len);
  616. } else {
  617. u8n = WideCharToMultiByte(CP_UTF8, 0, wbuf, n,
  618. buf, (DWORD)len, NULL, NULL);
  619. }
  620. if (u8n) {
  621. read_len += u8n;
  622. u8n = 0;
  623. } else {
  624. err = GetLastError();
  625. if (err == ERROR_INSUFFICIENT_BUFFER) {
  626. /* Calculate the needed buffer for a more useful error, as this
  627. means our "/ 4" logic above is insufficient for some input.
  628. */
  629. u8n = WideCharToMultiByte(CP_UTF8, 0, wbuf, n,
  630. NULL, 0, NULL, NULL);
  631. }
  632. }
  633. Py_END_ALLOW_THREADS
  634. PyMem_Free(wbuf);
  635. if (u8n) {
  636. PyErr_Format(PyExc_SystemError,
  637. "Buffer had room for %zd bytes but %u bytes required",
  638. len, u8n);
  639. return -1;
  640. }
  641. if (err) {
  642. PyErr_SetFromWindowsErr(err);
  643. return -1;
  644. }
  645. return read_len;
  646. }
  647. /*[clinic input]
  648. _io._WindowsConsoleIO.readinto
  649. cls: defining_class
  650. buffer: Py_buffer(accept={rwbuffer})
  651. /
  652. Same as RawIOBase.readinto().
  653. [clinic start generated code]*/
  654. static PyObject *
  655. _io__WindowsConsoleIO_readinto_impl(winconsoleio *self, PyTypeObject *cls,
  656. Py_buffer *buffer)
  657. /*[clinic end generated code: output=96717c74f6204b79 input=4b0627c3b1645f78]*/
  658. {
  659. _PyIO_State *state = get_io_state_by_cls(cls);
  660. Py_ssize_t len = readinto(state, self, buffer->buf, buffer->len);
  661. if (len < 0)
  662. return NULL;
  663. return PyLong_FromSsize_t(len);
  664. }
  665. static DWORD
  666. new_buffersize(winconsoleio *self, DWORD currentsize)
  667. {
  668. DWORD addend;
  669. /* Expand the buffer by an amount proportional to the current size,
  670. giving us amortized linear-time behavior. For bigger sizes, use a
  671. less-than-double growth factor to avoid excessive allocation. */
  672. if (currentsize > 65536)
  673. addend = currentsize >> 3;
  674. else
  675. addend = 256 + currentsize;
  676. if (addend < SMALLCHUNK)
  677. /* Avoid tiny read() calls. */
  678. addend = SMALLCHUNK;
  679. return addend + currentsize;
  680. }
  681. /*[clinic input]
  682. _io._WindowsConsoleIO.readall
  683. Read all data from the console, returned as bytes.
  684. Return an empty bytes object at EOF.
  685. [clinic start generated code]*/
  686. static PyObject *
  687. _io__WindowsConsoleIO_readall_impl(winconsoleio *self)
  688. /*[clinic end generated code: output=e6d312c684f6e23b input=4024d649a1006e69]*/
  689. {
  690. wchar_t *buf;
  691. DWORD bufsize, n, len = 0;
  692. PyObject *bytes;
  693. DWORD bytes_size, rn;
  694. HANDLE handle;
  695. if (self->fd == -1)
  696. return err_closed();
  697. handle = _Py_get_osfhandle(self->fd);
  698. if (handle == INVALID_HANDLE_VALUE)
  699. return NULL;
  700. bufsize = BUFSIZ;
  701. buf = (wchar_t*)PyMem_Malloc((bufsize + 1) * sizeof(wchar_t));
  702. if (buf == NULL)
  703. return NULL;
  704. while (1) {
  705. wchar_t *subbuf;
  706. if (len >= (Py_ssize_t)bufsize) {
  707. DWORD newsize = new_buffersize(self, len);
  708. if (newsize > BUFMAX)
  709. break;
  710. if (newsize < bufsize) {
  711. PyErr_SetString(PyExc_OverflowError,
  712. "unbounded read returned more bytes "
  713. "than a Python bytes object can hold");
  714. PyMem_Free(buf);
  715. return NULL;
  716. }
  717. bufsize = newsize;
  718. wchar_t *tmp = PyMem_Realloc(buf,
  719. (bufsize + 1) * sizeof(wchar_t));
  720. if (tmp == NULL) {
  721. PyMem_Free(buf);
  722. return NULL;
  723. }
  724. buf = tmp;
  725. }
  726. subbuf = read_console_w(handle, bufsize - len, &n);
  727. if (subbuf == NULL) {
  728. PyMem_Free(buf);
  729. return NULL;
  730. }
  731. if (n > 0)
  732. wcsncpy_s(&buf[len], bufsize - len + 1, subbuf, n);
  733. PyMem_Free(subbuf);
  734. /* when the read is empty we break */
  735. if (n == 0)
  736. break;
  737. len += n;
  738. }
  739. if (len == 0 && _buflen(self) == 0) {
  740. /* when the result starts with ^Z we return an empty buffer */
  741. PyMem_Free(buf);
  742. return PyBytes_FromStringAndSize(NULL, 0);
  743. }
  744. if (len) {
  745. Py_BEGIN_ALLOW_THREADS
  746. bytes_size = WideCharToMultiByte(CP_UTF8, 0, buf, len,
  747. NULL, 0, NULL, NULL);
  748. Py_END_ALLOW_THREADS
  749. if (!bytes_size) {
  750. DWORD err = GetLastError();
  751. PyMem_Free(buf);
  752. return PyErr_SetFromWindowsErr(err);
  753. }
  754. } else {
  755. bytes_size = 0;
  756. }
  757. bytes_size += _buflen(self);
  758. bytes = PyBytes_FromStringAndSize(NULL, bytes_size);
  759. rn = _copyfrombuf(self, PyBytes_AS_STRING(bytes), bytes_size);
  760. if (len) {
  761. Py_BEGIN_ALLOW_THREADS
  762. bytes_size = WideCharToMultiByte(CP_UTF8, 0, buf, len,
  763. &PyBytes_AS_STRING(bytes)[rn], bytes_size - rn, NULL, NULL);
  764. Py_END_ALLOW_THREADS
  765. if (!bytes_size) {
  766. DWORD err = GetLastError();
  767. PyMem_Free(buf);
  768. Py_CLEAR(bytes);
  769. return PyErr_SetFromWindowsErr(err);
  770. }
  771. /* add back the number of preserved bytes */
  772. bytes_size += rn;
  773. }
  774. PyMem_Free(buf);
  775. if (bytes_size < (size_t)PyBytes_GET_SIZE(bytes)) {
  776. if (_PyBytes_Resize(&bytes, n * sizeof(wchar_t)) < 0) {
  777. Py_CLEAR(bytes);
  778. return NULL;
  779. }
  780. }
  781. return bytes;
  782. }
  783. /*[clinic input]
  784. _io._WindowsConsoleIO.read
  785. cls: defining_class
  786. size: Py_ssize_t(accept={int, NoneType}) = -1
  787. /
  788. Read at most size bytes, returned as bytes.
  789. Only makes one system call when size is a positive integer,
  790. so less data may be returned than requested.
  791. Return an empty bytes object at EOF.
  792. [clinic start generated code]*/
  793. static PyObject *
  794. _io__WindowsConsoleIO_read_impl(winconsoleio *self, PyTypeObject *cls,
  795. Py_ssize_t size)
  796. /*[clinic end generated code: output=7e569a586537c0ae input=a14570a5da273365]*/
  797. {
  798. PyObject *bytes;
  799. Py_ssize_t bytes_size;
  800. if (self->fd == -1)
  801. return err_closed();
  802. if (!self->readable) {
  803. _PyIO_State *state = get_io_state_by_cls(cls);
  804. return err_mode(state, "reading");
  805. }
  806. if (size < 0)
  807. return _io__WindowsConsoleIO_readall_impl(self);
  808. if (size > BUFMAX) {
  809. PyErr_Format(PyExc_ValueError, "cannot read more than %d bytes", BUFMAX);
  810. return NULL;
  811. }
  812. bytes = PyBytes_FromStringAndSize(NULL, size);
  813. if (bytes == NULL)
  814. return NULL;
  815. _PyIO_State *state = get_io_state_by_cls(cls);
  816. bytes_size = readinto(state, self, PyBytes_AS_STRING(bytes),
  817. PyBytes_GET_SIZE(bytes));
  818. if (bytes_size < 0) {
  819. Py_CLEAR(bytes);
  820. return NULL;
  821. }
  822. if (bytes_size < PyBytes_GET_SIZE(bytes)) {
  823. if (_PyBytes_Resize(&bytes, bytes_size) < 0) {
  824. Py_CLEAR(bytes);
  825. return NULL;
  826. }
  827. }
  828. return bytes;
  829. }
  830. /*[clinic input]
  831. _io._WindowsConsoleIO.write
  832. cls: defining_class
  833. b: Py_buffer
  834. /
  835. Write buffer b to file, return number of bytes written.
  836. Only makes one system call, so not all of the data may be written.
  837. The number of bytes actually written is returned.
  838. [clinic start generated code]*/
  839. static PyObject *
  840. _io__WindowsConsoleIO_write_impl(winconsoleio *self, PyTypeObject *cls,
  841. Py_buffer *b)
  842. /*[clinic end generated code: output=e8019f480243cb29 input=10ac37c19339dfbe]*/
  843. {
  844. BOOL res = TRUE;
  845. wchar_t *wbuf;
  846. DWORD len, wlen, n = 0;
  847. HANDLE handle;
  848. if (self->fd == -1)
  849. return err_closed();
  850. if (!self->writable) {
  851. _PyIO_State *state = get_io_state_by_cls(cls);
  852. return err_mode(state, "writing");
  853. }
  854. handle = _Py_get_osfhandle(self->fd);
  855. if (handle == INVALID_HANDLE_VALUE)
  856. return NULL;
  857. if (!b->len) {
  858. return PyLong_FromLong(0);
  859. }
  860. if (b->len > BUFMAX)
  861. len = BUFMAX;
  862. else
  863. len = (DWORD)b->len;
  864. Py_BEGIN_ALLOW_THREADS
  865. wlen = MultiByteToWideChar(CP_UTF8, 0, b->buf, len, NULL, 0);
  866. /* issue11395 there is an unspecified upper bound on how many bytes
  867. can be written at once. We cap at 32k - the caller will have to
  868. handle partial writes.
  869. Since we don't know how many input bytes are being ignored, we
  870. have to reduce and recalculate. */
  871. while (wlen > 32766 / sizeof(wchar_t)) {
  872. len /= 2;
  873. /* Fix for github issues gh-110913 and gh-82052. */
  874. len = _find_last_utf8_boundary(b->buf, len);
  875. wlen = MultiByteToWideChar(CP_UTF8, 0, b->buf, len, NULL, 0);
  876. }
  877. Py_END_ALLOW_THREADS
  878. if (!wlen)
  879. return PyErr_SetFromWindowsErr(0);
  880. wbuf = (wchar_t*)PyMem_Malloc(wlen * sizeof(wchar_t));
  881. Py_BEGIN_ALLOW_THREADS
  882. wlen = MultiByteToWideChar(CP_UTF8, 0, b->buf, len, wbuf, wlen);
  883. if (wlen) {
  884. res = WriteConsoleW(handle, wbuf, wlen, &n, NULL);
  885. if (res && n < wlen) {
  886. /* Wrote fewer characters than expected, which means our
  887. * len value may be wrong. So recalculate it from the
  888. * characters that were written. As this could potentially
  889. * result in a different value, we also validate that value.
  890. */
  891. len = WideCharToMultiByte(CP_UTF8, 0, wbuf, n,
  892. NULL, 0, NULL, NULL);
  893. if (len) {
  894. wlen = MultiByteToWideChar(CP_UTF8, 0, b->buf, len,
  895. NULL, 0);
  896. assert(wlen == len);
  897. }
  898. }
  899. } else
  900. res = 0;
  901. Py_END_ALLOW_THREADS
  902. if (!res) {
  903. DWORD err = GetLastError();
  904. PyMem_Free(wbuf);
  905. return PyErr_SetFromWindowsErr(err);
  906. }
  907. PyMem_Free(wbuf);
  908. return PyLong_FromSsize_t(len);
  909. }
  910. static PyObject *
  911. winconsoleio_repr(winconsoleio *self)
  912. {
  913. if (self->fd == -1)
  914. return PyUnicode_FromFormat("<_io._WindowsConsoleIO [closed]>");
  915. if (self->readable)
  916. return PyUnicode_FromFormat("<_io._WindowsConsoleIO mode='rb' closefd=%s>",
  917. self->closefd ? "True" : "False");
  918. if (self->writable)
  919. return PyUnicode_FromFormat("<_io._WindowsConsoleIO mode='wb' closefd=%s>",
  920. self->closefd ? "True" : "False");
  921. PyErr_SetString(PyExc_SystemError, "_WindowsConsoleIO has invalid mode");
  922. return NULL;
  923. }
  924. /*[clinic input]
  925. _io._WindowsConsoleIO.isatty
  926. Always True.
  927. [clinic start generated code]*/
  928. static PyObject *
  929. _io__WindowsConsoleIO_isatty_impl(winconsoleio *self)
  930. /*[clinic end generated code: output=9eac09d287c11bd7 input=9b91591dbe356f86]*/
  931. {
  932. if (self->fd == -1)
  933. return err_closed();
  934. Py_RETURN_TRUE;
  935. }
  936. #define clinic_state() (find_io_state_by_def(Py_TYPE(self)))
  937. #include "clinic/winconsoleio.c.h"
  938. #undef clinic_state
  939. static PyMethodDef winconsoleio_methods[] = {
  940. _IO__WINDOWSCONSOLEIO_READ_METHODDEF
  941. _IO__WINDOWSCONSOLEIO_READALL_METHODDEF
  942. _IO__WINDOWSCONSOLEIO_READINTO_METHODDEF
  943. _IO__WINDOWSCONSOLEIO_WRITE_METHODDEF
  944. _IO__WINDOWSCONSOLEIO_CLOSE_METHODDEF
  945. _IO__WINDOWSCONSOLEIO_READABLE_METHODDEF
  946. _IO__WINDOWSCONSOLEIO_WRITABLE_METHODDEF
  947. _IO__WINDOWSCONSOLEIO_FILENO_METHODDEF
  948. _IO__WINDOWSCONSOLEIO_ISATTY_METHODDEF
  949. {NULL, NULL} /* sentinel */
  950. };
  951. /* 'closed' and 'mode' are attributes for compatibility with FileIO. */
  952. static PyObject *
  953. get_closed(winconsoleio *self, void *closure)
  954. {
  955. return PyBool_FromLong((long)(self->fd == -1));
  956. }
  957. static PyObject *
  958. get_closefd(winconsoleio *self, void *closure)
  959. {
  960. return PyBool_FromLong((long)(self->closefd));
  961. }
  962. static PyObject *
  963. get_mode(winconsoleio *self, void *closure)
  964. {
  965. return PyUnicode_FromString(self->readable ? "rb" : "wb");
  966. }
  967. static PyGetSetDef winconsoleio_getsetlist[] = {
  968. {"closed", (getter)get_closed, NULL, "True if the file is closed"},
  969. {"closefd", (getter)get_closefd, NULL,
  970. "True if the file descriptor will be closed by close()."},
  971. {"mode", (getter)get_mode, NULL, "String giving the file mode"},
  972. {NULL},
  973. };
  974. static PyMemberDef winconsoleio_members[] = {
  975. {"_blksize", T_UINT, offsetof(winconsoleio, blksize), 0},
  976. {"_finalizing", T_BOOL, offsetof(winconsoleio, finalizing), 0},
  977. {"__weaklistoffset__", T_PYSSIZET, offsetof(winconsoleio, weakreflist), READONLY},
  978. {"__dictoffset__", T_PYSSIZET, offsetof(winconsoleio, dict), READONLY},
  979. {NULL}
  980. };
  981. static PyType_Slot winconsoleio_slots[] = {
  982. {Py_tp_dealloc, winconsoleio_dealloc},
  983. {Py_tp_repr, winconsoleio_repr},
  984. {Py_tp_getattro, PyObject_GenericGetAttr},
  985. {Py_tp_doc, (void *)_io__WindowsConsoleIO___init____doc__},
  986. {Py_tp_traverse, winconsoleio_traverse},
  987. {Py_tp_clear, winconsoleio_clear},
  988. {Py_tp_methods, winconsoleio_methods},
  989. {Py_tp_members, winconsoleio_members},
  990. {Py_tp_getset, winconsoleio_getsetlist},
  991. {Py_tp_init, _io__WindowsConsoleIO___init__},
  992. {Py_tp_new, winconsoleio_new},
  993. {0, NULL},
  994. };
  995. PyType_Spec winconsoleio_spec = {
  996. .name = "_io._WindowsConsoleIO",
  997. .basicsize = sizeof(winconsoleio),
  998. .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC |
  999. Py_TPFLAGS_IMMUTABLETYPE),
  1000. .slots = winconsoleio_slots,
  1001. };
  1002. #endif /* HAVE_WINDOWS_CONSOLE_IO */