Skip to content

Fix out-of-bounds reads and writes when indexing a zero-dimensional array with an index array - #47

Merged
yoshoku merged 4 commits into
yoshoku:mainfrom
Watson1978:fix-zero-d-index-array
Dec 1, 2026
Merged

yoshoku merged 4 commits into
yoshoku:mainfrom
Watson1978:fix-zero-d-index-array

Conversation

@Watson1978

Copy link
Copy Markdown
Contributor

Purpose

Indexing a zero-dimensional array with an index array reads or writes past its buffer. The values in the index array are not used, and each extra index goes one element further.

Numo::DFloat.cast(7)[Numo::Int32[0, 0, 0]].to_a  # [7.0, 0.0, 6.9423563810322e-310]

x = Numo::DFloat.cast(7)
x[Numo::Int32[0, 0, 0]] = 1.0  # writes 16 bytes past the 8-byte buffer

Views (x.view[...]), Ruby Array indexes (x[[0, 0, 0]]), Numo::Bit and Numo::RObject take the same path.

Summary of Changes

An index into a zero-dimensional array has orig_dim == ndim == 0. na_index_aref_nadata and na_index_aref_naview use orig_dim >= ndim to find a :new axis, so they took this index for a new axis. They stepped by the element size and ignored the index array.

  • An axis is now new only when it has no index array. :new never has one, so new axes work as before.
  • In na_index_aref_naview, sdx1 started as all zeros, which SDX_IS_INDEX reads as an index with a NULL pointer. It now starts as a zero stride, so the index array takes the "index <- step" branch and every index points to the single element. na_index_aref_nadata already starts with a zero stride.

Cumo fixed the same in sonots/cumo#661.

Testing

  • Tests pass locally
  • Manual testing completed
Numo::DFloat.cast(7)[Numo::Int32[0, 0, 0]].to_a  # [7.0, 7.0, 7.0]

x = Numo::DFloat.cast(7)
x[Numo::Int32[0, 0, 0]] = 1.0
x[0]  # 1.0

With Ruby 4.0.9 built with AddressSanitizer, the code before the fix reports a heap-buffer-overflow in iter_dfloat_to_a for the read and in iter_dfloat_store_dfloat for the write. The fixed code reports nothing for these cases or for the test suites. 38 other indexing results, such as :new axes, index arrays on 1-D and 2-D arrays, out-of-range indexes and writes, are the same before and after the fix.

The new tests fail on the code before the fix. test_narray, test_bit, test_extra, test_math and test_ractor all pass on Ruby 4.0.10.

Related Issues

Relates to sonots/cumo#661.

🤖 Generated with Claude Code

@yoshoku

yoshoku commented Nov 30, 2026

Copy link
Copy Markdown
Owner

/opencode review

@yoshoku

yoshoku commented Nov 30, 2026

Copy link
Copy Markdown
Owner

@Watson1978 I have updated the opencode-review workflow, so could you please rebase your branch onto main?

Watson1978 and others added 2 commits November 30, 2026 23:16
…al array

An index into a zero-dimensional array is past its last dimension, so
the aref functions took it for a new axis. They stepped by the element
size and ignored the index array, so each extra index read or wrote one
element further, outside the zero-dimensional array.

Treat an axis as new only when it has no index array. In the view path,
start with a zero stride so that the index array takes the
"index <- step" branch.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@Watson1978
Watson1978 force-pushed the fix-zero-d-index-array branch from af1722b to a019d1b Compare November 30, 2026 14:16
@Watson1978

Copy link
Copy Markdown
Contributor Author

Rebased

@yoshoku

yoshoku commented Dec 1, 2026

Copy link
Copy Markdown
Owner

/opencode review

@github-actions

github-actions Bot commented Dec 1, 2026

Copy link
Copy Markdown

PR Review: Fix out-of-bounds reads/writes when indexing a 0-d array with an index array

Verdict

The fix is correct and minimal. I traced the full indexing pipeline (parse → check_index_count → na_aref_md → na_index_aref_nadata/na_index_aref_naview) and found no regressions. A few minor test-coverage and comment suggestions below.

Why the fix is correct

Root cause confirmed. For a 0-d array, every parsed index arg gets orig_dim = 0 == na1->ndim, so the old test qi_orig_dim >= na1->base.ndim (index.c:529, 591) misclassified index arrays as :new axes. The result was a view of shape [N] whose only addressed element is the single one, so iteration read/wrote at offsets 0, elmsz, 2*elmsz, ... past the 1-element buffer.

