From a4196612d65fbc26c3a4e4d55752303f8b9cb61a Mon Sep 17 00:00:00 2001 From: Eric Wieser Date: Fri, 7 Jun 2019 01:13:26 -0700 Subject: [PATCH 1/2] bpo-37188: Fix a divide-by-zero in arrays of size-0 objects (GH-13881) (cherry picked from commit 0690c79c419b8d2bdfe7c5b6dca57b018f5a5a54) Co-authored-by: Eric Wieser --- 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 87ecbf04e7edbb6..a3e6d76940e0a19 100644 --- a/Lib/ctypes/test/test_arrays.py +++ b/Lib/ctypes/test/test_arrays.py @@ -208,6 +208,21 @@ class T(Array): _type_ = c_int _length_ = 0 + def test_empty_element_struct(self): + class EmptyStruct(Structure): + _fields_ = [] + + obj = (EmptyStruct * 2)() # bpo37188: Floating point exception + assert sizeof(obj) == 0 + + def test_empty_element_array(self): + class EmptyArray(Array): + _type_ = c_int + _length_ = 0 + + obj = (EmptyArray * 2)() # bpo37188: Floating point exception + assert 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 f7513a3d74c4bc2..2201c4520ad048f 100644 --- a/Modules/_ctypes/_ctypes.c +++ b/Modules/_ctypes/_ctypes.c @@ -1518,7 +1518,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"); goto error; From b4a77ba87be63360ef04ac3af8f6f98ae0199c49 Mon Sep 17 00:00:00 2001 From: Stefan Krah Date: Sat, 8 Jun 2019 11:28:13 +0200 Subject: [PATCH 2/2] Use assertEqual(). --- Lib/ctypes/test/test_arrays.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Lib/ctypes/test/test_arrays.py b/Lib/ctypes/test/test_arrays.py index a3e6d76940e0a19..14603b7049c92c5 100644 --- a/Lib/ctypes/test/test_arrays.py +++ b/Lib/ctypes/test/test_arrays.py @@ -213,7 +213,7 @@ class EmptyStruct(Structure): _fields_ = [] obj = (EmptyStruct * 2)() # bpo37188: Floating point exception - assert sizeof(obj) == 0 + self.assertEqual(sizeof(obj), 0) def test_empty_element_array(self): class EmptyArray(Array): @@ -221,7 +221,7 @@ class EmptyArray(Array): _length_ = 0 obj = (EmptyArray * 2)() # bpo37188: Floating point exception - assert sizeof(obj) == 0 + self.assertEqual(sizeof(obj), 0) def test_bpo36504_signed_int_overflow(self): # The overflow check in PyCArrayType_new() could cause signed integer