Skip to content

reject negative indices in numpy array bounds checks - #6187

Open
sayed0200 wants to merge 1 commit into
pybind:masterfrom
sayed0200:numpy-reject-negative-index
Open

sayed0200 wants to merge 1 commit into
pybind:masterfrom
sayed0200:numpy-reject-negative-index

Conversation

@sayed0200

Copy link
Copy Markdown

Description

array::check_dimensions_impl (reached through byte_offset, offset_at, index_at, data, mutable_data, and array_t::at/mutable_at) only tested i >= *shape, and array::shape(dim)/array::strides(dim) only tested dim >= ndim(). A negative index or axis forwarded from Python passed the out-of-bounds guard and yielded a negative byte offset, i.e. an access before the start of the buffer. For at/data that is an out-of-bounds read; for mutable_at/mutable_data it is an out-of-bounds write at a caller-chosen negative offset.

Built against py::array_t<uint16_t>, a.at(-1) reads two bytes before the allocation (ASan reports heap-buffer-overflow) and a.mutable_at(-4096) = v writes far below it. These accessors already document that they throw when an index is out of bounds; a negative value is out of bounds, so the lower-bound check belongs in the accessor rather than at every binding call site. With the fix all three raise index_error the same way an over-large index does.

Added negative-index and negative-axis cases to the existing test_bounds_check and test_array_attributes; they fail on the current code and pass with the fix.

Suggested changelog entry:

  • Negative indices/axes passed to array/array_t element and shape/stride accessors now raise IndexError instead of addressing memory before the start of the buffer.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant