]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-153296: Fix thread-safety data race in io.StringIO iterator (#153368)
authorRishit Agnihotri <67520802+Twix1288@users.noreply.github.com>
Sat, 25 Jul 2026 08:35:25 +0000 (01:35 -0700)
committerGitHub <noreply@github.com>
Sat, 25 Jul 2026 08:35:25 +0000 (14:05 +0530)
Misc/NEWS.d/next/Library/2026-07-08-15-26-00.gh-issue-153296.Twix12.rst [new file with mode: 0644]
Modules/_io/stringio.c

diff --git a/Misc/NEWS.d/next/Library/2026-07-08-15-26-00.gh-issue-153296.Twix12.rst b/Misc/NEWS.d/next/Library/2026-07-08-15-26-00.gh-issue-153296.Twix12.rst
new file mode 100644 (file)
index 0000000..22604dd
--- /dev/null
@@ -0,0 +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.
index b8601383ad0a26fa7f1eb607bdce87fab3befb3e..27605b4c44239e9679624ad01e0ebb4510b63093 100644 (file)
@@ -407,8 +407,10 @@ _io_StringIO_readline_impl(stringio *self, Py_ssize_t size)
 }
 
 static PyObject *
-stringio_iternext(PyObject *op)
+stringio_iternext_lock_held(PyObject *op)
 {
+    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(op);
+
     PyObject *line;
     stringio *self = stringio_CAST(op);
 
@@ -444,6 +446,16 @@ stringio_iternext(PyObject *op)
     return line;
 }
 
+static PyObject *
+stringio_iternext(PyObject *op)
+{
+    PyObject *ret;
+    Py_BEGIN_CRITICAL_SECTION(op);
+    ret = stringio_iternext_lock_held(op);
+    Py_END_CRITICAL_SECTION();
+    return ret;
+}
+
 /*[clinic input]
 @critical_section
 _io.StringIO.truncate