Skip to content

Fix out-of-bounds reads and wrong values when storing a Ruby Array of NArrays - #44

Merged
yoshoku merged 1 commit into
yoshoku:mainfrom
Watson1978:fix-store-subnarray-rows
Nov 29, 2026
Merged

yoshoku merged 1 commit into
yoshoku:mainfrom
Watson1978:fix-store-subnarray-rows

Conversation

@Watson1978

Copy link
Copy Markdown
Contributor

Purpose

After #27, store with a Ruby Array of NArrays still reads outside a sub-narray in some cases. NArray.cast and NArray[] take the same path. The result holds heap data or values from outside the sub-narray, or the call raises.

s = Numo::Int32.new(3, 8).seq
d = Numo::Int32.zeros(2, 3, 8)
d.store([s[[2, 0, 1], true], Numo::Int32.new(1, 8).seq(100)])
d[1, 0, true].to_a  # heap data, such as [-245197043, 22093, -245197056, 22093, ...]

Numo::Int32.new(2, 3).fill(9).store([Numo::Int32[1, 2, 3], Numo::Int32.new(0)])
# TypeError: no implicit conversion of true into Integer

Summary of Changes

All three come from how loop_store_subnarray hands each row to the store template.

  • ndloop_set_stepidx skips an outer axis of length 1, so that axis kept the step and the index of the previous sub-narray. The iterator of argument 1 is now reset for each sub-narray.
  • For a sub-narray that is short in an outer axis, the check ran only when the loop entered that axis, and the flag was reset for every row. The later rows of that axis were read from past the end of the sub-narray instead of being zero-filled, and the loop read the index array of that axis past its end. The loop now keeps per axis whether the sub-narray reaches the row, and does not move the position where it does not.
  • An empty sub-narray has no data pointer, so the store template took the true or false flag for a value. It stored the flag for RObject and could store 1 for Bit, and raised TypeError or NoMethodError for the other types. The number of elements of the row now goes through shape[0], and the template tells a sub-narray row by its value.

The sub-narray is no longer left in the loop argument after its rows. It can be a temporary array from a cast, and ndloop_release would read it after it was collected if a later row raised.

Cumo fixed the same in sonots/cumo#382 to sonots/cumo#386. The restore of shape and elmsz from sonots/cumo#385 is left out, because nothing reads them after the loop here.

Testing

  • Tests pass locally
  • Manual testing completed
d[1, 0, true].to_a  # [100, 101, 102, 103, 104, 105, 106, 107]
Numo::Int32.new(2, 3).fill(9).store([Numo::Int32[1, 2, 3], Numo::Int32.new(0)]).to_a
# [[1, 2, 3], [0, 0, 0]]

I compared store with expected values built from Ruby Arrays. The sweep covers 14 dtypes and destinations of 2 to 4 dimensions. Each case stores one or two sub-narrays that are plain, sliced, offset, indexed or stepped, and that are longer, shorter, empty, or have an axis of length 1. That is 48,160 cases. Before the fix, 8 of the 42 dtype and destination groups crashed. In the other groups, 3,322 of 39,014 cases gave wrong values and 2,928 raised. After the fix, all cases match. With Ruby 4.0.9 built with AddressSanitizer, the code before the fix reports a heap-buffer-overflow in loop_store_subnarray, and the fixed code reports nothing.

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.9 and 4.1-dev.

Related Issues

Follows #27.

🤖 Generated with Claude Code

loop_store_subnarray reuses the iterator of argument 1 for each
sub-narray. ndloop_set_stepidx skips an outer axis of length 1, so that
axis kept the step and the index of the previous sub-narray. The store
then read outside the new sub-narray and wrote heap data into the
destination.

The check for an outer axis that a sub-narray does not reach ran only
when the loop entered that axis, and the flag was reset for every row.
The later rows of that axis were read from past the end of the
sub-narray instead of being zero-filled. The loop also read the index
array of such an axis past its end.

An empty sub-narray has no data pointer, so the store template took the
flag for a value. It stored the flag, or raised TypeError or
NoMethodError.

Reset the iterator of argument 1 for each sub-narray. Track per axis
whether the sub-narray reaches the row, and do not move the position
where it does not. Pass the number of elements of the row through
shape[0], and tell a sub-narray row by its value in the store template.
Clear the value after the rows of a sub-narray. It can be a temporary
array from a cast, and ndloop_release reads it if a later row raises.

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

yoshoku commented Nov 1, 2026

Copy link
Copy Markdown
Owner

