There was an error while loading. Please reload this page.
1 parent 5e52778 commit 3ef9f6bCopy full SHA for 3ef9f6b
2 files changed
Misc/NEWS.d/next/Windows/2023-01-17-18-17-58.gh-issue-82052.mWyysT.rst
@@ -0,0 +1 @@
1
+Fixed an issue where writing more than 32K of Unicode output to the console screen in one go can result in mojibake.
Modules/_io/winconsoleio.c
@@ -954,7 +954,7 @@ _io__WindowsConsoleIO_write_impl(winconsoleio *self, Py_buffer *b)
954
{
955
BOOL res = TRUE;
956
wchar_t *wbuf;
957
- DWORD len, wlen, n = 0;
+ DWORD len, wlen, orig_len, n = 0;
958
HANDLE handle;
959
960
if (self->fd == -1)
@@ -984,6 +984,21 @@ _io__WindowsConsoleIO_write_impl(winconsoleio *self, Py_buffer *b)
984
have to reduce and recalculate. */
985
while (wlen > 32766 / sizeof(wchar_t)) {
986
len /= 2;
987
+ orig_len = len;
988
+ /* Reduce the length until we hit the final byte of a UTF-8 sequence
989
+ * (top bit is unset). Fix for github issue 82052.
990
+ */
991
+ while (len > 0 && (((char *)b->buf)[len-1] & 0x80) != 0)
992
+ --len;
993
+ /* If we hit a length of 0, something has gone wrong. This shouldn't
994
+ * be possible, as valid UTF-8 can have at most 3 non-final bytes
995
+ * before a final one, and our buffer is way longer than that.
996
+ * But to be on the safe side, if we hit this issue we just restore
997
+ * the original length and let the console API sort it out.
998
999
+ if (len == 0) {
1000
+ len = orig_len;
1001
+ }
1002
wlen = MultiByteToWideChar(CP_UTF8, 0, b->buf, len, NULL, 0);
1003
}
1004
Py_END_ALLOW_THREADS
0 commit comments