Skip to content

Commit bb76bff

Browse files
authored
BUG: Fixed crash on self-referential dtypes (#17536)
Instead of causing a C stack overflow, these now raise RecursionError. It shouldn't be possible to recurse through the string, type, or byte conversion paths; only the tuple, dict, and list paths are at risk.
1 parent 7b0a764 commit bb76bff

2 files changed

Lines changed: 44 additions & 3 deletions

File tree

‎numpy/core/src/multiarray/descriptor.c‎

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1497,15 +1497,36 @@ _convert_from_any(PyObject *obj, int align)
14971497
}
14981498
else if (PyTuple_Check(obj)) {
14991499
/* or a tuple */
1500-
return _convert_from_tuple(obj, align);
1500+
if (Py_EnterRecursiveCall(
1501+
" while trying to convert the given data type from"
1502+
" a tuple object" ) != 0) {
1503+
return NULL;
1504+
}
1505+
PyArray_Descr *ret = _convert_from_tuple(obj, align);
1506+
Py_LeaveRecursiveCall();
1507+
return ret;
15011508
}
15021509
else if (PyList_Check(obj)) {
15031510
/* or a list */
1504-
return _convert_from_array_descr(obj, align);
1511+
if (Py_EnterRecursiveCall(
1512+
" while trying to convert the given data type from"
1513+
" a list object" ) != 0) {
1514+
return NULL;
1515+
}
1516+
PyArray_Descr *ret = _convert_from_array_descr(obj, align);
1517+
Py_LeaveRecursiveCall();
1518+
return ret;
15051519
}
15061520
else if (PyDict_Check(obj) || PyDictProxy_Check(obj)) {
15071521
/* or a dictionary */
1508-
return _convert_from_dict(obj, align);
1522+
if (Py_EnterRecursiveCall(
1523+
" while trying to convert the given data type from"
1524+
" a dict object" ) != 0) {
1525+
return NULL;
1526+
}
1527+
PyArray_Descr *ret = _convert_from_dict(obj, align);
1528+
Py_LeaveRecursiveCall();
1529+
return ret;
15091530
}
15101531
else if (PyArray_Check(obj)) {
15111532
PyErr_SetString(PyExc_TypeError, "Cannot construct a dtype from an array");

‎numpy/core/tests/test_dtype.py‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -767,6 +767,26 @@ def test1(self):
767767
('yi', np.dtype((a, (3, 2))))])
768768
assert_dtype_equal(c, d)
769769

770+
def test_list_recursion(self):
771+
l = list()
772+
l.append(('f', l))
773+
with pytest.raises(RecursionError):
774+
np.dtype(l)
775+
776+
def test_tuple_recursion(self):
777+
d = np.int32
778+
for i in range(100000):
779+
d = (d, (1,))
780+
with pytest.raises(RecursionError):
781+
np.dtype(d)
782+
783+
def test_dict_recursion(self):
784+
d = dict(names=['self'], formats=[None], offsets=[0])
785+
d['formats'][0] = d
786+
with pytest.raises(RecursionError):
787+
np.dtype(d)
788+
789+
770790
class TestMetadata:
771791
def test_no_metadata(self):
772792
d = np.dtype(int)

0 commit comments

Comments
 (0)