Skip to content

[3.8] gh-97616: list_resize() checks for integer overflow (GH-97617) #97628

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 1 commit into from
Oct 4, 2022
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 @@ -68,6 +68,19 @@ def imul(a, b): a *= b
self.assertRaises((MemoryError, OverflowError), mul, lst, n)
self.assertRaises((MemoryError, OverflowError), imul, lst, n)

def test_list_resize_overflow(self):
# gh-97616: test new_allocated * sizeof(PyObject*) overflow
# check in list_resize()
lst = [0] * 65
del lst[1:]
self.assertEqual(len(lst), 1)

size = ((2 ** (tuple.__itemsize__ * 8) - 1) // 2)
with self.assertRaises((MemoryError, OverflowError)):
lst * size
with self.assertRaises((MemoryError, OverflowError)):
lst *= size

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,3 @@
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. Patch by Victor Stinner.
10 changes: 8 additions & 2 deletions Objects/listobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -66,8 +66,14 @@ list_resize(PyListObject *self, Py_ssize_t newsize)

if (newsize == 0)
new_allocated = 0;
num_allocated_bytes = new_allocated * sizeof(PyObject *);
items = (PyObject **)PyMem_Realloc(self->ob_item, num_allocated_bytes);
if (new_allocated <= (size_t)PY_SSIZE_T_MAX / sizeof(PyObject *)) {
num_allocated_bytes = new_allocated * sizeof(PyObject *);
items = (PyObject **)PyMem_Realloc(self->ob_item, num_allocated_bytes);
}
else {
// integer overflow
items = NULL;
}
if (items == NULL) {
PyErr_NoMemory();
return -1;
Expand Down