Skip to content

BUG: sanity check __array_interface__ number of dimensions #28449

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 7, 2025
Merged
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
8 changes: 7 additions & 1 deletion numpy/_core/src/multiarray/ctors.c
Original file line number Diff line number Diff line change
Expand Up @@ -2153,7 +2153,7 @@ PyArray_FromInterface(PyObject *origin)
PyArray_Descr *dtype = NULL;
char *data = NULL;
Py_buffer view;
int i, n;
Py_ssize_t i, n;
npy_intp dims[NPY_MAXDIMS], strides[NPY_MAXDIMS];
int dataflags = NPY_ARRAY_BEHAVED;

Expand Down Expand Up @@ -2269,6 +2269,12 @@ PyArray_FromInterface(PyObject *origin)
/* Get dimensions from shape tuple */
else {
n = PyTuple_GET_SIZE(attr);
if (n > NPY_MAXDIMS) {
PyErr_Format(PyExc_ValueError,
"number of dimensions must be within [0, %d], got %d",
NPY_MAXDIMS, n);
goto fail;
}
for (i = 0; i < n; i++) {
PyObject *tmp = PyTuple_GET_ITEM(attr, i);
dims[i] = PyArray_PyIntAsIntp(tmp);
Expand Down
21 changes: 21 additions & 0 deletions numpy/_core/tests/test_multiarray.py
Original file line number Diff line number Diff line change
Expand Up @@ -10358,3 +10358,24 @@ def test_to_device(self):
r"The stream argument in to_device\(\) is not supported"
):
arr.to_device("cpu", stream=1)

def test_array_interface_excess_dimensions_raises():
"""Regression test for gh-27949: ensure too many dims raises ValueError instead of segfault."""

# Dummy object to hold a custom __array_interface__
class DummyArray:
def __init__(self, interface):
# Attach the array interface dict to mimic an array
self.__array_interface__ = interface

# Create a base array (scalar) and copy its interface
base = np.array(42) # base can be any scalar or array
interface = dict(base.__array_interface__)

# Modify the shape to exceed NumPy's dimension limit (NPY_MAXDIMS, typically 64)
interface['shape'] = tuple([1] * 136) # match the original bug report

dummy = DummyArray(interface)
# Now, using np.asanyarray on this dummy should trigger a ValueError (not segfault)
with pytest.raises(ValueError, match="dimensions must be within"):
np.asanyarray(dummy)
Loading