Skip to content

Commit fd82f16

Browse files
[3.7] gh-97616: list_resize() checks for integer overflow (GH-97617) (#97629)
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 <vstinner@python.org>
1 parent 98884f5 commit fd82f16

File tree

3 files changed

+24
-2
lines changed

3 files changed

+24
-2
lines changed

Lib/test/test_list.py

+13
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,19 @@ def imul(a, b): a *= b
6767
self.assertRaises((MemoryError, OverflowError), mul, lst, n)
6868
self.assertRaises((MemoryError, OverflowError), imul, lst, n)
6969

70+
def test_list_resize_overflow(self):
71+
# gh-97616: test new_allocated * sizeof(PyObject*) overflow
72+
# check in list_resize()
73+
lst = [0] * 65
74+
del lst[1:]
75+
self.assertEqual(len(lst), 1)
76+
77+
size = ((2 ** (tuple.__itemsize__ * 8) - 1) // 2)
78+
with self.assertRaises((MemoryError, OverflowError)):
79+
lst * size
80+
with self.assertRaises((MemoryError, OverflowError)):
81+
lst *= size
82+
7083
def test_repr_large(self):
7184
# Check the repr of large list objects
7285
def check(n):
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

+8-2
Original file line numberDiff line numberDiff line change
@@ -64,8 +64,14 @@ list_resize(PyListObject *self, Py_ssize_t newsize)
6464

6565
if (newsize == 0)
6666
new_allocated = 0;
67-
num_allocated_bytes = new_allocated * sizeof(PyObject *);
68-
items = (PyObject **)PyMem_Realloc(self->ob_item, num_allocated_bytes);
67+
if (new_allocated <= (size_t)PY_SSIZE_T_MAX / sizeof(PyObject *)) {
68+
num_allocated_bytes = new_allocated * sizeof(PyObject *);
69+
items = (PyObject **)PyMem_Realloc(self->ob_item, num_allocated_bytes);
70+
}
71+
else {
72+
// integer overflow
73+
items = NULL;
74+
}
6975
if (items == NULL) {
7076
PyErr_NoMemory();
7177
return -1;

0 commit comments

Comments
 (0)