[3.12] gh-111942: Fix SystemError in the TextIOWrapper constructor (GH-112061) (GH-112089)

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 <vstinner@python.org>
(cherry picked from commit 9302f05f9a)

Co-authored-by: Serhiy Storchaka <storchaka@gmail.com>
This commit is contained in:
Victor Stinner 2023-11-15 14:55:46 +01:00 committed by GitHub
parent 91a33fde48
commit 1445d77282
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 14 additions and 5 deletions

View file

@ -1119,6 +1119,15 @@ _io_TextIOWrapper___init___impl(textio *self, PyObject *buffer,
else if (io_check_errors(errors)) {
return -1;
}
Py_ssize_t errors_len;
const char *errors_str = PyUnicode_AsUTF8AndSize(errors, &errors_len);
if (errors_str == NULL) {
return -1;
}
if (strlen(errors_str) != (size_t)errors_len) {
PyErr_SetString(PyExc_ValueError, "embedded null character");
return -1;
}
if (validate_newline(newline) < 0) {
return -1;
@ -1191,11 +1200,11 @@ _io_TextIOWrapper___init___impl(textio *self, PyObject *buffer,
/* Build the decoder object */
_PyIO_State *state = find_io_state_by_def(Py_TYPE(self));
self->state = state;
if (_textiowrapper_set_decoder(self, codec_info, PyUnicode_AsUTF8(errors)) != 0)
if (_textiowrapper_set_decoder(self, codec_info, errors_str) != 0)
goto error;
/* Build the encoder object */
if (_textiowrapper_set_encoder(self, codec_info, PyUnicode_AsUTF8(errors)) != 0)
if (_textiowrapper_set_encoder(self, codec_info, errors_str) != 0)
goto error;
/* Finished sorting out the codec details */