From f14eb3996cccad2be3c666ebd0c0c326ed24b776 Mon Sep 17 00:00:00 2001 From: Segev Finer Date: Fri, 2 Jun 2017 01:58:26 +0300 Subject: [PATCH 1/2] bpo-30544: _io._WindowsConsoleIO.write raises the wrong error when WriteConsoleW fails --- Modules/_io/winconsoleio.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Modules/_io/winconsoleio.c b/Modules/_io/winconsoleio.c index 814462f7c989f1..f684e8f0c93999 100644 --- a/Modules/_io/winconsoleio.c +++ b/Modules/_io/winconsoleio.c @@ -966,6 +966,7 @@ _io__WindowsConsoleIO_write_impl(winconsoleio *self, Py_buffer *b) BOOL res = TRUE; wchar_t *wbuf; DWORD len, wlen, n = 0; + DWORD err; if (self->handle == INVALID_HANDLE_VALUE) return err_closed(); @@ -1000,6 +1001,9 @@ _io__WindowsConsoleIO_write_impl(winconsoleio *self, Py_buffer *b) wlen = MultiByteToWideChar(CP_UTF8, 0, b->buf, len, wbuf, wlen); if (wlen) { res = WriteConsoleW(self->handle, wbuf, wlen, &n, NULL); + if (!res) + err = GetLastError(); + if (n < wlen) { /* Wrote fewer characters than expected, which means our * len value may be wrong. So recalculate it from the @@ -1019,7 +1023,6 @@ _io__WindowsConsoleIO_write_impl(winconsoleio *self, Py_buffer *b) Py_END_ALLOW_THREADS if (!res) { - DWORD err = GetLastError(); PyMem_Free(wbuf); return PyErr_SetFromWindowsErr(err); } From 3b5a295487e891b48999e64de9d5023a60bfc857 Mon Sep 17 00:00:00 2001 From: Segev Finer Date: Fri, 2 Jun 2017 09:55:21 +0300 Subject: [PATCH 2/2] bpo-30544: _io._WindowsConsoleIO.write raises the wrong error when WriteConsoleW fails --- Modules/_io/winconsoleio.c | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/Modules/_io/winconsoleio.c b/Modules/_io/winconsoleio.c index f684e8f0c93999..d51df7e8887cee 100644 --- a/Modules/_io/winconsoleio.c +++ b/Modules/_io/winconsoleio.c @@ -966,7 +966,6 @@ _io__WindowsConsoleIO_write_impl(winconsoleio *self, Py_buffer *b) BOOL res = TRUE; wchar_t *wbuf; DWORD len, wlen, n = 0; - DWORD err; if (self->handle == INVALID_HANDLE_VALUE) return err_closed(); @@ -1001,10 +1000,7 @@ _io__WindowsConsoleIO_write_impl(winconsoleio *self, Py_buffer *b) wlen = MultiByteToWideChar(CP_UTF8, 0, b->buf, len, wbuf, wlen); if (wlen) { res = WriteConsoleW(self->handle, wbuf, wlen, &n, NULL); - if (!res) - err = GetLastError(); - - if (n < wlen) { + if (res && n < wlen) { /* Wrote fewer characters than expected, which means our * len value may be wrong. So recalculate it from the * characters that were written. As this could potentially @@ -1023,6 +1019,7 @@ _io__WindowsConsoleIO_write_impl(winconsoleio *self, Py_buffer *b) Py_END_ALLOW_THREADS if (!res) { + DWORD err = GetLastError(); PyMem_Free(wbuf); return PyErr_SetFromWindowsErr(err); }