Skip to content

Commit bff0051

Browse files
authored
gh-153296: Fix thread-safety data race in io.StringIO iterator (#153368)
1 parent e31d302 commit bff0051

2 files changed

Lines changed: 14 additions & 1 deletion

File tree

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fix a data race and use-after-free when iterating over an :class:`io.StringIO` object while it is being concurrently mutated. The ``__next__`` method now properly acquires the object's lock.

Modules/_io/stringio.c

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -407,8 +407,10 @@ _io_StringIO_readline_impl(stringio *self, Py_ssize_t size)
407407
}
408408

409409
static PyObject *
410-
stringio_iternext(PyObject *op)
410+
stringio_iternext_lock_held(PyObject *op)
411411
{
412+
_Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(op);
413+
412414
PyObject *line;
413415
stringio *self = stringio_CAST(op);
414416

@@ -444,6 +446,16 @@ stringio_iternext(PyObject *op)
444446
return line;
445447
}
446448

449+
static PyObject *
450+
stringio_iternext(PyObject *op)
451+
{
452+
PyObject *ret;
453+
Py_BEGIN_CRITICAL_SECTION(op);
454+
ret = stringio_iternext_lock_held(op);
455+
Py_END_CRITICAL_SECTION();
456+
return ret;
457+
}
458+
447459
/*[clinic input]
448460
@critical_section
449461
_io.StringIO.truncate

0 commit comments

Comments
 (0)