Skip to content

Fix crashes in eye, poly and bincount when an axis is empty - #49

Open
Watson1978 wants to merge 2 commits into
yoshoku:mainfrom
Watson1978:fix-empty-axis-without-loop
Open

Watson1978 wants to merge 2 commits into
yoshoku:mainfrom
Watson1978:fix-empty-axis-without-loop

Conversation

@Watson1978

@Watson1978 Watson1978 commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

Purpose

eye, poly and bincount with weights crash the interpreter when an axis is empty. All numeric types crash the same way, and Numo::RObject too for eye and poly.

Numo::DFloat.new(0, 2, 2).eye                          # [BUG] Segmentation fault at 0x0000000000000000
Numo::DFloat[].poly(1, 2)                              # same
Numo::DFloat.new(2, 1).seq.poly(Numo::DFloat.new(0))   # same, the result is empty by broadcasting
Numo::UInt32[0, 1, 2].bincount(Numo::DFloat.new(0, 3)) # same
Numo::DFloat.new(2, 3).seq[[], true].eye               # [BUG] Segmentation fault

On an empty view, eye can also write into the base array without an error.

a = Numo::DFloat.new(2, 3, 3).seq
a[1...1, true, true].eye  # a[1, true, true] becomes an identity matrix

Summary of Changes

loop_narray and the buffer copies in ndloop.c run their body once before they check any count.

  • Most iterators with NDF_HAS_LOOP then loop zero times, but the iterators of these three methods are registered with NO_LOOP. They do not look at a count, so they read and wrote through the pointer of an empty array. loop_narray now returns before the loop when the ndfunc has no NDF_HAS_LOOP and an outer axis is empty.
  • The buffer copies are used for views that an iterator cannot step through. They copied one element of an empty view, which read an empty index array past its end and wrote past an empty buffer. They now skip a buffer with an empty axis, including an empty last axis that is folded into the element size. This also removes an out-of-bounds write that only AddressSanitizer shows, as in Numo::DFloat.new(2, 3).seq[[], [0, 1, 2]] + 1.

bincount checked that the weight has the same length as self inside its iterator, which is no longer called for an empty outer axis. The check now runs before the loop, so Numo::UInt32[0, 1, 2].bincount(Numo::DFloat.new(0, 5)) still raises ShapeError.

Integer and Numo::RObject / and % read the divisor before their loop, so Numo::Int32[] / Numo::Int32[] still crashes. That needs a fix in those iterators and is not part of this change.

Cumo avoids the same crashes with a guard for every loop in sonots/cumo#513. That PR also keeps the shape of empty arrays through ndloop, which changes the results of other operations, so this change does not take that part.

Testing

  • Tests pass locally
  • Manual testing completed
Numo::DFloat.new(0, 2, 2).eye.shape                           # [0, 2, 2]
Numo::DFloat[].poly(1, 2).to_a                                # []
Numo::UInt32[0, 1, 2].bincount(Numo::DFloat.new(0, 3)).shape  # [0, 3]
Numo::DFloat.new(2, 3).seq[[], true].eye.shape                # [0, 3]

a = Numo::DFloat.new(2, 3, 3).seq
b = a.copy
a[1...1, true, true].eye
a == b  # true

With Ruby 4.0.9 built with AddressSanitizer, the fixed code reports nothing for these cases on 8 dtypes or for the test suites. 128 other results of eye are the same before and after the fix. They cover non-empty arrays, views, diagonal offsets, empty arrays that did not crash, and the errors for invalid arguments and frozen arrays. I also called about 140 other methods on 6 dtypes and 6 empty arrays and views, and the results are the same before and after the fix. 36 calls of bincount with valid and invalid weights give the same results and errors before and after the fix.

Each new test crashes the test process 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#513.

🤖 Generated with Claude Code

@Watson1978
Watson1978 force-pushed the fix-empty-axis-without-loop branch from 763ccb7 to 38ffe10 Compare November 30, 2026 14:18
Watson1978 and others added 2 commits December 1, 2026 18:07
loop_narray and the buffer copies run their body once before they
check any count. Most iterators with NDF_HAS_LOOP then loop zero
times, but the iterators of eye, poly and bincount with weights are
registered with NO_LOOP and do not look at a count. With an empty
outer axis they accessed a NULL pointer, as in
Numo::DFloat.new(0, 2, 2).eye and Numo::DFloat[].poly(1, 2), or wrote
into the base of an empty view. The buffer copies, used for views that
an iterator cannot step through, copied one element of an empty view.
They read an empty index array past its end and wrote past an empty
buffer, as in Numo::DFloat.new(2, 3).seq[[], true].eye.

