Skip to content

Commit f65f3a9

Browse files
[3.9] gh-97616: list_resize() checks for integer overflow (GH-97617) (GH-97627)
gh-97616: list_resize() checks for integer overflow (GH-97617) Fix multiplying a list by an integer (list *= int): detect the integer overflow when the new allocated length is close to the maximum size. Issue reported by Jordan Limor. list_resize() now checks for integer overflow before multiplying the new allocated length by the list item size (sizeof(PyObject*)). (cherry picked from commit a5f092f) Co-authored-by: Victor Stinner <[email protected]>
1 parent d6ef680 commit f65f3a9

File tree

3 files changed

+24
-2
lines changed

3 files changed

+24
-2
lines changed

Lib/test/test_list.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,19 @@ def imul(a, b): a *= b
6868
self.assertRaises((MemoryError, OverflowError), mul, lst, n)
6969
self.assertRaises((MemoryError, OverflowError), imul, lst, n)
7070

71+
def test_list_resize_overflow(self):
72+
# gh-97616: test new_allocated * sizeof(PyObject*) overflow
73+
# check in list_resize()
74+
lst = [0] * 65
75+
del lst[1:]
76+
self.assertEqual(len(lst), 1)
77+
78+
size = ((2 ** (tuple.__itemsize__ * 8) - 1) // 2)
79+
with self.assertRaises((MemoryError, OverflowError)):
80+
lst * size
81+
with self.assertRaises((MemoryError, OverflowError)):
82+
lst *= size
83+
7184
def test_repr_large(self):
7285
# Check the repr of large list objects
7386
def check(n):
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Fix multiplying a list by an integer (``list *= int``): detect the integer
2+
overflow when the new allocated length is close to the maximum size. Issue
3+
reported by Jordan Limor. Patch by Victor Stinner.

Objects/listobject.c

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -68,8 +68,14 @@ list_resize(PyListObject *self, Py_ssize_t newsize)
6868

6969
if (newsize == 0)
7070
new_allocated = 0;
71-
num_allocated_bytes = new_allocated * sizeof(PyObject *);
72-
items = (PyObject **)PyMem_Realloc(self->ob_item, num_allocated_bytes);
71+
if (new_allocated <= (size_t)PY_SSIZE_T_MAX / sizeof(PyObject *)) {
72+
num_allocated_bytes = new_allocated * sizeof(PyObject *);
73+
items = (PyObject **)PyMem_Realloc(self->ob_item, num_allocated_bytes);
74+
}
75+
else {
76+
// integer overflow
77+
items = NULL;
78+
}
7379
if (items == NULL) {
7480
PyErr_NoMemory();
7581
return -1;

0 commit comments

Comments
 (0)