Project

General

Profile

Actions

Bug #22631

closed

Set#map! / Set#collect! segfaults under GC.stress on 4.0.x

Bug #22631: Set#map! / Set#collect! segfaults under GC.stress on 4.0.x

Added by caplanmaor (Maor Caplan) 5 days ago. Updated 5 days ago.

Status:
Closed
Assignee:
-
Target version:
-
ruby -v:
ruby 4.0.10 (2026-11-19 revision a704b7cd95) +PRISM [x86_64-linux]
[ruby-core:127687]

Description

Set#collect!/map! on an empty set segfaults when a GC runs during the call.

Reproduction

GC.stress = true

1000.times do
  Set.new.map! { |x| x }
end

Segfaults on the first iteration, every run, on the official ruby:4.0.10 Docker image (gcc (Debian 14.2.0-19) 14.2.0). Also reproduced on 4.0.9 and 4.0.7.

repro.rb:4: [BUG] Segmentation fault at 0x0000000000000000
ruby 4.0.10 (2026-11-19 revision a704b7cd95) +PRISM [x86_64-linux]

-- C level backtrace information -------------------------------------------
libruby.so.4.0(memcpy+0xf) /usr/include/x86_64-linux-gnu/bits/string_fortified.h:29
libruby.so.4.0(ruby_nonempty_memcpy) ./include/ruby/internal/memory.h:759
libruby.so.4.0(rb_set_copy) ./include/ruby/internal/memory.h:756
libruby.so.4.0(set_i_initialize_copy+0x5) /usr/src/ruby/set.c:566
libruby.so.4.0(set_i_collect) /usr/src/ruby/set.c:1473

The memcpy source pointer (RSI) is NULL and the size (RDX) is 0x40.

Cause

set_i_collect builds a temporary set and copies it back into the receiver with set_i_initialize_copy. Nothing keeps the temporary alive across the set_copy call, so a GC triggered by the allocation inside rb_set_copy frees it and the memcpy then reads from the freed table.


Files

ruby-set-map-crash.txt (23.1 KB) ruby-set-map-crash.txt caplanmaor (Maor Caplan), 11/23/2026 08:02 PM

Updated by caplanmaor (Maor Caplan) 5 days ago Actions #1

  • Status changed from Open to Closed

Applied in changeset git|4ecd94d4b09a3f776b73db2c73db39cd890da7df.


[Bug #22631] Fix use-after-free in Set#collect! and Set#flatten!

Set#collect! builds a temporary set and copies it back into the
receiver with set_i_initialize_copy. After the last use of other
as a VALUE, only a pointer to its embedded table is left, so the
compiler is free to drop the reference. The allocation inside
set_copy can then trigger a GC that sweeps the temporary set and
frees its entries while they are still being copied.

On Ruby 4.0 set_free zeroes the table, so this crashes:

$ ruby -e 'GC.stress = true; Set.new.map! { |x| x }'
-e:1: [BUG] Segmentation fault at 0x0000000000000000
... memcpy <- rb_set_copy <- set_i_collect

On master the freed entries are read instead, which valgrind reports
as an invalid read in rb_set_copy of a block freed by the sweep
started from the ruby_xmalloc in the same call.

Set#flatten! passes a temporary set through set_i_replace to the same
function, so guard other in set_i_initialize_copy.

Actions

Also available in: PDF Atom