Return from loop_narray before the loop when the ndfunc has no loop of
its own and an outer axis is empty. Skip the copies for a buffer with
an empty axis, including one folded into the element size. Check the
bincount weight length before the loop as well, so that a weight with
an empty outer axis still raises ShapeError.

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-empty-axis-without-loop branch from 38ffe10 to f110de1 Compare December 1, 2026 09:08
@yoshoku

yoshoku commented Dec 2, 2026

Copy link
Copy Markdown
Owner

/opencode review

@github-actions

github-actions Bot commented Dec 2, 2026

Copy link
Copy Markdown

Review: PR #49 — Fix crashes in eye, poly and bincount when an axis is empty

I read the diff against main and traced the relevant ndloop paths (ndloop_alloc, ndloop_init_args, ndfunc_contract_loop, ndfunc_set_user_loop, ndfunc_set_bufcp, loop_narray, and the eye/poly/bincount iterators). Overall this is a correct, well-scoped fix. Details below.

Verification of the fix logic

loop_narray guard (ndloop.c:1270-1273) — Correct and narrowly scoped. The only ndfuncs with flag NO_LOOP that run through loop_narray are eye, poly, and weighted bincount (the NO_LOOP users in struct.c and na_ndloop_inspect use loop_narray_to_rarray/loop_inspect, which are unaffected). I traced each reported crash to its root:

  • Numo::DFloat.new(0, 2, 2).eye: lp->ndim == 1, n[0] == 0 → guard triggers; previously the iterator wrote through the NULL data pointer of the 0-size array. Fixed.
  • Numo::DFloat.new(2, 1).seq.poly(Numo::DFloat.new(0)): broadcasting sets lp->n[1] = 0, then ndloop_init_args zeroes all of lp->n (the s == 0 path at ndloop.c:655-661), so the guard fires. Fixed.
  • bincount with an empty outer axis: guard skips the iterator that would otherwise zero length bins into a 0-element output buffer (OOB write) and read through the empty-view iters.

Importantly, the guard is deliberately restricted to !NDF_HAS_LOOP, which is the right call: HAS_LOOP iterators (and reduction funcs like sum, which use STRIDE_LOOP_NIP) already handle zero-count user dims internally, and ndloop_init_args' zeroing of lp->n guarantees their user shapes are 0 whenever any axis is empty. Skipping the loop can never leave uninitialized output data, because an empty outer axis implies total output size 0. This also fixes the silent base-array corruption in a[1...1, true, true].eye.

Buffer-copy guards (ndloop.c:1016-1031, 1051, 1102) — Also correct, and I could reproduce the exact OOB mechanisms from the code:

  • For an index view with an empty user dim (e.g. a[true, [], true].eye, user dims [0, 3]), ndloop_set_stepidx does register the empty dim's iterator (n > 1 || nd > 0 is true because nd > 0), so src_iter[i].idx points at an empty index array; the old copy loop read idx[0] OOB, and sz = elmsz * n[...] = 0 made xmalloc(0) a 0-byte buffer that then received a full memcpy of elmsz * trailing bytes (OOB write). The new axis scan skips this. ✓
  • The elmsz == 0 check covers empty dims folded into the element size by contraction (which are not visible to the axis scan, since LBUFCP->ndim is the contracted count while buf_shape is indexed by the original ndim). ✓
  • elmsz == 0 cannot fire spuriously: no dtype has element_stride == 0 (Bit is 1), and elmsz only becomes 0 via a contracted n == 0 dim. ✓

Notably, the new tests do exercise these buffer-copy paths: a[true, [], true].eye (empty user dim with non-empty outer axis, so the guard in loop_narray does not fire and the bufcp guard is what saves it) and a[0, [], true].eye (the nd == 0 bufcp path). Good coverage of both guards.

