py/objstringio.c: Fix segfault in stringio_write.

Fixes issue #10402:
	printing to io.StringIO subclass leads to seg fault.
	stringio_write function does not check o_in is type_stringio.
	This checks for proper type and raises TypeError if it isn't.

Signed-off-by: Carlos Gil Gonzalez <carlosgilglez@gmail.com>
pull/10417/head
Carlosgg 2023-01-05 15:31:01 +00:00
rodzic 699477d12d
commit 89d8f887e0
3 zmienionych plików z 40 dodań i 0 usunięć

Wyświetl plik

@ -77,6 +77,13 @@ STATIC void stringio_copy_on_write(mp_obj_stringio_t *o) {
STATIC mp_uint_t stringio_write(mp_obj_t o_in, const void *buf, mp_uint_t size, int *errcode) {
(void)errcode;
if (!mp_obj_is_type(o_in, &mp_type_stringio)) {
if (!mp_obj_is_type(o_in, &mp_type_bytesio)) {
mp_raise_TypeError(MP_ERROR_TEXT("expecting a StringIO or BytesIO object"));
}
}
mp_obj_stringio_t *o = MP_OBJ_TO_PTR(o_in);
check_stringio_is_open(o);

Wyświetl plik

@ -0,0 +1,31 @@
import sys
sys.path[0] = ".frozen" # avoid local dir io import
import io
class TestStream(io.StringIO):
def __init_(self, alloc_size):
super().__init__(alloc_size)
class ByteStream(io.BytesIO):
def __init_(self, alloc_size):
super().__init__(alloc_size)
test_stringio = TestStream(100)
test_bytesio = ByteStream(100)
try:
print("hello", file=test_stringio)
except Exception as e:
print(e)
try:
print("hello", file=test_bytesio)
except Exception as e:
print(e)

Wyświetl plik

@ -0,0 +1,2 @@
expecting a StringIO or BytesIO object
expecting a StringIO or BytesIO object