Ruby 4.1.0dev (2026-10-27 revision db563a357875d4efbadec58b0fd8695ac9a82f42)
default.c
1#include "ruby/internal/config.h"
2
3#include <signal.h>
4#include <string.h>
5
6#ifndef _WIN32
7# include <sys/mman.h>
8# include <unistd.h>
9# include <fcntl.h>
10# ifdef HAVE_SYS_PRCTL_H
11# include <sys/prctl.h>
12# endif
13#endif
14
15#if !defined(PAGE_SIZE) && defined(HAVE_SYS_USER_H)
16/* LIST_HEAD conflicts with sys/queue.h on macOS */
17# include <sys/user.h>
18#endif
19
20#ifdef BUILDING_MODULAR_GC
21# define nlz_int64(x) (x == 0 ? 64 : (unsigned int)__builtin_clzll((unsigned long long)x))
22# define rb_popcount_intptr(x) ((unsigned int)__builtin_popcountll((unsigned long long)(x)))
23#else
24# include "internal/bits.h"
25#endif
26
27#include "ruby/ruby.h"
28#include "ruby/atomic.h"
29#include "ruby_atomic.h"
30#include "ruby/debug.h"
31#include "ruby/thread.h"
32#include "ruby/util.h"
33#include "ruby/vm.h"
35#include "ccan/list/list.h"
36#include "darray.h"
37#include "gc/gc.h"
38#include "gc/gc_impl.h"
39#include "yjit.h"
40#include "zjit.h"
41#include "internal/static_assert.h"
42#include "internal/vm_map.h"
43
44#ifdef BUILDING_MODULAR_GC
45/* hrtime.h transitively includes internal/time.h -> internal/bits.h, which are
46 * not available to out-of-tree modular GC builds. We only use a monotonic
47 * clock plus saturating add/sub, so provide that subset locally with the same
48 * semantics as hrtime.h. */
49# include <time.h>
50typedef uint64_t rb_hrtime_t;
51# define RB_HRTIME_PER_SEC ((rb_hrtime_t)1000000000)
52
53static inline rb_hrtime_t
54rb_hrtime_now(void)
55{
56# if defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_MONOTONIC)
57 struct timespec ts;
58 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
59 return (rb_hrtime_t)ts.tv_sec * RB_HRTIME_PER_SEC + (rb_hrtime_t)ts.tv_nsec;
60 }
61# endif
62 return 0;
63}
64
65static inline rb_hrtime_t
66rb_hrtime_add(rb_hrtime_t a, rb_hrtime_t b)
67{
68 rb_hrtime_t c = a + b;
69 return c < a ? UINT64_MAX : c; /* saturate on overflow */
70}
71
72static inline rb_hrtime_t
73rb_hrtime_sub(rb_hrtime_t a, rb_hrtime_t b)
74{
75 return a < b ? 0 : a - b;
76}
77#else
78# include "hrtime.h"
79#endif
80
81#include "probes.h"
82
83/* cl.exe's traditional preprocessor passes __VA_ARGS__ to a nested macro as
84 * a single argument; the extra expansion re-scans it into separate ones. */
85#define RUBY_DTRACE_GC_HOOK_EXPAND(expr) expr
86#define RUBY_DTRACE_GC_HOOK(name, ...) \
87 do {if (RUBY_DTRACE_GC_##name##_ENABLED()) RUBY_DTRACE_GC_HOOK_EXPAND(RUBY_DTRACE_GC_##name(__VA_ARGS__));} while (0)
88
89#if USE_ZJIT
90# include "gc/default/zjit_fastpath.h"
91#endif
92
93#ifdef BUILDING_MODULAR_GC
94# define RB_DEBUG_COUNTER_INC(_name) ((void)0)
95# define RB_DEBUG_COUNTER_INC_IF(_name, cond) (!!(cond))
96#else
97# include "debug_counter.h"
98#endif
99
100#ifdef BUILDING_MODULAR_GC
101# define rb_asan_poison_object(obj) ((void)(obj))
102# define rb_asan_unpoison_object(obj, newobj_p) ((void)(obj), (void)(newobj_p))
103# define asan_unpoisoning_object(obj) if ((obj) || true)
104# define asan_poison_memory_region(ptr, size) ((void)(ptr), (void)(size))
105# define asan_unpoison_memory_region(ptr, size, malloc_p) ((void)(ptr), (size), (malloc_p))
106# define asan_unpoisoning_memory_region(ptr, size) if ((ptr) || (size) || true)
107
108# define VALGRIND_MAKE_MEM_DEFINED(ptr, size) ((void)(ptr), (void)(size))
109# define VALGRIND_MAKE_MEM_UNDEFINED(ptr, size) ((void)(ptr), (void)(size))
110#else
111# include "internal/sanitizers.h"
112#endif
113
114/* MALLOC_HEADERS_BEGIN */
115#ifndef HAVE_MALLOC_USABLE_SIZE
116# ifdef _WIN32
117# define HAVE_MALLOC_USABLE_SIZE
118# define malloc_usable_size(a) _msize(a)
119# elif defined HAVE_MALLOC_SIZE
120# define HAVE_MALLOC_USABLE_SIZE
121# define malloc_usable_size(a) malloc_size(a)
122# endif
123#endif
124
125#ifdef HAVE_MALLOC_USABLE_SIZE
126# ifdef RUBY_ALTERNATIVE_MALLOC_HEADER
127/* Alternative malloc header is included in ruby/missing.h */
128# elif defined(HAVE_MALLOC_H)
129# include <malloc.h>
130# elif defined(HAVE_MALLOC_NP_H)
131# include <malloc_np.h>
132# elif defined(HAVE_MALLOC_MALLOC_H)
133# include <malloc/malloc.h>
134# endif
135#endif
136
137#ifdef HAVE_MALLOC_TRIM
138# include <malloc.h>
139
140# ifdef __EMSCRIPTEN__
141/* malloc_trim is defined in emscripten/emmalloc.h on emscripten. */
142# include <emscripten/emmalloc.h>
143# endif
144#endif
145
146#ifdef HAVE_MACH_TASK_EXCEPTION_PORTS
147# include <mach/task.h>
148# include <mach/mach_init.h>
149# include <mach/mach_port.h>
150#endif
151
152#ifndef RUBY_DEBUG_LOG
153# define RUBY_DEBUG_LOG(...)
154#endif
155
156#ifndef GC_HEAP_INIT_BYTES
157#define GC_HEAP_INIT_BYTES (2560 * 1024)
158#endif
159#ifndef GC_HEAP_FREE_SLOTS
160#define GC_HEAP_FREE_SLOTS 4096
161#endif
162#ifndef GC_RACTOR_HEAP_INIT_BYTES
163/* 0 is resolved at boot to the smallest size that works. */
164#define GC_RACTOR_HEAP_INIT_BYTES 0
165#endif
166#ifndef GC_HEAP_GROWTH_FACTOR
167#define GC_HEAP_GROWTH_FACTOR 1.8
168#endif
169#ifndef GC_HEAP_GROWTH_MAX_BYTES
170#define GC_HEAP_GROWTH_MAX_BYTES 0 /* 0 is disable */
171#endif
172#ifndef GC_HEAP_REMEMBERED_WB_UNPROTECTED_OBJECTS_LIMIT_RATIO
173# define GC_HEAP_REMEMBERED_WB_UNPROTECTED_OBJECTS_LIMIT_RATIO 0.01
174#endif
175#ifndef GC_HEAP_OLDOBJECT_LIMIT_FACTOR
176#define GC_HEAP_OLDOBJECT_LIMIT_FACTOR 2.0
177#endif
178
179#ifndef GC_HEAP_FREE_SLOTS_MIN_RATIO
180#define GC_HEAP_FREE_SLOTS_MIN_RATIO 0.20
181#endif
182#ifndef GC_HEAP_FREE_SLOTS_GOAL_RATIO
183#define GC_HEAP_FREE_SLOTS_GOAL_RATIO 0.40
184#endif
185#ifndef GC_HEAP_FREE_SLOTS_MAX_RATIO
186#define GC_HEAP_FREE_SLOTS_MAX_RATIO 0.65
187#endif
188
189#ifndef GC_MALLOC_LIMIT_MIN
190#define GC_MALLOC_LIMIT_MIN (16 * 1024 * 1024 /* 16MB */)
191#endif
192#ifndef GC_MALLOC_LIMIT_MAX
193#define GC_MALLOC_LIMIT_MAX (32 * 1024 * 1024 /* 32MB */)
194#endif
195#ifndef GC_MALLOC_LIMIT_GROWTH_FACTOR
196#define GC_MALLOC_LIMIT_GROWTH_FACTOR 1.4
197#endif
198
199#ifndef GC_OLDMALLOC_LIMIT_MIN
200#define GC_OLDMALLOC_LIMIT_MIN (16 * 1024 * 1024 /* 16MB */)
201#endif
202#ifndef GC_OLDMALLOC_LIMIT_GROWTH_FACTOR
203#define GC_OLDMALLOC_LIMIT_GROWTH_FACTOR 1.2
204#endif
205#ifndef GC_OLDMALLOC_LIMIT_MAX
206#define GC_OLDMALLOC_LIMIT_MAX (128 * 1024 * 1024 /* 128MB */)
207#endif
208
209#ifndef GC_MALLOC_INCREASE_LOCAL_THRESHOLD
210#define GC_MALLOC_INCREASE_LOCAL_THRESHOLD (8 * 1024 /* 8KB */)
211#endif
212
213#ifdef RB_THREAD_LOCAL_SPECIFIER
214#define USE_MALLOC_INCREASE_LOCAL 1
215static RB_THREAD_LOCAL_SPECIFIER int malloc_increase_local;
216#else
217#define USE_MALLOC_INCREASE_LOCAL 0
218#endif
219
220#ifndef GC_CAN_COMPILE_COMPACTION
221#if defined(__wasi__) /* WebAssembly doesn't support signals */
222# define GC_CAN_COMPILE_COMPACTION 0
223#else
224# define GC_CAN_COMPILE_COMPACTION 1
225#endif
226#endif
227
228#ifndef PRINT_ENTER_EXIT_TICK
229# define PRINT_ENTER_EXIT_TICK 0
230#endif
231#ifndef PRINT_ROOT_TICKS
232#define PRINT_ROOT_TICKS 0
233#endif
234
235#define USE_TICK_T (PRINT_ENTER_EXIT_TICK || PRINT_ROOT_TICKS)
236
237#ifndef HEAP_COUNT
238# if SIZEOF_VALUE >= 8
239# define HEAP_COUNT 12
240# else
241# define HEAP_COUNT 5
242# endif
243#endif
244
245/* The reciprocal table and pool_slot_sizes array are both generated from this
246 * single definition, so they can never get out of sync. */
247#if SIZEOF_VALUE >= 8
248# define EACH_POOL_SLOT_SIZE(SLOT) \
249 SLOT(32) SLOT(40) SLOT(64) SLOT(80) SLOT(96) SLOT(128) \
250 SLOT(160) SLOT(256) SLOT(512) SLOT(640) SLOT(768) SLOT(1024)
251#else
252# define EACH_POOL_SLOT_SIZE(SLOT) \
253 SLOT(32) SLOT(64) SLOT(128) SLOT(256) SLOT(512)
254#endif
255
256typedef struct {
257 size_t heap_init_bytes;
258 size_t ractor_heap_init_bytes;
259 size_t heap_free_slots;
260 double growth_factor;
261 size_t growth_max_bytes;
262
263 double heap_free_slots_min_ratio;
264 double heap_free_slots_goal_ratio;
265 double heap_free_slots_max_ratio;
266 double uncollectible_wb_unprotected_objects_limit_ratio;
267 double oldobject_limit_factor;
268
269 size_t malloc_limit_min;
270 size_t malloc_limit_max;
271 double malloc_limit_growth_factor;
272
273 size_t oldmalloc_limit_min;
274 size_t oldmalloc_limit_max;
275 double oldmalloc_limit_growth_factor;
277
278static ruby_gc_params_t gc_params = {
279 GC_HEAP_INIT_BYTES,
280 GC_RACTOR_HEAP_INIT_BYTES,
281 GC_HEAP_FREE_SLOTS,
282 GC_HEAP_GROWTH_FACTOR,
283 GC_HEAP_GROWTH_MAX_BYTES,
284
285 GC_HEAP_FREE_SLOTS_MIN_RATIO,
286 GC_HEAP_FREE_SLOTS_GOAL_RATIO,
287 GC_HEAP_FREE_SLOTS_MAX_RATIO,
288 GC_HEAP_REMEMBERED_WB_UNPROTECTED_OBJECTS_LIMIT_RATIO,
289 GC_HEAP_OLDOBJECT_LIMIT_FACTOR,
290
291 GC_MALLOC_LIMIT_MIN,
292 GC_MALLOC_LIMIT_MAX,
293 GC_MALLOC_LIMIT_GROWTH_FACTOR,
294
295 GC_OLDMALLOC_LIMIT_MIN,
296 GC_OLDMALLOC_LIMIT_MAX,
297 GC_OLDMALLOC_LIMIT_GROWTH_FACTOR,
298};
299
300/* GC_DEBUG:
301 * enable to embed GC debugging information.
302 */
303#ifndef GC_DEBUG
304#define GC_DEBUG 0
305#endif
306
307/* RGENGC_DEBUG:
308 * 1: basic information
309 * 2: remember set operation
310 * 3: mark
311 * 4:
312 * 5: sweep
313 */
314#ifndef RGENGC_DEBUG
315#ifdef RUBY_DEVEL
316#define RGENGC_DEBUG -1
317#else
318#define RGENGC_DEBUG 0
319#endif
320#endif
321#if RGENGC_DEBUG < 0 && !defined(_MSC_VER)
322# define RGENGC_DEBUG_ENABLED(level) (-(RGENGC_DEBUG) >= (level) && ruby_rgengc_debug >= (level))
323#else
324# define RGENGC_DEBUG_ENABLED(level) ((RGENGC_DEBUG) >= (level))
325#endif
326int ruby_rgengc_debug;
327
328/* RGENGC_PROFILE
329 * 0: disable RGenGC profiling
330 * 1: enable profiling for basic information
331 * 2: enable profiling for each types
332 */
333#ifndef RGENGC_PROFILE
334# define RGENGC_PROFILE 0
335#endif
336
337/* RGENGC_ESTIMATE_OLDMALLOC
338 * Enable/disable to estimate increase size of malloc'ed size by old objects.
339 * If estimation exceeds threshold, then will invoke full GC.
340 * 0: disable estimation.
341 * 1: enable estimation.
342 */
343#ifndef RGENGC_ESTIMATE_OLDMALLOC
344# define RGENGC_ESTIMATE_OLDMALLOC 1
345#endif
346
347#ifndef GC_PROFILE_MORE_DETAIL
348# define GC_PROFILE_MORE_DETAIL 0
349#endif
350#ifndef GC_PROFILE_DETAIL_MEMORY
351# define GC_PROFILE_DETAIL_MEMORY 0
352#endif
353#ifndef GC_ENABLE_LAZY_SWEEP
354# define GC_ENABLE_LAZY_SWEEP 1
355#endif
356
357#ifndef VERIFY_FREE_SIZE
358#if RUBY_DEBUG
359#define VERIFY_FREE_SIZE 1
360#else
361#define VERIFY_FREE_SIZE 0
362#endif
363#endif
364
365#if VERIFY_FREE_SIZE
366#undef CALC_EXACT_MALLOC_SIZE
367#define CALC_EXACT_MALLOC_SIZE 1
368#endif
369
370#ifndef CALC_EXACT_MALLOC_SIZE
371# define CALC_EXACT_MALLOC_SIZE 0
372#endif
373
374#if defined(HAVE_MALLOC_USABLE_SIZE) || CALC_EXACT_MALLOC_SIZE > 0
375# ifndef MALLOC_ALLOCATED_SIZE
376# define MALLOC_ALLOCATED_SIZE 0
377# endif
378#else
379# define MALLOC_ALLOCATED_SIZE 0
380#endif
381#ifndef MALLOC_ALLOCATED_SIZE_CHECK
382# define MALLOC_ALLOCATED_SIZE_CHECK 0
383#endif
384
385#ifndef GC_DEBUG_STRESS_TO_CLASS
386# define GC_DEBUG_STRESS_TO_CLASS RUBY_DEBUG
387#endif
388
389typedef enum {
390 GPR_FLAG_NONE = 0x000,
391 /* major reason */
392 GPR_FLAG_MAJOR_BY_NOFREE = 0x001,
393 GPR_FLAG_MAJOR_BY_OLDGEN = 0x002,
394 GPR_FLAG_MAJOR_BY_SHADY = 0x004,
395 GPR_FLAG_MAJOR_BY_FORCE = 0x008,
396#if RGENGC_ESTIMATE_OLDMALLOC
397 GPR_FLAG_MAJOR_BY_OLDMALLOC = 0x020,
398#endif
399 GPR_FLAG_MAJOR_MASK = 0x0ff,
400
401 /* gc reason */
402 GPR_FLAG_NEWOBJ = 0x100,
403 GPR_FLAG_MALLOC = 0x200,
404 GPR_FLAG_METHOD = 0x400,
405 GPR_FLAG_CAPI = 0x800,
406 GPR_FLAG_STRESS = 0x1000,
407
408 /* others */
409 GPR_FLAG_IMMEDIATE_SWEEP = 0x2000,
410 GPR_FLAG_HAVE_FINALIZE = 0x4000,
411 GPR_FLAG_IMMEDIATE_MARK = 0x8000,
412 GPR_FLAG_FULL_MARK = 0x10000,
413 GPR_FLAG_COMPACT = 0x20000,
414 GPR_FLAG_GLOBAL = 0x40000,
415
416 GPR_DEFAULT_REASON =
417 (GPR_FLAG_FULL_MARK | GPR_FLAG_IMMEDIATE_MARK |
418 GPR_FLAG_IMMEDIATE_SWEEP | GPR_FLAG_CAPI),
419} gc_profile_record_flag;
420
421typedef struct gc_profile_record {
422 unsigned int flags;
423 size_t sequence;
424
425 double gc_time;
426 double gc_invoke_time;
427 rb_hrtime_t gc_wall_time;
428 rb_hrtime_t gc_invoke_wall_time;
429 rb_hrtime_t gc_pause_time;
430 rb_hrtime_t gc_stop_time;
431 rb_hrtime_t gc_stw_time;
432 rb_hrtime_t gc_mark_wall_time;
433 rb_hrtime_t gc_sweep_wall_time;
434 rb_hrtime_t gc_compact_wall_time;
435
436 size_t heap_total_objects;
437 size_t heap_use_size;
438 size_t heap_total_size;
439 size_t moved_objects;
440
441#if GC_PROFILE_MORE_DETAIL
442 double gc_mark_time;
443 double gc_sweep_time;
444
445 size_t heap_use_pages;
446 size_t heap_live_objects;
447 size_t heap_free_objects;
448
449 size_t allocate_increase;
450 size_t allocate_limit;
451
452 double prepare_time;
453 size_t removing_objects;
454 size_t empty_objects;
455#if GC_PROFILE_DETAIL_MEMORY
456 long maxrss;
457 long minflt;
458 long majflt;
459#endif
460#endif
461#if MALLOC_ALLOCATED_SIZE
462 size_t allocated_size;
463#endif
464
465#if RGENGC_PROFILE > 0
466 size_t old_objects;
467 size_t remembered_normal_objects;
468 size_t remembered_shady_objects;
469#endif
471
472struct RMoved {
473 VALUE flags;
474 VALUE dummy;
475 VALUE destination;
476};
477
478#define RMOVED(obj) ((struct RMoved *)(obj))
479
480typedef uintptr_t bits_t;
481enum {
482 BITS_SIZE = sizeof(bits_t),
483 BITS_BITLENGTH = ( BITS_SIZE * CHAR_BIT )
484};
485
487 struct heap_page *page;
488};
489
491 struct heap_page_header header;
492 /* char gap[]; */
493 /* RVALUE values[]; */
494};
495
496#define STACK_CHUNK_SIZE 500
497
498typedef struct stack_chunk {
499 VALUE data[STACK_CHUNK_SIZE];
500 struct stack_chunk *next;
502
503typedef struct mark_stack {
504 stack_chunk_t *chunk;
505 stack_chunk_t *cache;
506 int index;
507 int limit;
508 size_t cache_size;
509 size_t unused_cache_size;
511
512typedef int (*gc_compact_compare_func)(const void *l, const void *r, void *d);
513
514typedef struct rb_heap_newobj {
515 uintptr_t alloc_cursor;
516 uintptr_t alloc_cursor_end;
517 struct free_region *alloc_next_region;
518 struct heap_page *alloc_using_page;
520
521typedef struct rb_heap_struct {
522 short slot_size;
523
524 /* Basic statistics */
525 size_t total_allocated_pages;
526 size_t force_major_gc_count;
527 size_t force_incremental_marking_finish_count;
528 size_t total_allocated_objects;
529 size_t total_freed_objects;
530 size_t final_slots_count;
531
532 /* Sweeping statistics */
533 size_t freed_slots;
534 size_t empty_slots;
535
536 /* Bump-pointer allocation state; only this objspace's owner thread writes it. */
537 rb_heap_newobj_t newobj;
538
539 struct heap_page *free_pages;
540 struct ccan_list_head pages;
541 struct heap_page *sweeping_page; /* iterator for .pages */
542 struct heap_page *compact_cursor;
543 uintptr_t compact_cursor_index;
544 struct heap_page *pooled_pages;
545 size_t total_pages; /* total page count in a heap */
546 size_t total_slots; /* total slot count */
547
548} rb_heap_t;
549
550enum {
551 gc_stress_no_major,
552 gc_stress_no_immediate_sweep,
553 gc_stress_full_mark_after_malloc,
554 gc_stress_max
555};
556
557enum gc_mode {
558 gc_mode_none,
559 gc_mode_marking,
560 gc_mode_sweeping,
561 gc_mode_compacting,
562};
563
564typedef rbimpl_atomic_uint64_t gc_counter_t;
565
566#if !defined(HAVE_GCC_ATOMIC_BUILTINS_64) && !defined(_WIN32) && \
567 !(defined(__sun) && defined(HAVE_ATOMIC_H) && (defined(_LP64) || defined(_I32LPx)))
568# define MALLOC_COUNTERS_NEED_LOCK 1
569#endif
570
572 gc_counter_t malloc;
573 gc_counter_t free;
574
575 /* Baselines the increase is measured from: malloc snapshotted at GC start
576 * (gc_reset_malloc_info), free re-snapshotted at gc_sweep_finish so the
577 * sweep's own frees never count. */
578 gc_counter_t malloc_at_last_gc;
579 gc_counter_t free_at_last_gc;
580};
581
582/* -- Deferred free of non-thread-safe T_DATA --
583 *
584 * A dead T_DATA not RUBY_TYPED_THREAD_SAFE_FREE cannot have its dfree run during a parallel
585 * local sweep: the dfree is extension code that may touch process state other Ractors are using,
586 * so it needs the world stopped (not merely serialization against other dfrees). The sweep
587 * therefore copies out what the free needs, reclaims the slot immediately, and the dfrees are
588 * called later under a VM barrier. Such a type is never embedded, so the payload always outlives
589 * the slot.
590 */
591#define TDATA_UNSAFE_FREE_CHUNK_CAPA 32
592/* Drained chunks kept for reuse; the rest are freed. */
593#define TDATA_UNSAFE_FREE_CACHE_MAX 64
594
596 void (*dfree)(void *);
597 void *data;
598};
599
601 struct tdata_unsafe_free_chunk *next;
602 unsigned int count;
603 uint32_t embed_xfree_bits;
604 struct tdata_unsafe_free_entry entries[TDATA_UNSAFE_FREE_CHUNK_CAPA];
605};
606STATIC_ASSERT(tdata_unsafe_free_bits_cover_chunk,
607 TDATA_UNSAFE_FREE_CHUNK_CAPA <= 32);
608
610 uint64_t minor_gc_count;
611 uint64_t major_gc_count;
612 uint64_t global_gc_invocation_count;
613 uint64_t marking_time_ns;
614 uint64_t sweeping_time_ns;
615};
616
618 uint64_t minor_gc_count;
619 uint64_t major_gc_count;
620 uint64_t global_gc_invocation_count;
621 uint64_t marking_time_ns;
622 uint64_t sweeping_time_ns;
623};
624
625typedef struct rb_objspace {
626 struct {
627 struct gc_malloc_bytes counters;
628#if RGENGC_ESTIMATE_OLDMALLOC
629 size_t oldmalloc_increase;
630 gc_counter_t freed_in_gc;
631#endif
632#ifdef MALLOC_COUNTERS_NEED_LOCK
633 rb_nativethread_lock_t lock;
634#endif
635 } malloc_counters;
636
637 struct {
638 size_t limit;
639#if MALLOC_ALLOCATED_SIZE
640 size_t allocated_size;
641 size_t allocations;
642#endif
643 } malloc_params;
644
646 bool full_mark;
647 } gc_config;
648
649 struct {
650 unsigned int mode : 2;
651 unsigned int immediate_sweep : 1;
652 unsigned int dont_gc : 1;
653 /* A user hold from GC.disable (kept in vm->gc.disable_holders); owner thread only. */
654 unsigned int user_gc_disabled : 1;
655 unsigned int dont_incremental : 1;
656 unsigned int during_gc : 1;
657 unsigned int during_global_gc : 1;
658 unsigned int during_compacting : 1;
659 unsigned int gc_lock_barrier : 1;
660 unsigned int during_reference_updating : 1;
661 unsigned int during_minor_gc : 1;
662 unsigned int during_postmortem : 1;
663 /* No Ractor will own this objspace any more and it will never allocate again. */
664 unsigned int ownerless : 1;
665 unsigned int measure_gc : 1;
666 } flags;
667
668 rb_event_flag_t hook_events;
669
670 rb_heap_t heaps[HEAP_COUNT];
671 size_t empty_pages_count;
672 struct heap_page *empty_pages;
673 /* Nonzero while gc.c parks this objspace in its zombie table: the pages it adds to
674 * global_objspace->zombie_total_pages. Written under the VM lock or the barrier. */
675 size_t zombie_pages;
676
677 struct {
678 rb_atomic_t finalizing;
679 } atomic_flags;
680
682 size_t marked_slots;
683
684 /* Moved out of the per-Ractor newobj cache: allocation state is per objspace. */
685 size_t incremental_mark_step_allocated_slots;
686
687 /* Inputs of the global GC trigger, all owned by this objspace's thread.
688 * shareable_objects is the live population of shareable objects; exceeding the
689 * limit requests a global GC. */
690 size_t shareable_objects;
691 size_t shareable_objects_limit;
692 /* Whether the last mark ran the pinned walk; the sweep asserts on it. */
693 unsigned char last_cycle_pinned;
694
695 struct {
696 rb_darray(struct heap_page *) sorted;
697
698 size_t allocated_pages;
699 size_t freed_pages;
700 uintptr_t range[2];
701 size_t freeable_pages;
702
703 size_t allocatable_bytes;
704
705 /* final */
706 VALUE deferred_final;
707 } heap_pages;
708
709 st_table *finalizer_table;
710
711 struct {
712 int run;
713 unsigned int latest_gc_info;
714 gc_profile_record *records;
715 gc_profile_record *current_record;
716 size_t next_index;
717 size_t size;
718 size_t record_count;
719 size_t max_records;
720 size_t record_sequence;
721
722#if GC_PROFILE_MORE_DETAIL
723 double prepare_time;
724#endif
725 double invoke_time;
726 rb_hrtime_t invoke_wall_time;
727
728 size_t minor_gc_count;
729 size_t major_gc_count;
730 size_t global_gc_count;
731 size_t global_gc_invocation_count;
732 size_t compact_count;
733 size_t read_barrier_faults;
734#if RGENGC_PROFILE > 0
735 size_t total_generated_normal_object_count;
736 size_t total_generated_shady_object_count;
737 size_t total_shade_operation_count;
738 size_t total_promoted_count;
739 size_t total_remembered_normal_object_count;
740 size_t total_remembered_shady_object_count;
741
742#if RGENGC_PROFILE >= 2
743 size_t generated_normal_object_count_types[RUBY_T_MASK];
744 size_t generated_shady_object_count_types[RUBY_T_MASK];
745 size_t shade_operation_count_types[RUBY_T_MASK];
746 size_t promoted_types[RUBY_T_MASK];
747 size_t remembered_normal_object_count_types[RUBY_T_MASK];
748 size_t remembered_shady_object_count_types[RUBY_T_MASK];
749#endif
750#endif /* RGENGC_PROFILE */
751
752 /* temporary profiling space */
753 double gc_sweep_start_time;
754 rb_hrtime_t gc_wall_start_time;
755 rb_hrtime_t gc_sweep_wall_start_time;
756 rb_hrtime_t gc_sweep_excluded_wall_time;
757 rb_hrtime_t gc_pause_start_time;
758 rb_hrtime_t gc_stw_start_time;
759 rb_hrtime_t gc_stop_time;
760 rb_hrtime_t gc_mark_phase_wall_start_time;
761 rb_hrtime_t gc_sweep_phase_wall_start_time;
762#if GC_PROFILE_MORE_DETAIL
763 size_t total_allocated_objects_at_gc_start;
764 size_t heap_used_at_gc_start;
765#endif
766
767 /* basic statistics */
768 size_t count;
769 unsigned long long marking_time_ns;
770 struct timespec marking_start_time;
771 unsigned long long sweeping_time_ns;
772 struct timespec sweeping_start_time;
773
774 /* Weak references */
775 size_t weak_references_count;
776 } profile;
777
778
779 struct {
780 bool parent_object_old_p;
781 VALUE parent_object;
782
783 int need_major_gc;
784 size_t last_major_gc;
785 size_t uncollectible_wb_unprotected_objects;
786 size_t uncollectible_wb_unprotected_objects_limit;
787 size_t old_objects;
788 size_t old_objects_limit;
789
790#if RGENGC_ESTIMATE_OLDMALLOC
791 size_t oldmalloc_increase_limit;
792#endif
793
794#if RGENGC_CHECK_MODE >= 2
795 struct st_table *allrefs_table;
796 size_t error_count;
797#endif
798 } rgengc;
799
800 struct {
801 size_t considered_count_table[T_MASK];
802 size_t moved_count_table[T_MASK];
803 size_t moved_up_count_table[T_MASK];
804 size_t moved_down_count_table[T_MASK];
805 size_t total_moved;
806
807 /* This function will be used, if set, to sort the heap prior to compaction */
808 gc_compact_compare_func compare_func;
809 } rcompactor;
810
811 struct {
812 size_t pooled_slots;
813 size_t step_slots;
814 } rincgc;
815
816#if GC_DEBUG_STRESS_TO_CLASS
817 VALUE stress_to_class;
818#endif
819
820 rb_darray(VALUE) weak_references;
821 rb_postponed_job_handle_t finalize_deferred_pjob;
822
823 /* Partially filled chunk of deferred non-thread-safe T_DATA metadata. */
825
826 int sweeping_heap_count;
827
828 int fork_vm_lock_lev;
829
830 struct rb_gc_vm_context vm_context;
831
832 /* Process-wide GC statistics publication. Default GC only: other
833 * implementations reject GC.stat(process: true) and never initialize
834 * this lock. */
835 struct {
836 rb_nativethread_lock_t lock;
837 struct gc_process_stat_snapshot published;
838 } process_stat;
839
840 /* The incremental-marking flag as an addressable field, so that ZJIT-generated
841 * code can read it; see rb_gc_impl_zjit_writebarrier_required_offset.
842 * Single-writer: a local GC runs on the owning Ractor's thread and a global GC
843 * writes under the stop-the-world barrier. Read by JIT code on the same thread. */
844 bool zjit_during_incremental_marking;
846
847/* The one VM-global GC structure; for now it only holds the page pool. Page bodies are
848 * carved out of large mmap arenas and reused via a process-wide freelist (per-page
849 * mmap/munmap would serialize on the kernel's mmap_lock). Leaf lock: no alloc, no GC. */
850typedef struct rb_global_objspace {
851 struct {
852 rb_nativethread_lock_t lock;
853 struct heap_page_body *hot_list; /* ≤ PAGE_POOL_HOT_MAX un-advised bodies; link at body offset 0 */
854 int hot_count;
855 size_t os_page_size; /* sysconf(_SC_PAGE_SIZE), cached at init */
856 /* List of mmap'd memory regions (arenas) for page bodies. */
857 struct page_arena {
858 struct page_arena *next;
859 char *start; /* usable area, HEAP_PAGE_ALIGN aligned */
860 size_t size; /* usable bytes (a multiple of HEAP_PAGE_SIZE) */
861 struct heap_page_body *cold_freelist; /* free bodies of this arena; link at body offset 0 */
862 int free_count; /* bodies of this arena currently free (hot list + cold_freelist) */
863 int cold_count; /* bodies on cold_freelist (subset of free_count) */
864 } *arenas; /* every arena, newest first */
865 char *arena_cursor; /* first body not yet carved out of the newest arena */
866 char *arena_end; /* end of current arena */
867 struct page_arena *arena_current; /* arena that arena_cursor carves from */
868 int arena_count; /* current mapped arenas (for GC.stat total_pages) */
869 int advised_count; /* page bodies with MADV_* applied (for GC.stat discarded pages) */
870 size_t arenas_unmapped; /* cumulative arenas munmapped (for GC.stat) */
871 } page_pool;
872
873 /* Pages held by zombie objspaces (sum of their zombie_pages), and what was left of
874 * it after the last global cycle (roughly the live data). Written under the VM
875 * lock or the barrier; readers (gc_need_global_p) may be racy. */
876 size_t zombie_total_pages;
877 size_t zombie_pages_survivors;
878
879 /* An objspace merge (objspace_absorb) is running: suppress the cross-objspace
880 * verifier while the graph is in flux. Written by the absorbing thread, read by
881 * verification with the world stopped. */
882 bool during_absorb;
883
884 /* main's objspace, for gc_enter's locking policy. main_ractor->objspace is swapped
885 * during Ractor creation; this stable pointer decides the same way at both ends of a
886 * GC. Set at boot, re-pointed in a forked child. */
887 rb_objspace_t *main_objspace;
888
889 /* GC.stress is process-global (upstream semantics). Written by GC.stress= in any
890 * Ractor (rare) and read on every Ractor's alloc and GC path; it is diagnostic, so
891 * plain store/load with last-writer-wins is fine. */
892 bool gc_stressful;
893 VALUE gc_stress_mode;
894
895 /* Global GC driver state. compacting is true during the move phase: reference
896 * updates are deferred until all forwarding exists, so a cross-objspace reference is
897 * rewritten exactly once. objspaces is the snapshot being collected. */
898 struct {
899 bool compacting;
900 struct rb_objspace **objspaces;
901 size_t n_objspaces, objspaces_capa;
902 size_t count;
903 } global_gc;
904
905 /* Index of every objspace's heap pages, ordered by body address. Writers (page
906 * alloc/free) serialize on page_pool.lock; the only reader is a stop-the-world global
907 * GC, so reads need no lock. A local GC uses its own heap_pages.sorted. */
908 struct {
909 struct heap_page **pages;
910 size_t n_pages, capa;
911 uintptr_t lomem, himem;
912 } page_index;
913
914 rb_postponed_job_handle_t tdata_deferred_free_pjob; /* atomic */
915
916 /* Pending count of deferred non-thread-safe T_DATA frees across all objspaces:
917 * bumped as each one is deferred, reset to 0 by the drain. Crossing
918 * TDATA_DEFERRED_FREE_THRESHOLD triggers the postponed job. */
919 size_t tdata_deferred_free_count; /* atomic */
920
921 /* Full chunks awaiting a drain (CAS stack), and drained chunks kept for reuse. */
922 struct tdata_unsafe_free_chunk *tdata_unsafe_free_published; /* atomic */
923 struct tdata_unsafe_free_chunk *tdata_unsafe_free_cache; /* atomic */
924 size_t tdata_unsafe_free_cache_len; /* atomic */
925
926 /* Archive of destroyed objspaces' final statistics, added once on absorption. */
927 struct gc_process_stat_total process_stat_archive;
929
930static rb_global_objspace_t rb_global_objspace_instance;
931static rb_global_objspace_t *global_objspace = NULL;
932
933/* Relaxed: every reader only asks whether a drain is worth arranging, and the drain
934 * itself stops the world before it touches a chunk. */
935static inline size_t
936tdata_deferred_free_count_load(void)
937{
938 return rbimpl_atomic_size_load(&global_objspace->tdata_deferred_free_count, RBIMPL_ATOMIC_RELAXED);
939}
940
941/* The floor keeps a global GC from running as soon as a few shareable objects appear;
942 * the factor follows the rule used for the old-generation limit. */
943#define SHAREABLE_OBJECTS_LIMIT_MIN (1 << 16)
944#define SHAREABLE_OBJECTS_LIMIT_FACTOR 2.0
945/* Start a global GC once terminated, uninherited Ractors hold this many heap pages. A
946 * small Ractor's objspace is about 13 pages, so discarding many of them still stays
947 * below it, while a single fat zombie crosses it. */
948#define ZOMBIE_PAGES_TRIGGER 256
949/* Trigger the deferred T_DATA free postponed job once this many have accumulated
950 * across all objspaces. */
951#define TDATA_DEFERRED_FREE_THRESHOLD (1 << 15)
952
953static void objspace_absorb(rb_objspace_t *dst, rb_objspace_t *src);
954
955
956static struct heap_page_body *page_pool_acquire(struct page_arena **arena_out);
957static void page_pool_release(struct heap_page_body *body, struct page_arena *arena);
958#ifdef HAVE_MMAP
959static void page_pool_release_locked(struct heap_page_body *body, struct page_arena *arena);
960#endif
961static void page_pool_reclaim(rb_global_objspace_t *g);
962
963#if RGENGC_CHECK_MODE && !defined(_WIN32) && !defined(__wasi__) && defined(HAVE_PTHREAD_H)
964# define PAGE_POOL_LOCK_ERRORCHECK 1
965#endif
966
967static void
968page_pool_lock_initialize(rb_nativethread_lock_t *lock)
969{
970#ifdef PAGE_POOL_LOCK_ERRORCHECK
971 pthread_mutexattr_t attr;
972 pthread_mutexattr_init(&attr);
973 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK);
974 pthread_mutex_init(lock, &attr);
975 pthread_mutexattr_destroy(&attr);
976#else
978#endif
979}
980
981static void
982global_objspace_init(void)
983{
984 if (global_objspace == NULL) {
985 rb_global_objspace_t *g = &rb_global_objspace_instance;
986 page_pool_lock_initialize(&g->page_pool.lock);
987 g->page_pool.hot_list = NULL;
988 g->page_pool.hot_count = 0;
989 g->page_pool.arenas = NULL;
990 g->page_pool.arena_cursor = NULL;
991 g->page_pool.arena_end = NULL;
992 g->page_pool.arena_current = NULL;
993 g->page_pool.arena_count = 0;
994 g->page_pool.advised_count = 0;
995 g->tdata_deferred_free_pjob = POSTPONED_JOB_HANDLE_INVALID;
996 g->tdata_unsafe_free_published = NULL;
997 g->tdata_unsafe_free_cache = NULL;
998 g->tdata_unsafe_free_cache_len = 0;
999 g->page_pool.arenas_unmapped = 0;
1000#ifdef HAVE_MMAP
1001 g->page_pool.os_page_size = sysconf(_SC_PAGE_SIZE);
1002#else
1003 g->page_pool.os_page_size = 0;
1004#endif
1005 global_objspace = g;
1006 }
1007}
1008
1009#ifndef HEAP_PAGE_ALIGN_LOG
1010/* default tiny heap size: 64KiB */
1011#define HEAP_PAGE_ALIGN_LOG 16
1012#endif
1013
1014#if GC_DEBUG
1015struct rvalue_overhead {
1016 const char *file;
1017 int line;
1018};
1019
1020// Make sure that RVALUE_OVERHEAD aligns to sizeof(VALUE)
1021# define RVALUE_OVERHEAD (sizeof(struct { \
1022 union { \
1023 struct rvalue_overhead overhead; \
1024 VALUE value; \
1025 }; \
1026}))
1027size_t rb_gc_impl_obj_slot_size(VALUE obj);
1028# define GET_RVALUE_OVERHEAD(obj) ((struct rvalue_overhead *)((uintptr_t)obj + rb_gc_impl_obj_slot_size(obj)))
1029#else
1030# ifndef RVALUE_OVERHEAD
1031# define RVALUE_OVERHEAD 0
1032# endif
1033#endif
1034
1035#define RVALUE_SLOT_SIZE (sizeof(struct RBasic) + sizeof(VALUE[RBIMPL_RVALUE_EMBED_LEN_MAX]) + RVALUE_OVERHEAD)
1036
1037static const size_t pool_slot_sizes[HEAP_COUNT] = {
1038#define SLOT(size) ((size) + RVALUE_OVERHEAD),
1039 EACH_POOL_SLOT_SIZE(SLOT)
1040#undef SLOT
1041};
1042
1043/* An init size below one slot in the largest heap never forces that heap's first
1044 * page, and allocating there then fails with "cannot create a new page after GC". */
1045static inline size_t
1046heap_init_bytes_min(void)
1047{
1048 return pool_slot_sizes[HEAP_COUNT - 1];
1049}
1050
1051/* Precomputed reciprocals for fast slot index calculation.
1052 * For slot size d: reciprocal = ceil(2^48 / d).
1053 * Then offset / d == (uint32_t)((offset * reciprocal) >> 48)
1054 * for all offset < HEAP_PAGE_SIZE. */
1055#define SLOT_RECIPROCAL_SHIFT 48
1056#define SLOT_RECIPROCAL(size) (((1ULL << SLOT_RECIPROCAL_SHIFT) + (size) - 1) / (size))
1057
1058static const uint64_t heap_slot_reciprocal_table[HEAP_COUNT] = {
1059#define SLOT(size) SLOT_RECIPROCAL((size) + RVALUE_OVERHEAD),
1060 EACH_POOL_SLOT_SIZE(SLOT)
1061#undef SLOT
1062};
1063
1064#if SIZEOF_VALUE >= 8
1065static uint8_t size_to_heap_idx[1024 / 8 + 1];
1066#else
1067static uint8_t size_to_heap_idx[512 / 8 + 1];
1068#endif
1069
1070#ifndef MAX
1071# define MAX(a, b) (((a) > (b)) ? (a) : (b))
1072#endif
1073#ifndef MIN
1074# define MIN(a, b) (((a) < (b)) ? (a) : (b))
1075#endif
1076#define roomof(x, y) (((x) + (y) - 1) / (y))
1077#define CEILDIV(i, mod) roomof(i, mod)
1078#define MIN_POOL_SLOT_SIZE 32
1079enum {
1080 HEAP_PAGE_ALIGN = (1UL << HEAP_PAGE_ALIGN_LOG),
1081 HEAP_PAGE_ALIGN_MASK = (~(~0UL << HEAP_PAGE_ALIGN_LOG)),
1082 HEAP_PAGE_SIZE = HEAP_PAGE_ALIGN,
1083 HEAP_PAGE_BITMAP_LIMIT = CEILDIV(CEILDIV(HEAP_PAGE_SIZE, MIN_POOL_SLOT_SIZE), BITS_BITLENGTH),
1084 HEAP_PAGE_BITMAP_SIZE = (BITS_SIZE * HEAP_PAGE_BITMAP_LIMIT),
1085};
1086#define HEAP_PAGE_ALIGN (1 << HEAP_PAGE_ALIGN_LOG)
1087#define HEAP_PAGE_SIZE HEAP_PAGE_ALIGN
1088
1089#if !defined(INCREMENTAL_MARK_STEP_ALLOCATIONS)
1090# define INCREMENTAL_MARK_STEP_ALLOCATIONS 500
1091#endif
1092
1093#undef INIT_HEAP_PAGE_ALLOC_USE_MMAP
1094/* Must define either HEAP_PAGE_ALLOC_USE_MMAP or
1095 * INIT_HEAP_PAGE_ALLOC_USE_MMAP. */
1096
1097#ifndef HAVE_MMAP
1098/* We can't use mmap of course, if it is not available. */
1099static const bool HEAP_PAGE_ALLOC_USE_MMAP = false;
1100
1101#elif defined(__wasm__)
1102/* wasmtime does not have proper support for mmap.
1103 * See https://github.com/bytecodealliance/wasmtime/blob/main/docs/WASI-rationale.md#why-no-mmap-and-friends
1104 */
1105static const bool HEAP_PAGE_ALLOC_USE_MMAP = false;
1106
1107#elif HAVE_CONST_PAGE_SIZE
1108/* If we have the PAGE_SIZE and it is a constant, then we can directly use it. */
1109static const bool HEAP_PAGE_ALLOC_USE_MMAP = (PAGE_SIZE <= HEAP_PAGE_SIZE);
1110
1111#elif defined(PAGE_MAX_SIZE) && (PAGE_MAX_SIZE <= HEAP_PAGE_SIZE)
1112/* If we can use the maximum page size. */
1113static const bool HEAP_PAGE_ALLOC_USE_MMAP = true;
1114
1115#elif defined(PAGE_SIZE)
1116/* If the PAGE_SIZE macro can be used dynamically. */
1117# define INIT_HEAP_PAGE_ALLOC_USE_MMAP (PAGE_SIZE <= HEAP_PAGE_SIZE)
1118
1119#elif defined(HAVE_SYSCONF) && defined(_SC_PAGE_SIZE)
1120/* If we can use sysconf to determine the page size. */
1121# define INIT_HEAP_PAGE_ALLOC_USE_MMAP (sysconf(_SC_PAGE_SIZE) <= HEAP_PAGE_SIZE)
1122
1123#else
1124/* Otherwise we can't determine the system page size, so don't use mmap. */
1125static const bool HEAP_PAGE_ALLOC_USE_MMAP = false;
1126#endif
1127
1128#ifdef INIT_HEAP_PAGE_ALLOC_USE_MMAP
1129/* We can determine the system page size at runtime. */
1130# define HEAP_PAGE_ALLOC_USE_MMAP (heap_page_alloc_use_mmap != false)
1131
1132static bool heap_page_alloc_use_mmap;
1133#endif
1134
1135#define RVALUE_AGE_BIT_COUNT 2
1136#define RVALUE_AGE_BIT_MASK (((bits_t)1 << RVALUE_AGE_BIT_COUNT) - 1)
1137#define RVALUE_OLD_AGE 3
1138
1140 VALUE flags; /* always 0 for freed obj */
1141 uintptr_t end; /* exclusive end address of the run */
1142 struct free_region *next; /* next free region in the page */
1143};
1144
1146 /* Cache line 0: allocation fast path + SLOT_INDEX */
1147 struct free_region *free_region;
1148 uintptr_t start;
1149 uint64_t slot_size_reciprocal;
1150 unsigned short slot_size;
1151 unsigned short total_slots;
1152 unsigned short free_slots;
1153 unsigned short final_slots;
1154 unsigned short pinned_slots;
1155 /* Page state flags. A bitfield is safe: the only writers are the owning Ractor
1156 * (GVL) and the global GC driver (stop-the-world), never together. has_shareable /
1157 * has_shref hint that the page holds at least one such bit, for re-scanning. */
1158 struct {
1159 unsigned int before_sweep : 1;
1160 unsigned int has_remembered_objects : 1;
1161 unsigned int has_uncollectible_wb_unprotected_objects : 1;
1162 unsigned int has_shref_objects : 1;
1163 unsigned int has_shareable_objects : 1;
1164 } flags;
1165
1166 rb_heap_t *heap;
1167
1168 /* The objspace owning this page, so any object's owner is one load away
1169 * (GET_HEAP_OBJSPACE). Rewritten only when a page changes owner (inheritance). */
1171
1172 struct heap_page *free_next;
1173 struct heap_page_body *body;
1174 struct page_arena *arena;
1175 struct ccan_list_node page_node;
1176
1177 bits_t wb_unprotected_bits[HEAP_PAGE_BITMAP_LIMIT];
1178 /* the following three bitmaps are cleared at the beginning of full GC */
1179 bits_t mark_bits[HEAP_PAGE_BITMAP_LIMIT];
1180 bits_t uncollectible_bits[HEAP_PAGE_BITMAP_LIMIT];
1181 bits_t marking_bits[HEAP_PAGE_BITMAP_LIMIT];
1182
1183 bits_t remembered_bits[HEAP_PAGE_BITMAP_LIMIT];
1184
1185 /* Two extra bits per object. shareable_bits: what a local sweep must never free
1186 * (only a global GC decides a shareable object is dead); set at creation and by
1187 * rb_gc_impl_obj_became_shareable. shref_bits: an unshareable object referenced
1188 * from a shareable one, a local GC root; the write barrier maintains it. */
1189 bits_t shareable_bits[HEAP_PAGE_BITMAP_LIMIT];
1190 bits_t shref_bits[HEAP_PAGE_BITMAP_LIMIT];
1191
1192 /* If set, the object is not movable */
1193 bits_t pinned_bits[HEAP_PAGE_BITMAP_LIMIT];
1194 bits_t age_bits[HEAP_PAGE_BITMAP_LIMIT * RVALUE_AGE_BIT_COUNT];
1195};
1196
1197/*
1198 * When asan is enabled, this will prohibit writing to the freelist until it is unlocked
1199 */
1200static void
1201asan_lock_freelist(struct heap_page *page)
1202{
1203 asan_poison_memory_region(&page->free_region, sizeof(struct free_region *));
1204}
1205
1206/*
1207 * When asan is enabled, this will enable the ability to write to the freelist
1208 */
1209static void
1210asan_unlock_freelist(struct heap_page *page)
1211{
1212 asan_unpoison_memory_region(&page->free_region, sizeof(struct free_region *), false);
1213}
1214
1215static inline bool
1216heap_page_in_global_empty_pages_pool(rb_objspace_t *objspace, struct heap_page *page)
1217{
1218 if (page->total_slots == 0) {
1219 GC_ASSERT(page->start == 0);
1220 GC_ASSERT(page->slot_size == 0);
1221 GC_ASSERT(page->heap == NULL);
1222 GC_ASSERT(page->free_slots == 0);
1223 asan_unpoisoning_memory_region(&page->free_region, sizeof(&page->free_region)) {
1224 GC_ASSERT(page->free_region == NULL);
1225 }
1226
1227 return true;
1228 }
1229 else {
1230 GC_ASSERT(page->start != 0);
1231 GC_ASSERT(page->slot_size != 0);
1232 GC_ASSERT(page->heap != NULL);
1233
1234 return false;
1235 }
1236}
1237
1238#define GET_PAGE_BODY(x) ((struct heap_page_body *)((bits_t)(x) & ~(HEAP_PAGE_ALIGN_MASK)))
1239#define GET_PAGE_HEADER(x) (&GET_PAGE_BODY(x)->header)
1240#define GET_HEAP_PAGE(x) (GET_PAGE_HEADER(x)->page)
1241
1242static inline size_t
1243slot_index_for_offset(size_t offset, uint64_t reciprocal)
1244{
1245 return (uint32_t)(((uint64_t)offset * reciprocal) >> SLOT_RECIPROCAL_SHIFT);
1246}
1247
1248#define SLOT_INDEX(page, p) slot_index_for_offset((uintptr_t)(p) - (page)->start, (page)->slot_size_reciprocal)
1249#define SLOT_BITMAP_INDEX(page, p) (SLOT_INDEX(page, p) / BITS_BITLENGTH)
1250#define SLOT_BITMAP_OFFSET(page, p) (SLOT_INDEX(page, p) & (BITS_BITLENGTH - 1))
1251#define SLOT_BITMAP_BIT(page, p) ((bits_t)1 << SLOT_BITMAP_OFFSET(page, p))
1252
1253#define _MARKED_IN_BITMAP(bits, page, p) ((bits)[SLOT_BITMAP_INDEX(page, p)] & SLOT_BITMAP_BIT(page, p))
1254#define _MARK_IN_BITMAP(bits, page, p) ((bits)[SLOT_BITMAP_INDEX(page, p)] |= SLOT_BITMAP_BIT(page, p))
1255#define _CLEAR_IN_BITMAP(bits, page, p) ((bits)[SLOT_BITMAP_INDEX(page, p)] &= ~SLOT_BITMAP_BIT(page, p))
1256
1257#define MARKED_IN_BITMAP(bits, p) _MARKED_IN_BITMAP(bits, GET_HEAP_PAGE(p), p)
1258#define MARK_IN_BITMAP(bits, p) _MARK_IN_BITMAP(bits, GET_HEAP_PAGE(p), p)
1259#define CLEAR_IN_BITMAP(bits, p) _CLEAR_IN_BITMAP(bits, GET_HEAP_PAGE(p), p)
1260
1261#define GET_HEAP_MARK_BITS(x) (&GET_HEAP_PAGE(x)->mark_bits[0])
1262#define GET_HEAP_PINNED_BITS(x) (&GET_HEAP_PAGE(x)->pinned_bits[0])
1263#define GET_HEAP_UNCOLLECTIBLE_BITS(x) (&GET_HEAP_PAGE(x)->uncollectible_bits[0])
1264#define GET_HEAP_WB_UNPROTECTED_BITS(x) (&GET_HEAP_PAGE(x)->wb_unprotected_bits[0])
1265#define GET_HEAP_MARKING_BITS(x) (&GET_HEAP_PAGE(x)->marking_bits[0])
1266#define GET_HEAP_SHAREABLE_BITS(x) (&GET_HEAP_PAGE(x)->shareable_bits[0])
1267#define GET_HEAP_SHREF_BITS(x) (&GET_HEAP_PAGE(x)->shref_bits[0])
1268#define GET_HEAP_OBJSPACE(x) (GET_HEAP_PAGE(x)->objspace)
1269
1270/* obj lives on a page of another objspace, not the current one (i.e. it is foreign). */
1271static inline bool
1272gc_foreign_object_p(const rb_objspace_t *objspace, VALUE obj)
1273{
1274 if (RB_LIKELY(!rb_gc_ever_multi_ractor_p())) return false;
1275
1276 return RB_UNLIKELY(GET_HEAP_OBJSPACE(obj) != objspace);
1277}
1278
1279/* Foreign and not inside a stop-the-world global GC. While true, a local GC must not
1280 * touch obj's per-object GC state (mark, pin, remember bits): its owner handles that,
1281 * or the global GC does with everyone stopped. */
1282static inline bool
1283gc_skip_foreign_object_p(const rb_objspace_t *objspace, VALUE obj)
1284{
1285 return gc_foreign_object_p(objspace, obj) && !objspace->flags.during_global_gc;
1286}
1287
1288/* Record obj as shareable on its owning page (bit, page flag and population counter).
1289 * Shared by born-shareable objects and make_shareable. The writer is the owner thread,
1290 * so plain bit operations suffice. */
1291static inline void
1292gc_page_add_shareable(struct heap_page *page, VALUE obj)
1293{
1294 GC_ASSERT(page == GET_HEAP_PAGE(obj));
1295 GC_ASSERT(RB_FL_TEST_RAW(obj, RUBY_FL_SHAREABLE));
1296 _MARK_IN_BITMAP(page->shareable_bits, page, obj);
1297 page->flags.has_shareable_objects = TRUE;
1298 page->objspace->shareable_objects++;
1299}
1300
1301static int
1302RVALUE_AGE_GET(VALUE obj)
1303{
1304 struct heap_page *page = GET_HEAP_PAGE(obj);
1305 bits_t *age_bits = page->age_bits;
1306 size_t slot_idx = SLOT_INDEX(page, obj);
1307 size_t idx = (slot_idx / BITS_BITLENGTH) * 2;
1308 int shift = (int)(slot_idx & (BITS_BITLENGTH - 1));
1309 int lo = (age_bits[idx] >> shift) & 1;
1310 int hi = (age_bits[idx + 1] >> shift) & 1;
1311 return lo | (hi << 1);
1312}
1313
1314static void
1315RVALUE_AGE_SET_BITMAP(VALUE obj, int age)
1316{
1317 RUBY_ASSERT(age <= RVALUE_OLD_AGE);
1318 struct heap_page *page = GET_HEAP_PAGE(obj);
1319 bits_t *age_bits = page->age_bits;
1320 size_t slot_idx = SLOT_INDEX(page, obj);
1321 size_t idx = (slot_idx / BITS_BITLENGTH) * 2;
1322 int shift = (int)(slot_idx & (BITS_BITLENGTH - 1));
1323 bits_t mask = (bits_t)1 << shift;
1324
1325 age_bits[idx] = (age_bits[idx] & ~mask) | ((bits_t)(age & 1) << shift);
1326 age_bits[idx + 1] = (age_bits[idx + 1] & ~mask) | ((bits_t)((age >> 1) & 1) << shift);
1327}
1328
1329static void
1330RVALUE_AGE_SET(VALUE obj, int age)
1331{
1332 RVALUE_AGE_SET_BITMAP(obj, age);
1333 if (age == RVALUE_OLD_AGE) {
1335 }
1336 else {
1338 }
1339}
1340
1341#define malloc_limit objspace->malloc_params.limit
1342#define malloc_increase gc_malloc_counters_increase_unsigned(objspace, &objspace->malloc_counters.counters)
1343#define malloc_allocated_size objspace->malloc_params.allocated_size
1344
1345#ifdef MALLOC_COUNTERS_NEED_LOCK
1346# define MALLOC_COUNTERS_LOCK(o) rb_native_mutex_lock(&(o)->malloc_counters.lock)
1347# define MALLOC_COUNTERS_UNLOCK(o) rb_native_mutex_unlock(&(o)->malloc_counters.lock)
1348#else
1349# define MALLOC_COUNTERS_LOCK(o) ((void)0)
1350# define MALLOC_COUNTERS_UNLOCK(o) ((void)0)
1351#endif
1352
1353static inline void
1354gc_counter_add(gc_counter_t *p, size_t delta)
1355{
1356#ifdef MALLOC_COUNTERS_NEED_LOCK
1357 *p += (gc_counter_t)delta;
1358#else
1359 rbimpl_atomic_u64_fetch_add_relaxed(p, (uint64_t)delta);
1360#endif
1361}
1362
1363static inline gc_counter_t
1364gc_counter_load_relaxed(const gc_counter_t *p)
1365{
1366#ifdef MALLOC_COUNTERS_NEED_LOCK
1367 return *p;
1368#else
1369 return rbimpl_atomic_u64_load_relaxed(p);
1370#endif
1371}
1372
1373static inline gc_counter_t
1374gc_counter_load_acquire(const gc_counter_t *p)
1375{
1376#ifdef MALLOC_COUNTERS_NEED_LOCK
1377 return *p;
1378#else
1379 return rbimpl_atomic_u64_load_acquire(p);
1380#endif
1381}
1382
1383static inline void
1384gc_counter_store_release(gc_counter_t *p, gc_counter_t v)
1385{
1386#ifdef MALLOC_COUNTERS_NEED_LOCK
1387 *p = v;
1388#else
1389 rbimpl_atomic_u64_set_release(p, v);
1390#endif
1391}
1392
1393static inline int64_t
1394gc_malloc_counters_increase(rb_objspace_t *objspace, const struct gc_malloc_bytes *c)
1395{
1396 MALLOC_COUNTERS_LOCK(objspace);
1397 gc_counter_t malloc_at = gc_counter_load_acquire(&c->malloc_at_last_gc);
1398 gc_counter_t free_at = gc_counter_load_acquire(&c->free_at_last_gc);
1399 gc_counter_t malloc_now = gc_counter_load_relaxed(&c->malloc);
1400 gc_counter_t free_now = gc_counter_load_relaxed(&c->free);
1401 MALLOC_COUNTERS_UNLOCK(objspace);
1402
1403 gc_counter_t malloc_delta = malloc_now - malloc_at;
1404 gc_counter_t free_delta = free_now - free_at;
1405
1406 if (malloc_delta >= free_delta) {
1407 return (int64_t)(malloc_delta - free_delta);
1408 }
1409 else {
1410 return -(int64_t)(free_delta - malloc_delta);
1411 }
1412}
1413
1414static inline size_t
1415gc_malloc_counters_increase_unsigned(rb_objspace_t *objspace, const struct gc_malloc_bytes *c)
1416{
1417 int64_t inc = gc_malloc_counters_increase(objspace, c);
1418 if (inc <= 0) return 0;
1419#if SIZEOF_SIZE_T < 8
1420 if ((uint64_t)inc > SIZE_MAX) return SIZE_MAX;
1421#endif
1422 return (size_t)inc;
1423}
1424
1425/* Frees done while sweeping are the GC's own work, not the mutator's: advance
1426 * free_at_last_gc past them so they cannot pay for the next cycle's allocation.
1427 * malloc_at_last_gc stays at gc_reset_malloc_info's snapshot (GC start). */
1428static inline void
1429gc_malloc_counters_snapshot_free_at_last_gc(rb_objspace_t *objspace, struct gc_malloc_bytes *c)
1430{
1431 MALLOC_COUNTERS_LOCK(objspace);
1432 gc_counter_store_release(&c->free_at_last_gc, gc_counter_load_relaxed(&c->free));
1433 MALLOC_COUNTERS_UNLOCK(objspace);
1434}
1435
1436static inline void
1437gc_malloc_counters_snapshot(rb_objspace_t *objspace, struct gc_malloc_bytes *c)
1438{
1439 MALLOC_COUNTERS_LOCK(objspace);
1440 gc_counter_t malloc_now = gc_counter_load_relaxed(&c->malloc);
1441 gc_counter_t free_now = gc_counter_load_relaxed(&c->free);
1442 gc_counter_store_release(&c->malloc_at_last_gc, malloc_now);
1443 gc_counter_store_release(&c->free_at_last_gc, free_now);
1444 MALLOC_COUNTERS_UNLOCK(objspace);
1445}
1446
1447#if RGENGC_ESTIMATE_OLDMALLOC
1448static inline size_t
1449gc_oldmalloc_increase_load(rb_objspace_t *objspace)
1450{
1451 return rbimpl_atomic_size_load(&objspace->malloc_counters.oldmalloc_increase, RBIMPL_ATOMIC_RELAXED);
1452}
1453#endif
1454
1455#define heap_pages_lomem objspace->heap_pages.range[0]
1456#define heap_pages_himem objspace->heap_pages.range[1]
1457#define heap_pages_freeable_pages objspace->heap_pages.freeable_pages
1458#define heap_pages_deferred_final objspace->heap_pages.deferred_final
1459#define heaps objspace->heaps
1460#define during_gc objspace->flags.during_gc
1461#define finalizing objspace->atomic_flags.finalizing
1462#define finalizer_table objspace->finalizer_table
1463#define ruby_gc_stressful global_objspace->gc_stressful
1464#define ruby_gc_stress_mode global_objspace->gc_stress_mode
1465#if GC_DEBUG_STRESS_TO_CLASS
1466#define stress_to_class objspace->stress_to_class
1467#define set_stress_to_class(c) (stress_to_class = (c))
1468#else
1469#define stress_to_class ((void)objspace, 0)
1470#define set_stress_to_class(c) ((void)objspace, (c))
1471#endif
1472
1473#if 0
1474#define dont_gc_on() (fprintf(stderr, "dont_gc_on@%s:%d\n", __FILE__, __LINE__), objspace->flags.dont_gc = 1)
1475#define dont_gc_off() (fprintf(stderr, "dont_gc_off@%s:%d\n", __FILE__, __LINE__), objspace->flags.dont_gc = 0)
1476#define dont_gc_set(b) (fprintf(stderr, "dont_gc_set(%d)@%s:%d\n", __FILE__, __LINE__), objspace->flags.dont_gc = (int)(b))
1477#define dont_gc_val() (objspace->flags.dont_gc)
1478#else
1479#define dont_gc_on() (objspace->flags.dont_gc = 1)
1480#define dont_gc_off() (objspace->flags.dont_gc = 0)
1481#define dont_gc_set(b) (objspace->flags.dont_gc = (int)(b))
1482#define dont_gc_val() (objspace->flags.dont_gc)
1483#endif
1484
1485#define gc_config_full_mark_set(b) (objspace->gc_config.full_mark = (int)(b))
1486#define gc_config_full_mark_val (objspace->gc_config.full_mark)
1487
1488static inline enum gc_mode
1489gc_mode_verify(enum gc_mode mode)
1490{
1491#if RGENGC_CHECK_MODE > 0
1492 switch (mode) {
1493 case gc_mode_none:
1494 case gc_mode_marking:
1495 case gc_mode_sweeping:
1496 case gc_mode_compacting:
1497 break;
1498 default:
1499 rb_bug("gc_mode_verify: unreachable (%d)", (int)mode);
1500 }
1501#endif
1502 return mode;
1503}
1504
1505static inline bool
1506has_sweeping_pages(rb_objspace_t *objspace)
1507{
1508 return objspace->sweeping_heap_count != 0;
1509}
1510
1511static inline size_t
1512heap_eden_total_pages(rb_objspace_t *objspace)
1513{
1514 size_t count = 0;
1515 for (int i = 0; i < HEAP_COUNT; i++) {
1516 count += (&heaps[i])->total_pages;
1517 }
1518 return count;
1519}
1520
1521static inline size_t
1522total_allocated_objects(rb_objspace_t *objspace)
1523{
1524 size_t count = 0;
1525 for (int i = 0; i < HEAP_COUNT; i++) {
1526 rb_heap_t *heap = &heaps[i];
1527 count += heap->total_allocated_objects;
1528 }
1529 return count;
1530}
1531
1532static inline size_t
1533total_freed_objects(rb_objspace_t *objspace)
1534{
1535 size_t count = 0;
1536 for (int i = 0; i < HEAP_COUNT; i++) {
1537 rb_heap_t *heap = &heaps[i];
1538 count += heap->total_freed_objects;
1539 }
1540 return count;
1541}
1542
1543static inline size_t
1544total_final_slots_count(rb_objspace_t *objspace)
1545{
1546 size_t count = 0;
1547 for (int i = 0; i < HEAP_COUNT; i++) {
1548 rb_heap_t *heap = &heaps[i];
1549 count += heap->final_slots_count;
1550 }
1551 return count;
1552}
1553
1554#define gc_mode(objspace) gc_mode_verify((enum gc_mode)(objspace)->flags.mode)
1555#define gc_mode_set(objspace, m) ((objspace)->flags.mode = (unsigned int)gc_mode_verify(m))
1556#define gc_needs_major_flags objspace->rgengc.need_major_gc
1557
1558#define is_marking(objspace) (gc_mode(objspace) == gc_mode_marking)
1559#define is_sweeping(objspace) (gc_mode(objspace) == gc_mode_sweeping)
1560#define is_full_marking(objspace) ((objspace)->flags.during_minor_gc == FALSE)
1561#define is_incremental_marking(objspace) ((objspace)->zjit_during_incremental_marking != FALSE)
1562#define will_be_incremental_marking(objspace) ((objspace)->rgengc.need_major_gc != GPR_FLAG_NONE)
1563
1564static void
1565gc_set_incremental_marking(rb_objspace_t *objspace, unsigned int value)
1566{
1567 if (objspace->zjit_during_incremental_marking != value) {
1568 objspace->zjit_during_incremental_marking = value;
1569 }
1570}
1571/*
1572 * Byte budget for incremental sweep steps. Each step sweeps at most
1573 * this many bytes worth of slots before yielding. The effective slot
1574 * count per step is GC_INCREMENTAL_SWEEP_BYTES / heap->slot_size,
1575 * so larger slot pools (which are less heavily used) naturally get
1576 * fewer slots swept per step.
1577 *
1578 * Baseline: 2048 slots * RVALUE_SLOT_SIZE = 2048 * 40 = 81920 bytes,
1579 * preserving the historical behavior for the smallest heap.
1580 */
1581#define GC_INCREMENTAL_SWEEP_BYTES (2048 * RVALUE_SLOT_SIZE)
1582#define GC_INCREMENTAL_SWEEP_POOL_BYTES (1024 * RVALUE_SLOT_SIZE)
1583#define is_lazy_sweeping(objspace) (GC_ENABLE_LAZY_SWEEP && has_sweeping_pages(objspace))
1584/* In lazy sweeping or the previous incremental marking finished and did not yield a free page. */
1585#define needs_continue_sweeping(objspace, heap) \
1586 ((heap)->free_pages == NULL && is_lazy_sweeping(objspace))
1587
1588#if SIZEOF_LONG == SIZEOF_VOIDP
1589# define obj_id_to_ref(objid) ((objid) ^ FIXNUM_FLAG) /* unset FIXNUM_FLAG */
1590#elif SIZEOF_LONG_LONG == SIZEOF_VOIDP
1591# define obj_id_to_ref(objid) (FIXNUM_P(objid) ? \
1592 ((objid) ^ FIXNUM_FLAG) : (NUM2PTR(objid) << 1))
1593#else
1594# error not supported
1595#endif
1596
1597struct RZombie {
1598 VALUE flags;
1599 VALUE next;
1600 void (*dfree)(void *);
1601 void *data;
1602};
1603
1604#define RZOMBIE(o) ((struct RZombie *)(o))
1605
1606static bool ruby_enable_autocompact = false;
1607#if RGENGC_CHECK_MODE
1608static gc_compact_compare_func ruby_autocompact_compare_func;
1609#endif
1610
1611static void init_mark_stack(mark_stack_t *stack);
1612static int garbage_collect(rb_objspace_t *, unsigned int reason);
1613
1614static int gc_start(rb_objspace_t *objspace, unsigned int reason);
1615static void gc_rest(rb_objspace_t *objspace);
1616
1617/* GC cycle events (ENTER, EXIT, START, END_MARK, END_SWEEP) fire only if the objspace's
1618 * own Ractor enabled them, so a concurrent local GC never walks the VM-global hook list
1619 * while another Ractor mutates it. NEWOBJ and FREEOBJ were already restricted. */
1620#define gc_event_hook(objspace, event) do { \
1621 if (RB_UNLIKELY((objspace)->hook_events & (event))) { \
1622 rb_gc_event_hook(0, (event)); \
1623 } \
1624} while (0)
1625
1626enum gc_enter_event {
1627 gc_enter_event_start,
1628 gc_enter_event_continue,
1629 gc_enter_event_rest,
1630 gc_enter_event_finalizer,
1631 gc_enter_event_global,
1632 gc_enter_event_global_auto,
1633};
1634
1635static inline bool gc_enter(rb_objspace_t *objspace, enum gc_enter_event event, unsigned int *lock_lev);
1636static inline void gc_exit(rb_objspace_t *objspace, enum gc_enter_event event, unsigned int *lock_lev);
1637static void gc_marking_enter(rb_objspace_t *objspace);
1638static void gc_marking_exit(rb_objspace_t *objspace);
1639static void gc_sweeping_enter(rb_objspace_t *objspace);
1640static void gc_sweeping_exit(rb_objspace_t *objspace);
1641static bool gc_marks_continue(rb_objspace_t *objspace, rb_heap_t *heap);
1642
1643static void gc_sweep(rb_objspace_t *objspace);
1644static void gc_sweep_finish_heap(rb_objspace_t *objspace, rb_heap_t *heap);
1645static void gc_sweep_continue(rb_objspace_t *objspace, rb_heap_t *heap);
1646
1647static inline void gc_mark(rb_objspace_t *objspace, VALUE ptr);
1648static inline void gc_pin(rb_objspace_t *objspace, VALUE ptr);
1649static inline void gc_mark_and_pin(rb_objspace_t *objspace, VALUE ptr);
1650
1651static int gc_mark_stacked_objects_incremental(rb_objspace_t *, size_t count);
1652NO_SANITIZE("memory", static inline bool is_pointer_to_heap(rb_objspace_t *objspace, const void *ptr));
1653
1654static void gc_verify_internal_consistency(void *objspace_ptr);
1655
1656static double getrusage_time(void);
1657static inline rb_hrtime_t elapsed_hrtime_from(rb_hrtime_t start);
1658static inline void gc_prof_setup_new_record(rb_objspace_t *objspace, unsigned int reason);
1659static inline void gc_prof_timer_start(rb_objspace_t *);
1660static inline void gc_prof_timer_stop(rb_objspace_t *);
1661static inline void gc_prof_mark_timer_start(rb_objspace_t *);
1662static inline void gc_prof_mark_timer_stop(rb_objspace_t *);
1663static inline void gc_prof_sweep_timer_start(rb_objspace_t *);
1664static inline void gc_prof_sweep_timer_stop(rb_objspace_t *);
1665static inline void gc_prof_set_malloc_info(rb_objspace_t *);
1666static inline void gc_prof_set_heap_info(rb_objspace_t *);
1667
1668#define gc_prof_record(objspace) (objspace)->profile.current_record
1669#define gc_prof_enabled(objspace) ((objspace)->profile.run && (objspace)->profile.current_record)
1670
1671#define gc_report(level, objspace, ...) \
1672 if (!RGENGC_DEBUG_ENABLED(level)) {} else gc_report_body(level, objspace, __VA_ARGS__)
1673PRINTF_ARGS(static void gc_report_body(int level, rb_objspace_t *objspace, const char *fmt, ...), 3, 4);
1674
1675static void gc_finalize_deferred(void *dmy);
1676static void gc_tdata_unsafe_drain_objspaces(rb_objspace_t **objspaces, size_t n);
1677
1678#if USE_TICK_T
1679
1680/* the following code is only for internal tuning. */
1681
1682/* Source code to use RDTSC is quoted and modified from
1683 * https://www.mcs.anl.gov/~kazutomo/rdtsc.html
1684 * written by Kazutomo Yoshii <kazutomo@mcs.anl.gov>
1685 */
1686
1687#if defined(__GNUC__) && defined(__i386__)
1688typedef unsigned long long tick_t;
1689#define PRItick "llu"
1690static inline tick_t
1691tick(void)
1692{
1693 unsigned long long int x;
1694 __asm__ __volatile__ ("rdtsc" : "=A" (x));
1695 return x;
1696}
1697
1698#elif defined(__GNUC__) && defined(__x86_64__)
1699typedef unsigned long long tick_t;
1700#define PRItick "llu"
1701
1702static __inline__ tick_t
1703tick(void)
1704{
1705 unsigned long hi, lo;
1706 __asm__ __volatile__ ("rdtsc" : "=a"(lo), "=d"(hi));
1707 return ((unsigned long long)lo)|( ((unsigned long long)hi)<<32);
1708}
1709
1710#elif defined(__powerpc64__) && (GCC_VERSION_SINCE(4,8,0) || defined(__clang__))
1711typedef unsigned long long tick_t;
1712#define PRItick "llu"
1713
1714static __inline__ tick_t
1715tick(void)
1716{
1717 unsigned long long val = __builtin_ppc_get_timebase();
1718 return val;
1719}
1720
1721#elif defined(__aarch64__) && defined(__GNUC__)
1722typedef unsigned long tick_t;
1723#define PRItick "lu"
1724
1725static __inline__ tick_t
1726tick(void)
1727{
1728 unsigned long val;
1729 __asm__ __volatile__ ("mrs %0, cntvct_el0" : "=r" (val));
1730 return val;
1731}
1732
1733
1734#elif defined(_WIN32) && defined(_MSC_VER)
1735#include <intrin.h>
1736typedef unsigned __int64 tick_t;
1737#define PRItick "llu"
1738
1739static inline tick_t
1740tick(void)
1741{
1742 return __rdtsc();
1743}
1744
1745#else /* use clock */
1746typedef clock_t tick_t;
1747#define PRItick "llu"
1748
1749static inline tick_t
1750tick(void)
1751{
1752 return clock();
1753}
1754#endif /* TSC */
1755#else /* USE_TICK_T */
1756#define MEASURE_LINE(expr) expr
1757#endif /* USE_TICK_T */
1758
1759static inline VALUE check_rvalue_consistency(rb_objspace_t *objspace, const VALUE obj);
1760
1761#define RVALUE_MARKED_BITMAP(obj) MARKED_IN_BITMAP(GET_HEAP_MARK_BITS(obj), (obj))
1762#define RVALUE_WB_UNPROTECTED_BITMAP(obj) MARKED_IN_BITMAP(GET_HEAP_WB_UNPROTECTED_BITS(obj), (obj))
1763#define RVALUE_MARKING_BITMAP(obj) MARKED_IN_BITMAP(GET_HEAP_MARKING_BITS(obj), (obj))
1764#define RVALUE_UNCOLLECTIBLE_BITMAP(obj) MARKED_IN_BITMAP(GET_HEAP_UNCOLLECTIBLE_BITS(obj), (obj))
1765#define RVALUE_PINNED_BITMAP(obj) MARKED_IN_BITMAP(GET_HEAP_PINNED_BITS(obj), (obj))
1766
1767static inline int
1768RVALUE_MARKED(rb_objspace_t *objspace, VALUE obj)
1769{
1770 check_rvalue_consistency(objspace, obj);
1771 return RVALUE_MARKED_BITMAP(obj) != 0;
1772}
1773
1774static inline int
1775RVALUE_PINNED(rb_objspace_t *objspace, VALUE obj)
1776{
1777 check_rvalue_consistency(objspace, obj);
1778 return RVALUE_PINNED_BITMAP(obj) != 0;
1779}
1780
1781static inline int
1782RVALUE_WB_UNPROTECTED(rb_objspace_t *objspace, VALUE obj)
1783{
1784 check_rvalue_consistency(objspace, obj);
1785 return RVALUE_WB_UNPROTECTED_BITMAP(obj) != 0;
1786}
1787
1788static inline int
1789RVALUE_MARKING(rb_objspace_t *objspace, VALUE obj)
1790{
1791 check_rvalue_consistency(objspace, obj);
1792 return RVALUE_MARKING_BITMAP(obj) != 0;
1793}
1794
1795static inline int
1796RVALUE_REMEMBERED(rb_objspace_t *objspace, VALUE obj)
1797{
1798 check_rvalue_consistency(objspace, obj);
1799 return MARKED_IN_BITMAP(GET_HEAP_PAGE(obj)->remembered_bits, obj) != 0;
1800}
1801
1802static inline int
1803RVALUE_UNCOLLECTIBLE(rb_objspace_t *objspace, VALUE obj)
1804{
1805 check_rvalue_consistency(objspace, obj);
1806 return RVALUE_UNCOLLECTIBLE_BITMAP(obj) != 0;
1807}
1808
1809#define RVALUE_PAGE_WB_UNPROTECTED(page, obj) MARKED_IN_BITMAP((page)->wb_unprotected_bits, (obj))
1810#define RVALUE_PAGE_UNCOLLECTIBLE(page, obj) MARKED_IN_BITMAP((page)->uncollectible_bits, (obj))
1811#define RVALUE_PAGE_MARKING(page, obj) MARKED_IN_BITMAP((page)->marking_bits, (obj))
1812
1813static void rgengc_remember(rb_objspace_t *objspace, VALUE obj);
1814static void gc_bitmaps_clear(rb_objspace_t *objspace, rb_heap_t *heap, bool clear_shref);
1815static void rgengc_rememberset_mark(rb_objspace_t *objspace, rb_heap_t *heap);
1816static bool verify_pointer_in_any_heap_p(const void *ptr); /* cross-objspace ownership test */
1817
1818static int
1819check_rvalue_consistency_force(rb_objspace_t *objspace, const VALUE obj, int terminate)
1820{
1821 int err = 0;
1822
1823 /* Under a global GC the barrier stops every Ractor, so the cross-objspace walk
1824 * below is safe without the VM lock. Sweeping an ownerless zombie objspace also
1825 * leaves GET_RACTOR() NULL, and taking the lock here would dereference it. */
1826 const bool world_stopped = objspace->flags.during_global_gc;
1827 /* The VM lock protects the cross-objspace walk while other Ractors run and
1828 * reallocate their heaps. Not taken while this objspace is in GC: pages are stable
1829 * then, the cross-objspace walk needs the world stopped anyway, and the Ractor lock
1830 * may already be held (Ractor -> VM order inversion). A global GC holds the barrier
1831 * and needs no lock. */
1832 const bool take_vm_lock = !world_stopped && !during_gc;
1833 unsigned int lev = 0;
1834 if (take_vm_lock) lev = RB_GC_VM_LOCK_NO_BARRIER();
1835 {
1836 if (SPECIAL_CONST_P(obj)) {
1837 fprintf(stderr, "check_rvalue_consistency: %p is a special const.\n", (void *)obj);
1838 err++;
1839 }
1840 else if (!is_pointer_to_heap(objspace, (void *)obj)) {
1841 /* obj may be a legitimate cross-objspace reference (a shareable object, an
1842 * in-flight shref payload); it is a non-object only if no objspace's heap
1843 * holds it. A foreign object's mark/age/remembered bits belong to its
1844 * owner and reading them would race its local GC: skip per-object checks. */
1845 if (!world_stopped) {
1846 /* A mid-local-GC verify holds no barrier, so other Ractors reallocate
1847 * heap_pages.sorted under verify_pointer_in_any_heap_p's page_index
1848 * read. Accept foreign pointers here; the global GC's world-stopped
1849 * verify does the full existence check. */
1850 }
1851 else if (!verify_pointer_in_any_heap_p((void *)obj)) {
1852 struct heap_page *empty_page = objspace->empty_pages;
1853 while (empty_page) {
1854 if ((uintptr_t)empty_page->body <= (uintptr_t)obj &&
1855 (uintptr_t)obj < (uintptr_t)empty_page->body + HEAP_PAGE_SIZE) {
1856 GC_ASSERT(heap_page_in_global_empty_pages_pool(objspace, empty_page));
1857 fprintf(stderr, "check_rvalue_consistency: %p is in an empty page (%p).\n",
1858 (void *)obj, (void *)empty_page);
1859 err++;
1860 goto skip;
1861 }
1862 empty_page = empty_page->free_next;
1863 }
1864 fprintf(stderr, "check_rvalue_consistency: %p is not a Ruby object.\n", (void *)obj);
1865 err++;
1866 skip:
1867 ;
1868 }
1869 }
1870 else {
1871 const int wb_unprotected_bit = RVALUE_WB_UNPROTECTED_BITMAP(obj) != 0;
1872 const int uncollectible_bit = RVALUE_UNCOLLECTIBLE_BITMAP(obj) != 0;
1873 const int mark_bit = RVALUE_MARKED_BITMAP(obj) != 0;
1874 const int marking_bit = RVALUE_MARKING_BITMAP(obj) != 0;
1875 const int remembered_bit = MARKED_IN_BITMAP(GET_HEAP_PAGE(obj)->remembered_bits, obj) != 0;
1876 const int age = RVALUE_AGE_GET((VALUE)obj);
1877
1878 if (heap_page_in_global_empty_pages_pool(objspace, GET_HEAP_PAGE(obj))) {
1879 fprintf(stderr, "check_rvalue_consistency: %s is in tomb page.\n", rb_obj_info(obj));
1880 err++;
1881 }
1882 if (BUILTIN_TYPE(obj) == T_NONE) {
1883 fprintf(stderr, "check_rvalue_consistency: %s is T_NONE.\n", rb_obj_info(obj));
1884 err++;
1885 }
1886 if (BUILTIN_TYPE(obj) == T_ZOMBIE) {
1887 fprintf(stderr, "check_rvalue_consistency: %s is T_ZOMBIE.\n", rb_obj_info(obj));
1888 err++;
1889 }
1890
1891 /* Do not run the memsize probe once an inconsistency (a T_NONE, say) was
1892 * found: an rb_bug inside the probe would lose the real diagnosis. */
1893 if (err == 0 && BUILTIN_TYPE(obj) != T_DATA) {
1894 rb_obj_memsize_of((VALUE)obj);
1895 }
1896
1897 /* check generation
1898 *
1899 * OLD == age == 3 && old-bitmap && mark-bit (except incremental marking)
1900 */
1901 if (age > 0 && wb_unprotected_bit) {
1902 fprintf(stderr, "check_rvalue_consistency: %s is not WB protected, but age is %d > 0.\n", rb_obj_info(obj), age);
1903 err++;
1904 }
1905
1906 if (!is_marking(objspace) && uncollectible_bit && !mark_bit) {
1907 fprintf(stderr, "check_rvalue_consistency: %s is uncollectible, but is not marked while !gc.\n", rb_obj_info(obj));
1908 err++;
1909 }
1910
1911 if (!is_full_marking(objspace)) {
1912 if (uncollectible_bit && age != RVALUE_OLD_AGE && !wb_unprotected_bit) {
1913 fprintf(stderr, "check_rvalue_consistency: %s is uncollectible, but not old (age: %d) and not WB unprotected.\n",
1914 rb_obj_info(obj), age);
1915 err++;
1916 }
1917 if (remembered_bit && age != RVALUE_OLD_AGE) {
1918 fprintf(stderr, "check_rvalue_consistency: %s is remembered, but not old (age: %d).\n",
1919 rb_obj_info(obj), age);
1920 err++;
1921 }
1922 }
1923
1924 /*
1925 * check coloring
1926 *
1927 * marking:false marking:true
1928 * marked:false white *invalid*
1929 * marked:true black grey
1930 */
1931 if (is_incremental_marking(objspace) && marking_bit) {
1932 if (!is_marking(objspace) && !mark_bit) {
1933 fprintf(stderr, "check_rvalue_consistency: %s is marking, but not marked.\n", rb_obj_info(obj));
1934 err++;
1935 }
1936 }
1937 }
1938 }
1939 if (take_vm_lock) RB_GC_VM_UNLOCK_NO_BARRIER(lev);
1940
1941 if (err > 0 && terminate) {
1942 rb_bug("check_rvalue_consistency_force: there is %d errors.", err);
1943 }
1944 return err;
1945}
1946
1947#if RGENGC_CHECK_MODE == 0
1948static inline VALUE
1949check_rvalue_consistency(rb_objspace_t *objspace, const VALUE obj)
1950{
1951 return obj;
1952}
1953#else
1954static VALUE
1955check_rvalue_consistency(rb_objspace_t *objspace, const VALUE obj)
1956{
1957 check_rvalue_consistency_force(objspace, obj, TRUE);
1958 return obj;
1959}
1960#endif
1961
1962static inline bool
1963gc_object_moved_p(rb_objspace_t *objspace, VALUE obj)
1964{
1965
1966 bool ret;
1967 asan_unpoisoning_object(obj) {
1968 ret = BUILTIN_TYPE(obj) == T_MOVED;
1969 }
1970 return ret;
1971}
1972
1973static inline int
1974RVALUE_OLD_P(rb_objspace_t *objspace, VALUE obj)
1975{
1976 GC_ASSERT(!RB_SPECIAL_CONST_P(obj));
1977 check_rvalue_consistency(objspace, obj);
1978 // Because this will only ever be called on GC controlled objects,
1979 // we can use the faster _RAW function here
1980 return RB_OBJ_PROMOTED_RAW(obj);
1981}
1982
1983static inline void
1984RVALUE_PAGE_OLD_UNCOLLECTIBLE_SET(rb_objspace_t *objspace, struct heap_page *page, VALUE obj)
1985{
1986 MARK_IN_BITMAP(&page->uncollectible_bits[0], obj);
1987 /* Count a promotion in the object's own objspace: a global GC ages every objspace's
1988 * slots from the driver, and counting them there would skew the other objspaces'
1989 * old_objects and with it their major GC frequency. */
1990 page->objspace->rgengc.old_objects++;
1991
1992#if RGENGC_PROFILE >= 2
1993 objspace->profile.total_promoted_count++;
1994 objspace->profile.promoted_types[BUILTIN_TYPE(obj)]++;
1995#endif
1996}
1997
1998static inline void
1999RVALUE_OLD_UNCOLLECTIBLE_SET(rb_objspace_t *objspace, VALUE obj)
2000{
2001 RB_DEBUG_COUNTER_INC(obj_promote);
2002 RVALUE_PAGE_OLD_UNCOLLECTIBLE_SET(objspace, GET_HEAP_PAGE(obj), obj);
2003}
2004
2005/* set age to age+1 */
2006static inline void
2007RVALUE_AGE_INC(rb_objspace_t *objspace, VALUE obj)
2008{
2009 int age = RVALUE_AGE_GET((VALUE)obj);
2010
2011 if (RGENGC_CHECK_MODE && age == RVALUE_OLD_AGE) {
2012 rb_bug("RVALUE_AGE_INC: can not increment age of OLD object %s.", rb_obj_info(obj));
2013 }
2014
2015 age++;
2016 RVALUE_AGE_SET(obj, age);
2017
2018 if (age == RVALUE_OLD_AGE) {
2019 RVALUE_OLD_UNCOLLECTIBLE_SET(objspace, obj);
2020 }
2021
2022 check_rvalue_consistency(objspace, obj);
2023}
2024
2025static inline void
2026RVALUE_AGE_SET_CANDIDATE(rb_objspace_t *objspace, VALUE obj)
2027{
2028 check_rvalue_consistency(objspace, obj);
2029 GC_ASSERT(!RVALUE_OLD_P(objspace, obj));
2030 RVALUE_AGE_SET(obj, RVALUE_OLD_AGE - 1);
2031 check_rvalue_consistency(objspace, obj);
2032}
2033
2034static inline void
2035RVALUE_AGE_RESET(VALUE obj)
2036{
2037 RVALUE_AGE_SET(obj, 0);
2038}
2039
2040static inline void
2041RVALUE_DEMOTE(rb_objspace_t *objspace, VALUE obj)
2042{
2043 check_rvalue_consistency(objspace, obj);
2044 GC_ASSERT(RVALUE_OLD_P(objspace, obj));
2045
2046 if (!is_incremental_marking(objspace) && RVALUE_REMEMBERED(objspace, obj)) {
2047 struct heap_page *page = GET_HEAP_PAGE(obj);
2048 _CLEAR_IN_BITMAP(page->remembered_bits, page, obj);
2049 }
2050
2051 CLEAR_IN_BITMAP(GET_HEAP_UNCOLLECTIBLE_BITS(obj), obj);
2052 RVALUE_AGE_RESET(obj);
2053
2054 if (RVALUE_MARKED(objspace, obj)) {
2055 /* symmetric with RVALUE_PAGE_OLD_UNCOLLECTIBLE_SET */
2056 GET_HEAP_PAGE(obj)->objspace->rgengc.old_objects--;
2057 }
2058
2059 check_rvalue_consistency(objspace, obj);
2060}
2061
2062static inline int
2063RVALUE_BLACK_P(rb_objspace_t *objspace, VALUE obj)
2064{
2065 return RVALUE_MARKED(objspace, obj) && !RVALUE_MARKING(objspace, obj);
2066}
2067
2068static inline int
2069RVALUE_WHITE_P(rb_objspace_t *objspace, VALUE obj)
2070{
2071 return !RVALUE_MARKED(objspace, obj);
2072}
2073
2074bool
2075rb_gc_impl_user_gc_disabled_set(void *objspace_ptr, bool disable)
2076{
2077 rb_objspace_t *objspace = objspace_ptr;
2078 const bool was = objspace->flags.user_gc_disabled;
2079 objspace->flags.user_gc_disabled = disable;
2080 return was;
2081}
2082
2083bool
2084rb_gc_impl_user_gc_disabled_p(void *objspace_ptr)
2085{
2086 rb_objspace_t *objspace = objspace_ptr;
2087 return objspace->flags.user_gc_disabled;
2088}
2089
2090bool
2091rb_gc_impl_gc_enabled_p(void *objspace_ptr)
2092{
2093 rb_objspace_t *objspace = objspace_ptr;
2094 return !dont_gc_val();
2095}
2096
2097void
2098rb_gc_impl_gc_enable(void *objspace_ptr)
2099{
2100 rb_objspace_t *objspace = objspace_ptr;
2101
2102 dont_gc_off();
2103}
2104
2105void
2106rb_gc_impl_gc_disable(void *objspace_ptr, bool finish_current_gc)
2107{
2108 rb_objspace_t *objspace = objspace_ptr;
2109
2110 if (finish_current_gc) {
2111 gc_rest(objspace);
2112 }
2113
2114 dont_gc_on();
2115}
2116
2117/* Finish an incremental mark or lazy sweep in progress without changing the enabled
2118 * state. gc.c uses it to settle the only objspace just before the process goes
2119 * multi-objspace. */
2120void
2121rb_gc_impl_gc_rest(void *objspace_ptr)
2122{
2123 gc_rest(objspace_ptr);
2124}
2125
2126/*
2127 --------------------------- ObjectSpace -----------------------------
2128*/
2129
2130static inline void *
2131calloc1(size_t n)
2132{
2133 return calloc(1, n);
2134}
2135
2136void
2137rb_gc_impl_set_event_hook(void *objspace_ptr, const rb_event_flag_t event)
2138{
2139 rb_objspace_t *objspace = objspace_ptr;
2140 /* FREEOBJ is main-objspace only (rb_objspace_set_event_hook masks it elsewhere). */
2141 GC_ASSERT(!(event & RUBY_INTERNAL_EVENT_FREEOBJ) ||
2142 objspace == global_objspace->main_objspace);
2143 objspace->hook_events = event & RUBY_INTERNAL_EVENT_OBJSPACE_MASK;
2144}
2145
2146unsigned long long
2147rb_gc_impl_get_total_time(void *objspace_ptr)
2148{
2149 rb_objspace_t *objspace = objspace_ptr;
2150
2151 unsigned long long marking_time = objspace->profile.marking_time_ns;
2152 unsigned long long sweeping_time = objspace->profile.sweeping_time_ns;
2153
2154 return marking_time + sweeping_time;
2155}
2156
2157void
2158rb_gc_impl_set_measure_total_time(void *objspace_ptr, VALUE flag)
2159{
2160 rb_objspace_t *objspace = objspace_ptr;
2161
2162 objspace->flags.measure_gc = RTEST(flag) ? TRUE : FALSE;
2163}
2164
2165bool
2166rb_gc_impl_get_measure_total_time(void *objspace_ptr)
2167{
2168 rb_objspace_t *objspace = objspace_ptr;
2169
2170 return objspace->flags.measure_gc;
2171}
2172
2173static void
2174gc_process_stat_capture(const rb_objspace_t *objspace,
2175 struct gc_process_stat_snapshot *out)
2176{
2177 out->minor_gc_count = objspace->profile.minor_gc_count;
2178 out->major_gc_count = objspace->profile.major_gc_count;
2179 out->global_gc_invocation_count = objspace->profile.global_gc_invocation_count;
2180 out->marking_time_ns = objspace->profile.marking_time_ns;
2181 out->sweeping_time_ns = objspace->profile.sweeping_time_ns;
2182}
2183
2184static void
2185gc_process_stat_publish(rb_objspace_t *objspace)
2186{
2187 struct gc_process_stat_snapshot snap;
2188 GC_ASSERT(objspace->profile.count == objspace->profile.minor_gc_count +
2189 objspace->profile.major_gc_count + objspace->profile.global_gc_count);
2190 gc_process_stat_capture(objspace, &snap);
2191 rb_native_mutex_lock(&objspace->process_stat.lock);
2192 objspace->process_stat.published = snap;
2193 rb_native_mutex_unlock(&objspace->process_stat.lock);
2194}
2195
2196static void
2197gc_process_stat_add(struct gc_process_stat_total *dst,
2198 const struct gc_process_stat_snapshot *src)
2199{
2200 dst->minor_gc_count += src->minor_gc_count;
2201 dst->major_gc_count += src->major_gc_count;
2202 dst->global_gc_invocation_count += src->global_gc_invocation_count;
2203 dst->marking_time_ns += src->marking_time_ns;
2204 dst->sweeping_time_ns += src->sweeping_time_ns;
2205}
2206
2207/* garbage objects will be collected soon. */
2208bool
2209rb_gc_impl_garbage_object_p(void *objspace_ptr, VALUE ptr)
2210{
2211 rb_objspace_t *objspace = objspace_ptr;
2212
2213 /* A foreign object is a live leaf: reading its type or mark bit would race the
2214 * owner's local GC, so outside a global GC's barrier never report it as garbage.
2215 * The fstring/symbol weak-set lookups do reach across objspaces, but those objects
2216 * are born shareable and only a stop-the-world global GC collects them, so "not
2217 * garbage" is correct. */
2218 if (gc_skip_foreign_object_p(objspace, ptr)) {
2219 return false;
2220 }
2221
2222 /* Asking whether a freed (T_NONE), moved (T_MOVED), or finalized (T_ZOMBIE)
2223 * object is garbage gives an unreliable answer: the slot may since have been
2224 * reused for an unrelated object. A reference to one of these is stale and a
2225 * bug in the caller. */
2226 asan_unpoisoning_object(ptr) {
2227 GC_ASSERT(BUILTIN_TYPE(ptr) != T_NONE);
2228 GC_ASSERT(BUILTIN_TYPE(ptr) != T_MOVED);
2229 GC_ASSERT(BUILTIN_TYPE(ptr) != T_ZOMBIE);
2230 }
2231
2232 return is_lazy_sweeping(objspace) && GET_HEAP_PAGE(ptr)->flags.before_sweep &&
2233 !RVALUE_MARKED(objspace, ptr);
2234}
2235
2236struct rb_gc_vm_context *
2237rb_gc_impl_get_vm_context(void *objspace_ptr)
2238{
2239 rb_objspace_t *objspace = objspace_ptr;
2240
2241 return &objspace->vm_context;
2242}
2243
2244static void free_stack_chunks(mark_stack_t *);
2245static void mark_stack_free_cache(mark_stack_t *);
2246static void heap_page_free(rb_objspace_t *objspace, struct heap_page *page);
2247
2248static inline void
2249gc_check_obj_in_page(struct heap_page *page, VALUE obj)
2250{
2251 if (RGENGC_CHECK_MODE &&
2252 /* obj should belong to page */
2253 !(page->start <= (uintptr_t)obj &&
2254 (uintptr_t)obj < ((uintptr_t)page->start + (page->total_slots * page->slot_size)) &&
2255 obj % sizeof(VALUE) == 0)) {
2256 rb_bug("gc_check_obj_in_page: %p is not rvalue.", (void *)obj);
2257 }
2258}
2259
2260static inline void
2261heap_page_add_free_region(rb_objspace_t *objspace, struct heap_page *page, VALUE obj)
2262{
2263 rb_asan_unpoison_object(obj, false);
2264
2265 // Should have already been reset
2266 GC_ASSERT(RVALUE_AGE_GET(obj) == 0);
2267
2268 gc_check_obj_in_page(page, obj);
2269
2270 asan_unlock_freelist(page);
2271
2272 /* Keep a freed slot from carrying its old shareable and shref bits into the next
2273 * object born there. */
2274 CLEAR_IN_BITMAP(GET_HEAP_SHAREABLE_BITS(obj), obj);
2275 CLEAR_IN_BITMAP(GET_HEAP_SHREF_BITS(obj), obj);
2276
2277 struct free_region *region = (struct free_region *)obj;
2278 region->flags = 0;
2279 region->end = (uintptr_t)obj + page->slot_size;
2280 region->next = page->free_region;
2281 page->free_region = region;
2282
2283 asan_lock_freelist(page);
2284
2285 rb_asan_poison_object(obj);
2286 gc_report(3, objspace, "heap_page_add_free_region: %p\n", (void *)obj);
2287}
2288
2289/* The initial size is per objspace, so a Ractor's own gets a smaller one than
2290 * main's rather than paying main's again. */
2291static inline size_t
2292objspace_heap_init_bytes(const rb_objspace_t *objspace)
2293{
2294 return objspace == global_objspace->main_objspace
2295 ? gc_params.heap_init_bytes : gc_params.ractor_heap_init_bytes;
2296}
2297
2298static void
2299heap_allocatable_bytes_expand(rb_objspace_t *objspace,
2300 rb_heap_t *heap, size_t free_slots, size_t total_slots, size_t slot_size)
2301{
2302 double goal_ratio = gc_params.heap_free_slots_goal_ratio;
2303 size_t target_total_slots;
2304
2305 if (goal_ratio == 0.0) {
2306 target_total_slots = (size_t)(total_slots * gc_params.growth_factor);
2307 }
2308 else if (total_slots == 0) {
2309 target_total_slots = objspace_heap_init_bytes(objspace) / slot_size;
2310 }
2311 else {
2312 /* Find `f' where free_slots = f * total_slots * goal_ratio
2313 * => f = (total_slots - free_slots) / ((1 - goal_ratio) * total_slots)
2314 */
2315 double f = (double)(total_slots - free_slots) / ((1 - goal_ratio) * total_slots);
2316
2317 if (f > gc_params.growth_factor) f = gc_params.growth_factor;
2318 if (f < 1.0) f = 1.1;
2319
2320 target_total_slots = (size_t)(f * total_slots);
2321
2322 if (0) {
2323 fprintf(stderr,
2324 "free_slots(%8"PRIuSIZE")/total_slots(%8"PRIuSIZE")=%1.2f,"
2325 " G(%1.2f), f(%1.2f),"
2326 " total_slots(%8"PRIuSIZE") => target_total_slots(%8"PRIuSIZE")\n",
2327 free_slots, total_slots, free_slots/(double)total_slots,
2328 goal_ratio, f, total_slots, target_total_slots);
2329 }
2330 }
2331
2332 if (gc_params.growth_max_bytes > 0) {
2333 size_t max_total_slots = total_slots + gc_params.growth_max_bytes / slot_size;
2334 if (target_total_slots > max_total_slots) target_total_slots = max_total_slots;
2335 }
2336
2337 size_t extend_slot_count = target_total_slots - total_slots;
2338 /* Extend by at least 1 page. */
2339 if (extend_slot_count == 0) extend_slot_count = 1;
2340
2341 objspace->heap_pages.allocatable_bytes += extend_slot_count * slot_size;
2342}
2343
2344static inline void
2345heap_add_freepage(rb_heap_t *heap, struct heap_page *page)
2346{
2347 asan_unlock_freelist(page);
2348 GC_ASSERT(page->free_slots != 0);
2349 GC_ASSERT(page->free_region != NULL);
2350
2351 page->free_next = heap->free_pages;
2352 heap->free_pages = page;
2353
2354 RUBY_DEBUG_LOG("page:%p free_region:%p", (void *)page, (void *)page->free_region);
2355
2356 asan_lock_freelist(page);
2357}
2358
2359static inline void
2360heap_add_poolpage(rb_objspace_t *objspace, rb_heap_t *heap, struct heap_page *page)
2361{
2362 asan_unlock_freelist(page);
2363 GC_ASSERT(page->free_slots != 0);
2364 GC_ASSERT(page->free_region != NULL);
2365
2366 page->free_next = heap->pooled_pages;
2367 heap->pooled_pages = page;
2368 objspace->rincgc.pooled_slots += page->free_slots;
2369
2370 asan_lock_freelist(page);
2371}
2372
2373static void
2374heap_unlink_page(rb_objspace_t *objspace, rb_heap_t *heap, struct heap_page *page)
2375{
2376 ccan_list_del(&page->page_node);
2377 heap->total_pages--;
2378 heap->total_slots -= page->total_slots;
2379}
2380
2381/* Detach a page with no living objects from its heap and park it on the objspace's
2382 * empty pages, from where it is reused or released to the page pool. The caller has
2383 * already taken it off the heap's free_pages chain, if it was on it. */
2384static void
2385heap_page_detach_empty(rb_objspace_t *objspace, rb_heap_t *heap, struct heap_page *page)
2386{
2387 heap_unlink_page(objspace, heap, page);
2388
2389 page->start = 0;
2390 page->total_slots = 0;
2391 page->slot_size = 0;
2392 page->heap = NULL;
2393 page->free_slots = 0;
2394
2395 asan_unlock_freelist(page);
2396 page->free_region = NULL;
2397 asan_lock_freelist(page);
2398
2399 asan_poison_memory_region(page->body, HEAP_PAGE_SIZE);
2400
2401 objspace->empty_pages_count++;
2402 page->free_next = objspace->empty_pages;
2403 objspace->empty_pages = page;
2404}
2405
2406static void
2407gc_aligned_free(void *ptr, size_t size)
2408{
2409#if defined __MINGW32__
2410 __mingw_aligned_free(ptr);
2411#elif defined _WIN32
2412 _aligned_free(ptr);
2413#elif defined(HAVE_POSIX_MEMALIGN) || defined(HAVE_MEMALIGN)
2414 free(ptr);
2415#else
2416 free(((void**)ptr)[-1]);
2417#endif
2418}
2419
2420static void
2421heap_page_body_free(struct heap_page_body *page_body, struct page_arena *arena)
2422{
2423 GC_ASSERT((uintptr_t)page_body % HEAP_PAGE_ALIGN == 0);
2424
2425 page_pool_release(page_body, arena);
2426}
2427
2428#ifdef PAGE_POOL_LOCK_ERRORCHECK
2429# define ASSERT_PAGE_POOL_LOCKED(g) GC_ASSERT(pthread_mutex_lock(&(g)->page_pool.lock) == EDEADLK)
2430#else
2431# define ASSERT_PAGE_POOL_LOCKED(g) ((void)0)
2432#endif
2433
2434/* Insert into page_index. Writers serialize on page_pool.lock; lomem and himem are a
2435 * monotonically growing over-approximation used for a quick reject. */
2436static void
2437global_page_index_insert(struct heap_page *page)
2438{
2439 rb_global_objspace_t *g = global_objspace;
2440 uintptr_t body = (uintptr_t)page->body;
2441
2442 rb_native_mutex_lock(&g->page_pool.lock);
2443 if (g->page_index.n_pages == g->page_index.capa) {
2444 size_t new_capa = g->page_index.capa ? g->page_index.capa * 2 : 128;
2445 struct heap_page **grown = realloc(g->page_index.pages, new_capa * sizeof(*grown));
2446 if (grown == NULL) rb_bug("global_page_index_insert: realloc failed");
2447 g->page_index.pages = grown;
2448 g->page_index.capa = new_capa;
2449 }
2450 size_t lo = 0, hi = g->page_index.n_pages;
2451 while (lo < hi) {
2452 size_t mid = (lo + hi) / 2;
2453 if ((uintptr_t)g->page_index.pages[mid]->body < body) lo = mid + 1;
2454 else hi = mid;
2455 }
2456 memmove(&g->page_index.pages[lo + 1], &g->page_index.pages[lo],
2457 (g->page_index.n_pages - lo) * sizeof(struct heap_page *));
2458 g->page_index.pages[lo] = page;
2459 g->page_index.n_pages++;
2460
2461 uintptr_t start = body + sizeof(struct heap_page_header);
2462 uintptr_t end = body + HEAP_PAGE_SIZE;
2463 if (g->page_index.lomem == 0 || g->page_index.lomem > start) g->page_index.lomem = start;
2464 if (g->page_index.himem < end) g->page_index.himem = end;
2465 rb_native_mutex_unlock(&g->page_pool.lock);
2466}
2467
2468static void
2469global_page_index_remove_locked(const struct heap_page *page)
2470{
2471 rb_global_objspace_t *g = global_objspace;
2472 uintptr_t body = (uintptr_t)page->body;
2473
2474 ASSERT_PAGE_POOL_LOCKED(g);
2475
2476 size_t lo = 0, hi = g->page_index.n_pages;
2477 while (lo < hi) {
2478 size_t mid = (lo + hi) / 2;
2479 if ((uintptr_t)g->page_index.pages[mid]->body < body) lo = mid + 1;
2480 else hi = mid;
2481 }
2482 GC_ASSERT(lo < g->page_index.n_pages && g->page_index.pages[lo] == page);
2483 memmove(&g->page_index.pages[lo], &g->page_index.pages[lo + 1],
2484 (g->page_index.n_pages - lo - 1) * sizeof(struct heap_page *));
2485 g->page_index.n_pages--;
2486}
2487
2488static void
2489global_page_index_remove(const struct heap_page *page)
2490{
2491 rb_global_objspace_t *g = global_objspace;
2492
2493 rb_native_mutex_lock(&g->page_pool.lock);
2494 global_page_index_remove_locked(page);
2495 rb_native_mutex_unlock(&g->page_pool.lock);
2496}
2497
2498static void
2499heap_page_free(rb_objspace_t *objspace, struct heap_page *page)
2500{
2501 global_page_index_remove(page);
2502 objspace->heap_pages.freed_pages++;
2503 heap_page_body_free(page->body, page->arena);
2504 free(page);
2505}
2506
2507static void
2508heap_pages_free_batch(rb_objspace_t *objspace, struct heap_page *pages)
2509{
2510 rb_global_objspace_t *g = global_objspace;
2511
2512 rb_native_mutex_lock(&g->page_pool.lock);
2513 for (struct heap_page *page = pages; page != NULL; page = page->free_next) {
2514 global_page_index_remove_locked(page);
2515 if (HEAP_PAGE_ALLOC_USE_MMAP) {
2516#ifdef HAVE_MMAP
2517 page_pool_release_locked(page->body, page->arena);
2518#endif
2519 }
2520 }
2521 rb_native_mutex_unlock(&g->page_pool.lock);
2522
2523 if (!HEAP_PAGE_ALLOC_USE_MMAP) {
2524 /* gc_aligned_free does not need the pool lock. */
2525 for (struct heap_page *page = pages; page != NULL; page = page->free_next) {
2526 heap_page_body_free(page->body, page->arena);
2527 }
2528 }
2529
2530 while (pages != NULL) {
2531 struct heap_page *next = pages->free_next;
2532 objspace->heap_pages.freed_pages++;
2533 free(pages);
2534 pages = next;
2535 }
2536}
2537
2538static void
2539heap_pages_free_unused_pages(rb_objspace_t *objspace)
2540{
2541 if (objspace->empty_pages != NULL && heap_pages_freeable_pages > 0) {
2542 GC_ASSERT(objspace->empty_pages_count > 0);
2543 objspace->empty_pages = NULL;
2544 objspace->empty_pages_count = 0;
2545
2546 size_t i, j;
2547 struct heap_page *to_free = NULL;
2548 for (i = j = 0; i < rb_darray_size(objspace->heap_pages.sorted); i++) {
2549 struct heap_page *page = rb_darray_get(objspace->heap_pages.sorted, i);
2550
2551 if (heap_page_in_global_empty_pages_pool(objspace, page) && heap_pages_freeable_pages > 0) {
2552 page->free_next = to_free;
2553 to_free = page;
2554 heap_pages_freeable_pages--;
2555 }
2556 else {
2557 if (heap_page_in_global_empty_pages_pool(objspace, page)) {
2558 page->free_next = objspace->empty_pages;
2559 objspace->empty_pages = page;
2560 objspace->empty_pages_count++;
2561 }
2562
2563 if (i != j) {
2564 rb_darray_set(objspace->heap_pages.sorted, j, page);
2565 }
2566 j++;
2567 }
2568 }
2569
2570 rb_darray_pop(objspace->heap_pages.sorted, i - j);
2571 GC_ASSERT(rb_darray_size(objspace->heap_pages.sorted) == j);
2572
2573 /* A retire GC can free every page, so an empty objspace is legitimate. */
2574 if (j > 0) {
2575 struct heap_page *hipage = rb_darray_get(objspace->heap_pages.sorted, rb_darray_size(objspace->heap_pages.sorted) - 1);
2576 uintptr_t himem = (uintptr_t)hipage->body + HEAP_PAGE_SIZE;
2577 GC_ASSERT(himem <= heap_pages_himem);
2578 heap_pages_himem = himem;
2579
2580 struct heap_page *lopage = rb_darray_get(objspace->heap_pages.sorted, 0);
2581 uintptr_t lomem = (uintptr_t)lopage->body + sizeof(struct heap_page_header);
2582 GC_ASSERT(lomem >= heap_pages_lomem);
2583 heap_pages_lomem = lomem;
2584 }
2585 else {
2586 heap_pages_lomem = 0;
2587 heap_pages_himem = 0;
2588 }
2589
2590 heap_pages_free_batch(objspace, to_free);
2591 }
2592}
2593
2594static void *
2595gc_aligned_malloc(size_t alignment, size_t size)
2596{
2597 /* alignment must be a power of 2 */
2598 GC_ASSERT(((alignment - 1) & alignment) == 0);
2599 GC_ASSERT(alignment % sizeof(void*) == 0);
2600
2601 void *res;
2602
2603#if defined __MINGW32__
2604 res = __mingw_aligned_malloc(size, alignment);
2605#elif defined _WIN32
2606 res = _aligned_malloc(size, alignment);
2607#elif defined(HAVE_POSIX_MEMALIGN)
2608 if (posix_memalign(&res, alignment, size) != 0) {
2609 return NULL;
2610 }
2611#elif defined(HAVE_MEMALIGN)
2612 res = memalign(alignment, size);
2613#else
2614 char* aligned;
2615 res = malloc(alignment + size + sizeof(void*));
2616 aligned = (char*)res + alignment + sizeof(void*);
2617 aligned -= ((VALUE)aligned & (alignment - 1));
2618 ((void**)aligned)[-1] = res;
2619 res = (void*)aligned;
2620#endif
2621
2622 GC_ASSERT((uintptr_t)res % alignment == 0);
2623
2624 return res;
2625}
2626
2627/* The page pool (global_objspace->page_pool): heap page bodies are carved out of large
2628 * arenas and reused through the pool. Free bodies are split into a small global hot
2629 * list (≤ PAGE_POOL_HOT_MAX, never madvise'd) and per-arena cold freelists (eligible for
2630 * OS release — see page_pool_reclaim). Both lists use an in-body link at offset 0. */
2631
2632#define PAGE_POOL_ARENA_SIZE (HEAP_PAGE_SIZE * 32) /* 2MiB with 64KiB pages */
2633#define PAGE_POOL_ARENA_BODIES (PAGE_POOL_ARENA_SIZE / HEAP_PAGE_SIZE) /* 32 */
2634#define PAGE_POOL_HOT_MAX 0 /* disabled — empty_pages is the retention buffer */
2635#define PAGE_POOL_ARENA_KEEP_HALF (PAGE_POOL_ARENA_BODIES / 2) /* 16 */
2636
2637/* Steal bit 0 of the in-body link word: set iff the body has been madvise'd (cold). */
2638#define PAGE_POOL_ADVISED_BIT ((uintptr_t)1)
2639
2640/* While a body is free, the arena back-pointer is stored at offset sizeof(header) — one
2641 * word past the link, inside the spared first OS page. PAGE_POOL_SCRATCH_SIZE covers
2642 * both the link (offset 0) and the tag for ASAN unpoison. */
2643#define PAGE_POOL_BODY_ARENA(body) \
2644 (*(struct page_arena **)((char *)(body) + sizeof(struct heap_page_header)))
2645#define PAGE_POOL_SCRATCH_SIZE (sizeof(struct heap_page_header) + sizeof(void *))
2646
2647#ifdef HAVE_MMAP
2648/* mmap a new arena to carve from. Called with the pool lock held, at which point the
2649 * previous arena is always fully carved. */
2650static bool
2651page_pool_add_arena(rb_global_objspace_t *g)
2652{
2653 GC_ASSERT(HEAP_PAGE_ALIGN % sysconf(_SC_PAGE_SIZE) == 0);
2654
2655 size_t mmap_size = PAGE_POOL_ARENA_SIZE + HEAP_PAGE_ALIGN;
2656 char *ptr = mmap(NULL, mmap_size,
2657 PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
2658 if (ptr == MAP_FAILED) {
2659 return false;
2660 }
2661
2662 // If we are building `default.c` as part of the ruby executable, we
2663 // may just call `ruby_annotate_mmap`. But if we are building
2664 // `default.c` as a shared library, we will not have access to private
2665 // symbols, and we have to either call prctl directly or make our own
2666 // wrapper.
2667#if defined(HAVE_SYS_PRCTL_H) && defined(PR_SET_VMA) && defined(PR_SET_VMA_ANON_NAME)
2668 prctl(PR_SET_VMA, PR_SET_VMA_ANON_NAME, ptr, mmap_size, "Ruby:GC:default:page_pool_arena");
2669 errno = 0;
2670#endif
2671
2672 /* Trim the unaligned head and tail so the usable area is HEAP_PAGE_ALIGN aligned. */
2673 char *aligned = ptr + HEAP_PAGE_ALIGN;
2674 aligned -= ((uintptr_t)aligned & (HEAP_PAGE_ALIGN - 1));
2675 GC_ASSERT(aligned > ptr);
2676 GC_ASSERT(aligned <= ptr + HEAP_PAGE_ALIGN);
2677
2678 size_t start_out_of_range_size = aligned - ptr;
2679 GC_ASSERT(start_out_of_range_size % sysconf(_SC_PAGE_SIZE) == 0);
2680 if (start_out_of_range_size > 0) {
2681 if (munmap(ptr, start_out_of_range_size)) {
2682 rb_bug("page_pool_add_arena: munmap failed for start");
2683 }
2684 }
2685
2686 size_t end_out_of_range_size = HEAP_PAGE_ALIGN - start_out_of_range_size;
2687 GC_ASSERT(end_out_of_range_size % sysconf(_SC_PAGE_SIZE) == 0);
2688 if (end_out_of_range_size > 0) {
2689 if (munmap(aligned + PAGE_POOL_ARENA_SIZE, end_out_of_range_size)) {
2690 rb_bug("page_pool_add_arena: munmap failed for end");
2691 }
2692 }
2693
2694 struct page_arena *arena = calloc1(sizeof(struct page_arena));
2695 if (arena == NULL) {
2696 if (munmap(aligned, PAGE_POOL_ARENA_SIZE)) {
2697 rb_bug("page_pool_add_arena: munmap failed for arena");
2698 }
2699 return false;
2700 }
2701 arena->start = aligned;
2702 arena->size = PAGE_POOL_ARENA_SIZE;
2703 arena->cold_freelist = NULL;
2704 arena->free_count = 0;
2705 arena->cold_count = 0;
2706 arena->next = g->page_pool.arenas;
2707 g->page_pool.arenas = arena;
2708 g->page_pool.arena_count++;
2709 g->page_pool.arena_current = arena;
2710
2711 g->page_pool.arena_cursor = aligned;
2712 g->page_pool.arena_end = aligned + PAGE_POOL_ARENA_SIZE;
2713
2714 return true;
2715}
2716#endif
2717
2718static struct heap_page_body *
2719page_pool_acquire(struct page_arena **arena_out)
2720{
2721 struct heap_page_body *body = NULL;
2722
2723 if (HEAP_PAGE_ALLOC_USE_MMAP) {
2724#ifdef HAVE_MMAP
2725 bool need_reuse = false;
2726 rb_global_objspace_t *g = global_objspace;
2727
2728 rb_native_mutex_lock(&g->page_pool.lock);
2729 if (g->page_pool.hot_list != NULL) {
2730 body = g->page_pool.hot_list;
2731 asan_unpoison_memory_region(body, PAGE_POOL_SCRATCH_SIZE, false);
2732 uintptr_t link = *(uintptr_t *)body;
2733 g->page_pool.hot_list = (struct heap_page_body *)(link & ~PAGE_POOL_ADVISED_BIT);
2734 g->page_pool.hot_count--;
2735 struct page_arena *arena = PAGE_POOL_BODY_ARENA(body);
2736 arena->free_count--;
2737 *arena_out = arena;
2738 }
2739 else {
2740 // find cold page body (madvised reusable)
2741 for (struct page_arena *a = g->page_pool.arenas; a; a = a->next) {
2742 if (a->cold_count > 0) {
2743 body = a->cold_freelist;
2744 asan_unpoison_memory_region(body, PAGE_POOL_SCRATCH_SIZE, false);
2745 uintptr_t link = *(uintptr_t *)body;
2746 a->cold_freelist = (struct heap_page_body *)(link & ~PAGE_POOL_ADVISED_BIT);
2747 a->cold_count--;
2748 a->free_count--;
2749 *arena_out = a;
2750 need_reuse = (link & PAGE_POOL_ADVISED_BIT) != 0;
2751 if (need_reuse) g->page_pool.advised_count--;
2752 break;
2753 }
2754 }
2755 if (body == NULL &&
2756 (g->page_pool.arena_cursor != g->page_pool.arena_end ||
2757 page_pool_add_arena(g))) {
2758 GC_ASSERT(g->page_pool.arena_cursor + HEAP_PAGE_SIZE <= g->page_pool.arena_end);
2759 body = (struct heap_page_body *)g->page_pool.arena_cursor;
2760 g->page_pool.arena_cursor += HEAP_PAGE_SIZE;
2761 *arena_out = g->page_pool.arena_current;
2762 }
2763 }
2764 rb_native_mutex_unlock(&g->page_pool.lock);
2765
2766 if (body != NULL) {
2767 if (need_reuse) {
2768 rb_vm_map_reuse((char *)body + g->page_pool.os_page_size,
2769 HEAP_PAGE_SIZE - g->page_pool.os_page_size);
2770 }
2771 asan_unpoison_memory_region(body, HEAP_PAGE_SIZE, false);
2772 }
2773#endif
2774 }
2775 else {
2776 body = gc_aligned_malloc(HEAP_PAGE_ALIGN, HEAP_PAGE_SIZE);
2777 *arena_out = NULL;
2778 }
2779
2780 return body;
2781}
2782
2783#ifdef HAVE_MMAP
2784static void
2785page_pool_release_locked(struct heap_page_body *body, struct page_arena *arena)
2786{
2787 rb_global_objspace_t *g = global_objspace;
2788
2789 ASSERT_PAGE_POOL_LOCKED(g);
2790
2791 /* A body in the empty-pages pool stays fully poisoned (see gc_sweep_page), so
2792 * unpoison the scratch area (link + arena tag) before writing. */
2793 asan_unpoison_memory_region(body, PAGE_POOL_SCRATCH_SIZE, false);
2794 arena->free_count++;
2795 PAGE_POOL_BODY_ARENA(body) = arena;
2796 if (g->page_pool.hot_count < PAGE_POOL_HOT_MAX) {
2797 *(uintptr_t *)body = (uintptr_t)g->page_pool.hot_list;
2798 g->page_pool.hot_list = body;
2799 g->page_pool.hot_count++;
2800 }
2801 else {
2802 *(uintptr_t *)body = (uintptr_t)arena->cold_freelist;
2803 arena->cold_freelist = body;
2804 arena->cold_count++;
2805 }
2806 asan_poison_memory_region(body, HEAP_PAGE_SIZE);
2807}
2808#endif
2809
2810static void
2811page_pool_release(struct heap_page_body *body, struct page_arena *arena)
2812{
2813 if (HEAP_PAGE_ALLOC_USE_MMAP) {
2814#ifdef HAVE_MMAP
2815 rb_global_objspace_t *g = global_objspace;
2816
2817 rb_native_mutex_lock(&g->page_pool.lock);
2818 page_pool_release_locked(body, arena);
2819 rb_native_mutex_unlock(&g->page_pool.lock);
2820#endif
2821 }
2822 else {
2823 gc_aligned_free(body, HEAP_PAGE_SIZE);
2824 }
2825}
2826
2827/* Allow the OS to reclaim pool memory. Runs only at major GC in single-objspace mode
2828 * (see gc_sweep_finish).
2829 *
2830 * Step A: madvise cold bodies, sparing the first OS page (which holds the in-body
2831 * freelist link and arena tag).
2832 *
2833 * Step B: munmap arenas whose 32 bodies are all free, keeping one extra empty
2834 * arena as a retention buffer when the remaining free pool is < half an arena. */
2835static void
2836page_pool_reclaim(rb_global_objspace_t *g)
2837{
2838 if (!HEAP_PAGE_ALLOC_USE_MMAP) return;
2839#ifdef HAVE_MMAP
2840 size_t os_page_size = g->page_pool.os_page_size;
2841
2842 rb_native_mutex_lock(&g->page_pool.lock);
2843
2844 /* Advising spares the first OS page of a body (it holds the in-body freelist link
2845 * and the arena tag), so it needs sub-page granularity: when the OS page size is
2846 * >= HEAP_PAGE_SIZE (e.g. 64KiB pages on aarch64) no body is ever advised, and
2847 * advised_count must not be adjusted anywhere either. */
2848 const bool can_advise = os_page_size < HEAP_PAGE_SIZE;
2849
2850 /* Step A — advise cold bodies (immediate release: drop RSS now if the platform allows). */
2851 if (can_advise) {
2852 for (struct page_arena *a = g->page_pool.arenas; a; a = a->next) {
2853 for (struct heap_page_body *body = a->cold_freelist; body; ) {
2854 asan_unpoison_memory_region(body, PAGE_POOL_SCRATCH_SIZE, false);
2855 uintptr_t link = *(uintptr_t *)body;
2856 struct heap_page_body *next =
2857 (struct heap_page_body *)(link & ~PAGE_POOL_ADVISED_BIT);
2858 if (!(link & PAGE_POOL_ADVISED_BIT)) {
2859 rb_vm_map_reusable_immediate((char *)body + os_page_size,
2860 HEAP_PAGE_SIZE - os_page_size, 0);
2861 *(uintptr_t *)body = link | PAGE_POOL_ADVISED_BIT;
2862 g->page_pool.advised_count++;
2863 }
2864 asan_poison_memory_region(body, PAGE_POOL_SCRATCH_SIZE);
2865 body = next;
2866 }
2867 }
2868 }
2869
2870 /* Step B — munmap fully-free arenas (with retention buffer).
2871 *
2872 * total_free = Σ free_count; free_count already includes hot-list bodies
2873 * (page_pool_release increments it unconditionally), so no separate hot_count.
2874 * An arena is eligible when all 32 of its bodies are free AND none sit on
2875 * the hot list (≤5 entries, pre-scanned). Keep one extra empty arena when
2876 * the rest of the free pool is < half an arena, to avoid thrash. */
2877 int total_free = 0;
2878 for (struct page_arena *a = g->page_pool.arenas; a; a = a->next) {
2879 total_free += a->free_count;
2880 }
2881
2882 struct page_arena *hot_arenas[PAGE_POOL_HOT_MAX ? PAGE_POOL_HOT_MAX : 1];
2883 int n_hot_arenas = 0;
2884 /* Collect arenas that have a hot body (≤ PAGE_POOL_HOT_MAX entries). */
2885 for (struct heap_page_body *body = g->page_pool.hot_list; body; ) {
2886 asan_unpoison_memory_region(body, PAGE_POOL_SCRATCH_SIZE, false);
2887 uintptr_t link = *(uintptr_t *)body;
2888 struct heap_page_body *next =
2889 (struct heap_page_body *)(link & ~PAGE_POOL_ADVISED_BIT);
2890 struct page_arena *arena = PAGE_POOL_BODY_ARENA(body);
2891 bool found = false;
2892 for (int i = 0; i < n_hot_arenas; i++) {
2893 if (hot_arenas[i] == arena) { found = true; break; }
2894 }
2895 if (!found && n_hot_arenas < PAGE_POOL_HOT_MAX) {
2896 hot_arenas[n_hot_arenas++] = arena;
2897 }
2898 asan_poison_memory_region(body, PAGE_POOL_SCRATCH_SIZE);
2899 body = next;
2900 }
2901
2902 bool retained_one = false;
2903 struct page_arena **pp = &g->page_pool.arenas;
2904 // munmap fully free arenas
2905 while (*pp) {
2906 struct page_arena *a = *pp;
2907 bool has_hot = false;
2908 for (int i = 0; i < n_hot_arenas; i++) {
2909 if (hot_arenas[i] == a) { has_hot = true; break; }
2910 }
2911 if (a->free_count != PAGE_POOL_ARENA_BODIES || has_hot) {
2912 pp = &a->next;
2913 continue;
2914 }
2915 GC_ASSERT(a->cold_count == PAGE_POOL_ARENA_BODIES);
2916
2917 int free_elsewhere = total_free - PAGE_POOL_ARENA_BODIES;
2918 if (free_elsewhere < PAGE_POOL_ARENA_KEEP_HALF && !retained_one) {
2919 retained_one = true;
2920 pp = &a->next;
2921 continue;
2922 }
2923
2924 *pp = a->next;
2925 if (munmap(a->start, a->size)) {
2926 rb_bug("page_pool_reclaim: munmap failed");
2927 }
2928 total_free -= PAGE_POOL_ARENA_BODIES;
2929 /* Every body of this arena is on its cold freelist, so Step A above has just
2930 * advised all of them -- but only if this platform can advise at all. */
2931 if (can_advise) {
2932 g->page_pool.advised_count -= PAGE_POOL_ARENA_BODIES;
2933 GC_ASSERT(g->page_pool.advised_count >= 0);
2934 }
2935 g->page_pool.arena_count--;
2936 g->page_pool.arenas_unmapped++;
2937 if (a == g->page_pool.arena_current) {
2938 // During next acquire, any remaining arenas that have cold bodies are used. This is guaranteed
2939 // because of the retention buffer.
2940 g->page_pool.arena_current = NULL;
2941 g->page_pool.arena_cursor = NULL;
2942 g->page_pool.arena_end = NULL;
2943 }
2944 free(a);
2945 }
2946
2947 rb_native_mutex_unlock(&g->page_pool.lock);
2948#endif
2949}
2950
2951static struct heap_page_body *
2952heap_page_body_allocate(struct page_arena **arena_out)
2953{
2954 struct heap_page_body *page_body = page_pool_acquire(arena_out);
2955
2956 GC_ASSERT(page_body == NULL || (uintptr_t)page_body % HEAP_PAGE_ALIGN == 0);
2957
2958 return page_body;
2959}
2960
2961static struct heap_page *
2962heap_page_resurrect(rb_objspace_t *objspace)
2963{
2964 struct heap_page *page = NULL;
2965 if (objspace->empty_pages == NULL) {
2966 GC_ASSERT(objspace->empty_pages_count == 0);
2967 }
2968 else {
2969 GC_ASSERT(objspace->empty_pages_count > 0);
2970 objspace->empty_pages_count--;
2971 page = objspace->empty_pages;
2972 objspace->empty_pages = page->free_next;
2973 /* Clear the flags left over from emptying the page before reusing it, or the
2974 * shareable and shref scans would keep walking an empty bitmap forever. */
2975 page->flags.has_shareable_objects = FALSE;
2976 page->flags.has_shref_objects = FALSE;
2977 }
2978
2979 return page;
2980}
2981
2982static struct heap_page *
2983heap_page_allocate(rb_objspace_t *objspace)
2984{
2985 struct page_arena *arena;
2986 struct heap_page_body *page_body = heap_page_body_allocate(&arena);
2987 if (page_body == 0) {
2988 rb_memerror();
2989 }
2990
2991 struct heap_page *page = calloc1(sizeof(struct heap_page));
2992 if (page == 0) {
2993 heap_page_body_free(page_body, arena);
2994 rb_memerror();
2995 }
2996
2997 uintptr_t start = (uintptr_t)page_body + sizeof(struct heap_page_header);
2998 uintptr_t end = (uintptr_t)page_body + HEAP_PAGE_SIZE;
2999
3000 size_t lo = 0;
3001 size_t hi = rb_darray_size(objspace->heap_pages.sorted);
3002 while (lo < hi) {
3003 struct heap_page *mid_page;
3004
3005 size_t mid = (lo + hi) / 2;
3006 mid_page = rb_darray_get(objspace->heap_pages.sorted, mid);
3007 if ((uintptr_t)mid_page->start < start) {
3008 lo = mid + 1;
3009 }
3010 else if ((uintptr_t)mid_page->start > start) {
3011 hi = mid;
3012 }
3013 else {
3014 rb_bug("same heap page is allocated: %p at %"PRIuVALUE, (void *)page_body, (VALUE)mid);
3015 }
3016 }
3017
3018 rb_darray_insert_without_gc(&objspace->heap_pages.sorted, hi, page);
3019
3020 if (heap_pages_lomem == 0 || heap_pages_lomem > start) heap_pages_lomem = start;
3021 if (heap_pages_himem < end) heap_pages_himem = end;
3022
3023 page->body = page_body;
3024 page->arena = arena;
3025 page_body->header.page = page;
3026 page->objspace = objspace;
3027
3028 objspace->heap_pages.allocated_pages++;
3029
3030 global_page_index_insert(page);
3031
3032 return page;
3033}
3034
3035static void
3036heap_add_page(rb_objspace_t *objspace, rb_heap_t *heap, struct heap_page *page)
3037{
3038 /* Adding to eden heap during incremental sweeping is forbidden */
3039 GC_ASSERT(!heap->sweeping_page);
3040 GC_ASSERT(heap_page_in_global_empty_pages_pool(objspace, page));
3041
3042 /* Align start to slot_size boundary */
3043 uintptr_t start = (uintptr_t)page->body + sizeof(struct heap_page_header);
3044 uintptr_t rem = start % heap->slot_size;
3045 if (rem) start += heap->slot_size - rem;
3046
3047 int slot_count = (int)((HEAP_PAGE_SIZE - (start - (uintptr_t)page->body))/heap->slot_size);
3048
3049 page->start = start;
3050 page->total_slots = slot_count;
3051 page->slot_size = heap->slot_size;
3052 page->slot_size_reciprocal = heap_slot_reciprocal_table[heap - heaps];
3053 page->heap = heap;
3054
3055 memset(&page->wb_unprotected_bits[0], 0, HEAP_PAGE_BITMAP_SIZE);
3056 memset(&page->age_bits[0], 0, sizeof(page->age_bits));
3057
3058 asan_unlock_freelist(page);
3059 asan_unpoison_memory_region(page->body, HEAP_PAGE_SIZE, false);
3060
3061 uintptr_t slots_end = start + (uintptr_t)slot_count * heap->slot_size;
3062
3063 memset((void *)start, 0, slots_end - start);
3064
3065 struct free_region *region = (struct free_region *)start;
3066 region->flags = 0;
3067 region->end = slots_end;
3068 region->next = NULL;
3069 page->free_region = region;
3070
3071 /* Poison every free slot; each is unpoisoned again as it is handed out. */
3072 for (uintptr_t p = start; p < slots_end; p += heap->slot_size) {
3073 rb_asan_poison_object((VALUE)p);
3074 }
3075 asan_lock_freelist(page);
3076
3077 page->free_slots = slot_count;
3078
3079 heap->total_allocated_pages++;
3080
3081 ccan_list_add_tail(&heap->pages, &page->page_node);
3082 heap->total_pages++;
3083 heap->total_slots += page->total_slots;
3084}
3085
3086static int
3087heap_page_allocate_and_initialize(rb_objspace_t *objspace, rb_heap_t *heap)
3088{
3089 gc_report(1, objspace, "heap_page_allocate_and_initialize: rb_darray_size(objspace->heap_pages.sorted): %"PRIdSIZE", "
3090 "allocatable_bytes: %"PRIdSIZE", heap->total_pages: %"PRIdSIZE"\n",
3091 rb_darray_size(objspace->heap_pages.sorted), objspace->heap_pages.allocatable_bytes, heap->total_pages);
3092
3093 bool allocated = false;
3094 struct heap_page *page = heap_page_resurrect(objspace);
3095
3096 if (page == NULL && objspace->heap_pages.allocatable_bytes > 0) {
3097 page = heap_page_allocate(objspace);
3098 allocated = true;
3099
3100 GC_ASSERT(page != NULL);
3101 }
3102
3103 if (page != NULL) {
3104 heap_add_page(objspace, heap, page);
3105 heap_add_freepage(heap, page);
3106
3107 if (allocated) {
3108 size_t page_bytes = (size_t)page->total_slots * page->slot_size;
3109 if (objspace->heap_pages.allocatable_bytes > page_bytes) {
3110 objspace->heap_pages.allocatable_bytes -= page_bytes;
3111 }
3112 else {
3113 objspace->heap_pages.allocatable_bytes = 0;
3114 }
3115 }
3116 }
3117
3118 return page != NULL;
3119}
3120
3121static void
3122heap_page_allocate_and_initialize_force(rb_objspace_t *objspace, rb_heap_t *heap)
3123{
3124 size_t prev_allocatable_bytes = objspace->heap_pages.allocatable_bytes;
3125 objspace->heap_pages.allocatable_bytes = HEAP_PAGE_SIZE;
3126 heap_page_allocate_and_initialize(objspace, heap);
3127 GC_ASSERT(heap->free_pages != NULL);
3128 objspace->heap_pages.allocatable_bytes = prev_allocatable_bytes;
3129}
3130
3131static void
3132gc_continue(rb_objspace_t *objspace, rb_heap_t *heap)
3133{
3134 unsigned int lock_lev;
3135 bool needs_gc = is_incremental_marking(objspace) || needs_continue_sweeping(objspace, heap);
3136 if (!needs_gc) return;
3137
3138 gc_enter(objspace, gc_enter_event_continue, &lock_lev); // takes vm barrier, try to avoid
3139
3140 /* Continue marking if in incremental marking. */
3141 if (is_incremental_marking(objspace)) {
3142 if (gc_marks_continue(objspace, heap)) {
3143 gc_sweep(objspace);
3144 }
3145 }
3146
3147 if (needs_continue_sweeping(objspace, heap)) {
3148 gc_sweep_continue(objspace, heap);
3149 }
3150
3151 gc_exit(objspace, gc_enter_event_continue, &lock_lev);
3152}
3153
3154static void
3155heap_prepare(rb_objspace_t *objspace, rb_heap_t *heap)
3156{
3157 GC_ASSERT(heap->free_pages == NULL);
3158
3159 if (heap->total_slots < objspace_heap_init_bytes(objspace) / heap->slot_size &&
3160 heap->sweeping_page == NULL) {
3161 heap_page_allocate_and_initialize_force(objspace, heap);
3162 GC_ASSERT(heap->free_pages != NULL);
3163 return;
3164 }
3165
3166 /* Continue incremental marking or lazy sweeping, if in any of those steps. */
3167 gc_continue(objspace, heap);
3168
3169 if (heap->free_pages == NULL) {
3170 heap_page_allocate_and_initialize(objspace, heap);
3171 }
3172
3173 /* If we still don't have a free page and not allowed to create a new page,
3174 * we should start a new GC cycle. */
3175 if (heap->free_pages == NULL) {
3176 GC_ASSERT(objspace->empty_pages_count == 0);
3177 GC_ASSERT(objspace->heap_pages.allocatable_bytes == 0);
3178
3179 if (gc_start(objspace, GPR_FLAG_NEWOBJ) == FALSE) {
3180 rb_memerror();
3181 }
3182 else {
3183 if (objspace->heap_pages.allocatable_bytes == 0 && !gc_config_full_mark_val) {
3184 heap_allocatable_bytes_expand(objspace, heap,
3185 heap->freed_slots + heap->empty_slots,
3186 heap->total_slots, heap->slot_size);
3187 GC_ASSERT(objspace->heap_pages.allocatable_bytes > 0);
3188 }
3189 /* Do steps of incremental marking or lazy sweeping if the GC run permits. */
3190 gc_continue(objspace, heap);
3191
3192 /* If we're not incremental marking (e.g. a minor GC) or finished
3193 * sweeping and still don't have a free page, then
3194 * gc_sweep_finish_heap should allow us to create a new page. */
3195 if (heap->free_pages == NULL && !heap_page_allocate_and_initialize(objspace, heap)) {
3196 if (gc_needs_major_flags == GPR_FLAG_NONE) {
3197 rb_bug("cannot create a new page after GC");
3198 }
3199 else { // Major GC is required, which will allow us to create new page
3200 if (gc_start(objspace, GPR_FLAG_NEWOBJ) == FALSE) {
3201 rb_memerror();
3202 }
3203 else {
3204 /* Do steps of incremental marking or lazy sweeping. */
3205 gc_continue(objspace, heap);
3206
3207 if (heap->free_pages == NULL &&
3208 !heap_page_allocate_and_initialize(objspace, heap)) {
3209 rb_bug("cannot create a new page after major GC");
3210 }
3211 }
3212 }
3213 }
3214 }
3215 }
3216
3217 GC_ASSERT(heap->free_pages != NULL);
3218}
3219
3220#if GC_DEBUG
3221static inline const char*
3222rb_gc_impl_source_location_cstr(int *ptr)
3223{
3224 /* We could directly refer `rb_source_location_cstr()` before, but not any
3225 * longer. We have to heavy lift using our debugging API. */
3226 if (! ptr) {
3227 return NULL;
3228 }
3229 else if (! (*ptr = rb_sourceline())) {
3230 return NULL;
3231 }
3232 else {
3233 return rb_sourcefile();
3234 }
3235}
3236#endif
3237
3238static inline VALUE
3239newobj_init(VALUE klass, VALUE flags, int wb_protected, rb_objspace_t *objspace, VALUE obj)
3240{
3241 GC_ASSERT(BUILTIN_TYPE(obj) == T_NONE);
3242 GC_ASSERT((flags & FL_WB_PROTECTED) == 0);
3243 RBASIC(obj)->flags = flags;
3244 *((VALUE *)&RBASIC(obj)->klass) = klass;
3245#if RBASIC_SHAPE_ID_FIELD
3246 RBASIC(obj)->shape_id = 0;
3247#endif
3248
3249 if (RB_UNLIKELY(flags & RUBY_FL_SHAREABLE)) {
3250 /* A born-shareable object must be WB protected: the shref and remembered-set
3251 * rules for shareable objects assume the write barrier. A local GC roots
3252 * shareable objects from this bit (pinned_roots_mark). */
3253 GC_ASSERT(wb_protected);
3254 gc_page_add_shareable(GET_HEAP_PAGE(obj), obj);
3255 }
3256
3257#if RGENGC_CHECK_MODE
3258 int lev = RB_GC_VM_LOCK_NO_BARRIER();
3259 {
3260 check_rvalue_consistency(objspace, obj);
3261
3262 GC_ASSERT(RVALUE_MARKED(objspace, obj) == FALSE);
3263 GC_ASSERT(RVALUE_MARKING(objspace, obj) == FALSE);
3264 GC_ASSERT(RVALUE_OLD_P(objspace, obj) == FALSE);
3265 GC_ASSERT(RVALUE_WB_UNPROTECTED(objspace, obj) == FALSE);
3266
3267 if (RVALUE_REMEMBERED(objspace, obj)) rb_bug("newobj: %s is remembered.", rb_obj_info(obj));
3268 }
3269 RB_GC_VM_UNLOCK_NO_BARRIER(lev);
3270#endif
3271
3272 if (RB_UNLIKELY(wb_protected == FALSE)) {
3273 MARK_IN_BITMAP(GET_HEAP_WB_UNPROTECTED_BITS(obj), obj);
3274 }
3275
3276#if RGENGC_PROFILE
3277 if (wb_protected) {
3278 objspace->profile.total_generated_normal_object_count++;
3279#if RGENGC_PROFILE >= 2
3280 objspace->profile.generated_normal_object_count_types[BUILTIN_TYPE(obj)]++;
3281#endif
3282 }
3283 else {
3284 objspace->profile.total_generated_shady_object_count++;
3285#if RGENGC_PROFILE >= 2
3286 objspace->profile.generated_shady_object_count_types[BUILTIN_TYPE(obj)]++;
3287#endif
3288 }
3289#endif
3290
3291#if GC_DEBUG
3292 GET_RVALUE_OVERHEAD(obj)->file = rb_gc_impl_source_location_cstr(&GET_RVALUE_OVERHEAD(obj)->line);
3293 GC_ASSERT(!SPECIAL_CONST_P(obj)); /* check alignment */
3294#endif
3295
3296 gc_report(5, objspace, "newobj: %s\n", rb_obj_info(obj));
3297
3298 // RUBY_DEBUG_LOG("obj:%p (%s)", (void *)obj, rb_obj_info(obj));
3299 return obj;
3300}
3301
3302size_t
3303rb_gc_impl_obj_slot_size(VALUE obj)
3304{
3305 return GET_HEAP_PAGE(obj)->slot_size - RVALUE_OVERHEAD;
3306}
3307
3308bool
3309rb_gc_impl_pinned_p(void *objspace_ptr, VALUE obj)
3310{
3311 return RVALUE_PINNED((rb_objspace_t *)objspace_ptr, obj);
3312}
3313
3314static inline size_t
3315heap_slot_size(unsigned char pool_id)
3316{
3317 GC_ASSERT(pool_id < HEAP_COUNT);
3318
3319 return pool_slot_sizes[pool_id] - RVALUE_OVERHEAD;
3320}
3321
3322size_t
3323rb_gc_impl_max_allocation_size(void)
3324{
3325 return heap_slot_size(HEAP_COUNT - 1);
3326}
3327
3328bool
3329rb_gc_impl_size_allocatable_p(size_t size)
3330{
3331 return size <= rb_gc_impl_max_allocation_size();
3332}
3333
3334static inline bool
3335heap_advance_region(rb_heap_t *heap)
3336{
3337 struct free_region *region = heap->newobj.alloc_next_region;
3338 if (region == NULL) {
3339 return false;
3340 }
3341
3342 rb_asan_unpoison_object((VALUE)region, false);
3343 GC_ASSERT(RB_TYPE_P((VALUE)region, T_NONE));
3344 heap->newobj.alloc_cursor = (uintptr_t)region;
3345 heap->newobj.alloc_cursor_end = region->end;
3346 heap->newobj.alloc_next_region = region->next;
3347 rb_asan_poison_object((VALUE)region);
3348
3349 return true;
3350}
3351
3352/* The whole region is ours until the next refill, so charge it to the step now. */
3353static inline void
3354heap_charge_region(rb_objspace_t *objspace, const rb_heap_t *heap, size_t heap_idx)
3355{
3356 objspace->incremental_mark_step_allocated_slots +=
3357 (heap->newobj.alloc_cursor_end - heap->newobj.alloc_cursor) / pool_slot_sizes[heap_idx];
3358}
3359
3360static inline VALUE
3361heap_alloc_slot(rb_objspace_t *objspace, size_t heap_idx)
3362{
3363 rb_heap_t *heap = &heaps[heap_idx];
3364
3365 uintptr_t cursor = heap->newobj.alloc_cursor;
3366 if (RB_UNLIKELY(cursor >= heap->newobj.alloc_cursor_end)) {
3367 /* Marking owes us a step before the next region, and newobj_refill runs it. */
3368 if (RB_UNLIKELY(is_incremental_marking(objspace)) ||
3369 heap_advance_region(heap) == false) {
3370 return Qfalse;
3371 }
3372 cursor = heap->newobj.alloc_cursor;
3373 }
3374
3375 VALUE obj = (VALUE)cursor;
3376 rb_asan_unpoison_object(obj, true);
3377 heap->newobj.alloc_cursor = cursor + pool_slot_sizes[heap_idx];
3378
3379 /* Single writer (the owning Ractor under the GVL), so a plain increment is enough. */
3380 heap->total_allocated_objects++;
3381
3382#if RGENGC_CHECK_MODE
3383 GC_ASSERT(rb_gc_impl_obj_slot_size(obj) == heap_slot_size(heap_idx));
3384 // zero clear
3385 MEMZERO((char *)obj, char, heap_slot_size(heap_idx));
3386#endif
3387 return obj;
3388}
3389
3390static struct heap_page *
3391heap_next_free_page(rb_objspace_t *objspace, rb_heap_t *heap)
3392{
3393 struct heap_page *page;
3394
3395 if (heap->free_pages == NULL) {
3396 heap_prepare(objspace, heap);
3397 }
3398
3399 page = heap->free_pages;
3400 heap->free_pages = page->free_next;
3401
3402 GC_ASSERT(page->free_slots != 0);
3403
3404 asan_unlock_freelist(page);
3405
3406 return page;
3407}
3408
3409static inline void
3410heap_set_alloc_page(rb_objspace_t *objspace, size_t heap_idx, struct heap_page *page)
3411{
3412 gc_report(3, objspace, "heap_set_alloc_page: Using page %p\n", (void *)page->body);
3413
3414 rb_heap_t *heap = &heaps[heap_idx];
3415
3416 GC_ASSERT(heap->newobj.alloc_cursor >= heap->newobj.alloc_cursor_end);
3417 GC_ASSERT(heap->newobj.alloc_next_region == NULL);
3418 GC_ASSERT(page->free_slots != 0);
3419 GC_ASSERT(page->free_region != NULL);
3420
3421 heap->newobj.alloc_using_page = page;
3422
3423 struct free_region *region = page->free_region;
3424 rb_asan_unpoison_object((VALUE)region, false);
3425 GC_ASSERT(RB_TYPE_P((VALUE)region, T_NONE));
3426 heap->newobj.alloc_cursor = (uintptr_t)region;
3427 heap->newobj.alloc_cursor_end = region->end;
3428 heap->newobj.alloc_next_region = region->next;
3429 rb_asan_poison_object((VALUE)region);
3430
3431 page->free_slots = 0;
3432 page->free_region = NULL;
3433}
3434
3435static void
3436init_size_to_heap_idx(void)
3437{
3438 /* Process-wide and immutable, so build it once at boot. A rebuild in a later
3439 * objspace_init would write the same values but race other threads' lock-free
3440 * allocation-fastpath reads. */
3441 static bool initialized = false;
3442 if (initialized) return;
3443 initialized = true;
3444
3445 for (size_t i = 0; i < sizeof(size_to_heap_idx); i++) {
3446 size_t effective = i * 8 + RVALUE_OVERHEAD;
3447 uint8_t idx;
3448 for (idx = 0; idx < HEAP_COUNT; idx++) {
3449 if (effective <= pool_slot_sizes[idx]) break;
3450 }
3451 size_to_heap_idx[i] = idx;
3452 }
3453}
3454
3455static inline size_t
3456heap_idx_for_size(size_t size)
3457{
3458 size_t compressed = (size + 7) >> 3;
3459 if (compressed < sizeof(size_to_heap_idx)) {
3460 size_t heap_idx = size_to_heap_idx[compressed];
3461 if (RB_LIKELY(heap_idx < HEAP_COUNT)) return heap_idx;
3462 }
3463
3464 rb_bug("heap_idx_for_size: allocation size too large "
3465 "(size=%"PRIuSIZE")", size);
3466}
3467
3468size_t
3469rb_gc_impl_size_slot_size(void *objspace_ptr, size_t size)
3470{
3471 return heap_slot_size((unsigned char)heap_idx_for_size(size));
3472}
3473
3474bool
3475rb_gc_impl_zjit_new_obj_fastpath(void *objspace_ptr, size_t alloc_size, VALUE flags, VALUE klass,
3476 struct rb_gc_zjit_fastpath *fastpath)
3477{
3478#if USE_ZJIT
3479 size_t heap_idx = 0;
3480 size_t slot_size = 0;
3481 for (; heap_idx < HEAP_COUNT; heap_idx++) {
3482 if (alloc_size + RVALUE_OVERHEAD <= pool_slot_sizes[heap_idx]) {
3483 slot_size = pool_slot_sizes[heap_idx];
3484 break;
3485 }
3486 }
3487 if (slot_size == 0) return false;
3488
3489#undef heaps
3490 size_t base = offsetof(rb_objspace_t, heaps)
3491 + heap_idx * sizeof(rb_heap_t)
3492 + offsetof(rb_heap_t, newobj);
3493#define heaps objspace->heaps
3494
3495 struct rb_gc_zjit_default_new_obj_fastpath default_fastpath = {
3496 base + offsetof(rb_heap_newobj_t, alloc_cursor),
3497 base + offsetof(rb_heap_newobj_t, alloc_cursor_end),
3498 slot_size,
3499 base - offsetof(rb_heap_t, newobj) + offsetof(rb_heap_t, total_allocated_objects),
3500 flags,
3501 klass
3502 };
3503
3504 memset(fastpath, 0, sizeof(*fastpath));
3505 fastpath->kind = RB_GC_ZJIT_FASTPATH_DEFAULT;
3506 memcpy(fastpath->data.words, &default_fastpath, sizeof(default_fastpath));
3507
3508 return true;
3509#else
3510 return false;
3511#endif
3512}
3513
3514int32_t
3515rb_gc_impl_zjit_writebarrier_required_offset(void)
3516{
3517 return (int32_t)offsetof(rb_objspace_t, zjit_during_incremental_marking);
3518}
3519
3520NOINLINE(static VALUE newobj_refill(rb_objspace_t *objspace, size_t heap_idx));
3521
3522static VALUE
3523newobj_refill(rb_objspace_t *objspace, size_t heap_idx)
3524{
3525 rb_heap_t *heap = &heaps[heap_idx];
3526 VALUE obj = Qfalse;
3527
3528 /* No lock: a heap is single-writer (its owner thread, serialized by the GVL inside
3529 * the Ractor), the page pool has its own mutex, and a GC started from here takes
3530 * whatever gc_enter needs. */
3531 if (is_incremental_marking(objspace)) {
3532 /* The fast path sends us here at every region, which is far more often than the
3533 * step size, so step only once the regions add up to it. */
3534 if (objspace->incremental_mark_step_allocated_slots >= INCREMENTAL_MARK_STEP_ALLOCATIONS) {
3535 gc_continue(objspace, heap);
3536 objspace->incremental_mark_step_allocated_slots = 0;
3537 }
3538
3539 // Move on to the region the fast path refused to take
3540 if (heap_advance_region(heap)) {
3541 heap_charge_region(objspace, heap, heap_idx);
3542 obj = heap_alloc_slot(objspace, heap_idx);
3543 }
3544 }
3545
3546 if (obj == Qfalse) {
3547 // Get next free page (possibly running GC)
3548 struct heap_page *page = heap_next_free_page(objspace, heap);
3549 heap_set_alloc_page(objspace, heap_idx, page);
3550 heap_charge_region(objspace, heap, heap_idx);
3551
3552 // Retry allocation after moving to new page
3553 obj = heap_alloc_slot(objspace, heap_idx);
3554 }
3555
3556 if (RB_UNLIKELY(obj == Qfalse)) {
3557 rb_memerror();
3558 }
3559 return obj;
3560}
3561
3562static VALUE
3563newobj_alloc(rb_objspace_t *objspace, size_t heap_idx)
3564{
3565 /* The objspace belongs to the current Ractor and is single-writer, so the fast path
3566 * needs no lock. Stress GC runs in the caller's slow path, before newobj_alloc. */
3567 VALUE obj = heap_alloc_slot(objspace, heap_idx);
3568
3569 if (RB_UNLIKELY(obj == Qfalse)) {
3570 obj = newobj_refill(objspace, heap_idx);
3571 }
3572
3573 return obj;
3574}
3575
3576ALWAYS_INLINE(static VALUE newobj_slowpath(VALUE klass, VALUE flags, rb_objspace_t *objspace, int wb_protected, size_t heap_idx));
3577
3578static inline VALUE
3579newobj_slowpath(VALUE klass, VALUE flags, rb_objspace_t *objspace, int wb_protected, size_t heap_idx)
3580{
3581 VALUE obj;
3582
3583 /* No lock (see newobj_refill); during_gc and the stress flag are this objspace's own state. */
3584 if (RB_UNLIKELY(during_gc || ruby_gc_stressful)) {
3585 if (during_gc) {
3586 dont_gc_on();
3587 during_gc = 0;
3588 if (rb_memerror_reentered()) {
3589 rb_memerror();
3590 }
3591 rb_bug("object allocation during garbage collection phase");
3592 }
3593
3594 if (ruby_gc_stressful) {
3595 if (!garbage_collect(objspace, GPR_FLAG_NEWOBJ)) {
3596 rb_memerror();
3597 }
3598 }
3599 }
3600
3601 obj = newobj_alloc(objspace, heap_idx);
3602 newobj_init(klass, flags, wb_protected, objspace, obj);
3603
3604 if (RB_UNLIKELY(ruby_gc_stressful)) {
3605 rb_heap_t *heap = &heaps[heap_idx];
3606 heap->newobj.alloc_cursor_end = heap->newobj.alloc_cursor;
3607 }
3608
3609 return obj;
3610}
3611
3612NOINLINE(static VALUE newobj_slowpath_wb_protected(VALUE klass, VALUE flags,
3613 rb_objspace_t *objspace, size_t heap_idx));
3614NOINLINE(static VALUE newobj_slowpath_wb_unprotected(VALUE klass, VALUE flags,
3615 rb_objspace_t *objspace, size_t heap_idx));
3616
3617static VALUE
3618newobj_slowpath_wb_protected(VALUE klass, VALUE flags, rb_objspace_t *objspace, size_t heap_idx)
3619{
3620 return newobj_slowpath(klass, flags, objspace, TRUE, heap_idx);
3621}
3622
3623static VALUE
3624newobj_slowpath_wb_unprotected(VALUE klass, VALUE flags, rb_objspace_t *objspace, size_t heap_idx)
3625{
3626 return newobj_slowpath(klass, flags, objspace, FALSE, heap_idx);
3627}
3628
3629VALUE
3630rb_gc_impl_new_obj(void *objspace_ptr, void *cache_ptr, VALUE klass, VALUE flags, bool wb_protected, size_t alloc_size, size_t *actual_alloc_size)
3631{
3632 VALUE obj;
3633 rb_objspace_t *objspace = objspace_ptr;
3634
3635 /* There is no per-Ractor cache; the argument stays for ABI compatibility with other
3636 * GC implementations such as MMTk. */
3637 (void)cache_ptr;
3638
3639 RB_DEBUG_COUNTER_INC(obj_newobj);
3640 (void)RB_DEBUG_COUNTER_INC_IF(obj_newobj_wb_unprotected, !wb_protected);
3641
3642 if (RB_UNLIKELY(stress_to_class)) {
3643 if (rb_hash_lookup2(stress_to_class, klass, Qundef) != Qundef) {
3644 rb_memerror();
3645 }
3646 }
3647
3648 size_t heap_idx = heap_idx_for_size(alloc_size);
3649 *actual_alloc_size = heap_slot_size((unsigned char)heap_idx);
3650
3651 if (!RB_UNLIKELY(during_gc || ruby_gc_stressful) &&
3652 wb_protected) {
3653 obj = newobj_alloc(objspace, heap_idx);
3654 newobj_init(klass, flags, wb_protected, objspace, obj);
3655 }
3656 else {
3657 RB_DEBUG_COUNTER_INC(obj_newobj_slowpath);
3658
3659 obj = wb_protected ?
3660 newobj_slowpath_wb_protected(klass, flags, objspace, heap_idx) :
3661 newobj_slowpath_wb_unprotected(klass, flags, objspace, heap_idx);
3662 }
3663
3664 return obj;
3665}
3666
3667static int
3668ptr_in_page_body_p(const void *ptr, const void *memb)
3669{
3670 struct heap_page *page = *(struct heap_page **)memb;
3671 uintptr_t p_body = (uintptr_t)page->body;
3672
3673 if ((uintptr_t)ptr >= p_body) {
3674 return (uintptr_t)ptr < (p_body + HEAP_PAGE_SIZE) ? 0 : 1;
3675 }
3676 else {
3677 return -1;
3678 }
3679}
3680
3681PUREFUNC(static inline struct heap_page *heap_page_for_ptr(rb_objspace_t *objspace, uintptr_t ptr);)
3682static inline struct heap_page *
3683heap_page_for_ptr(rb_objspace_t *objspace, uintptr_t ptr)
3684{
3685 struct heap_page **res;
3686
3687 if (ptr < (uintptr_t)heap_pages_lomem ||
3688 ptr > (uintptr_t)heap_pages_himem) {
3689 return NULL;
3690 }
3691
3692 res = bsearch((void *)ptr, rb_darray_ref(objspace->heap_pages.sorted, 0),
3693 rb_darray_size(objspace->heap_pages.sorted), sizeof(struct heap_page *),
3694 ptr_in_page_body_p);
3695
3696 if (res) {
3697 return *res;
3698 }
3699 else {
3700 return NULL;
3701 }
3702}
3703
3704PUREFUNC(static inline bool is_pointer_to_heap(rb_objspace_t *objspace, const void *ptr);)
3705static inline bool
3706is_pointer_to_heap(rb_objspace_t *objspace, const void *ptr)
3707{
3708 register uintptr_t p = (uintptr_t)ptr;
3709 register struct heap_page *page;
3710
3711 RB_DEBUG_COUNTER_INC(gc_isptr_trial);
3712
3713 if (p < heap_pages_lomem || p > heap_pages_himem) return FALSE;
3714 RB_DEBUG_COUNTER_INC(gc_isptr_range);
3715
3716 if (p % sizeof(VALUE) != 0) return FALSE;
3717 RB_DEBUG_COUNTER_INC(gc_isptr_align);
3718
3719 page = heap_page_for_ptr(objspace, (uintptr_t)ptr);
3720 if (page) {
3721 RB_DEBUG_COUNTER_INC(gc_isptr_maybe);
3722 if (heap_page_in_global_empty_pages_pool(objspace, page)) {
3723 return FALSE;
3724 }
3725 else {
3726 if (p < page->start) return FALSE;
3727 if (p >= page->start + (page->total_slots * page->slot_size)) return FALSE;
3728 if ((p - page->start) % page->slot_size != 0) return FALSE;
3729
3730 return TRUE;
3731 }
3732 }
3733 return FALSE;
3734}
3735
3736/*
3737 * Is this object live in the given objspace. For foreign objects in other object spaces,
3738 * it returns `false`. NOTE: this does NOT check whether or not it's unmarked during the process
3739 * of lazy sweeping.
3740 */
3741bool
3742rb_gc_impl_live_object_p(void *objspace_ptr, const void *ptr)
3743{
3744 rb_objspace_t *objspace = objspace_ptr;
3745
3746 /* Whether ptr refers to a live object. is_pointer_to_heap is the
3747 * address-only check; T_NONE, T_MOVED, and T_ZOMBIE slots are valid heap
3748 * addresses but not live objects. */
3749 if (!is_pointer_to_heap(objspace, ptr)) return false;
3750
3751 VALUE obj = (VALUE)ptr;
3752 bool live = false;
3753 asan_unpoisoning_object(obj) {
3754 switch (BUILTIN_TYPE(obj)) {
3755 case T_NONE:
3756 case T_MOVED:
3757 case T_ZOMBIE:
3758 break;
3759 default:
3760 live = true;
3761 break;
3762 }
3763 }
3764 return live;
3765}
3766
3767/* Flags preserved from the original object when it becomes a zombie, and so also the
3768 * only ones that may legitimately be set on one. */
3769#define ZOMBIE_OBJ_KEPT_FLAGS (FL_FINALIZE)
3770
3771void
3772rb_gc_impl_make_zombie(void *objspace_ptr, VALUE obj, void (*dfree)(void *), void *data)
3773{
3774 rb_objspace_t *objspace = objspace_ptr;
3775
3776 struct RZombie *zombie = RZOMBIE(obj);
3777 zombie->flags = T_ZOMBIE | (zombie->flags & ZOMBIE_OBJ_KEPT_FLAGS);
3778 zombie->dfree = dfree;
3779 zombie->data = data;
3780 VALUE prev, next = heap_pages_deferred_final;
3781 do {
3782 zombie->next = prev = next;
3783 next = RUBY_ATOMIC_VALUE_CAS(heap_pages_deferred_final, prev, obj);
3784 } while (next != prev);
3785
3786 struct heap_page *page = GET_HEAP_PAGE(obj);
3787 page->final_slots++;
3788 page->heap->final_slots_count++;
3789}
3790
3791static void
3792tdata_unsafe_free_chunk_reset(struct tdata_unsafe_free_chunk *chunk)
3793{
3794 chunk->next = NULL;
3795 chunk->count = 0;
3796 chunk->embed_xfree_bits = 0;
3797}
3798
3799static struct tdata_unsafe_free_chunk *
3800tdata_unsafe_free_chunk_alloc(void)
3801{
3802 /* Pops race each other (several Ractors can be sweeping), but pushes happen only
3803 * inside the drain, which holds a VM barrier -- and a barrier cannot complete while
3804 * a Ractor is inside gc_sweep_page. No push ever overlaps a pop, so the head only
3805 * moves forward and this CAS pop needs no ABA tagging. A sweep performed by a
3806 * thread other than the objspace's owner would break that. */
3807 struct tdata_unsafe_free_chunk *head =
3808 rbimpl_atomic_ptr_load((void **)&global_objspace->tdata_unsafe_free_cache,
3809 RBIMPL_ATOMIC_ACQUIRE);
3810 while (head) {
3811 struct tdata_unsafe_free_chunk *prev =
3812 rbimpl_atomic_ptr_cas((void **)&global_objspace->tdata_unsafe_free_cache,
3813 head, head->next,
3814 RBIMPL_ATOMIC_ACQ_REL, RBIMPL_ATOMIC_ACQUIRE);
3815 if (prev == head) {
3816 rbimpl_atomic_size_dec(&global_objspace->tdata_unsafe_free_cache_len,
3817 RBIMPL_ATOMIC_RELAXED);
3818 tdata_unsafe_free_chunk_reset(head);
3819 return head;
3820 }
3821 head = prev;
3822 }
3823
3824 /* Not xmalloc: this runs mid-sweep, and the chunks are GC bookkeeping that should not
3825 * feed back into malloc_increase (mark stack chunks do the same). */
3826 struct tdata_unsafe_free_chunk *chunk = malloc(sizeof(struct tdata_unsafe_free_chunk));
3827 if (!chunk) rb_memerror();
3828 tdata_unsafe_free_chunk_reset(chunk);
3829 return chunk;
3830}
3831
3832/* Hand this objspace's partial chunk to the global stack. The entries were counted as
3833 * they were appended, so the pending count does not change here. */
3834static void
3835gc_tdata_unsafe_free_publish(rb_objspace_t *objspace)
3836{
3837 struct tdata_unsafe_free_chunk *chunk = objspace->tdata_unsafe_free_chunk;
3838 if (chunk == NULL) return;
3839 GC_ASSERT(chunk->count > 0);
3840 objspace->tdata_unsafe_free_chunk = NULL;
3841
3842 struct tdata_unsafe_free_chunk *prev, *head =
3843 rbimpl_atomic_ptr_load((void **)&global_objspace->tdata_unsafe_free_published,
3844 RBIMPL_ATOMIC_RELAXED);
3845 do {
3846 chunk->next = prev = head;
3847 head = rbimpl_atomic_ptr_cas((void **)&global_objspace->tdata_unsafe_free_published,
3848 prev, chunk,
3849 RBIMPL_ATOMIC_ACQ_REL, RBIMPL_ATOMIC_ACQUIRE);
3850 } while (head != prev);
3851}
3852
3853/* Copy out what obj's deferred free needs, running no dfree. Returns true when the
3854 * caller may reclaim the slot and false when obj became a zombie, matching rb_gc_obj_free. */
3855static bool
3856gc_defer_thread_unsafe_free(rb_objspace_t *objspace, VALUE obj, bool *trigger)
3857{
3858 GC_ASSERT(!((uintptr_t)RTYPEDDATA(obj)->type & TYPED_DATA_EMBEDDED));
3859 const rb_data_type_t *type = RTYPEDDATA_TYPE(obj);
3860 void *data = RTYPEDDATA(obj)->data;
3861 GC_ASSERT(data != NULL);
3862
3863 rb_gc_obj_free_vm_weak_references(obj);
3864
3865 size_t count = rbimpl_atomic_size_fetch_add(&global_objspace->tdata_deferred_free_count, 1,
3866 RBIMPL_ATOMIC_RELAXED) + 1;
3867 if (!*trigger && count >= TDATA_DEFERRED_FREE_THRESHOLD) {
3868 *trigger = true;
3869 }
3870
3871 struct tdata_unsafe_free_chunk *chunk = objspace->tdata_unsafe_free_chunk;
3872 if (chunk == NULL) {
3873 chunk = objspace->tdata_unsafe_free_chunk = tdata_unsafe_free_chunk_alloc();
3874 }
3875 if (type->flags & RUBY_TYPED_EMBEDDABLE) {
3876 chunk->embed_xfree_bits |= (uint32_t)1 << chunk->count;
3877 }
3878 struct tdata_unsafe_free_entry *entry = &chunk->entries[chunk->count++];
3879 entry->dfree = type->function.dfree;
3880 entry->data = data;
3881 if (chunk->count == TDATA_UNSAFE_FREE_CHUNK_CAPA) {
3882 gc_tdata_unsafe_free_publish(objspace);
3883 }
3884
3885 if (FL_TEST_RAW(obj, FL_FINALIZE)) {
3886 /* The dfree is on the side list now, so this zombie carries none: it goes on the
3887 * regular deferred list, where the owner runs its Ruby finalizer promptly and
3888 * reclaims the slot, instead of waiting for the barrier. */
3889 rb_gc_impl_make_zombie(objspace, obj, 0, 0);
3890 return false;
3891 }
3892 return true;
3893}
3894
3895typedef int each_obj_callback(void *, void *, size_t, void *);
3896typedef int each_page_callback(struct heap_page *, void *);
3897
3900 bool reenable_incremental;
3901
3902 /* Visit only the pages that hold shareable objects, so a foreign Ractor's objspace
3903 * can be walked for its shareable objects alone, without touching the rest of its
3904 * isolated heap. */
3905 bool shareable_only;
3906
3907 /* Set when walking a foreign objspace without settling its stopped lazy sweep
3908 * (settling would run the owner's obj_free and dfree on this thread). Objects the
3909 * sweep is about to free are skipped: on an unswept page, unmarked means dead. */
3910 bool skip_unswept_dead;
3911
3912 each_obj_callback *each_obj_callback;
3913 each_page_callback *each_page_callback;
3914 void *data;
3915
3916 struct heap_page **pages[HEAP_COUNT];
3917 size_t pages_counts[HEAP_COUNT];
3918};
3919
3920static VALUE
3921objspace_each_objects_ensure(VALUE arg)
3922{
3923 struct each_obj_data *data = (struct each_obj_data *)arg;
3924 rb_objspace_t *objspace = data->objspace;
3925
3926 /* Reenable incremental GC */
3927 if (data->reenable_incremental) {
3928 objspace->flags.dont_incremental = FALSE;
3929 }
3930
3931 for (int i = 0; i < HEAP_COUNT; i++) {
3932 struct heap_page **pages = data->pages[i];
3933 free(pages);
3934 }
3935
3936 return Qnil;
3937}
3938
3939static VALUE
3940objspace_each_objects_try(VALUE arg)
3941{
3942 struct each_obj_data *data = (struct each_obj_data *)arg;
3943 rb_objspace_t *objspace = data->objspace;
3944
3945 /* Copy pages from all heaps to their respective buffers. */
3946 for (int i = 0; i < HEAP_COUNT; i++) {
3947 rb_heap_t *heap = &heaps[i];
3948 size_t size = heap->total_pages * sizeof(struct heap_page *);
3949
3950 struct heap_page **pages = malloc(size);
3951 if (!pages) rb_memerror();
3952
3953 /* Set up pages buffer by iterating over all pages in the current eden
3954 * heap. This will be a snapshot of the state of the heap before we
3955 * call the callback over each page that exists in this buffer. Thus it
3956 * is safe for the callback to allocate objects without possibly entering
3957 * an infinite loop. */
3958 struct heap_page *page = 0;
3959 size_t pages_count = 0;
3960 ccan_list_for_each(&heap->pages, page, page_node) {
3961 pages[pages_count] = page;
3962 pages_count++;
3963 }
3964 data->pages[i] = pages;
3965 data->pages_counts[i] = pages_count;
3966 GC_ASSERT(pages_count == heap->total_pages);
3967 }
3968
3969 for (int i = 0; i < HEAP_COUNT; i++) {
3970 rb_heap_t *heap = &heaps[i];
3971 size_t pages_count = data->pages_counts[i];
3972 struct heap_page **pages = data->pages[i];
3973
3974 struct heap_page *page = ccan_list_top(&heap->pages, struct heap_page, page_node);
3975 for (size_t i = 0; i < pages_count; i++) {
3976 /* If we have reached the end of the linked list then there are no
3977 * more pages, so break. */
3978 if (page == NULL) break;
3979
3980 /* If this page does not match the one in the buffer, then move to
3981 * the next page in the buffer. */
3982 if (pages[i] != page) continue;
3983
3984 uintptr_t pstart = (uintptr_t)page->start;
3985 uintptr_t pend = pstart + (page->total_slots * heap->slot_size);
3986
3987 if (data->shareable_only) {
3988 /* Hand shareable objects to the callback one slot at a time, not the
3989 * whole page: walking a foreign Ractor's objspace must never expose its
3990 * unshareable objects, which the caller cannot inspect safely. */
3991 if (page->flags.has_shareable_objects) {
3992 /* This walk runs over a foreign objspace under the barrier and
3993 * must not settle the owner's stopped lazy sweep: settling would run
3994 * the owner's obj_free and dfree on this thread with this Ractor's
3995 * identity (wrong per-Ractor tables, a foreign T_DATA dfree). So no
3996 * gc_rest, and objects the sweep is about to free are skipped: on an
3997 * unswept page unmarked means dead and its shareable bit merely has
3998 * not been bulk-cleared yet. Passing one to the callback would
3999 * resurrect it, handing out a reference the owner's sweep frees as
4000 * soon as the barrier lifts. */
4001 const bool page_unswept = is_lazy_sweeping(objspace) && page->flags.before_sweep;
4002 int planes = CEILDIV(page->total_slots, BITS_BITLENGTH);
4003 uintptr_t base = pstart;
4004 bool stop = false;
4005 for (int j = 0; j < planes && !stop; j++) {
4006 bits_t bits = page->shareable_bits[j];
4007 uintptr_t slot = base;
4008 while (bits) {
4009 if ((bits & 1) && data->each_obj_callback &&
4010 !(page_unswept && !RVALUE_MARKED(objspace, (VALUE)slot)) &&
4011 (*data->each_obj_callback)((void *)slot, (void *)(slot + heap->slot_size),
4012 heap->slot_size, data->data)) {
4013 stop = true;
4014 break;
4015 }
4016 slot += heap->slot_size;
4017 bits >>= 1;
4018 }
4019 base += BITS_BITLENGTH * heap->slot_size;
4020 }
4021 if (stop) break;
4022 }
4023 }
4024 else if (data->skip_unswept_dead &&
4025 is_lazy_sweeping(objspace) && page->flags.before_sweep) {
4026 /* A foreign page pending sweep: hand out the live objects one slot at a
4027 * time and skip the unmarked (dead) ones the owner's sweep frees as soon
4028 * as the barrier lifts. */
4029 bool stop = false;
4030 for (uintptr_t slot = pstart; slot < pend; slot += heap->slot_size) {
4031 if (!RVALUE_MARKED(objspace, (VALUE)slot)) continue;
4032 if (data->each_obj_callback &&
4033 (*data->each_obj_callback)((void *)slot, (void *)(slot + heap->slot_size),
4034 heap->slot_size, data->data)) {
4035 stop = true;
4036 break;
4037 }
4038 }
4039 if (stop) break;
4040 }
4041 else {
4042 if (data->each_obj_callback &&
4043 (*data->each_obj_callback)((void *)pstart, (void *)pend, heap->slot_size, data->data)) {
4044 break;
4045 }
4046 if (data->each_page_callback &&
4047 (*data->each_page_callback)(page, data->data)) {
4048 break;
4049 }
4050 }
4051
4052 page = ccan_list_next(&heap->pages, page, page_node);
4053 }
4054 }
4055
4056 return Qnil;
4057}
4058
4059static void
4060objspace_each_exec(bool protected, struct each_obj_data *each_obj_data)
4061{
4062 /* Disable incremental GC */
4064 bool reenable_incremental = FALSE;
4065 if (protected) {
4066 reenable_incremental = !objspace->flags.dont_incremental;
4067
4068 gc_rest(objspace);
4069 objspace->flags.dont_incremental = TRUE;
4070 }
4071
4072 each_obj_data->reenable_incremental = reenable_incremental;
4073 memset(&each_obj_data->pages, 0, sizeof(each_obj_data->pages));
4074 memset(&each_obj_data->pages_counts, 0, sizeof(each_obj_data->pages_counts));
4075 rb_ensure(objspace_each_objects_try, (VALUE)each_obj_data,
4076 objspace_each_objects_ensure, (VALUE)each_obj_data);
4077}
4078
4079static void
4080objspace_each_objects(rb_objspace_t *objspace, each_obj_callback *callback, void *data, bool protected)
4081{
4082 struct each_obj_data each_obj_data = {
4083 .objspace = objspace,
4084 .each_obj_callback = callback,
4085 .each_page_callback = NULL,
4086 .data = data,
4087 };
4088 objspace_each_exec(protected, &each_obj_data);
4089}
4090
4091void
4092rb_gc_impl_each_objects(void *objspace_ptr, each_obj_callback *callback, void *data)
4093{
4094 objspace_each_objects(objspace_ptr, callback, data, TRUE);
4095}
4096
4097/* Like rb_gc_impl_each_objects but visiting only pages that hold shareable objects, to
4098 * reach a foreign Ractor's shareable objects without walking the rest of its heap. */
4099void
4100rb_gc_impl_each_objects_shareable(void *objspace_ptr, each_obj_callback *callback, void *data)
4101{
4102 struct each_obj_data each_obj_data = {
4103 .objspace = objspace_ptr,
4104 .shareable_only = true,
4105 .each_obj_callback = callback,
4106 .each_page_callback = NULL,
4107 .data = data,
4108 };
4109 /* Not the protected variant: this objspace belongs to another Ractor (the caller
4110 * holds the barrier). The protected path calls gc_rest, which would run the owner's
4111 * stopped lazy sweep (its obj_free and dfree) on the walking thread with the
4112 * walker's Ractor identity (wrong per-Ractor tables, a foreign T_DATA dfree). The
4113 * owner is stopped and its page list is stable, and the walk itself skips dead,
4114 * unswept objects (the shareable_only branch of objspace_each_objects_try). The
4115 * walker's own incremental GC state is untouched, since this is not its objspace. */
4116 objspace_each_exec(FALSE, &each_obj_data);
4117}
4118
4119/* Walk every object of a foreign Ractor's objspace, unshareable ones included. Only for
4120 * callers that hold the barrier and whose callback is pure C (a heap dump, memory
4121 * accounting). As in the shareable walk above, the owner's stopped lazy sweep is not
4122 * settled and dead, unswept objects are skipped by the walk (skip_unswept_dead). */
4123void
4124rb_gc_impl_each_objects_foreign(void *objspace_ptr, each_obj_callback *callback, void *data)
4125{
4126 struct each_obj_data each_obj_data = {
4127 .objspace = objspace_ptr,
4128 .skip_unswept_dead = true,
4129 .each_obj_callback = callback,
4130 .each_page_callback = NULL,
4131 .data = data,
4132 };
4133 objspace_each_exec(FALSE, &each_obj_data);
4134}
4135
4136#if GC_CAN_COMPILE_COMPACTION
4137static void
4138objspace_each_pages(rb_objspace_t *objspace, each_page_callback *callback, void *data, bool protected)
4139{
4140 struct each_obj_data each_obj_data = {
4141 .objspace = objspace,
4142 .each_obj_callback = NULL,
4143 .each_page_callback = callback,
4144 .data = data,
4145 };
4146 objspace_each_exec(protected, &each_obj_data);
4147}
4148#endif
4149
4150VALUE
4151rb_gc_impl_define_finalizer(void *objspace_ptr, VALUE obj, VALUE block)
4152{
4153 rb_objspace_t *objspace = objspace_ptr;
4154 VALUE table;
4155 st_data_t data;
4156
4157 GC_ASSERT(!OBJ_FROZEN(obj));
4158
4159 /* Registering, storing and running finalizers all belong to the object's own
4160 * objspace, so refuse to define one on another Ractor's object (even a shareable
4161 * one): it would land in a table the owner's sweep never consults. */
4162 if (GET_HEAP_OBJSPACE(obj) != objspace) {
4163 rb_raise(rb_eRactorIsolationError,
4164 "can not define a finalizer for an object of another Ractor");
4165 }
4166
4167 RBASIC(obj)->flags |= FL_FINALIZE;
4168
4169 unsigned int lev = RB_GC_VM_LOCK();
4170
4171 if (st_lookup(finalizer_table, obj, &data)) {
4172 table = (VALUE)data;
4173 VALUE dup_table = rb_ary_dup(table);
4174
4175 RB_GC_VM_UNLOCK(lev);
4176 /* avoid duplicate block, table is usually small */
4177 {
4178 rb_len_t len = RARRAY_LEN(table);
4179 rb_len_t i;
4180
4181 for (i = 0; i < len; i++) {
4182 VALUE recv = RARRAY_AREF(dup_table, i);
4183 if (rb_equal(recv, block)) { // can't be called with VM lock held
4184 return recv;
4185 }
4186 }
4187 }
4188 lev = RB_GC_VM_LOCK();
4189 RB_GC_GUARD(dup_table);
4190
4191 rb_ary_push(table, block);
4192 }
4193 else {
4194 table = rb_ary_new3(2, rb_obj_id(obj), block);
4195 rb_obj_hide(table);
4196 st_add_direct(finalizer_table, obj, table);
4197 }
4198
4199 RB_GC_VM_UNLOCK(lev);
4200
4201 return block;
4202}
4203
4204void
4205rb_gc_impl_undefine_finalizer(void *objspace_ptr, VALUE obj)
4206{
4207 rb_objspace_t *objspace = objspace_ptr;
4208
4209 GC_ASSERT(!OBJ_FROZEN(obj));
4210
4211 /* Symmetric with define. */
4212 if (GET_HEAP_OBJSPACE(obj) != objspace) {
4213 rb_raise(rb_eRactorIsolationError,
4214 "can not undefine a finalizer of an object of another Ractor");
4215 }
4216
4217 st_data_t data = obj;
4218
4219 int lev = RB_GC_VM_LOCK();
4220 st_delete(finalizer_table, &data, 0);
4221 RB_GC_VM_UNLOCK(lev);
4222
4223 FL_UNSET(obj, FL_FINALIZE);
4224}
4225
4226void
4227rb_gc_impl_copy_finalizer(void *objspace_ptr, VALUE dest, VALUE obj)
4228{
4229 /* Finalizers do not cross objspaces: a copy of another Ractor's object starts with
4230 * none (guards the public rb_gc_copy_finalizer C API; no in-tree caller crosses).
4231 * A same-objspace copy behaves as before. Table accessed under the VM lock. */
4232 rb_objspace_t *objspace = objspace_ptr;
4233 VALUE table;
4234 st_data_t data;
4235
4236 if (!FL_TEST(obj, FL_FINALIZE)) return;
4237 if (GET_HEAP_OBJSPACE(obj) != objspace) return;
4238
4239 int lev = RB_GC_VM_LOCK();
4240 if (RB_LIKELY(st_lookup(finalizer_table, obj, &data))) {
4241 table = rb_ary_dup((VALUE)data);
4242 RARRAY_ASET(table, 0, rb_obj_id(dest));
4243 st_insert(finalizer_table, dest, table);
4244 FL_SET(dest, FL_FINALIZE);
4245 }
4246 else {
4247 rb_bug("rb_gc_copy_finalizer: FL_FINALIZE set but not found in finalizer_table: %s", rb_obj_info(obj));
4248 }
4249 RB_GC_VM_UNLOCK(lev);
4250}
4251
4252static VALUE
4253get_final(rb_len_t i, void *data)
4254{
4255 VALUE table = (VALUE)data;
4256
4257 return RARRAY_AREF(table, i + 1);
4258}
4259
4260static void
4261run_final(rb_objspace_t *objspace, VALUE zombie)
4262{
4263 if (RZOMBIE(zombie)->dfree) {
4264 RZOMBIE(zombie)->dfree(RZOMBIE(zombie)->data);
4265 }
4266
4267 st_data_t key = (st_data_t)zombie;
4268 if (FL_TEST_RAW(zombie, FL_FINALIZE)) {
4269 FL_UNSET(zombie, FL_FINALIZE);
4270 st_data_t table;
4271 if (st_delete(finalizer_table, &key, &table)) {
4272 rb_gc_run_obj_finalizer(RARRAY_AREF(table, 0), RARRAY_LEN(table) - 1, get_final, (void *)table);
4273 }
4274 else {
4275 rb_bug("FL_FINALIZE flag is set, but finalizers are not found");
4276 }
4277 }
4278 else {
4279 GC_ASSERT(!st_lookup(finalizer_table, key, NULL));
4280 }
4281}
4282
4283static void
4284finalize_list(rb_objspace_t *objspace, VALUE zombie)
4285{
4286 while (zombie) {
4287 VALUE next_zombie;
4288 struct heap_page *page;
4289 rb_asan_unpoison_object(zombie, false);
4290 next_zombie = RZOMBIE(zombie)->next;
4291 page = GET_HEAP_PAGE(zombie);
4292
4293 run_final(objspace, zombie);
4294 {
4295 GC_ASSERT(BUILTIN_TYPE(zombie) == T_ZOMBIE);
4296 GC_ASSERT(page->heap->final_slots_count > 0);
4297 GC_ASSERT(page->final_slots > 0);
4298
4299 page->heap->final_slots_count--;
4300 page->final_slots--;
4301 page->free_slots++;
4302 RVALUE_AGE_SET_BITMAP(zombie, 0);
4303 heap_page_add_free_region(objspace, page, zombie);
4304 page->heap->total_freed_objects++;
4305 }
4306
4307 zombie = next_zombie;
4308 }
4309}
4310
4311static void
4312finalize_zombies(rb_objspace_t *objspace)
4313{
4314 VALUE zombie;
4315 while ((zombie = RUBY_ATOMIC_VALUE_EXCHANGE(heap_pages_deferred_final, 0)) != 0) {
4316 finalize_list(objspace, zombie);
4317 }
4318}
4319
4320static void
4321finalize_deferred(rb_objspace_t *objspace)
4322{
4323 rb_gc_set_pending_interrupt();
4324 finalize_zombies(objspace);
4325 rb_gc_unset_pending_interrupt();
4326}
4327
4328static void
4329gc_finalize_deferred(void *dmy)
4330{
4331 /* One postponed job is shared by every objspace: the preregistration table only
4332 * holds about 32 entries and Ractors are created continuously. A deferred finalizer
4333 * belongs to the objspace of the thread that ran the job, i.e. the current one. */
4334 rb_objspace_t *objspace = rb_gc_get_objspace();
4335 if (RUBY_ATOMIC_EXCHANGE(finalizing, 1)) return;
4336
4337 finalize_deferred(objspace);
4338 RUBY_ATOMIC_SET(finalizing, 0);
4339}
4340
4341static void
4342gc_finalize_deferred_register(rb_objspace_t *objspace)
4343{
4344 /* Enqueue gc_finalize_deferred on this objspace's owning Ractor. A global GC can
4345 * defer a foreign objspace's finalizers, and those must run on their owner rather
4346 * than on the driver. */
4347 rb_gc_trigger_finalize_deferred(objspace, objspace->finalize_deferred_pjob);
4348}
4349
4350static int pop_mark_stack(mark_stack_t *stack, VALUE *data);
4351
4352/* Throw away an unfinished incremental mark and leave the objspace in gc_mode_none. The
4353 * mark bits the partial mark set stay behind, so the caller must clear them before the
4354 * heap is collected again. */
4355static void
4356gc_abort_incremental_marking(rb_objspace_t *objspace)
4357{
4358 GC_ASSERT(is_incremental_marking(objspace));
4359
4360 VALUE obj;
4361 while (pop_mark_stack(&objspace->mark_stack, &obj));
4362
4363 /* gc_grey records the weak references it greys for gc_marks_finish to resolve; this
4364 * cycle never reaches it, and the entries would outlive their objects. */
4365 rb_darray_clear(objspace->weak_references);
4366
4367 gc_set_incremental_marking(objspace, FALSE);
4368 gc_mode_set(objspace, gc_mode_none);
4369}
4370
4371static void
4372gc_abort(void *objspace_ptr)
4373{
4374 rb_objspace_t *objspace = objspace_ptr;
4375
4376 if (is_incremental_marking(objspace)) {
4377 gc_abort_incremental_marking(objspace);
4378 }
4379
4380 if (is_lazy_sweeping(objspace)) {
4381 objspace->sweeping_heap_count = 0;
4382 for (int i = 0; i < HEAP_COUNT; i++) {
4383 rb_heap_t *heap = &heaps[i];
4384
4385 heap->sweeping_page = NULL;
4386 struct heap_page *page = NULL;
4387
4388 ccan_list_for_each(&heap->pages, page, page_node) {
4389 page->flags.before_sweep = false;
4390 }
4391 }
4392 }
4393
4394 for (int i = 0; i < HEAP_COUNT; i++) {
4395 rb_heap_t *heap = &heaps[i];
4396 gc_bitmaps_clear(objspace, heap, false);
4397 }
4398
4399 gc_mode_set(objspace, gc_mode_none);
4400}
4401
4402#if VERIFY_FREE_SIZE
4403# ifdef RB_THREAD_LOCAL_SPECIFIER
4404# define GC_FREEING_OBJ_TLS RB_THREAD_LOCAL_SPECIFIER
4405# else
4406# define GC_FREEING_OBJ_TLS
4407# endif
4408
4409static GC_FREEING_OBJ_TLS VALUE gc_freeing_obj;
4410
4411/* Remember what we are tearing down so that a bad xfree() underneath can name
4412 * the object and not just the buffer. Saved and restored because a dfree
4413 * callback can free another object. */
4414static bool
4415gc_obj_free(void *objspace, VALUE obj)
4416{
4417 VALUE prev = gc_freeing_obj;
4418 gc_freeing_obj = obj;
4419
4420 bool freed = rb_gc_obj_free(objspace, obj);
4421
4422 gc_freeing_obj = prev;
4423 return freed;
4424}
4425
4426static const char *
4427gc_freeing_obj_info(void)
4428{
4429 /* Not thread-local: only reachable from a rb_bug() path, where a second
4430 * thread racing us is already unrecoverable. */
4431 static char buf[128];
4432
4433 if (!gc_freeing_obj) return NULL;
4434
4435 snprintf(buf, sizeof(buf), "%p %s", (void *)gc_freeing_obj, rb_obj_info(gc_freeing_obj));
4436 return buf;
4437}
4438#else
4439# define gc_obj_free(objspace, obj) rb_gc_obj_free((objspace), (obj))
4440# define gc_freeing_obj_info() NULL
4441#endif
4442
4443void
4444rb_gc_impl_shutdown_free_objects(void *objspace_ptr)
4445{
4446 rb_objspace_t *objspace = objspace_ptr;
4447
4448 for (size_t i = 0; i < rb_darray_size(objspace->heap_pages.sorted); i++) {
4449 struct heap_page *page = rb_darray_get(objspace->heap_pages.sorted, i);
4450 short stride = page->slot_size;
4451
4452 uintptr_t p = (uintptr_t)page->start;
4453 uintptr_t pend = p + page->total_slots * stride;
4454 for (; p < pend; p += stride) {
4455 VALUE vp = (VALUE)p;
4456 asan_unpoisoning_object(vp) {
4457 if (RB_BUILTIN_TYPE(vp) != T_NONE) {
4458 rb_gc_obj_free_vm_weak_references(vp);
4459 if (gc_obj_free(objspace, vp)) {
4460 RBASIC(vp)->flags = 0;
4461 }
4462 }
4463 }
4464 }
4465 }
4466}
4467
4468static int
4469rb_gc_impl_shutdown_call_finalizer_i(st_data_t key, st_data_t val, st_data_t _data)
4470{
4471 VALUE obj = (VALUE)key;
4472 VALUE table = (VALUE)val;
4473
4474 GC_ASSERT(RB_FL_TEST(obj, FL_FINALIZE));
4475 GC_ASSERT(RB_BUILTIN_TYPE(val) == T_ARRAY);
4476
4477 rb_gc_run_obj_finalizer(RARRAY_AREF(table, 0), RARRAY_LEN(table) - 1, get_final, (void *)table);
4478
4479 /* obj may be a poisoned zombie */
4480 asan_unpoisoning_object(obj) {
4481 FL_UNSET(obj, FL_FINALIZE);
4482 }
4483
4484 return ST_DELETE;
4485}
4486
4487void
4488rb_gc_impl_shutdown_call_finalizer(void *objspace_ptr)
4489{
4490 rb_objspace_t *objspace = objspace_ptr;
4491
4492#if RGENGC_CHECK_MODE >= 2
4493 gc_verify_internal_consistency(objspace);
4494#endif
4495
4496 /* prohibit incremental GC */
4497 objspace->flags.dont_incremental = 1;
4498
4499 if (RUBY_ATOMIC_EXCHANGE(finalizing, 1)) {
4500 /* Abort incremental marking and lazy sweeping to speed up shutdown. */
4501 gc_abort(objspace);
4502 dont_gc_on();
4503 return;
4504 }
4505
4506 while (finalizer_table->num_entries) {
4507 st_foreach(finalizer_table, rb_gc_impl_shutdown_call_finalizer_i, 0);
4508 }
4509
4510 /* run finalizers */
4511 finalize_deferred(objspace);
4512 GC_ASSERT(heap_pages_deferred_final == 0);
4513
4514 /* Deferred non-thread-safe frees: their objects are long gone, so the object walk
4515 * below will not reach them. Reap them here. */
4516 gc_tdata_unsafe_drain_objspaces(&objspace, 1);
4517
4518 /* Abort incremental marking and lazy sweeping to speed up shutdown. */
4519 gc_abort(objspace);
4520
4521 /* prohibit GC because force T_DATA finalizers can break an object graph consistency */
4522 dont_gc_on();
4523
4524 /* running data/file finalizers are part of garbage collection */
4525 unsigned int lock_lev;
4526 gc_enter(objspace, gc_enter_event_finalizer, &lock_lev);
4527
4528 /* run data/file object's finalizers */
4529 for (size_t i = 0; i < rb_darray_size(objspace->heap_pages.sorted); i++) {
4530 struct heap_page *page = rb_darray_get(objspace->heap_pages.sorted, i);
4531 short stride = page->slot_size;
4532
4533 uintptr_t p = (uintptr_t)page->start;
4534 uintptr_t pend = p + page->total_slots * stride;
4535 for (; p < pend; p += stride) {
4536 VALUE vp = (VALUE)p;
4537 asan_unpoisoning_object(vp) {
4538 if (rb_gc_shutdown_call_finalizer_p(vp)) {
4539 rb_gc_obj_free_vm_weak_references(vp);
4540 if (gc_obj_free(objspace, vp)) {
4541 RBASIC(vp)->flags = 0;
4542 }
4543 }
4544 }
4545 }
4546 }
4547
4548 gc_exit(objspace, gc_enter_event_finalizer, &lock_lev);
4549
4550 finalize_zombies(objspace);
4551
4552 st_free_table(finalizer_table);
4553 finalizer_table = 0;
4554 RUBY_ATOMIC_SET(finalizing, 0);
4555}
4556
4557void
4558rb_gc_impl_each_object(void *objspace_ptr, void (*func)(VALUE obj, void *data), void *data)
4559{
4560 rb_objspace_t *objspace = objspace_ptr;
4561
4562 for (size_t i = 0; i < rb_darray_size(objspace->heap_pages.sorted); i++) {
4563 struct heap_page *page = rb_darray_get(objspace->heap_pages.sorted, i);
4564 short stride = page->slot_size;
4565
4566 uintptr_t p = (uintptr_t)page->start;
4567 uintptr_t pend = p + page->total_slots * stride;
4568 for (; p < pend; p += stride) {
4569 VALUE obj = (VALUE)p;
4570
4571 asan_unpoisoning_object(obj) {
4572 func(obj, data);
4573 }
4574 }
4575 }
4576}
4577
4578/*
4579 ------------------------ Garbage Collection ------------------------
4580*/
4581
4582/* Sweeping */
4583
4584static size_t
4585objspace_available_slots(rb_objspace_t *objspace)
4586{
4587 size_t total_slots = 0;
4588 for (int i = 0; i < HEAP_COUNT; i++) {
4589 rb_heap_t *heap = &heaps[i];
4590 total_slots += heap->total_slots;
4591 }
4592 return total_slots;
4593}
4594
4595static size_t
4596objspace_live_slots(rb_objspace_t *objspace)
4597{
4598 return total_allocated_objects(objspace) - total_freed_objects(objspace) - total_final_slots_count(objspace);
4599}
4600
4601static size_t
4602objspace_free_slots(rb_objspace_t *objspace)
4603{
4604 return objspace_available_slots(objspace) - objspace_live_slots(objspace) - total_final_slots_count(objspace);
4605}
4606
4607static void
4608gc_setup_mark_bits(struct heap_page *page)
4609{
4610 /* copy oldgen bitmap to mark bitmap */
4611 memcpy(&page->mark_bits[0], &page->uncollectible_bits[0], HEAP_PAGE_BITMAP_SIZE);
4612}
4613
4614static int gc_is_moveable_obj(rb_objspace_t *objspace, VALUE obj);
4615static VALUE gc_move(rb_objspace_t *objspace, VALUE scan, VALUE free, struct heap_page *src_page, struct heap_page *dest_page);
4616
4617#if defined(_WIN32)
4618enum {HEAP_PAGE_LOCK = PAGE_NOACCESS, HEAP_PAGE_UNLOCK = PAGE_READWRITE};
4619
4620static BOOL
4621protect_page_body(struct heap_page_body *body, DWORD protect)
4622{
4623 DWORD old_protect;
4624 return VirtualProtect(body, HEAP_PAGE_SIZE, protect, &old_protect) != 0;
4625}
4626#elif defined(__wasi__)
4627// wasi-libc's mprotect emulation does not support PROT_NONE
4628enum {HEAP_PAGE_LOCK, HEAP_PAGE_UNLOCK};
4629#define protect_page_body(body, protect) 1
4630#else
4631enum {HEAP_PAGE_LOCK = PROT_NONE, HEAP_PAGE_UNLOCK = PROT_READ | PROT_WRITE};
4632#define protect_page_body(body, protect) !mprotect((body), HEAP_PAGE_SIZE, (protect))
4633#endif
4634
4635static void
4636lock_page_body(rb_objspace_t *objspace, struct heap_page_body *body)
4637{
4638 if (!protect_page_body(body, HEAP_PAGE_LOCK)) {
4639 rb_bug("Couldn't protect page %p, errno: %s", (void *)body, strerror(errno));
4640 }
4641 else {
4642 gc_report(5, objspace, "Protecting page in move %p\n", (void *)body);
4643 }
4644}
4645
4646static void
4647unlock_page_body(rb_objspace_t *objspace, struct heap_page_body *body)
4648{
4649 if (!protect_page_body(body, HEAP_PAGE_UNLOCK)) {
4650 rb_bug("Couldn't unprotect page %p, errno: %s", (void *)body, strerror(errno));
4651 }
4652 else {
4653 gc_report(5, objspace, "Unprotecting page in move %p\n", (void *)body);
4654 }
4655}
4656
4657static uintptr_t
4658heap_page_alloc_slot_from_region(struct heap_page *free_page)
4659{
4660 asan_unlock_freelist(free_page);
4661 struct free_region *region = free_page->free_region;
4662 asan_lock_freelist(free_page);
4663
4664 if (region == NULL) {
4665 return 0;
4666 }
4667
4668 rb_asan_unpoison_object((VALUE)region, false);
4669 GC_ASSERT(RB_TYPE_P((VALUE)region, T_NONE));
4670 uintptr_t dest = (uintptr_t)region;
4671 uintptr_t region_end = region->end;
4672 struct free_region *next = region->next;
4673
4674 uintptr_t new_start = dest + free_page->slot_size;
4675
4676 asan_unlock_freelist(free_page);
4677 if (new_start < region_end) {
4678 VALUE next_start = (VALUE)new_start;
4679 rb_asan_unpoison_object(next_start, false);
4680 struct free_region *new_region = (struct free_region *)new_start;
4681 new_region->flags = 0;
4682 new_region->end = region_end;
4683 new_region->next = next;
4684 rb_asan_poison_object(next_start);
4685 free_page->free_region = new_region;
4686 }
4687 else {
4688 free_page->free_region = next;
4689 }
4690 asan_lock_freelist(free_page);
4691
4692 return dest;
4693}
4694
4695static bool
4696try_move(rb_objspace_t *objspace, rb_heap_t *heap, struct heap_page *free_page, VALUE src)
4697{
4698 GC_ASSERT(gc_is_moveable_obj(objspace, src));
4699
4700 struct heap_page *src_page = GET_HEAP_PAGE(src);
4701 if (!free_page) {
4702 return false;
4703 }
4704
4705 /* We should return true if either src is successfully moved, or src is
4706 * unmoveable. A false return will cause the sweeping cursor to be
4707 * incremented to the next page, and src will attempt to move again */
4708 GC_ASSERT(RVALUE_MARKED(objspace, src));
4709
4710 uintptr_t dest_slot = heap_page_alloc_slot_from_region(free_page);
4711 if (dest_slot == 0) {
4712 return false;
4713 }
4714 VALUE dest = (VALUE)dest_slot;
4715
4716 GC_ASSERT(RB_BUILTIN_TYPE(dest) == T_NONE);
4717
4718 if (src_page->slot_size > free_page->slot_size) {
4719 objspace->rcompactor.moved_down_count_table[BUILTIN_TYPE(src)]++;
4720 }
4721 else if (free_page->slot_size > src_page->slot_size) {
4722 objspace->rcompactor.moved_up_count_table[BUILTIN_TYPE(src)]++;
4723 }
4724 objspace->rcompactor.moved_count_table[BUILTIN_TYPE(src)]++;
4725 objspace->rcompactor.total_moved++;
4726
4727 gc_move(objspace, src, dest, src_page, free_page);
4728 gc_pin(objspace, src);
4729 free_page->free_slots--;
4730
4731 return true;
4732}
4733
4734static void
4735gc_unprotect_pages(rb_objspace_t *objspace, rb_heap_t *heap)
4736{
4737 struct heap_page *cursor = heap->compact_cursor;
4738
4739 while (cursor) {
4740 unlock_page_body(objspace, cursor->body);
4741 cursor = ccan_list_next(&heap->pages, cursor, page_node);
4742 }
4743}
4744
4745static void gc_update_references(rb_objspace_t *objspace);
4746static void gc_update_references_heap(rb_objspace_t *objspace);
4747static void gc_update_references_global(rb_objspace_t *objspace);
4748#if GC_CAN_COMPILE_COMPACTION
4749static void invalidate_moved_page(rb_objspace_t *objspace, struct heap_page *page);
4750#endif
4751
4752#if defined(__MINGW32__) || defined(_WIN32)
4753# define GC_COMPACTION_SUPPORTED 1
4754#else
4755/* If not MinGW, Windows, or does not have mmap, we cannot use mprotect for
4756 * the read barrier, so we must disable compaction. */
4757# define GC_COMPACTION_SUPPORTED (GC_CAN_COMPILE_COMPACTION && HEAP_PAGE_ALLOC_USE_MMAP)
4758#endif
4759
4760#if GC_CAN_COMPILE_COMPACTION
4761static void
4762read_barrier_handler(uintptr_t address)
4763{
4764 rb_objspace_t *objspace = (rb_objspace_t *)rb_gc_get_objspace();
4765
4766 struct heap_page_body *page_body = GET_PAGE_BODY(address);
4767
4768 /* If the page_body is NULL, then mprotect cannot handle it and will crash
4769 * with "Cannot allocate memory". */
4770 if (page_body == NULL) {
4771 rb_bug("read_barrier_handler: segmentation fault at %p", (void *)address);
4772 }
4773
4774 int lev = RB_GC_VM_LOCK();
4775 {
4776 unlock_page_body(objspace, page_body);
4777
4778 objspace->profile.read_barrier_faults++;
4779
4780 invalidate_moved_page(objspace, GET_HEAP_PAGE(address));
4781 }
4782 RB_GC_VM_UNLOCK(lev);
4783}
4784#endif
4785
4786#if !GC_CAN_COMPILE_COMPACTION
4787static void
4788uninstall_handlers(void)
4789{
4790 /* no-op */
4791}
4792
4793static void
4794install_handlers(void)
4795{
4796 /* no-op */
4797}
4798#elif defined(_WIN32)
4799static LPTOP_LEVEL_EXCEPTION_FILTER old_handler;
4800typedef void (*signal_handler)(int);
4801static signal_handler old_sigsegv_handler;
4802
4803static LONG WINAPI
4804read_barrier_signal(EXCEPTION_POINTERS *info)
4805{
4806 /* EXCEPTION_ACCESS_VIOLATION is what's raised by access to protected pages */
4807 if (info->ExceptionRecord->ExceptionCode == EXCEPTION_ACCESS_VIOLATION) {
4808 /* > The second array element specifies the virtual address of the inaccessible data.
4809 * https://docs.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-exception_record
4810 *
4811 * Use this address to invalidate the page */
4812 read_barrier_handler((uintptr_t)info->ExceptionRecord->ExceptionInformation[1]);
4813 return EXCEPTION_CONTINUE_EXECUTION;
4814 }
4815 else {
4816 return EXCEPTION_CONTINUE_SEARCH;
4817 }
4818}
4819
4820static void
4821uninstall_handlers(void)
4822{
4823 signal(SIGSEGV, old_sigsegv_handler);
4824 SetUnhandledExceptionFilter(old_handler);
4825}
4826
4827static void
4828install_handlers(void)
4829{
4830 /* Remove SEGV handler so that the Unhandled Exception Filter handles it */
4831 old_sigsegv_handler = signal(SIGSEGV, NULL);
4832 /* Unhandled Exception Filter has access to the violation address similar
4833 * to si_addr from sigaction */
4834 old_handler = SetUnhandledExceptionFilter(read_barrier_signal);
4835}
4836#else
4837static struct sigaction old_sigbus_handler;
4838static struct sigaction old_sigsegv_handler;
4839
4840#ifdef HAVE_MACH_TASK_EXCEPTION_PORTS
4841static exception_mask_t old_exception_masks[32];
4842static mach_port_t old_exception_ports[32];
4843static exception_behavior_t old_exception_behaviors[32];
4844static thread_state_flavor_t old_exception_flavors[32];
4845static mach_msg_type_number_t old_exception_count;
4846
4847static void
4848disable_mach_bad_access_exc(void)
4849{
4850 old_exception_count = sizeof(old_exception_masks) / sizeof(old_exception_masks[0]);
4851 task_swap_exception_ports(
4852 mach_task_self(), EXC_MASK_BAD_ACCESS,
4853 MACH_PORT_NULL, EXCEPTION_DEFAULT, 0,
4854 old_exception_masks, &old_exception_count,
4855 old_exception_ports, old_exception_behaviors, old_exception_flavors
4856 );
4857}
4858
4859static void
4860restore_mach_bad_access_exc(void)
4861{
4862 for (mach_msg_type_number_t i = 0; i < old_exception_count; i++) {
4863 task_set_exception_ports(
4864 mach_task_self(),
4865 old_exception_masks[i], old_exception_ports[i],
4866 old_exception_behaviors[i], old_exception_flavors[i]
4867 );
4868 }
4869}
4870#endif
4871
4872#if defined(HAVE_PTHREAD_SIGMASK)
4873# define gc_sigmask pthread_sigmask
4874#else
4875# define gc_sigmask sigprocmask
4876#endif
4877
4878static void
4879read_barrier_signal(int sig, siginfo_t *info, void *data)
4880{
4881 // setup SEGV/BUS handlers for errors
4882 struct sigaction prev_sigbus, prev_sigsegv;
4883 sigaction(SIGBUS, &old_sigbus_handler, &prev_sigbus);
4884 sigaction(SIGSEGV, &old_sigsegv_handler, &prev_sigsegv);
4885
4886 // enable SIGBUS/SEGV
4887 sigset_t set, prev_set;
4888 sigemptyset(&set);
4889 sigaddset(&set, SIGBUS);
4890 sigaddset(&set, SIGSEGV);
4891 gc_sigmask(SIG_UNBLOCK, &set, &prev_set);
4892#ifdef HAVE_MACH_TASK_EXCEPTION_PORTS
4893 disable_mach_bad_access_exc();
4894#endif
4895 // run handler
4896 read_barrier_handler((uintptr_t)info->si_addr);
4897
4898 // reset SEGV/BUS handlers
4899#ifdef HAVE_MACH_TASK_EXCEPTION_PORTS
4900 restore_mach_bad_access_exc();
4901#endif
4902 sigaction(SIGBUS, &prev_sigbus, NULL);
4903 sigaction(SIGSEGV, &prev_sigsegv, NULL);
4904 gc_sigmask(SIG_SETMASK, &prev_set, NULL);
4905}
4906
4907static void
4908uninstall_handlers(void)
4909{
4910#ifdef HAVE_MACH_TASK_EXCEPTION_PORTS
4911 restore_mach_bad_access_exc();
4912#endif
4913 sigaction(SIGBUS, &old_sigbus_handler, NULL);
4914 sigaction(SIGSEGV, &old_sigsegv_handler, NULL);
4915}
4916
4917static void
4918install_handlers(void)
4919{
4920 struct sigaction action;
4921 memset(&action, 0, sizeof(struct sigaction));
4922 sigemptyset(&action.sa_mask);
4923 action.sa_sigaction = read_barrier_signal;
4924 action.sa_flags = SA_SIGINFO | SA_ONSTACK;
4925
4926 sigaction(SIGBUS, &action, &old_sigbus_handler);
4927 sigaction(SIGSEGV, &action, &old_sigsegv_handler);
4928#ifdef HAVE_MACH_TASK_EXCEPTION_PORTS
4929 disable_mach_bad_access_exc();
4930#endif
4931}
4932#endif
4933
4934static void
4935gc_compact_finish(rb_objspace_t *objspace)
4936{
4937 for (int i = 0; i < HEAP_COUNT; i++) {
4938 rb_heap_t *heap = &heaps[i];
4939 gc_unprotect_pages(objspace, heap);
4940 }
4941
4942 if (!global_objspace->global_gc.compacting) uninstall_handlers();
4943
4944 if (global_objspace->global_gc.compacting) {
4945 /* In a compacting global GC this updates only this objspace's heap references;
4946 * gc_start_global sets during_reference_updating on every objspace (the
4947 * move-or-mark decision reads it via rb_gc_get_objspace()) and runs the
4948 * non-idempotent VM-global side (gc_update_references_global) once at the end. */
4949 gc_update_references_heap(objspace);
4950 }
4951 else {
4952 gc_update_references(objspace);
4953 }
4954 objspace->profile.compact_count++;
4955
4956 for (int i = 0; i < HEAP_COUNT; i++) {
4957 rb_heap_t *heap = &heaps[i];
4958 heap->compact_cursor = NULL;
4959 heap->free_pages = NULL;
4960 heap->compact_cursor_index = 0;
4961 }
4962
4963 if (gc_prof_enabled(objspace)) {
4964 gc_profile_record *record = gc_prof_record(objspace);
4965 record->moved_objects = objspace->rcompactor.total_moved - record->moved_objects;
4966 }
4967 if (!global_objspace->global_gc.compacting) objspace->flags.during_compacting = FALSE;
4968}
4969
4971 struct heap_page *page;
4972 int final_slots;
4973 int freed_slots;
4974 int empty_slots;
4975 /* Hoisted out of the per-slot pinned-free assert: too expensive for the sweep loop
4976 * as an external call. */
4977 const bool check_pinned_free;
4978 /* This is a parallel local sweep (multi-Ractor, not a global GC), so a non-thread-safe
4979 * T_DATA dfree must be deferred to the global GC or the postponed job rather than run here. */
4980 const bool defer_thread_unsafe_local_sweep;
4981 bool trigger_thread_unsafe_sweep_postponed_job;
4982
4983 struct free_region *free_region;
4984};
4985
4986/* NOTE: We must free the root fiber during postmortem collection, otherwise another Ractor
4987 * can collect the fiber through a major GC while we're still tearing it down. Once fibers are
4988 * THREAD_SAFE_FREE, we no longer need the root fiber condition as it will be guaranteed to be
4989 * collected during this time. */
4990static bool
4991gc_obj_defer_local_free_p(rb_objspace_t *objspace, VALUE obj)
4992{
4993 if (BUILTIN_TYPE(obj) != T_DATA) return false;
4994
4995 const rb_data_type_t *type = RTYPEDDATA_TYPE(obj);
4996 if (!rb_gc_data_type_deferred_free_p(type)) return false;
4997
4998 if (RTYPEDDATA_GET_DATA(obj) == NULL) return false;
4999
5000 if (type->flags & RUBY_TYPED_FREE_IMMEDIATELY) {
5001 if (objspace->flags.during_postmortem) {
5002 if (rb_fiber_current() == obj) {
5003 return false;
5004 }
5005 }
5006 return true;
5007 }
5008 else {
5009 return false;
5010 }
5011}
5012
5013static void gc_tdata_deferred_free_job(void *unused);
5014static void gc_tdata_deferred_free_pjob_ensure(void);
5015static unsigned int gc_during_gc_get(const rb_objspace_t *objspace);
5016static void gc_during_gc_set(rb_objspace_t *objspace, unsigned int v);
5017static void gc_global_snapshot_objspaces(void);
5018
5019static void
5020gc_tdata_deferred_free_pjob_ensure(void)
5021{
5022 if (global_objspace->tdata_deferred_free_pjob == POSTPONED_JOB_HANDLE_INVALID) {
5023 global_objspace->tdata_deferred_free_pjob =
5024 rb_postponed_job_preregister(0, gc_tdata_deferred_free_job, NULL);
5025 if (global_objspace->tdata_deferred_free_pjob == POSTPONED_JOB_HANDLE_INVALID) {
5026 rb_bug("Could not preregister postponed job for deferred T_DATA free");
5027 }
5028 }
5029}
5030
5031/* A terminating Ractor's postmortem collection runs on an EC whose stack is already
5032 * torn down: it never checks interrupts again, so a job triggered there is lost and no
5033 * later sweep can rediscover the entries. Hand those to the main Ractor. */
5034static void
5035gc_tdata_deferred_free_trigger(rb_objspace_t *objspace)
5036{
5037 if (objspace->flags.during_postmortem) {
5038 rb_gc_trigger_postponed_job_on_main(global_objspace->tdata_deferred_free_pjob);
5039 }
5040 else {
5041 rb_postponed_job_trigger(global_objspace->tdata_deferred_free_pjob);
5042 }
5043}
5044
5045static void
5046gc_tdata_unsafe_free_entry(const struct tdata_unsafe_free_entry *entry, bool embed_xfree)
5047{
5048 entry->dfree(entry->data);
5049 if (embed_xfree) {
5050 xfree(entry->data);
5051 }
5052}
5053
5054static void
5055tdata_unsafe_free_chunk_recycle(struct tdata_unsafe_free_chunk *chunk)
5056{
5057 if (global_objspace->tdata_unsafe_free_cache_len >= TDATA_UNSAFE_FREE_CACHE_MAX) {
5058 free(chunk);
5059 return;
5060 }
5061 tdata_unsafe_free_chunk_reset(chunk);
5062 chunk->next = global_objspace->tdata_unsafe_free_cache;
5063 rbimpl_atomic_ptr_store((volatile void **)&global_objspace->tdata_unsafe_free_cache, chunk,
5064 RBIMPL_ATOMIC_RELEASE);
5065 global_objspace->tdata_unsafe_free_cache_len++;
5066}
5067
5068static void
5069gc_tdata_unsafe_drain_chunk(struct tdata_unsafe_free_chunk *chunk)
5070{
5071 for (unsigned int i = 0; i < chunk->count; i++) {
5072 gc_tdata_unsafe_free_entry(&chunk->entries[i],
5073 (chunk->embed_xfree_bits >> i) & 1);
5074 }
5075 tdata_unsafe_free_chunk_recycle(chunk);
5076}
5077
5078/* Run every pending deferred free: the published chunks (which belong to no objspace)
5079 * plus the given objspaces' partial chunks. The caller must have stopped the world --
5080 * VM barrier held, or a single Ractor left in the process -- and must pass every live
5081 * objspace, since the pending count is zeroed here. (Shutdown is the one exception:
5082 * nothing reads the count afterwards.) */
5083static void
5084gc_tdata_unsafe_drain_objspaces(rb_objspace_t **objspaces, size_t n)
5085{
5086 struct tdata_unsafe_free_chunk *chunk =
5087 rbimpl_atomic_ptr_exchange((void **)&global_objspace->tdata_unsafe_free_published, NULL,
5088 RBIMPL_ATOMIC_ACQ_REL);
5089 while (chunk) {
5090 struct tdata_unsafe_free_chunk *next = chunk->next;
5091 gc_tdata_unsafe_drain_chunk(chunk);
5092 chunk = next;
5093 }
5094
5095 for (size_t i = 0; i < n; i++) {
5096 rb_objspace_t *os = objspaces[i];
5097 struct tdata_unsafe_free_chunk *partial = os->tdata_unsafe_free_chunk;
5098 if (partial) {
5099 os->tdata_unsafe_free_chunk = NULL;
5100 gc_tdata_unsafe_drain_chunk(partial);
5101 }
5102 }
5103
5104 rbimpl_atomic_size_exchange(&global_objspace->tdata_deferred_free_count, 0,
5105 RBIMPL_ATOMIC_RELAXED);
5106}
5107
5108/* Stop the world and run the dfree function for all deferred T_DATAs. */
5109static void
5110gc_tdata_unsafe_drain(void)
5111{
5112 unsigned int lev = RB_GC_VM_LOCK();
5113
5114 if (tdata_deferred_free_count_load() == 0) {
5115 RB_GC_VM_UNLOCK(lev);
5116 return;
5117 }
5118
5119 rb_gc_vm_barrier();
5120
5121 gc_global_snapshot_objspaces();
5122
5123 /* Set during_gc=TRUE and init vm_context for the CURRENT objspace only.
5124 * The no-alloc guard checks only the allocating (=current) objspace's during_gc,
5125 * and rb_gc_get_ec() reads only the current objspace's vm_context.ec. */
5126 rb_objspace_t *objspace = rb_gc_get_objspace();
5127 unsigned int saved_during_gc = gc_during_gc_get(objspace);
5128 dont_gc_on();
5129 rb_gc_initialize_vm_context(&objspace->vm_context);
5130 gc_during_gc_set(objspace, TRUE);
5131
5132 gc_tdata_unsafe_drain_objspaces(global_objspace->global_gc.objspaces,
5133 global_objspace->global_gc.n_objspaces);
5134
5135 gc_during_gc_set(objspace, saved_during_gc);
5136 dont_gc_off();
5137
5138 RB_GC_VM_UNLOCK(lev);
5139}
5140
5141static void
5142gc_tdata_deferred_free_job(void *unused)
5143{
5144 (void)unused;
5145
5146 size_t count = tdata_deferred_free_count_load();
5147 if (count == 0) return;
5148 if (count < TDATA_DEFERRED_FREE_THRESHOLD && !rb_gc_single_objspace_p()) return;
5149
5150 gc_tdata_unsafe_drain();
5151}
5152
5153static inline void
5154gc_sweep_register_free_slot(rb_objspace_t *objspace, struct heap_page *page, struct gc_sweep_context *ctx, uintptr_t p, short slot_size)
5155{
5156 rb_asan_unpoison_object(p, false);
5157 ((struct RBasic *)p)->flags = 0;
5158
5159 /* Keep a freed slot from carrying its old shareable and shref bits into the next
5160 * object born there; the actual clear happens per bitmap word at the end of
5161 * gc_sweep_page rather than per slot. */
5162
5163 struct free_region *existing_region = ctx->free_region;
5164 if (existing_region) rb_asan_unpoison_object((VALUE)existing_region, false);
5165
5166 if (RB_LIKELY(existing_region && p == existing_region->end)) {
5167 existing_region->end = p + slot_size;
5168 }
5169 else {
5170 struct free_region *free_region = (struct free_region *)p;
5171 free_region->end = p + slot_size;
5172 free_region->next = existing_region;
5173
5174 ctx->free_region = free_region;
5175 }
5176
5177 if (existing_region) rb_asan_poison_object((VALUE)existing_region);
5178 rb_asan_poison_object(p);
5179}
5180
5181static inline void
5182gc_sweep_plane(rb_objspace_t *objspace, rb_heap_t *heap, uintptr_t p, bits_t bitset, struct gc_sweep_context *ctx)
5183{
5184 struct heap_page *sweep_page = ctx->page;
5185 short slot_size = sweep_page->slot_size;
5186
5187 do {
5188 VALUE vp = (VALUE)p;
5189 GC_ASSERT(vp % sizeof(VALUE) == 0);
5190
5191 rb_asan_unpoison_object(vp, false);
5192 if (bitset & 1) {
5193 switch (BUILTIN_TYPE(vp)) {
5194 case T_MOVED:
5195 if (objspace->flags.during_compacting) {
5196 /* The sweep cursor shouldn't have made it to any
5197 * T_MOVED slots while the compact flag is enabled.
5198 * The sweep cursor and compact cursor move in
5199 * opposite directions, and when they meet references will
5200 * get updated and "during_compacting" should get disabled */
5201 rb_bug("T_MOVED shouldn't be seen until compaction is finished");
5202 }
5203 gc_report(3, objspace, "page_sweep: %s is freed\n", rb_obj_info(vp));
5204 ctx->empty_slots++;
5205 gc_sweep_register_free_slot(objspace, sweep_page, ctx, p, slot_size);
5206 break;
5207 case T_ZOMBIE:
5208 /* already counted */
5209 break;
5210 case T_NONE:
5211 ctx->empty_slots++; /* already freed */
5212 gc_sweep_register_free_slot(objspace, sweep_page, ctx, p, slot_size);
5213 break;
5214
5215 default:
5216#if RGENGC_CHECK_MODE
5217 /* A local GC must never free a pinned slot; a global GC may (its exact
5218 * mark collects dead shareable objects). Reading the bits here is
5219 * CHECK-only and still valid: the bulk clear runs after the free loop. */
5220 if (ctx->check_pinned_free &&
5221 (MARKED_IN_BITMAP(GET_HEAP_SHAREABLE_BITS(vp), vp) ||
5222 MARKED_IN_BITMAP(GET_HEAP_SHREF_BITS(vp), vp))) {
5223 rb_bug("page_sweep: freeing pinned slot %s (shareable=%d shref=%d single_now=%d)",
5224 rb_obj_info(vp),
5225 (int)!!MARKED_IN_BITMAP(GET_HEAP_SHAREABLE_BITS(vp), vp),
5226 (int)!!MARKED_IN_BITMAP(GET_HEAP_SHREF_BITS(vp), vp),
5227 (int)rb_gc_single_objspace_p());
5228 }
5229#endif
5230#if RGENGC_CHECK_MODE
5231 if (!is_full_marking(objspace)) {
5232 if (RVALUE_OLD_P(objspace, vp)) rb_bug("page_sweep: %p - old while minor GC.", (void *)p);
5233 if (RVALUE_REMEMBERED(objspace, vp)) rb_bug("page_sweep: %p - remembered.", (void *)p);
5234 }
5235#endif
5236
5237#if RGENGC_CHECK_MODE
5238#define CHECK(x) if (x(objspace, vp) != FALSE) rb_bug("obj_free: " #x "(%s) != FALSE", rb_obj_info(vp))
5239 CHECK(RVALUE_WB_UNPROTECTED);
5240 CHECK(RVALUE_MARKED);
5241 CHECK(RVALUE_MARKING);
5242 CHECK(RVALUE_UNCOLLECTIBLE);
5243#undef CHECK
5244#endif
5245
5246 if (!rb_gc_obj_needs_cleanup_p(vp)) {
5247 (void)VALGRIND_MAKE_MEM_UNDEFINED((void*)p, slot_size);
5248 gc_sweep_register_free_slot(objspace, sweep_page, ctx, p, slot_size);
5249 gc_report(3, objspace, "page_sweep: %s (fast path) is freed\n", rb_obj_info(vp));
5250 ctx->freed_slots++;
5251 }
5252 else {
5253 gc_report(2, objspace, "page_sweep: free %p\n", (void *)p);
5254
5255 if (RB_UNLIKELY(ctx->defer_thread_unsafe_local_sweep && gc_obj_defer_local_free_p(objspace, vp))) {
5256 /* Defer the dfree instead of running it here: it needs the world
5257 * stopped, which a parallel local sweep cannot give it. The slot is reusable
5258 * right away unless we had to create a zombie. */
5259 if (gc_defer_thread_unsafe_free(objspace, vp,
5260 &ctx->trigger_thread_unsafe_sweep_postponed_job)) {
5261 (void)VALGRIND_MAKE_MEM_UNDEFINED((void*)p, slot_size);
5262 gc_sweep_register_free_slot(objspace, sweep_page, ctx, p, slot_size);
5263 ctx->freed_slots++;
5264 }
5265 else {
5266 ctx->final_slots++;
5267 }
5268 break;
5269 }
5270 rb_gc_obj_free_vm_weak_references(vp);
5271 if (gc_obj_free(objspace, vp)) {
5272 (void)VALGRIND_MAKE_MEM_UNDEFINED((void*)p, slot_size);
5273 gc_sweep_register_free_slot(objspace, sweep_page, ctx, p, slot_size);
5274 gc_report(3, objspace, "page_sweep: %s is freed\n", rb_obj_info(vp));
5275 ctx->freed_slots++;
5276 }
5277 else {
5278 ctx->final_slots++;
5279 }
5280 }
5281 break;
5282 }
5283 }
5284 p += slot_size;
5285 bitset >>= 1;
5286 } while (bitset);
5287}
5288
5289static inline void
5290gc_sweep_page(rb_objspace_t *objspace, rb_heap_t *heap, struct gc_sweep_context *ctx)
5291{
5292 struct heap_page *sweep_page = ctx->page;
5293 GC_ASSERT(sweep_page->heap == heap);
5294
5295 uintptr_t p;
5296 bits_t *bits, bitset;
5297
5298 gc_report(2, objspace, "page_sweep: start.\n");
5299
5300#if RGENGC_CHECK_MODE
5301 if (!objspace->flags.immediate_sweep) {
5302 GC_ASSERT(sweep_page->flags.before_sweep == TRUE);
5303 }
5304#endif
5305 sweep_page->flags.before_sweep = FALSE;
5306 sweep_page->free_slots = 0;
5307
5308 asan_unlock_freelist(sweep_page);
5309 sweep_page->free_region = NULL;
5310 asan_lock_freelist(sweep_page);
5311 ctx->free_region = NULL;
5312
5313 p = (uintptr_t)sweep_page->start;
5314 bits = sweep_page->mark_bits;
5315 short slot_size = sweep_page->slot_size;
5316 int total_slots = sweep_page->total_slots;
5317 int bitmap_plane_count = CEILDIV(total_slots, BITS_BITLENGTH);
5318
5319 int out_of_range_bits = total_slots % BITS_BITLENGTH;
5320 if (out_of_range_bits != 0) {
5321 bits[bitmap_plane_count - 1] |= ~(((bits_t)1 << out_of_range_bits) - 1);
5322 }
5323
5324 // Clear wb_unprotected and age bits for all unmarked slots
5325 {
5326 bits_t *wb_unprotected_bits = sweep_page->wb_unprotected_bits;
5327 bits_t *age_bits = sweep_page->age_bits;
5328 for (int i = 0; i < bitmap_plane_count; i++) {
5329 bits_t unmarked = ~bits[i];
5330 wb_unprotected_bits[i] &= ~unmarked;
5331 age_bits[i * 2] &= ~unmarked;
5332 age_bits[i * 2 + 1] &= ~unmarked;
5333 }
5334 }
5335
5336 for (int i = 0; i < bitmap_plane_count; i++) {
5337 bitset = ~bits[i];
5338 if (bitset) {
5339 gc_sweep_plane(objspace, heap, p, bitset, ctx);
5340 }
5341 p += BITS_BITLENGTH * slot_size;
5342 }
5343
5344 /* Bulk-clear the freed slots' shareable and shref bits before the freelist is
5345 * published, so a reused slot is clean. Freed slots are exactly the unmarked ones,
5346 * so `bits &= mark_bits` keeps live shareable objects (which must stay pinned) and
5347 * drops the rest. Pages with neither bit are skipped. */
5348 if (sweep_page->flags.has_shareable_objects || sweep_page->flags.has_shref_objects) {
5349 bits_t *shareable_bits = sweep_page->shareable_bits;
5350 bits_t *shref_bits = sweep_page->shref_bits;
5351 bits_t sh = 0, sr = 0;
5352 for (int i = 0; i < bitmap_plane_count; i++) {
5353 shareable_bits[i] &= bits[i];
5354 shref_bits[i] &= bits[i];
5355 sh |= shareable_bits[i];
5356 sr |= shref_bits[i];
5357 }
5358 if (!sh) sweep_page->flags.has_shareable_objects = FALSE;
5359 if (!sr) sweep_page->flags.has_shref_objects = FALSE;
5360 }
5361
5362 asan_unlock_freelist(sweep_page);
5363 sweep_page->free_region = ctx->free_region;
5364 asan_lock_freelist(sweep_page);
5365
5366 if (!heap->compact_cursor) {
5367 gc_setup_mark_bits(sweep_page);
5368 }
5369
5370#if GC_PROFILE_MORE_DETAIL
5371 if (gc_prof_enabled(objspace)) {
5372 gc_profile_record *record = gc_prof_record(objspace);
5373 record->removing_objects += ctx->final_slots + ctx->freed_slots;
5374 record->empty_objects += ctx->empty_slots;
5375 }
5376#endif
5377 if (0) fprintf(stderr, "gc_sweep_page(%"PRIdSIZE"): total_slots: %d, freed_slots: %d, empty_slots: %d, final_slots: %d\n",
5378 rb_gc_count(),
5379 sweep_page->total_slots,
5380 ctx->freed_slots, ctx->empty_slots, ctx->final_slots);
5381
5382 sweep_page->free_slots += ctx->freed_slots + ctx->empty_slots;
5383 sweep_page->heap->total_freed_objects += ctx->freed_slots;
5384
5385 if (heap_pages_deferred_final && !finalizing) {
5386 gc_finalize_deferred_register(objspace);
5387 }
5388
5389#if RGENGC_CHECK_MODE
5390 int region_slots = 0;
5391 asan_unlock_freelist(sweep_page);
5392 struct free_region *region = sweep_page->free_region;
5393 while (region) {
5394 rb_asan_unpoison_object((VALUE)region, false);
5395 GC_ASSERT(RB_TYPE_P((VALUE)region, T_NONE));
5396 uintptr_t region_start = (uintptr_t)region;
5397 uintptr_t region_end = region->end;
5398 struct free_region *next = region->next;
5399 rb_asan_poison_object((VALUE)region);
5400
5401 GC_ASSERT(region_end > region_start);
5402 GC_ASSERT((region_end - region_start) % slot_size == 0);
5403 region_slots += (int)((region_end - region_start) / slot_size);
5404
5405 region = next;
5406 }
5407 asan_lock_freelist(sweep_page);
5408 if (region_slots != sweep_page->free_slots) {
5409 rb_bug("inconsistent free region slots: expected %d but was %d", sweep_page->free_slots, region_slots);
5410 }
5411#endif
5412
5413 gc_report(2, objspace, "page_sweep: end.\n");
5414}
5415
5416static const char *
5417gc_mode_name(enum gc_mode mode)
5418{
5419 switch (mode) {
5420 case gc_mode_none: return "none";
5421 case gc_mode_marking: return "marking";
5422 case gc_mode_sweeping: return "sweeping";
5423 case gc_mode_compacting: return "compacting";
5424 default: rb_bug("gc_mode_name: unknown mode: %d", (int)mode);
5425 }
5426}
5427
5428static void
5429gc_mode_transition(rb_objspace_t *objspace, enum gc_mode mode)
5430{
5431#if RGENGC_CHECK_MODE
5432 enum gc_mode prev_mode = gc_mode(objspace);
5433 switch (prev_mode) {
5434 case gc_mode_none:
5435 /* A global GC marks every objspace as one heap (mark_roots on the driver), so an
5436 * individual objspace's mode stays `none` during that mark; the sweep inside the
5437 * barrier then makes the legitimate none -> sweeping transition. */
5438 GC_ASSERT(mode == gc_mode_marking ||
5439 (objspace->flags.during_global_gc && mode == gc_mode_sweeping));
5440 break;
5441 case gc_mode_marking: GC_ASSERT(mode == gc_mode_sweeping); break;
5442 case gc_mode_sweeping: GC_ASSERT(mode == gc_mode_none || mode == gc_mode_compacting); break;
5443 case gc_mode_compacting: GC_ASSERT(mode == gc_mode_none); break;
5444 }
5445#endif
5446 if (0) fprintf(stderr, "gc_mode_transition: %s->%s\n", gc_mode_name(gc_mode(objspace)), gc_mode_name(mode));
5447 gc_mode_set(objspace, mode);
5448}
5449
5450static void
5451heap_page_flush_alloc_regions(struct heap_page *page, rb_heap_t *heap)
5452{
5453 struct free_region *chain = heap->newobj.alloc_next_region;
5454
5455 if (heap->newobj.alloc_cursor < heap->newobj.alloc_cursor_end) {
5456 VALUE start = (VALUE)heap->newobj.alloc_cursor;
5457 rb_asan_unpoison_object(start, false);
5458 struct free_region *remnant = (struct free_region *)start;
5459 remnant->flags = 0;
5460 remnant->end = heap->newobj.alloc_cursor_end;
5461 remnant->next = chain;
5462 rb_asan_poison_object(start);
5463 chain = remnant;
5464 }
5465
5466 if (chain) {
5467 asan_unlock_freelist(page);
5468 if (page->free_region) {
5469 struct free_region *p = page->free_region;
5470 rb_asan_unpoison_object((VALUE)p, false);
5471 while (p->next) {
5472 struct free_region *prev = p;
5473 p = p->next;
5474 rb_asan_poison_object((VALUE)prev);
5475 rb_asan_unpoison_object((VALUE)p, false);
5476 }
5477 p->next = chain;
5478 rb_asan_poison_object((VALUE)p);
5479 }
5480 else {
5481 page->free_region = chain;
5482 }
5483 asan_lock_freelist(page);
5484 }
5485}
5486
5487static void
5488gc_sweep_start_heap(rb_objspace_t *objspace, rb_heap_t *heap)
5489{
5490 heap->sweeping_page = ccan_list_top(&heap->pages, struct heap_page, page_node);
5491 if (heap->sweeping_page) {
5492 objspace->sweeping_heap_count++;
5493 }
5494 heap->free_pages = NULL;
5495 heap->pooled_pages = NULL;
5496 if (!objspace->flags.immediate_sweep) {
5497 struct heap_page *page = NULL;
5498
5499 ccan_list_for_each(&heap->pages, page, page_node) {
5500 page->flags.before_sweep = TRUE;
5501 }
5502 }
5503}
5504
5505#if GC_CAN_COMPILE_COMPACTION
5506static void gc_sort_heap_by_compare_func(rb_objspace_t *objspace, gc_compact_compare_func compare_func);
5507static int compare_pinned_slots(const void *left, const void *right, void *d);
5508#endif
5509
5510/* Return the current allocation page and freelist to their pages, so the sweeper sees a
5511 * consistent heap. */
5512static void
5513heap_alloc_state_clear(rb_objspace_t *objspace)
5514{
5515 objspace->incremental_mark_step_allocated_slots = 0;
5516
5517 for (size_t heap_idx = 0; heap_idx < HEAP_COUNT; heap_idx++) {
5518 rb_heap_t *heap = &heaps[heap_idx];
5519
5520 struct heap_page *page = heap->newobj.alloc_using_page;
5521 RUBY_DEBUG_LOG("heap alloc_using_page:%p cursor:%p", (void *)page, (void *)heap->newobj.alloc_cursor);
5522
5523 if (page) {
5524 heap_page_flush_alloc_regions(page, heap);
5525 }
5526
5527 heap->newobj.alloc_using_page = NULL;
5528 heap->newobj.alloc_cursor = 0;
5529 heap->newobj.alloc_cursor_end = 0;
5530 heap->newobj.alloc_next_region = NULL;
5531 }
5532}
5533
5534static void
5535gc_sweep_freeobj_hooks_page(rb_objspace_t *objspace, struct heap_page *page)
5536{
5537 bits_t *bits = page->mark_bits;
5538 uintptr_t p = (uintptr_t)page->start;
5539 short slot_size = page->slot_size;
5540 int total_slots = page->total_slots;
5541 int bitmap_plane_count = CEILDIV(total_slots, BITS_BITLENGTH);
5542
5543 int out_of_range_bits = total_slots % BITS_BITLENGTH;
5544 bits_t last_plane_mask = (out_of_range_bits != 0)
5545 ? ~(((bits_t)1 << out_of_range_bits) - 1)
5546 : 0;
5547
5548 for (int j = 0; j < bitmap_plane_count; j++) {
5549 bits_t bitset = ~bits[j];
5550 if (j == bitmap_plane_count - 1) {
5551 bitset &= ~last_plane_mask;
5552 }
5553
5554 uintptr_t pp = p;
5555 while (bitset) {
5556 if (bitset & 1) {
5557 VALUE vp = (VALUE)pp;
5558 asan_unpoisoning_object(vp) {
5559 switch (BUILTIN_TYPE(vp)) {
5560 case T_NONE:
5561 case T_ZOMBIE:
5562 case T_MOVED:
5563 break;
5564 default:
5565 rb_gc_event_hook(vp, RUBY_INTERNAL_EVENT_FREEOBJ);
5566 break;
5567 }
5568 }
5569 }
5570 pp += slot_size;
5571 bitset >>= 1;
5572 }
5573 p += BITS_BITLENGTH * slot_size;
5574 }
5575}
5576
5577static void
5578gc_sweep_freeobj_hooks(rb_objspace_t *objspace)
5579{
5580 for (int i = 0; i < HEAP_COUNT; i++) {
5581 rb_heap_t *heap = &heaps[i];
5582 struct heap_page *page = NULL;
5583
5584 ccan_list_for_each(&heap->pages, page, page_node) {
5585 gc_sweep_freeobj_hooks_page(objspace, page);
5586 }
5587 }
5588}
5589
5590static void
5591gc_sweep_start(rb_objspace_t *objspace)
5592{
5593 gc_mode_transition(objspace, gc_mode_sweeping);
5594 objspace->rincgc.pooled_slots = 0;
5595
5596 if (RB_UNLIKELY(objspace->hook_events & RUBY_INTERNAL_EVENT_FREEOBJ)) {
5597 /* FREEOBJ is never enabled outside the main objspace
5598 * (rb_objspace_set_event_hook), so this hook, which runs user callbacks,
5599 * cannot fire during a non-main Ractor's lock-free local sweep. */
5600 GC_ASSERT(objspace == global_objspace->main_objspace);
5601 gc_sweep_freeobj_hooks(objspace);
5602 }
5603
5604#if GC_CAN_COMPILE_COMPACTION
5605 if (objspace->flags.during_compacting) {
5606 gc_sort_heap_by_compare_func(
5607 objspace,
5608 objspace->rcompactor.compare_func ? objspace->rcompactor.compare_func : compare_pinned_slots
5609 );
5610 }
5611#endif
5612
5613 for (int i = 0; i < HEAP_COUNT; i++) {
5614 rb_heap_t *heap = &heaps[i];
5615 gc_sweep_start_heap(objspace, heap);
5616
5617 /* We should call gc_sweep_finish_heap for size pools with no pages. */
5618 if (heap->sweeping_page == NULL) {
5619 GC_ASSERT(heap->total_pages == 0);
5620 GC_ASSERT(heap->total_slots == 0);
5621 gc_sweep_finish_heap(objspace, heap);
5622 }
5623 }
5624
5625 heap_alloc_state_clear(objspace);
5626}
5627
5628static void
5629gc_sweep_finish_heap(rb_objspace_t *objspace, rb_heap_t *heap)
5630{
5631 /* Nothing allocates from an ownerless objspace, so it has no growth decision */
5632 if (objspace->flags.ownerless) return;
5633
5634 size_t total_slots = heap->total_slots;
5635 size_t swept_slots = heap->freed_slots + heap->empty_slots;
5636
5637 size_t init_slots = objspace_heap_init_bytes(objspace) / heap->slot_size;
5638 size_t min_free_slots = (size_t)(MAX(total_slots, init_slots) * gc_params.heap_free_slots_min_ratio);
5639
5640 if (swept_slots < min_free_slots &&
5641 /* The heap is a growth heap if it freed more slots than had empty slots. */
5642 ((heap->empty_slots == 0 && total_slots > 0) || heap->freed_slots > heap->empty_slots)) {
5643 /* If we don't have enough slots and we have pages on the tomb heap, move
5644 * pages from the tomb heap to the eden heap. This may prevent page
5645 * creation thrashing (frequently allocating and deallocting pages) and
5646 * GC thrashing (running GC more frequently than required). */
5647 struct heap_page *resurrected_page;
5648 while (swept_slots < min_free_slots &&
5649 (resurrected_page = heap_page_resurrect(objspace))) {
5650 heap_add_page(objspace, heap, resurrected_page);
5651 heap_add_freepage(heap, resurrected_page);
5652
5653 swept_slots += resurrected_page->free_slots;
5654 }
5655
5656 if (swept_slots < min_free_slots) {
5657 /* Grow this heap if we are in a major GC or if we haven't run at least
5658 * RVALUE_OLD_AGE minor GC since the last major GC. */
5659 if (is_full_marking(objspace) ||
5660 objspace->profile.count - objspace->rgengc.last_major_gc < RVALUE_OLD_AGE) {
5661 if (objspace->heap_pages.allocatable_bytes < min_free_slots * heap->slot_size) {
5662 heap_allocatable_bytes_expand(objspace, heap, swept_slots, heap->total_slots, heap->slot_size);
5663 }
5664 }
5665 else if (swept_slots < min_free_slots * 7 / 8 &&
5666 objspace->heap_pages.allocatable_bytes < (min_free_slots * 7 / 8 - swept_slots) * heap->slot_size) {
5667 gc_needs_major_flags |= GPR_FLAG_MAJOR_BY_NOFREE;
5668 heap->force_major_gc_count++;
5669 }
5670 }
5671 }
5672}
5673
5674#if RGENGC_ESTIMATE_OLDMALLOC
5675static void
5676gc_check_oldmalloc(rb_objspace_t *objspace)
5677{
5678 size_t oldmalloc_increase = gc_oldmalloc_increase_load(objspace);
5679 MALLOC_COUNTERS_LOCK(objspace);
5680 gc_counter_t malloc_at = gc_counter_load_acquire(&objspace->malloc_counters.counters.malloc_at_last_gc);
5681 gc_counter_t free_at = gc_counter_load_acquire(&objspace->malloc_counters.counters.free_at_last_gc);
5682 gc_counter_t malloc_now = gc_counter_load_relaxed(&objspace->malloc_counters.counters.malloc);
5683 gc_counter_t free_now = gc_counter_load_relaxed(&objspace->malloc_counters.counters.free);
5684 gc_counter_t gc_freed = gc_counter_load_relaxed(&objspace->malloc_counters.freed_in_gc);
5685 MALLOC_COUNTERS_UNLOCK(objspace);
5686
5687 gc_counter_t freed = free_now - free_at;
5688 gc_counter_t mutator_freed = freed > gc_freed ? freed - gc_freed : 0;
5689 gc_counter_t allocated = malloc_now - malloc_at;
5690 gc_counter_t unswept = allocated > mutator_freed ? allocated - mutator_freed : 0;
5691
5692 if ((gc_counter_t)oldmalloc_increase <= unswept) return;
5693 oldmalloc_increase -= (size_t)unswept;
5694
5695 if (oldmalloc_increase > objspace->rgengc.oldmalloc_increase_limit) {
5696 gc_needs_major_flags |= GPR_FLAG_MAJOR_BY_OLDMALLOC;
5697 objspace->rgengc.oldmalloc_increase_limit =
5698 (size_t)(objspace->rgengc.oldmalloc_increase_limit * gc_params.oldmalloc_limit_growth_factor);
5699
5700 if (objspace->rgengc.oldmalloc_increase_limit > gc_params.oldmalloc_limit_max) {
5701 objspace->rgengc.oldmalloc_increase_limit = gc_params.oldmalloc_limit_max;
5702 }
5703 }
5704}
5705#endif
5706
5707static void
5708gc_sweep_finish(rb_objspace_t *objspace)
5709{
5710 gc_report(1, objspace, "gc_sweep_finish\n");
5711
5712 gc_prof_set_heap_info(objspace);
5713 heap_pages_free_unused_pages(objspace);
5714 if (rb_gc_single_objspace_p() && is_full_marking(objspace)) {
5715 /* gc_marks_finish retains ~2/3 of empty pages in objspace->empty_pages for reuse,
5716 * only the excess reaches the pool. */
5717 page_pool_reclaim(global_objspace);
5718 }
5719#if RGENGC_ESTIMATE_OLDMALLOC
5720 if (!is_full_marking(objspace)) {
5721 gc_check_oldmalloc(objspace);
5722 }
5723#endif
5724
5725 for (int i = 0; i < HEAP_COUNT; i++) {
5726 rb_heap_t *heap = &heaps[i];
5727
5728 heap->freed_slots = 0;
5729 heap->empty_slots = 0;
5730
5731 if (!will_be_incremental_marking(objspace)) {
5732 struct heap_page *end_page = heap->free_pages;
5733 if (end_page) {
5734 while (end_page->free_next) end_page = end_page->free_next;
5735 end_page->free_next = heap->pooled_pages;
5736 }
5737 else {
5738 heap->free_pages = heap->pooled_pages;
5739 }
5740 heap->pooled_pages = NULL;
5741 objspace->rincgc.pooled_slots = 0;
5742 }
5743 }
5744
5745 /* Not before: while sweeping is in progress its frees must keep reducing
5746 * malloc_increase (objspace_malloc_increase_body sweeps and retries on it). */
5747 gc_malloc_counters_snapshot_free_at_last_gc(objspace, &objspace->malloc_counters.counters);
5748
5749 /* Leftovers from an earlier multi-Ractor phase: no later sweep can rediscover them
5750 * (their slots are gone), and with one Ractor left the drain's barrier has nothing
5751 * to wait for. */
5752 if (tdata_deferred_free_count_load() > 0 && rb_gc_single_objspace_p()) {
5753 gc_tdata_deferred_free_trigger(objspace);
5754 }
5755
5757 gc_mode_transition(objspace, gc_mode_none);
5758}
5759
5760static int
5761gc_sweep_step(rb_objspace_t *objspace, rb_heap_t *heap)
5762{
5763 struct heap_page *sweep_page = heap->sweeping_page;
5764 int swept_slots = 0;
5765 int pooled_slots = 0;
5766 int sweep_budget = GC_INCREMENTAL_SWEEP_BYTES / heap->slot_size;
5767 int pool_budget = GC_INCREMENTAL_SWEEP_POOL_BYTES / heap->slot_size;
5768
5769 if (sweep_page == NULL) return FALSE;
5770
5771#if GC_ENABLE_LAZY_SWEEP
5772 gc_prof_sweep_timer_start(objspace);
5773#endif
5774
5775 /* Per-slot pinned-free assert (gc_sweep_context): check only when this cycle's mark
5776 * ran the pinned walk. The current world state would misfire: a single-world
5777 * cycle leaves dead shareable objects unmarked and its sweep can straddle the switch
5778 * to multi-objspace. A global GC's exact mark does not pin, so it is excluded. */
5779 const bool check_pinned_free = objspace->last_cycle_pinned;
5780
5781 const bool defer_thread_unsafe_local_sweep =
5782 !rb_gc_single_objspace_p() && !objspace->flags.during_global_gc;
5783 bool trigger_thread_unsafe_sweep_postponed_job = false;
5784
5785 do {
5786 RUBY_DEBUG_LOG("sweep_page:%p", (void *)sweep_page);
5787
5788 struct gc_sweep_context ctx = {
5789 .page = sweep_page,
5790 .final_slots = 0,
5791 .freed_slots = 0,
5792 .empty_slots = 0,
5793 .check_pinned_free = check_pinned_free,
5794 .defer_thread_unsafe_local_sweep = defer_thread_unsafe_local_sweep,
5795 .trigger_thread_unsafe_sweep_postponed_job = trigger_thread_unsafe_sweep_postponed_job,
5796 };
5797 gc_sweep_page(objspace, heap, &ctx);
5798 int free_slots = ctx.freed_slots + ctx.empty_slots;
5799 trigger_thread_unsafe_sweep_postponed_job = ctx.trigger_thread_unsafe_sweep_postponed_job;
5800
5801 RUBY_DTRACE_GC_HOOK(SWEEP_PAGE, ctx.page->slot_size, ctx.final_slots, ctx.freed_slots, ctx.empty_slots);
5802
5803 heap->sweeping_page = ccan_list_next(&heap->pages, sweep_page, page_node);
5804
5805 if (free_slots == sweep_page->total_slots &&
5806 (heap->total_pages > 1 || objspace->flags.ownerless)) {
5807 /* There are no living objects, so move this page to the global empty pages.
5808 * The last one stays so the heap has something to grow from -- except in an
5809 * ownerless objspace, which will never allocate again. */
5810 heap_page_detach_empty(objspace, heap, sweep_page);
5811 }
5812 else if (free_slots > 0) {
5813 heap->freed_slots += ctx.freed_slots;
5814 heap->empty_slots += ctx.empty_slots;
5815
5816 if (pooled_slots < pool_budget) {
5817 heap_add_poolpage(objspace, heap, sweep_page);
5818 pooled_slots += free_slots;
5819 }
5820 else {
5821 heap_add_freepage(heap, sweep_page);
5822 swept_slots += free_slots;
5823 if (swept_slots > sweep_budget) {
5824 break;
5825 }
5826 }
5827 }
5828 else {
5829 sweep_page->free_next = NULL;
5830 }
5831 } while ((sweep_page = heap->sweeping_page));
5832
5833 if (trigger_thread_unsafe_sweep_postponed_job) {
5834 gc_report(2, objspace, "thread-unsafe sweep postponed job triggered\n");
5835 gc_tdata_deferred_free_trigger(objspace);
5836 }
5837
5838 if (!heap->sweeping_page) {
5839 objspace->sweeping_heap_count--;
5840 GC_ASSERT(objspace->sweeping_heap_count >= 0);
5841 gc_sweep_finish_heap(objspace, heap);
5842
5843 if (!has_sweeping_pages(objspace)) {
5844 gc_sweep_finish(objspace);
5845 }
5846 }
5847
5848#if GC_ENABLE_LAZY_SWEEP
5849 gc_prof_sweep_timer_stop(objspace);
5850#endif
5851
5852 return heap->free_pages != NULL;
5853}
5854
5855static void
5856gc_sweep_rest(rb_objspace_t *objspace)
5857{
5858 for (int i = 0; i < HEAP_COUNT; i++) {
5859 rb_heap_t *heap = &heaps[i];
5860
5861 while (heap->sweeping_page) {
5862 gc_sweep_step(objspace, heap);
5863 }
5864 }
5865
5866 /* An objspace with no live pages never runs gc_sweep_step and so never reaches
5867 * gc_sweep_finish, leaving mode at sweeping or compacting until the next cycle's
5868 * gc_sweep_start asserts. If every heap is swept out, settle it to none here. */
5869 if (gc_mode(objspace) != gc_mode_none && !has_sweeping_pages(objspace)) {
5870 gc_sweep_finish(objspace);
5871 }
5872}
5873
5874static void
5875gc_sweep_continue(rb_objspace_t *objspace, rb_heap_t *sweep_heap)
5876{
5877 GC_ASSERT(dont_gc_val() == FALSE || objspace->profile.latest_gc_info & GPR_FLAG_METHOD);
5878 if (!GC_ENABLE_LAZY_SWEEP) return;
5879
5880 gc_sweeping_enter(objspace);
5881
5882 for (int i = 0; i < HEAP_COUNT; i++) {
5883 rb_heap_t *heap = &heaps[i];
5884 if (gc_sweep_step(objspace, heap)) {
5885 GC_ASSERT(heap->free_pages != NULL);
5886 }
5887 else if (heap == sweep_heap) {
5888 if (objspace->empty_pages_count > 0 || objspace->heap_pages.allocatable_bytes > 0) {
5889 /* [Bug #21548]
5890 *
5891 * If this heap is the heap we want to sweep, but we weren't able
5892 * to free any slots, but we also either have empty pages or could
5893 * allocate new pages, then we want to preemptively claim a page
5894 * because it's possible that sweeping another heap will call
5895 * gc_sweep_finish_heap, which may use up all of the
5896 * empty/allocatable pages. If other heaps are not finished sweeping
5897 * then we do not finish this GC and we will end up triggering a new
5898 * GC cycle during this GC phase. */
5899 heap_page_allocate_and_initialize(objspace, heap);
5900
5901 GC_ASSERT(heap->free_pages != NULL);
5902 }
5903 else {
5904 /* Not allowed to create a new page so finish sweeping. */
5905 gc_sweep_rest(objspace);
5906 GC_ASSERT(gc_mode(objspace) == gc_mode_none);
5907 break;
5908 }
5909 }
5910 }
5911
5912 gc_sweeping_exit(objspace);
5913}
5914
5915static void
5916gc_sweep_step_for_malloc(rb_objspace_t *objspace)
5917{
5918 GC_ASSERT(is_lazy_sweeping(objspace));
5919
5920 unsigned int lock_lev;
5921 gc_enter(objspace, gc_enter_event_continue, &lock_lev);
5922
5923 gc_sweeping_enter(objspace);
5924
5925 for (int i = 0; i < HEAP_COUNT; i++) {
5926 rb_heap_t *heap = &heaps[i];
5927 gc_sweep_step(objspace, heap);
5928 }
5929
5930 gc_sweeping_exit(objspace);
5931
5932 gc_exit(objspace, gc_enter_event_continue, &lock_lev);
5933}
5934
5935static bool gc_global_pointer_to_heap_p(const void *ptr);
5936
5937VALUE
5938rb_gc_impl_location(void *objspace_ptr, VALUE value)
5939{
5940 rb_objspace_t *objspace = objspace_ptr;
5941 VALUE destination;
5942
5943 /* A local (single-objspace) compaction never moves another objspace's objects, so
5944 * leave foreign references alone. A compacting global GC moves objects everywhere
5945 * under the barrier, so there every objspace's heap is searched for forwarding. */
5946 if (RB_UNLIKELY(objspace->flags.during_global_gc)
5947 ? !gc_global_pointer_to_heap_p((void *)value)
5948 : !is_pointer_to_heap(objspace_ptr, (void *)value)) {
5949 return value;
5950 }
5951
5952 asan_unpoisoning_object(value) {
5953 if (BUILTIN_TYPE(value) == T_MOVED) {
5954 destination = (VALUE)RMOVED(value)->destination;
5955 GC_ASSERT(BUILTIN_TYPE(destination) != T_NONE);
5956 }
5957 else {
5958 destination = value;
5959 }
5960 }
5961
5962 return destination;
5963}
5964
5965#if GC_CAN_COMPILE_COMPACTION
5966static void
5967invalidate_moved_plane(rb_objspace_t *objspace, struct heap_page *page, uintptr_t p, bits_t bitset)
5968{
5969 if (bitset) {
5970 do {
5971 if (bitset & 1) {
5972 VALUE forwarding_object = (VALUE)p;
5973 VALUE object;
5974
5975 if (BUILTIN_TYPE(forwarding_object) == T_MOVED) {
5976 GC_ASSERT(RVALUE_PINNED(objspace, forwarding_object));
5977 GC_ASSERT(!RVALUE_MARKED(objspace, forwarding_object));
5978
5979 CLEAR_IN_BITMAP(GET_HEAP_PINNED_BITS(forwarding_object), forwarding_object);
5980
5981 object = rb_gc_impl_location(objspace, forwarding_object);
5982 gc_move(objspace, object, forwarding_object, GET_HEAP_PAGE(object), page);
5983 /* forwarding_object is now our actual object, and "object"
5984 * is the free slot for the original page */
5985
5986 struct heap_page *orig_page = GET_HEAP_PAGE(object);
5987 orig_page->free_slots++;
5988 RVALUE_AGE_SET_BITMAP(object, 0);
5989 heap_page_add_free_region(objspace, orig_page, object);
5990
5991 GC_ASSERT(RVALUE_MARKED(objspace, forwarding_object));
5992 GC_ASSERT(BUILTIN_TYPE(forwarding_object) != T_MOVED);
5993 GC_ASSERT(BUILTIN_TYPE(forwarding_object) != T_NONE);
5994 }
5995 }
5996 p += page->slot_size;
5997 bitset >>= 1;
5998 } while (bitset);
5999 }
6000}
6001
6002static void
6003invalidate_moved_page(rb_objspace_t *objspace, struct heap_page *page)
6004{
6005 int i;
6006 bits_t *mark_bits, *pin_bits;
6007 bits_t bitset;
6008 short slot_size = page->slot_size;
6009 int total_slots = page->total_slots;
6010 int bitmap_plane_count = CEILDIV(total_slots, BITS_BITLENGTH);
6011
6012 mark_bits = page->mark_bits;
6013 pin_bits = page->pinned_bits;
6014
6015 uintptr_t p = page->start;
6016
6017 for (i=0; i < bitmap_plane_count; i++) {
6018 /* Moved objects are pinned but never marked. We reuse the pin bits
6019 * to indicate there is a moved object in this slot. */
6020 bitset = pin_bits[i] & ~mark_bits[i];
6021 invalidate_moved_plane(objspace, page, p, bitset);
6022 p += BITS_BITLENGTH * slot_size;
6023 }
6024}
6025#endif
6026
6027static void
6028gc_compact_start(rb_objspace_t *objspace)
6029{
6030 struct heap_page *page = NULL;
6031 gc_mode_transition(objspace, gc_mode_compacting);
6032
6033 for (int i = 0; i < HEAP_COUNT; i++) {
6034 rb_heap_t *heap = &heaps[i];
6035 ccan_list_for_each(&heap->pages, page, page_node) {
6036 page->flags.before_sweep = TRUE;
6037 }
6038
6039 heap->compact_cursor = ccan_list_tail(&heap->pages, struct heap_page, page_node);
6040 heap->compact_cursor_index = 0;
6041 }
6042
6043 if (gc_prof_enabled(objspace)) {
6044 gc_profile_record *record = gc_prof_record(objspace);
6045 record->moved_objects = objspace->rcompactor.total_moved;
6046 }
6047
6048 memset(objspace->rcompactor.considered_count_table, 0, T_MASK * sizeof(size_t));
6049 memset(objspace->rcompactor.moved_count_table, 0, T_MASK * sizeof(size_t));
6050 memset(objspace->rcompactor.moved_up_count_table, 0, T_MASK * sizeof(size_t));
6051 memset(objspace->rcompactor.moved_down_count_table, 0, T_MASK * sizeof(size_t));
6052
6053 /* Set up read barrier for pages containing MOVED objects */
6054 /* A compacting global GC installs the read barrier once for every objspace. */
6055 if (!global_objspace->global_gc.compacting) install_handlers();
6056}
6057
6058static void gc_sweep_compact(rb_objspace_t *objspace);
6059
6060static void
6061gc_sweep(rb_objspace_t *objspace)
6062{
6063 gc_sweeping_enter(objspace);
6064
6065 const unsigned int immediate_sweep = objspace->flags.immediate_sweep;
6066
6067 gc_report(1, objspace, "gc_sweep: immediate: %d\n", immediate_sweep);
6068
6069 gc_sweep_start(objspace);
6070 if (objspace->flags.during_compacting) {
6071 rb_hrtime_t compact_start_time = gc_prof_enabled(objspace) ? rb_hrtime_now() : 0;
6072 gc_sweep_compact(objspace);
6073 if (gc_prof_enabled(objspace)) {
6074 rb_hrtime_t compact_wall_time = elapsed_hrtime_from(compact_start_time);
6075 gc_profile_record *record = gc_prof_record(objspace);
6076 record->gc_compact_wall_time = rb_hrtime_add(record->gc_compact_wall_time,
6077 compact_wall_time);
6078 objspace->profile.gc_sweep_excluded_wall_time = rb_hrtime_add(
6079 objspace->profile.gc_sweep_excluded_wall_time,
6080 compact_wall_time);
6081 }
6082 }
6083
6084 if (immediate_sweep) {
6085#if !GC_ENABLE_LAZY_SWEEP
6086 gc_prof_sweep_timer_start(objspace);
6087#endif
6088 gc_sweep_rest(objspace);
6089#if !GC_ENABLE_LAZY_SWEEP
6090 gc_prof_sweep_timer_stop(objspace);
6091#endif
6092 }
6093 else {
6094
6095 /* Sweep every size pool. */
6096 for (int i = 0; i < HEAP_COUNT; i++) {
6097 rb_heap_t *heap = &heaps[i];
6098 gc_sweep_step(objspace, heap);
6099 }
6100 }
6101
6102 gc_sweeping_exit(objspace);
6103}
6104
6105/* Marking - Marking stack */
6106
6107static stack_chunk_t *
6108stack_chunk_alloc(void)
6109{
6110 stack_chunk_t *res;
6111
6112 res = malloc(sizeof(stack_chunk_t));
6113 if (!res)
6114 rb_memerror();
6115
6116 return res;
6117}
6118
6119static inline int
6120is_mark_stack_empty(mark_stack_t *stack)
6121{
6122 return stack->chunk == NULL;
6123}
6124
6125static size_t
6126mark_stack_size(mark_stack_t *stack)
6127{
6128 size_t size = stack->index;
6129 stack_chunk_t *chunk = stack->chunk ? stack->chunk->next : NULL;
6130
6131 while (chunk) {
6132 size += stack->limit;
6133 chunk = chunk->next;
6134 }
6135 return size;
6136}
6137
6138static void
6139add_stack_chunk_cache(mark_stack_t *stack, stack_chunk_t *chunk)
6140{
6141 chunk->next = stack->cache;
6142 stack->cache = chunk;
6143 stack->cache_size++;
6144}
6145
6146static void
6147shrink_stack_chunk_cache(mark_stack_t *stack)
6148{
6149 stack_chunk_t *chunk;
6150
6151 if (stack->unused_cache_size > (stack->cache_size/2)) {
6152 chunk = stack->cache;
6153 stack->cache = stack->cache->next;
6154 stack->cache_size--;
6155 free(chunk);
6156 }
6157 stack->unused_cache_size = stack->cache_size;
6158}
6159
6160static void
6161push_mark_stack_chunk(mark_stack_t *stack)
6162{
6163 stack_chunk_t *next;
6164
6165 GC_ASSERT(stack->index == stack->limit);
6166
6167 if (stack->cache_size > 0) {
6168 next = stack->cache;
6169 stack->cache = stack->cache->next;
6170 stack->cache_size--;
6171 if (stack->unused_cache_size > stack->cache_size)
6172 stack->unused_cache_size = stack->cache_size;
6173 }
6174 else {
6175 next = stack_chunk_alloc();
6176 }
6177 next->next = stack->chunk;
6178 stack->chunk = next;
6179 stack->index = 0;
6180}
6181
6182static void
6183pop_mark_stack_chunk(mark_stack_t *stack)
6184{
6185 stack_chunk_t *prev;
6186
6187 prev = stack->chunk->next;
6188 GC_ASSERT(stack->index == 0);
6189 add_stack_chunk_cache(stack, stack->chunk);
6190 stack->chunk = prev;
6191 stack->index = stack->limit;
6192}
6193
6194static void
6195mark_stack_chunk_list_free(stack_chunk_t *chunk)
6196{
6197 stack_chunk_t *next = NULL;
6198
6199 while (chunk != NULL) {
6200 next = chunk->next;
6201 free(chunk);
6202 chunk = next;
6203 }
6204}
6205
6206static void
6207free_stack_chunks(mark_stack_t *stack)
6208{
6209 mark_stack_chunk_list_free(stack->chunk);
6210}
6211
6212static void
6213mark_stack_free_cache(mark_stack_t *stack)
6214{
6215 mark_stack_chunk_list_free(stack->cache);
6216 stack->cache_size = 0;
6217 stack->unused_cache_size = 0;
6218}
6219
6220static void
6221push_mark_stack(mark_stack_t *stack, VALUE obj)
6222{
6223 switch (BUILTIN_TYPE(obj)) {
6224 case T_OBJECT:
6225 case T_CLASS:
6226 case T_MODULE:
6227 case T_FLOAT:
6228 case T_STRING:
6229 case T_REGEXP:
6230 case T_ARRAY:
6231 case T_HASH:
6232 case T_STRUCT:
6233 case T_BIGNUM:
6234 case T_FILE:
6235 case T_DATA:
6236 case T_MATCH:
6237 case T_COMPLEX:
6238 case T_RATIONAL:
6239 case T_TRUE:
6240 case T_FALSE:
6241 case T_SYMBOL:
6242 case T_IMEMO:
6243 case T_ICLASS:
6244 if (stack->index == stack->limit) {
6245 push_mark_stack_chunk(stack);
6246 }
6247 stack->chunk->data[stack->index++] = obj;
6248 return;
6249
6250 case T_NONE:
6251 case T_NIL:
6252 case T_FIXNUM:
6253 case T_MOVED:
6254 case T_ZOMBIE:
6255 case T_UNDEF:
6256 case T_MASK:
6257 rb_bug("push_mark_stack() called for broken object");
6258 break;
6259
6260 case T_NODE:
6261 rb_bug("push_mark_stack: unexpected T_NODE object");
6262 break;
6263 }
6264
6265 rb_bug("rb_gc_mark(): unknown data type 0x%x(%p) %s",
6266 BUILTIN_TYPE(obj), (void *)obj,
6267 is_pointer_to_heap((rb_objspace_t *)rb_gc_get_objspace(), (void *)obj) ? "corrupted object" : "non object");
6268}
6269
6270static int
6271pop_mark_stack(mark_stack_t *stack, VALUE *data)
6272{
6273 if (is_mark_stack_empty(stack)) {
6274 return FALSE;
6275 }
6276 if (stack->index == 1) {
6277 *data = stack->chunk->data[--stack->index];
6278 pop_mark_stack_chunk(stack);
6279 }
6280 else {
6281 *data = stack->chunk->data[--stack->index];
6282 }
6283 return TRUE;
6284}
6285
6286static void
6287init_mark_stack(mark_stack_t *stack)
6288{
6289 int i;
6290
6291 MEMZERO(stack, mark_stack_t, 1);
6292 stack->index = stack->limit = STACK_CHUNK_SIZE;
6293
6294 for (i=0; i < 4; i++) {
6295 add_stack_chunk_cache(stack, stack_chunk_alloc());
6296 }
6297 stack->unused_cache_size = stack->cache_size;
6298}
6299
6300/* Marking */
6301
6302ALWAYS_INLINE(static int gc_mark_set(rb_objspace_t *objspace, VALUE obj));
6303ALWAYS_INLINE(static void gc_mark_check_t_none(rb_objspace_t *objspace, VALUE obj));
6304ALWAYS_INLINE(static void rgengc_check_relation(rb_objspace_t *objspace, VALUE obj));
6305ALWAYS_INLINE(static void gc_aging(rb_objspace_t *objspace, VALUE obj));
6306ALWAYS_INLINE(static void gc_grey(rb_objspace_t *objspace, VALUE obj));
6307static void
6308rgengc_check_relation(rb_objspace_t *objspace, VALUE obj)
6309{
6310 if (objspace->rgengc.parent_object_old_p) {
6311 if (!RVALUE_OLD_P(objspace, obj)) {
6312 rgengc_remember(objspace, objspace->rgengc.parent_object);
6313 /* It is in the rememberset now, so its remaining children have nothing left
6314 * to ask for: stop testing them. */
6315 objspace->rgengc.parent_object_old_p = false;
6316 }
6317 }
6318}
6319
6320static inline int
6321gc_mark_set(rb_objspace_t *objspace, VALUE obj)
6322{
6323 if (RVALUE_MARKED(objspace, obj)) return 0;
6324 MARK_IN_BITMAP(GET_HEAP_MARK_BITS(obj), obj);
6325 return 1;
6326}
6327
6328static void
6329gc_aging(rb_objspace_t *objspace, VALUE obj)
6330{
6331 /* Disable aging if Major GC's are disabled. This will prevent longish lived
6332 * objects filling up the heap at the expense of marking many more objects.
6333 *
6334 * We should always pre-warm our process when disabling majors, by running
6335 * GC manually several times so that most objects likely to become oldgen
6336 * are already oldgen.
6337 */
6338 if(!gc_config_full_mark_val)
6339 return;
6340
6341 struct heap_page *page = GET_HEAP_PAGE(obj);
6342
6343 GC_ASSERT(RVALUE_MARKING(objspace, obj) == FALSE);
6344 check_rvalue_consistency(objspace, obj);
6345
6346 if (!RVALUE_PAGE_WB_UNPROTECTED(page, obj)) {
6347 if (!RVALUE_OLD_P(objspace, obj)) {
6348 int t = BUILTIN_TYPE(obj);
6349 if (t == T_CLASS || t == T_MODULE || t == T_ICLASS) {
6350 gc_report(3, objspace, "gc_aging: YOUNG class: %s\n", rb_obj_info(obj));
6351 RVALUE_AGE_SET(obj, RVALUE_OLD_AGE);
6352 RVALUE_OLD_UNCOLLECTIBLE_SET(objspace, obj);
6353 }
6354 else {
6355 gc_report(3, objspace, "gc_aging: YOUNG: %s\n", rb_obj_info(obj));
6356 RVALUE_AGE_INC(objspace, obj);
6357 }
6358 }
6359 else if (is_full_marking(objspace)) {
6360 GC_ASSERT(RVALUE_PAGE_UNCOLLECTIBLE(page, obj) == FALSE);
6361 RVALUE_PAGE_OLD_UNCOLLECTIBLE_SET(objspace, page, obj);
6362 }
6363 }
6364 check_rvalue_consistency(objspace, obj);
6365
6366 page->objspace->marked_slots++;
6367}
6368
6369static void
6370gc_grey(rb_objspace_t *objspace, VALUE obj)
6371{
6372#if RGENGC_CHECK_MODE
6373 if (RVALUE_MARKED(objspace, obj) == FALSE) rb_bug("gc_grey: %s is not marked.", rb_obj_info(obj));
6374 if (RVALUE_MARKING(objspace, obj) == TRUE) rb_bug("gc_grey: %s is marking/remembered.", rb_obj_info(obj));
6375#endif
6376
6377 if (is_incremental_marking(objspace)) {
6378 MARK_IN_BITMAP(GET_HEAP_MARKING_BITS(obj), obj);
6379 }
6380
6382 rb_darray_append_without_gc(&objspace->weak_references, obj);
6383 }
6384
6385 push_mark_stack(&objspace->mark_stack, obj);
6386}
6387
6388static inline void
6389gc_mark_check_t_none(rb_objspace_t *objspace, VALUE obj)
6390{
6391 if (RB_UNLIKELY(BUILTIN_TYPE(obj) == T_NONE)) {
6392 enum {info_size = 256};
6393 char obj_info_buf[info_size];
6394 rb_raw_obj_info(obj_info_buf, info_size, obj);
6395
6396 char parent_obj_info_buf[info_size];
6397 rb_raw_obj_info(parent_obj_info_buf, info_size, objspace->rgengc.parent_object);
6398
6399 rb_bug("try to mark T_NONE object (obj: %s, parent: %s)", obj_info_buf, parent_obj_info_buf);
6400 }
6401}
6402
6403static void
6404gc_mark(rb_objspace_t *objspace, VALUE obj)
6405{
6406 GC_ASSERT(during_gc);
6407 GC_ASSERT(!objspace->flags.during_reference_updating);
6408
6409 /* Never step into another objspace: a foreign object is a live leaf whose liveness
6410 * belongs to its owner, so touching its bitmaps here would be unsound. A global GC
6411 * lifts this: everyone is stopped and the bits live on the object's own page. */
6412 if (gc_skip_foreign_object_p(objspace, obj)) {
6413 return;
6414 }
6415
6416 if (RB_UNLIKELY(objspace->flags.during_global_gc)) {
6417 /* Recompute the shref of every shareable -> unshareable edge, within and across
6418 * objspaces: the clear pass dropped all shref bits and the write barrier
6419 * maintains them from here on. */
6420 VALUE parent = objspace->rgengc.parent_object;
6421 if (!UNDEF_P(parent) && parent != Qfalse &&
6424 struct heap_page *page = GET_HEAP_PAGE(obj);
6425 _MARK_IN_BITMAP(page->shref_bits, page, obj);
6426 page->flags.has_shref_objects = TRUE;
6427 }
6428 }
6429
6430 rgengc_check_relation(objspace, obj);
6431 if (!gc_mark_set(objspace, obj)) return; /* already marked */
6432
6433 if (0) { // for debug GC marking miss
6434 RUBY_DEBUG_LOG("%p (%s) parent:%p (%s)",
6435 (void *)obj, obj_type_name(obj),
6436 (void *)objspace->rgengc.parent_object, obj_type_name(objspace->rgengc.parent_object));
6437 }
6438
6439 gc_mark_check_t_none(objspace, obj);
6440
6441 gc_aging(objspace, obj);
6442 gc_grey(objspace, obj);
6443}
6444
6445static inline void
6446gc_pin(rb_objspace_t *objspace, VALUE obj)
6447{
6448 GC_ASSERT(!SPECIAL_CONST_P(obj));
6449
6450 if (RB_UNLIKELY(objspace->flags.during_compacting)) {
6451 /* Never write a foreign page's pinned bit (a global GC may: everyone is stopped). */
6452 if (gc_skip_foreign_object_p(objspace, obj)) return;
6453
6454 if (RB_LIKELY(during_gc)) {
6455 if (!RVALUE_PINNED(objspace, obj)) {
6456 GC_ASSERT(GET_HEAP_PAGE(obj)->pinned_slots <= GET_HEAP_PAGE(obj)->total_slots);
6457 GET_HEAP_PAGE(obj)->pinned_slots++;
6458 MARK_IN_BITMAP(GET_HEAP_PINNED_BITS(obj), obj);
6459 }
6460 }
6461 }
6462}
6463
6464static inline void
6465gc_mark_and_pin(rb_objspace_t *objspace, VALUE obj)
6466{
6467 gc_pin(objspace, obj);
6468 gc_mark(objspace, obj);
6469}
6470
6471void
6472rb_gc_impl_mark_and_move(void *objspace_ptr, VALUE *ptr)
6473{
6474 rb_objspace_t *objspace = objspace_ptr;
6475
6476 if (RB_UNLIKELY(objspace->flags.during_reference_updating)) {
6477 GC_ASSERT(objspace->flags.during_compacting);
6478 GC_ASSERT(during_gc);
6479
6480 VALUE destination = rb_gc_impl_location(objspace, *ptr);
6481 if (destination != *ptr) {
6482 *ptr = destination;
6483 }
6484 }
6485 else {
6486 gc_mark(objspace, *ptr);
6487 }
6488}
6489
6490void
6491rb_gc_impl_mark(void *objspace_ptr, VALUE obj)
6492{
6493 rb_objspace_t *objspace = objspace_ptr;
6494
6495 gc_mark(objspace, obj);
6496}
6497
6498void
6499rb_gc_impl_mark_and_pin(void *objspace_ptr, VALUE obj)
6500{
6501 rb_objspace_t *objspace = objspace_ptr;
6502
6503 gc_mark_and_pin(objspace, obj);
6504}
6505
6506/* A word scanned conservatively by a global GC can point into any objspace, so ownership
6507 * is decided against the driver's snapshot of every objspace (the bits then land on the
6508 * owner's page through gc_mark and gc_pin). */
6509static bool
6510gc_global_pointer_to_heap_p(const void *ptr)
6511{
6512 const rb_global_objspace_t *g = global_objspace;
6513 uintptr_t p = (uintptr_t)ptr;
6514
6515 if (p < g->page_index.lomem || p > g->page_index.himem) return false;
6516 if (p % sizeof(VALUE) != 0) return false;
6517
6518 struct heap_page **res = bsearch(ptr, g->page_index.pages, g->page_index.n_pages,
6519 sizeof(struct heap_page *), ptr_in_page_body_p);
6520 if (res == NULL) return false;
6521
6522 struct heap_page *page = *res;
6523 if (heap_page_in_global_empty_pages_pool(page->objspace, page)) return false;
6524 if (p < page->start) return false;
6525 if (p >= page->start + (page->total_slots * page->slot_size)) return false;
6526 if ((p - page->start) % page->slot_size != 0) return false;
6527 return true;
6528}
6529
6530void
6531rb_gc_impl_mark_maybe(void *objspace_ptr, VALUE obj)
6532{
6533 rb_objspace_t *objspace = objspace_ptr;
6534
6535 (void)VALGRIND_MAKE_MEM_DEFINED(&obj, sizeof(obj));
6536
6537 if (RB_UNLIKELY(objspace->flags.during_global_gc)
6538 ? gc_global_pointer_to_heap_p((void *)obj)
6539 : is_pointer_to_heap(objspace, (void *)obj)) {
6540 asan_unpoisoning_object(obj) {
6541 /* Garbage can live on the stack, so do not mark or pin */
6542 switch (BUILTIN_TYPE(obj)) {
6543 case T_ZOMBIE:
6544 case T_NONE:
6545 break;
6546 default:
6547 gc_mark_and_pin(objspace, obj);
6548 break;
6549 }
6550 }
6551 }
6552}
6553
6554static int
6555pin_value(st_data_t key, st_data_t value, st_data_t data)
6556{
6557 rb_gc_impl_mark_and_pin((void *)data, (VALUE)value);
6558
6559 return ST_CONTINUE;
6560}
6561
6562static inline void
6563gc_mark_set_parent_raw(rb_objspace_t *objspace, VALUE obj, bool old_p)
6564{
6565 asan_unpoison_memory_region(&objspace->rgengc.parent_object, sizeof(objspace->rgengc.parent_object), false);
6566 asan_unpoison_memory_region(&objspace->rgengc.parent_object_old_p, sizeof(objspace->rgengc.parent_object_old_p), false);
6567 objspace->rgengc.parent_object = obj;
6568 objspace->rgengc.parent_object_old_p = old_p;
6569}
6570
6571static inline void
6572gc_mark_set_parent(rb_objspace_t *objspace, VALUE obj)
6573{
6574 gc_mark_set_parent_raw(objspace, obj, RVALUE_OLD_P(objspace, obj));
6575}
6576
6577static inline void
6578gc_mark_set_parent_invalid(rb_objspace_t *objspace)
6579{
6580 asan_poison_memory_region(&objspace->rgengc.parent_object, sizeof(objspace->rgengc.parent_object));
6581 asan_poison_memory_region(&objspace->rgengc.parent_object_old_p, sizeof(objspace->rgengc.parent_object_old_p));
6582}
6583
6584static void pinned_roots_mark(rb_objspace_t *objspace, rb_heap_t *heap);
6585
6586static void
6587mark_roots(rb_objspace_t *objspace, const char **categoryp)
6588{
6589 VALUE objspace_guard = (VALUE)objspace;
6590#define MARK_CHECKPOINT(category) do { \
6591 if (categoryp) *categoryp = category; \
6592} while (0)
6593
6594 /* Pinning shareable objects and shrefs runs at the end of marking (gc_marks_finish),
6595 * not here: after the full walk it only has to touch what ordinary marking missed,
6596 * which is both cheap and a useful retention metric. */
6597
6598 MARK_CHECKPOINT("objspace");
6599 gc_mark_set_parent_raw(objspace, Qundef, false);
6600
6601 if (objspace->flags.during_global_gc) {
6602 /* Pin the finalizer tables of every objspace, zombies included.
6603 * (finalizer_table is a macro over the local "objspace".) */
6604 rb_objspace_t *const driver = objspace;
6605 for (size_t i = 0; i < global_objspace->global_gc.n_objspaces; i++) {
6606 rb_objspace_t *objspace = global_objspace->global_gc.objspaces[i];
6607 if (finalizer_table != NULL) {
6608 st_foreach(finalizer_table, pin_value, (st_data_t)driver);
6609 }
6610 }
6611 }
6612 else if (finalizer_table != NULL) {
6613 st_foreach(finalizer_table, pin_value, (st_data_t)objspace);
6614 }
6615
6616 if (stress_to_class) rb_gc_mark(stress_to_class);
6617
6618 rb_gc_save_machine_context();
6619 rb_gc_mark_roots(objspace, categoryp);
6620 /* Keep this frame, including its saved registers, until root marking has
6621 * scanned the machine stack. */
6622 RB_GC_GUARD(objspace_guard);
6623 gc_mark_set_parent_invalid(objspace);
6624}
6625
6626static void
6627gc_mark_children(rb_objspace_t *objspace, VALUE obj)
6628{
6629 gc_mark_set_parent(objspace, obj);
6630 rb_gc_mark_children(objspace, obj);
6631 gc_mark_set_parent_invalid(objspace);
6632}
6633
6638static inline int
6639gc_mark_stacked_objects(rb_objspace_t *objspace, int incremental, size_t count)
6640{
6641 mark_stack_t *mstack = &objspace->mark_stack;
6642 VALUE obj;
6643 size_t marked_slots_at_the_beginning = objspace->marked_slots;
6644 size_t popped_count = 0;
6645
6646 while (pop_mark_stack(mstack, &obj)) {
6647 if (obj == Qundef) continue; /* skip */
6648
6649 if (RGENGC_CHECK_MODE && !RVALUE_MARKED(objspace, obj)) {
6650 rb_bug("gc_mark_stacked_objects: %s is not marked.", rb_obj_info(obj));
6651 }
6652 gc_mark_children(objspace, obj);
6653
6654 popped_count++;
6655
6656 if (incremental) {
6657 if (RGENGC_CHECK_MODE && !RVALUE_MARKING(objspace, obj)) {
6658 rb_bug("gc_mark_stacked_objects: incremental, but marking bit is 0");
6659 }
6660 CLEAR_IN_BITMAP(GET_HEAP_MARKING_BITS(obj), obj);
6661
6662 if (popped_count + (objspace->marked_slots - marked_slots_at_the_beginning) > count) {
6663 break;
6664 }
6665 }
6666 else {
6667 /* just ignore marking bits */
6668 }
6669 }
6670
6671 RUBY_DTRACE_GC_HOOK(MARK_STACKED_OBJECTS, popped_count);
6672
6673 if (RGENGC_CHECK_MODE >= 3) gc_verify_internal_consistency(objspace);
6674
6675 if (is_mark_stack_empty(mstack)) {
6676 shrink_stack_chunk_cache(mstack);
6677 return TRUE;
6678 }
6679 else {
6680 return FALSE;
6681 }
6682}
6683
6684static int
6685gc_mark_stacked_objects_incremental(rb_objspace_t *objspace, size_t count)
6686{
6687 return gc_mark_stacked_objects(objspace, TRUE, count);
6688}
6689
6690static int
6691gc_mark_stacked_objects_all(rb_objspace_t *objspace)
6692{
6693 return gc_mark_stacked_objects(objspace, FALSE, 0);
6694}
6695
6696#if RGENGC_CHECK_MODE >= 4
6697
6698#define MAKE_ROOTSIG(obj) (((VALUE)(obj) << 1) | 0x01)
6699#define IS_ROOTSIG(obj) ((VALUE)(obj) & 0x01)
6700#define GET_ROOTSIG(obj) ((const char *)((VALUE)(obj) >> 1))
6701
6702struct reflist {
6703 VALUE *list;
6704 int pos;
6705 int size;
6706};
6707
6708static struct reflist *
6709reflist_create(VALUE obj)
6710{
6711 struct reflist *refs = xmalloc(sizeof(struct reflist));
6712 refs->size = 1;
6713 refs->list = ALLOC_N(VALUE, refs->size);
6714 refs->list[0] = obj;
6715 refs->pos = 1;
6716 return refs;
6717}
6718
6719static void
6720reflist_destruct(struct reflist *refs)
6721{
6722 xfree(refs->list);
6723 xfree(refs);
6724}
6725
6726static void
6727reflist_add(struct reflist *refs, VALUE obj)
6728{
6729 if (refs->pos == refs->size) {
6730 refs->size *= 2;
6731 SIZED_REALLOC_N(refs->list, VALUE, refs->size, refs->size/2);
6732 }
6733
6734 refs->list[refs->pos++] = obj;
6735}
6736
6737static void
6738reflist_dump(struct reflist *refs)
6739{
6740 int i;
6741 for (i=0; i<refs->pos; i++) {
6742 VALUE obj = refs->list[i];
6743 if (IS_ROOTSIG(obj)) { /* root */
6744 fprintf(stderr, "<root@%s>", GET_ROOTSIG(obj));
6745 }
6746 else {
6747 fprintf(stderr, "<%s>", rb_obj_info(obj));
6748 }
6749 if (i+1 < refs->pos) fprintf(stderr, ", ");
6750 }
6751}
6752
6753static int
6754reflist_referred_from_machine_context(struct reflist *refs)
6755{
6756 int i;
6757 for (i=0; i<refs->pos; i++) {
6758 VALUE obj = refs->list[i];
6759 if (IS_ROOTSIG(obj) && strcmp(GET_ROOTSIG(obj), "machine_context") == 0) return 1;
6760 }
6761 return 0;
6762}
6763
6764struct allrefs {
6766 /* a -> obj1
6767 * b -> obj1
6768 * c -> obj1
6769 * c -> obj2
6770 * d -> obj3
6771 * #=> {obj1 => [a, b, c], obj2 => [c, d]}
6772 */
6773 struct st_table *references;
6774 const char *category;
6775 VALUE root_obj;
6777};
6778
6779static int
6780allrefs_add(struct allrefs *data, VALUE obj)
6781{
6782 struct reflist *refs;
6783 st_data_t r;
6784
6785 if (st_lookup(data->references, obj, &r)) {
6786 refs = (struct reflist *)r;
6787 reflist_add(refs, data->root_obj);
6788 return 0;
6789 }
6790 else {
6791 refs = reflist_create(data->root_obj);
6792 st_insert(data->references, obj, (st_data_t)refs);
6793 return 1;
6794 }
6795}
6796
6797static void
6798allrefs_i(VALUE obj, void *ptr)
6799{
6800 struct allrefs *data = (struct allrefs *)ptr;
6801
6802 if (allrefs_add(data, obj)) {
6803 push_mark_stack(&data->mark_stack, obj);
6804 }
6805}
6806
6807static void
6808allrefs_roots_i(VALUE obj, void *ptr)
6809{
6810 struct allrefs *data = (struct allrefs *)ptr;
6811 if (strlen(data->category) == 0) rb_bug("!!!");
6812 data->root_obj = MAKE_ROOTSIG(data->category);
6813
6814 if (allrefs_add(data, obj)) {
6815 push_mark_stack(&data->mark_stack, obj);
6816 }
6817}
6818#define PUSH_MARK_FUNC_DATA(v) do { \
6819 struct gc_mark_func_data_struct *prev_mark_func_data = GET_VM()->gc.mark_func_data; \
6820 GET_VM()->gc.mark_func_data = (v);
6821
6822#define POP_MARK_FUNC_DATA() GET_VM()->gc.mark_func_data = prev_mark_func_data;} while (0)
6823
6824static st_table *
6825objspace_allrefs(rb_objspace_t *objspace)
6826{
6827 struct allrefs data;
6828 struct gc_mark_func_data_struct mfd;
6829 VALUE obj;
6830 int prev_dont_gc = dont_gc_val();
6831 dont_gc_on();
6832
6833 data.objspace = objspace;
6834 data.references = st_init_numtable();
6835 init_mark_stack(&data.mark_stack);
6836
6837 mfd.mark_func = allrefs_roots_i;
6838 mfd.data = &data;
6839
6840 /* traverse root objects */
6841 PUSH_MARK_FUNC_DATA(&mfd);
6842 GET_VM()->gc.mark_func_data = &mfd;
6843 mark_roots(objspace, &data.category);
6844 POP_MARK_FUNC_DATA();
6845
6846 /* traverse rest objects reachable from root objects */
6847 while (pop_mark_stack(&data.mark_stack, &obj)) {
6848 rb_objspace_reachable_objects_from_unlocked(data.root_obj = obj, allrefs_i, &data);
6849 }
6850 free_stack_chunks(&data.mark_stack);
6851
6852 dont_gc_set(prev_dont_gc);
6853 return data.references;
6854}
6855
6856static int
6857objspace_allrefs_destruct_i(st_data_t key, st_data_t value, st_data_t ptr)
6858{
6859 struct reflist *refs = (struct reflist *)value;
6860 reflist_destruct(refs);
6861 return ST_CONTINUE;
6862}
6863
6864static void
6865objspace_allrefs_destruct(struct st_table *refs)
6866{
6867 st_foreach(refs, objspace_allrefs_destruct_i, 0);
6868 st_free_table(refs);
6869}
6870
6871#if RGENGC_CHECK_MODE >= 5
6872static int
6873allrefs_dump_i(st_data_t k, st_data_t v, st_data_t ptr)
6874{
6875 VALUE obj = (VALUE)k;
6876 struct reflist *refs = (struct reflist *)v;
6877 fprintf(stderr, "[allrefs_dump_i] %s <- ", rb_obj_info(obj));
6878 reflist_dump(refs);
6879 fprintf(stderr, "\n");
6880 return ST_CONTINUE;
6881}
6882
6883static void
6884allrefs_dump(rb_objspace_t *objspace)
6885{
6886 VALUE size = objspace->rgengc.allrefs_table->num_entries;
6887 fprintf(stderr, "[all refs] (size: %"PRIuVALUE")\n", size);
6888 st_foreach(objspace->rgengc.allrefs_table, allrefs_dump_i, 0);
6889}
6890#endif
6891
6892static int
6893gc_check_after_marks_i(st_data_t k, st_data_t v, st_data_t ptr)
6894{
6895 VALUE obj = k;
6896 struct reflist *refs = (struct reflist *)v;
6898
6899 /* object should be marked or oldgen */
6900 if (!RVALUE_MARKED(objspace, obj)) {
6901 fprintf(stderr, "gc_check_after_marks_i: %s is not marked and not oldgen.\n", rb_obj_info(obj));
6902 fprintf(stderr, "gc_check_after_marks_i: %p is referred from ", (void *)obj);
6903 reflist_dump(refs);
6904
6905 if (reflist_referred_from_machine_context(refs)) {
6906 fprintf(stderr, " (marked from machine stack).\n");
6907 /* marked from machine context can be false positive */
6908 }
6909 else {
6910 objspace->rgengc.error_count++;
6911 fprintf(stderr, "\n");
6912 }
6913 }
6914 return ST_CONTINUE;
6915}
6916
6917static void
6918gc_marks_check(rb_objspace_t *objspace, st_foreach_callback_func *checker_func, const char *checker_name)
6919{
6920 MALLOC_COUNTERS_LOCK(objspace);
6921 struct gc_malloc_bytes saved_malloc = {
6922 .malloc = gc_counter_load_relaxed(&objspace->malloc_counters.counters.malloc),
6923 .free = gc_counter_load_relaxed(&objspace->malloc_counters.counters.free),
6924 .malloc_at_last_gc = gc_counter_load_relaxed(&objspace->malloc_counters.counters.malloc_at_last_gc),
6925 .free_at_last_gc = gc_counter_load_relaxed(&objspace->malloc_counters.counters.free_at_last_gc),
6926 };
6927#if RGENGC_ESTIMATE_OLDMALLOC
6928 size_t saved_oldmalloc_increase = gc_oldmalloc_increase_load(objspace);
6929 gc_counter_t saved_freed_in_gc = gc_counter_load_relaxed(&objspace->malloc_counters.freed_in_gc);
6930#endif
6931 MALLOC_COUNTERS_UNLOCK(objspace);
6932 VALUE already_disabled = rb_objspace_gc_disable(objspace);
6933
6934 objspace->rgengc.allrefs_table = objspace_allrefs(objspace);
6935
6936 if (checker_func) {
6937 st_foreach(objspace->rgengc.allrefs_table, checker_func, (st_data_t)objspace);
6938 }
6939
6940 if (objspace->rgengc.error_count > 0) {
6941#if RGENGC_CHECK_MODE >= 5
6942 allrefs_dump(objspace);
6943#endif
6944 if (checker_name) rb_bug("%s: GC has problem.", checker_name);
6945 }
6946
6947 objspace_allrefs_destruct(objspace->rgengc.allrefs_table);
6948 objspace->rgengc.allrefs_table = 0;
6949
6950 if (already_disabled == Qfalse) rb_objspace_gc_enable(objspace);
6951 MALLOC_COUNTERS_LOCK(objspace);
6952 gc_counter_store_release(&objspace->malloc_counters.counters.malloc, saved_malloc.malloc);
6953 gc_counter_store_release(&objspace->malloc_counters.counters.free, saved_malloc.free);
6954 gc_counter_store_release(&objspace->malloc_counters.counters.malloc_at_last_gc, saved_malloc.malloc_at_last_gc);
6955 gc_counter_store_release(&objspace->malloc_counters.counters.free_at_last_gc, saved_malloc.free_at_last_gc);
6956#if RGENGC_ESTIMATE_OLDMALLOC
6957 RUBY_ATOMIC_SIZE_EXCHANGE(objspace->malloc_counters.oldmalloc_increase, saved_oldmalloc_increase);
6958 gc_counter_store_release(&objspace->malloc_counters.freed_in_gc, saved_freed_in_gc);
6959#endif
6960 MALLOC_COUNTERS_UNLOCK(objspace);
6961}
6962#endif /* RGENGC_CHECK_MODE >= 4 */
6963
6966 /* True only while the world is stopped: a GC.verify holding the VM lock and barrier,
6967 * or a global GC. Cross-objspace checks (walking every objspace's pages) are sound
6968 * only then. */
6969 bool world_stopped;
6970 int err_count;
6971 size_t live_object_count;
6972 size_t zombie_object_count;
6973
6974 VALUE parent;
6975 bool parent_shareable;
6976 size_t old_object_count;
6977 size_t remembered_shady_count;
6978};
6979
6980
6981static void
6982check_generation_i(const VALUE child, void *ptr)
6983{
6985 const VALUE parent = data->parent;
6986
6987 if (RGENGC_CHECK_MODE) GC_ASSERT(RVALUE_OLD_P(data->objspace, parent));
6988
6989 /* A cross-objspace edge is kept alive by the shareable/shref mechanism and is not
6990 * tracked in this objspace's remembered set. */
6991 if (GET_HEAP_OBJSPACE(child) != data->objspace) return;
6992
6993 /* Once the process goes multi-Ractor, the shareable world is managed by pinning and
6994 * shrefs rather than by the remembered set: the pinned walk at the end of a mark
6995 * re-marks every shareable object (and its shref'd children) each local cycle, and a
6996 * global GC rebuilds the generation state. So the generational old->young invariant
6997 * does not hold when either endpoint is shareable: an old constcache, cc_table or
6998 * interned string pointing at a core class that is young after a global GC is the
6999 * typical false positive. That state outlives the return to a single Ractor until
7000 * the next major (an old shareable singleton class pointing at a young
7001 * attached_object, say), so the test uses rb_gc_ever_multi_ractor_p(), which stays
7002 * true forever once multiple Ractors existed. A program that never goes multi keeps
7003 * the strict check, and ASAN catches what is left. */
7004 if (rb_gc_ever_multi_ractor_p() &&
7005 (MARKED_IN_BITMAP(GET_HEAP_SHAREABLE_BITS(parent), parent) ||
7006 MARKED_IN_BITMAP(GET_HEAP_SHAREABLE_BITS(child), child))) {
7007 return;
7008 }
7009
7010 if (!RVALUE_OLD_P(data->objspace, child)) {
7011 /* A young shareable child is pinned and kept alive by the local GC (only a
7012 * global GC collects it), so it survives even when the old parent does not
7013 * remember it. It is outside the generational remembered set, so exclude it
7014 * from the old->young check. */
7015 if (!RVALUE_REMEMBERED(data->objspace, parent) &&
7016 !RVALUE_REMEMBERED(data->objspace, child) &&
7017 !RVALUE_UNCOLLECTIBLE(data->objspace, child) &&
7019 fprintf(stderr, "verify_internal_consistency_reachable_i: WB miss (O->Y) %s -> %s\n", rb_obj_info(parent), rb_obj_info(child));
7020 data->err_count++;
7021 }
7022 }
7023}
7024
7025static void
7026check_color_i(const VALUE child, void *ptr)
7027{
7029 const VALUE parent = data->parent;
7030
7031 /* This cycle never marks a foreign child (gc_skip_foreign_object_p) and the write
7032 * barrier is a no-op across objspaces, so its colour says nothing here. */
7033 if (GET_HEAP_OBJSPACE(child) != data->objspace) return;
7034
7035 if (!RVALUE_WB_UNPROTECTED(data->objspace, parent) && RVALUE_WHITE_P(data->objspace, child)) {
7036 fprintf(stderr, "verify_internal_consistency_reachable_i: WB miss (B->W) - %s -> %s\n",
7037 rb_obj_info(parent), rb_obj_info(child));
7038 data->err_count++;
7039 }
7040}
7041
7042static void
7043check_children_i(const VALUE child, void *ptr)
7044{
7046
7047 /* Fast path: a child in this objspace (99.99% of all edges). */
7048 if (RB_LIKELY(is_pointer_to_heap(data->objspace, (void *)child))) {
7049 if (check_rvalue_consistency_force(data->objspace, child, FALSE) != 0) {
7050 fprintf(stderr, "check_children_i: %s has error (referenced from %s)\n",
7051 rb_obj_info(child), rb_obj_info(data->parent));
7052 data->err_count++;
7053 }
7054 return;
7055 }
7056
7057 /* The remaining cross-objspace check (verify_pointer_in_any_heap_p) walks every
7058 * objspace's pages, sound only with the world stopped: mid-local-GC other Ractors
7059 * change page structures concurrently. The next world-stopped verify re-checks. */
7060 if (!data->world_stopped) return;
7061
7062 /* A non-heap child reaches this callback only when a stale field was followed by a
7063 * plain rb_gc_mark (the dmark of a live but unreachable wrapper, say). Report it and
7064 * keep going rather than aborting. */
7065 if (!verify_pointer_in_any_heap_p((void *)child)) {
7066 /* The graph is in flux mid-merge, so a transient non-heap edge is expected; it
7067 * is re-checked after the merge. */
7068 if (global_objspace->during_absorb) return;
7069 fprintf(stderr, "VERIFY-NOTE: non-heap child %p (from %s)\n",
7070 (void *)child, rb_obj_info(data->parent));
7071 return;
7072 }
7073
7074 if (GET_HEAP_OBJSPACE(child) != data->objspace) {
7075 /* A legal cross-objspace edge either starts at a shareable object or is recorded
7076 * in the child's shref bit (an in-flight send or move payload kept alive across
7077 * its owner's local GC; root_scope_check_i honours the same record). An
7078 * unshareable parent holding an unrecorded foreign unshareable child would be
7079 * invisible to both local GCs. The exception is a box's top_self, which every
7080 * thread's th->top_self points at and which is VM-permanent. Skipped during a
7081 * global GC: it clears every shref bit, so the shref exemption would not fire,
7082 * and its unified exact stop-the-world mark makes the invariant itself moot. */
7083 if (!data->parent_shareable &&
7084 child != rb_gc_vm_top_self() &&
7085 !MARKED_IN_BITMAP(GET_HEAP_SHAREABLE_BITS(child), child) &&
7086 !MARKED_IN_BITMAP(GET_HEAP_SHREF_BITS(child), child) &&
7087 !rb_gc_impl_during_global_gc_p(data->objspace) &&
7088 !global_objspace->during_absorb) {
7089 fprintf(stderr, "check_children_i: containment violation: "
7090 "unshareable %s (objspace %p) -> foreign unshareable %s (objspace %p)\n",
7091 rb_obj_info(data->parent), (void *)data->objspace,
7092 rb_obj_info(child), (void *)GET_HEAP_OBJSPACE(child));
7093 data->err_count++;
7094 }
7095
7096 /* The remaining per-objspace sanity rules belong to the owner. */
7097 return;
7098 }
7099}
7100
7101/* Whether a heap slot currently holds a live object. Returns false for empty
7102 * (T_NONE), moved (T_MOVED), and zombie (T_ZOMBIE) slots, and for garbage
7103 * objects about to be swept. */
7104static bool
7105gc_slot_live_object_p(rb_objspace_t *objspace, VALUE obj)
7106{
7107 switch (BUILTIN_TYPE(obj)) {
7108 case T_NONE:
7109 case T_MOVED:
7110 case T_ZOMBIE:
7111 return false;
7112 default:
7113 return !rb_gc_impl_garbage_object_p(objspace, obj);
7114 }
7115}
7116
7117/* Verifier only: does ptr point at a live slot in any objspace? The caller holds the VM
7118 * lock and the barrier, so page_index is stable. */
7119static bool
7120verify_pointer_in_any_heap_p(const void *ptr)
7121{
7122 return gc_global_pointer_to_heap_p(ptr);
7123}
7124
7125/* An exact root of the calling Ractor may only point at a shareable object, its own
7126 * objspace, or an in-flight payload with a recorded shref. Exempt: the conservative
7127 * machine scan (stale slots) and the VM-global containers that are cross-rooted by
7128 * design (every objspace scans them; the marker skips foreign entries). */
7129static void
7130root_scope_check_i(const char *category, VALUE obj, void *ptr)
7131{
7132 struct verify_internal_consistency_struct *data = ptr;
7133
7134 if (RB_SPECIAL_CONST_P(obj)) return;
7135 /* This check walks every objspace (verify_pointer_in_any_heap_p), so it is sound
7136 * only with the world stopped; a mid-local-GC verify races with other Ractors'
7137 * lock-free allocation. */
7138 if (!data->world_stopped) return;
7139 /* Mid-merge the VM-global root tables still point at the unmerged source (transient
7140 * non-heap or foreign roots); re-checked after the merge. */
7141 if (global_objspace->during_absorb) return;
7142 if (strcmp(category, "machine_context") == 0 ||
7143 strcmp(category, "vm_registered_objects") == 0 ||
7144 strcmp(category, "end_proc") == 0 ||
7145 strcmp(category, "trap_list") == 0) {
7146 return;
7147 }
7148
7149 if (!verify_pointer_in_any_heap_p((void *)obj)) {
7150 fprintf(stderr, "root_scope_check_i: root category \"%s\" names a non-heap pointer %p\n",
7151 category, (void *)obj);
7152 data->err_count++;
7153 return;
7154 }
7155
7156 if (GET_HEAP_OBJSPACE(obj) == data->objspace) return;
7157 if (MARKED_IN_BITMAP(GET_HEAP_SHAREABLE_BITS(obj), obj)) return;
7158 if (MARKED_IN_BITMAP(GET_HEAP_SHREF_BITS(obj), obj)) return;
7159 if (obj == rb_gc_vm_top_self()) return; /* VM-permanent (see check_children_i) */
7160
7161 fprintf(stderr, "root_scope_check_i: root category \"%s\" names a foreign "
7162 "unshareable without a shref record: %s (owner %p, self %p)\n",
7163 category, rb_obj_info(obj),
7164 (void *)GET_HEAP_OBJSPACE(obj), (void *)data->objspace);
7165 data->err_count++;
7166}
7167
7168static int
7169verify_internal_consistency_i(void *page_start, void *page_end, size_t stride,
7171{
7172 VALUE obj;
7173 rb_objspace_t *objspace = data->objspace;
7174
7175 for (obj = (VALUE)page_start; obj != (VALUE)page_end; obj += stride) {
7176 asan_unpoisoning_object(obj) {
7177 bool sh_bit = MARKED_IN_BITMAP(GET_HEAP_SHAREABLE_BITS(obj), obj) != 0;
7178 bool sr_bit = MARKED_IN_BITMAP(GET_HEAP_SHREF_BITS(obj), obj) != 0;
7179
7180 if (gc_slot_live_object_p(objspace, obj)) {
7181 /* count objects */
7182 data->live_object_count++;
7183 data->parent = obj;
7184 data->parent_shareable = sh_bit;
7185
7186 /* Bitmap invariants: a page's shareable bit matches FL_SHAREABLE
7187 * exactly, and a shref record only ever points at an unshareable
7188 * object. */
7189 if (sh_bit != !!RB_FL_TEST_RAW(obj, RUBY_FL_SHAREABLE)) {
7190 fprintf(stderr, "verify_internal_consistency_i: shareable bit %d "
7191 "disagrees with FL_SHAREABLE on %s\n", (int)sh_bit, rb_obj_info(obj));
7192 data->err_count++;
7193 }
7194 if (sr_bit && sh_bit) {
7195 fprintf(stderr, "verify_internal_consistency_i: shref bit on a shareable: %s\n",
7196 rb_obj_info(obj));
7197 data->err_count++;
7198 }
7199
7200 /* Normally, we don't expect T_MOVED objects to be in the heap.
7201 * But they can stay alive on the stack, */
7202 if (!gc_object_moved_p(objspace, obj)) {
7203 /* moved slots don't have children */
7204 rb_objspace_reachable_objects_from_unlocked(obj, check_children_i, (void *)data);
7205 }
7206
7207 /* check health of children */
7208 if (RVALUE_OLD_P(objspace, obj)) data->old_object_count++;
7209 if (RVALUE_WB_UNPROTECTED(objspace, obj) && RVALUE_UNCOLLECTIBLE(objspace, obj)) data->remembered_shady_count++;
7210
7211 if (!is_marking(objspace) && RVALUE_OLD_P(objspace, obj)) {
7212 /* reachable objects from an oldgen object should be old or (young with remember) */
7213 data->parent = obj;
7214 rb_objspace_reachable_objects_from_unlocked(obj, check_generation_i, (void *)data);
7215 }
7216
7217 if (!is_marking(objspace) && rb_gc_obj_shareable_p(obj)) {
7218 rb_gc_verify_shareable(obj);
7219 }
7220
7221 if (is_incremental_marking(objspace)) {
7222 if (RVALUE_BLACK_P(objspace, obj)) {
7223 /* reachable objects from black objects should be black or grey objects */
7224 data->parent = obj;
7225 rb_objspace_reachable_objects_from_unlocked(obj, check_color_i, (void *)data);
7226 }
7227 }
7228 }
7229 else {
7230 /* A freed slot must not carry its old pin bit into the next object born
7231 * there (a dead object not swept yet legitimately keeps it until the
7232 * sweep arrives). */
7233 if (BUILTIN_TYPE(obj) == T_NONE && (sh_bit || sr_bit)) {
7234 fprintf(stderr, "verify_internal_consistency_i: T_NONE slot carries "
7235 "shareable=%d shref=%d bits\n", (int)sh_bit, (int)sr_bit);
7236 data->err_count++;
7237 }
7238
7239 if (BUILTIN_TYPE(obj) == T_ZOMBIE) {
7240 data->zombie_object_count++;
7241
7242 if ((RBASIC(obj)->flags & ~ZOMBIE_OBJ_KEPT_FLAGS) != T_ZOMBIE) {
7243 fprintf(stderr, "verify_internal_consistency_i: T_ZOMBIE has extra flags set: %s\n",
7244 rb_obj_info(obj));
7245 data->err_count++;
7246 }
7247
7248 if (!!FL_TEST(obj, FL_FINALIZE) != !!st_is_member(finalizer_table, obj)) {
7249 fprintf(stderr, "verify_internal_consistency_i: FL_FINALIZE %s but %s finalizer_table: %s\n",
7250 FL_TEST(obj, FL_FINALIZE) ? "set" : "not set", st_is_member(finalizer_table, obj) ? "in" : "not in",
7251 rb_obj_info(obj));
7252 data->err_count++;
7253 }
7254 }
7255 }
7256 }
7257 }
7258
7259 return 0;
7260}
7261
7262static int
7263gc_verify_heap_page(rb_objspace_t *objspace, struct heap_page *page, VALUE obj)
7264{
7265 unsigned int has_remembered_shady = FALSE;
7266 unsigned int has_remembered_old = FALSE;
7267 int remembered_old_objects = 0;
7268 int free_objects = 0;
7269 int zombie_objects = 0;
7270
7271 short slot_size = page->slot_size;
7272 uintptr_t start = (uintptr_t)page->start;
7273 uintptr_t end = start + page->total_slots * slot_size;
7274
7275 for (uintptr_t ptr = start; ptr < end; ptr += slot_size) {
7276 VALUE val = (VALUE)ptr;
7277 asan_unpoisoning_object(val) {
7278 enum ruby_value_type type = BUILTIN_TYPE(val);
7279
7280 if (type == T_NONE) free_objects++;
7281 if (type == T_ZOMBIE) zombie_objects++;
7282 if (RVALUE_PAGE_UNCOLLECTIBLE(page, val) && RVALUE_PAGE_WB_UNPROTECTED(page, val)) {
7283 has_remembered_shady = TRUE;
7284 }
7285 if (RVALUE_PAGE_MARKING(page, val)) {
7286 has_remembered_old = TRUE;
7287 remembered_old_objects++;
7288 }
7289 }
7290 }
7291
7292 if (!is_incremental_marking(objspace) &&
7293 page->flags.has_remembered_objects == FALSE && has_remembered_old == TRUE) {
7294
7295 for (uintptr_t ptr = start; ptr < end; ptr += slot_size) {
7296 VALUE val = (VALUE)ptr;
7297 if (RVALUE_PAGE_MARKING(page, val)) {
7298 fprintf(stderr, "marking -> %s\n", rb_obj_info(val));
7299 }
7300 }
7301 rb_bug("page %p's has_remembered_objects should be false, but there are remembered old objects (%d). %s",
7302 (void *)page, remembered_old_objects, obj ? rb_obj_info(obj) : "");
7303 }
7304
7305 if (page->flags.has_uncollectible_wb_unprotected_objects == FALSE && has_remembered_shady == TRUE) {
7306 rb_bug("page %p's has_remembered_shady should be false, but there are remembered shady objects. %s",
7307 (void *)page, obj ? rb_obj_info(obj) : "");
7308 }
7309
7310 if (0) {
7311 /* free_slots may not equal to free_objects */
7312 if (page->free_slots != free_objects) {
7313 rb_bug("page %p's free_slots should be %d, but %d", (void *)page, page->free_slots, free_objects);
7314 }
7315 }
7316 if (page->final_slots != zombie_objects) {
7317 rb_bug("page %p's final_slots should be %d, but %d", (void *)page, page->final_slots, zombie_objects);
7318 }
7319
7320 return remembered_old_objects;
7321}
7322
7323static int
7324gc_verify_heap_pages_(rb_objspace_t *objspace, struct ccan_list_head *head)
7325{
7326 int remembered_old_objects = 0;
7327 struct heap_page *page = 0;
7328
7329 ccan_list_for_each(head, page, page_node) {
7330 asan_unlock_freelist(page);
7331 struct free_region *region = page->free_region;
7332 while (region) {
7333 VALUE vp = (VALUE)region;
7334 rb_asan_unpoison_object(vp, false);
7335 if (BUILTIN_TYPE(vp) != T_NONE) {
7336 fprintf(stderr, "free region head expected to be T_NONE but was: %s\n", rb_obj_info(vp));
7337 }
7338 struct free_region *next = region->next;
7339 rb_asan_poison_object(vp);
7340 region = next;
7341 }
7342 asan_lock_freelist(page);
7343
7344 if (page->flags.has_remembered_objects == FALSE) {
7345 remembered_old_objects += gc_verify_heap_page(objspace, page, Qfalse);
7346 }
7347 }
7348
7349 return remembered_old_objects;
7350}
7351
7352static int
7353gc_verify_heap_pages(rb_objspace_t *objspace)
7354{
7355 int remembered_old_objects = 0;
7356 for (int i = 0; i < HEAP_COUNT; i++) {
7357 remembered_old_objects += gc_verify_heap_pages_(objspace, &((&heaps[i])->pages));
7358 }
7359 return remembered_old_objects;
7360}
7361
7362static void
7363verify_registered_addr(VALUE *slot, VALUE initial_value, void *owner_objspace, void *d)
7364{
7365 struct verify_internal_consistency_struct *data = d;
7366 VALUE v = *slot;
7367
7368 /* Conservative registration permits uninitialized data and pre-registration
7369 * values; only a store made after registration is a violation. */
7370 if (v == initial_value) return;
7371 if (SPECIAL_CONST_P(v)) return;
7372 if (!verify_pointer_in_any_heap_p((void *)v)) return;
7373
7374 bool live = false;
7375 asan_unpoisoning_object(v) {
7376 live = BUILTIN_TYPE(v) != T_NONE && BUILTIN_TYPE(v) != T_ZOMBIE;
7377 }
7378 if (!live) return;
7379
7380 rb_objspace_t *value_objspace = GET_HEAP_OBJSPACE(v);
7381 if (value_objspace == (rb_objspace_t *)owner_objspace) return;
7382 /* Join and orphan handling move a registration to the inheritor before the
7383 * source objspace merge; a global GC scans every registry while the zombie
7384 * exists, so this is a safe transient exemption. */
7385 if (value_objspace->zombie_pages != 0) return;
7386 if (value_objspace->flags.during_postmortem) return;
7387 if (MARKED_IN_BITMAP(GET_HEAP_SHAREABLE_BITS(v), v)) return;
7388 if (MARKED_IN_BITMAP(GET_HEAP_SHREF_BITS(v), v)) return;
7389 /* When multiple Ractors register one address, ownership by any registrant is
7390 * enough to root the value. */
7391 if (rb_gc_registered_addr_owned_by_registrant_p(slot, value_objspace)) return;
7392
7393 fprintf(stderr, "registered address %p changed since registration to an unshareable object owned by another Ractor: %s\n",
7394 (void *)slot, rb_obj_info(v));
7395 data->err_count++;
7396}
7397
7398static void
7399gc_verify_internal_consistency_(rb_objspace_t *objspace, bool world_stopped)
7400{
7401 struct verify_internal_consistency_struct data = {0};
7402
7403 data.objspace = objspace;
7404 data.world_stopped = world_stopped;
7405 gc_report(5, objspace, "gc_verify_internal_consistency: start\n");
7406
7407 /* check relations */
7408 for (size_t i = 0; i < rb_darray_size(objspace->heap_pages.sorted); i++) {
7409 struct heap_page *page = rb_darray_get(objspace->heap_pages.sorted, i);
7410 short slot_size = page->slot_size;
7411
7412 uintptr_t start = (uintptr_t)page->start;
7413 uintptr_t end = start + page->total_slots * slot_size;
7414
7415 verify_internal_consistency_i((void *)start, (void *)end, slot_size, &data);
7416 }
7417
7418 /* Check the calling Ractor's root scoping (only when verifying the current
7419 * objspace). Skipped during a global GC, which deliberately spans every Ractor's
7420 * roots and legitimately reaches foreign objects: containment does not apply. */
7421 if (!rb_gc_single_objspace_p() && objspace == rb_gc_get_objspace() &&
7422 !rb_gc_impl_during_global_gc_p(objspace)) {
7423 rb_objspace_reachable_objects_from_root(root_scope_check_i, &data);
7424 }
7425
7426 if (data.world_stopped && !global_objspace->during_absorb) {
7427 rb_gc_each_registered_addr(verify_registered_addr, &data);
7428 }
7429
7430 if (data.err_count != 0) {
7431#if RGENGC_CHECK_MODE >= 5
7432 objspace->rgengc.error_count = data.err_count;
7433 gc_marks_check(objspace, NULL, NULL);
7434 allrefs_dump(objspace);
7435#endif
7436 rb_bug("gc_verify_internal_consistency: found internal inconsistency.");
7437 }
7438
7439 /* check heap_page status */
7440 gc_verify_heap_pages(objspace);
7441
7442 /* check counters */
7443
7444 if (!is_lazy_sweeping(objspace) &&
7445 !finalizing &&
7446 !rb_gc_multi_ractor_p()) {
7447 if (objspace_live_slots(objspace) != data.live_object_count) {
7448 fprintf(stderr, "heap_pages_final_slots: %"PRIdSIZE", total_freed_objects: %"PRIdSIZE"\n",
7449 total_final_slots_count(objspace), total_freed_objects(objspace));
7450 rb_bug("inconsistent live slot number: expect %"PRIuSIZE", but %"PRIuSIZE".",
7451 objspace_live_slots(objspace), data.live_object_count);
7452 }
7453 }
7454
7455 if (!is_marking(objspace)) {
7456 if (objspace->rgengc.old_objects != data.old_object_count) {
7457 rb_bug("inconsistent old slot number: expect %"PRIuSIZE", but %"PRIuSIZE".",
7458 objspace->rgengc.old_objects, data.old_object_count);
7459 }
7460 if (objspace->rgengc.uncollectible_wb_unprotected_objects != data.remembered_shady_count) {
7461 rb_bug("inconsistent number of wb unprotected objects: expect %"PRIuSIZE", but %"PRIuSIZE".",
7462 objspace->rgengc.uncollectible_wb_unprotected_objects, data.remembered_shady_count);
7463 }
7464 }
7465
7466 if (!finalizing) {
7467 size_t list_count = 0;
7468
7469 {
7470 VALUE z = heap_pages_deferred_final;
7471 while (z) {
7472 list_count++;
7473 z = RZOMBIE(z)->next;
7474 }
7475 }
7476
7477 if (total_final_slots_count(objspace) != data.zombie_object_count ||
7478 total_final_slots_count(objspace) != list_count) {
7479
7480 rb_bug("inconsistent finalizing object count:\n"
7481 " expect %"PRIuSIZE"\n"
7482 " but %"PRIuSIZE" zombies\n"
7483 " heap_pages_deferred_final list has %"PRIuSIZE" items.",
7484 total_final_slots_count(objspace),
7485 data.zombie_object_count,
7486 list_count);
7487 }
7488 }
7489
7490 gc_report(5, objspace, "gc_verify_internal_consistency: OK\n");
7491}
7492
7493/* The `during_gc` macro expands a bare identifier to `objspace->flags.during_gc`, so a
7494 * foreign objspace's flag cannot be written directly; these helpers reach it through the
7495 * `objspace` argument. */
7496static inline unsigned int
7497gc_during_gc_get(const rb_objspace_t *objspace)
7498{
7499 return during_gc;
7500}
7501
7502static inline void
7503gc_during_gc_set(rb_objspace_t *objspace, unsigned int v)
7504{
7505 during_gc = v;
7506}
7507
7508/* Run the check with during_gc cleared in both the verified objspace and the current
7509 * Ractor's: rb_objspace_reachable_objects_from() decides on rb_gc_get_objspace(), and
7510 * under a global GC the driver verifies foreign objspaces, so the driver's during_gc
7511 * needs clearing too (a no-op when cur == objspace). */
7512static void
7513gc_verify_internal_consistency_body(rb_objspace_t *objspace, bool world_stopped)
7514{
7515 const unsigned int prev_during_gc = during_gc;
7516 during_gc = FALSE; // stop gc here
7517
7518 rb_objspace_t *const cur = rb_gc_get_objspace();
7519 const unsigned int prev_cur_during_gc = (cur != objspace) ? gc_during_gc_get(cur) : 0;
7520 if (cur != objspace) gc_during_gc_set(cur, FALSE);
7521 {
7522 gc_verify_internal_consistency_(objspace, world_stopped);
7523 }
7524 if (cur != objspace) gc_during_gc_set(cur, prev_cur_during_gc);
7525 during_gc = prev_during_gc;
7526}
7527
7528static void
7529gc_verify_internal_consistency(void *objspace_ptr)
7530{
7531 rb_objspace_t *objspace = objspace_ptr;
7532
7533 /* Called mid-GC, take neither the VM lock nor the barrier: waiting would join a
7534 * pending global barrier mid-collection (a GC must never take the VM lock) and let
7535 * the global GC sweep the heap this mark is walking. The barrier is unnecessary
7536 * anyway; the objspace is single-writer, this verify runs on its owner thread, and
7537 * the global driver that sets during_gc everywhere already holds both. */
7538 if (during_gc) {
7539 /* The world is stopped only when the global GC's driver runs this while holding
7540 * the barrier; a non-main Ractor's local GC does not stop other Ractors. */
7541 gc_verify_internal_consistency_body(objspace, rb_gc_impl_during_global_gc_p(objspace));
7542 return;
7543 }
7544
7545 unsigned int lev = RB_GC_VM_LOCK();
7546 {
7547 rb_gc_vm_barrier(); // stop other ractors
7548 gc_verify_internal_consistency_body(objspace, true); // holding the barrier, so walking every objspace is sound
7549 }
7550 RB_GC_VM_UNLOCK(lev);
7551}
7552
7553static void
7554heap_move_pooled_pages_to_free_pages(rb_heap_t *heap)
7555{
7556 if (heap->pooled_pages) {
7557 if (heap->free_pages) {
7558 struct heap_page *free_pages_tail = heap->free_pages;
7559 while (free_pages_tail->free_next) {
7560 free_pages_tail = free_pages_tail->free_next;
7561 }
7562 free_pages_tail->free_next = heap->pooled_pages;
7563 }
7564 else {
7565 heap->free_pages = heap->pooled_pages;
7566 }
7567
7568 heap->pooled_pages = NULL;
7569 }
7570}
7571
7572static int
7573gc_remember_unprotected(rb_objspace_t *objspace, VALUE obj)
7574{
7575 struct heap_page *page = GET_HEAP_PAGE(obj);
7576 bits_t *uncollectible_bits = &page->uncollectible_bits[0];
7577
7578 if (!MARKED_IN_BITMAP(uncollectible_bits, obj)) {
7579 page->flags.has_uncollectible_wb_unprotected_objects = TRUE;
7580 MARK_IN_BITMAP(uncollectible_bits, obj);
7581 /* Like RVALUE_PAGE_OLD_UNCOLLECTIBLE_SET, count it in the object's own objspace. */
7582 page->objspace->rgengc.uncollectible_wb_unprotected_objects++;
7583
7584#if RGENGC_PROFILE > 0
7585 objspace->profile.total_remembered_shady_object_count++;
7586#if RGENGC_PROFILE >= 2
7587 objspace->profile.remembered_shady_object_count_types[BUILTIN_TYPE(obj)]++;
7588#endif
7589#endif
7590 return TRUE;
7591 }
7592 else {
7593 return FALSE;
7594 }
7595}
7596
7597static inline void
7598gc_marks_wb_unprotected_objects_plane(rb_objspace_t *objspace, uintptr_t p, bits_t bits, short slot_size)
7599{
7600 if (bits) {
7601 do {
7602 if (bits & 1) {
7603 gc_report(2, objspace, "gc_marks_wb_unprotected_objects: marked shady: %s\n", rb_obj_info((VALUE)p));
7604 GC_ASSERT(RVALUE_WB_UNPROTECTED(objspace, (VALUE)p));
7605 GC_ASSERT(RVALUE_MARKED(objspace, (VALUE)p));
7606 gc_mark_children(objspace, (VALUE)p);
7607 }
7608 p += slot_size;
7609 bits >>= 1;
7610 } while (bits);
7611 }
7612}
7613
7614static void
7615gc_marks_wb_unprotected_objects(rb_objspace_t *objspace, rb_heap_t *heap)
7616{
7617 struct heap_page *page = 0;
7618
7619 ccan_list_for_each(&heap->pages, page, page_node) {
7620 bits_t *mark_bits = page->mark_bits;
7621 bits_t *wbun_bits = page->wb_unprotected_bits;
7622 uintptr_t p = page->start;
7623 short slot_size = page->slot_size;
7624 int total_slots = page->total_slots;
7625 int bitmap_plane_count = CEILDIV(total_slots, BITS_BITLENGTH);
7626 size_t j;
7627
7628 for (j=0; j<(size_t)bitmap_plane_count; j++) {
7629 bits_t bits = mark_bits[j] & wbun_bits[j];
7630 gc_marks_wb_unprotected_objects_plane(objspace, p, bits, slot_size);
7631 p += BITS_BITLENGTH * slot_size;
7632 }
7633 }
7634
7635 gc_mark_stacked_objects_all(objspace);
7636}
7637
7638void
7639rb_gc_impl_declare_weak_references(void *objspace_ptr, VALUE obj)
7640{
7642}
7643
7644bool
7645rb_gc_impl_handle_weak_references_alive_p(void *objspace_ptr, VALUE obj)
7646{
7647 rb_objspace_t *objspace = objspace_ptr;
7648
7649 /* A local GC cannot decide a foreign object's liveness, so treat it as live; its
7650 * owner or the global GC decides (a global GC's unified mark is exact). */
7651 if (gc_skip_foreign_object_p(objspace, obj)) return true;
7652
7653 bool marked = RVALUE_MARKED(objspace, obj);
7654
7655 if (marked) {
7656 rgengc_check_relation(objspace, obj);
7657 }
7658
7659 return marked;
7660}
7661
7662static void
7663gc_update_weak_references(rb_objspace_t *objspace)
7664{
7665 VALUE *obj_ptr;
7666 rb_darray_foreach(objspace->weak_references, i, obj_ptr) {
7667 gc_mark_set_parent(objspace, *obj_ptr);
7668 rb_gc_handle_weak_references(*obj_ptr);
7669 gc_mark_set_parent_invalid(objspace);
7670 }
7671
7672 size_t capa = rb_darray_capa(objspace->weak_references);
7673 size_t size = rb_darray_size(objspace->weak_references);
7674
7675 objspace->profile.weak_references_count = size;
7676
7677 rb_darray_clear(objspace->weak_references);
7678
7679 /* If the darray has capacity for more than four times the amount used, we
7680 * shrink it down to half of that capacity. */
7681 if (capa > size * 4) {
7682 rb_darray_resize_capa_without_gc(&objspace->weak_references, size * 2);
7683 }
7684}
7685
7686static void
7687gc_marks_finish(rb_objspace_t *objspace)
7688{
7689 /* finish incremental GC */
7690 if (is_incremental_marking(objspace)) {
7691 if (RGENGC_CHECK_MODE && is_mark_stack_empty(&objspace->mark_stack) == 0) {
7692 rb_bug("gc_marks_finish: mark stack is not empty (%"PRIdSIZE").",
7693 mark_stack_size(&objspace->mark_stack));
7694 }
7695
7696 mark_roots(objspace, NULL);
7697 while (gc_mark_stacked_objects_incremental(objspace, INT_MAX) == false);
7698
7699#if RGENGC_CHECK_MODE >= 2
7700 if (gc_verify_heap_pages(objspace) != 0) {
7701 rb_bug("gc_marks_finish (incremental): there are remembered old objects.");
7702 }
7703#endif
7704
7705 gc_set_incremental_marking(objspace, FALSE);
7706 /* check children of all marked wb-unprotected objects */
7707 for (int i = 0; i < HEAP_COUNT; i++) {
7708 gc_marks_wb_unprotected_objects(objspace, &heaps[i]);
7709 }
7710 }
7711
7712 /* Pin the shareable objects and shrefs ordinary marking missed: a local GC must free
7713 * neither (another objspace may hold them). Running after the full walk makes the
7714 * pin count a retention metric: an upper bound on the garbage only a global GC can
7715 * reclaim. A global GC's exact mark does not pin. (The allrefs comparison of
7716 * RGENGC_CHECK_MODE >= 4 does not model these pins; it reports false positives.)
7717 *
7718 * Running it here rather than with the other roots is also what lets an incremental
7719 * mark run while other objspaces exist. The write barrier bails out on a
7720 * cross-objspace edge, so a store made between two mark steps leaves nothing behind
7721 * but a shareable or shref bit; scanning those bitmaps after the last step picks up
7722 * every bit set during the cycle, which a scan at gc_marks_start would miss. */
7723 objspace->last_cycle_pinned = 0;
7724 if (!rb_gc_single_objspace_p() && !objspace->flags.during_global_gc) {
7725 objspace->last_cycle_pinned = 1;
7726 gc_mark_set_parent_raw(objspace, Qundef, false);
7727 for (int i = 0; i < HEAP_COUNT; i++) {
7728 pinned_roots_mark(objspace, &heaps[i]);
7729 }
7730 /* And everything they keep alive. */
7731 gc_mark_stacked_objects_all(objspace);
7732 }
7733
7734 gc_update_weak_references(objspace);
7735
7736#if RGENGC_CHECK_MODE >= 4
7737 during_gc = FALSE;
7738 gc_marks_check(objspace, gc_check_after_marks_i, "after_marks");
7739 during_gc = TRUE;
7740#endif
7741
7742 {
7743 /* Only this objspace's own Ractor allocates from it. The main objspace
7744 * keeps the VM-wide count it has used since before per-Ractor GC. */
7745 const unsigned long ractor_cnt = objspace == global_objspace->main_objspace
7746 ? rb_gc_vm_ractor_count() : 1;
7747 const unsigned long r_mul = ractor_cnt > 8 ? 8 : ractor_cnt; // upto 8
7748
7749 size_t total_slots = objspace_available_slots(objspace);
7750 size_t sweep_slots = total_slots - objspace->marked_slots; /* will be swept slots */
7751 size_t max_free_slots = (size_t)(total_slots * gc_params.heap_free_slots_max_ratio);
7752 size_t min_free_slots = (size_t)(total_slots * gc_params.heap_free_slots_min_ratio);
7753 if (min_free_slots < gc_params.heap_free_slots * r_mul) {
7754 min_free_slots = gc_params.heap_free_slots * r_mul;
7755 }
7756
7757 int full_marking = is_full_marking(objspace);
7758
7759 GC_ASSERT(objspace_available_slots(objspace) >= objspace->marked_slots);
7760
7761 /* Setup freeable slots. */
7762 size_t total_init_slots = 0;
7763 for (int i = 0; i < HEAP_COUNT; i++) {
7764 total_init_slots += (objspace_heap_init_bytes(objspace) / heaps[i].slot_size) * r_mul;
7765 }
7766
7767 if (max_free_slots < total_init_slots) {
7768 max_free_slots = total_init_slots;
7769 }
7770
7771 /* Approximate freeable pages using the average slots-per-pages across all heaps */
7772 if (sweep_slots > max_free_slots) {
7773 size_t excess_slots = sweep_slots - max_free_slots;
7774 size_t total_heap_pages = heap_eden_total_pages(objspace);
7775 heap_pages_freeable_pages = total_heap_pages > 0
7776 ? excess_slots * total_heap_pages / total_slots
7777 : 0;
7778 }
7779 else {
7780 heap_pages_freeable_pages = 0;
7781 }
7782
7783 if (objspace->heap_pages.allocatable_bytes == 0 && sweep_slots < min_free_slots) {
7784 if (!full_marking && sweep_slots < min_free_slots * 7 / 8) {
7785 if (objspace->profile.count - objspace->rgengc.last_major_gc < RVALUE_OLD_AGE) {
7786 full_marking = TRUE;
7787 }
7788 else {
7789 gc_report(1, objspace, "gc_marks_finish: next is full GC!!)\n");
7790 gc_needs_major_flags |= GPR_FLAG_MAJOR_BY_NOFREE;
7791 }
7792 }
7793
7794 if (full_marking) {
7795 heap_allocatable_bytes_expand(objspace, NULL, sweep_slots, total_slots, heaps[0].slot_size);
7796 }
7797 }
7798
7799 if (full_marking) {
7800 /* See the comment about RUBY_GC_HEAP_OLDOBJECT_LIMIT_FACTOR */
7801 const double r = gc_params.oldobject_limit_factor;
7802 objspace->rgengc.uncollectible_wb_unprotected_objects_limit = MAX(
7803 (size_t)(objspace->rgengc.uncollectible_wb_unprotected_objects * r),
7804 (size_t)(objspace->rgengc.old_objects * gc_params.uncollectible_wb_unprotected_objects_limit_ratio)
7805 );
7806 objspace->rgengc.old_objects_limit = (size_t)(objspace->rgengc.old_objects * r);
7807 }
7808
7809 if (objspace->rgengc.uncollectible_wb_unprotected_objects > objspace->rgengc.uncollectible_wb_unprotected_objects_limit) {
7810 gc_needs_major_flags |= GPR_FLAG_MAJOR_BY_SHADY;
7811 }
7812 if (objspace->rgengc.old_objects > objspace->rgengc.old_objects_limit) {
7813 gc_needs_major_flags |= GPR_FLAG_MAJOR_BY_OLDGEN;
7814 }
7815
7816 gc_report(1, objspace, "gc_marks_finish (marks %"PRIdSIZE" objects, "
7817 "old %"PRIdSIZE" objects, total %"PRIdSIZE" slots, "
7818 "sweep %"PRIdSIZE" slots, allocatable %"PRIdSIZE" bytes, next GC: %s)\n",
7819 objspace->marked_slots, objspace->rgengc.old_objects, objspace_available_slots(objspace), sweep_slots, objspace->heap_pages.allocatable_bytes,
7820 gc_needs_major_flags ? "major" : "minor");
7821 }
7822
7823 // TODO: refactor so we don't need to call this
7824 rb_ractor_finish_marking(is_full_marking(objspace));
7825
7827}
7828
7829static bool
7830gc_compact_heap_cursors_met_p(rb_heap_t *heap)
7831{
7832 return heap->sweeping_page == heap->compact_cursor;
7833}
7834
7835
7836static rb_heap_t *
7837gc_compact_destination_pool(rb_objspace_t *objspace, rb_heap_t *src_pool, VALUE obj)
7838{
7839 size_t obj_size = rb_gc_obj_optimal_size(obj);
7840 if (obj_size == 0) {
7841 return src_pool;
7842 }
7843
7844 GC_ASSERT(rb_gc_impl_size_allocatable_p(obj_size));
7845
7846 size_t idx = heap_idx_for_size(obj_size);
7847
7848 return &heaps[idx];
7849}
7850
7851static bool
7852gc_compact_move(rb_objspace_t *objspace, rb_heap_t *heap, VALUE src)
7853{
7854 GC_ASSERT(BUILTIN_TYPE(src) != T_MOVED);
7855 GC_ASSERT(gc_is_moveable_obj(objspace, src));
7856
7857 rb_heap_t *dest_pool = gc_compact_destination_pool(objspace, heap, src);
7858 if (gc_compact_heap_cursors_met_p(dest_pool)) {
7859 return dest_pool != heap;
7860 }
7861
7862 while (!try_move(objspace, dest_pool, dest_pool->free_pages, src)) {
7863 struct gc_sweep_context ctx = {
7864 .page = dest_pool->sweeping_page,
7865 .final_slots = 0,
7866 .freed_slots = 0,
7867 .empty_slots = 0,
7868 };
7869
7870 /* The page of src could be partially compacted, so it may contain
7871 * T_MOVED. Sweeping a page may read objects on this page, so we
7872 * need to lock the page. */
7873 lock_page_body(objspace, GET_PAGE_BODY(src));
7874 gc_sweep_page(objspace, dest_pool, &ctx);
7875 unlock_page_body(objspace, GET_PAGE_BODY(src));
7876
7877 if (dest_pool->sweeping_page->free_slots > 0) {
7878 heap_add_freepage(dest_pool, dest_pool->sweeping_page);
7879 }
7880
7881 dest_pool->sweeping_page = ccan_list_next(&dest_pool->pages, dest_pool->sweeping_page, page_node);
7882 if (gc_compact_heap_cursors_met_p(dest_pool)) {
7883 return dest_pool != heap;
7884 }
7885 }
7886
7887 return true;
7888}
7889
7890static bool
7891gc_compact_plane(rb_objspace_t *objspace, rb_heap_t *heap, uintptr_t p, bits_t bitset, struct heap_page *page)
7892{
7893 short slot_size = page->slot_size;
7894
7895 do {
7896 VALUE vp = (VALUE)p;
7897 GC_ASSERT(vp % sizeof(VALUE) == 0);
7898
7899 if (bitset & 1) {
7900 objspace->rcompactor.considered_count_table[BUILTIN_TYPE(vp)]++;
7901
7902 if (gc_is_moveable_obj(objspace, vp)) {
7903 if (!gc_compact_move(objspace, heap, vp)) {
7904 //the cursors met. bubble up
7905 return false;
7906 }
7907 }
7908 }
7909 p += slot_size;
7910 bitset >>= 1;
7911 } while (bitset);
7912
7913 return true;
7914}
7915
7916// Iterate up all the objects in page, moving them to where they want to go
7917static bool
7918gc_compact_page(rb_objspace_t *objspace, rb_heap_t *heap, struct heap_page *page)
7919{
7920 GC_ASSERT(page == heap->compact_cursor);
7921
7922 bits_t *mark_bits, *pin_bits;
7923 bits_t bitset;
7924 uintptr_t p = page->start;
7925 short slot_size = page->slot_size;
7926 int total_slots = page->total_slots;
7927 int bitmap_plane_count = CEILDIV(total_slots, BITS_BITLENGTH);
7928
7929 mark_bits = page->mark_bits;
7930 pin_bits = page->pinned_bits;
7931
7932 for (int j = 0; j < bitmap_plane_count; j++) {
7933 // objects that can be moved are marked and not pinned
7934 bitset = (mark_bits[j] & ~pin_bits[j]);
7935 if (bitset) {
7936 if (!gc_compact_plane(objspace, heap, (uintptr_t)p, bitset, page))
7937 return false;
7938 }
7939 p += BITS_BITLENGTH * slot_size;
7940 }
7941
7942 return true;
7943}
7944
7945static bool
7946gc_compact_all_compacted_p(rb_objspace_t *objspace)
7947{
7948 for (int i = 0; i < HEAP_COUNT; i++) {
7949 rb_heap_t *heap = &heaps[i];
7950
7951 if (heap->total_pages > 0 &&
7952 !gc_compact_heap_cursors_met_p(heap)) {
7953 return false;
7954 }
7955 }
7956
7957 return true;
7958}
7959
7960/* Compaction's move phase: relocate this objspace's movable objects and leave T_MOVED
7961 * forwarding behind without updating references yet. A global GC calls this for every
7962 * objspace before updating any of them (two phases), so a cross-objspace reference to a
7963 * moved object is rewritten exactly once, after all forwarding exists. */
7964static void
7965gc_compact_relocate(rb_objspace_t *objspace)
7966{
7967 gc_compact_start(objspace);
7968
7969 while (!gc_compact_all_compacted_p(objspace)) {
7970 for (int i = 0; i < HEAP_COUNT; i++) {
7971 rb_heap_t *heap = &heaps[i];
7972
7973 if (gc_compact_heap_cursors_met_p(heap)) {
7974 continue;
7975 }
7976
7977 struct heap_page *start_page = heap->compact_cursor;
7978
7979 if (!gc_compact_page(objspace, heap, start_page)) {
7980 lock_page_body(objspace, start_page->body);
7981
7982 continue;
7983 }
7984
7985 // If we get here, we've finished moving all objects on the compact_cursor page
7986 // So we can lock it and move the cursor on to the next one.
7987 lock_page_body(objspace, start_page->body);
7988 heap->compact_cursor = ccan_list_prev(&heap->pages, heap->compact_cursor, page_node);
7989 }
7990 }
7991}
7992
7993static void
7994gc_sweep_compact(rb_objspace_t *objspace)
7995{
7996 gc_compact_relocate(objspace);
7997 /* A compacting global GC defers the finish (reference update) to the second phase,
7998 * after every objspace has been relocated. */
7999 if (!global_objspace->global_gc.compacting) {
8000 gc_compact_finish(objspace);
8001 }
8002}
8003
8004static void
8005gc_marks_rest(rb_objspace_t *objspace)
8006{
8007 gc_report(1, objspace, "gc_marks_rest\n");
8008
8009 for (int i = 0; i < HEAP_COUNT; i++) {
8010 (&heaps[i])->pooled_pages = NULL;
8011 }
8012
8013 if (is_incremental_marking(objspace)) {
8014 while (gc_mark_stacked_objects_incremental(objspace, INT_MAX) == FALSE);
8015 }
8016 else {
8017 gc_mark_stacked_objects_all(objspace);
8018 }
8019
8020 gc_marks_finish(objspace);
8021}
8022
8023static bool
8024gc_marks_step(rb_objspace_t *objspace, size_t slots)
8025{
8026 bool marking_finished = false;
8027
8028 GC_ASSERT(is_marking(objspace));
8029 if (gc_mark_stacked_objects_incremental(objspace, slots)) {
8030 gc_marks_finish(objspace);
8031
8032 marking_finished = true;
8033 }
8034
8035 return marking_finished;
8036}
8037
8038static bool
8039gc_marks_continue(rb_objspace_t *objspace, rb_heap_t *heap)
8040{
8041 GC_ASSERT(dont_gc_val() == FALSE || objspace->profile.latest_gc_info & GPR_FLAG_METHOD);
8042 bool marking_finished = true;
8043
8044 gc_marking_enter(objspace);
8045
8046 if (heap->free_pages) {
8047 gc_report(2, objspace, "gc_marks_continue: has pooled pages");
8048
8049 marking_finished = gc_marks_step(objspace, objspace->rincgc.step_slots);
8050 }
8051 else {
8052 gc_report(2, objspace, "gc_marks_continue: no more pooled pages (stack depth: %"PRIdSIZE").\n",
8053 mark_stack_size(&objspace->mark_stack));
8054 heap->force_incremental_marking_finish_count++;
8055 gc_marks_rest(objspace);
8056 }
8057
8058 gc_marking_exit(objspace);
8059
8060 return marking_finished;
8061}
8062
8063/* Mark the following as roots of this objspace.
8064 * - Every shareable object: another objspace may hold the only reference, invisible to a
8065 * local GC. Marking them rather than skipping them in the sweep preserves the
8066 * generational invariants (a pinned object ages and gets promoted like any live one).
8067 * Only a global GC decides that a shareable object is dead.
8068 * - Every shref (an unshareable object referenced from a shareable one): the referring
8069 * shareable object can live in another objspace or in an in-flight message queue. The
8070 * write barrier maintains them.
8071 * Skipped while the VM has a single Ractor: a local GC is then a whole-world GC and
8072 * shareable objects may die normally. */
8073static void
8074pinned_roots_mark(rb_objspace_t *objspace, rb_heap_t *heap)
8075{
8076 struct heap_page *page = NULL;
8077
8078 /* Runs before mark_roots, so rgengc_check_relation sees a valid (absent) parent rather
8079 * than the poison left by the previous GC. */
8080 gc_mark_set_parent_raw(objspace, Qundef, false);
8081
8082 /* A local GC never frees or traverses a shareable object, and keeps its unshareable
8083 * children alive through their shref bits, so:
8084 * - a shareable object only gets its mark bit set (like an old object), which keeps
8085 * the sweep off it, and is not traversed;
8086 * - a shref is marked and traversed, like a remembered old->young target: without
8087 * that, the referring shareable object is never walked and it would look
8088 * unreachable.
8089 * Objects can become shareable between GCs, so this pass scans the bitmaps in every
8090 * mark (gc_marks_finish) instead of maintaining a pin set across the sweep. */
8091 ccan_list_for_each(&heap->pages, page, page_node) {
8092 if (!(page->flags.has_shareable_objects | page->flags.has_shref_objects)) continue;
8093
8094 uintptr_t p = page->start;
8095 short slot_size = page->slot_size;
8096 int total_slots = page->total_slots;
8097 int bitmap_plane_count = CEILDIV(total_slots, BITS_BITLENGTH);
8098
8099 for (int j = 0; j < bitmap_plane_count; j++) {
8100 bits_t sr_bits = page->shref_bits[j];
8101 /* Only the pins ordinary marking left unmarked need work here: an already
8102 * marked object (reached by traversal, or pre-marked because it is old) is a
8103 * no-op in gc_mark_set, so skip visiting it. */
8104 bits_t bitset = (page->shareable_bits[j] | sr_bits) & ~page->mark_bits[j];
8105 uintptr_t pp = p;
8106 while (bitset) {
8107 if (bitset & 1) {
8108 VALUE obj = (VALUE)pp;
8109 asan_unpoisoning_object(obj) {
8110 switch (BUILTIN_TYPE(obj)) {
8111 case T_NONE:
8112 case T_ZOMBIE:
8113 case T_MOVED:
8114 /* A dead slot (a zombie awaiting its finalizer) is not a root. */
8115 break;
8116 default:
8117 gc_report(2, objspace, "pinned_roots_mark: mark %s\n", rb_obj_info(obj));
8118 if (sr_bits & 1) {
8119 gc_mark(objspace, obj); /* shref: root + traverse */
8120 }
8121 else if (gc_mark_set(objspace, obj)) {
8122 gc_aging(objspace, obj); /* shareable: mark, no traverse */
8123 /* Pin as well when compaction runs alongside: if a shareable
8124 * object moved, the C-struct slots of other Ractors (a
8125 * port in sync, say) are not updated and go stale. */
8126 gc_pin(objspace, obj);
8127 }
8128 break;
8129 }
8130 }
8131 }
8132 pp += slot_size;
8133 bitset >>= 1;
8134 sr_bits >>= 1;
8135 }
8136 p += BITS_BITLENGTH * slot_size;
8137 }
8138 }
8139}
8140
8141static void
8142gc_marks_start(rb_objspace_t *objspace, int full_mark)
8143{
8144 /* start marking */
8145 gc_report(1, objspace, "gc_marks_start: (%s)\n", full_mark ? "full" : "minor");
8146 gc_mode_transition(objspace, gc_mode_marking);
8147
8148 if (full_mark) {
8149 size_t incremental_marking_steps = (objspace->rincgc.pooled_slots / INCREMENTAL_MARK_STEP_ALLOCATIONS) + 1;
8150 objspace->rincgc.step_slots = (objspace->marked_slots * 2) / incremental_marking_steps;
8151
8152 if (0) fprintf(stderr, "objspace->marked_slots: %"PRIdSIZE", "
8153 "objspace->rincgc.pooled_page_num: %"PRIdSIZE", "
8154 "objspace->rincgc.step_slots: %"PRIdSIZE", \n",
8155 objspace->marked_slots, objspace->rincgc.pooled_slots, objspace->rincgc.step_slots);
8156 objspace->flags.during_minor_gc = FALSE;
8157 if (ruby_enable_autocompact && rb_gc_single_objspace_p()) {
8158 objspace->flags.during_compacting |= TRUE;
8159 }
8160 objspace->profile.major_gc_count++;
8161 objspace->rgengc.uncollectible_wb_unprotected_objects = 0;
8162 objspace->rgengc.old_objects = 0;
8163 objspace->rgengc.last_major_gc = objspace->profile.count;
8164 objspace->marked_slots = 0;
8165
8166 for (int i = 0; i < HEAP_COUNT; i++) {
8167 rb_heap_t *heap = &heaps[i];
8168 gc_bitmaps_clear(objspace, heap, false);
8169 heap_move_pooled_pages_to_free_pages(heap);
8170
8171 if (objspace->flags.during_compacting) {
8172 struct heap_page *page = NULL;
8173
8174 ccan_list_for_each(&heap->pages, page, page_node) {
8175 page->pinned_slots = 0;
8176 }
8177 }
8178 }
8179 }
8180 else {
8181 objspace->flags.during_minor_gc = TRUE;
8182 objspace->marked_slots =
8183 objspace->rgengc.old_objects + objspace->rgengc.uncollectible_wb_unprotected_objects; /* uncollectible objects are marked already */
8184 objspace->profile.minor_gc_count++;
8185
8186 for (int i = 0; i < HEAP_COUNT; i++) {
8187 rgengc_rememberset_mark(objspace, &heaps[i]);
8188 }
8189 }
8190
8191 mark_roots(objspace, NULL);
8192
8193 gc_report(1, objspace, "gc_marks_start: (%s) end, stack in %"PRIdSIZE"\n",
8194 full_mark ? "full" : "minor", mark_stack_size(&objspace->mark_stack));
8195}
8196
8197static bool
8198gc_marks(rb_objspace_t *objspace, int full_mark)
8199{
8200 gc_marking_enter(objspace);
8201
8202 bool marking_finished = false;
8203
8204 /* setup marking */
8205
8206 gc_marks_start(objspace, full_mark);
8207 if (!is_incremental_marking(objspace)) {
8208 gc_marks_rest(objspace);
8209 marking_finished = true;
8210 }
8211
8212#if RGENGC_PROFILE > 0
8213 if (gc_prof_record(objspace)) {
8214 gc_profile_record *record = gc_prof_record(objspace);
8215 record->old_objects = objspace->rgengc.old_objects;
8216 }
8217#endif
8218
8219 gc_marking_exit(objspace);
8220
8221 return marking_finished;
8222}
8223
8224/* RGENGC */
8225
8226static void
8227gc_report_body(int level, rb_objspace_t *objspace, const char *fmt, ...)
8228{
8229 if (level <= RGENGC_DEBUG) {
8230 char buf[1024];
8231 FILE *out = stderr;
8232 va_list args;
8233 const char *status = " ";
8234
8235 if (during_gc) {
8236 status = is_full_marking(objspace) ? "+" : "-";
8237 }
8238 else {
8239 if (is_lazy_sweeping(objspace)) {
8240 status = "S";
8241 }
8242 if (is_incremental_marking(objspace)) {
8243 status = "M";
8244 }
8245 }
8246
8247 va_start(args, fmt);
8248 vsnprintf(buf, 1024, fmt, args);
8249 va_end(args);
8250
8251 fprintf(out, "%s|", status);
8252 fputs(buf, out);
8253 }
8254}
8255
8256/* bit operations */
8257
8258static void
8259rgengc_remembersetbits_set(rb_objspace_t *objspace, VALUE obj)
8260{
8261 struct heap_page *page = GET_HEAP_PAGE(obj);
8262 bits_t *bits = &page->remembered_bits[0];
8263
8264 /* remembered_bits writers are always serialized: the write barrier only remembers a
8265 * local a (under its Ractor's GVL) and a global GC writes from the driver alone.
8266 * Set the bit before the page flag so a page pending re-scan stays in
8267 * rememberset_mark. */
8268 _MARK_IN_BITMAP(bits, page, obj);
8269 page->flags.has_remembered_objects = TRUE;
8270}
8271
8272/* wb, etc */
8273
8274/* return FALSE if already remembered */
8275static void
8276rgengc_remember(rb_objspace_t *objspace, VALUE obj)
8277{
8278 gc_report(6, objspace, "rgengc_remember: %s %s\n", rb_obj_info(obj),
8279 RVALUE_REMEMBERED(objspace, obj) ? "was already remembered" : "is remembered now");
8280
8281 check_rvalue_consistency(objspace, obj);
8282
8283 if (RGENGC_CHECK_MODE) {
8284 if (RVALUE_WB_UNPROTECTED(objspace, obj)) rb_bug("rgengc_remember: %s is not wb protected.", rb_obj_info(obj));
8285 }
8286
8287#if RGENGC_PROFILE > 0
8288 if (!RVALUE_REMEMBERED(objspace, obj)) {
8289 if (RVALUE_WB_UNPROTECTED(objspace, obj) == 0) {
8290 objspace->profile.total_remembered_normal_object_count++;
8291#if RGENGC_PROFILE >= 2
8292 objspace->profile.remembered_normal_object_count_types[BUILTIN_TYPE(obj)]++;
8293#endif
8294 }
8295 }
8296#endif /* RGENGC_PROFILE > 0 */
8297
8298 rgengc_remembersetbits_set(objspace, obj);
8299}
8300
8301#ifndef PROFILE_REMEMBERSET_MARK
8302#define PROFILE_REMEMBERSET_MARK 0
8303#endif
8304
8305static inline void
8306rgengc_rememberset_mark_plane(rb_objspace_t *objspace, uintptr_t p, bits_t bitset, short slot_size)
8307{
8308 if (bitset) {
8309 do {
8310 if (bitset & 1) {
8311 VALUE obj = (VALUE)p;
8312 gc_report(2, objspace, "rgengc_rememberset_mark: mark %s\n", rb_obj_info(obj));
8313 GC_ASSERT(RVALUE_UNCOLLECTIBLE(objspace, obj));
8314 GC_ASSERT(RVALUE_OLD_P(objspace, obj) || RVALUE_WB_UNPROTECTED(objspace, obj));
8315
8316 gc_mark_children(objspace, obj);
8317
8319 rb_darray_append_without_gc(&objspace->weak_references, obj);
8320 }
8321 }
8322 p += slot_size;
8323 bitset >>= 1;
8324 } while (bitset);
8325 }
8326}
8327
8328static void
8329rgengc_rememberset_mark(rb_objspace_t *objspace, rb_heap_t *heap)
8330{
8331 size_t j;
8332 struct heap_page *page = 0;
8333#if PROFILE_REMEMBERSET_MARK
8334 int has_old = 0, has_shady = 0, has_both = 0, skip = 0;
8335#endif
8336 gc_report(1, objspace, "rgengc_rememberset_mark: start\n");
8337
8338 ccan_list_for_each(&heap->pages, page, page_node) {
8339 if (page->flags.has_remembered_objects | page->flags.has_uncollectible_wb_unprotected_objects) {
8340 uintptr_t p = page->start;
8341 short slot_size = page->slot_size;
8342 int total_slots = page->total_slots;
8343 int bitmap_plane_count = CEILDIV(total_slots, BITS_BITLENGTH);
8344 bits_t bitset, bits[HEAP_PAGE_BITMAP_LIMIT];
8345 bits_t *remembered_bits = page->remembered_bits;
8346 bits_t *uncollectible_bits = page->uncollectible_bits;
8347 bits_t *wb_unprotected_bits = page->wb_unprotected_bits;
8348#if PROFILE_REMEMBERSET_MARK
8349 if (page->flags.has_remembered_objects && page->flags.has_uncollectible_wb_unprotected_objects) has_both++;
8350 else if (page->flags.has_remembered_objects) has_old++;
8351 else if (page->flags.has_uncollectible_wb_unprotected_objects) has_shady++;
8352#endif
8353 /* Clear has_remembered_objects before draining the bits. A concurrent
8354 * lock-free write barrier (another Ractor remembering a shareable object on
8355 * this page) sets the bit first and the flag second, so clearing the flag first
8356 * keeps the page scheduled for re-scan even if that set interleaves. The
8357 * per-word drain is an atomic read-and-clear, so an interleaved set is not lost
8358 * (it lands in the zeroed word). */
8359 page->flags.has_remembered_objects = FALSE;
8360 for (j=0; j < (size_t)bitmap_plane_count; j++) {
8361 bits[j] = RUBY_ATOMIC_SIZE_EXCHANGE(*(volatile size_t *)&remembered_bits[j], 0)
8362 | (uncollectible_bits[j] & wb_unprotected_bits[j]);
8363 }
8364
8365 for (j=0; j < (size_t)bitmap_plane_count; j++) {
8366 bitset = bits[j];
8367 rgengc_rememberset_mark_plane(objspace, p, bitset, slot_size);
8368 p += BITS_BITLENGTH * slot_size;
8369 }
8370 }
8371#if PROFILE_REMEMBERSET_MARK
8372 else {
8373 skip++;
8374 }
8375#endif
8376 }
8377
8378#if PROFILE_REMEMBERSET_MARK
8379 fprintf(stderr, "%d\t%d\t%d\t%d\n", has_both, has_old, has_shady, skip);
8380#endif
8381 gc_report(1, objspace, "rgengc_rememberset_mark: finished\n");
8382}
8383
8384static void
8385gc_bitmaps_clear(rb_objspace_t *objspace, rb_heap_t *heap, bool clear_shref)
8386{
8387 struct heap_page *page = 0;
8388
8389 ccan_list_for_each(&heap->pages, page, page_node) {
8390 memset(&page->mark_bits[0], 0, HEAP_PAGE_BITMAP_SIZE);
8391 memset(&page->uncollectible_bits[0], 0, HEAP_PAGE_BITMAP_SIZE);
8392 memset(&page->marking_bits[0], 0, HEAP_PAGE_BITMAP_SIZE);
8393 /* A plain memset can lose a concurrent remember, but only a shareable object can
8394 * be remembered from another Ractor's thread, and pinned_roots_mark re-marks
8395 * those every local cycle, and this clear precedes a major that re-scans all. */
8396 memset(&page->remembered_bits[0], 0, HEAP_PAGE_BITMAP_SIZE);
8397 memset(&page->pinned_bits[0], 0, HEAP_PAGE_BITMAP_SIZE);
8398 page->flags.has_uncollectible_wb_unprotected_objects = FALSE;
8399 page->flags.has_remembered_objects = FALSE;
8400 /* A shref is a local GC's root, so only a stop-the-world global GC may clear them:
8401 * its unified mark re-derives them from every shareable -> unshareable edge. */
8402 if (clear_shref) {
8403 memset(&page->shref_bits[0], 0, HEAP_PAGE_BITMAP_SIZE);
8404 page->flags.has_shref_objects = FALSE;
8405 }
8406 }
8407}
8408
8409/* RGENGC: APIs */
8410
8411NOINLINE(static void gc_writebarrier_generational(VALUE a, VALUE b, rb_objspace_t *objspace));
8412
8413/* Precondition: `a` and `b` live in `objspace`. */
8414static void
8415gc_writebarrier_generational(VALUE a, VALUE b, rb_objspace_t *objspace)
8416{
8417 if (RGENGC_CHECK_MODE) {
8418 if (!RVALUE_OLD_P(objspace, a)) rb_bug("gc_writebarrier_generational: %s is not an old object.", rb_obj_info(a));
8419 if ( RVALUE_OLD_P(objspace, b)) rb_bug("gc_writebarrier_generational: %s is an old object.", rb_obj_info(b));
8420 if (is_incremental_marking(objspace)) rb_bug("gc_writebarrier_generational: called while incremental marking: %s -> %s", rb_obj_info(a), rb_obj_info(b));
8421 }
8422
8423 /* Mark and remember a (the default behaviour).
8424 * No lock: setting a remembered bit is atomic (rgengc_remembersetbits_set), and that is
8425 * the only place a concurrent local GC or another Ractor's write barrier can race. */
8426 if (!RVALUE_REMEMBERED(objspace, a)) {
8427 rgengc_remember(objspace, a);
8428
8429 gc_report(1, objspace, "gc_writebarrier_generational: %s (remembered) -> %s\n", rb_obj_info(a), rb_obj_info(b));
8430 }
8431
8432 check_rvalue_consistency(objspace, a);
8433 check_rvalue_consistency(objspace, b);
8434}
8435
8436static void
8437gc_mark_from(rb_objspace_t *objspace, VALUE obj, VALUE parent)
8438{
8439 gc_mark_set_parent(objspace, parent);
8440 rgengc_check_relation(objspace, obj);
8441 if (gc_mark_set(objspace, obj) != FALSE) {
8442 gc_aging(objspace, obj);
8443 gc_grey(objspace, obj);
8444 }
8445 gc_mark_set_parent_invalid(objspace);
8446}
8447
8448NOINLINE(static void gc_writebarrier_incremental(VALUE a, VALUE b, rb_objspace_t *objspace));
8449
8450/* Precondition: `a` and `b` live in `objspace`. */
8451static void
8452gc_writebarrier_incremental(VALUE a, VALUE b, rb_objspace_t *objspace)
8453{
8454 gc_report(2, objspace, "gc_writebarrier_incremental: [LG] %p -> %s\n", (void *)a, rb_obj_info(b));
8455
8456 if (RVALUE_BLACK_P(objspace, a)) {
8457 if (RVALUE_WHITE_P(objspace, b)) {
8458 if (!RVALUE_WB_UNPROTECTED(objspace, a)) {
8459 gc_report(2, objspace, "gc_writebarrier_incremental: [IN] %p -> %s\n", (void *)a, rb_obj_info(b));
8460 gc_mark_from(objspace, b, a);
8461 }
8462 }
8463 else if (RVALUE_OLD_P(objspace, a) && !RVALUE_OLD_P(objspace, b)) {
8464 rgengc_remember(objspace, a);
8465 }
8466
8467 if (RB_UNLIKELY(objspace->flags.during_compacting)) {
8468 MARK_IN_BITMAP(GET_HEAP_PINNED_BITS(b), b);
8469 }
8470 }
8471}
8472
8473void
8474rb_gc_impl_writebarrier(void *objspace_ptr, VALUE a, VALUE b)
8475{
8476 rb_objspace_t *objspace = objspace_ptr;
8477
8478#if RGENGC_CHECK_MODE
8479 if (SPECIAL_CONST_P(a)) rb_bug("rb_gc_writebarrier: a is special const: %"PRIxVALUE, a);
8480 if (SPECIAL_CONST_P(b)) rb_bug("rb_gc_writebarrier: b is special const: %"PRIxVALUE, b);
8481#else
8484#endif
8485
8486 GC_ASSERT(!during_gc);
8487 GC_ASSERT(RB_BUILTIN_TYPE(a) != T_NONE);
8488 GC_ASSERT(RB_BUILTIN_TYPE(a) != T_MOVED);
8489 GC_ASSERT(RB_BUILTIN_TYPE(a) != T_ZOMBIE);
8490
8491 /* A shareable object now references an unshareable one: record b as a shref so its
8492 * owner's local GC roots it (the parent may live in another objspace, untraversed
8493 * there). Only b's owner stores this, on its own page: a plain store suffices. */
8494 if (RB_UNLIKELY(RB_FL_TEST_RAW(a, RUBY_FL_SHAREABLE)) &&
8496 struct heap_page *bpage = GET_HEAP_PAGE(b);
8497 if (!_MARKED_IN_BITMAP(bpage->shref_bits, bpage, b)) {
8498 _MARK_IN_BITMAP(bpage->shref_bits, bpage, b);
8499 bpage->flags.has_shref_objects = TRUE;
8500 }
8501 }
8502
8503 if (!is_incremental_marking(objspace)) {
8504 /* The generational barrier covers old->young edges within one objspace only.
8505 * NOTE: we shouldn't even check the age of `a` or `b` if they are in another
8506 * objspace, so check locality first. */
8507 if (gc_foreign_object_p(objspace, a) || gc_foreign_object_p(objspace, b) ||
8508 !RVALUE_OLD_P(objspace, a) || RVALUE_OLD_P(objspace, b)) {
8509 // do nothing
8510 }
8511 else {
8512 gc_writebarrier_generational(a, b, objspace);
8513 }
8514 }
8515 else {
8516 // Shareable objects from different object spaces are kept alive by shareable bits
8517 if (gc_foreign_object_p(objspace, a) || gc_foreign_object_p(objspace, b)) {
8518 // do nothing
8519 }
8520 else {
8521 gc_writebarrier_incremental(a, b, objspace);
8522 }
8523 }
8524}
8525
8526void
8527rb_gc_impl_obj_became_shareable(void *objspace_ptr, VALUE obj)
8528{
8529 /* An object becomes shareable on its owner thread, so this page update is
8530 * single-writer. */
8531 struct heap_page *page = GET_HEAP_PAGE(obj);
8532
8533 if (_MARKED_IN_BITMAP(page->shareable_bits, page, obj)) return;
8534 gc_page_add_shareable(page, obj);
8535
8536 /* The shref bits recorded while the object was unshareable are now covered by the
8537 * shareable pin, and a shref only points at an unshareable object. The owner thread is
8538 * the only writer, so a plain clear is enough. */
8539 if (_MARKED_IN_BITMAP(page->shref_bits, page, obj)) {
8540 _CLEAR_IN_BITMAP(page->shref_bits, page, obj);
8541 // NOTE: page->has_shref_objects could become stale here (value is true even though logically false)
8542 }
8543}
8544
8545void
8546rb_gc_impl_writebarrier_unprotect(void *objspace_ptr, VALUE obj)
8547{
8548 rb_objspace_t *objspace = objspace_ptr;
8549
8550 /* A shareable object is never WB-unprotected. Keeping shrefs correct relies on every
8551 * store into s->u going through the write barrier, which keeps wb_unprotected_bits
8552 * single-writer (only the owner thread can unprotect its own unshareable objects). */
8553 GC_ASSERT(!RB_FL_TEST_RAW(obj, RUBY_FL_SHAREABLE));
8554
8555 if (RVALUE_WB_UNPROTECTED(objspace, obj)) {
8556 return;
8557 }
8558 else {
8559 gc_report(2, objspace, "rb_gc_writebarrier_unprotect: %s %s\n", rb_obj_info(obj),
8560 RVALUE_REMEMBERED(objspace, obj) ? " (already remembered)" : "");
8561
8562 /* No lock: per the assert obj is our own unshareable, so these bits
8563 * (wb_unprotected, uncollectible, age) are single-writer on an owned page, and
8564 * RVALUE_DEMOTE's remembered-bit clear is atomic against word-sharing writers. */
8565 if (RVALUE_OLD_P(objspace, obj)) {
8566 gc_report(1, objspace, "rb_gc_writebarrier_unprotect: %s\n", rb_obj_info(obj));
8567 RVALUE_DEMOTE(objspace, obj);
8568 gc_mark_set(objspace, obj);
8569 gc_remember_unprotected(objspace, obj);
8570
8571#if RGENGC_PROFILE
8572 objspace->profile.total_shade_operation_count++;
8573#if RGENGC_PROFILE >= 2
8574 objspace->profile.shade_operation_count_types[BUILTIN_TYPE(obj)]++;
8575#endif /* RGENGC_PROFILE >= 2 */
8576#endif /* RGENGC_PROFILE */
8577 }
8578 else {
8579 RVALUE_AGE_RESET(obj);
8580 }
8581
8582 RB_DEBUG_COUNTER_INC(obj_wb_unprotect);
8583 MARK_IN_BITMAP(GET_HEAP_WB_UNPROTECTED_BITS(obj), obj);
8584 }
8585}
8586
8587void
8588rb_gc_impl_copy_attributes(void *objspace_ptr, VALUE dest, VALUE obj)
8589{
8590 rb_objspace_t *objspace = objspace_ptr;
8591
8592 if (RVALUE_WB_UNPROTECTED(objspace, obj)) {
8593 rb_gc_impl_writebarrier_unprotect(objspace, dest);
8594 }
8595 rb_gc_impl_copy_finalizer(objspace, dest, obj);
8596}
8597
8598const char *
8599rb_gc_impl_active_gc_name(void)
8600{
8601 return "default";
8602}
8603
8604/* NOTE: `obj` doesn't necessarily live in `objspace_ptr`, as `objspace_ptr` is just that
8605 * of the current Ractor. */
8606void
8607rb_gc_impl_writebarrier_remember(void *objspace_ptr, VALUE obj)
8608{
8609
8610 rb_objspace_t *objspace = objspace_ptr;
8611
8612 // Shareable objects from other object spaces don't need to be put on the remembered set
8613 // and are only collected during global GC, so not while incremental marking.
8614 if (RB_LIKELY(!gc_foreign_object_p(objspace, obj))) {
8615 gc_report(1, objspace, "rb_gc_writebarrier_remember: %s\n", rb_obj_info(obj));
8616 if (is_incremental_marking(objspace)) {
8617 if (RVALUE_BLACK_P(objspace, obj)) {
8618 gc_grey(objspace, obj);
8619 }
8620 }
8621 else if (RVALUE_OLD_P(objspace, obj)) {
8622 rgengc_remember(objspace, obj);
8623 }
8624 }
8625}
8626
8628 // Must be ID only
8629 ID ID_wb_protected, ID_age, ID_old, ID_uncollectible, ID_marking,
8630 ID_marked, ID_pinned, ID_remembered, ID_object_id, ID_shareable;
8631};
8632
8633#define RB_GC_OBJECT_METADATA_ENTRY_COUNT (sizeof(struct rb_gc_object_metadata_names) / sizeof(ID))
8634static struct rb_gc_object_metadata_entry object_metadata_entries[RB_GC_OBJECT_METADATA_ENTRY_COUNT + 1];
8635
8637rb_gc_impl_object_metadata(void *objspace_ptr, VALUE obj)
8638{
8639 rb_objspace_t *objspace = objspace_ptr;
8640 size_t n = 0;
8641 static struct rb_gc_object_metadata_names names;
8642
8643 if (!names.ID_marked) {
8644#define I(s) names.ID_##s = rb_intern(#s)
8645 I(wb_protected);
8646 I(age);
8647 I(old);
8648 I(uncollectible);
8649 I(marking);
8650 I(marked);
8651 I(pinned);
8652 I(remembered);
8653 I(object_id);
8654 I(shareable);
8655#undef I
8656 }
8657
8658#define SET_ENTRY(na, v) do { \
8659 GC_ASSERT(n <= RB_GC_OBJECT_METADATA_ENTRY_COUNT); \
8660 object_metadata_entries[n].name = names.ID_##na; \
8661 object_metadata_entries[n].val = v; \
8662 n++; \
8663} while (0)
8664
8665 if (!RVALUE_WB_UNPROTECTED(objspace, obj)) SET_ENTRY(wb_protected, Qtrue);
8666 SET_ENTRY(age, INT2FIX(RVALUE_AGE_GET(obj)));
8667 if (RVALUE_OLD_P(objspace, obj)) SET_ENTRY(old, Qtrue);
8668 if (RVALUE_UNCOLLECTIBLE(objspace, obj)) SET_ENTRY(uncollectible, Qtrue);
8669 if (RVALUE_MARKING(objspace, obj)) SET_ENTRY(marking, Qtrue);
8670 if (RVALUE_MARKED(objspace, obj)) SET_ENTRY(marked, Qtrue);
8671 if (RVALUE_PINNED(objspace, obj)) SET_ENTRY(pinned, Qtrue);
8672 if (RVALUE_REMEMBERED(objspace, obj)) SET_ENTRY(remembered, Qtrue);
8673 if (rb_obj_id_p(obj)) SET_ENTRY(object_id, rb_obj_id(obj));
8674 if (FL_TEST(obj, FL_SHAREABLE)) SET_ENTRY(shareable, Qtrue);
8675
8676 object_metadata_entries[n].name = 0;
8677 object_metadata_entries[n].val = 0;
8678#undef SET_ENTRY
8679
8680 return object_metadata_entries;
8681}
8682
8683void *
8684rb_gc_impl_ractor_cache_alloc(void *objspace_ptr, void *ractor)
8685{
8686 /* No cache needed: allocation happens in a per-Ractor objspace. */
8687 return NULL;
8688}
8689
8690void
8691rb_gc_impl_ractor_cache_free(void *objspace_ptr, void *cache)
8692{
8693 GC_ASSERT(cache == NULL);
8694}
8695
8696/* The terminating Ractor's final local GC, on its own thread: roots are minimal, so the
8697 * mark is tiny, and it reclaims what the joining side would otherwise inherit. Never
8698 * promotes to a global GC (that would STW on every Ractor death); empty pages go
8699 * straight back to the page pool. */
8700/* Finalize the zombies whose cleanup is pure C (a dfree, no Ruby-level finalizer);
8701 * the caller has no Ruby execution context any more, so zombies with a Ruby
8702 * finalizer stay deferred and travel to the inheritor as before. Returns whether
8703 * anything was finalized (those pages then need one more sweep to detach). */
8704static bool
8705finalize_deferred_dfree_only(rb_objspace_t *objspace)
8706{
8707 VALUE dfree_only = 0;
8708 VALUE zombie = RUBY_ATOMIC_VALUE_EXCHANGE(heap_pages_deferred_final, 0);
8709 while (zombie) {
8710 rb_asan_unpoison_object(zombie, false);
8711 VALUE next = RZOMBIE(zombie)->next;
8712 if (FL_TEST_RAW(zombie, FL_FINALIZE)) {
8713 /* re-defer, with the same push as rb_gc_impl_make_zombie */
8714 VALUE prev2, next2 = heap_pages_deferred_final;
8715 do {
8716 RZOMBIE(zombie)->next = prev2 = next2;
8717 next2 = RUBY_ATOMIC_VALUE_CAS(heap_pages_deferred_final, prev2, zombie);
8718 } while (next2 != prev2);
8719 rb_asan_poison_object(zombie);
8720 }
8721 else {
8722 RZOMBIE(zombie)->next = dfree_only;
8723 dfree_only = zombie;
8724 }
8725 zombie = next;
8726 }
8727 if (dfree_only) finalize_list(objspace, dfree_only);
8728 bool did = dfree_only != 0;
8729
8730 gc_tdata_unsafe_free_publish(objspace);
8731 return did;
8732}
8733
8734void
8735rb_gc_impl_objspace_retire_gc(void *objspace_ptr)
8736{
8737 rb_objspace_t *objspace = objspace_ptr;
8738
8739 /* The dying thread's stack is already torn down here, so the root scan must skip
8740 * its machine context (rb_gc_mark_roots). */
8741 objspace->flags.during_postmortem = 1;
8742 objspace->flags.ownerless = 1;
8743
8744 gc_rest(objspace);
8745 gc_start(objspace, GPR_FLAG_FULL_MARK | GPR_FLAG_IMMEDIATE_MARK | GPR_FLAG_IMMEDIATE_SWEEP);
8746
8747 /* The sweep above turned this heap's dead IO and the like into deferred zombies
8748 * (the per-Ractor stdio holds a page per Ractor otherwise); finalize the C-only
8749 * ones here and re-sweep the nearly-empty heap so their pages detach as empty. */
8750 if (finalize_deferred_dfree_only(objspace)) {
8751 gc_start(objspace, GPR_FLAG_FULL_MARK | GPR_FLAG_IMMEDIATE_MARK | GPR_FLAG_IMMEDIATE_SWEEP);
8752 }
8753
8754 heap_pages_freeable_pages = objspace->empty_pages_count;
8755 heap_pages_free_unused_pages(objspace);
8756
8757 objspace->flags.during_postmortem = 0;
8758}
8759
8760bool
8761rb_gc_impl_during_postmortem_p(void *objspace_ptr)
8762{
8763 rb_objspace_t *objspace = objspace_ptr;
8764 return objspace->flags.during_postmortem != 0;
8765}
8766
8767static void
8768heap_ready_to_gc(rb_objspace_t *objspace, rb_heap_t *heap)
8769{
8770 if (!heap->free_pages) {
8771 if (!heap_page_allocate_and_initialize(objspace, heap)) {
8772 objspace->heap_pages.allocatable_bytes = HEAP_PAGE_SIZE;
8773 heap_page_allocate_and_initialize(objspace, heap);
8774 }
8775 }
8776}
8777
8778static int
8779ready_to_gc(rb_objspace_t *objspace)
8780{
8781 if ((!objspace->flags.during_postmortem && rb_gc_gc_disabled_global_p()) || dont_gc_val() || during_gc) {
8782 for (int i = 0; i < HEAP_COUNT; i++) {
8783 rb_heap_t *heap = &heaps[i];
8784 heap_ready_to_gc(objspace, heap);
8785 }
8786 return FALSE;
8787 }
8788 else {
8789 return TRUE;
8790 }
8791}
8792
8793static void
8794gc_reset_malloc_info(rb_objspace_t *objspace, bool full_mark)
8795{
8796 gc_prof_set_malloc_info(objspace);
8797 {
8798 int64_t inc = gc_malloc_counters_increase(objspace, &objspace->malloc_counters.counters);
8799 gc_malloc_counters_snapshot(objspace, &objspace->malloc_counters.counters);
8800 size_t old_limit = malloc_limit;
8801
8802 /* A net-negative `inc` (more freed than malloc'd since last GC) is
8803 * treated the same as "allocated less than malloc_limit".
8804 * This matches what we were doing pre-monotonic counters, but is it right? */
8805 if (inc > 0 && (size_t)inc > malloc_limit) {
8806 malloc_limit = (size_t)((size_t)inc * gc_params.malloc_limit_growth_factor);
8807 if (malloc_limit > gc_params.malloc_limit_max) {
8808 malloc_limit = gc_params.malloc_limit_max;
8809 }
8810 }
8811 else {
8812 malloc_limit = (size_t)(malloc_limit * 0.98); /* magic number */
8813 if (malloc_limit < gc_params.malloc_limit_min) {
8814 malloc_limit = gc_params.malloc_limit_min;
8815 }
8816 }
8817
8818 if (0) {
8819 if (old_limit != malloc_limit) {
8820 fprintf(stderr, "[%"PRIuSIZE"] malloc_limit: %"PRIuSIZE" -> %"PRIuSIZE"\n",
8821 rb_gc_count(), old_limit, malloc_limit);
8822 }
8823 else {
8824 fprintf(stderr, "[%"PRIuSIZE"] malloc_limit: not changed (%"PRIuSIZE")\n",
8825 rb_gc_count(), malloc_limit);
8826 }
8827 }
8828 }
8829
8830 /* reset oldmalloc info */
8831#if RGENGC_ESTIMATE_OLDMALLOC
8832 MALLOC_COUNTERS_LOCK(objspace);
8833 gc_counter_store_release(&objspace->malloc_counters.freed_in_gc, 0);
8834 MALLOC_COUNTERS_UNLOCK(objspace);
8835 if (full_mark) {
8836 RUBY_ATOMIC_SIZE_EXCHANGE(objspace->malloc_counters.oldmalloc_increase, 0);
8837
8838 if ((objspace->profile.latest_gc_info & GPR_FLAG_MAJOR_BY_OLDMALLOC) == 0) {
8839 objspace->rgengc.oldmalloc_increase_limit =
8840 (size_t)(objspace->rgengc.oldmalloc_increase_limit / ((gc_params.oldmalloc_limit_growth_factor - 1)/10 + 1));
8841 if (objspace->rgengc.oldmalloc_increase_limit < gc_params.oldmalloc_limit_min) {
8842 objspace->rgengc.oldmalloc_increase_limit = gc_params.oldmalloc_limit_min;
8843 }
8844 }
8845 }
8846#endif
8847}
8848
8849/* What a collection records about itself before it runs. A global collection reports the
8850 * driver's objspace, so it comes through here too. */
8851static void
8852gc_start_record(rb_objspace_t *objspace, unsigned int reason, bool full_mark)
8853{
8854 objspace->profile.latest_gc_info = reason;
8855#if GC_PROFILE_MORE_DETAIL
8856 objspace->profile.total_allocated_objects_at_gc_start = total_allocated_objects(objspace);
8857 objspace->profile.heap_used_at_gc_start = rb_darray_size(objspace->heap_pages.sorted);
8858#endif
8859 objspace->profile.weak_references_count = 0;
8860 gc_prof_setup_new_record(objspace, reason);
8861 gc_reset_malloc_info(objspace, full_mark);
8862}
8863
8864static bool gc_start_global(rb_objspace_t *driver, unsigned int reason, bool compact, bool allow_skip);
8865
8866/* Decide whether this collection has to be global. A local GC can reclaim neither
8867 * shareable objects nor zombie objspaces, so once those grow past their limits only a
8868 * global GC makes progress. All inputs belong to this objspace. */
8869static bool
8870gc_need_global_p(rb_objspace_t *objspace)
8871{
8872 if (rb_gc_single_objspace_p()) return false;
8873 /* A Ractor's death must not stop the world, so the retire GC stays local. */
8874 if (objspace->flags.during_postmortem) return false;
8875 if (objspace->shareable_objects > objspace->shareable_objects_limit) return true;
8876 /* A zombie's garbage only a global cycle reclaims, but what survived the last one
8877 * is live data, so retrigger only once TRIGGER more pages accumulate on top of it.
8878 * Otherwise one live-heavy unjoined zombie turns every GC stop-the-world forever. */
8879 {
8880 size_t zp = global_objspace->zombie_total_pages;
8881 size_t base = global_objspace->zombie_pages_survivors < zp ? global_objspace->zombie_pages_survivors : zp;
8882 if (zp - base >= ZOMBIE_PAGES_TRIGGER) return true;
8883 }
8884 return false;
8885}
8886
8887static int
8888garbage_collect(rb_objspace_t *objspace, unsigned int reason)
8889{
8890 int ret;
8891
8892#if GC_PROFILE_MORE_DETAIL
8893 objspace->profile.prepare_time = getrusage_time();
8894#endif
8895
8896 gc_rest(objspace);
8897
8898#if GC_PROFILE_MORE_DETAIL
8899 objspace->profile.prepare_time = getrusage_time() - objspace->profile.prepare_time;
8900#endif
8901
8902 ret = gc_start(objspace, reason);
8903
8904 return ret;
8905}
8906
8907static int
8908gc_start(rb_objspace_t *objspace, unsigned int reason)
8909{
8910 unsigned int do_full_mark = !!(reason & GPR_FLAG_FULL_MARK);
8911
8912 if (!rb_darray_size(objspace->heap_pages.sorted)) return TRUE; /* heap is not ready */
8913 if (!(reason & GPR_FLAG_METHOD) && !ready_to_gc(objspace)) return TRUE; /* GC is not allowed */
8914
8915 /* An explicit GC.start(global: true) never gets here: rb_gc_impl_start has already decided from
8916 * the `global` keyword, and GPR_FLAG_METHOD keeps `global: false` from being promoted back. */
8917 if (!(reason & GPR_FLAG_METHOD) && gc_need_global_p(objspace)) {
8918 /* A global GC is always a major, so autocompact applies. */
8919 if (gc_start_global(objspace, reason, ruby_enable_autocompact, true)) {
8920 return TRUE;
8921 }
8922 /* Fall through to a local GC */
8923 }
8924
8925 rb_gc_initialize_vm_context(&objspace->vm_context);
8926
8927 GC_ASSERT(gc_mode(objspace) == gc_mode_none, "gc_mode is %s\n", gc_mode_name(gc_mode(objspace)));
8928 GC_ASSERT(!is_lazy_sweeping(objspace));
8929 GC_ASSERT(!is_incremental_marking(objspace));
8930
8931 /* reason may be clobbered, later, so keep set immediate_sweep here */
8932 objspace->flags.immediate_sweep = !!(reason & GPR_FLAG_IMMEDIATE_SWEEP);
8933
8934 if (ruby_gc_stressful) {
8935 int flag = FIXNUM_P(ruby_gc_stress_mode) ? FIX2INT(ruby_gc_stress_mode) : 0;
8936
8937 if ((flag & (1 << gc_stress_no_major)) == 0) {
8938 do_full_mark = TRUE;
8939 }
8940
8941 objspace->flags.immediate_sweep = !(flag & (1<<gc_stress_no_immediate_sweep));
8942 }
8943
8944 if (gc_needs_major_flags) {
8945 reason |= gc_needs_major_flags;
8946 do_full_mark = TRUE;
8947 }
8948
8949 /* if major gc has been disabled, never do a full mark */
8950 if (!gc_config_full_mark_val) {
8951 do_full_mark = FALSE;
8952 }
8953 gc_needs_major_flags = GPR_FLAG_NONE;
8954
8955 if (do_full_mark && (reason & GPR_FLAG_MAJOR_MASK) == 0) {
8956 reason |= GPR_FLAG_MAJOR_BY_FORCE; /* GC by CAPI, METHOD, and so on. */
8957 }
8958
8959 if (objspace->flags.dont_incremental ||
8960 reason & GPR_FLAG_IMMEDIATE_MARK ||
8961 ruby_gc_stressful) {
8962 gc_set_incremental_marking(objspace, FALSE);
8963 }
8964 else {
8965 gc_set_incremental_marking(objspace, do_full_mark);
8966 }
8967
8968 /* Compaction on the local GC path (autocompact) runs only with a single objspace:
8969 * without the stop-the-world barrier, moving objects would break cross-objspace
8970 * references. With multiple objspaces GC.compact and autocompact go through the
8971 * compacting global GC instead (rb_gc_impl_start, or the promotion above). */
8972 if (do_full_mark && ruby_enable_autocompact && rb_gc_single_objspace_p()) {
8973 objspace->flags.during_compacting = TRUE;
8974#if RGENGC_CHECK_MODE
8975 objspace->rcompactor.compare_func = ruby_autocompact_compare_func;
8976#endif
8977 }
8978 else {
8979 objspace->flags.during_compacting = !!(reason & GPR_FLAG_COMPACT);
8980 if (objspace->flags.during_compacting && !rb_gc_single_objspace_p()) {
8981 // compaction is currently global GC only with more than 1 running Ractor
8982 objspace->flags.during_compacting = FALSE;
8983 }
8984 }
8985
8986 if (!GC_ENABLE_LAZY_SWEEP || objspace->flags.dont_incremental) {
8987 objspace->flags.immediate_sweep = TRUE;
8988 }
8989
8990 if (objspace->flags.immediate_sweep) reason |= GPR_FLAG_IMMEDIATE_SWEEP;
8991
8992 /* Enter after during_compacting is decided */
8993 unsigned int lock_lev;
8994 gc_enter(objspace, gc_enter_event_start, &lock_lev);
8995
8996 gc_report(1, objspace, "gc_start(reason: %x) => %u, %d, %d\n",
8997 reason,
8998 do_full_mark, !is_incremental_marking(objspace), objspace->flags.immediate_sweep);
8999
9000 RB_DEBUG_COUNTER_INC(gc_count);
9001
9002 if (reason & GPR_FLAG_MAJOR_MASK) {
9003 (void)RB_DEBUG_COUNTER_INC_IF(gc_major_nofree, reason & GPR_FLAG_MAJOR_BY_NOFREE);
9004 (void)RB_DEBUG_COUNTER_INC_IF(gc_major_oldgen, reason & GPR_FLAG_MAJOR_BY_OLDGEN);
9005 (void)RB_DEBUG_COUNTER_INC_IF(gc_major_shady, reason & GPR_FLAG_MAJOR_BY_SHADY);
9006 (void)RB_DEBUG_COUNTER_INC_IF(gc_major_force, reason & GPR_FLAG_MAJOR_BY_FORCE);
9007#if RGENGC_ESTIMATE_OLDMALLOC
9008 (void)RB_DEBUG_COUNTER_INC_IF(gc_major_oldmalloc, reason & GPR_FLAG_MAJOR_BY_OLDMALLOC);
9009#endif
9010 }
9011 else {
9012 (void)RB_DEBUG_COUNTER_INC_IF(gc_minor_newobj, reason & GPR_FLAG_NEWOBJ);
9013 (void)RB_DEBUG_COUNTER_INC_IF(gc_minor_malloc, reason & GPR_FLAG_MALLOC);
9014 (void)RB_DEBUG_COUNTER_INC_IF(gc_minor_method, reason & GPR_FLAG_METHOD);
9015 (void)RB_DEBUG_COUNTER_INC_IF(gc_minor_capi, reason & GPR_FLAG_CAPI);
9016 (void)RB_DEBUG_COUNTER_INC_IF(gc_minor_stress, reason & GPR_FLAG_STRESS);
9017 }
9018
9019 objspace->profile.count++;
9020 gc_start_record(objspace, reason, do_full_mark);
9021
9022 gc_event_hook(objspace, RUBY_INTERNAL_EVENT_GC_START);
9023
9024 GC_ASSERT(during_gc);
9025
9026 gc_prof_timer_start(objspace);
9027 {
9028 if (gc_marks(objspace, do_full_mark)) {
9029 gc_sweep(objspace);
9030 }
9031 }
9032 gc_prof_timer_stop(objspace);
9033
9034 gc_exit(objspace, gc_enter_event_start, &lock_lev);
9035
9036 /* Verify after the GC, at a real safepoint with during_gc cleared: mid-GC
9037 * gc_verify_internal_consistency() takes the VM lock and a barrier, which would join
9038 * another Ractor's global GC barrier and let it collect on this half-collected heap. */
9039#if RGENGC_CHECK_MODE >= 2
9040 gc_verify_internal_consistency(objspace);
9041#endif
9042 return TRUE;
9043}
9044
9045static void
9046gc_rest(rb_objspace_t *objspace)
9047{
9048 if (is_incremental_marking(objspace) || is_lazy_sweeping(objspace)) {
9049 unsigned int lock_lev;
9050 gc_enter(objspace, gc_enter_event_rest, &lock_lev);
9051
9052 if (is_incremental_marking(objspace)) {
9053 gc_marking_enter(objspace);
9054 gc_marks_rest(objspace);
9055 gc_marking_exit(objspace);
9056
9057 gc_sweep(objspace);
9058 }
9059
9060 if (is_lazy_sweeping(objspace)) {
9061 gc_sweeping_enter(objspace);
9062 gc_sweep_rest(objspace);
9063 gc_sweeping_exit(objspace);
9064 }
9065
9066 gc_exit(objspace, gc_enter_event_rest, &lock_lev);
9067
9068 if (RGENGC_CHECK_MODE >= 2) gc_verify_internal_consistency(objspace); /* after GC, see gc_start */
9069 }
9070}
9071
9074 unsigned int reason;
9075};
9076
9077static void
9078gc_current_status_fill(rb_objspace_t *objspace, char *buff)
9079{
9080 int i = 0;
9081 if (is_marking(objspace)) {
9082 buff[i++] = 'M';
9083 if (is_full_marking(objspace)) buff[i++] = 'F';
9084 if (is_incremental_marking(objspace)) buff[i++] = 'I';
9085 }
9086 else if (is_sweeping(objspace)) {
9087 buff[i++] = 'S';
9088 if (is_lazy_sweeping(objspace)) buff[i++] = 'L';
9089 }
9090 else {
9091 buff[i++] = 'N';
9092 }
9093 buff[i] = '\0';
9094}
9095
9096static const char *
9097gc_current_status(rb_objspace_t *objspace)
9098{
9099 static char buff[0x10];
9100 gc_current_status_fill(objspace, buff);
9101 return buff;
9102}
9103
9104#if PRINT_ENTER_EXIT_TICK
9105
9106static tick_t last_exit_tick;
9107static tick_t enter_tick;
9108static int enter_count = 0;
9109static char last_gc_status[0x10];
9110
9111static inline void
9112gc_record(rb_objspace_t *objspace, int direction, const char *event)
9113{
9114 if (direction == 0) { /* enter */
9115 enter_count++;
9116 enter_tick = tick();
9117 gc_current_status_fill(objspace, last_gc_status);
9118 }
9119 else { /* exit */
9120 tick_t exit_tick = tick();
9121 char current_gc_status[0x10];
9122 gc_current_status_fill(objspace, current_gc_status);
9123#if 1
9124 /* [last mutator time] [gc time] [event] */
9125 fprintf(stderr, "%"PRItick"\t%"PRItick"\t%s\t[%s->%s|%c]\n",
9126 enter_tick - last_exit_tick,
9127 exit_tick - enter_tick,
9128 event,
9129 last_gc_status, current_gc_status,
9130 (objspace->profile.latest_gc_info & GPR_FLAG_MAJOR_MASK) ? '+' : '-');
9131 last_exit_tick = exit_tick;
9132#else
9133 /* [enter_tick] [gc time] [event] */
9134 fprintf(stderr, "%"PRItick"\t%"PRItick"\t%s\t[%s->%s|%c]\n",
9135 enter_tick,
9136 exit_tick - enter_tick,
9137 event,
9138 last_gc_status, current_gc_status,
9139 (objspace->profile.latest_gc_info & GPR_FLAG_MAJOR_MASK) ? '+' : '-');
9140#endif
9141 }
9142}
9143#else /* PRINT_ENTER_EXIT_TICK */
9144static inline void
9145gc_record(rb_objspace_t *objspace, int direction, const char *event)
9146{
9147 /* null */
9148}
9149#endif /* PRINT_ENTER_EXIT_TICK */
9150
9151static const char *
9152gc_enter_event_cstr(enum gc_enter_event event)
9153{
9154 switch (event) {
9155 case gc_enter_event_start: return "start";
9156 case gc_enter_event_continue: return "continue";
9157 case gc_enter_event_rest: return "rest";
9158 case gc_enter_event_finalizer: return "finalizer";
9159 case gc_enter_event_global: return "global";
9160 case gc_enter_event_global_auto: return "global_auto";
9161 }
9162 return NULL;
9163}
9164
9165static void
9166gc_enter_count(enum gc_enter_event event)
9167{
9168 switch (event) {
9169 case gc_enter_event_start: RB_DEBUG_COUNTER_INC(gc_enter_start); break;
9170 case gc_enter_event_continue: RB_DEBUG_COUNTER_INC(gc_enter_continue); break;
9171 case gc_enter_event_rest: RB_DEBUG_COUNTER_INC(gc_enter_rest); break;
9172 case gc_enter_event_finalizer: RB_DEBUG_COUNTER_INC(gc_enter_finalizer); break;
9173 case gc_enter_event_global: RB_DEBUG_COUNTER_INC(gc_enter_start); break;
9174 case gc_enter_event_global_auto: RB_DEBUG_COUNTER_INC(gc_enter_start); break;
9175 }
9176}
9177
9178static bool current_process_time(struct timespec *ts);
9179
9180/* A gc phase must be timed on the collecting thread's own cpu. A local gc runs
9181 * while the other ractors keep going, and process cpu time counts their work as
9182 * gc: with eight busy ractors the same ten collections were reported as 131ms
9183 * instead of 3ms, more than the wall clock they ran in. The kernel also answers
9184 * this one without walking every thread in the process. */
9185static bool
9186current_thread_time(struct timespec *ts)
9187{
9188#if defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_THREAD_CPUTIME_ID)
9189 {
9190 static int try_clock_gettime = 1;
9191 if (try_clock_gettime) {
9192 if (clock_gettime(CLOCK_THREAD_CPUTIME_ID, ts) == 0) {
9193 return true;
9194 }
9195 else {
9196 try_clock_gettime = 0;
9197 }
9198 }
9199 }
9200#endif
9201 return current_process_time(ts);
9202}
9203
9204static void
9205gc_clock_start(struct timespec *ts)
9206{
9207 if (!current_thread_time(ts)) {
9208 ts->tv_sec = 0;
9209 ts->tv_nsec = 0;
9210 }
9211}
9212
9213static unsigned long long
9214gc_clock_end(struct timespec *ts)
9215{
9216 struct timespec end_time;
9217
9218 if ((ts->tv_sec > 0 || ts->tv_nsec > 0) &&
9219 current_thread_time(&end_time) &&
9220 end_time.tv_sec >= ts->tv_sec) {
9221 return (unsigned long long)(end_time.tv_sec - ts->tv_sec) * (1000 * 1000 * 1000) +
9222 (end_time.tv_nsec - ts->tv_nsec);
9223 }
9224
9225 return 0;
9226}
9227
9228static void
9229gc_process_stat_after_fork_i(void *objspace_ptr, void *data)
9230{
9231 rb_objspace_t *objspace = objspace_ptr;
9232 rb_native_mutex_initialize(&objspace->process_stat.lock);
9233}
9234
9235static inline bool
9236gc_local_gc_holds_vm_lock(void)
9237{
9238 return rb_gc_single_objspace_p();
9239}
9240
9241static inline bool
9242gc_enter(rb_objspace_t *objspace, enum gc_enter_event event, unsigned int *lock_lev)
9243{
9244 /*
9245 * NOTE: The GC must never take the barrier VM lock from inside itself: the waiter could
9246 * join a pending barrier mid-collection and expose its half-collected heap to the global
9247 * GC. A no-barrier lock is safe. Other shared structures the GC paths touch use their own
9248 * native mutexes or the page-pool lock. */
9249 *lock_lev = 0;
9250
9251 RUBY_DTRACE_GC_HOOK(ENTER, event);
9252
9253 if (objspace->profile.run) {
9254 switch (event) {
9255 case gc_enter_event_start:
9256 case gc_enter_event_continue:
9257 case gc_enter_event_rest:
9258 case gc_enter_event_global:
9259 case gc_enter_event_global_auto:
9260 /* A global GC is the longest pause the process takes, so it is the last thing
9261 * the profiler may leave unmeasured. The switch below stops the world for it,
9262 * which is exactly the interval gc_stop_time is meant to name, so start the
9263 * clock here like a local collection does. */
9264 objspace->profile.gc_pause_start_time = rb_hrtime_now();
9265 break;
9266 case gc_enter_event_finalizer:
9267 break;
9268 }
9269 }
9270 switch (event) {
9271 case gc_enter_event_global:
9272 *lock_lev = RB_GC_VM_LOCK();
9273 // stop other ractors
9274 rb_gc_vm_barrier();
9275 break;
9276 case gc_enter_event_global_auto:
9277 *lock_lev = RB_GC_VM_LOCK();
9278 if (!gc_need_global_p(objspace)) {
9279 RB_GC_VM_UNLOCK(*lock_lev);
9280 *lock_lev = 0;
9281 objspace->profile.gc_pause_start_time = 0;
9282 return false;
9283 }
9284 rb_gc_vm_barrier();
9285 break;
9286 case gc_enter_event_finalizer:
9287 /* Shutdown finalizers read VM-global tables (fstring, symbol) and free T_DATA that
9288 * is not thread-safe, so take the no-barrier VM lock. */
9289 *lock_lev = RB_GC_VM_LOCK_NO_BARRIER();
9290 break;
9291 default:
9292 objspace->flags.gc_lock_barrier = FALSE;
9293 if (objspace->flags.during_compacting) {
9294 /* Compaction relocates objects and rewrites every Ractor's JIT and global
9295 * references, so it stops the world with a barrier VM lock. rb_gc_vm_barrier is
9296 * a reentrant no-op with a single Ractor, so an inner barrier request during the
9297 * move folds into this one and gc_exit ends it. */
9298 *lock_lev = RB_GC_VM_LOCK();
9299 rb_gc_vm_barrier();
9300 objspace->flags.gc_lock_barrier = TRUE;
9301 }
9302 else if (gc_local_gc_holds_vm_lock()) {
9303 *lock_lev = RB_GC_VM_LOCK_NO_BARRIER();
9304 }
9305 break;
9306 }
9307
9308 if (objspace->profile.gc_pause_start_time) {
9309 objspace->profile.gc_stw_start_time = rb_hrtime_now();
9310 objspace->profile.gc_stop_time = rb_hrtime_sub(
9311 objspace->profile.gc_stw_start_time,
9312 objspace->profile.gc_pause_start_time);
9313 }
9314
9315 gc_enter_count(event);
9316 if (RB_UNLIKELY(during_gc != 0)) rb_bug("during_gc != 0");
9317 if (RGENGC_CHECK_MODE >= 3) gc_verify_internal_consistency(objspace);
9318
9319 during_gc = TRUE;
9320 RUBY_DEBUG_LOG("%s (%s)",gc_enter_event_cstr(event), gc_current_status(objspace));
9321 gc_report(1, objspace, "gc_enter: %s [%s]\n", gc_enter_event_cstr(event), gc_current_status(objspace));
9322 gc_record(objspace, 0, gc_enter_event_cstr(event));
9323
9324 gc_event_hook(objspace, RUBY_INTERNAL_EVENT_GC_ENTER);
9325 return true;
9326}
9327
9328static inline void
9329gc_exit(rb_objspace_t *objspace, enum gc_enter_event event, unsigned int *lock_lev)
9330{
9331 GC_ASSERT(during_gc != 0);
9332
9333 RUBY_DTRACE_GC_HOOK(EXIT, event);
9334
9335 gc_event_hook(objspace, RUBY_INTERNAL_EVENT_GC_EXIT);
9336
9337 if (objspace->profile.gc_pause_start_time) {
9338 if (gc_prof_enabled(objspace)) {
9339 rb_hrtime_t now = rb_hrtime_now();
9340 gc_profile_record *record = gc_prof_record(objspace);
9341 record->gc_pause_time = rb_hrtime_add(record->gc_pause_time,
9342 rb_hrtime_sub(now, objspace->profile.gc_pause_start_time));
9343 record->gc_stop_time = rb_hrtime_add(record->gc_stop_time,
9344 objspace->profile.gc_stop_time);
9345 record->gc_stw_time = rb_hrtime_add(record->gc_stw_time,
9346 rb_hrtime_sub(now, objspace->profile.gc_stw_start_time));
9347 }
9348 objspace->profile.gc_pause_start_time = 0;
9349 objspace->profile.gc_stw_start_time = 0;
9350 objspace->profile.gc_stop_time = 0;
9351 }
9352
9353 gc_record(objspace, 1, gc_enter_event_cstr(event));
9354 RUBY_DEBUG_LOG("%s (%s)", gc_enter_event_cstr(event), gc_current_status(objspace));
9355 gc_report(1, objspace, "gc_exit: %s [%s]\n", gc_enter_event_cstr(event), gc_current_status(objspace));
9356 during_gc = FALSE;
9357 gc_process_stat_publish(objspace);
9358
9359 switch (event) {
9360 case gc_enter_event_global:
9361 case gc_enter_event_global_auto:
9362 RB_GC_VM_UNLOCK(*lock_lev);
9363 break;
9364 case gc_enter_event_finalizer:
9365 RB_GC_VM_UNLOCK_NO_BARRIER(*lock_lev);
9366 break;
9367 default:
9368 if (*lock_lev != 0) {
9369 if (objspace->flags.gc_lock_barrier) {
9370 objspace->flags.gc_lock_barrier = FALSE;
9371 RB_GC_VM_UNLOCK(*lock_lev);
9372 }
9373 else {
9374 RB_GC_VM_UNLOCK_NO_BARRIER(*lock_lev);
9375 }
9376 }
9377 break;
9378 }
9379}
9380
9381#ifndef MEASURE_GC
9382#define MEASURE_GC (objspace->flags.measure_gc)
9383#endif
9384
9385static void
9386gc_marking_enter(rb_objspace_t *objspace)
9387{
9388 GC_ASSERT(during_gc != 0);
9389
9390 gc_prof_mark_timer_start(objspace);
9391
9392 if (gc_prof_enabled(objspace)) {
9393 objspace->profile.gc_mark_phase_wall_start_time = rb_hrtime_now();
9394 }
9395
9396 if (MEASURE_GC) {
9397 gc_clock_start(&objspace->profile.marking_start_time);
9398 }
9399
9400 rb_gc_initialize_vm_context(&objspace->vm_context);
9401}
9402
9403static void
9404gc_marking_exit(rb_objspace_t *objspace)
9405{
9406 GC_ASSERT(during_gc != 0);
9407
9408 if (MEASURE_GC) {
9409 objspace->profile.marking_time_ns += gc_clock_end(&objspace->profile.marking_start_time);
9410 }
9411
9412 if (gc_prof_enabled(objspace)) {
9413 gc_profile_record *record = gc_prof_record(objspace);
9414 record->gc_mark_wall_time = rb_hrtime_add(record->gc_mark_wall_time,
9415 elapsed_hrtime_from(objspace->profile.gc_mark_phase_wall_start_time));
9416 }
9417
9418 gc_prof_mark_timer_stop(objspace);
9419}
9420
9421static void
9422gc_sweeping_cpu_enter(rb_objspace_t *objspace)
9423{
9424 if (MEASURE_GC) {
9425 gc_clock_start(&objspace->profile.sweeping_start_time);
9426 }
9427}
9428
9429static void
9430gc_sweeping_cpu_exit(rb_objspace_t *objspace)
9431{
9432 if (MEASURE_GC) {
9433 objspace->profile.sweeping_time_ns += gc_clock_end(&objspace->profile.sweeping_start_time);
9434 }
9435}
9436
9437static void
9438gc_sweeping_enter(rb_objspace_t *objspace)
9439{
9440 GC_ASSERT(during_gc != 0);
9441
9442 if (gc_prof_enabled(objspace)) {
9443 objspace->profile.gc_sweep_phase_wall_start_time = rb_hrtime_now();
9444 objspace->profile.gc_sweep_excluded_wall_time = 0;
9445 }
9446
9447 gc_sweeping_cpu_enter(objspace);
9448
9449 rb_gc_initialize_vm_context(&objspace->vm_context);
9450}
9451
9452static void
9453gc_sweeping_exit(rb_objspace_t *objspace)
9454{
9455 GC_ASSERT(during_gc != 0);
9456
9457 gc_sweeping_cpu_exit(objspace);
9458
9459 if (gc_prof_enabled(objspace)) {
9460 rb_hrtime_t sweep_wall_time = elapsed_hrtime_from(objspace->profile.gc_sweep_phase_wall_start_time);
9461 gc_profile_record *record = gc_prof_record(objspace);
9462 sweep_wall_time = rb_hrtime_sub(sweep_wall_time,
9463 objspace->profile.gc_sweep_excluded_wall_time);
9464 record->gc_sweep_wall_time = rb_hrtime_add(record->gc_sweep_wall_time,
9465 sweep_wall_time);
9466 objspace->profile.gc_sweep_excluded_wall_time = 0;
9467 }
9468}
9469
9470static void *
9471gc_with_gvl(void *ptr)
9472{
9473 struct objspace_and_reason *oar = (struct objspace_and_reason *)ptr;
9474 return (void *)(VALUE)garbage_collect(oar->objspace, oar->reason);
9475}
9476
9477int ruby_thread_has_gvl_p(void);
9478
9479static int
9480garbage_collect_with_gvl(rb_objspace_t *objspace, unsigned int reason)
9481{
9482 if (rb_gc_gc_disabled_global_p() || dont_gc_val()) {
9483 return TRUE;
9484 }
9485 else if (!ruby_native_thread_p()) {
9486 return TRUE;
9487 }
9488 else if (!ruby_thread_has_gvl_p()) {
9489 void *ret;
9490 struct objspace_and_reason oar;
9491 oar.objspace = objspace;
9492 oar.reason = reason;
9493 ret = rb_thread_call_with_gvl(gc_with_gvl, (void *)&oar);
9494
9495 return !!ret;
9496 }
9497 else {
9498 return garbage_collect(objspace, reason);
9499 }
9500}
9501
9502static int
9503gc_set_candidate_object_i(void *vstart, void *vend, size_t stride, void *data)
9504{
9506
9507 VALUE v = (VALUE)vstart;
9508 for (; v != (VALUE)vend; v += stride) {
9509 asan_unpoisoning_object(v) {
9510 switch (BUILTIN_TYPE(v)) {
9511 case T_NONE:
9512 case T_ZOMBIE:
9513 break;
9514 default:
9515 rb_gc_prepare_heap_process_object(v);
9516 if (!RVALUE_OLD_P(objspace, v) && !RVALUE_WB_UNPROTECTED(objspace, v)) {
9517 RVALUE_AGE_SET_CANDIDATE(objspace, v);
9518 }
9519 }
9520 }
9521 }
9522
9523 return 0;
9524}
9525
9526bool
9527rb_gc_impl_multi_objspace_p(void)
9528{
9529 return true;
9530}
9531
9532bool
9533rb_gc_impl_during_global_gc_p(void *objspace_ptr)
9534{
9535 rb_objspace_t *objspace = objspace_ptr;
9536 return objspace->flags.during_global_gc != 0;
9537}
9538
9539bool
9540rb_gc_impl_obj_foreign_p(void *objspace_ptr, VALUE obj)
9541{
9542 return gc_foreign_object_p(objspace_ptr, obj);
9543}
9544
9545
9546/* Whether obj is recorded as an unshareable object referenced from a shareable one. For
9547 * the verifier: a shareable -> unshareable edge is only accepted if the write barrier
9548 * recorded it here. */
9549bool
9550rb_gc_impl_shref_marked_p(void *objspace_ptr, VALUE obj)
9551{
9552 return MARKED_IN_BITMAP(GET_HEAP_SHREF_BITS(obj), obj) != 0;
9553}
9554
9555/* What a zombie objspace is worth to the zombie page trigger, floored: the retire GC
9556 * can empty an ownerless objspace outright, yet its struct, mark stack and heap_page
9557 * structs stay in malloc and it keeps the world multi-objspace until a global GC
9558 * merges it, so a page-less zombie must still push the trigger. Never 0, so a
9559 * nonzero zombie_pages also marks the objspace as a zombie. */
9560static size_t
9561objspace_zombie_pages(rb_objspace_t *objspace)
9562{
9563 size_t pages = rb_darray_size(objspace->heap_pages.sorted);
9564 return pages > HEAP_COUNT ? pages : HEAP_COUNT;
9565}
9566
9567/* gc.c parked the objspace in its zombie table, under the VM lock. */
9568void
9569rb_gc_impl_objspace_zombify(void *objspace_ptr)
9570{
9571 rb_objspace_t *objspace = objspace_ptr;
9572 GC_ASSERT(objspace->zombie_pages == 0);
9573 objspace->zombie_pages = objspace_zombie_pages(objspace);
9574 global_objspace->zombie_total_pages += objspace->zombie_pages;
9575}
9576
9577/* Re-measure every zombie this cycle covered, by difference, so a zombie parked after
9578 * the snapshot keeps the pages it was parked with. Inside the barrier. */
9579static void
9580gc_global_refresh_zombie_pages(void)
9581{
9582 for (size_t i = 0; i < global_objspace->global_gc.n_objspaces; i++) {
9583 rb_objspace_t *objspace = global_objspace->global_gc.objspaces[i];
9584 if (objspace->zombie_pages == 0) continue;
9585 size_t pages = objspace_zombie_pages(objspace);
9586 global_objspace->zombie_total_pages -= objspace->zombie_pages;
9587 global_objspace->zombie_total_pages += pages;
9588 objspace->zombie_pages = pages;
9589 }
9590 global_objspace->zombie_pages_survivors = global_objspace->zombie_total_pages;
9591}
9592
9593static void
9594gc_global_objspaces_i(void *os, void *data)
9595{
9596 if (global_objspace->global_gc.n_objspaces == global_objspace->global_gc.objspaces_capa) {
9597 size_t new_capa = global_objspace->global_gc.objspaces_capa ? global_objspace->global_gc.objspaces_capa * 2 : 16;
9598 struct rb_objspace **new_list = realloc(global_objspace->global_gc.objspaces, new_capa * sizeof(*new_list));
9599 if (new_list == NULL) rb_bug("gc_global_objspaces_i: realloc failed");
9600 global_objspace->global_gc.objspaces = new_list;
9601 global_objspace->global_gc.objspaces_capa = new_capa;
9602 }
9603 global_objspace->global_gc.objspaces[global_objspace->global_gc.n_objspaces++] = os;
9604}
9605
9606/* Re-snapshot every objspace this cycle covers, zombies included. The objspaces/capa
9607 * buffer is reused from the previous cycle. */
9608static void
9609gc_global_snapshot_objspaces(void)
9610{
9611 global_objspace->global_gc.n_objspaces = 0;
9612 rb_gc_vm_each_objspace(gc_global_objspaces_i, NULL);
9613
9614#if RGENGC_CHECK_MODE
9615 /* Check that the incrementally maintained page_index agrees with the per-objspace
9616 * sorted arrays. */
9617 size_t total = 0, zombie_total = 0;
9618 for (size_t i = 0; i < global_objspace->global_gc.n_objspaces; i++) {
9619 total += rb_darray_size(global_objspace->global_gc.objspaces[i]->heap_pages.sorted);
9620 zombie_total += global_objspace->global_gc.objspaces[i]->zombie_pages;
9621 }
9622 GC_ASSERT(total == global_objspace->page_index.n_pages);
9623 /* Every zombie is enumerated, so the snapshot sees all of zombie_total_pages. */
9624 GC_ASSERT(zombie_total == global_objspace->zombie_total_pages);
9625#endif
9626}
9627
9628/* Global GC: stop every Ractor and clear/mark/sweep all objspaces as one heap. It is the
9629 * only collector that can free shareable objects and decide cross-objspace reachability
9630 * precisely. */
9631/* The global GC's generic_fields weak pass, after the unified mark fixpoint, before the
9632 * sweep. Per-object rb_mark_generic_ivar is a no-op during a global GC (the driver has
9633 * GET_RACTOR() != owner); the whole table is swept here instead. Weak-KEY: mark the val
9634 * (fields_obj, a strong child) only for a live key, drain dead keys' entries. Marking a
9635 * val can make another key live, so repeat to a fixpoint. */
9638 bool progress;
9639};
9640
9641static int
9642genfields_mark_i(VALUE key, VALUE val, void *arg)
9643{
9644 struct genfields_mark_arg *a = (struct genfields_mark_arg *)arg;
9645 if (RB_SPECIAL_CONST_P(val) || !RVALUE_MARKED_BITMAP(key)) {
9646 return ST_CONTINUE;
9647 }
9648 /* Record the old(key)->young(val) edge with the host (key) as parent, even when val
9649 * is already marked: a conservative machine-stack scan can mark a fresh fields_obj
9650 * parentless before this pass, and branching on the mark bit would leave the key
9651 * unremembered, so the next minor GC misses the young val ("WB miss (O->Y)").
9652 * gc_mark runs rgengc_check_relation before its already-marked return: call always. */
9653 bool newly = !RVALUE_MARKED_BITMAP(val);
9654 gc_mark_set_parent(a->objspace, key);
9655 gc_mark(a->objspace, val);
9656 if (newly) a->progress = true;
9657 return ST_CONTINUE;
9658}
9659
9660static bool
9661genfields_dead_p(VALUE key)
9662{
9663 return RVALUE_MARKED_BITMAP(key) == 0;
9664}
9665
9666static void
9667gc_global_mark_generic_fields(rb_objspace_t *driver)
9668{
9669 struct genfields_mark_arg arg = { driver, false };
9670 do {
9671 arg.progress = false;
9672 /* Each entry's mark sets parent=key (genfields_mark_i) so the generational WB is
9673 * recorded correctly. gc_mark_stacked_objects_all sets its own per-object parent,
9674 * so restore the invalid parent (the poison contract) before calling it. */
9675 rb_gc_vm_generic_fields_mark_foreach(genfields_mark_i, &arg);
9676 gc_mark_set_parent_invalid(driver);
9677 if (arg.progress) {
9678 gc_mark_stacked_objects_all(driver);
9679 }
9680 } while (arg.progress);
9681
9682 rb_gc_vm_generic_fields_drain_dead(genfields_dead_p);
9683}
9684
9685/* Two Ractors choosing a global GC at once are serialized by the VM lock in gc_enter. If two
9686 * globals start concurrently, only one global will run and the other will run a local GC after
9687 * the barrier ends. */
9688static bool
9689gc_start_global(rb_objspace_t *driver, unsigned int reason, bool compact, bool allow_skip)
9690{
9691 unsigned int lock_lev;
9692 enum gc_enter_event event = allow_skip ? gc_enter_event_global_auto : gc_enter_event_global;
9693 if (!gc_enter(driver, event, &lock_lev)) {
9694 return false;
9695 }
9696
9697 reason |= GPR_FLAG_GLOBAL;
9698
9699 /* A global GC is a collection of the driver's objspace too, so report it like a local
9700 * one: it records a profile entry and reports what triggered it. */
9701 gc_start_record(driver, reason, true);
9702 gc_event_hook(driver, RUBY_INTERNAL_EVENT_GC_START);
9703 gc_prof_timer_start(driver);
9704
9705 gc_global_snapshot_objspaces();
9706
9707 /* Mark every objspace as in a global GC before step 3 settles the lazy sweeps: the
9708 * settle frees other objspaces' garbage on the driver thread, and
9709 * rb_free_generic_ivar must see "global GC in progress" to defer generic_fields
9710 * removal to the weak-pass drain. */
9711 for (size_t i = 0; i < global_objspace->global_gc.n_objspaces; i++) {
9712 global_objspace->global_gc.objspaces[i]->flags.during_global_gc = TRUE;
9713 }
9714
9715 /* A global GC collects every objspace, so each needs the malloc-counter reset the
9716 * driver got in gc_start_record; without it, gc_sweep_finish advancing free_at_last_gc
9717 * (step 9) would leave their malloc_increase overstated by everything swept here. */
9718 for (size_t i = 0; i < global_objspace->global_gc.n_objspaces; i++) {
9719 rb_objspace_t *const os = global_objspace->global_gc.objspaces[i];
9720 if (os != driver) {
9721 os->profile.latest_gc_info = reason;
9722 gc_reset_malloc_info(os, true);
9723 }
9724 }
9725
9726 /* step 3: settle every lazy sweep so the mark bits' meaning is fixed before the clear
9727 * below. (during_gc is a macro over the local "objspace".) rb_gc_get_ec() resolves
9728 * through objspace->vm_context during a GC, so initialize it for all: the driver
9729 * thread runs every objspace's phases. */
9730 for (size_t i = 0; i < global_objspace->global_gc.n_objspaces; i++) {
9731 rb_objspace_t *objspace = global_objspace->global_gc.objspaces[i];
9732 /* The barrier can stop a Ractor between the steps of its own incremental mark, and
9733 * nothing else finishes another objspace's mark. Drop the partial mark rather
9734 * than clear its flags in step 5 under a live gray stack: the owner would resume
9735 * with a mark stack into a heap this GC has since re-marked and swept. Nothing is
9736 * lost, the unified mark below redoes the work. */
9737 if (is_incremental_marking(objspace)) {
9738 gc_abort_incremental_marking(objspace);
9739 }
9740 GC_ASSERT(!is_incremental_marking(objspace));
9741 GC_ASSERT(is_mark_stack_empty(&objspace->mark_stack));
9742 rb_gc_initialize_vm_context(&objspace->vm_context);
9743 if (objspace != driver) during_gc = TRUE;
9744 gc_sweep_rest(objspace);
9745 }
9746
9747 /* step 5: clear every objspace's mark bits, remembered sets, generation counters and
9748 * shrefs (missing even one leaves a stale mark bit and a UAF). (heaps is a macro over
9749 * the local "objspace".) */
9750 for (size_t i = 0; i < global_objspace->global_gc.n_objspaces; i++) {
9751 rb_objspace_t *objspace = global_objspace->global_gc.objspaces[i];
9752 objspace->flags.during_minor_gc = FALSE;
9753 gc_set_incremental_marking(objspace, FALSE);
9754 /* The unified mark is precise and does not pin, so the per-objspace sweep below must
9755 * not re-check against a stale local cycle. */
9756 objspace->last_cycle_pinned = 0;
9757 objspace->rgengc.uncollectible_wb_unprotected_objects = 0;
9758 objspace->rgengc.old_objects = 0;
9759 objspace->profile.count++;
9760 objspace->profile.global_gc_count++;
9761 objspace->rgengc.last_major_gc = objspace->profile.count;
9762 objspace->rgengc.need_major_gc = GPR_FLAG_NONE;
9763 objspace->marked_slots = 0;
9764 for (int h = 0; h < HEAP_COUNT; h++) {
9765 rb_heap_t *heap = &heaps[h];
9766 gc_bitmaps_clear(objspace, heap, true);
9767 heap_move_pooled_pages_to_free_pages(heap);
9768 }
9769 }
9770 driver->profile.global_gc_invocation_count++;
9771 global_objspace->global_gc.count++;
9772
9773 /* Enable compaction in every objspace before the mark: the unified conservative root
9774 * scan then pins machine-stack referents (gc_pin only pins while during_compacting)
9775 * and step 9's sweep relocates the rest. global_gc.compacting defers the
9776 * reference-update phase to phase 2 below (two phases, safe across objspaces). */
9777 global_objspace->global_gc.compacting = compact;
9778 if (compact) {
9779 for (size_t i = 0; i < global_objspace->global_gc.n_objspaces; i++) {
9780 rb_objspace_t *objspace = global_objspace->global_gc.objspaces[i];
9781 objspace->flags.during_compacting = TRUE;
9782#if RGENGC_CHECK_MODE
9783 if (ruby_enable_autocompact) {
9784 objspace->rcompactor.compare_func = ruby_autocompact_compare_func;
9785 }
9786#endif
9787 /* A global GC skips gc_marks_start, which is what resets pinned_slots for a
9788 * compacting local GC, so reset it here. step 5 cleared pinned_bits; the
9789 * conservative mark re-pins machine-stack referents. */
9790 for (int h = 0; h < HEAP_COUNT; h++) {
9791 struct heap_page *page = NULL;
9792 ccan_list_for_each(&heaps[h].pages, page, page_node) {
9793 page->pinned_slots = 0;
9794 }
9795 }
9796 }
9797 }
9798
9799 /* steps 6-7: every Ractor's roots (gc.c walks them all), then one unified precise
9800 * mark. A global GC does not go through gc_marks, so the marking
9801 * phase is opened here instead; it closes after rb_ractor_finish_marking below, which is
9802 * where gc_marks_finish ends for a local collection. */
9803 gc_marking_enter(driver);
9804
9805 mark_roots(driver, NULL);
9806 gc_mark_stacked_objects_all(driver);
9807
9808 /* Run the generic_fields weak pass after the mark fixpoint: mark the vals (fields_obj)
9809 * of live keys and drain the entries of dead ones. The per-object rb_mark_generic_ivar
9810 * is a no-op during a global GC, so this is the only path that marks generic_fields. */
9811 gc_global_mark_generic_fields(driver);
9812
9813 gc_event_hook(driver, RUBY_INTERNAL_EVENT_GC_END_MARK);
9814
9815 /* step 8 */
9816 gc_update_weak_references(driver);
9817
9818 /* This cycle's root pass over every Ractor has swept the deleted ractor-local keys out of
9819 * each storage. Free the key structs while still inside the barrier (a local GC never
9820 * can; see rb_ractor_finish_marking). */
9821 rb_ractor_finish_marking(true);
9822
9823 gc_marking_exit(driver);
9824
9825 /* step 9: sweep every objspace inside the barrier, not lazily. Dead shareable objects
9826 * are reclaimed here and emptied pages go back to the pool. */
9827 if (!compact) {
9828 for (size_t i = 0; i < global_objspace->global_gc.n_objspaces; i++) {
9829 rb_objspace_t *os = global_objspace->global_gc.objspaces[i];
9830 unsigned int prev_immediate = os->flags.immediate_sweep;
9831 os->flags.immediate_sweep = TRUE;
9832 gc_sweep(os);
9833 os->flags.immediate_sweep = prev_immediate;
9834 }
9835 }
9836 else {
9837 /* The move -> update-references -> free flow runs as three passes across ALL
9838 * objspaces, not per objspace: (a) updating references must see every objspace's
9839 * forwarding (a reference can point at a moved foreign object), and (b) freeing
9840 * source pages must wait until everyone is updated (or another objspace's update
9841 * reads a freed T_MOVED). The read barrier is installed once for all passes. */
9842 install_handlers();
9843
9844 /* Only the driver records a profile entry for a global GC (gc_start_record), so time
9845 * only the driver's compaction work. The move/update/free below runs inside the
9846 * driver's sweep phase (gc_sweeping_enter/exit); attribute it to GC_COMPACT_WALL_TIME
9847 * and exclude it from the driver's sweep wall time so the two do not double-count,
9848 * mirroring the compacting branch of the local gc_sweep(). */
9849 const bool driver_prof = gc_prof_enabled(driver);
9850 rb_hrtime_t driver_compact_wall_time = 0;
9851
9852 /* pass 1 (move): relocate every objspace and leave T_MOVED forwarding behind. */
9853 for (size_t i = 0; i < global_objspace->global_gc.n_objspaces; i++) {
9854 rb_objspace_t *os = global_objspace->global_gc.objspaces[i];
9855 gc_sweeping_enter(os);
9856 gc_sweep_start(os); /* mode -> sweeping, order the heap for compaction */
9857 rb_hrtime_t t0 = (os == driver && driver_prof) ? rb_hrtime_now() : 0;
9858 gc_compact_relocate(os); /* mode -> compacting, move */
9859 if (os == driver && driver_prof) {
9860 driver_compact_wall_time = rb_hrtime_add(driver_compact_wall_time, elapsed_hrtime_from(t0));
9861 }
9862 gc_sweeping_cpu_exit(os);
9863 }
9864
9865 /* pass 2 (update): all forwarding now exists, so update every objspace's
9866 * references (cross-objspace ones resolve too); gc_compact_finish also unprotects
9867 * pages and clears during_compacting. The move-or-mark decision reads
9868 * rb_gc_get_objspace()'s during_reference_updating: set it on every objspace. */
9869 gc_sweeping_cpu_enter(driver);
9870 for (size_t i = 0; i < global_objspace->global_gc.n_objspaces; i++) {
9871 global_objspace->global_gc.objspaces[i]->flags.during_reference_updating = TRUE;
9872 }
9873
9874 for (size_t i = 0; i < global_objspace->global_gc.n_objspaces; i++) {
9875 rb_objspace_t *objspace = global_objspace->global_gc.objspaces[i];
9876 for (int h = 0; h < HEAP_COUNT; h++) {
9877 gc_unprotect_pages(objspace, &heaps[h]);
9878 }
9879 }
9880 rb_gc_before_updating_jit_code();
9881 gc_sweeping_cpu_exit(driver);
9882 for (size_t i = 0; i < global_objspace->global_gc.n_objspaces; i++) {
9883 rb_objspace_t *os = global_objspace->global_gc.objspaces[i];
9884 gc_sweeping_cpu_enter(os);
9885 rb_hrtime_t t0 = (os == driver && driver_prof) ? rb_hrtime_now() : 0;
9886 gc_compact_finish(os);
9887 if (os == driver && driver_prof) {
9888 driver_compact_wall_time = rb_hrtime_add(driver_compact_wall_time, elapsed_hrtime_from(t0));
9889 }
9890 gc_sweeping_cpu_exit(os);
9891 }
9892 /* The VM-global / weak-table side of the reference update runs once (each objspace's
9893 * heap side already ran in gc_compact_finish above). */
9894 {
9895 gc_sweeping_cpu_enter(driver);
9896 rb_hrtime_t t0 = driver_prof ? rb_hrtime_now() : 0;
9897 gc_update_references_global(driver);
9898 if (driver_prof) {
9899 driver_compact_wall_time = rb_hrtime_add(driver_compact_wall_time, elapsed_hrtime_from(t0));
9900 }
9901 gc_sweeping_cpu_exit(driver);
9902 }
9903 gc_sweeping_cpu_enter(driver);
9904 rb_gc_after_updating_jit_code();
9905 for (size_t i = 0; i < global_objspace->global_gc.n_objspaces; i++) {
9906 global_objspace->global_gc.objspaces[i]->flags.during_reference_updating = FALSE;
9907 global_objspace->global_gc.objspaces[i]->flags.during_compacting = FALSE;
9908 }
9909 global_objspace->global_gc.compacting = false;
9910 uninstall_handlers();
9911 gc_sweeping_cpu_exit(driver);
9912
9913 /* Record the driver's compaction time and exclude it from the driver's sweep phase.
9914 * gc_sweeping_exit(driver) in pass 3 subtracts gc_sweep_excluded_wall_time from the
9915 * sweep wall time, so this must be set before it runs. The excluded value is a sum
9916 * of sub-intervals of the driver's sweep phase, so the subtraction cannot underflow. */
9917 if (driver_prof) {
9918 gc_profile_record *const record = gc_prof_record(driver);
9919 record->gc_compact_wall_time = rb_hrtime_add(record->gc_compact_wall_time,
9920 driver_compact_wall_time);
9921 driver->profile.gc_sweep_excluded_wall_time = rb_hrtime_add(
9922 driver->profile.gc_sweep_excluded_wall_time, driver_compact_wall_time);
9923 }
9924
9925 /* pass 3 (free): page-sweep every objspace, freeing dead objects and the source pages
9926 * that are now empty. during_compacting is already cleared, so the sweep treats
9927 * T_MOVED as usual. */
9928 for (size_t i = 0; i < global_objspace->global_gc.n_objspaces; i++) {
9929 rb_objspace_t *os = global_objspace->global_gc.objspaces[i];
9930 gc_sweeping_cpu_enter(os);
9931 gc_sweep_rest(os);
9932 gc_sweeping_exit(os);
9933 }
9934 }
9935 global_objspace->global_gc.compacting = false;
9936
9937 /* A global GC never calls gc_marks_finish, which budgets heap growth
9938 * (allocatable_bytes). An objspace still full after the global sweep (materializing
9939 * a large received copy, say) has no free pages, no empty pages, budget 0, and its next
9940 * allocation would hit newobj_refill's "cannot create a new page after a major GC".
9941 * Give every objspace stuck like that the growth budget gc_marks_finish would. */
9942 for (size_t i = 0; i < global_objspace->global_gc.n_objspaces; i++) {
9943 rb_objspace_t *objspace = global_objspace->global_gc.objspaces[i];
9944 if (objspace->heap_pages.allocatable_bytes != 0 || objspace->empty_pages_count != 0) {
9945 continue;
9946 }
9947 bool stuck = false;
9948 for (int h = 0; h < HEAP_COUNT; h++) {
9949 if (heaps[h].free_pages == NULL) { stuck = true; break; }
9950 }
9951 if (stuck) {
9952 heap_allocatable_bytes_expand(objspace, NULL, 0,
9953 objspace_available_slots(objspace), heaps[0].slot_size);
9954 }
9955 }
9956
9957 /* Recount the surviving shareable objects (the sweep already folded the dead ones out of
9958 * shareable_bits) and reset each trigger limit. */
9959 for (size_t i = 0; i < global_objspace->global_gc.n_objspaces; i++) {
9960 rb_objspace_t *objspace = global_objspace->global_gc.objspaces[i];
9961 size_t survivors = 0;
9962 for (int h = 0; h < HEAP_COUNT; h++) {
9963 struct heap_page *page = NULL;
9964 ccan_list_for_each(&heaps[h].pages, page, page_node) {
9965 if (!page->flags.has_shareable_objects) continue;
9966 for (int j = 0; j < HEAP_PAGE_BITMAP_LIMIT; j++) {
9967 survivors += rb_popcount_intptr(page->shareable_bits[j]);
9968 }
9969 }
9970 }
9971 objspace->shareable_objects = survivors;
9972 size_t new_limit = (size_t)(survivors * SHAREABLE_OBJECTS_LIMIT_FACTOR);
9973 if (new_limit < SHAREABLE_OBJECTS_LIMIT_MIN) new_limit = SHAREABLE_OBJECTS_LIMIT_MIN;
9974 objspace->shareable_objects_limit = new_limit;
9975 }
9976
9977 /* Deferred non-thread-safe frees: the world is already stopped here, so reap them
9978 * without a second barrier. Uses the driver's snapshot rather than taking its own,
9979 * which step 10 below still walks. */
9980 gc_tdata_unsafe_drain_objspaces(global_objspace->global_gc.objspaces,
9981 global_objspace->global_gc.n_objspaces);
9982
9983 /* step 10 */
9984 for (size_t i = 0; i < global_objspace->global_gc.n_objspaces; i++) {
9985 rb_objspace_t *objspace = global_objspace->global_gc.objspaces[i];
9986 objspace->flags.during_global_gc = FALSE;
9987 if (objspace != driver) {
9988 during_gc = FALSE;
9989 gc_process_stat_publish(objspace);
9990 }
9991 }
9992
9993 /* The unified mark re-established the reachability of absorbed shareable objects, so a
9994 * single objspace's local mark is trustworthy again (pinning can be skipped until the
9995 * next absorb). */
9996 rb_gc_reset_absorbed_since_global_gc();
9997
9998 /* Re-measure the zombies now that the garbage is gone. Without this, the page
9999 * trigger above keeps firing on the stale numbers left when a joinable (slotted)
10000 * zombie retires without any pass merging it. */
10001 gc_global_refresh_zombie_pages();
10002
10003 /* If the sweep above collected an unjoined Ractor object, ractor_free disowned its
10004 * zombie_objspaces entry and posted the merge to main as a postponed job; the objspace
10005 * stays enumerable until main absorbs it at its next safepoint. */
10006
10007 gc_prof_timer_stop(driver);
10008 gc_exit(driver, event, &lock_lev);
10009 return true;
10010}
10011
10012static int
10013absorb_finalizer_i(st_data_t key, st_data_t val, st_data_t data)
10014{
10016 st_insert(finalizer_table, key, val);
10017 return ST_CONTINUE;
10018}
10019
10020static void
10021gc_make_mid_mark_objspace_absorbable(rb_objspace_t *src)
10022{
10023 rb_objspace_t *objspace = src;
10024 for (int h = 0; h < HEAP_COUNT; h++) {
10025 struct heap_page *page = NULL;
10026 ccan_list_for_each(&heaps[h].pages, page, page_node) {
10027 short stride = page->slot_size;
10028 uintptr_t p = (uintptr_t)page->start;
10029 uintptr_t pend = p + page->total_slots * stride;
10030
10031 for (; p < pend; p += stride) {
10032 VALUE vp = (VALUE)p;
10033 asan_unpoisoning_object(vp) {
10034 switch (RB_BUILTIN_TYPE(vp)) {
10035 case T_NONE:
10036 case T_ZOMBIE:
10037 break;
10038 default:
10039 RVALUE_AGE_RESET(vp);
10040 break;
10041 }
10042 }
10043 }
10044 }
10045 gc_bitmaps_clear(objspace, &heaps[h], false);
10046 }
10047 objspace->rgengc.old_objects = 0;
10048 objspace->rgengc.uncollectible_wb_unprotected_objects = 0;
10049 objspace->marked_slots = 0;
10050}
10051
10052/* Merge a dead Ractor's objspace into dst under the VM lock. src has no owner thread and
10053 * dst is the calling thread's own objspace (join/value) or main with everyone stopped
10054 * (global GC), so single-writer holds throughout. Pages move whole (their bits describe
10055 * objects, not the objspace), and dst's next collection is forced full to rebuild the
10056 * generational state. */
10057static void
10058objspace_absorb(rb_objspace_t *dst, rb_objspace_t *src)
10059{
10060 GC_ASSERT(dst != src);
10061
10062 /* Suppress the cross-objspace verifier checks while the graph is in flux (see
10063 * global_objspace->during_absorb). */
10064 const bool prev_absorb = global_objspace->during_absorb;
10065 global_objspace->during_absorb = true;
10066
10067 /* gc.c dropped src from its zombie table in this same VM-lock section, so src went
10068 * through zombify and its pages are part of the total. */
10069 GC_ASSERT(src->zombie_pages != 0);
10070 GC_ASSERT(global_objspace->zombie_total_pages >= src->zombie_pages);
10071 global_objspace->zombie_total_pages -= src->zombie_pages;
10072 src->zombie_pages = 0;
10073
10074 /* Settle dst first: adding pages under a walking lazy-sweep cursor, or into a
10075 * half-marked incremental heap, would sweep the merged pages with src's stale mark
10076 * bits and free live objects. */
10077 gc_rest(dst);
10078
10079 /* Settle src: no incremental marking, lazy sweep or in-progress allocation page. */
10080 {
10081 rb_objspace_t *objspace = src;
10082 /* A zombie parked by fork (rb_ractor_terminate_atfork retires the objspace
10083 * without the retire GC) can be mid-incremental-mark, and that mark cannot be
10084 * finished. Its owner's threads did not survive the fork, so mark_roots would
10085 * scan the absorbing Ractor's roots instead of src's. Drop the cycle. */
10086 if (is_incremental_marking(objspace)) {
10087 gc_abort_incremental_marking(objspace);
10088 gc_make_mid_mark_objspace_absorbable(objspace);
10089 }
10090 /* rb_ractor_terminate_atfork retires without the retire GC, so src may arrive
10091 * with the flag unset; the sweep gc_rest may finish is the last one it gets. */
10092 objspace->flags.ownerless = 1;
10093 gc_rest(src); // if mid-sweep
10094 heap_alloc_state_clear(objspace);
10095 /* gc_sweep_finish leaves swept pages "pooled" for a coming incremental mark; src
10096 * never runs one (it is about to be merged), so return them to its free list now,
10097 * restoring the pooled_pages == NULL the page merge below assumes (mirrors
10098 * gc_start_global step 3). */
10099 for (int h = 0; h < HEAP_COUNT; h++) {
10100 heap_move_pooled_pages_to_free_pages(&heaps[h]);
10101 }
10102
10103 /* Backstop for pages a sweep that ran before `ownerless` was set left attached */
10104 for (int h = 0; h < HEAP_COUNT; h++) {
10105 rb_heap_t *heap = &heaps[h];
10106 struct heap_page **link = &heap->free_pages;
10107 while (*link) {
10108 struct heap_page *page = *link;
10109 if (page->free_slots == page->total_slots) {
10110 *link = page->free_next;
10111 }
10112 else {
10113 link = &page->free_next;
10114 }
10115 }
10116
10117 struct heap_page *page, *next;
10118 ccan_list_for_each_safe(&heap->pages, page, next, page_node) {
10119 if (page->free_slots == page->total_slots) {
10120 GC_ASSERT(page->final_slots == 0);
10121 heap_page_detach_empty(objspace, heap, page);
10122 }
10123 }
10124 }
10125 }
10126
10127 /* From here the merge must not run dst's GC: the finalizer st_insert below can cross
10128 * the malloc-accounting threshold, and a GC then would sweep src's detached finalizer
10129 * procs, reachable only from this C frame, into dangling VALUEs. Page/darray moves
10130 * allocate nothing (_without_gc), so disabling costs nothing and makes the splice
10131 * atomic. (The two settles above deliberately collect: they stay outside.) */
10132 const bool dst_gc_was_enabled = rb_gc_impl_gc_enabled_p(dst);
10133 if (dst_gc_was_enabled) rb_gc_impl_gc_disable(dst, false);
10134
10135 /* Hand over the pages size pool by size pool. ("heaps" is a macro over the local
10136 * objspace, so the arrays are taken through scoped locals.) */
10137 rb_heap_t *dst_heaps;
10138 rb_heap_t *src_heaps;
10139 {
10140 rb_objspace_t *objspace = dst;
10141 dst_heaps = heaps;
10142 }
10143 {
10144 rb_objspace_t *objspace = src;
10145 src_heaps = heaps;
10146 }
10147 for (int h = 0; h < HEAP_COUNT; h++) {
10148 rb_heap_t *dheap = &dst_heaps[h];
10149 rb_heap_t *sheap = &src_heaps[h];
10150 struct heap_page *page = NULL;
10151
10152 GC_ASSERT(sheap->sweeping_page == NULL);
10153 GC_ASSERT(sheap->pooled_pages == NULL);
10154
10155 ccan_list_for_each(&sheap->pages, page, page_node) {
10156 page->objspace = dst;
10157 page->heap = dheap;
10158 }
10159 ccan_list_append_list(&dheap->pages, &sheap->pages);
10160
10161 /* Append the free-page chain to the tail. */
10162 if (sheap->free_pages) {
10163 struct heap_page **tail = &dheap->free_pages;
10164 while (*tail) tail = &(*tail)->free_next;
10165 *tail = sheap->free_pages;
10166 sheap->free_pages = NULL;
10167 }
10168
10169 dheap->total_pages += sheap->total_pages;
10170 dheap->total_slots += sheap->total_slots;
10171 dheap->total_allocated_pages += sheap->total_allocated_pages;
10172 dheap->total_allocated_objects += sheap->total_allocated_objects;
10173 dheap->total_freed_objects += sheap->total_freed_objects;
10174 dheap->final_slots_count += sheap->final_slots_count;
10175 }
10176
10177 /* The objspace-wide page bookkeeping. */
10178 {
10179 rb_objspace_t *objspace = dst; /* for the heap_pages_* macros */
10180 struct heap_page *page = NULL;
10181 size_t srcn = rb_darray_size(src->heap_pages.sorted);
10182 for (size_t i = 0; i < srcn; i++) {
10183 page = rb_darray_get(src->heap_pages.sorted, i);
10184 /* Residents of the empty pool (no live objects) are returned to page_pool rather
10185 * than inherited; dst's allocation demand is cheaply met from the shared pool's
10186 * free list. */
10187 if (heap_page_in_global_empty_pages_pool(src, page)) {
10188 heap_page_free(src, page);
10189 continue;
10190 }
10191 uintptr_t body = (uintptr_t)page->body;
10192 uintptr_t start = body + sizeof(struct heap_page_header);
10193 uintptr_t end = body + HEAP_PAGE_SIZE;
10194
10195 /* Keep the array ordered by page BODY address: heap_page_for_ptr bsearches
10196 * body ranges, and a detached empty page has start == 0, so ordering by
10197 * page->start would miss live pages (a global GC would then fail to mark a
10198 * registered root and sweep it). */
10199 size_t lo = 0;
10200 size_t hi = rb_darray_size(objspace->heap_pages.sorted);
10201 while (lo < hi) {
10202 size_t mid = (lo + hi) / 2;
10203 struct heap_page *mid_page = rb_darray_get(objspace->heap_pages.sorted, mid);
10204 if ((uintptr_t)mid_page->body < body) lo = mid + 1;
10205 else hi = mid;
10206 }
10207 rb_darray_insert_without_gc(&objspace->heap_pages.sorted, hi, page);
10208
10209 if (heap_pages_lomem == 0 || heap_pages_lomem > start) heap_pages_lomem = start;
10210 if (heap_pages_himem < end) heap_pages_himem = end;
10211 }
10212 objspace->heap_pages.allocated_pages += src->heap_pages.allocated_pages;
10213 objspace->heap_pages.freed_pages += src->heap_pages.freed_pages;
10214 rb_darray_free_without_gc(src->heap_pages.sorted);
10215 src->heap_pages.sorted = NULL;
10216 /* The empty_pages chain's structs were freed in the loop above. */
10217 src->empty_pages = NULL;
10218 src->empty_pages_count = 0;
10219 }
10220
10221 /* Finalizers: move the table's entries, and the dead Ractor's deferred zombies are run
10222 * by dst's thread from now on. */
10223 {
10224 st_table *src_finalizers;
10225 {
10226 rb_objspace_t *objspace = src;
10227 src_finalizers = finalizer_table;
10228 finalizer_table = NULL;
10229 }
10230 if (src_finalizers) {
10231 rb_objspace_t *objspace = dst;
10232 if (finalizer_table == NULL) {
10233 finalizer_table = src_finalizers;
10234 }
10235 else {
10236 st_foreach(src_finalizers, absorb_finalizer_i, (st_data_t)dst);
10237 st_free_table(src_finalizers);
10238 }
10239 }
10240 }
10241 {
10242 VALUE src_deferred = RUBY_ATOMIC_VALUE_EXCHANGE(src->heap_pages.deferred_final, 0);
10243 if (src_deferred) {
10244 VALUE tail_obj = src_deferred;
10245 rb_asan_unpoison_object(tail_obj, false);
10246 while (RZOMBIE(tail_obj)->next) {
10247 VALUE next_obj = RZOMBIE(tail_obj)->next;
10248 rb_asan_poison_object(tail_obj);
10249 tail_obj = next_obj;
10250 rb_asan_unpoison_object(tail_obj, false);
10251 }
10252 VALUE prev;
10253 do {
10254 prev = dst->heap_pages.deferred_final;
10255 RZOMBIE(tail_obj)->next = prev;
10256 } while (RUBY_ATOMIC_VALUE_CAS(dst->heap_pages.deferred_final, prev, src_deferred) != prev);
10257 rb_asan_poison_object(tail_obj);
10258 /* No owner was left to run these zombies (register's owner walk misses a dead
10259 * Ractor). dst runs this merge, so schedule dst's job here; otherwise they wait
10260 * until dst's next GC. */
10261 rb_postponed_job_trigger(dst->finalize_deferred_pjob);
10262 }
10263 }
10264 if (src->tdata_unsafe_free_chunk) {
10265 gc_tdata_unsafe_free_publish(src);
10266 }
10267 if (tdata_deferred_free_count_load() >= TDATA_DEFERRED_FREE_THRESHOLD) {
10268 gc_tdata_deferred_free_trigger(dst);
10269 }
10270
10271 /* Counters inherited by dst. */
10272 dst->rgengc.old_objects += src->rgengc.old_objects;
10273 dst->rgengc.uncollectible_wb_unprotected_objects += src->rgengc.uncollectible_wb_unprotected_objects;
10274 dst->shareable_objects += src->shareable_objects;
10275
10276 /* Merged pages carry src's mark/age state, so dst rebuilds its view at the next
10277 * collection. Note that this can be worked around by calling `GC.config(rgengc_allow_full_mark: false)`,
10278 * so the absorbed heap should be in a state where a minor GC would also work correctly.
10279 */
10280 dst->rgengc.need_major_gc |= GPR_FLAG_MAJOR_BY_FORCE;
10281
10282 /* src's outstanding malloc pressure moves with the xmalloc'd buffers. Later frees are
10283 * charged to dst, so without this transfer dst underestimates its own heap and delays
10284 * GCs. dst is live, so take its counter lock where gc_counter_add is not atomic. */
10285 {
10286 int64_t inc = gc_malloc_counters_increase(src, &src->malloc_counters.counters);
10287#if RGENGC_ESTIMATE_OLDMALLOC
10288 size_t oldmalloc_increase = gc_oldmalloc_increase_load(src);
10289#endif
10290 MALLOC_COUNTERS_LOCK(dst);
10291 if (inc > 0) gc_counter_add(&dst->malloc_counters.counters.malloc, (size_t)inc);
10292#if RGENGC_ESTIMATE_OLDMALLOC
10293 if (oldmalloc_increase > 0) RUBY_ATOMIC_SIZE_ADD(dst->malloc_counters.oldmalloc_increase, oldmalloc_increase);
10294#endif
10295 MALLOC_COUNTERS_UNLOCK(dst);
10296 }
10297
10298 {
10299 struct gc_process_stat_snapshot final_snap;
10300 gc_process_stat_capture(src, &final_snap);
10301 gc_process_stat_add(&global_objspace->process_stat_archive, &final_snap);
10302 }
10303 rb_native_mutex_destroy(&src->process_stat.lock);
10304
10305 /* Free the shell (as rb_gc_impl_objspace_free does). */
10306 free(src->profile.records);
10307 free_stack_chunks(&src->mark_stack);
10308 mark_stack_free_cache(&src->mark_stack);
10309 GC_ASSERT(rb_darray_size(src->weak_references) == 0);
10310 rb_darray_free_without_gc(src->weak_references);
10311#ifdef MALLOC_COUNTERS_NEED_LOCK
10312 rb_native_mutex_destroy(&src->malloc_counters.lock);
10313#endif
10314 free(src);
10315
10316 if (dst_gc_was_enabled) rb_gc_impl_gc_enable(dst);
10317
10318 /* Return the empty pages inheritance piled up in dst (mostly from the dead Ractor's
10319 * teardown material) to the pool with no budget. An empty page is by definition safe to
10320 * release, and re-acquiring one from the pool is cheap. */
10321 {
10322 rb_objspace_t *objspace = dst;
10323 heap_pages_freeable_pages = objspace->empty_pages_count;
10324 heap_pages_free_unused_pages(objspace);
10325 }
10326
10327 global_objspace->during_absorb = prev_absorb;
10328}
10329
10330void
10331rb_gc_impl_objspace_absorb(void *dst_ptr, void *src_ptr)
10332{
10333 objspace_absorb(dst_ptr, src_ptr);
10334}
10335
10336void
10337rb_gc_impl_start(void *objspace_ptr, bool full_mark, bool immediate_mark, bool immediate_sweep, bool compact, bool global)
10338{
10339 rb_objspace_t *objspace = objspace_ptr;
10340 unsigned int reason = (GPR_FLAG_FULL_MARK |
10341 GPR_FLAG_IMMEDIATE_MARK |
10342 GPR_FLAG_IMMEDIATE_SWEEP |
10343 GPR_FLAG_METHOD);
10344
10345 int full_marking_p = gc_config_full_mark_val;
10346 gc_config_full_mark_set(TRUE);
10347
10348 /* For now, compact implies full mark / sweep, so ignore other flags */
10349 if (compact) {
10350 GC_ASSERT(GC_COMPACTION_SUPPORTED);
10351
10352 reason |= GPR_FLAG_COMPACT;
10353 if (!rb_gc_single_objspace_p()) {
10354 global = true;
10355 }
10356 }
10357 else {
10358 if (!full_mark) reason &= ~GPR_FLAG_FULL_MARK;
10359 if (!immediate_mark) reason &= ~GPR_FLAG_IMMEDIATE_MARK;
10360 if (!immediate_sweep) reason &= ~GPR_FLAG_IMMEDIATE_SWEEP;
10361 }
10362
10363 if ((reason & (GPR_FLAG_FULL_MARK | GPR_FLAG_IMMEDIATE_MARK | GPR_FLAG_IMMEDIATE_SWEEP)) !=
10364 (GPR_FLAG_FULL_MARK | GPR_FLAG_IMMEDIATE_MARK | GPR_FLAG_IMMEDIATE_SWEEP)) {
10365 global = false;
10366 }
10367
10368 if (global && !rb_gc_single_objspace_p()) {
10369 /* A mid-cycle driver is settled by gc_start_global itself: it aborts the partial
10370 * mark and finishes the lazy sweep, so the dead slots are T_NONE before the
10371 * unified conservative root scan. */
10372 gc_start_global(objspace, reason, compact || ruby_enable_autocompact, false);
10373 }
10374 else {
10375 garbage_collect(objspace, reason);
10376 }
10377
10378 gc_finalize_deferred(objspace);
10379 /* An explicit GC.start is expected to reclaim immediately, so run the deferred non-thread-safe
10380 * frees synchronously instead of leaving them to gc_sweep_finish's postponed job. */
10381 if (tdata_deferred_free_count_load() > 0 && rb_gc_single_objspace_p()) {
10382 gc_tdata_unsafe_drain();
10383 }
10384 gc_config_full_mark_set(full_marking_p);
10385}
10386
10387void
10388rb_gc_impl_prepare_heap(void *objspace_ptr)
10389{
10390 rb_objspace_t *objspace = objspace_ptr;
10391
10392 rb_gc_impl_each_objects(objspace, gc_set_candidate_object_i, objspace_ptr);
10393
10394 double orig_max_free_slots = gc_params.heap_free_slots_max_ratio;
10395 /* Ensure that all empty pages are moved onto empty_pages. */
10396 gc_params.heap_free_slots_max_ratio = 0.0;
10397 rb_gc_impl_start(objspace, true, true, true, true, true);
10398 gc_params.heap_free_slots_max_ratio = orig_max_free_slots;
10399
10400 objspace->heap_pages.allocatable_bytes = 0;
10401 heap_pages_freeable_pages = objspace->empty_pages_count;
10402 heap_pages_free_unused_pages(objspace_ptr);
10403 GC_ASSERT(heap_pages_freeable_pages == 0);
10404 GC_ASSERT(objspace->empty_pages_count == 0);
10405
10406 // Process.warmup is meant to be called at the end of the boot sequence, which is commonly allocation
10407 // heavy and result in GC limits raising significantly, but it's not indicative of the limits needed
10408 // for runtime.
10409 // Recompute the allocatable_bytes limit based on `gc_params.heap_init_bytes`.
10410 GC_ASSERT(objspace->heap_pages.allocatable_bytes == 0);
10411 for (int i = 0; i < HEAP_COUNT; i++) {
10412 rb_heap_t *heap = &heaps[i];
10413 heap_allocatable_bytes_expand(objspace, heap, heap->empty_slots, heap->total_slots, heap->slot_size);
10414 }
10415
10416#if defined(HAVE_MALLOC_TRIM) && !defined(RUBY_ALTERNATIVE_MALLOC_HEADER)
10417 malloc_trim(0);
10418#endif
10419}
10420
10421static int
10422gc_is_moveable_obj(rb_objspace_t *objspace, VALUE obj)
10423{
10424 GC_ASSERT(!SPECIAL_CONST_P(obj));
10425
10426 switch (BUILTIN_TYPE(obj)) {
10427 case T_NONE:
10428 case T_MOVED:
10429 case T_ZOMBIE:
10430 return FALSE;
10431 case T_SYMBOL:
10432 case T_STRING:
10433 case T_OBJECT:
10434 case T_FLOAT:
10435 case T_IMEMO:
10436 case T_ARRAY:
10437 case T_BIGNUM:
10438 case T_ICLASS:
10439 case T_MODULE:
10440 case T_REGEXP:
10441 case T_DATA:
10442 case T_MATCH:
10443 case T_STRUCT:
10444 case T_HASH:
10445 case T_FILE:
10446 case T_COMPLEX:
10447 case T_RATIONAL:
10448 case T_NODE:
10449 case T_CLASS:
10450 if (FL_TEST_RAW(obj, FL_FINALIZE)) {
10451 /* The finalizer table is a numtable. It looks up objects by address.
10452 * We can't mark the keys in the finalizer table because that would
10453 * prevent the objects from being collected. This check prevents
10454 * objects that are keys in the finalizer table from being moved
10455 * without directly pinning them. */
10456 GC_ASSERT(st_is_member(finalizer_table, obj));
10457
10458 return FALSE;
10459 }
10460 GC_ASSERT(RVALUE_MARKED(objspace, obj));
10461 GC_ASSERT(!RVALUE_PINNED(objspace, obj));
10462
10463 return TRUE;
10464
10465 default:
10466 rb_bug("gc_is_moveable_obj: unreachable (%d)", (int)BUILTIN_TYPE(obj));
10467 break;
10468 }
10469
10470 return FALSE;
10471}
10472
10473void rb_mv_generic_ivar(VALUE src, VALUE dst);
10474
10475static VALUE
10476gc_move(rb_objspace_t *objspace, VALUE src, VALUE dest, struct heap_page *src_page, struct heap_page *dest_page)
10477{
10478 size_t src_slot_size = src_page->slot_size;
10479 size_t slot_size = dest_page->slot_size;
10480
10481 int marked;
10482 int wb_unprotected;
10483 int uncollectible;
10484 int age;
10485
10486 gc_report(4, objspace, "Moving object: %p -> %p\n", (void *)src, (void *)dest);
10487
10488 GC_ASSERT(BUILTIN_TYPE(src) != T_NONE);
10489 GC_ASSERT(!MARKED_IN_BITMAP(GET_HEAP_MARK_BITS(dest), dest));
10490
10491 GC_ASSERT(!RVALUE_MARKING(objspace, src));
10492
10493 /* Save off bits for current object. */
10494 marked = RVALUE_MARKED(objspace, src);
10495 wb_unprotected = RVALUE_WB_UNPROTECTED(objspace, src);
10496 uncollectible = RVALUE_UNCOLLECTIBLE(objspace, src);
10497 bool remembered = RVALUE_REMEMBERED(objspace, src);
10498 /* Pin bits travel with the object. Losing one during single-objspace compaction would
10499 * silently unpin it once the process goes multi-objspace, letting a local GC free a method
10500 * entry or shref target that another Ractor references. */
10501 bool shareable = MARKED_IN_BITMAP(GET_HEAP_SHAREABLE_BITS(src), src) != 0;
10502 bool shref = MARKED_IN_BITMAP(GET_HEAP_SHREF_BITS(src), src) != 0;
10503 age = RVALUE_AGE_GET(src);
10504
10505 /* Clear bits for eventual T_MOVED */
10506 CLEAR_IN_BITMAP(GET_HEAP_MARK_BITS(src), src);
10507 CLEAR_IN_BITMAP(GET_HEAP_WB_UNPROTECTED_BITS(src), src);
10508 CLEAR_IN_BITMAP(GET_HEAP_UNCOLLECTIBLE_BITS(src), src);
10509 CLEAR_IN_BITMAP(GET_HEAP_PAGE(src)->remembered_bits, src);
10510 CLEAR_IN_BITMAP(GET_HEAP_SHAREABLE_BITS(src), src);
10511 CLEAR_IN_BITMAP(GET_HEAP_SHREF_BITS(src), src);
10512
10513 /* Move the object */
10514 memcpy((void *)dest, (void *)src, MIN(src_slot_size, slot_size));
10515
10516 if (src_slot_size != slot_size) {
10517 rb_gc_obj_changed_slot_size(dest, slot_size - RVALUE_OVERHEAD);
10518 }
10519
10520 if (RVALUE_OVERHEAD > 0) {
10521 void *dest_overhead = (void *)(((uintptr_t)dest) + slot_size - RVALUE_OVERHEAD);
10522 void *src_overhead = (void *)(((uintptr_t)src) + src_slot_size - RVALUE_OVERHEAD);
10523
10524 memcpy(dest_overhead, src_overhead, RVALUE_OVERHEAD);
10525 }
10526
10527 memset((void *)src, 0, src_slot_size);
10528 RVALUE_AGE_SET_BITMAP(src, 0);
10529
10530 /* Set bits for object in new location */
10531 if (remembered) {
10532 MARK_IN_BITMAP(GET_HEAP_PAGE(dest)->remembered_bits, dest);
10533 }
10534 else {
10535 CLEAR_IN_BITMAP(GET_HEAP_PAGE(dest)->remembered_bits, dest);
10536 }
10537
10538 if (marked) {
10539 MARK_IN_BITMAP(GET_HEAP_MARK_BITS(dest), dest);
10540 }
10541 else {
10542 CLEAR_IN_BITMAP(GET_HEAP_MARK_BITS(dest), dest);
10543 }
10544
10545 if (wb_unprotected) {
10546 MARK_IN_BITMAP(GET_HEAP_WB_UNPROTECTED_BITS(dest), dest);
10547 }
10548 else {
10549 CLEAR_IN_BITMAP(GET_HEAP_WB_UNPROTECTED_BITS(dest), dest);
10550 }
10551
10552 if (uncollectible) {
10553 MARK_IN_BITMAP(GET_HEAP_UNCOLLECTIBLE_BITS(dest), dest);
10554 }
10555 else {
10556 CLEAR_IN_BITMAP(GET_HEAP_UNCOLLECTIBLE_BITS(dest), dest);
10557 }
10558
10559 if (shareable) {
10560 MARK_IN_BITMAP(GET_HEAP_SHAREABLE_BITS(dest), dest);
10561 GET_HEAP_PAGE(dest)->flags.has_shareable_objects = TRUE;
10562 }
10563 else {
10564 CLEAR_IN_BITMAP(GET_HEAP_SHAREABLE_BITS(dest), dest);
10565 }
10566
10567 if (shref) {
10568 MARK_IN_BITMAP(GET_HEAP_SHREF_BITS(dest), dest);
10569 GET_HEAP_PAGE(dest)->flags.has_shref_objects = TRUE;
10570 }
10571 else {
10572 CLEAR_IN_BITMAP(GET_HEAP_SHREF_BITS(dest), dest);
10573 }
10574
10575 RVALUE_AGE_SET(dest, age);
10576
10577 /* A re-embedded object (rb_gc_obj_changed_slot_size) references its
10578 * former fields_obj's contents directly; the write-barrier history
10579 * lived on the discarded fields_obj, so remember the object. */
10580 if (src_slot_size != slot_size && age >= RVALUE_OLD_AGE && !remembered) {
10581 rgengc_remember(objspace, dest);
10582 }
10583
10584 /* Assign forwarding address */
10585 RMOVED(src)->flags = T_MOVED;
10586 RMOVED(src)->dummy = Qundef;
10587 RMOVED(src)->destination = dest;
10588 GC_ASSERT(BUILTIN_TYPE(dest) != T_NONE);
10589
10590 GET_HEAP_PAGE(src)->heap->total_freed_objects++;
10591 GET_HEAP_PAGE(dest)->heap->total_allocated_objects++;
10592
10593 return src;
10594}
10595
10596#if GC_CAN_COMPILE_COMPACTION
10597static int
10598compare_pinned_slots(const void *left, const void *right, void *dummy)
10599{
10600 struct heap_page *left_page;
10601 struct heap_page *right_page;
10602
10603 left_page = *(struct heap_page * const *)left;
10604 right_page = *(struct heap_page * const *)right;
10605
10606 return left_page->pinned_slots - right_page->pinned_slots;
10607}
10608
10609static int
10610compare_free_slots(const void *left, const void *right, void *dummy)
10611{
10612 struct heap_page *left_page;
10613 struct heap_page *right_page;
10614
10615 left_page = *(struct heap_page * const *)left;
10616 right_page = *(struct heap_page * const *)right;
10617
10618 return left_page->free_slots - right_page->free_slots;
10619}
10620
10621static void
10622gc_sort_heap_by_compare_func(rb_objspace_t *objspace, gc_compact_compare_func compare_func)
10623{
10624 for (int j = 0; j < HEAP_COUNT; j++) {
10625 rb_heap_t *heap = &heaps[j];
10626
10627 size_t total_pages = heap->total_pages;
10628 size_t size = rb_size_mul_or_raise(total_pages, sizeof(struct heap_page *), rb_eRuntimeError);
10629 struct heap_page *page = 0, **page_list = malloc(size);
10630 size_t i = 0;
10631
10632 heap->free_pages = NULL;
10633 ccan_list_for_each(&heap->pages, page, page_node) {
10634 page_list[i++] = page;
10635 GC_ASSERT(page);
10636 }
10637
10638 GC_ASSERT((size_t)i == total_pages);
10639
10640 /* Sort the heap so "filled pages" are first. `heap_add_page` adds to the
10641 * head of the list, so empty pages will end up at the start of the heap */
10642 ruby_qsort(page_list, total_pages, sizeof(struct heap_page *), compare_func, NULL);
10643
10644 /* Reset the eden heap */
10645 ccan_list_head_init(&heap->pages);
10646
10647 for (i = 0; i < total_pages; i++) {
10648 ccan_list_add(&heap->pages, &page_list[i]->page_node);
10649 if (page_list[i]->free_slots != 0) {
10650 heap_add_freepage(heap, page_list[i]);
10651 }
10652 }
10653
10654 free(page_list);
10655 }
10656}
10657#endif
10658
10659void
10660rb_gc_impl_register_pinning_obj(void *objspace_ptr, VALUE obj)
10661{
10662 /* no-op */
10663}
10664
10665bool
10666rb_gc_impl_object_moved_p(void *objspace_ptr, VALUE obj)
10667{
10668 return gc_object_moved_p(objspace_ptr, obj);
10669}
10670
10671static int
10672gc_ref_update(void *vstart, void *vend, size_t stride, rb_objspace_t *objspace, struct heap_page *page)
10673{
10674 VALUE v = (VALUE)vstart;
10675
10676 page->flags.has_uncollectible_wb_unprotected_objects = FALSE;
10677 page->flags.has_remembered_objects = FALSE;
10678
10679 /* For each object on the page */
10680 for (; v != (VALUE)vend; v += stride) {
10681 asan_unpoisoning_object(v) {
10682 switch (BUILTIN_TYPE(v)) {
10683 case T_NONE:
10684 case T_MOVED:
10685 case T_ZOMBIE:
10686 break;
10687 default:
10688 if (RVALUE_WB_UNPROTECTED(objspace, v)) {
10689 page->flags.has_uncollectible_wb_unprotected_objects = TRUE;
10690 }
10691 if (RVALUE_REMEMBERED(objspace, v)) {
10692 page->flags.has_remembered_objects = TRUE;
10693 }
10694 if (page->flags.before_sweep) {
10695 if (RVALUE_MARKED(objspace, v)) {
10696 rb_gc_update_object_references(objspace, v);
10697 }
10698 }
10699 else {
10700 rb_gc_update_object_references(objspace, v);
10701 }
10702 }
10703 }
10704 }
10705
10706 return 0;
10707}
10708
10709static int
10710gc_update_references_weak_table_i(VALUE obj, void *data)
10711{
10712 int ret;
10713 asan_unpoisoning_object(obj) {
10714 ret = BUILTIN_TYPE(obj) == T_MOVED ? ST_REPLACE : ST_CONTINUE;
10715 }
10716 return ret;
10717}
10718
10719static int
10720gc_update_references_weak_table_replace_i(VALUE *obj, void *data)
10721{
10722 rb_gc_update_moved(obj);
10723
10724 return ST_CONTINUE;
10725}
10726
10727/* The per-objspace side of the reference update: walk this objspace's heap objects and rewrite
10728 * moved references (following T_MOVED forwarding across objspaces). A compacting global GC
10729 * runs this for every objspace. */
10730static void
10731gc_update_references_heap(rb_objspace_t *objspace)
10732{
10733 struct heap_page *page = NULL;
10734
10735 for (int i = 0; i < HEAP_COUNT; i++) {
10736 bool should_set_mark_bits = TRUE;
10737 rb_heap_t *heap = &heaps[i];
10738
10739 ccan_list_for_each(&heap->pages, page, page_node) {
10740 uintptr_t start = (uintptr_t)page->start;
10741 uintptr_t end = start + (page->total_slots * heap->slot_size);
10742
10743 gc_ref_update((void *)start, (void *)end, heap->slot_size, objspace, page);
10744 if (page == heap->sweeping_page) {
10745 should_set_mark_bits = FALSE;
10746 }
10747 if (should_set_mark_bits) {
10748 gc_setup_mark_bits(page);
10749 }
10750 }
10751 }
10752}
10753
10754/* The VM-global side of the reference update (finalizer table, every Ractor's VM roots,
10755 * weak tables). Process-wide, so a compacting global GC runs it once after every heap
10756 * side: rb_gc_update_vm_references and the weak tables' mark_and_move are not idempotent. */
10757static void
10758gc_update_references_global(rb_objspace_t *objspace)
10759{
10760 gc_update_table_refs(finalizer_table);
10761
10762 rb_gc_update_vm_references((void *)objspace);
10763
10764 for (int table = 0; table < RB_GC_VM_WEAK_TABLE_COUNT; table++) {
10765 rb_gc_vm_weak_table_foreach(
10766 gc_update_references_weak_table_i,
10767 gc_update_references_weak_table_replace_i,
10768 NULL,
10769 false,
10770 table
10771 );
10772 }
10773}
10774
10775static void
10776gc_update_references(rb_objspace_t *objspace)
10777{
10778 objspace->flags.during_reference_updating = true;
10779
10780 rb_gc_before_updating_jit_code();
10781
10782 gc_update_references_heap(objspace);
10783 gc_update_references_global(objspace);
10784
10785 rb_gc_after_updating_jit_code();
10786
10787 objspace->flags.during_reference_updating = false;
10788}
10789
10790#if GC_CAN_COMPILE_COMPACTION
10791static void
10792root_obj_check_moved_i(const char *category, VALUE obj, void *data)
10793{
10794 rb_objspace_t *objspace = data;
10795
10796 if (gc_object_moved_p(objspace, obj)) {
10797 rb_bug("ROOT %s points to MOVED: %p -> %s", category, (void *)obj, rb_obj_info(rb_gc_impl_location(objspace, obj)));
10798 }
10799}
10800
10801static void
10802reachable_object_check_moved_i(VALUE ref, void *data)
10803{
10804 VALUE parent = (VALUE)data;
10805 if (gc_object_moved_p(rb_gc_get_objspace(), ref)) {
10806 rb_bug("Object %s points to MOVED: %p -> %s", rb_obj_info(parent), (void *)ref, rb_obj_info(rb_gc_impl_location(rb_gc_get_objspace(), ref)));
10807 }
10808}
10809
10810static int
10811heap_check_moved_i(void *vstart, void *vend, size_t stride, void *data)
10812{
10813 rb_objspace_t *objspace = data;
10814
10815 VALUE v = (VALUE)vstart;
10816 for (; v != (VALUE)vend; v += stride) {
10817 if (gc_object_moved_p(objspace, v)) {
10818 /* Moved object still on the heap, something may have a reference. */
10819 }
10820 else {
10821 asan_unpoisoning_object(v) {
10822 switch (BUILTIN_TYPE(v)) {
10823 case T_NONE:
10824 case T_ZOMBIE:
10825 break;
10826 default:
10827 if (!rb_gc_impl_garbage_object_p(objspace, v)) {
10828 rb_objspace_reachable_objects_from_unlocked(v, reachable_object_check_moved_i, (void *)v);
10829 }
10830 }
10831 }
10832 }
10833 }
10834
10835 return 0;
10836}
10837#endif
10838
10839bool
10840rb_gc_impl_during_gc_p(void *objspace_ptr)
10841{
10842 rb_objspace_t *objspace = objspace_ptr;
10843
10844 return during_gc;
10845}
10846
10847#if RGENGC_PROFILE >= 2
10848
10849static const char*
10850type_name(int type, VALUE obj)
10851{
10852 switch ((enum ruby_value_type)type) {
10853 case RUBY_T_NONE: return "T_NONE";
10854 case RUBY_T_OBJECT: return "T_OBJECT";
10855 case RUBY_T_CLASS: return "T_CLASS";
10856 case RUBY_T_MODULE: return "T_MODULE";
10857 case RUBY_T_FLOAT: return "T_FLOAT";
10858 case RUBY_T_STRING: return "T_STRING";
10859 case RUBY_T_REGEXP: return "T_REGEXP";
10860 case RUBY_T_ARRAY: return "T_ARRAY";
10861 case RUBY_T_HASH: return "T_HASH";
10862 case RUBY_T_STRUCT: return "T_STRUCT";
10863 case RUBY_T_BIGNUM: return "T_BIGNUM";
10864 case RUBY_T_FILE: return "T_FILE";
10865 case RUBY_T_DATA: return "T_DATA";
10866 case RUBY_T_MATCH: return "T_MATCH";
10867 case RUBY_T_COMPLEX: return "T_COMPLEX";
10868 case RUBY_T_RATIONAL: return "T_RATIONAL";
10869 case RUBY_T_NIL: return "T_NIL";
10870 case RUBY_T_TRUE: return "T_TRUE";
10871 case RUBY_T_FALSE: return "T_FALSE";
10872 case RUBY_T_SYMBOL: return "T_SYMBOL";
10873 case RUBY_T_FIXNUM: return "T_FIXNUM";
10874 case RUBY_T_UNDEF: return "T_UNDEF";
10875 case RUBY_T_IMEMO: return "T_IMEMO";
10876 case RUBY_T_NODE: return "T_NODE";
10877 case RUBY_T_ICLASS: return "T_ICLASS";
10878 case RUBY_T_ZOMBIE: return "T_ZOMBIE";
10879 case RUBY_T_MOVED: return "T_MOVED";
10880 default: return "unknown";
10881 }
10882}
10883
10884static void
10885gc_count_add_each_types(VALUE hash, const char *name, const size_t *types)
10886{
10887 VALUE result = rb_hash_new_capa(T_MASK);
10888 int i;
10889 for (i=0; i<T_MASK; i++) {
10890 const char *type = type_name(i, 0);
10891 rb_hash_aset(result, ID2SYM(rb_intern(type)), SIZET2NUM(types[i]));
10892 }
10893 rb_hash_aset(hash, ID2SYM(rb_intern(name)), result);
10894}
10895#endif
10896
10897size_t
10898rb_gc_impl_gc_count(void *objspace_ptr)
10899{
10900 rb_objspace_t *objspace = objspace_ptr;
10901
10902 return objspace->profile.count;
10903}
10904
10905/* Filled by setup_gc_latest_gc_info_symbols() at boot, not on first use. */
10906static VALUE sym_major_by, sym_gc_by, sym_immediate_sweep, sym_have_finalizer, sym_state, sym_need_major_by;
10907static VALUE sym_nofree, sym_oldgen, sym_shady, sym_force, sym_stress;
10908#if RGENGC_ESTIMATE_OLDMALLOC
10909static VALUE sym_oldmalloc;
10910#endif
10911static VALUE sym_newobj, sym_malloc, sym_method, sym_capi;
10912static VALUE sym_none, sym_marking, sym_sweeping;
10913static VALUE sym_weak_references_count;
10914
10915static void
10916setup_gc_latest_gc_info_symbols(void)
10917{
10918#define S(s) sym_##s = ID2SYM(rb_intern_const(#s))
10919 S(major_by);
10920 S(gc_by);
10921 S(immediate_sweep);
10922 S(have_finalizer);
10923 S(state);
10924 S(need_major_by);
10925
10926 S(stress);
10927 S(nofree);
10928 S(oldgen);
10929 S(shady);
10930 S(force);
10931#if RGENGC_ESTIMATE_OLDMALLOC
10932 S(oldmalloc);
10933#endif
10934 S(newobj);
10935 S(malloc);
10936 S(method);
10937 S(capi);
10938
10939 S(none);
10940 S(marking);
10941 S(sweeping);
10942
10943 S(weak_references_count);
10944#undef S
10945}
10946
10947static VALUE
10948gc_info_decode(rb_objspace_t *objspace, const VALUE hash_or_key, const unsigned int orig_flags)
10949{
10950 VALUE hash = Qnil, key = Qnil;
10951 VALUE major_by, need_major_by;
10952 unsigned int flags = orig_flags ? orig_flags : objspace->profile.latest_gc_info;
10953
10954 if (SYMBOL_P(hash_or_key)) {
10955 key = hash_or_key;
10956 }
10957 else if (RB_TYPE_P(hash_or_key, T_HASH)) {
10958 hash = hash_or_key;
10959 }
10960 else {
10961 rb_bug("gc_info_decode: non-hash or symbol given");
10962 }
10963
10964#define SET(name, attr) \
10965 if (key == sym_##name) \
10966 return (attr); \
10967 else if (hash != Qnil) \
10968 rb_hash_aset(hash, sym_##name, (attr));
10969
10970 major_by =
10971 (flags & GPR_FLAG_MAJOR_BY_NOFREE) ? sym_nofree :
10972 (flags & GPR_FLAG_MAJOR_BY_OLDGEN) ? sym_oldgen :
10973 (flags & GPR_FLAG_MAJOR_BY_SHADY) ? sym_shady :
10974 (flags & GPR_FLAG_MAJOR_BY_FORCE) ? sym_force :
10975#if RGENGC_ESTIMATE_OLDMALLOC
10976 (flags & GPR_FLAG_MAJOR_BY_OLDMALLOC) ? sym_oldmalloc :
10977#endif
10978 Qnil;
10979 SET(major_by, major_by);
10980
10981 if (orig_flags == 0) { /* set need_major_by only if flags not set explicitly */
10982 unsigned int need_major_flags = gc_needs_major_flags;
10983 need_major_by =
10984 (need_major_flags & GPR_FLAG_MAJOR_BY_NOFREE) ? sym_nofree :
10985 (need_major_flags & GPR_FLAG_MAJOR_BY_OLDGEN) ? sym_oldgen :
10986 (need_major_flags & GPR_FLAG_MAJOR_BY_SHADY) ? sym_shady :
10987 (need_major_flags & GPR_FLAG_MAJOR_BY_FORCE) ? sym_force :
10988#if RGENGC_ESTIMATE_OLDMALLOC
10989 (need_major_flags & GPR_FLAG_MAJOR_BY_OLDMALLOC) ? sym_oldmalloc :
10990#endif
10991 Qnil;
10992 SET(need_major_by, need_major_by);
10993 }
10994
10995 SET(gc_by,
10996 (flags & GPR_FLAG_NEWOBJ) ? sym_newobj :
10997 (flags & GPR_FLAG_MALLOC) ? sym_malloc :
10998 (flags & GPR_FLAG_METHOD) ? sym_method :
10999 (flags & GPR_FLAG_CAPI) ? sym_capi :
11000 (flags & GPR_FLAG_STRESS) ? sym_stress :
11001 Qnil
11002 );
11003
11004 SET(have_finalizer, (flags & GPR_FLAG_HAVE_FINALIZE) ? Qtrue : Qfalse);
11005 SET(immediate_sweep, (flags & GPR_FLAG_IMMEDIATE_SWEEP) ? Qtrue : Qfalse);
11006
11007 if (orig_flags == 0) {
11008 SET(state, gc_mode(objspace) == gc_mode_none ? sym_none :
11009 gc_mode(objspace) == gc_mode_marking ? sym_marking : sym_sweeping);
11010 }
11011
11012 SET(weak_references_count, LONG2FIX(objspace->profile.weak_references_count));
11013#undef SET
11014
11015 if (!NIL_P(key)) {
11016 // Matched key should return above
11017 return Qundef;
11018 }
11019
11020 return hash;
11021}
11022
11023VALUE
11024rb_gc_impl_latest_gc_info(void *objspace_ptr, VALUE key)
11025{
11026 rb_objspace_t *objspace = objspace_ptr;
11027
11028 return gc_info_decode(objspace, key, 0);
11029}
11030
11031
11032enum gc_stat_sym {
11033 gc_stat_sym_count,
11034 gc_stat_sym_time,
11035 gc_stat_sym_marking_time,
11036 gc_stat_sym_sweeping_time,
11037 gc_stat_sym_heap_allocated_pages,
11038 gc_stat_sym_heap_empty_pages,
11039 gc_stat_sym_heap_allocatable_bytes,
11040 gc_stat_sym_heap_available_slots,
11041 gc_stat_sym_heap_live_slots,
11042 gc_stat_sym_heap_free_slots,
11043 gc_stat_sym_heap_final_slots,
11044 gc_stat_sym_heap_marked_slots,
11045 gc_stat_sym_heap_eden_pages,
11046 gc_stat_sym_total_allocated_pages,
11047 gc_stat_sym_total_freed_pages,
11048 gc_stat_sym_total_allocated_objects,
11049 gc_stat_sym_total_freed_objects,
11050 gc_stat_sym_total_malloc_bytes,
11051 gc_stat_sym_total_free_bytes,
11052 gc_stat_sym_malloc_increase_bytes,
11053 gc_stat_sym_malloc_increase_bytes_limit,
11054 gc_stat_sym_minor_gc_count,
11055 gc_stat_sym_major_gc_count,
11056 gc_stat_sym_global_gc_count,
11057 gc_stat_sym_global_gc_invocation_count,
11058 gc_stat_sym_compact_count,
11059 gc_stat_sym_read_barrier_faults,
11060 gc_stat_sym_total_moved_objects,
11061 gc_stat_sym_remembered_wb_unprotected_objects,
11062 gc_stat_sym_remembered_wb_unprotected_objects_limit,
11063 gc_stat_sym_old_objects,
11064 gc_stat_sym_old_objects_limit,
11065#if RGENGC_ESTIMATE_OLDMALLOC
11066 gc_stat_sym_oldmalloc_increase_bytes,
11067 gc_stat_sym_oldmalloc_increase_bytes_limit,
11068#endif
11069#if RGENGC_PROFILE
11070 gc_stat_sym_total_generated_normal_object_count,
11071 gc_stat_sym_total_generated_shady_object_count,
11072 gc_stat_sym_total_shade_operation_count,
11073 gc_stat_sym_total_promoted_count,
11074 gc_stat_sym_total_remembered_normal_object_count,
11075 gc_stat_sym_total_remembered_shady_object_count,
11076#endif
11077 gc_stat_sym_page_pool_arenas,
11078 gc_stat_sym_page_pool_arenas_freed,
11079 gc_stat_sym_page_pool_total_pages,
11080 gc_stat_sym_page_pool_discarded_pages,
11081 gc_stat_sym_last
11082};
11083
11084static VALUE gc_stat_symbols[gc_stat_sym_last];
11085
11086static void
11087setup_gc_stat_symbols(void)
11088{
11089#define S(s) gc_stat_symbols[gc_stat_sym_##s] = ID2SYM(rb_intern_const(#s))
11090 S(count);
11091 S(time);
11092 S(marking_time),
11093 S(sweeping_time),
11094 S(heap_allocated_pages);
11095 S(heap_empty_pages);
11096 S(heap_allocatable_bytes);
11097 S(heap_available_slots);
11098 S(heap_live_slots);
11099 S(heap_free_slots);
11100 S(heap_final_slots);
11101 S(heap_marked_slots);
11102 S(heap_eden_pages);
11103 S(total_allocated_pages);
11104 S(total_freed_pages);
11105 S(total_allocated_objects);
11106 S(total_freed_objects);
11107 S(total_malloc_bytes);
11108 S(total_free_bytes);
11109 S(malloc_increase_bytes);
11110 S(malloc_increase_bytes_limit);
11111 S(minor_gc_count);
11112 S(major_gc_count);
11113 S(global_gc_count);
11114 S(global_gc_invocation_count);
11115 S(compact_count);
11116 S(read_barrier_faults);
11117 S(total_moved_objects);
11118 S(remembered_wb_unprotected_objects);
11119 S(remembered_wb_unprotected_objects_limit);
11120 S(old_objects);
11121 S(old_objects_limit);
11122#if RGENGC_ESTIMATE_OLDMALLOC
11123 S(oldmalloc_increase_bytes);
11124 S(oldmalloc_increase_bytes_limit);
11125#endif
11126#if RGENGC_PROFILE
11127 S(total_generated_normal_object_count);
11128 S(total_generated_shady_object_count);
11129 S(total_shade_operation_count);
11130 S(total_promoted_count);
11131 S(total_remembered_normal_object_count);
11132 S(total_remembered_shady_object_count);
11133#endif /* RGENGC_PROFILE */
11134 S(page_pool_arenas);
11135 S(page_pool_arenas_freed);
11136 S(page_pool_total_pages);
11137 S(page_pool_discarded_pages);
11138#undef S
11139}
11140
11141static uint64_t
11142ns_to_ms(uint64_t ns)
11143{
11144 return ns / (1000 * 1000);
11145}
11146
11147static void malloc_increase_local_flush(rb_objspace_t *objspace);
11148
11149static void
11150gc_process_stat_accumulate_i(void *objspace_ptr, void *data)
11151{
11152 rb_objspace_t *objspace = objspace_ptr;
11153 struct gc_process_stat_total *total = (struct gc_process_stat_total *)data;
11154 struct gc_process_stat_snapshot snap;
11155 rb_native_mutex_lock(&objspace->process_stat.lock);
11156 snap = objspace->process_stat.published;
11157 rb_native_mutex_unlock(&objspace->process_stat.lock);
11158 gc_process_stat_add(total, &snap);
11159}
11160
11161static VALUE
11162gc_process_stat(VALUE hash_or_sym)
11163{
11164 VALUE hash = Qnil, key = Qnil;
11165
11166 if (RB_TYPE_P(hash_or_sym, T_HASH)) {
11167 hash = hash_or_sym;
11168 }
11169 else if (SYMBOL_P(hash_or_sym)) {
11170 key = hash_or_sym;
11171 }
11172 else {
11173 rb_bug("non-hash or symbol given");
11174 }
11175
11176 struct gc_process_stat_total total;
11177 uint64_t direct_global_gc_count;
11178 unsigned int lev = RB_GC_VM_LOCK();
11179 total = global_objspace->process_stat_archive;
11180 rb_gc_vm_each_objspace(gc_process_stat_accumulate_i, &total);
11181 direct_global_gc_count = global_objspace->global_gc.count;
11182 RB_GC_VM_UNLOCK(lev);
11183
11184 rb_objspace_t *const current = rb_gc_get_objspace();
11185 if (!gc_during_gc_get(current)) {
11186 GC_ASSERT(total.global_gc_invocation_count == direct_global_gc_count);
11187 }
11188
11189 /* Convert to Ruby values after all collector locks are released. */
11190 uint64_t time_ns = total.marking_time_ns + total.sweeping_time_ns;
11191 uint64_t count = total.minor_gc_count + total.major_gc_count + total.global_gc_invocation_count;
11192 size_t page_pool_arenas = global_objspace->page_pool.arena_count;
11193
11194#define SET64(name, attr) \
11195 if (key == gc_stat_symbols[gc_stat_sym_##name]) \
11196 return ULL2NUM(attr); \
11197 else if (hash != Qnil) \
11198 rb_hash_aset(hash, gc_stat_symbols[gc_stat_sym_##name], ULL2NUM(attr));
11199
11200 SET64(count, count);
11201 SET64(time, ns_to_ms(time_ns));
11202 SET64(marking_time, ns_to_ms(total.marking_time_ns));
11203 SET64(sweeping_time, ns_to_ms(total.sweeping_time_ns));
11204 SET64(minor_gc_count, total.minor_gc_count);
11205 SET64(major_gc_count, total.major_gc_count);
11206 SET64(global_gc_count, total.global_gc_invocation_count);
11207 SET64(page_pool_arenas, page_pool_arenas);
11208 SET64(page_pool_arenas_freed, global_objspace->page_pool.arenas_unmapped);
11209 SET64(page_pool_total_pages, (uint64_t)page_pool_arenas * PAGE_POOL_ARENA_BODIES);
11210 SET64(page_pool_discarded_pages, global_objspace->page_pool.advised_count);
11211
11212#undef SET64
11213
11214 if (!NIL_P(key)) {
11215 /* Matched key should return above. */
11216 return Qundef;
11217 }
11218
11219 return hash;
11220}
11221
11222VALUE
11223rb_gc_impl_stat(void *objspace_ptr, VALUE hash_or_sym)
11224{
11225 if (objspace_ptr == NULL) {
11226 return gc_process_stat(hash_or_sym);
11227 }
11228
11229 rb_objspace_t *objspace = objspace_ptr;
11230 VALUE hash = Qnil, key = Qnil;
11231
11232 malloc_increase_local_flush(objspace);
11233
11234 if (RB_TYPE_P(hash_or_sym, T_HASH)) {
11235 hash = hash_or_sym;
11236 }
11237 else if (SYMBOL_P(hash_or_sym)) {
11238 key = hash_or_sym;
11239 }
11240 else {
11241 rb_bug("non-hash or symbol given");
11242 }
11243
11244#define SET(name, attr) \
11245 if (key == gc_stat_symbols[gc_stat_sym_##name]) \
11246 return SIZET2NUM(attr); \
11247 else if (hash != Qnil) \
11248 rb_hash_aset(hash, gc_stat_symbols[gc_stat_sym_##name], SIZET2NUM(attr));
11249#define SET64(name, attr) \
11250 if (key == gc_stat_symbols[gc_stat_sym_##name]) \
11251 return ULL2NUM(attr); \
11252 else if (hash != Qnil) \
11253 rb_hash_aset(hash, gc_stat_symbols[gc_stat_sym_##name], ULL2NUM(attr));
11254
11255 SET(count, objspace->profile.count);
11256 SET(time, (size_t)ns_to_ms(objspace->profile.marking_time_ns + objspace->profile.sweeping_time_ns)); // TODO: UINT64T2NUM
11257 SET(marking_time, (size_t)ns_to_ms(objspace->profile.marking_time_ns));
11258 SET(sweeping_time, (size_t)ns_to_ms(objspace->profile.sweeping_time_ns));
11259
11260 {
11261 uint64_t total_malloc = (uint64_t)gc_counter_load_relaxed(&objspace->malloc_counters.counters.malloc);
11262 uint64_t total_free = (uint64_t)gc_counter_load_relaxed(&objspace->malloc_counters.counters.free);
11263 SET64(total_malloc_bytes, total_malloc);
11264 SET64(total_free_bytes, total_free);
11265 }
11266
11267 /* implementation dependent counters (small / fixnum-safe) */
11268 SET(heap_allocated_pages, rb_darray_size(objspace->heap_pages.sorted));
11269 SET(heap_empty_pages, objspace->empty_pages_count)
11270 SET(heap_allocatable_bytes, objspace->heap_pages.allocatable_bytes);
11271 SET(heap_eden_pages, heap_eden_total_pages(objspace));
11272 SET(total_allocated_pages, objspace->heap_pages.allocated_pages);
11273 SET(total_freed_pages, objspace->heap_pages.freed_pages);
11274 SET(malloc_increase_bytes, gc_malloc_counters_increase_unsigned(objspace, &objspace->malloc_counters.counters));
11275 SET(malloc_increase_bytes_limit, malloc_limit);
11276 SET(minor_gc_count, objspace->profile.minor_gc_count);
11277 SET(major_gc_count, objspace->profile.major_gc_count);
11278 SET(global_gc_count, objspace->profile.global_gc_count);
11279 SET(global_gc_invocation_count, objspace->profile.global_gc_invocation_count);
11280 SET(compact_count, objspace->profile.compact_count);
11281 SET(read_barrier_faults, objspace->profile.read_barrier_faults);
11282 SET(total_moved_objects, objspace->rcompactor.total_moved);
11283 SET(remembered_wb_unprotected_objects, objspace->rgengc.uncollectible_wb_unprotected_objects);
11284 SET(remembered_wb_unprotected_objects_limit, objspace->rgengc.uncollectible_wb_unprotected_objects_limit);
11285 SET(old_objects, objspace->rgengc.old_objects);
11286 SET(old_objects_limit, objspace->rgengc.old_objects_limit);
11287#if RGENGC_ESTIMATE_OLDMALLOC
11288 SET(oldmalloc_increase_bytes, gc_oldmalloc_increase_load(objspace));
11289 SET(oldmalloc_increase_bytes_limit, objspace->rgengc.oldmalloc_increase_limit);
11290#endif
11291
11292 SET(total_allocated_objects, total_allocated_objects(objspace));
11293 SET(total_freed_objects, total_freed_objects(objspace));
11294 SET(heap_available_slots, objspace_available_slots(objspace));
11295 SET(heap_live_slots, objspace_live_slots(objspace));
11296 SET(heap_free_slots, objspace_free_slots(objspace));
11297 SET(heap_final_slots, total_final_slots_count(objspace));
11298 SET(heap_marked_slots, objspace->marked_slots);
11299
11300#if RGENGC_PROFILE
11301 SET(total_generated_normal_object_count, objspace->profile.total_generated_normal_object_count);
11302 SET(total_generated_shady_object_count, objspace->profile.total_generated_shady_object_count);
11303 SET(total_shade_operation_count, objspace->profile.total_shade_operation_count);
11304 SET(total_promoted_count, objspace->profile.total_promoted_count);
11305 SET(total_remembered_normal_object_count, objspace->profile.total_remembered_normal_object_count);
11306 SET(total_remembered_shady_object_count, objspace->profile.total_remembered_shady_object_count);
11307#endif /* RGENGC_PROFILE */
11308#undef SET
11309#undef SET64
11310
11311 if (!NIL_P(key)) {
11312 // Matched key should return above
11313 return Qundef;
11314 }
11315
11316#if defined(RGENGC_PROFILE) && RGENGC_PROFILE >= 2
11317 if (hash != Qnil) {
11318 gc_count_add_each_types(hash, "generated_normal_object_count_types", objspace->profile.generated_normal_object_count_types);
11319 gc_count_add_each_types(hash, "generated_shady_object_count_types", objspace->profile.generated_shady_object_count_types);
11320 gc_count_add_each_types(hash, "shade_operation_count_types", objspace->profile.shade_operation_count_types);
11321 gc_count_add_each_types(hash, "promoted_types", objspace->profile.promoted_types);
11322 gc_count_add_each_types(hash, "remembered_normal_object_count_types", objspace->profile.remembered_normal_object_count_types);
11323 gc_count_add_each_types(hash, "remembered_shady_object_count_types", objspace->profile.remembered_shady_object_count_types);
11324 }
11325#endif
11326
11327 return hash;
11328}
11329
11330enum gc_stat_heap_sym {
11331 gc_stat_heap_sym_slot_size,
11332 gc_stat_heap_sym_heap_live_slots,
11333 gc_stat_heap_sym_heap_free_slots,
11334 gc_stat_heap_sym_heap_final_slots,
11335 gc_stat_heap_sym_heap_eden_pages,
11336 gc_stat_heap_sym_heap_eden_slots,
11337 gc_stat_heap_sym_total_allocated_pages,
11338 gc_stat_heap_sym_force_major_gc_count,
11339 gc_stat_heap_sym_force_incremental_marking_finish_count,
11340 gc_stat_heap_sym_heap_allocatable_slots,
11341 gc_stat_heap_sym_total_allocated_objects,
11342 gc_stat_heap_sym_total_freed_objects,
11343 gc_stat_heap_sym_last
11344};
11345
11346static VALUE gc_stat_heap_symbols[gc_stat_heap_sym_last];
11347
11348static void
11349setup_gc_stat_heap_symbols(void)
11350{
11351#define S(s) gc_stat_heap_symbols[gc_stat_heap_sym_##s] = ID2SYM(rb_intern_const(#s))
11352 S(slot_size);
11353 S(heap_live_slots);
11354 S(heap_free_slots);
11355 S(heap_final_slots);
11356 S(heap_eden_pages);
11357 S(heap_eden_slots);
11358 S(heap_allocatable_slots);
11359 S(total_allocated_pages);
11360 S(force_major_gc_count);
11361 S(force_incremental_marking_finish_count);
11362 S(total_allocated_objects);
11363 S(total_freed_objects);
11364#undef S
11365}
11366
11367static VALUE
11368stat_one_heap(rb_objspace_t *objspace, rb_heap_t *heap, VALUE hash, VALUE key)
11369{
11370#define SET(name, attr) \
11371 if (key == gc_stat_heap_symbols[gc_stat_heap_sym_##name]) \
11372 return SIZET2NUM(attr); \
11373 else if (hash != Qnil) \
11374 rb_hash_aset(hash, gc_stat_heap_symbols[gc_stat_heap_sym_##name], SIZET2NUM(attr));
11375
11376 SET(slot_size, heap->slot_size);
11377 SET(heap_live_slots, heap->total_allocated_objects - heap->total_freed_objects - heap->final_slots_count);
11378 SET(heap_free_slots, heap->total_slots - (heap->total_allocated_objects - heap->total_freed_objects));
11379 SET(heap_final_slots, heap->final_slots_count);
11380 SET(heap_eden_pages, heap->total_pages);
11381 SET(heap_eden_slots, heap->total_slots);
11382 SET(heap_allocatable_slots, objspace->heap_pages.allocatable_bytes / heap->slot_size);
11383 SET(total_allocated_pages, heap->total_allocated_pages);
11384 SET(force_major_gc_count, heap->force_major_gc_count);
11385 SET(force_incremental_marking_finish_count, heap->force_incremental_marking_finish_count);
11386 SET(total_allocated_objects, heap->total_allocated_objects);
11387 SET(total_freed_objects, heap->total_freed_objects);
11388#undef SET
11389
11390 if (!NIL_P(key)) {
11391 // Matched key should return above
11392 return Qundef;
11393 }
11394
11395 return hash;
11396}
11397
11398VALUE
11399rb_gc_impl_stat_heap(void *objspace_ptr, VALUE heap_name, VALUE hash_or_sym)
11400{
11401 rb_objspace_t *objspace = objspace_ptr;
11402
11403 if (NIL_P(heap_name)) {
11404 if (!RB_TYPE_P(hash_or_sym, T_HASH)) {
11405 rb_bug("non-hash given");
11406 }
11407
11408 for (int i = 0; i < HEAP_COUNT; i++) {
11409 VALUE hash = rb_hash_aref(hash_or_sym, INT2FIX(i));
11410 if (NIL_P(hash)) {
11411 hash = rb_hash_new();
11412 rb_hash_aset(hash_or_sym, INT2FIX(i), hash);
11413 }
11414
11415 stat_one_heap(objspace, &heaps[i], hash, Qnil);
11416 }
11417 }
11418 else if (FIXNUM_P(heap_name)) {
11419 int heap_idx = FIX2INT(heap_name);
11420
11421 if (heap_idx < 0 || heap_idx >= HEAP_COUNT) {
11422 rb_raise(rb_eArgError, "size pool index out of range");
11423 }
11424
11425 if (SYMBOL_P(hash_or_sym)) {
11426 return stat_one_heap(objspace, &heaps[heap_idx], Qnil, hash_or_sym);
11427 }
11428 else if (RB_TYPE_P(hash_or_sym, T_HASH)) {
11429 return stat_one_heap(objspace, &heaps[heap_idx], hash_or_sym, Qnil);
11430 }
11431 else {
11432 rb_bug("non-hash or symbol given");
11433 }
11434 }
11435 else {
11436 rb_bug("heap_name must be nil or an Integer");
11437 }
11438
11439 return hash_or_sym;
11440}
11441
11442/* I could include internal.h for this, but doing so undefines some Array macros
11443 * necessary for initialising objects, and I don't want to include all the array
11444 * headers to get them back
11445 * TODO: Investigate why RARRAY_AREF gets undefined in internal.h
11446 */
11447#ifndef RBOOL
11448#define RBOOL(v) (v ? Qtrue : Qfalse)
11449#endif
11450
11451VALUE
11452rb_gc_impl_config_get(void *objspace_ptr)
11453{
11454#define sym(name) ID2SYM(rb_intern_const(name))
11455 rb_objspace_t *objspace = objspace_ptr;
11456 VALUE hash = rb_hash_new();
11457
11458 rb_hash_aset(hash, sym("rgengc_allow_full_mark"), RBOOL(gc_config_full_mark_val));
11459
11460 return hash;
11461}
11462
11463static int
11464gc_config_set_key(VALUE key, VALUE value, VALUE data)
11465{
11467 if (rb_sym2id(key) == rb_intern("rgengc_allow_full_mark")) {
11468 gc_rest(objspace);
11469 gc_config_full_mark_set(RTEST(value));
11470 }
11471 return ST_CONTINUE;
11472}
11473
11474void
11475rb_gc_impl_config_set(void *objspace_ptr, VALUE hash)
11476{
11477 rb_objspace_t *objspace = objspace_ptr;
11478
11479 if (!RB_TYPE_P(hash, T_HASH)) {
11480 rb_raise(rb_eArgError, "expected keyword arguments");
11481 }
11482
11483 rb_hash_foreach(hash, gc_config_set_key, (st_data_t)objspace);
11484}
11485
11486VALUE
11487rb_gc_impl_stress_get(void *objspace_ptr)
11488{
11489 return ruby_gc_stress_mode;
11490}
11491
11492void
11493rb_gc_impl_stress_set(void *objspace_ptr, VALUE flag)
11494{
11495 global_objspace->gc_stressful = RTEST(flag);
11496 global_objspace->gc_stress_mode = flag;
11497}
11498
11499static int
11500get_envparam_size(const char *name, size_t *default_value, size_t lower_bound)
11501{
11502 const char *ptr = getenv(name);
11503 ssize_t val;
11504
11505 if (ptr != NULL && *ptr) {
11506 size_t unit = 0;
11507 char *end;
11508#if SIZEOF_SIZE_T == SIZEOF_LONG_LONG
11509 val = strtoll(ptr, &end, 0);
11510#else
11511 val = strtol(ptr, &end, 0);
11512#endif
11513 switch (*end) {
11514 case 'k': case 'K':
11515 unit = 1024;
11516 ++end;
11517 break;
11518 case 'm': case 'M':
11519 unit = 1024*1024;
11520 ++end;
11521 break;
11522 case 'g': case 'G':
11523 unit = 1024*1024*1024;
11524 ++end;
11525 break;
11526 }
11527 while (*end && isspace((unsigned char)*end)) end++;
11528 if (*end) {
11529 if (RTEST(ruby_verbose)) fprintf(stderr, "invalid string for %s: %s\n", name, ptr);
11530 return 0;
11531 }
11532 if (unit > 0) {
11533 if (val < -(ssize_t)(SIZE_MAX / 2 / unit) || (ssize_t)(SIZE_MAX / 2 / unit) < val) {
11534 if (RTEST(ruby_verbose)) fprintf(stderr, "%s=%s is ignored because it overflows\n", name, ptr);
11535 return 0;
11536 }
11537 val *= unit;
11538 }
11539 if (val > 0 && (size_t)val > lower_bound) {
11540 if (RTEST(ruby_verbose)) {
11541 fprintf(stderr, "%s=%"PRIdSIZE" (default value: %"PRIuSIZE")\n", name, val, *default_value);
11542 }
11543 *default_value = (size_t)val;
11544 return 1;
11545 }
11546 else {
11547 if (RTEST(ruby_verbose)) {
11548 fprintf(stderr, "%s=%"PRIdSIZE" (default value: %"PRIuSIZE") is ignored because it must be greater than %"PRIuSIZE".\n",
11549 name, val, *default_value, lower_bound);
11550 }
11551 return 0;
11552 }
11553 }
11554 return 0;
11555}
11556
11557static int
11558get_envparam_double(const char *name, double *default_value, double lower_bound, double upper_bound, int accept_zero)
11559{
11560 const char *ptr = getenv(name);
11561 double val;
11562
11563 if (ptr != NULL && *ptr) {
11564 char *end;
11565 val = strtod(ptr, &end);
11566 if (!*ptr || *end) {
11567 if (RTEST(ruby_verbose)) fprintf(stderr, "invalid string for %s: %s\n", name, ptr);
11568 return 0;
11569 }
11570
11571 if (accept_zero && val == 0.0) {
11572 goto accept;
11573 }
11574 else if (val <= lower_bound) {
11575 if (RTEST(ruby_verbose)) {
11576 fprintf(stderr, "%s=%f (default value: %f) is ignored because it must be greater than %f.\n",
11577 name, val, *default_value, lower_bound);
11578 }
11579 }
11580 else if (upper_bound != 0.0 && /* ignore upper_bound if it is 0.0 */
11581 val > upper_bound) {
11582 if (RTEST(ruby_verbose)) {
11583 fprintf(stderr, "%s=%f (default value: %f) is ignored because it must be lower than %f.\n",
11584 name, val, *default_value, upper_bound);
11585 }
11586 }
11587 else {
11588 goto accept;
11589 }
11590 }
11591 return 0;
11592
11593 accept:
11594 if (RTEST(ruby_verbose)) fprintf(stderr, "%s=%f (default value: %f)\n", name, val, *default_value);
11595 *default_value = val;
11596 return 1;
11597}
11598
11599/*
11600 * GC tuning environment variables
11601 *
11602 * * RUBY_GC_HEAP_FREE_SLOTS
11603 * - Prepare at least this amount of slots after GC.
11604 * - Allocate slots if there are not enough slots.
11605 * * RUBY_GC_HEAP_GROWTH_FACTOR (new from 2.1)
11606 * - Allocate slots by this factor.
11607 * - (next slots number) = (current slots number) * (this factor)
11608 * * RUBY_GC_HEAP_GROWTH_MAX_BYTES (was RUBY_GC_HEAP_GROWTH_MAX_SLOTS)
11609 * - Allocation rate is limited to this number of bytes.
11610 * * RUBY_GC_HEAP_FREE_SLOTS_MIN_RATIO (new from 2.4)
11611 * - Allocate additional pages when the number of free slots is
11612 * lower than the value (total_slots * (this ratio)).
11613 * * RUBY_GC_HEAP_FREE_SLOTS_GOAL_RATIO (new from 2.4)
11614 * - Allocate slots to satisfy this formula:
11615 * free_slots = total_slots * goal_ratio
11616 * - In other words, prepare (total_slots * goal_ratio) free slots.
11617 * - if this value is 0.0, then use RUBY_GC_HEAP_GROWTH_FACTOR directly.
11618 * * RUBY_GC_HEAP_FREE_SLOTS_MAX_RATIO (new from 2.4)
11619 * - Allow to free pages when the number of free slots is
11620 * greater than the value (total_slots * (this ratio)).
11621 * * RUBY_GC_HEAP_OLDOBJECT_LIMIT_FACTOR (new from 2.1.1)
11622 * - Do full GC when the number of old objects is more than R * N
11623 * where R is this factor and
11624 * N is the number of old objects just after last full GC.
11625 *
11626 * * obsolete
11627 * * RUBY_FREE_MIN -> RUBY_GC_HEAP_FREE_SLOTS (from 2.1)
11628 * * RUBY_HEAP_MIN_SLOTS -> RUBY_GC_HEAP_INIT_SLOTS (from 2.1) -> RUBY_GC_HEAP_INIT_BYTES
11629 *
11630 * * RUBY_GC_MALLOC_LIMIT
11631 * * RUBY_GC_MALLOC_LIMIT_MAX (new from 2.1)
11632 * * RUBY_GC_MALLOC_LIMIT_GROWTH_FACTOR (new from 2.1)
11633 *
11634 * * RUBY_GC_OLDMALLOC_LIMIT (new from 2.1)
11635 * * RUBY_GC_OLDMALLOC_LIMIT_MAX (new from 2.1)
11636 * * RUBY_GC_OLDMALLOC_LIMIT_GROWTH_FACTOR (new from 2.1)
11637 */
11638
11639void
11640rb_gc_impl_set_params(void *objspace_ptr)
11641{
11642 rb_objspace_t *objspace = objspace_ptr;
11643 get_envparam_size("RUBY_GC_HEAP_FREE_SLOTS", &gc_params.heap_free_slots, 0);
11644
11645 get_envparam_size("RUBY_GC_HEAP_INIT_BYTES", &gc_params.heap_init_bytes,
11646 heap_init_bytes_min() - 1);
11647 get_envparam_size("RUBY_GC_RACTOR_HEAP_INIT_BYTES", &gc_params.ractor_heap_init_bytes,
11648 heap_init_bytes_min() - 1);
11649
11650 get_envparam_double("RUBY_GC_HEAP_GROWTH_FACTOR", &gc_params.growth_factor, 1.0, 0.0, FALSE);
11651 get_envparam_size ("RUBY_GC_HEAP_GROWTH_MAX_BYTES", &gc_params.growth_max_bytes, 0);
11652 get_envparam_double("RUBY_GC_HEAP_FREE_SLOTS_MIN_RATIO", &gc_params.heap_free_slots_min_ratio,
11653 0.0, 1.0, FALSE);
11654 get_envparam_double("RUBY_GC_HEAP_FREE_SLOTS_MAX_RATIO", &gc_params.heap_free_slots_max_ratio,
11655 gc_params.heap_free_slots_min_ratio, 1.0, FALSE);
11656 get_envparam_double("RUBY_GC_HEAP_FREE_SLOTS_GOAL_RATIO", &gc_params.heap_free_slots_goal_ratio,
11657 gc_params.heap_free_slots_min_ratio, gc_params.heap_free_slots_max_ratio, TRUE);
11658 get_envparam_double("RUBY_GC_HEAP_OLDOBJECT_LIMIT_FACTOR", &gc_params.oldobject_limit_factor, 0.0, 0.0, TRUE);
11659 get_envparam_double("RUBY_GC_HEAP_REMEMBERED_WB_UNPROTECTED_OBJECTS_LIMIT_RATIO", &gc_params.uncollectible_wb_unprotected_objects_limit_ratio, 0.0, 0.0, TRUE);
11660
11661 if (get_envparam_size("RUBY_GC_MALLOC_LIMIT", &gc_params.malloc_limit_min, 0)) {
11662 malloc_limit = gc_params.malloc_limit_min;
11663 }
11664 get_envparam_size ("RUBY_GC_MALLOC_LIMIT_MAX", &gc_params.malloc_limit_max, 0);
11665 if (!gc_params.malloc_limit_max) { /* ignore max-check if 0 */
11666 gc_params.malloc_limit_max = SIZE_MAX;
11667 }
11668 get_envparam_double("RUBY_GC_MALLOC_LIMIT_GROWTH_FACTOR", &gc_params.malloc_limit_growth_factor, 1.0, 0.0, FALSE);
11669
11670#if RGENGC_ESTIMATE_OLDMALLOC
11671 if (get_envparam_size("RUBY_GC_OLDMALLOC_LIMIT", &gc_params.oldmalloc_limit_min, 0)) {
11672 objspace->rgengc.oldmalloc_increase_limit = gc_params.oldmalloc_limit_min;
11673 }
11674 get_envparam_size ("RUBY_GC_OLDMALLOC_LIMIT_MAX", &gc_params.oldmalloc_limit_max, 0);
11675 get_envparam_double("RUBY_GC_OLDMALLOC_LIMIT_GROWTH_FACTOR", &gc_params.oldmalloc_limit_growth_factor, 1.0, 0.0, FALSE);
11676#endif
11677}
11678
11679static inline size_t
11680objspace_malloc_size(rb_objspace_t *objspace, void *ptr, size_t hint)
11681{
11682#ifdef HAVE_MALLOC_USABLE_SIZE
11683 if (!hint) {
11684 hint = malloc_usable_size(ptr);
11685 }
11686#endif
11687 return hint;
11688}
11689
11690enum memop_type {
11691 MEMOP_TYPE_MALLOC = 0,
11692 MEMOP_TYPE_FREE,
11693 MEMOP_TYPE_REALLOC
11694};
11695
11696static inline void
11697atomic_sub_nounderflow(size_t *var, size_t sub)
11698{
11699 if (sub == 0) return;
11700
11701 while (1) {
11702 size_t val = rbimpl_atomic_size_load(var, RBIMPL_ATOMIC_RELAXED);
11703 size_t decrement = val < sub ? val : sub;
11704 if (RUBY_ATOMIC_SIZE_CAS(*var, val, val-decrement) == val) break;
11705 }
11706}
11707
11708#define gc_stress_full_mark_after_malloc_p() \
11709 (FIXNUM_P(ruby_gc_stress_mode) && (FIX2LONG(ruby_gc_stress_mode) & (1<<gc_stress_full_mark_after_malloc)))
11710
11711static void
11712objspace_malloc_gc_stress(rb_objspace_t *objspace)
11713{
11714 if (ruby_gc_stressful && ruby_native_thread_p()) {
11715 unsigned int reason = (GPR_FLAG_IMMEDIATE_MARK | GPR_FLAG_IMMEDIATE_SWEEP |
11716 GPR_FLAG_STRESS | GPR_FLAG_MALLOC);
11717
11718 if (gc_stress_full_mark_after_malloc_p()) {
11719 reason |= GPR_FLAG_FULL_MARK;
11720 }
11721 garbage_collect_with_gvl(objspace, reason);
11722 }
11723}
11724
11725static void
11726malloc_increase_commit(rb_objspace_t *objspace, size_t new_size, size_t old_size)
11727{
11728 if (new_size > old_size) {
11729 size_t delta = new_size - old_size;
11730 MALLOC_COUNTERS_LOCK(objspace);
11731 gc_counter_add(&objspace->malloc_counters.counters.malloc, delta);
11732#if RGENGC_ESTIMATE_OLDMALLOC
11733 RUBY_ATOMIC_SIZE_ADD(objspace->malloc_counters.oldmalloc_increase, delta);
11734#endif
11735 MALLOC_COUNTERS_UNLOCK(objspace);
11736 }
11737 else if (old_size > new_size) {
11738 size_t delta = old_size - new_size;
11739 MALLOC_COUNTERS_LOCK(objspace);
11740 gc_counter_add(&objspace->malloc_counters.counters.free, delta);
11741#if RGENGC_ESTIMATE_OLDMALLOC
11742 if (during_gc) gc_counter_add(&objspace->malloc_counters.freed_in_gc, delta);
11743 atomic_sub_nounderflow(&objspace->malloc_counters.oldmalloc_increase, delta);
11744#endif
11745 MALLOC_COUNTERS_UNLOCK(objspace);
11746 }
11747}
11748
11749#if USE_MALLOC_INCREASE_LOCAL
11750static void
11751malloc_increase_local_flush(rb_objspace_t *objspace)
11752{
11753 int delta = malloc_increase_local;
11754 if (delta == 0) return;
11755
11756 malloc_increase_local = 0;
11757 if (delta > 0) {
11758 malloc_increase_commit(objspace, (size_t)delta, 0);
11759 }
11760 else {
11761 malloc_increase_commit(objspace, 0, (size_t)(-delta));
11762 }
11763}
11764#else
11765static void
11766malloc_increase_local_flush(rb_objspace_t *objspace)
11767{
11768}
11769#endif
11770
11771static inline bool
11772objspace_malloc_increase_report(rb_objspace_t *objspace, void *mem, size_t new_size, size_t old_size, enum memop_type type, bool gc_allowed)
11773{
11774 if (0) fprintf(stderr, "increase - ptr: %p, type: %s, new_size: %"PRIdSIZE", old_size: %"PRIdSIZE"\n",
11775 mem,
11776 type == MEMOP_TYPE_MALLOC ? "malloc" :
11777 type == MEMOP_TYPE_FREE ? "free " :
11778 type == MEMOP_TYPE_REALLOC ? "realloc": "error",
11779 new_size, old_size);
11780 return false;
11781}
11782
11783static bool
11784objspace_malloc_increase_body(rb_objspace_t *objspace, void *mem, size_t new_size, size_t old_size, enum memop_type type, bool gc_allowed)
11785{
11786#if USE_MALLOC_INCREASE_LOCAL
11787 if (new_size < GC_MALLOC_INCREASE_LOCAL_THRESHOLD &&
11788 old_size < GC_MALLOC_INCREASE_LOCAL_THRESHOLD) {
11789 malloc_increase_local += (int)new_size - (int)old_size;
11790
11791 if (malloc_increase_local >= GC_MALLOC_INCREASE_LOCAL_THRESHOLD ||
11792 malloc_increase_local <= -GC_MALLOC_INCREASE_LOCAL_THRESHOLD) {
11793 malloc_increase_local_flush(objspace);
11794 }
11795 }
11796 else {
11797 malloc_increase_local_flush(objspace);
11798 malloc_increase_commit(objspace, new_size, old_size);
11799 }
11800#else
11801 malloc_increase_commit(objspace, new_size, old_size);
11802#endif
11803
11804 if (type == MEMOP_TYPE_MALLOC && gc_allowed) {
11805 retry:
11806 if (malloc_increase > malloc_limit && ruby_native_thread_p() && !dont_gc_val() && !rb_gc_gc_disabled_global_p()) {
11807 if (ruby_thread_has_gvl_p() && is_lazy_sweeping(objspace)) {
11808 gc_sweep_step_for_malloc(objspace); /* sweeping frees may reduce malloc_increase */
11809 goto retry;
11810 }
11811 garbage_collect_with_gvl(objspace, GPR_FLAG_MALLOC);
11812 }
11813 }
11814
11815#if MALLOC_ALLOCATED_SIZE
11816 if (new_size >= old_size) {
11817 RUBY_ATOMIC_SIZE_ADD(objspace->malloc_params.allocated_size, new_size - old_size);
11818 }
11819 else {
11820 size_t dec_size = old_size - new_size;
11821
11822#if MALLOC_ALLOCATED_SIZE_CHECK
11823 size_t allocated_size = objspace->malloc_params.allocated_size;
11824 if (allocated_size < dec_size) {
11825 rb_bug("objspace_malloc_increase: underflow malloc_params.allocated_size.");
11826 }
11827#endif
11828 atomic_sub_nounderflow(&objspace->malloc_params.allocated_size, dec_size);
11829 }
11830
11831 switch (type) {
11832 case MEMOP_TYPE_MALLOC:
11833 RUBY_ATOMIC_SIZE_INC(objspace->malloc_params.allocations);
11834 break;
11835 case MEMOP_TYPE_FREE:
11836 {
11837 size_t allocations = objspace->malloc_params.allocations;
11838 if (allocations > 0) {
11839 atomic_sub_nounderflow(&objspace->malloc_params.allocations, 1);
11840 }
11841#if MALLOC_ALLOCATED_SIZE_CHECK
11842 else {
11843 GC_ASSERT(objspace->malloc_params.allocations > 0);
11844 }
11845#endif
11846 }
11847 break;
11848 case MEMOP_TYPE_REALLOC: /* ignore */ break;
11849 }
11850#endif
11851 return true;
11852}
11853
11854#define objspace_malloc_increase(...) \
11855 for (bool malloc_increase_done = objspace_malloc_increase_report(__VA_ARGS__); \
11856 !malloc_increase_done; \
11857 malloc_increase_done = objspace_malloc_increase_body(__VA_ARGS__))
11858
11859struct malloc_obj_info { /* 4 words */
11860 size_t size;
11861};
11862
11863static inline size_t
11864objspace_malloc_prepare(rb_objspace_t *objspace, size_t size)
11865{
11866 if (size == 0) size = 1;
11867
11868#if CALC_EXACT_MALLOC_SIZE
11869 size += sizeof(struct malloc_obj_info);
11870#endif
11871
11872 return size;
11873}
11874
11875static bool
11876malloc_during_gc_p(rb_objspace_t *objspace)
11877{
11878 /* malloc is not allowed during GC when we're not using multiple ractors
11879 * (since ractors can run while another thread is sweeping) and when we
11880 * have the GVL (since if we don't have the GVL, we'll try to acquire the
11881 * GVL which will block and ensure the other thread finishes GC). */
11882 return during_gc && !dont_gc_val() && !rb_gc_multi_ractor_p() && ruby_thread_has_gvl_p();
11883}
11884
11885static inline void *
11886objspace_malloc_fixup(rb_objspace_t *objspace, void *mem, size_t size, bool gc_allowed)
11887{
11888 size = objspace_malloc_size(objspace, mem, size);
11889 objspace_malloc_increase(objspace, mem, size, 0, MEMOP_TYPE_MALLOC, gc_allowed) {}
11890
11891#if CALC_EXACT_MALLOC_SIZE
11892 {
11893 struct malloc_obj_info *info = mem;
11894 info->size = size;
11895 mem = info + 1;
11896 }
11897#endif
11898
11899 return mem;
11900}
11901
11902#if defined(__GNUC__) && RUBY_DEBUG
11903#define RB_BUG_INSTEAD_OF_RB_MEMERROR 1
11904#endif
11905
11906#ifndef RB_BUG_INSTEAD_OF_RB_MEMERROR
11907# define RB_BUG_INSTEAD_OF_RB_MEMERROR 0
11908#endif
11909
11910#define GC_MEMERROR(...) \
11911 ((RB_BUG_INSTEAD_OF_RB_MEMERROR+0) ? rb_bug("" __VA_ARGS__) : (void)0)
11912
11913#define TRY_WITH_GC(siz, expr) do { \
11914 const gc_profile_record_flag gpr = \
11915 GPR_FLAG_FULL_MARK | \
11916 GPR_FLAG_IMMEDIATE_MARK | \
11917 GPR_FLAG_IMMEDIATE_SWEEP | \
11918 GPR_FLAG_MALLOC; \
11919 /* stress GC must also honor gc_allowed (malloc_gc_disabled) */ \
11920 if (gc_allowed) objspace_malloc_gc_stress(objspace); \
11921 \
11922 if (RB_LIKELY((expr))) { \
11923 /* Success on 1st try */ \
11924 } \
11925 else if (gc_allowed && !garbage_collect_with_gvl(objspace, gpr)) { \
11926 /* @shyouhei thinks this doesn't happen */ \
11927 GC_MEMERROR("TRY_WITH_GC: could not GC"); \
11928 } \
11929 else if ((expr)) { \
11930 /* Success on 2nd try */ \
11931 } \
11932 else { \
11933 GC_MEMERROR("TRY_WITH_GC: could not allocate:" \
11934 "%"PRIdSIZE" bytes for %s", \
11935 siz, # expr); \
11936 } \
11937 } while (0)
11938
11939static void
11940check_malloc_not_in_gc(rb_objspace_t *objspace, const char *msg)
11941{
11942 if (RB_UNLIKELY(malloc_during_gc_p(objspace))) {
11943 dont_gc_on();
11944 during_gc = false;
11945 rb_bug("Cannot %s during GC", msg);
11946 }
11947}
11948
11949void
11950rb_gc_impl_free(void *objspace_ptr, void *ptr, size_t old_size)
11951{
11952 rb_objspace_t *objspace = objspace_ptr;
11953
11954 if (!ptr) {
11955 /*
11956 * ISO/IEC 9899 says "If ptr is a null pointer, no action occurs" since
11957 * its first version. We would better follow.
11958 */
11959 return;
11960 }
11961#if CALC_EXACT_MALLOC_SIZE
11962 struct malloc_obj_info *info = (struct malloc_obj_info *)ptr - 1;
11963#if VERIFY_FREE_SIZE
11964 if (!info->size) {
11965 const char *freeing = gc_freeing_obj_info();
11966 rb_bug("buffer %p has no recorded size%s%s. Was it allocated with ruby_mimalloc? If so it should be freed with ruby_mimfree", ptr,
11967 freeing ? ", while freeing " : "", freeing ? freeing : "");
11968 }
11969
11970 if (old_size && (old_size + sizeof(struct malloc_obj_info)) != info->size) {
11971 const char *freeing = gc_freeing_obj_info();
11972 rb_bug("buffer %p freed with old_size=%zu, but was allocated with size=%zu%s%s", ptr, old_size, info->size - sizeof(struct malloc_obj_info),
11973 freeing ? ", while freeing " : "", freeing ? freeing : "");
11974 }
11975#endif
11976 ptr = info;
11977 old_size = info->size;
11978#endif
11979 old_size = objspace_malloc_size(objspace, ptr, old_size);
11980
11981 objspace_malloc_increase(objspace, ptr, 0, old_size, MEMOP_TYPE_FREE, true) {
11982 free(ptr);
11983 ptr = NULL;
11984 RB_DEBUG_COUNTER_INC(heap_xfree);
11985 }
11986}
11987
11988void *
11989rb_gc_impl_malloc(void *objspace_ptr, size_t size, bool gc_allowed)
11990{
11991 rb_objspace_t *objspace = objspace_ptr;
11992 check_malloc_not_in_gc(objspace, "malloc");
11993
11994 void *mem;
11995
11996 size = objspace_malloc_prepare(objspace, size);
11997 TRY_WITH_GC(size, mem = malloc(size));
11998 RB_DEBUG_COUNTER_INC(heap_xmalloc);
11999 if (!mem) return mem;
12000 return objspace_malloc_fixup(objspace, mem, size, gc_allowed);
12001}
12002
12003void *
12004rb_gc_impl_calloc(void *objspace_ptr, size_t size, bool gc_allowed)
12005{
12006 rb_objspace_t *objspace = objspace_ptr;
12007
12008 if (RB_UNLIKELY(malloc_during_gc_p(objspace))) {
12009 rb_warn("calloc during GC detected, this could cause crashes if it triggers another GC");
12010#if RGENGC_CHECK_MODE || RUBY_DEBUG
12011 rb_bug("Cannot calloc during GC");
12012#endif
12013 }
12014
12015 void *mem;
12016
12017 size = objspace_malloc_prepare(objspace, size);
12018 TRY_WITH_GC(size, mem = calloc1(size));
12019 if (!mem) return mem;
12020 return objspace_malloc_fixup(objspace, mem, size, gc_allowed);
12021}
12022
12023void *
12024rb_gc_impl_realloc(void *objspace_ptr, void *ptr, size_t new_size, size_t old_size, bool gc_allowed)
12025{
12026 rb_objspace_t *objspace = objspace_ptr;
12027
12028 check_malloc_not_in_gc(objspace, "realloc");
12029
12030 void *mem;
12031
12032 if (!ptr) return rb_gc_impl_malloc(objspace, new_size, gc_allowed);
12033
12034 /*
12035 * The behavior of realloc(ptr, 0) is implementation defined.
12036 * Therefore we don't use realloc(ptr, 0) for portability reason.
12037 * see http://www.open-std.org/jtc1/sc22/wg14/www/docs/dr_400.htm
12038 */
12039 if (new_size == 0) {
12040 if ((mem = rb_gc_impl_malloc(objspace, 0, gc_allowed)) != NULL) {
12041 /*
12042 * - OpenBSD's malloc(3) man page says that when 0 is passed, it
12043 * returns a non-NULL pointer to an access-protected memory page.
12044 * The returned pointer cannot be read / written at all, but
12045 * still be a valid argument of free().
12046 *
12047 * https://man.openbsd.org/malloc.3
12048 *
12049 * - Linux's malloc(3) man page says that it _might_ perhaps return
12050 * a non-NULL pointer when its argument is 0. That return value
12051 * is safe (and is expected) to be passed to free().
12052 *
12053 * https://man7.org/linux/man-pages/man3/malloc.3.html
12054 *
12055 * - As I read the implementation jemalloc's malloc() returns fully
12056 * normal 16 bytes memory region when its argument is 0.
12057 *
12058 * - As I read the implementation musl libc's malloc() returns
12059 * fully normal 32 bytes memory region when its argument is 0.
12060 *
12061 * - Other malloc implementations can also return non-NULL.
12062 */
12063 rb_gc_impl_free(objspace, ptr, old_size);
12064 return mem;
12065 }
12066 else {
12067 /*
12068 * It is dangerous to return NULL here, because that could lead to
12069 * RCE. Fallback to 1 byte instead of zero.
12070 *
12071 * https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2019-11932
12072 */
12073 new_size = 1;
12074 }
12075 }
12076
12077#if CALC_EXACT_MALLOC_SIZE
12078 {
12079 struct malloc_obj_info *info = (struct malloc_obj_info *)ptr - 1;
12080 new_size += sizeof(struct malloc_obj_info);
12081 ptr = info;
12082#if VERIFY_FREE_SIZE
12083 if (old_size && (old_size + sizeof(struct malloc_obj_info)) != info->size) {
12084 const char *freeing = gc_freeing_obj_info();
12085 rb_bug("buffer %p realloced with old_size=%zu, but was allocated with size=%zu%s%s", ptr, old_size, info->size - sizeof(struct malloc_obj_info),
12086 freeing ? ", while freeing " : "", freeing ? freeing : "");
12087 }
12088#endif
12089 old_size = info->size;
12090 }
12091#endif
12092
12093 old_size = objspace_malloc_size(objspace, ptr, old_size);
12094 TRY_WITH_GC(new_size, mem = RB_GNUC_EXTENSION_BLOCK(realloc(ptr, new_size)));
12095 if (!mem) return mem;
12096 new_size = objspace_malloc_size(objspace, mem, new_size);
12097
12098#if CALC_EXACT_MALLOC_SIZE
12099 {
12100 struct malloc_obj_info *info = mem;
12101 info->size = new_size;
12102 mem = info + 1;
12103 }
12104#endif
12105
12106 objspace_malloc_increase(objspace, mem, new_size, old_size, MEMOP_TYPE_REALLOC, gc_allowed);
12107
12108 RB_DEBUG_COUNTER_INC(heap_xrealloc);
12109 return mem;
12110}
12111
12112void
12113rb_gc_impl_adjust_memory_usage(void *objspace_ptr, ssize_t diff)
12114{
12115 rb_objspace_t *objspace = objspace_ptr;
12116
12117 if (diff > 0) {
12118 objspace_malloc_increase(objspace, 0, diff, 0, MEMOP_TYPE_REALLOC, true);
12119 }
12120 else if (diff < 0) {
12121 objspace_malloc_increase(objspace, 0, 0, -diff, MEMOP_TYPE_REALLOC, true);
12122 }
12123}
12124
12125// TODO: move GC profiler stuff back into gc.c
12126/*
12127 ------------------------------ GC profiler ------------------------------
12128*/
12129
12130#define GC_PROFILE_RECORD_DEFAULT_SIZE 100
12131#define GC_PROFILE_RECORD_DEFAULT_MAX_RECORDS 4096
12132#define GC_PROFILE_RECORD_UNBOUNDED 0
12133
12134static bool
12135current_process_time(struct timespec *ts)
12136{
12137#if defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_PROCESS_CPUTIME_ID)
12138 {
12139 static int try_clock_gettime = 1;
12140 if (try_clock_gettime) {
12141 if (clock_gettime(CLOCK_PROCESS_CPUTIME_ID, ts) == 0) {
12142 return true;
12143 }
12144 else {
12145 try_clock_gettime = 0;
12146 }
12147 }
12148 }
12149#endif
12150
12151#ifdef RUSAGE_SELF
12152 {
12153 struct rusage usage;
12154 struct timeval time;
12155 if (getrusage(RUSAGE_SELF, &usage) == 0) {
12156 time = usage.ru_utime;
12157 ts->tv_sec = time.tv_sec;
12158 ts->tv_nsec = (int32_t)time.tv_usec * 1000;
12159 return true;
12160 }
12161 }
12162#endif
12163
12164#ifdef _WIN32
12165 {
12166 FILETIME creation_time, exit_time, kernel_time, user_time;
12167 ULARGE_INTEGER ui;
12168
12169 if (GetProcessTimes(GetCurrentProcess(),
12170 &creation_time, &exit_time, &kernel_time, &user_time) != 0) {
12171 memcpy(&ui, &user_time, sizeof(FILETIME));
12172#define PER100NSEC (uint64_t)(1000 * 1000 * 10)
12173 ts->tv_nsec = (long)(ui.QuadPart % PER100NSEC);
12174 ts->tv_sec = (time_t)(ui.QuadPart / PER100NSEC);
12175 return true;
12176 }
12177 }
12178#endif
12179
12180 return false;
12181}
12182
12183static double
12184getrusage_time(void)
12185{
12186 struct timespec ts;
12187 if (current_process_time(&ts)) {
12188 return ts.tv_sec + ts.tv_nsec * 1e-9;
12189 }
12190 else {
12191 return 0.0;
12192 }
12193}
12194
12195static inline double
12196hrtime_to_sec(rb_hrtime_t time)
12197{
12198 return (double)time / (double)RB_HRTIME_PER_SEC;
12199}
12200
12201static inline rb_hrtime_t
12202elapsed_hrtime_from(rb_hrtime_t start)
12203{
12204 return rb_hrtime_sub(rb_hrtime_now(), start);
12205}
12206
12207
12208static inline size_t
12209gc_profile_record_count(rb_objspace_t *objspace)
12210{
12211 return objspace->profile.record_count;
12212}
12213
12214static inline size_t
12215gc_profile_record_index(rb_objspace_t *objspace, size_t logical_index)
12216{
12217 if (objspace->profile.max_records != GC_PROFILE_RECORD_UNBOUNDED &&
12218 objspace->profile.record_count == objspace->profile.size) {
12219 return (objspace->profile.next_index + logical_index) % objspace->profile.size;
12220 }
12221 else {
12222 return logical_index;
12223 }
12224}
12225
12226static void
12227gc_profile_records_free(rb_objspace_t *objspace)
12228{
12229 void *p = objspace->profile.records;
12230 objspace->profile.records = NULL;
12231 objspace->profile.size = 0;
12232 objspace->profile.next_index = 0;
12233 objspace->profile.record_count = 0;
12234 objspace->profile.current_record = 0;
12235 free(p);
12236}
12237
12238static inline void
12239gc_prof_setup_new_record(rb_objspace_t *objspace, unsigned int reason)
12240{
12241 if (objspace->profile.run) {
12242 size_t index;
12243 gc_profile_record *record;
12244
12245 if (objspace->profile.max_records == GC_PROFILE_RECORD_UNBOUNDED) {
12246 index = objspace->profile.record_count++;
12247 objspace->profile.next_index = objspace->profile.record_count;
12248
12249 if (!objspace->profile.records) {
12250 objspace->profile.size = GC_PROFILE_RECORD_DEFAULT_SIZE;
12251 objspace->profile.records = malloc(xmalloc2_size(sizeof(gc_profile_record), objspace->profile.size));
12252 }
12253 if (index >= objspace->profile.size) {
12254 void *ptr;
12255 objspace->profile.size += 1000;
12256 ptr = realloc(objspace->profile.records, xmalloc2_size(sizeof(gc_profile_record), objspace->profile.size));
12257 if (!ptr) rb_memerror();
12258 objspace->profile.records = ptr;
12259 }
12260 }
12261 else {
12262 if (!objspace->profile.records) {
12263 objspace->profile.size = objspace->profile.max_records;
12264 objspace->profile.records = malloc(xmalloc2_size(sizeof(gc_profile_record), objspace->profile.size));
12265 }
12266 index = objspace->profile.next_index;
12267 objspace->profile.next_index = (objspace->profile.next_index + 1) % objspace->profile.size;
12268 if (objspace->profile.record_count < objspace->profile.size) {
12269 objspace->profile.record_count++;
12270 }
12271 }
12272
12273 if (!objspace->profile.records) {
12274 rb_bug("gc_profile malloc or realloc miss");
12275 }
12276 record = objspace->profile.current_record = &objspace->profile.records[index];
12277 MEMZERO(record, gc_profile_record, 1);
12278
12279 /* setup before-GC parameter */
12280 record->flags = reason | (ruby_gc_stressful ? GPR_FLAG_STRESS : 0);
12281 record->sequence = objspace->profile.record_sequence++;
12282 record->gc_invoke_wall_time = rb_hrtime_sub(rb_hrtime_now(),
12283 objspace->profile.invoke_wall_time);
12284#if MALLOC_ALLOCATED_SIZE
12285 record->allocated_size = malloc_allocated_size;
12286#endif
12287#if GC_PROFILE_MORE_DETAIL && GC_PROFILE_DETAIL_MEMORY
12288#ifdef RUSAGE_SELF
12289 {
12290 struct rusage usage;
12291 if (getrusage(RUSAGE_SELF, &usage) == 0) {
12292 record->maxrss = usage.ru_maxrss;
12293 record->minflt = usage.ru_minflt;
12294 record->majflt = usage.ru_majflt;
12295 }
12296 }
12297#endif
12298#endif
12299 }
12300}
12301
12302static inline void
12303gc_prof_timer_start(rb_objspace_t *objspace)
12304{
12305 if (gc_prof_enabled(objspace)) {
12306 gc_profile_record *record = gc_prof_record(objspace);
12307#if GC_PROFILE_MORE_DETAIL
12308 record->prepare_time = objspace->profile.prepare_time;
12309#endif
12310 record->gc_time = 0;
12311 record->gc_invoke_time = getrusage_time();
12312 objspace->profile.gc_wall_start_time = rb_hrtime_now();
12313 }
12314}
12315
12316static double
12317elapsed_time_from(double time)
12318{
12319 double now = getrusage_time();
12320 if (now > time) {
12321 return now - time;
12322 }
12323 else {
12324 return 0;
12325 }
12326}
12327
12328static inline void
12329gc_prof_timer_stop(rb_objspace_t *objspace)
12330{
12331 if (gc_prof_enabled(objspace)) {
12332 gc_profile_record *record = gc_prof_record(objspace);
12333 record->gc_time = elapsed_time_from(record->gc_invoke_time);
12334 record->gc_invoke_time -= objspace->profile.invoke_time;
12335 record->gc_wall_time = elapsed_hrtime_from(objspace->profile.gc_wall_start_time);
12336 }
12337}
12338
12339static inline void
12340gc_prof_mark_timer_start(rb_objspace_t *objspace)
12341{
12342 RUBY_DTRACE_GC_HOOK(MARK_BEGIN);
12343#if GC_PROFILE_MORE_DETAIL
12344 if (gc_prof_enabled(objspace)) {
12345 gc_prof_record(objspace)->gc_mark_time = getrusage_time();
12346 }
12347#endif
12348}
12349
12350static inline void
12351gc_prof_mark_timer_stop(rb_objspace_t *objspace)
12352{
12353 RUBY_DTRACE_GC_HOOK(MARK_END);
12354#if GC_PROFILE_MORE_DETAIL
12355 if (gc_prof_enabled(objspace)) {
12356 gc_profile_record *record = gc_prof_record(objspace);
12357 record->gc_mark_time = elapsed_time_from(record->gc_mark_time);
12358 }
12359#endif
12360}
12361
12362static inline void
12363gc_prof_sweep_timer_start(rb_objspace_t *objspace)
12364{
12365 RUBY_DTRACE_GC_HOOK(SWEEP_BEGIN);
12366 if (gc_prof_enabled(objspace)) {
12367 gc_profile_record *record = gc_prof_record(objspace);
12368
12369 if (record->gc_time > 0 || GC_PROFILE_MORE_DETAIL) {
12370 objspace->profile.gc_sweep_start_time = getrusage_time();
12371 objspace->profile.gc_sweep_wall_start_time = rb_hrtime_now();
12372 }
12373 }
12374}
12375
12376static inline void
12377gc_prof_sweep_timer_stop(rb_objspace_t *objspace)
12378{
12379 RUBY_DTRACE_GC_HOOK(SWEEP_END);
12380
12381 if (gc_prof_enabled(objspace)) {
12382 double sweep_time;
12383 gc_profile_record *record = gc_prof_record(objspace);
12384
12385 if (record->gc_time > 0) {
12386 sweep_time = elapsed_time_from(objspace->profile.gc_sweep_start_time);
12387 /* need to accumulate GC time for lazy sweep after gc() */
12388 record->gc_time += sweep_time;
12389 record->gc_wall_time = rb_hrtime_add(record->gc_wall_time,
12390 elapsed_hrtime_from(objspace->profile.gc_sweep_wall_start_time));
12391 }
12392 else if (GC_PROFILE_MORE_DETAIL) {
12393 sweep_time = elapsed_time_from(objspace->profile.gc_sweep_start_time);
12394 }
12395
12396#if GC_PROFILE_MORE_DETAIL
12397 record->gc_sweep_time += sweep_time;
12398 if (heap_pages_deferred_final) record->flags |= GPR_FLAG_HAVE_FINALIZE;
12399#endif
12400 if (heap_pages_deferred_final) objspace->profile.latest_gc_info |= GPR_FLAG_HAVE_FINALIZE;
12401 }
12402}
12403
12404static inline void
12405gc_prof_set_malloc_info(rb_objspace_t *objspace)
12406{
12407#if GC_PROFILE_MORE_DETAIL
12408 if (gc_prof_enabled(objspace)) {
12409 gc_profile_record *record = gc_prof_record(objspace);
12410 record->allocate_increase = malloc_increase;
12411 record->allocate_limit = malloc_limit;
12412 }
12413#endif
12414}
12415
12416static inline void
12417gc_prof_set_heap_info(rb_objspace_t *objspace)
12418{
12419 if (gc_prof_enabled(objspace)) {
12420 gc_profile_record *record = gc_prof_record(objspace);
12421
12422 /* Sum across all size pools since each has a different slot size. */
12423 size_t total = 0;
12424 size_t use_size = 0;
12425 size_t total_size = 0;
12426 for (int i = 0; i < HEAP_COUNT; i++) {
12427 rb_heap_t *heap = &heaps[i];
12428 size_t heap_live = heap->total_allocated_objects - heap->total_freed_objects - heap->final_slots_count;
12429 total += heap->total_slots;
12430 use_size += heap_live * heap->slot_size;
12431 total_size += heap->total_slots * heap->slot_size;
12432 }
12433
12434#if GC_PROFILE_MORE_DETAIL
12435 size_t live = objspace->profile.total_allocated_objects_at_gc_start - total_freed_objects(objspace);
12436 record->heap_use_pages = objspace->profile.heap_used_at_gc_start;
12437 record->heap_live_objects = live;
12438 record->heap_free_objects = total - live;
12439#endif
12440
12441 record->heap_total_objects = total;
12442 record->heap_use_size = use_size;
12443 record->heap_total_size = total_size;
12444 }
12445}
12446
12447/*
12448 * call-seq:
12449 * GC::Profiler.clear -> nil
12450 *
12451 * Clears the \GC profiler data.
12452 *
12453 */
12454
12455static VALUE
12456gc_profile_clear(VALUE _)
12457{
12458 rb_objspace_t *objspace = rb_gc_get_objspace();
12459 gc_profile_records_free(objspace);
12460 return Qnil;
12461}
12462
12463/*
12464 * call-seq:
12465 * GC::Profiler.configure(max_records: 4096) -> nil
12466 *
12467 * Configures how many raw profile records are retained by
12468 * GC::Profiler.raw_data.
12469 *
12470 * The profiler keeps at most +max_records+ records in a bounded ring buffer.
12471 * When the buffer is full, newer GC records overwrite the oldest retained
12472 * records. The default limit is 4096 records.
12473 *
12474 * Pass +nil+ to restore the historical unbounded behavior:
12475 *
12476 * GC::Profiler.configure(max_records: nil)
12477 *
12478 * Changing +max_records+ clears existing raw profile data. This method does
12479 * not enable or disable the profiler; use GC::Profiler.enable and
12480 * GC::Profiler.disable for that.
12481 */
12482
12483static VALUE
12484gc_profile_configure(int argc, VALUE *argv, VALUE _)
12485{
12486 static ID keywords[1] = {0};
12487 VALUE options, max_records;
12488 rb_objspace_t *objspace = rb_gc_get_objspace();
12489
12490 if (!keywords[0]) {
12491 keywords[0] = rb_intern("max_records");
12492 }
12493
12494 rb_scan_args_kw(rb_keyword_given_p(), argc, argv, ":", &options);
12495 rb_get_kwargs(options, keywords, 0, 1, &max_records);
12496
12497 if (max_records == Qundef) {
12498 return Qnil;
12499 }
12500 else if (NIL_P(max_records)) {
12501 objspace->profile.max_records = GC_PROFILE_RECORD_UNBOUNDED;
12502 }
12503 else {
12504 long value = NUM2LONG(max_records);
12505 if (value <= 0) {
12506 rb_raise(rb_eArgError, "max_records must be positive or nil");
12507 }
12508 objspace->profile.max_records = (size_t)value;
12509 }
12510
12511 gc_profile_records_free(objspace);
12512 return Qnil;
12513}
12514
12515/*
12516 * call-seq:
12517 * GC::Profiler.raw_data(limit: nil, since: nil) -> [Hash, ...]
12518 *
12519 * Returns an Array of retained raw profile data Hashes ordered from earliest
12520 * to latest by +:GC_INVOKE_TIME+. +limit:+ returns at most the newest
12521 * retained records. +since:+ returns records with +:GC_SEQUENCE+ greater
12522 * than the given sequence.
12523 *
12524 * For example:
12525 *
12526 * [
12527 * {
12528 * :GC_TIME=>1.3000000000000858e-05,
12529 * :GC_INVOKE_TIME=>0.010634999999999999,
12530 * :GC_WALL_TIME=>1.4000000000000001e-05,
12531 * :GC_INVOKE_WALL_TIME=>0.010640000000000000,
12532 * :GC_PAUSE_TIME=>1.5000000000000000e-05,
12533 * :GC_STOP_TIME=>1.0000000000000000e-06,
12534 * :GC_STW_TIME=>1.4000000000000001e-05,
12535 * :GC_MARK_WALL_TIME=>9.0000000000000002e-06,
12536 * :GC_SWEEP_WALL_TIME=>5.0000000000000004e-06,
12537 * :GC_COMPACT_WALL_TIME=>0.0000000000000000e+00,
12538 * :HEAP_USE_SIZE=>289640,
12539 * :HEAP_TOTAL_SIZE=>588960,
12540 * :HEAP_TOTAL_OBJECTS=>14724,
12541 * :GC_IS_MARKED=>false
12542 * },
12543 * # ...
12544 * ]
12545 *
12546 * The keys mean:
12547 *
12548 * +:GC_SEQUENCE+::
12549 * Monotonically increasing sequence number for this profiler record.
12550 * +:GC_TIME+::
12551 * CPU time elapsed in seconds for this GC run. This is process CPU time,
12552 * not elapsed wall-clock time.
12553 * +:GC_INVOKE_TIME+::
12554 * CPU time elapsed in seconds from startup to when the GC was invoked.
12555 * +:GC_WALL_TIME+::
12556 * Monotonic wall-clock counterpart to +:GC_TIME+ for this GC record.
12557 * This does not include time spent stopping other ractors before the VM
12558 * enters GC. Use the phase wall-clock fields below for mark, sweep, and
12559 * compaction attribution.
12560 * +:GC_INVOKE_WALL_TIME+::
12561 * Monotonic wall-clock time elapsed in seconds from startup to when the GC
12562 * was invoked.
12563 * +:GC_PAUSE_TIME+::
12564 * Monotonic wall-clock time elapsed in seconds while user execution was
12565 * blocked by this GC entry, including time to stop other ractors. This
12566 * may include time from incremental marking or lazy sweeping continuation
12567 * charged to this record.
12568 * +:GC_STOP_TIME+::
12569 * Monotonic wall-clock time elapsed in seconds stopping other ractors.
12570 * +:GC_STW_TIME+::
12571 * Monotonic wall-clock time elapsed in seconds after other ractors have
12572 * stopped and before the VM exits GC.
12573 * +:GC_MARK_WALL_TIME+::
12574 * Monotonic wall-clock time elapsed in seconds spent marking for this GC
12575 * record, accumulated across incremental marking continuations.
12576 * +:GC_SWEEP_WALL_TIME+::
12577 * Monotonic wall-clock time elapsed in seconds spent sweeping for this GC
12578 * record, accumulated across lazy sweeping continuations. This does not
12579 * include compaction time, which is reported separately as
12580 * +:GC_COMPACT_WALL_TIME+.
12581 * +:GC_COMPACT_WALL_TIME+::
12582 * Monotonic wall-clock time elapsed in seconds spent compacting for this GC
12583 * record, or +0.0+ if this GC did not compact.
12584 * +:HEAP_USE_SIZE+::
12585 * Total bytes of heap used
12586 * +:HEAP_TOTAL_SIZE+::
12587 * Total size of heap in bytes
12588 * +:HEAP_TOTAL_OBJECTS+::
12589 * Total number of objects
12590 * +:GC_IS_MARKED+::
12591 * Returns +true+ if the GC is in mark phase
12592 *
12593 * The wall-clock timing fields relate to each other as follows:
12594 *
12595 * GC_PAUSE_TIME == GC_STOP_TIME + GC_STW_TIME
12596 *
12597 * +:GC_MARK_WALL_TIME+, +:GC_SWEEP_WALL_TIME+, and +:GC_COMPACT_WALL_TIME+
12598 * report separate phase timings and must not be added to +:GC_WALL_TIME+.
12599 *
12600 * +:GC_WALL_TIME+ is the wall-clock counterpart to +:GC_TIME+ and is nested
12601 * inside +:GC_STW_TIME+, so it must not be added to +:GC_STW_TIME+. The difference
12602 * +GC_STW_TIME - GC_WALL_TIME+ is VM overhead inside the stopped interval
12603 * (GC event hooks, bookkeeping, consistency checks, and continuation work).
12604 *
12605 * If ruby was built with +GC_PROFILE_MORE_DETAIL+, you will also have access
12606 * to the following hash keys:
12607 *
12608 * +:GC_MARK_TIME+::
12609 * +:GC_SWEEP_TIME+::
12610 * +:ALLOCATE_INCREASE+::
12611 * +:ALLOCATE_LIMIT+::
12612 * +:HEAP_USE_PAGES+::
12613 * +:HEAP_LIVE_OBJECTS+::
12614 * +:HEAP_FREE_OBJECTS+::
12615 * +:HAVE_FINALIZE+::
12616 *
12617 */
12618
12619static VALUE
12620gc_profile_record_get(int argc, VALUE *argv, VALUE _)
12621{
12622 static ID keywords[2] = {0};
12623 VALUE prof, options, limit_value, since_value;
12624 VALUE gc_profile = rb_ary_new();
12625 size_t i, count, matching = 0, skip = 0, limit = SIZE_MAX, since = 0;
12626 bool use_since = false;
12627 rb_objspace_t *objspace = rb_gc_get_objspace();
12628
12629 if (!keywords[0]) {
12630 keywords[0] = rb_intern("limit");
12631 keywords[1] = rb_intern("since");
12632 }
12633
12634 rb_scan_args_kw(rb_keyword_given_p(), argc, argv, ":", &options);
12635 VALUE values[2] = {Qundef, Qundef};
12636 rb_get_kwargs(options, keywords, 0, 2, values);
12637 limit_value = values[0];
12638 since_value = values[1];
12639
12640 if (limit_value != Qundef && !NIL_P(limit_value)) {
12641 long value = NUM2LONG(limit_value);
12642 if (value < 0) {
12643 rb_raise(rb_eArgError, "limit must be non-negative");
12644 }
12645 limit = (size_t)value;
12646 }
12647 if (since_value != Qundef && !NIL_P(since_value)) {
12648 long value = NUM2LONG(since_value);
12649 if (value < 0) {
12650 rb_raise(rb_eArgError, "since must be non-negative");
12651 }
12652 since = (size_t)value;
12653 use_since = true;
12654 }
12655
12656 if (!objspace->profile.run) {
12657 return Qnil;
12658 }
12659
12660 count = gc_profile_record_count(objspace);
12661 for (i = 0; i < count; i++) {
12662 gc_profile_record *record = &objspace->profile.records[gc_profile_record_index(objspace, i)];
12663 if (!use_since || record->sequence > since) {
12664 matching++;
12665 }
12666 }
12667 if (limit < matching) {
12668 skip = matching - limit;
12669 }
12670
12671 for (i = 0; i < count; i++) {
12672 gc_profile_record *record = &objspace->profile.records[gc_profile_record_index(objspace, i)];
12673 if (use_since && record->sequence <= since) {
12674 continue;
12675 }
12676 if (skip > 0) {
12677 skip--;
12678 continue;
12679 }
12680
12681 prof = rb_hash_new();
12682 rb_hash_aset(prof, ID2SYM(rb_intern("GC_FLAGS")), gc_info_decode(objspace, rb_hash_new(), record->flags));
12683 rb_hash_aset(prof, ID2SYM(rb_intern("GC_SEQUENCE")), SIZET2NUM(record->sequence));
12684 rb_hash_aset(prof, ID2SYM(rb_intern("GC_TIME")), DBL2NUM(record->gc_time));
12685 rb_hash_aset(prof, ID2SYM(rb_intern("GC_INVOKE_TIME")), DBL2NUM(record->gc_invoke_time));
12686 rb_hash_aset(prof, ID2SYM(rb_intern("GC_WALL_TIME")),
12687 DBL2NUM(hrtime_to_sec(record->gc_wall_time)));
12688 rb_hash_aset(prof, ID2SYM(rb_intern("GC_INVOKE_WALL_TIME")),
12689 DBL2NUM(hrtime_to_sec(record->gc_invoke_wall_time)));
12690 rb_hash_aset(prof, ID2SYM(rb_intern("GC_PAUSE_TIME")),
12691 DBL2NUM(hrtime_to_sec(record->gc_pause_time)));
12692 rb_hash_aset(prof, ID2SYM(rb_intern("GC_STOP_TIME")),
12693 DBL2NUM(hrtime_to_sec(record->gc_stop_time)));
12694 rb_hash_aset(prof, ID2SYM(rb_intern("GC_STW_TIME")),
12695 DBL2NUM(hrtime_to_sec(record->gc_stw_time)));
12696 rb_hash_aset(prof, ID2SYM(rb_intern("GC_MARK_WALL_TIME")),
12697 DBL2NUM(hrtime_to_sec(record->gc_mark_wall_time)));
12698 rb_hash_aset(prof, ID2SYM(rb_intern("GC_SWEEP_WALL_TIME")),
12699 DBL2NUM(hrtime_to_sec(record->gc_sweep_wall_time)));
12700 rb_hash_aset(prof, ID2SYM(rb_intern("GC_COMPACT_WALL_TIME")),
12701 DBL2NUM(hrtime_to_sec(record->gc_compact_wall_time)));
12702 rb_hash_aset(prof, ID2SYM(rb_intern("HEAP_USE_SIZE")), SIZET2NUM(record->heap_use_size));
12703 rb_hash_aset(prof, ID2SYM(rb_intern("HEAP_TOTAL_SIZE")), SIZET2NUM(record->heap_total_size));
12704 rb_hash_aset(prof, ID2SYM(rb_intern("HEAP_TOTAL_OBJECTS")), SIZET2NUM(record->heap_total_objects));
12705 rb_hash_aset(prof, ID2SYM(rb_intern("MOVED_OBJECTS")), SIZET2NUM(record->moved_objects));
12706 rb_hash_aset(prof, ID2SYM(rb_intern("GC_IS_MARKED")), Qtrue);
12707#if GC_PROFILE_MORE_DETAIL
12708 rb_hash_aset(prof, ID2SYM(rb_intern("GC_MARK_TIME")), DBL2NUM(record->gc_mark_time));
12709 rb_hash_aset(prof, ID2SYM(rb_intern("GC_SWEEP_TIME")), DBL2NUM(record->gc_sweep_time));
12710 rb_hash_aset(prof, ID2SYM(rb_intern("ALLOCATE_INCREASE")), SIZET2NUM(record->allocate_increase));
12711 rb_hash_aset(prof, ID2SYM(rb_intern("ALLOCATE_LIMIT")), SIZET2NUM(record->allocate_limit));
12712 rb_hash_aset(prof, ID2SYM(rb_intern("HEAP_USE_PAGES")), SIZET2NUM(record->heap_use_pages));
12713 rb_hash_aset(prof, ID2SYM(rb_intern("HEAP_LIVE_OBJECTS")), SIZET2NUM(record->heap_live_objects));
12714 rb_hash_aset(prof, ID2SYM(rb_intern("HEAP_FREE_OBJECTS")), SIZET2NUM(record->heap_free_objects));
12715
12716 rb_hash_aset(prof, ID2SYM(rb_intern("REMOVING_OBJECTS")), SIZET2NUM(record->removing_objects));
12717 rb_hash_aset(prof, ID2SYM(rb_intern("EMPTY_OBJECTS")), SIZET2NUM(record->empty_objects));
12718
12719 rb_hash_aset(prof, ID2SYM(rb_intern("HAVE_FINALIZE")), (record->flags & GPR_FLAG_HAVE_FINALIZE) ? Qtrue : Qfalse);
12720#endif
12721
12722#if RGENGC_PROFILE > 0
12723 rb_hash_aset(prof, ID2SYM(rb_intern("OLD_OBJECTS")), SIZET2NUM(record->old_objects));
12724 rb_hash_aset(prof, ID2SYM(rb_intern("REMEMBERED_NORMAL_OBJECTS")), SIZET2NUM(record->remembered_normal_objects));
12725 rb_hash_aset(prof, ID2SYM(rb_intern("REMEMBERED_SHADY_OBJECTS")), SIZET2NUM(record->remembered_shady_objects));
12726#endif
12727 rb_ary_push(gc_profile, prof);
12728 }
12729
12730 return gc_profile;
12731}
12732
12733#if GC_PROFILE_MORE_DETAIL
12734#define MAJOR_REASON_MAX 0x10
12735
12736static char *
12737gc_profile_dump_major_reason(unsigned int flags, char *buff)
12738{
12739 unsigned int reason = flags & GPR_FLAG_MAJOR_MASK;
12740 int i = 0;
12741
12742 if (reason == GPR_FLAG_NONE) {
12743 buff[0] = '-';
12744 buff[1] = 0;
12745 }
12746 else {
12747#define C(x, s) \
12748 if (reason & GPR_FLAG_MAJOR_BY_##x) { \
12749 buff[i++] = #x[0]; \
12750 if (i >= MAJOR_REASON_MAX) rb_bug("gc_profile_dump_major_reason: overflow"); \
12751 buff[i] = 0; \
12752 }
12753 C(NOFREE, N);
12754 C(OLDGEN, O);
12755 C(SHADY, S);
12756#if RGENGC_ESTIMATE_OLDMALLOC
12757 C(OLDMALLOC, M);
12758#endif
12759#undef C
12760 }
12761 return buff;
12762}
12763#endif
12764
12765
12766
12767static void
12768gc_profile_dump_on(VALUE out, VALUE (*append)(VALUE, VALUE))
12769{
12770 rb_objspace_t *objspace = rb_gc_get_objspace();
12771 size_t count = gc_profile_record_count(objspace);
12772#ifdef MAJOR_REASON_MAX
12773 char reason_str[MAJOR_REASON_MAX];
12774#endif
12775
12776 if (objspace->profile.run && count /* > 1 */) {
12777 size_t i;
12778 const gc_profile_record *record;
12779
12780 append(out, rb_sprintf("GC %"PRIuSIZE" invokes.\n", objspace->profile.count));
12781 append(out, rb_str_new_cstr("Index Invoke Time(sec) Use Size(byte) Total Size(byte) Total Object GC Time(ms)\n"));
12782
12783 for (i = 0; i < count; i++) {
12784 record = &objspace->profile.records[gc_profile_record_index(objspace, i)];
12785 append(out, rb_sprintf("%5"PRIuSIZE" %19.3f %20"PRIuSIZE" %20"PRIuSIZE" %20"PRIuSIZE" %30.20f\n",
12786 i+1, record->gc_invoke_time, record->heap_use_size,
12787 record->heap_total_size, record->heap_total_objects, record->gc_time*1000));
12788 }
12789
12790#if GC_PROFILE_MORE_DETAIL
12791 const char *str = "\n\n" \
12792 "More detail.\n" \
12793 "Prepare Time = Previously GC's rest sweep time\n"
12794 "Index Flags Allocate Inc. Allocate Limit"
12795#if CALC_EXACT_MALLOC_SIZE
12796 " Allocated Size"
12797#endif
12798 " Use Page Mark Time(ms) Sweep Time(ms) Prepare Time(ms) LivingObj FreeObj RemovedObj EmptyObj"
12799#if RGENGC_PROFILE
12800 " OldgenObj RemNormObj RemShadObj"
12801#endif
12802#if GC_PROFILE_DETAIL_MEMORY
12803 " MaxRSS(KB) MinorFLT MajorFLT"
12804#endif
12805 "\n";
12806 append(out, rb_str_new_cstr(str));
12807
12808 for (i = 0; i < count; i++) {
12809 record = &objspace->profile.records[gc_profile_record_index(objspace, i)];
12810 append(out, rb_sprintf("%5"PRIuSIZE" %4s/%c/%6s%c %13"PRIuSIZE" %15"PRIuSIZE
12811#if CALC_EXACT_MALLOC_SIZE
12812 " %15"PRIuSIZE
12813#endif
12814 " %9"PRIuSIZE" %17.12f %17.12f %17.12f %10"PRIuSIZE" %10"PRIuSIZE" %10"PRIuSIZE" %10"PRIuSIZE
12815#if RGENGC_PROFILE
12816 "%10"PRIuSIZE" %10"PRIuSIZE" %10"PRIuSIZE
12817#endif
12818#if GC_PROFILE_DETAIL_MEMORY
12819 "%11ld %8ld %8ld"
12820#endif
12821
12822 "\n",
12823 i+1,
12824 gc_profile_dump_major_reason(record->flags, reason_str),
12825 (record->flags & GPR_FLAG_HAVE_FINALIZE) ? 'F' : '.',
12826 (record->flags & GPR_FLAG_NEWOBJ) ? "NEWOBJ" :
12827 (record->flags & GPR_FLAG_MALLOC) ? "MALLOC" :
12828 (record->flags & GPR_FLAG_METHOD) ? "METHOD" :
12829 (record->flags & GPR_FLAG_CAPI) ? "CAPI__" : "??????",
12830 (record->flags & GPR_FLAG_STRESS) ? '!' : ' ',
12831 record->allocate_increase, record->allocate_limit,
12832#if CALC_EXACT_MALLOC_SIZE
12833 record->allocated_size,
12834#endif
12835 record->heap_use_pages,
12836 record->gc_mark_time*1000,
12837 record->gc_sweep_time*1000,
12838 record->prepare_time*1000,
12839
12840 record->heap_live_objects,
12841 record->heap_free_objects,
12842 record->removing_objects,
12843 record->empty_objects
12844#if RGENGC_PROFILE
12845 ,
12846 record->old_objects,
12847 record->remembered_normal_objects,
12848 record->remembered_shady_objects
12849#endif
12850#if GC_PROFILE_DETAIL_MEMORY
12851 ,
12852 record->maxrss / 1024,
12853 record->minflt,
12854 record->majflt
12855#endif
12856
12857 ));
12858 }
12859#endif
12860 }
12861}
12862
12863/*
12864 * call-seq:
12865 * GC::Profiler.result -> String
12866 *
12867 * Returns a profile data report such as:
12868 *
12869 * GC 1 invokes.
12870 * Index Invoke Time(sec) Use Size(byte) Total Size(byte) Total Object GC time(ms)
12871 * 1 0.012 159240 212940 10647 0.00000000000001530000
12872 */
12873
12874static VALUE
12875gc_profile_result(VALUE _)
12876{
12877 VALUE str = rb_str_buf_new(0);
12878 gc_profile_dump_on(str, rb_str_buf_append);
12879 return str;
12880}
12881
12882/*
12883 * call-seq:
12884 * GC::Profiler.report
12885 * GC::Profiler.report(io)
12886 *
12887 * Writes the GC::Profiler.result to <tt>$stdout</tt> or the given IO object.
12888 *
12889 */
12890
12891static VALUE
12892gc_profile_report(int argc, VALUE *argv, VALUE self)
12893{
12894 VALUE out;
12895
12896 out = (!rb_check_arity(argc, 0, 1) ? rb_stdout : argv[0]);
12897 gc_profile_dump_on(out, rb_io_write);
12898
12899 return Qnil;
12900}
12901
12902/*
12903 * call-seq:
12904 * GC::Profiler.total_time -> float
12905 *
12906 * The total time used for garbage collection in seconds
12907 */
12908
12909static VALUE
12910gc_profile_total_time(VALUE self)
12911{
12912 double time = 0;
12913 rb_objspace_t *objspace = rb_gc_get_objspace();
12914
12915 if (objspace->profile.run && gc_profile_record_count(objspace) > 0) {
12916 size_t i;
12917 size_t count = gc_profile_record_count(objspace);
12918
12919 for (i = 0; i < count; i++) {
12920 time += objspace->profile.records[gc_profile_record_index(objspace, i)].gc_time;
12921 }
12922 }
12923 return DBL2NUM(time);
12924}
12925
12926/*
12927 * call-seq:
12928 * GC::Profiler.enabled? -> true or false
12929 *
12930 * The current status of \GC profile mode.
12931 */
12932
12933static VALUE
12934gc_profile_enable_get(VALUE self)
12935{
12936 rb_objspace_t *objspace = rb_gc_get_objspace();
12937 return objspace->profile.run ? Qtrue : Qfalse;
12938}
12939
12940/*
12941 * call-seq:
12942 * GC::Profiler.enable -> nil
12943 *
12944 * Starts the \GC profiler.
12945 *
12946 */
12947
12948static VALUE
12949gc_profile_enable(VALUE _)
12950{
12951 rb_objspace_t *objspace = rb_gc_get_objspace();
12952 objspace->profile.run = TRUE;
12953 objspace->profile.current_record = 0;
12954 return Qnil;
12955}
12956
12957/*
12958 * call-seq:
12959 * GC::Profiler.disable -> nil
12960 *
12961 * Stops the \GC profiler.
12962 *
12963 */
12964
12965static VALUE
12966gc_profile_disable(VALUE _)
12967{
12968 rb_objspace_t *objspace = rb_gc_get_objspace();
12969
12970 objspace->profile.run = FALSE;
12971 objspace->profile.current_record = 0;
12972 return Qnil;
12973}
12974
12975static void
12976rb_gc_verify_internal_consistency(void)
12977{
12978 gc_verify_internal_consistency(rb_gc_get_objspace());
12979}
12980
12981/*
12982 * call-seq:
12983 * GC.verify_internal_consistency -> nil
12984 *
12985 * Verifies internal consistency of the GC.
12986 * This method should only be used for debugging.
12987 *
12988 * This method is only expected to work on CRuby.
12989 */
12990static VALUE
12991gc_verify_internal_consistency_m(VALUE dummy)
12992{
12993 rb_gc_verify_internal_consistency();
12994 return Qnil;
12995}
12996
12997#if GC_CAN_COMPILE_COMPACTION
12998/*
12999 * call-seq:
13000 * GC.auto_compact = flag
13001 *
13002 * Updates automatic compaction mode.
13003 *
13004 * When enabled, the compactor will execute on every major collection.
13005 *
13006 * Enabling compaction will degrade performance on major collections.
13007 */
13008static VALUE
13009gc_set_auto_compact(VALUE _, VALUE v)
13010{
13011 GC_ASSERT(GC_COMPACTION_SUPPORTED);
13012
13013 ruby_enable_autocompact = RTEST(v);
13014
13015#if RGENGC_CHECK_MODE
13016 ruby_autocompact_compare_func = NULL;
13017
13018 if (SYMBOL_P(v)) {
13019 ID id = RB_SYM2ID(v);
13020 if (id == rb_intern("empty")) {
13021 ruby_autocompact_compare_func = compare_free_slots;
13022 }
13023 }
13024#endif
13025
13026 return v;
13027}
13028#else
13029# define gc_set_auto_compact rb_f_notimplement
13030#endif
13031
13032#if GC_CAN_COMPILE_COMPACTION
13033/*
13034 * call-seq:
13035 * GC.auto_compact -> true or false
13036 *
13037 * Returns whether or not automatic compaction has been enabled.
13038 */
13039static VALUE
13040gc_get_auto_compact(VALUE _)
13041{
13042 return ruby_enable_autocompact ? Qtrue : Qfalse;
13043}
13044#else
13045# define gc_get_auto_compact rb_f_notimplement
13046#endif
13047
13048#if GC_CAN_COMPILE_COMPACTION
13049/*
13050 * call-seq:
13051 * GC.latest_compact_info -> hash
13052 *
13053 * Returns information about object moved in the most recent \GC compaction.
13054 *
13055 * The returned +hash+ contains the following keys:
13056 *
13057 * [considered]
13058 * Hash containing the type of the object as the key and the number of
13059 * objects of that type that were considered for movement.
13060 * [moved]
13061 * Hash containing the type of the object as the key and the number of
13062 * objects of that type that were actually moved.
13063 * [moved_up]
13064 * Hash containing the type of the object as the key and the number of
13065 * objects of that type that were increased in size.
13066 * [moved_down]
13067 * Hash containing the type of the object as the key and the number of
13068 * objects of that type that were decreased in size.
13069 *
13070 * Some objects can't be moved (due to pinning) so these numbers can be used to
13071 * calculate compaction efficiency.
13072 */
13073static VALUE
13074gc_compact_stats(VALUE self)
13075{
13076 rb_objspace_t *objspace = rb_gc_get_objspace();
13077 VALUE h = rb_hash_new();
13078 VALUE considered = rb_hash_new();
13079 VALUE moved = rb_hash_new();
13080 VALUE moved_up = rb_hash_new();
13081 VALUE moved_down = rb_hash_new();
13082
13083 for (size_t i = 0; i < T_MASK; i++) {
13084 if (objspace->rcompactor.considered_count_table[i]) {
13085 rb_hash_aset(considered, type_sym(i), SIZET2NUM(objspace->rcompactor.considered_count_table[i]));
13086 }
13087
13088 if (objspace->rcompactor.moved_count_table[i]) {
13089 rb_hash_aset(moved, type_sym(i), SIZET2NUM(objspace->rcompactor.moved_count_table[i]));
13090 }
13091
13092 if (objspace->rcompactor.moved_up_count_table[i]) {
13093 rb_hash_aset(moved_up, type_sym(i), SIZET2NUM(objspace->rcompactor.moved_up_count_table[i]));
13094 }
13095
13096 if (objspace->rcompactor.moved_down_count_table[i]) {
13097 rb_hash_aset(moved_down, type_sym(i), SIZET2NUM(objspace->rcompactor.moved_down_count_table[i]));
13098 }
13099 }
13100
13101 rb_hash_aset(h, ID2SYM(rb_intern("considered")), considered);
13102 rb_hash_aset(h, ID2SYM(rb_intern("moved")), moved);
13103 rb_hash_aset(h, ID2SYM(rb_intern("moved_up")), moved_up);
13104 rb_hash_aset(h, ID2SYM(rb_intern("moved_down")), moved_down);
13105
13106 return h;
13107}
13108#else
13109# define gc_compact_stats rb_f_notimplement
13110#endif
13111
13112#if GC_CAN_COMPILE_COMPACTION
13113/*
13114 * call-seq:
13115 * GC.compact -> hash
13116 *
13117 * This function compacts objects together in Ruby's heap. It eliminates
13118 * unused space (or fragmentation) in the heap by moving objects in to that
13119 * unused space. If there is more than 1 running Ractor, it runs a global
13120 * GC compaction (all object spaces).
13121 *
13122 * The returned +hash+ contains statistics about the objects that were moved;
13123 * see GC.latest_compact_info.
13124 *
13125 * This method is only expected to work on CRuby.
13126 *
13127 * To test whether \GC compaction is supported, use the idiom:
13128 *
13129 * GC.respond_to?(:compact)
13130 */
13131static VALUE
13132gc_compact(VALUE self)
13133{
13134 rb_objspace_t *objspace = rb_gc_get_objspace();
13135 int full_marking_p = gc_config_full_mark_val;
13136 gc_config_full_mark_set(TRUE);
13137
13138 /* Run GC with compaction enabled */
13139 rb_gc_impl_start(rb_gc_get_objspace(), true, true, true, true, true);
13140 gc_config_full_mark_set(full_marking_p);
13141
13142 return gc_compact_stats(self);
13143}
13144#else
13145# define gc_compact rb_f_notimplement
13146#endif
13147
13148#if GC_CAN_COMPILE_COMPACTION
13149struct desired_compaction_pages_i_data {
13151 size_t required_slots[HEAP_COUNT];
13152};
13153
13154static int
13155desired_compaction_pages_i(struct heap_page *page, void *data)
13156{
13157 struct desired_compaction_pages_i_data *tdata = data;
13158 rb_objspace_t *objspace = tdata->objspace;
13159 VALUE vstart = (VALUE)page->start;
13160 VALUE vend = vstart + (VALUE)(page->total_slots * page->heap->slot_size);
13161
13162
13163 for (VALUE v = vstart; v != vend; v += page->heap->slot_size) {
13164 asan_unpoisoning_object(v) {
13165 /* skip T_NONEs; they won't be moved */
13166 if (BUILTIN_TYPE(v) != T_NONE) {
13167 rb_heap_t *dest_pool = gc_compact_destination_pool(objspace, page->heap, v);
13168 size_t dest_pool_idx = dest_pool - heaps;
13169 tdata->required_slots[dest_pool_idx]++;
13170 }
13171 }
13172 }
13173
13174 return 0;
13175}
13176
13177/* call-seq:
13178 * GC.verify_compaction_references(toward: nil, double_heap: false) -> hash
13179 *
13180 * Verify compaction reference consistency.
13181 *
13182 * This method is implementation specific. During compaction, objects that
13183 * were moved are replaced with T_MOVED objects. No object should have a
13184 * reference to a T_MOVED object after compaction.
13185 *
13186 * This function expands the heap to ensure room to move all objects,
13187 * compacts the heap to make sure everything moves, updates all references,
13188 * then performs a full \GC. If any object contains a reference to a T_MOVED
13189 * object, that object should be pushed on the mark stack, and will
13190 * make a SEGV.
13191 */
13192static VALUE
13193gc_verify_compaction_references(int argc, VALUE* argv, VALUE self)
13194{
13195 static ID keywords[3] = {0};
13196 if (!keywords[0]) {
13197 keywords[0] = rb_intern("toward");
13198 keywords[1] = rb_intern("double_heap");
13199 keywords[2] = rb_intern("expand_heap");
13200 }
13201
13202 VALUE options;
13203 rb_scan_args_kw(rb_keyword_given_p(), argc, argv, ":", &options);
13204
13205 VALUE arguments[3] = { Qnil, Qfalse, Qfalse };
13206 int kwarg_count = rb_get_kwargs(options, keywords, 0, 3, arguments);
13207 bool toward_empty = kwarg_count > 0 && SYMBOL_P(arguments[0]) && SYM2ID(arguments[0]) == rb_intern("empty");
13208 bool expand_heap = (kwarg_count > 1 && RTEST(arguments[1])) || (kwarg_count > 2 && RTEST(arguments[2]));
13209
13210 rb_objspace_t *objspace = rb_gc_get_objspace();
13211
13212 /* This verification machinery (heap expansion, toward_empty page ordering, the
13213 * moved-reference walk) is built for a single objspace, so with several demote it
13214 * to a plain full GC. Plain GC.compact does compact them via the global GC. */
13215 if (!rb_gc_single_objspace_p()) {
13216 rb_gc_impl_start(objspace, true, true, true, false, false);
13217 return gc_compact_stats(self);
13218 }
13219
13220 /* Clear the heap. */
13221 rb_gc_impl_start(objspace, true, true, true, false, false);
13222
13223 unsigned int lev = RB_GC_VM_LOCK();
13224 {
13225 gc_rest(objspace);
13226
13227 /* if both double_heap and expand_heap are set, expand_heap takes precedence */
13228 if (expand_heap) {
13229 struct desired_compaction_pages_i_data desired_compaction = {
13230 .objspace = objspace,
13231 .required_slots = {0},
13232 };
13233 /* Work out how many objects want to be in each size pool, taking account of moves */
13234 objspace_each_pages(objspace, desired_compaction_pages_i, &desired_compaction, TRUE);
13235
13236 /* Find out which pool has the most pages */
13237 size_t max_existing_pages = 0;
13238 for (int i = 0; i < HEAP_COUNT; i++) {
13239 rb_heap_t *heap = &heaps[i];
13240 max_existing_pages = MAX(max_existing_pages, heap->total_pages);
13241 }
13242
13243 /* Add pages to each size pool so that compaction is guaranteed to move every object */
13244 for (int i = 0; i < HEAP_COUNT; i++) {
13245 rb_heap_t *heap = &heaps[i];
13246
13247 size_t pages_to_add = 0;
13248 /*
13249 * Step 1: Make sure every pool has the same number of pages, by adding empty pages
13250 * to smaller pools. This is required to make sure the compact cursor can advance
13251 * through all of the pools in `gc_sweep_compact` without hitting the "sweep &
13252 * compact cursors met" condition on some pools before fully compacting others
13253 */
13254 pages_to_add += max_existing_pages - heap->total_pages;
13255 /*
13256 * Step 2: Now add additional free pages to each size pool sufficient to hold all objects
13257 * that want to be in that size pool, whether moved into it or moved within it
13258 */
13259 objspace->heap_pages.allocatable_bytes = desired_compaction.required_slots[i] * heap->slot_size;
13260 while (objspace->heap_pages.allocatable_bytes > 0) {
13261 heap_page_allocate_and_initialize(objspace, heap);
13262 }
13263 /*
13264 * Step 3: Add two more pages so that the compact & sweep cursors will meet _after_ all objects
13265 * have been moved, and not on the last iteration of the `gc_sweep_compact` loop
13266 */
13267 pages_to_add += 2;
13268
13269 for (; pages_to_add > 0; pages_to_add--) {
13270 heap_page_allocate_and_initialize_force(objspace, heap);
13271 }
13272 }
13273 }
13274
13275 if (toward_empty) {
13276 objspace->rcompactor.compare_func = compare_free_slots;
13277 }
13278 }
13279 RB_GC_VM_UNLOCK(lev);
13280
13281 rb_gc_impl_start(rb_gc_get_objspace(), true, true, true, true, false);
13282
13283 rb_objspace_reachable_objects_from_root(root_obj_check_moved_i, objspace);
13284 objspace_each_objects(objspace, heap_check_moved_i, objspace, TRUE);
13285
13286 objspace->rcompactor.compare_func = NULL;
13287
13288 return gc_compact_stats(self);
13289}
13290#else
13291# define gc_verify_compaction_references rb_f_notimplement
13292#endif
13293
13294void
13295rb_gc_impl_objspace_free(void *objspace_ptr)
13296{
13297 rb_objspace_t *objspace = objspace_ptr;
13298
13299 if (is_lazy_sweeping(objspace))
13300 rb_bug("lazy sweeping underway when freeing object space");
13301
13302 free(objspace->profile.records);
13303 objspace->profile.records = NULL;
13304
13305 for (size_t i = 0; i < rb_darray_size(objspace->heap_pages.sorted); i++) {
13306 heap_page_free(objspace, rb_darray_get(objspace->heap_pages.sorted, i));
13307 }
13308 rb_darray_free_without_gc(objspace->heap_pages.sorted);
13309 heap_pages_lomem = 0;
13310 heap_pages_himem = 0;
13311
13312 for (int i = 0; i < HEAP_COUNT; i++) {
13313 rb_heap_t *heap = &heaps[i];
13314 heap->total_pages = 0;
13315 heap->total_slots = 0;
13316 }
13317
13318 free_stack_chunks(&objspace->mark_stack);
13319 mark_stack_free_cache(&objspace->mark_stack);
13320
13321 rb_darray_free_without_gc(objspace->weak_references);
13322
13323#ifdef MALLOC_COUNTERS_NEED_LOCK
13324 rb_native_mutex_destroy(&objspace->malloc_counters.lock);
13325#endif
13326
13327 rb_native_mutex_destroy(&objspace->process_stat.lock);
13328
13329 free(objspace);
13330}
13331
13332#if MALLOC_ALLOCATED_SIZE
13333/*
13334 * call-seq:
13335 * GC.malloc_allocated_size -> Integer
13336 *
13337 * Returns the size of memory allocated by malloc().
13338 *
13339 * Only available if ruby was built with +CALC_EXACT_MALLOC_SIZE+.
13340 */
13341
13342static VALUE
13343gc_malloc_allocated_size(VALUE self)
13344{
13345 rb_objspace_t *objspace = (rb_objspace_t *)rb_gc_get_objspace();
13346 return ULL2NUM(objspace->malloc_params.allocated_size);
13347}
13348
13349/*
13350 * call-seq:
13351 * GC.malloc_allocations -> Integer
13352 *
13353 * Returns the number of malloc() allocations.
13354 *
13355 * Only available if ruby was built with +CALC_EXACT_MALLOC_SIZE+.
13356 */
13357
13358static VALUE
13359gc_malloc_allocations(VALUE self)
13360{
13361 rb_objspace_t *objspace = (rb_objspace_t *)rb_gc_get_objspace();
13362 return ULL2NUM(objspace->malloc_params.allocations);
13363}
13364#endif
13365
13366void
13367rb_gc_impl_before_fork(void *objspace_ptr)
13368{
13369 rb_objspace_t *objspace = objspace_ptr;
13370
13371 objspace->fork_vm_lock_lev = RB_GC_VM_LOCK();
13372 rb_gc_vm_barrier();
13373}
13374
13375void
13376rb_gc_impl_after_fork(void *objspace_ptr, rb_pid_t pid)
13377{
13378 rb_objspace_t *objspace = objspace_ptr;
13379
13380 if (pid == 0) {
13381 rb_gc_vm_each_objspace(gc_process_stat_after_fork_i, NULL);
13382 }
13383
13384 RB_GC_VM_UNLOCK(objspace->fork_vm_lock_lev);
13385 objspace->fork_vm_lock_lev = 0;
13386
13387 if (pid == 0) { /* child process */
13388 heap_alloc_state_clear(objspace);
13389 /* The forking Ractor becomes the child process's main Ractor. */
13390 global_objspace->main_objspace = objspace;
13391 page_pool_lock_initialize(&rb_global_objspace_instance.page_pool.lock);
13392 }
13393}
13394
13395VALUE rb_ident_hash_new_capa(rb_len_t size);
13396
13397#if GC_DEBUG_STRESS_TO_CLASS
13398/*
13399 * call-seq:
13400 * GC.add_stress_to_class(class[, ...])
13401 *
13402 * Raises NoMemoryError when allocating an instance of the given classes.
13403 *
13404 */
13405static VALUE
13406rb_gcdebug_add_stress_to_class(int argc, VALUE *argv, VALUE self)
13407{
13408 rb_objspace_t *objspace = rb_gc_get_objspace();
13409
13410 if (!stress_to_class) {
13411 set_stress_to_class(rb_ident_hash_new_capa(argc));
13412 }
13413
13414 for (int i = 0; i < argc; i++) {
13415 VALUE klass = argv[i];
13416 rb_hash_aset(stress_to_class, klass, Qtrue);
13417 }
13418
13419 return self;
13420}
13421
13422/*
13423 * call-seq:
13424 * GC.remove_stress_to_class(class[, ...])
13425 *
13426 * No longer raises NoMemoryError when allocating an instance of the
13427 * given classes.
13428 *
13429 */
13430static VALUE
13431rb_gcdebug_remove_stress_to_class(int argc, VALUE *argv, VALUE self)
13432{
13433 rb_objspace_t *objspace = rb_gc_get_objspace();
13434
13435 if (stress_to_class) {
13436 for (int i = 0; i < argc; ++i) {
13437 rb_hash_delete(stress_to_class, argv[i]);
13438 }
13439
13440 if (rb_hash_size(stress_to_class) == 0) {
13441 stress_to_class = 0;
13442 }
13443 }
13444
13445 return Qnil;
13446}
13447#endif
13448
13449void *
13450rb_gc_impl_objspace_alloc(void)
13451{
13452 global_objspace_init();
13453
13454 rb_objspace_t *objspace = calloc1(sizeof(rb_objspace_t));
13455 if (objspace) {
13456 rb_native_mutex_initialize(&objspace->process_stat.lock);
13457 }
13458
13459 return objspace;
13460}
13461
13462void
13463rb_gc_impl_objspace_init(void *objspace_ptr)
13464{
13465 rb_objspace_t *objspace = objspace_ptr;
13466
13467 gc_config_full_mark_set(TRUE);
13468
13469 malloc_limit = gc_params.malloc_limit_min;
13470 objspace->shareable_objects_limit = SHAREABLE_OBJECTS_LIMIT_MIN;
13471#ifdef MALLOC_COUNTERS_NEED_LOCK
13472 rb_native_mutex_initialize(&objspace->malloc_counters.lock);
13473#endif
13474 /* Shared by every objspace. preregister deduplicates on (func, data). */
13475 objspace->finalize_deferred_pjob = rb_postponed_job_preregister(0, gc_finalize_deferred, NULL);
13476 if (objspace->finalize_deferred_pjob == POSTPONED_JOB_HANDLE_INVALID) {
13477 rb_bug("Could not preregister postponed job for GC");
13478 }
13479
13480 gc_tdata_deferred_free_pjob_ensure();
13481
13482 /* A standard RVALUE (RBasic + embedded VALUEs + debug overhead) must fit
13483 * in at least one pool. In debug builds RVALUE_OVERHEAD can push this
13484 * beyond the 48-byte pool into the 64-byte pool, which is fine. */
13485 GC_ASSERT(rb_gc_impl_size_allocatable_p(sizeof(struct RBasic) + sizeof(VALUE[RBIMPL_RVALUE_EMBED_LEN_MAX])));
13486
13487 for (int i = 0; i < HEAP_COUNT; i++) {
13488 rb_heap_t *heap = &heaps[i];
13489
13490 heap->slot_size = pool_slot_sizes[i];
13491
13492 ccan_list_head_init(&heap->pages);
13493 }
13494
13495 if (global_objspace->main_objspace == NULL) {
13496 /* Single-threaded at boot and the first objspace is main's: compute process-wide
13497 * constants once here. A later objspace_init rewriting them, even with equal
13498 * values, would race other threads' lock-free reads. */
13499 global_objspace->main_objspace = objspace;
13500
13501 init_size_to_heap_idx();
13502
13503#if defined(INIT_HEAP_PAGE_ALLOC_USE_MMAP)
13504 /* Need to determine if we can use mmap at runtime. */
13505 heap_page_alloc_use_mmap = INIT_HEAP_PAGE_ALLOC_USE_MMAP;
13506#endif
13507 gc_params.heap_init_bytes = GC_HEAP_INIT_BYTES;
13508 gc_params.ractor_heap_init_bytes = GC_RACTOR_HEAP_INIT_BYTES ? GC_RACTOR_HEAP_INIT_BYTES
13509 : heap_init_bytes_min();
13510 }
13511 // GC.measure_total_time= sets the caller's objspace only; a new Ractor's follows
13512 // its creator's, which is the objspace running this init (main starts it on).
13513 objspace->flags.measure_gc = global_objspace->main_objspace == objspace ? true
13514 : ((rb_objspace_t *)rb_gc_get_objspace())->flags.measure_gc;
13515
13516 rb_darray_make_without_gc(&objspace->heap_pages.sorted, 0);
13517 rb_darray_make_without_gc(&objspace->weak_references, 0);
13518
13519#if RGENGC_ESTIMATE_OLDMALLOC
13520 objspace->rgengc.oldmalloc_increase_limit = gc_params.oldmalloc_limit_min;
13521#endif
13522
13523 init_mark_stack(&objspace->mark_stack);
13524
13525 objspace->profile.invoke_time = getrusage_time();
13526 objspace->profile.invoke_wall_time = rb_hrtime_now();
13527 objspace->profile.max_records = GC_PROFILE_RECORD_DEFAULT_MAX_RECORDS;
13528 finalizer_table = st_init_numtable();
13529
13530 gc_process_stat_publish(objspace);
13531}
13532
13533void
13534rb_gc_impl_init(void)
13535{
13536 /* Fill the symbol tables here, where no other ractor exists yet: they used to
13537 * be filled on first use, guarded by their own first element, so a second
13538 * ractor could see a half-filled table and GC.stat raised on the rest. */
13539 setup_gc_stat_symbols();
13540 setup_gc_stat_heap_symbols();
13541 setup_gc_latest_gc_info_symbols();
13542
13543 VALUE gc_constants = rb_hash_new();
13544 rb_hash_aset(gc_constants, ID2SYM(rb_intern("DEBUG")), GC_DEBUG ? Qtrue : Qfalse);
13545 /* Minimum slot size that fits a standard RVALUE */
13546 size_t rvalue_pool = 0;
13547 for (size_t i = 0; i < HEAP_COUNT; i++) {
13548 if (pool_slot_sizes[i] >= RVALUE_SLOT_SIZE) { rvalue_pool = pool_slot_sizes[i]; break; }
13549 }
13550 rb_hash_aset(gc_constants, ID2SYM(rb_intern("RVALUE_SIZE")), SIZET2NUM(rvalue_pool - RVALUE_OVERHEAD));
13551 rb_hash_aset(gc_constants, ID2SYM(rb_intern("RBASIC_SIZE")), SIZET2NUM(sizeof(struct RBasic)));
13552 rb_hash_aset(gc_constants, ID2SYM(rb_intern("RVALUE_OVERHEAD")), SIZET2NUM(RVALUE_OVERHEAD));
13553 rb_hash_aset(gc_constants, ID2SYM(rb_intern("HEAP_PAGE_BITMAP_SIZE")), SIZET2NUM(HEAP_PAGE_BITMAP_SIZE));
13554 rb_hash_aset(gc_constants, ID2SYM(rb_intern("HEAP_PAGE_SIZE")), SIZET2NUM(HEAP_PAGE_SIZE));
13555 rb_hash_aset(gc_constants, ID2SYM(rb_intern("HEAP_COUNT")), LONG2FIX(HEAP_COUNT));
13556 rb_hash_aset(gc_constants, ID2SYM(rb_intern("RVARGC_MAX_ALLOCATE_SIZE")), SIZET2NUM(rb_gc_impl_max_allocation_size()));
13557 rb_hash_aset(gc_constants, ID2SYM(rb_intern("RVALUE_OLD_AGE")), LONG2FIX(RVALUE_OLD_AGE));
13558 if (RB_BUG_INSTEAD_OF_RB_MEMERROR+0) {
13559 rb_hash_aset(gc_constants, ID2SYM(rb_intern("RB_BUG_INSTEAD_OF_RB_MEMERROR")), Qtrue);
13560 }
13561 OBJ_FREEZE(gc_constants);
13562 /* Internal constants in the garbage collector. */
13563 rb_define_const(rb_mGC, "INTERNAL_CONSTANTS", gc_constants);
13564
13565 if (GC_COMPACTION_SUPPORTED) {
13566 rb_define_singleton_method(rb_mGC, "compact", gc_compact, 0);
13567 rb_define_singleton_method(rb_mGC, "auto_compact", gc_get_auto_compact, 0);
13568 rb_define_singleton_method(rb_mGC, "auto_compact=", gc_set_auto_compact, 1);
13569 rb_define_singleton_method(rb_mGC, "latest_compact_info", gc_compact_stats, 0);
13570 rb_define_singleton_method(rb_mGC, "verify_compaction_references", gc_verify_compaction_references, -1);
13571 }
13572 else {
13576 rb_define_singleton_method(rb_mGC, "latest_compact_info", rb_f_notimplement, 0);
13577 rb_define_singleton_method(rb_mGC, "verify_compaction_references", rb_f_notimplement, -1);
13578 }
13579
13580#if GC_DEBUG_STRESS_TO_CLASS
13581 rb_define_singleton_method(rb_mGC, "add_stress_to_class", rb_gcdebug_add_stress_to_class, -1);
13582 rb_define_singleton_method(rb_mGC, "remove_stress_to_class", rb_gcdebug_remove_stress_to_class, -1);
13583#endif
13584
13585 /* internal methods */
13586 rb_define_singleton_method(rb_mGC, "verify_internal_consistency", gc_verify_internal_consistency_m, 0);
13587
13588#if MALLOC_ALLOCATED_SIZE
13589 rb_define_singleton_method(rb_mGC, "malloc_allocated_size", gc_malloc_allocated_size, 0);
13590 rb_define_singleton_method(rb_mGC, "malloc_allocations", gc_malloc_allocations, 0);
13591#endif
13592
13593 /* Document-class: GC::Profiler
13594 *
13595 * The GC profiler provides access to information on GC runs including time,
13596 * length and object space size.
13597 *
13598 * Example:
13599 *
13600 * GC::Profiler.enable
13601 *
13602 * require 'rdoc/rdoc'
13603 *
13604 * GC::Profiler.report
13605 *
13606 * pp GC::Profiler.raw_data
13607 *
13608 * GC::Profiler.disable
13609 *
13610 * GC::Profiler.raw_data returns one Hash per GC run, including CPU time
13611 * fields such as +:GC_TIME+ and wall-clock fields such as +:GC_WALL_TIME+,
13612 * +:GC_PAUSE_TIME+, +:GC_STOP_TIME+, and +:GC_STW_TIME+. +:GC_WALL_TIME+
13613 * is the wall-clock counterpart to +:GC_TIME+, while +:GC_PAUSE_TIME+
13614 * measures how long user execution was blocked by the GC entry.
13615 *
13616 * See also GC.count, GC.malloc_allocated_size and GC.malloc_allocations
13617 */
13618 VALUE rb_mProfiler = rb_define_module_under(rb_mGC, "Profiler");
13619 rb_define_singleton_method(rb_mProfiler, "enabled?", gc_profile_enable_get, 0);
13620 rb_define_singleton_method(rb_mProfiler, "enable", gc_profile_enable, 0);
13621 rb_define_singleton_method(rb_mProfiler, "raw_data", gc_profile_record_get, -1);
13622 rb_define_singleton_method(rb_mProfiler, "disable", gc_profile_disable, 0);
13623 rb_define_singleton_method(rb_mProfiler, "clear", gc_profile_clear, 0);
13624 rb_define_singleton_method(rb_mProfiler, "configure", gc_profile_configure, -1);
13625 rb_define_singleton_method(rb_mProfiler, "result", gc_profile_result, 0);
13626 rb_define_singleton_method(rb_mProfiler, "report", gc_profile_report, -1);
13627 rb_define_singleton_method(rb_mProfiler, "total_time", gc_profile_total_time, 0);
13628
13629 {
13630 VALUE opts;
13631 /* \GC build options */
13632 rb_define_const(rb_mGC, "OPTS", opts = rb_ary_new());
13633#define OPT(o) if (o) rb_ary_push(opts, rb_interned_str(#o, sizeof(#o) - 1))
13634 OPT(GC_DEBUG);
13635 OPT(USE_RGENGC);
13636 OPT(RGENGC_DEBUG);
13637 OPT(RGENGC_CHECK_MODE);
13638 OPT(RGENGC_PROFILE);
13639 OPT(RGENGC_ESTIMATE_OLDMALLOC);
13640 OPT(GC_PROFILE_MORE_DETAIL);
13641 OPT(GC_ENABLE_LAZY_SWEEP);
13642 OPT(CALC_EXACT_MALLOC_SIZE);
13643 OPT(MALLOC_ALLOCATED_SIZE);
13644 OPT(MALLOC_ALLOCATED_SIZE_CHECK);
13645 OPT(GC_PROFILE_DETAIL_MEMORY);
13646 OPT(GC_COMPACTION_SUPPORTED);
13647#undef OPT
13648 OBJ_FREEZE(opts);
13649 }
13650}
#define RBIMPL_ASSERT_OR_ASSUME(...)
This is either RUBY_ASSERT or RBIMPL_ASSUME, depending on RUBY_DEBUG.
Definition assert.h:311
#define RUBY_ASSERT(...)
Asserts that the given expression is truthy if and only if RUBY_DEBUG is truthy.
Definition assert.h:219
Atomic operations.
#define RUBY_ATOMIC_VALUE_CAS(var, oldval, newval)
Identical to RUBY_ATOMIC_CAS, except it expects its arguments are VALUE.
Definition atomic.h:416
#define RUBY_ATOMIC_SIZE_EXCHANGE(var, val)
Identical to RUBY_ATOMIC_EXCHANGE, except it expects its arguments are size_t.
Definition atomic.h:270
#define RUBY_ATOMIC_SIZE_INC(var)
Identical to RUBY_ATOMIC_INC, except it expects its argument is size_t.
Definition atomic.h:246
#define RUBY_ATOMIC_SIZE_CAS(var, oldval, newval)
Identical to RUBY_ATOMIC_CAS, except it expects its arguments are size_t.
Definition atomic.h:284
std::atomic< unsigned > rb_atomic_t
Type that is eligible for atomic operations.
Definition atomic.h:69
#define RUBY_ATOMIC_SIZE_ADD(var, val)
Identical to RUBY_ATOMIC_ADD, except it expects its arguments are size_t.
Definition atomic.h:307
#define RUBY_ATOMIC_VALUE_EXCHANGE(var, val)
Identical to RUBY_ATOMIC_EXCHANGE, except it expects its arguments are VALUE.
Definition atomic.h:402
#define RUBY_ATOMIC_SET(var, val)
Identical to RUBY_ATOMIC_EXCHANGE, except for the return type.
Definition atomic.h:185
#define RUBY_ATOMIC_EXCHANGE(var, val)
Atomically replaces the value pointed by var with val.
Definition atomic.h:152
#define rb_define_singleton_method(klass, mid, func, arity)
Defines klass.mid.
unsigned int rb_postponed_job_handle_t
The type of a handle returned from rb_postponed_job_preregister and passed to rb_postponed_job_trigge...
Definition debug.h:703
void rb_postponed_job_trigger(rb_postponed_job_handle_t h)
Triggers a pre-registered job registered with rb_postponed_job_preregister, scheduling it for executi...
Definition vm_trace.c:1899
rb_postponed_job_handle_t rb_postponed_job_preregister(unsigned int flags, rb_postponed_job_func_t func, void *data)
Pre-registers a func in Ruby's postponed job preregistration table, returning an opaque handle which ...
Definition vm_trace.c:1865
#define RB_GNUC_EXTENSION_BLOCK(x)
This is expanded to the passed token for non-GCC compilers.
Definition defines.h:91
#define RUBY_INTERNAL_EVENT_GC_EXIT
gc_exit() is called.
Definition event.h:99
#define RUBY_INTERNAL_EVENT_GC_ENTER
gc_enter() is called.
Definition event.h:98
#define RUBY_INTERNAL_EVENT_GC_END_SWEEP
GC ended sweep phase.
Definition event.h:97
#define RUBY_INTERNAL_EVENT_GC_END_MARK
GC ended mark phase.
Definition event.h:96
#define RUBY_INTERNAL_EVENT_OBJSPACE_MASK
Bitmask of GC events.
Definition event.h:100
#define RUBY_INTERNAL_EVENT_FREEOBJ
Object swept.
Definition event.h:94
#define RUBY_INTERNAL_EVENT_GC_START
GC started.
Definition event.h:95
uint32_t rb_event_flag_t
Represents event(s).
Definition event.h:108
static VALUE RB_FL_TEST(VALUE obj, VALUE flags)
Tests if the given flag(s) are set or not.
Definition fl_type.h:433
static VALUE RB_FL_TEST_RAW(VALUE obj, VALUE flags)
This is an implementation detail of RB_FL_TEST().
Definition fl_type.h:407
static void RB_FL_SET_RAW(VALUE obj, VALUE flags)
This is an implementation detail of RB_FL_SET().
Definition fl_type.h:544
static void RB_FL_UNSET_RAW(VALUE obj, VALUE flags)
This is an implementation detail of RB_FL_UNSET().
Definition fl_type.h:604
@ RUBY_FL_PROMOTED
Ruby objects are "generational".
Definition fl_type.h:205
@ RUBY_FL_SHAREABLE
This flag has something to do with Ractor.
Definition fl_type.h:253
@ RUBY_FL_WEAK_REFERENCE
This object weakly refers to other objects.
Definition fl_type.h:260
int rb_scan_args_kw(int kw_flag, int argc, const VALUE *argv, const char *fmt,...)
Identical to rb_scan_args(), except it also accepts kw_splat.
Definition class.c:3363
int rb_keyword_given_p(void)
Determines if the current method is given a keyword argument.
Definition eval.c:1048
int rb_get_kwargs(VALUE keyword_hash, const ID *table, int required, int optional, VALUE *values)
Keyword argument deconstructor.
Definition class.c:3139
#define T_COMPLEX
Old name of RUBY_T_COMPLEX.
Definition value_type.h:59
#define T_FILE
Old name of RUBY_T_FILE.
Definition value_type.h:62
#define T_STRING
Old name of RUBY_T_STRING.
Definition value_type.h:78
#define xfree
Old name of ruby_xfree.
Definition xmalloc.h:58
#define T_MASK
Old name of RUBY_T_MASK.
Definition value_type.h:68
#define Qundef
Old name of RUBY_Qundef.
#define INT2FIX
Old name of RB_INT2FIX.
Definition long.h:48
#define OBJ_FROZEN
Old name of RB_OBJ_FROZEN.
Definition fl_type.h:133
#define T_NIL
Old name of RUBY_T_NIL.
Definition value_type.h:72
#define T_FLOAT
Old name of RUBY_T_FLOAT.
Definition value_type.h:64
#define T_IMEMO
Old name of RUBY_T_IMEMO.
Definition value_type.h:67
#define ID2SYM
Old name of RB_ID2SYM.
Definition symbol.h:44
#define T_BIGNUM
Old name of RUBY_T_BIGNUM.
Definition value_type.h:57
#define SPECIAL_CONST_P
Old name of RB_SPECIAL_CONST_P.
#define T_STRUCT
Old name of RUBY_T_STRUCT.
Definition value_type.h:79
#define OBJ_FREEZE
Old name of RB_OBJ_FREEZE.
Definition fl_type.h:131
#define T_FIXNUM
Old name of RUBY_T_FIXNUM.
Definition value_type.h:63
#define SYM2ID
Old name of RB_SYM2ID.
Definition symbol.h:45
#define T_DATA
Old name of RUBY_T_DATA.
Definition value_type.h:60
#define FL_SHAREABLE
Old name of RUBY_FL_SHAREABLE.
Definition fl_type.h:62
#define T_NONE
Old name of RUBY_T_NONE.
Definition value_type.h:74
#define T_NODE
Old name of RUBY_T_NODE.
Definition value_type.h:73
#define SIZET2NUM
Old name of RB_SIZE2NUM.
Definition size_t.h:62
#define xmalloc
Old name of ruby_xmalloc.
Definition xmalloc.h:53
#define LONG2FIX
Old name of RB_INT2FIX.
Definition long.h:49
#define FIX2INT
Old name of RB_FIX2INT.
Definition int.h:41
#define FL_FINALIZE
Old name of RUBY_FL_FINALIZE.
Definition fl_type.h:61
#define T_MODULE
Old name of RUBY_T_MODULE.
Definition value_type.h:70
#define T_TRUE
Old name of RUBY_T_TRUE.
Definition value_type.h:81
#define T_RATIONAL
Old name of RUBY_T_RATIONAL.
Definition value_type.h:76
#define T_ICLASS
Old name of RUBY_T_ICLASS.
Definition value_type.h:66
#define T_HASH
Old name of RUBY_T_HASH.
Definition value_type.h:65
#define ALLOC_N
Old name of RB_ALLOC_N.
Definition memory.h:399
#define FL_TEST_RAW
Old name of RB_FL_TEST_RAW.
Definition fl_type.h:128
#define FL_SET
Old name of RB_FL_SET.
Definition fl_type.h:125
#define rb_ary_new3
Old name of rb_ary_new_from_args.
Definition array.h:658
#define T_FALSE
Old name of RUBY_T_FALSE.
Definition value_type.h:61
#define ULL2NUM
Old name of RB_ULL2NUM.
Definition long_long.h:31
#define T_UNDEF
Old name of RUBY_T_UNDEF.
Definition value_type.h:82
#define Qtrue
Old name of RUBY_Qtrue.
#define T_ZOMBIE
Old name of RUBY_T_ZOMBIE.
Definition value_type.h:83
#define Qnil
Old name of RUBY_Qnil.
#define Qfalse
Old name of RUBY_Qfalse.
#define T_ARRAY
Old name of RUBY_T_ARRAY.
Definition value_type.h:56
#define T_OBJECT
Old name of RUBY_T_OBJECT.
Definition value_type.h:75
#define NIL_P
Old name of RB_NIL_P.
#define FL_WB_PROTECTED
Old name of RUBY_FL_WB_PROTECTED.
Definition fl_type.h:59
#define T_SYMBOL
Old name of RUBY_T_SYMBOL.
Definition value_type.h:80
#define DBL2NUM
Old name of rb_float_new.
Definition double.h:29
#define T_MATCH
Old name of RUBY_T_MATCH.
Definition value_type.h:69
#define T_CLASS
Old name of RUBY_T_CLASS.
Definition value_type.h:58
#define BUILTIN_TYPE
Old name of RB_BUILTIN_TYPE.
Definition value_type.h:85
#define T_MOVED
Old name of RUBY_T_MOVED.
Definition value_type.h:71
#define FL_TEST
Old name of RB_FL_TEST.
Definition fl_type.h:127
#define NUM2LONG
Old name of RB_NUM2LONG.
Definition long.h:51
#define FL_UNSET
Old name of RB_FL_UNSET.
Definition fl_type.h:129
#define FIXNUM_P
Old name of RB_FIXNUM_P.
#define FL_SET_RAW
Old name of RB_FL_SET_RAW.
Definition fl_type.h:126
#define SYMBOL_P
Old name of RB_SYMBOL_P.
Definition value_type.h:88
#define T_REGEXP
Old name of RUBY_T_REGEXP.
Definition value_type.h:77
#define ruby_verbose
This variable controls whether the interpreter is in debug mode.
Definition error.h:476
VALUE rb_eRuntimeError
RuntimeError exception.
Definition error.c:1455
void rb_warn(const char *fmt,...)
Identical to rb_warning(), except it reports unless $VERBOSE is nil.
Definition error.c:464
VALUE rb_obj_hide(VALUE obj)
Make the object invisible from Ruby code.
Definition object.c:94
VALUE rb_mGC
GC module.
Definition gc.c:468
VALUE rb_equal(VALUE lhs, VALUE rhs)
This function is an optimised version of calling #==.
Definition object.c:140
VALUE rb_stdout
STDOUT constant.
Definition io.c:194
Routines to manipulate encodings of strings.
static bool RB_OBJ_PROMOTED_RAW(VALUE obj)
This is the implementation of RB_OBJ_PROMOTED().
Definition gc.h:594
#define USE_RGENGC
Definition gc.h:464
VALUE rb_ary_dup(VALUE ary)
Duplicates an array.
VALUE rb_ary_new(void)
Allocates a new, empty array.
VALUE rb_ary_push(VALUE ary, VALUE elem)
Special case of rb_ary_cat() that it adds only one element.
static int rb_check_arity(int argc, int min, int max)
Ensures that the passed integer is in the passed range.
Definition error.h:284
VALUE rb_str_buf_append(VALUE dst, VALUE src)
Identical to rb_str_cat_cstr(), except it takes Ruby's string instead of C's.
Definition string.c:3904
VALUE rb_str_buf_new(rb_len_t capa)
Allocates a "string buffer".
Definition string.c:1783
#define rb_str_new_cstr(str)
Identical to rb_str_new, except it assumes the passed pointer is a pointer to a C string.
Definition string.h:1539
const char * rb_sourcefile(void)
Resembles __FILE__.
Definition vm.c:2203
VALUE rb_f_notimplement(int argc, const VALUE *argv, VALUE obj, VALUE marker)
Raises rb_eNotImpError.
Definition vm_method.c:912
int rb_sourceline(void)
Resembles __LINE__.
Definition vm.c:2217
#define RB_SYM2ID
Just another name of rb_sym2id.
Definition symbol.h:43
ID rb_sym2id(VALUE obj)
Converts an instance of rb_cSymbol into an ID.
Definition symbol.c:1091
int capa
Designed capacity of the buffer.
Definition io.h:11
int len
Length of the buffer.
Definition io.h:8
void * rb_thread_call_with_gvl(void *(*func)(void *), void *data1)
(Re-)acquires the GVL.
Definition thread.c:2323
#define strtod(s, e)
Just another name of ruby_strtod.
Definition util.h:223
void ruby_qsort(void *, const size_t, const size_t, int(*)(const void *, const void *, void *), void *)
Reentrant implementation of quick sort.
#define MEMZERO(p, type, n)
Handy macro to erase a region of memory.
Definition memory.h:360
#define RB_GC_GUARD(v)
Prevents premature destruction of local objects.
Definition memory.h:167
VALUE type(ANYARGS)
ANYARGS-ed function type.
void rb_hash_foreach(VALUE q, int_type *w, VALUE e)
Iteration over the given hash.
VALUE rb_ensure(type *q, VALUE w, type *e, VALUE r)
An equivalent of ensure clause.
#define RARRAY_LEN
Just another name of rb_array_len.
Definition rarray.h:50
#define RARRAY_AREF(a, i)
References an object in an array.
Definition rarray.h:421
static void RARRAY_ASET(VALUE ary, rb_len_t i, VALUE v)
Assigns an object in an array.
Definition rarray.h:385
#define RBASIC(obj)
Convenient casting macro.
Definition rbasic.h:40
#define RUBY_TYPED_FREE_IMMEDIATELY
Macros to see if each corresponding flag is defined.
Definition rtypeddata.h:122
static const rb_data_type_t * RTYPEDDATA_TYPE(VALUE obj)
Queries for the type of given object.
Definition rtypeddata.h:692
#define RTYPEDDATA(obj)
Convenient casting macro.
Definition rtypeddata.h:96
#define errno
Ractor-aware version of errno.
Definition ruby.h:388
int ruby_native_thread_p(void)
Queries if the thread which calls this function is a ruby's thread.
Definition thread.c:6183
static bool RB_SPECIAL_CONST_P(VALUE obj)
Checks if the given object is of enum ruby_special_consts.
#define RTEST
This is an old name of RB_TEST.
#define _(args)
This was a transition path from K&R to ANSI.
Definition stdarg.h:35
Ruby object's base components.
Definition rbasic.h:69
This is the struct that holds necessary info for a struct.
Definition rtypeddata.h:242
Definition gc_impl.h:34
Definition st.h:79
Definition default.c:595
void rb_native_mutex_lock(rb_nativethread_lock_t *lock)
Just another name of rb_nativethread_lock_lock.
void rb_native_mutex_initialize(rb_nativethread_lock_t *lock)
Just another name of rb_nativethread_lock_initialize.
void rb_native_mutex_unlock(rb_nativethread_lock_t *lock)
Just another name of rb_nativethread_lock_unlock.
void rb_native_mutex_destroy(rb_nativethread_lock_t *lock)
Just another name of rb_nativethread_lock_destroy.
long rb_len_t
A signed integer type for lengths and indices of objects such as String and Array.
Definition value.h:142
uintptr_t ID
Type that represents a Ruby identifier such as a variable name.
Definition value.h:52
uintptr_t VALUE
Type that represents a Ruby object.
Definition value.h:40
static enum ruby_value_type RB_BUILTIN_TYPE(VALUE obj)
Queries the type of the object.
Definition value_type.h:182
static bool RB_TYPE_P(VALUE obj, enum ruby_value_type t)
Queries if the given object is of given type.
Definition value_type.h:376
ruby_value_type
C-level type of an object.
Definition value_type.h:113
@ RUBY_T_SYMBOL
Definition value_type.h:135
@ RUBY_T_MATCH
Definition value_type.h:128
@ RUBY_T_MODULE
Definition value_type.h:118
@ RUBY_T_ICLASS
Hidden classes known as IClasses.
Definition value_type.h:141
@ RUBY_T_MOVED
Definition value_type.h:143
@ RUBY_T_FIXNUM
Integers formerly known as Fixnums.
Definition value_type.h:136
@ RUBY_T_IMEMO
Definition value_type.h:139
@ RUBY_T_NODE
Definition value_type.h:140
@ RUBY_T_OBJECT
Definition value_type.h:116
@ RUBY_T_DATA
Definition value_type.h:127
@ RUBY_T_FALSE
Definition value_type.h:134
@ RUBY_T_UNDEF
Definition value_type.h:137
@ RUBY_T_COMPLEX
Definition value_type.h:129
@ RUBY_T_STRING
Definition value_type.h:120
@ RUBY_T_HASH
Definition value_type.h:123
@ RUBY_T_NIL
Definition value_type.h:132
@ RUBY_T_CLASS
Definition value_type.h:117
@ RUBY_T_ARRAY
Definition value_type.h:122
@ RUBY_T_MASK
Bitmask of ruby_value_type.
Definition value_type.h:145
@ RUBY_T_RATIONAL
Definition value_type.h:130
@ RUBY_T_ZOMBIE
Definition value_type.h:142
@ RUBY_T_BIGNUM
Definition value_type.h:125
@ RUBY_T_TRUE
Definition value_type.h:133
@ RUBY_T_FLOAT
Definition value_type.h:119
@ RUBY_T_STRUCT
Definition value_type.h:124
@ RUBY_T_NONE
Non-object (swept etc.)
Definition value_type.h:114
@ RUBY_T_REGEXP
Definition value_type.h:121
@ RUBY_T_FILE
Definition value_type.h:126