File tree Expand file tree Collapse file tree 2 files changed +28
-1
lines changed Expand file tree Collapse file tree 2 files changed +28
-1
lines changed Original file line number Diff line number Diff line change @@ -2153,7 +2153,7 @@ PyArray_FromInterface(PyObject *origin)
2153
2153
PyArray_Descr * dtype = NULL ;
2154
2154
char * data = NULL ;
2155
2155
Py_buffer view ;
2156
- int i , n ;
2156
+ Py_ssize_t i , n ;
2157
2157
npy_intp dims [NPY_MAXDIMS ], strides [NPY_MAXDIMS ];
2158
2158
int dataflags = NPY_ARRAY_BEHAVED ;
2159
2159
@@ -2269,6 +2269,12 @@ PyArray_FromInterface(PyObject *origin)
2269
2269
/* Get dimensions from shape tuple */
2270
2270
else {
2271
2271
n = PyTuple_GET_SIZE (attr );
2272
+ if (n > NPY_MAXDIMS ) {
2273
+ PyErr_Format (PyExc_ValueError ,
2274
+ "number of dimensions must be within [0, %d], got %d" ,
2275
+ NPY_MAXDIMS , n );
2276
+ goto fail ;
2277
+ }
2272
2278
for (i = 0 ; i < n ; i ++ ) {
2273
2279
PyObject * tmp = PyTuple_GET_ITEM (attr , i );
2274
2280
dims [i ] = PyArray_PyIntAsIntp (tmp );
Original file line number Diff line number Diff line change @@ -10358,3 +10358,24 @@ def test_to_device(self):
10358
10358
r"The stream argument in to_device\(\) is not supported"
10359
10359
):
10360
10360
arr .to_device ("cpu" , stream = 1 )
10361
+
10362
+ def test_array_interface_excess_dimensions_raises ():
10363
+ """Regression test for gh-27949: ensure too many dims raises ValueError instead of segfault."""
10364
+
10365
+ # Dummy object to hold a custom __array_interface__
10366
+ class DummyArray :
10367
+ def __init__ (self , interface ):
10368
+ # Attach the array interface dict to mimic an array
10369
+ self .__array_interface__ = interface
10370
+
10371
+ # Create a base array (scalar) and copy its interface
10372
+ base = np .array (42 ) # base can be any scalar or array
10373
+ interface = dict (base .__array_interface__ )
10374
+
10375
+ # Modify the shape to exceed NumPy's dimension limit (NPY_MAXDIMS, typically 64)
10376
+ interface ['shape' ] = tuple ([1 ] * 136 ) # match the original bug report
10377
+
10378
+ dummy = DummyArray (interface )
10379
+ # Now, using np.asanyarray on this dummy should trigger a ValueError (not segfault)
10380
+ with pytest .raises (ValueError , match = "dimensions must be within" ):
10381
+ np .asanyarray (dummy )
You can’t perform that action at this time.
0 commit comments