Skip to content

Commit 9302f05

Browse files
gh-111942: Fix SystemError in the TextIOWrapper constructor (#112061)
In non-debug more the check for the "errors" argument is skipped, and then PyUnicode_AsUTF8() can fail, but its result was not checked. Co-authored-by: Victor Stinner <[email protected]>
1 parent 0ff6368 commit 9302f05

File tree

3 files changed

+9
-5
lines changed

3 files changed

+9
-5
lines changed

Lib/test/test_io.py

+1-3
Original file line numberDiff line numberDiff line change
@@ -2725,9 +2725,7 @@ def test_constructor(self):
27252725
if support.Py_DEBUG or sys.flags.dev_mode or self.is_C:
27262726
with self.assertRaises(UnicodeEncodeError):
27272727
t.__init__(b, encoding="utf-8", errors='\udcfe')
2728-
if support.Py_DEBUG or sys.flags.dev_mode:
2729-
# TODO: If encoded to UTF-8, should also be checked for
2730-
# embedded null characters.
2728+
if support.Py_DEBUG or sys.flags.dev_mode or self.is_C:
27312729
with self.assertRaises(ValueError):
27322730
t.__init__(b, encoding="utf-8", errors='replace\0')
27332731
with self.assertRaises(TypeError):
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix SystemError in the TextIOWrapper constructor with non-encodable "errors"
2+
argument in non-debug mode.

Modules/_io/textio.c

+6-2
Original file line numberDiff line numberDiff line change
@@ -1112,6 +1112,10 @@ _io_TextIOWrapper___init___impl(textio *self, PyObject *buffer,
11121112
else if (io_check_errors(errors)) {
11131113
return -1;
11141114
}
1115+
const char *errors_str = _PyUnicode_AsUTF8NoNUL(errors);
1116+
if (errors_str == NULL) {
1117+
return -1;
1118+
}
11151119

11161120
if (validate_newline(newline) < 0) {
11171121
return -1;
@@ -1184,11 +1188,11 @@ _io_TextIOWrapper___init___impl(textio *self, PyObject *buffer,
11841188
/* Build the decoder object */
11851189
_PyIO_State *state = find_io_state_by_def(Py_TYPE(self));
11861190
self->state = state;
1187-
if (_textiowrapper_set_decoder(self, codec_info, PyUnicode_AsUTF8(errors)) != 0)
1191+
if (_textiowrapper_set_decoder(self, codec_info, errors_str) != 0)
11881192
goto error;
11891193

11901194
/* Build the encoder object */
1191-
if (_textiowrapper_set_encoder(self, codec_info, PyUnicode_AsUTF8(errors)) != 0)
1195+
if (_textiowrapper_set_encoder(self, codec_info, errors_str) != 0)
11921196
goto error;
11931197

11941198
/* Finished sorting out the codec details */

0 commit comments

Comments
 (0)