/opencode review

@github-actions

github-actions Bot commented Nov 1, 2026

Copy link
Copy Markdown

I reviewed the diff (static analysis plus a local build and reproduction of both examples from the PR description, which now produce the correct values on Ruby 3.2). The extension compiles cleanly, and the three fixes in loop_store_subnarray / store templates line up with the bug analysis: iterator reset per sub-narray, per-axis reach tracking with frozen position (which also prevents the OOB reads of per-axis idx arrays), and IsNArray(v1) + shape[0] for empty sub-narray rows.

I traced the control/data flow of ndloop.c around the change (iter indexing, ndfunc_set_user_loop's ndim/shape wiring, the c[] zeroing invariant between loop_store_rarray and loop_store_subnarray, view vs. data stridx handling in ndloop_set_stepidx, resume-state correctness of reach[] after counter wrap) and did not find a correctness defect in the new logic.

Findings

1. (Low) LARG(lp, 1).value is not cleared on the exception path — ext/numo/narray/ndloop.c:1582
value = Qnil / ptr = NULL happen only at loop_end:, which is skipped if a Ruby exception is raised inside (*(nf->func)). On that path ndloop_release (via rb_ensure) still sees a stale sub-narray, which is exactly the situation the fix targets when the sub-narray is a cast temporary. In practice the object is very likely still kept alive because lp (holding the VALUE) sits on na_ndloop_store_rarray's stack during rb_ensure and Ruby's conservative stack scan marks it, so this is mostly hygiene, not a live UAF. If you want it airtight, wrap the row loop in rb_ensure (or a RAISE-callback) that clears arg 1.

2. (Low) sub_narray_len as a struct field is broader than needed — ext/numo/narray/ndloop.c:1551
A plain size_t local inside loop_store_subnarray (e.g. size_t row_len; LARG(lp,1).shape = &row_len;) would work identically and keeps the hack visible only inside the function. Also note the implied invariant that only shape[0] is ever valid — a one-line comment on the field would help future readers, since shape elsewhere means an array of user dims. (The rationale for omitting Cumo's shape/elmsz restore is sound: nothing else reads arg 1's shape in this loop.)

3. (Nit) Reset range expression — ext/numo/narray/ndloop.c:1546
for (i = 0; i <= nd + lp->user.ndim; i++) happens to equal the allocation-time max_nd for this loop configuration (post-reduction lp->ndim + user.ndim after ud = 1). It is correct, but computing it once into a named variable (matching the max_nd concept used elsewhere in the file) would make the correspondence with the iter allocation obvious.

4. (Nit) The i > 0 guard in the store templates — ext/numo/narray/src/mh/store.h, ext/numo/narray/src/t_bit.c
The guard is harmless but not strictly required (a zero-count iter_*_store_* call is a no-op). Keeping it is fine; just be aware INIT_PTR_IDX(lp, 1, ...) still computes p2 from a possibly-NULL args[1].ptr for empty sub-narrays (pointer arithmetic on NULL, undereferenced) — same as pre-change code, so no regression.

5. (Info) Related limitation remains, pre-existing — verified against both main and this branch: storing a Ruby Array of 1-d NArrays into a 1-d destination still fails, e.g.
Numo::Int32.new(3).store([Numo::Int32[1], Numo::Int32[2], Numo::Int32[3]]) → TypeError: no implicit conversion of Numo::Int32 into Integer.
The rary-of-narrays traversal only engages at a loop level where lp->ndim > 0 before the user.ndim reduction, so level i0 == nd (a 1-d sub-narray as a flat row of a 1-d destination) is unreachable. Not a regression from this PR and arguably out of scope, but worth a note in the log/issue since the PR title covers "storing a Ruby Array of NArrays" generally.

6. (Nit, tests) Two coverage gaps worth considering — test/test_narray.rb

  • No case where the destination row is shorter than the sub-narray's last axis (the if (i > n) i = n; clamp path).
  • No case mixing a scalar row with NArray rows in the same rary (e.g. [sub_narray, 5]), which exercises the IsNArray/TYPE(v1) fallback interaction in the same loop.

The tests as written are good: they fail against pre-fix code (per the PR), cover all dtypes plus Bit explicitly, and the outer-axis-short cases give the reach machinery real coverage across several selector forms.

github run

@yoshoku
yoshoku merged commit cfcd266 into yoshoku:main Nov 29, 2026
14 checks passed
@Watson1978
Watson1978 deleted the fix-store-subnarray-rows branch November 30, 2026 05:27
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