Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit ad293f5

Browse filesBrowse files
committed
BUG: Prevent segmentation fault in np.asanyarray
1 parent ed8160f commit ad293f5
Copy full SHA for ad293f5

File tree

Expand file treeCollapse file tree

2 files changed

+29
-0
lines changed
Filter options
Expand file treeCollapse file tree

2 files changed

+29
-0
lines changed

‎numpy/_core/src/multiarray/ctors.c

Copy file name to clipboardExpand all lines: numpy/_core/src/multiarray/ctors.c
+6Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2250,6 +2250,12 @@ PyArray_FromInterface(PyObject *origin)
22502250
/* Get dimensions from shape tuple */
22512251
else {
22522252
n = PyTuple_GET_SIZE(attr);
2253+
if (n > NPY_MAXDIMS) {
2254+
PyErr_Format( PyExc_ValueError,
2255+
"number of dimensions must be within [0, %d], got %d",
2256+
NPY_MAXDIMS, n );
2257+
goto fail;
2258+
}
22532259
for (i = 0; i < n; i++) {
22542260
PyObject *tmp = PyTuple_GET_ITEM(attr, i);
22552261
dims[i] = PyArray_PyIntAsIntp(tmp);

‎numpy/_core/tests/test_multiarray.py

Copy file name to clipboardExpand all lines: numpy/_core/tests/test_multiarray.py
+23Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10420,3 +10420,26 @@ def test_to_device(self):
1042010420
r"The stream argument in to_device\(\) is not supported"
1042110421
):
1042210422
arr.to_device("cpu", stream=1)
10423+
10424+
def test_asanyarray_excess_dimensions_raises():
10425+
"""Regression test for gh-27949: ensure too many dims raises ValueError instead of segfault."""
10426+
import numpy as np
10427+
import pytest
10428+
10429+
# Dummy object to hold a custom __array_interface__
10430+
class DummyArray:
10431+
def __init__(self, interface):
10432+
# Attach the array interface dict to mimic an array
10433+
self.__array_interface__ = interface
10434+
10435+
# Create a base array (scalar) and copy its interface
10436+
base = np.array(42) # base can be any scalar or array
10437+
interface = dict(base.__array_interface__)
10438+
10439+
# Modify the shape to exceed NumPy's dimension limit (NPY_MAXDIMS, typically 64)
10440+
interface['shape'] = tuple([1] * 136) # match the original bug report
10441+
10442+
dummy = DummyArray(interface)
10443+
# Now, using np.asanyarray on this dummy should trigger a ValueError (not segfault)
10444+
with pytest.raises(ValueError, match="dimensions must be within"):
10445+
np.asanyarray(dummy)

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.