Skip to content
Closed
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
18 changes: 18 additions & 0 deletions Lib/ctypes/test/test_arrays.py
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,24 @@ class T(Array):
_type_ = c_int
_length_ = 1.87

def test_bad_length(self):
with self.assertRaises(ValueError):
class T(Array):
_type_ = c_int
_length_ = -1 << 1000
with self.assertRaises(ValueError):
class T(Array):
_type_ = c_int
_length_ = -1
with self.assertRaises(OverflowError):
class T(Array):
_type_ = c_int
_length_ = 1 << 1000
# _length_ might be zero.
class T(Array):
_type_ = c_int
_length_ = 0

@unittest.skipUnless(sys.maxsize > 2**32, 'requires 64bit platform')
@bigmemtest(size=_2G, memuse=1, dry_run=False)
def test_large_array(self, size):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Raise `ValueError` instead of `OverflowError` in case of a negative
``_length_`` in a `ctypes.Array` subclass. Patch by Oren Milman.
15 changes: 12 additions & 3 deletions Modules/_ctypes/_ctypes.c
Original file line number Diff line number Diff line change
Expand Up @@ -1391,6 +1391,7 @@ PyCArrayType_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
StgDictObject *itemdict;
PyObject *length_attr, *type_attr;
Py_ssize_t length;
int overflow;
Py_ssize_t itemsize, itemalign;

/* create the new instance (which is a class,
Expand All @@ -1412,13 +1413,21 @@ PyCArrayType_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Py_XDECREF(length_attr);
goto error;
}
length = PyLong_AsSsize_t(length_attr);
length = PyLong_AsLongAndOverflow(length_attr, &overflow);
Py_DECREF(length_attr);
if (length == -1 && PyErr_Occurred()) {
if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
/* PyLong_Check(length_attr) is true, so it is guaranteed that
no error occurred in PyLong_AsLongAndOverflow(). */
assert(!(length == -1 && PyErr_Occurred()));
if (overflow || length < 0) {
if (overflow > 0) {
PyErr_SetString(PyExc_OverflowError,
"The '_length_' attribute is too large");
}
else {
assert(overflow < 0 || length < 0);
PyErr_SetString(PyExc_ValueError,
"The '_length_' attribute must be non-negative");
}
goto error;
}

Expand Down