Skip to content

Commit f9ce9d4

Browse files
[3.8] gh-97616: list_resize() checks for integer overflow (GH-97617) (GH-97628)
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 9062049 commit f9ce9d4

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
@@ -66,8 +66,14 @@ list_resize(PyListObject *self, Py_ssize_t newsize)
6666

6767
if (newsize == 0)
6868
new_allocated = 0;
69-
num_allocated_bytes = new_allocated * sizeof(PyObject *);
70-
items = (PyObject **)PyMem_Realloc(self->ob_item, num_allocated_bytes);
69+
if (new_allocated <= (size_t)PY_SSIZE_T_MAX / sizeof(PyObject *)) {
70+
num_allocated_bytes = new_allocated * sizeof(PyObject *);
71+
items = (PyObject **)PyMem_Realloc(self->ob_item, num_allocated_bytes);
72+
}
73+
else {
74+
// integer overflow
75+
items = NULL;
76+
}
7177
if (items == NULL) {
7278
PyErr_NoMemory();
7379
return -1;

0 commit comments

Comments
 (0)