From a0a5b8bab3d69c08e63fa53f3b754e3e6c0c49ff Mon Sep 17 00:00:00 2001 From: "Gregory P. Smith" <68491+gpshead@users.noreply.github.com> Date: Tue, 20 Oct 2026 16:00:14 -0700 Subject: [PATCH] gh-159739: Fix crash in _PyTuple_Resize() with an invalid size (GH-159804) _PyTuple_Resize() did not validate newsize for non-empty tuples. Raise SystemError for a negative size and MemoryError for a too-large size, like PyTuple_New() already does for the empty-tuple path. (cherry picked from commit c3608845b678729245ef03deb78c47cdabcddf5f) Co-authored-by: Gregory P. Smith <68491+gpshead@users.noreply.github.com> --- Lib/test/test_capi/test_tuple.py | 4 ++++ .../2026-10-19-21-05-12.gh-issue-159739.Rk3fTq.rst | 3 +++ Objects/tupleobject.c | 10 +++++++++- 3 files changed, 16 insertions(+), 1 deletion(-) create mode 100644 Misc/NEWS.d/next/C_API/2026-10-19-21-05-12.gh-issue-159739.Rk3fTq.rst diff --git a/Lib/test/test_capi/test_tuple.py b/Lib/test/test_capi/test_tuple.py index 3683c008dbcaaf..3b5f0336d696bc 100644 --- a/Lib/test/test_capi/test_tuple.py +++ b/Lib/test/test_capi/test_tuple.py @@ -261,6 +261,10 @@ def test__tuple_resize(self): self.assertRaises(MemoryError, resize, a, PY_SSIZE_T_MAX) self.assertRaises(SystemError, resize, a, -1) self.assertRaises(SystemError, resize, a, PY_SSIZE_T_MIN) + a = ([1], [2], [3]) + self.assertRaises(MemoryError, resize, a, PY_SSIZE_T_MAX) + self.assertRaises(SystemError, resize, a, -1) + self.assertRaises(SystemError, resize, a, PY_SSIZE_T_MIN) # refcount > 1 a = (1, 2, 3) self.assertRaises(SystemError, resize, a, 3, False) diff --git a/Misc/NEWS.d/next/C_API/2026-10-19-21-05-12.gh-issue-159739.Rk3fTq.rst b/Misc/NEWS.d/next/C_API/2026-10-19-21-05-12.gh-issue-159739.Rk3fTq.rst new file mode 100644 index 00000000000000..2d510c63ac07a8 --- /dev/null +++ b/Misc/NEWS.d/next/C_API/2026-10-19-21-05-12.gh-issue-159739.Rk3fTq.rst @@ -0,0 +1,3 @@ +Fix a crash in :c:func:`_PyTuple_Resize` when resizing a non-empty tuple to a +negative or too large size. It now raises :exc:`SystemError` or +:exc:`MemoryError` respectively. diff --git a/Objects/tupleobject.c b/Objects/tupleobject.c index 9ed8fc3e964386..6e9b36864a12b4 100644 --- a/Objects/tupleobject.c +++ b/Objects/tupleobject.c @@ -961,7 +961,7 @@ _PyTuple_Resize(PyObject **pv, Py_ssize_t newsize) Py_ssize_t oldsize; v = (PyTupleObject *) *pv; - if (v == NULL || !Py_IS_TYPE(v, &PyTuple_Type) || + if (v == NULL || !Py_IS_TYPE(v, &PyTuple_Type) || newsize < 0 || (Py_SIZE(v) != 0 && !_PyObject_IsUniquelyReferenced(*pv))) { *pv = 0; Py_XDECREF(v); @@ -988,6 +988,14 @@ _PyTuple_Resize(PyObject **pv, Py_ssize_t newsize) *pv = PyTuple_New(newsize); return *pv == NULL ? -1 : 0; } + /* Check for overflow */ + if ((size_t)newsize > ((size_t)PY_SSIZE_T_MAX - (sizeof(PyTupleObject) - + sizeof(PyObject *))) / sizeof(PyObject *)) { + *pv = NULL; + Py_DECREF(v); + PyErr_NoMemory(); + return -1; + } if (_PyObject_GC_IS_TRACKED(v)) { _PyObject_GC_UNTRACK(v);