Skip to content

Fix Numo::Bit#to_binary returning uninitialized memory in its last byte - #48

Merged
yoshoku merged 3 commits into
yoshoku:mainfrom
Watson1978:fix-bit-to-binary-padding
Dec 1, 2026
Merged

yoshoku merged 3 commits into
yoshoku:mainfrom
Watson1978:fix-bit-to-binary-padding

Conversation

@Watson1978

Copy link
Copy Markdown
Contributor

Purpose

When the size of a Numo::Bit array is not a multiple of 8, the last byte that to_binary returns also holds the bits past the end of the array. The buffer is allocated with xmalloc, so these bits are uninitialized heap memory. For a view that is read in place, they are the elements of the base array outside the view.

b = Numo::Bit.new(1)
b.store(1)
b.to_binary.bytes  # the high 7 bits change between calls, e.g. [147], [51], [169]

a = Numo::Bit.new(16).fill(0)
a[4..7] = 1
a[0..3].to_binary.bytes  # [240]

marshal_dump and to_string use the same method, so these bits also reach Marshal.dump. Arrays with the same contents give different bytes, which breaks caches and comparisons keyed on the dump.

Summary of Changes

nary_to_binary now clears the bits past the end in the last byte of the returned string. It counts them on the same array that the byte length came from.

An array made by from_binary also kept the extra bits of its input, so Numo::Bit.from_binary("\xFF\xFF".b, [12]).to_binary now returns "\xFF\x0F" instead of "\xFF\xFF".

Cumo fixed the same in sonots/cumo#471.

Testing

  • Tests pass locally
  • Manual testing completed
b.to_binary.bytes        # [1]
a[0..3].to_binary.bytes  # [0]

Before the fix, 30 calls of to_binary on a 1-bit array gave 27 different bytes. After the fix, they all give [1]. Marshal.dump and to_string of a 5-bit array also give the same bytes on every call.

The new test fails 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#471.

🤖 Generated with Claude Code

Watson1978 and others added 2 commits November 30, 2026 23:17
When the size of a Bit array is not a multiple of 8, the last byte that
to_binary returns also holds the bits past the end. For a new array they
are uninitialized heap memory. For a view read in place they are
elements of the base. They also reach marshal_dump and to_string.

Clear those bits in the returned string. Count them on the same array
that the byte length came from.

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-bit-to-binary-padding branch from 4f0fa0b to a9e02ad Compare November 30, 2026 14:18
@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

Review of PR #48: Fix Numo::Bit#to_binary returning uninitialized memory in its last byte

I read the full diff against the actual base (4f9bc3f..a9e02ad — the "deleted tests" that show up when diffing against the stale local main are from PR #47, not this PR) and traced the change through the view/dup logic in nary_to_binary, the Bit allocation (bit_allocate in src/t_bit.c:516), bit packing (STORE_BIT/LOAD_BIT in numo/template.h), and nary_byte_size (narray.c:1233).

Verdict

The fix is correct. Notes on why, plus a few suggestions.

Correctness analysis

  • len comes from nary_byte_size(self) = ceil(size * 1.0/8) computed after the potential self = rb_funcall(self, id_dup, 0) at narray.c:1435, and na is re-fetched from the same post-dup self, so the byte length and the bit count always agree. This is the same subtlety the cumo port handled ("counted off the array the bytes came from"), and the patch gets it right — counting the view's size instead would clear live bits for byte-unaligned dup'd views.
  • All Bit paths are covered:
    • plain data array, size%8≠0 → masked;
    • contiguous view with view offset 0 (e.g. a[0..3] of 24) → no dup, ptr is the base start, view size used, masked;
    • view with nonzero bit offset or non-contiguous → dup into a fresh contiguous array, masked on the dup's size;
    • size%8==0 or len==0 → untouched.
  • The mask (1 << (size % 8)) - 1 matches the LSB-first bit layout (LOAD_BIT: bit p is byte p/8, bit p%8), so the low size%8 bits of the last byte are exactly the valid elements.
  • RSTRING_PTR(str) is the method's own copy, so masking never writes back into a frozen-string-backed source or a base array.
  • rb_obj_is_kind_of(self, numo_cBit) correctly includes Bit subclasses (BitSubclass).
  • to_string (alias at narray.c:2006) and marshal_dump (narray.c:1481) route through this method, so they're fixed too, and marshal_load/from_binary restore the already-zeroed padding, making dumps canonical and round-trip stable.
  • Element-wise consumers (eq, count_true, where, stores) all use per-bit LOAD_BIT/STORE_BIT, so leftover internal padding bits can't leak into results.

Suggestions (non-blocking)

  1. Internal padding is still stale. bit_allocate uses xmalloc and from_binary memcpy's raw bytes, so padding bits inside the array remain garbage (e.g. Numo::Bit.from_binary("\xFF\xFF".b, [12]) still holds 0xF0 in its buffer). Output is now canonical, which is the important part, but consider zeroing the tail at allocation or in from_binary as a follow-up — any future byte-wise fast path (e.g. a vectorized popcount for count_true) would silently over-count padding bits.
  2. Redundant re-check. RTEST(rb_obj_is_kind_of(self, numo_cBit)) is evaluated after the dup even though the result can't change (a Bit's dup is a Bit). Capturing int is_bit = ... once near the top and reusing it would be marginally cheaper and slightly clearer; purely a micro-nit.
  3. Extra test cases worth adding: a subclass data array with size%8≠0 (BitSubclass.new(5).fill(1).to_binary) to pin the kind_of behavior, and Numo::Bit.new(0).to_binary for the empty (len == 0) guard.
  4. Portability note (pre-existing, not introduced here): BIT_DIGIT is unsigned int (NB = 32, narray.h:450-452), and the byte-serialization of Bit (rb_usascii_str_new(ptr + offset, len) taking the first len buffer bytes) already assumes the little-endian bit-to-byte mapping; on big-endian the existing code reads the wrong bytes regardless of this patch. The mask is consistent with the layout the rest of the binary I/O assumes, so no action needed — just be aware big-endian Bit binary I/O was already broken before this PR.

No bugs found; the change is a faithful, well-tested port of the cumo fix and is safe to merge as-is.

github run

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

Copy link
Copy Markdown
Contributor Author

Thanks for the review. I added a test for a Bit subclass that owns its buffer (f542394). Before the fix, BitSubclass.new(5).fill(1).to_binary gave a different last byte on most runs.

About the other suggestions:

  • Padding bits inside the buffer: they are still not cleared, but no current operation reads them. On Numo::Bit.from_binary("\xFF\xFF".b, [12]), count_true, count_false, all?, any?, none?, ==, where, mean, ~, &, | and masking all give the right results. I would leave zeroing them to a change that reads whole bytes.
  • The second rb_obj_is_kind_of: it checks the array after the dup, which is the array the length comes from. If dup is overridden to return something other than a Bit, a flag taken before the dup would mask the last byte of that other array. So I kept it.
  • Numo::Bit.new(0).to_binary: with 0 elements the size is a multiple of 8, so the mask does not run with or without the len > 0 check. The test would not cover that check, so I did not add it.
  • Big-endian: agreed, this change does not affect it.

@yoshoku
yoshoku merged commit 76bb085 into yoshoku:main Dec 1, 2026
12 checks passed
@Watson1978
Watson1978 deleted the fix-bit-to-binary-padding 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