na_bincount_check_weight (bincount.h:14-29) — Semantics match the in-iterator check exactly: for NO_LOOP ndfuncs, LARG(lp, j).shape stays the argument's own trailing shape (never broadcast, since ndfunc_set_user_loop skips it), so l != m in the iterator compares the same values the pre-check compares. Placement is also right: it runs after the weight is already cast to SFloat/DFloat and after the minmax/max output sizing, so the relative order of ArgError/RangeError/ShapeError is unchanged, and the ndim == 0 early return preserves the prior DimensionError from na_ndloop for 0-dim arguments. The error class and message are identical to the iterator's. ✓

Issues and suggestions

  1. Minor — check ordering in the copy functions. In both ndloop_copy_to_buffer and ndloop_copy_from_buffer, the ndloop_buffer_is_empty check sits after the nd == 0 branch. For a fully contracted buffer with elmsz == 0 (all user dims contracted, one of them empty), the zero-dimension branch still executes memcpy(buf, src, 0) with src = lp->src_ptr + pos where the source array may have no data. This is a harmless 0-byte memcpy in practice, but it contradicts the stated intent of skipping empty buffers entirely; moving the empty check above the nd == 0 branch would make the two paths uniform.

  2. Minor — inaccurate comment. The comment on na_bincount_check_weight says "The iterator keeps its own check, as Ruby code can reshape the weight in between." Between the pre-check and the iterator there is no Ruby hook that can reshape the weight: the weight is already cast to its final class before the pre-check, and ndloop_cast_args cannot change shapes. The iterator check is now effectively redundant (kept as harmless defense). The comment should say something like "kept as a defensive re-check inside the loop" to avoid misleading future readers.

  3. Test gap (suggestion). No test covers the mirror case where self has the empty outer axis while the weight is non-empty and well-formed, e.g.:

    x = dtype.new(0, 3)          # or an equivalent 2-D empty-outer array
    actual = x.bincount(Numo::SFloat[0.5, 0.5, 0.5])
    assert_equal([0, 3], actual.shape)

    and the mismatched variant x.bincount(Numo::SFloat.new(0, 5)) raising ShapeError. The pre-check and the loop_narray guard interact here in a way the current tests don't pin down. Optionally, Numo::DFloat.new(2, 3).seq[[], [0, 1, 2]] + 1 (the ASan-only OOB write from the PR description, which goes through the buffer copies via a STRIDE_LOOP function rather than eye) would make a good regression test too, though the shared guard is already covered by the eye cases.

  4. Nit. ndloop_has_empty_axis is fine as written; just note that in loop_narray it is called with lp->n after ndfunc_contract_loop may have shifted the pointer (lp->n = &(lp->n[cnt])) — I verified the shifted pointer is the one used, so the scan covers the correct dims. No action needed.

Conclusion

The fix is correct, minimal, and consistent with the existing ndloop invariants (in particular the "zero all lp->n when the total is 0" behavior that guarantees no uninitialized outputs). The HAS_LOOP carve-out is the right scope, matching the PR's explicit decision not to adopt Cumo's broader shape-preservation change. I'd merge after considering the minor comment/ordering nits and the additional bincount test.

github run

@Watson1978

Copy link
Copy Markdown
Contributor Author

Thanks for the review. I checked each point and left the code as it is.

  1. Check order in the copy functions: a buffer is only set up when some axis is non-contiguous or indexed, so its ndim is at least 1 and the zero-dimension branch is not reached. A build that counted entries into that branch reported none over the test suites and a sweep of empty arrays and views.
  2. The comment on na_bincount_check_weight: Ruby code can run between the two checks. na_ndloop duplicates the argument array, which calls initialize_copy. With the check removed from the iterator, another thread calling w.reshape! made bincount read past the weight after about 16,000 tries, and a TracePoint on initialize_copy did it every time. So the iterator keeps its check.
  3. Tests: bincount on a self with an empty outer axis raises ShapeError: cannot reduce empty NArray from the max of self, before and after this change, so it does not reach this code. Numo::DFloat.new(2, 3).seq[[], [0, 1, 2]] + 1 returns [0, 0] on a normal build even before the fix. The same copy check is covered by a[true, [], true].eye and a[0, [], true].eye, which crash without it.
  4. Agreed, no change needed.

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