Skip to content

Fix a double free from NArray#free on arrays backed by a frozen String - #43

Merged
yoshoku merged 2 commits into
yoshoku:mainfrom
Watson1978:fix-free-unowned-buffer
Nov 29, 2026
Merged

yoshoku merged 2 commits into
yoshoku:mainfrom
Watson1978:fix-free-unowned-buffer

Conversation

@Watson1978

Copy link
Copy Markdown
Contributor

Purpose

from_binary and store_binary with a frozen String use the buffer of the String without copying it. Marshal.load does the same, because marshal_load freezes the String before it calls store_binary. NArray#free still freed that buffer. The String then holds freed memory, and the buffer is freed again when the String is collected.

d = Marshal.dump(Numo::DFloat.new(2048).seq)
20.times { Marshal.load(d).free }
GC.start  # glibc: double free or corruption (!prev)

Summary of Changes

na_free now calls xfree only when the array owns its buffer. Otherwise it only drops the pointer. The next write allocates a new buffer, as it already did after free. The array still keeps the String, so its memory is released when the array is collected.

Testing

  • Tests pass locally
  • Manual testing completed
s = ([1.0, 2.0, 3.0, 4.0].pack("d*") * 512).freeze
a = Numo::DFloat.from_binary(s)
a.free
s.unpack("d4")  # [1.0, 2.0, 3.0, 4.0]
a.seq[1]        # 1.0

Before the fix, s.unpack("d4") returned values like [0.0, 2.53e-321, 6.9e-310, 6.9e-310] after a.free. The values change from run to run. The same happened with store_binary, and with free on the base of a view. Calling free many times and then running the GC ended in double free or corruption. With Ruby 4.0.7 built with AddressSanitizer, the code before the fix reports a heap-use-after-free after free, and the fixed code reports nothing. After the fix, the String keeps its content, and free on an array that owns its buffer works as before.

The new test runs the case in a child process, because the code before the fix corrupts the heap. On the code before the fix, the child process aborted and then hung, so the test failed at its 60 second deadline. test_narray, test_bit, test_extra, test_math and test_ractor all pass on Ruby 4.0.8 and 4.1-dev.

Related Issues

None.

🤖 Generated with Claude Code

from_binary and store_binary with a frozen String, and Marshal.load,
make the array point at the buffer of the String without copying it.
NArray#free still called xfree on that buffer. The String kept using
the freed memory, and the buffer was freed again when the String was
collected.

Free the buffer only when the array owns it. Otherwise just drop the
pointer. The next write allocates a new buffer as before.

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

yoshoku commented Oct 27, 2026

Copy link
Copy Markdown
Owner

/opencode review

@github-actions

Copy link
Copy Markdown

PR Review: Fix double free from NArray#free on unowned buffers

Overall assessment

The fix is correct and minimal. I verified against the surrounding code and it is consistent with how ownership is already handled elsewhere:

  • The per-type GC deallocators (e.g. dfloat_free in ext/numo/narray/src/t_dfloat.c:330) already guard xfree with owned, so na_free was the odd one out.
  • After dropping an unowned pointer, the recovery path is safe: na_pointer_copy_on_write returns early when ptr == NULL (narray.c:636-638), and a subsequent write goes through id_allocate, which sets owned = TRUE after xmalloc2 (t_dfloat.c:392-397). So the "next write allocates a new buffer" claim checks out.
  • The array keeps the String alive via the source ivar (narray.c:1326, 1405), so the unowned buffer cannot dangle. Also note free is a no-op for views (it never touched the base buffer), so the view case was never part of the double-free path via na_free itself.

C change (narray.c:781-787)

No bugs found. A few observations:

  1. owned/source are left as FALSE/String after free of an unowned buffer. This is safe because nothing dereferences source once the pointer is dropped — na_pointer_copy_on_write checks ptr == NULL before consulting owned. The String then leaks (stays referenced) until the array itself is collected. Since nothing needs it anymore after free, consider adding rb_ivar_set(self, id_source, Qnil); in the unowned branch so the String becomes collectible immediately. Purely optional — the current behavior matches what the PR description promises.

  2. Documentation (narray.c:767-771): the free doc comment still says "Ignored for NArray-view" only. Worth mentioning that for arrays whose buffer is borrowed (e.g. from_binary/store_binary/Marshal#load with a frozen String), free detaches the pointer without releasing the borrowed memory. Also, after free a read raises "cannot read unallocated NArray" — same as an owned array, but users coming from "free just clears the pointer" might be surprised.

Test (test/test_narray.rb:2309-2347)

Solid overall. It mirrors the established child-process pattern in test_bit.rb:313-339, checks both the String integrity (src == data) and that a subsequent write (a.seq) reallocates a fresh buffer, and biases the allocator with GC.start + string churn to catch reuse of the freed block. A few suggestions:

  1. stderr is discarded (err: File::NULL), so if the child fails the assertion you get only a bare exit-status failure with no diagnostic. Consider writing child stderr to a temp file and including its content in the failure message (or in a def flake / assert message). Same applies to the pre-existing pattern in test_bit.rb, so this is consistency vs. diagnosability — your call.

  2. Timeout cost: on a pre-fix regression the child hangs, so this test adds 60s of wall time to the suite when it regresses. Acceptable for a safety test, but worth knowing.

  3. Process.kill('KILL', pid) has a benign TOCTOU race (child could exit between the WNOHANG check and the kill, raising Errno::ESRCH). Negligible in practice, and identical to the existing pattern.

  4. Nit: assert_equal('[true, 2047.0]', reader.value) couples the assertion to inspect formatting. A .unpack("d*")-style comparison or assert_equal([true, 2047.0], eval(...)) would be marginally less brittle, though the current version is simple and explicit.

Verdict

Ship it. The core change is the right fix, it's consistent with the codebase's existing ownership model, and the regression test would have caught the original bug (heap corruption abort in the child). The extra-ivar-clearing and stderr-capture suggestions are nice-to-haves, not blockers.

github run

@yoshoku
yoshoku merged commit ed165c6 into yoshoku:main Nov 29, 2026
13 checks passed
@Watson1978
Watson1978 deleted the fix-free-unowned-buffer 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