From 3f033eadab668fd2d338f44aa95fa77d709170f0 Mon Sep 17 00:00:00 2001 From: Eric Wieser Date: Thu, 6 Jun 2019 23:45:57 -0700 Subject: [PATCH] [2.7] bpo-37188: Fix a divide-by-zero in arrays of size-0 objects `itemsize` can be zero when `_type_` is an empty struct or length-0 array. This line used to be `length * itemsize < 0`, which didn't exhibit this problem. --- Lib/ctypes/test/test_arrays.py | 15 +++++++++++++++ Modules/_ctypes/_ctypes.c | 2 +- 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/Lib/ctypes/test/test_arrays.py b/Lib/ctypes/test/test_arrays.py index 29fd422a68cc0d3..ec00d9f9f657ee5 100644 --- a/Lib/ctypes/test/test_arrays.py +++ b/Lib/ctypes/test/test_arrays.py @@ -134,6 +134,21 @@ class my_int(c_int): t2 = my_int * 1 self.assertIs(t1, t2) + def test_empty_element_struct(self): + class EmptyStruct(Structure): + _fields_ = [] + + obj = (EmptyStruct * 2)() # bpo37188: Floating point exception + self.assertEqual(sizeof(obj), 0) + + def test_empty_element_array(self): + class EmptyArray(Array): + _type_ = c_int + _length_ = 0 + + obj = (EmptyArray * 2)() # bpo37188: Floating point exception + self.assertEqual(sizeof(obj), 0) + def test_bpo36504_signed_int_overflow(self): # The overflow check in PyCArrayType_new() could cause signed integer # overflow. diff --git a/Modules/_ctypes/_ctypes.c b/Modules/_ctypes/_ctypes.c index d608100243d8b96..bef251ef049d5ef 100644 --- a/Modules/_ctypes/_ctypes.c +++ b/Modules/_ctypes/_ctypes.c @@ -1534,7 +1534,7 @@ PyCArrayType_new(PyTypeObject *type, PyObject *args, PyObject *kwds) } itemsize = itemdict->size; - if (length > PY_SSIZE_T_MAX / itemsize) { + if (itemsize != 0 && length > PY_SSIZE_T_MAX / itemsize) { PyErr_SetString(PyExc_OverflowError, "array too large"); Py_DECREF(stgdict);