Repository navigation
Fix a double free from NArray#free on arrays backed by a frozen String - #43
Conversation
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>
|
/opencode review |
PR Review: Fix double free from
|
Purpose
from_binaryandstore_binarywith a frozen String use the buffer of the String without copying it.Marshal.loaddoes the same, becausemarshal_loadfreezes the String before it callsstore_binary.NArray#freestill freed that buffer. The String then holds freed memory, and the buffer is freed again when the String is collected.Summary of Changes
na_freenow callsxfreeonly when the array owns its buffer. Otherwise it only drops the pointer. The next write allocates a new buffer, as it already did afterfree. The array still keeps the String, so its memory is released when the array is collected.Testing
Before the fix,
s.unpack("d4")returned values like[0.0, 2.53e-321, 6.9e-310, 6.9e-310]aftera.free. The values change from run to run. The same happened withstore_binary, and withfreeon the base of a view. Callingfreemany times and then running the GC ended indouble free or corruption. With Ruby 4.0.7 built with AddressSanitizer, the code before the fix reports a heap-use-after-free afterfree, and the fixed code reports nothing. After the fix, the String keeps its content, andfreeon 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_mathandtest_ractorall pass on Ruby 4.0.8 and 4.1-dev.Related Issues
None.
🤖 Generated with Claude Code