Skip to content

[3.13] gh-132713: Fix repr(list) race condition (#132801) #132809

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Apr 23, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions Lib/test/test_list.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,19 @@ def test_list_resize_overflow(self):
with self.assertRaises((MemoryError, OverflowError)):
lst *= size

def test_repr_mutate(self):
class Obj:
@staticmethod
def __repr__():
try:
mylist.pop()
except IndexError:
pass
return 'obj'

mylist = [Obj() for _ in range(5)]
self.assertEqual(repr(mylist), '[obj, obj, obj]')

def test_repr_large(self):
# Check the repr of large list objects
def check(n):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fix ``repr(list)`` race condition: hold a strong reference to the item while
calling ``repr(item)``. Patch by Victor Stinner.
8 changes: 7 additions & 1 deletion Objects/listobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -585,6 +585,7 @@ list_repr_impl(PyListObject *v)
{
PyObject *s;
_PyUnicodeWriter writer;
PyObject *item = NULL;
Py_ssize_t i = Py_ReprEnter((PyObject*)v);
if (i != 0) {
return i > 0 ? PyUnicode_FromString("[...]") : NULL;
Expand All @@ -601,12 +602,15 @@ list_repr_impl(PyListObject *v)
/* Do repr() on each element. Note that this may mutate the list,
so must refetch the list size on each iteration. */
for (i = 0; i < Py_SIZE(v); ++i) {
/* Hold a strong reference since repr(item) can mutate the list */
item = Py_NewRef(v->ob_item[i]);

if (i > 0) {
if (_PyUnicodeWriter_WriteASCIIString(&writer, ", ", 2) < 0)
goto error;
}

s = PyObject_Repr(v->ob_item[i]);
s = PyObject_Repr(item);
if (s == NULL)
goto error;

Expand All @@ -615,6 +619,7 @@ list_repr_impl(PyListObject *v)
goto error;
}
Py_DECREF(s);
Py_CLEAR(item);
}

writer.overallocate = 0;
Expand All @@ -625,6 +630,7 @@ list_repr_impl(PyListObject *v)
return _PyUnicodeWriter_Finish(&writer);

error:
Py_XDECREF(item);
_PyUnicodeWriter_Dealloc(&writer);
Py_ReprLeave((PyObject *)v);
return NULL;
Expand Down
Loading