Ruby 4.1.0dev (2026-10-07 revision 8ddc747bddf6e121a5159185c3ed3f730da3bcda)
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 count;
611 uint64_t minor_gc_count;
612 uint64_t major_gc_count;
613 uint64_t global_gc_count;
614 uint64_t marking_time_ns;
615 uint64_t sweeping_time_ns;
616};
617
619 uint64_t count;
620 uint64_t minor_gc_count;
621 uint64_t major_gc_count;
622 uint64_t global_gc_count;
623 uint64_t marking_time_ns;
624 uint64_t sweeping_time_ns;
625};
626
627typedef struct rb_objspace {
628 struct {
629 struct gc_malloc_bytes counters;
630#if RGENGC_ESTIMATE_OLDMALLOC
631 struct gc_malloc_bytes oldcounters;
632#endif
633#ifdef MALLOC_COUNTERS_NEED_LOCK
634 rb_nativethread_lock_t lock;
635#endif
636 } malloc_counters;
637
638 struct {
639 size_t limit;
640#if MALLOC_ALLOCATED_SIZE
641 size_t allocated_size;
642 size_t allocations;
643#endif
644 } malloc_params;
645
647 bool full_mark;
648 } gc_config;
649
650 struct {
651 unsigned int mode : 2;
652 unsigned int immediate_sweep : 1;
653 unsigned int dont_gc : 1;
654 /* A user hold from GC.disable (kept in vm->gc.disable_holders); owner thread only. */
655 unsigned int user_gc_disabled : 1;
656 unsigned int dont_incremental : 1;
657 unsigned int during_gc : 1;
658 unsigned int during_global_gc : 1;
659 unsigned int during_compacting : 1;
660 unsigned int gc_lock_barrier : 1;
661 unsigned int during_reference_updating : 1;
662 unsigned int during_minor_gc : 1;
663 unsigned int during_incremental_marking : 1;
664 unsigned int during_postmortem : 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
674 struct {
675 rb_atomic_t finalizing;
676 } atomic_flags;
677
679 size_t marked_slots;
680
681 /* Moved out of the per-Ractor newobj cache: allocation state is per objspace. */
682 size_t incremental_mark_step_allocated_slots;
683
684 /* Inputs of the global GC trigger, all owned by this objspace's thread.
685 * shareable_objects is the live population of shareable objects; exceeding the
686 * limit requests a global GC. */
687 size_t shareable_objects;
688 size_t shareable_objects_limit;
689 /* Whether the last mark ran the pinned walk; the sweep asserts on it. */
690 unsigned char last_cycle_pinned;
691
692 struct {
693 rb_darray(struct heap_page *) sorted;
694
695 size_t allocated_pages;
696 size_t freed_pages;
697 uintptr_t range[2];
698 size_t freeable_pages;
699
700 size_t allocatable_bytes;
701
702 /* final */
703 VALUE deferred_final;
704 } heap_pages;
705
706 st_table *finalizer_table;
707
708 struct {
709 int run;
710 unsigned int latest_gc_info;
711 gc_profile_record *records;
712 gc_profile_record *current_record;
713 size_t next_index;
714 size_t size;
715 size_t record_count;
716 size_t max_records;
717 size_t record_sequence;
718
719#if GC_PROFILE_MORE_DETAIL
720 double prepare_time;
721#endif
722 double invoke_time;
723 rb_hrtime_t invoke_wall_time;
724
725 size_t minor_gc_count;
726 size_t major_gc_count;
727 size_t global_gc_count;
728 size_t compact_count;
729 size_t read_barrier_faults;
730#if RGENGC_PROFILE > 0
731 size_t total_generated_normal_object_count;
732 size_t total_generated_shady_object_count;
733 size_t total_shade_operation_count;
734 size_t total_promoted_count;
735 size_t total_remembered_normal_object_count;
736 size_t total_remembered_shady_object_count;
737
738#if RGENGC_PROFILE >= 2
739 size_t generated_normal_object_count_types[RUBY_T_MASK];
740 size_t generated_shady_object_count_types[RUBY_T_MASK];
741 size_t shade_operation_count_types[RUBY_T_MASK];
742 size_t promoted_types[RUBY_T_MASK];
743 size_t remembered_normal_object_count_types[RUBY_T_MASK];
744 size_t remembered_shady_object_count_types[RUBY_T_MASK];
745#endif
746#endif /* RGENGC_PROFILE */
747
748 /* temporary profiling space */
749 double gc_sweep_start_time;
750 rb_hrtime_t gc_wall_start_time;
751 rb_hrtime_t gc_sweep_wall_start_time;
752 rb_hrtime_t gc_sweep_excluded_wall_time;
753 rb_hrtime_t gc_pause_start_time;
754 rb_hrtime_t gc_stw_start_time;
755 rb_hrtime_t gc_stop_time;
756 rb_hrtime_t gc_mark_phase_wall_start_time;
757 rb_hrtime_t gc_sweep_phase_wall_start_time;
758#if GC_PROFILE_MORE_DETAIL
759 size_t total_allocated_objects_at_gc_start;
760 size_t heap_used_at_gc_start;
761#endif
762
763 /* basic statistics */
764 size_t count;
765 unsigned long long marking_time_ns;
766 struct timespec marking_start_time;
767 unsigned long long sweeping_time_ns;
768 struct timespec sweeping_start_time;
769
770 /* Weak references */
771 size_t weak_references_count;
772 } profile;
773
774
775 struct {
776 bool parent_object_old_p;
777 VALUE parent_object;
778
779 int need_major_gc;
780 size_t last_major_gc;
781 size_t uncollectible_wb_unprotected_objects;
782 size_t uncollectible_wb_unprotected_objects_limit;
783 size_t old_objects;
784 size_t old_objects_limit;
785
786#if RGENGC_ESTIMATE_OLDMALLOC
787 size_t oldmalloc_increase_limit;
788#endif
789
790#if RGENGC_CHECK_MODE >= 2
791 struct st_table *allrefs_table;
792 size_t error_count;
793#endif
794 } rgengc;
795
796 struct {
797 size_t considered_count_table[T_MASK];
798 size_t moved_count_table[T_MASK];
799 size_t moved_up_count_table[T_MASK];
800 size_t moved_down_count_table[T_MASK];
801 size_t total_moved;
802
803 /* This function will be used, if set, to sort the heap prior to compaction */
804 gc_compact_compare_func compare_func;
805 } rcompactor;
806
807 struct {
808 size_t pooled_slots;
809 size_t step_slots;
810 } rincgc;
811
812#if GC_DEBUG_STRESS_TO_CLASS
813 VALUE stress_to_class;
814#endif
815
816 rb_darray(VALUE) weak_references;
817 rb_postponed_job_handle_t finalize_deferred_pjob;
818
819 /* Partially filled chunk of deferred non-thread-safe T_DATA metadata. */
821
822 int sweeping_heap_count;
823
824 int fork_vm_lock_lev;
825
826 struct rb_gc_vm_context vm_context;
827
828 /* Process-wide GC statistics publication. Default GC only: other
829 * implementations reject GC.stat(scope: :global) and never initialize
830 * this lock. */
831 struct {
832 rb_nativethread_lock_t lock;
833 struct gc_process_stat_snapshot published;
834 } process_stat;
836
837/* The one VM-global GC structure; for now it only holds the page pool. Page bodies are
838 * carved out of large mmap arenas and reused via a process-wide freelist (per-page
839 * mmap/munmap would serialize on the kernel's mmap_lock). Leaf lock: no alloc, no GC. */
840typedef struct rb_global_objspace {
841 struct {
842 rb_nativethread_lock_t lock;
843 struct heap_page_body *hot_list; /* ≤ PAGE_POOL_HOT_MAX un-advised bodies; link at body offset 0 */
844 int hot_count;
845 size_t os_page_size; /* sysconf(_SC_PAGE_SIZE), cached at init */
846 /* List of mmap'd memory regions (arenas) for page bodies. */
847 struct page_arena {
848 struct page_arena *next;
849 char *start; /* usable area, HEAP_PAGE_ALIGN aligned */
850 size_t size; /* usable bytes (a multiple of HEAP_PAGE_SIZE) */
851 struct heap_page_body *cold_freelist; /* free bodies of this arena; link at body offset 0 */
852 int free_count; /* bodies of this arena currently free (hot list + cold_freelist) */
853 int cold_count; /* bodies on cold_freelist (subset of free_count) */
854 } *arenas; /* every arena, newest first */
855 char *arena_cursor; /* first body not yet carved out of the newest arena */
856 char *arena_end; /* end of current arena */
857 struct page_arena *arena_current; /* arena that arena_cursor carves from */
858 int arena_count; /* current mapped arenas (for GC.stat total_pages) */
859 int advised_count; /* page bodies with MADV_* applied (for GC.stat discarded pages) */
860 size_t arenas_unmapped; /* cumulative arenas munmapped (for GC.stat) */
861 } page_pool;
862
863 /* Zombie pages left after the last global cycle (roughly the live data). Updated
864 * under the barrier; readers (gc_need_global_p) may be racy. */
865 size_t zombie_pages_survivors;
866
867 /* An objspace merge (objspace_absorb) is running: suppress the cross-objspace
868 * verifier while the graph is in flux. Written by the absorbing thread, read by
869 * verification with the world stopped. */
870 bool during_absorb;
871
872 /* main's objspace, for gc_enter's locking policy. main_ractor->objspace is swapped
873 * during Ractor creation; this stable pointer decides the same way at both ends of a
874 * GC. Set at boot, re-pointed in a forked child. */
875 rb_objspace_t *main_objspace;
876
877 /* GC.stress is process-global (upstream semantics). Written by GC.stress= in any
878 * Ractor (rare) and read on every Ractor's alloc and GC path; it is diagnostic, so
879 * plain store/load with last-writer-wins is fine. */
880 bool gc_stressful;
881 VALUE gc_stress_mode;
882
883 /* Global GC driver state. compacting is true during the move phase: reference
884 * updates are deferred until all forwarding exists, so a cross-objspace reference is
885 * rewritten exactly once. objspaces is the snapshot being collected. */
886 struct {
887 bool compacting;
888 struct rb_objspace **objspaces;
889 size_t n_objspaces, objspaces_capa;
890 size_t count;
891 } global_gc;
892
893 /* Index of every objspace's heap pages, ordered by body address. Writers (page
894 * alloc/free) serialize on page_pool.lock; the only reader is a stop-the-world global
895 * GC, so reads need no lock. A local GC uses its own heap_pages.sorted. */
896 struct {
897 struct heap_page **pages;
898 size_t n_pages, capa;
899 uintptr_t lomem, himem;
900 } page_index;
901
902 rb_postponed_job_handle_t tdata_deferred_free_pjob; /* atomic */
903
904 /* Pending count of deferred non-thread-safe T_DATA frees across all objspaces:
905 * bumped as each one is deferred, reset to 0 by the drain. Crossing
906 * TDATA_DEFERRED_FREE_THRESHOLD triggers the postponed job. */
907 size_t tdata_deferred_free_count; /* atomic */
908
909 /* Full chunks awaiting a drain (CAS stack), and drained chunks kept for reuse. */
910 struct tdata_unsafe_free_chunk *tdata_unsafe_free_published; /* atomic */
911 struct tdata_unsafe_free_chunk *tdata_unsafe_free_cache; /* atomic */
912 size_t tdata_unsafe_free_cache_len; /* atomic */
913
914 /* Archive of destroyed objspaces' final statistics, added once on absorption. */
915 struct gc_process_stat_total process_stat_archive;
917
918static rb_global_objspace_t rb_global_objspace_instance;
919static rb_global_objspace_t *global_objspace = NULL;
920
921/* Relaxed: every reader only asks whether a drain is worth arranging, and the drain
922 * itself stops the world before it touches a chunk. There is no atomic size_t load, so
923 * go through the VALUE one (both are word sized). */
924static inline size_t
925tdata_deferred_free_count_load(void)
926{
927 return (size_t)rbimpl_atomic_value_load(
928 (volatile VALUE *)&global_objspace->tdata_deferred_free_count, RBIMPL_ATOMIC_RELAXED);
929}
930
931/* The floor keeps a global GC from running as soon as a few shareable objects appear;
932 * the factor follows the rule used for the old-generation limit. */
933#define SHAREABLE_OBJECTS_LIMIT_MIN (1 << 16)
934#define SHAREABLE_OBJECTS_LIMIT_FACTOR 2.0
935/* Start a global GC once terminated, uninherited Ractors hold this many heap pages. A
936 * small Ractor's objspace is about 13 pages, so discarding many of them still stays
937 * below it, while a single fat zombie crosses it. */
938#define ZOMBIE_PAGES_TRIGGER 256
939/* Trigger the deferred T_DATA free postponed job once this many have accumulated
940 * across all objspaces. */
941#define TDATA_DEFERRED_FREE_THRESHOLD (1 << 15)
942
943static void objspace_absorb(rb_objspace_t *dst, rb_objspace_t *src);
944
945
946static struct heap_page_body *page_pool_acquire(struct page_arena **arena_out);
947static void page_pool_release(struct heap_page_body *body, struct page_arena *arena);
948#ifdef HAVE_MMAP
949static void page_pool_release_locked(struct heap_page_body *body, struct page_arena *arena);
950#endif
951static void page_pool_reclaim(rb_global_objspace_t *g);
952
953#if RGENGC_CHECK_MODE && !defined(_WIN32) && !defined(__wasi__) && defined(HAVE_PTHREAD_H)
954# define PAGE_POOL_LOCK_ERRORCHECK 1
955#endif
956
957static void
958page_pool_lock_initialize(rb_nativethread_lock_t *lock)
959{
960#ifdef PAGE_POOL_LOCK_ERRORCHECK
961 pthread_mutexattr_t attr;
962 pthread_mutexattr_init(&attr);
963 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK);
964 pthread_mutex_init(lock, &attr);
965 pthread_mutexattr_destroy(&attr);
966#else
968#endif
969}
970
971static void
972global_objspace_init(void)
973{
974 if (global_objspace == NULL) {
975 rb_global_objspace_t *g = &rb_global_objspace_instance;
976 page_pool_lock_initialize(&g->page_pool.lock);
977 g->page_pool.hot_list = NULL;
978 g->page_pool.hot_count = 0;
979 g->page_pool.arenas = NULL;
980 g->page_pool.arena_cursor = NULL;
981 g->page_pool.arena_end = NULL;
982 g->page_pool.arena_current = NULL;
983 g->page_pool.arena_count = 0;
984 g->page_pool.advised_count = 0;
985 g->tdata_deferred_free_pjob = POSTPONED_JOB_HANDLE_INVALID;
986 g->tdata_unsafe_free_published = NULL;
987 g->tdata_unsafe_free_cache = NULL;
988 g->tdata_unsafe_free_cache_len = 0;
989 g->page_pool.arenas_unmapped = 0;
990#ifdef HAVE_MMAP
991 g->page_pool.os_page_size = sysconf(_SC_PAGE_SIZE);
992#else
993 g->page_pool.os_page_size = 0;
994#endif
995 global_objspace = g;
996 }
997}
998
999#ifndef HEAP_PAGE_ALIGN_LOG
1000/* default tiny heap size: 64KiB */
1001#define HEAP_PAGE_ALIGN_LOG 16
1002#endif
1003
1004#if GC_DEBUG
1005struct rvalue_overhead {
1006 const char *file;
1007 int line;
1008};
1009
1010// Make sure that RVALUE_OVERHEAD aligns to sizeof(VALUE)
1011# define RVALUE_OVERHEAD (sizeof(struct { \
1012 union { \
1013 struct rvalue_overhead overhead; \
1014 VALUE value; \
1015 }; \
1016}))
1017size_t rb_gc_impl_obj_slot_size(VALUE obj);
1018# define GET_RVALUE_OVERHEAD(obj) ((struct rvalue_overhead *)((uintptr_t)obj + rb_gc_impl_obj_slot_size(obj)))
1019#else
1020# ifndef RVALUE_OVERHEAD
1021# define RVALUE_OVERHEAD 0
1022# endif
1023#endif
1024
1025#define RVALUE_SLOT_SIZE (sizeof(struct RBasic) + sizeof(VALUE[RBIMPL_RVALUE_EMBED_LEN_MAX]) + RVALUE_OVERHEAD)
1026
1027static const size_t pool_slot_sizes[HEAP_COUNT] = {
1028#define SLOT(size) ((size) + RVALUE_OVERHEAD),
1029 EACH_POOL_SLOT_SIZE(SLOT)
1030#undef SLOT
1031};
1032
1033/* An init size below one slot in the largest heap never forces that heap's first
1034 * page, and allocating there then fails with "cannot create a new page after GC". */
1035static inline size_t
1036heap_init_bytes_min(void)
1037{
1038 return pool_slot_sizes[HEAP_COUNT - 1];
1039}
1040
1041/* Precomputed reciprocals for fast slot index calculation.
1042 * For slot size d: reciprocal = ceil(2^48 / d).
1043 * Then offset / d == (uint32_t)((offset * reciprocal) >> 48)
1044 * for all offset < HEAP_PAGE_SIZE. */
1045#define SLOT_RECIPROCAL_SHIFT 48
1046#define SLOT_RECIPROCAL(size) (((1ULL << SLOT_RECIPROCAL_SHIFT) + (size) - 1) / (size))
1047
1048static const uint64_t heap_slot_reciprocal_table[HEAP_COUNT] = {
1049#define SLOT(size) SLOT_RECIPROCAL((size) + RVALUE_OVERHEAD),
1050 EACH_POOL_SLOT_SIZE(SLOT)
1051#undef SLOT
1052};
1053
1054#if SIZEOF_VALUE >= 8
1055static uint8_t size_to_heap_idx[1024 / 8 + 1];
1056#else
1057static uint8_t size_to_heap_idx[512 / 8 + 1];
1058#endif
1059
1060#ifndef MAX
1061# define MAX(a, b) (((a) > (b)) ? (a) : (b))
1062#endif
1063#ifndef MIN
1064# define MIN(a, b) (((a) < (b)) ? (a) : (b))
1065#endif
1066#define roomof(x, y) (((x) + (y) - 1) / (y))
1067#define CEILDIV(i, mod) roomof(i, mod)
1068#define MIN_POOL_SLOT_SIZE 32
1069enum {
1070 HEAP_PAGE_ALIGN = (1UL << HEAP_PAGE_ALIGN_LOG),
1071 HEAP_PAGE_ALIGN_MASK = (~(~0UL << HEAP_PAGE_ALIGN_LOG)),
1072 HEAP_PAGE_SIZE = HEAP_PAGE_ALIGN,
1073 HEAP_PAGE_BITMAP_LIMIT = CEILDIV(CEILDIV(HEAP_PAGE_SIZE, MIN_POOL_SLOT_SIZE), BITS_BITLENGTH),
1074 HEAP_PAGE_BITMAP_SIZE = (BITS_SIZE * HEAP_PAGE_BITMAP_LIMIT),
1075};
1076#define HEAP_PAGE_ALIGN (1 << HEAP_PAGE_ALIGN_LOG)
1077#define HEAP_PAGE_SIZE HEAP_PAGE_ALIGN
1078
1079#if !defined(INCREMENTAL_MARK_STEP_ALLOCATIONS)
1080# define INCREMENTAL_MARK_STEP_ALLOCATIONS 500
1081#endif
1082
1083#undef INIT_HEAP_PAGE_ALLOC_USE_MMAP
1084/* Must define either HEAP_PAGE_ALLOC_USE_MMAP or
1085 * INIT_HEAP_PAGE_ALLOC_USE_MMAP. */
1086
1087#ifndef HAVE_MMAP
1088/* We can't use mmap of course, if it is not available. */
1089static const bool HEAP_PAGE_ALLOC_USE_MMAP = false;
1090
1091#elif defined(__wasm__)
1092/* wasmtime does not have proper support for mmap.
1093 * See https://github.com/bytecodealliance/wasmtime/blob/main/docs/WASI-rationale.md#why-no-mmap-and-friends
1094 */
1095static const bool HEAP_PAGE_ALLOC_USE_MMAP = false;
1096
1097#elif HAVE_CONST_PAGE_SIZE
1098/* If we have the PAGE_SIZE and it is a constant, then we can directly use it. */
1099static const bool HEAP_PAGE_ALLOC_USE_MMAP = (PAGE_SIZE <= HEAP_PAGE_SIZE);
1100
1101#elif defined(PAGE_MAX_SIZE) && (PAGE_MAX_SIZE <= HEAP_PAGE_SIZE)
1102/* If we can use the maximum page size. */
1103static const bool HEAP_PAGE_ALLOC_USE_MMAP = true;
1104
1105#elif defined(PAGE_SIZE)
1106/* If the PAGE_SIZE macro can be used dynamically. */
1107# define INIT_HEAP_PAGE_ALLOC_USE_MMAP (PAGE_SIZE <= HEAP_PAGE_SIZE)
1108
1109#elif defined(HAVE_SYSCONF) && defined(_SC_PAGE_SIZE)
1110/* If we can use sysconf to determine the page size. */
1111# define INIT_HEAP_PAGE_ALLOC_USE_MMAP (sysconf(_SC_PAGE_SIZE) <= HEAP_PAGE_SIZE)
1112
1113#else
1114/* Otherwise we can't determine the system page size, so don't use mmap. */
1115static const bool HEAP_PAGE_ALLOC_USE_MMAP = false;
1116#endif
1117
1118#ifdef INIT_HEAP_PAGE_ALLOC_USE_MMAP
1119/* We can determine the system page size at runtime. */
1120# define HEAP_PAGE_ALLOC_USE_MMAP (heap_page_alloc_use_mmap != false)
1121
1122static bool heap_page_alloc_use_mmap;
1123#endif
1124
1125#define RVALUE_AGE_BIT_COUNT 2
1126#define RVALUE_AGE_BIT_MASK (((bits_t)1 << RVALUE_AGE_BIT_COUNT) - 1)
1127#define RVALUE_OLD_AGE 3
1128
1130 VALUE flags; /* always 0 for freed obj */
1131 uintptr_t end; /* exclusive end address of the run */
1132 struct free_region *next; /* next free region in the page */
1133};
1134
1136 /* Cache line 0: allocation fast path + SLOT_INDEX */
1137 struct free_region *free_region;
1138 uintptr_t start;
1139 uint64_t slot_size_reciprocal;
1140 unsigned short slot_size;
1141 unsigned short total_slots;
1142 unsigned short free_slots;
1143 unsigned short final_slots;
1144 unsigned short pinned_slots;
1145 /* Page state flags. A bitfield is safe: the only writers are the owning Ractor
1146 * (GVL) and the global GC driver (stop-the-world), never together. has_shareable /
1147 * has_shref hint that the page holds at least one such bit, for re-scanning. */
1148 struct {
1149 unsigned int before_sweep : 1;
1150 unsigned int has_remembered_objects : 1;
1151 unsigned int has_uncollectible_wb_unprotected_objects : 1;
1152 unsigned int has_shref_objects : 1;
1153 unsigned int has_shareable_objects : 1;
1154 } flags;
1155
1156 rb_heap_t *heap;
1157
1158 /* The objspace owning this page, so any object's owner is one load away
1159 * (GET_HEAP_OBJSPACE). Rewritten only when a page changes owner (inheritance). */
1161
1162 struct heap_page *free_next;
1163 struct heap_page_body *body;
1164 struct page_arena *arena;
1165 struct ccan_list_node page_node;
1166
1167 bits_t wb_unprotected_bits[HEAP_PAGE_BITMAP_LIMIT];
1168 /* the following three bitmaps are cleared at the beginning of full GC */
1169 bits_t mark_bits[HEAP_PAGE_BITMAP_LIMIT];
1170 bits_t uncollectible_bits[HEAP_PAGE_BITMAP_LIMIT];
1171 bits_t marking_bits[HEAP_PAGE_BITMAP_LIMIT];
1172
1173 bits_t remembered_bits[HEAP_PAGE_BITMAP_LIMIT];
1174
1175 /* Two extra bits per object. shareable_bits: what a local sweep must never free
1176 * (only a global GC decides a shareable object is dead); set at creation and by
1177 * rb_gc_impl_obj_became_shareable. shref_bits: an unshareable object referenced
1178 * from a shareable one, a local GC root; the write barrier maintains it. */
1179 bits_t shareable_bits[HEAP_PAGE_BITMAP_LIMIT];
1180 bits_t shref_bits[HEAP_PAGE_BITMAP_LIMIT];
1181
1182 /* If set, the object is not movable */
1183 bits_t pinned_bits[HEAP_PAGE_BITMAP_LIMIT];
1184 bits_t age_bits[HEAP_PAGE_BITMAP_LIMIT * RVALUE_AGE_BIT_COUNT];
1185};
1186
1187/*
1188 * When asan is enabled, this will prohibit writing to the freelist until it is unlocked
1189 */
1190static void
1191asan_lock_freelist(struct heap_page *page)
1192{
1193 asan_poison_memory_region(&page->free_region, sizeof(struct free_region *));
1194}
1195
1196/*
1197 * When asan is enabled, this will enable the ability to write to the freelist
1198 */
1199static void
1200asan_unlock_freelist(struct heap_page *page)
1201{
1202 asan_unpoison_memory_region(&page->free_region, sizeof(struct free_region *), false);
1203}
1204
1205static inline bool
1206heap_page_in_global_empty_pages_pool(rb_objspace_t *objspace, struct heap_page *page)
1207{
1208 if (page->total_slots == 0) {
1209 GC_ASSERT(page->start == 0);
1210 GC_ASSERT(page->slot_size == 0);
1211 GC_ASSERT(page->heap == NULL);
1212 GC_ASSERT(page->free_slots == 0);
1213 asan_unpoisoning_memory_region(&page->free_region, sizeof(&page->free_region)) {
1214 GC_ASSERT(page->free_region == NULL);
1215 }
1216
1217 return true;
1218 }
1219 else {
1220 GC_ASSERT(page->start != 0);
1221 GC_ASSERT(page->slot_size != 0);
1222 GC_ASSERT(page->heap != NULL);
1223
1224 return false;
1225 }
1226}
1227
1228#define GET_PAGE_BODY(x) ((struct heap_page_body *)((bits_t)(x) & ~(HEAP_PAGE_ALIGN_MASK)))
1229#define GET_PAGE_HEADER(x) (&GET_PAGE_BODY(x)->header)
1230#define GET_HEAP_PAGE(x) (GET_PAGE_HEADER(x)->page)
1231
1232static inline size_t
1233slot_index_for_offset(size_t offset, uint64_t reciprocal)
1234{
1235 return (uint32_t)(((uint64_t)offset * reciprocal) >> SLOT_RECIPROCAL_SHIFT);
1236}
1237
1238#define SLOT_INDEX(page, p) slot_index_for_offset((uintptr_t)(p) - (page)->start, (page)->slot_size_reciprocal)
1239#define SLOT_BITMAP_INDEX(page, p) (SLOT_INDEX(page, p) / BITS_BITLENGTH)
1240#define SLOT_BITMAP_OFFSET(page, p) (SLOT_INDEX(page, p) & (BITS_BITLENGTH - 1))
1241#define SLOT_BITMAP_BIT(page, p) ((bits_t)1 << SLOT_BITMAP_OFFSET(page, p))
1242
1243#define _MARKED_IN_BITMAP(bits, page, p) ((bits)[SLOT_BITMAP_INDEX(page, p)] & SLOT_BITMAP_BIT(page, p))
1244#define _MARK_IN_BITMAP(bits, page, p) ((bits)[SLOT_BITMAP_INDEX(page, p)] |= SLOT_BITMAP_BIT(page, p))
1245#define _CLEAR_IN_BITMAP(bits, page, p) ((bits)[SLOT_BITMAP_INDEX(page, p)] &= ~SLOT_BITMAP_BIT(page, p))
1246
1247#define MARKED_IN_BITMAP(bits, p) _MARKED_IN_BITMAP(bits, GET_HEAP_PAGE(p), p)
1248#define MARK_IN_BITMAP(bits, p) _MARK_IN_BITMAP(bits, GET_HEAP_PAGE(p), p)
1249#define CLEAR_IN_BITMAP(bits, p) _CLEAR_IN_BITMAP(bits, GET_HEAP_PAGE(p), p)
1250
1251#define GET_HEAP_MARK_BITS(x) (&GET_HEAP_PAGE(x)->mark_bits[0])
1252#define GET_HEAP_PINNED_BITS(x) (&GET_HEAP_PAGE(x)->pinned_bits[0])
1253#define GET_HEAP_UNCOLLECTIBLE_BITS(x) (&GET_HEAP_PAGE(x)->uncollectible_bits[0])
1254#define GET_HEAP_WB_UNPROTECTED_BITS(x) (&GET_HEAP_PAGE(x)->wb_unprotected_bits[0])
1255#define GET_HEAP_MARKING_BITS(x) (&GET_HEAP_PAGE(x)->marking_bits[0])
1256#define GET_HEAP_SHAREABLE_BITS(x) (&GET_HEAP_PAGE(x)->shareable_bits[0])
1257#define GET_HEAP_SHREF_BITS(x) (&GET_HEAP_PAGE(x)->shref_bits[0])
1258#define GET_HEAP_OBJSPACE(x) (GET_HEAP_PAGE(x)->objspace)
1259
1260/* obj lives on a page of another objspace, not the current one (i.e. it is foreign). */
1261static inline bool
1262gc_foreign_object_p(const rb_objspace_t *objspace, VALUE obj)
1263{
1264 return RB_UNLIKELY(GET_HEAP_OBJSPACE(obj) != objspace);
1265}
1266
1267/* Foreign and not inside a stop-the-world global GC. While true, a local GC must not
1268 * touch obj's per-object GC state (mark, pin, remember bits): its owner handles that,
1269 * or the global GC does with everyone stopped. */
1270static inline bool
1271gc_skip_foreign_object_p(const rb_objspace_t *objspace, VALUE obj)
1272{
1273 return gc_foreign_object_p(objspace, obj) && !objspace->flags.during_global_gc;
1274}
1275
1276/* Record obj as shareable on its owning page (bit, page flag and population counter).
1277 * Shared by born-shareable objects and make_shareable. The writer is the owner thread,
1278 * so plain bit operations suffice. */
1279static inline void
1280gc_page_add_shareable(struct heap_page *page, VALUE obj)
1281{
1282 GC_ASSERT(page == GET_HEAP_PAGE(obj));
1283 GC_ASSERT(RB_FL_TEST_RAW(obj, RUBY_FL_SHAREABLE));
1284 _MARK_IN_BITMAP(page->shareable_bits, page, obj);
1285 page->flags.has_shareable_objects = TRUE;
1286 page->objspace->shareable_objects++;
1287}
1288
1289static int
1290RVALUE_AGE_GET(VALUE obj)
1291{
1292 struct heap_page *page = GET_HEAP_PAGE(obj);
1293 bits_t *age_bits = page->age_bits;
1294 size_t slot_idx = SLOT_INDEX(page, obj);
1295 size_t idx = (slot_idx / BITS_BITLENGTH) * 2;
1296 int shift = (int)(slot_idx & (BITS_BITLENGTH - 1));
1297 int lo = (age_bits[idx] >> shift) & 1;
1298 int hi = (age_bits[idx + 1] >> shift) & 1;
1299 return lo | (hi << 1);
1300}
1301
1302static void
1303RVALUE_AGE_SET_BITMAP(VALUE obj, int age)
1304{
1305 RUBY_ASSERT(age <= RVALUE_OLD_AGE);
1306 struct heap_page *page = GET_HEAP_PAGE(obj);
1307 bits_t *age_bits = page->age_bits;
1308 size_t slot_idx = SLOT_INDEX(page, obj);
1309 size_t idx = (slot_idx / BITS_BITLENGTH) * 2;
1310 int shift = (int)(slot_idx & (BITS_BITLENGTH - 1));
1311 bits_t mask = (bits_t)1 << shift;
1312
1313 age_bits[idx] = (age_bits[idx] & ~mask) | ((bits_t)(age & 1) << shift);
1314 age_bits[idx + 1] = (age_bits[idx + 1] & ~mask) | ((bits_t)((age >> 1) & 1) << shift);
1315}
1316
1317static void
1318RVALUE_AGE_SET(VALUE obj, int age)
1319{
1320 RVALUE_AGE_SET_BITMAP(obj, age);
1321 if (age == RVALUE_OLD_AGE) {
1323 }
1324 else {
1326 }
1327}
1328
1329#define malloc_limit objspace->malloc_params.limit
1330#define malloc_increase gc_malloc_counters_increase_unsigned(objspace, &objspace->malloc_counters.counters)
1331#define malloc_allocated_size objspace->malloc_params.allocated_size
1332
1333#ifdef MALLOC_COUNTERS_NEED_LOCK
1334# define MALLOC_COUNTERS_LOCK(o) rb_native_mutex_lock(&(o)->malloc_counters.lock)
1335# define MALLOC_COUNTERS_UNLOCK(o) rb_native_mutex_unlock(&(o)->malloc_counters.lock)
1336#else
1337# define MALLOC_COUNTERS_LOCK(o) ((void)0)
1338# define MALLOC_COUNTERS_UNLOCK(o) ((void)0)
1339#endif
1340
1341static inline void
1342gc_counter_add(gc_counter_t *p, size_t delta)
1343{
1344#ifdef MALLOC_COUNTERS_NEED_LOCK
1345 *p += (gc_counter_t)delta;
1346#else
1347 rbimpl_atomic_u64_fetch_add_relaxed(p, (uint64_t)delta);
1348#endif
1349}
1350
1351static inline gc_counter_t
1352gc_counter_load_relaxed(const gc_counter_t *p)
1353{
1354#ifdef MALLOC_COUNTERS_NEED_LOCK
1355 return *p;
1356#else
1357 return rbimpl_atomic_u64_load_relaxed(p);
1358#endif
1359}
1360
1361static inline gc_counter_t
1362gc_counter_load_acquire(const gc_counter_t *p)
1363{
1364#ifdef MALLOC_COUNTERS_NEED_LOCK
1365 return *p;
1366#else
1367 return rbimpl_atomic_u64_load_acquire(p);
1368#endif
1369}
1370
1371static inline void
1372gc_counter_store_release(gc_counter_t *p, gc_counter_t v)
1373{
1374#ifdef MALLOC_COUNTERS_NEED_LOCK
1375 *p = v;
1376#else
1377 rbimpl_atomic_u64_set_release(p, v);
1378#endif
1379}
1380
1381static inline int64_t
1382gc_malloc_counters_increase(rb_objspace_t *objspace, const struct gc_malloc_bytes *c)
1383{
1384 MALLOC_COUNTERS_LOCK(objspace);
1385 gc_counter_t malloc_at = gc_counter_load_acquire(&c->malloc_at_last_gc);
1386 gc_counter_t free_at = gc_counter_load_acquire(&c->free_at_last_gc);
1387 gc_counter_t malloc_now = gc_counter_load_relaxed(&c->malloc);
1388 gc_counter_t free_now = gc_counter_load_relaxed(&c->free);
1389 MALLOC_COUNTERS_UNLOCK(objspace);
1390
1391 gc_counter_t malloc_delta = malloc_now - malloc_at;
1392 gc_counter_t free_delta = free_now - free_at;
1393
1394 if (malloc_delta >= free_delta) {
1395 return (int64_t)(malloc_delta - free_delta);
1396 }
1397 else {
1398 return -(int64_t)(free_delta - malloc_delta);
1399 }
1400}
1401
1402static inline size_t
1403gc_malloc_counters_increase_unsigned(rb_objspace_t *objspace, const struct gc_malloc_bytes *c)
1404{
1405 int64_t inc = gc_malloc_counters_increase(objspace, c);
1406 if (inc <= 0) return 0;
1407#if SIZEOF_SIZE_T < 8
1408 if ((uint64_t)inc > SIZE_MAX) return SIZE_MAX;
1409#endif
1410 return (size_t)inc;
1411}
1412
1413/* Frees done while sweeping are the GC's own work, not the mutator's: advance
1414 * free_at_last_gc past them so they cannot pay for the next cycle's allocation.
1415 * malloc_at_last_gc stays at gc_reset_malloc_info's snapshot (GC start). */
1416static inline void
1417gc_malloc_counters_snapshot_free_at_last_gc(rb_objspace_t *objspace, struct gc_malloc_bytes *c)
1418{
1419 MALLOC_COUNTERS_LOCK(objspace);
1420 gc_counter_store_release(&c->free_at_last_gc, gc_counter_load_relaxed(&c->free));
1421 MALLOC_COUNTERS_UNLOCK(objspace);
1422}
1423
1424static inline void
1425gc_malloc_counters_snapshot(rb_objspace_t *objspace, struct gc_malloc_bytes *c)
1426{
1427 MALLOC_COUNTERS_LOCK(objspace);
1428 gc_counter_t malloc_now = gc_counter_load_relaxed(&c->malloc);
1429 gc_counter_t free_now = gc_counter_load_relaxed(&c->free);
1430 gc_counter_store_release(&c->malloc_at_last_gc, malloc_now);
1431 gc_counter_store_release(&c->free_at_last_gc, free_now);
1432 MALLOC_COUNTERS_UNLOCK(objspace);
1433}
1434
1435#define heap_pages_lomem objspace->heap_pages.range[0]
1436#define heap_pages_himem objspace->heap_pages.range[1]
1437#define heap_pages_freeable_pages objspace->heap_pages.freeable_pages
1438#define heap_pages_deferred_final objspace->heap_pages.deferred_final
1439#define heaps objspace->heaps
1440#define during_gc objspace->flags.during_gc
1441#define finalizing objspace->atomic_flags.finalizing
1442#define finalizer_table objspace->finalizer_table
1443#define ruby_gc_stressful global_objspace->gc_stressful
1444#define ruby_gc_stress_mode global_objspace->gc_stress_mode
1445#if GC_DEBUG_STRESS_TO_CLASS
1446#define stress_to_class objspace->stress_to_class
1447#define set_stress_to_class(c) (stress_to_class = (c))
1448#else
1449#define stress_to_class ((void)objspace, 0)
1450#define set_stress_to_class(c) ((void)objspace, (c))
1451#endif
1452
1453#if 0
1454#define dont_gc_on() (fprintf(stderr, "dont_gc_on@%s:%d\n", __FILE__, __LINE__), objspace->flags.dont_gc = 1)
1455#define dont_gc_off() (fprintf(stderr, "dont_gc_off@%s:%d\n", __FILE__, __LINE__), objspace->flags.dont_gc = 0)
1456#define dont_gc_set(b) (fprintf(stderr, "dont_gc_set(%d)@%s:%d\n", __FILE__, __LINE__), objspace->flags.dont_gc = (int)(b))
1457#define dont_gc_val() (objspace->flags.dont_gc)
1458#else
1459#define dont_gc_on() (objspace->flags.dont_gc = 1)
1460#define dont_gc_off() (objspace->flags.dont_gc = 0)
1461#define dont_gc_set(b) (objspace->flags.dont_gc = (int)(b))
1462#define dont_gc_val() (objspace->flags.dont_gc)
1463#endif
1464
1465#define gc_config_full_mark_set(b) (objspace->gc_config.full_mark = (int)(b))
1466#define gc_config_full_mark_val (objspace->gc_config.full_mark)
1467
1468static inline enum gc_mode
1469gc_mode_verify(enum gc_mode mode)
1470{
1471#if RGENGC_CHECK_MODE > 0
1472 switch (mode) {
1473 case gc_mode_none:
1474 case gc_mode_marking:
1475 case gc_mode_sweeping:
1476 case gc_mode_compacting:
1477 break;
1478 default:
1479 rb_bug("gc_mode_verify: unreachable (%d)", (int)mode);
1480 }
1481#endif
1482 return mode;
1483}
1484
1485static inline bool
1486has_sweeping_pages(rb_objspace_t *objspace)
1487{
1488 return objspace->sweeping_heap_count != 0;
1489}
1490
1491static inline size_t
1492heap_eden_total_pages(rb_objspace_t *objspace)
1493{
1494 size_t count = 0;
1495 for (int i = 0; i < HEAP_COUNT; i++) {
1496 count += (&heaps[i])->total_pages;
1497 }
1498 return count;
1499}
1500
1501static inline size_t
1502total_allocated_objects(rb_objspace_t *objspace)
1503{
1504 size_t count = 0;
1505 for (int i = 0; i < HEAP_COUNT; i++) {
1506 rb_heap_t *heap = &heaps[i];
1507 count += heap->total_allocated_objects;
1508 }
1509 return count;
1510}
1511
1512static inline size_t
1513total_freed_objects(rb_objspace_t *objspace)
1514{
1515 size_t count = 0;
1516 for (int i = 0; i < HEAP_COUNT; i++) {
1517 rb_heap_t *heap = &heaps[i];
1518 count += heap->total_freed_objects;
1519 }
1520 return count;
1521}
1522
1523static inline size_t
1524total_final_slots_count(rb_objspace_t *objspace)
1525{
1526 size_t count = 0;
1527 for (int i = 0; i < HEAP_COUNT; i++) {
1528 rb_heap_t *heap = &heaps[i];
1529 count += heap->final_slots_count;
1530 }
1531 return count;
1532}
1533
1534#define gc_mode(objspace) gc_mode_verify((enum gc_mode)(objspace)->flags.mode)
1535#define gc_mode_set(objspace, m) ((objspace)->flags.mode = (unsigned int)gc_mode_verify(m))
1536#define gc_needs_major_flags objspace->rgengc.need_major_gc
1537
1538#define is_marking(objspace) (gc_mode(objspace) == gc_mode_marking)
1539#define is_sweeping(objspace) (gc_mode(objspace) == gc_mode_sweeping)
1540#define is_full_marking(objspace) ((objspace)->flags.during_minor_gc == FALSE)
1541#define is_incremental_marking(objspace) ((objspace)->flags.during_incremental_marking != FALSE)
1542#define will_be_incremental_marking(objspace) ((objspace)->rgengc.need_major_gc != GPR_FLAG_NONE)
1543/*
1544 * Byte budget for incremental sweep steps. Each step sweeps at most
1545 * this many bytes worth of slots before yielding. The effective slot
1546 * count per step is GC_INCREMENTAL_SWEEP_BYTES / heap->slot_size,
1547 * so larger slot pools (which are less heavily used) naturally get
1548 * fewer slots swept per step.
1549 *
1550 * Baseline: 2048 slots * RVALUE_SLOT_SIZE = 2048 * 40 = 81920 bytes,
1551 * preserving the historical behavior for the smallest heap.
1552 */
1553#define GC_INCREMENTAL_SWEEP_BYTES (2048 * RVALUE_SLOT_SIZE)
1554#define GC_INCREMENTAL_SWEEP_POOL_BYTES (1024 * RVALUE_SLOT_SIZE)
1555#define is_lazy_sweeping(objspace) (GC_ENABLE_LAZY_SWEEP && has_sweeping_pages(objspace))
1556/* In lazy sweeping or the previous incremental marking finished and did not yield a free page. */
1557#define needs_continue_sweeping(objspace, heap) \
1558 ((heap)->free_pages == NULL && is_lazy_sweeping(objspace))
1559
1560#if SIZEOF_LONG == SIZEOF_VOIDP
1561# define obj_id_to_ref(objid) ((objid) ^ FIXNUM_FLAG) /* unset FIXNUM_FLAG */
1562#elif SIZEOF_LONG_LONG == SIZEOF_VOIDP
1563# define obj_id_to_ref(objid) (FIXNUM_P(objid) ? \
1564 ((objid) ^ FIXNUM_FLAG) : (NUM2PTR(objid) << 1))
1565#else
1566# error not supported
1567#endif
1568
1569struct RZombie {
1570 VALUE flags;
1571 VALUE next;
1572 void (*dfree)(void *);
1573 void *data;
1574};
1575
1576#define RZOMBIE(o) ((struct RZombie *)(o))
1577
1578static bool ruby_enable_autocompact = false;
1579#if RGENGC_CHECK_MODE
1580static gc_compact_compare_func ruby_autocompact_compare_func;
1581#endif
1582
1583static void init_mark_stack(mark_stack_t *stack);
1584static int garbage_collect(rb_objspace_t *, unsigned int reason);
1585
1586static int gc_start(rb_objspace_t *objspace, unsigned int reason);
1587static void gc_rest(rb_objspace_t *objspace);
1588
1589/* GC cycle events (ENTER, EXIT, START, END_MARK, END_SWEEP) fire only if the objspace's
1590 * own Ractor enabled them, so a concurrent local GC never walks the VM-global hook list
1591 * while another Ractor mutates it. NEWOBJ and FREEOBJ were already restricted. */
1592#define gc_event_hook(objspace, event) do { \
1593 if (RB_UNLIKELY((objspace)->hook_events & (event))) { \
1594 rb_gc_event_hook(0, (event)); \
1595 } \
1596} while (0)
1597
1598enum gc_enter_event {
1599 gc_enter_event_start,
1600 gc_enter_event_continue,
1601 gc_enter_event_rest,
1602 gc_enter_event_finalizer,
1603 gc_enter_event_global,
1604 gc_enter_event_global_auto,
1605};
1606
1607static inline bool gc_enter(rb_objspace_t *objspace, enum gc_enter_event event, unsigned int *lock_lev);
1608static inline void gc_exit(rb_objspace_t *objspace, enum gc_enter_event event, unsigned int *lock_lev);
1609static void gc_marking_enter(rb_objspace_t *objspace);
1610static void gc_marking_exit(rb_objspace_t *objspace);
1611static void gc_sweeping_enter(rb_objspace_t *objspace);
1612static void gc_sweeping_exit(rb_objspace_t *objspace);
1613static bool gc_marks_continue(rb_objspace_t *objspace, rb_heap_t *heap);
1614
1615static void gc_sweep(rb_objspace_t *objspace);
1616static void gc_sweep_finish_heap(rb_objspace_t *objspace, rb_heap_t *heap);
1617static void gc_sweep_continue(rb_objspace_t *objspace, rb_heap_t *heap);
1618
1619static inline void gc_mark(rb_objspace_t *objspace, VALUE ptr);
1620static inline void gc_pin(rb_objspace_t *objspace, VALUE ptr);
1621static inline void gc_mark_and_pin(rb_objspace_t *objspace, VALUE ptr);
1622
1623static int gc_mark_stacked_objects_incremental(rb_objspace_t *, size_t count);
1624NO_SANITIZE("memory", static inline bool is_pointer_to_heap(rb_objspace_t *objspace, const void *ptr));
1625
1626static void gc_verify_internal_consistency(void *objspace_ptr);
1627
1628static double getrusage_time(void);
1629static inline rb_hrtime_t elapsed_hrtime_from(rb_hrtime_t start);
1630static inline void gc_prof_setup_new_record(rb_objspace_t *objspace, unsigned int reason);
1631static inline void gc_prof_timer_start(rb_objspace_t *);
1632static inline void gc_prof_timer_stop(rb_objspace_t *);
1633static inline void gc_prof_mark_timer_start(rb_objspace_t *);
1634static inline void gc_prof_mark_timer_stop(rb_objspace_t *);
1635static inline void gc_prof_sweep_timer_start(rb_objspace_t *);
1636static inline void gc_prof_sweep_timer_stop(rb_objspace_t *);
1637static inline void gc_prof_set_malloc_info(rb_objspace_t *);
1638static inline void gc_prof_set_heap_info(rb_objspace_t *);
1639
1640#define gc_prof_record(objspace) (objspace)->profile.current_record
1641#define gc_prof_enabled(objspace) ((objspace)->profile.run && (objspace)->profile.current_record)
1642
1643#define gc_report(level, objspace, ...) \
1644 if (!RGENGC_DEBUG_ENABLED(level)) {} else gc_report_body(level, objspace, __VA_ARGS__)
1645PRINTF_ARGS(static void gc_report_body(int level, rb_objspace_t *objspace, const char *fmt, ...), 3, 4);
1646
1647static void gc_finalize_deferred(void *dmy);
1648static void gc_tdata_unsafe_drain_objspaces(rb_objspace_t **objspaces, size_t n);
1649
1650#if USE_TICK_T
1651
1652/* the following code is only for internal tuning. */
1653
1654/* Source code to use RDTSC is quoted and modified from
1655 * https://www.mcs.anl.gov/~kazutomo/rdtsc.html
1656 * written by Kazutomo Yoshii <kazutomo@mcs.anl.gov>
1657 */
1658
1659#if defined(__GNUC__) && defined(__i386__)
1660typedef unsigned long long tick_t;
1661#define PRItick "llu"
1662static inline tick_t
1663tick(void)
1664{
1665 unsigned long long int x;
1666 __asm__ __volatile__ ("rdtsc" : "=A" (x));
1667 return x;
1668}
1669
1670#elif defined(__GNUC__) && defined(__x86_64__)
1671typedef unsigned long long tick_t;
1672#define PRItick "llu"
1673
1674static __inline__ tick_t
1675tick(void)
1676{
1677 unsigned long hi, lo;
1678 __asm__ __volatile__ ("rdtsc" : "=a"(lo), "=d"(hi));
1679 return ((unsigned long long)lo)|( ((unsigned long long)hi)<<32);
1680}
1681
1682#elif defined(__powerpc64__) && (GCC_VERSION_SINCE(4,8,0) || defined(__clang__))
1683typedef unsigned long long tick_t;
1684#define PRItick "llu"
1685
1686static __inline__ tick_t
1687tick(void)
1688{
1689 unsigned long long val = __builtin_ppc_get_timebase();
1690 return val;
1691}
1692
1693#elif defined(__POWERPC__) && defined(__APPLE__)
1694/* Implementation for macOS PPC by @nobu
1695 * See: https://github.com/ruby/ruby/pull/5975#discussion_r890045558
1696 */
1697typedef unsigned long long tick_t;
1698#define PRItick "llu"
1699
1700static __inline__ tick_t
1701tick(void)
1702{
1703 unsigned long int upper, lower, tmp;
1704 # define mftbu(r) __asm__ volatile("mftbu %0" : "=r"(r))
1705 # define mftb(r) __asm__ volatile("mftb %0" : "=r"(r))
1706 do {
1707 mftbu(upper);
1708 mftb(lower);
1709 mftbu(tmp);
1710 } while (tmp != upper);
1711 return ((tick_t)upper << 32) | lower;
1712}
1713
1714#elif defined(__aarch64__) && defined(__GNUC__)
1715typedef unsigned long tick_t;
1716#define PRItick "lu"
1717
1718static __inline__ tick_t
1719tick(void)
1720{
1721 unsigned long val;
1722 __asm__ __volatile__ ("mrs %0, cntvct_el0" : "=r" (val));
1723 return val;
1724}
1725
1726
1727#elif defined(_WIN32) && defined(_MSC_VER)
1728#include <intrin.h>
1729typedef unsigned __int64 tick_t;
1730#define PRItick "llu"
1731
1732static inline tick_t
1733tick(void)
1734{
1735 return __rdtsc();
1736}
1737
1738#else /* use clock */
1739typedef clock_t tick_t;
1740#define PRItick "llu"
1741
1742static inline tick_t
1743tick(void)
1744{
1745 return clock();
1746}
1747#endif /* TSC */
1748#else /* USE_TICK_T */
1749#define MEASURE_LINE(expr) expr
1750#endif /* USE_TICK_T */
1751
1752static inline VALUE check_rvalue_consistency(rb_objspace_t *objspace, const VALUE obj);
1753
1754#define RVALUE_MARKED_BITMAP(obj) MARKED_IN_BITMAP(GET_HEAP_MARK_BITS(obj), (obj))
1755#define RVALUE_WB_UNPROTECTED_BITMAP(obj) MARKED_IN_BITMAP(GET_HEAP_WB_UNPROTECTED_BITS(obj), (obj))
1756#define RVALUE_MARKING_BITMAP(obj) MARKED_IN_BITMAP(GET_HEAP_MARKING_BITS(obj), (obj))
1757#define RVALUE_UNCOLLECTIBLE_BITMAP(obj) MARKED_IN_BITMAP(GET_HEAP_UNCOLLECTIBLE_BITS(obj), (obj))
1758#define RVALUE_PINNED_BITMAP(obj) MARKED_IN_BITMAP(GET_HEAP_PINNED_BITS(obj), (obj))
1759
1760static inline int
1761RVALUE_MARKED(rb_objspace_t *objspace, VALUE obj)
1762{
1763 check_rvalue_consistency(objspace, obj);
1764 return RVALUE_MARKED_BITMAP(obj) != 0;
1765}
1766
1767static inline int
1768RVALUE_PINNED(rb_objspace_t *objspace, VALUE obj)
1769{
1770 check_rvalue_consistency(objspace, obj);
1771 return RVALUE_PINNED_BITMAP(obj) != 0;
1772}
1773
1774static inline int
1775RVALUE_WB_UNPROTECTED(rb_objspace_t *objspace, VALUE obj)
1776{
1777 check_rvalue_consistency(objspace, obj);
1778 return RVALUE_WB_UNPROTECTED_BITMAP(obj) != 0;
1779}
1780
1781static inline int
1782RVALUE_MARKING(rb_objspace_t *objspace, VALUE obj)
1783{
1784 check_rvalue_consistency(objspace, obj);
1785 return RVALUE_MARKING_BITMAP(obj) != 0;
1786}
1787
1788static inline int
1789RVALUE_REMEMBERED(rb_objspace_t *objspace, VALUE obj)
1790{
1791 check_rvalue_consistency(objspace, obj);
1792 return MARKED_IN_BITMAP(GET_HEAP_PAGE(obj)->remembered_bits, obj) != 0;
1793}
1794
1795static inline int
1796RVALUE_UNCOLLECTIBLE(rb_objspace_t *objspace, VALUE obj)
1797{
1798 check_rvalue_consistency(objspace, obj);
1799 return RVALUE_UNCOLLECTIBLE_BITMAP(obj) != 0;
1800}
1801
1802#define RVALUE_PAGE_WB_UNPROTECTED(page, obj) MARKED_IN_BITMAP((page)->wb_unprotected_bits, (obj))
1803#define RVALUE_PAGE_UNCOLLECTIBLE(page, obj) MARKED_IN_BITMAP((page)->uncollectible_bits, (obj))
1804#define RVALUE_PAGE_MARKING(page, obj) MARKED_IN_BITMAP((page)->marking_bits, (obj))
1805
1806static void rgengc_remember(rb_objspace_t *objspace, VALUE obj);
1807static void gc_bitmaps_clear(rb_objspace_t *objspace, rb_heap_t *heap, bool clear_shref);
1808static void rgengc_rememberset_mark(rb_objspace_t *objspace, rb_heap_t *heap);
1809static bool verify_pointer_in_any_heap_p(const void *ptr); /* cross-objspace ownership test */
1810
1811static int
1812check_rvalue_consistency_force(rb_objspace_t *objspace, const VALUE obj, int terminate)
1813{
1814 int err = 0;
1815
1816 /* Under a global GC the barrier stops every Ractor, so the cross-objspace walk
1817 * below is safe without the VM lock. Sweeping an ownerless zombie objspace also
1818 * leaves GET_RACTOR() NULL, and taking the lock here would dereference it. */
1819 const bool world_stopped = objspace->flags.during_global_gc;
1820 /* The VM lock protects the cross-objspace walk while other Ractors run and
1821 * reallocate their heaps. Not taken while this objspace is in GC: pages are stable
1822 * then, the cross-objspace walk needs the world stopped anyway, and the Ractor lock
1823 * may already be held (Ractor -> VM order inversion). A global GC holds the barrier
1824 * and needs no lock. */
1825 const bool take_vm_lock = !world_stopped && !during_gc;
1826 unsigned int lev = 0;
1827 if (take_vm_lock) lev = RB_GC_VM_LOCK_NO_BARRIER();
1828 {
1829 if (SPECIAL_CONST_P(obj)) {
1830 fprintf(stderr, "check_rvalue_consistency: %p is a special const.\n", (void *)obj);
1831 err++;
1832 }
1833 else if (!is_pointer_to_heap(objspace, (void *)obj)) {
1834 /* obj may be a legitimate cross-objspace reference (a shareable object, an
1835 * in-flight shref payload); it is a non-object only if no objspace's heap
1836 * holds it. A foreign object's mark/age/remembered bits belong to its
1837 * owner and reading them would race its local GC: skip per-object checks. */
1838 if (!world_stopped) {
1839 /* A mid-local-GC verify holds no barrier, so other Ractors reallocate
1840 * heap_pages.sorted under verify_pointer_in_any_heap_p's page_index
1841 * read. Accept foreign pointers here; the global GC's world-stopped
1842 * verify does the full existence check. */
1843 }
1844 else if (!verify_pointer_in_any_heap_p((void *)obj)) {
1845 struct heap_page *empty_page = objspace->empty_pages;
1846 while (empty_page) {
1847 if ((uintptr_t)empty_page->body <= (uintptr_t)obj &&
1848 (uintptr_t)obj < (uintptr_t)empty_page->body + HEAP_PAGE_SIZE) {
1849 GC_ASSERT(heap_page_in_global_empty_pages_pool(objspace, empty_page));
1850 fprintf(stderr, "check_rvalue_consistency: %p is in an empty page (%p).\n",
1851 (void *)obj, (void *)empty_page);
1852 err++;
1853 goto skip;
1854 }
1855 empty_page = empty_page->free_next;
1856 }
1857 fprintf(stderr, "check_rvalue_consistency: %p is not a Ruby object.\n", (void *)obj);
1858 err++;
1859 skip:
1860 ;
1861 }
1862 }
1863 else {
1864 const int wb_unprotected_bit = RVALUE_WB_UNPROTECTED_BITMAP(obj) != 0;
1865 const int uncollectible_bit = RVALUE_UNCOLLECTIBLE_BITMAP(obj) != 0;
1866 const int mark_bit = RVALUE_MARKED_BITMAP(obj) != 0;
1867 const int marking_bit = RVALUE_MARKING_BITMAP(obj) != 0;
1868 const int remembered_bit = MARKED_IN_BITMAP(GET_HEAP_PAGE(obj)->remembered_bits, obj) != 0;
1869 const int age = RVALUE_AGE_GET((VALUE)obj);
1870
1871 if (heap_page_in_global_empty_pages_pool(objspace, GET_HEAP_PAGE(obj))) {
1872 fprintf(stderr, "check_rvalue_consistency: %s is in tomb page.\n", rb_obj_info(obj));
1873 err++;
1874 }
1875 if (BUILTIN_TYPE(obj) == T_NONE) {
1876 fprintf(stderr, "check_rvalue_consistency: %s is T_NONE.\n", rb_obj_info(obj));
1877 err++;
1878 }
1879 if (BUILTIN_TYPE(obj) == T_ZOMBIE) {
1880 fprintf(stderr, "check_rvalue_consistency: %s is T_ZOMBIE.\n", rb_obj_info(obj));
1881 err++;
1882 }
1883
1884 /* Do not run the memsize probe once an inconsistency (a T_NONE, say) was
1885 * found: an rb_bug inside the probe would lose the real diagnosis. */
1886 if (err == 0 && BUILTIN_TYPE(obj) != T_DATA) {
1887 rb_obj_memsize_of((VALUE)obj);
1888 }
1889
1890 /* check generation
1891 *
1892 * OLD == age == 3 && old-bitmap && mark-bit (except incremental marking)
1893 */
1894 if (age > 0 && wb_unprotected_bit) {
1895 fprintf(stderr, "check_rvalue_consistency: %s is not WB protected, but age is %d > 0.\n", rb_obj_info(obj), age);
1896 err++;
1897 }
1898
1899 if (!is_marking(objspace) && uncollectible_bit && !mark_bit) {
1900 fprintf(stderr, "check_rvalue_consistency: %s is uncollectible, but is not marked while !gc.\n", rb_obj_info(obj));
1901 err++;
1902 }
1903
1904 if (!is_full_marking(objspace)) {
1905 if (uncollectible_bit && age != RVALUE_OLD_AGE && !wb_unprotected_bit) {
1906 fprintf(stderr, "check_rvalue_consistency: %s is uncollectible, but not old (age: %d) and not WB unprotected.\n",
1907 rb_obj_info(obj), age);
1908 err++;
1909 }
1910 if (remembered_bit && age != RVALUE_OLD_AGE) {
1911 fprintf(stderr, "check_rvalue_consistency: %s is remembered, but not old (age: %d).\n",
1912 rb_obj_info(obj), age);
1913 err++;
1914 }
1915 }
1916
1917 /*
1918 * check coloring
1919 *
1920 * marking:false marking:true
1921 * marked:false white *invalid*
1922 * marked:true black grey
1923 */
1924 if (is_incremental_marking(objspace) && marking_bit) {
1925 if (!is_marking(objspace) && !mark_bit) {
1926 fprintf(stderr, "check_rvalue_consistency: %s is marking, but not marked.\n", rb_obj_info(obj));
1927 err++;
1928 }
1929 }
1930 }
1931 }
1932 if (take_vm_lock) RB_GC_VM_UNLOCK_NO_BARRIER(lev);
1933
1934 if (err > 0 && terminate) {
1935 rb_bug("check_rvalue_consistency_force: there is %d errors.", err);
1936 }
1937 return err;
1938}
1939
1940#if RGENGC_CHECK_MODE == 0
1941static inline VALUE
1942check_rvalue_consistency(rb_objspace_t *objspace, const VALUE obj)
1943{
1944 return obj;
1945}
1946#else
1947static VALUE
1948check_rvalue_consistency(rb_objspace_t *objspace, const VALUE obj)
1949{
1950 check_rvalue_consistency_force(objspace, obj, TRUE);
1951 return obj;
1952}
1953#endif
1954
1955static inline bool
1956gc_object_moved_p(rb_objspace_t *objspace, VALUE obj)
1957{
1958
1959 bool ret;
1960 asan_unpoisoning_object(obj) {
1961 ret = BUILTIN_TYPE(obj) == T_MOVED;
1962 }
1963 return ret;
1964}
1965
1966static inline int
1967RVALUE_OLD_P(rb_objspace_t *objspace, VALUE obj)
1968{
1969 GC_ASSERT(!RB_SPECIAL_CONST_P(obj));
1970 check_rvalue_consistency(objspace, obj);
1971 // Because this will only ever be called on GC controlled objects,
1972 // we can use the faster _RAW function here
1973 return RB_OBJ_PROMOTED_RAW(obj);
1974}
1975
1976static inline void
1977RVALUE_PAGE_OLD_UNCOLLECTIBLE_SET(rb_objspace_t *objspace, struct heap_page *page, VALUE obj)
1978{
1979 MARK_IN_BITMAP(&page->uncollectible_bits[0], obj);
1980 /* Count a promotion in the object's own objspace: a global GC ages every objspace's
1981 * slots from the driver, and counting them there would skew the other objspaces'
1982 * old_objects and with it their major GC frequency. */
1983 page->objspace->rgengc.old_objects++;
1984
1985#if RGENGC_PROFILE >= 2
1986 objspace->profile.total_promoted_count++;
1987 objspace->profile.promoted_types[BUILTIN_TYPE(obj)]++;
1988#endif
1989}
1990
1991static inline void
1992RVALUE_OLD_UNCOLLECTIBLE_SET(rb_objspace_t *objspace, VALUE obj)
1993{
1994 RB_DEBUG_COUNTER_INC(obj_promote);
1995 RVALUE_PAGE_OLD_UNCOLLECTIBLE_SET(objspace, GET_HEAP_PAGE(obj), obj);
1996}
1997
1998/* set age to age+1 */
1999static inline void
2000RVALUE_AGE_INC(rb_objspace_t *objspace, VALUE obj)
2001{
2002 int age = RVALUE_AGE_GET((VALUE)obj);
2003
2004 if (RGENGC_CHECK_MODE && age == RVALUE_OLD_AGE) {
2005 rb_bug("RVALUE_AGE_INC: can not increment age of OLD object %s.", rb_obj_info(obj));
2006 }
2007
2008 age++;
2009 RVALUE_AGE_SET(obj, age);
2010
2011 if (age == RVALUE_OLD_AGE) {
2012 RVALUE_OLD_UNCOLLECTIBLE_SET(objspace, obj);
2013 }
2014
2015 check_rvalue_consistency(objspace, obj);
2016}
2017
2018static inline void
2019RVALUE_AGE_SET_CANDIDATE(rb_objspace_t *objspace, VALUE obj)
2020{
2021 check_rvalue_consistency(objspace, obj);
2022 GC_ASSERT(!RVALUE_OLD_P(objspace, obj));
2023 RVALUE_AGE_SET(obj, RVALUE_OLD_AGE - 1);
2024 check_rvalue_consistency(objspace, obj);
2025}
2026
2027static inline void
2028RVALUE_AGE_RESET(VALUE obj)
2029{
2030 RVALUE_AGE_SET(obj, 0);
2031}
2032
2033static inline void
2034RVALUE_DEMOTE(rb_objspace_t *objspace, VALUE obj)
2035{
2036 check_rvalue_consistency(objspace, obj);
2037 GC_ASSERT(RVALUE_OLD_P(objspace, obj));
2038
2039 if (!is_incremental_marking(objspace) && RVALUE_REMEMBERED(objspace, obj)) {
2040 struct heap_page *page = GET_HEAP_PAGE(obj);
2041 _CLEAR_IN_BITMAP(page->remembered_bits, page, obj);
2042 }
2043
2044 CLEAR_IN_BITMAP(GET_HEAP_UNCOLLECTIBLE_BITS(obj), obj);
2045 RVALUE_AGE_RESET(obj);
2046
2047 if (RVALUE_MARKED(objspace, obj)) {
2048 /* symmetric with RVALUE_PAGE_OLD_UNCOLLECTIBLE_SET */
2049 GET_HEAP_PAGE(obj)->objspace->rgengc.old_objects--;
2050 }
2051
2052 check_rvalue_consistency(objspace, obj);
2053}
2054
2055static inline int
2056RVALUE_BLACK_P(rb_objspace_t *objspace, VALUE obj)
2057{
2058 return RVALUE_MARKED(objspace, obj) && !RVALUE_MARKING(objspace, obj);
2059}
2060
2061static inline int
2062RVALUE_WHITE_P(rb_objspace_t *objspace, VALUE obj)
2063{
2064 return !RVALUE_MARKED(objspace, obj);
2065}
2066
2067bool
2068rb_gc_impl_user_gc_disabled_set(void *objspace_ptr, bool disable)
2069{
2070 rb_objspace_t *objspace = objspace_ptr;
2071 const bool was = objspace->flags.user_gc_disabled;
2072 objspace->flags.user_gc_disabled = disable;
2073 return was;
2074}
2075
2076bool
2077rb_gc_impl_user_gc_disabled_p(void *objspace_ptr)
2078{
2079 rb_objspace_t *objspace = objspace_ptr;
2080 return objspace->flags.user_gc_disabled;
2081}
2082
2083bool
2084rb_gc_impl_gc_enabled_p(void *objspace_ptr)
2085{
2086 rb_objspace_t *objspace = objspace_ptr;
2087 return !dont_gc_val();
2088}
2089
2090void
2091rb_gc_impl_gc_enable(void *objspace_ptr)
2092{
2093 rb_objspace_t *objspace = objspace_ptr;
2094
2095 dont_gc_off();
2096}
2097
2098void
2099rb_gc_impl_gc_disable(void *objspace_ptr, bool finish_current_gc)
2100{
2101 rb_objspace_t *objspace = objspace_ptr;
2102
2103 if (finish_current_gc) {
2104 gc_rest(objspace);
2105 }
2106
2107 dont_gc_on();
2108}
2109
2110/* Finish an incremental mark or lazy sweep in progress without changing the enabled
2111 * state. gc.c uses it to settle the only objspace just before the process goes
2112 * multi-objspace. */
2113void
2114rb_gc_impl_gc_rest(void *objspace_ptr)
2115{
2116 gc_rest(objspace_ptr);
2117}
2118
2119/*
2120 --------------------------- ObjectSpace -----------------------------
2121*/
2122
2123static inline void *
2124calloc1(size_t n)
2125{
2126 return calloc(1, n);
2127}
2128
2129void
2130rb_gc_impl_set_event_hook(void *objspace_ptr, const rb_event_flag_t event)
2131{
2132 rb_objspace_t *objspace = objspace_ptr;
2133 /* FREEOBJ is main-objspace only (rb_objspace_set_event_hook masks it elsewhere). */
2134 GC_ASSERT(!(event & RUBY_INTERNAL_EVENT_FREEOBJ) ||
2135 objspace == global_objspace->main_objspace);
2136 objspace->hook_events = event & RUBY_INTERNAL_EVENT_OBJSPACE_MASK;
2137}
2138
2139unsigned long long
2140rb_gc_impl_get_total_time(void *objspace_ptr)
2141{
2142 rb_objspace_t *objspace = objspace_ptr;
2143
2144 unsigned long long marking_time = objspace->profile.marking_time_ns;
2145 unsigned long long sweeping_time = objspace->profile.sweeping_time_ns;
2146
2147 return marking_time + sweeping_time;
2148}
2149
2150void
2151rb_gc_impl_set_measure_total_time(void *objspace_ptr, VALUE flag)
2152{
2153 rb_objspace_t *objspace = objspace_ptr;
2154
2155 objspace->flags.measure_gc = RTEST(flag) ? TRUE : FALSE;
2156}
2157
2158bool
2159rb_gc_impl_get_measure_total_time(void *objspace_ptr)
2160{
2161 rb_objspace_t *objspace = objspace_ptr;
2162
2163 return objspace->flags.measure_gc;
2164}
2165
2166static void
2167gc_process_stat_capture(const rb_objspace_t *objspace,
2168 struct gc_process_stat_snapshot *out)
2169{
2170 out->count = objspace->profile.count;
2171 out->minor_gc_count = objspace->profile.minor_gc_count;
2172 out->major_gc_count = objspace->profile.major_gc_count;
2173 out->global_gc_count = objspace->profile.global_gc_count;
2174 out->marking_time_ns = objspace->profile.marking_time_ns;
2175 out->sweeping_time_ns = objspace->profile.sweeping_time_ns;
2176}
2177
2178static void
2179gc_process_stat_publish(rb_objspace_t *objspace)
2180{
2181 struct gc_process_stat_snapshot snap;
2182 gc_process_stat_capture(objspace, &snap);
2183 GC_ASSERT(snap.count == snap.minor_gc_count + snap.major_gc_count + snap.global_gc_count);
2184 rb_native_mutex_lock(&objspace->process_stat.lock);
2185 objspace->process_stat.published = snap;
2186 rb_native_mutex_unlock(&objspace->process_stat.lock);
2187}
2188
2189static void
2190gc_process_stat_add(struct gc_process_stat_total *dst,
2191 const struct gc_process_stat_snapshot *src)
2192{
2193 dst->count += src->count;
2194 dst->minor_gc_count += src->minor_gc_count;
2195 dst->major_gc_count += src->major_gc_count;
2196 dst->global_gc_count += src->global_gc_count;
2197 dst->marking_time_ns += src->marking_time_ns;
2198 dst->sweeping_time_ns += src->sweeping_time_ns;
2199}
2200
2201/* garbage objects will be collected soon. */
2202bool
2203rb_gc_impl_garbage_object_p(void *objspace_ptr, VALUE ptr)
2204{
2205 rb_objspace_t *objspace = objspace_ptr;
2206
2207 /* A foreign object is a live leaf: reading its type or mark bit would race the
2208 * owner's local GC, so outside a global GC's barrier never report it as garbage.
2209 * The fstring/symbol weak-set lookups do reach across objspaces, but those objects
2210 * are born shareable and only a stop-the-world global GC collects them, so "not
2211 * garbage" is correct. */
2212 if (gc_skip_foreign_object_p(objspace, ptr)) {
2213 return false;
2214 }
2215
2216 /* Asking whether a freed (T_NONE), moved (T_MOVED), or finalized (T_ZOMBIE)
2217 * object is garbage gives an unreliable answer: the slot may since have been
2218 * reused for an unrelated object. A reference to one of these is stale and a
2219 * bug in the caller. */
2220 asan_unpoisoning_object(ptr) {
2221 GC_ASSERT(BUILTIN_TYPE(ptr) != T_NONE);
2222 GC_ASSERT(BUILTIN_TYPE(ptr) != T_MOVED);
2223 GC_ASSERT(BUILTIN_TYPE(ptr) != T_ZOMBIE);
2224 }
2225
2226 return is_lazy_sweeping(objspace) && GET_HEAP_PAGE(ptr)->flags.before_sweep &&
2227 !RVALUE_MARKED(objspace, ptr);
2228}
2229
2230struct rb_gc_vm_context *
2231rb_gc_impl_get_vm_context(void *objspace_ptr)
2232{
2233 rb_objspace_t *objspace = objspace_ptr;
2234
2235 return &objspace->vm_context;
2236}
2237
2238static void free_stack_chunks(mark_stack_t *);
2239static void mark_stack_free_cache(mark_stack_t *);
2240static void heap_page_free(rb_objspace_t *objspace, struct heap_page *page);
2241
2242static inline void
2243gc_check_obj_in_page(struct heap_page *page, VALUE obj)
2244{
2245 if (RGENGC_CHECK_MODE &&
2246 /* obj should belong to page */
2247 !(page->start <= (uintptr_t)obj &&
2248 (uintptr_t)obj < ((uintptr_t)page->start + (page->total_slots * page->slot_size)) &&
2249 obj % sizeof(VALUE) == 0)) {
2250 rb_bug("gc_check_obj_in_page: %p is not rvalue.", (void *)obj);
2251 }
2252}
2253
2254static inline void
2255heap_page_add_free_region(rb_objspace_t *objspace, struct heap_page *page, VALUE obj)
2256{
2257 rb_asan_unpoison_object(obj, false);
2258
2259 // Should have already been reset
2260 GC_ASSERT(RVALUE_AGE_GET(obj) == 0);
2261
2262 gc_check_obj_in_page(page, obj);
2263
2264 asan_unlock_freelist(page);
2265
2266 /* Keep a freed slot from carrying its old shareable and shref bits into the next
2267 * object born there. */
2268 CLEAR_IN_BITMAP(GET_HEAP_SHAREABLE_BITS(obj), obj);
2269 CLEAR_IN_BITMAP(GET_HEAP_SHREF_BITS(obj), obj);
2270
2271 struct free_region *region = (struct free_region *)obj;
2272 region->flags = 0;
2273 region->end = (uintptr_t)obj + page->slot_size;
2274 region->next = page->free_region;
2275 page->free_region = region;
2276
2277 asan_lock_freelist(page);
2278
2279 rb_asan_poison_object(obj);
2280 gc_report(3, objspace, "heap_page_add_free_region: %p\n", (void *)obj);
2281}
2282
2283/* The initial size is per objspace, so a Ractor's own gets a smaller one than
2284 * main's rather than paying main's again. */
2285static inline size_t
2286objspace_heap_init_bytes(const rb_objspace_t *objspace)
2287{
2288 return objspace == global_objspace->main_objspace
2289 ? gc_params.heap_init_bytes : gc_params.ractor_heap_init_bytes;
2290}
2291
2292static void
2293heap_allocatable_bytes_expand(rb_objspace_t *objspace,
2294 rb_heap_t *heap, size_t free_slots, size_t total_slots, size_t slot_size)
2295{
2296 double goal_ratio = gc_params.heap_free_slots_goal_ratio;
2297 size_t target_total_slots;
2298
2299 if (goal_ratio == 0.0) {
2300 target_total_slots = (size_t)(total_slots * gc_params.growth_factor);
2301 }
2302 else if (total_slots == 0) {
2303 target_total_slots = objspace_heap_init_bytes(objspace) / slot_size;
2304 }
2305 else {
2306 /* Find `f' where free_slots = f * total_slots * goal_ratio
2307 * => f = (total_slots - free_slots) / ((1 - goal_ratio) * total_slots)
2308 */
2309 double f = (double)(total_slots - free_slots) / ((1 - goal_ratio) * total_slots);
2310
2311 if (f > gc_params.growth_factor) f = gc_params.growth_factor;
2312 if (f < 1.0) f = 1.1;
2313
2314 target_total_slots = (size_t)(f * total_slots);
2315
2316 if (0) {
2317 fprintf(stderr,
2318 "free_slots(%8"PRIuSIZE")/total_slots(%8"PRIuSIZE")=%1.2f,"
2319 " G(%1.2f), f(%1.2f),"
2320 " total_slots(%8"PRIuSIZE") => target_total_slots(%8"PRIuSIZE")\n",
2321 free_slots, total_slots, free_slots/(double)total_slots,
2322 goal_ratio, f, total_slots, target_total_slots);
2323 }
2324 }
2325
2326 if (gc_params.growth_max_bytes > 0) {
2327 size_t max_total_slots = total_slots + gc_params.growth_max_bytes / slot_size;
2328 if (target_total_slots > max_total_slots) target_total_slots = max_total_slots;
2329 }
2330
2331 size_t extend_slot_count = target_total_slots - total_slots;
2332 /* Extend by at least 1 page. */
2333 if (extend_slot_count == 0) extend_slot_count = 1;
2334
2335 objspace->heap_pages.allocatable_bytes += extend_slot_count * slot_size;
2336}
2337
2338static inline void
2339heap_add_freepage(rb_heap_t *heap, struct heap_page *page)
2340{
2341 asan_unlock_freelist(page);
2342 GC_ASSERT(page->free_slots != 0);
2343 GC_ASSERT(page->free_region != NULL);
2344
2345 page->free_next = heap->free_pages;
2346 heap->free_pages = page;
2347
2348 RUBY_DEBUG_LOG("page:%p free_region:%p", (void *)page, (void *)page->free_region);
2349
2350 asan_lock_freelist(page);
2351}
2352
2353static inline void
2354heap_add_poolpage(rb_objspace_t *objspace, rb_heap_t *heap, struct heap_page *page)
2355{
2356 asan_unlock_freelist(page);
2357 GC_ASSERT(page->free_slots != 0);
2358 GC_ASSERT(page->free_region != NULL);
2359
2360 page->free_next = heap->pooled_pages;
2361 heap->pooled_pages = page;
2362 objspace->rincgc.pooled_slots += page->free_slots;
2363
2364 asan_lock_freelist(page);
2365}
2366
2367static void
2368heap_unlink_page(rb_objspace_t *objspace, rb_heap_t *heap, struct heap_page *page)
2369{
2370 ccan_list_del(&page->page_node);
2371 heap->total_pages--;
2372 heap->total_slots -= page->total_slots;
2373}
2374
2375static void
2376gc_aligned_free(void *ptr, size_t size)
2377{
2378#if defined __MINGW32__
2379 __mingw_aligned_free(ptr);
2380#elif defined _WIN32
2381 _aligned_free(ptr);
2382#elif defined(HAVE_POSIX_MEMALIGN) || defined(HAVE_MEMALIGN)
2383 free(ptr);
2384#else
2385 free(((void**)ptr)[-1]);
2386#endif
2387}
2388
2389static void
2390heap_page_body_free(struct heap_page_body *page_body, struct page_arena *arena)
2391{
2392 GC_ASSERT((uintptr_t)page_body % HEAP_PAGE_ALIGN == 0);
2393
2394 page_pool_release(page_body, arena);
2395}
2396
2397#ifdef PAGE_POOL_LOCK_ERRORCHECK
2398# define ASSERT_PAGE_POOL_LOCKED(g) GC_ASSERT(pthread_mutex_lock(&(g)->page_pool.lock) == EDEADLK)
2399#else
2400# define ASSERT_PAGE_POOL_LOCKED(g) ((void)0)
2401#endif
2402
2403/* Insert into page_index. Writers serialize on page_pool.lock; lomem and himem are a
2404 * monotonically growing over-approximation used for a quick reject. */
2405static void
2406global_page_index_insert(struct heap_page *page)
2407{
2408 rb_global_objspace_t *g = global_objspace;
2409 uintptr_t body = (uintptr_t)page->body;
2410
2411 rb_native_mutex_lock(&g->page_pool.lock);
2412 if (g->page_index.n_pages == g->page_index.capa) {
2413 size_t new_capa = g->page_index.capa ? g->page_index.capa * 2 : 128;
2414 struct heap_page **grown = realloc(g->page_index.pages, new_capa * sizeof(*grown));
2415 if (grown == NULL) rb_bug("global_page_index_insert: realloc failed");
2416 g->page_index.pages = grown;
2417 g->page_index.capa = new_capa;
2418 }
2419 size_t lo = 0, hi = g->page_index.n_pages;
2420 while (lo < hi) {
2421 size_t mid = (lo + hi) / 2;
2422 if ((uintptr_t)g->page_index.pages[mid]->body < body) lo = mid + 1;
2423 else hi = mid;
2424 }
2425 memmove(&g->page_index.pages[lo + 1], &g->page_index.pages[lo],
2426 (g->page_index.n_pages - lo) * sizeof(struct heap_page *));
2427 g->page_index.pages[lo] = page;
2428 g->page_index.n_pages++;
2429
2430 uintptr_t start = body + sizeof(struct heap_page_header);
2431 uintptr_t end = body + HEAP_PAGE_SIZE;
2432 if (g->page_index.lomem == 0 || g->page_index.lomem > start) g->page_index.lomem = start;
2433 if (g->page_index.himem < end) g->page_index.himem = end;
2434 rb_native_mutex_unlock(&g->page_pool.lock);
2435}
2436
2437static void
2438global_page_index_remove_locked(const struct heap_page *page)
2439{
2440 rb_global_objspace_t *g = global_objspace;
2441 uintptr_t body = (uintptr_t)page->body;
2442
2443 ASSERT_PAGE_POOL_LOCKED(g);
2444
2445 size_t lo = 0, hi = g->page_index.n_pages;
2446 while (lo < hi) {
2447 size_t mid = (lo + hi) / 2;
2448 if ((uintptr_t)g->page_index.pages[mid]->body < body) lo = mid + 1;
2449 else hi = mid;
2450 }
2451 GC_ASSERT(lo < g->page_index.n_pages && g->page_index.pages[lo] == page);
2452 memmove(&g->page_index.pages[lo], &g->page_index.pages[lo + 1],
2453 (g->page_index.n_pages - lo - 1) * sizeof(struct heap_page *));
2454 g->page_index.n_pages--;
2455}
2456
2457static void
2458global_page_index_remove(const struct heap_page *page)
2459{
2460 rb_global_objspace_t *g = global_objspace;
2461
2462 rb_native_mutex_lock(&g->page_pool.lock);
2463 global_page_index_remove_locked(page);
2464 rb_native_mutex_unlock(&g->page_pool.lock);
2465}
2466
2467static void
2468heap_page_free(rb_objspace_t *objspace, struct heap_page *page)
2469{
2470 global_page_index_remove(page);
2471 objspace->heap_pages.freed_pages++;
2472 heap_page_body_free(page->body, page->arena);
2473 free(page);
2474}
2475
2476static void
2477heap_pages_free_batch(rb_objspace_t *objspace, struct heap_page *pages)
2478{
2479 rb_global_objspace_t *g = global_objspace;
2480
2481 rb_native_mutex_lock(&g->page_pool.lock);
2482 for (struct heap_page *page = pages; page != NULL; page = page->free_next) {
2483 global_page_index_remove_locked(page);
2484 if (HEAP_PAGE_ALLOC_USE_MMAP) {
2485#ifdef HAVE_MMAP
2486 page_pool_release_locked(page->body, page->arena);
2487#endif
2488 }
2489 }
2490 rb_native_mutex_unlock(&g->page_pool.lock);
2491
2492 if (!HEAP_PAGE_ALLOC_USE_MMAP) {
2493 /* gc_aligned_free does not need the pool lock. */
2494 for (struct heap_page *page = pages; page != NULL; page = page->free_next) {
2495 heap_page_body_free(page->body, page->arena);
2496 }
2497 }
2498
2499 while (pages != NULL) {
2500 struct heap_page *next = pages->free_next;
2501 objspace->heap_pages.freed_pages++;
2502 free(pages);
2503 pages = next;
2504 }
2505}
2506
2507static void
2508heap_pages_free_unused_pages(rb_objspace_t *objspace)
2509{
2510 if (objspace->empty_pages != NULL && heap_pages_freeable_pages > 0) {
2511 GC_ASSERT(objspace->empty_pages_count > 0);
2512 objspace->empty_pages = NULL;
2513 objspace->empty_pages_count = 0;
2514
2515 size_t i, j;
2516 struct heap_page *to_free = NULL;
2517 for (i = j = 0; i < rb_darray_size(objspace->heap_pages.sorted); i++) {
2518 struct heap_page *page = rb_darray_get(objspace->heap_pages.sorted, i);
2519
2520 if (heap_page_in_global_empty_pages_pool(objspace, page) && heap_pages_freeable_pages > 0) {
2521 page->free_next = to_free;
2522 to_free = page;
2523 heap_pages_freeable_pages--;
2524 }
2525 else {
2526 if (heap_page_in_global_empty_pages_pool(objspace, page)) {
2527 page->free_next = objspace->empty_pages;
2528 objspace->empty_pages = page;
2529 objspace->empty_pages_count++;
2530 }
2531
2532 if (i != j) {
2533 rb_darray_set(objspace->heap_pages.sorted, j, page);
2534 }
2535 j++;
2536 }
2537 }
2538
2539 rb_darray_pop(objspace->heap_pages.sorted, i - j);
2540 GC_ASSERT(rb_darray_size(objspace->heap_pages.sorted) == j);
2541
2542 /* A retire GC can free every page, so an empty objspace is legitimate. */
2543 if (j > 0) {
2544 struct heap_page *hipage = rb_darray_get(objspace->heap_pages.sorted, rb_darray_size(objspace->heap_pages.sorted) - 1);
2545 uintptr_t himem = (uintptr_t)hipage->body + HEAP_PAGE_SIZE;
2546 GC_ASSERT(himem <= heap_pages_himem);
2547 heap_pages_himem = himem;
2548
2549 struct heap_page *lopage = rb_darray_get(objspace->heap_pages.sorted, 0);
2550 uintptr_t lomem = (uintptr_t)lopage->body + sizeof(struct heap_page_header);
2551 GC_ASSERT(lomem >= heap_pages_lomem);
2552 heap_pages_lomem = lomem;
2553 }
2554 else {
2555 heap_pages_lomem = 0;
2556 heap_pages_himem = 0;
2557 }
2558
2559 heap_pages_free_batch(objspace, to_free);
2560 }
2561}
2562
2563static void *
2564gc_aligned_malloc(size_t alignment, size_t size)
2565{
2566 /* alignment must be a power of 2 */
2567 GC_ASSERT(((alignment - 1) & alignment) == 0);
2568 GC_ASSERT(alignment % sizeof(void*) == 0);
2569
2570 void *res;
2571
2572#if defined __MINGW32__
2573 res = __mingw_aligned_malloc(size, alignment);
2574#elif defined _WIN32
2575 res = _aligned_malloc(size, alignment);
2576#elif defined(HAVE_POSIX_MEMALIGN)
2577 if (posix_memalign(&res, alignment, size) != 0) {
2578 return NULL;
2579 }
2580#elif defined(HAVE_MEMALIGN)
2581 res = memalign(alignment, size);
2582#else
2583 char* aligned;
2584 res = malloc(alignment + size + sizeof(void*));
2585 aligned = (char*)res + alignment + sizeof(void*);
2586 aligned -= ((VALUE)aligned & (alignment - 1));
2587 ((void**)aligned)[-1] = res;
2588 res = (void*)aligned;
2589#endif
2590
2591 GC_ASSERT((uintptr_t)res % alignment == 0);
2592
2593 return res;
2594}
2595
2596/* The page pool (global_objspace->page_pool): heap page bodies are carved out of large
2597 * arenas and reused through the pool. Free bodies are split into a small global hot
2598 * list (≤ PAGE_POOL_HOT_MAX, never madvise'd) and per-arena cold freelists (eligible for
2599 * OS release — see page_pool_reclaim). Both lists use an in-body link at offset 0. */
2600
2601#define PAGE_POOL_ARENA_SIZE (HEAP_PAGE_SIZE * 32) /* 2MiB with 64KiB pages */
2602#define PAGE_POOL_ARENA_BODIES (PAGE_POOL_ARENA_SIZE / HEAP_PAGE_SIZE) /* 32 */
2603#define PAGE_POOL_HOT_MAX 0 /* disabled — empty_pages is the retention buffer */
2604#define PAGE_POOL_ARENA_KEEP_HALF (PAGE_POOL_ARENA_BODIES / 2) /* 16 */
2605
2606/* Steal bit 0 of the in-body link word: set iff the body has been madvise'd (cold). */
2607#define PAGE_POOL_ADVISED_BIT ((uintptr_t)1)
2608
2609/* While a body is free, the arena back-pointer is stored at offset sizeof(header) — one
2610 * word past the link, inside the spared first OS page. PAGE_POOL_SCRATCH_SIZE covers
2611 * both the link (offset 0) and the tag for ASAN unpoison. */
2612#define PAGE_POOL_BODY_ARENA(body) \
2613 (*(struct page_arena **)((char *)(body) + sizeof(struct heap_page_header)))
2614#define PAGE_POOL_SCRATCH_SIZE (sizeof(struct heap_page_header) + sizeof(void *))
2615
2616#ifdef HAVE_MMAP
2617/* mmap a new arena to carve from. Called with the pool lock held, at which point the
2618 * previous arena is always fully carved. */
2619static bool
2620page_pool_add_arena(rb_global_objspace_t *g)
2621{
2622 GC_ASSERT(HEAP_PAGE_ALIGN % sysconf(_SC_PAGE_SIZE) == 0);
2623
2624 size_t mmap_size = PAGE_POOL_ARENA_SIZE + HEAP_PAGE_ALIGN;
2625 char *ptr = mmap(NULL, mmap_size,
2626 PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
2627 if (ptr == MAP_FAILED) {
2628 return false;
2629 }
2630
2631 // If we are building `default.c` as part of the ruby executable, we
2632 // may just call `ruby_annotate_mmap`. But if we are building
2633 // `default.c` as a shared library, we will not have access to private
2634 // symbols, and we have to either call prctl directly or make our own
2635 // wrapper.
2636#if defined(HAVE_SYS_PRCTL_H) && defined(PR_SET_VMA) && defined(PR_SET_VMA_ANON_NAME)
2637 prctl(PR_SET_VMA, PR_SET_VMA_ANON_NAME, ptr, mmap_size, "Ruby:GC:default:page_pool_arena");
2638 errno = 0;
2639#endif
2640
2641 /* Trim the unaligned head and tail so the usable area is HEAP_PAGE_ALIGN aligned. */
2642 char *aligned = ptr + HEAP_PAGE_ALIGN;
2643 aligned -= ((uintptr_t)aligned & (HEAP_PAGE_ALIGN - 1));
2644 GC_ASSERT(aligned > ptr);
2645 GC_ASSERT(aligned <= ptr + HEAP_PAGE_ALIGN);
2646
2647 size_t start_out_of_range_size = aligned - ptr;
2648 GC_ASSERT(start_out_of_range_size % sysconf(_SC_PAGE_SIZE) == 0);
2649 if (start_out_of_range_size > 0) {
2650 if (munmap(ptr, start_out_of_range_size)) {
2651 rb_bug("page_pool_add_arena: munmap failed for start");
2652 }
2653 }
2654
2655 size_t end_out_of_range_size = HEAP_PAGE_ALIGN - start_out_of_range_size;
2656 GC_ASSERT(end_out_of_range_size % sysconf(_SC_PAGE_SIZE) == 0);
2657 if (end_out_of_range_size > 0) {
2658 if (munmap(aligned + PAGE_POOL_ARENA_SIZE, end_out_of_range_size)) {
2659 rb_bug("page_pool_add_arena: munmap failed for end");
2660 }
2661 }
2662
2663 struct page_arena *arena = calloc1(sizeof(struct page_arena));
2664 if (arena == NULL) {
2665 if (munmap(aligned, PAGE_POOL_ARENA_SIZE)) {
2666 rb_bug("page_pool_add_arena: munmap failed for arena");
2667 }
2668 return false;
2669 }
2670 arena->start = aligned;
2671 arena->size = PAGE_POOL_ARENA_SIZE;
2672 arena->cold_freelist = NULL;
2673 arena->free_count = 0;
2674 arena->cold_count = 0;
2675 arena->next = g->page_pool.arenas;
2676 g->page_pool.arenas = arena;
2677 g->page_pool.arena_count++;
2678 g->page_pool.arena_current = arena;
2679
2680 g->page_pool.arena_cursor = aligned;
2681 g->page_pool.arena_end = aligned + PAGE_POOL_ARENA_SIZE;
2682
2683 return true;
2684}
2685#endif
2686
2687static struct heap_page_body *
2688page_pool_acquire(struct page_arena **arena_out)
2689{
2690 struct heap_page_body *body = NULL;
2691
2692 if (HEAP_PAGE_ALLOC_USE_MMAP) {
2693#ifdef HAVE_MMAP
2694 bool need_reuse = false;
2695 rb_global_objspace_t *g = global_objspace;
2696
2697 rb_native_mutex_lock(&g->page_pool.lock);
2698 if (g->page_pool.hot_list != NULL) {
2699 body = g->page_pool.hot_list;
2700 asan_unpoison_memory_region(body, PAGE_POOL_SCRATCH_SIZE, false);
2701 uintptr_t link = *(uintptr_t *)body;
2702 g->page_pool.hot_list = (struct heap_page_body *)(link & ~PAGE_POOL_ADVISED_BIT);
2703 g->page_pool.hot_count--;
2704 struct page_arena *arena = PAGE_POOL_BODY_ARENA(body);
2705 arena->free_count--;
2706 *arena_out = arena;
2707 }
2708 else {
2709 // find cold page body (madvised reusable)
2710 for (struct page_arena *a = g->page_pool.arenas; a; a = a->next) {
2711 if (a->cold_count > 0) {
2712 body = a->cold_freelist;
2713 asan_unpoison_memory_region(body, PAGE_POOL_SCRATCH_SIZE, false);
2714 uintptr_t link = *(uintptr_t *)body;
2715 a->cold_freelist = (struct heap_page_body *)(link & ~PAGE_POOL_ADVISED_BIT);
2716 a->cold_count--;
2717 a->free_count--;
2718 *arena_out = a;
2719 need_reuse = (link & PAGE_POOL_ADVISED_BIT) != 0;
2720 if (need_reuse) g->page_pool.advised_count--;
2721 break;
2722 }
2723 }
2724 if (body == NULL &&
2725 (g->page_pool.arena_cursor != g->page_pool.arena_end ||
2726 page_pool_add_arena(g))) {
2727 GC_ASSERT(g->page_pool.arena_cursor + HEAP_PAGE_SIZE <= g->page_pool.arena_end);
2728 body = (struct heap_page_body *)g->page_pool.arena_cursor;
2729 g->page_pool.arena_cursor += HEAP_PAGE_SIZE;
2730 *arena_out = g->page_pool.arena_current;
2731 }
2732 }
2733 rb_native_mutex_unlock(&g->page_pool.lock);
2734
2735 if (body != NULL) {
2736 if (need_reuse) {
2737 rb_vm_map_reuse((char *)body + g->page_pool.os_page_size,
2738 HEAP_PAGE_SIZE - g->page_pool.os_page_size);
2739 }
2740 asan_unpoison_memory_region(body, HEAP_PAGE_SIZE, false);
2741 }
2742#endif
2743 }
2744 else {
2745 body = gc_aligned_malloc(HEAP_PAGE_ALIGN, HEAP_PAGE_SIZE);
2746 *arena_out = NULL;
2747 }
2748
2749 return body;
2750}
2751
2752#ifdef HAVE_MMAP
2753static void
2754page_pool_release_locked(struct heap_page_body *body, struct page_arena *arena)
2755{
2756 rb_global_objspace_t *g = global_objspace;
2757
2758 ASSERT_PAGE_POOL_LOCKED(g);
2759
2760 /* A body in the empty-pages pool stays fully poisoned (see gc_sweep_page), so
2761 * unpoison the scratch area (link + arena tag) before writing. */
2762 asan_unpoison_memory_region(body, PAGE_POOL_SCRATCH_SIZE, false);
2763 arena->free_count++;
2764 PAGE_POOL_BODY_ARENA(body) = arena;
2765 if (g->page_pool.hot_count < PAGE_POOL_HOT_MAX) {
2766 *(uintptr_t *)body = (uintptr_t)g->page_pool.hot_list;
2767 g->page_pool.hot_list = body;
2768 g->page_pool.hot_count++;
2769 }
2770 else {
2771 *(uintptr_t *)body = (uintptr_t)arena->cold_freelist;
2772 arena->cold_freelist = body;
2773 arena->cold_count++;
2774 }
2775 asan_poison_memory_region(body, HEAP_PAGE_SIZE);
2776}
2777#endif
2778
2779static void
2780page_pool_release(struct heap_page_body *body, struct page_arena *arena)
2781{
2782 if (HEAP_PAGE_ALLOC_USE_MMAP) {
2783#ifdef HAVE_MMAP
2784 rb_global_objspace_t *g = global_objspace;
2785
2786 rb_native_mutex_lock(&g->page_pool.lock);
2787 page_pool_release_locked(body, arena);
2788 rb_native_mutex_unlock(&g->page_pool.lock);
2789#endif
2790 }
2791 else {
2792 gc_aligned_free(body, HEAP_PAGE_SIZE);
2793 }
2794}
2795
2796/* Allow the OS to reclaim pool memory. Runs only at major GC in single-objspace mode
2797 * (see gc_sweep_finish).
2798 *
2799 * Step A: madvise cold bodies, sparing the first OS page (which holds the in-body
2800 * freelist link and arena tag).
2801 *
2802 * Step B: munmap arenas whose 32 bodies are all free, keeping one extra empty
2803 * arena as a retention buffer when the remaining free pool is < half an arena. */
2804static void
2805page_pool_reclaim(rb_global_objspace_t *g)
2806{
2807 if (!HEAP_PAGE_ALLOC_USE_MMAP) return;
2808#ifdef HAVE_MMAP
2809 size_t os_page_size = g->page_pool.os_page_size;
2810
2811 rb_native_mutex_lock(&g->page_pool.lock);
2812
2813 /* Advising spares the first OS page of a body (it holds the in-body freelist link
2814 * and the arena tag), so it needs sub-page granularity: when the OS page size is
2815 * >= HEAP_PAGE_SIZE (e.g. 64KiB pages on aarch64) no body is ever advised, and
2816 * advised_count must not be adjusted anywhere either. */
2817 const bool can_advise = os_page_size < HEAP_PAGE_SIZE;
2818
2819 /* Step A — advise cold bodies (immediate release: drop RSS now if the platform allows). */
2820 if (can_advise) {
2821 for (struct page_arena *a = g->page_pool.arenas; a; a = a->next) {
2822 for (struct heap_page_body *body = a->cold_freelist; body; ) {
2823 asan_unpoison_memory_region(body, PAGE_POOL_SCRATCH_SIZE, false);
2824 uintptr_t link = *(uintptr_t *)body;
2825 struct heap_page_body *next =
2826 (struct heap_page_body *)(link & ~PAGE_POOL_ADVISED_BIT);
2827 if (!(link & PAGE_POOL_ADVISED_BIT)) {
2828 rb_vm_map_reusable_immediate((char *)body + os_page_size,
2829 HEAP_PAGE_SIZE - os_page_size, 0);
2830 *(uintptr_t *)body = link | PAGE_POOL_ADVISED_BIT;
2831 g->page_pool.advised_count++;
2832 }
2833 asan_poison_memory_region(body, PAGE_POOL_SCRATCH_SIZE);
2834 body = next;
2835 }
2836 }
2837 }
2838
2839 /* Step B — munmap fully-free arenas (with retention buffer).
2840 *
2841 * total_free = Σ free_count; free_count already includes hot-list bodies
2842 * (page_pool_release increments it unconditionally), so no separate hot_count.
2843 * An arena is eligible when all 32 of its bodies are free AND none sit on
2844 * the hot list (≤5 entries, pre-scanned). Keep one extra empty arena when
2845 * the rest of the free pool is < half an arena, to avoid thrash. */
2846 int total_free = 0;
2847 for (struct page_arena *a = g->page_pool.arenas; a; a = a->next) {
2848 total_free += a->free_count;
2849 }
2850
2851 struct page_arena *hot_arenas[PAGE_POOL_HOT_MAX ? PAGE_POOL_HOT_MAX : 1];
2852 int n_hot_arenas = 0;
2853 /* Collect arenas that have a hot body (≤ PAGE_POOL_HOT_MAX entries). */
2854 for (struct heap_page_body *body = g->page_pool.hot_list; body; ) {
2855 asan_unpoison_memory_region(body, PAGE_POOL_SCRATCH_SIZE, false);
2856 uintptr_t link = *(uintptr_t *)body;
2857 struct heap_page_body *next =
2858 (struct heap_page_body *)(link & ~PAGE_POOL_ADVISED_BIT);
2859 struct page_arena *arena = PAGE_POOL_BODY_ARENA(body);
2860 bool found = false;
2861 for (int i = 0; i < n_hot_arenas; i++) {
2862 if (hot_arenas[i] == arena) { found = true; break; }
2863 }
2864 if (!found && n_hot_arenas < PAGE_POOL_HOT_MAX) {
2865 hot_arenas[n_hot_arenas++] = arena;
2866 }
2867 asan_poison_memory_region(body, PAGE_POOL_SCRATCH_SIZE);
2868 body = next;
2869 }
2870
2871 bool retained_one = false;
2872 struct page_arena **pp = &g->page_pool.arenas;
2873 // munmap fully free arenas
2874 while (*pp) {
2875 struct page_arena *a = *pp;
2876 bool has_hot = false;
2877 for (int i = 0; i < n_hot_arenas; i++) {
2878 if (hot_arenas[i] == a) { has_hot = true; break; }
2879 }
2880 if (a->free_count != PAGE_POOL_ARENA_BODIES || has_hot) {
2881 pp = &a->next;
2882 continue;
2883 }
2884 GC_ASSERT(a->cold_count == PAGE_POOL_ARENA_BODIES);
2885
2886 int free_elsewhere = total_free - PAGE_POOL_ARENA_BODIES;
2887 if (free_elsewhere < PAGE_POOL_ARENA_KEEP_HALF && !retained_one) {
2888 retained_one = true;
2889 pp = &a->next;
2890 continue;
2891 }
2892
2893 *pp = a->next;
2894 if (munmap(a->start, a->size)) {
2895 rb_bug("page_pool_reclaim: munmap failed");
2896 }
2897 total_free -= PAGE_POOL_ARENA_BODIES;
2898 /* Every body of this arena is on its cold freelist, so Step A above has just
2899 * advised all of them -- but only if this platform can advise at all. */
2900 if (can_advise) {
2901 g->page_pool.advised_count -= PAGE_POOL_ARENA_BODIES;
2902 GC_ASSERT(g->page_pool.advised_count >= 0);
2903 }
2904 g->page_pool.arena_count--;
2905 g->page_pool.arenas_unmapped++;
2906 if (a == g->page_pool.arena_current) {
2907 // During next acquire, any remaining arenas that have cold bodies are used. This is guaranteed
2908 // because of the retention buffer.
2909 g->page_pool.arena_current = NULL;
2910 g->page_pool.arena_cursor = NULL;
2911 g->page_pool.arena_end = NULL;
2912 }
2913 free(a);
2914 }
2915
2916 rb_native_mutex_unlock(&g->page_pool.lock);
2917#endif
2918}
2919
2920static struct heap_page_body *
2921heap_page_body_allocate(struct page_arena **arena_out)
2922{
2923 struct heap_page_body *page_body = page_pool_acquire(arena_out);
2924
2925 GC_ASSERT(page_body == NULL || (uintptr_t)page_body % HEAP_PAGE_ALIGN == 0);
2926
2927 return page_body;
2928}
2929
2930static struct heap_page *
2931heap_page_resurrect(rb_objspace_t *objspace)
2932{
2933 struct heap_page *page = NULL;
2934 if (objspace->empty_pages == NULL) {
2935 GC_ASSERT(objspace->empty_pages_count == 0);
2936 }
2937 else {
2938 GC_ASSERT(objspace->empty_pages_count > 0);
2939 objspace->empty_pages_count--;
2940 page = objspace->empty_pages;
2941 objspace->empty_pages = page->free_next;
2942 /* Clear the flags left over from emptying the page before reusing it, or the
2943 * shareable and shref scans would keep walking an empty bitmap forever. */
2944 page->flags.has_shareable_objects = FALSE;
2945 page->flags.has_shref_objects = FALSE;
2946 }
2947
2948 return page;
2949}
2950
2951static struct heap_page *
2952heap_page_allocate(rb_objspace_t *objspace)
2953{
2954 struct page_arena *arena;
2955 struct heap_page_body *page_body = heap_page_body_allocate(&arena);
2956 if (page_body == 0) {
2957 rb_memerror();
2958 }
2959
2960 struct heap_page *page = calloc1(sizeof(struct heap_page));
2961 if (page == 0) {
2962 heap_page_body_free(page_body, arena);
2963 rb_memerror();
2964 }
2965
2966 uintptr_t start = (uintptr_t)page_body + sizeof(struct heap_page_header);
2967 uintptr_t end = (uintptr_t)page_body + HEAP_PAGE_SIZE;
2968
2969 size_t lo = 0;
2970 size_t hi = rb_darray_size(objspace->heap_pages.sorted);
2971 while (lo < hi) {
2972 struct heap_page *mid_page;
2973
2974 size_t mid = (lo + hi) / 2;
2975 mid_page = rb_darray_get(objspace->heap_pages.sorted, mid);
2976 if ((uintptr_t)mid_page->start < start) {
2977 lo = mid + 1;
2978 }
2979 else if ((uintptr_t)mid_page->start > start) {
2980 hi = mid;
2981 }
2982 else {
2983 rb_bug("same heap page is allocated: %p at %"PRIuVALUE, (void *)page_body, (VALUE)mid);
2984 }
2985 }
2986
2987 rb_darray_insert_without_gc(&objspace->heap_pages.sorted, hi, page);
2988
2989 if (heap_pages_lomem == 0 || heap_pages_lomem > start) heap_pages_lomem = start;
2990 if (heap_pages_himem < end) heap_pages_himem = end;
2991
2992 page->body = page_body;
2993 page->arena = arena;
2994 page_body->header.page = page;
2995 page->objspace = objspace;
2996
2997 objspace->heap_pages.allocated_pages++;
2998
2999 global_page_index_insert(page);
3000
3001 return page;
3002}
3003
3004static void
3005heap_add_page(rb_objspace_t *objspace, rb_heap_t *heap, struct heap_page *page)
3006{
3007 /* Adding to eden heap during incremental sweeping is forbidden */
3008 GC_ASSERT(!heap->sweeping_page);
3009 GC_ASSERT(heap_page_in_global_empty_pages_pool(objspace, page));
3010
3011 /* Align start to slot_size boundary */
3012 uintptr_t start = (uintptr_t)page->body + sizeof(struct heap_page_header);
3013 uintptr_t rem = start % heap->slot_size;
3014 if (rem) start += heap->slot_size - rem;
3015
3016 int slot_count = (int)((HEAP_PAGE_SIZE - (start - (uintptr_t)page->body))/heap->slot_size);
3017
3018 page->start = start;
3019 page->total_slots = slot_count;
3020 page->slot_size = heap->slot_size;
3021 page->slot_size_reciprocal = heap_slot_reciprocal_table[heap - heaps];
3022 page->heap = heap;
3023
3024 memset(&page->wb_unprotected_bits[0], 0, HEAP_PAGE_BITMAP_SIZE);
3025 memset(&page->age_bits[0], 0, sizeof(page->age_bits));
3026
3027 asan_unlock_freelist(page);
3028 asan_unpoison_memory_region(page->body, HEAP_PAGE_SIZE, false);
3029
3030 uintptr_t slots_end = start + (uintptr_t)slot_count * heap->slot_size;
3031
3032 memset((void *)start, 0, slots_end - start);
3033
3034 struct free_region *region = (struct free_region *)start;
3035 region->flags = 0;
3036 region->end = slots_end;
3037 region->next = NULL;
3038 page->free_region = region;
3039
3040 /* Poison every free slot; each is unpoisoned again as it is handed out. */
3041 for (uintptr_t p = start; p < slots_end; p += heap->slot_size) {
3042 rb_asan_poison_object((VALUE)p);
3043 }
3044 asan_lock_freelist(page);
3045
3046 page->free_slots = slot_count;
3047
3048 heap->total_allocated_pages++;
3049
3050 ccan_list_add_tail(&heap->pages, &page->page_node);
3051 heap->total_pages++;
3052 heap->total_slots += page->total_slots;
3053}
3054
3055static int
3056heap_page_allocate_and_initialize(rb_objspace_t *objspace, rb_heap_t *heap)
3057{
3058 gc_report(1, objspace, "heap_page_allocate_and_initialize: rb_darray_size(objspace->heap_pages.sorted): %"PRIdSIZE", "
3059 "allocatable_bytes: %"PRIdSIZE", heap->total_pages: %"PRIdSIZE"\n",
3060 rb_darray_size(objspace->heap_pages.sorted), objspace->heap_pages.allocatable_bytes, heap->total_pages);
3061
3062 bool allocated = false;
3063 struct heap_page *page = heap_page_resurrect(objspace);
3064
3065 if (page == NULL && objspace->heap_pages.allocatable_bytes > 0) {
3066 page = heap_page_allocate(objspace);
3067 allocated = true;
3068
3069 GC_ASSERT(page != NULL);
3070 }
3071
3072 if (page != NULL) {
3073 heap_add_page(objspace, heap, page);
3074 heap_add_freepage(heap, page);
3075
3076 if (allocated) {
3077 size_t page_bytes = (size_t)page->total_slots * page->slot_size;
3078 if (objspace->heap_pages.allocatable_bytes > page_bytes) {
3079 objspace->heap_pages.allocatable_bytes -= page_bytes;
3080 }
3081 else {
3082 objspace->heap_pages.allocatable_bytes = 0;
3083 }
3084 }
3085 }
3086
3087 return page != NULL;
3088}
3089
3090static void
3091heap_page_allocate_and_initialize_force(rb_objspace_t *objspace, rb_heap_t *heap)
3092{
3093 size_t prev_allocatable_bytes = objspace->heap_pages.allocatable_bytes;
3094 objspace->heap_pages.allocatable_bytes = HEAP_PAGE_SIZE;
3095 heap_page_allocate_and_initialize(objspace, heap);
3096 GC_ASSERT(heap->free_pages != NULL);
3097 objspace->heap_pages.allocatable_bytes = prev_allocatable_bytes;
3098}
3099
3100static void
3101gc_continue(rb_objspace_t *objspace, rb_heap_t *heap)
3102{
3103 unsigned int lock_lev;
3104 bool needs_gc = is_incremental_marking(objspace) || needs_continue_sweeping(objspace, heap);
3105 if (!needs_gc) return;
3106
3107 gc_enter(objspace, gc_enter_event_continue, &lock_lev); // takes vm barrier, try to avoid
3108
3109 /* Continue marking if in incremental marking. */
3110 if (is_incremental_marking(objspace)) {
3111 if (gc_marks_continue(objspace, heap)) {
3112 gc_sweep(objspace);
3113 }
3114 }
3115
3116 if (needs_continue_sweeping(objspace, heap)) {
3117 gc_sweep_continue(objspace, heap);
3118 }
3119
3120 gc_exit(objspace, gc_enter_event_continue, &lock_lev);
3121}
3122
3123static void
3124heap_prepare(rb_objspace_t *objspace, rb_heap_t *heap)
3125{
3126 GC_ASSERT(heap->free_pages == NULL);
3127
3128 if (heap->total_slots < objspace_heap_init_bytes(objspace) / heap->slot_size &&
3129 heap->sweeping_page == NULL) {
3130 heap_page_allocate_and_initialize_force(objspace, heap);
3131 GC_ASSERT(heap->free_pages != NULL);
3132 return;
3133 }
3134
3135 /* Continue incremental marking or lazy sweeping, if in any of those steps. */
3136 gc_continue(objspace, heap);
3137
3138 if (heap->free_pages == NULL) {
3139 heap_page_allocate_and_initialize(objspace, heap);
3140 }
3141
3142 /* If we still don't have a free page and not allowed to create a new page,
3143 * we should start a new GC cycle. */
3144 if (heap->free_pages == NULL) {
3145 GC_ASSERT(objspace->empty_pages_count == 0);
3146 GC_ASSERT(objspace->heap_pages.allocatable_bytes == 0);
3147
3148 if (gc_start(objspace, GPR_FLAG_NEWOBJ) == FALSE) {
3149 rb_memerror();
3150 }
3151 else {
3152 if (objspace->heap_pages.allocatable_bytes == 0 && !gc_config_full_mark_val) {
3153 heap_allocatable_bytes_expand(objspace, heap,
3154 heap->freed_slots + heap->empty_slots,
3155 heap->total_slots, heap->slot_size);
3156 GC_ASSERT(objspace->heap_pages.allocatable_bytes > 0);
3157 }
3158 /* Do steps of incremental marking or lazy sweeping if the GC run permits. */
3159 gc_continue(objspace, heap);
3160
3161 /* If we're not incremental marking (e.g. a minor GC) or finished
3162 * sweeping and still don't have a free page, then
3163 * gc_sweep_finish_heap should allow us to create a new page. */
3164 if (heap->free_pages == NULL && !heap_page_allocate_and_initialize(objspace, heap)) {
3165 if (gc_needs_major_flags == GPR_FLAG_NONE) {
3166 rb_bug("cannot create a new page after GC");
3167 }
3168 else { // Major GC is required, which will allow us to create new page
3169 if (gc_start(objspace, GPR_FLAG_NEWOBJ) == FALSE) {
3170 rb_memerror();
3171 }
3172 else {
3173 /* Do steps of incremental marking or lazy sweeping. */
3174 gc_continue(objspace, heap);
3175
3176 if (heap->free_pages == NULL &&
3177 !heap_page_allocate_and_initialize(objspace, heap)) {
3178 rb_bug("cannot create a new page after major GC");
3179 }
3180 }
3181 }
3182 }
3183 }
3184 }
3185
3186 GC_ASSERT(heap->free_pages != NULL);
3187}
3188
3189#if GC_DEBUG
3190static inline const char*
3191rb_gc_impl_source_location_cstr(int *ptr)
3192{
3193 /* We could directly refer `rb_source_location_cstr()` before, but not any
3194 * longer. We have to heavy lift using our debugging API. */
3195 if (! ptr) {
3196 return NULL;
3197 }
3198 else if (! (*ptr = rb_sourceline())) {
3199 return NULL;
3200 }
3201 else {
3202 return rb_sourcefile();
3203 }
3204}
3205#endif
3206
3207static inline VALUE
3208newobj_init(VALUE klass, VALUE flags, int wb_protected, rb_objspace_t *objspace, VALUE obj)
3209{
3210 GC_ASSERT(BUILTIN_TYPE(obj) == T_NONE);
3211 GC_ASSERT((flags & FL_WB_PROTECTED) == 0);
3212 RBASIC(obj)->flags = flags;
3213 *((VALUE *)&RBASIC(obj)->klass) = klass;
3214#if RBASIC_SHAPE_ID_FIELD
3215 RBASIC(obj)->shape_id = 0;
3216#endif
3217
3218 if (RB_UNLIKELY(flags & RUBY_FL_SHAREABLE)) {
3219 /* A born-shareable object must be WB protected: the shref and remembered-set
3220 * rules for shareable objects assume the write barrier. A local GC roots
3221 * shareable objects from this bit (pinned_roots_mark). */
3222 GC_ASSERT(wb_protected);
3223 gc_page_add_shareable(GET_HEAP_PAGE(obj), obj);
3224 }
3225
3226#if RGENGC_CHECK_MODE
3227 int lev = RB_GC_VM_LOCK_NO_BARRIER();
3228 {
3229 check_rvalue_consistency(objspace, obj);
3230
3231 GC_ASSERT(RVALUE_MARKED(objspace, obj) == FALSE);
3232 GC_ASSERT(RVALUE_MARKING(objspace, obj) == FALSE);
3233 GC_ASSERT(RVALUE_OLD_P(objspace, obj) == FALSE);
3234 GC_ASSERT(RVALUE_WB_UNPROTECTED(objspace, obj) == FALSE);
3235
3236 if (RVALUE_REMEMBERED(objspace, obj)) rb_bug("newobj: %s is remembered.", rb_obj_info(obj));
3237 }
3238 RB_GC_VM_UNLOCK_NO_BARRIER(lev);
3239#endif
3240
3241 if (RB_UNLIKELY(wb_protected == FALSE)) {
3242 MARK_IN_BITMAP(GET_HEAP_WB_UNPROTECTED_BITS(obj), obj);
3243 }
3244
3245#if RGENGC_PROFILE
3246 if (wb_protected) {
3247 objspace->profile.total_generated_normal_object_count++;
3248#if RGENGC_PROFILE >= 2
3249 objspace->profile.generated_normal_object_count_types[BUILTIN_TYPE(obj)]++;
3250#endif
3251 }
3252 else {
3253 objspace->profile.total_generated_shady_object_count++;
3254#if RGENGC_PROFILE >= 2
3255 objspace->profile.generated_shady_object_count_types[BUILTIN_TYPE(obj)]++;
3256#endif
3257 }
3258#endif
3259
3260#if GC_DEBUG
3261 GET_RVALUE_OVERHEAD(obj)->file = rb_gc_impl_source_location_cstr(&GET_RVALUE_OVERHEAD(obj)->line);
3262 GC_ASSERT(!SPECIAL_CONST_P(obj)); /* check alignment */
3263#endif
3264
3265 gc_report(5, objspace, "newobj: %s\n", rb_obj_info(obj));
3266
3267 // RUBY_DEBUG_LOG("obj:%p (%s)", (void *)obj, rb_obj_info(obj));
3268 return obj;
3269}
3270
3271size_t
3272rb_gc_impl_obj_slot_size(VALUE obj)
3273{
3274 return GET_HEAP_PAGE(obj)->slot_size - RVALUE_OVERHEAD;
3275}
3276
3277bool
3278rb_gc_impl_pinned_p(void *objspace_ptr, VALUE obj)
3279{
3280 return RVALUE_PINNED((rb_objspace_t *)objspace_ptr, obj);
3281}
3282
3283static inline size_t
3284heap_slot_size(unsigned char pool_id)
3285{
3286 GC_ASSERT(pool_id < HEAP_COUNT);
3287
3288 return pool_slot_sizes[pool_id] - RVALUE_OVERHEAD;
3289}
3290
3291size_t
3292rb_gc_impl_max_allocation_size(void)
3293{
3294 return heap_slot_size(HEAP_COUNT - 1);
3295}
3296
3297bool
3298rb_gc_impl_size_allocatable_p(size_t size)
3299{
3300 return size <= rb_gc_impl_max_allocation_size();
3301}
3302
3303static inline bool
3304heap_advance_region(rb_heap_t *heap)
3305{
3306 struct free_region *region = heap->newobj.alloc_next_region;
3307 if (region == NULL) {
3308 return false;
3309 }
3310
3311 rb_asan_unpoison_object((VALUE)region, false);
3312 GC_ASSERT(RB_TYPE_P((VALUE)region, T_NONE));
3313 heap->newobj.alloc_cursor = (uintptr_t)region;
3314 heap->newobj.alloc_cursor_end = region->end;
3315 heap->newobj.alloc_next_region = region->next;
3316 rb_asan_poison_object((VALUE)region);
3317
3318 return true;
3319}
3320
3321/* The whole region is ours until the next refill, so charge it to the step now. */
3322static inline void
3323heap_charge_region(rb_objspace_t *objspace, const rb_heap_t *heap, size_t heap_idx)
3324{
3325 objspace->incremental_mark_step_allocated_slots +=
3326 (heap->newobj.alloc_cursor_end - heap->newobj.alloc_cursor) / pool_slot_sizes[heap_idx];
3327}
3328
3329static inline VALUE
3330heap_alloc_slot(rb_objspace_t *objspace, size_t heap_idx)
3331{
3332 rb_heap_t *heap = &heaps[heap_idx];
3333
3334 uintptr_t cursor = heap->newobj.alloc_cursor;
3335 if (RB_UNLIKELY(cursor >= heap->newobj.alloc_cursor_end)) {
3336 /* Marking owes us a step before the next region, and newobj_refill runs it. */
3337 if (RB_UNLIKELY(is_incremental_marking(objspace)) ||
3338 heap_advance_region(heap) == false) {
3339 return Qfalse;
3340 }
3341 cursor = heap->newobj.alloc_cursor;
3342 }
3343
3344 VALUE obj = (VALUE)cursor;
3345 rb_asan_unpoison_object(obj, true);
3346 heap->newobj.alloc_cursor = cursor + pool_slot_sizes[heap_idx];
3347
3348 /* Single writer (the owning Ractor under the GVL), so a plain increment is enough. */
3349 heap->total_allocated_objects++;
3350
3351#if RGENGC_CHECK_MODE
3352 GC_ASSERT(rb_gc_impl_obj_slot_size(obj) == heap_slot_size(heap_idx));
3353 // zero clear
3354 MEMZERO((char *)obj, char, heap_slot_size(heap_idx));
3355#endif
3356 return obj;
3357}
3358
3359static struct heap_page *
3360heap_next_free_page(rb_objspace_t *objspace, rb_heap_t *heap)
3361{
3362 struct heap_page *page;
3363
3364 if (heap->free_pages == NULL) {
3365 heap_prepare(objspace, heap);
3366 }
3367
3368 page = heap->free_pages;
3369 heap->free_pages = page->free_next;
3370
3371 GC_ASSERT(page->free_slots != 0);
3372
3373 asan_unlock_freelist(page);
3374
3375 return page;
3376}
3377
3378static inline void
3379heap_set_alloc_page(rb_objspace_t *objspace, size_t heap_idx, struct heap_page *page)
3380{
3381 gc_report(3, objspace, "heap_set_alloc_page: Using page %p\n", (void *)page->body);
3382
3383 rb_heap_t *heap = &heaps[heap_idx];
3384
3385 GC_ASSERT(heap->newobj.alloc_cursor >= heap->newobj.alloc_cursor_end);
3386 GC_ASSERT(heap->newobj.alloc_next_region == NULL);
3387 GC_ASSERT(page->free_slots != 0);
3388 GC_ASSERT(page->free_region != NULL);
3389
3390 heap->newobj.alloc_using_page = page;
3391
3392 struct free_region *region = page->free_region;
3393 rb_asan_unpoison_object((VALUE)region, false);
3394 GC_ASSERT(RB_TYPE_P((VALUE)region, T_NONE));
3395 heap->newobj.alloc_cursor = (uintptr_t)region;
3396 heap->newobj.alloc_cursor_end = region->end;
3397 heap->newobj.alloc_next_region = region->next;
3398 rb_asan_poison_object((VALUE)region);
3399
3400 page->free_slots = 0;
3401 page->free_region = NULL;
3402}
3403
3404static void
3405init_size_to_heap_idx(void)
3406{
3407 /* Process-wide and immutable, so build it once at boot. A rebuild in a later
3408 * objspace_init would write the same values but race other threads' lock-free
3409 * allocation-fastpath reads. */
3410 static bool initialized = false;
3411 if (initialized) return;
3412 initialized = true;
3413
3414 for (size_t i = 0; i < sizeof(size_to_heap_idx); i++) {
3415 size_t effective = i * 8 + RVALUE_OVERHEAD;
3416 uint8_t idx;
3417 for (idx = 0; idx < HEAP_COUNT; idx++) {
3418 if (effective <= pool_slot_sizes[idx]) break;
3419 }
3420 size_to_heap_idx[i] = idx;
3421 }
3422}
3423
3424static inline size_t
3425heap_idx_for_size(size_t size)
3426{
3427 size_t compressed = (size + 7) >> 3;
3428 if (compressed < sizeof(size_to_heap_idx)) {
3429 size_t heap_idx = size_to_heap_idx[compressed];
3430 if (RB_LIKELY(heap_idx < HEAP_COUNT)) return heap_idx;
3431 }
3432
3433 rb_bug("heap_idx_for_size: allocation size too large "
3434 "(size=%"PRIuSIZE")", size);
3435}
3436
3437size_t
3438rb_gc_impl_size_slot_size(void *objspace_ptr, size_t size)
3439{
3440 return heap_slot_size((unsigned char)heap_idx_for_size(size));
3441}
3442
3443bool
3444rb_gc_impl_zjit_new_obj_fastpath(void *objspace_ptr, size_t alloc_size, VALUE flags, VALUE klass,
3445 struct rb_gc_zjit_fastpath *fastpath)
3446{
3447#if USE_ZJIT
3448 size_t heap_idx = 0;
3449 size_t slot_size = 0;
3450 for (; heap_idx < HEAP_COUNT; heap_idx++) {
3451 if (alloc_size + RVALUE_OVERHEAD <= pool_slot_sizes[heap_idx]) {
3452 slot_size = pool_slot_sizes[heap_idx];
3453 break;
3454 }
3455 }
3456 if (slot_size == 0) return false;
3457
3458#undef heaps
3459 size_t base = offsetof(rb_objspace_t, heaps)
3460 + heap_idx * sizeof(rb_heap_t)
3461 + offsetof(rb_heap_t, newobj);
3462#define heaps objspace->heaps
3463
3464 struct rb_gc_zjit_default_new_obj_fastpath default_fastpath = {
3465 base + offsetof(rb_heap_newobj_t, alloc_cursor),
3466 base + offsetof(rb_heap_newobj_t, alloc_cursor_end),
3467 slot_size,
3468 base - offsetof(rb_heap_t, newobj) + offsetof(rb_heap_t, total_allocated_objects),
3469 flags,
3470 klass
3471 };
3472
3473 memset(fastpath, 0, sizeof(*fastpath));
3474 fastpath->kind = RB_GC_ZJIT_FASTPATH_DEFAULT;
3475 memcpy(fastpath->data.words, &default_fastpath, sizeof(default_fastpath));
3476
3477 return true;
3478#else
3479 return false;
3480#endif
3481}
3482
3483NOINLINE(static VALUE newobj_refill(rb_objspace_t *objspace, size_t heap_idx));
3484
3485static VALUE
3486newobj_refill(rb_objspace_t *objspace, size_t heap_idx)
3487{
3488 rb_heap_t *heap = &heaps[heap_idx];
3489 VALUE obj = Qfalse;
3490
3491 /* No lock: a heap is single-writer (its owner thread, serialized by the GVL inside
3492 * the Ractor), the page pool has its own mutex, and a GC started from here takes
3493 * whatever gc_enter needs. */
3494 if (is_incremental_marking(objspace)) {
3495 /* The fast path sends us here at every region, which is far more often than the
3496 * step size, so step only once the regions add up to it. */
3497 if (objspace->incremental_mark_step_allocated_slots >= INCREMENTAL_MARK_STEP_ALLOCATIONS) {
3498 gc_continue(objspace, heap);
3499 objspace->incremental_mark_step_allocated_slots = 0;
3500 }
3501
3502 // Move on to the region the fast path refused to take
3503 if (heap_advance_region(heap)) {
3504 heap_charge_region(objspace, heap, heap_idx);
3505 obj = heap_alloc_slot(objspace, heap_idx);
3506 }
3507 }
3508
3509 if (obj == Qfalse) {
3510 // Get next free page (possibly running GC)
3511 struct heap_page *page = heap_next_free_page(objspace, heap);
3512 heap_set_alloc_page(objspace, heap_idx, page);
3513 heap_charge_region(objspace, heap, heap_idx);
3514
3515 // Retry allocation after moving to new page
3516 obj = heap_alloc_slot(objspace, heap_idx);
3517 }
3518
3519 if (RB_UNLIKELY(obj == Qfalse)) {
3520 rb_memerror();
3521 }
3522 return obj;
3523}
3524
3525static VALUE
3526newobj_alloc(rb_objspace_t *objspace, size_t heap_idx)
3527{
3528 /* The objspace belongs to the current Ractor and is single-writer, so the fast path
3529 * needs no lock. Stress GC runs in the caller's slow path, before newobj_alloc. */
3530 VALUE obj = heap_alloc_slot(objspace, heap_idx);
3531
3532 if (RB_UNLIKELY(obj == Qfalse)) {
3533 obj = newobj_refill(objspace, heap_idx);
3534 }
3535
3536 return obj;
3537}
3538
3539ALWAYS_INLINE(static VALUE newobj_slowpath(VALUE klass, VALUE flags, rb_objspace_t *objspace, int wb_protected, size_t heap_idx));
3540
3541static inline VALUE
3542newobj_slowpath(VALUE klass, VALUE flags, rb_objspace_t *objspace, int wb_protected, size_t heap_idx)
3543{
3544 VALUE obj;
3545
3546 /* No lock (see newobj_refill); during_gc and the stress flag are this objspace's own state. */
3547 if (RB_UNLIKELY(during_gc || ruby_gc_stressful)) {
3548 if (during_gc) {
3549 dont_gc_on();
3550 during_gc = 0;
3551 if (rb_memerror_reentered()) {
3552 rb_memerror();
3553 }
3554 rb_bug("object allocation during garbage collection phase");
3555 }
3556
3557 if (ruby_gc_stressful) {
3558 if (!garbage_collect(objspace, GPR_FLAG_NEWOBJ)) {
3559 rb_memerror();
3560 }
3561 }
3562 }
3563
3564 obj = newobj_alloc(objspace, heap_idx);
3565 newobj_init(klass, flags, wb_protected, objspace, obj);
3566
3567 if (RB_UNLIKELY(ruby_gc_stressful)) {
3568 rb_heap_t *heap = &heaps[heap_idx];
3569 heap->newobj.alloc_cursor_end = heap->newobj.alloc_cursor;
3570 }
3571
3572 return obj;
3573}
3574
3575NOINLINE(static VALUE newobj_slowpath_wb_protected(VALUE klass, VALUE flags,
3576 rb_objspace_t *objspace, size_t heap_idx));
3577NOINLINE(static VALUE newobj_slowpath_wb_unprotected(VALUE klass, VALUE flags,
3578 rb_objspace_t *objspace, size_t heap_idx));
3579
3580static VALUE
3581newobj_slowpath_wb_protected(VALUE klass, VALUE flags, rb_objspace_t *objspace, size_t heap_idx)
3582{
3583 return newobj_slowpath(klass, flags, objspace, TRUE, heap_idx);
3584}
3585
3586static VALUE
3587newobj_slowpath_wb_unprotected(VALUE klass, VALUE flags, rb_objspace_t *objspace, size_t heap_idx)
3588{
3589 return newobj_slowpath(klass, flags, objspace, FALSE, heap_idx);
3590}
3591
3592VALUE
3593rb_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)
3594{
3595 VALUE obj;
3596 rb_objspace_t *objspace = objspace_ptr;
3597
3598 /* There is no per-Ractor cache; the argument stays for ABI compatibility with other
3599 * GC implementations such as MMTk. */
3600 (void)cache_ptr;
3601
3602 RB_DEBUG_COUNTER_INC(obj_newobj);
3603 (void)RB_DEBUG_COUNTER_INC_IF(obj_newobj_wb_unprotected, !wb_protected);
3604
3605 if (RB_UNLIKELY(stress_to_class)) {
3606 if (rb_hash_lookup2(stress_to_class, klass, Qundef) != Qundef) {
3607 rb_memerror();
3608 }
3609 }
3610
3611 size_t heap_idx = heap_idx_for_size(alloc_size);
3612 *actual_alloc_size = heap_slot_size((unsigned char)heap_idx);
3613
3614 if (!RB_UNLIKELY(during_gc || ruby_gc_stressful) &&
3615 wb_protected) {
3616 obj = newobj_alloc(objspace, heap_idx);
3617 newobj_init(klass, flags, wb_protected, objspace, obj);
3618 }
3619 else {
3620 RB_DEBUG_COUNTER_INC(obj_newobj_slowpath);
3621
3622 obj = wb_protected ?
3623 newobj_slowpath_wb_protected(klass, flags, objspace, heap_idx) :
3624 newobj_slowpath_wb_unprotected(klass, flags, objspace, heap_idx);
3625 }
3626
3627 return obj;
3628}
3629
3630static int
3631ptr_in_page_body_p(const void *ptr, const void *memb)
3632{
3633 struct heap_page *page = *(struct heap_page **)memb;
3634 uintptr_t p_body = (uintptr_t)page->body;
3635
3636 if ((uintptr_t)ptr >= p_body) {
3637 return (uintptr_t)ptr < (p_body + HEAP_PAGE_SIZE) ? 0 : 1;
3638 }
3639 else {
3640 return -1;
3641 }
3642}
3643
3644PUREFUNC(static inline struct heap_page *heap_page_for_ptr(rb_objspace_t *objspace, uintptr_t ptr);)
3645static inline struct heap_page *
3646heap_page_for_ptr(rb_objspace_t *objspace, uintptr_t ptr)
3647{
3648 struct heap_page **res;
3649
3650 if (ptr < (uintptr_t)heap_pages_lomem ||
3651 ptr > (uintptr_t)heap_pages_himem) {
3652 return NULL;
3653 }
3654
3655 res = bsearch((void *)ptr, rb_darray_ref(objspace->heap_pages.sorted, 0),
3656 rb_darray_size(objspace->heap_pages.sorted), sizeof(struct heap_page *),
3657 ptr_in_page_body_p);
3658
3659 if (res) {
3660 return *res;
3661 }
3662 else {
3663 return NULL;
3664 }
3665}
3666
3667PUREFUNC(static inline bool is_pointer_to_heap(rb_objspace_t *objspace, const void *ptr);)
3668static inline bool
3669is_pointer_to_heap(rb_objspace_t *objspace, const void *ptr)
3670{
3671 register uintptr_t p = (uintptr_t)ptr;
3672 register struct heap_page *page;
3673
3674 RB_DEBUG_COUNTER_INC(gc_isptr_trial);
3675
3676 if (p < heap_pages_lomem || p > heap_pages_himem) return FALSE;
3677 RB_DEBUG_COUNTER_INC(gc_isptr_range);
3678
3679 if (p % sizeof(VALUE) != 0) return FALSE;
3680 RB_DEBUG_COUNTER_INC(gc_isptr_align);
3681
3682 page = heap_page_for_ptr(objspace, (uintptr_t)ptr);
3683 if (page) {
3684 RB_DEBUG_COUNTER_INC(gc_isptr_maybe);
3685 if (heap_page_in_global_empty_pages_pool(objspace, page)) {
3686 return FALSE;
3687 }
3688 else {
3689 if (p < page->start) return FALSE;
3690 if (p >= page->start + (page->total_slots * page->slot_size)) return FALSE;
3691 if ((p - page->start) % page->slot_size != 0) return FALSE;
3692
3693 return TRUE;
3694 }
3695 }
3696 return FALSE;
3697}
3698
3699/*
3700 * Is this object live in the given objspace. For foreign objects in other object spaces,
3701 * it returns `false`. NOTE: this does NOT check whether or not it's unmarked during the process
3702 * of lazy sweeping.
3703 */
3704bool
3705rb_gc_impl_live_object_p(void *objspace_ptr, const void *ptr)
3706{
3707 rb_objspace_t *objspace = objspace_ptr;
3708
3709 /* Whether ptr refers to a live object. is_pointer_to_heap is the
3710 * address-only check; T_NONE, T_MOVED, and T_ZOMBIE slots are valid heap
3711 * addresses but not live objects. */
3712 if (!is_pointer_to_heap(objspace, ptr)) return false;
3713
3714 VALUE obj = (VALUE)ptr;
3715 bool live = false;
3716 asan_unpoisoning_object(obj) {
3717 switch (BUILTIN_TYPE(obj)) {
3718 case T_NONE:
3719 case T_MOVED:
3720 case T_ZOMBIE:
3721 break;
3722 default:
3723 live = true;
3724 break;
3725 }
3726 }
3727 return live;
3728}
3729
3730/* Flags preserved from the original object when it becomes a zombie, and so also the
3731 * only ones that may legitimately be set on one. */
3732#define ZOMBIE_OBJ_KEPT_FLAGS (FL_FINALIZE)
3733
3734void
3735rb_gc_impl_make_zombie(void *objspace_ptr, VALUE obj, void (*dfree)(void *), void *data)
3736{
3737 rb_objspace_t *objspace = objspace_ptr;
3738
3739 struct RZombie *zombie = RZOMBIE(obj);
3740 zombie->flags = T_ZOMBIE | (zombie->flags & ZOMBIE_OBJ_KEPT_FLAGS);
3741 zombie->dfree = dfree;
3742 zombie->data = data;
3743 VALUE prev, next = heap_pages_deferred_final;
3744 do {
3745 zombie->next = prev = next;
3746 next = RUBY_ATOMIC_VALUE_CAS(heap_pages_deferred_final, prev, obj);
3747 } while (next != prev);
3748
3749 struct heap_page *page = GET_HEAP_PAGE(obj);
3750 page->final_slots++;
3751 page->heap->final_slots_count++;
3752}
3753
3754static void
3755tdata_unsafe_free_chunk_reset(struct tdata_unsafe_free_chunk *chunk)
3756{
3757 chunk->next = NULL;
3758 chunk->count = 0;
3759 chunk->embed_xfree_bits = 0;
3760}
3761
3762static struct tdata_unsafe_free_chunk *
3763tdata_unsafe_free_chunk_alloc(void)
3764{
3765 /* Pops race each other (several Ractors can be sweeping), but pushes happen only
3766 * inside the drain, which holds a VM barrier -- and a barrier cannot complete while
3767 * a Ractor is inside gc_sweep_page. No push ever overlaps a pop, so the head only
3768 * moves forward and this CAS pop needs no ABA tagging. A sweep performed by a
3769 * thread other than the objspace's owner would break that. */
3770 struct tdata_unsafe_free_chunk *head =
3771 rbimpl_atomic_ptr_load((void **)&global_objspace->tdata_unsafe_free_cache,
3772 RBIMPL_ATOMIC_ACQUIRE);
3773 while (head) {
3774 struct tdata_unsafe_free_chunk *prev =
3775 rbimpl_atomic_ptr_cas((void **)&global_objspace->tdata_unsafe_free_cache,
3776 head, head->next,
3777 RBIMPL_ATOMIC_ACQ_REL, RBIMPL_ATOMIC_ACQUIRE);
3778 if (prev == head) {
3779 rbimpl_atomic_size_dec(&global_objspace->tdata_unsafe_free_cache_len,
3780 RBIMPL_ATOMIC_RELAXED);
3781 tdata_unsafe_free_chunk_reset(head);
3782 return head;
3783 }
3784 head = prev;
3785 }
3786
3787 /* Not xmalloc: this runs mid-sweep, and the chunks are GC bookkeeping that should not
3788 * feed back into malloc_increase (mark stack chunks do the same). */
3789 struct tdata_unsafe_free_chunk *chunk = malloc(sizeof(struct tdata_unsafe_free_chunk));
3790 if (!chunk) rb_memerror();
3791 tdata_unsafe_free_chunk_reset(chunk);
3792 return chunk;
3793}
3794
3795/* Hand this objspace's partial chunk to the global stack. The entries were counted as
3796 * they were appended, so the pending count does not change here. */
3797static void
3798gc_tdata_unsafe_free_publish(rb_objspace_t *objspace)
3799{
3800 struct tdata_unsafe_free_chunk *chunk = objspace->tdata_unsafe_free_chunk;
3801 if (chunk == NULL) return;
3802 GC_ASSERT(chunk->count > 0);
3803 objspace->tdata_unsafe_free_chunk = NULL;
3804
3805 struct tdata_unsafe_free_chunk *prev, *head =
3806 rbimpl_atomic_ptr_load((void **)&global_objspace->tdata_unsafe_free_published,
3807 RBIMPL_ATOMIC_RELAXED);
3808 do {
3809 chunk->next = prev = head;
3810 head = rbimpl_atomic_ptr_cas((void **)&global_objspace->tdata_unsafe_free_published,
3811 prev, chunk,
3812 RBIMPL_ATOMIC_ACQ_REL, RBIMPL_ATOMIC_ACQUIRE);
3813 } while (head != prev);
3814}
3815
3816/* Copy out what obj's deferred free needs, running no dfree. Returns true when the
3817 * caller may reclaim the slot and false when obj became a zombie, matching rb_gc_obj_free. */
3818static bool
3819gc_defer_thread_unsafe_free(rb_objspace_t *objspace, VALUE obj, bool *trigger)
3820{
3821 GC_ASSERT(!((uintptr_t)RTYPEDDATA(obj)->type & TYPED_DATA_EMBEDDED));
3822 const rb_data_type_t *type = RTYPEDDATA_TYPE(obj);
3823 void *data = RTYPEDDATA(obj)->data;
3824 GC_ASSERT(data != NULL);
3825
3826 rb_gc_obj_free_vm_weak_references(obj);
3827
3828 size_t count = rbimpl_atomic_size_fetch_add(&global_objspace->tdata_deferred_free_count, 1,
3829 RBIMPL_ATOMIC_RELAXED) + 1;
3830 if (!*trigger && count >= TDATA_DEFERRED_FREE_THRESHOLD) {
3831 *trigger = true;
3832 }
3833
3834 struct tdata_unsafe_free_chunk *chunk = objspace->tdata_unsafe_free_chunk;
3835 if (chunk == NULL) {
3836 chunk = objspace->tdata_unsafe_free_chunk = tdata_unsafe_free_chunk_alloc();
3837 }
3838 if (type->flags & RUBY_TYPED_EMBEDDABLE) {
3839 chunk->embed_xfree_bits |= (uint32_t)1 << chunk->count;
3840 }
3841 struct tdata_unsafe_free_entry *entry = &chunk->entries[chunk->count++];
3842 entry->dfree = type->function.dfree;
3843 entry->data = data;
3844 if (chunk->count == TDATA_UNSAFE_FREE_CHUNK_CAPA) {
3845 gc_tdata_unsafe_free_publish(objspace);
3846 }
3847
3848 if (FL_TEST_RAW(obj, FL_FINALIZE)) {
3849 /* The dfree is on the side list now, so this zombie carries none: it goes on the
3850 * regular deferred list, where the owner runs its Ruby finalizer promptly and
3851 * reclaims the slot, instead of waiting for the barrier. */
3852 rb_gc_impl_make_zombie(objspace, obj, 0, 0);
3853 return false;
3854 }
3855 return true;
3856}
3857
3858typedef int each_obj_callback(void *, void *, size_t, void *);
3859typedef int each_page_callback(struct heap_page *, void *);
3860
3863 bool reenable_incremental;
3864
3865 /* Visit only the pages that hold shareable objects, so a foreign Ractor's objspace
3866 * can be walked for its shareable objects alone, without touching the rest of its
3867 * isolated heap. */
3868 bool shareable_only;
3869
3870 /* Set when walking a foreign objspace without settling its stopped lazy sweep
3871 * (settling would run the owner's obj_free and dfree on this thread). Objects the
3872 * sweep is about to free are skipped: on an unswept page, unmarked means dead. */
3873 bool skip_unswept_dead;
3874
3875 each_obj_callback *each_obj_callback;
3876 each_page_callback *each_page_callback;
3877 void *data;
3878
3879 struct heap_page **pages[HEAP_COUNT];
3880 size_t pages_counts[HEAP_COUNT];
3881};
3882
3883static VALUE
3884objspace_each_objects_ensure(VALUE arg)
3885{
3886 struct each_obj_data *data = (struct each_obj_data *)arg;
3887 rb_objspace_t *objspace = data->objspace;
3888
3889 /* Reenable incremental GC */
3890 if (data->reenable_incremental) {
3891 objspace->flags.dont_incremental = FALSE;
3892 }
3893
3894 for (int i = 0; i < HEAP_COUNT; i++) {
3895 struct heap_page **pages = data->pages[i];
3896 free(pages);
3897 }
3898
3899 return Qnil;
3900}
3901
3902static VALUE
3903objspace_each_objects_try(VALUE arg)
3904{
3905 struct each_obj_data *data = (struct each_obj_data *)arg;
3906 rb_objspace_t *objspace = data->objspace;
3907
3908 /* Copy pages from all heaps to their respective buffers. */
3909 for (int i = 0; i < HEAP_COUNT; i++) {
3910 rb_heap_t *heap = &heaps[i];
3911 size_t size = heap->total_pages * sizeof(struct heap_page *);
3912
3913 struct heap_page **pages = malloc(size);
3914 if (!pages) rb_memerror();
3915
3916 /* Set up pages buffer by iterating over all pages in the current eden
3917 * heap. This will be a snapshot of the state of the heap before we
3918 * call the callback over each page that exists in this buffer. Thus it
3919 * is safe for the callback to allocate objects without possibly entering
3920 * an infinite loop. */
3921 struct heap_page *page = 0;
3922 size_t pages_count = 0;
3923 ccan_list_for_each(&heap->pages, page, page_node) {
3924 pages[pages_count] = page;
3925 pages_count++;
3926 }
3927 data->pages[i] = pages;
3928 data->pages_counts[i] = pages_count;
3929 GC_ASSERT(pages_count == heap->total_pages);
3930 }
3931
3932 for (int i = 0; i < HEAP_COUNT; i++) {
3933 rb_heap_t *heap = &heaps[i];
3934 size_t pages_count = data->pages_counts[i];
3935 struct heap_page **pages = data->pages[i];
3936
3937 struct heap_page *page = ccan_list_top(&heap->pages, struct heap_page, page_node);
3938 for (size_t i = 0; i < pages_count; i++) {
3939 /* If we have reached the end of the linked list then there are no
3940 * more pages, so break. */
3941 if (page == NULL) break;
3942
3943 /* If this page does not match the one in the buffer, then move to
3944 * the next page in the buffer. */
3945 if (pages[i] != page) continue;
3946
3947 uintptr_t pstart = (uintptr_t)page->start;
3948 uintptr_t pend = pstart + (page->total_slots * heap->slot_size);
3949
3950 if (data->shareable_only) {
3951 /* Hand shareable objects to the callback one slot at a time, not the
3952 * whole page: walking a foreign Ractor's objspace must never expose its
3953 * unshareable objects, which the caller cannot inspect safely. */
3954 if (page->flags.has_shareable_objects) {
3955 /* This walk runs over a foreign objspace under the barrier and
3956 * must not settle the owner's stopped lazy sweep: settling would run
3957 * the owner's obj_free and dfree on this thread with this Ractor's
3958 * identity (wrong per-Ractor tables, a foreign T_DATA dfree). So no
3959 * gc_rest, and objects the sweep is about to free are skipped: on an
3960 * unswept page unmarked means dead and its shareable bit merely has
3961 * not been bulk-cleared yet. Passing one to the callback would
3962 * resurrect it, handing out a reference the owner's sweep frees as
3963 * soon as the barrier lifts. */
3964 const bool page_unswept = is_lazy_sweeping(objspace) && page->flags.before_sweep;
3965 int planes = CEILDIV(page->total_slots, BITS_BITLENGTH);
3966 uintptr_t base = pstart;
3967 bool stop = false;
3968 for (int j = 0; j < planes && !stop; j++) {
3969 bits_t bits = page->shareable_bits[j];
3970 uintptr_t slot = base;
3971 while (bits) {
3972 if ((bits & 1) && data->each_obj_callback &&
3973 !(page_unswept && !RVALUE_MARKED(objspace, (VALUE)slot)) &&
3974 (*data->each_obj_callback)((void *)slot, (void *)(slot + heap->slot_size),
3975 heap->slot_size, data->data)) {
3976 stop = true;
3977 break;
3978 }
3979 slot += heap->slot_size;
3980 bits >>= 1;
3981 }
3982 base += BITS_BITLENGTH * heap->slot_size;
3983 }
3984 if (stop) break;
3985 }
3986 }
3987 else if (data->skip_unswept_dead &&
3988 is_lazy_sweeping(objspace) && page->flags.before_sweep) {
3989 /* A foreign page pending sweep: hand out the live objects one slot at a
3990 * time and skip the unmarked (dead) ones the owner's sweep frees as soon
3991 * as the barrier lifts. */
3992 bool stop = false;
3993 for (uintptr_t slot = pstart; slot < pend; slot += heap->slot_size) {
3994 if (!RVALUE_MARKED(objspace, (VALUE)slot)) continue;
3995 if (data->each_obj_callback &&
3996 (*data->each_obj_callback)((void *)slot, (void *)(slot + heap->slot_size),
3997 heap->slot_size, data->data)) {
3998 stop = true;
3999 break;
4000 }
4001 }
4002 if (stop) break;
4003 }
4004 else {
4005 if (data->each_obj_callback &&
4006 (*data->each_obj_callback)((void *)pstart, (void *)pend, heap->slot_size, data->data)) {
4007 break;
4008 }
4009 if (data->each_page_callback &&
4010 (*data->each_page_callback)(page, data->data)) {
4011 break;
4012 }
4013 }
4014
4015 page = ccan_list_next(&heap->pages, page, page_node);
4016 }
4017 }
4018
4019 return Qnil;
4020}
4021
4022static void
4023objspace_each_exec(bool protected, struct each_obj_data *each_obj_data)
4024{
4025 /* Disable incremental GC */
4027 bool reenable_incremental = FALSE;
4028 if (protected) {
4029 reenable_incremental = !objspace->flags.dont_incremental;
4030
4031 gc_rest(objspace);
4032 objspace->flags.dont_incremental = TRUE;
4033 }
4034
4035 each_obj_data->reenable_incremental = reenable_incremental;
4036 memset(&each_obj_data->pages, 0, sizeof(each_obj_data->pages));
4037 memset(&each_obj_data->pages_counts, 0, sizeof(each_obj_data->pages_counts));
4038 rb_ensure(objspace_each_objects_try, (VALUE)each_obj_data,
4039 objspace_each_objects_ensure, (VALUE)each_obj_data);
4040}
4041
4042static void
4043objspace_each_objects(rb_objspace_t *objspace, each_obj_callback *callback, void *data, bool protected)
4044{
4045 struct each_obj_data each_obj_data = {
4046 .objspace = objspace,
4047 .each_obj_callback = callback,
4048 .each_page_callback = NULL,
4049 .data = data,
4050 };
4051 objspace_each_exec(protected, &each_obj_data);
4052}
4053
4054void
4055rb_gc_impl_each_objects(void *objspace_ptr, each_obj_callback *callback, void *data)
4056{
4057 objspace_each_objects(objspace_ptr, callback, data, TRUE);
4058}
4059
4060/* Like rb_gc_impl_each_objects but visiting only pages that hold shareable objects, to
4061 * reach a foreign Ractor's shareable objects without walking the rest of its heap. */
4062void
4063rb_gc_impl_each_objects_shareable(void *objspace_ptr, each_obj_callback *callback, void *data)
4064{
4065 struct each_obj_data each_obj_data = {
4066 .objspace = objspace_ptr,
4067 .shareable_only = true,
4068 .each_obj_callback = callback,
4069 .each_page_callback = NULL,
4070 .data = data,
4071 };
4072 /* Not the protected variant: this objspace belongs to another Ractor (the caller
4073 * holds the barrier). The protected path calls gc_rest, which would run the owner's
4074 * stopped lazy sweep (its obj_free and dfree) on the walking thread with the
4075 * walker's Ractor identity (wrong per-Ractor tables, a foreign T_DATA dfree). The
4076 * owner is stopped and its page list is stable, and the walk itself skips dead,
4077 * unswept objects (the shareable_only branch of objspace_each_objects_try). The
4078 * walker's own incremental GC state is untouched, since this is not its objspace. */
4079 objspace_each_exec(FALSE, &each_obj_data);
4080}
4081
4082/* Walk every object of a foreign Ractor's objspace, unshareable ones included. Only for
4083 * callers that hold the barrier and whose callback is pure C (a heap dump, memory
4084 * accounting). As in the shareable walk above, the owner's stopped lazy sweep is not
4085 * settled and dead, unswept objects are skipped by the walk (skip_unswept_dead). */
4086void
4087rb_gc_impl_each_objects_foreign(void *objspace_ptr, each_obj_callback *callback, void *data)
4088{
4089 struct each_obj_data each_obj_data = {
4090 .objspace = objspace_ptr,
4091 .skip_unswept_dead = true,
4092 .each_obj_callback = callback,
4093 .each_page_callback = NULL,
4094 .data = data,
4095 };
4096 objspace_each_exec(FALSE, &each_obj_data);
4097}
4098
4099#if GC_CAN_COMPILE_COMPACTION
4100static void
4101objspace_each_pages(rb_objspace_t *objspace, each_page_callback *callback, void *data, bool protected)
4102{
4103 struct each_obj_data each_obj_data = {
4104 .objspace = objspace,
4105 .each_obj_callback = NULL,
4106 .each_page_callback = callback,
4107 .data = data,
4108 };
4109 objspace_each_exec(protected, &each_obj_data);
4110}
4111#endif
4112
4113VALUE
4114rb_gc_impl_define_finalizer(void *objspace_ptr, VALUE obj, VALUE block)
4115{
4116 rb_objspace_t *objspace = objspace_ptr;
4117 VALUE table;
4118 st_data_t data;
4119
4120 GC_ASSERT(!OBJ_FROZEN(obj));
4121
4122 /* Registering, storing and running finalizers all belong to the object's own
4123 * objspace, so refuse to define one on another Ractor's object (even a shareable
4124 * one): it would land in a table the owner's sweep never consults. */
4125 if (GET_HEAP_OBJSPACE(obj) != objspace) {
4126 rb_raise(rb_eRactorIsolationError,
4127 "can not define a finalizer for an object of another Ractor");
4128 }
4129
4130 RBASIC(obj)->flags |= FL_FINALIZE;
4131
4132 unsigned int lev = RB_GC_VM_LOCK();
4133
4134 if (st_lookup(finalizer_table, obj, &data)) {
4135 table = (VALUE)data;
4136 VALUE dup_table = rb_ary_dup(table);
4137
4138 RB_GC_VM_UNLOCK(lev);
4139 /* avoid duplicate block, table is usually small */
4140 {
4141 long len = RARRAY_LEN(table);
4142 long i;
4143
4144 for (i = 0; i < len; i++) {
4145 VALUE recv = RARRAY_AREF(dup_table, i);
4146 if (rb_equal(recv, block)) { // can't be called with VM lock held
4147 return recv;
4148 }
4149 }
4150 }
4151 lev = RB_GC_VM_LOCK();
4152 RB_GC_GUARD(dup_table);
4153
4154 rb_ary_push(table, block);
4155 }
4156 else {
4157 table = rb_ary_new3(2, rb_obj_id(obj), block);
4158 rb_obj_hide(table);
4159 st_add_direct(finalizer_table, obj, table);
4160 }
4161
4162 RB_GC_VM_UNLOCK(lev);
4163
4164 return block;
4165}
4166
4167void
4168rb_gc_impl_undefine_finalizer(void *objspace_ptr, VALUE obj)
4169{
4170 rb_objspace_t *objspace = objspace_ptr;
4171
4172 GC_ASSERT(!OBJ_FROZEN(obj));
4173
4174 /* Symmetric with define. */
4175 if (GET_HEAP_OBJSPACE(obj) != objspace) {
4176 rb_raise(rb_eRactorIsolationError,
4177 "can not undefine a finalizer of an object of another Ractor");
4178 }
4179
4180 st_data_t data = obj;
4181
4182 int lev = RB_GC_VM_LOCK();
4183 st_delete(finalizer_table, &data, 0);
4184 RB_GC_VM_UNLOCK(lev);
4185
4186 FL_UNSET(obj, FL_FINALIZE);
4187}
4188
4189void
4190rb_gc_impl_copy_finalizer(void *objspace_ptr, VALUE dest, VALUE obj)
4191{
4192 /* Finalizers do not cross objspaces: a copy of another Ractor's object starts with
4193 * none (guards the public rb_gc_copy_finalizer C API; no in-tree caller crosses).
4194 * A same-objspace copy behaves as before. Table accessed under the VM lock. */
4195 rb_objspace_t *objspace = objspace_ptr;
4196 VALUE table;
4197 st_data_t data;
4198
4199 if (!FL_TEST(obj, FL_FINALIZE)) return;
4200 if (GET_HEAP_OBJSPACE(obj) != objspace) return;
4201
4202 int lev = RB_GC_VM_LOCK();
4203 if (RB_LIKELY(st_lookup(finalizer_table, obj, &data))) {
4204 table = rb_ary_dup((VALUE)data);
4205 RARRAY_ASET(table, 0, rb_obj_id(dest));
4206 st_insert(finalizer_table, dest, table);
4207 FL_SET(dest, FL_FINALIZE);
4208 }
4209 else {
4210 rb_bug("rb_gc_copy_finalizer: FL_FINALIZE set but not found in finalizer_table: %s", rb_obj_info(obj));
4211 }
4212 RB_GC_VM_UNLOCK(lev);
4213}
4214
4215static VALUE
4216get_final(long i, void *data)
4217{
4218 VALUE table = (VALUE)data;
4219
4220 return RARRAY_AREF(table, i + 1);
4221}
4222
4223static void
4224run_final(rb_objspace_t *objspace, VALUE zombie)
4225{
4226 if (RZOMBIE(zombie)->dfree) {
4227 RZOMBIE(zombie)->dfree(RZOMBIE(zombie)->data);
4228 }
4229
4230 st_data_t key = (st_data_t)zombie;
4231 if (FL_TEST_RAW(zombie, FL_FINALIZE)) {
4232 FL_UNSET(zombie, FL_FINALIZE);
4233 st_data_t table;
4234 if (st_delete(finalizer_table, &key, &table)) {
4235 rb_gc_run_obj_finalizer(RARRAY_AREF(table, 0), RARRAY_LEN(table) - 1, get_final, (void *)table);
4236 }
4237 else {
4238 rb_bug("FL_FINALIZE flag is set, but finalizers are not found");
4239 }
4240 }
4241 else {
4242 GC_ASSERT(!st_lookup(finalizer_table, key, NULL));
4243 }
4244}
4245
4246static void
4247finalize_list(rb_objspace_t *objspace, VALUE zombie)
4248{
4249 while (zombie) {
4250 VALUE next_zombie;
4251 struct heap_page *page;
4252 rb_asan_unpoison_object(zombie, false);
4253 next_zombie = RZOMBIE(zombie)->next;
4254 page = GET_HEAP_PAGE(zombie);
4255
4256 run_final(objspace, zombie);
4257 {
4258 GC_ASSERT(BUILTIN_TYPE(zombie) == T_ZOMBIE);
4259 GC_ASSERT(page->heap->final_slots_count > 0);
4260 GC_ASSERT(page->final_slots > 0);
4261
4262 page->heap->final_slots_count--;
4263 page->final_slots--;
4264 page->free_slots++;
4265 RVALUE_AGE_SET_BITMAP(zombie, 0);
4266 heap_page_add_free_region(objspace, page, zombie);
4267 page->heap->total_freed_objects++;
4268 }
4269
4270 zombie = next_zombie;
4271 }
4272}
4273
4274static void
4275finalize_zombies(rb_objspace_t *objspace)
4276{
4277 VALUE zombie;
4278 while ((zombie = RUBY_ATOMIC_VALUE_EXCHANGE(heap_pages_deferred_final, 0)) != 0) {
4279 finalize_list(objspace, zombie);
4280 }
4281}
4282
4283static void
4284finalize_deferred(rb_objspace_t *objspace)
4285{
4286 rb_gc_set_pending_interrupt();
4287 finalize_zombies(objspace);
4288 rb_gc_unset_pending_interrupt();
4289}
4290
4291static void
4292gc_finalize_deferred(void *dmy)
4293{
4294 /* One postponed job is shared by every objspace: the preregistration table only
4295 * holds about 32 entries and Ractors are created continuously. A deferred finalizer
4296 * belongs to the objspace of the thread that ran the job, i.e. the current one. */
4297 rb_objspace_t *objspace = rb_gc_get_objspace();
4298 if (RUBY_ATOMIC_EXCHANGE(finalizing, 1)) return;
4299
4300 finalize_deferred(objspace);
4301 RUBY_ATOMIC_SET(finalizing, 0);
4302}
4303
4304static void
4305gc_finalize_deferred_register(rb_objspace_t *objspace)
4306{
4307 /* Enqueue gc_finalize_deferred on this objspace's owning Ractor. A global GC can
4308 * defer a foreign objspace's finalizers, and those must run on their owner rather
4309 * than on the driver. */
4310 rb_gc_trigger_finalize_deferred(objspace, objspace->finalize_deferred_pjob);
4311}
4312
4313static int pop_mark_stack(mark_stack_t *stack, VALUE *data);
4314
4315/* Throw away an unfinished incremental mark and leave the objspace in gc_mode_none. The
4316 * mark bits the partial mark set stay behind, so the caller must clear them before the
4317 * heap is collected again. */
4318static void
4319gc_abort_incremental_marking(rb_objspace_t *objspace)
4320{
4321 GC_ASSERT(is_incremental_marking(objspace));
4322
4323 VALUE obj;
4324 while (pop_mark_stack(&objspace->mark_stack, &obj));
4325
4326 /* gc_grey records the weak references it greys for gc_marks_finish to resolve; this
4327 * cycle never reaches it, and the entries would outlive their objects. */
4328 rb_darray_clear(objspace->weak_references);
4329
4330 objspace->flags.during_incremental_marking = FALSE;
4331 gc_mode_set(objspace, gc_mode_none);
4332}
4333
4334static void
4335gc_abort(void *objspace_ptr)
4336{
4337 rb_objspace_t *objspace = objspace_ptr;
4338
4339 if (is_incremental_marking(objspace)) {
4340 gc_abort_incremental_marking(objspace);
4341 }
4342
4343 if (is_lazy_sweeping(objspace)) {
4344 objspace->sweeping_heap_count = 0;
4345 for (int i = 0; i < HEAP_COUNT; i++) {
4346 rb_heap_t *heap = &heaps[i];
4347
4348 heap->sweeping_page = NULL;
4349 struct heap_page *page = NULL;
4350
4351 ccan_list_for_each(&heap->pages, page, page_node) {
4352 page->flags.before_sweep = false;
4353 }
4354 }
4355 }
4356
4357 for (int i = 0; i < HEAP_COUNT; i++) {
4358 rb_heap_t *heap = &heaps[i];
4359 gc_bitmaps_clear(objspace, heap, false);
4360 }
4361
4362 gc_mode_set(objspace, gc_mode_none);
4363}
4364
4365#if VERIFY_FREE_SIZE
4366# ifdef RB_THREAD_LOCAL_SPECIFIER
4367# define GC_FREEING_OBJ_TLS RB_THREAD_LOCAL_SPECIFIER
4368# else
4369# define GC_FREEING_OBJ_TLS
4370# endif
4371
4372static GC_FREEING_OBJ_TLS VALUE gc_freeing_obj;
4373
4374/* Remember what we are tearing down so that a bad xfree() underneath can name
4375 * the object and not just the buffer. Saved and restored because a dfree
4376 * callback can free another object. */
4377static bool
4378gc_obj_free(void *objspace, VALUE obj)
4379{
4380 VALUE prev = gc_freeing_obj;
4381 gc_freeing_obj = obj;
4382
4383 bool freed = rb_gc_obj_free(objspace, obj);
4384
4385 gc_freeing_obj = prev;
4386 return freed;
4387}
4388
4389static const char *
4390gc_freeing_obj_info(void)
4391{
4392 /* Not thread-local: only reachable from a rb_bug() path, where a second
4393 * thread racing us is already unrecoverable. */
4394 static char buf[128];
4395
4396 if (!gc_freeing_obj) return NULL;
4397
4398 snprintf(buf, sizeof(buf), "%p %s", (void *)gc_freeing_obj, rb_obj_info(gc_freeing_obj));
4399 return buf;
4400}
4401#else
4402# define gc_obj_free(objspace, obj) rb_gc_obj_free((objspace), (obj))
4403# define gc_freeing_obj_info() NULL
4404#endif
4405
4406void
4407rb_gc_impl_shutdown_free_objects(void *objspace_ptr)
4408{
4409 rb_objspace_t *objspace = objspace_ptr;
4410
4411 for (size_t i = 0; i < rb_darray_size(objspace->heap_pages.sorted); i++) {
4412 struct heap_page *page = rb_darray_get(objspace->heap_pages.sorted, i);
4413 short stride = page->slot_size;
4414
4415 uintptr_t p = (uintptr_t)page->start;
4416 uintptr_t pend = p + page->total_slots * stride;
4417 for (; p < pend; p += stride) {
4418 VALUE vp = (VALUE)p;
4419 asan_unpoisoning_object(vp) {
4420 if (RB_BUILTIN_TYPE(vp) != T_NONE) {
4421 rb_gc_obj_free_vm_weak_references(vp);
4422 if (gc_obj_free(objspace, vp)) {
4423 RBASIC(vp)->flags = 0;
4424 }
4425 }
4426 }
4427 }
4428 }
4429}
4430
4431static int
4432rb_gc_impl_shutdown_call_finalizer_i(st_data_t key, st_data_t val, st_data_t _data)
4433{
4434 VALUE obj = (VALUE)key;
4435 VALUE table = (VALUE)val;
4436
4437 GC_ASSERT(RB_FL_TEST(obj, FL_FINALIZE));
4438 GC_ASSERT(RB_BUILTIN_TYPE(val) == T_ARRAY);
4439
4440 rb_gc_run_obj_finalizer(RARRAY_AREF(table, 0), RARRAY_LEN(table) - 1, get_final, (void *)table);
4441
4442 FL_UNSET(obj, FL_FINALIZE);
4443
4444 return ST_DELETE;
4445}
4446
4447void
4448rb_gc_impl_shutdown_call_finalizer(void *objspace_ptr)
4449{
4450 rb_objspace_t *objspace = objspace_ptr;
4451
4452#if RGENGC_CHECK_MODE >= 2
4453 gc_verify_internal_consistency(objspace);
4454#endif
4455
4456 /* prohibit incremental GC */
4457 objspace->flags.dont_incremental = 1;
4458
4459 if (RUBY_ATOMIC_EXCHANGE(finalizing, 1)) {
4460 /* Abort incremental marking and lazy sweeping to speed up shutdown. */
4461 gc_abort(objspace);
4462 dont_gc_on();
4463 return;
4464 }
4465
4466 while (finalizer_table->num_entries) {
4467 st_foreach(finalizer_table, rb_gc_impl_shutdown_call_finalizer_i, 0);
4468 }
4469
4470 /* run finalizers */
4471 finalize_deferred(objspace);
4472 GC_ASSERT(heap_pages_deferred_final == 0);
4473
4474 /* Deferred non-thread-safe frees: their objects are long gone, so the object walk
4475 * below will not reach them. Reap them here. */
4476 gc_tdata_unsafe_drain_objspaces(&objspace, 1);
4477
4478 /* Abort incremental marking and lazy sweeping to speed up shutdown. */
4479 gc_abort(objspace);
4480
4481 /* prohibit GC because force T_DATA finalizers can break an object graph consistency */
4482 dont_gc_on();
4483
4484 /* running data/file finalizers are part of garbage collection */
4485 unsigned int lock_lev;
4486 gc_enter(objspace, gc_enter_event_finalizer, &lock_lev);
4487
4488 /* run data/file object's finalizers */
4489 for (size_t i = 0; i < rb_darray_size(objspace->heap_pages.sorted); i++) {
4490 struct heap_page *page = rb_darray_get(objspace->heap_pages.sorted, i);
4491 short stride = page->slot_size;
4492
4493 uintptr_t p = (uintptr_t)page->start;
4494 uintptr_t pend = p + page->total_slots * stride;
4495 for (; p < pend; p += stride) {
4496 VALUE vp = (VALUE)p;
4497 asan_unpoisoning_object(vp) {
4498 if (rb_gc_shutdown_call_finalizer_p(vp)) {
4499 rb_gc_obj_free_vm_weak_references(vp);
4500 if (gc_obj_free(objspace, vp)) {
4501 RBASIC(vp)->flags = 0;
4502 }
4503 }
4504 }
4505 }
4506 }
4507
4508 gc_exit(objspace, gc_enter_event_finalizer, &lock_lev);
4509
4510 finalize_zombies(objspace);
4511
4512 st_free_table(finalizer_table);
4513 finalizer_table = 0;
4514 RUBY_ATOMIC_SET(finalizing, 0);
4515}
4516
4517void
4518rb_gc_impl_each_object(void *objspace_ptr, void (*func)(VALUE obj, void *data), void *data)
4519{
4520 rb_objspace_t *objspace = objspace_ptr;
4521
4522 for (size_t i = 0; i < rb_darray_size(objspace->heap_pages.sorted); i++) {
4523 struct heap_page *page = rb_darray_get(objspace->heap_pages.sorted, i);
4524 short stride = page->slot_size;
4525
4526 uintptr_t p = (uintptr_t)page->start;
4527 uintptr_t pend = p + page->total_slots * stride;
4528 for (; p < pend; p += stride) {
4529 VALUE obj = (VALUE)p;
4530
4531 asan_unpoisoning_object(obj) {
4532 func(obj, data);
4533 }
4534 }
4535 }
4536}
4537
4538/*
4539 ------------------------ Garbage Collection ------------------------
4540*/
4541
4542/* Sweeping */
4543
4544static size_t
4545objspace_available_slots(rb_objspace_t *objspace)
4546{
4547 size_t total_slots = 0;
4548 for (int i = 0; i < HEAP_COUNT; i++) {
4549 rb_heap_t *heap = &heaps[i];
4550 total_slots += heap->total_slots;
4551 }
4552 return total_slots;
4553}
4554
4555static size_t
4556objspace_live_slots(rb_objspace_t *objspace)
4557{
4558 return total_allocated_objects(objspace) - total_freed_objects(objspace) - total_final_slots_count(objspace);
4559}
4560
4561static size_t
4562objspace_free_slots(rb_objspace_t *objspace)
4563{
4564 return objspace_available_slots(objspace) - objspace_live_slots(objspace) - total_final_slots_count(objspace);
4565}
4566
4567static void
4568gc_setup_mark_bits(struct heap_page *page)
4569{
4570 /* copy oldgen bitmap to mark bitmap */
4571 memcpy(&page->mark_bits[0], &page->uncollectible_bits[0], HEAP_PAGE_BITMAP_SIZE);
4572}
4573
4574static int gc_is_moveable_obj(rb_objspace_t *objspace, VALUE obj);
4575static VALUE gc_move(rb_objspace_t *objspace, VALUE scan, VALUE free, struct heap_page *src_page, struct heap_page *dest_page);
4576
4577#if defined(_WIN32)
4578enum {HEAP_PAGE_LOCK = PAGE_NOACCESS, HEAP_PAGE_UNLOCK = PAGE_READWRITE};
4579
4580static BOOL
4581protect_page_body(struct heap_page_body *body, DWORD protect)
4582{
4583 DWORD old_protect;
4584 return VirtualProtect(body, HEAP_PAGE_SIZE, protect, &old_protect) != 0;
4585}
4586#elif defined(__wasi__)
4587// wasi-libc's mprotect emulation does not support PROT_NONE
4588enum {HEAP_PAGE_LOCK, HEAP_PAGE_UNLOCK};
4589#define protect_page_body(body, protect) 1
4590#else
4591enum {HEAP_PAGE_LOCK = PROT_NONE, HEAP_PAGE_UNLOCK = PROT_READ | PROT_WRITE};
4592#define protect_page_body(body, protect) !mprotect((body), HEAP_PAGE_SIZE, (protect))
4593#endif
4594
4595static void
4596lock_page_body(rb_objspace_t *objspace, struct heap_page_body *body)
4597{
4598 if (!protect_page_body(body, HEAP_PAGE_LOCK)) {
4599 rb_bug("Couldn't protect page %p, errno: %s", (void *)body, strerror(errno));
4600 }
4601 else {
4602 gc_report(5, objspace, "Protecting page in move %p\n", (void *)body);
4603 }
4604}
4605
4606static void
4607unlock_page_body(rb_objspace_t *objspace, struct heap_page_body *body)
4608{
4609 if (!protect_page_body(body, HEAP_PAGE_UNLOCK)) {
4610 rb_bug("Couldn't unprotect page %p, errno: %s", (void *)body, strerror(errno));
4611 }
4612 else {
4613 gc_report(5, objspace, "Unprotecting page in move %p\n", (void *)body);
4614 }
4615}
4616
4617static uintptr_t
4618heap_page_alloc_slot_from_region(struct heap_page *free_page)
4619{
4620 asan_unlock_freelist(free_page);
4621 struct free_region *region = free_page->free_region;
4622 asan_lock_freelist(free_page);
4623
4624 if (region == NULL) {
4625 return 0;
4626 }
4627
4628 rb_asan_unpoison_object((VALUE)region, false);
4629 GC_ASSERT(RB_TYPE_P((VALUE)region, T_NONE));
4630 uintptr_t dest = (uintptr_t)region;
4631 uintptr_t region_end = region->end;
4632 struct free_region *next = region->next;
4633
4634 uintptr_t new_start = dest + free_page->slot_size;
4635
4636 asan_unlock_freelist(free_page);
4637 if (new_start < region_end) {
4638 VALUE next_start = (VALUE)new_start;
4639 rb_asan_unpoison_object(next_start, false);
4640 struct free_region *new_region = (struct free_region *)new_start;
4641 new_region->flags = 0;
4642 new_region->end = region_end;
4643 new_region->next = next;
4644 rb_asan_poison_object(next_start);
4645 free_page->free_region = new_region;
4646 }
4647 else {
4648 free_page->free_region = next;
4649 }
4650 asan_lock_freelist(free_page);
4651
4652 return dest;
4653}
4654
4655static bool
4656try_move(rb_objspace_t *objspace, rb_heap_t *heap, struct heap_page *free_page, VALUE src)
4657{
4658 GC_ASSERT(gc_is_moveable_obj(objspace, src));
4659
4660 struct heap_page *src_page = GET_HEAP_PAGE(src);
4661 if (!free_page) {
4662 return false;
4663 }
4664
4665 /* We should return true if either src is successfully moved, or src is
4666 * unmoveable. A false return will cause the sweeping cursor to be
4667 * incremented to the next page, and src will attempt to move again */
4668 GC_ASSERT(RVALUE_MARKED(objspace, src));
4669
4670 uintptr_t dest_slot = heap_page_alloc_slot_from_region(free_page);
4671 if (dest_slot == 0) {
4672 return false;
4673 }
4674 VALUE dest = (VALUE)dest_slot;
4675
4676 GC_ASSERT(RB_BUILTIN_TYPE(dest) == T_NONE);
4677
4678 if (src_page->slot_size > free_page->slot_size) {
4679 objspace->rcompactor.moved_down_count_table[BUILTIN_TYPE(src)]++;
4680 }
4681 else if (free_page->slot_size > src_page->slot_size) {
4682 objspace->rcompactor.moved_up_count_table[BUILTIN_TYPE(src)]++;
4683 }
4684 objspace->rcompactor.moved_count_table[BUILTIN_TYPE(src)]++;
4685 objspace->rcompactor.total_moved++;
4686
4687 gc_move(objspace, src, dest, src_page, free_page);
4688 gc_pin(objspace, src);
4689 free_page->free_slots--;
4690
4691 return true;
4692}
4693
4694static void
4695gc_unprotect_pages(rb_objspace_t *objspace, rb_heap_t *heap)
4696{
4697 struct heap_page *cursor = heap->compact_cursor;
4698
4699 while (cursor) {
4700 unlock_page_body(objspace, cursor->body);
4701 cursor = ccan_list_next(&heap->pages, cursor, page_node);
4702 }
4703}
4704
4705static void gc_update_references(rb_objspace_t *objspace);
4706static void gc_update_references_heap(rb_objspace_t *objspace);
4707static void gc_update_references_global(rb_objspace_t *objspace);
4708#if GC_CAN_COMPILE_COMPACTION
4709static void invalidate_moved_page(rb_objspace_t *objspace, struct heap_page *page);
4710#endif
4711
4712#if defined(__MINGW32__) || defined(_WIN32)
4713# define GC_COMPACTION_SUPPORTED 1
4714#else
4715/* If not MinGW, Windows, or does not have mmap, we cannot use mprotect for
4716 * the read barrier, so we must disable compaction. */
4717# define GC_COMPACTION_SUPPORTED (GC_CAN_COMPILE_COMPACTION && HEAP_PAGE_ALLOC_USE_MMAP)
4718#endif
4719
4720#if GC_CAN_COMPILE_COMPACTION
4721static void
4722read_barrier_handler(uintptr_t address)
4723{
4724 rb_objspace_t *objspace = (rb_objspace_t *)rb_gc_get_objspace();
4725
4726 struct heap_page_body *page_body = GET_PAGE_BODY(address);
4727
4728 /* If the page_body is NULL, then mprotect cannot handle it and will crash
4729 * with "Cannot allocate memory". */
4730 if (page_body == NULL) {
4731 rb_bug("read_barrier_handler: segmentation fault at %p", (void *)address);
4732 }
4733
4734 int lev = RB_GC_VM_LOCK();
4735 {
4736 unlock_page_body(objspace, page_body);
4737
4738 objspace->profile.read_barrier_faults++;
4739
4740 invalidate_moved_page(objspace, GET_HEAP_PAGE(address));
4741 }
4742 RB_GC_VM_UNLOCK(lev);
4743}
4744#endif
4745
4746#if !GC_CAN_COMPILE_COMPACTION
4747static void
4748uninstall_handlers(void)
4749{
4750 /* no-op */
4751}
4752
4753static void
4754install_handlers(void)
4755{
4756 /* no-op */
4757}
4758#elif defined(_WIN32)
4759static LPTOP_LEVEL_EXCEPTION_FILTER old_handler;
4760typedef void (*signal_handler)(int);
4761static signal_handler old_sigsegv_handler;
4762
4763static LONG WINAPI
4764read_barrier_signal(EXCEPTION_POINTERS *info)
4765{
4766 /* EXCEPTION_ACCESS_VIOLATION is what's raised by access to protected pages */
4767 if (info->ExceptionRecord->ExceptionCode == EXCEPTION_ACCESS_VIOLATION) {
4768 /* > The second array element specifies the virtual address of the inaccessible data.
4769 * https://docs.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-exception_record
4770 *
4771 * Use this address to invalidate the page */
4772 read_barrier_handler((uintptr_t)info->ExceptionRecord->ExceptionInformation[1]);
4773 return EXCEPTION_CONTINUE_EXECUTION;
4774 }
4775 else {
4776 return EXCEPTION_CONTINUE_SEARCH;
4777 }
4778}
4779
4780static void
4781uninstall_handlers(void)
4782{
4783 signal(SIGSEGV, old_sigsegv_handler);
4784 SetUnhandledExceptionFilter(old_handler);
4785}
4786
4787static void
4788install_handlers(void)
4789{
4790 /* Remove SEGV handler so that the Unhandled Exception Filter handles it */
4791 old_sigsegv_handler = signal(SIGSEGV, NULL);
4792 /* Unhandled Exception Filter has access to the violation address similar
4793 * to si_addr from sigaction */
4794 old_handler = SetUnhandledExceptionFilter(read_barrier_signal);
4795}
4796#else
4797static struct sigaction old_sigbus_handler;
4798static struct sigaction old_sigsegv_handler;
4799
4800#ifdef HAVE_MACH_TASK_EXCEPTION_PORTS
4801static exception_mask_t old_exception_masks[32];
4802static mach_port_t old_exception_ports[32];
4803static exception_behavior_t old_exception_behaviors[32];
4804static thread_state_flavor_t old_exception_flavors[32];
4805static mach_msg_type_number_t old_exception_count;
4806
4807static void
4808disable_mach_bad_access_exc(void)
4809{
4810 old_exception_count = sizeof(old_exception_masks) / sizeof(old_exception_masks[0]);
4811 task_swap_exception_ports(
4812 mach_task_self(), EXC_MASK_BAD_ACCESS,
4813 MACH_PORT_NULL, EXCEPTION_DEFAULT, 0,
4814 old_exception_masks, &old_exception_count,
4815 old_exception_ports, old_exception_behaviors, old_exception_flavors
4816 );
4817}
4818
4819static void
4820restore_mach_bad_access_exc(void)
4821{
4822 for (mach_msg_type_number_t i = 0; i < old_exception_count; i++) {
4823 task_set_exception_ports(
4824 mach_task_self(),
4825 old_exception_masks[i], old_exception_ports[i],
4826 old_exception_behaviors[i], old_exception_flavors[i]
4827 );
4828 }
4829}
4830#endif
4831
4832#if defined(HAVE_PTHREAD_SIGMASK)
4833# define gc_sigmask pthread_sigmask
4834#else
4835# define gc_sigmask sigprocmask
4836#endif
4837
4838static void
4839read_barrier_signal(int sig, siginfo_t *info, void *data)
4840{
4841 // setup SEGV/BUS handlers for errors
4842 struct sigaction prev_sigbus, prev_sigsegv;
4843 sigaction(SIGBUS, &old_sigbus_handler, &prev_sigbus);
4844 sigaction(SIGSEGV, &old_sigsegv_handler, &prev_sigsegv);
4845
4846 // enable SIGBUS/SEGV
4847 sigset_t set, prev_set;
4848 sigemptyset(&set);
4849 sigaddset(&set, SIGBUS);
4850 sigaddset(&set, SIGSEGV);
4851 gc_sigmask(SIG_UNBLOCK, &set, &prev_set);
4852#ifdef HAVE_MACH_TASK_EXCEPTION_PORTS
4853 disable_mach_bad_access_exc();
4854#endif
4855 // run handler
4856 read_barrier_handler((uintptr_t)info->si_addr);
4857
4858 // reset SEGV/BUS handlers
4859#ifdef HAVE_MACH_TASK_EXCEPTION_PORTS
4860 restore_mach_bad_access_exc();
4861#endif
4862 sigaction(SIGBUS, &prev_sigbus, NULL);
4863 sigaction(SIGSEGV, &prev_sigsegv, NULL);
4864 gc_sigmask(SIG_SETMASK, &prev_set, NULL);
4865}
4866
4867static void
4868uninstall_handlers(void)
4869{
4870#ifdef HAVE_MACH_TASK_EXCEPTION_PORTS
4871 restore_mach_bad_access_exc();
4872#endif
4873 sigaction(SIGBUS, &old_sigbus_handler, NULL);
4874 sigaction(SIGSEGV, &old_sigsegv_handler, NULL);
4875}
4876
4877static void
4878install_handlers(void)
4879{
4880 struct sigaction action;
4881 memset(&action, 0, sizeof(struct sigaction));
4882 sigemptyset(&action.sa_mask);
4883 action.sa_sigaction = read_barrier_signal;
4884 action.sa_flags = SA_SIGINFO | SA_ONSTACK;
4885
4886 sigaction(SIGBUS, &action, &old_sigbus_handler);
4887 sigaction(SIGSEGV, &action, &old_sigsegv_handler);
4888#ifdef HAVE_MACH_TASK_EXCEPTION_PORTS
4889 disable_mach_bad_access_exc();
4890#endif
4891}
4892#endif
4893
4894static void
4895gc_compact_finish(rb_objspace_t *objspace)
4896{
4897 for (int i = 0; i < HEAP_COUNT; i++) {
4898 rb_heap_t *heap = &heaps[i];
4899 gc_unprotect_pages(objspace, heap);
4900 }
4901
4902 if (!global_objspace->global_gc.compacting) uninstall_handlers();
4903
4904 if (global_objspace->global_gc.compacting) {
4905 /* In a compacting global GC this updates only this objspace's heap references;
4906 * gc_start_global sets during_reference_updating on every objspace (the
4907 * move-or-mark decision reads it via rb_gc_get_objspace()) and runs the
4908 * non-idempotent VM-global side (gc_update_references_global) once at the end. */
4909 gc_update_references_heap(objspace);
4910 }
4911 else {
4912 gc_update_references(objspace);
4913 }
4914 objspace->profile.compact_count++;
4915
4916 for (int i = 0; i < HEAP_COUNT; i++) {
4917 rb_heap_t *heap = &heaps[i];
4918 heap->compact_cursor = NULL;
4919 heap->free_pages = NULL;
4920 heap->compact_cursor_index = 0;
4921 }
4922
4923 if (gc_prof_enabled(objspace)) {
4924 gc_profile_record *record = gc_prof_record(objspace);
4925 record->moved_objects = objspace->rcompactor.total_moved - record->moved_objects;
4926 }
4927 if (!global_objspace->global_gc.compacting) objspace->flags.during_compacting = FALSE;
4928}
4929
4931 struct heap_page *page;
4932 int final_slots;
4933 int freed_slots;
4934 int empty_slots;
4935 /* Hoisted out of the per-slot pinned-free assert: too expensive for the sweep loop
4936 * as an external call. */
4937 const bool check_pinned_free;
4938 /* This is a parallel local sweep (multi-Ractor, not a global GC), so a non-thread-safe
4939 * T_DATA dfree must be deferred to the global GC or the postponed job rather than run here. */
4940 const bool defer_thread_unsafe_local_sweep;
4941 bool trigger_thread_unsafe_sweep_postponed_job;
4942
4943 struct free_region *free_region;
4944};
4945
4946/* NOTE: We must free the root fiber during postmortem collection, otherwise another Ractor
4947 * can collect the fiber through a major GC while we're still tearing it down. Once fibers are
4948 * THREAD_SAFE_FREE, we no longer need the root fiber condition as it will be guaranteed to be
4949 * collected during this time. */
4950static bool
4951gc_obj_defer_local_free_p(rb_objspace_t *objspace, VALUE obj)
4952{
4953 if (BUILTIN_TYPE(obj) != T_DATA) return false;
4954
4955 const rb_data_type_t *type = RTYPEDDATA_TYPE(obj);
4956 if (!rb_gc_data_type_deferred_free_p(type)) return false;
4957
4958 if (RTYPEDDATA_GET_DATA(obj) == NULL) return false;
4959
4960 if (type->flags & RUBY_TYPED_FREE_IMMEDIATELY) {
4961 if (objspace->flags.during_postmortem) {
4962 if (rb_fiber_current() == obj) {
4963 return false;
4964 }
4965 }
4966 return true;
4967 }
4968 else {
4969 return false;
4970 }
4971}
4972
4973static void gc_tdata_deferred_free_job(void *unused);
4974static void gc_tdata_deferred_free_pjob_ensure(void);
4975static unsigned int gc_during_gc_get(const rb_objspace_t *objspace);
4976static void gc_during_gc_set(rb_objspace_t *objspace, unsigned int v);
4977static void gc_global_snapshot_objspaces(void);
4978
4979static void
4980gc_tdata_deferred_free_pjob_ensure(void)
4981{
4982 if (global_objspace->tdata_deferred_free_pjob == POSTPONED_JOB_HANDLE_INVALID) {
4983 global_objspace->tdata_deferred_free_pjob =
4984 rb_postponed_job_preregister(0, gc_tdata_deferred_free_job, NULL);
4985 if (global_objspace->tdata_deferred_free_pjob == POSTPONED_JOB_HANDLE_INVALID) {
4986 rb_bug("Could not preregister postponed job for deferred T_DATA free");
4987 }
4988 }
4989}
4990
4991/* A terminating Ractor's postmortem collection runs on an EC whose stack is already
4992 * torn down: it never checks interrupts again, so a job triggered there is lost and no
4993 * later sweep can rediscover the entries. Hand those to the main Ractor. */
4994static void
4995gc_tdata_deferred_free_trigger(rb_objspace_t *objspace)
4996{
4997 if (objspace->flags.during_postmortem) {
4998 rb_gc_trigger_postponed_job_on_main(global_objspace->tdata_deferred_free_pjob);
4999 }
5000 else {
5001 rb_postponed_job_trigger(global_objspace->tdata_deferred_free_pjob);
5002 }
5003}
5004
5005static void
5006gc_tdata_unsafe_free_entry(const struct tdata_unsafe_free_entry *entry, bool embed_xfree)
5007{
5008 entry->dfree(entry->data);
5009 if (embed_xfree) {
5010 xfree(entry->data);
5011 }
5012}
5013
5014static void
5015tdata_unsafe_free_chunk_recycle(struct tdata_unsafe_free_chunk *chunk)
5016{
5017 if (global_objspace->tdata_unsafe_free_cache_len >= TDATA_UNSAFE_FREE_CACHE_MAX) {
5018 free(chunk);
5019 return;
5020 }
5021 tdata_unsafe_free_chunk_reset(chunk);
5022 chunk->next = global_objspace->tdata_unsafe_free_cache;
5023 rbimpl_atomic_ptr_store((volatile void **)&global_objspace->tdata_unsafe_free_cache, chunk,
5024 RBIMPL_ATOMIC_RELEASE);
5025 global_objspace->tdata_unsafe_free_cache_len++;
5026}
5027
5028static void
5029gc_tdata_unsafe_drain_chunk(struct tdata_unsafe_free_chunk *chunk)
5030{
5031 for (unsigned int i = 0; i < chunk->count; i++) {
5032 gc_tdata_unsafe_free_entry(&chunk->entries[i],
5033 (chunk->embed_xfree_bits >> i) & 1);
5034 }
5035 tdata_unsafe_free_chunk_recycle(chunk);
5036}
5037
5038/* Run every pending deferred free: the published chunks (which belong to no objspace)
5039 * plus the given objspaces' partial chunks. The caller must have stopped the world --
5040 * VM barrier held, or a single Ractor left in the process -- and must pass every live
5041 * objspace, since the pending count is zeroed here. (Shutdown is the one exception:
5042 * nothing reads the count afterwards.) */
5043static void
5044gc_tdata_unsafe_drain_objspaces(rb_objspace_t **objspaces, size_t n)
5045{
5046 struct tdata_unsafe_free_chunk *chunk =
5047 rbimpl_atomic_ptr_exchange((void **)&global_objspace->tdata_unsafe_free_published, NULL,
5048 RBIMPL_ATOMIC_ACQ_REL);
5049 while (chunk) {
5050 struct tdata_unsafe_free_chunk *next = chunk->next;
5051 gc_tdata_unsafe_drain_chunk(chunk);
5052 chunk = next;
5053 }
5054
5055 for (size_t i = 0; i < n; i++) {
5056 rb_objspace_t *os = objspaces[i];
5057 struct tdata_unsafe_free_chunk *partial = os->tdata_unsafe_free_chunk;
5058 if (partial) {
5059 os->tdata_unsafe_free_chunk = NULL;
5060 gc_tdata_unsafe_drain_chunk(partial);
5061 }
5062 }
5063
5064 rbimpl_atomic_size_exchange(&global_objspace->tdata_deferred_free_count, 0,
5065 RBIMPL_ATOMIC_RELAXED);
5066}
5067
5068/* Stop the world and run the dfree function for all deferred T_DATAs. */
5069static void
5070gc_tdata_unsafe_drain(void)
5071{
5072 unsigned int lev = RB_GC_VM_LOCK();
5073
5074 if (tdata_deferred_free_count_load() == 0) {
5075 RB_GC_VM_UNLOCK(lev);
5076 return;
5077 }
5078
5079 rb_gc_vm_barrier();
5080
5081 gc_global_snapshot_objspaces();
5082
5083 /* Set during_gc=TRUE and init vm_context for the CURRENT objspace only.
5084 * The no-alloc guard checks only the allocating (=current) objspace's during_gc,
5085 * and rb_gc_get_ec() reads only the current objspace's vm_context.ec. */
5086 rb_objspace_t *objspace = rb_gc_get_objspace();
5087 unsigned int saved_during_gc = gc_during_gc_get(objspace);
5088 dont_gc_on();
5089 rb_gc_initialize_vm_context(&objspace->vm_context);
5090 gc_during_gc_set(objspace, TRUE);
5091
5092 gc_tdata_unsafe_drain_objspaces(global_objspace->global_gc.objspaces,
5093 global_objspace->global_gc.n_objspaces);
5094
5095 gc_during_gc_set(objspace, saved_during_gc);
5096 dont_gc_off();
5097
5098 RB_GC_VM_UNLOCK(lev);
5099}
5100
5101static void
5102gc_tdata_deferred_free_job(void *unused)
5103{
5104 (void)unused;
5105
5106 size_t count = tdata_deferred_free_count_load();
5107 if (count == 0) return;
5108 if (count < TDATA_DEFERRED_FREE_THRESHOLD && !rb_gc_single_objspace_p()) return;
5109
5110 gc_tdata_unsafe_drain();
5111}
5112
5113static inline void
5114gc_sweep_register_free_slot(rb_objspace_t *objspace, struct heap_page *page, struct gc_sweep_context *ctx, uintptr_t p, short slot_size)
5115{
5116 rb_asan_unpoison_object(p, false);
5117 ((struct RBasic *)p)->flags = 0;
5118
5119 /* Keep a freed slot from carrying its old shareable and shref bits into the next
5120 * object born there; the actual clear happens per bitmap word at the end of
5121 * gc_sweep_page rather than per slot. */
5122
5123 struct free_region *existing_region = ctx->free_region;
5124 if (existing_region) rb_asan_unpoison_object((VALUE)existing_region, false);
5125
5126 if (RB_LIKELY(existing_region && p == existing_region->end)) {
5127 existing_region->end = p + slot_size;
5128 }
5129 else {
5130 struct free_region *free_region = (struct free_region *)p;
5131 free_region->end = p + slot_size;
5132 free_region->next = existing_region;
5133
5134 ctx->free_region = free_region;
5135 }
5136
5137 if (existing_region) rb_asan_poison_object((VALUE)existing_region);
5138 rb_asan_poison_object(p);
5139}
5140
5141static inline void
5142gc_sweep_plane(rb_objspace_t *objspace, rb_heap_t *heap, uintptr_t p, bits_t bitset, struct gc_sweep_context *ctx)
5143{
5144 struct heap_page *sweep_page = ctx->page;
5145 short slot_size = sweep_page->slot_size;
5146
5147 do {
5148 VALUE vp = (VALUE)p;
5149 GC_ASSERT(vp % sizeof(VALUE) == 0);
5150
5151 rb_asan_unpoison_object(vp, false);
5152 if (bitset & 1) {
5153 switch (BUILTIN_TYPE(vp)) {
5154 case T_MOVED:
5155 if (objspace->flags.during_compacting) {
5156 /* The sweep cursor shouldn't have made it to any
5157 * T_MOVED slots while the compact flag is enabled.
5158 * The sweep cursor and compact cursor move in
5159 * opposite directions, and when they meet references will
5160 * get updated and "during_compacting" should get disabled */
5161 rb_bug("T_MOVED shouldn't be seen until compaction is finished");
5162 }
5163 gc_report(3, objspace, "page_sweep: %s is freed\n", rb_obj_info(vp));
5164 ctx->empty_slots++;
5165 gc_sweep_register_free_slot(objspace, sweep_page, ctx, p, slot_size);
5166 break;
5167 case T_ZOMBIE:
5168 /* already counted */
5169 break;
5170 case T_NONE:
5171 ctx->empty_slots++; /* already freed */
5172 gc_sweep_register_free_slot(objspace, sweep_page, ctx, p, slot_size);
5173 break;
5174
5175 default:
5176#if RGENGC_CHECK_MODE
5177 /* A local GC must never free a pinned slot; a global GC may (its exact
5178 * mark collects dead shareable objects). Reading the bits here is
5179 * CHECK-only and still valid: the bulk clear runs after the free loop. */
5180 if (ctx->check_pinned_free &&
5181 (MARKED_IN_BITMAP(GET_HEAP_SHAREABLE_BITS(vp), vp) ||
5182 MARKED_IN_BITMAP(GET_HEAP_SHREF_BITS(vp), vp))) {
5183 rb_bug("page_sweep: freeing pinned slot %s (shareable=%d shref=%d single_now=%d)",
5184 rb_obj_info(vp),
5185 (int)!!MARKED_IN_BITMAP(GET_HEAP_SHAREABLE_BITS(vp), vp),
5186 (int)!!MARKED_IN_BITMAP(GET_HEAP_SHREF_BITS(vp), vp),
5187 (int)rb_gc_single_objspace_p());
5188 }
5189#endif
5190#if RGENGC_CHECK_MODE
5191 if (!is_full_marking(objspace)) {
5192 if (RVALUE_OLD_P(objspace, vp)) rb_bug("page_sweep: %p - old while minor GC.", (void *)p);
5193 if (RVALUE_REMEMBERED(objspace, vp)) rb_bug("page_sweep: %p - remembered.", (void *)p);
5194 }
5195#endif
5196
5197#if RGENGC_CHECK_MODE
5198#define CHECK(x) if (x(objspace, vp) != FALSE) rb_bug("obj_free: " #x "(%s) != FALSE", rb_obj_info(vp))
5199 CHECK(RVALUE_WB_UNPROTECTED);
5200 CHECK(RVALUE_MARKED);
5201 CHECK(RVALUE_MARKING);
5202 CHECK(RVALUE_UNCOLLECTIBLE);
5203#undef CHECK
5204#endif
5205
5206 if (!rb_gc_obj_needs_cleanup_p(vp)) {
5207 (void)VALGRIND_MAKE_MEM_UNDEFINED((void*)p, slot_size);
5208 gc_sweep_register_free_slot(objspace, sweep_page, ctx, p, slot_size);
5209 gc_report(3, objspace, "page_sweep: %s (fast path) is freed\n", rb_obj_info(vp));
5210 ctx->freed_slots++;
5211 }
5212 else {
5213 gc_report(2, objspace, "page_sweep: free %p\n", (void *)p);
5214
5215 if (RB_UNLIKELY(ctx->defer_thread_unsafe_local_sweep && gc_obj_defer_local_free_p(objspace, vp))) {
5216 /* Defer the dfree instead of running it here: it needs the world
5217 * stopped, which a parallel local sweep cannot give it. The slot is reusable
5218 * right away unless we had to create a zombie. */
5219 if (gc_defer_thread_unsafe_free(objspace, vp,
5220 &ctx->trigger_thread_unsafe_sweep_postponed_job)) {
5221 (void)VALGRIND_MAKE_MEM_UNDEFINED((void*)p, slot_size);
5222 gc_sweep_register_free_slot(objspace, sweep_page, ctx, p, slot_size);
5223 ctx->freed_slots++;
5224 }
5225 else {
5226 ctx->final_slots++;
5227 }
5228 break;
5229 }
5230 rb_gc_obj_free_vm_weak_references(vp);
5231 if (gc_obj_free(objspace, vp)) {
5232 (void)VALGRIND_MAKE_MEM_UNDEFINED((void*)p, slot_size);
5233 gc_sweep_register_free_slot(objspace, sweep_page, ctx, p, slot_size);
5234 gc_report(3, objspace, "page_sweep: %s is freed\n", rb_obj_info(vp));
5235 ctx->freed_slots++;
5236 }
5237 else {
5238 ctx->final_slots++;
5239 }
5240 }
5241 break;
5242 }
5243 }
5244 p += slot_size;
5245 bitset >>= 1;
5246 } while (bitset);
5247}
5248
5249static inline void
5250gc_sweep_page(rb_objspace_t *objspace, rb_heap_t *heap, struct gc_sweep_context *ctx)
5251{
5252 struct heap_page *sweep_page = ctx->page;
5253 GC_ASSERT(sweep_page->heap == heap);
5254
5255 uintptr_t p;
5256 bits_t *bits, bitset;
5257
5258 gc_report(2, objspace, "page_sweep: start.\n");
5259
5260#if RGENGC_CHECK_MODE
5261 if (!objspace->flags.immediate_sweep) {
5262 GC_ASSERT(sweep_page->flags.before_sweep == TRUE);
5263 }
5264#endif
5265 sweep_page->flags.before_sweep = FALSE;
5266 sweep_page->free_slots = 0;
5267
5268 asan_unlock_freelist(sweep_page);
5269 sweep_page->free_region = NULL;
5270 asan_lock_freelist(sweep_page);
5271 ctx->free_region = NULL;
5272
5273 p = (uintptr_t)sweep_page->start;
5274 bits = sweep_page->mark_bits;
5275 short slot_size = sweep_page->slot_size;
5276 int total_slots = sweep_page->total_slots;
5277 int bitmap_plane_count = CEILDIV(total_slots, BITS_BITLENGTH);
5278
5279 int out_of_range_bits = total_slots % BITS_BITLENGTH;
5280 if (out_of_range_bits != 0) {
5281 bits[bitmap_plane_count - 1] |= ~(((bits_t)1 << out_of_range_bits) - 1);
5282 }
5283
5284 // Clear wb_unprotected and age bits for all unmarked slots
5285 {
5286 bits_t *wb_unprotected_bits = sweep_page->wb_unprotected_bits;
5287 bits_t *age_bits = sweep_page->age_bits;
5288 for (int i = 0; i < bitmap_plane_count; i++) {
5289 bits_t unmarked = ~bits[i];
5290 wb_unprotected_bits[i] &= ~unmarked;
5291 age_bits[i * 2] &= ~unmarked;
5292 age_bits[i * 2 + 1] &= ~unmarked;
5293 }
5294 }
5295
5296 for (int i = 0; i < bitmap_plane_count; i++) {
5297 bitset = ~bits[i];
5298 if (bitset) {
5299 gc_sweep_plane(objspace, heap, p, bitset, ctx);
5300 }
5301 p += BITS_BITLENGTH * slot_size;
5302 }
5303
5304 /* Bulk-clear the freed slots' shareable and shref bits before the freelist is
5305 * published, so a reused slot is clean. Freed slots are exactly the unmarked ones,
5306 * so `bits &= mark_bits` keeps live shareable objects (which must stay pinned) and
5307 * drops the rest. Pages with neither bit are skipped. */
5308 if (sweep_page->flags.has_shareable_objects || sweep_page->flags.has_shref_objects) {
5309 bits_t *shareable_bits = sweep_page->shareable_bits;
5310 bits_t *shref_bits = sweep_page->shref_bits;
5311 bits_t sh = 0, sr = 0;
5312 for (int i = 0; i < bitmap_plane_count; i++) {
5313 shareable_bits[i] &= bits[i];
5314 shref_bits[i] &= bits[i];
5315 sh |= shareable_bits[i];
5316 sr |= shref_bits[i];
5317 }
5318 if (!sh) sweep_page->flags.has_shareable_objects = FALSE;
5319 if (!sr) sweep_page->flags.has_shref_objects = FALSE;
5320 }
5321
5322 asan_unlock_freelist(sweep_page);
5323 sweep_page->free_region = ctx->free_region;
5324 asan_lock_freelist(sweep_page);
5325
5326 if (!heap->compact_cursor) {
5327 gc_setup_mark_bits(sweep_page);
5328 }
5329
5330#if GC_PROFILE_MORE_DETAIL
5331 if (gc_prof_enabled(objspace)) {
5332 gc_profile_record *record = gc_prof_record(objspace);
5333 record->removing_objects += ctx->final_slots + ctx->freed_slots;
5334 record->empty_objects += ctx->empty_slots;
5335 }
5336#endif
5337 if (0) fprintf(stderr, "gc_sweep_page(%"PRIdSIZE"): total_slots: %d, freed_slots: %d, empty_slots: %d, final_slots: %d\n",
5338 rb_gc_count(),
5339 sweep_page->total_slots,
5340 ctx->freed_slots, ctx->empty_slots, ctx->final_slots);
5341
5342 sweep_page->free_slots += ctx->freed_slots + ctx->empty_slots;
5343 sweep_page->heap->total_freed_objects += ctx->freed_slots;
5344
5345 if (heap_pages_deferred_final && !finalizing) {
5346 gc_finalize_deferred_register(objspace);
5347 }
5348
5349#if RGENGC_CHECK_MODE
5350 int region_slots = 0;
5351 asan_unlock_freelist(sweep_page);
5352 struct free_region *region = sweep_page->free_region;
5353 while (region) {
5354 rb_asan_unpoison_object((VALUE)region, false);
5355 GC_ASSERT(RB_TYPE_P((VALUE)region, T_NONE));
5356 uintptr_t region_start = (uintptr_t)region;
5357 uintptr_t region_end = region->end;
5358 struct free_region *next = region->next;
5359 rb_asan_poison_object((VALUE)region);
5360
5361 GC_ASSERT(region_end > region_start);
5362 GC_ASSERT((region_end - region_start) % slot_size == 0);
5363 region_slots += (int)((region_end - region_start) / slot_size);
5364
5365 region = next;
5366 }
5367 asan_lock_freelist(sweep_page);
5368 if (region_slots != sweep_page->free_slots) {
5369 rb_bug("inconsistent free region slots: expected %d but was %d", sweep_page->free_slots, region_slots);
5370 }
5371#endif
5372
5373 gc_report(2, objspace, "page_sweep: end.\n");
5374}
5375
5376static const char *
5377gc_mode_name(enum gc_mode mode)
5378{
5379 switch (mode) {
5380 case gc_mode_none: return "none";
5381 case gc_mode_marking: return "marking";
5382 case gc_mode_sweeping: return "sweeping";
5383 case gc_mode_compacting: return "compacting";
5384 default: rb_bug("gc_mode_name: unknown mode: %d", (int)mode);
5385 }
5386}
5387
5388static void
5389gc_mode_transition(rb_objspace_t *objspace, enum gc_mode mode)
5390{
5391#if RGENGC_CHECK_MODE
5392 enum gc_mode prev_mode = gc_mode(objspace);
5393 switch (prev_mode) {
5394 case gc_mode_none:
5395 /* A global GC marks every objspace as one heap (mark_roots on the driver), so an
5396 * individual objspace's mode stays `none` during that mark; the sweep inside the
5397 * barrier then makes the legitimate none -> sweeping transition. */
5398 GC_ASSERT(mode == gc_mode_marking ||
5399 (objspace->flags.during_global_gc && mode == gc_mode_sweeping));
5400 break;
5401 case gc_mode_marking: GC_ASSERT(mode == gc_mode_sweeping); break;
5402 case gc_mode_sweeping: GC_ASSERT(mode == gc_mode_none || mode == gc_mode_compacting); break;
5403 case gc_mode_compacting: GC_ASSERT(mode == gc_mode_none); break;
5404 }
5405#endif
5406 if (0) fprintf(stderr, "gc_mode_transition: %s->%s\n", gc_mode_name(gc_mode(objspace)), gc_mode_name(mode));
5407 gc_mode_set(objspace, mode);
5408}
5409
5410static void
5411heap_page_flush_alloc_regions(struct heap_page *page, rb_heap_t *heap)
5412{
5413 struct free_region *chain = heap->newobj.alloc_next_region;
5414
5415 if (heap->newobj.alloc_cursor < heap->newobj.alloc_cursor_end) {
5416 VALUE start = (VALUE)heap->newobj.alloc_cursor;
5417 rb_asan_unpoison_object(start, false);
5418 struct free_region *remnant = (struct free_region *)start;
5419 remnant->flags = 0;
5420 remnant->end = heap->newobj.alloc_cursor_end;
5421 remnant->next = chain;
5422 rb_asan_poison_object(start);
5423 chain = remnant;
5424 }
5425
5426 if (chain) {
5427 asan_unlock_freelist(page);
5428 if (page->free_region) {
5429 struct free_region *p = page->free_region;
5430 rb_asan_unpoison_object((VALUE)p, false);
5431 while (p->next) {
5432 struct free_region *prev = p;
5433 p = p->next;
5434 rb_asan_poison_object((VALUE)prev);
5435 rb_asan_unpoison_object((VALUE)p, false);
5436 }
5437 p->next = chain;
5438 rb_asan_poison_object((VALUE)p);
5439 }
5440 else {
5441 page->free_region = chain;
5442 }
5443 asan_lock_freelist(page);
5444 }
5445}
5446
5447static void
5448gc_sweep_start_heap(rb_objspace_t *objspace, rb_heap_t *heap)
5449{
5450 heap->sweeping_page = ccan_list_top(&heap->pages, struct heap_page, page_node);
5451 if (heap->sweeping_page) {
5452 objspace->sweeping_heap_count++;
5453 }
5454 heap->free_pages = NULL;
5455 heap->pooled_pages = NULL;
5456 if (!objspace->flags.immediate_sweep) {
5457 struct heap_page *page = NULL;
5458
5459 ccan_list_for_each(&heap->pages, page, page_node) {
5460 page->flags.before_sweep = TRUE;
5461 }
5462 }
5463}
5464
5465#if GC_CAN_COMPILE_COMPACTION
5466static void gc_sort_heap_by_compare_func(rb_objspace_t *objspace, gc_compact_compare_func compare_func);
5467static int compare_pinned_slots(const void *left, const void *right, void *d);
5468#endif
5469
5470/* Return the current allocation page and freelist to their pages, so the sweeper sees a
5471 * consistent heap. */
5472static void
5473heap_alloc_state_clear(rb_objspace_t *objspace)
5474{
5475 objspace->incremental_mark_step_allocated_slots = 0;
5476
5477 for (size_t heap_idx = 0; heap_idx < HEAP_COUNT; heap_idx++) {
5478 rb_heap_t *heap = &heaps[heap_idx];
5479
5480 struct heap_page *page = heap->newobj.alloc_using_page;
5481 RUBY_DEBUG_LOG("heap alloc_using_page:%p cursor:%p", (void *)page, (void *)heap->newobj.alloc_cursor);
5482
5483 if (page) {
5484 heap_page_flush_alloc_regions(page, heap);
5485 }
5486
5487 heap->newobj.alloc_using_page = NULL;
5488 heap->newobj.alloc_cursor = 0;
5489 heap->newobj.alloc_cursor_end = 0;
5490 heap->newobj.alloc_next_region = NULL;
5491 }
5492}
5493
5494static void
5495gc_sweep_freeobj_hooks_page(rb_objspace_t *objspace, struct heap_page *page)
5496{
5497 bits_t *bits = page->mark_bits;
5498 uintptr_t p = (uintptr_t)page->start;
5499 short slot_size = page->slot_size;
5500 int total_slots = page->total_slots;
5501 int bitmap_plane_count = CEILDIV(total_slots, BITS_BITLENGTH);
5502
5503 int out_of_range_bits = total_slots % BITS_BITLENGTH;
5504 bits_t last_plane_mask = (out_of_range_bits != 0)
5505 ? ~(((bits_t)1 << out_of_range_bits) - 1)
5506 : 0;
5507
5508 for (int j = 0; j < bitmap_plane_count; j++) {
5509 bits_t bitset = ~bits[j];
5510 if (j == bitmap_plane_count - 1) {
5511 bitset &= ~last_plane_mask;
5512 }
5513
5514 uintptr_t pp = p;
5515 while (bitset) {
5516 if (bitset & 1) {
5517 VALUE vp = (VALUE)pp;
5518 asan_unpoisoning_object(vp) {
5519 switch (BUILTIN_TYPE(vp)) {
5520 case T_NONE:
5521 case T_ZOMBIE:
5522 case T_MOVED:
5523 break;
5524 default:
5525 rb_gc_event_hook(vp, RUBY_INTERNAL_EVENT_FREEOBJ);
5526 break;
5527 }
5528 }
5529 }
5530 pp += slot_size;
5531 bitset >>= 1;
5532 }
5533 p += BITS_BITLENGTH * slot_size;
5534 }
5535}
5536
5537static void
5538gc_sweep_freeobj_hooks(rb_objspace_t *objspace)
5539{
5540 for (int i = 0; i < HEAP_COUNT; i++) {
5541 rb_heap_t *heap = &heaps[i];
5542 struct heap_page *page = NULL;
5543
5544 ccan_list_for_each(&heap->pages, page, page_node) {
5545 gc_sweep_freeobj_hooks_page(objspace, page);
5546 }
5547 }
5548}
5549
5550static void
5551gc_sweep_start(rb_objspace_t *objspace)
5552{
5553 gc_mode_transition(objspace, gc_mode_sweeping);
5554 objspace->rincgc.pooled_slots = 0;
5555
5556 if (RB_UNLIKELY(objspace->hook_events & RUBY_INTERNAL_EVENT_FREEOBJ)) {
5557 /* FREEOBJ is never enabled outside the main objspace
5558 * (rb_objspace_set_event_hook), so this hook, which runs user callbacks,
5559 * cannot fire during a non-main Ractor's lock-free local sweep. */
5560 GC_ASSERT(objspace == global_objspace->main_objspace);
5561 gc_sweep_freeobj_hooks(objspace);
5562 }
5563
5564#if GC_CAN_COMPILE_COMPACTION
5565 if (objspace->flags.during_compacting) {
5566 gc_sort_heap_by_compare_func(
5567 objspace,
5568 objspace->rcompactor.compare_func ? objspace->rcompactor.compare_func : compare_pinned_slots
5569 );
5570 }
5571#endif
5572
5573 for (int i = 0; i < HEAP_COUNT; i++) {
5574 rb_heap_t *heap = &heaps[i];
5575 gc_sweep_start_heap(objspace, heap);
5576
5577 /* We should call gc_sweep_finish_heap for size pools with no pages. */
5578 if (heap->sweeping_page == NULL) {
5579 GC_ASSERT(heap->total_pages == 0);
5580 GC_ASSERT(heap->total_slots == 0);
5581 gc_sweep_finish_heap(objspace, heap);
5582 }
5583 }
5584
5585 heap_alloc_state_clear(objspace);
5586}
5587
5588static void
5589gc_sweep_finish_heap(rb_objspace_t *objspace, rb_heap_t *heap)
5590{
5591 size_t total_slots = heap->total_slots;
5592 size_t swept_slots = heap->freed_slots + heap->empty_slots;
5593
5594 size_t init_slots = objspace_heap_init_bytes(objspace) / heap->slot_size;
5595 size_t min_free_slots = (size_t)(MAX(total_slots, init_slots) * gc_params.heap_free_slots_min_ratio);
5596
5597 if (swept_slots < min_free_slots &&
5598 /* The heap is a growth heap if it freed more slots than had empty slots. */
5599 ((heap->empty_slots == 0 && total_slots > 0) || heap->freed_slots > heap->empty_slots)) {
5600 /* If we don't have enough slots and we have pages on the tomb heap, move
5601 * pages from the tomb heap to the eden heap. This may prevent page
5602 * creation thrashing (frequently allocating and deallocting pages) and
5603 * GC thrashing (running GC more frequently than required). */
5604 struct heap_page *resurrected_page;
5605 while (swept_slots < min_free_slots &&
5606 (resurrected_page = heap_page_resurrect(objspace))) {
5607 heap_add_page(objspace, heap, resurrected_page);
5608 heap_add_freepage(heap, resurrected_page);
5609
5610 swept_slots += resurrected_page->free_slots;
5611 }
5612
5613 if (swept_slots < min_free_slots) {
5614 /* Grow this heap if we are in a major GC or if we haven't run at least
5615 * RVALUE_OLD_AGE minor GC since the last major GC. */
5616 if (is_full_marking(objspace) ||
5617 objspace->profile.count - objspace->rgengc.last_major_gc < RVALUE_OLD_AGE) {
5618 if (objspace->heap_pages.allocatable_bytes < min_free_slots * heap->slot_size) {
5619 heap_allocatable_bytes_expand(objspace, heap, swept_slots, heap->total_slots, heap->slot_size);
5620 }
5621 }
5622 else if (swept_slots < min_free_slots * 7 / 8 &&
5623 objspace->heap_pages.allocatable_bytes < (min_free_slots * 7 / 8 - swept_slots) * heap->slot_size) {
5624 gc_needs_major_flags |= GPR_FLAG_MAJOR_BY_NOFREE;
5625 heap->force_major_gc_count++;
5626 }
5627 }
5628 }
5629}
5630
5631static void
5632gc_sweep_finish(rb_objspace_t *objspace)
5633{
5634 gc_report(1, objspace, "gc_sweep_finish\n");
5635
5636 gc_prof_set_heap_info(objspace);
5637 heap_pages_free_unused_pages(objspace);
5638 if (rb_gc_single_objspace_p() && is_full_marking(objspace)) {
5639 /* gc_marks_finish retains ~2/3 of empty pages in objspace->empty_pages for reuse,
5640 * only the excess reaches the pool. */
5641 page_pool_reclaim(global_objspace);
5642 }
5643
5644 for (int i = 0; i < HEAP_COUNT; i++) {
5645 rb_heap_t *heap = &heaps[i];
5646
5647 heap->freed_slots = 0;
5648 heap->empty_slots = 0;
5649
5650 if (!will_be_incremental_marking(objspace)) {
5651 struct heap_page *end_page = heap->free_pages;
5652 if (end_page) {
5653 while (end_page->free_next) end_page = end_page->free_next;
5654 end_page->free_next = heap->pooled_pages;
5655 }
5656 else {
5657 heap->free_pages = heap->pooled_pages;
5658 }
5659 heap->pooled_pages = NULL;
5660 objspace->rincgc.pooled_slots = 0;
5661 }
5662 }
5663
5664 /* Not before: while sweeping is in progress its frees must keep reducing
5665 * malloc_increase (objspace_malloc_increase_body sweeps and retries on it). */
5666 gc_malloc_counters_snapshot_free_at_last_gc(objspace, &objspace->malloc_counters.counters);
5667#if RGENGC_ESTIMATE_OLDMALLOC
5668 gc_malloc_counters_snapshot_free_at_last_gc(objspace, &objspace->malloc_counters.oldcounters);
5669#endif
5670
5671 /* Leftovers from an earlier multi-Ractor phase: no later sweep can rediscover them
5672 * (their slots are gone), and with one Ractor left the drain's barrier has nothing
5673 * to wait for. */
5674 if (tdata_deferred_free_count_load() > 0 && rb_gc_single_objspace_p()) {
5675 gc_tdata_deferred_free_trigger(objspace);
5676 }
5677
5679 gc_mode_transition(objspace, gc_mode_none);
5680}
5681
5682static int
5683gc_sweep_step(rb_objspace_t *objspace, rb_heap_t *heap)
5684{
5685 struct heap_page *sweep_page = heap->sweeping_page;
5686 int swept_slots = 0;
5687 int pooled_slots = 0;
5688 int sweep_budget = GC_INCREMENTAL_SWEEP_BYTES / heap->slot_size;
5689 int pool_budget = GC_INCREMENTAL_SWEEP_POOL_BYTES / heap->slot_size;
5690
5691 if (sweep_page == NULL) return FALSE;
5692
5693#if GC_ENABLE_LAZY_SWEEP
5694 gc_prof_sweep_timer_start(objspace);
5695#endif
5696
5697 /* Per-slot pinned-free assert (gc_sweep_context): check only when this cycle's mark
5698 * ran the pinned walk. The current world state would misfire: a single-world
5699 * cycle leaves dead shareable objects unmarked and its sweep can straddle the switch
5700 * to multi-objspace. A global GC's exact mark does not pin, so it is excluded. */
5701 const bool check_pinned_free = objspace->last_cycle_pinned;
5702
5703 const bool defer_thread_unsafe_local_sweep =
5704 !rb_gc_single_objspace_p() && !objspace->flags.during_global_gc;
5705 bool trigger_thread_unsafe_sweep_postponed_job = false;
5706
5707 do {
5708 RUBY_DEBUG_LOG("sweep_page:%p", (void *)sweep_page);
5709
5710 struct gc_sweep_context ctx = {
5711 .page = sweep_page,
5712 .final_slots = 0,
5713 .freed_slots = 0,
5714 .empty_slots = 0,
5715 .check_pinned_free = check_pinned_free,
5716 .defer_thread_unsafe_local_sweep = defer_thread_unsafe_local_sweep,
5717 .trigger_thread_unsafe_sweep_postponed_job = trigger_thread_unsafe_sweep_postponed_job,
5718 };
5719 gc_sweep_page(objspace, heap, &ctx);
5720 int free_slots = ctx.freed_slots + ctx.empty_slots;
5721 trigger_thread_unsafe_sweep_postponed_job = ctx.trigger_thread_unsafe_sweep_postponed_job;
5722
5723 RUBY_DTRACE_GC_HOOK(SWEEP_PAGE, ctx.page->slot_size, ctx.final_slots, ctx.freed_slots, ctx.empty_slots);
5724
5725 heap->sweeping_page = ccan_list_next(&heap->pages, sweep_page, page_node);
5726
5727 if (free_slots == sweep_page->total_slots && heap->total_pages > 1) {
5728 /* There are no living objects, so move this page to the global empty pages.
5729 * The last one stays: nothing grows a heap that has no pages at all. */
5730 heap_unlink_page(objspace, heap, sweep_page);
5731
5732 sweep_page->start = 0;
5733 sweep_page->total_slots = 0;
5734 sweep_page->slot_size = 0;
5735 sweep_page->heap = NULL;
5736 sweep_page->free_slots = 0;
5737
5738 asan_unlock_freelist(sweep_page);
5739 sweep_page->free_region = NULL;
5740 asan_lock_freelist(sweep_page);
5741
5742 asan_poison_memory_region(sweep_page->body, HEAP_PAGE_SIZE);
5743
5744 objspace->empty_pages_count++;
5745 sweep_page->free_next = objspace->empty_pages;
5746 objspace->empty_pages = sweep_page;
5747 }
5748 else if (free_slots > 0) {
5749 heap->freed_slots += ctx.freed_slots;
5750 heap->empty_slots += ctx.empty_slots;
5751
5752 if (pooled_slots < pool_budget) {
5753 heap_add_poolpage(objspace, heap, sweep_page);
5754 pooled_slots += free_slots;
5755 }
5756 else {
5757 heap_add_freepage(heap, sweep_page);
5758 swept_slots += free_slots;
5759 if (swept_slots > sweep_budget) {
5760 break;
5761 }
5762 }
5763 }
5764 else {
5765 sweep_page->free_next = NULL;
5766 }
5767 } while ((sweep_page = heap->sweeping_page));
5768
5769 if (trigger_thread_unsafe_sweep_postponed_job) {
5770 gc_report(2, objspace, "thread-unsafe sweep postponed job triggered\n");
5771 gc_tdata_deferred_free_trigger(objspace);
5772 }
5773
5774 if (!heap->sweeping_page) {
5775 objspace->sweeping_heap_count--;
5776 GC_ASSERT(objspace->sweeping_heap_count >= 0);
5777 gc_sweep_finish_heap(objspace, heap);
5778
5779 if (!has_sweeping_pages(objspace)) {
5780 gc_sweep_finish(objspace);
5781 }
5782 }
5783
5784#if GC_ENABLE_LAZY_SWEEP
5785 gc_prof_sweep_timer_stop(objspace);
5786#endif
5787
5788 return heap->free_pages != NULL;
5789}
5790
5791static void
5792gc_sweep_rest(rb_objspace_t *objspace)
5793{
5794 for (int i = 0; i < HEAP_COUNT; i++) {
5795 rb_heap_t *heap = &heaps[i];
5796
5797 while (heap->sweeping_page) {
5798 gc_sweep_step(objspace, heap);
5799 }
5800 }
5801
5802 /* An objspace with no live pages never runs gc_sweep_step and so never reaches
5803 * gc_sweep_finish, leaving mode at sweeping or compacting until the next cycle's
5804 * gc_sweep_start asserts. If every heap is swept out, settle it to none here. */
5805 if (gc_mode(objspace) != gc_mode_none && !has_sweeping_pages(objspace)) {
5806 gc_sweep_finish(objspace);
5807 }
5808}
5809
5810static void
5811gc_sweep_continue(rb_objspace_t *objspace, rb_heap_t *sweep_heap)
5812{
5813 GC_ASSERT(dont_gc_val() == FALSE || objspace->profile.latest_gc_info & GPR_FLAG_METHOD);
5814 if (!GC_ENABLE_LAZY_SWEEP) return;
5815
5816 gc_sweeping_enter(objspace);
5817
5818 for (int i = 0; i < HEAP_COUNT; i++) {
5819 rb_heap_t *heap = &heaps[i];
5820 if (gc_sweep_step(objspace, heap)) {
5821 GC_ASSERT(heap->free_pages != NULL);
5822 }
5823 else if (heap == sweep_heap) {
5824 if (objspace->empty_pages_count > 0 || objspace->heap_pages.allocatable_bytes > 0) {
5825 /* [Bug #21548]
5826 *
5827 * If this heap is the heap we want to sweep, but we weren't able
5828 * to free any slots, but we also either have empty pages or could
5829 * allocate new pages, then we want to preemptively claim a page
5830 * because it's possible that sweeping another heap will call
5831 * gc_sweep_finish_heap, which may use up all of the
5832 * empty/allocatable pages. If other heaps are not finished sweeping
5833 * then we do not finish this GC and we will end up triggering a new
5834 * GC cycle during this GC phase. */
5835 heap_page_allocate_and_initialize(objspace, heap);
5836
5837 GC_ASSERT(heap->free_pages != NULL);
5838 }
5839 else {
5840 /* Not allowed to create a new page so finish sweeping. */
5841 gc_sweep_rest(objspace);
5842 GC_ASSERT(gc_mode(objspace) == gc_mode_none);
5843 break;
5844 }
5845 }
5846 }
5847
5848 gc_sweeping_exit(objspace);
5849}
5850
5851static void
5852gc_sweep_step_for_malloc(rb_objspace_t *objspace)
5853{
5854 GC_ASSERT(is_lazy_sweeping(objspace));
5855
5856 unsigned int lock_lev;
5857 gc_enter(objspace, gc_enter_event_continue, &lock_lev);
5858
5859 gc_sweeping_enter(objspace);
5860
5861 for (int i = 0; i < HEAP_COUNT; i++) {
5862 rb_heap_t *heap = &heaps[i];
5863 gc_sweep_step(objspace, heap);
5864 }
5865
5866 gc_sweeping_exit(objspace);
5867
5868 gc_exit(objspace, gc_enter_event_continue, &lock_lev);
5869}
5870
5871static bool gc_global_pointer_to_heap_p(const void *ptr);
5872
5873VALUE
5874rb_gc_impl_location(void *objspace_ptr, VALUE value)
5875{
5876 rb_objspace_t *objspace = objspace_ptr;
5877 VALUE destination;
5878
5879 /* A local (single-objspace) compaction never moves another objspace's objects, so
5880 * leave foreign references alone. A compacting global GC moves objects everywhere
5881 * under the barrier, so there every objspace's heap is searched for forwarding. */
5882 if (RB_UNLIKELY(objspace->flags.during_global_gc)
5883 ? !gc_global_pointer_to_heap_p((void *)value)
5884 : !is_pointer_to_heap(objspace_ptr, (void *)value)) {
5885 return value;
5886 }
5887
5888 asan_unpoisoning_object(value) {
5889 if (BUILTIN_TYPE(value) == T_MOVED) {
5890 destination = (VALUE)RMOVED(value)->destination;
5891 GC_ASSERT(BUILTIN_TYPE(destination) != T_NONE);
5892 }
5893 else {
5894 destination = value;
5895 }
5896 }
5897
5898 return destination;
5899}
5900
5901#if GC_CAN_COMPILE_COMPACTION
5902static void
5903invalidate_moved_plane(rb_objspace_t *objspace, struct heap_page *page, uintptr_t p, bits_t bitset)
5904{
5905 if (bitset) {
5906 do {
5907 if (bitset & 1) {
5908 VALUE forwarding_object = (VALUE)p;
5909 VALUE object;
5910
5911 if (BUILTIN_TYPE(forwarding_object) == T_MOVED) {
5912 GC_ASSERT(RVALUE_PINNED(objspace, forwarding_object));
5913 GC_ASSERT(!RVALUE_MARKED(objspace, forwarding_object));
5914
5915 CLEAR_IN_BITMAP(GET_HEAP_PINNED_BITS(forwarding_object), forwarding_object);
5916
5917 object = rb_gc_impl_location(objspace, forwarding_object);
5918 gc_move(objspace, object, forwarding_object, GET_HEAP_PAGE(object), page);
5919 /* forwarding_object is now our actual object, and "object"
5920 * is the free slot for the original page */
5921
5922 struct heap_page *orig_page = GET_HEAP_PAGE(object);
5923 orig_page->free_slots++;
5924 RVALUE_AGE_SET_BITMAP(object, 0);
5925 heap_page_add_free_region(objspace, orig_page, object);
5926
5927 GC_ASSERT(RVALUE_MARKED(objspace, forwarding_object));
5928 GC_ASSERT(BUILTIN_TYPE(forwarding_object) != T_MOVED);
5929 GC_ASSERT(BUILTIN_TYPE(forwarding_object) != T_NONE);
5930 }
5931 }
5932 p += page->slot_size;
5933 bitset >>= 1;
5934 } while (bitset);
5935 }
5936}
5937
5938static void
5939invalidate_moved_page(rb_objspace_t *objspace, struct heap_page *page)
5940{
5941 int i;
5942 bits_t *mark_bits, *pin_bits;
5943 bits_t bitset;
5944 short slot_size = page->slot_size;
5945 int total_slots = page->total_slots;
5946 int bitmap_plane_count = CEILDIV(total_slots, BITS_BITLENGTH);
5947
5948 mark_bits = page->mark_bits;
5949 pin_bits = page->pinned_bits;
5950
5951 uintptr_t p = page->start;
5952
5953 for (i=0; i < bitmap_plane_count; i++) {
5954 /* Moved objects are pinned but never marked. We reuse the pin bits
5955 * to indicate there is a moved object in this slot. */
5956 bitset = pin_bits[i] & ~mark_bits[i];
5957 invalidate_moved_plane(objspace, page, p, bitset);
5958 p += BITS_BITLENGTH * slot_size;
5959 }
5960}
5961#endif
5962
5963static void
5964gc_compact_start(rb_objspace_t *objspace)
5965{
5966 struct heap_page *page = NULL;
5967 gc_mode_transition(objspace, gc_mode_compacting);
5968
5969 for (int i = 0; i < HEAP_COUNT; i++) {
5970 rb_heap_t *heap = &heaps[i];
5971 ccan_list_for_each(&heap->pages, page, page_node) {
5972 page->flags.before_sweep = TRUE;
5973 }
5974
5975 heap->compact_cursor = ccan_list_tail(&heap->pages, struct heap_page, page_node);
5976 heap->compact_cursor_index = 0;
5977 }
5978
5979 if (gc_prof_enabled(objspace)) {
5980 gc_profile_record *record = gc_prof_record(objspace);
5981 record->moved_objects = objspace->rcompactor.total_moved;
5982 }
5983
5984 memset(objspace->rcompactor.considered_count_table, 0, T_MASK * sizeof(size_t));
5985 memset(objspace->rcompactor.moved_count_table, 0, T_MASK * sizeof(size_t));
5986 memset(objspace->rcompactor.moved_up_count_table, 0, T_MASK * sizeof(size_t));
5987 memset(objspace->rcompactor.moved_down_count_table, 0, T_MASK * sizeof(size_t));
5988
5989 /* Set up read barrier for pages containing MOVED objects */
5990 /* A compacting global GC installs the read barrier once for every objspace. */
5991 if (!global_objspace->global_gc.compacting) install_handlers();
5992}
5993
5994static void gc_sweep_compact(rb_objspace_t *objspace);
5995
5996static void
5997gc_sweep(rb_objspace_t *objspace)
5998{
5999 gc_sweeping_enter(objspace);
6000
6001 const unsigned int immediate_sweep = objspace->flags.immediate_sweep;
6002
6003 gc_report(1, objspace, "gc_sweep: immediate: %d\n", immediate_sweep);
6004
6005 gc_sweep_start(objspace);
6006 if (objspace->flags.during_compacting) {
6007 rb_hrtime_t compact_start_time = gc_prof_enabled(objspace) ? rb_hrtime_now() : 0;
6008 gc_sweep_compact(objspace);
6009 if (gc_prof_enabled(objspace)) {
6010 rb_hrtime_t compact_wall_time = elapsed_hrtime_from(compact_start_time);
6011 gc_profile_record *record = gc_prof_record(objspace);
6012 record->gc_compact_wall_time = rb_hrtime_add(record->gc_compact_wall_time,
6013 compact_wall_time);
6014 objspace->profile.gc_sweep_excluded_wall_time = rb_hrtime_add(
6015 objspace->profile.gc_sweep_excluded_wall_time,
6016 compact_wall_time);
6017 }
6018 }
6019
6020 if (immediate_sweep) {
6021#if !GC_ENABLE_LAZY_SWEEP
6022 gc_prof_sweep_timer_start(objspace);
6023#endif
6024 gc_sweep_rest(objspace);
6025#if !GC_ENABLE_LAZY_SWEEP
6026 gc_prof_sweep_timer_stop(objspace);
6027#endif
6028 }
6029 else {
6030
6031 /* Sweep every size pool. */
6032 for (int i = 0; i < HEAP_COUNT; i++) {
6033 rb_heap_t *heap = &heaps[i];
6034 gc_sweep_step(objspace, heap);
6035 }
6036 }
6037
6038 gc_sweeping_exit(objspace);
6039}
6040
6041/* Marking - Marking stack */
6042
6043static stack_chunk_t *
6044stack_chunk_alloc(void)
6045{
6046 stack_chunk_t *res;
6047
6048 res = malloc(sizeof(stack_chunk_t));
6049 if (!res)
6050 rb_memerror();
6051
6052 return res;
6053}
6054
6055static inline int
6056is_mark_stack_empty(mark_stack_t *stack)
6057{
6058 return stack->chunk == NULL;
6059}
6060
6061static size_t
6062mark_stack_size(mark_stack_t *stack)
6063{
6064 size_t size = stack->index;
6065 stack_chunk_t *chunk = stack->chunk ? stack->chunk->next : NULL;
6066
6067 while (chunk) {
6068 size += stack->limit;
6069 chunk = chunk->next;
6070 }
6071 return size;
6072}
6073
6074static void
6075add_stack_chunk_cache(mark_stack_t *stack, stack_chunk_t *chunk)
6076{
6077 chunk->next = stack->cache;
6078 stack->cache = chunk;
6079 stack->cache_size++;
6080}
6081
6082static void
6083shrink_stack_chunk_cache(mark_stack_t *stack)
6084{
6085 stack_chunk_t *chunk;
6086
6087 if (stack->unused_cache_size > (stack->cache_size/2)) {
6088 chunk = stack->cache;
6089 stack->cache = stack->cache->next;
6090 stack->cache_size--;
6091 free(chunk);
6092 }
6093 stack->unused_cache_size = stack->cache_size;
6094}
6095
6096static void
6097push_mark_stack_chunk(mark_stack_t *stack)
6098{
6099 stack_chunk_t *next;
6100
6101 GC_ASSERT(stack->index == stack->limit);
6102
6103 if (stack->cache_size > 0) {
6104 next = stack->cache;
6105 stack->cache = stack->cache->next;
6106 stack->cache_size--;
6107 if (stack->unused_cache_size > stack->cache_size)
6108 stack->unused_cache_size = stack->cache_size;
6109 }
6110 else {
6111 next = stack_chunk_alloc();
6112 }
6113 next->next = stack->chunk;
6114 stack->chunk = next;
6115 stack->index = 0;
6116}
6117
6118static void
6119pop_mark_stack_chunk(mark_stack_t *stack)
6120{
6121 stack_chunk_t *prev;
6122
6123 prev = stack->chunk->next;
6124 GC_ASSERT(stack->index == 0);
6125 add_stack_chunk_cache(stack, stack->chunk);
6126 stack->chunk = prev;
6127 stack->index = stack->limit;
6128}
6129
6130static void
6131mark_stack_chunk_list_free(stack_chunk_t *chunk)
6132{
6133 stack_chunk_t *next = NULL;
6134
6135 while (chunk != NULL) {
6136 next = chunk->next;
6137 free(chunk);
6138 chunk = next;
6139 }
6140}
6141
6142static void
6143free_stack_chunks(mark_stack_t *stack)
6144{
6145 mark_stack_chunk_list_free(stack->chunk);
6146}
6147
6148static void
6149mark_stack_free_cache(mark_stack_t *stack)
6150{
6151 mark_stack_chunk_list_free(stack->cache);
6152 stack->cache_size = 0;
6153 stack->unused_cache_size = 0;
6154}
6155
6156static void
6157push_mark_stack(mark_stack_t *stack, VALUE obj)
6158{
6159 switch (BUILTIN_TYPE(obj)) {
6160 case T_OBJECT:
6161 case T_CLASS:
6162 case T_MODULE:
6163 case T_FLOAT:
6164 case T_STRING:
6165 case T_REGEXP:
6166 case T_ARRAY:
6167 case T_HASH:
6168 case T_STRUCT:
6169 case T_BIGNUM:
6170 case T_FILE:
6171 case T_DATA:
6172 case T_MATCH:
6173 case T_COMPLEX:
6174 case T_RATIONAL:
6175 case T_TRUE:
6176 case T_FALSE:
6177 case T_SYMBOL:
6178 case T_IMEMO:
6179 case T_ICLASS:
6180 if (stack->index == stack->limit) {
6181 push_mark_stack_chunk(stack);
6182 }
6183 stack->chunk->data[stack->index++] = obj;
6184 return;
6185
6186 case T_NONE:
6187 case T_NIL:
6188 case T_FIXNUM:
6189 case T_MOVED:
6190 case T_ZOMBIE:
6191 case T_UNDEF:
6192 case T_MASK:
6193 rb_bug("push_mark_stack() called for broken object");
6194 break;
6195
6196 case T_NODE:
6197 rb_bug("push_mark_stack: unexpected T_NODE object");
6198 break;
6199 }
6200
6201 rb_bug("rb_gc_mark(): unknown data type 0x%x(%p) %s",
6202 BUILTIN_TYPE(obj), (void *)obj,
6203 is_pointer_to_heap((rb_objspace_t *)rb_gc_get_objspace(), (void *)obj) ? "corrupted object" : "non object");
6204}
6205
6206static int
6207pop_mark_stack(mark_stack_t *stack, VALUE *data)
6208{
6209 if (is_mark_stack_empty(stack)) {
6210 return FALSE;
6211 }
6212 if (stack->index == 1) {
6213 *data = stack->chunk->data[--stack->index];
6214 pop_mark_stack_chunk(stack);
6215 }
6216 else {
6217 *data = stack->chunk->data[--stack->index];
6218 }
6219 return TRUE;
6220}
6221
6222static void
6223init_mark_stack(mark_stack_t *stack)
6224{
6225 int i;
6226
6227 MEMZERO(stack, mark_stack_t, 1);
6228 stack->index = stack->limit = STACK_CHUNK_SIZE;
6229
6230 for (i=0; i < 4; i++) {
6231 add_stack_chunk_cache(stack, stack_chunk_alloc());
6232 }
6233 stack->unused_cache_size = stack->cache_size;
6234}
6235
6236/* Marking */
6237
6238ALWAYS_INLINE(static int gc_mark_set(rb_objspace_t *objspace, VALUE obj));
6239ALWAYS_INLINE(static void gc_mark_check_t_none(rb_objspace_t *objspace, VALUE obj));
6240ALWAYS_INLINE(static void rgengc_check_relation(rb_objspace_t *objspace, VALUE obj));
6241ALWAYS_INLINE(static void gc_aging(rb_objspace_t *objspace, VALUE obj));
6242ALWAYS_INLINE(static void gc_grey(rb_objspace_t *objspace, VALUE obj));
6243static void
6244rgengc_check_relation(rb_objspace_t *objspace, VALUE obj)
6245{
6246 if (objspace->rgengc.parent_object_old_p) {
6247 if (!RVALUE_OLD_P(objspace, obj)) {
6248 rgengc_remember(objspace, objspace->rgengc.parent_object);
6249 /* It is in the rememberset now, so its remaining children have nothing left
6250 * to ask for: stop testing them. */
6251 objspace->rgengc.parent_object_old_p = false;
6252 }
6253 }
6254}
6255
6256static inline int
6257gc_mark_set(rb_objspace_t *objspace, VALUE obj)
6258{
6259 if (RVALUE_MARKED(objspace, obj)) return 0;
6260 MARK_IN_BITMAP(GET_HEAP_MARK_BITS(obj), obj);
6261 return 1;
6262}
6263
6264static void
6265gc_aging(rb_objspace_t *objspace, VALUE obj)
6266{
6267 /* Disable aging if Major GC's are disabled. This will prevent longish lived
6268 * objects filling up the heap at the expense of marking many more objects.
6269 *
6270 * We should always pre-warm our process when disabling majors, by running
6271 * GC manually several times so that most objects likely to become oldgen
6272 * are already oldgen.
6273 */
6274 if(!gc_config_full_mark_val)
6275 return;
6276
6277 struct heap_page *page = GET_HEAP_PAGE(obj);
6278
6279 GC_ASSERT(RVALUE_MARKING(objspace, obj) == FALSE);
6280 check_rvalue_consistency(objspace, obj);
6281
6282 if (!RVALUE_PAGE_WB_UNPROTECTED(page, obj)) {
6283 if (!RVALUE_OLD_P(objspace, obj)) {
6284 int t = BUILTIN_TYPE(obj);
6285 if (t == T_CLASS || t == T_MODULE || t == T_ICLASS) {
6286 gc_report(3, objspace, "gc_aging: YOUNG class: %s\n", rb_obj_info(obj));
6287 RVALUE_AGE_SET(obj, RVALUE_OLD_AGE);
6288 RVALUE_OLD_UNCOLLECTIBLE_SET(objspace, obj);
6289 }
6290 else {
6291 gc_report(3, objspace, "gc_aging: YOUNG: %s\n", rb_obj_info(obj));
6292 RVALUE_AGE_INC(objspace, obj);
6293 }
6294 }
6295 else if (is_full_marking(objspace)) {
6296 GC_ASSERT(RVALUE_PAGE_UNCOLLECTIBLE(page, obj) == FALSE);
6297 RVALUE_PAGE_OLD_UNCOLLECTIBLE_SET(objspace, page, obj);
6298 }
6299 }
6300 check_rvalue_consistency(objspace, obj);
6301
6302 objspace->marked_slots++;
6303}
6304
6305static void
6306gc_grey(rb_objspace_t *objspace, VALUE obj)
6307{
6308#if RGENGC_CHECK_MODE
6309 if (RVALUE_MARKED(objspace, obj) == FALSE) rb_bug("gc_grey: %s is not marked.", rb_obj_info(obj));
6310 if (RVALUE_MARKING(objspace, obj) == TRUE) rb_bug("gc_grey: %s is marking/remembered.", rb_obj_info(obj));
6311#endif
6312
6313 if (is_incremental_marking(objspace)) {
6314 MARK_IN_BITMAP(GET_HEAP_MARKING_BITS(obj), obj);
6315 }
6316
6318 rb_darray_append_without_gc(&objspace->weak_references, obj);
6319 }
6320
6321 push_mark_stack(&objspace->mark_stack, obj);
6322}
6323
6324static inline void
6325gc_mark_check_t_none(rb_objspace_t *objspace, VALUE obj)
6326{
6327 if (RB_UNLIKELY(BUILTIN_TYPE(obj) == T_NONE)) {
6328 enum {info_size = 256};
6329 char obj_info_buf[info_size];
6330 rb_raw_obj_info(obj_info_buf, info_size, obj);
6331
6332 char parent_obj_info_buf[info_size];
6333 rb_raw_obj_info(parent_obj_info_buf, info_size, objspace->rgengc.parent_object);
6334
6335 rb_bug("try to mark T_NONE object (obj: %s, parent: %s)", obj_info_buf, parent_obj_info_buf);
6336 }
6337}
6338
6339static void
6340gc_mark(rb_objspace_t *objspace, VALUE obj)
6341{
6342 GC_ASSERT(during_gc);
6343 GC_ASSERT(!objspace->flags.during_reference_updating);
6344
6345 /* Never step into another objspace: a foreign object is a live leaf whose liveness
6346 * belongs to its owner, so touching its bitmaps here would be unsound. A global GC
6347 * lifts this: everyone is stopped and the bits live on the object's own page. */
6348 if (gc_skip_foreign_object_p(objspace, obj)) {
6349 return;
6350 }
6351
6352 if (RB_UNLIKELY(objspace->flags.during_global_gc)) {
6353 /* Recompute the shref of every shareable -> unshareable edge, within and across
6354 * objspaces: the clear pass dropped all shref bits and the write barrier
6355 * maintains them from here on. */
6356 VALUE parent = objspace->rgengc.parent_object;
6357 if (!UNDEF_P(parent) && parent != Qfalse &&
6360 struct heap_page *page = GET_HEAP_PAGE(obj);
6361 _MARK_IN_BITMAP(page->shref_bits, page, obj);
6362 page->flags.has_shref_objects = TRUE;
6363 }
6364 }
6365
6366 rgengc_check_relation(objspace, obj);
6367 if (!gc_mark_set(objspace, obj)) return; /* already marked */
6368
6369 if (0) { // for debug GC marking miss
6370 RUBY_DEBUG_LOG("%p (%s) parent:%p (%s)",
6371 (void *)obj, obj_type_name(obj),
6372 (void *)objspace->rgengc.parent_object, obj_type_name(objspace->rgengc.parent_object));
6373 }
6374
6375 gc_mark_check_t_none(objspace, obj);
6376
6377 gc_aging(objspace, obj);
6378 gc_grey(objspace, obj);
6379}
6380
6381static inline void
6382gc_pin(rb_objspace_t *objspace, VALUE obj)
6383{
6384 GC_ASSERT(!SPECIAL_CONST_P(obj));
6385
6386 if (RB_UNLIKELY(objspace->flags.during_compacting)) {
6387 /* Never write a foreign page's pinned bit (a global GC may: everyone is stopped). */
6388 if (gc_skip_foreign_object_p(objspace, obj)) return;
6389
6390 if (RB_LIKELY(during_gc)) {
6391 if (!RVALUE_PINNED(objspace, obj)) {
6392 GC_ASSERT(GET_HEAP_PAGE(obj)->pinned_slots <= GET_HEAP_PAGE(obj)->total_slots);
6393 GET_HEAP_PAGE(obj)->pinned_slots++;
6394 MARK_IN_BITMAP(GET_HEAP_PINNED_BITS(obj), obj);
6395 }
6396 }
6397 }
6398}
6399
6400static inline void
6401gc_mark_and_pin(rb_objspace_t *objspace, VALUE obj)
6402{
6403 gc_pin(objspace, obj);
6404 gc_mark(objspace, obj);
6405}
6406
6407void
6408rb_gc_impl_mark_and_move(void *objspace_ptr, VALUE *ptr)
6409{
6410 rb_objspace_t *objspace = objspace_ptr;
6411
6412 if (RB_UNLIKELY(objspace->flags.during_reference_updating)) {
6413 GC_ASSERT(objspace->flags.during_compacting);
6414 GC_ASSERT(during_gc);
6415
6416 VALUE destination = rb_gc_impl_location(objspace, *ptr);
6417 if (destination != *ptr) {
6418 *ptr = destination;
6419 }
6420 }
6421 else {
6422 gc_mark(objspace, *ptr);
6423 }
6424}
6425
6426void
6427rb_gc_impl_mark(void *objspace_ptr, VALUE obj)
6428{
6429 rb_objspace_t *objspace = objspace_ptr;
6430
6431 gc_mark(objspace, obj);
6432}
6433
6434void
6435rb_gc_impl_mark_and_pin(void *objspace_ptr, VALUE obj)
6436{
6437 rb_objspace_t *objspace = objspace_ptr;
6438
6439 gc_mark_and_pin(objspace, obj);
6440}
6441
6442/* A word scanned conservatively by a global GC can point into any objspace, so ownership
6443 * is decided against the driver's snapshot of every objspace (the bits then land on the
6444 * owner's page through gc_mark and gc_pin). */
6445static bool
6446gc_global_pointer_to_heap_p(const void *ptr)
6447{
6448 const rb_global_objspace_t *g = global_objspace;
6449 uintptr_t p = (uintptr_t)ptr;
6450
6451 if (p < g->page_index.lomem || p > g->page_index.himem) return false;
6452 if (p % sizeof(VALUE) != 0) return false;
6453
6454 struct heap_page **res = bsearch(ptr, g->page_index.pages, g->page_index.n_pages,
6455 sizeof(struct heap_page *), ptr_in_page_body_p);
6456 if (res == NULL) return false;
6457
6458 struct heap_page *page = *res;
6459 if (heap_page_in_global_empty_pages_pool(page->objspace, page)) return false;
6460 if (p < page->start) return false;
6461 if (p >= page->start + (page->total_slots * page->slot_size)) return false;
6462 if ((p - page->start) % page->slot_size != 0) return false;
6463 return true;
6464}
6465
6466void
6467rb_gc_impl_mark_maybe(void *objspace_ptr, VALUE obj)
6468{
6469 rb_objspace_t *objspace = objspace_ptr;
6470
6471 (void)VALGRIND_MAKE_MEM_DEFINED(&obj, sizeof(obj));
6472
6473 if (RB_UNLIKELY(objspace->flags.during_global_gc)
6474 ? gc_global_pointer_to_heap_p((void *)obj)
6475 : is_pointer_to_heap(objspace, (void *)obj)) {
6476 asan_unpoisoning_object(obj) {
6477 /* Garbage can live on the stack, so do not mark or pin */
6478 switch (BUILTIN_TYPE(obj)) {
6479 case T_ZOMBIE:
6480 case T_NONE:
6481 break;
6482 default:
6483 gc_mark_and_pin(objspace, obj);
6484 break;
6485 }
6486 }
6487 }
6488}
6489
6490static int
6491pin_value(st_data_t key, st_data_t value, st_data_t data)
6492{
6493 rb_gc_impl_mark_and_pin((void *)data, (VALUE)value);
6494
6495 return ST_CONTINUE;
6496}
6497
6498static inline void
6499gc_mark_set_parent_raw(rb_objspace_t *objspace, VALUE obj, bool old_p)
6500{
6501 asan_unpoison_memory_region(&objspace->rgengc.parent_object, sizeof(objspace->rgengc.parent_object), false);
6502 asan_unpoison_memory_region(&objspace->rgengc.parent_object_old_p, sizeof(objspace->rgengc.parent_object_old_p), false);
6503 objspace->rgengc.parent_object = obj;
6504 objspace->rgengc.parent_object_old_p = old_p;
6505}
6506
6507static inline void
6508gc_mark_set_parent(rb_objspace_t *objspace, VALUE obj)
6509{
6510 gc_mark_set_parent_raw(objspace, obj, RVALUE_OLD_P(objspace, obj));
6511}
6512
6513static inline void
6514gc_mark_set_parent_invalid(rb_objspace_t *objspace)
6515{
6516 asan_poison_memory_region(&objspace->rgengc.parent_object, sizeof(objspace->rgengc.parent_object));
6517 asan_poison_memory_region(&objspace->rgengc.parent_object_old_p, sizeof(objspace->rgengc.parent_object_old_p));
6518}
6519
6520static void pinned_roots_mark(rb_objspace_t *objspace, rb_heap_t *heap);
6521
6522static void
6523mark_roots(rb_objspace_t *objspace, const char **categoryp)
6524{
6525 VALUE objspace_guard = (VALUE)objspace;
6526#define MARK_CHECKPOINT(category) do { \
6527 if (categoryp) *categoryp = category; \
6528} while (0)
6529
6530 /* Pinning shareable objects and shrefs runs at the end of marking (gc_marks_finish),
6531 * not here: after the full walk it only has to touch what ordinary marking missed,
6532 * which is both cheap and a useful retention metric. */
6533
6534 MARK_CHECKPOINT("objspace");
6535 gc_mark_set_parent_raw(objspace, Qundef, false);
6536
6537 if (objspace->flags.during_global_gc) {
6538 /* Pin the finalizer tables of every objspace, zombies included.
6539 * (finalizer_table is a macro over the local "objspace".) */
6540 rb_objspace_t *const driver = objspace;
6541 for (size_t i = 0; i < global_objspace->global_gc.n_objspaces; i++) {
6542 rb_objspace_t *objspace = global_objspace->global_gc.objspaces[i];
6543 if (finalizer_table != NULL) {
6544 st_foreach(finalizer_table, pin_value, (st_data_t)driver);
6545 }
6546 }
6547 }
6548 else if (finalizer_table != NULL) {
6549 st_foreach(finalizer_table, pin_value, (st_data_t)objspace);
6550 }
6551
6552 if (stress_to_class) rb_gc_mark(stress_to_class);
6553
6554 rb_gc_save_machine_context();
6555 rb_gc_mark_roots(objspace, categoryp);
6556 /* Keep this frame, including its saved registers, until root marking has
6557 * scanned the machine stack. */
6558 RB_GC_GUARD(objspace_guard);
6559 gc_mark_set_parent_invalid(objspace);
6560}
6561
6562static void
6563gc_mark_children(rb_objspace_t *objspace, VALUE obj)
6564{
6565 gc_mark_set_parent(objspace, obj);
6566 rb_gc_mark_children(objspace, obj);
6567 gc_mark_set_parent_invalid(objspace);
6568}
6569
6574static inline int
6575gc_mark_stacked_objects(rb_objspace_t *objspace, int incremental, size_t count)
6576{
6577 mark_stack_t *mstack = &objspace->mark_stack;
6578 VALUE obj;
6579 size_t marked_slots_at_the_beginning = objspace->marked_slots;
6580 size_t popped_count = 0;
6581
6582 while (pop_mark_stack(mstack, &obj)) {
6583 if (obj == Qundef) continue; /* skip */
6584
6585 if (RGENGC_CHECK_MODE && !RVALUE_MARKED(objspace, obj)) {
6586 rb_bug("gc_mark_stacked_objects: %s is not marked.", rb_obj_info(obj));
6587 }
6588 gc_mark_children(objspace, obj);
6589
6590 popped_count++;
6591
6592 if (incremental) {
6593 if (RGENGC_CHECK_MODE && !RVALUE_MARKING(objspace, obj)) {
6594 rb_bug("gc_mark_stacked_objects: incremental, but marking bit is 0");
6595 }
6596 CLEAR_IN_BITMAP(GET_HEAP_MARKING_BITS(obj), obj);
6597
6598 if (popped_count + (objspace->marked_slots - marked_slots_at_the_beginning) > count) {
6599 break;
6600 }
6601 }
6602 else {
6603 /* just ignore marking bits */
6604 }
6605 }
6606
6607 RUBY_DTRACE_GC_HOOK(MARK_STACKED_OBJECTS, popped_count);
6608
6609 if (RGENGC_CHECK_MODE >= 3) gc_verify_internal_consistency(objspace);
6610
6611 if (is_mark_stack_empty(mstack)) {
6612 shrink_stack_chunk_cache(mstack);
6613 return TRUE;
6614 }
6615 else {
6616 return FALSE;
6617 }
6618}
6619
6620static int
6621gc_mark_stacked_objects_incremental(rb_objspace_t *objspace, size_t count)
6622{
6623 return gc_mark_stacked_objects(objspace, TRUE, count);
6624}
6625
6626static int
6627gc_mark_stacked_objects_all(rb_objspace_t *objspace)
6628{
6629 return gc_mark_stacked_objects(objspace, FALSE, 0);
6630}
6631
6632#if RGENGC_CHECK_MODE >= 4
6633
6634#define MAKE_ROOTSIG(obj) (((VALUE)(obj) << 1) | 0x01)
6635#define IS_ROOTSIG(obj) ((VALUE)(obj) & 0x01)
6636#define GET_ROOTSIG(obj) ((const char *)((VALUE)(obj) >> 1))
6637
6638struct reflist {
6639 VALUE *list;
6640 int pos;
6641 int size;
6642};
6643
6644static struct reflist *
6645reflist_create(VALUE obj)
6646{
6647 struct reflist *refs = xmalloc(sizeof(struct reflist));
6648 refs->size = 1;
6649 refs->list = ALLOC_N(VALUE, refs->size);
6650 refs->list[0] = obj;
6651 refs->pos = 1;
6652 return refs;
6653}
6654
6655static void
6656reflist_destruct(struct reflist *refs)
6657{
6658 xfree(refs->list);
6659 xfree(refs);
6660}
6661
6662static void
6663reflist_add(struct reflist *refs, VALUE obj)
6664{
6665 if (refs->pos == refs->size) {
6666 refs->size *= 2;
6667 SIZED_REALLOC_N(refs->list, VALUE, refs->size, refs->size/2);
6668 }
6669
6670 refs->list[refs->pos++] = obj;
6671}
6672
6673static void
6674reflist_dump(struct reflist *refs)
6675{
6676 int i;
6677 for (i=0; i<refs->pos; i++) {
6678 VALUE obj = refs->list[i];
6679 if (IS_ROOTSIG(obj)) { /* root */
6680 fprintf(stderr, "<root@%s>", GET_ROOTSIG(obj));
6681 }
6682 else {
6683 fprintf(stderr, "<%s>", rb_obj_info(obj));
6684 }
6685 if (i+1 < refs->pos) fprintf(stderr, ", ");
6686 }
6687}
6688
6689static int
6690reflist_referred_from_machine_context(struct reflist *refs)
6691{
6692 int i;
6693 for (i=0; i<refs->pos; i++) {
6694 VALUE obj = refs->list[i];
6695 if (IS_ROOTSIG(obj) && strcmp(GET_ROOTSIG(obj), "machine_context") == 0) return 1;
6696 }
6697 return 0;
6698}
6699
6700struct allrefs {
6702 /* a -> obj1
6703 * b -> obj1
6704 * c -> obj1
6705 * c -> obj2
6706 * d -> obj3
6707 * #=> {obj1 => [a, b, c], obj2 => [c, d]}
6708 */
6709 struct st_table *references;
6710 const char *category;
6711 VALUE root_obj;
6713};
6714
6715static int
6716allrefs_add(struct allrefs *data, VALUE obj)
6717{
6718 struct reflist *refs;
6719 st_data_t r;
6720
6721 if (st_lookup(data->references, obj, &r)) {
6722 refs = (struct reflist *)r;
6723 reflist_add(refs, data->root_obj);
6724 return 0;
6725 }
6726 else {
6727 refs = reflist_create(data->root_obj);
6728 st_insert(data->references, obj, (st_data_t)refs);
6729 return 1;
6730 }
6731}
6732
6733static void
6734allrefs_i(VALUE obj, void *ptr)
6735{
6736 struct allrefs *data = (struct allrefs *)ptr;
6737
6738 if (allrefs_add(data, obj)) {
6739 push_mark_stack(&data->mark_stack, obj);
6740 }
6741}
6742
6743static void
6744allrefs_roots_i(VALUE obj, void *ptr)
6745{
6746 struct allrefs *data = (struct allrefs *)ptr;
6747 if (strlen(data->category) == 0) rb_bug("!!!");
6748 data->root_obj = MAKE_ROOTSIG(data->category);
6749
6750 if (allrefs_add(data, obj)) {
6751 push_mark_stack(&data->mark_stack, obj);
6752 }
6753}
6754#define PUSH_MARK_FUNC_DATA(v) do { \
6755 struct gc_mark_func_data_struct *prev_mark_func_data = GET_VM()->gc.mark_func_data; \
6756 GET_VM()->gc.mark_func_data = (v);
6757
6758#define POP_MARK_FUNC_DATA() GET_VM()->gc.mark_func_data = prev_mark_func_data;} while (0)
6759
6760static st_table *
6761objspace_allrefs(rb_objspace_t *objspace)
6762{
6763 struct allrefs data;
6764 struct gc_mark_func_data_struct mfd;
6765 VALUE obj;
6766 int prev_dont_gc = dont_gc_val();
6767 dont_gc_on();
6768
6769 data.objspace = objspace;
6770 data.references = st_init_numtable();
6771 init_mark_stack(&data.mark_stack);
6772
6773 mfd.mark_func = allrefs_roots_i;
6774 mfd.data = &data;
6775
6776 /* traverse root objects */
6777 PUSH_MARK_FUNC_DATA(&mfd);
6778 GET_VM()->gc.mark_func_data = &mfd;
6779 mark_roots(objspace, &data.category);
6780 POP_MARK_FUNC_DATA();
6781
6782 /* traverse rest objects reachable from root objects */
6783 while (pop_mark_stack(&data.mark_stack, &obj)) {
6784 rb_objspace_reachable_objects_from_unlocked(data.root_obj = obj, allrefs_i, &data);
6785 }
6786 free_stack_chunks(&data.mark_stack);
6787
6788 dont_gc_set(prev_dont_gc);
6789 return data.references;
6790}
6791
6792static int
6793objspace_allrefs_destruct_i(st_data_t key, st_data_t value, st_data_t ptr)
6794{
6795 struct reflist *refs = (struct reflist *)value;
6796 reflist_destruct(refs);
6797 return ST_CONTINUE;
6798}
6799
6800static void
6801objspace_allrefs_destruct(struct st_table *refs)
6802{
6803 st_foreach(refs, objspace_allrefs_destruct_i, 0);
6804 st_free_table(refs);
6805}
6806
6807#if RGENGC_CHECK_MODE >= 5
6808static int
6809allrefs_dump_i(st_data_t k, st_data_t v, st_data_t ptr)
6810{
6811 VALUE obj = (VALUE)k;
6812 struct reflist *refs = (struct reflist *)v;
6813 fprintf(stderr, "[allrefs_dump_i] %s <- ", rb_obj_info(obj));
6814 reflist_dump(refs);
6815 fprintf(stderr, "\n");
6816 return ST_CONTINUE;
6817}
6818
6819static void
6820allrefs_dump(rb_objspace_t *objspace)
6821{
6822 VALUE size = objspace->rgengc.allrefs_table->num_entries;
6823 fprintf(stderr, "[all refs] (size: %"PRIuVALUE")\n", size);
6824 st_foreach(objspace->rgengc.allrefs_table, allrefs_dump_i, 0);
6825}
6826#endif
6827
6828static int
6829gc_check_after_marks_i(st_data_t k, st_data_t v, st_data_t ptr)
6830{
6831 VALUE obj = k;
6832 struct reflist *refs = (struct reflist *)v;
6834
6835 /* object should be marked or oldgen */
6836 if (!RVALUE_MARKED(objspace, obj)) {
6837 fprintf(stderr, "gc_check_after_marks_i: %s is not marked and not oldgen.\n", rb_obj_info(obj));
6838 fprintf(stderr, "gc_check_after_marks_i: %p is referred from ", (void *)obj);
6839 reflist_dump(refs);
6840
6841 if (reflist_referred_from_machine_context(refs)) {
6842 fprintf(stderr, " (marked from machine stack).\n");
6843 /* marked from machine context can be false positive */
6844 }
6845 else {
6846 objspace->rgengc.error_count++;
6847 fprintf(stderr, "\n");
6848 }
6849 }
6850 return ST_CONTINUE;
6851}
6852
6853static void
6854gc_marks_check(rb_objspace_t *objspace, st_foreach_callback_func *checker_func, const char *checker_name)
6855{
6856 MALLOC_COUNTERS_LOCK(objspace);
6857 struct gc_malloc_bytes saved_malloc = {
6858 .malloc = gc_counter_load_relaxed(&objspace->malloc_counters.counters.malloc),
6859 .free = gc_counter_load_relaxed(&objspace->malloc_counters.counters.free),
6860 .malloc_at_last_gc = gc_counter_load_relaxed(&objspace->malloc_counters.counters.malloc_at_last_gc),
6861 .free_at_last_gc = gc_counter_load_relaxed(&objspace->malloc_counters.counters.free_at_last_gc),
6862 };
6863#if RGENGC_ESTIMATE_OLDMALLOC
6864 struct gc_malloc_bytes saved_oldmalloc = {
6865 .malloc = gc_counter_load_relaxed(&objspace->malloc_counters.oldcounters.malloc),
6866 .free = gc_counter_load_relaxed(&objspace->malloc_counters.oldcounters.free),
6867 .malloc_at_last_gc = gc_counter_load_relaxed(&objspace->malloc_counters.oldcounters.malloc_at_last_gc),
6868 .free_at_last_gc = gc_counter_load_relaxed(&objspace->malloc_counters.oldcounters.free_at_last_gc),
6869 };
6870#endif
6871 MALLOC_COUNTERS_UNLOCK(objspace);
6872 VALUE already_disabled = rb_objspace_gc_disable(objspace);
6873
6874 objspace->rgengc.allrefs_table = objspace_allrefs(objspace);
6875
6876 if (checker_func) {
6877 st_foreach(objspace->rgengc.allrefs_table, checker_func, (st_data_t)objspace);
6878 }
6879
6880 if (objspace->rgengc.error_count > 0) {
6881#if RGENGC_CHECK_MODE >= 5
6882 allrefs_dump(objspace);
6883#endif
6884 if (checker_name) rb_bug("%s: GC has problem.", checker_name);
6885 }
6886
6887 objspace_allrefs_destruct(objspace->rgengc.allrefs_table);
6888 objspace->rgengc.allrefs_table = 0;
6889
6890 if (already_disabled == Qfalse) rb_objspace_gc_enable(objspace);
6891 MALLOC_COUNTERS_LOCK(objspace);
6892 gc_counter_store_release(&objspace->malloc_counters.counters.malloc, saved_malloc.malloc);
6893 gc_counter_store_release(&objspace->malloc_counters.counters.free, saved_malloc.free);
6894 gc_counter_store_release(&objspace->malloc_counters.counters.malloc_at_last_gc, saved_malloc.malloc_at_last_gc);
6895 gc_counter_store_release(&objspace->malloc_counters.counters.free_at_last_gc, saved_malloc.free_at_last_gc);
6896#if RGENGC_ESTIMATE_OLDMALLOC
6897 gc_counter_store_release(&objspace->malloc_counters.oldcounters.malloc, saved_oldmalloc.malloc);
6898 gc_counter_store_release(&objspace->malloc_counters.oldcounters.free, saved_oldmalloc.free);
6899 gc_counter_store_release(&objspace->malloc_counters.oldcounters.malloc_at_last_gc, saved_oldmalloc.malloc_at_last_gc);
6900 gc_counter_store_release(&objspace->malloc_counters.oldcounters.free_at_last_gc, saved_oldmalloc.free_at_last_gc);
6901#endif
6902 MALLOC_COUNTERS_UNLOCK(objspace);
6903}
6904#endif /* RGENGC_CHECK_MODE >= 4 */
6905
6908 /* True only while the world is stopped: a GC.verify holding the VM lock and barrier,
6909 * or a global GC. Cross-objspace checks (walking every objspace's pages) are sound
6910 * only then. */
6911 bool world_stopped;
6912 int err_count;
6913 size_t live_object_count;
6914 size_t zombie_object_count;
6915
6916 VALUE parent;
6917 bool parent_shareable;
6918 size_t old_object_count;
6919 size_t remembered_shady_count;
6920};
6921
6922
6923static void
6924check_generation_i(const VALUE child, void *ptr)
6925{
6927 const VALUE parent = data->parent;
6928
6929 if (RGENGC_CHECK_MODE) GC_ASSERT(RVALUE_OLD_P(data->objspace, parent));
6930
6931 /* A cross-objspace edge is kept alive by the shareable/shref mechanism and is not
6932 * tracked in this objspace's remembered set. */
6933 if (GET_HEAP_OBJSPACE(child) != data->objspace) return;
6934
6935 /* Once the process goes multi-Ractor, the shareable world is managed by pinning and
6936 * shrefs rather than by the remembered set: the pinned walk at the end of a mark
6937 * re-marks every shareable object (and its shref'd children) each local cycle, and a
6938 * global GC rebuilds the generation state. So the generational old->young invariant
6939 * does not hold when either endpoint is shareable: an old constcache, cc_table or
6940 * interned string pointing at a core class that is young after a global GC is the
6941 * typical false positive. That state outlives the return to a single Ractor until
6942 * the next major (an old shareable singleton class pointing at a young
6943 * attached_object, say), so the test uses rb_gc_ever_multi_ractor_p(), which stays
6944 * true forever once multiple Ractors existed. A program that never goes multi keeps
6945 * the strict check, and ASAN catches what is left. */
6946 if (rb_gc_ever_multi_ractor_p() &&
6947 (MARKED_IN_BITMAP(GET_HEAP_SHAREABLE_BITS(parent), parent) ||
6948 MARKED_IN_BITMAP(GET_HEAP_SHAREABLE_BITS(child), child))) {
6949 return;
6950 }
6951
6952 if (!RVALUE_OLD_P(data->objspace, child)) {
6953 /* A young shareable child is pinned and kept alive by the local GC (only a
6954 * global GC collects it), so it survives even when the old parent does not
6955 * remember it. It is outside the generational remembered set, so exclude it
6956 * from the old->young check. */
6957 if (!RVALUE_REMEMBERED(data->objspace, parent) &&
6958 !RVALUE_REMEMBERED(data->objspace, child) &&
6959 !RVALUE_UNCOLLECTIBLE(data->objspace, child) &&
6961 fprintf(stderr, "verify_internal_consistency_reachable_i: WB miss (O->Y) %s -> %s\n", rb_obj_info(parent), rb_obj_info(child));
6962 data->err_count++;
6963 }
6964 }
6965}
6966
6967static void
6968check_color_i(const VALUE child, void *ptr)
6969{
6971 const VALUE parent = data->parent;
6972
6973 /* This cycle never marks a foreign child (gc_skip_foreign_object_p) and the write
6974 * barrier is a no-op across objspaces, so its colour says nothing here. */
6975 if (GET_HEAP_OBJSPACE(child) != data->objspace) return;
6976
6977 if (!RVALUE_WB_UNPROTECTED(data->objspace, parent) && RVALUE_WHITE_P(data->objspace, child)) {
6978 fprintf(stderr, "verify_internal_consistency_reachable_i: WB miss (B->W) - %s -> %s\n",
6979 rb_obj_info(parent), rb_obj_info(child));
6980 data->err_count++;
6981 }
6982}
6983
6984static void
6985check_children_i(const VALUE child, void *ptr)
6986{
6988
6989 /* Fast path: a child in this objspace (99.99% of all edges). */
6990 if (RB_LIKELY(is_pointer_to_heap(data->objspace, (void *)child))) {
6991 if (check_rvalue_consistency_force(data->objspace, child, FALSE) != 0) {
6992 fprintf(stderr, "check_children_i: %s has error (referenced from %s)\n",
6993 rb_obj_info(child), rb_obj_info(data->parent));
6994 data->err_count++;
6995 }
6996 return;
6997 }
6998
6999 /* The remaining cross-objspace check (verify_pointer_in_any_heap_p) walks every
7000 * objspace's pages, sound only with the world stopped: mid-local-GC other Ractors
7001 * change page structures concurrently. The next world-stopped verify re-checks. */
7002 if (!data->world_stopped) return;
7003
7004 /* A non-heap child reaches this callback only when a stale field was followed by a
7005 * plain rb_gc_mark (the dmark of a live but unreachable wrapper, say). Report it and
7006 * keep going rather than aborting. */
7007 if (!verify_pointer_in_any_heap_p((void *)child)) {
7008 /* The graph is in flux mid-merge, so a transient non-heap edge is expected; it
7009 * is re-checked after the merge. */
7010 if (global_objspace->during_absorb) return;
7011 fprintf(stderr, "VERIFY-NOTE: non-heap child %p (from %s)\n",
7012 (void *)child, rb_obj_info(data->parent));
7013 return;
7014 }
7015
7016 if (GET_HEAP_OBJSPACE(child) != data->objspace) {
7017 /* A legal cross-objspace edge either starts at a shareable object or is recorded
7018 * in the child's shref bit (an in-flight send or move payload kept alive across
7019 * its owner's local GC; root_scope_check_i honours the same record). An
7020 * unshareable parent holding an unrecorded foreign unshareable child would be
7021 * invisible to both local GCs. The exception is a box's top_self, which every
7022 * thread's th->top_self points at and which is VM-permanent. Skipped during a
7023 * global GC: it clears every shref bit, so the shref exemption would not fire,
7024 * and its unified exact stop-the-world mark makes the invariant itself moot. */
7025 if (!data->parent_shareable &&
7026 child != rb_gc_vm_top_self() &&
7027 !MARKED_IN_BITMAP(GET_HEAP_SHAREABLE_BITS(child), child) &&
7028 !MARKED_IN_BITMAP(GET_HEAP_SHREF_BITS(child), child) &&
7029 !rb_gc_impl_during_global_gc_p(data->objspace) &&
7030 !global_objspace->during_absorb) {
7031 fprintf(stderr, "check_children_i: containment violation: "
7032 "unshareable %s (objspace %p) -> foreign unshareable %s (objspace %p)\n",
7033 rb_obj_info(data->parent), (void *)data->objspace,
7034 rb_obj_info(child), (void *)GET_HEAP_OBJSPACE(child));
7035 data->err_count++;
7036 }
7037
7038 /* The remaining per-objspace sanity rules belong to the owner. */
7039 return;
7040 }
7041}
7042
7043/* Whether a heap slot currently holds a live object. Returns false for empty
7044 * (T_NONE), moved (T_MOVED), and zombie (T_ZOMBIE) slots, and for garbage
7045 * objects about to be swept. */
7046static bool
7047gc_slot_live_object_p(rb_objspace_t *objspace, VALUE obj)
7048{
7049 switch (BUILTIN_TYPE(obj)) {
7050 case T_NONE:
7051 case T_MOVED:
7052 case T_ZOMBIE:
7053 return false;
7054 default:
7055 return !rb_gc_impl_garbage_object_p(objspace, obj);
7056 }
7057}
7058
7059/* Verifier only: does ptr point at a live slot in any objspace? The caller holds the VM
7060 * lock and the barrier, so page_index is stable. */
7061static bool
7062verify_pointer_in_any_heap_p(const void *ptr)
7063{
7064 return gc_global_pointer_to_heap_p(ptr);
7065}
7066
7067/* An exact root of the calling Ractor may only point at a shareable object, its own
7068 * objspace, or an in-flight payload with a recorded shref. Exempt: the conservative
7069 * machine scan (stale slots) and the VM-global containers that are cross-rooted by
7070 * design (every objspace scans them; the marker skips foreign entries). */
7071static void
7072root_scope_check_i(const char *category, VALUE obj, void *ptr)
7073{
7074 struct verify_internal_consistency_struct *data = ptr;
7075
7076 if (RB_SPECIAL_CONST_P(obj)) return;
7077 /* This check walks every objspace (verify_pointer_in_any_heap_p), so it is sound
7078 * only with the world stopped; a mid-local-GC verify races with other Ractors'
7079 * lock-free allocation. */
7080 if (!data->world_stopped) return;
7081 /* Mid-merge the VM-global root tables still point at the unmerged source (transient
7082 * non-heap or foreign roots); re-checked after the merge. */
7083 if (global_objspace->during_absorb) return;
7084 if (strcmp(category, "machine_context") == 0 ||
7085 strcmp(category, "vm_registered_objects") == 0 ||
7086 strcmp(category, "end_proc") == 0 ||
7087 strcmp(category, "trap_list") == 0) {
7088 return;
7089 }
7090
7091 if (!verify_pointer_in_any_heap_p((void *)obj)) {
7092 fprintf(stderr, "root_scope_check_i: root category \"%s\" names a non-heap pointer %p\n",
7093 category, (void *)obj);
7094 data->err_count++;
7095 return;
7096 }
7097
7098 if (GET_HEAP_OBJSPACE(obj) == data->objspace) return;
7099 if (MARKED_IN_BITMAP(GET_HEAP_SHAREABLE_BITS(obj), obj)) return;
7100 if (MARKED_IN_BITMAP(GET_HEAP_SHREF_BITS(obj), obj)) return;
7101 if (obj == rb_gc_vm_top_self()) return; /* VM-permanent (see check_children_i) */
7102
7103 fprintf(stderr, "root_scope_check_i: root category \"%s\" names a foreign "
7104 "unshareable without a shref record: %s (owner %p, self %p)\n",
7105 category, rb_obj_info(obj),
7106 (void *)GET_HEAP_OBJSPACE(obj), (void *)data->objspace);
7107 data->err_count++;
7108}
7109
7110static int
7111verify_internal_consistency_i(void *page_start, void *page_end, size_t stride,
7113{
7114 VALUE obj;
7115 rb_objspace_t *objspace = data->objspace;
7116
7117 for (obj = (VALUE)page_start; obj != (VALUE)page_end; obj += stride) {
7118 asan_unpoisoning_object(obj) {
7119 bool sh_bit = MARKED_IN_BITMAP(GET_HEAP_SHAREABLE_BITS(obj), obj) != 0;
7120 bool sr_bit = MARKED_IN_BITMAP(GET_HEAP_SHREF_BITS(obj), obj) != 0;
7121
7122 if (gc_slot_live_object_p(objspace, obj)) {
7123 /* count objects */
7124 data->live_object_count++;
7125 data->parent = obj;
7126 data->parent_shareable = sh_bit;
7127
7128 /* Bitmap invariants: a page's shareable bit matches FL_SHAREABLE
7129 * exactly, and a shref record only ever points at an unshareable
7130 * object. */
7131 if (sh_bit != !!RB_FL_TEST_RAW(obj, RUBY_FL_SHAREABLE)) {
7132 fprintf(stderr, "verify_internal_consistency_i: shareable bit %d "
7133 "disagrees with FL_SHAREABLE on %s\n", (int)sh_bit, rb_obj_info(obj));
7134 data->err_count++;
7135 }
7136 if (sr_bit && sh_bit) {
7137 fprintf(stderr, "verify_internal_consistency_i: shref bit on a shareable: %s\n",
7138 rb_obj_info(obj));
7139 data->err_count++;
7140 }
7141
7142 /* Normally, we don't expect T_MOVED objects to be in the heap.
7143 * But they can stay alive on the stack, */
7144 if (!gc_object_moved_p(objspace, obj)) {
7145 /* moved slots don't have children */
7146 rb_objspace_reachable_objects_from_unlocked(obj, check_children_i, (void *)data);
7147 }
7148
7149 /* check health of children */
7150 if (RVALUE_OLD_P(objspace, obj)) data->old_object_count++;
7151 if (RVALUE_WB_UNPROTECTED(objspace, obj) && RVALUE_UNCOLLECTIBLE(objspace, obj)) data->remembered_shady_count++;
7152
7153 if (!is_marking(objspace) && RVALUE_OLD_P(objspace, obj)) {
7154 /* reachable objects from an oldgen object should be old or (young with remember) */
7155 data->parent = obj;
7156 rb_objspace_reachable_objects_from_unlocked(obj, check_generation_i, (void *)data);
7157 }
7158
7159 if (!is_marking(objspace) && rb_gc_obj_shareable_p(obj)) {
7160 rb_gc_verify_shareable(obj);
7161 }
7162
7163 if (is_incremental_marking(objspace)) {
7164 if (RVALUE_BLACK_P(objspace, obj)) {
7165 /* reachable objects from black objects should be black or grey objects */
7166 data->parent = obj;
7167 rb_objspace_reachable_objects_from_unlocked(obj, check_color_i, (void *)data);
7168 }
7169 }
7170 }
7171 else {
7172 /* A freed slot must not carry its old pin bit into the next object born
7173 * there (a dead object not swept yet legitimately keeps it until the
7174 * sweep arrives). */
7175 if (BUILTIN_TYPE(obj) == T_NONE && (sh_bit || sr_bit)) {
7176 fprintf(stderr, "verify_internal_consistency_i: T_NONE slot carries "
7177 "shareable=%d shref=%d bits\n", (int)sh_bit, (int)sr_bit);
7178 data->err_count++;
7179 }
7180
7181 if (BUILTIN_TYPE(obj) == T_ZOMBIE) {
7182 data->zombie_object_count++;
7183
7184 if ((RBASIC(obj)->flags & ~ZOMBIE_OBJ_KEPT_FLAGS) != T_ZOMBIE) {
7185 fprintf(stderr, "verify_internal_consistency_i: T_ZOMBIE has extra flags set: %s\n",
7186 rb_obj_info(obj));
7187 data->err_count++;
7188 }
7189
7190 if (!!FL_TEST(obj, FL_FINALIZE) != !!st_is_member(finalizer_table, obj)) {
7191 fprintf(stderr, "verify_internal_consistency_i: FL_FINALIZE %s but %s finalizer_table: %s\n",
7192 FL_TEST(obj, FL_FINALIZE) ? "set" : "not set", st_is_member(finalizer_table, obj) ? "in" : "not in",
7193 rb_obj_info(obj));
7194 data->err_count++;
7195 }
7196 }
7197 }
7198 }
7199 }
7200
7201 return 0;
7202}
7203
7204static int
7205gc_verify_heap_page(rb_objspace_t *objspace, struct heap_page *page, VALUE obj)
7206{
7207 unsigned int has_remembered_shady = FALSE;
7208 unsigned int has_remembered_old = FALSE;
7209 int remembered_old_objects = 0;
7210 int free_objects = 0;
7211 int zombie_objects = 0;
7212
7213 short slot_size = page->slot_size;
7214 uintptr_t start = (uintptr_t)page->start;
7215 uintptr_t end = start + page->total_slots * slot_size;
7216
7217 for (uintptr_t ptr = start; ptr < end; ptr += slot_size) {
7218 VALUE val = (VALUE)ptr;
7219 asan_unpoisoning_object(val) {
7220 enum ruby_value_type type = BUILTIN_TYPE(val);
7221
7222 if (type == T_NONE) free_objects++;
7223 if (type == T_ZOMBIE) zombie_objects++;
7224 if (RVALUE_PAGE_UNCOLLECTIBLE(page, val) && RVALUE_PAGE_WB_UNPROTECTED(page, val)) {
7225 has_remembered_shady = TRUE;
7226 }
7227 if (RVALUE_PAGE_MARKING(page, val)) {
7228 has_remembered_old = TRUE;
7229 remembered_old_objects++;
7230 }
7231 }
7232 }
7233
7234 if (!is_incremental_marking(objspace) &&
7235 page->flags.has_remembered_objects == FALSE && has_remembered_old == TRUE) {
7236
7237 for (uintptr_t ptr = start; ptr < end; ptr += slot_size) {
7238 VALUE val = (VALUE)ptr;
7239 if (RVALUE_PAGE_MARKING(page, val)) {
7240 fprintf(stderr, "marking -> %s\n", rb_obj_info(val));
7241 }
7242 }
7243 rb_bug("page %p's has_remembered_objects should be false, but there are remembered old objects (%d). %s",
7244 (void *)page, remembered_old_objects, obj ? rb_obj_info(obj) : "");
7245 }
7246
7247 if (page->flags.has_uncollectible_wb_unprotected_objects == FALSE && has_remembered_shady == TRUE) {
7248 rb_bug("page %p's has_remembered_shady should be false, but there are remembered shady objects. %s",
7249 (void *)page, obj ? rb_obj_info(obj) : "");
7250 }
7251
7252 if (0) {
7253 /* free_slots may not equal to free_objects */
7254 if (page->free_slots != free_objects) {
7255 rb_bug("page %p's free_slots should be %d, but %d", (void *)page, page->free_slots, free_objects);
7256 }
7257 }
7258 if (page->final_slots != zombie_objects) {
7259 rb_bug("page %p's final_slots should be %d, but %d", (void *)page, page->final_slots, zombie_objects);
7260 }
7261
7262 return remembered_old_objects;
7263}
7264
7265static int
7266gc_verify_heap_pages_(rb_objspace_t *objspace, struct ccan_list_head *head)
7267{
7268 int remembered_old_objects = 0;
7269 struct heap_page *page = 0;
7270
7271 ccan_list_for_each(head, page, page_node) {
7272 asan_unlock_freelist(page);
7273 struct free_region *region = page->free_region;
7274 while (region) {
7275 VALUE vp = (VALUE)region;
7276 rb_asan_unpoison_object(vp, false);
7277 if (BUILTIN_TYPE(vp) != T_NONE) {
7278 fprintf(stderr, "free region head expected to be T_NONE but was: %s\n", rb_obj_info(vp));
7279 }
7280 struct free_region *next = region->next;
7281 rb_asan_poison_object(vp);
7282 region = next;
7283 }
7284 asan_lock_freelist(page);
7285
7286 if (page->flags.has_remembered_objects == FALSE) {
7287 remembered_old_objects += gc_verify_heap_page(objspace, page, Qfalse);
7288 }
7289 }
7290
7291 return remembered_old_objects;
7292}
7293
7294static int
7295gc_verify_heap_pages(rb_objspace_t *objspace)
7296{
7297 int remembered_old_objects = 0;
7298 for (int i = 0; i < HEAP_COUNT; i++) {
7299 remembered_old_objects += gc_verify_heap_pages_(objspace, &((&heaps[i])->pages));
7300 }
7301 return remembered_old_objects;
7302}
7303
7304static void
7305verify_registered_addr(VALUE *slot, VALUE initial_value, void *owner_objspace, void *d)
7306{
7307 struct verify_internal_consistency_struct *data = d;
7308 VALUE v = *slot;
7309
7310 /* Conservative registration permits uninitialized data and pre-registration
7311 * values; only a store made after registration is a violation. */
7312 if (v == initial_value) return;
7313 if (SPECIAL_CONST_P(v)) return;
7314 if (!verify_pointer_in_any_heap_p((void *)v)) return;
7315
7316 bool live = false;
7317 asan_unpoisoning_object(v) {
7318 live = BUILTIN_TYPE(v) != T_NONE && BUILTIN_TYPE(v) != T_ZOMBIE;
7319 }
7320 if (!live) return;
7321
7322 rb_objspace_t *value_objspace = GET_HEAP_OBJSPACE(v);
7323 if (value_objspace == (rb_objspace_t *)owner_objspace) return;
7324 /* Join and orphan handling move a registration to the inheritor before the
7325 * source objspace merge; a global GC scans every registry while the zombie
7326 * exists, so this is a safe transient exemption. */
7327 if (rb_gc_vm_zombie_objspace_p(value_objspace)) return;
7328 if (value_objspace->flags.during_postmortem) return;
7329 if (MARKED_IN_BITMAP(GET_HEAP_SHAREABLE_BITS(v), v)) return;
7330 if (MARKED_IN_BITMAP(GET_HEAP_SHREF_BITS(v), v)) return;
7331 /* When multiple Ractors register one address, ownership by any registrant is
7332 * enough to root the value. */
7333 if (rb_gc_registered_addr_owned_by_registrant_p(slot, value_objspace)) return;
7334
7335 fprintf(stderr, "registered address %p changed since registration to an unshareable object owned by another Ractor: %s\n",
7336 (void *)slot, rb_obj_info(v));
7337 data->err_count++;
7338}
7339
7340static void
7341gc_verify_internal_consistency_(rb_objspace_t *objspace, bool world_stopped)
7342{
7343 struct verify_internal_consistency_struct data = {0};
7344
7345 data.objspace = objspace;
7346 data.world_stopped = world_stopped;
7347 gc_report(5, objspace, "gc_verify_internal_consistency: start\n");
7348
7349 /* check relations */
7350 for (size_t i = 0; i < rb_darray_size(objspace->heap_pages.sorted); i++) {
7351 struct heap_page *page = rb_darray_get(objspace->heap_pages.sorted, i);
7352 short slot_size = page->slot_size;
7353
7354 uintptr_t start = (uintptr_t)page->start;
7355 uintptr_t end = start + page->total_slots * slot_size;
7356
7357 verify_internal_consistency_i((void *)start, (void *)end, slot_size, &data);
7358 }
7359
7360 /* Check the calling Ractor's root scoping (only when verifying the current
7361 * objspace). Skipped during a global GC, which deliberately spans every Ractor's
7362 * roots and legitimately reaches foreign objects: containment does not apply. */
7363 if (!rb_gc_single_objspace_p() && objspace == rb_gc_get_objspace() &&
7364 !rb_gc_impl_during_global_gc_p(objspace)) {
7365 rb_objspace_reachable_objects_from_root(root_scope_check_i, &data);
7366 }
7367
7368 if (data.world_stopped && !global_objspace->during_absorb) {
7369 rb_gc_each_registered_addr(verify_registered_addr, &data);
7370 }
7371
7372 if (data.err_count != 0) {
7373#if RGENGC_CHECK_MODE >= 5
7374 objspace->rgengc.error_count = data.err_count;
7375 gc_marks_check(objspace, NULL, NULL);
7376 allrefs_dump(objspace);
7377#endif
7378 rb_bug("gc_verify_internal_consistency: found internal inconsistency.");
7379 }
7380
7381 /* check heap_page status */
7382 gc_verify_heap_pages(objspace);
7383
7384 /* check counters */
7385
7386 if (!is_lazy_sweeping(objspace) &&
7387 !finalizing &&
7388 !rb_gc_multi_ractor_p()) {
7389 if (objspace_live_slots(objspace) != data.live_object_count) {
7390 fprintf(stderr, "heap_pages_final_slots: %"PRIdSIZE", total_freed_objects: %"PRIdSIZE"\n",
7391 total_final_slots_count(objspace), total_freed_objects(objspace));
7392 rb_bug("inconsistent live slot number: expect %"PRIuSIZE", but %"PRIuSIZE".",
7393 objspace_live_slots(objspace), data.live_object_count);
7394 }
7395 }
7396
7397 if (!is_marking(objspace)) {
7398 if (objspace->rgengc.old_objects != data.old_object_count) {
7399 rb_bug("inconsistent old slot number: expect %"PRIuSIZE", but %"PRIuSIZE".",
7400 objspace->rgengc.old_objects, data.old_object_count);
7401 }
7402 if (objspace->rgengc.uncollectible_wb_unprotected_objects != data.remembered_shady_count) {
7403 rb_bug("inconsistent number of wb unprotected objects: expect %"PRIuSIZE", but %"PRIuSIZE".",
7404 objspace->rgengc.uncollectible_wb_unprotected_objects, data.remembered_shady_count);
7405 }
7406 }
7407
7408 if (!finalizing) {
7409 size_t list_count = 0;
7410
7411 {
7412 VALUE z = heap_pages_deferred_final;
7413 while (z) {
7414 list_count++;
7415 z = RZOMBIE(z)->next;
7416 }
7417 }
7418
7419 if (total_final_slots_count(objspace) != data.zombie_object_count ||
7420 total_final_slots_count(objspace) != list_count) {
7421
7422 rb_bug("inconsistent finalizing object count:\n"
7423 " expect %"PRIuSIZE"\n"
7424 " but %"PRIuSIZE" zombies\n"
7425 " heap_pages_deferred_final list has %"PRIuSIZE" items.",
7426 total_final_slots_count(objspace),
7427 data.zombie_object_count,
7428 list_count);
7429 }
7430 }
7431
7432 gc_report(5, objspace, "gc_verify_internal_consistency: OK\n");
7433}
7434
7435/* The `during_gc` macro expands a bare identifier to `objspace->flags.during_gc`, so a
7436 * foreign objspace's flag cannot be written directly; these helpers reach it through the
7437 * `objspace` argument. */
7438static inline unsigned int
7439gc_during_gc_get(const rb_objspace_t *objspace)
7440{
7441 return during_gc;
7442}
7443
7444static inline void
7445gc_during_gc_set(rb_objspace_t *objspace, unsigned int v)
7446{
7447 during_gc = v;
7448}
7449
7450/* Run the check with during_gc cleared in both the verified objspace and the current
7451 * Ractor's: rb_objspace_reachable_objects_from() decides on rb_gc_get_objspace(), and
7452 * under a global GC the driver verifies foreign objspaces, so the driver's during_gc
7453 * needs clearing too (a no-op when cur == objspace). */
7454static void
7455gc_verify_internal_consistency_body(rb_objspace_t *objspace, bool world_stopped)
7456{
7457 const unsigned int prev_during_gc = during_gc;
7458 during_gc = FALSE; // stop gc here
7459
7460 rb_objspace_t *const cur = rb_gc_get_objspace();
7461 const unsigned int prev_cur_during_gc = (cur != objspace) ? gc_during_gc_get(cur) : 0;
7462 if (cur != objspace) gc_during_gc_set(cur, FALSE);
7463 {
7464 gc_verify_internal_consistency_(objspace, world_stopped);
7465 }
7466 if (cur != objspace) gc_during_gc_set(cur, prev_cur_during_gc);
7467 during_gc = prev_during_gc;
7468}
7469
7470static void
7471gc_verify_internal_consistency(void *objspace_ptr)
7472{
7473 rb_objspace_t *objspace = objspace_ptr;
7474
7475 /* Called mid-GC, take neither the VM lock nor the barrier: waiting would join a
7476 * pending global barrier mid-collection (a GC must never take the VM lock) and let
7477 * the global GC sweep the heap this mark is walking. The barrier is unnecessary
7478 * anyway; the objspace is single-writer, this verify runs on its owner thread, and
7479 * the global driver that sets during_gc everywhere already holds both. */
7480 if (during_gc) {
7481 /* The world is stopped only when the global GC's driver runs this while holding
7482 * the barrier; a non-main Ractor's local GC does not stop other Ractors. */
7483 gc_verify_internal_consistency_body(objspace, rb_gc_impl_during_global_gc_p(objspace));
7484 return;
7485 }
7486
7487 unsigned int lev = RB_GC_VM_LOCK();
7488 {
7489 rb_gc_vm_barrier(); // stop other ractors
7490 gc_verify_internal_consistency_body(objspace, true); // holding the barrier, so walking every objspace is sound
7491 }
7492 RB_GC_VM_UNLOCK(lev);
7493}
7494
7495static void
7496heap_move_pooled_pages_to_free_pages(rb_heap_t *heap)
7497{
7498 if (heap->pooled_pages) {
7499 if (heap->free_pages) {
7500 struct heap_page *free_pages_tail = heap->free_pages;
7501 while (free_pages_tail->free_next) {
7502 free_pages_tail = free_pages_tail->free_next;
7503 }
7504 free_pages_tail->free_next = heap->pooled_pages;
7505 }
7506 else {
7507 heap->free_pages = heap->pooled_pages;
7508 }
7509
7510 heap->pooled_pages = NULL;
7511 }
7512}
7513
7514static int
7515gc_remember_unprotected(rb_objspace_t *objspace, VALUE obj)
7516{
7517 struct heap_page *page = GET_HEAP_PAGE(obj);
7518 bits_t *uncollectible_bits = &page->uncollectible_bits[0];
7519
7520 if (!MARKED_IN_BITMAP(uncollectible_bits, obj)) {
7521 page->flags.has_uncollectible_wb_unprotected_objects = TRUE;
7522 MARK_IN_BITMAP(uncollectible_bits, obj);
7523 /* Like RVALUE_PAGE_OLD_UNCOLLECTIBLE_SET, count it in the object's own objspace. */
7524 page->objspace->rgengc.uncollectible_wb_unprotected_objects++;
7525
7526#if RGENGC_PROFILE > 0
7527 objspace->profile.total_remembered_shady_object_count++;
7528#if RGENGC_PROFILE >= 2
7529 objspace->profile.remembered_shady_object_count_types[BUILTIN_TYPE(obj)]++;
7530#endif
7531#endif
7532 return TRUE;
7533 }
7534 else {
7535 return FALSE;
7536 }
7537}
7538
7539static inline void
7540gc_marks_wb_unprotected_objects_plane(rb_objspace_t *objspace, uintptr_t p, bits_t bits, short slot_size)
7541{
7542 if (bits) {
7543 do {
7544 if (bits & 1) {
7545 gc_report(2, objspace, "gc_marks_wb_unprotected_objects: marked shady: %s\n", rb_obj_info((VALUE)p));
7546 GC_ASSERT(RVALUE_WB_UNPROTECTED(objspace, (VALUE)p));
7547 GC_ASSERT(RVALUE_MARKED(objspace, (VALUE)p));
7548 gc_mark_children(objspace, (VALUE)p);
7549 }
7550 p += slot_size;
7551 bits >>= 1;
7552 } while (bits);
7553 }
7554}
7555
7556static void
7557gc_marks_wb_unprotected_objects(rb_objspace_t *objspace, rb_heap_t *heap)
7558{
7559 struct heap_page *page = 0;
7560
7561 ccan_list_for_each(&heap->pages, page, page_node) {
7562 bits_t *mark_bits = page->mark_bits;
7563 bits_t *wbun_bits = page->wb_unprotected_bits;
7564 uintptr_t p = page->start;
7565 short slot_size = page->slot_size;
7566 int total_slots = page->total_slots;
7567 int bitmap_plane_count = CEILDIV(total_slots, BITS_BITLENGTH);
7568 size_t j;
7569
7570 for (j=0; j<(size_t)bitmap_plane_count; j++) {
7571 bits_t bits = mark_bits[j] & wbun_bits[j];
7572 gc_marks_wb_unprotected_objects_plane(objspace, p, bits, slot_size);
7573 p += BITS_BITLENGTH * slot_size;
7574 }
7575 }
7576
7577 gc_mark_stacked_objects_all(objspace);
7578}
7579
7580void
7581rb_gc_impl_declare_weak_references(void *objspace_ptr, VALUE obj)
7582{
7584}
7585
7586bool
7587rb_gc_impl_handle_weak_references_alive_p(void *objspace_ptr, VALUE obj)
7588{
7589 rb_objspace_t *objspace = objspace_ptr;
7590
7591 /* A local GC cannot decide a foreign object's liveness, so treat it as live; its
7592 * owner or the global GC decides (a global GC's unified mark is exact). */
7593 if (gc_skip_foreign_object_p(objspace, obj)) return true;
7594
7595 bool marked = RVALUE_MARKED(objspace, obj);
7596
7597 if (marked) {
7598 rgengc_check_relation(objspace, obj);
7599 }
7600
7601 return marked;
7602}
7603
7604static void
7605gc_update_weak_references(rb_objspace_t *objspace)
7606{
7607 VALUE *obj_ptr;
7608 rb_darray_foreach(objspace->weak_references, i, obj_ptr) {
7609 gc_mark_set_parent(objspace, *obj_ptr);
7610 rb_gc_handle_weak_references(*obj_ptr);
7611 gc_mark_set_parent_invalid(objspace);
7612 }
7613
7614 size_t capa = rb_darray_capa(objspace->weak_references);
7615 size_t size = rb_darray_size(objspace->weak_references);
7616
7617 objspace->profile.weak_references_count = size;
7618
7619 rb_darray_clear(objspace->weak_references);
7620
7621 /* If the darray has capacity for more than four times the amount used, we
7622 * shrink it down to half of that capacity. */
7623 if (capa > size * 4) {
7624 rb_darray_resize_capa_without_gc(&objspace->weak_references, size * 2);
7625 }
7626}
7627
7628static void
7629gc_marks_finish(rb_objspace_t *objspace)
7630{
7631 /* finish incremental GC */
7632 if (is_incremental_marking(objspace)) {
7633 if (RGENGC_CHECK_MODE && is_mark_stack_empty(&objspace->mark_stack) == 0) {
7634 rb_bug("gc_marks_finish: mark stack is not empty (%"PRIdSIZE").",
7635 mark_stack_size(&objspace->mark_stack));
7636 }
7637
7638 mark_roots(objspace, NULL);
7639 while (gc_mark_stacked_objects_incremental(objspace, INT_MAX) == false);
7640
7641#if RGENGC_CHECK_MODE >= 2
7642 if (gc_verify_heap_pages(objspace) != 0) {
7643 rb_bug("gc_marks_finish (incremental): there are remembered old objects.");
7644 }
7645#endif
7646
7647 objspace->flags.during_incremental_marking = FALSE;
7648 /* check children of all marked wb-unprotected objects */
7649 for (int i = 0; i < HEAP_COUNT; i++) {
7650 gc_marks_wb_unprotected_objects(objspace, &heaps[i]);
7651 }
7652 }
7653
7654 /* Pin the shareable objects and shrefs ordinary marking missed: a local GC must free
7655 * neither (another objspace may hold them). Running after the full walk makes the
7656 * pin count a retention metric: an upper bound on the garbage only a global GC can
7657 * reclaim. A global GC's exact mark does not pin. (The allrefs comparison of
7658 * RGENGC_CHECK_MODE >= 4 does not model these pins; it reports false positives.)
7659 *
7660 * Running it here rather than with the other roots is also what lets an incremental
7661 * mark run while other objspaces exist. The write barrier bails out on a
7662 * cross-objspace edge, so a store made between two mark steps leaves nothing behind
7663 * but a shareable or shref bit; scanning those bitmaps after the last step picks up
7664 * every bit set during the cycle, which a scan at gc_marks_start would miss. */
7665 objspace->last_cycle_pinned = 0;
7666 if (!rb_gc_single_objspace_p() && !objspace->flags.during_global_gc) {
7667 objspace->last_cycle_pinned = 1;
7668 gc_mark_set_parent_raw(objspace, Qundef, false);
7669 for (int i = 0; i < HEAP_COUNT; i++) {
7670 pinned_roots_mark(objspace, &heaps[i]);
7671 }
7672 /* And everything they keep alive. */
7673 gc_mark_stacked_objects_all(objspace);
7674 }
7675
7676 gc_update_weak_references(objspace);
7677
7678#if RGENGC_CHECK_MODE >= 4
7679 during_gc = FALSE;
7680 gc_marks_check(objspace, gc_check_after_marks_i, "after_marks");
7681 during_gc = TRUE;
7682#endif
7683
7684 {
7685 /* Only this objspace's own Ractor allocates from it. The main objspace
7686 * keeps the VM-wide count it has used since before per-Ractor GC. */
7687 const unsigned long ractor_cnt = objspace == global_objspace->main_objspace
7688 ? rb_gc_vm_ractor_count() : 1;
7689 const unsigned long r_mul = ractor_cnt > 8 ? 8 : ractor_cnt; // upto 8
7690
7691 size_t total_slots = objspace_available_slots(objspace);
7692 size_t sweep_slots = total_slots - objspace->marked_slots; /* will be swept slots */
7693 size_t max_free_slots = (size_t)(total_slots * gc_params.heap_free_slots_max_ratio);
7694 size_t min_free_slots = (size_t)(total_slots * gc_params.heap_free_slots_min_ratio);
7695 if (min_free_slots < gc_params.heap_free_slots * r_mul) {
7696 min_free_slots = gc_params.heap_free_slots * r_mul;
7697 }
7698
7699 int full_marking = is_full_marking(objspace);
7700
7701 GC_ASSERT(objspace_available_slots(objspace) >= objspace->marked_slots);
7702
7703 /* Setup freeable slots. */
7704 size_t total_init_slots = 0;
7705 for (int i = 0; i < HEAP_COUNT; i++) {
7706 total_init_slots += (objspace_heap_init_bytes(objspace) / heaps[i].slot_size) * r_mul;
7707 }
7708
7709 if (max_free_slots < total_init_slots) {
7710 max_free_slots = total_init_slots;
7711 }
7712
7713 /* Approximate freeable pages using the average slots-per-pages across all heaps */
7714 if (sweep_slots > max_free_slots) {
7715 size_t excess_slots = sweep_slots - max_free_slots;
7716 size_t total_heap_pages = heap_eden_total_pages(objspace);
7717 heap_pages_freeable_pages = total_heap_pages > 0
7718 ? excess_slots * total_heap_pages / total_slots
7719 : 0;
7720 }
7721 else {
7722 heap_pages_freeable_pages = 0;
7723 }
7724
7725 if (objspace->heap_pages.allocatable_bytes == 0 && sweep_slots < min_free_slots) {
7726 if (!full_marking && sweep_slots < min_free_slots * 7 / 8) {
7727 if (objspace->profile.count - objspace->rgengc.last_major_gc < RVALUE_OLD_AGE) {
7728 full_marking = TRUE;
7729 }
7730 else {
7731 gc_report(1, objspace, "gc_marks_finish: next is full GC!!)\n");
7732 gc_needs_major_flags |= GPR_FLAG_MAJOR_BY_NOFREE;
7733 }
7734 }
7735
7736 if (full_marking) {
7737 heap_allocatable_bytes_expand(objspace, NULL, sweep_slots, total_slots, heaps[0].slot_size);
7738 }
7739 }
7740
7741 if (full_marking) {
7742 /* See the comment about RUBY_GC_HEAP_OLDOBJECT_LIMIT_FACTOR */
7743 const double r = gc_params.oldobject_limit_factor;
7744 objspace->rgengc.uncollectible_wb_unprotected_objects_limit = MAX(
7745 (size_t)(objspace->rgengc.uncollectible_wb_unprotected_objects * r),
7746 (size_t)(objspace->rgengc.old_objects * gc_params.uncollectible_wb_unprotected_objects_limit_ratio)
7747 );
7748 objspace->rgengc.old_objects_limit = (size_t)(objspace->rgengc.old_objects * r);
7749 }
7750
7751 if (objspace->rgengc.uncollectible_wb_unprotected_objects > objspace->rgengc.uncollectible_wb_unprotected_objects_limit) {
7752 gc_needs_major_flags |= GPR_FLAG_MAJOR_BY_SHADY;
7753 }
7754 if (objspace->rgengc.old_objects > objspace->rgengc.old_objects_limit) {
7755 gc_needs_major_flags |= GPR_FLAG_MAJOR_BY_OLDGEN;
7756 }
7757
7758 gc_report(1, objspace, "gc_marks_finish (marks %"PRIdSIZE" objects, "
7759 "old %"PRIdSIZE" objects, total %"PRIdSIZE" slots, "
7760 "sweep %"PRIdSIZE" slots, allocatable %"PRIdSIZE" bytes, next GC: %s)\n",
7761 objspace->marked_slots, objspace->rgengc.old_objects, objspace_available_slots(objspace), sweep_slots, objspace->heap_pages.allocatable_bytes,
7762 gc_needs_major_flags ? "major" : "minor");
7763 }
7764
7765 // TODO: refactor so we don't need to call this
7766 rb_ractor_finish_marking(is_full_marking(objspace));
7767
7769}
7770
7771static bool
7772gc_compact_heap_cursors_met_p(rb_heap_t *heap)
7773{
7774 return heap->sweeping_page == heap->compact_cursor;
7775}
7776
7777
7778static rb_heap_t *
7779gc_compact_destination_pool(rb_objspace_t *objspace, rb_heap_t *src_pool, VALUE obj)
7780{
7781 size_t obj_size = rb_gc_obj_optimal_size(obj);
7782 if (obj_size == 0) {
7783 return src_pool;
7784 }
7785
7786 GC_ASSERT(rb_gc_impl_size_allocatable_p(obj_size));
7787
7788 size_t idx = heap_idx_for_size(obj_size);
7789
7790 return &heaps[idx];
7791}
7792
7793static bool
7794gc_compact_move(rb_objspace_t *objspace, rb_heap_t *heap, VALUE src)
7795{
7796 GC_ASSERT(BUILTIN_TYPE(src) != T_MOVED);
7797 GC_ASSERT(gc_is_moveable_obj(objspace, src));
7798
7799 rb_heap_t *dest_pool = gc_compact_destination_pool(objspace, heap, src);
7800 if (gc_compact_heap_cursors_met_p(dest_pool)) {
7801 return dest_pool != heap;
7802 }
7803
7804 while (!try_move(objspace, dest_pool, dest_pool->free_pages, src)) {
7805 struct gc_sweep_context ctx = {
7806 .page = dest_pool->sweeping_page,
7807 .final_slots = 0,
7808 .freed_slots = 0,
7809 .empty_slots = 0,
7810 };
7811
7812 /* The page of src could be partially compacted, so it may contain
7813 * T_MOVED. Sweeping a page may read objects on this page, so we
7814 * need to lock the page. */
7815 lock_page_body(objspace, GET_PAGE_BODY(src));
7816 gc_sweep_page(objspace, dest_pool, &ctx);
7817 unlock_page_body(objspace, GET_PAGE_BODY(src));
7818
7819 if (dest_pool->sweeping_page->free_slots > 0) {
7820 heap_add_freepage(dest_pool, dest_pool->sweeping_page);
7821 }
7822
7823 dest_pool->sweeping_page = ccan_list_next(&dest_pool->pages, dest_pool->sweeping_page, page_node);
7824 if (gc_compact_heap_cursors_met_p(dest_pool)) {
7825 return dest_pool != heap;
7826 }
7827 }
7828
7829 return true;
7830}
7831
7832static bool
7833gc_compact_plane(rb_objspace_t *objspace, rb_heap_t *heap, uintptr_t p, bits_t bitset, struct heap_page *page)
7834{
7835 short slot_size = page->slot_size;
7836
7837 do {
7838 VALUE vp = (VALUE)p;
7839 GC_ASSERT(vp % sizeof(VALUE) == 0);
7840
7841 if (bitset & 1) {
7842 objspace->rcompactor.considered_count_table[BUILTIN_TYPE(vp)]++;
7843
7844 if (gc_is_moveable_obj(objspace, vp)) {
7845 if (!gc_compact_move(objspace, heap, vp)) {
7846 //the cursors met. bubble up
7847 return false;
7848 }
7849 }
7850 }
7851 p += slot_size;
7852 bitset >>= 1;
7853 } while (bitset);
7854
7855 return true;
7856}
7857
7858// Iterate up all the objects in page, moving them to where they want to go
7859static bool
7860gc_compact_page(rb_objspace_t *objspace, rb_heap_t *heap, struct heap_page *page)
7861{
7862 GC_ASSERT(page == heap->compact_cursor);
7863
7864 bits_t *mark_bits, *pin_bits;
7865 bits_t bitset;
7866 uintptr_t p = page->start;
7867 short slot_size = page->slot_size;
7868 int total_slots = page->total_slots;
7869 int bitmap_plane_count = CEILDIV(total_slots, BITS_BITLENGTH);
7870
7871 mark_bits = page->mark_bits;
7872 pin_bits = page->pinned_bits;
7873
7874 for (int j = 0; j < bitmap_plane_count; j++) {
7875 // objects that can be moved are marked and not pinned
7876 bitset = (mark_bits[j] & ~pin_bits[j]);
7877 if (bitset) {
7878 if (!gc_compact_plane(objspace, heap, (uintptr_t)p, bitset, page))
7879 return false;
7880 }
7881 p += BITS_BITLENGTH * slot_size;
7882 }
7883
7884 return true;
7885}
7886
7887static bool
7888gc_compact_all_compacted_p(rb_objspace_t *objspace)
7889{
7890 for (int i = 0; i < HEAP_COUNT; i++) {
7891 rb_heap_t *heap = &heaps[i];
7892
7893 if (heap->total_pages > 0 &&
7894 !gc_compact_heap_cursors_met_p(heap)) {
7895 return false;
7896 }
7897 }
7898
7899 return true;
7900}
7901
7902/* Compaction's move phase: relocate this objspace's movable objects and leave T_MOVED
7903 * forwarding behind without updating references yet. A global GC calls this for every
7904 * objspace before updating any of them (two phases), so a cross-objspace reference to a
7905 * moved object is rewritten exactly once, after all forwarding exists. */
7906static void
7907gc_compact_relocate(rb_objspace_t *objspace)
7908{
7909 gc_compact_start(objspace);
7910
7911 while (!gc_compact_all_compacted_p(objspace)) {
7912 for (int i = 0; i < HEAP_COUNT; i++) {
7913 rb_heap_t *heap = &heaps[i];
7914
7915 if (gc_compact_heap_cursors_met_p(heap)) {
7916 continue;
7917 }
7918
7919 struct heap_page *start_page = heap->compact_cursor;
7920
7921 if (!gc_compact_page(objspace, heap, start_page)) {
7922 lock_page_body(objspace, start_page->body);
7923
7924 continue;
7925 }
7926
7927 // If we get here, we've finished moving all objects on the compact_cursor page
7928 // So we can lock it and move the cursor on to the next one.
7929 lock_page_body(objspace, start_page->body);
7930 heap->compact_cursor = ccan_list_prev(&heap->pages, heap->compact_cursor, page_node);
7931 }
7932 }
7933}
7934
7935static void
7936gc_sweep_compact(rb_objspace_t *objspace)
7937{
7938 gc_compact_relocate(objspace);
7939 /* A compacting global GC defers the finish (reference update) to the second phase,
7940 * after every objspace has been relocated. */
7941 if (!global_objspace->global_gc.compacting) {
7942 gc_compact_finish(objspace);
7943 }
7944}
7945
7946static void
7947gc_marks_rest(rb_objspace_t *objspace)
7948{
7949 gc_report(1, objspace, "gc_marks_rest\n");
7950
7951 for (int i = 0; i < HEAP_COUNT; i++) {
7952 (&heaps[i])->pooled_pages = NULL;
7953 }
7954
7955 if (is_incremental_marking(objspace)) {
7956 while (gc_mark_stacked_objects_incremental(objspace, INT_MAX) == FALSE);
7957 }
7958 else {
7959 gc_mark_stacked_objects_all(objspace);
7960 }
7961
7962 gc_marks_finish(objspace);
7963}
7964
7965static bool
7966gc_marks_step(rb_objspace_t *objspace, size_t slots)
7967{
7968 bool marking_finished = false;
7969
7970 GC_ASSERT(is_marking(objspace));
7971 if (gc_mark_stacked_objects_incremental(objspace, slots)) {
7972 gc_marks_finish(objspace);
7973
7974 marking_finished = true;
7975 }
7976
7977 return marking_finished;
7978}
7979
7980static bool
7981gc_marks_continue(rb_objspace_t *objspace, rb_heap_t *heap)
7982{
7983 GC_ASSERT(dont_gc_val() == FALSE || objspace->profile.latest_gc_info & GPR_FLAG_METHOD);
7984 bool marking_finished = true;
7985
7986 gc_marking_enter(objspace);
7987
7988 if (heap->free_pages) {
7989 gc_report(2, objspace, "gc_marks_continue: has pooled pages");
7990
7991 marking_finished = gc_marks_step(objspace, objspace->rincgc.step_slots);
7992 }
7993 else {
7994 gc_report(2, objspace, "gc_marks_continue: no more pooled pages (stack depth: %"PRIdSIZE").\n",
7995 mark_stack_size(&objspace->mark_stack));
7996 heap->force_incremental_marking_finish_count++;
7997 gc_marks_rest(objspace);
7998 }
7999
8000 gc_marking_exit(objspace);
8001
8002 return marking_finished;
8003}
8004
8005/* Mark the following as roots of this objspace.
8006 * - Every shareable object: another objspace may hold the only reference, invisible to a
8007 * local GC. Marking them rather than skipping them in the sweep preserves the
8008 * generational invariants (a pinned object ages and gets promoted like any live one).
8009 * Only a global GC decides that a shareable object is dead.
8010 * - Every shref (an unshareable object referenced from a shareable one): the referring
8011 * shareable object can live in another objspace or in an in-flight message queue. The
8012 * write barrier maintains them.
8013 * Skipped while the VM has a single Ractor: a local GC is then a whole-world GC and
8014 * shareable objects may die normally. */
8015static void
8016pinned_roots_mark(rb_objspace_t *objspace, rb_heap_t *heap)
8017{
8018 struct heap_page *page = NULL;
8019
8020 /* Runs before mark_roots, so rgengc_check_relation sees a valid (absent) parent rather
8021 * than the poison left by the previous GC. */
8022 gc_mark_set_parent_raw(objspace, Qundef, false);
8023
8024 /* A local GC never frees or traverses a shareable object, and keeps its unshareable
8025 * children alive through their shref bits, so:
8026 * - a shareable object only gets its mark bit set (like an old object), which keeps
8027 * the sweep off it, and is not traversed;
8028 * - a shref is marked and traversed, like a remembered old->young target: without
8029 * that, the referring shareable object is never walked and it would look
8030 * unreachable.
8031 * Objects can become shareable between GCs, so this pass scans the bitmaps in every
8032 * mark (gc_marks_finish) instead of maintaining a pin set across the sweep. */
8033 ccan_list_for_each(&heap->pages, page, page_node) {
8034 if (!(page->flags.has_shareable_objects | page->flags.has_shref_objects)) continue;
8035
8036 uintptr_t p = page->start;
8037 short slot_size = page->slot_size;
8038 int total_slots = page->total_slots;
8039 int bitmap_plane_count = CEILDIV(total_slots, BITS_BITLENGTH);
8040
8041 for (int j = 0; j < bitmap_plane_count; j++) {
8042 bits_t sr_bits = page->shref_bits[j];
8043 /* Only the pins ordinary marking left unmarked need work here: an already
8044 * marked object (reached by traversal, or pre-marked because it is old) is a
8045 * no-op in gc_mark_set, so skip visiting it. */
8046 bits_t bitset = (page->shareable_bits[j] | sr_bits) & ~page->mark_bits[j];
8047 uintptr_t pp = p;
8048 while (bitset) {
8049 if (bitset & 1) {
8050 VALUE obj = (VALUE)pp;
8051 asan_unpoisoning_object(obj) {
8052 switch (BUILTIN_TYPE(obj)) {
8053 case T_NONE:
8054 case T_ZOMBIE:
8055 case T_MOVED:
8056 /* A dead slot (a zombie awaiting its finalizer) is not a root. */
8057 break;
8058 default:
8059 gc_report(2, objspace, "pinned_roots_mark: mark %s\n", rb_obj_info(obj));
8060 if (sr_bits & 1) {
8061 gc_mark(objspace, obj); /* shref: root + traverse */
8062 }
8063 else if (gc_mark_set(objspace, obj)) {
8064 gc_aging(objspace, obj); /* shareable: mark, no traverse */
8065 /* Pin as well when compaction runs alongside: if a shareable
8066 * object moved, the C-struct slots of other Ractors (a
8067 * port in sync, say) are not updated and go stale. */
8068 gc_pin(objspace, obj);
8069 }
8070 break;
8071 }
8072 }
8073 }
8074 pp += slot_size;
8075 bitset >>= 1;
8076 sr_bits >>= 1;
8077 }
8078 p += BITS_BITLENGTH * slot_size;
8079 }
8080 }
8081}
8082
8083static void
8084gc_marks_start(rb_objspace_t *objspace, int full_mark)
8085{
8086 /* start marking */
8087 gc_report(1, objspace, "gc_marks_start: (%s)\n", full_mark ? "full" : "minor");
8088 gc_mode_transition(objspace, gc_mode_marking);
8089
8090 if (full_mark) {
8091 size_t incremental_marking_steps = (objspace->rincgc.pooled_slots / INCREMENTAL_MARK_STEP_ALLOCATIONS) + 1;
8092 objspace->rincgc.step_slots = (objspace->marked_slots * 2) / incremental_marking_steps;
8093
8094 if (0) fprintf(stderr, "objspace->marked_slots: %"PRIdSIZE", "
8095 "objspace->rincgc.pooled_page_num: %"PRIdSIZE", "
8096 "objspace->rincgc.step_slots: %"PRIdSIZE", \n",
8097 objspace->marked_slots, objspace->rincgc.pooled_slots, objspace->rincgc.step_slots);
8098 objspace->flags.during_minor_gc = FALSE;
8099 if (ruby_enable_autocompact && rb_gc_single_objspace_p()) {
8100 objspace->flags.during_compacting |= TRUE;
8101 }
8102 objspace->profile.major_gc_count++;
8103 objspace->rgengc.uncollectible_wb_unprotected_objects = 0;
8104 objspace->rgengc.old_objects = 0;
8105 objspace->rgengc.last_major_gc = objspace->profile.count;
8106 objspace->marked_slots = 0;
8107
8108 for (int i = 0; i < HEAP_COUNT; i++) {
8109 rb_heap_t *heap = &heaps[i];
8110 gc_bitmaps_clear(objspace, heap, false);
8111 heap_move_pooled_pages_to_free_pages(heap);
8112
8113 if (objspace->flags.during_compacting) {
8114 struct heap_page *page = NULL;
8115
8116 ccan_list_for_each(&heap->pages, page, page_node) {
8117 page->pinned_slots = 0;
8118 }
8119 }
8120 }
8121 }
8122 else {
8123 objspace->flags.during_minor_gc = TRUE;
8124 objspace->marked_slots =
8125 objspace->rgengc.old_objects + objspace->rgengc.uncollectible_wb_unprotected_objects; /* uncollectible objects are marked already */
8126 objspace->profile.minor_gc_count++;
8127
8128 for (int i = 0; i < HEAP_COUNT; i++) {
8129 rgengc_rememberset_mark(objspace, &heaps[i]);
8130 }
8131 }
8132
8133 mark_roots(objspace, NULL);
8134
8135 gc_report(1, objspace, "gc_marks_start: (%s) end, stack in %"PRIdSIZE"\n",
8136 full_mark ? "full" : "minor", mark_stack_size(&objspace->mark_stack));
8137}
8138
8139static bool
8140gc_marks(rb_objspace_t *objspace, int full_mark)
8141{
8142 gc_marking_enter(objspace);
8143
8144 bool marking_finished = false;
8145
8146 /* setup marking */
8147
8148 gc_marks_start(objspace, full_mark);
8149 if (!is_incremental_marking(objspace)) {
8150 gc_marks_rest(objspace);
8151 marking_finished = true;
8152 }
8153
8154#if RGENGC_PROFILE > 0
8155 if (gc_prof_record(objspace)) {
8156 gc_profile_record *record = gc_prof_record(objspace);
8157 record->old_objects = objspace->rgengc.old_objects;
8158 }
8159#endif
8160
8161 gc_marking_exit(objspace);
8162
8163 return marking_finished;
8164}
8165
8166/* RGENGC */
8167
8168static void
8169gc_report_body(int level, rb_objspace_t *objspace, const char *fmt, ...)
8170{
8171 if (level <= RGENGC_DEBUG) {
8172 char buf[1024];
8173 FILE *out = stderr;
8174 va_list args;
8175 const char *status = " ";
8176
8177 if (during_gc) {
8178 status = is_full_marking(objspace) ? "+" : "-";
8179 }
8180 else {
8181 if (is_lazy_sweeping(objspace)) {
8182 status = "S";
8183 }
8184 if (is_incremental_marking(objspace)) {
8185 status = "M";
8186 }
8187 }
8188
8189 va_start(args, fmt);
8190 vsnprintf(buf, 1024, fmt, args);
8191 va_end(args);
8192
8193 fprintf(out, "%s|", status);
8194 fputs(buf, out);
8195 }
8196}
8197
8198/* bit operations */
8199
8200static void
8201rgengc_remembersetbits_set(rb_objspace_t *objspace, VALUE obj)
8202{
8203 struct heap_page *page = GET_HEAP_PAGE(obj);
8204 bits_t *bits = &page->remembered_bits[0];
8205
8206 /* remembered_bits writers are always serialized: the write barrier only remembers a
8207 * local a (under its Ractor's GVL) and a global GC writes from the driver alone.
8208 * Set the bit before the page flag so a page pending re-scan stays in
8209 * rememberset_mark. */
8210 _MARK_IN_BITMAP(bits, page, obj);
8211 page->flags.has_remembered_objects = TRUE;
8212}
8213
8214/* wb, etc */
8215
8216/* return FALSE if already remembered */
8217static void
8218rgengc_remember(rb_objspace_t *objspace, VALUE obj)
8219{
8220 gc_report(6, objspace, "rgengc_remember: %s %s\n", rb_obj_info(obj),
8221 RVALUE_REMEMBERED(objspace, obj) ? "was already remembered" : "is remembered now");
8222
8223 check_rvalue_consistency(objspace, obj);
8224
8225 if (RGENGC_CHECK_MODE) {
8226 if (RVALUE_WB_UNPROTECTED(objspace, obj)) rb_bug("rgengc_remember: %s is not wb protected.", rb_obj_info(obj));
8227 }
8228
8229#if RGENGC_PROFILE > 0
8230 if (!RVALUE_REMEMBERED(objspace, obj)) {
8231 if (RVALUE_WB_UNPROTECTED(objspace, obj) == 0) {
8232 objspace->profile.total_remembered_normal_object_count++;
8233#if RGENGC_PROFILE >= 2
8234 objspace->profile.remembered_normal_object_count_types[BUILTIN_TYPE(obj)]++;
8235#endif
8236 }
8237 }
8238#endif /* RGENGC_PROFILE > 0 */
8239
8240 rgengc_remembersetbits_set(objspace, obj);
8241}
8242
8243#ifndef PROFILE_REMEMBERSET_MARK
8244#define PROFILE_REMEMBERSET_MARK 0
8245#endif
8246
8247static inline void
8248rgengc_rememberset_mark_plane(rb_objspace_t *objspace, uintptr_t p, bits_t bitset, short slot_size)
8249{
8250 if (bitset) {
8251 do {
8252 if (bitset & 1) {
8253 VALUE obj = (VALUE)p;
8254 gc_report(2, objspace, "rgengc_rememberset_mark: mark %s\n", rb_obj_info(obj));
8255 GC_ASSERT(RVALUE_UNCOLLECTIBLE(objspace, obj));
8256 GC_ASSERT(RVALUE_OLD_P(objspace, obj) || RVALUE_WB_UNPROTECTED(objspace, obj));
8257
8258 gc_mark_children(objspace, obj);
8259
8261 rb_darray_append_without_gc(&objspace->weak_references, obj);
8262 }
8263 }
8264 p += slot_size;
8265 bitset >>= 1;
8266 } while (bitset);
8267 }
8268}
8269
8270static void
8271rgengc_rememberset_mark(rb_objspace_t *objspace, rb_heap_t *heap)
8272{
8273 size_t j;
8274 struct heap_page *page = 0;
8275#if PROFILE_REMEMBERSET_MARK
8276 int has_old = 0, has_shady = 0, has_both = 0, skip = 0;
8277#endif
8278 gc_report(1, objspace, "rgengc_rememberset_mark: start\n");
8279
8280 ccan_list_for_each(&heap->pages, page, page_node) {
8281 if (page->flags.has_remembered_objects | page->flags.has_uncollectible_wb_unprotected_objects) {
8282 uintptr_t p = page->start;
8283 short slot_size = page->slot_size;
8284 int total_slots = page->total_slots;
8285 int bitmap_plane_count = CEILDIV(total_slots, BITS_BITLENGTH);
8286 bits_t bitset, bits[HEAP_PAGE_BITMAP_LIMIT];
8287 bits_t *remembered_bits = page->remembered_bits;
8288 bits_t *uncollectible_bits = page->uncollectible_bits;
8289 bits_t *wb_unprotected_bits = page->wb_unprotected_bits;
8290#if PROFILE_REMEMBERSET_MARK
8291 if (page->flags.has_remembered_objects && page->flags.has_uncollectible_wb_unprotected_objects) has_both++;
8292 else if (page->flags.has_remembered_objects) has_old++;
8293 else if (page->flags.has_uncollectible_wb_unprotected_objects) has_shady++;
8294#endif
8295 /* Clear has_remembered_objects before draining the bits. A concurrent
8296 * lock-free write barrier (another Ractor remembering a shareable object on
8297 * this page) sets the bit first and the flag second, so clearing the flag first
8298 * keeps the page scheduled for re-scan even if that set interleaves. The
8299 * per-word drain is an atomic read-and-clear, so an interleaved set is not lost
8300 * (it lands in the zeroed word). */
8301 page->flags.has_remembered_objects = FALSE;
8302 for (j=0; j < (size_t)bitmap_plane_count; j++) {
8303 bits[j] = RUBY_ATOMIC_SIZE_EXCHANGE(*(volatile size_t *)&remembered_bits[j], 0)
8304 | (uncollectible_bits[j] & wb_unprotected_bits[j]);
8305 }
8306
8307 for (j=0; j < (size_t)bitmap_plane_count; j++) {
8308 bitset = bits[j];
8309 rgengc_rememberset_mark_plane(objspace, p, bitset, slot_size);
8310 p += BITS_BITLENGTH * slot_size;
8311 }
8312 }
8313#if PROFILE_REMEMBERSET_MARK
8314 else {
8315 skip++;
8316 }
8317#endif
8318 }
8319
8320#if PROFILE_REMEMBERSET_MARK
8321 fprintf(stderr, "%d\t%d\t%d\t%d\n", has_both, has_old, has_shady, skip);
8322#endif
8323 gc_report(1, objspace, "rgengc_rememberset_mark: finished\n");
8324}
8325
8326static void
8327gc_bitmaps_clear(rb_objspace_t *objspace, rb_heap_t *heap, bool clear_shref)
8328{
8329 struct heap_page *page = 0;
8330
8331 ccan_list_for_each(&heap->pages, page, page_node) {
8332 memset(&page->mark_bits[0], 0, HEAP_PAGE_BITMAP_SIZE);
8333 memset(&page->uncollectible_bits[0], 0, HEAP_PAGE_BITMAP_SIZE);
8334 memset(&page->marking_bits[0], 0, HEAP_PAGE_BITMAP_SIZE);
8335 /* A plain memset can lose a concurrent remember, but only a shareable object can
8336 * be remembered from another Ractor's thread, and pinned_roots_mark re-marks
8337 * those every local cycle, and this clear precedes a major that re-scans all. */
8338 memset(&page->remembered_bits[0], 0, HEAP_PAGE_BITMAP_SIZE);
8339 memset(&page->pinned_bits[0], 0, HEAP_PAGE_BITMAP_SIZE);
8340 page->flags.has_uncollectible_wb_unprotected_objects = FALSE;
8341 page->flags.has_remembered_objects = FALSE;
8342 /* A shref is a local GC's root, so only a stop-the-world global GC may clear them:
8343 * its unified mark re-derives them from every shareable -> unshareable edge. */
8344 if (clear_shref) {
8345 memset(&page->shref_bits[0], 0, HEAP_PAGE_BITMAP_SIZE);
8346 page->flags.has_shref_objects = FALSE;
8347 }
8348 }
8349}
8350
8351/* RGENGC: APIs */
8352
8353NOINLINE(static void gc_writebarrier_generational(VALUE a, VALUE b, rb_objspace_t *objspace));
8354
8355/* Precondition: `a` and `b` live in `objspace`. */
8356static void
8357gc_writebarrier_generational(VALUE a, VALUE b, rb_objspace_t *objspace)
8358{
8359 if (RGENGC_CHECK_MODE) {
8360 if (!RVALUE_OLD_P(objspace, a)) rb_bug("gc_writebarrier_generational: %s is not an old object.", rb_obj_info(a));
8361 if ( RVALUE_OLD_P(objspace, b)) rb_bug("gc_writebarrier_generational: %s is an old object.", rb_obj_info(b));
8362 if (is_incremental_marking(objspace)) rb_bug("gc_writebarrier_generational: called while incremental marking: %s -> %s", rb_obj_info(a), rb_obj_info(b));
8363 }
8364
8365 /* Mark and remember a (the default behaviour).
8366 * No lock: setting a remembered bit is atomic (rgengc_remembersetbits_set), and that is
8367 * the only place a concurrent local GC or another Ractor's write barrier can race. */
8368 if (!RVALUE_REMEMBERED(objspace, a)) {
8369 rgengc_remember(objspace, a);
8370
8371 gc_report(1, objspace, "gc_writebarrier_generational: %s (remembered) -> %s\n", rb_obj_info(a), rb_obj_info(b));
8372 }
8373
8374 check_rvalue_consistency(objspace, a);
8375 check_rvalue_consistency(objspace, b);
8376}
8377
8378static void
8379gc_mark_from(rb_objspace_t *objspace, VALUE obj, VALUE parent)
8380{
8381 gc_mark_set_parent(objspace, parent);
8382 rgengc_check_relation(objspace, obj);
8383 if (gc_mark_set(objspace, obj) != FALSE) {
8384 gc_aging(objspace, obj);
8385 gc_grey(objspace, obj);
8386 }
8387 gc_mark_set_parent_invalid(objspace);
8388}
8389
8390NOINLINE(static void gc_writebarrier_incremental(VALUE a, VALUE b, rb_objspace_t *objspace));
8391
8392/* Precondition: `a` and `b` live in `objspace`. */
8393static void
8394gc_writebarrier_incremental(VALUE a, VALUE b, rb_objspace_t *objspace)
8395{
8396 gc_report(2, objspace, "gc_writebarrier_incremental: [LG] %p -> %s\n", (void *)a, rb_obj_info(b));
8397
8398 if (RVALUE_BLACK_P(objspace, a)) {
8399 if (RVALUE_WHITE_P(objspace, b)) {
8400 if (!RVALUE_WB_UNPROTECTED(objspace, a)) {
8401 gc_report(2, objspace, "gc_writebarrier_incremental: [IN] %p -> %s\n", (void *)a, rb_obj_info(b));
8402 gc_mark_from(objspace, b, a);
8403 }
8404 }
8405 else if (RVALUE_OLD_P(objspace, a) && !RVALUE_OLD_P(objspace, b)) {
8406 rgengc_remember(objspace, a);
8407 }
8408
8409 if (RB_UNLIKELY(objspace->flags.during_compacting)) {
8410 MARK_IN_BITMAP(GET_HEAP_PINNED_BITS(b), b);
8411 }
8412 }
8413}
8414
8415void
8416rb_gc_impl_writebarrier(void *objspace_ptr, VALUE a, VALUE b)
8417{
8418 rb_objspace_t *objspace = objspace_ptr;
8419
8420#if RGENGC_CHECK_MODE
8421 if (SPECIAL_CONST_P(a)) rb_bug("rb_gc_writebarrier: a is special const: %"PRIxVALUE, a);
8422 if (SPECIAL_CONST_P(b)) rb_bug("rb_gc_writebarrier: b is special const: %"PRIxVALUE, b);
8423#else
8426#endif
8427
8428 GC_ASSERT(!during_gc);
8429 GC_ASSERT(RB_BUILTIN_TYPE(a) != T_NONE);
8430 GC_ASSERT(RB_BUILTIN_TYPE(a) != T_MOVED);
8431 GC_ASSERT(RB_BUILTIN_TYPE(a) != T_ZOMBIE);
8432
8433 /* A shareable object now references an unshareable one: record b as a shref so its
8434 * owner's local GC roots it (the parent may live in another objspace, untraversed
8435 * there). Only b's owner stores this, on its own page: a plain store suffices. */
8436 if (RB_UNLIKELY(RB_FL_TEST_RAW(a, RUBY_FL_SHAREABLE)) &&
8438 struct heap_page *bpage = GET_HEAP_PAGE(b);
8439 if (!_MARKED_IN_BITMAP(bpage->shref_bits, bpage, b)) {
8440 _MARK_IN_BITMAP(bpage->shref_bits, bpage, b);
8441 bpage->flags.has_shref_objects = TRUE;
8442 }
8443 }
8444
8445 if (!is_incremental_marking(objspace)) {
8446 /* The generational barrier covers old->young edges within one objspace only.
8447 * NOTE: we shouldn't even check the age of `a` or `b` if they are in another
8448 * objspace, so check locality first. The test is rb_gc_ever_multi_ractor_p, not
8449 * rb_gc_multi_ractor_p: a foreign objspace exists before the process is
8450 * multi-Ractor (rb_gc_objspace_alloc runs while the creator is still the only
8451 * Ractor) and outlives the return to one (a fork parks the others in
8452 * zombie_objspaces). */
8453 if ((rb_gc_ever_multi_ractor_p() &&
8454 (GET_HEAP_OBJSPACE(a) != objspace || GET_HEAP_OBJSPACE(b) != objspace)) ||
8455 !RVALUE_OLD_P(objspace, a) || RVALUE_OLD_P(objspace, b)) {
8456 // do nothing
8457 }
8458 else {
8459 gc_writebarrier_generational(a, b, objspace);
8460 }
8461 }
8462 else {
8463 // Shareable objects from different object spaces are kept alive by shareable bits
8464 if (rb_gc_ever_multi_ractor_p() &&
8465 (GET_HEAP_OBJSPACE(a) != objspace || GET_HEAP_OBJSPACE(b) != objspace)) {
8466 // do nothing
8467 }
8468 else {
8469 gc_writebarrier_incremental(a, b, objspace);
8470 }
8471 }
8472}
8473
8474void
8475rb_gc_impl_obj_became_shareable(void *objspace_ptr, VALUE obj)
8476{
8477 /* An object becomes shareable on its owner thread, so this page update is
8478 * single-writer. */
8479 struct heap_page *page = GET_HEAP_PAGE(obj);
8480
8481 if (_MARKED_IN_BITMAP(page->shareable_bits, page, obj)) return;
8482 gc_page_add_shareable(page, obj);
8483
8484 /* The shref bits recorded while the object was unshareable are now covered by the
8485 * shareable pin, and a shref only points at an unshareable object. The owner thread is
8486 * the only writer, so a plain clear is enough. */
8487 if (_MARKED_IN_BITMAP(page->shref_bits, page, obj)) {
8488 _CLEAR_IN_BITMAP(page->shref_bits, page, obj);
8489 // NOTE: page->has_shref_objects could become stale here (value is true even though logically false)
8490 }
8491}
8492
8493void
8494rb_gc_impl_writebarrier_unprotect(void *objspace_ptr, VALUE obj)
8495{
8496 rb_objspace_t *objspace = objspace_ptr;
8497
8498 /* A shareable object is never WB-unprotected. Keeping shrefs correct relies on every
8499 * store into s->u going through the write barrier, which keeps wb_unprotected_bits
8500 * single-writer (only the owner thread can unprotect its own unshareable objects). */
8501 GC_ASSERT(!RB_FL_TEST_RAW(obj, RUBY_FL_SHAREABLE));
8502
8503 if (RVALUE_WB_UNPROTECTED(objspace, obj)) {
8504 return;
8505 }
8506 else {
8507 gc_report(2, objspace, "rb_gc_writebarrier_unprotect: %s %s\n", rb_obj_info(obj),
8508 RVALUE_REMEMBERED(objspace, obj) ? " (already remembered)" : "");
8509
8510 /* No lock: per the assert obj is our own unshareable, so these bits
8511 * (wb_unprotected, uncollectible, age) are single-writer on an owned page, and
8512 * RVALUE_DEMOTE's remembered-bit clear is atomic against word-sharing writers. */
8513 if (RVALUE_OLD_P(objspace, obj)) {
8514 gc_report(1, objspace, "rb_gc_writebarrier_unprotect: %s\n", rb_obj_info(obj));
8515 RVALUE_DEMOTE(objspace, obj);
8516 gc_mark_set(objspace, obj);
8517 gc_remember_unprotected(objspace, obj);
8518
8519#if RGENGC_PROFILE
8520 objspace->profile.total_shade_operation_count++;
8521#if RGENGC_PROFILE >= 2
8522 objspace->profile.shade_operation_count_types[BUILTIN_TYPE(obj)]++;
8523#endif /* RGENGC_PROFILE >= 2 */
8524#endif /* RGENGC_PROFILE */
8525 }
8526 else {
8527 RVALUE_AGE_RESET(obj);
8528 }
8529
8530 RB_DEBUG_COUNTER_INC(obj_wb_unprotect);
8531 MARK_IN_BITMAP(GET_HEAP_WB_UNPROTECTED_BITS(obj), obj);
8532 }
8533}
8534
8535void
8536rb_gc_impl_copy_attributes(void *objspace_ptr, VALUE dest, VALUE obj)
8537{
8538 rb_objspace_t *objspace = objspace_ptr;
8539
8540 if (RVALUE_WB_UNPROTECTED(objspace, obj)) {
8541 rb_gc_impl_writebarrier_unprotect(objspace, dest);
8542 }
8543 rb_gc_impl_copy_finalizer(objspace, dest, obj);
8544}
8545
8546const char *
8547rb_gc_impl_active_gc_name(void)
8548{
8549 return "default";
8550}
8551
8552/* NOTE: `obj` doesn't necessarily live in `objspace_ptr`, as `objspace_ptr` is just that
8553 * of the current Ractor. */
8554void
8555rb_gc_impl_writebarrier_remember(void *objspace_ptr, VALUE obj)
8556{
8557
8558 rb_objspace_t *objspace = objspace_ptr;
8559
8560 // Shareable objects from other object spaces don't need to be put on the remembered set
8561 // and are only collected during global GC, so not while incremental marking.
8562 if (RB_LIKELY(!rb_gc_ever_multi_ractor_p() || GET_HEAP_OBJSPACE(obj) == objspace)) {
8563 gc_report(1, objspace, "rb_gc_writebarrier_remember: %s\n", rb_obj_info(obj));
8564 if (is_incremental_marking(objspace)) {
8565 if (RVALUE_BLACK_P(objspace, obj)) {
8566 gc_grey(objspace, obj);
8567 }
8568 }
8569 else if (RVALUE_OLD_P(objspace, obj)) {
8570 rgengc_remember(objspace, obj);
8571 }
8572 }
8573}
8574
8576 // Must be ID only
8577 ID ID_wb_protected, ID_age, ID_old, ID_uncollectible, ID_marking,
8578 ID_marked, ID_pinned, ID_remembered, ID_object_id, ID_shareable;
8579};
8580
8581#define RB_GC_OBJECT_METADATA_ENTRY_COUNT (sizeof(struct rb_gc_object_metadata_names) / sizeof(ID))
8582static struct rb_gc_object_metadata_entry object_metadata_entries[RB_GC_OBJECT_METADATA_ENTRY_COUNT + 1];
8583
8585rb_gc_impl_object_metadata(void *objspace_ptr, VALUE obj)
8586{
8587 rb_objspace_t *objspace = objspace_ptr;
8588 size_t n = 0;
8589 static struct rb_gc_object_metadata_names names;
8590
8591 if (!names.ID_marked) {
8592#define I(s) names.ID_##s = rb_intern(#s)
8593 I(wb_protected);
8594 I(age);
8595 I(old);
8596 I(uncollectible);
8597 I(marking);
8598 I(marked);
8599 I(pinned);
8600 I(remembered);
8601 I(object_id);
8602 I(shareable);
8603#undef I
8604 }
8605
8606#define SET_ENTRY(na, v) do { \
8607 GC_ASSERT(n <= RB_GC_OBJECT_METADATA_ENTRY_COUNT); \
8608 object_metadata_entries[n].name = names.ID_##na; \
8609 object_metadata_entries[n].val = v; \
8610 n++; \
8611} while (0)
8612
8613 if (!RVALUE_WB_UNPROTECTED(objspace, obj)) SET_ENTRY(wb_protected, Qtrue);
8614 SET_ENTRY(age, INT2FIX(RVALUE_AGE_GET(obj)));
8615 if (RVALUE_OLD_P(objspace, obj)) SET_ENTRY(old, Qtrue);
8616 if (RVALUE_UNCOLLECTIBLE(objspace, obj)) SET_ENTRY(uncollectible, Qtrue);
8617 if (RVALUE_MARKING(objspace, obj)) SET_ENTRY(marking, Qtrue);
8618 if (RVALUE_MARKED(objspace, obj)) SET_ENTRY(marked, Qtrue);
8619 if (RVALUE_PINNED(objspace, obj)) SET_ENTRY(pinned, Qtrue);
8620 if (RVALUE_REMEMBERED(objspace, obj)) SET_ENTRY(remembered, Qtrue);
8621 if (rb_obj_id_p(obj)) SET_ENTRY(object_id, rb_obj_id(obj));
8622 if (FL_TEST(obj, FL_SHAREABLE)) SET_ENTRY(shareable, Qtrue);
8623
8624 object_metadata_entries[n].name = 0;
8625 object_metadata_entries[n].val = 0;
8626#undef SET_ENTRY
8627
8628 return object_metadata_entries;
8629}
8630
8631void *
8632rb_gc_impl_ractor_cache_alloc(void *objspace_ptr, void *ractor)
8633{
8634 /* No cache needed: allocation happens in a per-Ractor objspace. */
8635 return NULL;
8636}
8637
8638void
8639rb_gc_impl_ractor_cache_free(void *objspace_ptr, void *cache)
8640{
8641 GC_ASSERT(cache == NULL);
8642}
8643
8644/* The terminating Ractor's final local GC, on its own thread: roots are minimal, so the
8645 * mark is tiny, and it reclaims what the joining side would otherwise inherit. Never
8646 * promotes to a global GC (that would STW on every Ractor death); empty pages go
8647 * straight back to the page pool. */
8648/* Finalize the zombies whose cleanup is pure C (a dfree, no Ruby-level finalizer);
8649 * the caller has no Ruby execution context any more, so zombies with a Ruby
8650 * finalizer stay deferred and travel to the inheritor as before. Returns whether
8651 * anything was finalized (those pages then need one more sweep to detach). */
8652static bool
8653finalize_deferred_dfree_only(rb_objspace_t *objspace)
8654{
8655 VALUE dfree_only = 0;
8656 VALUE zombie = RUBY_ATOMIC_VALUE_EXCHANGE(heap_pages_deferred_final, 0);
8657 while (zombie) {
8658 rb_asan_unpoison_object(zombie, false);
8659 VALUE next = RZOMBIE(zombie)->next;
8660 if (FL_TEST_RAW(zombie, FL_FINALIZE)) {
8661 /* re-defer, with the same push as rb_gc_impl_make_zombie */
8662 VALUE prev2, next2 = heap_pages_deferred_final;
8663 do {
8664 RZOMBIE(zombie)->next = prev2 = next2;
8665 next2 = RUBY_ATOMIC_VALUE_CAS(heap_pages_deferred_final, prev2, zombie);
8666 } while (next2 != prev2);
8667 rb_asan_poison_object(zombie);
8668 }
8669 else {
8670 RZOMBIE(zombie)->next = dfree_only;
8671 dfree_only = zombie;
8672 }
8673 zombie = next;
8674 }
8675 if (dfree_only) finalize_list(objspace, dfree_only);
8676 bool did = dfree_only != 0;
8677
8678 gc_tdata_unsafe_free_publish(objspace);
8679 return did;
8680}
8681
8682void
8683rb_gc_impl_objspace_retire_gc(void *objspace_ptr)
8684{
8685 rb_objspace_t *objspace = objspace_ptr;
8686
8687 /* The dying thread's stack is already torn down here, so the root scan must skip
8688 * its machine context (rb_gc_mark_roots). */
8689 objspace->flags.during_postmortem = 1;
8690
8691 gc_rest(objspace);
8692 gc_start(objspace, GPR_FLAG_FULL_MARK | GPR_FLAG_IMMEDIATE_MARK | GPR_FLAG_IMMEDIATE_SWEEP);
8693
8694 /* The sweep above turned this heap's dead IO and the like into deferred zombies
8695 * (the per-Ractor stdio holds a page per Ractor otherwise); finalize the C-only
8696 * ones here and re-sweep the nearly-empty heap so their pages detach as empty. */
8697 if (finalize_deferred_dfree_only(objspace)) {
8698 gc_start(objspace, GPR_FLAG_FULL_MARK | GPR_FLAG_IMMEDIATE_MARK | GPR_FLAG_IMMEDIATE_SWEEP);
8699 }
8700
8701 heap_pages_freeable_pages = objspace->empty_pages_count;
8702 heap_pages_free_unused_pages(objspace);
8703
8704 objspace->flags.during_postmortem = 0;
8705}
8706
8707bool
8708rb_gc_impl_during_postmortem_p(void *objspace_ptr)
8709{
8710 rb_objspace_t *objspace = objspace_ptr;
8711 return objspace->flags.during_postmortem != 0;
8712}
8713
8714static void
8715heap_ready_to_gc(rb_objspace_t *objspace, rb_heap_t *heap)
8716{
8717 if (!heap->free_pages) {
8718 if (!heap_page_allocate_and_initialize(objspace, heap)) {
8719 objspace->heap_pages.allocatable_bytes = HEAP_PAGE_SIZE;
8720 heap_page_allocate_and_initialize(objspace, heap);
8721 }
8722 }
8723}
8724
8725static int
8726ready_to_gc(rb_objspace_t *objspace)
8727{
8728 if ((!objspace->flags.during_postmortem && rb_gc_gc_disabled_global_p()) || dont_gc_val() || during_gc) {
8729 for (int i = 0; i < HEAP_COUNT; i++) {
8730 rb_heap_t *heap = &heaps[i];
8731 heap_ready_to_gc(objspace, heap);
8732 }
8733 return FALSE;
8734 }
8735 else {
8736 return TRUE;
8737 }
8738}
8739
8740static void
8741gc_reset_malloc_info(rb_objspace_t *objspace, bool full_mark)
8742{
8743 gc_prof_set_malloc_info(objspace);
8744 {
8745 int64_t inc = gc_malloc_counters_increase(objspace, &objspace->malloc_counters.counters);
8746 gc_malloc_counters_snapshot(objspace, &objspace->malloc_counters.counters);
8747 size_t old_limit = malloc_limit;
8748
8749 /* A net-negative `inc` (more freed than malloc'd since last GC) is
8750 * treated the same as "allocated less than malloc_limit".
8751 * This matches what we were doing pre-monotonic counters, but is it right? */
8752 if (inc > 0 && (size_t)inc > malloc_limit) {
8753 malloc_limit = (size_t)((size_t)inc * gc_params.malloc_limit_growth_factor);
8754 if (malloc_limit > gc_params.malloc_limit_max) {
8755 malloc_limit = gc_params.malloc_limit_max;
8756 }
8757 }
8758 else {
8759 malloc_limit = (size_t)(malloc_limit * 0.98); /* magic number */
8760 if (malloc_limit < gc_params.malloc_limit_min) {
8761 malloc_limit = gc_params.malloc_limit_min;
8762 }
8763 }
8764
8765 if (0) {
8766 if (old_limit != malloc_limit) {
8767 fprintf(stderr, "[%"PRIuSIZE"] malloc_limit: %"PRIuSIZE" -> %"PRIuSIZE"\n",
8768 rb_gc_count(), old_limit, malloc_limit);
8769 }
8770 else {
8771 fprintf(stderr, "[%"PRIuSIZE"] malloc_limit: not changed (%"PRIuSIZE")\n",
8772 rb_gc_count(), malloc_limit);
8773 }
8774 }
8775 }
8776
8777 /* reset oldmalloc info */
8778#if RGENGC_ESTIMATE_OLDMALLOC
8779 if (!full_mark) {
8780 /* No full snapshot on minor GC: oldmalloc_increase accumulates across
8781 * minors and resets at major GC. (gc_sweep_finish still advances the
8782 * free baseline after every sweep.) */
8783 int64_t oldmalloc_increase = gc_malloc_counters_increase(objspace, &objspace->malloc_counters.oldcounters);
8784 if (oldmalloc_increase > 0 &&
8785 (uint64_t)oldmalloc_increase > objspace->rgengc.oldmalloc_increase_limit) {
8786 gc_needs_major_flags |= GPR_FLAG_MAJOR_BY_OLDMALLOC;
8787 objspace->rgengc.oldmalloc_increase_limit =
8788 (size_t)(objspace->rgengc.oldmalloc_increase_limit * gc_params.oldmalloc_limit_growth_factor);
8789
8790 if (objspace->rgengc.oldmalloc_increase_limit > gc_params.oldmalloc_limit_max) {
8791 objspace->rgengc.oldmalloc_increase_limit = gc_params.oldmalloc_limit_max;
8792 }
8793 }
8794
8795 if (0) fprintf(stderr, "%"PRIdSIZE"\t%d\t%"PRId64"\t%"PRIuSIZE"\t%"PRIdSIZE"\n",
8796 rb_gc_count(),
8797 gc_needs_major_flags,
8798 oldmalloc_increase,
8799 objspace->rgengc.oldmalloc_increase_limit,
8800 gc_params.oldmalloc_limit_max);
8801 }
8802 else {
8803 gc_malloc_counters_snapshot(objspace, &objspace->malloc_counters.oldcounters);
8804
8805 if ((objspace->profile.latest_gc_info & GPR_FLAG_MAJOR_BY_OLDMALLOC) == 0) {
8806 objspace->rgengc.oldmalloc_increase_limit =
8807 (size_t)(objspace->rgengc.oldmalloc_increase_limit / ((gc_params.oldmalloc_limit_growth_factor - 1)/10 + 1));
8808 if (objspace->rgengc.oldmalloc_increase_limit < gc_params.oldmalloc_limit_min) {
8809 objspace->rgengc.oldmalloc_increase_limit = gc_params.oldmalloc_limit_min;
8810 }
8811 }
8812 }
8813#endif
8814}
8815
8816/* What a collection records about itself before it runs. A global collection reports the
8817 * driver's objspace, so it comes through here too. */
8818static void
8819gc_start_record(rb_objspace_t *objspace, unsigned int reason, bool full_mark)
8820{
8821 objspace->profile.latest_gc_info = reason;
8822#if GC_PROFILE_MORE_DETAIL
8823 objspace->profile.total_allocated_objects_at_gc_start = total_allocated_objects(objspace);
8824 objspace->profile.heap_used_at_gc_start = rb_darray_size(objspace->heap_pages.sorted);
8825#endif
8826 objspace->profile.weak_references_count = 0;
8827 gc_prof_setup_new_record(objspace, reason);
8828 gc_reset_malloc_info(objspace, full_mark);
8829}
8830
8831static bool gc_start_global(rb_objspace_t *driver, unsigned int reason, bool compact, bool allow_skip);
8832
8833/* Decide whether this collection has to be global. A local GC can reclaim neither
8834 * shareable objects nor zombie objspaces, so once those grow past their limits only a
8835 * global GC makes progress. All inputs belong to this objspace. */
8836static bool
8837gc_need_global_p(rb_objspace_t *objspace)
8838{
8839 if (rb_gc_single_objspace_p()) return false;
8840 /* A Ractor's death must not stop the world, so the retire GC stays local. */
8841 if (objspace->flags.during_postmortem) return false;
8842 if (objspace->shareable_objects > objspace->shareable_objects_limit) return true;
8843 /* A zombie's garbage only a global cycle reclaims, but what survived the last one
8844 * is live data, so retrigger only once TRIGGER more pages accumulate on top of it.
8845 * Otherwise one live-heavy unjoined zombie turns every GC stop-the-world forever. */
8846 {
8847 size_t zp = rb_gc_vm_zombie_total_pages();
8848 size_t base = global_objspace->zombie_pages_survivors < zp ? global_objspace->zombie_pages_survivors : zp;
8849 if (zp - base >= ZOMBIE_PAGES_TRIGGER) return true;
8850 }
8851 return false;
8852}
8853
8854static int
8855garbage_collect(rb_objspace_t *objspace, unsigned int reason)
8856{
8857 int ret;
8858
8859#if GC_PROFILE_MORE_DETAIL
8860 objspace->profile.prepare_time = getrusage_time();
8861#endif
8862
8863 gc_rest(objspace);
8864
8865#if GC_PROFILE_MORE_DETAIL
8866 objspace->profile.prepare_time = getrusage_time() - objspace->profile.prepare_time;
8867#endif
8868
8869 ret = gc_start(objspace, reason);
8870
8871 return ret;
8872}
8873
8874static int
8875gc_start(rb_objspace_t *objspace, unsigned int reason)
8876{
8877 unsigned int do_full_mark = !!(reason & GPR_FLAG_FULL_MARK);
8878
8879 if (!rb_darray_size(objspace->heap_pages.sorted)) return TRUE; /* heap is not ready */
8880 if (!(reason & GPR_FLAG_METHOD) && !ready_to_gc(objspace)) return TRUE; /* GC is not allowed */
8881
8882 /* An explicit GC.start(global: true) never gets here: rb_gc_impl_start has already decided from
8883 * the `global` keyword, and GPR_FLAG_METHOD keeps `global: false` from being promoted back. */
8884 if (!(reason & GPR_FLAG_METHOD) && gc_need_global_p(objspace)) {
8885 /* A global GC is always a major, so autocompact applies. */
8886 if (gc_start_global(objspace, reason, ruby_enable_autocompact, true)) {
8887 return TRUE;
8888 }
8889 /* Fall through to a local GC */
8890 }
8891
8892 rb_gc_initialize_vm_context(&objspace->vm_context);
8893
8894 GC_ASSERT(gc_mode(objspace) == gc_mode_none, "gc_mode is %s\n", gc_mode_name(gc_mode(objspace)));
8895 GC_ASSERT(!is_lazy_sweeping(objspace));
8896 GC_ASSERT(!is_incremental_marking(objspace));
8897
8898 /* reason may be clobbered, later, so keep set immediate_sweep here */
8899 objspace->flags.immediate_sweep = !!(reason & GPR_FLAG_IMMEDIATE_SWEEP);
8900
8901 if (ruby_gc_stressful) {
8902 int flag = FIXNUM_P(ruby_gc_stress_mode) ? FIX2INT(ruby_gc_stress_mode) : 0;
8903
8904 if ((flag & (1 << gc_stress_no_major)) == 0) {
8905 do_full_mark = TRUE;
8906 }
8907
8908 objspace->flags.immediate_sweep = !(flag & (1<<gc_stress_no_immediate_sweep));
8909 }
8910
8911 if (gc_needs_major_flags) {
8912 reason |= gc_needs_major_flags;
8913 do_full_mark = TRUE;
8914 }
8915
8916 /* if major gc has been disabled, never do a full mark */
8917 if (!gc_config_full_mark_val) {
8918 do_full_mark = FALSE;
8919 }
8920 gc_needs_major_flags = GPR_FLAG_NONE;
8921
8922 if (do_full_mark && (reason & GPR_FLAG_MAJOR_MASK) == 0) {
8923 reason |= GPR_FLAG_MAJOR_BY_FORCE; /* GC by CAPI, METHOD, and so on. */
8924 }
8925
8926 if (objspace->flags.dont_incremental ||
8927 reason & GPR_FLAG_IMMEDIATE_MARK ||
8928 ruby_gc_stressful) {
8929 objspace->flags.during_incremental_marking = FALSE;
8930 }
8931 else {
8932 objspace->flags.during_incremental_marking = do_full_mark;
8933 }
8934
8935 /* Compaction on the local GC path (autocompact) runs only with a single objspace:
8936 * without the stop-the-world barrier, moving objects would break cross-objspace
8937 * references. With multiple objspaces GC.compact and autocompact go through the
8938 * compacting global GC instead (rb_gc_impl_start, or the promotion above). */
8939 if (do_full_mark && ruby_enable_autocompact && rb_gc_single_objspace_p()) {
8940 objspace->flags.during_compacting = TRUE;
8941#if RGENGC_CHECK_MODE
8942 objspace->rcompactor.compare_func = ruby_autocompact_compare_func;
8943#endif
8944 }
8945 else {
8946 objspace->flags.during_compacting = !!(reason & GPR_FLAG_COMPACT);
8947 if (objspace->flags.during_compacting && !rb_gc_single_objspace_p()) {
8948 // compaction is currently global GC only with more than 1 running Ractor
8949 objspace->flags.during_compacting = FALSE;
8950 }
8951 }
8952
8953 if (!GC_ENABLE_LAZY_SWEEP || objspace->flags.dont_incremental) {
8954 objspace->flags.immediate_sweep = TRUE;
8955 }
8956
8957 if (objspace->flags.immediate_sweep) reason |= GPR_FLAG_IMMEDIATE_SWEEP;
8958
8959 /* Enter after during_compacting is decided */
8960 unsigned int lock_lev;
8961 gc_enter(objspace, gc_enter_event_start, &lock_lev);
8962
8963 gc_report(1, objspace, "gc_start(reason: %x) => %u, %d, %d\n",
8964 reason,
8965 do_full_mark, !is_incremental_marking(objspace), objspace->flags.immediate_sweep);
8966
8967 RB_DEBUG_COUNTER_INC(gc_count);
8968
8969 if (reason & GPR_FLAG_MAJOR_MASK) {
8970 (void)RB_DEBUG_COUNTER_INC_IF(gc_major_nofree, reason & GPR_FLAG_MAJOR_BY_NOFREE);
8971 (void)RB_DEBUG_COUNTER_INC_IF(gc_major_oldgen, reason & GPR_FLAG_MAJOR_BY_OLDGEN);
8972 (void)RB_DEBUG_COUNTER_INC_IF(gc_major_shady, reason & GPR_FLAG_MAJOR_BY_SHADY);
8973 (void)RB_DEBUG_COUNTER_INC_IF(gc_major_force, reason & GPR_FLAG_MAJOR_BY_FORCE);
8974#if RGENGC_ESTIMATE_OLDMALLOC
8975 (void)RB_DEBUG_COUNTER_INC_IF(gc_major_oldmalloc, reason & GPR_FLAG_MAJOR_BY_OLDMALLOC);
8976#endif
8977 }
8978 else {
8979 (void)RB_DEBUG_COUNTER_INC_IF(gc_minor_newobj, reason & GPR_FLAG_NEWOBJ);
8980 (void)RB_DEBUG_COUNTER_INC_IF(gc_minor_malloc, reason & GPR_FLAG_MALLOC);
8981 (void)RB_DEBUG_COUNTER_INC_IF(gc_minor_method, reason & GPR_FLAG_METHOD);
8982 (void)RB_DEBUG_COUNTER_INC_IF(gc_minor_capi, reason & GPR_FLAG_CAPI);
8983 (void)RB_DEBUG_COUNTER_INC_IF(gc_minor_stress, reason & GPR_FLAG_STRESS);
8984 }
8985
8986 objspace->profile.count++;
8987 gc_start_record(objspace, reason, do_full_mark);
8988
8989 gc_event_hook(objspace, RUBY_INTERNAL_EVENT_GC_START);
8990
8991 GC_ASSERT(during_gc);
8992
8993 gc_prof_timer_start(objspace);
8994 {
8995 if (gc_marks(objspace, do_full_mark)) {
8996 gc_sweep(objspace);
8997 }
8998 }
8999 gc_prof_timer_stop(objspace);
9000
9001 gc_exit(objspace, gc_enter_event_start, &lock_lev);
9002
9003 /* Verify after the GC, at a real safepoint with during_gc cleared: mid-GC
9004 * gc_verify_internal_consistency() takes the VM lock and a barrier, which would join
9005 * another Ractor's global GC barrier and let it collect on this half-collected heap. */
9006#if RGENGC_CHECK_MODE >= 2
9007 gc_verify_internal_consistency(objspace);
9008#endif
9009 return TRUE;
9010}
9011
9012static void
9013gc_rest(rb_objspace_t *objspace)
9014{
9015 if (is_incremental_marking(objspace) || is_lazy_sweeping(objspace)) {
9016 unsigned int lock_lev;
9017 gc_enter(objspace, gc_enter_event_rest, &lock_lev);
9018
9019 if (is_incremental_marking(objspace)) {
9020 gc_marking_enter(objspace);
9021 gc_marks_rest(objspace);
9022 gc_marking_exit(objspace);
9023
9024 gc_sweep(objspace);
9025 }
9026
9027 if (is_lazy_sweeping(objspace)) {
9028 gc_sweeping_enter(objspace);
9029 gc_sweep_rest(objspace);
9030 gc_sweeping_exit(objspace);
9031 }
9032
9033 gc_exit(objspace, gc_enter_event_rest, &lock_lev);
9034
9035 if (RGENGC_CHECK_MODE >= 2) gc_verify_internal_consistency(objspace); /* after GC, see gc_start */
9036 }
9037}
9038
9041 unsigned int reason;
9042};
9043
9044static void
9045gc_current_status_fill(rb_objspace_t *objspace, char *buff)
9046{
9047 int i = 0;
9048 if (is_marking(objspace)) {
9049 buff[i++] = 'M';
9050 if (is_full_marking(objspace)) buff[i++] = 'F';
9051 if (is_incremental_marking(objspace)) buff[i++] = 'I';
9052 }
9053 else if (is_sweeping(objspace)) {
9054 buff[i++] = 'S';
9055 if (is_lazy_sweeping(objspace)) buff[i++] = 'L';
9056 }
9057 else {
9058 buff[i++] = 'N';
9059 }
9060 buff[i] = '\0';
9061}
9062
9063static const char *
9064gc_current_status(rb_objspace_t *objspace)
9065{
9066 static char buff[0x10];
9067 gc_current_status_fill(objspace, buff);
9068 return buff;
9069}
9070
9071#if PRINT_ENTER_EXIT_TICK
9072
9073static tick_t last_exit_tick;
9074static tick_t enter_tick;
9075static int enter_count = 0;
9076static char last_gc_status[0x10];
9077
9078static inline void
9079gc_record(rb_objspace_t *objspace, int direction, const char *event)
9080{
9081 if (direction == 0) { /* enter */
9082 enter_count++;
9083 enter_tick = tick();
9084 gc_current_status_fill(objspace, last_gc_status);
9085 }
9086 else { /* exit */
9087 tick_t exit_tick = tick();
9088 char current_gc_status[0x10];
9089 gc_current_status_fill(objspace, current_gc_status);
9090#if 1
9091 /* [last mutator time] [gc time] [event] */
9092 fprintf(stderr, "%"PRItick"\t%"PRItick"\t%s\t[%s->%s|%c]\n",
9093 enter_tick - last_exit_tick,
9094 exit_tick - enter_tick,
9095 event,
9096 last_gc_status, current_gc_status,
9097 (objspace->profile.latest_gc_info & GPR_FLAG_MAJOR_MASK) ? '+' : '-');
9098 last_exit_tick = exit_tick;
9099#else
9100 /* [enter_tick] [gc time] [event] */
9101 fprintf(stderr, "%"PRItick"\t%"PRItick"\t%s\t[%s->%s|%c]\n",
9102 enter_tick,
9103 exit_tick - enter_tick,
9104 event,
9105 last_gc_status, current_gc_status,
9106 (objspace->profile.latest_gc_info & GPR_FLAG_MAJOR_MASK) ? '+' : '-');
9107#endif
9108 }
9109}
9110#else /* PRINT_ENTER_EXIT_TICK */
9111static inline void
9112gc_record(rb_objspace_t *objspace, int direction, const char *event)
9113{
9114 /* null */
9115}
9116#endif /* PRINT_ENTER_EXIT_TICK */
9117
9118static const char *
9119gc_enter_event_cstr(enum gc_enter_event event)
9120{
9121 switch (event) {
9122 case gc_enter_event_start: return "start";
9123 case gc_enter_event_continue: return "continue";
9124 case gc_enter_event_rest: return "rest";
9125 case gc_enter_event_finalizer: return "finalizer";
9126 case gc_enter_event_global: return "global";
9127 case gc_enter_event_global_auto: return "global_auto";
9128 }
9129 return NULL;
9130}
9131
9132static void
9133gc_enter_count(enum gc_enter_event event)
9134{
9135 switch (event) {
9136 case gc_enter_event_start: RB_DEBUG_COUNTER_INC(gc_enter_start); break;
9137 case gc_enter_event_continue: RB_DEBUG_COUNTER_INC(gc_enter_continue); break;
9138 case gc_enter_event_rest: RB_DEBUG_COUNTER_INC(gc_enter_rest); break;
9139 case gc_enter_event_finalizer: RB_DEBUG_COUNTER_INC(gc_enter_finalizer); break;
9140 case gc_enter_event_global: RB_DEBUG_COUNTER_INC(gc_enter_start); break;
9141 case gc_enter_event_global_auto: RB_DEBUG_COUNTER_INC(gc_enter_start); break;
9142 }
9143}
9144
9145static bool current_process_time(struct timespec *ts);
9146
9147/* A gc phase must be timed on the collecting thread's own cpu. A local gc runs
9148 * while the other ractors keep going, and process cpu time counts their work as
9149 * gc: with eight busy ractors the same ten collections were reported as 131ms
9150 * instead of 3ms, more than the wall clock they ran in. The kernel also answers
9151 * this one without walking every thread in the process. */
9152static bool
9153current_thread_time(struct timespec *ts)
9154{
9155#if defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_THREAD_CPUTIME_ID)
9156 {
9157 static int try_clock_gettime = 1;
9158 if (try_clock_gettime) {
9159 if (clock_gettime(CLOCK_THREAD_CPUTIME_ID, ts) == 0) {
9160 return true;
9161 }
9162 else {
9163 try_clock_gettime = 0;
9164 }
9165 }
9166 }
9167#endif
9168 return current_process_time(ts);
9169}
9170
9171static void
9172gc_clock_start(struct timespec *ts)
9173{
9174 if (!current_thread_time(ts)) {
9175 ts->tv_sec = 0;
9176 ts->tv_nsec = 0;
9177 }
9178}
9179
9180static unsigned long long
9181gc_clock_end(struct timespec *ts)
9182{
9183 struct timespec end_time;
9184
9185 if ((ts->tv_sec > 0 || ts->tv_nsec > 0) &&
9186 current_thread_time(&end_time) &&
9187 end_time.tv_sec >= ts->tv_sec) {
9188 return (unsigned long long)(end_time.tv_sec - ts->tv_sec) * (1000 * 1000 * 1000) +
9189 (end_time.tv_nsec - ts->tv_nsec);
9190 }
9191
9192 return 0;
9193}
9194
9195static void
9196gc_process_stat_after_fork_i(void *objspace_ptr, void *data)
9197{
9198 rb_objspace_t *objspace = objspace_ptr;
9199 rb_native_mutex_initialize(&objspace->process_stat.lock);
9200}
9201
9202static inline bool
9203gc_local_gc_holds_vm_lock(void)
9204{
9205 return rb_gc_single_objspace_p();
9206}
9207
9208static inline bool
9209gc_enter(rb_objspace_t *objspace, enum gc_enter_event event, unsigned int *lock_lev)
9210{
9211 /*
9212 * NOTE: The GC must never take the barrier VM lock from inside itself: the waiter could
9213 * join a pending barrier mid-collection and expose its half-collected heap to the global
9214 * GC. A no-barrier lock is safe. Other shared structures the GC paths touch use their own
9215 * native mutexes or the page-pool lock. */
9216 *lock_lev = 0;
9217
9218 RUBY_DTRACE_GC_HOOK(ENTER, event);
9219
9220 if (objspace->profile.run) {
9221 switch (event) {
9222 case gc_enter_event_start:
9223 case gc_enter_event_continue:
9224 case gc_enter_event_rest:
9225 case gc_enter_event_global:
9226 case gc_enter_event_global_auto:
9227 /* A global GC is the longest pause the process takes, so it is the last thing
9228 * the profiler may leave unmeasured. The switch below stops the world for it,
9229 * which is exactly the interval gc_stop_time is meant to name, so start the
9230 * clock here like a local collection does. */
9231 objspace->profile.gc_pause_start_time = rb_hrtime_now();
9232 break;
9233 case gc_enter_event_finalizer:
9234 break;
9235 }
9236 }
9237 switch (event) {
9238 case gc_enter_event_global:
9239 *lock_lev = RB_GC_VM_LOCK();
9240 // stop other ractors
9241 rb_gc_vm_barrier();
9242 break;
9243 case gc_enter_event_global_auto:
9244 *lock_lev = RB_GC_VM_LOCK();
9245 if (!gc_need_global_p(objspace)) {
9246 RB_GC_VM_UNLOCK(*lock_lev);
9247 *lock_lev = 0;
9248 objspace->profile.gc_pause_start_time = 0;
9249 return false;
9250 }
9251 rb_gc_vm_barrier();
9252 break;
9253 case gc_enter_event_finalizer:
9254 /* Shutdown finalizers read VM-global tables (fstring, symbol) and free T_DATA that
9255 * is not thread-safe, so take the no-barrier VM lock. */
9256 *lock_lev = RB_GC_VM_LOCK_NO_BARRIER();
9257 break;
9258 default:
9259 objspace->flags.gc_lock_barrier = FALSE;
9260 if (objspace->flags.during_compacting) {
9261 /* Compaction relocates objects and rewrites every Ractor's JIT and global
9262 * references, so it stops the world with a barrier VM lock. rb_gc_vm_barrier is
9263 * a reentrant no-op with a single Ractor, so an inner barrier request during the
9264 * move folds into this one and gc_exit ends it. */
9265 *lock_lev = RB_GC_VM_LOCK();
9266 rb_gc_vm_barrier();
9267 objspace->flags.gc_lock_barrier = TRUE;
9268 }
9269 else if (gc_local_gc_holds_vm_lock()) {
9270 *lock_lev = RB_GC_VM_LOCK_NO_BARRIER();
9271 }
9272 break;
9273 }
9274
9275 if (objspace->profile.gc_pause_start_time) {
9276 objspace->profile.gc_stw_start_time = rb_hrtime_now();
9277 objspace->profile.gc_stop_time = rb_hrtime_sub(
9278 objspace->profile.gc_stw_start_time,
9279 objspace->profile.gc_pause_start_time);
9280 }
9281
9282 gc_enter_count(event);
9283 if (RB_UNLIKELY(during_gc != 0)) rb_bug("during_gc != 0");
9284 if (RGENGC_CHECK_MODE >= 3) gc_verify_internal_consistency(objspace);
9285
9286 during_gc = TRUE;
9287 RUBY_DEBUG_LOG("%s (%s)",gc_enter_event_cstr(event), gc_current_status(objspace));
9288 gc_report(1, objspace, "gc_enter: %s [%s]\n", gc_enter_event_cstr(event), gc_current_status(objspace));
9289 gc_record(objspace, 0, gc_enter_event_cstr(event));
9290
9291 gc_event_hook(objspace, RUBY_INTERNAL_EVENT_GC_ENTER);
9292 return true;
9293}
9294
9295static inline void
9296gc_exit(rb_objspace_t *objspace, enum gc_enter_event event, unsigned int *lock_lev)
9297{
9298 GC_ASSERT(during_gc != 0);
9299
9300 RUBY_DTRACE_GC_HOOK(EXIT, event);
9301
9302 gc_event_hook(objspace, RUBY_INTERNAL_EVENT_GC_EXIT);
9303
9304 if (objspace->profile.gc_pause_start_time) {
9305 if (gc_prof_enabled(objspace)) {
9306 rb_hrtime_t now = rb_hrtime_now();
9307 gc_profile_record *record = gc_prof_record(objspace);
9308 record->gc_pause_time = rb_hrtime_add(record->gc_pause_time,
9309 rb_hrtime_sub(now, objspace->profile.gc_pause_start_time));
9310 record->gc_stop_time = rb_hrtime_add(record->gc_stop_time,
9311 objspace->profile.gc_stop_time);
9312 record->gc_stw_time = rb_hrtime_add(record->gc_stw_time,
9313 rb_hrtime_sub(now, objspace->profile.gc_stw_start_time));
9314 }
9315 objspace->profile.gc_pause_start_time = 0;
9316 objspace->profile.gc_stw_start_time = 0;
9317 objspace->profile.gc_stop_time = 0;
9318 }
9319
9320 gc_record(objspace, 1, gc_enter_event_cstr(event));
9321 RUBY_DEBUG_LOG("%s (%s)", gc_enter_event_cstr(event), gc_current_status(objspace));
9322 gc_report(1, objspace, "gc_exit: %s [%s]\n", gc_enter_event_cstr(event), gc_current_status(objspace));
9323 during_gc = FALSE;
9324 gc_process_stat_publish(objspace);
9325
9326 switch (event) {
9327 case gc_enter_event_global:
9328 case gc_enter_event_global_auto:
9329 RB_GC_VM_UNLOCK(*lock_lev);
9330 break;
9331 case gc_enter_event_finalizer:
9332 RB_GC_VM_UNLOCK_NO_BARRIER(*lock_lev);
9333 break;
9334 default:
9335 if (*lock_lev != 0) {
9336 if (objspace->flags.gc_lock_barrier) {
9337 objspace->flags.gc_lock_barrier = FALSE;
9338 RB_GC_VM_UNLOCK(*lock_lev);
9339 }
9340 else {
9341 RB_GC_VM_UNLOCK_NO_BARRIER(*lock_lev);
9342 }
9343 }
9344 break;
9345 }
9346}
9347
9348#ifndef MEASURE_GC
9349#define MEASURE_GC (objspace->flags.measure_gc)
9350#endif
9351
9352static void
9353gc_marking_enter(rb_objspace_t *objspace)
9354{
9355 GC_ASSERT(during_gc != 0);
9356
9357 gc_prof_mark_timer_start(objspace);
9358
9359 if (gc_prof_enabled(objspace)) {
9360 objspace->profile.gc_mark_phase_wall_start_time = rb_hrtime_now();
9361 }
9362
9363 if (MEASURE_GC) {
9364 gc_clock_start(&objspace->profile.marking_start_time);
9365 }
9366
9367 rb_gc_initialize_vm_context(&objspace->vm_context);
9368}
9369
9370static void
9371gc_marking_exit(rb_objspace_t *objspace)
9372{
9373 GC_ASSERT(during_gc != 0);
9374
9375 if (MEASURE_GC) {
9376 objspace->profile.marking_time_ns += gc_clock_end(&objspace->profile.marking_start_time);
9377 }
9378
9379 if (gc_prof_enabled(objspace)) {
9380 gc_profile_record *record = gc_prof_record(objspace);
9381 record->gc_mark_wall_time = rb_hrtime_add(record->gc_mark_wall_time,
9382 elapsed_hrtime_from(objspace->profile.gc_mark_phase_wall_start_time));
9383 }
9384
9385 gc_prof_mark_timer_stop(objspace);
9386}
9387
9388static void
9389gc_sweeping_cpu_enter(rb_objspace_t *objspace)
9390{
9391 if (MEASURE_GC) {
9392 gc_clock_start(&objspace->profile.sweeping_start_time);
9393 }
9394}
9395
9396static void
9397gc_sweeping_cpu_exit(rb_objspace_t *objspace)
9398{
9399 if (MEASURE_GC) {
9400 objspace->profile.sweeping_time_ns += gc_clock_end(&objspace->profile.sweeping_start_time);
9401 }
9402}
9403
9404static void
9405gc_sweeping_enter(rb_objspace_t *objspace)
9406{
9407 GC_ASSERT(during_gc != 0);
9408
9409 if (gc_prof_enabled(objspace)) {
9410 objspace->profile.gc_sweep_phase_wall_start_time = rb_hrtime_now();
9411 objspace->profile.gc_sweep_excluded_wall_time = 0;
9412 }
9413
9414 gc_sweeping_cpu_enter(objspace);
9415
9416 rb_gc_initialize_vm_context(&objspace->vm_context);
9417}
9418
9419static void
9420gc_sweeping_exit(rb_objspace_t *objspace)
9421{
9422 GC_ASSERT(during_gc != 0);
9423
9424 gc_sweeping_cpu_exit(objspace);
9425
9426 if (gc_prof_enabled(objspace)) {
9427 rb_hrtime_t sweep_wall_time = elapsed_hrtime_from(objspace->profile.gc_sweep_phase_wall_start_time);
9428 gc_profile_record *record = gc_prof_record(objspace);
9429 sweep_wall_time = rb_hrtime_sub(sweep_wall_time,
9430 objspace->profile.gc_sweep_excluded_wall_time);
9431 record->gc_sweep_wall_time = rb_hrtime_add(record->gc_sweep_wall_time,
9432 sweep_wall_time);
9433 objspace->profile.gc_sweep_excluded_wall_time = 0;
9434 }
9435}
9436
9437static void *
9438gc_with_gvl(void *ptr)
9439{
9440 struct objspace_and_reason *oar = (struct objspace_and_reason *)ptr;
9441 return (void *)(VALUE)garbage_collect(oar->objspace, oar->reason);
9442}
9443
9444int ruby_thread_has_gvl_p(void);
9445
9446static int
9447garbage_collect_with_gvl(rb_objspace_t *objspace, unsigned int reason)
9448{
9449 if (rb_gc_gc_disabled_global_p() || dont_gc_val()) {
9450 return TRUE;
9451 }
9452 else if (!ruby_native_thread_p()) {
9453 return TRUE;
9454 }
9455 else if (!ruby_thread_has_gvl_p()) {
9456 void *ret;
9457 struct objspace_and_reason oar;
9458 oar.objspace = objspace;
9459 oar.reason = reason;
9460 ret = rb_thread_call_with_gvl(gc_with_gvl, (void *)&oar);
9461
9462 return !!ret;
9463 }
9464 else {
9465 return garbage_collect(objspace, reason);
9466 }
9467}
9468
9469static int
9470gc_set_candidate_object_i(void *vstart, void *vend, size_t stride, void *data)
9471{
9473
9474 VALUE v = (VALUE)vstart;
9475 for (; v != (VALUE)vend; v += stride) {
9476 asan_unpoisoning_object(v) {
9477 switch (BUILTIN_TYPE(v)) {
9478 case T_NONE:
9479 case T_ZOMBIE:
9480 break;
9481 default:
9482 rb_gc_prepare_heap_process_object(v);
9483 if (!RVALUE_OLD_P(objspace, v) && !RVALUE_WB_UNPROTECTED(objspace, v)) {
9484 RVALUE_AGE_SET_CANDIDATE(objspace, v);
9485 }
9486 }
9487 }
9488 }
9489
9490 return 0;
9491}
9492
9493bool
9494rb_gc_impl_multi_objspace_p(void)
9495{
9496 return true;
9497}
9498
9499bool
9500rb_gc_impl_during_global_gc_p(void *objspace_ptr)
9501{
9502 rb_objspace_t *objspace = objspace_ptr;
9503 return objspace->flags.during_global_gc != 0;
9504}
9505
9506bool
9507rb_gc_impl_obj_foreign_p(void *objspace_ptr, VALUE obj)
9508{
9509 return gc_foreign_object_p(objspace_ptr, obj);
9510}
9511
9512
9513/* Whether obj is recorded as an unshareable object referenced from a shareable one. For
9514 * the verifier: a shareable -> unshareable edge is only accepted if the write barrier
9515 * recorded it here. */
9516bool
9517rb_gc_impl_shref_marked_p(void *objspace_ptr, VALUE obj)
9518{
9519 return MARKED_IN_BITMAP(GET_HEAP_SHREF_BITS(obj), obj) != 0;
9520}
9521
9522/* The objspace's current page count (used for the zombie_objspaces page accounting). */
9523size_t
9524rb_gc_impl_heap_page_count(void *objspace_ptr)
9525{
9526 rb_objspace_t *objspace = objspace_ptr;
9527 return rb_darray_size(objspace->heap_pages.sorted);
9528}
9529
9530static void
9531gc_global_objspaces_i(void *os, void *data)
9532{
9533 if (global_objspace->global_gc.n_objspaces == global_objspace->global_gc.objspaces_capa) {
9534 size_t new_capa = global_objspace->global_gc.objspaces_capa ? global_objspace->global_gc.objspaces_capa * 2 : 16;
9535 struct rb_objspace **new_list = realloc(global_objspace->global_gc.objspaces, new_capa * sizeof(*new_list));
9536 if (new_list == NULL) rb_bug("gc_global_objspaces_i: realloc failed");
9537 global_objspace->global_gc.objspaces = new_list;
9538 global_objspace->global_gc.objspaces_capa = new_capa;
9539 }
9540 global_objspace->global_gc.objspaces[global_objspace->global_gc.n_objspaces++] = os;
9541}
9542
9543/* Re-snapshot every objspace this cycle covers, zombies included. The objspaces/capa
9544 * buffer is reused from the previous cycle. */
9545static void
9546gc_global_snapshot_objspaces(void)
9547{
9548 global_objspace->global_gc.n_objspaces = 0;
9549 rb_gc_vm_each_objspace(gc_global_objspaces_i, NULL);
9550
9551#if RGENGC_CHECK_MODE
9552 /* Check that the incrementally maintained page_index agrees with the per-objspace
9553 * sorted arrays. */
9554 size_t total = 0;
9555 for (size_t i = 0; i < global_objspace->global_gc.n_objspaces; i++) {
9556 total += rb_darray_size(global_objspace->global_gc.objspaces[i]->heap_pages.sorted);
9557 }
9558 GC_ASSERT(total == global_objspace->page_index.n_pages);
9559#endif
9560}
9561
9562/* Global GC: stop every Ractor and clear/mark/sweep all objspaces as one heap. It is the
9563 * only collector that can free shareable objects and decide cross-objspace reachability
9564 * precisely. */
9565/* The global GC's generic_fields weak pass, after the unified mark fixpoint, before the
9566 * sweep. Per-object rb_mark_generic_ivar is a no-op during a global GC (the driver has
9567 * GET_RACTOR() != owner); the whole table is swept here instead. Weak-KEY: mark the val
9568 * (fields_obj, a strong child) only for a live key, drain dead keys' entries. Marking a
9569 * val can make another key live, so repeat to a fixpoint. */
9572 bool progress;
9573};
9574
9575static int
9576genfields_mark_i(VALUE key, VALUE val, void *arg)
9577{
9578 struct genfields_mark_arg *a = (struct genfields_mark_arg *)arg;
9579 if (RB_SPECIAL_CONST_P(val) || !RVALUE_MARKED_BITMAP(key)) {
9580 return ST_CONTINUE;
9581 }
9582 /* Record the old(key)->young(val) edge with the host (key) as parent, even when val
9583 * is already marked: a conservative machine-stack scan can mark a fresh fields_obj
9584 * parentless before this pass, and branching on the mark bit would leave the key
9585 * unremembered, so the next minor GC misses the young val ("WB miss (O->Y)").
9586 * gc_mark runs rgengc_check_relation before its already-marked return: call always. */
9587 bool newly = !RVALUE_MARKED_BITMAP(val);
9588 gc_mark_set_parent(a->objspace, key);
9589 gc_mark(a->objspace, val);
9590 if (newly) a->progress = true;
9591 return ST_CONTINUE;
9592}
9593
9594static bool
9595genfields_dead_p(VALUE key)
9596{
9597 return RVALUE_MARKED_BITMAP(key) == 0;
9598}
9599
9600static void
9601gc_global_mark_generic_fields(rb_objspace_t *driver)
9602{
9603 struct genfields_mark_arg arg = { driver, false };
9604 do {
9605 arg.progress = false;
9606 /* Each entry's mark sets parent=key (genfields_mark_i) so the generational WB is
9607 * recorded correctly. gc_mark_stacked_objects_all sets its own per-object parent,
9608 * so restore the invalid parent (the poison contract) before calling it. */
9609 rb_gc_vm_generic_fields_mark_foreach(genfields_mark_i, &arg);
9610 gc_mark_set_parent_invalid(driver);
9611 if (arg.progress) {
9612 gc_mark_stacked_objects_all(driver);
9613 }
9614 } while (arg.progress);
9615
9616 rb_gc_vm_generic_fields_drain_dead(genfields_dead_p);
9617}
9618
9619/* Two Ractors choosing a global GC at once are serialized by the VM lock in gc_enter. If two
9620 * globals start concurrently, only one global will run and the other will run a local GC after
9621 * the barrier ends. */
9622static bool
9623gc_start_global(rb_objspace_t *driver, unsigned int reason, bool compact, bool allow_skip)
9624{
9625 unsigned int lock_lev;
9626 enum gc_enter_event event = allow_skip ? gc_enter_event_global_auto : gc_enter_event_global;
9627 if (!gc_enter(driver, event, &lock_lev)) {
9628 return false;
9629 }
9630
9631 reason |= GPR_FLAG_GLOBAL;
9632
9633 /* A global GC is a collection of the driver's objspace too, and its profile.count
9634 * below says so, so report it like a local one. The driver is the objspace whose
9635 * count moves, which is the one a hook reading GC.stat would compare against. For
9636 * the same reason it records a profile entry and reports what triggered it. */
9637 gc_start_record(driver, reason, true);
9638 gc_event_hook(driver, RUBY_INTERNAL_EVENT_GC_START);
9639 gc_prof_timer_start(driver);
9640
9641 gc_global_snapshot_objspaces();
9642
9643 /* Mark every objspace as in a global GC before step 3 settles the lazy sweeps: the
9644 * settle frees other objspaces' garbage on the driver thread, and
9645 * rb_free_generic_ivar must see "global GC in progress" to defer generic_fields
9646 * removal to the weak-pass drain. */
9647 for (size_t i = 0; i < global_objspace->global_gc.n_objspaces; i++) {
9648 global_objspace->global_gc.objspaces[i]->flags.during_global_gc = TRUE;
9649 }
9650
9651 /* A global GC collects every objspace, so each needs the malloc-counter reset the
9652 * driver got in gc_start_record; without it, gc_sweep_finish advancing free_at_last_gc
9653 * (step 9) would leave their malloc_increase overstated by everything swept here. */
9654 for (size_t i = 0; i < global_objspace->global_gc.n_objspaces; i++) {
9655 rb_objspace_t *const os = global_objspace->global_gc.objspaces[i];
9656 if (os != driver) {
9657 os->profile.latest_gc_info = reason;
9658 gc_reset_malloc_info(os, true);
9659 }
9660 }
9661
9662 /* step 3: settle every lazy sweep so the mark bits' meaning is fixed before the clear
9663 * below. (during_gc is a macro over the local "objspace".) rb_gc_get_ec() resolves
9664 * through objspace->vm_context during a GC, so initialize it for all: the driver
9665 * thread runs every objspace's phases. */
9666 for (size_t i = 0; i < global_objspace->global_gc.n_objspaces; i++) {
9667 rb_objspace_t *objspace = global_objspace->global_gc.objspaces[i];
9668 /* The barrier can stop a Ractor between the steps of its own incremental mark, and
9669 * nothing else finishes another objspace's mark. Drop the partial mark rather
9670 * than clear its flags in step 5 under a live gray stack: the owner would resume
9671 * with a mark stack into a heap this GC has since re-marked and swept. Nothing is
9672 * lost, the unified mark below redoes the work. */
9673 if (is_incremental_marking(objspace)) {
9674 gc_abort_incremental_marking(objspace);
9675 }
9676 GC_ASSERT(!is_incremental_marking(objspace));
9677 GC_ASSERT(is_mark_stack_empty(&objspace->mark_stack));
9678 rb_gc_initialize_vm_context(&objspace->vm_context);
9679 if (objspace != driver) during_gc = TRUE;
9680 gc_sweep_rest(objspace);
9681 }
9682
9683 /* step 5: clear every objspace's mark bits, remembered sets, generation counters and
9684 * shrefs (missing even one leaves a stale mark bit and a UAF). (heaps is a macro over
9685 * the local "objspace".) */
9686 for (size_t i = 0; i < global_objspace->global_gc.n_objspaces; i++) {
9687 rb_objspace_t *objspace = global_objspace->global_gc.objspaces[i];
9688 objspace->flags.during_minor_gc = FALSE;
9689 objspace->flags.during_incremental_marking = FALSE;
9690 /* The unified mark is precise and does not pin, so the per-objspace sweep below must
9691 * not re-check against a stale local cycle. */
9692 objspace->last_cycle_pinned = 0;
9693 objspace->rgengc.uncollectible_wb_unprotected_objects = 0;
9694 objspace->rgengc.old_objects = 0;
9695 objspace->rgengc.last_major_gc = objspace->profile.count;
9696 objspace->rgengc.need_major_gc = GPR_FLAG_NONE;
9697 objspace->marked_slots = 0;
9698 for (int h = 0; h < HEAP_COUNT; h++) {
9699 rb_heap_t *heap = &heaps[h];
9700 gc_bitmaps_clear(objspace, heap, true);
9701 heap_move_pooled_pages_to_free_pages(heap);
9702 }
9703 }
9704 driver->profile.global_gc_count++;
9705 global_objspace->global_gc.count++;
9706
9707 /* Enable compaction in every objspace before the mark: the unified conservative root
9708 * scan then pins machine-stack referents (gc_pin only pins while during_compacting)
9709 * and step 9's sweep relocates the rest. global_gc.compacting defers the
9710 * reference-update phase to phase 2 below (two phases, safe across objspaces). */
9711 global_objspace->global_gc.compacting = compact;
9712 if (compact) {
9713 for (size_t i = 0; i < global_objspace->global_gc.n_objspaces; i++) {
9714 rb_objspace_t *objspace = global_objspace->global_gc.objspaces[i];
9715 objspace->flags.during_compacting = TRUE;
9716#if RGENGC_CHECK_MODE
9717 if (ruby_enable_autocompact) {
9718 objspace->rcompactor.compare_func = ruby_autocompact_compare_func;
9719 }
9720#endif
9721 /* A global GC skips gc_marks_start, which is what resets pinned_slots for a
9722 * compacting local GC, so reset it here. step 5 cleared pinned_bits; the
9723 * conservative mark re-pins machine-stack referents. */
9724 for (int h = 0; h < HEAP_COUNT; h++) {
9725 struct heap_page *page = NULL;
9726 ccan_list_for_each(&heaps[h].pages, page, page_node) {
9727 page->pinned_slots = 0;
9728 }
9729 }
9730 }
9731 }
9732
9733 /* steps 6-7: every Ractor's roots (gc.c walks them all), then one unified precise
9734 * mark. A global GC does not go through gc_marks, so the marking
9735 * phase is opened here instead; it closes after rb_ractor_finish_marking below, which is
9736 * where gc_marks_finish ends for a local collection. */
9737 gc_marking_enter(driver);
9738
9739 mark_roots(driver, NULL);
9740 gc_mark_stacked_objects_all(driver);
9741
9742 /* Run the generic_fields weak pass after the mark fixpoint: mark the vals (fields_obj)
9743 * of live keys and drain the entries of dead ones. The per-object rb_mark_generic_ivar
9744 * is a no-op during a global GC, so this is the only path that marks generic_fields. */
9745 gc_global_mark_generic_fields(driver);
9746
9747 gc_event_hook(driver, RUBY_INTERNAL_EVENT_GC_END_MARK);
9748
9749 /* step 8 */
9750 gc_update_weak_references(driver);
9751
9752 /* This cycle's root pass over every Ractor has swept the deleted ractor-local keys out of
9753 * each storage. Free the key structs while still inside the barrier (a local GC never
9754 * can; see rb_ractor_finish_marking). */
9755 rb_ractor_finish_marking(true);
9756
9757 gc_marking_exit(driver);
9758
9759 /* step 9: sweep every objspace inside the barrier, not lazily. Dead shareable objects
9760 * are reclaimed here and emptied pages go back to the pool. */
9761 if (!compact) {
9762 for (size_t i = 0; i < global_objspace->global_gc.n_objspaces; i++) {
9763 rb_objspace_t *os = global_objspace->global_gc.objspaces[i];
9764 unsigned int prev_immediate = os->flags.immediate_sweep;
9765 os->flags.immediate_sweep = TRUE;
9766 gc_sweep(os);
9767 os->flags.immediate_sweep = prev_immediate;
9768 }
9769 }
9770 else {
9771 /* The move -> update-references -> free flow runs as three passes across ALL
9772 * objspaces, not per objspace: (a) updating references must see every objspace's
9773 * forwarding (a reference can point at a moved foreign object), and (b) freeing
9774 * source pages must wait until everyone is updated (or another objspace's update
9775 * reads a freed T_MOVED). The read barrier is installed once for all passes. */
9776 install_handlers();
9777
9778 /* Only the driver records a profile entry for a global GC (gc_start_record), so time
9779 * only the driver's compaction work. The move/update/free below runs inside the
9780 * driver's sweep phase (gc_sweeping_enter/exit); attribute it to GC_COMPACT_WALL_TIME
9781 * and exclude it from the driver's sweep wall time so the two do not double-count,
9782 * mirroring the compacting branch of the local gc_sweep(). */
9783 const bool driver_prof = gc_prof_enabled(driver);
9784 rb_hrtime_t driver_compact_wall_time = 0;
9785
9786 /* pass 1 (move): relocate every objspace and leave T_MOVED forwarding behind. */
9787 for (size_t i = 0; i < global_objspace->global_gc.n_objspaces; i++) {
9788 rb_objspace_t *os = global_objspace->global_gc.objspaces[i];
9789 gc_sweeping_enter(os);
9790 gc_sweep_start(os); /* mode -> sweeping, order the heap for compaction */
9791 rb_hrtime_t t0 = (os == driver && driver_prof) ? rb_hrtime_now() : 0;
9792 gc_compact_relocate(os); /* mode -> compacting, move */
9793 if (os == driver && driver_prof) {
9794 driver_compact_wall_time = rb_hrtime_add(driver_compact_wall_time, elapsed_hrtime_from(t0));
9795 }
9796 gc_sweeping_cpu_exit(os);
9797 }
9798
9799 /* pass 2 (update): all forwarding now exists, so update every objspace's
9800 * references (cross-objspace ones resolve too); gc_compact_finish also unprotects
9801 * pages and clears during_compacting. The move-or-mark decision reads
9802 * rb_gc_get_objspace()'s during_reference_updating: set it on every objspace. */
9803 gc_sweeping_cpu_enter(driver);
9804 for (size_t i = 0; i < global_objspace->global_gc.n_objspaces; i++) {
9805 global_objspace->global_gc.objspaces[i]->flags.during_reference_updating = TRUE;
9806 }
9807
9808 for (size_t i = 0; i < global_objspace->global_gc.n_objspaces; i++) {
9809 rb_objspace_t *objspace = global_objspace->global_gc.objspaces[i];
9810 for (int h = 0; h < HEAP_COUNT; h++) {
9811 gc_unprotect_pages(objspace, &heaps[h]);
9812 }
9813 }
9814 rb_gc_before_updating_jit_code();
9815 gc_sweeping_cpu_exit(driver);
9816 for (size_t i = 0; i < global_objspace->global_gc.n_objspaces; i++) {
9817 rb_objspace_t *os = global_objspace->global_gc.objspaces[i];
9818 gc_sweeping_cpu_enter(os);
9819 rb_hrtime_t t0 = (os == driver && driver_prof) ? rb_hrtime_now() : 0;
9820 gc_compact_finish(os);
9821 if (os == driver && driver_prof) {
9822 driver_compact_wall_time = rb_hrtime_add(driver_compact_wall_time, elapsed_hrtime_from(t0));
9823 }
9824 gc_sweeping_cpu_exit(os);
9825 }
9826 /* The VM-global / weak-table side of the reference update runs once (each objspace's
9827 * heap side already ran in gc_compact_finish above). */
9828 {
9829 gc_sweeping_cpu_enter(driver);
9830 rb_hrtime_t t0 = driver_prof ? rb_hrtime_now() : 0;
9831 gc_update_references_global(driver);
9832 if (driver_prof) {
9833 driver_compact_wall_time = rb_hrtime_add(driver_compact_wall_time, elapsed_hrtime_from(t0));
9834 }
9835 gc_sweeping_cpu_exit(driver);
9836 }
9837 gc_sweeping_cpu_enter(driver);
9838 rb_gc_after_updating_jit_code();
9839 for (size_t i = 0; i < global_objspace->global_gc.n_objspaces; i++) {
9840 global_objspace->global_gc.objspaces[i]->flags.during_reference_updating = FALSE;
9841 global_objspace->global_gc.objspaces[i]->flags.during_compacting = FALSE;
9842 }
9843 global_objspace->global_gc.compacting = false;
9844 uninstall_handlers();
9845 gc_sweeping_cpu_exit(driver);
9846
9847 /* Record the driver's compaction time and exclude it from the driver's sweep phase.
9848 * gc_sweeping_exit(driver) in pass 3 subtracts gc_sweep_excluded_wall_time from the
9849 * sweep wall time, so this must be set before it runs. The excluded value is a sum
9850 * of sub-intervals of the driver's sweep phase, so the subtraction cannot underflow. */
9851 if (driver_prof) {
9852 gc_profile_record *const record = gc_prof_record(driver);
9853 record->gc_compact_wall_time = rb_hrtime_add(record->gc_compact_wall_time,
9854 driver_compact_wall_time);
9855 driver->profile.gc_sweep_excluded_wall_time = rb_hrtime_add(
9856 driver->profile.gc_sweep_excluded_wall_time, driver_compact_wall_time);
9857 }
9858
9859 /* pass 3 (free): page-sweep every objspace, freeing dead objects and the source pages
9860 * that are now empty. during_compacting is already cleared, so the sweep treats
9861 * T_MOVED as usual. */
9862 for (size_t i = 0; i < global_objspace->global_gc.n_objspaces; i++) {
9863 rb_objspace_t *os = global_objspace->global_gc.objspaces[i];
9864 gc_sweeping_cpu_enter(os);
9865 gc_sweep_rest(os);
9866 gc_sweeping_exit(os);
9867 }
9868 }
9869 global_objspace->global_gc.compacting = false;
9870
9871 /* A global GC never calls gc_marks_finish, which budgets heap growth
9872 * (allocatable_bytes). An objspace still full after the global sweep (materializing
9873 * a large received copy, say) has no free pages, no empty pages, budget 0, and its next
9874 * allocation would hit newobj_refill's "cannot create a new page after a major GC".
9875 * Give every objspace stuck like that the growth budget gc_marks_finish would. */
9876 for (size_t i = 0; i < global_objspace->global_gc.n_objspaces; i++) {
9877 rb_objspace_t *objspace = global_objspace->global_gc.objspaces[i];
9878 if (objspace->heap_pages.allocatable_bytes != 0 || objspace->empty_pages_count != 0) {
9879 continue;
9880 }
9881 bool stuck = false;
9882 for (int h = 0; h < HEAP_COUNT; h++) {
9883 if (heaps[h].free_pages == NULL) { stuck = true; break; }
9884 }
9885 if (stuck) {
9886 heap_allocatable_bytes_expand(objspace, NULL, 0,
9887 objspace_available_slots(objspace), heaps[0].slot_size);
9888 }
9889 }
9890
9891 /* Recount the surviving shareable objects (the sweep already folded the dead ones out of
9892 * shareable_bits) and reset each trigger limit. */
9893 for (size_t i = 0; i < global_objspace->global_gc.n_objspaces; i++) {
9894 rb_objspace_t *objspace = global_objspace->global_gc.objspaces[i];
9895 size_t survivors = 0;
9896 for (int h = 0; h < HEAP_COUNT; h++) {
9897 struct heap_page *page = NULL;
9898 ccan_list_for_each(&heaps[h].pages, page, page_node) {
9899 if (!page->flags.has_shareable_objects) continue;
9900 for (int j = 0; j < HEAP_PAGE_BITMAP_LIMIT; j++) {
9901 survivors += rb_popcount_intptr(page->shareable_bits[j]);
9902 }
9903 }
9904 }
9905 objspace->shareable_objects = survivors;
9906 size_t new_limit = (size_t)(survivors * SHAREABLE_OBJECTS_LIMIT_FACTOR);
9907 if (new_limit < SHAREABLE_OBJECTS_LIMIT_MIN) new_limit = SHAREABLE_OBJECTS_LIMIT_MIN;
9908 objspace->shareable_objects_limit = new_limit;
9909 }
9910
9911 /* Deferred non-thread-safe frees: the world is already stopped here, so reap them
9912 * without a second barrier. Uses the driver's snapshot rather than taking its own,
9913 * which step 10 below still walks. */
9914 gc_tdata_unsafe_drain_objspaces(global_objspace->global_gc.objspaces,
9915 global_objspace->global_gc.n_objspaces);
9916 driver->profile.count++;
9917
9918 /* step 10 */
9919 for (size_t i = 0; i < global_objspace->global_gc.n_objspaces; i++) {
9920 rb_objspace_t *objspace = global_objspace->global_gc.objspaces[i];
9921 objspace->flags.during_global_gc = FALSE;
9922 if (objspace != driver) {
9923 during_gc = FALSE;
9924 gc_process_stat_publish(objspace);
9925 }
9926 }
9927
9928 /* The unified mark re-established the reachability of absorbed shareable objects, so a
9929 * single objspace's local mark is trustworthy again (pinning can be skipped until the
9930 * next absorb). */
9931 rb_gc_reset_absorbed_since_global_gc();
9932
9933 /* Re-measure the zombie_objspaces table now that the garbage is gone; entries are stable
9934 * inside the barrier. Without this, the page trigger above keeps firing on the stale
9935 * numbers left when a joinable (slotted) zombie retires without any pass merging it. */
9936 rb_gc_vm_refresh_zombie_pages();
9937 global_objspace->zombie_pages_survivors = rb_gc_vm_zombie_total_pages();
9938
9939 /* If the sweep above collected an unjoined Ractor object, ractor_free disowned its
9940 * zombie_objspaces entry and posted the merge to main as a postponed job; the objspace
9941 * stays enumerable until main absorbs it at its next safepoint. */
9942
9943 gc_prof_timer_stop(driver);
9944 gc_exit(driver, event, &lock_lev);
9945 return true;
9946}
9947
9948static int
9949absorb_finalizer_i(st_data_t key, st_data_t val, st_data_t data)
9950{
9952 st_insert(finalizer_table, key, val);
9953 return ST_CONTINUE;
9954}
9955
9956static void
9957gc_make_mid_mark_objspace_absorbable(rb_objspace_t *src)
9958{
9959 rb_objspace_t *objspace = src;
9960 for (int h = 0; h < HEAP_COUNT; h++) {
9961 struct heap_page *page = NULL;
9962 ccan_list_for_each(&heaps[h].pages, page, page_node) {
9963 short stride = page->slot_size;
9964 uintptr_t p = (uintptr_t)page->start;
9965 uintptr_t pend = p + page->total_slots * stride;
9966
9967 for (; p < pend; p += stride) {
9968 VALUE vp = (VALUE)p;
9969 asan_unpoisoning_object(vp) {
9970 switch (RB_BUILTIN_TYPE(vp)) {
9971 case T_NONE:
9972 case T_ZOMBIE:
9973 break;
9974 default:
9975 RVALUE_AGE_RESET(vp);
9976 break;
9977 }
9978 }
9979 }
9980 }
9981 gc_bitmaps_clear(objspace, &heaps[h], false);
9982 }
9983 objspace->rgengc.old_objects = 0;
9984 objspace->rgengc.uncollectible_wb_unprotected_objects = 0;
9985 objspace->marked_slots = 0;
9986}
9987
9988/* Merge a dead Ractor's objspace into dst under the VM lock. src has no owner thread and
9989 * dst is the calling thread's own objspace (join/value) or main with everyone stopped
9990 * (global GC), so single-writer holds throughout. Pages move whole (their bits describe
9991 * objects, not the objspace), and dst's next collection is forced full to rebuild the
9992 * generational state. */
9993static void
9994objspace_absorb(rb_objspace_t *dst, rb_objspace_t *src)
9995{
9996 GC_ASSERT(dst != src);
9997
9998 /* Suppress the cross-objspace verifier checks while the graph is in flux (see
9999 * global_objspace->during_absorb). */
10000 const bool prev_absorb = global_objspace->during_absorb;
10001 global_objspace->during_absorb = true;
10002
10003 /* Settle dst first: adding pages under a walking lazy-sweep cursor, or into a
10004 * half-marked incremental heap, would sweep the merged pages with src's stale mark
10005 * bits and free live objects. */
10006 gc_rest(dst);
10007
10008 /* Settle src: no incremental marking, lazy sweep or in-progress allocation page. */
10009 {
10010 rb_objspace_t *objspace = src;
10011 /* A zombie parked by fork (rb_ractor_terminate_atfork retires the objspace
10012 * without the retire GC) can be mid-incremental-mark, and that mark cannot be
10013 * finished. Its owner's threads did not survive the fork, so mark_roots would
10014 * scan the absorbing Ractor's roots instead of src's. Drop the cycle. */
10015 if (is_incremental_marking(objspace)) {
10016 gc_abort_incremental_marking(objspace);
10017 gc_make_mid_mark_objspace_absorbable(objspace);
10018 }
10019 gc_rest(src); // if mid-sweep
10020 heap_alloc_state_clear(objspace);
10021 /* gc_sweep_finish leaves swept pages "pooled" for a coming incremental mark; src
10022 * never runs one (it is about to be merged), so return them to its free list now,
10023 * restoring the pooled_pages == NULL the page merge below assumes (mirrors
10024 * gc_start_global step 3). */
10025 for (int h = 0; h < HEAP_COUNT; h++) {
10026 heap_move_pooled_pages_to_free_pages(&heaps[h]);
10027 }
10028 }
10029
10030 /* From here the merge must not run dst's GC: the finalizer st_insert below can cross
10031 * the malloc-accounting threshold, and a GC then would sweep src's detached finalizer
10032 * procs, reachable only from this C frame, into dangling VALUEs. Page/darray moves
10033 * allocate nothing (_without_gc), so disabling costs nothing and makes the splice
10034 * atomic. (The two settles above deliberately collect: they stay outside.) */
10035 const bool dst_gc_was_enabled = rb_gc_impl_gc_enabled_p(dst);
10036 if (dst_gc_was_enabled) rb_gc_impl_gc_disable(dst, false);
10037
10038 /* Hand over the pages size pool by size pool. ("heaps" is a macro over the local
10039 * objspace, so the arrays are taken through scoped locals.) */
10040 rb_heap_t *dst_heaps;
10041 rb_heap_t *src_heaps;
10042 {
10043 rb_objspace_t *objspace = dst;
10044 dst_heaps = heaps;
10045 }
10046 {
10047 rb_objspace_t *objspace = src;
10048 src_heaps = heaps;
10049 }
10050 for (int h = 0; h < HEAP_COUNT; h++) {
10051 rb_heap_t *dheap = &dst_heaps[h];
10052 rb_heap_t *sheap = &src_heaps[h];
10053 struct heap_page *page = NULL;
10054
10055 GC_ASSERT(sheap->sweeping_page == NULL);
10056 GC_ASSERT(sheap->pooled_pages == NULL);
10057
10058 ccan_list_for_each(&sheap->pages, page, page_node) {
10059 page->objspace = dst;
10060 page->heap = dheap;
10061 }
10062 ccan_list_append_list(&dheap->pages, &sheap->pages);
10063
10064 /* Append the free-page chain to the tail. */
10065 if (sheap->free_pages) {
10066 struct heap_page **tail = &dheap->free_pages;
10067 while (*tail) tail = &(*tail)->free_next;
10068 *tail = sheap->free_pages;
10069 sheap->free_pages = NULL;
10070 }
10071
10072 dheap->total_pages += sheap->total_pages;
10073 dheap->total_slots += sheap->total_slots;
10074 dheap->total_allocated_pages += sheap->total_allocated_pages;
10075 dheap->total_allocated_objects += sheap->total_allocated_objects;
10076 dheap->total_freed_objects += sheap->total_freed_objects;
10077 dheap->final_slots_count += sheap->final_slots_count;
10078 }
10079
10080 /* The objspace-wide page bookkeeping. */
10081 {
10082 rb_objspace_t *objspace = dst; /* for the heap_pages_* macros */
10083 struct heap_page *page = NULL;
10084 size_t srcn = rb_darray_size(src->heap_pages.sorted);
10085 for (size_t i = 0; i < srcn; i++) {
10086 page = rb_darray_get(src->heap_pages.sorted, i);
10087 /* Residents of the empty pool (no live objects) are returned to page_pool rather
10088 * than inherited; dst's allocation demand is cheaply met from the shared pool's
10089 * free list. */
10090 if (heap_page_in_global_empty_pages_pool(src, page)) {
10091 heap_page_free(src, page);
10092 continue;
10093 }
10094 uintptr_t body = (uintptr_t)page->body;
10095 uintptr_t start = body + sizeof(struct heap_page_header);
10096 uintptr_t end = body + HEAP_PAGE_SIZE;
10097
10098 /* Keep the array ordered by page BODY address: heap_page_for_ptr bsearches
10099 * body ranges, and a detached empty page has start == 0, so ordering by
10100 * page->start would miss live pages (a global GC would then fail to mark a
10101 * registered root and sweep it). */
10102 size_t lo = 0;
10103 size_t hi = rb_darray_size(objspace->heap_pages.sorted);
10104 while (lo < hi) {
10105 size_t mid = (lo + hi) / 2;
10106 struct heap_page *mid_page = rb_darray_get(objspace->heap_pages.sorted, mid);
10107 if ((uintptr_t)mid_page->body < body) lo = mid + 1;
10108 else hi = mid;
10109 }
10110 rb_darray_insert_without_gc(&objspace->heap_pages.sorted, hi, page);
10111
10112 if (heap_pages_lomem == 0 || heap_pages_lomem > start) heap_pages_lomem = start;
10113 if (heap_pages_himem < end) heap_pages_himem = end;
10114 }
10115 objspace->heap_pages.allocated_pages += src->heap_pages.allocated_pages;
10116 objspace->heap_pages.freed_pages += src->heap_pages.freed_pages;
10117 rb_darray_free_without_gc(src->heap_pages.sorted);
10118 src->heap_pages.sorted = NULL;
10119 /* The empty_pages chain's structs were freed in the loop above. */
10120 src->empty_pages = NULL;
10121 src->empty_pages_count = 0;
10122 }
10123
10124 /* Finalizers: move the table's entries, and the dead Ractor's deferred zombies are run
10125 * by dst's thread from now on. */
10126 {
10127 st_table *src_finalizers;
10128 {
10129 rb_objspace_t *objspace = src;
10130 src_finalizers = finalizer_table;
10131 finalizer_table = NULL;
10132 }
10133 if (src_finalizers) {
10134 rb_objspace_t *objspace = dst;
10135 if (finalizer_table == NULL) {
10136 finalizer_table = src_finalizers;
10137 }
10138 else {
10139 st_foreach(src_finalizers, absorb_finalizer_i, (st_data_t)dst);
10140 st_free_table(src_finalizers);
10141 }
10142 }
10143 }
10144 {
10145 VALUE src_deferred = RUBY_ATOMIC_VALUE_EXCHANGE(src->heap_pages.deferred_final, 0);
10146 if (src_deferred) {
10147 VALUE tail_obj = src_deferred;
10148 rb_asan_unpoison_object(tail_obj, false);
10149 while (RZOMBIE(tail_obj)->next) {
10150 VALUE next_obj = RZOMBIE(tail_obj)->next;
10151 rb_asan_poison_object(tail_obj);
10152 tail_obj = next_obj;
10153 rb_asan_unpoison_object(tail_obj, false);
10154 }
10155 VALUE prev;
10156 do {
10157 prev = dst->heap_pages.deferred_final;
10158 RZOMBIE(tail_obj)->next = prev;
10159 } while (RUBY_ATOMIC_VALUE_CAS(dst->heap_pages.deferred_final, prev, src_deferred) != prev);
10160 rb_asan_poison_object(tail_obj);
10161 /* No owner was left to run these zombies (register's owner walk misses a dead
10162 * Ractor). dst runs this merge, so schedule dst's job here; otherwise they wait
10163 * until dst's next GC. */
10164 rb_postponed_job_trigger(dst->finalize_deferred_pjob);
10165 }
10166 }
10167 if (src->tdata_unsafe_free_chunk) {
10168 gc_tdata_unsafe_free_publish(src);
10169 }
10170 if (tdata_deferred_free_count_load() >= TDATA_DEFERRED_FREE_THRESHOLD) {
10171 gc_tdata_deferred_free_trigger(dst);
10172 }
10173
10174 /* Counters inherited by dst. */
10175 dst->rgengc.old_objects += src->rgengc.old_objects;
10176 dst->rgengc.uncollectible_wb_unprotected_objects += src->rgengc.uncollectible_wb_unprotected_objects;
10177 dst->shareable_objects += src->shareable_objects;
10178
10179 /* Merged pages carry src's mark/age state, so dst rebuilds its view at the next
10180 * collection. Note that this can be worked around by calling `GC.config(rgengc_allow_full_mark: false)`,
10181 * so the absorbed heap should be in a state where a minor GC would also work correctly.
10182 */
10183 dst->rgengc.need_major_gc |= GPR_FLAG_MAJOR_BY_FORCE;
10184
10185 /* src's outstanding malloc pressure moves with the xmalloc'd buffers. Later frees are
10186 * charged to dst, so without this transfer dst underestimates its own heap and delays
10187 * GCs. dst is live, so take its counter lock where gc_counter_add is not atomic. */
10188 {
10189 int64_t inc = gc_malloc_counters_increase(src, &src->malloc_counters.counters);
10190#if RGENGC_ESTIMATE_OLDMALLOC
10191 int64_t oldinc = gc_malloc_counters_increase(src, &src->malloc_counters.oldcounters);
10192#endif
10193 MALLOC_COUNTERS_LOCK(dst);
10194 if (inc > 0) gc_counter_add(&dst->malloc_counters.counters.malloc, (size_t)inc);
10195#if RGENGC_ESTIMATE_OLDMALLOC
10196 if (oldinc > 0) gc_counter_add(&dst->malloc_counters.oldcounters.malloc, (size_t)oldinc);
10197#endif
10198 MALLOC_COUNTERS_UNLOCK(dst);
10199 }
10200
10201 {
10202 struct gc_process_stat_snapshot final_snap;
10203 gc_process_stat_capture(src, &final_snap);
10204 gc_process_stat_add(&global_objspace->process_stat_archive, &final_snap);
10205 }
10206 rb_native_mutex_destroy(&src->process_stat.lock);
10207
10208 /* Free the shell (as rb_gc_impl_objspace_free does). */
10209 free(src->profile.records);
10210 free_stack_chunks(&src->mark_stack);
10211 mark_stack_free_cache(&src->mark_stack);
10212 GC_ASSERT(rb_darray_size(src->weak_references) == 0);
10213 rb_darray_free_without_gc(src->weak_references);
10214#ifdef MALLOC_COUNTERS_NEED_LOCK
10215 rb_native_mutex_destroy(&src->malloc_counters.lock);
10216#endif
10217 free(src);
10218
10219 if (dst_gc_was_enabled) rb_gc_impl_gc_enable(dst);
10220
10221 /* Return the empty pages inheritance piled up in dst (mostly from the dead Ractor's
10222 * teardown material) to the pool with no budget. An empty page is by definition safe to
10223 * release, and re-acquiring one from the pool is cheap. */
10224 {
10225 rb_objspace_t *objspace = dst;
10226 heap_pages_freeable_pages = objspace->empty_pages_count;
10227 heap_pages_free_unused_pages(objspace);
10228 }
10229
10230 global_objspace->during_absorb = prev_absorb;
10231}
10232
10233void
10234rb_gc_impl_objspace_absorb(void *dst_ptr, void *src_ptr)
10235{
10236 objspace_absorb(dst_ptr, src_ptr);
10237}
10238
10239void
10240rb_gc_impl_start(void *objspace_ptr, bool full_mark, bool immediate_mark, bool immediate_sweep, bool compact, bool global)
10241{
10242 rb_objspace_t *objspace = objspace_ptr;
10243 unsigned int reason = (GPR_FLAG_FULL_MARK |
10244 GPR_FLAG_IMMEDIATE_MARK |
10245 GPR_FLAG_IMMEDIATE_SWEEP |
10246 GPR_FLAG_METHOD);
10247
10248 int full_marking_p = gc_config_full_mark_val;
10249 gc_config_full_mark_set(TRUE);
10250
10251 /* For now, compact implies full mark / sweep, so ignore other flags */
10252 if (compact) {
10253 GC_ASSERT(GC_COMPACTION_SUPPORTED);
10254
10255 reason |= GPR_FLAG_COMPACT;
10256 if (!rb_gc_single_objspace_p()) {
10257 global = true;
10258 }
10259 }
10260 else {
10261 if (!full_mark) reason &= ~GPR_FLAG_FULL_MARK;
10262 if (!immediate_mark) reason &= ~GPR_FLAG_IMMEDIATE_MARK;
10263 if (!immediate_sweep) reason &= ~GPR_FLAG_IMMEDIATE_SWEEP;
10264 }
10265
10266 if ((reason & (GPR_FLAG_FULL_MARK | GPR_FLAG_IMMEDIATE_MARK | GPR_FLAG_IMMEDIATE_SWEEP)) !=
10267 (GPR_FLAG_FULL_MARK | GPR_FLAG_IMMEDIATE_MARK | GPR_FLAG_IMMEDIATE_SWEEP)) {
10268 global = false;
10269 }
10270
10271 if (global && !rb_gc_single_objspace_p()) {
10272 /* A mid-cycle driver is settled by gc_start_global itself: it aborts the partial
10273 * mark and finishes the lazy sweep, so the dead slots are T_NONE before the
10274 * unified conservative root scan. */
10275 gc_start_global(objspace, reason, compact || ruby_enable_autocompact, false);
10276 }
10277 else {
10278 garbage_collect(objspace, reason);
10279 }
10280
10281 gc_finalize_deferred(objspace);
10282 /* An explicit GC.start is expected to reclaim immediately, so run the deferred non-thread-safe
10283 * frees synchronously instead of leaving them to gc_sweep_finish's postponed job. */
10284 if (tdata_deferred_free_count_load() > 0 && rb_gc_single_objspace_p()) {
10285 gc_tdata_unsafe_drain();
10286 }
10287 gc_config_full_mark_set(full_marking_p);
10288}
10289
10290void
10291rb_gc_impl_prepare_heap(void *objspace_ptr)
10292{
10293 rb_objspace_t *objspace = objspace_ptr;
10294
10295 rb_gc_impl_each_objects(objspace, gc_set_candidate_object_i, objspace_ptr);
10296
10297 double orig_max_free_slots = gc_params.heap_free_slots_max_ratio;
10298 /* Ensure that all empty pages are moved onto empty_pages. */
10299 gc_params.heap_free_slots_max_ratio = 0.0;
10300 rb_gc_impl_start(objspace, true, true, true, true, true);
10301 gc_params.heap_free_slots_max_ratio = orig_max_free_slots;
10302
10303 objspace->heap_pages.allocatable_bytes = 0;
10304 heap_pages_freeable_pages = objspace->empty_pages_count;
10305 heap_pages_free_unused_pages(objspace_ptr);
10306 GC_ASSERT(heap_pages_freeable_pages == 0);
10307 GC_ASSERT(objspace->empty_pages_count == 0);
10308
10309 // Process.warmup is meant to be called at the end of the boot sequence, which is commonly allocation
10310 // heavy and result in GC limits raising significantly, but it's not indicative of the limits needed
10311 // for runtime.
10312 // Recompute the allocatable_bytes limit based on `gc_params.heap_init_bytes`.
10313 GC_ASSERT(objspace->heap_pages.allocatable_bytes == 0);
10314 for (int i = 0; i < HEAP_COUNT; i++) {
10315 rb_heap_t *heap = &heaps[i];
10316 heap_allocatable_bytes_expand(objspace, heap, heap->empty_slots, heap->total_slots, heap->slot_size);
10317 }
10318
10319#if defined(HAVE_MALLOC_TRIM) && !defined(RUBY_ALTERNATIVE_MALLOC_HEADER)
10320 malloc_trim(0);
10321#endif
10322}
10323
10324static int
10325gc_is_moveable_obj(rb_objspace_t *objspace, VALUE obj)
10326{
10327 GC_ASSERT(!SPECIAL_CONST_P(obj));
10328
10329 switch (BUILTIN_TYPE(obj)) {
10330 case T_NONE:
10331 case T_MOVED:
10332 case T_ZOMBIE:
10333 return FALSE;
10334 case T_SYMBOL:
10335 case T_STRING:
10336 case T_OBJECT:
10337 case T_FLOAT:
10338 case T_IMEMO:
10339 case T_ARRAY:
10340 case T_BIGNUM:
10341 case T_ICLASS:
10342 case T_MODULE:
10343 case T_REGEXP:
10344 case T_DATA:
10345 case T_MATCH:
10346 case T_STRUCT:
10347 case T_HASH:
10348 case T_FILE:
10349 case T_COMPLEX:
10350 case T_RATIONAL:
10351 case T_NODE:
10352 case T_CLASS:
10353 if (FL_TEST_RAW(obj, FL_FINALIZE)) {
10354 /* The finalizer table is a numtable. It looks up objects by address.
10355 * We can't mark the keys in the finalizer table because that would
10356 * prevent the objects from being collected. This check prevents
10357 * objects that are keys in the finalizer table from being moved
10358 * without directly pinning them. */
10359 GC_ASSERT(st_is_member(finalizer_table, obj));
10360
10361 return FALSE;
10362 }
10363 GC_ASSERT(RVALUE_MARKED(objspace, obj));
10364 GC_ASSERT(!RVALUE_PINNED(objspace, obj));
10365
10366 return TRUE;
10367
10368 default:
10369 rb_bug("gc_is_moveable_obj: unreachable (%d)", (int)BUILTIN_TYPE(obj));
10370 break;
10371 }
10372
10373 return FALSE;
10374}
10375
10376void rb_mv_generic_ivar(VALUE src, VALUE dst);
10377
10378static VALUE
10379gc_move(rb_objspace_t *objspace, VALUE src, VALUE dest, struct heap_page *src_page, struct heap_page *dest_page)
10380{
10381 size_t src_slot_size = src_page->slot_size;
10382 size_t slot_size = dest_page->slot_size;
10383
10384 int marked;
10385 int wb_unprotected;
10386 int uncollectible;
10387 int age;
10388
10389 gc_report(4, objspace, "Moving object: %p -> %p\n", (void *)src, (void *)dest);
10390
10391 GC_ASSERT(BUILTIN_TYPE(src) != T_NONE);
10392 GC_ASSERT(!MARKED_IN_BITMAP(GET_HEAP_MARK_BITS(dest), dest));
10393
10394 GC_ASSERT(!RVALUE_MARKING(objspace, src));
10395
10396 /* Save off bits for current object. */
10397 marked = RVALUE_MARKED(objspace, src);
10398 wb_unprotected = RVALUE_WB_UNPROTECTED(objspace, src);
10399 uncollectible = RVALUE_UNCOLLECTIBLE(objspace, src);
10400 bool remembered = RVALUE_REMEMBERED(objspace, src);
10401 /* Pin bits travel with the object. Losing one during single-objspace compaction would
10402 * silently unpin it once the process goes multi-objspace, letting a local GC free a method
10403 * entry or shref target that another Ractor references. */
10404 bool shareable = MARKED_IN_BITMAP(GET_HEAP_SHAREABLE_BITS(src), src) != 0;
10405 bool shref = MARKED_IN_BITMAP(GET_HEAP_SHREF_BITS(src), src) != 0;
10406 age = RVALUE_AGE_GET(src);
10407
10408 /* Clear bits for eventual T_MOVED */
10409 CLEAR_IN_BITMAP(GET_HEAP_MARK_BITS(src), src);
10410 CLEAR_IN_BITMAP(GET_HEAP_WB_UNPROTECTED_BITS(src), src);
10411 CLEAR_IN_BITMAP(GET_HEAP_UNCOLLECTIBLE_BITS(src), src);
10412 CLEAR_IN_BITMAP(GET_HEAP_PAGE(src)->remembered_bits, src);
10413 CLEAR_IN_BITMAP(GET_HEAP_SHAREABLE_BITS(src), src);
10414 CLEAR_IN_BITMAP(GET_HEAP_SHREF_BITS(src), src);
10415
10416 /* Move the object */
10417 memcpy((void *)dest, (void *)src, MIN(src_slot_size, slot_size));
10418
10419 if (src_slot_size != slot_size) {
10420 rb_gc_obj_changed_slot_size(dest, slot_size - RVALUE_OVERHEAD);
10421 }
10422
10423 if (RVALUE_OVERHEAD > 0) {
10424 void *dest_overhead = (void *)(((uintptr_t)dest) + slot_size - RVALUE_OVERHEAD);
10425 void *src_overhead = (void *)(((uintptr_t)src) + src_slot_size - RVALUE_OVERHEAD);
10426
10427 memcpy(dest_overhead, src_overhead, RVALUE_OVERHEAD);
10428 }
10429
10430 memset((void *)src, 0, src_slot_size);
10431 RVALUE_AGE_SET_BITMAP(src, 0);
10432
10433 /* Set bits for object in new location */
10434 if (remembered) {
10435 MARK_IN_BITMAP(GET_HEAP_PAGE(dest)->remembered_bits, dest);
10436 }
10437 else {
10438 CLEAR_IN_BITMAP(GET_HEAP_PAGE(dest)->remembered_bits, dest);
10439 }
10440
10441 if (marked) {
10442 MARK_IN_BITMAP(GET_HEAP_MARK_BITS(dest), dest);
10443 }
10444 else {
10445 CLEAR_IN_BITMAP(GET_HEAP_MARK_BITS(dest), dest);
10446 }
10447
10448 if (wb_unprotected) {
10449 MARK_IN_BITMAP(GET_HEAP_WB_UNPROTECTED_BITS(dest), dest);
10450 }
10451 else {
10452 CLEAR_IN_BITMAP(GET_HEAP_WB_UNPROTECTED_BITS(dest), dest);
10453 }
10454
10455 if (uncollectible) {
10456 MARK_IN_BITMAP(GET_HEAP_UNCOLLECTIBLE_BITS(dest), dest);
10457 }
10458 else {
10459 CLEAR_IN_BITMAP(GET_HEAP_UNCOLLECTIBLE_BITS(dest), dest);
10460 }
10461
10462 if (shareable) {
10463 MARK_IN_BITMAP(GET_HEAP_SHAREABLE_BITS(dest), dest);
10464 GET_HEAP_PAGE(dest)->flags.has_shareable_objects = TRUE;
10465 }
10466 else {
10467 CLEAR_IN_BITMAP(GET_HEAP_SHAREABLE_BITS(dest), dest);
10468 }
10469
10470 if (shref) {
10471 MARK_IN_BITMAP(GET_HEAP_SHREF_BITS(dest), dest);
10472 GET_HEAP_PAGE(dest)->flags.has_shref_objects = TRUE;
10473 }
10474 else {
10475 CLEAR_IN_BITMAP(GET_HEAP_SHREF_BITS(dest), dest);
10476 }
10477
10478 RVALUE_AGE_SET(dest, age);
10479
10480 /* A re-embedded object (rb_gc_obj_changed_slot_size) references its
10481 * former fields_obj's contents directly; the write-barrier history
10482 * lived on the discarded fields_obj, so remember the object. */
10483 if (src_slot_size != slot_size && age >= RVALUE_OLD_AGE && !remembered) {
10484 rgengc_remember(objspace, dest);
10485 }
10486
10487 /* Assign forwarding address */
10488 RMOVED(src)->flags = T_MOVED;
10489 RMOVED(src)->dummy = Qundef;
10490 RMOVED(src)->destination = dest;
10491 GC_ASSERT(BUILTIN_TYPE(dest) != T_NONE);
10492
10493 GET_HEAP_PAGE(src)->heap->total_freed_objects++;
10494 GET_HEAP_PAGE(dest)->heap->total_allocated_objects++;
10495
10496 return src;
10497}
10498
10499#if GC_CAN_COMPILE_COMPACTION
10500static int
10501compare_pinned_slots(const void *left, const void *right, void *dummy)
10502{
10503 struct heap_page *left_page;
10504 struct heap_page *right_page;
10505
10506 left_page = *(struct heap_page * const *)left;
10507 right_page = *(struct heap_page * const *)right;
10508
10509 return left_page->pinned_slots - right_page->pinned_slots;
10510}
10511
10512static int
10513compare_free_slots(const void *left, const void *right, void *dummy)
10514{
10515 struct heap_page *left_page;
10516 struct heap_page *right_page;
10517
10518 left_page = *(struct heap_page * const *)left;
10519 right_page = *(struct heap_page * const *)right;
10520
10521 return left_page->free_slots - right_page->free_slots;
10522}
10523
10524static void
10525gc_sort_heap_by_compare_func(rb_objspace_t *objspace, gc_compact_compare_func compare_func)
10526{
10527 for (int j = 0; j < HEAP_COUNT; j++) {
10528 rb_heap_t *heap = &heaps[j];
10529
10530 size_t total_pages = heap->total_pages;
10531 size_t size = rb_size_mul_or_raise(total_pages, sizeof(struct heap_page *), rb_eRuntimeError);
10532 struct heap_page *page = 0, **page_list = malloc(size);
10533 size_t i = 0;
10534
10535 heap->free_pages = NULL;
10536 ccan_list_for_each(&heap->pages, page, page_node) {
10537 page_list[i++] = page;
10538 GC_ASSERT(page);
10539 }
10540
10541 GC_ASSERT((size_t)i == total_pages);
10542
10543 /* Sort the heap so "filled pages" are first. `heap_add_page` adds to the
10544 * head of the list, so empty pages will end up at the start of the heap */
10545 ruby_qsort(page_list, total_pages, sizeof(struct heap_page *), compare_func, NULL);
10546
10547 /* Reset the eden heap */
10548 ccan_list_head_init(&heap->pages);
10549
10550 for (i = 0; i < total_pages; i++) {
10551 ccan_list_add(&heap->pages, &page_list[i]->page_node);
10552 if (page_list[i]->free_slots != 0) {
10553 heap_add_freepage(heap, page_list[i]);
10554 }
10555 }
10556
10557 free(page_list);
10558 }
10559}
10560#endif
10561
10562void
10563rb_gc_impl_register_pinning_obj(void *objspace_ptr, VALUE obj)
10564{
10565 /* no-op */
10566}
10567
10568bool
10569rb_gc_impl_object_moved_p(void *objspace_ptr, VALUE obj)
10570{
10571 return gc_object_moved_p(objspace_ptr, obj);
10572}
10573
10574static int
10575gc_ref_update(void *vstart, void *vend, size_t stride, rb_objspace_t *objspace, struct heap_page *page)
10576{
10577 VALUE v = (VALUE)vstart;
10578
10579 page->flags.has_uncollectible_wb_unprotected_objects = FALSE;
10580 page->flags.has_remembered_objects = FALSE;
10581
10582 /* For each object on the page */
10583 for (; v != (VALUE)vend; v += stride) {
10584 asan_unpoisoning_object(v) {
10585 switch (BUILTIN_TYPE(v)) {
10586 case T_NONE:
10587 case T_MOVED:
10588 case T_ZOMBIE:
10589 break;
10590 default:
10591 if (RVALUE_WB_UNPROTECTED(objspace, v)) {
10592 page->flags.has_uncollectible_wb_unprotected_objects = TRUE;
10593 }
10594 if (RVALUE_REMEMBERED(objspace, v)) {
10595 page->flags.has_remembered_objects = TRUE;
10596 }
10597 if (page->flags.before_sweep) {
10598 if (RVALUE_MARKED(objspace, v)) {
10599 rb_gc_update_object_references(objspace, v);
10600 }
10601 }
10602 else {
10603 rb_gc_update_object_references(objspace, v);
10604 }
10605 }
10606 }
10607 }
10608
10609 return 0;
10610}
10611
10612static int
10613gc_update_references_weak_table_i(VALUE obj, void *data)
10614{
10615 int ret;
10616 asan_unpoisoning_object(obj) {
10617 ret = BUILTIN_TYPE(obj) == T_MOVED ? ST_REPLACE : ST_CONTINUE;
10618 }
10619 return ret;
10620}
10621
10622static int
10623gc_update_references_weak_table_replace_i(VALUE *obj, void *data)
10624{
10625 rb_gc_update_moved(obj);
10626
10627 return ST_CONTINUE;
10628}
10629
10630/* The per-objspace side of the reference update: walk this objspace's heap objects and rewrite
10631 * moved references (following T_MOVED forwarding across objspaces). A compacting global GC
10632 * runs this for every objspace. */
10633static void
10634gc_update_references_heap(rb_objspace_t *objspace)
10635{
10636 struct heap_page *page = NULL;
10637
10638 for (int i = 0; i < HEAP_COUNT; i++) {
10639 bool should_set_mark_bits = TRUE;
10640 rb_heap_t *heap = &heaps[i];
10641
10642 ccan_list_for_each(&heap->pages, page, page_node) {
10643 uintptr_t start = (uintptr_t)page->start;
10644 uintptr_t end = start + (page->total_slots * heap->slot_size);
10645
10646 gc_ref_update((void *)start, (void *)end, heap->slot_size, objspace, page);
10647 if (page == heap->sweeping_page) {
10648 should_set_mark_bits = FALSE;
10649 }
10650 if (should_set_mark_bits) {
10651 gc_setup_mark_bits(page);
10652 }
10653 }
10654 }
10655}
10656
10657/* The VM-global side of the reference update (finalizer table, every Ractor's VM roots,
10658 * weak tables). Process-wide, so a compacting global GC runs it once after every heap
10659 * side: rb_gc_update_vm_references and the weak tables' mark_and_move are not idempotent. */
10660static void
10661gc_update_references_global(rb_objspace_t *objspace)
10662{
10663 gc_update_table_refs(finalizer_table);
10664
10665 rb_gc_update_vm_references((void *)objspace);
10666
10667 for (int table = 0; table < RB_GC_VM_WEAK_TABLE_COUNT; table++) {
10668 rb_gc_vm_weak_table_foreach(
10669 gc_update_references_weak_table_i,
10670 gc_update_references_weak_table_replace_i,
10671 NULL,
10672 false,
10673 table
10674 );
10675 }
10676}
10677
10678static void
10679gc_update_references(rb_objspace_t *objspace)
10680{
10681 objspace->flags.during_reference_updating = true;
10682
10683 rb_gc_before_updating_jit_code();
10684
10685 gc_update_references_heap(objspace);
10686 gc_update_references_global(objspace);
10687
10688 rb_gc_after_updating_jit_code();
10689
10690 objspace->flags.during_reference_updating = false;
10691}
10692
10693#if GC_CAN_COMPILE_COMPACTION
10694static void
10695root_obj_check_moved_i(const char *category, VALUE obj, void *data)
10696{
10697 rb_objspace_t *objspace = data;
10698
10699 if (gc_object_moved_p(objspace, obj)) {
10700 rb_bug("ROOT %s points to MOVED: %p -> %s", category, (void *)obj, rb_obj_info(rb_gc_impl_location(objspace, obj)));
10701 }
10702}
10703
10704static void
10705reachable_object_check_moved_i(VALUE ref, void *data)
10706{
10707 VALUE parent = (VALUE)data;
10708 if (gc_object_moved_p(rb_gc_get_objspace(), ref)) {
10709 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)));
10710 }
10711}
10712
10713static int
10714heap_check_moved_i(void *vstart, void *vend, size_t stride, void *data)
10715{
10716 rb_objspace_t *objspace = data;
10717
10718 VALUE v = (VALUE)vstart;
10719 for (; v != (VALUE)vend; v += stride) {
10720 if (gc_object_moved_p(objspace, v)) {
10721 /* Moved object still on the heap, something may have a reference. */
10722 }
10723 else {
10724 asan_unpoisoning_object(v) {
10725 switch (BUILTIN_TYPE(v)) {
10726 case T_NONE:
10727 case T_ZOMBIE:
10728 break;
10729 default:
10730 if (!rb_gc_impl_garbage_object_p(objspace, v)) {
10731 rb_objspace_reachable_objects_from_unlocked(v, reachable_object_check_moved_i, (void *)v);
10732 }
10733 }
10734 }
10735 }
10736 }
10737
10738 return 0;
10739}
10740#endif
10741
10742bool
10743rb_gc_impl_during_gc_p(void *objspace_ptr)
10744{
10745 rb_objspace_t *objspace = objspace_ptr;
10746
10747 return during_gc;
10748}
10749
10750#if RGENGC_PROFILE >= 2
10751
10752static const char*
10753type_name(int type, VALUE obj)
10754{
10755 switch ((enum ruby_value_type)type) {
10756 case RUBY_T_NONE: return "T_NONE";
10757 case RUBY_T_OBJECT: return "T_OBJECT";
10758 case RUBY_T_CLASS: return "T_CLASS";
10759 case RUBY_T_MODULE: return "T_MODULE";
10760 case RUBY_T_FLOAT: return "T_FLOAT";
10761 case RUBY_T_STRING: return "T_STRING";
10762 case RUBY_T_REGEXP: return "T_REGEXP";
10763 case RUBY_T_ARRAY: return "T_ARRAY";
10764 case RUBY_T_HASH: return "T_HASH";
10765 case RUBY_T_STRUCT: return "T_STRUCT";
10766 case RUBY_T_BIGNUM: return "T_BIGNUM";
10767 case RUBY_T_FILE: return "T_FILE";
10768 case RUBY_T_DATA: return "T_DATA";
10769 case RUBY_T_MATCH: return "T_MATCH";
10770 case RUBY_T_COMPLEX: return "T_COMPLEX";
10771 case RUBY_T_RATIONAL: return "T_RATIONAL";
10772 case RUBY_T_NIL: return "T_NIL";
10773 case RUBY_T_TRUE: return "T_TRUE";
10774 case RUBY_T_FALSE: return "T_FALSE";
10775 case RUBY_T_SYMBOL: return "T_SYMBOL";
10776 case RUBY_T_FIXNUM: return "T_FIXNUM";
10777 case RUBY_T_UNDEF: return "T_UNDEF";
10778 case RUBY_T_IMEMO: return "T_IMEMO";
10779 case RUBY_T_NODE: return "T_NODE";
10780 case RUBY_T_ICLASS: return "T_ICLASS";
10781 case RUBY_T_ZOMBIE: return "T_ZOMBIE";
10782 case RUBY_T_MOVED: return "T_MOVED";
10783 default: return "unknown";
10784 }
10785}
10786
10787static void
10788gc_count_add_each_types(VALUE hash, const char *name, const size_t *types)
10789{
10790 VALUE result = rb_hash_new_capa(T_MASK);
10791 int i;
10792 for (i=0; i<T_MASK; i++) {
10793 const char *type = type_name(i, 0);
10794 rb_hash_aset(result, ID2SYM(rb_intern(type)), SIZET2NUM(types[i]));
10795 }
10796 rb_hash_aset(hash, ID2SYM(rb_intern(name)), result);
10797}
10798#endif
10799
10800size_t
10801rb_gc_impl_gc_count(void *objspace_ptr)
10802{
10803 rb_objspace_t *objspace = objspace_ptr;
10804
10805 return objspace->profile.count;
10806}
10807
10808/* Filled by setup_gc_latest_gc_info_symbols() at boot, not on first use. */
10809static VALUE sym_major_by, sym_gc_by, sym_immediate_sweep, sym_have_finalizer, sym_state, sym_need_major_by;
10810static VALUE sym_nofree, sym_oldgen, sym_shady, sym_force, sym_stress;
10811#if RGENGC_ESTIMATE_OLDMALLOC
10812static VALUE sym_oldmalloc;
10813#endif
10814static VALUE sym_newobj, sym_malloc, sym_method, sym_capi;
10815static VALUE sym_none, sym_marking, sym_sweeping;
10816static VALUE sym_weak_references_count;
10817
10818static void
10819setup_gc_latest_gc_info_symbols(void)
10820{
10821#define S(s) sym_##s = ID2SYM(rb_intern_const(#s))
10822 S(major_by);
10823 S(gc_by);
10824 S(immediate_sweep);
10825 S(have_finalizer);
10826 S(state);
10827 S(need_major_by);
10828
10829 S(stress);
10830 S(nofree);
10831 S(oldgen);
10832 S(shady);
10833 S(force);
10834#if RGENGC_ESTIMATE_OLDMALLOC
10835 S(oldmalloc);
10836#endif
10837 S(newobj);
10838 S(malloc);
10839 S(method);
10840 S(capi);
10841
10842 S(none);
10843 S(marking);
10844 S(sweeping);
10845
10846 S(weak_references_count);
10847#undef S
10848}
10849
10850static VALUE
10851gc_info_decode(rb_objspace_t *objspace, const VALUE hash_or_key, const unsigned int orig_flags)
10852{
10853 VALUE hash = Qnil, key = Qnil;
10854 VALUE major_by, need_major_by;
10855 unsigned int flags = orig_flags ? orig_flags : objspace->profile.latest_gc_info;
10856
10857 if (SYMBOL_P(hash_or_key)) {
10858 key = hash_or_key;
10859 }
10860 else if (RB_TYPE_P(hash_or_key, T_HASH)) {
10861 hash = hash_or_key;
10862 }
10863 else {
10864 rb_bug("gc_info_decode: non-hash or symbol given");
10865 }
10866
10867#define SET(name, attr) \
10868 if (key == sym_##name) \
10869 return (attr); \
10870 else if (hash != Qnil) \
10871 rb_hash_aset(hash, sym_##name, (attr));
10872
10873 major_by =
10874 (flags & GPR_FLAG_MAJOR_BY_NOFREE) ? sym_nofree :
10875 (flags & GPR_FLAG_MAJOR_BY_OLDGEN) ? sym_oldgen :
10876 (flags & GPR_FLAG_MAJOR_BY_SHADY) ? sym_shady :
10877 (flags & GPR_FLAG_MAJOR_BY_FORCE) ? sym_force :
10878#if RGENGC_ESTIMATE_OLDMALLOC
10879 (flags & GPR_FLAG_MAJOR_BY_OLDMALLOC) ? sym_oldmalloc :
10880#endif
10881 Qnil;
10882 SET(major_by, major_by);
10883
10884 if (orig_flags == 0) { /* set need_major_by only if flags not set explicitly */
10885 unsigned int need_major_flags = gc_needs_major_flags;
10886 need_major_by =
10887 (need_major_flags & GPR_FLAG_MAJOR_BY_NOFREE) ? sym_nofree :
10888 (need_major_flags & GPR_FLAG_MAJOR_BY_OLDGEN) ? sym_oldgen :
10889 (need_major_flags & GPR_FLAG_MAJOR_BY_SHADY) ? sym_shady :
10890 (need_major_flags & GPR_FLAG_MAJOR_BY_FORCE) ? sym_force :
10891#if RGENGC_ESTIMATE_OLDMALLOC
10892 (need_major_flags & GPR_FLAG_MAJOR_BY_OLDMALLOC) ? sym_oldmalloc :
10893#endif
10894 Qnil;
10895 SET(need_major_by, need_major_by);
10896 }
10897
10898 SET(gc_by,
10899 (flags & GPR_FLAG_NEWOBJ) ? sym_newobj :
10900 (flags & GPR_FLAG_MALLOC) ? sym_malloc :
10901 (flags & GPR_FLAG_METHOD) ? sym_method :
10902 (flags & GPR_FLAG_CAPI) ? sym_capi :
10903 (flags & GPR_FLAG_STRESS) ? sym_stress :
10904 Qnil
10905 );
10906
10907 SET(have_finalizer, (flags & GPR_FLAG_HAVE_FINALIZE) ? Qtrue : Qfalse);
10908 SET(immediate_sweep, (flags & GPR_FLAG_IMMEDIATE_SWEEP) ? Qtrue : Qfalse);
10909
10910 if (orig_flags == 0) {
10911 SET(state, gc_mode(objspace) == gc_mode_none ? sym_none :
10912 gc_mode(objspace) == gc_mode_marking ? sym_marking : sym_sweeping);
10913 }
10914
10915 SET(weak_references_count, LONG2FIX(objspace->profile.weak_references_count));
10916#undef SET
10917
10918 if (!NIL_P(key)) {
10919 // Matched key should return above
10920 return Qundef;
10921 }
10922
10923 return hash;
10924}
10925
10926VALUE
10927rb_gc_impl_latest_gc_info(void *objspace_ptr, VALUE key)
10928{
10929 rb_objspace_t *objspace = objspace_ptr;
10930
10931 return gc_info_decode(objspace, key, 0);
10932}
10933
10934
10935enum gc_stat_sym {
10936 gc_stat_sym_count,
10937 gc_stat_sym_time,
10938 gc_stat_sym_marking_time,
10939 gc_stat_sym_sweeping_time,
10940 gc_stat_sym_heap_allocated_pages,
10941 gc_stat_sym_heap_empty_pages,
10942 gc_stat_sym_heap_allocatable_bytes,
10943 gc_stat_sym_heap_available_slots,
10944 gc_stat_sym_heap_live_slots,
10945 gc_stat_sym_heap_free_slots,
10946 gc_stat_sym_heap_final_slots,
10947 gc_stat_sym_heap_marked_slots,
10948 gc_stat_sym_heap_eden_pages,
10949 gc_stat_sym_total_allocated_pages,
10950 gc_stat_sym_total_freed_pages,
10951 gc_stat_sym_total_allocated_objects,
10952 gc_stat_sym_total_freed_objects,
10953 gc_stat_sym_total_malloc_bytes,
10954 gc_stat_sym_total_free_bytes,
10955 gc_stat_sym_malloc_increase_bytes,
10956 gc_stat_sym_malloc_increase_bytes_limit,
10957 gc_stat_sym_minor_gc_count,
10958 gc_stat_sym_major_gc_count,
10959 gc_stat_sym_global_gc_count,
10960 gc_stat_sym_compact_count,
10961 gc_stat_sym_read_barrier_faults,
10962 gc_stat_sym_total_moved_objects,
10963 gc_stat_sym_remembered_wb_unprotected_objects,
10964 gc_stat_sym_remembered_wb_unprotected_objects_limit,
10965 gc_stat_sym_old_objects,
10966 gc_stat_sym_old_objects_limit,
10967#if RGENGC_ESTIMATE_OLDMALLOC
10968 gc_stat_sym_oldmalloc_increase_bytes,
10969 gc_stat_sym_oldmalloc_increase_bytes_limit,
10970#endif
10971#if RGENGC_PROFILE
10972 gc_stat_sym_total_generated_normal_object_count,
10973 gc_stat_sym_total_generated_shady_object_count,
10974 gc_stat_sym_total_shade_operation_count,
10975 gc_stat_sym_total_promoted_count,
10976 gc_stat_sym_total_remembered_normal_object_count,
10977 gc_stat_sym_total_remembered_shady_object_count,
10978#endif
10979 gc_stat_sym_page_pool_arenas,
10980 gc_stat_sym_page_pool_arenas_freed,
10981 gc_stat_sym_page_pool_total_pages,
10982 gc_stat_sym_page_pool_discarded_pages,
10983 gc_stat_sym_last
10984};
10985
10986static VALUE gc_stat_symbols[gc_stat_sym_last];
10987
10988static void
10989setup_gc_stat_symbols(void)
10990{
10991#define S(s) gc_stat_symbols[gc_stat_sym_##s] = ID2SYM(rb_intern_const(#s))
10992 S(count);
10993 S(time);
10994 S(marking_time),
10995 S(sweeping_time),
10996 S(heap_allocated_pages);
10997 S(heap_empty_pages);
10998 S(heap_allocatable_bytes);
10999 S(heap_available_slots);
11000 S(heap_live_slots);
11001 S(heap_free_slots);
11002 S(heap_final_slots);
11003 S(heap_marked_slots);
11004 S(heap_eden_pages);
11005 S(total_allocated_pages);
11006 S(total_freed_pages);
11007 S(total_allocated_objects);
11008 S(total_freed_objects);
11009 S(total_malloc_bytes);
11010 S(total_free_bytes);
11011 S(malloc_increase_bytes);
11012 S(malloc_increase_bytes_limit);
11013 S(minor_gc_count);
11014 S(major_gc_count);
11015 S(global_gc_count);
11016 S(compact_count);
11017 S(read_barrier_faults);
11018 S(total_moved_objects);
11019 S(remembered_wb_unprotected_objects);
11020 S(remembered_wb_unprotected_objects_limit);
11021 S(old_objects);
11022 S(old_objects_limit);
11023#if RGENGC_ESTIMATE_OLDMALLOC
11024 S(oldmalloc_increase_bytes);
11025 S(oldmalloc_increase_bytes_limit);
11026#endif
11027#if RGENGC_PROFILE
11028 S(total_generated_normal_object_count);
11029 S(total_generated_shady_object_count);
11030 S(total_shade_operation_count);
11031 S(total_promoted_count);
11032 S(total_remembered_normal_object_count);
11033 S(total_remembered_shady_object_count);
11034#endif /* RGENGC_PROFILE */
11035 S(page_pool_arenas);
11036 S(page_pool_arenas_freed);
11037 S(page_pool_total_pages);
11038 S(page_pool_discarded_pages);
11039#undef S
11040}
11041
11042static uint64_t
11043ns_to_ms(uint64_t ns)
11044{
11045 return ns / (1000 * 1000);
11046}
11047
11048static void malloc_increase_local_flush(rb_objspace_t *objspace);
11049
11050static void
11051gc_process_stat_accumulate_i(void *objspace_ptr, void *data)
11052{
11053 rb_objspace_t *objspace = objspace_ptr;
11054 struct gc_process_stat_total *total = (struct gc_process_stat_total *)data;
11055 struct gc_process_stat_snapshot snap;
11056 rb_native_mutex_lock(&objspace->process_stat.lock);
11057 snap = objspace->process_stat.published;
11058 rb_native_mutex_unlock(&objspace->process_stat.lock);
11059 gc_process_stat_add(total, &snap);
11060}
11061
11062static VALUE
11063gc_process_stat(VALUE hash_or_sym)
11064{
11065 VALUE hash = Qnil, key = Qnil;
11066
11067 if (RB_TYPE_P(hash_or_sym, T_HASH)) {
11068 hash = hash_or_sym;
11069 }
11070 else if (SYMBOL_P(hash_or_sym)) {
11071 key = hash_or_sym;
11072 }
11073 else {
11074 rb_bug("non-hash or symbol given");
11075 }
11076
11077 struct gc_process_stat_total total;
11078 uint64_t direct_global_gc_count;
11079 unsigned int lev = RB_GC_VM_LOCK();
11080 total = global_objspace->process_stat_archive;
11081 rb_gc_vm_each_objspace(gc_process_stat_accumulate_i, &total);
11082 direct_global_gc_count = global_objspace->global_gc.count;
11083 RB_GC_VM_UNLOCK(lev);
11084
11085 rb_objspace_t *const current = rb_gc_get_objspace();
11086 if (!gc_during_gc_get(current)) {
11087 GC_ASSERT(total.global_gc_count == direct_global_gc_count);
11088 }
11089
11090 /* Convert to Ruby values after all collector locks are released. */
11091 uint64_t time_ns = total.marking_time_ns + total.sweeping_time_ns;
11092
11093#define SET64(name, attr) \
11094 if (key == gc_stat_symbols[gc_stat_sym_##name]) \
11095 return ULL2NUM(attr); \
11096 else if (hash != Qnil) \
11097 rb_hash_aset(hash, gc_stat_symbols[gc_stat_sym_##name], ULL2NUM(attr));
11098
11099 SET64(count, total.count);
11100 SET64(time, ns_to_ms(time_ns));
11101 SET64(marking_time, ns_to_ms(total.marking_time_ns));
11102 SET64(sweeping_time, ns_to_ms(total.sweeping_time_ns));
11103 SET64(minor_gc_count, total.minor_gc_count);
11104 SET64(major_gc_count, total.major_gc_count);
11105 SET64(global_gc_count, total.global_gc_count);
11106
11107#undef SET64
11108
11109 if (!NIL_P(key)) {
11110 /* Matched key should return above. */
11111 return Qundef;
11112 }
11113
11114 return hash;
11115}
11116
11117VALUE
11118rb_gc_impl_stat(void *objspace_ptr, VALUE hash_or_sym)
11119{
11120 if (objspace_ptr == NULL) {
11121 return gc_process_stat(hash_or_sym);
11122 }
11123
11124 rb_objspace_t *objspace = objspace_ptr;
11125 VALUE hash = Qnil, key = Qnil;
11126
11127 malloc_increase_local_flush(objspace);
11128
11129 if (RB_TYPE_P(hash_or_sym, T_HASH)) {
11130 hash = hash_or_sym;
11131 }
11132 else if (SYMBOL_P(hash_or_sym)) {
11133 key = hash_or_sym;
11134 }
11135 else {
11136 rb_bug("non-hash or symbol given");
11137 }
11138
11139#define SET(name, attr) \
11140 if (key == gc_stat_symbols[gc_stat_sym_##name]) \
11141 return SIZET2NUM(attr); \
11142 else if (hash != Qnil) \
11143 rb_hash_aset(hash, gc_stat_symbols[gc_stat_sym_##name], SIZET2NUM(attr));
11144#define SET64(name, attr) \
11145 if (key == gc_stat_symbols[gc_stat_sym_##name]) \
11146 return ULL2NUM(attr); \
11147 else if (hash != Qnil) \
11148 rb_hash_aset(hash, gc_stat_symbols[gc_stat_sym_##name], ULL2NUM(attr));
11149
11150 SET(count, objspace->profile.count);
11151 SET(time, (size_t)ns_to_ms(objspace->profile.marking_time_ns + objspace->profile.sweeping_time_ns)); // TODO: UINT64T2NUM
11152 SET(marking_time, (size_t)ns_to_ms(objspace->profile.marking_time_ns));
11153 SET(sweeping_time, (size_t)ns_to_ms(objspace->profile.sweeping_time_ns));
11154
11155 {
11156 uint64_t total_malloc = (uint64_t)gc_counter_load_relaxed(&objspace->malloc_counters.counters.malloc);
11157 uint64_t total_free = (uint64_t)gc_counter_load_relaxed(&objspace->malloc_counters.counters.free);
11158 SET64(total_malloc_bytes, total_malloc);
11159 SET64(total_free_bytes, total_free);
11160 }
11161
11162 /* implementation dependent counters (small / fixnum-safe) */
11163 SET(heap_allocated_pages, rb_darray_size(objspace->heap_pages.sorted));
11164 SET(heap_empty_pages, objspace->empty_pages_count)
11165 SET(heap_allocatable_bytes, objspace->heap_pages.allocatable_bytes);
11166 SET(heap_eden_pages, heap_eden_total_pages(objspace));
11167 SET(total_allocated_pages, objspace->heap_pages.allocated_pages);
11168 SET(total_freed_pages, objspace->heap_pages.freed_pages);
11169 SET(malloc_increase_bytes, gc_malloc_counters_increase_unsigned(objspace, &objspace->malloc_counters.counters));
11170 SET(malloc_increase_bytes_limit, malloc_limit);
11171 SET(minor_gc_count, objspace->profile.minor_gc_count);
11172 SET(major_gc_count, objspace->profile.major_gc_count);
11173 SET(global_gc_count, objspace->profile.global_gc_count);
11174 SET(compact_count, objspace->profile.compact_count);
11175 SET(read_barrier_faults, objspace->profile.read_barrier_faults);
11176 SET(total_moved_objects, objspace->rcompactor.total_moved);
11177 SET(remembered_wb_unprotected_objects, objspace->rgengc.uncollectible_wb_unprotected_objects);
11178 SET(remembered_wb_unprotected_objects_limit, objspace->rgengc.uncollectible_wb_unprotected_objects_limit);
11179 SET(old_objects, objspace->rgengc.old_objects);
11180 SET(old_objects_limit, objspace->rgengc.old_objects_limit);
11181#if RGENGC_ESTIMATE_OLDMALLOC
11182 SET(oldmalloc_increase_bytes, gc_malloc_counters_increase_unsigned(objspace, &objspace->malloc_counters.oldcounters));
11183 SET(oldmalloc_increase_bytes_limit, objspace->rgengc.oldmalloc_increase_limit);
11184#endif
11185
11186 SET(total_allocated_objects, total_allocated_objects(objspace));
11187 SET(total_freed_objects, total_freed_objects(objspace));
11188 SET(heap_available_slots, objspace_available_slots(objspace));
11189 SET(heap_live_slots, objspace_live_slots(objspace));
11190 SET(heap_free_slots, objspace_free_slots(objspace));
11191 SET(heap_final_slots, total_final_slots_count(objspace));
11192 SET(heap_marked_slots, objspace->marked_slots);
11193
11194 SET(page_pool_arenas, global_objspace->page_pool.arena_count);
11195 SET(page_pool_arenas_freed, global_objspace->page_pool.arenas_unmapped);
11196 SET(page_pool_total_pages, (size_t)global_objspace->page_pool.arena_count * PAGE_POOL_ARENA_BODIES);
11197 SET(page_pool_discarded_pages, global_objspace->page_pool.advised_count);
11198
11199#if RGENGC_PROFILE
11200 SET(total_generated_normal_object_count, objspace->profile.total_generated_normal_object_count);
11201 SET(total_generated_shady_object_count, objspace->profile.total_generated_shady_object_count);
11202 SET(total_shade_operation_count, objspace->profile.total_shade_operation_count);
11203 SET(total_promoted_count, objspace->profile.total_promoted_count);
11204 SET(total_remembered_normal_object_count, objspace->profile.total_remembered_normal_object_count);
11205 SET(total_remembered_shady_object_count, objspace->profile.total_remembered_shady_object_count);
11206#endif /* RGENGC_PROFILE */
11207#undef SET
11208#undef SET64
11209
11210 if (!NIL_P(key)) {
11211 // Matched key should return above
11212 return Qundef;
11213 }
11214
11215#if defined(RGENGC_PROFILE) && RGENGC_PROFILE >= 2
11216 if (hash != Qnil) {
11217 gc_count_add_each_types(hash, "generated_normal_object_count_types", objspace->profile.generated_normal_object_count_types);
11218 gc_count_add_each_types(hash, "generated_shady_object_count_types", objspace->profile.generated_shady_object_count_types);
11219 gc_count_add_each_types(hash, "shade_operation_count_types", objspace->profile.shade_operation_count_types);
11220 gc_count_add_each_types(hash, "promoted_types", objspace->profile.promoted_types);
11221 gc_count_add_each_types(hash, "remembered_normal_object_count_types", objspace->profile.remembered_normal_object_count_types);
11222 gc_count_add_each_types(hash, "remembered_shady_object_count_types", objspace->profile.remembered_shady_object_count_types);
11223 }
11224#endif
11225
11226 return hash;
11227}
11228
11229enum gc_stat_heap_sym {
11230 gc_stat_heap_sym_slot_size,
11231 gc_stat_heap_sym_heap_live_slots,
11232 gc_stat_heap_sym_heap_free_slots,
11233 gc_stat_heap_sym_heap_final_slots,
11234 gc_stat_heap_sym_heap_eden_pages,
11235 gc_stat_heap_sym_heap_eden_slots,
11236 gc_stat_heap_sym_total_allocated_pages,
11237 gc_stat_heap_sym_force_major_gc_count,
11238 gc_stat_heap_sym_force_incremental_marking_finish_count,
11239 gc_stat_heap_sym_heap_allocatable_slots,
11240 gc_stat_heap_sym_total_allocated_objects,
11241 gc_stat_heap_sym_total_freed_objects,
11242 gc_stat_heap_sym_last
11243};
11244
11245static VALUE gc_stat_heap_symbols[gc_stat_heap_sym_last];
11246
11247static void
11248setup_gc_stat_heap_symbols(void)
11249{
11250#define S(s) gc_stat_heap_symbols[gc_stat_heap_sym_##s] = ID2SYM(rb_intern_const(#s))
11251 S(slot_size);
11252 S(heap_live_slots);
11253 S(heap_free_slots);
11254 S(heap_final_slots);
11255 S(heap_eden_pages);
11256 S(heap_eden_slots);
11257 S(heap_allocatable_slots);
11258 S(total_allocated_pages);
11259 S(force_major_gc_count);
11260 S(force_incremental_marking_finish_count);
11261 S(total_allocated_objects);
11262 S(total_freed_objects);
11263#undef S
11264}
11265
11266static VALUE
11267stat_one_heap(rb_objspace_t *objspace, rb_heap_t *heap, VALUE hash, VALUE key)
11268{
11269#define SET(name, attr) \
11270 if (key == gc_stat_heap_symbols[gc_stat_heap_sym_##name]) \
11271 return SIZET2NUM(attr); \
11272 else if (hash != Qnil) \
11273 rb_hash_aset(hash, gc_stat_heap_symbols[gc_stat_heap_sym_##name], SIZET2NUM(attr));
11274
11275 SET(slot_size, heap->slot_size);
11276 SET(heap_live_slots, heap->total_allocated_objects - heap->total_freed_objects - heap->final_slots_count);
11277 SET(heap_free_slots, heap->total_slots - (heap->total_allocated_objects - heap->total_freed_objects));
11278 SET(heap_final_slots, heap->final_slots_count);
11279 SET(heap_eden_pages, heap->total_pages);
11280 SET(heap_eden_slots, heap->total_slots);
11281 SET(heap_allocatable_slots, objspace->heap_pages.allocatable_bytes / heap->slot_size);
11282 SET(total_allocated_pages, heap->total_allocated_pages);
11283 SET(force_major_gc_count, heap->force_major_gc_count);
11284 SET(force_incremental_marking_finish_count, heap->force_incremental_marking_finish_count);
11285 SET(total_allocated_objects, heap->total_allocated_objects);
11286 SET(total_freed_objects, heap->total_freed_objects);
11287#undef SET
11288
11289 if (!NIL_P(key)) {
11290 // Matched key should return above
11291 return Qundef;
11292 }
11293
11294 return hash;
11295}
11296
11297VALUE
11298rb_gc_impl_stat_heap(void *objspace_ptr, VALUE heap_name, VALUE hash_or_sym)
11299{
11300 rb_objspace_t *objspace = objspace_ptr;
11301
11302 if (NIL_P(heap_name)) {
11303 if (!RB_TYPE_P(hash_or_sym, T_HASH)) {
11304 rb_bug("non-hash given");
11305 }
11306
11307 for (int i = 0; i < HEAP_COUNT; i++) {
11308 VALUE hash = rb_hash_aref(hash_or_sym, INT2FIX(i));
11309 if (NIL_P(hash)) {
11310 hash = rb_hash_new();
11311 rb_hash_aset(hash_or_sym, INT2FIX(i), hash);
11312 }
11313
11314 stat_one_heap(objspace, &heaps[i], hash, Qnil);
11315 }
11316 }
11317 else if (FIXNUM_P(heap_name)) {
11318 int heap_idx = FIX2INT(heap_name);
11319
11320 if (heap_idx < 0 || heap_idx >= HEAP_COUNT) {
11321 rb_raise(rb_eArgError, "size pool index out of range");
11322 }
11323
11324 if (SYMBOL_P(hash_or_sym)) {
11325 return stat_one_heap(objspace, &heaps[heap_idx], Qnil, hash_or_sym);
11326 }
11327 else if (RB_TYPE_P(hash_or_sym, T_HASH)) {
11328 return stat_one_heap(objspace, &heaps[heap_idx], hash_or_sym, Qnil);
11329 }
11330 else {
11331 rb_bug("non-hash or symbol given");
11332 }
11333 }
11334 else {
11335 rb_bug("heap_name must be nil or an Integer");
11336 }
11337
11338 return hash_or_sym;
11339}
11340
11341/* I could include internal.h for this, but doing so undefines some Array macros
11342 * necessary for initialising objects, and I don't want to include all the array
11343 * headers to get them back
11344 * TODO: Investigate why RARRAY_AREF gets undefined in internal.h
11345 */
11346#ifndef RBOOL
11347#define RBOOL(v) (v ? Qtrue : Qfalse)
11348#endif
11349
11350VALUE
11351rb_gc_impl_config_get(void *objspace_ptr)
11352{
11353#define sym(name) ID2SYM(rb_intern_const(name))
11354 rb_objspace_t *objspace = objspace_ptr;
11355 VALUE hash = rb_hash_new();
11356
11357 rb_hash_aset(hash, sym("rgengc_allow_full_mark"), RBOOL(gc_config_full_mark_val));
11358
11359 return hash;
11360}
11361
11362static int
11363gc_config_set_key(VALUE key, VALUE value, VALUE data)
11364{
11366 if (rb_sym2id(key) == rb_intern("rgengc_allow_full_mark")) {
11367 gc_rest(objspace);
11368 gc_config_full_mark_set(RTEST(value));
11369 }
11370 return ST_CONTINUE;
11371}
11372
11373void
11374rb_gc_impl_config_set(void *objspace_ptr, VALUE hash)
11375{
11376 rb_objspace_t *objspace = objspace_ptr;
11377
11378 if (!RB_TYPE_P(hash, T_HASH)) {
11379 rb_raise(rb_eArgError, "expected keyword arguments");
11380 }
11381
11382 rb_hash_foreach(hash, gc_config_set_key, (st_data_t)objspace);
11383}
11384
11385VALUE
11386rb_gc_impl_stress_get(void *objspace_ptr)
11387{
11388 return ruby_gc_stress_mode;
11389}
11390
11391void
11392rb_gc_impl_stress_set(void *objspace_ptr, VALUE flag)
11393{
11394 global_objspace->gc_stressful = RTEST(flag);
11395 global_objspace->gc_stress_mode = flag;
11396}
11397
11398static int
11399get_envparam_size(const char *name, size_t *default_value, size_t lower_bound)
11400{
11401 const char *ptr = getenv(name);
11402 ssize_t val;
11403
11404 if (ptr != NULL && *ptr) {
11405 size_t unit = 0;
11406 char *end;
11407#if SIZEOF_SIZE_T == SIZEOF_LONG_LONG
11408 val = strtoll(ptr, &end, 0);
11409#else
11410 val = strtol(ptr, &end, 0);
11411#endif
11412 switch (*end) {
11413 case 'k': case 'K':
11414 unit = 1024;
11415 ++end;
11416 break;
11417 case 'm': case 'M':
11418 unit = 1024*1024;
11419 ++end;
11420 break;
11421 case 'g': case 'G':
11422 unit = 1024*1024*1024;
11423 ++end;
11424 break;
11425 }
11426 while (*end && isspace((unsigned char)*end)) end++;
11427 if (*end) {
11428 if (RTEST(ruby_verbose)) fprintf(stderr, "invalid string for %s: %s\n", name, ptr);
11429 return 0;
11430 }
11431 if (unit > 0) {
11432 if (val < -(ssize_t)(SIZE_MAX / 2 / unit) || (ssize_t)(SIZE_MAX / 2 / unit) < val) {
11433 if (RTEST(ruby_verbose)) fprintf(stderr, "%s=%s is ignored because it overflows\n", name, ptr);
11434 return 0;
11435 }
11436 val *= unit;
11437 }
11438 if (val > 0 && (size_t)val > lower_bound) {
11439 if (RTEST(ruby_verbose)) {
11440 fprintf(stderr, "%s=%"PRIdSIZE" (default value: %"PRIuSIZE")\n", name, val, *default_value);
11441 }
11442 *default_value = (size_t)val;
11443 return 1;
11444 }
11445 else {
11446 if (RTEST(ruby_verbose)) {
11447 fprintf(stderr, "%s=%"PRIdSIZE" (default value: %"PRIuSIZE") is ignored because it must be greater than %"PRIuSIZE".\n",
11448 name, val, *default_value, lower_bound);
11449 }
11450 return 0;
11451 }
11452 }
11453 return 0;
11454}
11455
11456static int
11457get_envparam_double(const char *name, double *default_value, double lower_bound, double upper_bound, int accept_zero)
11458{
11459 const char *ptr = getenv(name);
11460 double val;
11461
11462 if (ptr != NULL && *ptr) {
11463 char *end;
11464 val = strtod(ptr, &end);
11465 if (!*ptr || *end) {
11466 if (RTEST(ruby_verbose)) fprintf(stderr, "invalid string for %s: %s\n", name, ptr);
11467 return 0;
11468 }
11469
11470 if (accept_zero && val == 0.0) {
11471 goto accept;
11472 }
11473 else if (val <= lower_bound) {
11474 if (RTEST(ruby_verbose)) {
11475 fprintf(stderr, "%s=%f (default value: %f) is ignored because it must be greater than %f.\n",
11476 name, val, *default_value, lower_bound);
11477 }
11478 }
11479 else if (upper_bound != 0.0 && /* ignore upper_bound if it is 0.0 */
11480 val > upper_bound) {
11481 if (RTEST(ruby_verbose)) {
11482 fprintf(stderr, "%s=%f (default value: %f) is ignored because it must be lower than %f.\n",
11483 name, val, *default_value, upper_bound);
11484 }
11485 }
11486 else {
11487 goto accept;
11488 }
11489 }
11490 return 0;
11491
11492 accept:
11493 if (RTEST(ruby_verbose)) fprintf(stderr, "%s=%f (default value: %f)\n", name, val, *default_value);
11494 *default_value = val;
11495 return 1;
11496}
11497
11498/*
11499 * GC tuning environment variables
11500 *
11501 * * RUBY_GC_HEAP_FREE_SLOTS
11502 * - Prepare at least this amount of slots after GC.
11503 * - Allocate slots if there are not enough slots.
11504 * * RUBY_GC_HEAP_GROWTH_FACTOR (new from 2.1)
11505 * - Allocate slots by this factor.
11506 * - (next slots number) = (current slots number) * (this factor)
11507 * * RUBY_GC_HEAP_GROWTH_MAX_BYTES (was RUBY_GC_HEAP_GROWTH_MAX_SLOTS)
11508 * - Allocation rate is limited to this number of bytes.
11509 * * RUBY_GC_HEAP_FREE_SLOTS_MIN_RATIO (new from 2.4)
11510 * - Allocate additional pages when the number of free slots is
11511 * lower than the value (total_slots * (this ratio)).
11512 * * RUBY_GC_HEAP_FREE_SLOTS_GOAL_RATIO (new from 2.4)
11513 * - Allocate slots to satisfy this formula:
11514 * free_slots = total_slots * goal_ratio
11515 * - In other words, prepare (total_slots * goal_ratio) free slots.
11516 * - if this value is 0.0, then use RUBY_GC_HEAP_GROWTH_FACTOR directly.
11517 * * RUBY_GC_HEAP_FREE_SLOTS_MAX_RATIO (new from 2.4)
11518 * - Allow to free pages when the number of free slots is
11519 * greater than the value (total_slots * (this ratio)).
11520 * * RUBY_GC_HEAP_OLDOBJECT_LIMIT_FACTOR (new from 2.1.1)
11521 * - Do full GC when the number of old objects is more than R * N
11522 * where R is this factor and
11523 * N is the number of old objects just after last full GC.
11524 *
11525 * * obsolete
11526 * * RUBY_FREE_MIN -> RUBY_GC_HEAP_FREE_SLOTS (from 2.1)
11527 * * RUBY_HEAP_MIN_SLOTS -> RUBY_GC_HEAP_INIT_SLOTS (from 2.1) -> RUBY_GC_HEAP_INIT_BYTES
11528 *
11529 * * RUBY_GC_MALLOC_LIMIT
11530 * * RUBY_GC_MALLOC_LIMIT_MAX (new from 2.1)
11531 * * RUBY_GC_MALLOC_LIMIT_GROWTH_FACTOR (new from 2.1)
11532 *
11533 * * RUBY_GC_OLDMALLOC_LIMIT (new from 2.1)
11534 * * RUBY_GC_OLDMALLOC_LIMIT_MAX (new from 2.1)
11535 * * RUBY_GC_OLDMALLOC_LIMIT_GROWTH_FACTOR (new from 2.1)
11536 */
11537
11538void
11539rb_gc_impl_set_params(void *objspace_ptr)
11540{
11541 rb_objspace_t *objspace = objspace_ptr;
11542 get_envparam_size("RUBY_GC_HEAP_FREE_SLOTS", &gc_params.heap_free_slots, 0);
11543
11544 get_envparam_size("RUBY_GC_HEAP_INIT_BYTES", &gc_params.heap_init_bytes,
11545 heap_init_bytes_min() - 1);
11546 get_envparam_size("RUBY_GC_RACTOR_HEAP_INIT_BYTES", &gc_params.ractor_heap_init_bytes,
11547 heap_init_bytes_min() - 1);
11548
11549 get_envparam_double("RUBY_GC_HEAP_GROWTH_FACTOR", &gc_params.growth_factor, 1.0, 0.0, FALSE);
11550 get_envparam_size ("RUBY_GC_HEAP_GROWTH_MAX_BYTES", &gc_params.growth_max_bytes, 0);
11551 get_envparam_double("RUBY_GC_HEAP_FREE_SLOTS_MIN_RATIO", &gc_params.heap_free_slots_min_ratio,
11552 0.0, 1.0, FALSE);
11553 get_envparam_double("RUBY_GC_HEAP_FREE_SLOTS_MAX_RATIO", &gc_params.heap_free_slots_max_ratio,
11554 gc_params.heap_free_slots_min_ratio, 1.0, FALSE);
11555 get_envparam_double("RUBY_GC_HEAP_FREE_SLOTS_GOAL_RATIO", &gc_params.heap_free_slots_goal_ratio,
11556 gc_params.heap_free_slots_min_ratio, gc_params.heap_free_slots_max_ratio, TRUE);
11557 get_envparam_double("RUBY_GC_HEAP_OLDOBJECT_LIMIT_FACTOR", &gc_params.oldobject_limit_factor, 0.0, 0.0, TRUE);
11558 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);
11559
11560 if (get_envparam_size("RUBY_GC_MALLOC_LIMIT", &gc_params.malloc_limit_min, 0)) {
11561 malloc_limit = gc_params.malloc_limit_min;
11562 }
11563 get_envparam_size ("RUBY_GC_MALLOC_LIMIT_MAX", &gc_params.malloc_limit_max, 0);
11564 if (!gc_params.malloc_limit_max) { /* ignore max-check if 0 */
11565 gc_params.malloc_limit_max = SIZE_MAX;
11566 }
11567 get_envparam_double("RUBY_GC_MALLOC_LIMIT_GROWTH_FACTOR", &gc_params.malloc_limit_growth_factor, 1.0, 0.0, FALSE);
11568
11569#if RGENGC_ESTIMATE_OLDMALLOC
11570 if (get_envparam_size("RUBY_GC_OLDMALLOC_LIMIT", &gc_params.oldmalloc_limit_min, 0)) {
11571 objspace->rgengc.oldmalloc_increase_limit = gc_params.oldmalloc_limit_min;
11572 }
11573 get_envparam_size ("RUBY_GC_OLDMALLOC_LIMIT_MAX", &gc_params.oldmalloc_limit_max, 0);
11574 get_envparam_double("RUBY_GC_OLDMALLOC_LIMIT_GROWTH_FACTOR", &gc_params.oldmalloc_limit_growth_factor, 1.0, 0.0, FALSE);
11575#endif
11576}
11577
11578static inline size_t
11579objspace_malloc_size(rb_objspace_t *objspace, void *ptr, size_t hint)
11580{
11581#ifdef HAVE_MALLOC_USABLE_SIZE
11582 if (!hint) {
11583 hint = malloc_usable_size(ptr);
11584 }
11585#endif
11586 return hint;
11587}
11588
11589enum memop_type {
11590 MEMOP_TYPE_MALLOC = 0,
11591 MEMOP_TYPE_FREE,
11592 MEMOP_TYPE_REALLOC
11593};
11594
11595static inline void
11596atomic_sub_nounderflow(size_t *var, size_t sub)
11597{
11598 if (sub == 0) return;
11599
11600 while (1) {
11601 size_t val = *var;
11602 if (val < sub) sub = val;
11603 if (RUBY_ATOMIC_SIZE_CAS(*var, val, val-sub) == val) break;
11604 }
11605}
11606
11607#define gc_stress_full_mark_after_malloc_p() \
11608 (FIXNUM_P(ruby_gc_stress_mode) && (FIX2LONG(ruby_gc_stress_mode) & (1<<gc_stress_full_mark_after_malloc)))
11609
11610static void
11611objspace_malloc_gc_stress(rb_objspace_t *objspace)
11612{
11613 if (ruby_gc_stressful && ruby_native_thread_p()) {
11614 unsigned int reason = (GPR_FLAG_IMMEDIATE_MARK | GPR_FLAG_IMMEDIATE_SWEEP |
11615 GPR_FLAG_STRESS | GPR_FLAG_MALLOC);
11616
11617 if (gc_stress_full_mark_after_malloc_p()) {
11618 reason |= GPR_FLAG_FULL_MARK;
11619 }
11620 garbage_collect_with_gvl(objspace, reason);
11621 }
11622}
11623
11624static void
11625malloc_increase_commit(rb_objspace_t *objspace, size_t new_size, size_t old_size)
11626{
11627 if (new_size > old_size) {
11628 size_t delta = new_size - old_size;
11629 MALLOC_COUNTERS_LOCK(objspace);
11630 gc_counter_add(&objspace->malloc_counters.counters.malloc, delta);
11631#if RGENGC_ESTIMATE_OLDMALLOC
11632 gc_counter_add(&objspace->malloc_counters.oldcounters.malloc, delta);
11633#endif
11634 MALLOC_COUNTERS_UNLOCK(objspace);
11635 }
11636 else if (old_size > new_size) {
11637 size_t delta = old_size - new_size;
11638 MALLOC_COUNTERS_LOCK(objspace);
11639 gc_counter_add(&objspace->malloc_counters.counters.free, delta);
11640#if RGENGC_ESTIMATE_OLDMALLOC
11641 gc_counter_add(&objspace->malloc_counters.oldcounters.free, delta);
11642#endif
11643 MALLOC_COUNTERS_UNLOCK(objspace);
11644 }
11645}
11646
11647#if USE_MALLOC_INCREASE_LOCAL
11648static void
11649malloc_increase_local_flush(rb_objspace_t *objspace)
11650{
11651 int delta = malloc_increase_local;
11652 if (delta == 0) return;
11653
11654 malloc_increase_local = 0;
11655 if (delta > 0) {
11656 malloc_increase_commit(objspace, (size_t)delta, 0);
11657 }
11658 else {
11659 malloc_increase_commit(objspace, 0, (size_t)(-delta));
11660 }
11661}
11662#else
11663static void
11664malloc_increase_local_flush(rb_objspace_t *objspace)
11665{
11666}
11667#endif
11668
11669static inline bool
11670objspace_malloc_increase_report(rb_objspace_t *objspace, void *mem, size_t new_size, size_t old_size, enum memop_type type, bool gc_allowed)
11671{
11672 if (0) fprintf(stderr, "increase - ptr: %p, type: %s, new_size: %"PRIdSIZE", old_size: %"PRIdSIZE"\n",
11673 mem,
11674 type == MEMOP_TYPE_MALLOC ? "malloc" :
11675 type == MEMOP_TYPE_FREE ? "free " :
11676 type == MEMOP_TYPE_REALLOC ? "realloc": "error",
11677 new_size, old_size);
11678 return false;
11679}
11680
11681static bool
11682objspace_malloc_increase_body(rb_objspace_t *objspace, void *mem, size_t new_size, size_t old_size, enum memop_type type, bool gc_allowed)
11683{
11684#if USE_MALLOC_INCREASE_LOCAL
11685 if (new_size < GC_MALLOC_INCREASE_LOCAL_THRESHOLD &&
11686 old_size < GC_MALLOC_INCREASE_LOCAL_THRESHOLD) {
11687 malloc_increase_local += (int)new_size - (int)old_size;
11688
11689 if (malloc_increase_local >= GC_MALLOC_INCREASE_LOCAL_THRESHOLD ||
11690 malloc_increase_local <= -GC_MALLOC_INCREASE_LOCAL_THRESHOLD) {
11691 malloc_increase_local_flush(objspace);
11692 }
11693 }
11694 else {
11695 malloc_increase_local_flush(objspace);
11696 malloc_increase_commit(objspace, new_size, old_size);
11697 }
11698#else
11699 malloc_increase_commit(objspace, new_size, old_size);
11700#endif
11701
11702 if (type == MEMOP_TYPE_MALLOC && gc_allowed) {
11703 retry:
11704 if (malloc_increase > malloc_limit && ruby_native_thread_p() && !dont_gc_val() && !rb_gc_gc_disabled_global_p()) {
11705 if (ruby_thread_has_gvl_p() && is_lazy_sweeping(objspace)) {
11706 gc_sweep_step_for_malloc(objspace); /* sweeping frees may reduce malloc_increase */
11707 goto retry;
11708 }
11709 garbage_collect_with_gvl(objspace, GPR_FLAG_MALLOC);
11710 }
11711 }
11712
11713#if MALLOC_ALLOCATED_SIZE
11714 if (new_size >= old_size) {
11715 RUBY_ATOMIC_SIZE_ADD(objspace->malloc_params.allocated_size, new_size - old_size);
11716 }
11717 else {
11718 size_t dec_size = old_size - new_size;
11719
11720#if MALLOC_ALLOCATED_SIZE_CHECK
11721 size_t allocated_size = objspace->malloc_params.allocated_size;
11722 if (allocated_size < dec_size) {
11723 rb_bug("objspace_malloc_increase: underflow malloc_params.allocated_size.");
11724 }
11725#endif
11726 atomic_sub_nounderflow(&objspace->malloc_params.allocated_size, dec_size);
11727 }
11728
11729 switch (type) {
11730 case MEMOP_TYPE_MALLOC:
11731 RUBY_ATOMIC_SIZE_INC(objspace->malloc_params.allocations);
11732 break;
11733 case MEMOP_TYPE_FREE:
11734 {
11735 size_t allocations = objspace->malloc_params.allocations;
11736 if (allocations > 0) {
11737 atomic_sub_nounderflow(&objspace->malloc_params.allocations, 1);
11738 }
11739#if MALLOC_ALLOCATED_SIZE_CHECK
11740 else {
11741 GC_ASSERT(objspace->malloc_params.allocations > 0);
11742 }
11743#endif
11744 }
11745 break;
11746 case MEMOP_TYPE_REALLOC: /* ignore */ break;
11747 }
11748#endif
11749 return true;
11750}
11751
11752#define objspace_malloc_increase(...) \
11753 for (bool malloc_increase_done = objspace_malloc_increase_report(__VA_ARGS__); \
11754 !malloc_increase_done; \
11755 malloc_increase_done = objspace_malloc_increase_body(__VA_ARGS__))
11756
11757struct malloc_obj_info { /* 4 words */
11758 size_t size;
11759};
11760
11761static inline size_t
11762objspace_malloc_prepare(rb_objspace_t *objspace, size_t size)
11763{
11764 if (size == 0) size = 1;
11765
11766#if CALC_EXACT_MALLOC_SIZE
11767 size += sizeof(struct malloc_obj_info);
11768#endif
11769
11770 return size;
11771}
11772
11773static bool
11774malloc_during_gc_p(rb_objspace_t *objspace)
11775{
11776 /* malloc is not allowed during GC when we're not using multiple ractors
11777 * (since ractors can run while another thread is sweeping) and when we
11778 * have the GVL (since if we don't have the GVL, we'll try to acquire the
11779 * GVL which will block and ensure the other thread finishes GC). */
11780 return during_gc && !dont_gc_val() && !rb_gc_multi_ractor_p() && ruby_thread_has_gvl_p();
11781}
11782
11783static inline void *
11784objspace_malloc_fixup(rb_objspace_t *objspace, void *mem, size_t size, bool gc_allowed)
11785{
11786 size = objspace_malloc_size(objspace, mem, size);
11787 objspace_malloc_increase(objspace, mem, size, 0, MEMOP_TYPE_MALLOC, gc_allowed) {}
11788
11789#if CALC_EXACT_MALLOC_SIZE
11790 {
11791 struct malloc_obj_info *info = mem;
11792 info->size = size;
11793 mem = info + 1;
11794 }
11795#endif
11796
11797 return mem;
11798}
11799
11800#if defined(__GNUC__) && RUBY_DEBUG
11801#define RB_BUG_INSTEAD_OF_RB_MEMERROR 1
11802#endif
11803
11804#ifndef RB_BUG_INSTEAD_OF_RB_MEMERROR
11805# define RB_BUG_INSTEAD_OF_RB_MEMERROR 0
11806#endif
11807
11808#define GC_MEMERROR(...) \
11809 ((RB_BUG_INSTEAD_OF_RB_MEMERROR+0) ? rb_bug("" __VA_ARGS__) : (void)0)
11810
11811#define TRY_WITH_GC(siz, expr) do { \
11812 const gc_profile_record_flag gpr = \
11813 GPR_FLAG_FULL_MARK | \
11814 GPR_FLAG_IMMEDIATE_MARK | \
11815 GPR_FLAG_IMMEDIATE_SWEEP | \
11816 GPR_FLAG_MALLOC; \
11817 /* stress GC must also honor gc_allowed (malloc_gc_disabled) */ \
11818 if (gc_allowed) objspace_malloc_gc_stress(objspace); \
11819 \
11820 if (RB_LIKELY((expr))) { \
11821 /* Success on 1st try */ \
11822 } \
11823 else if (gc_allowed && !garbage_collect_with_gvl(objspace, gpr)) { \
11824 /* @shyouhei thinks this doesn't happen */ \
11825 GC_MEMERROR("TRY_WITH_GC: could not GC"); \
11826 } \
11827 else if ((expr)) { \
11828 /* Success on 2nd try */ \
11829 } \
11830 else { \
11831 GC_MEMERROR("TRY_WITH_GC: could not allocate:" \
11832 "%"PRIdSIZE" bytes for %s", \
11833 siz, # expr); \
11834 } \
11835 } while (0)
11836
11837static void
11838check_malloc_not_in_gc(rb_objspace_t *objspace, const char *msg)
11839{
11840 if (RB_UNLIKELY(malloc_during_gc_p(objspace))) {
11841 dont_gc_on();
11842 during_gc = false;
11843 rb_bug("Cannot %s during GC", msg);
11844 }
11845}
11846
11847void
11848rb_gc_impl_free(void *objspace_ptr, void *ptr, size_t old_size)
11849{
11850 rb_objspace_t *objspace = objspace_ptr;
11851
11852 if (!ptr) {
11853 /*
11854 * ISO/IEC 9899 says "If ptr is a null pointer, no action occurs" since
11855 * its first version. We would better follow.
11856 */
11857 return;
11858 }
11859#if CALC_EXACT_MALLOC_SIZE
11860 struct malloc_obj_info *info = (struct malloc_obj_info *)ptr - 1;
11861#if VERIFY_FREE_SIZE
11862 if (!info->size) {
11863 const char *freeing = gc_freeing_obj_info();
11864 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,
11865 freeing ? ", while freeing " : "", freeing ? freeing : "");
11866 }
11867
11868 if (old_size && (old_size + sizeof(struct malloc_obj_info)) != info->size) {
11869 const char *freeing = gc_freeing_obj_info();
11870 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),
11871 freeing ? ", while freeing " : "", freeing ? freeing : "");
11872 }
11873#endif
11874 ptr = info;
11875 old_size = info->size;
11876#endif
11877 old_size = objspace_malloc_size(objspace, ptr, old_size);
11878
11879 objspace_malloc_increase(objspace, ptr, 0, old_size, MEMOP_TYPE_FREE, true) {
11880 free(ptr);
11881 ptr = NULL;
11882 RB_DEBUG_COUNTER_INC(heap_xfree);
11883 }
11884}
11885
11886void *
11887rb_gc_impl_malloc(void *objspace_ptr, size_t size, bool gc_allowed)
11888{
11889 rb_objspace_t *objspace = objspace_ptr;
11890 check_malloc_not_in_gc(objspace, "malloc");
11891
11892 void *mem;
11893
11894 size = objspace_malloc_prepare(objspace, size);
11895 TRY_WITH_GC(size, mem = malloc(size));
11896 RB_DEBUG_COUNTER_INC(heap_xmalloc);
11897 if (!mem) return mem;
11898 return objspace_malloc_fixup(objspace, mem, size, gc_allowed);
11899}
11900
11901void *
11902rb_gc_impl_calloc(void *objspace_ptr, size_t size, bool gc_allowed)
11903{
11904 rb_objspace_t *objspace = objspace_ptr;
11905
11906 if (RB_UNLIKELY(malloc_during_gc_p(objspace))) {
11907 rb_warn("calloc during GC detected, this could cause crashes if it triggers another GC");
11908#if RGENGC_CHECK_MODE || RUBY_DEBUG
11909 rb_bug("Cannot calloc during GC");
11910#endif
11911 }
11912
11913 void *mem;
11914
11915 size = objspace_malloc_prepare(objspace, size);
11916 TRY_WITH_GC(size, mem = calloc1(size));
11917 if (!mem) return mem;
11918 return objspace_malloc_fixup(objspace, mem, size, gc_allowed);
11919}
11920
11921void *
11922rb_gc_impl_realloc(void *objspace_ptr, void *ptr, size_t new_size, size_t old_size, bool gc_allowed)
11923{
11924 rb_objspace_t *objspace = objspace_ptr;
11925
11926 check_malloc_not_in_gc(objspace, "realloc");
11927
11928 void *mem;
11929
11930 if (!ptr) return rb_gc_impl_malloc(objspace, new_size, gc_allowed);
11931
11932 /*
11933 * The behavior of realloc(ptr, 0) is implementation defined.
11934 * Therefore we don't use realloc(ptr, 0) for portability reason.
11935 * see http://www.open-std.org/jtc1/sc22/wg14/www/docs/dr_400.htm
11936 */
11937 if (new_size == 0) {
11938 if ((mem = rb_gc_impl_malloc(objspace, 0, gc_allowed)) != NULL) {
11939 /*
11940 * - OpenBSD's malloc(3) man page says that when 0 is passed, it
11941 * returns a non-NULL pointer to an access-protected memory page.
11942 * The returned pointer cannot be read / written at all, but
11943 * still be a valid argument of free().
11944 *
11945 * https://man.openbsd.org/malloc.3
11946 *
11947 * - Linux's malloc(3) man page says that it _might_ perhaps return
11948 * a non-NULL pointer when its argument is 0. That return value
11949 * is safe (and is expected) to be passed to free().
11950 *
11951 * https://man7.org/linux/man-pages/man3/malloc.3.html
11952 *
11953 * - As I read the implementation jemalloc's malloc() returns fully
11954 * normal 16 bytes memory region when its argument is 0.
11955 *
11956 * - As I read the implementation musl libc's malloc() returns
11957 * fully normal 32 bytes memory region when its argument is 0.
11958 *
11959 * - Other malloc implementations can also return non-NULL.
11960 */
11961 rb_gc_impl_free(objspace, ptr, old_size);
11962 return mem;
11963 }
11964 else {
11965 /*
11966 * It is dangerous to return NULL here, because that could lead to
11967 * RCE. Fallback to 1 byte instead of zero.
11968 *
11969 * https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2019-11932
11970 */
11971 new_size = 1;
11972 }
11973 }
11974
11975#if CALC_EXACT_MALLOC_SIZE
11976 {
11977 struct malloc_obj_info *info = (struct malloc_obj_info *)ptr - 1;
11978 new_size += sizeof(struct malloc_obj_info);
11979 ptr = info;
11980#if VERIFY_FREE_SIZE
11981 if (old_size && (old_size + sizeof(struct malloc_obj_info)) != info->size) {
11982 const char *freeing = gc_freeing_obj_info();
11983 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),
11984 freeing ? ", while freeing " : "", freeing ? freeing : "");
11985 }
11986#endif
11987 old_size = info->size;
11988 }
11989#endif
11990
11991 old_size = objspace_malloc_size(objspace, ptr, old_size);
11992 TRY_WITH_GC(new_size, mem = RB_GNUC_EXTENSION_BLOCK(realloc(ptr, new_size)));
11993 if (!mem) return mem;
11994 new_size = objspace_malloc_size(objspace, mem, new_size);
11995
11996#if CALC_EXACT_MALLOC_SIZE
11997 {
11998 struct malloc_obj_info *info = mem;
11999 info->size = new_size;
12000 mem = info + 1;
12001 }
12002#endif
12003
12004 objspace_malloc_increase(objspace, mem, new_size, old_size, MEMOP_TYPE_REALLOC, gc_allowed);
12005
12006 RB_DEBUG_COUNTER_INC(heap_xrealloc);
12007 return mem;
12008}
12009
12010void
12011rb_gc_impl_adjust_memory_usage(void *objspace_ptr, ssize_t diff)
12012{
12013 rb_objspace_t *objspace = objspace_ptr;
12014
12015 if (diff > 0) {
12016 objspace_malloc_increase(objspace, 0, diff, 0, MEMOP_TYPE_REALLOC, true);
12017 }
12018 else if (diff < 0) {
12019 objspace_malloc_increase(objspace, 0, 0, -diff, MEMOP_TYPE_REALLOC, true);
12020 }
12021}
12022
12023// TODO: move GC profiler stuff back into gc.c
12024/*
12025 ------------------------------ GC profiler ------------------------------
12026*/
12027
12028#define GC_PROFILE_RECORD_DEFAULT_SIZE 100
12029#define GC_PROFILE_RECORD_DEFAULT_MAX_RECORDS 4096
12030#define GC_PROFILE_RECORD_UNBOUNDED 0
12031
12032static bool
12033current_process_time(struct timespec *ts)
12034{
12035#if defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_PROCESS_CPUTIME_ID)
12036 {
12037 static int try_clock_gettime = 1;
12038 if (try_clock_gettime) {
12039 if (clock_gettime(CLOCK_PROCESS_CPUTIME_ID, ts) == 0) {
12040 return true;
12041 }
12042 else {
12043 try_clock_gettime = 0;
12044 }
12045 }
12046 }
12047#endif
12048
12049#ifdef RUSAGE_SELF
12050 {
12051 struct rusage usage;
12052 struct timeval time;
12053 if (getrusage(RUSAGE_SELF, &usage) == 0) {
12054 time = usage.ru_utime;
12055 ts->tv_sec = time.tv_sec;
12056 ts->tv_nsec = (int32_t)time.tv_usec * 1000;
12057 return true;
12058 }
12059 }
12060#endif
12061
12062#ifdef _WIN32
12063 {
12064 FILETIME creation_time, exit_time, kernel_time, user_time;
12065 ULARGE_INTEGER ui;
12066
12067 if (GetProcessTimes(GetCurrentProcess(),
12068 &creation_time, &exit_time, &kernel_time, &user_time) != 0) {
12069 memcpy(&ui, &user_time, sizeof(FILETIME));
12070#define PER100NSEC (uint64_t)(1000 * 1000 * 10)
12071 ts->tv_nsec = (long)(ui.QuadPart % PER100NSEC);
12072 ts->tv_sec = (time_t)(ui.QuadPart / PER100NSEC);
12073 return true;
12074 }
12075 }
12076#endif
12077
12078 return false;
12079}
12080
12081static double
12082getrusage_time(void)
12083{
12084 struct timespec ts;
12085 if (current_process_time(&ts)) {
12086 return ts.tv_sec + ts.tv_nsec * 1e-9;
12087 }
12088 else {
12089 return 0.0;
12090 }
12091}
12092
12093static inline double
12094hrtime_to_sec(rb_hrtime_t time)
12095{
12096 return (double)time / (double)RB_HRTIME_PER_SEC;
12097}
12098
12099static inline rb_hrtime_t
12100elapsed_hrtime_from(rb_hrtime_t start)
12101{
12102 return rb_hrtime_sub(rb_hrtime_now(), start);
12103}
12104
12105
12106static inline size_t
12107gc_profile_record_count(rb_objspace_t *objspace)
12108{
12109 return objspace->profile.record_count;
12110}
12111
12112static inline size_t
12113gc_profile_record_index(rb_objspace_t *objspace, size_t logical_index)
12114{
12115 if (objspace->profile.max_records != GC_PROFILE_RECORD_UNBOUNDED &&
12116 objspace->profile.record_count == objspace->profile.size) {
12117 return (objspace->profile.next_index + logical_index) % objspace->profile.size;
12118 }
12119 else {
12120 return logical_index;
12121 }
12122}
12123
12124static void
12125gc_profile_records_free(rb_objspace_t *objspace)
12126{
12127 void *p = objspace->profile.records;
12128 objspace->profile.records = NULL;
12129 objspace->profile.size = 0;
12130 objspace->profile.next_index = 0;
12131 objspace->profile.record_count = 0;
12132 objspace->profile.current_record = 0;
12133 free(p);
12134}
12135
12136static inline void
12137gc_prof_setup_new_record(rb_objspace_t *objspace, unsigned int reason)
12138{
12139 if (objspace->profile.run) {
12140 size_t index;
12141 gc_profile_record *record;
12142
12143 if (objspace->profile.max_records == GC_PROFILE_RECORD_UNBOUNDED) {
12144 index = objspace->profile.record_count++;
12145 objspace->profile.next_index = objspace->profile.record_count;
12146
12147 if (!objspace->profile.records) {
12148 objspace->profile.size = GC_PROFILE_RECORD_DEFAULT_SIZE;
12149 objspace->profile.records = malloc(xmalloc2_size(sizeof(gc_profile_record), objspace->profile.size));
12150 }
12151 if (index >= objspace->profile.size) {
12152 void *ptr;
12153 objspace->profile.size += 1000;
12154 ptr = realloc(objspace->profile.records, xmalloc2_size(sizeof(gc_profile_record), objspace->profile.size));
12155 if (!ptr) rb_memerror();
12156 objspace->profile.records = ptr;
12157 }
12158 }
12159 else {
12160 if (!objspace->profile.records) {
12161 objspace->profile.size = objspace->profile.max_records;
12162 objspace->profile.records = malloc(xmalloc2_size(sizeof(gc_profile_record), objspace->profile.size));
12163 }
12164 index = objspace->profile.next_index;
12165 objspace->profile.next_index = (objspace->profile.next_index + 1) % objspace->profile.size;
12166 if (objspace->profile.record_count < objspace->profile.size) {
12167 objspace->profile.record_count++;
12168 }
12169 }
12170
12171 if (!objspace->profile.records) {
12172 rb_bug("gc_profile malloc or realloc miss");
12173 }
12174 record = objspace->profile.current_record = &objspace->profile.records[index];
12175 MEMZERO(record, gc_profile_record, 1);
12176
12177 /* setup before-GC parameter */
12178 record->flags = reason | (ruby_gc_stressful ? GPR_FLAG_STRESS : 0);
12179 record->sequence = objspace->profile.record_sequence++;
12180 record->gc_invoke_wall_time = rb_hrtime_sub(rb_hrtime_now(),
12181 objspace->profile.invoke_wall_time);
12182#if MALLOC_ALLOCATED_SIZE
12183 record->allocated_size = malloc_allocated_size;
12184#endif
12185#if GC_PROFILE_MORE_DETAIL && GC_PROFILE_DETAIL_MEMORY
12186#ifdef RUSAGE_SELF
12187 {
12188 struct rusage usage;
12189 if (getrusage(RUSAGE_SELF, &usage) == 0) {
12190 record->maxrss = usage.ru_maxrss;
12191 record->minflt = usage.ru_minflt;
12192 record->majflt = usage.ru_majflt;
12193 }
12194 }
12195#endif
12196#endif
12197 }
12198}
12199
12200static inline void
12201gc_prof_timer_start(rb_objspace_t *objspace)
12202{
12203 if (gc_prof_enabled(objspace)) {
12204 gc_profile_record *record = gc_prof_record(objspace);
12205#if GC_PROFILE_MORE_DETAIL
12206 record->prepare_time = objspace->profile.prepare_time;
12207#endif
12208 record->gc_time = 0;
12209 record->gc_invoke_time = getrusage_time();
12210 objspace->profile.gc_wall_start_time = rb_hrtime_now();
12211 }
12212}
12213
12214static double
12215elapsed_time_from(double time)
12216{
12217 double now = getrusage_time();
12218 if (now > time) {
12219 return now - time;
12220 }
12221 else {
12222 return 0;
12223 }
12224}
12225
12226static inline void
12227gc_prof_timer_stop(rb_objspace_t *objspace)
12228{
12229 if (gc_prof_enabled(objspace)) {
12230 gc_profile_record *record = gc_prof_record(objspace);
12231 record->gc_time = elapsed_time_from(record->gc_invoke_time);
12232 record->gc_invoke_time -= objspace->profile.invoke_time;
12233 record->gc_wall_time = elapsed_hrtime_from(objspace->profile.gc_wall_start_time);
12234 }
12235}
12236
12237static inline void
12238gc_prof_mark_timer_start(rb_objspace_t *objspace)
12239{
12240 RUBY_DTRACE_GC_HOOK(MARK_BEGIN);
12241#if GC_PROFILE_MORE_DETAIL
12242 if (gc_prof_enabled(objspace)) {
12243 gc_prof_record(objspace)->gc_mark_time = getrusage_time();
12244 }
12245#endif
12246}
12247
12248static inline void
12249gc_prof_mark_timer_stop(rb_objspace_t *objspace)
12250{
12251 RUBY_DTRACE_GC_HOOK(MARK_END);
12252#if GC_PROFILE_MORE_DETAIL
12253 if (gc_prof_enabled(objspace)) {
12254 gc_profile_record *record = gc_prof_record(objspace);
12255 record->gc_mark_time = elapsed_time_from(record->gc_mark_time);
12256 }
12257#endif
12258}
12259
12260static inline void
12261gc_prof_sweep_timer_start(rb_objspace_t *objspace)
12262{
12263 RUBY_DTRACE_GC_HOOK(SWEEP_BEGIN);
12264 if (gc_prof_enabled(objspace)) {
12265 gc_profile_record *record = gc_prof_record(objspace);
12266
12267 if (record->gc_time > 0 || GC_PROFILE_MORE_DETAIL) {
12268 objspace->profile.gc_sweep_start_time = getrusage_time();
12269 objspace->profile.gc_sweep_wall_start_time = rb_hrtime_now();
12270 }
12271 }
12272}
12273
12274static inline void
12275gc_prof_sweep_timer_stop(rb_objspace_t *objspace)
12276{
12277 RUBY_DTRACE_GC_HOOK(SWEEP_END);
12278
12279 if (gc_prof_enabled(objspace)) {
12280 double sweep_time;
12281 gc_profile_record *record = gc_prof_record(objspace);
12282
12283 if (record->gc_time > 0) {
12284 sweep_time = elapsed_time_from(objspace->profile.gc_sweep_start_time);
12285 /* need to accumulate GC time for lazy sweep after gc() */
12286 record->gc_time += sweep_time;
12287 record->gc_wall_time = rb_hrtime_add(record->gc_wall_time,
12288 elapsed_hrtime_from(objspace->profile.gc_sweep_wall_start_time));
12289 }
12290 else if (GC_PROFILE_MORE_DETAIL) {
12291 sweep_time = elapsed_time_from(objspace->profile.gc_sweep_start_time);
12292 }
12293
12294#if GC_PROFILE_MORE_DETAIL
12295 record->gc_sweep_time += sweep_time;
12296 if (heap_pages_deferred_final) record->flags |= GPR_FLAG_HAVE_FINALIZE;
12297#endif
12298 if (heap_pages_deferred_final) objspace->profile.latest_gc_info |= GPR_FLAG_HAVE_FINALIZE;
12299 }
12300}
12301
12302static inline void
12303gc_prof_set_malloc_info(rb_objspace_t *objspace)
12304{
12305#if GC_PROFILE_MORE_DETAIL
12306 if (gc_prof_enabled(objspace)) {
12307 gc_profile_record *record = gc_prof_record(objspace);
12308 record->allocate_increase = malloc_increase;
12309 record->allocate_limit = malloc_limit;
12310 }
12311#endif
12312}
12313
12314static inline void
12315gc_prof_set_heap_info(rb_objspace_t *objspace)
12316{
12317 if (gc_prof_enabled(objspace)) {
12318 gc_profile_record *record = gc_prof_record(objspace);
12319
12320 /* Sum across all size pools since each has a different slot size. */
12321 size_t total = 0;
12322 size_t use_size = 0;
12323 size_t total_size = 0;
12324 for (int i = 0; i < HEAP_COUNT; i++) {
12325 rb_heap_t *heap = &heaps[i];
12326 size_t heap_live = heap->total_allocated_objects - heap->total_freed_objects - heap->final_slots_count;
12327 total += heap->total_slots;
12328 use_size += heap_live * heap->slot_size;
12329 total_size += heap->total_slots * heap->slot_size;
12330 }
12331
12332#if GC_PROFILE_MORE_DETAIL
12333 size_t live = objspace->profile.total_allocated_objects_at_gc_start - total_freed_objects(objspace);
12334 record->heap_use_pages = objspace->profile.heap_used_at_gc_start;
12335 record->heap_live_objects = live;
12336 record->heap_free_objects = total - live;
12337#endif
12338
12339 record->heap_total_objects = total;
12340 record->heap_use_size = use_size;
12341 record->heap_total_size = total_size;
12342 }
12343}
12344
12345/*
12346 * call-seq:
12347 * GC::Profiler.clear -> nil
12348 *
12349 * Clears the \GC profiler data.
12350 *
12351 */
12352
12353static VALUE
12354gc_profile_clear(VALUE _)
12355{
12356 rb_objspace_t *objspace = rb_gc_get_objspace();
12357 gc_profile_records_free(objspace);
12358 return Qnil;
12359}
12360
12361/*
12362 * call-seq:
12363 * GC::Profiler.configure(max_records: 4096) -> nil
12364 *
12365 * Configures how many raw profile records are retained by
12366 * GC::Profiler.raw_data.
12367 *
12368 * The profiler keeps at most +max_records+ records in a bounded ring buffer.
12369 * When the buffer is full, newer GC records overwrite the oldest retained
12370 * records. The default limit is 4096 records.
12371 *
12372 * Pass +nil+ to restore the historical unbounded behavior:
12373 *
12374 * GC::Profiler.configure(max_records: nil)
12375 *
12376 * Changing +max_records+ clears existing raw profile data. This method does
12377 * not enable or disable the profiler; use GC::Profiler.enable and
12378 * GC::Profiler.disable for that.
12379 */
12380
12381static VALUE
12382gc_profile_configure(int argc, VALUE *argv, VALUE _)
12383{
12384 static ID keywords[1] = {0};
12385 VALUE options, max_records;
12386 rb_objspace_t *objspace = rb_gc_get_objspace();
12387
12388 if (!keywords[0]) {
12389 keywords[0] = rb_intern("max_records");
12390 }
12391
12392 rb_scan_args_kw(rb_keyword_given_p(), argc, argv, ":", &options);
12393 rb_get_kwargs(options, keywords, 0, 1, &max_records);
12394
12395 if (max_records == Qundef) {
12396 return Qnil;
12397 }
12398 else if (NIL_P(max_records)) {
12399 objspace->profile.max_records = GC_PROFILE_RECORD_UNBOUNDED;
12400 }
12401 else {
12402 long value = NUM2LONG(max_records);
12403 if (value <= 0) {
12404 rb_raise(rb_eArgError, "max_records must be positive or nil");
12405 }
12406 objspace->profile.max_records = (size_t)value;
12407 }
12408
12409 gc_profile_records_free(objspace);
12410 return Qnil;
12411}
12412
12413/*
12414 * call-seq:
12415 * GC::Profiler.raw_data(limit: nil, since: nil) -> [Hash, ...]
12416 *
12417 * Returns an Array of retained raw profile data Hashes ordered from earliest
12418 * to latest by +:GC_INVOKE_TIME+. +limit:+ returns at most the newest
12419 * retained records. +since:+ returns records with +:GC_SEQUENCE+ greater
12420 * than the given sequence.
12421 *
12422 * For example:
12423 *
12424 * [
12425 * {
12426 * :GC_TIME=>1.3000000000000858e-05,
12427 * :GC_INVOKE_TIME=>0.010634999999999999,
12428 * :GC_WALL_TIME=>1.4000000000000001e-05,
12429 * :GC_INVOKE_WALL_TIME=>0.010640000000000000,
12430 * :GC_PAUSE_TIME=>1.5000000000000000e-05,
12431 * :GC_STOP_TIME=>1.0000000000000000e-06,
12432 * :GC_STW_TIME=>1.4000000000000001e-05,
12433 * :GC_MARK_WALL_TIME=>9.0000000000000002e-06,
12434 * :GC_SWEEP_WALL_TIME=>5.0000000000000004e-06,
12435 * :GC_COMPACT_WALL_TIME=>0.0000000000000000e+00,
12436 * :HEAP_USE_SIZE=>289640,
12437 * :HEAP_TOTAL_SIZE=>588960,
12438 * :HEAP_TOTAL_OBJECTS=>14724,
12439 * :GC_IS_MARKED=>false
12440 * },
12441 * # ...
12442 * ]
12443 *
12444 * The keys mean:
12445 *
12446 * +:GC_SEQUENCE+::
12447 * Monotonically increasing sequence number for this profiler record.
12448 * +:GC_TIME+::
12449 * CPU time elapsed in seconds for this GC run. This is process CPU time,
12450 * not elapsed wall-clock time.
12451 * +:GC_INVOKE_TIME+::
12452 * CPU time elapsed in seconds from startup to when the GC was invoked.
12453 * +:GC_WALL_TIME+::
12454 * Monotonic wall-clock counterpart to +:GC_TIME+ for this GC record.
12455 * This does not include time spent stopping other ractors before the VM
12456 * enters GC. Use the phase wall-clock fields below for mark, sweep, and
12457 * compaction attribution.
12458 * +:GC_INVOKE_WALL_TIME+::
12459 * Monotonic wall-clock time elapsed in seconds from startup to when the GC
12460 * was invoked.
12461 * +:GC_PAUSE_TIME+::
12462 * Monotonic wall-clock time elapsed in seconds while user execution was
12463 * blocked by this GC entry, including time to stop other ractors. This
12464 * may include time from incremental marking or lazy sweeping continuation
12465 * charged to this record.
12466 * +:GC_STOP_TIME+::
12467 * Monotonic wall-clock time elapsed in seconds stopping other ractors.
12468 * +:GC_STW_TIME+::
12469 * Monotonic wall-clock time elapsed in seconds after other ractors have
12470 * stopped and before the VM exits GC.
12471 * +:GC_MARK_WALL_TIME+::
12472 * Monotonic wall-clock time elapsed in seconds spent marking for this GC
12473 * record, accumulated across incremental marking continuations.
12474 * +:GC_SWEEP_WALL_TIME+::
12475 * Monotonic wall-clock time elapsed in seconds spent sweeping for this GC
12476 * record, accumulated across lazy sweeping continuations. This does not
12477 * include compaction time, which is reported separately as
12478 * +:GC_COMPACT_WALL_TIME+.
12479 * +:GC_COMPACT_WALL_TIME+::
12480 * Monotonic wall-clock time elapsed in seconds spent compacting for this GC
12481 * record, or +0.0+ if this GC did not compact.
12482 * +:HEAP_USE_SIZE+::
12483 * Total bytes of heap used
12484 * +:HEAP_TOTAL_SIZE+::
12485 * Total size of heap in bytes
12486 * +:HEAP_TOTAL_OBJECTS+::
12487 * Total number of objects
12488 * +:GC_IS_MARKED+::
12489 * Returns +true+ if the GC is in mark phase
12490 *
12491 * The wall-clock timing fields relate to each other as follows:
12492 *
12493 * GC_PAUSE_TIME == GC_STOP_TIME + GC_STW_TIME
12494 *
12495 * +:GC_MARK_WALL_TIME+, +:GC_SWEEP_WALL_TIME+, and +:GC_COMPACT_WALL_TIME+
12496 * report separate phase timings and must not be added to +:GC_WALL_TIME+.
12497 *
12498 * +:GC_WALL_TIME+ is the wall-clock counterpart to +:GC_TIME+ and is nested
12499 * inside +:GC_STW_TIME+, so it must not be added to +:GC_STW_TIME+. The difference
12500 * +GC_STW_TIME - GC_WALL_TIME+ is VM overhead inside the stopped interval
12501 * (GC event hooks, bookkeeping, consistency checks, and continuation work).
12502 *
12503 * If ruby was built with +GC_PROFILE_MORE_DETAIL+, you will also have access
12504 * to the following hash keys:
12505 *
12506 * +:GC_MARK_TIME+::
12507 * +:GC_SWEEP_TIME+::
12508 * +:ALLOCATE_INCREASE+::
12509 * +:ALLOCATE_LIMIT+::
12510 * +:HEAP_USE_PAGES+::
12511 * +:HEAP_LIVE_OBJECTS+::
12512 * +:HEAP_FREE_OBJECTS+::
12513 * +:HAVE_FINALIZE+::
12514 *
12515 */
12516
12517static VALUE
12518gc_profile_record_get(int argc, VALUE *argv, VALUE _)
12519{
12520 static ID keywords[2] = {0};
12521 VALUE prof, options, limit_value, since_value;
12522 VALUE gc_profile = rb_ary_new();
12523 size_t i, count, matching = 0, skip = 0, limit = SIZE_MAX, since = 0;
12524 bool use_since = false;
12525 rb_objspace_t *objspace = rb_gc_get_objspace();
12526
12527 if (!keywords[0]) {
12528 keywords[0] = rb_intern("limit");
12529 keywords[1] = rb_intern("since");
12530 }
12531
12532 rb_scan_args_kw(rb_keyword_given_p(), argc, argv, ":", &options);
12533 VALUE values[2] = {Qundef, Qundef};
12534 rb_get_kwargs(options, keywords, 0, 2, values);
12535 limit_value = values[0];
12536 since_value = values[1];
12537
12538 if (limit_value != Qundef && !NIL_P(limit_value)) {
12539 long value = NUM2LONG(limit_value);
12540 if (value < 0) {
12541 rb_raise(rb_eArgError, "limit must be non-negative");
12542 }
12543 limit = (size_t)value;
12544 }
12545 if (since_value != Qundef && !NIL_P(since_value)) {
12546 long value = NUM2LONG(since_value);
12547 if (value < 0) {
12548 rb_raise(rb_eArgError, "since must be non-negative");
12549 }
12550 since = (size_t)value;
12551 use_since = true;
12552 }
12553
12554 if (!objspace->profile.run) {
12555 return Qnil;
12556 }
12557
12558 count = gc_profile_record_count(objspace);
12559 for (i = 0; i < count; i++) {
12560 gc_profile_record *record = &objspace->profile.records[gc_profile_record_index(objspace, i)];
12561 if (!use_since || record->sequence > since) {
12562 matching++;
12563 }
12564 }
12565 if (limit < matching) {
12566 skip = matching - limit;
12567 }
12568
12569 for (i = 0; i < count; i++) {
12570 gc_profile_record *record = &objspace->profile.records[gc_profile_record_index(objspace, i)];
12571 if (use_since && record->sequence <= since) {
12572 continue;
12573 }
12574 if (skip > 0) {
12575 skip--;
12576 continue;
12577 }
12578
12579 prof = rb_hash_new();
12580 rb_hash_aset(prof, ID2SYM(rb_intern("GC_FLAGS")), gc_info_decode(objspace, rb_hash_new(), record->flags));
12581 rb_hash_aset(prof, ID2SYM(rb_intern("GC_SEQUENCE")), SIZET2NUM(record->sequence));
12582 rb_hash_aset(prof, ID2SYM(rb_intern("GC_TIME")), DBL2NUM(record->gc_time));
12583 rb_hash_aset(prof, ID2SYM(rb_intern("GC_INVOKE_TIME")), DBL2NUM(record->gc_invoke_time));
12584 rb_hash_aset(prof, ID2SYM(rb_intern("GC_WALL_TIME")),
12585 DBL2NUM(hrtime_to_sec(record->gc_wall_time)));
12586 rb_hash_aset(prof, ID2SYM(rb_intern("GC_INVOKE_WALL_TIME")),
12587 DBL2NUM(hrtime_to_sec(record->gc_invoke_wall_time)));
12588 rb_hash_aset(prof, ID2SYM(rb_intern("GC_PAUSE_TIME")),
12589 DBL2NUM(hrtime_to_sec(record->gc_pause_time)));
12590 rb_hash_aset(prof, ID2SYM(rb_intern("GC_STOP_TIME")),
12591 DBL2NUM(hrtime_to_sec(record->gc_stop_time)));
12592 rb_hash_aset(prof, ID2SYM(rb_intern("GC_STW_TIME")),
12593 DBL2NUM(hrtime_to_sec(record->gc_stw_time)));
12594 rb_hash_aset(prof, ID2SYM(rb_intern("GC_MARK_WALL_TIME")),
12595 DBL2NUM(hrtime_to_sec(record->gc_mark_wall_time)));
12596 rb_hash_aset(prof, ID2SYM(rb_intern("GC_SWEEP_WALL_TIME")),
12597 DBL2NUM(hrtime_to_sec(record->gc_sweep_wall_time)));
12598 rb_hash_aset(prof, ID2SYM(rb_intern("GC_COMPACT_WALL_TIME")),
12599 DBL2NUM(hrtime_to_sec(record->gc_compact_wall_time)));
12600 rb_hash_aset(prof, ID2SYM(rb_intern("HEAP_USE_SIZE")), SIZET2NUM(record->heap_use_size));
12601 rb_hash_aset(prof, ID2SYM(rb_intern("HEAP_TOTAL_SIZE")), SIZET2NUM(record->heap_total_size));
12602 rb_hash_aset(prof, ID2SYM(rb_intern("HEAP_TOTAL_OBJECTS")), SIZET2NUM(record->heap_total_objects));
12603 rb_hash_aset(prof, ID2SYM(rb_intern("MOVED_OBJECTS")), SIZET2NUM(record->moved_objects));
12604 rb_hash_aset(prof, ID2SYM(rb_intern("GC_IS_MARKED")), Qtrue);
12605#if GC_PROFILE_MORE_DETAIL
12606 rb_hash_aset(prof, ID2SYM(rb_intern("GC_MARK_TIME")), DBL2NUM(record->gc_mark_time));
12607 rb_hash_aset(prof, ID2SYM(rb_intern("GC_SWEEP_TIME")), DBL2NUM(record->gc_sweep_time));
12608 rb_hash_aset(prof, ID2SYM(rb_intern("ALLOCATE_INCREASE")), SIZET2NUM(record->allocate_increase));
12609 rb_hash_aset(prof, ID2SYM(rb_intern("ALLOCATE_LIMIT")), SIZET2NUM(record->allocate_limit));
12610 rb_hash_aset(prof, ID2SYM(rb_intern("HEAP_USE_PAGES")), SIZET2NUM(record->heap_use_pages));
12611 rb_hash_aset(prof, ID2SYM(rb_intern("HEAP_LIVE_OBJECTS")), SIZET2NUM(record->heap_live_objects));
12612 rb_hash_aset(prof, ID2SYM(rb_intern("HEAP_FREE_OBJECTS")), SIZET2NUM(record->heap_free_objects));
12613
12614 rb_hash_aset(prof, ID2SYM(rb_intern("REMOVING_OBJECTS")), SIZET2NUM(record->removing_objects));
12615 rb_hash_aset(prof, ID2SYM(rb_intern("EMPTY_OBJECTS")), SIZET2NUM(record->empty_objects));
12616
12617 rb_hash_aset(prof, ID2SYM(rb_intern("HAVE_FINALIZE")), (record->flags & GPR_FLAG_HAVE_FINALIZE) ? Qtrue : Qfalse);
12618#endif
12619
12620#if RGENGC_PROFILE > 0
12621 rb_hash_aset(prof, ID2SYM(rb_intern("OLD_OBJECTS")), SIZET2NUM(record->old_objects));
12622 rb_hash_aset(prof, ID2SYM(rb_intern("REMEMBERED_NORMAL_OBJECTS")), SIZET2NUM(record->remembered_normal_objects));
12623 rb_hash_aset(prof, ID2SYM(rb_intern("REMEMBERED_SHADY_OBJECTS")), SIZET2NUM(record->remembered_shady_objects));
12624#endif
12625 rb_ary_push(gc_profile, prof);
12626 }
12627
12628 return gc_profile;
12629}
12630
12631#if GC_PROFILE_MORE_DETAIL
12632#define MAJOR_REASON_MAX 0x10
12633
12634static char *
12635gc_profile_dump_major_reason(unsigned int flags, char *buff)
12636{
12637 unsigned int reason = flags & GPR_FLAG_MAJOR_MASK;
12638 int i = 0;
12639
12640 if (reason == GPR_FLAG_NONE) {
12641 buff[0] = '-';
12642 buff[1] = 0;
12643 }
12644 else {
12645#define C(x, s) \
12646 if (reason & GPR_FLAG_MAJOR_BY_##x) { \
12647 buff[i++] = #x[0]; \
12648 if (i >= MAJOR_REASON_MAX) rb_bug("gc_profile_dump_major_reason: overflow"); \
12649 buff[i] = 0; \
12650 }
12651 C(NOFREE, N);
12652 C(OLDGEN, O);
12653 C(SHADY, S);
12654#if RGENGC_ESTIMATE_OLDMALLOC
12655 C(OLDMALLOC, M);
12656#endif
12657#undef C
12658 }
12659 return buff;
12660}
12661#endif
12662
12663
12664
12665static void
12666gc_profile_dump_on(VALUE out, VALUE (*append)(VALUE, VALUE))
12667{
12668 rb_objspace_t *objspace = rb_gc_get_objspace();
12669 size_t count = gc_profile_record_count(objspace);
12670#ifdef MAJOR_REASON_MAX
12671 char reason_str[MAJOR_REASON_MAX];
12672#endif
12673
12674 if (objspace->profile.run && count /* > 1 */) {
12675 size_t i;
12676 const gc_profile_record *record;
12677
12678 append(out, rb_sprintf("GC %"PRIuSIZE" invokes.\n", objspace->profile.count));
12679 append(out, rb_str_new_cstr("Index Invoke Time(sec) Use Size(byte) Total Size(byte) Total Object GC Time(ms)\n"));
12680
12681 for (i = 0; i < count; i++) {
12682 record = &objspace->profile.records[gc_profile_record_index(objspace, i)];
12683 append(out, rb_sprintf("%5"PRIuSIZE" %19.3f %20"PRIuSIZE" %20"PRIuSIZE" %20"PRIuSIZE" %30.20f\n",
12684 i+1, record->gc_invoke_time, record->heap_use_size,
12685 record->heap_total_size, record->heap_total_objects, record->gc_time*1000));
12686 }
12687
12688#if GC_PROFILE_MORE_DETAIL
12689 const char *str = "\n\n" \
12690 "More detail.\n" \
12691 "Prepare Time = Previously GC's rest sweep time\n"
12692 "Index Flags Allocate Inc. Allocate Limit"
12693#if CALC_EXACT_MALLOC_SIZE
12694 " Allocated Size"
12695#endif
12696 " Use Page Mark Time(ms) Sweep Time(ms) Prepare Time(ms) LivingObj FreeObj RemovedObj EmptyObj"
12697#if RGENGC_PROFILE
12698 " OldgenObj RemNormObj RemShadObj"
12699#endif
12700#if GC_PROFILE_DETAIL_MEMORY
12701 " MaxRSS(KB) MinorFLT MajorFLT"
12702#endif
12703 "\n";
12704 append(out, rb_str_new_cstr(str));
12705
12706 for (i = 0; i < count; i++) {
12707 record = &objspace->profile.records[gc_profile_record_index(objspace, i)];
12708 append(out, rb_sprintf("%5"PRIuSIZE" %4s/%c/%6s%c %13"PRIuSIZE" %15"PRIuSIZE
12709#if CALC_EXACT_MALLOC_SIZE
12710 " %15"PRIuSIZE
12711#endif
12712 " %9"PRIuSIZE" %17.12f %17.12f %17.12f %10"PRIuSIZE" %10"PRIuSIZE" %10"PRIuSIZE" %10"PRIuSIZE
12713#if RGENGC_PROFILE
12714 "%10"PRIuSIZE" %10"PRIuSIZE" %10"PRIuSIZE
12715#endif
12716#if GC_PROFILE_DETAIL_MEMORY
12717 "%11ld %8ld %8ld"
12718#endif
12719
12720 "\n",
12721 i+1,
12722 gc_profile_dump_major_reason(record->flags, reason_str),
12723 (record->flags & GPR_FLAG_HAVE_FINALIZE) ? 'F' : '.',
12724 (record->flags & GPR_FLAG_NEWOBJ) ? "NEWOBJ" :
12725 (record->flags & GPR_FLAG_MALLOC) ? "MALLOC" :
12726 (record->flags & GPR_FLAG_METHOD) ? "METHOD" :
12727 (record->flags & GPR_FLAG_CAPI) ? "CAPI__" : "??????",
12728 (record->flags & GPR_FLAG_STRESS) ? '!' : ' ',
12729 record->allocate_increase, record->allocate_limit,
12730#if CALC_EXACT_MALLOC_SIZE
12731 record->allocated_size,
12732#endif
12733 record->heap_use_pages,
12734 record->gc_mark_time*1000,
12735 record->gc_sweep_time*1000,
12736 record->prepare_time*1000,
12737
12738 record->heap_live_objects,
12739 record->heap_free_objects,
12740 record->removing_objects,
12741 record->empty_objects
12742#if RGENGC_PROFILE
12743 ,
12744 record->old_objects,
12745 record->remembered_normal_objects,
12746 record->remembered_shady_objects
12747#endif
12748#if GC_PROFILE_DETAIL_MEMORY
12749 ,
12750 record->maxrss / 1024,
12751 record->minflt,
12752 record->majflt
12753#endif
12754
12755 ));
12756 }
12757#endif
12758 }
12759}
12760
12761/*
12762 * call-seq:
12763 * GC::Profiler.result -> String
12764 *
12765 * Returns a profile data report such as:
12766 *
12767 * GC 1 invokes.
12768 * Index Invoke Time(sec) Use Size(byte) Total Size(byte) Total Object GC time(ms)
12769 * 1 0.012 159240 212940 10647 0.00000000000001530000
12770 */
12771
12772static VALUE
12773gc_profile_result(VALUE _)
12774{
12775 VALUE str = rb_str_buf_new(0);
12776 gc_profile_dump_on(str, rb_str_buf_append);
12777 return str;
12778}
12779
12780/*
12781 * call-seq:
12782 * GC::Profiler.report
12783 * GC::Profiler.report(io)
12784 *
12785 * Writes the GC::Profiler.result to <tt>$stdout</tt> or the given IO object.
12786 *
12787 */
12788
12789static VALUE
12790gc_profile_report(int argc, VALUE *argv, VALUE self)
12791{
12792 VALUE out;
12793
12794 out = (!rb_check_arity(argc, 0, 1) ? rb_stdout : argv[0]);
12795 gc_profile_dump_on(out, rb_io_write);
12796
12797 return Qnil;
12798}
12799
12800/*
12801 * call-seq:
12802 * GC::Profiler.total_time -> float
12803 *
12804 * The total time used for garbage collection in seconds
12805 */
12806
12807static VALUE
12808gc_profile_total_time(VALUE self)
12809{
12810 double time = 0;
12811 rb_objspace_t *objspace = rb_gc_get_objspace();
12812
12813 if (objspace->profile.run && gc_profile_record_count(objspace) > 0) {
12814 size_t i;
12815 size_t count = gc_profile_record_count(objspace);
12816
12817 for (i = 0; i < count; i++) {
12818 time += objspace->profile.records[gc_profile_record_index(objspace, i)].gc_time;
12819 }
12820 }
12821 return DBL2NUM(time);
12822}
12823
12824/*
12825 * call-seq:
12826 * GC::Profiler.enabled? -> true or false
12827 *
12828 * The current status of \GC profile mode.
12829 */
12830
12831static VALUE
12832gc_profile_enable_get(VALUE self)
12833{
12834 rb_objspace_t *objspace = rb_gc_get_objspace();
12835 return objspace->profile.run ? Qtrue : Qfalse;
12836}
12837
12838/*
12839 * call-seq:
12840 * GC::Profiler.enable -> nil
12841 *
12842 * Starts the \GC profiler.
12843 *
12844 */
12845
12846static VALUE
12847gc_profile_enable(VALUE _)
12848{
12849 rb_objspace_t *objspace = rb_gc_get_objspace();
12850 objspace->profile.run = TRUE;
12851 objspace->profile.current_record = 0;
12852 return Qnil;
12853}
12854
12855/*
12856 * call-seq:
12857 * GC::Profiler.disable -> nil
12858 *
12859 * Stops the \GC profiler.
12860 *
12861 */
12862
12863static VALUE
12864gc_profile_disable(VALUE _)
12865{
12866 rb_objspace_t *objspace = rb_gc_get_objspace();
12867
12868 objspace->profile.run = FALSE;
12869 objspace->profile.current_record = 0;
12870 return Qnil;
12871}
12872
12873static void
12874rb_gc_verify_internal_consistency(void)
12875{
12876 gc_verify_internal_consistency(rb_gc_get_objspace());
12877}
12878
12879/*
12880 * call-seq:
12881 * GC.verify_internal_consistency -> nil
12882 *
12883 * Verifies internal consistency of the GC.
12884 * This method should only be used for debugging.
12885 *
12886 * This method is only expected to work on CRuby.
12887 */
12888static VALUE
12889gc_verify_internal_consistency_m(VALUE dummy)
12890{
12891 rb_gc_verify_internal_consistency();
12892 return Qnil;
12893}
12894
12895#if GC_CAN_COMPILE_COMPACTION
12896/*
12897 * call-seq:
12898 * GC.auto_compact = flag
12899 *
12900 * Updates automatic compaction mode.
12901 *
12902 * When enabled, the compactor will execute on every major collection.
12903 *
12904 * Enabling compaction will degrade performance on major collections.
12905 */
12906static VALUE
12907gc_set_auto_compact(VALUE _, VALUE v)
12908{
12909 GC_ASSERT(GC_COMPACTION_SUPPORTED);
12910
12911 ruby_enable_autocompact = RTEST(v);
12912
12913#if RGENGC_CHECK_MODE
12914 ruby_autocompact_compare_func = NULL;
12915
12916 if (SYMBOL_P(v)) {
12917 ID id = RB_SYM2ID(v);
12918 if (id == rb_intern("empty")) {
12919 ruby_autocompact_compare_func = compare_free_slots;
12920 }
12921 }
12922#endif
12923
12924 return v;
12925}
12926#else
12927# define gc_set_auto_compact rb_f_notimplement
12928#endif
12929
12930#if GC_CAN_COMPILE_COMPACTION
12931/*
12932 * call-seq:
12933 * GC.auto_compact -> true or false
12934 *
12935 * Returns whether or not automatic compaction has been enabled.
12936 */
12937static VALUE
12938gc_get_auto_compact(VALUE _)
12939{
12940 return ruby_enable_autocompact ? Qtrue : Qfalse;
12941}
12942#else
12943# define gc_get_auto_compact rb_f_notimplement
12944#endif
12945
12946#if GC_CAN_COMPILE_COMPACTION
12947/*
12948 * call-seq:
12949 * GC.latest_compact_info -> hash
12950 *
12951 * Returns information about object moved in the most recent \GC compaction.
12952 *
12953 * The returned +hash+ contains the following keys:
12954 *
12955 * [considered]
12956 * Hash containing the type of the object as the key and the number of
12957 * objects of that type that were considered for movement.
12958 * [moved]
12959 * Hash containing the type of the object as the key and the number of
12960 * objects of that type that were actually moved.
12961 * [moved_up]
12962 * Hash containing the type of the object as the key and the number of
12963 * objects of that type that were increased in size.
12964 * [moved_down]
12965 * Hash containing the type of the object as the key and the number of
12966 * objects of that type that were decreased in size.
12967 *
12968 * Some objects can't be moved (due to pinning) so these numbers can be used to
12969 * calculate compaction efficiency.
12970 */
12971static VALUE
12972gc_compact_stats(VALUE self)
12973{
12974 rb_objspace_t *objspace = rb_gc_get_objspace();
12975 VALUE h = rb_hash_new();
12976 VALUE considered = rb_hash_new();
12977 VALUE moved = rb_hash_new();
12978 VALUE moved_up = rb_hash_new();
12979 VALUE moved_down = rb_hash_new();
12980
12981 for (size_t i = 0; i < T_MASK; i++) {
12982 if (objspace->rcompactor.considered_count_table[i]) {
12983 rb_hash_aset(considered, type_sym(i), SIZET2NUM(objspace->rcompactor.considered_count_table[i]));
12984 }
12985
12986 if (objspace->rcompactor.moved_count_table[i]) {
12987 rb_hash_aset(moved, type_sym(i), SIZET2NUM(objspace->rcompactor.moved_count_table[i]));
12988 }
12989
12990 if (objspace->rcompactor.moved_up_count_table[i]) {
12991 rb_hash_aset(moved_up, type_sym(i), SIZET2NUM(objspace->rcompactor.moved_up_count_table[i]));
12992 }
12993
12994 if (objspace->rcompactor.moved_down_count_table[i]) {
12995 rb_hash_aset(moved_down, type_sym(i), SIZET2NUM(objspace->rcompactor.moved_down_count_table[i]));
12996 }
12997 }
12998
12999 rb_hash_aset(h, ID2SYM(rb_intern("considered")), considered);
13000 rb_hash_aset(h, ID2SYM(rb_intern("moved")), moved);
13001 rb_hash_aset(h, ID2SYM(rb_intern("moved_up")), moved_up);
13002 rb_hash_aset(h, ID2SYM(rb_intern("moved_down")), moved_down);
13003
13004 return h;
13005}
13006#else
13007# define gc_compact_stats rb_f_notimplement
13008#endif
13009
13010#if GC_CAN_COMPILE_COMPACTION
13011/*
13012 * call-seq:
13013 * GC.compact -> hash
13014 *
13015 * This function compacts objects together in Ruby's heap. It eliminates
13016 * unused space (or fragmentation) in the heap by moving objects in to that
13017 * unused space. If there is more than 1 running Ractor, it runs a global
13018 * GC compaction (all object spaces).
13019 *
13020 * The returned +hash+ contains statistics about the objects that were moved;
13021 * see GC.latest_compact_info.
13022 *
13023 * This method is only expected to work on CRuby.
13024 *
13025 * To test whether \GC compaction is supported, use the idiom:
13026 *
13027 * GC.respond_to?(:compact)
13028 */
13029static VALUE
13030gc_compact(VALUE self)
13031{
13032 rb_objspace_t *objspace = rb_gc_get_objspace();
13033 int full_marking_p = gc_config_full_mark_val;
13034 gc_config_full_mark_set(TRUE);
13035
13036 /* Run GC with compaction enabled */
13037 rb_gc_impl_start(rb_gc_get_objspace(), true, true, true, true, true);
13038 gc_config_full_mark_set(full_marking_p);
13039
13040 return gc_compact_stats(self);
13041}
13042#else
13043# define gc_compact rb_f_notimplement
13044#endif
13045
13046#if GC_CAN_COMPILE_COMPACTION
13047struct desired_compaction_pages_i_data {
13049 size_t required_slots[HEAP_COUNT];
13050};
13051
13052static int
13053desired_compaction_pages_i(struct heap_page *page, void *data)
13054{
13055 struct desired_compaction_pages_i_data *tdata = data;
13056 rb_objspace_t *objspace = tdata->objspace;
13057 VALUE vstart = (VALUE)page->start;
13058 VALUE vend = vstart + (VALUE)(page->total_slots * page->heap->slot_size);
13059
13060
13061 for (VALUE v = vstart; v != vend; v += page->heap->slot_size) {
13062 asan_unpoisoning_object(v) {
13063 /* skip T_NONEs; they won't be moved */
13064 if (BUILTIN_TYPE(v) != T_NONE) {
13065 rb_heap_t *dest_pool = gc_compact_destination_pool(objspace, page->heap, v);
13066 size_t dest_pool_idx = dest_pool - heaps;
13067 tdata->required_slots[dest_pool_idx]++;
13068 }
13069 }
13070 }
13071
13072 return 0;
13073}
13074
13075/* call-seq:
13076 * GC.verify_compaction_references(toward: nil, double_heap: false) -> hash
13077 *
13078 * Verify compaction reference consistency.
13079 *
13080 * This method is implementation specific. During compaction, objects that
13081 * were moved are replaced with T_MOVED objects. No object should have a
13082 * reference to a T_MOVED object after compaction.
13083 *
13084 * This function expands the heap to ensure room to move all objects,
13085 * compacts the heap to make sure everything moves, updates all references,
13086 * then performs a full \GC. If any object contains a reference to a T_MOVED
13087 * object, that object should be pushed on the mark stack, and will
13088 * make a SEGV.
13089 */
13090static VALUE
13091gc_verify_compaction_references(int argc, VALUE* argv, VALUE self)
13092{
13093 static ID keywords[3] = {0};
13094 if (!keywords[0]) {
13095 keywords[0] = rb_intern("toward");
13096 keywords[1] = rb_intern("double_heap");
13097 keywords[2] = rb_intern("expand_heap");
13098 }
13099
13100 VALUE options;
13101 rb_scan_args_kw(rb_keyword_given_p(), argc, argv, ":", &options);
13102
13103 VALUE arguments[3] = { Qnil, Qfalse, Qfalse };
13104 int kwarg_count = rb_get_kwargs(options, keywords, 0, 3, arguments);
13105 bool toward_empty = kwarg_count > 0 && SYMBOL_P(arguments[0]) && SYM2ID(arguments[0]) == rb_intern("empty");
13106 bool expand_heap = (kwarg_count > 1 && RTEST(arguments[1])) || (kwarg_count > 2 && RTEST(arguments[2]));
13107
13108 rb_objspace_t *objspace = rb_gc_get_objspace();
13109
13110 /* This verification machinery (heap expansion, toward_empty page ordering, the
13111 * moved-reference walk) is built for a single objspace, so with several demote it
13112 * to a plain full GC. Plain GC.compact does compact them via the global GC. */
13113 if (!rb_gc_single_objspace_p()) {
13114 rb_gc_impl_start(objspace, true, true, true, false, false);
13115 return gc_compact_stats(self);
13116 }
13117
13118 /* Clear the heap. */
13119 rb_gc_impl_start(objspace, true, true, true, false, false);
13120
13121 unsigned int lev = RB_GC_VM_LOCK();
13122 {
13123 gc_rest(objspace);
13124
13125 /* if both double_heap and expand_heap are set, expand_heap takes precedence */
13126 if (expand_heap) {
13127 struct desired_compaction_pages_i_data desired_compaction = {
13128 .objspace = objspace,
13129 .required_slots = {0},
13130 };
13131 /* Work out how many objects want to be in each size pool, taking account of moves */
13132 objspace_each_pages(objspace, desired_compaction_pages_i, &desired_compaction, TRUE);
13133
13134 /* Find out which pool has the most pages */
13135 size_t max_existing_pages = 0;
13136 for (int i = 0; i < HEAP_COUNT; i++) {
13137 rb_heap_t *heap = &heaps[i];
13138 max_existing_pages = MAX(max_existing_pages, heap->total_pages);
13139 }
13140
13141 /* Add pages to each size pool so that compaction is guaranteed to move every object */
13142 for (int i = 0; i < HEAP_COUNT; i++) {
13143 rb_heap_t *heap = &heaps[i];
13144
13145 size_t pages_to_add = 0;
13146 /*
13147 * Step 1: Make sure every pool has the same number of pages, by adding empty pages
13148 * to smaller pools. This is required to make sure the compact cursor can advance
13149 * through all of the pools in `gc_sweep_compact` without hitting the "sweep &
13150 * compact cursors met" condition on some pools before fully compacting others
13151 */
13152 pages_to_add += max_existing_pages - heap->total_pages;
13153 /*
13154 * Step 2: Now add additional free pages to each size pool sufficient to hold all objects
13155 * that want to be in that size pool, whether moved into it or moved within it
13156 */
13157 objspace->heap_pages.allocatable_bytes = desired_compaction.required_slots[i] * heap->slot_size;
13158 while (objspace->heap_pages.allocatable_bytes > 0) {
13159 heap_page_allocate_and_initialize(objspace, heap);
13160 }
13161 /*
13162 * Step 3: Add two more pages so that the compact & sweep cursors will meet _after_ all objects
13163 * have been moved, and not on the last iteration of the `gc_sweep_compact` loop
13164 */
13165 pages_to_add += 2;
13166
13167 for (; pages_to_add > 0; pages_to_add--) {
13168 heap_page_allocate_and_initialize_force(objspace, heap);
13169 }
13170 }
13171 }
13172
13173 if (toward_empty) {
13174 objspace->rcompactor.compare_func = compare_free_slots;
13175 }
13176 }
13177 RB_GC_VM_UNLOCK(lev);
13178
13179 rb_gc_impl_start(rb_gc_get_objspace(), true, true, true, true, false);
13180
13181 rb_objspace_reachable_objects_from_root(root_obj_check_moved_i, objspace);
13182 objspace_each_objects(objspace, heap_check_moved_i, objspace, TRUE);
13183
13184 objspace->rcompactor.compare_func = NULL;
13185
13186 return gc_compact_stats(self);
13187}
13188#else
13189# define gc_verify_compaction_references rb_f_notimplement
13190#endif
13191
13192void
13193rb_gc_impl_objspace_free(void *objspace_ptr)
13194{
13195 rb_objspace_t *objspace = objspace_ptr;
13196
13197 if (is_lazy_sweeping(objspace))
13198 rb_bug("lazy sweeping underway when freeing object space");
13199
13200 free(objspace->profile.records);
13201 objspace->profile.records = NULL;
13202
13203 for (size_t i = 0; i < rb_darray_size(objspace->heap_pages.sorted); i++) {
13204 heap_page_free(objspace, rb_darray_get(objspace->heap_pages.sorted, i));
13205 }
13206 rb_darray_free_without_gc(objspace->heap_pages.sorted);
13207 heap_pages_lomem = 0;
13208 heap_pages_himem = 0;
13209
13210 for (int i = 0; i < HEAP_COUNT; i++) {
13211 rb_heap_t *heap = &heaps[i];
13212 heap->total_pages = 0;
13213 heap->total_slots = 0;
13214 }
13215
13216 free_stack_chunks(&objspace->mark_stack);
13217 mark_stack_free_cache(&objspace->mark_stack);
13218
13219 rb_darray_free_without_gc(objspace->weak_references);
13220
13221#ifdef MALLOC_COUNTERS_NEED_LOCK
13222 rb_native_mutex_destroy(&objspace->malloc_counters.lock);
13223#endif
13224
13225 rb_native_mutex_destroy(&objspace->process_stat.lock);
13226
13227 free(objspace);
13228}
13229
13230#if MALLOC_ALLOCATED_SIZE
13231/*
13232 * call-seq:
13233 * GC.malloc_allocated_size -> Integer
13234 *
13235 * Returns the size of memory allocated by malloc().
13236 *
13237 * Only available if ruby was built with +CALC_EXACT_MALLOC_SIZE+.
13238 */
13239
13240static VALUE
13241gc_malloc_allocated_size(VALUE self)
13242{
13243 rb_objspace_t *objspace = (rb_objspace_t *)rb_gc_get_objspace();
13244 return ULL2NUM(objspace->malloc_params.allocated_size);
13245}
13246
13247/*
13248 * call-seq:
13249 * GC.malloc_allocations -> Integer
13250 *
13251 * Returns the number of malloc() allocations.
13252 *
13253 * Only available if ruby was built with +CALC_EXACT_MALLOC_SIZE+.
13254 */
13255
13256static VALUE
13257gc_malloc_allocations(VALUE self)
13258{
13259 rb_objspace_t *objspace = (rb_objspace_t *)rb_gc_get_objspace();
13260 return ULL2NUM(objspace->malloc_params.allocations);
13261}
13262#endif
13263
13264void
13265rb_gc_impl_before_fork(void *objspace_ptr)
13266{
13267 rb_objspace_t *objspace = objspace_ptr;
13268
13269 objspace->fork_vm_lock_lev = RB_GC_VM_LOCK();
13270 rb_gc_vm_barrier();
13271}
13272
13273void
13274rb_gc_impl_after_fork(void *objspace_ptr, rb_pid_t pid)
13275{
13276 rb_objspace_t *objspace = objspace_ptr;
13277
13278 if (pid == 0) {
13279 rb_gc_vm_each_objspace(gc_process_stat_after_fork_i, NULL);
13280 }
13281
13282 RB_GC_VM_UNLOCK(objspace->fork_vm_lock_lev);
13283 objspace->fork_vm_lock_lev = 0;
13284
13285 if (pid == 0) { /* child process */
13286 heap_alloc_state_clear(objspace);
13287 /* The forking Ractor becomes the child process's main Ractor. */
13288 global_objspace->main_objspace = objspace;
13289 page_pool_lock_initialize(&rb_global_objspace_instance.page_pool.lock);
13290 }
13291}
13292
13293VALUE rb_ident_hash_new_capa(long size);
13294
13295#if GC_DEBUG_STRESS_TO_CLASS
13296/*
13297 * call-seq:
13298 * GC.add_stress_to_class(class[, ...])
13299 *
13300 * Raises NoMemoryError when allocating an instance of the given classes.
13301 *
13302 */
13303static VALUE
13304rb_gcdebug_add_stress_to_class(int argc, VALUE *argv, VALUE self)
13305{
13306 rb_objspace_t *objspace = rb_gc_get_objspace();
13307
13308 if (!stress_to_class) {
13309 set_stress_to_class(rb_ident_hash_new_capa(argc));
13310 }
13311
13312 for (int i = 0; i < argc; i++) {
13313 VALUE klass = argv[i];
13314 rb_hash_aset(stress_to_class, klass, Qtrue);
13315 }
13316
13317 return self;
13318}
13319
13320/*
13321 * call-seq:
13322 * GC.remove_stress_to_class(class[, ...])
13323 *
13324 * No longer raises NoMemoryError when allocating an instance of the
13325 * given classes.
13326 *
13327 */
13328static VALUE
13329rb_gcdebug_remove_stress_to_class(int argc, VALUE *argv, VALUE self)
13330{
13331 rb_objspace_t *objspace = rb_gc_get_objspace();
13332
13333 if (stress_to_class) {
13334 for (int i = 0; i < argc; ++i) {
13335 rb_hash_delete(stress_to_class, argv[i]);
13336 }
13337
13338 if (rb_hash_size(stress_to_class) == 0) {
13339 stress_to_class = 0;
13340 }
13341 }
13342
13343 return Qnil;
13344}
13345#endif
13346
13347void *
13348rb_gc_impl_objspace_alloc(void)
13349{
13350 global_objspace_init();
13351
13352 rb_objspace_t *objspace = calloc1(sizeof(rb_objspace_t));
13353 if (objspace) {
13354 rb_native_mutex_initialize(&objspace->process_stat.lock);
13355 }
13356
13357 return objspace;
13358}
13359
13360void
13361rb_gc_impl_objspace_init(void *objspace_ptr)
13362{
13363 rb_objspace_t *objspace = objspace_ptr;
13364
13365 gc_config_full_mark_set(TRUE);
13366
13367 malloc_limit = gc_params.malloc_limit_min;
13368 objspace->shareable_objects_limit = SHAREABLE_OBJECTS_LIMIT_MIN;
13369#ifdef MALLOC_COUNTERS_NEED_LOCK
13370 rb_native_mutex_initialize(&objspace->malloc_counters.lock);
13371#endif
13372 /* Shared by every objspace. preregister deduplicates on (func, data). */
13373 objspace->finalize_deferred_pjob = rb_postponed_job_preregister(0, gc_finalize_deferred, NULL);
13374 if (objspace->finalize_deferred_pjob == POSTPONED_JOB_HANDLE_INVALID) {
13375 rb_bug("Could not preregister postponed job for GC");
13376 }
13377
13378 gc_tdata_deferred_free_pjob_ensure();
13379
13380 /* A standard RVALUE (RBasic + embedded VALUEs + debug overhead) must fit
13381 * in at least one pool. In debug builds RVALUE_OVERHEAD can push this
13382 * beyond the 48-byte pool into the 64-byte pool, which is fine. */
13383 GC_ASSERT(rb_gc_impl_size_allocatable_p(sizeof(struct RBasic) + sizeof(VALUE[RBIMPL_RVALUE_EMBED_LEN_MAX])));
13384
13385 for (int i = 0; i < HEAP_COUNT; i++) {
13386 rb_heap_t *heap = &heaps[i];
13387
13388 heap->slot_size = pool_slot_sizes[i];
13389
13390 ccan_list_head_init(&heap->pages);
13391 }
13392
13393 if (global_objspace->main_objspace == NULL) {
13394 /* Single-threaded at boot and the first objspace is main's: compute process-wide
13395 * constants once here. A later objspace_init rewriting them, even with equal
13396 * values, would race other threads' lock-free reads. */
13397 global_objspace->main_objspace = objspace;
13398
13399 init_size_to_heap_idx();
13400
13401#if defined(INIT_HEAP_PAGE_ALLOC_USE_MMAP)
13402 /* Need to determine if we can use mmap at runtime. */
13403 heap_page_alloc_use_mmap = INIT_HEAP_PAGE_ALLOC_USE_MMAP;
13404#endif
13405 gc_params.heap_init_bytes = GC_HEAP_INIT_BYTES;
13406 gc_params.ractor_heap_init_bytes = GC_RACTOR_HEAP_INIT_BYTES ? GC_RACTOR_HEAP_INIT_BYTES
13407 : heap_init_bytes_min();
13408 }
13409 // GC.measure_total_time= sets the caller's objspace only; a new Ractor's follows
13410 // its creator's, which is the objspace running this init (main starts it on).
13411 objspace->flags.measure_gc = global_objspace->main_objspace == objspace ? true
13412 : ((rb_objspace_t *)rb_gc_get_objspace())->flags.measure_gc;
13413
13414 rb_darray_make_without_gc(&objspace->heap_pages.sorted, 0);
13415 rb_darray_make_without_gc(&objspace->weak_references, 0);
13416
13417#if RGENGC_ESTIMATE_OLDMALLOC
13418 objspace->rgengc.oldmalloc_increase_limit = gc_params.oldmalloc_limit_min;
13419#endif
13420
13421 init_mark_stack(&objspace->mark_stack);
13422
13423 objspace->profile.invoke_time = getrusage_time();
13424 objspace->profile.invoke_wall_time = rb_hrtime_now();
13425 objspace->profile.max_records = GC_PROFILE_RECORD_DEFAULT_MAX_RECORDS;
13426 finalizer_table = st_init_numtable();
13427
13428 gc_process_stat_publish(objspace);
13429}
13430
13431void
13432rb_gc_impl_init(void)
13433{
13434 /* Fill the symbol tables here, where no other ractor exists yet: they used to
13435 * be filled on first use, guarded by their own first element, so a second
13436 * ractor could see a half-filled table and GC.stat raised on the rest. */
13437 setup_gc_stat_symbols();
13438 setup_gc_stat_heap_symbols();
13439 setup_gc_latest_gc_info_symbols();
13440
13441 VALUE gc_constants = rb_hash_new();
13442 rb_hash_aset(gc_constants, ID2SYM(rb_intern("DEBUG")), GC_DEBUG ? Qtrue : Qfalse);
13443 /* Minimum slot size that fits a standard RVALUE */
13444 size_t rvalue_pool = 0;
13445 for (size_t i = 0; i < HEAP_COUNT; i++) {
13446 if (pool_slot_sizes[i] >= RVALUE_SLOT_SIZE) { rvalue_pool = pool_slot_sizes[i]; break; }
13447 }
13448 rb_hash_aset(gc_constants, ID2SYM(rb_intern("RVALUE_SIZE")), SIZET2NUM(rvalue_pool - RVALUE_OVERHEAD));
13449 rb_hash_aset(gc_constants, ID2SYM(rb_intern("RBASIC_SIZE")), SIZET2NUM(sizeof(struct RBasic)));
13450 rb_hash_aset(gc_constants, ID2SYM(rb_intern("RVALUE_OVERHEAD")), SIZET2NUM(RVALUE_OVERHEAD));
13451 rb_hash_aset(gc_constants, ID2SYM(rb_intern("HEAP_PAGE_BITMAP_SIZE")), SIZET2NUM(HEAP_PAGE_BITMAP_SIZE));
13452 rb_hash_aset(gc_constants, ID2SYM(rb_intern("HEAP_PAGE_SIZE")), SIZET2NUM(HEAP_PAGE_SIZE));
13453 rb_hash_aset(gc_constants, ID2SYM(rb_intern("HEAP_COUNT")), LONG2FIX(HEAP_COUNT));
13454 rb_hash_aset(gc_constants, ID2SYM(rb_intern("RVARGC_MAX_ALLOCATE_SIZE")), SIZET2NUM(rb_gc_impl_max_allocation_size()));
13455 rb_hash_aset(gc_constants, ID2SYM(rb_intern("RVALUE_OLD_AGE")), LONG2FIX(RVALUE_OLD_AGE));
13456 if (RB_BUG_INSTEAD_OF_RB_MEMERROR+0) {
13457 rb_hash_aset(gc_constants, ID2SYM(rb_intern("RB_BUG_INSTEAD_OF_RB_MEMERROR")), Qtrue);
13458 }
13459 OBJ_FREEZE(gc_constants);
13460 /* Internal constants in the garbage collector. */
13461 rb_define_const(rb_mGC, "INTERNAL_CONSTANTS", gc_constants);
13462
13463 if (GC_COMPACTION_SUPPORTED) {
13464 rb_define_singleton_method(rb_mGC, "compact", gc_compact, 0);
13465 rb_define_singleton_method(rb_mGC, "auto_compact", gc_get_auto_compact, 0);
13466 rb_define_singleton_method(rb_mGC, "auto_compact=", gc_set_auto_compact, 1);
13467 rb_define_singleton_method(rb_mGC, "latest_compact_info", gc_compact_stats, 0);
13468 rb_define_singleton_method(rb_mGC, "verify_compaction_references", gc_verify_compaction_references, -1);
13469 }
13470 else {
13474 rb_define_singleton_method(rb_mGC, "latest_compact_info", rb_f_notimplement, 0);
13475 rb_define_singleton_method(rb_mGC, "verify_compaction_references", rb_f_notimplement, -1);
13476 }
13477
13478#if GC_DEBUG_STRESS_TO_CLASS
13479 rb_define_singleton_method(rb_mGC, "add_stress_to_class", rb_gcdebug_add_stress_to_class, -1);
13480 rb_define_singleton_method(rb_mGC, "remove_stress_to_class", rb_gcdebug_remove_stress_to_class, -1);
13481#endif
13482
13483 /* internal methods */
13484 rb_define_singleton_method(rb_mGC, "verify_internal_consistency", gc_verify_internal_consistency_m, 0);
13485
13486#if MALLOC_ALLOCATED_SIZE
13487 rb_define_singleton_method(rb_mGC, "malloc_allocated_size", gc_malloc_allocated_size, 0);
13488 rb_define_singleton_method(rb_mGC, "malloc_allocations", gc_malloc_allocations, 0);
13489#endif
13490
13491 /* Document-class: GC::Profiler
13492 *
13493 * The GC profiler provides access to information on GC runs including time,
13494 * length and object space size.
13495 *
13496 * Example:
13497 *
13498 * GC::Profiler.enable
13499 *
13500 * require 'rdoc/rdoc'
13501 *
13502 * GC::Profiler.report
13503 *
13504 * pp GC::Profiler.raw_data
13505 *
13506 * GC::Profiler.disable
13507 *
13508 * GC::Profiler.raw_data returns one Hash per GC run, including CPU time
13509 * fields such as +:GC_TIME+ and wall-clock fields such as +:GC_WALL_TIME+,
13510 * +:GC_PAUSE_TIME+, +:GC_STOP_TIME+, and +:GC_STW_TIME+. +:GC_WALL_TIME+
13511 * is the wall-clock counterpart to +:GC_TIME+, while +:GC_PAUSE_TIME+
13512 * measures how long user execution was blocked by the GC entry.
13513 *
13514 * See also GC.count, GC.malloc_allocated_size and GC.malloc_allocations
13515 */
13516 VALUE rb_mProfiler = rb_define_module_under(rb_mGC, "Profiler");
13517 rb_define_singleton_method(rb_mProfiler, "enabled?", gc_profile_enable_get, 0);
13518 rb_define_singleton_method(rb_mProfiler, "enable", gc_profile_enable, 0);
13519 rb_define_singleton_method(rb_mProfiler, "raw_data", gc_profile_record_get, -1);
13520 rb_define_singleton_method(rb_mProfiler, "disable", gc_profile_disable, 0);
13521 rb_define_singleton_method(rb_mProfiler, "clear", gc_profile_clear, 0);
13522 rb_define_singleton_method(rb_mProfiler, "configure", gc_profile_configure, -1);
13523 rb_define_singleton_method(rb_mProfiler, "result", gc_profile_result, 0);
13524 rb_define_singleton_method(rb_mProfiler, "report", gc_profile_report, -1);
13525 rb_define_singleton_method(rb_mProfiler, "total_time", gc_profile_total_time, 0);
13526
13527 {
13528 VALUE opts;
13529 /* \GC build options */
13530 rb_define_const(rb_mGC, "OPTS", opts = rb_ary_new());
13531#define OPT(o) if (o) rb_ary_push(opts, rb_interned_str(#o, sizeof(#o) - 1))
13532 OPT(GC_DEBUG);
13533 OPT(USE_RGENGC);
13534 OPT(RGENGC_DEBUG);
13535 OPT(RGENGC_CHECK_MODE);
13536 OPT(RGENGC_PROFILE);
13537 OPT(RGENGC_ESTIMATE_OLDMALLOC);
13538 OPT(GC_PROFILE_MORE_DETAIL);
13539 OPT(GC_ENABLE_LAZY_SWEEP);
13540 OPT(CALC_EXACT_MALLOC_SIZE);
13541 OPT(MALLOC_ALLOCATED_SIZE);
13542 OPT(MALLOC_ALLOCATED_SIZE_CHECK);
13543 OPT(GC_PROFILE_DETAIL_MEMORY);
13544 OPT(GC_COMPACTION_SUPPORTED);
13545#undef OPT
13546 OBJ_FREEZE(opts);
13547 }
13548}
#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:406
#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:297
#define RUBY_ATOMIC_VALUE_EXCHANGE(var, val)
Identical to RUBY_ATOMIC_EXCHANGE, except it expects its arguments are VALUE.
Definition atomic.h:392
#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:3397
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:3173
#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:1471
void rb_warn(const char *fmt,...)
Identical to rb_warning(), except it reports unless $VERBOSE is nil.
Definition error.c:468
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:203
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:3879
VALUE rb_str_buf_new(long capa)
Allocates a "string buffer".
Definition string.c:1769
#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:2176
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:2190
#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:2319
#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
static void RARRAY_ASET(VALUE ary, long i, VALUE v)
Assigns an object in an array.
Definition rarray.h:385
#define RARRAY_AREF(a, i)
Definition rarray.h:402
#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:6157
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.
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