The q[i].idx == NULL guard is safe. I verified the invariant that orig_dim >= na1->ndim can only arise from two situations:

  1. A sym_new arg — na_index_set_step always sets idx = NULL (index.c:304), so genuine :new axes still take the new-axis branch, and ranges/true/nil into a 0-d array (also idx == NULL) keep working as 1-element new axes, exactly as the new comment in na_index_parse_args states.
  2. A non-symbol arg on a 0-d array (k == 0, ndim == 0) — precisely the bug being fixed; these now fall through to the array-index branches where stride1 == 0 maps every index entry onto the single element (index[k] = index[k] * 0), which matches numpy's semantics for np.array(7)[np.array([0,0,0])].

I also checked check_index_count paths to confirm no other arg combination can produce orig_dim >= ndim with a non-NULL idx (rest/ellipsis expansion keeps k < na1->ndim, and multi-arg forms on 0-d arrays raise IndexError before parsing).

The sdx1 init change is required, not cosmetic. With the classification fixed, the 0-d case in na_index_aref_naview now reaches q[i].idx != NULL && SDX_IS_INDEX(sdx1). The old zero-init made SDX_IS_INDEX true while SDX_GET_INDEX was NULL → guaranteed NULL dereference in the "index <- index" branch. SDX_SET_STRIDE(sdx1, 0) tags it as a stride-0, so index arrays take the "index <- step" branch, which handles stride 0 cleanly (index.c:605-629). This mirrors the stride1 = 0 default in na_index_aref_nadata (index.c:510). Good catch — without this, the naview half of the fix would segfault.

Memory ownership is preserved. Each array-index branch sets q[i].idx = NULL after transferring the pointer to na2->stridx, so na_aref_md_ensure still frees exactly once. No leak or double-free introduced.

Assignment path is covered. aset with an index array routes through na_get_result_dimension → na_aref_main(..., nd=1) → the same fixed functions, then store writes all N elements of the resulting view. The Bit path (bit_aref/bit_aset, stride in bits, elmsz == 1) reduces to the same stride-0 mapping. The RObject triple-write to the same slot is benign.

Minor suggestions

  1. Test coverage gaps (test/test_narray.rb:934-951):
    • The assignment test omits Numo::Int32 (the read test covers it, but the write path is type-templated too). Adding it costs nothing.
    • No test for the Ruby-Array assignment form (b[1, false][[0, 0, 0]] = 1), which takes rb_apply(numo_cNArray, id_bracket, ...) in na_aref_md.
    • No negative assertion locking the bounds check: assert_raises(IndexError) { a[Numo::Int32[1]] } on a 0-d array (any value other than 0/-1 must fail via na_range_check against size 1). Worth pinning so a future refactor can't silently weaken it.
    • No test for the slice (keep_dim) path on 0-d arrays, which shares this code with keep_dim = 1.
  2. Comment clarity (index.c:442-444): "A range or true into a 0-d array matches too, and works as one because it picks the only element" is dense. Something like "args with orig_dim >= ndim and idx == NULL (i.e. :new, or any non-index-array arg on a 0-d array) are new axes; index arrays on a 0-d array instead address the single element N times" would state the invariant the idx == NULL guard relies on more directly.
  3. Pre-existing quirk noticed while tracing (not caused by this PR): x[idx_array, :new] on a 0-d array raises IndexError because na_get_result_dimension counts only :new args toward result_nd (check_index_count: argc(2) != result_nd(1)), whereas the equivalent on a 1-d array works. Fine to leave, but could be a follow-up issue.

The PR description's ASAN evidence, the "tests fail before the fix" property, and the reference to the equivalent Cumo fix all check out against the code. Approve.

github run

Watson1978 and others added 2 commits December 1, 2026 18:06
Add Int32 and a Ruby Array index to the assignment test, and slice and
an out-of-range index to the read test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@Watson1978

Copy link
Copy Markdown
Contributor Author

Thanks for the review. I addressed the minor suggestions.

  • Tests (bc0c772): the assignment test now covers Numo::Int32 and a Ruby Array index (b[1, false][[0, 0, 0]] = 1). The read test now covers slice and an out-of-range index (a[Numo::Int32[1]] raises IndexError). Both tests fail on main.
  • Comment (d553940): the comment in na_index_parse_args now states the new-axis condition first.

I left x[idx, :new] on a 0-d array as it is. It raises IndexError for x[0..0, :new] and x[true, :new] as well, so it is a limit on the number of indices for 0-d arrays and not related to this change.

@yoshoku
yoshoku merged commit c3a5c41 into yoshoku:main Dec 1, 2026
12 checks passed
@Watson1978
Watson1978 deleted the fix-zero-d-index-array branch December 2, 2026 09:58
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.

2 participants