Skip to content

Commit 2394419

Browse files
committed
Fix use after free in list objects
Set the items pointer in the list object to NULL after the items array is freed during list deallocation. Otherwise, we can end up with a list object added to the free list that contains a pointer to an already-freed items array.
1 parent 8a64a62 commit 2394419

File tree

2 files changed

+20
-1
lines changed

2 files changed

+20
-1
lines changed

Lib/test/test_list.py

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
import sys
2-
from test import list_tests
2+
import textwrap
3+
from test import list_tests, support
34
from test.support import cpython_only
5+
from test.support.import_helper import import_module
6+
from test.support.script_helper import assert_python_failure
47
import pickle
58
import unittest
69

@@ -309,5 +312,20 @@ def test_tier2_invalidates_iterator(self):
309312
a.append(4)
310313
self.assertEqual(list(it), [])
311314

315+
@support.cpython_only
316+
def test_no_memory(self):
317+
# gh-118331: Make sure we don't crash if list allocation fails
318+
import_module("_testcapi")
319+
code = textwrap.dedent("""
320+
import _testcapi, sys
321+
# Prime the freelist
322+
l = [None]
323+
del l
324+
_testcapi.set_nomemory(0)
325+
l = [None]
326+
""")
327+
_, _, err = assert_python_failure("-c", code)
328+
self.assertIn("MemoryError", err.decode("utf-8"))
329+
312330
if __name__ == "__main__":
313331
unittest.main()

Objects/listobject.c

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -533,6 +533,7 @@ list_dealloc(PyObject *self)
533533
Py_XDECREF(op->ob_item[i]);
534534
}
535535
free_list_items(op->ob_item, false);
536+
op->ob_item = NULL;
536537
}
537538
if (PyList_CheckExact(op)) {
538539
_Py_FREELIST_FREE(lists, op, PyObject_GC_Del);

0 commit comments

Comments
 (0)